本站源代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

224148 lines
7.5MB

  1. #ifndef USE_LIBSQLITE3
  2. /******************************************************************************
  3. ** This file is an amalgamation of many separate C source files from SQLite
  4. ** version 3.29.0. By combining all the individual C code files into this
  5. ** single large file, the entire code can be compiled as a single translation
  6. ** unit. This allows many compilers to do optimizations that would not be
  7. ** possible if the files were compiled separately. Performance improvements
  8. ** of 5% or more are commonly seen when SQLite is compiled as a single
  9. ** translation unit.
  10. **
  11. ** This file is all you need to compile SQLite. To use SQLite in other
  12. ** programs, you need this file and the "sqlite3.h" header file that defines
  13. ** the programming interface to the SQLite library. (If you do not have
  14. ** the "sqlite3.h" header file at hand, you will find a copy embedded within
  15. ** the text of this file. Search for "Begin file sqlite3.h" to find the start
  16. ** of the embedded sqlite3.h header file.) Additional code files may be needed
  17. ** if you want a wrapper to interface SQLite with your choice of programming
  18. ** language. The code for the "sqlite3" command-line shell is also in a
  19. ** separate file. This file contains only code for the core SQLite library.
  20. */
  21. #define SQLITE_CORE 1
  22. #define SQLITE_AMALGAMATION 1
  23. #ifndef SQLITE_PRIVATE
  24. # define SQLITE_PRIVATE static
  25. #endif
  26. /************** Begin file ctime.c *******************************************/
  27. /*
  28. ** 2010 February 23
  29. **
  30. ** The author disclaims copyright to this source code. In place of
  31. ** a legal notice, here is a blessing:
  32. **
  33. ** May you do good and not evil.
  34. ** May you find forgiveness for yourself and forgive others.
  35. ** May you share freely, never taking more than you give.
  36. **
  37. *************************************************************************
  38. **
  39. ** This file implements routines used to report what compile-time options
  40. ** SQLite was built with.
  41. */
  42. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS /* IMP: R-16824-07538 */
  43. /*
  44. ** Include the configuration header output by 'configure' if we're using the
  45. ** autoconf-based build
  46. */
  47. #if defined(_HAVE_SQLITE_CONFIG_H) && !defined(SQLITECONFIG_H)
  48. #include "config.h"
  49. #define SQLITECONFIG_H 1
  50. #endif
  51. /* These macros are provided to "stringify" the value of the define
  52. ** for those options in which the value is meaningful. */
  53. #define CTIMEOPT_VAL_(opt) #opt
  54. #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
  55. /* Like CTIMEOPT_VAL, but especially for SQLITE_DEFAULT_LOOKASIDE. This
  56. ** option requires a separate macro because legal values contain a single
  57. ** comma. e.g. (-DSQLITE_DEFAULT_LOOKASIDE="100,100") */
  58. #define CTIMEOPT_VAL2_(opt1,opt2) #opt1 "," #opt2
  59. #define CTIMEOPT_VAL2(opt) CTIMEOPT_VAL2_(opt)
  60. /*
  61. ** An array of names of all compile-time options. This array should
  62. ** be sorted A-Z.
  63. **
  64. ** This array looks large, but in a typical installation actually uses
  65. ** only a handful of compile-time options, so most times this array is usually
  66. ** rather short and uses little memory space.
  67. */
  68. static const char * const sqlite3azCompileOpt[] = {
  69. /*
  70. ** BEGIN CODE GENERATED BY tool/mkctime.tcl
  71. */
  72. #if SQLITE_32BIT_ROWID
  73. "32BIT_ROWID",
  74. #endif
  75. #if SQLITE_4_BYTE_ALIGNED_MALLOC
  76. "4_BYTE_ALIGNED_MALLOC",
  77. #endif
  78. #if SQLITE_64BIT_STATS
  79. "64BIT_STATS",
  80. #endif
  81. #if SQLITE_ALLOW_COVERING_INDEX_SCAN
  82. "ALLOW_COVERING_INDEX_SCAN",
  83. #endif
  84. #if SQLITE_ALLOW_URI_AUTHORITY
  85. "ALLOW_URI_AUTHORITY",
  86. #endif
  87. #ifdef SQLITE_BITMASK_TYPE
  88. "BITMASK_TYPE=" CTIMEOPT_VAL(SQLITE_BITMASK_TYPE),
  89. #endif
  90. #if SQLITE_BUG_COMPATIBLE_20160819
  91. "BUG_COMPATIBLE_20160819",
  92. #endif
  93. #if SQLITE_CASE_SENSITIVE_LIKE
  94. "CASE_SENSITIVE_LIKE",
  95. #endif
  96. #if SQLITE_CHECK_PAGES
  97. "CHECK_PAGES",
  98. #endif
  99. #if defined(__clang__) && defined(__clang_major__)
  100. "COMPILER=clang-" CTIMEOPT_VAL(__clang_major__) "."
  101. CTIMEOPT_VAL(__clang_minor__) "."
  102. CTIMEOPT_VAL(__clang_patchlevel__),
  103. #elif defined(_MSC_VER)
  104. "COMPILER=msvc-" CTIMEOPT_VAL(_MSC_VER),
  105. #elif defined(__GNUC__) && defined(__VERSION__)
  106. "COMPILER=gcc-" __VERSION__,
  107. #endif
  108. #if SQLITE_COVERAGE_TEST
  109. "COVERAGE_TEST",
  110. #endif
  111. #if SQLITE_DEBUG
  112. "DEBUG",
  113. #endif
  114. #if SQLITE_DEFAULT_AUTOMATIC_INDEX
  115. "DEFAULT_AUTOMATIC_INDEX",
  116. #endif
  117. #if SQLITE_DEFAULT_AUTOVACUUM
  118. "DEFAULT_AUTOVACUUM",
  119. #endif
  120. #ifdef SQLITE_DEFAULT_CACHE_SIZE
  121. "DEFAULT_CACHE_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_CACHE_SIZE),
  122. #endif
  123. #if SQLITE_DEFAULT_CKPTFULLFSYNC
  124. "DEFAULT_CKPTFULLFSYNC",
  125. #endif
  126. #ifdef SQLITE_DEFAULT_FILE_FORMAT
  127. "DEFAULT_FILE_FORMAT=" CTIMEOPT_VAL(SQLITE_DEFAULT_FILE_FORMAT),
  128. #endif
  129. #ifdef SQLITE_DEFAULT_FILE_PERMISSIONS
  130. "DEFAULT_FILE_PERMISSIONS=" CTIMEOPT_VAL(SQLITE_DEFAULT_FILE_PERMISSIONS),
  131. #endif
  132. #if SQLITE_DEFAULT_FOREIGN_KEYS
  133. "DEFAULT_FOREIGN_KEYS",
  134. #endif
  135. #ifdef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
  136. "DEFAULT_JOURNAL_SIZE_LIMIT=" CTIMEOPT_VAL(SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT),
  137. #endif
  138. #ifdef SQLITE_DEFAULT_LOCKING_MODE
  139. "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
  140. #endif
  141. #ifdef SQLITE_DEFAULT_LOOKASIDE
  142. "DEFAULT_LOOKASIDE=" CTIMEOPT_VAL2(SQLITE_DEFAULT_LOOKASIDE),
  143. #endif
  144. #if SQLITE_DEFAULT_MEMSTATUS
  145. "DEFAULT_MEMSTATUS",
  146. #endif
  147. #ifdef SQLITE_DEFAULT_MMAP_SIZE
  148. "DEFAULT_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_MMAP_SIZE),
  149. #endif
  150. #ifdef SQLITE_DEFAULT_PAGE_SIZE
  151. "DEFAULT_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_PAGE_SIZE),
  152. #endif
  153. #ifdef SQLITE_DEFAULT_PCACHE_INITSZ
  154. "DEFAULT_PCACHE_INITSZ=" CTIMEOPT_VAL(SQLITE_DEFAULT_PCACHE_INITSZ),
  155. #endif
  156. #ifdef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
  157. "DEFAULT_PROXYDIR_PERMISSIONS=" CTIMEOPT_VAL(SQLITE_DEFAULT_PROXYDIR_PERMISSIONS),
  158. #endif
  159. #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
  160. "DEFAULT_RECURSIVE_TRIGGERS",
  161. #endif
  162. #ifdef SQLITE_DEFAULT_ROWEST
  163. "DEFAULT_ROWEST=" CTIMEOPT_VAL(SQLITE_DEFAULT_ROWEST),
  164. #endif
  165. #ifdef SQLITE_DEFAULT_SECTOR_SIZE
  166. "DEFAULT_SECTOR_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_SECTOR_SIZE),
  167. #endif
  168. #ifdef SQLITE_DEFAULT_SYNCHRONOUS
  169. "DEFAULT_SYNCHRONOUS=" CTIMEOPT_VAL(SQLITE_DEFAULT_SYNCHRONOUS),
  170. #endif
  171. #ifdef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
  172. "DEFAULT_WAL_AUTOCHECKPOINT=" CTIMEOPT_VAL(SQLITE_DEFAULT_WAL_AUTOCHECKPOINT),
  173. #endif
  174. #ifdef SQLITE_DEFAULT_WAL_SYNCHRONOUS
  175. "DEFAULT_WAL_SYNCHRONOUS=" CTIMEOPT_VAL(SQLITE_DEFAULT_WAL_SYNCHRONOUS),
  176. #endif
  177. #ifdef SQLITE_DEFAULT_WORKER_THREADS
  178. "DEFAULT_WORKER_THREADS=" CTIMEOPT_VAL(SQLITE_DEFAULT_WORKER_THREADS),
  179. #endif
  180. #if SQLITE_DIRECT_OVERFLOW_READ
  181. "DIRECT_OVERFLOW_READ",
  182. #endif
  183. #if SQLITE_DISABLE_DIRSYNC
  184. "DISABLE_DIRSYNC",
  185. #endif
  186. #if SQLITE_DISABLE_FTS3_UNICODE
  187. "DISABLE_FTS3_UNICODE",
  188. #endif
  189. #if SQLITE_DISABLE_FTS4_DEFERRED
  190. "DISABLE_FTS4_DEFERRED",
  191. #endif
  192. #if SQLITE_DISABLE_INTRINSIC
  193. "DISABLE_INTRINSIC",
  194. #endif
  195. #if SQLITE_DISABLE_LFS
  196. "DISABLE_LFS",
  197. #endif
  198. #if SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
  199. "DISABLE_PAGECACHE_OVERFLOW_STATS",
  200. #endif
  201. #if SQLITE_DISABLE_SKIPAHEAD_DISTINCT
  202. "DISABLE_SKIPAHEAD_DISTINCT",
  203. #endif
  204. #ifdef SQLITE_ENABLE_8_3_NAMES
  205. "ENABLE_8_3_NAMES=" CTIMEOPT_VAL(SQLITE_ENABLE_8_3_NAMES),
  206. #endif
  207. #if SQLITE_ENABLE_API_ARMOR
  208. "ENABLE_API_ARMOR",
  209. #endif
  210. #if SQLITE_ENABLE_ATOMIC_WRITE
  211. "ENABLE_ATOMIC_WRITE",
  212. #endif
  213. #if SQLITE_ENABLE_BATCH_ATOMIC_WRITE
  214. "ENABLE_BATCH_ATOMIC_WRITE",
  215. #endif
  216. #if SQLITE_ENABLE_CEROD
  217. "ENABLE_CEROD=" CTIMEOPT_VAL(SQLITE_ENABLE_CEROD),
  218. #endif
  219. #if SQLITE_ENABLE_COLUMN_METADATA
  220. "ENABLE_COLUMN_METADATA",
  221. #endif
  222. #if SQLITE_ENABLE_COLUMN_USED_MASK
  223. "ENABLE_COLUMN_USED_MASK",
  224. #endif
  225. #if SQLITE_ENABLE_COSTMULT
  226. "ENABLE_COSTMULT",
  227. #endif
  228. #if SQLITE_ENABLE_CURSOR_HINTS
  229. "ENABLE_CURSOR_HINTS",
  230. #endif
  231. #if SQLITE_ENABLE_DBSTAT_VTAB
  232. "ENABLE_DBSTAT_VTAB",
  233. #endif
  234. #if SQLITE_ENABLE_EXPENSIVE_ASSERT
  235. "ENABLE_EXPENSIVE_ASSERT",
  236. #endif
  237. #if SQLITE_ENABLE_FTS1
  238. "ENABLE_FTS1",
  239. #endif
  240. #if SQLITE_ENABLE_FTS2
  241. "ENABLE_FTS2",
  242. #endif
  243. #if SQLITE_ENABLE_FTS3
  244. "ENABLE_FTS3",
  245. #endif
  246. #if SQLITE_ENABLE_FTS3_PARENTHESIS
  247. "ENABLE_FTS3_PARENTHESIS",
  248. #endif
  249. #if SQLITE_ENABLE_FTS3_TOKENIZER
  250. "ENABLE_FTS3_TOKENIZER",
  251. #endif
  252. #if SQLITE_ENABLE_FTS4
  253. "ENABLE_FTS4",
  254. #endif
  255. #if SQLITE_ENABLE_FTS5
  256. "ENABLE_FTS5",
  257. #endif
  258. #if SQLITE_ENABLE_GEOPOLY
  259. "ENABLE_GEOPOLY",
  260. #endif
  261. #if SQLITE_ENABLE_HIDDEN_COLUMNS
  262. "ENABLE_HIDDEN_COLUMNS",
  263. #endif
  264. #if SQLITE_ENABLE_ICU
  265. "ENABLE_ICU",
  266. #endif
  267. #if SQLITE_ENABLE_IOTRACE
  268. "ENABLE_IOTRACE",
  269. #endif
  270. #if SQLITE_ENABLE_JSON1
  271. "ENABLE_JSON1",
  272. #endif
  273. #if SQLITE_ENABLE_LOAD_EXTENSION
  274. "ENABLE_LOAD_EXTENSION",
  275. #endif
  276. #ifdef SQLITE_ENABLE_LOCKING_STYLE
  277. "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
  278. #endif
  279. #if SQLITE_ENABLE_MEMORY_MANAGEMENT
  280. "ENABLE_MEMORY_MANAGEMENT",
  281. #endif
  282. #if SQLITE_ENABLE_MEMSYS3
  283. "ENABLE_MEMSYS3",
  284. #endif
  285. #if SQLITE_ENABLE_MEMSYS5
  286. "ENABLE_MEMSYS5",
  287. #endif
  288. #if SQLITE_ENABLE_MULTIPLEX
  289. "ENABLE_MULTIPLEX",
  290. #endif
  291. #if SQLITE_ENABLE_NORMALIZE
  292. "ENABLE_NORMALIZE",
  293. #endif
  294. #if SQLITE_ENABLE_NULL_TRIM
  295. "ENABLE_NULL_TRIM",
  296. #endif
  297. #if SQLITE_ENABLE_OVERSIZE_CELL_CHECK
  298. "ENABLE_OVERSIZE_CELL_CHECK",
  299. #endif
  300. #if SQLITE_ENABLE_PREUPDATE_HOOK
  301. "ENABLE_PREUPDATE_HOOK",
  302. #endif
  303. #if SQLITE_ENABLE_QPSG
  304. "ENABLE_QPSG",
  305. #endif
  306. #if SQLITE_ENABLE_RBU
  307. "ENABLE_RBU",
  308. #endif
  309. #if SQLITE_ENABLE_RTREE
  310. "ENABLE_RTREE",
  311. #endif
  312. #if SQLITE_ENABLE_SELECTTRACE
  313. "ENABLE_SELECTTRACE",
  314. #endif
  315. #if SQLITE_ENABLE_SESSION
  316. "ENABLE_SESSION",
  317. #endif
  318. #if SQLITE_ENABLE_SNAPSHOT
  319. "ENABLE_SNAPSHOT",
  320. #endif
  321. #if SQLITE_ENABLE_SORTER_REFERENCES
  322. "ENABLE_SORTER_REFERENCES",
  323. #endif
  324. #if SQLITE_ENABLE_SQLLOG
  325. "ENABLE_SQLLOG",
  326. #endif
  327. #if defined(SQLITE_ENABLE_STAT4)
  328. "ENABLE_STAT4",
  329. #elif defined(SQLITE_ENABLE_STAT3)
  330. "ENABLE_STAT3",
  331. #endif
  332. #if SQLITE_ENABLE_STMTVTAB
  333. "ENABLE_STMTVTAB",
  334. #endif
  335. #if SQLITE_ENABLE_STMT_SCANSTATUS
  336. "ENABLE_STMT_SCANSTATUS",
  337. #endif
  338. #if SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
  339. "ENABLE_UNKNOWN_SQL_FUNCTION",
  340. #endif
  341. #if SQLITE_ENABLE_UNLOCK_NOTIFY
  342. "ENABLE_UNLOCK_NOTIFY",
  343. #endif
  344. #if SQLITE_ENABLE_UPDATE_DELETE_LIMIT
  345. "ENABLE_UPDATE_DELETE_LIMIT",
  346. #endif
  347. #if SQLITE_ENABLE_URI_00_ERROR
  348. "ENABLE_URI_00_ERROR",
  349. #endif
  350. #if SQLITE_ENABLE_VFSTRACE
  351. "ENABLE_VFSTRACE",
  352. #endif
  353. #if SQLITE_ENABLE_WHERETRACE
  354. "ENABLE_WHERETRACE",
  355. #endif
  356. #if SQLITE_ENABLE_ZIPVFS
  357. "ENABLE_ZIPVFS",
  358. #endif
  359. #if SQLITE_EXPLAIN_ESTIMATED_ROWS
  360. "EXPLAIN_ESTIMATED_ROWS",
  361. #endif
  362. #if SQLITE_EXTRA_IFNULLROW
  363. "EXTRA_IFNULLROW",
  364. #endif
  365. #ifdef SQLITE_EXTRA_INIT
  366. "EXTRA_INIT=" CTIMEOPT_VAL(SQLITE_EXTRA_INIT),
  367. #endif
  368. #ifdef SQLITE_EXTRA_SHUTDOWN
  369. "EXTRA_SHUTDOWN=" CTIMEOPT_VAL(SQLITE_EXTRA_SHUTDOWN),
  370. #endif
  371. #ifdef SQLITE_FTS3_MAX_EXPR_DEPTH
  372. "FTS3_MAX_EXPR_DEPTH=" CTIMEOPT_VAL(SQLITE_FTS3_MAX_EXPR_DEPTH),
  373. #endif
  374. #if SQLITE_FTS5_ENABLE_TEST_MI
  375. "FTS5_ENABLE_TEST_MI",
  376. #endif
  377. #if SQLITE_FTS5_NO_WITHOUT_ROWID
  378. "FTS5_NO_WITHOUT_ROWID",
  379. #endif
  380. #if SQLITE_HAS_CODEC
  381. "HAS_CODEC",
  382. #endif
  383. #if HAVE_ISNAN || SQLITE_HAVE_ISNAN
  384. "HAVE_ISNAN",
  385. #endif
  386. #if SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  387. "HOMEGROWN_RECURSIVE_MUTEX",
  388. #endif
  389. #if SQLITE_IGNORE_AFP_LOCK_ERRORS
  390. "IGNORE_AFP_LOCK_ERRORS",
  391. #endif
  392. #if SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  393. "IGNORE_FLOCK_LOCK_ERRORS",
  394. #endif
  395. #if SQLITE_INLINE_MEMCPY
  396. "INLINE_MEMCPY",
  397. #endif
  398. #if SQLITE_INT64_TYPE
  399. "INT64_TYPE",
  400. #endif
  401. #ifdef SQLITE_INTEGRITY_CHECK_ERROR_MAX
  402. "INTEGRITY_CHECK_ERROR_MAX=" CTIMEOPT_VAL(SQLITE_INTEGRITY_CHECK_ERROR_MAX),
  403. #endif
  404. #if SQLITE_LIKE_DOESNT_MATCH_BLOBS
  405. "LIKE_DOESNT_MATCH_BLOBS",
  406. #endif
  407. #if SQLITE_LOCK_TRACE
  408. "LOCK_TRACE",
  409. #endif
  410. #if SQLITE_LOG_CACHE_SPILL
  411. "LOG_CACHE_SPILL",
  412. #endif
  413. #ifdef SQLITE_MALLOC_SOFT_LIMIT
  414. "MALLOC_SOFT_LIMIT=" CTIMEOPT_VAL(SQLITE_MALLOC_SOFT_LIMIT),
  415. #endif
  416. #ifdef SQLITE_MAX_ATTACHED
  417. "MAX_ATTACHED=" CTIMEOPT_VAL(SQLITE_MAX_ATTACHED),
  418. #endif
  419. #ifdef SQLITE_MAX_COLUMN
  420. "MAX_COLUMN=" CTIMEOPT_VAL(SQLITE_MAX_COLUMN),
  421. #endif
  422. #ifdef SQLITE_MAX_COMPOUND_SELECT
  423. "MAX_COMPOUND_SELECT=" CTIMEOPT_VAL(SQLITE_MAX_COMPOUND_SELECT),
  424. #endif
  425. #ifdef SQLITE_MAX_DEFAULT_PAGE_SIZE
  426. "MAX_DEFAULT_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_DEFAULT_PAGE_SIZE),
  427. #endif
  428. #ifdef SQLITE_MAX_EXPR_DEPTH
  429. "MAX_EXPR_DEPTH=" CTIMEOPT_VAL(SQLITE_MAX_EXPR_DEPTH),
  430. #endif
  431. #ifdef SQLITE_MAX_FUNCTION_ARG
  432. "MAX_FUNCTION_ARG=" CTIMEOPT_VAL(SQLITE_MAX_FUNCTION_ARG),
  433. #endif
  434. #ifdef SQLITE_MAX_LENGTH
  435. "MAX_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_LENGTH),
  436. #endif
  437. #ifdef SQLITE_MAX_LIKE_PATTERN_LENGTH
  438. "MAX_LIKE_PATTERN_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_LIKE_PATTERN_LENGTH),
  439. #endif
  440. #ifdef SQLITE_MAX_MEMORY
  441. "MAX_MEMORY=" CTIMEOPT_VAL(SQLITE_MAX_MEMORY),
  442. #endif
  443. #ifdef SQLITE_MAX_MMAP_SIZE
  444. "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE),
  445. #endif
  446. #ifdef SQLITE_MAX_MMAP_SIZE_
  447. "MAX_MMAP_SIZE_=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE_),
  448. #endif
  449. #ifdef SQLITE_MAX_PAGE_COUNT
  450. "MAX_PAGE_COUNT=" CTIMEOPT_VAL(SQLITE_MAX_PAGE_COUNT),
  451. #endif
  452. #ifdef SQLITE_MAX_PAGE_SIZE
  453. "MAX_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_PAGE_SIZE),
  454. #endif
  455. #ifdef SQLITE_MAX_SCHEMA_RETRY
  456. "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
  457. #endif
  458. #ifdef SQLITE_MAX_SQL_LENGTH
  459. "MAX_SQL_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_SQL_LENGTH),
  460. #endif
  461. #ifdef SQLITE_MAX_TRIGGER_DEPTH
  462. "MAX_TRIGGER_DEPTH=" CTIMEOPT_VAL(SQLITE_MAX_TRIGGER_DEPTH),
  463. #endif
  464. #ifdef SQLITE_MAX_VARIABLE_NUMBER
  465. "MAX_VARIABLE_NUMBER=" CTIMEOPT_VAL(SQLITE_MAX_VARIABLE_NUMBER),
  466. #endif
  467. #ifdef SQLITE_MAX_VDBE_OP
  468. "MAX_VDBE_OP=" CTIMEOPT_VAL(SQLITE_MAX_VDBE_OP),
  469. #endif
  470. #ifdef SQLITE_MAX_WORKER_THREADS
  471. "MAX_WORKER_THREADS=" CTIMEOPT_VAL(SQLITE_MAX_WORKER_THREADS),
  472. #endif
  473. #if SQLITE_MEMDEBUG
  474. "MEMDEBUG",
  475. #endif
  476. #if SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  477. "MIXED_ENDIAN_64BIT_FLOAT",
  478. #endif
  479. #if SQLITE_MMAP_READWRITE
  480. "MMAP_READWRITE",
  481. #endif
  482. #if SQLITE_MUTEX_NOOP
  483. "MUTEX_NOOP",
  484. #endif
  485. #if SQLITE_MUTEX_NREF
  486. "MUTEX_NREF",
  487. #endif
  488. #if SQLITE_MUTEX_OMIT
  489. "MUTEX_OMIT",
  490. #endif
  491. #if SQLITE_MUTEX_PTHREADS
  492. "MUTEX_PTHREADS",
  493. #endif
  494. #if SQLITE_MUTEX_W32
  495. "MUTEX_W32",
  496. #endif
  497. #if SQLITE_NEED_ERR_NAME
  498. "NEED_ERR_NAME",
  499. #endif
  500. #if SQLITE_NOINLINE
  501. "NOINLINE",
  502. #endif
  503. #if SQLITE_NO_SYNC
  504. "NO_SYNC",
  505. #endif
  506. #if SQLITE_OMIT_ALTERTABLE
  507. "OMIT_ALTERTABLE",
  508. #endif
  509. #if SQLITE_OMIT_ANALYZE
  510. "OMIT_ANALYZE",
  511. #endif
  512. #if SQLITE_OMIT_ATTACH
  513. "OMIT_ATTACH",
  514. #endif
  515. #if SQLITE_OMIT_AUTHORIZATION
  516. "OMIT_AUTHORIZATION",
  517. #endif
  518. #if SQLITE_OMIT_AUTOINCREMENT
  519. "OMIT_AUTOINCREMENT",
  520. #endif
  521. #if SQLITE_OMIT_AUTOINIT
  522. "OMIT_AUTOINIT",
  523. #endif
  524. #if SQLITE_OMIT_AUTOMATIC_INDEX
  525. "OMIT_AUTOMATIC_INDEX",
  526. #endif
  527. #if SQLITE_OMIT_AUTORESET
  528. "OMIT_AUTORESET",
  529. #endif
  530. #if SQLITE_OMIT_AUTOVACUUM
  531. "OMIT_AUTOVACUUM",
  532. #endif
  533. #if SQLITE_OMIT_BETWEEN_OPTIMIZATION
  534. "OMIT_BETWEEN_OPTIMIZATION",
  535. #endif
  536. #if SQLITE_OMIT_BLOB_LITERAL
  537. "OMIT_BLOB_LITERAL",
  538. #endif
  539. #if SQLITE_OMIT_BTREECOUNT
  540. "OMIT_BTREECOUNT",
  541. #endif
  542. #if SQLITE_OMIT_CAST
  543. "OMIT_CAST",
  544. #endif
  545. #if SQLITE_OMIT_CHECK
  546. "OMIT_CHECK",
  547. #endif
  548. #if SQLITE_OMIT_COMPLETE
  549. "OMIT_COMPLETE",
  550. #endif
  551. #if SQLITE_OMIT_COMPOUND_SELECT
  552. "OMIT_COMPOUND_SELECT",
  553. #endif
  554. #if SQLITE_OMIT_CONFLICT_CLAUSE
  555. "OMIT_CONFLICT_CLAUSE",
  556. #endif
  557. #if SQLITE_OMIT_CTE
  558. "OMIT_CTE",
  559. #endif
  560. #if SQLITE_OMIT_DATETIME_FUNCS
  561. "OMIT_DATETIME_FUNCS",
  562. #endif
  563. #if SQLITE_OMIT_DECLTYPE
  564. "OMIT_DECLTYPE",
  565. #endif
  566. #if SQLITE_OMIT_DEPRECATED
  567. "OMIT_DEPRECATED",
  568. #endif
  569. #if SQLITE_OMIT_DISKIO
  570. "OMIT_DISKIO",
  571. #endif
  572. #if SQLITE_OMIT_EXPLAIN
  573. "OMIT_EXPLAIN",
  574. #endif
  575. #if SQLITE_OMIT_FLAG_PRAGMAS
  576. "OMIT_FLAG_PRAGMAS",
  577. #endif
  578. #if SQLITE_OMIT_FLOATING_POINT
  579. "OMIT_FLOATING_POINT",
  580. #endif
  581. #if SQLITE_OMIT_FOREIGN_KEY
  582. "OMIT_FOREIGN_KEY",
  583. #endif
  584. #if SQLITE_OMIT_GET_TABLE
  585. "OMIT_GET_TABLE",
  586. #endif
  587. #if SQLITE_OMIT_HEX_INTEGER
  588. "OMIT_HEX_INTEGER",
  589. #endif
  590. #if SQLITE_OMIT_INCRBLOB
  591. "OMIT_INCRBLOB",
  592. #endif
  593. #if SQLITE_OMIT_INTEGRITY_CHECK
  594. "OMIT_INTEGRITY_CHECK",
  595. #endif
  596. #if SQLITE_OMIT_LIKE_OPTIMIZATION
  597. "OMIT_LIKE_OPTIMIZATION",
  598. #endif
  599. #if SQLITE_OMIT_LOAD_EXTENSION
  600. "OMIT_LOAD_EXTENSION",
  601. #endif
  602. #if SQLITE_OMIT_LOCALTIME
  603. "OMIT_LOCALTIME",
  604. #endif
  605. #if SQLITE_OMIT_LOOKASIDE
  606. "OMIT_LOOKASIDE",
  607. #endif
  608. #if SQLITE_OMIT_MEMORYDB
  609. "OMIT_MEMORYDB",
  610. #endif
  611. #if SQLITE_OMIT_OR_OPTIMIZATION
  612. "OMIT_OR_OPTIMIZATION",
  613. #endif
  614. #if SQLITE_OMIT_PAGER_PRAGMAS
  615. "OMIT_PAGER_PRAGMAS",
  616. #endif
  617. #if SQLITE_OMIT_PARSER_TRACE
  618. "OMIT_PARSER_TRACE",
  619. #endif
  620. #if SQLITE_OMIT_POPEN
  621. "OMIT_POPEN",
  622. #endif
  623. #if SQLITE_OMIT_PRAGMA
  624. "OMIT_PRAGMA",
  625. #endif
  626. #if SQLITE_OMIT_PROGRESS_CALLBACK
  627. "OMIT_PROGRESS_CALLBACK",
  628. #endif
  629. #if SQLITE_OMIT_QUICKBALANCE
  630. "OMIT_QUICKBALANCE",
  631. #endif
  632. #if SQLITE_OMIT_REINDEX
  633. "OMIT_REINDEX",
  634. #endif
  635. #if SQLITE_OMIT_SCHEMA_PRAGMAS
  636. "OMIT_SCHEMA_PRAGMAS",
  637. #endif
  638. #if SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
  639. "OMIT_SCHEMA_VERSION_PRAGMAS",
  640. #endif
  641. #if SQLITE_OMIT_SHARED_CACHE
  642. "OMIT_SHARED_CACHE",
  643. #endif
  644. #if SQLITE_OMIT_SHUTDOWN_DIRECTORIES
  645. "OMIT_SHUTDOWN_DIRECTORIES",
  646. #endif
  647. #if SQLITE_OMIT_SUBQUERY
  648. "OMIT_SUBQUERY",
  649. #endif
  650. #if SQLITE_OMIT_TCL_VARIABLE
  651. "OMIT_TCL_VARIABLE",
  652. #endif
  653. #if SQLITE_OMIT_TEMPDB
  654. "OMIT_TEMPDB",
  655. #endif
  656. #if SQLITE_OMIT_TEST_CONTROL
  657. "OMIT_TEST_CONTROL",
  658. #endif
  659. #if SQLITE_OMIT_TRACE
  660. "OMIT_TRACE",
  661. #endif
  662. #if SQLITE_OMIT_TRIGGER
  663. "OMIT_TRIGGER",
  664. #endif
  665. #if SQLITE_OMIT_TRUNCATE_OPTIMIZATION
  666. "OMIT_TRUNCATE_OPTIMIZATION",
  667. #endif
  668. #if SQLITE_OMIT_UTF16
  669. "OMIT_UTF16",
  670. #endif
  671. #if SQLITE_OMIT_VACUUM
  672. "OMIT_VACUUM",
  673. #endif
  674. #if SQLITE_OMIT_VIEW
  675. "OMIT_VIEW",
  676. #endif
  677. #if SQLITE_OMIT_VIRTUALTABLE
  678. "OMIT_VIRTUALTABLE",
  679. #endif
  680. #if SQLITE_OMIT_WAL
  681. "OMIT_WAL",
  682. #endif
  683. #if SQLITE_OMIT_WSD
  684. "OMIT_WSD",
  685. #endif
  686. #if SQLITE_OMIT_XFER_OPT
  687. "OMIT_XFER_OPT",
  688. #endif
  689. #if SQLITE_PCACHE_SEPARATE_HEADER
  690. "PCACHE_SEPARATE_HEADER",
  691. #endif
  692. #if SQLITE_PERFORMANCE_TRACE
  693. "PERFORMANCE_TRACE",
  694. #endif
  695. #if SQLITE_POWERSAFE_OVERWRITE
  696. "POWERSAFE_OVERWRITE",
  697. #endif
  698. #if SQLITE_PREFER_PROXY_LOCKING
  699. "PREFER_PROXY_LOCKING",
  700. #endif
  701. #if SQLITE_PROXY_DEBUG
  702. "PROXY_DEBUG",
  703. #endif
  704. #if SQLITE_REVERSE_UNORDERED_SELECTS
  705. "REVERSE_UNORDERED_SELECTS",
  706. #endif
  707. #if SQLITE_RTREE_INT_ONLY
  708. "RTREE_INT_ONLY",
  709. #endif
  710. #if SQLITE_SECURE_DELETE
  711. "SECURE_DELETE",
  712. #endif
  713. #if SQLITE_SMALL_STACK
  714. "SMALL_STACK",
  715. #endif
  716. #ifdef SQLITE_SORTER_PMASZ
  717. "SORTER_PMASZ=" CTIMEOPT_VAL(SQLITE_SORTER_PMASZ),
  718. #endif
  719. #if SQLITE_SOUNDEX
  720. "SOUNDEX",
  721. #endif
  722. #ifdef SQLITE_STAT4_SAMPLES
  723. "STAT4_SAMPLES=" CTIMEOPT_VAL(SQLITE_STAT4_SAMPLES),
  724. #endif
  725. #ifdef SQLITE_STMTJRNL_SPILL
  726. "STMTJRNL_SPILL=" CTIMEOPT_VAL(SQLITE_STMTJRNL_SPILL),
  727. #endif
  728. #if SQLITE_SUBSTR_COMPATIBILITY
  729. "SUBSTR_COMPATIBILITY",
  730. #endif
  731. #if SQLITE_SYSTEM_MALLOC
  732. "SYSTEM_MALLOC",
  733. #endif
  734. #if SQLITE_TCL
  735. "TCL",
  736. #endif
  737. #ifdef SQLITE_TEMP_STORE
  738. "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
  739. #endif
  740. #if SQLITE_TEST
  741. "TEST",
  742. #endif
  743. #if defined(SQLITE_THREADSAFE)
  744. "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
  745. #elif defined(THREADSAFE)
  746. "THREADSAFE=" CTIMEOPT_VAL(THREADSAFE),
  747. #else
  748. "THREADSAFE=1",
  749. #endif
  750. #if SQLITE_UNLINK_AFTER_CLOSE
  751. "UNLINK_AFTER_CLOSE",
  752. #endif
  753. #if SQLITE_UNTESTABLE
  754. "UNTESTABLE",
  755. #endif
  756. #if SQLITE_USER_AUTHENTICATION
  757. "USER_AUTHENTICATION",
  758. #endif
  759. #if SQLITE_USE_ALLOCA
  760. "USE_ALLOCA",
  761. #endif
  762. #if SQLITE_USE_FCNTL_TRACE
  763. "USE_FCNTL_TRACE",
  764. #endif
  765. #if SQLITE_USE_URI
  766. "USE_URI",
  767. #endif
  768. #if SQLITE_VDBE_COVERAGE
  769. "VDBE_COVERAGE",
  770. #endif
  771. #if SQLITE_WIN32_MALLOC
  772. "WIN32_MALLOC",
  773. #endif
  774. #if SQLITE_ZERO_MALLOC
  775. "ZERO_MALLOC",
  776. #endif
  777. /*
  778. ** END CODE GENERATED BY tool/mkctime.tcl
  779. */
  780. };
  781. SQLITE_PRIVATE const char **sqlite3CompileOptions(int *pnOpt){
  782. *pnOpt = sizeof(sqlite3azCompileOpt) / sizeof(sqlite3azCompileOpt[0]);
  783. return (const char**)sqlite3azCompileOpt;
  784. }
  785. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  786. /************** End of ctime.c ***********************************************/
  787. /************** Begin file sqliteInt.h ***************************************/
  788. /*
  789. ** 2001 September 15
  790. **
  791. ** The author disclaims copyright to this source code. In place of
  792. ** a legal notice, here is a blessing:
  793. **
  794. ** May you do good and not evil.
  795. ** May you find forgiveness for yourself and forgive others.
  796. ** May you share freely, never taking more than you give.
  797. **
  798. *************************************************************************
  799. ** Internal interface definitions for SQLite.
  800. **
  801. */
  802. #ifndef SQLITEINT_H
  803. #define SQLITEINT_H
  804. /* Special Comments:
  805. **
  806. ** Some comments have special meaning to the tools that measure test
  807. ** coverage:
  808. **
  809. ** NO_TEST - The branches on this line are not
  810. ** measured by branch coverage. This is
  811. ** used on lines of code that actually
  812. ** implement parts of coverage testing.
  813. **
  814. ** OPTIMIZATION-IF-TRUE - This branch is allowed to alway be false
  815. ** and the correct answer is still obtained,
  816. ** though perhaps more slowly.
  817. **
  818. ** OPTIMIZATION-IF-FALSE - This branch is allowed to alway be true
  819. ** and the correct answer is still obtained,
  820. ** though perhaps more slowly.
  821. **
  822. ** PREVENTS-HARMLESS-OVERREAD - This branch prevents a buffer overread
  823. ** that would be harmless and undetectable
  824. ** if it did occur.
  825. **
  826. ** In all cases, the special comment must be enclosed in the usual
  827. ** slash-asterisk...asterisk-slash comment marks, with no spaces between the
  828. ** asterisks and the comment text.
  829. */
  830. /*
  831. ** Make sure the Tcl calling convention macro is defined. This macro is
  832. ** only used by test code and Tcl integration code.
  833. */
  834. #ifndef SQLITE_TCLAPI
  835. # define SQLITE_TCLAPI
  836. #endif
  837. /*
  838. ** Include the header file used to customize the compiler options for MSVC.
  839. ** This should be done first so that it can successfully prevent spurious
  840. ** compiler warnings due to subsequent content in this file and other files
  841. ** that are included by this file.
  842. */
  843. /************** Include msvc.h in the middle of sqliteInt.h ******************/
  844. /************** Begin file msvc.h ********************************************/
  845. /*
  846. ** 2015 January 12
  847. **
  848. ** The author disclaims copyright to this source code. In place of
  849. ** a legal notice, here is a blessing:
  850. **
  851. ** May you do good and not evil.
  852. ** May you find forgiveness for yourself and forgive others.
  853. ** May you share freely, never taking more than you give.
  854. **
  855. ******************************************************************************
  856. **
  857. ** This file contains code that is specific to MSVC.
  858. */
  859. #ifndef SQLITE_MSVC_H
  860. #define SQLITE_MSVC_H
  861. #if defined(_MSC_VER)
  862. #pragma warning(disable : 4054)
  863. #pragma warning(disable : 4055)
  864. #pragma warning(disable : 4100)
  865. #pragma warning(disable : 4127)
  866. #pragma warning(disable : 4130)
  867. #pragma warning(disable : 4152)
  868. #pragma warning(disable : 4189)
  869. #pragma warning(disable : 4206)
  870. #pragma warning(disable : 4210)
  871. #pragma warning(disable : 4232)
  872. #pragma warning(disable : 4244)
  873. #pragma warning(disable : 4305)
  874. #pragma warning(disable : 4306)
  875. #pragma warning(disable : 4702)
  876. #pragma warning(disable : 4706)
  877. #endif /* defined(_MSC_VER) */
  878. #if defined(_MSC_VER) && !defined(_WIN64)
  879. #undef SQLITE_4_BYTE_ALIGNED_MALLOC
  880. #define SQLITE_4_BYTE_ALIGNED_MALLOC
  881. #endif /* defined(_MSC_VER) && !defined(_WIN64) */
  882. #endif /* SQLITE_MSVC_H */
  883. /************** End of msvc.h ************************************************/
  884. /************** Continuing where we left off in sqliteInt.h ******************/
  885. /*
  886. ** Special setup for VxWorks
  887. */
  888. /************** Include vxworks.h in the middle of sqliteInt.h ***************/
  889. /************** Begin file vxworks.h *****************************************/
  890. /*
  891. ** 2015-03-02
  892. **
  893. ** The author disclaims copyright to this source code. In place of
  894. ** a legal notice, here is a blessing:
  895. **
  896. ** May you do good and not evil.
  897. ** May you find forgiveness for yourself and forgive others.
  898. ** May you share freely, never taking more than you give.
  899. **
  900. ******************************************************************************
  901. **
  902. ** This file contains code that is specific to Wind River's VxWorks
  903. */
  904. #if defined(__RTP__) || defined(_WRS_KERNEL)
  905. /* This is VxWorks. Set up things specially for that OS
  906. */
  907. #include <vxWorks.h>
  908. #include <pthread.h> /* amalgamator: dontcache */
  909. #define OS_VXWORKS 1
  910. #define SQLITE_OS_OTHER 0
  911. #define SQLITE_HOMEGROWN_RECURSIVE_MUTEX 1
  912. #define SQLITE_OMIT_LOAD_EXTENSION 1
  913. #define SQLITE_ENABLE_LOCKING_STYLE 0
  914. #define HAVE_UTIME 1
  915. #else
  916. /* This is not VxWorks. */
  917. #define OS_VXWORKS 0
  918. #define HAVE_FCHOWN 1
  919. #define HAVE_READLINK 1
  920. #define HAVE_LSTAT 1
  921. #endif /* defined(_WRS_KERNEL) */
  922. /************** End of vxworks.h *********************************************/
  923. /************** Continuing where we left off in sqliteInt.h ******************/
  924. /*
  925. ** These #defines should enable >2GB file support on POSIX if the
  926. ** underlying operating system supports it. If the OS lacks
  927. ** large file support, or if the OS is windows, these should be no-ops.
  928. **
  929. ** Ticket #2739: The _LARGEFILE_SOURCE macro must appear before any
  930. ** system #includes. Hence, this block of code must be the very first
  931. ** code in all source files.
  932. **
  933. ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
  934. ** on the compiler command line. This is necessary if you are compiling
  935. ** on a recent machine (ex: Red Hat 7.2) but you want your code to work
  936. ** on an older machine (ex: Red Hat 6.0). If you compile on Red Hat 7.2
  937. ** without this option, LFS is enable. But LFS does not exist in the kernel
  938. ** in Red Hat 6.0, so the code won't work. Hence, for maximum binary
  939. ** portability you should omit LFS.
  940. **
  941. ** The previous paragraph was written in 2005. (This paragraph is written
  942. ** on 2008-11-28.) These days, all Linux kernels support large files, so
  943. ** you should probably leave LFS enabled. But some embedded platforms might
  944. ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
  945. **
  946. ** Similar is true for Mac OS X. LFS is only supported on Mac OS X 9 and later.
  947. */
  948. #ifndef SQLITE_DISABLE_LFS
  949. # define _LARGE_FILE 1
  950. # ifndef _FILE_OFFSET_BITS
  951. # define _FILE_OFFSET_BITS 64
  952. # endif
  953. # define _LARGEFILE_SOURCE 1
  954. #endif
  955. /* The GCC_VERSION and MSVC_VERSION macros are used to
  956. ** conditionally include optimizations for each of these compilers. A
  957. ** value of 0 means that compiler is not being used. The
  958. ** SQLITE_DISABLE_INTRINSIC macro means do not use any compiler-specific
  959. ** optimizations, and hence set all compiler macros to 0
  960. **
  961. ** There was once also a CLANG_VERSION macro. However, we learn that the
  962. ** version numbers in clang are for "marketing" only and are inconsistent
  963. ** and unreliable. Fortunately, all versions of clang also recognize the
  964. ** gcc version numbers and have reasonable settings for gcc version numbers,
  965. ** so the GCC_VERSION macro will be set to a correct non-zero value even
  966. ** when compiling with clang.
  967. */
  968. #if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC)
  969. # define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)
  970. #else
  971. # define GCC_VERSION 0
  972. #endif
  973. #if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC)
  974. # define MSVC_VERSION _MSC_VER
  975. #else
  976. # define MSVC_VERSION 0
  977. #endif
  978. /* Needed for various definitions... */
  979. #if defined(__GNUC__) && !defined(_GNU_SOURCE)
  980. # define _GNU_SOURCE
  981. #endif
  982. #if defined(__OpenBSD__) && !defined(_BSD_SOURCE)
  983. # define _BSD_SOURCE
  984. #endif
  985. /*
  986. ** For MinGW, check to see if we can include the header file containing its
  987. ** version information, among other things. Normally, this internal MinGW
  988. ** header file would [only] be included automatically by other MinGW header
  989. ** files; however, the contained version information is now required by this
  990. ** header file to work around binary compatibility issues (see below) and
  991. ** this is the only known way to reliably obtain it. This entire #if block
  992. ** would be completely unnecessary if there was any other way of detecting
  993. ** MinGW via their preprocessor (e.g. if they customized their GCC to define
  994. ** some MinGW-specific macros). When compiling for MinGW, either the
  995. ** _HAVE_MINGW_H or _HAVE__MINGW_H (note the extra underscore) macro must be
  996. ** defined; otherwise, detection of conditions specific to MinGW will be
  997. ** disabled.
  998. */
  999. #if defined(_HAVE_MINGW_H)
  1000. # include "mingw.h"
  1001. #elif defined(_HAVE__MINGW_H)
  1002. # include "_mingw.h"
  1003. #endif
  1004. /*
  1005. ** For MinGW version 4.x (and higher), check to see if the _USE_32BIT_TIME_T
  1006. ** define is required to maintain binary compatibility with the MSVC runtime
  1007. ** library in use (e.g. for Windows XP).
  1008. */
  1009. #if !defined(_USE_32BIT_TIME_T) && !defined(_USE_64BIT_TIME_T) && \
  1010. defined(_WIN32) && !defined(_WIN64) && \
  1011. defined(__MINGW_MAJOR_VERSION) && __MINGW_MAJOR_VERSION >= 4 && \
  1012. defined(__MSVCRT__)
  1013. # define _USE_32BIT_TIME_T
  1014. #endif
  1015. /* The public SQLite interface. The _FILE_OFFSET_BITS macro must appear
  1016. ** first in QNX. Also, the _USE_32BIT_TIME_T macro must appear first for
  1017. ** MinGW.
  1018. */
  1019. /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
  1020. /************** Begin file sqlite3.h *****************************************/
  1021. /*
  1022. ** 2001-09-15
  1023. **
  1024. ** The author disclaims copyright to this source code. In place of
  1025. ** a legal notice, here is a blessing:
  1026. **
  1027. ** May you do good and not evil.
  1028. ** May you find forgiveness for yourself and forgive others.
  1029. ** May you share freely, never taking more than you give.
  1030. **
  1031. *************************************************************************
  1032. ** This header file defines the interface that the SQLite library
  1033. ** presents to client programs. If a C-function, structure, datatype,
  1034. ** or constant definition does not appear in this file, then it is
  1035. ** not a published API of SQLite, is subject to change without
  1036. ** notice, and should not be referenced by programs that use SQLite.
  1037. **
  1038. ** Some of the definitions that are in this file are marked as
  1039. ** "experimental". Experimental interfaces are normally new
  1040. ** features recently added to SQLite. We do not anticipate changes
  1041. ** to experimental interfaces but reserve the right to make minor changes
  1042. ** if experience from use "in the wild" suggest such changes are prudent.
  1043. **
  1044. ** The official C-language API documentation for SQLite is derived
  1045. ** from comments in this file. This file is the authoritative source
  1046. ** on how SQLite interfaces are supposed to operate.
  1047. **
  1048. ** The name of this file under configuration management is "sqlite.h.in".
  1049. ** The makefile makes some minor changes to this file (such as inserting
  1050. ** the version number) and changes its name to "sqlite3.h" as
  1051. ** part of the build process.
  1052. */
  1053. #ifndef SQLITE3_H
  1054. #define SQLITE3_H
  1055. #include <stdarg.h> /* Needed for the definition of va_list */
  1056. /*
  1057. ** Make sure we can call this stuff from C++.
  1058. */
  1059. #if 0
  1060. extern "C" {
  1061. #endif
  1062. /*
  1063. ** Provide the ability to override linkage features of the interface.
  1064. */
  1065. #ifndef SQLITE_EXTERN
  1066. # define SQLITE_EXTERN extern
  1067. #endif
  1068. #ifndef SQLITE_API
  1069. # define SQLITE_API
  1070. #endif
  1071. #ifndef SQLITE_CDECL
  1072. # define SQLITE_CDECL
  1073. #endif
  1074. #ifndef SQLITE_APICALL
  1075. # define SQLITE_APICALL
  1076. #endif
  1077. #ifndef SQLITE_STDCALL
  1078. # define SQLITE_STDCALL SQLITE_APICALL
  1079. #endif
  1080. #ifndef SQLITE_CALLBACK
  1081. # define SQLITE_CALLBACK
  1082. #endif
  1083. #ifndef SQLITE_SYSAPI
  1084. # define SQLITE_SYSAPI
  1085. #endif
  1086. /*
  1087. ** These no-op macros are used in front of interfaces to mark those
  1088. ** interfaces as either deprecated or experimental. New applications
  1089. ** should not use deprecated interfaces - they are supported for backwards
  1090. ** compatibility only. Application writers should be aware that
  1091. ** experimental interfaces are subject to change in point releases.
  1092. **
  1093. ** These macros used to resolve to various kinds of compiler magic that
  1094. ** would generate warning messages when they were used. But that
  1095. ** compiler magic ended up generating such a flurry of bug reports
  1096. ** that we have taken it all out and gone back to using simple
  1097. ** noop macros.
  1098. */
  1099. #define SQLITE_DEPRECATED
  1100. #define SQLITE_EXPERIMENTAL
  1101. /*
  1102. ** Ensure these symbols were not defined by some previous header file.
  1103. */
  1104. #ifdef SQLITE_VERSION
  1105. # undef SQLITE_VERSION
  1106. #endif
  1107. #ifdef SQLITE_VERSION_NUMBER
  1108. # undef SQLITE_VERSION_NUMBER
  1109. #endif
  1110. /*
  1111. ** CAPI3REF: Compile-Time Library Version Numbers
  1112. **
  1113. ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
  1114. ** evaluates to a string literal that is the SQLite version in the
  1115. ** format "X.Y.Z" where X is the major version number (always 3 for
  1116. ** SQLite3) and Y is the minor version number and Z is the release number.)^
  1117. ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
  1118. ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
  1119. ** numbers used in [SQLITE_VERSION].)^
  1120. ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
  1121. ** be larger than the release from which it is derived. Either Y will
  1122. ** be held constant and Z will be incremented or else Y will be incremented
  1123. ** and Z will be reset to zero.
  1124. **
  1125. ** Since [version 3.6.18] ([dateof:3.6.18]),
  1126. ** SQLite source code has been stored in the
  1127. ** <a href="http://www.fossil-scm.org/">Fossil configuration management
  1128. ** system</a>. ^The SQLITE_SOURCE_ID macro evaluates to
  1129. ** a string which identifies a particular check-in of SQLite
  1130. ** within its configuration management system. ^The SQLITE_SOURCE_ID
  1131. ** string contains the date and time of the check-in (UTC) and a SHA1
  1132. ** or SHA3-256 hash of the entire source tree. If the source code has
  1133. ** been edited in any way since it was last checked in, then the last
  1134. ** four hexadecimal digits of the hash may be modified.
  1135. **
  1136. ** See also: [sqlite3_libversion()],
  1137. ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
  1138. ** [sqlite_version()] and [sqlite_source_id()].
  1139. */
  1140. #define SQLITE_VERSION "3.29.0"
  1141. #define SQLITE_VERSION_NUMBER 3029000
  1142. #define SQLITE_SOURCE_ID "2019-07-10 17:32:03 fc82b73eaac8b36950e527f12c4b5dc1e147e6f4ad2217ae43ad82882a88bfa6"
  1143. /*
  1144. ** CAPI3REF: Run-Time Library Version Numbers
  1145. ** KEYWORDS: sqlite3_version sqlite3_sourceid
  1146. **
  1147. ** These interfaces provide the same information as the [SQLITE_VERSION],
  1148. ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
  1149. ** but are associated with the library instead of the header file. ^(Cautious
  1150. ** programmers might include assert() statements in their application to
  1151. ** verify that values returned by these interfaces match the macros in
  1152. ** the header, and thus ensure that the application is
  1153. ** compiled with matching library and header files.
  1154. **
  1155. ** <blockquote><pre>
  1156. ** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
  1157. ** assert( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,80)==0 );
  1158. ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
  1159. ** </pre></blockquote>)^
  1160. **
  1161. ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
  1162. ** macro. ^The sqlite3_libversion() function returns a pointer to the
  1163. ** to the sqlite3_version[] string constant. The sqlite3_libversion()
  1164. ** function is provided for use in DLLs since DLL users usually do not have
  1165. ** direct access to string constants within the DLL. ^The
  1166. ** sqlite3_libversion_number() function returns an integer equal to
  1167. ** [SQLITE_VERSION_NUMBER]. ^(The sqlite3_sourceid() function returns
  1168. ** a pointer to a string constant whose value is the same as the
  1169. ** [SQLITE_SOURCE_ID] C preprocessor macro. Except if SQLite is built
  1170. ** using an edited copy of [the amalgamation], then the last four characters
  1171. ** of the hash might be different from [SQLITE_SOURCE_ID].)^
  1172. **
  1173. ** See also: [sqlite_version()] and [sqlite_source_id()].
  1174. */
  1175. SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
  1176. SQLITE_API const char *sqlite3_libversion(void);
  1177. SQLITE_API const char *sqlite3_sourceid(void);
  1178. SQLITE_API int sqlite3_libversion_number(void);
  1179. /*
  1180. ** CAPI3REF: Run-Time Library Compilation Options Diagnostics
  1181. **
  1182. ** ^The sqlite3_compileoption_used() function returns 0 or 1
  1183. ** indicating whether the specified option was defined at
  1184. ** compile time. ^The SQLITE_ prefix may be omitted from the
  1185. ** option name passed to sqlite3_compileoption_used().
  1186. **
  1187. ** ^The sqlite3_compileoption_get() function allows iterating
  1188. ** over the list of options that were defined at compile time by
  1189. ** returning the N-th compile time option string. ^If N is out of range,
  1190. ** sqlite3_compileoption_get() returns a NULL pointer. ^The SQLITE_
  1191. ** prefix is omitted from any strings returned by
  1192. ** sqlite3_compileoption_get().
  1193. **
  1194. ** ^Support for the diagnostic functions sqlite3_compileoption_used()
  1195. ** and sqlite3_compileoption_get() may be omitted by specifying the
  1196. ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
  1197. **
  1198. ** See also: SQL functions [sqlite_compileoption_used()] and
  1199. ** [sqlite_compileoption_get()] and the [compile_options pragma].
  1200. */
  1201. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  1202. SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
  1203. SQLITE_API const char *sqlite3_compileoption_get(int N);
  1204. #else
  1205. # define sqlite3_compileoption_used(X) 0
  1206. # define sqlite3_compileoption_get(X) ((void*)0)
  1207. #endif
  1208. /*
  1209. ** CAPI3REF: Test To See If The Library Is Threadsafe
  1210. **
  1211. ** ^The sqlite3_threadsafe() function returns zero if and only if
  1212. ** SQLite was compiled with mutexing code omitted due to the
  1213. ** [SQLITE_THREADSAFE] compile-time option being set to 0.
  1214. **
  1215. ** SQLite can be compiled with or without mutexes. When
  1216. ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
  1217. ** are enabled and SQLite is threadsafe. When the
  1218. ** [SQLITE_THREADSAFE] macro is 0,
  1219. ** the mutexes are omitted. Without the mutexes, it is not safe
  1220. ** to use SQLite concurrently from more than one thread.
  1221. **
  1222. ** Enabling mutexes incurs a measurable performance penalty.
  1223. ** So if speed is of utmost importance, it makes sense to disable
  1224. ** the mutexes. But for maximum safety, mutexes should be enabled.
  1225. ** ^The default behavior is for mutexes to be enabled.
  1226. **
  1227. ** This interface can be used by an application to make sure that the
  1228. ** version of SQLite that it is linking against was compiled with
  1229. ** the desired setting of the [SQLITE_THREADSAFE] macro.
  1230. **
  1231. ** This interface only reports on the compile-time mutex setting
  1232. ** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with
  1233. ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
  1234. ** can be fully or partially disabled using a call to [sqlite3_config()]
  1235. ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
  1236. ** or [SQLITE_CONFIG_SERIALIZED]. ^(The return value of the
  1237. ** sqlite3_threadsafe() function shows only the compile-time setting of
  1238. ** thread safety, not any run-time changes to that setting made by
  1239. ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
  1240. ** is unchanged by calls to sqlite3_config().)^
  1241. **
  1242. ** See the [threading mode] documentation for additional information.
  1243. */
  1244. SQLITE_API int sqlite3_threadsafe(void);
  1245. /*
  1246. ** CAPI3REF: Database Connection Handle
  1247. ** KEYWORDS: {database connection} {database connections}
  1248. **
  1249. ** Each open SQLite database is represented by a pointer to an instance of
  1250. ** the opaque structure named "sqlite3". It is useful to think of an sqlite3
  1251. ** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and
  1252. ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
  1253. ** and [sqlite3_close_v2()] are its destructors. There are many other
  1254. ** interfaces (such as
  1255. ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
  1256. ** [sqlite3_busy_timeout()] to name but three) that are methods on an
  1257. ** sqlite3 object.
  1258. */
  1259. typedef struct sqlite3 sqlite3;
  1260. /*
  1261. ** CAPI3REF: 64-Bit Integer Types
  1262. ** KEYWORDS: sqlite_int64 sqlite_uint64
  1263. **
  1264. ** Because there is no cross-platform way to specify 64-bit integer types
  1265. ** SQLite includes typedefs for 64-bit signed and unsigned integers.
  1266. **
  1267. ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
  1268. ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
  1269. ** compatibility only.
  1270. **
  1271. ** ^The sqlite3_int64 and sqlite_int64 types can store integer values
  1272. ** between -9223372036854775808 and +9223372036854775807 inclusive. ^The
  1273. ** sqlite3_uint64 and sqlite_uint64 types can store integer values
  1274. ** between 0 and +18446744073709551615 inclusive.
  1275. */
  1276. #ifdef SQLITE_INT64_TYPE
  1277. typedef SQLITE_INT64_TYPE sqlite_int64;
  1278. # ifdef SQLITE_UINT64_TYPE
  1279. typedef SQLITE_UINT64_TYPE sqlite_uint64;
  1280. # else
  1281. typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
  1282. # endif
  1283. #elif defined(_MSC_VER) || defined(__BORLANDC__)
  1284. typedef __int64 sqlite_int64;
  1285. typedef unsigned __int64 sqlite_uint64;
  1286. #else
  1287. typedef long long int sqlite_int64;
  1288. typedef unsigned long long int sqlite_uint64;
  1289. #endif
  1290. typedef sqlite_int64 sqlite3_int64;
  1291. typedef sqlite_uint64 sqlite3_uint64;
  1292. /*
  1293. ** If compiling for a processor that lacks floating point support,
  1294. ** substitute integer for floating-point.
  1295. */
  1296. #ifdef SQLITE_OMIT_FLOATING_POINT
  1297. # define double sqlite3_int64
  1298. #endif
  1299. /*
  1300. ** CAPI3REF: Closing A Database Connection
  1301. ** DESTRUCTOR: sqlite3
  1302. **
  1303. ** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors
  1304. ** for the [sqlite3] object.
  1305. ** ^Calls to sqlite3_close() and sqlite3_close_v2() return [SQLITE_OK] if
  1306. ** the [sqlite3] object is successfully destroyed and all associated
  1307. ** resources are deallocated.
  1308. **
  1309. ** ^If the database connection is associated with unfinalized prepared
  1310. ** statements or unfinished sqlite3_backup objects then sqlite3_close()
  1311. ** will leave the database connection open and return [SQLITE_BUSY].
  1312. ** ^If sqlite3_close_v2() is called with unfinalized prepared statements
  1313. ** and/or unfinished sqlite3_backups, then the database connection becomes
  1314. ** an unusable "zombie" which will automatically be deallocated when the
  1315. ** last prepared statement is finalized or the last sqlite3_backup is
  1316. ** finished. The sqlite3_close_v2() interface is intended for use with
  1317. ** host languages that are garbage collected, and where the order in which
  1318. ** destructors are called is arbitrary.
  1319. **
  1320. ** Applications should [sqlite3_finalize | finalize] all [prepared statements],
  1321. ** [sqlite3_blob_close | close] all [BLOB handles], and
  1322. ** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated
  1323. ** with the [sqlite3] object prior to attempting to close the object. ^If
  1324. ** sqlite3_close_v2() is called on a [database connection] that still has
  1325. ** outstanding [prepared statements], [BLOB handles], and/or
  1326. ** [sqlite3_backup] objects then it returns [SQLITE_OK] and the deallocation
  1327. ** of resources is deferred until all [prepared statements], [BLOB handles],
  1328. ** and [sqlite3_backup] objects are also destroyed.
  1329. **
  1330. ** ^If an [sqlite3] object is destroyed while a transaction is open,
  1331. ** the transaction is automatically rolled back.
  1332. **
  1333. ** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)]
  1334. ** must be either a NULL
  1335. ** pointer or an [sqlite3] object pointer obtained
  1336. ** from [sqlite3_open()], [sqlite3_open16()], or
  1337. ** [sqlite3_open_v2()], and not previously closed.
  1338. ** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer
  1339. ** argument is a harmless no-op.
  1340. */
  1341. SQLITE_API int sqlite3_close(sqlite3*);
  1342. SQLITE_API int sqlite3_close_v2(sqlite3*);
  1343. /*
  1344. ** The type for a callback function.
  1345. ** This is legacy and deprecated. It is included for historical
  1346. ** compatibility and is not documented.
  1347. */
  1348. typedef int (*sqlite3_callback)(void*,int,char**, char**);
  1349. /*
  1350. ** CAPI3REF: One-Step Query Execution Interface
  1351. ** METHOD: sqlite3
  1352. **
  1353. ** The sqlite3_exec() interface is a convenience wrapper around
  1354. ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
  1355. ** that allows an application to run multiple statements of SQL
  1356. ** without having to use a lot of C code.
  1357. **
  1358. ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
  1359. ** semicolon-separate SQL statements passed into its 2nd argument,
  1360. ** in the context of the [database connection] passed in as its 1st
  1361. ** argument. ^If the callback function of the 3rd argument to
  1362. ** sqlite3_exec() is not NULL, then it is invoked for each result row
  1363. ** coming out of the evaluated SQL statements. ^The 4th argument to
  1364. ** sqlite3_exec() is relayed through to the 1st argument of each
  1365. ** callback invocation. ^If the callback pointer to sqlite3_exec()
  1366. ** is NULL, then no callback is ever invoked and result rows are
  1367. ** ignored.
  1368. **
  1369. ** ^If an error occurs while evaluating the SQL statements passed into
  1370. ** sqlite3_exec(), then execution of the current statement stops and
  1371. ** subsequent statements are skipped. ^If the 5th parameter to sqlite3_exec()
  1372. ** is not NULL then any error message is written into memory obtained
  1373. ** from [sqlite3_malloc()] and passed back through the 5th parameter.
  1374. ** To avoid memory leaks, the application should invoke [sqlite3_free()]
  1375. ** on error message strings returned through the 5th parameter of
  1376. ** sqlite3_exec() after the error message string is no longer needed.
  1377. ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
  1378. ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
  1379. ** NULL before returning.
  1380. **
  1381. ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
  1382. ** routine returns SQLITE_ABORT without invoking the callback again and
  1383. ** without running any subsequent SQL statements.
  1384. **
  1385. ** ^The 2nd argument to the sqlite3_exec() callback function is the
  1386. ** number of columns in the result. ^The 3rd argument to the sqlite3_exec()
  1387. ** callback is an array of pointers to strings obtained as if from
  1388. ** [sqlite3_column_text()], one for each column. ^If an element of a
  1389. ** result row is NULL then the corresponding string pointer for the
  1390. ** sqlite3_exec() callback is a NULL pointer. ^The 4th argument to the
  1391. ** sqlite3_exec() callback is an array of pointers to strings where each
  1392. ** entry represents the name of corresponding result column as obtained
  1393. ** from [sqlite3_column_name()].
  1394. **
  1395. ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
  1396. ** to an empty string, or a pointer that contains only whitespace and/or
  1397. ** SQL comments, then no SQL statements are evaluated and the database
  1398. ** is not changed.
  1399. **
  1400. ** Restrictions:
  1401. **
  1402. ** <ul>
  1403. ** <li> The application must ensure that the 1st parameter to sqlite3_exec()
  1404. ** is a valid and open [database connection].
  1405. ** <li> The application must not close the [database connection] specified by
  1406. ** the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
  1407. ** <li> The application must not modify the SQL statement text passed into
  1408. ** the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
  1409. ** </ul>
  1410. */
  1411. SQLITE_API int sqlite3_exec(
  1412. sqlite3*, /* An open database */
  1413. const char *sql, /* SQL to be evaluated */
  1414. int (*callback)(void*,int,char**,char**), /* Callback function */
  1415. void *, /* 1st argument to callback */
  1416. char **errmsg /* Error msg written here */
  1417. );
  1418. /*
  1419. ** CAPI3REF: Result Codes
  1420. ** KEYWORDS: {result code definitions}
  1421. **
  1422. ** Many SQLite functions return an integer result code from the set shown
  1423. ** here in order to indicate success or failure.
  1424. **
  1425. ** New error codes may be added in future versions of SQLite.
  1426. **
  1427. ** See also: [extended result code definitions]
  1428. */
  1429. #define SQLITE_OK 0 /* Successful result */
  1430. /* beginning-of-error-codes */
  1431. #define SQLITE_ERROR 1 /* Generic error */
  1432. #define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */
  1433. #define SQLITE_PERM 3 /* Access permission denied */
  1434. #define SQLITE_ABORT 4 /* Callback routine requested an abort */
  1435. #define SQLITE_BUSY 5 /* The database file is locked */
  1436. #define SQLITE_LOCKED 6 /* A table in the database is locked */
  1437. #define SQLITE_NOMEM 7 /* A malloc() failed */
  1438. #define SQLITE_READONLY 8 /* Attempt to write a readonly database */
  1439. #define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/
  1440. #define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */
  1441. #define SQLITE_CORRUPT 11 /* The database disk image is malformed */
  1442. #define SQLITE_NOTFOUND 12 /* Unknown opcode in sqlite3_file_control() */
  1443. #define SQLITE_FULL 13 /* Insertion failed because database is full */
  1444. #define SQLITE_CANTOPEN 14 /* Unable to open the database file */
  1445. #define SQLITE_PROTOCOL 15 /* Database lock protocol error */
  1446. #define SQLITE_EMPTY 16 /* Internal use only */
  1447. #define SQLITE_SCHEMA 17 /* The database schema changed */
  1448. #define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */
  1449. #define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */
  1450. #define SQLITE_MISMATCH 20 /* Data type mismatch */
  1451. #define SQLITE_MISUSE 21 /* Library used incorrectly */
  1452. #define SQLITE_NOLFS 22 /* Uses OS features not supported on host */
  1453. #define SQLITE_AUTH 23 /* Authorization denied */
  1454. #define SQLITE_FORMAT 24 /* Not used */
  1455. #define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */
  1456. #define SQLITE_NOTADB 26 /* File opened that is not a database file */
  1457. #define SQLITE_NOTICE 27 /* Notifications from sqlite3_log() */
  1458. #define SQLITE_WARNING 28 /* Warnings from sqlite3_log() */
  1459. #define SQLITE_ROW 100 /* sqlite3_step() has another row ready */
  1460. #define SQLITE_DONE 101 /* sqlite3_step() has finished executing */
  1461. /* end-of-error-codes */
  1462. /*
  1463. ** CAPI3REF: Extended Result Codes
  1464. ** KEYWORDS: {extended result code definitions}
  1465. **
  1466. ** In its default configuration, SQLite API routines return one of 30 integer
  1467. ** [result codes]. However, experience has shown that many of
  1468. ** these result codes are too coarse-grained. They do not provide as
  1469. ** much information about problems as programmers might like. In an effort to
  1470. ** address this, newer versions of SQLite (version 3.3.8 [dateof:3.3.8]
  1471. ** and later) include
  1472. ** support for additional result codes that provide more detailed information
  1473. ** about errors. These [extended result codes] are enabled or disabled
  1474. ** on a per database connection basis using the
  1475. ** [sqlite3_extended_result_codes()] API. Or, the extended code for
  1476. ** the most recent error can be obtained using
  1477. ** [sqlite3_extended_errcode()].
  1478. */
  1479. #define SQLITE_ERROR_MISSING_COLLSEQ (SQLITE_ERROR | (1<<8))
  1480. #define SQLITE_ERROR_RETRY (SQLITE_ERROR | (2<<8))
  1481. #define SQLITE_ERROR_SNAPSHOT (SQLITE_ERROR | (3<<8))
  1482. #define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8))
  1483. #define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8))
  1484. #define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8))
  1485. #define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8))
  1486. #define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8))
  1487. #define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8))
  1488. #define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8))
  1489. #define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8))
  1490. #define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8))
  1491. #define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8))
  1492. #define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8))
  1493. #define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8))
  1494. #define SQLITE_IOERR_ACCESS (SQLITE_IOERR | (13<<8))
  1495. #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
  1496. #define SQLITE_IOERR_LOCK (SQLITE_IOERR | (15<<8))
  1497. #define SQLITE_IOERR_CLOSE (SQLITE_IOERR | (16<<8))
  1498. #define SQLITE_IOERR_DIR_CLOSE (SQLITE_IOERR | (17<<8))
  1499. #define SQLITE_IOERR_SHMOPEN (SQLITE_IOERR | (18<<8))
  1500. #define SQLITE_IOERR_SHMSIZE (SQLITE_IOERR | (19<<8))
  1501. #define SQLITE_IOERR_SHMLOCK (SQLITE_IOERR | (20<<8))
  1502. #define SQLITE_IOERR_SHMMAP (SQLITE_IOERR | (21<<8))
  1503. #define SQLITE_IOERR_SEEK (SQLITE_IOERR | (22<<8))
  1504. #define SQLITE_IOERR_DELETE_NOENT (SQLITE_IOERR | (23<<8))
  1505. #define SQLITE_IOERR_MMAP (SQLITE_IOERR | (24<<8))
  1506. #define SQLITE_IOERR_GETTEMPPATH (SQLITE_IOERR | (25<<8))
  1507. #define SQLITE_IOERR_CONVPATH (SQLITE_IOERR | (26<<8))
  1508. #define SQLITE_IOERR_VNODE (SQLITE_IOERR | (27<<8))
  1509. #define SQLITE_IOERR_AUTH (SQLITE_IOERR | (28<<8))
  1510. #define SQLITE_IOERR_BEGIN_ATOMIC (SQLITE_IOERR | (29<<8))
  1511. #define SQLITE_IOERR_COMMIT_ATOMIC (SQLITE_IOERR | (30<<8))
  1512. #define SQLITE_IOERR_ROLLBACK_ATOMIC (SQLITE_IOERR | (31<<8))
  1513. #define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8))
  1514. #define SQLITE_LOCKED_VTAB (SQLITE_LOCKED | (2<<8))
  1515. #define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8))
  1516. #define SQLITE_BUSY_SNAPSHOT (SQLITE_BUSY | (2<<8))
  1517. #define SQLITE_CANTOPEN_NOTEMPDIR (SQLITE_CANTOPEN | (1<<8))
  1518. #define SQLITE_CANTOPEN_ISDIR (SQLITE_CANTOPEN | (2<<8))
  1519. #define SQLITE_CANTOPEN_FULLPATH (SQLITE_CANTOPEN | (3<<8))
  1520. #define SQLITE_CANTOPEN_CONVPATH (SQLITE_CANTOPEN | (4<<8))
  1521. #define SQLITE_CANTOPEN_DIRTYWAL (SQLITE_CANTOPEN | (5<<8)) /* Not Used */
  1522. #define SQLITE_CORRUPT_VTAB (SQLITE_CORRUPT | (1<<8))
  1523. #define SQLITE_CORRUPT_SEQUENCE (SQLITE_CORRUPT | (2<<8))
  1524. #define SQLITE_READONLY_RECOVERY (SQLITE_READONLY | (1<<8))
  1525. #define SQLITE_READONLY_CANTLOCK (SQLITE_READONLY | (2<<8))
  1526. #define SQLITE_READONLY_ROLLBACK (SQLITE_READONLY | (3<<8))
  1527. #define SQLITE_READONLY_DBMOVED (SQLITE_READONLY | (4<<8))
  1528. #define SQLITE_READONLY_CANTINIT (SQLITE_READONLY | (5<<8))
  1529. #define SQLITE_READONLY_DIRECTORY (SQLITE_READONLY | (6<<8))
  1530. #define SQLITE_ABORT_ROLLBACK (SQLITE_ABORT | (2<<8))
  1531. #define SQLITE_CONSTRAINT_CHECK (SQLITE_CONSTRAINT | (1<<8))
  1532. #define SQLITE_CONSTRAINT_COMMITHOOK (SQLITE_CONSTRAINT | (2<<8))
  1533. #define SQLITE_CONSTRAINT_FOREIGNKEY (SQLITE_CONSTRAINT | (3<<8))
  1534. #define SQLITE_CONSTRAINT_FUNCTION (SQLITE_CONSTRAINT | (4<<8))
  1535. #define SQLITE_CONSTRAINT_NOTNULL (SQLITE_CONSTRAINT | (5<<8))
  1536. #define SQLITE_CONSTRAINT_PRIMARYKEY (SQLITE_CONSTRAINT | (6<<8))
  1537. #define SQLITE_CONSTRAINT_TRIGGER (SQLITE_CONSTRAINT | (7<<8))
  1538. #define SQLITE_CONSTRAINT_UNIQUE (SQLITE_CONSTRAINT | (8<<8))
  1539. #define SQLITE_CONSTRAINT_VTAB (SQLITE_CONSTRAINT | (9<<8))
  1540. #define SQLITE_CONSTRAINT_ROWID (SQLITE_CONSTRAINT |(10<<8))
  1541. #define SQLITE_NOTICE_RECOVER_WAL (SQLITE_NOTICE | (1<<8))
  1542. #define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))
  1543. #define SQLITE_WARNING_AUTOINDEX (SQLITE_WARNING | (1<<8))
  1544. #define SQLITE_AUTH_USER (SQLITE_AUTH | (1<<8))
  1545. #define SQLITE_OK_LOAD_PERMANENTLY (SQLITE_OK | (1<<8))
  1546. /*
  1547. ** CAPI3REF: Flags For File Open Operations
  1548. **
  1549. ** These bit values are intended for use in the
  1550. ** 3rd parameter to the [sqlite3_open_v2()] interface and
  1551. ** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
  1552. */
  1553. #define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */
  1554. #define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */
  1555. #define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */
  1556. #define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */
  1557. #define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */
  1558. #define SQLITE_OPEN_AUTOPROXY 0x00000020 /* VFS only */
  1559. #define SQLITE_OPEN_URI 0x00000040 /* Ok for sqlite3_open_v2() */
  1560. #define SQLITE_OPEN_MEMORY 0x00000080 /* Ok for sqlite3_open_v2() */
  1561. #define SQLITE_OPEN_MAIN_DB 0x00000100 /* VFS only */
  1562. #define SQLITE_OPEN_TEMP_DB 0x00000200 /* VFS only */
  1563. #define SQLITE_OPEN_TRANSIENT_DB 0x00000400 /* VFS only */
  1564. #define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 /* VFS only */
  1565. #define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 /* VFS only */
  1566. #define SQLITE_OPEN_SUBJOURNAL 0x00002000 /* VFS only */
  1567. #define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* VFS only */
  1568. #define SQLITE_OPEN_NOMUTEX 0x00008000 /* Ok for sqlite3_open_v2() */
  1569. #define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for sqlite3_open_v2() */
  1570. #define SQLITE_OPEN_SHAREDCACHE 0x00020000 /* Ok for sqlite3_open_v2() */
  1571. #define SQLITE_OPEN_PRIVATECACHE 0x00040000 /* Ok for sqlite3_open_v2() */
  1572. #define SQLITE_OPEN_WAL 0x00080000 /* VFS only */
  1573. /* Reserved: 0x00F00000 */
  1574. /*
  1575. ** CAPI3REF: Device Characteristics
  1576. **
  1577. ** The xDeviceCharacteristics method of the [sqlite3_io_methods]
  1578. ** object returns an integer which is a vector of these
  1579. ** bit values expressing I/O characteristics of the mass storage
  1580. ** device that holds the file that the [sqlite3_io_methods]
  1581. ** refers to.
  1582. **
  1583. ** The SQLITE_IOCAP_ATOMIC property means that all writes of
  1584. ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
  1585. ** mean that writes of blocks that are nnn bytes in size and
  1586. ** are aligned to an address which is an integer multiple of
  1587. ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
  1588. ** that when data is appended to a file, the data is appended
  1589. ** first then the size of the file is extended, never the other
  1590. ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
  1591. ** information is written to disk in the same order as calls
  1592. ** to xWrite(). The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
  1593. ** after reboot following a crash or power loss, the only bytes in a
  1594. ** file that were written at the application level might have changed
  1595. ** and that adjacent bytes, even bytes within the same sector are
  1596. ** guaranteed to be unchanged. The SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
  1597. ** flag indicates that a file cannot be deleted when open. The
  1598. ** SQLITE_IOCAP_IMMUTABLE flag indicates that the file is on
  1599. ** read-only media and cannot be changed even by processes with
  1600. ** elevated privileges.
  1601. **
  1602. ** The SQLITE_IOCAP_BATCH_ATOMIC property means that the underlying
  1603. ** filesystem supports doing multiple write operations atomically when those
  1604. ** write operations are bracketed by [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] and
  1605. ** [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE].
  1606. */
  1607. #define SQLITE_IOCAP_ATOMIC 0x00000001
  1608. #define SQLITE_IOCAP_ATOMIC512 0x00000002
  1609. #define SQLITE_IOCAP_ATOMIC1K 0x00000004
  1610. #define SQLITE_IOCAP_ATOMIC2K 0x00000008
  1611. #define SQLITE_IOCAP_ATOMIC4K 0x00000010
  1612. #define SQLITE_IOCAP_ATOMIC8K 0x00000020
  1613. #define SQLITE_IOCAP_ATOMIC16K 0x00000040
  1614. #define SQLITE_IOCAP_ATOMIC32K 0x00000080
  1615. #define SQLITE_IOCAP_ATOMIC64K 0x00000100
  1616. #define SQLITE_IOCAP_SAFE_APPEND 0x00000200
  1617. #define SQLITE_IOCAP_SEQUENTIAL 0x00000400
  1618. #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN 0x00000800
  1619. #define SQLITE_IOCAP_POWERSAFE_OVERWRITE 0x00001000
  1620. #define SQLITE_IOCAP_IMMUTABLE 0x00002000
  1621. #define SQLITE_IOCAP_BATCH_ATOMIC 0x00004000
  1622. /*
  1623. ** CAPI3REF: File Locking Levels
  1624. **
  1625. ** SQLite uses one of these integer values as the second
  1626. ** argument to calls it makes to the xLock() and xUnlock() methods
  1627. ** of an [sqlite3_io_methods] object.
  1628. */
  1629. #define SQLITE_LOCK_NONE 0
  1630. #define SQLITE_LOCK_SHARED 1
  1631. #define SQLITE_LOCK_RESERVED 2
  1632. #define SQLITE_LOCK_PENDING 3
  1633. #define SQLITE_LOCK_EXCLUSIVE 4
  1634. /*
  1635. ** CAPI3REF: Synchronization Type Flags
  1636. **
  1637. ** When SQLite invokes the xSync() method of an
  1638. ** [sqlite3_io_methods] object it uses a combination of
  1639. ** these integer values as the second argument.
  1640. **
  1641. ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
  1642. ** sync operation only needs to flush data to mass storage. Inode
  1643. ** information need not be flushed. If the lower four bits of the flag
  1644. ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
  1645. ** If the lower four bits equal SQLITE_SYNC_FULL, that means
  1646. ** to use Mac OS X style fullsync instead of fsync().
  1647. **
  1648. ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
  1649. ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
  1650. ** settings. The [synchronous pragma] determines when calls to the
  1651. ** xSync VFS method occur and applies uniformly across all platforms.
  1652. ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
  1653. ** energetic or rigorous or forceful the sync operations are and
  1654. ** only make a difference on Mac OSX for the default SQLite code.
  1655. ** (Third-party VFS implementations might also make the distinction
  1656. ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
  1657. ** operating systems natively supported by SQLite, only Mac OSX
  1658. ** cares about the difference.)
  1659. */
  1660. #define SQLITE_SYNC_NORMAL 0x00002
  1661. #define SQLITE_SYNC_FULL 0x00003
  1662. #define SQLITE_SYNC_DATAONLY 0x00010
  1663. /*
  1664. ** CAPI3REF: OS Interface Open File Handle
  1665. **
  1666. ** An [sqlite3_file] object represents an open file in the
  1667. ** [sqlite3_vfs | OS interface layer]. Individual OS interface
  1668. ** implementations will
  1669. ** want to subclass this object by appending additional fields
  1670. ** for their own use. The pMethods entry is a pointer to an
  1671. ** [sqlite3_io_methods] object that defines methods for performing
  1672. ** I/O operations on the open file.
  1673. */
  1674. typedef struct sqlite3_file sqlite3_file;
  1675. struct sqlite3_file {
  1676. const struct sqlite3_io_methods *pMethods; /* Methods for an open file */
  1677. };
  1678. /*
  1679. ** CAPI3REF: OS Interface File Virtual Methods Object
  1680. **
  1681. ** Every file opened by the [sqlite3_vfs.xOpen] method populates an
  1682. ** [sqlite3_file] object (or, more commonly, a subclass of the
  1683. ** [sqlite3_file] object) with a pointer to an instance of this object.
  1684. ** This object defines the methods used to perform various operations
  1685. ** against the open file represented by the [sqlite3_file] object.
  1686. **
  1687. ** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element
  1688. ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
  1689. ** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed. The
  1690. ** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
  1691. ** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
  1692. ** to NULL.
  1693. **
  1694. ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
  1695. ** [SQLITE_SYNC_FULL]. The first choice is the normal fsync().
  1696. ** The second choice is a Mac OS X style fullsync. The [SQLITE_SYNC_DATAONLY]
  1697. ** flag may be ORed in to indicate that only the data of the file
  1698. ** and not its inode needs to be synced.
  1699. **
  1700. ** The integer values to xLock() and xUnlock() are one of
  1701. ** <ul>
  1702. ** <li> [SQLITE_LOCK_NONE],
  1703. ** <li> [SQLITE_LOCK_SHARED],
  1704. ** <li> [SQLITE_LOCK_RESERVED],
  1705. ** <li> [SQLITE_LOCK_PENDING], or
  1706. ** <li> [SQLITE_LOCK_EXCLUSIVE].
  1707. ** </ul>
  1708. ** xLock() increases the lock. xUnlock() decreases the lock.
  1709. ** The xCheckReservedLock() method checks whether any database connection,
  1710. ** either in this process or in some other process, is holding a RESERVED,
  1711. ** PENDING, or EXCLUSIVE lock on the file. It returns true
  1712. ** if such a lock exists and false otherwise.
  1713. **
  1714. ** The xFileControl() method is a generic interface that allows custom
  1715. ** VFS implementations to directly control an open file using the
  1716. ** [sqlite3_file_control()] interface. The second "op" argument is an
  1717. ** integer opcode. The third argument is a generic pointer intended to
  1718. ** point to a structure that may contain arguments or space in which to
  1719. ** write return values. Potential uses for xFileControl() might be
  1720. ** functions to enable blocking locks with timeouts, to change the
  1721. ** locking strategy (for example to use dot-file locks), to inquire
  1722. ** about the status of a lock, or to break stale locks. The SQLite
  1723. ** core reserves all opcodes less than 100 for its own use.
  1724. ** A [file control opcodes | list of opcodes] less than 100 is available.
  1725. ** Applications that define a custom xFileControl method should use opcodes
  1726. ** greater than 100 to avoid conflicts. VFS implementations should
  1727. ** return [SQLITE_NOTFOUND] for file control opcodes that they do not
  1728. ** recognize.
  1729. **
  1730. ** The xSectorSize() method returns the sector size of the
  1731. ** device that underlies the file. The sector size is the
  1732. ** minimum write that can be performed without disturbing
  1733. ** other bytes in the file. The xDeviceCharacteristics()
  1734. ** method returns a bit vector describing behaviors of the
  1735. ** underlying device:
  1736. **
  1737. ** <ul>
  1738. ** <li> [SQLITE_IOCAP_ATOMIC]
  1739. ** <li> [SQLITE_IOCAP_ATOMIC512]
  1740. ** <li> [SQLITE_IOCAP_ATOMIC1K]
  1741. ** <li> [SQLITE_IOCAP_ATOMIC2K]
  1742. ** <li> [SQLITE_IOCAP_ATOMIC4K]
  1743. ** <li> [SQLITE_IOCAP_ATOMIC8K]
  1744. ** <li> [SQLITE_IOCAP_ATOMIC16K]
  1745. ** <li> [SQLITE_IOCAP_ATOMIC32K]
  1746. ** <li> [SQLITE_IOCAP_ATOMIC64K]
  1747. ** <li> [SQLITE_IOCAP_SAFE_APPEND]
  1748. ** <li> [SQLITE_IOCAP_SEQUENTIAL]
  1749. ** <li> [SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN]
  1750. ** <li> [SQLITE_IOCAP_POWERSAFE_OVERWRITE]
  1751. ** <li> [SQLITE_IOCAP_IMMUTABLE]
  1752. ** <li> [SQLITE_IOCAP_BATCH_ATOMIC]
  1753. ** </ul>
  1754. **
  1755. ** The SQLITE_IOCAP_ATOMIC property means that all writes of
  1756. ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
  1757. ** mean that writes of blocks that are nnn bytes in size and
  1758. ** are aligned to an address which is an integer multiple of
  1759. ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
  1760. ** that when data is appended to a file, the data is appended
  1761. ** first then the size of the file is extended, never the other
  1762. ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
  1763. ** information is written to disk in the same order as calls
  1764. ** to xWrite().
  1765. **
  1766. ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
  1767. ** in the unread portions of the buffer with zeros. A VFS that
  1768. ** fails to zero-fill short reads might seem to work. However,
  1769. ** failure to zero-fill short reads will eventually lead to
  1770. ** database corruption.
  1771. */
  1772. typedef struct sqlite3_io_methods sqlite3_io_methods;
  1773. struct sqlite3_io_methods {
  1774. int iVersion;
  1775. int (*xClose)(sqlite3_file*);
  1776. int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
  1777. int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
  1778. int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
  1779. int (*xSync)(sqlite3_file*, int flags);
  1780. int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
  1781. int (*xLock)(sqlite3_file*, int);
  1782. int (*xUnlock)(sqlite3_file*, int);
  1783. int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
  1784. int (*xFileControl)(sqlite3_file*, int op, void *pArg);
  1785. int (*xSectorSize)(sqlite3_file*);
  1786. int (*xDeviceCharacteristics)(sqlite3_file*);
  1787. /* Methods above are valid for version 1 */
  1788. int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
  1789. int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
  1790. void (*xShmBarrier)(sqlite3_file*);
  1791. int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
  1792. /* Methods above are valid for version 2 */
  1793. int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
  1794. int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p);
  1795. /* Methods above are valid for version 3 */
  1796. /* Additional methods may be added in future releases */
  1797. };
  1798. /*
  1799. ** CAPI3REF: Standard File Control Opcodes
  1800. ** KEYWORDS: {file control opcodes} {file control opcode}
  1801. **
  1802. ** These integer constants are opcodes for the xFileControl method
  1803. ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
  1804. ** interface.
  1805. **
  1806. ** <ul>
  1807. ** <li>[[SQLITE_FCNTL_LOCKSTATE]]
  1808. ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This
  1809. ** opcode causes the xFileControl method to write the current state of
  1810. ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
  1811. ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
  1812. ** into an integer that the pArg argument points to. This capability
  1813. ** is used during testing and is only available when the SQLITE_TEST
  1814. ** compile-time option is used.
  1815. **
  1816. ** <li>[[SQLITE_FCNTL_SIZE_HINT]]
  1817. ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
  1818. ** layer a hint of how large the database file will grow to be during the
  1819. ** current transaction. This hint is not guaranteed to be accurate but it
  1820. ** is often close. The underlying VFS might choose to preallocate database
  1821. ** file space based on this hint in order to help writes to the database
  1822. ** file run faster.
  1823. **
  1824. ** <li>[[SQLITE_FCNTL_SIZE_LIMIT]]
  1825. ** The [SQLITE_FCNTL_SIZE_LIMIT] opcode is used by in-memory VFS that
  1826. ** implements [sqlite3_deserialize()] to set an upper bound on the size
  1827. ** of the in-memory database. The argument is a pointer to a [sqlite3_int64].
  1828. ** If the integer pointed to is negative, then it is filled in with the
  1829. ** current limit. Otherwise the limit is set to the larger of the value
  1830. ** of the integer pointed to and the current database size. The integer
  1831. ** pointed to is set to the new limit.
  1832. **
  1833. ** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
  1834. ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
  1835. ** extends and truncates the database file in chunks of a size specified
  1836. ** by the user. The fourth argument to [sqlite3_file_control()] should
  1837. ** point to an integer (type int) containing the new chunk-size to use
  1838. ** for the nominated database. Allocating database file space in large
  1839. ** chunks (say 1MB at a time), may reduce file-system fragmentation and
  1840. ** improve performance on some systems.
  1841. **
  1842. ** <li>[[SQLITE_FCNTL_FILE_POINTER]]
  1843. ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
  1844. ** to the [sqlite3_file] object associated with a particular database
  1845. ** connection. See also [SQLITE_FCNTL_JOURNAL_POINTER].
  1846. **
  1847. ** <li>[[SQLITE_FCNTL_JOURNAL_POINTER]]
  1848. ** The [SQLITE_FCNTL_JOURNAL_POINTER] opcode is used to obtain a pointer
  1849. ** to the [sqlite3_file] object associated with the journal file (either
  1850. ** the [rollback journal] or the [write-ahead log]) for a particular database
  1851. ** connection. See also [SQLITE_FCNTL_FILE_POINTER].
  1852. **
  1853. ** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
  1854. ** No longer in use.
  1855. **
  1856. ** <li>[[SQLITE_FCNTL_SYNC]]
  1857. ** The [SQLITE_FCNTL_SYNC] opcode is generated internally by SQLite and
  1858. ** sent to the VFS immediately before the xSync method is invoked on a
  1859. ** database file descriptor. Or, if the xSync method is not invoked
  1860. ** because the user has configured SQLite with
  1861. ** [PRAGMA synchronous | PRAGMA synchronous=OFF] it is invoked in place
  1862. ** of the xSync method. In most cases, the pointer argument passed with
  1863. ** this file-control is NULL. However, if the database file is being synced
  1864. ** as part of a multi-database commit, the argument points to a nul-terminated
  1865. ** string containing the transactions master-journal file name. VFSes that
  1866. ** do not need this signal should silently ignore this opcode. Applications
  1867. ** should not call [sqlite3_file_control()] with this opcode as doing so may
  1868. ** disrupt the operation of the specialized VFSes that do require it.
  1869. **
  1870. ** <li>[[SQLITE_FCNTL_COMMIT_PHASETWO]]
  1871. ** The [SQLITE_FCNTL_COMMIT_PHASETWO] opcode is generated internally by SQLite
  1872. ** and sent to the VFS after a transaction has been committed immediately
  1873. ** but before the database is unlocked. VFSes that do not need this signal
  1874. ** should silently ignore this opcode. Applications should not call
  1875. ** [sqlite3_file_control()] with this opcode as doing so may disrupt the
  1876. ** operation of the specialized VFSes that do require it.
  1877. **
  1878. ** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
  1879. ** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
  1880. ** retry counts and intervals for certain disk I/O operations for the
  1881. ** windows [VFS] in order to provide robustness in the presence of
  1882. ** anti-virus programs. By default, the windows VFS will retry file read,
  1883. ** file write, and file delete operations up to 10 times, with a delay
  1884. ** of 25 milliseconds before the first retry and with the delay increasing
  1885. ** by an additional 25 milliseconds with each subsequent retry. This
  1886. ** opcode allows these two values (10 retries and 25 milliseconds of delay)
  1887. ** to be adjusted. The values are changed for all database connections
  1888. ** within the same process. The argument is a pointer to an array of two
  1889. ** integers where the first integer is the new retry count and the second
  1890. ** integer is the delay. If either integer is negative, then the setting
  1891. ** is not changed but instead the prior value of that setting is written
  1892. ** into the array entry, allowing the current retry settings to be
  1893. ** interrogated. The zDbName parameter is ignored.
  1894. **
  1895. ** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
  1896. ** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
  1897. ** persistent [WAL | Write Ahead Log] setting. By default, the auxiliary
  1898. ** write ahead log ([WAL file]) and shared memory
  1899. ** files used for transaction control
  1900. ** are automatically deleted when the latest connection to the database
  1901. ** closes. Setting persistent WAL mode causes those files to persist after
  1902. ** close. Persisting the files is useful when other processes that do not
  1903. ** have write permission on the directory containing the database file want
  1904. ** to read the database file, as the WAL and shared memory files must exist
  1905. ** in order for the database to be readable. The fourth parameter to
  1906. ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
  1907. ** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
  1908. ** WAL mode. If the integer is -1, then it is overwritten with the current
  1909. ** WAL persistence setting.
  1910. **
  1911. ** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
  1912. ** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
  1913. ** persistent "powersafe-overwrite" or "PSOW" setting. The PSOW setting
  1914. ** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
  1915. ** xDeviceCharacteristics methods. The fourth parameter to
  1916. ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
  1917. ** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
  1918. ** mode. If the integer is -1, then it is overwritten with the current
  1919. ** zero-damage mode setting.
  1920. **
  1921. ** <li>[[SQLITE_FCNTL_OVERWRITE]]
  1922. ** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
  1923. ** a write transaction to indicate that, unless it is rolled back for some
  1924. ** reason, the entire database file will be overwritten by the current
  1925. ** transaction. This is used by VACUUM operations.
  1926. **
  1927. ** <li>[[SQLITE_FCNTL_VFSNAME]]
  1928. ** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
  1929. ** all [VFSes] in the VFS stack. The names are of all VFS shims and the
  1930. ** final bottom-level VFS are written into memory obtained from
  1931. ** [sqlite3_malloc()] and the result is stored in the char* variable
  1932. ** that the fourth parameter of [sqlite3_file_control()] points to.
  1933. ** The caller is responsible for freeing the memory when done. As with
  1934. ** all file-control actions, there is no guarantee that this will actually
  1935. ** do anything. Callers should initialize the char* variable to a NULL
  1936. ** pointer in case this file-control is not implemented. This file-control
  1937. ** is intended for diagnostic use only.
  1938. **
  1939. ** <li>[[SQLITE_FCNTL_VFS_POINTER]]
  1940. ** ^The [SQLITE_FCNTL_VFS_POINTER] opcode finds a pointer to the top-level
  1941. ** [VFSes] currently in use. ^(The argument X in
  1942. ** sqlite3_file_control(db,SQLITE_FCNTL_VFS_POINTER,X) must be
  1943. ** of type "[sqlite3_vfs] **". This opcodes will set *X
  1944. ** to a pointer to the top-level VFS.)^
  1945. ** ^When there are multiple VFS shims in the stack, this opcode finds the
  1946. ** upper-most shim only.
  1947. **
  1948. ** <li>[[SQLITE_FCNTL_PRAGMA]]
  1949. ** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA]
  1950. ** file control is sent to the open [sqlite3_file] object corresponding
  1951. ** to the database file to which the pragma statement refers. ^The argument
  1952. ** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
  1953. ** pointers to strings (char**) in which the second element of the array
  1954. ** is the name of the pragma and the third element is the argument to the
  1955. ** pragma or NULL if the pragma has no argument. ^The handler for an
  1956. ** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
  1957. ** of the char** argument point to a string obtained from [sqlite3_mprintf()]
  1958. ** or the equivalent and that string will become the result of the pragma or
  1959. ** the error message if the pragma fails. ^If the
  1960. ** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal
  1961. ** [PRAGMA] processing continues. ^If the [SQLITE_FCNTL_PRAGMA]
  1962. ** file control returns [SQLITE_OK], then the parser assumes that the
  1963. ** VFS has handled the PRAGMA itself and the parser generates a no-op
  1964. ** prepared statement if result string is NULL, or that returns a copy
  1965. ** of the result string if the string is non-NULL.
  1966. ** ^If the [SQLITE_FCNTL_PRAGMA] file control returns
  1967. ** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
  1968. ** that the VFS encountered an error while handling the [PRAGMA] and the
  1969. ** compilation of the PRAGMA fails with an error. ^The [SQLITE_FCNTL_PRAGMA]
  1970. ** file control occurs at the beginning of pragma statement analysis and so
  1971. ** it is able to override built-in [PRAGMA] statements.
  1972. **
  1973. ** <li>[[SQLITE_FCNTL_BUSYHANDLER]]
  1974. ** ^The [SQLITE_FCNTL_BUSYHANDLER]
  1975. ** file-control may be invoked by SQLite on the database file handle
  1976. ** shortly after it is opened in order to provide a custom VFS with access
  1977. ** to the connections busy-handler callback. The argument is of type (void **)
  1978. ** - an array of two (void *) values. The first (void *) actually points
  1979. ** to a function of type (int (*)(void *)). In order to invoke the connections
  1980. ** busy-handler, this function should be invoked with the second (void *) in
  1981. ** the array as the only argument. If it returns non-zero, then the operation
  1982. ** should be retried. If it returns zero, the custom VFS should abandon the
  1983. ** current operation.
  1984. **
  1985. ** <li>[[SQLITE_FCNTL_TEMPFILENAME]]
  1986. ** ^Application can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control
  1987. ** to have SQLite generate a
  1988. ** temporary filename using the same algorithm that is followed to generate
  1989. ** temporary filenames for TEMP tables and other internal uses. The
  1990. ** argument should be a char** which will be filled with the filename
  1991. ** written into memory obtained from [sqlite3_malloc()]. The caller should
  1992. ** invoke [sqlite3_free()] on the result to avoid a memory leak.
  1993. **
  1994. ** <li>[[SQLITE_FCNTL_MMAP_SIZE]]
  1995. ** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the
  1996. ** maximum number of bytes that will be used for memory-mapped I/O.
  1997. ** The argument is a pointer to a value of type sqlite3_int64 that
  1998. ** is an advisory maximum number of bytes in the file to memory map. The
  1999. ** pointer is overwritten with the old value. The limit is not changed if
  2000. ** the value originally pointed to is negative, and so the current limit
  2001. ** can be queried by passing in a pointer to a negative number. This
  2002. ** file-control is used internally to implement [PRAGMA mmap_size].
  2003. **
  2004. ** <li>[[SQLITE_FCNTL_TRACE]]
  2005. ** The [SQLITE_FCNTL_TRACE] file control provides advisory information
  2006. ** to the VFS about what the higher layers of the SQLite stack are doing.
  2007. ** This file control is used by some VFS activity tracing [shims].
  2008. ** The argument is a zero-terminated string. Higher layers in the
  2009. ** SQLite stack may generate instances of this file control if
  2010. ** the [SQLITE_USE_FCNTL_TRACE] compile-time option is enabled.
  2011. **
  2012. ** <li>[[SQLITE_FCNTL_HAS_MOVED]]
  2013. ** The [SQLITE_FCNTL_HAS_MOVED] file control interprets its argument as a
  2014. ** pointer to an integer and it writes a boolean into that integer depending
  2015. ** on whether or not the file has been renamed, moved, or deleted since it
  2016. ** was first opened.
  2017. **
  2018. ** <li>[[SQLITE_FCNTL_WIN32_GET_HANDLE]]
  2019. ** The [SQLITE_FCNTL_WIN32_GET_HANDLE] opcode can be used to obtain the
  2020. ** underlying native file handle associated with a file handle. This file
  2021. ** control interprets its argument as a pointer to a native file handle and
  2022. ** writes the resulting value there.
  2023. **
  2024. ** <li>[[SQLITE_FCNTL_WIN32_SET_HANDLE]]
  2025. ** The [SQLITE_FCNTL_WIN32_SET_HANDLE] opcode is used for debugging. This
  2026. ** opcode causes the xFileControl method to swap the file handle with the one
  2027. ** pointed to by the pArg argument. This capability is used during testing
  2028. ** and only needs to be supported when SQLITE_TEST is defined.
  2029. **
  2030. ** <li>[[SQLITE_FCNTL_WAL_BLOCK]]
  2031. ** The [SQLITE_FCNTL_WAL_BLOCK] is a signal to the VFS layer that it might
  2032. ** be advantageous to block on the next WAL lock if the lock is not immediately
  2033. ** available. The WAL subsystem issues this signal during rare
  2034. ** circumstances in order to fix a problem with priority inversion.
  2035. ** Applications should <em>not</em> use this file-control.
  2036. **
  2037. ** <li>[[SQLITE_FCNTL_ZIPVFS]]
  2038. ** The [SQLITE_FCNTL_ZIPVFS] opcode is implemented by zipvfs only. All other
  2039. ** VFS should return SQLITE_NOTFOUND for this opcode.
  2040. **
  2041. ** <li>[[SQLITE_FCNTL_RBU]]
  2042. ** The [SQLITE_FCNTL_RBU] opcode is implemented by the special VFS used by
  2043. ** the RBU extension only. All other VFS should return SQLITE_NOTFOUND for
  2044. ** this opcode.
  2045. **
  2046. ** <li>[[SQLITE_FCNTL_BEGIN_ATOMIC_WRITE]]
  2047. ** If the [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] opcode returns SQLITE_OK, then
  2048. ** the file descriptor is placed in "batch write mode", which
  2049. ** means all subsequent write operations will be deferred and done
  2050. ** atomically at the next [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE]. Systems
  2051. ** that do not support batch atomic writes will return SQLITE_NOTFOUND.
  2052. ** ^Following a successful SQLITE_FCNTL_BEGIN_ATOMIC_WRITE and prior to
  2053. ** the closing [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE] or
  2054. ** [SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE], SQLite will make
  2055. ** no VFS interface calls on the same [sqlite3_file] file descriptor
  2056. ** except for calls to the xWrite method and the xFileControl method
  2057. ** with [SQLITE_FCNTL_SIZE_HINT].
  2058. **
  2059. ** <li>[[SQLITE_FCNTL_COMMIT_ATOMIC_WRITE]]
  2060. ** The [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE] opcode causes all write
  2061. ** operations since the previous successful call to
  2062. ** [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] to be performed atomically.
  2063. ** This file control returns [SQLITE_OK] if and only if the writes were
  2064. ** all performed successfully and have been committed to persistent storage.
  2065. ** ^Regardless of whether or not it is successful, this file control takes
  2066. ** the file descriptor out of batch write mode so that all subsequent
  2067. ** write operations are independent.
  2068. ** ^SQLite will never invoke SQLITE_FCNTL_COMMIT_ATOMIC_WRITE without
  2069. ** a prior successful call to [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE].
  2070. **
  2071. ** <li>[[SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE]]
  2072. ** The [SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE] opcode causes all write
  2073. ** operations since the previous successful call to
  2074. ** [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] to be rolled back.
  2075. ** ^This file control takes the file descriptor out of batch write mode
  2076. ** so that all subsequent write operations are independent.
  2077. ** ^SQLite will never invoke SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE without
  2078. ** a prior successful call to [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE].
  2079. **
  2080. ** <li>[[SQLITE_FCNTL_LOCK_TIMEOUT]]
  2081. ** The [SQLITE_FCNTL_LOCK_TIMEOUT] opcode causes attempts to obtain
  2082. ** a file lock using the xLock or xShmLock methods of the VFS to wait
  2083. ** for up to M milliseconds before failing, where M is the single
  2084. ** unsigned integer parameter.
  2085. **
  2086. ** <li>[[SQLITE_FCNTL_DATA_VERSION]]
  2087. ** The [SQLITE_FCNTL_DATA_VERSION] opcode is used to detect changes to
  2088. ** a database file. The argument is a pointer to a 32-bit unsigned integer.
  2089. ** The "data version" for the pager is written into the pointer. The
  2090. ** "data version" changes whenever any change occurs to the corresponding
  2091. ** database file, either through SQL statements on the same database
  2092. ** connection or through transactions committed by separate database
  2093. ** connections possibly in other processes. The [sqlite3_total_changes()]
  2094. ** interface can be used to find if any database on the connection has changed,
  2095. ** but that interface responds to changes on TEMP as well as MAIN and does
  2096. ** not provide a mechanism to detect changes to MAIN only. Also, the
  2097. ** [sqlite3_total_changes()] interface responds to internal changes only and
  2098. ** omits changes made by other database connections. The
  2099. ** [PRAGMA data_version] command provide a mechanism to detect changes to
  2100. ** a single attached database that occur due to other database connections,
  2101. ** but omits changes implemented by the database connection on which it is
  2102. ** called. This file control is the only mechanism to detect changes that
  2103. ** happen either internally or externally and that are associated with
  2104. ** a particular attached database.
  2105. ** </ul>
  2106. */
  2107. #define SQLITE_FCNTL_LOCKSTATE 1
  2108. #define SQLITE_FCNTL_GET_LOCKPROXYFILE 2
  2109. #define SQLITE_FCNTL_SET_LOCKPROXYFILE 3
  2110. #define SQLITE_FCNTL_LAST_ERRNO 4
  2111. #define SQLITE_FCNTL_SIZE_HINT 5
  2112. #define SQLITE_FCNTL_CHUNK_SIZE 6
  2113. #define SQLITE_FCNTL_FILE_POINTER 7
  2114. #define SQLITE_FCNTL_SYNC_OMITTED 8
  2115. #define SQLITE_FCNTL_WIN32_AV_RETRY 9
  2116. #define SQLITE_FCNTL_PERSIST_WAL 10
  2117. #define SQLITE_FCNTL_OVERWRITE 11
  2118. #define SQLITE_FCNTL_VFSNAME 12
  2119. #define SQLITE_FCNTL_POWERSAFE_OVERWRITE 13
  2120. #define SQLITE_FCNTL_PRAGMA 14
  2121. #define SQLITE_FCNTL_BUSYHANDLER 15
  2122. #define SQLITE_FCNTL_TEMPFILENAME 16
  2123. #define SQLITE_FCNTL_MMAP_SIZE 18
  2124. #define SQLITE_FCNTL_TRACE 19
  2125. #define SQLITE_FCNTL_HAS_MOVED 20
  2126. #define SQLITE_FCNTL_SYNC 21
  2127. #define SQLITE_FCNTL_COMMIT_PHASETWO 22
  2128. #define SQLITE_FCNTL_WIN32_SET_HANDLE 23
  2129. #define SQLITE_FCNTL_WAL_BLOCK 24
  2130. #define SQLITE_FCNTL_ZIPVFS 25
  2131. #define SQLITE_FCNTL_RBU 26
  2132. #define SQLITE_FCNTL_VFS_POINTER 27
  2133. #define SQLITE_FCNTL_JOURNAL_POINTER 28
  2134. #define SQLITE_FCNTL_WIN32_GET_HANDLE 29
  2135. #define SQLITE_FCNTL_PDB 30
  2136. #define SQLITE_FCNTL_BEGIN_ATOMIC_WRITE 31
  2137. #define SQLITE_FCNTL_COMMIT_ATOMIC_WRITE 32
  2138. #define SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE 33
  2139. #define SQLITE_FCNTL_LOCK_TIMEOUT 34
  2140. #define SQLITE_FCNTL_DATA_VERSION 35
  2141. #define SQLITE_FCNTL_SIZE_LIMIT 36
  2142. /* deprecated names */
  2143. #define SQLITE_GET_LOCKPROXYFILE SQLITE_FCNTL_GET_LOCKPROXYFILE
  2144. #define SQLITE_SET_LOCKPROXYFILE SQLITE_FCNTL_SET_LOCKPROXYFILE
  2145. #define SQLITE_LAST_ERRNO SQLITE_FCNTL_LAST_ERRNO
  2146. /*
  2147. ** CAPI3REF: Mutex Handle
  2148. **
  2149. ** The mutex module within SQLite defines [sqlite3_mutex] to be an
  2150. ** abstract type for a mutex object. The SQLite core never looks
  2151. ** at the internal representation of an [sqlite3_mutex]. It only
  2152. ** deals with pointers to the [sqlite3_mutex] object.
  2153. **
  2154. ** Mutexes are created using [sqlite3_mutex_alloc()].
  2155. */
  2156. typedef struct sqlite3_mutex sqlite3_mutex;
  2157. /*
  2158. ** CAPI3REF: Loadable Extension Thunk
  2159. **
  2160. ** A pointer to the opaque sqlite3_api_routines structure is passed as
  2161. ** the third parameter to entry points of [loadable extensions]. This
  2162. ** structure must be typedefed in order to work around compiler warnings
  2163. ** on some platforms.
  2164. */
  2165. typedef struct sqlite3_api_routines sqlite3_api_routines;
  2166. /*
  2167. ** CAPI3REF: OS Interface Object
  2168. **
  2169. ** An instance of the sqlite3_vfs object defines the interface between
  2170. ** the SQLite core and the underlying operating system. The "vfs"
  2171. ** in the name of the object stands for "virtual file system". See
  2172. ** the [VFS | VFS documentation] for further information.
  2173. **
  2174. ** The VFS interface is sometimes extended by adding new methods onto
  2175. ** the end. Each time such an extension occurs, the iVersion field
  2176. ** is incremented. The iVersion value started out as 1 in
  2177. ** SQLite [version 3.5.0] on [dateof:3.5.0], then increased to 2
  2178. ** with SQLite [version 3.7.0] on [dateof:3.7.0], and then increased
  2179. ** to 3 with SQLite [version 3.7.6] on [dateof:3.7.6]. Additional fields
  2180. ** may be appended to the sqlite3_vfs object and the iVersion value
  2181. ** may increase again in future versions of SQLite.
  2182. ** Note that the structure
  2183. ** of the sqlite3_vfs object changes in the transition from
  2184. ** SQLite [version 3.5.9] to [version 3.6.0] on [dateof:3.6.0]
  2185. ** and yet the iVersion field was not modified.
  2186. **
  2187. ** The szOsFile field is the size of the subclassed [sqlite3_file]
  2188. ** structure used by this VFS. mxPathname is the maximum length of
  2189. ** a pathname in this VFS.
  2190. **
  2191. ** Registered sqlite3_vfs objects are kept on a linked list formed by
  2192. ** the pNext pointer. The [sqlite3_vfs_register()]
  2193. ** and [sqlite3_vfs_unregister()] interfaces manage this list
  2194. ** in a thread-safe way. The [sqlite3_vfs_find()] interface
  2195. ** searches the list. Neither the application code nor the VFS
  2196. ** implementation should use the pNext pointer.
  2197. **
  2198. ** The pNext field is the only field in the sqlite3_vfs
  2199. ** structure that SQLite will ever modify. SQLite will only access
  2200. ** or modify this field while holding a particular static mutex.
  2201. ** The application should never modify anything within the sqlite3_vfs
  2202. ** object once the object has been registered.
  2203. **
  2204. ** The zName field holds the name of the VFS module. The name must
  2205. ** be unique across all VFS modules.
  2206. **
  2207. ** [[sqlite3_vfs.xOpen]]
  2208. ** ^SQLite guarantees that the zFilename parameter to xOpen
  2209. ** is either a NULL pointer or string obtained
  2210. ** from xFullPathname() with an optional suffix added.
  2211. ** ^If a suffix is added to the zFilename parameter, it will
  2212. ** consist of a single "-" character followed by no more than
  2213. ** 11 alphanumeric and/or "-" characters.
  2214. ** ^SQLite further guarantees that
  2215. ** the string will be valid and unchanged until xClose() is
  2216. ** called. Because of the previous sentence,
  2217. ** the [sqlite3_file] can safely store a pointer to the
  2218. ** filename if it needs to remember the filename for some reason.
  2219. ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
  2220. ** must invent its own temporary name for the file. ^Whenever the
  2221. ** xFilename parameter is NULL it will also be the case that the
  2222. ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
  2223. **
  2224. ** The flags argument to xOpen() includes all bits set in
  2225. ** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()]
  2226. ** or [sqlite3_open16()] is used, then flags includes at least
  2227. ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
  2228. ** If xOpen() opens a file read-only then it sets *pOutFlags to
  2229. ** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set.
  2230. **
  2231. ** ^(SQLite will also add one of the following flags to the xOpen()
  2232. ** call, depending on the object being opened:
  2233. **
  2234. ** <ul>
  2235. ** <li> [SQLITE_OPEN_MAIN_DB]
  2236. ** <li> [SQLITE_OPEN_MAIN_JOURNAL]
  2237. ** <li> [SQLITE_OPEN_TEMP_DB]
  2238. ** <li> [SQLITE_OPEN_TEMP_JOURNAL]
  2239. ** <li> [SQLITE_OPEN_TRANSIENT_DB]
  2240. ** <li> [SQLITE_OPEN_SUBJOURNAL]
  2241. ** <li> [SQLITE_OPEN_MASTER_JOURNAL]
  2242. ** <li> [SQLITE_OPEN_WAL]
  2243. ** </ul>)^
  2244. **
  2245. ** The file I/O implementation can use the object type flags to
  2246. ** change the way it deals with files. For example, an application
  2247. ** that does not care about crash recovery or rollback might make
  2248. ** the open of a journal file a no-op. Writes to this journal would
  2249. ** also be no-ops, and any attempt to read the journal would return
  2250. ** SQLITE_IOERR. Or the implementation might recognize that a database
  2251. ** file will be doing page-aligned sector reads and writes in a random
  2252. ** order and set up its I/O subsystem accordingly.
  2253. **
  2254. ** SQLite might also add one of the following flags to the xOpen method:
  2255. **
  2256. ** <ul>
  2257. ** <li> [SQLITE_OPEN_DELETEONCLOSE]
  2258. ** <li> [SQLITE_OPEN_EXCLUSIVE]
  2259. ** </ul>
  2260. **
  2261. ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
  2262. ** deleted when it is closed. ^The [SQLITE_OPEN_DELETEONCLOSE]
  2263. ** will be set for TEMP databases and their journals, transient
  2264. ** databases, and subjournals.
  2265. **
  2266. ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
  2267. ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
  2268. ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
  2269. ** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
  2270. ** SQLITE_OPEN_CREATE, is used to indicate that file should always
  2271. ** be created, and that it is an error if it already exists.
  2272. ** It is <i>not</i> used to indicate the file should be opened
  2273. ** for exclusive access.
  2274. **
  2275. ** ^At least szOsFile bytes of memory are allocated by SQLite
  2276. ** to hold the [sqlite3_file] structure passed as the third
  2277. ** argument to xOpen. The xOpen method does not have to
  2278. ** allocate the structure; it should just fill it in. Note that
  2279. ** the xOpen method must set the sqlite3_file.pMethods to either
  2280. ** a valid [sqlite3_io_methods] object or to NULL. xOpen must do
  2281. ** this even if the open fails. SQLite expects that the sqlite3_file.pMethods
  2282. ** element will be valid after xOpen returns regardless of the success
  2283. ** or failure of the xOpen call.
  2284. **
  2285. ** [[sqlite3_vfs.xAccess]]
  2286. ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
  2287. ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
  2288. ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
  2289. ** to test whether a file is at least readable. The SQLITE_ACCESS_READ
  2290. ** flag is never actually used and is not implemented in the built-in
  2291. ** VFSes of SQLite. The file is named by the second argument and can be a
  2292. ** directory. The xAccess method returns [SQLITE_OK] on success or some
  2293. ** non-zero error code if there is an I/O error or if the name of
  2294. ** the file given in the second argument is illegal. If SQLITE_OK
  2295. ** is returned, then non-zero or zero is written into *pResOut to indicate
  2296. ** whether or not the file is accessible.
  2297. **
  2298. ** ^SQLite will always allocate at least mxPathname+1 bytes for the
  2299. ** output buffer xFullPathname. The exact size of the output buffer
  2300. ** is also passed as a parameter to both methods. If the output buffer
  2301. ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
  2302. ** handled as a fatal error by SQLite, vfs implementations should endeavor
  2303. ** to prevent this by setting mxPathname to a sufficiently large value.
  2304. **
  2305. ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
  2306. ** interfaces are not strictly a part of the filesystem, but they are
  2307. ** included in the VFS structure for completeness.
  2308. ** The xRandomness() function attempts to return nBytes bytes
  2309. ** of good-quality randomness into zOut. The return value is
  2310. ** the actual number of bytes of randomness obtained.
  2311. ** The xSleep() method causes the calling thread to sleep for at
  2312. ** least the number of microseconds given. ^The xCurrentTime()
  2313. ** method returns a Julian Day Number for the current date and time as
  2314. ** a floating point value.
  2315. ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
  2316. ** Day Number multiplied by 86400000 (the number of milliseconds in
  2317. ** a 24-hour day).
  2318. ** ^SQLite will use the xCurrentTimeInt64() method to get the current
  2319. ** date and time if that method is available (if iVersion is 2 or
  2320. ** greater and the function pointer is not NULL) and will fall back
  2321. ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
  2322. **
  2323. ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
  2324. ** are not used by the SQLite core. These optional interfaces are provided
  2325. ** by some VFSes to facilitate testing of the VFS code. By overriding
  2326. ** system calls with functions under its control, a test program can
  2327. ** simulate faults and error conditions that would otherwise be difficult
  2328. ** or impossible to induce. The set of system calls that can be overridden
  2329. ** varies from one VFS to another, and from one version of the same VFS to the
  2330. ** next. Applications that use these interfaces must be prepared for any
  2331. ** or all of these interfaces to be NULL or for their behavior to change
  2332. ** from one release to the next. Applications must not attempt to access
  2333. ** any of these methods if the iVersion of the VFS is less than 3.
  2334. */
  2335. typedef struct sqlite3_vfs sqlite3_vfs;
  2336. typedef void (*sqlite3_syscall_ptr)(void);
  2337. struct sqlite3_vfs {
  2338. int iVersion; /* Structure version number (currently 3) */
  2339. int szOsFile; /* Size of subclassed sqlite3_file */
  2340. int mxPathname; /* Maximum file pathname length */
  2341. sqlite3_vfs *pNext; /* Next registered VFS */
  2342. const char *zName; /* Name of this virtual file system */
  2343. void *pAppData; /* Pointer to application-specific data */
  2344. int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
  2345. int flags, int *pOutFlags);
  2346. int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
  2347. int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
  2348. int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
  2349. void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
  2350. void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
  2351. void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
  2352. void (*xDlClose)(sqlite3_vfs*, void*);
  2353. int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
  2354. int (*xSleep)(sqlite3_vfs*, int microseconds);
  2355. int (*xCurrentTime)(sqlite3_vfs*, double*);
  2356. int (*xGetLastError)(sqlite3_vfs*, int, char *);
  2357. /*
  2358. ** The methods above are in version 1 of the sqlite_vfs object
  2359. ** definition. Those that follow are added in version 2 or later
  2360. */
  2361. int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
  2362. /*
  2363. ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
  2364. ** Those below are for version 3 and greater.
  2365. */
  2366. int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
  2367. sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
  2368. const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
  2369. /*
  2370. ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
  2371. ** New fields may be appended in future versions. The iVersion
  2372. ** value will increment whenever this happens.
  2373. */
  2374. };
  2375. /*
  2376. ** CAPI3REF: Flags for the xAccess VFS method
  2377. **
  2378. ** These integer constants can be used as the third parameter to
  2379. ** the xAccess method of an [sqlite3_vfs] object. They determine
  2380. ** what kind of permissions the xAccess method is looking for.
  2381. ** With SQLITE_ACCESS_EXISTS, the xAccess method
  2382. ** simply checks whether the file exists.
  2383. ** With SQLITE_ACCESS_READWRITE, the xAccess method
  2384. ** checks whether the named directory is both readable and writable
  2385. ** (in other words, if files can be added, removed, and renamed within
  2386. ** the directory).
  2387. ** The SQLITE_ACCESS_READWRITE constant is currently used only by the
  2388. ** [temp_store_directory pragma], though this could change in a future
  2389. ** release of SQLite.
  2390. ** With SQLITE_ACCESS_READ, the xAccess method
  2391. ** checks whether the file is readable. The SQLITE_ACCESS_READ constant is
  2392. ** currently unused, though it might be used in a future release of
  2393. ** SQLite.
  2394. */
  2395. #define SQLITE_ACCESS_EXISTS 0
  2396. #define SQLITE_ACCESS_READWRITE 1 /* Used by PRAGMA temp_store_directory */
  2397. #define SQLITE_ACCESS_READ 2 /* Unused */
  2398. /*
  2399. ** CAPI3REF: Flags for the xShmLock VFS method
  2400. **
  2401. ** These integer constants define the various locking operations
  2402. ** allowed by the xShmLock method of [sqlite3_io_methods]. The
  2403. ** following are the only legal combinations of flags to the
  2404. ** xShmLock method:
  2405. **
  2406. ** <ul>
  2407. ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
  2408. ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
  2409. ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
  2410. ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
  2411. ** </ul>
  2412. **
  2413. ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
  2414. ** was given on the corresponding lock.
  2415. **
  2416. ** The xShmLock method can transition between unlocked and SHARED or
  2417. ** between unlocked and EXCLUSIVE. It cannot transition between SHARED
  2418. ** and EXCLUSIVE.
  2419. */
  2420. #define SQLITE_SHM_UNLOCK 1
  2421. #define SQLITE_SHM_LOCK 2
  2422. #define SQLITE_SHM_SHARED 4
  2423. #define SQLITE_SHM_EXCLUSIVE 8
  2424. /*
  2425. ** CAPI3REF: Maximum xShmLock index
  2426. **
  2427. ** The xShmLock method on [sqlite3_io_methods] may use values
  2428. ** between 0 and this upper bound as its "offset" argument.
  2429. ** The SQLite core will never attempt to acquire or release a
  2430. ** lock outside of this range
  2431. */
  2432. #define SQLITE_SHM_NLOCK 8
  2433. /*
  2434. ** CAPI3REF: Initialize The SQLite Library
  2435. **
  2436. ** ^The sqlite3_initialize() routine initializes the
  2437. ** SQLite library. ^The sqlite3_shutdown() routine
  2438. ** deallocates any resources that were allocated by sqlite3_initialize().
  2439. ** These routines are designed to aid in process initialization and
  2440. ** shutdown on embedded systems. Workstation applications using
  2441. ** SQLite normally do not need to invoke either of these routines.
  2442. **
  2443. ** A call to sqlite3_initialize() is an "effective" call if it is
  2444. ** the first time sqlite3_initialize() is invoked during the lifetime of
  2445. ** the process, or if it is the first time sqlite3_initialize() is invoked
  2446. ** following a call to sqlite3_shutdown(). ^(Only an effective call
  2447. ** of sqlite3_initialize() does any initialization. All other calls
  2448. ** are harmless no-ops.)^
  2449. **
  2450. ** A call to sqlite3_shutdown() is an "effective" call if it is the first
  2451. ** call to sqlite3_shutdown() since the last sqlite3_initialize(). ^(Only
  2452. ** an effective call to sqlite3_shutdown() does any deinitialization.
  2453. ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
  2454. **
  2455. ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
  2456. ** is not. The sqlite3_shutdown() interface must only be called from a
  2457. ** single thread. All open [database connections] must be closed and all
  2458. ** other SQLite resources must be deallocated prior to invoking
  2459. ** sqlite3_shutdown().
  2460. **
  2461. ** Among other things, ^sqlite3_initialize() will invoke
  2462. ** sqlite3_os_init(). Similarly, ^sqlite3_shutdown()
  2463. ** will invoke sqlite3_os_end().
  2464. **
  2465. ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
  2466. ** ^If for some reason, sqlite3_initialize() is unable to initialize
  2467. ** the library (perhaps it is unable to allocate a needed resource such
  2468. ** as a mutex) it returns an [error code] other than [SQLITE_OK].
  2469. **
  2470. ** ^The sqlite3_initialize() routine is called internally by many other
  2471. ** SQLite interfaces so that an application usually does not need to
  2472. ** invoke sqlite3_initialize() directly. For example, [sqlite3_open()]
  2473. ** calls sqlite3_initialize() so the SQLite library will be automatically
  2474. ** initialized when [sqlite3_open()] is called if it has not be initialized
  2475. ** already. ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
  2476. ** compile-time option, then the automatic calls to sqlite3_initialize()
  2477. ** are omitted and the application must call sqlite3_initialize() directly
  2478. ** prior to using any other SQLite interface. For maximum portability,
  2479. ** it is recommended that applications always invoke sqlite3_initialize()
  2480. ** directly prior to using any other SQLite interface. Future releases
  2481. ** of SQLite may require this. In other words, the behavior exhibited
  2482. ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
  2483. ** default behavior in some future release of SQLite.
  2484. **
  2485. ** The sqlite3_os_init() routine does operating-system specific
  2486. ** initialization of the SQLite library. The sqlite3_os_end()
  2487. ** routine undoes the effect of sqlite3_os_init(). Typical tasks
  2488. ** performed by these routines include allocation or deallocation
  2489. ** of static resources, initialization of global variables,
  2490. ** setting up a default [sqlite3_vfs] module, or setting up
  2491. ** a default configuration using [sqlite3_config()].
  2492. **
  2493. ** The application should never invoke either sqlite3_os_init()
  2494. ** or sqlite3_os_end() directly. The application should only invoke
  2495. ** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init()
  2496. ** interface is called automatically by sqlite3_initialize() and
  2497. ** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate
  2498. ** implementations for sqlite3_os_init() and sqlite3_os_end()
  2499. ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
  2500. ** When [custom builds | built for other platforms]
  2501. ** (using the [SQLITE_OS_OTHER=1] compile-time
  2502. ** option) the application must supply a suitable implementation for
  2503. ** sqlite3_os_init() and sqlite3_os_end(). An application-supplied
  2504. ** implementation of sqlite3_os_init() or sqlite3_os_end()
  2505. ** must return [SQLITE_OK] on success and some other [error code] upon
  2506. ** failure.
  2507. */
  2508. SQLITE_API int sqlite3_initialize(void);
  2509. SQLITE_API int sqlite3_shutdown(void);
  2510. SQLITE_API int sqlite3_os_init(void);
  2511. SQLITE_API int sqlite3_os_end(void);
  2512. /*
  2513. ** CAPI3REF: Configuring The SQLite Library
  2514. **
  2515. ** The sqlite3_config() interface is used to make global configuration
  2516. ** changes to SQLite in order to tune SQLite to the specific needs of
  2517. ** the application. The default configuration is recommended for most
  2518. ** applications and so this routine is usually not necessary. It is
  2519. ** provided to support rare applications with unusual needs.
  2520. **
  2521. ** <b>The sqlite3_config() interface is not threadsafe. The application
  2522. ** must ensure that no other SQLite interfaces are invoked by other
  2523. ** threads while sqlite3_config() is running.</b>
  2524. **
  2525. ** The sqlite3_config() interface
  2526. ** may only be invoked prior to library initialization using
  2527. ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
  2528. ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
  2529. ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
  2530. ** Note, however, that ^sqlite3_config() can be called as part of the
  2531. ** implementation of an application-defined [sqlite3_os_init()].
  2532. **
  2533. ** The first argument to sqlite3_config() is an integer
  2534. ** [configuration option] that determines
  2535. ** what property of SQLite is to be configured. Subsequent arguments
  2536. ** vary depending on the [configuration option]
  2537. ** in the first argument.
  2538. **
  2539. ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
  2540. ** ^If the option is unknown or SQLite is unable to set the option
  2541. ** then this routine returns a non-zero [error code].
  2542. */
  2543. SQLITE_API int sqlite3_config(int, ...);
  2544. /*
  2545. ** CAPI3REF: Configure database connections
  2546. ** METHOD: sqlite3
  2547. **
  2548. ** The sqlite3_db_config() interface is used to make configuration
  2549. ** changes to a [database connection]. The interface is similar to
  2550. ** [sqlite3_config()] except that the changes apply to a single
  2551. ** [database connection] (specified in the first argument).
  2552. **
  2553. ** The second argument to sqlite3_db_config(D,V,...) is the
  2554. ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code
  2555. ** that indicates what aspect of the [database connection] is being configured.
  2556. ** Subsequent arguments vary depending on the configuration verb.
  2557. **
  2558. ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
  2559. ** the call is considered successful.
  2560. */
  2561. SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
  2562. /*
  2563. ** CAPI3REF: Memory Allocation Routines
  2564. **
  2565. ** An instance of this object defines the interface between SQLite
  2566. ** and low-level memory allocation routines.
  2567. **
  2568. ** This object is used in only one place in the SQLite interface.
  2569. ** A pointer to an instance of this object is the argument to
  2570. ** [sqlite3_config()] when the configuration option is
  2571. ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
  2572. ** By creating an instance of this object
  2573. ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
  2574. ** during configuration, an application can specify an alternative
  2575. ** memory allocation subsystem for SQLite to use for all of its
  2576. ** dynamic memory needs.
  2577. **
  2578. ** Note that SQLite comes with several [built-in memory allocators]
  2579. ** that are perfectly adequate for the overwhelming majority of applications
  2580. ** and that this object is only useful to a tiny minority of applications
  2581. ** with specialized memory allocation requirements. This object is
  2582. ** also used during testing of SQLite in order to specify an alternative
  2583. ** memory allocator that simulates memory out-of-memory conditions in
  2584. ** order to verify that SQLite recovers gracefully from such
  2585. ** conditions.
  2586. **
  2587. ** The xMalloc, xRealloc, and xFree methods must work like the
  2588. ** malloc(), realloc() and free() functions from the standard C library.
  2589. ** ^SQLite guarantees that the second argument to
  2590. ** xRealloc is always a value returned by a prior call to xRoundup.
  2591. **
  2592. ** xSize should return the allocated size of a memory allocation
  2593. ** previously obtained from xMalloc or xRealloc. The allocated size
  2594. ** is always at least as big as the requested size but may be larger.
  2595. **
  2596. ** The xRoundup method returns what would be the allocated size of
  2597. ** a memory allocation given a particular requested size. Most memory
  2598. ** allocators round up memory allocations at least to the next multiple
  2599. ** of 8. Some allocators round up to a larger multiple or to a power of 2.
  2600. ** Every memory allocation request coming in through [sqlite3_malloc()]
  2601. ** or [sqlite3_realloc()] first calls xRoundup. If xRoundup returns 0,
  2602. ** that causes the corresponding memory allocation to fail.
  2603. **
  2604. ** The xInit method initializes the memory allocator. For example,
  2605. ** it might allocate any require mutexes or initialize internal data
  2606. ** structures. The xShutdown method is invoked (indirectly) by
  2607. ** [sqlite3_shutdown()] and should deallocate any resources acquired
  2608. ** by xInit. The pAppData pointer is used as the only parameter to
  2609. ** xInit and xShutdown.
  2610. **
  2611. ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
  2612. ** the xInit method, so the xInit method need not be threadsafe. The
  2613. ** xShutdown method is only called from [sqlite3_shutdown()] so it does
  2614. ** not need to be threadsafe either. For all other methods, SQLite
  2615. ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
  2616. ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
  2617. ** it is by default) and so the methods are automatically serialized.
  2618. ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
  2619. ** methods must be threadsafe or else make their own arrangements for
  2620. ** serialization.
  2621. **
  2622. ** SQLite will never invoke xInit() more than once without an intervening
  2623. ** call to xShutdown().
  2624. */
  2625. typedef struct sqlite3_mem_methods sqlite3_mem_methods;
  2626. struct sqlite3_mem_methods {
  2627. void *(*xMalloc)(int); /* Memory allocation function */
  2628. void (*xFree)(void*); /* Free a prior allocation */
  2629. void *(*xRealloc)(void*,int); /* Resize an allocation */
  2630. int (*xSize)(void*); /* Return the size of an allocation */
  2631. int (*xRoundup)(int); /* Round up request size to allocation size */
  2632. int (*xInit)(void*); /* Initialize the memory allocator */
  2633. void (*xShutdown)(void*); /* Deinitialize the memory allocator */
  2634. void *pAppData; /* Argument to xInit() and xShutdown() */
  2635. };
  2636. /*
  2637. ** CAPI3REF: Configuration Options
  2638. ** KEYWORDS: {configuration option}
  2639. **
  2640. ** These constants are the available integer configuration options that
  2641. ** can be passed as the first argument to the [sqlite3_config()] interface.
  2642. **
  2643. ** New configuration options may be added in future releases of SQLite.
  2644. ** Existing configuration options might be discontinued. Applications
  2645. ** should check the return code from [sqlite3_config()] to make sure that
  2646. ** the call worked. The [sqlite3_config()] interface will return a
  2647. ** non-zero [error code] if a discontinued or unsupported configuration option
  2648. ** is invoked.
  2649. **
  2650. ** <dl>
  2651. ** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
  2652. ** <dd>There are no arguments to this option. ^This option sets the
  2653. ** [threading mode] to Single-thread. In other words, it disables
  2654. ** all mutexing and puts SQLite into a mode where it can only be used
  2655. ** by a single thread. ^If SQLite is compiled with
  2656. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  2657. ** it is not possible to change the [threading mode] from its default
  2658. ** value of Single-thread and so [sqlite3_config()] will return
  2659. ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
  2660. ** configuration option.</dd>
  2661. **
  2662. ** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
  2663. ** <dd>There are no arguments to this option. ^This option sets the
  2664. ** [threading mode] to Multi-thread. In other words, it disables
  2665. ** mutexing on [database connection] and [prepared statement] objects.
  2666. ** The application is responsible for serializing access to
  2667. ** [database connections] and [prepared statements]. But other mutexes
  2668. ** are enabled so that SQLite will be safe to use in a multi-threaded
  2669. ** environment as long as no two threads attempt to use the same
  2670. ** [database connection] at the same time. ^If SQLite is compiled with
  2671. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  2672. ** it is not possible to set the Multi-thread [threading mode] and
  2673. ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
  2674. ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
  2675. **
  2676. ** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
  2677. ** <dd>There are no arguments to this option. ^This option sets the
  2678. ** [threading mode] to Serialized. In other words, this option enables
  2679. ** all mutexes including the recursive
  2680. ** mutexes on [database connection] and [prepared statement] objects.
  2681. ** In this mode (which is the default when SQLite is compiled with
  2682. ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
  2683. ** to [database connections] and [prepared statements] so that the
  2684. ** application is free to use the same [database connection] or the
  2685. ** same [prepared statement] in different threads at the same time.
  2686. ** ^If SQLite is compiled with
  2687. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  2688. ** it is not possible to set the Serialized [threading mode] and
  2689. ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
  2690. ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
  2691. **
  2692. ** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
  2693. ** <dd> ^(The SQLITE_CONFIG_MALLOC option takes a single argument which is
  2694. ** a pointer to an instance of the [sqlite3_mem_methods] structure.
  2695. ** The argument specifies
  2696. ** alternative low-level memory allocation routines to be used in place of
  2697. ** the memory allocation routines built into SQLite.)^ ^SQLite makes
  2698. ** its own private copy of the content of the [sqlite3_mem_methods] structure
  2699. ** before the [sqlite3_config()] call returns.</dd>
  2700. **
  2701. ** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
  2702. ** <dd> ^(The SQLITE_CONFIG_GETMALLOC option takes a single argument which
  2703. ** is a pointer to an instance of the [sqlite3_mem_methods] structure.
  2704. ** The [sqlite3_mem_methods]
  2705. ** structure is filled with the currently defined memory allocation routines.)^
  2706. ** This option can be used to overload the default memory allocation
  2707. ** routines with a wrapper that simulations memory allocation failure or
  2708. ** tracks memory usage, for example. </dd>
  2709. **
  2710. ** [[SQLITE_CONFIG_SMALL_MALLOC]] <dt>SQLITE_CONFIG_SMALL_MALLOC</dt>
  2711. ** <dd> ^The SQLITE_CONFIG_SMALL_MALLOC option takes single argument of
  2712. ** type int, interpreted as a boolean, which if true provides a hint to
  2713. ** SQLite that it should avoid large memory allocations if possible.
  2714. ** SQLite will run faster if it is free to make large memory allocations,
  2715. ** but some application might prefer to run slower in exchange for
  2716. ** guarantees about memory fragmentation that are possible if large
  2717. ** allocations are avoided. This hint is normally off.
  2718. ** </dd>
  2719. **
  2720. ** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
  2721. ** <dd> ^The SQLITE_CONFIG_MEMSTATUS option takes single argument of type int,
  2722. ** interpreted as a boolean, which enables or disables the collection of
  2723. ** memory allocation statistics. ^(When memory allocation statistics are
  2724. ** disabled, the following SQLite interfaces become non-operational:
  2725. ** <ul>
  2726. ** <li> [sqlite3_memory_used()]
  2727. ** <li> [sqlite3_memory_highwater()]
  2728. ** <li> [sqlite3_soft_heap_limit64()]
  2729. ** <li> [sqlite3_status64()]
  2730. ** </ul>)^
  2731. ** ^Memory allocation statistics are enabled by default unless SQLite is
  2732. ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
  2733. ** allocation statistics are disabled by default.
  2734. ** </dd>
  2735. **
  2736. ** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
  2737. ** <dd> The SQLITE_CONFIG_SCRATCH option is no longer used.
  2738. ** </dd>
  2739. **
  2740. ** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
  2741. ** <dd> ^The SQLITE_CONFIG_PAGECACHE option specifies a memory pool
  2742. ** that SQLite can use for the database page cache with the default page
  2743. ** cache implementation.
  2744. ** This configuration option is a no-op if an application-define page
  2745. ** cache implementation is loaded using the [SQLITE_CONFIG_PCACHE2].
  2746. ** ^There are three arguments to SQLITE_CONFIG_PAGECACHE: A pointer to
  2747. ** 8-byte aligned memory (pMem), the size of each page cache line (sz),
  2748. ** and the number of cache lines (N).
  2749. ** The sz argument should be the size of the largest database page
  2750. ** (a power of two between 512 and 65536) plus some extra bytes for each
  2751. ** page header. ^The number of extra bytes needed by the page header
  2752. ** can be determined using [SQLITE_CONFIG_PCACHE_HDRSZ].
  2753. ** ^It is harmless, apart from the wasted memory,
  2754. ** for the sz parameter to be larger than necessary. The pMem
  2755. ** argument must be either a NULL pointer or a pointer to an 8-byte
  2756. ** aligned block of memory of at least sz*N bytes, otherwise
  2757. ** subsequent behavior is undefined.
  2758. ** ^When pMem is not NULL, SQLite will strive to use the memory provided
  2759. ** to satisfy page cache needs, falling back to [sqlite3_malloc()] if
  2760. ** a page cache line is larger than sz bytes or if all of the pMem buffer
  2761. ** is exhausted.
  2762. ** ^If pMem is NULL and N is non-zero, then each database connection
  2763. ** does an initial bulk allocation for page cache memory
  2764. ** from [sqlite3_malloc()] sufficient for N cache lines if N is positive or
  2765. ** of -1024*N bytes if N is negative, . ^If additional
  2766. ** page cache memory is needed beyond what is provided by the initial
  2767. ** allocation, then SQLite goes to [sqlite3_malloc()] separately for each
  2768. ** additional cache line. </dd>
  2769. **
  2770. ** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
  2771. ** <dd> ^The SQLITE_CONFIG_HEAP option specifies a static memory buffer
  2772. ** that SQLite will use for all of its dynamic memory allocation needs
  2773. ** beyond those provided for by [SQLITE_CONFIG_PAGECACHE].
  2774. ** ^The SQLITE_CONFIG_HEAP option is only available if SQLite is compiled
  2775. ** with either [SQLITE_ENABLE_MEMSYS3] or [SQLITE_ENABLE_MEMSYS5] and returns
  2776. ** [SQLITE_ERROR] if invoked otherwise.
  2777. ** ^There are three arguments to SQLITE_CONFIG_HEAP:
  2778. ** An 8-byte aligned pointer to the memory,
  2779. ** the number of bytes in the memory buffer, and the minimum allocation size.
  2780. ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
  2781. ** to using its default memory allocator (the system malloc() implementation),
  2782. ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. ^If the
  2783. ** memory pointer is not NULL then the alternative memory
  2784. ** allocator is engaged to handle all of SQLites memory allocation needs.
  2785. ** The first pointer (the memory pointer) must be aligned to an 8-byte
  2786. ** boundary or subsequent behavior of SQLite will be undefined.
  2787. ** The minimum allocation size is capped at 2**12. Reasonable values
  2788. ** for the minimum allocation size are 2**5 through 2**8.</dd>
  2789. **
  2790. ** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
  2791. ** <dd> ^(The SQLITE_CONFIG_MUTEX option takes a single argument which is a
  2792. ** pointer to an instance of the [sqlite3_mutex_methods] structure.
  2793. ** The argument specifies alternative low-level mutex routines to be used
  2794. ** in place the mutex routines built into SQLite.)^ ^SQLite makes a copy of
  2795. ** the content of the [sqlite3_mutex_methods] structure before the call to
  2796. ** [sqlite3_config()] returns. ^If SQLite is compiled with
  2797. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  2798. ** the entire mutexing subsystem is omitted from the build and hence calls to
  2799. ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
  2800. ** return [SQLITE_ERROR].</dd>
  2801. **
  2802. ** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
  2803. ** <dd> ^(The SQLITE_CONFIG_GETMUTEX option takes a single argument which
  2804. ** is a pointer to an instance of the [sqlite3_mutex_methods] structure. The
  2805. ** [sqlite3_mutex_methods]
  2806. ** structure is filled with the currently defined mutex routines.)^
  2807. ** This option can be used to overload the default mutex allocation
  2808. ** routines with a wrapper used to track mutex usage for performance
  2809. ** profiling or testing, for example. ^If SQLite is compiled with
  2810. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  2811. ** the entire mutexing subsystem is omitted from the build and hence calls to
  2812. ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
  2813. ** return [SQLITE_ERROR].</dd>
  2814. **
  2815. ** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
  2816. ** <dd> ^(The SQLITE_CONFIG_LOOKASIDE option takes two arguments that determine
  2817. ** the default size of lookaside memory on each [database connection].
  2818. ** The first argument is the
  2819. ** size of each lookaside buffer slot and the second is the number of
  2820. ** slots allocated to each database connection.)^ ^(SQLITE_CONFIG_LOOKASIDE
  2821. ** sets the <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
  2822. ** option to [sqlite3_db_config()] can be used to change the lookaside
  2823. ** configuration on individual connections.)^ </dd>
  2824. **
  2825. ** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
  2826. ** <dd> ^(The SQLITE_CONFIG_PCACHE2 option takes a single argument which is
  2827. ** a pointer to an [sqlite3_pcache_methods2] object. This object specifies
  2828. ** the interface to a custom page cache implementation.)^
  2829. ** ^SQLite makes a copy of the [sqlite3_pcache_methods2] object.</dd>
  2830. **
  2831. ** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
  2832. ** <dd> ^(The SQLITE_CONFIG_GETPCACHE2 option takes a single argument which
  2833. ** is a pointer to an [sqlite3_pcache_methods2] object. SQLite copies of
  2834. ** the current page cache implementation into that object.)^ </dd>
  2835. **
  2836. ** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
  2837. ** <dd> The SQLITE_CONFIG_LOG option is used to configure the SQLite
  2838. ** global [error log].
  2839. ** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
  2840. ** function with a call signature of void(*)(void*,int,const char*),
  2841. ** and a pointer to void. ^If the function pointer is not NULL, it is
  2842. ** invoked by [sqlite3_log()] to process each logging event. ^If the
  2843. ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
  2844. ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
  2845. ** passed through as the first parameter to the application-defined logger
  2846. ** function whenever that function is invoked. ^The second parameter to
  2847. ** the logger function is a copy of the first parameter to the corresponding
  2848. ** [sqlite3_log()] call and is intended to be a [result code] or an
  2849. ** [extended result code]. ^The third parameter passed to the logger is
  2850. ** log message after formatting via [sqlite3_snprintf()].
  2851. ** The SQLite logging interface is not reentrant; the logger function
  2852. ** supplied by the application must not invoke any SQLite interface.
  2853. ** In a multi-threaded application, the application-defined logger
  2854. ** function must be threadsafe. </dd>
  2855. **
  2856. ** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
  2857. ** <dd>^(The SQLITE_CONFIG_URI option takes a single argument of type int.
  2858. ** If non-zero, then URI handling is globally enabled. If the parameter is zero,
  2859. ** then URI handling is globally disabled.)^ ^If URI handling is globally
  2860. ** enabled, all filenames passed to [sqlite3_open()], [sqlite3_open_v2()],
  2861. ** [sqlite3_open16()] or
  2862. ** specified as part of [ATTACH] commands are interpreted as URIs, regardless
  2863. ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
  2864. ** connection is opened. ^If it is globally disabled, filenames are
  2865. ** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
  2866. ** database connection is opened. ^(By default, URI handling is globally
  2867. ** disabled. The default value may be changed by compiling with the
  2868. ** [SQLITE_USE_URI] symbol defined.)^
  2869. **
  2870. ** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN
  2871. ** <dd>^The SQLITE_CONFIG_COVERING_INDEX_SCAN option takes a single integer
  2872. ** argument which is interpreted as a boolean in order to enable or disable
  2873. ** the use of covering indices for full table scans in the query optimizer.
  2874. ** ^The default setting is determined
  2875. ** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"
  2876. ** if that compile-time option is omitted.
  2877. ** The ability to disable the use of covering indices for full table scans
  2878. ** is because some incorrectly coded legacy applications might malfunction
  2879. ** when the optimization is enabled. Providing the ability to
  2880. ** disable the optimization allows the older, buggy application code to work
  2881. ** without change even with newer versions of SQLite.
  2882. **
  2883. ** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
  2884. ** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE
  2885. ** <dd> These options are obsolete and should not be used by new code.
  2886. ** They are retained for backwards compatibility but are now no-ops.
  2887. ** </dd>
  2888. **
  2889. ** [[SQLITE_CONFIG_SQLLOG]]
  2890. ** <dt>SQLITE_CONFIG_SQLLOG
  2891. ** <dd>This option is only available if sqlite is compiled with the
  2892. ** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should
  2893. ** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int).
  2894. ** The second should be of type (void*). The callback is invoked by the library
  2895. ** in three separate circumstances, identified by the value passed as the
  2896. ** fourth parameter. If the fourth parameter is 0, then the database connection
  2897. ** passed as the second argument has just been opened. The third argument
  2898. ** points to a buffer containing the name of the main database file. If the
  2899. ** fourth parameter is 1, then the SQL statement that the third parameter
  2900. ** points to has just been executed. Or, if the fourth parameter is 2, then
  2901. ** the connection being passed as the second parameter is being closed. The
  2902. ** third parameter is passed NULL In this case. An example of using this
  2903. ** configuration option can be seen in the "test_sqllog.c" source file in
  2904. ** the canonical SQLite source tree.</dd>
  2905. **
  2906. ** [[SQLITE_CONFIG_MMAP_SIZE]]
  2907. ** <dt>SQLITE_CONFIG_MMAP_SIZE
  2908. ** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values
  2909. ** that are the default mmap size limit (the default setting for
  2910. ** [PRAGMA mmap_size]) and the maximum allowed mmap size limit.
  2911. ** ^The default setting can be overridden by each database connection using
  2912. ** either the [PRAGMA mmap_size] command, or by using the
  2913. ** [SQLITE_FCNTL_MMAP_SIZE] file control. ^(The maximum allowed mmap size
  2914. ** will be silently truncated if necessary so that it does not exceed the
  2915. ** compile-time maximum mmap size set by the
  2916. ** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^
  2917. ** ^If either argument to this option is negative, then that argument is
  2918. ** changed to its compile-time default.
  2919. **
  2920. ** [[SQLITE_CONFIG_WIN32_HEAPSIZE]]
  2921. ** <dt>SQLITE_CONFIG_WIN32_HEAPSIZE
  2922. ** <dd>^The SQLITE_CONFIG_WIN32_HEAPSIZE option is only available if SQLite is
  2923. ** compiled for Windows with the [SQLITE_WIN32_MALLOC] pre-processor macro
  2924. ** defined. ^SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit unsigned integer value
  2925. ** that specifies the maximum size of the created heap.
  2926. **
  2927. ** [[SQLITE_CONFIG_PCACHE_HDRSZ]]
  2928. ** <dt>SQLITE_CONFIG_PCACHE_HDRSZ
  2929. ** <dd>^The SQLITE_CONFIG_PCACHE_HDRSZ option takes a single parameter which
  2930. ** is a pointer to an integer and writes into that integer the number of extra
  2931. ** bytes per page required for each page in [SQLITE_CONFIG_PAGECACHE].
  2932. ** The amount of extra space required can change depending on the compiler,
  2933. ** target platform, and SQLite version.
  2934. **
  2935. ** [[SQLITE_CONFIG_PMASZ]]
  2936. ** <dt>SQLITE_CONFIG_PMASZ
  2937. ** <dd>^The SQLITE_CONFIG_PMASZ option takes a single parameter which
  2938. ** is an unsigned integer and sets the "Minimum PMA Size" for the multithreaded
  2939. ** sorter to that integer. The default minimum PMA Size is set by the
  2940. ** [SQLITE_SORTER_PMASZ] compile-time option. New threads are launched
  2941. ** to help with sort operations when multithreaded sorting
  2942. ** is enabled (using the [PRAGMA threads] command) and the amount of content
  2943. ** to be sorted exceeds the page size times the minimum of the
  2944. ** [PRAGMA cache_size] setting and this value.
  2945. **
  2946. ** [[SQLITE_CONFIG_STMTJRNL_SPILL]]
  2947. ** <dt>SQLITE_CONFIG_STMTJRNL_SPILL
  2948. ** <dd>^The SQLITE_CONFIG_STMTJRNL_SPILL option takes a single parameter which
  2949. ** becomes the [statement journal] spill-to-disk threshold.
  2950. ** [Statement journals] are held in memory until their size (in bytes)
  2951. ** exceeds this threshold, at which point they are written to disk.
  2952. ** Or if the threshold is -1, statement journals are always held
  2953. ** exclusively in memory.
  2954. ** Since many statement journals never become large, setting the spill
  2955. ** threshold to a value such as 64KiB can greatly reduce the amount of
  2956. ** I/O required to support statement rollback.
  2957. ** The default value for this setting is controlled by the
  2958. ** [SQLITE_STMTJRNL_SPILL] compile-time option.
  2959. **
  2960. ** [[SQLITE_CONFIG_SORTERREF_SIZE]]
  2961. ** <dt>SQLITE_CONFIG_SORTERREF_SIZE
  2962. ** <dd>The SQLITE_CONFIG_SORTERREF_SIZE option accepts a single parameter
  2963. ** of type (int) - the new value of the sorter-reference size threshold.
  2964. ** Usually, when SQLite uses an external sort to order records according
  2965. ** to an ORDER BY clause, all fields required by the caller are present in the
  2966. ** sorted records. However, if SQLite determines based on the declared type
  2967. ** of a table column that its values are likely to be very large - larger
  2968. ** than the configured sorter-reference size threshold - then a reference
  2969. ** is stored in each sorted record and the required column values loaded
  2970. ** from the database as records are returned in sorted order. The default
  2971. ** value for this option is to never use this optimization. Specifying a
  2972. ** negative value for this option restores the default behaviour.
  2973. ** This option is only available if SQLite is compiled with the
  2974. ** [SQLITE_ENABLE_SORTER_REFERENCES] compile-time option.
  2975. **
  2976. ** [[SQLITE_CONFIG_MEMDB_MAXSIZE]]
  2977. ** <dt>SQLITE_CONFIG_MEMDB_MAXSIZE
  2978. ** <dd>The SQLITE_CONFIG_MEMDB_MAXSIZE option accepts a single parameter
  2979. ** [sqlite3_int64] parameter which is the default maximum size for an in-memory
  2980. ** database created using [sqlite3_deserialize()]. This default maximum
  2981. ** size can be adjusted up or down for individual databases using the
  2982. ** [SQLITE_FCNTL_SIZE_LIMIT] [sqlite3_file_control|file-control]. If this
  2983. ** configuration setting is never used, then the default maximum is determined
  2984. ** by the [SQLITE_MEMDB_DEFAULT_MAXSIZE] compile-time option. If that
  2985. ** compile-time option is not set, then the default maximum is 1073741824.
  2986. ** </dl>
  2987. */
  2988. #define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */
  2989. #define SQLITE_CONFIG_MULTITHREAD 2 /* nil */
  2990. #define SQLITE_CONFIG_SERIALIZED 3 /* nil */
  2991. #define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */
  2992. #define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */
  2993. #define SQLITE_CONFIG_SCRATCH 6 /* No longer used */
  2994. #define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */
  2995. #define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */
  2996. #define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */
  2997. #define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */
  2998. #define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */
  2999. /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
  3000. #define SQLITE_CONFIG_LOOKASIDE 13 /* int int */
  3001. #define SQLITE_CONFIG_PCACHE 14 /* no-op */
  3002. #define SQLITE_CONFIG_GETPCACHE 15 /* no-op */
  3003. #define SQLITE_CONFIG_LOG 16 /* xFunc, void* */
  3004. #define SQLITE_CONFIG_URI 17 /* int */
  3005. #define SQLITE_CONFIG_PCACHE2 18 /* sqlite3_pcache_methods2* */
  3006. #define SQLITE_CONFIG_GETPCACHE2 19 /* sqlite3_pcache_methods2* */
  3007. #define SQLITE_CONFIG_COVERING_INDEX_SCAN 20 /* int */
  3008. #define SQLITE_CONFIG_SQLLOG 21 /* xSqllog, void* */
  3009. #define SQLITE_CONFIG_MMAP_SIZE 22 /* sqlite3_int64, sqlite3_int64 */
  3010. #define SQLITE_CONFIG_WIN32_HEAPSIZE 23 /* int nByte */
  3011. #define SQLITE_CONFIG_PCACHE_HDRSZ 24 /* int *psz */
  3012. #define SQLITE_CONFIG_PMASZ 25 /* unsigned int szPma */
  3013. #define SQLITE_CONFIG_STMTJRNL_SPILL 26 /* int nByte */
  3014. #define SQLITE_CONFIG_SMALL_MALLOC 27 /* boolean */
  3015. #define SQLITE_CONFIG_SORTERREF_SIZE 28 /* int nByte */
  3016. #define SQLITE_CONFIG_MEMDB_MAXSIZE 29 /* sqlite3_int64 */
  3017. /*
  3018. ** CAPI3REF: Database Connection Configuration Options
  3019. **
  3020. ** These constants are the available integer configuration options that
  3021. ** can be passed as the second argument to the [sqlite3_db_config()] interface.
  3022. **
  3023. ** New configuration options may be added in future releases of SQLite.
  3024. ** Existing configuration options might be discontinued. Applications
  3025. ** should check the return code from [sqlite3_db_config()] to make sure that
  3026. ** the call worked. ^The [sqlite3_db_config()] interface will return a
  3027. ** non-zero [error code] if a discontinued or unsupported configuration option
  3028. ** is invoked.
  3029. **
  3030. ** <dl>
  3031. ** [[SQLITE_DBCONFIG_LOOKASIDE]]
  3032. ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
  3033. ** <dd> ^This option takes three additional arguments that determine the
  3034. ** [lookaside memory allocator] configuration for the [database connection].
  3035. ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
  3036. ** pointer to a memory buffer to use for lookaside memory.
  3037. ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
  3038. ** may be NULL in which case SQLite will allocate the
  3039. ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
  3040. ** size of each lookaside buffer slot. ^The third argument is the number of
  3041. ** slots. The size of the buffer in the first argument must be greater than
  3042. ** or equal to the product of the second and third arguments. The buffer
  3043. ** must be aligned to an 8-byte boundary. ^If the second argument to
  3044. ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
  3045. ** rounded down to the next smaller multiple of 8. ^(The lookaside memory
  3046. ** configuration for a database connection can only be changed when that
  3047. ** connection is not currently using lookaside memory, or in other words
  3048. ** when the "current value" returned by
  3049. ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
  3050. ** Any attempt to change the lookaside memory configuration when lookaside
  3051. ** memory is in use leaves the configuration unchanged and returns
  3052. ** [SQLITE_BUSY].)^</dd>
  3053. **
  3054. ** [[SQLITE_DBCONFIG_ENABLE_FKEY]]
  3055. ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
  3056. ** <dd> ^This option is used to enable or disable the enforcement of
  3057. ** [foreign key constraints]. There should be two additional arguments.
  3058. ** The first argument is an integer which is 0 to disable FK enforcement,
  3059. ** positive to enable FK enforcement or negative to leave FK enforcement
  3060. ** unchanged. The second parameter is a pointer to an integer into which
  3061. ** is written 0 or 1 to indicate whether FK enforcement is off or on
  3062. ** following this call. The second parameter may be a NULL pointer, in
  3063. ** which case the FK enforcement setting is not reported back. </dd>
  3064. **
  3065. ** [[SQLITE_DBCONFIG_ENABLE_TRIGGER]]
  3066. ** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
  3067. ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
  3068. ** There should be two additional arguments.
  3069. ** The first argument is an integer which is 0 to disable triggers,
  3070. ** positive to enable triggers or negative to leave the setting unchanged.
  3071. ** The second parameter is a pointer to an integer into which
  3072. ** is written 0 or 1 to indicate whether triggers are disabled or enabled
  3073. ** following this call. The second parameter may be a NULL pointer, in
  3074. ** which case the trigger setting is not reported back. </dd>
  3075. **
  3076. ** [[SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER]]
  3077. ** <dt>SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER</dt>
  3078. ** <dd> ^This option is used to enable or disable the
  3079. ** [fts3_tokenizer()] function which is part of the
  3080. ** [FTS3] full-text search engine extension.
  3081. ** There should be two additional arguments.
  3082. ** The first argument is an integer which is 0 to disable fts3_tokenizer() or
  3083. ** positive to enable fts3_tokenizer() or negative to leave the setting
  3084. ** unchanged.
  3085. ** The second parameter is a pointer to an integer into which
  3086. ** is written 0 or 1 to indicate whether fts3_tokenizer is disabled or enabled
  3087. ** following this call. The second parameter may be a NULL pointer, in
  3088. ** which case the new setting is not reported back. </dd>
  3089. **
  3090. ** [[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION]]
  3091. ** <dt>SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION</dt>
  3092. ** <dd> ^This option is used to enable or disable the [sqlite3_load_extension()]
  3093. ** interface independently of the [load_extension()] SQL function.
  3094. ** The [sqlite3_enable_load_extension()] API enables or disables both the
  3095. ** C-API [sqlite3_load_extension()] and the SQL function [load_extension()].
  3096. ** There should be two additional arguments.
  3097. ** When the first argument to this interface is 1, then only the C-API is
  3098. ** enabled and the SQL function remains disabled. If the first argument to
  3099. ** this interface is 0, then both the C-API and the SQL function are disabled.
  3100. ** If the first argument is -1, then no changes are made to state of either the
  3101. ** C-API or the SQL function.
  3102. ** The second parameter is a pointer to an integer into which
  3103. ** is written 0 or 1 to indicate whether [sqlite3_load_extension()] interface
  3104. ** is disabled or enabled following this call. The second parameter may
  3105. ** be a NULL pointer, in which case the new setting is not reported back.
  3106. ** </dd>
  3107. **
  3108. ** [[SQLITE_DBCONFIG_MAINDBNAME]] <dt>SQLITE_DBCONFIG_MAINDBNAME</dt>
  3109. ** <dd> ^This option is used to change the name of the "main" database
  3110. ** schema. ^The sole argument is a pointer to a constant UTF8 string
  3111. ** which will become the new schema name in place of "main". ^SQLite
  3112. ** does not make a copy of the new main schema name string, so the application
  3113. ** must ensure that the argument passed into this DBCONFIG option is unchanged
  3114. ** until after the database connection closes.
  3115. ** </dd>
  3116. **
  3117. ** [[SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE]]
  3118. ** <dt>SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE</dt>
  3119. ** <dd> Usually, when a database in wal mode is closed or detached from a
  3120. ** database handle, SQLite checks if this will mean that there are now no
  3121. ** connections at all to the database. If so, it performs a checkpoint
  3122. ** operation before closing the connection. This option may be used to
  3123. ** override this behaviour. The first parameter passed to this operation
  3124. ** is an integer - positive to disable checkpoints-on-close, or zero (the
  3125. ** default) to enable them, and negative to leave the setting unchanged.
  3126. ** The second parameter is a pointer to an integer
  3127. ** into which is written 0 or 1 to indicate whether checkpoints-on-close
  3128. ** have been disabled - 0 if they are not disabled, 1 if they are.
  3129. ** </dd>
  3130. **
  3131. ** [[SQLITE_DBCONFIG_ENABLE_QPSG]] <dt>SQLITE_DBCONFIG_ENABLE_QPSG</dt>
  3132. ** <dd>^(The SQLITE_DBCONFIG_ENABLE_QPSG option activates or deactivates
  3133. ** the [query planner stability guarantee] (QPSG). When the QPSG is active,
  3134. ** a single SQL query statement will always use the same algorithm regardless
  3135. ** of values of [bound parameters].)^ The QPSG disables some query optimizations
  3136. ** that look at the values of bound parameters, which can make some queries
  3137. ** slower. But the QPSG has the advantage of more predictable behavior. With
  3138. ** the QPSG active, SQLite will always use the same query plan in the field as
  3139. ** was used during testing in the lab.
  3140. ** The first argument to this setting is an integer which is 0 to disable
  3141. ** the QPSG, positive to enable QPSG, or negative to leave the setting
  3142. ** unchanged. The second parameter is a pointer to an integer into which
  3143. ** is written 0 or 1 to indicate whether the QPSG is disabled or enabled
  3144. ** following this call.
  3145. ** </dd>
  3146. **
  3147. ** [[SQLITE_DBCONFIG_TRIGGER_EQP]] <dt>SQLITE_DBCONFIG_TRIGGER_EQP</dt>
  3148. ** <dd> By default, the output of EXPLAIN QUERY PLAN commands does not
  3149. ** include output for any operations performed by trigger programs. This
  3150. ** option is used to set or clear (the default) a flag that governs this
  3151. ** behavior. The first parameter passed to this operation is an integer -
  3152. ** positive to enable output for trigger programs, or zero to disable it,
  3153. ** or negative to leave the setting unchanged.
  3154. ** The second parameter is a pointer to an integer into which is written
  3155. ** 0 or 1 to indicate whether output-for-triggers has been disabled - 0 if
  3156. ** it is not disabled, 1 if it is.
  3157. ** </dd>
  3158. **
  3159. ** [[SQLITE_DBCONFIG_RESET_DATABASE]] <dt>SQLITE_DBCONFIG_RESET_DATABASE</dt>
  3160. ** <dd> Set the SQLITE_DBCONFIG_RESET_DATABASE flag and then run
  3161. ** [VACUUM] in order to reset a database back to an empty database
  3162. ** with no schema and no content. The following process works even for
  3163. ** a badly corrupted database file:
  3164. ** <ol>
  3165. ** <li> If the database connection is newly opened, make sure it has read the
  3166. ** database schema by preparing then discarding some query against the
  3167. ** database, or calling sqlite3_table_column_metadata(), ignoring any
  3168. ** errors. This step is only necessary if the application desires to keep
  3169. ** the database in WAL mode after the reset if it was in WAL mode before
  3170. ** the reset.
  3171. ** <li> sqlite3_db_config(db, SQLITE_DBCONFIG_RESET_DATABASE, 1, 0);
  3172. ** <li> [sqlite3_exec](db, "[VACUUM]", 0, 0, 0);
  3173. ** <li> sqlite3_db_config(db, SQLITE_DBCONFIG_RESET_DATABASE, 0, 0);
  3174. ** </ol>
  3175. ** Because resetting a database is destructive and irreversible, the
  3176. ** process requires the use of this obscure API and multiple steps to help
  3177. ** ensure that it does not happen by accident.
  3178. **
  3179. ** [[SQLITE_DBCONFIG_DEFENSIVE]] <dt>SQLITE_DBCONFIG_DEFENSIVE</dt>
  3180. ** <dd>The SQLITE_DBCONFIG_DEFENSIVE option activates or deactivates the
  3181. ** "defensive" flag for a database connection. When the defensive
  3182. ** flag is enabled, language features that allow ordinary SQL to
  3183. ** deliberately corrupt the database file are disabled. The disabled
  3184. ** features include but are not limited to the following:
  3185. ** <ul>
  3186. ** <li> The [PRAGMA writable_schema=ON] statement.
  3187. ** <li> The [PRAGMA journal_mode=OFF] statement.
  3188. ** <li> Writes to the [sqlite_dbpage] virtual table.
  3189. ** <li> Direct writes to [shadow tables].
  3190. ** </ul>
  3191. ** </dd>
  3192. **
  3193. ** [[SQLITE_DBCONFIG_WRITABLE_SCHEMA]] <dt>SQLITE_DBCONFIG_WRITABLE_SCHEMA</dt>
  3194. ** <dd>The SQLITE_DBCONFIG_WRITABLE_SCHEMA option activates or deactivates the
  3195. ** "writable_schema" flag. This has the same effect and is logically equivalent
  3196. ** to setting [PRAGMA writable_schema=ON] or [PRAGMA writable_schema=OFF].
  3197. ** The first argument to this setting is an integer which is 0 to disable
  3198. ** the writable_schema, positive to enable writable_schema, or negative to
  3199. ** leave the setting unchanged. The second parameter is a pointer to an
  3200. ** integer into which is written 0 or 1 to indicate whether the writable_schema
  3201. ** is enabled or disabled following this call.
  3202. ** </dd>
  3203. **
  3204. ** [[SQLITE_DBCONFIG_LEGACY_ALTER_TABLE]]
  3205. ** <dt>SQLITE_DBCONFIG_LEGACY_ALTER_TABLE</dt>
  3206. ** <dd>The SQLITE_DBCONFIG_LEGACY_ALTER_TABLE option activates or deactivates
  3207. ** the legacy behavior of the [ALTER TABLE RENAME] command such it
  3208. ** behaves as it did prior to [version 3.24.0] (2018-06-04). See the
  3209. ** "Compatibility Notice" on the [ALTER TABLE RENAME documentation] for
  3210. ** additional information. This feature can also be turned on and off
  3211. ** using the [PRAGMA legacy_alter_table] statement.
  3212. ** </dd>
  3213. **
  3214. ** [[SQLITE_DBCONFIG_DQS_DML]]
  3215. ** <dt>SQLITE_DBCONFIG_DQS_DML</td>
  3216. ** <dd>The SQLITE_DBCONFIG_DQS_DML option activates or deactivates
  3217. ** the legacy [double-quoted string literal] misfeature for DML statement
  3218. ** only, that is DELETE, INSERT, SELECT, and UPDATE statements. The
  3219. ** default value of this setting is determined by the [-DSQLITE_DQS]
  3220. ** compile-time option.
  3221. ** </dd>
  3222. **
  3223. ** [[SQLITE_DBCONFIG_DQS_DDL]]
  3224. ** <dt>SQLITE_DBCONFIG_DQS_DDL</td>
  3225. ** <dd>The SQLITE_DBCONFIG_DQS option activates or deactivates
  3226. ** the legacy [double-quoted string literal] misfeature for DDL statements,
  3227. ** such as CREATE TABLE and CREATE INDEX. The
  3228. ** default value of this setting is determined by the [-DSQLITE_DQS]
  3229. ** compile-time option.
  3230. ** </dd>
  3231. ** </dl>
  3232. */
  3233. #define SQLITE_DBCONFIG_MAINDBNAME 1000 /* const char* */
  3234. #define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */
  3235. #define SQLITE_DBCONFIG_ENABLE_FKEY 1002 /* int int* */
  3236. #define SQLITE_DBCONFIG_ENABLE_TRIGGER 1003 /* int int* */
  3237. #define SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER 1004 /* int int* */
  3238. #define SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION 1005 /* int int* */
  3239. #define SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE 1006 /* int int* */
  3240. #define SQLITE_DBCONFIG_ENABLE_QPSG 1007 /* int int* */
  3241. #define SQLITE_DBCONFIG_TRIGGER_EQP 1008 /* int int* */
  3242. #define SQLITE_DBCONFIG_RESET_DATABASE 1009 /* int int* */
  3243. #define SQLITE_DBCONFIG_DEFENSIVE 1010 /* int int* */
  3244. #define SQLITE_DBCONFIG_WRITABLE_SCHEMA 1011 /* int int* */
  3245. #define SQLITE_DBCONFIG_LEGACY_ALTER_TABLE 1012 /* int int* */
  3246. #define SQLITE_DBCONFIG_DQS_DML 1013 /* int int* */
  3247. #define SQLITE_DBCONFIG_DQS_DDL 1014 /* int int* */
  3248. #define SQLITE_DBCONFIG_MAX 1014 /* Largest DBCONFIG */
  3249. /*
  3250. ** CAPI3REF: Enable Or Disable Extended Result Codes
  3251. ** METHOD: sqlite3
  3252. **
  3253. ** ^The sqlite3_extended_result_codes() routine enables or disables the
  3254. ** [extended result codes] feature of SQLite. ^The extended result
  3255. ** codes are disabled by default for historical compatibility.
  3256. */
  3257. SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
  3258. /*
  3259. ** CAPI3REF: Last Insert Rowid
  3260. ** METHOD: sqlite3
  3261. **
  3262. ** ^Each entry in most SQLite tables (except for [WITHOUT ROWID] tables)
  3263. ** has a unique 64-bit signed
  3264. ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
  3265. ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
  3266. ** names are not also used by explicitly declared columns. ^If
  3267. ** the table has a column of type [INTEGER PRIMARY KEY] then that column
  3268. ** is another alias for the rowid.
  3269. **
  3270. ** ^The sqlite3_last_insert_rowid(D) interface usually returns the [rowid] of
  3271. ** the most recent successful [INSERT] into a rowid table or [virtual table]
  3272. ** on database connection D. ^Inserts into [WITHOUT ROWID] tables are not
  3273. ** recorded. ^If no successful [INSERT]s into rowid tables have ever occurred
  3274. ** on the database connection D, then sqlite3_last_insert_rowid(D) returns
  3275. ** zero.
  3276. **
  3277. ** As well as being set automatically as rows are inserted into database
  3278. ** tables, the value returned by this function may be set explicitly by
  3279. ** [sqlite3_set_last_insert_rowid()]
  3280. **
  3281. ** Some virtual table implementations may INSERT rows into rowid tables as
  3282. ** part of committing a transaction (e.g. to flush data accumulated in memory
  3283. ** to disk). In this case subsequent calls to this function return the rowid
  3284. ** associated with these internal INSERT operations, which leads to
  3285. ** unintuitive results. Virtual table implementations that do write to rowid
  3286. ** tables in this way can avoid this problem by restoring the original
  3287. ** rowid value using [sqlite3_set_last_insert_rowid()] before returning
  3288. ** control to the user.
  3289. **
  3290. ** ^(If an [INSERT] occurs within a trigger then this routine will
  3291. ** return the [rowid] of the inserted row as long as the trigger is
  3292. ** running. Once the trigger program ends, the value returned
  3293. ** by this routine reverts to what it was before the trigger was fired.)^
  3294. **
  3295. ** ^An [INSERT] that fails due to a constraint violation is not a
  3296. ** successful [INSERT] and does not change the value returned by this
  3297. ** routine. ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
  3298. ** and INSERT OR ABORT make no changes to the return value of this
  3299. ** routine when their insertion fails. ^(When INSERT OR REPLACE
  3300. ** encounters a constraint violation, it does not fail. The
  3301. ** INSERT continues to completion after deleting rows that caused
  3302. ** the constraint problem so INSERT OR REPLACE will always change
  3303. ** the return value of this interface.)^
  3304. **
  3305. ** ^For the purposes of this routine, an [INSERT] is considered to
  3306. ** be successful even if it is subsequently rolled back.
  3307. **
  3308. ** This function is accessible to SQL statements via the
  3309. ** [last_insert_rowid() SQL function].
  3310. **
  3311. ** If a separate thread performs a new [INSERT] on the same
  3312. ** database connection while the [sqlite3_last_insert_rowid()]
  3313. ** function is running and thus changes the last insert [rowid],
  3314. ** then the value returned by [sqlite3_last_insert_rowid()] is
  3315. ** unpredictable and might not equal either the old or the new
  3316. ** last insert [rowid].
  3317. */
  3318. SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
  3319. /*
  3320. ** CAPI3REF: Set the Last Insert Rowid value.
  3321. ** METHOD: sqlite3
  3322. **
  3323. ** The sqlite3_set_last_insert_rowid(D, R) method allows the application to
  3324. ** set the value returned by calling sqlite3_last_insert_rowid(D) to R
  3325. ** without inserting a row into the database.
  3326. */
  3327. SQLITE_API void sqlite3_set_last_insert_rowid(sqlite3*,sqlite3_int64);
  3328. /*
  3329. ** CAPI3REF: Count The Number Of Rows Modified
  3330. ** METHOD: sqlite3
  3331. **
  3332. ** ^This function returns the number of rows modified, inserted or
  3333. ** deleted by the most recently completed INSERT, UPDATE or DELETE
  3334. ** statement on the database connection specified by the only parameter.
  3335. ** ^Executing any other type of SQL statement does not modify the value
  3336. ** returned by this function.
  3337. **
  3338. ** ^Only changes made directly by the INSERT, UPDATE or DELETE statement are
  3339. ** considered - auxiliary changes caused by [CREATE TRIGGER | triggers],
  3340. ** [foreign key actions] or [REPLACE] constraint resolution are not counted.
  3341. **
  3342. ** Changes to a view that are intercepted by
  3343. ** [INSTEAD OF trigger | INSTEAD OF triggers] are not counted. ^The value
  3344. ** returned by sqlite3_changes() immediately after an INSERT, UPDATE or
  3345. ** DELETE statement run on a view is always zero. Only changes made to real
  3346. ** tables are counted.
  3347. **
  3348. ** Things are more complicated if the sqlite3_changes() function is
  3349. ** executed while a trigger program is running. This may happen if the
  3350. ** program uses the [changes() SQL function], or if some other callback
  3351. ** function invokes sqlite3_changes() directly. Essentially:
  3352. **
  3353. ** <ul>
  3354. ** <li> ^(Before entering a trigger program the value returned by
  3355. ** sqlite3_changes() function is saved. After the trigger program
  3356. ** has finished, the original value is restored.)^
  3357. **
  3358. ** <li> ^(Within a trigger program each INSERT, UPDATE and DELETE
  3359. ** statement sets the value returned by sqlite3_changes()
  3360. ** upon completion as normal. Of course, this value will not include
  3361. ** any changes performed by sub-triggers, as the sqlite3_changes()
  3362. ** value will be saved and restored after each sub-trigger has run.)^
  3363. ** </ul>
  3364. **
  3365. ** ^This means that if the changes() SQL function (or similar) is used
  3366. ** by the first INSERT, UPDATE or DELETE statement within a trigger, it
  3367. ** returns the value as set when the calling statement began executing.
  3368. ** ^If it is used by the second or subsequent such statement within a trigger
  3369. ** program, the value returned reflects the number of rows modified by the
  3370. ** previous INSERT, UPDATE or DELETE statement within the same trigger.
  3371. **
  3372. ** If a separate thread makes changes on the same database connection
  3373. ** while [sqlite3_changes()] is running then the value returned
  3374. ** is unpredictable and not meaningful.
  3375. **
  3376. ** See also:
  3377. ** <ul>
  3378. ** <li> the [sqlite3_total_changes()] interface
  3379. ** <li> the [count_changes pragma]
  3380. ** <li> the [changes() SQL function]
  3381. ** <li> the [data_version pragma]
  3382. ** </ul>
  3383. */
  3384. SQLITE_API int sqlite3_changes(sqlite3*);
  3385. /*
  3386. ** CAPI3REF: Total Number Of Rows Modified
  3387. ** METHOD: sqlite3
  3388. **
  3389. ** ^This function returns the total number of rows inserted, modified or
  3390. ** deleted by all [INSERT], [UPDATE] or [DELETE] statements completed
  3391. ** since the database connection was opened, including those executed as
  3392. ** part of trigger programs. ^Executing any other type of SQL statement
  3393. ** does not affect the value returned by sqlite3_total_changes().
  3394. **
  3395. ** ^Changes made as part of [foreign key actions] are included in the
  3396. ** count, but those made as part of REPLACE constraint resolution are
  3397. ** not. ^Changes to a view that are intercepted by INSTEAD OF triggers
  3398. ** are not counted.
  3399. **
  3400. ** The [sqlite3_total_changes(D)] interface only reports the number
  3401. ** of rows that changed due to SQL statement run against database
  3402. ** connection D. Any changes by other database connections are ignored.
  3403. ** To detect changes against a database file from other database
  3404. ** connections use the [PRAGMA data_version] command or the
  3405. ** [SQLITE_FCNTL_DATA_VERSION] [file control].
  3406. **
  3407. ** If a separate thread makes changes on the same database connection
  3408. ** while [sqlite3_total_changes()] is running then the value
  3409. ** returned is unpredictable and not meaningful.
  3410. **
  3411. ** See also:
  3412. ** <ul>
  3413. ** <li> the [sqlite3_changes()] interface
  3414. ** <li> the [count_changes pragma]
  3415. ** <li> the [changes() SQL function]
  3416. ** <li> the [data_version pragma]
  3417. ** <li> the [SQLITE_FCNTL_DATA_VERSION] [file control]
  3418. ** </ul>
  3419. */
  3420. SQLITE_API int sqlite3_total_changes(sqlite3*);
  3421. /*
  3422. ** CAPI3REF: Interrupt A Long-Running Query
  3423. ** METHOD: sqlite3
  3424. **
  3425. ** ^This function causes any pending database operation to abort and
  3426. ** return at its earliest opportunity. This routine is typically
  3427. ** called in response to a user action such as pressing "Cancel"
  3428. ** or Ctrl-C where the user wants a long query operation to halt
  3429. ** immediately.
  3430. **
  3431. ** ^It is safe to call this routine from a thread different from the
  3432. ** thread that is currently running the database operation. But it
  3433. ** is not safe to call this routine with a [database connection] that
  3434. ** is closed or might close before sqlite3_interrupt() returns.
  3435. **
  3436. ** ^If an SQL operation is very nearly finished at the time when
  3437. ** sqlite3_interrupt() is called, then it might not have an opportunity
  3438. ** to be interrupted and might continue to completion.
  3439. **
  3440. ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
  3441. ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
  3442. ** that is inside an explicit transaction, then the entire transaction
  3443. ** will be rolled back automatically.
  3444. **
  3445. ** ^The sqlite3_interrupt(D) call is in effect until all currently running
  3446. ** SQL statements on [database connection] D complete. ^Any new SQL statements
  3447. ** that are started after the sqlite3_interrupt() call and before the
  3448. ** running statements reaches zero are interrupted as if they had been
  3449. ** running prior to the sqlite3_interrupt() call. ^New SQL statements
  3450. ** that are started after the running statement count reaches zero are
  3451. ** not effected by the sqlite3_interrupt().
  3452. ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
  3453. ** SQL statements is a no-op and has no effect on SQL statements
  3454. ** that are started after the sqlite3_interrupt() call returns.
  3455. */
  3456. SQLITE_API void sqlite3_interrupt(sqlite3*);
  3457. /*
  3458. ** CAPI3REF: Determine If An SQL Statement Is Complete
  3459. **
  3460. ** These routines are useful during command-line input to determine if the
  3461. ** currently entered text seems to form a complete SQL statement or
  3462. ** if additional input is needed before sending the text into
  3463. ** SQLite for parsing. ^These routines return 1 if the input string
  3464. ** appears to be a complete SQL statement. ^A statement is judged to be
  3465. ** complete if it ends with a semicolon token and is not a prefix of a
  3466. ** well-formed CREATE TRIGGER statement. ^Semicolons that are embedded within
  3467. ** string literals or quoted identifier names or comments are not
  3468. ** independent tokens (they are part of the token in which they are
  3469. ** embedded) and thus do not count as a statement terminator. ^Whitespace
  3470. ** and comments that follow the final semicolon are ignored.
  3471. **
  3472. ** ^These routines return 0 if the statement is incomplete. ^If a
  3473. ** memory allocation fails, then SQLITE_NOMEM is returned.
  3474. **
  3475. ** ^These routines do not parse the SQL statements thus
  3476. ** will not detect syntactically incorrect SQL.
  3477. **
  3478. ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
  3479. ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
  3480. ** automatically by sqlite3_complete16(). If that initialization fails,
  3481. ** then the return value from sqlite3_complete16() will be non-zero
  3482. ** regardless of whether or not the input SQL is complete.)^
  3483. **
  3484. ** The input to [sqlite3_complete()] must be a zero-terminated
  3485. ** UTF-8 string.
  3486. **
  3487. ** The input to [sqlite3_complete16()] must be a zero-terminated
  3488. ** UTF-16 string in native byte order.
  3489. */
  3490. SQLITE_API int sqlite3_complete(const char *sql);
  3491. SQLITE_API int sqlite3_complete16(const void *sql);
  3492. /*
  3493. ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
  3494. ** KEYWORDS: {busy-handler callback} {busy handler}
  3495. ** METHOD: sqlite3
  3496. **
  3497. ** ^The sqlite3_busy_handler(D,X,P) routine sets a callback function X
  3498. ** that might be invoked with argument P whenever
  3499. ** an attempt is made to access a database table associated with
  3500. ** [database connection] D when another thread
  3501. ** or process has the table locked.
  3502. ** The sqlite3_busy_handler() interface is used to implement
  3503. ** [sqlite3_busy_timeout()] and [PRAGMA busy_timeout].
  3504. **
  3505. ** ^If the busy callback is NULL, then [SQLITE_BUSY]
  3506. ** is returned immediately upon encountering the lock. ^If the busy callback
  3507. ** is not NULL, then the callback might be invoked with two arguments.
  3508. **
  3509. ** ^The first argument to the busy handler is a copy of the void* pointer which
  3510. ** is the third argument to sqlite3_busy_handler(). ^The second argument to
  3511. ** the busy handler callback is the number of times that the busy handler has
  3512. ** been invoked previously for the same locking event. ^If the
  3513. ** busy callback returns 0, then no additional attempts are made to
  3514. ** access the database and [SQLITE_BUSY] is returned
  3515. ** to the application.
  3516. ** ^If the callback returns non-zero, then another attempt
  3517. ** is made to access the database and the cycle repeats.
  3518. **
  3519. ** The presence of a busy handler does not guarantee that it will be invoked
  3520. ** when there is lock contention. ^If SQLite determines that invoking the busy
  3521. ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
  3522. ** to the application instead of invoking the
  3523. ** busy handler.
  3524. ** Consider a scenario where one process is holding a read lock that
  3525. ** it is trying to promote to a reserved lock and
  3526. ** a second process is holding a reserved lock that it is trying
  3527. ** to promote to an exclusive lock. The first process cannot proceed
  3528. ** because it is blocked by the second and the second process cannot
  3529. ** proceed because it is blocked by the first. If both processes
  3530. ** invoke the busy handlers, neither will make any progress. Therefore,
  3531. ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
  3532. ** will induce the first process to release its read lock and allow
  3533. ** the second process to proceed.
  3534. **
  3535. ** ^The default busy callback is NULL.
  3536. **
  3537. ** ^(There can only be a single busy handler defined for each
  3538. ** [database connection]. Setting a new busy handler clears any
  3539. ** previously set handler.)^ ^Note that calling [sqlite3_busy_timeout()]
  3540. ** or evaluating [PRAGMA busy_timeout=N] will change the
  3541. ** busy handler and thus clear any previously set busy handler.
  3542. **
  3543. ** The busy callback should not take any actions which modify the
  3544. ** database connection that invoked the busy handler. In other words,
  3545. ** the busy handler is not reentrant. Any such actions
  3546. ** result in undefined behavior.
  3547. **
  3548. ** A busy handler must not close the database connection
  3549. ** or [prepared statement] that invoked the busy handler.
  3550. */
  3551. SQLITE_API int sqlite3_busy_handler(sqlite3*,int(*)(void*,int),void*);
  3552. /*
  3553. ** CAPI3REF: Set A Busy Timeout
  3554. ** METHOD: sqlite3
  3555. **
  3556. ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
  3557. ** for a specified amount of time when a table is locked. ^The handler
  3558. ** will sleep multiple times until at least "ms" milliseconds of sleeping
  3559. ** have accumulated. ^After at least "ms" milliseconds of sleeping,
  3560. ** the handler returns 0 which causes [sqlite3_step()] to return
  3561. ** [SQLITE_BUSY].
  3562. **
  3563. ** ^Calling this routine with an argument less than or equal to zero
  3564. ** turns off all busy handlers.
  3565. **
  3566. ** ^(There can only be a single busy handler for a particular
  3567. ** [database connection] at any given moment. If another busy handler
  3568. ** was defined (using [sqlite3_busy_handler()]) prior to calling
  3569. ** this routine, that other busy handler is cleared.)^
  3570. **
  3571. ** See also: [PRAGMA busy_timeout]
  3572. */
  3573. SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
  3574. /*
  3575. ** CAPI3REF: Convenience Routines For Running Queries
  3576. ** METHOD: sqlite3
  3577. **
  3578. ** This is a legacy interface that is preserved for backwards compatibility.
  3579. ** Use of this interface is not recommended.
  3580. **
  3581. ** Definition: A <b>result table</b> is memory data structure created by the
  3582. ** [sqlite3_get_table()] interface. A result table records the
  3583. ** complete query results from one or more queries.
  3584. **
  3585. ** The table conceptually has a number of rows and columns. But
  3586. ** these numbers are not part of the result table itself. These
  3587. ** numbers are obtained separately. Let N be the number of rows
  3588. ** and M be the number of columns.
  3589. **
  3590. ** A result table is an array of pointers to zero-terminated UTF-8 strings.
  3591. ** There are (N+1)*M elements in the array. The first M pointers point
  3592. ** to zero-terminated strings that contain the names of the columns.
  3593. ** The remaining entries all point to query results. NULL values result
  3594. ** in NULL pointers. All other values are in their UTF-8 zero-terminated
  3595. ** string representation as returned by [sqlite3_column_text()].
  3596. **
  3597. ** A result table might consist of one or more memory allocations.
  3598. ** It is not safe to pass a result table directly to [sqlite3_free()].
  3599. ** A result table should be deallocated using [sqlite3_free_table()].
  3600. **
  3601. ** ^(As an example of the result table format, suppose a query result
  3602. ** is as follows:
  3603. **
  3604. ** <blockquote><pre>
  3605. ** Name | Age
  3606. ** -----------------------
  3607. ** Alice | 43
  3608. ** Bob | 28
  3609. ** Cindy | 21
  3610. ** </pre></blockquote>
  3611. **
  3612. ** There are two column (M==2) and three rows (N==3). Thus the
  3613. ** result table has 8 entries. Suppose the result table is stored
  3614. ** in an array names azResult. Then azResult holds this content:
  3615. **
  3616. ** <blockquote><pre>
  3617. ** azResult&#91;0] = "Name";
  3618. ** azResult&#91;1] = "Age";
  3619. ** azResult&#91;2] = "Alice";
  3620. ** azResult&#91;3] = "43";
  3621. ** azResult&#91;4] = "Bob";
  3622. ** azResult&#91;5] = "28";
  3623. ** azResult&#91;6] = "Cindy";
  3624. ** azResult&#91;7] = "21";
  3625. ** </pre></blockquote>)^
  3626. **
  3627. ** ^The sqlite3_get_table() function evaluates one or more
  3628. ** semicolon-separated SQL statements in the zero-terminated UTF-8
  3629. ** string of its 2nd parameter and returns a result table to the
  3630. ** pointer given in its 3rd parameter.
  3631. **
  3632. ** After the application has finished with the result from sqlite3_get_table(),
  3633. ** it must pass the result table pointer to sqlite3_free_table() in order to
  3634. ** release the memory that was malloced. Because of the way the
  3635. ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
  3636. ** function must not try to call [sqlite3_free()] directly. Only
  3637. ** [sqlite3_free_table()] is able to release the memory properly and safely.
  3638. **
  3639. ** The sqlite3_get_table() interface is implemented as a wrapper around
  3640. ** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access
  3641. ** to any internal data structures of SQLite. It uses only the public
  3642. ** interface defined here. As a consequence, errors that occur in the
  3643. ** wrapper layer outside of the internal [sqlite3_exec()] call are not
  3644. ** reflected in subsequent calls to [sqlite3_errcode()] or
  3645. ** [sqlite3_errmsg()].
  3646. */
  3647. SQLITE_API int sqlite3_get_table(
  3648. sqlite3 *db, /* An open database */
  3649. const char *zSql, /* SQL to be evaluated */
  3650. char ***pazResult, /* Results of the query */
  3651. int *pnRow, /* Number of result rows written here */
  3652. int *pnColumn, /* Number of result columns written here */
  3653. char **pzErrmsg /* Error msg written here */
  3654. );
  3655. SQLITE_API void sqlite3_free_table(char **result);
  3656. /*
  3657. ** CAPI3REF: Formatted String Printing Functions
  3658. **
  3659. ** These routines are work-alikes of the "printf()" family of functions
  3660. ** from the standard C library.
  3661. ** These routines understand most of the common formatting options from
  3662. ** the standard library printf()
  3663. ** plus some additional non-standard formats ([%q], [%Q], [%w], and [%z]).
  3664. ** See the [built-in printf()] documentation for details.
  3665. **
  3666. ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
  3667. ** results into memory obtained from [sqlite3_malloc64()].
  3668. ** The strings returned by these two routines should be
  3669. ** released by [sqlite3_free()]. ^Both routines return a
  3670. ** NULL pointer if [sqlite3_malloc64()] is unable to allocate enough
  3671. ** memory to hold the resulting string.
  3672. **
  3673. ** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
  3674. ** the standard C library. The result is written into the
  3675. ** buffer supplied as the second parameter whose size is given by
  3676. ** the first parameter. Note that the order of the
  3677. ** first two parameters is reversed from snprintf().)^ This is an
  3678. ** historical accident that cannot be fixed without breaking
  3679. ** backwards compatibility. ^(Note also that sqlite3_snprintf()
  3680. ** returns a pointer to its buffer instead of the number of
  3681. ** characters actually written into the buffer.)^ We admit that
  3682. ** the number of characters written would be a more useful return
  3683. ** value but we cannot change the implementation of sqlite3_snprintf()
  3684. ** now without breaking compatibility.
  3685. **
  3686. ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
  3687. ** guarantees that the buffer is always zero-terminated. ^The first
  3688. ** parameter "n" is the total size of the buffer, including space for
  3689. ** the zero terminator. So the longest string that can be completely
  3690. ** written will be n-1 characters.
  3691. **
  3692. ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
  3693. **
  3694. ** See also: [built-in printf()], [printf() SQL function]
  3695. */
  3696. SQLITE_API char *sqlite3_mprintf(const char*,...);
  3697. SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
  3698. SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
  3699. SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
  3700. /*
  3701. ** CAPI3REF: Memory Allocation Subsystem
  3702. **
  3703. ** The SQLite core uses these three routines for all of its own
  3704. ** internal memory allocation needs. "Core" in the previous sentence
  3705. ** does not include operating-system specific VFS implementation. The
  3706. ** Windows VFS uses native malloc() and free() for some operations.
  3707. **
  3708. ** ^The sqlite3_malloc() routine returns a pointer to a block
  3709. ** of memory at least N bytes in length, where N is the parameter.
  3710. ** ^If sqlite3_malloc() is unable to obtain sufficient free
  3711. ** memory, it returns a NULL pointer. ^If the parameter N to
  3712. ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
  3713. ** a NULL pointer.
  3714. **
  3715. ** ^The sqlite3_malloc64(N) routine works just like
  3716. ** sqlite3_malloc(N) except that N is an unsigned 64-bit integer instead
  3717. ** of a signed 32-bit integer.
  3718. **
  3719. ** ^Calling sqlite3_free() with a pointer previously returned
  3720. ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
  3721. ** that it might be reused. ^The sqlite3_free() routine is
  3722. ** a no-op if is called with a NULL pointer. Passing a NULL pointer
  3723. ** to sqlite3_free() is harmless. After being freed, memory
  3724. ** should neither be read nor written. Even reading previously freed
  3725. ** memory might result in a segmentation fault or other severe error.
  3726. ** Memory corruption, a segmentation fault, or other severe error
  3727. ** might result if sqlite3_free() is called with a non-NULL pointer that
  3728. ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
  3729. **
  3730. ** ^The sqlite3_realloc(X,N) interface attempts to resize a
  3731. ** prior memory allocation X to be at least N bytes.
  3732. ** ^If the X parameter to sqlite3_realloc(X,N)
  3733. ** is a NULL pointer then its behavior is identical to calling
  3734. ** sqlite3_malloc(N).
  3735. ** ^If the N parameter to sqlite3_realloc(X,N) is zero or
  3736. ** negative then the behavior is exactly the same as calling
  3737. ** sqlite3_free(X).
  3738. ** ^sqlite3_realloc(X,N) returns a pointer to a memory allocation
  3739. ** of at least N bytes in size or NULL if insufficient memory is available.
  3740. ** ^If M is the size of the prior allocation, then min(N,M) bytes
  3741. ** of the prior allocation are copied into the beginning of buffer returned
  3742. ** by sqlite3_realloc(X,N) and the prior allocation is freed.
  3743. ** ^If sqlite3_realloc(X,N) returns NULL and N is positive, then the
  3744. ** prior allocation is not freed.
  3745. **
  3746. ** ^The sqlite3_realloc64(X,N) interfaces works the same as
  3747. ** sqlite3_realloc(X,N) except that N is a 64-bit unsigned integer instead
  3748. ** of a 32-bit signed integer.
  3749. **
  3750. ** ^If X is a memory allocation previously obtained from sqlite3_malloc(),
  3751. ** sqlite3_malloc64(), sqlite3_realloc(), or sqlite3_realloc64(), then
  3752. ** sqlite3_msize(X) returns the size of that memory allocation in bytes.
  3753. ** ^The value returned by sqlite3_msize(X) might be larger than the number
  3754. ** of bytes requested when X was allocated. ^If X is a NULL pointer then
  3755. ** sqlite3_msize(X) returns zero. If X points to something that is not
  3756. ** the beginning of memory allocation, or if it points to a formerly
  3757. ** valid memory allocation that has now been freed, then the behavior
  3758. ** of sqlite3_msize(X) is undefined and possibly harmful.
  3759. **
  3760. ** ^The memory returned by sqlite3_malloc(), sqlite3_realloc(),
  3761. ** sqlite3_malloc64(), and sqlite3_realloc64()
  3762. ** is always aligned to at least an 8 byte boundary, or to a
  3763. ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
  3764. ** option is used.
  3765. **
  3766. ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
  3767. ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
  3768. ** implementation of these routines to be omitted. That capability
  3769. ** is no longer provided. Only built-in memory allocators can be used.
  3770. **
  3771. ** Prior to SQLite version 3.7.10, the Windows OS interface layer called
  3772. ** the system malloc() and free() directly when converting
  3773. ** filenames between the UTF-8 encoding used by SQLite
  3774. ** and whatever filename encoding is used by the particular Windows
  3775. ** installation. Memory allocation errors were detected, but
  3776. ** they were reported back as [SQLITE_CANTOPEN] or
  3777. ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
  3778. **
  3779. ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
  3780. ** must be either NULL or else pointers obtained from a prior
  3781. ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
  3782. ** not yet been released.
  3783. **
  3784. ** The application must not read or write any part of
  3785. ** a block of memory after it has been released using
  3786. ** [sqlite3_free()] or [sqlite3_realloc()].
  3787. */
  3788. SQLITE_API void *sqlite3_malloc(int);
  3789. SQLITE_API void *sqlite3_malloc64(sqlite3_uint64);
  3790. SQLITE_API void *sqlite3_realloc(void*, int);
  3791. SQLITE_API void *sqlite3_realloc64(void*, sqlite3_uint64);
  3792. SQLITE_API void sqlite3_free(void*);
  3793. SQLITE_API sqlite3_uint64 sqlite3_msize(void*);
  3794. /*
  3795. ** CAPI3REF: Memory Allocator Statistics
  3796. **
  3797. ** SQLite provides these two interfaces for reporting on the status
  3798. ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
  3799. ** routines, which form the built-in memory allocation subsystem.
  3800. **
  3801. ** ^The [sqlite3_memory_used()] routine returns the number of bytes
  3802. ** of memory currently outstanding (malloced but not freed).
  3803. ** ^The [sqlite3_memory_highwater()] routine returns the maximum
  3804. ** value of [sqlite3_memory_used()] since the high-water mark
  3805. ** was last reset. ^The values returned by [sqlite3_memory_used()] and
  3806. ** [sqlite3_memory_highwater()] include any overhead
  3807. ** added by SQLite in its implementation of [sqlite3_malloc()],
  3808. ** but not overhead added by the any underlying system library
  3809. ** routines that [sqlite3_malloc()] may call.
  3810. **
  3811. ** ^The memory high-water mark is reset to the current value of
  3812. ** [sqlite3_memory_used()] if and only if the parameter to
  3813. ** [sqlite3_memory_highwater()] is true. ^The value returned
  3814. ** by [sqlite3_memory_highwater(1)] is the high-water mark
  3815. ** prior to the reset.
  3816. */
  3817. SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
  3818. SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
  3819. /*
  3820. ** CAPI3REF: Pseudo-Random Number Generator
  3821. **
  3822. ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
  3823. ** select random [ROWID | ROWIDs] when inserting new records into a table that
  3824. ** already uses the largest possible [ROWID]. The PRNG is also used for
  3825. ** the build-in random() and randomblob() SQL functions. This interface allows
  3826. ** applications to access the same PRNG for other purposes.
  3827. **
  3828. ** ^A call to this routine stores N bytes of randomness into buffer P.
  3829. ** ^The P parameter can be a NULL pointer.
  3830. **
  3831. ** ^If this routine has not been previously called or if the previous
  3832. ** call had N less than one or a NULL pointer for P, then the PRNG is
  3833. ** seeded using randomness obtained from the xRandomness method of
  3834. ** the default [sqlite3_vfs] object.
  3835. ** ^If the previous call to this routine had an N of 1 or more and a
  3836. ** non-NULL P then the pseudo-randomness is generated
  3837. ** internally and without recourse to the [sqlite3_vfs] xRandomness
  3838. ** method.
  3839. */
  3840. SQLITE_API void sqlite3_randomness(int N, void *P);
  3841. /*
  3842. ** CAPI3REF: Compile-Time Authorization Callbacks
  3843. ** METHOD: sqlite3
  3844. ** KEYWORDS: {authorizer callback}
  3845. **
  3846. ** ^This routine registers an authorizer callback with a particular
  3847. ** [database connection], supplied in the first argument.
  3848. ** ^The authorizer callback is invoked as SQL statements are being compiled
  3849. ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
  3850. ** [sqlite3_prepare_v3()], [sqlite3_prepare16()], [sqlite3_prepare16_v2()],
  3851. ** and [sqlite3_prepare16_v3()]. ^At various
  3852. ** points during the compilation process, as logic is being created
  3853. ** to perform various actions, the authorizer callback is invoked to
  3854. ** see if those actions are allowed. ^The authorizer callback should
  3855. ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
  3856. ** specific action but allow the SQL statement to continue to be
  3857. ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
  3858. ** rejected with an error. ^If the authorizer callback returns
  3859. ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
  3860. ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
  3861. ** the authorizer will fail with an error message.
  3862. **
  3863. ** When the callback returns [SQLITE_OK], that means the operation
  3864. ** requested is ok. ^When the callback returns [SQLITE_DENY], the
  3865. ** [sqlite3_prepare_v2()] or equivalent call that triggered the
  3866. ** authorizer will fail with an error message explaining that
  3867. ** access is denied.
  3868. **
  3869. ** ^The first parameter to the authorizer callback is a copy of the third
  3870. ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
  3871. ** to the callback is an integer [SQLITE_COPY | action code] that specifies
  3872. ** the particular action to be authorized. ^The third through sixth parameters
  3873. ** to the callback are either NULL pointers or zero-terminated strings
  3874. ** that contain additional details about the action to be authorized.
  3875. ** Applications must always be prepared to encounter a NULL pointer in any
  3876. ** of the third through the sixth parameters of the authorization callback.
  3877. **
  3878. ** ^If the action code is [SQLITE_READ]
  3879. ** and the callback returns [SQLITE_IGNORE] then the
  3880. ** [prepared statement] statement is constructed to substitute
  3881. ** a NULL value in place of the table column that would have
  3882. ** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE]
  3883. ** return can be used to deny an untrusted user access to individual
  3884. ** columns of a table.
  3885. ** ^When a table is referenced by a [SELECT] but no column values are
  3886. ** extracted from that table (for example in a query like
  3887. ** "SELECT count(*) FROM tab") then the [SQLITE_READ] authorizer callback
  3888. ** is invoked once for that table with a column name that is an empty string.
  3889. ** ^If the action code is [SQLITE_DELETE] and the callback returns
  3890. ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
  3891. ** [truncate optimization] is disabled and all rows are deleted individually.
  3892. **
  3893. ** An authorizer is used when [sqlite3_prepare | preparing]
  3894. ** SQL statements from an untrusted source, to ensure that the SQL statements
  3895. ** do not try to access data they are not allowed to see, or that they do not
  3896. ** try to execute malicious statements that damage the database. For
  3897. ** example, an application may allow a user to enter arbitrary
  3898. ** SQL queries for evaluation by a database. But the application does
  3899. ** not want the user to be able to make arbitrary changes to the
  3900. ** database. An authorizer could then be put in place while the
  3901. ** user-entered SQL is being [sqlite3_prepare | prepared] that
  3902. ** disallows everything except [SELECT] statements.
  3903. **
  3904. ** Applications that need to process SQL from untrusted sources
  3905. ** might also consider lowering resource limits using [sqlite3_limit()]
  3906. ** and limiting database size using the [max_page_count] [PRAGMA]
  3907. ** in addition to using an authorizer.
  3908. **
  3909. ** ^(Only a single authorizer can be in place on a database connection
  3910. ** at a time. Each call to sqlite3_set_authorizer overrides the
  3911. ** previous call.)^ ^Disable the authorizer by installing a NULL callback.
  3912. ** The authorizer is disabled by default.
  3913. **
  3914. ** The authorizer callback must not do anything that will modify
  3915. ** the database connection that invoked the authorizer callback.
  3916. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  3917. ** database connections for the meaning of "modify" in this paragraph.
  3918. **
  3919. ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
  3920. ** statement might be re-prepared during [sqlite3_step()] due to a
  3921. ** schema change. Hence, the application should ensure that the
  3922. ** correct authorizer callback remains in place during the [sqlite3_step()].
  3923. **
  3924. ** ^Note that the authorizer callback is invoked only during
  3925. ** [sqlite3_prepare()] or its variants. Authorization is not
  3926. ** performed during statement evaluation in [sqlite3_step()], unless
  3927. ** as stated in the previous paragraph, sqlite3_step() invokes
  3928. ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
  3929. */
  3930. SQLITE_API int sqlite3_set_authorizer(
  3931. sqlite3*,
  3932. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  3933. void *pUserData
  3934. );
  3935. /*
  3936. ** CAPI3REF: Authorizer Return Codes
  3937. **
  3938. ** The [sqlite3_set_authorizer | authorizer callback function] must
  3939. ** return either [SQLITE_OK] or one of these two constants in order
  3940. ** to signal SQLite whether or not the action is permitted. See the
  3941. ** [sqlite3_set_authorizer | authorizer documentation] for additional
  3942. ** information.
  3943. **
  3944. ** Note that SQLITE_IGNORE is also used as a [conflict resolution mode]
  3945. ** returned from the [sqlite3_vtab_on_conflict()] interface.
  3946. */
  3947. #define SQLITE_DENY 1 /* Abort the SQL statement with an error */
  3948. #define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */
  3949. /*
  3950. ** CAPI3REF: Authorizer Action Codes
  3951. **
  3952. ** The [sqlite3_set_authorizer()] interface registers a callback function
  3953. ** that is invoked to authorize certain SQL statement actions. The
  3954. ** second parameter to the callback is an integer code that specifies
  3955. ** what action is being authorized. These are the integer action codes that
  3956. ** the authorizer callback may be passed.
  3957. **
  3958. ** These action code values signify what kind of operation is to be
  3959. ** authorized. The 3rd and 4th parameters to the authorization
  3960. ** callback function will be parameters or NULL depending on which of these
  3961. ** codes is used as the second parameter. ^(The 5th parameter to the
  3962. ** authorizer callback is the name of the database ("main", "temp",
  3963. ** etc.) if applicable.)^ ^The 6th parameter to the authorizer callback
  3964. ** is the name of the inner-most trigger or view that is responsible for
  3965. ** the access attempt or NULL if this access attempt is directly from
  3966. ** top-level SQL code.
  3967. */
  3968. /******************************************* 3rd ************ 4th ***********/
  3969. #define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */
  3970. #define SQLITE_CREATE_TABLE 2 /* Table Name NULL */
  3971. #define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */
  3972. #define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */
  3973. #define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */
  3974. #define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */
  3975. #define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */
  3976. #define SQLITE_CREATE_VIEW 8 /* View Name NULL */
  3977. #define SQLITE_DELETE 9 /* Table Name NULL */
  3978. #define SQLITE_DROP_INDEX 10 /* Index Name Table Name */
  3979. #define SQLITE_DROP_TABLE 11 /* Table Name NULL */
  3980. #define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */
  3981. #define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */
  3982. #define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */
  3983. #define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */
  3984. #define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */
  3985. #define SQLITE_DROP_VIEW 17 /* View Name NULL */
  3986. #define SQLITE_INSERT 18 /* Table Name NULL */
  3987. #define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */
  3988. #define SQLITE_READ 20 /* Table Name Column Name */
  3989. #define SQLITE_SELECT 21 /* NULL NULL */
  3990. #define SQLITE_TRANSACTION 22 /* Operation NULL */
  3991. #define SQLITE_UPDATE 23 /* Table Name Column Name */
  3992. #define SQLITE_ATTACH 24 /* Filename NULL */
  3993. #define SQLITE_DETACH 25 /* Database Name NULL */
  3994. #define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */
  3995. #define SQLITE_REINDEX 27 /* Index Name NULL */
  3996. #define SQLITE_ANALYZE 28 /* Table Name NULL */
  3997. #define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */
  3998. #define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */
  3999. #define SQLITE_FUNCTION 31 /* NULL Function Name */
  4000. #define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */
  4001. #define SQLITE_COPY 0 /* No longer used */
  4002. #define SQLITE_RECURSIVE 33 /* NULL NULL */
  4003. /*
  4004. ** CAPI3REF: Tracing And Profiling Functions
  4005. ** METHOD: sqlite3
  4006. **
  4007. ** These routines are deprecated. Use the [sqlite3_trace_v2()] interface
  4008. ** instead of the routines described here.
  4009. **
  4010. ** These routines register callback functions that can be used for
  4011. ** tracing and profiling the execution of SQL statements.
  4012. **
  4013. ** ^The callback function registered by sqlite3_trace() is invoked at
  4014. ** various times when an SQL statement is being run by [sqlite3_step()].
  4015. ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
  4016. ** SQL statement text as the statement first begins executing.
  4017. ** ^(Additional sqlite3_trace() callbacks might occur
  4018. ** as each triggered subprogram is entered. The callbacks for triggers
  4019. ** contain a UTF-8 SQL comment that identifies the trigger.)^
  4020. **
  4021. ** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit
  4022. ** the length of [bound parameter] expansion in the output of sqlite3_trace().
  4023. **
  4024. ** ^The callback function registered by sqlite3_profile() is invoked
  4025. ** as each SQL statement finishes. ^The profile callback contains
  4026. ** the original statement text and an estimate of wall-clock time
  4027. ** of how long that statement took to run. ^The profile callback
  4028. ** time is in units of nanoseconds, however the current implementation
  4029. ** is only capable of millisecond resolution so the six least significant
  4030. ** digits in the time are meaningless. Future versions of SQLite
  4031. ** might provide greater resolution on the profiler callback. Invoking
  4032. ** either [sqlite3_trace()] or [sqlite3_trace_v2()] will cancel the
  4033. ** profile callback.
  4034. */
  4035. SQLITE_API SQLITE_DEPRECATED void *sqlite3_trace(sqlite3*,
  4036. void(*xTrace)(void*,const char*), void*);
  4037. SQLITE_API SQLITE_DEPRECATED void *sqlite3_profile(sqlite3*,
  4038. void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
  4039. /*
  4040. ** CAPI3REF: SQL Trace Event Codes
  4041. ** KEYWORDS: SQLITE_TRACE
  4042. **
  4043. ** These constants identify classes of events that can be monitored
  4044. ** using the [sqlite3_trace_v2()] tracing logic. The M argument
  4045. ** to [sqlite3_trace_v2(D,M,X,P)] is an OR-ed combination of one or more of
  4046. ** the following constants. ^The first argument to the trace callback
  4047. ** is one of the following constants.
  4048. **
  4049. ** New tracing constants may be added in future releases.
  4050. **
  4051. ** ^A trace callback has four arguments: xCallback(T,C,P,X).
  4052. ** ^The T argument is one of the integer type codes above.
  4053. ** ^The C argument is a copy of the context pointer passed in as the
  4054. ** fourth argument to [sqlite3_trace_v2()].
  4055. ** The P and X arguments are pointers whose meanings depend on T.
  4056. **
  4057. ** <dl>
  4058. ** [[SQLITE_TRACE_STMT]] <dt>SQLITE_TRACE_STMT</dt>
  4059. ** <dd>^An SQLITE_TRACE_STMT callback is invoked when a prepared statement
  4060. ** first begins running and possibly at other times during the
  4061. ** execution of the prepared statement, such as at the start of each
  4062. ** trigger subprogram. ^The P argument is a pointer to the
  4063. ** [prepared statement]. ^The X argument is a pointer to a string which
  4064. ** is the unexpanded SQL text of the prepared statement or an SQL comment
  4065. ** that indicates the invocation of a trigger. ^The callback can compute
  4066. ** the same text that would have been returned by the legacy [sqlite3_trace()]
  4067. ** interface by using the X argument when X begins with "--" and invoking
  4068. ** [sqlite3_expanded_sql(P)] otherwise.
  4069. **
  4070. ** [[SQLITE_TRACE_PROFILE]] <dt>SQLITE_TRACE_PROFILE</dt>
  4071. ** <dd>^An SQLITE_TRACE_PROFILE callback provides approximately the same
  4072. ** information as is provided by the [sqlite3_profile()] callback.
  4073. ** ^The P argument is a pointer to the [prepared statement] and the
  4074. ** X argument points to a 64-bit integer which is the estimated of
  4075. ** the number of nanosecond that the prepared statement took to run.
  4076. ** ^The SQLITE_TRACE_PROFILE callback is invoked when the statement finishes.
  4077. **
  4078. ** [[SQLITE_TRACE_ROW]] <dt>SQLITE_TRACE_ROW</dt>
  4079. ** <dd>^An SQLITE_TRACE_ROW callback is invoked whenever a prepared
  4080. ** statement generates a single row of result.
  4081. ** ^The P argument is a pointer to the [prepared statement] and the
  4082. ** X argument is unused.
  4083. **
  4084. ** [[SQLITE_TRACE_CLOSE]] <dt>SQLITE_TRACE_CLOSE</dt>
  4085. ** <dd>^An SQLITE_TRACE_CLOSE callback is invoked when a database
  4086. ** connection closes.
  4087. ** ^The P argument is a pointer to the [database connection] object
  4088. ** and the X argument is unused.
  4089. ** </dl>
  4090. */
  4091. #define SQLITE_TRACE_STMT 0x01
  4092. #define SQLITE_TRACE_PROFILE 0x02
  4093. #define SQLITE_TRACE_ROW 0x04
  4094. #define SQLITE_TRACE_CLOSE 0x08
  4095. /*
  4096. ** CAPI3REF: SQL Trace Hook
  4097. ** METHOD: sqlite3
  4098. **
  4099. ** ^The sqlite3_trace_v2(D,M,X,P) interface registers a trace callback
  4100. ** function X against [database connection] D, using property mask M
  4101. ** and context pointer P. ^If the X callback is
  4102. ** NULL or if the M mask is zero, then tracing is disabled. The
  4103. ** M argument should be the bitwise OR-ed combination of
  4104. ** zero or more [SQLITE_TRACE] constants.
  4105. **
  4106. ** ^Each call to either sqlite3_trace() or sqlite3_trace_v2() overrides
  4107. ** (cancels) any prior calls to sqlite3_trace() or sqlite3_trace_v2().
  4108. **
  4109. ** ^The X callback is invoked whenever any of the events identified by
  4110. ** mask M occur. ^The integer return value from the callback is currently
  4111. ** ignored, though this may change in future releases. Callback
  4112. ** implementations should return zero to ensure future compatibility.
  4113. **
  4114. ** ^A trace callback is invoked with four arguments: callback(T,C,P,X).
  4115. ** ^The T argument is one of the [SQLITE_TRACE]
  4116. ** constants to indicate why the callback was invoked.
  4117. ** ^The C argument is a copy of the context pointer.
  4118. ** The P and X arguments are pointers whose meanings depend on T.
  4119. **
  4120. ** The sqlite3_trace_v2() interface is intended to replace the legacy
  4121. ** interfaces [sqlite3_trace()] and [sqlite3_profile()], both of which
  4122. ** are deprecated.
  4123. */
  4124. SQLITE_API int sqlite3_trace_v2(
  4125. sqlite3*,
  4126. unsigned uMask,
  4127. int(*xCallback)(unsigned,void*,void*,void*),
  4128. void *pCtx
  4129. );
  4130. /*
  4131. ** CAPI3REF: Query Progress Callbacks
  4132. ** METHOD: sqlite3
  4133. **
  4134. ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
  4135. ** function X to be invoked periodically during long running calls to
  4136. ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
  4137. ** database connection D. An example use for this
  4138. ** interface is to keep a GUI updated during a large query.
  4139. **
  4140. ** ^The parameter P is passed through as the only parameter to the
  4141. ** callback function X. ^The parameter N is the approximate number of
  4142. ** [virtual machine instructions] that are evaluated between successive
  4143. ** invocations of the callback X. ^If N is less than one then the progress
  4144. ** handler is disabled.
  4145. **
  4146. ** ^Only a single progress handler may be defined at one time per
  4147. ** [database connection]; setting a new progress handler cancels the
  4148. ** old one. ^Setting parameter X to NULL disables the progress handler.
  4149. ** ^The progress handler is also disabled by setting N to a value less
  4150. ** than 1.
  4151. **
  4152. ** ^If the progress callback returns non-zero, the operation is
  4153. ** interrupted. This feature can be used to implement a
  4154. ** "Cancel" button on a GUI progress dialog box.
  4155. **
  4156. ** The progress handler callback must not do anything that will modify
  4157. ** the database connection that invoked the progress handler.
  4158. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  4159. ** database connections for the meaning of "modify" in this paragraph.
  4160. **
  4161. */
  4162. SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
  4163. /*
  4164. ** CAPI3REF: Opening A New Database Connection
  4165. ** CONSTRUCTOR: sqlite3
  4166. **
  4167. ** ^These routines open an SQLite database file as specified by the
  4168. ** filename argument. ^The filename argument is interpreted as UTF-8 for
  4169. ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
  4170. ** order for sqlite3_open16(). ^(A [database connection] handle is usually
  4171. ** returned in *ppDb, even if an error occurs. The only exception is that
  4172. ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
  4173. ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
  4174. ** object.)^ ^(If the database is opened (and/or created) successfully, then
  4175. ** [SQLITE_OK] is returned. Otherwise an [error code] is returned.)^ ^The
  4176. ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
  4177. ** an English language description of the error following a failure of any
  4178. ** of the sqlite3_open() routines.
  4179. **
  4180. ** ^The default encoding will be UTF-8 for databases created using
  4181. ** sqlite3_open() or sqlite3_open_v2(). ^The default encoding for databases
  4182. ** created using sqlite3_open16() will be UTF-16 in the native byte order.
  4183. **
  4184. ** Whether or not an error occurs when it is opened, resources
  4185. ** associated with the [database connection] handle should be released by
  4186. ** passing it to [sqlite3_close()] when it is no longer required.
  4187. **
  4188. ** The sqlite3_open_v2() interface works like sqlite3_open()
  4189. ** except that it accepts two additional parameters for additional control
  4190. ** over the new database connection. ^(The flags parameter to
  4191. ** sqlite3_open_v2() can take one of
  4192. ** the following three values, optionally combined with the
  4193. ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
  4194. ** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^
  4195. **
  4196. ** <dl>
  4197. ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
  4198. ** <dd>The database is opened in read-only mode. If the database does not
  4199. ** already exist, an error is returned.</dd>)^
  4200. **
  4201. ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
  4202. ** <dd>The database is opened for reading and writing if possible, or reading
  4203. ** only if the file is write protected by the operating system. In either
  4204. ** case the database must already exist, otherwise an error is returned.</dd>)^
  4205. **
  4206. ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
  4207. ** <dd>The database is opened for reading and writing, and is created if
  4208. ** it does not already exist. This is the behavior that is always used for
  4209. ** sqlite3_open() and sqlite3_open16().</dd>)^
  4210. ** </dl>
  4211. **
  4212. ** If the 3rd parameter to sqlite3_open_v2() is not one of the
  4213. ** combinations shown above optionally combined with other
  4214. ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
  4215. ** then the behavior is undefined.
  4216. **
  4217. ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
  4218. ** opens in the multi-thread [threading mode] as long as the single-thread
  4219. ** mode has not been set at compile-time or start-time. ^If the
  4220. ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
  4221. ** in the serialized [threading mode] unless single-thread was
  4222. ** previously selected at compile-time or start-time.
  4223. ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
  4224. ** eligible to use [shared cache mode], regardless of whether or not shared
  4225. ** cache is enabled using [sqlite3_enable_shared_cache()]. ^The
  4226. ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
  4227. ** participate in [shared cache mode] even if it is enabled.
  4228. **
  4229. ** ^The fourth parameter to sqlite3_open_v2() is the name of the
  4230. ** [sqlite3_vfs] object that defines the operating system interface that
  4231. ** the new database connection should use. ^If the fourth parameter is
  4232. ** a NULL pointer then the default [sqlite3_vfs] object is used.
  4233. **
  4234. ** ^If the filename is ":memory:", then a private, temporary in-memory database
  4235. ** is created for the connection. ^This in-memory database will vanish when
  4236. ** the database connection is closed. Future versions of SQLite might
  4237. ** make use of additional special filenames that begin with the ":" character.
  4238. ** It is recommended that when a database filename actually does begin with
  4239. ** a ":" character you should prefix the filename with a pathname such as
  4240. ** "./" to avoid ambiguity.
  4241. **
  4242. ** ^If the filename is an empty string, then a private, temporary
  4243. ** on-disk database will be created. ^This private database will be
  4244. ** automatically deleted as soon as the database connection is closed.
  4245. **
  4246. ** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
  4247. **
  4248. ** ^If [URI filename] interpretation is enabled, and the filename argument
  4249. ** begins with "file:", then the filename is interpreted as a URI. ^URI
  4250. ** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
  4251. ** set in the third argument to sqlite3_open_v2(), or if it has
  4252. ** been enabled globally using the [SQLITE_CONFIG_URI] option with the
  4253. ** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
  4254. ** URI filename interpretation is turned off
  4255. ** by default, but future releases of SQLite might enable URI filename
  4256. ** interpretation by default. See "[URI filenames]" for additional
  4257. ** information.
  4258. **
  4259. ** URI filenames are parsed according to RFC 3986. ^If the URI contains an
  4260. ** authority, then it must be either an empty string or the string
  4261. ** "localhost". ^If the authority is not an empty string or "localhost", an
  4262. ** error is returned to the caller. ^The fragment component of a URI, if
  4263. ** present, is ignored.
  4264. **
  4265. ** ^SQLite uses the path component of the URI as the name of the disk file
  4266. ** which contains the database. ^If the path begins with a '/' character,
  4267. ** then it is interpreted as an absolute path. ^If the path does not begin
  4268. ** with a '/' (meaning that the authority section is omitted from the URI)
  4269. ** then the path is interpreted as a relative path.
  4270. ** ^(On windows, the first component of an absolute path
  4271. ** is a drive specification (e.g. "C:").)^
  4272. **
  4273. ** [[core URI query parameters]]
  4274. ** The query component of a URI may contain parameters that are interpreted
  4275. ** either by SQLite itself, or by a [VFS | custom VFS implementation].
  4276. ** SQLite and its built-in [VFSes] interpret the
  4277. ** following query parameters:
  4278. **
  4279. ** <ul>
  4280. ** <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
  4281. ** a VFS object that provides the operating system interface that should
  4282. ** be used to access the database file on disk. ^If this option is set to
  4283. ** an empty string the default VFS object is used. ^Specifying an unknown
  4284. ** VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
  4285. ** present, then the VFS specified by the option takes precedence over
  4286. ** the value passed as the fourth parameter to sqlite3_open_v2().
  4287. **
  4288. ** <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",
  4289. ** "rwc", or "memory". Attempting to set it to any other value is
  4290. ** an error)^.
  4291. ** ^If "ro" is specified, then the database is opened for read-only
  4292. ** access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the
  4293. ** third argument to sqlite3_open_v2(). ^If the mode option is set to
  4294. ** "rw", then the database is opened for read-write (but not create)
  4295. ** access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had
  4296. ** been set. ^Value "rwc" is equivalent to setting both
  4297. ** SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE. ^If the mode option is
  4298. ** set to "memory" then a pure [in-memory database] that never reads
  4299. ** or writes from disk is used. ^It is an error to specify a value for
  4300. ** the mode parameter that is less restrictive than that specified by
  4301. ** the flags passed in the third parameter to sqlite3_open_v2().
  4302. **
  4303. ** <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
  4304. ** "private". ^Setting it to "shared" is equivalent to setting the
  4305. ** SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
  4306. ** sqlite3_open_v2(). ^Setting the cache parameter to "private" is
  4307. ** equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
  4308. ** ^If sqlite3_open_v2() is used and the "cache" parameter is present in
  4309. ** a URI filename, its value overrides any behavior requested by setting
  4310. ** SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
  4311. **
  4312. ** <li> <b>psow</b>: ^The psow parameter indicates whether or not the
  4313. ** [powersafe overwrite] property does or does not apply to the
  4314. ** storage media on which the database file resides.
  4315. **
  4316. ** <li> <b>nolock</b>: ^The nolock parameter is a boolean query parameter
  4317. ** which if set disables file locking in rollback journal modes. This
  4318. ** is useful for accessing a database on a filesystem that does not
  4319. ** support locking. Caution: Database corruption might result if two
  4320. ** or more processes write to the same database and any one of those
  4321. ** processes uses nolock=1.
  4322. **
  4323. ** <li> <b>immutable</b>: ^The immutable parameter is a boolean query
  4324. ** parameter that indicates that the database file is stored on
  4325. ** read-only media. ^When immutable is set, SQLite assumes that the
  4326. ** database file cannot be changed, even by a process with higher
  4327. ** privilege, and so the database is opened read-only and all locking
  4328. ** and change detection is disabled. Caution: Setting the immutable
  4329. ** property on a database file that does in fact change can result
  4330. ** in incorrect query results and/or [SQLITE_CORRUPT] errors.
  4331. ** See also: [SQLITE_IOCAP_IMMUTABLE].
  4332. **
  4333. ** </ul>
  4334. **
  4335. ** ^Specifying an unknown parameter in the query component of a URI is not an
  4336. ** error. Future versions of SQLite might understand additional query
  4337. ** parameters. See "[query parameters with special meaning to SQLite]" for
  4338. ** additional information.
  4339. **
  4340. ** [[URI filename examples]] <h3>URI filename examples</h3>
  4341. **
  4342. ** <table border="1" align=center cellpadding=5>
  4343. ** <tr><th> URI filenames <th> Results
  4344. ** <tr><td> file:data.db <td>
  4345. ** Open the file "data.db" in the current directory.
  4346. ** <tr><td> file:/home/fred/data.db<br>
  4347. ** file:///home/fred/data.db <br>
  4348. ** file://localhost/home/fred/data.db <br> <td>
  4349. ** Open the database file "/home/fred/data.db".
  4350. ** <tr><td> file://darkstar/home/fred/data.db <td>
  4351. ** An error. "darkstar" is not a recognized authority.
  4352. ** <tr><td style="white-space:nowrap">
  4353. ** file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
  4354. ** <td> Windows only: Open the file "data.db" on fred's desktop on drive
  4355. ** C:. Note that the %20 escaping in this example is not strictly
  4356. ** necessary - space characters can be used literally
  4357. ** in URI filenames.
  4358. ** <tr><td> file:data.db?mode=ro&cache=private <td>
  4359. ** Open file "data.db" in the current directory for read-only access.
  4360. ** Regardless of whether or not shared-cache mode is enabled by
  4361. ** default, use a private cache.
  4362. ** <tr><td> file:/home/fred/data.db?vfs=unix-dotfile <td>
  4363. ** Open file "/home/fred/data.db". Use the special VFS "unix-dotfile"
  4364. ** that uses dot-files in place of posix advisory locking.
  4365. ** <tr><td> file:data.db?mode=readonly <td>
  4366. ** An error. "readonly" is not a valid option for the "mode" parameter.
  4367. ** </table>
  4368. **
  4369. ** ^URI hexadecimal escape sequences (%HH) are supported within the path and
  4370. ** query components of a URI. A hexadecimal escape sequence consists of a
  4371. ** percent sign - "%" - followed by exactly two hexadecimal digits
  4372. ** specifying an octet value. ^Before the path or query components of a
  4373. ** URI filename are interpreted, they are encoded using UTF-8 and all
  4374. ** hexadecimal escape sequences replaced by a single byte containing the
  4375. ** corresponding octet. If this process generates an invalid UTF-8 encoding,
  4376. ** the results are undefined.
  4377. **
  4378. ** <b>Note to Windows users:</b> The encoding used for the filename argument
  4379. ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
  4380. ** codepage is currently defined. Filenames containing international
  4381. ** characters must be converted to UTF-8 prior to passing them into
  4382. ** sqlite3_open() or sqlite3_open_v2().
  4383. **
  4384. ** <b>Note to Windows Runtime users:</b> The temporary directory must be set
  4385. ** prior to calling sqlite3_open() or sqlite3_open_v2(). Otherwise, various
  4386. ** features that require the use of temporary files may fail.
  4387. **
  4388. ** See also: [sqlite3_temp_directory]
  4389. */
  4390. SQLITE_API int sqlite3_open(
  4391. const char *filename, /* Database filename (UTF-8) */
  4392. sqlite3 **ppDb /* OUT: SQLite db handle */
  4393. );
  4394. SQLITE_API int sqlite3_open16(
  4395. const void *filename, /* Database filename (UTF-16) */
  4396. sqlite3 **ppDb /* OUT: SQLite db handle */
  4397. );
  4398. SQLITE_API int sqlite3_open_v2(
  4399. const char *filename, /* Database filename (UTF-8) */
  4400. sqlite3 **ppDb, /* OUT: SQLite db handle */
  4401. int flags, /* Flags */
  4402. const char *zVfs /* Name of VFS module to use */
  4403. );
  4404. /*
  4405. ** CAPI3REF: Obtain Values For URI Parameters
  4406. **
  4407. ** These are utility routines, useful to VFS implementations, that check
  4408. ** to see if a database file was a URI that contained a specific query
  4409. ** parameter, and if so obtains the value of that query parameter.
  4410. **
  4411. ** If F is the database filename pointer passed into the xOpen() method of
  4412. ** a VFS implementation when the flags parameter to xOpen() has one or
  4413. ** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and
  4414. ** P is the name of the query parameter, then
  4415. ** sqlite3_uri_parameter(F,P) returns the value of the P
  4416. ** parameter if it exists or a NULL pointer if P does not appear as a
  4417. ** query parameter on F. If P is a query parameter of F
  4418. ** has no explicit value, then sqlite3_uri_parameter(F,P) returns
  4419. ** a pointer to an empty string.
  4420. **
  4421. ** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
  4422. ** parameter and returns true (1) or false (0) according to the value
  4423. ** of P. The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
  4424. ** value of query parameter P is one of "yes", "true", or "on" in any
  4425. ** case or if the value begins with a non-zero number. The
  4426. ** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
  4427. ** query parameter P is one of "no", "false", or "off" in any case or
  4428. ** if the value begins with a numeric zero. If P is not a query
  4429. ** parameter on F or if the value of P is does not match any of the
  4430. ** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
  4431. **
  4432. ** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
  4433. ** 64-bit signed integer and returns that integer, or D if P does not
  4434. ** exist. If the value of P is something other than an integer, then
  4435. ** zero is returned.
  4436. **
  4437. ** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
  4438. ** sqlite3_uri_boolean(F,P,B) returns B. If F is not a NULL pointer and
  4439. ** is not a database file pathname pointer that SQLite passed into the xOpen
  4440. ** VFS method, then the behavior of this routine is undefined and probably
  4441. ** undesirable.
  4442. **
  4443. ** See the [URI filename] documentation for additional information.
  4444. */
  4445. SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam);
  4446. SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
  4447. SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
  4448. /*
  4449. ** CAPI3REF: Error Codes And Messages
  4450. ** METHOD: sqlite3
  4451. **
  4452. ** ^If the most recent sqlite3_* API call associated with
  4453. ** [database connection] D failed, then the sqlite3_errcode(D) interface
  4454. ** returns the numeric [result code] or [extended result code] for that
  4455. ** API call.
  4456. ** ^The sqlite3_extended_errcode()
  4457. ** interface is the same except that it always returns the
  4458. ** [extended result code] even when extended result codes are
  4459. ** disabled.
  4460. **
  4461. ** The values returned by sqlite3_errcode() and/or
  4462. ** sqlite3_extended_errcode() might change with each API call.
  4463. ** Except, there are some interfaces that are guaranteed to never
  4464. ** change the value of the error code. The error-code preserving
  4465. ** interfaces are:
  4466. **
  4467. ** <ul>
  4468. ** <li> sqlite3_errcode()
  4469. ** <li> sqlite3_extended_errcode()
  4470. ** <li> sqlite3_errmsg()
  4471. ** <li> sqlite3_errmsg16()
  4472. ** </ul>
  4473. **
  4474. ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
  4475. ** text that describes the error, as either UTF-8 or UTF-16 respectively.
  4476. ** ^(Memory to hold the error message string is managed internally.
  4477. ** The application does not need to worry about freeing the result.
  4478. ** However, the error string might be overwritten or deallocated by
  4479. ** subsequent calls to other SQLite interface functions.)^
  4480. **
  4481. ** ^The sqlite3_errstr() interface returns the English-language text
  4482. ** that describes the [result code], as UTF-8.
  4483. ** ^(Memory to hold the error message string is managed internally
  4484. ** and must not be freed by the application)^.
  4485. **
  4486. ** When the serialized [threading mode] is in use, it might be the
  4487. ** case that a second error occurs on a separate thread in between
  4488. ** the time of the first error and the call to these interfaces.
  4489. ** When that happens, the second error will be reported since these
  4490. ** interfaces always report the most recent result. To avoid
  4491. ** this, each thread can obtain exclusive use of the [database connection] D
  4492. ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
  4493. ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
  4494. ** all calls to the interfaces listed here are completed.
  4495. **
  4496. ** If an interface fails with SQLITE_MISUSE, that means the interface
  4497. ** was invoked incorrectly by the application. In that case, the
  4498. ** error code and message may or may not be set.
  4499. */
  4500. SQLITE_API int sqlite3_errcode(sqlite3 *db);
  4501. SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
  4502. SQLITE_API const char *sqlite3_errmsg(sqlite3*);
  4503. SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
  4504. SQLITE_API const char *sqlite3_errstr(int);
  4505. /*
  4506. ** CAPI3REF: Prepared Statement Object
  4507. ** KEYWORDS: {prepared statement} {prepared statements}
  4508. **
  4509. ** An instance of this object represents a single SQL statement that
  4510. ** has been compiled into binary form and is ready to be evaluated.
  4511. **
  4512. ** Think of each SQL statement as a separate computer program. The
  4513. ** original SQL text is source code. A prepared statement object
  4514. ** is the compiled object code. All SQL must be converted into a
  4515. ** prepared statement before it can be run.
  4516. **
  4517. ** The life-cycle of a prepared statement object usually goes like this:
  4518. **
  4519. ** <ol>
  4520. ** <li> Create the prepared statement object using [sqlite3_prepare_v2()].
  4521. ** <li> Bind values to [parameters] using the sqlite3_bind_*()
  4522. ** interfaces.
  4523. ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
  4524. ** <li> Reset the prepared statement using [sqlite3_reset()] then go back
  4525. ** to step 2. Do this zero or more times.
  4526. ** <li> Destroy the object using [sqlite3_finalize()].
  4527. ** </ol>
  4528. */
  4529. typedef struct sqlite3_stmt sqlite3_stmt;
  4530. /*
  4531. ** CAPI3REF: Run-time Limits
  4532. ** METHOD: sqlite3
  4533. **
  4534. ** ^(This interface allows the size of various constructs to be limited
  4535. ** on a connection by connection basis. The first parameter is the
  4536. ** [database connection] whose limit is to be set or queried. The
  4537. ** second parameter is one of the [limit categories] that define a
  4538. ** class of constructs to be size limited. The third parameter is the
  4539. ** new limit for that construct.)^
  4540. **
  4541. ** ^If the new limit is a negative number, the limit is unchanged.
  4542. ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
  4543. ** [limits | hard upper bound]
  4544. ** set at compile-time by a C preprocessor macro called
  4545. ** [limits | SQLITE_MAX_<i>NAME</i>].
  4546. ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
  4547. ** ^Attempts to increase a limit above its hard upper bound are
  4548. ** silently truncated to the hard upper bound.
  4549. **
  4550. ** ^Regardless of whether or not the limit was changed, the
  4551. ** [sqlite3_limit()] interface returns the prior value of the limit.
  4552. ** ^Hence, to find the current value of a limit without changing it,
  4553. ** simply invoke this interface with the third parameter set to -1.
  4554. **
  4555. ** Run-time limits are intended for use in applications that manage
  4556. ** both their own internal database and also databases that are controlled
  4557. ** by untrusted external sources. An example application might be a
  4558. ** web browser that has its own databases for storing history and
  4559. ** separate databases controlled by JavaScript applications downloaded
  4560. ** off the Internet. The internal databases can be given the
  4561. ** large, default limits. Databases managed by external sources can
  4562. ** be given much smaller limits designed to prevent a denial of service
  4563. ** attack. Developers might also want to use the [sqlite3_set_authorizer()]
  4564. ** interface to further control untrusted SQL. The size of the database
  4565. ** created by an untrusted script can be contained using the
  4566. ** [max_page_count] [PRAGMA].
  4567. **
  4568. ** New run-time limit categories may be added in future releases.
  4569. */
  4570. SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
  4571. /*
  4572. ** CAPI3REF: Run-Time Limit Categories
  4573. ** KEYWORDS: {limit category} {*limit categories}
  4574. **
  4575. ** These constants define various performance limits
  4576. ** that can be lowered at run-time using [sqlite3_limit()].
  4577. ** The synopsis of the meanings of the various limits is shown below.
  4578. ** Additional information is available at [limits | Limits in SQLite].
  4579. **
  4580. ** <dl>
  4581. ** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
  4582. ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
  4583. **
  4584. ** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
  4585. ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
  4586. **
  4587. ** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
  4588. ** <dd>The maximum number of columns in a table definition or in the
  4589. ** result set of a [SELECT] or the maximum number of columns in an index
  4590. ** or in an ORDER BY or GROUP BY clause.</dd>)^
  4591. **
  4592. ** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
  4593. ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
  4594. **
  4595. ** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
  4596. ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
  4597. **
  4598. ** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
  4599. ** <dd>The maximum number of instructions in a virtual machine program
  4600. ** used to implement an SQL statement. If [sqlite3_prepare_v2()] or
  4601. ** the equivalent tries to allocate space for more than this many opcodes
  4602. ** in a single prepared statement, an SQLITE_NOMEM error is returned.</dd>)^
  4603. **
  4604. ** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
  4605. ** <dd>The maximum number of arguments on a function.</dd>)^
  4606. **
  4607. ** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
  4608. ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
  4609. **
  4610. ** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
  4611. ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
  4612. ** <dd>The maximum length of the pattern argument to the [LIKE] or
  4613. ** [GLOB] operators.</dd>)^
  4614. **
  4615. ** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
  4616. ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
  4617. ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
  4618. **
  4619. ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
  4620. ** <dd>The maximum depth of recursion for triggers.</dd>)^
  4621. **
  4622. ** [[SQLITE_LIMIT_WORKER_THREADS]] ^(<dt>SQLITE_LIMIT_WORKER_THREADS</dt>
  4623. ** <dd>The maximum number of auxiliary worker threads that a single
  4624. ** [prepared statement] may start.</dd>)^
  4625. ** </dl>
  4626. */
  4627. #define SQLITE_LIMIT_LENGTH 0
  4628. #define SQLITE_LIMIT_SQL_LENGTH 1
  4629. #define SQLITE_LIMIT_COLUMN 2
  4630. #define SQLITE_LIMIT_EXPR_DEPTH 3
  4631. #define SQLITE_LIMIT_COMPOUND_SELECT 4
  4632. #define SQLITE_LIMIT_VDBE_OP 5
  4633. #define SQLITE_LIMIT_FUNCTION_ARG 6
  4634. #define SQLITE_LIMIT_ATTACHED 7
  4635. #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8
  4636. #define SQLITE_LIMIT_VARIABLE_NUMBER 9
  4637. #define SQLITE_LIMIT_TRIGGER_DEPTH 10
  4638. #define SQLITE_LIMIT_WORKER_THREADS 11
  4639. /*
  4640. ** CAPI3REF: Prepare Flags
  4641. **
  4642. ** These constants define various flags that can be passed into
  4643. ** "prepFlags" parameter of the [sqlite3_prepare_v3()] and
  4644. ** [sqlite3_prepare16_v3()] interfaces.
  4645. **
  4646. ** New flags may be added in future releases of SQLite.
  4647. **
  4648. ** <dl>
  4649. ** [[SQLITE_PREPARE_PERSISTENT]] ^(<dt>SQLITE_PREPARE_PERSISTENT</dt>
  4650. ** <dd>The SQLITE_PREPARE_PERSISTENT flag is a hint to the query planner
  4651. ** that the prepared statement will be retained for a long time and
  4652. ** probably reused many times.)^ ^Without this flag, [sqlite3_prepare_v3()]
  4653. ** and [sqlite3_prepare16_v3()] assume that the prepared statement will
  4654. ** be used just once or at most a few times and then destroyed using
  4655. ** [sqlite3_finalize()] relatively soon. The current implementation acts
  4656. ** on this hint by avoiding the use of [lookaside memory] so as not to
  4657. ** deplete the limited store of lookaside memory. Future versions of
  4658. ** SQLite may act on this hint differently.
  4659. **
  4660. ** [[SQLITE_PREPARE_NORMALIZE]] <dt>SQLITE_PREPARE_NORMALIZE</dt>
  4661. ** <dd>The SQLITE_PREPARE_NORMALIZE flag is a no-op. This flag used
  4662. ** to be required for any prepared statement that wanted to use the
  4663. ** [sqlite3_normalized_sql()] interface. However, the
  4664. ** [sqlite3_normalized_sql()] interface is now available to all
  4665. ** prepared statements, regardless of whether or not they use this
  4666. ** flag.
  4667. **
  4668. ** [[SQLITE_PREPARE_NO_VTAB]] <dt>SQLITE_PREPARE_NO_VTAB</dt>
  4669. ** <dd>The SQLITE_PREPARE_NO_VTAB flag causes the SQL compiler
  4670. ** to return an error (error code SQLITE_ERROR) if the statement uses
  4671. ** any virtual tables.
  4672. ** </dl>
  4673. */
  4674. #define SQLITE_PREPARE_PERSISTENT 0x01
  4675. #define SQLITE_PREPARE_NORMALIZE 0x02
  4676. #define SQLITE_PREPARE_NO_VTAB 0x04
  4677. /*
  4678. ** CAPI3REF: Compiling An SQL Statement
  4679. ** KEYWORDS: {SQL statement compiler}
  4680. ** METHOD: sqlite3
  4681. ** CONSTRUCTOR: sqlite3_stmt
  4682. **
  4683. ** To execute an SQL statement, it must first be compiled into a byte-code
  4684. ** program using one of these routines. Or, in other words, these routines
  4685. ** are constructors for the [prepared statement] object.
  4686. **
  4687. ** The preferred routine to use is [sqlite3_prepare_v2()]. The
  4688. ** [sqlite3_prepare()] interface is legacy and should be avoided.
  4689. ** [sqlite3_prepare_v3()] has an extra "prepFlags" option that is used
  4690. ** for special purposes.
  4691. **
  4692. ** The use of the UTF-8 interfaces is preferred, as SQLite currently
  4693. ** does all parsing using UTF-8. The UTF-16 interfaces are provided
  4694. ** as a convenience. The UTF-16 interfaces work by converting the
  4695. ** input text into UTF-8, then invoking the corresponding UTF-8 interface.
  4696. **
  4697. ** The first argument, "db", is a [database connection] obtained from a
  4698. ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
  4699. ** [sqlite3_open16()]. The database connection must not have been closed.
  4700. **
  4701. ** The second argument, "zSql", is the statement to be compiled, encoded
  4702. ** as either UTF-8 or UTF-16. The sqlite3_prepare(), sqlite3_prepare_v2(),
  4703. ** and sqlite3_prepare_v3()
  4704. ** interfaces use UTF-8, and sqlite3_prepare16(), sqlite3_prepare16_v2(),
  4705. ** and sqlite3_prepare16_v3() use UTF-16.
  4706. **
  4707. ** ^If the nByte argument is negative, then zSql is read up to the
  4708. ** first zero terminator. ^If nByte is positive, then it is the
  4709. ** number of bytes read from zSql. ^If nByte is zero, then no prepared
  4710. ** statement is generated.
  4711. ** If the caller knows that the supplied string is nul-terminated, then
  4712. ** there is a small performance advantage to passing an nByte parameter that
  4713. ** is the number of bytes in the input string <i>including</i>
  4714. ** the nul-terminator.
  4715. **
  4716. ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
  4717. ** past the end of the first SQL statement in zSql. These routines only
  4718. ** compile the first statement in zSql, so *pzTail is left pointing to
  4719. ** what remains uncompiled.
  4720. **
  4721. ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
  4722. ** executed using [sqlite3_step()]. ^If there is an error, *ppStmt is set
  4723. ** to NULL. ^If the input text contains no SQL (if the input is an empty
  4724. ** string or a comment) then *ppStmt is set to NULL.
  4725. ** The calling procedure is responsible for deleting the compiled
  4726. ** SQL statement using [sqlite3_finalize()] after it has finished with it.
  4727. ** ppStmt may not be NULL.
  4728. **
  4729. ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
  4730. ** otherwise an [error code] is returned.
  4731. **
  4732. ** The sqlite3_prepare_v2(), sqlite3_prepare_v3(), sqlite3_prepare16_v2(),
  4733. ** and sqlite3_prepare16_v3() interfaces are recommended for all new programs.
  4734. ** The older interfaces (sqlite3_prepare() and sqlite3_prepare16())
  4735. ** are retained for backwards compatibility, but their use is discouraged.
  4736. ** ^In the "vX" interfaces, the prepared statement
  4737. ** that is returned (the [sqlite3_stmt] object) contains a copy of the
  4738. ** original SQL text. This causes the [sqlite3_step()] interface to
  4739. ** behave differently in three ways:
  4740. **
  4741. ** <ol>
  4742. ** <li>
  4743. ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
  4744. ** always used to do, [sqlite3_step()] will automatically recompile the SQL
  4745. ** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY]
  4746. ** retries will occur before sqlite3_step() gives up and returns an error.
  4747. ** </li>
  4748. **
  4749. ** <li>
  4750. ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
  4751. ** [error codes] or [extended error codes]. ^The legacy behavior was that
  4752. ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
  4753. ** and the application would have to make a second call to [sqlite3_reset()]
  4754. ** in order to find the underlying cause of the problem. With the "v2" prepare
  4755. ** interfaces, the underlying reason for the error is returned immediately.
  4756. ** </li>
  4757. **
  4758. ** <li>
  4759. ** ^If the specific value bound to [parameter | host parameter] in the
  4760. ** WHERE clause might influence the choice of query plan for a statement,
  4761. ** then the statement will be automatically recompiled, as if there had been
  4762. ** a schema change, on the first [sqlite3_step()] call following any change
  4763. ** to the [sqlite3_bind_text | bindings] of that [parameter].
  4764. ** ^The specific value of WHERE-clause [parameter] might influence the
  4765. ** choice of query plan if the parameter is the left-hand side of a [LIKE]
  4766. ** or [GLOB] operator or if the parameter is compared to an indexed column
  4767. ** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled.
  4768. ** </li>
  4769. ** </ol>
  4770. **
  4771. ** <p>^sqlite3_prepare_v3() differs from sqlite3_prepare_v2() only in having
  4772. ** the extra prepFlags parameter, which is a bit array consisting of zero or
  4773. ** more of the [SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_*] flags. ^The
  4774. ** sqlite3_prepare_v2() interface works exactly the same as
  4775. ** sqlite3_prepare_v3() with a zero prepFlags parameter.
  4776. */
  4777. SQLITE_API int sqlite3_prepare(
  4778. sqlite3 *db, /* Database handle */
  4779. const char *zSql, /* SQL statement, UTF-8 encoded */
  4780. int nByte, /* Maximum length of zSql in bytes. */
  4781. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  4782. const char **pzTail /* OUT: Pointer to unused portion of zSql */
  4783. );
  4784. SQLITE_API int sqlite3_prepare_v2(
  4785. sqlite3 *db, /* Database handle */
  4786. const char *zSql, /* SQL statement, UTF-8 encoded */
  4787. int nByte, /* Maximum length of zSql in bytes. */
  4788. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  4789. const char **pzTail /* OUT: Pointer to unused portion of zSql */
  4790. );
  4791. SQLITE_API int sqlite3_prepare_v3(
  4792. sqlite3 *db, /* Database handle */
  4793. const char *zSql, /* SQL statement, UTF-8 encoded */
  4794. int nByte, /* Maximum length of zSql in bytes. */
  4795. unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_ flags */
  4796. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  4797. const char **pzTail /* OUT: Pointer to unused portion of zSql */
  4798. );
  4799. SQLITE_API int sqlite3_prepare16(
  4800. sqlite3 *db, /* Database handle */
  4801. const void *zSql, /* SQL statement, UTF-16 encoded */
  4802. int nByte, /* Maximum length of zSql in bytes. */
  4803. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  4804. const void **pzTail /* OUT: Pointer to unused portion of zSql */
  4805. );
  4806. SQLITE_API int sqlite3_prepare16_v2(
  4807. sqlite3 *db, /* Database handle */
  4808. const void *zSql, /* SQL statement, UTF-16 encoded */
  4809. int nByte, /* Maximum length of zSql in bytes. */
  4810. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  4811. const void **pzTail /* OUT: Pointer to unused portion of zSql */
  4812. );
  4813. SQLITE_API int sqlite3_prepare16_v3(
  4814. sqlite3 *db, /* Database handle */
  4815. const void *zSql, /* SQL statement, UTF-16 encoded */
  4816. int nByte, /* Maximum length of zSql in bytes. */
  4817. unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_ flags */
  4818. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  4819. const void **pzTail /* OUT: Pointer to unused portion of zSql */
  4820. );
  4821. /*
  4822. ** CAPI3REF: Retrieving Statement SQL
  4823. ** METHOD: sqlite3_stmt
  4824. **
  4825. ** ^The sqlite3_sql(P) interface returns a pointer to a copy of the UTF-8
  4826. ** SQL text used to create [prepared statement] P if P was
  4827. ** created by [sqlite3_prepare_v2()], [sqlite3_prepare_v3()],
  4828. ** [sqlite3_prepare16_v2()], or [sqlite3_prepare16_v3()].
  4829. ** ^The sqlite3_expanded_sql(P) interface returns a pointer to a UTF-8
  4830. ** string containing the SQL text of prepared statement P with
  4831. ** [bound parameters] expanded.
  4832. ** ^The sqlite3_normalized_sql(P) interface returns a pointer to a UTF-8
  4833. ** string containing the normalized SQL text of prepared statement P. The
  4834. ** semantics used to normalize a SQL statement are unspecified and subject
  4835. ** to change. At a minimum, literal values will be replaced with suitable
  4836. ** placeholders.
  4837. **
  4838. ** ^(For example, if a prepared statement is created using the SQL
  4839. ** text "SELECT $abc,:xyz" and if parameter $abc is bound to integer 2345
  4840. ** and parameter :xyz is unbound, then sqlite3_sql() will return
  4841. ** the original string, "SELECT $abc,:xyz" but sqlite3_expanded_sql()
  4842. ** will return "SELECT 2345,NULL".)^
  4843. **
  4844. ** ^The sqlite3_expanded_sql() interface returns NULL if insufficient memory
  4845. ** is available to hold the result, or if the result would exceed the
  4846. ** the maximum string length determined by the [SQLITE_LIMIT_LENGTH].
  4847. **
  4848. ** ^The [SQLITE_TRACE_SIZE_LIMIT] compile-time option limits the size of
  4849. ** bound parameter expansions. ^The [SQLITE_OMIT_TRACE] compile-time
  4850. ** option causes sqlite3_expanded_sql() to always return NULL.
  4851. **
  4852. ** ^The strings returned by sqlite3_sql(P) and sqlite3_normalized_sql(P)
  4853. ** are managed by SQLite and are automatically freed when the prepared
  4854. ** statement is finalized.
  4855. ** ^The string returned by sqlite3_expanded_sql(P), on the other hand,
  4856. ** is obtained from [sqlite3_malloc()] and must be free by the application
  4857. ** by passing it to [sqlite3_free()].
  4858. */
  4859. SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
  4860. SQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt);
  4861. SQLITE_API const char *sqlite3_normalized_sql(sqlite3_stmt *pStmt);
  4862. /*
  4863. ** CAPI3REF: Determine If An SQL Statement Writes The Database
  4864. ** METHOD: sqlite3_stmt
  4865. **
  4866. ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
  4867. ** and only if the [prepared statement] X makes no direct changes to
  4868. ** the content of the database file.
  4869. **
  4870. ** Note that [application-defined SQL functions] or
  4871. ** [virtual tables] might change the database indirectly as a side effect.
  4872. ** ^(For example, if an application defines a function "eval()" that
  4873. ** calls [sqlite3_exec()], then the following SQL statement would
  4874. ** change the database file through side-effects:
  4875. **
  4876. ** <blockquote><pre>
  4877. ** SELECT eval('DELETE FROM t1') FROM t2;
  4878. ** </pre></blockquote>
  4879. **
  4880. ** But because the [SELECT] statement does not change the database file
  4881. ** directly, sqlite3_stmt_readonly() would still return true.)^
  4882. **
  4883. ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
  4884. ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
  4885. ** since the statements themselves do not actually modify the database but
  4886. ** rather they control the timing of when other statements modify the
  4887. ** database. ^The [ATTACH] and [DETACH] statements also cause
  4888. ** sqlite3_stmt_readonly() to return true since, while those statements
  4889. ** change the configuration of a database connection, they do not make
  4890. ** changes to the content of the database files on disk.
  4891. ** ^The sqlite3_stmt_readonly() interface returns true for [BEGIN] since
  4892. ** [BEGIN] merely sets internal flags, but the [BEGIN|BEGIN IMMEDIATE] and
  4893. ** [BEGIN|BEGIN EXCLUSIVE] commands do touch the database and so
  4894. ** sqlite3_stmt_readonly() returns false for those commands.
  4895. */
  4896. SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
  4897. /*
  4898. ** CAPI3REF: Query The EXPLAIN Setting For A Prepared Statement
  4899. ** METHOD: sqlite3_stmt
  4900. **
  4901. ** ^The sqlite3_stmt_isexplain(S) interface returns 1 if the
  4902. ** prepared statement S is an EXPLAIN statement, or 2 if the
  4903. ** statement S is an EXPLAIN QUERY PLAN.
  4904. ** ^The sqlite3_stmt_isexplain(S) interface returns 0 if S is
  4905. ** an ordinary statement or a NULL pointer.
  4906. */
  4907. SQLITE_API int sqlite3_stmt_isexplain(sqlite3_stmt *pStmt);
  4908. /*
  4909. ** CAPI3REF: Determine If A Prepared Statement Has Been Reset
  4910. ** METHOD: sqlite3_stmt
  4911. **
  4912. ** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
  4913. ** [prepared statement] S has been stepped at least once using
  4914. ** [sqlite3_step(S)] but has neither run to completion (returned
  4915. ** [SQLITE_DONE] from [sqlite3_step(S)]) nor
  4916. ** been reset using [sqlite3_reset(S)]. ^The sqlite3_stmt_busy(S)
  4917. ** interface returns false if S is a NULL pointer. If S is not a
  4918. ** NULL pointer and is not a pointer to a valid [prepared statement]
  4919. ** object, then the behavior is undefined and probably undesirable.
  4920. **
  4921. ** This interface can be used in combination [sqlite3_next_stmt()]
  4922. ** to locate all prepared statements associated with a database
  4923. ** connection that are in need of being reset. This can be used,
  4924. ** for example, in diagnostic routines to search for prepared
  4925. ** statements that are holding a transaction open.
  4926. */
  4927. SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);
  4928. /*
  4929. ** CAPI3REF: Dynamically Typed Value Object
  4930. ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
  4931. **
  4932. ** SQLite uses the sqlite3_value object to represent all values
  4933. ** that can be stored in a database table. SQLite uses dynamic typing
  4934. ** for the values it stores. ^Values stored in sqlite3_value objects
  4935. ** can be integers, floating point values, strings, BLOBs, or NULL.
  4936. **
  4937. ** An sqlite3_value object may be either "protected" or "unprotected".
  4938. ** Some interfaces require a protected sqlite3_value. Other interfaces
  4939. ** will accept either a protected or an unprotected sqlite3_value.
  4940. ** Every interface that accepts sqlite3_value arguments specifies
  4941. ** whether or not it requires a protected sqlite3_value. The
  4942. ** [sqlite3_value_dup()] interface can be used to construct a new
  4943. ** protected sqlite3_value from an unprotected sqlite3_value.
  4944. **
  4945. ** The terms "protected" and "unprotected" refer to whether or not
  4946. ** a mutex is held. An internal mutex is held for a protected
  4947. ** sqlite3_value object but no mutex is held for an unprotected
  4948. ** sqlite3_value object. If SQLite is compiled to be single-threaded
  4949. ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
  4950. ** or if SQLite is run in one of reduced mutex modes
  4951. ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
  4952. ** then there is no distinction between protected and unprotected
  4953. ** sqlite3_value objects and they can be used interchangeably. However,
  4954. ** for maximum code portability it is recommended that applications
  4955. ** still make the distinction between protected and unprotected
  4956. ** sqlite3_value objects even when not strictly required.
  4957. **
  4958. ** ^The sqlite3_value objects that are passed as parameters into the
  4959. ** implementation of [application-defined SQL functions] are protected.
  4960. ** ^The sqlite3_value object returned by
  4961. ** [sqlite3_column_value()] is unprotected.
  4962. ** Unprotected sqlite3_value objects may only be used as arguments
  4963. ** to [sqlite3_result_value()], [sqlite3_bind_value()], and
  4964. ** [sqlite3_value_dup()].
  4965. ** The [sqlite3_value_blob | sqlite3_value_type()] family of
  4966. ** interfaces require protected sqlite3_value objects.
  4967. */
  4968. typedef struct sqlite3_value sqlite3_value;
  4969. /*
  4970. ** CAPI3REF: SQL Function Context Object
  4971. **
  4972. ** The context in which an SQL function executes is stored in an
  4973. ** sqlite3_context object. ^A pointer to an sqlite3_context object
  4974. ** is always first parameter to [application-defined SQL functions].
  4975. ** The application-defined SQL function implementation will pass this
  4976. ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
  4977. ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
  4978. ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
  4979. ** and/or [sqlite3_set_auxdata()].
  4980. */
  4981. typedef struct sqlite3_context sqlite3_context;
  4982. /*
  4983. ** CAPI3REF: Binding Values To Prepared Statements
  4984. ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
  4985. ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
  4986. ** METHOD: sqlite3_stmt
  4987. **
  4988. ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
  4989. ** literals may be replaced by a [parameter] that matches one of following
  4990. ** templates:
  4991. **
  4992. ** <ul>
  4993. ** <li> ?
  4994. ** <li> ?NNN
  4995. ** <li> :VVV
  4996. ** <li> @VVV
  4997. ** <li> $VVV
  4998. ** </ul>
  4999. **
  5000. ** In the templates above, NNN represents an integer literal,
  5001. ** and VVV represents an alphanumeric identifier.)^ ^The values of these
  5002. ** parameters (also called "host parameter names" or "SQL parameters")
  5003. ** can be set using the sqlite3_bind_*() routines defined here.
  5004. **
  5005. ** ^The first argument to the sqlite3_bind_*() routines is always
  5006. ** a pointer to the [sqlite3_stmt] object returned from
  5007. ** [sqlite3_prepare_v2()] or its variants.
  5008. **
  5009. ** ^The second argument is the index of the SQL parameter to be set.
  5010. ** ^The leftmost SQL parameter has an index of 1. ^When the same named
  5011. ** SQL parameter is used more than once, second and subsequent
  5012. ** occurrences have the same index as the first occurrence.
  5013. ** ^The index for named parameters can be looked up using the
  5014. ** [sqlite3_bind_parameter_index()] API if desired. ^The index
  5015. ** for "?NNN" parameters is the value of NNN.
  5016. ** ^The NNN value must be between 1 and the [sqlite3_limit()]
  5017. ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
  5018. **
  5019. ** ^The third argument is the value to bind to the parameter.
  5020. ** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16()
  5021. ** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter
  5022. ** is ignored and the end result is the same as sqlite3_bind_null().
  5023. **
  5024. ** ^(In those routines that have a fourth argument, its value is the
  5025. ** number of bytes in the parameter. To be clear: the value is the
  5026. ** number of <u>bytes</u> in the value, not the number of characters.)^
  5027. ** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()
  5028. ** is negative, then the length of the string is
  5029. ** the number of bytes up to the first zero terminator.
  5030. ** If the fourth parameter to sqlite3_bind_blob() is negative, then
  5031. ** the behavior is undefined.
  5032. ** If a non-negative fourth parameter is provided to sqlite3_bind_text()
  5033. ** or sqlite3_bind_text16() or sqlite3_bind_text64() then
  5034. ** that parameter must be the byte offset
  5035. ** where the NUL terminator would occur assuming the string were NUL
  5036. ** terminated. If any NUL characters occur at byte offsets less than
  5037. ** the value of the fourth parameter then the resulting string value will
  5038. ** contain embedded NULs. The result of expressions involving strings
  5039. ** with embedded NULs is undefined.
  5040. **
  5041. ** ^The fifth argument to the BLOB and string binding interfaces
  5042. ** is a destructor used to dispose of the BLOB or
  5043. ** string after SQLite has finished with it. ^The destructor is called
  5044. ** to dispose of the BLOB or string even if the call to the bind API fails,
  5045. ** except the destructor is not called if the third parameter is a NULL
  5046. ** pointer or the fourth parameter is negative.
  5047. ** ^If the fifth argument is
  5048. ** the special value [SQLITE_STATIC], then SQLite assumes that the
  5049. ** information is in static, unmanaged space and does not need to be freed.
  5050. ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
  5051. ** SQLite makes its own private copy of the data immediately, before
  5052. ** the sqlite3_bind_*() routine returns.
  5053. **
  5054. ** ^The sixth argument to sqlite3_bind_text64() must be one of
  5055. ** [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE]
  5056. ** to specify the encoding of the text in the third parameter. If
  5057. ** the sixth argument to sqlite3_bind_text64() is not one of the
  5058. ** allowed values shown above, or if the text encoding is different
  5059. ** from the encoding specified by the sixth parameter, then the behavior
  5060. ** is undefined.
  5061. **
  5062. ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
  5063. ** is filled with zeroes. ^A zeroblob uses a fixed amount of memory
  5064. ** (just an integer to hold its size) while it is being processed.
  5065. ** Zeroblobs are intended to serve as placeholders for BLOBs whose
  5066. ** content is later written using
  5067. ** [sqlite3_blob_open | incremental BLOB I/O] routines.
  5068. ** ^A negative value for the zeroblob results in a zero-length BLOB.
  5069. **
  5070. ** ^The sqlite3_bind_pointer(S,I,P,T,D) routine causes the I-th parameter in
  5071. ** [prepared statement] S to have an SQL value of NULL, but to also be
  5072. ** associated with the pointer P of type T. ^D is either a NULL pointer or
  5073. ** a pointer to a destructor function for P. ^SQLite will invoke the
  5074. ** destructor D with a single argument of P when it is finished using
  5075. ** P. The T parameter should be a static string, preferably a string
  5076. ** literal. The sqlite3_bind_pointer() routine is part of the
  5077. ** [pointer passing interface] added for SQLite 3.20.0.
  5078. **
  5079. ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
  5080. ** for the [prepared statement] or with a prepared statement for which
  5081. ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
  5082. ** then the call will return [SQLITE_MISUSE]. If any sqlite3_bind_()
  5083. ** routine is passed a [prepared statement] that has been finalized, the
  5084. ** result is undefined and probably harmful.
  5085. **
  5086. ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
  5087. ** ^Unbound parameters are interpreted as NULL.
  5088. **
  5089. ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
  5090. ** [error code] if anything goes wrong.
  5091. ** ^[SQLITE_TOOBIG] might be returned if the size of a string or BLOB
  5092. ** exceeds limits imposed by [sqlite3_limit]([SQLITE_LIMIT_LENGTH]) or
  5093. ** [SQLITE_MAX_LENGTH].
  5094. ** ^[SQLITE_RANGE] is returned if the parameter
  5095. ** index is out of range. ^[SQLITE_NOMEM] is returned if malloc() fails.
  5096. **
  5097. ** See also: [sqlite3_bind_parameter_count()],
  5098. ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
  5099. */
  5100. SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
  5101. SQLITE_API int sqlite3_bind_blob64(sqlite3_stmt*, int, const void*, sqlite3_uint64,
  5102. void(*)(void*));
  5103. SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
  5104. SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
  5105. SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
  5106. SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
  5107. SQLITE_API int sqlite3_bind_text(sqlite3_stmt*,int,const char*,int,void(*)(void*));
  5108. SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
  5109. SQLITE_API int sqlite3_bind_text64(sqlite3_stmt*, int, const char*, sqlite3_uint64,
  5110. void(*)(void*), unsigned char encoding);
  5111. SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
  5112. SQLITE_API int sqlite3_bind_pointer(sqlite3_stmt*, int, void*, const char*,void(*)(void*));
  5113. SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
  5114. SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt*, int, sqlite3_uint64);
  5115. /*
  5116. ** CAPI3REF: Number Of SQL Parameters
  5117. ** METHOD: sqlite3_stmt
  5118. **
  5119. ** ^This routine can be used to find the number of [SQL parameters]
  5120. ** in a [prepared statement]. SQL parameters are tokens of the
  5121. ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
  5122. ** placeholders for values that are [sqlite3_bind_blob | bound]
  5123. ** to the parameters at a later time.
  5124. **
  5125. ** ^(This routine actually returns the index of the largest (rightmost)
  5126. ** parameter. For all forms except ?NNN, this will correspond to the
  5127. ** number of unique parameters. If parameters of the ?NNN form are used,
  5128. ** there may be gaps in the list.)^
  5129. **
  5130. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  5131. ** [sqlite3_bind_parameter_name()], and
  5132. ** [sqlite3_bind_parameter_index()].
  5133. */
  5134. SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
  5135. /*
  5136. ** CAPI3REF: Name Of A Host Parameter
  5137. ** METHOD: sqlite3_stmt
  5138. **
  5139. ** ^The sqlite3_bind_parameter_name(P,N) interface returns
  5140. ** the name of the N-th [SQL parameter] in the [prepared statement] P.
  5141. ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
  5142. ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
  5143. ** respectively.
  5144. ** In other words, the initial ":" or "$" or "@" or "?"
  5145. ** is included as part of the name.)^
  5146. ** ^Parameters of the form "?" without a following integer have no name
  5147. ** and are referred to as "nameless" or "anonymous parameters".
  5148. **
  5149. ** ^The first host parameter has an index of 1, not 0.
  5150. **
  5151. ** ^If the value N is out of range or if the N-th parameter is
  5152. ** nameless, then NULL is returned. ^The returned string is
  5153. ** always in UTF-8 encoding even if the named parameter was
  5154. ** originally specified as UTF-16 in [sqlite3_prepare16()],
  5155. ** [sqlite3_prepare16_v2()], or [sqlite3_prepare16_v3()].
  5156. **
  5157. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  5158. ** [sqlite3_bind_parameter_count()], and
  5159. ** [sqlite3_bind_parameter_index()].
  5160. */
  5161. SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
  5162. /*
  5163. ** CAPI3REF: Index Of A Parameter With A Given Name
  5164. ** METHOD: sqlite3_stmt
  5165. **
  5166. ** ^Return the index of an SQL parameter given its name. ^The
  5167. ** index value returned is suitable for use as the second
  5168. ** parameter to [sqlite3_bind_blob|sqlite3_bind()]. ^A zero
  5169. ** is returned if no matching parameter is found. ^The parameter
  5170. ** name must be given in UTF-8 even if the original statement
  5171. ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()] or
  5172. ** [sqlite3_prepare16_v3()].
  5173. **
  5174. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  5175. ** [sqlite3_bind_parameter_count()], and
  5176. ** [sqlite3_bind_parameter_name()].
  5177. */
  5178. SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
  5179. /*
  5180. ** CAPI3REF: Reset All Bindings On A Prepared Statement
  5181. ** METHOD: sqlite3_stmt
  5182. **
  5183. ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
  5184. ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
  5185. ** ^Use this routine to reset all host parameters to NULL.
  5186. */
  5187. SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
  5188. /*
  5189. ** CAPI3REF: Number Of Columns In A Result Set
  5190. ** METHOD: sqlite3_stmt
  5191. **
  5192. ** ^Return the number of columns in the result set returned by the
  5193. ** [prepared statement]. ^If this routine returns 0, that means the
  5194. ** [prepared statement] returns no data (for example an [UPDATE]).
  5195. ** ^However, just because this routine returns a positive number does not
  5196. ** mean that one or more rows of data will be returned. ^A SELECT statement
  5197. ** will always have a positive sqlite3_column_count() but depending on the
  5198. ** WHERE clause constraints and the table content, it might return no rows.
  5199. **
  5200. ** See also: [sqlite3_data_count()]
  5201. */
  5202. SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
  5203. /*
  5204. ** CAPI3REF: Column Names In A Result Set
  5205. ** METHOD: sqlite3_stmt
  5206. **
  5207. ** ^These routines return the name assigned to a particular column
  5208. ** in the result set of a [SELECT] statement. ^The sqlite3_column_name()
  5209. ** interface returns a pointer to a zero-terminated UTF-8 string
  5210. ** and sqlite3_column_name16() returns a pointer to a zero-terminated
  5211. ** UTF-16 string. ^The first parameter is the [prepared statement]
  5212. ** that implements the [SELECT] statement. ^The second parameter is the
  5213. ** column number. ^The leftmost column is number 0.
  5214. **
  5215. ** ^The returned string pointer is valid until either the [prepared statement]
  5216. ** is destroyed by [sqlite3_finalize()] or until the statement is automatically
  5217. ** reprepared by the first call to [sqlite3_step()] for a particular run
  5218. ** or until the next call to
  5219. ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
  5220. **
  5221. ** ^If sqlite3_malloc() fails during the processing of either routine
  5222. ** (for example during a conversion from UTF-8 to UTF-16) then a
  5223. ** NULL pointer is returned.
  5224. **
  5225. ** ^The name of a result column is the value of the "AS" clause for
  5226. ** that column, if there is an AS clause. If there is no AS clause
  5227. ** then the name of the column is unspecified and may change from
  5228. ** one release of SQLite to the next.
  5229. */
  5230. SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
  5231. SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
  5232. /*
  5233. ** CAPI3REF: Source Of Data In A Query Result
  5234. ** METHOD: sqlite3_stmt
  5235. **
  5236. ** ^These routines provide a means to determine the database, table, and
  5237. ** table column that is the origin of a particular result column in
  5238. ** [SELECT] statement.
  5239. ** ^The name of the database or table or column can be returned as
  5240. ** either a UTF-8 or UTF-16 string. ^The _database_ routines return
  5241. ** the database name, the _table_ routines return the table name, and
  5242. ** the origin_ routines return the column name.
  5243. ** ^The returned string is valid until the [prepared statement] is destroyed
  5244. ** using [sqlite3_finalize()] or until the statement is automatically
  5245. ** reprepared by the first call to [sqlite3_step()] for a particular run
  5246. ** or until the same information is requested
  5247. ** again in a different encoding.
  5248. **
  5249. ** ^The names returned are the original un-aliased names of the
  5250. ** database, table, and column.
  5251. **
  5252. ** ^The first argument to these interfaces is a [prepared statement].
  5253. ** ^These functions return information about the Nth result column returned by
  5254. ** the statement, where N is the second function argument.
  5255. ** ^The left-most column is column 0 for these routines.
  5256. **
  5257. ** ^If the Nth column returned by the statement is an expression or
  5258. ** subquery and is not a column value, then all of these functions return
  5259. ** NULL. ^These routine might also return NULL if a memory allocation error
  5260. ** occurs. ^Otherwise, they return the name of the attached database, table,
  5261. ** or column that query result column was extracted from.
  5262. **
  5263. ** ^As with all other SQLite APIs, those whose names end with "16" return
  5264. ** UTF-16 encoded strings and the other functions return UTF-8.
  5265. **
  5266. ** ^These APIs are only available if the library was compiled with the
  5267. ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
  5268. **
  5269. ** If two or more threads call one or more of these routines against the same
  5270. ** prepared statement and column at the same time then the results are
  5271. ** undefined.
  5272. **
  5273. ** If two or more threads call one or more
  5274. ** [sqlite3_column_database_name | column metadata interfaces]
  5275. ** for the same [prepared statement] and result column
  5276. ** at the same time then the results are undefined.
  5277. */
  5278. SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
  5279. SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
  5280. SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
  5281. SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
  5282. SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
  5283. SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
  5284. /*
  5285. ** CAPI3REF: Declared Datatype Of A Query Result
  5286. ** METHOD: sqlite3_stmt
  5287. **
  5288. ** ^(The first parameter is a [prepared statement].
  5289. ** If this statement is a [SELECT] statement and the Nth column of the
  5290. ** returned result set of that [SELECT] is a table column (not an
  5291. ** expression or subquery) then the declared type of the table
  5292. ** column is returned.)^ ^If the Nth column of the result set is an
  5293. ** expression or subquery, then a NULL pointer is returned.
  5294. ** ^The returned string is always UTF-8 encoded.
  5295. **
  5296. ** ^(For example, given the database schema:
  5297. **
  5298. ** CREATE TABLE t1(c1 VARIANT);
  5299. **
  5300. ** and the following statement to be compiled:
  5301. **
  5302. ** SELECT c1 + 1, c1 FROM t1;
  5303. **
  5304. ** this routine would return the string "VARIANT" for the second result
  5305. ** column (i==1), and a NULL pointer for the first result column (i==0).)^
  5306. **
  5307. ** ^SQLite uses dynamic run-time typing. ^So just because a column
  5308. ** is declared to contain a particular type does not mean that the
  5309. ** data stored in that column is of the declared type. SQLite is
  5310. ** strongly typed, but the typing is dynamic not static. ^Type
  5311. ** is associated with individual values, not with the containers
  5312. ** used to hold those values.
  5313. */
  5314. SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
  5315. SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
  5316. /*
  5317. ** CAPI3REF: Evaluate An SQL Statement
  5318. ** METHOD: sqlite3_stmt
  5319. **
  5320. ** After a [prepared statement] has been prepared using any of
  5321. ** [sqlite3_prepare_v2()], [sqlite3_prepare_v3()], [sqlite3_prepare16_v2()],
  5322. ** or [sqlite3_prepare16_v3()] or one of the legacy
  5323. ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
  5324. ** must be called one or more times to evaluate the statement.
  5325. **
  5326. ** The details of the behavior of the sqlite3_step() interface depend
  5327. ** on whether the statement was prepared using the newer "vX" interfaces
  5328. ** [sqlite3_prepare_v3()], [sqlite3_prepare_v2()], [sqlite3_prepare16_v3()],
  5329. ** [sqlite3_prepare16_v2()] or the older legacy
  5330. ** interfaces [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the
  5331. ** new "vX" interface is recommended for new applications but the legacy
  5332. ** interface will continue to be supported.
  5333. **
  5334. ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
  5335. ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
  5336. ** ^With the "v2" interface, any of the other [result codes] or
  5337. ** [extended result codes] might be returned as well.
  5338. **
  5339. ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
  5340. ** database locks it needs to do its job. ^If the statement is a [COMMIT]
  5341. ** or occurs outside of an explicit transaction, then you can retry the
  5342. ** statement. If the statement is not a [COMMIT] and occurs within an
  5343. ** explicit transaction then you should rollback the transaction before
  5344. ** continuing.
  5345. **
  5346. ** ^[SQLITE_DONE] means that the statement has finished executing
  5347. ** successfully. sqlite3_step() should not be called again on this virtual
  5348. ** machine without first calling [sqlite3_reset()] to reset the virtual
  5349. ** machine back to its initial state.
  5350. **
  5351. ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
  5352. ** is returned each time a new row of data is ready for processing by the
  5353. ** caller. The values may be accessed using the [column access functions].
  5354. ** sqlite3_step() is called again to retrieve the next row of data.
  5355. **
  5356. ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
  5357. ** violation) has occurred. sqlite3_step() should not be called again on
  5358. ** the VM. More information may be found by calling [sqlite3_errmsg()].
  5359. ** ^With the legacy interface, a more specific error code (for example,
  5360. ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
  5361. ** can be obtained by calling [sqlite3_reset()] on the
  5362. ** [prepared statement]. ^In the "v2" interface,
  5363. ** the more specific error code is returned directly by sqlite3_step().
  5364. **
  5365. ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
  5366. ** Perhaps it was called on a [prepared statement] that has
  5367. ** already been [sqlite3_finalize | finalized] or on one that had
  5368. ** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could
  5369. ** be the case that the same database connection is being used by two or
  5370. ** more threads at the same moment in time.
  5371. **
  5372. ** For all versions of SQLite up to and including 3.6.23.1, a call to
  5373. ** [sqlite3_reset()] was required after sqlite3_step() returned anything
  5374. ** other than [SQLITE_ROW] before any subsequent invocation of
  5375. ** sqlite3_step(). Failure to reset the prepared statement using
  5376. ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
  5377. ** sqlite3_step(). But after [version 3.6.23.1] ([dateof:3.6.23.1],
  5378. ** sqlite3_step() began
  5379. ** calling [sqlite3_reset()] automatically in this circumstance rather
  5380. ** than returning [SQLITE_MISUSE]. This is not considered a compatibility
  5381. ** break because any application that ever receives an SQLITE_MISUSE error
  5382. ** is broken by definition. The [SQLITE_OMIT_AUTORESET] compile-time option
  5383. ** can be used to restore the legacy behavior.
  5384. **
  5385. ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
  5386. ** API always returns a generic error code, [SQLITE_ERROR], following any
  5387. ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call
  5388. ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
  5389. ** specific [error codes] that better describes the error.
  5390. ** We admit that this is a goofy design. The problem has been fixed
  5391. ** with the "v2" interface. If you prepare all of your SQL statements
  5392. ** using [sqlite3_prepare_v3()] or [sqlite3_prepare_v2()]
  5393. ** or [sqlite3_prepare16_v2()] or [sqlite3_prepare16_v3()] instead
  5394. ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
  5395. ** then the more specific [error codes] are returned directly
  5396. ** by sqlite3_step(). The use of the "vX" interfaces is recommended.
  5397. */
  5398. SQLITE_API int sqlite3_step(sqlite3_stmt*);
  5399. /*
  5400. ** CAPI3REF: Number of columns in a result set
  5401. ** METHOD: sqlite3_stmt
  5402. **
  5403. ** ^The sqlite3_data_count(P) interface returns the number of columns in the
  5404. ** current row of the result set of [prepared statement] P.
  5405. ** ^If prepared statement P does not have results ready to return
  5406. ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
  5407. ** interfaces) then sqlite3_data_count(P) returns 0.
  5408. ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
  5409. ** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
  5410. ** [sqlite3_step](P) returned [SQLITE_DONE]. ^The sqlite3_data_count(P)
  5411. ** will return non-zero if previous call to [sqlite3_step](P) returned
  5412. ** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
  5413. ** where it always returns zero since each step of that multi-step
  5414. ** pragma returns 0 columns of data.
  5415. **
  5416. ** See also: [sqlite3_column_count()]
  5417. */
  5418. SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
  5419. /*
  5420. ** CAPI3REF: Fundamental Datatypes
  5421. ** KEYWORDS: SQLITE_TEXT
  5422. **
  5423. ** ^(Every value in SQLite has one of five fundamental datatypes:
  5424. **
  5425. ** <ul>
  5426. ** <li> 64-bit signed integer
  5427. ** <li> 64-bit IEEE floating point number
  5428. ** <li> string
  5429. ** <li> BLOB
  5430. ** <li> NULL
  5431. ** </ul>)^
  5432. **
  5433. ** These constants are codes for each of those types.
  5434. **
  5435. ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
  5436. ** for a completely different meaning. Software that links against both
  5437. ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
  5438. ** SQLITE_TEXT.
  5439. */
  5440. #define SQLITE_INTEGER 1
  5441. #define SQLITE_FLOAT 2
  5442. #define SQLITE_BLOB 4
  5443. #define SQLITE_NULL 5
  5444. #ifdef SQLITE_TEXT
  5445. # undef SQLITE_TEXT
  5446. #else
  5447. # define SQLITE_TEXT 3
  5448. #endif
  5449. #define SQLITE3_TEXT 3
  5450. /*
  5451. ** CAPI3REF: Result Values From A Query
  5452. ** KEYWORDS: {column access functions}
  5453. ** METHOD: sqlite3_stmt
  5454. **
  5455. ** <b>Summary:</b>
  5456. ** <blockquote><table border=0 cellpadding=0 cellspacing=0>
  5457. ** <tr><td><b>sqlite3_column_blob</b><td>&rarr;<td>BLOB result
  5458. ** <tr><td><b>sqlite3_column_double</b><td>&rarr;<td>REAL result
  5459. ** <tr><td><b>sqlite3_column_int</b><td>&rarr;<td>32-bit INTEGER result
  5460. ** <tr><td><b>sqlite3_column_int64</b><td>&rarr;<td>64-bit INTEGER result
  5461. ** <tr><td><b>sqlite3_column_text</b><td>&rarr;<td>UTF-8 TEXT result
  5462. ** <tr><td><b>sqlite3_column_text16</b><td>&rarr;<td>UTF-16 TEXT result
  5463. ** <tr><td><b>sqlite3_column_value</b><td>&rarr;<td>The result as an
  5464. ** [sqlite3_value|unprotected sqlite3_value] object.
  5465. ** <tr><td>&nbsp;<td>&nbsp;<td>&nbsp;
  5466. ** <tr><td><b>sqlite3_column_bytes</b><td>&rarr;<td>Size of a BLOB
  5467. ** or a UTF-8 TEXT result in bytes
  5468. ** <tr><td><b>sqlite3_column_bytes16&nbsp;&nbsp;</b>
  5469. ** <td>&rarr;&nbsp;&nbsp;<td>Size of UTF-16
  5470. ** TEXT in bytes
  5471. ** <tr><td><b>sqlite3_column_type</b><td>&rarr;<td>Default
  5472. ** datatype of the result
  5473. ** </table></blockquote>
  5474. **
  5475. ** <b>Details:</b>
  5476. **
  5477. ** ^These routines return information about a single column of the current
  5478. ** result row of a query. ^In every case the first argument is a pointer
  5479. ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
  5480. ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
  5481. ** and the second argument is the index of the column for which information
  5482. ** should be returned. ^The leftmost column of the result set has the index 0.
  5483. ** ^The number of columns in the result can be determined using
  5484. ** [sqlite3_column_count()].
  5485. **
  5486. ** If the SQL statement does not currently point to a valid row, or if the
  5487. ** column index is out of range, the result is undefined.
  5488. ** These routines may only be called when the most recent call to
  5489. ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
  5490. ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
  5491. ** If any of these routines are called after [sqlite3_reset()] or
  5492. ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
  5493. ** something other than [SQLITE_ROW], the results are undefined.
  5494. ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
  5495. ** are called from a different thread while any of these routines
  5496. ** are pending, then the results are undefined.
  5497. **
  5498. ** The first six interfaces (_blob, _double, _int, _int64, _text, and _text16)
  5499. ** each return the value of a result column in a specific data format. If
  5500. ** the result column is not initially in the requested format (for example,
  5501. ** if the query returns an integer but the sqlite3_column_text() interface
  5502. ** is used to extract the value) then an automatic type conversion is performed.
  5503. **
  5504. ** ^The sqlite3_column_type() routine returns the
  5505. ** [SQLITE_INTEGER | datatype code] for the initial data type
  5506. ** of the result column. ^The returned value is one of [SQLITE_INTEGER],
  5507. ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].
  5508. ** The return value of sqlite3_column_type() can be used to decide which
  5509. ** of the first six interface should be used to extract the column value.
  5510. ** The value returned by sqlite3_column_type() is only meaningful if no
  5511. ** automatic type conversions have occurred for the value in question.
  5512. ** After a type conversion, the result of calling sqlite3_column_type()
  5513. ** is undefined, though harmless. Future
  5514. ** versions of SQLite may change the behavior of sqlite3_column_type()
  5515. ** following a type conversion.
  5516. **
  5517. ** If the result is a BLOB or a TEXT string, then the sqlite3_column_bytes()
  5518. ** or sqlite3_column_bytes16() interfaces can be used to determine the size
  5519. ** of that BLOB or string.
  5520. **
  5521. ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
  5522. ** routine returns the number of bytes in that BLOB or string.
  5523. ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
  5524. ** the string to UTF-8 and then returns the number of bytes.
  5525. ** ^If the result is a numeric value then sqlite3_column_bytes() uses
  5526. ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
  5527. ** the number of bytes in that string.
  5528. ** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
  5529. **
  5530. ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
  5531. ** routine returns the number of bytes in that BLOB or string.
  5532. ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
  5533. ** the string to UTF-16 and then returns the number of bytes.
  5534. ** ^If the result is a numeric value then sqlite3_column_bytes16() uses
  5535. ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
  5536. ** the number of bytes in that string.
  5537. ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
  5538. **
  5539. ** ^The values returned by [sqlite3_column_bytes()] and
  5540. ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
  5541. ** of the string. ^For clarity: the values returned by
  5542. ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
  5543. ** bytes in the string, not the number of characters.
  5544. **
  5545. ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
  5546. ** even empty strings, are always zero-terminated. ^The return
  5547. ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
  5548. **
  5549. ** <b>Warning:</b> ^The object returned by [sqlite3_column_value()] is an
  5550. ** [unprotected sqlite3_value] object. In a multithreaded environment,
  5551. ** an unprotected sqlite3_value object may only be used safely with
  5552. ** [sqlite3_bind_value()] and [sqlite3_result_value()].
  5553. ** If the [unprotected sqlite3_value] object returned by
  5554. ** [sqlite3_column_value()] is used in any other way, including calls
  5555. ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
  5556. ** or [sqlite3_value_bytes()], the behavior is not threadsafe.
  5557. ** Hence, the sqlite3_column_value() interface
  5558. ** is normally only useful within the implementation of
  5559. ** [application-defined SQL functions] or [virtual tables], not within
  5560. ** top-level application code.
  5561. **
  5562. ** The these routines may attempt to convert the datatype of the result.
  5563. ** ^For example, if the internal representation is FLOAT and a text result
  5564. ** is requested, [sqlite3_snprintf()] is used internally to perform the
  5565. ** conversion automatically. ^(The following table details the conversions
  5566. ** that are applied:
  5567. **
  5568. ** <blockquote>
  5569. ** <table border="1">
  5570. ** <tr><th> Internal<br>Type <th> Requested<br>Type <th> Conversion
  5571. **
  5572. ** <tr><td> NULL <td> INTEGER <td> Result is 0
  5573. ** <tr><td> NULL <td> FLOAT <td> Result is 0.0
  5574. ** <tr><td> NULL <td> TEXT <td> Result is a NULL pointer
  5575. ** <tr><td> NULL <td> BLOB <td> Result is a NULL pointer
  5576. ** <tr><td> INTEGER <td> FLOAT <td> Convert from integer to float
  5577. ** <tr><td> INTEGER <td> TEXT <td> ASCII rendering of the integer
  5578. ** <tr><td> INTEGER <td> BLOB <td> Same as INTEGER->TEXT
  5579. ** <tr><td> FLOAT <td> INTEGER <td> [CAST] to INTEGER
  5580. ** <tr><td> FLOAT <td> TEXT <td> ASCII rendering of the float
  5581. ** <tr><td> FLOAT <td> BLOB <td> [CAST] to BLOB
  5582. ** <tr><td> TEXT <td> INTEGER <td> [CAST] to INTEGER
  5583. ** <tr><td> TEXT <td> FLOAT <td> [CAST] to REAL
  5584. ** <tr><td> TEXT <td> BLOB <td> No change
  5585. ** <tr><td> BLOB <td> INTEGER <td> [CAST] to INTEGER
  5586. ** <tr><td> BLOB <td> FLOAT <td> [CAST] to REAL
  5587. ** <tr><td> BLOB <td> TEXT <td> Add a zero terminator if needed
  5588. ** </table>
  5589. ** </blockquote>)^
  5590. **
  5591. ** Note that when type conversions occur, pointers returned by prior
  5592. ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
  5593. ** sqlite3_column_text16() may be invalidated.
  5594. ** Type conversions and pointer invalidations might occur
  5595. ** in the following cases:
  5596. **
  5597. ** <ul>
  5598. ** <li> The initial content is a BLOB and sqlite3_column_text() or
  5599. ** sqlite3_column_text16() is called. A zero-terminator might
  5600. ** need to be added to the string.</li>
  5601. ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
  5602. ** sqlite3_column_text16() is called. The content must be converted
  5603. ** to UTF-16.</li>
  5604. ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
  5605. ** sqlite3_column_text() is called. The content must be converted
  5606. ** to UTF-8.</li>
  5607. ** </ul>
  5608. **
  5609. ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
  5610. ** not invalidate a prior pointer, though of course the content of the buffer
  5611. ** that the prior pointer references will have been modified. Other kinds
  5612. ** of conversion are done in place when it is possible, but sometimes they
  5613. ** are not possible and in those cases prior pointers are invalidated.
  5614. **
  5615. ** The safest policy is to invoke these routines
  5616. ** in one of the following ways:
  5617. **
  5618. ** <ul>
  5619. ** <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
  5620. ** <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
  5621. ** <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
  5622. ** </ul>
  5623. **
  5624. ** In other words, you should call sqlite3_column_text(),
  5625. ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
  5626. ** into the desired format, then invoke sqlite3_column_bytes() or
  5627. ** sqlite3_column_bytes16() to find the size of the result. Do not mix calls
  5628. ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
  5629. ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
  5630. ** with calls to sqlite3_column_bytes().
  5631. **
  5632. ** ^The pointers returned are valid until a type conversion occurs as
  5633. ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
  5634. ** [sqlite3_finalize()] is called. ^The memory space used to hold strings
  5635. ** and BLOBs is freed automatically. Do not pass the pointers returned
  5636. ** from [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
  5637. ** [sqlite3_free()].
  5638. **
  5639. ** As long as the input parameters are correct, these routines will only
  5640. ** fail if an out-of-memory error occurs during a format conversion.
  5641. ** Only the following subset of interfaces are subject to out-of-memory
  5642. ** errors:
  5643. **
  5644. ** <ul>
  5645. ** <li> sqlite3_column_blob()
  5646. ** <li> sqlite3_column_text()
  5647. ** <li> sqlite3_column_text16()
  5648. ** <li> sqlite3_column_bytes()
  5649. ** <li> sqlite3_column_bytes16()
  5650. ** </ul>
  5651. **
  5652. ** If an out-of-memory error occurs, then the return value from these
  5653. ** routines is the same as if the column had contained an SQL NULL value.
  5654. ** Valid SQL NULL returns can be distinguished from out-of-memory errors
  5655. ** by invoking the [sqlite3_errcode()] immediately after the suspect
  5656. ** return value is obtained and before any
  5657. ** other SQLite interface is called on the same [database connection].
  5658. */
  5659. SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
  5660. SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
  5661. SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
  5662. SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
  5663. SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
  5664. SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
  5665. SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
  5666. SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
  5667. SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
  5668. SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
  5669. /*
  5670. ** CAPI3REF: Destroy A Prepared Statement Object
  5671. ** DESTRUCTOR: sqlite3_stmt
  5672. **
  5673. ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
  5674. ** ^If the most recent evaluation of the statement encountered no errors
  5675. ** or if the statement is never been evaluated, then sqlite3_finalize() returns
  5676. ** SQLITE_OK. ^If the most recent evaluation of statement S failed, then
  5677. ** sqlite3_finalize(S) returns the appropriate [error code] or
  5678. ** [extended error code].
  5679. **
  5680. ** ^The sqlite3_finalize(S) routine can be called at any point during
  5681. ** the life cycle of [prepared statement] S:
  5682. ** before statement S is ever evaluated, after
  5683. ** one or more calls to [sqlite3_reset()], or after any call
  5684. ** to [sqlite3_step()] regardless of whether or not the statement has
  5685. ** completed execution.
  5686. **
  5687. ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
  5688. **
  5689. ** The application must finalize every [prepared statement] in order to avoid
  5690. ** resource leaks. It is a grievous error for the application to try to use
  5691. ** a prepared statement after it has been finalized. Any use of a prepared
  5692. ** statement after it has been finalized can result in undefined and
  5693. ** undesirable behavior such as segfaults and heap corruption.
  5694. */
  5695. SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
  5696. /*
  5697. ** CAPI3REF: Reset A Prepared Statement Object
  5698. ** METHOD: sqlite3_stmt
  5699. **
  5700. ** The sqlite3_reset() function is called to reset a [prepared statement]
  5701. ** object back to its initial state, ready to be re-executed.
  5702. ** ^Any SQL statement variables that had values bound to them using
  5703. ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
  5704. ** Use [sqlite3_clear_bindings()] to reset the bindings.
  5705. **
  5706. ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
  5707. ** back to the beginning of its program.
  5708. **
  5709. ** ^If the most recent call to [sqlite3_step(S)] for the
  5710. ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
  5711. ** or if [sqlite3_step(S)] has never before been called on S,
  5712. ** then [sqlite3_reset(S)] returns [SQLITE_OK].
  5713. **
  5714. ** ^If the most recent call to [sqlite3_step(S)] for the
  5715. ** [prepared statement] S indicated an error, then
  5716. ** [sqlite3_reset(S)] returns an appropriate [error code].
  5717. **
  5718. ** ^The [sqlite3_reset(S)] interface does not change the values
  5719. ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
  5720. */
  5721. SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
  5722. /*
  5723. ** CAPI3REF: Create Or Redefine SQL Functions
  5724. ** KEYWORDS: {function creation routines}
  5725. ** KEYWORDS: {application-defined SQL function}
  5726. ** KEYWORDS: {application-defined SQL functions}
  5727. ** METHOD: sqlite3
  5728. **
  5729. ** ^These functions (collectively known as "function creation routines")
  5730. ** are used to add SQL functions or aggregates or to redefine the behavior
  5731. ** of existing SQL functions or aggregates. The only differences between
  5732. ** the three "sqlite3_create_function*" routines are the text encoding
  5733. ** expected for the second parameter (the name of the function being
  5734. ** created) and the presence or absence of a destructor callback for
  5735. ** the application data pointer. Function sqlite3_create_window_function()
  5736. ** is similar, but allows the user to supply the extra callback functions
  5737. ** needed by [aggregate window functions].
  5738. **
  5739. ** ^The first parameter is the [database connection] to which the SQL
  5740. ** function is to be added. ^If an application uses more than one database
  5741. ** connection then application-defined SQL functions must be added
  5742. ** to each database connection separately.
  5743. **
  5744. ** ^The second parameter is the name of the SQL function to be created or
  5745. ** redefined. ^The length of the name is limited to 255 bytes in a UTF-8
  5746. ** representation, exclusive of the zero-terminator. ^Note that the name
  5747. ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
  5748. ** ^Any attempt to create a function with a longer name
  5749. ** will result in [SQLITE_MISUSE] being returned.
  5750. **
  5751. ** ^The third parameter (nArg)
  5752. ** is the number of arguments that the SQL function or
  5753. ** aggregate takes. ^If this parameter is -1, then the SQL function or
  5754. ** aggregate may take any number of arguments between 0 and the limit
  5755. ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third
  5756. ** parameter is less than -1 or greater than 127 then the behavior is
  5757. ** undefined.
  5758. **
  5759. ** ^The fourth parameter, eTextRep, specifies what
  5760. ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
  5761. ** its parameters. The application should set this parameter to
  5762. ** [SQLITE_UTF16LE] if the function implementation invokes
  5763. ** [sqlite3_value_text16le()] on an input, or [SQLITE_UTF16BE] if the
  5764. ** implementation invokes [sqlite3_value_text16be()] on an input, or
  5765. ** [SQLITE_UTF16] if [sqlite3_value_text16()] is used, or [SQLITE_UTF8]
  5766. ** otherwise. ^The same SQL function may be registered multiple times using
  5767. ** different preferred text encodings, with different implementations for
  5768. ** each encoding.
  5769. ** ^When multiple implementations of the same function are available, SQLite
  5770. ** will pick the one that involves the least amount of data conversion.
  5771. **
  5772. ** ^The fourth parameter may optionally be ORed with [SQLITE_DETERMINISTIC]
  5773. ** to signal that the function will always return the same result given
  5774. ** the same inputs within a single SQL statement. Most SQL functions are
  5775. ** deterministic. The built-in [random()] SQL function is an example of a
  5776. ** function that is not deterministic. The SQLite query planner is able to
  5777. ** perform additional optimizations on deterministic functions, so use
  5778. ** of the [SQLITE_DETERMINISTIC] flag is recommended where possible.
  5779. **
  5780. ** ^(The fifth parameter is an arbitrary pointer. The implementation of the
  5781. ** function can gain access to this pointer using [sqlite3_user_data()].)^
  5782. **
  5783. ** ^The sixth, seventh and eighth parameters passed to the three
  5784. ** "sqlite3_create_function*" functions, xFunc, xStep and xFinal, are
  5785. ** pointers to C-language functions that implement the SQL function or
  5786. ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
  5787. ** callback only; NULL pointers must be passed as the xStep and xFinal
  5788. ** parameters. ^An aggregate SQL function requires an implementation of xStep
  5789. ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
  5790. ** SQL function or aggregate, pass NULL pointers for all three function
  5791. ** callbacks.
  5792. **
  5793. ** ^The sixth, seventh, eighth and ninth parameters (xStep, xFinal, xValue
  5794. ** and xInverse) passed to sqlite3_create_window_function are pointers to
  5795. ** C-language callbacks that implement the new function. xStep and xFinal
  5796. ** must both be non-NULL. xValue and xInverse may either both be NULL, in
  5797. ** which case a regular aggregate function is created, or must both be
  5798. ** non-NULL, in which case the new function may be used as either an aggregate
  5799. ** or aggregate window function. More details regarding the implementation
  5800. ** of aggregate window functions are
  5801. ** [user-defined window functions|available here].
  5802. **
  5803. ** ^(If the final parameter to sqlite3_create_function_v2() or
  5804. ** sqlite3_create_window_function() is not NULL, then it is destructor for
  5805. ** the application data pointer. The destructor is invoked when the function
  5806. ** is deleted, either by being overloaded or when the database connection
  5807. ** closes.)^ ^The destructor is also invoked if the call to
  5808. ** sqlite3_create_function_v2() fails. ^When the destructor callback is
  5809. ** invoked, it is passed a single argument which is a copy of the application
  5810. ** data pointer which was the fifth parameter to sqlite3_create_function_v2().
  5811. **
  5812. ** ^It is permitted to register multiple implementations of the same
  5813. ** functions with the same name but with either differing numbers of
  5814. ** arguments or differing preferred text encodings. ^SQLite will use
  5815. ** the implementation that most closely matches the way in which the
  5816. ** SQL function is used. ^A function implementation with a non-negative
  5817. ** nArg parameter is a better match than a function implementation with
  5818. ** a negative nArg. ^A function where the preferred text encoding
  5819. ** matches the database encoding is a better
  5820. ** match than a function where the encoding is different.
  5821. ** ^A function where the encoding difference is between UTF16le and UTF16be
  5822. ** is a closer match than a function where the encoding difference is
  5823. ** between UTF8 and UTF16.
  5824. **
  5825. ** ^Built-in functions may be overloaded by new application-defined functions.
  5826. **
  5827. ** ^An application-defined function is permitted to call other
  5828. ** SQLite interfaces. However, such calls must not
  5829. ** close the database connection nor finalize or reset the prepared
  5830. ** statement in which the function is running.
  5831. */
  5832. SQLITE_API int sqlite3_create_function(
  5833. sqlite3 *db,
  5834. const char *zFunctionName,
  5835. int nArg,
  5836. int eTextRep,
  5837. void *pApp,
  5838. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  5839. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  5840. void (*xFinal)(sqlite3_context*)
  5841. );
  5842. SQLITE_API int sqlite3_create_function16(
  5843. sqlite3 *db,
  5844. const void *zFunctionName,
  5845. int nArg,
  5846. int eTextRep,
  5847. void *pApp,
  5848. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  5849. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  5850. void (*xFinal)(sqlite3_context*)
  5851. );
  5852. SQLITE_API int sqlite3_create_function_v2(
  5853. sqlite3 *db,
  5854. const char *zFunctionName,
  5855. int nArg,
  5856. int eTextRep,
  5857. void *pApp,
  5858. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  5859. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  5860. void (*xFinal)(sqlite3_context*),
  5861. void(*xDestroy)(void*)
  5862. );
  5863. SQLITE_API int sqlite3_create_window_function(
  5864. sqlite3 *db,
  5865. const char *zFunctionName,
  5866. int nArg,
  5867. int eTextRep,
  5868. void *pApp,
  5869. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  5870. void (*xFinal)(sqlite3_context*),
  5871. void (*xValue)(sqlite3_context*),
  5872. void (*xInverse)(sqlite3_context*,int,sqlite3_value**),
  5873. void(*xDestroy)(void*)
  5874. );
  5875. /*
  5876. ** CAPI3REF: Text Encodings
  5877. **
  5878. ** These constant define integer codes that represent the various
  5879. ** text encodings supported by SQLite.
  5880. */
  5881. #define SQLITE_UTF8 1 /* IMP: R-37514-35566 */
  5882. #define SQLITE_UTF16LE 2 /* IMP: R-03371-37637 */
  5883. #define SQLITE_UTF16BE 3 /* IMP: R-51971-34154 */
  5884. #define SQLITE_UTF16 4 /* Use native byte order */
  5885. #define SQLITE_ANY 5 /* Deprecated */
  5886. #define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */
  5887. /*
  5888. ** CAPI3REF: Function Flags
  5889. **
  5890. ** These constants may be ORed together with the
  5891. ** [SQLITE_UTF8 | preferred text encoding] as the fourth argument
  5892. ** to [sqlite3_create_function()], [sqlite3_create_function16()], or
  5893. ** [sqlite3_create_function_v2()].
  5894. */
  5895. #define SQLITE_DETERMINISTIC 0x800
  5896. /*
  5897. ** CAPI3REF: Deprecated Functions
  5898. ** DEPRECATED
  5899. **
  5900. ** These functions are [deprecated]. In order to maintain
  5901. ** backwards compatibility with older code, these functions continue
  5902. ** to be supported. However, new applications should avoid
  5903. ** the use of these functions. To encourage programmers to avoid
  5904. ** these functions, we will not explain what they do.
  5905. */
  5906. #ifndef SQLITE_OMIT_DEPRECATED
  5907. SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
  5908. SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
  5909. SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
  5910. SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
  5911. SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
  5912. SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),
  5913. void*,sqlite3_int64);
  5914. #endif
  5915. /*
  5916. ** CAPI3REF: Obtaining SQL Values
  5917. ** METHOD: sqlite3_value
  5918. **
  5919. ** <b>Summary:</b>
  5920. ** <blockquote><table border=0 cellpadding=0 cellspacing=0>
  5921. ** <tr><td><b>sqlite3_value_blob</b><td>&rarr;<td>BLOB value
  5922. ** <tr><td><b>sqlite3_value_double</b><td>&rarr;<td>REAL value
  5923. ** <tr><td><b>sqlite3_value_int</b><td>&rarr;<td>32-bit INTEGER value
  5924. ** <tr><td><b>sqlite3_value_int64</b><td>&rarr;<td>64-bit INTEGER value
  5925. ** <tr><td><b>sqlite3_value_pointer</b><td>&rarr;<td>Pointer value
  5926. ** <tr><td><b>sqlite3_value_text</b><td>&rarr;<td>UTF-8 TEXT value
  5927. ** <tr><td><b>sqlite3_value_text16</b><td>&rarr;<td>UTF-16 TEXT value in
  5928. ** the native byteorder
  5929. ** <tr><td><b>sqlite3_value_text16be</b><td>&rarr;<td>UTF-16be TEXT value
  5930. ** <tr><td><b>sqlite3_value_text16le</b><td>&rarr;<td>UTF-16le TEXT value
  5931. ** <tr><td>&nbsp;<td>&nbsp;<td>&nbsp;
  5932. ** <tr><td><b>sqlite3_value_bytes</b><td>&rarr;<td>Size of a BLOB
  5933. ** or a UTF-8 TEXT in bytes
  5934. ** <tr><td><b>sqlite3_value_bytes16&nbsp;&nbsp;</b>
  5935. ** <td>&rarr;&nbsp;&nbsp;<td>Size of UTF-16
  5936. ** TEXT in bytes
  5937. ** <tr><td><b>sqlite3_value_type</b><td>&rarr;<td>Default
  5938. ** datatype of the value
  5939. ** <tr><td><b>sqlite3_value_numeric_type&nbsp;&nbsp;</b>
  5940. ** <td>&rarr;&nbsp;&nbsp;<td>Best numeric datatype of the value
  5941. ** <tr><td><b>sqlite3_value_nochange&nbsp;&nbsp;</b>
  5942. ** <td>&rarr;&nbsp;&nbsp;<td>True if the column is unchanged in an UPDATE
  5943. ** against a virtual table.
  5944. ** <tr><td><b>sqlite3_value_frombind&nbsp;&nbsp;</b>
  5945. ** <td>&rarr;&nbsp;&nbsp;<td>True if value originated from a [bound parameter]
  5946. ** </table></blockquote>
  5947. **
  5948. ** <b>Details:</b>
  5949. **
  5950. ** These routines extract type, size, and content information from
  5951. ** [protected sqlite3_value] objects. Protected sqlite3_value objects
  5952. ** are used to pass parameter information into implementation of
  5953. ** [application-defined SQL functions] and [virtual tables].
  5954. **
  5955. ** These routines work only with [protected sqlite3_value] objects.
  5956. ** Any attempt to use these routines on an [unprotected sqlite3_value]
  5957. ** is not threadsafe.
  5958. **
  5959. ** ^These routines work just like the corresponding [column access functions]
  5960. ** except that these routines take a single [protected sqlite3_value] object
  5961. ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
  5962. **
  5963. ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
  5964. ** in the native byte-order of the host machine. ^The
  5965. ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
  5966. ** extract UTF-16 strings as big-endian and little-endian respectively.
  5967. **
  5968. ** ^If [sqlite3_value] object V was initialized
  5969. ** using [sqlite3_bind_pointer(S,I,P,X,D)] or [sqlite3_result_pointer(C,P,X,D)]
  5970. ** and if X and Y are strings that compare equal according to strcmp(X,Y),
  5971. ** then sqlite3_value_pointer(V,Y) will return the pointer P. ^Otherwise,
  5972. ** sqlite3_value_pointer(V,Y) returns a NULL. The sqlite3_bind_pointer()
  5973. ** routine is part of the [pointer passing interface] added for SQLite 3.20.0.
  5974. **
  5975. ** ^(The sqlite3_value_type(V) interface returns the
  5976. ** [SQLITE_INTEGER | datatype code] for the initial datatype of the
  5977. ** [sqlite3_value] object V. The returned value is one of [SQLITE_INTEGER],
  5978. ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].)^
  5979. ** Other interfaces might change the datatype for an sqlite3_value object.
  5980. ** For example, if the datatype is initially SQLITE_INTEGER and
  5981. ** sqlite3_value_text(V) is called to extract a text value for that
  5982. ** integer, then subsequent calls to sqlite3_value_type(V) might return
  5983. ** SQLITE_TEXT. Whether or not a persistent internal datatype conversion
  5984. ** occurs is undefined and may change from one release of SQLite to the next.
  5985. **
  5986. ** ^(The sqlite3_value_numeric_type() interface attempts to apply
  5987. ** numeric affinity to the value. This means that an attempt is
  5988. ** made to convert the value to an integer or floating point. If
  5989. ** such a conversion is possible without loss of information (in other
  5990. ** words, if the value is a string that looks like a number)
  5991. ** then the conversion is performed. Otherwise no conversion occurs.
  5992. ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
  5993. **
  5994. ** ^Within the [xUpdate] method of a [virtual table], the
  5995. ** sqlite3_value_nochange(X) interface returns true if and only if
  5996. ** the column corresponding to X is unchanged by the UPDATE operation
  5997. ** that the xUpdate method call was invoked to implement and if
  5998. ** and the prior [xColumn] method call that was invoked to extracted
  5999. ** the value for that column returned without setting a result (probably
  6000. ** because it queried [sqlite3_vtab_nochange()] and found that the column
  6001. ** was unchanging). ^Within an [xUpdate] method, any value for which
  6002. ** sqlite3_value_nochange(X) is true will in all other respects appear
  6003. ** to be a NULL value. If sqlite3_value_nochange(X) is invoked anywhere other
  6004. ** than within an [xUpdate] method call for an UPDATE statement, then
  6005. ** the return value is arbitrary and meaningless.
  6006. **
  6007. ** ^The sqlite3_value_frombind(X) interface returns non-zero if the
  6008. ** value X originated from one of the [sqlite3_bind_int|sqlite3_bind()]
  6009. ** interfaces. ^If X comes from an SQL literal value, or a table column,
  6010. ** and expression, then sqlite3_value_frombind(X) returns zero.
  6011. **
  6012. ** Please pay particular attention to the fact that the pointer returned
  6013. ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
  6014. ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
  6015. ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
  6016. ** or [sqlite3_value_text16()].
  6017. **
  6018. ** These routines must be called from the same thread as
  6019. ** the SQL function that supplied the [sqlite3_value*] parameters.
  6020. **
  6021. ** As long as the input parameter is correct, these routines can only
  6022. ** fail if an out-of-memory error occurs during a format conversion.
  6023. ** Only the following subset of interfaces are subject to out-of-memory
  6024. ** errors:
  6025. **
  6026. ** <ul>
  6027. ** <li> sqlite3_value_blob()
  6028. ** <li> sqlite3_value_text()
  6029. ** <li> sqlite3_value_text16()
  6030. ** <li> sqlite3_value_text16le()
  6031. ** <li> sqlite3_value_text16be()
  6032. ** <li> sqlite3_value_bytes()
  6033. ** <li> sqlite3_value_bytes16()
  6034. ** </ul>
  6035. **
  6036. ** If an out-of-memory error occurs, then the return value from these
  6037. ** routines is the same as if the column had contained an SQL NULL value.
  6038. ** Valid SQL NULL returns can be distinguished from out-of-memory errors
  6039. ** by invoking the [sqlite3_errcode()] immediately after the suspect
  6040. ** return value is obtained and before any
  6041. ** other SQLite interface is called on the same [database connection].
  6042. */
  6043. SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
  6044. SQLITE_API double sqlite3_value_double(sqlite3_value*);
  6045. SQLITE_API int sqlite3_value_int(sqlite3_value*);
  6046. SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
  6047. SQLITE_API void *sqlite3_value_pointer(sqlite3_value*, const char*);
  6048. SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
  6049. SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
  6050. SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
  6051. SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
  6052. SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
  6053. SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
  6054. SQLITE_API int sqlite3_value_type(sqlite3_value*);
  6055. SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
  6056. SQLITE_API int sqlite3_value_nochange(sqlite3_value*);
  6057. SQLITE_API int sqlite3_value_frombind(sqlite3_value*);
  6058. /*
  6059. ** CAPI3REF: Finding The Subtype Of SQL Values
  6060. ** METHOD: sqlite3_value
  6061. **
  6062. ** The sqlite3_value_subtype(V) function returns the subtype for
  6063. ** an [application-defined SQL function] argument V. The subtype
  6064. ** information can be used to pass a limited amount of context from
  6065. ** one SQL function to another. Use the [sqlite3_result_subtype()]
  6066. ** routine to set the subtype for the return value of an SQL function.
  6067. */
  6068. SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value*);
  6069. /*
  6070. ** CAPI3REF: Copy And Free SQL Values
  6071. ** METHOD: sqlite3_value
  6072. **
  6073. ** ^The sqlite3_value_dup(V) interface makes a copy of the [sqlite3_value]
  6074. ** object D and returns a pointer to that copy. ^The [sqlite3_value] returned
  6075. ** is a [protected sqlite3_value] object even if the input is not.
  6076. ** ^The sqlite3_value_dup(V) interface returns NULL if V is NULL or if a
  6077. ** memory allocation fails.
  6078. **
  6079. ** ^The sqlite3_value_free(V) interface frees an [sqlite3_value] object
  6080. ** previously obtained from [sqlite3_value_dup()]. ^If V is a NULL pointer
  6081. ** then sqlite3_value_free(V) is a harmless no-op.
  6082. */
  6083. SQLITE_API sqlite3_value *sqlite3_value_dup(const sqlite3_value*);
  6084. SQLITE_API void sqlite3_value_free(sqlite3_value*);
  6085. /*
  6086. ** CAPI3REF: Obtain Aggregate Function Context
  6087. ** METHOD: sqlite3_context
  6088. **
  6089. ** Implementations of aggregate SQL functions use this
  6090. ** routine to allocate memory for storing their state.
  6091. **
  6092. ** ^The first time the sqlite3_aggregate_context(C,N) routine is called
  6093. ** for a particular aggregate function, SQLite
  6094. ** allocates N of memory, zeroes out that memory, and returns a pointer
  6095. ** to the new memory. ^On second and subsequent calls to
  6096. ** sqlite3_aggregate_context() for the same aggregate function instance,
  6097. ** the same buffer is returned. Sqlite3_aggregate_context() is normally
  6098. ** called once for each invocation of the xStep callback and then one
  6099. ** last time when the xFinal callback is invoked. ^(When no rows match
  6100. ** an aggregate query, the xStep() callback of the aggregate function
  6101. ** implementation is never called and xFinal() is called exactly once.
  6102. ** In those cases, sqlite3_aggregate_context() might be called for the
  6103. ** first time from within xFinal().)^
  6104. **
  6105. ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer
  6106. ** when first called if N is less than or equal to zero or if a memory
  6107. ** allocate error occurs.
  6108. **
  6109. ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
  6110. ** determined by the N parameter on first successful call. Changing the
  6111. ** value of N in subsequent call to sqlite3_aggregate_context() within
  6112. ** the same aggregate function instance will not resize the memory
  6113. ** allocation.)^ Within the xFinal callback, it is customary to set
  6114. ** N=0 in calls to sqlite3_aggregate_context(C,N) so that no
  6115. ** pointless memory allocations occur.
  6116. **
  6117. ** ^SQLite automatically frees the memory allocated by
  6118. ** sqlite3_aggregate_context() when the aggregate query concludes.
  6119. **
  6120. ** The first parameter must be a copy of the
  6121. ** [sqlite3_context | SQL function context] that is the first parameter
  6122. ** to the xStep or xFinal callback routine that implements the aggregate
  6123. ** function.
  6124. **
  6125. ** This routine must be called from the same thread in which
  6126. ** the aggregate SQL function is running.
  6127. */
  6128. SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
  6129. /*
  6130. ** CAPI3REF: User Data For Functions
  6131. ** METHOD: sqlite3_context
  6132. **
  6133. ** ^The sqlite3_user_data() interface returns a copy of
  6134. ** the pointer that was the pUserData parameter (the 5th parameter)
  6135. ** of the [sqlite3_create_function()]
  6136. ** and [sqlite3_create_function16()] routines that originally
  6137. ** registered the application defined function.
  6138. **
  6139. ** This routine must be called from the same thread in which
  6140. ** the application-defined function is running.
  6141. */
  6142. SQLITE_API void *sqlite3_user_data(sqlite3_context*);
  6143. /*
  6144. ** CAPI3REF: Database Connection For Functions
  6145. ** METHOD: sqlite3_context
  6146. **
  6147. ** ^The sqlite3_context_db_handle() interface returns a copy of
  6148. ** the pointer to the [database connection] (the 1st parameter)
  6149. ** of the [sqlite3_create_function()]
  6150. ** and [sqlite3_create_function16()] routines that originally
  6151. ** registered the application defined function.
  6152. */
  6153. SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
  6154. /*
  6155. ** CAPI3REF: Function Auxiliary Data
  6156. ** METHOD: sqlite3_context
  6157. **
  6158. ** These functions may be used by (non-aggregate) SQL functions to
  6159. ** associate metadata with argument values. If the same value is passed to
  6160. ** multiple invocations of the same SQL function during query execution, under
  6161. ** some circumstances the associated metadata may be preserved. An example
  6162. ** of where this might be useful is in a regular-expression matching
  6163. ** function. The compiled version of the regular expression can be stored as
  6164. ** metadata associated with the pattern string.
  6165. ** Then as long as the pattern string remains the same,
  6166. ** the compiled regular expression can be reused on multiple
  6167. ** invocations of the same function.
  6168. **
  6169. ** ^The sqlite3_get_auxdata(C,N) interface returns a pointer to the metadata
  6170. ** associated by the sqlite3_set_auxdata(C,N,P,X) function with the Nth argument
  6171. ** value to the application-defined function. ^N is zero for the left-most
  6172. ** function argument. ^If there is no metadata
  6173. ** associated with the function argument, the sqlite3_get_auxdata(C,N) interface
  6174. ** returns a NULL pointer.
  6175. **
  6176. ** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th
  6177. ** argument of the application-defined function. ^Subsequent
  6178. ** calls to sqlite3_get_auxdata(C,N) return P from the most recent
  6179. ** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or
  6180. ** NULL if the metadata has been discarded.
  6181. ** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL,
  6182. ** SQLite will invoke the destructor function X with parameter P exactly
  6183. ** once, when the metadata is discarded.
  6184. ** SQLite is free to discard the metadata at any time, including: <ul>
  6185. ** <li> ^(when the corresponding function parameter changes)^, or
  6186. ** <li> ^(when [sqlite3_reset()] or [sqlite3_finalize()] is called for the
  6187. ** SQL statement)^, or
  6188. ** <li> ^(when sqlite3_set_auxdata() is invoked again on the same
  6189. ** parameter)^, or
  6190. ** <li> ^(during the original sqlite3_set_auxdata() call when a memory
  6191. ** allocation error occurs.)^ </ul>
  6192. **
  6193. ** Note the last bullet in particular. The destructor X in
  6194. ** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the
  6195. ** sqlite3_set_auxdata() interface even returns. Hence sqlite3_set_auxdata()
  6196. ** should be called near the end of the function implementation and the
  6197. ** function implementation should not make any use of P after
  6198. ** sqlite3_set_auxdata() has been called.
  6199. **
  6200. ** ^(In practice, metadata is preserved between function calls for
  6201. ** function parameters that are compile-time constants, including literal
  6202. ** values and [parameters] and expressions composed from the same.)^
  6203. **
  6204. ** The value of the N parameter to these interfaces should be non-negative.
  6205. ** Future enhancements may make use of negative N values to define new
  6206. ** kinds of function caching behavior.
  6207. **
  6208. ** These routines must be called from the same thread in which
  6209. ** the SQL function is running.
  6210. */
  6211. SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
  6212. SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
  6213. /*
  6214. ** CAPI3REF: Constants Defining Special Destructor Behavior
  6215. **
  6216. ** These are special values for the destructor that is passed in as the
  6217. ** final argument to routines like [sqlite3_result_blob()]. ^If the destructor
  6218. ** argument is SQLITE_STATIC, it means that the content pointer is constant
  6219. ** and will never change. It does not need to be destroyed. ^The
  6220. ** SQLITE_TRANSIENT value means that the content will likely change in
  6221. ** the near future and that SQLite should make its own private copy of
  6222. ** the content before returning.
  6223. **
  6224. ** The typedef is necessary to work around problems in certain
  6225. ** C++ compilers.
  6226. */
  6227. typedef void (*sqlite3_destructor_type)(void*);
  6228. #define SQLITE_STATIC ((sqlite3_destructor_type)0)
  6229. #define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1)
  6230. /*
  6231. ** CAPI3REF: Setting The Result Of An SQL Function
  6232. ** METHOD: sqlite3_context
  6233. **
  6234. ** These routines are used by the xFunc or xFinal callbacks that
  6235. ** implement SQL functions and aggregates. See
  6236. ** [sqlite3_create_function()] and [sqlite3_create_function16()]
  6237. ** for additional information.
  6238. **
  6239. ** These functions work very much like the [parameter binding] family of
  6240. ** functions used to bind values to host parameters in prepared statements.
  6241. ** Refer to the [SQL parameter] documentation for additional information.
  6242. **
  6243. ** ^The sqlite3_result_blob() interface sets the result from
  6244. ** an application-defined function to be the BLOB whose content is pointed
  6245. ** to by the second parameter and which is N bytes long where N is the
  6246. ** third parameter.
  6247. **
  6248. ** ^The sqlite3_result_zeroblob(C,N) and sqlite3_result_zeroblob64(C,N)
  6249. ** interfaces set the result of the application-defined function to be
  6250. ** a BLOB containing all zero bytes and N bytes in size.
  6251. **
  6252. ** ^The sqlite3_result_double() interface sets the result from
  6253. ** an application-defined function to be a floating point value specified
  6254. ** by its 2nd argument.
  6255. **
  6256. ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
  6257. ** cause the implemented SQL function to throw an exception.
  6258. ** ^SQLite uses the string pointed to by the
  6259. ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
  6260. ** as the text of an error message. ^SQLite interprets the error
  6261. ** message string from sqlite3_result_error() as UTF-8. ^SQLite
  6262. ** interprets the string from sqlite3_result_error16() as UTF-16 in native
  6263. ** byte order. ^If the third parameter to sqlite3_result_error()
  6264. ** or sqlite3_result_error16() is negative then SQLite takes as the error
  6265. ** message all text up through the first zero character.
  6266. ** ^If the third parameter to sqlite3_result_error() or
  6267. ** sqlite3_result_error16() is non-negative then SQLite takes that many
  6268. ** bytes (not characters) from the 2nd parameter as the error message.
  6269. ** ^The sqlite3_result_error() and sqlite3_result_error16()
  6270. ** routines make a private copy of the error message text before
  6271. ** they return. Hence, the calling function can deallocate or
  6272. ** modify the text after they return without harm.
  6273. ** ^The sqlite3_result_error_code() function changes the error code
  6274. ** returned by SQLite as a result of an error in a function. ^By default,
  6275. ** the error code is SQLITE_ERROR. ^A subsequent call to sqlite3_result_error()
  6276. ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
  6277. **
  6278. ** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an
  6279. ** error indicating that a string or BLOB is too long to represent.
  6280. **
  6281. ** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an
  6282. ** error indicating that a memory allocation failed.
  6283. **
  6284. ** ^The sqlite3_result_int() interface sets the return value
  6285. ** of the application-defined function to be the 32-bit signed integer
  6286. ** value given in the 2nd argument.
  6287. ** ^The sqlite3_result_int64() interface sets the return value
  6288. ** of the application-defined function to be the 64-bit signed integer
  6289. ** value given in the 2nd argument.
  6290. **
  6291. ** ^The sqlite3_result_null() interface sets the return value
  6292. ** of the application-defined function to be NULL.
  6293. **
  6294. ** ^The sqlite3_result_text(), sqlite3_result_text16(),
  6295. ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
  6296. ** set the return value of the application-defined function to be
  6297. ** a text string which is represented as UTF-8, UTF-16 native byte order,
  6298. ** UTF-16 little endian, or UTF-16 big endian, respectively.
  6299. ** ^The sqlite3_result_text64() interface sets the return value of an
  6300. ** application-defined function to be a text string in an encoding
  6301. ** specified by the fifth (and last) parameter, which must be one
  6302. ** of [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE].
  6303. ** ^SQLite takes the text result from the application from
  6304. ** the 2nd parameter of the sqlite3_result_text* interfaces.
  6305. ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
  6306. ** is negative, then SQLite takes result text from the 2nd parameter
  6307. ** through the first zero character.
  6308. ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
  6309. ** is non-negative, then as many bytes (not characters) of the text
  6310. ** pointed to by the 2nd parameter are taken as the application-defined
  6311. ** function result. If the 3rd parameter is non-negative, then it
  6312. ** must be the byte offset into the string where the NUL terminator would
  6313. ** appear if the string where NUL terminated. If any NUL characters occur
  6314. ** in the string at a byte offset that is less than the value of the 3rd
  6315. ** parameter, then the resulting string will contain embedded NULs and the
  6316. ** result of expressions operating on strings with embedded NULs is undefined.
  6317. ** ^If the 4th parameter to the sqlite3_result_text* interfaces
  6318. ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
  6319. ** function as the destructor on the text or BLOB result when it has
  6320. ** finished using that result.
  6321. ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
  6322. ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
  6323. ** assumes that the text or BLOB result is in constant space and does not
  6324. ** copy the content of the parameter nor call a destructor on the content
  6325. ** when it has finished using that result.
  6326. ** ^If the 4th parameter to the sqlite3_result_text* interfaces
  6327. ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
  6328. ** then SQLite makes a copy of the result into space obtained
  6329. ** from [sqlite3_malloc()] before it returns.
  6330. **
  6331. ** ^The sqlite3_result_value() interface sets the result of
  6332. ** the application-defined function to be a copy of the
  6333. ** [unprotected sqlite3_value] object specified by the 2nd parameter. ^The
  6334. ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
  6335. ** so that the [sqlite3_value] specified in the parameter may change or
  6336. ** be deallocated after sqlite3_result_value() returns without harm.
  6337. ** ^A [protected sqlite3_value] object may always be used where an
  6338. ** [unprotected sqlite3_value] object is required, so either
  6339. ** kind of [sqlite3_value] object can be used with this interface.
  6340. **
  6341. ** ^The sqlite3_result_pointer(C,P,T,D) interface sets the result to an
  6342. ** SQL NULL value, just like [sqlite3_result_null(C)], except that it
  6343. ** also associates the host-language pointer P or type T with that
  6344. ** NULL value such that the pointer can be retrieved within an
  6345. ** [application-defined SQL function] using [sqlite3_value_pointer()].
  6346. ** ^If the D parameter is not NULL, then it is a pointer to a destructor
  6347. ** for the P parameter. ^SQLite invokes D with P as its only argument
  6348. ** when SQLite is finished with P. The T parameter should be a static
  6349. ** string and preferably a string literal. The sqlite3_result_pointer()
  6350. ** routine is part of the [pointer passing interface] added for SQLite 3.20.0.
  6351. **
  6352. ** If these routines are called from within the different thread
  6353. ** than the one containing the application-defined function that received
  6354. ** the [sqlite3_context] pointer, the results are undefined.
  6355. */
  6356. SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
  6357. SQLITE_API void sqlite3_result_blob64(sqlite3_context*,const void*,
  6358. sqlite3_uint64,void(*)(void*));
  6359. SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
  6360. SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
  6361. SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
  6362. SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
  6363. SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
  6364. SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
  6365. SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
  6366. SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
  6367. SQLITE_API void sqlite3_result_null(sqlite3_context*);
  6368. SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
  6369. SQLITE_API void sqlite3_result_text64(sqlite3_context*, const char*,sqlite3_uint64,
  6370. void(*)(void*), unsigned char encoding);
  6371. SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
  6372. SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
  6373. SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
  6374. SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
  6375. SQLITE_API void sqlite3_result_pointer(sqlite3_context*, void*,const char*,void(*)(void*));
  6376. SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
  6377. SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context*, sqlite3_uint64 n);
  6378. /*
  6379. ** CAPI3REF: Setting The Subtype Of An SQL Function
  6380. ** METHOD: sqlite3_context
  6381. **
  6382. ** The sqlite3_result_subtype(C,T) function causes the subtype of
  6383. ** the result from the [application-defined SQL function] with
  6384. ** [sqlite3_context] C to be the value T. Only the lower 8 bits
  6385. ** of the subtype T are preserved in current versions of SQLite;
  6386. ** higher order bits are discarded.
  6387. ** The number of subtype bytes preserved by SQLite might increase
  6388. ** in future releases of SQLite.
  6389. */
  6390. SQLITE_API void sqlite3_result_subtype(sqlite3_context*,unsigned int);
  6391. /*
  6392. ** CAPI3REF: Define New Collating Sequences
  6393. ** METHOD: sqlite3
  6394. **
  6395. ** ^These functions add, remove, or modify a [collation] associated
  6396. ** with the [database connection] specified as the first argument.
  6397. **
  6398. ** ^The name of the collation is a UTF-8 string
  6399. ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
  6400. ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
  6401. ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
  6402. ** considered to be the same name.
  6403. **
  6404. ** ^(The third argument (eTextRep) must be one of the constants:
  6405. ** <ul>
  6406. ** <li> [SQLITE_UTF8],
  6407. ** <li> [SQLITE_UTF16LE],
  6408. ** <li> [SQLITE_UTF16BE],
  6409. ** <li> [SQLITE_UTF16], or
  6410. ** <li> [SQLITE_UTF16_ALIGNED].
  6411. ** </ul>)^
  6412. ** ^The eTextRep argument determines the encoding of strings passed
  6413. ** to the collating function callback, xCallback.
  6414. ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
  6415. ** force strings to be UTF16 with native byte order.
  6416. ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
  6417. ** on an even byte address.
  6418. **
  6419. ** ^The fourth argument, pArg, is an application data pointer that is passed
  6420. ** through as the first argument to the collating function callback.
  6421. **
  6422. ** ^The fifth argument, xCallback, is a pointer to the collating function.
  6423. ** ^Multiple collating functions can be registered using the same name but
  6424. ** with different eTextRep parameters and SQLite will use whichever
  6425. ** function requires the least amount of data transformation.
  6426. ** ^If the xCallback argument is NULL then the collating function is
  6427. ** deleted. ^When all collating functions having the same name are deleted,
  6428. ** that collation is no longer usable.
  6429. **
  6430. ** ^The collating function callback is invoked with a copy of the pArg
  6431. ** application data pointer and with two strings in the encoding specified
  6432. ** by the eTextRep argument. The collating function must return an
  6433. ** integer that is negative, zero, or positive
  6434. ** if the first string is less than, equal to, or greater than the second,
  6435. ** respectively. A collating function must always return the same answer
  6436. ** given the same inputs. If two or more collating functions are registered
  6437. ** to the same collation name (using different eTextRep values) then all
  6438. ** must give an equivalent answer when invoked with equivalent strings.
  6439. ** The collating function must obey the following properties for all
  6440. ** strings A, B, and C:
  6441. **
  6442. ** <ol>
  6443. ** <li> If A==B then B==A.
  6444. ** <li> If A==B and B==C then A==C.
  6445. ** <li> If A&lt;B THEN B&gt;A.
  6446. ** <li> If A&lt;B and B&lt;C then A&lt;C.
  6447. ** </ol>
  6448. **
  6449. ** If a collating function fails any of the above constraints and that
  6450. ** collating function is registered and used, then the behavior of SQLite
  6451. ** is undefined.
  6452. **
  6453. ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
  6454. ** with the addition that the xDestroy callback is invoked on pArg when
  6455. ** the collating function is deleted.
  6456. ** ^Collating functions are deleted when they are overridden by later
  6457. ** calls to the collation creation functions or when the
  6458. ** [database connection] is closed using [sqlite3_close()].
  6459. **
  6460. ** ^The xDestroy callback is <u>not</u> called if the
  6461. ** sqlite3_create_collation_v2() function fails. Applications that invoke
  6462. ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
  6463. ** check the return code and dispose of the application data pointer
  6464. ** themselves rather than expecting SQLite to deal with it for them.
  6465. ** This is different from every other SQLite interface. The inconsistency
  6466. ** is unfortunate but cannot be changed without breaking backwards
  6467. ** compatibility.
  6468. **
  6469. ** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
  6470. */
  6471. SQLITE_API int sqlite3_create_collation(
  6472. sqlite3*,
  6473. const char *zName,
  6474. int eTextRep,
  6475. void *pArg,
  6476. int(*xCompare)(void*,int,const void*,int,const void*)
  6477. );
  6478. SQLITE_API int sqlite3_create_collation_v2(
  6479. sqlite3*,
  6480. const char *zName,
  6481. int eTextRep,
  6482. void *pArg,
  6483. int(*xCompare)(void*,int,const void*,int,const void*),
  6484. void(*xDestroy)(void*)
  6485. );
  6486. SQLITE_API int sqlite3_create_collation16(
  6487. sqlite3*,
  6488. const void *zName,
  6489. int eTextRep,
  6490. void *pArg,
  6491. int(*xCompare)(void*,int,const void*,int,const void*)
  6492. );
  6493. /*
  6494. ** CAPI3REF: Collation Needed Callbacks
  6495. ** METHOD: sqlite3
  6496. **
  6497. ** ^To avoid having to register all collation sequences before a database
  6498. ** can be used, a single callback function may be registered with the
  6499. ** [database connection] to be invoked whenever an undefined collation
  6500. ** sequence is required.
  6501. **
  6502. ** ^If the function is registered using the sqlite3_collation_needed() API,
  6503. ** then it is passed the names of undefined collation sequences as strings
  6504. ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
  6505. ** the names are passed as UTF-16 in machine native byte order.
  6506. ** ^A call to either function replaces the existing collation-needed callback.
  6507. **
  6508. ** ^(When the callback is invoked, the first argument passed is a copy
  6509. ** of the second argument to sqlite3_collation_needed() or
  6510. ** sqlite3_collation_needed16(). The second argument is the database
  6511. ** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
  6512. ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
  6513. ** sequence function required. The fourth parameter is the name of the
  6514. ** required collation sequence.)^
  6515. **
  6516. ** The callback function should register the desired collation using
  6517. ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
  6518. ** [sqlite3_create_collation_v2()].
  6519. */
  6520. SQLITE_API int sqlite3_collation_needed(
  6521. sqlite3*,
  6522. void*,
  6523. void(*)(void*,sqlite3*,int eTextRep,const char*)
  6524. );
  6525. SQLITE_API int sqlite3_collation_needed16(
  6526. sqlite3*,
  6527. void*,
  6528. void(*)(void*,sqlite3*,int eTextRep,const void*)
  6529. );
  6530. #ifdef SQLITE_HAS_CODEC
  6531. /*
  6532. ** Specify the key for an encrypted database. This routine should be
  6533. ** called right after sqlite3_open().
  6534. **
  6535. ** The code to implement this API is not available in the public release
  6536. ** of SQLite.
  6537. */
  6538. SQLITE_API int sqlite3_key(
  6539. sqlite3 *db, /* Database to be rekeyed */
  6540. const void *pKey, int nKey /* The key */
  6541. );
  6542. SQLITE_API int sqlite3_key_v2(
  6543. sqlite3 *db, /* Database to be rekeyed */
  6544. const char *zDbName, /* Name of the database */
  6545. const void *pKey, int nKey /* The key */
  6546. );
  6547. /*
  6548. ** Change the key on an open database. If the current database is not
  6549. ** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the
  6550. ** database is decrypted.
  6551. **
  6552. ** The code to implement this API is not available in the public release
  6553. ** of SQLite.
  6554. */
  6555. SQLITE_API int sqlite3_rekey(
  6556. sqlite3 *db, /* Database to be rekeyed */
  6557. const void *pKey, int nKey /* The new key */
  6558. );
  6559. SQLITE_API int sqlite3_rekey_v2(
  6560. sqlite3 *db, /* Database to be rekeyed */
  6561. const char *zDbName, /* Name of the database */
  6562. const void *pKey, int nKey /* The new key */
  6563. );
  6564. /*
  6565. ** Specify the activation key for a SEE database. Unless
  6566. ** activated, none of the SEE routines will work.
  6567. */
  6568. SQLITE_API void sqlite3_activate_see(
  6569. const char *zPassPhrase /* Activation phrase */
  6570. );
  6571. #endif
  6572. #ifdef SQLITE_ENABLE_CEROD
  6573. /*
  6574. ** Specify the activation key for a CEROD database. Unless
  6575. ** activated, none of the CEROD routines will work.
  6576. */
  6577. SQLITE_API void sqlite3_activate_cerod(
  6578. const char *zPassPhrase /* Activation phrase */
  6579. );
  6580. #endif
  6581. /*
  6582. ** CAPI3REF: Suspend Execution For A Short Time
  6583. **
  6584. ** The sqlite3_sleep() function causes the current thread to suspend execution
  6585. ** for at least a number of milliseconds specified in its parameter.
  6586. **
  6587. ** If the operating system does not support sleep requests with
  6588. ** millisecond time resolution, then the time will be rounded up to
  6589. ** the nearest second. The number of milliseconds of sleep actually
  6590. ** requested from the operating system is returned.
  6591. **
  6592. ** ^SQLite implements this interface by calling the xSleep()
  6593. ** method of the default [sqlite3_vfs] object. If the xSleep() method
  6594. ** of the default VFS is not implemented correctly, or not implemented at
  6595. ** all, then the behavior of sqlite3_sleep() may deviate from the description
  6596. ** in the previous paragraphs.
  6597. */
  6598. SQLITE_API int sqlite3_sleep(int);
  6599. /*
  6600. ** CAPI3REF: Name Of The Folder Holding Temporary Files
  6601. **
  6602. ** ^(If this global variable is made to point to a string which is
  6603. ** the name of a folder (a.k.a. directory), then all temporary files
  6604. ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
  6605. ** will be placed in that directory.)^ ^If this variable
  6606. ** is a NULL pointer, then SQLite performs a search for an appropriate
  6607. ** temporary file directory.
  6608. **
  6609. ** Applications are strongly discouraged from using this global variable.
  6610. ** It is required to set a temporary folder on Windows Runtime (WinRT).
  6611. ** But for all other platforms, it is highly recommended that applications
  6612. ** neither read nor write this variable. This global variable is a relic
  6613. ** that exists for backwards compatibility of legacy applications and should
  6614. ** be avoided in new projects.
  6615. **
  6616. ** It is not safe to read or modify this variable in more than one
  6617. ** thread at a time. It is not safe to read or modify this variable
  6618. ** if a [database connection] is being used at the same time in a separate
  6619. ** thread.
  6620. ** It is intended that this variable be set once
  6621. ** as part of process initialization and before any SQLite interface
  6622. ** routines have been called and that this variable remain unchanged
  6623. ** thereafter.
  6624. **
  6625. ** ^The [temp_store_directory pragma] may modify this variable and cause
  6626. ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
  6627. ** the [temp_store_directory pragma] always assumes that any string
  6628. ** that this variable points to is held in memory obtained from
  6629. ** [sqlite3_malloc] and the pragma may attempt to free that memory
  6630. ** using [sqlite3_free].
  6631. ** Hence, if this variable is modified directly, either it should be
  6632. ** made NULL or made to point to memory obtained from [sqlite3_malloc]
  6633. ** or else the use of the [temp_store_directory pragma] should be avoided.
  6634. ** Except when requested by the [temp_store_directory pragma], SQLite
  6635. ** does not free the memory that sqlite3_temp_directory points to. If
  6636. ** the application wants that memory to be freed, it must do
  6637. ** so itself, taking care to only do so after all [database connection]
  6638. ** objects have been destroyed.
  6639. **
  6640. ** <b>Note to Windows Runtime users:</b> The temporary directory must be set
  6641. ** prior to calling [sqlite3_open] or [sqlite3_open_v2]. Otherwise, various
  6642. ** features that require the use of temporary files may fail. Here is an
  6643. ** example of how to do this using C++ with the Windows Runtime:
  6644. **
  6645. ** <blockquote><pre>
  6646. ** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
  6647. ** &nbsp; TemporaryFolder->Path->Data();
  6648. ** char zPathBuf&#91;MAX_PATH + 1&#93;;
  6649. ** memset(zPathBuf, 0, sizeof(zPathBuf));
  6650. ** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
  6651. ** &nbsp; NULL, NULL);
  6652. ** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
  6653. ** </pre></blockquote>
  6654. */
  6655. SQLITE_API char *sqlite3_temp_directory;
  6656. /*
  6657. ** CAPI3REF: Name Of The Folder Holding Database Files
  6658. **
  6659. ** ^(If this global variable is made to point to a string which is
  6660. ** the name of a folder (a.k.a. directory), then all database files
  6661. ** specified with a relative pathname and created or accessed by
  6662. ** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed
  6663. ** to be relative to that directory.)^ ^If this variable is a NULL
  6664. ** pointer, then SQLite assumes that all database files specified
  6665. ** with a relative pathname are relative to the current directory
  6666. ** for the process. Only the windows VFS makes use of this global
  6667. ** variable; it is ignored by the unix VFS.
  6668. **
  6669. ** Changing the value of this variable while a database connection is
  6670. ** open can result in a corrupt database.
  6671. **
  6672. ** It is not safe to read or modify this variable in more than one
  6673. ** thread at a time. It is not safe to read or modify this variable
  6674. ** if a [database connection] is being used at the same time in a separate
  6675. ** thread.
  6676. ** It is intended that this variable be set once
  6677. ** as part of process initialization and before any SQLite interface
  6678. ** routines have been called and that this variable remain unchanged
  6679. ** thereafter.
  6680. **
  6681. ** ^The [data_store_directory pragma] may modify this variable and cause
  6682. ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
  6683. ** the [data_store_directory pragma] always assumes that any string
  6684. ** that this variable points to is held in memory obtained from
  6685. ** [sqlite3_malloc] and the pragma may attempt to free that memory
  6686. ** using [sqlite3_free].
  6687. ** Hence, if this variable is modified directly, either it should be
  6688. ** made NULL or made to point to memory obtained from [sqlite3_malloc]
  6689. ** or else the use of the [data_store_directory pragma] should be avoided.
  6690. */
  6691. SQLITE_API char *sqlite3_data_directory;
  6692. /*
  6693. ** CAPI3REF: Win32 Specific Interface
  6694. **
  6695. ** These interfaces are available only on Windows. The
  6696. ** [sqlite3_win32_set_directory] interface is used to set the value associated
  6697. ** with the [sqlite3_temp_directory] or [sqlite3_data_directory] variable, to
  6698. ** zValue, depending on the value of the type parameter. The zValue parameter
  6699. ** should be NULL to cause the previous value to be freed via [sqlite3_free];
  6700. ** a non-NULL value will be copied into memory obtained from [sqlite3_malloc]
  6701. ** prior to being used. The [sqlite3_win32_set_directory] interface returns
  6702. ** [SQLITE_OK] to indicate success, [SQLITE_ERROR] if the type is unsupported,
  6703. ** or [SQLITE_NOMEM] if memory could not be allocated. The value of the
  6704. ** [sqlite3_data_directory] variable is intended to act as a replacement for
  6705. ** the current directory on the sub-platforms of Win32 where that concept is
  6706. ** not present, e.g. WinRT and UWP. The [sqlite3_win32_set_directory8] and
  6707. ** [sqlite3_win32_set_directory16] interfaces behave exactly the same as the
  6708. ** sqlite3_win32_set_directory interface except the string parameter must be
  6709. ** UTF-8 or UTF-16, respectively.
  6710. */
  6711. SQLITE_API int sqlite3_win32_set_directory(
  6712. unsigned long type, /* Identifier for directory being set or reset */
  6713. void *zValue /* New value for directory being set or reset */
  6714. );
  6715. SQLITE_API int sqlite3_win32_set_directory8(unsigned long type, const char *zValue);
  6716. SQLITE_API int sqlite3_win32_set_directory16(unsigned long type, const void *zValue);
  6717. /*
  6718. ** CAPI3REF: Win32 Directory Types
  6719. **
  6720. ** These macros are only available on Windows. They define the allowed values
  6721. ** for the type argument to the [sqlite3_win32_set_directory] interface.
  6722. */
  6723. #define SQLITE_WIN32_DATA_DIRECTORY_TYPE 1
  6724. #define SQLITE_WIN32_TEMP_DIRECTORY_TYPE 2
  6725. /*
  6726. ** CAPI3REF: Test For Auto-Commit Mode
  6727. ** KEYWORDS: {autocommit mode}
  6728. ** METHOD: sqlite3
  6729. **
  6730. ** ^The sqlite3_get_autocommit() interface returns non-zero or
  6731. ** zero if the given database connection is or is not in autocommit mode,
  6732. ** respectively. ^Autocommit mode is on by default.
  6733. ** ^Autocommit mode is disabled by a [BEGIN] statement.
  6734. ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
  6735. **
  6736. ** If certain kinds of errors occur on a statement within a multi-statement
  6737. ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
  6738. ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
  6739. ** transaction might be rolled back automatically. The only way to
  6740. ** find out whether SQLite automatically rolled back the transaction after
  6741. ** an error is to use this function.
  6742. **
  6743. ** If another thread changes the autocommit status of the database
  6744. ** connection while this routine is running, then the return value
  6745. ** is undefined.
  6746. */
  6747. SQLITE_API int sqlite3_get_autocommit(sqlite3*);
  6748. /*
  6749. ** CAPI3REF: Find The Database Handle Of A Prepared Statement
  6750. ** METHOD: sqlite3_stmt
  6751. **
  6752. ** ^The sqlite3_db_handle interface returns the [database connection] handle
  6753. ** to which a [prepared statement] belongs. ^The [database connection]
  6754. ** returned by sqlite3_db_handle is the same [database connection]
  6755. ** that was the first argument
  6756. ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
  6757. ** create the statement in the first place.
  6758. */
  6759. SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
  6760. /*
  6761. ** CAPI3REF: Return The Filename For A Database Connection
  6762. ** METHOD: sqlite3
  6763. **
  6764. ** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename
  6765. ** associated with database N of connection D. ^The main database file
  6766. ** has the name "main". If there is no attached database N on the database
  6767. ** connection D, or if database N is a temporary or in-memory database, then
  6768. ** this function will return either a NULL pointer or an empty string.
  6769. **
  6770. ** ^The filename returned by this function is the output of the
  6771. ** xFullPathname method of the [VFS]. ^In other words, the filename
  6772. ** will be an absolute pathname, even if the filename used
  6773. ** to open the database originally was a URI or relative pathname.
  6774. */
  6775. SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName);
  6776. /*
  6777. ** CAPI3REF: Determine if a database is read-only
  6778. ** METHOD: sqlite3
  6779. **
  6780. ** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N
  6781. ** of connection D is read-only, 0 if it is read/write, or -1 if N is not
  6782. ** the name of a database on connection D.
  6783. */
  6784. SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
  6785. /*
  6786. ** CAPI3REF: Find the next prepared statement
  6787. ** METHOD: sqlite3
  6788. **
  6789. ** ^This interface returns a pointer to the next [prepared statement] after
  6790. ** pStmt associated with the [database connection] pDb. ^If pStmt is NULL
  6791. ** then this interface returns a pointer to the first prepared statement
  6792. ** associated with the database connection pDb. ^If no prepared statement
  6793. ** satisfies the conditions of this routine, it returns NULL.
  6794. **
  6795. ** The [database connection] pointer D in a call to
  6796. ** [sqlite3_next_stmt(D,S)] must refer to an open database
  6797. ** connection and in particular must not be a NULL pointer.
  6798. */
  6799. SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
  6800. /*
  6801. ** CAPI3REF: Commit And Rollback Notification Callbacks
  6802. ** METHOD: sqlite3
  6803. **
  6804. ** ^The sqlite3_commit_hook() interface registers a callback
  6805. ** function to be invoked whenever a transaction is [COMMIT | committed].
  6806. ** ^Any callback set by a previous call to sqlite3_commit_hook()
  6807. ** for the same database connection is overridden.
  6808. ** ^The sqlite3_rollback_hook() interface registers a callback
  6809. ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
  6810. ** ^Any callback set by a previous call to sqlite3_rollback_hook()
  6811. ** for the same database connection is overridden.
  6812. ** ^The pArg argument is passed through to the callback.
  6813. ** ^If the callback on a commit hook function returns non-zero,
  6814. ** then the commit is converted into a rollback.
  6815. **
  6816. ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
  6817. ** return the P argument from the previous call of the same function
  6818. ** on the same [database connection] D, or NULL for
  6819. ** the first call for each function on D.
  6820. **
  6821. ** The commit and rollback hook callbacks are not reentrant.
  6822. ** The callback implementation must not do anything that will modify
  6823. ** the database connection that invoked the callback. Any actions
  6824. ** to modify the database connection must be deferred until after the
  6825. ** completion of the [sqlite3_step()] call that triggered the commit
  6826. ** or rollback hook in the first place.
  6827. ** Note that running any other SQL statements, including SELECT statements,
  6828. ** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
  6829. ** the database connections for the meaning of "modify" in this paragraph.
  6830. **
  6831. ** ^Registering a NULL function disables the callback.
  6832. **
  6833. ** ^When the commit hook callback routine returns zero, the [COMMIT]
  6834. ** operation is allowed to continue normally. ^If the commit hook
  6835. ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
  6836. ** ^The rollback hook is invoked on a rollback that results from a commit
  6837. ** hook returning non-zero, just as it would be with any other rollback.
  6838. **
  6839. ** ^For the purposes of this API, a transaction is said to have been
  6840. ** rolled back if an explicit "ROLLBACK" statement is executed, or
  6841. ** an error or constraint causes an implicit rollback to occur.
  6842. ** ^The rollback callback is not invoked if a transaction is
  6843. ** automatically rolled back because the database connection is closed.
  6844. **
  6845. ** See also the [sqlite3_update_hook()] interface.
  6846. */
  6847. SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
  6848. SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
  6849. /*
  6850. ** CAPI3REF: Data Change Notification Callbacks
  6851. ** METHOD: sqlite3
  6852. **
  6853. ** ^The sqlite3_update_hook() interface registers a callback function
  6854. ** with the [database connection] identified by the first argument
  6855. ** to be invoked whenever a row is updated, inserted or deleted in
  6856. ** a [rowid table].
  6857. ** ^Any callback set by a previous call to this function
  6858. ** for the same database connection is overridden.
  6859. **
  6860. ** ^The second argument is a pointer to the function to invoke when a
  6861. ** row is updated, inserted or deleted in a rowid table.
  6862. ** ^The first argument to the callback is a copy of the third argument
  6863. ** to sqlite3_update_hook().
  6864. ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
  6865. ** or [SQLITE_UPDATE], depending on the operation that caused the callback
  6866. ** to be invoked.
  6867. ** ^The third and fourth arguments to the callback contain pointers to the
  6868. ** database and table name containing the affected row.
  6869. ** ^The final callback parameter is the [rowid] of the row.
  6870. ** ^In the case of an update, this is the [rowid] after the update takes place.
  6871. **
  6872. ** ^(The update hook is not invoked when internal system tables are
  6873. ** modified (i.e. sqlite_master and sqlite_sequence).)^
  6874. ** ^The update hook is not invoked when [WITHOUT ROWID] tables are modified.
  6875. **
  6876. ** ^In the current implementation, the update hook
  6877. ** is not invoked when conflicting rows are deleted because of an
  6878. ** [ON CONFLICT | ON CONFLICT REPLACE] clause. ^Nor is the update hook
  6879. ** invoked when rows are deleted using the [truncate optimization].
  6880. ** The exceptions defined in this paragraph might change in a future
  6881. ** release of SQLite.
  6882. **
  6883. ** The update hook implementation must not do anything that will modify
  6884. ** the database connection that invoked the update hook. Any actions
  6885. ** to modify the database connection must be deferred until after the
  6886. ** completion of the [sqlite3_step()] call that triggered the update hook.
  6887. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  6888. ** database connections for the meaning of "modify" in this paragraph.
  6889. **
  6890. ** ^The sqlite3_update_hook(D,C,P) function
  6891. ** returns the P argument from the previous call
  6892. ** on the same [database connection] D, or NULL for
  6893. ** the first call on D.
  6894. **
  6895. ** See also the [sqlite3_commit_hook()], [sqlite3_rollback_hook()],
  6896. ** and [sqlite3_preupdate_hook()] interfaces.
  6897. */
  6898. SQLITE_API void *sqlite3_update_hook(
  6899. sqlite3*,
  6900. void(*)(void *,int ,char const *,char const *,sqlite3_int64),
  6901. void*
  6902. );
  6903. /*
  6904. ** CAPI3REF: Enable Or Disable Shared Pager Cache
  6905. **
  6906. ** ^(This routine enables or disables the sharing of the database cache
  6907. ** and schema data structures between [database connection | connections]
  6908. ** to the same database. Sharing is enabled if the argument is true
  6909. ** and disabled if the argument is false.)^
  6910. **
  6911. ** ^Cache sharing is enabled and disabled for an entire process.
  6912. ** This is a change as of SQLite [version 3.5.0] ([dateof:3.5.0]).
  6913. ** In prior versions of SQLite,
  6914. ** sharing was enabled or disabled for each thread separately.
  6915. **
  6916. ** ^(The cache sharing mode set by this interface effects all subsequent
  6917. ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
  6918. ** Existing database connections continue use the sharing mode
  6919. ** that was in effect at the time they were opened.)^
  6920. **
  6921. ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
  6922. ** successfully. An [error code] is returned otherwise.)^
  6923. **
  6924. ** ^Shared cache is disabled by default. But this might change in
  6925. ** future releases of SQLite. Applications that care about shared
  6926. ** cache setting should set it explicitly.
  6927. **
  6928. ** Note: This method is disabled on MacOS X 10.7 and iOS version 5.0
  6929. ** and will always return SQLITE_MISUSE. On those systems,
  6930. ** shared cache mode should be enabled per-database connection via
  6931. ** [sqlite3_open_v2()] with [SQLITE_OPEN_SHAREDCACHE].
  6932. **
  6933. ** This interface is threadsafe on processors where writing a
  6934. ** 32-bit integer is atomic.
  6935. **
  6936. ** See Also: [SQLite Shared-Cache Mode]
  6937. */
  6938. SQLITE_API int sqlite3_enable_shared_cache(int);
  6939. /*
  6940. ** CAPI3REF: Attempt To Free Heap Memory
  6941. **
  6942. ** ^The sqlite3_release_memory() interface attempts to free N bytes
  6943. ** of heap memory by deallocating non-essential memory allocations
  6944. ** held by the database library. Memory used to cache database
  6945. ** pages to improve performance is an example of non-essential memory.
  6946. ** ^sqlite3_release_memory() returns the number of bytes actually freed,
  6947. ** which might be more or less than the amount requested.
  6948. ** ^The sqlite3_release_memory() routine is a no-op returning zero
  6949. ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
  6950. **
  6951. ** See also: [sqlite3_db_release_memory()]
  6952. */
  6953. SQLITE_API int sqlite3_release_memory(int);
  6954. /*
  6955. ** CAPI3REF: Free Memory Used By A Database Connection
  6956. ** METHOD: sqlite3
  6957. **
  6958. ** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
  6959. ** memory as possible from database connection D. Unlike the
  6960. ** [sqlite3_release_memory()] interface, this interface is in effect even
  6961. ** when the [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
  6962. ** omitted.
  6963. **
  6964. ** See also: [sqlite3_release_memory()]
  6965. */
  6966. SQLITE_API int sqlite3_db_release_memory(sqlite3*);
  6967. /*
  6968. ** CAPI3REF: Impose A Limit On Heap Size
  6969. **
  6970. ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
  6971. ** soft limit on the amount of heap memory that may be allocated by SQLite.
  6972. ** ^SQLite strives to keep heap memory utilization below the soft heap
  6973. ** limit by reducing the number of pages held in the page cache
  6974. ** as heap memory usages approaches the limit.
  6975. ** ^The soft heap limit is "soft" because even though SQLite strives to stay
  6976. ** below the limit, it will exceed the limit rather than generate
  6977. ** an [SQLITE_NOMEM] error. In other words, the soft heap limit
  6978. ** is advisory only.
  6979. **
  6980. ** ^The return value from sqlite3_soft_heap_limit64() is the size of
  6981. ** the soft heap limit prior to the call, or negative in the case of an
  6982. ** error. ^If the argument N is negative
  6983. ** then no change is made to the soft heap limit. Hence, the current
  6984. ** size of the soft heap limit can be determined by invoking
  6985. ** sqlite3_soft_heap_limit64() with a negative argument.
  6986. **
  6987. ** ^If the argument N is zero then the soft heap limit is disabled.
  6988. **
  6989. ** ^(The soft heap limit is not enforced in the current implementation
  6990. ** if one or more of following conditions are true:
  6991. **
  6992. ** <ul>
  6993. ** <li> The soft heap limit is set to zero.
  6994. ** <li> Memory accounting is disabled using a combination of the
  6995. ** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
  6996. ** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
  6997. ** <li> An alternative page cache implementation is specified using
  6998. ** [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
  6999. ** <li> The page cache allocates from its own memory pool supplied
  7000. ** by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
  7001. ** from the heap.
  7002. ** </ul>)^
  7003. **
  7004. ** Beginning with SQLite [version 3.7.3] ([dateof:3.7.3]),
  7005. ** the soft heap limit is enforced
  7006. ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
  7007. ** compile-time option is invoked. With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
  7008. ** the soft heap limit is enforced on every memory allocation. Without
  7009. ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
  7010. ** when memory is allocated by the page cache. Testing suggests that because
  7011. ** the page cache is the predominate memory user in SQLite, most
  7012. ** applications will achieve adequate soft heap limit enforcement without
  7013. ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
  7014. **
  7015. ** The circumstances under which SQLite will enforce the soft heap limit may
  7016. ** changes in future releases of SQLite.
  7017. */
  7018. SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
  7019. /*
  7020. ** CAPI3REF: Deprecated Soft Heap Limit Interface
  7021. ** DEPRECATED
  7022. **
  7023. ** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
  7024. ** interface. This routine is provided for historical compatibility
  7025. ** only. All new applications should use the
  7026. ** [sqlite3_soft_heap_limit64()] interface rather than this one.
  7027. */
  7028. SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
  7029. /*
  7030. ** CAPI3REF: Extract Metadata About A Column Of A Table
  7031. ** METHOD: sqlite3
  7032. **
  7033. ** ^(The sqlite3_table_column_metadata(X,D,T,C,....) routine returns
  7034. ** information about column C of table T in database D
  7035. ** on [database connection] X.)^ ^The sqlite3_table_column_metadata()
  7036. ** interface returns SQLITE_OK and fills in the non-NULL pointers in
  7037. ** the final five arguments with appropriate values if the specified
  7038. ** column exists. ^The sqlite3_table_column_metadata() interface returns
  7039. ** SQLITE_ERROR and if the specified column does not exist.
  7040. ** ^If the column-name parameter to sqlite3_table_column_metadata() is a
  7041. ** NULL pointer, then this routine simply checks for the existence of the
  7042. ** table and returns SQLITE_OK if the table exists and SQLITE_ERROR if it
  7043. ** does not. If the table name parameter T in a call to
  7044. ** sqlite3_table_column_metadata(X,D,T,C,...) is NULL then the result is
  7045. ** undefined behavior.
  7046. **
  7047. ** ^The column is identified by the second, third and fourth parameters to
  7048. ** this function. ^(The second parameter is either the name of the database
  7049. ** (i.e. "main", "temp", or an attached database) containing the specified
  7050. ** table or NULL.)^ ^If it is NULL, then all attached databases are searched
  7051. ** for the table using the same algorithm used by the database engine to
  7052. ** resolve unqualified table references.
  7053. **
  7054. ** ^The third and fourth parameters to this function are the table and column
  7055. ** name of the desired column, respectively.
  7056. **
  7057. ** ^Metadata is returned by writing to the memory locations passed as the 5th
  7058. ** and subsequent parameters to this function. ^Any of these arguments may be
  7059. ** NULL, in which case the corresponding element of metadata is omitted.
  7060. **
  7061. ** ^(<blockquote>
  7062. ** <table border="1">
  7063. ** <tr><th> Parameter <th> Output<br>Type <th> Description
  7064. **
  7065. ** <tr><td> 5th <td> const char* <td> Data type
  7066. ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
  7067. ** <tr><td> 7th <td> int <td> True if column has a NOT NULL constraint
  7068. ** <tr><td> 8th <td> int <td> True if column is part of the PRIMARY KEY
  7069. ** <tr><td> 9th <td> int <td> True if column is [AUTOINCREMENT]
  7070. ** </table>
  7071. ** </blockquote>)^
  7072. **
  7073. ** ^The memory pointed to by the character pointers returned for the
  7074. ** declaration type and collation sequence is valid until the next
  7075. ** call to any SQLite API function.
  7076. **
  7077. ** ^If the specified table is actually a view, an [error code] is returned.
  7078. **
  7079. ** ^If the specified column is "rowid", "oid" or "_rowid_" and the table
  7080. ** is not a [WITHOUT ROWID] table and an
  7081. ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
  7082. ** parameters are set for the explicitly declared column. ^(If there is no
  7083. ** [INTEGER PRIMARY KEY] column, then the outputs
  7084. ** for the [rowid] are set as follows:
  7085. **
  7086. ** <pre>
  7087. ** data type: "INTEGER"
  7088. ** collation sequence: "BINARY"
  7089. ** not null: 0
  7090. ** primary key: 1
  7091. ** auto increment: 0
  7092. ** </pre>)^
  7093. **
  7094. ** ^This function causes all database schemas to be read from disk and
  7095. ** parsed, if that has not already been done, and returns an error if
  7096. ** any errors are encountered while loading the schema.
  7097. */
  7098. SQLITE_API int sqlite3_table_column_metadata(
  7099. sqlite3 *db, /* Connection handle */
  7100. const char *zDbName, /* Database name or NULL */
  7101. const char *zTableName, /* Table name */
  7102. const char *zColumnName, /* Column name */
  7103. char const **pzDataType, /* OUTPUT: Declared data type */
  7104. char const **pzCollSeq, /* OUTPUT: Collation sequence name */
  7105. int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
  7106. int *pPrimaryKey, /* OUTPUT: True if column part of PK */
  7107. int *pAutoinc /* OUTPUT: True if column is auto-increment */
  7108. );
  7109. /*
  7110. ** CAPI3REF: Load An Extension
  7111. ** METHOD: sqlite3
  7112. **
  7113. ** ^This interface loads an SQLite extension library from the named file.
  7114. **
  7115. ** ^The sqlite3_load_extension() interface attempts to load an
  7116. ** [SQLite extension] library contained in the file zFile. If
  7117. ** the file cannot be loaded directly, attempts are made to load
  7118. ** with various operating-system specific extensions added.
  7119. ** So for example, if "samplelib" cannot be loaded, then names like
  7120. ** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might
  7121. ** be tried also.
  7122. **
  7123. ** ^The entry point is zProc.
  7124. ** ^(zProc may be 0, in which case SQLite will try to come up with an
  7125. ** entry point name on its own. It first tries "sqlite3_extension_init".
  7126. ** If that does not work, it constructs a name "sqlite3_X_init" where the
  7127. ** X is consists of the lower-case equivalent of all ASCII alphabetic
  7128. ** characters in the filename from the last "/" to the first following
  7129. ** "." and omitting any initial "lib".)^
  7130. ** ^The sqlite3_load_extension() interface returns
  7131. ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
  7132. ** ^If an error occurs and pzErrMsg is not 0, then the
  7133. ** [sqlite3_load_extension()] interface shall attempt to
  7134. ** fill *pzErrMsg with error message text stored in memory
  7135. ** obtained from [sqlite3_malloc()]. The calling function
  7136. ** should free this memory by calling [sqlite3_free()].
  7137. **
  7138. ** ^Extension loading must be enabled using
  7139. ** [sqlite3_enable_load_extension()] or
  7140. ** [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],1,NULL)
  7141. ** prior to calling this API,
  7142. ** otherwise an error will be returned.
  7143. **
  7144. ** <b>Security warning:</b> It is recommended that the
  7145. ** [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method be used to enable only this
  7146. ** interface. The use of the [sqlite3_enable_load_extension()] interface
  7147. ** should be avoided. This will keep the SQL function [load_extension()]
  7148. ** disabled and prevent SQL injections from giving attackers
  7149. ** access to extension loading capabilities.
  7150. **
  7151. ** See also the [load_extension() SQL function].
  7152. */
  7153. SQLITE_API int sqlite3_load_extension(
  7154. sqlite3 *db, /* Load the extension into this database connection */
  7155. const char *zFile, /* Name of the shared library containing extension */
  7156. const char *zProc, /* Entry point. Derived from zFile if 0 */
  7157. char **pzErrMsg /* Put error message here if not 0 */
  7158. );
  7159. /*
  7160. ** CAPI3REF: Enable Or Disable Extension Loading
  7161. ** METHOD: sqlite3
  7162. **
  7163. ** ^So as not to open security holes in older applications that are
  7164. ** unprepared to deal with [extension loading], and as a means of disabling
  7165. ** [extension loading] while evaluating user-entered SQL, the following API
  7166. ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
  7167. **
  7168. ** ^Extension loading is off by default.
  7169. ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
  7170. ** to turn extension loading on and call it with onoff==0 to turn
  7171. ** it back off again.
  7172. **
  7173. ** ^This interface enables or disables both the C-API
  7174. ** [sqlite3_load_extension()] and the SQL function [load_extension()].
  7175. ** ^(Use [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],..)
  7176. ** to enable or disable only the C-API.)^
  7177. **
  7178. ** <b>Security warning:</b> It is recommended that extension loading
  7179. ** be disabled using the [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method
  7180. ** rather than this interface, so the [load_extension()] SQL function
  7181. ** remains disabled. This will prevent SQL injections from giving attackers
  7182. ** access to extension loading capabilities.
  7183. */
  7184. SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
  7185. /*
  7186. ** CAPI3REF: Automatically Load Statically Linked Extensions
  7187. **
  7188. ** ^This interface causes the xEntryPoint() function to be invoked for
  7189. ** each new [database connection] that is created. The idea here is that
  7190. ** xEntryPoint() is the entry point for a statically linked [SQLite extension]
  7191. ** that is to be automatically loaded into all new database connections.
  7192. **
  7193. ** ^(Even though the function prototype shows that xEntryPoint() takes
  7194. ** no arguments and returns void, SQLite invokes xEntryPoint() with three
  7195. ** arguments and expects an integer result as if the signature of the
  7196. ** entry point where as follows:
  7197. **
  7198. ** <blockquote><pre>
  7199. ** &nbsp; int xEntryPoint(
  7200. ** &nbsp; sqlite3 *db,
  7201. ** &nbsp; const char **pzErrMsg,
  7202. ** &nbsp; const struct sqlite3_api_routines *pThunk
  7203. ** &nbsp; );
  7204. ** </pre></blockquote>)^
  7205. **
  7206. ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
  7207. ** point to an appropriate error message (obtained from [sqlite3_mprintf()])
  7208. ** and return an appropriate [error code]. ^SQLite ensures that *pzErrMsg
  7209. ** is NULL before calling the xEntryPoint(). ^SQLite will invoke
  7210. ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any
  7211. ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
  7212. ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
  7213. **
  7214. ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
  7215. ** on the list of automatic extensions is a harmless no-op. ^No entry point
  7216. ** will be called more than once for each database connection that is opened.
  7217. **
  7218. ** See also: [sqlite3_reset_auto_extension()]
  7219. ** and [sqlite3_cancel_auto_extension()]
  7220. */
  7221. SQLITE_API int sqlite3_auto_extension(void(*xEntryPoint)(void));
  7222. /*
  7223. ** CAPI3REF: Cancel Automatic Extension Loading
  7224. **
  7225. ** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the
  7226. ** initialization routine X that was registered using a prior call to
  7227. ** [sqlite3_auto_extension(X)]. ^The [sqlite3_cancel_auto_extension(X)]
  7228. ** routine returns 1 if initialization routine X was successfully
  7229. ** unregistered and it returns 0 if X was not on the list of initialization
  7230. ** routines.
  7231. */
  7232. SQLITE_API int sqlite3_cancel_auto_extension(void(*xEntryPoint)(void));
  7233. /*
  7234. ** CAPI3REF: Reset Automatic Extension Loading
  7235. **
  7236. ** ^This interface disables all automatic extensions previously
  7237. ** registered using [sqlite3_auto_extension()].
  7238. */
  7239. SQLITE_API void sqlite3_reset_auto_extension(void);
  7240. /*
  7241. ** The interface to the virtual-table mechanism is currently considered
  7242. ** to be experimental. The interface might change in incompatible ways.
  7243. ** If this is a problem for you, do not use the interface at this time.
  7244. **
  7245. ** When the virtual-table mechanism stabilizes, we will declare the
  7246. ** interface fixed, support it indefinitely, and remove this comment.
  7247. */
  7248. /*
  7249. ** Structures used by the virtual table interface
  7250. */
  7251. typedef struct sqlite3_vtab sqlite3_vtab;
  7252. typedef struct sqlite3_index_info sqlite3_index_info;
  7253. typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
  7254. typedef struct sqlite3_module sqlite3_module;
  7255. /*
  7256. ** CAPI3REF: Virtual Table Object
  7257. ** KEYWORDS: sqlite3_module {virtual table module}
  7258. **
  7259. ** This structure, sometimes called a "virtual table module",
  7260. ** defines the implementation of a [virtual tables].
  7261. ** This structure consists mostly of methods for the module.
  7262. **
  7263. ** ^A virtual table module is created by filling in a persistent
  7264. ** instance of this structure and passing a pointer to that instance
  7265. ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
  7266. ** ^The registration remains valid until it is replaced by a different
  7267. ** module or until the [database connection] closes. The content
  7268. ** of this structure must not change while it is registered with
  7269. ** any database connection.
  7270. */
  7271. struct sqlite3_module {
  7272. int iVersion;
  7273. int (*xCreate)(sqlite3*, void *pAux,
  7274. int argc, const char *const*argv,
  7275. sqlite3_vtab **ppVTab, char**);
  7276. int (*xConnect)(sqlite3*, void *pAux,
  7277. int argc, const char *const*argv,
  7278. sqlite3_vtab **ppVTab, char**);
  7279. int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
  7280. int (*xDisconnect)(sqlite3_vtab *pVTab);
  7281. int (*xDestroy)(sqlite3_vtab *pVTab);
  7282. int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
  7283. int (*xClose)(sqlite3_vtab_cursor*);
  7284. int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
  7285. int argc, sqlite3_value **argv);
  7286. int (*xNext)(sqlite3_vtab_cursor*);
  7287. int (*xEof)(sqlite3_vtab_cursor*);
  7288. int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
  7289. int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
  7290. int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
  7291. int (*xBegin)(sqlite3_vtab *pVTab);
  7292. int (*xSync)(sqlite3_vtab *pVTab);
  7293. int (*xCommit)(sqlite3_vtab *pVTab);
  7294. int (*xRollback)(sqlite3_vtab *pVTab);
  7295. int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
  7296. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
  7297. void **ppArg);
  7298. int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
  7299. /* The methods above are in version 1 of the sqlite_module object. Those
  7300. ** below are for version 2 and greater. */
  7301. int (*xSavepoint)(sqlite3_vtab *pVTab, int);
  7302. int (*xRelease)(sqlite3_vtab *pVTab, int);
  7303. int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
  7304. /* The methods above are in versions 1 and 2 of the sqlite_module object.
  7305. ** Those below are for version 3 and greater. */
  7306. int (*xShadowName)(const char*);
  7307. };
  7308. /*
  7309. ** CAPI3REF: Virtual Table Indexing Information
  7310. ** KEYWORDS: sqlite3_index_info
  7311. **
  7312. ** The sqlite3_index_info structure and its substructures is used as part
  7313. ** of the [virtual table] interface to
  7314. ** pass information into and receive the reply from the [xBestIndex]
  7315. ** method of a [virtual table module]. The fields under **Inputs** are the
  7316. ** inputs to xBestIndex and are read-only. xBestIndex inserts its
  7317. ** results into the **Outputs** fields.
  7318. **
  7319. ** ^(The aConstraint[] array records WHERE clause constraints of the form:
  7320. **
  7321. ** <blockquote>column OP expr</blockquote>
  7322. **
  7323. ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^ ^(The particular operator is
  7324. ** stored in aConstraint[].op using one of the
  7325. ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
  7326. ** ^(The index of the column is stored in
  7327. ** aConstraint[].iColumn.)^ ^(aConstraint[].usable is TRUE if the
  7328. ** expr on the right-hand side can be evaluated (and thus the constraint
  7329. ** is usable) and false if it cannot.)^
  7330. **
  7331. ** ^The optimizer automatically inverts terms of the form "expr OP column"
  7332. ** and makes other simplifications to the WHERE clause in an attempt to
  7333. ** get as many WHERE clause terms into the form shown above as possible.
  7334. ** ^The aConstraint[] array only reports WHERE clause terms that are
  7335. ** relevant to the particular virtual table being queried.
  7336. **
  7337. ** ^Information about the ORDER BY clause is stored in aOrderBy[].
  7338. ** ^Each term of aOrderBy records a column of the ORDER BY clause.
  7339. **
  7340. ** The colUsed field indicates which columns of the virtual table may be
  7341. ** required by the current scan. Virtual table columns are numbered from
  7342. ** zero in the order in which they appear within the CREATE TABLE statement
  7343. ** passed to sqlite3_declare_vtab(). For the first 63 columns (columns 0-62),
  7344. ** the corresponding bit is set within the colUsed mask if the column may be
  7345. ** required by SQLite. If the table has at least 64 columns and any column
  7346. ** to the right of the first 63 is required, then bit 63 of colUsed is also
  7347. ** set. In other words, column iCol may be required if the expression
  7348. ** (colUsed & ((sqlite3_uint64)1 << (iCol>=63 ? 63 : iCol))) evaluates to
  7349. ** non-zero.
  7350. **
  7351. ** The [xBestIndex] method must fill aConstraintUsage[] with information
  7352. ** about what parameters to pass to xFilter. ^If argvIndex>0 then
  7353. ** the right-hand side of the corresponding aConstraint[] is evaluated
  7354. ** and becomes the argvIndex-th entry in argv. ^(If aConstraintUsage[].omit
  7355. ** is true, then the constraint is assumed to be fully handled by the
  7356. ** virtual table and is not checked again by SQLite.)^
  7357. **
  7358. ** ^The idxNum and idxPtr values are recorded and passed into the
  7359. ** [xFilter] method.
  7360. ** ^[sqlite3_free()] is used to free idxPtr if and only if
  7361. ** needToFreeIdxPtr is true.
  7362. **
  7363. ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
  7364. ** the correct order to satisfy the ORDER BY clause so that no separate
  7365. ** sorting step is required.
  7366. **
  7367. ** ^The estimatedCost value is an estimate of the cost of a particular
  7368. ** strategy. A cost of N indicates that the cost of the strategy is similar
  7369. ** to a linear scan of an SQLite table with N rows. A cost of log(N)
  7370. ** indicates that the expense of the operation is similar to that of a
  7371. ** binary search on a unique indexed field of an SQLite table with N rows.
  7372. **
  7373. ** ^The estimatedRows value is an estimate of the number of rows that
  7374. ** will be returned by the strategy.
  7375. **
  7376. ** The xBestIndex method may optionally populate the idxFlags field with a
  7377. ** mask of SQLITE_INDEX_SCAN_* flags. Currently there is only one such flag -
  7378. ** SQLITE_INDEX_SCAN_UNIQUE. If the xBestIndex method sets this flag, SQLite
  7379. ** assumes that the strategy may visit at most one row.
  7380. **
  7381. ** Additionally, if xBestIndex sets the SQLITE_INDEX_SCAN_UNIQUE flag, then
  7382. ** SQLite also assumes that if a call to the xUpdate() method is made as
  7383. ** part of the same statement to delete or update a virtual table row and the
  7384. ** implementation returns SQLITE_CONSTRAINT, then there is no need to rollback
  7385. ** any database changes. In other words, if the xUpdate() returns
  7386. ** SQLITE_CONSTRAINT, the database contents must be exactly as they were
  7387. ** before xUpdate was called. By contrast, if SQLITE_INDEX_SCAN_UNIQUE is not
  7388. ** set and xUpdate returns SQLITE_CONSTRAINT, any database changes made by
  7389. ** the xUpdate method are automatically rolled back by SQLite.
  7390. **
  7391. ** IMPORTANT: The estimatedRows field was added to the sqlite3_index_info
  7392. ** structure for SQLite [version 3.8.2] ([dateof:3.8.2]).
  7393. ** If a virtual table extension is
  7394. ** used with an SQLite version earlier than 3.8.2, the results of attempting
  7395. ** to read or write the estimatedRows field are undefined (but are likely
  7396. ** to included crashing the application). The estimatedRows field should
  7397. ** therefore only be used if [sqlite3_libversion_number()] returns a
  7398. ** value greater than or equal to 3008002. Similarly, the idxFlags field
  7399. ** was added for [version 3.9.0] ([dateof:3.9.0]).
  7400. ** It may therefore only be used if
  7401. ** sqlite3_libversion_number() returns a value greater than or equal to
  7402. ** 3009000.
  7403. */
  7404. struct sqlite3_index_info {
  7405. /* Inputs */
  7406. int nConstraint; /* Number of entries in aConstraint */
  7407. struct sqlite3_index_constraint {
  7408. int iColumn; /* Column constrained. -1 for ROWID */
  7409. unsigned char op; /* Constraint operator */
  7410. unsigned char usable; /* True if this constraint is usable */
  7411. int iTermOffset; /* Used internally - xBestIndex should ignore */
  7412. } *aConstraint; /* Table of WHERE clause constraints */
  7413. int nOrderBy; /* Number of terms in the ORDER BY clause */
  7414. struct sqlite3_index_orderby {
  7415. int iColumn; /* Column number */
  7416. unsigned char desc; /* True for DESC. False for ASC. */
  7417. } *aOrderBy; /* The ORDER BY clause */
  7418. /* Outputs */
  7419. struct sqlite3_index_constraint_usage {
  7420. int argvIndex; /* if >0, constraint is part of argv to xFilter */
  7421. unsigned char omit; /* Do not code a test for this constraint */
  7422. } *aConstraintUsage;
  7423. int idxNum; /* Number used to identify the index */
  7424. char *idxStr; /* String, possibly obtained from sqlite3_malloc */
  7425. int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */
  7426. int orderByConsumed; /* True if output is already ordered */
  7427. double estimatedCost; /* Estimated cost of using this index */
  7428. /* Fields below are only available in SQLite 3.8.2 and later */
  7429. sqlite3_int64 estimatedRows; /* Estimated number of rows returned */
  7430. /* Fields below are only available in SQLite 3.9.0 and later */
  7431. int idxFlags; /* Mask of SQLITE_INDEX_SCAN_* flags */
  7432. /* Fields below are only available in SQLite 3.10.0 and later */
  7433. sqlite3_uint64 colUsed; /* Input: Mask of columns used by statement */
  7434. };
  7435. /*
  7436. ** CAPI3REF: Virtual Table Scan Flags
  7437. **
  7438. ** Virtual table implementations are allowed to set the
  7439. ** [sqlite3_index_info].idxFlags field to some combination of
  7440. ** these bits.
  7441. */
  7442. #define SQLITE_INDEX_SCAN_UNIQUE 1 /* Scan visits at most 1 row */
  7443. /*
  7444. ** CAPI3REF: Virtual Table Constraint Operator Codes
  7445. **
  7446. ** These macros defined the allowed values for the
  7447. ** [sqlite3_index_info].aConstraint[].op field. Each value represents
  7448. ** an operator that is part of a constraint term in the wHERE clause of
  7449. ** a query that uses a [virtual table].
  7450. */
  7451. #define SQLITE_INDEX_CONSTRAINT_EQ 2
  7452. #define SQLITE_INDEX_CONSTRAINT_GT 4
  7453. #define SQLITE_INDEX_CONSTRAINT_LE 8
  7454. #define SQLITE_INDEX_CONSTRAINT_LT 16
  7455. #define SQLITE_INDEX_CONSTRAINT_GE 32
  7456. #define SQLITE_INDEX_CONSTRAINT_MATCH 64
  7457. #define SQLITE_INDEX_CONSTRAINT_LIKE 65
  7458. #define SQLITE_INDEX_CONSTRAINT_GLOB 66
  7459. #define SQLITE_INDEX_CONSTRAINT_REGEXP 67
  7460. #define SQLITE_INDEX_CONSTRAINT_NE 68
  7461. #define SQLITE_INDEX_CONSTRAINT_ISNOT 69
  7462. #define SQLITE_INDEX_CONSTRAINT_ISNOTNULL 70
  7463. #define SQLITE_INDEX_CONSTRAINT_ISNULL 71
  7464. #define SQLITE_INDEX_CONSTRAINT_IS 72
  7465. #define SQLITE_INDEX_CONSTRAINT_FUNCTION 150
  7466. /*
  7467. ** CAPI3REF: Register A Virtual Table Implementation
  7468. ** METHOD: sqlite3
  7469. **
  7470. ** ^These routines are used to register a new [virtual table module] name.
  7471. ** ^Module names must be registered before
  7472. ** creating a new [virtual table] using the module and before using a
  7473. ** preexisting [virtual table] for the module.
  7474. **
  7475. ** ^The module name is registered on the [database connection] specified
  7476. ** by the first parameter. ^The name of the module is given by the
  7477. ** second parameter. ^The third parameter is a pointer to
  7478. ** the implementation of the [virtual table module]. ^The fourth
  7479. ** parameter is an arbitrary client data pointer that is passed through
  7480. ** into the [xCreate] and [xConnect] methods of the virtual table module
  7481. ** when a new virtual table is be being created or reinitialized.
  7482. **
  7483. ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
  7484. ** is a pointer to a destructor for the pClientData. ^SQLite will
  7485. ** invoke the destructor function (if it is not NULL) when SQLite
  7486. ** no longer needs the pClientData pointer. ^The destructor will also
  7487. ** be invoked if the call to sqlite3_create_module_v2() fails.
  7488. ** ^The sqlite3_create_module()
  7489. ** interface is equivalent to sqlite3_create_module_v2() with a NULL
  7490. ** destructor.
  7491. */
  7492. SQLITE_API int sqlite3_create_module(
  7493. sqlite3 *db, /* SQLite connection to register module with */
  7494. const char *zName, /* Name of the module */
  7495. const sqlite3_module *p, /* Methods for the module */
  7496. void *pClientData /* Client data for xCreate/xConnect */
  7497. );
  7498. SQLITE_API int sqlite3_create_module_v2(
  7499. sqlite3 *db, /* SQLite connection to register module with */
  7500. const char *zName, /* Name of the module */
  7501. const sqlite3_module *p, /* Methods for the module */
  7502. void *pClientData, /* Client data for xCreate/xConnect */
  7503. void(*xDestroy)(void*) /* Module destructor function */
  7504. );
  7505. /*
  7506. ** CAPI3REF: Virtual Table Instance Object
  7507. ** KEYWORDS: sqlite3_vtab
  7508. **
  7509. ** Every [virtual table module] implementation uses a subclass
  7510. ** of this object to describe a particular instance
  7511. ** of the [virtual table]. Each subclass will
  7512. ** be tailored to the specific needs of the module implementation.
  7513. ** The purpose of this superclass is to define certain fields that are
  7514. ** common to all module implementations.
  7515. **
  7516. ** ^Virtual tables methods can set an error message by assigning a
  7517. ** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should
  7518. ** take care that any prior string is freed by a call to [sqlite3_free()]
  7519. ** prior to assigning a new string to zErrMsg. ^After the error message
  7520. ** is delivered up to the client application, the string will be automatically
  7521. ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
  7522. */
  7523. struct sqlite3_vtab {
  7524. const sqlite3_module *pModule; /* The module for this virtual table */
  7525. int nRef; /* Number of open cursors */
  7526. char *zErrMsg; /* Error message from sqlite3_mprintf() */
  7527. /* Virtual table implementations will typically add additional fields */
  7528. };
  7529. /*
  7530. ** CAPI3REF: Virtual Table Cursor Object
  7531. ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
  7532. **
  7533. ** Every [virtual table module] implementation uses a subclass of the
  7534. ** following structure to describe cursors that point into the
  7535. ** [virtual table] and are used
  7536. ** to loop through the virtual table. Cursors are created using the
  7537. ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
  7538. ** by the [sqlite3_module.xClose | xClose] method. Cursors are used
  7539. ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
  7540. ** of the module. Each module implementation will define
  7541. ** the content of a cursor structure to suit its own needs.
  7542. **
  7543. ** This superclass exists in order to define fields of the cursor that
  7544. ** are common to all implementations.
  7545. */
  7546. struct sqlite3_vtab_cursor {
  7547. sqlite3_vtab *pVtab; /* Virtual table of this cursor */
  7548. /* Virtual table implementations will typically add additional fields */
  7549. };
  7550. /*
  7551. ** CAPI3REF: Declare The Schema Of A Virtual Table
  7552. **
  7553. ** ^The [xCreate] and [xConnect] methods of a
  7554. ** [virtual table module] call this interface
  7555. ** to declare the format (the names and datatypes of the columns) of
  7556. ** the virtual tables they implement.
  7557. */
  7558. SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
  7559. /*
  7560. ** CAPI3REF: Overload A Function For A Virtual Table
  7561. ** METHOD: sqlite3
  7562. **
  7563. ** ^(Virtual tables can provide alternative implementations of functions
  7564. ** using the [xFindFunction] method of the [virtual table module].
  7565. ** But global versions of those functions
  7566. ** must exist in order to be overloaded.)^
  7567. **
  7568. ** ^(This API makes sure a global version of a function with a particular
  7569. ** name and number of parameters exists. If no such function exists
  7570. ** before this API is called, a new function is created.)^ ^The implementation
  7571. ** of the new function always causes an exception to be thrown. So
  7572. ** the new function is not good for anything by itself. Its only
  7573. ** purpose is to be a placeholder function that can be overloaded
  7574. ** by a [virtual table].
  7575. */
  7576. SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
  7577. /*
  7578. ** The interface to the virtual-table mechanism defined above (back up
  7579. ** to a comment remarkably similar to this one) is currently considered
  7580. ** to be experimental. The interface might change in incompatible ways.
  7581. ** If this is a problem for you, do not use the interface at this time.
  7582. **
  7583. ** When the virtual-table mechanism stabilizes, we will declare the
  7584. ** interface fixed, support it indefinitely, and remove this comment.
  7585. */
  7586. /*
  7587. ** CAPI3REF: A Handle To An Open BLOB
  7588. ** KEYWORDS: {BLOB handle} {BLOB handles}
  7589. **
  7590. ** An instance of this object represents an open BLOB on which
  7591. ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
  7592. ** ^Objects of this type are created by [sqlite3_blob_open()]
  7593. ** and destroyed by [sqlite3_blob_close()].
  7594. ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
  7595. ** can be used to read or write small subsections of the BLOB.
  7596. ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
  7597. */
  7598. typedef struct sqlite3_blob sqlite3_blob;
  7599. /*
  7600. ** CAPI3REF: Open A BLOB For Incremental I/O
  7601. ** METHOD: sqlite3
  7602. ** CONSTRUCTOR: sqlite3_blob
  7603. **
  7604. ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
  7605. ** in row iRow, column zColumn, table zTable in database zDb;
  7606. ** in other words, the same BLOB that would be selected by:
  7607. **
  7608. ** <pre>
  7609. ** SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
  7610. ** </pre>)^
  7611. **
  7612. ** ^(Parameter zDb is not the filename that contains the database, but
  7613. ** rather the symbolic name of the database. For attached databases, this is
  7614. ** the name that appears after the AS keyword in the [ATTACH] statement.
  7615. ** For the main database file, the database name is "main". For TEMP
  7616. ** tables, the database name is "temp".)^
  7617. **
  7618. ** ^If the flags parameter is non-zero, then the BLOB is opened for read
  7619. ** and write access. ^If the flags parameter is zero, the BLOB is opened for
  7620. ** read-only access.
  7621. **
  7622. ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is stored
  7623. ** in *ppBlob. Otherwise an [error code] is returned and, unless the error
  7624. ** code is SQLITE_MISUSE, *ppBlob is set to NULL.)^ ^This means that, provided
  7625. ** the API is not misused, it is always safe to call [sqlite3_blob_close()]
  7626. ** on *ppBlob after this function it returns.
  7627. **
  7628. ** This function fails with SQLITE_ERROR if any of the following are true:
  7629. ** <ul>
  7630. ** <li> ^(Database zDb does not exist)^,
  7631. ** <li> ^(Table zTable does not exist within database zDb)^,
  7632. ** <li> ^(Table zTable is a WITHOUT ROWID table)^,
  7633. ** <li> ^(Column zColumn does not exist)^,
  7634. ** <li> ^(Row iRow is not present in the table)^,
  7635. ** <li> ^(The specified column of row iRow contains a value that is not
  7636. ** a TEXT or BLOB value)^,
  7637. ** <li> ^(Column zColumn is part of an index, PRIMARY KEY or UNIQUE
  7638. ** constraint and the blob is being opened for read/write access)^,
  7639. ** <li> ^([foreign key constraints | Foreign key constraints] are enabled,
  7640. ** column zColumn is part of a [child key] definition and the blob is
  7641. ** being opened for read/write access)^.
  7642. ** </ul>
  7643. **
  7644. ** ^Unless it returns SQLITE_MISUSE, this function sets the
  7645. ** [database connection] error code and message accessible via
  7646. ** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
  7647. **
  7648. ** A BLOB referenced by sqlite3_blob_open() may be read using the
  7649. ** [sqlite3_blob_read()] interface and modified by using
  7650. ** [sqlite3_blob_write()]. The [BLOB handle] can be moved to a
  7651. ** different row of the same table using the [sqlite3_blob_reopen()]
  7652. ** interface. However, the column, table, or database of a [BLOB handle]
  7653. ** cannot be changed after the [BLOB handle] is opened.
  7654. **
  7655. ** ^(If the row that a BLOB handle points to is modified by an
  7656. ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
  7657. ** then the BLOB handle is marked as "expired".
  7658. ** This is true if any column of the row is changed, even a column
  7659. ** other than the one the BLOB handle is open on.)^
  7660. ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
  7661. ** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
  7662. ** ^(Changes written into a BLOB prior to the BLOB expiring are not
  7663. ** rolled back by the expiration of the BLOB. Such changes will eventually
  7664. ** commit if the transaction continues to completion.)^
  7665. **
  7666. ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
  7667. ** the opened blob. ^The size of a blob may not be changed by this
  7668. ** interface. Use the [UPDATE] SQL command to change the size of a
  7669. ** blob.
  7670. **
  7671. ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
  7672. ** and the built-in [zeroblob] SQL function may be used to create a
  7673. ** zero-filled blob to read or write using the incremental-blob interface.
  7674. **
  7675. ** To avoid a resource leak, every open [BLOB handle] should eventually
  7676. ** be released by a call to [sqlite3_blob_close()].
  7677. **
  7678. ** See also: [sqlite3_blob_close()],
  7679. ** [sqlite3_blob_reopen()], [sqlite3_blob_read()],
  7680. ** [sqlite3_blob_bytes()], [sqlite3_blob_write()].
  7681. */
  7682. SQLITE_API int sqlite3_blob_open(
  7683. sqlite3*,
  7684. const char *zDb,
  7685. const char *zTable,
  7686. const char *zColumn,
  7687. sqlite3_int64 iRow,
  7688. int flags,
  7689. sqlite3_blob **ppBlob
  7690. );
  7691. /*
  7692. ** CAPI3REF: Move a BLOB Handle to a New Row
  7693. ** METHOD: sqlite3_blob
  7694. **
  7695. ** ^This function is used to move an existing [BLOB handle] so that it points
  7696. ** to a different row of the same database table. ^The new row is identified
  7697. ** by the rowid value passed as the second argument. Only the row can be
  7698. ** changed. ^The database, table and column on which the blob handle is open
  7699. ** remain the same. Moving an existing [BLOB handle] to a new row is
  7700. ** faster than closing the existing handle and opening a new one.
  7701. **
  7702. ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
  7703. ** it must exist and there must be either a blob or text value stored in
  7704. ** the nominated column.)^ ^If the new row is not present in the table, or if
  7705. ** it does not contain a blob or text value, or if another error occurs, an
  7706. ** SQLite error code is returned and the blob handle is considered aborted.
  7707. ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
  7708. ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
  7709. ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
  7710. ** always returns zero.
  7711. **
  7712. ** ^This function sets the database handle error code and message.
  7713. */
  7714. SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
  7715. /*
  7716. ** CAPI3REF: Close A BLOB Handle
  7717. ** DESTRUCTOR: sqlite3_blob
  7718. **
  7719. ** ^This function closes an open [BLOB handle]. ^(The BLOB handle is closed
  7720. ** unconditionally. Even if this routine returns an error code, the
  7721. ** handle is still closed.)^
  7722. **
  7723. ** ^If the blob handle being closed was opened for read-write access, and if
  7724. ** the database is in auto-commit mode and there are no other open read-write
  7725. ** blob handles or active write statements, the current transaction is
  7726. ** committed. ^If an error occurs while committing the transaction, an error
  7727. ** code is returned and the transaction rolled back.
  7728. **
  7729. ** Calling this function with an argument that is not a NULL pointer or an
  7730. ** open blob handle results in undefined behaviour. ^Calling this routine
  7731. ** with a null pointer (such as would be returned by a failed call to
  7732. ** [sqlite3_blob_open()]) is a harmless no-op. ^Otherwise, if this function
  7733. ** is passed a valid open blob handle, the values returned by the
  7734. ** sqlite3_errcode() and sqlite3_errmsg() functions are set before returning.
  7735. */
  7736. SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
  7737. /*
  7738. ** CAPI3REF: Return The Size Of An Open BLOB
  7739. ** METHOD: sqlite3_blob
  7740. **
  7741. ** ^Returns the size in bytes of the BLOB accessible via the
  7742. ** successfully opened [BLOB handle] in its only argument. ^The
  7743. ** incremental blob I/O routines can only read or overwriting existing
  7744. ** blob content; they cannot change the size of a blob.
  7745. **
  7746. ** This routine only works on a [BLOB handle] which has been created
  7747. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  7748. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  7749. ** to this routine results in undefined and probably undesirable behavior.
  7750. */
  7751. SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
  7752. /*
  7753. ** CAPI3REF: Read Data From A BLOB Incrementally
  7754. ** METHOD: sqlite3_blob
  7755. **
  7756. ** ^(This function is used to read data from an open [BLOB handle] into a
  7757. ** caller-supplied buffer. N bytes of data are copied into buffer Z
  7758. ** from the open BLOB, starting at offset iOffset.)^
  7759. **
  7760. ** ^If offset iOffset is less than N bytes from the end of the BLOB,
  7761. ** [SQLITE_ERROR] is returned and no data is read. ^If N or iOffset is
  7762. ** less than zero, [SQLITE_ERROR] is returned and no data is read.
  7763. ** ^The size of the blob (and hence the maximum value of N+iOffset)
  7764. ** can be determined using the [sqlite3_blob_bytes()] interface.
  7765. **
  7766. ** ^An attempt to read from an expired [BLOB handle] fails with an
  7767. ** error code of [SQLITE_ABORT].
  7768. **
  7769. ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
  7770. ** Otherwise, an [error code] or an [extended error code] is returned.)^
  7771. **
  7772. ** This routine only works on a [BLOB handle] which has been created
  7773. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  7774. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  7775. ** to this routine results in undefined and probably undesirable behavior.
  7776. **
  7777. ** See also: [sqlite3_blob_write()].
  7778. */
  7779. SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
  7780. /*
  7781. ** CAPI3REF: Write Data Into A BLOB Incrementally
  7782. ** METHOD: sqlite3_blob
  7783. **
  7784. ** ^(This function is used to write data into an open [BLOB handle] from a
  7785. ** caller-supplied buffer. N bytes of data are copied from the buffer Z
  7786. ** into the open BLOB, starting at offset iOffset.)^
  7787. **
  7788. ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
  7789. ** Otherwise, an [error code] or an [extended error code] is returned.)^
  7790. ** ^Unless SQLITE_MISUSE is returned, this function sets the
  7791. ** [database connection] error code and message accessible via
  7792. ** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
  7793. **
  7794. ** ^If the [BLOB handle] passed as the first argument was not opened for
  7795. ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
  7796. ** this function returns [SQLITE_READONLY].
  7797. **
  7798. ** This function may only modify the contents of the BLOB; it is
  7799. ** not possible to increase the size of a BLOB using this API.
  7800. ** ^If offset iOffset is less than N bytes from the end of the BLOB,
  7801. ** [SQLITE_ERROR] is returned and no data is written. The size of the
  7802. ** BLOB (and hence the maximum value of N+iOffset) can be determined
  7803. ** using the [sqlite3_blob_bytes()] interface. ^If N or iOffset are less
  7804. ** than zero [SQLITE_ERROR] is returned and no data is written.
  7805. **
  7806. ** ^An attempt to write to an expired [BLOB handle] fails with an
  7807. ** error code of [SQLITE_ABORT]. ^Writes to the BLOB that occurred
  7808. ** before the [BLOB handle] expired are not rolled back by the
  7809. ** expiration of the handle, though of course those changes might
  7810. ** have been overwritten by the statement that expired the BLOB handle
  7811. ** or by other independent statements.
  7812. **
  7813. ** This routine only works on a [BLOB handle] which has been created
  7814. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  7815. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  7816. ** to this routine results in undefined and probably undesirable behavior.
  7817. **
  7818. ** See also: [sqlite3_blob_read()].
  7819. */
  7820. SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
  7821. /*
  7822. ** CAPI3REF: Virtual File System Objects
  7823. **
  7824. ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
  7825. ** that SQLite uses to interact
  7826. ** with the underlying operating system. Most SQLite builds come with a
  7827. ** single default VFS that is appropriate for the host computer.
  7828. ** New VFSes can be registered and existing VFSes can be unregistered.
  7829. ** The following interfaces are provided.
  7830. **
  7831. ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
  7832. ** ^Names are case sensitive.
  7833. ** ^Names are zero-terminated UTF-8 strings.
  7834. ** ^If there is no match, a NULL pointer is returned.
  7835. ** ^If zVfsName is NULL then the default VFS is returned.
  7836. **
  7837. ** ^New VFSes are registered with sqlite3_vfs_register().
  7838. ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
  7839. ** ^The same VFS can be registered multiple times without injury.
  7840. ** ^To make an existing VFS into the default VFS, register it again
  7841. ** with the makeDflt flag set. If two different VFSes with the
  7842. ** same name are registered, the behavior is undefined. If a
  7843. ** VFS is registered with a name that is NULL or an empty string,
  7844. ** then the behavior is undefined.
  7845. **
  7846. ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
  7847. ** ^(If the default VFS is unregistered, another VFS is chosen as
  7848. ** the default. The choice for the new VFS is arbitrary.)^
  7849. */
  7850. SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
  7851. SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
  7852. SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
  7853. /*
  7854. ** CAPI3REF: Mutexes
  7855. **
  7856. ** The SQLite core uses these routines for thread
  7857. ** synchronization. Though they are intended for internal
  7858. ** use by SQLite, code that links against SQLite is
  7859. ** permitted to use any of these routines.
  7860. **
  7861. ** The SQLite source code contains multiple implementations
  7862. ** of these mutex routines. An appropriate implementation
  7863. ** is selected automatically at compile-time. The following
  7864. ** implementations are available in the SQLite core:
  7865. **
  7866. ** <ul>
  7867. ** <li> SQLITE_MUTEX_PTHREADS
  7868. ** <li> SQLITE_MUTEX_W32
  7869. ** <li> SQLITE_MUTEX_NOOP
  7870. ** </ul>
  7871. **
  7872. ** The SQLITE_MUTEX_NOOP implementation is a set of routines
  7873. ** that does no real locking and is appropriate for use in
  7874. ** a single-threaded application. The SQLITE_MUTEX_PTHREADS and
  7875. ** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix
  7876. ** and Windows.
  7877. **
  7878. ** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
  7879. ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
  7880. ** implementation is included with the library. In this case the
  7881. ** application must supply a custom mutex implementation using the
  7882. ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
  7883. ** before calling sqlite3_initialize() or any other public sqlite3_
  7884. ** function that calls sqlite3_initialize().
  7885. **
  7886. ** ^The sqlite3_mutex_alloc() routine allocates a new
  7887. ** mutex and returns a pointer to it. ^The sqlite3_mutex_alloc()
  7888. ** routine returns NULL if it is unable to allocate the requested
  7889. ** mutex. The argument to sqlite3_mutex_alloc() must one of these
  7890. ** integer constants:
  7891. **
  7892. ** <ul>
  7893. ** <li> SQLITE_MUTEX_FAST
  7894. ** <li> SQLITE_MUTEX_RECURSIVE
  7895. ** <li> SQLITE_MUTEX_STATIC_MASTER
  7896. ** <li> SQLITE_MUTEX_STATIC_MEM
  7897. ** <li> SQLITE_MUTEX_STATIC_OPEN
  7898. ** <li> SQLITE_MUTEX_STATIC_PRNG
  7899. ** <li> SQLITE_MUTEX_STATIC_LRU
  7900. ** <li> SQLITE_MUTEX_STATIC_PMEM
  7901. ** <li> SQLITE_MUTEX_STATIC_APP1
  7902. ** <li> SQLITE_MUTEX_STATIC_APP2
  7903. ** <li> SQLITE_MUTEX_STATIC_APP3
  7904. ** <li> SQLITE_MUTEX_STATIC_VFS1
  7905. ** <li> SQLITE_MUTEX_STATIC_VFS2
  7906. ** <li> SQLITE_MUTEX_STATIC_VFS3
  7907. ** </ul>
  7908. **
  7909. ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
  7910. ** cause sqlite3_mutex_alloc() to create
  7911. ** a new mutex. ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  7912. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  7913. ** The mutex implementation does not need to make a distinction
  7914. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  7915. ** not want to. SQLite will only request a recursive mutex in
  7916. ** cases where it really needs one. If a faster non-recursive mutex
  7917. ** implementation is available on the host platform, the mutex subsystem
  7918. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  7919. **
  7920. ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
  7921. ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
  7922. ** a pointer to a static preexisting mutex. ^Nine static mutexes are
  7923. ** used by the current version of SQLite. Future versions of SQLite
  7924. ** may add additional static mutexes. Static mutexes are for internal
  7925. ** use by SQLite only. Applications that use SQLite mutexes should
  7926. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  7927. ** SQLITE_MUTEX_RECURSIVE.
  7928. **
  7929. ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  7930. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  7931. ** returns a different mutex on every call. ^For the static
  7932. ** mutex types, the same mutex is returned on every call that has
  7933. ** the same type number.
  7934. **
  7935. ** ^The sqlite3_mutex_free() routine deallocates a previously
  7936. ** allocated dynamic mutex. Attempting to deallocate a static
  7937. ** mutex results in undefined behavior.
  7938. **
  7939. ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  7940. ** to enter a mutex. ^If another thread is already within the mutex,
  7941. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  7942. ** SQLITE_BUSY. ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
  7943. ** upon successful entry. ^(Mutexes created using
  7944. ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
  7945. ** In such cases, the
  7946. ** mutex must be exited an equal number of times before another thread
  7947. ** can enter.)^ If the same thread tries to enter any mutex other
  7948. ** than an SQLITE_MUTEX_RECURSIVE more than once, the behavior is undefined.
  7949. **
  7950. ** ^(Some systems (for example, Windows 95) do not support the operation
  7951. ** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try()
  7952. ** will always return SQLITE_BUSY. The SQLite core only ever uses
  7953. ** sqlite3_mutex_try() as an optimization so this is acceptable
  7954. ** behavior.)^
  7955. **
  7956. ** ^The sqlite3_mutex_leave() routine exits a mutex that was
  7957. ** previously entered by the same thread. The behavior
  7958. ** is undefined if the mutex is not currently entered by the
  7959. ** calling thread or is not currently allocated.
  7960. **
  7961. ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
  7962. ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
  7963. ** behave as no-ops.
  7964. **
  7965. ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
  7966. */
  7967. SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
  7968. SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
  7969. SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
  7970. SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
  7971. SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
  7972. /*
  7973. ** CAPI3REF: Mutex Methods Object
  7974. **
  7975. ** An instance of this structure defines the low-level routines
  7976. ** used to allocate and use mutexes.
  7977. **
  7978. ** Usually, the default mutex implementations provided by SQLite are
  7979. ** sufficient, however the application has the option of substituting a custom
  7980. ** implementation for specialized deployments or systems for which SQLite
  7981. ** does not provide a suitable implementation. In this case, the application
  7982. ** creates and populates an instance of this structure to pass
  7983. ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
  7984. ** Additionally, an instance of this structure can be used as an
  7985. ** output variable when querying the system for the current mutex
  7986. ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
  7987. **
  7988. ** ^The xMutexInit method defined by this structure is invoked as
  7989. ** part of system initialization by the sqlite3_initialize() function.
  7990. ** ^The xMutexInit routine is called by SQLite exactly once for each
  7991. ** effective call to [sqlite3_initialize()].
  7992. **
  7993. ** ^The xMutexEnd method defined by this structure is invoked as
  7994. ** part of system shutdown by the sqlite3_shutdown() function. The
  7995. ** implementation of this method is expected to release all outstanding
  7996. ** resources obtained by the mutex methods implementation, especially
  7997. ** those obtained by the xMutexInit method. ^The xMutexEnd()
  7998. ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
  7999. **
  8000. ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
  8001. ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
  8002. ** xMutexNotheld) implement the following interfaces (respectively):
  8003. **
  8004. ** <ul>
  8005. ** <li> [sqlite3_mutex_alloc()] </li>
  8006. ** <li> [sqlite3_mutex_free()] </li>
  8007. ** <li> [sqlite3_mutex_enter()] </li>
  8008. ** <li> [sqlite3_mutex_try()] </li>
  8009. ** <li> [sqlite3_mutex_leave()] </li>
  8010. ** <li> [sqlite3_mutex_held()] </li>
  8011. ** <li> [sqlite3_mutex_notheld()] </li>
  8012. ** </ul>)^
  8013. **
  8014. ** The only difference is that the public sqlite3_XXX functions enumerated
  8015. ** above silently ignore any invocations that pass a NULL pointer instead
  8016. ** of a valid mutex handle. The implementations of the methods defined
  8017. ** by this structure are not required to handle this case, the results
  8018. ** of passing a NULL pointer instead of a valid mutex handle are undefined
  8019. ** (i.e. it is acceptable to provide an implementation that segfaults if
  8020. ** it is passed a NULL pointer).
  8021. **
  8022. ** The xMutexInit() method must be threadsafe. It must be harmless to
  8023. ** invoke xMutexInit() multiple times within the same process and without
  8024. ** intervening calls to xMutexEnd(). Second and subsequent calls to
  8025. ** xMutexInit() must be no-ops.
  8026. **
  8027. ** xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
  8028. ** and its associates). Similarly, xMutexAlloc() must not use SQLite memory
  8029. ** allocation for a static mutex. ^However xMutexAlloc() may use SQLite
  8030. ** memory allocation for a fast or recursive mutex.
  8031. **
  8032. ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
  8033. ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
  8034. ** If xMutexInit fails in any way, it is expected to clean up after itself
  8035. ** prior to returning.
  8036. */
  8037. typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
  8038. struct sqlite3_mutex_methods {
  8039. int (*xMutexInit)(void);
  8040. int (*xMutexEnd)(void);
  8041. sqlite3_mutex *(*xMutexAlloc)(int);
  8042. void (*xMutexFree)(sqlite3_mutex *);
  8043. void (*xMutexEnter)(sqlite3_mutex *);
  8044. int (*xMutexTry)(sqlite3_mutex *);
  8045. void (*xMutexLeave)(sqlite3_mutex *);
  8046. int (*xMutexHeld)(sqlite3_mutex *);
  8047. int (*xMutexNotheld)(sqlite3_mutex *);
  8048. };
  8049. /*
  8050. ** CAPI3REF: Mutex Verification Routines
  8051. **
  8052. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
  8053. ** are intended for use inside assert() statements. The SQLite core
  8054. ** never uses these routines except inside an assert() and applications
  8055. ** are advised to follow the lead of the core. The SQLite core only
  8056. ** provides implementations for these routines when it is compiled
  8057. ** with the SQLITE_DEBUG flag. External mutex implementations
  8058. ** are only required to provide these routines if SQLITE_DEBUG is
  8059. ** defined and if NDEBUG is not defined.
  8060. **
  8061. ** These routines should return true if the mutex in their argument
  8062. ** is held or not held, respectively, by the calling thread.
  8063. **
  8064. ** The implementation is not required to provide versions of these
  8065. ** routines that actually work. If the implementation does not provide working
  8066. ** versions of these routines, it should at least provide stubs that always
  8067. ** return true so that one does not get spurious assertion failures.
  8068. **
  8069. ** If the argument to sqlite3_mutex_held() is a NULL pointer then
  8070. ** the routine should return 1. This seems counter-intuitive since
  8071. ** clearly the mutex cannot be held if it does not exist. But
  8072. ** the reason the mutex does not exist is because the build is not
  8073. ** using mutexes. And we do not want the assert() containing the
  8074. ** call to sqlite3_mutex_held() to fail, so a non-zero return is
  8075. ** the appropriate thing to do. The sqlite3_mutex_notheld()
  8076. ** interface should also return 1 when given a NULL pointer.
  8077. */
  8078. #ifndef NDEBUG
  8079. SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
  8080. SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
  8081. #endif
  8082. /*
  8083. ** CAPI3REF: Mutex Types
  8084. **
  8085. ** The [sqlite3_mutex_alloc()] interface takes a single argument
  8086. ** which is one of these integer constants.
  8087. **
  8088. ** The set of static mutexes may change from one SQLite release to the
  8089. ** next. Applications that override the built-in mutex logic must be
  8090. ** prepared to accommodate additional static mutexes.
  8091. */
  8092. #define SQLITE_MUTEX_FAST 0
  8093. #define SQLITE_MUTEX_RECURSIVE 1
  8094. #define SQLITE_MUTEX_STATIC_MASTER 2
  8095. #define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */
  8096. #define SQLITE_MUTEX_STATIC_MEM2 4 /* NOT USED */
  8097. #define SQLITE_MUTEX_STATIC_OPEN 4 /* sqlite3BtreeOpen() */
  8098. #define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_randomness() */
  8099. #define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */
  8100. #define SQLITE_MUTEX_STATIC_LRU2 7 /* NOT USED */
  8101. #define SQLITE_MUTEX_STATIC_PMEM 7 /* sqlite3PageMalloc() */
  8102. #define SQLITE_MUTEX_STATIC_APP1 8 /* For use by application */
  8103. #define SQLITE_MUTEX_STATIC_APP2 9 /* For use by application */
  8104. #define SQLITE_MUTEX_STATIC_APP3 10 /* For use by application */
  8105. #define SQLITE_MUTEX_STATIC_VFS1 11 /* For use by built-in VFS */
  8106. #define SQLITE_MUTEX_STATIC_VFS2 12 /* For use by extension VFS */
  8107. #define SQLITE_MUTEX_STATIC_VFS3 13 /* For use by application VFS */
  8108. /*
  8109. ** CAPI3REF: Retrieve the mutex for a database connection
  8110. ** METHOD: sqlite3
  8111. **
  8112. ** ^This interface returns a pointer the [sqlite3_mutex] object that
  8113. ** serializes access to the [database connection] given in the argument
  8114. ** when the [threading mode] is Serialized.
  8115. ** ^If the [threading mode] is Single-thread or Multi-thread then this
  8116. ** routine returns a NULL pointer.
  8117. */
  8118. SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
  8119. /*
  8120. ** CAPI3REF: Low-Level Control Of Database Files
  8121. ** METHOD: sqlite3
  8122. ** KEYWORDS: {file control}
  8123. **
  8124. ** ^The [sqlite3_file_control()] interface makes a direct call to the
  8125. ** xFileControl method for the [sqlite3_io_methods] object associated
  8126. ** with a particular database identified by the second argument. ^The
  8127. ** name of the database is "main" for the main database or "temp" for the
  8128. ** TEMP database, or the name that appears after the AS keyword for
  8129. ** databases that are added using the [ATTACH] SQL command.
  8130. ** ^A NULL pointer can be used in place of "main" to refer to the
  8131. ** main database file.
  8132. ** ^The third and fourth parameters to this routine
  8133. ** are passed directly through to the second and third parameters of
  8134. ** the xFileControl method. ^The return value of the xFileControl
  8135. ** method becomes the return value of this routine.
  8136. **
  8137. ** A few opcodes for [sqlite3_file_control()] are handled directly
  8138. ** by the SQLite core and never invoke the
  8139. ** sqlite3_io_methods.xFileControl method.
  8140. ** ^The [SQLITE_FCNTL_FILE_POINTER] value for the op parameter causes
  8141. ** a pointer to the underlying [sqlite3_file] object to be written into
  8142. ** the space pointed to by the 4th parameter. The
  8143. ** [SQLITE_FCNTL_JOURNAL_POINTER] works similarly except that it returns
  8144. ** the [sqlite3_file] object associated with the journal file instead of
  8145. ** the main database. The [SQLITE_FCNTL_VFS_POINTER] opcode returns
  8146. ** a pointer to the underlying [sqlite3_vfs] object for the file.
  8147. ** The [SQLITE_FCNTL_DATA_VERSION] returns the data version counter
  8148. ** from the pager.
  8149. **
  8150. ** ^If the second parameter (zDbName) does not match the name of any
  8151. ** open database file, then SQLITE_ERROR is returned. ^This error
  8152. ** code is not remembered and will not be recalled by [sqlite3_errcode()]
  8153. ** or [sqlite3_errmsg()]. The underlying xFileControl method might
  8154. ** also return SQLITE_ERROR. There is no way to distinguish between
  8155. ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
  8156. ** xFileControl method.
  8157. **
  8158. ** See also: [file control opcodes]
  8159. */
  8160. SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
  8161. /*
  8162. ** CAPI3REF: Testing Interface
  8163. **
  8164. ** ^The sqlite3_test_control() interface is used to read out internal
  8165. ** state of SQLite and to inject faults into SQLite for testing
  8166. ** purposes. ^The first parameter is an operation code that determines
  8167. ** the number, meaning, and operation of all subsequent parameters.
  8168. **
  8169. ** This interface is not for use by applications. It exists solely
  8170. ** for verifying the correct operation of the SQLite library. Depending
  8171. ** on how the SQLite library is compiled, this interface might not exist.
  8172. **
  8173. ** The details of the operation codes, their meanings, the parameters
  8174. ** they take, and what they do are all subject to change without notice.
  8175. ** Unlike most of the SQLite API, this function is not guaranteed to
  8176. ** operate consistently from one release to the next.
  8177. */
  8178. SQLITE_API int sqlite3_test_control(int op, ...);
  8179. /*
  8180. ** CAPI3REF: Testing Interface Operation Codes
  8181. **
  8182. ** These constants are the valid operation code parameters used
  8183. ** as the first argument to [sqlite3_test_control()].
  8184. **
  8185. ** These parameters and their meanings are subject to change
  8186. ** without notice. These values are for testing purposes only.
  8187. ** Applications should not use any of these parameters or the
  8188. ** [sqlite3_test_control()] interface.
  8189. */
  8190. #define SQLITE_TESTCTRL_FIRST 5
  8191. #define SQLITE_TESTCTRL_PRNG_SAVE 5
  8192. #define SQLITE_TESTCTRL_PRNG_RESTORE 6
  8193. #define SQLITE_TESTCTRL_PRNG_RESET 7
  8194. #define SQLITE_TESTCTRL_BITVEC_TEST 8
  8195. #define SQLITE_TESTCTRL_FAULT_INSTALL 9
  8196. #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10
  8197. #define SQLITE_TESTCTRL_PENDING_BYTE 11
  8198. #define SQLITE_TESTCTRL_ASSERT 12
  8199. #define SQLITE_TESTCTRL_ALWAYS 13
  8200. #define SQLITE_TESTCTRL_RESERVE 14
  8201. #define SQLITE_TESTCTRL_OPTIMIZATIONS 15
  8202. #define SQLITE_TESTCTRL_ISKEYWORD 16 /* NOT USED */
  8203. #define SQLITE_TESTCTRL_SCRATCHMALLOC 17 /* NOT USED */
  8204. #define SQLITE_TESTCTRL_INTERNAL_FUNCTIONS 17
  8205. #define SQLITE_TESTCTRL_LOCALTIME_FAULT 18
  8206. #define SQLITE_TESTCTRL_EXPLAIN_STMT 19 /* NOT USED */
  8207. #define SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD 19
  8208. #define SQLITE_TESTCTRL_NEVER_CORRUPT 20
  8209. #define SQLITE_TESTCTRL_VDBE_COVERAGE 21
  8210. #define SQLITE_TESTCTRL_BYTEORDER 22
  8211. #define SQLITE_TESTCTRL_ISINIT 23
  8212. #define SQLITE_TESTCTRL_SORTER_MMAP 24
  8213. #define SQLITE_TESTCTRL_IMPOSTER 25
  8214. #define SQLITE_TESTCTRL_PARSER_COVERAGE 26
  8215. #define SQLITE_TESTCTRL_RESULT_INTREAL 27
  8216. #define SQLITE_TESTCTRL_LAST 27 /* Largest TESTCTRL */
  8217. /*
  8218. ** CAPI3REF: SQL Keyword Checking
  8219. **
  8220. ** These routines provide access to the set of SQL language keywords
  8221. ** recognized by SQLite. Applications can uses these routines to determine
  8222. ** whether or not a specific identifier needs to be escaped (for example,
  8223. ** by enclosing in double-quotes) so as not to confuse the parser.
  8224. **
  8225. ** The sqlite3_keyword_count() interface returns the number of distinct
  8226. ** keywords understood by SQLite.
  8227. **
  8228. ** The sqlite3_keyword_name(N,Z,L) interface finds the N-th keyword and
  8229. ** makes *Z point to that keyword expressed as UTF8 and writes the number
  8230. ** of bytes in the keyword into *L. The string that *Z points to is not
  8231. ** zero-terminated. The sqlite3_keyword_name(N,Z,L) routine returns
  8232. ** SQLITE_OK if N is within bounds and SQLITE_ERROR if not. If either Z
  8233. ** or L are NULL or invalid pointers then calls to
  8234. ** sqlite3_keyword_name(N,Z,L) result in undefined behavior.
  8235. **
  8236. ** The sqlite3_keyword_check(Z,L) interface checks to see whether or not
  8237. ** the L-byte UTF8 identifier that Z points to is a keyword, returning non-zero
  8238. ** if it is and zero if not.
  8239. **
  8240. ** The parser used by SQLite is forgiving. It is often possible to use
  8241. ** a keyword as an identifier as long as such use does not result in a
  8242. ** parsing ambiguity. For example, the statement
  8243. ** "CREATE TABLE BEGIN(REPLACE,PRAGMA,END);" is accepted by SQLite, and
  8244. ** creates a new table named "BEGIN" with three columns named
  8245. ** "REPLACE", "PRAGMA", and "END". Nevertheless, best practice is to avoid
  8246. ** using keywords as identifiers. Common techniques used to avoid keyword
  8247. ** name collisions include:
  8248. ** <ul>
  8249. ** <li> Put all identifier names inside double-quotes. This is the official
  8250. ** SQL way to escape identifier names.
  8251. ** <li> Put identifier names inside &#91;...&#93;. This is not standard SQL,
  8252. ** but it is what SQL Server does and so lots of programmers use this
  8253. ** technique.
  8254. ** <li> Begin every identifier with the letter "Z" as no SQL keywords start
  8255. ** with "Z".
  8256. ** <li> Include a digit somewhere in every identifier name.
  8257. ** </ul>
  8258. **
  8259. ** Note that the number of keywords understood by SQLite can depend on
  8260. ** compile-time options. For example, "VACUUM" is not a keyword if
  8261. ** SQLite is compiled with the [-DSQLITE_OMIT_VACUUM] option. Also,
  8262. ** new keywords may be added to future releases of SQLite.
  8263. */
  8264. SQLITE_API int sqlite3_keyword_count(void);
  8265. SQLITE_API int sqlite3_keyword_name(int,const char**,int*);
  8266. SQLITE_API int sqlite3_keyword_check(const char*,int);
  8267. /*
  8268. ** CAPI3REF: Dynamic String Object
  8269. ** KEYWORDS: {dynamic string}
  8270. **
  8271. ** An instance of the sqlite3_str object contains a dynamically-sized
  8272. ** string under construction.
  8273. **
  8274. ** The lifecycle of an sqlite3_str object is as follows:
  8275. ** <ol>
  8276. ** <li> ^The sqlite3_str object is created using [sqlite3_str_new()].
  8277. ** <li> ^Text is appended to the sqlite3_str object using various
  8278. ** methods, such as [sqlite3_str_appendf()].
  8279. ** <li> ^The sqlite3_str object is destroyed and the string it created
  8280. ** is returned using the [sqlite3_str_finish()] interface.
  8281. ** </ol>
  8282. */
  8283. typedef struct sqlite3_str sqlite3_str;
  8284. /*
  8285. ** CAPI3REF: Create A New Dynamic String Object
  8286. ** CONSTRUCTOR: sqlite3_str
  8287. **
  8288. ** ^The [sqlite3_str_new(D)] interface allocates and initializes
  8289. ** a new [sqlite3_str] object. To avoid memory leaks, the object returned by
  8290. ** [sqlite3_str_new()] must be freed by a subsequent call to
  8291. ** [sqlite3_str_finish(X)].
  8292. **
  8293. ** ^The [sqlite3_str_new(D)] interface always returns a pointer to a
  8294. ** valid [sqlite3_str] object, though in the event of an out-of-memory
  8295. ** error the returned object might be a special singleton that will
  8296. ** silently reject new text, always return SQLITE_NOMEM from
  8297. ** [sqlite3_str_errcode()], always return 0 for
  8298. ** [sqlite3_str_length()], and always return NULL from
  8299. ** [sqlite3_str_finish(X)]. It is always safe to use the value
  8300. ** returned by [sqlite3_str_new(D)] as the sqlite3_str parameter
  8301. ** to any of the other [sqlite3_str] methods.
  8302. **
  8303. ** The D parameter to [sqlite3_str_new(D)] may be NULL. If the
  8304. ** D parameter in [sqlite3_str_new(D)] is not NULL, then the maximum
  8305. ** length of the string contained in the [sqlite3_str] object will be
  8306. ** the value set for [sqlite3_limit](D,[SQLITE_LIMIT_LENGTH]) instead
  8307. ** of [SQLITE_MAX_LENGTH].
  8308. */
  8309. SQLITE_API sqlite3_str *sqlite3_str_new(sqlite3*);
  8310. /*
  8311. ** CAPI3REF: Finalize A Dynamic String
  8312. ** DESTRUCTOR: sqlite3_str
  8313. **
  8314. ** ^The [sqlite3_str_finish(X)] interface destroys the sqlite3_str object X
  8315. ** and returns a pointer to a memory buffer obtained from [sqlite3_malloc64()]
  8316. ** that contains the constructed string. The calling application should
  8317. ** pass the returned value to [sqlite3_free()] to avoid a memory leak.
  8318. ** ^The [sqlite3_str_finish(X)] interface may return a NULL pointer if any
  8319. ** errors were encountered during construction of the string. ^The
  8320. ** [sqlite3_str_finish(X)] interface will also return a NULL pointer if the
  8321. ** string in [sqlite3_str] object X is zero bytes long.
  8322. */
  8323. SQLITE_API char *sqlite3_str_finish(sqlite3_str*);
  8324. /*
  8325. ** CAPI3REF: Add Content To A Dynamic String
  8326. ** METHOD: sqlite3_str
  8327. **
  8328. ** These interfaces add content to an sqlite3_str object previously obtained
  8329. ** from [sqlite3_str_new()].
  8330. **
  8331. ** ^The [sqlite3_str_appendf(X,F,...)] and
  8332. ** [sqlite3_str_vappendf(X,F,V)] interfaces uses the [built-in printf]
  8333. ** functionality of SQLite to append formatted text onto the end of
  8334. ** [sqlite3_str] object X.
  8335. **
  8336. ** ^The [sqlite3_str_append(X,S,N)] method appends exactly N bytes from string S
  8337. ** onto the end of the [sqlite3_str] object X. N must be non-negative.
  8338. ** S must contain at least N non-zero bytes of content. To append a
  8339. ** zero-terminated string in its entirety, use the [sqlite3_str_appendall()]
  8340. ** method instead.
  8341. **
  8342. ** ^The [sqlite3_str_appendall(X,S)] method appends the complete content of
  8343. ** zero-terminated string S onto the end of [sqlite3_str] object X.
  8344. **
  8345. ** ^The [sqlite3_str_appendchar(X,N,C)] method appends N copies of the
  8346. ** single-byte character C onto the end of [sqlite3_str] object X.
  8347. ** ^This method can be used, for example, to add whitespace indentation.
  8348. **
  8349. ** ^The [sqlite3_str_reset(X)] method resets the string under construction
  8350. ** inside [sqlite3_str] object X back to zero bytes in length.
  8351. **
  8352. ** These methods do not return a result code. ^If an error occurs, that fact
  8353. ** is recorded in the [sqlite3_str] object and can be recovered by a
  8354. ** subsequent call to [sqlite3_str_errcode(X)].
  8355. */
  8356. SQLITE_API void sqlite3_str_appendf(sqlite3_str*, const char *zFormat, ...);
  8357. SQLITE_API void sqlite3_str_vappendf(sqlite3_str*, const char *zFormat, va_list);
  8358. SQLITE_API void sqlite3_str_append(sqlite3_str*, const char *zIn, int N);
  8359. SQLITE_API void sqlite3_str_appendall(sqlite3_str*, const char *zIn);
  8360. SQLITE_API void sqlite3_str_appendchar(sqlite3_str*, int N, char C);
  8361. SQLITE_API void sqlite3_str_reset(sqlite3_str*);
  8362. /*
  8363. ** CAPI3REF: Status Of A Dynamic String
  8364. ** METHOD: sqlite3_str
  8365. **
  8366. ** These interfaces return the current status of an [sqlite3_str] object.
  8367. **
  8368. ** ^If any prior errors have occurred while constructing the dynamic string
  8369. ** in sqlite3_str X, then the [sqlite3_str_errcode(X)] method will return
  8370. ** an appropriate error code. ^The [sqlite3_str_errcode(X)] method returns
  8371. ** [SQLITE_NOMEM] following any out-of-memory error, or
  8372. ** [SQLITE_TOOBIG] if the size of the dynamic string exceeds
  8373. ** [SQLITE_MAX_LENGTH], or [SQLITE_OK] if there have been no errors.
  8374. **
  8375. ** ^The [sqlite3_str_length(X)] method returns the current length, in bytes,
  8376. ** of the dynamic string under construction in [sqlite3_str] object X.
  8377. ** ^The length returned by [sqlite3_str_length(X)] does not include the
  8378. ** zero-termination byte.
  8379. **
  8380. ** ^The [sqlite3_str_value(X)] method returns a pointer to the current
  8381. ** content of the dynamic string under construction in X. The value
  8382. ** returned by [sqlite3_str_value(X)] is managed by the sqlite3_str object X
  8383. ** and might be freed or altered by any subsequent method on the same
  8384. ** [sqlite3_str] object. Applications must not used the pointer returned
  8385. ** [sqlite3_str_value(X)] after any subsequent method call on the same
  8386. ** object. ^Applications may change the content of the string returned
  8387. ** by [sqlite3_str_value(X)] as long as they do not write into any bytes
  8388. ** outside the range of 0 to [sqlite3_str_length(X)] and do not read or
  8389. ** write any byte after any subsequent sqlite3_str method call.
  8390. */
  8391. SQLITE_API int sqlite3_str_errcode(sqlite3_str*);
  8392. SQLITE_API int sqlite3_str_length(sqlite3_str*);
  8393. SQLITE_API char *sqlite3_str_value(sqlite3_str*);
  8394. /*
  8395. ** CAPI3REF: SQLite Runtime Status
  8396. **
  8397. ** ^These interfaces are used to retrieve runtime status information
  8398. ** about the performance of SQLite, and optionally to reset various
  8399. ** highwater marks. ^The first argument is an integer code for
  8400. ** the specific parameter to measure. ^(Recognized integer codes
  8401. ** are of the form [status parameters | SQLITE_STATUS_...].)^
  8402. ** ^The current value of the parameter is returned into *pCurrent.
  8403. ** ^The highest recorded value is returned in *pHighwater. ^If the
  8404. ** resetFlag is true, then the highest record value is reset after
  8405. ** *pHighwater is written. ^(Some parameters do not record the highest
  8406. ** value. For those parameters
  8407. ** nothing is written into *pHighwater and the resetFlag is ignored.)^
  8408. ** ^(Other parameters record only the highwater mark and not the current
  8409. ** value. For these latter parameters nothing is written into *pCurrent.)^
  8410. **
  8411. ** ^The sqlite3_status() and sqlite3_status64() routines return
  8412. ** SQLITE_OK on success and a non-zero [error code] on failure.
  8413. **
  8414. ** If either the current value or the highwater mark is too large to
  8415. ** be represented by a 32-bit integer, then the values returned by
  8416. ** sqlite3_status() are undefined.
  8417. **
  8418. ** See also: [sqlite3_db_status()]
  8419. */
  8420. SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
  8421. SQLITE_API int sqlite3_status64(
  8422. int op,
  8423. sqlite3_int64 *pCurrent,
  8424. sqlite3_int64 *pHighwater,
  8425. int resetFlag
  8426. );
  8427. /*
  8428. ** CAPI3REF: Status Parameters
  8429. ** KEYWORDS: {status parameters}
  8430. **
  8431. ** These integer constants designate various run-time status parameters
  8432. ** that can be returned by [sqlite3_status()].
  8433. **
  8434. ** <dl>
  8435. ** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
  8436. ** <dd>This parameter is the current amount of memory checked out
  8437. ** using [sqlite3_malloc()], either directly or indirectly. The
  8438. ** figure includes calls made to [sqlite3_malloc()] by the application
  8439. ** and internal memory usage by the SQLite library. Auxiliary page-cache
  8440. ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
  8441. ** this parameter. The amount returned is the sum of the allocation
  8442. ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
  8443. **
  8444. ** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
  8445. ** <dd>This parameter records the largest memory allocation request
  8446. ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
  8447. ** internal equivalents). Only the value returned in the
  8448. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  8449. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  8450. **
  8451. ** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
  8452. ** <dd>This parameter records the number of separate memory allocations
  8453. ** currently checked out.</dd>)^
  8454. **
  8455. ** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
  8456. ** <dd>This parameter returns the number of pages used out of the
  8457. ** [pagecache memory allocator] that was configured using
  8458. ** [SQLITE_CONFIG_PAGECACHE]. The
  8459. ** value returned is in pages, not in bytes.</dd>)^
  8460. **
  8461. ** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]]
  8462. ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
  8463. ** <dd>This parameter returns the number of bytes of page cache
  8464. ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
  8465. ** buffer and where forced to overflow to [sqlite3_malloc()]. The
  8466. ** returned value includes allocations that overflowed because they
  8467. ** where too large (they were larger than the "sz" parameter to
  8468. ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
  8469. ** no space was left in the page cache.</dd>)^
  8470. **
  8471. ** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
  8472. ** <dd>This parameter records the largest memory allocation request
  8473. ** handed to [pagecache memory allocator]. Only the value returned in the
  8474. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  8475. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  8476. **
  8477. ** [[SQLITE_STATUS_SCRATCH_USED]] <dt>SQLITE_STATUS_SCRATCH_USED</dt>
  8478. ** <dd>No longer used.</dd>
  8479. **
  8480. ** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
  8481. ** <dd>No longer used.</dd>
  8482. **
  8483. ** [[SQLITE_STATUS_SCRATCH_SIZE]] <dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
  8484. ** <dd>No longer used.</dd>
  8485. **
  8486. ** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
  8487. ** <dd>The *pHighwater parameter records the deepest parser stack.
  8488. ** The *pCurrent value is undefined. The *pHighwater value is only
  8489. ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
  8490. ** </dl>
  8491. **
  8492. ** New status parameters may be added from time to time.
  8493. */
  8494. #define SQLITE_STATUS_MEMORY_USED 0
  8495. #define SQLITE_STATUS_PAGECACHE_USED 1
  8496. #define SQLITE_STATUS_PAGECACHE_OVERFLOW 2
  8497. #define SQLITE_STATUS_SCRATCH_USED 3 /* NOT USED */
  8498. #define SQLITE_STATUS_SCRATCH_OVERFLOW 4 /* NOT USED */
  8499. #define SQLITE_STATUS_MALLOC_SIZE 5
  8500. #define SQLITE_STATUS_PARSER_STACK 6
  8501. #define SQLITE_STATUS_PAGECACHE_SIZE 7
  8502. #define SQLITE_STATUS_SCRATCH_SIZE 8 /* NOT USED */
  8503. #define SQLITE_STATUS_MALLOC_COUNT 9
  8504. /*
  8505. ** CAPI3REF: Database Connection Status
  8506. ** METHOD: sqlite3
  8507. **
  8508. ** ^This interface is used to retrieve runtime status information
  8509. ** about a single [database connection]. ^The first argument is the
  8510. ** database connection object to be interrogated. ^The second argument
  8511. ** is an integer constant, taken from the set of
  8512. ** [SQLITE_DBSTATUS options], that
  8513. ** determines the parameter to interrogate. The set of
  8514. ** [SQLITE_DBSTATUS options] is likely
  8515. ** to grow in future releases of SQLite.
  8516. **
  8517. ** ^The current value of the requested parameter is written into *pCur
  8518. ** and the highest instantaneous value is written into *pHiwtr. ^If
  8519. ** the resetFlg is true, then the highest instantaneous value is
  8520. ** reset back down to the current value.
  8521. **
  8522. ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
  8523. ** non-zero [error code] on failure.
  8524. **
  8525. ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
  8526. */
  8527. SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
  8528. /*
  8529. ** CAPI3REF: Status Parameters for database connections
  8530. ** KEYWORDS: {SQLITE_DBSTATUS options}
  8531. **
  8532. ** These constants are the available integer "verbs" that can be passed as
  8533. ** the second argument to the [sqlite3_db_status()] interface.
  8534. **
  8535. ** New verbs may be added in future releases of SQLite. Existing verbs
  8536. ** might be discontinued. Applications should check the return code from
  8537. ** [sqlite3_db_status()] to make sure that the call worked.
  8538. ** The [sqlite3_db_status()] interface will return a non-zero error code
  8539. ** if a discontinued or unsupported verb is invoked.
  8540. **
  8541. ** <dl>
  8542. ** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
  8543. ** <dd>This parameter returns the number of lookaside memory slots currently
  8544. ** checked out.</dd>)^
  8545. **
  8546. ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
  8547. ** <dd>This parameter returns the number malloc attempts that were
  8548. ** satisfied using lookaside memory. Only the high-water value is meaningful;
  8549. ** the current value is always zero.)^
  8550. **
  8551. ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
  8552. ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
  8553. ** <dd>This parameter returns the number malloc attempts that might have
  8554. ** been satisfied using lookaside memory but failed due to the amount of
  8555. ** memory requested being larger than the lookaside slot size.
  8556. ** Only the high-water value is meaningful;
  8557. ** the current value is always zero.)^
  8558. **
  8559. ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
  8560. ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
  8561. ** <dd>This parameter returns the number malloc attempts that might have
  8562. ** been satisfied using lookaside memory but failed due to all lookaside
  8563. ** memory already being in use.
  8564. ** Only the high-water value is meaningful;
  8565. ** the current value is always zero.)^
  8566. **
  8567. ** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
  8568. ** <dd>This parameter returns the approximate number of bytes of heap
  8569. ** memory used by all pager caches associated with the database connection.)^
  8570. ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
  8571. **
  8572. ** [[SQLITE_DBSTATUS_CACHE_USED_SHARED]]
  8573. ** ^(<dt>SQLITE_DBSTATUS_CACHE_USED_SHARED</dt>
  8574. ** <dd>This parameter is similar to DBSTATUS_CACHE_USED, except that if a
  8575. ** pager cache is shared between two or more connections the bytes of heap
  8576. ** memory used by that pager cache is divided evenly between the attached
  8577. ** connections.)^ In other words, if none of the pager caches associated
  8578. ** with the database connection are shared, this request returns the same
  8579. ** value as DBSTATUS_CACHE_USED. Or, if one or more or the pager caches are
  8580. ** shared, the value returned by this call will be smaller than that returned
  8581. ** by DBSTATUS_CACHE_USED. ^The highwater mark associated with
  8582. ** SQLITE_DBSTATUS_CACHE_USED_SHARED is always 0.
  8583. **
  8584. ** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
  8585. ** <dd>This parameter returns the approximate number of bytes of heap
  8586. ** memory used to store the schema for all databases associated
  8587. ** with the connection - main, temp, and any [ATTACH]-ed databases.)^
  8588. ** ^The full amount of memory used by the schemas is reported, even if the
  8589. ** schema memory is shared with other database connections due to
  8590. ** [shared cache mode] being enabled.
  8591. ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
  8592. **
  8593. ** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
  8594. ** <dd>This parameter returns the approximate number of bytes of heap
  8595. ** and lookaside memory used by all prepared statements associated with
  8596. ** the database connection.)^
  8597. ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
  8598. ** </dd>
  8599. **
  8600. ** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
  8601. ** <dd>This parameter returns the number of pager cache hits that have
  8602. ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT
  8603. ** is always 0.
  8604. ** </dd>
  8605. **
  8606. ** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
  8607. ** <dd>This parameter returns the number of pager cache misses that have
  8608. ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS
  8609. ** is always 0.
  8610. ** </dd>
  8611. **
  8612. ** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>
  8613. ** <dd>This parameter returns the number of dirty cache entries that have
  8614. ** been written to disk. Specifically, the number of pages written to the
  8615. ** wal file in wal mode databases, or the number of pages written to the
  8616. ** database file in rollback mode databases. Any pages written as part of
  8617. ** transaction rollback or database recovery operations are not included.
  8618. ** If an IO or other error occurs while writing a page to disk, the effect
  8619. ** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The
  8620. ** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.
  8621. ** </dd>
  8622. **
  8623. ** [[SQLITE_DBSTATUS_CACHE_SPILL]] ^(<dt>SQLITE_DBSTATUS_CACHE_SPILL</dt>
  8624. ** <dd>This parameter returns the number of dirty cache entries that have
  8625. ** been written to disk in the middle of a transaction due to the page
  8626. ** cache overflowing. Transactions are more efficient if they are written
  8627. ** to disk all at once. When pages spill mid-transaction, that introduces
  8628. ** additional overhead. This parameter can be used help identify
  8629. ** inefficiencies that can be resolve by increasing the cache size.
  8630. ** </dd>
  8631. **
  8632. ** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(<dt>SQLITE_DBSTATUS_DEFERRED_FKS</dt>
  8633. ** <dd>This parameter returns zero for the current value if and only if
  8634. ** all foreign key constraints (deferred or immediate) have been
  8635. ** resolved.)^ ^The highwater mark is always 0.
  8636. ** </dd>
  8637. ** </dl>
  8638. */
  8639. #define SQLITE_DBSTATUS_LOOKASIDE_USED 0
  8640. #define SQLITE_DBSTATUS_CACHE_USED 1
  8641. #define SQLITE_DBSTATUS_SCHEMA_USED 2
  8642. #define SQLITE_DBSTATUS_STMT_USED 3
  8643. #define SQLITE_DBSTATUS_LOOKASIDE_HIT 4
  8644. #define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE 5
  8645. #define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL 6
  8646. #define SQLITE_DBSTATUS_CACHE_HIT 7
  8647. #define SQLITE_DBSTATUS_CACHE_MISS 8
  8648. #define SQLITE_DBSTATUS_CACHE_WRITE 9
  8649. #define SQLITE_DBSTATUS_DEFERRED_FKS 10
  8650. #define SQLITE_DBSTATUS_CACHE_USED_SHARED 11
  8651. #define SQLITE_DBSTATUS_CACHE_SPILL 12
  8652. #define SQLITE_DBSTATUS_MAX 12 /* Largest defined DBSTATUS */
  8653. /*
  8654. ** CAPI3REF: Prepared Statement Status
  8655. ** METHOD: sqlite3_stmt
  8656. **
  8657. ** ^(Each prepared statement maintains various
  8658. ** [SQLITE_STMTSTATUS counters] that measure the number
  8659. ** of times it has performed specific operations.)^ These counters can
  8660. ** be used to monitor the performance characteristics of the prepared
  8661. ** statements. For example, if the number of table steps greatly exceeds
  8662. ** the number of table searches or result rows, that would tend to indicate
  8663. ** that the prepared statement is using a full table scan rather than
  8664. ** an index.
  8665. **
  8666. ** ^(This interface is used to retrieve and reset counter values from
  8667. ** a [prepared statement]. The first argument is the prepared statement
  8668. ** object to be interrogated. The second argument
  8669. ** is an integer code for a specific [SQLITE_STMTSTATUS counter]
  8670. ** to be interrogated.)^
  8671. ** ^The current value of the requested counter is returned.
  8672. ** ^If the resetFlg is true, then the counter is reset to zero after this
  8673. ** interface call returns.
  8674. **
  8675. ** See also: [sqlite3_status()] and [sqlite3_db_status()].
  8676. */
  8677. SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
  8678. /*
  8679. ** CAPI3REF: Status Parameters for prepared statements
  8680. ** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
  8681. **
  8682. ** These preprocessor macros define integer codes that name counter
  8683. ** values associated with the [sqlite3_stmt_status()] interface.
  8684. ** The meanings of the various counters are as follows:
  8685. **
  8686. ** <dl>
  8687. ** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
  8688. ** <dd>^This is the number of times that SQLite has stepped forward in
  8689. ** a table as part of a full table scan. Large numbers for this counter
  8690. ** may indicate opportunities for performance improvement through
  8691. ** careful use of indices.</dd>
  8692. **
  8693. ** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
  8694. ** <dd>^This is the number of sort operations that have occurred.
  8695. ** A non-zero value in this counter may indicate an opportunity to
  8696. ** improvement performance through careful use of indices.</dd>
  8697. **
  8698. ** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
  8699. ** <dd>^This is the number of rows inserted into transient indices that
  8700. ** were created automatically in order to help joins run faster.
  8701. ** A non-zero value in this counter may indicate an opportunity to
  8702. ** improvement performance by adding permanent indices that do not
  8703. ** need to be reinitialized each time the statement is run.</dd>
  8704. **
  8705. ** [[SQLITE_STMTSTATUS_VM_STEP]] <dt>SQLITE_STMTSTATUS_VM_STEP</dt>
  8706. ** <dd>^This is the number of virtual machine operations executed
  8707. ** by the prepared statement if that number is less than or equal
  8708. ** to 2147483647. The number of virtual machine operations can be
  8709. ** used as a proxy for the total work done by the prepared statement.
  8710. ** If the number of virtual machine operations exceeds 2147483647
  8711. ** then the value returned by this statement status code is undefined.
  8712. **
  8713. ** [[SQLITE_STMTSTATUS_REPREPARE]] <dt>SQLITE_STMTSTATUS_REPREPARE</dt>
  8714. ** <dd>^This is the number of times that the prepare statement has been
  8715. ** automatically regenerated due to schema changes or change to
  8716. ** [bound parameters] that might affect the query plan.
  8717. **
  8718. ** [[SQLITE_STMTSTATUS_RUN]] <dt>SQLITE_STMTSTATUS_RUN</dt>
  8719. ** <dd>^This is the number of times that the prepared statement has
  8720. ** been run. A single "run" for the purposes of this counter is one
  8721. ** or more calls to [sqlite3_step()] followed by a call to [sqlite3_reset()].
  8722. ** The counter is incremented on the first [sqlite3_step()] call of each
  8723. ** cycle.
  8724. **
  8725. ** [[SQLITE_STMTSTATUS_MEMUSED]] <dt>SQLITE_STMTSTATUS_MEMUSED</dt>
  8726. ** <dd>^This is the approximate number of bytes of heap memory
  8727. ** used to store the prepared statement. ^This value is not actually
  8728. ** a counter, and so the resetFlg parameter to sqlite3_stmt_status()
  8729. ** is ignored when the opcode is SQLITE_STMTSTATUS_MEMUSED.
  8730. ** </dd>
  8731. ** </dl>
  8732. */
  8733. #define SQLITE_STMTSTATUS_FULLSCAN_STEP 1
  8734. #define SQLITE_STMTSTATUS_SORT 2
  8735. #define SQLITE_STMTSTATUS_AUTOINDEX 3
  8736. #define SQLITE_STMTSTATUS_VM_STEP 4
  8737. #define SQLITE_STMTSTATUS_REPREPARE 5
  8738. #define SQLITE_STMTSTATUS_RUN 6
  8739. #define SQLITE_STMTSTATUS_MEMUSED 99
  8740. /*
  8741. ** CAPI3REF: Custom Page Cache Object
  8742. **
  8743. ** The sqlite3_pcache type is opaque. It is implemented by
  8744. ** the pluggable module. The SQLite core has no knowledge of
  8745. ** its size or internal structure and never deals with the
  8746. ** sqlite3_pcache object except by holding and passing pointers
  8747. ** to the object.
  8748. **
  8749. ** See [sqlite3_pcache_methods2] for additional information.
  8750. */
  8751. typedef struct sqlite3_pcache sqlite3_pcache;
  8752. /*
  8753. ** CAPI3REF: Custom Page Cache Object
  8754. **
  8755. ** The sqlite3_pcache_page object represents a single page in the
  8756. ** page cache. The page cache will allocate instances of this
  8757. ** object. Various methods of the page cache use pointers to instances
  8758. ** of this object as parameters or as their return value.
  8759. **
  8760. ** See [sqlite3_pcache_methods2] for additional information.
  8761. */
  8762. typedef struct sqlite3_pcache_page sqlite3_pcache_page;
  8763. struct sqlite3_pcache_page {
  8764. void *pBuf; /* The content of the page */
  8765. void *pExtra; /* Extra information associated with the page */
  8766. };
  8767. /*
  8768. ** CAPI3REF: Application Defined Page Cache.
  8769. ** KEYWORDS: {page cache}
  8770. **
  8771. ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
  8772. ** register an alternative page cache implementation by passing in an
  8773. ** instance of the sqlite3_pcache_methods2 structure.)^
  8774. ** In many applications, most of the heap memory allocated by
  8775. ** SQLite is used for the page cache.
  8776. ** By implementing a
  8777. ** custom page cache using this API, an application can better control
  8778. ** the amount of memory consumed by SQLite, the way in which
  8779. ** that memory is allocated and released, and the policies used to
  8780. ** determine exactly which parts of a database file are cached and for
  8781. ** how long.
  8782. **
  8783. ** The alternative page cache mechanism is an
  8784. ** extreme measure that is only needed by the most demanding applications.
  8785. ** The built-in page cache is recommended for most uses.
  8786. **
  8787. ** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
  8788. ** internal buffer by SQLite within the call to [sqlite3_config]. Hence
  8789. ** the application may discard the parameter after the call to
  8790. ** [sqlite3_config()] returns.)^
  8791. **
  8792. ** [[the xInit() page cache method]]
  8793. ** ^(The xInit() method is called once for each effective
  8794. ** call to [sqlite3_initialize()])^
  8795. ** (usually only once during the lifetime of the process). ^(The xInit()
  8796. ** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
  8797. ** The intent of the xInit() method is to set up global data structures
  8798. ** required by the custom page cache implementation.
  8799. ** ^(If the xInit() method is NULL, then the
  8800. ** built-in default page cache is used instead of the application defined
  8801. ** page cache.)^
  8802. **
  8803. ** [[the xShutdown() page cache method]]
  8804. ** ^The xShutdown() method is called by [sqlite3_shutdown()].
  8805. ** It can be used to clean up
  8806. ** any outstanding resources before process shutdown, if required.
  8807. ** ^The xShutdown() method may be NULL.
  8808. **
  8809. ** ^SQLite automatically serializes calls to the xInit method,
  8810. ** so the xInit method need not be threadsafe. ^The
  8811. ** xShutdown method is only called from [sqlite3_shutdown()] so it does
  8812. ** not need to be threadsafe either. All other methods must be threadsafe
  8813. ** in multithreaded applications.
  8814. **
  8815. ** ^SQLite will never invoke xInit() more than once without an intervening
  8816. ** call to xShutdown().
  8817. **
  8818. ** [[the xCreate() page cache methods]]
  8819. ** ^SQLite invokes the xCreate() method to construct a new cache instance.
  8820. ** SQLite will typically create one cache instance for each open database file,
  8821. ** though this is not guaranteed. ^The
  8822. ** first parameter, szPage, is the size in bytes of the pages that must
  8823. ** be allocated by the cache. ^szPage will always a power of two. ^The
  8824. ** second parameter szExtra is a number of bytes of extra storage
  8825. ** associated with each page cache entry. ^The szExtra parameter will
  8826. ** a number less than 250. SQLite will use the
  8827. ** extra szExtra bytes on each page to store metadata about the underlying
  8828. ** database page on disk. The value passed into szExtra depends
  8829. ** on the SQLite version, the target platform, and how SQLite was compiled.
  8830. ** ^The third argument to xCreate(), bPurgeable, is true if the cache being
  8831. ** created will be used to cache database pages of a file stored on disk, or
  8832. ** false if it is used for an in-memory database. The cache implementation
  8833. ** does not have to do anything special based with the value of bPurgeable;
  8834. ** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will
  8835. ** never invoke xUnpin() except to deliberately delete a page.
  8836. ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
  8837. ** false will always have the "discard" flag set to true.
  8838. ** ^Hence, a cache created with bPurgeable false will
  8839. ** never contain any unpinned pages.
  8840. **
  8841. ** [[the xCachesize() page cache method]]
  8842. ** ^(The xCachesize() method may be called at any time by SQLite to set the
  8843. ** suggested maximum cache-size (number of pages stored by) the cache
  8844. ** instance passed as the first argument. This is the value configured using
  8845. ** the SQLite "[PRAGMA cache_size]" command.)^ As with the bPurgeable
  8846. ** parameter, the implementation is not required to do anything with this
  8847. ** value; it is advisory only.
  8848. **
  8849. ** [[the xPagecount() page cache methods]]
  8850. ** The xPagecount() method must return the number of pages currently
  8851. ** stored in the cache, both pinned and unpinned.
  8852. **
  8853. ** [[the xFetch() page cache methods]]
  8854. ** The xFetch() method locates a page in the cache and returns a pointer to
  8855. ** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
  8856. ** The pBuf element of the returned sqlite3_pcache_page object will be a
  8857. ** pointer to a buffer of szPage bytes used to store the content of a
  8858. ** single database page. The pExtra element of sqlite3_pcache_page will be
  8859. ** a pointer to the szExtra bytes of extra storage that SQLite has requested
  8860. ** for each entry in the page cache.
  8861. **
  8862. ** The page to be fetched is determined by the key. ^The minimum key value
  8863. ** is 1. After it has been retrieved using xFetch, the page is considered
  8864. ** to be "pinned".
  8865. **
  8866. ** If the requested page is already in the page cache, then the page cache
  8867. ** implementation must return a pointer to the page buffer with its content
  8868. ** intact. If the requested page is not already in the cache, then the
  8869. ** cache implementation should use the value of the createFlag
  8870. ** parameter to help it determined what action to take:
  8871. **
  8872. ** <table border=1 width=85% align=center>
  8873. ** <tr><th> createFlag <th> Behavior when page is not already in cache
  8874. ** <tr><td> 0 <td> Do not allocate a new page. Return NULL.
  8875. ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
  8876. ** Otherwise return NULL.
  8877. ** <tr><td> 2 <td> Make every effort to allocate a new page. Only return
  8878. ** NULL if allocating a new page is effectively impossible.
  8879. ** </table>
  8880. **
  8881. ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1. SQLite
  8882. ** will only use a createFlag of 2 after a prior call with a createFlag of 1
  8883. ** failed.)^ In between the to xFetch() calls, SQLite may
  8884. ** attempt to unpin one or more cache pages by spilling the content of
  8885. ** pinned pages to disk and synching the operating system disk cache.
  8886. **
  8887. ** [[the xUnpin() page cache method]]
  8888. ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
  8889. ** as its second argument. If the third parameter, discard, is non-zero,
  8890. ** then the page must be evicted from the cache.
  8891. ** ^If the discard parameter is
  8892. ** zero, then the page may be discarded or retained at the discretion of
  8893. ** page cache implementation. ^The page cache implementation
  8894. ** may choose to evict unpinned pages at any time.
  8895. **
  8896. ** The cache must not perform any reference counting. A single
  8897. ** call to xUnpin() unpins the page regardless of the number of prior calls
  8898. ** to xFetch().
  8899. **
  8900. ** [[the xRekey() page cache methods]]
  8901. ** The xRekey() method is used to change the key value associated with the
  8902. ** page passed as the second argument. If the cache
  8903. ** previously contains an entry associated with newKey, it must be
  8904. ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
  8905. ** to be pinned.
  8906. **
  8907. ** When SQLite calls the xTruncate() method, the cache must discard all
  8908. ** existing cache entries with page numbers (keys) greater than or equal
  8909. ** to the value of the iLimit parameter passed to xTruncate(). If any
  8910. ** of these pages are pinned, they are implicitly unpinned, meaning that
  8911. ** they can be safely discarded.
  8912. **
  8913. ** [[the xDestroy() page cache method]]
  8914. ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
  8915. ** All resources associated with the specified cache should be freed. ^After
  8916. ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
  8917. ** handle invalid, and will not use it with any other sqlite3_pcache_methods2
  8918. ** functions.
  8919. **
  8920. ** [[the xShrink() page cache method]]
  8921. ** ^SQLite invokes the xShrink() method when it wants the page cache to
  8922. ** free up as much of heap memory as possible. The page cache implementation
  8923. ** is not obligated to free any memory, but well-behaved implementations should
  8924. ** do their best.
  8925. */
  8926. typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;
  8927. struct sqlite3_pcache_methods2 {
  8928. int iVersion;
  8929. void *pArg;
  8930. int (*xInit)(void*);
  8931. void (*xShutdown)(void*);
  8932. sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
  8933. void (*xCachesize)(sqlite3_pcache*, int nCachesize);
  8934. int (*xPagecount)(sqlite3_pcache*);
  8935. sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
  8936. void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
  8937. void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*,
  8938. unsigned oldKey, unsigned newKey);
  8939. void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
  8940. void (*xDestroy)(sqlite3_pcache*);
  8941. void (*xShrink)(sqlite3_pcache*);
  8942. };
  8943. /*
  8944. ** This is the obsolete pcache_methods object that has now been replaced
  8945. ** by sqlite3_pcache_methods2. This object is not used by SQLite. It is
  8946. ** retained in the header file for backwards compatibility only.
  8947. */
  8948. typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
  8949. struct sqlite3_pcache_methods {
  8950. void *pArg;
  8951. int (*xInit)(void*);
  8952. void (*xShutdown)(void*);
  8953. sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
  8954. void (*xCachesize)(sqlite3_pcache*, int nCachesize);
  8955. int (*xPagecount)(sqlite3_pcache*);
  8956. void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
  8957. void (*xUnpin)(sqlite3_pcache*, void*, int discard);
  8958. void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
  8959. void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
  8960. void (*xDestroy)(sqlite3_pcache*);
  8961. };
  8962. /*
  8963. ** CAPI3REF: Online Backup Object
  8964. **
  8965. ** The sqlite3_backup object records state information about an ongoing
  8966. ** online backup operation. ^The sqlite3_backup object is created by
  8967. ** a call to [sqlite3_backup_init()] and is destroyed by a call to
  8968. ** [sqlite3_backup_finish()].
  8969. **
  8970. ** See Also: [Using the SQLite Online Backup API]
  8971. */
  8972. typedef struct sqlite3_backup sqlite3_backup;
  8973. /*
  8974. ** CAPI3REF: Online Backup API.
  8975. **
  8976. ** The backup API copies the content of one database into another.
  8977. ** It is useful either for creating backups of databases or
  8978. ** for copying in-memory databases to or from persistent files.
  8979. **
  8980. ** See Also: [Using the SQLite Online Backup API]
  8981. **
  8982. ** ^SQLite holds a write transaction open on the destination database file
  8983. ** for the duration of the backup operation.
  8984. ** ^The source database is read-locked only while it is being read;
  8985. ** it is not locked continuously for the entire backup operation.
  8986. ** ^Thus, the backup may be performed on a live source database without
  8987. ** preventing other database connections from
  8988. ** reading or writing to the source database while the backup is underway.
  8989. **
  8990. ** ^(To perform a backup operation:
  8991. ** <ol>
  8992. ** <li><b>sqlite3_backup_init()</b> is called once to initialize the
  8993. ** backup,
  8994. ** <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
  8995. ** the data between the two databases, and finally
  8996. ** <li><b>sqlite3_backup_finish()</b> is called to release all resources
  8997. ** associated with the backup operation.
  8998. ** </ol>)^
  8999. ** There should be exactly one call to sqlite3_backup_finish() for each
  9000. ** successful call to sqlite3_backup_init().
  9001. **
  9002. ** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
  9003. **
  9004. ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
  9005. ** [database connection] associated with the destination database
  9006. ** and the database name, respectively.
  9007. ** ^The database name is "main" for the main database, "temp" for the
  9008. ** temporary database, or the name specified after the AS keyword in
  9009. ** an [ATTACH] statement for an attached database.
  9010. ** ^The S and M arguments passed to
  9011. ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
  9012. ** and database name of the source database, respectively.
  9013. ** ^The source and destination [database connections] (parameters S and D)
  9014. ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
  9015. ** an error.
  9016. **
  9017. ** ^A call to sqlite3_backup_init() will fail, returning NULL, if
  9018. ** there is already a read or read-write transaction open on the
  9019. ** destination database.
  9020. **
  9021. ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
  9022. ** returned and an error code and error message are stored in the
  9023. ** destination [database connection] D.
  9024. ** ^The error code and message for the failed call to sqlite3_backup_init()
  9025. ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
  9026. ** [sqlite3_errmsg16()] functions.
  9027. ** ^A successful call to sqlite3_backup_init() returns a pointer to an
  9028. ** [sqlite3_backup] object.
  9029. ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
  9030. ** sqlite3_backup_finish() functions to perform the specified backup
  9031. ** operation.
  9032. **
  9033. ** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
  9034. **
  9035. ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
  9036. ** the source and destination databases specified by [sqlite3_backup] object B.
  9037. ** ^If N is negative, all remaining source pages are copied.
  9038. ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
  9039. ** are still more pages to be copied, then the function returns [SQLITE_OK].
  9040. ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
  9041. ** from source to destination, then it returns [SQLITE_DONE].
  9042. ** ^If an error occurs while running sqlite3_backup_step(B,N),
  9043. ** then an [error code] is returned. ^As well as [SQLITE_OK] and
  9044. ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
  9045. ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
  9046. ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
  9047. **
  9048. ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
  9049. ** <ol>
  9050. ** <li> the destination database was opened read-only, or
  9051. ** <li> the destination database is using write-ahead-log journaling
  9052. ** and the destination and source page sizes differ, or
  9053. ** <li> the destination database is an in-memory database and the
  9054. ** destination and source page sizes differ.
  9055. ** </ol>)^
  9056. **
  9057. ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
  9058. ** the [sqlite3_busy_handler | busy-handler function]
  9059. ** is invoked (if one is specified). ^If the
  9060. ** busy-handler returns non-zero before the lock is available, then
  9061. ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
  9062. ** sqlite3_backup_step() can be retried later. ^If the source
  9063. ** [database connection]
  9064. ** is being used to write to the source database when sqlite3_backup_step()
  9065. ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
  9066. ** case the call to sqlite3_backup_step() can be retried later on. ^(If
  9067. ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
  9068. ** [SQLITE_READONLY] is returned, then
  9069. ** there is no point in retrying the call to sqlite3_backup_step(). These
  9070. ** errors are considered fatal.)^ The application must accept
  9071. ** that the backup operation has failed and pass the backup operation handle
  9072. ** to the sqlite3_backup_finish() to release associated resources.
  9073. **
  9074. ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
  9075. ** on the destination file. ^The exclusive lock is not released until either
  9076. ** sqlite3_backup_finish() is called or the backup operation is complete
  9077. ** and sqlite3_backup_step() returns [SQLITE_DONE]. ^Every call to
  9078. ** sqlite3_backup_step() obtains a [shared lock] on the source database that
  9079. ** lasts for the duration of the sqlite3_backup_step() call.
  9080. ** ^Because the source database is not locked between calls to
  9081. ** sqlite3_backup_step(), the source database may be modified mid-way
  9082. ** through the backup process. ^If the source database is modified by an
  9083. ** external process or via a database connection other than the one being
  9084. ** used by the backup operation, then the backup will be automatically
  9085. ** restarted by the next call to sqlite3_backup_step(). ^If the source
  9086. ** database is modified by the using the same database connection as is used
  9087. ** by the backup operation, then the backup database is automatically
  9088. ** updated at the same time.
  9089. **
  9090. ** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
  9091. **
  9092. ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
  9093. ** application wishes to abandon the backup operation, the application
  9094. ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
  9095. ** ^The sqlite3_backup_finish() interfaces releases all
  9096. ** resources associated with the [sqlite3_backup] object.
  9097. ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
  9098. ** active write-transaction on the destination database is rolled back.
  9099. ** The [sqlite3_backup] object is invalid
  9100. ** and may not be used following a call to sqlite3_backup_finish().
  9101. **
  9102. ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
  9103. ** sqlite3_backup_step() errors occurred, regardless or whether or not
  9104. ** sqlite3_backup_step() completed.
  9105. ** ^If an out-of-memory condition or IO error occurred during any prior
  9106. ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
  9107. ** sqlite3_backup_finish() returns the corresponding [error code].
  9108. **
  9109. ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
  9110. ** is not a permanent error and does not affect the return value of
  9111. ** sqlite3_backup_finish().
  9112. **
  9113. ** [[sqlite3_backup_remaining()]] [[sqlite3_backup_pagecount()]]
  9114. ** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
  9115. **
  9116. ** ^The sqlite3_backup_remaining() routine returns the number of pages still
  9117. ** to be backed up at the conclusion of the most recent sqlite3_backup_step().
  9118. ** ^The sqlite3_backup_pagecount() routine returns the total number of pages
  9119. ** in the source database at the conclusion of the most recent
  9120. ** sqlite3_backup_step().
  9121. ** ^(The values returned by these functions are only updated by
  9122. ** sqlite3_backup_step(). If the source database is modified in a way that
  9123. ** changes the size of the source database or the number of pages remaining,
  9124. ** those changes are not reflected in the output of sqlite3_backup_pagecount()
  9125. ** and sqlite3_backup_remaining() until after the next
  9126. ** sqlite3_backup_step().)^
  9127. **
  9128. ** <b>Concurrent Usage of Database Handles</b>
  9129. **
  9130. ** ^The source [database connection] may be used by the application for other
  9131. ** purposes while a backup operation is underway or being initialized.
  9132. ** ^If SQLite is compiled and configured to support threadsafe database
  9133. ** connections, then the source database connection may be used concurrently
  9134. ** from within other threads.
  9135. **
  9136. ** However, the application must guarantee that the destination
  9137. ** [database connection] is not passed to any other API (by any thread) after
  9138. ** sqlite3_backup_init() is called and before the corresponding call to
  9139. ** sqlite3_backup_finish(). SQLite does not currently check to see
  9140. ** if the application incorrectly accesses the destination [database connection]
  9141. ** and so no error code is reported, but the operations may malfunction
  9142. ** nevertheless. Use of the destination database connection while a
  9143. ** backup is in progress might also also cause a mutex deadlock.
  9144. **
  9145. ** If running in [shared cache mode], the application must
  9146. ** guarantee that the shared cache used by the destination database
  9147. ** is not accessed while the backup is running. In practice this means
  9148. ** that the application must guarantee that the disk file being
  9149. ** backed up to is not accessed by any connection within the process,
  9150. ** not just the specific connection that was passed to sqlite3_backup_init().
  9151. **
  9152. ** The [sqlite3_backup] object itself is partially threadsafe. Multiple
  9153. ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
  9154. ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
  9155. ** APIs are not strictly speaking threadsafe. If they are invoked at the
  9156. ** same time as another thread is invoking sqlite3_backup_step() it is
  9157. ** possible that they return invalid values.
  9158. */
  9159. SQLITE_API sqlite3_backup *sqlite3_backup_init(
  9160. sqlite3 *pDest, /* Destination database handle */
  9161. const char *zDestName, /* Destination database name */
  9162. sqlite3 *pSource, /* Source database handle */
  9163. const char *zSourceName /* Source database name */
  9164. );
  9165. SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
  9166. SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
  9167. SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
  9168. SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
  9169. /*
  9170. ** CAPI3REF: Unlock Notification
  9171. ** METHOD: sqlite3
  9172. **
  9173. ** ^When running in shared-cache mode, a database operation may fail with
  9174. ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
  9175. ** individual tables within the shared-cache cannot be obtained. See
  9176. ** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
  9177. ** ^This API may be used to register a callback that SQLite will invoke
  9178. ** when the connection currently holding the required lock relinquishes it.
  9179. ** ^This API is only available if the library was compiled with the
  9180. ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
  9181. **
  9182. ** See Also: [Using the SQLite Unlock Notification Feature].
  9183. **
  9184. ** ^Shared-cache locks are released when a database connection concludes
  9185. ** its current transaction, either by committing it or rolling it back.
  9186. **
  9187. ** ^When a connection (known as the blocked connection) fails to obtain a
  9188. ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
  9189. ** identity of the database connection (the blocking connection) that
  9190. ** has locked the required resource is stored internally. ^After an
  9191. ** application receives an SQLITE_LOCKED error, it may call the
  9192. ** sqlite3_unlock_notify() method with the blocked connection handle as
  9193. ** the first argument to register for a callback that will be invoked
  9194. ** when the blocking connections current transaction is concluded. ^The
  9195. ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
  9196. ** call that concludes the blocking connections transaction.
  9197. **
  9198. ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
  9199. ** there is a chance that the blocking connection will have already
  9200. ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
  9201. ** If this happens, then the specified callback is invoked immediately,
  9202. ** from within the call to sqlite3_unlock_notify().)^
  9203. **
  9204. ** ^If the blocked connection is attempting to obtain a write-lock on a
  9205. ** shared-cache table, and more than one other connection currently holds
  9206. ** a read-lock on the same table, then SQLite arbitrarily selects one of
  9207. ** the other connections to use as the blocking connection.
  9208. **
  9209. ** ^(There may be at most one unlock-notify callback registered by a
  9210. ** blocked connection. If sqlite3_unlock_notify() is called when the
  9211. ** blocked connection already has a registered unlock-notify callback,
  9212. ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
  9213. ** called with a NULL pointer as its second argument, then any existing
  9214. ** unlock-notify callback is canceled. ^The blocked connections
  9215. ** unlock-notify callback may also be canceled by closing the blocked
  9216. ** connection using [sqlite3_close()].
  9217. **
  9218. ** The unlock-notify callback is not reentrant. If an application invokes
  9219. ** any sqlite3_xxx API functions from within an unlock-notify callback, a
  9220. ** crash or deadlock may be the result.
  9221. **
  9222. ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
  9223. ** returns SQLITE_OK.
  9224. **
  9225. ** <b>Callback Invocation Details</b>
  9226. **
  9227. ** When an unlock-notify callback is registered, the application provides a
  9228. ** single void* pointer that is passed to the callback when it is invoked.
  9229. ** However, the signature of the callback function allows SQLite to pass
  9230. ** it an array of void* context pointers. The first argument passed to
  9231. ** an unlock-notify callback is a pointer to an array of void* pointers,
  9232. ** and the second is the number of entries in the array.
  9233. **
  9234. ** When a blocking connections transaction is concluded, there may be
  9235. ** more than one blocked connection that has registered for an unlock-notify
  9236. ** callback. ^If two or more such blocked connections have specified the
  9237. ** same callback function, then instead of invoking the callback function
  9238. ** multiple times, it is invoked once with the set of void* context pointers
  9239. ** specified by the blocked connections bundled together into an array.
  9240. ** This gives the application an opportunity to prioritize any actions
  9241. ** related to the set of unblocked database connections.
  9242. **
  9243. ** <b>Deadlock Detection</b>
  9244. **
  9245. ** Assuming that after registering for an unlock-notify callback a
  9246. ** database waits for the callback to be issued before taking any further
  9247. ** action (a reasonable assumption), then using this API may cause the
  9248. ** application to deadlock. For example, if connection X is waiting for
  9249. ** connection Y's transaction to be concluded, and similarly connection
  9250. ** Y is waiting on connection X's transaction, then neither connection
  9251. ** will proceed and the system may remain deadlocked indefinitely.
  9252. **
  9253. ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
  9254. ** detection. ^If a given call to sqlite3_unlock_notify() would put the
  9255. ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
  9256. ** unlock-notify callback is registered. The system is said to be in
  9257. ** a deadlocked state if connection A has registered for an unlock-notify
  9258. ** callback on the conclusion of connection B's transaction, and connection
  9259. ** B has itself registered for an unlock-notify callback when connection
  9260. ** A's transaction is concluded. ^Indirect deadlock is also detected, so
  9261. ** the system is also considered to be deadlocked if connection B has
  9262. ** registered for an unlock-notify callback on the conclusion of connection
  9263. ** C's transaction, where connection C is waiting on connection A. ^Any
  9264. ** number of levels of indirection are allowed.
  9265. **
  9266. ** <b>The "DROP TABLE" Exception</b>
  9267. **
  9268. ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
  9269. ** always appropriate to call sqlite3_unlock_notify(). There is however,
  9270. ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
  9271. ** SQLite checks if there are any currently executing SELECT statements
  9272. ** that belong to the same connection. If there are, SQLITE_LOCKED is
  9273. ** returned. In this case there is no "blocking connection", so invoking
  9274. ** sqlite3_unlock_notify() results in the unlock-notify callback being
  9275. ** invoked immediately. If the application then re-attempts the "DROP TABLE"
  9276. ** or "DROP INDEX" query, an infinite loop might be the result.
  9277. **
  9278. ** One way around this problem is to check the extended error code returned
  9279. ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
  9280. ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
  9281. ** the special "DROP TABLE/INDEX" case, the extended error code is just
  9282. ** SQLITE_LOCKED.)^
  9283. */
  9284. SQLITE_API int sqlite3_unlock_notify(
  9285. sqlite3 *pBlocked, /* Waiting connection */
  9286. void (*xNotify)(void **apArg, int nArg), /* Callback function to invoke */
  9287. void *pNotifyArg /* Argument to pass to xNotify */
  9288. );
  9289. /*
  9290. ** CAPI3REF: String Comparison
  9291. **
  9292. ** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications
  9293. ** and extensions to compare the contents of two buffers containing UTF-8
  9294. ** strings in a case-independent fashion, using the same definition of "case
  9295. ** independence" that SQLite uses internally when comparing identifiers.
  9296. */
  9297. SQLITE_API int sqlite3_stricmp(const char *, const char *);
  9298. SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
  9299. /*
  9300. ** CAPI3REF: String Globbing
  9301. *
  9302. ** ^The [sqlite3_strglob(P,X)] interface returns zero if and only if
  9303. ** string X matches the [GLOB] pattern P.
  9304. ** ^The definition of [GLOB] pattern matching used in
  9305. ** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the
  9306. ** SQL dialect understood by SQLite. ^The [sqlite3_strglob(P,X)] function
  9307. ** is case sensitive.
  9308. **
  9309. ** Note that this routine returns zero on a match and non-zero if the strings
  9310. ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
  9311. **
  9312. ** See also: [sqlite3_strlike()].
  9313. */
  9314. SQLITE_API int sqlite3_strglob(const char *zGlob, const char *zStr);
  9315. /*
  9316. ** CAPI3REF: String LIKE Matching
  9317. *
  9318. ** ^The [sqlite3_strlike(P,X,E)] interface returns zero if and only if
  9319. ** string X matches the [LIKE] pattern P with escape character E.
  9320. ** ^The definition of [LIKE] pattern matching used in
  9321. ** [sqlite3_strlike(P,X,E)] is the same as for the "X LIKE P ESCAPE E"
  9322. ** operator in the SQL dialect understood by SQLite. ^For "X LIKE P" without
  9323. ** the ESCAPE clause, set the E parameter of [sqlite3_strlike(P,X,E)] to 0.
  9324. ** ^As with the LIKE operator, the [sqlite3_strlike(P,X,E)] function is case
  9325. ** insensitive - equivalent upper and lower case ASCII characters match
  9326. ** one another.
  9327. **
  9328. ** ^The [sqlite3_strlike(P,X,E)] function matches Unicode characters, though
  9329. ** only ASCII characters are case folded.
  9330. **
  9331. ** Note that this routine returns zero on a match and non-zero if the strings
  9332. ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
  9333. **
  9334. ** See also: [sqlite3_strglob()].
  9335. */
  9336. SQLITE_API int sqlite3_strlike(const char *zGlob, const char *zStr, unsigned int cEsc);
  9337. /*
  9338. ** CAPI3REF: Error Logging Interface
  9339. **
  9340. ** ^The [sqlite3_log()] interface writes a message into the [error log]
  9341. ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
  9342. ** ^If logging is enabled, the zFormat string and subsequent arguments are
  9343. ** used with [sqlite3_snprintf()] to generate the final output string.
  9344. **
  9345. ** The sqlite3_log() interface is intended for use by extensions such as
  9346. ** virtual tables, collating functions, and SQL functions. While there is
  9347. ** nothing to prevent an application from calling sqlite3_log(), doing so
  9348. ** is considered bad form.
  9349. **
  9350. ** The zFormat string must not be NULL.
  9351. **
  9352. ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
  9353. ** will not use dynamically allocated memory. The log message is stored in
  9354. ** a fixed-length buffer on the stack. If the log message is longer than
  9355. ** a few hundred characters, it will be truncated to the length of the
  9356. ** buffer.
  9357. */
  9358. SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
  9359. /*
  9360. ** CAPI3REF: Write-Ahead Log Commit Hook
  9361. ** METHOD: sqlite3
  9362. **
  9363. ** ^The [sqlite3_wal_hook()] function is used to register a callback that
  9364. ** is invoked each time data is committed to a database in wal mode.
  9365. **
  9366. ** ^(The callback is invoked by SQLite after the commit has taken place and
  9367. ** the associated write-lock on the database released)^, so the implementation
  9368. ** may read, write or [checkpoint] the database as required.
  9369. **
  9370. ** ^The first parameter passed to the callback function when it is invoked
  9371. ** is a copy of the third parameter passed to sqlite3_wal_hook() when
  9372. ** registering the callback. ^The second is a copy of the database handle.
  9373. ** ^The third parameter is the name of the database that was written to -
  9374. ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
  9375. ** is the number of pages currently in the write-ahead log file,
  9376. ** including those that were just committed.
  9377. **
  9378. ** The callback function should normally return [SQLITE_OK]. ^If an error
  9379. ** code is returned, that error will propagate back up through the
  9380. ** SQLite code base to cause the statement that provoked the callback
  9381. ** to report an error, though the commit will have still occurred. If the
  9382. ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
  9383. ** that does not correspond to any valid SQLite error code, the results
  9384. ** are undefined.
  9385. **
  9386. ** A single database handle may have at most a single write-ahead log callback
  9387. ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
  9388. ** previously registered write-ahead log callback. ^Note that the
  9389. ** [sqlite3_wal_autocheckpoint()] interface and the
  9390. ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
  9391. ** overwrite any prior [sqlite3_wal_hook()] settings.
  9392. */
  9393. SQLITE_API void *sqlite3_wal_hook(
  9394. sqlite3*,
  9395. int(*)(void *,sqlite3*,const char*,int),
  9396. void*
  9397. );
  9398. /*
  9399. ** CAPI3REF: Configure an auto-checkpoint
  9400. ** METHOD: sqlite3
  9401. **
  9402. ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
  9403. ** [sqlite3_wal_hook()] that causes any database on [database connection] D
  9404. ** to automatically [checkpoint]
  9405. ** after committing a transaction if there are N or
  9406. ** more frames in the [write-ahead log] file. ^Passing zero or
  9407. ** a negative value as the nFrame parameter disables automatic
  9408. ** checkpoints entirely.
  9409. **
  9410. ** ^The callback registered by this function replaces any existing callback
  9411. ** registered using [sqlite3_wal_hook()]. ^Likewise, registering a callback
  9412. ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
  9413. ** configured by this function.
  9414. **
  9415. ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
  9416. ** from SQL.
  9417. **
  9418. ** ^Checkpoints initiated by this mechanism are
  9419. ** [sqlite3_wal_checkpoint_v2|PASSIVE].
  9420. **
  9421. ** ^Every new [database connection] defaults to having the auto-checkpoint
  9422. ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
  9423. ** pages. The use of this interface
  9424. ** is only necessary if the default setting is found to be suboptimal
  9425. ** for a particular application.
  9426. */
  9427. SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
  9428. /*
  9429. ** CAPI3REF: Checkpoint a database
  9430. ** METHOD: sqlite3
  9431. **
  9432. ** ^(The sqlite3_wal_checkpoint(D,X) is equivalent to
  9433. ** [sqlite3_wal_checkpoint_v2](D,X,[SQLITE_CHECKPOINT_PASSIVE],0,0).)^
  9434. **
  9435. ** In brief, sqlite3_wal_checkpoint(D,X) causes the content in the
  9436. ** [write-ahead log] for database X on [database connection] D to be
  9437. ** transferred into the database file and for the write-ahead log to
  9438. ** be reset. See the [checkpointing] documentation for addition
  9439. ** information.
  9440. **
  9441. ** This interface used to be the only way to cause a checkpoint to
  9442. ** occur. But then the newer and more powerful [sqlite3_wal_checkpoint_v2()]
  9443. ** interface was added. This interface is retained for backwards
  9444. ** compatibility and as a convenience for applications that need to manually
  9445. ** start a callback but which do not need the full power (and corresponding
  9446. ** complication) of [sqlite3_wal_checkpoint_v2()].
  9447. */
  9448. SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
  9449. /*
  9450. ** CAPI3REF: Checkpoint a database
  9451. ** METHOD: sqlite3
  9452. **
  9453. ** ^(The sqlite3_wal_checkpoint_v2(D,X,M,L,C) interface runs a checkpoint
  9454. ** operation on database X of [database connection] D in mode M. Status
  9455. ** information is written back into integers pointed to by L and C.)^
  9456. ** ^(The M parameter must be a valid [checkpoint mode]:)^
  9457. **
  9458. ** <dl>
  9459. ** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
  9460. ** ^Checkpoint as many frames as possible without waiting for any database
  9461. ** readers or writers to finish, then sync the database file if all frames
  9462. ** in the log were checkpointed. ^The [busy-handler callback]
  9463. ** is never invoked in the SQLITE_CHECKPOINT_PASSIVE mode.
  9464. ** ^On the other hand, passive mode might leave the checkpoint unfinished
  9465. ** if there are concurrent readers or writers.
  9466. **
  9467. ** <dt>SQLITE_CHECKPOINT_FULL<dd>
  9468. ** ^This mode blocks (it invokes the
  9469. ** [sqlite3_busy_handler|busy-handler callback]) until there is no
  9470. ** database writer and all readers are reading from the most recent database
  9471. ** snapshot. ^It then checkpoints all frames in the log file and syncs the
  9472. ** database file. ^This mode blocks new database writers while it is pending,
  9473. ** but new database readers are allowed to continue unimpeded.
  9474. **
  9475. ** <dt>SQLITE_CHECKPOINT_RESTART<dd>
  9476. ** ^This mode works the same way as SQLITE_CHECKPOINT_FULL with the addition
  9477. ** that after checkpointing the log file it blocks (calls the
  9478. ** [busy-handler callback])
  9479. ** until all readers are reading from the database file only. ^This ensures
  9480. ** that the next writer will restart the log file from the beginning.
  9481. ** ^Like SQLITE_CHECKPOINT_FULL, this mode blocks new
  9482. ** database writer attempts while it is pending, but does not impede readers.
  9483. **
  9484. ** <dt>SQLITE_CHECKPOINT_TRUNCATE<dd>
  9485. ** ^This mode works the same way as SQLITE_CHECKPOINT_RESTART with the
  9486. ** addition that it also truncates the log file to zero bytes just prior
  9487. ** to a successful return.
  9488. ** </dl>
  9489. **
  9490. ** ^If pnLog is not NULL, then *pnLog is set to the total number of frames in
  9491. ** the log file or to -1 if the checkpoint could not run because
  9492. ** of an error or because the database is not in [WAL mode]. ^If pnCkpt is not
  9493. ** NULL,then *pnCkpt is set to the total number of checkpointed frames in the
  9494. ** log file (including any that were already checkpointed before the function
  9495. ** was called) or to -1 if the checkpoint could not run due to an error or
  9496. ** because the database is not in WAL mode. ^Note that upon successful
  9497. ** completion of an SQLITE_CHECKPOINT_TRUNCATE, the log file will have been
  9498. ** truncated to zero bytes and so both *pnLog and *pnCkpt will be set to zero.
  9499. **
  9500. ** ^All calls obtain an exclusive "checkpoint" lock on the database file. ^If
  9501. ** any other process is running a checkpoint operation at the same time, the
  9502. ** lock cannot be obtained and SQLITE_BUSY is returned. ^Even if there is a
  9503. ** busy-handler configured, it will not be invoked in this case.
  9504. **
  9505. ** ^The SQLITE_CHECKPOINT_FULL, RESTART and TRUNCATE modes also obtain the
  9506. ** exclusive "writer" lock on the database file. ^If the writer lock cannot be
  9507. ** obtained immediately, and a busy-handler is configured, it is invoked and
  9508. ** the writer lock retried until either the busy-handler returns 0 or the lock
  9509. ** is successfully obtained. ^The busy-handler is also invoked while waiting for
  9510. ** database readers as described above. ^If the busy-handler returns 0 before
  9511. ** the writer lock is obtained or while waiting for database readers, the
  9512. ** checkpoint operation proceeds from that point in the same way as
  9513. ** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible
  9514. ** without blocking any further. ^SQLITE_BUSY is returned in this case.
  9515. **
  9516. ** ^If parameter zDb is NULL or points to a zero length string, then the
  9517. ** specified operation is attempted on all WAL databases [attached] to
  9518. ** [database connection] db. In this case the
  9519. ** values written to output parameters *pnLog and *pnCkpt are undefined. ^If
  9520. ** an SQLITE_BUSY error is encountered when processing one or more of the
  9521. ** attached WAL databases, the operation is still attempted on any remaining
  9522. ** attached databases and SQLITE_BUSY is returned at the end. ^If any other
  9523. ** error occurs while processing an attached database, processing is abandoned
  9524. ** and the error code is returned to the caller immediately. ^If no error
  9525. ** (SQLITE_BUSY or otherwise) is encountered while processing the attached
  9526. ** databases, SQLITE_OK is returned.
  9527. **
  9528. ** ^If database zDb is the name of an attached database that is not in WAL
  9529. ** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. ^If
  9530. ** zDb is not NULL (or a zero length string) and is not the name of any
  9531. ** attached database, SQLITE_ERROR is returned to the caller.
  9532. **
  9533. ** ^Unless it returns SQLITE_MISUSE,
  9534. ** the sqlite3_wal_checkpoint_v2() interface
  9535. ** sets the error information that is queried by
  9536. ** [sqlite3_errcode()] and [sqlite3_errmsg()].
  9537. **
  9538. ** ^The [PRAGMA wal_checkpoint] command can be used to invoke this interface
  9539. ** from SQL.
  9540. */
  9541. SQLITE_API int sqlite3_wal_checkpoint_v2(
  9542. sqlite3 *db, /* Database handle */
  9543. const char *zDb, /* Name of attached database (or NULL) */
  9544. int eMode, /* SQLITE_CHECKPOINT_* value */
  9545. int *pnLog, /* OUT: Size of WAL log in frames */
  9546. int *pnCkpt /* OUT: Total number of frames checkpointed */
  9547. );
  9548. /*
  9549. ** CAPI3REF: Checkpoint Mode Values
  9550. ** KEYWORDS: {checkpoint mode}
  9551. **
  9552. ** These constants define all valid values for the "checkpoint mode" passed
  9553. ** as the third parameter to the [sqlite3_wal_checkpoint_v2()] interface.
  9554. ** See the [sqlite3_wal_checkpoint_v2()] documentation for details on the
  9555. ** meaning of each of these checkpoint modes.
  9556. */
  9557. #define SQLITE_CHECKPOINT_PASSIVE 0 /* Do as much as possible w/o blocking */
  9558. #define SQLITE_CHECKPOINT_FULL 1 /* Wait for writers, then checkpoint */
  9559. #define SQLITE_CHECKPOINT_RESTART 2 /* Like FULL but wait for for readers */
  9560. #define SQLITE_CHECKPOINT_TRUNCATE 3 /* Like RESTART but also truncate WAL */
  9561. /*
  9562. ** CAPI3REF: Virtual Table Interface Configuration
  9563. **
  9564. ** This function may be called by either the [xConnect] or [xCreate] method
  9565. ** of a [virtual table] implementation to configure
  9566. ** various facets of the virtual table interface.
  9567. **
  9568. ** If this interface is invoked outside the context of an xConnect or
  9569. ** xCreate virtual table method then the behavior is undefined.
  9570. **
  9571. ** At present, there is only one option that may be configured using
  9572. ** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].) Further options
  9573. ** may be added in the future.
  9574. */
  9575. SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);
  9576. /*
  9577. ** CAPI3REF: Virtual Table Configuration Options
  9578. **
  9579. ** These macros define the various options to the
  9580. ** [sqlite3_vtab_config()] interface that [virtual table] implementations
  9581. ** can use to customize and optimize their behavior.
  9582. **
  9583. ** <dl>
  9584. ** [[SQLITE_VTAB_CONSTRAINT_SUPPORT]]
  9585. ** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT
  9586. ** <dd>Calls of the form
  9587. ** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
  9588. ** where X is an integer. If X is zero, then the [virtual table] whose
  9589. ** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
  9590. ** support constraints. In this configuration (which is the default) if
  9591. ** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
  9592. ** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
  9593. ** specified as part of the users SQL statement, regardless of the actual
  9594. ** ON CONFLICT mode specified.
  9595. **
  9596. ** If X is non-zero, then the virtual table implementation guarantees
  9597. ** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
  9598. ** any modifications to internal or persistent data structures have been made.
  9599. ** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite
  9600. ** is able to roll back a statement or database transaction, and abandon
  9601. ** or continue processing the current SQL statement as appropriate.
  9602. ** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
  9603. ** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
  9604. ** had been ABORT.
  9605. **
  9606. ** Virtual table implementations that are required to handle OR REPLACE
  9607. ** must do so within the [xUpdate] method. If a call to the
  9608. ** [sqlite3_vtab_on_conflict()] function indicates that the current ON
  9609. ** CONFLICT policy is REPLACE, the virtual table implementation should
  9610. ** silently replace the appropriate rows within the xUpdate callback and
  9611. ** return SQLITE_OK. Or, if this is not possible, it may return
  9612. ** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT
  9613. ** constraint handling.
  9614. ** </dl>
  9615. */
  9616. #define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
  9617. /*
  9618. ** CAPI3REF: Determine The Virtual Table Conflict Policy
  9619. **
  9620. ** This function may only be called from within a call to the [xUpdate] method
  9621. ** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
  9622. ** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
  9623. ** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
  9624. ** of the SQL statement that triggered the call to the [xUpdate] method of the
  9625. ** [virtual table].
  9626. */
  9627. SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *);
  9628. /*
  9629. ** CAPI3REF: Determine If Virtual Table Column Access Is For UPDATE
  9630. **
  9631. ** If the sqlite3_vtab_nochange(X) routine is called within the [xColumn]
  9632. ** method of a [virtual table], then it returns true if and only if the
  9633. ** column is being fetched as part of an UPDATE operation during which the
  9634. ** column value will not change. Applications might use this to substitute
  9635. ** a return value that is less expensive to compute and that the corresponding
  9636. ** [xUpdate] method understands as a "no-change" value.
  9637. **
  9638. ** If the [xColumn] method calls sqlite3_vtab_nochange() and finds that
  9639. ** the column is not changed by the UPDATE statement, then the xColumn
  9640. ** method can optionally return without setting a result, without calling
  9641. ** any of the [sqlite3_result_int|sqlite3_result_xxxxx() interfaces].
  9642. ** In that case, [sqlite3_value_nochange(X)] will return true for the
  9643. ** same column in the [xUpdate] method.
  9644. */
  9645. SQLITE_API int sqlite3_vtab_nochange(sqlite3_context*);
  9646. /*
  9647. ** CAPI3REF: Determine The Collation For a Virtual Table Constraint
  9648. **
  9649. ** This function may only be called from within a call to the [xBestIndex]
  9650. ** method of a [virtual table].
  9651. **
  9652. ** The first argument must be the sqlite3_index_info object that is the
  9653. ** first parameter to the xBestIndex() method. The second argument must be
  9654. ** an index into the aConstraint[] array belonging to the sqlite3_index_info
  9655. ** structure passed to xBestIndex. This function returns a pointer to a buffer
  9656. ** containing the name of the collation sequence for the corresponding
  9657. ** constraint.
  9658. */
  9659. SQLITE_API SQLITE_EXPERIMENTAL const char *sqlite3_vtab_collation(sqlite3_index_info*,int);
  9660. /*
  9661. ** CAPI3REF: Conflict resolution modes
  9662. ** KEYWORDS: {conflict resolution mode}
  9663. **
  9664. ** These constants are returned by [sqlite3_vtab_on_conflict()] to
  9665. ** inform a [virtual table] implementation what the [ON CONFLICT] mode
  9666. ** is for the SQL statement being evaluated.
  9667. **
  9668. ** Note that the [SQLITE_IGNORE] constant is also used as a potential
  9669. ** return value from the [sqlite3_set_authorizer()] callback and that
  9670. ** [SQLITE_ABORT] is also a [result code].
  9671. */
  9672. #define SQLITE_ROLLBACK 1
  9673. /* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
  9674. #define SQLITE_FAIL 3
  9675. /* #define SQLITE_ABORT 4 // Also an error code */
  9676. #define SQLITE_REPLACE 5
  9677. /*
  9678. ** CAPI3REF: Prepared Statement Scan Status Opcodes
  9679. ** KEYWORDS: {scanstatus options}
  9680. **
  9681. ** The following constants can be used for the T parameter to the
  9682. ** [sqlite3_stmt_scanstatus(S,X,T,V)] interface. Each constant designates a
  9683. ** different metric for sqlite3_stmt_scanstatus() to return.
  9684. **
  9685. ** When the value returned to V is a string, space to hold that string is
  9686. ** managed by the prepared statement S and will be automatically freed when
  9687. ** S is finalized.
  9688. **
  9689. ** <dl>
  9690. ** [[SQLITE_SCANSTAT_NLOOP]] <dt>SQLITE_SCANSTAT_NLOOP</dt>
  9691. ** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be
  9692. ** set to the total number of times that the X-th loop has run.</dd>
  9693. **
  9694. ** [[SQLITE_SCANSTAT_NVISIT]] <dt>SQLITE_SCANSTAT_NVISIT</dt>
  9695. ** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be set
  9696. ** to the total number of rows examined by all iterations of the X-th loop.</dd>
  9697. **
  9698. ** [[SQLITE_SCANSTAT_EST]] <dt>SQLITE_SCANSTAT_EST</dt>
  9699. ** <dd>^The "double" variable pointed to by the T parameter will be set to the
  9700. ** query planner's estimate for the average number of rows output from each
  9701. ** iteration of the X-th loop. If the query planner's estimates was accurate,
  9702. ** then this value will approximate the quotient NVISIT/NLOOP and the
  9703. ** product of this value for all prior loops with the same SELECTID will
  9704. ** be the NLOOP value for the current loop.
  9705. **
  9706. ** [[SQLITE_SCANSTAT_NAME]] <dt>SQLITE_SCANSTAT_NAME</dt>
  9707. ** <dd>^The "const char *" variable pointed to by the T parameter will be set
  9708. ** to a zero-terminated UTF-8 string containing the name of the index or table
  9709. ** used for the X-th loop.
  9710. **
  9711. ** [[SQLITE_SCANSTAT_EXPLAIN]] <dt>SQLITE_SCANSTAT_EXPLAIN</dt>
  9712. ** <dd>^The "const char *" variable pointed to by the T parameter will be set
  9713. ** to a zero-terminated UTF-8 string containing the [EXPLAIN QUERY PLAN]
  9714. ** description for the X-th loop.
  9715. **
  9716. ** [[SQLITE_SCANSTAT_SELECTID]] <dt>SQLITE_SCANSTAT_SELECT</dt>
  9717. ** <dd>^The "int" variable pointed to by the T parameter will be set to the
  9718. ** "select-id" for the X-th loop. The select-id identifies which query or
  9719. ** subquery the loop is part of. The main query has a select-id of zero.
  9720. ** The select-id is the same value as is output in the first column
  9721. ** of an [EXPLAIN QUERY PLAN] query.
  9722. ** </dl>
  9723. */
  9724. #define SQLITE_SCANSTAT_NLOOP 0
  9725. #define SQLITE_SCANSTAT_NVISIT 1
  9726. #define SQLITE_SCANSTAT_EST 2
  9727. #define SQLITE_SCANSTAT_NAME 3
  9728. #define SQLITE_SCANSTAT_EXPLAIN 4
  9729. #define SQLITE_SCANSTAT_SELECTID 5
  9730. /*
  9731. ** CAPI3REF: Prepared Statement Scan Status
  9732. ** METHOD: sqlite3_stmt
  9733. **
  9734. ** This interface returns information about the predicted and measured
  9735. ** performance for pStmt. Advanced applications can use this
  9736. ** interface to compare the predicted and the measured performance and
  9737. ** issue warnings and/or rerun [ANALYZE] if discrepancies are found.
  9738. **
  9739. ** Since this interface is expected to be rarely used, it is only
  9740. ** available if SQLite is compiled using the [SQLITE_ENABLE_STMT_SCANSTATUS]
  9741. ** compile-time option.
  9742. **
  9743. ** The "iScanStatusOp" parameter determines which status information to return.
  9744. ** The "iScanStatusOp" must be one of the [scanstatus options] or the behavior
  9745. ** of this interface is undefined.
  9746. ** ^The requested measurement is written into a variable pointed to by
  9747. ** the "pOut" parameter.
  9748. ** Parameter "idx" identifies the specific loop to retrieve statistics for.
  9749. ** Loops are numbered starting from zero. ^If idx is out of range - less than
  9750. ** zero or greater than or equal to the total number of loops used to implement
  9751. ** the statement - a non-zero value is returned and the variable that pOut
  9752. ** points to is unchanged.
  9753. **
  9754. ** ^Statistics might not be available for all loops in all statements. ^In cases
  9755. ** where there exist loops with no available statistics, this function behaves
  9756. ** as if the loop did not exist - it returns non-zero and leave the variable
  9757. ** that pOut points to unchanged.
  9758. **
  9759. ** See also: [sqlite3_stmt_scanstatus_reset()]
  9760. */
  9761. SQLITE_API int sqlite3_stmt_scanstatus(
  9762. sqlite3_stmt *pStmt, /* Prepared statement for which info desired */
  9763. int idx, /* Index of loop to report on */
  9764. int iScanStatusOp, /* Information desired. SQLITE_SCANSTAT_* */
  9765. void *pOut /* Result written here */
  9766. );
  9767. /*
  9768. ** CAPI3REF: Zero Scan-Status Counters
  9769. ** METHOD: sqlite3_stmt
  9770. **
  9771. ** ^Zero all [sqlite3_stmt_scanstatus()] related event counters.
  9772. **
  9773. ** This API is only available if the library is built with pre-processor
  9774. ** symbol [SQLITE_ENABLE_STMT_SCANSTATUS] defined.
  9775. */
  9776. SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt*);
  9777. /*
  9778. ** CAPI3REF: Flush caches to disk mid-transaction
  9779. **
  9780. ** ^If a write-transaction is open on [database connection] D when the
  9781. ** [sqlite3_db_cacheflush(D)] interface invoked, any dirty
  9782. ** pages in the pager-cache that are not currently in use are written out
  9783. ** to disk. A dirty page may be in use if a database cursor created by an
  9784. ** active SQL statement is reading from it, or if it is page 1 of a database
  9785. ** file (page 1 is always "in use"). ^The [sqlite3_db_cacheflush(D)]
  9786. ** interface flushes caches for all schemas - "main", "temp", and
  9787. ** any [attached] databases.
  9788. **
  9789. ** ^If this function needs to obtain extra database locks before dirty pages
  9790. ** can be flushed to disk, it does so. ^If those locks cannot be obtained
  9791. ** immediately and there is a busy-handler callback configured, it is invoked
  9792. ** in the usual manner. ^If the required lock still cannot be obtained, then
  9793. ** the database is skipped and an attempt made to flush any dirty pages
  9794. ** belonging to the next (if any) database. ^If any databases are skipped
  9795. ** because locks cannot be obtained, but no other error occurs, this
  9796. ** function returns SQLITE_BUSY.
  9797. **
  9798. ** ^If any other error occurs while flushing dirty pages to disk (for
  9799. ** example an IO error or out-of-memory condition), then processing is
  9800. ** abandoned and an SQLite [error code] is returned to the caller immediately.
  9801. **
  9802. ** ^Otherwise, if no error occurs, [sqlite3_db_cacheflush()] returns SQLITE_OK.
  9803. **
  9804. ** ^This function does not set the database handle error code or message
  9805. ** returned by the [sqlite3_errcode()] and [sqlite3_errmsg()] functions.
  9806. */
  9807. SQLITE_API int sqlite3_db_cacheflush(sqlite3*);
  9808. /*
  9809. ** CAPI3REF: The pre-update hook.
  9810. **
  9811. ** ^These interfaces are only available if SQLite is compiled using the
  9812. ** [SQLITE_ENABLE_PREUPDATE_HOOK] compile-time option.
  9813. **
  9814. ** ^The [sqlite3_preupdate_hook()] interface registers a callback function
  9815. ** that is invoked prior to each [INSERT], [UPDATE], and [DELETE] operation
  9816. ** on a database table.
  9817. ** ^At most one preupdate hook may be registered at a time on a single
  9818. ** [database connection]; each call to [sqlite3_preupdate_hook()] overrides
  9819. ** the previous setting.
  9820. ** ^The preupdate hook is disabled by invoking [sqlite3_preupdate_hook()]
  9821. ** with a NULL pointer as the second parameter.
  9822. ** ^The third parameter to [sqlite3_preupdate_hook()] is passed through as
  9823. ** the first parameter to callbacks.
  9824. **
  9825. ** ^The preupdate hook only fires for changes to real database tables; the
  9826. ** preupdate hook is not invoked for changes to [virtual tables] or to
  9827. ** system tables like sqlite_master or sqlite_stat1.
  9828. **
  9829. ** ^The second parameter to the preupdate callback is a pointer to
  9830. ** the [database connection] that registered the preupdate hook.
  9831. ** ^The third parameter to the preupdate callback is one of the constants
  9832. ** [SQLITE_INSERT], [SQLITE_DELETE], or [SQLITE_UPDATE] to identify the
  9833. ** kind of update operation that is about to occur.
  9834. ** ^(The fourth parameter to the preupdate callback is the name of the
  9835. ** database within the database connection that is being modified. This
  9836. ** will be "main" for the main database or "temp" for TEMP tables or
  9837. ** the name given after the AS keyword in the [ATTACH] statement for attached
  9838. ** databases.)^
  9839. ** ^The fifth parameter to the preupdate callback is the name of the
  9840. ** table that is being modified.
  9841. **
  9842. ** For an UPDATE or DELETE operation on a [rowid table], the sixth
  9843. ** parameter passed to the preupdate callback is the initial [rowid] of the
  9844. ** row being modified or deleted. For an INSERT operation on a rowid table,
  9845. ** or any operation on a WITHOUT ROWID table, the value of the sixth
  9846. ** parameter is undefined. For an INSERT or UPDATE on a rowid table the
  9847. ** seventh parameter is the final rowid value of the row being inserted
  9848. ** or updated. The value of the seventh parameter passed to the callback
  9849. ** function is not defined for operations on WITHOUT ROWID tables, or for
  9850. ** INSERT operations on rowid tables.
  9851. **
  9852. ** The [sqlite3_preupdate_old()], [sqlite3_preupdate_new()],
  9853. ** [sqlite3_preupdate_count()], and [sqlite3_preupdate_depth()] interfaces
  9854. ** provide additional information about a preupdate event. These routines
  9855. ** may only be called from within a preupdate callback. Invoking any of
  9856. ** these routines from outside of a preupdate callback or with a
  9857. ** [database connection] pointer that is different from the one supplied
  9858. ** to the preupdate callback results in undefined and probably undesirable
  9859. ** behavior.
  9860. **
  9861. ** ^The [sqlite3_preupdate_count(D)] interface returns the number of columns
  9862. ** in the row that is being inserted, updated, or deleted.
  9863. **
  9864. ** ^The [sqlite3_preupdate_old(D,N,P)] interface writes into P a pointer to
  9865. ** a [protected sqlite3_value] that contains the value of the Nth column of
  9866. ** the table row before it is updated. The N parameter must be between 0
  9867. ** and one less than the number of columns or the behavior will be
  9868. ** undefined. This must only be used within SQLITE_UPDATE and SQLITE_DELETE
  9869. ** preupdate callbacks; if it is used by an SQLITE_INSERT callback then the
  9870. ** behavior is undefined. The [sqlite3_value] that P points to
  9871. ** will be destroyed when the preupdate callback returns.
  9872. **
  9873. ** ^The [sqlite3_preupdate_new(D,N,P)] interface writes into P a pointer to
  9874. ** a [protected sqlite3_value] that contains the value of the Nth column of
  9875. ** the table row after it is updated. The N parameter must be between 0
  9876. ** and one less than the number of columns or the behavior will be
  9877. ** undefined. This must only be used within SQLITE_INSERT and SQLITE_UPDATE
  9878. ** preupdate callbacks; if it is used by an SQLITE_DELETE callback then the
  9879. ** behavior is undefined. The [sqlite3_value] that P points to
  9880. ** will be destroyed when the preupdate callback returns.
  9881. **
  9882. ** ^The [sqlite3_preupdate_depth(D)] interface returns 0 if the preupdate
  9883. ** callback was invoked as a result of a direct insert, update, or delete
  9884. ** operation; or 1 for inserts, updates, or deletes invoked by top-level
  9885. ** triggers; or 2 for changes resulting from triggers called by top-level
  9886. ** triggers; and so forth.
  9887. **
  9888. ** See also: [sqlite3_update_hook()]
  9889. */
  9890. #if defined(SQLITE_ENABLE_PREUPDATE_HOOK)
  9891. SQLITE_API void *sqlite3_preupdate_hook(
  9892. sqlite3 *db,
  9893. void(*xPreUpdate)(
  9894. void *pCtx, /* Copy of third arg to preupdate_hook() */
  9895. sqlite3 *db, /* Database handle */
  9896. int op, /* SQLITE_UPDATE, DELETE or INSERT */
  9897. char const *zDb, /* Database name */
  9898. char const *zName, /* Table name */
  9899. sqlite3_int64 iKey1, /* Rowid of row about to be deleted/updated */
  9900. sqlite3_int64 iKey2 /* New rowid value (for a rowid UPDATE) */
  9901. ),
  9902. void*
  9903. );
  9904. SQLITE_API int sqlite3_preupdate_old(sqlite3 *, int, sqlite3_value **);
  9905. SQLITE_API int sqlite3_preupdate_count(sqlite3 *);
  9906. SQLITE_API int sqlite3_preupdate_depth(sqlite3 *);
  9907. SQLITE_API int sqlite3_preupdate_new(sqlite3 *, int, sqlite3_value **);
  9908. #endif
  9909. /*
  9910. ** CAPI3REF: Low-level system error code
  9911. **
  9912. ** ^Attempt to return the underlying operating system error code or error
  9913. ** number that caused the most recent I/O error or failure to open a file.
  9914. ** The return value is OS-dependent. For example, on unix systems, after
  9915. ** [sqlite3_open_v2()] returns [SQLITE_CANTOPEN], this interface could be
  9916. ** called to get back the underlying "errno" that caused the problem, such
  9917. ** as ENOSPC, EAUTH, EISDIR, and so forth.
  9918. */
  9919. SQLITE_API int sqlite3_system_errno(sqlite3*);
  9920. /*
  9921. ** CAPI3REF: Database Snapshot
  9922. ** KEYWORDS: {snapshot} {sqlite3_snapshot}
  9923. **
  9924. ** An instance of the snapshot object records the state of a [WAL mode]
  9925. ** database for some specific point in history.
  9926. **
  9927. ** In [WAL mode], multiple [database connections] that are open on the
  9928. ** same database file can each be reading a different historical version
  9929. ** of the database file. When a [database connection] begins a read
  9930. ** transaction, that connection sees an unchanging copy of the database
  9931. ** as it existed for the point in time when the transaction first started.
  9932. ** Subsequent changes to the database from other connections are not seen
  9933. ** by the reader until a new read transaction is started.
  9934. **
  9935. ** The sqlite3_snapshot object records state information about an historical
  9936. ** version of the database file so that it is possible to later open a new read
  9937. ** transaction that sees that historical version of the database rather than
  9938. ** the most recent version.
  9939. */
  9940. typedef struct sqlite3_snapshot {
  9941. unsigned char hidden[48];
  9942. } sqlite3_snapshot;
  9943. /*
  9944. ** CAPI3REF: Record A Database Snapshot
  9945. ** CONSTRUCTOR: sqlite3_snapshot
  9946. **
  9947. ** ^The [sqlite3_snapshot_get(D,S,P)] interface attempts to make a
  9948. ** new [sqlite3_snapshot] object that records the current state of
  9949. ** schema S in database connection D. ^On success, the
  9950. ** [sqlite3_snapshot_get(D,S,P)] interface writes a pointer to the newly
  9951. ** created [sqlite3_snapshot] object into *P and returns SQLITE_OK.
  9952. ** If there is not already a read-transaction open on schema S when
  9953. ** this function is called, one is opened automatically.
  9954. **
  9955. ** The following must be true for this function to succeed. If any of
  9956. ** the following statements are false when sqlite3_snapshot_get() is
  9957. ** called, SQLITE_ERROR is returned. The final value of *P is undefined
  9958. ** in this case.
  9959. **
  9960. ** <ul>
  9961. ** <li> The database handle must not be in [autocommit mode].
  9962. **
  9963. ** <li> Schema S of [database connection] D must be a [WAL mode] database.
  9964. **
  9965. ** <li> There must not be a write transaction open on schema S of database
  9966. ** connection D.
  9967. **
  9968. ** <li> One or more transactions must have been written to the current wal
  9969. ** file since it was created on disk (by any connection). This means
  9970. ** that a snapshot cannot be taken on a wal mode database with no wal
  9971. ** file immediately after it is first opened. At least one transaction
  9972. ** must be written to it first.
  9973. ** </ul>
  9974. **
  9975. ** This function may also return SQLITE_NOMEM. If it is called with the
  9976. ** database handle in autocommit mode but fails for some other reason,
  9977. ** whether or not a read transaction is opened on schema S is undefined.
  9978. **
  9979. ** The [sqlite3_snapshot] object returned from a successful call to
  9980. ** [sqlite3_snapshot_get()] must be freed using [sqlite3_snapshot_free()]
  9981. ** to avoid a memory leak.
  9982. **
  9983. ** The [sqlite3_snapshot_get()] interface is only available when the
  9984. ** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used.
  9985. */
  9986. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_get(
  9987. sqlite3 *db,
  9988. const char *zSchema,
  9989. sqlite3_snapshot **ppSnapshot
  9990. );
  9991. /*
  9992. ** CAPI3REF: Start a read transaction on an historical snapshot
  9993. ** METHOD: sqlite3_snapshot
  9994. **
  9995. ** ^The [sqlite3_snapshot_open(D,S,P)] interface either starts a new read
  9996. ** transaction or upgrades an existing one for schema S of
  9997. ** [database connection] D such that the read transaction refers to
  9998. ** historical [snapshot] P, rather than the most recent change to the
  9999. ** database. ^The [sqlite3_snapshot_open()] interface returns SQLITE_OK
  10000. ** on success or an appropriate [error code] if it fails.
  10001. **
  10002. ** ^In order to succeed, the database connection must not be in
  10003. ** [autocommit mode] when [sqlite3_snapshot_open(D,S,P)] is called. If there
  10004. ** is already a read transaction open on schema S, then the database handle
  10005. ** must have no active statements (SELECT statements that have been passed
  10006. ** to sqlite3_step() but not sqlite3_reset() or sqlite3_finalize()).
  10007. ** SQLITE_ERROR is returned if either of these conditions is violated, or
  10008. ** if schema S does not exist, or if the snapshot object is invalid.
  10009. **
  10010. ** ^A call to sqlite3_snapshot_open() will fail to open if the specified
  10011. ** snapshot has been overwritten by a [checkpoint]. In this case
  10012. ** SQLITE_ERROR_SNAPSHOT is returned.
  10013. **
  10014. ** If there is already a read transaction open when this function is
  10015. ** invoked, then the same read transaction remains open (on the same
  10016. ** database snapshot) if SQLITE_ERROR, SQLITE_BUSY or SQLITE_ERROR_SNAPSHOT
  10017. ** is returned. If another error code - for example SQLITE_PROTOCOL or an
  10018. ** SQLITE_IOERR error code - is returned, then the final state of the
  10019. ** read transaction is undefined. If SQLITE_OK is returned, then the
  10020. ** read transaction is now open on database snapshot P.
  10021. **
  10022. ** ^(A call to [sqlite3_snapshot_open(D,S,P)] will fail if the
  10023. ** database connection D does not know that the database file for
  10024. ** schema S is in [WAL mode]. A database connection might not know
  10025. ** that the database file is in [WAL mode] if there has been no prior
  10026. ** I/O on that database connection, or if the database entered [WAL mode]
  10027. ** after the most recent I/O on the database connection.)^
  10028. ** (Hint: Run "[PRAGMA application_id]" against a newly opened
  10029. ** database connection in order to make it ready to use snapshots.)
  10030. **
  10031. ** The [sqlite3_snapshot_open()] interface is only available when the
  10032. ** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used.
  10033. */
  10034. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_open(
  10035. sqlite3 *db,
  10036. const char *zSchema,
  10037. sqlite3_snapshot *pSnapshot
  10038. );
  10039. /*
  10040. ** CAPI3REF: Destroy a snapshot
  10041. ** DESTRUCTOR: sqlite3_snapshot
  10042. **
  10043. ** ^The [sqlite3_snapshot_free(P)] interface destroys [sqlite3_snapshot] P.
  10044. ** The application must eventually free every [sqlite3_snapshot] object
  10045. ** using this routine to avoid a memory leak.
  10046. **
  10047. ** The [sqlite3_snapshot_free()] interface is only available when the
  10048. ** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used.
  10049. */
  10050. SQLITE_API SQLITE_EXPERIMENTAL void sqlite3_snapshot_free(sqlite3_snapshot*);
  10051. /*
  10052. ** CAPI3REF: Compare the ages of two snapshot handles.
  10053. ** METHOD: sqlite3_snapshot
  10054. **
  10055. ** The sqlite3_snapshot_cmp(P1, P2) interface is used to compare the ages
  10056. ** of two valid snapshot handles.
  10057. **
  10058. ** If the two snapshot handles are not associated with the same database
  10059. ** file, the result of the comparison is undefined.
  10060. **
  10061. ** Additionally, the result of the comparison is only valid if both of the
  10062. ** snapshot handles were obtained by calling sqlite3_snapshot_get() since the
  10063. ** last time the wal file was deleted. The wal file is deleted when the
  10064. ** database is changed back to rollback mode or when the number of database
  10065. ** clients drops to zero. If either snapshot handle was obtained before the
  10066. ** wal file was last deleted, the value returned by this function
  10067. ** is undefined.
  10068. **
  10069. ** Otherwise, this API returns a negative value if P1 refers to an older
  10070. ** snapshot than P2, zero if the two handles refer to the same database
  10071. ** snapshot, and a positive value if P1 is a newer snapshot than P2.
  10072. **
  10073. ** This interface is only available if SQLite is compiled with the
  10074. ** [SQLITE_ENABLE_SNAPSHOT] option.
  10075. */
  10076. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_cmp(
  10077. sqlite3_snapshot *p1,
  10078. sqlite3_snapshot *p2
  10079. );
  10080. /*
  10081. ** CAPI3REF: Recover snapshots from a wal file
  10082. ** METHOD: sqlite3_snapshot
  10083. **
  10084. ** If a [WAL file] remains on disk after all database connections close
  10085. ** (either through the use of the [SQLITE_FCNTL_PERSIST_WAL] [file control]
  10086. ** or because the last process to have the database opened exited without
  10087. ** calling [sqlite3_close()]) and a new connection is subsequently opened
  10088. ** on that database and [WAL file], the [sqlite3_snapshot_open()] interface
  10089. ** will only be able to open the last transaction added to the WAL file
  10090. ** even though the WAL file contains other valid transactions.
  10091. **
  10092. ** This function attempts to scan the WAL file associated with database zDb
  10093. ** of database handle db and make all valid snapshots available to
  10094. ** sqlite3_snapshot_open(). It is an error if there is already a read
  10095. ** transaction open on the database, or if the database is not a WAL mode
  10096. ** database.
  10097. **
  10098. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  10099. **
  10100. ** This interface is only available if SQLite is compiled with the
  10101. ** [SQLITE_ENABLE_SNAPSHOT] option.
  10102. */
  10103. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb);
  10104. /*
  10105. ** CAPI3REF: Serialize a database
  10106. **
  10107. ** The sqlite3_serialize(D,S,P,F) interface returns a pointer to memory
  10108. ** that is a serialization of the S database on [database connection] D.
  10109. ** If P is not a NULL pointer, then the size of the database in bytes
  10110. ** is written into *P.
  10111. **
  10112. ** For an ordinary on-disk database file, the serialization is just a
  10113. ** copy of the disk file. For an in-memory database or a "TEMP" database,
  10114. ** the serialization is the same sequence of bytes which would be written
  10115. ** to disk if that database where backed up to disk.
  10116. **
  10117. ** The usual case is that sqlite3_serialize() copies the serialization of
  10118. ** the database into memory obtained from [sqlite3_malloc64()] and returns
  10119. ** a pointer to that memory. The caller is responsible for freeing the
  10120. ** returned value to avoid a memory leak. However, if the F argument
  10121. ** contains the SQLITE_SERIALIZE_NOCOPY bit, then no memory allocations
  10122. ** are made, and the sqlite3_serialize() function will return a pointer
  10123. ** to the contiguous memory representation of the database that SQLite
  10124. ** is currently using for that database, or NULL if the no such contiguous
  10125. ** memory representation of the database exists. A contiguous memory
  10126. ** representation of the database will usually only exist if there has
  10127. ** been a prior call to [sqlite3_deserialize(D,S,...)] with the same
  10128. ** values of D and S.
  10129. ** The size of the database is written into *P even if the
  10130. ** SQLITE_SERIALIZE_NOCOPY bit is set but no contiguous copy
  10131. ** of the database exists.
  10132. **
  10133. ** A call to sqlite3_serialize(D,S,P,F) might return NULL even if the
  10134. ** SQLITE_SERIALIZE_NOCOPY bit is omitted from argument F if a memory
  10135. ** allocation error occurs.
  10136. **
  10137. ** This interface is only available if SQLite is compiled with the
  10138. ** [SQLITE_ENABLE_DESERIALIZE] option.
  10139. */
  10140. SQLITE_API unsigned char *sqlite3_serialize(
  10141. sqlite3 *db, /* The database connection */
  10142. const char *zSchema, /* Which DB to serialize. ex: "main", "temp", ... */
  10143. sqlite3_int64 *piSize, /* Write size of the DB here, if not NULL */
  10144. unsigned int mFlags /* Zero or more SQLITE_SERIALIZE_* flags */
  10145. );
  10146. /*
  10147. ** CAPI3REF: Flags for sqlite3_serialize
  10148. **
  10149. ** Zero or more of the following constants can be OR-ed together for
  10150. ** the F argument to [sqlite3_serialize(D,S,P,F)].
  10151. **
  10152. ** SQLITE_SERIALIZE_NOCOPY means that [sqlite3_serialize()] will return
  10153. ** a pointer to contiguous in-memory database that it is currently using,
  10154. ** without making a copy of the database. If SQLite is not currently using
  10155. ** a contiguous in-memory database, then this option causes
  10156. ** [sqlite3_serialize()] to return a NULL pointer. SQLite will only be
  10157. ** using a contiguous in-memory database if it has been initialized by a
  10158. ** prior call to [sqlite3_deserialize()].
  10159. */
  10160. #define SQLITE_SERIALIZE_NOCOPY 0x001 /* Do no memory allocations */
  10161. /*
  10162. ** CAPI3REF: Deserialize a database
  10163. **
  10164. ** The sqlite3_deserialize(D,S,P,N,M,F) interface causes the
  10165. ** [database connection] D to disconnect from database S and then
  10166. ** reopen S as an in-memory database based on the serialization contained
  10167. ** in P. The serialized database P is N bytes in size. M is the size of
  10168. ** the buffer P, which might be larger than N. If M is larger than N, and
  10169. ** the SQLITE_DESERIALIZE_READONLY bit is not set in F, then SQLite is
  10170. ** permitted to add content to the in-memory database as long as the total
  10171. ** size does not exceed M bytes.
  10172. **
  10173. ** If the SQLITE_DESERIALIZE_FREEONCLOSE bit is set in F, then SQLite will
  10174. ** invoke sqlite3_free() on the serialization buffer when the database
  10175. ** connection closes. If the SQLITE_DESERIALIZE_RESIZEABLE bit is set, then
  10176. ** SQLite will try to increase the buffer size using sqlite3_realloc64()
  10177. ** if writes on the database cause it to grow larger than M bytes.
  10178. **
  10179. ** The sqlite3_deserialize() interface will fail with SQLITE_BUSY if the
  10180. ** database is currently in a read transaction or is involved in a backup
  10181. ** operation.
  10182. **
  10183. ** If sqlite3_deserialize(D,S,P,N,M,F) fails for any reason and if the
  10184. ** SQLITE_DESERIALIZE_FREEONCLOSE bit is set in argument F, then
  10185. ** [sqlite3_free()] is invoked on argument P prior to returning.
  10186. **
  10187. ** This interface is only available if SQLite is compiled with the
  10188. ** [SQLITE_ENABLE_DESERIALIZE] option.
  10189. */
  10190. SQLITE_API int sqlite3_deserialize(
  10191. sqlite3 *db, /* The database connection */
  10192. const char *zSchema, /* Which DB to reopen with the deserialization */
  10193. unsigned char *pData, /* The serialized database content */
  10194. sqlite3_int64 szDb, /* Number bytes in the deserialization */
  10195. sqlite3_int64 szBuf, /* Total size of buffer pData[] */
  10196. unsigned mFlags /* Zero or more SQLITE_DESERIALIZE_* flags */
  10197. );
  10198. /*
  10199. ** CAPI3REF: Flags for sqlite3_deserialize()
  10200. **
  10201. ** The following are allowed values for 6th argument (the F argument) to
  10202. ** the [sqlite3_deserialize(D,S,P,N,M,F)] interface.
  10203. **
  10204. ** The SQLITE_DESERIALIZE_FREEONCLOSE means that the database serialization
  10205. ** in the P argument is held in memory obtained from [sqlite3_malloc64()]
  10206. ** and that SQLite should take ownership of this memory and automatically
  10207. ** free it when it has finished using it. Without this flag, the caller
  10208. ** is responsible for freeing any dynamically allocated memory.
  10209. **
  10210. ** The SQLITE_DESERIALIZE_RESIZEABLE flag means that SQLite is allowed to
  10211. ** grow the size of the database using calls to [sqlite3_realloc64()]. This
  10212. ** flag should only be used if SQLITE_DESERIALIZE_FREEONCLOSE is also used.
  10213. ** Without this flag, the deserialized database cannot increase in size beyond
  10214. ** the number of bytes specified by the M parameter.
  10215. **
  10216. ** The SQLITE_DESERIALIZE_READONLY flag means that the deserialized database
  10217. ** should be treated as read-only.
  10218. */
  10219. #define SQLITE_DESERIALIZE_FREEONCLOSE 1 /* Call sqlite3_free() on close */
  10220. #define SQLITE_DESERIALIZE_RESIZEABLE 2 /* Resize using sqlite3_realloc64() */
  10221. #define SQLITE_DESERIALIZE_READONLY 4 /* Database is read-only */
  10222. /*
  10223. ** Undo the hack that converts floating point types to integer for
  10224. ** builds on processors without floating point support.
  10225. */
  10226. #ifdef SQLITE_OMIT_FLOATING_POINT
  10227. # undef double
  10228. #endif
  10229. #if 0
  10230. } /* End of the 'extern "C"' block */
  10231. #endif
  10232. #endif /* SQLITE3_H */
  10233. /******** Begin file sqlite3rtree.h *********/
  10234. /*
  10235. ** 2010 August 30
  10236. **
  10237. ** The author disclaims copyright to this source code. In place of
  10238. ** a legal notice, here is a blessing:
  10239. **
  10240. ** May you do good and not evil.
  10241. ** May you find forgiveness for yourself and forgive others.
  10242. ** May you share freely, never taking more than you give.
  10243. **
  10244. *************************************************************************
  10245. */
  10246. #ifndef _SQLITE3RTREE_H_
  10247. #define _SQLITE3RTREE_H_
  10248. #if 0
  10249. extern "C" {
  10250. #endif
  10251. typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
  10252. typedef struct sqlite3_rtree_query_info sqlite3_rtree_query_info;
  10253. /* The double-precision datatype used by RTree depends on the
  10254. ** SQLITE_RTREE_INT_ONLY compile-time option.
  10255. */
  10256. #ifdef SQLITE_RTREE_INT_ONLY
  10257. typedef sqlite3_int64 sqlite3_rtree_dbl;
  10258. #else
  10259. typedef double sqlite3_rtree_dbl;
  10260. #endif
  10261. /*
  10262. ** Register a geometry callback named zGeom that can be used as part of an
  10263. ** R-Tree geometry query as follows:
  10264. **
  10265. ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
  10266. */
  10267. SQLITE_API int sqlite3_rtree_geometry_callback(
  10268. sqlite3 *db,
  10269. const char *zGeom,
  10270. int (*xGeom)(sqlite3_rtree_geometry*, int, sqlite3_rtree_dbl*,int*),
  10271. void *pContext
  10272. );
  10273. /*
  10274. ** A pointer to a structure of the following type is passed as the first
  10275. ** argument to callbacks registered using rtree_geometry_callback().
  10276. */
  10277. struct sqlite3_rtree_geometry {
  10278. void *pContext; /* Copy of pContext passed to s_r_g_c() */
  10279. int nParam; /* Size of array aParam[] */
  10280. sqlite3_rtree_dbl *aParam; /* Parameters passed to SQL geom function */
  10281. void *pUser; /* Callback implementation user data */
  10282. void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */
  10283. };
  10284. /*
  10285. ** Register a 2nd-generation geometry callback named zScore that can be
  10286. ** used as part of an R-Tree geometry query as follows:
  10287. **
  10288. ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zQueryFunc(... params ...)
  10289. */
  10290. SQLITE_API int sqlite3_rtree_query_callback(
  10291. sqlite3 *db,
  10292. const char *zQueryFunc,
  10293. int (*xQueryFunc)(sqlite3_rtree_query_info*),
  10294. void *pContext,
  10295. void (*xDestructor)(void*)
  10296. );
  10297. /*
  10298. ** A pointer to a structure of the following type is passed as the
  10299. ** argument to scored geometry callback registered using
  10300. ** sqlite3_rtree_query_callback().
  10301. **
  10302. ** Note that the first 5 fields of this structure are identical to
  10303. ** sqlite3_rtree_geometry. This structure is a subclass of
  10304. ** sqlite3_rtree_geometry.
  10305. */
  10306. struct sqlite3_rtree_query_info {
  10307. void *pContext; /* pContext from when function registered */
  10308. int nParam; /* Number of function parameters */
  10309. sqlite3_rtree_dbl *aParam; /* value of function parameters */
  10310. void *pUser; /* callback can use this, if desired */
  10311. void (*xDelUser)(void*); /* function to free pUser */
  10312. sqlite3_rtree_dbl *aCoord; /* Coordinates of node or entry to check */
  10313. unsigned int *anQueue; /* Number of pending entries in the queue */
  10314. int nCoord; /* Number of coordinates */
  10315. int iLevel; /* Level of current node or entry */
  10316. int mxLevel; /* The largest iLevel value in the tree */
  10317. sqlite3_int64 iRowid; /* Rowid for current entry */
  10318. sqlite3_rtree_dbl rParentScore; /* Score of parent node */
  10319. int eParentWithin; /* Visibility of parent node */
  10320. int eWithin; /* OUT: Visibility */
  10321. sqlite3_rtree_dbl rScore; /* OUT: Write the score here */
  10322. /* The following fields are only available in 3.8.11 and later */
  10323. sqlite3_value **apSqlParam; /* Original SQL values of parameters */
  10324. };
  10325. /*
  10326. ** Allowed values for sqlite3_rtree_query.eWithin and .eParentWithin.
  10327. */
  10328. #define NOT_WITHIN 0 /* Object completely outside of query region */
  10329. #define PARTLY_WITHIN 1 /* Object partially overlaps query region */
  10330. #define FULLY_WITHIN 2 /* Object fully contained within query region */
  10331. #if 0
  10332. } /* end of the 'extern "C"' block */
  10333. #endif
  10334. #endif /* ifndef _SQLITE3RTREE_H_ */
  10335. /******** End of sqlite3rtree.h *********/
  10336. /******** Begin file sqlite3session.h *********/
  10337. #if !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION)
  10338. #define __SQLITESESSION_H_ 1
  10339. /*
  10340. ** Make sure we can call this stuff from C++.
  10341. */
  10342. #if 0
  10343. extern "C" {
  10344. #endif
  10345. /*
  10346. ** CAPI3REF: Session Object Handle
  10347. **
  10348. ** An instance of this object is a [session] that can be used to
  10349. ** record changes to a database.
  10350. */
  10351. typedef struct sqlite3_session sqlite3_session;
  10352. /*
  10353. ** CAPI3REF: Changeset Iterator Handle
  10354. **
  10355. ** An instance of this object acts as a cursor for iterating
  10356. ** over the elements of a [changeset] or [patchset].
  10357. */
  10358. typedef struct sqlite3_changeset_iter sqlite3_changeset_iter;
  10359. /*
  10360. ** CAPI3REF: Create A New Session Object
  10361. ** CONSTRUCTOR: sqlite3_session
  10362. **
  10363. ** Create a new session object attached to database handle db. If successful,
  10364. ** a pointer to the new object is written to *ppSession and SQLITE_OK is
  10365. ** returned. If an error occurs, *ppSession is set to NULL and an SQLite
  10366. ** error code (e.g. SQLITE_NOMEM) is returned.
  10367. **
  10368. ** It is possible to create multiple session objects attached to a single
  10369. ** database handle.
  10370. **
  10371. ** Session objects created using this function should be deleted using the
  10372. ** [sqlite3session_delete()] function before the database handle that they
  10373. ** are attached to is itself closed. If the database handle is closed before
  10374. ** the session object is deleted, then the results of calling any session
  10375. ** module function, including [sqlite3session_delete()] on the session object
  10376. ** are undefined.
  10377. **
  10378. ** Because the session module uses the [sqlite3_preupdate_hook()] API, it
  10379. ** is not possible for an application to register a pre-update hook on a
  10380. ** database handle that has one or more session objects attached. Nor is
  10381. ** it possible to create a session object attached to a database handle for
  10382. ** which a pre-update hook is already defined. The results of attempting
  10383. ** either of these things are undefined.
  10384. **
  10385. ** The session object will be used to create changesets for tables in
  10386. ** database zDb, where zDb is either "main", or "temp", or the name of an
  10387. ** attached database. It is not an error if database zDb is not attached
  10388. ** to the database when the session object is created.
  10389. */
  10390. SQLITE_API int sqlite3session_create(
  10391. sqlite3 *db, /* Database handle */
  10392. const char *zDb, /* Name of db (e.g. "main") */
  10393. sqlite3_session **ppSession /* OUT: New session object */
  10394. );
  10395. /*
  10396. ** CAPI3REF: Delete A Session Object
  10397. ** DESTRUCTOR: sqlite3_session
  10398. **
  10399. ** Delete a session object previously allocated using
  10400. ** [sqlite3session_create()]. Once a session object has been deleted, the
  10401. ** results of attempting to use pSession with any other session module
  10402. ** function are undefined.
  10403. **
  10404. ** Session objects must be deleted before the database handle to which they
  10405. ** are attached is closed. Refer to the documentation for
  10406. ** [sqlite3session_create()] for details.
  10407. */
  10408. SQLITE_API void sqlite3session_delete(sqlite3_session *pSession);
  10409. /*
  10410. ** CAPI3REF: Enable Or Disable A Session Object
  10411. ** METHOD: sqlite3_session
  10412. **
  10413. ** Enable or disable the recording of changes by a session object. When
  10414. ** enabled, a session object records changes made to the database. When
  10415. ** disabled - it does not. A newly created session object is enabled.
  10416. ** Refer to the documentation for [sqlite3session_changeset()] for further
  10417. ** details regarding how enabling and disabling a session object affects
  10418. ** the eventual changesets.
  10419. **
  10420. ** Passing zero to this function disables the session. Passing a value
  10421. ** greater than zero enables it. Passing a value less than zero is a
  10422. ** no-op, and may be used to query the current state of the session.
  10423. **
  10424. ** The return value indicates the final state of the session object: 0 if
  10425. ** the session is disabled, or 1 if it is enabled.
  10426. */
  10427. SQLITE_API int sqlite3session_enable(sqlite3_session *pSession, int bEnable);
  10428. /*
  10429. ** CAPI3REF: Set Or Clear the Indirect Change Flag
  10430. ** METHOD: sqlite3_session
  10431. **
  10432. ** Each change recorded by a session object is marked as either direct or
  10433. ** indirect. A change is marked as indirect if either:
  10434. **
  10435. ** <ul>
  10436. ** <li> The session object "indirect" flag is set when the change is
  10437. ** made, or
  10438. ** <li> The change is made by an SQL trigger or foreign key action
  10439. ** instead of directly as a result of a users SQL statement.
  10440. ** </ul>
  10441. **
  10442. ** If a single row is affected by more than one operation within a session,
  10443. ** then the change is considered indirect if all operations meet the criteria
  10444. ** for an indirect change above, or direct otherwise.
  10445. **
  10446. ** This function is used to set, clear or query the session object indirect
  10447. ** flag. If the second argument passed to this function is zero, then the
  10448. ** indirect flag is cleared. If it is greater than zero, the indirect flag
  10449. ** is set. Passing a value less than zero does not modify the current value
  10450. ** of the indirect flag, and may be used to query the current state of the
  10451. ** indirect flag for the specified session object.
  10452. **
  10453. ** The return value indicates the final state of the indirect flag: 0 if
  10454. ** it is clear, or 1 if it is set.
  10455. */
  10456. SQLITE_API int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect);
  10457. /*
  10458. ** CAPI3REF: Attach A Table To A Session Object
  10459. ** METHOD: sqlite3_session
  10460. **
  10461. ** If argument zTab is not NULL, then it is the name of a table to attach
  10462. ** to the session object passed as the first argument. All subsequent changes
  10463. ** made to the table while the session object is enabled will be recorded. See
  10464. ** documentation for [sqlite3session_changeset()] for further details.
  10465. **
  10466. ** Or, if argument zTab is NULL, then changes are recorded for all tables
  10467. ** in the database. If additional tables are added to the database (by
  10468. ** executing "CREATE TABLE" statements) after this call is made, changes for
  10469. ** the new tables are also recorded.
  10470. **
  10471. ** Changes can only be recorded for tables that have a PRIMARY KEY explicitly
  10472. ** defined as part of their CREATE TABLE statement. It does not matter if the
  10473. ** PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias) or not. The PRIMARY
  10474. ** KEY may consist of a single column, or may be a composite key.
  10475. **
  10476. ** It is not an error if the named table does not exist in the database. Nor
  10477. ** is it an error if the named table does not have a PRIMARY KEY. However,
  10478. ** no changes will be recorded in either of these scenarios.
  10479. **
  10480. ** Changes are not recorded for individual rows that have NULL values stored
  10481. ** in one or more of their PRIMARY KEY columns.
  10482. **
  10483. ** SQLITE_OK is returned if the call completes without error. Or, if an error
  10484. ** occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
  10485. **
  10486. ** <h3>Special sqlite_stat1 Handling</h3>
  10487. **
  10488. ** As of SQLite version 3.22.0, the "sqlite_stat1" table is an exception to
  10489. ** some of the rules above. In SQLite, the schema of sqlite_stat1 is:
  10490. ** <pre>
  10491. ** &nbsp; CREATE TABLE sqlite_stat1(tbl,idx,stat)
  10492. ** </pre>
  10493. **
  10494. ** Even though sqlite_stat1 does not have a PRIMARY KEY, changes are
  10495. ** recorded for it as if the PRIMARY KEY is (tbl,idx). Additionally, changes
  10496. ** are recorded for rows for which (idx IS NULL) is true. However, for such
  10497. ** rows a zero-length blob (SQL value X'') is stored in the changeset or
  10498. ** patchset instead of a NULL value. This allows such changesets to be
  10499. ** manipulated by legacy implementations of sqlite3changeset_invert(),
  10500. ** concat() and similar.
  10501. **
  10502. ** The sqlite3changeset_apply() function automatically converts the
  10503. ** zero-length blob back to a NULL value when updating the sqlite_stat1
  10504. ** table. However, if the application calls sqlite3changeset_new(),
  10505. ** sqlite3changeset_old() or sqlite3changeset_conflict on a changeset
  10506. ** iterator directly (including on a changeset iterator passed to a
  10507. ** conflict-handler callback) then the X'' value is returned. The application
  10508. ** must translate X'' to NULL itself if required.
  10509. **
  10510. ** Legacy (older than 3.22.0) versions of the sessions module cannot capture
  10511. ** changes made to the sqlite_stat1 table. Legacy versions of the
  10512. ** sqlite3changeset_apply() function silently ignore any modifications to the
  10513. ** sqlite_stat1 table that are part of a changeset or patchset.
  10514. */
  10515. SQLITE_API int sqlite3session_attach(
  10516. sqlite3_session *pSession, /* Session object */
  10517. const char *zTab /* Table name */
  10518. );
  10519. /*
  10520. ** CAPI3REF: Set a table filter on a Session Object.
  10521. ** METHOD: sqlite3_session
  10522. **
  10523. ** The second argument (xFilter) is the "filter callback". For changes to rows
  10524. ** in tables that are not attached to the Session object, the filter is called
  10525. ** to determine whether changes to the table's rows should be tracked or not.
  10526. ** If xFilter returns 0, changes is not tracked. Note that once a table is
  10527. ** attached, xFilter will not be called again.
  10528. */
  10529. SQLITE_API void sqlite3session_table_filter(
  10530. sqlite3_session *pSession, /* Session object */
  10531. int(*xFilter)(
  10532. void *pCtx, /* Copy of third arg to _filter_table() */
  10533. const char *zTab /* Table name */
  10534. ),
  10535. void *pCtx /* First argument passed to xFilter */
  10536. );
  10537. /*
  10538. ** CAPI3REF: Generate A Changeset From A Session Object
  10539. ** METHOD: sqlite3_session
  10540. **
  10541. ** Obtain a changeset containing changes to the tables attached to the
  10542. ** session object passed as the first argument. If successful,
  10543. ** set *ppChangeset to point to a buffer containing the changeset
  10544. ** and *pnChangeset to the size of the changeset in bytes before returning
  10545. ** SQLITE_OK. If an error occurs, set both *ppChangeset and *pnChangeset to
  10546. ** zero and return an SQLite error code.
  10547. **
  10548. ** A changeset consists of zero or more INSERT, UPDATE and/or DELETE changes,
  10549. ** each representing a change to a single row of an attached table. An INSERT
  10550. ** change contains the values of each field of a new database row. A DELETE
  10551. ** contains the original values of each field of a deleted database row. An
  10552. ** UPDATE change contains the original values of each field of an updated
  10553. ** database row along with the updated values for each updated non-primary-key
  10554. ** column. It is not possible for an UPDATE change to represent a change that
  10555. ** modifies the values of primary key columns. If such a change is made, it
  10556. ** is represented in a changeset as a DELETE followed by an INSERT.
  10557. **
  10558. ** Changes are not recorded for rows that have NULL values stored in one or
  10559. ** more of their PRIMARY KEY columns. If such a row is inserted or deleted,
  10560. ** no corresponding change is present in the changesets returned by this
  10561. ** function. If an existing row with one or more NULL values stored in
  10562. ** PRIMARY KEY columns is updated so that all PRIMARY KEY columns are non-NULL,
  10563. ** only an INSERT is appears in the changeset. Similarly, if an existing row
  10564. ** with non-NULL PRIMARY KEY values is updated so that one or more of its
  10565. ** PRIMARY KEY columns are set to NULL, the resulting changeset contains a
  10566. ** DELETE change only.
  10567. **
  10568. ** The contents of a changeset may be traversed using an iterator created
  10569. ** using the [sqlite3changeset_start()] API. A changeset may be applied to
  10570. ** a database with a compatible schema using the [sqlite3changeset_apply()]
  10571. ** API.
  10572. **
  10573. ** Within a changeset generated by this function, all changes related to a
  10574. ** single table are grouped together. In other words, when iterating through
  10575. ** a changeset or when applying a changeset to a database, all changes related
  10576. ** to a single table are processed before moving on to the next table. Tables
  10577. ** are sorted in the same order in which they were attached (or auto-attached)
  10578. ** to the sqlite3_session object. The order in which the changes related to
  10579. ** a single table are stored is undefined.
  10580. **
  10581. ** Following a successful call to this function, it is the responsibility of
  10582. ** the caller to eventually free the buffer that *ppChangeset points to using
  10583. ** [sqlite3_free()].
  10584. **
  10585. ** <h3>Changeset Generation</h3>
  10586. **
  10587. ** Once a table has been attached to a session object, the session object
  10588. ** records the primary key values of all new rows inserted into the table.
  10589. ** It also records the original primary key and other column values of any
  10590. ** deleted or updated rows. For each unique primary key value, data is only
  10591. ** recorded once - the first time a row with said primary key is inserted,
  10592. ** updated or deleted in the lifetime of the session.
  10593. **
  10594. ** There is one exception to the previous paragraph: when a row is inserted,
  10595. ** updated or deleted, if one or more of its primary key columns contain a
  10596. ** NULL value, no record of the change is made.
  10597. **
  10598. ** The session object therefore accumulates two types of records - those
  10599. ** that consist of primary key values only (created when the user inserts
  10600. ** a new record) and those that consist of the primary key values and the
  10601. ** original values of other table columns (created when the users deletes
  10602. ** or updates a record).
  10603. **
  10604. ** When this function is called, the requested changeset is created using
  10605. ** both the accumulated records and the current contents of the database
  10606. ** file. Specifically:
  10607. **
  10608. ** <ul>
  10609. ** <li> For each record generated by an insert, the database is queried
  10610. ** for a row with a matching primary key. If one is found, an INSERT
  10611. ** change is added to the changeset. If no such row is found, no change
  10612. ** is added to the changeset.
  10613. **
  10614. ** <li> For each record generated by an update or delete, the database is
  10615. ** queried for a row with a matching primary key. If such a row is
  10616. ** found and one or more of the non-primary key fields have been
  10617. ** modified from their original values, an UPDATE change is added to
  10618. ** the changeset. Or, if no such row is found in the table, a DELETE
  10619. ** change is added to the changeset. If there is a row with a matching
  10620. ** primary key in the database, but all fields contain their original
  10621. ** values, no change is added to the changeset.
  10622. ** </ul>
  10623. **
  10624. ** This means, amongst other things, that if a row is inserted and then later
  10625. ** deleted while a session object is active, neither the insert nor the delete
  10626. ** will be present in the changeset. Or if a row is deleted and then later a
  10627. ** row with the same primary key values inserted while a session object is
  10628. ** active, the resulting changeset will contain an UPDATE change instead of
  10629. ** a DELETE and an INSERT.
  10630. **
  10631. ** When a session object is disabled (see the [sqlite3session_enable()] API),
  10632. ** it does not accumulate records when rows are inserted, updated or deleted.
  10633. ** This may appear to have some counter-intuitive effects if a single row
  10634. ** is written to more than once during a session. For example, if a row
  10635. ** is inserted while a session object is enabled, then later deleted while
  10636. ** the same session object is disabled, no INSERT record will appear in the
  10637. ** changeset, even though the delete took place while the session was disabled.
  10638. ** Or, if one field of a row is updated while a session is disabled, and
  10639. ** another field of the same row is updated while the session is enabled, the
  10640. ** resulting changeset will contain an UPDATE change that updates both fields.
  10641. */
  10642. SQLITE_API int sqlite3session_changeset(
  10643. sqlite3_session *pSession, /* Session object */
  10644. int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */
  10645. void **ppChangeset /* OUT: Buffer containing changeset */
  10646. );
  10647. /*
  10648. ** CAPI3REF: Load The Difference Between Tables Into A Session
  10649. ** METHOD: sqlite3_session
  10650. **
  10651. ** If it is not already attached to the session object passed as the first
  10652. ** argument, this function attaches table zTbl in the same manner as the
  10653. ** [sqlite3session_attach()] function. If zTbl does not exist, or if it
  10654. ** does not have a primary key, this function is a no-op (but does not return
  10655. ** an error).
  10656. **
  10657. ** Argument zFromDb must be the name of a database ("main", "temp" etc.)
  10658. ** attached to the same database handle as the session object that contains
  10659. ** a table compatible with the table attached to the session by this function.
  10660. ** A table is considered compatible if it:
  10661. **
  10662. ** <ul>
  10663. ** <li> Has the same name,
  10664. ** <li> Has the same set of columns declared in the same order, and
  10665. ** <li> Has the same PRIMARY KEY definition.
  10666. ** </ul>
  10667. **
  10668. ** If the tables are not compatible, SQLITE_SCHEMA is returned. If the tables
  10669. ** are compatible but do not have any PRIMARY KEY columns, it is not an error
  10670. ** but no changes are added to the session object. As with other session
  10671. ** APIs, tables without PRIMARY KEYs are simply ignored.
  10672. **
  10673. ** This function adds a set of changes to the session object that could be
  10674. ** used to update the table in database zFrom (call this the "from-table")
  10675. ** so that its content is the same as the table attached to the session
  10676. ** object (call this the "to-table"). Specifically:
  10677. **
  10678. ** <ul>
  10679. ** <li> For each row (primary key) that exists in the to-table but not in
  10680. ** the from-table, an INSERT record is added to the session object.
  10681. **
  10682. ** <li> For each row (primary key) that exists in the to-table but not in
  10683. ** the from-table, a DELETE record is added to the session object.
  10684. **
  10685. ** <li> For each row (primary key) that exists in both tables, but features
  10686. ** different non-PK values in each, an UPDATE record is added to the
  10687. ** session.
  10688. ** </ul>
  10689. **
  10690. ** To clarify, if this function is called and then a changeset constructed
  10691. ** using [sqlite3session_changeset()], then after applying that changeset to
  10692. ** database zFrom the contents of the two compatible tables would be
  10693. ** identical.
  10694. **
  10695. ** It an error if database zFrom does not exist or does not contain the
  10696. ** required compatible table.
  10697. **
  10698. ** If the operation successful, SQLITE_OK is returned. Otherwise, an SQLite
  10699. ** error code. In this case, if argument pzErrMsg is not NULL, *pzErrMsg
  10700. ** may be set to point to a buffer containing an English language error
  10701. ** message. It is the responsibility of the caller to free this buffer using
  10702. ** sqlite3_free().
  10703. */
  10704. SQLITE_API int sqlite3session_diff(
  10705. sqlite3_session *pSession,
  10706. const char *zFromDb,
  10707. const char *zTbl,
  10708. char **pzErrMsg
  10709. );
  10710. /*
  10711. ** CAPI3REF: Generate A Patchset From A Session Object
  10712. ** METHOD: sqlite3_session
  10713. **
  10714. ** The differences between a patchset and a changeset are that:
  10715. **
  10716. ** <ul>
  10717. ** <li> DELETE records consist of the primary key fields only. The
  10718. ** original values of other fields are omitted.
  10719. ** <li> The original values of any modified fields are omitted from
  10720. ** UPDATE records.
  10721. ** </ul>
  10722. **
  10723. ** A patchset blob may be used with up to date versions of all
  10724. ** sqlite3changeset_xxx API functions except for sqlite3changeset_invert(),
  10725. ** which returns SQLITE_CORRUPT if it is passed a patchset. Similarly,
  10726. ** attempting to use a patchset blob with old versions of the
  10727. ** sqlite3changeset_xxx APIs also provokes an SQLITE_CORRUPT error.
  10728. **
  10729. ** Because the non-primary key "old.*" fields are omitted, no
  10730. ** SQLITE_CHANGESET_DATA conflicts can be detected or reported if a patchset
  10731. ** is passed to the sqlite3changeset_apply() API. Other conflict types work
  10732. ** in the same way as for changesets.
  10733. **
  10734. ** Changes within a patchset are ordered in the same way as for changesets
  10735. ** generated by the sqlite3session_changeset() function (i.e. all changes for
  10736. ** a single table are grouped together, tables appear in the order in which
  10737. ** they were attached to the session object).
  10738. */
  10739. SQLITE_API int sqlite3session_patchset(
  10740. sqlite3_session *pSession, /* Session object */
  10741. int *pnPatchset, /* OUT: Size of buffer at *ppPatchset */
  10742. void **ppPatchset /* OUT: Buffer containing patchset */
  10743. );
  10744. /*
  10745. ** CAPI3REF: Test if a changeset has recorded any changes.
  10746. **
  10747. ** Return non-zero if no changes to attached tables have been recorded by
  10748. ** the session object passed as the first argument. Otherwise, if one or
  10749. ** more changes have been recorded, return zero.
  10750. **
  10751. ** Even if this function returns zero, it is possible that calling
  10752. ** [sqlite3session_changeset()] on the session handle may still return a
  10753. ** changeset that contains no changes. This can happen when a row in
  10754. ** an attached table is modified and then later on the original values
  10755. ** are restored. However, if this function returns non-zero, then it is
  10756. ** guaranteed that a call to sqlite3session_changeset() will return a
  10757. ** changeset containing zero changes.
  10758. */
  10759. SQLITE_API int sqlite3session_isempty(sqlite3_session *pSession);
  10760. /*
  10761. ** CAPI3REF: Create An Iterator To Traverse A Changeset
  10762. ** CONSTRUCTOR: sqlite3_changeset_iter
  10763. **
  10764. ** Create an iterator used to iterate through the contents of a changeset.
  10765. ** If successful, *pp is set to point to the iterator handle and SQLITE_OK
  10766. ** is returned. Otherwise, if an error occurs, *pp is set to zero and an
  10767. ** SQLite error code is returned.
  10768. **
  10769. ** The following functions can be used to advance and query a changeset
  10770. ** iterator created by this function:
  10771. **
  10772. ** <ul>
  10773. ** <li> [sqlite3changeset_next()]
  10774. ** <li> [sqlite3changeset_op()]
  10775. ** <li> [sqlite3changeset_new()]
  10776. ** <li> [sqlite3changeset_old()]
  10777. ** </ul>
  10778. **
  10779. ** It is the responsibility of the caller to eventually destroy the iterator
  10780. ** by passing it to [sqlite3changeset_finalize()]. The buffer containing the
  10781. ** changeset (pChangeset) must remain valid until after the iterator is
  10782. ** destroyed.
  10783. **
  10784. ** Assuming the changeset blob was created by one of the
  10785. ** [sqlite3session_changeset()], [sqlite3changeset_concat()] or
  10786. ** [sqlite3changeset_invert()] functions, all changes within the changeset
  10787. ** that apply to a single table are grouped together. This means that when
  10788. ** an application iterates through a changeset using an iterator created by
  10789. ** this function, all changes that relate to a single table are visited
  10790. ** consecutively. There is no chance that the iterator will visit a change
  10791. ** the applies to table X, then one for table Y, and then later on visit
  10792. ** another change for table X.
  10793. **
  10794. ** The behavior of sqlite3changeset_start_v2() and its streaming equivalent
  10795. ** may be modified by passing a combination of
  10796. ** [SQLITE_CHANGESETSTART_INVERT | supported flags] as the 4th parameter.
  10797. **
  10798. ** Note that the sqlite3changeset_start_v2() API is still <b>experimental</b>
  10799. ** and therefore subject to change.
  10800. */
  10801. SQLITE_API int sqlite3changeset_start(
  10802. sqlite3_changeset_iter **pp, /* OUT: New changeset iterator handle */
  10803. int nChangeset, /* Size of changeset blob in bytes */
  10804. void *pChangeset /* Pointer to blob containing changeset */
  10805. );
  10806. SQLITE_API int sqlite3changeset_start_v2(
  10807. sqlite3_changeset_iter **pp, /* OUT: New changeset iterator handle */
  10808. int nChangeset, /* Size of changeset blob in bytes */
  10809. void *pChangeset, /* Pointer to blob containing changeset */
  10810. int flags /* SESSION_CHANGESETSTART_* flags */
  10811. );
  10812. /*
  10813. ** CAPI3REF: Flags for sqlite3changeset_start_v2
  10814. **
  10815. ** The following flags may passed via the 4th parameter to
  10816. ** [sqlite3changeset_start_v2] and [sqlite3changeset_start_v2_strm]:
  10817. **
  10818. ** <dt>SQLITE_CHANGESETAPPLY_INVERT <dd>
  10819. ** Invert the changeset while iterating through it. This is equivalent to
  10820. ** inverting a changeset using sqlite3changeset_invert() before applying it.
  10821. ** It is an error to specify this flag with a patchset.
  10822. */
  10823. #define SQLITE_CHANGESETSTART_INVERT 0x0002
  10824. /*
  10825. ** CAPI3REF: Advance A Changeset Iterator
  10826. ** METHOD: sqlite3_changeset_iter
  10827. **
  10828. ** This function may only be used with iterators created by function
  10829. ** [sqlite3changeset_start()]. If it is called on an iterator passed to
  10830. ** a conflict-handler callback by [sqlite3changeset_apply()], SQLITE_MISUSE
  10831. ** is returned and the call has no effect.
  10832. **
  10833. ** Immediately after an iterator is created by sqlite3changeset_start(), it
  10834. ** does not point to any change in the changeset. Assuming the changeset
  10835. ** is not empty, the first call to this function advances the iterator to
  10836. ** point to the first change in the changeset. Each subsequent call advances
  10837. ** the iterator to point to the next change in the changeset (if any). If
  10838. ** no error occurs and the iterator points to a valid change after a call
  10839. ** to sqlite3changeset_next() has advanced it, SQLITE_ROW is returned.
  10840. ** Otherwise, if all changes in the changeset have already been visited,
  10841. ** SQLITE_DONE is returned.
  10842. **
  10843. ** If an error occurs, an SQLite error code is returned. Possible error
  10844. ** codes include SQLITE_CORRUPT (if the changeset buffer is corrupt) or
  10845. ** SQLITE_NOMEM.
  10846. */
  10847. SQLITE_API int sqlite3changeset_next(sqlite3_changeset_iter *pIter);
  10848. /*
  10849. ** CAPI3REF: Obtain The Current Operation From A Changeset Iterator
  10850. ** METHOD: sqlite3_changeset_iter
  10851. **
  10852. ** The pIter argument passed to this function may either be an iterator
  10853. ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
  10854. ** created by [sqlite3changeset_start()]. In the latter case, the most recent
  10855. ** call to [sqlite3changeset_next()] must have returned [SQLITE_ROW]. If this
  10856. ** is not the case, this function returns [SQLITE_MISUSE].
  10857. **
  10858. ** If argument pzTab is not NULL, then *pzTab is set to point to a
  10859. ** nul-terminated utf-8 encoded string containing the name of the table
  10860. ** affected by the current change. The buffer remains valid until either
  10861. ** sqlite3changeset_next() is called on the iterator or until the
  10862. ** conflict-handler function returns. If pnCol is not NULL, then *pnCol is
  10863. ** set to the number of columns in the table affected by the change. If
  10864. ** pbIndirect is not NULL, then *pbIndirect is set to true (1) if the change
  10865. ** is an indirect change, or false (0) otherwise. See the documentation for
  10866. ** [sqlite3session_indirect()] for a description of direct and indirect
  10867. ** changes. Finally, if pOp is not NULL, then *pOp is set to one of
  10868. ** [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE], depending on the
  10869. ** type of change that the iterator currently points to.
  10870. **
  10871. ** If no error occurs, SQLITE_OK is returned. If an error does occur, an
  10872. ** SQLite error code is returned. The values of the output variables may not
  10873. ** be trusted in this case.
  10874. */
  10875. SQLITE_API int sqlite3changeset_op(
  10876. sqlite3_changeset_iter *pIter, /* Iterator object */
  10877. const char **pzTab, /* OUT: Pointer to table name */
  10878. int *pnCol, /* OUT: Number of columns in table */
  10879. int *pOp, /* OUT: SQLITE_INSERT, DELETE or UPDATE */
  10880. int *pbIndirect /* OUT: True for an 'indirect' change */
  10881. );
  10882. /*
  10883. ** CAPI3REF: Obtain The Primary Key Definition Of A Table
  10884. ** METHOD: sqlite3_changeset_iter
  10885. **
  10886. ** For each modified table, a changeset includes the following:
  10887. **
  10888. ** <ul>
  10889. ** <li> The number of columns in the table, and
  10890. ** <li> Which of those columns make up the tables PRIMARY KEY.
  10891. ** </ul>
  10892. **
  10893. ** This function is used to find which columns comprise the PRIMARY KEY of
  10894. ** the table modified by the change that iterator pIter currently points to.
  10895. ** If successful, *pabPK is set to point to an array of nCol entries, where
  10896. ** nCol is the number of columns in the table. Elements of *pabPK are set to
  10897. ** 0x01 if the corresponding column is part of the tables primary key, or
  10898. ** 0x00 if it is not.
  10899. **
  10900. ** If argument pnCol is not NULL, then *pnCol is set to the number of columns
  10901. ** in the table.
  10902. **
  10903. ** If this function is called when the iterator does not point to a valid
  10904. ** entry, SQLITE_MISUSE is returned and the output variables zeroed. Otherwise,
  10905. ** SQLITE_OK is returned and the output variables populated as described
  10906. ** above.
  10907. */
  10908. SQLITE_API int sqlite3changeset_pk(
  10909. sqlite3_changeset_iter *pIter, /* Iterator object */
  10910. unsigned char **pabPK, /* OUT: Array of boolean - true for PK cols */
  10911. int *pnCol /* OUT: Number of entries in output array */
  10912. );
  10913. /*
  10914. ** CAPI3REF: Obtain old.* Values From A Changeset Iterator
  10915. ** METHOD: sqlite3_changeset_iter
  10916. **
  10917. ** The pIter argument passed to this function may either be an iterator
  10918. ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
  10919. ** created by [sqlite3changeset_start()]. In the latter case, the most recent
  10920. ** call to [sqlite3changeset_next()] must have returned SQLITE_ROW.
  10921. ** Furthermore, it may only be called if the type of change that the iterator
  10922. ** currently points to is either [SQLITE_DELETE] or [SQLITE_UPDATE]. Otherwise,
  10923. ** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
  10924. **
  10925. ** Argument iVal must be greater than or equal to 0, and less than the number
  10926. ** of columns in the table affected by the current change. Otherwise,
  10927. ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
  10928. **
  10929. ** If successful, this function sets *ppValue to point to a protected
  10930. ** sqlite3_value object containing the iVal'th value from the vector of
  10931. ** original row values stored as part of the UPDATE or DELETE change and
  10932. ** returns SQLITE_OK. The name of the function comes from the fact that this
  10933. ** is similar to the "old.*" columns available to update or delete triggers.
  10934. **
  10935. ** If some other error occurs (e.g. an OOM condition), an SQLite error code
  10936. ** is returned and *ppValue is set to NULL.
  10937. */
  10938. SQLITE_API int sqlite3changeset_old(
  10939. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  10940. int iVal, /* Column number */
  10941. sqlite3_value **ppValue /* OUT: Old value (or NULL pointer) */
  10942. );
  10943. /*
  10944. ** CAPI3REF: Obtain new.* Values From A Changeset Iterator
  10945. ** METHOD: sqlite3_changeset_iter
  10946. **
  10947. ** The pIter argument passed to this function may either be an iterator
  10948. ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
  10949. ** created by [sqlite3changeset_start()]. In the latter case, the most recent
  10950. ** call to [sqlite3changeset_next()] must have returned SQLITE_ROW.
  10951. ** Furthermore, it may only be called if the type of change that the iterator
  10952. ** currently points to is either [SQLITE_UPDATE] or [SQLITE_INSERT]. Otherwise,
  10953. ** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
  10954. **
  10955. ** Argument iVal must be greater than or equal to 0, and less than the number
  10956. ** of columns in the table affected by the current change. Otherwise,
  10957. ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
  10958. **
  10959. ** If successful, this function sets *ppValue to point to a protected
  10960. ** sqlite3_value object containing the iVal'th value from the vector of
  10961. ** new row values stored as part of the UPDATE or INSERT change and
  10962. ** returns SQLITE_OK. If the change is an UPDATE and does not include
  10963. ** a new value for the requested column, *ppValue is set to NULL and
  10964. ** SQLITE_OK returned. The name of the function comes from the fact that
  10965. ** this is similar to the "new.*" columns available to update or delete
  10966. ** triggers.
  10967. **
  10968. ** If some other error occurs (e.g. an OOM condition), an SQLite error code
  10969. ** is returned and *ppValue is set to NULL.
  10970. */
  10971. SQLITE_API int sqlite3changeset_new(
  10972. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  10973. int iVal, /* Column number */
  10974. sqlite3_value **ppValue /* OUT: New value (or NULL pointer) */
  10975. );
  10976. /*
  10977. ** CAPI3REF: Obtain Conflicting Row Values From A Changeset Iterator
  10978. ** METHOD: sqlite3_changeset_iter
  10979. **
  10980. ** This function should only be used with iterator objects passed to a
  10981. ** conflict-handler callback by [sqlite3changeset_apply()] with either
  10982. ** [SQLITE_CHANGESET_DATA] or [SQLITE_CHANGESET_CONFLICT]. If this function
  10983. ** is called on any other iterator, [SQLITE_MISUSE] is returned and *ppValue
  10984. ** is set to NULL.
  10985. **
  10986. ** Argument iVal must be greater than or equal to 0, and less than the number
  10987. ** of columns in the table affected by the current change. Otherwise,
  10988. ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
  10989. **
  10990. ** If successful, this function sets *ppValue to point to a protected
  10991. ** sqlite3_value object containing the iVal'th value from the
  10992. ** "conflicting row" associated with the current conflict-handler callback
  10993. ** and returns SQLITE_OK.
  10994. **
  10995. ** If some other error occurs (e.g. an OOM condition), an SQLite error code
  10996. ** is returned and *ppValue is set to NULL.
  10997. */
  10998. SQLITE_API int sqlite3changeset_conflict(
  10999. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  11000. int iVal, /* Column number */
  11001. sqlite3_value **ppValue /* OUT: Value from conflicting row */
  11002. );
  11003. /*
  11004. ** CAPI3REF: Determine The Number Of Foreign Key Constraint Violations
  11005. ** METHOD: sqlite3_changeset_iter
  11006. **
  11007. ** This function may only be called with an iterator passed to an
  11008. ** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case
  11009. ** it sets the output variable to the total number of known foreign key
  11010. ** violations in the destination database and returns SQLITE_OK.
  11011. **
  11012. ** In all other cases this function returns SQLITE_MISUSE.
  11013. */
  11014. SQLITE_API int sqlite3changeset_fk_conflicts(
  11015. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  11016. int *pnOut /* OUT: Number of FK violations */
  11017. );
  11018. /*
  11019. ** CAPI3REF: Finalize A Changeset Iterator
  11020. ** METHOD: sqlite3_changeset_iter
  11021. **
  11022. ** This function is used to finalize an iterator allocated with
  11023. ** [sqlite3changeset_start()].
  11024. **
  11025. ** This function should only be called on iterators created using the
  11026. ** [sqlite3changeset_start()] function. If an application calls this
  11027. ** function with an iterator passed to a conflict-handler by
  11028. ** [sqlite3changeset_apply()], [SQLITE_MISUSE] is immediately returned and the
  11029. ** call has no effect.
  11030. **
  11031. ** If an error was encountered within a call to an sqlite3changeset_xxx()
  11032. ** function (for example an [SQLITE_CORRUPT] in [sqlite3changeset_next()] or an
  11033. ** [SQLITE_NOMEM] in [sqlite3changeset_new()]) then an error code corresponding
  11034. ** to that error is returned by this function. Otherwise, SQLITE_OK is
  11035. ** returned. This is to allow the following pattern (pseudo-code):
  11036. **
  11037. ** <pre>
  11038. ** sqlite3changeset_start();
  11039. ** while( SQLITE_ROW==sqlite3changeset_next() ){
  11040. ** // Do something with change.
  11041. ** }
  11042. ** rc = sqlite3changeset_finalize();
  11043. ** if( rc!=SQLITE_OK ){
  11044. ** // An error has occurred
  11045. ** }
  11046. ** </pre>
  11047. */
  11048. SQLITE_API int sqlite3changeset_finalize(sqlite3_changeset_iter *pIter);
  11049. /*
  11050. ** CAPI3REF: Invert A Changeset
  11051. **
  11052. ** This function is used to "invert" a changeset object. Applying an inverted
  11053. ** changeset to a database reverses the effects of applying the uninverted
  11054. ** changeset. Specifically:
  11055. **
  11056. ** <ul>
  11057. ** <li> Each DELETE change is changed to an INSERT, and
  11058. ** <li> Each INSERT change is changed to a DELETE, and
  11059. ** <li> For each UPDATE change, the old.* and new.* values are exchanged.
  11060. ** </ul>
  11061. **
  11062. ** This function does not change the order in which changes appear within
  11063. ** the changeset. It merely reverses the sense of each individual change.
  11064. **
  11065. ** If successful, a pointer to a buffer containing the inverted changeset
  11066. ** is stored in *ppOut, the size of the same buffer is stored in *pnOut, and
  11067. ** SQLITE_OK is returned. If an error occurs, both *pnOut and *ppOut are
  11068. ** zeroed and an SQLite error code returned.
  11069. **
  11070. ** It is the responsibility of the caller to eventually call sqlite3_free()
  11071. ** on the *ppOut pointer to free the buffer allocation following a successful
  11072. ** call to this function.
  11073. **
  11074. ** WARNING/TODO: This function currently assumes that the input is a valid
  11075. ** changeset. If it is not, the results are undefined.
  11076. */
  11077. SQLITE_API int sqlite3changeset_invert(
  11078. int nIn, const void *pIn, /* Input changeset */
  11079. int *pnOut, void **ppOut /* OUT: Inverse of input */
  11080. );
  11081. /*
  11082. ** CAPI3REF: Concatenate Two Changeset Objects
  11083. **
  11084. ** This function is used to concatenate two changesets, A and B, into a
  11085. ** single changeset. The result is a changeset equivalent to applying
  11086. ** changeset A followed by changeset B.
  11087. **
  11088. ** This function combines the two input changesets using an
  11089. ** sqlite3_changegroup object. Calling it produces similar results as the
  11090. ** following code fragment:
  11091. **
  11092. ** <pre>
  11093. ** sqlite3_changegroup *pGrp;
  11094. ** rc = sqlite3_changegroup_new(&pGrp);
  11095. ** if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nA, pA);
  11096. ** if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nB, pB);
  11097. ** if( rc==SQLITE_OK ){
  11098. ** rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);
  11099. ** }else{
  11100. ** *ppOut = 0;
  11101. ** *pnOut = 0;
  11102. ** }
  11103. ** </pre>
  11104. **
  11105. ** Refer to the sqlite3_changegroup documentation below for details.
  11106. */
  11107. SQLITE_API int sqlite3changeset_concat(
  11108. int nA, /* Number of bytes in buffer pA */
  11109. void *pA, /* Pointer to buffer containing changeset A */
  11110. int nB, /* Number of bytes in buffer pB */
  11111. void *pB, /* Pointer to buffer containing changeset B */
  11112. int *pnOut, /* OUT: Number of bytes in output changeset */
  11113. void **ppOut /* OUT: Buffer containing output changeset */
  11114. );
  11115. /*
  11116. ** CAPI3REF: Changegroup Handle
  11117. **
  11118. ** A changegroup is an object used to combine two or more
  11119. ** [changesets] or [patchsets]
  11120. */
  11121. typedef struct sqlite3_changegroup sqlite3_changegroup;
  11122. /*
  11123. ** CAPI3REF: Create A New Changegroup Object
  11124. ** CONSTRUCTOR: sqlite3_changegroup
  11125. **
  11126. ** An sqlite3_changegroup object is used to combine two or more changesets
  11127. ** (or patchsets) into a single changeset (or patchset). A single changegroup
  11128. ** object may combine changesets or patchsets, but not both. The output is
  11129. ** always in the same format as the input.
  11130. **
  11131. ** If successful, this function returns SQLITE_OK and populates (*pp) with
  11132. ** a pointer to a new sqlite3_changegroup object before returning. The caller
  11133. ** should eventually free the returned object using a call to
  11134. ** sqlite3changegroup_delete(). If an error occurs, an SQLite error code
  11135. ** (i.e. SQLITE_NOMEM) is returned and *pp is set to NULL.
  11136. **
  11137. ** The usual usage pattern for an sqlite3_changegroup object is as follows:
  11138. **
  11139. ** <ul>
  11140. ** <li> It is created using a call to sqlite3changegroup_new().
  11141. **
  11142. ** <li> Zero or more changesets (or patchsets) are added to the object
  11143. ** by calling sqlite3changegroup_add().
  11144. **
  11145. ** <li> The result of combining all input changesets together is obtained
  11146. ** by the application via a call to sqlite3changegroup_output().
  11147. **
  11148. ** <li> The object is deleted using a call to sqlite3changegroup_delete().
  11149. ** </ul>
  11150. **
  11151. ** Any number of calls to add() and output() may be made between the calls to
  11152. ** new() and delete(), and in any order.
  11153. **
  11154. ** As well as the regular sqlite3changegroup_add() and
  11155. ** sqlite3changegroup_output() functions, also available are the streaming
  11156. ** versions sqlite3changegroup_add_strm() and sqlite3changegroup_output_strm().
  11157. */
  11158. SQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp);
  11159. /*
  11160. ** CAPI3REF: Add A Changeset To A Changegroup
  11161. ** METHOD: sqlite3_changegroup
  11162. **
  11163. ** Add all changes within the changeset (or patchset) in buffer pData (size
  11164. ** nData bytes) to the changegroup.
  11165. **
  11166. ** If the buffer contains a patchset, then all prior calls to this function
  11167. ** on the same changegroup object must also have specified patchsets. Or, if
  11168. ** the buffer contains a changeset, so must have the earlier calls to this
  11169. ** function. Otherwise, SQLITE_ERROR is returned and no changes are added
  11170. ** to the changegroup.
  11171. **
  11172. ** Rows within the changeset and changegroup are identified by the values in
  11173. ** their PRIMARY KEY columns. A change in the changeset is considered to
  11174. ** apply to the same row as a change already present in the changegroup if
  11175. ** the two rows have the same primary key.
  11176. **
  11177. ** Changes to rows that do not already appear in the changegroup are
  11178. ** simply copied into it. Or, if both the new changeset and the changegroup
  11179. ** contain changes that apply to a single row, the final contents of the
  11180. ** changegroup depends on the type of each change, as follows:
  11181. **
  11182. ** <table border=1 style="margin-left:8ex;margin-right:8ex">
  11183. ** <tr><th style="white-space:pre">Existing Change </th>
  11184. ** <th style="white-space:pre">New Change </th>
  11185. ** <th>Output Change
  11186. ** <tr><td>INSERT <td>INSERT <td>
  11187. ** The new change is ignored. This case does not occur if the new
  11188. ** changeset was recorded immediately after the changesets already
  11189. ** added to the changegroup.
  11190. ** <tr><td>INSERT <td>UPDATE <td>
  11191. ** The INSERT change remains in the changegroup. The values in the
  11192. ** INSERT change are modified as if the row was inserted by the
  11193. ** existing change and then updated according to the new change.
  11194. ** <tr><td>INSERT <td>DELETE <td>
  11195. ** The existing INSERT is removed from the changegroup. The DELETE is
  11196. ** not added.
  11197. ** <tr><td>UPDATE <td>INSERT <td>
  11198. ** The new change is ignored. This case does not occur if the new
  11199. ** changeset was recorded immediately after the changesets already
  11200. ** added to the changegroup.
  11201. ** <tr><td>UPDATE <td>UPDATE <td>
  11202. ** The existing UPDATE remains within the changegroup. It is amended
  11203. ** so that the accompanying values are as if the row was updated once
  11204. ** by the existing change and then again by the new change.
  11205. ** <tr><td>UPDATE <td>DELETE <td>
  11206. ** The existing UPDATE is replaced by the new DELETE within the
  11207. ** changegroup.
  11208. ** <tr><td>DELETE <td>INSERT <td>
  11209. ** If one or more of the column values in the row inserted by the
  11210. ** new change differ from those in the row deleted by the existing
  11211. ** change, the existing DELETE is replaced by an UPDATE within the
  11212. ** changegroup. Otherwise, if the inserted row is exactly the same
  11213. ** as the deleted row, the existing DELETE is simply discarded.
  11214. ** <tr><td>DELETE <td>UPDATE <td>
  11215. ** The new change is ignored. This case does not occur if the new
  11216. ** changeset was recorded immediately after the changesets already
  11217. ** added to the changegroup.
  11218. ** <tr><td>DELETE <td>DELETE <td>
  11219. ** The new change is ignored. This case does not occur if the new
  11220. ** changeset was recorded immediately after the changesets already
  11221. ** added to the changegroup.
  11222. ** </table>
  11223. **
  11224. ** If the new changeset contains changes to a table that is already present
  11225. ** in the changegroup, then the number of columns and the position of the
  11226. ** primary key columns for the table must be consistent. If this is not the
  11227. ** case, this function fails with SQLITE_SCHEMA. If the input changeset
  11228. ** appears to be corrupt and the corruption is detected, SQLITE_CORRUPT is
  11229. ** returned. Or, if an out-of-memory condition occurs during processing, this
  11230. ** function returns SQLITE_NOMEM. In all cases, if an error occurs the
  11231. ** final contents of the changegroup is undefined.
  11232. **
  11233. ** If no error occurs, SQLITE_OK is returned.
  11234. */
  11235. SQLITE_API int sqlite3changegroup_add(sqlite3_changegroup*, int nData, void *pData);
  11236. /*
  11237. ** CAPI3REF: Obtain A Composite Changeset From A Changegroup
  11238. ** METHOD: sqlite3_changegroup
  11239. **
  11240. ** Obtain a buffer containing a changeset (or patchset) representing the
  11241. ** current contents of the changegroup. If the inputs to the changegroup
  11242. ** were themselves changesets, the output is a changeset. Or, if the
  11243. ** inputs were patchsets, the output is also a patchset.
  11244. **
  11245. ** As with the output of the sqlite3session_changeset() and
  11246. ** sqlite3session_patchset() functions, all changes related to a single
  11247. ** table are grouped together in the output of this function. Tables appear
  11248. ** in the same order as for the very first changeset added to the changegroup.
  11249. ** If the second or subsequent changesets added to the changegroup contain
  11250. ** changes for tables that do not appear in the first changeset, they are
  11251. ** appended onto the end of the output changeset, again in the order in
  11252. ** which they are first encountered.
  11253. **
  11254. ** If an error occurs, an SQLite error code is returned and the output
  11255. ** variables (*pnData) and (*ppData) are set to 0. Otherwise, SQLITE_OK
  11256. ** is returned and the output variables are set to the size of and a
  11257. ** pointer to the output buffer, respectively. In this case it is the
  11258. ** responsibility of the caller to eventually free the buffer using a
  11259. ** call to sqlite3_free().
  11260. */
  11261. SQLITE_API int sqlite3changegroup_output(
  11262. sqlite3_changegroup*,
  11263. int *pnData, /* OUT: Size of output buffer in bytes */
  11264. void **ppData /* OUT: Pointer to output buffer */
  11265. );
  11266. /*
  11267. ** CAPI3REF: Delete A Changegroup Object
  11268. ** DESTRUCTOR: sqlite3_changegroup
  11269. */
  11270. SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup*);
  11271. /*
  11272. ** CAPI3REF: Apply A Changeset To A Database
  11273. **
  11274. ** Apply a changeset or patchset to a database. These functions attempt to
  11275. ** update the "main" database attached to handle db with the changes found in
  11276. ** the changeset passed via the second and third arguments.
  11277. **
  11278. ** The fourth argument (xFilter) passed to these functions is the "filter
  11279. ** callback". If it is not NULL, then for each table affected by at least one
  11280. ** change in the changeset, the filter callback is invoked with
  11281. ** the table name as the second argument, and a copy of the context pointer
  11282. ** passed as the sixth argument as the first. If the "filter callback"
  11283. ** returns zero, then no attempt is made to apply any changes to the table.
  11284. ** Otherwise, if the return value is non-zero or the xFilter argument to
  11285. ** is NULL, all changes related to the table are attempted.
  11286. **
  11287. ** For each table that is not excluded by the filter callback, this function
  11288. ** tests that the target database contains a compatible table. A table is
  11289. ** considered compatible if all of the following are true:
  11290. **
  11291. ** <ul>
  11292. ** <li> The table has the same name as the name recorded in the
  11293. ** changeset, and
  11294. ** <li> The table has at least as many columns as recorded in the
  11295. ** changeset, and
  11296. ** <li> The table has primary key columns in the same position as
  11297. ** recorded in the changeset.
  11298. ** </ul>
  11299. **
  11300. ** If there is no compatible table, it is not an error, but none of the
  11301. ** changes associated with the table are applied. A warning message is issued
  11302. ** via the sqlite3_log() mechanism with the error code SQLITE_SCHEMA. At most
  11303. ** one such warning is issued for each table in the changeset.
  11304. **
  11305. ** For each change for which there is a compatible table, an attempt is made
  11306. ** to modify the table contents according to the UPDATE, INSERT or DELETE
  11307. ** change. If a change cannot be applied cleanly, the conflict handler
  11308. ** function passed as the fifth argument to sqlite3changeset_apply() may be
  11309. ** invoked. A description of exactly when the conflict handler is invoked for
  11310. ** each type of change is below.
  11311. **
  11312. ** Unlike the xFilter argument, xConflict may not be passed NULL. The results
  11313. ** of passing anything other than a valid function pointer as the xConflict
  11314. ** argument are undefined.
  11315. **
  11316. ** Each time the conflict handler function is invoked, it must return one
  11317. ** of [SQLITE_CHANGESET_OMIT], [SQLITE_CHANGESET_ABORT] or
  11318. ** [SQLITE_CHANGESET_REPLACE]. SQLITE_CHANGESET_REPLACE may only be returned
  11319. ** if the second argument passed to the conflict handler is either
  11320. ** SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If the conflict-handler
  11321. ** returns an illegal value, any changes already made are rolled back and
  11322. ** the call to sqlite3changeset_apply() returns SQLITE_MISUSE. Different
  11323. ** actions are taken by sqlite3changeset_apply() depending on the value
  11324. ** returned by each invocation of the conflict-handler function. Refer to
  11325. ** the documentation for the three
  11326. ** [SQLITE_CHANGESET_OMIT|available return values] for details.
  11327. **
  11328. ** <dl>
  11329. ** <dt>DELETE Changes<dd>
  11330. ** For each DELETE change, the function checks if the target database
  11331. ** contains a row with the same primary key value (or values) as the
  11332. ** original row values stored in the changeset. If it does, and the values
  11333. ** stored in all non-primary key columns also match the values stored in
  11334. ** the changeset the row is deleted from the target database.
  11335. **
  11336. ** If a row with matching primary key values is found, but one or more of
  11337. ** the non-primary key fields contains a value different from the original
  11338. ** row value stored in the changeset, the conflict-handler function is
  11339. ** invoked with [SQLITE_CHANGESET_DATA] as the second argument. If the
  11340. ** database table has more columns than are recorded in the changeset,
  11341. ** only the values of those non-primary key fields are compared against
  11342. ** the current database contents - any trailing database table columns
  11343. ** are ignored.
  11344. **
  11345. ** If no row with matching primary key values is found in the database,
  11346. ** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
  11347. ** passed as the second argument.
  11348. **
  11349. ** If the DELETE operation is attempted, but SQLite returns SQLITE_CONSTRAINT
  11350. ** (which can only happen if a foreign key constraint is violated), the
  11351. ** conflict-handler function is invoked with [SQLITE_CHANGESET_CONSTRAINT]
  11352. ** passed as the second argument. This includes the case where the DELETE
  11353. ** operation is attempted because an earlier call to the conflict handler
  11354. ** function returned [SQLITE_CHANGESET_REPLACE].
  11355. **
  11356. ** <dt>INSERT Changes<dd>
  11357. ** For each INSERT change, an attempt is made to insert the new row into
  11358. ** the database. If the changeset row contains fewer fields than the
  11359. ** database table, the trailing fields are populated with their default
  11360. ** values.
  11361. **
  11362. ** If the attempt to insert the row fails because the database already
  11363. ** contains a row with the same primary key values, the conflict handler
  11364. ** function is invoked with the second argument set to
  11365. ** [SQLITE_CHANGESET_CONFLICT].
  11366. **
  11367. ** If the attempt to insert the row fails because of some other constraint
  11368. ** violation (e.g. NOT NULL or UNIQUE), the conflict handler function is
  11369. ** invoked with the second argument set to [SQLITE_CHANGESET_CONSTRAINT].
  11370. ** This includes the case where the INSERT operation is re-attempted because
  11371. ** an earlier call to the conflict handler function returned
  11372. ** [SQLITE_CHANGESET_REPLACE].
  11373. **
  11374. ** <dt>UPDATE Changes<dd>
  11375. ** For each UPDATE change, the function checks if the target database
  11376. ** contains a row with the same primary key value (or values) as the
  11377. ** original row values stored in the changeset. If it does, and the values
  11378. ** stored in all modified non-primary key columns also match the values
  11379. ** stored in the changeset the row is updated within the target database.
  11380. **
  11381. ** If a row with matching primary key values is found, but one or more of
  11382. ** the modified non-primary key fields contains a value different from an
  11383. ** original row value stored in the changeset, the conflict-handler function
  11384. ** is invoked with [SQLITE_CHANGESET_DATA] as the second argument. Since
  11385. ** UPDATE changes only contain values for non-primary key fields that are
  11386. ** to be modified, only those fields need to match the original values to
  11387. ** avoid the SQLITE_CHANGESET_DATA conflict-handler callback.
  11388. **
  11389. ** If no row with matching primary key values is found in the database,
  11390. ** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
  11391. ** passed as the second argument.
  11392. **
  11393. ** If the UPDATE operation is attempted, but SQLite returns
  11394. ** SQLITE_CONSTRAINT, the conflict-handler function is invoked with
  11395. ** [SQLITE_CHANGESET_CONSTRAINT] passed as the second argument.
  11396. ** This includes the case where the UPDATE operation is attempted after
  11397. ** an earlier call to the conflict handler function returned
  11398. ** [SQLITE_CHANGESET_REPLACE].
  11399. ** </dl>
  11400. **
  11401. ** It is safe to execute SQL statements, including those that write to the
  11402. ** table that the callback related to, from within the xConflict callback.
  11403. ** This can be used to further customize the applications conflict
  11404. ** resolution strategy.
  11405. **
  11406. ** All changes made by these functions are enclosed in a savepoint transaction.
  11407. ** If any other error (aside from a constraint failure when attempting to
  11408. ** write to the target database) occurs, then the savepoint transaction is
  11409. ** rolled back, restoring the target database to its original state, and an
  11410. ** SQLite error code returned.
  11411. **
  11412. ** If the output parameters (ppRebase) and (pnRebase) are non-NULL and
  11413. ** the input is a changeset (not a patchset), then sqlite3changeset_apply_v2()
  11414. ** may set (*ppRebase) to point to a "rebase" that may be used with the
  11415. ** sqlite3_rebaser APIs buffer before returning. In this case (*pnRebase)
  11416. ** is set to the size of the buffer in bytes. It is the responsibility of the
  11417. ** caller to eventually free any such buffer using sqlite3_free(). The buffer
  11418. ** is only allocated and populated if one or more conflicts were encountered
  11419. ** while applying the patchset. See comments surrounding the sqlite3_rebaser
  11420. ** APIs for further details.
  11421. **
  11422. ** The behavior of sqlite3changeset_apply_v2() and its streaming equivalent
  11423. ** may be modified by passing a combination of
  11424. ** [SQLITE_CHANGESETAPPLY_NOSAVEPOINT | supported flags] as the 9th parameter.
  11425. **
  11426. ** Note that the sqlite3changeset_apply_v2() API is still <b>experimental</b>
  11427. ** and therefore subject to change.
  11428. */
  11429. SQLITE_API int sqlite3changeset_apply(
  11430. sqlite3 *db, /* Apply change to "main" db of this handle */
  11431. int nChangeset, /* Size of changeset in bytes */
  11432. void *pChangeset, /* Changeset blob */
  11433. int(*xFilter)(
  11434. void *pCtx, /* Copy of sixth arg to _apply() */
  11435. const char *zTab /* Table name */
  11436. ),
  11437. int(*xConflict)(
  11438. void *pCtx, /* Copy of sixth arg to _apply() */
  11439. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  11440. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  11441. ),
  11442. void *pCtx /* First argument passed to xConflict */
  11443. );
  11444. SQLITE_API int sqlite3changeset_apply_v2(
  11445. sqlite3 *db, /* Apply change to "main" db of this handle */
  11446. int nChangeset, /* Size of changeset in bytes */
  11447. void *pChangeset, /* Changeset blob */
  11448. int(*xFilter)(
  11449. void *pCtx, /* Copy of sixth arg to _apply() */
  11450. const char *zTab /* Table name */
  11451. ),
  11452. int(*xConflict)(
  11453. void *pCtx, /* Copy of sixth arg to _apply() */
  11454. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  11455. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  11456. ),
  11457. void *pCtx, /* First argument passed to xConflict */
  11458. void **ppRebase, int *pnRebase, /* OUT: Rebase data */
  11459. int flags /* SESSION_CHANGESETAPPLY_* flags */
  11460. );
  11461. /*
  11462. ** CAPI3REF: Flags for sqlite3changeset_apply_v2
  11463. **
  11464. ** The following flags may passed via the 9th parameter to
  11465. ** [sqlite3changeset_apply_v2] and [sqlite3changeset_apply_v2_strm]:
  11466. **
  11467. ** <dl>
  11468. ** <dt>SQLITE_CHANGESETAPPLY_NOSAVEPOINT <dd>
  11469. ** Usually, the sessions module encloses all operations performed by
  11470. ** a single call to apply_v2() or apply_v2_strm() in a [SAVEPOINT]. The
  11471. ** SAVEPOINT is committed if the changeset or patchset is successfully
  11472. ** applied, or rolled back if an error occurs. Specifying this flag
  11473. ** causes the sessions module to omit this savepoint. In this case, if the
  11474. ** caller has an open transaction or savepoint when apply_v2() is called,
  11475. ** it may revert the partially applied changeset by rolling it back.
  11476. **
  11477. ** <dt>SQLITE_CHANGESETAPPLY_INVERT <dd>
  11478. ** Invert the changeset before applying it. This is equivalent to inverting
  11479. ** a changeset using sqlite3changeset_invert() before applying it. It is
  11480. ** an error to specify this flag with a patchset.
  11481. */
  11482. #define SQLITE_CHANGESETAPPLY_NOSAVEPOINT 0x0001
  11483. #define SQLITE_CHANGESETAPPLY_INVERT 0x0002
  11484. /*
  11485. ** CAPI3REF: Constants Passed To The Conflict Handler
  11486. **
  11487. ** Values that may be passed as the second argument to a conflict-handler.
  11488. **
  11489. ** <dl>
  11490. ** <dt>SQLITE_CHANGESET_DATA<dd>
  11491. ** The conflict handler is invoked with CHANGESET_DATA as the second argument
  11492. ** when processing a DELETE or UPDATE change if a row with the required
  11493. ** PRIMARY KEY fields is present in the database, but one or more other
  11494. ** (non primary-key) fields modified by the update do not contain the
  11495. ** expected "before" values.
  11496. **
  11497. ** The conflicting row, in this case, is the database row with the matching
  11498. ** primary key.
  11499. **
  11500. ** <dt>SQLITE_CHANGESET_NOTFOUND<dd>
  11501. ** The conflict handler is invoked with CHANGESET_NOTFOUND as the second
  11502. ** argument when processing a DELETE or UPDATE change if a row with the
  11503. ** required PRIMARY KEY fields is not present in the database.
  11504. **
  11505. ** There is no conflicting row in this case. The results of invoking the
  11506. ** sqlite3changeset_conflict() API are undefined.
  11507. **
  11508. ** <dt>SQLITE_CHANGESET_CONFLICT<dd>
  11509. ** CHANGESET_CONFLICT is passed as the second argument to the conflict
  11510. ** handler while processing an INSERT change if the operation would result
  11511. ** in duplicate primary key values.
  11512. **
  11513. ** The conflicting row in this case is the database row with the matching
  11514. ** primary key.
  11515. **
  11516. ** <dt>SQLITE_CHANGESET_FOREIGN_KEY<dd>
  11517. ** If foreign key handling is enabled, and applying a changeset leaves the
  11518. ** database in a state containing foreign key violations, the conflict
  11519. ** handler is invoked with CHANGESET_FOREIGN_KEY as the second argument
  11520. ** exactly once before the changeset is committed. If the conflict handler
  11521. ** returns CHANGESET_OMIT, the changes, including those that caused the
  11522. ** foreign key constraint violation, are committed. Or, if it returns
  11523. ** CHANGESET_ABORT, the changeset is rolled back.
  11524. **
  11525. ** No current or conflicting row information is provided. The only function
  11526. ** it is possible to call on the supplied sqlite3_changeset_iter handle
  11527. ** is sqlite3changeset_fk_conflicts().
  11528. **
  11529. ** <dt>SQLITE_CHANGESET_CONSTRAINT<dd>
  11530. ** If any other constraint violation occurs while applying a change (i.e.
  11531. ** a UNIQUE, CHECK or NOT NULL constraint), the conflict handler is
  11532. ** invoked with CHANGESET_CONSTRAINT as the second argument.
  11533. **
  11534. ** There is no conflicting row in this case. The results of invoking the
  11535. ** sqlite3changeset_conflict() API are undefined.
  11536. **
  11537. ** </dl>
  11538. */
  11539. #define SQLITE_CHANGESET_DATA 1
  11540. #define SQLITE_CHANGESET_NOTFOUND 2
  11541. #define SQLITE_CHANGESET_CONFLICT 3
  11542. #define SQLITE_CHANGESET_CONSTRAINT 4
  11543. #define SQLITE_CHANGESET_FOREIGN_KEY 5
  11544. /*
  11545. ** CAPI3REF: Constants Returned By The Conflict Handler
  11546. **
  11547. ** A conflict handler callback must return one of the following three values.
  11548. **
  11549. ** <dl>
  11550. ** <dt>SQLITE_CHANGESET_OMIT<dd>
  11551. ** If a conflict handler returns this value no special action is taken. The
  11552. ** change that caused the conflict is not applied. The session module
  11553. ** continues to the next change in the changeset.
  11554. **
  11555. ** <dt>SQLITE_CHANGESET_REPLACE<dd>
  11556. ** This value may only be returned if the second argument to the conflict
  11557. ** handler was SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If this
  11558. ** is not the case, any changes applied so far are rolled back and the
  11559. ** call to sqlite3changeset_apply() returns SQLITE_MISUSE.
  11560. **
  11561. ** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_DATA conflict
  11562. ** handler, then the conflicting row is either updated or deleted, depending
  11563. ** on the type of change.
  11564. **
  11565. ** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_CONFLICT conflict
  11566. ** handler, then the conflicting row is removed from the database and a
  11567. ** second attempt to apply the change is made. If this second attempt fails,
  11568. ** the original row is restored to the database before continuing.
  11569. **
  11570. ** <dt>SQLITE_CHANGESET_ABORT<dd>
  11571. ** If this value is returned, any changes applied so far are rolled back
  11572. ** and the call to sqlite3changeset_apply() returns SQLITE_ABORT.
  11573. ** </dl>
  11574. */
  11575. #define SQLITE_CHANGESET_OMIT 0
  11576. #define SQLITE_CHANGESET_REPLACE 1
  11577. #define SQLITE_CHANGESET_ABORT 2
  11578. /*
  11579. ** CAPI3REF: Rebasing changesets
  11580. ** EXPERIMENTAL
  11581. **
  11582. ** Suppose there is a site hosting a database in state S0. And that
  11583. ** modifications are made that move that database to state S1 and a
  11584. ** changeset recorded (the "local" changeset). Then, a changeset based
  11585. ** on S0 is received from another site (the "remote" changeset) and
  11586. ** applied to the database. The database is then in state
  11587. ** (S1+"remote"), where the exact state depends on any conflict
  11588. ** resolution decisions (OMIT or REPLACE) made while applying "remote".
  11589. ** Rebasing a changeset is to update it to take those conflict
  11590. ** resolution decisions into account, so that the same conflicts
  11591. ** do not have to be resolved elsewhere in the network.
  11592. **
  11593. ** For example, if both the local and remote changesets contain an
  11594. ** INSERT of the same key on "CREATE TABLE t1(a PRIMARY KEY, b)":
  11595. **
  11596. ** local: INSERT INTO t1 VALUES(1, 'v1');
  11597. ** remote: INSERT INTO t1 VALUES(1, 'v2');
  11598. **
  11599. ** and the conflict resolution is REPLACE, then the INSERT change is
  11600. ** removed from the local changeset (it was overridden). Or, if the
  11601. ** conflict resolution was "OMIT", then the local changeset is modified
  11602. ** to instead contain:
  11603. **
  11604. ** UPDATE t1 SET b = 'v2' WHERE a=1;
  11605. **
  11606. ** Changes within the local changeset are rebased as follows:
  11607. **
  11608. ** <dl>
  11609. ** <dt>Local INSERT<dd>
  11610. ** This may only conflict with a remote INSERT. If the conflict
  11611. ** resolution was OMIT, then add an UPDATE change to the rebased
  11612. ** changeset. Or, if the conflict resolution was REPLACE, add
  11613. ** nothing to the rebased changeset.
  11614. **
  11615. ** <dt>Local DELETE<dd>
  11616. ** This may conflict with a remote UPDATE or DELETE. In both cases the
  11617. ** only possible resolution is OMIT. If the remote operation was a
  11618. ** DELETE, then add no change to the rebased changeset. If the remote
  11619. ** operation was an UPDATE, then the old.* fields of change are updated
  11620. ** to reflect the new.* values in the UPDATE.
  11621. **
  11622. ** <dt>Local UPDATE<dd>
  11623. ** This may conflict with a remote UPDATE or DELETE. If it conflicts
  11624. ** with a DELETE, and the conflict resolution was OMIT, then the update
  11625. ** is changed into an INSERT. Any undefined values in the new.* record
  11626. ** from the update change are filled in using the old.* values from
  11627. ** the conflicting DELETE. Or, if the conflict resolution was REPLACE,
  11628. ** the UPDATE change is simply omitted from the rebased changeset.
  11629. **
  11630. ** If conflict is with a remote UPDATE and the resolution is OMIT, then
  11631. ** the old.* values are rebased using the new.* values in the remote
  11632. ** change. Or, if the resolution is REPLACE, then the change is copied
  11633. ** into the rebased changeset with updates to columns also updated by
  11634. ** the conflicting remote UPDATE removed. If this means no columns would
  11635. ** be updated, the change is omitted.
  11636. ** </dl>
  11637. **
  11638. ** A local change may be rebased against multiple remote changes
  11639. ** simultaneously. If a single key is modified by multiple remote
  11640. ** changesets, they are combined as follows before the local changeset
  11641. ** is rebased:
  11642. **
  11643. ** <ul>
  11644. ** <li> If there has been one or more REPLACE resolutions on a
  11645. ** key, it is rebased according to a REPLACE.
  11646. **
  11647. ** <li> If there have been no REPLACE resolutions on a key, then
  11648. ** the local changeset is rebased according to the most recent
  11649. ** of the OMIT resolutions.
  11650. ** </ul>
  11651. **
  11652. ** Note that conflict resolutions from multiple remote changesets are
  11653. ** combined on a per-field basis, not per-row. This means that in the
  11654. ** case of multiple remote UPDATE operations, some fields of a single
  11655. ** local change may be rebased for REPLACE while others are rebased for
  11656. ** OMIT.
  11657. **
  11658. ** In order to rebase a local changeset, the remote changeset must first
  11659. ** be applied to the local database using sqlite3changeset_apply_v2() and
  11660. ** the buffer of rebase information captured. Then:
  11661. **
  11662. ** <ol>
  11663. ** <li> An sqlite3_rebaser object is created by calling
  11664. ** sqlite3rebaser_create().
  11665. ** <li> The new object is configured with the rebase buffer obtained from
  11666. ** sqlite3changeset_apply_v2() by calling sqlite3rebaser_configure().
  11667. ** If the local changeset is to be rebased against multiple remote
  11668. ** changesets, then sqlite3rebaser_configure() should be called
  11669. ** multiple times, in the same order that the multiple
  11670. ** sqlite3changeset_apply_v2() calls were made.
  11671. ** <li> Each local changeset is rebased by calling sqlite3rebaser_rebase().
  11672. ** <li> The sqlite3_rebaser object is deleted by calling
  11673. ** sqlite3rebaser_delete().
  11674. ** </ol>
  11675. */
  11676. typedef struct sqlite3_rebaser sqlite3_rebaser;
  11677. /*
  11678. ** CAPI3REF: Create a changeset rebaser object.
  11679. ** EXPERIMENTAL
  11680. **
  11681. ** Allocate a new changeset rebaser object. If successful, set (*ppNew) to
  11682. ** point to the new object and return SQLITE_OK. Otherwise, if an error
  11683. ** occurs, return an SQLite error code (e.g. SQLITE_NOMEM) and set (*ppNew)
  11684. ** to NULL.
  11685. */
  11686. SQLITE_API int sqlite3rebaser_create(sqlite3_rebaser **ppNew);
  11687. /*
  11688. ** CAPI3REF: Configure a changeset rebaser object.
  11689. ** EXPERIMENTAL
  11690. **
  11691. ** Configure the changeset rebaser object to rebase changesets according
  11692. ** to the conflict resolutions described by buffer pRebase (size nRebase
  11693. ** bytes), which must have been obtained from a previous call to
  11694. ** sqlite3changeset_apply_v2().
  11695. */
  11696. SQLITE_API int sqlite3rebaser_configure(
  11697. sqlite3_rebaser*,
  11698. int nRebase, const void *pRebase
  11699. );
  11700. /*
  11701. ** CAPI3REF: Rebase a changeset
  11702. ** EXPERIMENTAL
  11703. **
  11704. ** Argument pIn must point to a buffer containing a changeset nIn bytes
  11705. ** in size. This function allocates and populates a buffer with a copy
  11706. ** of the changeset rebased rebased according to the configuration of the
  11707. ** rebaser object passed as the first argument. If successful, (*ppOut)
  11708. ** is set to point to the new buffer containing the rebased changeset and
  11709. ** (*pnOut) to its size in bytes and SQLITE_OK returned. It is the
  11710. ** responsibility of the caller to eventually free the new buffer using
  11711. ** sqlite3_free(). Otherwise, if an error occurs, (*ppOut) and (*pnOut)
  11712. ** are set to zero and an SQLite error code returned.
  11713. */
  11714. SQLITE_API int sqlite3rebaser_rebase(
  11715. sqlite3_rebaser*,
  11716. int nIn, const void *pIn,
  11717. int *pnOut, void **ppOut
  11718. );
  11719. /*
  11720. ** CAPI3REF: Delete a changeset rebaser object.
  11721. ** EXPERIMENTAL
  11722. **
  11723. ** Delete the changeset rebaser object and all associated resources. There
  11724. ** should be one call to this function for each successful invocation
  11725. ** of sqlite3rebaser_create().
  11726. */
  11727. SQLITE_API void sqlite3rebaser_delete(sqlite3_rebaser *p);
  11728. /*
  11729. ** CAPI3REF: Streaming Versions of API functions.
  11730. **
  11731. ** The six streaming API xxx_strm() functions serve similar purposes to the
  11732. ** corresponding non-streaming API functions:
  11733. **
  11734. ** <table border=1 style="margin-left:8ex;margin-right:8ex">
  11735. ** <tr><th>Streaming function<th>Non-streaming equivalent</th>
  11736. ** <tr><td>sqlite3changeset_apply_strm<td>[sqlite3changeset_apply]
  11737. ** <tr><td>sqlite3changeset_apply_strm_v2<td>[sqlite3changeset_apply_v2]
  11738. ** <tr><td>sqlite3changeset_concat_strm<td>[sqlite3changeset_concat]
  11739. ** <tr><td>sqlite3changeset_invert_strm<td>[sqlite3changeset_invert]
  11740. ** <tr><td>sqlite3changeset_start_strm<td>[sqlite3changeset_start]
  11741. ** <tr><td>sqlite3session_changeset_strm<td>[sqlite3session_changeset]
  11742. ** <tr><td>sqlite3session_patchset_strm<td>[sqlite3session_patchset]
  11743. ** </table>
  11744. **
  11745. ** Non-streaming functions that accept changesets (or patchsets) as input
  11746. ** require that the entire changeset be stored in a single buffer in memory.
  11747. ** Similarly, those that return a changeset or patchset do so by returning
  11748. ** a pointer to a single large buffer allocated using sqlite3_malloc().
  11749. ** Normally this is convenient. However, if an application running in a
  11750. ** low-memory environment is required to handle very large changesets, the
  11751. ** large contiguous memory allocations required can become onerous.
  11752. **
  11753. ** In order to avoid this problem, instead of a single large buffer, input
  11754. ** is passed to a streaming API functions by way of a callback function that
  11755. ** the sessions module invokes to incrementally request input data as it is
  11756. ** required. In all cases, a pair of API function parameters such as
  11757. **
  11758. ** <pre>
  11759. ** &nbsp; int nChangeset,
  11760. ** &nbsp; void *pChangeset,
  11761. ** </pre>
  11762. **
  11763. ** Is replaced by:
  11764. **
  11765. ** <pre>
  11766. ** &nbsp; int (*xInput)(void *pIn, void *pData, int *pnData),
  11767. ** &nbsp; void *pIn,
  11768. ** </pre>
  11769. **
  11770. ** Each time the xInput callback is invoked by the sessions module, the first
  11771. ** argument passed is a copy of the supplied pIn context pointer. The second
  11772. ** argument, pData, points to a buffer (*pnData) bytes in size. Assuming no
  11773. ** error occurs the xInput method should copy up to (*pnData) bytes of data
  11774. ** into the buffer and set (*pnData) to the actual number of bytes copied
  11775. ** before returning SQLITE_OK. If the input is completely exhausted, (*pnData)
  11776. ** should be set to zero to indicate this. Or, if an error occurs, an SQLite
  11777. ** error code should be returned. In all cases, if an xInput callback returns
  11778. ** an error, all processing is abandoned and the streaming API function
  11779. ** returns a copy of the error code to the caller.
  11780. **
  11781. ** In the case of sqlite3changeset_start_strm(), the xInput callback may be
  11782. ** invoked by the sessions module at any point during the lifetime of the
  11783. ** iterator. If such an xInput callback returns an error, the iterator enters
  11784. ** an error state, whereby all subsequent calls to iterator functions
  11785. ** immediately fail with the same error code as returned by xInput.
  11786. **
  11787. ** Similarly, streaming API functions that return changesets (or patchsets)
  11788. ** return them in chunks by way of a callback function instead of via a
  11789. ** pointer to a single large buffer. In this case, a pair of parameters such
  11790. ** as:
  11791. **
  11792. ** <pre>
  11793. ** &nbsp; int *pnChangeset,
  11794. ** &nbsp; void **ppChangeset,
  11795. ** </pre>
  11796. **
  11797. ** Is replaced by:
  11798. **
  11799. ** <pre>
  11800. ** &nbsp; int (*xOutput)(void *pOut, const void *pData, int nData),
  11801. ** &nbsp; void *pOut
  11802. ** </pre>
  11803. **
  11804. ** The xOutput callback is invoked zero or more times to return data to
  11805. ** the application. The first parameter passed to each call is a copy of the
  11806. ** pOut pointer supplied by the application. The second parameter, pData,
  11807. ** points to a buffer nData bytes in size containing the chunk of output
  11808. ** data being returned. If the xOutput callback successfully processes the
  11809. ** supplied data, it should return SQLITE_OK to indicate success. Otherwise,
  11810. ** it should return some other SQLite error code. In this case processing
  11811. ** is immediately abandoned and the streaming API function returns a copy
  11812. ** of the xOutput error code to the application.
  11813. **
  11814. ** The sessions module never invokes an xOutput callback with the third
  11815. ** parameter set to a value less than or equal to zero. Other than this,
  11816. ** no guarantees are made as to the size of the chunks of data returned.
  11817. */
  11818. SQLITE_API int sqlite3changeset_apply_strm(
  11819. sqlite3 *db, /* Apply change to "main" db of this handle */
  11820. int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
  11821. void *pIn, /* First arg for xInput */
  11822. int(*xFilter)(
  11823. void *pCtx, /* Copy of sixth arg to _apply() */
  11824. const char *zTab /* Table name */
  11825. ),
  11826. int(*xConflict)(
  11827. void *pCtx, /* Copy of sixth arg to _apply() */
  11828. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  11829. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  11830. ),
  11831. void *pCtx /* First argument passed to xConflict */
  11832. );
  11833. SQLITE_API int sqlite3changeset_apply_v2_strm(
  11834. sqlite3 *db, /* Apply change to "main" db of this handle */
  11835. int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
  11836. void *pIn, /* First arg for xInput */
  11837. int(*xFilter)(
  11838. void *pCtx, /* Copy of sixth arg to _apply() */
  11839. const char *zTab /* Table name */
  11840. ),
  11841. int(*xConflict)(
  11842. void *pCtx, /* Copy of sixth arg to _apply() */
  11843. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  11844. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  11845. ),
  11846. void *pCtx, /* First argument passed to xConflict */
  11847. void **ppRebase, int *pnRebase,
  11848. int flags
  11849. );
  11850. SQLITE_API int sqlite3changeset_concat_strm(
  11851. int (*xInputA)(void *pIn, void *pData, int *pnData),
  11852. void *pInA,
  11853. int (*xInputB)(void *pIn, void *pData, int *pnData),
  11854. void *pInB,
  11855. int (*xOutput)(void *pOut, const void *pData, int nData),
  11856. void *pOut
  11857. );
  11858. SQLITE_API int sqlite3changeset_invert_strm(
  11859. int (*xInput)(void *pIn, void *pData, int *pnData),
  11860. void *pIn,
  11861. int (*xOutput)(void *pOut, const void *pData, int nData),
  11862. void *pOut
  11863. );
  11864. SQLITE_API int sqlite3changeset_start_strm(
  11865. sqlite3_changeset_iter **pp,
  11866. int (*xInput)(void *pIn, void *pData, int *pnData),
  11867. void *pIn
  11868. );
  11869. SQLITE_API int sqlite3changeset_start_v2_strm(
  11870. sqlite3_changeset_iter **pp,
  11871. int (*xInput)(void *pIn, void *pData, int *pnData),
  11872. void *pIn,
  11873. int flags
  11874. );
  11875. SQLITE_API int sqlite3session_changeset_strm(
  11876. sqlite3_session *pSession,
  11877. int (*xOutput)(void *pOut, const void *pData, int nData),
  11878. void *pOut
  11879. );
  11880. SQLITE_API int sqlite3session_patchset_strm(
  11881. sqlite3_session *pSession,
  11882. int (*xOutput)(void *pOut, const void *pData, int nData),
  11883. void *pOut
  11884. );
  11885. SQLITE_API int sqlite3changegroup_add_strm(sqlite3_changegroup*,
  11886. int (*xInput)(void *pIn, void *pData, int *pnData),
  11887. void *pIn
  11888. );
  11889. SQLITE_API int sqlite3changegroup_output_strm(sqlite3_changegroup*,
  11890. int (*xOutput)(void *pOut, const void *pData, int nData),
  11891. void *pOut
  11892. );
  11893. SQLITE_API int sqlite3rebaser_rebase_strm(
  11894. sqlite3_rebaser *pRebaser,
  11895. int (*xInput)(void *pIn, void *pData, int *pnData),
  11896. void *pIn,
  11897. int (*xOutput)(void *pOut, const void *pData, int nData),
  11898. void *pOut
  11899. );
  11900. /*
  11901. ** CAPI3REF: Configure global parameters
  11902. **
  11903. ** The sqlite3session_config() interface is used to make global configuration
  11904. ** changes to the sessions module in order to tune it to the specific needs
  11905. ** of the application.
  11906. **
  11907. ** The sqlite3session_config() interface is not threadsafe. If it is invoked
  11908. ** while any other thread is inside any other sessions method then the
  11909. ** results are undefined. Furthermore, if it is invoked after any sessions
  11910. ** related objects have been created, the results are also undefined.
  11911. **
  11912. ** The first argument to the sqlite3session_config() function must be one
  11913. ** of the SQLITE_SESSION_CONFIG_XXX constants defined below. The
  11914. ** interpretation of the (void*) value passed as the second parameter and
  11915. ** the effect of calling this function depends on the value of the first
  11916. ** parameter.
  11917. **
  11918. ** <dl>
  11919. ** <dt>SQLITE_SESSION_CONFIG_STRMSIZE<dd>
  11920. ** By default, the sessions module streaming interfaces attempt to input
  11921. ** and output data in approximately 1 KiB chunks. This operand may be used
  11922. ** to set and query the value of this configuration setting. The pointer
  11923. ** passed as the second argument must point to a value of type (int).
  11924. ** If this value is greater than 0, it is used as the new streaming data
  11925. ** chunk size for both input and output. Before returning, the (int) value
  11926. ** pointed to by pArg is set to the final value of the streaming interface
  11927. ** chunk size.
  11928. ** </dl>
  11929. **
  11930. ** This function returns SQLITE_OK if successful, or an SQLite error code
  11931. ** otherwise.
  11932. */
  11933. SQLITE_API int sqlite3session_config(int op, void *pArg);
  11934. /*
  11935. ** CAPI3REF: Values for sqlite3session_config().
  11936. */
  11937. #define SQLITE_SESSION_CONFIG_STRMSIZE 1
  11938. /*
  11939. ** Make sure we can call this stuff from C++.
  11940. */
  11941. #if 0
  11942. }
  11943. #endif
  11944. #endif /* !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION) */
  11945. /******** End of sqlite3session.h *********/
  11946. /******** Begin file fts5.h *********/
  11947. /*
  11948. ** 2014 May 31
  11949. **
  11950. ** The author disclaims copyright to this source code. In place of
  11951. ** a legal notice, here is a blessing:
  11952. **
  11953. ** May you do good and not evil.
  11954. ** May you find forgiveness for yourself and forgive others.
  11955. ** May you share freely, never taking more than you give.
  11956. **
  11957. ******************************************************************************
  11958. **
  11959. ** Interfaces to extend FTS5. Using the interfaces defined in this file,
  11960. ** FTS5 may be extended with:
  11961. **
  11962. ** * custom tokenizers, and
  11963. ** * custom auxiliary functions.
  11964. */
  11965. #ifndef _FTS5_H
  11966. #define _FTS5_H
  11967. #if 0
  11968. extern "C" {
  11969. #endif
  11970. /*************************************************************************
  11971. ** CUSTOM AUXILIARY FUNCTIONS
  11972. **
  11973. ** Virtual table implementations may overload SQL functions by implementing
  11974. ** the sqlite3_module.xFindFunction() method.
  11975. */
  11976. typedef struct Fts5ExtensionApi Fts5ExtensionApi;
  11977. typedef struct Fts5Context Fts5Context;
  11978. typedef struct Fts5PhraseIter Fts5PhraseIter;
  11979. typedef void (*fts5_extension_function)(
  11980. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  11981. Fts5Context *pFts, /* First arg to pass to pApi functions */
  11982. sqlite3_context *pCtx, /* Context for returning result/error */
  11983. int nVal, /* Number of values in apVal[] array */
  11984. sqlite3_value **apVal /* Array of trailing arguments */
  11985. );
  11986. struct Fts5PhraseIter {
  11987. const unsigned char *a;
  11988. const unsigned char *b;
  11989. };
  11990. /*
  11991. ** EXTENSION API FUNCTIONS
  11992. **
  11993. ** xUserData(pFts):
  11994. ** Return a copy of the context pointer the extension function was
  11995. ** registered with.
  11996. **
  11997. ** xColumnTotalSize(pFts, iCol, pnToken):
  11998. ** If parameter iCol is less than zero, set output variable *pnToken
  11999. ** to the total number of tokens in the FTS5 table. Or, if iCol is
  12000. ** non-negative but less than the number of columns in the table, return
  12001. ** the total number of tokens in column iCol, considering all rows in
  12002. ** the FTS5 table.
  12003. **
  12004. ** If parameter iCol is greater than or equal to the number of columns
  12005. ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
  12006. ** an OOM condition or IO error), an appropriate SQLite error code is
  12007. ** returned.
  12008. **
  12009. ** xColumnCount(pFts):
  12010. ** Return the number of columns in the table.
  12011. **
  12012. ** xColumnSize(pFts, iCol, pnToken):
  12013. ** If parameter iCol is less than zero, set output variable *pnToken
  12014. ** to the total number of tokens in the current row. Or, if iCol is
  12015. ** non-negative but less than the number of columns in the table, set
  12016. ** *pnToken to the number of tokens in column iCol of the current row.
  12017. **
  12018. ** If parameter iCol is greater than or equal to the number of columns
  12019. ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
  12020. ** an OOM condition or IO error), an appropriate SQLite error code is
  12021. ** returned.
  12022. **
  12023. ** This function may be quite inefficient if used with an FTS5 table
  12024. ** created with the "columnsize=0" option.
  12025. **
  12026. ** xColumnText:
  12027. ** This function attempts to retrieve the text of column iCol of the
  12028. ** current document. If successful, (*pz) is set to point to a buffer
  12029. ** containing the text in utf-8 encoding, (*pn) is set to the size in bytes
  12030. ** (not characters) of the buffer and SQLITE_OK is returned. Otherwise,
  12031. ** if an error occurs, an SQLite error code is returned and the final values
  12032. ** of (*pz) and (*pn) are undefined.
  12033. **
  12034. ** xPhraseCount:
  12035. ** Returns the number of phrases in the current query expression.
  12036. **
  12037. ** xPhraseSize:
  12038. ** Returns the number of tokens in phrase iPhrase of the query. Phrases
  12039. ** are numbered starting from zero.
  12040. **
  12041. ** xInstCount:
  12042. ** Set *pnInst to the total number of occurrences of all phrases within
  12043. ** the query within the current row. Return SQLITE_OK if successful, or
  12044. ** an error code (i.e. SQLITE_NOMEM) if an error occurs.
  12045. **
  12046. ** This API can be quite slow if used with an FTS5 table created with the
  12047. ** "detail=none" or "detail=column" option. If the FTS5 table is created
  12048. ** with either "detail=none" or "detail=column" and "content=" option
  12049. ** (i.e. if it is a contentless table), then this API always returns 0.
  12050. **
  12051. ** xInst:
  12052. ** Query for the details of phrase match iIdx within the current row.
  12053. ** Phrase matches are numbered starting from zero, so the iIdx argument
  12054. ** should be greater than or equal to zero and smaller than the value
  12055. ** output by xInstCount().
  12056. **
  12057. ** Usually, output parameter *piPhrase is set to the phrase number, *piCol
  12058. ** to the column in which it occurs and *piOff the token offset of the
  12059. ** first token of the phrase. Returns SQLITE_OK if successful, or an error
  12060. ** code (i.e. SQLITE_NOMEM) if an error occurs.
  12061. **
  12062. ** This API can be quite slow if used with an FTS5 table created with the
  12063. ** "detail=none" or "detail=column" option.
  12064. **
  12065. ** xRowid:
  12066. ** Returns the rowid of the current row.
  12067. **
  12068. ** xTokenize:
  12069. ** Tokenize text using the tokenizer belonging to the FTS5 table.
  12070. **
  12071. ** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):
  12072. ** This API function is used to query the FTS table for phrase iPhrase
  12073. ** of the current query. Specifically, a query equivalent to:
  12074. **
  12075. ** ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
  12076. **
  12077. ** with $p set to a phrase equivalent to the phrase iPhrase of the
  12078. ** current query is executed. Any column filter that applies to
  12079. ** phrase iPhrase of the current query is included in $p. For each
  12080. ** row visited, the callback function passed as the fourth argument
  12081. ** is invoked. The context and API objects passed to the callback
  12082. ** function may be used to access the properties of each matched row.
  12083. ** Invoking Api.xUserData() returns a copy of the pointer passed as
  12084. ** the third argument to pUserData.
  12085. **
  12086. ** If the callback function returns any value other than SQLITE_OK, the
  12087. ** query is abandoned and the xQueryPhrase function returns immediately.
  12088. ** If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
  12089. ** Otherwise, the error code is propagated upwards.
  12090. **
  12091. ** If the query runs to completion without incident, SQLITE_OK is returned.
  12092. ** Or, if some error occurs before the query completes or is aborted by
  12093. ** the callback, an SQLite error code is returned.
  12094. **
  12095. **
  12096. ** xSetAuxdata(pFts5, pAux, xDelete)
  12097. **
  12098. ** Save the pointer passed as the second argument as the extension functions
  12099. ** "auxiliary data". The pointer may then be retrieved by the current or any
  12100. ** future invocation of the same fts5 extension function made as part of
  12101. ** the same MATCH query using the xGetAuxdata() API.
  12102. **
  12103. ** Each extension function is allocated a single auxiliary data slot for
  12104. ** each FTS query (MATCH expression). If the extension function is invoked
  12105. ** more than once for a single FTS query, then all invocations share a
  12106. ** single auxiliary data context.
  12107. **
  12108. ** If there is already an auxiliary data pointer when this function is
  12109. ** invoked, then it is replaced by the new pointer. If an xDelete callback
  12110. ** was specified along with the original pointer, it is invoked at this
  12111. ** point.
  12112. **
  12113. ** The xDelete callback, if one is specified, is also invoked on the
  12114. ** auxiliary data pointer after the FTS5 query has finished.
  12115. **
  12116. ** If an error (e.g. an OOM condition) occurs within this function,
  12117. ** the auxiliary data is set to NULL and an error code returned. If the
  12118. ** xDelete parameter was not NULL, it is invoked on the auxiliary data
  12119. ** pointer before returning.
  12120. **
  12121. **
  12122. ** xGetAuxdata(pFts5, bClear)
  12123. **
  12124. ** Returns the current auxiliary data pointer for the fts5 extension
  12125. ** function. See the xSetAuxdata() method for details.
  12126. **
  12127. ** If the bClear argument is non-zero, then the auxiliary data is cleared
  12128. ** (set to NULL) before this function returns. In this case the xDelete,
  12129. ** if any, is not invoked.
  12130. **
  12131. **
  12132. ** xRowCount(pFts5, pnRow)
  12133. **
  12134. ** This function is used to retrieve the total number of rows in the table.
  12135. ** In other words, the same value that would be returned by:
  12136. **
  12137. ** SELECT count(*) FROM ftstable;
  12138. **
  12139. ** xPhraseFirst()
  12140. ** This function is used, along with type Fts5PhraseIter and the xPhraseNext
  12141. ** method, to iterate through all instances of a single query phrase within
  12142. ** the current row. This is the same information as is accessible via the
  12143. ** xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
  12144. ** to use, this API may be faster under some circumstances. To iterate
  12145. ** through instances of phrase iPhrase, use the following code:
  12146. **
  12147. ** Fts5PhraseIter iter;
  12148. ** int iCol, iOff;
  12149. ** for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
  12150. ** iCol>=0;
  12151. ** pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
  12152. ** ){
  12153. ** // An instance of phrase iPhrase at offset iOff of column iCol
  12154. ** }
  12155. **
  12156. ** The Fts5PhraseIter structure is defined above. Applications should not
  12157. ** modify this structure directly - it should only be used as shown above
  12158. ** with the xPhraseFirst() and xPhraseNext() API methods (and by
  12159. ** xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below).
  12160. **
  12161. ** This API can be quite slow if used with an FTS5 table created with the
  12162. ** "detail=none" or "detail=column" option. If the FTS5 table is created
  12163. ** with either "detail=none" or "detail=column" and "content=" option
  12164. ** (i.e. if it is a contentless table), then this API always iterates
  12165. ** through an empty set (all calls to xPhraseFirst() set iCol to -1).
  12166. **
  12167. ** xPhraseNext()
  12168. ** See xPhraseFirst above.
  12169. **
  12170. ** xPhraseFirstColumn()
  12171. ** This function and xPhraseNextColumn() are similar to the xPhraseFirst()
  12172. ** and xPhraseNext() APIs described above. The difference is that instead
  12173. ** of iterating through all instances of a phrase in the current row, these
  12174. ** APIs are used to iterate through the set of columns in the current row
  12175. ** that contain one or more instances of a specified phrase. For example:
  12176. **
  12177. ** Fts5PhraseIter iter;
  12178. ** int iCol;
  12179. ** for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol);
  12180. ** iCol>=0;
  12181. ** pApi->xPhraseNextColumn(pFts, &iter, &iCol)
  12182. ** ){
  12183. ** // Column iCol contains at least one instance of phrase iPhrase
  12184. ** }
  12185. **
  12186. ** This API can be quite slow if used with an FTS5 table created with the
  12187. ** "detail=none" option. If the FTS5 table is created with either
  12188. ** "detail=none" "content=" option (i.e. if it is a contentless table),
  12189. ** then this API always iterates through an empty set (all calls to
  12190. ** xPhraseFirstColumn() set iCol to -1).
  12191. **
  12192. ** The information accessed using this API and its companion
  12193. ** xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext
  12194. ** (or xInst/xInstCount). The chief advantage of this API is that it is
  12195. ** significantly more efficient than those alternatives when used with
  12196. ** "detail=column" tables.
  12197. **
  12198. ** xPhraseNextColumn()
  12199. ** See xPhraseFirstColumn above.
  12200. */
  12201. struct Fts5ExtensionApi {
  12202. int iVersion; /* Currently always set to 3 */
  12203. void *(*xUserData)(Fts5Context*);
  12204. int (*xColumnCount)(Fts5Context*);
  12205. int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
  12206. int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
  12207. int (*xTokenize)(Fts5Context*,
  12208. const char *pText, int nText, /* Text to tokenize */
  12209. void *pCtx, /* Context passed to xToken() */
  12210. int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
  12211. );
  12212. int (*xPhraseCount)(Fts5Context*);
  12213. int (*xPhraseSize)(Fts5Context*, int iPhrase);
  12214. int (*xInstCount)(Fts5Context*, int *pnInst);
  12215. int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);
  12216. sqlite3_int64 (*xRowid)(Fts5Context*);
  12217. int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);
  12218. int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);
  12219. int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,
  12220. int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)
  12221. );
  12222. int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));
  12223. void *(*xGetAuxdata)(Fts5Context*, int bClear);
  12224. int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);
  12225. void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);
  12226. int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*);
  12227. void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol);
  12228. };
  12229. /*
  12230. ** CUSTOM AUXILIARY FUNCTIONS
  12231. *************************************************************************/
  12232. /*************************************************************************
  12233. ** CUSTOM TOKENIZERS
  12234. **
  12235. ** Applications may also register custom tokenizer types. A tokenizer
  12236. ** is registered by providing fts5 with a populated instance of the
  12237. ** following structure. All structure methods must be defined, setting
  12238. ** any member of the fts5_tokenizer struct to NULL leads to undefined
  12239. ** behaviour. The structure methods are expected to function as follows:
  12240. **
  12241. ** xCreate:
  12242. ** This function is used to allocate and initialize a tokenizer instance.
  12243. ** A tokenizer instance is required to actually tokenize text.
  12244. **
  12245. ** The first argument passed to this function is a copy of the (void*)
  12246. ** pointer provided by the application when the fts5_tokenizer object
  12247. ** was registered with FTS5 (the third argument to xCreateTokenizer()).
  12248. ** The second and third arguments are an array of nul-terminated strings
  12249. ** containing the tokenizer arguments, if any, specified following the
  12250. ** tokenizer name as part of the CREATE VIRTUAL TABLE statement used
  12251. ** to create the FTS5 table.
  12252. **
  12253. ** The final argument is an output variable. If successful, (*ppOut)
  12254. ** should be set to point to the new tokenizer handle and SQLITE_OK
  12255. ** returned. If an error occurs, some value other than SQLITE_OK should
  12256. ** be returned. In this case, fts5 assumes that the final value of *ppOut
  12257. ** is undefined.
  12258. **
  12259. ** xDelete:
  12260. ** This function is invoked to delete a tokenizer handle previously
  12261. ** allocated using xCreate(). Fts5 guarantees that this function will
  12262. ** be invoked exactly once for each successful call to xCreate().
  12263. **
  12264. ** xTokenize:
  12265. ** This function is expected to tokenize the nText byte string indicated
  12266. ** by argument pText. pText may or may not be nul-terminated. The first
  12267. ** argument passed to this function is a pointer to an Fts5Tokenizer object
  12268. ** returned by an earlier call to xCreate().
  12269. **
  12270. ** The second argument indicates the reason that FTS5 is requesting
  12271. ** tokenization of the supplied text. This is always one of the following
  12272. ** four values:
  12273. **
  12274. ** <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into
  12275. ** or removed from the FTS table. The tokenizer is being invoked to
  12276. ** determine the set of tokens to add to (or delete from) the
  12277. ** FTS index.
  12278. **
  12279. ** <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed
  12280. ** against the FTS index. The tokenizer is being called to tokenize
  12281. ** a bareword or quoted string specified as part of the query.
  12282. **
  12283. ** <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
  12284. ** FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is
  12285. ** followed by a "*" character, indicating that the last token
  12286. ** returned by the tokenizer will be treated as a token prefix.
  12287. **
  12288. ** <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to
  12289. ** satisfy an fts5_api.xTokenize() request made by an auxiliary
  12290. ** function. Or an fts5_api.xColumnSize() request made by the same
  12291. ** on a columnsize=0 database.
  12292. ** </ul>
  12293. **
  12294. ** For each token in the input string, the supplied callback xToken() must
  12295. ** be invoked. The first argument to it should be a copy of the pointer
  12296. ** passed as the second argument to xTokenize(). The third and fourth
  12297. ** arguments are a pointer to a buffer containing the token text, and the
  12298. ** size of the token in bytes. The 4th and 5th arguments are the byte offsets
  12299. ** of the first byte of and first byte immediately following the text from
  12300. ** which the token is derived within the input.
  12301. **
  12302. ** The second argument passed to the xToken() callback ("tflags") should
  12303. ** normally be set to 0. The exception is if the tokenizer supports
  12304. ** synonyms. In this case see the discussion below for details.
  12305. **
  12306. ** FTS5 assumes the xToken() callback is invoked for each token in the
  12307. ** order that they occur within the input text.
  12308. **
  12309. ** If an xToken() callback returns any value other than SQLITE_OK, then
  12310. ** the tokenization should be abandoned and the xTokenize() method should
  12311. ** immediately return a copy of the xToken() return value. Or, if the
  12312. ** input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,
  12313. ** if an error occurs with the xTokenize() implementation itself, it
  12314. ** may abandon the tokenization and return any error code other than
  12315. ** SQLITE_OK or SQLITE_DONE.
  12316. **
  12317. ** SYNONYM SUPPORT
  12318. **
  12319. ** Custom tokenizers may also support synonyms. Consider a case in which a
  12320. ** user wishes to query for a phrase such as "first place". Using the
  12321. ** built-in tokenizers, the FTS5 query 'first + place' will match instances
  12322. ** of "first place" within the document set, but not alternative forms
  12323. ** such as "1st place". In some applications, it would be better to match
  12324. ** all instances of "first place" or "1st place" regardless of which form
  12325. ** the user specified in the MATCH query text.
  12326. **
  12327. ** There are several ways to approach this in FTS5:
  12328. **
  12329. ** <ol><li> By mapping all synonyms to a single token. In this case, the
  12330. ** In the above example, this means that the tokenizer returns the
  12331. ** same token for inputs "first" and "1st". Say that token is in
  12332. ** fact "first", so that when the user inserts the document "I won
  12333. ** 1st place" entries are added to the index for tokens "i", "won",
  12334. ** "first" and "place". If the user then queries for '1st + place',
  12335. ** the tokenizer substitutes "first" for "1st" and the query works
  12336. ** as expected.
  12337. **
  12338. ** <li> By querying the index for all synonyms of each query term
  12339. ** separately. In this case, when tokenizing query text, the
  12340. ** tokenizer may provide multiple synonyms for a single term
  12341. ** within the document. FTS5 then queries the index for each
  12342. ** synonym individually. For example, faced with the query:
  12343. **
  12344. ** <codeblock>
  12345. ** ... MATCH 'first place'</codeblock>
  12346. **
  12347. ** the tokenizer offers both "1st" and "first" as synonyms for the
  12348. ** first token in the MATCH query and FTS5 effectively runs a query
  12349. ** similar to:
  12350. **
  12351. ** <codeblock>
  12352. ** ... MATCH '(first OR 1st) place'</codeblock>
  12353. **
  12354. ** except that, for the purposes of auxiliary functions, the query
  12355. ** still appears to contain just two phrases - "(first OR 1st)"
  12356. ** being treated as a single phrase.
  12357. **
  12358. ** <li> By adding multiple synonyms for a single term to the FTS index.
  12359. ** Using this method, when tokenizing document text, the tokenizer
  12360. ** provides multiple synonyms for each token. So that when a
  12361. ** document such as "I won first place" is tokenized, entries are
  12362. ** added to the FTS index for "i", "won", "first", "1st" and
  12363. ** "place".
  12364. **
  12365. ** This way, even if the tokenizer does not provide synonyms
  12366. ** when tokenizing query text (it should not - to do so would be
  12367. ** inefficient), it doesn't matter if the user queries for
  12368. ** 'first + place' or '1st + place', as there are entries in the
  12369. ** FTS index corresponding to both forms of the first token.
  12370. ** </ol>
  12371. **
  12372. ** Whether it is parsing document or query text, any call to xToken that
  12373. ** specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit
  12374. ** is considered to supply a synonym for the previous token. For example,
  12375. ** when parsing the document "I won first place", a tokenizer that supports
  12376. ** synonyms would call xToken() 5 times, as follows:
  12377. **
  12378. ** <codeblock>
  12379. ** xToken(pCtx, 0, "i", 1, 0, 1);
  12380. ** xToken(pCtx, 0, "won", 3, 2, 5);
  12381. ** xToken(pCtx, 0, "first", 5, 6, 11);
  12382. ** xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3, 6, 11);
  12383. ** xToken(pCtx, 0, "place", 5, 12, 17);
  12384. **</codeblock>
  12385. **
  12386. ** It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
  12387. ** xToken() is called. Multiple synonyms may be specified for a single token
  12388. ** by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence.
  12389. ** There is no limit to the number of synonyms that may be provided for a
  12390. ** single token.
  12391. **
  12392. ** In many cases, method (1) above is the best approach. It does not add
  12393. ** extra data to the FTS index or require FTS5 to query for multiple terms,
  12394. ** so it is efficient in terms of disk space and query speed. However, it
  12395. ** does not support prefix queries very well. If, as suggested above, the
  12396. ** token "first" is substituted for "1st" by the tokenizer, then the query:
  12397. **
  12398. ** <codeblock>
  12399. ** ... MATCH '1s*'</codeblock>
  12400. **
  12401. ** will not match documents that contain the token "1st" (as the tokenizer
  12402. ** will probably not map "1s" to any prefix of "first").
  12403. **
  12404. ** For full prefix support, method (3) may be preferred. In this case,
  12405. ** because the index contains entries for both "first" and "1st", prefix
  12406. ** queries such as 'fi*' or '1s*' will match correctly. However, because
  12407. ** extra entries are added to the FTS index, this method uses more space
  12408. ** within the database.
  12409. **
  12410. ** Method (2) offers a midpoint between (1) and (3). Using this method,
  12411. ** a query such as '1s*' will match documents that contain the literal
  12412. ** token "1st", but not "first" (assuming the tokenizer is not able to
  12413. ** provide synonyms for prefixes). However, a non-prefix query like '1st'
  12414. ** will match against "1st" and "first". This method does not require
  12415. ** extra disk space, as no extra entries are added to the FTS index.
  12416. ** On the other hand, it may require more CPU cycles to run MATCH queries,
  12417. ** as separate queries of the FTS index are required for each synonym.
  12418. **
  12419. ** When using methods (2) or (3), it is important that the tokenizer only
  12420. ** provide synonyms when tokenizing document text (method (2)) or query
  12421. ** text (method (3)), not both. Doing so will not cause any errors, but is
  12422. ** inefficient.
  12423. */
  12424. typedef struct Fts5Tokenizer Fts5Tokenizer;
  12425. typedef struct fts5_tokenizer fts5_tokenizer;
  12426. struct fts5_tokenizer {
  12427. int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
  12428. void (*xDelete)(Fts5Tokenizer*);
  12429. int (*xTokenize)(Fts5Tokenizer*,
  12430. void *pCtx,
  12431. int flags, /* Mask of FTS5_TOKENIZE_* flags */
  12432. const char *pText, int nText,
  12433. int (*xToken)(
  12434. void *pCtx, /* Copy of 2nd argument to xTokenize() */
  12435. int tflags, /* Mask of FTS5_TOKEN_* flags */
  12436. const char *pToken, /* Pointer to buffer containing token */
  12437. int nToken, /* Size of token in bytes */
  12438. int iStart, /* Byte offset of token within input text */
  12439. int iEnd /* Byte offset of end of token within input text */
  12440. )
  12441. );
  12442. };
  12443. /* Flags that may be passed as the third argument to xTokenize() */
  12444. #define FTS5_TOKENIZE_QUERY 0x0001
  12445. #define FTS5_TOKENIZE_PREFIX 0x0002
  12446. #define FTS5_TOKENIZE_DOCUMENT 0x0004
  12447. #define FTS5_TOKENIZE_AUX 0x0008
  12448. /* Flags that may be passed by the tokenizer implementation back to FTS5
  12449. ** as the third argument to the supplied xToken callback. */
  12450. #define FTS5_TOKEN_COLOCATED 0x0001 /* Same position as prev. token */
  12451. /*
  12452. ** END OF CUSTOM TOKENIZERS
  12453. *************************************************************************/
  12454. /*************************************************************************
  12455. ** FTS5 EXTENSION REGISTRATION API
  12456. */
  12457. typedef struct fts5_api fts5_api;
  12458. struct fts5_api {
  12459. int iVersion; /* Currently always set to 2 */
  12460. /* Create a new tokenizer */
  12461. int (*xCreateTokenizer)(
  12462. fts5_api *pApi,
  12463. const char *zName,
  12464. void *pContext,
  12465. fts5_tokenizer *pTokenizer,
  12466. void (*xDestroy)(void*)
  12467. );
  12468. /* Find an existing tokenizer */
  12469. int (*xFindTokenizer)(
  12470. fts5_api *pApi,
  12471. const char *zName,
  12472. void **ppContext,
  12473. fts5_tokenizer *pTokenizer
  12474. );
  12475. /* Create a new auxiliary function */
  12476. int (*xCreateFunction)(
  12477. fts5_api *pApi,
  12478. const char *zName,
  12479. void *pContext,
  12480. fts5_extension_function xFunction,
  12481. void (*xDestroy)(void*)
  12482. );
  12483. };
  12484. /*
  12485. ** END OF REGISTRATION API
  12486. *************************************************************************/
  12487. #if 0
  12488. } /* end of the 'extern "C"' block */
  12489. #endif
  12490. #endif /* _FTS5_H */
  12491. /******** End of fts5.h *********/
  12492. /************** End of sqlite3.h *********************************************/
  12493. /************** Continuing where we left off in sqliteInt.h ******************/
  12494. /*
  12495. ** Include the configuration header output by 'configure' if we're using the
  12496. ** autoconf-based build
  12497. */
  12498. #if defined(_HAVE_SQLITE_CONFIG_H) && !defined(SQLITECONFIG_H)
  12499. /* #include "config.h" */
  12500. #define SQLITECONFIG_H 1
  12501. #endif
  12502. /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
  12503. /************** Begin file sqliteLimit.h *************************************/
  12504. /*
  12505. ** 2007 May 7
  12506. **
  12507. ** The author disclaims copyright to this source code. In place of
  12508. ** a legal notice, here is a blessing:
  12509. **
  12510. ** May you do good and not evil.
  12511. ** May you find forgiveness for yourself and forgive others.
  12512. ** May you share freely, never taking more than you give.
  12513. **
  12514. *************************************************************************
  12515. **
  12516. ** This file defines various limits of what SQLite can process.
  12517. */
  12518. /*
  12519. ** The maximum length of a TEXT or BLOB in bytes. This also
  12520. ** limits the size of a row in a table or index.
  12521. **
  12522. ** The hard limit is the ability of a 32-bit signed integer
  12523. ** to count the size: 2^31-1 or 2147483647.
  12524. */
  12525. #ifndef SQLITE_MAX_LENGTH
  12526. # define SQLITE_MAX_LENGTH 1000000000
  12527. #endif
  12528. /*
  12529. ** This is the maximum number of
  12530. **
  12531. ** * Columns in a table
  12532. ** * Columns in an index
  12533. ** * Columns in a view
  12534. ** * Terms in the SET clause of an UPDATE statement
  12535. ** * Terms in the result set of a SELECT statement
  12536. ** * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
  12537. ** * Terms in the VALUES clause of an INSERT statement
  12538. **
  12539. ** The hard upper limit here is 32676. Most database people will
  12540. ** tell you that in a well-normalized database, you usually should
  12541. ** not have more than a dozen or so columns in any table. And if
  12542. ** that is the case, there is no point in having more than a few
  12543. ** dozen values in any of the other situations described above.
  12544. */
  12545. #ifndef SQLITE_MAX_COLUMN
  12546. # define SQLITE_MAX_COLUMN 2000
  12547. #endif
  12548. /*
  12549. ** The maximum length of a single SQL statement in bytes.
  12550. **
  12551. ** It used to be the case that setting this value to zero would
  12552. ** turn the limit off. That is no longer true. It is not possible
  12553. ** to turn this limit off.
  12554. */
  12555. #ifndef SQLITE_MAX_SQL_LENGTH
  12556. # define SQLITE_MAX_SQL_LENGTH 1000000000
  12557. #endif
  12558. /*
  12559. ** The maximum depth of an expression tree. This is limited to
  12560. ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
  12561. ** want to place more severe limits on the complexity of an
  12562. ** expression.
  12563. **
  12564. ** A value of 0 used to mean that the limit was not enforced.
  12565. ** But that is no longer true. The limit is now strictly enforced
  12566. ** at all times.
  12567. */
  12568. #ifndef SQLITE_MAX_EXPR_DEPTH
  12569. # define SQLITE_MAX_EXPR_DEPTH 1000
  12570. #endif
  12571. /*
  12572. ** The maximum number of terms in a compound SELECT statement.
  12573. ** The code generator for compound SELECT statements does one
  12574. ** level of recursion for each term. A stack overflow can result
  12575. ** if the number of terms is too large. In practice, most SQL
  12576. ** never has more than 3 or 4 terms. Use a value of 0 to disable
  12577. ** any limit on the number of terms in a compount SELECT.
  12578. */
  12579. #ifndef SQLITE_MAX_COMPOUND_SELECT
  12580. # define SQLITE_MAX_COMPOUND_SELECT 500
  12581. #endif
  12582. /*
  12583. ** The maximum number of opcodes in a VDBE program.
  12584. ** Not currently enforced.
  12585. */
  12586. #ifndef SQLITE_MAX_VDBE_OP
  12587. # define SQLITE_MAX_VDBE_OP 250000000
  12588. #endif
  12589. /*
  12590. ** The maximum number of arguments to an SQL function.
  12591. */
  12592. #ifndef SQLITE_MAX_FUNCTION_ARG
  12593. # define SQLITE_MAX_FUNCTION_ARG 127
  12594. #endif
  12595. /*
  12596. ** The suggested maximum number of in-memory pages to use for
  12597. ** the main database table and for temporary tables.
  12598. **
  12599. ** IMPLEMENTATION-OF: R-30185-15359 The default suggested cache size is -2000,
  12600. ** which means the cache size is limited to 2048000 bytes of memory.
  12601. ** IMPLEMENTATION-OF: R-48205-43578 The default suggested cache size can be
  12602. ** altered using the SQLITE_DEFAULT_CACHE_SIZE compile-time options.
  12603. */
  12604. #ifndef SQLITE_DEFAULT_CACHE_SIZE
  12605. # define SQLITE_DEFAULT_CACHE_SIZE -2000
  12606. #endif
  12607. /*
  12608. ** The default number of frames to accumulate in the log file before
  12609. ** checkpointing the database in WAL mode.
  12610. */
  12611. #ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
  12612. # define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT 1000
  12613. #endif
  12614. /*
  12615. ** The maximum number of attached databases. This must be between 0
  12616. ** and 125. The upper bound of 125 is because the attached databases are
  12617. ** counted using a signed 8-bit integer which has a maximum value of 127
  12618. ** and we have to allow 2 extra counts for the "main" and "temp" databases.
  12619. */
  12620. #ifndef SQLITE_MAX_ATTACHED
  12621. # define SQLITE_MAX_ATTACHED 10
  12622. #endif
  12623. /*
  12624. ** The maximum value of a ?nnn wildcard that the parser will accept.
  12625. */
  12626. #ifndef SQLITE_MAX_VARIABLE_NUMBER
  12627. # define SQLITE_MAX_VARIABLE_NUMBER 999
  12628. #endif
  12629. /* Maximum page size. The upper bound on this value is 65536. This a limit
  12630. ** imposed by the use of 16-bit offsets within each page.
  12631. **
  12632. ** Earlier versions of SQLite allowed the user to change this value at
  12633. ** compile time. This is no longer permitted, on the grounds that it creates
  12634. ** a library that is technically incompatible with an SQLite library
  12635. ** compiled with a different limit. If a process operating on a database
  12636. ** with a page-size of 65536 bytes crashes, then an instance of SQLite
  12637. ** compiled with the default page-size limit will not be able to rollback
  12638. ** the aborted transaction. This could lead to database corruption.
  12639. */
  12640. #ifdef SQLITE_MAX_PAGE_SIZE
  12641. # undef SQLITE_MAX_PAGE_SIZE
  12642. #endif
  12643. #define SQLITE_MAX_PAGE_SIZE 65536
  12644. /*
  12645. ** The default size of a database page.
  12646. */
  12647. #ifndef SQLITE_DEFAULT_PAGE_SIZE
  12648. # define SQLITE_DEFAULT_PAGE_SIZE 4096
  12649. #endif
  12650. #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
  12651. # undef SQLITE_DEFAULT_PAGE_SIZE
  12652. # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
  12653. #endif
  12654. /*
  12655. ** Ordinarily, if no value is explicitly provided, SQLite creates databases
  12656. ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
  12657. ** device characteristics (sector-size and atomic write() support),
  12658. ** SQLite may choose a larger value. This constant is the maximum value
  12659. ** SQLite will choose on its own.
  12660. */
  12661. #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
  12662. # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
  12663. #endif
  12664. #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
  12665. # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
  12666. # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
  12667. #endif
  12668. /*
  12669. ** Maximum number of pages in one database file.
  12670. **
  12671. ** This is really just the default value for the max_page_count pragma.
  12672. ** This value can be lowered (or raised) at run-time using that the
  12673. ** max_page_count macro.
  12674. */
  12675. #ifndef SQLITE_MAX_PAGE_COUNT
  12676. # define SQLITE_MAX_PAGE_COUNT 1073741823
  12677. #endif
  12678. /*
  12679. ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
  12680. ** operator.
  12681. */
  12682. #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
  12683. # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
  12684. #endif
  12685. /*
  12686. ** Maximum depth of recursion for triggers.
  12687. **
  12688. ** A value of 1 means that a trigger program will not be able to itself
  12689. ** fire any triggers. A value of 0 means that no trigger programs at all
  12690. ** may be executed.
  12691. */
  12692. #ifndef SQLITE_MAX_TRIGGER_DEPTH
  12693. # define SQLITE_MAX_TRIGGER_DEPTH 1000
  12694. #endif
  12695. /************** End of sqliteLimit.h *****************************************/
  12696. /************** Continuing where we left off in sqliteInt.h ******************/
  12697. /* Disable nuisance warnings on Borland compilers */
  12698. #if defined(__BORLANDC__)
  12699. #pragma warn -rch /* unreachable code */
  12700. #pragma warn -ccc /* Condition is always true or false */
  12701. #pragma warn -aus /* Assigned value is never used */
  12702. #pragma warn -csu /* Comparing signed and unsigned */
  12703. #pragma warn -spa /* Suspicious pointer arithmetic */
  12704. #endif
  12705. /*
  12706. ** Include standard header files as necessary
  12707. */
  12708. #ifdef HAVE_STDINT_H
  12709. #include <stdint.h>
  12710. #endif
  12711. #ifdef HAVE_INTTYPES_H
  12712. #include <inttypes.h>
  12713. #endif
  12714. /*
  12715. ** The following macros are used to cast pointers to integers and
  12716. ** integers to pointers. The way you do this varies from one compiler
  12717. ** to the next, so we have developed the following set of #if statements
  12718. ** to generate appropriate macros for a wide range of compilers.
  12719. **
  12720. ** The correct "ANSI" way to do this is to use the intptr_t type.
  12721. ** Unfortunately, that typedef is not available on all compilers, or
  12722. ** if it is available, it requires an #include of specific headers
  12723. ** that vary from one machine to the next.
  12724. **
  12725. ** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on
  12726. ** the ((void*)&((char*)0)[X]) construct. But MSVC chokes on ((void*)(X)).
  12727. ** So we have to define the macros in different ways depending on the
  12728. ** compiler.
  12729. */
  12730. #if defined(__PTRDIFF_TYPE__) /* This case should work for GCC */
  12731. # define SQLITE_INT_TO_PTR(X) ((void*)(__PTRDIFF_TYPE__)(X))
  12732. # define SQLITE_PTR_TO_INT(X) ((int)(__PTRDIFF_TYPE__)(X))
  12733. #elif !defined(__GNUC__) /* Works for compilers other than LLVM */
  12734. # define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X])
  12735. # define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0))
  12736. #elif defined(HAVE_STDINT_H) /* Use this case if we have ANSI headers */
  12737. # define SQLITE_INT_TO_PTR(X) ((void*)(intptr_t)(X))
  12738. # define SQLITE_PTR_TO_INT(X) ((int)(intptr_t)(X))
  12739. #else /* Generates a warning - but it always works */
  12740. # define SQLITE_INT_TO_PTR(X) ((void*)(X))
  12741. # define SQLITE_PTR_TO_INT(X) ((int)(X))
  12742. #endif
  12743. /*
  12744. ** A macro to hint to the compiler that a function should not be
  12745. ** inlined.
  12746. */
  12747. #if defined(__GNUC__)
  12748. # define SQLITE_NOINLINE __attribute__((noinline))
  12749. #elif defined(_MSC_VER) && _MSC_VER>=1310
  12750. # define SQLITE_NOINLINE __declspec(noinline)
  12751. #else
  12752. # define SQLITE_NOINLINE
  12753. #endif
  12754. /*
  12755. ** Make sure that the compiler intrinsics we desire are enabled when
  12756. ** compiling with an appropriate version of MSVC unless prevented by
  12757. ** the SQLITE_DISABLE_INTRINSIC define.
  12758. */
  12759. #if !defined(SQLITE_DISABLE_INTRINSIC)
  12760. # if defined(_MSC_VER) && _MSC_VER>=1400
  12761. # if !defined(_WIN32_WCE)
  12762. # include <intrin.h>
  12763. # pragma intrinsic(_byteswap_ushort)
  12764. # pragma intrinsic(_byteswap_ulong)
  12765. # pragma intrinsic(_byteswap_uint64)
  12766. # pragma intrinsic(_ReadWriteBarrier)
  12767. # else
  12768. # include <cmnintrin.h>
  12769. # endif
  12770. # endif
  12771. #endif
  12772. /*
  12773. ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
  12774. ** 0 means mutexes are permanently disable and the library is never
  12775. ** threadsafe. 1 means the library is serialized which is the highest
  12776. ** level of threadsafety. 2 means the library is multithreaded - multiple
  12777. ** threads can use SQLite as long as no two threads try to use the same
  12778. ** database connection at the same time.
  12779. **
  12780. ** Older versions of SQLite used an optional THREADSAFE macro.
  12781. ** We support that for legacy.
  12782. **
  12783. ** To ensure that the correct value of "THREADSAFE" is reported when querying
  12784. ** for compile-time options at runtime (e.g. "PRAGMA compile_options"), this
  12785. ** logic is partially replicated in ctime.c. If it is updated here, it should
  12786. ** also be updated there.
  12787. */
  12788. #if !defined(SQLITE_THREADSAFE)
  12789. # if defined(THREADSAFE)
  12790. # define SQLITE_THREADSAFE THREADSAFE
  12791. # else
  12792. # define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
  12793. # endif
  12794. #endif
  12795. /*
  12796. ** Powersafe overwrite is on by default. But can be turned off using
  12797. ** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
  12798. */
  12799. #ifndef SQLITE_POWERSAFE_OVERWRITE
  12800. # define SQLITE_POWERSAFE_OVERWRITE 1
  12801. #endif
  12802. /*
  12803. ** EVIDENCE-OF: R-25715-37072 Memory allocation statistics are enabled by
  12804. ** default unless SQLite is compiled with SQLITE_DEFAULT_MEMSTATUS=0 in
  12805. ** which case memory allocation statistics are disabled by default.
  12806. */
  12807. #if !defined(SQLITE_DEFAULT_MEMSTATUS)
  12808. # define SQLITE_DEFAULT_MEMSTATUS 1
  12809. #endif
  12810. /*
  12811. ** Exactly one of the following macros must be defined in order to
  12812. ** specify which memory allocation subsystem to use.
  12813. **
  12814. ** SQLITE_SYSTEM_MALLOC // Use normal system malloc()
  12815. ** SQLITE_WIN32_MALLOC // Use Win32 native heap API
  12816. ** SQLITE_ZERO_MALLOC // Use a stub allocator that always fails
  12817. ** SQLITE_MEMDEBUG // Debugging version of system malloc()
  12818. **
  12819. ** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
  12820. ** assert() macro is enabled, each call into the Win32 native heap subsystem
  12821. ** will cause HeapValidate to be called. If heap validation should fail, an
  12822. ** assertion will be triggered.
  12823. **
  12824. ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
  12825. ** the default.
  12826. */
  12827. #if defined(SQLITE_SYSTEM_MALLOC) \
  12828. + defined(SQLITE_WIN32_MALLOC) \
  12829. + defined(SQLITE_ZERO_MALLOC) \
  12830. + defined(SQLITE_MEMDEBUG)>1
  12831. # error "Two or more of the following compile-time configuration options\
  12832. are defined but at most one is allowed:\
  12833. SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
  12834. SQLITE_ZERO_MALLOC"
  12835. #endif
  12836. #if defined(SQLITE_SYSTEM_MALLOC) \
  12837. + defined(SQLITE_WIN32_MALLOC) \
  12838. + defined(SQLITE_ZERO_MALLOC) \
  12839. + defined(SQLITE_MEMDEBUG)==0
  12840. # define SQLITE_SYSTEM_MALLOC 1
  12841. #endif
  12842. /*
  12843. ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
  12844. ** sizes of memory allocations below this value where possible.
  12845. */
  12846. #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
  12847. # define SQLITE_MALLOC_SOFT_LIMIT 1024
  12848. #endif
  12849. /*
  12850. ** We need to define _XOPEN_SOURCE as follows in order to enable
  12851. ** recursive mutexes on most Unix systems and fchmod() on OpenBSD.
  12852. ** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit
  12853. ** it.
  12854. */
  12855. #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__)
  12856. # define _XOPEN_SOURCE 600
  12857. #endif
  12858. /*
  12859. ** NDEBUG and SQLITE_DEBUG are opposites. It should always be true that
  12860. ** defined(NDEBUG)==!defined(SQLITE_DEBUG). If this is not currently true,
  12861. ** make it true by defining or undefining NDEBUG.
  12862. **
  12863. ** Setting NDEBUG makes the code smaller and faster by disabling the
  12864. ** assert() statements in the code. So we want the default action
  12865. ** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
  12866. ** is set. Thus NDEBUG becomes an opt-in rather than an opt-out
  12867. ** feature.
  12868. */
  12869. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  12870. # define NDEBUG 1
  12871. #endif
  12872. #if defined(NDEBUG) && defined(SQLITE_DEBUG)
  12873. # undef NDEBUG
  12874. #endif
  12875. /*
  12876. ** Enable SQLITE_ENABLE_EXPLAIN_COMMENTS if SQLITE_DEBUG is turned on.
  12877. */
  12878. #if !defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) && defined(SQLITE_DEBUG)
  12879. # define SQLITE_ENABLE_EXPLAIN_COMMENTS 1
  12880. #endif
  12881. /*
  12882. ** The testcase() macro is used to aid in coverage testing. When
  12883. ** doing coverage testing, the condition inside the argument to
  12884. ** testcase() must be evaluated both true and false in order to
  12885. ** get full branch coverage. The testcase() macro is inserted
  12886. ** to help ensure adequate test coverage in places where simple
  12887. ** condition/decision coverage is inadequate. For example, testcase()
  12888. ** can be used to make sure boundary values are tested. For
  12889. ** bitmask tests, testcase() can be used to make sure each bit
  12890. ** is significant and used at least once. On switch statements
  12891. ** where multiple cases go to the same block of code, testcase()
  12892. ** can insure that all cases are evaluated.
  12893. **
  12894. */
  12895. #ifdef SQLITE_COVERAGE_TEST
  12896. SQLITE_PRIVATE void sqlite3Coverage(int);
  12897. # define testcase(X) if( X ){ sqlite3Coverage(__LINE__); }
  12898. #else
  12899. # define testcase(X)
  12900. #endif
  12901. /*
  12902. ** The TESTONLY macro is used to enclose variable declarations or
  12903. ** other bits of code that are needed to support the arguments
  12904. ** within testcase() and assert() macros.
  12905. */
  12906. #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
  12907. # define TESTONLY(X) X
  12908. #else
  12909. # define TESTONLY(X)
  12910. #endif
  12911. /*
  12912. ** Sometimes we need a small amount of code such as a variable initialization
  12913. ** to setup for a later assert() statement. We do not want this code to
  12914. ** appear when assert() is disabled. The following macro is therefore
  12915. ** used to contain that setup code. The "VVA" acronym stands for
  12916. ** "Verification, Validation, and Accreditation". In other words, the
  12917. ** code within VVA_ONLY() will only run during verification processes.
  12918. */
  12919. #ifndef NDEBUG
  12920. # define VVA_ONLY(X) X
  12921. #else
  12922. # define VVA_ONLY(X)
  12923. #endif
  12924. /*
  12925. ** The ALWAYS and NEVER macros surround boolean expressions which
  12926. ** are intended to always be true or false, respectively. Such
  12927. ** expressions could be omitted from the code completely. But they
  12928. ** are included in a few cases in order to enhance the resilience
  12929. ** of SQLite to unexpected behavior - to make the code "self-healing"
  12930. ** or "ductile" rather than being "brittle" and crashing at the first
  12931. ** hint of unplanned behavior.
  12932. **
  12933. ** In other words, ALWAYS and NEVER are added for defensive code.
  12934. **
  12935. ** When doing coverage testing ALWAYS and NEVER are hard-coded to
  12936. ** be true and false so that the unreachable code they specify will
  12937. ** not be counted as untested code.
  12938. */
  12939. #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
  12940. # define ALWAYS(X) (1)
  12941. # define NEVER(X) (0)
  12942. #elif !defined(NDEBUG)
  12943. # define ALWAYS(X) ((X)?1:(assert(0),0))
  12944. # define NEVER(X) ((X)?(assert(0),1):0)
  12945. #else
  12946. # define ALWAYS(X) (X)
  12947. # define NEVER(X) (X)
  12948. #endif
  12949. /*
  12950. ** Some conditionals are optimizations only. In other words, if the
  12951. ** conditionals are replaced with a constant 1 (true) or 0 (false) then
  12952. ** the correct answer is still obtained, though perhaps not as quickly.
  12953. **
  12954. ** The following macros mark these optimizations conditionals.
  12955. */
  12956. #if defined(SQLITE_MUTATION_TEST)
  12957. # define OK_IF_ALWAYS_TRUE(X) (1)
  12958. # define OK_IF_ALWAYS_FALSE(X) (0)
  12959. #else
  12960. # define OK_IF_ALWAYS_TRUE(X) (X)
  12961. # define OK_IF_ALWAYS_FALSE(X) (X)
  12962. #endif
  12963. /*
  12964. ** Some malloc failures are only possible if SQLITE_TEST_REALLOC_STRESS is
  12965. ** defined. We need to defend against those failures when testing with
  12966. ** SQLITE_TEST_REALLOC_STRESS, but we don't want the unreachable branches
  12967. ** during a normal build. The following macro can be used to disable tests
  12968. ** that are always false except when SQLITE_TEST_REALLOC_STRESS is set.
  12969. */
  12970. #if defined(SQLITE_TEST_REALLOC_STRESS)
  12971. # define ONLY_IF_REALLOC_STRESS(X) (X)
  12972. #elif !defined(NDEBUG)
  12973. # define ONLY_IF_REALLOC_STRESS(X) ((X)?(assert(0),1):0)
  12974. #else
  12975. # define ONLY_IF_REALLOC_STRESS(X) (0)
  12976. #endif
  12977. /*
  12978. ** Declarations used for tracing the operating system interfaces.
  12979. */
  12980. #if defined(SQLITE_FORCE_OS_TRACE) || defined(SQLITE_TEST) || \
  12981. (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
  12982. extern int sqlite3OSTrace;
  12983. # define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
  12984. # define SQLITE_HAVE_OS_TRACE
  12985. #else
  12986. # define OSTRACE(X)
  12987. # undef SQLITE_HAVE_OS_TRACE
  12988. #endif
  12989. /*
  12990. ** Is the sqlite3ErrName() function needed in the build? Currently,
  12991. ** it is needed by "mutex_w32.c" (when debugging), "os_win.c" (when
  12992. ** OSTRACE is enabled), and by several "test*.c" files (which are
  12993. ** compiled using SQLITE_TEST).
  12994. */
  12995. #if defined(SQLITE_HAVE_OS_TRACE) || defined(SQLITE_TEST) || \
  12996. (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
  12997. # define SQLITE_NEED_ERR_NAME
  12998. #else
  12999. # undef SQLITE_NEED_ERR_NAME
  13000. #endif
  13001. /*
  13002. ** SQLITE_ENABLE_EXPLAIN_COMMENTS is incompatible with SQLITE_OMIT_EXPLAIN
  13003. */
  13004. #ifdef SQLITE_OMIT_EXPLAIN
  13005. # undef SQLITE_ENABLE_EXPLAIN_COMMENTS
  13006. #endif
  13007. /*
  13008. ** Return true (non-zero) if the input is an integer that is too large
  13009. ** to fit in 32-bits. This macro is used inside of various testcase()
  13010. ** macros to verify that we have tested SQLite for large-file support.
  13011. */
  13012. #define IS_BIG_INT(X) (((X)&~(i64)0xffffffff)!=0)
  13013. /*
  13014. ** The macro unlikely() is a hint that surrounds a boolean
  13015. ** expression that is usually false. Macro likely() surrounds
  13016. ** a boolean expression that is usually true. These hints could,
  13017. ** in theory, be used by the compiler to generate better code, but
  13018. ** currently they are just comments for human readers.
  13019. */
  13020. #define likely(X) (X)
  13021. #define unlikely(X) (X)
  13022. /************** Include hash.h in the middle of sqliteInt.h ******************/
  13023. /************** Begin file hash.h ********************************************/
  13024. /*
  13025. ** 2001 September 22
  13026. **
  13027. ** The author disclaims copyright to this source code. In place of
  13028. ** a legal notice, here is a blessing:
  13029. **
  13030. ** May you do good and not evil.
  13031. ** May you find forgiveness for yourself and forgive others.
  13032. ** May you share freely, never taking more than you give.
  13033. **
  13034. *************************************************************************
  13035. ** This is the header file for the generic hash-table implementation
  13036. ** used in SQLite.
  13037. */
  13038. #ifndef SQLITE_HASH_H
  13039. #define SQLITE_HASH_H
  13040. /* Forward declarations of structures. */
  13041. typedef struct Hash Hash;
  13042. typedef struct HashElem HashElem;
  13043. /* A complete hash table is an instance of the following structure.
  13044. ** The internals of this structure are intended to be opaque -- client
  13045. ** code should not attempt to access or modify the fields of this structure
  13046. ** directly. Change this structure only by using the routines below.
  13047. ** However, some of the "procedures" and "functions" for modifying and
  13048. ** accessing this structure are really macros, so we can't really make
  13049. ** this structure opaque.
  13050. **
  13051. ** All elements of the hash table are on a single doubly-linked list.
  13052. ** Hash.first points to the head of this list.
  13053. **
  13054. ** There are Hash.htsize buckets. Each bucket points to a spot in
  13055. ** the global doubly-linked list. The contents of the bucket are the
  13056. ** element pointed to plus the next _ht.count-1 elements in the list.
  13057. **
  13058. ** Hash.htsize and Hash.ht may be zero. In that case lookup is done
  13059. ** by a linear search of the global list. For small tables, the
  13060. ** Hash.ht table is never allocated because if there are few elements
  13061. ** in the table, it is faster to do a linear search than to manage
  13062. ** the hash table.
  13063. */
  13064. struct Hash {
  13065. unsigned int htsize; /* Number of buckets in the hash table */
  13066. unsigned int count; /* Number of entries in this table */
  13067. HashElem *first; /* The first element of the array */
  13068. struct _ht { /* the hash table */
  13069. unsigned int count; /* Number of entries with this hash */
  13070. HashElem *chain; /* Pointer to first entry with this hash */
  13071. } *ht;
  13072. };
  13073. /* Each element in the hash table is an instance of the following
  13074. ** structure. All elements are stored on a single doubly-linked list.
  13075. **
  13076. ** Again, this structure is intended to be opaque, but it can't really
  13077. ** be opaque because it is used by macros.
  13078. */
  13079. struct HashElem {
  13080. HashElem *next, *prev; /* Next and previous elements in the table */
  13081. void *data; /* Data associated with this element */
  13082. const char *pKey; /* Key associated with this element */
  13083. };
  13084. /*
  13085. ** Access routines. To delete, insert a NULL pointer.
  13086. */
  13087. SQLITE_PRIVATE void sqlite3HashInit(Hash*);
  13088. SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, void *pData);
  13089. SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey);
  13090. SQLITE_PRIVATE void sqlite3HashClear(Hash*);
  13091. /*
  13092. ** Macros for looping over all elements of a hash table. The idiom is
  13093. ** like this:
  13094. **
  13095. ** Hash h;
  13096. ** HashElem *p;
  13097. ** ...
  13098. ** for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
  13099. ** SomeStructure *pData = sqliteHashData(p);
  13100. ** // do something with pData
  13101. ** }
  13102. */
  13103. #define sqliteHashFirst(H) ((H)->first)
  13104. #define sqliteHashNext(E) ((E)->next)
  13105. #define sqliteHashData(E) ((E)->data)
  13106. /* #define sqliteHashKey(E) ((E)->pKey) // NOT USED */
  13107. /* #define sqliteHashKeysize(E) ((E)->nKey) // NOT USED */
  13108. /*
  13109. ** Number of entries in a hash table
  13110. */
  13111. /* #define sqliteHashCount(H) ((H)->count) // NOT USED */
  13112. #endif /* SQLITE_HASH_H */
  13113. /************** End of hash.h ************************************************/
  13114. /************** Continuing where we left off in sqliteInt.h ******************/
  13115. /************** Include parse.h in the middle of sqliteInt.h *****************/
  13116. /************** Begin file parse.h *******************************************/
  13117. #define TK_SEMI 1
  13118. #define TK_EXPLAIN 2
  13119. #define TK_QUERY 3
  13120. #define TK_PLAN 4
  13121. #define TK_BEGIN 5
  13122. #define TK_TRANSACTION 6
  13123. #define TK_DEFERRED 7
  13124. #define TK_IMMEDIATE 8
  13125. #define TK_EXCLUSIVE 9
  13126. #define TK_COMMIT 10
  13127. #define TK_END 11
  13128. #define TK_ROLLBACK 12
  13129. #define TK_SAVEPOINT 13
  13130. #define TK_RELEASE 14
  13131. #define TK_TO 15
  13132. #define TK_TABLE 16
  13133. #define TK_CREATE 17
  13134. #define TK_IF 18
  13135. #define TK_NOT 19
  13136. #define TK_EXISTS 20
  13137. #define TK_TEMP 21
  13138. #define TK_LP 22
  13139. #define TK_RP 23
  13140. #define TK_AS 24
  13141. #define TK_WITHOUT 25
  13142. #define TK_COMMA 26
  13143. #define TK_ABORT 27
  13144. #define TK_ACTION 28
  13145. #define TK_AFTER 29
  13146. #define TK_ANALYZE 30
  13147. #define TK_ASC 31
  13148. #define TK_ATTACH 32
  13149. #define TK_BEFORE 33
  13150. #define TK_BY 34
  13151. #define TK_CASCADE 35
  13152. #define TK_CAST 36
  13153. #define TK_CONFLICT 37
  13154. #define TK_DATABASE 38
  13155. #define TK_DESC 39
  13156. #define TK_DETACH 40
  13157. #define TK_EACH 41
  13158. #define TK_FAIL 42
  13159. #define TK_OR 43
  13160. #define TK_AND 44
  13161. #define TK_IS 45
  13162. #define TK_MATCH 46
  13163. #define TK_LIKE_KW 47
  13164. #define TK_BETWEEN 48
  13165. #define TK_IN 49
  13166. #define TK_ISNULL 50
  13167. #define TK_NOTNULL 51
  13168. #define TK_NE 52
  13169. #define TK_EQ 53
  13170. #define TK_GT 54
  13171. #define TK_LE 55
  13172. #define TK_LT 56
  13173. #define TK_GE 57
  13174. #define TK_ESCAPE 58
  13175. #define TK_ID 59
  13176. #define TK_COLUMNKW 60
  13177. #define TK_DO 61
  13178. #define TK_FOR 62
  13179. #define TK_IGNORE 63
  13180. #define TK_INITIALLY 64
  13181. #define TK_INSTEAD 65
  13182. #define TK_NO 66
  13183. #define TK_KEY 67
  13184. #define TK_OF 68
  13185. #define TK_OFFSET 69
  13186. #define TK_PRAGMA 70
  13187. #define TK_RAISE 71
  13188. #define TK_RECURSIVE 72
  13189. #define TK_REPLACE 73
  13190. #define TK_RESTRICT 74
  13191. #define TK_ROW 75
  13192. #define TK_ROWS 76
  13193. #define TK_TRIGGER 77
  13194. #define TK_VACUUM 78
  13195. #define TK_VIEW 79
  13196. #define TK_VIRTUAL 80
  13197. #define TK_WITH 81
  13198. #define TK_CURRENT 82
  13199. #define TK_FOLLOWING 83
  13200. #define TK_PARTITION 84
  13201. #define TK_PRECEDING 85
  13202. #define TK_RANGE 86
  13203. #define TK_UNBOUNDED 87
  13204. #define TK_EXCLUDE 88
  13205. #define TK_GROUPS 89
  13206. #define TK_OTHERS 90
  13207. #define TK_TIES 91
  13208. #define TK_REINDEX 92
  13209. #define TK_RENAME 93
  13210. #define TK_CTIME_KW 94
  13211. #define TK_ANY 95
  13212. #define TK_BITAND 96
  13213. #define TK_BITOR 97
  13214. #define TK_LSHIFT 98
  13215. #define TK_RSHIFT 99
  13216. #define TK_PLUS 100
  13217. #define TK_MINUS 101
  13218. #define TK_STAR 102
  13219. #define TK_SLASH 103
  13220. #define TK_REM 104
  13221. #define TK_CONCAT 105
  13222. #define TK_COLLATE 106
  13223. #define TK_BITNOT 107
  13224. #define TK_ON 108
  13225. #define TK_INDEXED 109
  13226. #define TK_STRING 110
  13227. #define TK_JOIN_KW 111
  13228. #define TK_CONSTRAINT 112
  13229. #define TK_DEFAULT 113
  13230. #define TK_NULL 114
  13231. #define TK_PRIMARY 115
  13232. #define TK_UNIQUE 116
  13233. #define TK_CHECK 117
  13234. #define TK_REFERENCES 118
  13235. #define TK_AUTOINCR 119
  13236. #define TK_INSERT 120
  13237. #define TK_DELETE 121
  13238. #define TK_UPDATE 122
  13239. #define TK_SET 123
  13240. #define TK_DEFERRABLE 124
  13241. #define TK_FOREIGN 125
  13242. #define TK_DROP 126
  13243. #define TK_UNION 127
  13244. #define TK_ALL 128
  13245. #define TK_EXCEPT 129
  13246. #define TK_INTERSECT 130
  13247. #define TK_SELECT 131
  13248. #define TK_VALUES 132
  13249. #define TK_DISTINCT 133
  13250. #define TK_DOT 134
  13251. #define TK_FROM 135
  13252. #define TK_JOIN 136
  13253. #define TK_USING 137
  13254. #define TK_ORDER 138
  13255. #define TK_GROUP 139
  13256. #define TK_HAVING 140
  13257. #define TK_LIMIT 141
  13258. #define TK_WHERE 142
  13259. #define TK_INTO 143
  13260. #define TK_NOTHING 144
  13261. #define TK_FLOAT 145
  13262. #define TK_BLOB 146
  13263. #define TK_INTEGER 147
  13264. #define TK_VARIABLE 148
  13265. #define TK_CASE 149
  13266. #define TK_WHEN 150
  13267. #define TK_THEN 151
  13268. #define TK_ELSE 152
  13269. #define TK_INDEX 153
  13270. #define TK_ALTER 154
  13271. #define TK_ADD 155
  13272. #define TK_WINDOW 156
  13273. #define TK_OVER 157
  13274. #define TK_FILTER 158
  13275. #define TK_TRUEFALSE 159
  13276. #define TK_ISNOT 160
  13277. #define TK_FUNCTION 161
  13278. #define TK_COLUMN 162
  13279. #define TK_AGG_FUNCTION 163
  13280. #define TK_AGG_COLUMN 164
  13281. #define TK_UMINUS 165
  13282. #define TK_UPLUS 166
  13283. #define TK_TRUTH 167
  13284. #define TK_REGISTER 168
  13285. #define TK_VECTOR 169
  13286. #define TK_SELECT_COLUMN 170
  13287. #define TK_IF_NULL_ROW 171
  13288. #define TK_ASTERISK 172
  13289. #define TK_SPAN 173
  13290. #define TK_SPACE 174
  13291. #define TK_ILLEGAL 175
  13292. /************** End of parse.h ***********************************************/
  13293. /************** Continuing where we left off in sqliteInt.h ******************/
  13294. #include <stdio.h>
  13295. #include <stdlib.h>
  13296. #include <string.h>
  13297. #include <assert.h>
  13298. #include <stddef.h>
  13299. /*
  13300. ** Use a macro to replace memcpy() if compiled with SQLITE_INLINE_MEMCPY.
  13301. ** This allows better measurements of where memcpy() is used when running
  13302. ** cachegrind. But this macro version of memcpy() is very slow so it
  13303. ** should not be used in production. This is a performance measurement
  13304. ** hack only.
  13305. */
  13306. #ifdef SQLITE_INLINE_MEMCPY
  13307. # define memcpy(D,S,N) {char*xxd=(char*)(D);const char*xxs=(const char*)(S);\
  13308. int xxn=(N);while(xxn-->0)*(xxd++)=*(xxs++);}
  13309. #endif
  13310. /*
  13311. ** If compiling for a processor that lacks floating point support,
  13312. ** substitute integer for floating-point
  13313. */
  13314. #ifdef SQLITE_OMIT_FLOATING_POINT
  13315. # define double sqlite_int64
  13316. # define float sqlite_int64
  13317. # define LONGDOUBLE_TYPE sqlite_int64
  13318. # ifndef SQLITE_BIG_DBL
  13319. # define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
  13320. # endif
  13321. # define SQLITE_OMIT_DATETIME_FUNCS 1
  13322. # define SQLITE_OMIT_TRACE 1
  13323. # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  13324. # undef SQLITE_HAVE_ISNAN
  13325. #endif
  13326. #ifndef SQLITE_BIG_DBL
  13327. # define SQLITE_BIG_DBL (1e99)
  13328. #endif
  13329. /*
  13330. ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
  13331. ** afterward. Having this macro allows us to cause the C compiler
  13332. ** to omit code used by TEMP tables without messy #ifndef statements.
  13333. */
  13334. #ifdef SQLITE_OMIT_TEMPDB
  13335. #define OMIT_TEMPDB 1
  13336. #else
  13337. #define OMIT_TEMPDB 0
  13338. #endif
  13339. /*
  13340. ** The "file format" number is an integer that is incremented whenever
  13341. ** the VDBE-level file format changes. The following macros define the
  13342. ** the default file format for new databases and the maximum file format
  13343. ** that the library can read.
  13344. */
  13345. #define SQLITE_MAX_FILE_FORMAT 4
  13346. #ifndef SQLITE_DEFAULT_FILE_FORMAT
  13347. # define SQLITE_DEFAULT_FILE_FORMAT 4
  13348. #endif
  13349. /*
  13350. ** Determine whether triggers are recursive by default. This can be
  13351. ** changed at run-time using a pragma.
  13352. */
  13353. #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
  13354. # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
  13355. #endif
  13356. /*
  13357. ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
  13358. ** on the command-line
  13359. */
  13360. #ifndef SQLITE_TEMP_STORE
  13361. # define SQLITE_TEMP_STORE 1
  13362. #endif
  13363. /*
  13364. ** If no value has been provided for SQLITE_MAX_WORKER_THREADS, or if
  13365. ** SQLITE_TEMP_STORE is set to 3 (never use temporary files), set it
  13366. ** to zero.
  13367. */
  13368. #if SQLITE_TEMP_STORE==3 || SQLITE_THREADSAFE==0
  13369. # undef SQLITE_MAX_WORKER_THREADS
  13370. # define SQLITE_MAX_WORKER_THREADS 0
  13371. #endif
  13372. #ifndef SQLITE_MAX_WORKER_THREADS
  13373. # define SQLITE_MAX_WORKER_THREADS 8
  13374. #endif
  13375. #ifndef SQLITE_DEFAULT_WORKER_THREADS
  13376. # define SQLITE_DEFAULT_WORKER_THREADS 0
  13377. #endif
  13378. #if SQLITE_DEFAULT_WORKER_THREADS>SQLITE_MAX_WORKER_THREADS
  13379. # undef SQLITE_MAX_WORKER_THREADS
  13380. # define SQLITE_MAX_WORKER_THREADS SQLITE_DEFAULT_WORKER_THREADS
  13381. #endif
  13382. /*
  13383. ** The default initial allocation for the pagecache when using separate
  13384. ** pagecaches for each database connection. A positive number is the
  13385. ** number of pages. A negative number N translations means that a buffer
  13386. ** of -1024*N bytes is allocated and used for as many pages as it will hold.
  13387. **
  13388. ** The default value of "20" was choosen to minimize the run-time of the
  13389. ** speedtest1 test program with options: --shrink-memory --reprepare
  13390. */
  13391. #ifndef SQLITE_DEFAULT_PCACHE_INITSZ
  13392. # define SQLITE_DEFAULT_PCACHE_INITSZ 20
  13393. #endif
  13394. /*
  13395. ** Default value for the SQLITE_CONFIG_SORTERREF_SIZE option.
  13396. */
  13397. #ifndef SQLITE_DEFAULT_SORTERREF_SIZE
  13398. # define SQLITE_DEFAULT_SORTERREF_SIZE 0x7fffffff
  13399. #endif
  13400. /*
  13401. ** The compile-time options SQLITE_MMAP_READWRITE and
  13402. ** SQLITE_ENABLE_BATCH_ATOMIC_WRITE are not compatible with one another.
  13403. ** You must choose one or the other (or neither) but not both.
  13404. */
  13405. #if defined(SQLITE_MMAP_READWRITE) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
  13406. #error Cannot use both SQLITE_MMAP_READWRITE and SQLITE_ENABLE_BATCH_ATOMIC_WRITE
  13407. #endif
  13408. /*
  13409. ** GCC does not define the offsetof() macro so we'll have to do it
  13410. ** ourselves.
  13411. */
  13412. #ifndef offsetof
  13413. #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
  13414. #endif
  13415. /*
  13416. ** Macros to compute minimum and maximum of two numbers.
  13417. */
  13418. #ifndef MIN
  13419. # define MIN(A,B) ((A)<(B)?(A):(B))
  13420. #endif
  13421. #ifndef MAX
  13422. # define MAX(A,B) ((A)>(B)?(A):(B))
  13423. #endif
  13424. /*
  13425. ** Swap two objects of type TYPE.
  13426. */
  13427. #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
  13428. /*
  13429. ** Check to see if this machine uses EBCDIC. (Yes, believe it or
  13430. ** not, there are still machines out there that use EBCDIC.)
  13431. */
  13432. #if 'A' == '\301'
  13433. # define SQLITE_EBCDIC 1
  13434. #else
  13435. # define SQLITE_ASCII 1
  13436. #endif
  13437. /*
  13438. ** Integers of known sizes. These typedefs might change for architectures
  13439. ** where the sizes very. Preprocessor macros are available so that the
  13440. ** types can be conveniently redefined at compile-type. Like this:
  13441. **
  13442. ** cc '-DUINTPTR_TYPE=long long int' ...
  13443. */
  13444. #ifndef UINT32_TYPE
  13445. # ifdef HAVE_UINT32_T
  13446. # define UINT32_TYPE uint32_t
  13447. # else
  13448. # define UINT32_TYPE unsigned int
  13449. # endif
  13450. #endif
  13451. #ifndef UINT16_TYPE
  13452. # ifdef HAVE_UINT16_T
  13453. # define UINT16_TYPE uint16_t
  13454. # else
  13455. # define UINT16_TYPE unsigned short int
  13456. # endif
  13457. #endif
  13458. #ifndef INT16_TYPE
  13459. # ifdef HAVE_INT16_T
  13460. # define INT16_TYPE int16_t
  13461. # else
  13462. # define INT16_TYPE short int
  13463. # endif
  13464. #endif
  13465. #ifndef UINT8_TYPE
  13466. # ifdef HAVE_UINT8_T
  13467. # define UINT8_TYPE uint8_t
  13468. # else
  13469. # define UINT8_TYPE unsigned char
  13470. # endif
  13471. #endif
  13472. #ifndef INT8_TYPE
  13473. # ifdef HAVE_INT8_T
  13474. # define INT8_TYPE int8_t
  13475. # else
  13476. # define INT8_TYPE signed char
  13477. # endif
  13478. #endif
  13479. #ifndef LONGDOUBLE_TYPE
  13480. # define LONGDOUBLE_TYPE long double
  13481. #endif
  13482. typedef sqlite_int64 i64; /* 8-byte signed integer */
  13483. typedef sqlite_uint64 u64; /* 8-byte unsigned integer */
  13484. typedef UINT32_TYPE u32; /* 4-byte unsigned integer */
  13485. typedef UINT16_TYPE u16; /* 2-byte unsigned integer */
  13486. typedef INT16_TYPE i16; /* 2-byte signed integer */
  13487. typedef UINT8_TYPE u8; /* 1-byte unsigned integer */
  13488. typedef INT8_TYPE i8; /* 1-byte signed integer */
  13489. /*
  13490. ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
  13491. ** that can be stored in a u32 without loss of data. The value
  13492. ** is 0x00000000ffffffff. But because of quirks of some compilers, we
  13493. ** have to specify the value in the less intuitive manner shown:
  13494. */
  13495. #define SQLITE_MAX_U32 ((((u64)1)<<32)-1)
  13496. /*
  13497. ** The datatype used to store estimates of the number of rows in a
  13498. ** table or index. This is an unsigned integer type. For 99.9% of
  13499. ** the world, a 32-bit integer is sufficient. But a 64-bit integer
  13500. ** can be used at compile-time if desired.
  13501. */
  13502. #ifdef SQLITE_64BIT_STATS
  13503. typedef u64 tRowcnt; /* 64-bit only if requested at compile-time */
  13504. #else
  13505. typedef u32 tRowcnt; /* 32-bit is the default */
  13506. #endif
  13507. /*
  13508. ** Estimated quantities used for query planning are stored as 16-bit
  13509. ** logarithms. For quantity X, the value stored is 10*log2(X). This
  13510. ** gives a possible range of values of approximately 1.0e986 to 1e-986.
  13511. ** But the allowed values are "grainy". Not every value is representable.
  13512. ** For example, quantities 16 and 17 are both represented by a LogEst
  13513. ** of 40. However, since LogEst quantities are suppose to be estimates,
  13514. ** not exact values, this imprecision is not a problem.
  13515. **
  13516. ** "LogEst" is short for "Logarithmic Estimate".
  13517. **
  13518. ** Examples:
  13519. ** 1 -> 0 20 -> 43 10000 -> 132
  13520. ** 2 -> 10 25 -> 46 25000 -> 146
  13521. ** 3 -> 16 100 -> 66 1000000 -> 199
  13522. ** 4 -> 20 1000 -> 99 1048576 -> 200
  13523. ** 10 -> 33 1024 -> 100 4294967296 -> 320
  13524. **
  13525. ** The LogEst can be negative to indicate fractional values.
  13526. ** Examples:
  13527. **
  13528. ** 0.5 -> -10 0.1 -> -33 0.0625 -> -40
  13529. */
  13530. typedef INT16_TYPE LogEst;
  13531. /*
  13532. ** Set the SQLITE_PTRSIZE macro to the number of bytes in a pointer
  13533. */
  13534. #ifndef SQLITE_PTRSIZE
  13535. # if defined(__SIZEOF_POINTER__)
  13536. # define SQLITE_PTRSIZE __SIZEOF_POINTER__
  13537. # elif defined(i386) || defined(__i386__) || defined(_M_IX86) || \
  13538. defined(_M_ARM) || defined(__arm__) || defined(__x86) || \
  13539. (defined(__TOS_AIX__) && !defined(__64BIT__))
  13540. # define SQLITE_PTRSIZE 4
  13541. # else
  13542. # define SQLITE_PTRSIZE 8
  13543. # endif
  13544. #endif
  13545. /* The uptr type is an unsigned integer large enough to hold a pointer
  13546. */
  13547. #if defined(HAVE_STDINT_H)
  13548. typedef uintptr_t uptr;
  13549. #elif SQLITE_PTRSIZE==4
  13550. typedef u32 uptr;
  13551. #else
  13552. typedef u64 uptr;
  13553. #endif
  13554. /*
  13555. ** The SQLITE_WITHIN(P,S,E) macro checks to see if pointer P points to
  13556. ** something between S (inclusive) and E (exclusive).
  13557. **
  13558. ** In other words, S is a buffer and E is a pointer to the first byte after
  13559. ** the end of buffer S. This macro returns true if P points to something
  13560. ** contained within the buffer S.
  13561. */
  13562. #define SQLITE_WITHIN(P,S,E) (((uptr)(P)>=(uptr)(S))&&((uptr)(P)<(uptr)(E)))
  13563. /*
  13564. ** Macros to determine whether the machine is big or little endian,
  13565. ** and whether or not that determination is run-time or compile-time.
  13566. **
  13567. ** For best performance, an attempt is made to guess at the byte-order
  13568. ** using C-preprocessor macros. If that is unsuccessful, or if
  13569. ** -DSQLITE_BYTEORDER=0 is set, then byte-order is determined
  13570. ** at run-time.
  13571. */
  13572. #ifndef SQLITE_BYTEORDER
  13573. # if defined(i386) || defined(__i386__) || defined(_M_IX86) || \
  13574. defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \
  13575. defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \
  13576. defined(__ARMEL__) || defined(__AARCH64EL__) || defined(_M_ARM64)
  13577. # define SQLITE_BYTEORDER 1234
  13578. # elif defined(sparc) || defined(__ppc__) || \
  13579. defined(__ARMEB__) || defined(__AARCH64EB__)
  13580. # define SQLITE_BYTEORDER 4321
  13581. # else
  13582. # define SQLITE_BYTEORDER 0
  13583. # endif
  13584. #endif
  13585. #if SQLITE_BYTEORDER==4321
  13586. # define SQLITE_BIGENDIAN 1
  13587. # define SQLITE_LITTLEENDIAN 0
  13588. # define SQLITE_UTF16NATIVE SQLITE_UTF16BE
  13589. #elif SQLITE_BYTEORDER==1234
  13590. # define SQLITE_BIGENDIAN 0
  13591. # define SQLITE_LITTLEENDIAN 1
  13592. # define SQLITE_UTF16NATIVE SQLITE_UTF16LE
  13593. #else
  13594. # ifdef SQLITE_AMALGAMATION
  13595. const int sqlite3one = 1;
  13596. # else
  13597. extern const int sqlite3one;
  13598. # endif
  13599. # define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0)
  13600. # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
  13601. # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
  13602. #endif
  13603. /*
  13604. ** Constants for the largest and smallest possible 64-bit signed integers.
  13605. ** These macros are designed to work correctly on both 32-bit and 64-bit
  13606. ** compilers.
  13607. */
  13608. #define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
  13609. #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
  13610. /*
  13611. ** Round up a number to the next larger multiple of 8. This is used
  13612. ** to force 8-byte alignment on 64-bit architectures.
  13613. */
  13614. #define ROUND8(x) (((x)+7)&~7)
  13615. /*
  13616. ** Round down to the nearest multiple of 8
  13617. */
  13618. #define ROUNDDOWN8(x) ((x)&~7)
  13619. /*
  13620. ** Assert that the pointer X is aligned to an 8-byte boundary. This
  13621. ** macro is used only within assert() to verify that the code gets
  13622. ** all alignment restrictions correct.
  13623. **
  13624. ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
  13625. ** underlying malloc() implementation might return us 4-byte aligned
  13626. ** pointers. In that case, only verify 4-byte alignment.
  13627. */
  13628. #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
  13629. # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&3)==0)
  13630. #else
  13631. # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&7)==0)
  13632. #endif
  13633. /*
  13634. ** Disable MMAP on platforms where it is known to not work
  13635. */
  13636. #if defined(__OpenBSD__) || defined(__QNXNTO__)
  13637. # undef SQLITE_MAX_MMAP_SIZE
  13638. # define SQLITE_MAX_MMAP_SIZE 0
  13639. #endif
  13640. /*
  13641. ** Default maximum size of memory used by memory-mapped I/O in the VFS
  13642. */
  13643. #ifdef __APPLE__
  13644. # include <TargetConditionals.h>
  13645. #endif
  13646. #ifndef SQLITE_MAX_MMAP_SIZE
  13647. # if defined(__linux__) \
  13648. || defined(_WIN32) \
  13649. || (defined(__APPLE__) && defined(__MACH__)) \
  13650. || defined(__sun) \
  13651. || defined(__FreeBSD__) \
  13652. || defined(__DragonFly__)
  13653. # define SQLITE_MAX_MMAP_SIZE 0x7fff0000 /* 2147418112 */
  13654. # else
  13655. # define SQLITE_MAX_MMAP_SIZE 0
  13656. # endif
  13657. #endif
  13658. /*
  13659. ** The default MMAP_SIZE is zero on all platforms. Or, even if a larger
  13660. ** default MMAP_SIZE is specified at compile-time, make sure that it does
  13661. ** not exceed the maximum mmap size.
  13662. */
  13663. #ifndef SQLITE_DEFAULT_MMAP_SIZE
  13664. # define SQLITE_DEFAULT_MMAP_SIZE 0
  13665. #endif
  13666. #if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE
  13667. # undef SQLITE_DEFAULT_MMAP_SIZE
  13668. # define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE
  13669. #endif
  13670. /*
  13671. ** Only one of SQLITE_ENABLE_STAT3 or SQLITE_ENABLE_STAT4 can be defined.
  13672. ** Priority is given to SQLITE_ENABLE_STAT4. If either are defined, also
  13673. ** define SQLITE_ENABLE_STAT3_OR_STAT4
  13674. */
  13675. #ifdef SQLITE_ENABLE_STAT4
  13676. # undef SQLITE_ENABLE_STAT3
  13677. # define SQLITE_ENABLE_STAT3_OR_STAT4 1
  13678. #elif SQLITE_ENABLE_STAT3
  13679. # define SQLITE_ENABLE_STAT3_OR_STAT4 1
  13680. #elif SQLITE_ENABLE_STAT3_OR_STAT4
  13681. # undef SQLITE_ENABLE_STAT3_OR_STAT4
  13682. #endif
  13683. /*
  13684. ** SELECTTRACE_ENABLED will be either 1 or 0 depending on whether or not
  13685. ** the Select query generator tracing logic is turned on.
  13686. */
  13687. #if defined(SQLITE_ENABLE_SELECTTRACE)
  13688. # define SELECTTRACE_ENABLED 1
  13689. #else
  13690. # define SELECTTRACE_ENABLED 0
  13691. #endif
  13692. /*
  13693. ** An instance of the following structure is used to store the busy-handler
  13694. ** callback for a given sqlite handle.
  13695. **
  13696. ** The sqlite.busyHandler member of the sqlite struct contains the busy
  13697. ** callback for the database handle. Each pager opened via the sqlite
  13698. ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
  13699. ** callback is currently invoked only from within pager.c.
  13700. */
  13701. typedef struct BusyHandler BusyHandler;
  13702. struct BusyHandler {
  13703. int (*xBusyHandler)(void *,int); /* The busy callback */
  13704. void *pBusyArg; /* First arg to busy callback */
  13705. int nBusy; /* Incremented with each busy call */
  13706. u8 bExtraFileArg; /* Include sqlite3_file as callback arg */
  13707. };
  13708. /*
  13709. ** Name of the master database table. The master database table
  13710. ** is a special table that holds the names and attributes of all
  13711. ** user tables and indices.
  13712. */
  13713. #define MASTER_NAME "sqlite_master"
  13714. #define TEMP_MASTER_NAME "sqlite_temp_master"
  13715. /*
  13716. ** The root-page of the master database table.
  13717. */
  13718. #define MASTER_ROOT 1
  13719. /*
  13720. ** The name of the schema table.
  13721. */
  13722. #define SCHEMA_TABLE(x) ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
  13723. /*
  13724. ** A convenience macro that returns the number of elements in
  13725. ** an array.
  13726. */
  13727. #define ArraySize(X) ((int)(sizeof(X)/sizeof(X[0])))
  13728. /*
  13729. ** Determine if the argument is a power of two
  13730. */
  13731. #define IsPowerOfTwo(X) (((X)&((X)-1))==0)
  13732. /*
  13733. ** The following value as a destructor means to use sqlite3DbFree().
  13734. ** The sqlite3DbFree() routine requires two parameters instead of the
  13735. ** one parameter that destructors normally want. So we have to introduce
  13736. ** this magic value that the code knows to handle differently. Any
  13737. ** pointer will work here as long as it is distinct from SQLITE_STATIC
  13738. ** and SQLITE_TRANSIENT.
  13739. */
  13740. #define SQLITE_DYNAMIC ((sqlite3_destructor_type)sqlite3MallocSize)
  13741. /*
  13742. ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
  13743. ** not support Writable Static Data (WSD) such as global and static variables.
  13744. ** All variables must either be on the stack or dynamically allocated from
  13745. ** the heap. When WSD is unsupported, the variable declarations scattered
  13746. ** throughout the SQLite code must become constants instead. The SQLITE_WSD
  13747. ** macro is used for this purpose. And instead of referencing the variable
  13748. ** directly, we use its constant as a key to lookup the run-time allocated
  13749. ** buffer that holds real variable. The constant is also the initializer
  13750. ** for the run-time allocated buffer.
  13751. **
  13752. ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
  13753. ** macros become no-ops and have zero performance impact.
  13754. */
  13755. #ifdef SQLITE_OMIT_WSD
  13756. #define SQLITE_WSD const
  13757. #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
  13758. #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
  13759. SQLITE_API int sqlite3_wsd_init(int N, int J);
  13760. SQLITE_API void *sqlite3_wsd_find(void *K, int L);
  13761. #else
  13762. #define SQLITE_WSD
  13763. #define GLOBAL(t,v) v
  13764. #define sqlite3GlobalConfig sqlite3Config
  13765. #endif
  13766. /*
  13767. ** The following macros are used to suppress compiler warnings and to
  13768. ** make it clear to human readers when a function parameter is deliberately
  13769. ** left unused within the body of a function. This usually happens when
  13770. ** a function is called via a function pointer. For example the
  13771. ** implementation of an SQL aggregate step callback may not use the
  13772. ** parameter indicating the number of arguments passed to the aggregate,
  13773. ** if it knows that this is enforced elsewhere.
  13774. **
  13775. ** When a function parameter is not used at all within the body of a function,
  13776. ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
  13777. ** However, these macros may also be used to suppress warnings related to
  13778. ** parameters that may or may not be used depending on compilation options.
  13779. ** For example those parameters only used in assert() statements. In these
  13780. ** cases the parameters are named as per the usual conventions.
  13781. */
  13782. #define UNUSED_PARAMETER(x) (void)(x)
  13783. #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
  13784. /*
  13785. ** Forward references to structures
  13786. */
  13787. typedef struct AggInfo AggInfo;
  13788. typedef struct AuthContext AuthContext;
  13789. typedef struct AutoincInfo AutoincInfo;
  13790. typedef struct Bitvec Bitvec;
  13791. typedef struct CollSeq CollSeq;
  13792. typedef struct Column Column;
  13793. typedef struct Db Db;
  13794. typedef struct Schema Schema;
  13795. typedef struct Expr Expr;
  13796. typedef struct ExprList ExprList;
  13797. typedef struct FKey FKey;
  13798. typedef struct FuncDestructor FuncDestructor;
  13799. typedef struct FuncDef FuncDef;
  13800. typedef struct FuncDefHash FuncDefHash;
  13801. typedef struct IdList IdList;
  13802. typedef struct Index Index;
  13803. typedef struct IndexSample IndexSample;
  13804. typedef struct KeyClass KeyClass;
  13805. typedef struct KeyInfo KeyInfo;
  13806. typedef struct Lookaside Lookaside;
  13807. typedef struct LookasideSlot LookasideSlot;
  13808. typedef struct Module Module;
  13809. typedef struct NameContext NameContext;
  13810. typedef struct Parse Parse;
  13811. typedef struct PreUpdate PreUpdate;
  13812. typedef struct PrintfArguments PrintfArguments;
  13813. typedef struct RenameToken RenameToken;
  13814. typedef struct RowSet RowSet;
  13815. typedef struct Savepoint Savepoint;
  13816. typedef struct Select Select;
  13817. typedef struct SQLiteThread SQLiteThread;
  13818. typedef struct SelectDest SelectDest;
  13819. typedef struct SrcList SrcList;
  13820. typedef struct sqlite3_str StrAccum; /* Internal alias for sqlite3_str */
  13821. typedef struct Table Table;
  13822. typedef struct TableLock TableLock;
  13823. typedef struct Token Token;
  13824. typedef struct TreeView TreeView;
  13825. typedef struct Trigger Trigger;
  13826. typedef struct TriggerPrg TriggerPrg;
  13827. typedef struct TriggerStep TriggerStep;
  13828. typedef struct UnpackedRecord UnpackedRecord;
  13829. typedef struct Upsert Upsert;
  13830. typedef struct VTable VTable;
  13831. typedef struct VtabCtx VtabCtx;
  13832. typedef struct Walker Walker;
  13833. typedef struct WhereInfo WhereInfo;
  13834. typedef struct Window Window;
  13835. typedef struct With With;
  13836. /*
  13837. ** The bitmask datatype defined below is used for various optimizations.
  13838. **
  13839. ** Changing this from a 64-bit to a 32-bit type limits the number of
  13840. ** tables in a join to 32 instead of 64. But it also reduces the size
  13841. ** of the library by 738 bytes on ix86.
  13842. */
  13843. #ifdef SQLITE_BITMASK_TYPE
  13844. typedef SQLITE_BITMASK_TYPE Bitmask;
  13845. #else
  13846. typedef u64 Bitmask;
  13847. #endif
  13848. /*
  13849. ** The number of bits in a Bitmask. "BMS" means "BitMask Size".
  13850. */
  13851. #define BMS ((int)(sizeof(Bitmask)*8))
  13852. /*
  13853. ** A bit in a Bitmask
  13854. */
  13855. #define MASKBIT(n) (((Bitmask)1)<<(n))
  13856. #define MASKBIT32(n) (((unsigned int)1)<<(n))
  13857. #define ALLBITS ((Bitmask)-1)
  13858. /* A VList object records a mapping between parameters/variables/wildcards
  13859. ** in the SQL statement (such as $abc, @pqr, or :xyz) and the integer
  13860. ** variable number associated with that parameter. See the format description
  13861. ** on the sqlite3VListAdd() routine for more information. A VList is really
  13862. ** just an array of integers.
  13863. */
  13864. typedef int VList;
  13865. /*
  13866. ** Defer sourcing vdbe.h and btree.h until after the "u8" and
  13867. ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
  13868. ** pointer types (i.e. FuncDef) defined above.
  13869. */
  13870. /************** Include btree.h in the middle of sqliteInt.h *****************/
  13871. /************** Begin file btree.h *******************************************/
  13872. /*
  13873. ** 2001 September 15
  13874. **
  13875. ** The author disclaims copyright to this source code. In place of
  13876. ** a legal notice, here is a blessing:
  13877. **
  13878. ** May you do good and not evil.
  13879. ** May you find forgiveness for yourself and forgive others.
  13880. ** May you share freely, never taking more than you give.
  13881. **
  13882. *************************************************************************
  13883. ** This header file defines the interface that the sqlite B-Tree file
  13884. ** subsystem. See comments in the source code for a detailed description
  13885. ** of what each interface routine does.
  13886. */
  13887. #ifndef SQLITE_BTREE_H
  13888. #define SQLITE_BTREE_H
  13889. /* TODO: This definition is just included so other modules compile. It
  13890. ** needs to be revisited.
  13891. */
  13892. #define SQLITE_N_BTREE_META 16
  13893. /*
  13894. ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
  13895. ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
  13896. */
  13897. #ifndef SQLITE_DEFAULT_AUTOVACUUM
  13898. #define SQLITE_DEFAULT_AUTOVACUUM 0
  13899. #endif
  13900. #define BTREE_AUTOVACUUM_NONE 0 /* Do not do auto-vacuum */
  13901. #define BTREE_AUTOVACUUM_FULL 1 /* Do full auto-vacuum */
  13902. #define BTREE_AUTOVACUUM_INCR 2 /* Incremental vacuum */
  13903. /*
  13904. ** Forward declarations of structure
  13905. */
  13906. typedef struct Btree Btree;
  13907. typedef struct BtCursor BtCursor;
  13908. typedef struct BtShared BtShared;
  13909. typedef struct BtreePayload BtreePayload;
  13910. SQLITE_PRIVATE int sqlite3BtreeOpen(
  13911. sqlite3_vfs *pVfs, /* VFS to use with this b-tree */
  13912. const char *zFilename, /* Name of database file to open */
  13913. sqlite3 *db, /* Associated database connection */
  13914. Btree **ppBtree, /* Return open Btree* here */
  13915. int flags, /* Flags */
  13916. int vfsFlags /* Flags passed through to VFS open */
  13917. );
  13918. /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
  13919. ** following values.
  13920. **
  13921. ** NOTE: These values must match the corresponding PAGER_ values in
  13922. ** pager.h.
  13923. */
  13924. #define BTREE_OMIT_JOURNAL 1 /* Do not create or use a rollback journal */
  13925. #define BTREE_MEMORY 2 /* This is an in-memory DB */
  13926. #define BTREE_SINGLE 4 /* The file contains at most 1 b-tree */
  13927. #define BTREE_UNORDERED 8 /* Use of a hash implementation is OK */
  13928. SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
  13929. SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
  13930. SQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree*,int);
  13931. #if SQLITE_MAX_MMAP_SIZE>0
  13932. SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64);
  13933. #endif
  13934. SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(Btree*,unsigned);
  13935. SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
  13936. SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
  13937. SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
  13938. SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
  13939. SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
  13940. SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree*);
  13941. SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p);
  13942. SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
  13943. SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
  13944. SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int,int*);
  13945. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
  13946. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
  13947. SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
  13948. SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int,int);
  13949. SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
  13950. SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
  13951. SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
  13952. SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
  13953. SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
  13954. SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
  13955. SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
  13956. #ifndef SQLITE_OMIT_SHARED_CACHE
  13957. SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
  13958. #endif
  13959. SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
  13960. SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
  13961. SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
  13962. SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
  13963. SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
  13964. /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
  13965. ** of the flags shown below.
  13966. **
  13967. ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
  13968. ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
  13969. ** is stored in the leaves. (BTREE_INTKEY is used for SQL tables.) With
  13970. ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
  13971. ** anywhere - the key is the content. (BTREE_BLOBKEY is used for SQL
  13972. ** indices.)
  13973. */
  13974. #define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */
  13975. #define BTREE_BLOBKEY 2 /* Table has keys only - no data */
  13976. SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
  13977. SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
  13978. SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor*);
  13979. SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree*, int, int);
  13980. SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
  13981. SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
  13982. SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p);
  13983. /*
  13984. ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
  13985. ** should be one of the following values. The integer values are assigned
  13986. ** to constants so that the offset of the corresponding field in an
  13987. ** SQLite database header may be found using the following formula:
  13988. **
  13989. ** offset = 36 + (idx * 4)
  13990. **
  13991. ** For example, the free-page-count field is located at byte offset 36 of
  13992. ** the database file header. The incr-vacuum-flag field is located at
  13993. ** byte offset 64 (== 36+4*7).
  13994. **
  13995. ** The BTREE_DATA_VERSION value is not really a value stored in the header.
  13996. ** It is a read-only number computed by the pager. But we merge it with
  13997. ** the header value access routines since its access pattern is the same.
  13998. ** Call it a "virtual meta value".
  13999. */
  14000. #define BTREE_FREE_PAGE_COUNT 0
  14001. #define BTREE_SCHEMA_VERSION 1
  14002. #define BTREE_FILE_FORMAT 2
  14003. #define BTREE_DEFAULT_CACHE_SIZE 3
  14004. #define BTREE_LARGEST_ROOT_PAGE 4
  14005. #define BTREE_TEXT_ENCODING 5
  14006. #define BTREE_USER_VERSION 6
  14007. #define BTREE_INCR_VACUUM 7
  14008. #define BTREE_APPLICATION_ID 8
  14009. #define BTREE_DATA_VERSION 15 /* A virtual meta-value */
  14010. /*
  14011. ** Kinds of hints that can be passed into the sqlite3BtreeCursorHint()
  14012. ** interface.
  14013. **
  14014. ** BTREE_HINT_RANGE (arguments: Expr*, Mem*)
  14015. **
  14016. ** The first argument is an Expr* (which is guaranteed to be constant for
  14017. ** the lifetime of the cursor) that defines constraints on which rows
  14018. ** might be fetched with this cursor. The Expr* tree may contain
  14019. ** TK_REGISTER nodes that refer to values stored in the array of registers
  14020. ** passed as the second parameter. In other words, if Expr.op==TK_REGISTER
  14021. ** then the value of the node is the value in Mem[pExpr.iTable]. Any
  14022. ** TK_COLUMN node in the expression tree refers to the Expr.iColumn-th
  14023. ** column of the b-tree of the cursor. The Expr tree will not contain
  14024. ** any function calls nor subqueries nor references to b-trees other than
  14025. ** the cursor being hinted.
  14026. **
  14027. ** The design of the _RANGE hint is aid b-tree implementations that try
  14028. ** to prefetch content from remote machines - to provide those
  14029. ** implementations with limits on what needs to be prefetched and thereby
  14030. ** reduce network bandwidth.
  14031. **
  14032. ** Note that BTREE_HINT_FLAGS with BTREE_BULKLOAD is the only hint used by
  14033. ** standard SQLite. The other hints are provided for extentions that use
  14034. ** the SQLite parser and code generator but substitute their own storage
  14035. ** engine.
  14036. */
  14037. #define BTREE_HINT_RANGE 0 /* Range constraints on queries */
  14038. /*
  14039. ** Values that may be OR'd together to form the argument to the
  14040. ** BTREE_HINT_FLAGS hint for sqlite3BtreeCursorHint():
  14041. **
  14042. ** The BTREE_BULKLOAD flag is set on index cursors when the index is going
  14043. ** to be filled with content that is already in sorted order.
  14044. **
  14045. ** The BTREE_SEEK_EQ flag is set on cursors that will get OP_SeekGE or
  14046. ** OP_SeekLE opcodes for a range search, but where the range of entries
  14047. ** selected will all have the same key. In other words, the cursor will
  14048. ** be used only for equality key searches.
  14049. **
  14050. */
  14051. #define BTREE_BULKLOAD 0x00000001 /* Used to full index in sorted order */
  14052. #define BTREE_SEEK_EQ 0x00000002 /* EQ seeks only - no range seeks */
  14053. /*
  14054. ** Flags passed as the third argument to sqlite3BtreeCursor().
  14055. **
  14056. ** For read-only cursors the wrFlag argument is always zero. For read-write
  14057. ** cursors it may be set to either (BTREE_WRCSR|BTREE_FORDELETE) or just
  14058. ** (BTREE_WRCSR). If the BTREE_FORDELETE bit is set, then the cursor will
  14059. ** only be used by SQLite for the following:
  14060. **
  14061. ** * to seek to and then delete specific entries, and/or
  14062. **
  14063. ** * to read values that will be used to create keys that other
  14064. ** BTREE_FORDELETE cursors will seek to and delete.
  14065. **
  14066. ** The BTREE_FORDELETE flag is an optimization hint. It is not used by
  14067. ** by this, the native b-tree engine of SQLite, but it is available to
  14068. ** alternative storage engines that might be substituted in place of this
  14069. ** b-tree system. For alternative storage engines in which a delete of
  14070. ** the main table row automatically deletes corresponding index rows,
  14071. ** the FORDELETE flag hint allows those alternative storage engines to
  14072. ** skip a lot of work. Namely: FORDELETE cursors may treat all SEEK
  14073. ** and DELETE operations as no-ops, and any READ operation against a
  14074. ** FORDELETE cursor may return a null row: 0x01 0x00.
  14075. */
  14076. #define BTREE_WRCSR 0x00000004 /* read-write cursor */
  14077. #define BTREE_FORDELETE 0x00000008 /* Cursor is for seek/delete only */
  14078. SQLITE_PRIVATE int sqlite3BtreeCursor(
  14079. Btree*, /* BTree containing table to open */
  14080. int iTable, /* Index of root page */
  14081. int wrFlag, /* 1 for writing. 0 for read-only */
  14082. struct KeyInfo*, /* First argument to compare function */
  14083. BtCursor *pCursor /* Space to write cursor structure */
  14084. );
  14085. SQLITE_PRIVATE BtCursor *sqlite3BtreeFakeValidCursor(void);
  14086. SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
  14087. SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
  14088. SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor*, unsigned);
  14089. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  14090. SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor*, int, ...);
  14091. #endif
  14092. SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
  14093. SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
  14094. BtCursor*,
  14095. UnpackedRecord *pUnKey,
  14096. i64 intKey,
  14097. int bias,
  14098. int *pRes
  14099. );
  14100. SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*);
  14101. SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor*, int*);
  14102. SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*, u8 flags);
  14103. /* Allowed flags for sqlite3BtreeDelete() and sqlite3BtreeInsert() */
  14104. #define BTREE_SAVEPOSITION 0x02 /* Leave cursor pointing at NEXT or PREV */
  14105. #define BTREE_AUXDELETE 0x04 /* not the primary delete operation */
  14106. #define BTREE_APPEND 0x08 /* Insert is likely an append */
  14107. /* An instance of the BtreePayload object describes the content of a single
  14108. ** entry in either an index or table btree.
  14109. **
  14110. ** Index btrees (used for indexes and also WITHOUT ROWID tables) contain
  14111. ** an arbitrary key and no data. These btrees have pKey,nKey set to the
  14112. ** key and the pData,nData,nZero fields are uninitialized. The aMem,nMem
  14113. ** fields give an array of Mem objects that are a decomposition of the key.
  14114. ** The nMem field might be zero, indicating that no decomposition is available.
  14115. **
  14116. ** Table btrees (used for rowid tables) contain an integer rowid used as
  14117. ** the key and passed in the nKey field. The pKey field is zero.
  14118. ** pData,nData hold the content of the new entry. nZero extra zero bytes
  14119. ** are appended to the end of the content when constructing the entry.
  14120. ** The aMem,nMem fields are uninitialized for table btrees.
  14121. **
  14122. ** Field usage summary:
  14123. **
  14124. ** Table BTrees Index Btrees
  14125. **
  14126. ** pKey always NULL encoded key
  14127. ** nKey the ROWID length of pKey
  14128. ** pData data not used
  14129. ** aMem not used decomposed key value
  14130. ** nMem not used entries in aMem
  14131. ** nData length of pData not used
  14132. ** nZero extra zeros after pData not used
  14133. **
  14134. ** This object is used to pass information into sqlite3BtreeInsert(). The
  14135. ** same information used to be passed as five separate parameters. But placing
  14136. ** the information into this object helps to keep the interface more
  14137. ** organized and understandable, and it also helps the resulting code to
  14138. ** run a little faster by using fewer registers for parameter passing.
  14139. */
  14140. struct BtreePayload {
  14141. const void *pKey; /* Key content for indexes. NULL for tables */
  14142. sqlite3_int64 nKey; /* Size of pKey for indexes. PRIMARY KEY for tabs */
  14143. const void *pData; /* Data for tables. */
  14144. sqlite3_value *aMem; /* First of nMem value in the unpacked pKey */
  14145. u16 nMem; /* Number of aMem[] value. Might be zero */
  14146. int nData; /* Size of pData. 0 if none. */
  14147. int nZero; /* Extra zero data appended after pData,nData */
  14148. };
  14149. SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const BtreePayload *pPayload,
  14150. int flags, int seekResult);
  14151. SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
  14152. SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
  14153. SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int flags);
  14154. SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
  14155. SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int flags);
  14156. SQLITE_PRIVATE i64 sqlite3BtreeIntegerKey(BtCursor*);
  14157. #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
  14158. SQLITE_PRIVATE i64 sqlite3BtreeOffset(BtCursor*);
  14159. #endif
  14160. SQLITE_PRIVATE int sqlite3BtreePayload(BtCursor*, u32 offset, u32 amt, void*);
  14161. SQLITE_PRIVATE const void *sqlite3BtreePayloadFetch(BtCursor*, u32 *pAmt);
  14162. SQLITE_PRIVATE u32 sqlite3BtreePayloadSize(BtCursor*);
  14163. SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeMaxRecordSize(BtCursor*);
  14164. SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
  14165. SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
  14166. SQLITE_PRIVATE i64 sqlite3BtreeRowCountEst(BtCursor*);
  14167. #ifndef SQLITE_OMIT_INCRBLOB
  14168. SQLITE_PRIVATE int sqlite3BtreePayloadChecked(BtCursor*, u32 offset, u32 amt, void*);
  14169. SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
  14170. SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *);
  14171. #endif
  14172. SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
  14173. SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
  14174. SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor*, unsigned int mask);
  14175. SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *pBt);
  14176. SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void);
  14177. #ifndef NDEBUG
  14178. SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
  14179. #endif
  14180. SQLITE_PRIVATE int sqlite3BtreeCursorIsValidNN(BtCursor*);
  14181. #ifndef SQLITE_OMIT_BTREECOUNT
  14182. SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
  14183. #endif
  14184. #ifdef SQLITE_TEST
  14185. SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
  14186. SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
  14187. #endif
  14188. #ifndef SQLITE_OMIT_WAL
  14189. SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
  14190. #endif
  14191. /*
  14192. ** If we are not using shared cache, then there is no need to
  14193. ** use mutexes to access the BtShared structures. So make the
  14194. ** Enter and Leave procedures no-ops.
  14195. */
  14196. #ifndef SQLITE_OMIT_SHARED_CACHE
  14197. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree*);
  14198. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3*);
  14199. SQLITE_PRIVATE int sqlite3BtreeSharable(Btree*);
  14200. SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor*);
  14201. SQLITE_PRIVATE int sqlite3BtreeConnectionCount(Btree*);
  14202. #else
  14203. # define sqlite3BtreeEnter(X)
  14204. # define sqlite3BtreeEnterAll(X)
  14205. # define sqlite3BtreeSharable(X) 0
  14206. # define sqlite3BtreeEnterCursor(X)
  14207. # define sqlite3BtreeConnectionCount(X) 1
  14208. #endif
  14209. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
  14210. SQLITE_PRIVATE void sqlite3BtreeLeave(Btree*);
  14211. SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor*);
  14212. SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3*);
  14213. #ifndef NDEBUG
  14214. /* These routines are used inside assert() statements only. */
  14215. SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree*);
  14216. SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3*);
  14217. SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
  14218. #endif
  14219. #else
  14220. # define sqlite3BtreeLeave(X)
  14221. # define sqlite3BtreeLeaveCursor(X)
  14222. # define sqlite3BtreeLeaveAll(X)
  14223. # define sqlite3BtreeHoldsMutex(X) 1
  14224. # define sqlite3BtreeHoldsAllMutexes(X) 1
  14225. # define sqlite3SchemaMutexHeld(X,Y,Z) 1
  14226. #endif
  14227. #endif /* SQLITE_BTREE_H */
  14228. /************** End of btree.h ***********************************************/
  14229. /************** Continuing where we left off in sqliteInt.h ******************/
  14230. /************** Include vdbe.h in the middle of sqliteInt.h ******************/
  14231. /************** Begin file vdbe.h ********************************************/
  14232. /*
  14233. ** 2001 September 15
  14234. **
  14235. ** The author disclaims copyright to this source code. In place of
  14236. ** a legal notice, here is a blessing:
  14237. **
  14238. ** May you do good and not evil.
  14239. ** May you find forgiveness for yourself and forgive others.
  14240. ** May you share freely, never taking more than you give.
  14241. **
  14242. *************************************************************************
  14243. ** Header file for the Virtual DataBase Engine (VDBE)
  14244. **
  14245. ** This header defines the interface to the virtual database engine
  14246. ** or VDBE. The VDBE implements an abstract machine that runs a
  14247. ** simple program to access and modify the underlying database.
  14248. */
  14249. #ifndef SQLITE_VDBE_H
  14250. #define SQLITE_VDBE_H
  14251. /* #include <stdio.h> */
  14252. /*
  14253. ** A single VDBE is an opaque structure named "Vdbe". Only routines
  14254. ** in the source file sqliteVdbe.c are allowed to see the insides
  14255. ** of this structure.
  14256. */
  14257. typedef struct Vdbe Vdbe;
  14258. /*
  14259. ** The names of the following types declared in vdbeInt.h are required
  14260. ** for the VdbeOp definition.
  14261. */
  14262. typedef struct sqlite3_value Mem;
  14263. typedef struct SubProgram SubProgram;
  14264. /*
  14265. ** A single instruction of the virtual machine has an opcode
  14266. ** and as many as three operands. The instruction is recorded
  14267. ** as an instance of the following structure:
  14268. */
  14269. struct VdbeOp {
  14270. u8 opcode; /* What operation to perform */
  14271. signed char p4type; /* One of the P4_xxx constants for p4 */
  14272. u16 p5; /* Fifth parameter is an unsigned 16-bit integer */
  14273. int p1; /* First operand */
  14274. int p2; /* Second parameter (often the jump destination) */
  14275. int p3; /* The third parameter */
  14276. union p4union { /* fourth parameter */
  14277. int i; /* Integer value if p4type==P4_INT32 */
  14278. void *p; /* Generic pointer */
  14279. char *z; /* Pointer to data for string (char array) types */
  14280. i64 *pI64; /* Used when p4type is P4_INT64 */
  14281. double *pReal; /* Used when p4type is P4_REAL */
  14282. FuncDef *pFunc; /* Used when p4type is P4_FUNCDEF */
  14283. sqlite3_context *pCtx; /* Used when p4type is P4_FUNCCTX */
  14284. CollSeq *pColl; /* Used when p4type is P4_COLLSEQ */
  14285. Mem *pMem; /* Used when p4type is P4_MEM */
  14286. VTable *pVtab; /* Used when p4type is P4_VTAB */
  14287. KeyInfo *pKeyInfo; /* Used when p4type is P4_KEYINFO */
  14288. int *ai; /* Used when p4type is P4_INTARRAY */
  14289. SubProgram *pProgram; /* Used when p4type is P4_SUBPROGRAM */
  14290. Table *pTab; /* Used when p4type is P4_TABLE */
  14291. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  14292. Expr *pExpr; /* Used when p4type is P4_EXPR */
  14293. #endif
  14294. int (*xAdvance)(BtCursor *, int);
  14295. } p4;
  14296. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  14297. char *zComment; /* Comment to improve readability */
  14298. #endif
  14299. #ifdef VDBE_PROFILE
  14300. u32 cnt; /* Number of times this instruction was executed */
  14301. u64 cycles; /* Total time spent executing this instruction */
  14302. #endif
  14303. #ifdef SQLITE_VDBE_COVERAGE
  14304. u32 iSrcLine; /* Source-code line that generated this opcode
  14305. ** with flags in the upper 8 bits */
  14306. #endif
  14307. };
  14308. typedef struct VdbeOp VdbeOp;
  14309. /*
  14310. ** A sub-routine used to implement a trigger program.
  14311. */
  14312. struct SubProgram {
  14313. VdbeOp *aOp; /* Array of opcodes for sub-program */
  14314. int nOp; /* Elements in aOp[] */
  14315. int nMem; /* Number of memory cells required */
  14316. int nCsr; /* Number of cursors required */
  14317. u8 *aOnce; /* Array of OP_Once flags */
  14318. void *token; /* id that may be used to recursive triggers */
  14319. SubProgram *pNext; /* Next sub-program already visited */
  14320. };
  14321. /*
  14322. ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
  14323. ** it takes up less space.
  14324. */
  14325. struct VdbeOpList {
  14326. u8 opcode; /* What operation to perform */
  14327. signed char p1; /* First operand */
  14328. signed char p2; /* Second parameter (often the jump destination) */
  14329. signed char p3; /* Third parameter */
  14330. };
  14331. typedef struct VdbeOpList VdbeOpList;
  14332. /*
  14333. ** Allowed values of VdbeOp.p4type
  14334. */
  14335. #define P4_NOTUSED 0 /* The P4 parameter is not used */
  14336. #define P4_TRANSIENT 0 /* P4 is a pointer to a transient string */
  14337. #define P4_STATIC (-1) /* Pointer to a static string */
  14338. #define P4_COLLSEQ (-2) /* P4 is a pointer to a CollSeq structure */
  14339. #define P4_INT32 (-3) /* P4 is a 32-bit signed integer */
  14340. #define P4_SUBPROGRAM (-4) /* P4 is a pointer to a SubProgram structure */
  14341. #define P4_ADVANCE (-5) /* P4 is a pointer to BtreeNext() or BtreePrev() */
  14342. #define P4_TABLE (-6) /* P4 is a pointer to a Table structure */
  14343. /* Above do not own any resources. Must free those below */
  14344. #define P4_FREE_IF_LE (-7)
  14345. #define P4_DYNAMIC (-7) /* Pointer to memory from sqliteMalloc() */
  14346. #define P4_FUNCDEF (-8) /* P4 is a pointer to a FuncDef structure */
  14347. #define P4_KEYINFO (-9) /* P4 is a pointer to a KeyInfo structure */
  14348. #define P4_EXPR (-10) /* P4 is a pointer to an Expr tree */
  14349. #define P4_MEM (-11) /* P4 is a pointer to a Mem* structure */
  14350. #define P4_VTAB (-12) /* P4 is a pointer to an sqlite3_vtab structure */
  14351. #define P4_REAL (-13) /* P4 is a 64-bit floating point value */
  14352. #define P4_INT64 (-14) /* P4 is a 64-bit signed integer */
  14353. #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
  14354. #define P4_FUNCCTX (-16) /* P4 is a pointer to an sqlite3_context object */
  14355. #define P4_DYNBLOB (-17) /* Pointer to memory from sqliteMalloc() */
  14356. /* Error message codes for OP_Halt */
  14357. #define P5_ConstraintNotNull 1
  14358. #define P5_ConstraintUnique 2
  14359. #define P5_ConstraintCheck 3
  14360. #define P5_ConstraintFK 4
  14361. /*
  14362. ** The Vdbe.aColName array contains 5n Mem structures, where n is the
  14363. ** number of columns of data returned by the statement.
  14364. */
  14365. #define COLNAME_NAME 0
  14366. #define COLNAME_DECLTYPE 1
  14367. #define COLNAME_DATABASE 2
  14368. #define COLNAME_TABLE 3
  14369. #define COLNAME_COLUMN 4
  14370. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  14371. # define COLNAME_N 5 /* Number of COLNAME_xxx symbols */
  14372. #else
  14373. # ifdef SQLITE_OMIT_DECLTYPE
  14374. # define COLNAME_N 1 /* Store only the name */
  14375. # else
  14376. # define COLNAME_N 2 /* Store the name and decltype */
  14377. # endif
  14378. #endif
  14379. /*
  14380. ** The following macro converts a label returned by sqlite3VdbeMakeLabel()
  14381. ** into an index into the Parse.aLabel[] array that contains the resolved
  14382. ** address of that label.
  14383. */
  14384. #define ADDR(X) (~(X))
  14385. /*
  14386. ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
  14387. ** header file that defines a number for each opcode used by the VDBE.
  14388. */
  14389. /************** Include opcodes.h in the middle of vdbe.h ********************/
  14390. /************** Begin file opcodes.h *****************************************/
  14391. /* Automatically generated. Do not edit */
  14392. /* See the tool/mkopcodeh.tcl script for details */
  14393. #define OP_Savepoint 0
  14394. #define OP_AutoCommit 1
  14395. #define OP_Transaction 2
  14396. #define OP_SorterNext 3 /* jump */
  14397. #define OP_Prev 4 /* jump */
  14398. #define OP_Next 5 /* jump */
  14399. #define OP_Checkpoint 6
  14400. #define OP_JournalMode 7
  14401. #define OP_Vacuum 8
  14402. #define OP_VFilter 9 /* jump, synopsis: iplan=r[P3] zplan='P4' */
  14403. #define OP_VUpdate 10 /* synopsis: data=r[P3@P2] */
  14404. #define OP_Goto 11 /* jump */
  14405. #define OP_Gosub 12 /* jump */
  14406. #define OP_InitCoroutine 13 /* jump */
  14407. #define OP_Yield 14 /* jump */
  14408. #define OP_MustBeInt 15 /* jump */
  14409. #define OP_Jump 16 /* jump */
  14410. #define OP_Once 17 /* jump */
  14411. #define OP_If 18 /* jump */
  14412. #define OP_Not 19 /* same as TK_NOT, synopsis: r[P2]= !r[P1] */
  14413. #define OP_IfNot 20 /* jump */
  14414. #define OP_IfNullRow 21 /* jump, synopsis: if P1.nullRow then r[P3]=NULL, goto P2 */
  14415. #define OP_SeekLT 22 /* jump, synopsis: key=r[P3@P4] */
  14416. #define OP_SeekLE 23 /* jump, synopsis: key=r[P3@P4] */
  14417. #define OP_SeekGE 24 /* jump, synopsis: key=r[P3@P4] */
  14418. #define OP_SeekGT 25 /* jump, synopsis: key=r[P3@P4] */
  14419. #define OP_IfNoHope 26 /* jump, synopsis: key=r[P3@P4] */
  14420. #define OP_NoConflict 27 /* jump, synopsis: key=r[P3@P4] */
  14421. #define OP_NotFound 28 /* jump, synopsis: key=r[P3@P4] */
  14422. #define OP_Found 29 /* jump, synopsis: key=r[P3@P4] */
  14423. #define OP_SeekRowid 30 /* jump, synopsis: intkey=r[P3] */
  14424. #define OP_NotExists 31 /* jump, synopsis: intkey=r[P3] */
  14425. #define OP_Last 32 /* jump */
  14426. #define OP_IfSmaller 33 /* jump */
  14427. #define OP_SorterSort 34 /* jump */
  14428. #define OP_Sort 35 /* jump */
  14429. #define OP_Rewind 36 /* jump */
  14430. #define OP_IdxLE 37 /* jump, synopsis: key=r[P3@P4] */
  14431. #define OP_IdxGT 38 /* jump, synopsis: key=r[P3@P4] */
  14432. #define OP_IdxLT 39 /* jump, synopsis: key=r[P3@P4] */
  14433. #define OP_IdxGE 40 /* jump, synopsis: key=r[P3@P4] */
  14434. #define OP_RowSetRead 41 /* jump, synopsis: r[P3]=rowset(P1) */
  14435. #define OP_RowSetTest 42 /* jump, synopsis: if r[P3] in rowset(P1) goto P2 */
  14436. #define OP_Or 43 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */
  14437. #define OP_And 44 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */
  14438. #define OP_Program 45 /* jump */
  14439. #define OP_FkIfZero 46 /* jump, synopsis: if fkctr[P1]==0 goto P2 */
  14440. #define OP_IfPos 47 /* jump, synopsis: if r[P1]>0 then r[P1]-=P3, goto P2 */
  14441. #define OP_IfNotZero 48 /* jump, synopsis: if r[P1]!=0 then r[P1]--, goto P2 */
  14442. #define OP_DecrJumpZero 49 /* jump, synopsis: if (--r[P1])==0 goto P2 */
  14443. #define OP_IsNull 50 /* jump, same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */
  14444. #define OP_NotNull 51 /* jump, same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */
  14445. #define OP_Ne 52 /* jump, same as TK_NE, synopsis: IF r[P3]!=r[P1] */
  14446. #define OP_Eq 53 /* jump, same as TK_EQ, synopsis: IF r[P3]==r[P1] */
  14447. #define OP_Gt 54 /* jump, same as TK_GT, synopsis: IF r[P3]>r[P1] */
  14448. #define OP_Le 55 /* jump, same as TK_LE, synopsis: IF r[P3]<=r[P1] */
  14449. #define OP_Lt 56 /* jump, same as TK_LT, synopsis: IF r[P3]<r[P1] */
  14450. #define OP_Ge 57 /* jump, same as TK_GE, synopsis: IF r[P3]>=r[P1] */
  14451. #define OP_ElseNotEq 58 /* jump, same as TK_ESCAPE */
  14452. #define OP_IncrVacuum 59 /* jump */
  14453. #define OP_VNext 60 /* jump */
  14454. #define OP_Init 61 /* jump, synopsis: Start at P2 */
  14455. #define OP_PureFunc0 62
  14456. #define OP_Function0 63 /* synopsis: r[P3]=func(r[P2@P5]) */
  14457. #define OP_PureFunc 64
  14458. #define OP_Function 65 /* synopsis: r[P3]=func(r[P2@P5]) */
  14459. #define OP_Return 66
  14460. #define OP_EndCoroutine 67
  14461. #define OP_HaltIfNull 68 /* synopsis: if r[P3]=null halt */
  14462. #define OP_Halt 69
  14463. #define OP_Integer 70 /* synopsis: r[P2]=P1 */
  14464. #define OP_Int64 71 /* synopsis: r[P2]=P4 */
  14465. #define OP_String 72 /* synopsis: r[P2]='P4' (len=P1) */
  14466. #define OP_Null 73 /* synopsis: r[P2..P3]=NULL */
  14467. #define OP_SoftNull 74 /* synopsis: r[P1]=NULL */
  14468. #define OP_Blob 75 /* synopsis: r[P2]=P4 (len=P1) */
  14469. #define OP_Variable 76 /* synopsis: r[P2]=parameter(P1,P4) */
  14470. #define OP_Move 77 /* synopsis: r[P2@P3]=r[P1@P3] */
  14471. #define OP_Copy 78 /* synopsis: r[P2@P3+1]=r[P1@P3+1] */
  14472. #define OP_SCopy 79 /* synopsis: r[P2]=r[P1] */
  14473. #define OP_IntCopy 80 /* synopsis: r[P2]=r[P1] */
  14474. #define OP_ResultRow 81 /* synopsis: output=r[P1@P2] */
  14475. #define OP_CollSeq 82
  14476. #define OP_AddImm 83 /* synopsis: r[P1]=r[P1]+P2 */
  14477. #define OP_RealAffinity 84
  14478. #define OP_Cast 85 /* synopsis: affinity(r[P1]) */
  14479. #define OP_Permutation 86
  14480. #define OP_Compare 87 /* synopsis: r[P1@P3] <-> r[P2@P3] */
  14481. #define OP_IsTrue 88 /* synopsis: r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4 */
  14482. #define OP_Offset 89 /* synopsis: r[P3] = sqlite_offset(P1) */
  14483. #define OP_Column 90 /* synopsis: r[P3]=PX */
  14484. #define OP_Affinity 91 /* synopsis: affinity(r[P1@P2]) */
  14485. #define OP_MakeRecord 92 /* synopsis: r[P3]=mkrec(r[P1@P2]) */
  14486. #define OP_Count 93 /* synopsis: r[P2]=count() */
  14487. #define OP_ReadCookie 94
  14488. #define OP_SetCookie 95
  14489. #define OP_BitAnd 96 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */
  14490. #define OP_BitOr 97 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */
  14491. #define OP_ShiftLeft 98 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<<r[P1] */
  14492. #define OP_ShiftRight 99 /* same as TK_RSHIFT, synopsis: r[P3]=r[P2]>>r[P1] */
  14493. #define OP_Add 100 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */
  14494. #define OP_Subtract 101 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */
  14495. #define OP_Multiply 102 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */
  14496. #define OP_Divide 103 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */
  14497. #define OP_Remainder 104 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */
  14498. #define OP_Concat 105 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */
  14499. #define OP_ReopenIdx 106 /* synopsis: root=P2 iDb=P3 */
  14500. #define OP_BitNot 107 /* same as TK_BITNOT, synopsis: r[P2]= ~r[P1] */
  14501. #define OP_OpenRead 108 /* synopsis: root=P2 iDb=P3 */
  14502. #define OP_OpenWrite 109 /* synopsis: root=P2 iDb=P3 */
  14503. #define OP_String8 110 /* same as TK_STRING, synopsis: r[P2]='P4' */
  14504. #define OP_OpenDup 111
  14505. #define OP_OpenAutoindex 112 /* synopsis: nColumn=P2 */
  14506. #define OP_OpenEphemeral 113 /* synopsis: nColumn=P2 */
  14507. #define OP_SorterOpen 114
  14508. #define OP_SequenceTest 115 /* synopsis: if( cursor[P1].ctr++ ) pc = P2 */
  14509. #define OP_OpenPseudo 116 /* synopsis: P3 columns in r[P2] */
  14510. #define OP_Close 117
  14511. #define OP_ColumnsUsed 118
  14512. #define OP_SeekHit 119 /* synopsis: seekHit=P2 */
  14513. #define OP_Sequence 120 /* synopsis: r[P2]=cursor[P1].ctr++ */
  14514. #define OP_NewRowid 121 /* synopsis: r[P2]=rowid */
  14515. #define OP_Insert 122 /* synopsis: intkey=r[P3] data=r[P2] */
  14516. #define OP_Delete 123
  14517. #define OP_ResetCount 124
  14518. #define OP_SorterCompare 125 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */
  14519. #define OP_SorterData 126 /* synopsis: r[P2]=data */
  14520. #define OP_RowData 127 /* synopsis: r[P2]=data */
  14521. #define OP_Rowid 128 /* synopsis: r[P2]=rowid */
  14522. #define OP_NullRow 129
  14523. #define OP_SeekEnd 130
  14524. #define OP_SorterInsert 131 /* synopsis: key=r[P2] */
  14525. #define OP_IdxInsert 132 /* synopsis: key=r[P2] */
  14526. #define OP_IdxDelete 133 /* synopsis: key=r[P2@P3] */
  14527. #define OP_DeferredSeek 134 /* synopsis: Move P3 to P1.rowid if needed */
  14528. #define OP_IdxRowid 135 /* synopsis: r[P2]=rowid */
  14529. #define OP_Destroy 136
  14530. #define OP_Clear 137
  14531. #define OP_ResetSorter 138
  14532. #define OP_CreateBtree 139 /* synopsis: r[P2]=root iDb=P1 flags=P3 */
  14533. #define OP_SqlExec 140
  14534. #define OP_ParseSchema 141
  14535. #define OP_LoadAnalysis 142
  14536. #define OP_DropTable 143
  14537. #define OP_DropIndex 144
  14538. #define OP_Real 145 /* same as TK_FLOAT, synopsis: r[P2]=P4 */
  14539. #define OP_DropTrigger 146
  14540. #define OP_IntegrityCk 147
  14541. #define OP_RowSetAdd 148 /* synopsis: rowset(P1)=r[P2] */
  14542. #define OP_Param 149
  14543. #define OP_FkCounter 150 /* synopsis: fkctr[P1]+=P2 */
  14544. #define OP_MemMax 151 /* synopsis: r[P1]=max(r[P1],r[P2]) */
  14545. #define OP_OffsetLimit 152 /* synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) */
  14546. #define OP_AggInverse 153 /* synopsis: accum=r[P3] inverse(r[P2@P5]) */
  14547. #define OP_AggStep 154 /* synopsis: accum=r[P3] step(r[P2@P5]) */
  14548. #define OP_AggStep1 155 /* synopsis: accum=r[P3] step(r[P2@P5]) */
  14549. #define OP_AggValue 156 /* synopsis: r[P3]=value N=P2 */
  14550. #define OP_AggFinal 157 /* synopsis: accum=r[P1] N=P2 */
  14551. #define OP_Expire 158
  14552. #define OP_TableLock 159 /* synopsis: iDb=P1 root=P2 write=P3 */
  14553. #define OP_VBegin 160
  14554. #define OP_VCreate 161
  14555. #define OP_VDestroy 162
  14556. #define OP_VOpen 163
  14557. #define OP_VColumn 164 /* synopsis: r[P3]=vcolumn(P2) */
  14558. #define OP_VRename 165
  14559. #define OP_Pagecount 166
  14560. #define OP_MaxPgcnt 167
  14561. #define OP_Trace 168
  14562. #define OP_CursorHint 169
  14563. #define OP_Noop 170
  14564. #define OP_Explain 171
  14565. #define OP_Abortable 172
  14566. /* Properties such as "out2" or "jump" that are specified in
  14567. ** comments following the "case" for each opcode in the vdbe.c
  14568. ** are encoded into bitvectors as follows:
  14569. */
  14570. #define OPFLG_JUMP 0x01 /* jump: P2 holds jmp target */
  14571. #define OPFLG_IN1 0x02 /* in1: P1 is an input */
  14572. #define OPFLG_IN2 0x04 /* in2: P2 is an input */
  14573. #define OPFLG_IN3 0x08 /* in3: P3 is an input */
  14574. #define OPFLG_OUT2 0x10 /* out2: P2 is an output */
  14575. #define OPFLG_OUT3 0x20 /* out3: P3 is an output */
  14576. #define OPFLG_INITIALIZER {\
  14577. /* 0 */ 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x00, 0x10,\
  14578. /* 8 */ 0x00, 0x01, 0x00, 0x01, 0x01, 0x01, 0x03, 0x03,\
  14579. /* 16 */ 0x01, 0x01, 0x03, 0x12, 0x03, 0x01, 0x09, 0x09,\
  14580. /* 24 */ 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09,\
  14581. /* 32 */ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,\
  14582. /* 40 */ 0x01, 0x23, 0x0b, 0x26, 0x26, 0x01, 0x01, 0x03,\
  14583. /* 48 */ 0x03, 0x03, 0x03, 0x03, 0x0b, 0x0b, 0x0b, 0x0b,\
  14584. /* 56 */ 0x0b, 0x0b, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,\
  14585. /* 64 */ 0x00, 0x00, 0x02, 0x02, 0x08, 0x00, 0x10, 0x10,\
  14586. /* 72 */ 0x10, 0x10, 0x00, 0x10, 0x10, 0x00, 0x00, 0x10,\
  14587. /* 80 */ 0x10, 0x00, 0x00, 0x02, 0x02, 0x02, 0x00, 0x00,\
  14588. /* 88 */ 0x12, 0x20, 0x00, 0x00, 0x00, 0x10, 0x10, 0x00,\
  14589. /* 96 */ 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26,\
  14590. /* 104 */ 0x26, 0x26, 0x00, 0x12, 0x00, 0x00, 0x10, 0x00,\
  14591. /* 112 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
  14592. /* 120 */ 0x10, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
  14593. /* 128 */ 0x10, 0x00, 0x00, 0x04, 0x04, 0x00, 0x00, 0x10,\
  14594. /* 136 */ 0x10, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00,\
  14595. /* 144 */ 0x00, 0x10, 0x00, 0x00, 0x06, 0x10, 0x00, 0x04,\
  14596. /* 152 */ 0x1a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
  14597. /* 160 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x10,\
  14598. /* 168 */ 0x00, 0x00, 0x00, 0x00, 0x00,}
  14599. /* The sqlite3P2Values() routine is able to run faster if it knows
  14600. ** the value of the largest JUMP opcode. The smaller the maximum
  14601. ** JUMP opcode the better, so the mkopcodeh.tcl script that
  14602. ** generated this include file strives to group all JUMP opcodes
  14603. ** together near the beginning of the list.
  14604. */
  14605. #define SQLITE_MX_JUMP_OPCODE 61 /* Maximum JUMP opcode */
  14606. /************** End of opcodes.h *********************************************/
  14607. /************** Continuing where we left off in vdbe.h ***********************/
  14608. /*
  14609. ** Additional non-public SQLITE_PREPARE_* flags
  14610. */
  14611. #define SQLITE_PREPARE_SAVESQL 0x80 /* Preserve SQL text */
  14612. #define SQLITE_PREPARE_MASK 0x0f /* Mask of public flags */
  14613. /*
  14614. ** Prototypes for the VDBE interface. See comments on the implementation
  14615. ** for a description of what each of these routines does.
  14616. */
  14617. SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse*);
  14618. SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
  14619. SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
  14620. SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
  14621. SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe*,int);
  14622. SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe*,int,const char*);
  14623. SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe*,int,const char*,...);
  14624. SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
  14625. SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
  14626. SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(Vdbe*,int,int,int,int,const u8*,int);
  14627. SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
  14628. SQLITE_PRIVATE void sqlite3VdbeEndCoroutine(Vdbe*,int);
  14629. #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
  14630. SQLITE_PRIVATE void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N);
  14631. SQLITE_PRIVATE void sqlite3VdbeVerifyNoResultRow(Vdbe *p);
  14632. #else
  14633. # define sqlite3VdbeVerifyNoMallocRequired(A,B)
  14634. # define sqlite3VdbeVerifyNoResultRow(A)
  14635. #endif
  14636. #if defined(SQLITE_DEBUG)
  14637. SQLITE_PRIVATE void sqlite3VdbeVerifyAbortable(Vdbe *p, int);
  14638. #else
  14639. # define sqlite3VdbeVerifyAbortable(A,B)
  14640. #endif
  14641. SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp,int iLineno);
  14642. #ifndef SQLITE_OMIT_EXPLAIN
  14643. SQLITE_PRIVATE void sqlite3VdbeExplain(Parse*,u8,const char*,...);
  14644. SQLITE_PRIVATE void sqlite3VdbeExplainPop(Parse*);
  14645. SQLITE_PRIVATE int sqlite3VdbeExplainParent(Parse*);
  14646. # define ExplainQueryPlan(P) sqlite3VdbeExplain P
  14647. # define ExplainQueryPlanPop(P) sqlite3VdbeExplainPop(P)
  14648. # define ExplainQueryPlanParent(P) sqlite3VdbeExplainParent(P)
  14649. #else
  14650. # define ExplainQueryPlan(P)
  14651. # define ExplainQueryPlanPop(P)
  14652. # define ExplainQueryPlanParent(P) 0
  14653. # define sqlite3ExplainBreakpoint(A,B) /*no-op*/
  14654. #endif
  14655. #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_EXPLAIN)
  14656. SQLITE_PRIVATE void sqlite3ExplainBreakpoint(const char*,const char*);
  14657. #else
  14658. # define sqlite3ExplainBreakpoint(A,B) /*no-op*/
  14659. #endif
  14660. SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
  14661. SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe*, u32 addr, u8);
  14662. SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);
  14663. SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);
  14664. SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);
  14665. SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u16 P5);
  14666. SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
  14667. SQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe*, int addr);
  14668. SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe*, u8 op);
  14669. SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
  14670. SQLITE_PRIVATE void sqlite3VdbeAppendP4(Vdbe*, void *pP4, int p4type);
  14671. SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse*, Index*);
  14672. SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
  14673. SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
  14674. SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Parse*);
  14675. SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
  14676. SQLITE_PRIVATE void sqlite3VdbeReusable(Vdbe*);
  14677. SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
  14678. SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3*,Vdbe*);
  14679. SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
  14680. SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
  14681. SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
  14682. SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
  14683. #ifdef SQLITE_DEBUG
  14684. SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *, int);
  14685. #endif
  14686. SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
  14687. SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
  14688. SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
  14689. SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
  14690. SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
  14691. SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
  14692. SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
  14693. SQLITE_PRIVATE u8 sqlite3VdbePrepareFlags(Vdbe*);
  14694. SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, u8);
  14695. #ifdef SQLITE_ENABLE_NORMALIZE
  14696. SQLITE_PRIVATE void sqlite3VdbeAddDblquoteStr(sqlite3*,Vdbe*,const char*);
  14697. SQLITE_PRIVATE int sqlite3VdbeUsesDoubleQuotedString(Vdbe*,const char*);
  14698. #endif
  14699. SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
  14700. SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
  14701. SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe*, int, u8);
  14702. SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
  14703. #ifndef SQLITE_OMIT_TRACE
  14704. SQLITE_PRIVATE char *sqlite3VdbeExpandSql(Vdbe*, const char*);
  14705. #endif
  14706. SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
  14707. SQLITE_PRIVATE int sqlite3BlobCompare(const Mem*, const Mem*);
  14708. SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
  14709. SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
  14710. SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(int, const void *, UnpackedRecord *, int);
  14711. SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo*);
  14712. typedef int (*RecordCompare)(int,const void*,UnpackedRecord*);
  14713. SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord*);
  14714. #ifndef SQLITE_OMIT_TRIGGER
  14715. SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
  14716. #endif
  14717. SQLITE_PRIVATE int sqlite3NotPureFunc(sqlite3_context*);
  14718. /* Use SQLITE_ENABLE_COMMENTS to enable generation of extra comments on
  14719. ** each VDBE opcode.
  14720. **
  14721. ** Use the SQLITE_ENABLE_MODULE_COMMENTS macro to see some extra no-op
  14722. ** comments in VDBE programs that show key decision points in the code
  14723. ** generator.
  14724. */
  14725. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  14726. SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe*, const char*, ...);
  14727. # define VdbeComment(X) sqlite3VdbeComment X
  14728. SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
  14729. # define VdbeNoopComment(X) sqlite3VdbeNoopComment X
  14730. # ifdef SQLITE_ENABLE_MODULE_COMMENTS
  14731. # define VdbeModuleComment(X) sqlite3VdbeNoopComment X
  14732. # else
  14733. # define VdbeModuleComment(X)
  14734. # endif
  14735. #else
  14736. # define VdbeComment(X)
  14737. # define VdbeNoopComment(X)
  14738. # define VdbeModuleComment(X)
  14739. #endif
  14740. /*
  14741. ** The VdbeCoverage macros are used to set a coverage testing point
  14742. ** for VDBE branch instructions. The coverage testing points are line
  14743. ** numbers in the sqlite3.c source file. VDBE branch coverage testing
  14744. ** only works with an amalagmation build. That's ok since a VDBE branch
  14745. ** coverage build designed for testing the test suite only. No application
  14746. ** should ever ship with VDBE branch coverage measuring turned on.
  14747. **
  14748. ** VdbeCoverage(v) // Mark the previously coded instruction
  14749. ** // as a branch
  14750. **
  14751. ** VdbeCoverageIf(v, conditional) // Mark previous if conditional true
  14752. **
  14753. ** VdbeCoverageAlwaysTaken(v) // Previous branch is always taken
  14754. **
  14755. ** VdbeCoverageNeverTaken(v) // Previous branch is never taken
  14756. **
  14757. ** VdbeCoverageNeverNull(v) // Previous three-way branch is only
  14758. ** // taken on the first two ways. The
  14759. ** // NULL option is not possible
  14760. **
  14761. ** VdbeCoverageEqNe(v) // Previous OP_Jump is only interested
  14762. ** // in distingishing equal and not-equal.
  14763. **
  14764. ** Every VDBE branch operation must be tagged with one of the macros above.
  14765. ** If not, then when "make test" is run with -DSQLITE_VDBE_COVERAGE and
  14766. ** -DSQLITE_DEBUG then an ALWAYS() will fail in the vdbeTakeBranch()
  14767. ** routine in vdbe.c, alerting the developer to the missed tag.
  14768. **
  14769. ** During testing, the test application will invoke
  14770. ** sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE,...) to set a callback
  14771. ** routine that is invoked as each bytecode branch is taken. The callback
  14772. ** contains the sqlite3.c source line number ov the VdbeCoverage macro and
  14773. ** flags to indicate whether or not the branch was taken. The test application
  14774. ** is responsible for keeping track of this and reporting byte-code branches
  14775. ** that are never taken.
  14776. **
  14777. ** See the VdbeBranchTaken() macro and vdbeTakeBranch() function in the
  14778. ** vdbe.c source file for additional information.
  14779. */
  14780. #ifdef SQLITE_VDBE_COVERAGE
  14781. SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe*,int);
  14782. # define VdbeCoverage(v) sqlite3VdbeSetLineNumber(v,__LINE__)
  14783. # define VdbeCoverageIf(v,x) if(x)sqlite3VdbeSetLineNumber(v,__LINE__)
  14784. # define VdbeCoverageAlwaysTaken(v) \
  14785. sqlite3VdbeSetLineNumber(v,__LINE__|0x5000000);
  14786. # define VdbeCoverageNeverTaken(v) \
  14787. sqlite3VdbeSetLineNumber(v,__LINE__|0x6000000);
  14788. # define VdbeCoverageNeverNull(v) \
  14789. sqlite3VdbeSetLineNumber(v,__LINE__|0x4000000);
  14790. # define VdbeCoverageNeverNullIf(v,x) \
  14791. if(x)sqlite3VdbeSetLineNumber(v,__LINE__|0x4000000);
  14792. # define VdbeCoverageEqNe(v) \
  14793. sqlite3VdbeSetLineNumber(v,__LINE__|0x8000000);
  14794. # define VDBE_OFFSET_LINENO(x) (__LINE__+x)
  14795. #else
  14796. # define VdbeCoverage(v)
  14797. # define VdbeCoverageIf(v,x)
  14798. # define VdbeCoverageAlwaysTaken(v)
  14799. # define VdbeCoverageNeverTaken(v)
  14800. # define VdbeCoverageNeverNull(v)
  14801. # define VdbeCoverageNeverNullIf(v,x)
  14802. # define VdbeCoverageEqNe(v)
  14803. # define VDBE_OFFSET_LINENO(x) 0
  14804. #endif
  14805. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  14806. SQLITE_PRIVATE void sqlite3VdbeScanStatus(Vdbe*, int, int, int, LogEst, const char*);
  14807. #else
  14808. # define sqlite3VdbeScanStatus(a,b,c,d,e)
  14809. #endif
  14810. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  14811. SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, VdbeOp*);
  14812. #endif
  14813. #endif /* SQLITE_VDBE_H */
  14814. /************** End of vdbe.h ************************************************/
  14815. /************** Continuing where we left off in sqliteInt.h ******************/
  14816. /************** Include pager.h in the middle of sqliteInt.h *****************/
  14817. /************** Begin file pager.h *******************************************/
  14818. /*
  14819. ** 2001 September 15
  14820. **
  14821. ** The author disclaims copyright to this source code. In place of
  14822. ** a legal notice, here is a blessing:
  14823. **
  14824. ** May you do good and not evil.
  14825. ** May you find forgiveness for yourself and forgive others.
  14826. ** May you share freely, never taking more than you give.
  14827. **
  14828. *************************************************************************
  14829. ** This header file defines the interface that the sqlite page cache
  14830. ** subsystem. The page cache subsystem reads and writes a file a page
  14831. ** at a time and provides a journal for rollback.
  14832. */
  14833. #ifndef SQLITE_PAGER_H
  14834. #define SQLITE_PAGER_H
  14835. /*
  14836. ** Default maximum size for persistent journal files. A negative
  14837. ** value means no limit. This value may be overridden using the
  14838. ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
  14839. */
  14840. #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
  14841. #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
  14842. #endif
  14843. /*
  14844. ** The type used to represent a page number. The first page in a file
  14845. ** is called page 1. 0 is used to represent "not a page".
  14846. */
  14847. typedef u32 Pgno;
  14848. /*
  14849. ** Each open file is managed by a separate instance of the "Pager" structure.
  14850. */
  14851. typedef struct Pager Pager;
  14852. /*
  14853. ** Handle type for pages.
  14854. */
  14855. typedef struct PgHdr DbPage;
  14856. /*
  14857. ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
  14858. ** reserved for working around a windows/posix incompatibility). It is
  14859. ** used in the journal to signify that the remainder of the journal file
  14860. ** is devoted to storing a master journal name - there are no more pages to
  14861. ** roll back. See comments for function writeMasterJournal() in pager.c
  14862. ** for details.
  14863. */
  14864. #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
  14865. /*
  14866. ** Allowed values for the flags parameter to sqlite3PagerOpen().
  14867. **
  14868. ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
  14869. */
  14870. #define PAGER_OMIT_JOURNAL 0x0001 /* Do not use a rollback journal */
  14871. #define PAGER_MEMORY 0x0002 /* In-memory database */
  14872. /*
  14873. ** Valid values for the second argument to sqlite3PagerLockingMode().
  14874. */
  14875. #define PAGER_LOCKINGMODE_QUERY -1
  14876. #define PAGER_LOCKINGMODE_NORMAL 0
  14877. #define PAGER_LOCKINGMODE_EXCLUSIVE 1
  14878. /*
  14879. ** Numeric constants that encode the journalmode.
  14880. **
  14881. ** The numeric values encoded here (other than PAGER_JOURNALMODE_QUERY)
  14882. ** are exposed in the API via the "PRAGMA journal_mode" command and
  14883. ** therefore cannot be changed without a compatibility break.
  14884. */
  14885. #define PAGER_JOURNALMODE_QUERY (-1) /* Query the value of journalmode */
  14886. #define PAGER_JOURNALMODE_DELETE 0 /* Commit by deleting journal file */
  14887. #define PAGER_JOURNALMODE_PERSIST 1 /* Commit by zeroing journal header */
  14888. #define PAGER_JOURNALMODE_OFF 2 /* Journal omitted. */
  14889. #define PAGER_JOURNALMODE_TRUNCATE 3 /* Commit by truncating journal */
  14890. #define PAGER_JOURNALMODE_MEMORY 4 /* In-memory journal file */
  14891. #define PAGER_JOURNALMODE_WAL 5 /* Use write-ahead logging */
  14892. /*
  14893. ** Flags that make up the mask passed to sqlite3PagerGet().
  14894. */
  14895. #define PAGER_GET_NOCONTENT 0x01 /* Do not load data from disk */
  14896. #define PAGER_GET_READONLY 0x02 /* Read-only page is acceptable */
  14897. /*
  14898. ** Flags for sqlite3PagerSetFlags()
  14899. **
  14900. ** Value constraints (enforced via assert()):
  14901. ** PAGER_FULLFSYNC == SQLITE_FullFSync
  14902. ** PAGER_CKPT_FULLFSYNC == SQLITE_CkptFullFSync
  14903. ** PAGER_CACHE_SPILL == SQLITE_CacheSpill
  14904. */
  14905. #define PAGER_SYNCHRONOUS_OFF 0x01 /* PRAGMA synchronous=OFF */
  14906. #define PAGER_SYNCHRONOUS_NORMAL 0x02 /* PRAGMA synchronous=NORMAL */
  14907. #define PAGER_SYNCHRONOUS_FULL 0x03 /* PRAGMA synchronous=FULL */
  14908. #define PAGER_SYNCHRONOUS_EXTRA 0x04 /* PRAGMA synchronous=EXTRA */
  14909. #define PAGER_SYNCHRONOUS_MASK 0x07 /* Mask for four values above */
  14910. #define PAGER_FULLFSYNC 0x08 /* PRAGMA fullfsync=ON */
  14911. #define PAGER_CKPT_FULLFSYNC 0x10 /* PRAGMA checkpoint_fullfsync=ON */
  14912. #define PAGER_CACHESPILL 0x20 /* PRAGMA cache_spill=ON */
  14913. #define PAGER_FLAGS_MASK 0x38 /* All above except SYNCHRONOUS */
  14914. /*
  14915. ** The remainder of this file contains the declarations of the functions
  14916. ** that make up the Pager sub-system API. See source code comments for
  14917. ** a detailed description of each routine.
  14918. */
  14919. /* Open and close a Pager connection. */
  14920. SQLITE_PRIVATE int sqlite3PagerOpen(
  14921. sqlite3_vfs*,
  14922. Pager **ppPager,
  14923. const char*,
  14924. int,
  14925. int,
  14926. int,
  14927. void(*)(DbPage*)
  14928. );
  14929. SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager, sqlite3*);
  14930. SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
  14931. /* Functions used to configure a Pager object. */
  14932. SQLITE_PRIVATE void sqlite3PagerSetBusyHandler(Pager*, int(*)(void *), void *);
  14933. SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
  14934. #ifdef SQLITE_HAS_CODEC
  14935. SQLITE_PRIVATE void sqlite3PagerAlignReserve(Pager*,Pager*);
  14936. #endif
  14937. SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
  14938. SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
  14939. SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager*, int);
  14940. SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64);
  14941. SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);
  14942. SQLITE_PRIVATE void sqlite3PagerSetFlags(Pager*,unsigned);
  14943. SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
  14944. SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
  14945. SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
  14946. SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
  14947. SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
  14948. SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
  14949. SQLITE_PRIVATE int sqlite3PagerFlush(Pager*);
  14950. /* Functions used to obtain and release page references. */
  14951. SQLITE_PRIVATE int sqlite3PagerGet(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
  14952. SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
  14953. SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
  14954. SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
  14955. SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage*);
  14956. SQLITE_PRIVATE void sqlite3PagerUnrefPageOne(DbPage*);
  14957. /* Operations on page references. */
  14958. SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
  14959. SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
  14960. SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
  14961. SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
  14962. SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
  14963. SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
  14964. /* Functions used to manage pager transactions and savepoints. */
  14965. SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
  14966. SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
  14967. SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
  14968. SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
  14969. SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster);
  14970. SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
  14971. SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
  14972. SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
  14973. SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
  14974. SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
  14975. #ifndef SQLITE_OMIT_WAL
  14976. SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, sqlite3*, int, int*, int*);
  14977. SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager);
  14978. SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager);
  14979. SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
  14980. SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager, sqlite3*);
  14981. # ifdef SQLITE_ENABLE_SNAPSHOT
  14982. SQLITE_PRIVATE int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppSnapshot);
  14983. SQLITE_PRIVATE int sqlite3PagerSnapshotOpen(Pager *pPager, sqlite3_snapshot *pSnapshot);
  14984. SQLITE_PRIVATE int sqlite3PagerSnapshotRecover(Pager *pPager);
  14985. SQLITE_PRIVATE int sqlite3PagerSnapshotCheck(Pager *pPager, sqlite3_snapshot *pSnapshot);
  14986. SQLITE_PRIVATE void sqlite3PagerSnapshotUnlock(Pager *pPager);
  14987. # endif
  14988. #endif
  14989. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  14990. SQLITE_PRIVATE int sqlite3PagerDirectReadOk(Pager *pPager, Pgno pgno);
  14991. #endif
  14992. #ifdef SQLITE_ENABLE_ZIPVFS
  14993. SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager);
  14994. #endif
  14995. /* Functions used to query pager state and configuration. */
  14996. SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
  14997. SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager*);
  14998. #ifdef SQLITE_DEBUG
  14999. SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
  15000. #endif
  15001. SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
  15002. SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int);
  15003. SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager*);
  15004. SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
  15005. SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager*);
  15006. SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
  15007. SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
  15008. SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
  15009. SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
  15010. SQLITE_PRIVATE void sqlite3PagerClearCache(Pager*);
  15011. SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *);
  15012. #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
  15013. SQLITE_PRIVATE void sqlite3PagerResetLockTimeout(Pager *pPager);
  15014. #else
  15015. # define sqlite3PagerResetLockTimeout(X)
  15016. #endif
  15017. /* Functions used to truncate the database file. */
  15018. SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
  15019. SQLITE_PRIVATE void sqlite3PagerRekey(DbPage*, Pgno, u16);
  15020. #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
  15021. SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
  15022. #endif
  15023. /* Functions to support testing and debugging. */
  15024. #if !defined(NDEBUG) || defined(SQLITE_TEST)
  15025. SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage*);
  15026. SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage*);
  15027. #endif
  15028. #ifdef SQLITE_TEST
  15029. SQLITE_PRIVATE int *sqlite3PagerStats(Pager*);
  15030. SQLITE_PRIVATE void sqlite3PagerRefdump(Pager*);
  15031. void disable_simulated_io_errors(void);
  15032. void enable_simulated_io_errors(void);
  15033. #else
  15034. # define disable_simulated_io_errors()
  15035. # define enable_simulated_io_errors()
  15036. #endif
  15037. #endif /* SQLITE_PAGER_H */
  15038. /************** End of pager.h ***********************************************/
  15039. /************** Continuing where we left off in sqliteInt.h ******************/
  15040. /************** Include pcache.h in the middle of sqliteInt.h ****************/
  15041. /************** Begin file pcache.h ******************************************/
  15042. /*
  15043. ** 2008 August 05
  15044. **
  15045. ** The author disclaims copyright to this source code. In place of
  15046. ** a legal notice, here is a blessing:
  15047. **
  15048. ** May you do good and not evil.
  15049. ** May you find forgiveness for yourself and forgive others.
  15050. ** May you share freely, never taking more than you give.
  15051. **
  15052. *************************************************************************
  15053. ** This header file defines the interface that the sqlite page cache
  15054. ** subsystem.
  15055. */
  15056. #ifndef _PCACHE_H_
  15057. typedef struct PgHdr PgHdr;
  15058. typedef struct PCache PCache;
  15059. /*
  15060. ** Every page in the cache is controlled by an instance of the following
  15061. ** structure.
  15062. */
  15063. struct PgHdr {
  15064. sqlite3_pcache_page *pPage; /* Pcache object page handle */
  15065. void *pData; /* Page data */
  15066. void *pExtra; /* Extra content */
  15067. PCache *pCache; /* PRIVATE: Cache that owns this page */
  15068. PgHdr *pDirty; /* Transient list of dirty sorted by pgno */
  15069. Pager *pPager; /* The pager this page is part of */
  15070. Pgno pgno; /* Page number for this page */
  15071. #ifdef SQLITE_CHECK_PAGES
  15072. u32 pageHash; /* Hash of page content */
  15073. #endif
  15074. u16 flags; /* PGHDR flags defined below */
  15075. /**********************************************************************
  15076. ** Elements above, except pCache, are public. All that follow are
  15077. ** private to pcache.c and should not be accessed by other modules.
  15078. ** pCache is grouped with the public elements for efficiency.
  15079. */
  15080. i16 nRef; /* Number of users of this page */
  15081. PgHdr *pDirtyNext; /* Next element in list of dirty pages */
  15082. PgHdr *pDirtyPrev; /* Previous element in list of dirty pages */
  15083. /* NB: pDirtyNext and pDirtyPrev are undefined if the
  15084. ** PgHdr object is not dirty */
  15085. };
  15086. /* Bit values for PgHdr.flags */
  15087. #define PGHDR_CLEAN 0x001 /* Page not on the PCache.pDirty list */
  15088. #define PGHDR_DIRTY 0x002 /* Page is on the PCache.pDirty list */
  15089. #define PGHDR_WRITEABLE 0x004 /* Journaled and ready to modify */
  15090. #define PGHDR_NEED_SYNC 0x008 /* Fsync the rollback journal before
  15091. ** writing this page to the database */
  15092. #define PGHDR_DONT_WRITE 0x010 /* Do not write content to disk */
  15093. #define PGHDR_MMAP 0x020 /* This is an mmap page object */
  15094. #define PGHDR_WAL_APPEND 0x040 /* Appended to wal file */
  15095. /* Initialize and shutdown the page cache subsystem */
  15096. SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
  15097. SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
  15098. /* Page cache buffer management:
  15099. ** These routines implement SQLITE_CONFIG_PAGECACHE.
  15100. */
  15101. SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
  15102. /* Create a new pager cache.
  15103. ** Under memory stress, invoke xStress to try to make pages clean.
  15104. ** Only clean and unpinned pages can be reclaimed.
  15105. */
  15106. SQLITE_PRIVATE int sqlite3PcacheOpen(
  15107. int szPage, /* Size of every page */
  15108. int szExtra, /* Extra space associated with each page */
  15109. int bPurgeable, /* True if pages are on backing store */
  15110. int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
  15111. void *pStress, /* Argument to xStress */
  15112. PCache *pToInit /* Preallocated space for the PCache */
  15113. );
  15114. /* Modify the page-size after the cache has been created. */
  15115. SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *, int);
  15116. /* Return the size in bytes of a PCache object. Used to preallocate
  15117. ** storage space.
  15118. */
  15119. SQLITE_PRIVATE int sqlite3PcacheSize(void);
  15120. /* One release per successful fetch. Page is pinned until released.
  15121. ** Reference counted.
  15122. */
  15123. SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(PCache*, Pgno, int createFlag);
  15124. SQLITE_PRIVATE int sqlite3PcacheFetchStress(PCache*, Pgno, sqlite3_pcache_page**);
  15125. SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(PCache*, Pgno, sqlite3_pcache_page *pPage);
  15126. SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
  15127. SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*); /* Remove page from cache */
  15128. SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*); /* Make sure page is marked dirty */
  15129. SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*); /* Mark a single page as clean */
  15130. SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*); /* Mark all dirty list pages as clean */
  15131. SQLITE_PRIVATE void sqlite3PcacheClearWritable(PCache*);
  15132. /* Change a page number. Used by incr-vacuum. */
  15133. SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
  15134. /* Remove all pages with pgno>x. Reset the cache if x==0 */
  15135. SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
  15136. /* Get a list of all dirty pages in the cache, sorted by page number */
  15137. SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
  15138. /* Reset and close the cache object */
  15139. SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
  15140. /* Clear flags from pages of the page cache */
  15141. SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
  15142. /* Discard the contents of the cache */
  15143. SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
  15144. /* Return the total number of outstanding page references */
  15145. SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
  15146. /* Increment the reference count of an existing page */
  15147. SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
  15148. SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
  15149. /* Return the total number of pages stored in the cache */
  15150. SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
  15151. #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
  15152. /* Iterate through all dirty pages currently stored in the cache. This
  15153. ** interface is only available if SQLITE_CHECK_PAGES is defined when the
  15154. ** library is built.
  15155. */
  15156. SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
  15157. #endif
  15158. #if defined(SQLITE_DEBUG)
  15159. /* Check invariants on a PgHdr object */
  15160. SQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr*);
  15161. #endif
  15162. /* Set and get the suggested cache-size for the specified pager-cache.
  15163. **
  15164. ** If no global maximum is configured, then the system attempts to limit
  15165. ** the total number of pages cached by purgeable pager-caches to the sum
  15166. ** of the suggested cache-sizes.
  15167. */
  15168. SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
  15169. #ifdef SQLITE_TEST
  15170. SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
  15171. #endif
  15172. /* Set or get the suggested spill-size for the specified pager-cache.
  15173. **
  15174. ** The spill-size is the minimum number of pages in cache before the cache
  15175. ** will attempt to spill dirty pages by calling xStress.
  15176. */
  15177. SQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *, int);
  15178. /* Free up as much memory as possible from the page cache */
  15179. SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);
  15180. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  15181. /* Try to return memory used by the pcache module to the main memory heap */
  15182. SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
  15183. #endif
  15184. #ifdef SQLITE_TEST
  15185. SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
  15186. #endif
  15187. SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
  15188. /* Return the header size */
  15189. SQLITE_PRIVATE int sqlite3HeaderSizePcache(void);
  15190. SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void);
  15191. /* Number of dirty pages as a percentage of the configured cache size */
  15192. SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache*);
  15193. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  15194. SQLITE_PRIVATE int sqlite3PCacheIsDirty(PCache *pCache);
  15195. #endif
  15196. #endif /* _PCACHE_H_ */
  15197. /************** End of pcache.h **********************************************/
  15198. /************** Continuing where we left off in sqliteInt.h ******************/
  15199. /************** Include os.h in the middle of sqliteInt.h ********************/
  15200. /************** Begin file os.h **********************************************/
  15201. /*
  15202. ** 2001 September 16
  15203. **
  15204. ** The author disclaims copyright to this source code. In place of
  15205. ** a legal notice, here is a blessing:
  15206. **
  15207. ** May you do good and not evil.
  15208. ** May you find forgiveness for yourself and forgive others.
  15209. ** May you share freely, never taking more than you give.
  15210. **
  15211. ******************************************************************************
  15212. **
  15213. ** This header file (together with is companion C source-code file
  15214. ** "os.c") attempt to abstract the underlying operating system so that
  15215. ** the SQLite library will work on both POSIX and windows systems.
  15216. **
  15217. ** This header file is #include-ed by sqliteInt.h and thus ends up
  15218. ** being included by every source file.
  15219. */
  15220. #ifndef _SQLITE_OS_H_
  15221. #define _SQLITE_OS_H_
  15222. /*
  15223. ** Attempt to automatically detect the operating system and setup the
  15224. ** necessary pre-processor macros for it.
  15225. */
  15226. /************** Include os_setup.h in the middle of os.h *********************/
  15227. /************** Begin file os_setup.h ****************************************/
  15228. /*
  15229. ** 2013 November 25
  15230. **
  15231. ** The author disclaims copyright to this source code. In place of
  15232. ** a legal notice, here is a blessing:
  15233. **
  15234. ** May you do good and not evil.
  15235. ** May you find forgiveness for yourself and forgive others.
  15236. ** May you share freely, never taking more than you give.
  15237. **
  15238. ******************************************************************************
  15239. **
  15240. ** This file contains pre-processor directives related to operating system
  15241. ** detection and/or setup.
  15242. */
  15243. #ifndef SQLITE_OS_SETUP_H
  15244. #define SQLITE_OS_SETUP_H
  15245. /*
  15246. ** Figure out if we are dealing with Unix, Windows, or some other operating
  15247. ** system.
  15248. **
  15249. ** After the following block of preprocess macros, all of SQLITE_OS_UNIX,
  15250. ** SQLITE_OS_WIN, and SQLITE_OS_OTHER will defined to either 1 or 0. One of
  15251. ** the three will be 1. The other two will be 0.
  15252. */
  15253. #if defined(SQLITE_OS_OTHER)
  15254. # if SQLITE_OS_OTHER==1
  15255. # undef SQLITE_OS_UNIX
  15256. # define SQLITE_OS_UNIX 0
  15257. # undef SQLITE_OS_WIN
  15258. # define SQLITE_OS_WIN 0
  15259. # else
  15260. # undef SQLITE_OS_OTHER
  15261. # endif
  15262. #endif
  15263. #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
  15264. # define SQLITE_OS_OTHER 0
  15265. # ifndef SQLITE_OS_WIN
  15266. # if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || \
  15267. defined(__MINGW32__) || defined(__BORLANDC__)
  15268. # define SQLITE_OS_WIN 1
  15269. # define SQLITE_OS_UNIX 0
  15270. # else
  15271. # define SQLITE_OS_WIN 0
  15272. # define SQLITE_OS_UNIX 1
  15273. # endif
  15274. # else
  15275. # define SQLITE_OS_UNIX 0
  15276. # endif
  15277. #else
  15278. # ifndef SQLITE_OS_WIN
  15279. # define SQLITE_OS_WIN 0
  15280. # endif
  15281. #endif
  15282. #endif /* SQLITE_OS_SETUP_H */
  15283. /************** End of os_setup.h ********************************************/
  15284. /************** Continuing where we left off in os.h *************************/
  15285. /* If the SET_FULLSYNC macro is not defined above, then make it
  15286. ** a no-op
  15287. */
  15288. #ifndef SET_FULLSYNC
  15289. # define SET_FULLSYNC(x,y)
  15290. #endif
  15291. /*
  15292. ** The default size of a disk sector
  15293. */
  15294. #ifndef SQLITE_DEFAULT_SECTOR_SIZE
  15295. # define SQLITE_DEFAULT_SECTOR_SIZE 4096
  15296. #endif
  15297. /*
  15298. ** Temporary files are named starting with this prefix followed by 16 random
  15299. ** alphanumeric characters, and no file extension. They are stored in the
  15300. ** OS's standard temporary file directory, and are deleted prior to exit.
  15301. ** If sqlite is being embedded in another program, you may wish to change the
  15302. ** prefix to reflect your program's name, so that if your program exits
  15303. ** prematurely, old temporary files can be easily identified. This can be done
  15304. ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
  15305. **
  15306. ** 2006-10-31: The default prefix used to be "sqlite_". But then
  15307. ** Mcafee started using SQLite in their anti-virus product and it
  15308. ** started putting files with the "sqlite" name in the c:/temp folder.
  15309. ** This annoyed many windows users. Those users would then do a
  15310. ** Google search for "sqlite", find the telephone numbers of the
  15311. ** developers and call to wake them up at night and complain.
  15312. ** For this reason, the default name prefix is changed to be "sqlite"
  15313. ** spelled backwards. So the temp files are still identified, but
  15314. ** anybody smart enough to figure out the code is also likely smart
  15315. ** enough to know that calling the developer will not help get rid
  15316. ** of the file.
  15317. */
  15318. #ifndef SQLITE_TEMP_FILE_PREFIX
  15319. # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
  15320. #endif
  15321. /*
  15322. ** The following values may be passed as the second argument to
  15323. ** sqlite3OsLock(). The various locks exhibit the following semantics:
  15324. **
  15325. ** SHARED: Any number of processes may hold a SHARED lock simultaneously.
  15326. ** RESERVED: A single process may hold a RESERVED lock on a file at
  15327. ** any time. Other processes may hold and obtain new SHARED locks.
  15328. ** PENDING: A single process may hold a PENDING lock on a file at
  15329. ** any one time. Existing SHARED locks may persist, but no new
  15330. ** SHARED locks may be obtained by other processes.
  15331. ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
  15332. **
  15333. ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
  15334. ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
  15335. ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
  15336. ** sqlite3OsLock().
  15337. */
  15338. #define NO_LOCK 0
  15339. #define SHARED_LOCK 1
  15340. #define RESERVED_LOCK 2
  15341. #define PENDING_LOCK 3
  15342. #define EXCLUSIVE_LOCK 4
  15343. /*
  15344. ** File Locking Notes: (Mostly about windows but also some info for Unix)
  15345. **
  15346. ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
  15347. ** those functions are not available. So we use only LockFile() and
  15348. ** UnlockFile().
  15349. **
  15350. ** LockFile() prevents not just writing but also reading by other processes.
  15351. ** A SHARED_LOCK is obtained by locking a single randomly-chosen
  15352. ** byte out of a specific range of bytes. The lock byte is obtained at
  15353. ** random so two separate readers can probably access the file at the
  15354. ** same time, unless they are unlucky and choose the same lock byte.
  15355. ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
  15356. ** There can only be one writer. A RESERVED_LOCK is obtained by locking
  15357. ** a single byte of the file that is designated as the reserved lock byte.
  15358. ** A PENDING_LOCK is obtained by locking a designated byte different from
  15359. ** the RESERVED_LOCK byte.
  15360. **
  15361. ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
  15362. ** which means we can use reader/writer locks. When reader/writer locks
  15363. ** are used, the lock is placed on the same range of bytes that is used
  15364. ** for probabilistic locking in Win95/98/ME. Hence, the locking scheme
  15365. ** will support two or more Win95 readers or two or more WinNT readers.
  15366. ** But a single Win95 reader will lock out all WinNT readers and a single
  15367. ** WinNT reader will lock out all other Win95 readers.
  15368. **
  15369. ** The following #defines specify the range of bytes used for locking.
  15370. ** SHARED_SIZE is the number of bytes available in the pool from which
  15371. ** a random byte is selected for a shared lock. The pool of bytes for
  15372. ** shared locks begins at SHARED_FIRST.
  15373. **
  15374. ** The same locking strategy and
  15375. ** byte ranges are used for Unix. This leaves open the possibility of having
  15376. ** clients on win95, winNT, and unix all talking to the same shared file
  15377. ** and all locking correctly. To do so would require that samba (or whatever
  15378. ** tool is being used for file sharing) implements locks correctly between
  15379. ** windows and unix. I'm guessing that isn't likely to happen, but by
  15380. ** using the same locking range we are at least open to the possibility.
  15381. **
  15382. ** Locking in windows is manditory. For this reason, we cannot store
  15383. ** actual data in the bytes used for locking. The pager never allocates
  15384. ** the pages involved in locking therefore. SHARED_SIZE is selected so
  15385. ** that all locks will fit on a single page even at the minimum page size.
  15386. ** PENDING_BYTE defines the beginning of the locks. By default PENDING_BYTE
  15387. ** is set high so that we don't have to allocate an unused page except
  15388. ** for very large databases. But one should test the page skipping logic
  15389. ** by setting PENDING_BYTE low and running the entire regression suite.
  15390. **
  15391. ** Changing the value of PENDING_BYTE results in a subtly incompatible
  15392. ** file format. Depending on how it is changed, you might not notice
  15393. ** the incompatibility right away, even running a full regression test.
  15394. ** The default location of PENDING_BYTE is the first byte past the
  15395. ** 1GB boundary.
  15396. **
  15397. */
  15398. #ifdef SQLITE_OMIT_WSD
  15399. # define PENDING_BYTE (0x40000000)
  15400. #else
  15401. # define PENDING_BYTE sqlite3PendingByte
  15402. #endif
  15403. #define RESERVED_BYTE (PENDING_BYTE+1)
  15404. #define SHARED_FIRST (PENDING_BYTE+2)
  15405. #define SHARED_SIZE 510
  15406. /*
  15407. ** Wrapper around OS specific sqlite3_os_init() function.
  15408. */
  15409. SQLITE_PRIVATE int sqlite3OsInit(void);
  15410. /*
  15411. ** Functions for accessing sqlite3_file methods
  15412. */
  15413. SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file*);
  15414. SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
  15415. SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
  15416. SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
  15417. SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
  15418. SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
  15419. SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
  15420. SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
  15421. SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
  15422. SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
  15423. SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
  15424. #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
  15425. SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
  15426. SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
  15427. #ifndef SQLITE_OMIT_WAL
  15428. SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
  15429. SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
  15430. SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
  15431. SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
  15432. #endif /* SQLITE_OMIT_WAL */
  15433. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **);
  15434. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *);
  15435. /*
  15436. ** Functions for accessing sqlite3_vfs methods
  15437. */
  15438. SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
  15439. SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
  15440. SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
  15441. SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
  15442. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  15443. SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
  15444. SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
  15445. SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
  15446. SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
  15447. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  15448. SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
  15449. SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
  15450. SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs*);
  15451. SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
  15452. /*
  15453. ** Convenience functions for opening and closing files using
  15454. ** sqlite3_malloc() to obtain space for the file-handle structure.
  15455. */
  15456. SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
  15457. SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *);
  15458. #endif /* _SQLITE_OS_H_ */
  15459. /************** End of os.h **************************************************/
  15460. /************** Continuing where we left off in sqliteInt.h ******************/
  15461. /************** Include mutex.h in the middle of sqliteInt.h *****************/
  15462. /************** Begin file mutex.h *******************************************/
  15463. /*
  15464. ** 2007 August 28
  15465. **
  15466. ** The author disclaims copyright to this source code. In place of
  15467. ** a legal notice, here is a blessing:
  15468. **
  15469. ** May you do good and not evil.
  15470. ** May you find forgiveness for yourself and forgive others.
  15471. ** May you share freely, never taking more than you give.
  15472. **
  15473. *************************************************************************
  15474. **
  15475. ** This file contains the common header for all mutex implementations.
  15476. ** The sqliteInt.h header #includes this file so that it is available
  15477. ** to all source files. We break it out in an effort to keep the code
  15478. ** better organized.
  15479. **
  15480. ** NOTE: source files should *not* #include this header file directly.
  15481. ** Source files should #include the sqliteInt.h file and let that file
  15482. ** include this one indirectly.
  15483. */
  15484. /*
  15485. ** Figure out what version of the code to use. The choices are
  15486. **
  15487. ** SQLITE_MUTEX_OMIT No mutex logic. Not even stubs. The
  15488. ** mutexes implementation cannot be overridden
  15489. ** at start-time.
  15490. **
  15491. ** SQLITE_MUTEX_NOOP For single-threaded applications. No
  15492. ** mutual exclusion is provided. But this
  15493. ** implementation can be overridden at
  15494. ** start-time.
  15495. **
  15496. ** SQLITE_MUTEX_PTHREADS For multi-threaded applications on Unix.
  15497. **
  15498. ** SQLITE_MUTEX_W32 For multi-threaded applications on Win32.
  15499. */
  15500. #if !SQLITE_THREADSAFE
  15501. # define SQLITE_MUTEX_OMIT
  15502. #endif
  15503. #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
  15504. # if SQLITE_OS_UNIX
  15505. # define SQLITE_MUTEX_PTHREADS
  15506. # elif SQLITE_OS_WIN
  15507. # define SQLITE_MUTEX_W32
  15508. # else
  15509. # define SQLITE_MUTEX_NOOP
  15510. # endif
  15511. #endif
  15512. #ifdef SQLITE_MUTEX_OMIT
  15513. /*
  15514. ** If this is a no-op implementation, implement everything as macros.
  15515. */
  15516. #define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8)
  15517. #define sqlite3_mutex_free(X)
  15518. #define sqlite3_mutex_enter(X)
  15519. #define sqlite3_mutex_try(X) SQLITE_OK
  15520. #define sqlite3_mutex_leave(X)
  15521. #define sqlite3_mutex_held(X) ((void)(X),1)
  15522. #define sqlite3_mutex_notheld(X) ((void)(X),1)
  15523. #define sqlite3MutexAlloc(X) ((sqlite3_mutex*)8)
  15524. #define sqlite3MutexInit() SQLITE_OK
  15525. #define sqlite3MutexEnd()
  15526. #define MUTEX_LOGIC(X)
  15527. #else
  15528. #define MUTEX_LOGIC(X) X
  15529. #endif /* defined(SQLITE_MUTEX_OMIT) */
  15530. /************** End of mutex.h ***********************************************/
  15531. /************** Continuing where we left off in sqliteInt.h ******************/
  15532. /* The SQLITE_EXTRA_DURABLE compile-time option used to set the default
  15533. ** synchronous setting to EXTRA. It is no longer supported.
  15534. */
  15535. #ifdef SQLITE_EXTRA_DURABLE
  15536. # warning Use SQLITE_DEFAULT_SYNCHRONOUS=3 instead of SQLITE_EXTRA_DURABLE
  15537. # define SQLITE_DEFAULT_SYNCHRONOUS 3
  15538. #endif
  15539. /*
  15540. ** Default synchronous levels.
  15541. **
  15542. ** Note that (for historcal reasons) the PAGER_SYNCHRONOUS_* macros differ
  15543. ** from the SQLITE_DEFAULT_SYNCHRONOUS value by 1.
  15544. **
  15545. ** PAGER_SYNCHRONOUS DEFAULT_SYNCHRONOUS
  15546. ** OFF 1 0
  15547. ** NORMAL 2 1
  15548. ** FULL 3 2
  15549. ** EXTRA 4 3
  15550. **
  15551. ** The "PRAGMA synchronous" statement also uses the zero-based numbers.
  15552. ** In other words, the zero-based numbers are used for all external interfaces
  15553. ** and the one-based values are used internally.
  15554. */
  15555. #ifndef SQLITE_DEFAULT_SYNCHRONOUS
  15556. # define SQLITE_DEFAULT_SYNCHRONOUS 2
  15557. #endif
  15558. #ifndef SQLITE_DEFAULT_WAL_SYNCHRONOUS
  15559. # define SQLITE_DEFAULT_WAL_SYNCHRONOUS SQLITE_DEFAULT_SYNCHRONOUS
  15560. #endif
  15561. /*
  15562. ** Each database file to be accessed by the system is an instance
  15563. ** of the following structure. There are normally two of these structures
  15564. ** in the sqlite.aDb[] array. aDb[0] is the main database file and
  15565. ** aDb[1] is the database file used to hold temporary tables. Additional
  15566. ** databases may be attached.
  15567. */
  15568. struct Db {
  15569. char *zDbSName; /* Name of this database. (schema name, not filename) */
  15570. Btree *pBt; /* The B*Tree structure for this database file */
  15571. u8 safety_level; /* How aggressive at syncing data to disk */
  15572. u8 bSyncSet; /* True if "PRAGMA synchronous=N" has been run */
  15573. Schema *pSchema; /* Pointer to database schema (possibly shared) */
  15574. };
  15575. /*
  15576. ** An instance of the following structure stores a database schema.
  15577. **
  15578. ** Most Schema objects are associated with a Btree. The exception is
  15579. ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
  15580. ** In shared cache mode, a single Schema object can be shared by multiple
  15581. ** Btrees that refer to the same underlying BtShared object.
  15582. **
  15583. ** Schema objects are automatically deallocated when the last Btree that
  15584. ** references them is destroyed. The TEMP Schema is manually freed by
  15585. ** sqlite3_close().
  15586. *
  15587. ** A thread must be holding a mutex on the corresponding Btree in order
  15588. ** to access Schema content. This implies that the thread must also be
  15589. ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
  15590. ** For a TEMP Schema, only the connection mutex is required.
  15591. */
  15592. struct Schema {
  15593. int schema_cookie; /* Database schema version number for this file */
  15594. int iGeneration; /* Generation counter. Incremented with each change */
  15595. Hash tblHash; /* All tables indexed by name */
  15596. Hash idxHash; /* All (named) indices indexed by name */
  15597. Hash trigHash; /* All triggers indexed by name */
  15598. Hash fkeyHash; /* All foreign keys by referenced table name */
  15599. Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */
  15600. u8 file_format; /* Schema format version for this file */
  15601. u8 enc; /* Text encoding used by this database */
  15602. u16 schemaFlags; /* Flags associated with this schema */
  15603. int cache_size; /* Number of pages to use in the cache */
  15604. };
  15605. /*
  15606. ** These macros can be used to test, set, or clear bits in the
  15607. ** Db.pSchema->flags field.
  15608. */
  15609. #define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))==(P))
  15610. #define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))!=0)
  15611. #define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags|=(P)
  15612. #define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags&=~(P)
  15613. /*
  15614. ** Allowed values for the DB.pSchema->flags field.
  15615. **
  15616. ** The DB_SchemaLoaded flag is set after the database schema has been
  15617. ** read into internal hash tables.
  15618. **
  15619. ** DB_UnresetViews means that one or more views have column names that
  15620. ** have been filled out. If the schema changes, these column names might
  15621. ** changes and so the view will need to be reset.
  15622. */
  15623. #define DB_SchemaLoaded 0x0001 /* The schema has been loaded */
  15624. #define DB_UnresetViews 0x0002 /* Some views have defined column names */
  15625. #define DB_Empty 0x0004 /* The file is empty (length 0 bytes) */
  15626. #define DB_ResetWanted 0x0008 /* Reset the schema when nSchemaLock==0 */
  15627. /*
  15628. ** The number of different kinds of things that can be limited
  15629. ** using the sqlite3_limit() interface.
  15630. */
  15631. #define SQLITE_N_LIMIT (SQLITE_LIMIT_WORKER_THREADS+1)
  15632. /*
  15633. ** Lookaside malloc is a set of fixed-size buffers that can be used
  15634. ** to satisfy small transient memory allocation requests for objects
  15635. ** associated with a particular database connection. The use of
  15636. ** lookaside malloc provides a significant performance enhancement
  15637. ** (approx 10%) by avoiding numerous malloc/free requests while parsing
  15638. ** SQL statements.
  15639. **
  15640. ** The Lookaside structure holds configuration information about the
  15641. ** lookaside malloc subsystem. Each available memory allocation in
  15642. ** the lookaside subsystem is stored on a linked list of LookasideSlot
  15643. ** objects.
  15644. **
  15645. ** Lookaside allocations are only allowed for objects that are associated
  15646. ** with a particular database connection. Hence, schema information cannot
  15647. ** be stored in lookaside because in shared cache mode the schema information
  15648. ** is shared by multiple database connections. Therefore, while parsing
  15649. ** schema information, the Lookaside.bEnabled flag is cleared so that
  15650. ** lookaside allocations are not used to construct the schema objects.
  15651. */
  15652. struct Lookaside {
  15653. u32 bDisable; /* Only operate the lookaside when zero */
  15654. u16 sz; /* Size of each buffer in bytes */
  15655. u8 bMalloced; /* True if pStart obtained from sqlite3_malloc() */
  15656. u32 nSlot; /* Number of lookaside slots allocated */
  15657. u32 anStat[3]; /* 0: hits. 1: size misses. 2: full misses */
  15658. LookasideSlot *pInit; /* List of buffers not previously used */
  15659. LookasideSlot *pFree; /* List of available buffers */
  15660. void *pStart; /* First byte of available memory space */
  15661. void *pEnd; /* First byte past end of available space */
  15662. };
  15663. struct LookasideSlot {
  15664. LookasideSlot *pNext; /* Next buffer in the list of free buffers */
  15665. };
  15666. /*
  15667. ** A hash table for built-in function definitions. (Application-defined
  15668. ** functions use a regular table table from hash.h.)
  15669. **
  15670. ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
  15671. ** Collisions are on the FuncDef.u.pHash chain. Use the SQLITE_FUNC_HASH()
  15672. ** macro to compute a hash on the function name.
  15673. */
  15674. #define SQLITE_FUNC_HASH_SZ 23
  15675. struct FuncDefHash {
  15676. FuncDef *a[SQLITE_FUNC_HASH_SZ]; /* Hash table for functions */
  15677. };
  15678. #define SQLITE_FUNC_HASH(C,L) (((C)+(L))%SQLITE_FUNC_HASH_SZ)
  15679. #ifdef SQLITE_USER_AUTHENTICATION
  15680. /*
  15681. ** Information held in the "sqlite3" database connection object and used
  15682. ** to manage user authentication.
  15683. */
  15684. typedef struct sqlite3_userauth sqlite3_userauth;
  15685. struct sqlite3_userauth {
  15686. u8 authLevel; /* Current authentication level */
  15687. int nAuthPW; /* Size of the zAuthPW in bytes */
  15688. char *zAuthPW; /* Password used to authenticate */
  15689. char *zAuthUser; /* User name used to authenticate */
  15690. };
  15691. /* Allowed values for sqlite3_userauth.authLevel */
  15692. #define UAUTH_Unknown 0 /* Authentication not yet checked */
  15693. #define UAUTH_Fail 1 /* User authentication failed */
  15694. #define UAUTH_User 2 /* Authenticated as a normal user */
  15695. #define UAUTH_Admin 3 /* Authenticated as an administrator */
  15696. /* Functions used only by user authorization logic */
  15697. SQLITE_PRIVATE int sqlite3UserAuthTable(const char*);
  15698. SQLITE_PRIVATE int sqlite3UserAuthCheckLogin(sqlite3*,const char*,u8*);
  15699. SQLITE_PRIVATE void sqlite3UserAuthInit(sqlite3*);
  15700. SQLITE_PRIVATE void sqlite3CryptFunc(sqlite3_context*,int,sqlite3_value**);
  15701. #endif /* SQLITE_USER_AUTHENTICATION */
  15702. /*
  15703. ** typedef for the authorization callback function.
  15704. */
  15705. #ifdef SQLITE_USER_AUTHENTICATION
  15706. typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
  15707. const char*, const char*);
  15708. #else
  15709. typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
  15710. const char*);
  15711. #endif
  15712. #ifndef SQLITE_OMIT_DEPRECATED
  15713. /* This is an extra SQLITE_TRACE macro that indicates "legacy" tracing
  15714. ** in the style of sqlite3_trace()
  15715. */
  15716. #define SQLITE_TRACE_LEGACY 0x40 /* Use the legacy xTrace */
  15717. #define SQLITE_TRACE_XPROFILE 0x80 /* Use the legacy xProfile */
  15718. #else
  15719. #define SQLITE_TRACE_LEGACY 0
  15720. #define SQLITE_TRACE_XPROFILE 0
  15721. #endif /* SQLITE_OMIT_DEPRECATED */
  15722. #define SQLITE_TRACE_NONLEGACY_MASK 0x0f /* Normal flags */
  15723. /*
  15724. ** Each database connection is an instance of the following structure.
  15725. */
  15726. struct sqlite3 {
  15727. sqlite3_vfs *pVfs; /* OS Interface */
  15728. struct Vdbe *pVdbe; /* List of active virtual machines */
  15729. CollSeq *pDfltColl; /* The default collating sequence (BINARY) */
  15730. sqlite3_mutex *mutex; /* Connection mutex */
  15731. Db *aDb; /* All backends */
  15732. int nDb; /* Number of backends currently in use */
  15733. u32 mDbFlags; /* flags recording internal state */
  15734. u64 flags; /* flags settable by pragmas. See below */
  15735. i64 lastRowid; /* ROWID of most recent insert (see above) */
  15736. i64 szMmap; /* Default mmap_size setting */
  15737. u32 nSchemaLock; /* Do not reset the schema when non-zero */
  15738. unsigned int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */
  15739. int errCode; /* Most recent error code (SQLITE_*) */
  15740. int errMask; /* & result codes with this before returning */
  15741. int iSysErrno; /* Errno value from last system error */
  15742. u16 dbOptFlags; /* Flags to enable/disable optimizations */
  15743. u8 enc; /* Text encoding */
  15744. u8 autoCommit; /* The auto-commit flag. */
  15745. u8 temp_store; /* 1: file 2: memory 0: default */
  15746. u8 mallocFailed; /* True if we have seen a malloc failure */
  15747. u8 bBenignMalloc; /* Do not require OOMs if true */
  15748. u8 dfltLockMode; /* Default locking-mode for attached dbs */
  15749. signed char nextAutovac; /* Autovac setting after VACUUM if >=0 */
  15750. u8 suppressErr; /* Do not issue error messages if true */
  15751. u8 vtabOnConflict; /* Value to return for s3_vtab_on_conflict() */
  15752. u8 isTransactionSavepoint; /* True if the outermost savepoint is a TS */
  15753. u8 mTrace; /* zero or more SQLITE_TRACE flags */
  15754. u8 noSharedCache; /* True if no shared-cache backends */
  15755. u8 nSqlExec; /* Number of pending OP_SqlExec opcodes */
  15756. int nextPagesize; /* Pagesize after VACUUM if >0 */
  15757. u32 magic; /* Magic number for detect library misuse */
  15758. int nChange; /* Value returned by sqlite3_changes() */
  15759. int nTotalChange; /* Value returned by sqlite3_total_changes() */
  15760. int aLimit[SQLITE_N_LIMIT]; /* Limits */
  15761. int nMaxSorterMmap; /* Maximum size of regions mapped by sorter */
  15762. struct sqlite3InitInfo { /* Information used during initialization */
  15763. int newTnum; /* Rootpage of table being initialized */
  15764. u8 iDb; /* Which db file is being initialized */
  15765. u8 busy; /* TRUE if currently initializing */
  15766. unsigned orphanTrigger : 1; /* Last statement is orphaned TEMP trigger */
  15767. unsigned imposterTable : 1; /* Building an imposter table */
  15768. unsigned reopenMemdb : 1; /* ATTACH is really a reopen using MemDB */
  15769. } init;
  15770. int nVdbeActive; /* Number of VDBEs currently running */
  15771. int nVdbeRead; /* Number of active VDBEs that read or write */
  15772. int nVdbeWrite; /* Number of active VDBEs that read and write */
  15773. int nVdbeExec; /* Number of nested calls to VdbeExec() */
  15774. int nVDestroy; /* Number of active OP_VDestroy operations */
  15775. int nExtension; /* Number of loaded extensions */
  15776. void **aExtension; /* Array of shared library handles */
  15777. int (*xTrace)(u32,void*,void*,void*); /* Trace function */
  15778. void *pTraceArg; /* Argument to the trace function */
  15779. #ifndef SQLITE_OMIT_DEPRECATED
  15780. void (*xProfile)(void*,const char*,u64); /* Profiling function */
  15781. void *pProfileArg; /* Argument to profile function */
  15782. #endif
  15783. void *pCommitArg; /* Argument to xCommitCallback() */
  15784. int (*xCommitCallback)(void*); /* Invoked at every commit. */
  15785. void *pRollbackArg; /* Argument to xRollbackCallback() */
  15786. void (*xRollbackCallback)(void*); /* Invoked at every commit. */
  15787. void *pUpdateArg;
  15788. void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
  15789. Parse *pParse; /* Current parse */
  15790. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  15791. void *pPreUpdateArg; /* First argument to xPreUpdateCallback */
  15792. void (*xPreUpdateCallback)( /* Registered using sqlite3_preupdate_hook() */
  15793. void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64
  15794. );
  15795. PreUpdate *pPreUpdate; /* Context for active pre-update callback */
  15796. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  15797. #ifndef SQLITE_OMIT_WAL
  15798. int (*xWalCallback)(void *, sqlite3 *, const char *, int);
  15799. void *pWalArg;
  15800. #endif
  15801. void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
  15802. void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
  15803. void *pCollNeededArg;
  15804. sqlite3_value *pErr; /* Most recent error message */
  15805. union {
  15806. volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
  15807. double notUsed1; /* Spacer */
  15808. } u1;
  15809. Lookaside lookaside; /* Lookaside malloc configuration */
  15810. #ifndef SQLITE_OMIT_AUTHORIZATION
  15811. sqlite3_xauth xAuth; /* Access authorization function */
  15812. void *pAuthArg; /* 1st argument to the access auth function */
  15813. #endif
  15814. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  15815. int (*xProgress)(void *); /* The progress callback */
  15816. void *pProgressArg; /* Argument to the progress callback */
  15817. unsigned nProgressOps; /* Number of opcodes for progress callback */
  15818. #endif
  15819. #ifndef SQLITE_OMIT_VIRTUALTABLE
  15820. int nVTrans; /* Allocated size of aVTrans */
  15821. Hash aModule; /* populated by sqlite3_create_module() */
  15822. VtabCtx *pVtabCtx; /* Context for active vtab connect/create */
  15823. VTable **aVTrans; /* Virtual tables with open transactions */
  15824. VTable *pDisconnect; /* Disconnect these in next sqlite3_prepare() */
  15825. #endif
  15826. Hash aFunc; /* Hash table of connection functions */
  15827. Hash aCollSeq; /* All collating sequences */
  15828. BusyHandler busyHandler; /* Busy callback */
  15829. Db aDbStatic[2]; /* Static space for the 2 default backends */
  15830. Savepoint *pSavepoint; /* List of active savepoints */
  15831. int busyTimeout; /* Busy handler timeout, in msec */
  15832. int nSavepoint; /* Number of non-transaction savepoints */
  15833. int nStatement; /* Number of nested statement-transactions */
  15834. i64 nDeferredCons; /* Net deferred constraints this transaction. */
  15835. i64 nDeferredImmCons; /* Net deferred immediate constraints */
  15836. int *pnBytesFreed; /* If not NULL, increment this in DbFree() */
  15837. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  15838. /* The following variables are all protected by the STATIC_MASTER
  15839. ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
  15840. **
  15841. ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
  15842. ** unlock so that it can proceed.
  15843. **
  15844. ** When X.pBlockingConnection==Y, that means that something that X tried
  15845. ** tried to do recently failed with an SQLITE_LOCKED error due to locks
  15846. ** held by Y.
  15847. */
  15848. sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
  15849. sqlite3 *pUnlockConnection; /* Connection to watch for unlock */
  15850. void *pUnlockArg; /* Argument to xUnlockNotify */
  15851. void (*xUnlockNotify)(void **, int); /* Unlock notify callback */
  15852. sqlite3 *pNextBlocked; /* Next in list of all blocked connections */
  15853. #endif
  15854. #ifdef SQLITE_USER_AUTHENTICATION
  15855. sqlite3_userauth auth; /* User authentication information */
  15856. #endif
  15857. };
  15858. /*
  15859. ** A macro to discover the encoding of a database.
  15860. */
  15861. #define SCHEMA_ENC(db) ((db)->aDb[0].pSchema->enc)
  15862. #define ENC(db) ((db)->enc)
  15863. /*
  15864. ** Possible values for the sqlite3.flags.
  15865. **
  15866. ** Value constraints (enforced via assert()):
  15867. ** SQLITE_FullFSync == PAGER_FULLFSYNC
  15868. ** SQLITE_CkptFullFSync == PAGER_CKPT_FULLFSYNC
  15869. ** SQLITE_CacheSpill == PAGER_CACHE_SPILL
  15870. */
  15871. #define SQLITE_WriteSchema 0x00000001 /* OK to update SQLITE_MASTER */
  15872. #define SQLITE_LegacyFileFmt 0x00000002 /* Create new databases in format 1 */
  15873. #define SQLITE_FullColNames 0x00000004 /* Show full column names on SELECT */
  15874. #define SQLITE_FullFSync 0x00000008 /* Use full fsync on the backend */
  15875. #define SQLITE_CkptFullFSync 0x00000010 /* Use full fsync for checkpoint */
  15876. #define SQLITE_CacheSpill 0x00000020 /* OK to spill pager cache */
  15877. #define SQLITE_ShortColNames 0x00000040 /* Show short columns names */
  15878. #define SQLITE_CountRows 0x00000080 /* Count rows changed by INSERT, */
  15879. /* DELETE, or UPDATE and return */
  15880. /* the count using a callback. */
  15881. #define SQLITE_NullCallback 0x00000100 /* Invoke the callback once if the */
  15882. /* result set is empty */
  15883. #define SQLITE_IgnoreChecks 0x00000200 /* Do not enforce check constraints */
  15884. #define SQLITE_ReadUncommit 0x00000400 /* READ UNCOMMITTED in shared-cache */
  15885. #define SQLITE_NoCkptOnClose 0x00000800 /* No checkpoint on close()/DETACH */
  15886. #define SQLITE_ReverseOrder 0x00001000 /* Reverse unordered SELECTs */
  15887. #define SQLITE_RecTriggers 0x00002000 /* Enable recursive triggers */
  15888. #define SQLITE_ForeignKeys 0x00004000 /* Enforce foreign key constraints */
  15889. #define SQLITE_AutoIndex 0x00008000 /* Enable automatic indexes */
  15890. #define SQLITE_LoadExtension 0x00010000 /* Enable load_extension */
  15891. #define SQLITE_LoadExtFunc 0x00020000 /* Enable load_extension() SQL func */
  15892. #define SQLITE_EnableTrigger 0x00040000 /* True to enable triggers */
  15893. #define SQLITE_DeferFKs 0x00080000 /* Defer all FK constraints */
  15894. #define SQLITE_QueryOnly 0x00100000 /* Disable database changes */
  15895. #define SQLITE_CellSizeCk 0x00200000 /* Check btree cell sizes on load */
  15896. #define SQLITE_Fts3Tokenizer 0x00400000 /* Enable fts3_tokenizer(2) */
  15897. #define SQLITE_EnableQPSG 0x00800000 /* Query Planner Stability Guarantee*/
  15898. #define SQLITE_TriggerEQP 0x01000000 /* Show trigger EXPLAIN QUERY PLAN */
  15899. #define SQLITE_ResetDatabase 0x02000000 /* Reset the database */
  15900. #define SQLITE_LegacyAlter 0x04000000 /* Legacy ALTER TABLE behaviour */
  15901. #define SQLITE_NoSchemaError 0x08000000 /* Do not report schema parse errors*/
  15902. #define SQLITE_Defensive 0x10000000 /* Input SQL is likely hostile */
  15903. #define SQLITE_DqsDDL 0x20000000 /* dbl-quoted strings allowed in DDL*/
  15904. #define SQLITE_DqsDML 0x40000000 /* dbl-quoted strings allowed in DML*/
  15905. /* Flags used only if debugging */
  15906. #define HI(X) ((u64)(X)<<32)
  15907. #ifdef SQLITE_DEBUG
  15908. #define SQLITE_SqlTrace HI(0x0001) /* Debug print SQL as it executes */
  15909. #define SQLITE_VdbeListing HI(0x0002) /* Debug listings of VDBE progs */
  15910. #define SQLITE_VdbeTrace HI(0x0004) /* True to trace VDBE execution */
  15911. #define SQLITE_VdbeAddopTrace HI(0x0008) /* Trace sqlite3VdbeAddOp() calls */
  15912. #define SQLITE_VdbeEQP HI(0x0010) /* Debug EXPLAIN QUERY PLAN */
  15913. #define SQLITE_ParserTrace HI(0x0020) /* PRAGMA parser_trace=ON */
  15914. #endif
  15915. /*
  15916. ** Allowed values for sqlite3.mDbFlags
  15917. */
  15918. #define DBFLAG_SchemaChange 0x0001 /* Uncommitted Hash table changes */
  15919. #define DBFLAG_PreferBuiltin 0x0002 /* Preference to built-in funcs */
  15920. #define DBFLAG_Vacuum 0x0004 /* Currently in a VACUUM */
  15921. #define DBFLAG_VacuumInto 0x0008 /* Currently running VACUUM INTO */
  15922. #define DBFLAG_SchemaKnownOk 0x0010 /* Schema is known to be valid */
  15923. /*
  15924. ** Bits of the sqlite3.dbOptFlags field that are used by the
  15925. ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
  15926. ** selectively disable various optimizations.
  15927. */
  15928. #define SQLITE_QueryFlattener 0x0001 /* Query flattening */
  15929. #define SQLITE_WindowFunc 0x0002 /* Use xInverse for window functions */
  15930. #define SQLITE_GroupByOrder 0x0004 /* GROUPBY cover of ORDERBY */
  15931. #define SQLITE_FactorOutConst 0x0008 /* Constant factoring */
  15932. #define SQLITE_DistinctOpt 0x0010 /* DISTINCT using indexes */
  15933. #define SQLITE_CoverIdxScan 0x0020 /* Covering index scans */
  15934. #define SQLITE_OrderByIdxJoin 0x0040 /* ORDER BY of joins via index */
  15935. #define SQLITE_Transitive 0x0080 /* Transitive constraints */
  15936. #define SQLITE_OmitNoopJoin 0x0100 /* Omit unused tables in joins */
  15937. #define SQLITE_CountOfView 0x0200 /* The count-of-view optimization */
  15938. #define SQLITE_CursorHints 0x0400 /* Add OP_CursorHint opcodes */
  15939. #define SQLITE_Stat34 0x0800 /* Use STAT3 or STAT4 data */
  15940. /* TH3 expects the Stat34 ^^^^^^ value to be 0x0800. Don't change it */
  15941. #define SQLITE_PushDown 0x1000 /* The push-down optimization */
  15942. #define SQLITE_SimplifyJoin 0x2000 /* Convert LEFT JOIN to JOIN */
  15943. #define SQLITE_SkipScan 0x4000 /* Skip-scans */
  15944. #define SQLITE_PropagateConst 0x8000 /* The constant propagation opt */
  15945. #define SQLITE_AllOpts 0xffff /* All optimizations */
  15946. /*
  15947. ** Macros for testing whether or not optimizations are enabled or disabled.
  15948. */
  15949. #define OptimizationDisabled(db, mask) (((db)->dbOptFlags&(mask))!=0)
  15950. #define OptimizationEnabled(db, mask) (((db)->dbOptFlags&(mask))==0)
  15951. /*
  15952. ** Return true if it OK to factor constant expressions into the initialization
  15953. ** code. The argument is a Parse object for the code generator.
  15954. */
  15955. #define ConstFactorOk(P) ((P)->okConstFactor)
  15956. /*
  15957. ** Possible values for the sqlite.magic field.
  15958. ** The numbers are obtained at random and have no special meaning, other
  15959. ** than being distinct from one another.
  15960. */
  15961. #define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */
  15962. #define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */
  15963. #define SQLITE_MAGIC_SICK 0x4b771290 /* Error and awaiting close */
  15964. #define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */
  15965. #define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */
  15966. #define SQLITE_MAGIC_ZOMBIE 0x64cffc7f /* Close with last statement close */
  15967. /*
  15968. ** Each SQL function is defined by an instance of the following
  15969. ** structure. For global built-in functions (ex: substr(), max(), count())
  15970. ** a pointer to this structure is held in the sqlite3BuiltinFunctions object.
  15971. ** For per-connection application-defined functions, a pointer to this
  15972. ** structure is held in the db->aHash hash table.
  15973. **
  15974. ** The u.pHash field is used by the global built-ins. The u.pDestructor
  15975. ** field is used by per-connection app-def functions.
  15976. */
  15977. struct FuncDef {
  15978. i8 nArg; /* Number of arguments. -1 means unlimited */
  15979. u32 funcFlags; /* Some combination of SQLITE_FUNC_* */
  15980. void *pUserData; /* User data parameter */
  15981. FuncDef *pNext; /* Next function with same name */
  15982. void (*xSFunc)(sqlite3_context*,int,sqlite3_value**); /* func or agg-step */
  15983. void (*xFinalize)(sqlite3_context*); /* Agg finalizer */
  15984. void (*xValue)(sqlite3_context*); /* Current agg value */
  15985. void (*xInverse)(sqlite3_context*,int,sqlite3_value**); /* inverse agg-step */
  15986. const char *zName; /* SQL name of the function. */
  15987. union {
  15988. FuncDef *pHash; /* Next with a different name but the same hash */
  15989. FuncDestructor *pDestructor; /* Reference counted destructor function */
  15990. } u;
  15991. };
  15992. /*
  15993. ** This structure encapsulates a user-function destructor callback (as
  15994. ** configured using create_function_v2()) and a reference counter. When
  15995. ** create_function_v2() is called to create a function with a destructor,
  15996. ** a single object of this type is allocated. FuncDestructor.nRef is set to
  15997. ** the number of FuncDef objects created (either 1 or 3, depending on whether
  15998. ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
  15999. ** member of each of the new FuncDef objects is set to point to the allocated
  16000. ** FuncDestructor.
  16001. **
  16002. ** Thereafter, when one of the FuncDef objects is deleted, the reference
  16003. ** count on this object is decremented. When it reaches 0, the destructor
  16004. ** is invoked and the FuncDestructor structure freed.
  16005. */
  16006. struct FuncDestructor {
  16007. int nRef;
  16008. void (*xDestroy)(void *);
  16009. void *pUserData;
  16010. };
  16011. /*
  16012. ** Possible values for FuncDef.flags. Note that the _LENGTH and _TYPEOF
  16013. ** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG. And
  16014. ** SQLITE_FUNC_CONSTANT must be the same as SQLITE_DETERMINISTIC. There
  16015. ** are assert() statements in the code to verify this.
  16016. **
  16017. ** Value constraints (enforced via assert()):
  16018. ** SQLITE_FUNC_MINMAX == NC_MinMaxAgg == SF_MinMaxAgg
  16019. ** SQLITE_FUNC_LENGTH == OPFLAG_LENGTHARG
  16020. ** SQLITE_FUNC_TYPEOF == OPFLAG_TYPEOFARG
  16021. ** SQLITE_FUNC_CONSTANT == SQLITE_DETERMINISTIC from the API
  16022. ** SQLITE_FUNC_ENCMASK depends on SQLITE_UTF* macros in the API
  16023. */
  16024. #define SQLITE_FUNC_ENCMASK 0x0003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */
  16025. #define SQLITE_FUNC_LIKE 0x0004 /* Candidate for the LIKE optimization */
  16026. #define SQLITE_FUNC_CASE 0x0008 /* Case-sensitive LIKE-type function */
  16027. #define SQLITE_FUNC_EPHEM 0x0010 /* Ephemeral. Delete with VDBE */
  16028. #define SQLITE_FUNC_NEEDCOLL 0x0020 /* sqlite3GetFuncCollSeq() might be called*/
  16029. #define SQLITE_FUNC_LENGTH 0x0040 /* Built-in length() function */
  16030. #define SQLITE_FUNC_TYPEOF 0x0080 /* Built-in typeof() function */
  16031. #define SQLITE_FUNC_COUNT 0x0100 /* Built-in count(*) aggregate */
  16032. #define SQLITE_FUNC_COALESCE 0x0200 /* Built-in coalesce() or ifnull() */
  16033. #define SQLITE_FUNC_UNLIKELY 0x0400 /* Built-in unlikely() function */
  16034. #define SQLITE_FUNC_CONSTANT 0x0800 /* Constant inputs give a constant output */
  16035. #define SQLITE_FUNC_MINMAX 0x1000 /* True for min() and max() aggregates */
  16036. #define SQLITE_FUNC_SLOCHNG 0x2000 /* "Slow Change". Value constant during a
  16037. ** single query - might change over time */
  16038. #define SQLITE_FUNC_AFFINITY 0x4000 /* Built-in affinity() function */
  16039. #define SQLITE_FUNC_OFFSET 0x8000 /* Built-in sqlite_offset() function */
  16040. #define SQLITE_FUNC_WINDOW 0x00010000 /* Built-in window-only function */
  16041. #define SQLITE_FUNC_INTERNAL 0x00040000 /* For use by NestedParse() only */
  16042. /*
  16043. ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
  16044. ** used to create the initializers for the FuncDef structures.
  16045. **
  16046. ** FUNCTION(zName, nArg, iArg, bNC, xFunc)
  16047. ** Used to create a scalar function definition of a function zName
  16048. ** implemented by C function xFunc that accepts nArg arguments. The
  16049. ** value passed as iArg is cast to a (void*) and made available
  16050. ** as the user-data (sqlite3_user_data()) for the function. If
  16051. ** argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
  16052. **
  16053. ** VFUNCTION(zName, nArg, iArg, bNC, xFunc)
  16054. ** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag.
  16055. **
  16056. ** DFUNCTION(zName, nArg, iArg, bNC, xFunc)
  16057. ** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag and
  16058. ** adds the SQLITE_FUNC_SLOCHNG flag. Used for date & time functions
  16059. ** and functions like sqlite_version() that can change, but not during
  16060. ** a single query. The iArg is ignored. The user-data is always set
  16061. ** to a NULL pointer. The bNC parameter is not used.
  16062. **
  16063. ** PURE_DATE(zName, nArg, iArg, bNC, xFunc)
  16064. ** Used for "pure" date/time functions, this macro is like DFUNCTION
  16065. ** except that it does set the SQLITE_FUNC_CONSTANT flags. iArg is
  16066. ** ignored and the user-data for these functions is set to an
  16067. ** arbitrary non-NULL pointer. The bNC parameter is not used.
  16068. **
  16069. ** AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
  16070. ** Used to create an aggregate function definition implemented by
  16071. ** the C functions xStep and xFinal. The first four parameters
  16072. ** are interpreted in the same way as the first 4 parameters to
  16073. ** FUNCTION().
  16074. **
  16075. ** WFUNCTION(zName, nArg, iArg, xStep, xFinal, xValue, xInverse)
  16076. ** Used to create an aggregate function definition implemented by
  16077. ** the C functions xStep and xFinal. The first four parameters
  16078. ** are interpreted in the same way as the first 4 parameters to
  16079. ** FUNCTION().
  16080. **
  16081. ** LIKEFUNC(zName, nArg, pArg, flags)
  16082. ** Used to create a scalar function definition of a function zName
  16083. ** that accepts nArg arguments and is implemented by a call to C
  16084. ** function likeFunc. Argument pArg is cast to a (void *) and made
  16085. ** available as the function user-data (sqlite3_user_data()). The
  16086. ** FuncDef.flags variable is set to the value passed as the flags
  16087. ** parameter.
  16088. */
  16089. #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
  16090. {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  16091. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} }
  16092. #define VFUNCTION(zName, nArg, iArg, bNC, xFunc) \
  16093. {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  16094. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} }
  16095. #define DFUNCTION(zName, nArg, iArg, bNC, xFunc) \
  16096. {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8, \
  16097. 0, 0, xFunc, 0, 0, 0, #zName, {0} }
  16098. #define PURE_DATE(zName, nArg, iArg, bNC, xFunc) \
  16099. {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|SQLITE_FUNC_CONSTANT, \
  16100. (void*)&sqlite3Config, 0, xFunc, 0, 0, 0, #zName, {0} }
  16101. #define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
  16102. {nArg,SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags,\
  16103. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} }
  16104. #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
  16105. {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  16106. pArg, 0, xFunc, 0, 0, 0, #zName, }
  16107. #define LIKEFUNC(zName, nArg, arg, flags) \
  16108. {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|flags, \
  16109. (void *)arg, 0, likeFunc, 0, 0, 0, #zName, {0} }
  16110. #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal, xValue) \
  16111. {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL), \
  16112. SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,xValue,0,#zName, {0}}
  16113. #define AGGREGATE2(zName, nArg, arg, nc, xStep, xFinal, extraFlags) \
  16114. {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL)|extraFlags, \
  16115. SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,xFinal,0,#zName, {0}}
  16116. #define WAGGREGATE(zName, nArg, arg, nc, xStep, xFinal, xValue, xInverse, f) \
  16117. {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL)|f, \
  16118. SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,xValue,xInverse,#zName, {0}}
  16119. #define INTERNAL_FUNCTION(zName, nArg, xFunc) \
  16120. {nArg, SQLITE_FUNC_INTERNAL|SQLITE_UTF8|SQLITE_FUNC_CONSTANT, \
  16121. 0, 0, xFunc, 0, 0, 0, #zName, {0} }
  16122. /*
  16123. ** All current savepoints are stored in a linked list starting at
  16124. ** sqlite3.pSavepoint. The first element in the list is the most recently
  16125. ** opened savepoint. Savepoints are added to the list by the vdbe
  16126. ** OP_Savepoint instruction.
  16127. */
  16128. struct Savepoint {
  16129. char *zName; /* Savepoint name (nul-terminated) */
  16130. i64 nDeferredCons; /* Number of deferred fk violations */
  16131. i64 nDeferredImmCons; /* Number of deferred imm fk. */
  16132. Savepoint *pNext; /* Parent savepoint (if any) */
  16133. };
  16134. /*
  16135. ** The following are used as the second parameter to sqlite3Savepoint(),
  16136. ** and as the P1 argument to the OP_Savepoint instruction.
  16137. */
  16138. #define SAVEPOINT_BEGIN 0
  16139. #define SAVEPOINT_RELEASE 1
  16140. #define SAVEPOINT_ROLLBACK 2
  16141. /*
  16142. ** Each SQLite module (virtual table definition) is defined by an
  16143. ** instance of the following structure, stored in the sqlite3.aModule
  16144. ** hash table.
  16145. */
  16146. struct Module {
  16147. const sqlite3_module *pModule; /* Callback pointers */
  16148. const char *zName; /* Name passed to create_module() */
  16149. void *pAux; /* pAux passed to create_module() */
  16150. void (*xDestroy)(void *); /* Module destructor function */
  16151. Table *pEpoTab; /* Eponymous table for this module */
  16152. };
  16153. /*
  16154. ** information about each column of an SQL table is held in an instance
  16155. ** of this structure.
  16156. */
  16157. struct Column {
  16158. char *zName; /* Name of this column, \000, then the type */
  16159. Expr *pDflt; /* Default value of this column */
  16160. char *zColl; /* Collating sequence. If NULL, use the default */
  16161. u8 notNull; /* An OE_ code for handling a NOT NULL constraint */
  16162. char affinity; /* One of the SQLITE_AFF_... values */
  16163. u8 szEst; /* Estimated size of value in this column. sizeof(INT)==1 */
  16164. u8 colFlags; /* Boolean properties. See COLFLAG_ defines below */
  16165. };
  16166. /* Allowed values for Column.colFlags:
  16167. */
  16168. #define COLFLAG_PRIMKEY 0x0001 /* Column is part of the primary key */
  16169. #define COLFLAG_HIDDEN 0x0002 /* A hidden column in a virtual table */
  16170. #define COLFLAG_HASTYPE 0x0004 /* Type name follows column name */
  16171. #define COLFLAG_UNIQUE 0x0008 /* Column def contains "UNIQUE" or "PK" */
  16172. #define COLFLAG_SORTERREF 0x0010 /* Use sorter-refs with this column */
  16173. /*
  16174. ** A "Collating Sequence" is defined by an instance of the following
  16175. ** structure. Conceptually, a collating sequence consists of a name and
  16176. ** a comparison routine that defines the order of that sequence.
  16177. **
  16178. ** If CollSeq.xCmp is NULL, it means that the
  16179. ** collating sequence is undefined. Indices built on an undefined
  16180. ** collating sequence may not be read or written.
  16181. */
  16182. struct CollSeq {
  16183. char *zName; /* Name of the collating sequence, UTF-8 encoded */
  16184. u8 enc; /* Text encoding handled by xCmp() */
  16185. void *pUser; /* First argument to xCmp() */
  16186. int (*xCmp)(void*,int, const void*, int, const void*);
  16187. void (*xDel)(void*); /* Destructor for pUser */
  16188. };
  16189. /*
  16190. ** A sort order can be either ASC or DESC.
  16191. */
  16192. #define SQLITE_SO_ASC 0 /* Sort in ascending order */
  16193. #define SQLITE_SO_DESC 1 /* Sort in ascending order */
  16194. #define SQLITE_SO_UNDEFINED -1 /* No sort order specified */
  16195. /*
  16196. ** Column affinity types.
  16197. **
  16198. ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
  16199. ** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve
  16200. ** the speed a little by numbering the values consecutively.
  16201. **
  16202. ** But rather than start with 0 or 1, we begin with 'A'. That way,
  16203. ** when multiple affinity types are concatenated into a string and
  16204. ** used as the P4 operand, they will be more readable.
  16205. **
  16206. ** Note also that the numeric types are grouped together so that testing
  16207. ** for a numeric type is a single comparison. And the BLOB type is first.
  16208. */
  16209. #define SQLITE_AFF_BLOB 'A'
  16210. #define SQLITE_AFF_TEXT 'B'
  16211. #define SQLITE_AFF_NUMERIC 'C'
  16212. #define SQLITE_AFF_INTEGER 'D'
  16213. #define SQLITE_AFF_REAL 'E'
  16214. #define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC)
  16215. /*
  16216. ** The SQLITE_AFF_MASK values masks off the significant bits of an
  16217. ** affinity value.
  16218. */
  16219. #define SQLITE_AFF_MASK 0x47
  16220. /*
  16221. ** Additional bit values that can be ORed with an affinity without
  16222. ** changing the affinity.
  16223. **
  16224. ** The SQLITE_NOTNULL flag is a combination of NULLEQ and JUMPIFNULL.
  16225. ** It causes an assert() to fire if either operand to a comparison
  16226. ** operator is NULL. It is added to certain comparison operators to
  16227. ** prove that the operands are always NOT NULL.
  16228. */
  16229. #define SQLITE_KEEPNULL 0x08 /* Used by vector == or <> */
  16230. #define SQLITE_JUMPIFNULL 0x10 /* jumps if either operand is NULL */
  16231. #define SQLITE_STOREP2 0x20 /* Store result in reg[P2] rather than jump */
  16232. #define SQLITE_NULLEQ 0x80 /* NULL=NULL */
  16233. #define SQLITE_NOTNULL 0x90 /* Assert that operands are never NULL */
  16234. /*
  16235. ** An object of this type is created for each virtual table present in
  16236. ** the database schema.
  16237. **
  16238. ** If the database schema is shared, then there is one instance of this
  16239. ** structure for each database connection (sqlite3*) that uses the shared
  16240. ** schema. This is because each database connection requires its own unique
  16241. ** instance of the sqlite3_vtab* handle used to access the virtual table
  16242. ** implementation. sqlite3_vtab* handles can not be shared between
  16243. ** database connections, even when the rest of the in-memory database
  16244. ** schema is shared, as the implementation often stores the database
  16245. ** connection handle passed to it via the xConnect() or xCreate() method
  16246. ** during initialization internally. This database connection handle may
  16247. ** then be used by the virtual table implementation to access real tables
  16248. ** within the database. So that they appear as part of the callers
  16249. ** transaction, these accesses need to be made via the same database
  16250. ** connection as that used to execute SQL operations on the virtual table.
  16251. **
  16252. ** All VTable objects that correspond to a single table in a shared
  16253. ** database schema are initially stored in a linked-list pointed to by
  16254. ** the Table.pVTable member variable of the corresponding Table object.
  16255. ** When an sqlite3_prepare() operation is required to access the virtual
  16256. ** table, it searches the list for the VTable that corresponds to the
  16257. ** database connection doing the preparing so as to use the correct
  16258. ** sqlite3_vtab* handle in the compiled query.
  16259. **
  16260. ** When an in-memory Table object is deleted (for example when the
  16261. ** schema is being reloaded for some reason), the VTable objects are not
  16262. ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
  16263. ** immediately. Instead, they are moved from the Table.pVTable list to
  16264. ** another linked list headed by the sqlite3.pDisconnect member of the
  16265. ** corresponding sqlite3 structure. They are then deleted/xDisconnected
  16266. ** next time a statement is prepared using said sqlite3*. This is done
  16267. ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
  16268. ** Refer to comments above function sqlite3VtabUnlockList() for an
  16269. ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
  16270. ** list without holding the corresponding sqlite3.mutex mutex.
  16271. **
  16272. ** The memory for objects of this type is always allocated by
  16273. ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
  16274. ** the first argument.
  16275. */
  16276. struct VTable {
  16277. sqlite3 *db; /* Database connection associated with this table */
  16278. Module *pMod; /* Pointer to module implementation */
  16279. sqlite3_vtab *pVtab; /* Pointer to vtab instance */
  16280. int nRef; /* Number of pointers to this structure */
  16281. u8 bConstraint; /* True if constraints are supported */
  16282. int iSavepoint; /* Depth of the SAVEPOINT stack */
  16283. VTable *pNext; /* Next in linked list (see above) */
  16284. };
  16285. /*
  16286. ** The schema for each SQL table and view is represented in memory
  16287. ** by an instance of the following structure.
  16288. */
  16289. struct Table {
  16290. char *zName; /* Name of the table or view */
  16291. Column *aCol; /* Information about each column */
  16292. Index *pIndex; /* List of SQL indexes on this table. */
  16293. Select *pSelect; /* NULL for tables. Points to definition if a view. */
  16294. FKey *pFKey; /* Linked list of all foreign keys in this table */
  16295. char *zColAff; /* String defining the affinity of each column */
  16296. ExprList *pCheck; /* All CHECK constraints */
  16297. /* ... also used as column name list in a VIEW */
  16298. int tnum; /* Root BTree page for this table */
  16299. u32 nTabRef; /* Number of pointers to this Table */
  16300. u32 tabFlags; /* Mask of TF_* values */
  16301. i16 iPKey; /* If not negative, use aCol[iPKey] as the rowid */
  16302. i16 nCol; /* Number of columns in this table */
  16303. LogEst nRowLogEst; /* Estimated rows in table - from sqlite_stat1 table */
  16304. LogEst szTabRow; /* Estimated size of each table row in bytes */
  16305. #ifdef SQLITE_ENABLE_COSTMULT
  16306. LogEst costMult; /* Cost multiplier for using this table */
  16307. #endif
  16308. u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */
  16309. #ifndef SQLITE_OMIT_ALTERTABLE
  16310. int addColOffset; /* Offset in CREATE TABLE stmt to add a new column */
  16311. #endif
  16312. #ifndef SQLITE_OMIT_VIRTUALTABLE
  16313. int nModuleArg; /* Number of arguments to the module */
  16314. char **azModuleArg; /* 0: module 1: schema 2: vtab name 3...: args */
  16315. VTable *pVTable; /* List of VTable objects. */
  16316. #endif
  16317. Trigger *pTrigger; /* List of triggers stored in pSchema */
  16318. Schema *pSchema; /* Schema that contains this table */
  16319. Table *pNextZombie; /* Next on the Parse.pZombieTab list */
  16320. };
  16321. /*
  16322. ** Allowed values for Table.tabFlags.
  16323. **
  16324. ** TF_OOOHidden applies to tables or view that have hidden columns that are
  16325. ** followed by non-hidden columns. Example: "CREATE VIRTUAL TABLE x USING
  16326. ** vtab1(a HIDDEN, b);". Since "b" is a non-hidden column but "a" is hidden,
  16327. ** the TF_OOOHidden attribute would apply in this case. Such tables require
  16328. ** special handling during INSERT processing.
  16329. */
  16330. #define TF_Readonly 0x0001 /* Read-only system table */
  16331. #define TF_Ephemeral 0x0002 /* An ephemeral table */
  16332. #define TF_HasPrimaryKey 0x0004 /* Table has a primary key */
  16333. #define TF_Autoincrement 0x0008 /* Integer primary key is autoincrement */
  16334. #define TF_HasStat1 0x0010 /* nRowLogEst set from sqlite_stat1 */
  16335. #define TF_WithoutRowid 0x0020 /* No rowid. PRIMARY KEY is the key */
  16336. #define TF_NoVisibleRowid 0x0040 /* No user-visible "rowid" column */
  16337. #define TF_OOOHidden 0x0080 /* Out-of-Order hidden columns */
  16338. #define TF_StatsUsed 0x0100 /* Query planner decisions affected by
  16339. ** Index.aiRowLogEst[] values */
  16340. #define TF_HasNotNull 0x0200 /* Contains NOT NULL constraints */
  16341. #define TF_Shadow 0x0400 /* True for a shadow table */
  16342. /*
  16343. ** Test to see whether or not a table is a virtual table. This is
  16344. ** done as a macro so that it will be optimized out when virtual
  16345. ** table support is omitted from the build.
  16346. */
  16347. #ifndef SQLITE_OMIT_VIRTUALTABLE
  16348. # define IsVirtual(X) ((X)->nModuleArg)
  16349. #else
  16350. # define IsVirtual(X) 0
  16351. #endif
  16352. /*
  16353. ** Macros to determine if a column is hidden. IsOrdinaryHiddenColumn()
  16354. ** only works for non-virtual tables (ordinary tables and views) and is
  16355. ** always false unless SQLITE_ENABLE_HIDDEN_COLUMNS is defined. The
  16356. ** IsHiddenColumn() macro is general purpose.
  16357. */
  16358. #if defined(SQLITE_ENABLE_HIDDEN_COLUMNS)
  16359. # define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
  16360. # define IsOrdinaryHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
  16361. #elif !defined(SQLITE_OMIT_VIRTUALTABLE)
  16362. # define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
  16363. # define IsOrdinaryHiddenColumn(X) 0
  16364. #else
  16365. # define IsHiddenColumn(X) 0
  16366. # define IsOrdinaryHiddenColumn(X) 0
  16367. #endif
  16368. /* Does the table have a rowid */
  16369. #define HasRowid(X) (((X)->tabFlags & TF_WithoutRowid)==0)
  16370. #define VisibleRowid(X) (((X)->tabFlags & TF_NoVisibleRowid)==0)
  16371. /*
  16372. ** Each foreign key constraint is an instance of the following structure.
  16373. **
  16374. ** A foreign key is associated with two tables. The "from" table is
  16375. ** the table that contains the REFERENCES clause that creates the foreign
  16376. ** key. The "to" table is the table that is named in the REFERENCES clause.
  16377. ** Consider this example:
  16378. **
  16379. ** CREATE TABLE ex1(
  16380. ** a INTEGER PRIMARY KEY,
  16381. ** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
  16382. ** );
  16383. **
  16384. ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
  16385. ** Equivalent names:
  16386. **
  16387. ** from-table == child-table
  16388. ** to-table == parent-table
  16389. **
  16390. ** Each REFERENCES clause generates an instance of the following structure
  16391. ** which is attached to the from-table. The to-table need not exist when
  16392. ** the from-table is created. The existence of the to-table is not checked.
  16393. **
  16394. ** The list of all parents for child Table X is held at X.pFKey.
  16395. **
  16396. ** A list of all children for a table named Z (which might not even exist)
  16397. ** is held in Schema.fkeyHash with a hash key of Z.
  16398. */
  16399. struct FKey {
  16400. Table *pFrom; /* Table containing the REFERENCES clause (aka: Child) */
  16401. FKey *pNextFrom; /* Next FKey with the same in pFrom. Next parent of pFrom */
  16402. char *zTo; /* Name of table that the key points to (aka: Parent) */
  16403. FKey *pNextTo; /* Next with the same zTo. Next child of zTo. */
  16404. FKey *pPrevTo; /* Previous with the same zTo */
  16405. int nCol; /* Number of columns in this key */
  16406. /* EV: R-30323-21917 */
  16407. u8 isDeferred; /* True if constraint checking is deferred till COMMIT */
  16408. u8 aAction[2]; /* ON DELETE and ON UPDATE actions, respectively */
  16409. Trigger *apTrigger[2];/* Triggers for aAction[] actions */
  16410. struct sColMap { /* Mapping of columns in pFrom to columns in zTo */
  16411. int iFrom; /* Index of column in pFrom */
  16412. char *zCol; /* Name of column in zTo. If NULL use PRIMARY KEY */
  16413. } aCol[1]; /* One entry for each of nCol columns */
  16414. };
  16415. /*
  16416. ** SQLite supports many different ways to resolve a constraint
  16417. ** error. ROLLBACK processing means that a constraint violation
  16418. ** causes the operation in process to fail and for the current transaction
  16419. ** to be rolled back. ABORT processing means the operation in process
  16420. ** fails and any prior changes from that one operation are backed out,
  16421. ** but the transaction is not rolled back. FAIL processing means that
  16422. ** the operation in progress stops and returns an error code. But prior
  16423. ** changes due to the same operation are not backed out and no rollback
  16424. ** occurs. IGNORE means that the particular row that caused the constraint
  16425. ** error is not inserted or updated. Processing continues and no error
  16426. ** is returned. REPLACE means that preexisting database rows that caused
  16427. ** a UNIQUE constraint violation are removed so that the new insert or
  16428. ** update can proceed. Processing continues and no error is reported.
  16429. **
  16430. ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
  16431. ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
  16432. ** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign
  16433. ** key is set to NULL. CASCADE means that a DELETE or UPDATE of the
  16434. ** referenced table row is propagated into the row that holds the
  16435. ** foreign key.
  16436. **
  16437. ** The following symbolic values are used to record which type
  16438. ** of action to take.
  16439. */
  16440. #define OE_None 0 /* There is no constraint to check */
  16441. #define OE_Rollback 1 /* Fail the operation and rollback the transaction */
  16442. #define OE_Abort 2 /* Back out changes but do no rollback transaction */
  16443. #define OE_Fail 3 /* Stop the operation but leave all prior changes */
  16444. #define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */
  16445. #define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */
  16446. #define OE_Update 6 /* Process as a DO UPDATE in an upsert */
  16447. #define OE_Restrict 7 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
  16448. #define OE_SetNull 8 /* Set the foreign key value to NULL */
  16449. #define OE_SetDflt 9 /* Set the foreign key value to its default */
  16450. #define OE_Cascade 10 /* Cascade the changes */
  16451. #define OE_Default 11 /* Do whatever the default action is */
  16452. /*
  16453. ** An instance of the following structure is passed as the first
  16454. ** argument to sqlite3VdbeKeyCompare and is used to control the
  16455. ** comparison of the two index keys.
  16456. **
  16457. ** Note that aSortOrder[] and aColl[] have nField+1 slots. There
  16458. ** are nField slots for the columns of an index then one extra slot
  16459. ** for the rowid at the end.
  16460. */
  16461. struct KeyInfo {
  16462. u32 nRef; /* Number of references to this KeyInfo object */
  16463. u8 enc; /* Text encoding - one of the SQLITE_UTF* values */
  16464. u16 nKeyField; /* Number of key columns in the index */
  16465. u16 nAllField; /* Total columns, including key plus others */
  16466. sqlite3 *db; /* The database connection */
  16467. u8 *aSortOrder; /* Sort order for each column. */
  16468. CollSeq *aColl[1]; /* Collating sequence for each term of the key */
  16469. };
  16470. /*
  16471. ** This object holds a record which has been parsed out into individual
  16472. ** fields, for the purposes of doing a comparison.
  16473. **
  16474. ** A record is an object that contains one or more fields of data.
  16475. ** Records are used to store the content of a table row and to store
  16476. ** the key of an index. A blob encoding of a record is created by
  16477. ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
  16478. ** OP_Column opcode.
  16479. **
  16480. ** An instance of this object serves as a "key" for doing a search on
  16481. ** an index b+tree. The goal of the search is to find the entry that
  16482. ** is closed to the key described by this object. This object might hold
  16483. ** just a prefix of the key. The number of fields is given by
  16484. ** pKeyInfo->nField.
  16485. **
  16486. ** The r1 and r2 fields are the values to return if this key is less than
  16487. ** or greater than a key in the btree, respectively. These are normally
  16488. ** -1 and +1 respectively, but might be inverted to +1 and -1 if the b-tree
  16489. ** is in DESC order.
  16490. **
  16491. ** The key comparison functions actually return default_rc when they find
  16492. ** an equals comparison. default_rc can be -1, 0, or +1. If there are
  16493. ** multiple entries in the b-tree with the same key (when only looking
  16494. ** at the first pKeyInfo->nFields,) then default_rc can be set to -1 to
  16495. ** cause the search to find the last match, or +1 to cause the search to
  16496. ** find the first match.
  16497. **
  16498. ** The key comparison functions will set eqSeen to true if they ever
  16499. ** get and equal results when comparing this structure to a b-tree record.
  16500. ** When default_rc!=0, the search might end up on the record immediately
  16501. ** before the first match or immediately after the last match. The
  16502. ** eqSeen field will indicate whether or not an exact match exists in the
  16503. ** b-tree.
  16504. */
  16505. struct UnpackedRecord {
  16506. KeyInfo *pKeyInfo; /* Collation and sort-order information */
  16507. Mem *aMem; /* Values */
  16508. u16 nField; /* Number of entries in apMem[] */
  16509. i8 default_rc; /* Comparison result if keys are equal */
  16510. u8 errCode; /* Error detected by xRecordCompare (CORRUPT or NOMEM) */
  16511. i8 r1; /* Value to return if (lhs < rhs) */
  16512. i8 r2; /* Value to return if (lhs > rhs) */
  16513. u8 eqSeen; /* True if an equality comparison has been seen */
  16514. };
  16515. /*
  16516. ** Each SQL index is represented in memory by an
  16517. ** instance of the following structure.
  16518. **
  16519. ** The columns of the table that are to be indexed are described
  16520. ** by the aiColumn[] field of this structure. For example, suppose
  16521. ** we have the following table and index:
  16522. **
  16523. ** CREATE TABLE Ex1(c1 int, c2 int, c3 text);
  16524. ** CREATE INDEX Ex2 ON Ex1(c3,c1);
  16525. **
  16526. ** In the Table structure describing Ex1, nCol==3 because there are
  16527. ** three columns in the table. In the Index structure describing
  16528. ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
  16529. ** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the
  16530. ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
  16531. ** The second column to be indexed (c1) has an index of 0 in
  16532. ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
  16533. **
  16534. ** The Index.onError field determines whether or not the indexed columns
  16535. ** must be unique and what to do if they are not. When Index.onError=OE_None,
  16536. ** it means this is not a unique index. Otherwise it is a unique index
  16537. ** and the value of Index.onError indicate the which conflict resolution
  16538. ** algorithm to employ whenever an attempt is made to insert a non-unique
  16539. ** element.
  16540. **
  16541. ** While parsing a CREATE TABLE or CREATE INDEX statement in order to
  16542. ** generate VDBE code (as opposed to parsing one read from an sqlite_master
  16543. ** table as part of parsing an existing database schema), transient instances
  16544. ** of this structure may be created. In this case the Index.tnum variable is
  16545. ** used to store the address of a VDBE instruction, not a database page
  16546. ** number (it cannot - the database page is not allocated until the VDBE
  16547. ** program is executed). See convertToWithoutRowidTable() for details.
  16548. */
  16549. struct Index {
  16550. char *zName; /* Name of this index */
  16551. i16 *aiColumn; /* Which columns are used by this index. 1st is 0 */
  16552. LogEst *aiRowLogEst; /* From ANALYZE: Est. rows selected by each column */
  16553. Table *pTable; /* The SQL table being indexed */
  16554. char *zColAff; /* String defining the affinity of each column */
  16555. Index *pNext; /* The next index associated with the same table */
  16556. Schema *pSchema; /* Schema containing this index */
  16557. u8 *aSortOrder; /* for each column: True==DESC, False==ASC */
  16558. const char **azColl; /* Array of collation sequence names for index */
  16559. Expr *pPartIdxWhere; /* WHERE clause for partial indices */
  16560. ExprList *aColExpr; /* Column expressions */
  16561. int tnum; /* DB Page containing root of this index */
  16562. LogEst szIdxRow; /* Estimated average row size in bytes */
  16563. u16 nKeyCol; /* Number of columns forming the key */
  16564. u16 nColumn; /* Number of columns stored in the index */
  16565. u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  16566. unsigned idxType:2; /* 0:Normal 1:UNIQUE, 2:PRIMARY KEY, 3:IPK */
  16567. unsigned bUnordered:1; /* Use this index for == or IN queries only */
  16568. unsigned uniqNotNull:1; /* True if UNIQUE and NOT NULL for all columns */
  16569. unsigned isResized:1; /* True if resizeIndexObject() has been called */
  16570. unsigned isCovering:1; /* True if this is a covering index */
  16571. unsigned noSkipScan:1; /* Do not try to use skip-scan if true */
  16572. unsigned hasStat1:1; /* aiRowLogEst values come from sqlite_stat1 */
  16573. unsigned bNoQuery:1; /* Do not use this index to optimize queries */
  16574. unsigned bAscKeyBug:1; /* True if the bba7b69f9849b5bf bug applies */
  16575. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  16576. int nSample; /* Number of elements in aSample[] */
  16577. int nSampleCol; /* Size of IndexSample.anEq[] and so on */
  16578. tRowcnt *aAvgEq; /* Average nEq values for keys not in aSample */
  16579. IndexSample *aSample; /* Samples of the left-most key */
  16580. tRowcnt *aiRowEst; /* Non-logarithmic stat1 data for this index */
  16581. tRowcnt nRowEst0; /* Non-logarithmic number of rows in the index */
  16582. #endif
  16583. Bitmask colNotIdxed; /* 0 for unindexed columns in pTab */
  16584. };
  16585. /*
  16586. ** Allowed values for Index.idxType
  16587. */
  16588. #define SQLITE_IDXTYPE_APPDEF 0 /* Created using CREATE INDEX */
  16589. #define SQLITE_IDXTYPE_UNIQUE 1 /* Implements a UNIQUE constraint */
  16590. #define SQLITE_IDXTYPE_PRIMARYKEY 2 /* Is the PRIMARY KEY for the table */
  16591. #define SQLITE_IDXTYPE_IPK 3 /* INTEGER PRIMARY KEY index */
  16592. /* Return true if index X is a PRIMARY KEY index */
  16593. #define IsPrimaryKeyIndex(X) ((X)->idxType==SQLITE_IDXTYPE_PRIMARYKEY)
  16594. /* Return true if index X is a UNIQUE index */
  16595. #define IsUniqueIndex(X) ((X)->onError!=OE_None)
  16596. /* The Index.aiColumn[] values are normally positive integer. But
  16597. ** there are some negative values that have special meaning:
  16598. */
  16599. #define XN_ROWID (-1) /* Indexed column is the rowid */
  16600. #define XN_EXPR (-2) /* Indexed column is an expression */
  16601. /*
  16602. ** Each sample stored in the sqlite_stat3 table is represented in memory
  16603. ** using a structure of this type. See documentation at the top of the
  16604. ** analyze.c source file for additional information.
  16605. */
  16606. struct IndexSample {
  16607. void *p; /* Pointer to sampled record */
  16608. int n; /* Size of record in bytes */
  16609. tRowcnt *anEq; /* Est. number of rows where the key equals this sample */
  16610. tRowcnt *anLt; /* Est. number of rows where key is less than this sample */
  16611. tRowcnt *anDLt; /* Est. number of distinct keys less than this sample */
  16612. };
  16613. /*
  16614. ** Possible values to use within the flags argument to sqlite3GetToken().
  16615. */
  16616. #define SQLITE_TOKEN_QUOTED 0x1 /* Token is a quoted identifier. */
  16617. #define SQLITE_TOKEN_KEYWORD 0x2 /* Token is a keyword. */
  16618. /*
  16619. ** Each token coming out of the lexer is an instance of
  16620. ** this structure. Tokens are also used as part of an expression.
  16621. **
  16622. ** The memory that "z" points to is owned by other objects. Take care
  16623. ** that the owner of the "z" string does not deallocate the string before
  16624. ** the Token goes out of scope! Very often, the "z" points to some place
  16625. ** in the middle of the Parse.zSql text. But it might also point to a
  16626. ** static string.
  16627. */
  16628. struct Token {
  16629. const char *z; /* Text of the token. Not NULL-terminated! */
  16630. unsigned int n; /* Number of characters in this token */
  16631. };
  16632. /*
  16633. ** An instance of this structure contains information needed to generate
  16634. ** code for a SELECT that contains aggregate functions.
  16635. **
  16636. ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
  16637. ** pointer to this structure. The Expr.iColumn field is the index in
  16638. ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
  16639. ** code for that node.
  16640. **
  16641. ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
  16642. ** original Select structure that describes the SELECT statement. These
  16643. ** fields do not need to be freed when deallocating the AggInfo structure.
  16644. */
  16645. struct AggInfo {
  16646. u8 directMode; /* Direct rendering mode means take data directly
  16647. ** from source tables rather than from accumulators */
  16648. u8 useSortingIdx; /* In direct mode, reference the sorting index rather
  16649. ** than the source table */
  16650. int sortingIdx; /* Cursor number of the sorting index */
  16651. int sortingIdxPTab; /* Cursor number of pseudo-table */
  16652. int nSortingColumn; /* Number of columns in the sorting index */
  16653. int mnReg, mxReg; /* Range of registers allocated for aCol and aFunc */
  16654. ExprList *pGroupBy; /* The group by clause */
  16655. struct AggInfo_col { /* For each column used in source tables */
  16656. Table *pTab; /* Source table */
  16657. int iTable; /* Cursor number of the source table */
  16658. int iColumn; /* Column number within the source table */
  16659. int iSorterColumn; /* Column number in the sorting index */
  16660. int iMem; /* Memory location that acts as accumulator */
  16661. Expr *pExpr; /* The original expression */
  16662. } *aCol;
  16663. int nColumn; /* Number of used entries in aCol[] */
  16664. int nAccumulator; /* Number of columns that show through to the output.
  16665. ** Additional columns are used only as parameters to
  16666. ** aggregate functions */
  16667. struct AggInfo_func { /* For each aggregate function */
  16668. Expr *pExpr; /* Expression encoding the function */
  16669. FuncDef *pFunc; /* The aggregate function implementation */
  16670. int iMem; /* Memory location that acts as accumulator */
  16671. int iDistinct; /* Ephemeral table used to enforce DISTINCT */
  16672. } *aFunc;
  16673. int nFunc; /* Number of entries in aFunc[] */
  16674. };
  16675. /*
  16676. ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
  16677. ** Usually it is 16-bits. But if SQLITE_MAX_VARIABLE_NUMBER is greater
  16678. ** than 32767 we have to make it 32-bit. 16-bit is preferred because
  16679. ** it uses less memory in the Expr object, which is a big memory user
  16680. ** in systems with lots of prepared statements. And few applications
  16681. ** need more than about 10 or 20 variables. But some extreme users want
  16682. ** to have prepared statements with over 32767 variables, and for them
  16683. ** the option is available (at compile-time).
  16684. */
  16685. #if SQLITE_MAX_VARIABLE_NUMBER<=32767
  16686. typedef i16 ynVar;
  16687. #else
  16688. typedef int ynVar;
  16689. #endif
  16690. /*
  16691. ** Each node of an expression in the parse tree is an instance
  16692. ** of this structure.
  16693. **
  16694. ** Expr.op is the opcode. The integer parser token codes are reused
  16695. ** as opcodes here. For example, the parser defines TK_GE to be an integer
  16696. ** code representing the ">=" operator. This same integer code is reused
  16697. ** to represent the greater-than-or-equal-to operator in the expression
  16698. ** tree.
  16699. **
  16700. ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
  16701. ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
  16702. ** the expression is a variable (TK_VARIABLE), then Expr.token contains the
  16703. ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
  16704. ** then Expr.token contains the name of the function.
  16705. **
  16706. ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
  16707. ** binary operator. Either or both may be NULL.
  16708. **
  16709. ** Expr.x.pList is a list of arguments if the expression is an SQL function,
  16710. ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
  16711. ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
  16712. ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
  16713. ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
  16714. ** valid.
  16715. **
  16716. ** An expression of the form ID or ID.ID refers to a column in a table.
  16717. ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
  16718. ** the integer cursor number of a VDBE cursor pointing to that table and
  16719. ** Expr.iColumn is the column number for the specific column. If the
  16720. ** expression is used as a result in an aggregate SELECT, then the
  16721. ** value is also stored in the Expr.iAgg column in the aggregate so that
  16722. ** it can be accessed after all aggregates are computed.
  16723. **
  16724. ** If the expression is an unbound variable marker (a question mark
  16725. ** character '?' in the original SQL) then the Expr.iTable holds the index
  16726. ** number for that variable.
  16727. **
  16728. ** If the expression is a subquery then Expr.iColumn holds an integer
  16729. ** register number containing the result of the subquery. If the
  16730. ** subquery gives a constant result, then iTable is -1. If the subquery
  16731. ** gives a different answer at different times during statement processing
  16732. ** then iTable is the address of a subroutine that computes the subquery.
  16733. **
  16734. ** If the Expr is of type OP_Column, and the table it is selecting from
  16735. ** is a disk table or the "old.*" pseudo-table, then pTab points to the
  16736. ** corresponding table definition.
  16737. **
  16738. ** ALLOCATION NOTES:
  16739. **
  16740. ** Expr objects can use a lot of memory space in database schema. To
  16741. ** help reduce memory requirements, sometimes an Expr object will be
  16742. ** truncated. And to reduce the number of memory allocations, sometimes
  16743. ** two or more Expr objects will be stored in a single memory allocation,
  16744. ** together with Expr.zToken strings.
  16745. **
  16746. ** If the EP_Reduced and EP_TokenOnly flags are set when
  16747. ** an Expr object is truncated. When EP_Reduced is set, then all
  16748. ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
  16749. ** are contained within the same memory allocation. Note, however, that
  16750. ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
  16751. ** allocated, regardless of whether or not EP_Reduced is set.
  16752. */
  16753. struct Expr {
  16754. u8 op; /* Operation performed by this node */
  16755. char affinity; /* The affinity of the column or 0 if not a column */
  16756. u32 flags; /* Various flags. EP_* See below */
  16757. union {
  16758. char *zToken; /* Token value. Zero terminated and dequoted */
  16759. int iValue; /* Non-negative integer value if EP_IntValue */
  16760. } u;
  16761. /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
  16762. ** space is allocated for the fields below this point. An attempt to
  16763. ** access them will result in a segfault or malfunction.
  16764. *********************************************************************/
  16765. Expr *pLeft; /* Left subnode */
  16766. Expr *pRight; /* Right subnode */
  16767. union {
  16768. ExprList *pList; /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */
  16769. Select *pSelect; /* EP_xIsSelect and op = IN, EXISTS, SELECT */
  16770. } x;
  16771. /* If the EP_Reduced flag is set in the Expr.flags mask, then no
  16772. ** space is allocated for the fields below this point. An attempt to
  16773. ** access them will result in a segfault or malfunction.
  16774. *********************************************************************/
  16775. #if SQLITE_MAX_EXPR_DEPTH>0
  16776. int nHeight; /* Height of the tree headed by this node */
  16777. #endif
  16778. int iTable; /* TK_COLUMN: cursor number of table holding column
  16779. ** TK_REGISTER: register number
  16780. ** TK_TRIGGER: 1 -> new, 0 -> old
  16781. ** EP_Unlikely: 134217728 times likelihood
  16782. ** TK_SELECT: 1st register of result vector */
  16783. ynVar iColumn; /* TK_COLUMN: column index. -1 for rowid.
  16784. ** TK_VARIABLE: variable number (always >= 1).
  16785. ** TK_SELECT_COLUMN: column of the result vector */
  16786. i16 iAgg; /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
  16787. i16 iRightJoinTable; /* If EP_FromJoin, the right table of the join */
  16788. u8 op2; /* TK_REGISTER/TK_TRUTH: original value of Expr.op
  16789. ** TK_COLUMN: the value of p5 for OP_Column
  16790. ** TK_AGG_FUNCTION: nesting depth */
  16791. AggInfo *pAggInfo; /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
  16792. union {
  16793. Table *pTab; /* TK_COLUMN: Table containing column. Can be NULL
  16794. ** for a column of an index on an expression */
  16795. Window *pWin; /* TK_FUNCTION: Window definition for the func */
  16796. struct { /* TK_IN, TK_SELECT, and TK_EXISTS */
  16797. int iAddr; /* Subroutine entry address */
  16798. int regReturn; /* Register used to hold return address */
  16799. } sub;
  16800. } y;
  16801. };
  16802. /*
  16803. ** The following are the meanings of bits in the Expr.flags field.
  16804. ** Value restrictions:
  16805. **
  16806. ** EP_Agg == NC_HasAgg == SF_HasAgg
  16807. ** EP_Win == NC_HasWin
  16808. */
  16809. #define EP_FromJoin 0x000001 /* Originates in ON/USING clause of outer join */
  16810. #define EP_Distinct 0x000002 /* Aggregate function with DISTINCT keyword */
  16811. #define EP_HasFunc 0x000004 /* Contains one or more functions of any kind */
  16812. #define EP_FixedCol 0x000008 /* TK_Column with a known fixed value */
  16813. #define EP_Agg 0x000010 /* Contains one or more aggregate functions */
  16814. #define EP_VarSelect 0x000020 /* pSelect is correlated, not constant */
  16815. #define EP_DblQuoted 0x000040 /* token.z was originally in "..." */
  16816. #define EP_InfixFunc 0x000080 /* True for an infix function: LIKE, GLOB, etc */
  16817. #define EP_Collate 0x000100 /* Tree contains a TK_COLLATE operator */
  16818. #define EP_Generic 0x000200 /* Ignore COLLATE or affinity on this tree */
  16819. #define EP_IntValue 0x000400 /* Integer value contained in u.iValue */
  16820. #define EP_xIsSelect 0x000800 /* x.pSelect is valid (otherwise x.pList is) */
  16821. #define EP_Skip 0x001000 /* Operator does not contribute to affinity */
  16822. #define EP_Reduced 0x002000 /* Expr struct EXPR_REDUCEDSIZE bytes only */
  16823. #define EP_TokenOnly 0x004000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */
  16824. #define EP_Win 0x008000 /* Contains window functions */
  16825. #define EP_MemToken 0x010000 /* Need to sqlite3DbFree() Expr.zToken */
  16826. #define EP_NoReduce 0x020000 /* Cannot EXPRDUP_REDUCE this Expr */
  16827. #define EP_Unlikely 0x040000 /* unlikely() or likelihood() function */
  16828. #define EP_ConstFunc 0x080000 /* A SQLITE_FUNC_CONSTANT or _SLOCHNG function */
  16829. #define EP_CanBeNull 0x100000 /* Can be null despite NOT NULL constraint */
  16830. #define EP_Subquery 0x200000 /* Tree contains a TK_SELECT operator */
  16831. #define EP_Alias 0x400000 /* Is an alias for a result set column */
  16832. #define EP_Leaf 0x800000 /* Expr.pLeft, .pRight, .u.pSelect all NULL */
  16833. #define EP_WinFunc 0x1000000 /* TK_FUNCTION with Expr.y.pWin set */
  16834. #define EP_Subrtn 0x2000000 /* Uses Expr.y.sub. TK_IN, _SELECT, or _EXISTS */
  16835. #define EP_Quoted 0x4000000 /* TK_ID was originally quoted */
  16836. #define EP_Static 0x8000000 /* Held in memory not obtained from malloc() */
  16837. #define EP_IsTrue 0x10000000 /* Always has boolean value of TRUE */
  16838. #define EP_IsFalse 0x20000000 /* Always has boolean value of FALSE */
  16839. /*
  16840. ** The EP_Propagate mask is a set of properties that automatically propagate
  16841. ** upwards into parent nodes.
  16842. */
  16843. #define EP_Propagate (EP_Collate|EP_Subquery|EP_HasFunc)
  16844. /*
  16845. ** These macros can be used to test, set, or clear bits in the
  16846. ** Expr.flags field.
  16847. */
  16848. #define ExprHasProperty(E,P) (((E)->flags&(P))!=0)
  16849. #define ExprHasAllProperty(E,P) (((E)->flags&(P))==(P))
  16850. #define ExprSetProperty(E,P) (E)->flags|=(P)
  16851. #define ExprClearProperty(E,P) (E)->flags&=~(P)
  16852. #define ExprAlwaysTrue(E) (((E)->flags&(EP_FromJoin|EP_IsTrue))==EP_IsTrue)
  16853. #define ExprAlwaysFalse(E) (((E)->flags&(EP_FromJoin|EP_IsFalse))==EP_IsFalse)
  16854. /* The ExprSetVVAProperty() macro is used for Verification, Validation,
  16855. ** and Accreditation only. It works like ExprSetProperty() during VVA
  16856. ** processes but is a no-op for delivery.
  16857. */
  16858. #ifdef SQLITE_DEBUG
  16859. # define ExprSetVVAProperty(E,P) (E)->flags|=(P)
  16860. #else
  16861. # define ExprSetVVAProperty(E,P)
  16862. #endif
  16863. /*
  16864. ** Macros to determine the number of bytes required by a normal Expr
  16865. ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
  16866. ** and an Expr struct with the EP_TokenOnly flag set.
  16867. */
  16868. #define EXPR_FULLSIZE sizeof(Expr) /* Full size */
  16869. #define EXPR_REDUCEDSIZE offsetof(Expr,iTable) /* Common features */
  16870. #define EXPR_TOKENONLYSIZE offsetof(Expr,pLeft) /* Fewer features */
  16871. /*
  16872. ** Flags passed to the sqlite3ExprDup() function. See the header comment
  16873. ** above sqlite3ExprDup() for details.
  16874. */
  16875. #define EXPRDUP_REDUCE 0x0001 /* Used reduced-size Expr nodes */
  16876. /*
  16877. ** A list of expressions. Each expression may optionally have a
  16878. ** name. An expr/name combination can be used in several ways, such
  16879. ** as the list of "expr AS ID" fields following a "SELECT" or in the
  16880. ** list of "ID = expr" items in an UPDATE. A list of expressions can
  16881. ** also be used as the argument to a function, in which case the a.zName
  16882. ** field is not used.
  16883. **
  16884. ** By default the Expr.zSpan field holds a human-readable description of
  16885. ** the expression that is used in the generation of error messages and
  16886. ** column labels. In this case, Expr.zSpan is typically the text of a
  16887. ** column expression as it exists in a SELECT statement. However, if
  16888. ** the bSpanIsTab flag is set, then zSpan is overloaded to mean the name
  16889. ** of the result column in the form: DATABASE.TABLE.COLUMN. This later
  16890. ** form is used for name resolution with nested FROM clauses.
  16891. */
  16892. struct ExprList {
  16893. int nExpr; /* Number of expressions on the list */
  16894. struct ExprList_item { /* For each expression in the list */
  16895. Expr *pExpr; /* The parse tree for this expression */
  16896. char *zName; /* Token associated with this expression */
  16897. char *zSpan; /* Original text of the expression */
  16898. u8 sortOrder; /* 1 for DESC or 0 for ASC */
  16899. unsigned done :1; /* A flag to indicate when processing is finished */
  16900. unsigned bSpanIsTab :1; /* zSpan holds DB.TABLE.COLUMN */
  16901. unsigned reusable :1; /* Constant expression is reusable */
  16902. unsigned bSorterRef :1; /* Defer evaluation until after sorting */
  16903. union {
  16904. struct {
  16905. u16 iOrderByCol; /* For ORDER BY, column number in result set */
  16906. u16 iAlias; /* Index into Parse.aAlias[] for zName */
  16907. } x;
  16908. int iConstExprReg; /* Register in which Expr value is cached */
  16909. } u;
  16910. } a[1]; /* One slot for each expression in the list */
  16911. };
  16912. /*
  16913. ** An instance of this structure can hold a simple list of identifiers,
  16914. ** such as the list "a,b,c" in the following statements:
  16915. **
  16916. ** INSERT INTO t(a,b,c) VALUES ...;
  16917. ** CREATE INDEX idx ON t(a,b,c);
  16918. ** CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
  16919. **
  16920. ** The IdList.a.idx field is used when the IdList represents the list of
  16921. ** column names after a table name in an INSERT statement. In the statement
  16922. **
  16923. ** INSERT INTO t(a,b,c) ...
  16924. **
  16925. ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
  16926. */
  16927. struct IdList {
  16928. struct IdList_item {
  16929. char *zName; /* Name of the identifier */
  16930. int idx; /* Index in some Table.aCol[] of a column named zName */
  16931. } *a;
  16932. int nId; /* Number of identifiers on the list */
  16933. };
  16934. /*
  16935. ** The following structure describes the FROM clause of a SELECT statement.
  16936. ** Each table or subquery in the FROM clause is a separate element of
  16937. ** the SrcList.a[] array.
  16938. **
  16939. ** With the addition of multiple database support, the following structure
  16940. ** can also be used to describe a particular table such as the table that
  16941. ** is modified by an INSERT, DELETE, or UPDATE statement. In standard SQL,
  16942. ** such a table must be a simple name: ID. But in SQLite, the table can
  16943. ** now be identified by a database name, a dot, then the table name: ID.ID.
  16944. **
  16945. ** The jointype starts out showing the join type between the current table
  16946. ** and the next table on the list. The parser builds the list this way.
  16947. ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
  16948. ** jointype expresses the join between the table and the previous table.
  16949. **
  16950. ** In the colUsed field, the high-order bit (bit 63) is set if the table
  16951. ** contains more than 63 columns and the 64-th or later column is used.
  16952. */
  16953. struct SrcList {
  16954. int nSrc; /* Number of tables or subqueries in the FROM clause */
  16955. u32 nAlloc; /* Number of entries allocated in a[] below */
  16956. struct SrcList_item {
  16957. Schema *pSchema; /* Schema to which this item is fixed */
  16958. char *zDatabase; /* Name of database holding this table */
  16959. char *zName; /* Name of the table */
  16960. char *zAlias; /* The "B" part of a "A AS B" phrase. zName is the "A" */
  16961. Table *pTab; /* An SQL table corresponding to zName */
  16962. Select *pSelect; /* A SELECT statement used in place of a table name */
  16963. int addrFillSub; /* Address of subroutine to manifest a subquery */
  16964. int regReturn; /* Register holding return address of addrFillSub */
  16965. int regResult; /* Registers holding results of a co-routine */
  16966. struct {
  16967. u8 jointype; /* Type of join between this table and the previous */
  16968. unsigned notIndexed :1; /* True if there is a NOT INDEXED clause */
  16969. unsigned isIndexedBy :1; /* True if there is an INDEXED BY clause */
  16970. unsigned isTabFunc :1; /* True if table-valued-function syntax */
  16971. unsigned isCorrelated :1; /* True if sub-query is correlated */
  16972. unsigned viaCoroutine :1; /* Implemented as a co-routine */
  16973. unsigned isRecursive :1; /* True for recursive reference in WITH */
  16974. } fg;
  16975. int iCursor; /* The VDBE cursor number used to access this table */
  16976. Expr *pOn; /* The ON clause of a join */
  16977. IdList *pUsing; /* The USING clause of a join */
  16978. Bitmask colUsed; /* Bit N (1<<N) set if column N of pTab is used */
  16979. union {
  16980. char *zIndexedBy; /* Identifier from "INDEXED BY <zIndex>" clause */
  16981. ExprList *pFuncArg; /* Arguments to table-valued-function */
  16982. } u1;
  16983. Index *pIBIndex; /* Index structure corresponding to u1.zIndexedBy */
  16984. } a[1]; /* One entry for each identifier on the list */
  16985. };
  16986. /*
  16987. ** Permitted values of the SrcList.a.jointype field
  16988. */
  16989. #define JT_INNER 0x0001 /* Any kind of inner or cross join */
  16990. #define JT_CROSS 0x0002 /* Explicit use of the CROSS keyword */
  16991. #define JT_NATURAL 0x0004 /* True for a "natural" join */
  16992. #define JT_LEFT 0x0008 /* Left outer join */
  16993. #define JT_RIGHT 0x0010 /* Right outer join */
  16994. #define JT_OUTER 0x0020 /* The "OUTER" keyword is present */
  16995. #define JT_ERROR 0x0040 /* unknown or unsupported join type */
  16996. /*
  16997. ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
  16998. ** and the WhereInfo.wctrlFlags member.
  16999. **
  17000. ** Value constraints (enforced via assert()):
  17001. ** WHERE_USE_LIMIT == SF_FixedLimit
  17002. */
  17003. #define WHERE_ORDERBY_NORMAL 0x0000 /* No-op */
  17004. #define WHERE_ORDERBY_MIN 0x0001 /* ORDER BY processing for min() func */
  17005. #define WHERE_ORDERBY_MAX 0x0002 /* ORDER BY processing for max() func */
  17006. #define WHERE_ONEPASS_DESIRED 0x0004 /* Want to do one-pass UPDATE/DELETE */
  17007. #define WHERE_ONEPASS_MULTIROW 0x0008 /* ONEPASS is ok with multiple rows */
  17008. #define WHERE_DUPLICATES_OK 0x0010 /* Ok to return a row more than once */
  17009. #define WHERE_OR_SUBCLAUSE 0x0020 /* Processing a sub-WHERE as part of
  17010. ** the OR optimization */
  17011. #define WHERE_GROUPBY 0x0040 /* pOrderBy is really a GROUP BY */
  17012. #define WHERE_DISTINCTBY 0x0080 /* pOrderby is really a DISTINCT clause */
  17013. #define WHERE_WANT_DISTINCT 0x0100 /* All output needs to be distinct */
  17014. #define WHERE_SORTBYGROUP 0x0200 /* Support sqlite3WhereIsSorted() */
  17015. #define WHERE_SEEK_TABLE 0x0400 /* Do not defer seeks on main table */
  17016. #define WHERE_ORDERBY_LIMIT 0x0800 /* ORDERBY+LIMIT on the inner loop */
  17017. #define WHERE_SEEK_UNIQ_TABLE 0x1000 /* Do not defer seeks if unique */
  17018. /* 0x2000 not currently used */
  17019. #define WHERE_USE_LIMIT 0x4000 /* Use the LIMIT in cost estimates */
  17020. /* 0x8000 not currently used */
  17021. /* Allowed return values from sqlite3WhereIsDistinct()
  17022. */
  17023. #define WHERE_DISTINCT_NOOP 0 /* DISTINCT keyword not used */
  17024. #define WHERE_DISTINCT_UNIQUE 1 /* No duplicates */
  17025. #define WHERE_DISTINCT_ORDERED 2 /* All duplicates are adjacent */
  17026. #define WHERE_DISTINCT_UNORDERED 3 /* Duplicates are scattered */
  17027. /*
  17028. ** A NameContext defines a context in which to resolve table and column
  17029. ** names. The context consists of a list of tables (the pSrcList) field and
  17030. ** a list of named expression (pEList). The named expression list may
  17031. ** be NULL. The pSrc corresponds to the FROM clause of a SELECT or
  17032. ** to the table being operated on by INSERT, UPDATE, or DELETE. The
  17033. ** pEList corresponds to the result set of a SELECT and is NULL for
  17034. ** other statements.
  17035. **
  17036. ** NameContexts can be nested. When resolving names, the inner-most
  17037. ** context is searched first. If no match is found, the next outer
  17038. ** context is checked. If there is still no match, the next context
  17039. ** is checked. This process continues until either a match is found
  17040. ** or all contexts are check. When a match is found, the nRef member of
  17041. ** the context containing the match is incremented.
  17042. **
  17043. ** Each subquery gets a new NameContext. The pNext field points to the
  17044. ** NameContext in the parent query. Thus the process of scanning the
  17045. ** NameContext list corresponds to searching through successively outer
  17046. ** subqueries looking for a match.
  17047. */
  17048. struct NameContext {
  17049. Parse *pParse; /* The parser */
  17050. SrcList *pSrcList; /* One or more tables used to resolve names */
  17051. union {
  17052. ExprList *pEList; /* Optional list of result-set columns */
  17053. AggInfo *pAggInfo; /* Information about aggregates at this level */
  17054. Upsert *pUpsert; /* ON CONFLICT clause information from an upsert */
  17055. } uNC;
  17056. NameContext *pNext; /* Next outer name context. NULL for outermost */
  17057. int nRef; /* Number of names resolved by this context */
  17058. int nErr; /* Number of errors encountered while resolving names */
  17059. int ncFlags; /* Zero or more NC_* flags defined below */
  17060. Select *pWinSelect; /* SELECT statement for any window functions */
  17061. };
  17062. /*
  17063. ** Allowed values for the NameContext, ncFlags field.
  17064. **
  17065. ** Value constraints (all checked via assert()):
  17066. ** NC_HasAgg == SF_HasAgg == EP_Agg
  17067. ** NC_MinMaxAgg == SF_MinMaxAgg == SQLITE_FUNC_MINMAX
  17068. ** NC_HasWin == EP_Win
  17069. **
  17070. */
  17071. #define NC_AllowAgg 0x0001 /* Aggregate functions are allowed here */
  17072. #define NC_PartIdx 0x0002 /* True if resolving a partial index WHERE */
  17073. #define NC_IsCheck 0x0004 /* True if resolving names in a CHECK constraint */
  17074. #define NC_InAggFunc 0x0008 /* True if analyzing arguments to an agg func */
  17075. #define NC_HasAgg 0x0010 /* One or more aggregate functions seen */
  17076. #define NC_IdxExpr 0x0020 /* True if resolving columns of CREATE INDEX */
  17077. #define NC_VarSelect 0x0040 /* A correlated subquery has been seen */
  17078. #define NC_UEList 0x0080 /* True if uNC.pEList is used */
  17079. #define NC_UAggInfo 0x0100 /* True if uNC.pAggInfo is used */
  17080. #define NC_UUpsert 0x0200 /* True if uNC.pUpsert is used */
  17081. #define NC_MinMaxAgg 0x1000 /* min/max aggregates seen. See note above */
  17082. #define NC_Complex 0x2000 /* True if a function or subquery seen */
  17083. #define NC_AllowWin 0x4000 /* Window functions are allowed here */
  17084. #define NC_HasWin 0x8000 /* One or more window functions seen */
  17085. #define NC_IsDDL 0x10000 /* Resolving names in a CREATE statement */
  17086. /*
  17087. ** An instance of the following object describes a single ON CONFLICT
  17088. ** clause in an upsert.
  17089. **
  17090. ** The pUpsertTarget field is only set if the ON CONFLICT clause includes
  17091. ** conflict-target clause. (In "ON CONFLICT(a,b)" the "(a,b)" is the
  17092. ** conflict-target clause.) The pUpsertTargetWhere is the optional
  17093. ** WHERE clause used to identify partial unique indexes.
  17094. **
  17095. ** pUpsertSet is the list of column=expr terms of the UPDATE statement.
  17096. ** The pUpsertSet field is NULL for a ON CONFLICT DO NOTHING. The
  17097. ** pUpsertWhere is the WHERE clause for the UPDATE and is NULL if the
  17098. ** WHERE clause is omitted.
  17099. */
  17100. struct Upsert {
  17101. ExprList *pUpsertTarget; /* Optional description of conflicting index */
  17102. Expr *pUpsertTargetWhere; /* WHERE clause for partial index targets */
  17103. ExprList *pUpsertSet; /* The SET clause from an ON CONFLICT UPDATE */
  17104. Expr *pUpsertWhere; /* WHERE clause for the ON CONFLICT UPDATE */
  17105. /* The fields above comprise the parse tree for the upsert clause.
  17106. ** The fields below are used to transfer information from the INSERT
  17107. ** processing down into the UPDATE processing while generating code.
  17108. ** Upsert owns the memory allocated above, but not the memory below. */
  17109. Index *pUpsertIdx; /* Constraint that pUpsertTarget identifies */
  17110. SrcList *pUpsertSrc; /* Table to be updated */
  17111. int regData; /* First register holding array of VALUES */
  17112. int iDataCur; /* Index of the data cursor */
  17113. int iIdxCur; /* Index of the first index cursor */
  17114. };
  17115. /*
  17116. ** An instance of the following structure contains all information
  17117. ** needed to generate code for a single SELECT statement.
  17118. **
  17119. ** See the header comment on the computeLimitRegisters() routine for a
  17120. ** detailed description of the meaning of the iLimit and iOffset fields.
  17121. **
  17122. ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
  17123. ** These addresses must be stored so that we can go back and fill in
  17124. ** the P4_KEYINFO and P2 parameters later. Neither the KeyInfo nor
  17125. ** the number of columns in P2 can be computed at the same time
  17126. ** as the OP_OpenEphm instruction is coded because not
  17127. ** enough information about the compound query is known at that point.
  17128. ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
  17129. ** for the result set. The KeyInfo for addrOpenEphm[2] contains collating
  17130. ** sequences for the ORDER BY clause.
  17131. */
  17132. struct Select {
  17133. ExprList *pEList; /* The fields of the result */
  17134. u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
  17135. LogEst nSelectRow; /* Estimated number of result rows */
  17136. u32 selFlags; /* Various SF_* values */
  17137. int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */
  17138. u32 selId; /* Unique identifier number for this SELECT */
  17139. int addrOpenEphm[2]; /* OP_OpenEphem opcodes related to this select */
  17140. SrcList *pSrc; /* The FROM clause */
  17141. Expr *pWhere; /* The WHERE clause */
  17142. ExprList *pGroupBy; /* The GROUP BY clause */
  17143. Expr *pHaving; /* The HAVING clause */
  17144. ExprList *pOrderBy; /* The ORDER BY clause */
  17145. Select *pPrior; /* Prior select in a compound select statement */
  17146. Select *pNext; /* Next select to the left in a compound */
  17147. Expr *pLimit; /* LIMIT expression. NULL means not used. */
  17148. With *pWith; /* WITH clause attached to this select. Or NULL. */
  17149. #ifndef SQLITE_OMIT_WINDOWFUNC
  17150. Window *pWin; /* List of window functions */
  17151. Window *pWinDefn; /* List of named window definitions */
  17152. #endif
  17153. };
  17154. /*
  17155. ** Allowed values for Select.selFlags. The "SF" prefix stands for
  17156. ** "Select Flag".
  17157. **
  17158. ** Value constraints (all checked via assert())
  17159. ** SF_HasAgg == NC_HasAgg
  17160. ** SF_MinMaxAgg == NC_MinMaxAgg == SQLITE_FUNC_MINMAX
  17161. ** SF_FixedLimit == WHERE_USE_LIMIT
  17162. */
  17163. #define SF_Distinct 0x00001 /* Output should be DISTINCT */
  17164. #define SF_All 0x00002 /* Includes the ALL keyword */
  17165. #define SF_Resolved 0x00004 /* Identifiers have been resolved */
  17166. #define SF_Aggregate 0x00008 /* Contains agg functions or a GROUP BY */
  17167. #define SF_HasAgg 0x00010 /* Contains aggregate functions */
  17168. #define SF_UsesEphemeral 0x00020 /* Uses the OpenEphemeral opcode */
  17169. #define SF_Expanded 0x00040 /* sqlite3SelectExpand() called on this */
  17170. #define SF_HasTypeInfo 0x00080 /* FROM subqueries have Table metadata */
  17171. #define SF_Compound 0x00100 /* Part of a compound query */
  17172. #define SF_Values 0x00200 /* Synthesized from VALUES clause */
  17173. #define SF_MultiValue 0x00400 /* Single VALUES term with multiple rows */
  17174. #define SF_NestedFrom 0x00800 /* Part of a parenthesized FROM clause */
  17175. #define SF_MinMaxAgg 0x01000 /* Aggregate containing min() or max() */
  17176. #define SF_Recursive 0x02000 /* The recursive part of a recursive CTE */
  17177. #define SF_FixedLimit 0x04000 /* nSelectRow set by a constant LIMIT */
  17178. #define SF_MaybeConvert 0x08000 /* Need convertCompoundSelectToSubquery() */
  17179. #define SF_Converted 0x10000 /* By convertCompoundSelectToSubquery() */
  17180. #define SF_IncludeHidden 0x20000 /* Include hidden columns in output */
  17181. #define SF_ComplexResult 0x40000 /* Result contains subquery or function */
  17182. /*
  17183. ** The results of a SELECT can be distributed in several ways, as defined
  17184. ** by one of the following macros. The "SRT" prefix means "SELECT Result
  17185. ** Type".
  17186. **
  17187. ** SRT_Union Store results as a key in a temporary index
  17188. ** identified by pDest->iSDParm.
  17189. **
  17190. ** SRT_Except Remove results from the temporary index pDest->iSDParm.
  17191. **
  17192. ** SRT_Exists Store a 1 in memory cell pDest->iSDParm if the result
  17193. ** set is not empty.
  17194. **
  17195. ** SRT_Discard Throw the results away. This is used by SELECT
  17196. ** statements within triggers whose only purpose is
  17197. ** the side-effects of functions.
  17198. **
  17199. ** All of the above are free to ignore their ORDER BY clause. Those that
  17200. ** follow must honor the ORDER BY clause.
  17201. **
  17202. ** SRT_Output Generate a row of output (using the OP_ResultRow
  17203. ** opcode) for each row in the result set.
  17204. **
  17205. ** SRT_Mem Only valid if the result is a single column.
  17206. ** Store the first column of the first result row
  17207. ** in register pDest->iSDParm then abandon the rest
  17208. ** of the query. This destination implies "LIMIT 1".
  17209. **
  17210. ** SRT_Set The result must be a single column. Store each
  17211. ** row of result as the key in table pDest->iSDParm.
  17212. ** Apply the affinity pDest->affSdst before storing
  17213. ** results. Used to implement "IN (SELECT ...)".
  17214. **
  17215. ** SRT_EphemTab Create an temporary table pDest->iSDParm and store
  17216. ** the result there. The cursor is left open after
  17217. ** returning. This is like SRT_Table except that
  17218. ** this destination uses OP_OpenEphemeral to create
  17219. ** the table first.
  17220. **
  17221. ** SRT_Coroutine Generate a co-routine that returns a new row of
  17222. ** results each time it is invoked. The entry point
  17223. ** of the co-routine is stored in register pDest->iSDParm
  17224. ** and the result row is stored in pDest->nDest registers
  17225. ** starting with pDest->iSdst.
  17226. **
  17227. ** SRT_Table Store results in temporary table pDest->iSDParm.
  17228. ** SRT_Fifo This is like SRT_EphemTab except that the table
  17229. ** is assumed to already be open. SRT_Fifo has
  17230. ** the additional property of being able to ignore
  17231. ** the ORDER BY clause.
  17232. **
  17233. ** SRT_DistFifo Store results in a temporary table pDest->iSDParm.
  17234. ** But also use temporary table pDest->iSDParm+1 as
  17235. ** a record of all prior results and ignore any duplicate
  17236. ** rows. Name means: "Distinct Fifo".
  17237. **
  17238. ** SRT_Queue Store results in priority queue pDest->iSDParm (really
  17239. ** an index). Append a sequence number so that all entries
  17240. ** are distinct.
  17241. **
  17242. ** SRT_DistQueue Store results in priority queue pDest->iSDParm only if
  17243. ** the same record has never been stored before. The
  17244. ** index at pDest->iSDParm+1 hold all prior stores.
  17245. */
  17246. #define SRT_Union 1 /* Store result as keys in an index */
  17247. #define SRT_Except 2 /* Remove result from a UNION index */
  17248. #define SRT_Exists 3 /* Store 1 if the result is not empty */
  17249. #define SRT_Discard 4 /* Do not save the results anywhere */
  17250. #define SRT_Fifo 5 /* Store result as data with an automatic rowid */
  17251. #define SRT_DistFifo 6 /* Like SRT_Fifo, but unique results only */
  17252. #define SRT_Queue 7 /* Store result in an queue */
  17253. #define SRT_DistQueue 8 /* Like SRT_Queue, but unique results only */
  17254. /* The ORDER BY clause is ignored for all of the above */
  17255. #define IgnorableOrderby(X) ((X->eDest)<=SRT_DistQueue)
  17256. #define SRT_Output 9 /* Output each row of result */
  17257. #define SRT_Mem 10 /* Store result in a memory cell */
  17258. #define SRT_Set 11 /* Store results as keys in an index */
  17259. #define SRT_EphemTab 12 /* Create transient tab and store like SRT_Table */
  17260. #define SRT_Coroutine 13 /* Generate a single row of result */
  17261. #define SRT_Table 14 /* Store result as data with an automatic rowid */
  17262. /*
  17263. ** An instance of this object describes where to put of the results of
  17264. ** a SELECT statement.
  17265. */
  17266. struct SelectDest {
  17267. u8 eDest; /* How to dispose of the results. On of SRT_* above. */
  17268. int iSDParm; /* A parameter used by the eDest disposal method */
  17269. int iSdst; /* Base register where results are written */
  17270. int nSdst; /* Number of registers allocated */
  17271. char *zAffSdst; /* Affinity used when eDest==SRT_Set */
  17272. ExprList *pOrderBy; /* Key columns for SRT_Queue and SRT_DistQueue */
  17273. };
  17274. /*
  17275. ** During code generation of statements that do inserts into AUTOINCREMENT
  17276. ** tables, the following information is attached to the Table.u.autoInc.p
  17277. ** pointer of each autoincrement table to record some side information that
  17278. ** the code generator needs. We have to keep per-table autoincrement
  17279. ** information in case inserts are done within triggers. Triggers do not
  17280. ** normally coordinate their activities, but we do need to coordinate the
  17281. ** loading and saving of autoincrement information.
  17282. */
  17283. struct AutoincInfo {
  17284. AutoincInfo *pNext; /* Next info block in a list of them all */
  17285. Table *pTab; /* Table this info block refers to */
  17286. int iDb; /* Index in sqlite3.aDb[] of database holding pTab */
  17287. int regCtr; /* Memory register holding the rowid counter */
  17288. };
  17289. /*
  17290. ** At least one instance of the following structure is created for each
  17291. ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
  17292. ** statement. All such objects are stored in the linked list headed at
  17293. ** Parse.pTriggerPrg and deleted once statement compilation has been
  17294. ** completed.
  17295. **
  17296. ** A Vdbe sub-program that implements the body and WHEN clause of trigger
  17297. ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
  17298. ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
  17299. ** The Parse.pTriggerPrg list never contains two entries with the same
  17300. ** values for both pTrigger and orconf.
  17301. **
  17302. ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
  17303. ** accessed (or set to 0 for triggers fired as a result of INSERT
  17304. ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
  17305. ** a mask of new.* columns used by the program.
  17306. */
  17307. struct TriggerPrg {
  17308. Trigger *pTrigger; /* Trigger this program was coded from */
  17309. TriggerPrg *pNext; /* Next entry in Parse.pTriggerPrg list */
  17310. SubProgram *pProgram; /* Program implementing pTrigger/orconf */
  17311. int orconf; /* Default ON CONFLICT policy */
  17312. u32 aColmask[2]; /* Masks of old.*, new.* columns accessed */
  17313. };
  17314. /*
  17315. ** The yDbMask datatype for the bitmask of all attached databases.
  17316. */
  17317. #if SQLITE_MAX_ATTACHED>30
  17318. typedef unsigned char yDbMask[(SQLITE_MAX_ATTACHED+9)/8];
  17319. # define DbMaskTest(M,I) (((M)[(I)/8]&(1<<((I)&7)))!=0)
  17320. # define DbMaskZero(M) memset((M),0,sizeof(M))
  17321. # define DbMaskSet(M,I) (M)[(I)/8]|=(1<<((I)&7))
  17322. # define DbMaskAllZero(M) sqlite3DbMaskAllZero(M)
  17323. # define DbMaskNonZero(M) (sqlite3DbMaskAllZero(M)==0)
  17324. #else
  17325. typedef unsigned int yDbMask;
  17326. # define DbMaskTest(M,I) (((M)&(((yDbMask)1)<<(I)))!=0)
  17327. # define DbMaskZero(M) (M)=0
  17328. # define DbMaskSet(M,I) (M)|=(((yDbMask)1)<<(I))
  17329. # define DbMaskAllZero(M) (M)==0
  17330. # define DbMaskNonZero(M) (M)!=0
  17331. #endif
  17332. /*
  17333. ** An SQL parser context. A copy of this structure is passed through
  17334. ** the parser and down into all the parser action routine in order to
  17335. ** carry around information that is global to the entire parse.
  17336. **
  17337. ** The structure is divided into two parts. When the parser and code
  17338. ** generate call themselves recursively, the first part of the structure
  17339. ** is constant but the second part is reset at the beginning and end of
  17340. ** each recursion.
  17341. **
  17342. ** The nTableLock and aTableLock variables are only used if the shared-cache
  17343. ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
  17344. ** used to store the set of table-locks required by the statement being
  17345. ** compiled. Function sqlite3TableLock() is used to add entries to the
  17346. ** list.
  17347. */
  17348. struct Parse {
  17349. sqlite3 *db; /* The main database structure */
  17350. char *zErrMsg; /* An error message */
  17351. Vdbe *pVdbe; /* An engine for executing database bytecode */
  17352. int rc; /* Return code from execution */
  17353. u8 colNamesSet; /* TRUE after OP_ColumnName has been issued to pVdbe */
  17354. u8 checkSchema; /* Causes schema cookie check after an error */
  17355. u8 nested; /* Number of nested calls to the parser/code generator */
  17356. u8 nTempReg; /* Number of temporary registers in aTempReg[] */
  17357. u8 isMultiWrite; /* True if statement may modify/insert multiple rows */
  17358. u8 mayAbort; /* True if statement may throw an ABORT exception */
  17359. u8 hasCompound; /* Need to invoke convertCompoundSelectToSubquery() */
  17360. u8 okConstFactor; /* OK to factor out constants */
  17361. u8 disableLookaside; /* Number of times lookaside has been disabled */
  17362. u8 disableVtab; /* Disable all virtual tables for this parse */
  17363. int nRangeReg; /* Size of the temporary register block */
  17364. int iRangeReg; /* First register in temporary register block */
  17365. int nErr; /* Number of errors seen */
  17366. int nTab; /* Number of previously allocated VDBE cursors */
  17367. int nMem; /* Number of memory cells used so far */
  17368. int szOpAlloc; /* Bytes of memory space allocated for Vdbe.aOp[] */
  17369. int iSelfTab; /* Table associated with an index on expr, or negative
  17370. ** of the base register during check-constraint eval */
  17371. int nLabel; /* The *negative* of the number of labels used */
  17372. int nLabelAlloc; /* Number of slots in aLabel */
  17373. int *aLabel; /* Space to hold the labels */
  17374. ExprList *pConstExpr;/* Constant expressions */
  17375. Token constraintName;/* Name of the constraint currently being parsed */
  17376. yDbMask writeMask; /* Start a write transaction on these databases */
  17377. yDbMask cookieMask; /* Bitmask of schema verified databases */
  17378. int regRowid; /* Register holding rowid of CREATE TABLE entry */
  17379. int regRoot; /* Register holding root page number for new objects */
  17380. int nMaxArg; /* Max args passed to user function by sub-program */
  17381. int nSelect; /* Number of SELECT stmts. Counter for Select.selId */
  17382. #ifndef SQLITE_OMIT_SHARED_CACHE
  17383. int nTableLock; /* Number of locks in aTableLock */
  17384. TableLock *aTableLock; /* Required table locks for shared-cache mode */
  17385. #endif
  17386. AutoincInfo *pAinc; /* Information about AUTOINCREMENT counters */
  17387. Parse *pToplevel; /* Parse structure for main program (or NULL) */
  17388. Table *pTriggerTab; /* Table triggers are being coded for */
  17389. Parse *pParentParse; /* Parent parser if this parser is nested */
  17390. int addrCrTab; /* Address of OP_CreateBtree opcode on CREATE TABLE */
  17391. u32 nQueryLoop; /* Est number of iterations of a query (10*log2(N)) */
  17392. u32 oldmask; /* Mask of old.* columns referenced */
  17393. u32 newmask; /* Mask of new.* columns referenced */
  17394. u8 eTriggerOp; /* TK_UPDATE, TK_INSERT or TK_DELETE */
  17395. u8 eOrconf; /* Default ON CONFLICT policy for trigger steps */
  17396. u8 disableTriggers; /* True to disable triggers */
  17397. /**************************************************************************
  17398. ** Fields above must be initialized to zero. The fields that follow,
  17399. ** down to the beginning of the recursive section, do not need to be
  17400. ** initialized as they will be set before being used. The boundary is
  17401. ** determined by offsetof(Parse,aTempReg).
  17402. **************************************************************************/
  17403. int aTempReg[8]; /* Holding area for temporary registers */
  17404. Token sNameToken; /* Token with unqualified schema object name */
  17405. /************************************************************************
  17406. ** Above is constant between recursions. Below is reset before and after
  17407. ** each recursion. The boundary between these two regions is determined
  17408. ** using offsetof(Parse,sLastToken) so the sLastToken field must be the
  17409. ** first field in the recursive region.
  17410. ************************************************************************/
  17411. Token sLastToken; /* The last token parsed */
  17412. ynVar nVar; /* Number of '?' variables seen in the SQL so far */
  17413. u8 iPkSortOrder; /* ASC or DESC for INTEGER PRIMARY KEY */
  17414. u8 explain; /* True if the EXPLAIN flag is found on the query */
  17415. #if !(defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_OMIT_ALTERTABLE))
  17416. u8 eParseMode; /* PARSE_MODE_XXX constant */
  17417. #endif
  17418. #ifndef SQLITE_OMIT_VIRTUALTABLE
  17419. int nVtabLock; /* Number of virtual tables to lock */
  17420. #endif
  17421. int nHeight; /* Expression tree height of current sub-select */
  17422. #ifndef SQLITE_OMIT_EXPLAIN
  17423. int addrExplain; /* Address of current OP_Explain opcode */
  17424. #endif
  17425. VList *pVList; /* Mapping between variable names and numbers */
  17426. Vdbe *pReprepare; /* VM being reprepared (sqlite3Reprepare()) */
  17427. const char *zTail; /* All SQL text past the last semicolon parsed */
  17428. Table *pNewTable; /* A table being constructed by CREATE TABLE */
  17429. Index *pNewIndex; /* An index being constructed by CREATE INDEX.
  17430. ** Also used to hold redundant UNIQUE constraints
  17431. ** during a RENAME COLUMN */
  17432. Trigger *pNewTrigger; /* Trigger under construct by a CREATE TRIGGER */
  17433. const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
  17434. #ifndef SQLITE_OMIT_VIRTUALTABLE
  17435. Token sArg; /* Complete text of a module argument */
  17436. Table **apVtabLock; /* Pointer to virtual tables needing locking */
  17437. #endif
  17438. Table *pZombieTab; /* List of Table objects to delete after code gen */
  17439. TriggerPrg *pTriggerPrg; /* Linked list of coded triggers */
  17440. With *pWith; /* Current WITH clause, or NULL */
  17441. With *pWithToFree; /* Free this WITH object at the end of the parse */
  17442. #ifndef SQLITE_OMIT_ALTERTABLE
  17443. RenameToken *pRename; /* Tokens subject to renaming by ALTER TABLE */
  17444. #endif
  17445. };
  17446. #define PARSE_MODE_NORMAL 0
  17447. #define PARSE_MODE_DECLARE_VTAB 1
  17448. #define PARSE_MODE_RENAME_COLUMN 2
  17449. #define PARSE_MODE_RENAME_TABLE 3
  17450. /*
  17451. ** Sizes and pointers of various parts of the Parse object.
  17452. */
  17453. #define PARSE_HDR_SZ offsetof(Parse,aTempReg) /* Recursive part w/o aColCache*/
  17454. #define PARSE_RECURSE_SZ offsetof(Parse,sLastToken) /* Recursive part */
  17455. #define PARSE_TAIL_SZ (sizeof(Parse)-PARSE_RECURSE_SZ) /* Non-recursive part */
  17456. #define PARSE_TAIL(X) (((char*)(X))+PARSE_RECURSE_SZ) /* Pointer to tail */
  17457. /*
  17458. ** Return true if currently inside an sqlite3_declare_vtab() call.
  17459. */
  17460. #ifdef SQLITE_OMIT_VIRTUALTABLE
  17461. #define IN_DECLARE_VTAB 0
  17462. #else
  17463. #define IN_DECLARE_VTAB (pParse->eParseMode==PARSE_MODE_DECLARE_VTAB)
  17464. #endif
  17465. #if defined(SQLITE_OMIT_ALTERTABLE)
  17466. #define IN_RENAME_OBJECT 0
  17467. #else
  17468. #define IN_RENAME_OBJECT (pParse->eParseMode>=PARSE_MODE_RENAME_COLUMN)
  17469. #endif
  17470. #if defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_OMIT_ALTERTABLE)
  17471. #define IN_SPECIAL_PARSE 0
  17472. #else
  17473. #define IN_SPECIAL_PARSE (pParse->eParseMode!=PARSE_MODE_NORMAL)
  17474. #endif
  17475. /*
  17476. ** An instance of the following structure can be declared on a stack and used
  17477. ** to save the Parse.zAuthContext value so that it can be restored later.
  17478. */
  17479. struct AuthContext {
  17480. const char *zAuthContext; /* Put saved Parse.zAuthContext here */
  17481. Parse *pParse; /* The Parse structure */
  17482. };
  17483. /*
  17484. ** Bitfield flags for P5 value in various opcodes.
  17485. **
  17486. ** Value constraints (enforced via assert()):
  17487. ** OPFLAG_LENGTHARG == SQLITE_FUNC_LENGTH
  17488. ** OPFLAG_TYPEOFARG == SQLITE_FUNC_TYPEOF
  17489. ** OPFLAG_BULKCSR == BTREE_BULKLOAD
  17490. ** OPFLAG_SEEKEQ == BTREE_SEEK_EQ
  17491. ** OPFLAG_FORDELETE == BTREE_FORDELETE
  17492. ** OPFLAG_SAVEPOSITION == BTREE_SAVEPOSITION
  17493. ** OPFLAG_AUXDELETE == BTREE_AUXDELETE
  17494. */
  17495. #define OPFLAG_NCHANGE 0x01 /* OP_Insert: Set to update db->nChange */
  17496. /* Also used in P2 (not P5) of OP_Delete */
  17497. #define OPFLAG_NOCHNG 0x01 /* OP_VColumn nochange for UPDATE */
  17498. #define OPFLAG_EPHEM 0x01 /* OP_Column: Ephemeral output is ok */
  17499. #define OPFLAG_LASTROWID 0x20 /* Set to update db->lastRowid */
  17500. #define OPFLAG_ISUPDATE 0x04 /* This OP_Insert is an sql UPDATE */
  17501. #define OPFLAG_APPEND 0x08 /* This is likely to be an append */
  17502. #define OPFLAG_USESEEKRESULT 0x10 /* Try to avoid a seek in BtreeInsert() */
  17503. #define OPFLAG_ISNOOP 0x40 /* OP_Delete does pre-update-hook only */
  17504. #define OPFLAG_LENGTHARG 0x40 /* OP_Column only used for length() */
  17505. #define OPFLAG_TYPEOFARG 0x80 /* OP_Column only used for typeof() */
  17506. #define OPFLAG_BULKCSR 0x01 /* OP_Open** used to open bulk cursor */
  17507. #define OPFLAG_SEEKEQ 0x02 /* OP_Open** cursor uses EQ seek only */
  17508. #define OPFLAG_FORDELETE 0x08 /* OP_Open should use BTREE_FORDELETE */
  17509. #define OPFLAG_P2ISREG 0x10 /* P2 to OP_Open** is a register number */
  17510. #define OPFLAG_PERMUTE 0x01 /* OP_Compare: use the permutation */
  17511. #define OPFLAG_SAVEPOSITION 0x02 /* OP_Delete/Insert: save cursor pos */
  17512. #define OPFLAG_AUXDELETE 0x04 /* OP_Delete: index in a DELETE op */
  17513. #define OPFLAG_NOCHNG_MAGIC 0x6d /* OP_MakeRecord: serialtype 10 is ok */
  17514. /*
  17515. * Each trigger present in the database schema is stored as an instance of
  17516. * struct Trigger.
  17517. *
  17518. * Pointers to instances of struct Trigger are stored in two ways.
  17519. * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
  17520. * database). This allows Trigger structures to be retrieved by name.
  17521. * 2. All triggers associated with a single table form a linked list, using the
  17522. * pNext member of struct Trigger. A pointer to the first element of the
  17523. * linked list is stored as the "pTrigger" member of the associated
  17524. * struct Table.
  17525. *
  17526. * The "step_list" member points to the first element of a linked list
  17527. * containing the SQL statements specified as the trigger program.
  17528. */
  17529. struct Trigger {
  17530. char *zName; /* The name of the trigger */
  17531. char *table; /* The table or view to which the trigger applies */
  17532. u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT */
  17533. u8 tr_tm; /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
  17534. Expr *pWhen; /* The WHEN clause of the expression (may be NULL) */
  17535. IdList *pColumns; /* If this is an UPDATE OF <column-list> trigger,
  17536. the <column-list> is stored here */
  17537. Schema *pSchema; /* Schema containing the trigger */
  17538. Schema *pTabSchema; /* Schema containing the table */
  17539. TriggerStep *step_list; /* Link list of trigger program steps */
  17540. Trigger *pNext; /* Next trigger associated with the table */
  17541. };
  17542. /*
  17543. ** A trigger is either a BEFORE or an AFTER trigger. The following constants
  17544. ** determine which.
  17545. **
  17546. ** If there are multiple triggers, you might of some BEFORE and some AFTER.
  17547. ** In that cases, the constants below can be ORed together.
  17548. */
  17549. #define TRIGGER_BEFORE 1
  17550. #define TRIGGER_AFTER 2
  17551. /*
  17552. * An instance of struct TriggerStep is used to store a single SQL statement
  17553. * that is a part of a trigger-program.
  17554. *
  17555. * Instances of struct TriggerStep are stored in a singly linked list (linked
  17556. * using the "pNext" member) referenced by the "step_list" member of the
  17557. * associated struct Trigger instance. The first element of the linked list is
  17558. * the first step of the trigger-program.
  17559. *
  17560. * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
  17561. * "SELECT" statement. The meanings of the other members is determined by the
  17562. * value of "op" as follows:
  17563. *
  17564. * (op == TK_INSERT)
  17565. * orconf -> stores the ON CONFLICT algorithm
  17566. * pSelect -> If this is an INSERT INTO ... SELECT ... statement, then
  17567. * this stores a pointer to the SELECT statement. Otherwise NULL.
  17568. * zTarget -> Dequoted name of the table to insert into.
  17569. * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
  17570. * this stores values to be inserted. Otherwise NULL.
  17571. * pIdList -> If this is an INSERT INTO ... (<column-names>) VALUES ...
  17572. * statement, then this stores the column-names to be
  17573. * inserted into.
  17574. *
  17575. * (op == TK_DELETE)
  17576. * zTarget -> Dequoted name of the table to delete from.
  17577. * pWhere -> The WHERE clause of the DELETE statement if one is specified.
  17578. * Otherwise NULL.
  17579. *
  17580. * (op == TK_UPDATE)
  17581. * zTarget -> Dequoted name of the table to update.
  17582. * pWhere -> The WHERE clause of the UPDATE statement if one is specified.
  17583. * Otherwise NULL.
  17584. * pExprList -> A list of the columns to update and the expressions to update
  17585. * them to. See sqlite3Update() documentation of "pChanges"
  17586. * argument.
  17587. *
  17588. */
  17589. struct TriggerStep {
  17590. u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
  17591. u8 orconf; /* OE_Rollback etc. */
  17592. Trigger *pTrig; /* The trigger that this step is a part of */
  17593. Select *pSelect; /* SELECT statement or RHS of INSERT INTO SELECT ... */
  17594. char *zTarget; /* Target table for DELETE, UPDATE, INSERT */
  17595. Expr *pWhere; /* The WHERE clause for DELETE or UPDATE steps */
  17596. ExprList *pExprList; /* SET clause for UPDATE */
  17597. IdList *pIdList; /* Column names for INSERT */
  17598. Upsert *pUpsert; /* Upsert clauses on an INSERT */
  17599. char *zSpan; /* Original SQL text of this command */
  17600. TriggerStep *pNext; /* Next in the link-list */
  17601. TriggerStep *pLast; /* Last element in link-list. Valid for 1st elem only */
  17602. };
  17603. /*
  17604. ** The following structure contains information used by the sqliteFix...
  17605. ** routines as they walk the parse tree to make database references
  17606. ** explicit.
  17607. */
  17608. typedef struct DbFixer DbFixer;
  17609. struct DbFixer {
  17610. Parse *pParse; /* The parsing context. Error messages written here */
  17611. Schema *pSchema; /* Fix items to this schema */
  17612. int bVarOnly; /* Check for variable references only */
  17613. const char *zDb; /* Make sure all objects are contained in this database */
  17614. const char *zType; /* Type of the container - used for error messages */
  17615. const Token *pName; /* Name of the container - used for error messages */
  17616. };
  17617. /*
  17618. ** An objected used to accumulate the text of a string where we
  17619. ** do not necessarily know how big the string will be in the end.
  17620. */
  17621. struct sqlite3_str {
  17622. sqlite3 *db; /* Optional database for lookaside. Can be NULL */
  17623. char *zText; /* The string collected so far */
  17624. u32 nAlloc; /* Amount of space allocated in zText */
  17625. u32 mxAlloc; /* Maximum allowed allocation. 0 for no malloc usage */
  17626. u32 nChar; /* Length of the string so far */
  17627. u8 accError; /* SQLITE_NOMEM or SQLITE_TOOBIG */
  17628. u8 printfFlags; /* SQLITE_PRINTF flags below */
  17629. };
  17630. #define SQLITE_PRINTF_INTERNAL 0x01 /* Internal-use-only converters allowed */
  17631. #define SQLITE_PRINTF_SQLFUNC 0x02 /* SQL function arguments to VXPrintf */
  17632. #define SQLITE_PRINTF_MALLOCED 0x04 /* True if xText is allocated space */
  17633. #define isMalloced(X) (((X)->printfFlags & SQLITE_PRINTF_MALLOCED)!=0)
  17634. /*
  17635. ** A pointer to this structure is used to communicate information
  17636. ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
  17637. */
  17638. typedef struct {
  17639. sqlite3 *db; /* The database being initialized */
  17640. char **pzErrMsg; /* Error message stored here */
  17641. int iDb; /* 0 for main database. 1 for TEMP, 2.. for ATTACHed */
  17642. int rc; /* Result code stored here */
  17643. u32 mInitFlags; /* Flags controlling error messages */
  17644. u32 nInitRow; /* Number of rows processed */
  17645. } InitData;
  17646. /*
  17647. ** Allowed values for mInitFlags
  17648. */
  17649. #define INITFLAG_AlterTable 0x0001 /* This is a reparse after ALTER TABLE */
  17650. /*
  17651. ** Structure containing global configuration data for the SQLite library.
  17652. **
  17653. ** This structure also contains some state information.
  17654. */
  17655. struct Sqlite3Config {
  17656. int bMemstat; /* True to enable memory status */
  17657. int bCoreMutex; /* True to enable core mutexing */
  17658. int bFullMutex; /* True to enable full mutexing */
  17659. int bOpenUri; /* True to interpret filenames as URIs */
  17660. int bUseCis; /* Use covering indices for full-scans */
  17661. int bSmallMalloc; /* Avoid large memory allocations if true */
  17662. int mxStrlen; /* Maximum string length */
  17663. int neverCorrupt; /* Database is always well-formed */
  17664. int szLookaside; /* Default lookaside buffer size */
  17665. int nLookaside; /* Default lookaside buffer count */
  17666. int nStmtSpill; /* Stmt-journal spill-to-disk threshold */
  17667. sqlite3_mem_methods m; /* Low-level memory allocation interface */
  17668. sqlite3_mutex_methods mutex; /* Low-level mutex interface */
  17669. sqlite3_pcache_methods2 pcache2; /* Low-level page-cache interface */
  17670. void *pHeap; /* Heap storage space */
  17671. int nHeap; /* Size of pHeap[] */
  17672. int mnReq, mxReq; /* Min and max heap requests sizes */
  17673. sqlite3_int64 szMmap; /* mmap() space per open file */
  17674. sqlite3_int64 mxMmap; /* Maximum value for szMmap */
  17675. void *pPage; /* Page cache memory */
  17676. int szPage; /* Size of each page in pPage[] */
  17677. int nPage; /* Number of pages in pPage[] */
  17678. int mxParserStack; /* maximum depth of the parser stack */
  17679. int sharedCacheEnabled; /* true if shared-cache mode enabled */
  17680. u32 szPma; /* Maximum Sorter PMA size */
  17681. /* The above might be initialized to non-zero. The following need to always
  17682. ** initially be zero, however. */
  17683. int isInit; /* True after initialization has finished */
  17684. int inProgress; /* True while initialization in progress */
  17685. int isMutexInit; /* True after mutexes are initialized */
  17686. int isMallocInit; /* True after malloc is initialized */
  17687. int isPCacheInit; /* True after malloc is initialized */
  17688. int nRefInitMutex; /* Number of users of pInitMutex */
  17689. sqlite3_mutex *pInitMutex; /* Mutex used by sqlite3_initialize() */
  17690. void (*xLog)(void*,int,const char*); /* Function for logging */
  17691. void *pLogArg; /* First argument to xLog() */
  17692. #ifdef SQLITE_ENABLE_SQLLOG
  17693. void(*xSqllog)(void*,sqlite3*,const char*, int);
  17694. void *pSqllogArg;
  17695. #endif
  17696. #ifdef SQLITE_VDBE_COVERAGE
  17697. /* The following callback (if not NULL) is invoked on every VDBE branch
  17698. ** operation. Set the callback using SQLITE_TESTCTRL_VDBE_COVERAGE.
  17699. */
  17700. void (*xVdbeBranch)(void*,unsigned iSrcLine,u8 eThis,u8 eMx); /* Callback */
  17701. void *pVdbeBranchArg; /* 1st argument */
  17702. #endif
  17703. #ifdef SQLITE_ENABLE_DESERIALIZE
  17704. sqlite3_int64 mxMemdbSize; /* Default max memdb size */
  17705. #endif
  17706. #ifndef SQLITE_UNTESTABLE
  17707. int (*xTestCallback)(int); /* Invoked by sqlite3FaultSim() */
  17708. #endif
  17709. int bLocaltimeFault; /* True to fail localtime() calls */
  17710. int bInternalFunctions; /* Internal SQL functions are visible */
  17711. int iOnceResetThreshold; /* When to reset OP_Once counters */
  17712. u32 szSorterRef; /* Min size in bytes to use sorter-refs */
  17713. };
  17714. /*
  17715. ** This macro is used inside of assert() statements to indicate that
  17716. ** the assert is only valid on a well-formed database. Instead of:
  17717. **
  17718. ** assert( X );
  17719. **
  17720. ** One writes:
  17721. **
  17722. ** assert( X || CORRUPT_DB );
  17723. **
  17724. ** CORRUPT_DB is true during normal operation. CORRUPT_DB does not indicate
  17725. ** that the database is definitely corrupt, only that it might be corrupt.
  17726. ** For most test cases, CORRUPT_DB is set to false using a special
  17727. ** sqlite3_test_control(). This enables assert() statements to prove
  17728. ** things that are always true for well-formed databases.
  17729. */
  17730. #define CORRUPT_DB (sqlite3Config.neverCorrupt==0)
  17731. /*
  17732. ** Context pointer passed down through the tree-walk.
  17733. */
  17734. struct Walker {
  17735. Parse *pParse; /* Parser context. */
  17736. int (*xExprCallback)(Walker*, Expr*); /* Callback for expressions */
  17737. int (*xSelectCallback)(Walker*,Select*); /* Callback for SELECTs */
  17738. void (*xSelectCallback2)(Walker*,Select*);/* Second callback for SELECTs */
  17739. int walkerDepth; /* Number of subqueries */
  17740. u8 eCode; /* A small processing code */
  17741. union { /* Extra data for callback */
  17742. NameContext *pNC; /* Naming context */
  17743. int n; /* A counter */
  17744. int iCur; /* A cursor number */
  17745. SrcList *pSrcList; /* FROM clause */
  17746. struct SrcCount *pSrcCount; /* Counting column references */
  17747. struct CCurHint *pCCurHint; /* Used by codeCursorHint() */
  17748. int *aiCol; /* array of column indexes */
  17749. struct IdxCover *pIdxCover; /* Check for index coverage */
  17750. struct IdxExprTrans *pIdxTrans; /* Convert idxed expr to column */
  17751. ExprList *pGroupBy; /* GROUP BY clause */
  17752. Select *pSelect; /* HAVING to WHERE clause ctx */
  17753. struct WindowRewrite *pRewrite; /* Window rewrite context */
  17754. struct WhereConst *pConst; /* WHERE clause constants */
  17755. struct RenameCtx *pRename; /* RENAME COLUMN context */
  17756. } u;
  17757. };
  17758. /* Forward declarations */
  17759. SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
  17760. SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
  17761. SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
  17762. SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
  17763. SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
  17764. SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker*, Expr*);
  17765. SQLITE_PRIVATE int sqlite3SelectWalkNoop(Walker*, Select*);
  17766. SQLITE_PRIVATE int sqlite3SelectWalkFail(Walker*, Select*);
  17767. #ifdef SQLITE_DEBUG
  17768. SQLITE_PRIVATE void sqlite3SelectWalkAssert2(Walker*, Select*);
  17769. #endif
  17770. /*
  17771. ** Return code from the parse-tree walking primitives and their
  17772. ** callbacks.
  17773. */
  17774. #define WRC_Continue 0 /* Continue down into children */
  17775. #define WRC_Prune 1 /* Omit children but continue walking siblings */
  17776. #define WRC_Abort 2 /* Abandon the tree walk */
  17777. /*
  17778. ** An instance of this structure represents a set of one or more CTEs
  17779. ** (common table expressions) created by a single WITH clause.
  17780. */
  17781. struct With {
  17782. int nCte; /* Number of CTEs in the WITH clause */
  17783. With *pOuter; /* Containing WITH clause, or NULL */
  17784. struct Cte { /* For each CTE in the WITH clause.... */
  17785. char *zName; /* Name of this CTE */
  17786. ExprList *pCols; /* List of explicit column names, or NULL */
  17787. Select *pSelect; /* The definition of this CTE */
  17788. const char *zCteErr; /* Error message for circular references */
  17789. } a[1];
  17790. };
  17791. #ifdef SQLITE_DEBUG
  17792. /*
  17793. ** An instance of the TreeView object is used for printing the content of
  17794. ** data structures on sqlite3DebugPrintf() using a tree-like view.
  17795. */
  17796. struct TreeView {
  17797. int iLevel; /* Which level of the tree we are on */
  17798. u8 bLine[100]; /* Draw vertical in column i if bLine[i] is true */
  17799. };
  17800. #endif /* SQLITE_DEBUG */
  17801. /*
  17802. ** This object is used in various ways, all related to window functions
  17803. **
  17804. ** (1) A single instance of this structure is attached to the
  17805. ** the Expr.pWin field for each window function in an expression tree.
  17806. ** This object holds the information contained in the OVER clause,
  17807. ** plus additional fields used during code generation.
  17808. **
  17809. ** (2) All window functions in a single SELECT form a linked-list
  17810. ** attached to Select.pWin. The Window.pFunc and Window.pExpr
  17811. ** fields point back to the expression that is the window function.
  17812. **
  17813. ** (3) The terms of the WINDOW clause of a SELECT are instances of this
  17814. ** object on a linked list attached to Select.pWinDefn.
  17815. **
  17816. ** The uses (1) and (2) are really the same Window object that just happens
  17817. ** to be accessible in two different ways. Use case (3) are separate objects.
  17818. */
  17819. struct Window {
  17820. char *zName; /* Name of window (may be NULL) */
  17821. char *zBase; /* Name of base window for chaining (may be NULL) */
  17822. ExprList *pPartition; /* PARTITION BY clause */
  17823. ExprList *pOrderBy; /* ORDER BY clause */
  17824. u8 eFrmType; /* TK_RANGE, TK_GROUPS, TK_ROWS, or 0 */
  17825. u8 eStart; /* UNBOUNDED, CURRENT, PRECEDING or FOLLOWING */
  17826. u8 eEnd; /* UNBOUNDED, CURRENT, PRECEDING or FOLLOWING */
  17827. u8 bImplicitFrame; /* True if frame was implicitly specified */
  17828. u8 eExclude; /* TK_NO, TK_CURRENT, TK_TIES, TK_GROUP, or 0 */
  17829. Expr *pStart; /* Expression for "<expr> PRECEDING" */
  17830. Expr *pEnd; /* Expression for "<expr> FOLLOWING" */
  17831. Window *pNextWin; /* Next window function belonging to this SELECT */
  17832. Expr *pFilter; /* The FILTER expression */
  17833. FuncDef *pFunc; /* The function */
  17834. int iEphCsr; /* Partition buffer or Peer buffer */
  17835. int regAccum;
  17836. int regResult;
  17837. int csrApp; /* Function cursor (used by min/max) */
  17838. int regApp; /* Function register (also used by min/max) */
  17839. int regPart; /* Array of registers for PARTITION BY values */
  17840. Expr *pOwner; /* Expression object this window is attached to */
  17841. int nBufferCol; /* Number of columns in buffer table */
  17842. int iArgCol; /* Offset of first argument for this function */
  17843. int regOne; /* Register containing constant value 1 */
  17844. int regStartRowid;
  17845. int regEndRowid;
  17846. };
  17847. #ifndef SQLITE_OMIT_WINDOWFUNC
  17848. SQLITE_PRIVATE void sqlite3WindowDelete(sqlite3*, Window*);
  17849. SQLITE_PRIVATE void sqlite3WindowListDelete(sqlite3 *db, Window *p);
  17850. SQLITE_PRIVATE Window *sqlite3WindowAlloc(Parse*, int, int, Expr*, int , Expr*, u8);
  17851. SQLITE_PRIVATE void sqlite3WindowAttach(Parse*, Expr*, Window*);
  17852. SQLITE_PRIVATE int sqlite3WindowCompare(Parse*, Window*, Window*);
  17853. SQLITE_PRIVATE void sqlite3WindowCodeInit(Parse*, Window*);
  17854. SQLITE_PRIVATE void sqlite3WindowCodeStep(Parse*, Select*, WhereInfo*, int, int);
  17855. SQLITE_PRIVATE int sqlite3WindowRewrite(Parse*, Select*);
  17856. SQLITE_PRIVATE int sqlite3ExpandSubquery(Parse*, struct SrcList_item*);
  17857. SQLITE_PRIVATE void sqlite3WindowUpdate(Parse*, Window*, Window*, FuncDef*);
  17858. SQLITE_PRIVATE Window *sqlite3WindowDup(sqlite3 *db, Expr *pOwner, Window *p);
  17859. SQLITE_PRIVATE Window *sqlite3WindowListDup(sqlite3 *db, Window *p);
  17860. SQLITE_PRIVATE void sqlite3WindowFunctions(void);
  17861. SQLITE_PRIVATE void sqlite3WindowChain(Parse*, Window*, Window*);
  17862. SQLITE_PRIVATE Window *sqlite3WindowAssemble(Parse*, Window*, ExprList*, ExprList*, Token*);
  17863. #else
  17864. # define sqlite3WindowDelete(a,b)
  17865. # define sqlite3WindowFunctions()
  17866. # define sqlite3WindowAttach(a,b,c)
  17867. #endif
  17868. /*
  17869. ** Assuming zIn points to the first byte of a UTF-8 character,
  17870. ** advance zIn to point to the first byte of the next UTF-8 character.
  17871. */
  17872. #define SQLITE_SKIP_UTF8(zIn) { \
  17873. if( (*(zIn++))>=0xc0 ){ \
  17874. while( (*zIn & 0xc0)==0x80 ){ zIn++; } \
  17875. } \
  17876. }
  17877. /*
  17878. ** The SQLITE_*_BKPT macros are substitutes for the error codes with
  17879. ** the same name but without the _BKPT suffix. These macros invoke
  17880. ** routines that report the line-number on which the error originated
  17881. ** using sqlite3_log(). The routines also provide a convenient place
  17882. ** to set a debugger breakpoint.
  17883. */
  17884. SQLITE_PRIVATE int sqlite3ReportError(int iErr, int lineno, const char *zType);
  17885. SQLITE_PRIVATE int sqlite3CorruptError(int);
  17886. SQLITE_PRIVATE int sqlite3MisuseError(int);
  17887. SQLITE_PRIVATE int sqlite3CantopenError(int);
  17888. #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
  17889. #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
  17890. #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
  17891. #ifdef SQLITE_DEBUG
  17892. SQLITE_PRIVATE int sqlite3NomemError(int);
  17893. SQLITE_PRIVATE int sqlite3IoerrnomemError(int);
  17894. SQLITE_PRIVATE int sqlite3CorruptPgnoError(int,Pgno);
  17895. # define SQLITE_NOMEM_BKPT sqlite3NomemError(__LINE__)
  17896. # define SQLITE_IOERR_NOMEM_BKPT sqlite3IoerrnomemError(__LINE__)
  17897. # define SQLITE_CORRUPT_PGNO(P) sqlite3CorruptPgnoError(__LINE__,(P))
  17898. #else
  17899. # define SQLITE_NOMEM_BKPT SQLITE_NOMEM
  17900. # define SQLITE_IOERR_NOMEM_BKPT SQLITE_IOERR_NOMEM
  17901. # define SQLITE_CORRUPT_PGNO(P) sqlite3CorruptError(__LINE__)
  17902. #endif
  17903. /*
  17904. ** FTS3 and FTS4 both require virtual table support
  17905. */
  17906. #if defined(SQLITE_OMIT_VIRTUALTABLE)
  17907. # undef SQLITE_ENABLE_FTS3
  17908. # undef SQLITE_ENABLE_FTS4
  17909. #endif
  17910. /*
  17911. ** FTS4 is really an extension for FTS3. It is enabled using the
  17912. ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also call
  17913. ** the SQLITE_ENABLE_FTS4 macro to serve as an alias for SQLITE_ENABLE_FTS3.
  17914. */
  17915. #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
  17916. # define SQLITE_ENABLE_FTS3 1
  17917. #endif
  17918. /*
  17919. ** The ctype.h header is needed for non-ASCII systems. It is also
  17920. ** needed by FTS3 when FTS3 is included in the amalgamation.
  17921. */
  17922. #if !defined(SQLITE_ASCII) || \
  17923. (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
  17924. # include <ctype.h>
  17925. #endif
  17926. /*
  17927. ** The following macros mimic the standard library functions toupper(),
  17928. ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
  17929. ** sqlite versions only work for ASCII characters, regardless of locale.
  17930. */
  17931. #ifdef SQLITE_ASCII
  17932. # define sqlite3Toupper(x) ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
  17933. # define sqlite3Isspace(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
  17934. # define sqlite3Isalnum(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
  17935. # define sqlite3Isalpha(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
  17936. # define sqlite3Isdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
  17937. # define sqlite3Isxdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
  17938. # define sqlite3Tolower(x) (sqlite3UpperToLower[(unsigned char)(x)])
  17939. # define sqlite3Isquote(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x80)
  17940. #else
  17941. # define sqlite3Toupper(x) toupper((unsigned char)(x))
  17942. # define sqlite3Isspace(x) isspace((unsigned char)(x))
  17943. # define sqlite3Isalnum(x) isalnum((unsigned char)(x))
  17944. # define sqlite3Isalpha(x) isalpha((unsigned char)(x))
  17945. # define sqlite3Isdigit(x) isdigit((unsigned char)(x))
  17946. # define sqlite3Isxdigit(x) isxdigit((unsigned char)(x))
  17947. # define sqlite3Tolower(x) tolower((unsigned char)(x))
  17948. # define sqlite3Isquote(x) ((x)=='"'||(x)=='\''||(x)=='['||(x)=='`')
  17949. #endif
  17950. SQLITE_PRIVATE int sqlite3IsIdChar(u8);
  17951. /*
  17952. ** Internal function prototypes
  17953. */
  17954. SQLITE_PRIVATE int sqlite3StrICmp(const char*,const char*);
  17955. SQLITE_PRIVATE int sqlite3Strlen30(const char*);
  17956. #define sqlite3Strlen30NN(C) (strlen(C)&0x3fffffff)
  17957. SQLITE_PRIVATE char *sqlite3ColumnType(Column*,char*);
  17958. #define sqlite3StrNICmp sqlite3_strnicmp
  17959. SQLITE_PRIVATE int sqlite3MallocInit(void);
  17960. SQLITE_PRIVATE void sqlite3MallocEnd(void);
  17961. SQLITE_PRIVATE void *sqlite3Malloc(u64);
  17962. SQLITE_PRIVATE void *sqlite3MallocZero(u64);
  17963. SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, u64);
  17964. SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, u64);
  17965. SQLITE_PRIVATE void *sqlite3DbMallocRawNN(sqlite3*, u64);
  17966. SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
  17967. SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, u64);
  17968. SQLITE_PRIVATE char *sqlite3DbSpanDup(sqlite3*,const char*,const char*);
  17969. SQLITE_PRIVATE void *sqlite3Realloc(void*, u64);
  17970. SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, u64);
  17971. SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, u64);
  17972. SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
  17973. SQLITE_PRIVATE void sqlite3DbFreeNN(sqlite3*, void*);
  17974. SQLITE_PRIVATE int sqlite3MallocSize(void*);
  17975. SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
  17976. SQLITE_PRIVATE void *sqlite3PageMalloc(int);
  17977. SQLITE_PRIVATE void sqlite3PageFree(void*);
  17978. SQLITE_PRIVATE void sqlite3MemSetDefault(void);
  17979. #ifndef SQLITE_UNTESTABLE
  17980. SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
  17981. #endif
  17982. SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
  17983. /*
  17984. ** On systems with ample stack space and that support alloca(), make
  17985. ** use of alloca() to obtain space for large automatic objects. By default,
  17986. ** obtain space from malloc().
  17987. **
  17988. ** The alloca() routine never returns NULL. This will cause code paths
  17989. ** that deal with sqlite3StackAlloc() failures to be unreachable.
  17990. */
  17991. #ifdef SQLITE_USE_ALLOCA
  17992. # define sqlite3StackAllocRaw(D,N) alloca(N)
  17993. # define sqlite3StackAllocZero(D,N) memset(alloca(N), 0, N)
  17994. # define sqlite3StackFree(D,P)
  17995. #else
  17996. # define sqlite3StackAllocRaw(D,N) sqlite3DbMallocRaw(D,N)
  17997. # define sqlite3StackAllocZero(D,N) sqlite3DbMallocZero(D,N)
  17998. # define sqlite3StackFree(D,P) sqlite3DbFree(D,P)
  17999. #endif
  18000. /* Do not allow both MEMSYS5 and MEMSYS3 to be defined together. If they
  18001. ** are, disable MEMSYS3
  18002. */
  18003. #ifdef SQLITE_ENABLE_MEMSYS5
  18004. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
  18005. #undef SQLITE_ENABLE_MEMSYS3
  18006. #endif
  18007. #ifdef SQLITE_ENABLE_MEMSYS3
  18008. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
  18009. #endif
  18010. #ifndef SQLITE_MUTEX_OMIT
  18011. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
  18012. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void);
  18013. SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int);
  18014. SQLITE_PRIVATE int sqlite3MutexInit(void);
  18015. SQLITE_PRIVATE int sqlite3MutexEnd(void);
  18016. #endif
  18017. #if !defined(SQLITE_MUTEX_OMIT) && !defined(SQLITE_MUTEX_NOOP)
  18018. SQLITE_PRIVATE void sqlite3MemoryBarrier(void);
  18019. #else
  18020. # define sqlite3MemoryBarrier()
  18021. #endif
  18022. SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int);
  18023. SQLITE_PRIVATE void sqlite3StatusUp(int, int);
  18024. SQLITE_PRIVATE void sqlite3StatusDown(int, int);
  18025. SQLITE_PRIVATE void sqlite3StatusHighwater(int, int);
  18026. SQLITE_PRIVATE int sqlite3LookasideUsed(sqlite3*,int*);
  18027. /* Access to mutexes used by sqlite3_status() */
  18028. SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void);
  18029. SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void);
  18030. #if defined(SQLITE_ENABLE_MULTITHREADED_CHECKS) && !defined(SQLITE_MUTEX_OMIT)
  18031. SQLITE_PRIVATE void sqlite3MutexWarnOnContention(sqlite3_mutex*);
  18032. #else
  18033. # define sqlite3MutexWarnOnContention(x)
  18034. #endif
  18035. #ifndef SQLITE_OMIT_FLOATING_POINT
  18036. # define EXP754 (((u64)0x7ff)<<52)
  18037. # define MAN754 ((((u64)1)<<52)-1)
  18038. # define IsNaN(X) (((X)&EXP754)==EXP754 && ((X)&MAN754)!=0)
  18039. SQLITE_PRIVATE int sqlite3IsNaN(double);
  18040. #else
  18041. # define IsNaN(X) 0
  18042. # define sqlite3IsNaN(X) 0
  18043. #endif
  18044. /*
  18045. ** An instance of the following structure holds information about SQL
  18046. ** functions arguments that are the parameters to the printf() function.
  18047. */
  18048. struct PrintfArguments {
  18049. int nArg; /* Total number of arguments */
  18050. int nUsed; /* Number of arguments used so far */
  18051. sqlite3_value **apArg; /* The argument values */
  18052. };
  18053. SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
  18054. SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
  18055. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  18056. SQLITE_PRIVATE void sqlite3DebugPrintf(const char*, ...);
  18057. #endif
  18058. #if defined(SQLITE_TEST)
  18059. SQLITE_PRIVATE void *sqlite3TestTextToPtr(const char*);
  18060. #endif
  18061. #if defined(SQLITE_DEBUG)
  18062. SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView*, const Expr*, u8);
  18063. SQLITE_PRIVATE void sqlite3TreeViewBareExprList(TreeView*, const ExprList*, const char*);
  18064. SQLITE_PRIVATE void sqlite3TreeViewExprList(TreeView*, const ExprList*, u8, const char*);
  18065. SQLITE_PRIVATE void sqlite3TreeViewSrcList(TreeView*, const SrcList*);
  18066. SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView*, const Select*, u8);
  18067. SQLITE_PRIVATE void sqlite3TreeViewWith(TreeView*, const With*, u8);
  18068. #ifndef SQLITE_OMIT_WINDOWFUNC
  18069. SQLITE_PRIVATE void sqlite3TreeViewWindow(TreeView*, const Window*, u8);
  18070. SQLITE_PRIVATE void sqlite3TreeViewWinFunc(TreeView*, const Window*, u8);
  18071. #endif
  18072. #endif
  18073. SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*);
  18074. SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
  18075. SQLITE_PRIVATE int sqlite3ErrorToParser(sqlite3*,int);
  18076. SQLITE_PRIVATE void sqlite3Dequote(char*);
  18077. SQLITE_PRIVATE void sqlite3DequoteExpr(Expr*);
  18078. SQLITE_PRIVATE void sqlite3TokenInit(Token*,char*);
  18079. SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
  18080. SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
  18081. SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
  18082. SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
  18083. SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
  18084. SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
  18085. SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
  18086. SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);
  18087. #ifdef SQLITE_DEBUG
  18088. SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse*,int,int);
  18089. #endif
  18090. SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
  18091. SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
  18092. SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
  18093. SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*);
  18094. SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse*, Expr*, Select*);
  18095. SQLITE_PRIVATE Expr *sqlite3ExprAnd(Parse*,Expr*, Expr*);
  18096. SQLITE_PRIVATE Expr *sqlite3ExprSimplifiedAndOr(Expr*);
  18097. SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*, int);
  18098. SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*, u32);
  18099. SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
  18100. SQLITE_PRIVATE void sqlite3ExprUnmapAndDelete(Parse*, Expr*);
  18101. SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
  18102. SQLITE_PRIVATE ExprList *sqlite3ExprListAppendVector(Parse*,ExprList*,IdList*,Expr*);
  18103. SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList*,int);
  18104. SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
  18105. SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,const char*,const char*);
  18106. SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
  18107. SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList*);
  18108. SQLITE_PRIVATE int sqlite3IndexHasDuplicateRootPage(Index*);
  18109. SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
  18110. SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
  18111. SQLITE_PRIVATE int sqlite3InitOne(sqlite3*, int, char**, u32);
  18112. SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
  18113. #ifndef SQLITE_OMIT_VIRTUALTABLE
  18114. SQLITE_PRIVATE Module *sqlite3PragmaVtabRegister(sqlite3*,const char *zName);
  18115. #endif
  18116. SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);
  18117. SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);
  18118. SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);
  18119. SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
  18120. SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3*,Table*);
  18121. SQLITE_PRIVATE int sqlite3ColumnsFromExprList(Parse*,ExprList*,i16*,Column**);
  18122. SQLITE_PRIVATE void sqlite3SelectAddColumnTypeAndCollation(Parse*,Table*,Select*);
  18123. SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
  18124. SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
  18125. SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table*);
  18126. SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index*, i16);
  18127. SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
  18128. #if SQLITE_ENABLE_HIDDEN_COLUMNS
  18129. SQLITE_PRIVATE void sqlite3ColumnPropertiesFromName(Table*, Column*);
  18130. #else
  18131. # define sqlite3ColumnPropertiesFromName(T,C) /* no-op */
  18132. #endif
  18133. SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*,Token*);
  18134. SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
  18135. SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
  18136. SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
  18137. SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,Expr*,const char*,const char*);
  18138. SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
  18139. SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,u8,Select*);
  18140. SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
  18141. sqlite3_vfs**,char**,char **);
  18142. #ifdef SQLITE_HAS_CODEC
  18143. SQLITE_PRIVATE int sqlite3CodecQueryParameters(sqlite3*,const char*,const char*);
  18144. #else
  18145. # define sqlite3CodecQueryParameters(A,B,C) 0
  18146. #endif
  18147. SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
  18148. #ifdef SQLITE_UNTESTABLE
  18149. # define sqlite3FaultSim(X) SQLITE_OK
  18150. #else
  18151. SQLITE_PRIVATE int sqlite3FaultSim(int);
  18152. #endif
  18153. SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
  18154. SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
  18155. SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec*, u32);
  18156. SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
  18157. SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
  18158. SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
  18159. SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
  18160. #ifndef SQLITE_UNTESTABLE
  18161. SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
  18162. #endif
  18163. SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*);
  18164. SQLITE_PRIVATE void sqlite3RowSetDelete(void*);
  18165. SQLITE_PRIVATE void sqlite3RowSetClear(void*);
  18166. SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
  18167. SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, int iBatch, i64);
  18168. SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
  18169. SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,ExprList*,Select*,int,int);
  18170. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  18171. SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse*,Table*);
  18172. #else
  18173. # define sqlite3ViewGetColumnNames(A,B) 0
  18174. #endif
  18175. #if SQLITE_MAX_ATTACHED>30
  18176. SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask);
  18177. #endif
  18178. SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
  18179. SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
  18180. SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
  18181. SQLITE_PRIVATE void sqlite3FreeIndex(sqlite3*, Index*);
  18182. #ifndef SQLITE_OMIT_AUTOINCREMENT
  18183. SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse);
  18184. SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse);
  18185. #else
  18186. # define sqlite3AutoincrementBegin(X)
  18187. # define sqlite3AutoincrementEnd(X)
  18188. #endif
  18189. SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, Select*, IdList*, int, Upsert*);
  18190. SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
  18191. SQLITE_PRIVATE IdList *sqlite3IdListAppend(Parse*, IdList*, Token*);
  18192. SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
  18193. SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(Parse*, SrcList*, int, int);
  18194. SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(Parse*, SrcList*, Token*, Token*);
  18195. SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
  18196. Token*, Select*, Expr*, IdList*);
  18197. SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
  18198. SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse*, SrcList*, ExprList*);
  18199. SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
  18200. SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
  18201. SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
  18202. SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
  18203. SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
  18204. SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(sqlite3*,i16,int,char**);
  18205. SQLITE_PRIVATE void sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
  18206. Expr*, int, int, u8);
  18207. SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
  18208. SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
  18209. SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
  18210. Expr*,ExprList*,u32,Expr*);
  18211. SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
  18212. SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
  18213. SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
  18214. SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
  18215. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  18216. SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,char*);
  18217. #endif
  18218. SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*, ExprList*, Expr*);
  18219. SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*,Expr*,int,ExprList*,Expr*,
  18220. Upsert*);
  18221. SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int);
  18222. SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
  18223. SQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo*);
  18224. SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo*);
  18225. SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo*);
  18226. SQLITE_PRIVATE int sqlite3WhereOrderByLimitOptLabel(WhereInfo*);
  18227. SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo*);
  18228. SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo*);
  18229. SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo*);
  18230. SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo*, int*);
  18231. #define ONEPASS_OFF 0 /* Use of ONEPASS not allowed */
  18232. #define ONEPASS_SINGLE 1 /* ONEPASS valid for a single row update */
  18233. #define ONEPASS_MULTI 2 /* ONEPASS is valid for multiple rows */
  18234. SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(Parse*, Index*, int, int, int);
  18235. SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
  18236. SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
  18237. SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
  18238. SQLITE_PRIVATE void sqlite3ExprCode(Parse*, Expr*, int);
  18239. SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, Expr*, int);
  18240. SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse*, Expr*, int);
  18241. SQLITE_PRIVATE int sqlite3ExprCodeAtInit(Parse*, Expr*, int);
  18242. SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
  18243. SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
  18244. SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse*, Expr*, int);
  18245. SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int, u8);
  18246. #define SQLITE_ECEL_DUP 0x01 /* Deep, not shallow copies */
  18247. #define SQLITE_ECEL_FACTOR 0x02 /* Factor out constant terms */
  18248. #define SQLITE_ECEL_REF 0x04 /* Use ExprList.u.x.iOrderByCol */
  18249. #define SQLITE_ECEL_OMITREF 0x08 /* Omit if ExprList.u.x.iOrderByCol */
  18250. SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
  18251. SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
  18252. SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse*, Expr*, int, int);
  18253. SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
  18254. #define LOCATE_VIEW 0x01
  18255. #define LOCATE_NOERR 0x02
  18256. SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,u32 flags,const char*, const char*);
  18257. SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,u32 flags,struct SrcList_item *);
  18258. SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
  18259. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
  18260. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
  18261. SQLITE_PRIVATE void sqlite3Vacuum(Parse*,Token*,Expr*);
  18262. SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*, int, sqlite3_value*);
  18263. SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
  18264. SQLITE_PRIVATE int sqlite3ExprCompare(Parse*,Expr*, Expr*, int);
  18265. SQLITE_PRIVATE int sqlite3ExprCompareSkip(Expr*, Expr*, int);
  18266. SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*, int);
  18267. SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Parse*,Expr*, Expr*, int);
  18268. SQLITE_PRIVATE int sqlite3ExprImpliesNonNullRow(Expr*,int);
  18269. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
  18270. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
  18271. SQLITE_PRIVATE int sqlite3ExprCoveredByIndex(Expr*, int iCur, Index *pIdx);
  18272. SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr*, SrcList*);
  18273. SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
  18274. #ifndef SQLITE_UNTESTABLE
  18275. SQLITE_PRIVATE void sqlite3PrngSaveState(void);
  18276. SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
  18277. #endif
  18278. SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int);
  18279. SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
  18280. SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
  18281. SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
  18282. SQLITE_PRIVATE void sqlite3EndTransaction(Parse*,int);
  18283. SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
  18284. SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
  18285. SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
  18286. SQLITE_PRIVATE int sqlite3ExprIdToTrueFalse(Expr*);
  18287. SQLITE_PRIVATE int sqlite3ExprTruthValue(const Expr*);
  18288. SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
  18289. SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
  18290. SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*, u8);
  18291. SQLITE_PRIVATE int sqlite3ExprIsConstantOrGroupBy(Parse*, Expr*, ExprList*);
  18292. SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr*,int);
  18293. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  18294. SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr*);
  18295. #endif
  18296. SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
  18297. SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
  18298. SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
  18299. SQLITE_PRIVATE int sqlite3IsRowid(const char*);
  18300. SQLITE_PRIVATE void sqlite3GenerateRowDelete(
  18301. Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8,int);
  18302. SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*, int);
  18303. SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*,Index*,int);
  18304. SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse*,int);
  18305. SQLITE_PRIVATE int sqlite3ExprReferencesUpdatedColumn(Expr*,int*,int);
  18306. SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int*,int,int,int,int,
  18307. u8,u8,int,int*,int*,Upsert*);
  18308. #ifdef SQLITE_ENABLE_NULL_TRIM
  18309. SQLITE_PRIVATE void sqlite3SetMakeRecordP5(Vdbe*,Table*);
  18310. #else
  18311. # define sqlite3SetMakeRecordP5(A,B)
  18312. #endif
  18313. SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*,Table*,int,int,int,int*,int,int,int);
  18314. SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, u8, int, u8*, int*, int*);
  18315. SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
  18316. SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
  18317. SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
  18318. SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, int, char*, i8, u8);
  18319. SQLITE_PRIVATE void sqlite3UniqueConstraint(Parse*, int, Index*);
  18320. SQLITE_PRIVATE void sqlite3RowidConstraint(Parse*, int, Table*);
  18321. SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
  18322. SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
  18323. SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
  18324. SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
  18325. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
  18326. SQLITE_PRIVATE FuncDef *sqlite3FunctionSearch(int,const char*);
  18327. SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(FuncDef*,int);
  18328. SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,u8,u8);
  18329. SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void);
  18330. SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
  18331. SQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3*);
  18332. SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
  18333. SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
  18334. SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
  18335. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  18336. SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, ExprList*,Expr*,int);
  18337. #endif
  18338. #ifndef SQLITE_OMIT_TRIGGER
  18339. SQLITE_PRIVATE void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
  18340. Expr*,int, int);
  18341. SQLITE_PRIVATE void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
  18342. SQLITE_PRIVATE void sqlite3DropTrigger(Parse*, SrcList*, int);
  18343. SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse*, Trigger*);
  18344. SQLITE_PRIVATE Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
  18345. SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *, Table *);
  18346. SQLITE_PRIVATE void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
  18347. int, int, int);
  18348. SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
  18349. void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
  18350. SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
  18351. SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*,
  18352. const char*,const char*);
  18353. SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(Parse*,Token*, IdList*,
  18354. Select*,u8,Upsert*,
  18355. const char*,const char*);
  18356. SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(Parse*,Token*,ExprList*, Expr*, u8,
  18357. const char*,const char*);
  18358. SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(Parse*,Token*, Expr*,
  18359. const char*,const char*);
  18360. SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3*, Trigger*);
  18361. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
  18362. SQLITE_PRIVATE u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
  18363. # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
  18364. # define sqlite3IsToplevel(p) ((p)->pToplevel==0)
  18365. #else
  18366. # define sqlite3TriggersExist(B,C,D,E,F) 0
  18367. # define sqlite3DeleteTrigger(A,B)
  18368. # define sqlite3DropTriggerPtr(A,B)
  18369. # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
  18370. # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
  18371. # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
  18372. # define sqlite3TriggerList(X, Y) 0
  18373. # define sqlite3ParseToplevel(p) p
  18374. # define sqlite3IsToplevel(p) 1
  18375. # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
  18376. #endif
  18377. SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
  18378. SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
  18379. SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
  18380. #ifndef SQLITE_OMIT_AUTHORIZATION
  18381. SQLITE_PRIVATE void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
  18382. SQLITE_PRIVATE int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
  18383. SQLITE_PRIVATE void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
  18384. SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext*);
  18385. SQLITE_PRIVATE int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
  18386. #else
  18387. # define sqlite3AuthRead(a,b,c,d)
  18388. # define sqlite3AuthCheck(a,b,c,d,e) SQLITE_OK
  18389. # define sqlite3AuthContextPush(a,b,c)
  18390. # define sqlite3AuthContextPop(a) ((void)(a))
  18391. #endif
  18392. SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
  18393. SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
  18394. SQLITE_PRIVATE void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
  18395. SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
  18396. SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
  18397. SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
  18398. SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
  18399. SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
  18400. SQLITE_PRIVATE int sqlite3RealSameAsInt(double,sqlite3_int64);
  18401. SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
  18402. SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
  18403. SQLITE_PRIVATE int sqlite3Atoi(const char*);
  18404. #ifndef SQLITE_OMIT_UTF16
  18405. SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
  18406. #endif
  18407. SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
  18408. SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**);
  18409. SQLITE_PRIVATE LogEst sqlite3LogEst(u64);
  18410. SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst,LogEst);
  18411. #ifndef SQLITE_OMIT_VIRTUALTABLE
  18412. SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double);
  18413. #endif
  18414. #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
  18415. defined(SQLITE_ENABLE_STAT3_OR_STAT4) || \
  18416. defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
  18417. SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst);
  18418. #endif
  18419. SQLITE_PRIVATE VList *sqlite3VListAdd(sqlite3*,VList*,const char*,int,int);
  18420. SQLITE_PRIVATE const char *sqlite3VListNumToName(VList*,int);
  18421. SQLITE_PRIVATE int sqlite3VListNameToNum(VList*,const char*,int);
  18422. /*
  18423. ** Routines to read and write variable-length integers. These used to
  18424. ** be defined locally, but now we use the varint routines in the util.c
  18425. ** file.
  18426. */
  18427. SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
  18428. SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
  18429. SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
  18430. SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
  18431. /*
  18432. ** The common case is for a varint to be a single byte. They following
  18433. ** macros handle the common case without a procedure call, but then call
  18434. ** the procedure for larger varints.
  18435. */
  18436. #define getVarint32(A,B) \
  18437. (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))
  18438. #define putVarint32(A,B) \
  18439. (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\
  18440. sqlite3PutVarint((A),(B)))
  18441. #define getVarint sqlite3GetVarint
  18442. #define putVarint sqlite3PutVarint
  18443. SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3*, Index*);
  18444. SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe*, Table*, int);
  18445. SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
  18446. SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
  18447. SQLITE_PRIVATE char sqlite3TableColumnAffinity(Table*,int);
  18448. SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
  18449. SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
  18450. SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char*, i64*);
  18451. SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3*, int, const char*,...);
  18452. SQLITE_PRIVATE void sqlite3Error(sqlite3*,int);
  18453. SQLITE_PRIVATE void sqlite3SystemError(sqlite3*,int);
  18454. SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
  18455. SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
  18456. SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
  18457. #if defined(SQLITE_NEED_ERR_NAME)
  18458. SQLITE_PRIVATE const char *sqlite3ErrName(int);
  18459. #endif
  18460. #ifdef SQLITE_ENABLE_DESERIALIZE
  18461. SQLITE_PRIVATE int sqlite3MemdbInit(void);
  18462. #endif
  18463. SQLITE_PRIVATE const char *sqlite3ErrStr(int);
  18464. SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
  18465. SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
  18466. SQLITE_PRIVATE int sqlite3IsBinary(const CollSeq*);
  18467. SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
  18468. SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
  18469. SQLITE_PRIVATE CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, Expr *pExpr);
  18470. SQLITE_PRIVATE int sqlite3ExprCollSeqMatch(Parse*,Expr*,Expr*);
  18471. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, const Token*, int);
  18472. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*);
  18473. SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*);
  18474. SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
  18475. SQLITE_PRIVATE int sqlite3WritableSchema(sqlite3*);
  18476. SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
  18477. SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
  18478. SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
  18479. SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
  18480. SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
  18481. SQLITE_PRIVATE int sqlite3AbsInt32(int);
  18482. #ifdef SQLITE_ENABLE_8_3_NAMES
  18483. SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
  18484. #else
  18485. # define sqlite3FileSuffix3(X,Y)
  18486. #endif
  18487. SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,u8);
  18488. SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
  18489. SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
  18490. SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
  18491. void(*)(void*));
  18492. SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value*);
  18493. SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
  18494. #ifndef SQLITE_UNTESTABLE
  18495. SQLITE_PRIVATE void sqlite3ResultIntReal(sqlite3_context*);
  18496. #endif
  18497. SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
  18498. #ifndef SQLITE_OMIT_UTF16
  18499. SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
  18500. #endif
  18501. SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
  18502. SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
  18503. #ifndef SQLITE_AMALGAMATION
  18504. SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
  18505. SQLITE_PRIVATE const char sqlite3StrBINARY[];
  18506. SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
  18507. SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
  18508. SQLITE_PRIVATE const Token sqlite3IntTokens[];
  18509. SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
  18510. SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;
  18511. #ifndef SQLITE_OMIT_WSD
  18512. SQLITE_PRIVATE int sqlite3PendingByte;
  18513. #endif
  18514. #endif
  18515. #ifdef VDBE_PROFILE
  18516. SQLITE_PRIVATE sqlite3_uint64 sqlite3NProfileCnt;
  18517. #endif
  18518. SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
  18519. SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
  18520. SQLITE_PRIVATE void sqlite3AlterFunctions(void);
  18521. SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
  18522. SQLITE_PRIVATE void sqlite3AlterRenameColumn(Parse*, SrcList*, Token*, Token*);
  18523. SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
  18524. SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
  18525. SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*, int);
  18526. SQLITE_PRIVATE void sqlite3CodeRhsOfIN(Parse*, Expr*, int);
  18527. SQLITE_PRIVATE int sqlite3CodeSubselect(Parse*, Expr*);
  18528. SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
  18529. SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p);
  18530. SQLITE_PRIVATE int sqlite3MatchSpanName(const char*, const char*, const char*, const char*);
  18531. SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
  18532. SQLITE_PRIVATE int sqlite3ResolveExprListNames(NameContext*, ExprList*);
  18533. SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
  18534. SQLITE_PRIVATE int sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*);
  18535. SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
  18536. SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
  18537. SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
  18538. SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
  18539. SQLITE_PRIVATE void *sqlite3RenameTokenMap(Parse*, void*, Token*);
  18540. SQLITE_PRIVATE void sqlite3RenameTokenRemap(Parse*, void *pTo, void *pFrom);
  18541. SQLITE_PRIVATE void sqlite3RenameExprUnmap(Parse*, Expr*);
  18542. SQLITE_PRIVATE void sqlite3RenameExprlistUnmap(Parse*, ExprList*);
  18543. SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
  18544. SQLITE_PRIVATE char sqlite3AffinityType(const char*, Column*);
  18545. SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
  18546. SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*, sqlite3_file*);
  18547. SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
  18548. SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
  18549. SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
  18550. SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
  18551. SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
  18552. SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
  18553. SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
  18554. SQLITE_PRIVATE void sqlite3SchemaClear(void *);
  18555. SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
  18556. SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
  18557. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int,int);
  18558. SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo*);
  18559. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo*);
  18560. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse*, Index*);
  18561. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoFromExprList(Parse*, ExprList*, int, int);
  18562. #ifdef SQLITE_DEBUG
  18563. SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo*);
  18564. #endif
  18565. SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
  18566. void (*)(sqlite3_context*,int,sqlite3_value **),
  18567. void (*)(sqlite3_context*,int,sqlite3_value **),
  18568. void (*)(sqlite3_context*),
  18569. void (*)(sqlite3_context*),
  18570. void (*)(sqlite3_context*,int,sqlite3_value **),
  18571. FuncDestructor *pDestructor
  18572. );
  18573. SQLITE_PRIVATE void sqlite3NoopDestructor(void*);
  18574. SQLITE_PRIVATE void sqlite3OomFault(sqlite3*);
  18575. SQLITE_PRIVATE void sqlite3OomClear(sqlite3*);
  18576. SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
  18577. SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
  18578. SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, sqlite3*, char*, int, int);
  18579. SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
  18580. SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
  18581. SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
  18582. SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
  18583. SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
  18584. #ifndef SQLITE_OMIT_SUBQUERY
  18585. SQLITE_PRIVATE int sqlite3ExprCheckIN(Parse*, Expr*);
  18586. #else
  18587. # define sqlite3ExprCheckIN(x,y) SQLITE_OK
  18588. #endif
  18589. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  18590. SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void);
  18591. SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
  18592. Parse*,Index*,UnpackedRecord**,Expr*,int,int,int*);
  18593. SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(Parse*, Expr*, u8, sqlite3_value**);
  18594. SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord*);
  18595. SQLITE_PRIVATE int sqlite3Stat4Column(sqlite3*, const void*, int, int, sqlite3_value**);
  18596. SQLITE_PRIVATE char sqlite3IndexColumnAffinity(sqlite3*, Index*, int);
  18597. #endif
  18598. /*
  18599. ** The interface to the LEMON-generated parser
  18600. */
  18601. #ifndef SQLITE_AMALGAMATION
  18602. SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(u64), Parse*);
  18603. SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
  18604. #endif
  18605. SQLITE_PRIVATE void sqlite3Parser(void*, int, Token);
  18606. SQLITE_PRIVATE int sqlite3ParserFallback(int);
  18607. #ifdef YYTRACKMAXSTACKDEPTH
  18608. SQLITE_PRIVATE int sqlite3ParserStackPeak(void*);
  18609. #endif
  18610. SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
  18611. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  18612. SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3*);
  18613. #else
  18614. # define sqlite3CloseExtensions(X)
  18615. #endif
  18616. #ifndef SQLITE_OMIT_SHARED_CACHE
  18617. SQLITE_PRIVATE void sqlite3TableLock(Parse *, int, int, u8, const char *);
  18618. #else
  18619. #define sqlite3TableLock(v,w,x,y,z)
  18620. #endif
  18621. #ifdef SQLITE_TEST
  18622. SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char*);
  18623. #endif
  18624. #ifdef SQLITE_OMIT_VIRTUALTABLE
  18625. # define sqlite3VtabClear(Y)
  18626. # define sqlite3VtabSync(X,Y) SQLITE_OK
  18627. # define sqlite3VtabRollback(X)
  18628. # define sqlite3VtabCommit(X)
  18629. # define sqlite3VtabInSync(db) 0
  18630. # define sqlite3VtabLock(X)
  18631. # define sqlite3VtabUnlock(X)
  18632. # define sqlite3VtabUnlockList(X)
  18633. # define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
  18634. # define sqlite3GetVTable(X,Y) ((VTable*)0)
  18635. #else
  18636. SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table*);
  18637. SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
  18638. SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe*);
  18639. SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db);
  18640. SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db);
  18641. SQLITE_PRIVATE void sqlite3VtabLock(VTable *);
  18642. SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *);
  18643. SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3*);
  18644. SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *, int, int);
  18645. SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe*, sqlite3_vtab*);
  18646. SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*);
  18647. SQLITE_PRIVATE Module *sqlite3VtabCreateModule(
  18648. sqlite3*,
  18649. const char*,
  18650. const sqlite3_module*,
  18651. void*,
  18652. void(*)(void*)
  18653. );
  18654. # define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
  18655. #endif
  18656. SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse*,Module*);
  18657. SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3*,Module*);
  18658. SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
  18659. SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
  18660. SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
  18661. SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
  18662. SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
  18663. SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
  18664. SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
  18665. SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
  18666. SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
  18667. SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
  18668. SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*);
  18669. SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
  18670. SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
  18671. SQLITE_PRIVATE void sqlite3ParserReset(Parse*);
  18672. #ifdef SQLITE_ENABLE_NORMALIZE
  18673. SQLITE_PRIVATE char *sqlite3Normalize(Vdbe*, const char*);
  18674. #endif
  18675. SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
  18676. SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
  18677. SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
  18678. SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
  18679. SQLITE_PRIVATE const char *sqlite3JournalModename(int);
  18680. #ifndef SQLITE_OMIT_WAL
  18681. SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
  18682. SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
  18683. #endif
  18684. #ifndef SQLITE_OMIT_CTE
  18685. SQLITE_PRIVATE With *sqlite3WithAdd(Parse*,With*,Token*,ExprList*,Select*);
  18686. SQLITE_PRIVATE void sqlite3WithDelete(sqlite3*,With*);
  18687. SQLITE_PRIVATE void sqlite3WithPush(Parse*, With*, u8);
  18688. #else
  18689. #define sqlite3WithPush(x,y,z)
  18690. #define sqlite3WithDelete(x,y)
  18691. #endif
  18692. #ifndef SQLITE_OMIT_UPSERT
  18693. SQLITE_PRIVATE Upsert *sqlite3UpsertNew(sqlite3*,ExprList*,Expr*,ExprList*,Expr*);
  18694. SQLITE_PRIVATE void sqlite3UpsertDelete(sqlite3*,Upsert*);
  18695. SQLITE_PRIVATE Upsert *sqlite3UpsertDup(sqlite3*,Upsert*);
  18696. SQLITE_PRIVATE int sqlite3UpsertAnalyzeTarget(Parse*,SrcList*,Upsert*);
  18697. SQLITE_PRIVATE void sqlite3UpsertDoUpdate(Parse*,Upsert*,Table*,Index*,int);
  18698. #else
  18699. #define sqlite3UpsertNew(v,w,x,y,z) ((Upsert*)0)
  18700. #define sqlite3UpsertDelete(x,y)
  18701. #define sqlite3UpsertDup(x,y) ((Upsert*)0)
  18702. #endif
  18703. /* Declarations for functions in fkey.c. All of these are replaced by
  18704. ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
  18705. ** key functionality is available. If OMIT_TRIGGER is defined but
  18706. ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
  18707. ** this case foreign keys are parsed, but no other functionality is
  18708. ** provided (enforcement of FK constraints requires the triggers sub-system).
  18709. */
  18710. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  18711. SQLITE_PRIVATE void sqlite3FkCheck(Parse*, Table*, int, int, int*, int);
  18712. SQLITE_PRIVATE void sqlite3FkDropTable(Parse*, SrcList *, Table*);
  18713. SQLITE_PRIVATE void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int);
  18714. SQLITE_PRIVATE int sqlite3FkRequired(Parse*, Table*, int*, int);
  18715. SQLITE_PRIVATE u32 sqlite3FkOldmask(Parse*, Table*);
  18716. SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *);
  18717. #else
  18718. #define sqlite3FkActions(a,b,c,d,e,f)
  18719. #define sqlite3FkCheck(a,b,c,d,e,f)
  18720. #define sqlite3FkDropTable(a,b,c)
  18721. #define sqlite3FkOldmask(a,b) 0
  18722. #define sqlite3FkRequired(a,b,c,d) 0
  18723. #define sqlite3FkReferences(a) 0
  18724. #endif
  18725. #ifndef SQLITE_OMIT_FOREIGN_KEY
  18726. SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *, Table*);
  18727. SQLITE_PRIVATE int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**);
  18728. #else
  18729. #define sqlite3FkDelete(a,b)
  18730. #define sqlite3FkLocateIndex(a,b,c,d,e)
  18731. #endif
  18732. /*
  18733. ** Available fault injectors. Should be numbered beginning with 0.
  18734. */
  18735. #define SQLITE_FAULTINJECTOR_MALLOC 0
  18736. #define SQLITE_FAULTINJECTOR_COUNT 1
  18737. /*
  18738. ** The interface to the code in fault.c used for identifying "benign"
  18739. ** malloc failures. This is only present if SQLITE_UNTESTABLE
  18740. ** is not defined.
  18741. */
  18742. #ifndef SQLITE_UNTESTABLE
  18743. SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void);
  18744. SQLITE_PRIVATE void sqlite3EndBenignMalloc(void);
  18745. #else
  18746. #define sqlite3BeginBenignMalloc()
  18747. #define sqlite3EndBenignMalloc()
  18748. #endif
  18749. /*
  18750. ** Allowed return values from sqlite3FindInIndex()
  18751. */
  18752. #define IN_INDEX_ROWID 1 /* Search the rowid of the table */
  18753. #define IN_INDEX_EPH 2 /* Search an ephemeral b-tree */
  18754. #define IN_INDEX_INDEX_ASC 3 /* Existing index ASCENDING */
  18755. #define IN_INDEX_INDEX_DESC 4 /* Existing index DESCENDING */
  18756. #define IN_INDEX_NOOP 5 /* No table available. Use comparisons */
  18757. /*
  18758. ** Allowed flags for the 3rd parameter to sqlite3FindInIndex().
  18759. */
  18760. #define IN_INDEX_NOOP_OK 0x0001 /* OK to return IN_INDEX_NOOP */
  18761. #define IN_INDEX_MEMBERSHIP 0x0002 /* IN operator used for membership test */
  18762. #define IN_INDEX_LOOP 0x0004 /* IN operator used as a loop */
  18763. SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, u32, int*, int*, int*);
  18764. SQLITE_PRIVATE int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
  18765. SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *);
  18766. #if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
  18767. || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
  18768. SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *);
  18769. #endif
  18770. SQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p);
  18771. SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
  18772. SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p);
  18773. #if SQLITE_MAX_EXPR_DEPTH>0
  18774. SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *);
  18775. SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse*, int);
  18776. #else
  18777. #define sqlite3SelectExprHeight(x) 0
  18778. #define sqlite3ExprCheckHeight(x,y)
  18779. #endif
  18780. SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
  18781. SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
  18782. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  18783. SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
  18784. SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db);
  18785. SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db);
  18786. #else
  18787. #define sqlite3ConnectionBlocked(x,y)
  18788. #define sqlite3ConnectionUnlocked(x)
  18789. #define sqlite3ConnectionClosed(x)
  18790. #endif
  18791. #ifdef SQLITE_DEBUG
  18792. SQLITE_PRIVATE void sqlite3ParserTrace(FILE*, char *);
  18793. #endif
  18794. #if defined(YYCOVERAGE)
  18795. SQLITE_PRIVATE int sqlite3ParserCoverage(FILE*);
  18796. #endif
  18797. /*
  18798. ** If the SQLITE_ENABLE IOTRACE exists then the global variable
  18799. ** sqlite3IoTrace is a pointer to a printf-like routine used to
  18800. ** print I/O tracing messages.
  18801. */
  18802. #ifdef SQLITE_ENABLE_IOTRACE
  18803. # define IOTRACE(A) if( sqlite3IoTrace ){ sqlite3IoTrace A; }
  18804. SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe*);
  18805. SQLITE_API SQLITE_EXTERN void (SQLITE_CDECL *sqlite3IoTrace)(const char*,...);
  18806. #else
  18807. # define IOTRACE(A)
  18808. # define sqlite3VdbeIOTraceSql(X)
  18809. #endif
  18810. /*
  18811. ** These routines are available for the mem2.c debugging memory allocator
  18812. ** only. They are used to verify that different "types" of memory
  18813. ** allocations are properly tracked by the system.
  18814. **
  18815. ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
  18816. ** the MEMTYPE_* macros defined below. The type must be a bitmask with
  18817. ** a single bit set.
  18818. **
  18819. ** sqlite3MemdebugHasType() returns true if any of the bits in its second
  18820. ** argument match the type set by the previous sqlite3MemdebugSetType().
  18821. ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
  18822. **
  18823. ** sqlite3MemdebugNoType() returns true if none of the bits in its second
  18824. ** argument match the type set by the previous sqlite3MemdebugSetType().
  18825. **
  18826. ** Perhaps the most important point is the difference between MEMTYPE_HEAP
  18827. ** and MEMTYPE_LOOKASIDE. If an allocation is MEMTYPE_LOOKASIDE, that means
  18828. ** it might have been allocated by lookaside, except the allocation was
  18829. ** too large or lookaside was already full. It is important to verify
  18830. ** that allocations that might have been satisfied by lookaside are not
  18831. ** passed back to non-lookaside free() routines. Asserts such as the
  18832. ** example above are placed on the non-lookaside free() routines to verify
  18833. ** this constraint.
  18834. **
  18835. ** All of this is no-op for a production build. It only comes into
  18836. ** play when the SQLITE_MEMDEBUG compile-time option is used.
  18837. */
  18838. #ifdef SQLITE_MEMDEBUG
  18839. SQLITE_PRIVATE void sqlite3MemdebugSetType(void*,u8);
  18840. SQLITE_PRIVATE int sqlite3MemdebugHasType(void*,u8);
  18841. SQLITE_PRIVATE int sqlite3MemdebugNoType(void*,u8);
  18842. #else
  18843. # define sqlite3MemdebugSetType(X,Y) /* no-op */
  18844. # define sqlite3MemdebugHasType(X,Y) 1
  18845. # define sqlite3MemdebugNoType(X,Y) 1
  18846. #endif
  18847. #define MEMTYPE_HEAP 0x01 /* General heap allocations */
  18848. #define MEMTYPE_LOOKASIDE 0x02 /* Heap that might have been lookaside */
  18849. #define MEMTYPE_PCACHE 0x04 /* Page cache allocations */
  18850. /*
  18851. ** Threading interface
  18852. */
  18853. #if SQLITE_MAX_WORKER_THREADS>0
  18854. SQLITE_PRIVATE int sqlite3ThreadCreate(SQLiteThread**,void*(*)(void*),void*);
  18855. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread*, void**);
  18856. #endif
  18857. #if defined(SQLITE_ENABLE_DBPAGE_VTAB) || defined(SQLITE_TEST)
  18858. SQLITE_PRIVATE int sqlite3DbpageRegister(sqlite3*);
  18859. #endif
  18860. #if defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)
  18861. SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3*);
  18862. #endif
  18863. SQLITE_PRIVATE int sqlite3ExprVectorSize(Expr *pExpr);
  18864. SQLITE_PRIVATE int sqlite3ExprIsVector(Expr *pExpr);
  18865. SQLITE_PRIVATE Expr *sqlite3VectorFieldSubexpr(Expr*, int);
  18866. SQLITE_PRIVATE Expr *sqlite3ExprForVectorField(Parse*,Expr*,int);
  18867. SQLITE_PRIVATE void sqlite3VectorErrorMsg(Parse*, Expr*);
  18868. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  18869. SQLITE_PRIVATE const char **sqlite3CompileOptions(int *pnOpt);
  18870. #endif
  18871. #endif /* SQLITEINT_H */
  18872. /************** End of sqliteInt.h *******************************************/
  18873. /************** Begin file global.c ******************************************/
  18874. /*
  18875. ** 2008 June 13
  18876. **
  18877. ** The author disclaims copyright to this source code. In place of
  18878. ** a legal notice, here is a blessing:
  18879. **
  18880. ** May you do good and not evil.
  18881. ** May you find forgiveness for yourself and forgive others.
  18882. ** May you share freely, never taking more than you give.
  18883. **
  18884. *************************************************************************
  18885. **
  18886. ** This file contains definitions of global variables and constants.
  18887. */
  18888. /* #include "sqliteInt.h" */
  18889. /* An array to map all upper-case characters into their corresponding
  18890. ** lower-case character.
  18891. **
  18892. ** SQLite only considers US-ASCII (or EBCDIC) characters. We do not
  18893. ** handle case conversions for the UTF character set since the tables
  18894. ** involved are nearly as big or bigger than SQLite itself.
  18895. */
  18896. SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
  18897. #ifdef SQLITE_ASCII
  18898. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
  18899. 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
  18900. 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
  18901. 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
  18902. 104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
  18903. 122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
  18904. 108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
  18905. 126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
  18906. 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
  18907. 162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
  18908. 180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
  18909. 198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
  18910. 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
  18911. 234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
  18912. 252,253,254,255
  18913. #endif
  18914. #ifdef SQLITE_EBCDIC
  18915. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* 0x */
  18916. 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
  18917. 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
  18918. 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
  18919. 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
  18920. 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
  18921. 96, 97, 98, 99,100,101,102,103,104,105,106,107,108,109,110,111, /* 6x */
  18922. 112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127, /* 7x */
  18923. 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
  18924. 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159, /* 9x */
  18925. 160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
  18926. 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
  18927. 192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
  18928. 208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
  18929. 224,225,162,163,164,165,166,167,168,169,234,235,236,237,238,239, /* Ex */
  18930. 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255, /* Fx */
  18931. #endif
  18932. };
  18933. /*
  18934. ** The following 256 byte lookup table is used to support SQLites built-in
  18935. ** equivalents to the following standard library functions:
  18936. **
  18937. ** isspace() 0x01
  18938. ** isalpha() 0x02
  18939. ** isdigit() 0x04
  18940. ** isalnum() 0x06
  18941. ** isxdigit() 0x08
  18942. ** toupper() 0x20
  18943. ** SQLite identifier character 0x40
  18944. ** Quote character 0x80
  18945. **
  18946. ** Bit 0x20 is set if the mapped character requires translation to upper
  18947. ** case. i.e. if the character is a lower-case ASCII character.
  18948. ** If x is a lower-case ASCII character, then its upper-case equivalent
  18949. ** is (x - 0x20). Therefore toupper() can be implemented as:
  18950. **
  18951. ** (x & ~(map[x]&0x20))
  18952. **
  18953. ** The equivalent of tolower() is implemented using the sqlite3UpperToLower[]
  18954. ** array. tolower() is used more often than toupper() by SQLite.
  18955. **
  18956. ** Bit 0x40 is set if the character is non-alphanumeric and can be used in an
  18957. ** SQLite identifier. Identifiers are alphanumerics, "_", "$", and any
  18958. ** non-ASCII UTF character. Hence the test for whether or not a character is
  18959. ** part of an identifier is 0x46.
  18960. */
  18961. #ifdef SQLITE_ASCII
  18962. SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
  18963. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 00..07 ........ */
  18964. 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, /* 08..0f ........ */
  18965. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 10..17 ........ */
  18966. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 18..1f ........ */
  18967. 0x01, 0x00, 0x80, 0x00, 0x40, 0x00, 0x00, 0x80, /* 20..27 !"#$%&' */
  18968. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 28..2f ()*+,-./ */
  18969. 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, /* 30..37 01234567 */
  18970. 0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 38..3f 89:;<=>? */
  18971. 0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02, /* 40..47 @ABCDEFG */
  18972. 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 48..4f HIJKLMNO */
  18973. 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 50..57 PQRSTUVW */
  18974. 0x02, 0x02, 0x02, 0x80, 0x00, 0x00, 0x00, 0x40, /* 58..5f XYZ[\]^_ */
  18975. 0x80, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22, /* 60..67 `abcdefg */
  18976. 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 68..6f hijklmno */
  18977. 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 70..77 pqrstuvw */
  18978. 0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, /* 78..7f xyz{|}~. */
  18979. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 80..87 ........ */
  18980. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 88..8f ........ */
  18981. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 90..97 ........ */
  18982. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 98..9f ........ */
  18983. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a0..a7 ........ */
  18984. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a8..af ........ */
  18985. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b0..b7 ........ */
  18986. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b8..bf ........ */
  18987. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c0..c7 ........ */
  18988. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c8..cf ........ */
  18989. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d0..d7 ........ */
  18990. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d8..df ........ */
  18991. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e0..e7 ........ */
  18992. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e8..ef ........ */
  18993. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* f0..f7 ........ */
  18994. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40 /* f8..ff ........ */
  18995. };
  18996. #endif
  18997. /* EVIDENCE-OF: R-02982-34736 In order to maintain full backwards
  18998. ** compatibility for legacy applications, the URI filename capability is
  18999. ** disabled by default.
  19000. **
  19001. ** EVIDENCE-OF: R-38799-08373 URI filenames can be enabled or disabled
  19002. ** using the SQLITE_USE_URI=1 or SQLITE_USE_URI=0 compile-time options.
  19003. **
  19004. ** EVIDENCE-OF: R-43642-56306 By default, URI handling is globally
  19005. ** disabled. The default value may be changed by compiling with the
  19006. ** SQLITE_USE_URI symbol defined.
  19007. **
  19008. ** URI filenames are enabled by default if SQLITE_HAS_CODEC is
  19009. ** enabled.
  19010. */
  19011. #ifndef SQLITE_USE_URI
  19012. # ifdef SQLITE_HAS_CODEC
  19013. # define SQLITE_USE_URI 1
  19014. # else
  19015. # define SQLITE_USE_URI 0
  19016. # endif
  19017. #endif
  19018. /* EVIDENCE-OF: R-38720-18127 The default setting is determined by the
  19019. ** SQLITE_ALLOW_COVERING_INDEX_SCAN compile-time option, or is "on" if
  19020. ** that compile-time option is omitted.
  19021. */
  19022. #if !defined(SQLITE_ALLOW_COVERING_INDEX_SCAN)
  19023. # define SQLITE_ALLOW_COVERING_INDEX_SCAN 1
  19024. #else
  19025. # if !SQLITE_ALLOW_COVERING_INDEX_SCAN
  19026. # error "Compile-time disabling of covering index scan using the\
  19027. -DSQLITE_ALLOW_COVERING_INDEX_SCAN=0 option is deprecated.\
  19028. Contact SQLite developers if this is a problem for you, and\
  19029. delete this #error macro to continue with your build."
  19030. # endif
  19031. #endif
  19032. /* The minimum PMA size is set to this value multiplied by the database
  19033. ** page size in bytes.
  19034. */
  19035. #ifndef SQLITE_SORTER_PMASZ
  19036. # define SQLITE_SORTER_PMASZ 250
  19037. #endif
  19038. /* Statement journals spill to disk when their size exceeds the following
  19039. ** threshold (in bytes). 0 means that statement journals are created and
  19040. ** written to disk immediately (the default behavior for SQLite versions
  19041. ** before 3.12.0). -1 means always keep the entire statement journal in
  19042. ** memory. (The statement journal is also always held entirely in memory
  19043. ** if journal_mode=MEMORY or if temp_store=MEMORY, regardless of this
  19044. ** setting.)
  19045. */
  19046. #ifndef SQLITE_STMTJRNL_SPILL
  19047. # define SQLITE_STMTJRNL_SPILL (64*1024)
  19048. #endif
  19049. /*
  19050. ** The default lookaside-configuration, the format "SZ,N". SZ is the
  19051. ** number of bytes in each lookaside slot (should be a multiple of 8)
  19052. ** and N is the number of slots. The lookaside-configuration can be
  19053. ** changed as start-time using sqlite3_config(SQLITE_CONFIG_LOOKASIDE)
  19054. ** or at run-time for an individual database connection using
  19055. ** sqlite3_db_config(db, SQLITE_DBCONFIG_LOOKASIDE);
  19056. */
  19057. #ifndef SQLITE_DEFAULT_LOOKASIDE
  19058. # define SQLITE_DEFAULT_LOOKASIDE 1200,100
  19059. #endif
  19060. /* The default maximum size of an in-memory database created using
  19061. ** sqlite3_deserialize()
  19062. */
  19063. #ifndef SQLITE_MEMDB_DEFAULT_MAXSIZE
  19064. # define SQLITE_MEMDB_DEFAULT_MAXSIZE 1073741824
  19065. #endif
  19066. /*
  19067. ** The following singleton contains the global configuration for
  19068. ** the SQLite library.
  19069. */
  19070. SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
  19071. SQLITE_DEFAULT_MEMSTATUS, /* bMemstat */
  19072. 1, /* bCoreMutex */
  19073. SQLITE_THREADSAFE==1, /* bFullMutex */
  19074. SQLITE_USE_URI, /* bOpenUri */
  19075. SQLITE_ALLOW_COVERING_INDEX_SCAN, /* bUseCis */
  19076. 0, /* bSmallMalloc */
  19077. 0x7ffffffe, /* mxStrlen */
  19078. 0, /* neverCorrupt */
  19079. SQLITE_DEFAULT_LOOKASIDE, /* szLookaside, nLookaside */
  19080. SQLITE_STMTJRNL_SPILL, /* nStmtSpill */
  19081. {0,0,0,0,0,0,0,0}, /* m */
  19082. {0,0,0,0,0,0,0,0,0}, /* mutex */
  19083. {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
  19084. (void*)0, /* pHeap */
  19085. 0, /* nHeap */
  19086. 0, 0, /* mnHeap, mxHeap */
  19087. SQLITE_DEFAULT_MMAP_SIZE, /* szMmap */
  19088. SQLITE_MAX_MMAP_SIZE, /* mxMmap */
  19089. (void*)0, /* pPage */
  19090. 0, /* szPage */
  19091. SQLITE_DEFAULT_PCACHE_INITSZ, /* nPage */
  19092. 0, /* mxParserStack */
  19093. 0, /* sharedCacheEnabled */
  19094. SQLITE_SORTER_PMASZ, /* szPma */
  19095. /* All the rest should always be initialized to zero */
  19096. 0, /* isInit */
  19097. 0, /* inProgress */
  19098. 0, /* isMutexInit */
  19099. 0, /* isMallocInit */
  19100. 0, /* isPCacheInit */
  19101. 0, /* nRefInitMutex */
  19102. 0, /* pInitMutex */
  19103. 0, /* xLog */
  19104. 0, /* pLogArg */
  19105. #ifdef SQLITE_ENABLE_SQLLOG
  19106. 0, /* xSqllog */
  19107. 0, /* pSqllogArg */
  19108. #endif
  19109. #ifdef SQLITE_VDBE_COVERAGE
  19110. 0, /* xVdbeBranch */
  19111. 0, /* pVbeBranchArg */
  19112. #endif
  19113. #ifdef SQLITE_ENABLE_DESERIALIZE
  19114. SQLITE_MEMDB_DEFAULT_MAXSIZE, /* mxMemdbSize */
  19115. #endif
  19116. #ifndef SQLITE_UNTESTABLE
  19117. 0, /* xTestCallback */
  19118. #endif
  19119. 0, /* bLocaltimeFault */
  19120. 0, /* bInternalFunctions */
  19121. 0x7ffffffe, /* iOnceResetThreshold */
  19122. SQLITE_DEFAULT_SORTERREF_SIZE, /* szSorterRef */
  19123. };
  19124. /*
  19125. ** Hash table for global functions - functions common to all
  19126. ** database connections. After initialization, this table is
  19127. ** read-only.
  19128. */
  19129. SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;
  19130. /*
  19131. ** Constant tokens for values 0 and 1.
  19132. */
  19133. SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
  19134. { "0", 1 },
  19135. { "1", 1 }
  19136. };
  19137. #ifdef VDBE_PROFILE
  19138. /*
  19139. ** The following performance counter can be used in place of
  19140. ** sqlite3Hwtime() for profiling. This is a no-op on standard builds.
  19141. */
  19142. SQLITE_PRIVATE sqlite3_uint64 sqlite3NProfileCnt = 0;
  19143. #endif
  19144. /*
  19145. ** The value of the "pending" byte must be 0x40000000 (1 byte past the
  19146. ** 1-gibabyte boundary) in a compatible database. SQLite never uses
  19147. ** the database page that contains the pending byte. It never attempts
  19148. ** to read or write that page. The pending byte page is set aside
  19149. ** for use by the VFS layers as space for managing file locks.
  19150. **
  19151. ** During testing, it is often desirable to move the pending byte to
  19152. ** a different position in the file. This allows code that has to
  19153. ** deal with the pending byte to run on files that are much smaller
  19154. ** than 1 GiB. The sqlite3_test_control() interface can be used to
  19155. ** move the pending byte.
  19156. **
  19157. ** IMPORTANT: Changing the pending byte to any value other than
  19158. ** 0x40000000 results in an incompatible database file format!
  19159. ** Changing the pending byte during operation will result in undefined
  19160. ** and incorrect behavior.
  19161. */
  19162. #ifndef SQLITE_OMIT_WSD
  19163. SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
  19164. #endif
  19165. /* #include "opcodes.h" */
  19166. /*
  19167. ** Properties of opcodes. The OPFLG_INITIALIZER macro is
  19168. ** created by mkopcodeh.awk during compilation. Data is obtained
  19169. ** from the comments following the "case OP_xxxx:" statements in
  19170. ** the vdbe.c file.
  19171. */
  19172. SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
  19173. /*
  19174. ** Name of the default collating sequence
  19175. */
  19176. SQLITE_PRIVATE const char sqlite3StrBINARY[] = "BINARY";
  19177. /************** End of global.c **********************************************/
  19178. /************** Begin file status.c ******************************************/
  19179. /*
  19180. ** 2008 June 18
  19181. **
  19182. ** The author disclaims copyright to this source code. In place of
  19183. ** a legal notice, here is a blessing:
  19184. **
  19185. ** May you do good and not evil.
  19186. ** May you find forgiveness for yourself and forgive others.
  19187. ** May you share freely, never taking more than you give.
  19188. **
  19189. *************************************************************************
  19190. **
  19191. ** This module implements the sqlite3_status() interface and related
  19192. ** functionality.
  19193. */
  19194. /* #include "sqliteInt.h" */
  19195. /************** Include vdbeInt.h in the middle of status.c ******************/
  19196. /************** Begin file vdbeInt.h *****************************************/
  19197. /*
  19198. ** 2003 September 6
  19199. **
  19200. ** The author disclaims copyright to this source code. In place of
  19201. ** a legal notice, here is a blessing:
  19202. **
  19203. ** May you do good and not evil.
  19204. ** May you find forgiveness for yourself and forgive others.
  19205. ** May you share freely, never taking more than you give.
  19206. **
  19207. *************************************************************************
  19208. ** This is the header file for information that is private to the
  19209. ** VDBE. This information used to all be at the top of the single
  19210. ** source code file "vdbe.c". When that file became too big (over
  19211. ** 6000 lines long) it was split up into several smaller files and
  19212. ** this header information was factored out.
  19213. */
  19214. #ifndef SQLITE_VDBEINT_H
  19215. #define SQLITE_VDBEINT_H
  19216. /*
  19217. ** The maximum number of times that a statement will try to reparse
  19218. ** itself before giving up and returning SQLITE_SCHEMA.
  19219. */
  19220. #ifndef SQLITE_MAX_SCHEMA_RETRY
  19221. # define SQLITE_MAX_SCHEMA_RETRY 50
  19222. #endif
  19223. /*
  19224. ** VDBE_DISPLAY_P4 is true or false depending on whether or not the
  19225. ** "explain" P4 display logic is enabled.
  19226. */
  19227. #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
  19228. || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  19229. # define VDBE_DISPLAY_P4 1
  19230. #else
  19231. # define VDBE_DISPLAY_P4 0
  19232. #endif
  19233. /*
  19234. ** SQL is translated into a sequence of instructions to be
  19235. ** executed by a virtual machine. Each instruction is an instance
  19236. ** of the following structure.
  19237. */
  19238. typedef struct VdbeOp Op;
  19239. /*
  19240. ** Boolean values
  19241. */
  19242. typedef unsigned Bool;
  19243. /* Opaque type used by code in vdbesort.c */
  19244. typedef struct VdbeSorter VdbeSorter;
  19245. /* Elements of the linked list at Vdbe.pAuxData */
  19246. typedef struct AuxData AuxData;
  19247. /* Types of VDBE cursors */
  19248. #define CURTYPE_BTREE 0
  19249. #define CURTYPE_SORTER 1
  19250. #define CURTYPE_VTAB 2
  19251. #define CURTYPE_PSEUDO 3
  19252. /*
  19253. ** A VdbeCursor is an superclass (a wrapper) for various cursor objects:
  19254. **
  19255. ** * A b-tree cursor
  19256. ** - In the main database or in an ephemeral database
  19257. ** - On either an index or a table
  19258. ** * A sorter
  19259. ** * A virtual table
  19260. ** * A one-row "pseudotable" stored in a single register
  19261. */
  19262. typedef struct VdbeCursor VdbeCursor;
  19263. struct VdbeCursor {
  19264. u8 eCurType; /* One of the CURTYPE_* values above */
  19265. i8 iDb; /* Index of cursor database in db->aDb[] (or -1) */
  19266. u8 nullRow; /* True if pointing to a row with no data */
  19267. u8 deferredMoveto; /* A call to sqlite3BtreeMoveto() is needed */
  19268. u8 isTable; /* True for rowid tables. False for indexes */
  19269. #ifdef SQLITE_DEBUG
  19270. u8 seekOp; /* Most recent seek operation on this cursor */
  19271. u8 wrFlag; /* The wrFlag argument to sqlite3BtreeCursor() */
  19272. #endif
  19273. Bool isEphemeral:1; /* True for an ephemeral table */
  19274. Bool useRandomRowid:1; /* Generate new record numbers semi-randomly */
  19275. Bool isOrdered:1; /* True if the table is not BTREE_UNORDERED */
  19276. Bool seekHit:1; /* See the OP_SeekHit and OP_IfNoHope opcodes */
  19277. Btree *pBtx; /* Separate file holding temporary table */
  19278. i64 seqCount; /* Sequence counter */
  19279. int *aAltMap; /* Mapping from table to index column numbers */
  19280. /* Cached OP_Column parse information is only valid if cacheStatus matches
  19281. ** Vdbe.cacheCtr. Vdbe.cacheCtr will never take on the value of
  19282. ** CACHE_STALE (0) and so setting cacheStatus=CACHE_STALE guarantees that
  19283. ** the cache is out of date. */
  19284. u32 cacheStatus; /* Cache is valid if this matches Vdbe.cacheCtr */
  19285. int seekResult; /* Result of previous sqlite3BtreeMoveto() or 0
  19286. ** if there have been no prior seeks on the cursor. */
  19287. /* seekResult does not distinguish between "no seeks have ever occurred
  19288. ** on this cursor" and "the most recent seek was an exact match".
  19289. ** For CURTYPE_PSEUDO, seekResult is the register holding the record */
  19290. /* When a new VdbeCursor is allocated, only the fields above are zeroed.
  19291. ** The fields that follow are uninitialized, and must be individually
  19292. ** initialized prior to first use. */
  19293. VdbeCursor *pAltCursor; /* Associated index cursor from which to read */
  19294. union {
  19295. BtCursor *pCursor; /* CURTYPE_BTREE or _PSEUDO. Btree cursor */
  19296. sqlite3_vtab_cursor *pVCur; /* CURTYPE_VTAB. Vtab cursor */
  19297. VdbeSorter *pSorter; /* CURTYPE_SORTER. Sorter object */
  19298. } uc;
  19299. KeyInfo *pKeyInfo; /* Info about index keys needed by index cursors */
  19300. u32 iHdrOffset; /* Offset to next unparsed byte of the header */
  19301. Pgno pgnoRoot; /* Root page of the open btree cursor */
  19302. i16 nField; /* Number of fields in the header */
  19303. u16 nHdrParsed; /* Number of header fields parsed so far */
  19304. i64 movetoTarget; /* Argument to the deferred sqlite3BtreeMoveto() */
  19305. u32 *aOffset; /* Pointer to aType[nField] */
  19306. const u8 *aRow; /* Data for the current row, if all on one page */
  19307. u32 payloadSize; /* Total number of bytes in the record */
  19308. u32 szRow; /* Byte available in aRow */
  19309. #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
  19310. u64 maskUsed; /* Mask of columns used by this cursor */
  19311. #endif
  19312. /* 2*nField extra array elements allocated for aType[], beyond the one
  19313. ** static element declared in the structure. nField total array slots for
  19314. ** aType[] and nField+1 array slots for aOffset[] */
  19315. u32 aType[1]; /* Type values record decode. MUST BE LAST */
  19316. };
  19317. /*
  19318. ** A value for VdbeCursor.cacheStatus that means the cache is always invalid.
  19319. */
  19320. #define CACHE_STALE 0
  19321. /*
  19322. ** When a sub-program is executed (OP_Program), a structure of this type
  19323. ** is allocated to store the current value of the program counter, as
  19324. ** well as the current memory cell array and various other frame specific
  19325. ** values stored in the Vdbe struct. When the sub-program is finished,
  19326. ** these values are copied back to the Vdbe from the VdbeFrame structure,
  19327. ** restoring the state of the VM to as it was before the sub-program
  19328. ** began executing.
  19329. **
  19330. ** The memory for a VdbeFrame object is allocated and managed by a memory
  19331. ** cell in the parent (calling) frame. When the memory cell is deleted or
  19332. ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
  19333. ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
  19334. ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
  19335. ** this instead of deleting the VdbeFrame immediately is to avoid recursive
  19336. ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
  19337. ** child frame are released.
  19338. **
  19339. ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
  19340. ** set to NULL if the currently executing frame is the main program.
  19341. */
  19342. typedef struct VdbeFrame VdbeFrame;
  19343. struct VdbeFrame {
  19344. Vdbe *v; /* VM this frame belongs to */
  19345. VdbeFrame *pParent; /* Parent of this frame, or NULL if parent is main */
  19346. Op *aOp; /* Program instructions for parent frame */
  19347. i64 *anExec; /* Event counters from parent frame */
  19348. Mem *aMem; /* Array of memory cells for parent frame */
  19349. VdbeCursor **apCsr; /* Array of Vdbe cursors for parent frame */
  19350. u8 *aOnce; /* Bitmask used by OP_Once */
  19351. void *token; /* Copy of SubProgram.token */
  19352. i64 lastRowid; /* Last insert rowid (sqlite3.lastRowid) */
  19353. AuxData *pAuxData; /* Linked list of auxdata allocations */
  19354. #if SQLITE_DEBUG
  19355. u32 iFrameMagic; /* magic number for sanity checking */
  19356. #endif
  19357. int nCursor; /* Number of entries in apCsr */
  19358. int pc; /* Program Counter in parent (calling) frame */
  19359. int nOp; /* Size of aOp array */
  19360. int nMem; /* Number of entries in aMem */
  19361. int nChildMem; /* Number of memory cells for child frame */
  19362. int nChildCsr; /* Number of cursors for child frame */
  19363. int nChange; /* Statement changes (Vdbe.nChange) */
  19364. int nDbChange; /* Value of db->nChange */
  19365. };
  19366. /* Magic number for sanity checking on VdbeFrame objects */
  19367. #define SQLITE_FRAME_MAGIC 0x879fb71e
  19368. /*
  19369. ** Return a pointer to the array of registers allocated for use
  19370. ** by a VdbeFrame.
  19371. */
  19372. #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
  19373. /*
  19374. ** Internally, the vdbe manipulates nearly all SQL values as Mem
  19375. ** structures. Each Mem struct may cache multiple representations (string,
  19376. ** integer etc.) of the same value.
  19377. */
  19378. struct sqlite3_value {
  19379. union MemValue {
  19380. double r; /* Real value used when MEM_Real is set in flags */
  19381. i64 i; /* Integer value used when MEM_Int is set in flags */
  19382. int nZero; /* Extra zero bytes when MEM_Zero and MEM_Blob set */
  19383. const char *zPType; /* Pointer type when MEM_Term|MEM_Subtype|MEM_Null */
  19384. FuncDef *pDef; /* Used only when flags==MEM_Agg */
  19385. } u;
  19386. u16 flags; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
  19387. u8 enc; /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
  19388. u8 eSubtype; /* Subtype for this value */
  19389. int n; /* Number of characters in string value, excluding '\0' */
  19390. char *z; /* String or BLOB value */
  19391. /* ShallowCopy only needs to copy the information above */
  19392. char *zMalloc; /* Space to hold MEM_Str or MEM_Blob if szMalloc>0 */
  19393. int szMalloc; /* Size of the zMalloc allocation */
  19394. u32 uTemp; /* Transient storage for serial_type in OP_MakeRecord */
  19395. sqlite3 *db; /* The associated database connection */
  19396. void (*xDel)(void*);/* Destructor for Mem.z - only valid if MEM_Dyn */
  19397. #ifdef SQLITE_DEBUG
  19398. Mem *pScopyFrom; /* This Mem is a shallow copy of pScopyFrom */
  19399. u16 mScopyFlags; /* flags value immediately after the shallow copy */
  19400. #endif
  19401. };
  19402. /*
  19403. ** Size of struct Mem not including the Mem.zMalloc member or anything that
  19404. ** follows.
  19405. */
  19406. #define MEMCELLSIZE offsetof(Mem,zMalloc)
  19407. /* One or more of the following flags are set to indicate the validOK
  19408. ** representations of the value stored in the Mem struct.
  19409. **
  19410. ** If the MEM_Null flag is set, then the value is an SQL NULL value.
  19411. ** For a pointer type created using sqlite3_bind_pointer() or
  19412. ** sqlite3_result_pointer() the MEM_Term and MEM_Subtype flags are also set.
  19413. **
  19414. ** If the MEM_Str flag is set then Mem.z points at a string representation.
  19415. ** Usually this is encoded in the same unicode encoding as the main
  19416. ** database (see below for exceptions). If the MEM_Term flag is also
  19417. ** set, then the string is nul terminated. The MEM_Int and MEM_Real
  19418. ** flags may coexist with the MEM_Str flag.
  19419. */
  19420. #define MEM_Null 0x0001 /* Value is NULL (or a pointer) */
  19421. #define MEM_Str 0x0002 /* Value is a string */
  19422. #define MEM_Int 0x0004 /* Value is an integer */
  19423. #define MEM_Real 0x0008 /* Value is a real number */
  19424. #define MEM_Blob 0x0010 /* Value is a BLOB */
  19425. #define MEM_IntReal 0x0020 /* MEM_Int that stringifies like MEM_Real */
  19426. #define MEM_AffMask 0x003f /* Mask of affinity bits */
  19427. #define MEM_FromBind 0x0040 /* Value originates from sqlite3_bind() */
  19428. #define MEM_Undefined 0x0080 /* Value is undefined */
  19429. #define MEM_Cleared 0x0100 /* NULL set by OP_Null, not from data */
  19430. #define MEM_TypeMask 0xc1bf /* Mask of type bits */
  19431. /* Whenever Mem contains a valid string or blob representation, one of
  19432. ** the following flags must be set to determine the memory management
  19433. ** policy for Mem.z. The MEM_Term flag tells us whether or not the
  19434. ** string is \000 or \u0000 terminated
  19435. */
  19436. #define MEM_Term 0x0200 /* String in Mem.z is zero terminated */
  19437. #define MEM_Dyn 0x0400 /* Need to call Mem.xDel() on Mem.z */
  19438. #define MEM_Static 0x0800 /* Mem.z points to a static string */
  19439. #define MEM_Ephem 0x1000 /* Mem.z points to an ephemeral string */
  19440. #define MEM_Agg 0x2000 /* Mem.z points to an agg function context */
  19441. #define MEM_Zero 0x4000 /* Mem.i contains count of 0s appended to blob */
  19442. #define MEM_Subtype 0x8000 /* Mem.eSubtype is valid */
  19443. #ifdef SQLITE_OMIT_INCRBLOB
  19444. #undef MEM_Zero
  19445. #define MEM_Zero 0x0000
  19446. #endif
  19447. /* Return TRUE if Mem X contains dynamically allocated content - anything
  19448. ** that needs to be deallocated to avoid a leak.
  19449. */
  19450. #define VdbeMemDynamic(X) \
  19451. (((X)->flags&(MEM_Agg|MEM_Dyn))!=0)
  19452. /*
  19453. ** Clear any existing type flags from a Mem and replace them with f
  19454. */
  19455. #define MemSetTypeFlag(p, f) \
  19456. ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
  19457. /*
  19458. ** True if Mem X is a NULL-nochng type.
  19459. */
  19460. #define MemNullNochng(X) \
  19461. ((X)->flags==(MEM_Null|MEM_Zero) && (X)->n==0 && (X)->u.nZero==0)
  19462. /*
  19463. ** Return true if a memory cell is not marked as invalid. This macro
  19464. ** is for use inside assert() statements only.
  19465. */
  19466. #ifdef SQLITE_DEBUG
  19467. #define memIsValid(M) ((M)->flags & MEM_Undefined)==0
  19468. #endif
  19469. /*
  19470. ** Each auxiliary data pointer stored by a user defined function
  19471. ** implementation calling sqlite3_set_auxdata() is stored in an instance
  19472. ** of this structure. All such structures associated with a single VM
  19473. ** are stored in a linked list headed at Vdbe.pAuxData. All are destroyed
  19474. ** when the VM is halted (if not before).
  19475. */
  19476. struct AuxData {
  19477. int iAuxOp; /* Instruction number of OP_Function opcode */
  19478. int iAuxArg; /* Index of function argument. */
  19479. void *pAux; /* Aux data pointer */
  19480. void (*xDeleteAux)(void*); /* Destructor for the aux data */
  19481. AuxData *pNextAux; /* Next element in list */
  19482. };
  19483. /*
  19484. ** The "context" argument for an installable function. A pointer to an
  19485. ** instance of this structure is the first argument to the routines used
  19486. ** implement the SQL functions.
  19487. **
  19488. ** There is a typedef for this structure in sqlite.h. So all routines,
  19489. ** even the public interface to SQLite, can use a pointer to this structure.
  19490. ** But this file is the only place where the internal details of this
  19491. ** structure are known.
  19492. **
  19493. ** This structure is defined inside of vdbeInt.h because it uses substructures
  19494. ** (Mem) which are only defined there.
  19495. */
  19496. struct sqlite3_context {
  19497. Mem *pOut; /* The return value is stored here */
  19498. FuncDef *pFunc; /* Pointer to function information */
  19499. Mem *pMem; /* Memory cell used to store aggregate context */
  19500. Vdbe *pVdbe; /* The VM that owns this context */
  19501. int iOp; /* Instruction number of OP_Function */
  19502. int isError; /* Error code returned by the function. */
  19503. u8 skipFlag; /* Skip accumulator loading if true */
  19504. u8 argc; /* Number of arguments */
  19505. sqlite3_value *argv[1]; /* Argument set */
  19506. };
  19507. /* A bitfield type for use inside of structures. Always follow with :N where
  19508. ** N is the number of bits.
  19509. */
  19510. typedef unsigned bft; /* Bit Field Type */
  19511. /* The ScanStatus object holds a single value for the
  19512. ** sqlite3_stmt_scanstatus() interface.
  19513. */
  19514. typedef struct ScanStatus ScanStatus;
  19515. struct ScanStatus {
  19516. int addrExplain; /* OP_Explain for loop */
  19517. int addrLoop; /* Address of "loops" counter */
  19518. int addrVisit; /* Address of "rows visited" counter */
  19519. int iSelectID; /* The "Select-ID" for this loop */
  19520. LogEst nEst; /* Estimated output rows per loop */
  19521. char *zName; /* Name of table or index */
  19522. };
  19523. /* The DblquoteStr object holds the text of a double-quoted
  19524. ** string for a prepared statement. A linked list of these objects
  19525. ** is constructed during statement parsing and is held on Vdbe.pDblStr.
  19526. ** When computing a normalized SQL statement for an SQL statement, that
  19527. ** list is consulted for each double-quoted identifier to see if the
  19528. ** identifier should really be a string literal.
  19529. */
  19530. typedef struct DblquoteStr DblquoteStr;
  19531. struct DblquoteStr {
  19532. DblquoteStr *pNextStr; /* Next string literal in the list */
  19533. char z[8]; /* Dequoted value for the string */
  19534. };
  19535. /*
  19536. ** An instance of the virtual machine. This structure contains the complete
  19537. ** state of the virtual machine.
  19538. **
  19539. ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
  19540. ** is really a pointer to an instance of this structure.
  19541. */
  19542. struct Vdbe {
  19543. sqlite3 *db; /* The database connection that owns this statement */
  19544. Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */
  19545. Parse *pParse; /* Parsing context used to create this Vdbe */
  19546. ynVar nVar; /* Number of entries in aVar[] */
  19547. u32 magic; /* Magic number for sanity checking */
  19548. int nMem; /* Number of memory locations currently allocated */
  19549. int nCursor; /* Number of slots in apCsr[] */
  19550. u32 cacheCtr; /* VdbeCursor row cache generation counter */
  19551. int pc; /* The program counter */
  19552. int rc; /* Value to return */
  19553. int nChange; /* Number of db changes made since last reset */
  19554. int iStatement; /* Statement number (or 0 if has no opened stmt) */
  19555. i64 iCurrentTime; /* Value of julianday('now') for this statement */
  19556. i64 nFkConstraint; /* Number of imm. FK constraints this VM */
  19557. i64 nStmtDefCons; /* Number of def. constraints when stmt started */
  19558. i64 nStmtDefImmCons; /* Number of def. imm constraints when stmt started */
  19559. Mem *aMem; /* The memory locations */
  19560. Mem **apArg; /* Arguments to currently executing user function */
  19561. VdbeCursor **apCsr; /* One element of this array for each open cursor */
  19562. Mem *aVar; /* Values for the OP_Variable opcode. */
  19563. /* When allocating a new Vdbe object, all of the fields below should be
  19564. ** initialized to zero or NULL */
  19565. Op *aOp; /* Space to hold the virtual machine's program */
  19566. int nOp; /* Number of instructions in the program */
  19567. int nOpAlloc; /* Slots allocated for aOp[] */
  19568. Mem *aColName; /* Column names to return */
  19569. Mem *pResultSet; /* Pointer to an array of results */
  19570. char *zErrMsg; /* Error message written here */
  19571. VList *pVList; /* Name of variables */
  19572. #ifndef SQLITE_OMIT_TRACE
  19573. i64 startTime; /* Time when query started - used for profiling */
  19574. #endif
  19575. #ifdef SQLITE_DEBUG
  19576. int rcApp; /* errcode set by sqlite3_result_error_code() */
  19577. u32 nWrite; /* Number of write operations that have occurred */
  19578. #endif
  19579. u16 nResColumn; /* Number of columns in one row of the result set */
  19580. u8 errorAction; /* Recovery action to do in case of an error */
  19581. u8 minWriteFileFormat; /* Minimum file format for writable database files */
  19582. u8 prepFlags; /* SQLITE_PREPARE_* flags */
  19583. bft expired:2; /* 1: recompile VM immediately 2: when convenient */
  19584. bft explain:2; /* True if EXPLAIN present on SQL command */
  19585. bft doingRerun:1; /* True if rerunning after an auto-reprepare */
  19586. bft changeCntOn:1; /* True to update the change-counter */
  19587. bft runOnlyOnce:1; /* Automatically expire on reset */
  19588. bft usesStmtJournal:1; /* True if uses a statement journal */
  19589. bft readOnly:1; /* True for statements that do not write */
  19590. bft bIsReader:1; /* True for statements that read */
  19591. yDbMask btreeMask; /* Bitmask of db->aDb[] entries referenced */
  19592. yDbMask lockMask; /* Subset of btreeMask that requires a lock */
  19593. u32 aCounter[7]; /* Counters used by sqlite3_stmt_status() */
  19594. char *zSql; /* Text of the SQL statement that generated this */
  19595. #ifdef SQLITE_ENABLE_NORMALIZE
  19596. char *zNormSql; /* Normalization of the associated SQL statement */
  19597. DblquoteStr *pDblStr; /* List of double-quoted string literals */
  19598. #endif
  19599. void *pFree; /* Free this when deleting the vdbe */
  19600. VdbeFrame *pFrame; /* Parent frame */
  19601. VdbeFrame *pDelFrame; /* List of frame objects to free on VM reset */
  19602. int nFrame; /* Number of frames in pFrame list */
  19603. u32 expmask; /* Binding to these vars invalidates VM */
  19604. SubProgram *pProgram; /* Linked list of all sub-programs used by VM */
  19605. AuxData *pAuxData; /* Linked list of auxdata allocations */
  19606. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  19607. i64 *anExec; /* Number of times each op has been executed */
  19608. int nScan; /* Entries in aScan[] */
  19609. ScanStatus *aScan; /* Scan definitions for sqlite3_stmt_scanstatus() */
  19610. #endif
  19611. };
  19612. /*
  19613. ** The following are allowed values for Vdbe.magic
  19614. */
  19615. #define VDBE_MAGIC_INIT 0x16bceaa5 /* Building a VDBE program */
  19616. #define VDBE_MAGIC_RUN 0x2df20da3 /* VDBE is ready to execute */
  19617. #define VDBE_MAGIC_HALT 0x319c2973 /* VDBE has completed execution */
  19618. #define VDBE_MAGIC_RESET 0x48fa9f76 /* Reset and ready to run again */
  19619. #define VDBE_MAGIC_DEAD 0x5606c3c8 /* The VDBE has been deallocated */
  19620. /*
  19621. ** Structure used to store the context required by the
  19622. ** sqlite3_preupdate_*() API functions.
  19623. */
  19624. struct PreUpdate {
  19625. Vdbe *v;
  19626. VdbeCursor *pCsr; /* Cursor to read old values from */
  19627. int op; /* One of SQLITE_INSERT, UPDATE, DELETE */
  19628. u8 *aRecord; /* old.* database record */
  19629. KeyInfo keyinfo;
  19630. UnpackedRecord *pUnpacked; /* Unpacked version of aRecord[] */
  19631. UnpackedRecord *pNewUnpacked; /* Unpacked version of new.* record */
  19632. int iNewReg; /* Register for new.* values */
  19633. i64 iKey1; /* First key value passed to hook */
  19634. i64 iKey2; /* Second key value passed to hook */
  19635. Mem *aNew; /* Array of new.* values */
  19636. Table *pTab; /* Schema object being upated */
  19637. Index *pPk; /* PK index if pTab is WITHOUT ROWID */
  19638. };
  19639. /*
  19640. ** Function prototypes
  19641. */
  19642. SQLITE_PRIVATE void sqlite3VdbeError(Vdbe*, const char *, ...);
  19643. SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
  19644. void sqliteVdbePopStack(Vdbe*,int);
  19645. SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor**, int*);
  19646. SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor*);
  19647. SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
  19648. SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8);
  19649. SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int, u32*);
  19650. SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, Mem*, u32);
  19651. SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
  19652. SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3*, AuxData**, int, int);
  19653. int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
  19654. SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(sqlite3*,VdbeCursor*,UnpackedRecord*,int*);
  19655. SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor*, i64*);
  19656. SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
  19657. #ifndef SQLITE_OMIT_EXPLAIN
  19658. SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
  19659. #endif
  19660. SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
  19661. SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
  19662. SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
  19663. SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
  19664. SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
  19665. SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
  19666. SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
  19667. SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
  19668. SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
  19669. #ifdef SQLITE_OMIT_FLOATING_POINT
  19670. # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
  19671. #else
  19672. SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double);
  19673. #endif
  19674. SQLITE_PRIVATE void sqlite3VdbeMemSetPointer(Mem*, void*, const char*, void(*)(void*));
  19675. SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem*,sqlite3*,u16);
  19676. SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
  19677. SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
  19678. #ifdef SQLITE_DEBUG
  19679. SQLITE_PRIVATE int sqlite3VdbeMemIsRowSet(const Mem*);
  19680. #endif
  19681. SQLITE_PRIVATE int sqlite3VdbeMemSetRowSet(Mem*);
  19682. SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
  19683. SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, u8, u8);
  19684. SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
  19685. SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
  19686. SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
  19687. SQLITE_PRIVATE int sqlite3VdbeBooleanValue(Mem*, int ifNull);
  19688. SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
  19689. SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
  19690. SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
  19691. SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem*,u8,u8);
  19692. SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,u32,u32,Mem*);
  19693. SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
  19694. SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
  19695. #ifndef SQLITE_OMIT_WINDOWFUNC
  19696. SQLITE_PRIVATE int sqlite3VdbeMemAggValue(Mem*, Mem*, FuncDef*);
  19697. #endif
  19698. #ifndef SQLITE_OMIT_EXPLAIN
  19699. SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
  19700. #endif
  19701. SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
  19702. SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int n);
  19703. SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
  19704. #ifdef SQLITE_DEBUG
  19705. SQLITE_PRIVATE int sqlite3VdbeFrameIsValid(VdbeFrame*);
  19706. #endif
  19707. SQLITE_PRIVATE void sqlite3VdbeFrameMemDel(void*); /* Destructor on Mem */
  19708. SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*); /* Actually deletes the Frame */
  19709. SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
  19710. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  19711. SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(Vdbe*,VdbeCursor*,int,const char*,Table*,i64,int);
  19712. #endif
  19713. SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
  19714. SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, int, VdbeCursor *);
  19715. SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *, VdbeSorter *);
  19716. SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
  19717. SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *);
  19718. SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *);
  19719. SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *, int *);
  19720. SQLITE_PRIVATE int sqlite3VdbeSorterWrite(const VdbeCursor *, Mem *);
  19721. SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int, int *);
  19722. #ifdef SQLITE_DEBUG
  19723. SQLITE_PRIVATE void sqlite3VdbeIncrWriteCounter(Vdbe*, VdbeCursor*);
  19724. SQLITE_PRIVATE void sqlite3VdbeAssertAbortable(Vdbe*);
  19725. #else
  19726. # define sqlite3VdbeIncrWriteCounter(V,C)
  19727. # define sqlite3VdbeAssertAbortable(V)
  19728. #endif
  19729. #if !defined(SQLITE_OMIT_SHARED_CACHE)
  19730. SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe*);
  19731. #else
  19732. # define sqlite3VdbeEnter(X)
  19733. #endif
  19734. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
  19735. SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe*);
  19736. #else
  19737. # define sqlite3VdbeLeave(X)
  19738. #endif
  19739. #ifdef SQLITE_DEBUG
  19740. SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
  19741. SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem*);
  19742. #endif
  19743. #ifndef SQLITE_OMIT_FOREIGN_KEY
  19744. SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
  19745. #else
  19746. # define sqlite3VdbeCheckFk(p,i) 0
  19747. #endif
  19748. #ifdef SQLITE_DEBUG
  19749. SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe*);
  19750. SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
  19751. #endif
  19752. #ifndef SQLITE_OMIT_UTF16
  19753. SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
  19754. SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
  19755. #endif
  19756. #ifndef SQLITE_OMIT_INCRBLOB
  19757. SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *);
  19758. #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
  19759. #else
  19760. #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
  19761. #define ExpandBlob(P) SQLITE_OK
  19762. #endif
  19763. #endif /* !defined(SQLITE_VDBEINT_H) */
  19764. /************** End of vdbeInt.h *********************************************/
  19765. /************** Continuing where we left off in status.c *********************/
  19766. /*
  19767. ** Variables in which to record status information.
  19768. */
  19769. #if SQLITE_PTRSIZE>4
  19770. typedef sqlite3_int64 sqlite3StatValueType;
  19771. #else
  19772. typedef u32 sqlite3StatValueType;
  19773. #endif
  19774. typedef struct sqlite3StatType sqlite3StatType;
  19775. static SQLITE_WSD struct sqlite3StatType {
  19776. sqlite3StatValueType nowValue[10]; /* Current value */
  19777. sqlite3StatValueType mxValue[10]; /* Maximum value */
  19778. } sqlite3Stat = { {0,}, {0,} };
  19779. /*
  19780. ** Elements of sqlite3Stat[] are protected by either the memory allocator
  19781. ** mutex, or by the pcache1 mutex. The following array determines which.
  19782. */
  19783. static const char statMutex[] = {
  19784. 0, /* SQLITE_STATUS_MEMORY_USED */
  19785. 1, /* SQLITE_STATUS_PAGECACHE_USED */
  19786. 1, /* SQLITE_STATUS_PAGECACHE_OVERFLOW */
  19787. 0, /* SQLITE_STATUS_SCRATCH_USED */
  19788. 0, /* SQLITE_STATUS_SCRATCH_OVERFLOW */
  19789. 0, /* SQLITE_STATUS_MALLOC_SIZE */
  19790. 0, /* SQLITE_STATUS_PARSER_STACK */
  19791. 1, /* SQLITE_STATUS_PAGECACHE_SIZE */
  19792. 0, /* SQLITE_STATUS_SCRATCH_SIZE */
  19793. 0, /* SQLITE_STATUS_MALLOC_COUNT */
  19794. };
  19795. /* The "wsdStat" macro will resolve to the status information
  19796. ** state vector. If writable static data is unsupported on the target,
  19797. ** we have to locate the state vector at run-time. In the more common
  19798. ** case where writable static data is supported, wsdStat can refer directly
  19799. ** to the "sqlite3Stat" state vector declared above.
  19800. */
  19801. #ifdef SQLITE_OMIT_WSD
  19802. # define wsdStatInit sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
  19803. # define wsdStat x[0]
  19804. #else
  19805. # define wsdStatInit
  19806. # define wsdStat sqlite3Stat
  19807. #endif
  19808. /*
  19809. ** Return the current value of a status parameter. The caller must
  19810. ** be holding the appropriate mutex.
  19811. */
  19812. SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int op){
  19813. wsdStatInit;
  19814. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  19815. assert( op>=0 && op<ArraySize(statMutex) );
  19816. assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
  19817. : sqlite3MallocMutex()) );
  19818. return wsdStat.nowValue[op];
  19819. }
  19820. /*
  19821. ** Add N to the value of a status record. The caller must hold the
  19822. ** appropriate mutex. (Locking is checked by assert()).
  19823. **
  19824. ** The StatusUp() routine can accept positive or negative values for N.
  19825. ** The value of N is added to the current status value and the high-water
  19826. ** mark is adjusted if necessary.
  19827. **
  19828. ** The StatusDown() routine lowers the current value by N. The highwater
  19829. ** mark is unchanged. N must be non-negative for StatusDown().
  19830. */
  19831. SQLITE_PRIVATE void sqlite3StatusUp(int op, int N){
  19832. wsdStatInit;
  19833. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  19834. assert( op>=0 && op<ArraySize(statMutex) );
  19835. assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
  19836. : sqlite3MallocMutex()) );
  19837. wsdStat.nowValue[op] += N;
  19838. if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
  19839. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  19840. }
  19841. }
  19842. SQLITE_PRIVATE void sqlite3StatusDown(int op, int N){
  19843. wsdStatInit;
  19844. assert( N>=0 );
  19845. assert( op>=0 && op<ArraySize(statMutex) );
  19846. assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
  19847. : sqlite3MallocMutex()) );
  19848. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  19849. wsdStat.nowValue[op] -= N;
  19850. }
  19851. /*
  19852. ** Adjust the highwater mark if necessary.
  19853. ** The caller must hold the appropriate mutex.
  19854. */
  19855. SQLITE_PRIVATE void sqlite3StatusHighwater(int op, int X){
  19856. sqlite3StatValueType newValue;
  19857. wsdStatInit;
  19858. assert( X>=0 );
  19859. newValue = (sqlite3StatValueType)X;
  19860. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  19861. assert( op>=0 && op<ArraySize(statMutex) );
  19862. assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
  19863. : sqlite3MallocMutex()) );
  19864. assert( op==SQLITE_STATUS_MALLOC_SIZE
  19865. || op==SQLITE_STATUS_PAGECACHE_SIZE
  19866. || op==SQLITE_STATUS_PARSER_STACK );
  19867. if( newValue>wsdStat.mxValue[op] ){
  19868. wsdStat.mxValue[op] = newValue;
  19869. }
  19870. }
  19871. /*
  19872. ** Query status information.
  19873. */
  19874. SQLITE_API int sqlite3_status64(
  19875. int op,
  19876. sqlite3_int64 *pCurrent,
  19877. sqlite3_int64 *pHighwater,
  19878. int resetFlag
  19879. ){
  19880. sqlite3_mutex *pMutex;
  19881. wsdStatInit;
  19882. if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
  19883. return SQLITE_MISUSE_BKPT;
  19884. }
  19885. #ifdef SQLITE_ENABLE_API_ARMOR
  19886. if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
  19887. #endif
  19888. pMutex = statMutex[op] ? sqlite3Pcache1Mutex() : sqlite3MallocMutex();
  19889. sqlite3_mutex_enter(pMutex);
  19890. *pCurrent = wsdStat.nowValue[op];
  19891. *pHighwater = wsdStat.mxValue[op];
  19892. if( resetFlag ){
  19893. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  19894. }
  19895. sqlite3_mutex_leave(pMutex);
  19896. (void)pMutex; /* Prevent warning when SQLITE_THREADSAFE=0 */
  19897. return SQLITE_OK;
  19898. }
  19899. SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
  19900. sqlite3_int64 iCur = 0, iHwtr = 0;
  19901. int rc;
  19902. #ifdef SQLITE_ENABLE_API_ARMOR
  19903. if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
  19904. #endif
  19905. rc = sqlite3_status64(op, &iCur, &iHwtr, resetFlag);
  19906. if( rc==0 ){
  19907. *pCurrent = (int)iCur;
  19908. *pHighwater = (int)iHwtr;
  19909. }
  19910. return rc;
  19911. }
  19912. /*
  19913. ** Return the number of LookasideSlot elements on the linked list
  19914. */
  19915. static u32 countLookasideSlots(LookasideSlot *p){
  19916. u32 cnt = 0;
  19917. while( p ){
  19918. p = p->pNext;
  19919. cnt++;
  19920. }
  19921. return cnt;
  19922. }
  19923. /*
  19924. ** Count the number of slots of lookaside memory that are outstanding
  19925. */
  19926. SQLITE_PRIVATE int sqlite3LookasideUsed(sqlite3 *db, int *pHighwater){
  19927. u32 nInit = countLookasideSlots(db->lookaside.pInit);
  19928. u32 nFree = countLookasideSlots(db->lookaside.pFree);
  19929. if( pHighwater ) *pHighwater = db->lookaside.nSlot - nInit;
  19930. return db->lookaside.nSlot - (nInit+nFree);
  19931. }
  19932. /*
  19933. ** Query status information for a single database connection
  19934. */
  19935. SQLITE_API int sqlite3_db_status(
  19936. sqlite3 *db, /* The database connection whose status is desired */
  19937. int op, /* Status verb */
  19938. int *pCurrent, /* Write current value here */
  19939. int *pHighwater, /* Write high-water mark here */
  19940. int resetFlag /* Reset high-water mark if true */
  19941. ){
  19942. int rc = SQLITE_OK; /* Return code */
  19943. #ifdef SQLITE_ENABLE_API_ARMOR
  19944. if( !sqlite3SafetyCheckOk(db) || pCurrent==0|| pHighwater==0 ){
  19945. return SQLITE_MISUSE_BKPT;
  19946. }
  19947. #endif
  19948. sqlite3_mutex_enter(db->mutex);
  19949. switch( op ){
  19950. case SQLITE_DBSTATUS_LOOKASIDE_USED: {
  19951. *pCurrent = sqlite3LookasideUsed(db, pHighwater);
  19952. if( resetFlag ){
  19953. LookasideSlot *p = db->lookaside.pFree;
  19954. if( p ){
  19955. while( p->pNext ) p = p->pNext;
  19956. p->pNext = db->lookaside.pInit;
  19957. db->lookaside.pInit = db->lookaside.pFree;
  19958. db->lookaside.pFree = 0;
  19959. }
  19960. }
  19961. break;
  19962. }
  19963. case SQLITE_DBSTATUS_LOOKASIDE_HIT:
  19964. case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
  19965. case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
  19966. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
  19967. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
  19968. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
  19969. assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
  19970. assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
  19971. *pCurrent = 0;
  19972. *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
  19973. if( resetFlag ){
  19974. db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
  19975. }
  19976. break;
  19977. }
  19978. /*
  19979. ** Return an approximation for the amount of memory currently used
  19980. ** by all pagers associated with the given database connection. The
  19981. ** highwater mark is meaningless and is returned as zero.
  19982. */
  19983. case SQLITE_DBSTATUS_CACHE_USED_SHARED:
  19984. case SQLITE_DBSTATUS_CACHE_USED: {
  19985. int totalUsed = 0;
  19986. int i;
  19987. sqlite3BtreeEnterAll(db);
  19988. for(i=0; i<db->nDb; i++){
  19989. Btree *pBt = db->aDb[i].pBt;
  19990. if( pBt ){
  19991. Pager *pPager = sqlite3BtreePager(pBt);
  19992. int nByte = sqlite3PagerMemUsed(pPager);
  19993. if( op==SQLITE_DBSTATUS_CACHE_USED_SHARED ){
  19994. nByte = nByte / sqlite3BtreeConnectionCount(pBt);
  19995. }
  19996. totalUsed += nByte;
  19997. }
  19998. }
  19999. sqlite3BtreeLeaveAll(db);
  20000. *pCurrent = totalUsed;
  20001. *pHighwater = 0;
  20002. break;
  20003. }
  20004. /*
  20005. ** *pCurrent gets an accurate estimate of the amount of memory used
  20006. ** to store the schema for all databases (main, temp, and any ATTACHed
  20007. ** databases. *pHighwater is set to zero.
  20008. */
  20009. case SQLITE_DBSTATUS_SCHEMA_USED: {
  20010. int i; /* Used to iterate through schemas */
  20011. int nByte = 0; /* Used to accumulate return value */
  20012. sqlite3BtreeEnterAll(db);
  20013. db->pnBytesFreed = &nByte;
  20014. for(i=0; i<db->nDb; i++){
  20015. Schema *pSchema = db->aDb[i].pSchema;
  20016. if( ALWAYS(pSchema!=0) ){
  20017. HashElem *p;
  20018. nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
  20019. pSchema->tblHash.count
  20020. + pSchema->trigHash.count
  20021. + pSchema->idxHash.count
  20022. + pSchema->fkeyHash.count
  20023. );
  20024. nByte += sqlite3_msize(pSchema->tblHash.ht);
  20025. nByte += sqlite3_msize(pSchema->trigHash.ht);
  20026. nByte += sqlite3_msize(pSchema->idxHash.ht);
  20027. nByte += sqlite3_msize(pSchema->fkeyHash.ht);
  20028. for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
  20029. sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
  20030. }
  20031. for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
  20032. sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
  20033. }
  20034. }
  20035. }
  20036. db->pnBytesFreed = 0;
  20037. sqlite3BtreeLeaveAll(db);
  20038. *pHighwater = 0;
  20039. *pCurrent = nByte;
  20040. break;
  20041. }
  20042. /*
  20043. ** *pCurrent gets an accurate estimate of the amount of memory used
  20044. ** to store all prepared statements.
  20045. ** *pHighwater is set to zero.
  20046. */
  20047. case SQLITE_DBSTATUS_STMT_USED: {
  20048. struct Vdbe *pVdbe; /* Used to iterate through VMs */
  20049. int nByte = 0; /* Used to accumulate return value */
  20050. db->pnBytesFreed = &nByte;
  20051. for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
  20052. sqlite3VdbeClearObject(db, pVdbe);
  20053. sqlite3DbFree(db, pVdbe);
  20054. }
  20055. db->pnBytesFreed = 0;
  20056. *pHighwater = 0; /* IMP: R-64479-57858 */
  20057. *pCurrent = nByte;
  20058. break;
  20059. }
  20060. /*
  20061. ** Set *pCurrent to the total cache hits or misses encountered by all
  20062. ** pagers the database handle is connected to. *pHighwater is always set
  20063. ** to zero.
  20064. */
  20065. case SQLITE_DBSTATUS_CACHE_SPILL:
  20066. op = SQLITE_DBSTATUS_CACHE_WRITE+1;
  20067. /* Fall through into the next case */
  20068. case SQLITE_DBSTATUS_CACHE_HIT:
  20069. case SQLITE_DBSTATUS_CACHE_MISS:
  20070. case SQLITE_DBSTATUS_CACHE_WRITE:{
  20071. int i;
  20072. int nRet = 0;
  20073. assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
  20074. assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 );
  20075. for(i=0; i<db->nDb; i++){
  20076. if( db->aDb[i].pBt ){
  20077. Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
  20078. sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
  20079. }
  20080. }
  20081. *pHighwater = 0; /* IMP: R-42420-56072 */
  20082. /* IMP: R-54100-20147 */
  20083. /* IMP: R-29431-39229 */
  20084. *pCurrent = nRet;
  20085. break;
  20086. }
  20087. /* Set *pCurrent to non-zero if there are unresolved deferred foreign
  20088. ** key constraints. Set *pCurrent to zero if all foreign key constraints
  20089. ** have been satisfied. The *pHighwater is always set to zero.
  20090. */
  20091. case SQLITE_DBSTATUS_DEFERRED_FKS: {
  20092. *pHighwater = 0; /* IMP: R-11967-56545 */
  20093. *pCurrent = db->nDeferredImmCons>0 || db->nDeferredCons>0;
  20094. break;
  20095. }
  20096. default: {
  20097. rc = SQLITE_ERROR;
  20098. }
  20099. }
  20100. sqlite3_mutex_leave(db->mutex);
  20101. return rc;
  20102. }
  20103. /************** End of status.c **********************************************/
  20104. /************** Begin file date.c ********************************************/
  20105. /*
  20106. ** 2003 October 31
  20107. **
  20108. ** The author disclaims copyright to this source code. In place of
  20109. ** a legal notice, here is a blessing:
  20110. **
  20111. ** May you do good and not evil.
  20112. ** May you find forgiveness for yourself and forgive others.
  20113. ** May you share freely, never taking more than you give.
  20114. **
  20115. *************************************************************************
  20116. ** This file contains the C functions that implement date and time
  20117. ** functions for SQLite.
  20118. **
  20119. ** There is only one exported symbol in this file - the function
  20120. ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
  20121. ** All other code has file scope.
  20122. **
  20123. ** SQLite processes all times and dates as julian day numbers. The
  20124. ** dates and times are stored as the number of days since noon
  20125. ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
  20126. ** calendar system.
  20127. **
  20128. ** 1970-01-01 00:00:00 is JD 2440587.5
  20129. ** 2000-01-01 00:00:00 is JD 2451544.5
  20130. **
  20131. ** This implementation requires years to be expressed as a 4-digit number
  20132. ** which means that only dates between 0000-01-01 and 9999-12-31 can
  20133. ** be represented, even though julian day numbers allow a much wider
  20134. ** range of dates.
  20135. **
  20136. ** The Gregorian calendar system is used for all dates and times,
  20137. ** even those that predate the Gregorian calendar. Historians usually
  20138. ** use the julian calendar for dates prior to 1582-10-15 and for some
  20139. ** dates afterwards, depending on locale. Beware of this difference.
  20140. **
  20141. ** The conversion algorithms are implemented based on descriptions
  20142. ** in the following text:
  20143. **
  20144. ** Jean Meeus
  20145. ** Astronomical Algorithms, 2nd Edition, 1998
  20146. ** ISBN 0-943396-61-1
  20147. ** Willmann-Bell, Inc
  20148. ** Richmond, Virginia (USA)
  20149. */
  20150. /* #include "sqliteInt.h" */
  20151. /* #include <stdlib.h> */
  20152. /* #include <assert.h> */
  20153. #include <time.h>
  20154. #ifndef SQLITE_OMIT_DATETIME_FUNCS
  20155. /*
  20156. ** The MSVC CRT on Windows CE may not have a localtime() function.
  20157. ** So declare a substitute. The substitute function itself is
  20158. ** defined in "os_win.c".
  20159. */
  20160. #if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \
  20161. (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API)
  20162. struct tm *__cdecl localtime(const time_t *);
  20163. #endif
  20164. /*
  20165. ** A structure for holding a single date and time.
  20166. */
  20167. typedef struct DateTime DateTime;
  20168. struct DateTime {
  20169. sqlite3_int64 iJD; /* The julian day number times 86400000 */
  20170. int Y, M, D; /* Year, month, and day */
  20171. int h, m; /* Hour and minutes */
  20172. int tz; /* Timezone offset in minutes */
  20173. double s; /* Seconds */
  20174. char validJD; /* True (1) if iJD is valid */
  20175. char rawS; /* Raw numeric value stored in s */
  20176. char validYMD; /* True (1) if Y,M,D are valid */
  20177. char validHMS; /* True (1) if h,m,s are valid */
  20178. char validTZ; /* True (1) if tz is valid */
  20179. char tzSet; /* Timezone was set explicitly */
  20180. char isError; /* An overflow has occurred */
  20181. };
  20182. /*
  20183. ** Convert zDate into one or more integers according to the conversion
  20184. ** specifier zFormat.
  20185. **
  20186. ** zFormat[] contains 4 characters for each integer converted, except for
  20187. ** the last integer which is specified by three characters. The meaning
  20188. ** of a four-character format specifiers ABCD is:
  20189. **
  20190. ** A: number of digits to convert. Always "2" or "4".
  20191. ** B: minimum value. Always "0" or "1".
  20192. ** C: maximum value, decoded as:
  20193. ** a: 12
  20194. ** b: 14
  20195. ** c: 24
  20196. ** d: 31
  20197. ** e: 59
  20198. ** f: 9999
  20199. ** D: the separator character, or \000 to indicate this is the
  20200. ** last number to convert.
  20201. **
  20202. ** Example: To translate an ISO-8601 date YYYY-MM-DD, the format would
  20203. ** be "40f-21a-20c". The "40f-" indicates the 4-digit year followed by "-".
  20204. ** The "21a-" indicates the 2-digit month followed by "-". The "20c" indicates
  20205. ** the 2-digit day which is the last integer in the set.
  20206. **
  20207. ** The function returns the number of successful conversions.
  20208. */
  20209. static int getDigits(const char *zDate, const char *zFormat, ...){
  20210. /* The aMx[] array translates the 3rd character of each format
  20211. ** spec into a max size: a b c d e f */
  20212. static const u16 aMx[] = { 12, 14, 24, 31, 59, 9999 };
  20213. va_list ap;
  20214. int cnt = 0;
  20215. char nextC;
  20216. va_start(ap, zFormat);
  20217. do{
  20218. char N = zFormat[0] - '0';
  20219. char min = zFormat[1] - '0';
  20220. int val = 0;
  20221. u16 max;
  20222. assert( zFormat[2]>='a' && zFormat[2]<='f' );
  20223. max = aMx[zFormat[2] - 'a'];
  20224. nextC = zFormat[3];
  20225. val = 0;
  20226. while( N-- ){
  20227. if( !sqlite3Isdigit(*zDate) ){
  20228. goto end_getDigits;
  20229. }
  20230. val = val*10 + *zDate - '0';
  20231. zDate++;
  20232. }
  20233. if( val<(int)min || val>(int)max || (nextC!=0 && nextC!=*zDate) ){
  20234. goto end_getDigits;
  20235. }
  20236. *va_arg(ap,int*) = val;
  20237. zDate++;
  20238. cnt++;
  20239. zFormat += 4;
  20240. }while( nextC );
  20241. end_getDigits:
  20242. va_end(ap);
  20243. return cnt;
  20244. }
  20245. /*
  20246. ** Parse a timezone extension on the end of a date-time.
  20247. ** The extension is of the form:
  20248. **
  20249. ** (+/-)HH:MM
  20250. **
  20251. ** Or the "zulu" notation:
  20252. **
  20253. ** Z
  20254. **
  20255. ** If the parse is successful, write the number of minutes
  20256. ** of change in p->tz and return 0. If a parser error occurs,
  20257. ** return non-zero.
  20258. **
  20259. ** A missing specifier is not considered an error.
  20260. */
  20261. static int parseTimezone(const char *zDate, DateTime *p){
  20262. int sgn = 0;
  20263. int nHr, nMn;
  20264. int c;
  20265. while( sqlite3Isspace(*zDate) ){ zDate++; }
  20266. p->tz = 0;
  20267. c = *zDate;
  20268. if( c=='-' ){
  20269. sgn = -1;
  20270. }else if( c=='+' ){
  20271. sgn = +1;
  20272. }else if( c=='Z' || c=='z' ){
  20273. zDate++;
  20274. goto zulu_time;
  20275. }else{
  20276. return c!=0;
  20277. }
  20278. zDate++;
  20279. if( getDigits(zDate, "20b:20e", &nHr, &nMn)!=2 ){
  20280. return 1;
  20281. }
  20282. zDate += 5;
  20283. p->tz = sgn*(nMn + nHr*60);
  20284. zulu_time:
  20285. while( sqlite3Isspace(*zDate) ){ zDate++; }
  20286. p->tzSet = 1;
  20287. return *zDate!=0;
  20288. }
  20289. /*
  20290. ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
  20291. ** The HH, MM, and SS must each be exactly 2 digits. The
  20292. ** fractional seconds FFFF can be one or more digits.
  20293. **
  20294. ** Return 1 if there is a parsing error and 0 on success.
  20295. */
  20296. static int parseHhMmSs(const char *zDate, DateTime *p){
  20297. int h, m, s;
  20298. double ms = 0.0;
  20299. if( getDigits(zDate, "20c:20e", &h, &m)!=2 ){
  20300. return 1;
  20301. }
  20302. zDate += 5;
  20303. if( *zDate==':' ){
  20304. zDate++;
  20305. if( getDigits(zDate, "20e", &s)!=1 ){
  20306. return 1;
  20307. }
  20308. zDate += 2;
  20309. if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
  20310. double rScale = 1.0;
  20311. zDate++;
  20312. while( sqlite3Isdigit(*zDate) ){
  20313. ms = ms*10.0 + *zDate - '0';
  20314. rScale *= 10.0;
  20315. zDate++;
  20316. }
  20317. ms /= rScale;
  20318. }
  20319. }else{
  20320. s = 0;
  20321. }
  20322. p->validJD = 0;
  20323. p->rawS = 0;
  20324. p->validHMS = 1;
  20325. p->h = h;
  20326. p->m = m;
  20327. p->s = s + ms;
  20328. if( parseTimezone(zDate, p) ) return 1;
  20329. p->validTZ = (p->tz!=0)?1:0;
  20330. return 0;
  20331. }
  20332. /*
  20333. ** Put the DateTime object into its error state.
  20334. */
  20335. static void datetimeError(DateTime *p){
  20336. memset(p, 0, sizeof(*p));
  20337. p->isError = 1;
  20338. }
  20339. /*
  20340. ** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume
  20341. ** that the YYYY-MM-DD is according to the Gregorian calendar.
  20342. **
  20343. ** Reference: Meeus page 61
  20344. */
  20345. static void computeJD(DateTime *p){
  20346. int Y, M, D, A, B, X1, X2;
  20347. if( p->validJD ) return;
  20348. if( p->validYMD ){
  20349. Y = p->Y;
  20350. M = p->M;
  20351. D = p->D;
  20352. }else{
  20353. Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */
  20354. M = 1;
  20355. D = 1;
  20356. }
  20357. if( Y<-4713 || Y>9999 || p->rawS ){
  20358. datetimeError(p);
  20359. return;
  20360. }
  20361. if( M<=2 ){
  20362. Y--;
  20363. M += 12;
  20364. }
  20365. A = Y/100;
  20366. B = 2 - A + (A/4);
  20367. X1 = 36525*(Y+4716)/100;
  20368. X2 = 306001*(M+1)/10000;
  20369. p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
  20370. p->validJD = 1;
  20371. if( p->validHMS ){
  20372. p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
  20373. if( p->validTZ ){
  20374. p->iJD -= p->tz*60000;
  20375. p->validYMD = 0;
  20376. p->validHMS = 0;
  20377. p->validTZ = 0;
  20378. }
  20379. }
  20380. }
  20381. /*
  20382. ** Parse dates of the form
  20383. **
  20384. ** YYYY-MM-DD HH:MM:SS.FFF
  20385. ** YYYY-MM-DD HH:MM:SS
  20386. ** YYYY-MM-DD HH:MM
  20387. ** YYYY-MM-DD
  20388. **
  20389. ** Write the result into the DateTime structure and return 0
  20390. ** on success and 1 if the input string is not a well-formed
  20391. ** date.
  20392. */
  20393. static int parseYyyyMmDd(const char *zDate, DateTime *p){
  20394. int Y, M, D, neg;
  20395. if( zDate[0]=='-' ){
  20396. zDate++;
  20397. neg = 1;
  20398. }else{
  20399. neg = 0;
  20400. }
  20401. if( getDigits(zDate, "40f-21a-21d", &Y, &M, &D)!=3 ){
  20402. return 1;
  20403. }
  20404. zDate += 10;
  20405. while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
  20406. if( parseHhMmSs(zDate, p)==0 ){
  20407. /* We got the time */
  20408. }else if( *zDate==0 ){
  20409. p->validHMS = 0;
  20410. }else{
  20411. return 1;
  20412. }
  20413. p->validJD = 0;
  20414. p->validYMD = 1;
  20415. p->Y = neg ? -Y : Y;
  20416. p->M = M;
  20417. p->D = D;
  20418. if( p->validTZ ){
  20419. computeJD(p);
  20420. }
  20421. return 0;
  20422. }
  20423. /*
  20424. ** Set the time to the current time reported by the VFS.
  20425. **
  20426. ** Return the number of errors.
  20427. */
  20428. static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
  20429. p->iJD = sqlite3StmtCurrentTime(context);
  20430. if( p->iJD>0 ){
  20431. p->validJD = 1;
  20432. return 0;
  20433. }else{
  20434. return 1;
  20435. }
  20436. }
  20437. /*
  20438. ** Input "r" is a numeric quantity which might be a julian day number,
  20439. ** or the number of seconds since 1970. If the value if r is within
  20440. ** range of a julian day number, install it as such and set validJD.
  20441. ** If the value is a valid unix timestamp, put it in p->s and set p->rawS.
  20442. */
  20443. static void setRawDateNumber(DateTime *p, double r){
  20444. p->s = r;
  20445. p->rawS = 1;
  20446. if( r>=0.0 && r<5373484.5 ){
  20447. p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
  20448. p->validJD = 1;
  20449. }
  20450. }
  20451. /*
  20452. ** Attempt to parse the given string into a julian day number. Return
  20453. ** the number of errors.
  20454. **
  20455. ** The following are acceptable forms for the input string:
  20456. **
  20457. ** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
  20458. ** DDDD.DD
  20459. ** now
  20460. **
  20461. ** In the first form, the +/-HH:MM is always optional. The fractional
  20462. ** seconds extension (the ".FFF") is optional. The seconds portion
  20463. ** (":SS.FFF") is option. The year and date can be omitted as long
  20464. ** as there is a time string. The time string can be omitted as long
  20465. ** as there is a year and date.
  20466. */
  20467. static int parseDateOrTime(
  20468. sqlite3_context *context,
  20469. const char *zDate,
  20470. DateTime *p
  20471. ){
  20472. double r;
  20473. if( parseYyyyMmDd(zDate,p)==0 ){
  20474. return 0;
  20475. }else if( parseHhMmSs(zDate, p)==0 ){
  20476. return 0;
  20477. }else if( sqlite3StrICmp(zDate,"now")==0 && sqlite3NotPureFunc(context) ){
  20478. return setDateTimeToCurrent(context, p);
  20479. }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8)>0 ){
  20480. setRawDateNumber(p, r);
  20481. return 0;
  20482. }
  20483. return 1;
  20484. }
  20485. /* The julian day number for 9999-12-31 23:59:59.999 is 5373484.4999999.
  20486. ** Multiplying this by 86400000 gives 464269060799999 as the maximum value
  20487. ** for DateTime.iJD.
  20488. **
  20489. ** But some older compilers (ex: gcc 4.2.1 on older Macs) cannot deal with
  20490. ** such a large integer literal, so we have to encode it.
  20491. */
  20492. #define INT_464269060799999 ((((i64)0x1a640)<<32)|0x1072fdff)
  20493. /*
  20494. ** Return TRUE if the given julian day number is within range.
  20495. **
  20496. ** The input is the JulianDay times 86400000.
  20497. */
  20498. static int validJulianDay(sqlite3_int64 iJD){
  20499. return iJD>=0 && iJD<=INT_464269060799999;
  20500. }
  20501. /*
  20502. ** Compute the Year, Month, and Day from the julian day number.
  20503. */
  20504. static void computeYMD(DateTime *p){
  20505. int Z, A, B, C, D, E, X1;
  20506. if( p->validYMD ) return;
  20507. if( !p->validJD ){
  20508. p->Y = 2000;
  20509. p->M = 1;
  20510. p->D = 1;
  20511. }else if( !validJulianDay(p->iJD) ){
  20512. datetimeError(p);
  20513. return;
  20514. }else{
  20515. Z = (int)((p->iJD + 43200000)/86400000);
  20516. A = (int)((Z - 1867216.25)/36524.25);
  20517. A = Z + 1 + A - (A/4);
  20518. B = A + 1524;
  20519. C = (int)((B - 122.1)/365.25);
  20520. D = (36525*(C&32767))/100;
  20521. E = (int)((B-D)/30.6001);
  20522. X1 = (int)(30.6001*E);
  20523. p->D = B - D - X1;
  20524. p->M = E<14 ? E-1 : E-13;
  20525. p->Y = p->M>2 ? C - 4716 : C - 4715;
  20526. }
  20527. p->validYMD = 1;
  20528. }
  20529. /*
  20530. ** Compute the Hour, Minute, and Seconds from the julian day number.
  20531. */
  20532. static void computeHMS(DateTime *p){
  20533. int s;
  20534. if( p->validHMS ) return;
  20535. computeJD(p);
  20536. s = (int)((p->iJD + 43200000) % 86400000);
  20537. p->s = s/1000.0;
  20538. s = (int)p->s;
  20539. p->s -= s;
  20540. p->h = s/3600;
  20541. s -= p->h*3600;
  20542. p->m = s/60;
  20543. p->s += s - p->m*60;
  20544. p->rawS = 0;
  20545. p->validHMS = 1;
  20546. }
  20547. /*
  20548. ** Compute both YMD and HMS
  20549. */
  20550. static void computeYMD_HMS(DateTime *p){
  20551. computeYMD(p);
  20552. computeHMS(p);
  20553. }
  20554. /*
  20555. ** Clear the YMD and HMS and the TZ
  20556. */
  20557. static void clearYMD_HMS_TZ(DateTime *p){
  20558. p->validYMD = 0;
  20559. p->validHMS = 0;
  20560. p->validTZ = 0;
  20561. }
  20562. #ifndef SQLITE_OMIT_LOCALTIME
  20563. /*
  20564. ** On recent Windows platforms, the localtime_s() function is available
  20565. ** as part of the "Secure CRT". It is essentially equivalent to
  20566. ** localtime_r() available under most POSIX platforms, except that the
  20567. ** order of the parameters is reversed.
  20568. **
  20569. ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
  20570. **
  20571. ** If the user has not indicated to use localtime_r() or localtime_s()
  20572. ** already, check for an MSVC build environment that provides
  20573. ** localtime_s().
  20574. */
  20575. #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S \
  20576. && defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
  20577. #undef HAVE_LOCALTIME_S
  20578. #define HAVE_LOCALTIME_S 1
  20579. #endif
  20580. /*
  20581. ** The following routine implements the rough equivalent of localtime_r()
  20582. ** using whatever operating-system specific localtime facility that
  20583. ** is available. This routine returns 0 on success and
  20584. ** non-zero on any kind of error.
  20585. **
  20586. ** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
  20587. ** routine will always fail.
  20588. **
  20589. ** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C
  20590. ** library function localtime_r() is used to assist in the calculation of
  20591. ** local time.
  20592. */
  20593. static int osLocaltime(time_t *t, struct tm *pTm){
  20594. int rc;
  20595. #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S
  20596. struct tm *pX;
  20597. #if SQLITE_THREADSAFE>0
  20598. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  20599. #endif
  20600. sqlite3_mutex_enter(mutex);
  20601. pX = localtime(t);
  20602. #ifndef SQLITE_UNTESTABLE
  20603. if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
  20604. #endif
  20605. if( pX ) *pTm = *pX;
  20606. sqlite3_mutex_leave(mutex);
  20607. rc = pX==0;
  20608. #else
  20609. #ifndef SQLITE_UNTESTABLE
  20610. if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
  20611. #endif
  20612. #if HAVE_LOCALTIME_R
  20613. rc = localtime_r(t, pTm)==0;
  20614. #else
  20615. rc = localtime_s(pTm, t);
  20616. #endif /* HAVE_LOCALTIME_R */
  20617. #endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
  20618. return rc;
  20619. }
  20620. #endif /* SQLITE_OMIT_LOCALTIME */
  20621. #ifndef SQLITE_OMIT_LOCALTIME
  20622. /*
  20623. ** Compute the difference (in milliseconds) between localtime and UTC
  20624. ** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
  20625. ** return this value and set *pRc to SQLITE_OK.
  20626. **
  20627. ** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
  20628. ** is undefined in this case.
  20629. */
  20630. static sqlite3_int64 localtimeOffset(
  20631. DateTime *p, /* Date at which to calculate offset */
  20632. sqlite3_context *pCtx, /* Write error here if one occurs */
  20633. int *pRc /* OUT: Error code. SQLITE_OK or ERROR */
  20634. ){
  20635. DateTime x, y;
  20636. time_t t;
  20637. struct tm sLocal;
  20638. /* Initialize the contents of sLocal to avoid a compiler warning. */
  20639. memset(&sLocal, 0, sizeof(sLocal));
  20640. x = *p;
  20641. computeYMD_HMS(&x);
  20642. if( x.Y<1971 || x.Y>=2038 ){
  20643. /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only
  20644. ** works for years between 1970 and 2037. For dates outside this range,
  20645. ** SQLite attempts to map the year into an equivalent year within this
  20646. ** range, do the calculation, then map the year back.
  20647. */
  20648. x.Y = 2000;
  20649. x.M = 1;
  20650. x.D = 1;
  20651. x.h = 0;
  20652. x.m = 0;
  20653. x.s = 0.0;
  20654. } else {
  20655. int s = (int)(x.s + 0.5);
  20656. x.s = s;
  20657. }
  20658. x.tz = 0;
  20659. x.validJD = 0;
  20660. computeJD(&x);
  20661. t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
  20662. if( osLocaltime(&t, &sLocal) ){
  20663. sqlite3_result_error(pCtx, "local time unavailable", -1);
  20664. *pRc = SQLITE_ERROR;
  20665. return 0;
  20666. }
  20667. y.Y = sLocal.tm_year + 1900;
  20668. y.M = sLocal.tm_mon + 1;
  20669. y.D = sLocal.tm_mday;
  20670. y.h = sLocal.tm_hour;
  20671. y.m = sLocal.tm_min;
  20672. y.s = sLocal.tm_sec;
  20673. y.validYMD = 1;
  20674. y.validHMS = 1;
  20675. y.validJD = 0;
  20676. y.rawS = 0;
  20677. y.validTZ = 0;
  20678. y.isError = 0;
  20679. computeJD(&y);
  20680. *pRc = SQLITE_OK;
  20681. return y.iJD - x.iJD;
  20682. }
  20683. #endif /* SQLITE_OMIT_LOCALTIME */
  20684. /*
  20685. ** The following table defines various date transformations of the form
  20686. **
  20687. ** 'NNN days'
  20688. **
  20689. ** Where NNN is an arbitrary floating-point number and "days" can be one
  20690. ** of several units of time.
  20691. */
  20692. static const struct {
  20693. u8 eType; /* Transformation type code */
  20694. u8 nName; /* Length of th name */
  20695. char *zName; /* Name of the transformation */
  20696. double rLimit; /* Maximum NNN value for this transform */
  20697. double rXform; /* Constant used for this transform */
  20698. } aXformType[] = {
  20699. { 0, 6, "second", 464269060800.0, 86400000.0/(24.0*60.0*60.0) },
  20700. { 0, 6, "minute", 7737817680.0, 86400000.0/(24.0*60.0) },
  20701. { 0, 4, "hour", 128963628.0, 86400000.0/24.0 },
  20702. { 0, 3, "day", 5373485.0, 86400000.0 },
  20703. { 1, 5, "month", 176546.0, 30.0*86400000.0 },
  20704. { 2, 4, "year", 14713.0, 365.0*86400000.0 },
  20705. };
  20706. /*
  20707. ** Process a modifier to a date-time stamp. The modifiers are
  20708. ** as follows:
  20709. **
  20710. ** NNN days
  20711. ** NNN hours
  20712. ** NNN minutes
  20713. ** NNN.NNNN seconds
  20714. ** NNN months
  20715. ** NNN years
  20716. ** start of month
  20717. ** start of year
  20718. ** start of week
  20719. ** start of day
  20720. ** weekday N
  20721. ** unixepoch
  20722. ** localtime
  20723. ** utc
  20724. **
  20725. ** Return 0 on success and 1 if there is any kind of error. If the error
  20726. ** is in a system call (i.e. localtime()), then an error message is written
  20727. ** to context pCtx. If the error is an unrecognized modifier, no error is
  20728. ** written to pCtx.
  20729. */
  20730. static int parseModifier(
  20731. sqlite3_context *pCtx, /* Function context */
  20732. const char *z, /* The text of the modifier */
  20733. int n, /* Length of zMod in bytes */
  20734. DateTime *p /* The date/time value to be modified */
  20735. ){
  20736. int rc = 1;
  20737. double r;
  20738. switch(sqlite3UpperToLower[(u8)z[0]] ){
  20739. #ifndef SQLITE_OMIT_LOCALTIME
  20740. case 'l': {
  20741. /* localtime
  20742. **
  20743. ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
  20744. ** show local time.
  20745. */
  20746. if( sqlite3_stricmp(z, "localtime")==0 && sqlite3NotPureFunc(pCtx) ){
  20747. computeJD(p);
  20748. p->iJD += localtimeOffset(p, pCtx, &rc);
  20749. clearYMD_HMS_TZ(p);
  20750. }
  20751. break;
  20752. }
  20753. #endif
  20754. case 'u': {
  20755. /*
  20756. ** unixepoch
  20757. **
  20758. ** Treat the current value of p->s as the number of
  20759. ** seconds since 1970. Convert to a real julian day number.
  20760. */
  20761. if( sqlite3_stricmp(z, "unixepoch")==0 && p->rawS ){
  20762. r = p->s*1000.0 + 210866760000000.0;
  20763. if( r>=0.0 && r<464269060800000.0 ){
  20764. clearYMD_HMS_TZ(p);
  20765. p->iJD = (sqlite3_int64)r;
  20766. p->validJD = 1;
  20767. p->rawS = 0;
  20768. rc = 0;
  20769. }
  20770. }
  20771. #ifndef SQLITE_OMIT_LOCALTIME
  20772. else if( sqlite3_stricmp(z, "utc")==0 && sqlite3NotPureFunc(pCtx) ){
  20773. if( p->tzSet==0 ){
  20774. sqlite3_int64 c1;
  20775. computeJD(p);
  20776. c1 = localtimeOffset(p, pCtx, &rc);
  20777. if( rc==SQLITE_OK ){
  20778. p->iJD -= c1;
  20779. clearYMD_HMS_TZ(p);
  20780. p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
  20781. }
  20782. p->tzSet = 1;
  20783. }else{
  20784. rc = SQLITE_OK;
  20785. }
  20786. }
  20787. #endif
  20788. break;
  20789. }
  20790. case 'w': {
  20791. /*
  20792. ** weekday N
  20793. **
  20794. ** Move the date to the same time on the next occurrence of
  20795. ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
  20796. ** date is already on the appropriate weekday, this is a no-op.
  20797. */
  20798. if( sqlite3_strnicmp(z, "weekday ", 8)==0
  20799. && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)>0
  20800. && (n=(int)r)==r && n>=0 && r<7 ){
  20801. sqlite3_int64 Z;
  20802. computeYMD_HMS(p);
  20803. p->validTZ = 0;
  20804. p->validJD = 0;
  20805. computeJD(p);
  20806. Z = ((p->iJD + 129600000)/86400000) % 7;
  20807. if( Z>n ) Z -= 7;
  20808. p->iJD += (n - Z)*86400000;
  20809. clearYMD_HMS_TZ(p);
  20810. rc = 0;
  20811. }
  20812. break;
  20813. }
  20814. case 's': {
  20815. /*
  20816. ** start of TTTTT
  20817. **
  20818. ** Move the date backwards to the beginning of the current day,
  20819. ** or month or year.
  20820. */
  20821. if( sqlite3_strnicmp(z, "start of ", 9)!=0 ) break;
  20822. if( !p->validJD && !p->validYMD && !p->validHMS ) break;
  20823. z += 9;
  20824. computeYMD(p);
  20825. p->validHMS = 1;
  20826. p->h = p->m = 0;
  20827. p->s = 0.0;
  20828. p->rawS = 0;
  20829. p->validTZ = 0;
  20830. p->validJD = 0;
  20831. if( sqlite3_stricmp(z,"month")==0 ){
  20832. p->D = 1;
  20833. rc = 0;
  20834. }else if( sqlite3_stricmp(z,"year")==0 ){
  20835. p->M = 1;
  20836. p->D = 1;
  20837. rc = 0;
  20838. }else if( sqlite3_stricmp(z,"day")==0 ){
  20839. rc = 0;
  20840. }
  20841. break;
  20842. }
  20843. case '+':
  20844. case '-':
  20845. case '0':
  20846. case '1':
  20847. case '2':
  20848. case '3':
  20849. case '4':
  20850. case '5':
  20851. case '6':
  20852. case '7':
  20853. case '8':
  20854. case '9': {
  20855. double rRounder;
  20856. int i;
  20857. for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
  20858. if( sqlite3AtoF(z, &r, n, SQLITE_UTF8)<=0 ){
  20859. rc = 1;
  20860. break;
  20861. }
  20862. if( z[n]==':' ){
  20863. /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
  20864. ** specified number of hours, minutes, seconds, and fractional seconds
  20865. ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be
  20866. ** omitted.
  20867. */
  20868. const char *z2 = z;
  20869. DateTime tx;
  20870. sqlite3_int64 day;
  20871. if( !sqlite3Isdigit(*z2) ) z2++;
  20872. memset(&tx, 0, sizeof(tx));
  20873. if( parseHhMmSs(z2, &tx) ) break;
  20874. computeJD(&tx);
  20875. tx.iJD -= 43200000;
  20876. day = tx.iJD/86400000;
  20877. tx.iJD -= day*86400000;
  20878. if( z[0]=='-' ) tx.iJD = -tx.iJD;
  20879. computeJD(p);
  20880. clearYMD_HMS_TZ(p);
  20881. p->iJD += tx.iJD;
  20882. rc = 0;
  20883. break;
  20884. }
  20885. /* If control reaches this point, it means the transformation is
  20886. ** one of the forms like "+NNN days". */
  20887. z += n;
  20888. while( sqlite3Isspace(*z) ) z++;
  20889. n = sqlite3Strlen30(z);
  20890. if( n>10 || n<3 ) break;
  20891. if( sqlite3UpperToLower[(u8)z[n-1]]=='s' ) n--;
  20892. computeJD(p);
  20893. rc = 1;
  20894. rRounder = r<0 ? -0.5 : +0.5;
  20895. for(i=0; i<ArraySize(aXformType); i++){
  20896. if( aXformType[i].nName==n
  20897. && sqlite3_strnicmp(aXformType[i].zName, z, n)==0
  20898. && r>-aXformType[i].rLimit && r<aXformType[i].rLimit
  20899. ){
  20900. switch( aXformType[i].eType ){
  20901. case 1: { /* Special processing to add months */
  20902. int x;
  20903. computeYMD_HMS(p);
  20904. p->M += (int)r;
  20905. x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
  20906. p->Y += x;
  20907. p->M -= x*12;
  20908. p->validJD = 0;
  20909. r -= (int)r;
  20910. break;
  20911. }
  20912. case 2: { /* Special processing to add years */
  20913. int y = (int)r;
  20914. computeYMD_HMS(p);
  20915. p->Y += y;
  20916. p->validJD = 0;
  20917. r -= (int)r;
  20918. break;
  20919. }
  20920. }
  20921. computeJD(p);
  20922. p->iJD += (sqlite3_int64)(r*aXformType[i].rXform + rRounder);
  20923. rc = 0;
  20924. break;
  20925. }
  20926. }
  20927. clearYMD_HMS_TZ(p);
  20928. break;
  20929. }
  20930. default: {
  20931. break;
  20932. }
  20933. }
  20934. return rc;
  20935. }
  20936. /*
  20937. ** Process time function arguments. argv[0] is a date-time stamp.
  20938. ** argv[1] and following are modifiers. Parse them all and write
  20939. ** the resulting time into the DateTime structure p. Return 0
  20940. ** on success and 1 if there are any errors.
  20941. **
  20942. ** If there are zero parameters (if even argv[0] is undefined)
  20943. ** then assume a default value of "now" for argv[0].
  20944. */
  20945. static int isDate(
  20946. sqlite3_context *context,
  20947. int argc,
  20948. sqlite3_value **argv,
  20949. DateTime *p
  20950. ){
  20951. int i, n;
  20952. const unsigned char *z;
  20953. int eType;
  20954. memset(p, 0, sizeof(*p));
  20955. if( argc==0 ){
  20956. return setDateTimeToCurrent(context, p);
  20957. }
  20958. if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
  20959. || eType==SQLITE_INTEGER ){
  20960. setRawDateNumber(p, sqlite3_value_double(argv[0]));
  20961. }else{
  20962. z = sqlite3_value_text(argv[0]);
  20963. if( !z || parseDateOrTime(context, (char*)z, p) ){
  20964. return 1;
  20965. }
  20966. }
  20967. for(i=1; i<argc; i++){
  20968. z = sqlite3_value_text(argv[i]);
  20969. n = sqlite3_value_bytes(argv[i]);
  20970. if( z==0 || parseModifier(context, (char*)z, n, p) ) return 1;
  20971. }
  20972. computeJD(p);
  20973. if( p->isError || !validJulianDay(p->iJD) ) return 1;
  20974. return 0;
  20975. }
  20976. /*
  20977. ** The following routines implement the various date and time functions
  20978. ** of SQLite.
  20979. */
  20980. /*
  20981. ** julianday( TIMESTRING, MOD, MOD, ...)
  20982. **
  20983. ** Return the julian day number of the date specified in the arguments
  20984. */
  20985. static void juliandayFunc(
  20986. sqlite3_context *context,
  20987. int argc,
  20988. sqlite3_value **argv
  20989. ){
  20990. DateTime x;
  20991. if( isDate(context, argc, argv, &x)==0 ){
  20992. computeJD(&x);
  20993. sqlite3_result_double(context, x.iJD/86400000.0);
  20994. }
  20995. }
  20996. /*
  20997. ** datetime( TIMESTRING, MOD, MOD, ...)
  20998. **
  20999. ** Return YYYY-MM-DD HH:MM:SS
  21000. */
  21001. static void datetimeFunc(
  21002. sqlite3_context *context,
  21003. int argc,
  21004. sqlite3_value **argv
  21005. ){
  21006. DateTime x;
  21007. if( isDate(context, argc, argv, &x)==0 ){
  21008. char zBuf[100];
  21009. computeYMD_HMS(&x);
  21010. sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
  21011. x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
  21012. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  21013. }
  21014. }
  21015. /*
  21016. ** time( TIMESTRING, MOD, MOD, ...)
  21017. **
  21018. ** Return HH:MM:SS
  21019. */
  21020. static void timeFunc(
  21021. sqlite3_context *context,
  21022. int argc,
  21023. sqlite3_value **argv
  21024. ){
  21025. DateTime x;
  21026. if( isDate(context, argc, argv, &x)==0 ){
  21027. char zBuf[100];
  21028. computeHMS(&x);
  21029. sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
  21030. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  21031. }
  21032. }
  21033. /*
  21034. ** date( TIMESTRING, MOD, MOD, ...)
  21035. **
  21036. ** Return YYYY-MM-DD
  21037. */
  21038. static void dateFunc(
  21039. sqlite3_context *context,
  21040. int argc,
  21041. sqlite3_value **argv
  21042. ){
  21043. DateTime x;
  21044. if( isDate(context, argc, argv, &x)==0 ){
  21045. char zBuf[100];
  21046. computeYMD(&x);
  21047. sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
  21048. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  21049. }
  21050. }
  21051. /*
  21052. ** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
  21053. **
  21054. ** Return a string described by FORMAT. Conversions as follows:
  21055. **
  21056. ** %d day of month
  21057. ** %f ** fractional seconds SS.SSS
  21058. ** %H hour 00-24
  21059. ** %j day of year 000-366
  21060. ** %J ** julian day number
  21061. ** %m month 01-12
  21062. ** %M minute 00-59
  21063. ** %s seconds since 1970-01-01
  21064. ** %S seconds 00-59
  21065. ** %w day of week 0-6 sunday==0
  21066. ** %W week of year 00-53
  21067. ** %Y year 0000-9999
  21068. ** %% %
  21069. */
  21070. static void strftimeFunc(
  21071. sqlite3_context *context,
  21072. int argc,
  21073. sqlite3_value **argv
  21074. ){
  21075. DateTime x;
  21076. u64 n;
  21077. size_t i,j;
  21078. char *z;
  21079. sqlite3 *db;
  21080. const char *zFmt;
  21081. char zBuf[100];
  21082. if( argc==0 ) return;
  21083. zFmt = (const char*)sqlite3_value_text(argv[0]);
  21084. if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
  21085. db = sqlite3_context_db_handle(context);
  21086. for(i=0, n=1; zFmt[i]; i++, n++){
  21087. if( zFmt[i]=='%' ){
  21088. switch( zFmt[i+1] ){
  21089. case 'd':
  21090. case 'H':
  21091. case 'm':
  21092. case 'M':
  21093. case 'S':
  21094. case 'W':
  21095. n++;
  21096. /* fall thru */
  21097. case 'w':
  21098. case '%':
  21099. break;
  21100. case 'f':
  21101. n += 8;
  21102. break;
  21103. case 'j':
  21104. n += 3;
  21105. break;
  21106. case 'Y':
  21107. n += 8;
  21108. break;
  21109. case 's':
  21110. case 'J':
  21111. n += 50;
  21112. break;
  21113. default:
  21114. return; /* ERROR. return a NULL */
  21115. }
  21116. i++;
  21117. }
  21118. }
  21119. testcase( n==sizeof(zBuf)-1 );
  21120. testcase( n==sizeof(zBuf) );
  21121. testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  21122. testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
  21123. if( n<sizeof(zBuf) ){
  21124. z = zBuf;
  21125. }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  21126. sqlite3_result_error_toobig(context);
  21127. return;
  21128. }else{
  21129. z = sqlite3DbMallocRawNN(db, (int)n);
  21130. if( z==0 ){
  21131. sqlite3_result_error_nomem(context);
  21132. return;
  21133. }
  21134. }
  21135. computeJD(&x);
  21136. computeYMD_HMS(&x);
  21137. for(i=j=0; zFmt[i]; i++){
  21138. if( zFmt[i]!='%' ){
  21139. z[j++] = zFmt[i];
  21140. }else{
  21141. i++;
  21142. switch( zFmt[i] ){
  21143. case 'd': sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
  21144. case 'f': {
  21145. double s = x.s;
  21146. if( s>59.999 ) s = 59.999;
  21147. sqlite3_snprintf(7, &z[j],"%06.3f", s);
  21148. j += sqlite3Strlen30(&z[j]);
  21149. break;
  21150. }
  21151. case 'H': sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
  21152. case 'W': /* Fall thru */
  21153. case 'j': {
  21154. int nDay; /* Number of days since 1st day of year */
  21155. DateTime y = x;
  21156. y.validJD = 0;
  21157. y.M = 1;
  21158. y.D = 1;
  21159. computeJD(&y);
  21160. nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
  21161. if( zFmt[i]=='W' ){
  21162. int wd; /* 0=Monday, 1=Tuesday, ... 6=Sunday */
  21163. wd = (int)(((x.iJD+43200000)/86400000)%7);
  21164. sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
  21165. j += 2;
  21166. }else{
  21167. sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
  21168. j += 3;
  21169. }
  21170. break;
  21171. }
  21172. case 'J': {
  21173. sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
  21174. j+=sqlite3Strlen30(&z[j]);
  21175. break;
  21176. }
  21177. case 'm': sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
  21178. case 'M': sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
  21179. case 's': {
  21180. sqlite3_snprintf(30,&z[j],"%lld",
  21181. (i64)(x.iJD/1000 - 21086676*(i64)10000));
  21182. j += sqlite3Strlen30(&z[j]);
  21183. break;
  21184. }
  21185. case 'S': sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
  21186. case 'w': {
  21187. z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
  21188. break;
  21189. }
  21190. case 'Y': {
  21191. sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
  21192. break;
  21193. }
  21194. default: z[j++] = '%'; break;
  21195. }
  21196. }
  21197. }
  21198. z[j] = 0;
  21199. sqlite3_result_text(context, z, -1,
  21200. z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
  21201. }
  21202. /*
  21203. ** current_time()
  21204. **
  21205. ** This function returns the same value as time('now').
  21206. */
  21207. static void ctimeFunc(
  21208. sqlite3_context *context,
  21209. int NotUsed,
  21210. sqlite3_value **NotUsed2
  21211. ){
  21212. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  21213. timeFunc(context, 0, 0);
  21214. }
  21215. /*
  21216. ** current_date()
  21217. **
  21218. ** This function returns the same value as date('now').
  21219. */
  21220. static void cdateFunc(
  21221. sqlite3_context *context,
  21222. int NotUsed,
  21223. sqlite3_value **NotUsed2
  21224. ){
  21225. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  21226. dateFunc(context, 0, 0);
  21227. }
  21228. /*
  21229. ** current_timestamp()
  21230. **
  21231. ** This function returns the same value as datetime('now').
  21232. */
  21233. static void ctimestampFunc(
  21234. sqlite3_context *context,
  21235. int NotUsed,
  21236. sqlite3_value **NotUsed2
  21237. ){
  21238. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  21239. datetimeFunc(context, 0, 0);
  21240. }
  21241. #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
  21242. #ifdef SQLITE_OMIT_DATETIME_FUNCS
  21243. /*
  21244. ** If the library is compiled to omit the full-scale date and time
  21245. ** handling (to get a smaller binary), the following minimal version
  21246. ** of the functions current_time(), current_date() and current_timestamp()
  21247. ** are included instead. This is to support column declarations that
  21248. ** include "DEFAULT CURRENT_TIME" etc.
  21249. **
  21250. ** This function uses the C-library functions time(), gmtime()
  21251. ** and strftime(). The format string to pass to strftime() is supplied
  21252. ** as the user-data for the function.
  21253. */
  21254. static void currentTimeFunc(
  21255. sqlite3_context *context,
  21256. int argc,
  21257. sqlite3_value **argv
  21258. ){
  21259. time_t t;
  21260. char *zFormat = (char *)sqlite3_user_data(context);
  21261. sqlite3_int64 iT;
  21262. struct tm *pTm;
  21263. struct tm sNow;
  21264. char zBuf[20];
  21265. UNUSED_PARAMETER(argc);
  21266. UNUSED_PARAMETER(argv);
  21267. iT = sqlite3StmtCurrentTime(context);
  21268. if( iT<=0 ) return;
  21269. t = iT/1000 - 10000*(sqlite3_int64)21086676;
  21270. #if HAVE_GMTIME_R
  21271. pTm = gmtime_r(&t, &sNow);
  21272. #else
  21273. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  21274. pTm = gmtime(&t);
  21275. if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
  21276. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  21277. #endif
  21278. if( pTm ){
  21279. strftime(zBuf, 20, zFormat, &sNow);
  21280. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  21281. }
  21282. }
  21283. #endif
  21284. /*
  21285. ** This function registered all of the above C functions as SQL
  21286. ** functions. This should be the only routine in this file with
  21287. ** external linkage.
  21288. */
  21289. SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
  21290. static FuncDef aDateTimeFuncs[] = {
  21291. #ifndef SQLITE_OMIT_DATETIME_FUNCS
  21292. PURE_DATE(julianday, -1, 0, 0, juliandayFunc ),
  21293. PURE_DATE(date, -1, 0, 0, dateFunc ),
  21294. PURE_DATE(time, -1, 0, 0, timeFunc ),
  21295. PURE_DATE(datetime, -1, 0, 0, datetimeFunc ),
  21296. PURE_DATE(strftime, -1, 0, 0, strftimeFunc ),
  21297. DFUNCTION(current_time, 0, 0, 0, ctimeFunc ),
  21298. DFUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
  21299. DFUNCTION(current_date, 0, 0, 0, cdateFunc ),
  21300. #else
  21301. STR_FUNCTION(current_time, 0, "%H:%M:%S", 0, currentTimeFunc),
  21302. STR_FUNCTION(current_date, 0, "%Y-%m-%d", 0, currentTimeFunc),
  21303. STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
  21304. #endif
  21305. };
  21306. sqlite3InsertBuiltinFuncs(aDateTimeFuncs, ArraySize(aDateTimeFuncs));
  21307. }
  21308. /************** End of date.c ************************************************/
  21309. /************** Begin file os.c **********************************************/
  21310. /*
  21311. ** 2005 November 29
  21312. **
  21313. ** The author disclaims copyright to this source code. In place of
  21314. ** a legal notice, here is a blessing:
  21315. **
  21316. ** May you do good and not evil.
  21317. ** May you find forgiveness for yourself and forgive others.
  21318. ** May you share freely, never taking more than you give.
  21319. **
  21320. ******************************************************************************
  21321. **
  21322. ** This file contains OS interface code that is common to all
  21323. ** architectures.
  21324. */
  21325. /* #include "sqliteInt.h" */
  21326. /*
  21327. ** If we compile with the SQLITE_TEST macro set, then the following block
  21328. ** of code will give us the ability to simulate a disk I/O error. This
  21329. ** is used for testing the I/O recovery logic.
  21330. */
  21331. #if defined(SQLITE_TEST)
  21332. SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
  21333. SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
  21334. SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
  21335. SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
  21336. SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
  21337. SQLITE_API int sqlite3_diskfull_pending = 0;
  21338. SQLITE_API int sqlite3_diskfull = 0;
  21339. #endif /* defined(SQLITE_TEST) */
  21340. /*
  21341. ** When testing, also keep a count of the number of open files.
  21342. */
  21343. #if defined(SQLITE_TEST)
  21344. SQLITE_API int sqlite3_open_file_count = 0;
  21345. #endif /* defined(SQLITE_TEST) */
  21346. /*
  21347. ** The default SQLite sqlite3_vfs implementations do not allocate
  21348. ** memory (actually, os_unix.c allocates a small amount of memory
  21349. ** from within OsOpen()), but some third-party implementations may.
  21350. ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
  21351. ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
  21352. **
  21353. ** The following functions are instrumented for malloc() failure
  21354. ** testing:
  21355. **
  21356. ** sqlite3OsRead()
  21357. ** sqlite3OsWrite()
  21358. ** sqlite3OsSync()
  21359. ** sqlite3OsFileSize()
  21360. ** sqlite3OsLock()
  21361. ** sqlite3OsCheckReservedLock()
  21362. ** sqlite3OsFileControl()
  21363. ** sqlite3OsShmMap()
  21364. ** sqlite3OsOpen()
  21365. ** sqlite3OsDelete()
  21366. ** sqlite3OsAccess()
  21367. ** sqlite3OsFullPathname()
  21368. **
  21369. */
  21370. #if defined(SQLITE_TEST)
  21371. SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
  21372. #define DO_OS_MALLOC_TEST(x) \
  21373. if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3JournalIsInMemory(x))) { \
  21374. void *pTstAlloc = sqlite3Malloc(10); \
  21375. if (!pTstAlloc) return SQLITE_IOERR_NOMEM_BKPT; \
  21376. sqlite3_free(pTstAlloc); \
  21377. }
  21378. #else
  21379. #define DO_OS_MALLOC_TEST(x)
  21380. #endif
  21381. /*
  21382. ** The following routines are convenience wrappers around methods
  21383. ** of the sqlite3_file object. This is mostly just syntactic sugar. All
  21384. ** of this would be completely automatic if SQLite were coded using
  21385. ** C++ instead of plain old C.
  21386. */
  21387. SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file *pId){
  21388. if( pId->pMethods ){
  21389. pId->pMethods->xClose(pId);
  21390. pId->pMethods = 0;
  21391. }
  21392. }
  21393. SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
  21394. DO_OS_MALLOC_TEST(id);
  21395. return id->pMethods->xRead(id, pBuf, amt, offset);
  21396. }
  21397. SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
  21398. DO_OS_MALLOC_TEST(id);
  21399. return id->pMethods->xWrite(id, pBuf, amt, offset);
  21400. }
  21401. SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
  21402. return id->pMethods->xTruncate(id, size);
  21403. }
  21404. SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
  21405. DO_OS_MALLOC_TEST(id);
  21406. return flags ? id->pMethods->xSync(id, flags) : SQLITE_OK;
  21407. }
  21408. SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
  21409. DO_OS_MALLOC_TEST(id);
  21410. return id->pMethods->xFileSize(id, pSize);
  21411. }
  21412. SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
  21413. DO_OS_MALLOC_TEST(id);
  21414. return id->pMethods->xLock(id, lockType);
  21415. }
  21416. SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
  21417. return id->pMethods->xUnlock(id, lockType);
  21418. }
  21419. SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
  21420. DO_OS_MALLOC_TEST(id);
  21421. return id->pMethods->xCheckReservedLock(id, pResOut);
  21422. }
  21423. /*
  21424. ** Use sqlite3OsFileControl() when we are doing something that might fail
  21425. ** and we need to know about the failures. Use sqlite3OsFileControlHint()
  21426. ** when simply tossing information over the wall to the VFS and we do not
  21427. ** really care if the VFS receives and understands the information since it
  21428. ** is only a hint and can be safely ignored. The sqlite3OsFileControlHint()
  21429. ** routine has no return value since the return value would be meaningless.
  21430. */
  21431. SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
  21432. if( id->pMethods==0 ) return SQLITE_NOTFOUND;
  21433. #ifdef SQLITE_TEST
  21434. if( op!=SQLITE_FCNTL_COMMIT_PHASETWO
  21435. && op!=SQLITE_FCNTL_LOCK_TIMEOUT
  21436. ){
  21437. /* Faults are not injected into COMMIT_PHASETWO because, assuming SQLite
  21438. ** is using a regular VFS, it is called after the corresponding
  21439. ** transaction has been committed. Injecting a fault at this point
  21440. ** confuses the test scripts - the COMMIT comand returns SQLITE_NOMEM
  21441. ** but the transaction is committed anyway.
  21442. **
  21443. ** The core must call OsFileControl() though, not OsFileControlHint(),
  21444. ** as if a custom VFS (e.g. zipvfs) returns an error here, it probably
  21445. ** means the commit really has failed and an error should be returned
  21446. ** to the user. */
  21447. DO_OS_MALLOC_TEST(id);
  21448. }
  21449. #endif
  21450. return id->pMethods->xFileControl(id, op, pArg);
  21451. }
  21452. SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
  21453. if( id->pMethods ) (void)id->pMethods->xFileControl(id, op, pArg);
  21454. }
  21455. SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
  21456. int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
  21457. return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
  21458. }
  21459. SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
  21460. return id->pMethods->xDeviceCharacteristics(id);
  21461. }
  21462. #ifndef SQLITE_OMIT_WAL
  21463. SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
  21464. return id->pMethods->xShmLock(id, offset, n, flags);
  21465. }
  21466. SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
  21467. id->pMethods->xShmBarrier(id);
  21468. }
  21469. SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
  21470. return id->pMethods->xShmUnmap(id, deleteFlag);
  21471. }
  21472. SQLITE_PRIVATE int sqlite3OsShmMap(
  21473. sqlite3_file *id, /* Database file handle */
  21474. int iPage,
  21475. int pgsz,
  21476. int bExtend, /* True to extend file if necessary */
  21477. void volatile **pp /* OUT: Pointer to mapping */
  21478. ){
  21479. DO_OS_MALLOC_TEST(id);
  21480. return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
  21481. }
  21482. #endif /* SQLITE_OMIT_WAL */
  21483. #if SQLITE_MAX_MMAP_SIZE>0
  21484. /* The real implementation of xFetch and xUnfetch */
  21485. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
  21486. DO_OS_MALLOC_TEST(id);
  21487. return id->pMethods->xFetch(id, iOff, iAmt, pp);
  21488. }
  21489. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
  21490. return id->pMethods->xUnfetch(id, iOff, p);
  21491. }
  21492. #else
  21493. /* No-op stubs to use when memory-mapped I/O is disabled */
  21494. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
  21495. *pp = 0;
  21496. return SQLITE_OK;
  21497. }
  21498. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
  21499. return SQLITE_OK;
  21500. }
  21501. #endif
  21502. /*
  21503. ** The next group of routines are convenience wrappers around the
  21504. ** VFS methods.
  21505. */
  21506. SQLITE_PRIVATE int sqlite3OsOpen(
  21507. sqlite3_vfs *pVfs,
  21508. const char *zPath,
  21509. sqlite3_file *pFile,
  21510. int flags,
  21511. int *pFlagsOut
  21512. ){
  21513. int rc;
  21514. DO_OS_MALLOC_TEST(0);
  21515. /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
  21516. ** down into the VFS layer. Some SQLITE_OPEN_ flags (for example,
  21517. ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
  21518. ** reaching the VFS. */
  21519. rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
  21520. assert( rc==SQLITE_OK || pFile->pMethods==0 );
  21521. return rc;
  21522. }
  21523. SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
  21524. DO_OS_MALLOC_TEST(0);
  21525. assert( dirSync==0 || dirSync==1 );
  21526. return pVfs->xDelete(pVfs, zPath, dirSync);
  21527. }
  21528. SQLITE_PRIVATE int sqlite3OsAccess(
  21529. sqlite3_vfs *pVfs,
  21530. const char *zPath,
  21531. int flags,
  21532. int *pResOut
  21533. ){
  21534. DO_OS_MALLOC_TEST(0);
  21535. return pVfs->xAccess(pVfs, zPath, flags, pResOut);
  21536. }
  21537. SQLITE_PRIVATE int sqlite3OsFullPathname(
  21538. sqlite3_vfs *pVfs,
  21539. const char *zPath,
  21540. int nPathOut,
  21541. char *zPathOut
  21542. ){
  21543. DO_OS_MALLOC_TEST(0);
  21544. zPathOut[0] = 0;
  21545. return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
  21546. }
  21547. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  21548. SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
  21549. return pVfs->xDlOpen(pVfs, zPath);
  21550. }
  21551. SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  21552. pVfs->xDlError(pVfs, nByte, zBufOut);
  21553. }
  21554. SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
  21555. return pVfs->xDlSym(pVfs, pHdle, zSym);
  21556. }
  21557. SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
  21558. pVfs->xDlClose(pVfs, pHandle);
  21559. }
  21560. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  21561. SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  21562. return pVfs->xRandomness(pVfs, nByte, zBufOut);
  21563. }
  21564. SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
  21565. return pVfs->xSleep(pVfs, nMicro);
  21566. }
  21567. SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs *pVfs){
  21568. return pVfs->xGetLastError ? pVfs->xGetLastError(pVfs, 0, 0) : 0;
  21569. }
  21570. SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
  21571. int rc;
  21572. /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
  21573. ** method to get the current date and time if that method is available
  21574. ** (if iVersion is 2 or greater and the function pointer is not NULL) and
  21575. ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
  21576. ** unavailable.
  21577. */
  21578. if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
  21579. rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
  21580. }else{
  21581. double r;
  21582. rc = pVfs->xCurrentTime(pVfs, &r);
  21583. *pTimeOut = (sqlite3_int64)(r*86400000.0);
  21584. }
  21585. return rc;
  21586. }
  21587. SQLITE_PRIVATE int sqlite3OsOpenMalloc(
  21588. sqlite3_vfs *pVfs,
  21589. const char *zFile,
  21590. sqlite3_file **ppFile,
  21591. int flags,
  21592. int *pOutFlags
  21593. ){
  21594. int rc;
  21595. sqlite3_file *pFile;
  21596. pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
  21597. if( pFile ){
  21598. rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
  21599. if( rc!=SQLITE_OK ){
  21600. sqlite3_free(pFile);
  21601. }else{
  21602. *ppFile = pFile;
  21603. }
  21604. }else{
  21605. rc = SQLITE_NOMEM_BKPT;
  21606. }
  21607. return rc;
  21608. }
  21609. SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *pFile){
  21610. assert( pFile );
  21611. sqlite3OsClose(pFile);
  21612. sqlite3_free(pFile);
  21613. }
  21614. /*
  21615. ** This function is a wrapper around the OS specific implementation of
  21616. ** sqlite3_os_init(). The purpose of the wrapper is to provide the
  21617. ** ability to simulate a malloc failure, so that the handling of an
  21618. ** error in sqlite3_os_init() by the upper layers can be tested.
  21619. */
  21620. SQLITE_PRIVATE int sqlite3OsInit(void){
  21621. void *p = sqlite3_malloc(10);
  21622. if( p==0 ) return SQLITE_NOMEM_BKPT;
  21623. sqlite3_free(p);
  21624. return sqlite3_os_init();
  21625. }
  21626. /*
  21627. ** The list of all registered VFS implementations.
  21628. */
  21629. static sqlite3_vfs * SQLITE_WSD vfsList = 0;
  21630. #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
  21631. /*
  21632. ** Locate a VFS by name. If no name is given, simply return the
  21633. ** first VFS on the list.
  21634. */
  21635. SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
  21636. sqlite3_vfs *pVfs = 0;
  21637. #if SQLITE_THREADSAFE
  21638. sqlite3_mutex *mutex;
  21639. #endif
  21640. #ifndef SQLITE_OMIT_AUTOINIT
  21641. int rc = sqlite3_initialize();
  21642. if( rc ) return 0;
  21643. #endif
  21644. #if SQLITE_THREADSAFE
  21645. mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  21646. #endif
  21647. sqlite3_mutex_enter(mutex);
  21648. for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
  21649. if( zVfs==0 ) break;
  21650. if( strcmp(zVfs, pVfs->zName)==0 ) break;
  21651. }
  21652. sqlite3_mutex_leave(mutex);
  21653. return pVfs;
  21654. }
  21655. /*
  21656. ** Unlink a VFS from the linked list
  21657. */
  21658. static void vfsUnlink(sqlite3_vfs *pVfs){
  21659. assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
  21660. if( pVfs==0 ){
  21661. /* No-op */
  21662. }else if( vfsList==pVfs ){
  21663. vfsList = pVfs->pNext;
  21664. }else if( vfsList ){
  21665. sqlite3_vfs *p = vfsList;
  21666. while( p->pNext && p->pNext!=pVfs ){
  21667. p = p->pNext;
  21668. }
  21669. if( p->pNext==pVfs ){
  21670. p->pNext = pVfs->pNext;
  21671. }
  21672. }
  21673. }
  21674. /*
  21675. ** Register a VFS with the system. It is harmless to register the same
  21676. ** VFS multiple times. The new VFS becomes the default if makeDflt is
  21677. ** true.
  21678. */
  21679. SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
  21680. MUTEX_LOGIC(sqlite3_mutex *mutex;)
  21681. #ifndef SQLITE_OMIT_AUTOINIT
  21682. int rc = sqlite3_initialize();
  21683. if( rc ) return rc;
  21684. #endif
  21685. #ifdef SQLITE_ENABLE_API_ARMOR
  21686. if( pVfs==0 ) return SQLITE_MISUSE_BKPT;
  21687. #endif
  21688. MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  21689. sqlite3_mutex_enter(mutex);
  21690. vfsUnlink(pVfs);
  21691. if( makeDflt || vfsList==0 ){
  21692. pVfs->pNext = vfsList;
  21693. vfsList = pVfs;
  21694. }else{
  21695. pVfs->pNext = vfsList->pNext;
  21696. vfsList->pNext = pVfs;
  21697. }
  21698. assert(vfsList);
  21699. sqlite3_mutex_leave(mutex);
  21700. return SQLITE_OK;
  21701. }
  21702. /*
  21703. ** Unregister a VFS so that it is no longer accessible.
  21704. */
  21705. SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
  21706. MUTEX_LOGIC(sqlite3_mutex *mutex;)
  21707. #ifndef SQLITE_OMIT_AUTOINIT
  21708. int rc = sqlite3_initialize();
  21709. if( rc ) return rc;
  21710. #endif
  21711. MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  21712. sqlite3_mutex_enter(mutex);
  21713. vfsUnlink(pVfs);
  21714. sqlite3_mutex_leave(mutex);
  21715. return SQLITE_OK;
  21716. }
  21717. /************** End of os.c **************************************************/
  21718. /************** Begin file fault.c *******************************************/
  21719. /*
  21720. ** 2008 Jan 22
  21721. **
  21722. ** The author disclaims copyright to this source code. In place of
  21723. ** a legal notice, here is a blessing:
  21724. **
  21725. ** May you do good and not evil.
  21726. ** May you find forgiveness for yourself and forgive others.
  21727. ** May you share freely, never taking more than you give.
  21728. **
  21729. *************************************************************************
  21730. **
  21731. ** This file contains code to support the concept of "benign"
  21732. ** malloc failures (when the xMalloc() or xRealloc() method of the
  21733. ** sqlite3_mem_methods structure fails to allocate a block of memory
  21734. ** and returns 0).
  21735. **
  21736. ** Most malloc failures are non-benign. After they occur, SQLite
  21737. ** abandons the current operation and returns an error code (usually
  21738. ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
  21739. ** fatal. For example, if a malloc fails while resizing a hash table, this
  21740. ** is completely recoverable simply by not carrying out the resize. The
  21741. ** hash table will continue to function normally. So a malloc failure
  21742. ** during a hash table resize is a benign fault.
  21743. */
  21744. /* #include "sqliteInt.h" */
  21745. #ifndef SQLITE_UNTESTABLE
  21746. /*
  21747. ** Global variables.
  21748. */
  21749. typedef struct BenignMallocHooks BenignMallocHooks;
  21750. static SQLITE_WSD struct BenignMallocHooks {
  21751. void (*xBenignBegin)(void);
  21752. void (*xBenignEnd)(void);
  21753. } sqlite3Hooks = { 0, 0 };
  21754. /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
  21755. ** structure. If writable static data is unsupported on the target,
  21756. ** we have to locate the state vector at run-time. In the more common
  21757. ** case where writable static data is supported, wsdHooks can refer directly
  21758. ** to the "sqlite3Hooks" state vector declared above.
  21759. */
  21760. #ifdef SQLITE_OMIT_WSD
  21761. # define wsdHooksInit \
  21762. BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
  21763. # define wsdHooks x[0]
  21764. #else
  21765. # define wsdHooksInit
  21766. # define wsdHooks sqlite3Hooks
  21767. #endif
  21768. /*
  21769. ** Register hooks to call when sqlite3BeginBenignMalloc() and
  21770. ** sqlite3EndBenignMalloc() are called, respectively.
  21771. */
  21772. SQLITE_PRIVATE void sqlite3BenignMallocHooks(
  21773. void (*xBenignBegin)(void),
  21774. void (*xBenignEnd)(void)
  21775. ){
  21776. wsdHooksInit;
  21777. wsdHooks.xBenignBegin = xBenignBegin;
  21778. wsdHooks.xBenignEnd = xBenignEnd;
  21779. }
  21780. /*
  21781. ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
  21782. ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
  21783. ** indicates that subsequent malloc failures are non-benign.
  21784. */
  21785. SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
  21786. wsdHooksInit;
  21787. if( wsdHooks.xBenignBegin ){
  21788. wsdHooks.xBenignBegin();
  21789. }
  21790. }
  21791. SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
  21792. wsdHooksInit;
  21793. if( wsdHooks.xBenignEnd ){
  21794. wsdHooks.xBenignEnd();
  21795. }
  21796. }
  21797. #endif /* #ifndef SQLITE_UNTESTABLE */
  21798. /************** End of fault.c ***********************************************/
  21799. /************** Begin file mem0.c ********************************************/
  21800. /*
  21801. ** 2008 October 28
  21802. **
  21803. ** The author disclaims copyright to this source code. In place of
  21804. ** a legal notice, here is a blessing:
  21805. **
  21806. ** May you do good and not evil.
  21807. ** May you find forgiveness for yourself and forgive others.
  21808. ** May you share freely, never taking more than you give.
  21809. **
  21810. *************************************************************************
  21811. **
  21812. ** This file contains a no-op memory allocation drivers for use when
  21813. ** SQLITE_ZERO_MALLOC is defined. The allocation drivers implemented
  21814. ** here always fail. SQLite will not operate with these drivers. These
  21815. ** are merely placeholders. Real drivers must be substituted using
  21816. ** sqlite3_config() before SQLite will operate.
  21817. */
  21818. /* #include "sqliteInt.h" */
  21819. /*
  21820. ** This version of the memory allocator is the default. It is
  21821. ** used when no other memory allocator is specified using compile-time
  21822. ** macros.
  21823. */
  21824. #ifdef SQLITE_ZERO_MALLOC
  21825. /*
  21826. ** No-op versions of all memory allocation routines
  21827. */
  21828. static void *sqlite3MemMalloc(int nByte){ return 0; }
  21829. static void sqlite3MemFree(void *pPrior){ return; }
  21830. static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
  21831. static int sqlite3MemSize(void *pPrior){ return 0; }
  21832. static int sqlite3MemRoundup(int n){ return n; }
  21833. static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
  21834. static void sqlite3MemShutdown(void *NotUsed){ return; }
  21835. /*
  21836. ** This routine is the only routine in this file with external linkage.
  21837. **
  21838. ** Populate the low-level memory allocation function pointers in
  21839. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  21840. */
  21841. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  21842. static const sqlite3_mem_methods defaultMethods = {
  21843. sqlite3MemMalloc,
  21844. sqlite3MemFree,
  21845. sqlite3MemRealloc,
  21846. sqlite3MemSize,
  21847. sqlite3MemRoundup,
  21848. sqlite3MemInit,
  21849. sqlite3MemShutdown,
  21850. 0
  21851. };
  21852. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  21853. }
  21854. #endif /* SQLITE_ZERO_MALLOC */
  21855. /************** End of mem0.c ************************************************/
  21856. /************** Begin file mem1.c ********************************************/
  21857. /*
  21858. ** 2007 August 14
  21859. **
  21860. ** The author disclaims copyright to this source code. In place of
  21861. ** a legal notice, here is a blessing:
  21862. **
  21863. ** May you do good and not evil.
  21864. ** May you find forgiveness for yourself and forgive others.
  21865. ** May you share freely, never taking more than you give.
  21866. **
  21867. *************************************************************************
  21868. **
  21869. ** This file contains low-level memory allocation drivers for when
  21870. ** SQLite will use the standard C-library malloc/realloc/free interface
  21871. ** to obtain the memory it needs.
  21872. **
  21873. ** This file contains implementations of the low-level memory allocation
  21874. ** routines specified in the sqlite3_mem_methods object. The content of
  21875. ** this file is only used if SQLITE_SYSTEM_MALLOC is defined. The
  21876. ** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the
  21877. ** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined. The
  21878. ** default configuration is to use memory allocation routines in this
  21879. ** file.
  21880. **
  21881. ** C-preprocessor macro summary:
  21882. **
  21883. ** HAVE_MALLOC_USABLE_SIZE The configure script sets this symbol if
  21884. ** the malloc_usable_size() interface exists
  21885. ** on the target platform. Or, this symbol
  21886. ** can be set manually, if desired.
  21887. ** If an equivalent interface exists by
  21888. ** a different name, using a separate -D
  21889. ** option to rename it.
  21890. **
  21891. ** SQLITE_WITHOUT_ZONEMALLOC Some older macs lack support for the zone
  21892. ** memory allocator. Set this symbol to enable
  21893. ** building on older macs.
  21894. **
  21895. ** SQLITE_WITHOUT_MSIZE Set this symbol to disable the use of
  21896. ** _msize() on windows systems. This might
  21897. ** be necessary when compiling for Delphi,
  21898. ** for example.
  21899. */
  21900. /* #include "sqliteInt.h" */
  21901. /*
  21902. ** This version of the memory allocator is the default. It is
  21903. ** used when no other memory allocator is specified using compile-time
  21904. ** macros.
  21905. */
  21906. #ifdef SQLITE_SYSTEM_MALLOC
  21907. #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
  21908. /*
  21909. ** Use the zone allocator available on apple products unless the
  21910. ** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.
  21911. */
  21912. #include <sys/sysctl.h>
  21913. #include <malloc/malloc.h>
  21914. #ifdef SQLITE_MIGHT_BE_SINGLE_CORE
  21915. #include <libkern/OSAtomic.h>
  21916. #endif /* SQLITE_MIGHT_BE_SINGLE_CORE */
  21917. static malloc_zone_t* _sqliteZone_;
  21918. #define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
  21919. #define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
  21920. #define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
  21921. #define SQLITE_MALLOCSIZE(x) \
  21922. (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
  21923. #else /* if not __APPLE__ */
  21924. /*
  21925. ** Use standard C library malloc and free on non-Apple systems.
  21926. ** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
  21927. */
  21928. #define SQLITE_MALLOC(x) malloc(x)
  21929. #define SQLITE_FREE(x) free(x)
  21930. #define SQLITE_REALLOC(x,y) realloc((x),(y))
  21931. /*
  21932. ** The malloc.h header file is needed for malloc_usable_size() function
  21933. ** on some systems (e.g. Linux).
  21934. */
  21935. #if HAVE_MALLOC_H && HAVE_MALLOC_USABLE_SIZE
  21936. # define SQLITE_USE_MALLOC_H 1
  21937. # define SQLITE_USE_MALLOC_USABLE_SIZE 1
  21938. /*
  21939. ** The MSVCRT has malloc_usable_size(), but it is called _msize(). The
  21940. ** use of _msize() is automatic, but can be disabled by compiling with
  21941. ** -DSQLITE_WITHOUT_MSIZE. Using the _msize() function also requires
  21942. ** the malloc.h header file.
  21943. */
  21944. #elif defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)
  21945. # define SQLITE_USE_MALLOC_H
  21946. # define SQLITE_USE_MSIZE
  21947. #endif
  21948. /*
  21949. ** Include the malloc.h header file, if necessary. Also set define macro
  21950. ** SQLITE_MALLOCSIZE to the appropriate function name, which is _msize()
  21951. ** for MSVC and malloc_usable_size() for most other systems (e.g. Linux).
  21952. ** The memory size function can always be overridden manually by defining
  21953. ** the macro SQLITE_MALLOCSIZE to the desired function name.
  21954. */
  21955. #if defined(SQLITE_USE_MALLOC_H)
  21956. # include <malloc.h>
  21957. # if defined(SQLITE_USE_MALLOC_USABLE_SIZE)
  21958. # if !defined(SQLITE_MALLOCSIZE)
  21959. # define SQLITE_MALLOCSIZE(x) malloc_usable_size(x)
  21960. # endif
  21961. # elif defined(SQLITE_USE_MSIZE)
  21962. # if !defined(SQLITE_MALLOCSIZE)
  21963. # define SQLITE_MALLOCSIZE _msize
  21964. # endif
  21965. # endif
  21966. #endif /* defined(SQLITE_USE_MALLOC_H) */
  21967. #endif /* __APPLE__ or not __APPLE__ */
  21968. /*
  21969. ** Like malloc(), but remember the size of the allocation
  21970. ** so that we can find it later using sqlite3MemSize().
  21971. **
  21972. ** For this low-level routine, we are guaranteed that nByte>0 because
  21973. ** cases of nByte<=0 will be intercepted and dealt with by higher level
  21974. ** routines.
  21975. */
  21976. static void *sqlite3MemMalloc(int nByte){
  21977. #ifdef SQLITE_MALLOCSIZE
  21978. void *p;
  21979. testcase( ROUND8(nByte)==nByte );
  21980. p = SQLITE_MALLOC( nByte );
  21981. if( p==0 ){
  21982. testcase( sqlite3GlobalConfig.xLog!=0 );
  21983. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
  21984. }
  21985. return p;
  21986. #else
  21987. sqlite3_int64 *p;
  21988. assert( nByte>0 );
  21989. testcase( ROUND8(nByte)!=nByte );
  21990. p = SQLITE_MALLOC( nByte+8 );
  21991. if( p ){
  21992. p[0] = nByte;
  21993. p++;
  21994. }else{
  21995. testcase( sqlite3GlobalConfig.xLog!=0 );
  21996. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
  21997. }
  21998. return (void *)p;
  21999. #endif
  22000. }
  22001. /*
  22002. ** Like free() but works for allocations obtained from sqlite3MemMalloc()
  22003. ** or sqlite3MemRealloc().
  22004. **
  22005. ** For this low-level routine, we already know that pPrior!=0 since
  22006. ** cases where pPrior==0 will have been intecepted and dealt with
  22007. ** by higher-level routines.
  22008. */
  22009. static void sqlite3MemFree(void *pPrior){
  22010. #ifdef SQLITE_MALLOCSIZE
  22011. SQLITE_FREE(pPrior);
  22012. #else
  22013. sqlite3_int64 *p = (sqlite3_int64*)pPrior;
  22014. assert( pPrior!=0 );
  22015. p--;
  22016. SQLITE_FREE(p);
  22017. #endif
  22018. }
  22019. /*
  22020. ** Report the allocated size of a prior return from xMalloc()
  22021. ** or xRealloc().
  22022. */
  22023. static int sqlite3MemSize(void *pPrior){
  22024. #ifdef SQLITE_MALLOCSIZE
  22025. assert( pPrior!=0 );
  22026. return (int)SQLITE_MALLOCSIZE(pPrior);
  22027. #else
  22028. sqlite3_int64 *p;
  22029. assert( pPrior!=0 );
  22030. p = (sqlite3_int64*)pPrior;
  22031. p--;
  22032. return (int)p[0];
  22033. #endif
  22034. }
  22035. /*
  22036. ** Like realloc(). Resize an allocation previously obtained from
  22037. ** sqlite3MemMalloc().
  22038. **
  22039. ** For this low-level interface, we know that pPrior!=0. Cases where
  22040. ** pPrior==0 while have been intercepted by higher-level routine and
  22041. ** redirected to xMalloc. Similarly, we know that nByte>0 because
  22042. ** cases where nByte<=0 will have been intercepted by higher-level
  22043. ** routines and redirected to xFree.
  22044. */
  22045. static void *sqlite3MemRealloc(void *pPrior, int nByte){
  22046. #ifdef SQLITE_MALLOCSIZE
  22047. void *p = SQLITE_REALLOC(pPrior, nByte);
  22048. if( p==0 ){
  22049. testcase( sqlite3GlobalConfig.xLog!=0 );
  22050. sqlite3_log(SQLITE_NOMEM,
  22051. "failed memory resize %u to %u bytes",
  22052. SQLITE_MALLOCSIZE(pPrior), nByte);
  22053. }
  22054. return p;
  22055. #else
  22056. sqlite3_int64 *p = (sqlite3_int64*)pPrior;
  22057. assert( pPrior!=0 && nByte>0 );
  22058. assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
  22059. p--;
  22060. p = SQLITE_REALLOC(p, nByte+8 );
  22061. if( p ){
  22062. p[0] = nByte;
  22063. p++;
  22064. }else{
  22065. testcase( sqlite3GlobalConfig.xLog!=0 );
  22066. sqlite3_log(SQLITE_NOMEM,
  22067. "failed memory resize %u to %u bytes",
  22068. sqlite3MemSize(pPrior), nByte);
  22069. }
  22070. return (void*)p;
  22071. #endif
  22072. }
  22073. /*
  22074. ** Round up a request size to the next valid allocation size.
  22075. */
  22076. static int sqlite3MemRoundup(int n){
  22077. return ROUND8(n);
  22078. }
  22079. /*
  22080. ** Initialize this module.
  22081. */
  22082. static int sqlite3MemInit(void *NotUsed){
  22083. #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
  22084. int cpuCount;
  22085. size_t len;
  22086. if( _sqliteZone_ ){
  22087. return SQLITE_OK;
  22088. }
  22089. len = sizeof(cpuCount);
  22090. /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
  22091. sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
  22092. if( cpuCount>1 ){
  22093. /* defer MT decisions to system malloc */
  22094. _sqliteZone_ = malloc_default_zone();
  22095. }else{
  22096. /* only 1 core, use our own zone to contention over global locks,
  22097. ** e.g. we have our own dedicated locks */
  22098. _sqliteZone_ = malloc_create_zone(4096, 0);
  22099. malloc_set_zone_name(_sqliteZone_, "Sqlite_Heap");
  22100. }
  22101. #endif /* defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC) */
  22102. UNUSED_PARAMETER(NotUsed);
  22103. return SQLITE_OK;
  22104. }
  22105. /*
  22106. ** Deinitialize this module.
  22107. */
  22108. static void sqlite3MemShutdown(void *NotUsed){
  22109. UNUSED_PARAMETER(NotUsed);
  22110. return;
  22111. }
  22112. /*
  22113. ** This routine is the only routine in this file with external linkage.
  22114. **
  22115. ** Populate the low-level memory allocation function pointers in
  22116. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  22117. */
  22118. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  22119. static const sqlite3_mem_methods defaultMethods = {
  22120. sqlite3MemMalloc,
  22121. sqlite3MemFree,
  22122. sqlite3MemRealloc,
  22123. sqlite3MemSize,
  22124. sqlite3MemRoundup,
  22125. sqlite3MemInit,
  22126. sqlite3MemShutdown,
  22127. 0
  22128. };
  22129. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  22130. }
  22131. #endif /* SQLITE_SYSTEM_MALLOC */
  22132. /************** End of mem1.c ************************************************/
  22133. /************** Begin file mem2.c ********************************************/
  22134. /*
  22135. ** 2007 August 15
  22136. **
  22137. ** The author disclaims copyright to this source code. In place of
  22138. ** a legal notice, here is a blessing:
  22139. **
  22140. ** May you do good and not evil.
  22141. ** May you find forgiveness for yourself and forgive others.
  22142. ** May you share freely, never taking more than you give.
  22143. **
  22144. *************************************************************************
  22145. **
  22146. ** This file contains low-level memory allocation drivers for when
  22147. ** SQLite will use the standard C-library malloc/realloc/free interface
  22148. ** to obtain the memory it needs while adding lots of additional debugging
  22149. ** information to each allocation in order to help detect and fix memory
  22150. ** leaks and memory usage errors.
  22151. **
  22152. ** This file contains implementations of the low-level memory allocation
  22153. ** routines specified in the sqlite3_mem_methods object.
  22154. */
  22155. /* #include "sqliteInt.h" */
  22156. /*
  22157. ** This version of the memory allocator is used only if the
  22158. ** SQLITE_MEMDEBUG macro is defined
  22159. */
  22160. #ifdef SQLITE_MEMDEBUG
  22161. /*
  22162. ** The backtrace functionality is only available with GLIBC
  22163. */
  22164. #ifdef __GLIBC__
  22165. extern int backtrace(void**,int);
  22166. extern void backtrace_symbols_fd(void*const*,int,int);
  22167. #else
  22168. # define backtrace(A,B) 1
  22169. # define backtrace_symbols_fd(A,B,C)
  22170. #endif
  22171. /* #include <stdio.h> */
  22172. /*
  22173. ** Each memory allocation looks like this:
  22174. **
  22175. ** ------------------------------------------------------------------------
  22176. ** | Title | backtrace pointers | MemBlockHdr | allocation | EndGuard |
  22177. ** ------------------------------------------------------------------------
  22178. **
  22179. ** The application code sees only a pointer to the allocation. We have
  22180. ** to back up from the allocation pointer to find the MemBlockHdr. The
  22181. ** MemBlockHdr tells us the size of the allocation and the number of
  22182. ** backtrace pointers. There is also a guard word at the end of the
  22183. ** MemBlockHdr.
  22184. */
  22185. struct MemBlockHdr {
  22186. i64 iSize; /* Size of this allocation */
  22187. struct MemBlockHdr *pNext, *pPrev; /* Linked list of all unfreed memory */
  22188. char nBacktrace; /* Number of backtraces on this alloc */
  22189. char nBacktraceSlots; /* Available backtrace slots */
  22190. u8 nTitle; /* Bytes of title; includes '\0' */
  22191. u8 eType; /* Allocation type code */
  22192. int iForeGuard; /* Guard word for sanity */
  22193. };
  22194. /*
  22195. ** Guard words
  22196. */
  22197. #define FOREGUARD 0x80F5E153
  22198. #define REARGUARD 0xE4676B53
  22199. /*
  22200. ** Number of malloc size increments to track.
  22201. */
  22202. #define NCSIZE 1000
  22203. /*
  22204. ** All of the static variables used by this module are collected
  22205. ** into a single structure named "mem". This is to keep the
  22206. ** static variables organized and to reduce namespace pollution
  22207. ** when this module is combined with other in the amalgamation.
  22208. */
  22209. static struct {
  22210. /*
  22211. ** Mutex to control access to the memory allocation subsystem.
  22212. */
  22213. sqlite3_mutex *mutex;
  22214. /*
  22215. ** Head and tail of a linked list of all outstanding allocations
  22216. */
  22217. struct MemBlockHdr *pFirst;
  22218. struct MemBlockHdr *pLast;
  22219. /*
  22220. ** The number of levels of backtrace to save in new allocations.
  22221. */
  22222. int nBacktrace;
  22223. void (*xBacktrace)(int, int, void **);
  22224. /*
  22225. ** Title text to insert in front of each block
  22226. */
  22227. int nTitle; /* Bytes of zTitle to save. Includes '\0' and padding */
  22228. char zTitle[100]; /* The title text */
  22229. /*
  22230. ** sqlite3MallocDisallow() increments the following counter.
  22231. ** sqlite3MallocAllow() decrements it.
  22232. */
  22233. int disallow; /* Do not allow memory allocation */
  22234. /*
  22235. ** Gather statistics on the sizes of memory allocations.
  22236. ** nAlloc[i] is the number of allocation attempts of i*8
  22237. ** bytes. i==NCSIZE is the number of allocation attempts for
  22238. ** sizes more than NCSIZE*8 bytes.
  22239. */
  22240. int nAlloc[NCSIZE]; /* Total number of allocations */
  22241. int nCurrent[NCSIZE]; /* Current number of allocations */
  22242. int mxCurrent[NCSIZE]; /* Highwater mark for nCurrent */
  22243. } mem;
  22244. /*
  22245. ** Adjust memory usage statistics
  22246. */
  22247. static void adjustStats(int iSize, int increment){
  22248. int i = ROUND8(iSize)/8;
  22249. if( i>NCSIZE-1 ){
  22250. i = NCSIZE - 1;
  22251. }
  22252. if( increment>0 ){
  22253. mem.nAlloc[i]++;
  22254. mem.nCurrent[i]++;
  22255. if( mem.nCurrent[i]>mem.mxCurrent[i] ){
  22256. mem.mxCurrent[i] = mem.nCurrent[i];
  22257. }
  22258. }else{
  22259. mem.nCurrent[i]--;
  22260. assert( mem.nCurrent[i]>=0 );
  22261. }
  22262. }
  22263. /*
  22264. ** Given an allocation, find the MemBlockHdr for that allocation.
  22265. **
  22266. ** This routine checks the guards at either end of the allocation and
  22267. ** if they are incorrect it asserts.
  22268. */
  22269. static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
  22270. struct MemBlockHdr *p;
  22271. int *pInt;
  22272. u8 *pU8;
  22273. int nReserve;
  22274. p = (struct MemBlockHdr*)pAllocation;
  22275. p--;
  22276. assert( p->iForeGuard==(int)FOREGUARD );
  22277. nReserve = ROUND8(p->iSize);
  22278. pInt = (int*)pAllocation;
  22279. pU8 = (u8*)pAllocation;
  22280. assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
  22281. /* This checks any of the "extra" bytes allocated due
  22282. ** to rounding up to an 8 byte boundary to ensure
  22283. ** they haven't been overwritten.
  22284. */
  22285. while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
  22286. return p;
  22287. }
  22288. /*
  22289. ** Return the number of bytes currently allocated at address p.
  22290. */
  22291. static int sqlite3MemSize(void *p){
  22292. struct MemBlockHdr *pHdr;
  22293. if( !p ){
  22294. return 0;
  22295. }
  22296. pHdr = sqlite3MemsysGetHeader(p);
  22297. return (int)pHdr->iSize;
  22298. }
  22299. /*
  22300. ** Initialize the memory allocation subsystem.
  22301. */
  22302. static int sqlite3MemInit(void *NotUsed){
  22303. UNUSED_PARAMETER(NotUsed);
  22304. assert( (sizeof(struct MemBlockHdr)&7) == 0 );
  22305. if( !sqlite3GlobalConfig.bMemstat ){
  22306. /* If memory status is enabled, then the malloc.c wrapper will already
  22307. ** hold the STATIC_MEM mutex when the routines here are invoked. */
  22308. mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  22309. }
  22310. return SQLITE_OK;
  22311. }
  22312. /*
  22313. ** Deinitialize the memory allocation subsystem.
  22314. */
  22315. static void sqlite3MemShutdown(void *NotUsed){
  22316. UNUSED_PARAMETER(NotUsed);
  22317. mem.mutex = 0;
  22318. }
  22319. /*
  22320. ** Round up a request size to the next valid allocation size.
  22321. */
  22322. static int sqlite3MemRoundup(int n){
  22323. return ROUND8(n);
  22324. }
  22325. /*
  22326. ** Fill a buffer with pseudo-random bytes. This is used to preset
  22327. ** the content of a new memory allocation to unpredictable values and
  22328. ** to clear the content of a freed allocation to unpredictable values.
  22329. */
  22330. static void randomFill(char *pBuf, int nByte){
  22331. unsigned int x, y, r;
  22332. x = SQLITE_PTR_TO_INT(pBuf);
  22333. y = nByte | 1;
  22334. while( nByte >= 4 ){
  22335. x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
  22336. y = y*1103515245 + 12345;
  22337. r = x ^ y;
  22338. *(int*)pBuf = r;
  22339. pBuf += 4;
  22340. nByte -= 4;
  22341. }
  22342. while( nByte-- > 0 ){
  22343. x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
  22344. y = y*1103515245 + 12345;
  22345. r = x ^ y;
  22346. *(pBuf++) = r & 0xff;
  22347. }
  22348. }
  22349. /*
  22350. ** Allocate nByte bytes of memory.
  22351. */
  22352. static void *sqlite3MemMalloc(int nByte){
  22353. struct MemBlockHdr *pHdr;
  22354. void **pBt;
  22355. char *z;
  22356. int *pInt;
  22357. void *p = 0;
  22358. int totalSize;
  22359. int nReserve;
  22360. sqlite3_mutex_enter(mem.mutex);
  22361. assert( mem.disallow==0 );
  22362. nReserve = ROUND8(nByte);
  22363. totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
  22364. mem.nBacktrace*sizeof(void*) + mem.nTitle;
  22365. p = malloc(totalSize);
  22366. if( p ){
  22367. z = p;
  22368. pBt = (void**)&z[mem.nTitle];
  22369. pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
  22370. pHdr->pNext = 0;
  22371. pHdr->pPrev = mem.pLast;
  22372. if( mem.pLast ){
  22373. mem.pLast->pNext = pHdr;
  22374. }else{
  22375. mem.pFirst = pHdr;
  22376. }
  22377. mem.pLast = pHdr;
  22378. pHdr->iForeGuard = FOREGUARD;
  22379. pHdr->eType = MEMTYPE_HEAP;
  22380. pHdr->nBacktraceSlots = mem.nBacktrace;
  22381. pHdr->nTitle = mem.nTitle;
  22382. if( mem.nBacktrace ){
  22383. void *aAddr[40];
  22384. pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
  22385. memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
  22386. assert(pBt[0]);
  22387. if( mem.xBacktrace ){
  22388. mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
  22389. }
  22390. }else{
  22391. pHdr->nBacktrace = 0;
  22392. }
  22393. if( mem.nTitle ){
  22394. memcpy(z, mem.zTitle, mem.nTitle);
  22395. }
  22396. pHdr->iSize = nByte;
  22397. adjustStats(nByte, +1);
  22398. pInt = (int*)&pHdr[1];
  22399. pInt[nReserve/sizeof(int)] = REARGUARD;
  22400. randomFill((char*)pInt, nByte);
  22401. memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
  22402. p = (void*)pInt;
  22403. }
  22404. sqlite3_mutex_leave(mem.mutex);
  22405. return p;
  22406. }
  22407. /*
  22408. ** Free memory.
  22409. */
  22410. static void sqlite3MemFree(void *pPrior){
  22411. struct MemBlockHdr *pHdr;
  22412. void **pBt;
  22413. char *z;
  22414. assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0
  22415. || mem.mutex!=0 );
  22416. pHdr = sqlite3MemsysGetHeader(pPrior);
  22417. pBt = (void**)pHdr;
  22418. pBt -= pHdr->nBacktraceSlots;
  22419. sqlite3_mutex_enter(mem.mutex);
  22420. if( pHdr->pPrev ){
  22421. assert( pHdr->pPrev->pNext==pHdr );
  22422. pHdr->pPrev->pNext = pHdr->pNext;
  22423. }else{
  22424. assert( mem.pFirst==pHdr );
  22425. mem.pFirst = pHdr->pNext;
  22426. }
  22427. if( pHdr->pNext ){
  22428. assert( pHdr->pNext->pPrev==pHdr );
  22429. pHdr->pNext->pPrev = pHdr->pPrev;
  22430. }else{
  22431. assert( mem.pLast==pHdr );
  22432. mem.pLast = pHdr->pPrev;
  22433. }
  22434. z = (char*)pBt;
  22435. z -= pHdr->nTitle;
  22436. adjustStats((int)pHdr->iSize, -1);
  22437. randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
  22438. (int)pHdr->iSize + sizeof(int) + pHdr->nTitle);
  22439. free(z);
  22440. sqlite3_mutex_leave(mem.mutex);
  22441. }
  22442. /*
  22443. ** Change the size of an existing memory allocation.
  22444. **
  22445. ** For this debugging implementation, we *always* make a copy of the
  22446. ** allocation into a new place in memory. In this way, if the
  22447. ** higher level code is using pointer to the old allocation, it is
  22448. ** much more likely to break and we are much more liking to find
  22449. ** the error.
  22450. */
  22451. static void *sqlite3MemRealloc(void *pPrior, int nByte){
  22452. struct MemBlockHdr *pOldHdr;
  22453. void *pNew;
  22454. assert( mem.disallow==0 );
  22455. assert( (nByte & 7)==0 ); /* EV: R-46199-30249 */
  22456. pOldHdr = sqlite3MemsysGetHeader(pPrior);
  22457. pNew = sqlite3MemMalloc(nByte);
  22458. if( pNew ){
  22459. memcpy(pNew, pPrior, (int)(nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize));
  22460. if( nByte>pOldHdr->iSize ){
  22461. randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - (int)pOldHdr->iSize);
  22462. }
  22463. sqlite3MemFree(pPrior);
  22464. }
  22465. return pNew;
  22466. }
  22467. /*
  22468. ** Populate the low-level memory allocation function pointers in
  22469. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  22470. */
  22471. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  22472. static const sqlite3_mem_methods defaultMethods = {
  22473. sqlite3MemMalloc,
  22474. sqlite3MemFree,
  22475. sqlite3MemRealloc,
  22476. sqlite3MemSize,
  22477. sqlite3MemRoundup,
  22478. sqlite3MemInit,
  22479. sqlite3MemShutdown,
  22480. 0
  22481. };
  22482. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  22483. }
  22484. /*
  22485. ** Set the "type" of an allocation.
  22486. */
  22487. SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
  22488. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  22489. struct MemBlockHdr *pHdr;
  22490. pHdr = sqlite3MemsysGetHeader(p);
  22491. assert( pHdr->iForeGuard==FOREGUARD );
  22492. pHdr->eType = eType;
  22493. }
  22494. }
  22495. /*
  22496. ** Return TRUE if the mask of type in eType matches the type of the
  22497. ** allocation p. Also return true if p==NULL.
  22498. **
  22499. ** This routine is designed for use within an assert() statement, to
  22500. ** verify the type of an allocation. For example:
  22501. **
  22502. ** assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  22503. */
  22504. SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
  22505. int rc = 1;
  22506. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  22507. struct MemBlockHdr *pHdr;
  22508. pHdr = sqlite3MemsysGetHeader(p);
  22509. assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
  22510. if( (pHdr->eType&eType)==0 ){
  22511. rc = 0;
  22512. }
  22513. }
  22514. return rc;
  22515. }
  22516. /*
  22517. ** Return TRUE if the mask of type in eType matches no bits of the type of the
  22518. ** allocation p. Also return true if p==NULL.
  22519. **
  22520. ** This routine is designed for use within an assert() statement, to
  22521. ** verify the type of an allocation. For example:
  22522. **
  22523. ** assert( sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
  22524. */
  22525. SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
  22526. int rc = 1;
  22527. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  22528. struct MemBlockHdr *pHdr;
  22529. pHdr = sqlite3MemsysGetHeader(p);
  22530. assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
  22531. if( (pHdr->eType&eType)!=0 ){
  22532. rc = 0;
  22533. }
  22534. }
  22535. return rc;
  22536. }
  22537. /*
  22538. ** Set the number of backtrace levels kept for each allocation.
  22539. ** A value of zero turns off backtracing. The number is always rounded
  22540. ** up to a multiple of 2.
  22541. */
  22542. SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
  22543. if( depth<0 ){ depth = 0; }
  22544. if( depth>20 ){ depth = 20; }
  22545. depth = (depth+1)&0xfe;
  22546. mem.nBacktrace = depth;
  22547. }
  22548. SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
  22549. mem.xBacktrace = xBacktrace;
  22550. }
  22551. /*
  22552. ** Set the title string for subsequent allocations.
  22553. */
  22554. SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
  22555. unsigned int n = sqlite3Strlen30(zTitle) + 1;
  22556. sqlite3_mutex_enter(mem.mutex);
  22557. if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
  22558. memcpy(mem.zTitle, zTitle, n);
  22559. mem.zTitle[n] = 0;
  22560. mem.nTitle = ROUND8(n);
  22561. sqlite3_mutex_leave(mem.mutex);
  22562. }
  22563. SQLITE_PRIVATE void sqlite3MemdebugSync(){
  22564. struct MemBlockHdr *pHdr;
  22565. for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
  22566. void **pBt = (void**)pHdr;
  22567. pBt -= pHdr->nBacktraceSlots;
  22568. mem.xBacktrace((int)pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
  22569. }
  22570. }
  22571. /*
  22572. ** Open the file indicated and write a log of all unfreed memory
  22573. ** allocations into that log.
  22574. */
  22575. SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
  22576. FILE *out;
  22577. struct MemBlockHdr *pHdr;
  22578. void **pBt;
  22579. int i;
  22580. out = fopen(zFilename, "w");
  22581. if( out==0 ){
  22582. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  22583. zFilename);
  22584. return;
  22585. }
  22586. for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
  22587. char *z = (char*)pHdr;
  22588. z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
  22589. fprintf(out, "**** %lld bytes at %p from %s ****\n",
  22590. pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
  22591. if( pHdr->nBacktrace ){
  22592. fflush(out);
  22593. pBt = (void**)pHdr;
  22594. pBt -= pHdr->nBacktraceSlots;
  22595. backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
  22596. fprintf(out, "\n");
  22597. }
  22598. }
  22599. fprintf(out, "COUNTS:\n");
  22600. for(i=0; i<NCSIZE-1; i++){
  22601. if( mem.nAlloc[i] ){
  22602. fprintf(out, " %5d: %10d %10d %10d\n",
  22603. i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
  22604. }
  22605. }
  22606. if( mem.nAlloc[NCSIZE-1] ){
  22607. fprintf(out, " %5d: %10d %10d %10d\n",
  22608. NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
  22609. mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
  22610. }
  22611. fclose(out);
  22612. }
  22613. /*
  22614. ** Return the number of times sqlite3MemMalloc() has been called.
  22615. */
  22616. SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
  22617. int i;
  22618. int nTotal = 0;
  22619. for(i=0; i<NCSIZE; i++){
  22620. nTotal += mem.nAlloc[i];
  22621. }
  22622. return nTotal;
  22623. }
  22624. #endif /* SQLITE_MEMDEBUG */
  22625. /************** End of mem2.c ************************************************/
  22626. /************** Begin file mem3.c ********************************************/
  22627. /*
  22628. ** 2007 October 14
  22629. **
  22630. ** The author disclaims copyright to this source code. In place of
  22631. ** a legal notice, here is a blessing:
  22632. **
  22633. ** May you do good and not evil.
  22634. ** May you find forgiveness for yourself and forgive others.
  22635. ** May you share freely, never taking more than you give.
  22636. **
  22637. *************************************************************************
  22638. ** This file contains the C functions that implement a memory
  22639. ** allocation subsystem for use by SQLite.
  22640. **
  22641. ** This version of the memory allocation subsystem omits all
  22642. ** use of malloc(). The SQLite user supplies a block of memory
  22643. ** before calling sqlite3_initialize() from which allocations
  22644. ** are made and returned by the xMalloc() and xRealloc()
  22645. ** implementations. Once sqlite3_initialize() has been called,
  22646. ** the amount of memory available to SQLite is fixed and cannot
  22647. ** be changed.
  22648. **
  22649. ** This version of the memory allocation subsystem is included
  22650. ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
  22651. */
  22652. /* #include "sqliteInt.h" */
  22653. /*
  22654. ** This version of the memory allocator is only built into the library
  22655. ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
  22656. ** mean that the library will use a memory-pool by default, just that
  22657. ** it is available. The mempool allocator is activated by calling
  22658. ** sqlite3_config().
  22659. */
  22660. #ifdef SQLITE_ENABLE_MEMSYS3
  22661. /*
  22662. ** Maximum size (in Mem3Blocks) of a "small" chunk.
  22663. */
  22664. #define MX_SMALL 10
  22665. /*
  22666. ** Number of freelist hash slots
  22667. */
  22668. #define N_HASH 61
  22669. /*
  22670. ** A memory allocation (also called a "chunk") consists of two or
  22671. ** more blocks where each block is 8 bytes. The first 8 bytes are
  22672. ** a header that is not returned to the user.
  22673. **
  22674. ** A chunk is two or more blocks that is either checked out or
  22675. ** free. The first block has format u.hdr. u.hdr.size4x is 4 times the
  22676. ** size of the allocation in blocks if the allocation is free.
  22677. ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
  22678. ** false if the chunk is on the freelist. The u.hdr.size4x&2 bit
  22679. ** is true if the previous chunk is checked out and false if the
  22680. ** previous chunk is free. The u.hdr.prevSize field is the size of
  22681. ** the previous chunk in blocks if the previous chunk is on the
  22682. ** freelist. If the previous chunk is checked out, then
  22683. ** u.hdr.prevSize can be part of the data for that chunk and should
  22684. ** not be read or written.
  22685. **
  22686. ** We often identify a chunk by its index in mem3.aPool[]. When
  22687. ** this is done, the chunk index refers to the second block of
  22688. ** the chunk. In this way, the first chunk has an index of 1.
  22689. ** A chunk index of 0 means "no such chunk" and is the equivalent
  22690. ** of a NULL pointer.
  22691. **
  22692. ** The second block of free chunks is of the form u.list. The
  22693. ** two fields form a double-linked list of chunks of related sizes.
  22694. ** Pointers to the head of the list are stored in mem3.aiSmall[]
  22695. ** for smaller chunks and mem3.aiHash[] for larger chunks.
  22696. **
  22697. ** The second block of a chunk is user data if the chunk is checked
  22698. ** out. If a chunk is checked out, the user data may extend into
  22699. ** the u.hdr.prevSize value of the following chunk.
  22700. */
  22701. typedef struct Mem3Block Mem3Block;
  22702. struct Mem3Block {
  22703. union {
  22704. struct {
  22705. u32 prevSize; /* Size of previous chunk in Mem3Block elements */
  22706. u32 size4x; /* 4x the size of current chunk in Mem3Block elements */
  22707. } hdr;
  22708. struct {
  22709. u32 next; /* Index in mem3.aPool[] of next free chunk */
  22710. u32 prev; /* Index in mem3.aPool[] of previous free chunk */
  22711. } list;
  22712. } u;
  22713. };
  22714. /*
  22715. ** All of the static variables used by this module are collected
  22716. ** into a single structure named "mem3". This is to keep the
  22717. ** static variables organized and to reduce namespace pollution
  22718. ** when this module is combined with other in the amalgamation.
  22719. */
  22720. static SQLITE_WSD struct Mem3Global {
  22721. /*
  22722. ** Memory available for allocation. nPool is the size of the array
  22723. ** (in Mem3Blocks) pointed to by aPool less 2.
  22724. */
  22725. u32 nPool;
  22726. Mem3Block *aPool;
  22727. /*
  22728. ** True if we are evaluating an out-of-memory callback.
  22729. */
  22730. int alarmBusy;
  22731. /*
  22732. ** Mutex to control access to the memory allocation subsystem.
  22733. */
  22734. sqlite3_mutex *mutex;
  22735. /*
  22736. ** The minimum amount of free space that we have seen.
  22737. */
  22738. u32 mnMaster;
  22739. /*
  22740. ** iMaster is the index of the master chunk. Most new allocations
  22741. ** occur off of this chunk. szMaster is the size (in Mem3Blocks)
  22742. ** of the current master. iMaster is 0 if there is not master chunk.
  22743. ** The master chunk is not in either the aiHash[] or aiSmall[].
  22744. */
  22745. u32 iMaster;
  22746. u32 szMaster;
  22747. /*
  22748. ** Array of lists of free blocks according to the block size
  22749. ** for smaller chunks, or a hash on the block size for larger
  22750. ** chunks.
  22751. */
  22752. u32 aiSmall[MX_SMALL-1]; /* For sizes 2 through MX_SMALL, inclusive */
  22753. u32 aiHash[N_HASH]; /* For sizes MX_SMALL+1 and larger */
  22754. } mem3 = { 97535575 };
  22755. #define mem3 GLOBAL(struct Mem3Global, mem3)
  22756. /*
  22757. ** Unlink the chunk at mem3.aPool[i] from list it is currently
  22758. ** on. *pRoot is the list that i is a member of.
  22759. */
  22760. static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
  22761. u32 next = mem3.aPool[i].u.list.next;
  22762. u32 prev = mem3.aPool[i].u.list.prev;
  22763. assert( sqlite3_mutex_held(mem3.mutex) );
  22764. if( prev==0 ){
  22765. *pRoot = next;
  22766. }else{
  22767. mem3.aPool[prev].u.list.next = next;
  22768. }
  22769. if( next ){
  22770. mem3.aPool[next].u.list.prev = prev;
  22771. }
  22772. mem3.aPool[i].u.list.next = 0;
  22773. mem3.aPool[i].u.list.prev = 0;
  22774. }
  22775. /*
  22776. ** Unlink the chunk at index i from
  22777. ** whatever list is currently a member of.
  22778. */
  22779. static void memsys3Unlink(u32 i){
  22780. u32 size, hash;
  22781. assert( sqlite3_mutex_held(mem3.mutex) );
  22782. assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
  22783. assert( i>=1 );
  22784. size = mem3.aPool[i-1].u.hdr.size4x/4;
  22785. assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
  22786. assert( size>=2 );
  22787. if( size <= MX_SMALL ){
  22788. memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
  22789. }else{
  22790. hash = size % N_HASH;
  22791. memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
  22792. }
  22793. }
  22794. /*
  22795. ** Link the chunk at mem3.aPool[i] so that is on the list rooted
  22796. ** at *pRoot.
  22797. */
  22798. static void memsys3LinkIntoList(u32 i, u32 *pRoot){
  22799. assert( sqlite3_mutex_held(mem3.mutex) );
  22800. mem3.aPool[i].u.list.next = *pRoot;
  22801. mem3.aPool[i].u.list.prev = 0;
  22802. if( *pRoot ){
  22803. mem3.aPool[*pRoot].u.list.prev = i;
  22804. }
  22805. *pRoot = i;
  22806. }
  22807. /*
  22808. ** Link the chunk at index i into either the appropriate
  22809. ** small chunk list, or into the large chunk hash table.
  22810. */
  22811. static void memsys3Link(u32 i){
  22812. u32 size, hash;
  22813. assert( sqlite3_mutex_held(mem3.mutex) );
  22814. assert( i>=1 );
  22815. assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
  22816. size = mem3.aPool[i-1].u.hdr.size4x/4;
  22817. assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
  22818. assert( size>=2 );
  22819. if( size <= MX_SMALL ){
  22820. memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
  22821. }else{
  22822. hash = size % N_HASH;
  22823. memsys3LinkIntoList(i, &mem3.aiHash[hash]);
  22824. }
  22825. }
  22826. /*
  22827. ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
  22828. ** will already be held (obtained by code in malloc.c) if
  22829. ** sqlite3GlobalConfig.bMemStat is true.
  22830. */
  22831. static void memsys3Enter(void){
  22832. if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
  22833. mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  22834. }
  22835. sqlite3_mutex_enter(mem3.mutex);
  22836. }
  22837. static void memsys3Leave(void){
  22838. sqlite3_mutex_leave(mem3.mutex);
  22839. }
  22840. /*
  22841. ** Called when we are unable to satisfy an allocation of nBytes.
  22842. */
  22843. static void memsys3OutOfMemory(int nByte){
  22844. if( !mem3.alarmBusy ){
  22845. mem3.alarmBusy = 1;
  22846. assert( sqlite3_mutex_held(mem3.mutex) );
  22847. sqlite3_mutex_leave(mem3.mutex);
  22848. sqlite3_release_memory(nByte);
  22849. sqlite3_mutex_enter(mem3.mutex);
  22850. mem3.alarmBusy = 0;
  22851. }
  22852. }
  22853. /*
  22854. ** Chunk i is a free chunk that has been unlinked. Adjust its
  22855. ** size parameters for check-out and return a pointer to the
  22856. ** user portion of the chunk.
  22857. */
  22858. static void *memsys3Checkout(u32 i, u32 nBlock){
  22859. u32 x;
  22860. assert( sqlite3_mutex_held(mem3.mutex) );
  22861. assert( i>=1 );
  22862. assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
  22863. assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
  22864. x = mem3.aPool[i-1].u.hdr.size4x;
  22865. mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
  22866. mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
  22867. mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
  22868. return &mem3.aPool[i];
  22869. }
  22870. /*
  22871. ** Carve a piece off of the end of the mem3.iMaster free chunk.
  22872. ** Return a pointer to the new allocation. Or, if the master chunk
  22873. ** is not large enough, return 0.
  22874. */
  22875. static void *memsys3FromMaster(u32 nBlock){
  22876. assert( sqlite3_mutex_held(mem3.mutex) );
  22877. assert( mem3.szMaster>=nBlock );
  22878. if( nBlock>=mem3.szMaster-1 ){
  22879. /* Use the entire master */
  22880. void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
  22881. mem3.iMaster = 0;
  22882. mem3.szMaster = 0;
  22883. mem3.mnMaster = 0;
  22884. return p;
  22885. }else{
  22886. /* Split the master block. Return the tail. */
  22887. u32 newi, x;
  22888. newi = mem3.iMaster + mem3.szMaster - nBlock;
  22889. assert( newi > mem3.iMaster+1 );
  22890. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
  22891. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
  22892. mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
  22893. mem3.szMaster -= nBlock;
  22894. mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
  22895. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  22896. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  22897. if( mem3.szMaster < mem3.mnMaster ){
  22898. mem3.mnMaster = mem3.szMaster;
  22899. }
  22900. return (void*)&mem3.aPool[newi];
  22901. }
  22902. }
  22903. /*
  22904. ** *pRoot is the head of a list of free chunks of the same size
  22905. ** or same size hash. In other words, *pRoot is an entry in either
  22906. ** mem3.aiSmall[] or mem3.aiHash[].
  22907. **
  22908. ** This routine examines all entries on the given list and tries
  22909. ** to coalesce each entries with adjacent free chunks.
  22910. **
  22911. ** If it sees a chunk that is larger than mem3.iMaster, it replaces
  22912. ** the current mem3.iMaster with the new larger chunk. In order for
  22913. ** this mem3.iMaster replacement to work, the master chunk must be
  22914. ** linked into the hash tables. That is not the normal state of
  22915. ** affairs, of course. The calling routine must link the master
  22916. ** chunk before invoking this routine, then must unlink the (possibly
  22917. ** changed) master chunk once this routine has finished.
  22918. */
  22919. static void memsys3Merge(u32 *pRoot){
  22920. u32 iNext, prev, size, i, x;
  22921. assert( sqlite3_mutex_held(mem3.mutex) );
  22922. for(i=*pRoot; i>0; i=iNext){
  22923. iNext = mem3.aPool[i].u.list.next;
  22924. size = mem3.aPool[i-1].u.hdr.size4x;
  22925. assert( (size&1)==0 );
  22926. if( (size&2)==0 ){
  22927. memsys3UnlinkFromList(i, pRoot);
  22928. assert( i > mem3.aPool[i-1].u.hdr.prevSize );
  22929. prev = i - mem3.aPool[i-1].u.hdr.prevSize;
  22930. if( prev==iNext ){
  22931. iNext = mem3.aPool[prev].u.list.next;
  22932. }
  22933. memsys3Unlink(prev);
  22934. size = i + size/4 - prev;
  22935. x = mem3.aPool[prev-1].u.hdr.size4x & 2;
  22936. mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
  22937. mem3.aPool[prev+size-1].u.hdr.prevSize = size;
  22938. memsys3Link(prev);
  22939. i = prev;
  22940. }else{
  22941. size /= 4;
  22942. }
  22943. if( size>mem3.szMaster ){
  22944. mem3.iMaster = i;
  22945. mem3.szMaster = size;
  22946. }
  22947. }
  22948. }
  22949. /*
  22950. ** Return a block of memory of at least nBytes in size.
  22951. ** Return NULL if unable.
  22952. **
  22953. ** This function assumes that the necessary mutexes, if any, are
  22954. ** already held by the caller. Hence "Unsafe".
  22955. */
  22956. static void *memsys3MallocUnsafe(int nByte){
  22957. u32 i;
  22958. u32 nBlock;
  22959. u32 toFree;
  22960. assert( sqlite3_mutex_held(mem3.mutex) );
  22961. assert( sizeof(Mem3Block)==8 );
  22962. if( nByte<=12 ){
  22963. nBlock = 2;
  22964. }else{
  22965. nBlock = (nByte + 11)/8;
  22966. }
  22967. assert( nBlock>=2 );
  22968. /* STEP 1:
  22969. ** Look for an entry of the correct size in either the small
  22970. ** chunk table or in the large chunk hash table. This is
  22971. ** successful most of the time (about 9 times out of 10).
  22972. */
  22973. if( nBlock <= MX_SMALL ){
  22974. i = mem3.aiSmall[nBlock-2];
  22975. if( i>0 ){
  22976. memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
  22977. return memsys3Checkout(i, nBlock);
  22978. }
  22979. }else{
  22980. int hash = nBlock % N_HASH;
  22981. for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
  22982. if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
  22983. memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
  22984. return memsys3Checkout(i, nBlock);
  22985. }
  22986. }
  22987. }
  22988. /* STEP 2:
  22989. ** Try to satisfy the allocation by carving a piece off of the end
  22990. ** of the master chunk. This step usually works if step 1 fails.
  22991. */
  22992. if( mem3.szMaster>=nBlock ){
  22993. return memsys3FromMaster(nBlock);
  22994. }
  22995. /* STEP 3:
  22996. ** Loop through the entire memory pool. Coalesce adjacent free
  22997. ** chunks. Recompute the master chunk as the largest free chunk.
  22998. ** Then try again to satisfy the allocation by carving a piece off
  22999. ** of the end of the master chunk. This step happens very
  23000. ** rarely (we hope!)
  23001. */
  23002. for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
  23003. memsys3OutOfMemory(toFree);
  23004. if( mem3.iMaster ){
  23005. memsys3Link(mem3.iMaster);
  23006. mem3.iMaster = 0;
  23007. mem3.szMaster = 0;
  23008. }
  23009. for(i=0; i<N_HASH; i++){
  23010. memsys3Merge(&mem3.aiHash[i]);
  23011. }
  23012. for(i=0; i<MX_SMALL-1; i++){
  23013. memsys3Merge(&mem3.aiSmall[i]);
  23014. }
  23015. if( mem3.szMaster ){
  23016. memsys3Unlink(mem3.iMaster);
  23017. if( mem3.szMaster>=nBlock ){
  23018. return memsys3FromMaster(nBlock);
  23019. }
  23020. }
  23021. }
  23022. /* If none of the above worked, then we fail. */
  23023. return 0;
  23024. }
  23025. /*
  23026. ** Free an outstanding memory allocation.
  23027. **
  23028. ** This function assumes that the necessary mutexes, if any, are
  23029. ** already held by the caller. Hence "Unsafe".
  23030. */
  23031. static void memsys3FreeUnsafe(void *pOld){
  23032. Mem3Block *p = (Mem3Block*)pOld;
  23033. int i;
  23034. u32 size, x;
  23035. assert( sqlite3_mutex_held(mem3.mutex) );
  23036. assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
  23037. i = p - mem3.aPool;
  23038. assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
  23039. size = mem3.aPool[i-1].u.hdr.size4x/4;
  23040. assert( i+size<=mem3.nPool+1 );
  23041. mem3.aPool[i-1].u.hdr.size4x &= ~1;
  23042. mem3.aPool[i+size-1].u.hdr.prevSize = size;
  23043. mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
  23044. memsys3Link(i);
  23045. /* Try to expand the master using the newly freed chunk */
  23046. if( mem3.iMaster ){
  23047. while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
  23048. size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
  23049. mem3.iMaster -= size;
  23050. mem3.szMaster += size;
  23051. memsys3Unlink(mem3.iMaster);
  23052. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  23053. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  23054. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
  23055. }
  23056. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  23057. while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
  23058. memsys3Unlink(mem3.iMaster+mem3.szMaster);
  23059. mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
  23060. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  23061. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
  23062. }
  23063. }
  23064. }
  23065. /*
  23066. ** Return the size of an outstanding allocation, in bytes. The
  23067. ** size returned omits the 8-byte header overhead. This only
  23068. ** works for chunks that are currently checked out.
  23069. */
  23070. static int memsys3Size(void *p){
  23071. Mem3Block *pBlock;
  23072. assert( p!=0 );
  23073. pBlock = (Mem3Block*)p;
  23074. assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
  23075. return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
  23076. }
  23077. /*
  23078. ** Round up a request size to the next valid allocation size.
  23079. */
  23080. static int memsys3Roundup(int n){
  23081. if( n<=12 ){
  23082. return 12;
  23083. }else{
  23084. return ((n+11)&~7) - 4;
  23085. }
  23086. }
  23087. /*
  23088. ** Allocate nBytes of memory.
  23089. */
  23090. static void *memsys3Malloc(int nBytes){
  23091. sqlite3_int64 *p;
  23092. assert( nBytes>0 ); /* malloc.c filters out 0 byte requests */
  23093. memsys3Enter();
  23094. p = memsys3MallocUnsafe(nBytes);
  23095. memsys3Leave();
  23096. return (void*)p;
  23097. }
  23098. /*
  23099. ** Free memory.
  23100. */
  23101. static void memsys3Free(void *pPrior){
  23102. assert( pPrior );
  23103. memsys3Enter();
  23104. memsys3FreeUnsafe(pPrior);
  23105. memsys3Leave();
  23106. }
  23107. /*
  23108. ** Change the size of an existing memory allocation
  23109. */
  23110. static void *memsys3Realloc(void *pPrior, int nBytes){
  23111. int nOld;
  23112. void *p;
  23113. if( pPrior==0 ){
  23114. return sqlite3_malloc(nBytes);
  23115. }
  23116. if( nBytes<=0 ){
  23117. sqlite3_free(pPrior);
  23118. return 0;
  23119. }
  23120. nOld = memsys3Size(pPrior);
  23121. if( nBytes<=nOld && nBytes>=nOld-128 ){
  23122. return pPrior;
  23123. }
  23124. memsys3Enter();
  23125. p = memsys3MallocUnsafe(nBytes);
  23126. if( p ){
  23127. if( nOld<nBytes ){
  23128. memcpy(p, pPrior, nOld);
  23129. }else{
  23130. memcpy(p, pPrior, nBytes);
  23131. }
  23132. memsys3FreeUnsafe(pPrior);
  23133. }
  23134. memsys3Leave();
  23135. return p;
  23136. }
  23137. /*
  23138. ** Initialize this module.
  23139. */
  23140. static int memsys3Init(void *NotUsed){
  23141. UNUSED_PARAMETER(NotUsed);
  23142. if( !sqlite3GlobalConfig.pHeap ){
  23143. return SQLITE_ERROR;
  23144. }
  23145. /* Store a pointer to the memory block in global structure mem3. */
  23146. assert( sizeof(Mem3Block)==8 );
  23147. mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
  23148. mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
  23149. /* Initialize the master block. */
  23150. mem3.szMaster = mem3.nPool;
  23151. mem3.mnMaster = mem3.szMaster;
  23152. mem3.iMaster = 1;
  23153. mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
  23154. mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
  23155. mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
  23156. return SQLITE_OK;
  23157. }
  23158. /*
  23159. ** Deinitialize this module.
  23160. */
  23161. static void memsys3Shutdown(void *NotUsed){
  23162. UNUSED_PARAMETER(NotUsed);
  23163. mem3.mutex = 0;
  23164. return;
  23165. }
  23166. /*
  23167. ** Open the file indicated and write a log of all unfreed memory
  23168. ** allocations into that log.
  23169. */
  23170. SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
  23171. #ifdef SQLITE_DEBUG
  23172. FILE *out;
  23173. u32 i, j;
  23174. u32 size;
  23175. if( zFilename==0 || zFilename[0]==0 ){
  23176. out = stdout;
  23177. }else{
  23178. out = fopen(zFilename, "w");
  23179. if( out==0 ){
  23180. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  23181. zFilename);
  23182. return;
  23183. }
  23184. }
  23185. memsys3Enter();
  23186. fprintf(out, "CHUNKS:\n");
  23187. for(i=1; i<=mem3.nPool; i+=size/4){
  23188. size = mem3.aPool[i-1].u.hdr.size4x;
  23189. if( size/4<=1 ){
  23190. fprintf(out, "%p size error\n", &mem3.aPool[i]);
  23191. assert( 0 );
  23192. break;
  23193. }
  23194. if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
  23195. fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
  23196. assert( 0 );
  23197. break;
  23198. }
  23199. if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
  23200. fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
  23201. assert( 0 );
  23202. break;
  23203. }
  23204. if( size&1 ){
  23205. fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
  23206. }else{
  23207. fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
  23208. i==mem3.iMaster ? " **master**" : "");
  23209. }
  23210. }
  23211. for(i=0; i<MX_SMALL-1; i++){
  23212. if( mem3.aiSmall[i]==0 ) continue;
  23213. fprintf(out, "small(%2d):", i);
  23214. for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
  23215. fprintf(out, " %p(%d)", &mem3.aPool[j],
  23216. (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
  23217. }
  23218. fprintf(out, "\n");
  23219. }
  23220. for(i=0; i<N_HASH; i++){
  23221. if( mem3.aiHash[i]==0 ) continue;
  23222. fprintf(out, "hash(%2d):", i);
  23223. for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
  23224. fprintf(out, " %p(%d)", &mem3.aPool[j],
  23225. (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
  23226. }
  23227. fprintf(out, "\n");
  23228. }
  23229. fprintf(out, "master=%d\n", mem3.iMaster);
  23230. fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
  23231. fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
  23232. sqlite3_mutex_leave(mem3.mutex);
  23233. if( out==stdout ){
  23234. fflush(stdout);
  23235. }else{
  23236. fclose(out);
  23237. }
  23238. #else
  23239. UNUSED_PARAMETER(zFilename);
  23240. #endif
  23241. }
  23242. /*
  23243. ** This routine is the only routine in this file with external
  23244. ** linkage.
  23245. **
  23246. ** Populate the low-level memory allocation function pointers in
  23247. ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
  23248. ** arguments specify the block of memory to manage.
  23249. **
  23250. ** This routine is only called by sqlite3_config(), and therefore
  23251. ** is not required to be threadsafe (it is not).
  23252. */
  23253. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
  23254. static const sqlite3_mem_methods mempoolMethods = {
  23255. memsys3Malloc,
  23256. memsys3Free,
  23257. memsys3Realloc,
  23258. memsys3Size,
  23259. memsys3Roundup,
  23260. memsys3Init,
  23261. memsys3Shutdown,
  23262. 0
  23263. };
  23264. return &mempoolMethods;
  23265. }
  23266. #endif /* SQLITE_ENABLE_MEMSYS3 */
  23267. /************** End of mem3.c ************************************************/
  23268. /************** Begin file mem5.c ********************************************/
  23269. /*
  23270. ** 2007 October 14
  23271. **
  23272. ** The author disclaims copyright to this source code. In place of
  23273. ** a legal notice, here is a blessing:
  23274. **
  23275. ** May you do good and not evil.
  23276. ** May you find forgiveness for yourself and forgive others.
  23277. ** May you share freely, never taking more than you give.
  23278. **
  23279. *************************************************************************
  23280. ** This file contains the C functions that implement a memory
  23281. ** allocation subsystem for use by SQLite.
  23282. **
  23283. ** This version of the memory allocation subsystem omits all
  23284. ** use of malloc(). The application gives SQLite a block of memory
  23285. ** before calling sqlite3_initialize() from which allocations
  23286. ** are made and returned by the xMalloc() and xRealloc()
  23287. ** implementations. Once sqlite3_initialize() has been called,
  23288. ** the amount of memory available to SQLite is fixed and cannot
  23289. ** be changed.
  23290. **
  23291. ** This version of the memory allocation subsystem is included
  23292. ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
  23293. **
  23294. ** This memory allocator uses the following algorithm:
  23295. **
  23296. ** 1. All memory allocation sizes are rounded up to a power of 2.
  23297. **
  23298. ** 2. If two adjacent free blocks are the halves of a larger block,
  23299. ** then the two blocks are coalesced into the single larger block.
  23300. **
  23301. ** 3. New memory is allocated from the first available free block.
  23302. **
  23303. ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
  23304. ** Concerning Dynamic Storage Allocation". Journal of the Association for
  23305. ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
  23306. **
  23307. ** Let n be the size of the largest allocation divided by the minimum
  23308. ** allocation size (after rounding all sizes up to a power of 2.) Let M
  23309. ** be the maximum amount of memory ever outstanding at one time. Let
  23310. ** N be the total amount of memory available for allocation. Robson
  23311. ** proved that this memory allocator will never breakdown due to
  23312. ** fragmentation as long as the following constraint holds:
  23313. **
  23314. ** N >= M*(1 + log2(n)/2) - n + 1
  23315. **
  23316. ** The sqlite3_status() logic tracks the maximum values of n and M so
  23317. ** that an application can, at any time, verify this constraint.
  23318. */
  23319. /* #include "sqliteInt.h" */
  23320. /*
  23321. ** This version of the memory allocator is used only when
  23322. ** SQLITE_ENABLE_MEMSYS5 is defined.
  23323. */
  23324. #ifdef SQLITE_ENABLE_MEMSYS5
  23325. /*
  23326. ** A minimum allocation is an instance of the following structure.
  23327. ** Larger allocations are an array of these structures where the
  23328. ** size of the array is a power of 2.
  23329. **
  23330. ** The size of this object must be a power of two. That fact is
  23331. ** verified in memsys5Init().
  23332. */
  23333. typedef struct Mem5Link Mem5Link;
  23334. struct Mem5Link {
  23335. int next; /* Index of next free chunk */
  23336. int prev; /* Index of previous free chunk */
  23337. };
  23338. /*
  23339. ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
  23340. ** mem5.szAtom is always at least 8 and 32-bit integers are used,
  23341. ** it is not actually possible to reach this limit.
  23342. */
  23343. #define LOGMAX 30
  23344. /*
  23345. ** Masks used for mem5.aCtrl[] elements.
  23346. */
  23347. #define CTRL_LOGSIZE 0x1f /* Log2 Size of this block */
  23348. #define CTRL_FREE 0x20 /* True if not checked out */
  23349. /*
  23350. ** All of the static variables used by this module are collected
  23351. ** into a single structure named "mem5". This is to keep the
  23352. ** static variables organized and to reduce namespace pollution
  23353. ** when this module is combined with other in the amalgamation.
  23354. */
  23355. static SQLITE_WSD struct Mem5Global {
  23356. /*
  23357. ** Memory available for allocation
  23358. */
  23359. int szAtom; /* Smallest possible allocation in bytes */
  23360. int nBlock; /* Number of szAtom sized blocks in zPool */
  23361. u8 *zPool; /* Memory available to be allocated */
  23362. /*
  23363. ** Mutex to control access to the memory allocation subsystem.
  23364. */
  23365. sqlite3_mutex *mutex;
  23366. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  23367. /*
  23368. ** Performance statistics
  23369. */
  23370. u64 nAlloc; /* Total number of calls to malloc */
  23371. u64 totalAlloc; /* Total of all malloc calls - includes internal frag */
  23372. u64 totalExcess; /* Total internal fragmentation */
  23373. u32 currentOut; /* Current checkout, including internal fragmentation */
  23374. u32 currentCount; /* Current number of distinct checkouts */
  23375. u32 maxOut; /* Maximum instantaneous currentOut */
  23376. u32 maxCount; /* Maximum instantaneous currentCount */
  23377. u32 maxRequest; /* Largest allocation (exclusive of internal frag) */
  23378. #endif
  23379. /*
  23380. ** Lists of free blocks. aiFreelist[0] is a list of free blocks of
  23381. ** size mem5.szAtom. aiFreelist[1] holds blocks of size szAtom*2.
  23382. ** aiFreelist[2] holds free blocks of size szAtom*4. And so forth.
  23383. */
  23384. int aiFreelist[LOGMAX+1];
  23385. /*
  23386. ** Space for tracking which blocks are checked out and the size
  23387. ** of each block. One byte per block.
  23388. */
  23389. u8 *aCtrl;
  23390. } mem5;
  23391. /*
  23392. ** Access the static variable through a macro for SQLITE_OMIT_WSD.
  23393. */
  23394. #define mem5 GLOBAL(struct Mem5Global, mem5)
  23395. /*
  23396. ** Assuming mem5.zPool is divided up into an array of Mem5Link
  23397. ** structures, return a pointer to the idx-th such link.
  23398. */
  23399. #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
  23400. /*
  23401. ** Unlink the chunk at mem5.aPool[i] from list it is currently
  23402. ** on. It should be found on mem5.aiFreelist[iLogsize].
  23403. */
  23404. static void memsys5Unlink(int i, int iLogsize){
  23405. int next, prev;
  23406. assert( i>=0 && i<mem5.nBlock );
  23407. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  23408. assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
  23409. next = MEM5LINK(i)->next;
  23410. prev = MEM5LINK(i)->prev;
  23411. if( prev<0 ){
  23412. mem5.aiFreelist[iLogsize] = next;
  23413. }else{
  23414. MEM5LINK(prev)->next = next;
  23415. }
  23416. if( next>=0 ){
  23417. MEM5LINK(next)->prev = prev;
  23418. }
  23419. }
  23420. /*
  23421. ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
  23422. ** free list.
  23423. */
  23424. static void memsys5Link(int i, int iLogsize){
  23425. int x;
  23426. assert( sqlite3_mutex_held(mem5.mutex) );
  23427. assert( i>=0 && i<mem5.nBlock );
  23428. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  23429. assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
  23430. x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
  23431. MEM5LINK(i)->prev = -1;
  23432. if( x>=0 ){
  23433. assert( x<mem5.nBlock );
  23434. MEM5LINK(x)->prev = i;
  23435. }
  23436. mem5.aiFreelist[iLogsize] = i;
  23437. }
  23438. /*
  23439. ** Obtain or release the mutex needed to access global data structures.
  23440. */
  23441. static void memsys5Enter(void){
  23442. sqlite3_mutex_enter(mem5.mutex);
  23443. }
  23444. static void memsys5Leave(void){
  23445. sqlite3_mutex_leave(mem5.mutex);
  23446. }
  23447. /*
  23448. ** Return the size of an outstanding allocation, in bytes.
  23449. ** This only works for chunks that are currently checked out.
  23450. */
  23451. static int memsys5Size(void *p){
  23452. int iSize, i;
  23453. assert( p!=0 );
  23454. i = (int)(((u8 *)p-mem5.zPool)/mem5.szAtom);
  23455. assert( i>=0 && i<mem5.nBlock );
  23456. iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
  23457. return iSize;
  23458. }
  23459. /*
  23460. ** Return a block of memory of at least nBytes in size.
  23461. ** Return NULL if unable. Return NULL if nBytes==0.
  23462. **
  23463. ** The caller guarantees that nByte is positive.
  23464. **
  23465. ** The caller has obtained a mutex prior to invoking this
  23466. ** routine so there is never any chance that two or more
  23467. ** threads can be in this routine at the same time.
  23468. */
  23469. static void *memsys5MallocUnsafe(int nByte){
  23470. int i; /* Index of a mem5.aPool[] slot */
  23471. int iBin; /* Index into mem5.aiFreelist[] */
  23472. int iFullSz; /* Size of allocation rounded up to power of 2 */
  23473. int iLogsize; /* Log2 of iFullSz/POW2_MIN */
  23474. /* nByte must be a positive */
  23475. assert( nByte>0 );
  23476. /* No more than 1GiB per allocation */
  23477. if( nByte > 0x40000000 ) return 0;
  23478. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  23479. /* Keep track of the maximum allocation request. Even unfulfilled
  23480. ** requests are counted */
  23481. if( (u32)nByte>mem5.maxRequest ){
  23482. mem5.maxRequest = nByte;
  23483. }
  23484. #endif
  23485. /* Round nByte up to the next valid power of two */
  23486. for(iFullSz=mem5.szAtom,iLogsize=0; iFullSz<nByte; iFullSz*=2,iLogsize++){}
  23487. /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
  23488. ** block. If not, then split a block of the next larger power of
  23489. ** two in order to create a new free block of size iLogsize.
  23490. */
  23491. for(iBin=iLogsize; iBin<=LOGMAX && mem5.aiFreelist[iBin]<0; iBin++){}
  23492. if( iBin>LOGMAX ){
  23493. testcase( sqlite3GlobalConfig.xLog!=0 );
  23494. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
  23495. return 0;
  23496. }
  23497. i = mem5.aiFreelist[iBin];
  23498. memsys5Unlink(i, iBin);
  23499. while( iBin>iLogsize ){
  23500. int newSize;
  23501. iBin--;
  23502. newSize = 1 << iBin;
  23503. mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
  23504. memsys5Link(i+newSize, iBin);
  23505. }
  23506. mem5.aCtrl[i] = iLogsize;
  23507. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  23508. /* Update allocator performance statistics. */
  23509. mem5.nAlloc++;
  23510. mem5.totalAlloc += iFullSz;
  23511. mem5.totalExcess += iFullSz - nByte;
  23512. mem5.currentCount++;
  23513. mem5.currentOut += iFullSz;
  23514. if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
  23515. if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
  23516. #endif
  23517. #ifdef SQLITE_DEBUG
  23518. /* Make sure the allocated memory does not assume that it is set to zero
  23519. ** or retains a value from a previous allocation */
  23520. memset(&mem5.zPool[i*mem5.szAtom], 0xAA, iFullSz);
  23521. #endif
  23522. /* Return a pointer to the allocated memory. */
  23523. return (void*)&mem5.zPool[i*mem5.szAtom];
  23524. }
  23525. /*
  23526. ** Free an outstanding memory allocation.
  23527. */
  23528. static void memsys5FreeUnsafe(void *pOld){
  23529. u32 size, iLogsize;
  23530. int iBlock;
  23531. /* Set iBlock to the index of the block pointed to by pOld in
  23532. ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
  23533. */
  23534. iBlock = (int)(((u8 *)pOld-mem5.zPool)/mem5.szAtom);
  23535. /* Check that the pointer pOld points to a valid, non-free block. */
  23536. assert( iBlock>=0 && iBlock<mem5.nBlock );
  23537. assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
  23538. assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
  23539. iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
  23540. size = 1<<iLogsize;
  23541. assert( iBlock+size-1<(u32)mem5.nBlock );
  23542. mem5.aCtrl[iBlock] |= CTRL_FREE;
  23543. mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
  23544. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  23545. assert( mem5.currentCount>0 );
  23546. assert( mem5.currentOut>=(size*mem5.szAtom) );
  23547. mem5.currentCount--;
  23548. mem5.currentOut -= size*mem5.szAtom;
  23549. assert( mem5.currentOut>0 || mem5.currentCount==0 );
  23550. assert( mem5.currentCount>0 || mem5.currentOut==0 );
  23551. #endif
  23552. mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
  23553. while( ALWAYS(iLogsize<LOGMAX) ){
  23554. int iBuddy;
  23555. if( (iBlock>>iLogsize) & 1 ){
  23556. iBuddy = iBlock - size;
  23557. assert( iBuddy>=0 );
  23558. }else{
  23559. iBuddy = iBlock + size;
  23560. if( iBuddy>=mem5.nBlock ) break;
  23561. }
  23562. if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
  23563. memsys5Unlink(iBuddy, iLogsize);
  23564. iLogsize++;
  23565. if( iBuddy<iBlock ){
  23566. mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
  23567. mem5.aCtrl[iBlock] = 0;
  23568. iBlock = iBuddy;
  23569. }else{
  23570. mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
  23571. mem5.aCtrl[iBuddy] = 0;
  23572. }
  23573. size *= 2;
  23574. }
  23575. #ifdef SQLITE_DEBUG
  23576. /* Overwrite freed memory with the 0x55 bit pattern to verify that it is
  23577. ** not used after being freed */
  23578. memset(&mem5.zPool[iBlock*mem5.szAtom], 0x55, size);
  23579. #endif
  23580. memsys5Link(iBlock, iLogsize);
  23581. }
  23582. /*
  23583. ** Allocate nBytes of memory.
  23584. */
  23585. static void *memsys5Malloc(int nBytes){
  23586. sqlite3_int64 *p = 0;
  23587. if( nBytes>0 ){
  23588. memsys5Enter();
  23589. p = memsys5MallocUnsafe(nBytes);
  23590. memsys5Leave();
  23591. }
  23592. return (void*)p;
  23593. }
  23594. /*
  23595. ** Free memory.
  23596. **
  23597. ** The outer layer memory allocator prevents this routine from
  23598. ** being called with pPrior==0.
  23599. */
  23600. static void memsys5Free(void *pPrior){
  23601. assert( pPrior!=0 );
  23602. memsys5Enter();
  23603. memsys5FreeUnsafe(pPrior);
  23604. memsys5Leave();
  23605. }
  23606. /*
  23607. ** Change the size of an existing memory allocation.
  23608. **
  23609. ** The outer layer memory allocator prevents this routine from
  23610. ** being called with pPrior==0.
  23611. **
  23612. ** nBytes is always a value obtained from a prior call to
  23613. ** memsys5Round(). Hence nBytes is always a non-negative power
  23614. ** of two. If nBytes==0 that means that an oversize allocation
  23615. ** (an allocation larger than 0x40000000) was requested and this
  23616. ** routine should return 0 without freeing pPrior.
  23617. */
  23618. static void *memsys5Realloc(void *pPrior, int nBytes){
  23619. int nOld;
  23620. void *p;
  23621. assert( pPrior!=0 );
  23622. assert( (nBytes&(nBytes-1))==0 ); /* EV: R-46199-30249 */
  23623. assert( nBytes>=0 );
  23624. if( nBytes==0 ){
  23625. return 0;
  23626. }
  23627. nOld = memsys5Size(pPrior);
  23628. if( nBytes<=nOld ){
  23629. return pPrior;
  23630. }
  23631. p = memsys5Malloc(nBytes);
  23632. if( p ){
  23633. memcpy(p, pPrior, nOld);
  23634. memsys5Free(pPrior);
  23635. }
  23636. return p;
  23637. }
  23638. /*
  23639. ** Round up a request size to the next valid allocation size. If
  23640. ** the allocation is too large to be handled by this allocation system,
  23641. ** return 0.
  23642. **
  23643. ** All allocations must be a power of two and must be expressed by a
  23644. ** 32-bit signed integer. Hence the largest allocation is 0x40000000
  23645. ** or 1073741824 bytes.
  23646. */
  23647. static int memsys5Roundup(int n){
  23648. int iFullSz;
  23649. if( n > 0x40000000 ) return 0;
  23650. for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
  23651. return iFullSz;
  23652. }
  23653. /*
  23654. ** Return the ceiling of the logarithm base 2 of iValue.
  23655. **
  23656. ** Examples: memsys5Log(1) -> 0
  23657. ** memsys5Log(2) -> 1
  23658. ** memsys5Log(4) -> 2
  23659. ** memsys5Log(5) -> 3
  23660. ** memsys5Log(8) -> 3
  23661. ** memsys5Log(9) -> 4
  23662. */
  23663. static int memsys5Log(int iValue){
  23664. int iLog;
  23665. for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
  23666. return iLog;
  23667. }
  23668. /*
  23669. ** Initialize the memory allocator.
  23670. **
  23671. ** This routine is not threadsafe. The caller must be holding a mutex
  23672. ** to prevent multiple threads from entering at the same time.
  23673. */
  23674. static int memsys5Init(void *NotUsed){
  23675. int ii; /* Loop counter */
  23676. int nByte; /* Number of bytes of memory available to this allocator */
  23677. u8 *zByte; /* Memory usable by this allocator */
  23678. int nMinLog; /* Log base 2 of minimum allocation size in bytes */
  23679. int iOffset; /* An offset into mem5.aCtrl[] */
  23680. UNUSED_PARAMETER(NotUsed);
  23681. /* For the purposes of this routine, disable the mutex */
  23682. mem5.mutex = 0;
  23683. /* The size of a Mem5Link object must be a power of two. Verify that
  23684. ** this is case.
  23685. */
  23686. assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
  23687. nByte = sqlite3GlobalConfig.nHeap;
  23688. zByte = (u8*)sqlite3GlobalConfig.pHeap;
  23689. assert( zByte!=0 ); /* sqlite3_config() does not allow otherwise */
  23690. /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
  23691. nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
  23692. mem5.szAtom = (1<<nMinLog);
  23693. while( (int)sizeof(Mem5Link)>mem5.szAtom ){
  23694. mem5.szAtom = mem5.szAtom << 1;
  23695. }
  23696. mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
  23697. mem5.zPool = zByte;
  23698. mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
  23699. for(ii=0; ii<=LOGMAX; ii++){
  23700. mem5.aiFreelist[ii] = -1;
  23701. }
  23702. iOffset = 0;
  23703. for(ii=LOGMAX; ii>=0; ii--){
  23704. int nAlloc = (1<<ii);
  23705. if( (iOffset+nAlloc)<=mem5.nBlock ){
  23706. mem5.aCtrl[iOffset] = ii | CTRL_FREE;
  23707. memsys5Link(iOffset, ii);
  23708. iOffset += nAlloc;
  23709. }
  23710. assert((iOffset+nAlloc)>mem5.nBlock);
  23711. }
  23712. /* If a mutex is required for normal operation, allocate one */
  23713. if( sqlite3GlobalConfig.bMemstat==0 ){
  23714. mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  23715. }
  23716. return SQLITE_OK;
  23717. }
  23718. /*
  23719. ** Deinitialize this module.
  23720. */
  23721. static void memsys5Shutdown(void *NotUsed){
  23722. UNUSED_PARAMETER(NotUsed);
  23723. mem5.mutex = 0;
  23724. return;
  23725. }
  23726. #ifdef SQLITE_TEST
  23727. /*
  23728. ** Open the file indicated and write a log of all unfreed memory
  23729. ** allocations into that log.
  23730. */
  23731. SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
  23732. FILE *out;
  23733. int i, j, n;
  23734. int nMinLog;
  23735. if( zFilename==0 || zFilename[0]==0 ){
  23736. out = stdout;
  23737. }else{
  23738. out = fopen(zFilename, "w");
  23739. if( out==0 ){
  23740. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  23741. zFilename);
  23742. return;
  23743. }
  23744. }
  23745. memsys5Enter();
  23746. nMinLog = memsys5Log(mem5.szAtom);
  23747. for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
  23748. for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
  23749. fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
  23750. }
  23751. fprintf(out, "mem5.nAlloc = %llu\n", mem5.nAlloc);
  23752. fprintf(out, "mem5.totalAlloc = %llu\n", mem5.totalAlloc);
  23753. fprintf(out, "mem5.totalExcess = %llu\n", mem5.totalExcess);
  23754. fprintf(out, "mem5.currentOut = %u\n", mem5.currentOut);
  23755. fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
  23756. fprintf(out, "mem5.maxOut = %u\n", mem5.maxOut);
  23757. fprintf(out, "mem5.maxCount = %u\n", mem5.maxCount);
  23758. fprintf(out, "mem5.maxRequest = %u\n", mem5.maxRequest);
  23759. memsys5Leave();
  23760. if( out==stdout ){
  23761. fflush(stdout);
  23762. }else{
  23763. fclose(out);
  23764. }
  23765. }
  23766. #endif
  23767. /*
  23768. ** This routine is the only routine in this file with external
  23769. ** linkage. It returns a pointer to a static sqlite3_mem_methods
  23770. ** struct populated with the memsys5 methods.
  23771. */
  23772. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
  23773. static const sqlite3_mem_methods memsys5Methods = {
  23774. memsys5Malloc,
  23775. memsys5Free,
  23776. memsys5Realloc,
  23777. memsys5Size,
  23778. memsys5Roundup,
  23779. memsys5Init,
  23780. memsys5Shutdown,
  23781. 0
  23782. };
  23783. return &memsys5Methods;
  23784. }
  23785. #endif /* SQLITE_ENABLE_MEMSYS5 */
  23786. /************** End of mem5.c ************************************************/
  23787. /************** Begin file mutex.c *******************************************/
  23788. /*
  23789. ** 2007 August 14
  23790. **
  23791. ** The author disclaims copyright to this source code. In place of
  23792. ** a legal notice, here is a blessing:
  23793. **
  23794. ** May you do good and not evil.
  23795. ** May you find forgiveness for yourself and forgive others.
  23796. ** May you share freely, never taking more than you give.
  23797. **
  23798. *************************************************************************
  23799. ** This file contains the C functions that implement mutexes.
  23800. **
  23801. ** This file contains code that is common across all mutex implementations.
  23802. */
  23803. /* #include "sqliteInt.h" */
  23804. #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
  23805. /*
  23806. ** For debugging purposes, record when the mutex subsystem is initialized
  23807. ** and uninitialized so that we can assert() if there is an attempt to
  23808. ** allocate a mutex while the system is uninitialized.
  23809. */
  23810. static SQLITE_WSD int mutexIsInit = 0;
  23811. #endif /* SQLITE_DEBUG && !defined(SQLITE_MUTEX_OMIT) */
  23812. #ifndef SQLITE_MUTEX_OMIT
  23813. #ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS
  23814. /*
  23815. ** This block (enclosed by SQLITE_ENABLE_MULTITHREADED_CHECKS) contains
  23816. ** the implementation of a wrapper around the system default mutex
  23817. ** implementation (sqlite3DefaultMutex()).
  23818. **
  23819. ** Most calls are passed directly through to the underlying default
  23820. ** mutex implementation. Except, if a mutex is configured by calling
  23821. ** sqlite3MutexWarnOnContention() on it, then if contention is ever
  23822. ** encountered within xMutexEnter() a warning is emitted via sqlite3_log().
  23823. **
  23824. ** This type of mutex is used as the database handle mutex when testing
  23825. ** apps that usually use SQLITE_CONFIG_MULTITHREAD mode.
  23826. */
  23827. /*
  23828. ** Type for all mutexes used when SQLITE_ENABLE_MULTITHREADED_CHECKS
  23829. ** is defined. Variable CheckMutex.mutex is a pointer to the real mutex
  23830. ** allocated by the system mutex implementation. Variable iType is usually set
  23831. ** to the type of mutex requested - SQLITE_MUTEX_RECURSIVE, SQLITE_MUTEX_FAST
  23832. ** or one of the static mutex identifiers. Or, if this is a recursive mutex
  23833. ** that has been configured using sqlite3MutexWarnOnContention(), it is
  23834. ** set to SQLITE_MUTEX_WARNONCONTENTION.
  23835. */
  23836. typedef struct CheckMutex CheckMutex;
  23837. struct CheckMutex {
  23838. int iType;
  23839. sqlite3_mutex *mutex;
  23840. };
  23841. #define SQLITE_MUTEX_WARNONCONTENTION (-1)
  23842. /*
  23843. ** Pointer to real mutex methods object used by the CheckMutex
  23844. ** implementation. Set by checkMutexInit().
  23845. */
  23846. static SQLITE_WSD const sqlite3_mutex_methods *pGlobalMutexMethods;
  23847. #ifdef SQLITE_DEBUG
  23848. static int checkMutexHeld(sqlite3_mutex *p){
  23849. return pGlobalMutexMethods->xMutexHeld(((CheckMutex*)p)->mutex);
  23850. }
  23851. static int checkMutexNotheld(sqlite3_mutex *p){
  23852. return pGlobalMutexMethods->xMutexNotheld(((CheckMutex*)p)->mutex);
  23853. }
  23854. #endif
  23855. /*
  23856. ** Initialize and deinitialize the mutex subsystem.
  23857. */
  23858. static int checkMutexInit(void){
  23859. pGlobalMutexMethods = sqlite3DefaultMutex();
  23860. return SQLITE_OK;
  23861. }
  23862. static int checkMutexEnd(void){
  23863. pGlobalMutexMethods = 0;
  23864. return SQLITE_OK;
  23865. }
  23866. /*
  23867. ** Allocate a mutex.
  23868. */
  23869. static sqlite3_mutex *checkMutexAlloc(int iType){
  23870. static CheckMutex staticMutexes[] = {
  23871. {2, 0}, {3, 0}, {4, 0}, {5, 0},
  23872. {6, 0}, {7, 0}, {8, 0}, {9, 0},
  23873. {10, 0}, {11, 0}, {12, 0}, {13, 0}
  23874. };
  23875. CheckMutex *p = 0;
  23876. assert( SQLITE_MUTEX_RECURSIVE==1 && SQLITE_MUTEX_FAST==0 );
  23877. if( iType<2 ){
  23878. p = sqlite3MallocZero(sizeof(CheckMutex));
  23879. if( p==0 ) return 0;
  23880. p->iType = iType;
  23881. }else{
  23882. #ifdef SQLITE_ENABLE_API_ARMOR
  23883. if( iType-2>=ArraySize(staticMutexes) ){
  23884. (void)SQLITE_MISUSE_BKPT;
  23885. return 0;
  23886. }
  23887. #endif
  23888. p = &staticMutexes[iType-2];
  23889. }
  23890. if( p->mutex==0 ){
  23891. p->mutex = pGlobalMutexMethods->xMutexAlloc(iType);
  23892. if( p->mutex==0 ){
  23893. if( iType<2 ){
  23894. sqlite3_free(p);
  23895. }
  23896. p = 0;
  23897. }
  23898. }
  23899. return (sqlite3_mutex*)p;
  23900. }
  23901. /*
  23902. ** Free a mutex.
  23903. */
  23904. static void checkMutexFree(sqlite3_mutex *p){
  23905. assert( SQLITE_MUTEX_RECURSIVE<2 );
  23906. assert( SQLITE_MUTEX_FAST<2 );
  23907. assert( SQLITE_MUTEX_WARNONCONTENTION<2 );
  23908. #if SQLITE_ENABLE_API_ARMOR
  23909. if( ((CheckMutex*)p)->iType<2 )
  23910. #endif
  23911. {
  23912. CheckMutex *pCheck = (CheckMutex*)p;
  23913. pGlobalMutexMethods->xMutexFree(pCheck->mutex);
  23914. sqlite3_free(pCheck);
  23915. }
  23916. #ifdef SQLITE_ENABLE_API_ARMOR
  23917. else{
  23918. (void)SQLITE_MISUSE_BKPT;
  23919. }
  23920. #endif
  23921. }
  23922. /*
  23923. ** Enter the mutex.
  23924. */
  23925. static void checkMutexEnter(sqlite3_mutex *p){
  23926. CheckMutex *pCheck = (CheckMutex*)p;
  23927. if( pCheck->iType==SQLITE_MUTEX_WARNONCONTENTION ){
  23928. if( SQLITE_OK==pGlobalMutexMethods->xMutexTry(pCheck->mutex) ){
  23929. return;
  23930. }
  23931. sqlite3_log(SQLITE_MISUSE,
  23932. "illegal multi-threaded access to database connection"
  23933. );
  23934. }
  23935. pGlobalMutexMethods->xMutexEnter(pCheck->mutex);
  23936. }
  23937. /*
  23938. ** Enter the mutex (do not block).
  23939. */
  23940. static int checkMutexTry(sqlite3_mutex *p){
  23941. CheckMutex *pCheck = (CheckMutex*)p;
  23942. return pGlobalMutexMethods->xMutexTry(pCheck->mutex);
  23943. }
  23944. /*
  23945. ** Leave the mutex.
  23946. */
  23947. static void checkMutexLeave(sqlite3_mutex *p){
  23948. CheckMutex *pCheck = (CheckMutex*)p;
  23949. pGlobalMutexMethods->xMutexLeave(pCheck->mutex);
  23950. }
  23951. sqlite3_mutex_methods const *multiThreadedCheckMutex(void){
  23952. static const sqlite3_mutex_methods sMutex = {
  23953. checkMutexInit,
  23954. checkMutexEnd,
  23955. checkMutexAlloc,
  23956. checkMutexFree,
  23957. checkMutexEnter,
  23958. checkMutexTry,
  23959. checkMutexLeave,
  23960. #ifdef SQLITE_DEBUG
  23961. checkMutexHeld,
  23962. checkMutexNotheld
  23963. #else
  23964. 0,
  23965. 0
  23966. #endif
  23967. };
  23968. return &sMutex;
  23969. }
  23970. /*
  23971. ** Mark the SQLITE_MUTEX_RECURSIVE mutex passed as the only argument as
  23972. ** one on which there should be no contention.
  23973. */
  23974. SQLITE_PRIVATE void sqlite3MutexWarnOnContention(sqlite3_mutex *p){
  23975. if( sqlite3GlobalConfig.mutex.xMutexAlloc==checkMutexAlloc ){
  23976. CheckMutex *pCheck = (CheckMutex*)p;
  23977. assert( pCheck->iType==SQLITE_MUTEX_RECURSIVE );
  23978. pCheck->iType = SQLITE_MUTEX_WARNONCONTENTION;
  23979. }
  23980. }
  23981. #endif /* ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS */
  23982. /*
  23983. ** Initialize the mutex system.
  23984. */
  23985. SQLITE_PRIVATE int sqlite3MutexInit(void){
  23986. int rc = SQLITE_OK;
  23987. if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
  23988. /* If the xMutexAlloc method has not been set, then the user did not
  23989. ** install a mutex implementation via sqlite3_config() prior to
  23990. ** sqlite3_initialize() being called. This block copies pointers to
  23991. ** the default implementation into the sqlite3GlobalConfig structure.
  23992. */
  23993. sqlite3_mutex_methods const *pFrom;
  23994. sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
  23995. if( sqlite3GlobalConfig.bCoreMutex ){
  23996. #ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS
  23997. pFrom = multiThreadedCheckMutex();
  23998. #else
  23999. pFrom = sqlite3DefaultMutex();
  24000. #endif
  24001. }else{
  24002. pFrom = sqlite3NoopMutex();
  24003. }
  24004. pTo->xMutexInit = pFrom->xMutexInit;
  24005. pTo->xMutexEnd = pFrom->xMutexEnd;
  24006. pTo->xMutexFree = pFrom->xMutexFree;
  24007. pTo->xMutexEnter = pFrom->xMutexEnter;
  24008. pTo->xMutexTry = pFrom->xMutexTry;
  24009. pTo->xMutexLeave = pFrom->xMutexLeave;
  24010. pTo->xMutexHeld = pFrom->xMutexHeld;
  24011. pTo->xMutexNotheld = pFrom->xMutexNotheld;
  24012. sqlite3MemoryBarrier();
  24013. pTo->xMutexAlloc = pFrom->xMutexAlloc;
  24014. }
  24015. assert( sqlite3GlobalConfig.mutex.xMutexInit );
  24016. rc = sqlite3GlobalConfig.mutex.xMutexInit();
  24017. #ifdef SQLITE_DEBUG
  24018. GLOBAL(int, mutexIsInit) = 1;
  24019. #endif
  24020. return rc;
  24021. }
  24022. /*
  24023. ** Shutdown the mutex system. This call frees resources allocated by
  24024. ** sqlite3MutexInit().
  24025. */
  24026. SQLITE_PRIVATE int sqlite3MutexEnd(void){
  24027. int rc = SQLITE_OK;
  24028. if( sqlite3GlobalConfig.mutex.xMutexEnd ){
  24029. rc = sqlite3GlobalConfig.mutex.xMutexEnd();
  24030. }
  24031. #ifdef SQLITE_DEBUG
  24032. GLOBAL(int, mutexIsInit) = 0;
  24033. #endif
  24034. return rc;
  24035. }
  24036. /*
  24037. ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
  24038. */
  24039. SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
  24040. #ifndef SQLITE_OMIT_AUTOINIT
  24041. if( id<=SQLITE_MUTEX_RECURSIVE && sqlite3_initialize() ) return 0;
  24042. if( id>SQLITE_MUTEX_RECURSIVE && sqlite3MutexInit() ) return 0;
  24043. #endif
  24044. assert( sqlite3GlobalConfig.mutex.xMutexAlloc );
  24045. return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
  24046. }
  24047. SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
  24048. if( !sqlite3GlobalConfig.bCoreMutex ){
  24049. return 0;
  24050. }
  24051. assert( GLOBAL(int, mutexIsInit) );
  24052. assert( sqlite3GlobalConfig.mutex.xMutexAlloc );
  24053. return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
  24054. }
  24055. /*
  24056. ** Free a dynamic mutex.
  24057. */
  24058. SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
  24059. if( p ){
  24060. assert( sqlite3GlobalConfig.mutex.xMutexFree );
  24061. sqlite3GlobalConfig.mutex.xMutexFree(p);
  24062. }
  24063. }
  24064. /*
  24065. ** Obtain the mutex p. If some other thread already has the mutex, block
  24066. ** until it can be obtained.
  24067. */
  24068. SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
  24069. if( p ){
  24070. assert( sqlite3GlobalConfig.mutex.xMutexEnter );
  24071. sqlite3GlobalConfig.mutex.xMutexEnter(p);
  24072. }
  24073. }
  24074. /*
  24075. ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
  24076. ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
  24077. */
  24078. SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
  24079. int rc = SQLITE_OK;
  24080. if( p ){
  24081. assert( sqlite3GlobalConfig.mutex.xMutexTry );
  24082. return sqlite3GlobalConfig.mutex.xMutexTry(p);
  24083. }
  24084. return rc;
  24085. }
  24086. /*
  24087. ** The sqlite3_mutex_leave() routine exits a mutex that was previously
  24088. ** entered by the same thread. The behavior is undefined if the mutex
  24089. ** is not currently entered. If a NULL pointer is passed as an argument
  24090. ** this function is a no-op.
  24091. */
  24092. SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
  24093. if( p ){
  24094. assert( sqlite3GlobalConfig.mutex.xMutexLeave );
  24095. sqlite3GlobalConfig.mutex.xMutexLeave(p);
  24096. }
  24097. }
  24098. #ifndef NDEBUG
  24099. /*
  24100. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  24101. ** intended for use inside assert() statements.
  24102. */
  24103. SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
  24104. assert( p==0 || sqlite3GlobalConfig.mutex.xMutexHeld );
  24105. return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
  24106. }
  24107. SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
  24108. assert( p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld );
  24109. return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
  24110. }
  24111. #endif
  24112. #endif /* !defined(SQLITE_MUTEX_OMIT) */
  24113. /************** End of mutex.c ***********************************************/
  24114. /************** Begin file mutex_noop.c **************************************/
  24115. /*
  24116. ** 2008 October 07
  24117. **
  24118. ** The author disclaims copyright to this source code. In place of
  24119. ** a legal notice, here is a blessing:
  24120. **
  24121. ** May you do good and not evil.
  24122. ** May you find forgiveness for yourself and forgive others.
  24123. ** May you share freely, never taking more than you give.
  24124. **
  24125. *************************************************************************
  24126. ** This file contains the C functions that implement mutexes.
  24127. **
  24128. ** This implementation in this file does not provide any mutual
  24129. ** exclusion and is thus suitable for use only in applications
  24130. ** that use SQLite in a single thread. The routines defined
  24131. ** here are place-holders. Applications can substitute working
  24132. ** mutex routines at start-time using the
  24133. **
  24134. ** sqlite3_config(SQLITE_CONFIG_MUTEX,...)
  24135. **
  24136. ** interface.
  24137. **
  24138. ** If compiled with SQLITE_DEBUG, then additional logic is inserted
  24139. ** that does error checking on mutexes to make sure they are being
  24140. ** called correctly.
  24141. */
  24142. /* #include "sqliteInt.h" */
  24143. #ifndef SQLITE_MUTEX_OMIT
  24144. #ifndef SQLITE_DEBUG
  24145. /*
  24146. ** Stub routines for all mutex methods.
  24147. **
  24148. ** This routines provide no mutual exclusion or error checking.
  24149. */
  24150. static int noopMutexInit(void){ return SQLITE_OK; }
  24151. static int noopMutexEnd(void){ return SQLITE_OK; }
  24152. static sqlite3_mutex *noopMutexAlloc(int id){
  24153. UNUSED_PARAMETER(id);
  24154. return (sqlite3_mutex*)8;
  24155. }
  24156. static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  24157. static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  24158. static int noopMutexTry(sqlite3_mutex *p){
  24159. UNUSED_PARAMETER(p);
  24160. return SQLITE_OK;
  24161. }
  24162. static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  24163. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
  24164. static const sqlite3_mutex_methods sMutex = {
  24165. noopMutexInit,
  24166. noopMutexEnd,
  24167. noopMutexAlloc,
  24168. noopMutexFree,
  24169. noopMutexEnter,
  24170. noopMutexTry,
  24171. noopMutexLeave,
  24172. 0,
  24173. 0,
  24174. };
  24175. return &sMutex;
  24176. }
  24177. #endif /* !SQLITE_DEBUG */
  24178. #ifdef SQLITE_DEBUG
  24179. /*
  24180. ** In this implementation, error checking is provided for testing
  24181. ** and debugging purposes. The mutexes still do not provide any
  24182. ** mutual exclusion.
  24183. */
  24184. /*
  24185. ** The mutex object
  24186. */
  24187. typedef struct sqlite3_debug_mutex {
  24188. int id; /* The mutex type */
  24189. int cnt; /* Number of entries without a matching leave */
  24190. } sqlite3_debug_mutex;
  24191. /*
  24192. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  24193. ** intended for use inside assert() statements.
  24194. */
  24195. static int debugMutexHeld(sqlite3_mutex *pX){
  24196. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  24197. return p==0 || p->cnt>0;
  24198. }
  24199. static int debugMutexNotheld(sqlite3_mutex *pX){
  24200. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  24201. return p==0 || p->cnt==0;
  24202. }
  24203. /*
  24204. ** Initialize and deinitialize the mutex subsystem.
  24205. */
  24206. static int debugMutexInit(void){ return SQLITE_OK; }
  24207. static int debugMutexEnd(void){ return SQLITE_OK; }
  24208. /*
  24209. ** The sqlite3_mutex_alloc() routine allocates a new
  24210. ** mutex and returns a pointer to it. If it returns NULL
  24211. ** that means that a mutex could not be allocated.
  24212. */
  24213. static sqlite3_mutex *debugMutexAlloc(int id){
  24214. static sqlite3_debug_mutex aStatic[SQLITE_MUTEX_STATIC_VFS3 - 1];
  24215. sqlite3_debug_mutex *pNew = 0;
  24216. switch( id ){
  24217. case SQLITE_MUTEX_FAST:
  24218. case SQLITE_MUTEX_RECURSIVE: {
  24219. pNew = sqlite3Malloc(sizeof(*pNew));
  24220. if( pNew ){
  24221. pNew->id = id;
  24222. pNew->cnt = 0;
  24223. }
  24224. break;
  24225. }
  24226. default: {
  24227. #ifdef SQLITE_ENABLE_API_ARMOR
  24228. if( id-2<0 || id-2>=ArraySize(aStatic) ){
  24229. (void)SQLITE_MISUSE_BKPT;
  24230. return 0;
  24231. }
  24232. #endif
  24233. pNew = &aStatic[id-2];
  24234. pNew->id = id;
  24235. break;
  24236. }
  24237. }
  24238. return (sqlite3_mutex*)pNew;
  24239. }
  24240. /*
  24241. ** This routine deallocates a previously allocated mutex.
  24242. */
  24243. static void debugMutexFree(sqlite3_mutex *pX){
  24244. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  24245. assert( p->cnt==0 );
  24246. if( p->id==SQLITE_MUTEX_RECURSIVE || p->id==SQLITE_MUTEX_FAST ){
  24247. sqlite3_free(p);
  24248. }else{
  24249. #ifdef SQLITE_ENABLE_API_ARMOR
  24250. (void)SQLITE_MISUSE_BKPT;
  24251. #endif
  24252. }
  24253. }
  24254. /*
  24255. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  24256. ** to enter a mutex. If another thread is already within the mutex,
  24257. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  24258. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  24259. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  24260. ** be entered multiple times by the same thread. In such cases the,
  24261. ** mutex must be exited an equal number of times before another thread
  24262. ** can enter. If the same thread tries to enter any other kind of mutex
  24263. ** more than once, the behavior is undefined.
  24264. */
  24265. static void debugMutexEnter(sqlite3_mutex *pX){
  24266. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  24267. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  24268. p->cnt++;
  24269. }
  24270. static int debugMutexTry(sqlite3_mutex *pX){
  24271. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  24272. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  24273. p->cnt++;
  24274. return SQLITE_OK;
  24275. }
  24276. /*
  24277. ** The sqlite3_mutex_leave() routine exits a mutex that was
  24278. ** previously entered by the same thread. The behavior
  24279. ** is undefined if the mutex is not currently entered or
  24280. ** is not currently allocated. SQLite will never do either.
  24281. */
  24282. static void debugMutexLeave(sqlite3_mutex *pX){
  24283. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  24284. assert( debugMutexHeld(pX) );
  24285. p->cnt--;
  24286. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  24287. }
  24288. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
  24289. static const sqlite3_mutex_methods sMutex = {
  24290. debugMutexInit,
  24291. debugMutexEnd,
  24292. debugMutexAlloc,
  24293. debugMutexFree,
  24294. debugMutexEnter,
  24295. debugMutexTry,
  24296. debugMutexLeave,
  24297. debugMutexHeld,
  24298. debugMutexNotheld
  24299. };
  24300. return &sMutex;
  24301. }
  24302. #endif /* SQLITE_DEBUG */
  24303. /*
  24304. ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
  24305. ** is used regardless of the run-time threadsafety setting.
  24306. */
  24307. #ifdef SQLITE_MUTEX_NOOP
  24308. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  24309. return sqlite3NoopMutex();
  24310. }
  24311. #endif /* defined(SQLITE_MUTEX_NOOP) */
  24312. #endif /* !defined(SQLITE_MUTEX_OMIT) */
  24313. /************** End of mutex_noop.c ******************************************/
  24314. /************** Begin file mutex_unix.c **************************************/
  24315. /*
  24316. ** 2007 August 28
  24317. **
  24318. ** The author disclaims copyright to this source code. In place of
  24319. ** a legal notice, here is a blessing:
  24320. **
  24321. ** May you do good and not evil.
  24322. ** May you find forgiveness for yourself and forgive others.
  24323. ** May you share freely, never taking more than you give.
  24324. **
  24325. *************************************************************************
  24326. ** This file contains the C functions that implement mutexes for pthreads
  24327. */
  24328. /* #include "sqliteInt.h" */
  24329. /*
  24330. ** The code in this file is only used if we are compiling threadsafe
  24331. ** under unix with pthreads.
  24332. **
  24333. ** Note that this implementation requires a version of pthreads that
  24334. ** supports recursive mutexes.
  24335. */
  24336. #ifdef SQLITE_MUTEX_PTHREADS
  24337. #include <pthread.h>
  24338. /*
  24339. ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
  24340. ** are necessary under two condidtions: (1) Debug builds and (2) using
  24341. ** home-grown mutexes. Encapsulate these conditions into a single #define.
  24342. */
  24343. #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
  24344. # define SQLITE_MUTEX_NREF 1
  24345. #else
  24346. # define SQLITE_MUTEX_NREF 0
  24347. #endif
  24348. /*
  24349. ** Each recursive mutex is an instance of the following structure.
  24350. */
  24351. struct sqlite3_mutex {
  24352. pthread_mutex_t mutex; /* Mutex controlling the lock */
  24353. #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
  24354. int id; /* Mutex type */
  24355. #endif
  24356. #if SQLITE_MUTEX_NREF
  24357. volatile int nRef; /* Number of entrances */
  24358. volatile pthread_t owner; /* Thread that is within this mutex */
  24359. int trace; /* True to trace changes */
  24360. #endif
  24361. };
  24362. #if SQLITE_MUTEX_NREF
  24363. # define SQLITE3_MUTEX_INITIALIZER(id) \
  24364. {PTHREAD_MUTEX_INITIALIZER,id,0,(pthread_t)0,0}
  24365. #elif defined(SQLITE_ENABLE_API_ARMOR)
  24366. # define SQLITE3_MUTEX_INITIALIZER(id) { PTHREAD_MUTEX_INITIALIZER, id }
  24367. #else
  24368. #define SQLITE3_MUTEX_INITIALIZER(id) { PTHREAD_MUTEX_INITIALIZER }
  24369. #endif
  24370. /*
  24371. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  24372. ** intended for use only inside assert() statements. On some platforms,
  24373. ** there might be race conditions that can cause these routines to
  24374. ** deliver incorrect results. In particular, if pthread_equal() is
  24375. ** not an atomic operation, then these routines might delivery
  24376. ** incorrect results. On most platforms, pthread_equal() is a
  24377. ** comparison of two integers and is therefore atomic. But we are
  24378. ** told that HPUX is not such a platform. If so, then these routines
  24379. ** will not always work correctly on HPUX.
  24380. **
  24381. ** On those platforms where pthread_equal() is not atomic, SQLite
  24382. ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
  24383. ** make sure no assert() statements are evaluated and hence these
  24384. ** routines are never called.
  24385. */
  24386. #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
  24387. static int pthreadMutexHeld(sqlite3_mutex *p){
  24388. return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
  24389. }
  24390. static int pthreadMutexNotheld(sqlite3_mutex *p){
  24391. return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
  24392. }
  24393. #endif
  24394. /*
  24395. ** Try to provide a memory barrier operation, needed for initialization
  24396. ** and also for the implementation of xShmBarrier in the VFS in cases
  24397. ** where SQLite is compiled without mutexes.
  24398. */
  24399. SQLITE_PRIVATE void sqlite3MemoryBarrier(void){
  24400. #if defined(SQLITE_MEMORY_BARRIER)
  24401. SQLITE_MEMORY_BARRIER;
  24402. #elif defined(__GNUC__) && GCC_VERSION>=4001000
  24403. __sync_synchronize();
  24404. #endif
  24405. }
  24406. /*
  24407. ** Initialize and deinitialize the mutex subsystem.
  24408. */
  24409. static int pthreadMutexInit(void){ return SQLITE_OK; }
  24410. static int pthreadMutexEnd(void){ return SQLITE_OK; }
  24411. /*
  24412. ** The sqlite3_mutex_alloc() routine allocates a new
  24413. ** mutex and returns a pointer to it. If it returns NULL
  24414. ** that means that a mutex could not be allocated. SQLite
  24415. ** will unwind its stack and return an error. The argument
  24416. ** to sqlite3_mutex_alloc() is one of these integer constants:
  24417. **
  24418. ** <ul>
  24419. ** <li> SQLITE_MUTEX_FAST
  24420. ** <li> SQLITE_MUTEX_RECURSIVE
  24421. ** <li> SQLITE_MUTEX_STATIC_MASTER
  24422. ** <li> SQLITE_MUTEX_STATIC_MEM
  24423. ** <li> SQLITE_MUTEX_STATIC_OPEN
  24424. ** <li> SQLITE_MUTEX_STATIC_PRNG
  24425. ** <li> SQLITE_MUTEX_STATIC_LRU
  24426. ** <li> SQLITE_MUTEX_STATIC_PMEM
  24427. ** <li> SQLITE_MUTEX_STATIC_APP1
  24428. ** <li> SQLITE_MUTEX_STATIC_APP2
  24429. ** <li> SQLITE_MUTEX_STATIC_APP3
  24430. ** <li> SQLITE_MUTEX_STATIC_VFS1
  24431. ** <li> SQLITE_MUTEX_STATIC_VFS2
  24432. ** <li> SQLITE_MUTEX_STATIC_VFS3
  24433. ** </ul>
  24434. **
  24435. ** The first two constants cause sqlite3_mutex_alloc() to create
  24436. ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  24437. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  24438. ** The mutex implementation does not need to make a distinction
  24439. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  24440. ** not want to. But SQLite will only request a recursive mutex in
  24441. ** cases where it really needs one. If a faster non-recursive mutex
  24442. ** implementation is available on the host platform, the mutex subsystem
  24443. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  24444. **
  24445. ** The other allowed parameters to sqlite3_mutex_alloc() each return
  24446. ** a pointer to a static preexisting mutex. Six static mutexes are
  24447. ** used by the current version of SQLite. Future versions of SQLite
  24448. ** may add additional static mutexes. Static mutexes are for internal
  24449. ** use by SQLite only. Applications that use SQLite mutexes should
  24450. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  24451. ** SQLITE_MUTEX_RECURSIVE.
  24452. **
  24453. ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  24454. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  24455. ** returns a different mutex on every call. But for the static
  24456. ** mutex types, the same mutex is returned on every call that has
  24457. ** the same type number.
  24458. */
  24459. static sqlite3_mutex *pthreadMutexAlloc(int iType){
  24460. static sqlite3_mutex staticMutexes[] = {
  24461. SQLITE3_MUTEX_INITIALIZER(2),
  24462. SQLITE3_MUTEX_INITIALIZER(3),
  24463. SQLITE3_MUTEX_INITIALIZER(4),
  24464. SQLITE3_MUTEX_INITIALIZER(5),
  24465. SQLITE3_MUTEX_INITIALIZER(6),
  24466. SQLITE3_MUTEX_INITIALIZER(7),
  24467. SQLITE3_MUTEX_INITIALIZER(8),
  24468. SQLITE3_MUTEX_INITIALIZER(9),
  24469. SQLITE3_MUTEX_INITIALIZER(10),
  24470. SQLITE3_MUTEX_INITIALIZER(11),
  24471. SQLITE3_MUTEX_INITIALIZER(12),
  24472. SQLITE3_MUTEX_INITIALIZER(13)
  24473. };
  24474. sqlite3_mutex *p;
  24475. switch( iType ){
  24476. case SQLITE_MUTEX_RECURSIVE: {
  24477. p = sqlite3MallocZero( sizeof(*p) );
  24478. if( p ){
  24479. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  24480. /* If recursive mutexes are not available, we will have to
  24481. ** build our own. See below. */
  24482. pthread_mutex_init(&p->mutex, 0);
  24483. #else
  24484. /* Use a recursive mutex if it is available */
  24485. pthread_mutexattr_t recursiveAttr;
  24486. pthread_mutexattr_init(&recursiveAttr);
  24487. pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
  24488. pthread_mutex_init(&p->mutex, &recursiveAttr);
  24489. pthread_mutexattr_destroy(&recursiveAttr);
  24490. #endif
  24491. #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
  24492. p->id = SQLITE_MUTEX_RECURSIVE;
  24493. #endif
  24494. }
  24495. break;
  24496. }
  24497. case SQLITE_MUTEX_FAST: {
  24498. p = sqlite3MallocZero( sizeof(*p) );
  24499. if( p ){
  24500. pthread_mutex_init(&p->mutex, 0);
  24501. #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
  24502. p->id = SQLITE_MUTEX_FAST;
  24503. #endif
  24504. }
  24505. break;
  24506. }
  24507. default: {
  24508. #ifdef SQLITE_ENABLE_API_ARMOR
  24509. if( iType-2<0 || iType-2>=ArraySize(staticMutexes) ){
  24510. (void)SQLITE_MISUSE_BKPT;
  24511. return 0;
  24512. }
  24513. #endif
  24514. p = &staticMutexes[iType-2];
  24515. break;
  24516. }
  24517. }
  24518. #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
  24519. assert( p==0 || p->id==iType );
  24520. #endif
  24521. return p;
  24522. }
  24523. /*
  24524. ** This routine deallocates a previously
  24525. ** allocated mutex. SQLite is careful to deallocate every
  24526. ** mutex that it allocates.
  24527. */
  24528. static void pthreadMutexFree(sqlite3_mutex *p){
  24529. assert( p->nRef==0 );
  24530. #if SQLITE_ENABLE_API_ARMOR
  24531. if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE )
  24532. #endif
  24533. {
  24534. pthread_mutex_destroy(&p->mutex);
  24535. sqlite3_free(p);
  24536. }
  24537. #ifdef SQLITE_ENABLE_API_ARMOR
  24538. else{
  24539. (void)SQLITE_MISUSE_BKPT;
  24540. }
  24541. #endif
  24542. }
  24543. /*
  24544. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  24545. ** to enter a mutex. If another thread is already within the mutex,
  24546. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  24547. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  24548. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  24549. ** be entered multiple times by the same thread. In such cases the,
  24550. ** mutex must be exited an equal number of times before another thread
  24551. ** can enter. If the same thread tries to enter any other kind of mutex
  24552. ** more than once, the behavior is undefined.
  24553. */
  24554. static void pthreadMutexEnter(sqlite3_mutex *p){
  24555. assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
  24556. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  24557. /* If recursive mutexes are not available, then we have to grow
  24558. ** our own. This implementation assumes that pthread_equal()
  24559. ** is atomic - that it cannot be deceived into thinking self
  24560. ** and p->owner are equal if p->owner changes between two values
  24561. ** that are not equal to self while the comparison is taking place.
  24562. ** This implementation also assumes a coherent cache - that
  24563. ** separate processes cannot read different values from the same
  24564. ** address at the same time. If either of these two conditions
  24565. ** are not met, then the mutexes will fail and problems will result.
  24566. */
  24567. {
  24568. pthread_t self = pthread_self();
  24569. if( p->nRef>0 && pthread_equal(p->owner, self) ){
  24570. p->nRef++;
  24571. }else{
  24572. pthread_mutex_lock(&p->mutex);
  24573. assert( p->nRef==0 );
  24574. p->owner = self;
  24575. p->nRef = 1;
  24576. }
  24577. }
  24578. #else
  24579. /* Use the built-in recursive mutexes if they are available.
  24580. */
  24581. pthread_mutex_lock(&p->mutex);
  24582. #if SQLITE_MUTEX_NREF
  24583. assert( p->nRef>0 || p->owner==0 );
  24584. p->owner = pthread_self();
  24585. p->nRef++;
  24586. #endif
  24587. #endif
  24588. #ifdef SQLITE_DEBUG
  24589. if( p->trace ){
  24590. printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  24591. }
  24592. #endif
  24593. }
  24594. static int pthreadMutexTry(sqlite3_mutex *p){
  24595. int rc;
  24596. assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
  24597. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  24598. /* If recursive mutexes are not available, then we have to grow
  24599. ** our own. This implementation assumes that pthread_equal()
  24600. ** is atomic - that it cannot be deceived into thinking self
  24601. ** and p->owner are equal if p->owner changes between two values
  24602. ** that are not equal to self while the comparison is taking place.
  24603. ** This implementation also assumes a coherent cache - that
  24604. ** separate processes cannot read different values from the same
  24605. ** address at the same time. If either of these two conditions
  24606. ** are not met, then the mutexes will fail and problems will result.
  24607. */
  24608. {
  24609. pthread_t self = pthread_self();
  24610. if( p->nRef>0 && pthread_equal(p->owner, self) ){
  24611. p->nRef++;
  24612. rc = SQLITE_OK;
  24613. }else if( pthread_mutex_trylock(&p->mutex)==0 ){
  24614. assert( p->nRef==0 );
  24615. p->owner = self;
  24616. p->nRef = 1;
  24617. rc = SQLITE_OK;
  24618. }else{
  24619. rc = SQLITE_BUSY;
  24620. }
  24621. }
  24622. #else
  24623. /* Use the built-in recursive mutexes if they are available.
  24624. */
  24625. if( pthread_mutex_trylock(&p->mutex)==0 ){
  24626. #if SQLITE_MUTEX_NREF
  24627. p->owner = pthread_self();
  24628. p->nRef++;
  24629. #endif
  24630. rc = SQLITE_OK;
  24631. }else{
  24632. rc = SQLITE_BUSY;
  24633. }
  24634. #endif
  24635. #ifdef SQLITE_DEBUG
  24636. if( rc==SQLITE_OK && p->trace ){
  24637. printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  24638. }
  24639. #endif
  24640. return rc;
  24641. }
  24642. /*
  24643. ** The sqlite3_mutex_leave() routine exits a mutex that was
  24644. ** previously entered by the same thread. The behavior
  24645. ** is undefined if the mutex is not currently entered or
  24646. ** is not currently allocated. SQLite will never do either.
  24647. */
  24648. static void pthreadMutexLeave(sqlite3_mutex *p){
  24649. assert( pthreadMutexHeld(p) );
  24650. #if SQLITE_MUTEX_NREF
  24651. p->nRef--;
  24652. if( p->nRef==0 ) p->owner = 0;
  24653. #endif
  24654. assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
  24655. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  24656. if( p->nRef==0 ){
  24657. pthread_mutex_unlock(&p->mutex);
  24658. }
  24659. #else
  24660. pthread_mutex_unlock(&p->mutex);
  24661. #endif
  24662. #ifdef SQLITE_DEBUG
  24663. if( p->trace ){
  24664. printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  24665. }
  24666. #endif
  24667. }
  24668. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  24669. static const sqlite3_mutex_methods sMutex = {
  24670. pthreadMutexInit,
  24671. pthreadMutexEnd,
  24672. pthreadMutexAlloc,
  24673. pthreadMutexFree,
  24674. pthreadMutexEnter,
  24675. pthreadMutexTry,
  24676. pthreadMutexLeave,
  24677. #ifdef SQLITE_DEBUG
  24678. pthreadMutexHeld,
  24679. pthreadMutexNotheld
  24680. #else
  24681. 0,
  24682. 0
  24683. #endif
  24684. };
  24685. return &sMutex;
  24686. }
  24687. #endif /* SQLITE_MUTEX_PTHREADS */
  24688. /************** End of mutex_unix.c ******************************************/
  24689. /************** Begin file mutex_w32.c ***************************************/
  24690. /*
  24691. ** 2007 August 14
  24692. **
  24693. ** The author disclaims copyright to this source code. In place of
  24694. ** a legal notice, here is a blessing:
  24695. **
  24696. ** May you do good and not evil.
  24697. ** May you find forgiveness for yourself and forgive others.
  24698. ** May you share freely, never taking more than you give.
  24699. **
  24700. *************************************************************************
  24701. ** This file contains the C functions that implement mutexes for Win32.
  24702. */
  24703. /* #include "sqliteInt.h" */
  24704. #if SQLITE_OS_WIN
  24705. /*
  24706. ** Include code that is common to all os_*.c files
  24707. */
  24708. /************** Include os_common.h in the middle of mutex_w32.c *************/
  24709. /************** Begin file os_common.h ***************************************/
  24710. /*
  24711. ** 2004 May 22
  24712. **
  24713. ** The author disclaims copyright to this source code. In place of
  24714. ** a legal notice, here is a blessing:
  24715. **
  24716. ** May you do good and not evil.
  24717. ** May you find forgiveness for yourself and forgive others.
  24718. ** May you share freely, never taking more than you give.
  24719. **
  24720. ******************************************************************************
  24721. **
  24722. ** This file contains macros and a little bit of code that is common to
  24723. ** all of the platform-specific files (os_*.c) and is #included into those
  24724. ** files.
  24725. **
  24726. ** This file should be #included by the os_*.c files only. It is not a
  24727. ** general purpose header file.
  24728. */
  24729. #ifndef _OS_COMMON_H_
  24730. #define _OS_COMMON_H_
  24731. /*
  24732. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  24733. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  24734. ** switch. The following code should catch this problem at compile-time.
  24735. */
  24736. #ifdef MEMORY_DEBUG
  24737. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  24738. #endif
  24739. /*
  24740. ** Macros for performance tracing. Normally turned off. Only works
  24741. ** on i486 hardware.
  24742. */
  24743. #ifdef SQLITE_PERFORMANCE_TRACE
  24744. /*
  24745. ** hwtime.h contains inline assembler code for implementing
  24746. ** high-performance timing routines.
  24747. */
  24748. /************** Include hwtime.h in the middle of os_common.h ****************/
  24749. /************** Begin file hwtime.h ******************************************/
  24750. /*
  24751. ** 2008 May 27
  24752. **
  24753. ** The author disclaims copyright to this source code. In place of
  24754. ** a legal notice, here is a blessing:
  24755. **
  24756. ** May you do good and not evil.
  24757. ** May you find forgiveness for yourself and forgive others.
  24758. ** May you share freely, never taking more than you give.
  24759. **
  24760. ******************************************************************************
  24761. **
  24762. ** This file contains inline asm code for retrieving "high-performance"
  24763. ** counters for x86 class CPUs.
  24764. */
  24765. #ifndef SQLITE_HWTIME_H
  24766. #define SQLITE_HWTIME_H
  24767. /*
  24768. ** The following routine only works on pentium-class (or newer) processors.
  24769. ** It uses the RDTSC opcode to read the cycle count value out of the
  24770. ** processor and returns that value. This can be used for high-res
  24771. ** profiling.
  24772. */
  24773. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  24774. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  24775. #if defined(__GNUC__)
  24776. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  24777. unsigned int lo, hi;
  24778. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  24779. return (sqlite_uint64)hi << 32 | lo;
  24780. }
  24781. #elif defined(_MSC_VER)
  24782. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  24783. __asm {
  24784. rdtsc
  24785. ret ; return value at EDX:EAX
  24786. }
  24787. }
  24788. #endif
  24789. #elif (defined(__GNUC__) && defined(__x86_64__))
  24790. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  24791. unsigned long val;
  24792. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  24793. return val;
  24794. }
  24795. #elif (defined(__GNUC__) && defined(__ppc__))
  24796. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  24797. unsigned long long retval;
  24798. unsigned long junk;
  24799. __asm__ __volatile__ ("\n\
  24800. 1: mftbu %1\n\
  24801. mftb %L0\n\
  24802. mftbu %0\n\
  24803. cmpw %0,%1\n\
  24804. bne 1b"
  24805. : "=r" (retval), "=r" (junk));
  24806. return retval;
  24807. }
  24808. #else
  24809. #error Need implementation of sqlite3Hwtime() for your platform.
  24810. /*
  24811. ** To compile without implementing sqlite3Hwtime() for your platform,
  24812. ** you can remove the above #error and use the following
  24813. ** stub function. You will lose timing support for many
  24814. ** of the debugging and testing utilities, but it should at
  24815. ** least compile and run.
  24816. */
  24817. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  24818. #endif
  24819. #endif /* !defined(SQLITE_HWTIME_H) */
  24820. /************** End of hwtime.h **********************************************/
  24821. /************** Continuing where we left off in os_common.h ******************/
  24822. static sqlite_uint64 g_start;
  24823. static sqlite_uint64 g_elapsed;
  24824. #define TIMER_START g_start=sqlite3Hwtime()
  24825. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  24826. #define TIMER_ELAPSED g_elapsed
  24827. #else
  24828. #define TIMER_START
  24829. #define TIMER_END
  24830. #define TIMER_ELAPSED ((sqlite_uint64)0)
  24831. #endif
  24832. /*
  24833. ** If we compile with the SQLITE_TEST macro set, then the following block
  24834. ** of code will give us the ability to simulate a disk I/O error. This
  24835. ** is used for testing the I/O recovery logic.
  24836. */
  24837. #if defined(SQLITE_TEST)
  24838. SQLITE_API extern int sqlite3_io_error_hit;
  24839. SQLITE_API extern int sqlite3_io_error_hardhit;
  24840. SQLITE_API extern int sqlite3_io_error_pending;
  24841. SQLITE_API extern int sqlite3_io_error_persist;
  24842. SQLITE_API extern int sqlite3_io_error_benign;
  24843. SQLITE_API extern int sqlite3_diskfull_pending;
  24844. SQLITE_API extern int sqlite3_diskfull;
  24845. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  24846. #define SimulateIOError(CODE) \
  24847. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  24848. || sqlite3_io_error_pending-- == 1 ) \
  24849. { local_ioerr(); CODE; }
  24850. static void local_ioerr(){
  24851. IOTRACE(("IOERR\n"));
  24852. sqlite3_io_error_hit++;
  24853. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  24854. }
  24855. #define SimulateDiskfullError(CODE) \
  24856. if( sqlite3_diskfull_pending ){ \
  24857. if( sqlite3_diskfull_pending == 1 ){ \
  24858. local_ioerr(); \
  24859. sqlite3_diskfull = 1; \
  24860. sqlite3_io_error_hit = 1; \
  24861. CODE; \
  24862. }else{ \
  24863. sqlite3_diskfull_pending--; \
  24864. } \
  24865. }
  24866. #else
  24867. #define SimulateIOErrorBenign(X)
  24868. #define SimulateIOError(A)
  24869. #define SimulateDiskfullError(A)
  24870. #endif /* defined(SQLITE_TEST) */
  24871. /*
  24872. ** When testing, keep a count of the number of open files.
  24873. */
  24874. #if defined(SQLITE_TEST)
  24875. SQLITE_API extern int sqlite3_open_file_count;
  24876. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  24877. #else
  24878. #define OpenCounter(X)
  24879. #endif /* defined(SQLITE_TEST) */
  24880. #endif /* !defined(_OS_COMMON_H_) */
  24881. /************** End of os_common.h *******************************************/
  24882. /************** Continuing where we left off in mutex_w32.c ******************/
  24883. /*
  24884. ** Include the header file for the Windows VFS.
  24885. */
  24886. /************** Include os_win.h in the middle of mutex_w32.c ****************/
  24887. /************** Begin file os_win.h ******************************************/
  24888. /*
  24889. ** 2013 November 25
  24890. **
  24891. ** The author disclaims copyright to this source code. In place of
  24892. ** a legal notice, here is a blessing:
  24893. **
  24894. ** May you do good and not evil.
  24895. ** May you find forgiveness for yourself and forgive others.
  24896. ** May you share freely, never taking more than you give.
  24897. **
  24898. ******************************************************************************
  24899. **
  24900. ** This file contains code that is specific to Windows.
  24901. */
  24902. #ifndef SQLITE_OS_WIN_H
  24903. #define SQLITE_OS_WIN_H
  24904. /*
  24905. ** Include the primary Windows SDK header file.
  24906. */
  24907. #include "windows.h"
  24908. #ifdef __CYGWIN__
  24909. # include <sys/cygwin.h>
  24910. # include <errno.h> /* amalgamator: dontcache */
  24911. #endif
  24912. /*
  24913. ** Determine if we are dealing with Windows NT.
  24914. **
  24915. ** We ought to be able to determine if we are compiling for Windows 9x or
  24916. ** Windows NT using the _WIN32_WINNT macro as follows:
  24917. **
  24918. ** #if defined(_WIN32_WINNT)
  24919. ** # define SQLITE_OS_WINNT 1
  24920. ** #else
  24921. ** # define SQLITE_OS_WINNT 0
  24922. ** #endif
  24923. **
  24924. ** However, Visual Studio 2005 does not set _WIN32_WINNT by default, as
  24925. ** it ought to, so the above test does not work. We'll just assume that
  24926. ** everything is Windows NT unless the programmer explicitly says otherwise
  24927. ** by setting SQLITE_OS_WINNT to 0.
  24928. */
  24929. #if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT)
  24930. # define SQLITE_OS_WINNT 1
  24931. #endif
  24932. /*
  24933. ** Determine if we are dealing with Windows CE - which has a much reduced
  24934. ** API.
  24935. */
  24936. #if defined(_WIN32_WCE)
  24937. # define SQLITE_OS_WINCE 1
  24938. #else
  24939. # define SQLITE_OS_WINCE 0
  24940. #endif
  24941. /*
  24942. ** Determine if we are dealing with WinRT, which provides only a subset of
  24943. ** the full Win32 API.
  24944. */
  24945. #if !defined(SQLITE_OS_WINRT)
  24946. # define SQLITE_OS_WINRT 0
  24947. #endif
  24948. /*
  24949. ** For WinCE, some API function parameters do not appear to be declared as
  24950. ** volatile.
  24951. */
  24952. #if SQLITE_OS_WINCE
  24953. # define SQLITE_WIN32_VOLATILE
  24954. #else
  24955. # define SQLITE_WIN32_VOLATILE volatile
  24956. #endif
  24957. /*
  24958. ** For some Windows sub-platforms, the _beginthreadex() / _endthreadex()
  24959. ** functions are not available (e.g. those not using MSVC, Cygwin, etc).
  24960. */
  24961. #if SQLITE_OS_WIN && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
  24962. SQLITE_THREADSAFE>0 && !defined(__CYGWIN__)
  24963. # define SQLITE_OS_WIN_THREADS 1
  24964. #else
  24965. # define SQLITE_OS_WIN_THREADS 0
  24966. #endif
  24967. #endif /* SQLITE_OS_WIN_H */
  24968. /************** End of os_win.h **********************************************/
  24969. /************** Continuing where we left off in mutex_w32.c ******************/
  24970. #endif
  24971. /*
  24972. ** The code in this file is only used if we are compiling multithreaded
  24973. ** on a Win32 system.
  24974. */
  24975. #ifdef SQLITE_MUTEX_W32
  24976. /*
  24977. ** Each recursive mutex is an instance of the following structure.
  24978. */
  24979. struct sqlite3_mutex {
  24980. CRITICAL_SECTION mutex; /* Mutex controlling the lock */
  24981. int id; /* Mutex type */
  24982. #ifdef SQLITE_DEBUG
  24983. volatile int nRef; /* Number of enterances */
  24984. volatile DWORD owner; /* Thread holding this mutex */
  24985. volatile LONG trace; /* True to trace changes */
  24986. #endif
  24987. };
  24988. /*
  24989. ** These are the initializer values used when declaring a "static" mutex
  24990. ** on Win32. It should be noted that all mutexes require initialization
  24991. ** on the Win32 platform.
  24992. */
  24993. #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
  24994. #ifdef SQLITE_DEBUG
  24995. #define SQLITE3_MUTEX_INITIALIZER(id) { SQLITE_W32_MUTEX_INITIALIZER, id, \
  24996. 0L, (DWORD)0, 0 }
  24997. #else
  24998. #define SQLITE3_MUTEX_INITIALIZER(id) { SQLITE_W32_MUTEX_INITIALIZER, id }
  24999. #endif
  25000. #ifdef SQLITE_DEBUG
  25001. /*
  25002. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  25003. ** intended for use only inside assert() statements.
  25004. */
  25005. static int winMutexHeld(sqlite3_mutex *p){
  25006. return p->nRef!=0 && p->owner==GetCurrentThreadId();
  25007. }
  25008. static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
  25009. return p->nRef==0 || p->owner!=tid;
  25010. }
  25011. static int winMutexNotheld(sqlite3_mutex *p){
  25012. DWORD tid = GetCurrentThreadId();
  25013. return winMutexNotheld2(p, tid);
  25014. }
  25015. #endif
  25016. /*
  25017. ** Try to provide a memory barrier operation, needed for initialization
  25018. ** and also for the xShmBarrier method of the VFS in cases when SQLite is
  25019. ** compiled without mutexes (SQLITE_THREADSAFE=0).
  25020. */
  25021. SQLITE_PRIVATE void sqlite3MemoryBarrier(void){
  25022. #if defined(SQLITE_MEMORY_BARRIER)
  25023. SQLITE_MEMORY_BARRIER;
  25024. #elif defined(__GNUC__)
  25025. __sync_synchronize();
  25026. #elif MSVC_VERSION>=1300
  25027. _ReadWriteBarrier();
  25028. #elif defined(MemoryBarrier)
  25029. MemoryBarrier();
  25030. #endif
  25031. }
  25032. /*
  25033. ** Initialize and deinitialize the mutex subsystem.
  25034. */
  25035. static sqlite3_mutex winMutex_staticMutexes[] = {
  25036. SQLITE3_MUTEX_INITIALIZER(2),
  25037. SQLITE3_MUTEX_INITIALIZER(3),
  25038. SQLITE3_MUTEX_INITIALIZER(4),
  25039. SQLITE3_MUTEX_INITIALIZER(5),
  25040. SQLITE3_MUTEX_INITIALIZER(6),
  25041. SQLITE3_MUTEX_INITIALIZER(7),
  25042. SQLITE3_MUTEX_INITIALIZER(8),
  25043. SQLITE3_MUTEX_INITIALIZER(9),
  25044. SQLITE3_MUTEX_INITIALIZER(10),
  25045. SQLITE3_MUTEX_INITIALIZER(11),
  25046. SQLITE3_MUTEX_INITIALIZER(12),
  25047. SQLITE3_MUTEX_INITIALIZER(13)
  25048. };
  25049. static int winMutex_isInit = 0;
  25050. static int winMutex_isNt = -1; /* <0 means "need to query" */
  25051. /* As the winMutexInit() and winMutexEnd() functions are called as part
  25052. ** of the sqlite3_initialize() and sqlite3_shutdown() processing, the
  25053. ** "interlocked" magic used here is probably not strictly necessary.
  25054. */
  25055. static LONG SQLITE_WIN32_VOLATILE winMutex_lock = 0;
  25056. SQLITE_API int sqlite3_win32_is_nt(void); /* os_win.c */
  25057. SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */
  25058. static int winMutexInit(void){
  25059. /* The first to increment to 1 does actual initialization */
  25060. if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
  25061. int i;
  25062. for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
  25063. #if SQLITE_OS_WINRT
  25064. InitializeCriticalSectionEx(&winMutex_staticMutexes[i].mutex, 0, 0);
  25065. #else
  25066. InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
  25067. #endif
  25068. }
  25069. winMutex_isInit = 1;
  25070. }else{
  25071. /* Another thread is (in the process of) initializing the static
  25072. ** mutexes */
  25073. while( !winMutex_isInit ){
  25074. sqlite3_win32_sleep(1);
  25075. }
  25076. }
  25077. return SQLITE_OK;
  25078. }
  25079. static int winMutexEnd(void){
  25080. /* The first to decrement to 0 does actual shutdown
  25081. ** (which should be the last to shutdown.) */
  25082. if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
  25083. if( winMutex_isInit==1 ){
  25084. int i;
  25085. for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
  25086. DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
  25087. }
  25088. winMutex_isInit = 0;
  25089. }
  25090. }
  25091. return SQLITE_OK;
  25092. }
  25093. /*
  25094. ** The sqlite3_mutex_alloc() routine allocates a new
  25095. ** mutex and returns a pointer to it. If it returns NULL
  25096. ** that means that a mutex could not be allocated. SQLite
  25097. ** will unwind its stack and return an error. The argument
  25098. ** to sqlite3_mutex_alloc() is one of these integer constants:
  25099. **
  25100. ** <ul>
  25101. ** <li> SQLITE_MUTEX_FAST
  25102. ** <li> SQLITE_MUTEX_RECURSIVE
  25103. ** <li> SQLITE_MUTEX_STATIC_MASTER
  25104. ** <li> SQLITE_MUTEX_STATIC_MEM
  25105. ** <li> SQLITE_MUTEX_STATIC_OPEN
  25106. ** <li> SQLITE_MUTEX_STATIC_PRNG
  25107. ** <li> SQLITE_MUTEX_STATIC_LRU
  25108. ** <li> SQLITE_MUTEX_STATIC_PMEM
  25109. ** <li> SQLITE_MUTEX_STATIC_APP1
  25110. ** <li> SQLITE_MUTEX_STATIC_APP2
  25111. ** <li> SQLITE_MUTEX_STATIC_APP3
  25112. ** <li> SQLITE_MUTEX_STATIC_VFS1
  25113. ** <li> SQLITE_MUTEX_STATIC_VFS2
  25114. ** <li> SQLITE_MUTEX_STATIC_VFS3
  25115. ** </ul>
  25116. **
  25117. ** The first two constants cause sqlite3_mutex_alloc() to create
  25118. ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  25119. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  25120. ** The mutex implementation does not need to make a distinction
  25121. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  25122. ** not want to. But SQLite will only request a recursive mutex in
  25123. ** cases where it really needs one. If a faster non-recursive mutex
  25124. ** implementation is available on the host platform, the mutex subsystem
  25125. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  25126. **
  25127. ** The other allowed parameters to sqlite3_mutex_alloc() each return
  25128. ** a pointer to a static preexisting mutex. Six static mutexes are
  25129. ** used by the current version of SQLite. Future versions of SQLite
  25130. ** may add additional static mutexes. Static mutexes are for internal
  25131. ** use by SQLite only. Applications that use SQLite mutexes should
  25132. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  25133. ** SQLITE_MUTEX_RECURSIVE.
  25134. **
  25135. ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  25136. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  25137. ** returns a different mutex on every call. But for the static
  25138. ** mutex types, the same mutex is returned on every call that has
  25139. ** the same type number.
  25140. */
  25141. static sqlite3_mutex *winMutexAlloc(int iType){
  25142. sqlite3_mutex *p;
  25143. switch( iType ){
  25144. case SQLITE_MUTEX_FAST:
  25145. case SQLITE_MUTEX_RECURSIVE: {
  25146. p = sqlite3MallocZero( sizeof(*p) );
  25147. if( p ){
  25148. p->id = iType;
  25149. #ifdef SQLITE_DEBUG
  25150. #ifdef SQLITE_WIN32_MUTEX_TRACE_DYNAMIC
  25151. p->trace = 1;
  25152. #endif
  25153. #endif
  25154. #if SQLITE_OS_WINRT
  25155. InitializeCriticalSectionEx(&p->mutex, 0, 0);
  25156. #else
  25157. InitializeCriticalSection(&p->mutex);
  25158. #endif
  25159. }
  25160. break;
  25161. }
  25162. default: {
  25163. #ifdef SQLITE_ENABLE_API_ARMOR
  25164. if( iType-2<0 || iType-2>=ArraySize(winMutex_staticMutexes) ){
  25165. (void)SQLITE_MISUSE_BKPT;
  25166. return 0;
  25167. }
  25168. #endif
  25169. p = &winMutex_staticMutexes[iType-2];
  25170. #ifdef SQLITE_DEBUG
  25171. #ifdef SQLITE_WIN32_MUTEX_TRACE_STATIC
  25172. InterlockedCompareExchange(&p->trace, 1, 0);
  25173. #endif
  25174. #endif
  25175. break;
  25176. }
  25177. }
  25178. assert( p==0 || p->id==iType );
  25179. return p;
  25180. }
  25181. /*
  25182. ** This routine deallocates a previously
  25183. ** allocated mutex. SQLite is careful to deallocate every
  25184. ** mutex that it allocates.
  25185. */
  25186. static void winMutexFree(sqlite3_mutex *p){
  25187. assert( p );
  25188. assert( p->nRef==0 && p->owner==0 );
  25189. if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE ){
  25190. DeleteCriticalSection(&p->mutex);
  25191. sqlite3_free(p);
  25192. }else{
  25193. #ifdef SQLITE_ENABLE_API_ARMOR
  25194. (void)SQLITE_MISUSE_BKPT;
  25195. #endif
  25196. }
  25197. }
  25198. /*
  25199. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  25200. ** to enter a mutex. If another thread is already within the mutex,
  25201. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  25202. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  25203. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  25204. ** be entered multiple times by the same thread. In such cases the,
  25205. ** mutex must be exited an equal number of times before another thread
  25206. ** can enter. If the same thread tries to enter any other kind of mutex
  25207. ** more than once, the behavior is undefined.
  25208. */
  25209. static void winMutexEnter(sqlite3_mutex *p){
  25210. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  25211. DWORD tid = GetCurrentThreadId();
  25212. #endif
  25213. #ifdef SQLITE_DEBUG
  25214. assert( p );
  25215. assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
  25216. #else
  25217. assert( p );
  25218. #endif
  25219. assert( winMutex_isInit==1 );
  25220. EnterCriticalSection(&p->mutex);
  25221. #ifdef SQLITE_DEBUG
  25222. assert( p->nRef>0 || p->owner==0 );
  25223. p->owner = tid;
  25224. p->nRef++;
  25225. if( p->trace ){
  25226. OSTRACE(("ENTER-MUTEX tid=%lu, mutex(%d)=%p (%d), nRef=%d\n",
  25227. tid, p->id, p, p->trace, p->nRef));
  25228. }
  25229. #endif
  25230. }
  25231. static int winMutexTry(sqlite3_mutex *p){
  25232. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  25233. DWORD tid = GetCurrentThreadId();
  25234. #endif
  25235. int rc = SQLITE_BUSY;
  25236. assert( p );
  25237. assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
  25238. /*
  25239. ** The sqlite3_mutex_try() routine is very rarely used, and when it
  25240. ** is used it is merely an optimization. So it is OK for it to always
  25241. ** fail.
  25242. **
  25243. ** The TryEnterCriticalSection() interface is only available on WinNT.
  25244. ** And some windows compilers complain if you try to use it without
  25245. ** first doing some #defines that prevent SQLite from building on Win98.
  25246. ** For that reason, we will omit this optimization for now. See
  25247. ** ticket #2685.
  25248. */
  25249. #if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0400
  25250. assert( winMutex_isInit==1 );
  25251. assert( winMutex_isNt>=-1 && winMutex_isNt<=1 );
  25252. if( winMutex_isNt<0 ){
  25253. winMutex_isNt = sqlite3_win32_is_nt();
  25254. }
  25255. assert( winMutex_isNt==0 || winMutex_isNt==1 );
  25256. if( winMutex_isNt && TryEnterCriticalSection(&p->mutex) ){
  25257. #ifdef SQLITE_DEBUG
  25258. p->owner = tid;
  25259. p->nRef++;
  25260. #endif
  25261. rc = SQLITE_OK;
  25262. }
  25263. #else
  25264. UNUSED_PARAMETER(p);
  25265. #endif
  25266. #ifdef SQLITE_DEBUG
  25267. if( p->trace ){
  25268. OSTRACE(("TRY-MUTEX tid=%lu, mutex(%d)=%p (%d), owner=%lu, nRef=%d, rc=%s\n",
  25269. tid, p->id, p, p->trace, p->owner, p->nRef, sqlite3ErrName(rc)));
  25270. }
  25271. #endif
  25272. return rc;
  25273. }
  25274. /*
  25275. ** The sqlite3_mutex_leave() routine exits a mutex that was
  25276. ** previously entered by the same thread. The behavior
  25277. ** is undefined if the mutex is not currently entered or
  25278. ** is not currently allocated. SQLite will never do either.
  25279. */
  25280. static void winMutexLeave(sqlite3_mutex *p){
  25281. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  25282. DWORD tid = GetCurrentThreadId();
  25283. #endif
  25284. assert( p );
  25285. #ifdef SQLITE_DEBUG
  25286. assert( p->nRef>0 );
  25287. assert( p->owner==tid );
  25288. p->nRef--;
  25289. if( p->nRef==0 ) p->owner = 0;
  25290. assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
  25291. #endif
  25292. assert( winMutex_isInit==1 );
  25293. LeaveCriticalSection(&p->mutex);
  25294. #ifdef SQLITE_DEBUG
  25295. if( p->trace ){
  25296. OSTRACE(("LEAVE-MUTEX tid=%lu, mutex(%d)=%p (%d), nRef=%d\n",
  25297. tid, p->id, p, p->trace, p->nRef));
  25298. }
  25299. #endif
  25300. }
  25301. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  25302. static const sqlite3_mutex_methods sMutex = {
  25303. winMutexInit,
  25304. winMutexEnd,
  25305. winMutexAlloc,
  25306. winMutexFree,
  25307. winMutexEnter,
  25308. winMutexTry,
  25309. winMutexLeave,
  25310. #ifdef SQLITE_DEBUG
  25311. winMutexHeld,
  25312. winMutexNotheld
  25313. #else
  25314. 0,
  25315. 0
  25316. #endif
  25317. };
  25318. return &sMutex;
  25319. }
  25320. #endif /* SQLITE_MUTEX_W32 */
  25321. /************** End of mutex_w32.c *******************************************/
  25322. /************** Begin file malloc.c ******************************************/
  25323. /*
  25324. ** 2001 September 15
  25325. **
  25326. ** The author disclaims copyright to this source code. In place of
  25327. ** a legal notice, here is a blessing:
  25328. **
  25329. ** May you do good and not evil.
  25330. ** May you find forgiveness for yourself and forgive others.
  25331. ** May you share freely, never taking more than you give.
  25332. **
  25333. *************************************************************************
  25334. **
  25335. ** Memory allocation functions used throughout sqlite.
  25336. */
  25337. /* #include "sqliteInt.h" */
  25338. /* #include <stdarg.h> */
  25339. /*
  25340. ** Attempt to release up to n bytes of non-essential memory currently
  25341. ** held by SQLite. An example of non-essential memory is memory used to
  25342. ** cache database pages that are not currently in use.
  25343. */
  25344. SQLITE_API int sqlite3_release_memory(int n){
  25345. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  25346. return sqlite3PcacheReleaseMemory(n);
  25347. #else
  25348. /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
  25349. ** is a no-op returning zero if SQLite is not compiled with
  25350. ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
  25351. UNUSED_PARAMETER(n);
  25352. return 0;
  25353. #endif
  25354. }
  25355. /*
  25356. ** State information local to the memory allocation subsystem.
  25357. */
  25358. static SQLITE_WSD struct Mem0Global {
  25359. sqlite3_mutex *mutex; /* Mutex to serialize access */
  25360. sqlite3_int64 alarmThreshold; /* The soft heap limit */
  25361. /*
  25362. ** True if heap is nearly "full" where "full" is defined by the
  25363. ** sqlite3_soft_heap_limit() setting.
  25364. */
  25365. int nearlyFull;
  25366. } mem0 = { 0, 0, 0 };
  25367. #define mem0 GLOBAL(struct Mem0Global, mem0)
  25368. /*
  25369. ** Return the memory allocator mutex. sqlite3_status() needs it.
  25370. */
  25371. SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void){
  25372. return mem0.mutex;
  25373. }
  25374. #ifndef SQLITE_OMIT_DEPRECATED
  25375. /*
  25376. ** Deprecated external interface. It used to set an alarm callback
  25377. ** that was invoked when memory usage grew too large. Now it is a
  25378. ** no-op.
  25379. */
  25380. SQLITE_API int sqlite3_memory_alarm(
  25381. void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
  25382. void *pArg,
  25383. sqlite3_int64 iThreshold
  25384. ){
  25385. (void)xCallback;
  25386. (void)pArg;
  25387. (void)iThreshold;
  25388. return SQLITE_OK;
  25389. }
  25390. #endif
  25391. /*
  25392. ** Set the soft heap-size limit for the library. Passing a zero or
  25393. ** negative value indicates no limit.
  25394. */
  25395. SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
  25396. sqlite3_int64 priorLimit;
  25397. sqlite3_int64 excess;
  25398. sqlite3_int64 nUsed;
  25399. #ifndef SQLITE_OMIT_AUTOINIT
  25400. int rc = sqlite3_initialize();
  25401. if( rc ) return -1;
  25402. #endif
  25403. sqlite3_mutex_enter(mem0.mutex);
  25404. priorLimit = mem0.alarmThreshold;
  25405. if( n<0 ){
  25406. sqlite3_mutex_leave(mem0.mutex);
  25407. return priorLimit;
  25408. }
  25409. mem0.alarmThreshold = n;
  25410. nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  25411. mem0.nearlyFull = (n>0 && n<=nUsed);
  25412. sqlite3_mutex_leave(mem0.mutex);
  25413. excess = sqlite3_memory_used() - n;
  25414. if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
  25415. return priorLimit;
  25416. }
  25417. SQLITE_API void sqlite3_soft_heap_limit(int n){
  25418. if( n<0 ) n = 0;
  25419. sqlite3_soft_heap_limit64(n);
  25420. }
  25421. /*
  25422. ** Initialize the memory allocation subsystem.
  25423. */
  25424. SQLITE_PRIVATE int sqlite3MallocInit(void){
  25425. int rc;
  25426. if( sqlite3GlobalConfig.m.xMalloc==0 ){
  25427. sqlite3MemSetDefault();
  25428. }
  25429. memset(&mem0, 0, sizeof(mem0));
  25430. mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  25431. if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
  25432. || sqlite3GlobalConfig.nPage<=0 ){
  25433. sqlite3GlobalConfig.pPage = 0;
  25434. sqlite3GlobalConfig.szPage = 0;
  25435. }
  25436. rc = sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
  25437. if( rc!=SQLITE_OK ) memset(&mem0, 0, sizeof(mem0));
  25438. return rc;
  25439. }
  25440. /*
  25441. ** Return true if the heap is currently under memory pressure - in other
  25442. ** words if the amount of heap used is close to the limit set by
  25443. ** sqlite3_soft_heap_limit().
  25444. */
  25445. SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
  25446. return mem0.nearlyFull;
  25447. }
  25448. /*
  25449. ** Deinitialize the memory allocation subsystem.
  25450. */
  25451. SQLITE_PRIVATE void sqlite3MallocEnd(void){
  25452. if( sqlite3GlobalConfig.m.xShutdown ){
  25453. sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
  25454. }
  25455. memset(&mem0, 0, sizeof(mem0));
  25456. }
  25457. /*
  25458. ** Return the amount of memory currently checked out.
  25459. */
  25460. SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
  25461. sqlite3_int64 res, mx;
  25462. sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, 0);
  25463. return res;
  25464. }
  25465. /*
  25466. ** Return the maximum amount of memory that has ever been
  25467. ** checked out since either the beginning of this process
  25468. ** or since the most recent reset.
  25469. */
  25470. SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
  25471. sqlite3_int64 res, mx;
  25472. sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, resetFlag);
  25473. return mx;
  25474. }
  25475. /*
  25476. ** Trigger the alarm
  25477. */
  25478. static void sqlite3MallocAlarm(int nByte){
  25479. if( mem0.alarmThreshold<=0 ) return;
  25480. sqlite3_mutex_leave(mem0.mutex);
  25481. sqlite3_release_memory(nByte);
  25482. sqlite3_mutex_enter(mem0.mutex);
  25483. }
  25484. /*
  25485. ** Do a memory allocation with statistics and alarms. Assume the
  25486. ** lock is already held.
  25487. */
  25488. static void mallocWithAlarm(int n, void **pp){
  25489. void *p;
  25490. int nFull;
  25491. assert( sqlite3_mutex_held(mem0.mutex) );
  25492. assert( n>0 );
  25493. /* In Firefox (circa 2017-02-08), xRoundup() is remapped to an internal
  25494. ** implementation of malloc_good_size(), which must be called in debug
  25495. ** mode and specifically when the DMD "Dark Matter Detector" is enabled
  25496. ** or else a crash results. Hence, do not attempt to optimize out the
  25497. ** following xRoundup() call. */
  25498. nFull = sqlite3GlobalConfig.m.xRoundup(n);
  25499. #ifdef SQLITE_MAX_MEMORY
  25500. if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED)+nFull>SQLITE_MAX_MEMORY ){
  25501. *pp = 0;
  25502. return;
  25503. }
  25504. #endif
  25505. sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, n);
  25506. if( mem0.alarmThreshold>0 ){
  25507. sqlite3_int64 nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  25508. if( nUsed >= mem0.alarmThreshold - nFull ){
  25509. mem0.nearlyFull = 1;
  25510. sqlite3MallocAlarm(nFull);
  25511. }else{
  25512. mem0.nearlyFull = 0;
  25513. }
  25514. }
  25515. p = sqlite3GlobalConfig.m.xMalloc(nFull);
  25516. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  25517. if( p==0 && mem0.alarmThreshold>0 ){
  25518. sqlite3MallocAlarm(nFull);
  25519. p = sqlite3GlobalConfig.m.xMalloc(nFull);
  25520. }
  25521. #endif
  25522. if( p ){
  25523. nFull = sqlite3MallocSize(p);
  25524. sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nFull);
  25525. sqlite3StatusUp(SQLITE_STATUS_MALLOC_COUNT, 1);
  25526. }
  25527. *pp = p;
  25528. }
  25529. /*
  25530. ** Allocate memory. This routine is like sqlite3_malloc() except that it
  25531. ** assumes the memory subsystem has already been initialized.
  25532. */
  25533. SQLITE_PRIVATE void *sqlite3Malloc(u64 n){
  25534. void *p;
  25535. if( n==0 || n>=0x7fffff00 ){
  25536. /* A memory allocation of a number of bytes which is near the maximum
  25537. ** signed integer value might cause an integer overflow inside of the
  25538. ** xMalloc(). Hence we limit the maximum size to 0x7fffff00, giving
  25539. ** 255 bytes of overhead. SQLite itself will never use anything near
  25540. ** this amount. The only way to reach the limit is with sqlite3_malloc() */
  25541. p = 0;
  25542. }else if( sqlite3GlobalConfig.bMemstat ){
  25543. sqlite3_mutex_enter(mem0.mutex);
  25544. mallocWithAlarm((int)n, &p);
  25545. sqlite3_mutex_leave(mem0.mutex);
  25546. }else{
  25547. p = sqlite3GlobalConfig.m.xMalloc((int)n);
  25548. }
  25549. assert( EIGHT_BYTE_ALIGNMENT(p) ); /* IMP: R-11148-40995 */
  25550. return p;
  25551. }
  25552. /*
  25553. ** This version of the memory allocation is for use by the application.
  25554. ** First make sure the memory subsystem is initialized, then do the
  25555. ** allocation.
  25556. */
  25557. SQLITE_API void *sqlite3_malloc(int n){
  25558. #ifndef SQLITE_OMIT_AUTOINIT
  25559. if( sqlite3_initialize() ) return 0;
  25560. #endif
  25561. return n<=0 ? 0 : sqlite3Malloc(n);
  25562. }
  25563. SQLITE_API void *sqlite3_malloc64(sqlite3_uint64 n){
  25564. #ifndef SQLITE_OMIT_AUTOINIT
  25565. if( sqlite3_initialize() ) return 0;
  25566. #endif
  25567. return sqlite3Malloc(n);
  25568. }
  25569. /*
  25570. ** TRUE if p is a lookaside memory allocation from db
  25571. */
  25572. #ifndef SQLITE_OMIT_LOOKASIDE
  25573. static int isLookaside(sqlite3 *db, void *p){
  25574. return SQLITE_WITHIN(p, db->lookaside.pStart, db->lookaside.pEnd);
  25575. }
  25576. #else
  25577. #define isLookaside(A,B) 0
  25578. #endif
  25579. /*
  25580. ** Return the size of a memory allocation previously obtained from
  25581. ** sqlite3Malloc() or sqlite3_malloc().
  25582. */
  25583. SQLITE_PRIVATE int sqlite3MallocSize(void *p){
  25584. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  25585. return sqlite3GlobalConfig.m.xSize(p);
  25586. }
  25587. SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
  25588. assert( p!=0 );
  25589. if( db==0 || !isLookaside(db,p) ){
  25590. #ifdef SQLITE_DEBUG
  25591. if( db==0 ){
  25592. assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
  25593. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  25594. }else{
  25595. assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  25596. assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  25597. }
  25598. #endif
  25599. return sqlite3GlobalConfig.m.xSize(p);
  25600. }else{
  25601. assert( sqlite3_mutex_held(db->mutex) );
  25602. return db->lookaside.sz;
  25603. }
  25604. }
  25605. SQLITE_API sqlite3_uint64 sqlite3_msize(void *p){
  25606. assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
  25607. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  25608. return p ? sqlite3GlobalConfig.m.xSize(p) : 0;
  25609. }
  25610. /*
  25611. ** Free memory previously obtained from sqlite3Malloc().
  25612. */
  25613. SQLITE_API void sqlite3_free(void *p){
  25614. if( p==0 ) return; /* IMP: R-49053-54554 */
  25615. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  25616. assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
  25617. if( sqlite3GlobalConfig.bMemstat ){
  25618. sqlite3_mutex_enter(mem0.mutex);
  25619. sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, sqlite3MallocSize(p));
  25620. sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1);
  25621. sqlite3GlobalConfig.m.xFree(p);
  25622. sqlite3_mutex_leave(mem0.mutex);
  25623. }else{
  25624. sqlite3GlobalConfig.m.xFree(p);
  25625. }
  25626. }
  25627. /*
  25628. ** Add the size of memory allocation "p" to the count in
  25629. ** *db->pnBytesFreed.
  25630. */
  25631. static SQLITE_NOINLINE void measureAllocationSize(sqlite3 *db, void *p){
  25632. *db->pnBytesFreed += sqlite3DbMallocSize(db,p);
  25633. }
  25634. /*
  25635. ** Free memory that might be associated with a particular database
  25636. ** connection. Calling sqlite3DbFree(D,X) for X==0 is a harmless no-op.
  25637. ** The sqlite3DbFreeNN(D,X) version requires that X be non-NULL.
  25638. */
  25639. SQLITE_PRIVATE void sqlite3DbFreeNN(sqlite3 *db, void *p){
  25640. assert( db==0 || sqlite3_mutex_held(db->mutex) );
  25641. assert( p!=0 );
  25642. if( db ){
  25643. if( db->pnBytesFreed ){
  25644. measureAllocationSize(db, p);
  25645. return;
  25646. }
  25647. if( isLookaside(db, p) ){
  25648. LookasideSlot *pBuf = (LookasideSlot*)p;
  25649. #ifdef SQLITE_DEBUG
  25650. /* Trash all content in the buffer being freed */
  25651. memset(p, 0xaa, db->lookaside.sz);
  25652. #endif
  25653. pBuf->pNext = db->lookaside.pFree;
  25654. db->lookaside.pFree = pBuf;
  25655. return;
  25656. }
  25657. }
  25658. assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  25659. assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  25660. assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
  25661. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  25662. sqlite3_free(p);
  25663. }
  25664. SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
  25665. assert( db==0 || sqlite3_mutex_held(db->mutex) );
  25666. if( p ) sqlite3DbFreeNN(db, p);
  25667. }
  25668. /*
  25669. ** Change the size of an existing memory allocation
  25670. */
  25671. SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, u64 nBytes){
  25672. int nOld, nNew, nDiff;
  25673. void *pNew;
  25674. assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
  25675. assert( sqlite3MemdebugNoType(pOld, (u8)~MEMTYPE_HEAP) );
  25676. if( pOld==0 ){
  25677. return sqlite3Malloc(nBytes); /* IMP: R-04300-56712 */
  25678. }
  25679. if( nBytes==0 ){
  25680. sqlite3_free(pOld); /* IMP: R-26507-47431 */
  25681. return 0;
  25682. }
  25683. if( nBytes>=0x7fffff00 ){
  25684. /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
  25685. return 0;
  25686. }
  25687. nOld = sqlite3MallocSize(pOld);
  25688. /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
  25689. ** argument to xRealloc is always a value returned by a prior call to
  25690. ** xRoundup. */
  25691. nNew = sqlite3GlobalConfig.m.xRoundup((int)nBytes);
  25692. if( nOld==nNew ){
  25693. pNew = pOld;
  25694. }else if( sqlite3GlobalConfig.bMemstat ){
  25695. sqlite3_mutex_enter(mem0.mutex);
  25696. sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, (int)nBytes);
  25697. nDiff = nNew - nOld;
  25698. if( nDiff>0 && sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >=
  25699. mem0.alarmThreshold-nDiff ){
  25700. sqlite3MallocAlarm(nDiff);
  25701. }
  25702. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  25703. if( pNew==0 && mem0.alarmThreshold>0 ){
  25704. sqlite3MallocAlarm((int)nBytes);
  25705. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  25706. }
  25707. if( pNew ){
  25708. nNew = sqlite3MallocSize(pNew);
  25709. sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
  25710. }
  25711. sqlite3_mutex_leave(mem0.mutex);
  25712. }else{
  25713. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  25714. }
  25715. assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-11148-40995 */
  25716. return pNew;
  25717. }
  25718. /*
  25719. ** The public interface to sqlite3Realloc. Make sure that the memory
  25720. ** subsystem is initialized prior to invoking sqliteRealloc.
  25721. */
  25722. SQLITE_API void *sqlite3_realloc(void *pOld, int n){
  25723. #ifndef SQLITE_OMIT_AUTOINIT
  25724. if( sqlite3_initialize() ) return 0;
  25725. #endif
  25726. if( n<0 ) n = 0; /* IMP: R-26507-47431 */
  25727. return sqlite3Realloc(pOld, n);
  25728. }
  25729. SQLITE_API void *sqlite3_realloc64(void *pOld, sqlite3_uint64 n){
  25730. #ifndef SQLITE_OMIT_AUTOINIT
  25731. if( sqlite3_initialize() ) return 0;
  25732. #endif
  25733. return sqlite3Realloc(pOld, n);
  25734. }
  25735. /*
  25736. ** Allocate and zero memory.
  25737. */
  25738. SQLITE_PRIVATE void *sqlite3MallocZero(u64 n){
  25739. void *p = sqlite3Malloc(n);
  25740. if( p ){
  25741. memset(p, 0, (size_t)n);
  25742. }
  25743. return p;
  25744. }
  25745. /*
  25746. ** Allocate and zero memory. If the allocation fails, make
  25747. ** the mallocFailed flag in the connection pointer.
  25748. */
  25749. SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, u64 n){
  25750. void *p;
  25751. testcase( db==0 );
  25752. p = sqlite3DbMallocRaw(db, n);
  25753. if( p ) memset(p, 0, (size_t)n);
  25754. return p;
  25755. }
  25756. /* Finish the work of sqlite3DbMallocRawNN for the unusual and
  25757. ** slower case when the allocation cannot be fulfilled using lookaside.
  25758. */
  25759. static SQLITE_NOINLINE void *dbMallocRawFinish(sqlite3 *db, u64 n){
  25760. void *p;
  25761. assert( db!=0 );
  25762. p = sqlite3Malloc(n);
  25763. if( !p ) sqlite3OomFault(db);
  25764. sqlite3MemdebugSetType(p,
  25765. (db->lookaside.bDisable==0) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP);
  25766. return p;
  25767. }
  25768. /*
  25769. ** Allocate memory, either lookaside (if possible) or heap.
  25770. ** If the allocation fails, set the mallocFailed flag in
  25771. ** the connection pointer.
  25772. **
  25773. ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
  25774. ** failure on the same database connection) then always return 0.
  25775. ** Hence for a particular database connection, once malloc starts
  25776. ** failing, it fails consistently until mallocFailed is reset.
  25777. ** This is an important assumption. There are many places in the
  25778. ** code that do things like this:
  25779. **
  25780. ** int *a = (int*)sqlite3DbMallocRaw(db, 100);
  25781. ** int *b = (int*)sqlite3DbMallocRaw(db, 200);
  25782. ** if( b ) a[10] = 9;
  25783. **
  25784. ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
  25785. ** that all prior mallocs (ex: "a") worked too.
  25786. **
  25787. ** The sqlite3MallocRawNN() variant guarantees that the "db" parameter is
  25788. ** not a NULL pointer.
  25789. */
  25790. SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, u64 n){
  25791. void *p;
  25792. if( db ) return sqlite3DbMallocRawNN(db, n);
  25793. p = sqlite3Malloc(n);
  25794. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  25795. return p;
  25796. }
  25797. SQLITE_PRIVATE void *sqlite3DbMallocRawNN(sqlite3 *db, u64 n){
  25798. #ifndef SQLITE_OMIT_LOOKASIDE
  25799. LookasideSlot *pBuf;
  25800. assert( db!=0 );
  25801. assert( sqlite3_mutex_held(db->mutex) );
  25802. assert( db->pnBytesFreed==0 );
  25803. if( db->lookaside.bDisable==0 ){
  25804. assert( db->mallocFailed==0 );
  25805. if( n>db->lookaside.sz ){
  25806. db->lookaside.anStat[1]++;
  25807. }else if( (pBuf = db->lookaside.pFree)!=0 ){
  25808. db->lookaside.pFree = pBuf->pNext;
  25809. db->lookaside.anStat[0]++;
  25810. return (void*)pBuf;
  25811. }else if( (pBuf = db->lookaside.pInit)!=0 ){
  25812. db->lookaside.pInit = pBuf->pNext;
  25813. db->lookaside.anStat[0]++;
  25814. return (void*)pBuf;
  25815. }else{
  25816. db->lookaside.anStat[2]++;
  25817. }
  25818. }else if( db->mallocFailed ){
  25819. return 0;
  25820. }
  25821. #else
  25822. assert( db!=0 );
  25823. assert( sqlite3_mutex_held(db->mutex) );
  25824. assert( db->pnBytesFreed==0 );
  25825. if( db->mallocFailed ){
  25826. return 0;
  25827. }
  25828. #endif
  25829. return dbMallocRawFinish(db, n);
  25830. }
  25831. /* Forward declaration */
  25832. static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n);
  25833. /*
  25834. ** Resize the block of memory pointed to by p to n bytes. If the
  25835. ** resize fails, set the mallocFailed flag in the connection object.
  25836. */
  25837. SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, u64 n){
  25838. assert( db!=0 );
  25839. if( p==0 ) return sqlite3DbMallocRawNN(db, n);
  25840. assert( sqlite3_mutex_held(db->mutex) );
  25841. if( isLookaside(db,p) && n<=db->lookaside.sz ) return p;
  25842. return dbReallocFinish(db, p, n);
  25843. }
  25844. static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n){
  25845. void *pNew = 0;
  25846. assert( db!=0 );
  25847. assert( p!=0 );
  25848. if( db->mallocFailed==0 ){
  25849. if( isLookaside(db, p) ){
  25850. pNew = sqlite3DbMallocRawNN(db, n);
  25851. if( pNew ){
  25852. memcpy(pNew, p, db->lookaside.sz);
  25853. sqlite3DbFree(db, p);
  25854. }
  25855. }else{
  25856. assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  25857. assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  25858. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  25859. pNew = sqlite3_realloc64(p, n);
  25860. if( !pNew ){
  25861. sqlite3OomFault(db);
  25862. }
  25863. sqlite3MemdebugSetType(pNew,
  25864. (db->lookaside.bDisable==0 ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
  25865. }
  25866. }
  25867. return pNew;
  25868. }
  25869. /*
  25870. ** Attempt to reallocate p. If the reallocation fails, then free p
  25871. ** and set the mallocFailed flag in the database connection.
  25872. */
  25873. SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, u64 n){
  25874. void *pNew;
  25875. pNew = sqlite3DbRealloc(db, p, n);
  25876. if( !pNew ){
  25877. sqlite3DbFree(db, p);
  25878. }
  25879. return pNew;
  25880. }
  25881. /*
  25882. ** Make a copy of a string in memory obtained from sqliteMalloc(). These
  25883. ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
  25884. ** is because when memory debugging is turned on, these two functions are
  25885. ** called via macros that record the current file and line number in the
  25886. ** ThreadData structure.
  25887. */
  25888. SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
  25889. char *zNew;
  25890. size_t n;
  25891. if( z==0 ){
  25892. return 0;
  25893. }
  25894. n = strlen(z) + 1;
  25895. zNew = sqlite3DbMallocRaw(db, n);
  25896. if( zNew ){
  25897. memcpy(zNew, z, n);
  25898. }
  25899. return zNew;
  25900. }
  25901. SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, u64 n){
  25902. char *zNew;
  25903. assert( db!=0 );
  25904. if( z==0 ){
  25905. return 0;
  25906. }
  25907. assert( (n&0x7fffffff)==n );
  25908. zNew = sqlite3DbMallocRawNN(db, n+1);
  25909. if( zNew ){
  25910. memcpy(zNew, z, (size_t)n);
  25911. zNew[n] = 0;
  25912. }
  25913. return zNew;
  25914. }
  25915. /*
  25916. ** The text between zStart and zEnd represents a phrase within a larger
  25917. ** SQL statement. Make a copy of this phrase in space obtained form
  25918. ** sqlite3DbMalloc(). Omit leading and trailing whitespace.
  25919. */
  25920. SQLITE_PRIVATE char *sqlite3DbSpanDup(sqlite3 *db, const char *zStart, const char *zEnd){
  25921. int n;
  25922. while( sqlite3Isspace(zStart[0]) ) zStart++;
  25923. n = (int)(zEnd - zStart);
  25924. while( ALWAYS(n>0) && sqlite3Isspace(zStart[n-1]) ) n--;
  25925. return sqlite3DbStrNDup(db, zStart, n);
  25926. }
  25927. /*
  25928. ** Free any prior content in *pz and replace it with a copy of zNew.
  25929. */
  25930. SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zNew){
  25931. sqlite3DbFree(db, *pz);
  25932. *pz = sqlite3DbStrDup(db, zNew);
  25933. }
  25934. /*
  25935. ** Call this routine to record the fact that an OOM (out-of-memory) error
  25936. ** has happened. This routine will set db->mallocFailed, and also
  25937. ** temporarily disable the lookaside memory allocator and interrupt
  25938. ** any running VDBEs.
  25939. */
  25940. SQLITE_PRIVATE void sqlite3OomFault(sqlite3 *db){
  25941. if( db->mallocFailed==0 && db->bBenignMalloc==0 ){
  25942. db->mallocFailed = 1;
  25943. if( db->nVdbeExec>0 ){
  25944. db->u1.isInterrupted = 1;
  25945. }
  25946. db->lookaside.bDisable++;
  25947. if( db->pParse ){
  25948. db->pParse->rc = SQLITE_NOMEM_BKPT;
  25949. }
  25950. }
  25951. }
  25952. /*
  25953. ** This routine reactivates the memory allocator and clears the
  25954. ** db->mallocFailed flag as necessary.
  25955. **
  25956. ** The memory allocator is not restarted if there are running
  25957. ** VDBEs.
  25958. */
  25959. SQLITE_PRIVATE void sqlite3OomClear(sqlite3 *db){
  25960. if( db->mallocFailed && db->nVdbeExec==0 ){
  25961. db->mallocFailed = 0;
  25962. db->u1.isInterrupted = 0;
  25963. assert( db->lookaside.bDisable>0 );
  25964. db->lookaside.bDisable--;
  25965. }
  25966. }
  25967. /*
  25968. ** Take actions at the end of an API call to indicate an OOM error
  25969. */
  25970. static SQLITE_NOINLINE int apiOomError(sqlite3 *db){
  25971. sqlite3OomClear(db);
  25972. sqlite3Error(db, SQLITE_NOMEM);
  25973. return SQLITE_NOMEM_BKPT;
  25974. }
  25975. /*
  25976. ** This function must be called before exiting any API function (i.e.
  25977. ** returning control to the user) that has called sqlite3_malloc or
  25978. ** sqlite3_realloc.
  25979. **
  25980. ** The returned value is normally a copy of the second argument to this
  25981. ** function. However, if a malloc() failure has occurred since the previous
  25982. ** invocation SQLITE_NOMEM is returned instead.
  25983. **
  25984. ** If an OOM as occurred, then the connection error-code (the value
  25985. ** returned by sqlite3_errcode()) is set to SQLITE_NOMEM.
  25986. */
  25987. SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
  25988. /* If the db handle must hold the connection handle mutex here.
  25989. ** Otherwise the read (and possible write) of db->mallocFailed
  25990. ** is unsafe, as is the call to sqlite3Error().
  25991. */
  25992. assert( db!=0 );
  25993. assert( sqlite3_mutex_held(db->mutex) );
  25994. if( db->mallocFailed || rc==SQLITE_IOERR_NOMEM ){
  25995. return apiOomError(db);
  25996. }
  25997. return rc & db->errMask;
  25998. }
  25999. /************** End of malloc.c **********************************************/
  26000. /************** Begin file printf.c ******************************************/
  26001. /*
  26002. ** The "printf" code that follows dates from the 1980's. It is in
  26003. ** the public domain.
  26004. **
  26005. **************************************************************************
  26006. **
  26007. ** This file contains code for a set of "printf"-like routines. These
  26008. ** routines format strings much like the printf() from the standard C
  26009. ** library, though the implementation here has enhancements to support
  26010. ** SQLite.
  26011. */
  26012. /* #include "sqliteInt.h" */
  26013. /*
  26014. ** Conversion types fall into various categories as defined by the
  26015. ** following enumeration.
  26016. */
  26017. #define etRADIX 0 /* non-decimal integer types. %x %o */
  26018. #define etFLOAT 1 /* Floating point. %f */
  26019. #define etEXP 2 /* Exponentional notation. %e and %E */
  26020. #define etGENERIC 3 /* Floating or exponential, depending on exponent. %g */
  26021. #define etSIZE 4 /* Return number of characters processed so far. %n */
  26022. #define etSTRING 5 /* Strings. %s */
  26023. #define etDYNSTRING 6 /* Dynamically allocated strings. %z */
  26024. #define etPERCENT 7 /* Percent symbol. %% */
  26025. #define etCHARX 8 /* Characters. %c */
  26026. /* The rest are extensions, not normally found in printf() */
  26027. #define etSQLESCAPE 9 /* Strings with '\'' doubled. %q */
  26028. #define etSQLESCAPE2 10 /* Strings with '\'' doubled and enclosed in '',
  26029. NULL pointers replaced by SQL NULL. %Q */
  26030. #define etTOKEN 11 /* a pointer to a Token structure */
  26031. #define etSRCLIST 12 /* a pointer to a SrcList */
  26032. #define etPOINTER 13 /* The %p conversion */
  26033. #define etSQLESCAPE3 14 /* %w -> Strings with '\"' doubled */
  26034. #define etORDINAL 15 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */
  26035. #define etDECIMAL 16 /* %d or %u, but not %x, %o */
  26036. #define etINVALID 17 /* Any unrecognized conversion type */
  26037. /*
  26038. ** An "etByte" is an 8-bit unsigned value.
  26039. */
  26040. typedef unsigned char etByte;
  26041. /*
  26042. ** Each builtin conversion character (ex: the 'd' in "%d") is described
  26043. ** by an instance of the following structure
  26044. */
  26045. typedef struct et_info { /* Information about each format field */
  26046. char fmttype; /* The format field code letter */
  26047. etByte base; /* The base for radix conversion */
  26048. etByte flags; /* One or more of FLAG_ constants below */
  26049. etByte type; /* Conversion paradigm */
  26050. etByte charset; /* Offset into aDigits[] of the digits string */
  26051. etByte prefix; /* Offset into aPrefix[] of the prefix string */
  26052. } et_info;
  26053. /*
  26054. ** Allowed values for et_info.flags
  26055. */
  26056. #define FLAG_SIGNED 1 /* True if the value to convert is signed */
  26057. #define FLAG_STRING 4 /* Allow infinite precision */
  26058. /*
  26059. ** The following table is searched linearly, so it is good to put the
  26060. ** most frequently used conversion types first.
  26061. */
  26062. static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
  26063. static const char aPrefix[] = "-x0\000X0";
  26064. static const et_info fmtinfo[] = {
  26065. { 'd', 10, 1, etDECIMAL, 0, 0 },
  26066. { 's', 0, 4, etSTRING, 0, 0 },
  26067. { 'g', 0, 1, etGENERIC, 30, 0 },
  26068. { 'z', 0, 4, etDYNSTRING, 0, 0 },
  26069. { 'q', 0, 4, etSQLESCAPE, 0, 0 },
  26070. { 'Q', 0, 4, etSQLESCAPE2, 0, 0 },
  26071. { 'w', 0, 4, etSQLESCAPE3, 0, 0 },
  26072. { 'c', 0, 0, etCHARX, 0, 0 },
  26073. { 'o', 8, 0, etRADIX, 0, 2 },
  26074. { 'u', 10, 0, etDECIMAL, 0, 0 },
  26075. { 'x', 16, 0, etRADIX, 16, 1 },
  26076. { 'X', 16, 0, etRADIX, 0, 4 },
  26077. #ifndef SQLITE_OMIT_FLOATING_POINT
  26078. { 'f', 0, 1, etFLOAT, 0, 0 },
  26079. { 'e', 0, 1, etEXP, 30, 0 },
  26080. { 'E', 0, 1, etEXP, 14, 0 },
  26081. { 'G', 0, 1, etGENERIC, 14, 0 },
  26082. #endif
  26083. { 'i', 10, 1, etDECIMAL, 0, 0 },
  26084. { 'n', 0, 0, etSIZE, 0, 0 },
  26085. { '%', 0, 0, etPERCENT, 0, 0 },
  26086. { 'p', 16, 0, etPOINTER, 0, 1 },
  26087. /* All the rest are undocumented and are for internal use only */
  26088. { 'T', 0, 0, etTOKEN, 0, 0 },
  26089. { 'S', 0, 0, etSRCLIST, 0, 0 },
  26090. { 'r', 10, 1, etORDINAL, 0, 0 },
  26091. };
  26092. /* Floating point constants used for rounding */
  26093. static const double arRound[] = {
  26094. 5.0e-01, 5.0e-02, 5.0e-03, 5.0e-04, 5.0e-05,
  26095. 5.0e-06, 5.0e-07, 5.0e-08, 5.0e-09, 5.0e-10,
  26096. };
  26097. /*
  26098. ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
  26099. ** conversions will work.
  26100. */
  26101. #ifndef SQLITE_OMIT_FLOATING_POINT
  26102. /*
  26103. ** "*val" is a double such that 0.1 <= *val < 10.0
  26104. ** Return the ascii code for the leading digit of *val, then
  26105. ** multiply "*val" by 10.0 to renormalize.
  26106. **
  26107. ** Example:
  26108. ** input: *val = 3.14159
  26109. ** output: *val = 1.4159 function return = '3'
  26110. **
  26111. ** The counter *cnt is incremented each time. After counter exceeds
  26112. ** 16 (the number of significant digits in a 64-bit float) '0' is
  26113. ** always returned.
  26114. */
  26115. static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
  26116. int digit;
  26117. LONGDOUBLE_TYPE d;
  26118. if( (*cnt)<=0 ) return '0';
  26119. (*cnt)--;
  26120. digit = (int)*val;
  26121. d = digit;
  26122. digit += '0';
  26123. *val = (*val - d)*10.0;
  26124. return (char)digit;
  26125. }
  26126. #endif /* SQLITE_OMIT_FLOATING_POINT */
  26127. /*
  26128. ** Set the StrAccum object to an error mode.
  26129. */
  26130. static void setStrAccumError(StrAccum *p, u8 eError){
  26131. assert( eError==SQLITE_NOMEM || eError==SQLITE_TOOBIG );
  26132. p->accError = eError;
  26133. if( p->mxAlloc ) sqlite3_str_reset(p);
  26134. if( eError==SQLITE_TOOBIG ) sqlite3ErrorToParser(p->db, eError);
  26135. }
  26136. /*
  26137. ** Extra argument values from a PrintfArguments object
  26138. */
  26139. static sqlite3_int64 getIntArg(PrintfArguments *p){
  26140. if( p->nArg<=p->nUsed ) return 0;
  26141. return sqlite3_value_int64(p->apArg[p->nUsed++]);
  26142. }
  26143. static double getDoubleArg(PrintfArguments *p){
  26144. if( p->nArg<=p->nUsed ) return 0.0;
  26145. return sqlite3_value_double(p->apArg[p->nUsed++]);
  26146. }
  26147. static char *getTextArg(PrintfArguments *p){
  26148. if( p->nArg<=p->nUsed ) return 0;
  26149. return (char*)sqlite3_value_text(p->apArg[p->nUsed++]);
  26150. }
  26151. /*
  26152. ** Allocate memory for a temporary buffer needed for printf rendering.
  26153. **
  26154. ** If the requested size of the temp buffer is larger than the size
  26155. ** of the output buffer in pAccum, then cause an SQLITE_TOOBIG error.
  26156. ** Do the size check before the memory allocation to prevent rogue
  26157. ** SQL from requesting large allocations using the precision or width
  26158. ** field of the printf() function.
  26159. */
  26160. static char *printfTempBuf(sqlite3_str *pAccum, sqlite3_int64 n){
  26161. char *z;
  26162. if( pAccum->accError ) return 0;
  26163. if( n>pAccum->nAlloc && n>pAccum->mxAlloc ){
  26164. setStrAccumError(pAccum, SQLITE_TOOBIG);
  26165. return 0;
  26166. }
  26167. z = sqlite3DbMallocRaw(pAccum->db, n);
  26168. if( z==0 ){
  26169. setStrAccumError(pAccum, SQLITE_NOMEM);
  26170. }
  26171. return z;
  26172. }
  26173. /*
  26174. ** On machines with a small stack size, you can redefine the
  26175. ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
  26176. */
  26177. #ifndef SQLITE_PRINT_BUF_SIZE
  26178. # define SQLITE_PRINT_BUF_SIZE 70
  26179. #endif
  26180. #define etBUFSIZE SQLITE_PRINT_BUF_SIZE /* Size of the output buffer */
  26181. /*
  26182. ** Render a string given by "fmt" into the StrAccum object.
  26183. */
  26184. SQLITE_API void sqlite3_str_vappendf(
  26185. sqlite3_str *pAccum, /* Accumulate results here */
  26186. const char *fmt, /* Format string */
  26187. va_list ap /* arguments */
  26188. ){
  26189. int c; /* Next character in the format string */
  26190. char *bufpt; /* Pointer to the conversion buffer */
  26191. int precision; /* Precision of the current field */
  26192. int length; /* Length of the field */
  26193. int idx; /* A general purpose loop counter */
  26194. int width; /* Width of the current field */
  26195. etByte flag_leftjustify; /* True if "-" flag is present */
  26196. etByte flag_prefix; /* '+' or ' ' or 0 for prefix */
  26197. etByte flag_alternateform; /* True if "#" flag is present */
  26198. etByte flag_altform2; /* True if "!" flag is present */
  26199. etByte flag_zeropad; /* True if field width constant starts with zero */
  26200. etByte flag_long; /* 1 for the "l" flag, 2 for "ll", 0 by default */
  26201. etByte done; /* Loop termination flag */
  26202. etByte cThousand; /* Thousands separator for %d and %u */
  26203. etByte xtype = etINVALID; /* Conversion paradigm */
  26204. u8 bArgList; /* True for SQLITE_PRINTF_SQLFUNC */
  26205. char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */
  26206. sqlite_uint64 longvalue; /* Value for integer types */
  26207. LONGDOUBLE_TYPE realvalue; /* Value for real types */
  26208. const et_info *infop; /* Pointer to the appropriate info structure */
  26209. char *zOut; /* Rendering buffer */
  26210. int nOut; /* Size of the rendering buffer */
  26211. char *zExtra = 0; /* Malloced memory used by some conversion */
  26212. #ifndef SQLITE_OMIT_FLOATING_POINT
  26213. int exp, e2; /* exponent of real numbers */
  26214. int nsd; /* Number of significant digits returned */
  26215. double rounder; /* Used for rounding floating point values */
  26216. etByte flag_dp; /* True if decimal point should be shown */
  26217. etByte flag_rtz; /* True if trailing zeros should be removed */
  26218. #endif
  26219. PrintfArguments *pArgList = 0; /* Arguments for SQLITE_PRINTF_SQLFUNC */
  26220. char buf[etBUFSIZE]; /* Conversion buffer */
  26221. /* pAccum never starts out with an empty buffer that was obtained from
  26222. ** malloc(). This precondition is required by the mprintf("%z...")
  26223. ** optimization. */
  26224. assert( pAccum->nChar>0 || (pAccum->printfFlags&SQLITE_PRINTF_MALLOCED)==0 );
  26225. bufpt = 0;
  26226. if( (pAccum->printfFlags & SQLITE_PRINTF_SQLFUNC)!=0 ){
  26227. pArgList = va_arg(ap, PrintfArguments*);
  26228. bArgList = 1;
  26229. }else{
  26230. bArgList = 0;
  26231. }
  26232. for(; (c=(*fmt))!=0; ++fmt){
  26233. if( c!='%' ){
  26234. bufpt = (char *)fmt;
  26235. #if HAVE_STRCHRNUL
  26236. fmt = strchrnul(fmt, '%');
  26237. #else
  26238. do{ fmt++; }while( *fmt && *fmt != '%' );
  26239. #endif
  26240. sqlite3_str_append(pAccum, bufpt, (int)(fmt - bufpt));
  26241. if( *fmt==0 ) break;
  26242. }
  26243. if( (c=(*++fmt))==0 ){
  26244. sqlite3_str_append(pAccum, "%", 1);
  26245. break;
  26246. }
  26247. /* Find out what flags are present */
  26248. flag_leftjustify = flag_prefix = cThousand =
  26249. flag_alternateform = flag_altform2 = flag_zeropad = 0;
  26250. done = 0;
  26251. width = 0;
  26252. flag_long = 0;
  26253. precision = -1;
  26254. do{
  26255. switch( c ){
  26256. case '-': flag_leftjustify = 1; break;
  26257. case '+': flag_prefix = '+'; break;
  26258. case ' ': flag_prefix = ' '; break;
  26259. case '#': flag_alternateform = 1; break;
  26260. case '!': flag_altform2 = 1; break;
  26261. case '0': flag_zeropad = 1; break;
  26262. case ',': cThousand = ','; break;
  26263. default: done = 1; break;
  26264. case 'l': {
  26265. flag_long = 1;
  26266. c = *++fmt;
  26267. if( c=='l' ){
  26268. c = *++fmt;
  26269. flag_long = 2;
  26270. }
  26271. done = 1;
  26272. break;
  26273. }
  26274. case '1': case '2': case '3': case '4': case '5':
  26275. case '6': case '7': case '8': case '9': {
  26276. unsigned wx = c - '0';
  26277. while( (c = *++fmt)>='0' && c<='9' ){
  26278. wx = wx*10 + c - '0';
  26279. }
  26280. testcase( wx>0x7fffffff );
  26281. width = wx & 0x7fffffff;
  26282. #ifdef SQLITE_PRINTF_PRECISION_LIMIT
  26283. if( width>SQLITE_PRINTF_PRECISION_LIMIT ){
  26284. width = SQLITE_PRINTF_PRECISION_LIMIT;
  26285. }
  26286. #endif
  26287. if( c!='.' && c!='l' ){
  26288. done = 1;
  26289. }else{
  26290. fmt--;
  26291. }
  26292. break;
  26293. }
  26294. case '*': {
  26295. if( bArgList ){
  26296. width = (int)getIntArg(pArgList);
  26297. }else{
  26298. width = va_arg(ap,int);
  26299. }
  26300. if( width<0 ){
  26301. flag_leftjustify = 1;
  26302. width = width >= -2147483647 ? -width : 0;
  26303. }
  26304. #ifdef SQLITE_PRINTF_PRECISION_LIMIT
  26305. if( width>SQLITE_PRINTF_PRECISION_LIMIT ){
  26306. width = SQLITE_PRINTF_PRECISION_LIMIT;
  26307. }
  26308. #endif
  26309. if( (c = fmt[1])!='.' && c!='l' ){
  26310. c = *++fmt;
  26311. done = 1;
  26312. }
  26313. break;
  26314. }
  26315. case '.': {
  26316. c = *++fmt;
  26317. if( c=='*' ){
  26318. if( bArgList ){
  26319. precision = (int)getIntArg(pArgList);
  26320. }else{
  26321. precision = va_arg(ap,int);
  26322. }
  26323. if( precision<0 ){
  26324. precision = precision >= -2147483647 ? -precision : -1;
  26325. }
  26326. c = *++fmt;
  26327. }else{
  26328. unsigned px = 0;
  26329. while( c>='0' && c<='9' ){
  26330. px = px*10 + c - '0';
  26331. c = *++fmt;
  26332. }
  26333. testcase( px>0x7fffffff );
  26334. precision = px & 0x7fffffff;
  26335. }
  26336. #ifdef SQLITE_PRINTF_PRECISION_LIMIT
  26337. if( precision>SQLITE_PRINTF_PRECISION_LIMIT ){
  26338. precision = SQLITE_PRINTF_PRECISION_LIMIT;
  26339. }
  26340. #endif
  26341. if( c=='l' ){
  26342. --fmt;
  26343. }else{
  26344. done = 1;
  26345. }
  26346. break;
  26347. }
  26348. }
  26349. }while( !done && (c=(*++fmt))!=0 );
  26350. /* Fetch the info entry for the field */
  26351. infop = &fmtinfo[0];
  26352. xtype = etINVALID;
  26353. for(idx=0; idx<ArraySize(fmtinfo); idx++){
  26354. if( c==fmtinfo[idx].fmttype ){
  26355. infop = &fmtinfo[idx];
  26356. xtype = infop->type;
  26357. break;
  26358. }
  26359. }
  26360. /*
  26361. ** At this point, variables are initialized as follows:
  26362. **
  26363. ** flag_alternateform TRUE if a '#' is present.
  26364. ** flag_altform2 TRUE if a '!' is present.
  26365. ** flag_prefix '+' or ' ' or zero
  26366. ** flag_leftjustify TRUE if a '-' is present or if the
  26367. ** field width was negative.
  26368. ** flag_zeropad TRUE if the width began with 0.
  26369. ** flag_long 1 for "l", 2 for "ll"
  26370. ** width The specified field width. This is
  26371. ** always non-negative. Zero is the default.
  26372. ** precision The specified precision. The default
  26373. ** is -1.
  26374. ** xtype The class of the conversion.
  26375. ** infop Pointer to the appropriate info struct.
  26376. */
  26377. switch( xtype ){
  26378. case etPOINTER:
  26379. flag_long = sizeof(char*)==sizeof(i64) ? 2 :
  26380. sizeof(char*)==sizeof(long int) ? 1 : 0;
  26381. /* Fall through into the next case */
  26382. case etORDINAL:
  26383. case etRADIX:
  26384. cThousand = 0;
  26385. /* Fall through into the next case */
  26386. case etDECIMAL:
  26387. if( infop->flags & FLAG_SIGNED ){
  26388. i64 v;
  26389. if( bArgList ){
  26390. v = getIntArg(pArgList);
  26391. }else if( flag_long ){
  26392. if( flag_long==2 ){
  26393. v = va_arg(ap,i64) ;
  26394. }else{
  26395. v = va_arg(ap,long int);
  26396. }
  26397. }else{
  26398. v = va_arg(ap,int);
  26399. }
  26400. if( v<0 ){
  26401. if( v==SMALLEST_INT64 ){
  26402. longvalue = ((u64)1)<<63;
  26403. }else{
  26404. longvalue = -v;
  26405. }
  26406. prefix = '-';
  26407. }else{
  26408. longvalue = v;
  26409. prefix = flag_prefix;
  26410. }
  26411. }else{
  26412. if( bArgList ){
  26413. longvalue = (u64)getIntArg(pArgList);
  26414. }else if( flag_long ){
  26415. if( flag_long==2 ){
  26416. longvalue = va_arg(ap,u64);
  26417. }else{
  26418. longvalue = va_arg(ap,unsigned long int);
  26419. }
  26420. }else{
  26421. longvalue = va_arg(ap,unsigned int);
  26422. }
  26423. prefix = 0;
  26424. }
  26425. if( longvalue==0 ) flag_alternateform = 0;
  26426. if( flag_zeropad && precision<width-(prefix!=0) ){
  26427. precision = width-(prefix!=0);
  26428. }
  26429. if( precision<etBUFSIZE-10-etBUFSIZE/3 ){
  26430. nOut = etBUFSIZE;
  26431. zOut = buf;
  26432. }else{
  26433. u64 n;
  26434. n = (u64)precision + 10;
  26435. if( cThousand ) n += precision/3;
  26436. zOut = zExtra = printfTempBuf(pAccum, n);
  26437. if( zOut==0 ) return;
  26438. nOut = (int)n;
  26439. }
  26440. bufpt = &zOut[nOut-1];
  26441. if( xtype==etORDINAL ){
  26442. static const char zOrd[] = "thstndrd";
  26443. int x = (int)(longvalue % 10);
  26444. if( x>=4 || (longvalue/10)%10==1 ){
  26445. x = 0;
  26446. }
  26447. *(--bufpt) = zOrd[x*2+1];
  26448. *(--bufpt) = zOrd[x*2];
  26449. }
  26450. {
  26451. const char *cset = &aDigits[infop->charset];
  26452. u8 base = infop->base;
  26453. do{ /* Convert to ascii */
  26454. *(--bufpt) = cset[longvalue%base];
  26455. longvalue = longvalue/base;
  26456. }while( longvalue>0 );
  26457. }
  26458. length = (int)(&zOut[nOut-1]-bufpt);
  26459. while( precision>length ){
  26460. *(--bufpt) = '0'; /* Zero pad */
  26461. length++;
  26462. }
  26463. if( cThousand ){
  26464. int nn = (length - 1)/3; /* Number of "," to insert */
  26465. int ix = (length - 1)%3 + 1;
  26466. bufpt -= nn;
  26467. for(idx=0; nn>0; idx++){
  26468. bufpt[idx] = bufpt[idx+nn];
  26469. ix--;
  26470. if( ix==0 ){
  26471. bufpt[++idx] = cThousand;
  26472. nn--;
  26473. ix = 3;
  26474. }
  26475. }
  26476. }
  26477. if( prefix ) *(--bufpt) = prefix; /* Add sign */
  26478. if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */
  26479. const char *pre;
  26480. char x;
  26481. pre = &aPrefix[infop->prefix];
  26482. for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
  26483. }
  26484. length = (int)(&zOut[nOut-1]-bufpt);
  26485. break;
  26486. case etFLOAT:
  26487. case etEXP:
  26488. case etGENERIC:
  26489. if( bArgList ){
  26490. realvalue = getDoubleArg(pArgList);
  26491. }else{
  26492. realvalue = va_arg(ap,double);
  26493. }
  26494. #ifdef SQLITE_OMIT_FLOATING_POINT
  26495. length = 0;
  26496. #else
  26497. if( precision<0 ) precision = 6; /* Set default precision */
  26498. if( realvalue<0.0 ){
  26499. realvalue = -realvalue;
  26500. prefix = '-';
  26501. }else{
  26502. prefix = flag_prefix;
  26503. }
  26504. if( xtype==etGENERIC && precision>0 ) precision--;
  26505. testcase( precision>0xfff );
  26506. idx = precision & 0xfff;
  26507. rounder = arRound[idx%10];
  26508. while( idx>=10 ){ rounder *= 1.0e-10; idx -= 10; }
  26509. if( xtype==etFLOAT ){
  26510. double rx = (double)realvalue;
  26511. sqlite3_uint64 u;
  26512. int ex;
  26513. memcpy(&u, &rx, sizeof(u));
  26514. ex = -1023 + (int)((u>>52)&0x7ff);
  26515. if( precision+(ex/3) < 15 ) rounder += realvalue*3e-16;
  26516. realvalue += rounder;
  26517. }
  26518. /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
  26519. exp = 0;
  26520. if( sqlite3IsNaN((double)realvalue) ){
  26521. bufpt = "NaN";
  26522. length = 3;
  26523. break;
  26524. }
  26525. if( realvalue>0.0 ){
  26526. LONGDOUBLE_TYPE scale = 1.0;
  26527. while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
  26528. while( realvalue>=1e10*scale && exp<=350 ){ scale *= 1e10; exp+=10; }
  26529. while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
  26530. realvalue /= scale;
  26531. while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
  26532. while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
  26533. if( exp>350 ){
  26534. bufpt = buf;
  26535. buf[0] = prefix;
  26536. memcpy(buf+(prefix!=0),"Inf",4);
  26537. length = 3+(prefix!=0);
  26538. break;
  26539. }
  26540. }
  26541. bufpt = buf;
  26542. /*
  26543. ** If the field type is etGENERIC, then convert to either etEXP
  26544. ** or etFLOAT, as appropriate.
  26545. */
  26546. if( xtype!=etFLOAT ){
  26547. realvalue += rounder;
  26548. if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
  26549. }
  26550. if( xtype==etGENERIC ){
  26551. flag_rtz = !flag_alternateform;
  26552. if( exp<-4 || exp>precision ){
  26553. xtype = etEXP;
  26554. }else{
  26555. precision = precision - exp;
  26556. xtype = etFLOAT;
  26557. }
  26558. }else{
  26559. flag_rtz = flag_altform2;
  26560. }
  26561. if( xtype==etEXP ){
  26562. e2 = 0;
  26563. }else{
  26564. e2 = exp;
  26565. }
  26566. {
  26567. i64 szBufNeeded; /* Size of a temporary buffer needed */
  26568. szBufNeeded = MAX(e2,0)+(i64)precision+(i64)width+15;
  26569. if( szBufNeeded > etBUFSIZE ){
  26570. bufpt = zExtra = printfTempBuf(pAccum, szBufNeeded);
  26571. if( bufpt==0 ) return;
  26572. }
  26573. }
  26574. zOut = bufpt;
  26575. nsd = 16 + flag_altform2*10;
  26576. flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
  26577. /* The sign in front of the number */
  26578. if( prefix ){
  26579. *(bufpt++) = prefix;
  26580. }
  26581. /* Digits prior to the decimal point */
  26582. if( e2<0 ){
  26583. *(bufpt++) = '0';
  26584. }else{
  26585. for(; e2>=0; e2--){
  26586. *(bufpt++) = et_getdigit(&realvalue,&nsd);
  26587. }
  26588. }
  26589. /* The decimal point */
  26590. if( flag_dp ){
  26591. *(bufpt++) = '.';
  26592. }
  26593. /* "0" digits after the decimal point but before the first
  26594. ** significant digit of the number */
  26595. for(e2++; e2<0; precision--, e2++){
  26596. assert( precision>0 );
  26597. *(bufpt++) = '0';
  26598. }
  26599. /* Significant digits after the decimal point */
  26600. while( (precision--)>0 ){
  26601. *(bufpt++) = et_getdigit(&realvalue,&nsd);
  26602. }
  26603. /* Remove trailing zeros and the "." if no digits follow the "." */
  26604. if( flag_rtz && flag_dp ){
  26605. while( bufpt[-1]=='0' ) *(--bufpt) = 0;
  26606. assert( bufpt>zOut );
  26607. if( bufpt[-1]=='.' ){
  26608. if( flag_altform2 ){
  26609. *(bufpt++) = '0';
  26610. }else{
  26611. *(--bufpt) = 0;
  26612. }
  26613. }
  26614. }
  26615. /* Add the "eNNN" suffix */
  26616. if( xtype==etEXP ){
  26617. *(bufpt++) = aDigits[infop->charset];
  26618. if( exp<0 ){
  26619. *(bufpt++) = '-'; exp = -exp;
  26620. }else{
  26621. *(bufpt++) = '+';
  26622. }
  26623. if( exp>=100 ){
  26624. *(bufpt++) = (char)((exp/100)+'0'); /* 100's digit */
  26625. exp %= 100;
  26626. }
  26627. *(bufpt++) = (char)(exp/10+'0'); /* 10's digit */
  26628. *(bufpt++) = (char)(exp%10+'0'); /* 1's digit */
  26629. }
  26630. *bufpt = 0;
  26631. /* The converted number is in buf[] and zero terminated. Output it.
  26632. ** Note that the number is in the usual order, not reversed as with
  26633. ** integer conversions. */
  26634. length = (int)(bufpt-zOut);
  26635. bufpt = zOut;
  26636. /* Special case: Add leading zeros if the flag_zeropad flag is
  26637. ** set and we are not left justified */
  26638. if( flag_zeropad && !flag_leftjustify && length < width){
  26639. int i;
  26640. int nPad = width - length;
  26641. for(i=width; i>=nPad; i--){
  26642. bufpt[i] = bufpt[i-nPad];
  26643. }
  26644. i = prefix!=0;
  26645. while( nPad-- ) bufpt[i++] = '0';
  26646. length = width;
  26647. }
  26648. #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
  26649. break;
  26650. case etSIZE:
  26651. if( !bArgList ){
  26652. *(va_arg(ap,int*)) = pAccum->nChar;
  26653. }
  26654. length = width = 0;
  26655. break;
  26656. case etPERCENT:
  26657. buf[0] = '%';
  26658. bufpt = buf;
  26659. length = 1;
  26660. break;
  26661. case etCHARX:
  26662. if( bArgList ){
  26663. bufpt = getTextArg(pArgList);
  26664. length = 1;
  26665. if( bufpt ){
  26666. buf[0] = c = *(bufpt++);
  26667. if( (c&0xc0)==0xc0 ){
  26668. while( length<4 && (bufpt[0]&0xc0)==0x80 ){
  26669. buf[length++] = *(bufpt++);
  26670. }
  26671. }
  26672. }else{
  26673. buf[0] = 0;
  26674. }
  26675. }else{
  26676. unsigned int ch = va_arg(ap,unsigned int);
  26677. if( ch<0x00080 ){
  26678. buf[0] = ch & 0xff;
  26679. length = 1;
  26680. }else if( ch<0x00800 ){
  26681. buf[0] = 0xc0 + (u8)((ch>>6)&0x1f);
  26682. buf[1] = 0x80 + (u8)(ch & 0x3f);
  26683. length = 2;
  26684. }else if( ch<0x10000 ){
  26685. buf[0] = 0xe0 + (u8)((ch>>12)&0x0f);
  26686. buf[1] = 0x80 + (u8)((ch>>6) & 0x3f);
  26687. buf[2] = 0x80 + (u8)(ch & 0x3f);
  26688. length = 3;
  26689. }else{
  26690. buf[0] = 0xf0 + (u8)((ch>>18) & 0x07);
  26691. buf[1] = 0x80 + (u8)((ch>>12) & 0x3f);
  26692. buf[2] = 0x80 + (u8)((ch>>6) & 0x3f);
  26693. buf[3] = 0x80 + (u8)(ch & 0x3f);
  26694. length = 4;
  26695. }
  26696. }
  26697. if( precision>1 ){
  26698. width -= precision-1;
  26699. if( width>1 && !flag_leftjustify ){
  26700. sqlite3_str_appendchar(pAccum, width-1, ' ');
  26701. width = 0;
  26702. }
  26703. while( precision-- > 1 ){
  26704. sqlite3_str_append(pAccum, buf, length);
  26705. }
  26706. }
  26707. bufpt = buf;
  26708. flag_altform2 = 1;
  26709. goto adjust_width_for_utf8;
  26710. case etSTRING:
  26711. case etDYNSTRING:
  26712. if( bArgList ){
  26713. bufpt = getTextArg(pArgList);
  26714. xtype = etSTRING;
  26715. }else{
  26716. bufpt = va_arg(ap,char*);
  26717. }
  26718. if( bufpt==0 ){
  26719. bufpt = "";
  26720. }else if( xtype==etDYNSTRING ){
  26721. if( pAccum->nChar==0
  26722. && pAccum->mxAlloc
  26723. && width==0
  26724. && precision<0
  26725. && pAccum->accError==0
  26726. ){
  26727. /* Special optimization for sqlite3_mprintf("%z..."):
  26728. ** Extend an existing memory allocation rather than creating
  26729. ** a new one. */
  26730. assert( (pAccum->printfFlags&SQLITE_PRINTF_MALLOCED)==0 );
  26731. pAccum->zText = bufpt;
  26732. pAccum->nAlloc = sqlite3DbMallocSize(pAccum->db, bufpt);
  26733. pAccum->nChar = 0x7fffffff & (int)strlen(bufpt);
  26734. pAccum->printfFlags |= SQLITE_PRINTF_MALLOCED;
  26735. length = 0;
  26736. break;
  26737. }
  26738. zExtra = bufpt;
  26739. }
  26740. if( precision>=0 ){
  26741. if( flag_altform2 ){
  26742. /* Set length to the number of bytes needed in order to display
  26743. ** precision characters */
  26744. unsigned char *z = (unsigned char*)bufpt;
  26745. while( precision-- > 0 && z[0] ){
  26746. SQLITE_SKIP_UTF8(z);
  26747. }
  26748. length = (int)(z - (unsigned char*)bufpt);
  26749. }else{
  26750. for(length=0; length<precision && bufpt[length]; length++){}
  26751. }
  26752. }else{
  26753. length = 0x7fffffff & (int)strlen(bufpt);
  26754. }
  26755. adjust_width_for_utf8:
  26756. if( flag_altform2 && width>0 ){
  26757. /* Adjust width to account for extra bytes in UTF-8 characters */
  26758. int ii = length - 1;
  26759. while( ii>=0 ) if( (bufpt[ii--] & 0xc0)==0x80 ) width++;
  26760. }
  26761. break;
  26762. case etSQLESCAPE: /* %q: Escape ' characters */
  26763. case etSQLESCAPE2: /* %Q: Escape ' and enclose in '...' */
  26764. case etSQLESCAPE3: { /* %w: Escape " characters */
  26765. int i, j, k, n, isnull;
  26766. int needQuote;
  26767. char ch;
  26768. char q = ((xtype==etSQLESCAPE3)?'"':'\''); /* Quote character */
  26769. char *escarg;
  26770. if( bArgList ){
  26771. escarg = getTextArg(pArgList);
  26772. }else{
  26773. escarg = va_arg(ap,char*);
  26774. }
  26775. isnull = escarg==0;
  26776. if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
  26777. /* For %q, %Q, and %w, the precision is the number of byte (or
  26778. ** characters if the ! flags is present) to use from the input.
  26779. ** Because of the extra quoting characters inserted, the number
  26780. ** of output characters may be larger than the precision.
  26781. */
  26782. k = precision;
  26783. for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
  26784. if( ch==q ) n++;
  26785. if( flag_altform2 && (ch&0xc0)==0xc0 ){
  26786. while( (escarg[i+1]&0xc0)==0x80 ){ i++; }
  26787. }
  26788. }
  26789. needQuote = !isnull && xtype==etSQLESCAPE2;
  26790. n += i + 3;
  26791. if( n>etBUFSIZE ){
  26792. bufpt = zExtra = printfTempBuf(pAccum, n);
  26793. if( bufpt==0 ) return;
  26794. }else{
  26795. bufpt = buf;
  26796. }
  26797. j = 0;
  26798. if( needQuote ) bufpt[j++] = q;
  26799. k = i;
  26800. for(i=0; i<k; i++){
  26801. bufpt[j++] = ch = escarg[i];
  26802. if( ch==q ) bufpt[j++] = ch;
  26803. }
  26804. if( needQuote ) bufpt[j++] = q;
  26805. bufpt[j] = 0;
  26806. length = j;
  26807. goto adjust_width_for_utf8;
  26808. }
  26809. case etTOKEN: {
  26810. Token *pToken;
  26811. if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;
  26812. pToken = va_arg(ap, Token*);
  26813. assert( bArgList==0 );
  26814. if( pToken && pToken->n ){
  26815. sqlite3_str_append(pAccum, (const char*)pToken->z, pToken->n);
  26816. }
  26817. length = width = 0;
  26818. break;
  26819. }
  26820. case etSRCLIST: {
  26821. SrcList *pSrc;
  26822. int k;
  26823. struct SrcList_item *pItem;
  26824. if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;
  26825. pSrc = va_arg(ap, SrcList*);
  26826. k = va_arg(ap, int);
  26827. pItem = &pSrc->a[k];
  26828. assert( bArgList==0 );
  26829. assert( k>=0 && k<pSrc->nSrc );
  26830. if( pItem->zDatabase ){
  26831. sqlite3_str_appendall(pAccum, pItem->zDatabase);
  26832. sqlite3_str_append(pAccum, ".", 1);
  26833. }
  26834. sqlite3_str_appendall(pAccum, pItem->zName);
  26835. length = width = 0;
  26836. break;
  26837. }
  26838. default: {
  26839. assert( xtype==etINVALID );
  26840. return;
  26841. }
  26842. }/* End switch over the format type */
  26843. /*
  26844. ** The text of the conversion is pointed to by "bufpt" and is
  26845. ** "length" characters long. The field width is "width". Do
  26846. ** the output. Both length and width are in bytes, not characters,
  26847. ** at this point. If the "!" flag was present on string conversions
  26848. ** indicating that width and precision should be expressed in characters,
  26849. ** then the values have been translated prior to reaching this point.
  26850. */
  26851. width -= length;
  26852. if( width>0 ){
  26853. if( !flag_leftjustify ) sqlite3_str_appendchar(pAccum, width, ' ');
  26854. sqlite3_str_append(pAccum, bufpt, length);
  26855. if( flag_leftjustify ) sqlite3_str_appendchar(pAccum, width, ' ');
  26856. }else{
  26857. sqlite3_str_append(pAccum, bufpt, length);
  26858. }
  26859. if( zExtra ){
  26860. sqlite3DbFree(pAccum->db, zExtra);
  26861. zExtra = 0;
  26862. }
  26863. }/* End for loop over the format string */
  26864. } /* End of function */
  26865. /*
  26866. ** Enlarge the memory allocation on a StrAccum object so that it is
  26867. ** able to accept at least N more bytes of text.
  26868. **
  26869. ** Return the number of bytes of text that StrAccum is able to accept
  26870. ** after the attempted enlargement. The value returned might be zero.
  26871. */
  26872. static int sqlite3StrAccumEnlarge(StrAccum *p, int N){
  26873. char *zNew;
  26874. assert( p->nChar+(i64)N >= p->nAlloc ); /* Only called if really needed */
  26875. if( p->accError ){
  26876. testcase(p->accError==SQLITE_TOOBIG);
  26877. testcase(p->accError==SQLITE_NOMEM);
  26878. return 0;
  26879. }
  26880. if( p->mxAlloc==0 ){
  26881. setStrAccumError(p, SQLITE_TOOBIG);
  26882. return p->nAlloc - p->nChar - 1;
  26883. }else{
  26884. char *zOld = isMalloced(p) ? p->zText : 0;
  26885. i64 szNew = p->nChar;
  26886. szNew += N + 1;
  26887. if( szNew+p->nChar<=p->mxAlloc ){
  26888. /* Force exponential buffer size growth as long as it does not overflow,
  26889. ** to avoid having to call this routine too often */
  26890. szNew += p->nChar;
  26891. }
  26892. if( szNew > p->mxAlloc ){
  26893. sqlite3_str_reset(p);
  26894. setStrAccumError(p, SQLITE_TOOBIG);
  26895. return 0;
  26896. }else{
  26897. p->nAlloc = (int)szNew;
  26898. }
  26899. if( p->db ){
  26900. zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
  26901. }else{
  26902. zNew = sqlite3_realloc64(zOld, p->nAlloc);
  26903. }
  26904. if( zNew ){
  26905. assert( p->zText!=0 || p->nChar==0 );
  26906. if( !isMalloced(p) && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
  26907. p->zText = zNew;
  26908. p->nAlloc = sqlite3DbMallocSize(p->db, zNew);
  26909. p->printfFlags |= SQLITE_PRINTF_MALLOCED;
  26910. }else{
  26911. sqlite3_str_reset(p);
  26912. setStrAccumError(p, SQLITE_NOMEM);
  26913. return 0;
  26914. }
  26915. }
  26916. return N;
  26917. }
  26918. /*
  26919. ** Append N copies of character c to the given string buffer.
  26920. */
  26921. SQLITE_API void sqlite3_str_appendchar(sqlite3_str *p, int N, char c){
  26922. testcase( p->nChar + (i64)N > 0x7fffffff );
  26923. if( p->nChar+(i64)N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ){
  26924. return;
  26925. }
  26926. while( (N--)>0 ) p->zText[p->nChar++] = c;
  26927. }
  26928. /*
  26929. ** The StrAccum "p" is not large enough to accept N new bytes of z[].
  26930. ** So enlarge if first, then do the append.
  26931. **
  26932. ** This is a helper routine to sqlite3_str_append() that does special-case
  26933. ** work (enlarging the buffer) using tail recursion, so that the
  26934. ** sqlite3_str_append() routine can use fast calling semantics.
  26935. */
  26936. static void SQLITE_NOINLINE enlargeAndAppend(StrAccum *p, const char *z, int N){
  26937. N = sqlite3StrAccumEnlarge(p, N);
  26938. if( N>0 ){
  26939. memcpy(&p->zText[p->nChar], z, N);
  26940. p->nChar += N;
  26941. }
  26942. }
  26943. /*
  26944. ** Append N bytes of text from z to the StrAccum object. Increase the
  26945. ** size of the memory allocation for StrAccum if necessary.
  26946. */
  26947. SQLITE_API void sqlite3_str_append(sqlite3_str *p, const char *z, int N){
  26948. assert( z!=0 || N==0 );
  26949. assert( p->zText!=0 || p->nChar==0 || p->accError );
  26950. assert( N>=0 );
  26951. assert( p->accError==0 || p->nAlloc==0 || p->mxAlloc==0 );
  26952. if( p->nChar+N >= p->nAlloc ){
  26953. enlargeAndAppend(p,z,N);
  26954. }else if( N ){
  26955. assert( p->zText );
  26956. p->nChar += N;
  26957. memcpy(&p->zText[p->nChar-N], z, N);
  26958. }
  26959. }
  26960. /*
  26961. ** Append the complete text of zero-terminated string z[] to the p string.
  26962. */
  26963. SQLITE_API void sqlite3_str_appendall(sqlite3_str *p, const char *z){
  26964. sqlite3_str_append(p, z, sqlite3Strlen30(z));
  26965. }
  26966. /*
  26967. ** Finish off a string by making sure it is zero-terminated.
  26968. ** Return a pointer to the resulting string. Return a NULL
  26969. ** pointer if any kind of error was encountered.
  26970. */
  26971. static SQLITE_NOINLINE char *strAccumFinishRealloc(StrAccum *p){
  26972. char *zText;
  26973. assert( p->mxAlloc>0 && !isMalloced(p) );
  26974. zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
  26975. if( zText ){
  26976. memcpy(zText, p->zText, p->nChar+1);
  26977. p->printfFlags |= SQLITE_PRINTF_MALLOCED;
  26978. }else{
  26979. setStrAccumError(p, SQLITE_NOMEM);
  26980. }
  26981. p->zText = zText;
  26982. return zText;
  26983. }
  26984. SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
  26985. if( p->zText ){
  26986. p->zText[p->nChar] = 0;
  26987. if( p->mxAlloc>0 && !isMalloced(p) ){
  26988. return strAccumFinishRealloc(p);
  26989. }
  26990. }
  26991. return p->zText;
  26992. }
  26993. /*
  26994. ** This singleton is an sqlite3_str object that is returned if
  26995. ** sqlite3_malloc() fails to provide space for a real one. This
  26996. ** sqlite3_str object accepts no new text and always returns
  26997. ** an SQLITE_NOMEM error.
  26998. */
  26999. static sqlite3_str sqlite3OomStr = {
  27000. 0, 0, 0, 0, 0, SQLITE_NOMEM, 0
  27001. };
  27002. /* Finalize a string created using sqlite3_str_new().
  27003. */
  27004. SQLITE_API char *sqlite3_str_finish(sqlite3_str *p){
  27005. char *z;
  27006. if( p!=0 && p!=&sqlite3OomStr ){
  27007. z = sqlite3StrAccumFinish(p);
  27008. sqlite3_free(p);
  27009. }else{
  27010. z = 0;
  27011. }
  27012. return z;
  27013. }
  27014. /* Return any error code associated with p */
  27015. SQLITE_API int sqlite3_str_errcode(sqlite3_str *p){
  27016. return p ? p->accError : SQLITE_NOMEM;
  27017. }
  27018. /* Return the current length of p in bytes */
  27019. SQLITE_API int sqlite3_str_length(sqlite3_str *p){
  27020. return p ? p->nChar : 0;
  27021. }
  27022. /* Return the current value for p */
  27023. SQLITE_API char *sqlite3_str_value(sqlite3_str *p){
  27024. if( p==0 || p->nChar==0 ) return 0;
  27025. p->zText[p->nChar] = 0;
  27026. return p->zText;
  27027. }
  27028. /*
  27029. ** Reset an StrAccum string. Reclaim all malloced memory.
  27030. */
  27031. SQLITE_API void sqlite3_str_reset(StrAccum *p){
  27032. if( isMalloced(p) ){
  27033. sqlite3DbFree(p->db, p->zText);
  27034. p->printfFlags &= ~SQLITE_PRINTF_MALLOCED;
  27035. }
  27036. p->nAlloc = 0;
  27037. p->nChar = 0;
  27038. p->zText = 0;
  27039. }
  27040. /*
  27041. ** Initialize a string accumulator.
  27042. **
  27043. ** p: The accumulator to be initialized.
  27044. ** db: Pointer to a database connection. May be NULL. Lookaside
  27045. ** memory is used if not NULL. db->mallocFailed is set appropriately
  27046. ** when not NULL.
  27047. ** zBase: An initial buffer. May be NULL in which case the initial buffer
  27048. ** is malloced.
  27049. ** n: Size of zBase in bytes. If total space requirements never exceed
  27050. ** n then no memory allocations ever occur.
  27051. ** mx: Maximum number of bytes to accumulate. If mx==0 then no memory
  27052. ** allocations will ever occur.
  27053. */
  27054. SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, sqlite3 *db, char *zBase, int n, int mx){
  27055. p->zText = zBase;
  27056. p->db = db;
  27057. p->nAlloc = n;
  27058. p->mxAlloc = mx;
  27059. p->nChar = 0;
  27060. p->accError = 0;
  27061. p->printfFlags = 0;
  27062. }
  27063. /* Allocate and initialize a new dynamic string object */
  27064. SQLITE_API sqlite3_str *sqlite3_str_new(sqlite3 *db){
  27065. sqlite3_str *p = sqlite3_malloc64(sizeof(*p));
  27066. if( p ){
  27067. sqlite3StrAccumInit(p, 0, 0, 0,
  27068. db ? db->aLimit[SQLITE_LIMIT_LENGTH] : SQLITE_MAX_LENGTH);
  27069. }else{
  27070. p = &sqlite3OomStr;
  27071. }
  27072. return p;
  27073. }
  27074. /*
  27075. ** Print into memory obtained from sqliteMalloc(). Use the internal
  27076. ** %-conversion extensions.
  27077. */
  27078. SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
  27079. char *z;
  27080. char zBase[SQLITE_PRINT_BUF_SIZE];
  27081. StrAccum acc;
  27082. assert( db!=0 );
  27083. sqlite3StrAccumInit(&acc, db, zBase, sizeof(zBase),
  27084. db->aLimit[SQLITE_LIMIT_LENGTH]);
  27085. acc.printfFlags = SQLITE_PRINTF_INTERNAL;
  27086. sqlite3_str_vappendf(&acc, zFormat, ap);
  27087. z = sqlite3StrAccumFinish(&acc);
  27088. if( acc.accError==SQLITE_NOMEM ){
  27089. sqlite3OomFault(db);
  27090. }
  27091. return z;
  27092. }
  27093. /*
  27094. ** Print into memory obtained from sqliteMalloc(). Use the internal
  27095. ** %-conversion extensions.
  27096. */
  27097. SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
  27098. va_list ap;
  27099. char *z;
  27100. va_start(ap, zFormat);
  27101. z = sqlite3VMPrintf(db, zFormat, ap);
  27102. va_end(ap);
  27103. return z;
  27104. }
  27105. /*
  27106. ** Print into memory obtained from sqlite3_malloc(). Omit the internal
  27107. ** %-conversion extensions.
  27108. */
  27109. SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
  27110. char *z;
  27111. char zBase[SQLITE_PRINT_BUF_SIZE];
  27112. StrAccum acc;
  27113. #ifdef SQLITE_ENABLE_API_ARMOR
  27114. if( zFormat==0 ){
  27115. (void)SQLITE_MISUSE_BKPT;
  27116. return 0;
  27117. }
  27118. #endif
  27119. #ifndef SQLITE_OMIT_AUTOINIT
  27120. if( sqlite3_initialize() ) return 0;
  27121. #endif
  27122. sqlite3StrAccumInit(&acc, 0, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
  27123. sqlite3_str_vappendf(&acc, zFormat, ap);
  27124. z = sqlite3StrAccumFinish(&acc);
  27125. return z;
  27126. }
  27127. /*
  27128. ** Print into memory obtained from sqlite3_malloc()(). Omit the internal
  27129. ** %-conversion extensions.
  27130. */
  27131. SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
  27132. va_list ap;
  27133. char *z;
  27134. #ifndef SQLITE_OMIT_AUTOINIT
  27135. if( sqlite3_initialize() ) return 0;
  27136. #endif
  27137. va_start(ap, zFormat);
  27138. z = sqlite3_vmprintf(zFormat, ap);
  27139. va_end(ap);
  27140. return z;
  27141. }
  27142. /*
  27143. ** sqlite3_snprintf() works like snprintf() except that it ignores the
  27144. ** current locale settings. This is important for SQLite because we
  27145. ** are not able to use a "," as the decimal point in place of "." as
  27146. ** specified by some locales.
  27147. **
  27148. ** Oops: The first two arguments of sqlite3_snprintf() are backwards
  27149. ** from the snprintf() standard. Unfortunately, it is too late to change
  27150. ** this without breaking compatibility, so we just have to live with the
  27151. ** mistake.
  27152. **
  27153. ** sqlite3_vsnprintf() is the varargs version.
  27154. */
  27155. SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
  27156. StrAccum acc;
  27157. if( n<=0 ) return zBuf;
  27158. #ifdef SQLITE_ENABLE_API_ARMOR
  27159. if( zBuf==0 || zFormat==0 ) {
  27160. (void)SQLITE_MISUSE_BKPT;
  27161. if( zBuf ) zBuf[0] = 0;
  27162. return zBuf;
  27163. }
  27164. #endif
  27165. sqlite3StrAccumInit(&acc, 0, zBuf, n, 0);
  27166. sqlite3_str_vappendf(&acc, zFormat, ap);
  27167. zBuf[acc.nChar] = 0;
  27168. return zBuf;
  27169. }
  27170. SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
  27171. char *z;
  27172. va_list ap;
  27173. va_start(ap,zFormat);
  27174. z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
  27175. va_end(ap);
  27176. return z;
  27177. }
  27178. /*
  27179. ** This is the routine that actually formats the sqlite3_log() message.
  27180. ** We house it in a separate routine from sqlite3_log() to avoid using
  27181. ** stack space on small-stack systems when logging is disabled.
  27182. **
  27183. ** sqlite3_log() must render into a static buffer. It cannot dynamically
  27184. ** allocate memory because it might be called while the memory allocator
  27185. ** mutex is held.
  27186. **
  27187. ** sqlite3_str_vappendf() might ask for *temporary* memory allocations for
  27188. ** certain format characters (%q) or for very large precisions or widths.
  27189. ** Care must be taken that any sqlite3_log() calls that occur while the
  27190. ** memory mutex is held do not use these mechanisms.
  27191. */
  27192. static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
  27193. StrAccum acc; /* String accumulator */
  27194. char zMsg[SQLITE_PRINT_BUF_SIZE*3]; /* Complete log message */
  27195. sqlite3StrAccumInit(&acc, 0, zMsg, sizeof(zMsg), 0);
  27196. sqlite3_str_vappendf(&acc, zFormat, ap);
  27197. sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
  27198. sqlite3StrAccumFinish(&acc));
  27199. }
  27200. /*
  27201. ** Format and write a message to the log if logging is enabled.
  27202. */
  27203. SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
  27204. va_list ap; /* Vararg list */
  27205. if( sqlite3GlobalConfig.xLog ){
  27206. va_start(ap, zFormat);
  27207. renderLogMsg(iErrCode, zFormat, ap);
  27208. va_end(ap);
  27209. }
  27210. }
  27211. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  27212. /*
  27213. ** A version of printf() that understands %lld. Used for debugging.
  27214. ** The printf() built into some versions of windows does not understand %lld
  27215. ** and segfaults if you give it a long long int.
  27216. */
  27217. SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
  27218. va_list ap;
  27219. StrAccum acc;
  27220. char zBuf[500];
  27221. sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
  27222. va_start(ap,zFormat);
  27223. sqlite3_str_vappendf(&acc, zFormat, ap);
  27224. va_end(ap);
  27225. sqlite3StrAccumFinish(&acc);
  27226. #ifdef SQLITE_OS_TRACE_PROC
  27227. {
  27228. extern void SQLITE_OS_TRACE_PROC(const char *zBuf, int nBuf);
  27229. SQLITE_OS_TRACE_PROC(zBuf, sizeof(zBuf));
  27230. }
  27231. #else
  27232. fprintf(stdout,"%s", zBuf);
  27233. fflush(stdout);
  27234. #endif
  27235. }
  27236. #endif
  27237. /*
  27238. ** variable-argument wrapper around sqlite3_str_vappendf(). The bFlags argument
  27239. ** can contain the bit SQLITE_PRINTF_INTERNAL enable internal formats.
  27240. */
  27241. SQLITE_API void sqlite3_str_appendf(StrAccum *p, const char *zFormat, ...){
  27242. va_list ap;
  27243. va_start(ap,zFormat);
  27244. sqlite3_str_vappendf(p, zFormat, ap);
  27245. va_end(ap);
  27246. }
  27247. /************** End of printf.c **********************************************/
  27248. /************** Begin file treeview.c ****************************************/
  27249. /*
  27250. ** 2015-06-08
  27251. **
  27252. ** The author disclaims copyright to this source code. In place of
  27253. ** a legal notice, here is a blessing:
  27254. **
  27255. ** May you do good and not evil.
  27256. ** May you find forgiveness for yourself and forgive others.
  27257. ** May you share freely, never taking more than you give.
  27258. **
  27259. *************************************************************************
  27260. **
  27261. ** This file contains C code to implement the TreeView debugging routines.
  27262. ** These routines print a parse tree to standard output for debugging and
  27263. ** analysis.
  27264. **
  27265. ** The interfaces in this file is only available when compiling
  27266. ** with SQLITE_DEBUG.
  27267. */
  27268. /* #include "sqliteInt.h" */
  27269. #ifdef SQLITE_DEBUG
  27270. /*
  27271. ** Add a new subitem to the tree. The moreToFollow flag indicates that this
  27272. ** is not the last item in the tree.
  27273. */
  27274. static TreeView *sqlite3TreeViewPush(TreeView *p, u8 moreToFollow){
  27275. if( p==0 ){
  27276. p = sqlite3_malloc64( sizeof(*p) );
  27277. if( p==0 ) return 0;
  27278. memset(p, 0, sizeof(*p));
  27279. }else{
  27280. p->iLevel++;
  27281. }
  27282. assert( moreToFollow==0 || moreToFollow==1 );
  27283. if( p->iLevel<sizeof(p->bLine) ) p->bLine[p->iLevel] = moreToFollow;
  27284. return p;
  27285. }
  27286. /*
  27287. ** Finished with one layer of the tree
  27288. */
  27289. static void sqlite3TreeViewPop(TreeView *p){
  27290. if( p==0 ) return;
  27291. p->iLevel--;
  27292. if( p->iLevel<0 ) sqlite3_free(p);
  27293. }
  27294. /*
  27295. ** Generate a single line of output for the tree, with a prefix that contains
  27296. ** all the appropriate tree lines
  27297. */
  27298. static void sqlite3TreeViewLine(TreeView *p, const char *zFormat, ...){
  27299. va_list ap;
  27300. int i;
  27301. StrAccum acc;
  27302. char zBuf[500];
  27303. sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
  27304. if( p ){
  27305. for(i=0; i<p->iLevel && i<sizeof(p->bLine)-1; i++){
  27306. sqlite3_str_append(&acc, p->bLine[i] ? "| " : " ", 4);
  27307. }
  27308. sqlite3_str_append(&acc, p->bLine[i] ? "|-- " : "'-- ", 4);
  27309. }
  27310. if( zFormat!=0 ){
  27311. va_start(ap, zFormat);
  27312. sqlite3_str_vappendf(&acc, zFormat, ap);
  27313. va_end(ap);
  27314. assert( acc.nChar>0 );
  27315. sqlite3_str_append(&acc, "\n", 1);
  27316. }
  27317. sqlite3StrAccumFinish(&acc);
  27318. fprintf(stdout,"%s", zBuf);
  27319. fflush(stdout);
  27320. }
  27321. /*
  27322. ** Shorthand for starting a new tree item that consists of a single label
  27323. */
  27324. static void sqlite3TreeViewItem(TreeView *p, const char *zLabel,u8 moreFollows){
  27325. p = sqlite3TreeViewPush(p, moreFollows);
  27326. sqlite3TreeViewLine(p, "%s", zLabel);
  27327. }
  27328. /*
  27329. ** Generate a human-readable description of a WITH clause.
  27330. */
  27331. SQLITE_PRIVATE void sqlite3TreeViewWith(TreeView *pView, const With *pWith, u8 moreToFollow){
  27332. int i;
  27333. if( pWith==0 ) return;
  27334. if( pWith->nCte==0 ) return;
  27335. if( pWith->pOuter ){
  27336. sqlite3TreeViewLine(pView, "WITH (0x%p, pOuter=0x%p)",pWith,pWith->pOuter);
  27337. }else{
  27338. sqlite3TreeViewLine(pView, "WITH (0x%p)", pWith);
  27339. }
  27340. if( pWith->nCte>0 ){
  27341. pView = sqlite3TreeViewPush(pView, 1);
  27342. for(i=0; i<pWith->nCte; i++){
  27343. StrAccum x;
  27344. char zLine[1000];
  27345. const struct Cte *pCte = &pWith->a[i];
  27346. sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
  27347. sqlite3_str_appendf(&x, "%s", pCte->zName);
  27348. if( pCte->pCols && pCte->pCols->nExpr>0 ){
  27349. char cSep = '(';
  27350. int j;
  27351. for(j=0; j<pCte->pCols->nExpr; j++){
  27352. sqlite3_str_appendf(&x, "%c%s", cSep, pCte->pCols->a[j].zName);
  27353. cSep = ',';
  27354. }
  27355. sqlite3_str_appendf(&x, ")");
  27356. }
  27357. sqlite3_str_appendf(&x, " AS");
  27358. sqlite3StrAccumFinish(&x);
  27359. sqlite3TreeViewItem(pView, zLine, i<pWith->nCte-1);
  27360. sqlite3TreeViewSelect(pView, pCte->pSelect, 0);
  27361. sqlite3TreeViewPop(pView);
  27362. }
  27363. sqlite3TreeViewPop(pView);
  27364. }
  27365. }
  27366. /*
  27367. ** Generate a human-readable description of a SrcList object.
  27368. */
  27369. SQLITE_PRIVATE void sqlite3TreeViewSrcList(TreeView *pView, const SrcList *pSrc){
  27370. int i;
  27371. for(i=0; i<pSrc->nSrc; i++){
  27372. const struct SrcList_item *pItem = &pSrc->a[i];
  27373. StrAccum x;
  27374. char zLine[100];
  27375. sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
  27376. sqlite3_str_appendf(&x, "{%d,*}", pItem->iCursor);
  27377. if( pItem->zDatabase ){
  27378. sqlite3_str_appendf(&x, " %s.%s", pItem->zDatabase, pItem->zName);
  27379. }else if( pItem->zName ){
  27380. sqlite3_str_appendf(&x, " %s", pItem->zName);
  27381. }
  27382. if( pItem->pTab ){
  27383. sqlite3_str_appendf(&x, " tab=%Q nCol=%d ptr=%p",
  27384. pItem->pTab->zName, pItem->pTab->nCol, pItem->pTab);
  27385. }
  27386. if( pItem->zAlias ){
  27387. sqlite3_str_appendf(&x, " (AS %s)", pItem->zAlias);
  27388. }
  27389. if( pItem->fg.jointype & JT_LEFT ){
  27390. sqlite3_str_appendf(&x, " LEFT-JOIN");
  27391. }
  27392. sqlite3StrAccumFinish(&x);
  27393. sqlite3TreeViewItem(pView, zLine, i<pSrc->nSrc-1);
  27394. if( pItem->pSelect ){
  27395. sqlite3TreeViewSelect(pView, pItem->pSelect, 0);
  27396. }
  27397. if( pItem->fg.isTabFunc ){
  27398. sqlite3TreeViewExprList(pView, pItem->u1.pFuncArg, 0, "func-args:");
  27399. }
  27400. sqlite3TreeViewPop(pView);
  27401. }
  27402. }
  27403. /*
  27404. ** Generate a human-readable description of a Select object.
  27405. */
  27406. SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView *pView, const Select *p, u8 moreToFollow){
  27407. int n = 0;
  27408. int cnt = 0;
  27409. if( p==0 ){
  27410. sqlite3TreeViewLine(pView, "nil-SELECT");
  27411. return;
  27412. }
  27413. pView = sqlite3TreeViewPush(pView, moreToFollow);
  27414. if( p->pWith ){
  27415. sqlite3TreeViewWith(pView, p->pWith, 1);
  27416. cnt = 1;
  27417. sqlite3TreeViewPush(pView, 1);
  27418. }
  27419. do{
  27420. sqlite3TreeViewLine(pView,
  27421. "SELECT%s%s (%u/%p) selFlags=0x%x nSelectRow=%d",
  27422. ((p->selFlags & SF_Distinct) ? " DISTINCT" : ""),
  27423. ((p->selFlags & SF_Aggregate) ? " agg_flag" : ""),
  27424. p->selId, p, p->selFlags,
  27425. (int)p->nSelectRow
  27426. );
  27427. if( cnt++ ) sqlite3TreeViewPop(pView);
  27428. if( p->pPrior ){
  27429. n = 1000;
  27430. }else{
  27431. n = 0;
  27432. if( p->pSrc && p->pSrc->nSrc ) n++;
  27433. if( p->pWhere ) n++;
  27434. if( p->pGroupBy ) n++;
  27435. if( p->pHaving ) n++;
  27436. if( p->pOrderBy ) n++;
  27437. if( p->pLimit ) n++;
  27438. #ifndef SQLITE_OMIT_WINDOWFUNC
  27439. if( p->pWin ) n++;
  27440. if( p->pWinDefn ) n++;
  27441. #endif
  27442. }
  27443. sqlite3TreeViewExprList(pView, p->pEList, (n--)>0, "result-set");
  27444. #ifndef SQLITE_OMIT_WINDOWFUNC
  27445. if( p->pWin ){
  27446. Window *pX;
  27447. pView = sqlite3TreeViewPush(pView, (n--)>0);
  27448. sqlite3TreeViewLine(pView, "window-functions");
  27449. for(pX=p->pWin; pX; pX=pX->pNextWin){
  27450. sqlite3TreeViewWinFunc(pView, pX, pX->pNextWin!=0);
  27451. }
  27452. sqlite3TreeViewPop(pView);
  27453. }
  27454. #endif
  27455. if( p->pSrc && p->pSrc->nSrc ){
  27456. pView = sqlite3TreeViewPush(pView, (n--)>0);
  27457. sqlite3TreeViewLine(pView, "FROM");
  27458. sqlite3TreeViewSrcList(pView, p->pSrc);
  27459. sqlite3TreeViewPop(pView);
  27460. }
  27461. if( p->pWhere ){
  27462. sqlite3TreeViewItem(pView, "WHERE", (n--)>0);
  27463. sqlite3TreeViewExpr(pView, p->pWhere, 0);
  27464. sqlite3TreeViewPop(pView);
  27465. }
  27466. if( p->pGroupBy ){
  27467. sqlite3TreeViewExprList(pView, p->pGroupBy, (n--)>0, "GROUPBY");
  27468. }
  27469. if( p->pHaving ){
  27470. sqlite3TreeViewItem(pView, "HAVING", (n--)>0);
  27471. sqlite3TreeViewExpr(pView, p->pHaving, 0);
  27472. sqlite3TreeViewPop(pView);
  27473. }
  27474. #ifndef SQLITE_OMIT_WINDOWFUNC
  27475. if( p->pWinDefn ){
  27476. Window *pX;
  27477. sqlite3TreeViewItem(pView, "WINDOW", (n--)>0);
  27478. for(pX=p->pWinDefn; pX; pX=pX->pNextWin){
  27479. sqlite3TreeViewWindow(pView, pX, pX->pNextWin!=0);
  27480. }
  27481. sqlite3TreeViewPop(pView);
  27482. }
  27483. #endif
  27484. if( p->pOrderBy ){
  27485. sqlite3TreeViewExprList(pView, p->pOrderBy, (n--)>0, "ORDERBY");
  27486. }
  27487. if( p->pLimit ){
  27488. sqlite3TreeViewItem(pView, "LIMIT", (n--)>0);
  27489. sqlite3TreeViewExpr(pView, p->pLimit->pLeft, p->pLimit->pRight!=0);
  27490. if( p->pLimit->pRight ){
  27491. sqlite3TreeViewItem(pView, "OFFSET", (n--)>0);
  27492. sqlite3TreeViewExpr(pView, p->pLimit->pRight, 0);
  27493. sqlite3TreeViewPop(pView);
  27494. }
  27495. sqlite3TreeViewPop(pView);
  27496. }
  27497. if( p->pPrior ){
  27498. const char *zOp = "UNION";
  27499. switch( p->op ){
  27500. case TK_ALL: zOp = "UNION ALL"; break;
  27501. case TK_INTERSECT: zOp = "INTERSECT"; break;
  27502. case TK_EXCEPT: zOp = "EXCEPT"; break;
  27503. }
  27504. sqlite3TreeViewItem(pView, zOp, 1);
  27505. }
  27506. p = p->pPrior;
  27507. }while( p!=0 );
  27508. sqlite3TreeViewPop(pView);
  27509. }
  27510. #ifndef SQLITE_OMIT_WINDOWFUNC
  27511. /*
  27512. ** Generate a description of starting or stopping bounds
  27513. */
  27514. SQLITE_PRIVATE void sqlite3TreeViewBound(
  27515. TreeView *pView, /* View context */
  27516. u8 eBound, /* UNBOUNDED, CURRENT, PRECEDING, FOLLOWING */
  27517. Expr *pExpr, /* Value for PRECEDING or FOLLOWING */
  27518. u8 moreToFollow /* True if more to follow */
  27519. ){
  27520. switch( eBound ){
  27521. case TK_UNBOUNDED: {
  27522. sqlite3TreeViewItem(pView, "UNBOUNDED", moreToFollow);
  27523. sqlite3TreeViewPop(pView);
  27524. break;
  27525. }
  27526. case TK_CURRENT: {
  27527. sqlite3TreeViewItem(pView, "CURRENT", moreToFollow);
  27528. sqlite3TreeViewPop(pView);
  27529. break;
  27530. }
  27531. case TK_PRECEDING: {
  27532. sqlite3TreeViewItem(pView, "PRECEDING", moreToFollow);
  27533. sqlite3TreeViewExpr(pView, pExpr, 0);
  27534. sqlite3TreeViewPop(pView);
  27535. break;
  27536. }
  27537. case TK_FOLLOWING: {
  27538. sqlite3TreeViewItem(pView, "FOLLOWING", moreToFollow);
  27539. sqlite3TreeViewExpr(pView, pExpr, 0);
  27540. sqlite3TreeViewPop(pView);
  27541. break;
  27542. }
  27543. }
  27544. }
  27545. #endif /* SQLITE_OMIT_WINDOWFUNC */
  27546. #ifndef SQLITE_OMIT_WINDOWFUNC
  27547. /*
  27548. ** Generate a human-readable explanation for a Window object
  27549. */
  27550. SQLITE_PRIVATE void sqlite3TreeViewWindow(TreeView *pView, const Window *pWin, u8 more){
  27551. int nElement = 0;
  27552. if( pWin->pFilter ){
  27553. sqlite3TreeViewItem(pView, "FILTER", 1);
  27554. sqlite3TreeViewExpr(pView, pWin->pFilter, 0);
  27555. sqlite3TreeViewPop(pView);
  27556. }
  27557. pView = sqlite3TreeViewPush(pView, more);
  27558. if( pWin->zName ){
  27559. sqlite3TreeViewLine(pView, "OVER %s (%p)", pWin->zName, pWin);
  27560. }else{
  27561. sqlite3TreeViewLine(pView, "OVER (%p)", pWin);
  27562. }
  27563. if( pWin->zBase ) nElement++;
  27564. if( pWin->pOrderBy ) nElement++;
  27565. if( pWin->eFrmType ) nElement++;
  27566. if( pWin->eExclude ) nElement++;
  27567. if( pWin->zBase ){
  27568. sqlite3TreeViewPush(pView, (--nElement)>0);
  27569. sqlite3TreeViewLine(pView, "window: %s", pWin->zBase);
  27570. sqlite3TreeViewPop(pView);
  27571. }
  27572. if( pWin->pPartition ){
  27573. sqlite3TreeViewExprList(pView, pWin->pPartition, nElement>0,"PARTITION-BY");
  27574. }
  27575. if( pWin->pOrderBy ){
  27576. sqlite3TreeViewExprList(pView, pWin->pOrderBy, (--nElement)>0, "ORDER-BY");
  27577. }
  27578. if( pWin->eFrmType ){
  27579. char zBuf[30];
  27580. const char *zFrmType = "ROWS";
  27581. if( pWin->eFrmType==TK_RANGE ) zFrmType = "RANGE";
  27582. if( pWin->eFrmType==TK_GROUPS ) zFrmType = "GROUPS";
  27583. sqlite3_snprintf(sizeof(zBuf),zBuf,"%s%s",zFrmType,
  27584. pWin->bImplicitFrame ? " (implied)" : "");
  27585. sqlite3TreeViewItem(pView, zBuf, (--nElement)>0);
  27586. sqlite3TreeViewBound(pView, pWin->eStart, pWin->pStart, 1);
  27587. sqlite3TreeViewBound(pView, pWin->eEnd, pWin->pEnd, 0);
  27588. sqlite3TreeViewPop(pView);
  27589. }
  27590. if( pWin->eExclude ){
  27591. char zBuf[30];
  27592. const char *zExclude;
  27593. switch( pWin->eExclude ){
  27594. case TK_NO: zExclude = "NO OTHERS"; break;
  27595. case TK_CURRENT: zExclude = "CURRENT ROW"; break;
  27596. case TK_GROUP: zExclude = "GROUP"; break;
  27597. case TK_TIES: zExclude = "TIES"; break;
  27598. default:
  27599. sqlite3_snprintf(sizeof(zBuf),zBuf,"invalid(%d)", pWin->eExclude);
  27600. zExclude = zBuf;
  27601. break;
  27602. }
  27603. sqlite3TreeViewPush(pView, 0);
  27604. sqlite3TreeViewLine(pView, "EXCLUDE %s", zExclude);
  27605. sqlite3TreeViewPop(pView);
  27606. }
  27607. sqlite3TreeViewPop(pView);
  27608. }
  27609. #endif /* SQLITE_OMIT_WINDOWFUNC */
  27610. #ifndef SQLITE_OMIT_WINDOWFUNC
  27611. /*
  27612. ** Generate a human-readable explanation for a Window Function object
  27613. */
  27614. SQLITE_PRIVATE void sqlite3TreeViewWinFunc(TreeView *pView, const Window *pWin, u8 more){
  27615. pView = sqlite3TreeViewPush(pView, more);
  27616. sqlite3TreeViewLine(pView, "WINFUNC %s(%d)",
  27617. pWin->pFunc->zName, pWin->pFunc->nArg);
  27618. sqlite3TreeViewWindow(pView, pWin, 0);
  27619. sqlite3TreeViewPop(pView);
  27620. }
  27621. #endif /* SQLITE_OMIT_WINDOWFUNC */
  27622. /*
  27623. ** Generate a human-readable explanation of an expression tree.
  27624. */
  27625. SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 moreToFollow){
  27626. const char *zBinOp = 0; /* Binary operator */
  27627. const char *zUniOp = 0; /* Unary operator */
  27628. char zFlgs[60];
  27629. pView = sqlite3TreeViewPush(pView, moreToFollow);
  27630. if( pExpr==0 ){
  27631. sqlite3TreeViewLine(pView, "nil");
  27632. sqlite3TreeViewPop(pView);
  27633. return;
  27634. }
  27635. if( pExpr->flags ){
  27636. if( ExprHasProperty(pExpr, EP_FromJoin) ){
  27637. sqlite3_snprintf(sizeof(zFlgs),zFlgs," flags=0x%x iRJT=%d",
  27638. pExpr->flags, pExpr->iRightJoinTable);
  27639. }else{
  27640. sqlite3_snprintf(sizeof(zFlgs),zFlgs," flags=0x%x",pExpr->flags);
  27641. }
  27642. }else{
  27643. zFlgs[0] = 0;
  27644. }
  27645. switch( pExpr->op ){
  27646. case TK_AGG_COLUMN: {
  27647. sqlite3TreeViewLine(pView, "AGG{%d:%d}%s",
  27648. pExpr->iTable, pExpr->iColumn, zFlgs);
  27649. break;
  27650. }
  27651. case TK_COLUMN: {
  27652. if( pExpr->iTable<0 ){
  27653. /* This only happens when coding check constraints */
  27654. sqlite3TreeViewLine(pView, "COLUMN(%d)%s", pExpr->iColumn, zFlgs);
  27655. }else{
  27656. sqlite3TreeViewLine(pView, "{%d:%d}%s",
  27657. pExpr->iTable, pExpr->iColumn, zFlgs);
  27658. }
  27659. if( ExprHasProperty(pExpr, EP_FixedCol) ){
  27660. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  27661. }
  27662. break;
  27663. }
  27664. case TK_INTEGER: {
  27665. if( pExpr->flags & EP_IntValue ){
  27666. sqlite3TreeViewLine(pView, "%d", pExpr->u.iValue);
  27667. }else{
  27668. sqlite3TreeViewLine(pView, "%s", pExpr->u.zToken);
  27669. }
  27670. break;
  27671. }
  27672. #ifndef SQLITE_OMIT_FLOATING_POINT
  27673. case TK_FLOAT: {
  27674. sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
  27675. break;
  27676. }
  27677. #endif
  27678. case TK_STRING: {
  27679. sqlite3TreeViewLine(pView,"%Q", pExpr->u.zToken);
  27680. break;
  27681. }
  27682. case TK_NULL: {
  27683. sqlite3TreeViewLine(pView,"NULL");
  27684. break;
  27685. }
  27686. case TK_TRUEFALSE: {
  27687. sqlite3TreeViewLine(pView,
  27688. sqlite3ExprTruthValue(pExpr) ? "TRUE" : "FALSE");
  27689. break;
  27690. }
  27691. #ifndef SQLITE_OMIT_BLOB_LITERAL
  27692. case TK_BLOB: {
  27693. sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
  27694. break;
  27695. }
  27696. #endif
  27697. case TK_VARIABLE: {
  27698. sqlite3TreeViewLine(pView,"VARIABLE(%s,%d)",
  27699. pExpr->u.zToken, pExpr->iColumn);
  27700. break;
  27701. }
  27702. case TK_REGISTER: {
  27703. sqlite3TreeViewLine(pView,"REGISTER(%d)", pExpr->iTable);
  27704. break;
  27705. }
  27706. case TK_ID: {
  27707. sqlite3TreeViewLine(pView,"ID \"%w\"", pExpr->u.zToken);
  27708. break;
  27709. }
  27710. #ifndef SQLITE_OMIT_CAST
  27711. case TK_CAST: {
  27712. /* Expressions of the form: CAST(pLeft AS token) */
  27713. sqlite3TreeViewLine(pView,"CAST %Q", pExpr->u.zToken);
  27714. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  27715. break;
  27716. }
  27717. #endif /* SQLITE_OMIT_CAST */
  27718. case TK_LT: zBinOp = "LT"; break;
  27719. case TK_LE: zBinOp = "LE"; break;
  27720. case TK_GT: zBinOp = "GT"; break;
  27721. case TK_GE: zBinOp = "GE"; break;
  27722. case TK_NE: zBinOp = "NE"; break;
  27723. case TK_EQ: zBinOp = "EQ"; break;
  27724. case TK_IS: zBinOp = "IS"; break;
  27725. case TK_ISNOT: zBinOp = "ISNOT"; break;
  27726. case TK_AND: zBinOp = "AND"; break;
  27727. case TK_OR: zBinOp = "OR"; break;
  27728. case TK_PLUS: zBinOp = "ADD"; break;
  27729. case TK_STAR: zBinOp = "MUL"; break;
  27730. case TK_MINUS: zBinOp = "SUB"; break;
  27731. case TK_REM: zBinOp = "REM"; break;
  27732. case TK_BITAND: zBinOp = "BITAND"; break;
  27733. case TK_BITOR: zBinOp = "BITOR"; break;
  27734. case TK_SLASH: zBinOp = "DIV"; break;
  27735. case TK_LSHIFT: zBinOp = "LSHIFT"; break;
  27736. case TK_RSHIFT: zBinOp = "RSHIFT"; break;
  27737. case TK_CONCAT: zBinOp = "CONCAT"; break;
  27738. case TK_DOT: zBinOp = "DOT"; break;
  27739. case TK_UMINUS: zUniOp = "UMINUS"; break;
  27740. case TK_UPLUS: zUniOp = "UPLUS"; break;
  27741. case TK_BITNOT: zUniOp = "BITNOT"; break;
  27742. case TK_NOT: zUniOp = "NOT"; break;
  27743. case TK_ISNULL: zUniOp = "ISNULL"; break;
  27744. case TK_NOTNULL: zUniOp = "NOTNULL"; break;
  27745. case TK_TRUTH: {
  27746. int x;
  27747. const char *azOp[] = {
  27748. "IS-FALSE", "IS-TRUE", "IS-NOT-FALSE", "IS-NOT-TRUE"
  27749. };
  27750. assert( pExpr->op2==TK_IS || pExpr->op2==TK_ISNOT );
  27751. assert( pExpr->pRight );
  27752. assert( sqlite3ExprSkipCollate(pExpr->pRight)->op==TK_TRUEFALSE );
  27753. x = (pExpr->op2==TK_ISNOT)*2 + sqlite3ExprTruthValue(pExpr->pRight);
  27754. zUniOp = azOp[x];
  27755. break;
  27756. }
  27757. case TK_SPAN: {
  27758. sqlite3TreeViewLine(pView, "SPAN %Q", pExpr->u.zToken);
  27759. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  27760. break;
  27761. }
  27762. case TK_COLLATE: {
  27763. sqlite3TreeViewLine(pView, "COLLATE %Q", pExpr->u.zToken);
  27764. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  27765. break;
  27766. }
  27767. case TK_AGG_FUNCTION:
  27768. case TK_FUNCTION: {
  27769. ExprList *pFarg; /* List of function arguments */
  27770. Window *pWin;
  27771. if( ExprHasProperty(pExpr, EP_TokenOnly) ){
  27772. pFarg = 0;
  27773. pWin = 0;
  27774. }else{
  27775. pFarg = pExpr->x.pList;
  27776. #ifndef SQLITE_OMIT_WINDOWFUNC
  27777. pWin = pExpr->y.pWin;
  27778. #else
  27779. pWin = 0;
  27780. #endif
  27781. }
  27782. if( pExpr->op==TK_AGG_FUNCTION ){
  27783. sqlite3TreeViewLine(pView, "AGG_FUNCTION%d %Q",
  27784. pExpr->op2, pExpr->u.zToken);
  27785. }else{
  27786. sqlite3TreeViewLine(pView, "FUNCTION %Q", pExpr->u.zToken);
  27787. }
  27788. if( pFarg ){
  27789. sqlite3TreeViewExprList(pView, pFarg, pWin!=0, 0);
  27790. }
  27791. #ifndef SQLITE_OMIT_WINDOWFUNC
  27792. if( pWin ){
  27793. sqlite3TreeViewWindow(pView, pWin, 0);
  27794. }
  27795. #endif
  27796. break;
  27797. }
  27798. #ifndef SQLITE_OMIT_SUBQUERY
  27799. case TK_EXISTS: {
  27800. sqlite3TreeViewLine(pView, "EXISTS-expr flags=0x%x", pExpr->flags);
  27801. sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
  27802. break;
  27803. }
  27804. case TK_SELECT: {
  27805. sqlite3TreeViewLine(pView, "SELECT-expr flags=0x%x", pExpr->flags);
  27806. sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
  27807. break;
  27808. }
  27809. case TK_IN: {
  27810. sqlite3TreeViewLine(pView, "IN flags=0x%x", pExpr->flags);
  27811. sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
  27812. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  27813. sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
  27814. }else{
  27815. sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
  27816. }
  27817. break;
  27818. }
  27819. #endif /* SQLITE_OMIT_SUBQUERY */
  27820. /*
  27821. ** x BETWEEN y AND z
  27822. **
  27823. ** This is equivalent to
  27824. **
  27825. ** x>=y AND x<=z
  27826. **
  27827. ** X is stored in pExpr->pLeft.
  27828. ** Y is stored in pExpr->pList->a[0].pExpr.
  27829. ** Z is stored in pExpr->pList->a[1].pExpr.
  27830. */
  27831. case TK_BETWEEN: {
  27832. Expr *pX = pExpr->pLeft;
  27833. Expr *pY = pExpr->x.pList->a[0].pExpr;
  27834. Expr *pZ = pExpr->x.pList->a[1].pExpr;
  27835. sqlite3TreeViewLine(pView, "BETWEEN");
  27836. sqlite3TreeViewExpr(pView, pX, 1);
  27837. sqlite3TreeViewExpr(pView, pY, 1);
  27838. sqlite3TreeViewExpr(pView, pZ, 0);
  27839. break;
  27840. }
  27841. case TK_TRIGGER: {
  27842. /* If the opcode is TK_TRIGGER, then the expression is a reference
  27843. ** to a column in the new.* or old.* pseudo-tables available to
  27844. ** trigger programs. In this case Expr.iTable is set to 1 for the
  27845. ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
  27846. ** is set to the column of the pseudo-table to read, or to -1 to
  27847. ** read the rowid field.
  27848. */
  27849. sqlite3TreeViewLine(pView, "%s(%d)",
  27850. pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
  27851. break;
  27852. }
  27853. case TK_CASE: {
  27854. sqlite3TreeViewLine(pView, "CASE");
  27855. sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
  27856. sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
  27857. break;
  27858. }
  27859. #ifndef SQLITE_OMIT_TRIGGER
  27860. case TK_RAISE: {
  27861. const char *zType = "unk";
  27862. switch( pExpr->affinity ){
  27863. case OE_Rollback: zType = "rollback"; break;
  27864. case OE_Abort: zType = "abort"; break;
  27865. case OE_Fail: zType = "fail"; break;
  27866. case OE_Ignore: zType = "ignore"; break;
  27867. }
  27868. sqlite3TreeViewLine(pView, "RAISE %s(%Q)", zType, pExpr->u.zToken);
  27869. break;
  27870. }
  27871. #endif
  27872. case TK_MATCH: {
  27873. sqlite3TreeViewLine(pView, "MATCH {%d:%d}%s",
  27874. pExpr->iTable, pExpr->iColumn, zFlgs);
  27875. sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
  27876. break;
  27877. }
  27878. case TK_VECTOR: {
  27879. sqlite3TreeViewBareExprList(pView, pExpr->x.pList, "VECTOR");
  27880. break;
  27881. }
  27882. case TK_SELECT_COLUMN: {
  27883. sqlite3TreeViewLine(pView, "SELECT-COLUMN %d", pExpr->iColumn);
  27884. sqlite3TreeViewSelect(pView, pExpr->pLeft->x.pSelect, 0);
  27885. break;
  27886. }
  27887. case TK_IF_NULL_ROW: {
  27888. sqlite3TreeViewLine(pView, "IF-NULL-ROW %d", pExpr->iTable);
  27889. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  27890. break;
  27891. }
  27892. default: {
  27893. sqlite3TreeViewLine(pView, "op=%d", pExpr->op);
  27894. break;
  27895. }
  27896. }
  27897. if( zBinOp ){
  27898. sqlite3TreeViewLine(pView, "%s%s", zBinOp, zFlgs);
  27899. sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
  27900. sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
  27901. }else if( zUniOp ){
  27902. sqlite3TreeViewLine(pView, "%s%s", zUniOp, zFlgs);
  27903. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  27904. }
  27905. sqlite3TreeViewPop(pView);
  27906. }
  27907. /*
  27908. ** Generate a human-readable explanation of an expression list.
  27909. */
  27910. SQLITE_PRIVATE void sqlite3TreeViewBareExprList(
  27911. TreeView *pView,
  27912. const ExprList *pList,
  27913. const char *zLabel
  27914. ){
  27915. if( zLabel==0 || zLabel[0]==0 ) zLabel = "LIST";
  27916. if( pList==0 ){
  27917. sqlite3TreeViewLine(pView, "%s (empty)", zLabel);
  27918. }else{
  27919. int i;
  27920. sqlite3TreeViewLine(pView, "%s", zLabel);
  27921. for(i=0; i<pList->nExpr; i++){
  27922. int j = pList->a[i].u.x.iOrderByCol;
  27923. char *zName = pList->a[i].zName;
  27924. int moreToFollow = i<pList->nExpr - 1;
  27925. if( j || zName ){
  27926. sqlite3TreeViewPush(pView, moreToFollow);
  27927. moreToFollow = 0;
  27928. sqlite3TreeViewLine(pView, 0);
  27929. if( zName ){
  27930. fprintf(stdout, "AS %s ", zName);
  27931. }
  27932. if( j ){
  27933. fprintf(stdout, "iOrderByCol=%d", j);
  27934. }
  27935. fprintf(stdout, "\n");
  27936. fflush(stdout);
  27937. }
  27938. sqlite3TreeViewExpr(pView, pList->a[i].pExpr, moreToFollow);
  27939. if( j || zName ){
  27940. sqlite3TreeViewPop(pView);
  27941. }
  27942. }
  27943. }
  27944. }
  27945. SQLITE_PRIVATE void sqlite3TreeViewExprList(
  27946. TreeView *pView,
  27947. const ExprList *pList,
  27948. u8 moreToFollow,
  27949. const char *zLabel
  27950. ){
  27951. pView = sqlite3TreeViewPush(pView, moreToFollow);
  27952. sqlite3TreeViewBareExprList(pView, pList, zLabel);
  27953. sqlite3TreeViewPop(pView);
  27954. }
  27955. #endif /* SQLITE_DEBUG */
  27956. /************** End of treeview.c ********************************************/
  27957. /************** Begin file random.c ******************************************/
  27958. /*
  27959. ** 2001 September 15
  27960. **
  27961. ** The author disclaims copyright to this source code. In place of
  27962. ** a legal notice, here is a blessing:
  27963. **
  27964. ** May you do good and not evil.
  27965. ** May you find forgiveness for yourself and forgive others.
  27966. ** May you share freely, never taking more than you give.
  27967. **
  27968. *************************************************************************
  27969. ** This file contains code to implement a pseudo-random number
  27970. ** generator (PRNG) for SQLite.
  27971. **
  27972. ** Random numbers are used by some of the database backends in order
  27973. ** to generate random integer keys for tables or random filenames.
  27974. */
  27975. /* #include "sqliteInt.h" */
  27976. /* All threads share a single random number generator.
  27977. ** This structure is the current state of the generator.
  27978. */
  27979. static SQLITE_WSD struct sqlite3PrngType {
  27980. unsigned char isInit; /* True if initialized */
  27981. unsigned char i, j; /* State variables */
  27982. unsigned char s[256]; /* State variables */
  27983. } sqlite3Prng;
  27984. /*
  27985. ** Return N random bytes.
  27986. */
  27987. SQLITE_API void sqlite3_randomness(int N, void *pBuf){
  27988. unsigned char t;
  27989. unsigned char *zBuf = pBuf;
  27990. /* The "wsdPrng" macro will resolve to the pseudo-random number generator
  27991. ** state vector. If writable static data is unsupported on the target,
  27992. ** we have to locate the state vector at run-time. In the more common
  27993. ** case where writable static data is supported, wsdPrng can refer directly
  27994. ** to the "sqlite3Prng" state vector declared above.
  27995. */
  27996. #ifdef SQLITE_OMIT_WSD
  27997. struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
  27998. # define wsdPrng p[0]
  27999. #else
  28000. # define wsdPrng sqlite3Prng
  28001. #endif
  28002. #if SQLITE_THREADSAFE
  28003. sqlite3_mutex *mutex;
  28004. #endif
  28005. #ifndef SQLITE_OMIT_AUTOINIT
  28006. if( sqlite3_initialize() ) return;
  28007. #endif
  28008. #if SQLITE_THREADSAFE
  28009. mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
  28010. #endif
  28011. sqlite3_mutex_enter(mutex);
  28012. if( N<=0 || pBuf==0 ){
  28013. wsdPrng.isInit = 0;
  28014. sqlite3_mutex_leave(mutex);
  28015. return;
  28016. }
  28017. /* Initialize the state of the random number generator once,
  28018. ** the first time this routine is called. The seed value does
  28019. ** not need to contain a lot of randomness since we are not
  28020. ** trying to do secure encryption or anything like that...
  28021. **
  28022. ** Nothing in this file or anywhere else in SQLite does any kind of
  28023. ** encryption. The RC4 algorithm is being used as a PRNG (pseudo-random
  28024. ** number generator) not as an encryption device.
  28025. */
  28026. if( !wsdPrng.isInit ){
  28027. int i;
  28028. char k[256];
  28029. wsdPrng.j = 0;
  28030. wsdPrng.i = 0;
  28031. sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
  28032. for(i=0; i<256; i++){
  28033. wsdPrng.s[i] = (u8)i;
  28034. }
  28035. for(i=0; i<256; i++){
  28036. wsdPrng.j += wsdPrng.s[i] + k[i];
  28037. t = wsdPrng.s[wsdPrng.j];
  28038. wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
  28039. wsdPrng.s[i] = t;
  28040. }
  28041. wsdPrng.isInit = 1;
  28042. }
  28043. assert( N>0 );
  28044. do{
  28045. wsdPrng.i++;
  28046. t = wsdPrng.s[wsdPrng.i];
  28047. wsdPrng.j += t;
  28048. wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
  28049. wsdPrng.s[wsdPrng.j] = t;
  28050. t += wsdPrng.s[wsdPrng.i];
  28051. *(zBuf++) = wsdPrng.s[t];
  28052. }while( --N );
  28053. sqlite3_mutex_leave(mutex);
  28054. }
  28055. #ifndef SQLITE_UNTESTABLE
  28056. /*
  28057. ** For testing purposes, we sometimes want to preserve the state of
  28058. ** PRNG and restore the PRNG to its saved state at a later time, or
  28059. ** to reset the PRNG to its initial state. These routines accomplish
  28060. ** those tasks.
  28061. **
  28062. ** The sqlite3_test_control() interface calls these routines to
  28063. ** control the PRNG.
  28064. */
  28065. static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
  28066. SQLITE_PRIVATE void sqlite3PrngSaveState(void){
  28067. memcpy(
  28068. &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
  28069. &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
  28070. sizeof(sqlite3Prng)
  28071. );
  28072. }
  28073. SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
  28074. memcpy(
  28075. &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
  28076. &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
  28077. sizeof(sqlite3Prng)
  28078. );
  28079. }
  28080. #endif /* SQLITE_UNTESTABLE */
  28081. /************** End of random.c **********************************************/
  28082. /************** Begin file threads.c *****************************************/
  28083. /*
  28084. ** 2012 July 21
  28085. **
  28086. ** The author disclaims copyright to this source code. In place of
  28087. ** a legal notice, here is a blessing:
  28088. **
  28089. ** May you do good and not evil.
  28090. ** May you find forgiveness for yourself and forgive others.
  28091. ** May you share freely, never taking more than you give.
  28092. **
  28093. ******************************************************************************
  28094. **
  28095. ** This file presents a simple cross-platform threading interface for
  28096. ** use internally by SQLite.
  28097. **
  28098. ** A "thread" can be created using sqlite3ThreadCreate(). This thread
  28099. ** runs independently of its creator until it is joined using
  28100. ** sqlite3ThreadJoin(), at which point it terminates.
  28101. **
  28102. ** Threads do not have to be real. It could be that the work of the
  28103. ** "thread" is done by the main thread at either the sqlite3ThreadCreate()
  28104. ** or sqlite3ThreadJoin() call. This is, in fact, what happens in
  28105. ** single threaded systems. Nothing in SQLite requires multiple threads.
  28106. ** This interface exists so that applications that want to take advantage
  28107. ** of multiple cores can do so, while also allowing applications to stay
  28108. ** single-threaded if desired.
  28109. */
  28110. /* #include "sqliteInt.h" */
  28111. #if SQLITE_OS_WIN
  28112. /* # include "os_win.h" */
  28113. #endif
  28114. #if SQLITE_MAX_WORKER_THREADS>0
  28115. /********************************* Unix Pthreads ****************************/
  28116. #if SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) && SQLITE_THREADSAFE>0
  28117. #define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */
  28118. /* #include <pthread.h> */
  28119. /* A running thread */
  28120. struct SQLiteThread {
  28121. pthread_t tid; /* Thread ID */
  28122. int done; /* Set to true when thread finishes */
  28123. void *pOut; /* Result returned by the thread */
  28124. void *(*xTask)(void*); /* The thread routine */
  28125. void *pIn; /* Argument to the thread */
  28126. };
  28127. /* Create a new thread */
  28128. SQLITE_PRIVATE int sqlite3ThreadCreate(
  28129. SQLiteThread **ppThread, /* OUT: Write the thread object here */
  28130. void *(*xTask)(void*), /* Routine to run in a separate thread */
  28131. void *pIn /* Argument passed into xTask() */
  28132. ){
  28133. SQLiteThread *p;
  28134. int rc;
  28135. assert( ppThread!=0 );
  28136. assert( xTask!=0 );
  28137. /* This routine is never used in single-threaded mode */
  28138. assert( sqlite3GlobalConfig.bCoreMutex!=0 );
  28139. *ppThread = 0;
  28140. p = sqlite3Malloc(sizeof(*p));
  28141. if( p==0 ) return SQLITE_NOMEM_BKPT;
  28142. memset(p, 0, sizeof(*p));
  28143. p->xTask = xTask;
  28144. p->pIn = pIn;
  28145. /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a
  28146. ** function that returns SQLITE_ERROR when passed the argument 200, that
  28147. ** forces worker threads to run sequentially and deterministically
  28148. ** for testing purposes. */
  28149. if( sqlite3FaultSim(200) ){
  28150. rc = 1;
  28151. }else{
  28152. rc = pthread_create(&p->tid, 0, xTask, pIn);
  28153. }
  28154. if( rc ){
  28155. p->done = 1;
  28156. p->pOut = xTask(pIn);
  28157. }
  28158. *ppThread = p;
  28159. return SQLITE_OK;
  28160. }
  28161. /* Get the results of the thread */
  28162. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
  28163. int rc;
  28164. assert( ppOut!=0 );
  28165. if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
  28166. if( p->done ){
  28167. *ppOut = p->pOut;
  28168. rc = SQLITE_OK;
  28169. }else{
  28170. rc = pthread_join(p->tid, ppOut) ? SQLITE_ERROR : SQLITE_OK;
  28171. }
  28172. sqlite3_free(p);
  28173. return rc;
  28174. }
  28175. #endif /* SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) */
  28176. /******************************** End Unix Pthreads *************************/
  28177. /********************************* Win32 Threads ****************************/
  28178. #if SQLITE_OS_WIN_THREADS
  28179. #define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */
  28180. #include <process.h>
  28181. /* A running thread */
  28182. struct SQLiteThread {
  28183. void *tid; /* The thread handle */
  28184. unsigned id; /* The thread identifier */
  28185. void *(*xTask)(void*); /* The routine to run as a thread */
  28186. void *pIn; /* Argument to xTask */
  28187. void *pResult; /* Result of xTask */
  28188. };
  28189. /* Thread procedure Win32 compatibility shim */
  28190. static unsigned __stdcall sqlite3ThreadProc(
  28191. void *pArg /* IN: Pointer to the SQLiteThread structure */
  28192. ){
  28193. SQLiteThread *p = (SQLiteThread *)pArg;
  28194. assert( p!=0 );
  28195. #if 0
  28196. /*
  28197. ** This assert appears to trigger spuriously on certain
  28198. ** versions of Windows, possibly due to _beginthreadex()
  28199. ** and/or CreateThread() not fully setting their thread
  28200. ** ID parameter before starting the thread.
  28201. */
  28202. assert( p->id==GetCurrentThreadId() );
  28203. #endif
  28204. assert( p->xTask!=0 );
  28205. p->pResult = p->xTask(p->pIn);
  28206. _endthreadex(0);
  28207. return 0; /* NOT REACHED */
  28208. }
  28209. /* Create a new thread */
  28210. SQLITE_PRIVATE int sqlite3ThreadCreate(
  28211. SQLiteThread **ppThread, /* OUT: Write the thread object here */
  28212. void *(*xTask)(void*), /* Routine to run in a separate thread */
  28213. void *pIn /* Argument passed into xTask() */
  28214. ){
  28215. SQLiteThread *p;
  28216. assert( ppThread!=0 );
  28217. assert( xTask!=0 );
  28218. *ppThread = 0;
  28219. p = sqlite3Malloc(sizeof(*p));
  28220. if( p==0 ) return SQLITE_NOMEM_BKPT;
  28221. /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a
  28222. ** function that returns SQLITE_ERROR when passed the argument 200, that
  28223. ** forces worker threads to run sequentially and deterministically
  28224. ** (via the sqlite3FaultSim() term of the conditional) for testing
  28225. ** purposes. */
  28226. if( sqlite3GlobalConfig.bCoreMutex==0 || sqlite3FaultSim(200) ){
  28227. memset(p, 0, sizeof(*p));
  28228. }else{
  28229. p->xTask = xTask;
  28230. p->pIn = pIn;
  28231. p->tid = (void*)_beginthreadex(0, 0, sqlite3ThreadProc, p, 0, &p->id);
  28232. if( p->tid==0 ){
  28233. memset(p, 0, sizeof(*p));
  28234. }
  28235. }
  28236. if( p->xTask==0 ){
  28237. p->id = GetCurrentThreadId();
  28238. p->pResult = xTask(pIn);
  28239. }
  28240. *ppThread = p;
  28241. return SQLITE_OK;
  28242. }
  28243. SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject); /* os_win.c */
  28244. /* Get the results of the thread */
  28245. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
  28246. DWORD rc;
  28247. BOOL bRc;
  28248. assert( ppOut!=0 );
  28249. if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
  28250. if( p->xTask==0 ){
  28251. /* assert( p->id==GetCurrentThreadId() ); */
  28252. rc = WAIT_OBJECT_0;
  28253. assert( p->tid==0 );
  28254. }else{
  28255. assert( p->id!=0 && p->id!=GetCurrentThreadId() );
  28256. rc = sqlite3Win32Wait((HANDLE)p->tid);
  28257. assert( rc!=WAIT_IO_COMPLETION );
  28258. bRc = CloseHandle((HANDLE)p->tid);
  28259. assert( bRc );
  28260. }
  28261. if( rc==WAIT_OBJECT_0 ) *ppOut = p->pResult;
  28262. sqlite3_free(p);
  28263. return (rc==WAIT_OBJECT_0) ? SQLITE_OK : SQLITE_ERROR;
  28264. }
  28265. #endif /* SQLITE_OS_WIN_THREADS */
  28266. /******************************** End Win32 Threads *************************/
  28267. /********************************* Single-Threaded **************************/
  28268. #ifndef SQLITE_THREADS_IMPLEMENTED
  28269. /*
  28270. ** This implementation does not actually create a new thread. It does the
  28271. ** work of the thread in the main thread, when either the thread is created
  28272. ** or when it is joined
  28273. */
  28274. /* A running thread */
  28275. struct SQLiteThread {
  28276. void *(*xTask)(void*); /* The routine to run as a thread */
  28277. void *pIn; /* Argument to xTask */
  28278. void *pResult; /* Result of xTask */
  28279. };
  28280. /* Create a new thread */
  28281. SQLITE_PRIVATE int sqlite3ThreadCreate(
  28282. SQLiteThread **ppThread, /* OUT: Write the thread object here */
  28283. void *(*xTask)(void*), /* Routine to run in a separate thread */
  28284. void *pIn /* Argument passed into xTask() */
  28285. ){
  28286. SQLiteThread *p;
  28287. assert( ppThread!=0 );
  28288. assert( xTask!=0 );
  28289. *ppThread = 0;
  28290. p = sqlite3Malloc(sizeof(*p));
  28291. if( p==0 ) return SQLITE_NOMEM_BKPT;
  28292. if( (SQLITE_PTR_TO_INT(p)/17)&1 ){
  28293. p->xTask = xTask;
  28294. p->pIn = pIn;
  28295. }else{
  28296. p->xTask = 0;
  28297. p->pResult = xTask(pIn);
  28298. }
  28299. *ppThread = p;
  28300. return SQLITE_OK;
  28301. }
  28302. /* Get the results of the thread */
  28303. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
  28304. assert( ppOut!=0 );
  28305. if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
  28306. if( p->xTask ){
  28307. *ppOut = p->xTask(p->pIn);
  28308. }else{
  28309. *ppOut = p->pResult;
  28310. }
  28311. sqlite3_free(p);
  28312. #if defined(SQLITE_TEST)
  28313. {
  28314. void *pTstAlloc = sqlite3Malloc(10);
  28315. if (!pTstAlloc) return SQLITE_NOMEM_BKPT;
  28316. sqlite3_free(pTstAlloc);
  28317. }
  28318. #endif
  28319. return SQLITE_OK;
  28320. }
  28321. #endif /* !defined(SQLITE_THREADS_IMPLEMENTED) */
  28322. /****************************** End Single-Threaded *************************/
  28323. #endif /* SQLITE_MAX_WORKER_THREADS>0 */
  28324. /************** End of threads.c *********************************************/
  28325. /************** Begin file utf.c *********************************************/
  28326. /*
  28327. ** 2004 April 13
  28328. **
  28329. ** The author disclaims copyright to this source code. In place of
  28330. ** a legal notice, here is a blessing:
  28331. **
  28332. ** May you do good and not evil.
  28333. ** May you find forgiveness for yourself and forgive others.
  28334. ** May you share freely, never taking more than you give.
  28335. **
  28336. *************************************************************************
  28337. ** This file contains routines used to translate between UTF-8,
  28338. ** UTF-16, UTF-16BE, and UTF-16LE.
  28339. **
  28340. ** Notes on UTF-8:
  28341. **
  28342. ** Byte-0 Byte-1 Byte-2 Byte-3 Value
  28343. ** 0xxxxxxx 00000000 00000000 0xxxxxxx
  28344. ** 110yyyyy 10xxxxxx 00000000 00000yyy yyxxxxxx
  28345. ** 1110zzzz 10yyyyyy 10xxxxxx 00000000 zzzzyyyy yyxxxxxx
  28346. ** 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx 000uuuuu zzzzyyyy yyxxxxxx
  28347. **
  28348. **
  28349. ** Notes on UTF-16: (with wwww+1==uuuuu)
  28350. **
  28351. ** Word-0 Word-1 Value
  28352. ** 110110ww wwzzzzyy 110111yy yyxxxxxx 000uuuuu zzzzyyyy yyxxxxxx
  28353. ** zzzzyyyy yyxxxxxx 00000000 zzzzyyyy yyxxxxxx
  28354. **
  28355. **
  28356. ** BOM or Byte Order Mark:
  28357. ** 0xff 0xfe little-endian utf-16 follows
  28358. ** 0xfe 0xff big-endian utf-16 follows
  28359. **
  28360. */
  28361. /* #include "sqliteInt.h" */
  28362. /* #include <assert.h> */
  28363. /* #include "vdbeInt.h" */
  28364. #if !defined(SQLITE_AMALGAMATION) && SQLITE_BYTEORDER==0
  28365. /*
  28366. ** The following constant value is used by the SQLITE_BIGENDIAN and
  28367. ** SQLITE_LITTLEENDIAN macros.
  28368. */
  28369. SQLITE_PRIVATE const int sqlite3one = 1;
  28370. #endif /* SQLITE_AMALGAMATION && SQLITE_BYTEORDER==0 */
  28371. /*
  28372. ** This lookup table is used to help decode the first byte of
  28373. ** a multi-byte UTF8 character.
  28374. */
  28375. static const unsigned char sqlite3Utf8Trans1[] = {
  28376. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  28377. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  28378. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  28379. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  28380. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  28381. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  28382. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  28383. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  28384. };
  28385. #define WRITE_UTF8(zOut, c) { \
  28386. if( c<0x00080 ){ \
  28387. *zOut++ = (u8)(c&0xFF); \
  28388. } \
  28389. else if( c<0x00800 ){ \
  28390. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
  28391. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  28392. } \
  28393. else if( c<0x10000 ){ \
  28394. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
  28395. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  28396. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  28397. }else{ \
  28398. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
  28399. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
  28400. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  28401. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  28402. } \
  28403. }
  28404. #define WRITE_UTF16LE(zOut, c) { \
  28405. if( c<=0xFFFF ){ \
  28406. *zOut++ = (u8)(c&0x00FF); \
  28407. *zOut++ = (u8)((c>>8)&0x00FF); \
  28408. }else{ \
  28409. *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
  28410. *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
  28411. *zOut++ = (u8)(c&0x00FF); \
  28412. *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
  28413. } \
  28414. }
  28415. #define WRITE_UTF16BE(zOut, c) { \
  28416. if( c<=0xFFFF ){ \
  28417. *zOut++ = (u8)((c>>8)&0x00FF); \
  28418. *zOut++ = (u8)(c&0x00FF); \
  28419. }else{ \
  28420. *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
  28421. *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
  28422. *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
  28423. *zOut++ = (u8)(c&0x00FF); \
  28424. } \
  28425. }
  28426. #define READ_UTF16LE(zIn, TERM, c){ \
  28427. c = (*zIn++); \
  28428. c += ((*zIn++)<<8); \
  28429. if( c>=0xD800 && c<0xE000 && TERM ){ \
  28430. int c2 = (*zIn++); \
  28431. c2 += ((*zIn++)<<8); \
  28432. c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
  28433. } \
  28434. }
  28435. #define READ_UTF16BE(zIn, TERM, c){ \
  28436. c = ((*zIn++)<<8); \
  28437. c += (*zIn++); \
  28438. if( c>=0xD800 && c<0xE000 && TERM ){ \
  28439. int c2 = ((*zIn++)<<8); \
  28440. c2 += (*zIn++); \
  28441. c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
  28442. } \
  28443. }
  28444. /*
  28445. ** Translate a single UTF-8 character. Return the unicode value.
  28446. **
  28447. ** During translation, assume that the byte that zTerm points
  28448. ** is a 0x00.
  28449. **
  28450. ** Write a pointer to the next unread byte back into *pzNext.
  28451. **
  28452. ** Notes On Invalid UTF-8:
  28453. **
  28454. ** * This routine never allows a 7-bit character (0x00 through 0x7f) to
  28455. ** be encoded as a multi-byte character. Any multi-byte character that
  28456. ** attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
  28457. **
  28458. ** * This routine never allows a UTF16 surrogate value to be encoded.
  28459. ** If a multi-byte character attempts to encode a value between
  28460. ** 0xd800 and 0xe000 then it is rendered as 0xfffd.
  28461. **
  28462. ** * Bytes in the range of 0x80 through 0xbf which occur as the first
  28463. ** byte of a character are interpreted as single-byte characters
  28464. ** and rendered as themselves even though they are technically
  28465. ** invalid characters.
  28466. **
  28467. ** * This routine accepts over-length UTF8 encodings
  28468. ** for unicode values 0x80 and greater. It does not change over-length
  28469. ** encodings to 0xfffd as some systems recommend.
  28470. */
  28471. #define READ_UTF8(zIn, zTerm, c) \
  28472. c = *(zIn++); \
  28473. if( c>=0xc0 ){ \
  28474. c = sqlite3Utf8Trans1[c-0xc0]; \
  28475. while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
  28476. c = (c<<6) + (0x3f & *(zIn++)); \
  28477. } \
  28478. if( c<0x80 \
  28479. || (c&0xFFFFF800)==0xD800 \
  28480. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
  28481. }
  28482. SQLITE_PRIVATE u32 sqlite3Utf8Read(
  28483. const unsigned char **pz /* Pointer to string from which to read char */
  28484. ){
  28485. unsigned int c;
  28486. /* Same as READ_UTF8() above but without the zTerm parameter.
  28487. ** For this routine, we assume the UTF8 string is always zero-terminated.
  28488. */
  28489. c = *((*pz)++);
  28490. if( c>=0xc0 ){
  28491. c = sqlite3Utf8Trans1[c-0xc0];
  28492. while( (*(*pz) & 0xc0)==0x80 ){
  28493. c = (c<<6) + (0x3f & *((*pz)++));
  28494. }
  28495. if( c<0x80
  28496. || (c&0xFFFFF800)==0xD800
  28497. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; }
  28498. }
  28499. return c;
  28500. }
  28501. /*
  28502. ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
  28503. ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
  28504. */
  28505. /* #define TRANSLATE_TRACE 1 */
  28506. #ifndef SQLITE_OMIT_UTF16
  28507. /*
  28508. ** This routine transforms the internal text encoding used by pMem to
  28509. ** desiredEnc. It is an error if the string is already of the desired
  28510. ** encoding, or if *pMem does not contain a string value.
  28511. */
  28512. SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
  28513. sqlite3_int64 len; /* Maximum length of output string in bytes */
  28514. unsigned char *zOut; /* Output buffer */
  28515. unsigned char *zIn; /* Input iterator */
  28516. unsigned char *zTerm; /* End of input */
  28517. unsigned char *z; /* Output iterator */
  28518. unsigned int c;
  28519. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  28520. assert( pMem->flags&MEM_Str );
  28521. assert( pMem->enc!=desiredEnc );
  28522. assert( pMem->enc!=0 );
  28523. assert( pMem->n>=0 );
  28524. #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
  28525. {
  28526. char zBuf[100];
  28527. sqlite3VdbeMemPrettyPrint(pMem, zBuf);
  28528. fprintf(stderr, "INPUT: %s\n", zBuf);
  28529. }
  28530. #endif
  28531. /* If the translation is between UTF-16 little and big endian, then
  28532. ** all that is required is to swap the byte order. This case is handled
  28533. ** differently from the others.
  28534. */
  28535. if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
  28536. u8 temp;
  28537. int rc;
  28538. rc = sqlite3VdbeMemMakeWriteable(pMem);
  28539. if( rc!=SQLITE_OK ){
  28540. assert( rc==SQLITE_NOMEM );
  28541. return SQLITE_NOMEM_BKPT;
  28542. }
  28543. zIn = (u8*)pMem->z;
  28544. zTerm = &zIn[pMem->n&~1];
  28545. while( zIn<zTerm ){
  28546. temp = *zIn;
  28547. *zIn = *(zIn+1);
  28548. zIn++;
  28549. *zIn++ = temp;
  28550. }
  28551. pMem->enc = desiredEnc;
  28552. goto translate_out;
  28553. }
  28554. /* Set len to the maximum number of bytes required in the output buffer. */
  28555. if( desiredEnc==SQLITE_UTF8 ){
  28556. /* When converting from UTF-16, the maximum growth results from
  28557. ** translating a 2-byte character to a 4-byte UTF-8 character.
  28558. ** A single byte is required for the output string
  28559. ** nul-terminator.
  28560. */
  28561. pMem->n &= ~1;
  28562. len = 2 * (sqlite3_int64)pMem->n + 1;
  28563. }else{
  28564. /* When converting from UTF-8 to UTF-16 the maximum growth is caused
  28565. ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
  28566. ** character. Two bytes are required in the output buffer for the
  28567. ** nul-terminator.
  28568. */
  28569. len = 2 * (sqlite3_int64)pMem->n + 2;
  28570. }
  28571. /* Set zIn to point at the start of the input buffer and zTerm to point 1
  28572. ** byte past the end.
  28573. **
  28574. ** Variable zOut is set to point at the output buffer, space obtained
  28575. ** from sqlite3_malloc().
  28576. */
  28577. zIn = (u8*)pMem->z;
  28578. zTerm = &zIn[pMem->n];
  28579. zOut = sqlite3DbMallocRaw(pMem->db, len);
  28580. if( !zOut ){
  28581. return SQLITE_NOMEM_BKPT;
  28582. }
  28583. z = zOut;
  28584. if( pMem->enc==SQLITE_UTF8 ){
  28585. if( desiredEnc==SQLITE_UTF16LE ){
  28586. /* UTF-8 -> UTF-16 Little-endian */
  28587. while( zIn<zTerm ){
  28588. READ_UTF8(zIn, zTerm, c);
  28589. WRITE_UTF16LE(z, c);
  28590. }
  28591. }else{
  28592. assert( desiredEnc==SQLITE_UTF16BE );
  28593. /* UTF-8 -> UTF-16 Big-endian */
  28594. while( zIn<zTerm ){
  28595. READ_UTF8(zIn, zTerm, c);
  28596. WRITE_UTF16BE(z, c);
  28597. }
  28598. }
  28599. pMem->n = (int)(z - zOut);
  28600. *z++ = 0;
  28601. }else{
  28602. assert( desiredEnc==SQLITE_UTF8 );
  28603. if( pMem->enc==SQLITE_UTF16LE ){
  28604. /* UTF-16 Little-endian -> UTF-8 */
  28605. while( zIn<zTerm ){
  28606. READ_UTF16LE(zIn, zIn<zTerm, c);
  28607. WRITE_UTF8(z, c);
  28608. }
  28609. }else{
  28610. /* UTF-16 Big-endian -> UTF-8 */
  28611. while( zIn<zTerm ){
  28612. READ_UTF16BE(zIn, zIn<zTerm, c);
  28613. WRITE_UTF8(z, c);
  28614. }
  28615. }
  28616. pMem->n = (int)(z - zOut);
  28617. }
  28618. *z = 0;
  28619. assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
  28620. c = pMem->flags;
  28621. sqlite3VdbeMemRelease(pMem);
  28622. pMem->flags = MEM_Str|MEM_Term|(c&(MEM_AffMask|MEM_Subtype));
  28623. pMem->enc = desiredEnc;
  28624. pMem->z = (char*)zOut;
  28625. pMem->zMalloc = pMem->z;
  28626. pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->z);
  28627. translate_out:
  28628. #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
  28629. {
  28630. char zBuf[100];
  28631. sqlite3VdbeMemPrettyPrint(pMem, zBuf);
  28632. fprintf(stderr, "OUTPUT: %s\n", zBuf);
  28633. }
  28634. #endif
  28635. return SQLITE_OK;
  28636. }
  28637. #endif /* SQLITE_OMIT_UTF16 */
  28638. #ifndef SQLITE_OMIT_UTF16
  28639. /*
  28640. ** This routine checks for a byte-order mark at the beginning of the
  28641. ** UTF-16 string stored in *pMem. If one is present, it is removed and
  28642. ** the encoding of the Mem adjusted. This routine does not do any
  28643. ** byte-swapping, it just sets Mem.enc appropriately.
  28644. **
  28645. ** The allocation (static, dynamic etc.) and encoding of the Mem may be
  28646. ** changed by this function.
  28647. */
  28648. SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
  28649. int rc = SQLITE_OK;
  28650. u8 bom = 0;
  28651. assert( pMem->n>=0 );
  28652. if( pMem->n>1 ){
  28653. u8 b1 = *(u8 *)pMem->z;
  28654. u8 b2 = *(((u8 *)pMem->z) + 1);
  28655. if( b1==0xFE && b2==0xFF ){
  28656. bom = SQLITE_UTF16BE;
  28657. }
  28658. if( b1==0xFF && b2==0xFE ){
  28659. bom = SQLITE_UTF16LE;
  28660. }
  28661. }
  28662. if( bom ){
  28663. rc = sqlite3VdbeMemMakeWriteable(pMem);
  28664. if( rc==SQLITE_OK ){
  28665. pMem->n -= 2;
  28666. memmove(pMem->z, &pMem->z[2], pMem->n);
  28667. pMem->z[pMem->n] = '\0';
  28668. pMem->z[pMem->n+1] = '\0';
  28669. pMem->flags |= MEM_Term;
  28670. pMem->enc = bom;
  28671. }
  28672. }
  28673. return rc;
  28674. }
  28675. #endif /* SQLITE_OMIT_UTF16 */
  28676. /*
  28677. ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
  28678. ** return the number of unicode characters in pZ up to (but not including)
  28679. ** the first 0x00 byte. If nByte is not less than zero, return the
  28680. ** number of unicode characters in the first nByte of pZ (or up to
  28681. ** the first 0x00, whichever comes first).
  28682. */
  28683. SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
  28684. int r = 0;
  28685. const u8 *z = (const u8*)zIn;
  28686. const u8 *zTerm;
  28687. if( nByte>=0 ){
  28688. zTerm = &z[nByte];
  28689. }else{
  28690. zTerm = (const u8*)(-1);
  28691. }
  28692. assert( z<=zTerm );
  28693. while( *z!=0 && z<zTerm ){
  28694. SQLITE_SKIP_UTF8(z);
  28695. r++;
  28696. }
  28697. return r;
  28698. }
  28699. /* This test function is not currently used by the automated test-suite.
  28700. ** Hence it is only available in debug builds.
  28701. */
  28702. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  28703. /*
  28704. ** Translate UTF-8 to UTF-8.
  28705. **
  28706. ** This has the effect of making sure that the string is well-formed
  28707. ** UTF-8. Miscoded characters are removed.
  28708. **
  28709. ** The translation is done in-place and aborted if the output
  28710. ** overruns the input.
  28711. */
  28712. SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
  28713. unsigned char *zOut = zIn;
  28714. unsigned char *zStart = zIn;
  28715. u32 c;
  28716. while( zIn[0] && zOut<=zIn ){
  28717. c = sqlite3Utf8Read((const u8**)&zIn);
  28718. if( c!=0xfffd ){
  28719. WRITE_UTF8(zOut, c);
  28720. }
  28721. }
  28722. *zOut = 0;
  28723. return (int)(zOut - zStart);
  28724. }
  28725. #endif
  28726. #ifndef SQLITE_OMIT_UTF16
  28727. /*
  28728. ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
  28729. ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
  28730. ** be freed by the calling function.
  28731. **
  28732. ** NULL is returned if there is an allocation error.
  28733. */
  28734. SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
  28735. Mem m;
  28736. memset(&m, 0, sizeof(m));
  28737. m.db = db;
  28738. sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
  28739. sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
  28740. if( db->mallocFailed ){
  28741. sqlite3VdbeMemRelease(&m);
  28742. m.z = 0;
  28743. }
  28744. assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
  28745. assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
  28746. assert( m.z || db->mallocFailed );
  28747. return m.z;
  28748. }
  28749. /*
  28750. ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
  28751. ** Return the number of bytes in the first nChar unicode characters
  28752. ** in pZ. nChar must be non-negative.
  28753. */
  28754. SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
  28755. int c;
  28756. unsigned char const *z = zIn;
  28757. int n = 0;
  28758. if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
  28759. while( n<nChar ){
  28760. READ_UTF16BE(z, 1, c);
  28761. n++;
  28762. }
  28763. }else{
  28764. while( n<nChar ){
  28765. READ_UTF16LE(z, 1, c);
  28766. n++;
  28767. }
  28768. }
  28769. return (int)(z-(unsigned char const *)zIn);
  28770. }
  28771. #if defined(SQLITE_TEST)
  28772. /*
  28773. ** This routine is called from the TCL test function "translate_selftest".
  28774. ** It checks that the primitives for serializing and deserializing
  28775. ** characters in each encoding are inverses of each other.
  28776. */
  28777. SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
  28778. unsigned int i, t;
  28779. unsigned char zBuf[20];
  28780. unsigned char *z;
  28781. int n;
  28782. unsigned int c;
  28783. for(i=0; i<0x00110000; i++){
  28784. z = zBuf;
  28785. WRITE_UTF8(z, i);
  28786. n = (int)(z-zBuf);
  28787. assert( n>0 && n<=4 );
  28788. z[0] = 0;
  28789. z = zBuf;
  28790. c = sqlite3Utf8Read((const u8**)&z);
  28791. t = i;
  28792. if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
  28793. if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
  28794. assert( c==t );
  28795. assert( (z-zBuf)==n );
  28796. }
  28797. for(i=0; i<0x00110000; i++){
  28798. if( i>=0xD800 && i<0xE000 ) continue;
  28799. z = zBuf;
  28800. WRITE_UTF16LE(z, i);
  28801. n = (int)(z-zBuf);
  28802. assert( n>0 && n<=4 );
  28803. z[0] = 0;
  28804. z = zBuf;
  28805. READ_UTF16LE(z, 1, c);
  28806. assert( c==i );
  28807. assert( (z-zBuf)==n );
  28808. }
  28809. for(i=0; i<0x00110000; i++){
  28810. if( i>=0xD800 && i<0xE000 ) continue;
  28811. z = zBuf;
  28812. WRITE_UTF16BE(z, i);
  28813. n = (int)(z-zBuf);
  28814. assert( n>0 && n<=4 );
  28815. z[0] = 0;
  28816. z = zBuf;
  28817. READ_UTF16BE(z, 1, c);
  28818. assert( c==i );
  28819. assert( (z-zBuf)==n );
  28820. }
  28821. }
  28822. #endif /* SQLITE_TEST */
  28823. #endif /* SQLITE_OMIT_UTF16 */
  28824. /************** End of utf.c *************************************************/
  28825. /************** Begin file util.c ********************************************/
  28826. /*
  28827. ** 2001 September 15
  28828. **
  28829. ** The author disclaims copyright to this source code. In place of
  28830. ** a legal notice, here is a blessing:
  28831. **
  28832. ** May you do good and not evil.
  28833. ** May you find forgiveness for yourself and forgive others.
  28834. ** May you share freely, never taking more than you give.
  28835. **
  28836. *************************************************************************
  28837. ** Utility functions used throughout sqlite.
  28838. **
  28839. ** This file contains functions for allocating memory, comparing
  28840. ** strings, and stuff like that.
  28841. **
  28842. */
  28843. /* #include "sqliteInt.h" */
  28844. /* #include <stdarg.h> */
  28845. #include <math.h>
  28846. /*
  28847. ** Routine needed to support the testcase() macro.
  28848. */
  28849. #ifdef SQLITE_COVERAGE_TEST
  28850. SQLITE_PRIVATE void sqlite3Coverage(int x){
  28851. static unsigned dummy = 0;
  28852. dummy += (unsigned)x;
  28853. }
  28854. #endif
  28855. /*
  28856. ** Calls to sqlite3FaultSim() are used to simulate a failure during testing,
  28857. ** or to bypass normal error detection during testing in order to let
  28858. ** execute proceed futher downstream.
  28859. **
  28860. ** In deployment, sqlite3FaultSim() *always* return SQLITE_OK (0). The
  28861. ** sqlite3FaultSim() function only returns non-zero during testing.
  28862. **
  28863. ** During testing, if the test harness has set a fault-sim callback using
  28864. ** a call to sqlite3_test_control(SQLITE_TESTCTRL_FAULT_INSTALL), then
  28865. ** each call to sqlite3FaultSim() is relayed to that application-supplied
  28866. ** callback and the integer return value form the application-supplied
  28867. ** callback is returned by sqlite3FaultSim().
  28868. **
  28869. ** The integer argument to sqlite3FaultSim() is a code to identify which
  28870. ** sqlite3FaultSim() instance is being invoked. Each call to sqlite3FaultSim()
  28871. ** should have a unique code. To prevent legacy testing applications from
  28872. ** breaking, the codes should not be changed or reused.
  28873. */
  28874. #ifndef SQLITE_UNTESTABLE
  28875. SQLITE_PRIVATE int sqlite3FaultSim(int iTest){
  28876. int (*xCallback)(int) = sqlite3GlobalConfig.xTestCallback;
  28877. return xCallback ? xCallback(iTest) : SQLITE_OK;
  28878. }
  28879. #endif
  28880. #ifndef SQLITE_OMIT_FLOATING_POINT
  28881. /*
  28882. ** Return true if the floating point value is Not a Number (NaN).
  28883. */
  28884. SQLITE_PRIVATE int sqlite3IsNaN(double x){
  28885. u64 y;
  28886. memcpy(&y,&x,sizeof(y));
  28887. return IsNaN(y);
  28888. }
  28889. #endif /* SQLITE_OMIT_FLOATING_POINT */
  28890. /*
  28891. ** Compute a string length that is limited to what can be stored in
  28892. ** lower 30 bits of a 32-bit signed integer.
  28893. **
  28894. ** The value returned will never be negative. Nor will it ever be greater
  28895. ** than the actual length of the string. For very long strings (greater
  28896. ** than 1GiB) the value returned might be less than the true string length.
  28897. */
  28898. SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
  28899. if( z==0 ) return 0;
  28900. return 0x3fffffff & (int)strlen(z);
  28901. }
  28902. /*
  28903. ** Return the declared type of a column. Or return zDflt if the column
  28904. ** has no declared type.
  28905. **
  28906. ** The column type is an extra string stored after the zero-terminator on
  28907. ** the column name if and only if the COLFLAG_HASTYPE flag is set.
  28908. */
  28909. SQLITE_PRIVATE char *sqlite3ColumnType(Column *pCol, char *zDflt){
  28910. if( (pCol->colFlags & COLFLAG_HASTYPE)==0 ) return zDflt;
  28911. return pCol->zName + strlen(pCol->zName) + 1;
  28912. }
  28913. /*
  28914. ** Helper function for sqlite3Error() - called rarely. Broken out into
  28915. ** a separate routine to avoid unnecessary register saves on entry to
  28916. ** sqlite3Error().
  28917. */
  28918. static SQLITE_NOINLINE void sqlite3ErrorFinish(sqlite3 *db, int err_code){
  28919. if( db->pErr ) sqlite3ValueSetNull(db->pErr);
  28920. sqlite3SystemError(db, err_code);
  28921. }
  28922. /*
  28923. ** Set the current error code to err_code and clear any prior error message.
  28924. ** Also set iSysErrno (by calling sqlite3System) if the err_code indicates
  28925. ** that would be appropriate.
  28926. */
  28927. SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code){
  28928. assert( db!=0 );
  28929. db->errCode = err_code;
  28930. if( err_code || db->pErr ) sqlite3ErrorFinish(db, err_code);
  28931. }
  28932. /*
  28933. ** Load the sqlite3.iSysErrno field if that is an appropriate thing
  28934. ** to do based on the SQLite error code in rc.
  28935. */
  28936. SQLITE_PRIVATE void sqlite3SystemError(sqlite3 *db, int rc){
  28937. if( rc==SQLITE_IOERR_NOMEM ) return;
  28938. rc &= 0xff;
  28939. if( rc==SQLITE_CANTOPEN || rc==SQLITE_IOERR ){
  28940. db->iSysErrno = sqlite3OsGetLastError(db->pVfs);
  28941. }
  28942. }
  28943. /*
  28944. ** Set the most recent error code and error string for the sqlite
  28945. ** handle "db". The error code is set to "err_code".
  28946. **
  28947. ** If it is not NULL, string zFormat specifies the format of the
  28948. ** error string in the style of the printf functions: The following
  28949. ** format characters are allowed:
  28950. **
  28951. ** %s Insert a string
  28952. ** %z A string that should be freed after use
  28953. ** %d Insert an integer
  28954. ** %T Insert a token
  28955. ** %S Insert the first element of a SrcList
  28956. **
  28957. ** zFormat and any string tokens that follow it are assumed to be
  28958. ** encoded in UTF-8.
  28959. **
  28960. ** To clear the most recent error for sqlite handle "db", sqlite3Error
  28961. ** should be called with err_code set to SQLITE_OK and zFormat set
  28962. ** to NULL.
  28963. */
  28964. SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3 *db, int err_code, const char *zFormat, ...){
  28965. assert( db!=0 );
  28966. db->errCode = err_code;
  28967. sqlite3SystemError(db, err_code);
  28968. if( zFormat==0 ){
  28969. sqlite3Error(db, err_code);
  28970. }else if( db->pErr || (db->pErr = sqlite3ValueNew(db))!=0 ){
  28971. char *z;
  28972. va_list ap;
  28973. va_start(ap, zFormat);
  28974. z = sqlite3VMPrintf(db, zFormat, ap);
  28975. va_end(ap);
  28976. sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
  28977. }
  28978. }
  28979. /*
  28980. ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
  28981. ** The following formatting characters are allowed:
  28982. **
  28983. ** %s Insert a string
  28984. ** %z A string that should be freed after use
  28985. ** %d Insert an integer
  28986. ** %T Insert a token
  28987. ** %S Insert the first element of a SrcList
  28988. **
  28989. ** This function should be used to report any error that occurs while
  28990. ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
  28991. ** last thing the sqlite3_prepare() function does is copy the error
  28992. ** stored by this function into the database handle using sqlite3Error().
  28993. ** Functions sqlite3Error() or sqlite3ErrorWithMsg() should be used
  28994. ** during statement execution (sqlite3_step() etc.).
  28995. */
  28996. SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
  28997. char *zMsg;
  28998. va_list ap;
  28999. sqlite3 *db = pParse->db;
  29000. va_start(ap, zFormat);
  29001. zMsg = sqlite3VMPrintf(db, zFormat, ap);
  29002. va_end(ap);
  29003. if( db->suppressErr ){
  29004. sqlite3DbFree(db, zMsg);
  29005. }else{
  29006. pParse->nErr++;
  29007. sqlite3DbFree(db, pParse->zErrMsg);
  29008. pParse->zErrMsg = zMsg;
  29009. pParse->rc = SQLITE_ERROR;
  29010. }
  29011. }
  29012. /*
  29013. ** If database connection db is currently parsing SQL, then transfer
  29014. ** error code errCode to that parser if the parser has not already
  29015. ** encountered some other kind of error.
  29016. */
  29017. SQLITE_PRIVATE int sqlite3ErrorToParser(sqlite3 *db, int errCode){
  29018. Parse *pParse;
  29019. if( db==0 || (pParse = db->pParse)==0 ) return errCode;
  29020. pParse->rc = errCode;
  29021. pParse->nErr++;
  29022. return errCode;
  29023. }
  29024. /*
  29025. ** Convert an SQL-style quoted string into a normal string by removing
  29026. ** the quote characters. The conversion is done in-place. If the
  29027. ** input does not begin with a quote character, then this routine
  29028. ** is a no-op.
  29029. **
  29030. ** The input string must be zero-terminated. A new zero-terminator
  29031. ** is added to the dequoted string.
  29032. **
  29033. ** The return value is -1 if no dequoting occurs or the length of the
  29034. ** dequoted string, exclusive of the zero terminator, if dequoting does
  29035. ** occur.
  29036. **
  29037. ** 2002-02-14: This routine is extended to remove MS-Access style
  29038. ** brackets from around identifiers. For example: "[a-b-c]" becomes
  29039. ** "a-b-c".
  29040. */
  29041. SQLITE_PRIVATE void sqlite3Dequote(char *z){
  29042. char quote;
  29043. int i, j;
  29044. if( z==0 ) return;
  29045. quote = z[0];
  29046. if( !sqlite3Isquote(quote) ) return;
  29047. if( quote=='[' ) quote = ']';
  29048. for(i=1, j=0;; i++){
  29049. assert( z[i] );
  29050. if( z[i]==quote ){
  29051. if( z[i+1]==quote ){
  29052. z[j++] = quote;
  29053. i++;
  29054. }else{
  29055. break;
  29056. }
  29057. }else{
  29058. z[j++] = z[i];
  29059. }
  29060. }
  29061. z[j] = 0;
  29062. }
  29063. SQLITE_PRIVATE void sqlite3DequoteExpr(Expr *p){
  29064. assert( sqlite3Isquote(p->u.zToken[0]) );
  29065. p->flags |= p->u.zToken[0]=='"' ? EP_Quoted|EP_DblQuoted : EP_Quoted;
  29066. sqlite3Dequote(p->u.zToken);
  29067. }
  29068. /*
  29069. ** Generate a Token object from a string
  29070. */
  29071. SQLITE_PRIVATE void sqlite3TokenInit(Token *p, char *z){
  29072. p->z = z;
  29073. p->n = sqlite3Strlen30(z);
  29074. }
  29075. /* Convenient short-hand */
  29076. #define UpperToLower sqlite3UpperToLower
  29077. /*
  29078. ** Some systems have stricmp(). Others have strcasecmp(). Because
  29079. ** there is no consistency, we will define our own.
  29080. **
  29081. ** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
  29082. ** sqlite3_strnicmp() APIs allow applications and extensions to compare
  29083. ** the contents of two buffers containing UTF-8 strings in a
  29084. ** case-independent fashion, using the same definition of "case
  29085. ** independence" that SQLite uses internally when comparing identifiers.
  29086. */
  29087. SQLITE_API int sqlite3_stricmp(const char *zLeft, const char *zRight){
  29088. if( zLeft==0 ){
  29089. return zRight ? -1 : 0;
  29090. }else if( zRight==0 ){
  29091. return 1;
  29092. }
  29093. return sqlite3StrICmp(zLeft, zRight);
  29094. }
  29095. SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
  29096. unsigned char *a, *b;
  29097. int c, x;
  29098. a = (unsigned char *)zLeft;
  29099. b = (unsigned char *)zRight;
  29100. for(;;){
  29101. c = *a;
  29102. x = *b;
  29103. if( c==x ){
  29104. if( c==0 ) break;
  29105. }else{
  29106. c = (int)UpperToLower[c] - (int)UpperToLower[x];
  29107. if( c ) break;
  29108. }
  29109. a++;
  29110. b++;
  29111. }
  29112. return c;
  29113. }
  29114. SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
  29115. register unsigned char *a, *b;
  29116. if( zLeft==0 ){
  29117. return zRight ? -1 : 0;
  29118. }else if( zRight==0 ){
  29119. return 1;
  29120. }
  29121. a = (unsigned char *)zLeft;
  29122. b = (unsigned char *)zRight;
  29123. while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
  29124. return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
  29125. }
  29126. /*
  29127. ** Compute 10 to the E-th power. Examples: E==1 results in 10.
  29128. ** E==2 results in 100. E==50 results in 1.0e50.
  29129. **
  29130. ** This routine only works for values of E between 1 and 341.
  29131. */
  29132. static LONGDOUBLE_TYPE sqlite3Pow10(int E){
  29133. #if defined(_MSC_VER)
  29134. static const LONGDOUBLE_TYPE x[] = {
  29135. 1.0e+001L,
  29136. 1.0e+002L,
  29137. 1.0e+004L,
  29138. 1.0e+008L,
  29139. 1.0e+016L,
  29140. 1.0e+032L,
  29141. 1.0e+064L,
  29142. 1.0e+128L,
  29143. 1.0e+256L
  29144. };
  29145. LONGDOUBLE_TYPE r = 1.0;
  29146. int i;
  29147. assert( E>=0 && E<=307 );
  29148. for(i=0; E!=0; i++, E >>=1){
  29149. if( E & 1 ) r *= x[i];
  29150. }
  29151. return r;
  29152. #else
  29153. LONGDOUBLE_TYPE x = 10.0;
  29154. LONGDOUBLE_TYPE r = 1.0;
  29155. while(1){
  29156. if( E & 1 ) r *= x;
  29157. E >>= 1;
  29158. if( E==0 ) break;
  29159. x *= x;
  29160. }
  29161. return r;
  29162. #endif
  29163. }
  29164. /*
  29165. ** The string z[] is an text representation of a real number.
  29166. ** Convert this string to a double and write it into *pResult.
  29167. **
  29168. ** The string z[] is length bytes in length (bytes, not characters) and
  29169. ** uses the encoding enc. The string is not necessarily zero-terminated.
  29170. **
  29171. ** Return TRUE if the result is a valid real number (or integer) and FALSE
  29172. ** if the string is empty or contains extraneous text. More specifically
  29173. ** return
  29174. ** 1 => The input string is a pure integer
  29175. ** 2 or more => The input has a decimal point or eNNN clause
  29176. ** 0 or less => The input string is not a valid number
  29177. ** -1 => Not a valid number, but has a valid prefix which
  29178. ** includes a decimal point and/or an eNNN clause
  29179. **
  29180. ** Valid numbers are in one of these formats:
  29181. **
  29182. ** [+-]digits[E[+-]digits]
  29183. ** [+-]digits.[digits][E[+-]digits]
  29184. ** [+-].digits[E[+-]digits]
  29185. **
  29186. ** Leading and trailing whitespace is ignored for the purpose of determining
  29187. ** validity.
  29188. **
  29189. ** If some prefix of the input string is a valid number, this routine
  29190. ** returns FALSE but it still converts the prefix and writes the result
  29191. ** into *pResult.
  29192. */
  29193. SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
  29194. #ifndef SQLITE_OMIT_FLOATING_POINT
  29195. int incr;
  29196. const char *zEnd = z + length;
  29197. /* sign * significand * (10 ^ (esign * exponent)) */
  29198. int sign = 1; /* sign of significand */
  29199. i64 s = 0; /* significand */
  29200. int d = 0; /* adjust exponent for shifting decimal point */
  29201. int esign = 1; /* sign of exponent */
  29202. int e = 0; /* exponent */
  29203. int eValid = 1; /* True exponent is either not used or is well-formed */
  29204. double result;
  29205. int nDigit = 0; /* Number of digits processed */
  29206. int eType = 1; /* 1: pure integer, 2+: fractional -1 or less: bad UTF16 */
  29207. assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
  29208. *pResult = 0.0; /* Default return value, in case of an error */
  29209. if( enc==SQLITE_UTF8 ){
  29210. incr = 1;
  29211. }else{
  29212. int i;
  29213. incr = 2;
  29214. assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  29215. testcase( enc==SQLITE_UTF16LE );
  29216. testcase( enc==SQLITE_UTF16BE );
  29217. for(i=3-enc; i<length && z[i]==0; i+=2){}
  29218. if( i<length ) eType = -100;
  29219. zEnd = &z[i^1];
  29220. z += (enc&1);
  29221. }
  29222. /* skip leading spaces */
  29223. while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
  29224. if( z>=zEnd ) return 0;
  29225. /* get sign of significand */
  29226. if( *z=='-' ){
  29227. sign = -1;
  29228. z+=incr;
  29229. }else if( *z=='+' ){
  29230. z+=incr;
  29231. }
  29232. /* copy max significant digits to significand */
  29233. while( z<zEnd && sqlite3Isdigit(*z) ){
  29234. s = s*10 + (*z - '0');
  29235. z+=incr; nDigit++;
  29236. if( s>=((LARGEST_INT64-9)/10) ){
  29237. /* skip non-significant significand digits
  29238. ** (increase exponent by d to shift decimal left) */
  29239. while( z<zEnd && sqlite3Isdigit(*z) ){ z+=incr; d++; }
  29240. }
  29241. }
  29242. if( z>=zEnd ) goto do_atof_calc;
  29243. /* if decimal point is present */
  29244. if( *z=='.' ){
  29245. z+=incr;
  29246. eType++;
  29247. /* copy digits from after decimal to significand
  29248. ** (decrease exponent by d to shift decimal right) */
  29249. while( z<zEnd && sqlite3Isdigit(*z) ){
  29250. if( s<((LARGEST_INT64-9)/10) ){
  29251. s = s*10 + (*z - '0');
  29252. d--;
  29253. nDigit++;
  29254. }
  29255. z+=incr;
  29256. }
  29257. }
  29258. if( z>=zEnd ) goto do_atof_calc;
  29259. /* if exponent is present */
  29260. if( *z=='e' || *z=='E' ){
  29261. z+=incr;
  29262. eValid = 0;
  29263. eType++;
  29264. /* This branch is needed to avoid a (harmless) buffer overread. The
  29265. ** special comment alerts the mutation tester that the correct answer
  29266. ** is obtained even if the branch is omitted */
  29267. if( z>=zEnd ) goto do_atof_calc; /*PREVENTS-HARMLESS-OVERREAD*/
  29268. /* get sign of exponent */
  29269. if( *z=='-' ){
  29270. esign = -1;
  29271. z+=incr;
  29272. }else if( *z=='+' ){
  29273. z+=incr;
  29274. }
  29275. /* copy digits to exponent */
  29276. while( z<zEnd && sqlite3Isdigit(*z) ){
  29277. e = e<10000 ? (e*10 + (*z - '0')) : 10000;
  29278. z+=incr;
  29279. eValid = 1;
  29280. }
  29281. }
  29282. /* skip trailing spaces */
  29283. while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
  29284. do_atof_calc:
  29285. /* adjust exponent by d, and update sign */
  29286. e = (e*esign) + d;
  29287. if( e<0 ) {
  29288. esign = -1;
  29289. e *= -1;
  29290. } else {
  29291. esign = 1;
  29292. }
  29293. if( s==0 ) {
  29294. /* In the IEEE 754 standard, zero is signed. */
  29295. result = sign<0 ? -(double)0 : (double)0;
  29296. } else {
  29297. /* Attempt to reduce exponent.
  29298. **
  29299. ** Branches that are not required for the correct answer but which only
  29300. ** help to obtain the correct answer faster are marked with special
  29301. ** comments, as a hint to the mutation tester.
  29302. */
  29303. while( e>0 ){ /*OPTIMIZATION-IF-TRUE*/
  29304. if( esign>0 ){
  29305. if( s>=(LARGEST_INT64/10) ) break; /*OPTIMIZATION-IF-FALSE*/
  29306. s *= 10;
  29307. }else{
  29308. if( s%10!=0 ) break; /*OPTIMIZATION-IF-FALSE*/
  29309. s /= 10;
  29310. }
  29311. e--;
  29312. }
  29313. /* adjust the sign of significand */
  29314. s = sign<0 ? -s : s;
  29315. if( e==0 ){ /*OPTIMIZATION-IF-TRUE*/
  29316. result = (double)s;
  29317. }else{
  29318. /* attempt to handle extremely small/large numbers better */
  29319. if( e>307 ){ /*OPTIMIZATION-IF-TRUE*/
  29320. if( e<342 ){ /*OPTIMIZATION-IF-TRUE*/
  29321. LONGDOUBLE_TYPE scale = sqlite3Pow10(e-308);
  29322. if( esign<0 ){
  29323. result = s / scale;
  29324. result /= 1.0e+308;
  29325. }else{
  29326. result = s * scale;
  29327. result *= 1.0e+308;
  29328. }
  29329. }else{ assert( e>=342 );
  29330. if( esign<0 ){
  29331. result = 0.0*s;
  29332. }else{
  29333. #ifdef INFINITY
  29334. result = INFINITY*s;
  29335. #else
  29336. result = 1e308*1e308*s; /* Infinity */
  29337. #endif
  29338. }
  29339. }
  29340. }else{
  29341. LONGDOUBLE_TYPE scale = sqlite3Pow10(e);
  29342. if( esign<0 ){
  29343. result = s / scale;
  29344. }else{
  29345. result = s * scale;
  29346. }
  29347. }
  29348. }
  29349. }
  29350. /* store the result */
  29351. *pResult = result;
  29352. /* return true if number and no extra non-whitespace chracters after */
  29353. if( z==zEnd && nDigit>0 && eValid && eType>0 ){
  29354. return eType;
  29355. }else if( eType>=2 && (eType==3 || eValid) && nDigit>0 ){
  29356. return -1;
  29357. }else{
  29358. return 0;
  29359. }
  29360. #else
  29361. return !sqlite3Atoi64(z, pResult, length, enc);
  29362. #endif /* SQLITE_OMIT_FLOATING_POINT */
  29363. }
  29364. /*
  29365. ** Compare the 19-character string zNum against the text representation
  29366. ** value 2^63: 9223372036854775808. Return negative, zero, or positive
  29367. ** if zNum is less than, equal to, or greater than the string.
  29368. ** Note that zNum must contain exactly 19 characters.
  29369. **
  29370. ** Unlike memcmp() this routine is guaranteed to return the difference
  29371. ** in the values of the last digit if the only difference is in the
  29372. ** last digit. So, for example,
  29373. **
  29374. ** compare2pow63("9223372036854775800", 1)
  29375. **
  29376. ** will return -8.
  29377. */
  29378. static int compare2pow63(const char *zNum, int incr){
  29379. int c = 0;
  29380. int i;
  29381. /* 012345678901234567 */
  29382. const char *pow63 = "922337203685477580";
  29383. for(i=0; c==0 && i<18; i++){
  29384. c = (zNum[i*incr]-pow63[i])*10;
  29385. }
  29386. if( c==0 ){
  29387. c = zNum[18*incr] - '8';
  29388. testcase( c==(-1) );
  29389. testcase( c==0 );
  29390. testcase( c==(+1) );
  29391. }
  29392. return c;
  29393. }
  29394. /*
  29395. ** Convert zNum to a 64-bit signed integer. zNum must be decimal. This
  29396. ** routine does *not* accept hexadecimal notation.
  29397. **
  29398. ** Returns:
  29399. **
  29400. ** -1 Not even a prefix of the input text looks like an integer
  29401. ** 0 Successful transformation. Fits in a 64-bit signed integer.
  29402. ** 1 Excess non-space text after the integer value
  29403. ** 2 Integer too large for a 64-bit signed integer or is malformed
  29404. ** 3 Special case of 9223372036854775808
  29405. **
  29406. ** length is the number of bytes in the string (bytes, not characters).
  29407. ** The string is not necessarily zero-terminated. The encoding is
  29408. ** given by enc.
  29409. */
  29410. SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
  29411. int incr;
  29412. u64 u = 0;
  29413. int neg = 0; /* assume positive */
  29414. int i;
  29415. int c = 0;
  29416. int nonNum = 0; /* True if input contains UTF16 with high byte non-zero */
  29417. int rc; /* Baseline return code */
  29418. const char *zStart;
  29419. const char *zEnd = zNum + length;
  29420. assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
  29421. if( enc==SQLITE_UTF8 ){
  29422. incr = 1;
  29423. }else{
  29424. incr = 2;
  29425. assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  29426. for(i=3-enc; i<length && zNum[i]==0; i+=2){}
  29427. nonNum = i<length;
  29428. zEnd = &zNum[i^1];
  29429. zNum += (enc&1);
  29430. }
  29431. while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
  29432. if( zNum<zEnd ){
  29433. if( *zNum=='-' ){
  29434. neg = 1;
  29435. zNum+=incr;
  29436. }else if( *zNum=='+' ){
  29437. zNum+=incr;
  29438. }
  29439. }
  29440. zStart = zNum;
  29441. while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
  29442. for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
  29443. u = u*10 + c - '0';
  29444. }
  29445. testcase( i==18*incr );
  29446. testcase( i==19*incr );
  29447. testcase( i==20*incr );
  29448. if( u>LARGEST_INT64 ){
  29449. /* This test and assignment is needed only to suppress UB warnings
  29450. ** from clang and -fsanitize=undefined. This test and assignment make
  29451. ** the code a little larger and slower, and no harm comes from omitting
  29452. ** them, but we must appaise the undefined-behavior pharisees. */
  29453. *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
  29454. }else if( neg ){
  29455. *pNum = -(i64)u;
  29456. }else{
  29457. *pNum = (i64)u;
  29458. }
  29459. rc = 0;
  29460. if( i==0 && zStart==zNum ){ /* No digits */
  29461. rc = -1;
  29462. }else if( nonNum ){ /* UTF16 with high-order bytes non-zero */
  29463. rc = 1;
  29464. }else if( &zNum[i]<zEnd ){ /* Extra bytes at the end */
  29465. int jj = i;
  29466. do{
  29467. if( !sqlite3Isspace(zNum[jj]) ){
  29468. rc = 1; /* Extra non-space text after the integer */
  29469. break;
  29470. }
  29471. jj += incr;
  29472. }while( &zNum[jj]<zEnd );
  29473. }
  29474. if( i<19*incr ){
  29475. /* Less than 19 digits, so we know that it fits in 64 bits */
  29476. assert( u<=LARGEST_INT64 );
  29477. return rc;
  29478. }else{
  29479. /* zNum is a 19-digit numbers. Compare it against 9223372036854775808. */
  29480. c = i>19*incr ? 1 : compare2pow63(zNum, incr);
  29481. if( c<0 ){
  29482. /* zNum is less than 9223372036854775808 so it fits */
  29483. assert( u<=LARGEST_INT64 );
  29484. return rc;
  29485. }else{
  29486. *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
  29487. if( c>0 ){
  29488. /* zNum is greater than 9223372036854775808 so it overflows */
  29489. return 2;
  29490. }else{
  29491. /* zNum is exactly 9223372036854775808. Fits if negative. The
  29492. ** special case 2 overflow if positive */
  29493. assert( u-1==LARGEST_INT64 );
  29494. return neg ? rc : 3;
  29495. }
  29496. }
  29497. }
  29498. }
  29499. /*
  29500. ** Transform a UTF-8 integer literal, in either decimal or hexadecimal,
  29501. ** into a 64-bit signed integer. This routine accepts hexadecimal literals,
  29502. ** whereas sqlite3Atoi64() does not.
  29503. **
  29504. ** Returns:
  29505. **
  29506. ** 0 Successful transformation. Fits in a 64-bit signed integer.
  29507. ** 1 Excess text after the integer value
  29508. ** 2 Integer too large for a 64-bit signed integer or is malformed
  29509. ** 3 Special case of 9223372036854775808
  29510. */
  29511. SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char *z, i64 *pOut){
  29512. #ifndef SQLITE_OMIT_HEX_INTEGER
  29513. if( z[0]=='0'
  29514. && (z[1]=='x' || z[1]=='X')
  29515. ){
  29516. u64 u = 0;
  29517. int i, k;
  29518. for(i=2; z[i]=='0'; i++){}
  29519. for(k=i; sqlite3Isxdigit(z[k]); k++){
  29520. u = u*16 + sqlite3HexToInt(z[k]);
  29521. }
  29522. memcpy(pOut, &u, 8);
  29523. return (z[k]==0 && k-i<=16) ? 0 : 2;
  29524. }else
  29525. #endif /* SQLITE_OMIT_HEX_INTEGER */
  29526. {
  29527. return sqlite3Atoi64(z, pOut, sqlite3Strlen30(z), SQLITE_UTF8);
  29528. }
  29529. }
  29530. /*
  29531. ** If zNum represents an integer that will fit in 32-bits, then set
  29532. ** *pValue to that integer and return true. Otherwise return false.
  29533. **
  29534. ** This routine accepts both decimal and hexadecimal notation for integers.
  29535. **
  29536. ** Any non-numeric characters that following zNum are ignored.
  29537. ** This is different from sqlite3Atoi64() which requires the
  29538. ** input number to be zero-terminated.
  29539. */
  29540. SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
  29541. sqlite_int64 v = 0;
  29542. int i, c;
  29543. int neg = 0;
  29544. if( zNum[0]=='-' ){
  29545. neg = 1;
  29546. zNum++;
  29547. }else if( zNum[0]=='+' ){
  29548. zNum++;
  29549. }
  29550. #ifndef SQLITE_OMIT_HEX_INTEGER
  29551. else if( zNum[0]=='0'
  29552. && (zNum[1]=='x' || zNum[1]=='X')
  29553. && sqlite3Isxdigit(zNum[2])
  29554. ){
  29555. u32 u = 0;
  29556. zNum += 2;
  29557. while( zNum[0]=='0' ) zNum++;
  29558. for(i=0; sqlite3Isxdigit(zNum[i]) && i<8; i++){
  29559. u = u*16 + sqlite3HexToInt(zNum[i]);
  29560. }
  29561. if( (u&0x80000000)==0 && sqlite3Isxdigit(zNum[i])==0 ){
  29562. memcpy(pValue, &u, 4);
  29563. return 1;
  29564. }else{
  29565. return 0;
  29566. }
  29567. }
  29568. #endif
  29569. if( !sqlite3Isdigit(zNum[0]) ) return 0;
  29570. while( zNum[0]=='0' ) zNum++;
  29571. for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
  29572. v = v*10 + c;
  29573. }
  29574. /* The longest decimal representation of a 32 bit integer is 10 digits:
  29575. **
  29576. ** 1234567890
  29577. ** 2^31 -> 2147483648
  29578. */
  29579. testcase( i==10 );
  29580. if( i>10 ){
  29581. return 0;
  29582. }
  29583. testcase( v-neg==2147483647 );
  29584. if( v-neg>2147483647 ){
  29585. return 0;
  29586. }
  29587. if( neg ){
  29588. v = -v;
  29589. }
  29590. *pValue = (int)v;
  29591. return 1;
  29592. }
  29593. /*
  29594. ** Return a 32-bit integer value extracted from a string. If the
  29595. ** string is not an integer, just return 0.
  29596. */
  29597. SQLITE_PRIVATE int sqlite3Atoi(const char *z){
  29598. int x = 0;
  29599. if( z ) sqlite3GetInt32(z, &x);
  29600. return x;
  29601. }
  29602. /*
  29603. ** The variable-length integer encoding is as follows:
  29604. **
  29605. ** KEY:
  29606. ** A = 0xxxxxxx 7 bits of data and one flag bit
  29607. ** B = 1xxxxxxx 7 bits of data and one flag bit
  29608. ** C = xxxxxxxx 8 bits of data
  29609. **
  29610. ** 7 bits - A
  29611. ** 14 bits - BA
  29612. ** 21 bits - BBA
  29613. ** 28 bits - BBBA
  29614. ** 35 bits - BBBBA
  29615. ** 42 bits - BBBBBA
  29616. ** 49 bits - BBBBBBA
  29617. ** 56 bits - BBBBBBBA
  29618. ** 64 bits - BBBBBBBBC
  29619. */
  29620. /*
  29621. ** Write a 64-bit variable-length integer to memory starting at p[0].
  29622. ** The length of data write will be between 1 and 9 bytes. The number
  29623. ** of bytes written is returned.
  29624. **
  29625. ** A variable-length integer consists of the lower 7 bits of each byte
  29626. ** for all bytes that have the 8th bit set and one byte with the 8th
  29627. ** bit clear. Except, if we get to the 9th byte, it stores the full
  29628. ** 8 bits and is the last byte.
  29629. */
  29630. static int SQLITE_NOINLINE putVarint64(unsigned char *p, u64 v){
  29631. int i, j, n;
  29632. u8 buf[10];
  29633. if( v & (((u64)0xff000000)<<32) ){
  29634. p[8] = (u8)v;
  29635. v >>= 8;
  29636. for(i=7; i>=0; i--){
  29637. p[i] = (u8)((v & 0x7f) | 0x80);
  29638. v >>= 7;
  29639. }
  29640. return 9;
  29641. }
  29642. n = 0;
  29643. do{
  29644. buf[n++] = (u8)((v & 0x7f) | 0x80);
  29645. v >>= 7;
  29646. }while( v!=0 );
  29647. buf[0] &= 0x7f;
  29648. assert( n<=9 );
  29649. for(i=0, j=n-1; j>=0; j--, i++){
  29650. p[i] = buf[j];
  29651. }
  29652. return n;
  29653. }
  29654. SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
  29655. if( v<=0x7f ){
  29656. p[0] = v&0x7f;
  29657. return 1;
  29658. }
  29659. if( v<=0x3fff ){
  29660. p[0] = ((v>>7)&0x7f)|0x80;
  29661. p[1] = v&0x7f;
  29662. return 2;
  29663. }
  29664. return putVarint64(p,v);
  29665. }
  29666. /*
  29667. ** Bitmasks used by sqlite3GetVarint(). These precomputed constants
  29668. ** are defined here rather than simply putting the constant expressions
  29669. ** inline in order to work around bugs in the RVT compiler.
  29670. **
  29671. ** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
  29672. **
  29673. ** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
  29674. */
  29675. #define SLOT_2_0 0x001fc07f
  29676. #define SLOT_4_2_0 0xf01fc07f
  29677. /*
  29678. ** Read a 64-bit variable-length integer from memory starting at p[0].
  29679. ** Return the number of bytes read. The value is stored in *v.
  29680. */
  29681. SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
  29682. u32 a,b,s;
  29683. if( ((signed char*)p)[0]>=0 ){
  29684. *v = *p;
  29685. return 1;
  29686. }
  29687. if( ((signed char*)p)[1]>=0 ){
  29688. *v = ((u32)(p[0]&0x7f)<<7) | p[1];
  29689. return 2;
  29690. }
  29691. /* Verify that constants are precomputed correctly */
  29692. assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
  29693. assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
  29694. a = ((u32)p[0])<<14;
  29695. b = p[1];
  29696. p += 2;
  29697. a |= *p;
  29698. /* a: p0<<14 | p2 (unmasked) */
  29699. if (!(a&0x80))
  29700. {
  29701. a &= SLOT_2_0;
  29702. b &= 0x7f;
  29703. b = b<<7;
  29704. a |= b;
  29705. *v = a;
  29706. return 3;
  29707. }
  29708. /* CSE1 from below */
  29709. a &= SLOT_2_0;
  29710. p++;
  29711. b = b<<14;
  29712. b |= *p;
  29713. /* b: p1<<14 | p3 (unmasked) */
  29714. if (!(b&0x80))
  29715. {
  29716. b &= SLOT_2_0;
  29717. /* moved CSE1 up */
  29718. /* a &= (0x7f<<14)|(0x7f); */
  29719. a = a<<7;
  29720. a |= b;
  29721. *v = a;
  29722. return 4;
  29723. }
  29724. /* a: p0<<14 | p2 (masked) */
  29725. /* b: p1<<14 | p3 (unmasked) */
  29726. /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  29727. /* moved CSE1 up */
  29728. /* a &= (0x7f<<14)|(0x7f); */
  29729. b &= SLOT_2_0;
  29730. s = a;
  29731. /* s: p0<<14 | p2 (masked) */
  29732. p++;
  29733. a = a<<14;
  29734. a |= *p;
  29735. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  29736. if (!(a&0x80))
  29737. {
  29738. /* we can skip these cause they were (effectively) done above
  29739. ** while calculating s */
  29740. /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  29741. /* b &= (0x7f<<14)|(0x7f); */
  29742. b = b<<7;
  29743. a |= b;
  29744. s = s>>18;
  29745. *v = ((u64)s)<<32 | a;
  29746. return 5;
  29747. }
  29748. /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  29749. s = s<<7;
  29750. s |= b;
  29751. /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  29752. p++;
  29753. b = b<<14;
  29754. b |= *p;
  29755. /* b: p1<<28 | p3<<14 | p5 (unmasked) */
  29756. if (!(b&0x80))
  29757. {
  29758. /* we can skip this cause it was (effectively) done above in calc'ing s */
  29759. /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  29760. a &= SLOT_2_0;
  29761. a = a<<7;
  29762. a |= b;
  29763. s = s>>18;
  29764. *v = ((u64)s)<<32 | a;
  29765. return 6;
  29766. }
  29767. p++;
  29768. a = a<<14;
  29769. a |= *p;
  29770. /* a: p2<<28 | p4<<14 | p6 (unmasked) */
  29771. if (!(a&0x80))
  29772. {
  29773. a &= SLOT_4_2_0;
  29774. b &= SLOT_2_0;
  29775. b = b<<7;
  29776. a |= b;
  29777. s = s>>11;
  29778. *v = ((u64)s)<<32 | a;
  29779. return 7;
  29780. }
  29781. /* CSE2 from below */
  29782. a &= SLOT_2_0;
  29783. p++;
  29784. b = b<<14;
  29785. b |= *p;
  29786. /* b: p3<<28 | p5<<14 | p7 (unmasked) */
  29787. if (!(b&0x80))
  29788. {
  29789. b &= SLOT_4_2_0;
  29790. /* moved CSE2 up */
  29791. /* a &= (0x7f<<14)|(0x7f); */
  29792. a = a<<7;
  29793. a |= b;
  29794. s = s>>4;
  29795. *v = ((u64)s)<<32 | a;
  29796. return 8;
  29797. }
  29798. p++;
  29799. a = a<<15;
  29800. a |= *p;
  29801. /* a: p4<<29 | p6<<15 | p8 (unmasked) */
  29802. /* moved CSE2 up */
  29803. /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
  29804. b &= SLOT_2_0;
  29805. b = b<<8;
  29806. a |= b;
  29807. s = s<<4;
  29808. b = p[-4];
  29809. b &= 0x7f;
  29810. b = b>>3;
  29811. s |= b;
  29812. *v = ((u64)s)<<32 | a;
  29813. return 9;
  29814. }
  29815. /*
  29816. ** Read a 32-bit variable-length integer from memory starting at p[0].
  29817. ** Return the number of bytes read. The value is stored in *v.
  29818. **
  29819. ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
  29820. ** integer, then set *v to 0xffffffff.
  29821. **
  29822. ** A MACRO version, getVarint32, is provided which inlines the
  29823. ** single-byte case. All code should use the MACRO version as
  29824. ** this function assumes the single-byte case has already been handled.
  29825. */
  29826. SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
  29827. u32 a,b;
  29828. /* The 1-byte case. Overwhelmingly the most common. Handled inline
  29829. ** by the getVarin32() macro */
  29830. a = *p;
  29831. /* a: p0 (unmasked) */
  29832. #ifndef getVarint32
  29833. if (!(a&0x80))
  29834. {
  29835. /* Values between 0 and 127 */
  29836. *v = a;
  29837. return 1;
  29838. }
  29839. #endif
  29840. /* The 2-byte case */
  29841. p++;
  29842. b = *p;
  29843. /* b: p1 (unmasked) */
  29844. if (!(b&0x80))
  29845. {
  29846. /* Values between 128 and 16383 */
  29847. a &= 0x7f;
  29848. a = a<<7;
  29849. *v = a | b;
  29850. return 2;
  29851. }
  29852. /* The 3-byte case */
  29853. p++;
  29854. a = a<<14;
  29855. a |= *p;
  29856. /* a: p0<<14 | p2 (unmasked) */
  29857. if (!(a&0x80))
  29858. {
  29859. /* Values between 16384 and 2097151 */
  29860. a &= (0x7f<<14)|(0x7f);
  29861. b &= 0x7f;
  29862. b = b<<7;
  29863. *v = a | b;
  29864. return 3;
  29865. }
  29866. /* A 32-bit varint is used to store size information in btrees.
  29867. ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
  29868. ** A 3-byte varint is sufficient, for example, to record the size
  29869. ** of a 1048569-byte BLOB or string.
  29870. **
  29871. ** We only unroll the first 1-, 2-, and 3- byte cases. The very
  29872. ** rare larger cases can be handled by the slower 64-bit varint
  29873. ** routine.
  29874. */
  29875. #if 1
  29876. {
  29877. u64 v64;
  29878. u8 n;
  29879. p -= 2;
  29880. n = sqlite3GetVarint(p, &v64);
  29881. assert( n>3 && n<=9 );
  29882. if( (v64 & SQLITE_MAX_U32)!=v64 ){
  29883. *v = 0xffffffff;
  29884. }else{
  29885. *v = (u32)v64;
  29886. }
  29887. return n;
  29888. }
  29889. #else
  29890. /* For following code (kept for historical record only) shows an
  29891. ** unrolling for the 3- and 4-byte varint cases. This code is
  29892. ** slightly faster, but it is also larger and much harder to test.
  29893. */
  29894. p++;
  29895. b = b<<14;
  29896. b |= *p;
  29897. /* b: p1<<14 | p3 (unmasked) */
  29898. if (!(b&0x80))
  29899. {
  29900. /* Values between 2097152 and 268435455 */
  29901. b &= (0x7f<<14)|(0x7f);
  29902. a &= (0x7f<<14)|(0x7f);
  29903. a = a<<7;
  29904. *v = a | b;
  29905. return 4;
  29906. }
  29907. p++;
  29908. a = a<<14;
  29909. a |= *p;
  29910. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  29911. if (!(a&0x80))
  29912. {
  29913. /* Values between 268435456 and 34359738367 */
  29914. a &= SLOT_4_2_0;
  29915. b &= SLOT_4_2_0;
  29916. b = b<<7;
  29917. *v = a | b;
  29918. return 5;
  29919. }
  29920. /* We can only reach this point when reading a corrupt database
  29921. ** file. In that case we are not in any hurry. Use the (relatively
  29922. ** slow) general-purpose sqlite3GetVarint() routine to extract the
  29923. ** value. */
  29924. {
  29925. u64 v64;
  29926. u8 n;
  29927. p -= 4;
  29928. n = sqlite3GetVarint(p, &v64);
  29929. assert( n>5 && n<=9 );
  29930. *v = (u32)v64;
  29931. return n;
  29932. }
  29933. #endif
  29934. }
  29935. /*
  29936. ** Return the number of bytes that will be needed to store the given
  29937. ** 64-bit integer.
  29938. */
  29939. SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
  29940. int i;
  29941. for(i=1; (v >>= 7)!=0; i++){ assert( i<10 ); }
  29942. return i;
  29943. }
  29944. /*
  29945. ** Read or write a four-byte big-endian integer value.
  29946. */
  29947. SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
  29948. #if SQLITE_BYTEORDER==4321
  29949. u32 x;
  29950. memcpy(&x,p,4);
  29951. return x;
  29952. #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  29953. u32 x;
  29954. memcpy(&x,p,4);
  29955. return __builtin_bswap32(x);
  29956. #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  29957. u32 x;
  29958. memcpy(&x,p,4);
  29959. return _byteswap_ulong(x);
  29960. #else
  29961. testcase( p[0]&0x80 );
  29962. return ((unsigned)p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
  29963. #endif
  29964. }
  29965. SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
  29966. #if SQLITE_BYTEORDER==4321
  29967. memcpy(p,&v,4);
  29968. #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  29969. u32 x = __builtin_bswap32(v);
  29970. memcpy(p,&x,4);
  29971. #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  29972. u32 x = _byteswap_ulong(v);
  29973. memcpy(p,&x,4);
  29974. #else
  29975. p[0] = (u8)(v>>24);
  29976. p[1] = (u8)(v>>16);
  29977. p[2] = (u8)(v>>8);
  29978. p[3] = (u8)v;
  29979. #endif
  29980. }
  29981. /*
  29982. ** Translate a single byte of Hex into an integer.
  29983. ** This routine only works if h really is a valid hexadecimal
  29984. ** character: 0..9a..fA..F
  29985. */
  29986. SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
  29987. assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') );
  29988. #ifdef SQLITE_ASCII
  29989. h += 9*(1&(h>>6));
  29990. #endif
  29991. #ifdef SQLITE_EBCDIC
  29992. h += 9*(1&~(h>>4));
  29993. #endif
  29994. return (u8)(h & 0xf);
  29995. }
  29996. #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
  29997. /*
  29998. ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
  29999. ** value. Return a pointer to its binary value. Space to hold the
  30000. ** binary value has been obtained from malloc and must be freed by
  30001. ** the calling routine.
  30002. */
  30003. SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
  30004. char *zBlob;
  30005. int i;
  30006. zBlob = (char *)sqlite3DbMallocRawNN(db, n/2 + 1);
  30007. n--;
  30008. if( zBlob ){
  30009. for(i=0; i<n; i+=2){
  30010. zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
  30011. }
  30012. zBlob[i/2] = 0;
  30013. }
  30014. return zBlob;
  30015. }
  30016. #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
  30017. /*
  30018. ** Log an error that is an API call on a connection pointer that should
  30019. ** not have been used. The "type" of connection pointer is given as the
  30020. ** argument. The zType is a word like "NULL" or "closed" or "invalid".
  30021. */
  30022. static void logBadConnection(const char *zType){
  30023. sqlite3_log(SQLITE_MISUSE,
  30024. "API call with %s database connection pointer",
  30025. zType
  30026. );
  30027. }
  30028. /*
  30029. ** Check to make sure we have a valid db pointer. This test is not
  30030. ** foolproof but it does provide some measure of protection against
  30031. ** misuse of the interface such as passing in db pointers that are
  30032. ** NULL or which have been previously closed. If this routine returns
  30033. ** 1 it means that the db pointer is valid and 0 if it should not be
  30034. ** dereferenced for any reason. The calling function should invoke
  30035. ** SQLITE_MISUSE immediately.
  30036. **
  30037. ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
  30038. ** use. sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
  30039. ** open properly and is not fit for general use but which can be
  30040. ** used as an argument to sqlite3_errmsg() or sqlite3_close().
  30041. */
  30042. SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
  30043. u32 magic;
  30044. if( db==0 ){
  30045. logBadConnection("NULL");
  30046. return 0;
  30047. }
  30048. magic = db->magic;
  30049. if( magic!=SQLITE_MAGIC_OPEN ){
  30050. if( sqlite3SafetyCheckSickOrOk(db) ){
  30051. testcase( sqlite3GlobalConfig.xLog!=0 );
  30052. logBadConnection("unopened");
  30053. }
  30054. return 0;
  30055. }else{
  30056. return 1;
  30057. }
  30058. }
  30059. SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
  30060. u32 magic;
  30061. magic = db->magic;
  30062. if( magic!=SQLITE_MAGIC_SICK &&
  30063. magic!=SQLITE_MAGIC_OPEN &&
  30064. magic!=SQLITE_MAGIC_BUSY ){
  30065. testcase( sqlite3GlobalConfig.xLog!=0 );
  30066. logBadConnection("invalid");
  30067. return 0;
  30068. }else{
  30069. return 1;
  30070. }
  30071. }
  30072. /*
  30073. ** Attempt to add, substract, or multiply the 64-bit signed value iB against
  30074. ** the other 64-bit signed integer at *pA and store the result in *pA.
  30075. ** Return 0 on success. Or if the operation would have resulted in an
  30076. ** overflow, leave *pA unchanged and return 1.
  30077. */
  30078. SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
  30079. #if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
  30080. return __builtin_add_overflow(*pA, iB, pA);
  30081. #else
  30082. i64 iA = *pA;
  30083. testcase( iA==0 ); testcase( iA==1 );
  30084. testcase( iB==-1 ); testcase( iB==0 );
  30085. if( iB>=0 ){
  30086. testcase( iA>0 && LARGEST_INT64 - iA == iB );
  30087. testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
  30088. if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
  30089. }else{
  30090. testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
  30091. testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
  30092. if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
  30093. }
  30094. *pA += iB;
  30095. return 0;
  30096. #endif
  30097. }
  30098. SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
  30099. #if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
  30100. return __builtin_sub_overflow(*pA, iB, pA);
  30101. #else
  30102. testcase( iB==SMALLEST_INT64+1 );
  30103. if( iB==SMALLEST_INT64 ){
  30104. testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
  30105. if( (*pA)>=0 ) return 1;
  30106. *pA -= iB;
  30107. return 0;
  30108. }else{
  30109. return sqlite3AddInt64(pA, -iB);
  30110. }
  30111. #endif
  30112. }
  30113. SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
  30114. #if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
  30115. return __builtin_mul_overflow(*pA, iB, pA);
  30116. #else
  30117. i64 iA = *pA;
  30118. if( iB>0 ){
  30119. if( iA>LARGEST_INT64/iB ) return 1;
  30120. if( iA<SMALLEST_INT64/iB ) return 1;
  30121. }else if( iB<0 ){
  30122. if( iA>0 ){
  30123. if( iB<SMALLEST_INT64/iA ) return 1;
  30124. }else if( iA<0 ){
  30125. if( iB==SMALLEST_INT64 ) return 1;
  30126. if( iA==SMALLEST_INT64 ) return 1;
  30127. if( -iA>LARGEST_INT64/-iB ) return 1;
  30128. }
  30129. }
  30130. *pA = iA*iB;
  30131. return 0;
  30132. #endif
  30133. }
  30134. /*
  30135. ** Compute the absolute value of a 32-bit signed integer, of possible. Or
  30136. ** if the integer has a value of -2147483648, return +2147483647
  30137. */
  30138. SQLITE_PRIVATE int sqlite3AbsInt32(int x){
  30139. if( x>=0 ) return x;
  30140. if( x==(int)0x80000000 ) return 0x7fffffff;
  30141. return -x;
  30142. }
  30143. #ifdef SQLITE_ENABLE_8_3_NAMES
  30144. /*
  30145. ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
  30146. ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
  30147. ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
  30148. ** three characters, then shorten the suffix on z[] to be the last three
  30149. ** characters of the original suffix.
  30150. **
  30151. ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
  30152. ** do the suffix shortening regardless of URI parameter.
  30153. **
  30154. ** Examples:
  30155. **
  30156. ** test.db-journal => test.nal
  30157. ** test.db-wal => test.wal
  30158. ** test.db-shm => test.shm
  30159. ** test.db-mj7f3319fa => test.9fa
  30160. */
  30161. SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
  30162. #if SQLITE_ENABLE_8_3_NAMES<2
  30163. if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
  30164. #endif
  30165. {
  30166. int i, sz;
  30167. sz = sqlite3Strlen30(z);
  30168. for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
  30169. if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
  30170. }
  30171. }
  30172. #endif
  30173. /*
  30174. ** Find (an approximate) sum of two LogEst values. This computation is
  30175. ** not a simple "+" operator because LogEst is stored as a logarithmic
  30176. ** value.
  30177. **
  30178. */
  30179. SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst a, LogEst b){
  30180. static const unsigned char x[] = {
  30181. 10, 10, /* 0,1 */
  30182. 9, 9, /* 2,3 */
  30183. 8, 8, /* 4,5 */
  30184. 7, 7, 7, /* 6,7,8 */
  30185. 6, 6, 6, /* 9,10,11 */
  30186. 5, 5, 5, /* 12-14 */
  30187. 4, 4, 4, 4, /* 15-18 */
  30188. 3, 3, 3, 3, 3, 3, /* 19-24 */
  30189. 2, 2, 2, 2, 2, 2, 2, /* 25-31 */
  30190. };
  30191. if( a>=b ){
  30192. if( a>b+49 ) return a;
  30193. if( a>b+31 ) return a+1;
  30194. return a+x[a-b];
  30195. }else{
  30196. if( b>a+49 ) return b;
  30197. if( b>a+31 ) return b+1;
  30198. return b+x[b-a];
  30199. }
  30200. }
  30201. /*
  30202. ** Convert an integer into a LogEst. In other words, compute an
  30203. ** approximation for 10*log2(x).
  30204. */
  30205. SQLITE_PRIVATE LogEst sqlite3LogEst(u64 x){
  30206. static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
  30207. LogEst y = 40;
  30208. if( x<8 ){
  30209. if( x<2 ) return 0;
  30210. while( x<8 ){ y -= 10; x <<= 1; }
  30211. }else{
  30212. #if GCC_VERSION>=5004000
  30213. int i = 60 - __builtin_clzll(x);
  30214. y += i*10;
  30215. x >>= i;
  30216. #else
  30217. while( x>255 ){ y += 40; x >>= 4; } /*OPTIMIZATION-IF-TRUE*/
  30218. while( x>15 ){ y += 10; x >>= 1; }
  30219. #endif
  30220. }
  30221. return a[x&7] + y - 10;
  30222. }
  30223. #ifndef SQLITE_OMIT_VIRTUALTABLE
  30224. /*
  30225. ** Convert a double into a LogEst
  30226. ** In other words, compute an approximation for 10*log2(x).
  30227. */
  30228. SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double x){
  30229. u64 a;
  30230. LogEst e;
  30231. assert( sizeof(x)==8 && sizeof(a)==8 );
  30232. if( x<=1 ) return 0;
  30233. if( x<=2000000000 ) return sqlite3LogEst((u64)x);
  30234. memcpy(&a, &x, 8);
  30235. e = (a>>52) - 1022;
  30236. return e*10;
  30237. }
  30238. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  30239. #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
  30240. defined(SQLITE_ENABLE_STAT3_OR_STAT4) || \
  30241. defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
  30242. /*
  30243. ** Convert a LogEst into an integer.
  30244. **
  30245. ** Note that this routine is only used when one or more of various
  30246. ** non-standard compile-time options is enabled.
  30247. */
  30248. SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){
  30249. u64 n;
  30250. n = x%10;
  30251. x /= 10;
  30252. if( n>=5 ) n -= 2;
  30253. else if( n>=1 ) n -= 1;
  30254. #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
  30255. defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
  30256. if( x>60 ) return (u64)LARGEST_INT64;
  30257. #else
  30258. /* If only SQLITE_ENABLE_STAT3_OR_STAT4 is on, then the largest input
  30259. ** possible to this routine is 310, resulting in a maximum x of 31 */
  30260. assert( x<=60 );
  30261. #endif
  30262. return x>=3 ? (n+8)<<(x-3) : (n+8)>>(3-x);
  30263. }
  30264. #endif /* defined SCANSTAT or STAT4 or ESTIMATED_ROWS */
  30265. /*
  30266. ** Add a new name/number pair to a VList. This might require that the
  30267. ** VList object be reallocated, so return the new VList. If an OOM
  30268. ** error occurs, the original VList returned and the
  30269. ** db->mallocFailed flag is set.
  30270. **
  30271. ** A VList is really just an array of integers. To destroy a VList,
  30272. ** simply pass it to sqlite3DbFree().
  30273. **
  30274. ** The first integer is the number of integers allocated for the whole
  30275. ** VList. The second integer is the number of integers actually used.
  30276. ** Each name/number pair is encoded by subsequent groups of 3 or more
  30277. ** integers.
  30278. **
  30279. ** Each name/number pair starts with two integers which are the numeric
  30280. ** value for the pair and the size of the name/number pair, respectively.
  30281. ** The text name overlays one or more following integers. The text name
  30282. ** is always zero-terminated.
  30283. **
  30284. ** Conceptually:
  30285. **
  30286. ** struct VList {
  30287. ** int nAlloc; // Number of allocated slots
  30288. ** int nUsed; // Number of used slots
  30289. ** struct VListEntry {
  30290. ** int iValue; // Value for this entry
  30291. ** int nSlot; // Slots used by this entry
  30292. ** // ... variable name goes here
  30293. ** } a[0];
  30294. ** }
  30295. **
  30296. ** During code generation, pointers to the variable names within the
  30297. ** VList are taken. When that happens, nAlloc is set to zero as an
  30298. ** indication that the VList may never again be enlarged, since the
  30299. ** accompanying realloc() would invalidate the pointers.
  30300. */
  30301. SQLITE_PRIVATE VList *sqlite3VListAdd(
  30302. sqlite3 *db, /* The database connection used for malloc() */
  30303. VList *pIn, /* The input VList. Might be NULL */
  30304. const char *zName, /* Name of symbol to add */
  30305. int nName, /* Bytes of text in zName */
  30306. int iVal /* Value to associate with zName */
  30307. ){
  30308. int nInt; /* number of sizeof(int) objects needed for zName */
  30309. char *z; /* Pointer to where zName will be stored */
  30310. int i; /* Index in pIn[] where zName is stored */
  30311. nInt = nName/4 + 3;
  30312. assert( pIn==0 || pIn[0]>=3 ); /* Verify ok to add new elements */
  30313. if( pIn==0 || pIn[1]+nInt > pIn[0] ){
  30314. /* Enlarge the allocation */
  30315. sqlite3_int64 nAlloc = (pIn ? 2*(sqlite3_int64)pIn[0] : 10) + nInt;
  30316. VList *pOut = sqlite3DbRealloc(db, pIn, nAlloc*sizeof(int));
  30317. if( pOut==0 ) return pIn;
  30318. if( pIn==0 ) pOut[1] = 2;
  30319. pIn = pOut;
  30320. pIn[0] = nAlloc;
  30321. }
  30322. i = pIn[1];
  30323. pIn[i] = iVal;
  30324. pIn[i+1] = nInt;
  30325. z = (char*)&pIn[i+2];
  30326. pIn[1] = i+nInt;
  30327. assert( pIn[1]<=pIn[0] );
  30328. memcpy(z, zName, nName);
  30329. z[nName] = 0;
  30330. return pIn;
  30331. }
  30332. /*
  30333. ** Return a pointer to the name of a variable in the given VList that
  30334. ** has the value iVal. Or return a NULL if there is no such variable in
  30335. ** the list
  30336. */
  30337. SQLITE_PRIVATE const char *sqlite3VListNumToName(VList *pIn, int iVal){
  30338. int i, mx;
  30339. if( pIn==0 ) return 0;
  30340. mx = pIn[1];
  30341. i = 2;
  30342. do{
  30343. if( pIn[i]==iVal ) return (char*)&pIn[i+2];
  30344. i += pIn[i+1];
  30345. }while( i<mx );
  30346. return 0;
  30347. }
  30348. /*
  30349. ** Return the number of the variable named zName, if it is in VList.
  30350. ** or return 0 if there is no such variable.
  30351. */
  30352. SQLITE_PRIVATE int sqlite3VListNameToNum(VList *pIn, const char *zName, int nName){
  30353. int i, mx;
  30354. if( pIn==0 ) return 0;
  30355. mx = pIn[1];
  30356. i = 2;
  30357. do{
  30358. const char *z = (const char*)&pIn[i+2];
  30359. if( strncmp(z,zName,nName)==0 && z[nName]==0 ) return pIn[i];
  30360. i += pIn[i+1];
  30361. }while( i<mx );
  30362. return 0;
  30363. }
  30364. /************** End of util.c ************************************************/
  30365. /************** Begin file hash.c ********************************************/
  30366. /*
  30367. ** 2001 September 22
  30368. **
  30369. ** The author disclaims copyright to this source code. In place of
  30370. ** a legal notice, here is a blessing:
  30371. **
  30372. ** May you do good and not evil.
  30373. ** May you find forgiveness for yourself and forgive others.
  30374. ** May you share freely, never taking more than you give.
  30375. **
  30376. *************************************************************************
  30377. ** This is the implementation of generic hash-tables
  30378. ** used in SQLite.
  30379. */
  30380. /* #include "sqliteInt.h" */
  30381. /* #include <assert.h> */
  30382. /* Turn bulk memory into a hash table object by initializing the
  30383. ** fields of the Hash structure.
  30384. **
  30385. ** "pNew" is a pointer to the hash table that is to be initialized.
  30386. */
  30387. SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
  30388. assert( pNew!=0 );
  30389. pNew->first = 0;
  30390. pNew->count = 0;
  30391. pNew->htsize = 0;
  30392. pNew->ht = 0;
  30393. }
  30394. /* Remove all entries from a hash table. Reclaim all memory.
  30395. ** Call this routine to delete a hash table or to reset a hash table
  30396. ** to the empty state.
  30397. */
  30398. SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
  30399. HashElem *elem; /* For looping over all elements of the table */
  30400. assert( pH!=0 );
  30401. elem = pH->first;
  30402. pH->first = 0;
  30403. sqlite3_free(pH->ht);
  30404. pH->ht = 0;
  30405. pH->htsize = 0;
  30406. while( elem ){
  30407. HashElem *next_elem = elem->next;
  30408. sqlite3_free(elem);
  30409. elem = next_elem;
  30410. }
  30411. pH->count = 0;
  30412. }
  30413. /*
  30414. ** The hashing function.
  30415. */
  30416. static unsigned int strHash(const char *z){
  30417. unsigned int h = 0;
  30418. unsigned char c;
  30419. while( (c = (unsigned char)*z++)!=0 ){ /*OPTIMIZATION-IF-TRUE*/
  30420. /* Knuth multiplicative hashing. (Sorting & Searching, p. 510).
  30421. ** 0x9e3779b1 is 2654435761 which is the closest prime number to
  30422. ** (2**32)*golden_ratio, where golden_ratio = (sqrt(5) - 1)/2. */
  30423. h += sqlite3UpperToLower[c];
  30424. h *= 0x9e3779b1;
  30425. }
  30426. return h;
  30427. }
  30428. /* Link pNew element into the hash table pH. If pEntry!=0 then also
  30429. ** insert pNew into the pEntry hash bucket.
  30430. */
  30431. static void insertElement(
  30432. Hash *pH, /* The complete hash table */
  30433. struct _ht *pEntry, /* The entry into which pNew is inserted */
  30434. HashElem *pNew /* The element to be inserted */
  30435. ){
  30436. HashElem *pHead; /* First element already in pEntry */
  30437. if( pEntry ){
  30438. pHead = pEntry->count ? pEntry->chain : 0;
  30439. pEntry->count++;
  30440. pEntry->chain = pNew;
  30441. }else{
  30442. pHead = 0;
  30443. }
  30444. if( pHead ){
  30445. pNew->next = pHead;
  30446. pNew->prev = pHead->prev;
  30447. if( pHead->prev ){ pHead->prev->next = pNew; }
  30448. else { pH->first = pNew; }
  30449. pHead->prev = pNew;
  30450. }else{
  30451. pNew->next = pH->first;
  30452. if( pH->first ){ pH->first->prev = pNew; }
  30453. pNew->prev = 0;
  30454. pH->first = pNew;
  30455. }
  30456. }
  30457. /* Resize the hash table so that it cantains "new_size" buckets.
  30458. **
  30459. ** The hash table might fail to resize if sqlite3_malloc() fails or
  30460. ** if the new size is the same as the prior size.
  30461. ** Return TRUE if the resize occurs and false if not.
  30462. */
  30463. static int rehash(Hash *pH, unsigned int new_size){
  30464. struct _ht *new_ht; /* The new hash table */
  30465. HashElem *elem, *next_elem; /* For looping over existing elements */
  30466. #if SQLITE_MALLOC_SOFT_LIMIT>0
  30467. if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
  30468. new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
  30469. }
  30470. if( new_size==pH->htsize ) return 0;
  30471. #endif
  30472. /* The inability to allocates space for a larger hash table is
  30473. ** a performance hit but it is not a fatal error. So mark the
  30474. ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of
  30475. ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()
  30476. ** only zeroes the requested number of bytes whereas this module will
  30477. ** use the actual amount of space allocated for the hash table (which
  30478. ** may be larger than the requested amount).
  30479. */
  30480. sqlite3BeginBenignMalloc();
  30481. new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
  30482. sqlite3EndBenignMalloc();
  30483. if( new_ht==0 ) return 0;
  30484. sqlite3_free(pH->ht);
  30485. pH->ht = new_ht;
  30486. pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
  30487. memset(new_ht, 0, new_size*sizeof(struct _ht));
  30488. for(elem=pH->first, pH->first=0; elem; elem = next_elem){
  30489. unsigned int h = strHash(elem->pKey) % new_size;
  30490. next_elem = elem->next;
  30491. insertElement(pH, &new_ht[h], elem);
  30492. }
  30493. return 1;
  30494. }
  30495. /* This function (for internal use only) locates an element in an
  30496. ** hash table that matches the given key. If no element is found,
  30497. ** a pointer to a static null element with HashElem.data==0 is returned.
  30498. ** If pH is not NULL, then the hash for this key is written to *pH.
  30499. */
  30500. static HashElem *findElementWithHash(
  30501. const Hash *pH, /* The pH to be searched */
  30502. const char *pKey, /* The key we are searching for */
  30503. unsigned int *pHash /* Write the hash value here */
  30504. ){
  30505. HashElem *elem; /* Used to loop thru the element list */
  30506. unsigned int count; /* Number of elements left to test */
  30507. unsigned int h; /* The computed hash */
  30508. static HashElem nullElement = { 0, 0, 0, 0 };
  30509. if( pH->ht ){ /*OPTIMIZATION-IF-TRUE*/
  30510. struct _ht *pEntry;
  30511. h = strHash(pKey) % pH->htsize;
  30512. pEntry = &pH->ht[h];
  30513. elem = pEntry->chain;
  30514. count = pEntry->count;
  30515. }else{
  30516. h = 0;
  30517. elem = pH->first;
  30518. count = pH->count;
  30519. }
  30520. if( pHash ) *pHash = h;
  30521. while( count-- ){
  30522. assert( elem!=0 );
  30523. if( sqlite3StrICmp(elem->pKey,pKey)==0 ){
  30524. return elem;
  30525. }
  30526. elem = elem->next;
  30527. }
  30528. return &nullElement;
  30529. }
  30530. /* Remove a single entry from the hash table given a pointer to that
  30531. ** element and a hash on the element's key.
  30532. */
  30533. static void removeElementGivenHash(
  30534. Hash *pH, /* The pH containing "elem" */
  30535. HashElem* elem, /* The element to be removed from the pH */
  30536. unsigned int h /* Hash value for the element */
  30537. ){
  30538. struct _ht *pEntry;
  30539. if( elem->prev ){
  30540. elem->prev->next = elem->next;
  30541. }else{
  30542. pH->first = elem->next;
  30543. }
  30544. if( elem->next ){
  30545. elem->next->prev = elem->prev;
  30546. }
  30547. if( pH->ht ){
  30548. pEntry = &pH->ht[h];
  30549. if( pEntry->chain==elem ){
  30550. pEntry->chain = elem->next;
  30551. }
  30552. assert( pEntry->count>0 );
  30553. pEntry->count--;
  30554. }
  30555. sqlite3_free( elem );
  30556. pH->count--;
  30557. if( pH->count==0 ){
  30558. assert( pH->first==0 );
  30559. assert( pH->count==0 );
  30560. sqlite3HashClear(pH);
  30561. }
  30562. }
  30563. /* Attempt to locate an element of the hash table pH with a key
  30564. ** that matches pKey. Return the data for this element if it is
  30565. ** found, or NULL if there is no match.
  30566. */
  30567. SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey){
  30568. assert( pH!=0 );
  30569. assert( pKey!=0 );
  30570. return findElementWithHash(pH, pKey, 0)->data;
  30571. }
  30572. /* Insert an element into the hash table pH. The key is pKey
  30573. ** and the data is "data".
  30574. **
  30575. ** If no element exists with a matching key, then a new
  30576. ** element is created and NULL is returned.
  30577. **
  30578. ** If another element already exists with the same key, then the
  30579. ** new data replaces the old data and the old data is returned.
  30580. ** The key is not copied in this instance. If a malloc fails, then
  30581. ** the new data is returned and the hash table is unchanged.
  30582. **
  30583. ** If the "data" parameter to this function is NULL, then the
  30584. ** element corresponding to "key" is removed from the hash table.
  30585. */
  30586. SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, void *data){
  30587. unsigned int h; /* the hash of the key modulo hash table size */
  30588. HashElem *elem; /* Used to loop thru the element list */
  30589. HashElem *new_elem; /* New element added to the pH */
  30590. assert( pH!=0 );
  30591. assert( pKey!=0 );
  30592. elem = findElementWithHash(pH,pKey,&h);
  30593. if( elem->data ){
  30594. void *old_data = elem->data;
  30595. if( data==0 ){
  30596. removeElementGivenHash(pH,elem,h);
  30597. }else{
  30598. elem->data = data;
  30599. elem->pKey = pKey;
  30600. }
  30601. return old_data;
  30602. }
  30603. if( data==0 ) return 0;
  30604. new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
  30605. if( new_elem==0 ) return data;
  30606. new_elem->pKey = pKey;
  30607. new_elem->data = data;
  30608. pH->count++;
  30609. if( pH->count>=10 && pH->count > 2*pH->htsize ){
  30610. if( rehash(pH, pH->count*2) ){
  30611. assert( pH->htsize>0 );
  30612. h = strHash(pKey) % pH->htsize;
  30613. }
  30614. }
  30615. insertElement(pH, pH->ht ? &pH->ht[h] : 0, new_elem);
  30616. return 0;
  30617. }
  30618. /************** End of hash.c ************************************************/
  30619. /************** Begin file opcodes.c *****************************************/
  30620. /* Automatically generated. Do not edit */
  30621. /* See the tool/mkopcodec.tcl script for details. */
  30622. #if !defined(SQLITE_OMIT_EXPLAIN) \
  30623. || defined(VDBE_PROFILE) \
  30624. || defined(SQLITE_DEBUG)
  30625. #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) || defined(SQLITE_DEBUG)
  30626. # define OpHelp(X) "\0" X
  30627. #else
  30628. # define OpHelp(X)
  30629. #endif
  30630. SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
  30631. static const char *const azName[] = {
  30632. /* 0 */ "Savepoint" OpHelp(""),
  30633. /* 1 */ "AutoCommit" OpHelp(""),
  30634. /* 2 */ "Transaction" OpHelp(""),
  30635. /* 3 */ "SorterNext" OpHelp(""),
  30636. /* 4 */ "Prev" OpHelp(""),
  30637. /* 5 */ "Next" OpHelp(""),
  30638. /* 6 */ "Checkpoint" OpHelp(""),
  30639. /* 7 */ "JournalMode" OpHelp(""),
  30640. /* 8 */ "Vacuum" OpHelp(""),
  30641. /* 9 */ "VFilter" OpHelp("iplan=r[P3] zplan='P4'"),
  30642. /* 10 */ "VUpdate" OpHelp("data=r[P3@P2]"),
  30643. /* 11 */ "Goto" OpHelp(""),
  30644. /* 12 */ "Gosub" OpHelp(""),
  30645. /* 13 */ "InitCoroutine" OpHelp(""),
  30646. /* 14 */ "Yield" OpHelp(""),
  30647. /* 15 */ "MustBeInt" OpHelp(""),
  30648. /* 16 */ "Jump" OpHelp(""),
  30649. /* 17 */ "Once" OpHelp(""),
  30650. /* 18 */ "If" OpHelp(""),
  30651. /* 19 */ "Not" OpHelp("r[P2]= !r[P1]"),
  30652. /* 20 */ "IfNot" OpHelp(""),
  30653. /* 21 */ "IfNullRow" OpHelp("if P1.nullRow then r[P3]=NULL, goto P2"),
  30654. /* 22 */ "SeekLT" OpHelp("key=r[P3@P4]"),
  30655. /* 23 */ "SeekLE" OpHelp("key=r[P3@P4]"),
  30656. /* 24 */ "SeekGE" OpHelp("key=r[P3@P4]"),
  30657. /* 25 */ "SeekGT" OpHelp("key=r[P3@P4]"),
  30658. /* 26 */ "IfNoHope" OpHelp("key=r[P3@P4]"),
  30659. /* 27 */ "NoConflict" OpHelp("key=r[P3@P4]"),
  30660. /* 28 */ "NotFound" OpHelp("key=r[P3@P4]"),
  30661. /* 29 */ "Found" OpHelp("key=r[P3@P4]"),
  30662. /* 30 */ "SeekRowid" OpHelp("intkey=r[P3]"),
  30663. /* 31 */ "NotExists" OpHelp("intkey=r[P3]"),
  30664. /* 32 */ "Last" OpHelp(""),
  30665. /* 33 */ "IfSmaller" OpHelp(""),
  30666. /* 34 */ "SorterSort" OpHelp(""),
  30667. /* 35 */ "Sort" OpHelp(""),
  30668. /* 36 */ "Rewind" OpHelp(""),
  30669. /* 37 */ "IdxLE" OpHelp("key=r[P3@P4]"),
  30670. /* 38 */ "IdxGT" OpHelp("key=r[P3@P4]"),
  30671. /* 39 */ "IdxLT" OpHelp("key=r[P3@P4]"),
  30672. /* 40 */ "IdxGE" OpHelp("key=r[P3@P4]"),
  30673. /* 41 */ "RowSetRead" OpHelp("r[P3]=rowset(P1)"),
  30674. /* 42 */ "RowSetTest" OpHelp("if r[P3] in rowset(P1) goto P2"),
  30675. /* 43 */ "Or" OpHelp("r[P3]=(r[P1] || r[P2])"),
  30676. /* 44 */ "And" OpHelp("r[P3]=(r[P1] && r[P2])"),
  30677. /* 45 */ "Program" OpHelp(""),
  30678. /* 46 */ "FkIfZero" OpHelp("if fkctr[P1]==0 goto P2"),
  30679. /* 47 */ "IfPos" OpHelp("if r[P1]>0 then r[P1]-=P3, goto P2"),
  30680. /* 48 */ "IfNotZero" OpHelp("if r[P1]!=0 then r[P1]--, goto P2"),
  30681. /* 49 */ "DecrJumpZero" OpHelp("if (--r[P1])==0 goto P2"),
  30682. /* 50 */ "IsNull" OpHelp("if r[P1]==NULL goto P2"),
  30683. /* 51 */ "NotNull" OpHelp("if r[P1]!=NULL goto P2"),
  30684. /* 52 */ "Ne" OpHelp("IF r[P3]!=r[P1]"),
  30685. /* 53 */ "Eq" OpHelp("IF r[P3]==r[P1]"),
  30686. /* 54 */ "Gt" OpHelp("IF r[P3]>r[P1]"),
  30687. /* 55 */ "Le" OpHelp("IF r[P3]<=r[P1]"),
  30688. /* 56 */ "Lt" OpHelp("IF r[P3]<r[P1]"),
  30689. /* 57 */ "Ge" OpHelp("IF r[P3]>=r[P1]"),
  30690. /* 58 */ "ElseNotEq" OpHelp(""),
  30691. /* 59 */ "IncrVacuum" OpHelp(""),
  30692. /* 60 */ "VNext" OpHelp(""),
  30693. /* 61 */ "Init" OpHelp("Start at P2"),
  30694. /* 62 */ "PureFunc0" OpHelp(""),
  30695. /* 63 */ "Function0" OpHelp("r[P3]=func(r[P2@P5])"),
  30696. /* 64 */ "PureFunc" OpHelp(""),
  30697. /* 65 */ "Function" OpHelp("r[P3]=func(r[P2@P5])"),
  30698. /* 66 */ "Return" OpHelp(""),
  30699. /* 67 */ "EndCoroutine" OpHelp(""),
  30700. /* 68 */ "HaltIfNull" OpHelp("if r[P3]=null halt"),
  30701. /* 69 */ "Halt" OpHelp(""),
  30702. /* 70 */ "Integer" OpHelp("r[P2]=P1"),
  30703. /* 71 */ "Int64" OpHelp("r[P2]=P4"),
  30704. /* 72 */ "String" OpHelp("r[P2]='P4' (len=P1)"),
  30705. /* 73 */ "Null" OpHelp("r[P2..P3]=NULL"),
  30706. /* 74 */ "SoftNull" OpHelp("r[P1]=NULL"),
  30707. /* 75 */ "Blob" OpHelp("r[P2]=P4 (len=P1)"),
  30708. /* 76 */ "Variable" OpHelp("r[P2]=parameter(P1,P4)"),
  30709. /* 77 */ "Move" OpHelp("r[P2@P3]=r[P1@P3]"),
  30710. /* 78 */ "Copy" OpHelp("r[P2@P3+1]=r[P1@P3+1]"),
  30711. /* 79 */ "SCopy" OpHelp("r[P2]=r[P1]"),
  30712. /* 80 */ "IntCopy" OpHelp("r[P2]=r[P1]"),
  30713. /* 81 */ "ResultRow" OpHelp("output=r[P1@P2]"),
  30714. /* 82 */ "CollSeq" OpHelp(""),
  30715. /* 83 */ "AddImm" OpHelp("r[P1]=r[P1]+P2"),
  30716. /* 84 */ "RealAffinity" OpHelp(""),
  30717. /* 85 */ "Cast" OpHelp("affinity(r[P1])"),
  30718. /* 86 */ "Permutation" OpHelp(""),
  30719. /* 87 */ "Compare" OpHelp("r[P1@P3] <-> r[P2@P3]"),
  30720. /* 88 */ "IsTrue" OpHelp("r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4"),
  30721. /* 89 */ "Offset" OpHelp("r[P3] = sqlite_offset(P1)"),
  30722. /* 90 */ "Column" OpHelp("r[P3]=PX"),
  30723. /* 91 */ "Affinity" OpHelp("affinity(r[P1@P2])"),
  30724. /* 92 */ "MakeRecord" OpHelp("r[P3]=mkrec(r[P1@P2])"),
  30725. /* 93 */ "Count" OpHelp("r[P2]=count()"),
  30726. /* 94 */ "ReadCookie" OpHelp(""),
  30727. /* 95 */ "SetCookie" OpHelp(""),
  30728. /* 96 */ "BitAnd" OpHelp("r[P3]=r[P1]&r[P2]"),
  30729. /* 97 */ "BitOr" OpHelp("r[P3]=r[P1]|r[P2]"),
  30730. /* 98 */ "ShiftLeft" OpHelp("r[P3]=r[P2]<<r[P1]"),
  30731. /* 99 */ "ShiftRight" OpHelp("r[P3]=r[P2]>>r[P1]"),
  30732. /* 100 */ "Add" OpHelp("r[P3]=r[P1]+r[P2]"),
  30733. /* 101 */ "Subtract" OpHelp("r[P3]=r[P2]-r[P1]"),
  30734. /* 102 */ "Multiply" OpHelp("r[P3]=r[P1]*r[P2]"),
  30735. /* 103 */ "Divide" OpHelp("r[P3]=r[P2]/r[P1]"),
  30736. /* 104 */ "Remainder" OpHelp("r[P3]=r[P2]%r[P1]"),
  30737. /* 105 */ "Concat" OpHelp("r[P3]=r[P2]+r[P1]"),
  30738. /* 106 */ "ReopenIdx" OpHelp("root=P2 iDb=P3"),
  30739. /* 107 */ "BitNot" OpHelp("r[P2]= ~r[P1]"),
  30740. /* 108 */ "OpenRead" OpHelp("root=P2 iDb=P3"),
  30741. /* 109 */ "OpenWrite" OpHelp("root=P2 iDb=P3"),
  30742. /* 110 */ "String8" OpHelp("r[P2]='P4'"),
  30743. /* 111 */ "OpenDup" OpHelp(""),
  30744. /* 112 */ "OpenAutoindex" OpHelp("nColumn=P2"),
  30745. /* 113 */ "OpenEphemeral" OpHelp("nColumn=P2"),
  30746. /* 114 */ "SorterOpen" OpHelp(""),
  30747. /* 115 */ "SequenceTest" OpHelp("if( cursor[P1].ctr++ ) pc = P2"),
  30748. /* 116 */ "OpenPseudo" OpHelp("P3 columns in r[P2]"),
  30749. /* 117 */ "Close" OpHelp(""),
  30750. /* 118 */ "ColumnsUsed" OpHelp(""),
  30751. /* 119 */ "SeekHit" OpHelp("seekHit=P2"),
  30752. /* 120 */ "Sequence" OpHelp("r[P2]=cursor[P1].ctr++"),
  30753. /* 121 */ "NewRowid" OpHelp("r[P2]=rowid"),
  30754. /* 122 */ "Insert" OpHelp("intkey=r[P3] data=r[P2]"),
  30755. /* 123 */ "Delete" OpHelp(""),
  30756. /* 124 */ "ResetCount" OpHelp(""),
  30757. /* 125 */ "SorterCompare" OpHelp("if key(P1)!=trim(r[P3],P4) goto P2"),
  30758. /* 126 */ "SorterData" OpHelp("r[P2]=data"),
  30759. /* 127 */ "RowData" OpHelp("r[P2]=data"),
  30760. /* 128 */ "Rowid" OpHelp("r[P2]=rowid"),
  30761. /* 129 */ "NullRow" OpHelp(""),
  30762. /* 130 */ "SeekEnd" OpHelp(""),
  30763. /* 131 */ "SorterInsert" OpHelp("key=r[P2]"),
  30764. /* 132 */ "IdxInsert" OpHelp("key=r[P2]"),
  30765. /* 133 */ "IdxDelete" OpHelp("key=r[P2@P3]"),
  30766. /* 134 */ "DeferredSeek" OpHelp("Move P3 to P1.rowid if needed"),
  30767. /* 135 */ "IdxRowid" OpHelp("r[P2]=rowid"),
  30768. /* 136 */ "Destroy" OpHelp(""),
  30769. /* 137 */ "Clear" OpHelp(""),
  30770. /* 138 */ "ResetSorter" OpHelp(""),
  30771. /* 139 */ "CreateBtree" OpHelp("r[P2]=root iDb=P1 flags=P3"),
  30772. /* 140 */ "SqlExec" OpHelp(""),
  30773. /* 141 */ "ParseSchema" OpHelp(""),
  30774. /* 142 */ "LoadAnalysis" OpHelp(""),
  30775. /* 143 */ "DropTable" OpHelp(""),
  30776. /* 144 */ "DropIndex" OpHelp(""),
  30777. /* 145 */ "Real" OpHelp("r[P2]=P4"),
  30778. /* 146 */ "DropTrigger" OpHelp(""),
  30779. /* 147 */ "IntegrityCk" OpHelp(""),
  30780. /* 148 */ "RowSetAdd" OpHelp("rowset(P1)=r[P2]"),
  30781. /* 149 */ "Param" OpHelp(""),
  30782. /* 150 */ "FkCounter" OpHelp("fkctr[P1]+=P2"),
  30783. /* 151 */ "MemMax" OpHelp("r[P1]=max(r[P1],r[P2])"),
  30784. /* 152 */ "OffsetLimit" OpHelp("if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)"),
  30785. /* 153 */ "AggInverse" OpHelp("accum=r[P3] inverse(r[P2@P5])"),
  30786. /* 154 */ "AggStep" OpHelp("accum=r[P3] step(r[P2@P5])"),
  30787. /* 155 */ "AggStep1" OpHelp("accum=r[P3] step(r[P2@P5])"),
  30788. /* 156 */ "AggValue" OpHelp("r[P3]=value N=P2"),
  30789. /* 157 */ "AggFinal" OpHelp("accum=r[P1] N=P2"),
  30790. /* 158 */ "Expire" OpHelp(""),
  30791. /* 159 */ "TableLock" OpHelp("iDb=P1 root=P2 write=P3"),
  30792. /* 160 */ "VBegin" OpHelp(""),
  30793. /* 161 */ "VCreate" OpHelp(""),
  30794. /* 162 */ "VDestroy" OpHelp(""),
  30795. /* 163 */ "VOpen" OpHelp(""),
  30796. /* 164 */ "VColumn" OpHelp("r[P3]=vcolumn(P2)"),
  30797. /* 165 */ "VRename" OpHelp(""),
  30798. /* 166 */ "Pagecount" OpHelp(""),
  30799. /* 167 */ "MaxPgcnt" OpHelp(""),
  30800. /* 168 */ "Trace" OpHelp(""),
  30801. /* 169 */ "CursorHint" OpHelp(""),
  30802. /* 170 */ "Noop" OpHelp(""),
  30803. /* 171 */ "Explain" OpHelp(""),
  30804. /* 172 */ "Abortable" OpHelp(""),
  30805. };
  30806. return azName[i];
  30807. }
  30808. #endif
  30809. /************** End of opcodes.c *********************************************/
  30810. /************** Begin file os_unix.c *****************************************/
  30811. /*
  30812. ** 2004 May 22
  30813. **
  30814. ** The author disclaims copyright to this source code. In place of
  30815. ** a legal notice, here is a blessing:
  30816. **
  30817. ** May you do good and not evil.
  30818. ** May you find forgiveness for yourself and forgive others.
  30819. ** May you share freely, never taking more than you give.
  30820. **
  30821. ******************************************************************************
  30822. **
  30823. ** This file contains the VFS implementation for unix-like operating systems
  30824. ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
  30825. **
  30826. ** There are actually several different VFS implementations in this file.
  30827. ** The differences are in the way that file locking is done. The default
  30828. ** implementation uses Posix Advisory Locks. Alternative implementations
  30829. ** use flock(), dot-files, various proprietary locking schemas, or simply
  30830. ** skip locking all together.
  30831. **
  30832. ** This source file is organized into divisions where the logic for various
  30833. ** subfunctions is contained within the appropriate division. PLEASE
  30834. ** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
  30835. ** in the correct division and should be clearly labeled.
  30836. **
  30837. ** The layout of divisions is as follows:
  30838. **
  30839. ** * General-purpose declarations and utility functions.
  30840. ** * Unique file ID logic used by VxWorks.
  30841. ** * Various locking primitive implementations (all except proxy locking):
  30842. ** + for Posix Advisory Locks
  30843. ** + for no-op locks
  30844. ** + for dot-file locks
  30845. ** + for flock() locking
  30846. ** + for named semaphore locks (VxWorks only)
  30847. ** + for AFP filesystem locks (MacOSX only)
  30848. ** * sqlite3_file methods not associated with locking.
  30849. ** * Definitions of sqlite3_io_methods objects for all locking
  30850. ** methods plus "finder" functions for each locking method.
  30851. ** * sqlite3_vfs method implementations.
  30852. ** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
  30853. ** * Definitions of sqlite3_vfs objects for all locking methods
  30854. ** plus implementations of sqlite3_os_init() and sqlite3_os_end().
  30855. */
  30856. /* #include "sqliteInt.h" */
  30857. #if SQLITE_OS_UNIX /* This file is used on unix only */
  30858. /*
  30859. ** There are various methods for file locking used for concurrency
  30860. ** control:
  30861. **
  30862. ** 1. POSIX locking (the default),
  30863. ** 2. No locking,
  30864. ** 3. Dot-file locking,
  30865. ** 4. flock() locking,
  30866. ** 5. AFP locking (OSX only),
  30867. ** 6. Named POSIX semaphores (VXWorks only),
  30868. ** 7. proxy locking. (OSX only)
  30869. **
  30870. ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
  30871. ** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
  30872. ** selection of the appropriate locking style based on the filesystem
  30873. ** where the database is located.
  30874. */
  30875. #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
  30876. # if defined(__APPLE__)
  30877. # define SQLITE_ENABLE_LOCKING_STYLE 1
  30878. # else
  30879. # define SQLITE_ENABLE_LOCKING_STYLE 0
  30880. # endif
  30881. #endif
  30882. /* Use pread() and pwrite() if they are available */
  30883. #if defined(__APPLE__)
  30884. # define HAVE_PREAD 1
  30885. # define HAVE_PWRITE 1
  30886. #endif
  30887. #if defined(HAVE_PREAD64) && defined(HAVE_PWRITE64)
  30888. # undef USE_PREAD
  30889. # define USE_PREAD64 1
  30890. #elif defined(HAVE_PREAD) && defined(HAVE_PWRITE)
  30891. # undef USE_PREAD64
  30892. # define USE_PREAD 1
  30893. #endif
  30894. /*
  30895. ** standard include files.
  30896. */
  30897. #include <sys/types.h>
  30898. #include <sys/stat.h>
  30899. #include <fcntl.h>
  30900. #include <sys/ioctl.h>
  30901. #include <unistd.h>
  30902. /* #include <time.h> */
  30903. #include <sys/time.h>
  30904. #include <errno.h>
  30905. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  30906. # include <sys/mman.h>
  30907. #endif
  30908. #if SQLITE_ENABLE_LOCKING_STYLE
  30909. /* # include <sys/ioctl.h> */
  30910. # include <sys/file.h>
  30911. # include <sys/param.h>
  30912. #endif /* SQLITE_ENABLE_LOCKING_STYLE */
  30913. #if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \
  30914. (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000))
  30915. # if (!defined(TARGET_OS_EMBEDDED) || (TARGET_OS_EMBEDDED==0)) \
  30916. && (!defined(TARGET_IPHONE_SIMULATOR) || (TARGET_IPHONE_SIMULATOR==0))
  30917. # define HAVE_GETHOSTUUID 1
  30918. # else
  30919. # warning "gethostuuid() is disabled."
  30920. # endif
  30921. #endif
  30922. #if OS_VXWORKS
  30923. /* # include <sys/ioctl.h> */
  30924. # include <semaphore.h>
  30925. # include <limits.h>
  30926. #endif /* OS_VXWORKS */
  30927. #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
  30928. # include <sys/mount.h>
  30929. #endif
  30930. #ifdef HAVE_UTIME
  30931. # include <utime.h>
  30932. #endif
  30933. /*
  30934. ** Allowed values of unixFile.fsFlags
  30935. */
  30936. #define SQLITE_FSFLAGS_IS_MSDOS 0x1
  30937. /*
  30938. ** If we are to be thread-safe, include the pthreads header.
  30939. */
  30940. #if SQLITE_THREADSAFE
  30941. /* # include <pthread.h> */
  30942. #endif
  30943. /*
  30944. ** Default permissions when creating a new file
  30945. */
  30946. #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
  30947. # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
  30948. #endif
  30949. /*
  30950. ** Default permissions when creating auto proxy dir
  30951. */
  30952. #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
  30953. # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
  30954. #endif
  30955. /*
  30956. ** Maximum supported path-length.
  30957. */
  30958. #define MAX_PATHNAME 512
  30959. /*
  30960. ** Maximum supported symbolic links
  30961. */
  30962. #define SQLITE_MAX_SYMLINKS 100
  30963. /* Always cast the getpid() return type for compatibility with
  30964. ** kernel modules in VxWorks. */
  30965. #define osGetpid(X) (pid_t)getpid()
  30966. /*
  30967. ** Only set the lastErrno if the error code is a real error and not
  30968. ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
  30969. */
  30970. #define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
  30971. /* Forward references */
  30972. typedef struct unixShm unixShm; /* Connection shared memory */
  30973. typedef struct unixShmNode unixShmNode; /* Shared memory instance */
  30974. typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
  30975. typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
  30976. /*
  30977. ** Sometimes, after a file handle is closed by SQLite, the file descriptor
  30978. ** cannot be closed immediately. In these cases, instances of the following
  30979. ** structure are used to store the file descriptor while waiting for an
  30980. ** opportunity to either close or reuse it.
  30981. */
  30982. struct UnixUnusedFd {
  30983. int fd; /* File descriptor to close */
  30984. int flags; /* Flags this file descriptor was opened with */
  30985. UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
  30986. };
  30987. /*
  30988. ** The unixFile structure is subclass of sqlite3_file specific to the unix
  30989. ** VFS implementations.
  30990. */
  30991. typedef struct unixFile unixFile;
  30992. struct unixFile {
  30993. sqlite3_io_methods const *pMethod; /* Always the first entry */
  30994. sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
  30995. unixInodeInfo *pInode; /* Info about locks on this inode */
  30996. int h; /* The file descriptor */
  30997. unsigned char eFileLock; /* The type of lock held on this fd */
  30998. unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
  30999. int lastErrno; /* The unix errno from last I/O error */
  31000. void *lockingContext; /* Locking style specific state */
  31001. UnixUnusedFd *pPreallocatedUnused; /* Pre-allocated UnixUnusedFd */
  31002. const char *zPath; /* Name of the file */
  31003. unixShm *pShm; /* Shared memory segment information */
  31004. int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
  31005. #if SQLITE_MAX_MMAP_SIZE>0
  31006. int nFetchOut; /* Number of outstanding xFetch refs */
  31007. sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
  31008. sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
  31009. sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
  31010. void *pMapRegion; /* Memory mapped region */
  31011. #endif
  31012. int sectorSize; /* Device sector size */
  31013. int deviceCharacteristics; /* Precomputed device characteristics */
  31014. #if SQLITE_ENABLE_LOCKING_STYLE
  31015. int openFlags; /* The flags specified at open() */
  31016. #endif
  31017. #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
  31018. unsigned fsFlags; /* cached details from statfs() */
  31019. #endif
  31020. #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
  31021. unsigned iBusyTimeout; /* Wait this many millisec on locks */
  31022. #endif
  31023. #if OS_VXWORKS
  31024. struct vxworksFileId *pId; /* Unique file ID */
  31025. #endif
  31026. #ifdef SQLITE_DEBUG
  31027. /* The next group of variables are used to track whether or not the
  31028. ** transaction counter in bytes 24-27 of database files are updated
  31029. ** whenever any part of the database changes. An assertion fault will
  31030. ** occur if a file is updated without also updating the transaction
  31031. ** counter. This test is made to avoid new problems similar to the
  31032. ** one described by ticket #3584.
  31033. */
  31034. unsigned char transCntrChng; /* True if the transaction counter changed */
  31035. unsigned char dbUpdate; /* True if any part of database file changed */
  31036. unsigned char inNormalWrite; /* True if in a normal write operation */
  31037. #endif
  31038. #ifdef SQLITE_TEST
  31039. /* In test mode, increase the size of this structure a bit so that
  31040. ** it is larger than the struct CrashFile defined in test6.c.
  31041. */
  31042. char aPadding[32];
  31043. #endif
  31044. };
  31045. /* This variable holds the process id (pid) from when the xRandomness()
  31046. ** method was called. If xOpen() is called from a different process id,
  31047. ** indicating that a fork() has occurred, the PRNG will be reset.
  31048. */
  31049. static pid_t randomnessPid = 0;
  31050. /*
  31051. ** Allowed values for the unixFile.ctrlFlags bitmask:
  31052. */
  31053. #define UNIXFILE_EXCL 0x01 /* Connections from one process only */
  31054. #define UNIXFILE_RDONLY 0x02 /* Connection is read only */
  31055. #define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
  31056. #ifndef SQLITE_DISABLE_DIRSYNC
  31057. # define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
  31058. #else
  31059. # define UNIXFILE_DIRSYNC 0x00
  31060. #endif
  31061. #define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
  31062. #define UNIXFILE_DELETE 0x20 /* Delete on close */
  31063. #define UNIXFILE_URI 0x40 /* Filename might have query parameters */
  31064. #define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
  31065. /*
  31066. ** Include code that is common to all os_*.c files
  31067. */
  31068. /************** Include os_common.h in the middle of os_unix.c ***************/
  31069. /************** Begin file os_common.h ***************************************/
  31070. /*
  31071. ** 2004 May 22
  31072. **
  31073. ** The author disclaims copyright to this source code. In place of
  31074. ** a legal notice, here is a blessing:
  31075. **
  31076. ** May you do good and not evil.
  31077. ** May you find forgiveness for yourself and forgive others.
  31078. ** May you share freely, never taking more than you give.
  31079. **
  31080. ******************************************************************************
  31081. **
  31082. ** This file contains macros and a little bit of code that is common to
  31083. ** all of the platform-specific files (os_*.c) and is #included into those
  31084. ** files.
  31085. **
  31086. ** This file should be #included by the os_*.c files only. It is not a
  31087. ** general purpose header file.
  31088. */
  31089. #ifndef _OS_COMMON_H_
  31090. #define _OS_COMMON_H_
  31091. /*
  31092. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  31093. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  31094. ** switch. The following code should catch this problem at compile-time.
  31095. */
  31096. #ifdef MEMORY_DEBUG
  31097. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  31098. #endif
  31099. /*
  31100. ** Macros for performance tracing. Normally turned off. Only works
  31101. ** on i486 hardware.
  31102. */
  31103. #ifdef SQLITE_PERFORMANCE_TRACE
  31104. /*
  31105. ** hwtime.h contains inline assembler code for implementing
  31106. ** high-performance timing routines.
  31107. */
  31108. /************** Include hwtime.h in the middle of os_common.h ****************/
  31109. /************** Begin file hwtime.h ******************************************/
  31110. /*
  31111. ** 2008 May 27
  31112. **
  31113. ** The author disclaims copyright to this source code. In place of
  31114. ** a legal notice, here is a blessing:
  31115. **
  31116. ** May you do good and not evil.
  31117. ** May you find forgiveness for yourself and forgive others.
  31118. ** May you share freely, never taking more than you give.
  31119. **
  31120. ******************************************************************************
  31121. **
  31122. ** This file contains inline asm code for retrieving "high-performance"
  31123. ** counters for x86 class CPUs.
  31124. */
  31125. #ifndef SQLITE_HWTIME_H
  31126. #define SQLITE_HWTIME_H
  31127. /*
  31128. ** The following routine only works on pentium-class (or newer) processors.
  31129. ** It uses the RDTSC opcode to read the cycle count value out of the
  31130. ** processor and returns that value. This can be used for high-res
  31131. ** profiling.
  31132. */
  31133. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  31134. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  31135. #if defined(__GNUC__)
  31136. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  31137. unsigned int lo, hi;
  31138. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  31139. return (sqlite_uint64)hi << 32 | lo;
  31140. }
  31141. #elif defined(_MSC_VER)
  31142. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  31143. __asm {
  31144. rdtsc
  31145. ret ; return value at EDX:EAX
  31146. }
  31147. }
  31148. #endif
  31149. #elif (defined(__GNUC__) && defined(__x86_64__))
  31150. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  31151. unsigned long val;
  31152. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  31153. return val;
  31154. }
  31155. #elif (defined(__GNUC__) && defined(__ppc__))
  31156. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  31157. unsigned long long retval;
  31158. unsigned long junk;
  31159. __asm__ __volatile__ ("\n\
  31160. 1: mftbu %1\n\
  31161. mftb %L0\n\
  31162. mftbu %0\n\
  31163. cmpw %0,%1\n\
  31164. bne 1b"
  31165. : "=r" (retval), "=r" (junk));
  31166. return retval;
  31167. }
  31168. #else
  31169. #error Need implementation of sqlite3Hwtime() for your platform.
  31170. /*
  31171. ** To compile without implementing sqlite3Hwtime() for your platform,
  31172. ** you can remove the above #error and use the following
  31173. ** stub function. You will lose timing support for many
  31174. ** of the debugging and testing utilities, but it should at
  31175. ** least compile and run.
  31176. */
  31177. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  31178. #endif
  31179. #endif /* !defined(SQLITE_HWTIME_H) */
  31180. /************** End of hwtime.h **********************************************/
  31181. /************** Continuing where we left off in os_common.h ******************/
  31182. static sqlite_uint64 g_start;
  31183. static sqlite_uint64 g_elapsed;
  31184. #define TIMER_START g_start=sqlite3Hwtime()
  31185. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  31186. #define TIMER_ELAPSED g_elapsed
  31187. #else
  31188. #define TIMER_START
  31189. #define TIMER_END
  31190. #define TIMER_ELAPSED ((sqlite_uint64)0)
  31191. #endif
  31192. /*
  31193. ** If we compile with the SQLITE_TEST macro set, then the following block
  31194. ** of code will give us the ability to simulate a disk I/O error. This
  31195. ** is used for testing the I/O recovery logic.
  31196. */
  31197. #if defined(SQLITE_TEST)
  31198. SQLITE_API extern int sqlite3_io_error_hit;
  31199. SQLITE_API extern int sqlite3_io_error_hardhit;
  31200. SQLITE_API extern int sqlite3_io_error_pending;
  31201. SQLITE_API extern int sqlite3_io_error_persist;
  31202. SQLITE_API extern int sqlite3_io_error_benign;
  31203. SQLITE_API extern int sqlite3_diskfull_pending;
  31204. SQLITE_API extern int sqlite3_diskfull;
  31205. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  31206. #define SimulateIOError(CODE) \
  31207. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  31208. || sqlite3_io_error_pending-- == 1 ) \
  31209. { local_ioerr(); CODE; }
  31210. static void local_ioerr(){
  31211. IOTRACE(("IOERR\n"));
  31212. sqlite3_io_error_hit++;
  31213. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  31214. }
  31215. #define SimulateDiskfullError(CODE) \
  31216. if( sqlite3_diskfull_pending ){ \
  31217. if( sqlite3_diskfull_pending == 1 ){ \
  31218. local_ioerr(); \
  31219. sqlite3_diskfull = 1; \
  31220. sqlite3_io_error_hit = 1; \
  31221. CODE; \
  31222. }else{ \
  31223. sqlite3_diskfull_pending--; \
  31224. } \
  31225. }
  31226. #else
  31227. #define SimulateIOErrorBenign(X)
  31228. #define SimulateIOError(A)
  31229. #define SimulateDiskfullError(A)
  31230. #endif /* defined(SQLITE_TEST) */
  31231. /*
  31232. ** When testing, keep a count of the number of open files.
  31233. */
  31234. #if defined(SQLITE_TEST)
  31235. SQLITE_API extern int sqlite3_open_file_count;
  31236. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  31237. #else
  31238. #define OpenCounter(X)
  31239. #endif /* defined(SQLITE_TEST) */
  31240. #endif /* !defined(_OS_COMMON_H_) */
  31241. /************** End of os_common.h *******************************************/
  31242. /************** Continuing where we left off in os_unix.c ********************/
  31243. /*
  31244. ** Define various macros that are missing from some systems.
  31245. */
  31246. #ifndef O_LARGEFILE
  31247. # define O_LARGEFILE 0
  31248. #endif
  31249. #ifdef SQLITE_DISABLE_LFS
  31250. # undef O_LARGEFILE
  31251. # define O_LARGEFILE 0
  31252. #endif
  31253. #ifndef O_NOFOLLOW
  31254. # define O_NOFOLLOW 0
  31255. #endif
  31256. #ifndef O_BINARY
  31257. # define O_BINARY 0
  31258. #endif
  31259. /*
  31260. ** The threadid macro resolves to the thread-id or to 0. Used for
  31261. ** testing and debugging only.
  31262. */
  31263. #if SQLITE_THREADSAFE
  31264. #define threadid pthread_self()
  31265. #else
  31266. #define threadid 0
  31267. #endif
  31268. /*
  31269. ** HAVE_MREMAP defaults to true on Linux and false everywhere else.
  31270. */
  31271. #if !defined(HAVE_MREMAP)
  31272. # if defined(__linux__) && defined(_GNU_SOURCE)
  31273. # define HAVE_MREMAP 1
  31274. # else
  31275. # define HAVE_MREMAP 0
  31276. # endif
  31277. #endif
  31278. /*
  31279. ** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
  31280. ** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
  31281. */
  31282. #ifdef __ANDROID__
  31283. # define lseek lseek64
  31284. #endif
  31285. #ifdef __linux__
  31286. /*
  31287. ** Linux-specific IOCTL magic numbers used for controlling F2FS
  31288. */
  31289. #define F2FS_IOCTL_MAGIC 0xf5
  31290. #define F2FS_IOC_START_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 1)
  31291. #define F2FS_IOC_COMMIT_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 2)
  31292. #define F2FS_IOC_START_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 3)
  31293. #define F2FS_IOC_ABORT_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 5)
  31294. #define F2FS_IOC_GET_FEATURES _IOR(F2FS_IOCTL_MAGIC, 12, u32)
  31295. #define F2FS_FEATURE_ATOMIC_WRITE 0x0004
  31296. #endif /* __linux__ */
  31297. /*
  31298. ** Different Unix systems declare open() in different ways. Same use
  31299. ** open(const char*,int,mode_t). Others use open(const char*,int,...).
  31300. ** The difference is important when using a pointer to the function.
  31301. **
  31302. ** The safest way to deal with the problem is to always use this wrapper
  31303. ** which always has the same well-defined interface.
  31304. */
  31305. static int posixOpen(const char *zFile, int flags, int mode){
  31306. return open(zFile, flags, mode);
  31307. }
  31308. /* Forward reference */
  31309. static int openDirectory(const char*, int*);
  31310. static int unixGetpagesize(void);
  31311. /*
  31312. ** Many system calls are accessed through pointer-to-functions so that
  31313. ** they may be overridden at runtime to facilitate fault injection during
  31314. ** testing and sandboxing. The following array holds the names and pointers
  31315. ** to all overrideable system calls.
  31316. */
  31317. static struct unix_syscall {
  31318. const char *zName; /* Name of the system call */
  31319. sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
  31320. sqlite3_syscall_ptr pDefault; /* Default value */
  31321. } aSyscall[] = {
  31322. { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
  31323. #define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
  31324. { "close", (sqlite3_syscall_ptr)close, 0 },
  31325. #define osClose ((int(*)(int))aSyscall[1].pCurrent)
  31326. { "access", (sqlite3_syscall_ptr)access, 0 },
  31327. #define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
  31328. { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
  31329. #define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
  31330. { "stat", (sqlite3_syscall_ptr)stat, 0 },
  31331. #define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
  31332. /*
  31333. ** The DJGPP compiler environment looks mostly like Unix, but it
  31334. ** lacks the fcntl() system call. So redefine fcntl() to be something
  31335. ** that always succeeds. This means that locking does not occur under
  31336. ** DJGPP. But it is DOS - what did you expect?
  31337. */
  31338. #ifdef __DJGPP__
  31339. { "fstat", 0, 0 },
  31340. #define osFstat(a,b,c) 0
  31341. #else
  31342. { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
  31343. #define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
  31344. #endif
  31345. { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
  31346. #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
  31347. { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
  31348. #define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
  31349. { "read", (sqlite3_syscall_ptr)read, 0 },
  31350. #define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
  31351. #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
  31352. { "pread", (sqlite3_syscall_ptr)pread, 0 },
  31353. #else
  31354. { "pread", (sqlite3_syscall_ptr)0, 0 },
  31355. #endif
  31356. #define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
  31357. #if defined(USE_PREAD64)
  31358. { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
  31359. #else
  31360. { "pread64", (sqlite3_syscall_ptr)0, 0 },
  31361. #endif
  31362. #define osPread64 ((ssize_t(*)(int,void*,size_t,off64_t))aSyscall[10].pCurrent)
  31363. { "write", (sqlite3_syscall_ptr)write, 0 },
  31364. #define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
  31365. #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
  31366. { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
  31367. #else
  31368. { "pwrite", (sqlite3_syscall_ptr)0, 0 },
  31369. #endif
  31370. #define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
  31371. aSyscall[12].pCurrent)
  31372. #if defined(USE_PREAD64)
  31373. { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
  31374. #else
  31375. { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
  31376. #endif
  31377. #define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off64_t))\
  31378. aSyscall[13].pCurrent)
  31379. { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
  31380. #define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
  31381. #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
  31382. { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
  31383. #else
  31384. { "fallocate", (sqlite3_syscall_ptr)0, 0 },
  31385. #endif
  31386. #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
  31387. { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
  31388. #define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
  31389. { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
  31390. #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
  31391. { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
  31392. #define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
  31393. { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
  31394. #define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
  31395. #if defined(HAVE_FCHOWN)
  31396. { "fchown", (sqlite3_syscall_ptr)fchown, 0 },
  31397. #else
  31398. { "fchown", (sqlite3_syscall_ptr)0, 0 },
  31399. #endif
  31400. #define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
  31401. #if defined(HAVE_FCHOWN)
  31402. { "geteuid", (sqlite3_syscall_ptr)geteuid, 0 },
  31403. #else
  31404. { "geteuid", (sqlite3_syscall_ptr)0, 0 },
  31405. #endif
  31406. #define osGeteuid ((uid_t(*)(void))aSyscall[21].pCurrent)
  31407. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  31408. { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
  31409. #else
  31410. { "mmap", (sqlite3_syscall_ptr)0, 0 },
  31411. #endif
  31412. #define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent)
  31413. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  31414. { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
  31415. #else
  31416. { "munmap", (sqlite3_syscall_ptr)0, 0 },
  31417. #endif
  31418. #define osMunmap ((int(*)(void*,size_t))aSyscall[23].pCurrent)
  31419. #if HAVE_MREMAP && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
  31420. { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
  31421. #else
  31422. { "mremap", (sqlite3_syscall_ptr)0, 0 },
  31423. #endif
  31424. #define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[24].pCurrent)
  31425. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  31426. { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 },
  31427. #else
  31428. { "getpagesize", (sqlite3_syscall_ptr)0, 0 },
  31429. #endif
  31430. #define osGetpagesize ((int(*)(void))aSyscall[25].pCurrent)
  31431. #if defined(HAVE_READLINK)
  31432. { "readlink", (sqlite3_syscall_ptr)readlink, 0 },
  31433. #else
  31434. { "readlink", (sqlite3_syscall_ptr)0, 0 },
  31435. #endif
  31436. #define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent)
  31437. #if defined(HAVE_LSTAT)
  31438. { "lstat", (sqlite3_syscall_ptr)lstat, 0 },
  31439. #else
  31440. { "lstat", (sqlite3_syscall_ptr)0, 0 },
  31441. #endif
  31442. #define osLstat ((int(*)(const char*,struct stat*))aSyscall[27].pCurrent)
  31443. #if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
  31444. # ifdef __ANDROID__
  31445. { "ioctl", (sqlite3_syscall_ptr)(int(*)(int, int, ...))ioctl, 0 },
  31446. # else
  31447. { "ioctl", (sqlite3_syscall_ptr)ioctl, 0 },
  31448. # endif
  31449. #else
  31450. { "ioctl", (sqlite3_syscall_ptr)0, 0 },
  31451. #endif
  31452. #define osIoctl ((int(*)(int,int,...))aSyscall[28].pCurrent)
  31453. }; /* End of the overrideable system calls */
  31454. /*
  31455. ** On some systems, calls to fchown() will trigger a message in a security
  31456. ** log if they come from non-root processes. So avoid calling fchown() if
  31457. ** we are not running as root.
  31458. */
  31459. static int robustFchown(int fd, uid_t uid, gid_t gid){
  31460. #if defined(HAVE_FCHOWN)
  31461. return osGeteuid() ? 0 : osFchown(fd,uid,gid);
  31462. #else
  31463. return 0;
  31464. #endif
  31465. }
  31466. /*
  31467. ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
  31468. ** "unix" VFSes. Return SQLITE_OK opon successfully updating the
  31469. ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
  31470. ** system call named zName.
  31471. */
  31472. static int unixSetSystemCall(
  31473. sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
  31474. const char *zName, /* Name of system call to override */
  31475. sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
  31476. ){
  31477. unsigned int i;
  31478. int rc = SQLITE_NOTFOUND;
  31479. UNUSED_PARAMETER(pNotUsed);
  31480. if( zName==0 ){
  31481. /* If no zName is given, restore all system calls to their default
  31482. ** settings and return NULL
  31483. */
  31484. rc = SQLITE_OK;
  31485. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  31486. if( aSyscall[i].pDefault ){
  31487. aSyscall[i].pCurrent = aSyscall[i].pDefault;
  31488. }
  31489. }
  31490. }else{
  31491. /* If zName is specified, operate on only the one system call
  31492. ** specified.
  31493. */
  31494. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  31495. if( strcmp(zName, aSyscall[i].zName)==0 ){
  31496. if( aSyscall[i].pDefault==0 ){
  31497. aSyscall[i].pDefault = aSyscall[i].pCurrent;
  31498. }
  31499. rc = SQLITE_OK;
  31500. if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
  31501. aSyscall[i].pCurrent = pNewFunc;
  31502. break;
  31503. }
  31504. }
  31505. }
  31506. return rc;
  31507. }
  31508. /*
  31509. ** Return the value of a system call. Return NULL if zName is not a
  31510. ** recognized system call name. NULL is also returned if the system call
  31511. ** is currently undefined.
  31512. */
  31513. static sqlite3_syscall_ptr unixGetSystemCall(
  31514. sqlite3_vfs *pNotUsed,
  31515. const char *zName
  31516. ){
  31517. unsigned int i;
  31518. UNUSED_PARAMETER(pNotUsed);
  31519. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  31520. if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
  31521. }
  31522. return 0;
  31523. }
  31524. /*
  31525. ** Return the name of the first system call after zName. If zName==NULL
  31526. ** then return the name of the first system call. Return NULL if zName
  31527. ** is the last system call or if zName is not the name of a valid
  31528. ** system call.
  31529. */
  31530. static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
  31531. int i = -1;
  31532. UNUSED_PARAMETER(p);
  31533. if( zName ){
  31534. for(i=0; i<ArraySize(aSyscall)-1; i++){
  31535. if( strcmp(zName, aSyscall[i].zName)==0 ) break;
  31536. }
  31537. }
  31538. for(i++; i<ArraySize(aSyscall); i++){
  31539. if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
  31540. }
  31541. return 0;
  31542. }
  31543. /*
  31544. ** Do not accept any file descriptor less than this value, in order to avoid
  31545. ** opening database file using file descriptors that are commonly used for
  31546. ** standard input, output, and error.
  31547. */
  31548. #ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
  31549. # define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
  31550. #endif
  31551. /*
  31552. ** Invoke open(). Do so multiple times, until it either succeeds or
  31553. ** fails for some reason other than EINTR.
  31554. **
  31555. ** If the file creation mode "m" is 0 then set it to the default for
  31556. ** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
  31557. ** 0644) as modified by the system umask. If m is not 0, then
  31558. ** make the file creation mode be exactly m ignoring the umask.
  31559. **
  31560. ** The m parameter will be non-zero only when creating -wal, -journal,
  31561. ** and -shm files. We want those files to have *exactly* the same
  31562. ** permissions as their original database, unadulterated by the umask.
  31563. ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
  31564. ** transaction crashes and leaves behind hot journals, then any
  31565. ** process that is able to write to the database will also be able to
  31566. ** recover the hot journals.
  31567. */
  31568. static int robust_open(const char *z, int f, mode_t m){
  31569. int fd;
  31570. mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
  31571. while(1){
  31572. #if defined(O_CLOEXEC)
  31573. fd = osOpen(z,f|O_CLOEXEC,m2);
  31574. #else
  31575. fd = osOpen(z,f,m2);
  31576. #endif
  31577. if( fd<0 ){
  31578. if( errno==EINTR ) continue;
  31579. break;
  31580. }
  31581. if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
  31582. osClose(fd);
  31583. sqlite3_log(SQLITE_WARNING,
  31584. "attempt to open \"%s\" as file descriptor %d", z, fd);
  31585. fd = -1;
  31586. if( osOpen("/dev/null", f, m)<0 ) break;
  31587. }
  31588. if( fd>=0 ){
  31589. if( m!=0 ){
  31590. struct stat statbuf;
  31591. if( osFstat(fd, &statbuf)==0
  31592. && statbuf.st_size==0
  31593. && (statbuf.st_mode&0777)!=m
  31594. ){
  31595. osFchmod(fd, m);
  31596. }
  31597. }
  31598. #if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
  31599. osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
  31600. #endif
  31601. }
  31602. return fd;
  31603. }
  31604. /*
  31605. ** Helper functions to obtain and relinquish the global mutex. The
  31606. ** global mutex is used to protect the unixInodeInfo and
  31607. ** vxworksFileId objects used by this file, all of which may be
  31608. ** shared by multiple threads.
  31609. **
  31610. ** Function unixMutexHeld() is used to assert() that the global mutex
  31611. ** is held when required. This function is only used as part of assert()
  31612. ** statements. e.g.
  31613. **
  31614. ** unixEnterMutex()
  31615. ** assert( unixMutexHeld() );
  31616. ** unixEnterLeave()
  31617. **
  31618. ** To prevent deadlock, the global unixBigLock must must be acquired
  31619. ** before the unixInodeInfo.pLockMutex mutex, if both are held. It is
  31620. ** OK to get the pLockMutex without holding unixBigLock first, but if
  31621. ** that happens, the unixBigLock mutex must not be acquired until after
  31622. ** pLockMutex is released.
  31623. **
  31624. ** OK: enter(unixBigLock), enter(pLockInfo)
  31625. ** OK: enter(unixBigLock)
  31626. ** OK: enter(pLockInfo)
  31627. ** ERROR: enter(pLockInfo), enter(unixBigLock)
  31628. */
  31629. static sqlite3_mutex *unixBigLock = 0;
  31630. static void unixEnterMutex(void){
  31631. assert( sqlite3_mutex_notheld(unixBigLock) ); /* Not a recursive mutex */
  31632. sqlite3_mutex_enter(unixBigLock);
  31633. }
  31634. static void unixLeaveMutex(void){
  31635. assert( sqlite3_mutex_held(unixBigLock) );
  31636. sqlite3_mutex_leave(unixBigLock);
  31637. }
  31638. #ifdef SQLITE_DEBUG
  31639. static int unixMutexHeld(void) {
  31640. return sqlite3_mutex_held(unixBigLock);
  31641. }
  31642. #endif
  31643. #ifdef SQLITE_HAVE_OS_TRACE
  31644. /*
  31645. ** Helper function for printing out trace information from debugging
  31646. ** binaries. This returns the string representation of the supplied
  31647. ** integer lock-type.
  31648. */
  31649. static const char *azFileLock(int eFileLock){
  31650. switch( eFileLock ){
  31651. case NO_LOCK: return "NONE";
  31652. case SHARED_LOCK: return "SHARED";
  31653. case RESERVED_LOCK: return "RESERVED";
  31654. case PENDING_LOCK: return "PENDING";
  31655. case EXCLUSIVE_LOCK: return "EXCLUSIVE";
  31656. }
  31657. return "ERROR";
  31658. }
  31659. #endif
  31660. #ifdef SQLITE_LOCK_TRACE
  31661. /*
  31662. ** Print out information about all locking operations.
  31663. **
  31664. ** This routine is used for troubleshooting locks on multithreaded
  31665. ** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
  31666. ** command-line option on the compiler. This code is normally
  31667. ** turned off.
  31668. */
  31669. static int lockTrace(int fd, int op, struct flock *p){
  31670. char *zOpName, *zType;
  31671. int s;
  31672. int savedErrno;
  31673. if( op==F_GETLK ){
  31674. zOpName = "GETLK";
  31675. }else if( op==F_SETLK ){
  31676. zOpName = "SETLK";
  31677. }else{
  31678. s = osFcntl(fd, op, p);
  31679. sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
  31680. return s;
  31681. }
  31682. if( p->l_type==F_RDLCK ){
  31683. zType = "RDLCK";
  31684. }else if( p->l_type==F_WRLCK ){
  31685. zType = "WRLCK";
  31686. }else if( p->l_type==F_UNLCK ){
  31687. zType = "UNLCK";
  31688. }else{
  31689. assert( 0 );
  31690. }
  31691. assert( p->l_whence==SEEK_SET );
  31692. s = osFcntl(fd, op, p);
  31693. savedErrno = errno;
  31694. sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
  31695. threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
  31696. (int)p->l_pid, s);
  31697. if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
  31698. struct flock l2;
  31699. l2 = *p;
  31700. osFcntl(fd, F_GETLK, &l2);
  31701. if( l2.l_type==F_RDLCK ){
  31702. zType = "RDLCK";
  31703. }else if( l2.l_type==F_WRLCK ){
  31704. zType = "WRLCK";
  31705. }else if( l2.l_type==F_UNLCK ){
  31706. zType = "UNLCK";
  31707. }else{
  31708. assert( 0 );
  31709. }
  31710. sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
  31711. zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
  31712. }
  31713. errno = savedErrno;
  31714. return s;
  31715. }
  31716. #undef osFcntl
  31717. #define osFcntl lockTrace
  31718. #endif /* SQLITE_LOCK_TRACE */
  31719. /*
  31720. ** Retry ftruncate() calls that fail due to EINTR
  31721. **
  31722. ** All calls to ftruncate() within this file should be made through
  31723. ** this wrapper. On the Android platform, bypassing the logic below
  31724. ** could lead to a corrupt database.
  31725. */
  31726. static int robust_ftruncate(int h, sqlite3_int64 sz){
  31727. int rc;
  31728. #ifdef __ANDROID__
  31729. /* On Android, ftruncate() always uses 32-bit offsets, even if
  31730. ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
  31731. ** truncate a file to any size larger than 2GiB. Silently ignore any
  31732. ** such attempts. */
  31733. if( sz>(sqlite3_int64)0x7FFFFFFF ){
  31734. rc = SQLITE_OK;
  31735. }else
  31736. #endif
  31737. do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
  31738. return rc;
  31739. }
  31740. /*
  31741. ** This routine translates a standard POSIX errno code into something
  31742. ** useful to the clients of the sqlite3 functions. Specifically, it is
  31743. ** intended to translate a variety of "try again" errors into SQLITE_BUSY
  31744. ** and a variety of "please close the file descriptor NOW" errors into
  31745. ** SQLITE_IOERR
  31746. **
  31747. ** Errors during initialization of locks, or file system support for locks,
  31748. ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
  31749. */
  31750. static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
  31751. assert( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
  31752. (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
  31753. (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
  31754. (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) );
  31755. switch (posixError) {
  31756. case EACCES:
  31757. case EAGAIN:
  31758. case ETIMEDOUT:
  31759. case EBUSY:
  31760. case EINTR:
  31761. case ENOLCK:
  31762. /* random NFS retry error, unless during file system support
  31763. * introspection, in which it actually means what it says */
  31764. return SQLITE_BUSY;
  31765. case EPERM:
  31766. return SQLITE_PERM;
  31767. default:
  31768. return sqliteIOErr;
  31769. }
  31770. }
  31771. /******************************************************************************
  31772. ****************** Begin Unique File ID Utility Used By VxWorks ***************
  31773. **
  31774. ** On most versions of unix, we can get a unique ID for a file by concatenating
  31775. ** the device number and the inode number. But this does not work on VxWorks.
  31776. ** On VxWorks, a unique file id must be based on the canonical filename.
  31777. **
  31778. ** A pointer to an instance of the following structure can be used as a
  31779. ** unique file ID in VxWorks. Each instance of this structure contains
  31780. ** a copy of the canonical filename. There is also a reference count.
  31781. ** The structure is reclaimed when the number of pointers to it drops to
  31782. ** zero.
  31783. **
  31784. ** There are never very many files open at one time and lookups are not
  31785. ** a performance-critical path, so it is sufficient to put these
  31786. ** structures on a linked list.
  31787. */
  31788. struct vxworksFileId {
  31789. struct vxworksFileId *pNext; /* Next in a list of them all */
  31790. int nRef; /* Number of references to this one */
  31791. int nName; /* Length of the zCanonicalName[] string */
  31792. char *zCanonicalName; /* Canonical filename */
  31793. };
  31794. #if OS_VXWORKS
  31795. /*
  31796. ** All unique filenames are held on a linked list headed by this
  31797. ** variable:
  31798. */
  31799. static struct vxworksFileId *vxworksFileList = 0;
  31800. /*
  31801. ** Simplify a filename into its canonical form
  31802. ** by making the following changes:
  31803. **
  31804. ** * removing any trailing and duplicate /
  31805. ** * convert /./ into just /
  31806. ** * convert /A/../ where A is any simple name into just /
  31807. **
  31808. ** Changes are made in-place. Return the new name length.
  31809. **
  31810. ** The original filename is in z[0..n-1]. Return the number of
  31811. ** characters in the simplified name.
  31812. */
  31813. static int vxworksSimplifyName(char *z, int n){
  31814. int i, j;
  31815. while( n>1 && z[n-1]=='/' ){ n--; }
  31816. for(i=j=0; i<n; i++){
  31817. if( z[i]=='/' ){
  31818. if( z[i+1]=='/' ) continue;
  31819. if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
  31820. i += 1;
  31821. continue;
  31822. }
  31823. if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
  31824. while( j>0 && z[j-1]!='/' ){ j--; }
  31825. if( j>0 ){ j--; }
  31826. i += 2;
  31827. continue;
  31828. }
  31829. }
  31830. z[j++] = z[i];
  31831. }
  31832. z[j] = 0;
  31833. return j;
  31834. }
  31835. /*
  31836. ** Find a unique file ID for the given absolute pathname. Return
  31837. ** a pointer to the vxworksFileId object. This pointer is the unique
  31838. ** file ID.
  31839. **
  31840. ** The nRef field of the vxworksFileId object is incremented before
  31841. ** the object is returned. A new vxworksFileId object is created
  31842. ** and added to the global list if necessary.
  31843. **
  31844. ** If a memory allocation error occurs, return NULL.
  31845. */
  31846. static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
  31847. struct vxworksFileId *pNew; /* search key and new file ID */
  31848. struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
  31849. int n; /* Length of zAbsoluteName string */
  31850. assert( zAbsoluteName[0]=='/' );
  31851. n = (int)strlen(zAbsoluteName);
  31852. pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
  31853. if( pNew==0 ) return 0;
  31854. pNew->zCanonicalName = (char*)&pNew[1];
  31855. memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
  31856. n = vxworksSimplifyName(pNew->zCanonicalName, n);
  31857. /* Search for an existing entry that matching the canonical name.
  31858. ** If found, increment the reference count and return a pointer to
  31859. ** the existing file ID.
  31860. */
  31861. unixEnterMutex();
  31862. for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
  31863. if( pCandidate->nName==n
  31864. && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
  31865. ){
  31866. sqlite3_free(pNew);
  31867. pCandidate->nRef++;
  31868. unixLeaveMutex();
  31869. return pCandidate;
  31870. }
  31871. }
  31872. /* No match was found. We will make a new file ID */
  31873. pNew->nRef = 1;
  31874. pNew->nName = n;
  31875. pNew->pNext = vxworksFileList;
  31876. vxworksFileList = pNew;
  31877. unixLeaveMutex();
  31878. return pNew;
  31879. }
  31880. /*
  31881. ** Decrement the reference count on a vxworksFileId object. Free
  31882. ** the object when the reference count reaches zero.
  31883. */
  31884. static void vxworksReleaseFileId(struct vxworksFileId *pId){
  31885. unixEnterMutex();
  31886. assert( pId->nRef>0 );
  31887. pId->nRef--;
  31888. if( pId->nRef==0 ){
  31889. struct vxworksFileId **pp;
  31890. for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
  31891. assert( *pp==pId );
  31892. *pp = pId->pNext;
  31893. sqlite3_free(pId);
  31894. }
  31895. unixLeaveMutex();
  31896. }
  31897. #endif /* OS_VXWORKS */
  31898. /*************** End of Unique File ID Utility Used By VxWorks ****************
  31899. ******************************************************************************/
  31900. /******************************************************************************
  31901. *************************** Posix Advisory Locking ****************************
  31902. **
  31903. ** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
  31904. ** section 6.5.2.2 lines 483 through 490 specify that when a process
  31905. ** sets or clears a lock, that operation overrides any prior locks set
  31906. ** by the same process. It does not explicitly say so, but this implies
  31907. ** that it overrides locks set by the same process using a different
  31908. ** file descriptor. Consider this test case:
  31909. **
  31910. ** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
  31911. ** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
  31912. **
  31913. ** Suppose ./file1 and ./file2 are really the same file (because
  31914. ** one is a hard or symbolic link to the other) then if you set
  31915. ** an exclusive lock on fd1, then try to get an exclusive lock
  31916. ** on fd2, it works. I would have expected the second lock to
  31917. ** fail since there was already a lock on the file due to fd1.
  31918. ** But not so. Since both locks came from the same process, the
  31919. ** second overrides the first, even though they were on different
  31920. ** file descriptors opened on different file names.
  31921. **
  31922. ** This means that we cannot use POSIX locks to synchronize file access
  31923. ** among competing threads of the same process. POSIX locks will work fine
  31924. ** to synchronize access for threads in separate processes, but not
  31925. ** threads within the same process.
  31926. **
  31927. ** To work around the problem, SQLite has to manage file locks internally
  31928. ** on its own. Whenever a new database is opened, we have to find the
  31929. ** specific inode of the database file (the inode is determined by the
  31930. ** st_dev and st_ino fields of the stat structure that fstat() fills in)
  31931. ** and check for locks already existing on that inode. When locks are
  31932. ** created or removed, we have to look at our own internal record of the
  31933. ** locks to see if another thread has previously set a lock on that same
  31934. ** inode.
  31935. **
  31936. ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
  31937. ** For VxWorks, we have to use the alternative unique ID system based on
  31938. ** canonical filename and implemented in the previous division.)
  31939. **
  31940. ** The sqlite3_file structure for POSIX is no longer just an integer file
  31941. ** descriptor. It is now a structure that holds the integer file
  31942. ** descriptor and a pointer to a structure that describes the internal
  31943. ** locks on the corresponding inode. There is one locking structure
  31944. ** per inode, so if the same inode is opened twice, both unixFile structures
  31945. ** point to the same locking structure. The locking structure keeps
  31946. ** a reference count (so we will know when to delete it) and a "cnt"
  31947. ** field that tells us its internal lock status. cnt==0 means the
  31948. ** file is unlocked. cnt==-1 means the file has an exclusive lock.
  31949. ** cnt>0 means there are cnt shared locks on the file.
  31950. **
  31951. ** Any attempt to lock or unlock a file first checks the locking
  31952. ** structure. The fcntl() system call is only invoked to set a
  31953. ** POSIX lock if the internal lock structure transitions between
  31954. ** a locked and an unlocked state.
  31955. **
  31956. ** But wait: there are yet more problems with POSIX advisory locks.
  31957. **
  31958. ** If you close a file descriptor that points to a file that has locks,
  31959. ** all locks on that file that are owned by the current process are
  31960. ** released. To work around this problem, each unixInodeInfo object
  31961. ** maintains a count of the number of pending locks on tha inode.
  31962. ** When an attempt is made to close an unixFile, if there are
  31963. ** other unixFile open on the same inode that are holding locks, the call
  31964. ** to close() the file descriptor is deferred until all of the locks clear.
  31965. ** The unixInodeInfo structure keeps a list of file descriptors that need to
  31966. ** be closed and that list is walked (and cleared) when the last lock
  31967. ** clears.
  31968. **
  31969. ** Yet another problem: LinuxThreads do not play well with posix locks.
  31970. **
  31971. ** Many older versions of linux use the LinuxThreads library which is
  31972. ** not posix compliant. Under LinuxThreads, a lock created by thread
  31973. ** A cannot be modified or overridden by a different thread B.
  31974. ** Only thread A can modify the lock. Locking behavior is correct
  31975. ** if the appliation uses the newer Native Posix Thread Library (NPTL)
  31976. ** on linux - with NPTL a lock created by thread A can override locks
  31977. ** in thread B. But there is no way to know at compile-time which
  31978. ** threading library is being used. So there is no way to know at
  31979. ** compile-time whether or not thread A can override locks on thread B.
  31980. ** One has to do a run-time check to discover the behavior of the
  31981. ** current process.
  31982. **
  31983. ** SQLite used to support LinuxThreads. But support for LinuxThreads
  31984. ** was dropped beginning with version 3.7.0. SQLite will still work with
  31985. ** LinuxThreads provided that (1) there is no more than one connection
  31986. ** per database file in the same process and (2) database connections
  31987. ** do not move across threads.
  31988. */
  31989. /*
  31990. ** An instance of the following structure serves as the key used
  31991. ** to locate a particular unixInodeInfo object.
  31992. */
  31993. struct unixFileId {
  31994. dev_t dev; /* Device number */
  31995. #if OS_VXWORKS
  31996. struct vxworksFileId *pId; /* Unique file ID for vxworks. */
  31997. #else
  31998. /* We are told that some versions of Android contain a bug that
  31999. ** sizes ino_t at only 32-bits instead of 64-bits. (See
  32000. ** https://android-review.googlesource.com/#/c/115351/3/dist/sqlite3.c)
  32001. ** To work around this, always allocate 64-bits for the inode number.
  32002. ** On small machines that only have 32-bit inodes, this wastes 4 bytes,
  32003. ** but that should not be a big deal. */
  32004. /* WAS: ino_t ino; */
  32005. u64 ino; /* Inode number */
  32006. #endif
  32007. };
  32008. /*
  32009. ** An instance of the following structure is allocated for each open
  32010. ** inode.
  32011. **
  32012. ** A single inode can have multiple file descriptors, so each unixFile
  32013. ** structure contains a pointer to an instance of this object and this
  32014. ** object keeps a count of the number of unixFile pointing to it.
  32015. **
  32016. ** Mutex rules:
  32017. **
  32018. ** (1) Only the pLockMutex mutex must be held in order to read or write
  32019. ** any of the locking fields:
  32020. ** nShared, nLock, eFileLock, bProcessLock, pUnused
  32021. **
  32022. ** (2) When nRef>0, then the following fields are unchanging and can
  32023. ** be read (but not written) without holding any mutex:
  32024. ** fileId, pLockMutex
  32025. **
  32026. ** (3) With the exceptions above, all the fields may only be read
  32027. ** or written while holding the global unixBigLock mutex.
  32028. **
  32029. ** Deadlock prevention: The global unixBigLock mutex may not
  32030. ** be acquired while holding the pLockMutex mutex. If both unixBigLock
  32031. ** and pLockMutex are needed, then unixBigLock must be acquired first.
  32032. */
  32033. struct unixInodeInfo {
  32034. struct unixFileId fileId; /* The lookup key */
  32035. sqlite3_mutex *pLockMutex; /* Hold this mutex for... */
  32036. int nShared; /* Number of SHARED locks held */
  32037. int nLock; /* Number of outstanding file locks */
  32038. unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
  32039. unsigned char bProcessLock; /* An exclusive process lock is held */
  32040. UnixUnusedFd *pUnused; /* Unused file descriptors to close */
  32041. int nRef; /* Number of pointers to this structure */
  32042. unixShmNode *pShmNode; /* Shared memory associated with this inode */
  32043. unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
  32044. unixInodeInfo *pPrev; /* .... doubly linked */
  32045. #if SQLITE_ENABLE_LOCKING_STYLE
  32046. unsigned long long sharedByte; /* for AFP simulated shared lock */
  32047. #endif
  32048. #if OS_VXWORKS
  32049. sem_t *pSem; /* Named POSIX semaphore */
  32050. char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
  32051. #endif
  32052. };
  32053. /*
  32054. ** A lists of all unixInodeInfo objects.
  32055. **
  32056. ** Must hold unixBigLock in order to read or write this variable.
  32057. */
  32058. static unixInodeInfo *inodeList = 0; /* All unixInodeInfo objects */
  32059. #ifdef SQLITE_DEBUG
  32060. /*
  32061. ** True if the inode mutex (on the unixFile.pFileMutex field) is held, or not.
  32062. ** This routine is used only within assert() to help verify correct mutex
  32063. ** usage.
  32064. */
  32065. int unixFileMutexHeld(unixFile *pFile){
  32066. assert( pFile->pInode );
  32067. return sqlite3_mutex_held(pFile->pInode->pLockMutex);
  32068. }
  32069. int unixFileMutexNotheld(unixFile *pFile){
  32070. assert( pFile->pInode );
  32071. return sqlite3_mutex_notheld(pFile->pInode->pLockMutex);
  32072. }
  32073. #endif
  32074. /*
  32075. **
  32076. ** This function - unixLogErrorAtLine(), is only ever called via the macro
  32077. ** unixLogError().
  32078. **
  32079. ** It is invoked after an error occurs in an OS function and errno has been
  32080. ** set. It logs a message using sqlite3_log() containing the current value of
  32081. ** errno and, if possible, the human-readable equivalent from strerror() or
  32082. ** strerror_r().
  32083. **
  32084. ** The first argument passed to the macro should be the error code that
  32085. ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
  32086. ** The two subsequent arguments should be the name of the OS function that
  32087. ** failed (e.g. "unlink", "open") and the associated file-system path,
  32088. ** if any.
  32089. */
  32090. #define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
  32091. static int unixLogErrorAtLine(
  32092. int errcode, /* SQLite error code */
  32093. const char *zFunc, /* Name of OS function that failed */
  32094. const char *zPath, /* File path associated with error */
  32095. int iLine /* Source line number where error occurred */
  32096. ){
  32097. char *zErr; /* Message from strerror() or equivalent */
  32098. int iErrno = errno; /* Saved syscall error number */
  32099. /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
  32100. ** the strerror() function to obtain the human-readable error message
  32101. ** equivalent to errno. Otherwise, use strerror_r().
  32102. */
  32103. #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
  32104. char aErr[80];
  32105. memset(aErr, 0, sizeof(aErr));
  32106. zErr = aErr;
  32107. /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
  32108. ** assume that the system provides the GNU version of strerror_r() that
  32109. ** returns a pointer to a buffer containing the error message. That pointer
  32110. ** may point to aErr[], or it may point to some static storage somewhere.
  32111. ** Otherwise, assume that the system provides the POSIX version of
  32112. ** strerror_r(), which always writes an error message into aErr[].
  32113. **
  32114. ** If the code incorrectly assumes that it is the POSIX version that is
  32115. ** available, the error message will often be an empty string. Not a
  32116. ** huge problem. Incorrectly concluding that the GNU version is available
  32117. ** could lead to a segfault though.
  32118. */
  32119. #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
  32120. zErr =
  32121. # endif
  32122. strerror_r(iErrno, aErr, sizeof(aErr)-1);
  32123. #elif SQLITE_THREADSAFE
  32124. /* This is a threadsafe build, but strerror_r() is not available. */
  32125. zErr = "";
  32126. #else
  32127. /* Non-threadsafe build, use strerror(). */
  32128. zErr = strerror(iErrno);
  32129. #endif
  32130. if( zPath==0 ) zPath = "";
  32131. sqlite3_log(errcode,
  32132. "os_unix.c:%d: (%d) %s(%s) - %s",
  32133. iLine, iErrno, zFunc, zPath, zErr
  32134. );
  32135. return errcode;
  32136. }
  32137. /*
  32138. ** Close a file descriptor.
  32139. **
  32140. ** We assume that close() almost always works, since it is only in a
  32141. ** very sick application or on a very sick platform that it might fail.
  32142. ** If it does fail, simply leak the file descriptor, but do log the
  32143. ** error.
  32144. **
  32145. ** Note that it is not safe to retry close() after EINTR since the
  32146. ** file descriptor might have already been reused by another thread.
  32147. ** So we don't even try to recover from an EINTR. Just log the error
  32148. ** and move on.
  32149. */
  32150. static void robust_close(unixFile *pFile, int h, int lineno){
  32151. if( osClose(h) ){
  32152. unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
  32153. pFile ? pFile->zPath : 0, lineno);
  32154. }
  32155. }
  32156. /*
  32157. ** Set the pFile->lastErrno. Do this in a subroutine as that provides
  32158. ** a convenient place to set a breakpoint.
  32159. */
  32160. static void storeLastErrno(unixFile *pFile, int error){
  32161. pFile->lastErrno = error;
  32162. }
  32163. /*
  32164. ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
  32165. */
  32166. static void closePendingFds(unixFile *pFile){
  32167. unixInodeInfo *pInode = pFile->pInode;
  32168. UnixUnusedFd *p;
  32169. UnixUnusedFd *pNext;
  32170. assert( unixFileMutexHeld(pFile) );
  32171. for(p=pInode->pUnused; p; p=pNext){
  32172. pNext = p->pNext;
  32173. robust_close(pFile, p->fd, __LINE__);
  32174. sqlite3_free(p);
  32175. }
  32176. pInode->pUnused = 0;
  32177. }
  32178. /*
  32179. ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
  32180. **
  32181. ** The global mutex must be held when this routine is called, but the mutex
  32182. ** on the inode being deleted must NOT be held.
  32183. */
  32184. static void releaseInodeInfo(unixFile *pFile){
  32185. unixInodeInfo *pInode = pFile->pInode;
  32186. assert( unixMutexHeld() );
  32187. assert( unixFileMutexNotheld(pFile) );
  32188. if( ALWAYS(pInode) ){
  32189. pInode->nRef--;
  32190. if( pInode->nRef==0 ){
  32191. assert( pInode->pShmNode==0 );
  32192. sqlite3_mutex_enter(pInode->pLockMutex);
  32193. closePendingFds(pFile);
  32194. sqlite3_mutex_leave(pInode->pLockMutex);
  32195. if( pInode->pPrev ){
  32196. assert( pInode->pPrev->pNext==pInode );
  32197. pInode->pPrev->pNext = pInode->pNext;
  32198. }else{
  32199. assert( inodeList==pInode );
  32200. inodeList = pInode->pNext;
  32201. }
  32202. if( pInode->pNext ){
  32203. assert( pInode->pNext->pPrev==pInode );
  32204. pInode->pNext->pPrev = pInode->pPrev;
  32205. }
  32206. sqlite3_mutex_free(pInode->pLockMutex);
  32207. sqlite3_free(pInode);
  32208. }
  32209. }
  32210. }
  32211. /*
  32212. ** Given a file descriptor, locate the unixInodeInfo object that
  32213. ** describes that file descriptor. Create a new one if necessary. The
  32214. ** return value might be uninitialized if an error occurs.
  32215. **
  32216. ** The global mutex must held when calling this routine.
  32217. **
  32218. ** Return an appropriate error code.
  32219. */
  32220. static int findInodeInfo(
  32221. unixFile *pFile, /* Unix file with file desc used in the key */
  32222. unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
  32223. ){
  32224. int rc; /* System call return code */
  32225. int fd; /* The file descriptor for pFile */
  32226. struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
  32227. struct stat statbuf; /* Low-level file information */
  32228. unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
  32229. assert( unixMutexHeld() );
  32230. /* Get low-level information about the file that we can used to
  32231. ** create a unique name for the file.
  32232. */
  32233. fd = pFile->h;
  32234. rc = osFstat(fd, &statbuf);
  32235. if( rc!=0 ){
  32236. storeLastErrno(pFile, errno);
  32237. #if defined(EOVERFLOW) && defined(SQLITE_DISABLE_LFS)
  32238. if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
  32239. #endif
  32240. return SQLITE_IOERR;
  32241. }
  32242. #ifdef __APPLE__
  32243. /* On OS X on an msdos filesystem, the inode number is reported
  32244. ** incorrectly for zero-size files. See ticket #3260. To work
  32245. ** around this problem (we consider it a bug in OS X, not SQLite)
  32246. ** we always increase the file size to 1 by writing a single byte
  32247. ** prior to accessing the inode number. The one byte written is
  32248. ** an ASCII 'S' character which also happens to be the first byte
  32249. ** in the header of every SQLite database. In this way, if there
  32250. ** is a race condition such that another thread has already populated
  32251. ** the first page of the database, no damage is done.
  32252. */
  32253. if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
  32254. do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
  32255. if( rc!=1 ){
  32256. storeLastErrno(pFile, errno);
  32257. return SQLITE_IOERR;
  32258. }
  32259. rc = osFstat(fd, &statbuf);
  32260. if( rc!=0 ){
  32261. storeLastErrno(pFile, errno);
  32262. return SQLITE_IOERR;
  32263. }
  32264. }
  32265. #endif
  32266. memset(&fileId, 0, sizeof(fileId));
  32267. fileId.dev = statbuf.st_dev;
  32268. #if OS_VXWORKS
  32269. fileId.pId = pFile->pId;
  32270. #else
  32271. fileId.ino = (u64)statbuf.st_ino;
  32272. #endif
  32273. assert( unixMutexHeld() );
  32274. pInode = inodeList;
  32275. while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
  32276. pInode = pInode->pNext;
  32277. }
  32278. if( pInode==0 ){
  32279. pInode = sqlite3_malloc64( sizeof(*pInode) );
  32280. if( pInode==0 ){
  32281. return SQLITE_NOMEM_BKPT;
  32282. }
  32283. memset(pInode, 0, sizeof(*pInode));
  32284. memcpy(&pInode->fileId, &fileId, sizeof(fileId));
  32285. if( sqlite3GlobalConfig.bCoreMutex ){
  32286. pInode->pLockMutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
  32287. if( pInode->pLockMutex==0 ){
  32288. sqlite3_free(pInode);
  32289. return SQLITE_NOMEM_BKPT;
  32290. }
  32291. }
  32292. pInode->nRef = 1;
  32293. assert( unixMutexHeld() );
  32294. pInode->pNext = inodeList;
  32295. pInode->pPrev = 0;
  32296. if( inodeList ) inodeList->pPrev = pInode;
  32297. inodeList = pInode;
  32298. }else{
  32299. pInode->nRef++;
  32300. }
  32301. *ppInode = pInode;
  32302. return SQLITE_OK;
  32303. }
  32304. /*
  32305. ** Return TRUE if pFile has been renamed or unlinked since it was first opened.
  32306. */
  32307. static int fileHasMoved(unixFile *pFile){
  32308. #if OS_VXWORKS
  32309. return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
  32310. #else
  32311. struct stat buf;
  32312. return pFile->pInode!=0 &&
  32313. (osStat(pFile->zPath, &buf)!=0
  32314. || (u64)buf.st_ino!=pFile->pInode->fileId.ino);
  32315. #endif
  32316. }
  32317. /*
  32318. ** Check a unixFile that is a database. Verify the following:
  32319. **
  32320. ** (1) There is exactly one hard link on the file
  32321. ** (2) The file is not a symbolic link
  32322. ** (3) The file has not been renamed or unlinked
  32323. **
  32324. ** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
  32325. */
  32326. static void verifyDbFile(unixFile *pFile){
  32327. struct stat buf;
  32328. int rc;
  32329. /* These verifications occurs for the main database only */
  32330. if( pFile->ctrlFlags & UNIXFILE_NOLOCK ) return;
  32331. rc = osFstat(pFile->h, &buf);
  32332. if( rc!=0 ){
  32333. sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
  32334. return;
  32335. }
  32336. if( buf.st_nlink==0 ){
  32337. sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
  32338. return;
  32339. }
  32340. if( buf.st_nlink>1 ){
  32341. sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
  32342. return;
  32343. }
  32344. if( fileHasMoved(pFile) ){
  32345. sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
  32346. return;
  32347. }
  32348. }
  32349. /*
  32350. ** This routine checks if there is a RESERVED lock held on the specified
  32351. ** file by this or any other process. If such a lock is held, set *pResOut
  32352. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  32353. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  32354. */
  32355. static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
  32356. int rc = SQLITE_OK;
  32357. int reserved = 0;
  32358. unixFile *pFile = (unixFile*)id;
  32359. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  32360. assert( pFile );
  32361. assert( pFile->eFileLock<=SHARED_LOCK );
  32362. sqlite3_mutex_enter(pFile->pInode->pLockMutex);
  32363. /* Check if a thread in this process holds such a lock */
  32364. if( pFile->pInode->eFileLock>SHARED_LOCK ){
  32365. reserved = 1;
  32366. }
  32367. /* Otherwise see if some other process holds it.
  32368. */
  32369. #ifndef __DJGPP__
  32370. if( !reserved && !pFile->pInode->bProcessLock ){
  32371. struct flock lock;
  32372. lock.l_whence = SEEK_SET;
  32373. lock.l_start = RESERVED_BYTE;
  32374. lock.l_len = 1;
  32375. lock.l_type = F_WRLCK;
  32376. if( osFcntl(pFile->h, F_GETLK, &lock) ){
  32377. rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
  32378. storeLastErrno(pFile, errno);
  32379. } else if( lock.l_type!=F_UNLCK ){
  32380. reserved = 1;
  32381. }
  32382. }
  32383. #endif
  32384. sqlite3_mutex_leave(pFile->pInode->pLockMutex);
  32385. OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
  32386. *pResOut = reserved;
  32387. return rc;
  32388. }
  32389. /*
  32390. ** Set a posix-advisory-lock.
  32391. **
  32392. ** There are two versions of this routine. If compiled with
  32393. ** SQLITE_ENABLE_SETLK_TIMEOUT then the routine has an extra parameter
  32394. ** which is a pointer to a unixFile. If the unixFile->iBusyTimeout
  32395. ** value is set, then it is the number of milliseconds to wait before
  32396. ** failing the lock. The iBusyTimeout value is always reset back to
  32397. ** zero on each call.
  32398. **
  32399. ** If SQLITE_ENABLE_SETLK_TIMEOUT is not defined, then do a non-blocking
  32400. ** attempt to set the lock.
  32401. */
  32402. #ifndef SQLITE_ENABLE_SETLK_TIMEOUT
  32403. # define osSetPosixAdvisoryLock(h,x,t) osFcntl(h,F_SETLK,x)
  32404. #else
  32405. static int osSetPosixAdvisoryLock(
  32406. int h, /* The file descriptor on which to take the lock */
  32407. struct flock *pLock, /* The description of the lock */
  32408. unixFile *pFile /* Structure holding timeout value */
  32409. ){
  32410. int rc = osFcntl(h,F_SETLK,pLock);
  32411. while( rc<0 && pFile->iBusyTimeout>0 ){
  32412. /* On systems that support some kind of blocking file lock with a timeout,
  32413. ** make appropriate changes here to invoke that blocking file lock. On
  32414. ** generic posix, however, there is no such API. So we simply try the
  32415. ** lock once every millisecond until either the timeout expires, or until
  32416. ** the lock is obtained. */
  32417. usleep(1000);
  32418. rc = osFcntl(h,F_SETLK,pLock);
  32419. pFile->iBusyTimeout--;
  32420. }
  32421. return rc;
  32422. }
  32423. #endif /* SQLITE_ENABLE_SETLK_TIMEOUT */
  32424. /*
  32425. ** Attempt to set a system-lock on the file pFile. The lock is
  32426. ** described by pLock.
  32427. **
  32428. ** If the pFile was opened read/write from unix-excl, then the only lock
  32429. ** ever obtained is an exclusive lock, and it is obtained exactly once
  32430. ** the first time any lock is attempted. All subsequent system locking
  32431. ** operations become no-ops. Locking operations still happen internally,
  32432. ** in order to coordinate access between separate database connections
  32433. ** within this process, but all of that is handled in memory and the
  32434. ** operating system does not participate.
  32435. **
  32436. ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
  32437. ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
  32438. ** and is read-only.
  32439. **
  32440. ** Zero is returned if the call completes successfully, or -1 if a call
  32441. ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
  32442. */
  32443. static int unixFileLock(unixFile *pFile, struct flock *pLock){
  32444. int rc;
  32445. unixInodeInfo *pInode = pFile->pInode;
  32446. assert( pInode!=0 );
  32447. assert( sqlite3_mutex_held(pInode->pLockMutex) );
  32448. if( (pFile->ctrlFlags & (UNIXFILE_EXCL|UNIXFILE_RDONLY))==UNIXFILE_EXCL ){
  32449. if( pInode->bProcessLock==0 ){
  32450. struct flock lock;
  32451. assert( pInode->nLock==0 );
  32452. lock.l_whence = SEEK_SET;
  32453. lock.l_start = SHARED_FIRST;
  32454. lock.l_len = SHARED_SIZE;
  32455. lock.l_type = F_WRLCK;
  32456. rc = osSetPosixAdvisoryLock(pFile->h, &lock, pFile);
  32457. if( rc<0 ) return rc;
  32458. pInode->bProcessLock = 1;
  32459. pInode->nLock++;
  32460. }else{
  32461. rc = 0;
  32462. }
  32463. }else{
  32464. rc = osSetPosixAdvisoryLock(pFile->h, pLock, pFile);
  32465. }
  32466. return rc;
  32467. }
  32468. /*
  32469. ** Lock the file with the lock specified by parameter eFileLock - one
  32470. ** of the following:
  32471. **
  32472. ** (1) SHARED_LOCK
  32473. ** (2) RESERVED_LOCK
  32474. ** (3) PENDING_LOCK
  32475. ** (4) EXCLUSIVE_LOCK
  32476. **
  32477. ** Sometimes when requesting one lock state, additional lock states
  32478. ** are inserted in between. The locking might fail on one of the later
  32479. ** transitions leaving the lock state different from what it started but
  32480. ** still short of its goal. The following chart shows the allowed
  32481. ** transitions and the inserted intermediate states:
  32482. **
  32483. ** UNLOCKED -> SHARED
  32484. ** SHARED -> RESERVED
  32485. ** SHARED -> (PENDING) -> EXCLUSIVE
  32486. ** RESERVED -> (PENDING) -> EXCLUSIVE
  32487. ** PENDING -> EXCLUSIVE
  32488. **
  32489. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  32490. ** routine to lower a locking level.
  32491. */
  32492. static int unixLock(sqlite3_file *id, int eFileLock){
  32493. /* The following describes the implementation of the various locks and
  32494. ** lock transitions in terms of the POSIX advisory shared and exclusive
  32495. ** lock primitives (called read-locks and write-locks below, to avoid
  32496. ** confusion with SQLite lock names). The algorithms are complicated
  32497. ** slightly in order to be compatible with Windows95 systems simultaneously
  32498. ** accessing the same database file, in case that is ever required.
  32499. **
  32500. ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
  32501. ** byte', each single bytes at well known offsets, and the 'shared byte
  32502. ** range', a range of 510 bytes at a well known offset.
  32503. **
  32504. ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
  32505. ** byte'. If this is successful, 'shared byte range' is read-locked
  32506. ** and the lock on the 'pending byte' released. (Legacy note: When
  32507. ** SQLite was first developed, Windows95 systems were still very common,
  32508. ** and Widnows95 lacks a shared-lock capability. So on Windows95, a
  32509. ** single randomly selected by from the 'shared byte range' is locked.
  32510. ** Windows95 is now pretty much extinct, but this work-around for the
  32511. ** lack of shared-locks on Windows95 lives on, for backwards
  32512. ** compatibility.)
  32513. **
  32514. ** A process may only obtain a RESERVED lock after it has a SHARED lock.
  32515. ** A RESERVED lock is implemented by grabbing a write-lock on the
  32516. ** 'reserved byte'.
  32517. **
  32518. ** A process may only obtain a PENDING lock after it has obtained a
  32519. ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
  32520. ** on the 'pending byte'. This ensures that no new SHARED locks can be
  32521. ** obtained, but existing SHARED locks are allowed to persist. A process
  32522. ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
  32523. ** This property is used by the algorithm for rolling back a journal file
  32524. ** after a crash.
  32525. **
  32526. ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
  32527. ** implemented by obtaining a write-lock on the entire 'shared byte
  32528. ** range'. Since all other locks require a read-lock on one of the bytes
  32529. ** within this range, this ensures that no other locks are held on the
  32530. ** database.
  32531. */
  32532. int rc = SQLITE_OK;
  32533. unixFile *pFile = (unixFile*)id;
  32534. unixInodeInfo *pInode;
  32535. struct flock lock;
  32536. int tErrno = 0;
  32537. assert( pFile );
  32538. OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
  32539. azFileLock(eFileLock), azFileLock(pFile->eFileLock),
  32540. azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
  32541. osGetpid(0)));
  32542. /* If there is already a lock of this type or more restrictive on the
  32543. ** unixFile, do nothing. Don't use the end_lock: exit path, as
  32544. ** unixEnterMutex() hasn't been called yet.
  32545. */
  32546. if( pFile->eFileLock>=eFileLock ){
  32547. OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
  32548. azFileLock(eFileLock)));
  32549. return SQLITE_OK;
  32550. }
  32551. /* Make sure the locking sequence is correct.
  32552. ** (1) We never move from unlocked to anything higher than shared lock.
  32553. ** (2) SQLite never explicitly requests a pendig lock.
  32554. ** (3) A shared lock is always held when a reserve lock is requested.
  32555. */
  32556. assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
  32557. assert( eFileLock!=PENDING_LOCK );
  32558. assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
  32559. /* This mutex is needed because pFile->pInode is shared across threads
  32560. */
  32561. pInode = pFile->pInode;
  32562. sqlite3_mutex_enter(pInode->pLockMutex);
  32563. /* If some thread using this PID has a lock via a different unixFile*
  32564. ** handle that precludes the requested lock, return BUSY.
  32565. */
  32566. if( (pFile->eFileLock!=pInode->eFileLock &&
  32567. (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
  32568. ){
  32569. rc = SQLITE_BUSY;
  32570. goto end_lock;
  32571. }
  32572. /* If a SHARED lock is requested, and some thread using this PID already
  32573. ** has a SHARED or RESERVED lock, then increment reference counts and
  32574. ** return SQLITE_OK.
  32575. */
  32576. if( eFileLock==SHARED_LOCK &&
  32577. (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
  32578. assert( eFileLock==SHARED_LOCK );
  32579. assert( pFile->eFileLock==0 );
  32580. assert( pInode->nShared>0 );
  32581. pFile->eFileLock = SHARED_LOCK;
  32582. pInode->nShared++;
  32583. pInode->nLock++;
  32584. goto end_lock;
  32585. }
  32586. /* A PENDING lock is needed before acquiring a SHARED lock and before
  32587. ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
  32588. ** be released.
  32589. */
  32590. lock.l_len = 1L;
  32591. lock.l_whence = SEEK_SET;
  32592. if( eFileLock==SHARED_LOCK
  32593. || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
  32594. ){
  32595. lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
  32596. lock.l_start = PENDING_BYTE;
  32597. if( unixFileLock(pFile, &lock) ){
  32598. tErrno = errno;
  32599. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  32600. if( rc!=SQLITE_BUSY ){
  32601. storeLastErrno(pFile, tErrno);
  32602. }
  32603. goto end_lock;
  32604. }
  32605. }
  32606. /* If control gets to this point, then actually go ahead and make
  32607. ** operating system calls for the specified lock.
  32608. */
  32609. if( eFileLock==SHARED_LOCK ){
  32610. assert( pInode->nShared==0 );
  32611. assert( pInode->eFileLock==0 );
  32612. assert( rc==SQLITE_OK );
  32613. /* Now get the read-lock */
  32614. lock.l_start = SHARED_FIRST;
  32615. lock.l_len = SHARED_SIZE;
  32616. if( unixFileLock(pFile, &lock) ){
  32617. tErrno = errno;
  32618. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  32619. }
  32620. /* Drop the temporary PENDING lock */
  32621. lock.l_start = PENDING_BYTE;
  32622. lock.l_len = 1L;
  32623. lock.l_type = F_UNLCK;
  32624. if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
  32625. /* This could happen with a network mount */
  32626. tErrno = errno;
  32627. rc = SQLITE_IOERR_UNLOCK;
  32628. }
  32629. if( rc ){
  32630. if( rc!=SQLITE_BUSY ){
  32631. storeLastErrno(pFile, tErrno);
  32632. }
  32633. goto end_lock;
  32634. }else{
  32635. pFile->eFileLock = SHARED_LOCK;
  32636. pInode->nLock++;
  32637. pInode->nShared = 1;
  32638. }
  32639. }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
  32640. /* We are trying for an exclusive lock but another thread in this
  32641. ** same process is still holding a shared lock. */
  32642. rc = SQLITE_BUSY;
  32643. }else{
  32644. /* The request was for a RESERVED or EXCLUSIVE lock. It is
  32645. ** assumed that there is a SHARED or greater lock on the file
  32646. ** already.
  32647. */
  32648. assert( 0!=pFile->eFileLock );
  32649. lock.l_type = F_WRLCK;
  32650. assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
  32651. if( eFileLock==RESERVED_LOCK ){
  32652. lock.l_start = RESERVED_BYTE;
  32653. lock.l_len = 1L;
  32654. }else{
  32655. lock.l_start = SHARED_FIRST;
  32656. lock.l_len = SHARED_SIZE;
  32657. }
  32658. if( unixFileLock(pFile, &lock) ){
  32659. tErrno = errno;
  32660. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  32661. if( rc!=SQLITE_BUSY ){
  32662. storeLastErrno(pFile, tErrno);
  32663. }
  32664. }
  32665. }
  32666. #ifdef SQLITE_DEBUG
  32667. /* Set up the transaction-counter change checking flags when
  32668. ** transitioning from a SHARED to a RESERVED lock. The change
  32669. ** from SHARED to RESERVED marks the beginning of a normal
  32670. ** write operation (not a hot journal rollback).
  32671. */
  32672. if( rc==SQLITE_OK
  32673. && pFile->eFileLock<=SHARED_LOCK
  32674. && eFileLock==RESERVED_LOCK
  32675. ){
  32676. pFile->transCntrChng = 0;
  32677. pFile->dbUpdate = 0;
  32678. pFile->inNormalWrite = 1;
  32679. }
  32680. #endif
  32681. if( rc==SQLITE_OK ){
  32682. pFile->eFileLock = eFileLock;
  32683. pInode->eFileLock = eFileLock;
  32684. }else if( eFileLock==EXCLUSIVE_LOCK ){
  32685. pFile->eFileLock = PENDING_LOCK;
  32686. pInode->eFileLock = PENDING_LOCK;
  32687. }
  32688. end_lock:
  32689. sqlite3_mutex_leave(pInode->pLockMutex);
  32690. OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
  32691. rc==SQLITE_OK ? "ok" : "failed"));
  32692. return rc;
  32693. }
  32694. /*
  32695. ** Add the file descriptor used by file handle pFile to the corresponding
  32696. ** pUnused list.
  32697. */
  32698. static void setPendingFd(unixFile *pFile){
  32699. unixInodeInfo *pInode = pFile->pInode;
  32700. UnixUnusedFd *p = pFile->pPreallocatedUnused;
  32701. assert( unixFileMutexHeld(pFile) );
  32702. p->pNext = pInode->pUnused;
  32703. pInode->pUnused = p;
  32704. pFile->h = -1;
  32705. pFile->pPreallocatedUnused = 0;
  32706. }
  32707. /*
  32708. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  32709. ** must be either NO_LOCK or SHARED_LOCK.
  32710. **
  32711. ** If the locking level of the file descriptor is already at or below
  32712. ** the requested locking level, this routine is a no-op.
  32713. **
  32714. ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
  32715. ** the byte range is divided into 2 parts and the first part is unlocked then
  32716. ** set to a read lock, then the other part is simply unlocked. This works
  32717. ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
  32718. ** remove the write lock on a region when a read lock is set.
  32719. */
  32720. static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
  32721. unixFile *pFile = (unixFile*)id;
  32722. unixInodeInfo *pInode;
  32723. struct flock lock;
  32724. int rc = SQLITE_OK;
  32725. assert( pFile );
  32726. OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
  32727. pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
  32728. osGetpid(0)));
  32729. assert( eFileLock<=SHARED_LOCK );
  32730. if( pFile->eFileLock<=eFileLock ){
  32731. return SQLITE_OK;
  32732. }
  32733. pInode = pFile->pInode;
  32734. sqlite3_mutex_enter(pInode->pLockMutex);
  32735. assert( pInode->nShared!=0 );
  32736. if( pFile->eFileLock>SHARED_LOCK ){
  32737. assert( pInode->eFileLock==pFile->eFileLock );
  32738. #ifdef SQLITE_DEBUG
  32739. /* When reducing a lock such that other processes can start
  32740. ** reading the database file again, make sure that the
  32741. ** transaction counter was updated if any part of the database
  32742. ** file changed. If the transaction counter is not updated,
  32743. ** other connections to the same file might not realize that
  32744. ** the file has changed and hence might not know to flush their
  32745. ** cache. The use of a stale cache can lead to database corruption.
  32746. */
  32747. pFile->inNormalWrite = 0;
  32748. #endif
  32749. /* downgrading to a shared lock on NFS involves clearing the write lock
  32750. ** before establishing the readlock - to avoid a race condition we downgrade
  32751. ** the lock in 2 blocks, so that part of the range will be covered by a
  32752. ** write lock until the rest is covered by a read lock:
  32753. ** 1: [WWWWW]
  32754. ** 2: [....W]
  32755. ** 3: [RRRRW]
  32756. ** 4: [RRRR.]
  32757. */
  32758. if( eFileLock==SHARED_LOCK ){
  32759. #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
  32760. (void)handleNFSUnlock;
  32761. assert( handleNFSUnlock==0 );
  32762. #endif
  32763. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  32764. if( handleNFSUnlock ){
  32765. int tErrno; /* Error code from system call errors */
  32766. off_t divSize = SHARED_SIZE - 1;
  32767. lock.l_type = F_UNLCK;
  32768. lock.l_whence = SEEK_SET;
  32769. lock.l_start = SHARED_FIRST;
  32770. lock.l_len = divSize;
  32771. if( unixFileLock(pFile, &lock)==(-1) ){
  32772. tErrno = errno;
  32773. rc = SQLITE_IOERR_UNLOCK;
  32774. storeLastErrno(pFile, tErrno);
  32775. goto end_unlock;
  32776. }
  32777. lock.l_type = F_RDLCK;
  32778. lock.l_whence = SEEK_SET;
  32779. lock.l_start = SHARED_FIRST;
  32780. lock.l_len = divSize;
  32781. if( unixFileLock(pFile, &lock)==(-1) ){
  32782. tErrno = errno;
  32783. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
  32784. if( IS_LOCK_ERROR(rc) ){
  32785. storeLastErrno(pFile, tErrno);
  32786. }
  32787. goto end_unlock;
  32788. }
  32789. lock.l_type = F_UNLCK;
  32790. lock.l_whence = SEEK_SET;
  32791. lock.l_start = SHARED_FIRST+divSize;
  32792. lock.l_len = SHARED_SIZE-divSize;
  32793. if( unixFileLock(pFile, &lock)==(-1) ){
  32794. tErrno = errno;
  32795. rc = SQLITE_IOERR_UNLOCK;
  32796. storeLastErrno(pFile, tErrno);
  32797. goto end_unlock;
  32798. }
  32799. }else
  32800. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  32801. {
  32802. lock.l_type = F_RDLCK;
  32803. lock.l_whence = SEEK_SET;
  32804. lock.l_start = SHARED_FIRST;
  32805. lock.l_len = SHARED_SIZE;
  32806. if( unixFileLock(pFile, &lock) ){
  32807. /* In theory, the call to unixFileLock() cannot fail because another
  32808. ** process is holding an incompatible lock. If it does, this
  32809. ** indicates that the other process is not following the locking
  32810. ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
  32811. ** SQLITE_BUSY would confuse the upper layer (in practice it causes
  32812. ** an assert to fail). */
  32813. rc = SQLITE_IOERR_RDLOCK;
  32814. storeLastErrno(pFile, errno);
  32815. goto end_unlock;
  32816. }
  32817. }
  32818. }
  32819. lock.l_type = F_UNLCK;
  32820. lock.l_whence = SEEK_SET;
  32821. lock.l_start = PENDING_BYTE;
  32822. lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
  32823. if( unixFileLock(pFile, &lock)==0 ){
  32824. pInode->eFileLock = SHARED_LOCK;
  32825. }else{
  32826. rc = SQLITE_IOERR_UNLOCK;
  32827. storeLastErrno(pFile, errno);
  32828. goto end_unlock;
  32829. }
  32830. }
  32831. if( eFileLock==NO_LOCK ){
  32832. /* Decrement the shared lock counter. Release the lock using an
  32833. ** OS call only when all threads in this same process have released
  32834. ** the lock.
  32835. */
  32836. pInode->nShared--;
  32837. if( pInode->nShared==0 ){
  32838. lock.l_type = F_UNLCK;
  32839. lock.l_whence = SEEK_SET;
  32840. lock.l_start = lock.l_len = 0L;
  32841. if( unixFileLock(pFile, &lock)==0 ){
  32842. pInode->eFileLock = NO_LOCK;
  32843. }else{
  32844. rc = SQLITE_IOERR_UNLOCK;
  32845. storeLastErrno(pFile, errno);
  32846. pInode->eFileLock = NO_LOCK;
  32847. pFile->eFileLock = NO_LOCK;
  32848. }
  32849. }
  32850. /* Decrement the count of locks against this same file. When the
  32851. ** count reaches zero, close any other file descriptors whose close
  32852. ** was deferred because of outstanding locks.
  32853. */
  32854. pInode->nLock--;
  32855. assert( pInode->nLock>=0 );
  32856. if( pInode->nLock==0 ) closePendingFds(pFile);
  32857. }
  32858. end_unlock:
  32859. sqlite3_mutex_leave(pInode->pLockMutex);
  32860. if( rc==SQLITE_OK ){
  32861. pFile->eFileLock = eFileLock;
  32862. }
  32863. return rc;
  32864. }
  32865. /*
  32866. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  32867. ** must be either NO_LOCK or SHARED_LOCK.
  32868. **
  32869. ** If the locking level of the file descriptor is already at or below
  32870. ** the requested locking level, this routine is a no-op.
  32871. */
  32872. static int unixUnlock(sqlite3_file *id, int eFileLock){
  32873. #if SQLITE_MAX_MMAP_SIZE>0
  32874. assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
  32875. #endif
  32876. return posixUnlock(id, eFileLock, 0);
  32877. }
  32878. #if SQLITE_MAX_MMAP_SIZE>0
  32879. static int unixMapfile(unixFile *pFd, i64 nByte);
  32880. static void unixUnmapfile(unixFile *pFd);
  32881. #endif
  32882. /*
  32883. ** This function performs the parts of the "close file" operation
  32884. ** common to all locking schemes. It closes the directory and file
  32885. ** handles, if they are valid, and sets all fields of the unixFile
  32886. ** structure to 0.
  32887. **
  32888. ** It is *not* necessary to hold the mutex when this routine is called,
  32889. ** even on VxWorks. A mutex will be acquired on VxWorks by the
  32890. ** vxworksReleaseFileId() routine.
  32891. */
  32892. static int closeUnixFile(sqlite3_file *id){
  32893. unixFile *pFile = (unixFile*)id;
  32894. #if SQLITE_MAX_MMAP_SIZE>0
  32895. unixUnmapfile(pFile);
  32896. #endif
  32897. if( pFile->h>=0 ){
  32898. robust_close(pFile, pFile->h, __LINE__);
  32899. pFile->h = -1;
  32900. }
  32901. #if OS_VXWORKS
  32902. if( pFile->pId ){
  32903. if( pFile->ctrlFlags & UNIXFILE_DELETE ){
  32904. osUnlink(pFile->pId->zCanonicalName);
  32905. }
  32906. vxworksReleaseFileId(pFile->pId);
  32907. pFile->pId = 0;
  32908. }
  32909. #endif
  32910. #ifdef SQLITE_UNLINK_AFTER_CLOSE
  32911. if( pFile->ctrlFlags & UNIXFILE_DELETE ){
  32912. osUnlink(pFile->zPath);
  32913. sqlite3_free(*(char**)&pFile->zPath);
  32914. pFile->zPath = 0;
  32915. }
  32916. #endif
  32917. OSTRACE(("CLOSE %-3d\n", pFile->h));
  32918. OpenCounter(-1);
  32919. sqlite3_free(pFile->pPreallocatedUnused);
  32920. memset(pFile, 0, sizeof(unixFile));
  32921. return SQLITE_OK;
  32922. }
  32923. /*
  32924. ** Close a file.
  32925. */
  32926. static int unixClose(sqlite3_file *id){
  32927. int rc = SQLITE_OK;
  32928. unixFile *pFile = (unixFile *)id;
  32929. unixInodeInfo *pInode = pFile->pInode;
  32930. assert( pInode!=0 );
  32931. verifyDbFile(pFile);
  32932. unixUnlock(id, NO_LOCK);
  32933. assert( unixFileMutexNotheld(pFile) );
  32934. unixEnterMutex();
  32935. /* unixFile.pInode is always valid here. Otherwise, a different close
  32936. ** routine (e.g. nolockClose()) would be called instead.
  32937. */
  32938. assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
  32939. sqlite3_mutex_enter(pInode->pLockMutex);
  32940. if( pInode->nLock ){
  32941. /* If there are outstanding locks, do not actually close the file just
  32942. ** yet because that would clear those locks. Instead, add the file
  32943. ** descriptor to pInode->pUnused list. It will be automatically closed
  32944. ** when the last lock is cleared.
  32945. */
  32946. setPendingFd(pFile);
  32947. }
  32948. sqlite3_mutex_leave(pInode->pLockMutex);
  32949. releaseInodeInfo(pFile);
  32950. rc = closeUnixFile(id);
  32951. unixLeaveMutex();
  32952. return rc;
  32953. }
  32954. /************** End of the posix advisory lock implementation *****************
  32955. ******************************************************************************/
  32956. /******************************************************************************
  32957. ****************************** No-op Locking **********************************
  32958. **
  32959. ** Of the various locking implementations available, this is by far the
  32960. ** simplest: locking is ignored. No attempt is made to lock the database
  32961. ** file for reading or writing.
  32962. **
  32963. ** This locking mode is appropriate for use on read-only databases
  32964. ** (ex: databases that are burned into CD-ROM, for example.) It can
  32965. ** also be used if the application employs some external mechanism to
  32966. ** prevent simultaneous access of the same database by two or more
  32967. ** database connections. But there is a serious risk of database
  32968. ** corruption if this locking mode is used in situations where multiple
  32969. ** database connections are accessing the same database file at the same
  32970. ** time and one or more of those connections are writing.
  32971. */
  32972. static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
  32973. UNUSED_PARAMETER(NotUsed);
  32974. *pResOut = 0;
  32975. return SQLITE_OK;
  32976. }
  32977. static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
  32978. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  32979. return SQLITE_OK;
  32980. }
  32981. static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
  32982. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  32983. return SQLITE_OK;
  32984. }
  32985. /*
  32986. ** Close the file.
  32987. */
  32988. static int nolockClose(sqlite3_file *id) {
  32989. return closeUnixFile(id);
  32990. }
  32991. /******************* End of the no-op lock implementation *********************
  32992. ******************************************************************************/
  32993. /******************************************************************************
  32994. ************************* Begin dot-file Locking ******************************
  32995. **
  32996. ** The dotfile locking implementation uses the existence of separate lock
  32997. ** files (really a directory) to control access to the database. This works
  32998. ** on just about every filesystem imaginable. But there are serious downsides:
  32999. **
  33000. ** (1) There is zero concurrency. A single reader blocks all other
  33001. ** connections from reading or writing the database.
  33002. **
  33003. ** (2) An application crash or power loss can leave stale lock files
  33004. ** sitting around that need to be cleared manually.
  33005. **
  33006. ** Nevertheless, a dotlock is an appropriate locking mode for use if no
  33007. ** other locking strategy is available.
  33008. **
  33009. ** Dotfile locking works by creating a subdirectory in the same directory as
  33010. ** the database and with the same name but with a ".lock" extension added.
  33011. ** The existence of a lock directory implies an EXCLUSIVE lock. All other
  33012. ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
  33013. */
  33014. /*
  33015. ** The file suffix added to the data base filename in order to create the
  33016. ** lock directory.
  33017. */
  33018. #define DOTLOCK_SUFFIX ".lock"
  33019. /*
  33020. ** This routine checks if there is a RESERVED lock held on the specified
  33021. ** file by this or any other process. If such a lock is held, set *pResOut
  33022. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  33023. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  33024. **
  33025. ** In dotfile locking, either a lock exists or it does not. So in this
  33026. ** variation of CheckReservedLock(), *pResOut is set to true if any lock
  33027. ** is held on the file and false if the file is unlocked.
  33028. */
  33029. static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
  33030. int rc = SQLITE_OK;
  33031. int reserved = 0;
  33032. unixFile *pFile = (unixFile*)id;
  33033. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  33034. assert( pFile );
  33035. reserved = osAccess((const char*)pFile->lockingContext, 0)==0;
  33036. OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
  33037. *pResOut = reserved;
  33038. return rc;
  33039. }
  33040. /*
  33041. ** Lock the file with the lock specified by parameter eFileLock - one
  33042. ** of the following:
  33043. **
  33044. ** (1) SHARED_LOCK
  33045. ** (2) RESERVED_LOCK
  33046. ** (3) PENDING_LOCK
  33047. ** (4) EXCLUSIVE_LOCK
  33048. **
  33049. ** Sometimes when requesting one lock state, additional lock states
  33050. ** are inserted in between. The locking might fail on one of the later
  33051. ** transitions leaving the lock state different from what it started but
  33052. ** still short of its goal. The following chart shows the allowed
  33053. ** transitions and the inserted intermediate states:
  33054. **
  33055. ** UNLOCKED -> SHARED
  33056. ** SHARED -> RESERVED
  33057. ** SHARED -> (PENDING) -> EXCLUSIVE
  33058. ** RESERVED -> (PENDING) -> EXCLUSIVE
  33059. ** PENDING -> EXCLUSIVE
  33060. **
  33061. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  33062. ** routine to lower a locking level.
  33063. **
  33064. ** With dotfile locking, we really only support state (4): EXCLUSIVE.
  33065. ** But we track the other locking levels internally.
  33066. */
  33067. static int dotlockLock(sqlite3_file *id, int eFileLock) {
  33068. unixFile *pFile = (unixFile*)id;
  33069. char *zLockFile = (char *)pFile->lockingContext;
  33070. int rc = SQLITE_OK;
  33071. /* If we have any lock, then the lock file already exists. All we have
  33072. ** to do is adjust our internal record of the lock level.
  33073. */
  33074. if( pFile->eFileLock > NO_LOCK ){
  33075. pFile->eFileLock = eFileLock;
  33076. /* Always update the timestamp on the old file */
  33077. #ifdef HAVE_UTIME
  33078. utime(zLockFile, NULL);
  33079. #else
  33080. utimes(zLockFile, NULL);
  33081. #endif
  33082. return SQLITE_OK;
  33083. }
  33084. /* grab an exclusive lock */
  33085. rc = osMkdir(zLockFile, 0777);
  33086. if( rc<0 ){
  33087. /* failed to open/create the lock directory */
  33088. int tErrno = errno;
  33089. if( EEXIST == tErrno ){
  33090. rc = SQLITE_BUSY;
  33091. } else {
  33092. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  33093. if( rc!=SQLITE_BUSY ){
  33094. storeLastErrno(pFile, tErrno);
  33095. }
  33096. }
  33097. return rc;
  33098. }
  33099. /* got it, set the type and return ok */
  33100. pFile->eFileLock = eFileLock;
  33101. return rc;
  33102. }
  33103. /*
  33104. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  33105. ** must be either NO_LOCK or SHARED_LOCK.
  33106. **
  33107. ** If the locking level of the file descriptor is already at or below
  33108. ** the requested locking level, this routine is a no-op.
  33109. **
  33110. ** When the locking level reaches NO_LOCK, delete the lock file.
  33111. */
  33112. static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
  33113. unixFile *pFile = (unixFile*)id;
  33114. char *zLockFile = (char *)pFile->lockingContext;
  33115. int rc;
  33116. assert( pFile );
  33117. OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
  33118. pFile->eFileLock, osGetpid(0)));
  33119. assert( eFileLock<=SHARED_LOCK );
  33120. /* no-op if possible */
  33121. if( pFile->eFileLock==eFileLock ){
  33122. return SQLITE_OK;
  33123. }
  33124. /* To downgrade to shared, simply update our internal notion of the
  33125. ** lock state. No need to mess with the file on disk.
  33126. */
  33127. if( eFileLock==SHARED_LOCK ){
  33128. pFile->eFileLock = SHARED_LOCK;
  33129. return SQLITE_OK;
  33130. }
  33131. /* To fully unlock the database, delete the lock file */
  33132. assert( eFileLock==NO_LOCK );
  33133. rc = osRmdir(zLockFile);
  33134. if( rc<0 ){
  33135. int tErrno = errno;
  33136. if( tErrno==ENOENT ){
  33137. rc = SQLITE_OK;
  33138. }else{
  33139. rc = SQLITE_IOERR_UNLOCK;
  33140. storeLastErrno(pFile, tErrno);
  33141. }
  33142. return rc;
  33143. }
  33144. pFile->eFileLock = NO_LOCK;
  33145. return SQLITE_OK;
  33146. }
  33147. /*
  33148. ** Close a file. Make sure the lock has been released before closing.
  33149. */
  33150. static int dotlockClose(sqlite3_file *id) {
  33151. unixFile *pFile = (unixFile*)id;
  33152. assert( id!=0 );
  33153. dotlockUnlock(id, NO_LOCK);
  33154. sqlite3_free(pFile->lockingContext);
  33155. return closeUnixFile(id);
  33156. }
  33157. /****************** End of the dot-file lock implementation *******************
  33158. ******************************************************************************/
  33159. /******************************************************************************
  33160. ************************** Begin flock Locking ********************************
  33161. **
  33162. ** Use the flock() system call to do file locking.
  33163. **
  33164. ** flock() locking is like dot-file locking in that the various
  33165. ** fine-grain locking levels supported by SQLite are collapsed into
  33166. ** a single exclusive lock. In other words, SHARED, RESERVED, and
  33167. ** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
  33168. ** still works when you do this, but concurrency is reduced since
  33169. ** only a single process can be reading the database at a time.
  33170. **
  33171. ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
  33172. */
  33173. #if SQLITE_ENABLE_LOCKING_STYLE
  33174. /*
  33175. ** Retry flock() calls that fail with EINTR
  33176. */
  33177. #ifdef EINTR
  33178. static int robust_flock(int fd, int op){
  33179. int rc;
  33180. do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
  33181. return rc;
  33182. }
  33183. #else
  33184. # define robust_flock(a,b) flock(a,b)
  33185. #endif
  33186. /*
  33187. ** This routine checks if there is a RESERVED lock held on the specified
  33188. ** file by this or any other process. If such a lock is held, set *pResOut
  33189. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  33190. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  33191. */
  33192. static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
  33193. int rc = SQLITE_OK;
  33194. int reserved = 0;
  33195. unixFile *pFile = (unixFile*)id;
  33196. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  33197. assert( pFile );
  33198. /* Check if a thread in this process holds such a lock */
  33199. if( pFile->eFileLock>SHARED_LOCK ){
  33200. reserved = 1;
  33201. }
  33202. /* Otherwise see if some other process holds it. */
  33203. if( !reserved ){
  33204. /* attempt to get the lock */
  33205. int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
  33206. if( !lrc ){
  33207. /* got the lock, unlock it */
  33208. lrc = robust_flock(pFile->h, LOCK_UN);
  33209. if ( lrc ) {
  33210. int tErrno = errno;
  33211. /* unlock failed with an error */
  33212. lrc = SQLITE_IOERR_UNLOCK;
  33213. storeLastErrno(pFile, tErrno);
  33214. rc = lrc;
  33215. }
  33216. } else {
  33217. int tErrno = errno;
  33218. reserved = 1;
  33219. /* someone else might have it reserved */
  33220. lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  33221. if( IS_LOCK_ERROR(lrc) ){
  33222. storeLastErrno(pFile, tErrno);
  33223. rc = lrc;
  33224. }
  33225. }
  33226. }
  33227. OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
  33228. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  33229. if( (rc & 0xff) == SQLITE_IOERR ){
  33230. rc = SQLITE_OK;
  33231. reserved=1;
  33232. }
  33233. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  33234. *pResOut = reserved;
  33235. return rc;
  33236. }
  33237. /*
  33238. ** Lock the file with the lock specified by parameter eFileLock - one
  33239. ** of the following:
  33240. **
  33241. ** (1) SHARED_LOCK
  33242. ** (2) RESERVED_LOCK
  33243. ** (3) PENDING_LOCK
  33244. ** (4) EXCLUSIVE_LOCK
  33245. **
  33246. ** Sometimes when requesting one lock state, additional lock states
  33247. ** are inserted in between. The locking might fail on one of the later
  33248. ** transitions leaving the lock state different from what it started but
  33249. ** still short of its goal. The following chart shows the allowed
  33250. ** transitions and the inserted intermediate states:
  33251. **
  33252. ** UNLOCKED -> SHARED
  33253. ** SHARED -> RESERVED
  33254. ** SHARED -> (PENDING) -> EXCLUSIVE
  33255. ** RESERVED -> (PENDING) -> EXCLUSIVE
  33256. ** PENDING -> EXCLUSIVE
  33257. **
  33258. ** flock() only really support EXCLUSIVE locks. We track intermediate
  33259. ** lock states in the sqlite3_file structure, but all locks SHARED or
  33260. ** above are really EXCLUSIVE locks and exclude all other processes from
  33261. ** access the file.
  33262. **
  33263. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  33264. ** routine to lower a locking level.
  33265. */
  33266. static int flockLock(sqlite3_file *id, int eFileLock) {
  33267. int rc = SQLITE_OK;
  33268. unixFile *pFile = (unixFile*)id;
  33269. assert( pFile );
  33270. /* if we already have a lock, it is exclusive.
  33271. ** Just adjust level and punt on outta here. */
  33272. if (pFile->eFileLock > NO_LOCK) {
  33273. pFile->eFileLock = eFileLock;
  33274. return SQLITE_OK;
  33275. }
  33276. /* grab an exclusive lock */
  33277. if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
  33278. int tErrno = errno;
  33279. /* didn't get, must be busy */
  33280. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  33281. if( IS_LOCK_ERROR(rc) ){
  33282. storeLastErrno(pFile, tErrno);
  33283. }
  33284. } else {
  33285. /* got it, set the type and return ok */
  33286. pFile->eFileLock = eFileLock;
  33287. }
  33288. OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
  33289. rc==SQLITE_OK ? "ok" : "failed"));
  33290. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  33291. if( (rc & 0xff) == SQLITE_IOERR ){
  33292. rc = SQLITE_BUSY;
  33293. }
  33294. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  33295. return rc;
  33296. }
  33297. /*
  33298. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  33299. ** must be either NO_LOCK or SHARED_LOCK.
  33300. **
  33301. ** If the locking level of the file descriptor is already at or below
  33302. ** the requested locking level, this routine is a no-op.
  33303. */
  33304. static int flockUnlock(sqlite3_file *id, int eFileLock) {
  33305. unixFile *pFile = (unixFile*)id;
  33306. assert( pFile );
  33307. OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
  33308. pFile->eFileLock, osGetpid(0)));
  33309. assert( eFileLock<=SHARED_LOCK );
  33310. /* no-op if possible */
  33311. if( pFile->eFileLock==eFileLock ){
  33312. return SQLITE_OK;
  33313. }
  33314. /* shared can just be set because we always have an exclusive */
  33315. if (eFileLock==SHARED_LOCK) {
  33316. pFile->eFileLock = eFileLock;
  33317. return SQLITE_OK;
  33318. }
  33319. /* no, really, unlock. */
  33320. if( robust_flock(pFile->h, LOCK_UN) ){
  33321. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  33322. return SQLITE_OK;
  33323. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  33324. return SQLITE_IOERR_UNLOCK;
  33325. }else{
  33326. pFile->eFileLock = NO_LOCK;
  33327. return SQLITE_OK;
  33328. }
  33329. }
  33330. /*
  33331. ** Close a file.
  33332. */
  33333. static int flockClose(sqlite3_file *id) {
  33334. assert( id!=0 );
  33335. flockUnlock(id, NO_LOCK);
  33336. return closeUnixFile(id);
  33337. }
  33338. #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
  33339. /******************* End of the flock lock implementation *********************
  33340. ******************************************************************************/
  33341. /******************************************************************************
  33342. ************************ Begin Named Semaphore Locking ************************
  33343. **
  33344. ** Named semaphore locking is only supported on VxWorks.
  33345. **
  33346. ** Semaphore locking is like dot-lock and flock in that it really only
  33347. ** supports EXCLUSIVE locking. Only a single process can read or write
  33348. ** the database file at a time. This reduces potential concurrency, but
  33349. ** makes the lock implementation much easier.
  33350. */
  33351. #if OS_VXWORKS
  33352. /*
  33353. ** This routine checks if there is a RESERVED lock held on the specified
  33354. ** file by this or any other process. If such a lock is held, set *pResOut
  33355. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  33356. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  33357. */
  33358. static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
  33359. int rc = SQLITE_OK;
  33360. int reserved = 0;
  33361. unixFile *pFile = (unixFile*)id;
  33362. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  33363. assert( pFile );
  33364. /* Check if a thread in this process holds such a lock */
  33365. if( pFile->eFileLock>SHARED_LOCK ){
  33366. reserved = 1;
  33367. }
  33368. /* Otherwise see if some other process holds it. */
  33369. if( !reserved ){
  33370. sem_t *pSem = pFile->pInode->pSem;
  33371. if( sem_trywait(pSem)==-1 ){
  33372. int tErrno = errno;
  33373. if( EAGAIN != tErrno ){
  33374. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
  33375. storeLastErrno(pFile, tErrno);
  33376. } else {
  33377. /* someone else has the lock when we are in NO_LOCK */
  33378. reserved = (pFile->eFileLock < SHARED_LOCK);
  33379. }
  33380. }else{
  33381. /* we could have it if we want it */
  33382. sem_post(pSem);
  33383. }
  33384. }
  33385. OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
  33386. *pResOut = reserved;
  33387. return rc;
  33388. }
  33389. /*
  33390. ** Lock the file with the lock specified by parameter eFileLock - one
  33391. ** of the following:
  33392. **
  33393. ** (1) SHARED_LOCK
  33394. ** (2) RESERVED_LOCK
  33395. ** (3) PENDING_LOCK
  33396. ** (4) EXCLUSIVE_LOCK
  33397. **
  33398. ** Sometimes when requesting one lock state, additional lock states
  33399. ** are inserted in between. The locking might fail on one of the later
  33400. ** transitions leaving the lock state different from what it started but
  33401. ** still short of its goal. The following chart shows the allowed
  33402. ** transitions and the inserted intermediate states:
  33403. **
  33404. ** UNLOCKED -> SHARED
  33405. ** SHARED -> RESERVED
  33406. ** SHARED -> (PENDING) -> EXCLUSIVE
  33407. ** RESERVED -> (PENDING) -> EXCLUSIVE
  33408. ** PENDING -> EXCLUSIVE
  33409. **
  33410. ** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
  33411. ** lock states in the sqlite3_file structure, but all locks SHARED or
  33412. ** above are really EXCLUSIVE locks and exclude all other processes from
  33413. ** access the file.
  33414. **
  33415. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  33416. ** routine to lower a locking level.
  33417. */
  33418. static int semXLock(sqlite3_file *id, int eFileLock) {
  33419. unixFile *pFile = (unixFile*)id;
  33420. sem_t *pSem = pFile->pInode->pSem;
  33421. int rc = SQLITE_OK;
  33422. /* if we already have a lock, it is exclusive.
  33423. ** Just adjust level and punt on outta here. */
  33424. if (pFile->eFileLock > NO_LOCK) {
  33425. pFile->eFileLock = eFileLock;
  33426. rc = SQLITE_OK;
  33427. goto sem_end_lock;
  33428. }
  33429. /* lock semaphore now but bail out when already locked. */
  33430. if( sem_trywait(pSem)==-1 ){
  33431. rc = SQLITE_BUSY;
  33432. goto sem_end_lock;
  33433. }
  33434. /* got it, set the type and return ok */
  33435. pFile->eFileLock = eFileLock;
  33436. sem_end_lock:
  33437. return rc;
  33438. }
  33439. /*
  33440. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  33441. ** must be either NO_LOCK or SHARED_LOCK.
  33442. **
  33443. ** If the locking level of the file descriptor is already at or below
  33444. ** the requested locking level, this routine is a no-op.
  33445. */
  33446. static int semXUnlock(sqlite3_file *id, int eFileLock) {
  33447. unixFile *pFile = (unixFile*)id;
  33448. sem_t *pSem = pFile->pInode->pSem;
  33449. assert( pFile );
  33450. assert( pSem );
  33451. OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
  33452. pFile->eFileLock, osGetpid(0)));
  33453. assert( eFileLock<=SHARED_LOCK );
  33454. /* no-op if possible */
  33455. if( pFile->eFileLock==eFileLock ){
  33456. return SQLITE_OK;
  33457. }
  33458. /* shared can just be set because we always have an exclusive */
  33459. if (eFileLock==SHARED_LOCK) {
  33460. pFile->eFileLock = eFileLock;
  33461. return SQLITE_OK;
  33462. }
  33463. /* no, really unlock. */
  33464. if ( sem_post(pSem)==-1 ) {
  33465. int rc, tErrno = errno;
  33466. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
  33467. if( IS_LOCK_ERROR(rc) ){
  33468. storeLastErrno(pFile, tErrno);
  33469. }
  33470. return rc;
  33471. }
  33472. pFile->eFileLock = NO_LOCK;
  33473. return SQLITE_OK;
  33474. }
  33475. /*
  33476. ** Close a file.
  33477. */
  33478. static int semXClose(sqlite3_file *id) {
  33479. if( id ){
  33480. unixFile *pFile = (unixFile*)id;
  33481. semXUnlock(id, NO_LOCK);
  33482. assert( pFile );
  33483. assert( unixFileMutexNotheld(pFile) );
  33484. unixEnterMutex();
  33485. releaseInodeInfo(pFile);
  33486. unixLeaveMutex();
  33487. closeUnixFile(id);
  33488. }
  33489. return SQLITE_OK;
  33490. }
  33491. #endif /* OS_VXWORKS */
  33492. /*
  33493. ** Named semaphore locking is only available on VxWorks.
  33494. **
  33495. *************** End of the named semaphore lock implementation ****************
  33496. ******************************************************************************/
  33497. /******************************************************************************
  33498. *************************** Begin AFP Locking *********************************
  33499. **
  33500. ** AFP is the Apple Filing Protocol. AFP is a network filesystem found
  33501. ** on Apple Macintosh computers - both OS9 and OSX.
  33502. **
  33503. ** Third-party implementations of AFP are available. But this code here
  33504. ** only works on OSX.
  33505. */
  33506. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  33507. /*
  33508. ** The afpLockingContext structure contains all afp lock specific state
  33509. */
  33510. typedef struct afpLockingContext afpLockingContext;
  33511. struct afpLockingContext {
  33512. int reserved;
  33513. const char *dbPath; /* Name of the open file */
  33514. };
  33515. struct ByteRangeLockPB2
  33516. {
  33517. unsigned long long offset; /* offset to first byte to lock */
  33518. unsigned long long length; /* nbr of bytes to lock */
  33519. unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
  33520. unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
  33521. unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
  33522. int fd; /* file desc to assoc this lock with */
  33523. };
  33524. #define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
  33525. /*
  33526. ** This is a utility for setting or clearing a bit-range lock on an
  33527. ** AFP filesystem.
  33528. **
  33529. ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
  33530. */
  33531. static int afpSetLock(
  33532. const char *path, /* Name of the file to be locked or unlocked */
  33533. unixFile *pFile, /* Open file descriptor on path */
  33534. unsigned long long offset, /* First byte to be locked */
  33535. unsigned long long length, /* Number of bytes to lock */
  33536. int setLockFlag /* True to set lock. False to clear lock */
  33537. ){
  33538. struct ByteRangeLockPB2 pb;
  33539. int err;
  33540. pb.unLockFlag = setLockFlag ? 0 : 1;
  33541. pb.startEndFlag = 0;
  33542. pb.offset = offset;
  33543. pb.length = length;
  33544. pb.fd = pFile->h;
  33545. OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
  33546. (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
  33547. offset, length));
  33548. err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
  33549. if ( err==-1 ) {
  33550. int rc;
  33551. int tErrno = errno;
  33552. OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
  33553. path, tErrno, strerror(tErrno)));
  33554. #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
  33555. rc = SQLITE_BUSY;
  33556. #else
  33557. rc = sqliteErrorFromPosixError(tErrno,
  33558. setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
  33559. #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
  33560. if( IS_LOCK_ERROR(rc) ){
  33561. storeLastErrno(pFile, tErrno);
  33562. }
  33563. return rc;
  33564. } else {
  33565. return SQLITE_OK;
  33566. }
  33567. }
  33568. /*
  33569. ** This routine checks if there is a RESERVED lock held on the specified
  33570. ** file by this or any other process. If such a lock is held, set *pResOut
  33571. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  33572. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  33573. */
  33574. static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
  33575. int rc = SQLITE_OK;
  33576. int reserved = 0;
  33577. unixFile *pFile = (unixFile*)id;
  33578. afpLockingContext *context;
  33579. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  33580. assert( pFile );
  33581. context = (afpLockingContext *) pFile->lockingContext;
  33582. if( context->reserved ){
  33583. *pResOut = 1;
  33584. return SQLITE_OK;
  33585. }
  33586. sqlite3_mutex_enter(pFile->pInode->pLockMutex);
  33587. /* Check if a thread in this process holds such a lock */
  33588. if( pFile->pInode->eFileLock>SHARED_LOCK ){
  33589. reserved = 1;
  33590. }
  33591. /* Otherwise see if some other process holds it.
  33592. */
  33593. if( !reserved ){
  33594. /* lock the RESERVED byte */
  33595. int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
  33596. if( SQLITE_OK==lrc ){
  33597. /* if we succeeded in taking the reserved lock, unlock it to restore
  33598. ** the original state */
  33599. lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
  33600. } else {
  33601. /* if we failed to get the lock then someone else must have it */
  33602. reserved = 1;
  33603. }
  33604. if( IS_LOCK_ERROR(lrc) ){
  33605. rc=lrc;
  33606. }
  33607. }
  33608. sqlite3_mutex_leave(pFile->pInode->pLockMutex);
  33609. OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
  33610. *pResOut = reserved;
  33611. return rc;
  33612. }
  33613. /*
  33614. ** Lock the file with the lock specified by parameter eFileLock - one
  33615. ** of the following:
  33616. **
  33617. ** (1) SHARED_LOCK
  33618. ** (2) RESERVED_LOCK
  33619. ** (3) PENDING_LOCK
  33620. ** (4) EXCLUSIVE_LOCK
  33621. **
  33622. ** Sometimes when requesting one lock state, additional lock states
  33623. ** are inserted in between. The locking might fail on one of the later
  33624. ** transitions leaving the lock state different from what it started but
  33625. ** still short of its goal. The following chart shows the allowed
  33626. ** transitions and the inserted intermediate states:
  33627. **
  33628. ** UNLOCKED -> SHARED
  33629. ** SHARED -> RESERVED
  33630. ** SHARED -> (PENDING) -> EXCLUSIVE
  33631. ** RESERVED -> (PENDING) -> EXCLUSIVE
  33632. ** PENDING -> EXCLUSIVE
  33633. **
  33634. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  33635. ** routine to lower a locking level.
  33636. */
  33637. static int afpLock(sqlite3_file *id, int eFileLock){
  33638. int rc = SQLITE_OK;
  33639. unixFile *pFile = (unixFile*)id;
  33640. unixInodeInfo *pInode = pFile->pInode;
  33641. afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
  33642. assert( pFile );
  33643. OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
  33644. azFileLock(eFileLock), azFileLock(pFile->eFileLock),
  33645. azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
  33646. /* If there is already a lock of this type or more restrictive on the
  33647. ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
  33648. ** unixEnterMutex() hasn't been called yet.
  33649. */
  33650. if( pFile->eFileLock>=eFileLock ){
  33651. OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
  33652. azFileLock(eFileLock)));
  33653. return SQLITE_OK;
  33654. }
  33655. /* Make sure the locking sequence is correct
  33656. ** (1) We never move from unlocked to anything higher than shared lock.
  33657. ** (2) SQLite never explicitly requests a pendig lock.
  33658. ** (3) A shared lock is always held when a reserve lock is requested.
  33659. */
  33660. assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
  33661. assert( eFileLock!=PENDING_LOCK );
  33662. assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
  33663. /* This mutex is needed because pFile->pInode is shared across threads
  33664. */
  33665. pInode = pFile->pInode;
  33666. sqlite3_mutex_enter(pInode->pLockMutex);
  33667. /* If some thread using this PID has a lock via a different unixFile*
  33668. ** handle that precludes the requested lock, return BUSY.
  33669. */
  33670. if( (pFile->eFileLock!=pInode->eFileLock &&
  33671. (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
  33672. ){
  33673. rc = SQLITE_BUSY;
  33674. goto afp_end_lock;
  33675. }
  33676. /* If a SHARED lock is requested, and some thread using this PID already
  33677. ** has a SHARED or RESERVED lock, then increment reference counts and
  33678. ** return SQLITE_OK.
  33679. */
  33680. if( eFileLock==SHARED_LOCK &&
  33681. (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
  33682. assert( eFileLock==SHARED_LOCK );
  33683. assert( pFile->eFileLock==0 );
  33684. assert( pInode->nShared>0 );
  33685. pFile->eFileLock = SHARED_LOCK;
  33686. pInode->nShared++;
  33687. pInode->nLock++;
  33688. goto afp_end_lock;
  33689. }
  33690. /* A PENDING lock is needed before acquiring a SHARED lock and before
  33691. ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
  33692. ** be released.
  33693. */
  33694. if( eFileLock==SHARED_LOCK
  33695. || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
  33696. ){
  33697. int failed;
  33698. failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
  33699. if (failed) {
  33700. rc = failed;
  33701. goto afp_end_lock;
  33702. }
  33703. }
  33704. /* If control gets to this point, then actually go ahead and make
  33705. ** operating system calls for the specified lock.
  33706. */
  33707. if( eFileLock==SHARED_LOCK ){
  33708. int lrc1, lrc2, lrc1Errno = 0;
  33709. long lk, mask;
  33710. assert( pInode->nShared==0 );
  33711. assert( pInode->eFileLock==0 );
  33712. mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
  33713. /* Now get the read-lock SHARED_LOCK */
  33714. /* note that the quality of the randomness doesn't matter that much */
  33715. lk = random();
  33716. pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
  33717. lrc1 = afpSetLock(context->dbPath, pFile,
  33718. SHARED_FIRST+pInode->sharedByte, 1, 1);
  33719. if( IS_LOCK_ERROR(lrc1) ){
  33720. lrc1Errno = pFile->lastErrno;
  33721. }
  33722. /* Drop the temporary PENDING lock */
  33723. lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
  33724. if( IS_LOCK_ERROR(lrc1) ) {
  33725. storeLastErrno(pFile, lrc1Errno);
  33726. rc = lrc1;
  33727. goto afp_end_lock;
  33728. } else if( IS_LOCK_ERROR(lrc2) ){
  33729. rc = lrc2;
  33730. goto afp_end_lock;
  33731. } else if( lrc1 != SQLITE_OK ) {
  33732. rc = lrc1;
  33733. } else {
  33734. pFile->eFileLock = SHARED_LOCK;
  33735. pInode->nLock++;
  33736. pInode->nShared = 1;
  33737. }
  33738. }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
  33739. /* We are trying for an exclusive lock but another thread in this
  33740. ** same process is still holding a shared lock. */
  33741. rc = SQLITE_BUSY;
  33742. }else{
  33743. /* The request was for a RESERVED or EXCLUSIVE lock. It is
  33744. ** assumed that there is a SHARED or greater lock on the file
  33745. ** already.
  33746. */
  33747. int failed = 0;
  33748. assert( 0!=pFile->eFileLock );
  33749. if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
  33750. /* Acquire a RESERVED lock */
  33751. failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
  33752. if( !failed ){
  33753. context->reserved = 1;
  33754. }
  33755. }
  33756. if (!failed && eFileLock == EXCLUSIVE_LOCK) {
  33757. /* Acquire an EXCLUSIVE lock */
  33758. /* Remove the shared lock before trying the range. we'll need to
  33759. ** reestablish the shared lock if we can't get the afpUnlock
  33760. */
  33761. if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
  33762. pInode->sharedByte, 1, 0)) ){
  33763. int failed2 = SQLITE_OK;
  33764. /* now attemmpt to get the exclusive lock range */
  33765. failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
  33766. SHARED_SIZE, 1);
  33767. if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
  33768. SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
  33769. /* Can't reestablish the shared lock. Sqlite can't deal, this is
  33770. ** a critical I/O error
  33771. */
  33772. rc = ((failed & 0xff) == SQLITE_IOERR) ? failed2 :
  33773. SQLITE_IOERR_LOCK;
  33774. goto afp_end_lock;
  33775. }
  33776. }else{
  33777. rc = failed;
  33778. }
  33779. }
  33780. if( failed ){
  33781. rc = failed;
  33782. }
  33783. }
  33784. if( rc==SQLITE_OK ){
  33785. pFile->eFileLock = eFileLock;
  33786. pInode->eFileLock = eFileLock;
  33787. }else if( eFileLock==EXCLUSIVE_LOCK ){
  33788. pFile->eFileLock = PENDING_LOCK;
  33789. pInode->eFileLock = PENDING_LOCK;
  33790. }
  33791. afp_end_lock:
  33792. sqlite3_mutex_leave(pInode->pLockMutex);
  33793. OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
  33794. rc==SQLITE_OK ? "ok" : "failed"));
  33795. return rc;
  33796. }
  33797. /*
  33798. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  33799. ** must be either NO_LOCK or SHARED_LOCK.
  33800. **
  33801. ** If the locking level of the file descriptor is already at or below
  33802. ** the requested locking level, this routine is a no-op.
  33803. */
  33804. static int afpUnlock(sqlite3_file *id, int eFileLock) {
  33805. int rc = SQLITE_OK;
  33806. unixFile *pFile = (unixFile*)id;
  33807. unixInodeInfo *pInode;
  33808. afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
  33809. int skipShared = 0;
  33810. #ifdef SQLITE_TEST
  33811. int h = pFile->h;
  33812. #endif
  33813. assert( pFile );
  33814. OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
  33815. pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
  33816. osGetpid(0)));
  33817. assert( eFileLock<=SHARED_LOCK );
  33818. if( pFile->eFileLock<=eFileLock ){
  33819. return SQLITE_OK;
  33820. }
  33821. pInode = pFile->pInode;
  33822. sqlite3_mutex_enter(pInode->pLockMutex);
  33823. assert( pInode->nShared!=0 );
  33824. if( pFile->eFileLock>SHARED_LOCK ){
  33825. assert( pInode->eFileLock==pFile->eFileLock );
  33826. SimulateIOErrorBenign(1);
  33827. SimulateIOError( h=(-1) )
  33828. SimulateIOErrorBenign(0);
  33829. #ifdef SQLITE_DEBUG
  33830. /* When reducing a lock such that other processes can start
  33831. ** reading the database file again, make sure that the
  33832. ** transaction counter was updated if any part of the database
  33833. ** file changed. If the transaction counter is not updated,
  33834. ** other connections to the same file might not realize that
  33835. ** the file has changed and hence might not know to flush their
  33836. ** cache. The use of a stale cache can lead to database corruption.
  33837. */
  33838. assert( pFile->inNormalWrite==0
  33839. || pFile->dbUpdate==0
  33840. || pFile->transCntrChng==1 );
  33841. pFile->inNormalWrite = 0;
  33842. #endif
  33843. if( pFile->eFileLock==EXCLUSIVE_LOCK ){
  33844. rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
  33845. if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
  33846. /* only re-establish the shared lock if necessary */
  33847. int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
  33848. rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
  33849. } else {
  33850. skipShared = 1;
  33851. }
  33852. }
  33853. if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
  33854. rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
  33855. }
  33856. if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
  33857. rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
  33858. if( !rc ){
  33859. context->reserved = 0;
  33860. }
  33861. }
  33862. if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
  33863. pInode->eFileLock = SHARED_LOCK;
  33864. }
  33865. }
  33866. if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
  33867. /* Decrement the shared lock counter. Release the lock using an
  33868. ** OS call only when all threads in this same process have released
  33869. ** the lock.
  33870. */
  33871. unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
  33872. pInode->nShared--;
  33873. if( pInode->nShared==0 ){
  33874. SimulateIOErrorBenign(1);
  33875. SimulateIOError( h=(-1) )
  33876. SimulateIOErrorBenign(0);
  33877. if( !skipShared ){
  33878. rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
  33879. }
  33880. if( !rc ){
  33881. pInode->eFileLock = NO_LOCK;
  33882. pFile->eFileLock = NO_LOCK;
  33883. }
  33884. }
  33885. if( rc==SQLITE_OK ){
  33886. pInode->nLock--;
  33887. assert( pInode->nLock>=0 );
  33888. if( pInode->nLock==0 ) closePendingFds(pFile);
  33889. }
  33890. }
  33891. sqlite3_mutex_leave(pInode->pLockMutex);
  33892. if( rc==SQLITE_OK ){
  33893. pFile->eFileLock = eFileLock;
  33894. }
  33895. return rc;
  33896. }
  33897. /*
  33898. ** Close a file & cleanup AFP specific locking context
  33899. */
  33900. static int afpClose(sqlite3_file *id) {
  33901. int rc = SQLITE_OK;
  33902. unixFile *pFile = (unixFile*)id;
  33903. assert( id!=0 );
  33904. afpUnlock(id, NO_LOCK);
  33905. assert( unixFileMutexNotheld(pFile) );
  33906. unixEnterMutex();
  33907. if( pFile->pInode ){
  33908. unixInodeInfo *pInode = pFile->pInode;
  33909. sqlite3_mutex_enter(pInode->pLockMutex);
  33910. if( pInode->nLock ){
  33911. /* If there are outstanding locks, do not actually close the file just
  33912. ** yet because that would clear those locks. Instead, add the file
  33913. ** descriptor to pInode->aPending. It will be automatically closed when
  33914. ** the last lock is cleared.
  33915. */
  33916. setPendingFd(pFile);
  33917. }
  33918. sqlite3_mutex_leave(pInode->pLockMutex);
  33919. }
  33920. releaseInodeInfo(pFile);
  33921. sqlite3_free(pFile->lockingContext);
  33922. rc = closeUnixFile(id);
  33923. unixLeaveMutex();
  33924. return rc;
  33925. }
  33926. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  33927. /*
  33928. ** The code above is the AFP lock implementation. The code is specific
  33929. ** to MacOSX and does not work on other unix platforms. No alternative
  33930. ** is available. If you don't compile for a mac, then the "unix-afp"
  33931. ** VFS is not available.
  33932. **
  33933. ********************* End of the AFP lock implementation **********************
  33934. ******************************************************************************/
  33935. /******************************************************************************
  33936. *************************** Begin NFS Locking ********************************/
  33937. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  33938. /*
  33939. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  33940. ** must be either NO_LOCK or SHARED_LOCK.
  33941. **
  33942. ** If the locking level of the file descriptor is already at or below
  33943. ** the requested locking level, this routine is a no-op.
  33944. */
  33945. static int nfsUnlock(sqlite3_file *id, int eFileLock){
  33946. return posixUnlock(id, eFileLock, 1);
  33947. }
  33948. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  33949. /*
  33950. ** The code above is the NFS lock implementation. The code is specific
  33951. ** to MacOSX and does not work on other unix platforms. No alternative
  33952. ** is available.
  33953. **
  33954. ********************* End of the NFS lock implementation **********************
  33955. ******************************************************************************/
  33956. /******************************************************************************
  33957. **************** Non-locking sqlite3_file methods *****************************
  33958. **
  33959. ** The next division contains implementations for all methods of the
  33960. ** sqlite3_file object other than the locking methods. The locking
  33961. ** methods were defined in divisions above (one locking method per
  33962. ** division). Those methods that are common to all locking modes
  33963. ** are gather together into this division.
  33964. */
  33965. /*
  33966. ** Seek to the offset passed as the second argument, then read cnt
  33967. ** bytes into pBuf. Return the number of bytes actually read.
  33968. **
  33969. ** NB: If you define USE_PREAD or USE_PREAD64, then it might also
  33970. ** be necessary to define _XOPEN_SOURCE to be 500. This varies from
  33971. ** one system to another. Since SQLite does not define USE_PREAD
  33972. ** in any form by default, we will not attempt to define _XOPEN_SOURCE.
  33973. ** See tickets #2741 and #2681.
  33974. **
  33975. ** To avoid stomping the errno value on a failed read the lastErrno value
  33976. ** is set before returning.
  33977. */
  33978. static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
  33979. int got;
  33980. int prior = 0;
  33981. #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
  33982. i64 newOffset;
  33983. #endif
  33984. TIMER_START;
  33985. assert( cnt==(cnt&0x1ffff) );
  33986. assert( id->h>2 );
  33987. do{
  33988. #if defined(USE_PREAD)
  33989. got = osPread(id->h, pBuf, cnt, offset);
  33990. SimulateIOError( got = -1 );
  33991. #elif defined(USE_PREAD64)
  33992. got = osPread64(id->h, pBuf, cnt, offset);
  33993. SimulateIOError( got = -1 );
  33994. #else
  33995. newOffset = lseek(id->h, offset, SEEK_SET);
  33996. SimulateIOError( newOffset = -1 );
  33997. if( newOffset<0 ){
  33998. storeLastErrno((unixFile*)id, errno);
  33999. return -1;
  34000. }
  34001. got = osRead(id->h, pBuf, cnt);
  34002. #endif
  34003. if( got==cnt ) break;
  34004. if( got<0 ){
  34005. if( errno==EINTR ){ got = 1; continue; }
  34006. prior = 0;
  34007. storeLastErrno((unixFile*)id, errno);
  34008. break;
  34009. }else if( got>0 ){
  34010. cnt -= got;
  34011. offset += got;
  34012. prior += got;
  34013. pBuf = (void*)(got + (char*)pBuf);
  34014. }
  34015. }while( got>0 );
  34016. TIMER_END;
  34017. OSTRACE(("READ %-3d %5d %7lld %llu\n",
  34018. id->h, got+prior, offset-prior, TIMER_ELAPSED));
  34019. return got+prior;
  34020. }
  34021. /*
  34022. ** Read data from a file into a buffer. Return SQLITE_OK if all
  34023. ** bytes were read successfully and SQLITE_IOERR if anything goes
  34024. ** wrong.
  34025. */
  34026. static int unixRead(
  34027. sqlite3_file *id,
  34028. void *pBuf,
  34029. int amt,
  34030. sqlite3_int64 offset
  34031. ){
  34032. unixFile *pFile = (unixFile *)id;
  34033. int got;
  34034. assert( id );
  34035. assert( offset>=0 );
  34036. assert( amt>0 );
  34037. /* If this is a database file (not a journal, master-journal or temp
  34038. ** file), the bytes in the locking range should never be read or written. */
  34039. #if 0
  34040. assert( pFile->pPreallocatedUnused==0
  34041. || offset>=PENDING_BYTE+512
  34042. || offset+amt<=PENDING_BYTE
  34043. );
  34044. #endif
  34045. #if SQLITE_MAX_MMAP_SIZE>0
  34046. /* Deal with as much of this read request as possible by transfering
  34047. ** data from the memory mapping using memcpy(). */
  34048. if( offset<pFile->mmapSize ){
  34049. if( offset+amt <= pFile->mmapSize ){
  34050. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
  34051. return SQLITE_OK;
  34052. }else{
  34053. int nCopy = pFile->mmapSize - offset;
  34054. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
  34055. pBuf = &((u8 *)pBuf)[nCopy];
  34056. amt -= nCopy;
  34057. offset += nCopy;
  34058. }
  34059. }
  34060. #endif
  34061. got = seekAndRead(pFile, offset, pBuf, amt);
  34062. if( got==amt ){
  34063. return SQLITE_OK;
  34064. }else if( got<0 ){
  34065. /* lastErrno set by seekAndRead */
  34066. return SQLITE_IOERR_READ;
  34067. }else{
  34068. storeLastErrno(pFile, 0); /* not a system error */
  34069. /* Unread parts of the buffer must be zero-filled */
  34070. memset(&((char*)pBuf)[got], 0, amt-got);
  34071. return SQLITE_IOERR_SHORT_READ;
  34072. }
  34073. }
  34074. /*
  34075. ** Attempt to seek the file-descriptor passed as the first argument to
  34076. ** absolute offset iOff, then attempt to write nBuf bytes of data from
  34077. ** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
  34078. ** return the actual number of bytes written (which may be less than
  34079. ** nBuf).
  34080. */
  34081. static int seekAndWriteFd(
  34082. int fd, /* File descriptor to write to */
  34083. i64 iOff, /* File offset to begin writing at */
  34084. const void *pBuf, /* Copy data from this buffer to the file */
  34085. int nBuf, /* Size of buffer pBuf in bytes */
  34086. int *piErrno /* OUT: Error number if error occurs */
  34087. ){
  34088. int rc = 0; /* Value returned by system call */
  34089. assert( nBuf==(nBuf&0x1ffff) );
  34090. assert( fd>2 );
  34091. assert( piErrno!=0 );
  34092. nBuf &= 0x1ffff;
  34093. TIMER_START;
  34094. #if defined(USE_PREAD)
  34095. do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
  34096. #elif defined(USE_PREAD64)
  34097. do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
  34098. #else
  34099. do{
  34100. i64 iSeek = lseek(fd, iOff, SEEK_SET);
  34101. SimulateIOError( iSeek = -1 );
  34102. if( iSeek<0 ){
  34103. rc = -1;
  34104. break;
  34105. }
  34106. rc = osWrite(fd, pBuf, nBuf);
  34107. }while( rc<0 && errno==EINTR );
  34108. #endif
  34109. TIMER_END;
  34110. OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
  34111. if( rc<0 ) *piErrno = errno;
  34112. return rc;
  34113. }
  34114. /*
  34115. ** Seek to the offset in id->offset then read cnt bytes into pBuf.
  34116. ** Return the number of bytes actually read. Update the offset.
  34117. **
  34118. ** To avoid stomping the errno value on a failed write the lastErrno value
  34119. ** is set before returning.
  34120. */
  34121. static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
  34122. return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
  34123. }
  34124. /*
  34125. ** Write data from a buffer into a file. Return SQLITE_OK on success
  34126. ** or some other error code on failure.
  34127. */
  34128. static int unixWrite(
  34129. sqlite3_file *id,
  34130. const void *pBuf,
  34131. int amt,
  34132. sqlite3_int64 offset
  34133. ){
  34134. unixFile *pFile = (unixFile*)id;
  34135. int wrote = 0;
  34136. assert( id );
  34137. assert( amt>0 );
  34138. /* If this is a database file (not a journal, master-journal or temp
  34139. ** file), the bytes in the locking range should never be read or written. */
  34140. #if 0
  34141. assert( pFile->pPreallocatedUnused==0
  34142. || offset>=PENDING_BYTE+512
  34143. || offset+amt<=PENDING_BYTE
  34144. );
  34145. #endif
  34146. #ifdef SQLITE_DEBUG
  34147. /* If we are doing a normal write to a database file (as opposed to
  34148. ** doing a hot-journal rollback or a write to some file other than a
  34149. ** normal database file) then record the fact that the database
  34150. ** has changed. If the transaction counter is modified, record that
  34151. ** fact too.
  34152. */
  34153. if( pFile->inNormalWrite ){
  34154. pFile->dbUpdate = 1; /* The database has been modified */
  34155. if( offset<=24 && offset+amt>=27 ){
  34156. int rc;
  34157. char oldCntr[4];
  34158. SimulateIOErrorBenign(1);
  34159. rc = seekAndRead(pFile, 24, oldCntr, 4);
  34160. SimulateIOErrorBenign(0);
  34161. if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
  34162. pFile->transCntrChng = 1; /* The transaction counter has changed */
  34163. }
  34164. }
  34165. }
  34166. #endif
  34167. #if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
  34168. /* Deal with as much of this write request as possible by transfering
  34169. ** data from the memory mapping using memcpy(). */
  34170. if( offset<pFile->mmapSize ){
  34171. if( offset+amt <= pFile->mmapSize ){
  34172. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
  34173. return SQLITE_OK;
  34174. }else{
  34175. int nCopy = pFile->mmapSize - offset;
  34176. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
  34177. pBuf = &((u8 *)pBuf)[nCopy];
  34178. amt -= nCopy;
  34179. offset += nCopy;
  34180. }
  34181. }
  34182. #endif
  34183. while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
  34184. amt -= wrote;
  34185. offset += wrote;
  34186. pBuf = &((char*)pBuf)[wrote];
  34187. }
  34188. SimulateIOError(( wrote=(-1), amt=1 ));
  34189. SimulateDiskfullError(( wrote=0, amt=1 ));
  34190. if( amt>wrote ){
  34191. if( wrote<0 && pFile->lastErrno!=ENOSPC ){
  34192. /* lastErrno set by seekAndWrite */
  34193. return SQLITE_IOERR_WRITE;
  34194. }else{
  34195. storeLastErrno(pFile, 0); /* not a system error */
  34196. return SQLITE_FULL;
  34197. }
  34198. }
  34199. return SQLITE_OK;
  34200. }
  34201. #ifdef SQLITE_TEST
  34202. /*
  34203. ** Count the number of fullsyncs and normal syncs. This is used to test
  34204. ** that syncs and fullsyncs are occurring at the right times.
  34205. */
  34206. SQLITE_API int sqlite3_sync_count = 0;
  34207. SQLITE_API int sqlite3_fullsync_count = 0;
  34208. #endif
  34209. /*
  34210. ** We do not trust systems to provide a working fdatasync(). Some do.
  34211. ** Others do no. To be safe, we will stick with the (slightly slower)
  34212. ** fsync(). If you know that your system does support fdatasync() correctly,
  34213. ** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
  34214. */
  34215. #if !defined(fdatasync) && !HAVE_FDATASYNC
  34216. # define fdatasync fsync
  34217. #endif
  34218. /*
  34219. ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
  34220. ** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
  34221. ** only available on Mac OS X. But that could change.
  34222. */
  34223. #ifdef F_FULLFSYNC
  34224. # define HAVE_FULLFSYNC 1
  34225. #else
  34226. # define HAVE_FULLFSYNC 0
  34227. #endif
  34228. /*
  34229. ** The fsync() system call does not work as advertised on many
  34230. ** unix systems. The following procedure is an attempt to make
  34231. ** it work better.
  34232. **
  34233. ** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
  34234. ** for testing when we want to run through the test suite quickly.
  34235. ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
  34236. ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
  34237. ** or power failure will likely corrupt the database file.
  34238. **
  34239. ** SQLite sets the dataOnly flag if the size of the file is unchanged.
  34240. ** The idea behind dataOnly is that it should only write the file content
  34241. ** to disk, not the inode. We only set dataOnly if the file size is
  34242. ** unchanged since the file size is part of the inode. However,
  34243. ** Ted Ts'o tells us that fdatasync() will also write the inode if the
  34244. ** file size has changed. The only real difference between fdatasync()
  34245. ** and fsync(), Ted tells us, is that fdatasync() will not flush the
  34246. ** inode if the mtime or owner or other inode attributes have changed.
  34247. ** We only care about the file size, not the other file attributes, so
  34248. ** as far as SQLite is concerned, an fdatasync() is always adequate.
  34249. ** So, we always use fdatasync() if it is available, regardless of
  34250. ** the value of the dataOnly flag.
  34251. */
  34252. static int full_fsync(int fd, int fullSync, int dataOnly){
  34253. int rc;
  34254. /* The following "ifdef/elif/else/" block has the same structure as
  34255. ** the one below. It is replicated here solely to avoid cluttering
  34256. ** up the real code with the UNUSED_PARAMETER() macros.
  34257. */
  34258. #ifdef SQLITE_NO_SYNC
  34259. UNUSED_PARAMETER(fd);
  34260. UNUSED_PARAMETER(fullSync);
  34261. UNUSED_PARAMETER(dataOnly);
  34262. #elif HAVE_FULLFSYNC
  34263. UNUSED_PARAMETER(dataOnly);
  34264. #else
  34265. UNUSED_PARAMETER(fullSync);
  34266. UNUSED_PARAMETER(dataOnly);
  34267. #endif
  34268. /* Record the number of times that we do a normal fsync() and
  34269. ** FULLSYNC. This is used during testing to verify that this procedure
  34270. ** gets called with the correct arguments.
  34271. */
  34272. #ifdef SQLITE_TEST
  34273. if( fullSync ) sqlite3_fullsync_count++;
  34274. sqlite3_sync_count++;
  34275. #endif
  34276. /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
  34277. ** no-op. But go ahead and call fstat() to validate the file
  34278. ** descriptor as we need a method to provoke a failure during
  34279. ** coverate testing.
  34280. */
  34281. #ifdef SQLITE_NO_SYNC
  34282. {
  34283. struct stat buf;
  34284. rc = osFstat(fd, &buf);
  34285. }
  34286. #elif HAVE_FULLFSYNC
  34287. if( fullSync ){
  34288. rc = osFcntl(fd, F_FULLFSYNC, 0);
  34289. }else{
  34290. rc = 1;
  34291. }
  34292. /* If the FULLFSYNC failed, fall back to attempting an fsync().
  34293. ** It shouldn't be possible for fullfsync to fail on the local
  34294. ** file system (on OSX), so failure indicates that FULLFSYNC
  34295. ** isn't supported for this file system. So, attempt an fsync
  34296. ** and (for now) ignore the overhead of a superfluous fcntl call.
  34297. ** It'd be better to detect fullfsync support once and avoid
  34298. ** the fcntl call every time sync is called.
  34299. */
  34300. if( rc ) rc = fsync(fd);
  34301. #elif defined(__APPLE__)
  34302. /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
  34303. ** so currently we default to the macro that redefines fdatasync to fsync
  34304. */
  34305. rc = fsync(fd);
  34306. #else
  34307. rc = fdatasync(fd);
  34308. #if OS_VXWORKS
  34309. if( rc==-1 && errno==ENOTSUP ){
  34310. rc = fsync(fd);
  34311. }
  34312. #endif /* OS_VXWORKS */
  34313. #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
  34314. if( OS_VXWORKS && rc!= -1 ){
  34315. rc = 0;
  34316. }
  34317. return rc;
  34318. }
  34319. /*
  34320. ** Open a file descriptor to the directory containing file zFilename.
  34321. ** If successful, *pFd is set to the opened file descriptor and
  34322. ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
  34323. ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
  34324. ** value.
  34325. **
  34326. ** The directory file descriptor is used for only one thing - to
  34327. ** fsync() a directory to make sure file creation and deletion events
  34328. ** are flushed to disk. Such fsyncs are not needed on newer
  34329. ** journaling filesystems, but are required on older filesystems.
  34330. **
  34331. ** This routine can be overridden using the xSetSysCall interface.
  34332. ** The ability to override this routine was added in support of the
  34333. ** chromium sandbox. Opening a directory is a security risk (we are
  34334. ** told) so making it overrideable allows the chromium sandbox to
  34335. ** replace this routine with a harmless no-op. To make this routine
  34336. ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
  34337. ** *pFd set to a negative number.
  34338. **
  34339. ** If SQLITE_OK is returned, the caller is responsible for closing
  34340. ** the file descriptor *pFd using close().
  34341. */
  34342. static int openDirectory(const char *zFilename, int *pFd){
  34343. int ii;
  34344. int fd = -1;
  34345. char zDirname[MAX_PATHNAME+1];
  34346. sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
  34347. for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--);
  34348. if( ii>0 ){
  34349. zDirname[ii] = '\0';
  34350. }else{
  34351. if( zDirname[0]!='/' ) zDirname[0] = '.';
  34352. zDirname[1] = 0;
  34353. }
  34354. fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
  34355. if( fd>=0 ){
  34356. OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
  34357. }
  34358. *pFd = fd;
  34359. if( fd>=0 ) return SQLITE_OK;
  34360. return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname);
  34361. }
  34362. /*
  34363. ** Make sure all writes to a particular file are committed to disk.
  34364. **
  34365. ** If dataOnly==0 then both the file itself and its metadata (file
  34366. ** size, access time, etc) are synced. If dataOnly!=0 then only the
  34367. ** file data is synced.
  34368. **
  34369. ** Under Unix, also make sure that the directory entry for the file
  34370. ** has been created by fsync-ing the directory that contains the file.
  34371. ** If we do not do this and we encounter a power failure, the directory
  34372. ** entry for the journal might not exist after we reboot. The next
  34373. ** SQLite to access the file will not know that the journal exists (because
  34374. ** the directory entry for the journal was never created) and the transaction
  34375. ** will not roll back - possibly leading to database corruption.
  34376. */
  34377. static int unixSync(sqlite3_file *id, int flags){
  34378. int rc;
  34379. unixFile *pFile = (unixFile*)id;
  34380. int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
  34381. int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
  34382. /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
  34383. assert((flags&0x0F)==SQLITE_SYNC_NORMAL
  34384. || (flags&0x0F)==SQLITE_SYNC_FULL
  34385. );
  34386. /* Unix cannot, but some systems may return SQLITE_FULL from here. This
  34387. ** line is to test that doing so does not cause any problems.
  34388. */
  34389. SimulateDiskfullError( return SQLITE_FULL );
  34390. assert( pFile );
  34391. OSTRACE(("SYNC %-3d\n", pFile->h));
  34392. rc = full_fsync(pFile->h, isFullsync, isDataOnly);
  34393. SimulateIOError( rc=1 );
  34394. if( rc ){
  34395. storeLastErrno(pFile, errno);
  34396. return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
  34397. }
  34398. /* Also fsync the directory containing the file if the DIRSYNC flag
  34399. ** is set. This is a one-time occurrence. Many systems (examples: AIX)
  34400. ** are unable to fsync a directory, so ignore errors on the fsync.
  34401. */
  34402. if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
  34403. int dirfd;
  34404. OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
  34405. HAVE_FULLFSYNC, isFullsync));
  34406. rc = osOpenDirectory(pFile->zPath, &dirfd);
  34407. if( rc==SQLITE_OK ){
  34408. full_fsync(dirfd, 0, 0);
  34409. robust_close(pFile, dirfd, __LINE__);
  34410. }else{
  34411. assert( rc==SQLITE_CANTOPEN );
  34412. rc = SQLITE_OK;
  34413. }
  34414. pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
  34415. }
  34416. return rc;
  34417. }
  34418. /*
  34419. ** Truncate an open file to a specified size
  34420. */
  34421. static int unixTruncate(sqlite3_file *id, i64 nByte){
  34422. unixFile *pFile = (unixFile *)id;
  34423. int rc;
  34424. assert( pFile );
  34425. SimulateIOError( return SQLITE_IOERR_TRUNCATE );
  34426. /* If the user has configured a chunk-size for this file, truncate the
  34427. ** file so that it consists of an integer number of chunks (i.e. the
  34428. ** actual file size after the operation may be larger than the requested
  34429. ** size).
  34430. */
  34431. if( pFile->szChunk>0 ){
  34432. nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
  34433. }
  34434. rc = robust_ftruncate(pFile->h, nByte);
  34435. if( rc ){
  34436. storeLastErrno(pFile, errno);
  34437. return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
  34438. }else{
  34439. #ifdef SQLITE_DEBUG
  34440. /* If we are doing a normal write to a database file (as opposed to
  34441. ** doing a hot-journal rollback or a write to some file other than a
  34442. ** normal database file) and we truncate the file to zero length,
  34443. ** that effectively updates the change counter. This might happen
  34444. ** when restoring a database using the backup API from a zero-length
  34445. ** source.
  34446. */
  34447. if( pFile->inNormalWrite && nByte==0 ){
  34448. pFile->transCntrChng = 1;
  34449. }
  34450. #endif
  34451. #if SQLITE_MAX_MMAP_SIZE>0
  34452. /* If the file was just truncated to a size smaller than the currently
  34453. ** mapped region, reduce the effective mapping size as well. SQLite will
  34454. ** use read() and write() to access data beyond this point from now on.
  34455. */
  34456. if( nByte<pFile->mmapSize ){
  34457. pFile->mmapSize = nByte;
  34458. }
  34459. #endif
  34460. return SQLITE_OK;
  34461. }
  34462. }
  34463. /*
  34464. ** Determine the current size of a file in bytes
  34465. */
  34466. static int unixFileSize(sqlite3_file *id, i64 *pSize){
  34467. int rc;
  34468. struct stat buf;
  34469. assert( id );
  34470. rc = osFstat(((unixFile*)id)->h, &buf);
  34471. SimulateIOError( rc=1 );
  34472. if( rc!=0 ){
  34473. storeLastErrno((unixFile*)id, errno);
  34474. return SQLITE_IOERR_FSTAT;
  34475. }
  34476. *pSize = buf.st_size;
  34477. /* When opening a zero-size database, the findInodeInfo() procedure
  34478. ** writes a single byte into that file in order to work around a bug
  34479. ** in the OS-X msdos filesystem. In order to avoid problems with upper
  34480. ** layers, we need to report this file size as zero even though it is
  34481. ** really 1. Ticket #3260.
  34482. */
  34483. if( *pSize==1 ) *pSize = 0;
  34484. return SQLITE_OK;
  34485. }
  34486. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  34487. /*
  34488. ** Handler for proxy-locking file-control verbs. Defined below in the
  34489. ** proxying locking division.
  34490. */
  34491. static int proxyFileControl(sqlite3_file*,int,void*);
  34492. #endif
  34493. /*
  34494. ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
  34495. ** file-control operation. Enlarge the database to nBytes in size
  34496. ** (rounded up to the next chunk-size). If the database is already
  34497. ** nBytes or larger, this routine is a no-op.
  34498. */
  34499. static int fcntlSizeHint(unixFile *pFile, i64 nByte){
  34500. if( pFile->szChunk>0 ){
  34501. i64 nSize; /* Required file size */
  34502. struct stat buf; /* Used to hold return values of fstat() */
  34503. if( osFstat(pFile->h, &buf) ){
  34504. return SQLITE_IOERR_FSTAT;
  34505. }
  34506. nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
  34507. if( nSize>(i64)buf.st_size ){
  34508. #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
  34509. /* The code below is handling the return value of osFallocate()
  34510. ** correctly. posix_fallocate() is defined to "returns zero on success,
  34511. ** or an error number on failure". See the manpage for details. */
  34512. int err;
  34513. do{
  34514. err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
  34515. }while( err==EINTR );
  34516. if( err && err!=EINVAL ) return SQLITE_IOERR_WRITE;
  34517. #else
  34518. /* If the OS does not have posix_fallocate(), fake it. Write a
  34519. ** single byte to the last byte in each block that falls entirely
  34520. ** within the extended region. Then, if required, a single byte
  34521. ** at offset (nSize-1), to set the size of the file correctly.
  34522. ** This is a similar technique to that used by glibc on systems
  34523. ** that do not have a real fallocate() call.
  34524. */
  34525. int nBlk = buf.st_blksize; /* File-system block size */
  34526. int nWrite = 0; /* Number of bytes written by seekAndWrite */
  34527. i64 iWrite; /* Next offset to write to */
  34528. iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1;
  34529. assert( iWrite>=buf.st_size );
  34530. assert( ((iWrite+1)%nBlk)==0 );
  34531. for(/*no-op*/; iWrite<nSize+nBlk-1; iWrite+=nBlk ){
  34532. if( iWrite>=nSize ) iWrite = nSize - 1;
  34533. nWrite = seekAndWrite(pFile, iWrite, "", 1);
  34534. if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
  34535. }
  34536. #endif
  34537. }
  34538. }
  34539. #if SQLITE_MAX_MMAP_SIZE>0
  34540. if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
  34541. int rc;
  34542. if( pFile->szChunk<=0 ){
  34543. if( robust_ftruncate(pFile->h, nByte) ){
  34544. storeLastErrno(pFile, errno);
  34545. return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
  34546. }
  34547. }
  34548. rc = unixMapfile(pFile, nByte);
  34549. return rc;
  34550. }
  34551. #endif
  34552. return SQLITE_OK;
  34553. }
  34554. /*
  34555. ** If *pArg is initially negative then this is a query. Set *pArg to
  34556. ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
  34557. **
  34558. ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
  34559. */
  34560. static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
  34561. if( *pArg<0 ){
  34562. *pArg = (pFile->ctrlFlags & mask)!=0;
  34563. }else if( (*pArg)==0 ){
  34564. pFile->ctrlFlags &= ~mask;
  34565. }else{
  34566. pFile->ctrlFlags |= mask;
  34567. }
  34568. }
  34569. /* Forward declaration */
  34570. static int unixGetTempname(int nBuf, char *zBuf);
  34571. /*
  34572. ** Information and control of an open file handle.
  34573. */
  34574. static int unixFileControl(sqlite3_file *id, int op, void *pArg){
  34575. unixFile *pFile = (unixFile*)id;
  34576. switch( op ){
  34577. #if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
  34578. case SQLITE_FCNTL_BEGIN_ATOMIC_WRITE: {
  34579. int rc = osIoctl(pFile->h, F2FS_IOC_START_ATOMIC_WRITE);
  34580. return rc ? SQLITE_IOERR_BEGIN_ATOMIC : SQLITE_OK;
  34581. }
  34582. case SQLITE_FCNTL_COMMIT_ATOMIC_WRITE: {
  34583. int rc = osIoctl(pFile->h, F2FS_IOC_COMMIT_ATOMIC_WRITE);
  34584. return rc ? SQLITE_IOERR_COMMIT_ATOMIC : SQLITE_OK;
  34585. }
  34586. case SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE: {
  34587. int rc = osIoctl(pFile->h, F2FS_IOC_ABORT_VOLATILE_WRITE);
  34588. return rc ? SQLITE_IOERR_ROLLBACK_ATOMIC : SQLITE_OK;
  34589. }
  34590. #endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
  34591. case SQLITE_FCNTL_LOCKSTATE: {
  34592. *(int*)pArg = pFile->eFileLock;
  34593. return SQLITE_OK;
  34594. }
  34595. case SQLITE_FCNTL_LAST_ERRNO: {
  34596. *(int*)pArg = pFile->lastErrno;
  34597. return SQLITE_OK;
  34598. }
  34599. case SQLITE_FCNTL_CHUNK_SIZE: {
  34600. pFile->szChunk = *(int *)pArg;
  34601. return SQLITE_OK;
  34602. }
  34603. case SQLITE_FCNTL_SIZE_HINT: {
  34604. int rc;
  34605. SimulateIOErrorBenign(1);
  34606. rc = fcntlSizeHint(pFile, *(i64 *)pArg);
  34607. SimulateIOErrorBenign(0);
  34608. return rc;
  34609. }
  34610. case SQLITE_FCNTL_PERSIST_WAL: {
  34611. unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
  34612. return SQLITE_OK;
  34613. }
  34614. case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
  34615. unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
  34616. return SQLITE_OK;
  34617. }
  34618. case SQLITE_FCNTL_VFSNAME: {
  34619. *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
  34620. return SQLITE_OK;
  34621. }
  34622. case SQLITE_FCNTL_TEMPFILENAME: {
  34623. char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
  34624. if( zTFile ){
  34625. unixGetTempname(pFile->pVfs->mxPathname, zTFile);
  34626. *(char**)pArg = zTFile;
  34627. }
  34628. return SQLITE_OK;
  34629. }
  34630. case SQLITE_FCNTL_HAS_MOVED: {
  34631. *(int*)pArg = fileHasMoved(pFile);
  34632. return SQLITE_OK;
  34633. }
  34634. #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
  34635. case SQLITE_FCNTL_LOCK_TIMEOUT: {
  34636. pFile->iBusyTimeout = *(int*)pArg;
  34637. return SQLITE_OK;
  34638. }
  34639. #endif
  34640. #if SQLITE_MAX_MMAP_SIZE>0
  34641. case SQLITE_FCNTL_MMAP_SIZE: {
  34642. i64 newLimit = *(i64*)pArg;
  34643. int rc = SQLITE_OK;
  34644. if( newLimit>sqlite3GlobalConfig.mxMmap ){
  34645. newLimit = sqlite3GlobalConfig.mxMmap;
  34646. }
  34647. /* The value of newLimit may be eventually cast to (size_t) and passed
  34648. ** to mmap(). Restrict its value to 2GB if (size_t) is not at least a
  34649. ** 64-bit type. */
  34650. if( newLimit>0 && sizeof(size_t)<8 ){
  34651. newLimit = (newLimit & 0x7FFFFFFF);
  34652. }
  34653. *(i64*)pArg = pFile->mmapSizeMax;
  34654. if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
  34655. pFile->mmapSizeMax = newLimit;
  34656. if( pFile->mmapSize>0 ){
  34657. unixUnmapfile(pFile);
  34658. rc = unixMapfile(pFile, -1);
  34659. }
  34660. }
  34661. return rc;
  34662. }
  34663. #endif
  34664. #ifdef SQLITE_DEBUG
  34665. /* The pager calls this method to signal that it has done
  34666. ** a rollback and that the database is therefore unchanged and
  34667. ** it hence it is OK for the transaction change counter to be
  34668. ** unchanged.
  34669. */
  34670. case SQLITE_FCNTL_DB_UNCHANGED: {
  34671. ((unixFile*)id)->dbUpdate = 0;
  34672. return SQLITE_OK;
  34673. }
  34674. #endif
  34675. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  34676. case SQLITE_FCNTL_SET_LOCKPROXYFILE:
  34677. case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
  34678. return proxyFileControl(id,op,pArg);
  34679. }
  34680. #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
  34681. }
  34682. return SQLITE_NOTFOUND;
  34683. }
  34684. /*
  34685. ** If pFd->sectorSize is non-zero when this function is called, it is a
  34686. ** no-op. Otherwise, the values of pFd->sectorSize and
  34687. ** pFd->deviceCharacteristics are set according to the file-system
  34688. ** characteristics.
  34689. **
  34690. ** There are two versions of this function. One for QNX and one for all
  34691. ** other systems.
  34692. */
  34693. #ifndef __QNXNTO__
  34694. static void setDeviceCharacteristics(unixFile *pFd){
  34695. assert( pFd->deviceCharacteristics==0 || pFd->sectorSize!=0 );
  34696. if( pFd->sectorSize==0 ){
  34697. #if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
  34698. int res;
  34699. u32 f = 0;
  34700. /* Check for support for F2FS atomic batch writes. */
  34701. res = osIoctl(pFd->h, F2FS_IOC_GET_FEATURES, &f);
  34702. if( res==0 && (f & F2FS_FEATURE_ATOMIC_WRITE) ){
  34703. pFd->deviceCharacteristics = SQLITE_IOCAP_BATCH_ATOMIC;
  34704. }
  34705. #endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
  34706. /* Set the POWERSAFE_OVERWRITE flag if requested. */
  34707. if( pFd->ctrlFlags & UNIXFILE_PSOW ){
  34708. pFd->deviceCharacteristics |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
  34709. }
  34710. pFd->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
  34711. }
  34712. }
  34713. #else
  34714. #include <sys/dcmd_blk.h>
  34715. #include <sys/statvfs.h>
  34716. static void setDeviceCharacteristics(unixFile *pFile){
  34717. if( pFile->sectorSize == 0 ){
  34718. struct statvfs fsInfo;
  34719. /* Set defaults for non-supported filesystems */
  34720. pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
  34721. pFile->deviceCharacteristics = 0;
  34722. if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
  34723. return;
  34724. }
  34725. if( !strcmp(fsInfo.f_basetype, "tmp") ) {
  34726. pFile->sectorSize = fsInfo.f_bsize;
  34727. pFile->deviceCharacteristics =
  34728. SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
  34729. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  34730. ** the write succeeds */
  34731. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  34732. ** so it is ordered */
  34733. 0;
  34734. }else if( strstr(fsInfo.f_basetype, "etfs") ){
  34735. pFile->sectorSize = fsInfo.f_bsize;
  34736. pFile->deviceCharacteristics =
  34737. /* etfs cluster size writes are atomic */
  34738. (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
  34739. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  34740. ** the write succeeds */
  34741. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  34742. ** so it is ordered */
  34743. 0;
  34744. }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
  34745. pFile->sectorSize = fsInfo.f_bsize;
  34746. pFile->deviceCharacteristics =
  34747. SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
  34748. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  34749. ** the write succeeds */
  34750. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  34751. ** so it is ordered */
  34752. 0;
  34753. }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
  34754. pFile->sectorSize = fsInfo.f_bsize;
  34755. pFile->deviceCharacteristics =
  34756. /* full bitset of atomics from max sector size and smaller */
  34757. ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
  34758. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  34759. ** so it is ordered */
  34760. 0;
  34761. }else if( strstr(fsInfo.f_basetype, "dos") ){
  34762. pFile->sectorSize = fsInfo.f_bsize;
  34763. pFile->deviceCharacteristics =
  34764. /* full bitset of atomics from max sector size and smaller */
  34765. ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
  34766. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  34767. ** so it is ordered */
  34768. 0;
  34769. }else{
  34770. pFile->deviceCharacteristics =
  34771. SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
  34772. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  34773. ** the write succeeds */
  34774. 0;
  34775. }
  34776. }
  34777. /* Last chance verification. If the sector size isn't a multiple of 512
  34778. ** then it isn't valid.*/
  34779. if( pFile->sectorSize % 512 != 0 ){
  34780. pFile->deviceCharacteristics = 0;
  34781. pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
  34782. }
  34783. }
  34784. #endif
  34785. /*
  34786. ** Return the sector size in bytes of the underlying block device for
  34787. ** the specified file. This is almost always 512 bytes, but may be
  34788. ** larger for some devices.
  34789. **
  34790. ** SQLite code assumes this function cannot fail. It also assumes that
  34791. ** if two files are created in the same file-system directory (i.e.
  34792. ** a database and its journal file) that the sector size will be the
  34793. ** same for both.
  34794. */
  34795. static int unixSectorSize(sqlite3_file *id){
  34796. unixFile *pFd = (unixFile*)id;
  34797. setDeviceCharacteristics(pFd);
  34798. return pFd->sectorSize;
  34799. }
  34800. /*
  34801. ** Return the device characteristics for the file.
  34802. **
  34803. ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
  34804. ** However, that choice is controversial since technically the underlying
  34805. ** file system does not always provide powersafe overwrites. (In other
  34806. ** words, after a power-loss event, parts of the file that were never
  34807. ** written might end up being altered.) However, non-PSOW behavior is very,
  34808. ** very rare. And asserting PSOW makes a large reduction in the amount
  34809. ** of required I/O for journaling, since a lot of padding is eliminated.
  34810. ** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
  34811. ** available to turn it off and URI query parameter available to turn it off.
  34812. */
  34813. static int unixDeviceCharacteristics(sqlite3_file *id){
  34814. unixFile *pFd = (unixFile*)id;
  34815. setDeviceCharacteristics(pFd);
  34816. return pFd->deviceCharacteristics;
  34817. }
  34818. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  34819. /*
  34820. ** Return the system page size.
  34821. **
  34822. ** This function should not be called directly by other code in this file.
  34823. ** Instead, it should be called via macro osGetpagesize().
  34824. */
  34825. static int unixGetpagesize(void){
  34826. #if OS_VXWORKS
  34827. return 1024;
  34828. #elif defined(_BSD_SOURCE)
  34829. return getpagesize();
  34830. #else
  34831. return (int)sysconf(_SC_PAGESIZE);
  34832. #endif
  34833. }
  34834. #endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
  34835. #ifndef SQLITE_OMIT_WAL
  34836. /*
  34837. ** Object used to represent an shared memory buffer.
  34838. **
  34839. ** When multiple threads all reference the same wal-index, each thread
  34840. ** has its own unixShm object, but they all point to a single instance
  34841. ** of this unixShmNode object. In other words, each wal-index is opened
  34842. ** only once per process.
  34843. **
  34844. ** Each unixShmNode object is connected to a single unixInodeInfo object.
  34845. ** We could coalesce this object into unixInodeInfo, but that would mean
  34846. ** every open file that does not use shared memory (in other words, most
  34847. ** open files) would have to carry around this extra information. So
  34848. ** the unixInodeInfo object contains a pointer to this unixShmNode object
  34849. ** and the unixShmNode object is created only when needed.
  34850. **
  34851. ** unixMutexHeld() must be true when creating or destroying
  34852. ** this object or while reading or writing the following fields:
  34853. **
  34854. ** nRef
  34855. **
  34856. ** The following fields are read-only after the object is created:
  34857. **
  34858. ** hShm
  34859. ** zFilename
  34860. **
  34861. ** Either unixShmNode.pShmMutex must be held or unixShmNode.nRef==0 and
  34862. ** unixMutexHeld() is true when reading or writing any other field
  34863. ** in this structure.
  34864. */
  34865. struct unixShmNode {
  34866. unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
  34867. sqlite3_mutex *pShmMutex; /* Mutex to access this object */
  34868. char *zFilename; /* Name of the mmapped file */
  34869. int hShm; /* Open file descriptor */
  34870. int szRegion; /* Size of shared-memory regions */
  34871. u16 nRegion; /* Size of array apRegion */
  34872. u8 isReadonly; /* True if read-only */
  34873. u8 isUnlocked; /* True if no DMS lock held */
  34874. char **apRegion; /* Array of mapped shared-memory regions */
  34875. int nRef; /* Number of unixShm objects pointing to this */
  34876. unixShm *pFirst; /* All unixShm objects pointing to this */
  34877. #ifdef SQLITE_DEBUG
  34878. u8 exclMask; /* Mask of exclusive locks held */
  34879. u8 sharedMask; /* Mask of shared locks held */
  34880. u8 nextShmId; /* Next available unixShm.id value */
  34881. #endif
  34882. };
  34883. /*
  34884. ** Structure used internally by this VFS to record the state of an
  34885. ** open shared memory connection.
  34886. **
  34887. ** The following fields are initialized when this object is created and
  34888. ** are read-only thereafter:
  34889. **
  34890. ** unixShm.pShmNode
  34891. ** unixShm.id
  34892. **
  34893. ** All other fields are read/write. The unixShm.pShmNode->pShmMutex must
  34894. ** be held while accessing any read/write fields.
  34895. */
  34896. struct unixShm {
  34897. unixShmNode *pShmNode; /* The underlying unixShmNode object */
  34898. unixShm *pNext; /* Next unixShm with the same unixShmNode */
  34899. u8 hasMutex; /* True if holding the unixShmNode->pShmMutex */
  34900. u8 id; /* Id of this connection within its unixShmNode */
  34901. u16 sharedMask; /* Mask of shared locks held */
  34902. u16 exclMask; /* Mask of exclusive locks held */
  34903. };
  34904. /*
  34905. ** Constants used for locking
  34906. */
  34907. #define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
  34908. #define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
  34909. /*
  34910. ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
  34911. **
  34912. ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
  34913. ** otherwise.
  34914. */
  34915. static int unixShmSystemLock(
  34916. unixFile *pFile, /* Open connection to the WAL file */
  34917. int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
  34918. int ofst, /* First byte of the locking range */
  34919. int n /* Number of bytes to lock */
  34920. ){
  34921. unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
  34922. struct flock f; /* The posix advisory locking structure */
  34923. int rc = SQLITE_OK; /* Result code form fcntl() */
  34924. /* Access to the unixShmNode object is serialized by the caller */
  34925. pShmNode = pFile->pInode->pShmNode;
  34926. assert( pShmNode->nRef==0 || sqlite3_mutex_held(pShmNode->pShmMutex) );
  34927. assert( pShmNode->nRef>0 || unixMutexHeld() );
  34928. /* Shared locks never span more than one byte */
  34929. assert( n==1 || lockType!=F_RDLCK );
  34930. /* Locks are within range */
  34931. assert( n>=1 && n<=SQLITE_SHM_NLOCK );
  34932. if( pShmNode->hShm>=0 ){
  34933. /* Initialize the locking parameters */
  34934. f.l_type = lockType;
  34935. f.l_whence = SEEK_SET;
  34936. f.l_start = ofst;
  34937. f.l_len = n;
  34938. rc = osSetPosixAdvisoryLock(pShmNode->hShm, &f, pFile);
  34939. rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
  34940. }
  34941. /* Update the global lock state and do debug tracing */
  34942. #ifdef SQLITE_DEBUG
  34943. { u16 mask;
  34944. OSTRACE(("SHM-LOCK "));
  34945. mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
  34946. if( rc==SQLITE_OK ){
  34947. if( lockType==F_UNLCK ){
  34948. OSTRACE(("unlock %d ok", ofst));
  34949. pShmNode->exclMask &= ~mask;
  34950. pShmNode->sharedMask &= ~mask;
  34951. }else if( lockType==F_RDLCK ){
  34952. OSTRACE(("read-lock %d ok", ofst));
  34953. pShmNode->exclMask &= ~mask;
  34954. pShmNode->sharedMask |= mask;
  34955. }else{
  34956. assert( lockType==F_WRLCK );
  34957. OSTRACE(("write-lock %d ok", ofst));
  34958. pShmNode->exclMask |= mask;
  34959. pShmNode->sharedMask &= ~mask;
  34960. }
  34961. }else{
  34962. if( lockType==F_UNLCK ){
  34963. OSTRACE(("unlock %d failed", ofst));
  34964. }else if( lockType==F_RDLCK ){
  34965. OSTRACE(("read-lock failed"));
  34966. }else{
  34967. assert( lockType==F_WRLCK );
  34968. OSTRACE(("write-lock %d failed", ofst));
  34969. }
  34970. }
  34971. OSTRACE((" - afterwards %03x,%03x\n",
  34972. pShmNode->sharedMask, pShmNode->exclMask));
  34973. }
  34974. #endif
  34975. return rc;
  34976. }
  34977. /*
  34978. ** Return the minimum number of 32KB shm regions that should be mapped at
  34979. ** a time, assuming that each mapping must be an integer multiple of the
  34980. ** current system page-size.
  34981. **
  34982. ** Usually, this is 1. The exception seems to be systems that are configured
  34983. ** to use 64KB pages - in this case each mapping must cover at least two
  34984. ** shm regions.
  34985. */
  34986. static int unixShmRegionPerMap(void){
  34987. int shmsz = 32*1024; /* SHM region size */
  34988. int pgsz = osGetpagesize(); /* System page size */
  34989. assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
  34990. if( pgsz<shmsz ) return 1;
  34991. return pgsz/shmsz;
  34992. }
  34993. /*
  34994. ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
  34995. **
  34996. ** This is not a VFS shared-memory method; it is a utility function called
  34997. ** by VFS shared-memory methods.
  34998. */
  34999. static void unixShmPurge(unixFile *pFd){
  35000. unixShmNode *p = pFd->pInode->pShmNode;
  35001. assert( unixMutexHeld() );
  35002. if( p && ALWAYS(p->nRef==0) ){
  35003. int nShmPerMap = unixShmRegionPerMap();
  35004. int i;
  35005. assert( p->pInode==pFd->pInode );
  35006. sqlite3_mutex_free(p->pShmMutex);
  35007. for(i=0; i<p->nRegion; i+=nShmPerMap){
  35008. if( p->hShm>=0 ){
  35009. osMunmap(p->apRegion[i], p->szRegion);
  35010. }else{
  35011. sqlite3_free(p->apRegion[i]);
  35012. }
  35013. }
  35014. sqlite3_free(p->apRegion);
  35015. if( p->hShm>=0 ){
  35016. robust_close(pFd, p->hShm, __LINE__);
  35017. p->hShm = -1;
  35018. }
  35019. p->pInode->pShmNode = 0;
  35020. sqlite3_free(p);
  35021. }
  35022. }
  35023. /*
  35024. ** The DMS lock has not yet been taken on shm file pShmNode. Attempt to
  35025. ** take it now. Return SQLITE_OK if successful, or an SQLite error
  35026. ** code otherwise.
  35027. **
  35028. ** If the DMS cannot be locked because this is a readonly_shm=1
  35029. ** connection and no other process already holds a lock, return
  35030. ** SQLITE_READONLY_CANTINIT and set pShmNode->isUnlocked=1.
  35031. */
  35032. static int unixLockSharedMemory(unixFile *pDbFd, unixShmNode *pShmNode){
  35033. struct flock lock;
  35034. int rc = SQLITE_OK;
  35035. /* Use F_GETLK to determine the locks other processes are holding
  35036. ** on the DMS byte. If it indicates that another process is holding
  35037. ** a SHARED lock, then this process may also take a SHARED lock
  35038. ** and proceed with opening the *-shm file.
  35039. **
  35040. ** Or, if no other process is holding any lock, then this process
  35041. ** is the first to open it. In this case take an EXCLUSIVE lock on the
  35042. ** DMS byte and truncate the *-shm file to zero bytes in size. Then
  35043. ** downgrade to a SHARED lock on the DMS byte.
  35044. **
  35045. ** If another process is holding an EXCLUSIVE lock on the DMS byte,
  35046. ** return SQLITE_BUSY to the caller (it will try again). An earlier
  35047. ** version of this code attempted the SHARED lock at this point. But
  35048. ** this introduced a subtle race condition: if the process holding
  35049. ** EXCLUSIVE failed just before truncating the *-shm file, then this
  35050. ** process might open and use the *-shm file without truncating it.
  35051. ** And if the *-shm file has been corrupted by a power failure or
  35052. ** system crash, the database itself may also become corrupt. */
  35053. lock.l_whence = SEEK_SET;
  35054. lock.l_start = UNIX_SHM_DMS;
  35055. lock.l_len = 1;
  35056. lock.l_type = F_WRLCK;
  35057. if( osFcntl(pShmNode->hShm, F_GETLK, &lock)!=0 ) {
  35058. rc = SQLITE_IOERR_LOCK;
  35059. }else if( lock.l_type==F_UNLCK ){
  35060. if( pShmNode->isReadonly ){
  35061. pShmNode->isUnlocked = 1;
  35062. rc = SQLITE_READONLY_CANTINIT;
  35063. }else{
  35064. rc = unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1);
  35065. /* The first connection to attach must truncate the -shm file. We
  35066. ** truncate to 3 bytes (an arbitrary small number, less than the
  35067. ** -shm header size) rather than 0 as a system debugging aid, to
  35068. ** help detect if a -shm file truncation is legitimate or is the work
  35069. ** or a rogue process. */
  35070. if( rc==SQLITE_OK && robust_ftruncate(pShmNode->hShm, 3) ){
  35071. rc = unixLogError(SQLITE_IOERR_SHMOPEN,"ftruncate",pShmNode->zFilename);
  35072. }
  35073. }
  35074. }else if( lock.l_type==F_WRLCK ){
  35075. rc = SQLITE_BUSY;
  35076. }
  35077. if( rc==SQLITE_OK ){
  35078. assert( lock.l_type==F_UNLCK || lock.l_type==F_RDLCK );
  35079. rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
  35080. }
  35081. return rc;
  35082. }
  35083. /*
  35084. ** Open a shared-memory area associated with open database file pDbFd.
  35085. ** This particular implementation uses mmapped files.
  35086. **
  35087. ** The file used to implement shared-memory is in the same directory
  35088. ** as the open database file and has the same name as the open database
  35089. ** file with the "-shm" suffix added. For example, if the database file
  35090. ** is "/home/user1/config.db" then the file that is created and mmapped
  35091. ** for shared memory will be called "/home/user1/config.db-shm".
  35092. **
  35093. ** Another approach to is to use files in /dev/shm or /dev/tmp or an
  35094. ** some other tmpfs mount. But if a file in a different directory
  35095. ** from the database file is used, then differing access permissions
  35096. ** or a chroot() might cause two different processes on the same
  35097. ** database to end up using different files for shared memory -
  35098. ** meaning that their memory would not really be shared - resulting
  35099. ** in database corruption. Nevertheless, this tmpfs file usage
  35100. ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
  35101. ** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
  35102. ** option results in an incompatible build of SQLite; builds of SQLite
  35103. ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
  35104. ** same database file at the same time, database corruption will likely
  35105. ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
  35106. ** "unsupported" and may go away in a future SQLite release.
  35107. **
  35108. ** When opening a new shared-memory file, if no other instances of that
  35109. ** file are currently open, in this process or in other processes, then
  35110. ** the file must be truncated to zero length or have its header cleared.
  35111. **
  35112. ** If the original database file (pDbFd) is using the "unix-excl" VFS
  35113. ** that means that an exclusive lock is held on the database file and
  35114. ** that no other processes are able to read or write the database. In
  35115. ** that case, we do not really need shared memory. No shared memory
  35116. ** file is created. The shared memory will be simulated with heap memory.
  35117. */
  35118. static int unixOpenSharedMemory(unixFile *pDbFd){
  35119. struct unixShm *p = 0; /* The connection to be opened */
  35120. struct unixShmNode *pShmNode; /* The underlying mmapped file */
  35121. int rc = SQLITE_OK; /* Result code */
  35122. unixInodeInfo *pInode; /* The inode of fd */
  35123. char *zShm; /* Name of the file used for SHM */
  35124. int nShmFilename; /* Size of the SHM filename in bytes */
  35125. /* Allocate space for the new unixShm object. */
  35126. p = sqlite3_malloc64( sizeof(*p) );
  35127. if( p==0 ) return SQLITE_NOMEM_BKPT;
  35128. memset(p, 0, sizeof(*p));
  35129. assert( pDbFd->pShm==0 );
  35130. /* Check to see if a unixShmNode object already exists. Reuse an existing
  35131. ** one if present. Create a new one if necessary.
  35132. */
  35133. assert( unixFileMutexNotheld(pDbFd) );
  35134. unixEnterMutex();
  35135. pInode = pDbFd->pInode;
  35136. pShmNode = pInode->pShmNode;
  35137. if( pShmNode==0 ){
  35138. struct stat sStat; /* fstat() info for database file */
  35139. #ifndef SQLITE_SHM_DIRECTORY
  35140. const char *zBasePath = pDbFd->zPath;
  35141. #endif
  35142. /* Call fstat() to figure out the permissions on the database file. If
  35143. ** a new *-shm file is created, an attempt will be made to create it
  35144. ** with the same permissions.
  35145. */
  35146. if( osFstat(pDbFd->h, &sStat) ){
  35147. rc = SQLITE_IOERR_FSTAT;
  35148. goto shm_open_err;
  35149. }
  35150. #ifdef SQLITE_SHM_DIRECTORY
  35151. nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
  35152. #else
  35153. nShmFilename = 6 + (int)strlen(zBasePath);
  35154. #endif
  35155. pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
  35156. if( pShmNode==0 ){
  35157. rc = SQLITE_NOMEM_BKPT;
  35158. goto shm_open_err;
  35159. }
  35160. memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
  35161. zShm = pShmNode->zFilename = (char*)&pShmNode[1];
  35162. #ifdef SQLITE_SHM_DIRECTORY
  35163. sqlite3_snprintf(nShmFilename, zShm,
  35164. SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
  35165. (u32)sStat.st_ino, (u32)sStat.st_dev);
  35166. #else
  35167. sqlite3_snprintf(nShmFilename, zShm, "%s-shm", zBasePath);
  35168. sqlite3FileSuffix3(pDbFd->zPath, zShm);
  35169. #endif
  35170. pShmNode->hShm = -1;
  35171. pDbFd->pInode->pShmNode = pShmNode;
  35172. pShmNode->pInode = pDbFd->pInode;
  35173. if( sqlite3GlobalConfig.bCoreMutex ){
  35174. pShmNode->pShmMutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
  35175. if( pShmNode->pShmMutex==0 ){
  35176. rc = SQLITE_NOMEM_BKPT;
  35177. goto shm_open_err;
  35178. }
  35179. }
  35180. if( pInode->bProcessLock==0 ){
  35181. if( 0==sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
  35182. pShmNode->hShm = robust_open(zShm, O_RDWR|O_CREAT,(sStat.st_mode&0777));
  35183. }
  35184. if( pShmNode->hShm<0 ){
  35185. pShmNode->hShm = robust_open(zShm, O_RDONLY, (sStat.st_mode&0777));
  35186. if( pShmNode->hShm<0 ){
  35187. rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShm);
  35188. goto shm_open_err;
  35189. }
  35190. pShmNode->isReadonly = 1;
  35191. }
  35192. /* If this process is running as root, make sure that the SHM file
  35193. ** is owned by the same user that owns the original database. Otherwise,
  35194. ** the original owner will not be able to connect.
  35195. */
  35196. robustFchown(pShmNode->hShm, sStat.st_uid, sStat.st_gid);
  35197. rc = unixLockSharedMemory(pDbFd, pShmNode);
  35198. if( rc!=SQLITE_OK && rc!=SQLITE_READONLY_CANTINIT ) goto shm_open_err;
  35199. }
  35200. }
  35201. /* Make the new connection a child of the unixShmNode */
  35202. p->pShmNode = pShmNode;
  35203. #ifdef SQLITE_DEBUG
  35204. p->id = pShmNode->nextShmId++;
  35205. #endif
  35206. pShmNode->nRef++;
  35207. pDbFd->pShm = p;
  35208. unixLeaveMutex();
  35209. /* The reference count on pShmNode has already been incremented under
  35210. ** the cover of the unixEnterMutex() mutex and the pointer from the
  35211. ** new (struct unixShm) object to the pShmNode has been set. All that is
  35212. ** left to do is to link the new object into the linked list starting
  35213. ** at pShmNode->pFirst. This must be done while holding the
  35214. ** pShmNode->pShmMutex.
  35215. */
  35216. sqlite3_mutex_enter(pShmNode->pShmMutex);
  35217. p->pNext = pShmNode->pFirst;
  35218. pShmNode->pFirst = p;
  35219. sqlite3_mutex_leave(pShmNode->pShmMutex);
  35220. return rc;
  35221. /* Jump here on any error */
  35222. shm_open_err:
  35223. unixShmPurge(pDbFd); /* This call frees pShmNode if required */
  35224. sqlite3_free(p);
  35225. unixLeaveMutex();
  35226. return rc;
  35227. }
  35228. /*
  35229. ** This function is called to obtain a pointer to region iRegion of the
  35230. ** shared-memory associated with the database file fd. Shared-memory regions
  35231. ** are numbered starting from zero. Each shared-memory region is szRegion
  35232. ** bytes in size.
  35233. **
  35234. ** If an error occurs, an error code is returned and *pp is set to NULL.
  35235. **
  35236. ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
  35237. ** region has not been allocated (by any client, including one running in a
  35238. ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
  35239. ** bExtend is non-zero and the requested shared-memory region has not yet
  35240. ** been allocated, it is allocated by this function.
  35241. **
  35242. ** If the shared-memory region has already been allocated or is allocated by
  35243. ** this call as described above, then it is mapped into this processes
  35244. ** address space (if it is not already), *pp is set to point to the mapped
  35245. ** memory and SQLITE_OK returned.
  35246. */
  35247. static int unixShmMap(
  35248. sqlite3_file *fd, /* Handle open on database file */
  35249. int iRegion, /* Region to retrieve */
  35250. int szRegion, /* Size of regions */
  35251. int bExtend, /* True to extend file if necessary */
  35252. void volatile **pp /* OUT: Mapped memory */
  35253. ){
  35254. unixFile *pDbFd = (unixFile*)fd;
  35255. unixShm *p;
  35256. unixShmNode *pShmNode;
  35257. int rc = SQLITE_OK;
  35258. int nShmPerMap = unixShmRegionPerMap();
  35259. int nReqRegion;
  35260. /* If the shared-memory file has not yet been opened, open it now. */
  35261. if( pDbFd->pShm==0 ){
  35262. rc = unixOpenSharedMemory(pDbFd);
  35263. if( rc!=SQLITE_OK ) return rc;
  35264. }
  35265. p = pDbFd->pShm;
  35266. pShmNode = p->pShmNode;
  35267. sqlite3_mutex_enter(pShmNode->pShmMutex);
  35268. if( pShmNode->isUnlocked ){
  35269. rc = unixLockSharedMemory(pDbFd, pShmNode);
  35270. if( rc!=SQLITE_OK ) goto shmpage_out;
  35271. pShmNode->isUnlocked = 0;
  35272. }
  35273. assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
  35274. assert( pShmNode->pInode==pDbFd->pInode );
  35275. assert( pShmNode->hShm>=0 || pDbFd->pInode->bProcessLock==1 );
  35276. assert( pShmNode->hShm<0 || pDbFd->pInode->bProcessLock==0 );
  35277. /* Minimum number of regions required to be mapped. */
  35278. nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
  35279. if( pShmNode->nRegion<nReqRegion ){
  35280. char **apNew; /* New apRegion[] array */
  35281. int nByte = nReqRegion*szRegion; /* Minimum required file size */
  35282. struct stat sStat; /* Used by fstat() */
  35283. pShmNode->szRegion = szRegion;
  35284. if( pShmNode->hShm>=0 ){
  35285. /* The requested region is not mapped into this processes address space.
  35286. ** Check to see if it has been allocated (i.e. if the wal-index file is
  35287. ** large enough to contain the requested region).
  35288. */
  35289. if( osFstat(pShmNode->hShm, &sStat) ){
  35290. rc = SQLITE_IOERR_SHMSIZE;
  35291. goto shmpage_out;
  35292. }
  35293. if( sStat.st_size<nByte ){
  35294. /* The requested memory region does not exist. If bExtend is set to
  35295. ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
  35296. */
  35297. if( !bExtend ){
  35298. goto shmpage_out;
  35299. }
  35300. /* Alternatively, if bExtend is true, extend the file. Do this by
  35301. ** writing a single byte to the end of each (OS) page being
  35302. ** allocated or extended. Technically, we need only write to the
  35303. ** last page in order to extend the file. But writing to all new
  35304. ** pages forces the OS to allocate them immediately, which reduces
  35305. ** the chances of SIGBUS while accessing the mapped region later on.
  35306. */
  35307. else{
  35308. static const int pgsz = 4096;
  35309. int iPg;
  35310. /* Write to the last byte of each newly allocated or extended page */
  35311. assert( (nByte % pgsz)==0 );
  35312. for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
  35313. int x = 0;
  35314. if( seekAndWriteFd(pShmNode->hShm, iPg*pgsz + pgsz-1,"",1,&x)!=1 ){
  35315. const char *zFile = pShmNode->zFilename;
  35316. rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
  35317. goto shmpage_out;
  35318. }
  35319. }
  35320. }
  35321. }
  35322. }
  35323. /* Map the requested memory region into this processes address space. */
  35324. apNew = (char **)sqlite3_realloc(
  35325. pShmNode->apRegion, nReqRegion*sizeof(char *)
  35326. );
  35327. if( !apNew ){
  35328. rc = SQLITE_IOERR_NOMEM_BKPT;
  35329. goto shmpage_out;
  35330. }
  35331. pShmNode->apRegion = apNew;
  35332. while( pShmNode->nRegion<nReqRegion ){
  35333. int nMap = szRegion*nShmPerMap;
  35334. int i;
  35335. void *pMem;
  35336. if( pShmNode->hShm>=0 ){
  35337. pMem = osMmap(0, nMap,
  35338. pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
  35339. MAP_SHARED, pShmNode->hShm, szRegion*(i64)pShmNode->nRegion
  35340. );
  35341. if( pMem==MAP_FAILED ){
  35342. rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
  35343. goto shmpage_out;
  35344. }
  35345. }else{
  35346. pMem = sqlite3_malloc64(nMap);
  35347. if( pMem==0 ){
  35348. rc = SQLITE_NOMEM_BKPT;
  35349. goto shmpage_out;
  35350. }
  35351. memset(pMem, 0, nMap);
  35352. }
  35353. for(i=0; i<nShmPerMap; i++){
  35354. pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
  35355. }
  35356. pShmNode->nRegion += nShmPerMap;
  35357. }
  35358. }
  35359. shmpage_out:
  35360. if( pShmNode->nRegion>iRegion ){
  35361. *pp = pShmNode->apRegion[iRegion];
  35362. }else{
  35363. *pp = 0;
  35364. }
  35365. if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
  35366. sqlite3_mutex_leave(pShmNode->pShmMutex);
  35367. return rc;
  35368. }
  35369. /*
  35370. ** Change the lock state for a shared-memory segment.
  35371. **
  35372. ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
  35373. ** different here than in posix. In xShmLock(), one can go from unlocked
  35374. ** to shared and back or from unlocked to exclusive and back. But one may
  35375. ** not go from shared to exclusive or from exclusive to shared.
  35376. */
  35377. static int unixShmLock(
  35378. sqlite3_file *fd, /* Database file holding the shared memory */
  35379. int ofst, /* First lock to acquire or release */
  35380. int n, /* Number of locks to acquire or release */
  35381. int flags /* What to do with the lock */
  35382. ){
  35383. unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
  35384. unixShm *p = pDbFd->pShm; /* The shared memory being locked */
  35385. unixShm *pX; /* For looping over all siblings */
  35386. unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
  35387. int rc = SQLITE_OK; /* Result code */
  35388. u16 mask; /* Mask of locks to take or release */
  35389. assert( pShmNode==pDbFd->pInode->pShmNode );
  35390. assert( pShmNode->pInode==pDbFd->pInode );
  35391. assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
  35392. assert( n>=1 );
  35393. assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
  35394. || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
  35395. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
  35396. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
  35397. assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
  35398. assert( pShmNode->hShm>=0 || pDbFd->pInode->bProcessLock==1 );
  35399. assert( pShmNode->hShm<0 || pDbFd->pInode->bProcessLock==0 );
  35400. mask = (1<<(ofst+n)) - (1<<ofst);
  35401. assert( n>1 || mask==(1<<ofst) );
  35402. sqlite3_mutex_enter(pShmNode->pShmMutex);
  35403. if( flags & SQLITE_SHM_UNLOCK ){
  35404. u16 allMask = 0; /* Mask of locks held by siblings */
  35405. /* See if any siblings hold this same lock */
  35406. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  35407. if( pX==p ) continue;
  35408. assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
  35409. allMask |= pX->sharedMask;
  35410. }
  35411. /* Unlock the system-level locks */
  35412. if( (mask & allMask)==0 ){
  35413. rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
  35414. }else{
  35415. rc = SQLITE_OK;
  35416. }
  35417. /* Undo the local locks */
  35418. if( rc==SQLITE_OK ){
  35419. p->exclMask &= ~mask;
  35420. p->sharedMask &= ~mask;
  35421. }
  35422. }else if( flags & SQLITE_SHM_SHARED ){
  35423. u16 allShared = 0; /* Union of locks held by connections other than "p" */
  35424. /* Find out which shared locks are already held by sibling connections.
  35425. ** If any sibling already holds an exclusive lock, go ahead and return
  35426. ** SQLITE_BUSY.
  35427. */
  35428. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  35429. if( (pX->exclMask & mask)!=0 ){
  35430. rc = SQLITE_BUSY;
  35431. break;
  35432. }
  35433. allShared |= pX->sharedMask;
  35434. }
  35435. /* Get shared locks at the system level, if necessary */
  35436. if( rc==SQLITE_OK ){
  35437. if( (allShared & mask)==0 ){
  35438. rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
  35439. }else{
  35440. rc = SQLITE_OK;
  35441. }
  35442. }
  35443. /* Get the local shared locks */
  35444. if( rc==SQLITE_OK ){
  35445. p->sharedMask |= mask;
  35446. }
  35447. }else{
  35448. /* Make sure no sibling connections hold locks that will block this
  35449. ** lock. If any do, return SQLITE_BUSY right away.
  35450. */
  35451. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  35452. if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
  35453. rc = SQLITE_BUSY;
  35454. break;
  35455. }
  35456. }
  35457. /* Get the exclusive locks at the system level. Then if successful
  35458. ** also mark the local connection as being locked.
  35459. */
  35460. if( rc==SQLITE_OK ){
  35461. rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
  35462. if( rc==SQLITE_OK ){
  35463. assert( (p->sharedMask & mask)==0 );
  35464. p->exclMask |= mask;
  35465. }
  35466. }
  35467. }
  35468. sqlite3_mutex_leave(pShmNode->pShmMutex);
  35469. OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
  35470. p->id, osGetpid(0), p->sharedMask, p->exclMask));
  35471. return rc;
  35472. }
  35473. /*
  35474. ** Implement a memory barrier or memory fence on shared memory.
  35475. **
  35476. ** All loads and stores begun before the barrier must complete before
  35477. ** any load or store begun after the barrier.
  35478. */
  35479. static void unixShmBarrier(
  35480. sqlite3_file *fd /* Database file holding the shared memory */
  35481. ){
  35482. UNUSED_PARAMETER(fd);
  35483. sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
  35484. assert( fd->pMethods->xLock==nolockLock
  35485. || unixFileMutexNotheld((unixFile*)fd)
  35486. );
  35487. unixEnterMutex(); /* Also mutex, for redundancy */
  35488. unixLeaveMutex();
  35489. }
  35490. /*
  35491. ** Close a connection to shared-memory. Delete the underlying
  35492. ** storage if deleteFlag is true.
  35493. **
  35494. ** If there is no shared memory associated with the connection then this
  35495. ** routine is a harmless no-op.
  35496. */
  35497. static int unixShmUnmap(
  35498. sqlite3_file *fd, /* The underlying database file */
  35499. int deleteFlag /* Delete shared-memory if true */
  35500. ){
  35501. unixShm *p; /* The connection to be closed */
  35502. unixShmNode *pShmNode; /* The underlying shared-memory file */
  35503. unixShm **pp; /* For looping over sibling connections */
  35504. unixFile *pDbFd; /* The underlying database file */
  35505. pDbFd = (unixFile*)fd;
  35506. p = pDbFd->pShm;
  35507. if( p==0 ) return SQLITE_OK;
  35508. pShmNode = p->pShmNode;
  35509. assert( pShmNode==pDbFd->pInode->pShmNode );
  35510. assert( pShmNode->pInode==pDbFd->pInode );
  35511. /* Remove connection p from the set of connections associated
  35512. ** with pShmNode */
  35513. sqlite3_mutex_enter(pShmNode->pShmMutex);
  35514. for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
  35515. *pp = p->pNext;
  35516. /* Free the connection p */
  35517. sqlite3_free(p);
  35518. pDbFd->pShm = 0;
  35519. sqlite3_mutex_leave(pShmNode->pShmMutex);
  35520. /* If pShmNode->nRef has reached 0, then close the underlying
  35521. ** shared-memory file, too */
  35522. assert( unixFileMutexNotheld(pDbFd) );
  35523. unixEnterMutex();
  35524. assert( pShmNode->nRef>0 );
  35525. pShmNode->nRef--;
  35526. if( pShmNode->nRef==0 ){
  35527. if( deleteFlag && pShmNode->hShm>=0 ){
  35528. osUnlink(pShmNode->zFilename);
  35529. }
  35530. unixShmPurge(pDbFd);
  35531. }
  35532. unixLeaveMutex();
  35533. return SQLITE_OK;
  35534. }
  35535. #else
  35536. # define unixShmMap 0
  35537. # define unixShmLock 0
  35538. # define unixShmBarrier 0
  35539. # define unixShmUnmap 0
  35540. #endif /* #ifndef SQLITE_OMIT_WAL */
  35541. #if SQLITE_MAX_MMAP_SIZE>0
  35542. /*
  35543. ** If it is currently memory mapped, unmap file pFd.
  35544. */
  35545. static void unixUnmapfile(unixFile *pFd){
  35546. assert( pFd->nFetchOut==0 );
  35547. if( pFd->pMapRegion ){
  35548. osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
  35549. pFd->pMapRegion = 0;
  35550. pFd->mmapSize = 0;
  35551. pFd->mmapSizeActual = 0;
  35552. }
  35553. }
  35554. /*
  35555. ** Attempt to set the size of the memory mapping maintained by file
  35556. ** descriptor pFd to nNew bytes. Any existing mapping is discarded.
  35557. **
  35558. ** If successful, this function sets the following variables:
  35559. **
  35560. ** unixFile.pMapRegion
  35561. ** unixFile.mmapSize
  35562. ** unixFile.mmapSizeActual
  35563. **
  35564. ** If unsuccessful, an error message is logged via sqlite3_log() and
  35565. ** the three variables above are zeroed. In this case SQLite should
  35566. ** continue accessing the database using the xRead() and xWrite()
  35567. ** methods.
  35568. */
  35569. static void unixRemapfile(
  35570. unixFile *pFd, /* File descriptor object */
  35571. i64 nNew /* Required mapping size */
  35572. ){
  35573. const char *zErr = "mmap";
  35574. int h = pFd->h; /* File descriptor open on db file */
  35575. u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
  35576. i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
  35577. u8 *pNew = 0; /* Location of new mapping */
  35578. int flags = PROT_READ; /* Flags to pass to mmap() */
  35579. assert( pFd->nFetchOut==0 );
  35580. assert( nNew>pFd->mmapSize );
  35581. assert( nNew<=pFd->mmapSizeMax );
  35582. assert( nNew>0 );
  35583. assert( pFd->mmapSizeActual>=pFd->mmapSize );
  35584. assert( MAP_FAILED!=0 );
  35585. #ifdef SQLITE_MMAP_READWRITE
  35586. if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
  35587. #endif
  35588. if( pOrig ){
  35589. #if HAVE_MREMAP
  35590. i64 nReuse = pFd->mmapSize;
  35591. #else
  35592. const int szSyspage = osGetpagesize();
  35593. i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
  35594. #endif
  35595. u8 *pReq = &pOrig[nReuse];
  35596. /* Unmap any pages of the existing mapping that cannot be reused. */
  35597. if( nReuse!=nOrig ){
  35598. osMunmap(pReq, nOrig-nReuse);
  35599. }
  35600. #if HAVE_MREMAP
  35601. pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
  35602. zErr = "mremap";
  35603. #else
  35604. pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
  35605. if( pNew!=MAP_FAILED ){
  35606. if( pNew!=pReq ){
  35607. osMunmap(pNew, nNew - nReuse);
  35608. pNew = 0;
  35609. }else{
  35610. pNew = pOrig;
  35611. }
  35612. }
  35613. #endif
  35614. /* The attempt to extend the existing mapping failed. Free it. */
  35615. if( pNew==MAP_FAILED || pNew==0 ){
  35616. osMunmap(pOrig, nReuse);
  35617. }
  35618. }
  35619. /* If pNew is still NULL, try to create an entirely new mapping. */
  35620. if( pNew==0 ){
  35621. pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
  35622. }
  35623. if( pNew==MAP_FAILED ){
  35624. pNew = 0;
  35625. nNew = 0;
  35626. unixLogError(SQLITE_OK, zErr, pFd->zPath);
  35627. /* If the mmap() above failed, assume that all subsequent mmap() calls
  35628. ** will probably fail too. Fall back to using xRead/xWrite exclusively
  35629. ** in this case. */
  35630. pFd->mmapSizeMax = 0;
  35631. }
  35632. pFd->pMapRegion = (void *)pNew;
  35633. pFd->mmapSize = pFd->mmapSizeActual = nNew;
  35634. }
  35635. /*
  35636. ** Memory map or remap the file opened by file-descriptor pFd (if the file
  35637. ** is already mapped, the existing mapping is replaced by the new). Or, if
  35638. ** there already exists a mapping for this file, and there are still
  35639. ** outstanding xFetch() references to it, this function is a no-op.
  35640. **
  35641. ** If parameter nByte is non-negative, then it is the requested size of
  35642. ** the mapping to create. Otherwise, if nByte is less than zero, then the
  35643. ** requested size is the size of the file on disk. The actual size of the
  35644. ** created mapping is either the requested size or the value configured
  35645. ** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
  35646. **
  35647. ** SQLITE_OK is returned if no error occurs (even if the mapping is not
  35648. ** recreated as a result of outstanding references) or an SQLite error
  35649. ** code otherwise.
  35650. */
  35651. static int unixMapfile(unixFile *pFd, i64 nMap){
  35652. assert( nMap>=0 || pFd->nFetchOut==0 );
  35653. assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
  35654. if( pFd->nFetchOut>0 ) return SQLITE_OK;
  35655. if( nMap<0 ){
  35656. struct stat statbuf; /* Low-level file information */
  35657. if( osFstat(pFd->h, &statbuf) ){
  35658. return SQLITE_IOERR_FSTAT;
  35659. }
  35660. nMap = statbuf.st_size;
  35661. }
  35662. if( nMap>pFd->mmapSizeMax ){
  35663. nMap = pFd->mmapSizeMax;
  35664. }
  35665. assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
  35666. if( nMap!=pFd->mmapSize ){
  35667. unixRemapfile(pFd, nMap);
  35668. }
  35669. return SQLITE_OK;
  35670. }
  35671. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  35672. /*
  35673. ** If possible, return a pointer to a mapping of file fd starting at offset
  35674. ** iOff. The mapping must be valid for at least nAmt bytes.
  35675. **
  35676. ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
  35677. ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
  35678. ** Finally, if an error does occur, return an SQLite error code. The final
  35679. ** value of *pp is undefined in this case.
  35680. **
  35681. ** If this function does return a pointer, the caller must eventually
  35682. ** release the reference by calling unixUnfetch().
  35683. */
  35684. static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
  35685. #if SQLITE_MAX_MMAP_SIZE>0
  35686. unixFile *pFd = (unixFile *)fd; /* The underlying database file */
  35687. #endif
  35688. *pp = 0;
  35689. #if SQLITE_MAX_MMAP_SIZE>0
  35690. if( pFd->mmapSizeMax>0 ){
  35691. if( pFd->pMapRegion==0 ){
  35692. int rc = unixMapfile(pFd, -1);
  35693. if( rc!=SQLITE_OK ) return rc;
  35694. }
  35695. if( pFd->mmapSize >= iOff+nAmt ){
  35696. *pp = &((u8 *)pFd->pMapRegion)[iOff];
  35697. pFd->nFetchOut++;
  35698. }
  35699. }
  35700. #endif
  35701. return SQLITE_OK;
  35702. }
  35703. /*
  35704. ** If the third argument is non-NULL, then this function releases a
  35705. ** reference obtained by an earlier call to unixFetch(). The second
  35706. ** argument passed to this function must be the same as the corresponding
  35707. ** argument that was passed to the unixFetch() invocation.
  35708. **
  35709. ** Or, if the third argument is NULL, then this function is being called
  35710. ** to inform the VFS layer that, according to POSIX, any existing mapping
  35711. ** may now be invalid and should be unmapped.
  35712. */
  35713. static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
  35714. #if SQLITE_MAX_MMAP_SIZE>0
  35715. unixFile *pFd = (unixFile *)fd; /* The underlying database file */
  35716. UNUSED_PARAMETER(iOff);
  35717. /* If p==0 (unmap the entire file) then there must be no outstanding
  35718. ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
  35719. ** then there must be at least one outstanding. */
  35720. assert( (p==0)==(pFd->nFetchOut==0) );
  35721. /* If p!=0, it must match the iOff value. */
  35722. assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
  35723. if( p ){
  35724. pFd->nFetchOut--;
  35725. }else{
  35726. unixUnmapfile(pFd);
  35727. }
  35728. assert( pFd->nFetchOut>=0 );
  35729. #else
  35730. UNUSED_PARAMETER(fd);
  35731. UNUSED_PARAMETER(p);
  35732. UNUSED_PARAMETER(iOff);
  35733. #endif
  35734. return SQLITE_OK;
  35735. }
  35736. /*
  35737. ** Here ends the implementation of all sqlite3_file methods.
  35738. **
  35739. ********************** End sqlite3_file Methods *******************************
  35740. ******************************************************************************/
  35741. /*
  35742. ** This division contains definitions of sqlite3_io_methods objects that
  35743. ** implement various file locking strategies. It also contains definitions
  35744. ** of "finder" functions. A finder-function is used to locate the appropriate
  35745. ** sqlite3_io_methods object for a particular database file. The pAppData
  35746. ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
  35747. ** the correct finder-function for that VFS.
  35748. **
  35749. ** Most finder functions return a pointer to a fixed sqlite3_io_methods
  35750. ** object. The only interesting finder-function is autolockIoFinder, which
  35751. ** looks at the filesystem type and tries to guess the best locking
  35752. ** strategy from that.
  35753. **
  35754. ** For finder-function F, two objects are created:
  35755. **
  35756. ** (1) The real finder-function named "FImpt()".
  35757. **
  35758. ** (2) A constant pointer to this function named just "F".
  35759. **
  35760. **
  35761. ** A pointer to the F pointer is used as the pAppData value for VFS
  35762. ** objects. We have to do this instead of letting pAppData point
  35763. ** directly at the finder-function since C90 rules prevent a void*
  35764. ** from be cast into a function pointer.
  35765. **
  35766. **
  35767. ** Each instance of this macro generates two objects:
  35768. **
  35769. ** * A constant sqlite3_io_methods object call METHOD that has locking
  35770. ** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
  35771. **
  35772. ** * An I/O method finder function called FINDER that returns a pointer
  35773. ** to the METHOD object in the previous bullet.
  35774. */
  35775. #define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
  35776. static const sqlite3_io_methods METHOD = { \
  35777. VERSION, /* iVersion */ \
  35778. CLOSE, /* xClose */ \
  35779. unixRead, /* xRead */ \
  35780. unixWrite, /* xWrite */ \
  35781. unixTruncate, /* xTruncate */ \
  35782. unixSync, /* xSync */ \
  35783. unixFileSize, /* xFileSize */ \
  35784. LOCK, /* xLock */ \
  35785. UNLOCK, /* xUnlock */ \
  35786. CKLOCK, /* xCheckReservedLock */ \
  35787. unixFileControl, /* xFileControl */ \
  35788. unixSectorSize, /* xSectorSize */ \
  35789. unixDeviceCharacteristics, /* xDeviceCapabilities */ \
  35790. SHMMAP, /* xShmMap */ \
  35791. unixShmLock, /* xShmLock */ \
  35792. unixShmBarrier, /* xShmBarrier */ \
  35793. unixShmUnmap, /* xShmUnmap */ \
  35794. unixFetch, /* xFetch */ \
  35795. unixUnfetch, /* xUnfetch */ \
  35796. }; \
  35797. static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
  35798. UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
  35799. return &METHOD; \
  35800. } \
  35801. static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
  35802. = FINDER##Impl;
  35803. /*
  35804. ** Here are all of the sqlite3_io_methods objects for each of the
  35805. ** locking strategies. Functions that return pointers to these methods
  35806. ** are also created.
  35807. */
  35808. IOMETHODS(
  35809. posixIoFinder, /* Finder function name */
  35810. posixIoMethods, /* sqlite3_io_methods object name */
  35811. 3, /* shared memory and mmap are enabled */
  35812. unixClose, /* xClose method */
  35813. unixLock, /* xLock method */
  35814. unixUnlock, /* xUnlock method */
  35815. unixCheckReservedLock, /* xCheckReservedLock method */
  35816. unixShmMap /* xShmMap method */
  35817. )
  35818. IOMETHODS(
  35819. nolockIoFinder, /* Finder function name */
  35820. nolockIoMethods, /* sqlite3_io_methods object name */
  35821. 3, /* shared memory and mmap are enabled */
  35822. nolockClose, /* xClose method */
  35823. nolockLock, /* xLock method */
  35824. nolockUnlock, /* xUnlock method */
  35825. nolockCheckReservedLock, /* xCheckReservedLock method */
  35826. 0 /* xShmMap method */
  35827. )
  35828. IOMETHODS(
  35829. dotlockIoFinder, /* Finder function name */
  35830. dotlockIoMethods, /* sqlite3_io_methods object name */
  35831. 1, /* shared memory is disabled */
  35832. dotlockClose, /* xClose method */
  35833. dotlockLock, /* xLock method */
  35834. dotlockUnlock, /* xUnlock method */
  35835. dotlockCheckReservedLock, /* xCheckReservedLock method */
  35836. 0 /* xShmMap method */
  35837. )
  35838. #if SQLITE_ENABLE_LOCKING_STYLE
  35839. IOMETHODS(
  35840. flockIoFinder, /* Finder function name */
  35841. flockIoMethods, /* sqlite3_io_methods object name */
  35842. 1, /* shared memory is disabled */
  35843. flockClose, /* xClose method */
  35844. flockLock, /* xLock method */
  35845. flockUnlock, /* xUnlock method */
  35846. flockCheckReservedLock, /* xCheckReservedLock method */
  35847. 0 /* xShmMap method */
  35848. )
  35849. #endif
  35850. #if OS_VXWORKS
  35851. IOMETHODS(
  35852. semIoFinder, /* Finder function name */
  35853. semIoMethods, /* sqlite3_io_methods object name */
  35854. 1, /* shared memory is disabled */
  35855. semXClose, /* xClose method */
  35856. semXLock, /* xLock method */
  35857. semXUnlock, /* xUnlock method */
  35858. semXCheckReservedLock, /* xCheckReservedLock method */
  35859. 0 /* xShmMap method */
  35860. )
  35861. #endif
  35862. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  35863. IOMETHODS(
  35864. afpIoFinder, /* Finder function name */
  35865. afpIoMethods, /* sqlite3_io_methods object name */
  35866. 1, /* shared memory is disabled */
  35867. afpClose, /* xClose method */
  35868. afpLock, /* xLock method */
  35869. afpUnlock, /* xUnlock method */
  35870. afpCheckReservedLock, /* xCheckReservedLock method */
  35871. 0 /* xShmMap method */
  35872. )
  35873. #endif
  35874. /*
  35875. ** The proxy locking method is a "super-method" in the sense that it
  35876. ** opens secondary file descriptors for the conch and lock files and
  35877. ** it uses proxy, dot-file, AFP, and flock() locking methods on those
  35878. ** secondary files. For this reason, the division that implements
  35879. ** proxy locking is located much further down in the file. But we need
  35880. ** to go ahead and define the sqlite3_io_methods and finder function
  35881. ** for proxy locking here. So we forward declare the I/O methods.
  35882. */
  35883. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  35884. static int proxyClose(sqlite3_file*);
  35885. static int proxyLock(sqlite3_file*, int);
  35886. static int proxyUnlock(sqlite3_file*, int);
  35887. static int proxyCheckReservedLock(sqlite3_file*, int*);
  35888. IOMETHODS(
  35889. proxyIoFinder, /* Finder function name */
  35890. proxyIoMethods, /* sqlite3_io_methods object name */
  35891. 1, /* shared memory is disabled */
  35892. proxyClose, /* xClose method */
  35893. proxyLock, /* xLock method */
  35894. proxyUnlock, /* xUnlock method */
  35895. proxyCheckReservedLock, /* xCheckReservedLock method */
  35896. 0 /* xShmMap method */
  35897. )
  35898. #endif
  35899. /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
  35900. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  35901. IOMETHODS(
  35902. nfsIoFinder, /* Finder function name */
  35903. nfsIoMethods, /* sqlite3_io_methods object name */
  35904. 1, /* shared memory is disabled */
  35905. unixClose, /* xClose method */
  35906. unixLock, /* xLock method */
  35907. nfsUnlock, /* xUnlock method */
  35908. unixCheckReservedLock, /* xCheckReservedLock method */
  35909. 0 /* xShmMap method */
  35910. )
  35911. #endif
  35912. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  35913. /*
  35914. ** This "finder" function attempts to determine the best locking strategy
  35915. ** for the database file "filePath". It then returns the sqlite3_io_methods
  35916. ** object that implements that strategy.
  35917. **
  35918. ** This is for MacOSX only.
  35919. */
  35920. static const sqlite3_io_methods *autolockIoFinderImpl(
  35921. const char *filePath, /* name of the database file */
  35922. unixFile *pNew /* open file object for the database file */
  35923. ){
  35924. static const struct Mapping {
  35925. const char *zFilesystem; /* Filesystem type name */
  35926. const sqlite3_io_methods *pMethods; /* Appropriate locking method */
  35927. } aMap[] = {
  35928. { "hfs", &posixIoMethods },
  35929. { "ufs", &posixIoMethods },
  35930. { "afpfs", &afpIoMethods },
  35931. { "smbfs", &afpIoMethods },
  35932. { "webdav", &nolockIoMethods },
  35933. { 0, 0 }
  35934. };
  35935. int i;
  35936. struct statfs fsInfo;
  35937. struct flock lockInfo;
  35938. if( !filePath ){
  35939. /* If filePath==NULL that means we are dealing with a transient file
  35940. ** that does not need to be locked. */
  35941. return &nolockIoMethods;
  35942. }
  35943. if( statfs(filePath, &fsInfo) != -1 ){
  35944. if( fsInfo.f_flags & MNT_RDONLY ){
  35945. return &nolockIoMethods;
  35946. }
  35947. for(i=0; aMap[i].zFilesystem; i++){
  35948. if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
  35949. return aMap[i].pMethods;
  35950. }
  35951. }
  35952. }
  35953. /* Default case. Handles, amongst others, "nfs".
  35954. ** Test byte-range lock using fcntl(). If the call succeeds,
  35955. ** assume that the file-system supports POSIX style locks.
  35956. */
  35957. lockInfo.l_len = 1;
  35958. lockInfo.l_start = 0;
  35959. lockInfo.l_whence = SEEK_SET;
  35960. lockInfo.l_type = F_RDLCK;
  35961. if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
  35962. if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
  35963. return &nfsIoMethods;
  35964. } else {
  35965. return &posixIoMethods;
  35966. }
  35967. }else{
  35968. return &dotlockIoMethods;
  35969. }
  35970. }
  35971. static const sqlite3_io_methods
  35972. *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
  35973. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  35974. #if OS_VXWORKS
  35975. /*
  35976. ** This "finder" function for VxWorks checks to see if posix advisory
  35977. ** locking works. If it does, then that is what is used. If it does not
  35978. ** work, then fallback to named semaphore locking.
  35979. */
  35980. static const sqlite3_io_methods *vxworksIoFinderImpl(
  35981. const char *filePath, /* name of the database file */
  35982. unixFile *pNew /* the open file object */
  35983. ){
  35984. struct flock lockInfo;
  35985. if( !filePath ){
  35986. /* If filePath==NULL that means we are dealing with a transient file
  35987. ** that does not need to be locked. */
  35988. return &nolockIoMethods;
  35989. }
  35990. /* Test if fcntl() is supported and use POSIX style locks.
  35991. ** Otherwise fall back to the named semaphore method.
  35992. */
  35993. lockInfo.l_len = 1;
  35994. lockInfo.l_start = 0;
  35995. lockInfo.l_whence = SEEK_SET;
  35996. lockInfo.l_type = F_RDLCK;
  35997. if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
  35998. return &posixIoMethods;
  35999. }else{
  36000. return &semIoMethods;
  36001. }
  36002. }
  36003. static const sqlite3_io_methods
  36004. *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
  36005. #endif /* OS_VXWORKS */
  36006. /*
  36007. ** An abstract type for a pointer to an IO method finder function:
  36008. */
  36009. typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
  36010. /****************************************************************************
  36011. **************************** sqlite3_vfs methods ****************************
  36012. **
  36013. ** This division contains the implementation of methods on the
  36014. ** sqlite3_vfs object.
  36015. */
  36016. /*
  36017. ** Initialize the contents of the unixFile structure pointed to by pId.
  36018. */
  36019. static int fillInUnixFile(
  36020. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  36021. int h, /* Open file descriptor of file being opened */
  36022. sqlite3_file *pId, /* Write to the unixFile structure here */
  36023. const char *zFilename, /* Name of the file being opened */
  36024. int ctrlFlags /* Zero or more UNIXFILE_* values */
  36025. ){
  36026. const sqlite3_io_methods *pLockingStyle;
  36027. unixFile *pNew = (unixFile *)pId;
  36028. int rc = SQLITE_OK;
  36029. assert( pNew->pInode==NULL );
  36030. /* No locking occurs in temporary files */
  36031. assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
  36032. OSTRACE(("OPEN %-3d %s\n", h, zFilename));
  36033. pNew->h = h;
  36034. pNew->pVfs = pVfs;
  36035. pNew->zPath = zFilename;
  36036. pNew->ctrlFlags = (u8)ctrlFlags;
  36037. #if SQLITE_MAX_MMAP_SIZE>0
  36038. pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
  36039. #endif
  36040. if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
  36041. "psow", SQLITE_POWERSAFE_OVERWRITE) ){
  36042. pNew->ctrlFlags |= UNIXFILE_PSOW;
  36043. }
  36044. if( strcmp(pVfs->zName,"unix-excl")==0 ){
  36045. pNew->ctrlFlags |= UNIXFILE_EXCL;
  36046. }
  36047. #if OS_VXWORKS
  36048. pNew->pId = vxworksFindFileId(zFilename);
  36049. if( pNew->pId==0 ){
  36050. ctrlFlags |= UNIXFILE_NOLOCK;
  36051. rc = SQLITE_NOMEM_BKPT;
  36052. }
  36053. #endif
  36054. if( ctrlFlags & UNIXFILE_NOLOCK ){
  36055. pLockingStyle = &nolockIoMethods;
  36056. }else{
  36057. pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
  36058. #if SQLITE_ENABLE_LOCKING_STYLE
  36059. /* Cache zFilename in the locking context (AFP and dotlock override) for
  36060. ** proxyLock activation is possible (remote proxy is based on db name)
  36061. ** zFilename remains valid until file is closed, to support */
  36062. pNew->lockingContext = (void*)zFilename;
  36063. #endif
  36064. }
  36065. if( pLockingStyle == &posixIoMethods
  36066. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  36067. || pLockingStyle == &nfsIoMethods
  36068. #endif
  36069. ){
  36070. unixEnterMutex();
  36071. rc = findInodeInfo(pNew, &pNew->pInode);
  36072. if( rc!=SQLITE_OK ){
  36073. /* If an error occurred in findInodeInfo(), close the file descriptor
  36074. ** immediately, before releasing the mutex. findInodeInfo() may fail
  36075. ** in two scenarios:
  36076. **
  36077. ** (a) A call to fstat() failed.
  36078. ** (b) A malloc failed.
  36079. **
  36080. ** Scenario (b) may only occur if the process is holding no other
  36081. ** file descriptors open on the same file. If there were other file
  36082. ** descriptors on this file, then no malloc would be required by
  36083. ** findInodeInfo(). If this is the case, it is quite safe to close
  36084. ** handle h - as it is guaranteed that no posix locks will be released
  36085. ** by doing so.
  36086. **
  36087. ** If scenario (a) caused the error then things are not so safe. The
  36088. ** implicit assumption here is that if fstat() fails, things are in
  36089. ** such bad shape that dropping a lock or two doesn't matter much.
  36090. */
  36091. robust_close(pNew, h, __LINE__);
  36092. h = -1;
  36093. }
  36094. unixLeaveMutex();
  36095. }
  36096. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  36097. else if( pLockingStyle == &afpIoMethods ){
  36098. /* AFP locking uses the file path so it needs to be included in
  36099. ** the afpLockingContext.
  36100. */
  36101. afpLockingContext *pCtx;
  36102. pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
  36103. if( pCtx==0 ){
  36104. rc = SQLITE_NOMEM_BKPT;
  36105. }else{
  36106. /* NB: zFilename exists and remains valid until the file is closed
  36107. ** according to requirement F11141. So we do not need to make a
  36108. ** copy of the filename. */
  36109. pCtx->dbPath = zFilename;
  36110. pCtx->reserved = 0;
  36111. srandomdev();
  36112. unixEnterMutex();
  36113. rc = findInodeInfo(pNew, &pNew->pInode);
  36114. if( rc!=SQLITE_OK ){
  36115. sqlite3_free(pNew->lockingContext);
  36116. robust_close(pNew, h, __LINE__);
  36117. h = -1;
  36118. }
  36119. unixLeaveMutex();
  36120. }
  36121. }
  36122. #endif
  36123. else if( pLockingStyle == &dotlockIoMethods ){
  36124. /* Dotfile locking uses the file path so it needs to be included in
  36125. ** the dotlockLockingContext
  36126. */
  36127. char *zLockFile;
  36128. int nFilename;
  36129. assert( zFilename!=0 );
  36130. nFilename = (int)strlen(zFilename) + 6;
  36131. zLockFile = (char *)sqlite3_malloc64(nFilename);
  36132. if( zLockFile==0 ){
  36133. rc = SQLITE_NOMEM_BKPT;
  36134. }else{
  36135. sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
  36136. }
  36137. pNew->lockingContext = zLockFile;
  36138. }
  36139. #if OS_VXWORKS
  36140. else if( pLockingStyle == &semIoMethods ){
  36141. /* Named semaphore locking uses the file path so it needs to be
  36142. ** included in the semLockingContext
  36143. */
  36144. unixEnterMutex();
  36145. rc = findInodeInfo(pNew, &pNew->pInode);
  36146. if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
  36147. char *zSemName = pNew->pInode->aSemName;
  36148. int n;
  36149. sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
  36150. pNew->pId->zCanonicalName);
  36151. for( n=1; zSemName[n]; n++ )
  36152. if( zSemName[n]=='/' ) zSemName[n] = '_';
  36153. pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
  36154. if( pNew->pInode->pSem == SEM_FAILED ){
  36155. rc = SQLITE_NOMEM_BKPT;
  36156. pNew->pInode->aSemName[0] = '\0';
  36157. }
  36158. }
  36159. unixLeaveMutex();
  36160. }
  36161. #endif
  36162. storeLastErrno(pNew, 0);
  36163. #if OS_VXWORKS
  36164. if( rc!=SQLITE_OK ){
  36165. if( h>=0 ) robust_close(pNew, h, __LINE__);
  36166. h = -1;
  36167. osUnlink(zFilename);
  36168. pNew->ctrlFlags |= UNIXFILE_DELETE;
  36169. }
  36170. #endif
  36171. if( rc!=SQLITE_OK ){
  36172. if( h>=0 ) robust_close(pNew, h, __LINE__);
  36173. }else{
  36174. pNew->pMethod = pLockingStyle;
  36175. OpenCounter(+1);
  36176. verifyDbFile(pNew);
  36177. }
  36178. return rc;
  36179. }
  36180. /*
  36181. ** Return the name of a directory in which to put temporary files.
  36182. ** If no suitable temporary file directory can be found, return NULL.
  36183. */
  36184. static const char *unixTempFileDir(void){
  36185. static const char *azDirs[] = {
  36186. 0,
  36187. 0,
  36188. "/var/tmp",
  36189. "/usr/tmp",
  36190. "/tmp",
  36191. "."
  36192. };
  36193. unsigned int i = 0;
  36194. struct stat buf;
  36195. const char *zDir = sqlite3_temp_directory;
  36196. if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
  36197. if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
  36198. while(1){
  36199. if( zDir!=0
  36200. && osStat(zDir, &buf)==0
  36201. && S_ISDIR(buf.st_mode)
  36202. && osAccess(zDir, 03)==0
  36203. ){
  36204. return zDir;
  36205. }
  36206. if( i>=sizeof(azDirs)/sizeof(azDirs[0]) ) break;
  36207. zDir = azDirs[i++];
  36208. }
  36209. return 0;
  36210. }
  36211. /*
  36212. ** Create a temporary file name in zBuf. zBuf must be allocated
  36213. ** by the calling process and must be big enough to hold at least
  36214. ** pVfs->mxPathname bytes.
  36215. */
  36216. static int unixGetTempname(int nBuf, char *zBuf){
  36217. const char *zDir;
  36218. int iLimit = 0;
  36219. /* It's odd to simulate an io-error here, but really this is just
  36220. ** using the io-error infrastructure to test that SQLite handles this
  36221. ** function failing.
  36222. */
  36223. zBuf[0] = 0;
  36224. SimulateIOError( return SQLITE_IOERR );
  36225. zDir = unixTempFileDir();
  36226. if( zDir==0 ) return SQLITE_IOERR_GETTEMPPATH;
  36227. do{
  36228. u64 r;
  36229. sqlite3_randomness(sizeof(r), &r);
  36230. assert( nBuf>2 );
  36231. zBuf[nBuf-2] = 0;
  36232. sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c",
  36233. zDir, r, 0);
  36234. if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ) return SQLITE_ERROR;
  36235. }while( osAccess(zBuf,0)==0 );
  36236. return SQLITE_OK;
  36237. }
  36238. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  36239. /*
  36240. ** Routine to transform a unixFile into a proxy-locking unixFile.
  36241. ** Implementation in the proxy-lock division, but used by unixOpen()
  36242. ** if SQLITE_PREFER_PROXY_LOCKING is defined.
  36243. */
  36244. static int proxyTransformUnixFile(unixFile*, const char*);
  36245. #endif
  36246. /*
  36247. ** Search for an unused file descriptor that was opened on the database
  36248. ** file (not a journal or master-journal file) identified by pathname
  36249. ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
  36250. ** argument to this function.
  36251. **
  36252. ** Such a file descriptor may exist if a database connection was closed
  36253. ** but the associated file descriptor could not be closed because some
  36254. ** other file descriptor open on the same file is holding a file-lock.
  36255. ** Refer to comments in the unixClose() function and the lengthy comment
  36256. ** describing "Posix Advisory Locking" at the start of this file for
  36257. ** further details. Also, ticket #4018.
  36258. **
  36259. ** If a suitable file descriptor is found, then it is returned. If no
  36260. ** such file descriptor is located, -1 is returned.
  36261. */
  36262. static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
  36263. UnixUnusedFd *pUnused = 0;
  36264. /* Do not search for an unused file descriptor on vxworks. Not because
  36265. ** vxworks would not benefit from the change (it might, we're not sure),
  36266. ** but because no way to test it is currently available. It is better
  36267. ** not to risk breaking vxworks support for the sake of such an obscure
  36268. ** feature. */
  36269. #if !OS_VXWORKS
  36270. struct stat sStat; /* Results of stat() call */
  36271. unixEnterMutex();
  36272. /* A stat() call may fail for various reasons. If this happens, it is
  36273. ** almost certain that an open() call on the same path will also fail.
  36274. ** For this reason, if an error occurs in the stat() call here, it is
  36275. ** ignored and -1 is returned. The caller will try to open a new file
  36276. ** descriptor on the same path, fail, and return an error to SQLite.
  36277. **
  36278. ** Even if a subsequent open() call does succeed, the consequences of
  36279. ** not searching for a reusable file descriptor are not dire. */
  36280. if( inodeList!=0 && 0==osStat(zPath, &sStat) ){
  36281. unixInodeInfo *pInode;
  36282. pInode = inodeList;
  36283. while( pInode && (pInode->fileId.dev!=sStat.st_dev
  36284. || pInode->fileId.ino!=(u64)sStat.st_ino) ){
  36285. pInode = pInode->pNext;
  36286. }
  36287. if( pInode ){
  36288. UnixUnusedFd **pp;
  36289. assert( sqlite3_mutex_notheld(pInode->pLockMutex) );
  36290. sqlite3_mutex_enter(pInode->pLockMutex);
  36291. for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
  36292. pUnused = *pp;
  36293. if( pUnused ){
  36294. *pp = pUnused->pNext;
  36295. }
  36296. sqlite3_mutex_leave(pInode->pLockMutex);
  36297. }
  36298. }
  36299. unixLeaveMutex();
  36300. #endif /* if !OS_VXWORKS */
  36301. return pUnused;
  36302. }
  36303. /*
  36304. ** Find the mode, uid and gid of file zFile.
  36305. */
  36306. static int getFileMode(
  36307. const char *zFile, /* File name */
  36308. mode_t *pMode, /* OUT: Permissions of zFile */
  36309. uid_t *pUid, /* OUT: uid of zFile. */
  36310. gid_t *pGid /* OUT: gid of zFile. */
  36311. ){
  36312. struct stat sStat; /* Output of stat() on database file */
  36313. int rc = SQLITE_OK;
  36314. if( 0==osStat(zFile, &sStat) ){
  36315. *pMode = sStat.st_mode & 0777;
  36316. *pUid = sStat.st_uid;
  36317. *pGid = sStat.st_gid;
  36318. }else{
  36319. rc = SQLITE_IOERR_FSTAT;
  36320. }
  36321. return rc;
  36322. }
  36323. /*
  36324. ** This function is called by unixOpen() to determine the unix permissions
  36325. ** to create new files with. If no error occurs, then SQLITE_OK is returned
  36326. ** and a value suitable for passing as the third argument to open(2) is
  36327. ** written to *pMode. If an IO error occurs, an SQLite error code is
  36328. ** returned and the value of *pMode is not modified.
  36329. **
  36330. ** In most cases, this routine sets *pMode to 0, which will become
  36331. ** an indication to robust_open() to create the file using
  36332. ** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
  36333. ** But if the file being opened is a WAL or regular journal file, then
  36334. ** this function queries the file-system for the permissions on the
  36335. ** corresponding database file and sets *pMode to this value. Whenever
  36336. ** possible, WAL and journal files are created using the same permissions
  36337. ** as the associated database file.
  36338. **
  36339. ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
  36340. ** original filename is unavailable. But 8_3_NAMES is only used for
  36341. ** FAT filesystems and permissions do not matter there, so just use
  36342. ** the default permissions.
  36343. */
  36344. static int findCreateFileMode(
  36345. const char *zPath, /* Path of file (possibly) being created */
  36346. int flags, /* Flags passed as 4th argument to xOpen() */
  36347. mode_t *pMode, /* OUT: Permissions to open file with */
  36348. uid_t *pUid, /* OUT: uid to set on the file */
  36349. gid_t *pGid /* OUT: gid to set on the file */
  36350. ){
  36351. int rc = SQLITE_OK; /* Return Code */
  36352. *pMode = 0;
  36353. *pUid = 0;
  36354. *pGid = 0;
  36355. if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
  36356. char zDb[MAX_PATHNAME+1]; /* Database file path */
  36357. int nDb; /* Number of valid bytes in zDb */
  36358. /* zPath is a path to a WAL or journal file. The following block derives
  36359. ** the path to the associated database file from zPath. This block handles
  36360. ** the following naming conventions:
  36361. **
  36362. ** "<path to db>-journal"
  36363. ** "<path to db>-wal"
  36364. ** "<path to db>-journalNN"
  36365. ** "<path to db>-walNN"
  36366. **
  36367. ** where NN is a decimal number. The NN naming schemes are
  36368. ** used by the test_multiplex.c module.
  36369. */
  36370. nDb = sqlite3Strlen30(zPath) - 1;
  36371. while( zPath[nDb]!='-' ){
  36372. /* In normal operation, the journal file name will always contain
  36373. ** a '-' character. However in 8+3 filename mode, or if a corrupt
  36374. ** rollback journal specifies a master journal with a goofy name, then
  36375. ** the '-' might be missing. */
  36376. if( nDb==0 || zPath[nDb]=='.' ) return SQLITE_OK;
  36377. nDb--;
  36378. }
  36379. memcpy(zDb, zPath, nDb);
  36380. zDb[nDb] = '\0';
  36381. rc = getFileMode(zDb, pMode, pUid, pGid);
  36382. }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
  36383. *pMode = 0600;
  36384. }else if( flags & SQLITE_OPEN_URI ){
  36385. /* If this is a main database file and the file was opened using a URI
  36386. ** filename, check for the "modeof" parameter. If present, interpret
  36387. ** its value as a filename and try to copy the mode, uid and gid from
  36388. ** that file. */
  36389. const char *z = sqlite3_uri_parameter(zPath, "modeof");
  36390. if( z ){
  36391. rc = getFileMode(z, pMode, pUid, pGid);
  36392. }
  36393. }
  36394. return rc;
  36395. }
  36396. /*
  36397. ** Open the file zPath.
  36398. **
  36399. ** Previously, the SQLite OS layer used three functions in place of this
  36400. ** one:
  36401. **
  36402. ** sqlite3OsOpenReadWrite();
  36403. ** sqlite3OsOpenReadOnly();
  36404. ** sqlite3OsOpenExclusive();
  36405. **
  36406. ** These calls correspond to the following combinations of flags:
  36407. **
  36408. ** ReadWrite() -> (READWRITE | CREATE)
  36409. ** ReadOnly() -> (READONLY)
  36410. ** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
  36411. **
  36412. ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
  36413. ** true, the file was configured to be automatically deleted when the
  36414. ** file handle closed. To achieve the same effect using this new
  36415. ** interface, add the DELETEONCLOSE flag to those specified above for
  36416. ** OpenExclusive().
  36417. */
  36418. static int unixOpen(
  36419. sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
  36420. const char *zPath, /* Pathname of file to be opened */
  36421. sqlite3_file *pFile, /* The file descriptor to be filled in */
  36422. int flags, /* Input flags to control the opening */
  36423. int *pOutFlags /* Output flags returned to SQLite core */
  36424. ){
  36425. unixFile *p = (unixFile *)pFile;
  36426. int fd = -1; /* File descriptor returned by open() */
  36427. int openFlags = 0; /* Flags to pass to open() */
  36428. int eType = flags&0xFFFFFF00; /* Type of file to open */
  36429. int noLock; /* True to omit locking primitives */
  36430. int rc = SQLITE_OK; /* Function Return Code */
  36431. int ctrlFlags = 0; /* UNIXFILE_* flags */
  36432. int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
  36433. int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
  36434. int isCreate = (flags & SQLITE_OPEN_CREATE);
  36435. int isReadonly = (flags & SQLITE_OPEN_READONLY);
  36436. int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
  36437. #if SQLITE_ENABLE_LOCKING_STYLE
  36438. int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
  36439. #endif
  36440. #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
  36441. struct statfs fsInfo;
  36442. #endif
  36443. /* If creating a master or main-file journal, this function will open
  36444. ** a file-descriptor on the directory too. The first time unixSync()
  36445. ** is called the directory file descriptor will be fsync()ed and close()d.
  36446. */
  36447. int isNewJrnl = (isCreate && (
  36448. eType==SQLITE_OPEN_MASTER_JOURNAL
  36449. || eType==SQLITE_OPEN_MAIN_JOURNAL
  36450. || eType==SQLITE_OPEN_WAL
  36451. ));
  36452. /* If argument zPath is a NULL pointer, this function is required to open
  36453. ** a temporary file. Use this buffer to store the file name in.
  36454. */
  36455. char zTmpname[MAX_PATHNAME+2];
  36456. const char *zName = zPath;
  36457. /* Check the following statements are true:
  36458. **
  36459. ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
  36460. ** (b) if CREATE is set, then READWRITE must also be set, and
  36461. ** (c) if EXCLUSIVE is set, then CREATE must also be set.
  36462. ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
  36463. */
  36464. assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
  36465. assert(isCreate==0 || isReadWrite);
  36466. assert(isExclusive==0 || isCreate);
  36467. assert(isDelete==0 || isCreate);
  36468. /* The main DB, main journal, WAL file and master journal are never
  36469. ** automatically deleted. Nor are they ever temporary files. */
  36470. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
  36471. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
  36472. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
  36473. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
  36474. /* Assert that the upper layer has set one of the "file-type" flags. */
  36475. assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
  36476. || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
  36477. || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
  36478. || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
  36479. );
  36480. /* Detect a pid change and reset the PRNG. There is a race condition
  36481. ** here such that two or more threads all trying to open databases at
  36482. ** the same instant might all reset the PRNG. But multiple resets
  36483. ** are harmless.
  36484. */
  36485. if( randomnessPid!=osGetpid(0) ){
  36486. randomnessPid = osGetpid(0);
  36487. sqlite3_randomness(0,0);
  36488. }
  36489. memset(p, 0, sizeof(unixFile));
  36490. if( eType==SQLITE_OPEN_MAIN_DB ){
  36491. UnixUnusedFd *pUnused;
  36492. pUnused = findReusableFd(zName, flags);
  36493. if( pUnused ){
  36494. fd = pUnused->fd;
  36495. }else{
  36496. pUnused = sqlite3_malloc64(sizeof(*pUnused));
  36497. if( !pUnused ){
  36498. return SQLITE_NOMEM_BKPT;
  36499. }
  36500. }
  36501. p->pPreallocatedUnused = pUnused;
  36502. /* Database filenames are double-zero terminated if they are not
  36503. ** URIs with parameters. Hence, they can always be passed into
  36504. ** sqlite3_uri_parameter(). */
  36505. assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
  36506. }else if( !zName ){
  36507. /* If zName is NULL, the upper layer is requesting a temp file. */
  36508. assert(isDelete && !isNewJrnl);
  36509. rc = unixGetTempname(pVfs->mxPathname, zTmpname);
  36510. if( rc!=SQLITE_OK ){
  36511. return rc;
  36512. }
  36513. zName = zTmpname;
  36514. /* Generated temporary filenames are always double-zero terminated
  36515. ** for use by sqlite3_uri_parameter(). */
  36516. assert( zName[strlen(zName)+1]==0 );
  36517. }
  36518. /* Determine the value of the flags parameter passed to POSIX function
  36519. ** open(). These must be calculated even if open() is not called, as
  36520. ** they may be stored as part of the file handle and used by the
  36521. ** 'conch file' locking functions later on. */
  36522. if( isReadonly ) openFlags |= O_RDONLY;
  36523. if( isReadWrite ) openFlags |= O_RDWR;
  36524. if( isCreate ) openFlags |= O_CREAT;
  36525. if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
  36526. openFlags |= (O_LARGEFILE|O_BINARY);
  36527. if( fd<0 ){
  36528. mode_t openMode; /* Permissions to create file with */
  36529. uid_t uid; /* Userid for the file */
  36530. gid_t gid; /* Groupid for the file */
  36531. rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
  36532. if( rc!=SQLITE_OK ){
  36533. assert( !p->pPreallocatedUnused );
  36534. assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
  36535. return rc;
  36536. }
  36537. fd = robust_open(zName, openFlags, openMode);
  36538. OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
  36539. assert( !isExclusive || (openFlags & O_CREAT)!=0 );
  36540. if( fd<0 ){
  36541. if( isNewJrnl && errno==EACCES && osAccess(zName, F_OK) ){
  36542. /* If unable to create a journal because the directory is not
  36543. ** writable, change the error code to indicate that. */
  36544. rc = SQLITE_READONLY_DIRECTORY;
  36545. }else if( errno!=EISDIR && isReadWrite ){
  36546. /* Failed to open the file for read/write access. Try read-only. */
  36547. flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
  36548. openFlags &= ~(O_RDWR|O_CREAT);
  36549. flags |= SQLITE_OPEN_READONLY;
  36550. openFlags |= O_RDONLY;
  36551. isReadonly = 1;
  36552. fd = robust_open(zName, openFlags, openMode);
  36553. }
  36554. }
  36555. if( fd<0 ){
  36556. int rc2 = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
  36557. if( rc==SQLITE_OK ) rc = rc2;
  36558. goto open_finished;
  36559. }
  36560. /* If this process is running as root and if creating a new rollback
  36561. ** journal or WAL file, set the ownership of the journal or WAL to be
  36562. ** the same as the original database.
  36563. */
  36564. if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
  36565. robustFchown(fd, uid, gid);
  36566. }
  36567. }
  36568. assert( fd>=0 );
  36569. if( pOutFlags ){
  36570. *pOutFlags = flags;
  36571. }
  36572. if( p->pPreallocatedUnused ){
  36573. p->pPreallocatedUnused->fd = fd;
  36574. p->pPreallocatedUnused->flags = flags;
  36575. }
  36576. if( isDelete ){
  36577. #if OS_VXWORKS
  36578. zPath = zName;
  36579. #elif defined(SQLITE_UNLINK_AFTER_CLOSE)
  36580. zPath = sqlite3_mprintf("%s", zName);
  36581. if( zPath==0 ){
  36582. robust_close(p, fd, __LINE__);
  36583. return SQLITE_NOMEM_BKPT;
  36584. }
  36585. #else
  36586. osUnlink(zName);
  36587. #endif
  36588. }
  36589. #if SQLITE_ENABLE_LOCKING_STYLE
  36590. else{
  36591. p->openFlags = openFlags;
  36592. }
  36593. #endif
  36594. #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
  36595. if( fstatfs(fd, &fsInfo) == -1 ){
  36596. storeLastErrno(p, errno);
  36597. robust_close(p, fd, __LINE__);
  36598. return SQLITE_IOERR_ACCESS;
  36599. }
  36600. if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
  36601. ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
  36602. }
  36603. if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
  36604. ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
  36605. }
  36606. #endif
  36607. /* Set up appropriate ctrlFlags */
  36608. if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
  36609. if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
  36610. noLock = eType!=SQLITE_OPEN_MAIN_DB;
  36611. if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
  36612. if( isNewJrnl ) ctrlFlags |= UNIXFILE_DIRSYNC;
  36613. if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
  36614. #if SQLITE_ENABLE_LOCKING_STYLE
  36615. #if SQLITE_PREFER_PROXY_LOCKING
  36616. isAutoProxy = 1;
  36617. #endif
  36618. if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
  36619. char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
  36620. int useProxy = 0;
  36621. /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
  36622. ** never use proxy, NULL means use proxy for non-local files only. */
  36623. if( envforce!=NULL ){
  36624. useProxy = atoi(envforce)>0;
  36625. }else{
  36626. useProxy = !(fsInfo.f_flags&MNT_LOCAL);
  36627. }
  36628. if( useProxy ){
  36629. rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
  36630. if( rc==SQLITE_OK ){
  36631. rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
  36632. if( rc!=SQLITE_OK ){
  36633. /* Use unixClose to clean up the resources added in fillInUnixFile
  36634. ** and clear all the structure's references. Specifically,
  36635. ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
  36636. */
  36637. unixClose(pFile);
  36638. return rc;
  36639. }
  36640. }
  36641. goto open_finished;
  36642. }
  36643. }
  36644. #endif
  36645. assert( zPath==0 || zPath[0]=='/'
  36646. || eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL
  36647. );
  36648. rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
  36649. open_finished:
  36650. if( rc!=SQLITE_OK ){
  36651. sqlite3_free(p->pPreallocatedUnused);
  36652. }
  36653. return rc;
  36654. }
  36655. /*
  36656. ** Delete the file at zPath. If the dirSync argument is true, fsync()
  36657. ** the directory after deleting the file.
  36658. */
  36659. static int unixDelete(
  36660. sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
  36661. const char *zPath, /* Name of file to be deleted */
  36662. int dirSync /* If true, fsync() directory after deleting file */
  36663. ){
  36664. int rc = SQLITE_OK;
  36665. UNUSED_PARAMETER(NotUsed);
  36666. SimulateIOError(return SQLITE_IOERR_DELETE);
  36667. if( osUnlink(zPath)==(-1) ){
  36668. if( errno==ENOENT
  36669. #if OS_VXWORKS
  36670. || osAccess(zPath,0)!=0
  36671. #endif
  36672. ){
  36673. rc = SQLITE_IOERR_DELETE_NOENT;
  36674. }else{
  36675. rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
  36676. }
  36677. return rc;
  36678. }
  36679. #ifndef SQLITE_DISABLE_DIRSYNC
  36680. if( (dirSync & 1)!=0 ){
  36681. int fd;
  36682. rc = osOpenDirectory(zPath, &fd);
  36683. if( rc==SQLITE_OK ){
  36684. if( full_fsync(fd,0,0) ){
  36685. rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
  36686. }
  36687. robust_close(0, fd, __LINE__);
  36688. }else{
  36689. assert( rc==SQLITE_CANTOPEN );
  36690. rc = SQLITE_OK;
  36691. }
  36692. }
  36693. #endif
  36694. return rc;
  36695. }
  36696. /*
  36697. ** Test the existence of or access permissions of file zPath. The
  36698. ** test performed depends on the value of flags:
  36699. **
  36700. ** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
  36701. ** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
  36702. ** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
  36703. **
  36704. ** Otherwise return 0.
  36705. */
  36706. static int unixAccess(
  36707. sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
  36708. const char *zPath, /* Path of the file to examine */
  36709. int flags, /* What do we want to learn about the zPath file? */
  36710. int *pResOut /* Write result boolean here */
  36711. ){
  36712. UNUSED_PARAMETER(NotUsed);
  36713. SimulateIOError( return SQLITE_IOERR_ACCESS; );
  36714. assert( pResOut!=0 );
  36715. /* The spec says there are three possible values for flags. But only
  36716. ** two of them are actually used */
  36717. assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE );
  36718. if( flags==SQLITE_ACCESS_EXISTS ){
  36719. struct stat buf;
  36720. *pResOut = (0==osStat(zPath, &buf) && buf.st_size>0);
  36721. }else{
  36722. *pResOut = osAccess(zPath, W_OK|R_OK)==0;
  36723. }
  36724. return SQLITE_OK;
  36725. }
  36726. /*
  36727. **
  36728. */
  36729. static int mkFullPathname(
  36730. const char *zPath, /* Input path */
  36731. char *zOut, /* Output buffer */
  36732. int nOut /* Allocated size of buffer zOut */
  36733. ){
  36734. int nPath = sqlite3Strlen30(zPath);
  36735. int iOff = 0;
  36736. if( zPath[0]!='/' ){
  36737. if( osGetcwd(zOut, nOut-2)==0 ){
  36738. return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
  36739. }
  36740. iOff = sqlite3Strlen30(zOut);
  36741. zOut[iOff++] = '/';
  36742. }
  36743. if( (iOff+nPath+1)>nOut ){
  36744. /* SQLite assumes that xFullPathname() nul-terminates the output buffer
  36745. ** even if it returns an error. */
  36746. zOut[iOff] = '\0';
  36747. return SQLITE_CANTOPEN_BKPT;
  36748. }
  36749. sqlite3_snprintf(nOut-iOff, &zOut[iOff], "%s", zPath);
  36750. return SQLITE_OK;
  36751. }
  36752. /*
  36753. ** Turn a relative pathname into a full pathname. The relative path
  36754. ** is stored as a nul-terminated string in the buffer pointed to by
  36755. ** zPath.
  36756. **
  36757. ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
  36758. ** (in this case, MAX_PATHNAME bytes). The full-path is written to
  36759. ** this buffer before returning.
  36760. */
  36761. static int unixFullPathname(
  36762. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  36763. const char *zPath, /* Possibly relative input path */
  36764. int nOut, /* Size of output buffer in bytes */
  36765. char *zOut /* Output buffer */
  36766. ){
  36767. #if !defined(HAVE_READLINK) || !defined(HAVE_LSTAT)
  36768. return mkFullPathname(zPath, zOut, nOut);
  36769. #else
  36770. int rc = SQLITE_OK;
  36771. int nByte;
  36772. int nLink = 1; /* Number of symbolic links followed so far */
  36773. const char *zIn = zPath; /* Input path for each iteration of loop */
  36774. char *zDel = 0;
  36775. assert( pVfs->mxPathname==MAX_PATHNAME );
  36776. UNUSED_PARAMETER(pVfs);
  36777. /* It's odd to simulate an io-error here, but really this is just
  36778. ** using the io-error infrastructure to test that SQLite handles this
  36779. ** function failing. This function could fail if, for example, the
  36780. ** current working directory has been unlinked.
  36781. */
  36782. SimulateIOError( return SQLITE_ERROR );
  36783. do {
  36784. /* Call stat() on path zIn. Set bLink to true if the path is a symbolic
  36785. ** link, or false otherwise. */
  36786. int bLink = 0;
  36787. struct stat buf;
  36788. if( osLstat(zIn, &buf)!=0 ){
  36789. if( errno!=ENOENT ){
  36790. rc = unixLogError(SQLITE_CANTOPEN_BKPT, "lstat", zIn);
  36791. }
  36792. }else{
  36793. bLink = S_ISLNK(buf.st_mode);
  36794. }
  36795. if( bLink ){
  36796. if( zDel==0 ){
  36797. zDel = sqlite3_malloc(nOut);
  36798. if( zDel==0 ) rc = SQLITE_NOMEM_BKPT;
  36799. }else if( ++nLink>SQLITE_MAX_SYMLINKS ){
  36800. rc = SQLITE_CANTOPEN_BKPT;
  36801. }
  36802. if( rc==SQLITE_OK ){
  36803. nByte = osReadlink(zIn, zDel, nOut-1);
  36804. if( nByte<0 ){
  36805. rc = unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zIn);
  36806. }else{
  36807. if( zDel[0]!='/' ){
  36808. int n;
  36809. for(n = sqlite3Strlen30(zIn); n>0 && zIn[n-1]!='/'; n--);
  36810. if( nByte+n+1>nOut ){
  36811. rc = SQLITE_CANTOPEN_BKPT;
  36812. }else{
  36813. memmove(&zDel[n], zDel, nByte+1);
  36814. memcpy(zDel, zIn, n);
  36815. nByte += n;
  36816. }
  36817. }
  36818. zDel[nByte] = '\0';
  36819. }
  36820. }
  36821. zIn = zDel;
  36822. }
  36823. assert( rc!=SQLITE_OK || zIn!=zOut || zIn[0]=='/' );
  36824. if( rc==SQLITE_OK && zIn!=zOut ){
  36825. rc = mkFullPathname(zIn, zOut, nOut);
  36826. }
  36827. if( bLink==0 ) break;
  36828. zIn = zOut;
  36829. }while( rc==SQLITE_OK );
  36830. sqlite3_free(zDel);
  36831. return rc;
  36832. #endif /* HAVE_READLINK && HAVE_LSTAT */
  36833. }
  36834. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  36835. /*
  36836. ** Interfaces for opening a shared library, finding entry points
  36837. ** within the shared library, and closing the shared library.
  36838. */
  36839. #include <dlfcn.h>
  36840. static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
  36841. UNUSED_PARAMETER(NotUsed);
  36842. return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
  36843. }
  36844. /*
  36845. ** SQLite calls this function immediately after a call to unixDlSym() or
  36846. ** unixDlOpen() fails (returns a null pointer). If a more detailed error
  36847. ** message is available, it is written to zBufOut. If no error message
  36848. ** is available, zBufOut is left unmodified and SQLite uses a default
  36849. ** error message.
  36850. */
  36851. static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
  36852. const char *zErr;
  36853. UNUSED_PARAMETER(NotUsed);
  36854. unixEnterMutex();
  36855. zErr = dlerror();
  36856. if( zErr ){
  36857. sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
  36858. }
  36859. unixLeaveMutex();
  36860. }
  36861. static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
  36862. /*
  36863. ** GCC with -pedantic-errors says that C90 does not allow a void* to be
  36864. ** cast into a pointer to a function. And yet the library dlsym() routine
  36865. ** returns a void* which is really a pointer to a function. So how do we
  36866. ** use dlsym() with -pedantic-errors?
  36867. **
  36868. ** Variable x below is defined to be a pointer to a function taking
  36869. ** parameters void* and const char* and returning a pointer to a function.
  36870. ** We initialize x by assigning it a pointer to the dlsym() function.
  36871. ** (That assignment requires a cast.) Then we call the function that
  36872. ** x points to.
  36873. **
  36874. ** This work-around is unlikely to work correctly on any system where
  36875. ** you really cannot cast a function pointer into void*. But then, on the
  36876. ** other hand, dlsym() will not work on such a system either, so we have
  36877. ** not really lost anything.
  36878. */
  36879. void (*(*x)(void*,const char*))(void);
  36880. UNUSED_PARAMETER(NotUsed);
  36881. x = (void(*(*)(void*,const char*))(void))dlsym;
  36882. return (*x)(p, zSym);
  36883. }
  36884. static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
  36885. UNUSED_PARAMETER(NotUsed);
  36886. dlclose(pHandle);
  36887. }
  36888. #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  36889. #define unixDlOpen 0
  36890. #define unixDlError 0
  36891. #define unixDlSym 0
  36892. #define unixDlClose 0
  36893. #endif
  36894. /*
  36895. ** Write nBuf bytes of random data to the supplied buffer zBuf.
  36896. */
  36897. static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
  36898. UNUSED_PARAMETER(NotUsed);
  36899. assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
  36900. /* We have to initialize zBuf to prevent valgrind from reporting
  36901. ** errors. The reports issued by valgrind are incorrect - we would
  36902. ** prefer that the randomness be increased by making use of the
  36903. ** uninitialized space in zBuf - but valgrind errors tend to worry
  36904. ** some users. Rather than argue, it seems easier just to initialize
  36905. ** the whole array and silence valgrind, even if that means less randomness
  36906. ** in the random seed.
  36907. **
  36908. ** When testing, initializing zBuf[] to zero is all we do. That means
  36909. ** that we always use the same random number sequence. This makes the
  36910. ** tests repeatable.
  36911. */
  36912. memset(zBuf, 0, nBuf);
  36913. randomnessPid = osGetpid(0);
  36914. #if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
  36915. {
  36916. int fd, got;
  36917. fd = robust_open("/dev/urandom", O_RDONLY, 0);
  36918. if( fd<0 ){
  36919. time_t t;
  36920. time(&t);
  36921. memcpy(zBuf, &t, sizeof(t));
  36922. memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
  36923. assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
  36924. nBuf = sizeof(t) + sizeof(randomnessPid);
  36925. }else{
  36926. do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
  36927. robust_close(0, fd, __LINE__);
  36928. }
  36929. }
  36930. #endif
  36931. return nBuf;
  36932. }
  36933. /*
  36934. ** Sleep for a little while. Return the amount of time slept.
  36935. ** The argument is the number of microseconds we want to sleep.
  36936. ** The return value is the number of microseconds of sleep actually
  36937. ** requested from the underlying operating system, a number which
  36938. ** might be greater than or equal to the argument, but not less
  36939. ** than the argument.
  36940. */
  36941. static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
  36942. #if OS_VXWORKS
  36943. struct timespec sp;
  36944. sp.tv_sec = microseconds / 1000000;
  36945. sp.tv_nsec = (microseconds % 1000000) * 1000;
  36946. nanosleep(&sp, NULL);
  36947. UNUSED_PARAMETER(NotUsed);
  36948. return microseconds;
  36949. #elif defined(HAVE_USLEEP) && HAVE_USLEEP
  36950. usleep(microseconds);
  36951. UNUSED_PARAMETER(NotUsed);
  36952. return microseconds;
  36953. #else
  36954. int seconds = (microseconds+999999)/1000000;
  36955. sleep(seconds);
  36956. UNUSED_PARAMETER(NotUsed);
  36957. return seconds*1000000;
  36958. #endif
  36959. }
  36960. /*
  36961. ** The following variable, if set to a non-zero value, is interpreted as
  36962. ** the number of seconds since 1970 and is used to set the result of
  36963. ** sqlite3OsCurrentTime() during testing.
  36964. */
  36965. #ifdef SQLITE_TEST
  36966. SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
  36967. #endif
  36968. /*
  36969. ** Find the current time (in Universal Coordinated Time). Write into *piNow
  36970. ** the current time and date as a Julian Day number times 86_400_000. In
  36971. ** other words, write into *piNow the number of milliseconds since the Julian
  36972. ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
  36973. ** proleptic Gregorian calendar.
  36974. **
  36975. ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
  36976. ** cannot be found.
  36977. */
  36978. static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
  36979. static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
  36980. int rc = SQLITE_OK;
  36981. #if defined(NO_GETTOD)
  36982. time_t t;
  36983. time(&t);
  36984. *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
  36985. #elif OS_VXWORKS
  36986. struct timespec sNow;
  36987. clock_gettime(CLOCK_REALTIME, &sNow);
  36988. *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
  36989. #else
  36990. struct timeval sNow;
  36991. (void)gettimeofday(&sNow, 0); /* Cannot fail given valid arguments */
  36992. *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
  36993. #endif
  36994. #ifdef SQLITE_TEST
  36995. if( sqlite3_current_time ){
  36996. *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
  36997. }
  36998. #endif
  36999. UNUSED_PARAMETER(NotUsed);
  37000. return rc;
  37001. }
  37002. #ifndef SQLITE_OMIT_DEPRECATED
  37003. /*
  37004. ** Find the current time (in Universal Coordinated Time). Write the
  37005. ** current time and date as a Julian Day number into *prNow and
  37006. ** return 0. Return 1 if the time and date cannot be found.
  37007. */
  37008. static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
  37009. sqlite3_int64 i = 0;
  37010. int rc;
  37011. UNUSED_PARAMETER(NotUsed);
  37012. rc = unixCurrentTimeInt64(0, &i);
  37013. *prNow = i/86400000.0;
  37014. return rc;
  37015. }
  37016. #else
  37017. # define unixCurrentTime 0
  37018. #endif
  37019. /*
  37020. ** The xGetLastError() method is designed to return a better
  37021. ** low-level error message when operating-system problems come up
  37022. ** during SQLite operation. Only the integer return code is currently
  37023. ** used.
  37024. */
  37025. static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
  37026. UNUSED_PARAMETER(NotUsed);
  37027. UNUSED_PARAMETER(NotUsed2);
  37028. UNUSED_PARAMETER(NotUsed3);
  37029. return errno;
  37030. }
  37031. /*
  37032. ************************ End of sqlite3_vfs methods ***************************
  37033. ******************************************************************************/
  37034. /******************************************************************************
  37035. ************************** Begin Proxy Locking ********************************
  37036. **
  37037. ** Proxy locking is a "uber-locking-method" in this sense: It uses the
  37038. ** other locking methods on secondary lock files. Proxy locking is a
  37039. ** meta-layer over top of the primitive locking implemented above. For
  37040. ** this reason, the division that implements of proxy locking is deferred
  37041. ** until late in the file (here) after all of the other I/O methods have
  37042. ** been defined - so that the primitive locking methods are available
  37043. ** as services to help with the implementation of proxy locking.
  37044. **
  37045. ****
  37046. **
  37047. ** The default locking schemes in SQLite use byte-range locks on the
  37048. ** database file to coordinate safe, concurrent access by multiple readers
  37049. ** and writers [http://sqlite.org/lockingv3.html]. The five file locking
  37050. ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
  37051. ** as POSIX read & write locks over fixed set of locations (via fsctl),
  37052. ** on AFP and SMB only exclusive byte-range locks are available via fsctl
  37053. ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
  37054. ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
  37055. ** address in the shared range is taken for a SHARED lock, the entire
  37056. ** shared range is taken for an EXCLUSIVE lock):
  37057. **
  37058. ** PENDING_BYTE 0x40000000
  37059. ** RESERVED_BYTE 0x40000001
  37060. ** SHARED_RANGE 0x40000002 -> 0x40000200
  37061. **
  37062. ** This works well on the local file system, but shows a nearly 100x
  37063. ** slowdown in read performance on AFP because the AFP client disables
  37064. ** the read cache when byte-range locks are present. Enabling the read
  37065. ** cache exposes a cache coherency problem that is present on all OS X
  37066. ** supported network file systems. NFS and AFP both observe the
  37067. ** close-to-open semantics for ensuring cache coherency
  37068. ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
  37069. ** address the requirements for concurrent database access by multiple
  37070. ** readers and writers
  37071. ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
  37072. **
  37073. ** To address the performance and cache coherency issues, proxy file locking
  37074. ** changes the way database access is controlled by limiting access to a
  37075. ** single host at a time and moving file locks off of the database file
  37076. ** and onto a proxy file on the local file system.
  37077. **
  37078. **
  37079. ** Using proxy locks
  37080. ** -----------------
  37081. **
  37082. ** C APIs
  37083. **
  37084. ** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
  37085. ** <proxy_path> | ":auto:");
  37086. ** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
  37087. ** &<proxy_path>);
  37088. **
  37089. **
  37090. ** SQL pragmas
  37091. **
  37092. ** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
  37093. ** PRAGMA [database.]lock_proxy_file
  37094. **
  37095. ** Specifying ":auto:" means that if there is a conch file with a matching
  37096. ** host ID in it, the proxy path in the conch file will be used, otherwise
  37097. ** a proxy path based on the user's temp dir
  37098. ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
  37099. ** actual proxy file name is generated from the name and path of the
  37100. ** database file. For example:
  37101. **
  37102. ** For database path "/Users/me/foo.db"
  37103. ** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
  37104. **
  37105. ** Once a lock proxy is configured for a database connection, it can not
  37106. ** be removed, however it may be switched to a different proxy path via
  37107. ** the above APIs (assuming the conch file is not being held by another
  37108. ** connection or process).
  37109. **
  37110. **
  37111. ** How proxy locking works
  37112. ** -----------------------
  37113. **
  37114. ** Proxy file locking relies primarily on two new supporting files:
  37115. **
  37116. ** * conch file to limit access to the database file to a single host
  37117. ** at a time
  37118. **
  37119. ** * proxy file to act as a proxy for the advisory locks normally
  37120. ** taken on the database
  37121. **
  37122. ** The conch file - to use a proxy file, sqlite must first "hold the conch"
  37123. ** by taking an sqlite-style shared lock on the conch file, reading the
  37124. ** contents and comparing the host's unique host ID (see below) and lock
  37125. ** proxy path against the values stored in the conch. The conch file is
  37126. ** stored in the same directory as the database file and the file name
  37127. ** is patterned after the database file name as ".<databasename>-conch".
  37128. ** If the conch file does not exist, or its contents do not match the
  37129. ** host ID and/or proxy path, then the lock is escalated to an exclusive
  37130. ** lock and the conch file contents is updated with the host ID and proxy
  37131. ** path and the lock is downgraded to a shared lock again. If the conch
  37132. ** is held by another process (with a shared lock), the exclusive lock
  37133. ** will fail and SQLITE_BUSY is returned.
  37134. **
  37135. ** The proxy file - a single-byte file used for all advisory file locks
  37136. ** normally taken on the database file. This allows for safe sharing
  37137. ** of the database file for multiple readers and writers on the same
  37138. ** host (the conch ensures that they all use the same local lock file).
  37139. **
  37140. ** Requesting the lock proxy does not immediately take the conch, it is
  37141. ** only taken when the first request to lock database file is made.
  37142. ** This matches the semantics of the traditional locking behavior, where
  37143. ** opening a connection to a database file does not take a lock on it.
  37144. ** The shared lock and an open file descriptor are maintained until
  37145. ** the connection to the database is closed.
  37146. **
  37147. ** The proxy file and the lock file are never deleted so they only need
  37148. ** to be created the first time they are used.
  37149. **
  37150. ** Configuration options
  37151. ** ---------------------
  37152. **
  37153. ** SQLITE_PREFER_PROXY_LOCKING
  37154. **
  37155. ** Database files accessed on non-local file systems are
  37156. ** automatically configured for proxy locking, lock files are
  37157. ** named automatically using the same logic as
  37158. ** PRAGMA lock_proxy_file=":auto:"
  37159. **
  37160. ** SQLITE_PROXY_DEBUG
  37161. **
  37162. ** Enables the logging of error messages during host id file
  37163. ** retrieval and creation
  37164. **
  37165. ** LOCKPROXYDIR
  37166. **
  37167. ** Overrides the default directory used for lock proxy files that
  37168. ** are named automatically via the ":auto:" setting
  37169. **
  37170. ** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
  37171. **
  37172. ** Permissions to use when creating a directory for storing the
  37173. ** lock proxy files, only used when LOCKPROXYDIR is not set.
  37174. **
  37175. **
  37176. ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
  37177. ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
  37178. ** force proxy locking to be used for every database file opened, and 0
  37179. ** will force automatic proxy locking to be disabled for all database
  37180. ** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
  37181. ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
  37182. */
  37183. /*
  37184. ** Proxy locking is only available on MacOSX
  37185. */
  37186. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  37187. /*
  37188. ** The proxyLockingContext has the path and file structures for the remote
  37189. ** and local proxy files in it
  37190. */
  37191. typedef struct proxyLockingContext proxyLockingContext;
  37192. struct proxyLockingContext {
  37193. unixFile *conchFile; /* Open conch file */
  37194. char *conchFilePath; /* Name of the conch file */
  37195. unixFile *lockProxy; /* Open proxy lock file */
  37196. char *lockProxyPath; /* Name of the proxy lock file */
  37197. char *dbPath; /* Name of the open file */
  37198. int conchHeld; /* 1 if the conch is held, -1 if lockless */
  37199. int nFails; /* Number of conch taking failures */
  37200. void *oldLockingContext; /* Original lockingcontext to restore on close */
  37201. sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
  37202. };
  37203. /*
  37204. ** The proxy lock file path for the database at dbPath is written into lPath,
  37205. ** which must point to valid, writable memory large enough for a maxLen length
  37206. ** file path.
  37207. */
  37208. static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
  37209. int len;
  37210. int dbLen;
  37211. int i;
  37212. #ifdef LOCKPROXYDIR
  37213. len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
  37214. #else
  37215. # ifdef _CS_DARWIN_USER_TEMP_DIR
  37216. {
  37217. if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
  37218. OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
  37219. lPath, errno, osGetpid(0)));
  37220. return SQLITE_IOERR_LOCK;
  37221. }
  37222. len = strlcat(lPath, "sqliteplocks", maxLen);
  37223. }
  37224. # else
  37225. len = strlcpy(lPath, "/tmp/", maxLen);
  37226. # endif
  37227. #endif
  37228. if( lPath[len-1]!='/' ){
  37229. len = strlcat(lPath, "/", maxLen);
  37230. }
  37231. /* transform the db path to a unique cache name */
  37232. dbLen = (int)strlen(dbPath);
  37233. for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
  37234. char c = dbPath[i];
  37235. lPath[i+len] = (c=='/')?'_':c;
  37236. }
  37237. lPath[i+len]='\0';
  37238. strlcat(lPath, ":auto:", maxLen);
  37239. OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
  37240. return SQLITE_OK;
  37241. }
  37242. /*
  37243. ** Creates the lock file and any missing directories in lockPath
  37244. */
  37245. static int proxyCreateLockPath(const char *lockPath){
  37246. int i, len;
  37247. char buf[MAXPATHLEN];
  37248. int start = 0;
  37249. assert(lockPath!=NULL);
  37250. /* try to create all the intermediate directories */
  37251. len = (int)strlen(lockPath);
  37252. buf[0] = lockPath[0];
  37253. for( i=1; i<len; i++ ){
  37254. if( lockPath[i] == '/' && (i - start > 0) ){
  37255. /* only mkdir if leaf dir != "." or "/" or ".." */
  37256. if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
  37257. || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
  37258. buf[i]='\0';
  37259. if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
  37260. int err=errno;
  37261. if( err!=EEXIST ) {
  37262. OSTRACE(("CREATELOCKPATH FAILED creating %s, "
  37263. "'%s' proxy lock path=%s pid=%d\n",
  37264. buf, strerror(err), lockPath, osGetpid(0)));
  37265. return err;
  37266. }
  37267. }
  37268. }
  37269. start=i+1;
  37270. }
  37271. buf[i] = lockPath[i];
  37272. }
  37273. OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n",lockPath,osGetpid(0)));
  37274. return 0;
  37275. }
  37276. /*
  37277. ** Create a new VFS file descriptor (stored in memory obtained from
  37278. ** sqlite3_malloc) and open the file named "path" in the file descriptor.
  37279. **
  37280. ** The caller is responsible not only for closing the file descriptor
  37281. ** but also for freeing the memory associated with the file descriptor.
  37282. */
  37283. static int proxyCreateUnixFile(
  37284. const char *path, /* path for the new unixFile */
  37285. unixFile **ppFile, /* unixFile created and returned by ref */
  37286. int islockfile /* if non zero missing dirs will be created */
  37287. ) {
  37288. int fd = -1;
  37289. unixFile *pNew;
  37290. int rc = SQLITE_OK;
  37291. int openFlags = O_RDWR | O_CREAT;
  37292. sqlite3_vfs dummyVfs;
  37293. int terrno = 0;
  37294. UnixUnusedFd *pUnused = NULL;
  37295. /* 1. first try to open/create the file
  37296. ** 2. if that fails, and this is a lock file (not-conch), try creating
  37297. ** the parent directories and then try again.
  37298. ** 3. if that fails, try to open the file read-only
  37299. ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
  37300. */
  37301. pUnused = findReusableFd(path, openFlags);
  37302. if( pUnused ){
  37303. fd = pUnused->fd;
  37304. }else{
  37305. pUnused = sqlite3_malloc64(sizeof(*pUnused));
  37306. if( !pUnused ){
  37307. return SQLITE_NOMEM_BKPT;
  37308. }
  37309. }
  37310. if( fd<0 ){
  37311. fd = robust_open(path, openFlags, 0);
  37312. terrno = errno;
  37313. if( fd<0 && errno==ENOENT && islockfile ){
  37314. if( proxyCreateLockPath(path) == SQLITE_OK ){
  37315. fd = robust_open(path, openFlags, 0);
  37316. }
  37317. }
  37318. }
  37319. if( fd<0 ){
  37320. openFlags = O_RDONLY;
  37321. fd = robust_open(path, openFlags, 0);
  37322. terrno = errno;
  37323. }
  37324. if( fd<0 ){
  37325. if( islockfile ){
  37326. return SQLITE_BUSY;
  37327. }
  37328. switch (terrno) {
  37329. case EACCES:
  37330. return SQLITE_PERM;
  37331. case EIO:
  37332. return SQLITE_IOERR_LOCK; /* even though it is the conch */
  37333. default:
  37334. return SQLITE_CANTOPEN_BKPT;
  37335. }
  37336. }
  37337. pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
  37338. if( pNew==NULL ){
  37339. rc = SQLITE_NOMEM_BKPT;
  37340. goto end_create_proxy;
  37341. }
  37342. memset(pNew, 0, sizeof(unixFile));
  37343. pNew->openFlags = openFlags;
  37344. memset(&dummyVfs, 0, sizeof(dummyVfs));
  37345. dummyVfs.pAppData = (void*)&autolockIoFinder;
  37346. dummyVfs.zName = "dummy";
  37347. pUnused->fd = fd;
  37348. pUnused->flags = openFlags;
  37349. pNew->pPreallocatedUnused = pUnused;
  37350. rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
  37351. if( rc==SQLITE_OK ){
  37352. *ppFile = pNew;
  37353. return SQLITE_OK;
  37354. }
  37355. end_create_proxy:
  37356. robust_close(pNew, fd, __LINE__);
  37357. sqlite3_free(pNew);
  37358. sqlite3_free(pUnused);
  37359. return rc;
  37360. }
  37361. #ifdef SQLITE_TEST
  37362. /* simulate multiple hosts by creating unique hostid file paths */
  37363. SQLITE_API int sqlite3_hostid_num = 0;
  37364. #endif
  37365. #define PROXY_HOSTIDLEN 16 /* conch file host id length */
  37366. #ifdef HAVE_GETHOSTUUID
  37367. /* Not always defined in the headers as it ought to be */
  37368. extern int gethostuuid(uuid_t id, const struct timespec *wait);
  37369. #endif
  37370. /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
  37371. ** bytes of writable memory.
  37372. */
  37373. static int proxyGetHostID(unsigned char *pHostID, int *pError){
  37374. assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
  37375. memset(pHostID, 0, PROXY_HOSTIDLEN);
  37376. #ifdef HAVE_GETHOSTUUID
  37377. {
  37378. struct timespec timeout = {1, 0}; /* 1 sec timeout */
  37379. if( gethostuuid(pHostID, &timeout) ){
  37380. int err = errno;
  37381. if( pError ){
  37382. *pError = err;
  37383. }
  37384. return SQLITE_IOERR;
  37385. }
  37386. }
  37387. #else
  37388. UNUSED_PARAMETER(pError);
  37389. #endif
  37390. #ifdef SQLITE_TEST
  37391. /* simulate multiple hosts by creating unique hostid file paths */
  37392. if( sqlite3_hostid_num != 0){
  37393. pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
  37394. }
  37395. #endif
  37396. return SQLITE_OK;
  37397. }
  37398. /* The conch file contains the header, host id and lock file path
  37399. */
  37400. #define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
  37401. #define PROXY_HEADERLEN 1 /* conch file header length */
  37402. #define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
  37403. #define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
  37404. /*
  37405. ** Takes an open conch file, copies the contents to a new path and then moves
  37406. ** it back. The newly created file's file descriptor is assigned to the
  37407. ** conch file structure and finally the original conch file descriptor is
  37408. ** closed. Returns zero if successful.
  37409. */
  37410. static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
  37411. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  37412. unixFile *conchFile = pCtx->conchFile;
  37413. char tPath[MAXPATHLEN];
  37414. char buf[PROXY_MAXCONCHLEN];
  37415. char *cPath = pCtx->conchFilePath;
  37416. size_t readLen = 0;
  37417. size_t pathLen = 0;
  37418. char errmsg[64] = "";
  37419. int fd = -1;
  37420. int rc = -1;
  37421. UNUSED_PARAMETER(myHostID);
  37422. /* create a new path by replace the trailing '-conch' with '-break' */
  37423. pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
  37424. if( pathLen>MAXPATHLEN || pathLen<6 ||
  37425. (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
  37426. sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
  37427. goto end_breaklock;
  37428. }
  37429. /* read the conch content */
  37430. readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
  37431. if( readLen<PROXY_PATHINDEX ){
  37432. sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
  37433. goto end_breaklock;
  37434. }
  37435. /* write it out to the temporary break file */
  37436. fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
  37437. if( fd<0 ){
  37438. sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
  37439. goto end_breaklock;
  37440. }
  37441. if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
  37442. sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
  37443. goto end_breaklock;
  37444. }
  37445. if( rename(tPath, cPath) ){
  37446. sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
  37447. goto end_breaklock;
  37448. }
  37449. rc = 0;
  37450. fprintf(stderr, "broke stale lock on %s\n", cPath);
  37451. robust_close(pFile, conchFile->h, __LINE__);
  37452. conchFile->h = fd;
  37453. conchFile->openFlags = O_RDWR | O_CREAT;
  37454. end_breaklock:
  37455. if( rc ){
  37456. if( fd>=0 ){
  37457. osUnlink(tPath);
  37458. robust_close(pFile, fd, __LINE__);
  37459. }
  37460. fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
  37461. }
  37462. return rc;
  37463. }
  37464. /* Take the requested lock on the conch file and break a stale lock if the
  37465. ** host id matches.
  37466. */
  37467. static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
  37468. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  37469. unixFile *conchFile = pCtx->conchFile;
  37470. int rc = SQLITE_OK;
  37471. int nTries = 0;
  37472. struct timespec conchModTime;
  37473. memset(&conchModTime, 0, sizeof(conchModTime));
  37474. do {
  37475. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
  37476. nTries ++;
  37477. if( rc==SQLITE_BUSY ){
  37478. /* If the lock failed (busy):
  37479. * 1st try: get the mod time of the conch, wait 0.5s and try again.
  37480. * 2nd try: fail if the mod time changed or host id is different, wait
  37481. * 10 sec and try again
  37482. * 3rd try: break the lock unless the mod time has changed.
  37483. */
  37484. struct stat buf;
  37485. if( osFstat(conchFile->h, &buf) ){
  37486. storeLastErrno(pFile, errno);
  37487. return SQLITE_IOERR_LOCK;
  37488. }
  37489. if( nTries==1 ){
  37490. conchModTime = buf.st_mtimespec;
  37491. usleep(500000); /* wait 0.5 sec and try the lock again*/
  37492. continue;
  37493. }
  37494. assert( nTries>1 );
  37495. if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
  37496. conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
  37497. return SQLITE_BUSY;
  37498. }
  37499. if( nTries==2 ){
  37500. char tBuf[PROXY_MAXCONCHLEN];
  37501. int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
  37502. if( len<0 ){
  37503. storeLastErrno(pFile, errno);
  37504. return SQLITE_IOERR_LOCK;
  37505. }
  37506. if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
  37507. /* don't break the lock if the host id doesn't match */
  37508. if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
  37509. return SQLITE_BUSY;
  37510. }
  37511. }else{
  37512. /* don't break the lock on short read or a version mismatch */
  37513. return SQLITE_BUSY;
  37514. }
  37515. usleep(10000000); /* wait 10 sec and try the lock again */
  37516. continue;
  37517. }
  37518. assert( nTries==3 );
  37519. if( 0==proxyBreakConchLock(pFile, myHostID) ){
  37520. rc = SQLITE_OK;
  37521. if( lockType==EXCLUSIVE_LOCK ){
  37522. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
  37523. }
  37524. if( !rc ){
  37525. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
  37526. }
  37527. }
  37528. }
  37529. } while( rc==SQLITE_BUSY && nTries<3 );
  37530. return rc;
  37531. }
  37532. /* Takes the conch by taking a shared lock and read the contents conch, if
  37533. ** lockPath is non-NULL, the host ID and lock file path must match. A NULL
  37534. ** lockPath means that the lockPath in the conch file will be used if the
  37535. ** host IDs match, or a new lock path will be generated automatically
  37536. ** and written to the conch file.
  37537. */
  37538. static int proxyTakeConch(unixFile *pFile){
  37539. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  37540. if( pCtx->conchHeld!=0 ){
  37541. return SQLITE_OK;
  37542. }else{
  37543. unixFile *conchFile = pCtx->conchFile;
  37544. uuid_t myHostID;
  37545. int pError = 0;
  37546. char readBuf[PROXY_MAXCONCHLEN];
  37547. char lockPath[MAXPATHLEN];
  37548. char *tempLockPath = NULL;
  37549. int rc = SQLITE_OK;
  37550. int createConch = 0;
  37551. int hostIdMatch = 0;
  37552. int readLen = 0;
  37553. int tryOldLockPath = 0;
  37554. int forceNewLockPath = 0;
  37555. OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
  37556. (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
  37557. osGetpid(0)));
  37558. rc = proxyGetHostID(myHostID, &pError);
  37559. if( (rc&0xff)==SQLITE_IOERR ){
  37560. storeLastErrno(pFile, pError);
  37561. goto end_takeconch;
  37562. }
  37563. rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
  37564. if( rc!=SQLITE_OK ){
  37565. goto end_takeconch;
  37566. }
  37567. /* read the existing conch file */
  37568. readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
  37569. if( readLen<0 ){
  37570. /* I/O error: lastErrno set by seekAndRead */
  37571. storeLastErrno(pFile, conchFile->lastErrno);
  37572. rc = SQLITE_IOERR_READ;
  37573. goto end_takeconch;
  37574. }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
  37575. readBuf[0]!=(char)PROXY_CONCHVERSION ){
  37576. /* a short read or version format mismatch means we need to create a new
  37577. ** conch file.
  37578. */
  37579. createConch = 1;
  37580. }
  37581. /* if the host id matches and the lock path already exists in the conch
  37582. ** we'll try to use the path there, if we can't open that path, we'll
  37583. ** retry with a new auto-generated path
  37584. */
  37585. do { /* in case we need to try again for an :auto: named lock file */
  37586. if( !createConch && !forceNewLockPath ){
  37587. hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
  37588. PROXY_HOSTIDLEN);
  37589. /* if the conch has data compare the contents */
  37590. if( !pCtx->lockProxyPath ){
  37591. /* for auto-named local lock file, just check the host ID and we'll
  37592. ** use the local lock file path that's already in there
  37593. */
  37594. if( hostIdMatch ){
  37595. size_t pathLen = (readLen - PROXY_PATHINDEX);
  37596. if( pathLen>=MAXPATHLEN ){
  37597. pathLen=MAXPATHLEN-1;
  37598. }
  37599. memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
  37600. lockPath[pathLen] = 0;
  37601. tempLockPath = lockPath;
  37602. tryOldLockPath = 1;
  37603. /* create a copy of the lock path if the conch is taken */
  37604. goto end_takeconch;
  37605. }
  37606. }else if( hostIdMatch
  37607. && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
  37608. readLen-PROXY_PATHINDEX)
  37609. ){
  37610. /* conch host and lock path match */
  37611. goto end_takeconch;
  37612. }
  37613. }
  37614. /* if the conch isn't writable and doesn't match, we can't take it */
  37615. if( (conchFile->openFlags&O_RDWR) == 0 ){
  37616. rc = SQLITE_BUSY;
  37617. goto end_takeconch;
  37618. }
  37619. /* either the conch didn't match or we need to create a new one */
  37620. if( !pCtx->lockProxyPath ){
  37621. proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
  37622. tempLockPath = lockPath;
  37623. /* create a copy of the lock path _only_ if the conch is taken */
  37624. }
  37625. /* update conch with host and path (this will fail if other process
  37626. ** has a shared lock already), if the host id matches, use the big
  37627. ** stick.
  37628. */
  37629. futimes(conchFile->h, NULL);
  37630. if( hostIdMatch && !createConch ){
  37631. if( conchFile->pInode && conchFile->pInode->nShared>1 ){
  37632. /* We are trying for an exclusive lock but another thread in this
  37633. ** same process is still holding a shared lock. */
  37634. rc = SQLITE_BUSY;
  37635. } else {
  37636. rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
  37637. }
  37638. }else{
  37639. rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
  37640. }
  37641. if( rc==SQLITE_OK ){
  37642. char writeBuffer[PROXY_MAXCONCHLEN];
  37643. int writeSize = 0;
  37644. writeBuffer[0] = (char)PROXY_CONCHVERSION;
  37645. memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
  37646. if( pCtx->lockProxyPath!=NULL ){
  37647. strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
  37648. MAXPATHLEN);
  37649. }else{
  37650. strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
  37651. }
  37652. writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
  37653. robust_ftruncate(conchFile->h, writeSize);
  37654. rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
  37655. full_fsync(conchFile->h,0,0);
  37656. /* If we created a new conch file (not just updated the contents of a
  37657. ** valid conch file), try to match the permissions of the database
  37658. */
  37659. if( rc==SQLITE_OK && createConch ){
  37660. struct stat buf;
  37661. int err = osFstat(pFile->h, &buf);
  37662. if( err==0 ){
  37663. mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
  37664. S_IROTH|S_IWOTH);
  37665. /* try to match the database file R/W permissions, ignore failure */
  37666. #ifndef SQLITE_PROXY_DEBUG
  37667. osFchmod(conchFile->h, cmode);
  37668. #else
  37669. do{
  37670. rc = osFchmod(conchFile->h, cmode);
  37671. }while( rc==(-1) && errno==EINTR );
  37672. if( rc!=0 ){
  37673. int code = errno;
  37674. fprintf(stderr, "fchmod %o FAILED with %d %s\n",
  37675. cmode, code, strerror(code));
  37676. } else {
  37677. fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
  37678. }
  37679. }else{
  37680. int code = errno;
  37681. fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
  37682. err, code, strerror(code));
  37683. #endif
  37684. }
  37685. }
  37686. }
  37687. conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
  37688. end_takeconch:
  37689. OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
  37690. if( rc==SQLITE_OK && pFile->openFlags ){
  37691. int fd;
  37692. if( pFile->h>=0 ){
  37693. robust_close(pFile, pFile->h, __LINE__);
  37694. }
  37695. pFile->h = -1;
  37696. fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
  37697. OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
  37698. if( fd>=0 ){
  37699. pFile->h = fd;
  37700. }else{
  37701. rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
  37702. during locking */
  37703. }
  37704. }
  37705. if( rc==SQLITE_OK && !pCtx->lockProxy ){
  37706. char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
  37707. rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
  37708. if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
  37709. /* we couldn't create the proxy lock file with the old lock file path
  37710. ** so try again via auto-naming
  37711. */
  37712. forceNewLockPath = 1;
  37713. tryOldLockPath = 0;
  37714. continue; /* go back to the do {} while start point, try again */
  37715. }
  37716. }
  37717. if( rc==SQLITE_OK ){
  37718. /* Need to make a copy of path if we extracted the value
  37719. ** from the conch file or the path was allocated on the stack
  37720. */
  37721. if( tempLockPath ){
  37722. pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
  37723. if( !pCtx->lockProxyPath ){
  37724. rc = SQLITE_NOMEM_BKPT;
  37725. }
  37726. }
  37727. }
  37728. if( rc==SQLITE_OK ){
  37729. pCtx->conchHeld = 1;
  37730. if( pCtx->lockProxy->pMethod == &afpIoMethods ){
  37731. afpLockingContext *afpCtx;
  37732. afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
  37733. afpCtx->dbPath = pCtx->lockProxyPath;
  37734. }
  37735. } else {
  37736. conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
  37737. }
  37738. OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
  37739. rc==SQLITE_OK?"ok":"failed"));
  37740. return rc;
  37741. } while (1); /* in case we need to retry the :auto: lock file -
  37742. ** we should never get here except via the 'continue' call. */
  37743. }
  37744. }
  37745. /*
  37746. ** If pFile holds a lock on a conch file, then release that lock.
  37747. */
  37748. static int proxyReleaseConch(unixFile *pFile){
  37749. int rc = SQLITE_OK; /* Subroutine return code */
  37750. proxyLockingContext *pCtx; /* The locking context for the proxy lock */
  37751. unixFile *conchFile; /* Name of the conch file */
  37752. pCtx = (proxyLockingContext *)pFile->lockingContext;
  37753. conchFile = pCtx->conchFile;
  37754. OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
  37755. (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
  37756. osGetpid(0)));
  37757. if( pCtx->conchHeld>0 ){
  37758. rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
  37759. }
  37760. pCtx->conchHeld = 0;
  37761. OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
  37762. (rc==SQLITE_OK ? "ok" : "failed")));
  37763. return rc;
  37764. }
  37765. /*
  37766. ** Given the name of a database file, compute the name of its conch file.
  37767. ** Store the conch filename in memory obtained from sqlite3_malloc64().
  37768. ** Make *pConchPath point to the new name. Return SQLITE_OK on success
  37769. ** or SQLITE_NOMEM if unable to obtain memory.
  37770. **
  37771. ** The caller is responsible for ensuring that the allocated memory
  37772. ** space is eventually freed.
  37773. **
  37774. ** *pConchPath is set to NULL if a memory allocation error occurs.
  37775. */
  37776. static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
  37777. int i; /* Loop counter */
  37778. int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
  37779. char *conchPath; /* buffer in which to construct conch name */
  37780. /* Allocate space for the conch filename and initialize the name to
  37781. ** the name of the original database file. */
  37782. *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
  37783. if( conchPath==0 ){
  37784. return SQLITE_NOMEM_BKPT;
  37785. }
  37786. memcpy(conchPath, dbPath, len+1);
  37787. /* now insert a "." before the last / character */
  37788. for( i=(len-1); i>=0; i-- ){
  37789. if( conchPath[i]=='/' ){
  37790. i++;
  37791. break;
  37792. }
  37793. }
  37794. conchPath[i]='.';
  37795. while ( i<len ){
  37796. conchPath[i+1]=dbPath[i];
  37797. i++;
  37798. }
  37799. /* append the "-conch" suffix to the file */
  37800. memcpy(&conchPath[i+1], "-conch", 7);
  37801. assert( (int)strlen(conchPath) == len+7 );
  37802. return SQLITE_OK;
  37803. }
  37804. /* Takes a fully configured proxy locking-style unix file and switches
  37805. ** the local lock file path
  37806. */
  37807. static int switchLockProxyPath(unixFile *pFile, const char *path) {
  37808. proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
  37809. char *oldPath = pCtx->lockProxyPath;
  37810. int rc = SQLITE_OK;
  37811. if( pFile->eFileLock!=NO_LOCK ){
  37812. return SQLITE_BUSY;
  37813. }
  37814. /* nothing to do if the path is NULL, :auto: or matches the existing path */
  37815. if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
  37816. (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
  37817. return SQLITE_OK;
  37818. }else{
  37819. unixFile *lockProxy = pCtx->lockProxy;
  37820. pCtx->lockProxy=NULL;
  37821. pCtx->conchHeld = 0;
  37822. if( lockProxy!=NULL ){
  37823. rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
  37824. if( rc ) return rc;
  37825. sqlite3_free(lockProxy);
  37826. }
  37827. sqlite3_free(oldPath);
  37828. pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
  37829. }
  37830. return rc;
  37831. }
  37832. /*
  37833. ** pFile is a file that has been opened by a prior xOpen call. dbPath
  37834. ** is a string buffer at least MAXPATHLEN+1 characters in size.
  37835. **
  37836. ** This routine find the filename associated with pFile and writes it
  37837. ** int dbPath.
  37838. */
  37839. static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
  37840. #if defined(__APPLE__)
  37841. if( pFile->pMethod == &afpIoMethods ){
  37842. /* afp style keeps a reference to the db path in the filePath field
  37843. ** of the struct */
  37844. assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
  37845. strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
  37846. MAXPATHLEN);
  37847. } else
  37848. #endif
  37849. if( pFile->pMethod == &dotlockIoMethods ){
  37850. /* dot lock style uses the locking context to store the dot lock
  37851. ** file path */
  37852. int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
  37853. memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
  37854. }else{
  37855. /* all other styles use the locking context to store the db file path */
  37856. assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
  37857. strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
  37858. }
  37859. return SQLITE_OK;
  37860. }
  37861. /*
  37862. ** Takes an already filled in unix file and alters it so all file locking
  37863. ** will be performed on the local proxy lock file. The following fields
  37864. ** are preserved in the locking context so that they can be restored and
  37865. ** the unix structure properly cleaned up at close time:
  37866. ** ->lockingContext
  37867. ** ->pMethod
  37868. */
  37869. static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
  37870. proxyLockingContext *pCtx;
  37871. char dbPath[MAXPATHLEN+1]; /* Name of the database file */
  37872. char *lockPath=NULL;
  37873. int rc = SQLITE_OK;
  37874. if( pFile->eFileLock!=NO_LOCK ){
  37875. return SQLITE_BUSY;
  37876. }
  37877. proxyGetDbPathForUnixFile(pFile, dbPath);
  37878. if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
  37879. lockPath=NULL;
  37880. }else{
  37881. lockPath=(char *)path;
  37882. }
  37883. OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
  37884. (lockPath ? lockPath : ":auto:"), osGetpid(0)));
  37885. pCtx = sqlite3_malloc64( sizeof(*pCtx) );
  37886. if( pCtx==0 ){
  37887. return SQLITE_NOMEM_BKPT;
  37888. }
  37889. memset(pCtx, 0, sizeof(*pCtx));
  37890. rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
  37891. if( rc==SQLITE_OK ){
  37892. rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
  37893. if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
  37894. /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
  37895. ** (c) the file system is read-only, then enable no-locking access.
  37896. ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
  37897. ** that openFlags will have only one of O_RDONLY or O_RDWR.
  37898. */
  37899. struct statfs fsInfo;
  37900. struct stat conchInfo;
  37901. int goLockless = 0;
  37902. if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
  37903. int err = errno;
  37904. if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
  37905. goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
  37906. }
  37907. }
  37908. if( goLockless ){
  37909. pCtx->conchHeld = -1; /* read only FS/ lockless */
  37910. rc = SQLITE_OK;
  37911. }
  37912. }
  37913. }
  37914. if( rc==SQLITE_OK && lockPath ){
  37915. pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
  37916. }
  37917. if( rc==SQLITE_OK ){
  37918. pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
  37919. if( pCtx->dbPath==NULL ){
  37920. rc = SQLITE_NOMEM_BKPT;
  37921. }
  37922. }
  37923. if( rc==SQLITE_OK ){
  37924. /* all memory is allocated, proxys are created and assigned,
  37925. ** switch the locking context and pMethod then return.
  37926. */
  37927. pCtx->oldLockingContext = pFile->lockingContext;
  37928. pFile->lockingContext = pCtx;
  37929. pCtx->pOldMethod = pFile->pMethod;
  37930. pFile->pMethod = &proxyIoMethods;
  37931. }else{
  37932. if( pCtx->conchFile ){
  37933. pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
  37934. sqlite3_free(pCtx->conchFile);
  37935. }
  37936. sqlite3DbFree(0, pCtx->lockProxyPath);
  37937. sqlite3_free(pCtx->conchFilePath);
  37938. sqlite3_free(pCtx);
  37939. }
  37940. OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
  37941. (rc==SQLITE_OK ? "ok" : "failed")));
  37942. return rc;
  37943. }
  37944. /*
  37945. ** This routine handles sqlite3_file_control() calls that are specific
  37946. ** to proxy locking.
  37947. */
  37948. static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
  37949. switch( op ){
  37950. case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
  37951. unixFile *pFile = (unixFile*)id;
  37952. if( pFile->pMethod == &proxyIoMethods ){
  37953. proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
  37954. proxyTakeConch(pFile);
  37955. if( pCtx->lockProxyPath ){
  37956. *(const char **)pArg = pCtx->lockProxyPath;
  37957. }else{
  37958. *(const char **)pArg = ":auto: (not held)";
  37959. }
  37960. } else {
  37961. *(const char **)pArg = NULL;
  37962. }
  37963. return SQLITE_OK;
  37964. }
  37965. case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
  37966. unixFile *pFile = (unixFile*)id;
  37967. int rc = SQLITE_OK;
  37968. int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
  37969. if( pArg==NULL || (const char *)pArg==0 ){
  37970. if( isProxyStyle ){
  37971. /* turn off proxy locking - not supported. If support is added for
  37972. ** switching proxy locking mode off then it will need to fail if
  37973. ** the journal mode is WAL mode.
  37974. */
  37975. rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
  37976. }else{
  37977. /* turn off proxy locking - already off - NOOP */
  37978. rc = SQLITE_OK;
  37979. }
  37980. }else{
  37981. const char *proxyPath = (const char *)pArg;
  37982. if( isProxyStyle ){
  37983. proxyLockingContext *pCtx =
  37984. (proxyLockingContext*)pFile->lockingContext;
  37985. if( !strcmp(pArg, ":auto:")
  37986. || (pCtx->lockProxyPath &&
  37987. !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
  37988. ){
  37989. rc = SQLITE_OK;
  37990. }else{
  37991. rc = switchLockProxyPath(pFile, proxyPath);
  37992. }
  37993. }else{
  37994. /* turn on proxy file locking */
  37995. rc = proxyTransformUnixFile(pFile, proxyPath);
  37996. }
  37997. }
  37998. return rc;
  37999. }
  38000. default: {
  38001. assert( 0 ); /* The call assures that only valid opcodes are sent */
  38002. }
  38003. }
  38004. /*NOTREACHED*/
  38005. return SQLITE_ERROR;
  38006. }
  38007. /*
  38008. ** Within this division (the proxying locking implementation) the procedures
  38009. ** above this point are all utilities. The lock-related methods of the
  38010. ** proxy-locking sqlite3_io_method object follow.
  38011. */
  38012. /*
  38013. ** This routine checks if there is a RESERVED lock held on the specified
  38014. ** file by this or any other process. If such a lock is held, set *pResOut
  38015. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  38016. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  38017. */
  38018. static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
  38019. unixFile *pFile = (unixFile*)id;
  38020. int rc = proxyTakeConch(pFile);
  38021. if( rc==SQLITE_OK ){
  38022. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  38023. if( pCtx->conchHeld>0 ){
  38024. unixFile *proxy = pCtx->lockProxy;
  38025. return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
  38026. }else{ /* conchHeld < 0 is lockless */
  38027. pResOut=0;
  38028. }
  38029. }
  38030. return rc;
  38031. }
  38032. /*
  38033. ** Lock the file with the lock specified by parameter eFileLock - one
  38034. ** of the following:
  38035. **
  38036. ** (1) SHARED_LOCK
  38037. ** (2) RESERVED_LOCK
  38038. ** (3) PENDING_LOCK
  38039. ** (4) EXCLUSIVE_LOCK
  38040. **
  38041. ** Sometimes when requesting one lock state, additional lock states
  38042. ** are inserted in between. The locking might fail on one of the later
  38043. ** transitions leaving the lock state different from what it started but
  38044. ** still short of its goal. The following chart shows the allowed
  38045. ** transitions and the inserted intermediate states:
  38046. **
  38047. ** UNLOCKED -> SHARED
  38048. ** SHARED -> RESERVED
  38049. ** SHARED -> (PENDING) -> EXCLUSIVE
  38050. ** RESERVED -> (PENDING) -> EXCLUSIVE
  38051. ** PENDING -> EXCLUSIVE
  38052. **
  38053. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  38054. ** routine to lower a locking level.
  38055. */
  38056. static int proxyLock(sqlite3_file *id, int eFileLock) {
  38057. unixFile *pFile = (unixFile*)id;
  38058. int rc = proxyTakeConch(pFile);
  38059. if( rc==SQLITE_OK ){
  38060. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  38061. if( pCtx->conchHeld>0 ){
  38062. unixFile *proxy = pCtx->lockProxy;
  38063. rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
  38064. pFile->eFileLock = proxy->eFileLock;
  38065. }else{
  38066. /* conchHeld < 0 is lockless */
  38067. }
  38068. }
  38069. return rc;
  38070. }
  38071. /*
  38072. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  38073. ** must be either NO_LOCK or SHARED_LOCK.
  38074. **
  38075. ** If the locking level of the file descriptor is already at or below
  38076. ** the requested locking level, this routine is a no-op.
  38077. */
  38078. static int proxyUnlock(sqlite3_file *id, int eFileLock) {
  38079. unixFile *pFile = (unixFile*)id;
  38080. int rc = proxyTakeConch(pFile);
  38081. if( rc==SQLITE_OK ){
  38082. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  38083. if( pCtx->conchHeld>0 ){
  38084. unixFile *proxy = pCtx->lockProxy;
  38085. rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
  38086. pFile->eFileLock = proxy->eFileLock;
  38087. }else{
  38088. /* conchHeld < 0 is lockless */
  38089. }
  38090. }
  38091. return rc;
  38092. }
  38093. /*
  38094. ** Close a file that uses proxy locks.
  38095. */
  38096. static int proxyClose(sqlite3_file *id) {
  38097. if( ALWAYS(id) ){
  38098. unixFile *pFile = (unixFile*)id;
  38099. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  38100. unixFile *lockProxy = pCtx->lockProxy;
  38101. unixFile *conchFile = pCtx->conchFile;
  38102. int rc = SQLITE_OK;
  38103. if( lockProxy ){
  38104. rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
  38105. if( rc ) return rc;
  38106. rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
  38107. if( rc ) return rc;
  38108. sqlite3_free(lockProxy);
  38109. pCtx->lockProxy = 0;
  38110. }
  38111. if( conchFile ){
  38112. if( pCtx->conchHeld ){
  38113. rc = proxyReleaseConch(pFile);
  38114. if( rc ) return rc;
  38115. }
  38116. rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
  38117. if( rc ) return rc;
  38118. sqlite3_free(conchFile);
  38119. }
  38120. sqlite3DbFree(0, pCtx->lockProxyPath);
  38121. sqlite3_free(pCtx->conchFilePath);
  38122. sqlite3DbFree(0, pCtx->dbPath);
  38123. /* restore the original locking context and pMethod then close it */
  38124. pFile->lockingContext = pCtx->oldLockingContext;
  38125. pFile->pMethod = pCtx->pOldMethod;
  38126. sqlite3_free(pCtx);
  38127. return pFile->pMethod->xClose(id);
  38128. }
  38129. return SQLITE_OK;
  38130. }
  38131. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  38132. /*
  38133. ** The proxy locking style is intended for use with AFP filesystems.
  38134. ** And since AFP is only supported on MacOSX, the proxy locking is also
  38135. ** restricted to MacOSX.
  38136. **
  38137. **
  38138. ******************* End of the proxy lock implementation **********************
  38139. ******************************************************************************/
  38140. /*
  38141. ** Initialize the operating system interface.
  38142. **
  38143. ** This routine registers all VFS implementations for unix-like operating
  38144. ** systems. This routine, and the sqlite3_os_end() routine that follows,
  38145. ** should be the only routines in this file that are visible from other
  38146. ** files.
  38147. **
  38148. ** This routine is called once during SQLite initialization and by a
  38149. ** single thread. The memory allocation and mutex subsystems have not
  38150. ** necessarily been initialized when this routine is called, and so they
  38151. ** should not be used.
  38152. */
  38153. SQLITE_API int sqlite3_os_init(void){
  38154. /*
  38155. ** The following macro defines an initializer for an sqlite3_vfs object.
  38156. ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
  38157. ** to the "finder" function. (pAppData is a pointer to a pointer because
  38158. ** silly C90 rules prohibit a void* from being cast to a function pointer
  38159. ** and so we have to go through the intermediate pointer to avoid problems
  38160. ** when compiling with -pedantic-errors on GCC.)
  38161. **
  38162. ** The FINDER parameter to this macro is the name of the pointer to the
  38163. ** finder-function. The finder-function returns a pointer to the
  38164. ** sqlite_io_methods object that implements the desired locking
  38165. ** behaviors. See the division above that contains the IOMETHODS
  38166. ** macro for addition information on finder-functions.
  38167. **
  38168. ** Most finders simply return a pointer to a fixed sqlite3_io_methods
  38169. ** object. But the "autolockIoFinder" available on MacOSX does a little
  38170. ** more than that; it looks at the filesystem type that hosts the
  38171. ** database file and tries to choose an locking method appropriate for
  38172. ** that filesystem time.
  38173. */
  38174. #define UNIXVFS(VFSNAME, FINDER) { \
  38175. 3, /* iVersion */ \
  38176. sizeof(unixFile), /* szOsFile */ \
  38177. MAX_PATHNAME, /* mxPathname */ \
  38178. 0, /* pNext */ \
  38179. VFSNAME, /* zName */ \
  38180. (void*)&FINDER, /* pAppData */ \
  38181. unixOpen, /* xOpen */ \
  38182. unixDelete, /* xDelete */ \
  38183. unixAccess, /* xAccess */ \
  38184. unixFullPathname, /* xFullPathname */ \
  38185. unixDlOpen, /* xDlOpen */ \
  38186. unixDlError, /* xDlError */ \
  38187. unixDlSym, /* xDlSym */ \
  38188. unixDlClose, /* xDlClose */ \
  38189. unixRandomness, /* xRandomness */ \
  38190. unixSleep, /* xSleep */ \
  38191. unixCurrentTime, /* xCurrentTime */ \
  38192. unixGetLastError, /* xGetLastError */ \
  38193. unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
  38194. unixSetSystemCall, /* xSetSystemCall */ \
  38195. unixGetSystemCall, /* xGetSystemCall */ \
  38196. unixNextSystemCall, /* xNextSystemCall */ \
  38197. }
  38198. /*
  38199. ** All default VFSes for unix are contained in the following array.
  38200. **
  38201. ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
  38202. ** by the SQLite core when the VFS is registered. So the following
  38203. ** array cannot be const.
  38204. */
  38205. static sqlite3_vfs aVfs[] = {
  38206. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  38207. UNIXVFS("unix", autolockIoFinder ),
  38208. #elif OS_VXWORKS
  38209. UNIXVFS("unix", vxworksIoFinder ),
  38210. #else
  38211. UNIXVFS("unix", posixIoFinder ),
  38212. #endif
  38213. UNIXVFS("unix-none", nolockIoFinder ),
  38214. UNIXVFS("unix-dotfile", dotlockIoFinder ),
  38215. UNIXVFS("unix-excl", posixIoFinder ),
  38216. #if OS_VXWORKS
  38217. UNIXVFS("unix-namedsem", semIoFinder ),
  38218. #endif
  38219. #if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
  38220. UNIXVFS("unix-posix", posixIoFinder ),
  38221. #endif
  38222. #if SQLITE_ENABLE_LOCKING_STYLE
  38223. UNIXVFS("unix-flock", flockIoFinder ),
  38224. #endif
  38225. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  38226. UNIXVFS("unix-afp", afpIoFinder ),
  38227. UNIXVFS("unix-nfs", nfsIoFinder ),
  38228. UNIXVFS("unix-proxy", proxyIoFinder ),
  38229. #endif
  38230. };
  38231. unsigned int i; /* Loop counter */
  38232. /* Double-check that the aSyscall[] array has been constructed
  38233. ** correctly. See ticket [bb3a86e890c8e96ab] */
  38234. assert( ArraySize(aSyscall)==29 );
  38235. /* Register all VFSes defined in the aVfs[] array */
  38236. for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
  38237. sqlite3_vfs_register(&aVfs[i], i==0);
  38238. }
  38239. unixBigLock = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1);
  38240. return SQLITE_OK;
  38241. }
  38242. /*
  38243. ** Shutdown the operating system interface.
  38244. **
  38245. ** Some operating systems might need to do some cleanup in this routine,
  38246. ** to release dynamically allocated objects. But not on unix.
  38247. ** This routine is a no-op for unix.
  38248. */
  38249. SQLITE_API int sqlite3_os_end(void){
  38250. unixBigLock = 0;
  38251. return SQLITE_OK;
  38252. }
  38253. #endif /* SQLITE_OS_UNIX */
  38254. /************** End of os_unix.c *********************************************/
  38255. /************** Begin file os_win.c ******************************************/
  38256. /*
  38257. ** 2004 May 22
  38258. **
  38259. ** The author disclaims copyright to this source code. In place of
  38260. ** a legal notice, here is a blessing:
  38261. **
  38262. ** May you do good and not evil.
  38263. ** May you find forgiveness for yourself and forgive others.
  38264. ** May you share freely, never taking more than you give.
  38265. **
  38266. ******************************************************************************
  38267. **
  38268. ** This file contains code that is specific to Windows.
  38269. */
  38270. /* #include "sqliteInt.h" */
  38271. #if SQLITE_OS_WIN /* This file is used for Windows only */
  38272. /*
  38273. ** Include code that is common to all os_*.c files
  38274. */
  38275. /************** Include os_common.h in the middle of os_win.c ****************/
  38276. /************** Begin file os_common.h ***************************************/
  38277. /*
  38278. ** 2004 May 22
  38279. **
  38280. ** The author disclaims copyright to this source code. In place of
  38281. ** a legal notice, here is a blessing:
  38282. **
  38283. ** May you do good and not evil.
  38284. ** May you find forgiveness for yourself and forgive others.
  38285. ** May you share freely, never taking more than you give.
  38286. **
  38287. ******************************************************************************
  38288. **
  38289. ** This file contains macros and a little bit of code that is common to
  38290. ** all of the platform-specific files (os_*.c) and is #included into those
  38291. ** files.
  38292. **
  38293. ** This file should be #included by the os_*.c files only. It is not a
  38294. ** general purpose header file.
  38295. */
  38296. #ifndef _OS_COMMON_H_
  38297. #define _OS_COMMON_H_
  38298. /*
  38299. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  38300. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  38301. ** switch. The following code should catch this problem at compile-time.
  38302. */
  38303. #ifdef MEMORY_DEBUG
  38304. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  38305. #endif
  38306. /*
  38307. ** Macros for performance tracing. Normally turned off. Only works
  38308. ** on i486 hardware.
  38309. */
  38310. #ifdef SQLITE_PERFORMANCE_TRACE
  38311. /*
  38312. ** hwtime.h contains inline assembler code for implementing
  38313. ** high-performance timing routines.
  38314. */
  38315. /************** Include hwtime.h in the middle of os_common.h ****************/
  38316. /************** Begin file hwtime.h ******************************************/
  38317. /*
  38318. ** 2008 May 27
  38319. **
  38320. ** The author disclaims copyright to this source code. In place of
  38321. ** a legal notice, here is a blessing:
  38322. **
  38323. ** May you do good and not evil.
  38324. ** May you find forgiveness for yourself and forgive others.
  38325. ** May you share freely, never taking more than you give.
  38326. **
  38327. ******************************************************************************
  38328. **
  38329. ** This file contains inline asm code for retrieving "high-performance"
  38330. ** counters for x86 class CPUs.
  38331. */
  38332. #ifndef SQLITE_HWTIME_H
  38333. #define SQLITE_HWTIME_H
  38334. /*
  38335. ** The following routine only works on pentium-class (or newer) processors.
  38336. ** It uses the RDTSC opcode to read the cycle count value out of the
  38337. ** processor and returns that value. This can be used for high-res
  38338. ** profiling.
  38339. */
  38340. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  38341. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  38342. #if defined(__GNUC__)
  38343. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  38344. unsigned int lo, hi;
  38345. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  38346. return (sqlite_uint64)hi << 32 | lo;
  38347. }
  38348. #elif defined(_MSC_VER)
  38349. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  38350. __asm {
  38351. rdtsc
  38352. ret ; return value at EDX:EAX
  38353. }
  38354. }
  38355. #endif
  38356. #elif (defined(__GNUC__) && defined(__x86_64__))
  38357. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  38358. unsigned long val;
  38359. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  38360. return val;
  38361. }
  38362. #elif (defined(__GNUC__) && defined(__ppc__))
  38363. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  38364. unsigned long long retval;
  38365. unsigned long junk;
  38366. __asm__ __volatile__ ("\n\
  38367. 1: mftbu %1\n\
  38368. mftb %L0\n\
  38369. mftbu %0\n\
  38370. cmpw %0,%1\n\
  38371. bne 1b"
  38372. : "=r" (retval), "=r" (junk));
  38373. return retval;
  38374. }
  38375. #else
  38376. #error Need implementation of sqlite3Hwtime() for your platform.
  38377. /*
  38378. ** To compile without implementing sqlite3Hwtime() for your platform,
  38379. ** you can remove the above #error and use the following
  38380. ** stub function. You will lose timing support for many
  38381. ** of the debugging and testing utilities, but it should at
  38382. ** least compile and run.
  38383. */
  38384. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  38385. #endif
  38386. #endif /* !defined(SQLITE_HWTIME_H) */
  38387. /************** End of hwtime.h **********************************************/
  38388. /************** Continuing where we left off in os_common.h ******************/
  38389. static sqlite_uint64 g_start;
  38390. static sqlite_uint64 g_elapsed;
  38391. #define TIMER_START g_start=sqlite3Hwtime()
  38392. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  38393. #define TIMER_ELAPSED g_elapsed
  38394. #else
  38395. #define TIMER_START
  38396. #define TIMER_END
  38397. #define TIMER_ELAPSED ((sqlite_uint64)0)
  38398. #endif
  38399. /*
  38400. ** If we compile with the SQLITE_TEST macro set, then the following block
  38401. ** of code will give us the ability to simulate a disk I/O error. This
  38402. ** is used for testing the I/O recovery logic.
  38403. */
  38404. #if defined(SQLITE_TEST)
  38405. SQLITE_API extern int sqlite3_io_error_hit;
  38406. SQLITE_API extern int sqlite3_io_error_hardhit;
  38407. SQLITE_API extern int sqlite3_io_error_pending;
  38408. SQLITE_API extern int sqlite3_io_error_persist;
  38409. SQLITE_API extern int sqlite3_io_error_benign;
  38410. SQLITE_API extern int sqlite3_diskfull_pending;
  38411. SQLITE_API extern int sqlite3_diskfull;
  38412. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  38413. #define SimulateIOError(CODE) \
  38414. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  38415. || sqlite3_io_error_pending-- == 1 ) \
  38416. { local_ioerr(); CODE; }
  38417. static void local_ioerr(){
  38418. IOTRACE(("IOERR\n"));
  38419. sqlite3_io_error_hit++;
  38420. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  38421. }
  38422. #define SimulateDiskfullError(CODE) \
  38423. if( sqlite3_diskfull_pending ){ \
  38424. if( sqlite3_diskfull_pending == 1 ){ \
  38425. local_ioerr(); \
  38426. sqlite3_diskfull = 1; \
  38427. sqlite3_io_error_hit = 1; \
  38428. CODE; \
  38429. }else{ \
  38430. sqlite3_diskfull_pending--; \
  38431. } \
  38432. }
  38433. #else
  38434. #define SimulateIOErrorBenign(X)
  38435. #define SimulateIOError(A)
  38436. #define SimulateDiskfullError(A)
  38437. #endif /* defined(SQLITE_TEST) */
  38438. /*
  38439. ** When testing, keep a count of the number of open files.
  38440. */
  38441. #if defined(SQLITE_TEST)
  38442. SQLITE_API extern int sqlite3_open_file_count;
  38443. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  38444. #else
  38445. #define OpenCounter(X)
  38446. #endif /* defined(SQLITE_TEST) */
  38447. #endif /* !defined(_OS_COMMON_H_) */
  38448. /************** End of os_common.h *******************************************/
  38449. /************** Continuing where we left off in os_win.c *********************/
  38450. /*
  38451. ** Include the header file for the Windows VFS.
  38452. */
  38453. /* #include "os_win.h" */
  38454. /*
  38455. ** Compiling and using WAL mode requires several APIs that are only
  38456. ** available in Windows platforms based on the NT kernel.
  38457. */
  38458. #if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL)
  38459. # error "WAL mode requires support from the Windows NT kernel, compile\
  38460. with SQLITE_OMIT_WAL."
  38461. #endif
  38462. #if !SQLITE_OS_WINNT && SQLITE_MAX_MMAP_SIZE>0
  38463. # error "Memory mapped files require support from the Windows NT kernel,\
  38464. compile with SQLITE_MAX_MMAP_SIZE=0."
  38465. #endif
  38466. /*
  38467. ** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions
  38468. ** based on the sub-platform)?
  38469. */
  38470. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(SQLITE_WIN32_NO_ANSI)
  38471. # define SQLITE_WIN32_HAS_ANSI
  38472. #endif
  38473. /*
  38474. ** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions
  38475. ** based on the sub-platform)?
  38476. */
  38477. #if (SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT) && \
  38478. !defined(SQLITE_WIN32_NO_WIDE)
  38479. # define SQLITE_WIN32_HAS_WIDE
  38480. #endif
  38481. /*
  38482. ** Make sure at least one set of Win32 APIs is available.
  38483. */
  38484. #if !defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_WIN32_HAS_WIDE)
  38485. # error "At least one of SQLITE_WIN32_HAS_ANSI and SQLITE_WIN32_HAS_WIDE\
  38486. must be defined."
  38487. #endif
  38488. /*
  38489. ** Define the required Windows SDK version constants if they are not
  38490. ** already available.
  38491. */
  38492. #ifndef NTDDI_WIN8
  38493. # define NTDDI_WIN8 0x06020000
  38494. #endif
  38495. #ifndef NTDDI_WINBLUE
  38496. # define NTDDI_WINBLUE 0x06030000
  38497. #endif
  38498. #ifndef NTDDI_WINTHRESHOLD
  38499. # define NTDDI_WINTHRESHOLD 0x06040000
  38500. #endif
  38501. /*
  38502. ** Check to see if the GetVersionEx[AW] functions are deprecated on the
  38503. ** target system. GetVersionEx was first deprecated in Win8.1.
  38504. */
  38505. #ifndef SQLITE_WIN32_GETVERSIONEX
  38506. # if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINBLUE
  38507. # define SQLITE_WIN32_GETVERSIONEX 0 /* GetVersionEx() is deprecated */
  38508. # else
  38509. # define SQLITE_WIN32_GETVERSIONEX 1 /* GetVersionEx() is current */
  38510. # endif
  38511. #endif
  38512. /*
  38513. ** Check to see if the CreateFileMappingA function is supported on the
  38514. ** target system. It is unavailable when using "mincore.lib" on Win10.
  38515. ** When compiling for Windows 10, always assume "mincore.lib" is in use.
  38516. */
  38517. #ifndef SQLITE_WIN32_CREATEFILEMAPPINGA
  38518. # if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINTHRESHOLD
  38519. # define SQLITE_WIN32_CREATEFILEMAPPINGA 0
  38520. # else
  38521. # define SQLITE_WIN32_CREATEFILEMAPPINGA 1
  38522. # endif
  38523. #endif
  38524. /*
  38525. ** This constant should already be defined (in the "WinDef.h" SDK file).
  38526. */
  38527. #ifndef MAX_PATH
  38528. # define MAX_PATH (260)
  38529. #endif
  38530. /*
  38531. ** Maximum pathname length (in chars) for Win32. This should normally be
  38532. ** MAX_PATH.
  38533. */
  38534. #ifndef SQLITE_WIN32_MAX_PATH_CHARS
  38535. # define SQLITE_WIN32_MAX_PATH_CHARS (MAX_PATH)
  38536. #endif
  38537. /*
  38538. ** This constant should already be defined (in the "WinNT.h" SDK file).
  38539. */
  38540. #ifndef UNICODE_STRING_MAX_CHARS
  38541. # define UNICODE_STRING_MAX_CHARS (32767)
  38542. #endif
  38543. /*
  38544. ** Maximum pathname length (in chars) for WinNT. This should normally be
  38545. ** UNICODE_STRING_MAX_CHARS.
  38546. */
  38547. #ifndef SQLITE_WINNT_MAX_PATH_CHARS
  38548. # define SQLITE_WINNT_MAX_PATH_CHARS (UNICODE_STRING_MAX_CHARS)
  38549. #endif
  38550. /*
  38551. ** Maximum pathname length (in bytes) for Win32. The MAX_PATH macro is in
  38552. ** characters, so we allocate 4 bytes per character assuming worst-case of
  38553. ** 4-bytes-per-character for UTF8.
  38554. */
  38555. #ifndef SQLITE_WIN32_MAX_PATH_BYTES
  38556. # define SQLITE_WIN32_MAX_PATH_BYTES (SQLITE_WIN32_MAX_PATH_CHARS*4)
  38557. #endif
  38558. /*
  38559. ** Maximum pathname length (in bytes) for WinNT. This should normally be
  38560. ** UNICODE_STRING_MAX_CHARS * sizeof(WCHAR).
  38561. */
  38562. #ifndef SQLITE_WINNT_MAX_PATH_BYTES
  38563. # define SQLITE_WINNT_MAX_PATH_BYTES \
  38564. (sizeof(WCHAR) * SQLITE_WINNT_MAX_PATH_CHARS)
  38565. #endif
  38566. /*
  38567. ** Maximum error message length (in chars) for WinRT.
  38568. */
  38569. #ifndef SQLITE_WIN32_MAX_ERRMSG_CHARS
  38570. # define SQLITE_WIN32_MAX_ERRMSG_CHARS (1024)
  38571. #endif
  38572. /*
  38573. ** Returns non-zero if the character should be treated as a directory
  38574. ** separator.
  38575. */
  38576. #ifndef winIsDirSep
  38577. # define winIsDirSep(a) (((a) == '/') || ((a) == '\\'))
  38578. #endif
  38579. /*
  38580. ** This macro is used when a local variable is set to a value that is
  38581. ** [sometimes] not used by the code (e.g. via conditional compilation).
  38582. */
  38583. #ifndef UNUSED_VARIABLE_VALUE
  38584. # define UNUSED_VARIABLE_VALUE(x) (void)(x)
  38585. #endif
  38586. /*
  38587. ** Returns the character that should be used as the directory separator.
  38588. */
  38589. #ifndef winGetDirSep
  38590. # define winGetDirSep() '\\'
  38591. #endif
  38592. /*
  38593. ** Do we need to manually define the Win32 file mapping APIs for use with WAL
  38594. ** mode or memory mapped files (e.g. these APIs are available in the Windows
  38595. ** CE SDK; however, they are not present in the header file)?
  38596. */
  38597. #if SQLITE_WIN32_FILEMAPPING_API && \
  38598. (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
  38599. /*
  38600. ** Two of the file mapping APIs are different under WinRT. Figure out which
  38601. ** set we need.
  38602. */
  38603. #if SQLITE_OS_WINRT
  38604. WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \
  38605. LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR);
  38606. WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T);
  38607. #else
  38608. #if defined(SQLITE_WIN32_HAS_ANSI)
  38609. WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \
  38610. DWORD, DWORD, DWORD, LPCSTR);
  38611. #endif /* defined(SQLITE_WIN32_HAS_ANSI) */
  38612. #if defined(SQLITE_WIN32_HAS_WIDE)
  38613. WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \
  38614. DWORD, DWORD, DWORD, LPCWSTR);
  38615. #endif /* defined(SQLITE_WIN32_HAS_WIDE) */
  38616. WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T);
  38617. #endif /* SQLITE_OS_WINRT */
  38618. /*
  38619. ** These file mapping APIs are common to both Win32 and WinRT.
  38620. */
  38621. WINBASEAPI BOOL WINAPI FlushViewOfFile(LPCVOID, SIZE_T);
  38622. WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
  38623. #endif /* SQLITE_WIN32_FILEMAPPING_API */
  38624. /*
  38625. ** Some Microsoft compilers lack this definition.
  38626. */
  38627. #ifndef INVALID_FILE_ATTRIBUTES
  38628. # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
  38629. #endif
  38630. #ifndef FILE_FLAG_MASK
  38631. # define FILE_FLAG_MASK (0xFF3C0000)
  38632. #endif
  38633. #ifndef FILE_ATTRIBUTE_MASK
  38634. # define FILE_ATTRIBUTE_MASK (0x0003FFF7)
  38635. #endif
  38636. #ifndef SQLITE_OMIT_WAL
  38637. /* Forward references to structures used for WAL */
  38638. typedef struct winShm winShm; /* A connection to shared-memory */
  38639. typedef struct winShmNode winShmNode; /* A region of shared-memory */
  38640. #endif
  38641. /*
  38642. ** WinCE lacks native support for file locking so we have to fake it
  38643. ** with some code of our own.
  38644. */
  38645. #if SQLITE_OS_WINCE
  38646. typedef struct winceLock {
  38647. int nReaders; /* Number of reader locks obtained */
  38648. BOOL bPending; /* Indicates a pending lock has been obtained */
  38649. BOOL bReserved; /* Indicates a reserved lock has been obtained */
  38650. BOOL bExclusive; /* Indicates an exclusive lock has been obtained */
  38651. } winceLock;
  38652. #endif
  38653. /*
  38654. ** The winFile structure is a subclass of sqlite3_file* specific to the win32
  38655. ** portability layer.
  38656. */
  38657. typedef struct winFile winFile;
  38658. struct winFile {
  38659. const sqlite3_io_methods *pMethod; /*** Must be first ***/
  38660. sqlite3_vfs *pVfs; /* The VFS used to open this file */
  38661. HANDLE h; /* Handle for accessing the file */
  38662. u8 locktype; /* Type of lock currently held on this file */
  38663. short sharedLockByte; /* Randomly chosen byte used as a shared lock */
  38664. u8 ctrlFlags; /* Flags. See WINFILE_* below */
  38665. DWORD lastErrno; /* The Windows errno from the last I/O error */
  38666. #ifndef SQLITE_OMIT_WAL
  38667. winShm *pShm; /* Instance of shared memory on this file */
  38668. #endif
  38669. const char *zPath; /* Full pathname of this file */
  38670. int szChunk; /* Chunk size configured by FCNTL_CHUNK_SIZE */
  38671. #if SQLITE_OS_WINCE
  38672. LPWSTR zDeleteOnClose; /* Name of file to delete when closing */
  38673. HANDLE hMutex; /* Mutex used to control access to shared lock */
  38674. HANDLE hShared; /* Shared memory segment used for locking */
  38675. winceLock local; /* Locks obtained by this instance of winFile */
  38676. winceLock *shared; /* Global shared lock memory for the file */
  38677. #endif
  38678. #if SQLITE_MAX_MMAP_SIZE>0
  38679. int nFetchOut; /* Number of outstanding xFetch references */
  38680. HANDLE hMap; /* Handle for accessing memory mapping */
  38681. void *pMapRegion; /* Area memory mapped */
  38682. sqlite3_int64 mmapSize; /* Size of mapped region */
  38683. sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
  38684. #endif
  38685. };
  38686. /*
  38687. ** The winVfsAppData structure is used for the pAppData member for all of the
  38688. ** Win32 VFS variants.
  38689. */
  38690. typedef struct winVfsAppData winVfsAppData;
  38691. struct winVfsAppData {
  38692. const sqlite3_io_methods *pMethod; /* The file I/O methods to use. */
  38693. void *pAppData; /* The extra pAppData, if any. */
  38694. BOOL bNoLock; /* Non-zero if locking is disabled. */
  38695. };
  38696. /*
  38697. ** Allowed values for winFile.ctrlFlags
  38698. */
  38699. #define WINFILE_RDONLY 0x02 /* Connection is read only */
  38700. #define WINFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
  38701. #define WINFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
  38702. /*
  38703. * The size of the buffer used by sqlite3_win32_write_debug().
  38704. */
  38705. #ifndef SQLITE_WIN32_DBG_BUF_SIZE
  38706. # define SQLITE_WIN32_DBG_BUF_SIZE ((int)(4096-sizeof(DWORD)))
  38707. #endif
  38708. /*
  38709. * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
  38710. * various Win32 API heap functions instead of our own.
  38711. */
  38712. #ifdef SQLITE_WIN32_MALLOC
  38713. /*
  38714. * If this is non-zero, an isolated heap will be created by the native Win32
  38715. * allocator subsystem; otherwise, the default process heap will be used. This
  38716. * setting has no effect when compiling for WinRT. By default, this is enabled
  38717. * and an isolated heap will be created to store all allocated data.
  38718. *
  38719. ******************************************************************************
  38720. * WARNING: It is important to note that when this setting is non-zero and the
  38721. * winMemShutdown function is called (e.g. by the sqlite3_shutdown
  38722. * function), all data that was allocated using the isolated heap will
  38723. * be freed immediately and any attempt to access any of that freed
  38724. * data will almost certainly result in an immediate access violation.
  38725. ******************************************************************************
  38726. */
  38727. #ifndef SQLITE_WIN32_HEAP_CREATE
  38728. # define SQLITE_WIN32_HEAP_CREATE (TRUE)
  38729. #endif
  38730. /*
  38731. * This is the maximum possible initial size of the Win32-specific heap, in
  38732. * bytes.
  38733. */
  38734. #ifndef SQLITE_WIN32_HEAP_MAX_INIT_SIZE
  38735. # define SQLITE_WIN32_HEAP_MAX_INIT_SIZE (4294967295U)
  38736. #endif
  38737. /*
  38738. * This is the extra space for the initial size of the Win32-specific heap,
  38739. * in bytes. This value may be zero.
  38740. */
  38741. #ifndef SQLITE_WIN32_HEAP_INIT_EXTRA
  38742. # define SQLITE_WIN32_HEAP_INIT_EXTRA (4194304)
  38743. #endif
  38744. /*
  38745. * Calculate the maximum legal cache size, in pages, based on the maximum
  38746. * possible initial heap size and the default page size, setting aside the
  38747. * needed extra space.
  38748. */
  38749. #ifndef SQLITE_WIN32_MAX_CACHE_SIZE
  38750. # define SQLITE_WIN32_MAX_CACHE_SIZE (((SQLITE_WIN32_HEAP_MAX_INIT_SIZE) - \
  38751. (SQLITE_WIN32_HEAP_INIT_EXTRA)) / \
  38752. (SQLITE_DEFAULT_PAGE_SIZE))
  38753. #endif
  38754. /*
  38755. * This is cache size used in the calculation of the initial size of the
  38756. * Win32-specific heap. It cannot be negative.
  38757. */
  38758. #ifndef SQLITE_WIN32_CACHE_SIZE
  38759. # if SQLITE_DEFAULT_CACHE_SIZE>=0
  38760. # define SQLITE_WIN32_CACHE_SIZE (SQLITE_DEFAULT_CACHE_SIZE)
  38761. # else
  38762. # define SQLITE_WIN32_CACHE_SIZE (-(SQLITE_DEFAULT_CACHE_SIZE))
  38763. # endif
  38764. #endif
  38765. /*
  38766. * Make sure that the calculated cache size, in pages, cannot cause the
  38767. * initial size of the Win32-specific heap to exceed the maximum amount
  38768. * of memory that can be specified in the call to HeapCreate.
  38769. */
  38770. #if SQLITE_WIN32_CACHE_SIZE>SQLITE_WIN32_MAX_CACHE_SIZE
  38771. # undef SQLITE_WIN32_CACHE_SIZE
  38772. # define SQLITE_WIN32_CACHE_SIZE (2000)
  38773. #endif
  38774. /*
  38775. * The initial size of the Win32-specific heap. This value may be zero.
  38776. */
  38777. #ifndef SQLITE_WIN32_HEAP_INIT_SIZE
  38778. # define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_WIN32_CACHE_SIZE) * \
  38779. (SQLITE_DEFAULT_PAGE_SIZE) + \
  38780. (SQLITE_WIN32_HEAP_INIT_EXTRA))
  38781. #endif
  38782. /*
  38783. * The maximum size of the Win32-specific heap. This value may be zero.
  38784. */
  38785. #ifndef SQLITE_WIN32_HEAP_MAX_SIZE
  38786. # define SQLITE_WIN32_HEAP_MAX_SIZE (0)
  38787. #endif
  38788. /*
  38789. * The extra flags to use in calls to the Win32 heap APIs. This value may be
  38790. * zero for the default behavior.
  38791. */
  38792. #ifndef SQLITE_WIN32_HEAP_FLAGS
  38793. # define SQLITE_WIN32_HEAP_FLAGS (0)
  38794. #endif
  38795. /*
  38796. ** The winMemData structure stores information required by the Win32-specific
  38797. ** sqlite3_mem_methods implementation.
  38798. */
  38799. typedef struct winMemData winMemData;
  38800. struct winMemData {
  38801. #ifndef NDEBUG
  38802. u32 magic1; /* Magic number to detect structure corruption. */
  38803. #endif
  38804. HANDLE hHeap; /* The handle to our heap. */
  38805. BOOL bOwned; /* Do we own the heap (i.e. destroy it on shutdown)? */
  38806. #ifndef NDEBUG
  38807. u32 magic2; /* Magic number to detect structure corruption. */
  38808. #endif
  38809. };
  38810. #ifndef NDEBUG
  38811. #define WINMEM_MAGIC1 0x42b2830b
  38812. #define WINMEM_MAGIC2 0xbd4d7cf4
  38813. #endif
  38814. static struct winMemData win_mem_data = {
  38815. #ifndef NDEBUG
  38816. WINMEM_MAGIC1,
  38817. #endif
  38818. NULL, FALSE
  38819. #ifndef NDEBUG
  38820. ,WINMEM_MAGIC2
  38821. #endif
  38822. };
  38823. #ifndef NDEBUG
  38824. #define winMemAssertMagic1() assert( win_mem_data.magic1==WINMEM_MAGIC1 )
  38825. #define winMemAssertMagic2() assert( win_mem_data.magic2==WINMEM_MAGIC2 )
  38826. #define winMemAssertMagic() winMemAssertMagic1(); winMemAssertMagic2();
  38827. #else
  38828. #define winMemAssertMagic()
  38829. #endif
  38830. #define winMemGetDataPtr() &win_mem_data
  38831. #define winMemGetHeap() win_mem_data.hHeap
  38832. #define winMemGetOwned() win_mem_data.bOwned
  38833. static void *winMemMalloc(int nBytes);
  38834. static void winMemFree(void *pPrior);
  38835. static void *winMemRealloc(void *pPrior, int nBytes);
  38836. static int winMemSize(void *p);
  38837. static int winMemRoundup(int n);
  38838. static int winMemInit(void *pAppData);
  38839. static void winMemShutdown(void *pAppData);
  38840. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
  38841. #endif /* SQLITE_WIN32_MALLOC */
  38842. /*
  38843. ** The following variable is (normally) set once and never changes
  38844. ** thereafter. It records whether the operating system is Win9x
  38845. ** or WinNT.
  38846. **
  38847. ** 0: Operating system unknown.
  38848. ** 1: Operating system is Win9x.
  38849. ** 2: Operating system is WinNT.
  38850. **
  38851. ** In order to facilitate testing on a WinNT system, the test fixture
  38852. ** can manually set this value to 1 to emulate Win98 behavior.
  38853. */
  38854. #ifdef SQLITE_TEST
  38855. SQLITE_API LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
  38856. #else
  38857. static LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
  38858. #endif
  38859. #ifndef SYSCALL
  38860. # define SYSCALL sqlite3_syscall_ptr
  38861. #endif
  38862. /*
  38863. ** This function is not available on Windows CE or WinRT.
  38864. */
  38865. #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
  38866. # define osAreFileApisANSI() 1
  38867. #endif
  38868. /*
  38869. ** Many system calls are accessed through pointer-to-functions so that
  38870. ** they may be overridden at runtime to facilitate fault injection during
  38871. ** testing and sandboxing. The following array holds the names and pointers
  38872. ** to all overrideable system calls.
  38873. */
  38874. static struct win_syscall {
  38875. const char *zName; /* Name of the system call */
  38876. sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
  38877. sqlite3_syscall_ptr pDefault; /* Default value */
  38878. } aSyscall[] = {
  38879. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  38880. { "AreFileApisANSI", (SYSCALL)AreFileApisANSI, 0 },
  38881. #else
  38882. { "AreFileApisANSI", (SYSCALL)0, 0 },
  38883. #endif
  38884. #ifndef osAreFileApisANSI
  38885. #define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
  38886. #endif
  38887. #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
  38888. { "CharLowerW", (SYSCALL)CharLowerW, 0 },
  38889. #else
  38890. { "CharLowerW", (SYSCALL)0, 0 },
  38891. #endif
  38892. #define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
  38893. #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
  38894. { "CharUpperW", (SYSCALL)CharUpperW, 0 },
  38895. #else
  38896. { "CharUpperW", (SYSCALL)0, 0 },
  38897. #endif
  38898. #define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
  38899. { "CloseHandle", (SYSCALL)CloseHandle, 0 },
  38900. #define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
  38901. #if defined(SQLITE_WIN32_HAS_ANSI)
  38902. { "CreateFileA", (SYSCALL)CreateFileA, 0 },
  38903. #else
  38904. { "CreateFileA", (SYSCALL)0, 0 },
  38905. #endif
  38906. #define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
  38907. LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
  38908. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  38909. { "CreateFileW", (SYSCALL)CreateFileW, 0 },
  38910. #else
  38911. { "CreateFileW", (SYSCALL)0, 0 },
  38912. #endif
  38913. #define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
  38914. LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
  38915. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \
  38916. (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) && \
  38917. SQLITE_WIN32_CREATEFILEMAPPINGA
  38918. { "CreateFileMappingA", (SYSCALL)CreateFileMappingA, 0 },
  38919. #else
  38920. { "CreateFileMappingA", (SYSCALL)0, 0 },
  38921. #endif
  38922. #define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
  38923. DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent)
  38924. #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
  38925. (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
  38926. { "CreateFileMappingW", (SYSCALL)CreateFileMappingW, 0 },
  38927. #else
  38928. { "CreateFileMappingW", (SYSCALL)0, 0 },
  38929. #endif
  38930. #define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
  38931. DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
  38932. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  38933. { "CreateMutexW", (SYSCALL)CreateMutexW, 0 },
  38934. #else
  38935. { "CreateMutexW", (SYSCALL)0, 0 },
  38936. #endif
  38937. #define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
  38938. LPCWSTR))aSyscall[8].pCurrent)
  38939. #if defined(SQLITE_WIN32_HAS_ANSI)
  38940. { "DeleteFileA", (SYSCALL)DeleteFileA, 0 },
  38941. #else
  38942. { "DeleteFileA", (SYSCALL)0, 0 },
  38943. #endif
  38944. #define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
  38945. #if defined(SQLITE_WIN32_HAS_WIDE)
  38946. { "DeleteFileW", (SYSCALL)DeleteFileW, 0 },
  38947. #else
  38948. { "DeleteFileW", (SYSCALL)0, 0 },
  38949. #endif
  38950. #define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
  38951. #if SQLITE_OS_WINCE
  38952. { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
  38953. #else
  38954. { "FileTimeToLocalFileTime", (SYSCALL)0, 0 },
  38955. #endif
  38956. #define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
  38957. LPFILETIME))aSyscall[11].pCurrent)
  38958. #if SQLITE_OS_WINCE
  38959. { "FileTimeToSystemTime", (SYSCALL)FileTimeToSystemTime, 0 },
  38960. #else
  38961. { "FileTimeToSystemTime", (SYSCALL)0, 0 },
  38962. #endif
  38963. #define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
  38964. LPSYSTEMTIME))aSyscall[12].pCurrent)
  38965. { "FlushFileBuffers", (SYSCALL)FlushFileBuffers, 0 },
  38966. #define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
  38967. #if defined(SQLITE_WIN32_HAS_ANSI)
  38968. { "FormatMessageA", (SYSCALL)FormatMessageA, 0 },
  38969. #else
  38970. { "FormatMessageA", (SYSCALL)0, 0 },
  38971. #endif
  38972. #define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
  38973. DWORD,va_list*))aSyscall[14].pCurrent)
  38974. #if defined(SQLITE_WIN32_HAS_WIDE)
  38975. { "FormatMessageW", (SYSCALL)FormatMessageW, 0 },
  38976. #else
  38977. { "FormatMessageW", (SYSCALL)0, 0 },
  38978. #endif
  38979. #define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
  38980. DWORD,va_list*))aSyscall[15].pCurrent)
  38981. #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
  38982. { "FreeLibrary", (SYSCALL)FreeLibrary, 0 },
  38983. #else
  38984. { "FreeLibrary", (SYSCALL)0, 0 },
  38985. #endif
  38986. #define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
  38987. { "GetCurrentProcessId", (SYSCALL)GetCurrentProcessId, 0 },
  38988. #define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
  38989. #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
  38990. { "GetDiskFreeSpaceA", (SYSCALL)GetDiskFreeSpaceA, 0 },
  38991. #else
  38992. { "GetDiskFreeSpaceA", (SYSCALL)0, 0 },
  38993. #endif
  38994. #define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
  38995. LPDWORD))aSyscall[18].pCurrent)
  38996. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  38997. { "GetDiskFreeSpaceW", (SYSCALL)GetDiskFreeSpaceW, 0 },
  38998. #else
  38999. { "GetDiskFreeSpaceW", (SYSCALL)0, 0 },
  39000. #endif
  39001. #define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
  39002. LPDWORD))aSyscall[19].pCurrent)
  39003. #if defined(SQLITE_WIN32_HAS_ANSI)
  39004. { "GetFileAttributesA", (SYSCALL)GetFileAttributesA, 0 },
  39005. #else
  39006. { "GetFileAttributesA", (SYSCALL)0, 0 },
  39007. #endif
  39008. #define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
  39009. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  39010. { "GetFileAttributesW", (SYSCALL)GetFileAttributesW, 0 },
  39011. #else
  39012. { "GetFileAttributesW", (SYSCALL)0, 0 },
  39013. #endif
  39014. #define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
  39015. #if defined(SQLITE_WIN32_HAS_WIDE)
  39016. { "GetFileAttributesExW", (SYSCALL)GetFileAttributesExW, 0 },
  39017. #else
  39018. { "GetFileAttributesExW", (SYSCALL)0, 0 },
  39019. #endif
  39020. #define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
  39021. LPVOID))aSyscall[22].pCurrent)
  39022. #if !SQLITE_OS_WINRT
  39023. { "GetFileSize", (SYSCALL)GetFileSize, 0 },
  39024. #else
  39025. { "GetFileSize", (SYSCALL)0, 0 },
  39026. #endif
  39027. #define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
  39028. #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
  39029. { "GetFullPathNameA", (SYSCALL)GetFullPathNameA, 0 },
  39030. #else
  39031. { "GetFullPathNameA", (SYSCALL)0, 0 },
  39032. #endif
  39033. #define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
  39034. LPSTR*))aSyscall[24].pCurrent)
  39035. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  39036. { "GetFullPathNameW", (SYSCALL)GetFullPathNameW, 0 },
  39037. #else
  39038. { "GetFullPathNameW", (SYSCALL)0, 0 },
  39039. #endif
  39040. #define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
  39041. LPWSTR*))aSyscall[25].pCurrent)
  39042. { "GetLastError", (SYSCALL)GetLastError, 0 },
  39043. #define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
  39044. #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
  39045. #if SQLITE_OS_WINCE
  39046. /* The GetProcAddressA() routine is only available on Windows CE. */
  39047. { "GetProcAddressA", (SYSCALL)GetProcAddressA, 0 },
  39048. #else
  39049. /* All other Windows platforms expect GetProcAddress() to take
  39050. ** an ANSI string regardless of the _UNICODE setting */
  39051. { "GetProcAddressA", (SYSCALL)GetProcAddress, 0 },
  39052. #endif
  39053. #else
  39054. { "GetProcAddressA", (SYSCALL)0, 0 },
  39055. #endif
  39056. #define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
  39057. LPCSTR))aSyscall[27].pCurrent)
  39058. #if !SQLITE_OS_WINRT
  39059. { "GetSystemInfo", (SYSCALL)GetSystemInfo, 0 },
  39060. #else
  39061. { "GetSystemInfo", (SYSCALL)0, 0 },
  39062. #endif
  39063. #define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
  39064. { "GetSystemTime", (SYSCALL)GetSystemTime, 0 },
  39065. #define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
  39066. #if !SQLITE_OS_WINCE
  39067. { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
  39068. #else
  39069. { "GetSystemTimeAsFileTime", (SYSCALL)0, 0 },
  39070. #endif
  39071. #define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
  39072. LPFILETIME))aSyscall[30].pCurrent)
  39073. #if defined(SQLITE_WIN32_HAS_ANSI)
  39074. { "GetTempPathA", (SYSCALL)GetTempPathA, 0 },
  39075. #else
  39076. { "GetTempPathA", (SYSCALL)0, 0 },
  39077. #endif
  39078. #define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
  39079. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  39080. { "GetTempPathW", (SYSCALL)GetTempPathW, 0 },
  39081. #else
  39082. { "GetTempPathW", (SYSCALL)0, 0 },
  39083. #endif
  39084. #define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
  39085. #if !SQLITE_OS_WINRT
  39086. { "GetTickCount", (SYSCALL)GetTickCount, 0 },
  39087. #else
  39088. { "GetTickCount", (SYSCALL)0, 0 },
  39089. #endif
  39090. #define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
  39091. #if defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_GETVERSIONEX
  39092. { "GetVersionExA", (SYSCALL)GetVersionExA, 0 },
  39093. #else
  39094. { "GetVersionExA", (SYSCALL)0, 0 },
  39095. #endif
  39096. #define osGetVersionExA ((BOOL(WINAPI*)( \
  39097. LPOSVERSIONINFOA))aSyscall[34].pCurrent)
  39098. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
  39099. SQLITE_WIN32_GETVERSIONEX
  39100. { "GetVersionExW", (SYSCALL)GetVersionExW, 0 },
  39101. #else
  39102. { "GetVersionExW", (SYSCALL)0, 0 },
  39103. #endif
  39104. #define osGetVersionExW ((BOOL(WINAPI*)( \
  39105. LPOSVERSIONINFOW))aSyscall[35].pCurrent)
  39106. { "HeapAlloc", (SYSCALL)HeapAlloc, 0 },
  39107. #define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
  39108. SIZE_T))aSyscall[36].pCurrent)
  39109. #if !SQLITE_OS_WINRT
  39110. { "HeapCreate", (SYSCALL)HeapCreate, 0 },
  39111. #else
  39112. { "HeapCreate", (SYSCALL)0, 0 },
  39113. #endif
  39114. #define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
  39115. SIZE_T))aSyscall[37].pCurrent)
  39116. #if !SQLITE_OS_WINRT
  39117. { "HeapDestroy", (SYSCALL)HeapDestroy, 0 },
  39118. #else
  39119. { "HeapDestroy", (SYSCALL)0, 0 },
  39120. #endif
  39121. #define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[38].pCurrent)
  39122. { "HeapFree", (SYSCALL)HeapFree, 0 },
  39123. #define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[39].pCurrent)
  39124. { "HeapReAlloc", (SYSCALL)HeapReAlloc, 0 },
  39125. #define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
  39126. SIZE_T))aSyscall[40].pCurrent)
  39127. { "HeapSize", (SYSCALL)HeapSize, 0 },
  39128. #define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
  39129. LPCVOID))aSyscall[41].pCurrent)
  39130. #if !SQLITE_OS_WINRT
  39131. { "HeapValidate", (SYSCALL)HeapValidate, 0 },
  39132. #else
  39133. { "HeapValidate", (SYSCALL)0, 0 },
  39134. #endif
  39135. #define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
  39136. LPCVOID))aSyscall[42].pCurrent)
  39137. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  39138. { "HeapCompact", (SYSCALL)HeapCompact, 0 },
  39139. #else
  39140. { "HeapCompact", (SYSCALL)0, 0 },
  39141. #endif
  39142. #define osHeapCompact ((UINT(WINAPI*)(HANDLE,DWORD))aSyscall[43].pCurrent)
  39143. #if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  39144. { "LoadLibraryA", (SYSCALL)LoadLibraryA, 0 },
  39145. #else
  39146. { "LoadLibraryA", (SYSCALL)0, 0 },
  39147. #endif
  39148. #define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[44].pCurrent)
  39149. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
  39150. !defined(SQLITE_OMIT_LOAD_EXTENSION)
  39151. { "LoadLibraryW", (SYSCALL)LoadLibraryW, 0 },
  39152. #else
  39153. { "LoadLibraryW", (SYSCALL)0, 0 },
  39154. #endif
  39155. #define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[45].pCurrent)
  39156. #if !SQLITE_OS_WINRT
  39157. { "LocalFree", (SYSCALL)LocalFree, 0 },
  39158. #else
  39159. { "LocalFree", (SYSCALL)0, 0 },
  39160. #endif
  39161. #define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[46].pCurrent)
  39162. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  39163. { "LockFile", (SYSCALL)LockFile, 0 },
  39164. #else
  39165. { "LockFile", (SYSCALL)0, 0 },
  39166. #endif
  39167. #ifndef osLockFile
  39168. #define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  39169. DWORD))aSyscall[47].pCurrent)
  39170. #endif
  39171. #if !SQLITE_OS_WINCE
  39172. { "LockFileEx", (SYSCALL)LockFileEx, 0 },
  39173. #else
  39174. { "LockFileEx", (SYSCALL)0, 0 },
  39175. #endif
  39176. #ifndef osLockFileEx
  39177. #define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
  39178. LPOVERLAPPED))aSyscall[48].pCurrent)
  39179. #endif
  39180. #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && \
  39181. (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
  39182. { "MapViewOfFile", (SYSCALL)MapViewOfFile, 0 },
  39183. #else
  39184. { "MapViewOfFile", (SYSCALL)0, 0 },
  39185. #endif
  39186. #define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  39187. SIZE_T))aSyscall[49].pCurrent)
  39188. { "MultiByteToWideChar", (SYSCALL)MultiByteToWideChar, 0 },
  39189. #define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
  39190. int))aSyscall[50].pCurrent)
  39191. { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
  39192. #define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
  39193. LARGE_INTEGER*))aSyscall[51].pCurrent)
  39194. { "ReadFile", (SYSCALL)ReadFile, 0 },
  39195. #define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
  39196. LPOVERLAPPED))aSyscall[52].pCurrent)
  39197. { "SetEndOfFile", (SYSCALL)SetEndOfFile, 0 },
  39198. #define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[53].pCurrent)
  39199. #if !SQLITE_OS_WINRT
  39200. { "SetFilePointer", (SYSCALL)SetFilePointer, 0 },
  39201. #else
  39202. { "SetFilePointer", (SYSCALL)0, 0 },
  39203. #endif
  39204. #define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
  39205. DWORD))aSyscall[54].pCurrent)
  39206. #if !SQLITE_OS_WINRT
  39207. { "Sleep", (SYSCALL)Sleep, 0 },
  39208. #else
  39209. { "Sleep", (SYSCALL)0, 0 },
  39210. #endif
  39211. #define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[55].pCurrent)
  39212. { "SystemTimeToFileTime", (SYSCALL)SystemTimeToFileTime, 0 },
  39213. #define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
  39214. LPFILETIME))aSyscall[56].pCurrent)
  39215. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  39216. { "UnlockFile", (SYSCALL)UnlockFile, 0 },
  39217. #else
  39218. { "UnlockFile", (SYSCALL)0, 0 },
  39219. #endif
  39220. #ifndef osUnlockFile
  39221. #define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  39222. DWORD))aSyscall[57].pCurrent)
  39223. #endif
  39224. #if !SQLITE_OS_WINCE
  39225. { "UnlockFileEx", (SYSCALL)UnlockFileEx, 0 },
  39226. #else
  39227. { "UnlockFileEx", (SYSCALL)0, 0 },
  39228. #endif
  39229. #define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  39230. LPOVERLAPPED))aSyscall[58].pCurrent)
  39231. #if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  39232. { "UnmapViewOfFile", (SYSCALL)UnmapViewOfFile, 0 },
  39233. #else
  39234. { "UnmapViewOfFile", (SYSCALL)0, 0 },
  39235. #endif
  39236. #define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[59].pCurrent)
  39237. { "WideCharToMultiByte", (SYSCALL)WideCharToMultiByte, 0 },
  39238. #define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
  39239. LPCSTR,LPBOOL))aSyscall[60].pCurrent)
  39240. { "WriteFile", (SYSCALL)WriteFile, 0 },
  39241. #define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
  39242. LPOVERLAPPED))aSyscall[61].pCurrent)
  39243. #if SQLITE_OS_WINRT
  39244. { "CreateEventExW", (SYSCALL)CreateEventExW, 0 },
  39245. #else
  39246. { "CreateEventExW", (SYSCALL)0, 0 },
  39247. #endif
  39248. #define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
  39249. DWORD,DWORD))aSyscall[62].pCurrent)
  39250. #if !SQLITE_OS_WINRT
  39251. { "WaitForSingleObject", (SYSCALL)WaitForSingleObject, 0 },
  39252. #else
  39253. { "WaitForSingleObject", (SYSCALL)0, 0 },
  39254. #endif
  39255. #define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
  39256. DWORD))aSyscall[63].pCurrent)
  39257. #if !SQLITE_OS_WINCE
  39258. { "WaitForSingleObjectEx", (SYSCALL)WaitForSingleObjectEx, 0 },
  39259. #else
  39260. { "WaitForSingleObjectEx", (SYSCALL)0, 0 },
  39261. #endif
  39262. #define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
  39263. BOOL))aSyscall[64].pCurrent)
  39264. #if SQLITE_OS_WINRT
  39265. { "SetFilePointerEx", (SYSCALL)SetFilePointerEx, 0 },
  39266. #else
  39267. { "SetFilePointerEx", (SYSCALL)0, 0 },
  39268. #endif
  39269. #define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
  39270. PLARGE_INTEGER,DWORD))aSyscall[65].pCurrent)
  39271. #if SQLITE_OS_WINRT
  39272. { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
  39273. #else
  39274. { "GetFileInformationByHandleEx", (SYSCALL)0, 0 },
  39275. #endif
  39276. #define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
  39277. FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[66].pCurrent)
  39278. #if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
  39279. { "MapViewOfFileFromApp", (SYSCALL)MapViewOfFileFromApp, 0 },
  39280. #else
  39281. { "MapViewOfFileFromApp", (SYSCALL)0, 0 },
  39282. #endif
  39283. #define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
  39284. SIZE_T))aSyscall[67].pCurrent)
  39285. #if SQLITE_OS_WINRT
  39286. { "CreateFile2", (SYSCALL)CreateFile2, 0 },
  39287. #else
  39288. { "CreateFile2", (SYSCALL)0, 0 },
  39289. #endif
  39290. #define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
  39291. LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[68].pCurrent)
  39292. #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  39293. { "LoadPackagedLibrary", (SYSCALL)LoadPackagedLibrary, 0 },
  39294. #else
  39295. { "LoadPackagedLibrary", (SYSCALL)0, 0 },
  39296. #endif
  39297. #define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
  39298. DWORD))aSyscall[69].pCurrent)
  39299. #if SQLITE_OS_WINRT
  39300. { "GetTickCount64", (SYSCALL)GetTickCount64, 0 },
  39301. #else
  39302. { "GetTickCount64", (SYSCALL)0, 0 },
  39303. #endif
  39304. #define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[70].pCurrent)
  39305. #if SQLITE_OS_WINRT
  39306. { "GetNativeSystemInfo", (SYSCALL)GetNativeSystemInfo, 0 },
  39307. #else
  39308. { "GetNativeSystemInfo", (SYSCALL)0, 0 },
  39309. #endif
  39310. #define osGetNativeSystemInfo ((VOID(WINAPI*)( \
  39311. LPSYSTEM_INFO))aSyscall[71].pCurrent)
  39312. #if defined(SQLITE_WIN32_HAS_ANSI)
  39313. { "OutputDebugStringA", (SYSCALL)OutputDebugStringA, 0 },
  39314. #else
  39315. { "OutputDebugStringA", (SYSCALL)0, 0 },
  39316. #endif
  39317. #define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[72].pCurrent)
  39318. #if defined(SQLITE_WIN32_HAS_WIDE)
  39319. { "OutputDebugStringW", (SYSCALL)OutputDebugStringW, 0 },
  39320. #else
  39321. { "OutputDebugStringW", (SYSCALL)0, 0 },
  39322. #endif
  39323. #define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[73].pCurrent)
  39324. { "GetProcessHeap", (SYSCALL)GetProcessHeap, 0 },
  39325. #define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[74].pCurrent)
  39326. #if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
  39327. { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
  39328. #else
  39329. { "CreateFileMappingFromApp", (SYSCALL)0, 0 },
  39330. #endif
  39331. #define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
  39332. LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[75].pCurrent)
  39333. /*
  39334. ** NOTE: On some sub-platforms, the InterlockedCompareExchange "function"
  39335. ** is really just a macro that uses a compiler intrinsic (e.g. x64).
  39336. ** So do not try to make this is into a redefinable interface.
  39337. */
  39338. #if defined(InterlockedCompareExchange)
  39339. { "InterlockedCompareExchange", (SYSCALL)0, 0 },
  39340. #define osInterlockedCompareExchange InterlockedCompareExchange
  39341. #else
  39342. { "InterlockedCompareExchange", (SYSCALL)InterlockedCompareExchange, 0 },
  39343. #define osInterlockedCompareExchange ((LONG(WINAPI*)(LONG \
  39344. SQLITE_WIN32_VOLATILE*, LONG,LONG))aSyscall[76].pCurrent)
  39345. #endif /* defined(InterlockedCompareExchange) */
  39346. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
  39347. { "UuidCreate", (SYSCALL)UuidCreate, 0 },
  39348. #else
  39349. { "UuidCreate", (SYSCALL)0, 0 },
  39350. #endif
  39351. #define osUuidCreate ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[77].pCurrent)
  39352. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
  39353. { "UuidCreateSequential", (SYSCALL)UuidCreateSequential, 0 },
  39354. #else
  39355. { "UuidCreateSequential", (SYSCALL)0, 0 },
  39356. #endif
  39357. #define osUuidCreateSequential \
  39358. ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[78].pCurrent)
  39359. #if !defined(SQLITE_NO_SYNC) && SQLITE_MAX_MMAP_SIZE>0
  39360. { "FlushViewOfFile", (SYSCALL)FlushViewOfFile, 0 },
  39361. #else
  39362. { "FlushViewOfFile", (SYSCALL)0, 0 },
  39363. #endif
  39364. #define osFlushViewOfFile \
  39365. ((BOOL(WINAPI*)(LPCVOID,SIZE_T))aSyscall[79].pCurrent)
  39366. }; /* End of the overrideable system calls */
  39367. /*
  39368. ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
  39369. ** "win32" VFSes. Return SQLITE_OK opon successfully updating the
  39370. ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
  39371. ** system call named zName.
  39372. */
  39373. static int winSetSystemCall(
  39374. sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
  39375. const char *zName, /* Name of system call to override */
  39376. sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
  39377. ){
  39378. unsigned int i;
  39379. int rc = SQLITE_NOTFOUND;
  39380. UNUSED_PARAMETER(pNotUsed);
  39381. if( zName==0 ){
  39382. /* If no zName is given, restore all system calls to their default
  39383. ** settings and return NULL
  39384. */
  39385. rc = SQLITE_OK;
  39386. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  39387. if( aSyscall[i].pDefault ){
  39388. aSyscall[i].pCurrent = aSyscall[i].pDefault;
  39389. }
  39390. }
  39391. }else{
  39392. /* If zName is specified, operate on only the one system call
  39393. ** specified.
  39394. */
  39395. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  39396. if( strcmp(zName, aSyscall[i].zName)==0 ){
  39397. if( aSyscall[i].pDefault==0 ){
  39398. aSyscall[i].pDefault = aSyscall[i].pCurrent;
  39399. }
  39400. rc = SQLITE_OK;
  39401. if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
  39402. aSyscall[i].pCurrent = pNewFunc;
  39403. break;
  39404. }
  39405. }
  39406. }
  39407. return rc;
  39408. }
  39409. /*
  39410. ** Return the value of a system call. Return NULL if zName is not a
  39411. ** recognized system call name. NULL is also returned if the system call
  39412. ** is currently undefined.
  39413. */
  39414. static sqlite3_syscall_ptr winGetSystemCall(
  39415. sqlite3_vfs *pNotUsed,
  39416. const char *zName
  39417. ){
  39418. unsigned int i;
  39419. UNUSED_PARAMETER(pNotUsed);
  39420. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  39421. if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
  39422. }
  39423. return 0;
  39424. }
  39425. /*
  39426. ** Return the name of the first system call after zName. If zName==NULL
  39427. ** then return the name of the first system call. Return NULL if zName
  39428. ** is the last system call or if zName is not the name of a valid
  39429. ** system call.
  39430. */
  39431. static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
  39432. int i = -1;
  39433. UNUSED_PARAMETER(p);
  39434. if( zName ){
  39435. for(i=0; i<ArraySize(aSyscall)-1; i++){
  39436. if( strcmp(zName, aSyscall[i].zName)==0 ) break;
  39437. }
  39438. }
  39439. for(i++; i<ArraySize(aSyscall); i++){
  39440. if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
  39441. }
  39442. return 0;
  39443. }
  39444. #ifdef SQLITE_WIN32_MALLOC
  39445. /*
  39446. ** If a Win32 native heap has been configured, this function will attempt to
  39447. ** compact it. Upon success, SQLITE_OK will be returned. Upon failure, one
  39448. ** of SQLITE_NOMEM, SQLITE_ERROR, or SQLITE_NOTFOUND will be returned. The
  39449. ** "pnLargest" argument, if non-zero, will be used to return the size of the
  39450. ** largest committed free block in the heap, in bytes.
  39451. */
  39452. SQLITE_API int sqlite3_win32_compact_heap(LPUINT pnLargest){
  39453. int rc = SQLITE_OK;
  39454. UINT nLargest = 0;
  39455. HANDLE hHeap;
  39456. winMemAssertMagic();
  39457. hHeap = winMemGetHeap();
  39458. assert( hHeap!=0 );
  39459. assert( hHeap!=INVALID_HANDLE_VALUE );
  39460. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  39461. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  39462. #endif
  39463. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  39464. if( (nLargest=osHeapCompact(hHeap, SQLITE_WIN32_HEAP_FLAGS))==0 ){
  39465. DWORD lastErrno = osGetLastError();
  39466. if( lastErrno==NO_ERROR ){
  39467. sqlite3_log(SQLITE_NOMEM, "failed to HeapCompact (no space), heap=%p",
  39468. (void*)hHeap);
  39469. rc = SQLITE_NOMEM_BKPT;
  39470. }else{
  39471. sqlite3_log(SQLITE_ERROR, "failed to HeapCompact (%lu), heap=%p",
  39472. osGetLastError(), (void*)hHeap);
  39473. rc = SQLITE_ERROR;
  39474. }
  39475. }
  39476. #else
  39477. sqlite3_log(SQLITE_NOTFOUND, "failed to HeapCompact, heap=%p",
  39478. (void*)hHeap);
  39479. rc = SQLITE_NOTFOUND;
  39480. #endif
  39481. if( pnLargest ) *pnLargest = nLargest;
  39482. return rc;
  39483. }
  39484. /*
  39485. ** If a Win32 native heap has been configured, this function will attempt to
  39486. ** destroy and recreate it. If the Win32 native heap is not isolated and/or
  39487. ** the sqlite3_memory_used() function does not return zero, SQLITE_BUSY will
  39488. ** be returned and no changes will be made to the Win32 native heap.
  39489. */
  39490. SQLITE_API int sqlite3_win32_reset_heap(){
  39491. int rc;
  39492. MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
  39493. MUTEX_LOGIC( sqlite3_mutex *pMem; ) /* The memsys static mutex */
  39494. MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  39495. MUTEX_LOGIC( pMem = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); )
  39496. sqlite3_mutex_enter(pMaster);
  39497. sqlite3_mutex_enter(pMem);
  39498. winMemAssertMagic();
  39499. if( winMemGetHeap()!=NULL && winMemGetOwned() && sqlite3_memory_used()==0 ){
  39500. /*
  39501. ** At this point, there should be no outstanding memory allocations on
  39502. ** the heap. Also, since both the master and memsys locks are currently
  39503. ** being held by us, no other function (i.e. from another thread) should
  39504. ** be able to even access the heap. Attempt to destroy and recreate our
  39505. ** isolated Win32 native heap now.
  39506. */
  39507. assert( winMemGetHeap()!=NULL );
  39508. assert( winMemGetOwned() );
  39509. assert( sqlite3_memory_used()==0 );
  39510. winMemShutdown(winMemGetDataPtr());
  39511. assert( winMemGetHeap()==NULL );
  39512. assert( !winMemGetOwned() );
  39513. assert( sqlite3_memory_used()==0 );
  39514. rc = winMemInit(winMemGetDataPtr());
  39515. assert( rc!=SQLITE_OK || winMemGetHeap()!=NULL );
  39516. assert( rc!=SQLITE_OK || winMemGetOwned() );
  39517. assert( rc!=SQLITE_OK || sqlite3_memory_used()==0 );
  39518. }else{
  39519. /*
  39520. ** The Win32 native heap cannot be modified because it may be in use.
  39521. */
  39522. rc = SQLITE_BUSY;
  39523. }
  39524. sqlite3_mutex_leave(pMem);
  39525. sqlite3_mutex_leave(pMaster);
  39526. return rc;
  39527. }
  39528. #endif /* SQLITE_WIN32_MALLOC */
  39529. /*
  39530. ** This function outputs the specified (ANSI) string to the Win32 debugger
  39531. ** (if available).
  39532. */
  39533. SQLITE_API void sqlite3_win32_write_debug(const char *zBuf, int nBuf){
  39534. char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
  39535. int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
  39536. if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
  39537. assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
  39538. #ifdef SQLITE_ENABLE_API_ARMOR
  39539. if( !zBuf ){
  39540. (void)SQLITE_MISUSE_BKPT;
  39541. return;
  39542. }
  39543. #endif
  39544. #if defined(SQLITE_WIN32_HAS_ANSI)
  39545. if( nMin>0 ){
  39546. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  39547. memcpy(zDbgBuf, zBuf, nMin);
  39548. osOutputDebugStringA(zDbgBuf);
  39549. }else{
  39550. osOutputDebugStringA(zBuf);
  39551. }
  39552. #elif defined(SQLITE_WIN32_HAS_WIDE)
  39553. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  39554. if ( osMultiByteToWideChar(
  39555. osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,
  39556. nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){
  39557. return;
  39558. }
  39559. osOutputDebugStringW((LPCWSTR)zDbgBuf);
  39560. #else
  39561. if( nMin>0 ){
  39562. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  39563. memcpy(zDbgBuf, zBuf, nMin);
  39564. fprintf(stderr, "%s", zDbgBuf);
  39565. }else{
  39566. fprintf(stderr, "%s", zBuf);
  39567. }
  39568. #endif
  39569. }
  39570. /*
  39571. ** The following routine suspends the current thread for at least ms
  39572. ** milliseconds. This is equivalent to the Win32 Sleep() interface.
  39573. */
  39574. #if SQLITE_OS_WINRT
  39575. static HANDLE sleepObj = NULL;
  39576. #endif
  39577. SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds){
  39578. #if SQLITE_OS_WINRT
  39579. if ( sleepObj==NULL ){
  39580. sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
  39581. SYNCHRONIZE);
  39582. }
  39583. assert( sleepObj!=NULL );
  39584. osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);
  39585. #else
  39586. osSleep(milliseconds);
  39587. #endif
  39588. }
  39589. #if SQLITE_MAX_WORKER_THREADS>0 && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
  39590. SQLITE_THREADSAFE>0
  39591. SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject){
  39592. DWORD rc;
  39593. while( (rc = osWaitForSingleObjectEx(hObject, INFINITE,
  39594. TRUE))==WAIT_IO_COMPLETION ){}
  39595. return rc;
  39596. }
  39597. #endif
  39598. /*
  39599. ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
  39600. ** or WinCE. Return false (zero) for Win95, Win98, or WinME.
  39601. **
  39602. ** Here is an interesting observation: Win95, Win98, and WinME lack
  39603. ** the LockFileEx() API. But we can still statically link against that
  39604. ** API as long as we don't call it when running Win95/98/ME. A call to
  39605. ** this routine is used to determine if the host is Win95/98/ME or
  39606. ** WinNT/2K/XP so that we will know whether or not we can safely call
  39607. ** the LockFileEx() API.
  39608. */
  39609. #if !SQLITE_WIN32_GETVERSIONEX
  39610. # define osIsNT() (1)
  39611. #elif SQLITE_OS_WINCE || SQLITE_OS_WINRT || !defined(SQLITE_WIN32_HAS_ANSI)
  39612. # define osIsNT() (1)
  39613. #elif !defined(SQLITE_WIN32_HAS_WIDE)
  39614. # define osIsNT() (0)
  39615. #else
  39616. # define osIsNT() ((sqlite3_os_type==2) || sqlite3_win32_is_nt())
  39617. #endif
  39618. /*
  39619. ** This function determines if the machine is running a version of Windows
  39620. ** based on the NT kernel.
  39621. */
  39622. SQLITE_API int sqlite3_win32_is_nt(void){
  39623. #if SQLITE_OS_WINRT
  39624. /*
  39625. ** NOTE: The WinRT sub-platform is always assumed to be based on the NT
  39626. ** kernel.
  39627. */
  39628. return 1;
  39629. #elif SQLITE_WIN32_GETVERSIONEX
  39630. if( osInterlockedCompareExchange(&sqlite3_os_type, 0, 0)==0 ){
  39631. #if defined(SQLITE_WIN32_HAS_ANSI)
  39632. OSVERSIONINFOA sInfo;
  39633. sInfo.dwOSVersionInfoSize = sizeof(sInfo);
  39634. osGetVersionExA(&sInfo);
  39635. osInterlockedCompareExchange(&sqlite3_os_type,
  39636. (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
  39637. #elif defined(SQLITE_WIN32_HAS_WIDE)
  39638. OSVERSIONINFOW sInfo;
  39639. sInfo.dwOSVersionInfoSize = sizeof(sInfo);
  39640. osGetVersionExW(&sInfo);
  39641. osInterlockedCompareExchange(&sqlite3_os_type,
  39642. (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
  39643. #endif
  39644. }
  39645. return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
  39646. #elif SQLITE_TEST
  39647. return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
  39648. #else
  39649. /*
  39650. ** NOTE: All sub-platforms where the GetVersionEx[AW] functions are
  39651. ** deprecated are always assumed to be based on the NT kernel.
  39652. */
  39653. return 1;
  39654. #endif
  39655. }
  39656. #ifdef SQLITE_WIN32_MALLOC
  39657. /*
  39658. ** Allocate nBytes of memory.
  39659. */
  39660. static void *winMemMalloc(int nBytes){
  39661. HANDLE hHeap;
  39662. void *p;
  39663. winMemAssertMagic();
  39664. hHeap = winMemGetHeap();
  39665. assert( hHeap!=0 );
  39666. assert( hHeap!=INVALID_HANDLE_VALUE );
  39667. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  39668. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  39669. #endif
  39670. assert( nBytes>=0 );
  39671. p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
  39672. if( !p ){
  39673. sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%lu), heap=%p",
  39674. nBytes, osGetLastError(), (void*)hHeap);
  39675. }
  39676. return p;
  39677. }
  39678. /*
  39679. ** Free memory.
  39680. */
  39681. static void winMemFree(void *pPrior){
  39682. HANDLE hHeap;
  39683. winMemAssertMagic();
  39684. hHeap = winMemGetHeap();
  39685. assert( hHeap!=0 );
  39686. assert( hHeap!=INVALID_HANDLE_VALUE );
  39687. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  39688. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
  39689. #endif
  39690. if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
  39691. if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
  39692. sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%lu), heap=%p",
  39693. pPrior, osGetLastError(), (void*)hHeap);
  39694. }
  39695. }
  39696. /*
  39697. ** Change the size of an existing memory allocation
  39698. */
  39699. static void *winMemRealloc(void *pPrior, int nBytes){
  39700. HANDLE hHeap;
  39701. void *p;
  39702. winMemAssertMagic();
  39703. hHeap = winMemGetHeap();
  39704. assert( hHeap!=0 );
  39705. assert( hHeap!=INVALID_HANDLE_VALUE );
  39706. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  39707. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
  39708. #endif
  39709. assert( nBytes>=0 );
  39710. if( !pPrior ){
  39711. p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
  39712. }else{
  39713. p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
  39714. }
  39715. if( !p ){
  39716. sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%lu), heap=%p",
  39717. pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
  39718. (void*)hHeap);
  39719. }
  39720. return p;
  39721. }
  39722. /*
  39723. ** Return the size of an outstanding allocation, in bytes.
  39724. */
  39725. static int winMemSize(void *p){
  39726. HANDLE hHeap;
  39727. SIZE_T n;
  39728. winMemAssertMagic();
  39729. hHeap = winMemGetHeap();
  39730. assert( hHeap!=0 );
  39731. assert( hHeap!=INVALID_HANDLE_VALUE );
  39732. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  39733. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, p) );
  39734. #endif
  39735. if( !p ) return 0;
  39736. n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
  39737. if( n==(SIZE_T)-1 ){
  39738. sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%lu), heap=%p",
  39739. p, osGetLastError(), (void*)hHeap);
  39740. return 0;
  39741. }
  39742. return (int)n;
  39743. }
  39744. /*
  39745. ** Round up a request size to the next valid allocation size.
  39746. */
  39747. static int winMemRoundup(int n){
  39748. return n;
  39749. }
  39750. /*
  39751. ** Initialize this module.
  39752. */
  39753. static int winMemInit(void *pAppData){
  39754. winMemData *pWinMemData = (winMemData *)pAppData;
  39755. if( !pWinMemData ) return SQLITE_ERROR;
  39756. assert( pWinMemData->magic1==WINMEM_MAGIC1 );
  39757. assert( pWinMemData->magic2==WINMEM_MAGIC2 );
  39758. #if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
  39759. if( !pWinMemData->hHeap ){
  39760. DWORD dwInitialSize = SQLITE_WIN32_HEAP_INIT_SIZE;
  39761. DWORD dwMaximumSize = (DWORD)sqlite3GlobalConfig.nHeap;
  39762. if( dwMaximumSize==0 ){
  39763. dwMaximumSize = SQLITE_WIN32_HEAP_MAX_SIZE;
  39764. }else if( dwInitialSize>dwMaximumSize ){
  39765. dwInitialSize = dwMaximumSize;
  39766. }
  39767. pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
  39768. dwInitialSize, dwMaximumSize);
  39769. if( !pWinMemData->hHeap ){
  39770. sqlite3_log(SQLITE_NOMEM,
  39771. "failed to HeapCreate (%lu), flags=%u, initSize=%lu, maxSize=%lu",
  39772. osGetLastError(), SQLITE_WIN32_HEAP_FLAGS, dwInitialSize,
  39773. dwMaximumSize);
  39774. return SQLITE_NOMEM_BKPT;
  39775. }
  39776. pWinMemData->bOwned = TRUE;
  39777. assert( pWinMemData->bOwned );
  39778. }
  39779. #else
  39780. pWinMemData->hHeap = osGetProcessHeap();
  39781. if( !pWinMemData->hHeap ){
  39782. sqlite3_log(SQLITE_NOMEM,
  39783. "failed to GetProcessHeap (%lu)", osGetLastError());
  39784. return SQLITE_NOMEM_BKPT;
  39785. }
  39786. pWinMemData->bOwned = FALSE;
  39787. assert( !pWinMemData->bOwned );
  39788. #endif
  39789. assert( pWinMemData->hHeap!=0 );
  39790. assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
  39791. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  39792. assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  39793. #endif
  39794. return SQLITE_OK;
  39795. }
  39796. /*
  39797. ** Deinitialize this module.
  39798. */
  39799. static void winMemShutdown(void *pAppData){
  39800. winMemData *pWinMemData = (winMemData *)pAppData;
  39801. if( !pWinMemData ) return;
  39802. assert( pWinMemData->magic1==WINMEM_MAGIC1 );
  39803. assert( pWinMemData->magic2==WINMEM_MAGIC2 );
  39804. if( pWinMemData->hHeap ){
  39805. assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
  39806. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  39807. assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  39808. #endif
  39809. if( pWinMemData->bOwned ){
  39810. if( !osHeapDestroy(pWinMemData->hHeap) ){
  39811. sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%lu), heap=%p",
  39812. osGetLastError(), (void*)pWinMemData->hHeap);
  39813. }
  39814. pWinMemData->bOwned = FALSE;
  39815. }
  39816. pWinMemData->hHeap = NULL;
  39817. }
  39818. }
  39819. /*
  39820. ** Populate the low-level memory allocation function pointers in
  39821. ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
  39822. ** arguments specify the block of memory to manage.
  39823. **
  39824. ** This routine is only called by sqlite3_config(), and therefore
  39825. ** is not required to be threadsafe (it is not).
  39826. */
  39827. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
  39828. static const sqlite3_mem_methods winMemMethods = {
  39829. winMemMalloc,
  39830. winMemFree,
  39831. winMemRealloc,
  39832. winMemSize,
  39833. winMemRoundup,
  39834. winMemInit,
  39835. winMemShutdown,
  39836. &win_mem_data
  39837. };
  39838. return &winMemMethods;
  39839. }
  39840. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  39841. sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
  39842. }
  39843. #endif /* SQLITE_WIN32_MALLOC */
  39844. /*
  39845. ** Convert a UTF-8 string to Microsoft Unicode.
  39846. **
  39847. ** Space to hold the returned string is obtained from sqlite3_malloc().
  39848. */
  39849. static LPWSTR winUtf8ToUnicode(const char *zText){
  39850. int nChar;
  39851. LPWSTR zWideText;
  39852. nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, NULL, 0);
  39853. if( nChar==0 ){
  39854. return 0;
  39855. }
  39856. zWideText = sqlite3MallocZero( nChar*sizeof(WCHAR) );
  39857. if( zWideText==0 ){
  39858. return 0;
  39859. }
  39860. nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, zWideText,
  39861. nChar);
  39862. if( nChar==0 ){
  39863. sqlite3_free(zWideText);
  39864. zWideText = 0;
  39865. }
  39866. return zWideText;
  39867. }
  39868. /*
  39869. ** Convert a Microsoft Unicode string to UTF-8.
  39870. **
  39871. ** Space to hold the returned string is obtained from sqlite3_malloc().
  39872. */
  39873. static char *winUnicodeToUtf8(LPCWSTR zWideText){
  39874. int nByte;
  39875. char *zText;
  39876. nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, 0, 0, 0, 0);
  39877. if( nByte == 0 ){
  39878. return 0;
  39879. }
  39880. zText = sqlite3MallocZero( nByte );
  39881. if( zText==0 ){
  39882. return 0;
  39883. }
  39884. nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, zText, nByte,
  39885. 0, 0);
  39886. if( nByte == 0 ){
  39887. sqlite3_free(zText);
  39888. zText = 0;
  39889. }
  39890. return zText;
  39891. }
  39892. /*
  39893. ** Convert an ANSI string to Microsoft Unicode, using the ANSI or OEM
  39894. ** code page.
  39895. **
  39896. ** Space to hold the returned string is obtained from sqlite3_malloc().
  39897. */
  39898. static LPWSTR winMbcsToUnicode(const char *zText, int useAnsi){
  39899. int nByte;
  39900. LPWSTR zMbcsText;
  39901. int codepage = useAnsi ? CP_ACP : CP_OEMCP;
  39902. nByte = osMultiByteToWideChar(codepage, 0, zText, -1, NULL,
  39903. 0)*sizeof(WCHAR);
  39904. if( nByte==0 ){
  39905. return 0;
  39906. }
  39907. zMbcsText = sqlite3MallocZero( nByte*sizeof(WCHAR) );
  39908. if( zMbcsText==0 ){
  39909. return 0;
  39910. }
  39911. nByte = osMultiByteToWideChar(codepage, 0, zText, -1, zMbcsText,
  39912. nByte);
  39913. if( nByte==0 ){
  39914. sqlite3_free(zMbcsText);
  39915. zMbcsText = 0;
  39916. }
  39917. return zMbcsText;
  39918. }
  39919. /*
  39920. ** Convert a Microsoft Unicode string to a multi-byte character string,
  39921. ** using the ANSI or OEM code page.
  39922. **
  39923. ** Space to hold the returned string is obtained from sqlite3_malloc().
  39924. */
  39925. static char *winUnicodeToMbcs(LPCWSTR zWideText, int useAnsi){
  39926. int nByte;
  39927. char *zText;
  39928. int codepage = useAnsi ? CP_ACP : CP_OEMCP;
  39929. nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, 0, 0, 0, 0);
  39930. if( nByte == 0 ){
  39931. return 0;
  39932. }
  39933. zText = sqlite3MallocZero( nByte );
  39934. if( zText==0 ){
  39935. return 0;
  39936. }
  39937. nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, zText,
  39938. nByte, 0, 0);
  39939. if( nByte == 0 ){
  39940. sqlite3_free(zText);
  39941. zText = 0;
  39942. }
  39943. return zText;
  39944. }
  39945. /*
  39946. ** Convert a multi-byte character string to UTF-8.
  39947. **
  39948. ** Space to hold the returned string is obtained from sqlite3_malloc().
  39949. */
  39950. static char *winMbcsToUtf8(const char *zText, int useAnsi){
  39951. char *zTextUtf8;
  39952. LPWSTR zTmpWide;
  39953. zTmpWide = winMbcsToUnicode(zText, useAnsi);
  39954. if( zTmpWide==0 ){
  39955. return 0;
  39956. }
  39957. zTextUtf8 = winUnicodeToUtf8(zTmpWide);
  39958. sqlite3_free(zTmpWide);
  39959. return zTextUtf8;
  39960. }
  39961. /*
  39962. ** Convert a UTF-8 string to a multi-byte character string.
  39963. **
  39964. ** Space to hold the returned string is obtained from sqlite3_malloc().
  39965. */
  39966. static char *winUtf8ToMbcs(const char *zText, int useAnsi){
  39967. char *zTextMbcs;
  39968. LPWSTR zTmpWide;
  39969. zTmpWide = winUtf8ToUnicode(zText);
  39970. if( zTmpWide==0 ){
  39971. return 0;
  39972. }
  39973. zTextMbcs = winUnicodeToMbcs(zTmpWide, useAnsi);
  39974. sqlite3_free(zTmpWide);
  39975. return zTextMbcs;
  39976. }
  39977. /*
  39978. ** This is a public wrapper for the winUtf8ToUnicode() function.
  39979. */
  39980. SQLITE_API LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText){
  39981. #ifdef SQLITE_ENABLE_API_ARMOR
  39982. if( !zText ){
  39983. (void)SQLITE_MISUSE_BKPT;
  39984. return 0;
  39985. }
  39986. #endif
  39987. #ifndef SQLITE_OMIT_AUTOINIT
  39988. if( sqlite3_initialize() ) return 0;
  39989. #endif
  39990. return winUtf8ToUnicode(zText);
  39991. }
  39992. /*
  39993. ** This is a public wrapper for the winUnicodeToUtf8() function.
  39994. */
  39995. SQLITE_API char *sqlite3_win32_unicode_to_utf8(LPCWSTR zWideText){
  39996. #ifdef SQLITE_ENABLE_API_ARMOR
  39997. if( !zWideText ){
  39998. (void)SQLITE_MISUSE_BKPT;
  39999. return 0;
  40000. }
  40001. #endif
  40002. #ifndef SQLITE_OMIT_AUTOINIT
  40003. if( sqlite3_initialize() ) return 0;
  40004. #endif
  40005. return winUnicodeToUtf8(zWideText);
  40006. }
  40007. /*
  40008. ** This is a public wrapper for the winMbcsToUtf8() function.
  40009. */
  40010. SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zText){
  40011. #ifdef SQLITE_ENABLE_API_ARMOR
  40012. if( !zText ){
  40013. (void)SQLITE_MISUSE_BKPT;
  40014. return 0;
  40015. }
  40016. #endif
  40017. #ifndef SQLITE_OMIT_AUTOINIT
  40018. if( sqlite3_initialize() ) return 0;
  40019. #endif
  40020. return winMbcsToUtf8(zText, osAreFileApisANSI());
  40021. }
  40022. /*
  40023. ** This is a public wrapper for the winMbcsToUtf8() function.
  40024. */
  40025. SQLITE_API char *sqlite3_win32_mbcs_to_utf8_v2(const char *zText, int useAnsi){
  40026. #ifdef SQLITE_ENABLE_API_ARMOR
  40027. if( !zText ){
  40028. (void)SQLITE_MISUSE_BKPT;
  40029. return 0;
  40030. }
  40031. #endif
  40032. #ifndef SQLITE_OMIT_AUTOINIT
  40033. if( sqlite3_initialize() ) return 0;
  40034. #endif
  40035. return winMbcsToUtf8(zText, useAnsi);
  40036. }
  40037. /*
  40038. ** This is a public wrapper for the winUtf8ToMbcs() function.
  40039. */
  40040. SQLITE_API char *sqlite3_win32_utf8_to_mbcs(const char *zText){
  40041. #ifdef SQLITE_ENABLE_API_ARMOR
  40042. if( !zText ){
  40043. (void)SQLITE_MISUSE_BKPT;
  40044. return 0;
  40045. }
  40046. #endif
  40047. #ifndef SQLITE_OMIT_AUTOINIT
  40048. if( sqlite3_initialize() ) return 0;
  40049. #endif
  40050. return winUtf8ToMbcs(zText, osAreFileApisANSI());
  40051. }
  40052. /*
  40053. ** This is a public wrapper for the winUtf8ToMbcs() function.
  40054. */
  40055. SQLITE_API char *sqlite3_win32_utf8_to_mbcs_v2(const char *zText, int useAnsi){
  40056. #ifdef SQLITE_ENABLE_API_ARMOR
  40057. if( !zText ){
  40058. (void)SQLITE_MISUSE_BKPT;
  40059. return 0;
  40060. }
  40061. #endif
  40062. #ifndef SQLITE_OMIT_AUTOINIT
  40063. if( sqlite3_initialize() ) return 0;
  40064. #endif
  40065. return winUtf8ToMbcs(zText, useAnsi);
  40066. }
  40067. /*
  40068. ** This function is the same as sqlite3_win32_set_directory (below); however,
  40069. ** it accepts a UTF-8 string.
  40070. */
  40071. SQLITE_API int sqlite3_win32_set_directory8(
  40072. unsigned long type, /* Identifier for directory being set or reset */
  40073. const char *zValue /* New value for directory being set or reset */
  40074. ){
  40075. char **ppDirectory = 0;
  40076. #ifndef SQLITE_OMIT_AUTOINIT
  40077. int rc = sqlite3_initialize();
  40078. if( rc ) return rc;
  40079. #endif
  40080. if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){
  40081. ppDirectory = &sqlite3_data_directory;
  40082. }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){
  40083. ppDirectory = &sqlite3_temp_directory;
  40084. }
  40085. assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE
  40086. || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
  40087. );
  40088. assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
  40089. if( ppDirectory ){
  40090. char *zCopy = 0;
  40091. if( zValue && zValue[0] ){
  40092. zCopy = sqlite3_mprintf("%s", zValue);
  40093. if ( zCopy==0 ){
  40094. return SQLITE_NOMEM_BKPT;
  40095. }
  40096. }
  40097. sqlite3_free(*ppDirectory);
  40098. *ppDirectory = zCopy;
  40099. return SQLITE_OK;
  40100. }
  40101. return SQLITE_ERROR;
  40102. }
  40103. /*
  40104. ** This function is the same as sqlite3_win32_set_directory (below); however,
  40105. ** it accepts a UTF-16 string.
  40106. */
  40107. SQLITE_API int sqlite3_win32_set_directory16(
  40108. unsigned long type, /* Identifier for directory being set or reset */
  40109. const void *zValue /* New value for directory being set or reset */
  40110. ){
  40111. int rc;
  40112. char *zUtf8 = 0;
  40113. if( zValue ){
  40114. zUtf8 = sqlite3_win32_unicode_to_utf8(zValue);
  40115. if( zUtf8==0 ) return SQLITE_NOMEM_BKPT;
  40116. }
  40117. rc = sqlite3_win32_set_directory8(type, zUtf8);
  40118. if( zUtf8 ) sqlite3_free(zUtf8);
  40119. return rc;
  40120. }
  40121. /*
  40122. ** This function sets the data directory or the temporary directory based on
  40123. ** the provided arguments. The type argument must be 1 in order to set the
  40124. ** data directory or 2 in order to set the temporary directory. The zValue
  40125. ** argument is the name of the directory to use. The return value will be
  40126. ** SQLITE_OK if successful.
  40127. */
  40128. SQLITE_API int sqlite3_win32_set_directory(
  40129. unsigned long type, /* Identifier for directory being set or reset */
  40130. void *zValue /* New value for directory being set or reset */
  40131. ){
  40132. return sqlite3_win32_set_directory16(type, zValue);
  40133. }
  40134. /*
  40135. ** The return value of winGetLastErrorMsg
  40136. ** is zero if the error message fits in the buffer, or non-zero
  40137. ** otherwise (if the message was truncated).
  40138. */
  40139. static int winGetLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
  40140. /* FormatMessage returns 0 on failure. Otherwise it
  40141. ** returns the number of TCHARs written to the output
  40142. ** buffer, excluding the terminating null char.
  40143. */
  40144. DWORD dwLen = 0;
  40145. char *zOut = 0;
  40146. if( osIsNT() ){
  40147. #if SQLITE_OS_WINRT
  40148. WCHAR zTempWide[SQLITE_WIN32_MAX_ERRMSG_CHARS+1];
  40149. dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
  40150. FORMAT_MESSAGE_IGNORE_INSERTS,
  40151. NULL,
  40152. lastErrno,
  40153. 0,
  40154. zTempWide,
  40155. SQLITE_WIN32_MAX_ERRMSG_CHARS,
  40156. 0);
  40157. #else
  40158. LPWSTR zTempWide = NULL;
  40159. dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  40160. FORMAT_MESSAGE_FROM_SYSTEM |
  40161. FORMAT_MESSAGE_IGNORE_INSERTS,
  40162. NULL,
  40163. lastErrno,
  40164. 0,
  40165. (LPWSTR) &zTempWide,
  40166. 0,
  40167. 0);
  40168. #endif
  40169. if( dwLen > 0 ){
  40170. /* allocate a buffer and convert to UTF8 */
  40171. sqlite3BeginBenignMalloc();
  40172. zOut = winUnicodeToUtf8(zTempWide);
  40173. sqlite3EndBenignMalloc();
  40174. #if !SQLITE_OS_WINRT
  40175. /* free the system buffer allocated by FormatMessage */
  40176. osLocalFree(zTempWide);
  40177. #endif
  40178. }
  40179. }
  40180. #ifdef SQLITE_WIN32_HAS_ANSI
  40181. else{
  40182. char *zTemp = NULL;
  40183. dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  40184. FORMAT_MESSAGE_FROM_SYSTEM |
  40185. FORMAT_MESSAGE_IGNORE_INSERTS,
  40186. NULL,
  40187. lastErrno,
  40188. 0,
  40189. (LPSTR) &zTemp,
  40190. 0,
  40191. 0);
  40192. if( dwLen > 0 ){
  40193. /* allocate a buffer and convert to UTF8 */
  40194. sqlite3BeginBenignMalloc();
  40195. zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI());
  40196. sqlite3EndBenignMalloc();
  40197. /* free the system buffer allocated by FormatMessage */
  40198. osLocalFree(zTemp);
  40199. }
  40200. }
  40201. #endif
  40202. if( 0 == dwLen ){
  40203. sqlite3_snprintf(nBuf, zBuf, "OsError 0x%lx (%lu)", lastErrno, lastErrno);
  40204. }else{
  40205. /* copy a maximum of nBuf chars to output buffer */
  40206. sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
  40207. /* free the UTF8 buffer */
  40208. sqlite3_free(zOut);
  40209. }
  40210. return 0;
  40211. }
  40212. /*
  40213. **
  40214. ** This function - winLogErrorAtLine() - is only ever called via the macro
  40215. ** winLogError().
  40216. **
  40217. ** This routine is invoked after an error occurs in an OS function.
  40218. ** It logs a message using sqlite3_log() containing the current value of
  40219. ** error code and, if possible, the human-readable equivalent from
  40220. ** FormatMessage.
  40221. **
  40222. ** The first argument passed to the macro should be the error code that
  40223. ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
  40224. ** The two subsequent arguments should be the name of the OS function that
  40225. ** failed and the associated file-system path, if any.
  40226. */
  40227. #define winLogError(a,b,c,d) winLogErrorAtLine(a,b,c,d,__LINE__)
  40228. static int winLogErrorAtLine(
  40229. int errcode, /* SQLite error code */
  40230. DWORD lastErrno, /* Win32 last error */
  40231. const char *zFunc, /* Name of OS function that failed */
  40232. const char *zPath, /* File path associated with error */
  40233. int iLine /* Source line number where error occurred */
  40234. ){
  40235. char zMsg[500]; /* Human readable error text */
  40236. int i; /* Loop counter */
  40237. zMsg[0] = 0;
  40238. winGetLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
  40239. assert( errcode!=SQLITE_OK );
  40240. if( zPath==0 ) zPath = "";
  40241. for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
  40242. zMsg[i] = 0;
  40243. sqlite3_log(errcode,
  40244. "os_win.c:%d: (%lu) %s(%s) - %s",
  40245. iLine, lastErrno, zFunc, zPath, zMsg
  40246. );
  40247. return errcode;
  40248. }
  40249. /*
  40250. ** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
  40251. ** will be retried following a locking error - probably caused by
  40252. ** antivirus software. Also the initial delay before the first retry.
  40253. ** The delay increases linearly with each retry.
  40254. */
  40255. #ifndef SQLITE_WIN32_IOERR_RETRY
  40256. # define SQLITE_WIN32_IOERR_RETRY 10
  40257. #endif
  40258. #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
  40259. # define SQLITE_WIN32_IOERR_RETRY_DELAY 25
  40260. #endif
  40261. static int winIoerrRetry = SQLITE_WIN32_IOERR_RETRY;
  40262. static int winIoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
  40263. /*
  40264. ** The "winIoerrCanRetry1" macro is used to determine if a particular I/O
  40265. ** error code obtained via GetLastError() is eligible to be retried. It
  40266. ** must accept the error code DWORD as its only argument and should return
  40267. ** non-zero if the error code is transient in nature and the operation
  40268. ** responsible for generating the original error might succeed upon being
  40269. ** retried. The argument to this macro should be a variable.
  40270. **
  40271. ** Additionally, a macro named "winIoerrCanRetry2" may be defined. If it
  40272. ** is defined, it will be consulted only when the macro "winIoerrCanRetry1"
  40273. ** returns zero. The "winIoerrCanRetry2" macro is completely optional and
  40274. ** may be used to include additional error codes in the set that should
  40275. ** result in the failing I/O operation being retried by the caller. If
  40276. ** defined, the "winIoerrCanRetry2" macro must exhibit external semantics
  40277. ** identical to those of the "winIoerrCanRetry1" macro.
  40278. */
  40279. #if !defined(winIoerrCanRetry1)
  40280. #define winIoerrCanRetry1(a) (((a)==ERROR_ACCESS_DENIED) || \
  40281. ((a)==ERROR_SHARING_VIOLATION) || \
  40282. ((a)==ERROR_LOCK_VIOLATION) || \
  40283. ((a)==ERROR_DEV_NOT_EXIST) || \
  40284. ((a)==ERROR_NETNAME_DELETED) || \
  40285. ((a)==ERROR_SEM_TIMEOUT) || \
  40286. ((a)==ERROR_NETWORK_UNREACHABLE))
  40287. #endif
  40288. /*
  40289. ** If a ReadFile() or WriteFile() error occurs, invoke this routine
  40290. ** to see if it should be retried. Return TRUE to retry. Return FALSE
  40291. ** to give up with an error.
  40292. */
  40293. static int winRetryIoerr(int *pnRetry, DWORD *pError){
  40294. DWORD e = osGetLastError();
  40295. if( *pnRetry>=winIoerrRetry ){
  40296. if( pError ){
  40297. *pError = e;
  40298. }
  40299. return 0;
  40300. }
  40301. if( winIoerrCanRetry1(e) ){
  40302. sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
  40303. ++*pnRetry;
  40304. return 1;
  40305. }
  40306. #if defined(winIoerrCanRetry2)
  40307. else if( winIoerrCanRetry2(e) ){
  40308. sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
  40309. ++*pnRetry;
  40310. return 1;
  40311. }
  40312. #endif
  40313. if( pError ){
  40314. *pError = e;
  40315. }
  40316. return 0;
  40317. }
  40318. /*
  40319. ** Log a I/O error retry episode.
  40320. */
  40321. static void winLogIoerr(int nRetry, int lineno){
  40322. if( nRetry ){
  40323. sqlite3_log(SQLITE_NOTICE,
  40324. "delayed %dms for lock/sharing conflict at line %d",
  40325. winIoerrRetryDelay*nRetry*(nRetry+1)/2, lineno
  40326. );
  40327. }
  40328. }
  40329. /*
  40330. ** This #if does not rely on the SQLITE_OS_WINCE define because the
  40331. ** corresponding section in "date.c" cannot use it.
  40332. */
  40333. #if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \
  40334. (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API)
  40335. /*
  40336. ** The MSVC CRT on Windows CE may not have a localtime() function.
  40337. ** So define a substitute.
  40338. */
  40339. /* # include <time.h> */
  40340. struct tm *__cdecl localtime(const time_t *t)
  40341. {
  40342. static struct tm y;
  40343. FILETIME uTm, lTm;
  40344. SYSTEMTIME pTm;
  40345. sqlite3_int64 t64;
  40346. t64 = *t;
  40347. t64 = (t64 + 11644473600)*10000000;
  40348. uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
  40349. uTm.dwHighDateTime= (DWORD)(t64 >> 32);
  40350. osFileTimeToLocalFileTime(&uTm,&lTm);
  40351. osFileTimeToSystemTime(&lTm,&pTm);
  40352. y.tm_year = pTm.wYear - 1900;
  40353. y.tm_mon = pTm.wMonth - 1;
  40354. y.tm_wday = pTm.wDayOfWeek;
  40355. y.tm_mday = pTm.wDay;
  40356. y.tm_hour = pTm.wHour;
  40357. y.tm_min = pTm.wMinute;
  40358. y.tm_sec = pTm.wSecond;
  40359. return &y;
  40360. }
  40361. #endif
  40362. #if SQLITE_OS_WINCE
  40363. /*************************************************************************
  40364. ** This section contains code for WinCE only.
  40365. */
  40366. #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
  40367. /*
  40368. ** Acquire a lock on the handle h
  40369. */
  40370. static void winceMutexAcquire(HANDLE h){
  40371. DWORD dwErr;
  40372. do {
  40373. dwErr = osWaitForSingleObject(h, INFINITE);
  40374. } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
  40375. }
  40376. /*
  40377. ** Release a lock acquired by winceMutexAcquire()
  40378. */
  40379. #define winceMutexRelease(h) ReleaseMutex(h)
  40380. /*
  40381. ** Create the mutex and shared memory used for locking in the file
  40382. ** descriptor pFile
  40383. */
  40384. static int winceCreateLock(const char *zFilename, winFile *pFile){
  40385. LPWSTR zTok;
  40386. LPWSTR zName;
  40387. DWORD lastErrno;
  40388. BOOL bLogged = FALSE;
  40389. BOOL bInit = TRUE;
  40390. zName = winUtf8ToUnicode(zFilename);
  40391. if( zName==0 ){
  40392. /* out of memory */
  40393. return SQLITE_IOERR_NOMEM_BKPT;
  40394. }
  40395. /* Initialize the local lockdata */
  40396. memset(&pFile->local, 0, sizeof(pFile->local));
  40397. /* Replace the backslashes from the filename and lowercase it
  40398. ** to derive a mutex name. */
  40399. zTok = osCharLowerW(zName);
  40400. for (;*zTok;zTok++){
  40401. if (*zTok == '\\') *zTok = '_';
  40402. }
  40403. /* Create/open the named mutex */
  40404. pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
  40405. if (!pFile->hMutex){
  40406. pFile->lastErrno = osGetLastError();
  40407. sqlite3_free(zName);
  40408. return winLogError(SQLITE_IOERR, pFile->lastErrno,
  40409. "winceCreateLock1", zFilename);
  40410. }
  40411. /* Acquire the mutex before continuing */
  40412. winceMutexAcquire(pFile->hMutex);
  40413. /* Since the names of named mutexes, semaphores, file mappings etc are
  40414. ** case-sensitive, take advantage of that by uppercasing the mutex name
  40415. ** and using that as the shared filemapping name.
  40416. */
  40417. osCharUpperW(zName);
  40418. pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
  40419. PAGE_READWRITE, 0, sizeof(winceLock),
  40420. zName);
  40421. /* Set a flag that indicates we're the first to create the memory so it
  40422. ** must be zero-initialized */
  40423. lastErrno = osGetLastError();
  40424. if (lastErrno == ERROR_ALREADY_EXISTS){
  40425. bInit = FALSE;
  40426. }
  40427. sqlite3_free(zName);
  40428. /* If we succeeded in making the shared memory handle, map it. */
  40429. if( pFile->hShared ){
  40430. pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared,
  40431. FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
  40432. /* If mapping failed, close the shared memory handle and erase it */
  40433. if( !pFile->shared ){
  40434. pFile->lastErrno = osGetLastError();
  40435. winLogError(SQLITE_IOERR, pFile->lastErrno,
  40436. "winceCreateLock2", zFilename);
  40437. bLogged = TRUE;
  40438. osCloseHandle(pFile->hShared);
  40439. pFile->hShared = NULL;
  40440. }
  40441. }
  40442. /* If shared memory could not be created, then close the mutex and fail */
  40443. if( pFile->hShared==NULL ){
  40444. if( !bLogged ){
  40445. pFile->lastErrno = lastErrno;
  40446. winLogError(SQLITE_IOERR, pFile->lastErrno,
  40447. "winceCreateLock3", zFilename);
  40448. bLogged = TRUE;
  40449. }
  40450. winceMutexRelease(pFile->hMutex);
  40451. osCloseHandle(pFile->hMutex);
  40452. pFile->hMutex = NULL;
  40453. return SQLITE_IOERR;
  40454. }
  40455. /* Initialize the shared memory if we're supposed to */
  40456. if( bInit ){
  40457. memset(pFile->shared, 0, sizeof(winceLock));
  40458. }
  40459. winceMutexRelease(pFile->hMutex);
  40460. return SQLITE_OK;
  40461. }
  40462. /*
  40463. ** Destroy the part of winFile that deals with wince locks
  40464. */
  40465. static void winceDestroyLock(winFile *pFile){
  40466. if (pFile->hMutex){
  40467. /* Acquire the mutex */
  40468. winceMutexAcquire(pFile->hMutex);
  40469. /* The following blocks should probably assert in debug mode, but they
  40470. are to cleanup in case any locks remained open */
  40471. if (pFile->local.nReaders){
  40472. pFile->shared->nReaders --;
  40473. }
  40474. if (pFile->local.bReserved){
  40475. pFile->shared->bReserved = FALSE;
  40476. }
  40477. if (pFile->local.bPending){
  40478. pFile->shared->bPending = FALSE;
  40479. }
  40480. if (pFile->local.bExclusive){
  40481. pFile->shared->bExclusive = FALSE;
  40482. }
  40483. /* De-reference and close our copy of the shared memory handle */
  40484. osUnmapViewOfFile(pFile->shared);
  40485. osCloseHandle(pFile->hShared);
  40486. /* Done with the mutex */
  40487. winceMutexRelease(pFile->hMutex);
  40488. osCloseHandle(pFile->hMutex);
  40489. pFile->hMutex = NULL;
  40490. }
  40491. }
  40492. /*
  40493. ** An implementation of the LockFile() API of Windows for CE
  40494. */
  40495. static BOOL winceLockFile(
  40496. LPHANDLE phFile,
  40497. DWORD dwFileOffsetLow,
  40498. DWORD dwFileOffsetHigh,
  40499. DWORD nNumberOfBytesToLockLow,
  40500. DWORD nNumberOfBytesToLockHigh
  40501. ){
  40502. winFile *pFile = HANDLE_TO_WINFILE(phFile);
  40503. BOOL bReturn = FALSE;
  40504. UNUSED_PARAMETER(dwFileOffsetHigh);
  40505. UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
  40506. if (!pFile->hMutex) return TRUE;
  40507. winceMutexAcquire(pFile->hMutex);
  40508. /* Wanting an exclusive lock? */
  40509. if (dwFileOffsetLow == (DWORD)SHARED_FIRST
  40510. && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
  40511. if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
  40512. pFile->shared->bExclusive = TRUE;
  40513. pFile->local.bExclusive = TRUE;
  40514. bReturn = TRUE;
  40515. }
  40516. }
  40517. /* Want a read-only lock? */
  40518. else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
  40519. nNumberOfBytesToLockLow == 1){
  40520. if (pFile->shared->bExclusive == 0){
  40521. pFile->local.nReaders ++;
  40522. if (pFile->local.nReaders == 1){
  40523. pFile->shared->nReaders ++;
  40524. }
  40525. bReturn = TRUE;
  40526. }
  40527. }
  40528. /* Want a pending lock? */
  40529. else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
  40530. && nNumberOfBytesToLockLow == 1){
  40531. /* If no pending lock has been acquired, then acquire it */
  40532. if (pFile->shared->bPending == 0) {
  40533. pFile->shared->bPending = TRUE;
  40534. pFile->local.bPending = TRUE;
  40535. bReturn = TRUE;
  40536. }
  40537. }
  40538. /* Want a reserved lock? */
  40539. else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
  40540. && nNumberOfBytesToLockLow == 1){
  40541. if (pFile->shared->bReserved == 0) {
  40542. pFile->shared->bReserved = TRUE;
  40543. pFile->local.bReserved = TRUE;
  40544. bReturn = TRUE;
  40545. }
  40546. }
  40547. winceMutexRelease(pFile->hMutex);
  40548. return bReturn;
  40549. }
  40550. /*
  40551. ** An implementation of the UnlockFile API of Windows for CE
  40552. */
  40553. static BOOL winceUnlockFile(
  40554. LPHANDLE phFile,
  40555. DWORD dwFileOffsetLow,
  40556. DWORD dwFileOffsetHigh,
  40557. DWORD nNumberOfBytesToUnlockLow,
  40558. DWORD nNumberOfBytesToUnlockHigh
  40559. ){
  40560. winFile *pFile = HANDLE_TO_WINFILE(phFile);
  40561. BOOL bReturn = FALSE;
  40562. UNUSED_PARAMETER(dwFileOffsetHigh);
  40563. UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
  40564. if (!pFile->hMutex) return TRUE;
  40565. winceMutexAcquire(pFile->hMutex);
  40566. /* Releasing a reader lock or an exclusive lock */
  40567. if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
  40568. /* Did we have an exclusive lock? */
  40569. if (pFile->local.bExclusive){
  40570. assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
  40571. pFile->local.bExclusive = FALSE;
  40572. pFile->shared->bExclusive = FALSE;
  40573. bReturn = TRUE;
  40574. }
  40575. /* Did we just have a reader lock? */
  40576. else if (pFile->local.nReaders){
  40577. assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE
  40578. || nNumberOfBytesToUnlockLow == 1);
  40579. pFile->local.nReaders --;
  40580. if (pFile->local.nReaders == 0)
  40581. {
  40582. pFile->shared->nReaders --;
  40583. }
  40584. bReturn = TRUE;
  40585. }
  40586. }
  40587. /* Releasing a pending lock */
  40588. else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
  40589. && nNumberOfBytesToUnlockLow == 1){
  40590. if (pFile->local.bPending){
  40591. pFile->local.bPending = FALSE;
  40592. pFile->shared->bPending = FALSE;
  40593. bReturn = TRUE;
  40594. }
  40595. }
  40596. /* Releasing a reserved lock */
  40597. else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
  40598. && nNumberOfBytesToUnlockLow == 1){
  40599. if (pFile->local.bReserved) {
  40600. pFile->local.bReserved = FALSE;
  40601. pFile->shared->bReserved = FALSE;
  40602. bReturn = TRUE;
  40603. }
  40604. }
  40605. winceMutexRelease(pFile->hMutex);
  40606. return bReturn;
  40607. }
  40608. /*
  40609. ** End of the special code for wince
  40610. *****************************************************************************/
  40611. #endif /* SQLITE_OS_WINCE */
  40612. /*
  40613. ** Lock a file region.
  40614. */
  40615. static BOOL winLockFile(
  40616. LPHANDLE phFile,
  40617. DWORD flags,
  40618. DWORD offsetLow,
  40619. DWORD offsetHigh,
  40620. DWORD numBytesLow,
  40621. DWORD numBytesHigh
  40622. ){
  40623. #if SQLITE_OS_WINCE
  40624. /*
  40625. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  40626. ** API LockFile.
  40627. */
  40628. return winceLockFile(phFile, offsetLow, offsetHigh,
  40629. numBytesLow, numBytesHigh);
  40630. #else
  40631. if( osIsNT() ){
  40632. OVERLAPPED ovlp;
  40633. memset(&ovlp, 0, sizeof(OVERLAPPED));
  40634. ovlp.Offset = offsetLow;
  40635. ovlp.OffsetHigh = offsetHigh;
  40636. return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
  40637. }else{
  40638. return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
  40639. numBytesHigh);
  40640. }
  40641. #endif
  40642. }
  40643. /*
  40644. ** Unlock a file region.
  40645. */
  40646. static BOOL winUnlockFile(
  40647. LPHANDLE phFile,
  40648. DWORD offsetLow,
  40649. DWORD offsetHigh,
  40650. DWORD numBytesLow,
  40651. DWORD numBytesHigh
  40652. ){
  40653. #if SQLITE_OS_WINCE
  40654. /*
  40655. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  40656. ** API UnlockFile.
  40657. */
  40658. return winceUnlockFile(phFile, offsetLow, offsetHigh,
  40659. numBytesLow, numBytesHigh);
  40660. #else
  40661. if( osIsNT() ){
  40662. OVERLAPPED ovlp;
  40663. memset(&ovlp, 0, sizeof(OVERLAPPED));
  40664. ovlp.Offset = offsetLow;
  40665. ovlp.OffsetHigh = offsetHigh;
  40666. return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
  40667. }else{
  40668. return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
  40669. numBytesHigh);
  40670. }
  40671. #endif
  40672. }
  40673. /*****************************************************************************
  40674. ** The next group of routines implement the I/O methods specified
  40675. ** by the sqlite3_io_methods object.
  40676. ******************************************************************************/
  40677. /*
  40678. ** Some Microsoft compilers lack this definition.
  40679. */
  40680. #ifndef INVALID_SET_FILE_POINTER
  40681. # define INVALID_SET_FILE_POINTER ((DWORD)-1)
  40682. #endif
  40683. /*
  40684. ** Move the current position of the file handle passed as the first
  40685. ** argument to offset iOffset within the file. If successful, return 0.
  40686. ** Otherwise, set pFile->lastErrno and return non-zero.
  40687. */
  40688. static int winSeekFile(winFile *pFile, sqlite3_int64 iOffset){
  40689. #if !SQLITE_OS_WINRT
  40690. LONG upperBits; /* Most sig. 32 bits of new offset */
  40691. LONG lowerBits; /* Least sig. 32 bits of new offset */
  40692. DWORD dwRet; /* Value returned by SetFilePointer() */
  40693. DWORD lastErrno; /* Value returned by GetLastError() */
  40694. OSTRACE(("SEEK file=%p, offset=%lld\n", pFile->h, iOffset));
  40695. upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
  40696. lowerBits = (LONG)(iOffset & 0xffffffff);
  40697. /* API oddity: If successful, SetFilePointer() returns a dword
  40698. ** containing the lower 32-bits of the new file-offset. Or, if it fails,
  40699. ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
  40700. ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
  40701. ** whether an error has actually occurred, it is also necessary to call
  40702. ** GetLastError().
  40703. */
  40704. dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
  40705. if( (dwRet==INVALID_SET_FILE_POINTER
  40706. && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
  40707. pFile->lastErrno = lastErrno;
  40708. winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
  40709. "winSeekFile", pFile->zPath);
  40710. OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
  40711. return 1;
  40712. }
  40713. OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
  40714. return 0;
  40715. #else
  40716. /*
  40717. ** Same as above, except that this implementation works for WinRT.
  40718. */
  40719. LARGE_INTEGER x; /* The new offset */
  40720. BOOL bRet; /* Value returned by SetFilePointerEx() */
  40721. x.QuadPart = iOffset;
  40722. bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
  40723. if(!bRet){
  40724. pFile->lastErrno = osGetLastError();
  40725. winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
  40726. "winSeekFile", pFile->zPath);
  40727. OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
  40728. return 1;
  40729. }
  40730. OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
  40731. return 0;
  40732. #endif
  40733. }
  40734. #if SQLITE_MAX_MMAP_SIZE>0
  40735. /* Forward references to VFS helper methods used for memory mapped files */
  40736. static int winMapfile(winFile*, sqlite3_int64);
  40737. static int winUnmapfile(winFile*);
  40738. #endif
  40739. /*
  40740. ** Close a file.
  40741. **
  40742. ** It is reported that an attempt to close a handle might sometimes
  40743. ** fail. This is a very unreasonable result, but Windows is notorious
  40744. ** for being unreasonable so I do not doubt that it might happen. If
  40745. ** the close fails, we pause for 100 milliseconds and try again. As
  40746. ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
  40747. ** giving up and returning an error.
  40748. */
  40749. #define MX_CLOSE_ATTEMPT 3
  40750. static int winClose(sqlite3_file *id){
  40751. int rc, cnt = 0;
  40752. winFile *pFile = (winFile*)id;
  40753. assert( id!=0 );
  40754. #ifndef SQLITE_OMIT_WAL
  40755. assert( pFile->pShm==0 );
  40756. #endif
  40757. assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE );
  40758. OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p\n",
  40759. osGetCurrentProcessId(), pFile, pFile->h));
  40760. #if SQLITE_MAX_MMAP_SIZE>0
  40761. winUnmapfile(pFile);
  40762. #endif
  40763. do{
  40764. rc = osCloseHandle(pFile->h);
  40765. /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
  40766. }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );
  40767. #if SQLITE_OS_WINCE
  40768. #define WINCE_DELETION_ATTEMPTS 3
  40769. {
  40770. winVfsAppData *pAppData = (winVfsAppData*)pFile->pVfs->pAppData;
  40771. if( pAppData==NULL || !pAppData->bNoLock ){
  40772. winceDestroyLock(pFile);
  40773. }
  40774. }
  40775. if( pFile->zDeleteOnClose ){
  40776. int cnt = 0;
  40777. while(
  40778. osDeleteFileW(pFile->zDeleteOnClose)==0
  40779. && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
  40780. && cnt++ < WINCE_DELETION_ATTEMPTS
  40781. ){
  40782. sqlite3_win32_sleep(100); /* Wait a little before trying again */
  40783. }
  40784. sqlite3_free(pFile->zDeleteOnClose);
  40785. }
  40786. #endif
  40787. if( rc ){
  40788. pFile->h = NULL;
  40789. }
  40790. OpenCounter(-1);
  40791. OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p, rc=%s\n",
  40792. osGetCurrentProcessId(), pFile, pFile->h, rc ? "ok" : "failed"));
  40793. return rc ? SQLITE_OK
  40794. : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
  40795. "winClose", pFile->zPath);
  40796. }
  40797. /*
  40798. ** Read data from a file into a buffer. Return SQLITE_OK if all
  40799. ** bytes were read successfully and SQLITE_IOERR if anything goes
  40800. ** wrong.
  40801. */
  40802. static int winRead(
  40803. sqlite3_file *id, /* File to read from */
  40804. void *pBuf, /* Write content into this buffer */
  40805. int amt, /* Number of bytes to read */
  40806. sqlite3_int64 offset /* Begin reading at this offset */
  40807. ){
  40808. #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
  40809. OVERLAPPED overlapped; /* The offset for ReadFile. */
  40810. #endif
  40811. winFile *pFile = (winFile*)id; /* file handle */
  40812. DWORD nRead; /* Number of bytes actually read from file */
  40813. int nRetry = 0; /* Number of retrys */
  40814. assert( id!=0 );
  40815. assert( amt>0 );
  40816. assert( offset>=0 );
  40817. SimulateIOError(return SQLITE_IOERR_READ);
  40818. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
  40819. "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
  40820. pFile->h, pBuf, amt, offset, pFile->locktype));
  40821. #if SQLITE_MAX_MMAP_SIZE>0
  40822. /* Deal with as much of this read request as possible by transfering
  40823. ** data from the memory mapping using memcpy(). */
  40824. if( offset<pFile->mmapSize ){
  40825. if( offset+amt <= pFile->mmapSize ){
  40826. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
  40827. OSTRACE(("READ-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  40828. osGetCurrentProcessId(), pFile, pFile->h));
  40829. return SQLITE_OK;
  40830. }else{
  40831. int nCopy = (int)(pFile->mmapSize - offset);
  40832. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
  40833. pBuf = &((u8 *)pBuf)[nCopy];
  40834. amt -= nCopy;
  40835. offset += nCopy;
  40836. }
  40837. }
  40838. #endif
  40839. #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
  40840. if( winSeekFile(pFile, offset) ){
  40841. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
  40842. osGetCurrentProcessId(), pFile, pFile->h));
  40843. return SQLITE_FULL;
  40844. }
  40845. while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
  40846. #else
  40847. memset(&overlapped, 0, sizeof(OVERLAPPED));
  40848. overlapped.Offset = (LONG)(offset & 0xffffffff);
  40849. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  40850. while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
  40851. osGetLastError()!=ERROR_HANDLE_EOF ){
  40852. #endif
  40853. DWORD lastErrno;
  40854. if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
  40855. pFile->lastErrno = lastErrno;
  40856. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_READ\n",
  40857. osGetCurrentProcessId(), pFile, pFile->h));
  40858. return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
  40859. "winRead", pFile->zPath);
  40860. }
  40861. winLogIoerr(nRetry, __LINE__);
  40862. if( nRead<(DWORD)amt ){
  40863. /* Unread parts of the buffer must be zero-filled */
  40864. memset(&((char*)pBuf)[nRead], 0, amt-nRead);
  40865. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_SHORT_READ\n",
  40866. osGetCurrentProcessId(), pFile, pFile->h));
  40867. return SQLITE_IOERR_SHORT_READ;
  40868. }
  40869. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  40870. osGetCurrentProcessId(), pFile, pFile->h));
  40871. return SQLITE_OK;
  40872. }
  40873. /*
  40874. ** Write data from a buffer into a file. Return SQLITE_OK on success
  40875. ** or some other error code on failure.
  40876. */
  40877. static int winWrite(
  40878. sqlite3_file *id, /* File to write into */
  40879. const void *pBuf, /* The bytes to be written */
  40880. int amt, /* Number of bytes to write */
  40881. sqlite3_int64 offset /* Offset into the file to begin writing at */
  40882. ){
  40883. int rc = 0; /* True if error has occurred, else false */
  40884. winFile *pFile = (winFile*)id; /* File handle */
  40885. int nRetry = 0; /* Number of retries */
  40886. assert( amt>0 );
  40887. assert( pFile );
  40888. SimulateIOError(return SQLITE_IOERR_WRITE);
  40889. SimulateDiskfullError(return SQLITE_FULL);
  40890. OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
  40891. "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
  40892. pFile->h, pBuf, amt, offset, pFile->locktype));
  40893. #if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
  40894. /* Deal with as much of this write request as possible by transfering
  40895. ** data from the memory mapping using memcpy(). */
  40896. if( offset<pFile->mmapSize ){
  40897. if( offset+amt <= pFile->mmapSize ){
  40898. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
  40899. OSTRACE(("WRITE-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  40900. osGetCurrentProcessId(), pFile, pFile->h));
  40901. return SQLITE_OK;
  40902. }else{
  40903. int nCopy = (int)(pFile->mmapSize - offset);
  40904. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
  40905. pBuf = &((u8 *)pBuf)[nCopy];
  40906. amt -= nCopy;
  40907. offset += nCopy;
  40908. }
  40909. }
  40910. #endif
  40911. #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
  40912. rc = winSeekFile(pFile, offset);
  40913. if( rc==0 ){
  40914. #else
  40915. {
  40916. #endif
  40917. #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
  40918. OVERLAPPED overlapped; /* The offset for WriteFile. */
  40919. #endif
  40920. u8 *aRem = (u8 *)pBuf; /* Data yet to be written */
  40921. int nRem = amt; /* Number of bytes yet to be written */
  40922. DWORD nWrite; /* Bytes written by each WriteFile() call */
  40923. DWORD lastErrno = NO_ERROR; /* Value returned by GetLastError() */
  40924. #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
  40925. memset(&overlapped, 0, sizeof(OVERLAPPED));
  40926. overlapped.Offset = (LONG)(offset & 0xffffffff);
  40927. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  40928. #endif
  40929. while( nRem>0 ){
  40930. #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
  40931. if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
  40932. #else
  40933. if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
  40934. #endif
  40935. if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
  40936. break;
  40937. }
  40938. assert( nWrite==0 || nWrite<=(DWORD)nRem );
  40939. if( nWrite==0 || nWrite>(DWORD)nRem ){
  40940. lastErrno = osGetLastError();
  40941. break;
  40942. }
  40943. #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
  40944. offset += nWrite;
  40945. overlapped.Offset = (LONG)(offset & 0xffffffff);
  40946. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  40947. #endif
  40948. aRem += nWrite;
  40949. nRem -= nWrite;
  40950. }
  40951. if( nRem>0 ){
  40952. pFile->lastErrno = lastErrno;
  40953. rc = 1;
  40954. }
  40955. }
  40956. if( rc ){
  40957. if( ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
  40958. || ( pFile->lastErrno==ERROR_DISK_FULL )){
  40959. OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
  40960. osGetCurrentProcessId(), pFile, pFile->h));
  40961. return winLogError(SQLITE_FULL, pFile->lastErrno,
  40962. "winWrite1", pFile->zPath);
  40963. }
  40964. OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_WRITE\n",
  40965. osGetCurrentProcessId(), pFile, pFile->h));
  40966. return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
  40967. "winWrite2", pFile->zPath);
  40968. }else{
  40969. winLogIoerr(nRetry, __LINE__);
  40970. }
  40971. OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  40972. osGetCurrentProcessId(), pFile, pFile->h));
  40973. return SQLITE_OK;
  40974. }
  40975. /*
  40976. ** Truncate an open file to a specified size
  40977. */
  40978. static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
  40979. winFile *pFile = (winFile*)id; /* File handle object */
  40980. int rc = SQLITE_OK; /* Return code for this function */
  40981. DWORD lastErrno;
  40982. #if SQLITE_MAX_MMAP_SIZE>0
  40983. sqlite3_int64 oldMmapSize;
  40984. if( pFile->nFetchOut>0 ){
  40985. /* File truncation is a no-op if there are outstanding memory mapped
  40986. ** pages. This is because truncating the file means temporarily unmapping
  40987. ** the file, and that might delete memory out from under existing cursors.
  40988. **
  40989. ** This can result in incremental vacuum not truncating the file,
  40990. ** if there is an active read cursor when the incremental vacuum occurs.
  40991. ** No real harm comes of this - the database file is not corrupted,
  40992. ** though some folks might complain that the file is bigger than it
  40993. ** needs to be.
  40994. **
  40995. ** The only feasible work-around is to defer the truncation until after
  40996. ** all references to memory-mapped content are closed. That is doable,
  40997. ** but involves adding a few branches in the common write code path which
  40998. ** could slow down normal operations slightly. Hence, we have decided for
  40999. ** now to simply make trancations a no-op if there are pending reads. We
  41000. ** can maybe revisit this decision in the future.
  41001. */
  41002. return SQLITE_OK;
  41003. }
  41004. #endif
  41005. assert( pFile );
  41006. SimulateIOError(return SQLITE_IOERR_TRUNCATE);
  41007. OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, size=%lld, lock=%d\n",
  41008. osGetCurrentProcessId(), pFile, pFile->h, nByte, pFile->locktype));
  41009. /* If the user has configured a chunk-size for this file, truncate the
  41010. ** file so that it consists of an integer number of chunks (i.e. the
  41011. ** actual file size after the operation may be larger than the requested
  41012. ** size).
  41013. */
  41014. if( pFile->szChunk>0 ){
  41015. nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
  41016. }
  41017. #if SQLITE_MAX_MMAP_SIZE>0
  41018. if( pFile->pMapRegion ){
  41019. oldMmapSize = pFile->mmapSize;
  41020. }else{
  41021. oldMmapSize = 0;
  41022. }
  41023. winUnmapfile(pFile);
  41024. #endif
  41025. /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
  41026. if( winSeekFile(pFile, nByte) ){
  41027. rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
  41028. "winTruncate1", pFile->zPath);
  41029. }else if( 0==osSetEndOfFile(pFile->h) &&
  41030. ((lastErrno = osGetLastError())!=ERROR_USER_MAPPED_FILE) ){
  41031. pFile->lastErrno = lastErrno;
  41032. rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
  41033. "winTruncate2", pFile->zPath);
  41034. }
  41035. #if SQLITE_MAX_MMAP_SIZE>0
  41036. if( rc==SQLITE_OK && oldMmapSize>0 ){
  41037. if( oldMmapSize>nByte ){
  41038. winMapfile(pFile, -1);
  41039. }else{
  41040. winMapfile(pFile, oldMmapSize);
  41041. }
  41042. }
  41043. #endif
  41044. OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, rc=%s\n",
  41045. osGetCurrentProcessId(), pFile, pFile->h, sqlite3ErrName(rc)));
  41046. return rc;
  41047. }
  41048. #ifdef SQLITE_TEST
  41049. /*
  41050. ** Count the number of fullsyncs and normal syncs. This is used to test
  41051. ** that syncs and fullsyncs are occuring at the right times.
  41052. */
  41053. SQLITE_API int sqlite3_sync_count = 0;
  41054. SQLITE_API int sqlite3_fullsync_count = 0;
  41055. #endif
  41056. /*
  41057. ** Make sure all writes to a particular file are committed to disk.
  41058. */
  41059. static int winSync(sqlite3_file *id, int flags){
  41060. #ifndef SQLITE_NO_SYNC
  41061. /*
  41062. ** Used only when SQLITE_NO_SYNC is not defined.
  41063. */
  41064. BOOL rc;
  41065. #endif
  41066. #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
  41067. defined(SQLITE_HAVE_OS_TRACE)
  41068. /*
  41069. ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
  41070. ** OSTRACE() macros.
  41071. */
  41072. winFile *pFile = (winFile*)id;
  41073. #else
  41074. UNUSED_PARAMETER(id);
  41075. #endif
  41076. assert( pFile );
  41077. /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
  41078. assert((flags&0x0F)==SQLITE_SYNC_NORMAL
  41079. || (flags&0x0F)==SQLITE_SYNC_FULL
  41080. );
  41081. /* Unix cannot, but some systems may return SQLITE_FULL from here. This
  41082. ** line is to test that doing so does not cause any problems.
  41083. */
  41084. SimulateDiskfullError( return SQLITE_FULL );
  41085. OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, flags=%x, lock=%d\n",
  41086. osGetCurrentProcessId(), pFile, pFile->h, flags,
  41087. pFile->locktype));
  41088. #ifndef SQLITE_TEST
  41089. UNUSED_PARAMETER(flags);
  41090. #else
  41091. if( (flags&0x0F)==SQLITE_SYNC_FULL ){
  41092. sqlite3_fullsync_count++;
  41093. }
  41094. sqlite3_sync_count++;
  41095. #endif
  41096. /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
  41097. ** no-op
  41098. */
  41099. #ifdef SQLITE_NO_SYNC
  41100. OSTRACE(("SYNC-NOP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  41101. osGetCurrentProcessId(), pFile, pFile->h));
  41102. return SQLITE_OK;
  41103. #else
  41104. #if SQLITE_MAX_MMAP_SIZE>0
  41105. if( pFile->pMapRegion ){
  41106. if( osFlushViewOfFile(pFile->pMapRegion, 0) ){
  41107. OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
  41108. "rc=SQLITE_OK\n", osGetCurrentProcessId(),
  41109. pFile, pFile->pMapRegion));
  41110. }else{
  41111. pFile->lastErrno = osGetLastError();
  41112. OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
  41113. "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(),
  41114. pFile, pFile->pMapRegion));
  41115. return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
  41116. "winSync1", pFile->zPath);
  41117. }
  41118. }
  41119. #endif
  41120. rc = osFlushFileBuffers(pFile->h);
  41121. SimulateIOError( rc=FALSE );
  41122. if( rc ){
  41123. OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  41124. osGetCurrentProcessId(), pFile, pFile->h));
  41125. return SQLITE_OK;
  41126. }else{
  41127. pFile->lastErrno = osGetLastError();
  41128. OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_FSYNC\n",
  41129. osGetCurrentProcessId(), pFile, pFile->h));
  41130. return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
  41131. "winSync2", pFile->zPath);
  41132. }
  41133. #endif
  41134. }
  41135. /*
  41136. ** Determine the current size of a file in bytes
  41137. */
  41138. static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
  41139. winFile *pFile = (winFile*)id;
  41140. int rc = SQLITE_OK;
  41141. assert( id!=0 );
  41142. assert( pSize!=0 );
  41143. SimulateIOError(return SQLITE_IOERR_FSTAT);
  41144. OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize));
  41145. #if SQLITE_OS_WINRT
  41146. {
  41147. FILE_STANDARD_INFO info;
  41148. if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
  41149. &info, sizeof(info)) ){
  41150. *pSize = info.EndOfFile.QuadPart;
  41151. }else{
  41152. pFile->lastErrno = osGetLastError();
  41153. rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
  41154. "winFileSize", pFile->zPath);
  41155. }
  41156. }
  41157. #else
  41158. {
  41159. DWORD upperBits;
  41160. DWORD lowerBits;
  41161. DWORD lastErrno;
  41162. lowerBits = osGetFileSize(pFile->h, &upperBits);
  41163. *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
  41164. if( (lowerBits == INVALID_FILE_SIZE)
  41165. && ((lastErrno = osGetLastError())!=NO_ERROR) ){
  41166. pFile->lastErrno = lastErrno;
  41167. rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
  41168. "winFileSize", pFile->zPath);
  41169. }
  41170. }
  41171. #endif
  41172. OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n",
  41173. pFile->h, pSize, *pSize, sqlite3ErrName(rc)));
  41174. return rc;
  41175. }
  41176. /*
  41177. ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
  41178. */
  41179. #ifndef LOCKFILE_FAIL_IMMEDIATELY
  41180. # define LOCKFILE_FAIL_IMMEDIATELY 1
  41181. #endif
  41182. #ifndef LOCKFILE_EXCLUSIVE_LOCK
  41183. # define LOCKFILE_EXCLUSIVE_LOCK 2
  41184. #endif
  41185. /*
  41186. ** Historically, SQLite has used both the LockFile and LockFileEx functions.
  41187. ** When the LockFile function was used, it was always expected to fail
  41188. ** immediately if the lock could not be obtained. Also, it always expected to
  41189. ** obtain an exclusive lock. These flags are used with the LockFileEx function
  41190. ** and reflect those expectations; therefore, they should not be changed.
  41191. */
  41192. #ifndef SQLITE_LOCKFILE_FLAGS
  41193. # define SQLITE_LOCKFILE_FLAGS (LOCKFILE_FAIL_IMMEDIATELY | \
  41194. LOCKFILE_EXCLUSIVE_LOCK)
  41195. #endif
  41196. /*
  41197. ** Currently, SQLite never calls the LockFileEx function without wanting the
  41198. ** call to fail immediately if the lock cannot be obtained.
  41199. */
  41200. #ifndef SQLITE_LOCKFILEEX_FLAGS
  41201. # define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
  41202. #endif
  41203. /*
  41204. ** Acquire a reader lock.
  41205. ** Different API routines are called depending on whether or not this
  41206. ** is Win9x or WinNT.
  41207. */
  41208. static int winGetReadLock(winFile *pFile){
  41209. int res;
  41210. OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
  41211. if( osIsNT() ){
  41212. #if SQLITE_OS_WINCE
  41213. /*
  41214. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  41215. ** API LockFileEx.
  41216. */
  41217. res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
  41218. #else
  41219. res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
  41220. SHARED_SIZE, 0);
  41221. #endif
  41222. }
  41223. #ifdef SQLITE_WIN32_HAS_ANSI
  41224. else{
  41225. int lk;
  41226. sqlite3_randomness(sizeof(lk), &lk);
  41227. pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
  41228. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
  41229. SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
  41230. }
  41231. #endif
  41232. if( res == 0 ){
  41233. pFile->lastErrno = osGetLastError();
  41234. /* No need to log a failure to lock */
  41235. }
  41236. OSTRACE(("READ-LOCK file=%p, result=%d\n", pFile->h, res));
  41237. return res;
  41238. }
  41239. /*
  41240. ** Undo a readlock
  41241. */
  41242. static int winUnlockReadLock(winFile *pFile){
  41243. int res;
  41244. DWORD lastErrno;
  41245. OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
  41246. if( osIsNT() ){
  41247. res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
  41248. }
  41249. #ifdef SQLITE_WIN32_HAS_ANSI
  41250. else{
  41251. res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
  41252. }
  41253. #endif
  41254. if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
  41255. pFile->lastErrno = lastErrno;
  41256. winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
  41257. "winUnlockReadLock", pFile->zPath);
  41258. }
  41259. OSTRACE(("READ-UNLOCK file=%p, result=%d\n", pFile->h, res));
  41260. return res;
  41261. }
  41262. /*
  41263. ** Lock the file with the lock specified by parameter locktype - one
  41264. ** of the following:
  41265. **
  41266. ** (1) SHARED_LOCK
  41267. ** (2) RESERVED_LOCK
  41268. ** (3) PENDING_LOCK
  41269. ** (4) EXCLUSIVE_LOCK
  41270. **
  41271. ** Sometimes when requesting one lock state, additional lock states
  41272. ** are inserted in between. The locking might fail on one of the later
  41273. ** transitions leaving the lock state different from what it started but
  41274. ** still short of its goal. The following chart shows the allowed
  41275. ** transitions and the inserted intermediate states:
  41276. **
  41277. ** UNLOCKED -> SHARED
  41278. ** SHARED -> RESERVED
  41279. ** SHARED -> (PENDING) -> EXCLUSIVE
  41280. ** RESERVED -> (PENDING) -> EXCLUSIVE
  41281. ** PENDING -> EXCLUSIVE
  41282. **
  41283. ** This routine will only increase a lock. The winUnlock() routine
  41284. ** erases all locks at once and returns us immediately to locking level 0.
  41285. ** It is not possible to lower the locking level one step at a time. You
  41286. ** must go straight to locking level 0.
  41287. */
  41288. static int winLock(sqlite3_file *id, int locktype){
  41289. int rc = SQLITE_OK; /* Return code from subroutines */
  41290. int res = 1; /* Result of a Windows lock call */
  41291. int newLocktype; /* Set pFile->locktype to this value before exiting */
  41292. int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
  41293. winFile *pFile = (winFile*)id;
  41294. DWORD lastErrno = NO_ERROR;
  41295. assert( id!=0 );
  41296. OSTRACE(("LOCK file=%p, oldLock=%d(%d), newLock=%d\n",
  41297. pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
  41298. /* If there is already a lock of this type or more restrictive on the
  41299. ** OsFile, do nothing. Don't use the end_lock: exit path, as
  41300. ** sqlite3OsEnterMutex() hasn't been called yet.
  41301. */
  41302. if( pFile->locktype>=locktype ){
  41303. OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h));
  41304. return SQLITE_OK;
  41305. }
  41306. /* Do not allow any kind of write-lock on a read-only database
  41307. */
  41308. if( (pFile->ctrlFlags & WINFILE_RDONLY)!=0 && locktype>=RESERVED_LOCK ){
  41309. return SQLITE_IOERR_LOCK;
  41310. }
  41311. /* Make sure the locking sequence is correct
  41312. */
  41313. assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
  41314. assert( locktype!=PENDING_LOCK );
  41315. assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
  41316. /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
  41317. ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of
  41318. ** the PENDING_LOCK byte is temporary.
  41319. */
  41320. newLocktype = pFile->locktype;
  41321. if( pFile->locktype==NO_LOCK
  41322. || (locktype==EXCLUSIVE_LOCK && pFile->locktype<=RESERVED_LOCK)
  41323. ){
  41324. int cnt = 3;
  41325. while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
  41326. PENDING_BYTE, 0, 1, 0))==0 ){
  41327. /* Try 3 times to get the pending lock. This is needed to work
  41328. ** around problems caused by indexing and/or anti-virus software on
  41329. ** Windows systems.
  41330. ** If you are using this code as a model for alternative VFSes, do not
  41331. ** copy this retry logic. It is a hack intended for Windows only.
  41332. */
  41333. lastErrno = osGetLastError();
  41334. OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, result=%d\n",
  41335. pFile->h, cnt, res));
  41336. if( lastErrno==ERROR_INVALID_HANDLE ){
  41337. pFile->lastErrno = lastErrno;
  41338. rc = SQLITE_IOERR_LOCK;
  41339. OSTRACE(("LOCK-FAIL file=%p, count=%d, rc=%s\n",
  41340. pFile->h, cnt, sqlite3ErrName(rc)));
  41341. return rc;
  41342. }
  41343. if( cnt ) sqlite3_win32_sleep(1);
  41344. }
  41345. gotPendingLock = res;
  41346. if( !res ){
  41347. lastErrno = osGetLastError();
  41348. }
  41349. }
  41350. /* Acquire a shared lock
  41351. */
  41352. if( locktype==SHARED_LOCK && res ){
  41353. assert( pFile->locktype==NO_LOCK );
  41354. res = winGetReadLock(pFile);
  41355. if( res ){
  41356. newLocktype = SHARED_LOCK;
  41357. }else{
  41358. lastErrno = osGetLastError();
  41359. }
  41360. }
  41361. /* Acquire a RESERVED lock
  41362. */
  41363. if( locktype==RESERVED_LOCK && res ){
  41364. assert( pFile->locktype==SHARED_LOCK );
  41365. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
  41366. if( res ){
  41367. newLocktype = RESERVED_LOCK;
  41368. }else{
  41369. lastErrno = osGetLastError();
  41370. }
  41371. }
  41372. /* Acquire a PENDING lock
  41373. */
  41374. if( locktype==EXCLUSIVE_LOCK && res ){
  41375. newLocktype = PENDING_LOCK;
  41376. gotPendingLock = 0;
  41377. }
  41378. /* Acquire an EXCLUSIVE lock
  41379. */
  41380. if( locktype==EXCLUSIVE_LOCK && res ){
  41381. assert( pFile->locktype>=SHARED_LOCK );
  41382. res = winUnlockReadLock(pFile);
  41383. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
  41384. SHARED_SIZE, 0);
  41385. if( res ){
  41386. newLocktype = EXCLUSIVE_LOCK;
  41387. }else{
  41388. lastErrno = osGetLastError();
  41389. winGetReadLock(pFile);
  41390. }
  41391. }
  41392. /* If we are holding a PENDING lock that ought to be released, then
  41393. ** release it now.
  41394. */
  41395. if( gotPendingLock && locktype==SHARED_LOCK ){
  41396. winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
  41397. }
  41398. /* Update the state of the lock has held in the file descriptor then
  41399. ** return the appropriate result code.
  41400. */
  41401. if( res ){
  41402. rc = SQLITE_OK;
  41403. }else{
  41404. pFile->lastErrno = lastErrno;
  41405. rc = SQLITE_BUSY;
  41406. OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n",
  41407. pFile->h, locktype, newLocktype));
  41408. }
  41409. pFile->locktype = (u8)newLocktype;
  41410. OSTRACE(("LOCK file=%p, lock=%d, rc=%s\n",
  41411. pFile->h, pFile->locktype, sqlite3ErrName(rc)));
  41412. return rc;
  41413. }
  41414. /*
  41415. ** This routine checks if there is a RESERVED lock held on the specified
  41416. ** file by this or any other process. If such a lock is held, return
  41417. ** non-zero, otherwise zero.
  41418. */
  41419. static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
  41420. int res;
  41421. winFile *pFile = (winFile*)id;
  41422. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  41423. OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile->h, pResOut));
  41424. assert( id!=0 );
  41425. if( pFile->locktype>=RESERVED_LOCK ){
  41426. res = 1;
  41427. OSTRACE(("TEST-WR-LOCK file=%p, result=%d (local)\n", pFile->h, res));
  41428. }else{
  41429. res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE,0,1,0);
  41430. if( res ){
  41431. winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
  41432. }
  41433. res = !res;
  41434. OSTRACE(("TEST-WR-LOCK file=%p, result=%d (remote)\n", pFile->h, res));
  41435. }
  41436. *pResOut = res;
  41437. OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
  41438. pFile->h, pResOut, *pResOut));
  41439. return SQLITE_OK;
  41440. }
  41441. /*
  41442. ** Lower the locking level on file descriptor id to locktype. locktype
  41443. ** must be either NO_LOCK or SHARED_LOCK.
  41444. **
  41445. ** If the locking level of the file descriptor is already at or below
  41446. ** the requested locking level, this routine is a no-op.
  41447. **
  41448. ** It is not possible for this routine to fail if the second argument
  41449. ** is NO_LOCK. If the second argument is SHARED_LOCK then this routine
  41450. ** might return SQLITE_IOERR;
  41451. */
  41452. static int winUnlock(sqlite3_file *id, int locktype){
  41453. int type;
  41454. winFile *pFile = (winFile*)id;
  41455. int rc = SQLITE_OK;
  41456. assert( pFile!=0 );
  41457. assert( locktype<=SHARED_LOCK );
  41458. OSTRACE(("UNLOCK file=%p, oldLock=%d(%d), newLock=%d\n",
  41459. pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
  41460. type = pFile->locktype;
  41461. if( type>=EXCLUSIVE_LOCK ){
  41462. winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
  41463. if( locktype==SHARED_LOCK && !winGetReadLock(pFile) ){
  41464. /* This should never happen. We should always be able to
  41465. ** reacquire the read lock */
  41466. rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
  41467. "winUnlock", pFile->zPath);
  41468. }
  41469. }
  41470. if( type>=RESERVED_LOCK ){
  41471. winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
  41472. }
  41473. if( locktype==NO_LOCK && type>=SHARED_LOCK ){
  41474. winUnlockReadLock(pFile);
  41475. }
  41476. if( type>=PENDING_LOCK ){
  41477. winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
  41478. }
  41479. pFile->locktype = (u8)locktype;
  41480. OSTRACE(("UNLOCK file=%p, lock=%d, rc=%s\n",
  41481. pFile->h, pFile->locktype, sqlite3ErrName(rc)));
  41482. return rc;
  41483. }
  41484. /******************************************************************************
  41485. ****************************** No-op Locking **********************************
  41486. **
  41487. ** Of the various locking implementations available, this is by far the
  41488. ** simplest: locking is ignored. No attempt is made to lock the database
  41489. ** file for reading or writing.
  41490. **
  41491. ** This locking mode is appropriate for use on read-only databases
  41492. ** (ex: databases that are burned into CD-ROM, for example.) It can
  41493. ** also be used if the application employs some external mechanism to
  41494. ** prevent simultaneous access of the same database by two or more
  41495. ** database connections. But there is a serious risk of database
  41496. ** corruption if this locking mode is used in situations where multiple
  41497. ** database connections are accessing the same database file at the same
  41498. ** time and one or more of those connections are writing.
  41499. */
  41500. static int winNolockLock(sqlite3_file *id, int locktype){
  41501. UNUSED_PARAMETER(id);
  41502. UNUSED_PARAMETER(locktype);
  41503. return SQLITE_OK;
  41504. }
  41505. static int winNolockCheckReservedLock(sqlite3_file *id, int *pResOut){
  41506. UNUSED_PARAMETER(id);
  41507. UNUSED_PARAMETER(pResOut);
  41508. return SQLITE_OK;
  41509. }
  41510. static int winNolockUnlock(sqlite3_file *id, int locktype){
  41511. UNUSED_PARAMETER(id);
  41512. UNUSED_PARAMETER(locktype);
  41513. return SQLITE_OK;
  41514. }
  41515. /******************* End of the no-op lock implementation *********************
  41516. ******************************************************************************/
  41517. /*
  41518. ** If *pArg is initially negative then this is a query. Set *pArg to
  41519. ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
  41520. **
  41521. ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
  41522. */
  41523. static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
  41524. if( *pArg<0 ){
  41525. *pArg = (pFile->ctrlFlags & mask)!=0;
  41526. }else if( (*pArg)==0 ){
  41527. pFile->ctrlFlags &= ~mask;
  41528. }else{
  41529. pFile->ctrlFlags |= mask;
  41530. }
  41531. }
  41532. /* Forward references to VFS helper methods used for temporary files */
  41533. static int winGetTempname(sqlite3_vfs *, char **);
  41534. static int winIsDir(const void *);
  41535. static BOOL winIsDriveLetterAndColon(const char *);
  41536. /*
  41537. ** Control and query of the open file handle.
  41538. */
  41539. static int winFileControl(sqlite3_file *id, int op, void *pArg){
  41540. winFile *pFile = (winFile*)id;
  41541. OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg));
  41542. switch( op ){
  41543. case SQLITE_FCNTL_LOCKSTATE: {
  41544. *(int*)pArg = pFile->locktype;
  41545. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  41546. return SQLITE_OK;
  41547. }
  41548. case SQLITE_FCNTL_LAST_ERRNO: {
  41549. *(int*)pArg = (int)pFile->lastErrno;
  41550. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  41551. return SQLITE_OK;
  41552. }
  41553. case SQLITE_FCNTL_CHUNK_SIZE: {
  41554. pFile->szChunk = *(int *)pArg;
  41555. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  41556. return SQLITE_OK;
  41557. }
  41558. case SQLITE_FCNTL_SIZE_HINT: {
  41559. if( pFile->szChunk>0 ){
  41560. sqlite3_int64 oldSz;
  41561. int rc = winFileSize(id, &oldSz);
  41562. if( rc==SQLITE_OK ){
  41563. sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
  41564. if( newSz>oldSz ){
  41565. SimulateIOErrorBenign(1);
  41566. rc = winTruncate(id, newSz);
  41567. SimulateIOErrorBenign(0);
  41568. }
  41569. }
  41570. OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  41571. return rc;
  41572. }
  41573. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  41574. return SQLITE_OK;
  41575. }
  41576. case SQLITE_FCNTL_PERSIST_WAL: {
  41577. winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
  41578. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  41579. return SQLITE_OK;
  41580. }
  41581. case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
  41582. winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
  41583. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  41584. return SQLITE_OK;
  41585. }
  41586. case SQLITE_FCNTL_VFSNAME: {
  41587. *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
  41588. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  41589. return SQLITE_OK;
  41590. }
  41591. case SQLITE_FCNTL_WIN32_AV_RETRY: {
  41592. int *a = (int*)pArg;
  41593. if( a[0]>0 ){
  41594. winIoerrRetry = a[0];
  41595. }else{
  41596. a[0] = winIoerrRetry;
  41597. }
  41598. if( a[1]>0 ){
  41599. winIoerrRetryDelay = a[1];
  41600. }else{
  41601. a[1] = winIoerrRetryDelay;
  41602. }
  41603. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  41604. return SQLITE_OK;
  41605. }
  41606. case SQLITE_FCNTL_WIN32_GET_HANDLE: {
  41607. LPHANDLE phFile = (LPHANDLE)pArg;
  41608. *phFile = pFile->h;
  41609. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  41610. return SQLITE_OK;
  41611. }
  41612. #ifdef SQLITE_TEST
  41613. case SQLITE_FCNTL_WIN32_SET_HANDLE: {
  41614. LPHANDLE phFile = (LPHANDLE)pArg;
  41615. HANDLE hOldFile = pFile->h;
  41616. pFile->h = *phFile;
  41617. *phFile = hOldFile;
  41618. OSTRACE(("FCNTL oldFile=%p, newFile=%p, rc=SQLITE_OK\n",
  41619. hOldFile, pFile->h));
  41620. return SQLITE_OK;
  41621. }
  41622. #endif
  41623. case SQLITE_FCNTL_TEMPFILENAME: {
  41624. char *zTFile = 0;
  41625. int rc = winGetTempname(pFile->pVfs, &zTFile);
  41626. if( rc==SQLITE_OK ){
  41627. *(char**)pArg = zTFile;
  41628. }
  41629. OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  41630. return rc;
  41631. }
  41632. #if SQLITE_MAX_MMAP_SIZE>0
  41633. case SQLITE_FCNTL_MMAP_SIZE: {
  41634. i64 newLimit = *(i64*)pArg;
  41635. int rc = SQLITE_OK;
  41636. if( newLimit>sqlite3GlobalConfig.mxMmap ){
  41637. newLimit = sqlite3GlobalConfig.mxMmap;
  41638. }
  41639. /* The value of newLimit may be eventually cast to (SIZE_T) and passed
  41640. ** to MapViewOfFile(). Restrict its value to 2GB if (SIZE_T) is not at
  41641. ** least a 64-bit type. */
  41642. if( newLimit>0 && sizeof(SIZE_T)<8 ){
  41643. newLimit = (newLimit & 0x7FFFFFFF);
  41644. }
  41645. *(i64*)pArg = pFile->mmapSizeMax;
  41646. if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
  41647. pFile->mmapSizeMax = newLimit;
  41648. if( pFile->mmapSize>0 ){
  41649. winUnmapfile(pFile);
  41650. rc = winMapfile(pFile, -1);
  41651. }
  41652. }
  41653. OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  41654. return rc;
  41655. }
  41656. #endif
  41657. }
  41658. OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));
  41659. return SQLITE_NOTFOUND;
  41660. }
  41661. /*
  41662. ** Return the sector size in bytes of the underlying block device for
  41663. ** the specified file. This is almost always 512 bytes, but may be
  41664. ** larger for some devices.
  41665. **
  41666. ** SQLite code assumes this function cannot fail. It also assumes that
  41667. ** if two files are created in the same file-system directory (i.e.
  41668. ** a database and its journal file) that the sector size will be the
  41669. ** same for both.
  41670. */
  41671. static int winSectorSize(sqlite3_file *id){
  41672. (void)id;
  41673. return SQLITE_DEFAULT_SECTOR_SIZE;
  41674. }
  41675. /*
  41676. ** Return a vector of device characteristics.
  41677. */
  41678. static int winDeviceCharacteristics(sqlite3_file *id){
  41679. winFile *p = (winFile*)id;
  41680. return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
  41681. ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
  41682. }
  41683. /*
  41684. ** Windows will only let you create file view mappings
  41685. ** on allocation size granularity boundaries.
  41686. ** During sqlite3_os_init() we do a GetSystemInfo()
  41687. ** to get the granularity size.
  41688. */
  41689. static SYSTEM_INFO winSysInfo;
  41690. #ifndef SQLITE_OMIT_WAL
  41691. /*
  41692. ** Helper functions to obtain and relinquish the global mutex. The
  41693. ** global mutex is used to protect the winLockInfo objects used by
  41694. ** this file, all of which may be shared by multiple threads.
  41695. **
  41696. ** Function winShmMutexHeld() is used to assert() that the global mutex
  41697. ** is held when required. This function is only used as part of assert()
  41698. ** statements. e.g.
  41699. **
  41700. ** winShmEnterMutex()
  41701. ** assert( winShmMutexHeld() );
  41702. ** winShmLeaveMutex()
  41703. */
  41704. static sqlite3_mutex *winBigLock = 0;
  41705. static void winShmEnterMutex(void){
  41706. sqlite3_mutex_enter(winBigLock);
  41707. }
  41708. static void winShmLeaveMutex(void){
  41709. sqlite3_mutex_leave(winBigLock);
  41710. }
  41711. #ifndef NDEBUG
  41712. static int winShmMutexHeld(void) {
  41713. return sqlite3_mutex_held(winBigLock);
  41714. }
  41715. #endif
  41716. /*
  41717. ** Object used to represent a single file opened and mmapped to provide
  41718. ** shared memory. When multiple threads all reference the same
  41719. ** log-summary, each thread has its own winFile object, but they all
  41720. ** point to a single instance of this object. In other words, each
  41721. ** log-summary is opened only once per process.
  41722. **
  41723. ** winShmMutexHeld() must be true when creating or destroying
  41724. ** this object or while reading or writing the following fields:
  41725. **
  41726. ** nRef
  41727. ** pNext
  41728. **
  41729. ** The following fields are read-only after the object is created:
  41730. **
  41731. ** fid
  41732. ** zFilename
  41733. **
  41734. ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
  41735. ** winShmMutexHeld() is true when reading or writing any other field
  41736. ** in this structure.
  41737. **
  41738. */
  41739. struct winShmNode {
  41740. sqlite3_mutex *mutex; /* Mutex to access this object */
  41741. char *zFilename; /* Name of the file */
  41742. winFile hFile; /* File handle from winOpen */
  41743. int szRegion; /* Size of shared-memory regions */
  41744. int nRegion; /* Size of array apRegion */
  41745. u8 isReadonly; /* True if read-only */
  41746. u8 isUnlocked; /* True if no DMS lock held */
  41747. struct ShmRegion {
  41748. HANDLE hMap; /* File handle from CreateFileMapping */
  41749. void *pMap;
  41750. } *aRegion;
  41751. DWORD lastErrno; /* The Windows errno from the last I/O error */
  41752. int nRef; /* Number of winShm objects pointing to this */
  41753. winShm *pFirst; /* All winShm objects pointing to this */
  41754. winShmNode *pNext; /* Next in list of all winShmNode objects */
  41755. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  41756. u8 nextShmId; /* Next available winShm.id value */
  41757. #endif
  41758. };
  41759. /*
  41760. ** A global array of all winShmNode objects.
  41761. **
  41762. ** The winShmMutexHeld() must be true while reading or writing this list.
  41763. */
  41764. static winShmNode *winShmNodeList = 0;
  41765. /*
  41766. ** Structure used internally by this VFS to record the state of an
  41767. ** open shared memory connection.
  41768. **
  41769. ** The following fields are initialized when this object is created and
  41770. ** are read-only thereafter:
  41771. **
  41772. ** winShm.pShmNode
  41773. ** winShm.id
  41774. **
  41775. ** All other fields are read/write. The winShm.pShmNode->mutex must be held
  41776. ** while accessing any read/write fields.
  41777. */
  41778. struct winShm {
  41779. winShmNode *pShmNode; /* The underlying winShmNode object */
  41780. winShm *pNext; /* Next winShm with the same winShmNode */
  41781. u8 hasMutex; /* True if holding the winShmNode mutex */
  41782. u16 sharedMask; /* Mask of shared locks held */
  41783. u16 exclMask; /* Mask of exclusive locks held */
  41784. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  41785. u8 id; /* Id of this connection with its winShmNode */
  41786. #endif
  41787. };
  41788. /*
  41789. ** Constants used for locking
  41790. */
  41791. #define WIN_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
  41792. #define WIN_SHM_DMS (WIN_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
  41793. /*
  41794. ** Apply advisory locks for all n bytes beginning at ofst.
  41795. */
  41796. #define WINSHM_UNLCK 1
  41797. #define WINSHM_RDLCK 2
  41798. #define WINSHM_WRLCK 3
  41799. static int winShmSystemLock(
  41800. winShmNode *pFile, /* Apply locks to this open shared-memory segment */
  41801. int lockType, /* WINSHM_UNLCK, WINSHM_RDLCK, or WINSHM_WRLCK */
  41802. int ofst, /* Offset to first byte to be locked/unlocked */
  41803. int nByte /* Number of bytes to lock or unlock */
  41804. ){
  41805. int rc = 0; /* Result code form Lock/UnlockFileEx() */
  41806. /* Access to the winShmNode object is serialized by the caller */
  41807. assert( pFile->nRef==0 || sqlite3_mutex_held(pFile->mutex) );
  41808. OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n",
  41809. pFile->hFile.h, lockType, ofst, nByte));
  41810. /* Release/Acquire the system-level lock */
  41811. if( lockType==WINSHM_UNLCK ){
  41812. rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
  41813. }else{
  41814. /* Initialize the locking parameters */
  41815. DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
  41816. if( lockType == WINSHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
  41817. rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
  41818. }
  41819. if( rc!= 0 ){
  41820. rc = SQLITE_OK;
  41821. }else{
  41822. pFile->lastErrno = osGetLastError();
  41823. rc = SQLITE_BUSY;
  41824. }
  41825. OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n",
  41826. pFile->hFile.h, (lockType == WINSHM_UNLCK) ? "winUnlockFile" :
  41827. "winLockFile", pFile->lastErrno, sqlite3ErrName(rc)));
  41828. return rc;
  41829. }
  41830. /* Forward references to VFS methods */
  41831. static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
  41832. static int winDelete(sqlite3_vfs *,const char*,int);
  41833. /*
  41834. ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
  41835. **
  41836. ** This is not a VFS shared-memory method; it is a utility function called
  41837. ** by VFS shared-memory methods.
  41838. */
  41839. static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
  41840. winShmNode **pp;
  41841. winShmNode *p;
  41842. assert( winShmMutexHeld() );
  41843. OSTRACE(("SHM-PURGE pid=%lu, deleteFlag=%d\n",
  41844. osGetCurrentProcessId(), deleteFlag));
  41845. pp = &winShmNodeList;
  41846. while( (p = *pp)!=0 ){
  41847. if( p->nRef==0 ){
  41848. int i;
  41849. if( p->mutex ){ sqlite3_mutex_free(p->mutex); }
  41850. for(i=0; i<p->nRegion; i++){
  41851. BOOL bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
  41852. OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n",
  41853. osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
  41854. UNUSED_VARIABLE_VALUE(bRc);
  41855. bRc = osCloseHandle(p->aRegion[i].hMap);
  41856. OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n",
  41857. osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
  41858. UNUSED_VARIABLE_VALUE(bRc);
  41859. }
  41860. if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){
  41861. SimulateIOErrorBenign(1);
  41862. winClose((sqlite3_file *)&p->hFile);
  41863. SimulateIOErrorBenign(0);
  41864. }
  41865. if( deleteFlag ){
  41866. SimulateIOErrorBenign(1);
  41867. sqlite3BeginBenignMalloc();
  41868. winDelete(pVfs, p->zFilename, 0);
  41869. sqlite3EndBenignMalloc();
  41870. SimulateIOErrorBenign(0);
  41871. }
  41872. *pp = p->pNext;
  41873. sqlite3_free(p->aRegion);
  41874. sqlite3_free(p);
  41875. }else{
  41876. pp = &p->pNext;
  41877. }
  41878. }
  41879. }
  41880. /*
  41881. ** The DMS lock has not yet been taken on shm file pShmNode. Attempt to
  41882. ** take it now. Return SQLITE_OK if successful, or an SQLite error
  41883. ** code otherwise.
  41884. **
  41885. ** If the DMS cannot be locked because this is a readonly_shm=1
  41886. ** connection and no other process already holds a lock, return
  41887. ** SQLITE_READONLY_CANTINIT and set pShmNode->isUnlocked=1.
  41888. */
  41889. static int winLockSharedMemory(winShmNode *pShmNode){
  41890. int rc = winShmSystemLock(pShmNode, WINSHM_WRLCK, WIN_SHM_DMS, 1);
  41891. if( rc==SQLITE_OK ){
  41892. if( pShmNode->isReadonly ){
  41893. pShmNode->isUnlocked = 1;
  41894. winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
  41895. return SQLITE_READONLY_CANTINIT;
  41896. }else if( winTruncate((sqlite3_file*)&pShmNode->hFile, 0) ){
  41897. winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
  41898. return winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
  41899. "winLockSharedMemory", pShmNode->zFilename);
  41900. }
  41901. }
  41902. if( rc==SQLITE_OK ){
  41903. winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
  41904. }
  41905. return winShmSystemLock(pShmNode, WINSHM_RDLCK, WIN_SHM_DMS, 1);
  41906. }
  41907. /*
  41908. ** Open the shared-memory area associated with database file pDbFd.
  41909. **
  41910. ** When opening a new shared-memory file, if no other instances of that
  41911. ** file are currently open, in this process or in other processes, then
  41912. ** the file must be truncated to zero length or have its header cleared.
  41913. */
  41914. static int winOpenSharedMemory(winFile *pDbFd){
  41915. struct winShm *p; /* The connection to be opened */
  41916. winShmNode *pShmNode = 0; /* The underlying mmapped file */
  41917. int rc = SQLITE_OK; /* Result code */
  41918. winShmNode *pNew; /* Newly allocated winShmNode */
  41919. int nName; /* Size of zName in bytes */
  41920. assert( pDbFd->pShm==0 ); /* Not previously opened */
  41921. /* Allocate space for the new sqlite3_shm object. Also speculatively
  41922. ** allocate space for a new winShmNode and filename.
  41923. */
  41924. p = sqlite3MallocZero( sizeof(*p) );
  41925. if( p==0 ) return SQLITE_IOERR_NOMEM_BKPT;
  41926. nName = sqlite3Strlen30(pDbFd->zPath);
  41927. pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );
  41928. if( pNew==0 ){
  41929. sqlite3_free(p);
  41930. return SQLITE_IOERR_NOMEM_BKPT;
  41931. }
  41932. pNew->zFilename = (char*)&pNew[1];
  41933. sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
  41934. sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
  41935. /* Look to see if there is an existing winShmNode that can be used.
  41936. ** If no matching winShmNode currently exists, create a new one.
  41937. */
  41938. winShmEnterMutex();
  41939. for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
  41940. /* TBD need to come up with better match here. Perhaps
  41941. ** use FILE_ID_BOTH_DIR_INFO Structure.
  41942. */
  41943. if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
  41944. }
  41945. if( pShmNode ){
  41946. sqlite3_free(pNew);
  41947. }else{
  41948. int inFlags = SQLITE_OPEN_WAL;
  41949. int outFlags = 0;
  41950. pShmNode = pNew;
  41951. pNew = 0;
  41952. ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
  41953. pShmNode->pNext = winShmNodeList;
  41954. winShmNodeList = pShmNode;
  41955. if( sqlite3GlobalConfig.bCoreMutex ){
  41956. pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
  41957. if( pShmNode->mutex==0 ){
  41958. rc = SQLITE_IOERR_NOMEM_BKPT;
  41959. goto shm_open_err;
  41960. }
  41961. }
  41962. if( 0==sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
  41963. inFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;
  41964. }else{
  41965. inFlags |= SQLITE_OPEN_READONLY;
  41966. }
  41967. rc = winOpen(pDbFd->pVfs, pShmNode->zFilename,
  41968. (sqlite3_file*)&pShmNode->hFile,
  41969. inFlags, &outFlags);
  41970. if( rc!=SQLITE_OK ){
  41971. rc = winLogError(rc, osGetLastError(), "winOpenShm",
  41972. pShmNode->zFilename);
  41973. goto shm_open_err;
  41974. }
  41975. if( outFlags==SQLITE_OPEN_READONLY ) pShmNode->isReadonly = 1;
  41976. rc = winLockSharedMemory(pShmNode);
  41977. if( rc!=SQLITE_OK && rc!=SQLITE_READONLY_CANTINIT ) goto shm_open_err;
  41978. }
  41979. /* Make the new connection a child of the winShmNode */
  41980. p->pShmNode = pShmNode;
  41981. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  41982. p->id = pShmNode->nextShmId++;
  41983. #endif
  41984. pShmNode->nRef++;
  41985. pDbFd->pShm = p;
  41986. winShmLeaveMutex();
  41987. /* The reference count on pShmNode has already been incremented under
  41988. ** the cover of the winShmEnterMutex() mutex and the pointer from the
  41989. ** new (struct winShm) object to the pShmNode has been set. All that is
  41990. ** left to do is to link the new object into the linked list starting
  41991. ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
  41992. ** mutex.
  41993. */
  41994. sqlite3_mutex_enter(pShmNode->mutex);
  41995. p->pNext = pShmNode->pFirst;
  41996. pShmNode->pFirst = p;
  41997. sqlite3_mutex_leave(pShmNode->mutex);
  41998. return rc;
  41999. /* Jump here on any error */
  42000. shm_open_err:
  42001. winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
  42002. winShmPurge(pDbFd->pVfs, 0); /* This call frees pShmNode if required */
  42003. sqlite3_free(p);
  42004. sqlite3_free(pNew);
  42005. winShmLeaveMutex();
  42006. return rc;
  42007. }
  42008. /*
  42009. ** Close a connection to shared-memory. Delete the underlying
  42010. ** storage if deleteFlag is true.
  42011. */
  42012. static int winShmUnmap(
  42013. sqlite3_file *fd, /* Database holding shared memory */
  42014. int deleteFlag /* Delete after closing if true */
  42015. ){
  42016. winFile *pDbFd; /* Database holding shared-memory */
  42017. winShm *p; /* The connection to be closed */
  42018. winShmNode *pShmNode; /* The underlying shared-memory file */
  42019. winShm **pp; /* For looping over sibling connections */
  42020. pDbFd = (winFile*)fd;
  42021. p = pDbFd->pShm;
  42022. if( p==0 ) return SQLITE_OK;
  42023. pShmNode = p->pShmNode;
  42024. /* Remove connection p from the set of connections associated
  42025. ** with pShmNode */
  42026. sqlite3_mutex_enter(pShmNode->mutex);
  42027. for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
  42028. *pp = p->pNext;
  42029. /* Free the connection p */
  42030. sqlite3_free(p);
  42031. pDbFd->pShm = 0;
  42032. sqlite3_mutex_leave(pShmNode->mutex);
  42033. /* If pShmNode->nRef has reached 0, then close the underlying
  42034. ** shared-memory file, too */
  42035. winShmEnterMutex();
  42036. assert( pShmNode->nRef>0 );
  42037. pShmNode->nRef--;
  42038. if( pShmNode->nRef==0 ){
  42039. winShmPurge(pDbFd->pVfs, deleteFlag);
  42040. }
  42041. winShmLeaveMutex();
  42042. return SQLITE_OK;
  42043. }
  42044. /*
  42045. ** Change the lock state for a shared-memory segment.
  42046. */
  42047. static int winShmLock(
  42048. sqlite3_file *fd, /* Database file holding the shared memory */
  42049. int ofst, /* First lock to acquire or release */
  42050. int n, /* Number of locks to acquire or release */
  42051. int flags /* What to do with the lock */
  42052. ){
  42053. winFile *pDbFd = (winFile*)fd; /* Connection holding shared memory */
  42054. winShm *p = pDbFd->pShm; /* The shared memory being locked */
  42055. winShm *pX; /* For looping over all siblings */
  42056. winShmNode *pShmNode = p->pShmNode;
  42057. int rc = SQLITE_OK; /* Result code */
  42058. u16 mask; /* Mask of locks to take or release */
  42059. assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
  42060. assert( n>=1 );
  42061. assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
  42062. || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
  42063. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
  42064. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
  42065. assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
  42066. mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
  42067. assert( n>1 || mask==(1<<ofst) );
  42068. sqlite3_mutex_enter(pShmNode->mutex);
  42069. if( flags & SQLITE_SHM_UNLOCK ){
  42070. u16 allMask = 0; /* Mask of locks held by siblings */
  42071. /* See if any siblings hold this same lock */
  42072. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  42073. if( pX==p ) continue;
  42074. assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
  42075. allMask |= pX->sharedMask;
  42076. }
  42077. /* Unlock the system-level locks */
  42078. if( (mask & allMask)==0 ){
  42079. rc = winShmSystemLock(pShmNode, WINSHM_UNLCK, ofst+WIN_SHM_BASE, n);
  42080. }else{
  42081. rc = SQLITE_OK;
  42082. }
  42083. /* Undo the local locks */
  42084. if( rc==SQLITE_OK ){
  42085. p->exclMask &= ~mask;
  42086. p->sharedMask &= ~mask;
  42087. }
  42088. }else if( flags & SQLITE_SHM_SHARED ){
  42089. u16 allShared = 0; /* Union of locks held by connections other than "p" */
  42090. /* Find out which shared locks are already held by sibling connections.
  42091. ** If any sibling already holds an exclusive lock, go ahead and return
  42092. ** SQLITE_BUSY.
  42093. */
  42094. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  42095. if( (pX->exclMask & mask)!=0 ){
  42096. rc = SQLITE_BUSY;
  42097. break;
  42098. }
  42099. allShared |= pX->sharedMask;
  42100. }
  42101. /* Get shared locks at the system level, if necessary */
  42102. if( rc==SQLITE_OK ){
  42103. if( (allShared & mask)==0 ){
  42104. rc = winShmSystemLock(pShmNode, WINSHM_RDLCK, ofst+WIN_SHM_BASE, n);
  42105. }else{
  42106. rc = SQLITE_OK;
  42107. }
  42108. }
  42109. /* Get the local shared locks */
  42110. if( rc==SQLITE_OK ){
  42111. p->sharedMask |= mask;
  42112. }
  42113. }else{
  42114. /* Make sure no sibling connections hold locks that will block this
  42115. ** lock. If any do, return SQLITE_BUSY right away.
  42116. */
  42117. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  42118. if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
  42119. rc = SQLITE_BUSY;
  42120. break;
  42121. }
  42122. }
  42123. /* Get the exclusive locks at the system level. Then if successful
  42124. ** also mark the local connection as being locked.
  42125. */
  42126. if( rc==SQLITE_OK ){
  42127. rc = winShmSystemLock(pShmNode, WINSHM_WRLCK, ofst+WIN_SHM_BASE, n);
  42128. if( rc==SQLITE_OK ){
  42129. assert( (p->sharedMask & mask)==0 );
  42130. p->exclMask |= mask;
  42131. }
  42132. }
  42133. }
  42134. sqlite3_mutex_leave(pShmNode->mutex);
  42135. OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n",
  42136. osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask,
  42137. sqlite3ErrName(rc)));
  42138. return rc;
  42139. }
  42140. /*
  42141. ** Implement a memory barrier or memory fence on shared memory.
  42142. **
  42143. ** All loads and stores begun before the barrier must complete before
  42144. ** any load or store begun after the barrier.
  42145. */
  42146. static void winShmBarrier(
  42147. sqlite3_file *fd /* Database holding the shared memory */
  42148. ){
  42149. UNUSED_PARAMETER(fd);
  42150. sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
  42151. winShmEnterMutex(); /* Also mutex, for redundancy */
  42152. winShmLeaveMutex();
  42153. }
  42154. /*
  42155. ** This function is called to obtain a pointer to region iRegion of the
  42156. ** shared-memory associated with the database file fd. Shared-memory regions
  42157. ** are numbered starting from zero. Each shared-memory region is szRegion
  42158. ** bytes in size.
  42159. **
  42160. ** If an error occurs, an error code is returned and *pp is set to NULL.
  42161. **
  42162. ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
  42163. ** region has not been allocated (by any client, including one running in a
  42164. ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
  42165. ** isWrite is non-zero and the requested shared-memory region has not yet
  42166. ** been allocated, it is allocated by this function.
  42167. **
  42168. ** If the shared-memory region has already been allocated or is allocated by
  42169. ** this call as described above, then it is mapped into this processes
  42170. ** address space (if it is not already), *pp is set to point to the mapped
  42171. ** memory and SQLITE_OK returned.
  42172. */
  42173. static int winShmMap(
  42174. sqlite3_file *fd, /* Handle open on database file */
  42175. int iRegion, /* Region to retrieve */
  42176. int szRegion, /* Size of regions */
  42177. int isWrite, /* True to extend file if necessary */
  42178. void volatile **pp /* OUT: Mapped memory */
  42179. ){
  42180. winFile *pDbFd = (winFile*)fd;
  42181. winShm *pShm = pDbFd->pShm;
  42182. winShmNode *pShmNode;
  42183. DWORD protect = PAGE_READWRITE;
  42184. DWORD flags = FILE_MAP_WRITE | FILE_MAP_READ;
  42185. int rc = SQLITE_OK;
  42186. if( !pShm ){
  42187. rc = winOpenSharedMemory(pDbFd);
  42188. if( rc!=SQLITE_OK ) return rc;
  42189. pShm = pDbFd->pShm;
  42190. }
  42191. pShmNode = pShm->pShmNode;
  42192. sqlite3_mutex_enter(pShmNode->mutex);
  42193. if( pShmNode->isUnlocked ){
  42194. rc = winLockSharedMemory(pShmNode);
  42195. if( rc!=SQLITE_OK ) goto shmpage_out;
  42196. pShmNode->isUnlocked = 0;
  42197. }
  42198. assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
  42199. if( pShmNode->nRegion<=iRegion ){
  42200. struct ShmRegion *apNew; /* New aRegion[] array */
  42201. int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
  42202. sqlite3_int64 sz; /* Current size of wal-index file */
  42203. pShmNode->szRegion = szRegion;
  42204. /* The requested region is not mapped into this processes address space.
  42205. ** Check to see if it has been allocated (i.e. if the wal-index file is
  42206. ** large enough to contain the requested region).
  42207. */
  42208. rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
  42209. if( rc!=SQLITE_OK ){
  42210. rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
  42211. "winShmMap1", pDbFd->zPath);
  42212. goto shmpage_out;
  42213. }
  42214. if( sz<nByte ){
  42215. /* The requested memory region does not exist. If isWrite is set to
  42216. ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
  42217. **
  42218. ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
  42219. ** the requested memory region.
  42220. */
  42221. if( !isWrite ) goto shmpage_out;
  42222. rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
  42223. if( rc!=SQLITE_OK ){
  42224. rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
  42225. "winShmMap2", pDbFd->zPath);
  42226. goto shmpage_out;
  42227. }
  42228. }
  42229. /* Map the requested memory region into this processes address space. */
  42230. apNew = (struct ShmRegion *)sqlite3_realloc64(
  42231. pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
  42232. );
  42233. if( !apNew ){
  42234. rc = SQLITE_IOERR_NOMEM_BKPT;
  42235. goto shmpage_out;
  42236. }
  42237. pShmNode->aRegion = apNew;
  42238. if( pShmNode->isReadonly ){
  42239. protect = PAGE_READONLY;
  42240. flags = FILE_MAP_READ;
  42241. }
  42242. while( pShmNode->nRegion<=iRegion ){
  42243. HANDLE hMap = NULL; /* file-mapping handle */
  42244. void *pMap = 0; /* Mapped memory region */
  42245. #if SQLITE_OS_WINRT
  42246. hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
  42247. NULL, protect, nByte, NULL
  42248. );
  42249. #elif defined(SQLITE_WIN32_HAS_WIDE)
  42250. hMap = osCreateFileMappingW(pShmNode->hFile.h,
  42251. NULL, protect, 0, nByte, NULL
  42252. );
  42253. #elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA
  42254. hMap = osCreateFileMappingA(pShmNode->hFile.h,
  42255. NULL, protect, 0, nByte, NULL
  42256. );
  42257. #endif
  42258. OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n",
  42259. osGetCurrentProcessId(), pShmNode->nRegion, nByte,
  42260. hMap ? "ok" : "failed"));
  42261. if( hMap ){
  42262. int iOffset = pShmNode->nRegion*szRegion;
  42263. int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
  42264. #if SQLITE_OS_WINRT
  42265. pMap = osMapViewOfFileFromApp(hMap, flags,
  42266. iOffset - iOffsetShift, szRegion + iOffsetShift
  42267. );
  42268. #else
  42269. pMap = osMapViewOfFile(hMap, flags,
  42270. 0, iOffset - iOffsetShift, szRegion + iOffsetShift
  42271. );
  42272. #endif
  42273. OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n",
  42274. osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
  42275. szRegion, pMap ? "ok" : "failed"));
  42276. }
  42277. if( !pMap ){
  42278. pShmNode->lastErrno = osGetLastError();
  42279. rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
  42280. "winShmMap3", pDbFd->zPath);
  42281. if( hMap ) osCloseHandle(hMap);
  42282. goto shmpage_out;
  42283. }
  42284. pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
  42285. pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
  42286. pShmNode->nRegion++;
  42287. }
  42288. }
  42289. shmpage_out:
  42290. if( pShmNode->nRegion>iRegion ){
  42291. int iOffset = iRegion*szRegion;
  42292. int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
  42293. char *p = (char *)pShmNode->aRegion[iRegion].pMap;
  42294. *pp = (void *)&p[iOffsetShift];
  42295. }else{
  42296. *pp = 0;
  42297. }
  42298. if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
  42299. sqlite3_mutex_leave(pShmNode->mutex);
  42300. return rc;
  42301. }
  42302. #else
  42303. # define winShmMap 0
  42304. # define winShmLock 0
  42305. # define winShmBarrier 0
  42306. # define winShmUnmap 0
  42307. #endif /* #ifndef SQLITE_OMIT_WAL */
  42308. /*
  42309. ** Cleans up the mapped region of the specified file, if any.
  42310. */
  42311. #if SQLITE_MAX_MMAP_SIZE>0
  42312. static int winUnmapfile(winFile *pFile){
  42313. assert( pFile!=0 );
  42314. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, "
  42315. "mmapSize=%lld, mmapSizeMax=%lld\n",
  42316. osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion,
  42317. pFile->mmapSize, pFile->mmapSizeMax));
  42318. if( pFile->pMapRegion ){
  42319. if( !osUnmapViewOfFile(pFile->pMapRegion) ){
  42320. pFile->lastErrno = osGetLastError();
  42321. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, "
  42322. "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile,
  42323. pFile->pMapRegion));
  42324. return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
  42325. "winUnmapfile1", pFile->zPath);
  42326. }
  42327. pFile->pMapRegion = 0;
  42328. pFile->mmapSize = 0;
  42329. }
  42330. if( pFile->hMap!=NULL ){
  42331. if( !osCloseHandle(pFile->hMap) ){
  42332. pFile->lastErrno = osGetLastError();
  42333. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n",
  42334. osGetCurrentProcessId(), pFile, pFile->hMap));
  42335. return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
  42336. "winUnmapfile2", pFile->zPath);
  42337. }
  42338. pFile->hMap = NULL;
  42339. }
  42340. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  42341. osGetCurrentProcessId(), pFile));
  42342. return SQLITE_OK;
  42343. }
  42344. /*
  42345. ** Memory map or remap the file opened by file-descriptor pFd (if the file
  42346. ** is already mapped, the existing mapping is replaced by the new). Or, if
  42347. ** there already exists a mapping for this file, and there are still
  42348. ** outstanding xFetch() references to it, this function is a no-op.
  42349. **
  42350. ** If parameter nByte is non-negative, then it is the requested size of
  42351. ** the mapping to create. Otherwise, if nByte is less than zero, then the
  42352. ** requested size is the size of the file on disk. The actual size of the
  42353. ** created mapping is either the requested size or the value configured
  42354. ** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller.
  42355. **
  42356. ** SQLITE_OK is returned if no error occurs (even if the mapping is not
  42357. ** recreated as a result of outstanding references) or an SQLite error
  42358. ** code otherwise.
  42359. */
  42360. static int winMapfile(winFile *pFd, sqlite3_int64 nByte){
  42361. sqlite3_int64 nMap = nByte;
  42362. int rc;
  42363. assert( nMap>=0 || pFd->nFetchOut==0 );
  42364. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, size=%lld\n",
  42365. osGetCurrentProcessId(), pFd, nByte));
  42366. if( pFd->nFetchOut>0 ) return SQLITE_OK;
  42367. if( nMap<0 ){
  42368. rc = winFileSize((sqlite3_file*)pFd, &nMap);
  42369. if( rc ){
  42370. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n",
  42371. osGetCurrentProcessId(), pFd));
  42372. return SQLITE_IOERR_FSTAT;
  42373. }
  42374. }
  42375. if( nMap>pFd->mmapSizeMax ){
  42376. nMap = pFd->mmapSizeMax;
  42377. }
  42378. nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1);
  42379. if( nMap==0 && pFd->mmapSize>0 ){
  42380. winUnmapfile(pFd);
  42381. }
  42382. if( nMap!=pFd->mmapSize ){
  42383. void *pNew = 0;
  42384. DWORD protect = PAGE_READONLY;
  42385. DWORD flags = FILE_MAP_READ;
  42386. winUnmapfile(pFd);
  42387. #ifdef SQLITE_MMAP_READWRITE
  42388. if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){
  42389. protect = PAGE_READWRITE;
  42390. flags |= FILE_MAP_WRITE;
  42391. }
  42392. #endif
  42393. #if SQLITE_OS_WINRT
  42394. pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL);
  42395. #elif defined(SQLITE_WIN32_HAS_WIDE)
  42396. pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect,
  42397. (DWORD)((nMap>>32) & 0xffffffff),
  42398. (DWORD)(nMap & 0xffffffff), NULL);
  42399. #elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA
  42400. pFd->hMap = osCreateFileMappingA(pFd->h, NULL, protect,
  42401. (DWORD)((nMap>>32) & 0xffffffff),
  42402. (DWORD)(nMap & 0xffffffff), NULL);
  42403. #endif
  42404. if( pFd->hMap==NULL ){
  42405. pFd->lastErrno = osGetLastError();
  42406. rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
  42407. "winMapfile1", pFd->zPath);
  42408. /* Log the error, but continue normal operation using xRead/xWrite */
  42409. OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=%s\n",
  42410. osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
  42411. return SQLITE_OK;
  42412. }
  42413. assert( (nMap % winSysInfo.dwPageSize)==0 );
  42414. assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff );
  42415. #if SQLITE_OS_WINRT
  42416. pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, (SIZE_T)nMap);
  42417. #else
  42418. pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap);
  42419. #endif
  42420. if( pNew==NULL ){
  42421. osCloseHandle(pFd->hMap);
  42422. pFd->hMap = NULL;
  42423. pFd->lastErrno = osGetLastError();
  42424. rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
  42425. "winMapfile2", pFd->zPath);
  42426. /* Log the error, but continue normal operation using xRead/xWrite */
  42427. OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=%s\n",
  42428. osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
  42429. return SQLITE_OK;
  42430. }
  42431. pFd->pMapRegion = pNew;
  42432. pFd->mmapSize = nMap;
  42433. }
  42434. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  42435. osGetCurrentProcessId(), pFd));
  42436. return SQLITE_OK;
  42437. }
  42438. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  42439. /*
  42440. ** If possible, return a pointer to a mapping of file fd starting at offset
  42441. ** iOff. The mapping must be valid for at least nAmt bytes.
  42442. **
  42443. ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
  42444. ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
  42445. ** Finally, if an error does occur, return an SQLite error code. The final
  42446. ** value of *pp is undefined in this case.
  42447. **
  42448. ** If this function does return a pointer, the caller must eventually
  42449. ** release the reference by calling winUnfetch().
  42450. */
  42451. static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
  42452. #if SQLITE_MAX_MMAP_SIZE>0
  42453. winFile *pFd = (winFile*)fd; /* The underlying database file */
  42454. #endif
  42455. *pp = 0;
  42456. OSTRACE(("FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\n",
  42457. osGetCurrentProcessId(), fd, iOff, nAmt, pp));
  42458. #if SQLITE_MAX_MMAP_SIZE>0
  42459. if( pFd->mmapSizeMax>0 ){
  42460. if( pFd->pMapRegion==0 ){
  42461. int rc = winMapfile(pFd, -1);
  42462. if( rc!=SQLITE_OK ){
  42463. OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n",
  42464. osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
  42465. return rc;
  42466. }
  42467. }
  42468. if( pFd->mmapSize >= iOff+nAmt ){
  42469. *pp = &((u8 *)pFd->pMapRegion)[iOff];
  42470. pFd->nFetchOut++;
  42471. }
  42472. }
  42473. #endif
  42474. OSTRACE(("FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\n",
  42475. osGetCurrentProcessId(), fd, pp, *pp));
  42476. return SQLITE_OK;
  42477. }
  42478. /*
  42479. ** If the third argument is non-NULL, then this function releases a
  42480. ** reference obtained by an earlier call to winFetch(). The second
  42481. ** argument passed to this function must be the same as the corresponding
  42482. ** argument that was passed to the winFetch() invocation.
  42483. **
  42484. ** Or, if the third argument is NULL, then this function is being called
  42485. ** to inform the VFS layer that, according to POSIX, any existing mapping
  42486. ** may now be invalid and should be unmapped.
  42487. */
  42488. static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){
  42489. #if SQLITE_MAX_MMAP_SIZE>0
  42490. winFile *pFd = (winFile*)fd; /* The underlying database file */
  42491. /* If p==0 (unmap the entire file) then there must be no outstanding
  42492. ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
  42493. ** then there must be at least one outstanding. */
  42494. assert( (p==0)==(pFd->nFetchOut==0) );
  42495. /* If p!=0, it must match the iOff value. */
  42496. assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
  42497. OSTRACE(("UNFETCH pid=%lu, pFile=%p, offset=%lld, p=%p\n",
  42498. osGetCurrentProcessId(), pFd, iOff, p));
  42499. if( p ){
  42500. pFd->nFetchOut--;
  42501. }else{
  42502. /* FIXME: If Windows truly always prevents truncating or deleting a
  42503. ** file while a mapping is held, then the following winUnmapfile() call
  42504. ** is unnecessary can be omitted - potentially improving
  42505. ** performance. */
  42506. winUnmapfile(pFd);
  42507. }
  42508. assert( pFd->nFetchOut>=0 );
  42509. #endif
  42510. OSTRACE(("UNFETCH pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  42511. osGetCurrentProcessId(), fd));
  42512. return SQLITE_OK;
  42513. }
  42514. /*
  42515. ** Here ends the implementation of all sqlite3_file methods.
  42516. **
  42517. ********************** End sqlite3_file Methods *******************************
  42518. ******************************************************************************/
  42519. /*
  42520. ** This vector defines all the methods that can operate on an
  42521. ** sqlite3_file for win32.
  42522. */
  42523. static const sqlite3_io_methods winIoMethod = {
  42524. 3, /* iVersion */
  42525. winClose, /* xClose */
  42526. winRead, /* xRead */
  42527. winWrite, /* xWrite */
  42528. winTruncate, /* xTruncate */
  42529. winSync, /* xSync */
  42530. winFileSize, /* xFileSize */
  42531. winLock, /* xLock */
  42532. winUnlock, /* xUnlock */
  42533. winCheckReservedLock, /* xCheckReservedLock */
  42534. winFileControl, /* xFileControl */
  42535. winSectorSize, /* xSectorSize */
  42536. winDeviceCharacteristics, /* xDeviceCharacteristics */
  42537. winShmMap, /* xShmMap */
  42538. winShmLock, /* xShmLock */
  42539. winShmBarrier, /* xShmBarrier */
  42540. winShmUnmap, /* xShmUnmap */
  42541. winFetch, /* xFetch */
  42542. winUnfetch /* xUnfetch */
  42543. };
  42544. /*
  42545. ** This vector defines all the methods that can operate on an
  42546. ** sqlite3_file for win32 without performing any locking.
  42547. */
  42548. static const sqlite3_io_methods winIoNolockMethod = {
  42549. 3, /* iVersion */
  42550. winClose, /* xClose */
  42551. winRead, /* xRead */
  42552. winWrite, /* xWrite */
  42553. winTruncate, /* xTruncate */
  42554. winSync, /* xSync */
  42555. winFileSize, /* xFileSize */
  42556. winNolockLock, /* xLock */
  42557. winNolockUnlock, /* xUnlock */
  42558. winNolockCheckReservedLock, /* xCheckReservedLock */
  42559. winFileControl, /* xFileControl */
  42560. winSectorSize, /* xSectorSize */
  42561. winDeviceCharacteristics, /* xDeviceCharacteristics */
  42562. winShmMap, /* xShmMap */
  42563. winShmLock, /* xShmLock */
  42564. winShmBarrier, /* xShmBarrier */
  42565. winShmUnmap, /* xShmUnmap */
  42566. winFetch, /* xFetch */
  42567. winUnfetch /* xUnfetch */
  42568. };
  42569. static winVfsAppData winAppData = {
  42570. &winIoMethod, /* pMethod */
  42571. 0, /* pAppData */
  42572. 0 /* bNoLock */
  42573. };
  42574. static winVfsAppData winNolockAppData = {
  42575. &winIoNolockMethod, /* pMethod */
  42576. 0, /* pAppData */
  42577. 1 /* bNoLock */
  42578. };
  42579. /****************************************************************************
  42580. **************************** sqlite3_vfs methods ****************************
  42581. **
  42582. ** This division contains the implementation of methods on the
  42583. ** sqlite3_vfs object.
  42584. */
  42585. #if defined(__CYGWIN__)
  42586. /*
  42587. ** Convert a filename from whatever the underlying operating system
  42588. ** supports for filenames into UTF-8. Space to hold the result is
  42589. ** obtained from malloc and must be freed by the calling function.
  42590. */
  42591. static char *winConvertToUtf8Filename(const void *zFilename){
  42592. char *zConverted = 0;
  42593. if( osIsNT() ){
  42594. zConverted = winUnicodeToUtf8(zFilename);
  42595. }
  42596. #ifdef SQLITE_WIN32_HAS_ANSI
  42597. else{
  42598. zConverted = winMbcsToUtf8(zFilename, osAreFileApisANSI());
  42599. }
  42600. #endif
  42601. /* caller will handle out of memory */
  42602. return zConverted;
  42603. }
  42604. #endif
  42605. /*
  42606. ** Convert a UTF-8 filename into whatever form the underlying
  42607. ** operating system wants filenames in. Space to hold the result
  42608. ** is obtained from malloc and must be freed by the calling
  42609. ** function.
  42610. */
  42611. static void *winConvertFromUtf8Filename(const char *zFilename){
  42612. void *zConverted = 0;
  42613. if( osIsNT() ){
  42614. zConverted = winUtf8ToUnicode(zFilename);
  42615. }
  42616. #ifdef SQLITE_WIN32_HAS_ANSI
  42617. else{
  42618. zConverted = winUtf8ToMbcs(zFilename, osAreFileApisANSI());
  42619. }
  42620. #endif
  42621. /* caller will handle out of memory */
  42622. return zConverted;
  42623. }
  42624. /*
  42625. ** This function returns non-zero if the specified UTF-8 string buffer
  42626. ** ends with a directory separator character or one was successfully
  42627. ** added to it.
  42628. */
  42629. static int winMakeEndInDirSep(int nBuf, char *zBuf){
  42630. if( zBuf ){
  42631. int nLen = sqlite3Strlen30(zBuf);
  42632. if( nLen>0 ){
  42633. if( winIsDirSep(zBuf[nLen-1]) ){
  42634. return 1;
  42635. }else if( nLen+1<nBuf ){
  42636. zBuf[nLen] = winGetDirSep();
  42637. zBuf[nLen+1] = '\0';
  42638. return 1;
  42639. }
  42640. }
  42641. }
  42642. return 0;
  42643. }
  42644. /*
  42645. ** Create a temporary file name and store the resulting pointer into pzBuf.
  42646. ** The pointer returned in pzBuf must be freed via sqlite3_free().
  42647. */
  42648. static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){
  42649. static char zChars[] =
  42650. "abcdefghijklmnopqrstuvwxyz"
  42651. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  42652. "0123456789";
  42653. size_t i, j;
  42654. int nPre = sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX);
  42655. int nMax, nBuf, nDir, nLen;
  42656. char *zBuf;
  42657. /* It's odd to simulate an io-error here, but really this is just
  42658. ** using the io-error infrastructure to test that SQLite handles this
  42659. ** function failing.
  42660. */
  42661. SimulateIOError( return SQLITE_IOERR );
  42662. /* Allocate a temporary buffer to store the fully qualified file
  42663. ** name for the temporary file. If this fails, we cannot continue.
  42664. */
  42665. nMax = pVfs->mxPathname; nBuf = nMax + 2;
  42666. zBuf = sqlite3MallocZero( nBuf );
  42667. if( !zBuf ){
  42668. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  42669. return SQLITE_IOERR_NOMEM_BKPT;
  42670. }
  42671. /* Figure out the effective temporary directory. First, check if one
  42672. ** has been explicitly set by the application; otherwise, use the one
  42673. ** configured by the operating system.
  42674. */
  42675. nDir = nMax - (nPre + 15);
  42676. assert( nDir>0 );
  42677. if( sqlite3_temp_directory ){
  42678. int nDirLen = sqlite3Strlen30(sqlite3_temp_directory);
  42679. if( nDirLen>0 ){
  42680. if( !winIsDirSep(sqlite3_temp_directory[nDirLen-1]) ){
  42681. nDirLen++;
  42682. }
  42683. if( nDirLen>nDir ){
  42684. sqlite3_free(zBuf);
  42685. OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
  42686. return winLogError(SQLITE_ERROR, 0, "winGetTempname1", 0);
  42687. }
  42688. sqlite3_snprintf(nMax, zBuf, "%s", sqlite3_temp_directory);
  42689. }
  42690. }
  42691. #if defined(__CYGWIN__)
  42692. else{
  42693. static const char *azDirs[] = {
  42694. 0, /* getenv("SQLITE_TMPDIR") */
  42695. 0, /* getenv("TMPDIR") */
  42696. 0, /* getenv("TMP") */
  42697. 0, /* getenv("TEMP") */
  42698. 0, /* getenv("USERPROFILE") */
  42699. "/var/tmp",
  42700. "/usr/tmp",
  42701. "/tmp",
  42702. ".",
  42703. 0 /* List terminator */
  42704. };
  42705. unsigned int i;
  42706. const char *zDir = 0;
  42707. if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
  42708. if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
  42709. if( !azDirs[2] ) azDirs[2] = getenv("TMP");
  42710. if( !azDirs[3] ) azDirs[3] = getenv("TEMP");
  42711. if( !azDirs[4] ) azDirs[4] = getenv("USERPROFILE");
  42712. for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
  42713. void *zConverted;
  42714. if( zDir==0 ) continue;
  42715. /* If the path starts with a drive letter followed by the colon
  42716. ** character, assume it is already a native Win32 path; otherwise,
  42717. ** it must be converted to a native Win32 path via the Cygwin API
  42718. ** prior to using it.
  42719. */
  42720. if( winIsDriveLetterAndColon(zDir) ){
  42721. zConverted = winConvertFromUtf8Filename(zDir);
  42722. if( !zConverted ){
  42723. sqlite3_free(zBuf);
  42724. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  42725. return SQLITE_IOERR_NOMEM_BKPT;
  42726. }
  42727. if( winIsDir(zConverted) ){
  42728. sqlite3_snprintf(nMax, zBuf, "%s", zDir);
  42729. sqlite3_free(zConverted);
  42730. break;
  42731. }
  42732. sqlite3_free(zConverted);
  42733. }else{
  42734. zConverted = sqlite3MallocZero( nMax+1 );
  42735. if( !zConverted ){
  42736. sqlite3_free(zBuf);
  42737. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  42738. return SQLITE_IOERR_NOMEM_BKPT;
  42739. }
  42740. if( cygwin_conv_path(
  42741. osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A, zDir,
  42742. zConverted, nMax+1)<0 ){
  42743. sqlite3_free(zConverted);
  42744. sqlite3_free(zBuf);
  42745. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_CONVPATH\n"));
  42746. return winLogError(SQLITE_IOERR_CONVPATH, (DWORD)errno,
  42747. "winGetTempname2", zDir);
  42748. }
  42749. if( winIsDir(zConverted) ){
  42750. /* At this point, we know the candidate directory exists and should
  42751. ** be used. However, we may need to convert the string containing
  42752. ** its name into UTF-8 (i.e. if it is UTF-16 right now).
  42753. */
  42754. char *zUtf8 = winConvertToUtf8Filename(zConverted);
  42755. if( !zUtf8 ){
  42756. sqlite3_free(zConverted);
  42757. sqlite3_free(zBuf);
  42758. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  42759. return SQLITE_IOERR_NOMEM_BKPT;
  42760. }
  42761. sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
  42762. sqlite3_free(zUtf8);
  42763. sqlite3_free(zConverted);
  42764. break;
  42765. }
  42766. sqlite3_free(zConverted);
  42767. }
  42768. }
  42769. }
  42770. #elif !SQLITE_OS_WINRT && !defined(__CYGWIN__)
  42771. else if( osIsNT() ){
  42772. char *zMulti;
  42773. LPWSTR zWidePath = sqlite3MallocZero( nMax*sizeof(WCHAR) );
  42774. if( !zWidePath ){
  42775. sqlite3_free(zBuf);
  42776. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  42777. return SQLITE_IOERR_NOMEM_BKPT;
  42778. }
  42779. if( osGetTempPathW(nMax, zWidePath)==0 ){
  42780. sqlite3_free(zWidePath);
  42781. sqlite3_free(zBuf);
  42782. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
  42783. return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
  42784. "winGetTempname2", 0);
  42785. }
  42786. zMulti = winUnicodeToUtf8(zWidePath);
  42787. if( zMulti ){
  42788. sqlite3_snprintf(nMax, zBuf, "%s", zMulti);
  42789. sqlite3_free(zMulti);
  42790. sqlite3_free(zWidePath);
  42791. }else{
  42792. sqlite3_free(zWidePath);
  42793. sqlite3_free(zBuf);
  42794. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  42795. return SQLITE_IOERR_NOMEM_BKPT;
  42796. }
  42797. }
  42798. #ifdef SQLITE_WIN32_HAS_ANSI
  42799. else{
  42800. char *zUtf8;
  42801. char *zMbcsPath = sqlite3MallocZero( nMax );
  42802. if( !zMbcsPath ){
  42803. sqlite3_free(zBuf);
  42804. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  42805. return SQLITE_IOERR_NOMEM_BKPT;
  42806. }
  42807. if( osGetTempPathA(nMax, zMbcsPath)==0 ){
  42808. sqlite3_free(zBuf);
  42809. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
  42810. return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
  42811. "winGetTempname3", 0);
  42812. }
  42813. zUtf8 = winMbcsToUtf8(zMbcsPath, osAreFileApisANSI());
  42814. if( zUtf8 ){
  42815. sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
  42816. sqlite3_free(zUtf8);
  42817. }else{
  42818. sqlite3_free(zBuf);
  42819. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  42820. return SQLITE_IOERR_NOMEM_BKPT;
  42821. }
  42822. }
  42823. #endif /* SQLITE_WIN32_HAS_ANSI */
  42824. #endif /* !SQLITE_OS_WINRT */
  42825. /*
  42826. ** Check to make sure the temporary directory ends with an appropriate
  42827. ** separator. If it does not and there is not enough space left to add
  42828. ** one, fail.
  42829. */
  42830. if( !winMakeEndInDirSep(nDir+1, zBuf) ){
  42831. sqlite3_free(zBuf);
  42832. OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
  42833. return winLogError(SQLITE_ERROR, 0, "winGetTempname4", 0);
  42834. }
  42835. /*
  42836. ** Check that the output buffer is large enough for the temporary file
  42837. ** name in the following format:
  42838. **
  42839. ** "<temporary_directory>/etilqs_XXXXXXXXXXXXXXX\0\0"
  42840. **
  42841. ** If not, return SQLITE_ERROR. The number 17 is used here in order to
  42842. ** account for the space used by the 15 character random suffix and the
  42843. ** two trailing NUL characters. The final directory separator character
  42844. ** has already added if it was not already present.
  42845. */
  42846. nLen = sqlite3Strlen30(zBuf);
  42847. if( (nLen + nPre + 17) > nBuf ){
  42848. sqlite3_free(zBuf);
  42849. OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
  42850. return winLogError(SQLITE_ERROR, 0, "winGetTempname5", 0);
  42851. }
  42852. sqlite3_snprintf(nBuf-16-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX);
  42853. j = sqlite3Strlen30(zBuf);
  42854. sqlite3_randomness(15, &zBuf[j]);
  42855. for(i=0; i<15; i++, j++){
  42856. zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
  42857. }
  42858. zBuf[j] = 0;
  42859. zBuf[j+1] = 0;
  42860. *pzBuf = zBuf;
  42861. OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf));
  42862. return SQLITE_OK;
  42863. }
  42864. /*
  42865. ** Return TRUE if the named file is really a directory. Return false if
  42866. ** it is something other than a directory, or if there is any kind of memory
  42867. ** allocation failure.
  42868. */
  42869. static int winIsDir(const void *zConverted){
  42870. DWORD attr;
  42871. int rc = 0;
  42872. DWORD lastErrno;
  42873. if( osIsNT() ){
  42874. int cnt = 0;
  42875. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  42876. memset(&sAttrData, 0, sizeof(sAttrData));
  42877. while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
  42878. GetFileExInfoStandard,
  42879. &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
  42880. if( !rc ){
  42881. return 0; /* Invalid name? */
  42882. }
  42883. attr = sAttrData.dwFileAttributes;
  42884. #if SQLITE_OS_WINCE==0
  42885. }else{
  42886. attr = osGetFileAttributesA((char*)zConverted);
  42887. #endif
  42888. }
  42889. return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);
  42890. }
  42891. /* forward reference */
  42892. static int winAccess(
  42893. sqlite3_vfs *pVfs, /* Not used on win32 */
  42894. const char *zFilename, /* Name of file to check */
  42895. int flags, /* Type of test to make on this file */
  42896. int *pResOut /* OUT: Result */
  42897. );
  42898. /*
  42899. ** Open a file.
  42900. */
  42901. static int winOpen(
  42902. sqlite3_vfs *pVfs, /* Used to get maximum path length and AppData */
  42903. const char *zName, /* Name of the file (UTF-8) */
  42904. sqlite3_file *id, /* Write the SQLite file handle here */
  42905. int flags, /* Open mode flags */
  42906. int *pOutFlags /* Status return flags */
  42907. ){
  42908. HANDLE h;
  42909. DWORD lastErrno = 0;
  42910. DWORD dwDesiredAccess;
  42911. DWORD dwShareMode;
  42912. DWORD dwCreationDisposition;
  42913. DWORD dwFlagsAndAttributes = 0;
  42914. #if SQLITE_OS_WINCE
  42915. int isTemp = 0;
  42916. #endif
  42917. winVfsAppData *pAppData;
  42918. winFile *pFile = (winFile*)id;
  42919. void *zConverted; /* Filename in OS encoding */
  42920. const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
  42921. int cnt = 0;
  42922. /* If argument zPath is a NULL pointer, this function is required to open
  42923. ** a temporary file. Use this buffer to store the file name in.
  42924. */
  42925. char *zTmpname = 0; /* For temporary filename, if necessary. */
  42926. int rc = SQLITE_OK; /* Function Return Code */
  42927. #if !defined(NDEBUG) || SQLITE_OS_WINCE
  42928. int eType = flags&0xFFFFFF00; /* Type of file to open */
  42929. #endif
  42930. int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
  42931. int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
  42932. int isCreate = (flags & SQLITE_OPEN_CREATE);
  42933. int isReadonly = (flags & SQLITE_OPEN_READONLY);
  42934. int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
  42935. #ifndef NDEBUG
  42936. int isOpenJournal = (isCreate && (
  42937. eType==SQLITE_OPEN_MASTER_JOURNAL
  42938. || eType==SQLITE_OPEN_MAIN_JOURNAL
  42939. || eType==SQLITE_OPEN_WAL
  42940. ));
  42941. #endif
  42942. OSTRACE(("OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\n",
  42943. zUtf8Name, id, flags, pOutFlags));
  42944. /* Check the following statements are true:
  42945. **
  42946. ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
  42947. ** (b) if CREATE is set, then READWRITE must also be set, and
  42948. ** (c) if EXCLUSIVE is set, then CREATE must also be set.
  42949. ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
  42950. */
  42951. assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
  42952. assert(isCreate==0 || isReadWrite);
  42953. assert(isExclusive==0 || isCreate);
  42954. assert(isDelete==0 || isCreate);
  42955. /* The main DB, main journal, WAL file and master journal are never
  42956. ** automatically deleted. Nor are they ever temporary files. */
  42957. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
  42958. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
  42959. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
  42960. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
  42961. /* Assert that the upper layer has set one of the "file-type" flags. */
  42962. assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
  42963. || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
  42964. || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
  42965. || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
  42966. );
  42967. assert( pFile!=0 );
  42968. memset(pFile, 0, sizeof(winFile));
  42969. pFile->h = INVALID_HANDLE_VALUE;
  42970. #if SQLITE_OS_WINRT
  42971. if( !zUtf8Name && !sqlite3_temp_directory ){
  42972. sqlite3_log(SQLITE_ERROR,
  42973. "sqlite3_temp_directory variable should be set for WinRT");
  42974. }
  42975. #endif
  42976. /* If the second argument to this function is NULL, generate a
  42977. ** temporary file name to use
  42978. */
  42979. if( !zUtf8Name ){
  42980. assert( isDelete && !isOpenJournal );
  42981. rc = winGetTempname(pVfs, &zTmpname);
  42982. if( rc!=SQLITE_OK ){
  42983. OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc)));
  42984. return rc;
  42985. }
  42986. zUtf8Name = zTmpname;
  42987. }
  42988. /* Database filenames are double-zero terminated if they are not
  42989. ** URIs with parameters. Hence, they can always be passed into
  42990. ** sqlite3_uri_parameter().
  42991. */
  42992. assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
  42993. zUtf8Name[sqlite3Strlen30(zUtf8Name)+1]==0 );
  42994. /* Convert the filename to the system encoding. */
  42995. zConverted = winConvertFromUtf8Filename(zUtf8Name);
  42996. if( zConverted==0 ){
  42997. sqlite3_free(zTmpname);
  42998. OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name));
  42999. return SQLITE_IOERR_NOMEM_BKPT;
  43000. }
  43001. if( winIsDir(zConverted) ){
  43002. sqlite3_free(zConverted);
  43003. sqlite3_free(zTmpname);
  43004. OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name));
  43005. return SQLITE_CANTOPEN_ISDIR;
  43006. }
  43007. if( isReadWrite ){
  43008. dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
  43009. }else{
  43010. dwDesiredAccess = GENERIC_READ;
  43011. }
  43012. /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
  43013. ** created. SQLite doesn't use it to indicate "exclusive access"
  43014. ** as it is usually understood.
  43015. */
  43016. if( isExclusive ){
  43017. /* Creates a new file, only if it does not already exist. */
  43018. /* If the file exists, it fails. */
  43019. dwCreationDisposition = CREATE_NEW;
  43020. }else if( isCreate ){
  43021. /* Open existing file, or create if it doesn't exist */
  43022. dwCreationDisposition = OPEN_ALWAYS;
  43023. }else{
  43024. /* Opens a file, only if it exists. */
  43025. dwCreationDisposition = OPEN_EXISTING;
  43026. }
  43027. dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
  43028. if( isDelete ){
  43029. #if SQLITE_OS_WINCE
  43030. dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
  43031. isTemp = 1;
  43032. #else
  43033. dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
  43034. | FILE_ATTRIBUTE_HIDDEN
  43035. | FILE_FLAG_DELETE_ON_CLOSE;
  43036. #endif
  43037. }else{
  43038. dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
  43039. }
  43040. /* Reports from the internet are that performance is always
  43041. ** better if FILE_FLAG_RANDOM_ACCESS is used. Ticket #2699. */
  43042. #if SQLITE_OS_WINCE
  43043. dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
  43044. #endif
  43045. if( osIsNT() ){
  43046. #if SQLITE_OS_WINRT
  43047. CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
  43048. extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
  43049. extendedParameters.dwFileAttributes =
  43050. dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;
  43051. extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;
  43052. extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
  43053. extendedParameters.lpSecurityAttributes = NULL;
  43054. extendedParameters.hTemplateFile = NULL;
  43055. do{
  43056. h = osCreateFile2((LPCWSTR)zConverted,
  43057. dwDesiredAccess,
  43058. dwShareMode,
  43059. dwCreationDisposition,
  43060. &extendedParameters);
  43061. if( h!=INVALID_HANDLE_VALUE ) break;
  43062. if( isReadWrite ){
  43063. int rc2, isRO = 0;
  43064. sqlite3BeginBenignMalloc();
  43065. rc2 = winAccess(pVfs, zName, SQLITE_ACCESS_READ, &isRO);
  43066. sqlite3EndBenignMalloc();
  43067. if( rc2==SQLITE_OK && isRO ) break;
  43068. }
  43069. }while( winRetryIoerr(&cnt, &lastErrno) );
  43070. #else
  43071. do{
  43072. h = osCreateFileW((LPCWSTR)zConverted,
  43073. dwDesiredAccess,
  43074. dwShareMode, NULL,
  43075. dwCreationDisposition,
  43076. dwFlagsAndAttributes,
  43077. NULL);
  43078. if( h!=INVALID_HANDLE_VALUE ) break;
  43079. if( isReadWrite ){
  43080. int rc2, isRO = 0;
  43081. sqlite3BeginBenignMalloc();
  43082. rc2 = winAccess(pVfs, zName, SQLITE_ACCESS_READ, &isRO);
  43083. sqlite3EndBenignMalloc();
  43084. if( rc2==SQLITE_OK && isRO ) break;
  43085. }
  43086. }while( winRetryIoerr(&cnt, &lastErrno) );
  43087. #endif
  43088. }
  43089. #ifdef SQLITE_WIN32_HAS_ANSI
  43090. else{
  43091. do{
  43092. h = osCreateFileA((LPCSTR)zConverted,
  43093. dwDesiredAccess,
  43094. dwShareMode, NULL,
  43095. dwCreationDisposition,
  43096. dwFlagsAndAttributes,
  43097. NULL);
  43098. if( h!=INVALID_HANDLE_VALUE ) break;
  43099. if( isReadWrite ){
  43100. int rc2, isRO = 0;
  43101. sqlite3BeginBenignMalloc();
  43102. rc2 = winAccess(pVfs, zName, SQLITE_ACCESS_READ, &isRO);
  43103. sqlite3EndBenignMalloc();
  43104. if( rc2==SQLITE_OK && isRO ) break;
  43105. }
  43106. }while( winRetryIoerr(&cnt, &lastErrno) );
  43107. }
  43108. #endif
  43109. winLogIoerr(cnt, __LINE__);
  43110. OSTRACE(("OPEN file=%p, name=%s, access=%lx, rc=%s\n", h, zUtf8Name,
  43111. dwDesiredAccess, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
  43112. if( h==INVALID_HANDLE_VALUE ){
  43113. sqlite3_free(zConverted);
  43114. sqlite3_free(zTmpname);
  43115. if( isReadWrite && !isExclusive ){
  43116. return winOpen(pVfs, zName, id,
  43117. ((flags|SQLITE_OPEN_READONLY) &
  43118. ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
  43119. pOutFlags);
  43120. }else{
  43121. pFile->lastErrno = lastErrno;
  43122. winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
  43123. return SQLITE_CANTOPEN_BKPT;
  43124. }
  43125. }
  43126. if( pOutFlags ){
  43127. if( isReadWrite ){
  43128. *pOutFlags = SQLITE_OPEN_READWRITE;
  43129. }else{
  43130. *pOutFlags = SQLITE_OPEN_READONLY;
  43131. }
  43132. }
  43133. OSTRACE(("OPEN file=%p, name=%s, access=%lx, pOutFlags=%p, *pOutFlags=%d, "
  43134. "rc=%s\n", h, zUtf8Name, dwDesiredAccess, pOutFlags, pOutFlags ?
  43135. *pOutFlags : 0, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
  43136. pAppData = (winVfsAppData*)pVfs->pAppData;
  43137. #if SQLITE_OS_WINCE
  43138. {
  43139. if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
  43140. && ((pAppData==NULL) || !pAppData->bNoLock)
  43141. && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK
  43142. ){
  43143. osCloseHandle(h);
  43144. sqlite3_free(zConverted);
  43145. sqlite3_free(zTmpname);
  43146. OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc)));
  43147. return rc;
  43148. }
  43149. }
  43150. if( isTemp ){
  43151. pFile->zDeleteOnClose = zConverted;
  43152. }else
  43153. #endif
  43154. {
  43155. sqlite3_free(zConverted);
  43156. }
  43157. sqlite3_free(zTmpname);
  43158. pFile->pMethod = pAppData ? pAppData->pMethod : &winIoMethod;
  43159. pFile->pVfs = pVfs;
  43160. pFile->h = h;
  43161. if( isReadonly ){
  43162. pFile->ctrlFlags |= WINFILE_RDONLY;
  43163. }
  43164. if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
  43165. pFile->ctrlFlags |= WINFILE_PSOW;
  43166. }
  43167. pFile->lastErrno = NO_ERROR;
  43168. pFile->zPath = zName;
  43169. #if SQLITE_MAX_MMAP_SIZE>0
  43170. pFile->hMap = NULL;
  43171. pFile->pMapRegion = 0;
  43172. pFile->mmapSize = 0;
  43173. pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap;
  43174. #endif
  43175. OpenCounter(+1);
  43176. return rc;
  43177. }
  43178. /*
  43179. ** Delete the named file.
  43180. **
  43181. ** Note that Windows does not allow a file to be deleted if some other
  43182. ** process has it open. Sometimes a virus scanner or indexing program
  43183. ** will open a journal file shortly after it is created in order to do
  43184. ** whatever it does. While this other process is holding the
  43185. ** file open, we will be unable to delete it. To work around this
  43186. ** problem, we delay 100 milliseconds and try to delete again. Up
  43187. ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
  43188. ** up and returning an error.
  43189. */
  43190. static int winDelete(
  43191. sqlite3_vfs *pVfs, /* Not used on win32 */
  43192. const char *zFilename, /* Name of file to delete */
  43193. int syncDir /* Not used on win32 */
  43194. ){
  43195. int cnt = 0;
  43196. int rc;
  43197. DWORD attr;
  43198. DWORD lastErrno = 0;
  43199. void *zConverted;
  43200. UNUSED_PARAMETER(pVfs);
  43201. UNUSED_PARAMETER(syncDir);
  43202. SimulateIOError(return SQLITE_IOERR_DELETE);
  43203. OSTRACE(("DELETE name=%s, syncDir=%d\n", zFilename, syncDir));
  43204. zConverted = winConvertFromUtf8Filename(zFilename);
  43205. if( zConverted==0 ){
  43206. OSTRACE(("DELETE name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
  43207. return SQLITE_IOERR_NOMEM_BKPT;
  43208. }
  43209. if( osIsNT() ){
  43210. do {
  43211. #if SQLITE_OS_WINRT
  43212. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  43213. memset(&sAttrData, 0, sizeof(sAttrData));
  43214. if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
  43215. &sAttrData) ){
  43216. attr = sAttrData.dwFileAttributes;
  43217. }else{
  43218. lastErrno = osGetLastError();
  43219. if( lastErrno==ERROR_FILE_NOT_FOUND
  43220. || lastErrno==ERROR_PATH_NOT_FOUND ){
  43221. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  43222. }else{
  43223. rc = SQLITE_ERROR;
  43224. }
  43225. break;
  43226. }
  43227. #else
  43228. attr = osGetFileAttributesW(zConverted);
  43229. #endif
  43230. if ( attr==INVALID_FILE_ATTRIBUTES ){
  43231. lastErrno = osGetLastError();
  43232. if( lastErrno==ERROR_FILE_NOT_FOUND
  43233. || lastErrno==ERROR_PATH_NOT_FOUND ){
  43234. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  43235. }else{
  43236. rc = SQLITE_ERROR;
  43237. }
  43238. break;
  43239. }
  43240. if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
  43241. rc = SQLITE_ERROR; /* Files only. */
  43242. break;
  43243. }
  43244. if ( osDeleteFileW(zConverted) ){
  43245. rc = SQLITE_OK; /* Deleted OK. */
  43246. break;
  43247. }
  43248. if ( !winRetryIoerr(&cnt, &lastErrno) ){
  43249. rc = SQLITE_ERROR; /* No more retries. */
  43250. break;
  43251. }
  43252. } while(1);
  43253. }
  43254. #ifdef SQLITE_WIN32_HAS_ANSI
  43255. else{
  43256. do {
  43257. attr = osGetFileAttributesA(zConverted);
  43258. if ( attr==INVALID_FILE_ATTRIBUTES ){
  43259. lastErrno = osGetLastError();
  43260. if( lastErrno==ERROR_FILE_NOT_FOUND
  43261. || lastErrno==ERROR_PATH_NOT_FOUND ){
  43262. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  43263. }else{
  43264. rc = SQLITE_ERROR;
  43265. }
  43266. break;
  43267. }
  43268. if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
  43269. rc = SQLITE_ERROR; /* Files only. */
  43270. break;
  43271. }
  43272. if ( osDeleteFileA(zConverted) ){
  43273. rc = SQLITE_OK; /* Deleted OK. */
  43274. break;
  43275. }
  43276. if ( !winRetryIoerr(&cnt, &lastErrno) ){
  43277. rc = SQLITE_ERROR; /* No more retries. */
  43278. break;
  43279. }
  43280. } while(1);
  43281. }
  43282. #endif
  43283. if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){
  43284. rc = winLogError(SQLITE_IOERR_DELETE, lastErrno, "winDelete", zFilename);
  43285. }else{
  43286. winLogIoerr(cnt, __LINE__);
  43287. }
  43288. sqlite3_free(zConverted);
  43289. OSTRACE(("DELETE name=%s, rc=%s\n", zFilename, sqlite3ErrName(rc)));
  43290. return rc;
  43291. }
  43292. /*
  43293. ** Check the existence and status of a file.
  43294. */
  43295. static int winAccess(
  43296. sqlite3_vfs *pVfs, /* Not used on win32 */
  43297. const char *zFilename, /* Name of file to check */
  43298. int flags, /* Type of test to make on this file */
  43299. int *pResOut /* OUT: Result */
  43300. ){
  43301. DWORD attr;
  43302. int rc = 0;
  43303. DWORD lastErrno = 0;
  43304. void *zConverted;
  43305. UNUSED_PARAMETER(pVfs);
  43306. SimulateIOError( return SQLITE_IOERR_ACCESS; );
  43307. OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n",
  43308. zFilename, flags, pResOut));
  43309. zConverted = winConvertFromUtf8Filename(zFilename);
  43310. if( zConverted==0 ){
  43311. OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
  43312. return SQLITE_IOERR_NOMEM_BKPT;
  43313. }
  43314. if( osIsNT() ){
  43315. int cnt = 0;
  43316. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  43317. memset(&sAttrData, 0, sizeof(sAttrData));
  43318. while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
  43319. GetFileExInfoStandard,
  43320. &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
  43321. if( rc ){
  43322. /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
  43323. ** as if it does not exist.
  43324. */
  43325. if( flags==SQLITE_ACCESS_EXISTS
  43326. && sAttrData.nFileSizeHigh==0
  43327. && sAttrData.nFileSizeLow==0 ){
  43328. attr = INVALID_FILE_ATTRIBUTES;
  43329. }else{
  43330. attr = sAttrData.dwFileAttributes;
  43331. }
  43332. }else{
  43333. winLogIoerr(cnt, __LINE__);
  43334. if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){
  43335. sqlite3_free(zConverted);
  43336. return winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess",
  43337. zFilename);
  43338. }else{
  43339. attr = INVALID_FILE_ATTRIBUTES;
  43340. }
  43341. }
  43342. }
  43343. #ifdef SQLITE_WIN32_HAS_ANSI
  43344. else{
  43345. attr = osGetFileAttributesA((char*)zConverted);
  43346. }
  43347. #endif
  43348. sqlite3_free(zConverted);
  43349. switch( flags ){
  43350. case SQLITE_ACCESS_READ:
  43351. case SQLITE_ACCESS_EXISTS:
  43352. rc = attr!=INVALID_FILE_ATTRIBUTES;
  43353. break;
  43354. case SQLITE_ACCESS_READWRITE:
  43355. rc = attr!=INVALID_FILE_ATTRIBUTES &&
  43356. (attr & FILE_ATTRIBUTE_READONLY)==0;
  43357. break;
  43358. default:
  43359. assert(!"Invalid flags argument");
  43360. }
  43361. *pResOut = rc;
  43362. OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
  43363. zFilename, pResOut, *pResOut));
  43364. return SQLITE_OK;
  43365. }
  43366. /*
  43367. ** Returns non-zero if the specified path name starts with a drive letter
  43368. ** followed by a colon character.
  43369. */
  43370. static BOOL winIsDriveLetterAndColon(
  43371. const char *zPathname
  43372. ){
  43373. return ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' );
  43374. }
  43375. /*
  43376. ** Returns non-zero if the specified path name should be used verbatim. If
  43377. ** non-zero is returned from this function, the calling function must simply
  43378. ** use the provided path name verbatim -OR- resolve it into a full path name
  43379. ** using the GetFullPathName Win32 API function (if available).
  43380. */
  43381. static BOOL winIsVerbatimPathname(
  43382. const char *zPathname
  43383. ){
  43384. /*
  43385. ** If the path name starts with a forward slash or a backslash, it is either
  43386. ** a legal UNC name, a volume relative path, or an absolute path name in the
  43387. ** "Unix" format on Windows. There is no easy way to differentiate between
  43388. ** the final two cases; therefore, we return the safer return value of TRUE
  43389. ** so that callers of this function will simply use it verbatim.
  43390. */
  43391. if ( winIsDirSep(zPathname[0]) ){
  43392. return TRUE;
  43393. }
  43394. /*
  43395. ** If the path name starts with a letter and a colon it is either a volume
  43396. ** relative path or an absolute path. Callers of this function must not
  43397. ** attempt to treat it as a relative path name (i.e. they should simply use
  43398. ** it verbatim).
  43399. */
  43400. if ( winIsDriveLetterAndColon(zPathname) ){
  43401. return TRUE;
  43402. }
  43403. /*
  43404. ** If we get to this point, the path name should almost certainly be a purely
  43405. ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
  43406. */
  43407. return FALSE;
  43408. }
  43409. /*
  43410. ** Turn a relative pathname into a full pathname. Write the full
  43411. ** pathname into zOut[]. zOut[] will be at least pVfs->mxPathname
  43412. ** bytes in size.
  43413. */
  43414. static int winFullPathname(
  43415. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  43416. const char *zRelative, /* Possibly relative input path */
  43417. int nFull, /* Size of output buffer in bytes */
  43418. char *zFull /* Output buffer */
  43419. ){
  43420. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
  43421. DWORD nByte;
  43422. void *zConverted;
  43423. char *zOut;
  43424. #endif
  43425. /* If this path name begins with "/X:", where "X" is any alphabetic
  43426. ** character, discard the initial "/" from the pathname.
  43427. */
  43428. if( zRelative[0]=='/' && winIsDriveLetterAndColon(zRelative+1) ){
  43429. zRelative++;
  43430. }
  43431. #if defined(__CYGWIN__)
  43432. SimulateIOError( return SQLITE_ERROR );
  43433. UNUSED_PARAMETER(nFull);
  43434. assert( nFull>=pVfs->mxPathname );
  43435. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  43436. /*
  43437. ** NOTE: We are dealing with a relative path name and the data
  43438. ** directory has been set. Therefore, use it as the basis
  43439. ** for converting the relative path name to an absolute
  43440. ** one by prepending the data directory and a slash.
  43441. */
  43442. char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
  43443. if( !zOut ){
  43444. return SQLITE_IOERR_NOMEM_BKPT;
  43445. }
  43446. if( cygwin_conv_path(
  43447. (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A) |
  43448. CCP_RELATIVE, zRelative, zOut, pVfs->mxPathname+1)<0 ){
  43449. sqlite3_free(zOut);
  43450. return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
  43451. "winFullPathname1", zRelative);
  43452. }else{
  43453. char *zUtf8 = winConvertToUtf8Filename(zOut);
  43454. if( !zUtf8 ){
  43455. sqlite3_free(zOut);
  43456. return SQLITE_IOERR_NOMEM_BKPT;
  43457. }
  43458. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
  43459. sqlite3_data_directory, winGetDirSep(), zUtf8);
  43460. sqlite3_free(zUtf8);
  43461. sqlite3_free(zOut);
  43462. }
  43463. }else{
  43464. char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
  43465. if( !zOut ){
  43466. return SQLITE_IOERR_NOMEM_BKPT;
  43467. }
  43468. if( cygwin_conv_path(
  43469. (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A),
  43470. zRelative, zOut, pVfs->mxPathname+1)<0 ){
  43471. sqlite3_free(zOut);
  43472. return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
  43473. "winFullPathname2", zRelative);
  43474. }else{
  43475. char *zUtf8 = winConvertToUtf8Filename(zOut);
  43476. if( !zUtf8 ){
  43477. sqlite3_free(zOut);
  43478. return SQLITE_IOERR_NOMEM_BKPT;
  43479. }
  43480. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zUtf8);
  43481. sqlite3_free(zUtf8);
  43482. sqlite3_free(zOut);
  43483. }
  43484. }
  43485. return SQLITE_OK;
  43486. #endif
  43487. #if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
  43488. SimulateIOError( return SQLITE_ERROR );
  43489. /* WinCE has no concept of a relative pathname, or so I am told. */
  43490. /* WinRT has no way to convert a relative path to an absolute one. */
  43491. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  43492. /*
  43493. ** NOTE: We are dealing with a relative path name and the data
  43494. ** directory has been set. Therefore, use it as the basis
  43495. ** for converting the relative path name to an absolute
  43496. ** one by prepending the data directory and a backslash.
  43497. */
  43498. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
  43499. sqlite3_data_directory, winGetDirSep(), zRelative);
  43500. }else{
  43501. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
  43502. }
  43503. return SQLITE_OK;
  43504. #endif
  43505. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
  43506. /* It's odd to simulate an io-error here, but really this is just
  43507. ** using the io-error infrastructure to test that SQLite handles this
  43508. ** function failing. This function could fail if, for example, the
  43509. ** current working directory has been unlinked.
  43510. */
  43511. SimulateIOError( return SQLITE_ERROR );
  43512. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  43513. /*
  43514. ** NOTE: We are dealing with a relative path name and the data
  43515. ** directory has been set. Therefore, use it as the basis
  43516. ** for converting the relative path name to an absolute
  43517. ** one by prepending the data directory and a backslash.
  43518. */
  43519. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
  43520. sqlite3_data_directory, winGetDirSep(), zRelative);
  43521. return SQLITE_OK;
  43522. }
  43523. zConverted = winConvertFromUtf8Filename(zRelative);
  43524. if( zConverted==0 ){
  43525. return SQLITE_IOERR_NOMEM_BKPT;
  43526. }
  43527. if( osIsNT() ){
  43528. LPWSTR zTemp;
  43529. nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0);
  43530. if( nByte==0 ){
  43531. sqlite3_free(zConverted);
  43532. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  43533. "winFullPathname1", zRelative);
  43534. }
  43535. nByte += 3;
  43536. zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
  43537. if( zTemp==0 ){
  43538. sqlite3_free(zConverted);
  43539. return SQLITE_IOERR_NOMEM_BKPT;
  43540. }
  43541. nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
  43542. if( nByte==0 ){
  43543. sqlite3_free(zConverted);
  43544. sqlite3_free(zTemp);
  43545. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  43546. "winFullPathname2", zRelative);
  43547. }
  43548. sqlite3_free(zConverted);
  43549. zOut = winUnicodeToUtf8(zTemp);
  43550. sqlite3_free(zTemp);
  43551. }
  43552. #ifdef SQLITE_WIN32_HAS_ANSI
  43553. else{
  43554. char *zTemp;
  43555. nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0);
  43556. if( nByte==0 ){
  43557. sqlite3_free(zConverted);
  43558. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  43559. "winFullPathname3", zRelative);
  43560. }
  43561. nByte += 3;
  43562. zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
  43563. if( zTemp==0 ){
  43564. sqlite3_free(zConverted);
  43565. return SQLITE_IOERR_NOMEM_BKPT;
  43566. }
  43567. nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
  43568. if( nByte==0 ){
  43569. sqlite3_free(zConverted);
  43570. sqlite3_free(zTemp);
  43571. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  43572. "winFullPathname4", zRelative);
  43573. }
  43574. sqlite3_free(zConverted);
  43575. zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI());
  43576. sqlite3_free(zTemp);
  43577. }
  43578. #endif
  43579. if( zOut ){
  43580. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
  43581. sqlite3_free(zOut);
  43582. return SQLITE_OK;
  43583. }else{
  43584. return SQLITE_IOERR_NOMEM_BKPT;
  43585. }
  43586. #endif
  43587. }
  43588. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  43589. /*
  43590. ** Interfaces for opening a shared library, finding entry points
  43591. ** within the shared library, and closing the shared library.
  43592. */
  43593. static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
  43594. HANDLE h;
  43595. #if defined(__CYGWIN__)
  43596. int nFull = pVfs->mxPathname+1;
  43597. char *zFull = sqlite3MallocZero( nFull );
  43598. void *zConverted = 0;
  43599. if( zFull==0 ){
  43600. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
  43601. return 0;
  43602. }
  43603. if( winFullPathname(pVfs, zFilename, nFull, zFull)!=SQLITE_OK ){
  43604. sqlite3_free(zFull);
  43605. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
  43606. return 0;
  43607. }
  43608. zConverted = winConvertFromUtf8Filename(zFull);
  43609. sqlite3_free(zFull);
  43610. #else
  43611. void *zConverted = winConvertFromUtf8Filename(zFilename);
  43612. UNUSED_PARAMETER(pVfs);
  43613. #endif
  43614. if( zConverted==0 ){
  43615. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
  43616. return 0;
  43617. }
  43618. if( osIsNT() ){
  43619. #if SQLITE_OS_WINRT
  43620. h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
  43621. #else
  43622. h = osLoadLibraryW((LPCWSTR)zConverted);
  43623. #endif
  43624. }
  43625. #ifdef SQLITE_WIN32_HAS_ANSI
  43626. else{
  43627. h = osLoadLibraryA((char*)zConverted);
  43628. }
  43629. #endif
  43630. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)h));
  43631. sqlite3_free(zConverted);
  43632. return (void*)h;
  43633. }
  43634. static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
  43635. UNUSED_PARAMETER(pVfs);
  43636. winGetLastErrorMsg(osGetLastError(), nBuf, zBufOut);
  43637. }
  43638. static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){
  43639. FARPROC proc;
  43640. UNUSED_PARAMETER(pVfs);
  43641. proc = osGetProcAddressA((HANDLE)pH, zSym);
  43642. OSTRACE(("DLSYM handle=%p, symbol=%s, address=%p\n",
  43643. (void*)pH, zSym, (void*)proc));
  43644. return (void(*)(void))proc;
  43645. }
  43646. static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
  43647. UNUSED_PARAMETER(pVfs);
  43648. osFreeLibrary((HANDLE)pHandle);
  43649. OSTRACE(("DLCLOSE handle=%p\n", (void*)pHandle));
  43650. }
  43651. #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  43652. #define winDlOpen 0
  43653. #define winDlError 0
  43654. #define winDlSym 0
  43655. #define winDlClose 0
  43656. #endif
  43657. /* State information for the randomness gatherer. */
  43658. typedef struct EntropyGatherer EntropyGatherer;
  43659. struct EntropyGatherer {
  43660. unsigned char *a; /* Gather entropy into this buffer */
  43661. int na; /* Size of a[] in bytes */
  43662. int i; /* XOR next input into a[i] */
  43663. int nXor; /* Number of XOR operations done */
  43664. };
  43665. #if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
  43666. /* Mix sz bytes of entropy into p. */
  43667. static void xorMemory(EntropyGatherer *p, unsigned char *x, int sz){
  43668. int j, k;
  43669. for(j=0, k=p->i; j<sz; j++){
  43670. p->a[k++] ^= x[j];
  43671. if( k>=p->na ) k = 0;
  43672. }
  43673. p->i = k;
  43674. p->nXor += sz;
  43675. }
  43676. #endif /* !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS) */
  43677. /*
  43678. ** Write up to nBuf bytes of randomness into zBuf.
  43679. */
  43680. static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  43681. #if defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS)
  43682. UNUSED_PARAMETER(pVfs);
  43683. memset(zBuf, 0, nBuf);
  43684. return nBuf;
  43685. #else
  43686. EntropyGatherer e;
  43687. UNUSED_PARAMETER(pVfs);
  43688. memset(zBuf, 0, nBuf);
  43689. e.a = (unsigned char*)zBuf;
  43690. e.na = nBuf;
  43691. e.nXor = 0;
  43692. e.i = 0;
  43693. {
  43694. SYSTEMTIME x;
  43695. osGetSystemTime(&x);
  43696. xorMemory(&e, (unsigned char*)&x, sizeof(SYSTEMTIME));
  43697. }
  43698. {
  43699. DWORD pid = osGetCurrentProcessId();
  43700. xorMemory(&e, (unsigned char*)&pid, sizeof(DWORD));
  43701. }
  43702. #if SQLITE_OS_WINRT
  43703. {
  43704. ULONGLONG cnt = osGetTickCount64();
  43705. xorMemory(&e, (unsigned char*)&cnt, sizeof(ULONGLONG));
  43706. }
  43707. #else
  43708. {
  43709. DWORD cnt = osGetTickCount();
  43710. xorMemory(&e, (unsigned char*)&cnt, sizeof(DWORD));
  43711. }
  43712. #endif /* SQLITE_OS_WINRT */
  43713. {
  43714. LARGE_INTEGER i;
  43715. osQueryPerformanceCounter(&i);
  43716. xorMemory(&e, (unsigned char*)&i, sizeof(LARGE_INTEGER));
  43717. }
  43718. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
  43719. {
  43720. UUID id;
  43721. memset(&id, 0, sizeof(UUID));
  43722. osUuidCreate(&id);
  43723. xorMemory(&e, (unsigned char*)&id, sizeof(UUID));
  43724. memset(&id, 0, sizeof(UUID));
  43725. osUuidCreateSequential(&id);
  43726. xorMemory(&e, (unsigned char*)&id, sizeof(UUID));
  43727. }
  43728. #endif /* !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID */
  43729. return e.nXor>nBuf ? nBuf : e.nXor;
  43730. #endif /* defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS) */
  43731. }
  43732. /*
  43733. ** Sleep for a little while. Return the amount of time slept.
  43734. */
  43735. static int winSleep(sqlite3_vfs *pVfs, int microsec){
  43736. sqlite3_win32_sleep((microsec+999)/1000);
  43737. UNUSED_PARAMETER(pVfs);
  43738. return ((microsec+999)/1000)*1000;
  43739. }
  43740. /*
  43741. ** The following variable, if set to a non-zero value, is interpreted as
  43742. ** the number of seconds since 1970 and is used to set the result of
  43743. ** sqlite3OsCurrentTime() during testing.
  43744. */
  43745. #ifdef SQLITE_TEST
  43746. SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
  43747. #endif
  43748. /*
  43749. ** Find the current time (in Universal Coordinated Time). Write into *piNow
  43750. ** the current time and date as a Julian Day number times 86_400_000. In
  43751. ** other words, write into *piNow the number of milliseconds since the Julian
  43752. ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
  43753. ** proleptic Gregorian calendar.
  43754. **
  43755. ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
  43756. ** cannot be found.
  43757. */
  43758. static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
  43759. /* FILETIME structure is a 64-bit value representing the number of
  43760. 100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
  43761. */
  43762. FILETIME ft;
  43763. static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
  43764. #ifdef SQLITE_TEST
  43765. static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
  43766. #endif
  43767. /* 2^32 - to avoid use of LL and warnings in gcc */
  43768. static const sqlite3_int64 max32BitValue =
  43769. (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 +
  43770. (sqlite3_int64)294967296;
  43771. #if SQLITE_OS_WINCE
  43772. SYSTEMTIME time;
  43773. osGetSystemTime(&time);
  43774. /* if SystemTimeToFileTime() fails, it returns zero. */
  43775. if (!osSystemTimeToFileTime(&time,&ft)){
  43776. return SQLITE_ERROR;
  43777. }
  43778. #else
  43779. osGetSystemTimeAsFileTime( &ft );
  43780. #endif
  43781. *piNow = winFiletimeEpoch +
  43782. ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
  43783. (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
  43784. #ifdef SQLITE_TEST
  43785. if( sqlite3_current_time ){
  43786. *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
  43787. }
  43788. #endif
  43789. UNUSED_PARAMETER(pVfs);
  43790. return SQLITE_OK;
  43791. }
  43792. /*
  43793. ** Find the current time (in Universal Coordinated Time). Write the
  43794. ** current time and date as a Julian Day number into *prNow and
  43795. ** return 0. Return 1 if the time and date cannot be found.
  43796. */
  43797. static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
  43798. int rc;
  43799. sqlite3_int64 i;
  43800. rc = winCurrentTimeInt64(pVfs, &i);
  43801. if( !rc ){
  43802. *prNow = i/86400000.0;
  43803. }
  43804. return rc;
  43805. }
  43806. /*
  43807. ** The idea is that this function works like a combination of
  43808. ** GetLastError() and FormatMessage() on Windows (or errno and
  43809. ** strerror_r() on Unix). After an error is returned by an OS
  43810. ** function, SQLite calls this function with zBuf pointing to
  43811. ** a buffer of nBuf bytes. The OS layer should populate the
  43812. ** buffer with a nul-terminated UTF-8 encoded error message
  43813. ** describing the last IO error to have occurred within the calling
  43814. ** thread.
  43815. **
  43816. ** If the error message is too large for the supplied buffer,
  43817. ** it should be truncated. The return value of xGetLastError
  43818. ** is zero if the error message fits in the buffer, or non-zero
  43819. ** otherwise (if the message was truncated). If non-zero is returned,
  43820. ** then it is not necessary to include the nul-terminator character
  43821. ** in the output buffer.
  43822. **
  43823. ** Not supplying an error message will have no adverse effect
  43824. ** on SQLite. It is fine to have an implementation that never
  43825. ** returns an error message:
  43826. **
  43827. ** int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  43828. ** assert(zBuf[0]=='\0');
  43829. ** return 0;
  43830. ** }
  43831. **
  43832. ** However if an error message is supplied, it will be incorporated
  43833. ** by sqlite into the error message available to the user using
  43834. ** sqlite3_errmsg(), possibly making IO errors easier to debug.
  43835. */
  43836. static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  43837. DWORD e = osGetLastError();
  43838. UNUSED_PARAMETER(pVfs);
  43839. if( nBuf>0 ) winGetLastErrorMsg(e, nBuf, zBuf);
  43840. return e;
  43841. }
  43842. /*
  43843. ** Initialize and deinitialize the operating system interface.
  43844. */
  43845. SQLITE_API int sqlite3_os_init(void){
  43846. static sqlite3_vfs winVfs = {
  43847. 3, /* iVersion */
  43848. sizeof(winFile), /* szOsFile */
  43849. SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
  43850. 0, /* pNext */
  43851. "win32", /* zName */
  43852. &winAppData, /* pAppData */
  43853. winOpen, /* xOpen */
  43854. winDelete, /* xDelete */
  43855. winAccess, /* xAccess */
  43856. winFullPathname, /* xFullPathname */
  43857. winDlOpen, /* xDlOpen */
  43858. winDlError, /* xDlError */
  43859. winDlSym, /* xDlSym */
  43860. winDlClose, /* xDlClose */
  43861. winRandomness, /* xRandomness */
  43862. winSleep, /* xSleep */
  43863. winCurrentTime, /* xCurrentTime */
  43864. winGetLastError, /* xGetLastError */
  43865. winCurrentTimeInt64, /* xCurrentTimeInt64 */
  43866. winSetSystemCall, /* xSetSystemCall */
  43867. winGetSystemCall, /* xGetSystemCall */
  43868. winNextSystemCall, /* xNextSystemCall */
  43869. };
  43870. #if defined(SQLITE_WIN32_HAS_WIDE)
  43871. static sqlite3_vfs winLongPathVfs = {
  43872. 3, /* iVersion */
  43873. sizeof(winFile), /* szOsFile */
  43874. SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
  43875. 0, /* pNext */
  43876. "win32-longpath", /* zName */
  43877. &winAppData, /* pAppData */
  43878. winOpen, /* xOpen */
  43879. winDelete, /* xDelete */
  43880. winAccess, /* xAccess */
  43881. winFullPathname, /* xFullPathname */
  43882. winDlOpen, /* xDlOpen */
  43883. winDlError, /* xDlError */
  43884. winDlSym, /* xDlSym */
  43885. winDlClose, /* xDlClose */
  43886. winRandomness, /* xRandomness */
  43887. winSleep, /* xSleep */
  43888. winCurrentTime, /* xCurrentTime */
  43889. winGetLastError, /* xGetLastError */
  43890. winCurrentTimeInt64, /* xCurrentTimeInt64 */
  43891. winSetSystemCall, /* xSetSystemCall */
  43892. winGetSystemCall, /* xGetSystemCall */
  43893. winNextSystemCall, /* xNextSystemCall */
  43894. };
  43895. #endif
  43896. static sqlite3_vfs winNolockVfs = {
  43897. 3, /* iVersion */
  43898. sizeof(winFile), /* szOsFile */
  43899. SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
  43900. 0, /* pNext */
  43901. "win32-none", /* zName */
  43902. &winNolockAppData, /* pAppData */
  43903. winOpen, /* xOpen */
  43904. winDelete, /* xDelete */
  43905. winAccess, /* xAccess */
  43906. winFullPathname, /* xFullPathname */
  43907. winDlOpen, /* xDlOpen */
  43908. winDlError, /* xDlError */
  43909. winDlSym, /* xDlSym */
  43910. winDlClose, /* xDlClose */
  43911. winRandomness, /* xRandomness */
  43912. winSleep, /* xSleep */
  43913. winCurrentTime, /* xCurrentTime */
  43914. winGetLastError, /* xGetLastError */
  43915. winCurrentTimeInt64, /* xCurrentTimeInt64 */
  43916. winSetSystemCall, /* xSetSystemCall */
  43917. winGetSystemCall, /* xGetSystemCall */
  43918. winNextSystemCall, /* xNextSystemCall */
  43919. };
  43920. #if defined(SQLITE_WIN32_HAS_WIDE)
  43921. static sqlite3_vfs winLongPathNolockVfs = {
  43922. 3, /* iVersion */
  43923. sizeof(winFile), /* szOsFile */
  43924. SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
  43925. 0, /* pNext */
  43926. "win32-longpath-none", /* zName */
  43927. &winNolockAppData, /* pAppData */
  43928. winOpen, /* xOpen */
  43929. winDelete, /* xDelete */
  43930. winAccess, /* xAccess */
  43931. winFullPathname, /* xFullPathname */
  43932. winDlOpen, /* xDlOpen */
  43933. winDlError, /* xDlError */
  43934. winDlSym, /* xDlSym */
  43935. winDlClose, /* xDlClose */
  43936. winRandomness, /* xRandomness */
  43937. winSleep, /* xSleep */
  43938. winCurrentTime, /* xCurrentTime */
  43939. winGetLastError, /* xGetLastError */
  43940. winCurrentTimeInt64, /* xCurrentTimeInt64 */
  43941. winSetSystemCall, /* xSetSystemCall */
  43942. winGetSystemCall, /* xGetSystemCall */
  43943. winNextSystemCall, /* xNextSystemCall */
  43944. };
  43945. #endif
  43946. /* Double-check that the aSyscall[] array has been constructed
  43947. ** correctly. See ticket [bb3a86e890c8e96ab] */
  43948. assert( ArraySize(aSyscall)==80 );
  43949. /* get memory map allocation granularity */
  43950. memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
  43951. #if SQLITE_OS_WINRT
  43952. osGetNativeSystemInfo(&winSysInfo);
  43953. #else
  43954. osGetSystemInfo(&winSysInfo);
  43955. #endif
  43956. assert( winSysInfo.dwAllocationGranularity>0 );
  43957. assert( winSysInfo.dwPageSize>0 );
  43958. sqlite3_vfs_register(&winVfs, 1);
  43959. #if defined(SQLITE_WIN32_HAS_WIDE)
  43960. sqlite3_vfs_register(&winLongPathVfs, 0);
  43961. #endif
  43962. sqlite3_vfs_register(&winNolockVfs, 0);
  43963. #if defined(SQLITE_WIN32_HAS_WIDE)
  43964. sqlite3_vfs_register(&winLongPathNolockVfs, 0);
  43965. #endif
  43966. #ifndef SQLITE_OMIT_WAL
  43967. winBigLock = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1);
  43968. #endif
  43969. return SQLITE_OK;
  43970. }
  43971. SQLITE_API int sqlite3_os_end(void){
  43972. #if SQLITE_OS_WINRT
  43973. if( sleepObj!=NULL ){
  43974. osCloseHandle(sleepObj);
  43975. sleepObj = NULL;
  43976. }
  43977. #endif
  43978. #ifndef SQLITE_OMIT_WAL
  43979. winBigLock = 0;
  43980. #endif
  43981. return SQLITE_OK;
  43982. }
  43983. #endif /* SQLITE_OS_WIN */
  43984. /************** End of os_win.c **********************************************/
  43985. /************** Begin file memdb.c *******************************************/
  43986. /*
  43987. ** 2016-09-07
  43988. **
  43989. ** The author disclaims copyright to this source code. In place of
  43990. ** a legal notice, here is a blessing:
  43991. **
  43992. ** May you do good and not evil.
  43993. ** May you find forgiveness for yourself and forgive others.
  43994. ** May you share freely, never taking more than you give.
  43995. **
  43996. ******************************************************************************
  43997. **
  43998. ** This file implements an in-memory VFS. A database is held as a contiguous
  43999. ** block of memory.
  44000. **
  44001. ** This file also implements interface sqlite3_serialize() and
  44002. ** sqlite3_deserialize().
  44003. */
  44004. /* #include "sqliteInt.h" */
  44005. #ifdef SQLITE_ENABLE_DESERIALIZE
  44006. /*
  44007. ** Forward declaration of objects used by this utility
  44008. */
  44009. typedef struct sqlite3_vfs MemVfs;
  44010. typedef struct MemFile MemFile;
  44011. /* Access to a lower-level VFS that (might) implement dynamic loading,
  44012. ** access to randomness, etc.
  44013. */
  44014. #define ORIGVFS(p) ((sqlite3_vfs*)((p)->pAppData))
  44015. /* An open file */
  44016. struct MemFile {
  44017. sqlite3_file base; /* IO methods */
  44018. sqlite3_int64 sz; /* Size of the file */
  44019. sqlite3_int64 szAlloc; /* Space allocated to aData */
  44020. sqlite3_int64 szMax; /* Maximum allowed size of the file */
  44021. unsigned char *aData; /* content of the file */
  44022. int nMmap; /* Number of memory mapped pages */
  44023. unsigned mFlags; /* Flags */
  44024. int eLock; /* Most recent lock against this file */
  44025. };
  44026. /*
  44027. ** Methods for MemFile
  44028. */
  44029. static int memdbClose(sqlite3_file*);
  44030. static int memdbRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
  44031. static int memdbWrite(sqlite3_file*,const void*,int iAmt, sqlite3_int64 iOfst);
  44032. static int memdbTruncate(sqlite3_file*, sqlite3_int64 size);
  44033. static int memdbSync(sqlite3_file*, int flags);
  44034. static int memdbFileSize(sqlite3_file*, sqlite3_int64 *pSize);
  44035. static int memdbLock(sqlite3_file*, int);
  44036. /* static int memdbCheckReservedLock(sqlite3_file*, int *pResOut);// not used */
  44037. static int memdbFileControl(sqlite3_file*, int op, void *pArg);
  44038. /* static int memdbSectorSize(sqlite3_file*); // not used */
  44039. static int memdbDeviceCharacteristics(sqlite3_file*);
  44040. static int memdbFetch(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
  44041. static int memdbUnfetch(sqlite3_file*, sqlite3_int64 iOfst, void *p);
  44042. /*
  44043. ** Methods for MemVfs
  44044. */
  44045. static int memdbOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *);
  44046. /* static int memdbDelete(sqlite3_vfs*, const char *zName, int syncDir); */
  44047. static int memdbAccess(sqlite3_vfs*, const char *zName, int flags, int *);
  44048. static int memdbFullPathname(sqlite3_vfs*, const char *zName, int, char *zOut);
  44049. static void *memdbDlOpen(sqlite3_vfs*, const char *zFilename);
  44050. static void memdbDlError(sqlite3_vfs*, int nByte, char *zErrMsg);
  44051. static void (*memdbDlSym(sqlite3_vfs *pVfs, void *p, const char*zSym))(void);
  44052. static void memdbDlClose(sqlite3_vfs*, void*);
  44053. static int memdbRandomness(sqlite3_vfs*, int nByte, char *zOut);
  44054. static int memdbSleep(sqlite3_vfs*, int microseconds);
  44055. /* static int memdbCurrentTime(sqlite3_vfs*, double*); */
  44056. static int memdbGetLastError(sqlite3_vfs*, int, char *);
  44057. static int memdbCurrentTimeInt64(sqlite3_vfs*, sqlite3_int64*);
  44058. static sqlite3_vfs memdb_vfs = {
  44059. 2, /* iVersion */
  44060. 0, /* szOsFile (set when registered) */
  44061. 1024, /* mxPathname */
  44062. 0, /* pNext */
  44063. "memdb", /* zName */
  44064. 0, /* pAppData (set when registered) */
  44065. memdbOpen, /* xOpen */
  44066. 0, /* memdbDelete, */ /* xDelete */
  44067. memdbAccess, /* xAccess */
  44068. memdbFullPathname, /* xFullPathname */
  44069. memdbDlOpen, /* xDlOpen */
  44070. memdbDlError, /* xDlError */
  44071. memdbDlSym, /* xDlSym */
  44072. memdbDlClose, /* xDlClose */
  44073. memdbRandomness, /* xRandomness */
  44074. memdbSleep, /* xSleep */
  44075. 0, /* memdbCurrentTime, */ /* xCurrentTime */
  44076. memdbGetLastError, /* xGetLastError */
  44077. memdbCurrentTimeInt64 /* xCurrentTimeInt64 */
  44078. };
  44079. static const sqlite3_io_methods memdb_io_methods = {
  44080. 3, /* iVersion */
  44081. memdbClose, /* xClose */
  44082. memdbRead, /* xRead */
  44083. memdbWrite, /* xWrite */
  44084. memdbTruncate, /* xTruncate */
  44085. memdbSync, /* xSync */
  44086. memdbFileSize, /* xFileSize */
  44087. memdbLock, /* xLock */
  44088. memdbLock, /* xUnlock - same as xLock in this case */
  44089. 0, /* memdbCheckReservedLock, */ /* xCheckReservedLock */
  44090. memdbFileControl, /* xFileControl */
  44091. 0, /* memdbSectorSize,*/ /* xSectorSize */
  44092. memdbDeviceCharacteristics, /* xDeviceCharacteristics */
  44093. 0, /* xShmMap */
  44094. 0, /* xShmLock */
  44095. 0, /* xShmBarrier */
  44096. 0, /* xShmUnmap */
  44097. memdbFetch, /* xFetch */
  44098. memdbUnfetch /* xUnfetch */
  44099. };
  44100. /*
  44101. ** Close an memdb-file.
  44102. **
  44103. ** The pData pointer is owned by the application, so there is nothing
  44104. ** to free.
  44105. */
  44106. static int memdbClose(sqlite3_file *pFile){
  44107. MemFile *p = (MemFile *)pFile;
  44108. if( p->mFlags & SQLITE_DESERIALIZE_FREEONCLOSE ) sqlite3_free(p->aData);
  44109. return SQLITE_OK;
  44110. }
  44111. /*
  44112. ** Read data from an memdb-file.
  44113. */
  44114. static int memdbRead(
  44115. sqlite3_file *pFile,
  44116. void *zBuf,
  44117. int iAmt,
  44118. sqlite_int64 iOfst
  44119. ){
  44120. MemFile *p = (MemFile *)pFile;
  44121. if( iOfst+iAmt>p->sz ){
  44122. memset(zBuf, 0, iAmt);
  44123. if( iOfst<p->sz ) memcpy(zBuf, p->aData+iOfst, p->sz - iOfst);
  44124. return SQLITE_IOERR_SHORT_READ;
  44125. }
  44126. memcpy(zBuf, p->aData+iOfst, iAmt);
  44127. return SQLITE_OK;
  44128. }
  44129. /*
  44130. ** Try to enlarge the memory allocation to hold at least sz bytes
  44131. */
  44132. static int memdbEnlarge(MemFile *p, sqlite3_int64 newSz){
  44133. unsigned char *pNew;
  44134. if( (p->mFlags & SQLITE_DESERIALIZE_RESIZEABLE)==0 || p->nMmap>0 ){
  44135. return SQLITE_FULL;
  44136. }
  44137. if( newSz>p->szMax ){
  44138. return SQLITE_FULL;
  44139. }
  44140. newSz *= 2;
  44141. if( newSz>p->szMax ) newSz = p->szMax;
  44142. pNew = sqlite3_realloc64(p->aData, newSz);
  44143. if( pNew==0 ) return SQLITE_NOMEM;
  44144. p->aData = pNew;
  44145. p->szAlloc = newSz;
  44146. return SQLITE_OK;
  44147. }
  44148. /*
  44149. ** Write data to an memdb-file.
  44150. */
  44151. static int memdbWrite(
  44152. sqlite3_file *pFile,
  44153. const void *z,
  44154. int iAmt,
  44155. sqlite_int64 iOfst
  44156. ){
  44157. MemFile *p = (MemFile *)pFile;
  44158. if( NEVER(p->mFlags & SQLITE_DESERIALIZE_READONLY) ) return SQLITE_READONLY;
  44159. if( iOfst+iAmt>p->sz ){
  44160. int rc;
  44161. if( iOfst+iAmt>p->szAlloc
  44162. && (rc = memdbEnlarge(p, iOfst+iAmt))!=SQLITE_OK
  44163. ){
  44164. return rc;
  44165. }
  44166. if( iOfst>p->sz ) memset(p->aData+p->sz, 0, iOfst-p->sz);
  44167. p->sz = iOfst+iAmt;
  44168. }
  44169. memcpy(p->aData+iOfst, z, iAmt);
  44170. return SQLITE_OK;
  44171. }
  44172. /*
  44173. ** Truncate an memdb-file.
  44174. **
  44175. ** In rollback mode (which is always the case for memdb, as it does not
  44176. ** support WAL mode) the truncate() method is only used to reduce
  44177. ** the size of a file, never to increase the size.
  44178. */
  44179. static int memdbTruncate(sqlite3_file *pFile, sqlite_int64 size){
  44180. MemFile *p = (MemFile *)pFile;
  44181. if( NEVER(size>p->sz) ) return SQLITE_FULL;
  44182. p->sz = size;
  44183. return SQLITE_OK;
  44184. }
  44185. /*
  44186. ** Sync an memdb-file.
  44187. */
  44188. static int memdbSync(sqlite3_file *pFile, int flags){
  44189. return SQLITE_OK;
  44190. }
  44191. /*
  44192. ** Return the current file-size of an memdb-file.
  44193. */
  44194. static int memdbFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
  44195. MemFile *p = (MemFile *)pFile;
  44196. *pSize = p->sz;
  44197. return SQLITE_OK;
  44198. }
  44199. /*
  44200. ** Lock an memdb-file.
  44201. */
  44202. static int memdbLock(sqlite3_file *pFile, int eLock){
  44203. MemFile *p = (MemFile *)pFile;
  44204. if( eLock>SQLITE_LOCK_SHARED
  44205. && (p->mFlags & SQLITE_DESERIALIZE_READONLY)!=0
  44206. ){
  44207. return SQLITE_READONLY;
  44208. }
  44209. p->eLock = eLock;
  44210. return SQLITE_OK;
  44211. }
  44212. #if 0 /* Never used because memdbAccess() always returns false */
  44213. /*
  44214. ** Check if another file-handle holds a RESERVED lock on an memdb-file.
  44215. */
  44216. static int memdbCheckReservedLock(sqlite3_file *pFile, int *pResOut){
  44217. *pResOut = 0;
  44218. return SQLITE_OK;
  44219. }
  44220. #endif
  44221. /*
  44222. ** File control method. For custom operations on an memdb-file.
  44223. */
  44224. static int memdbFileControl(sqlite3_file *pFile, int op, void *pArg){
  44225. MemFile *p = (MemFile *)pFile;
  44226. int rc = SQLITE_NOTFOUND;
  44227. if( op==SQLITE_FCNTL_VFSNAME ){
  44228. *(char**)pArg = sqlite3_mprintf("memdb(%p,%lld)", p->aData, p->sz);
  44229. rc = SQLITE_OK;
  44230. }
  44231. if( op==SQLITE_FCNTL_SIZE_LIMIT ){
  44232. sqlite3_int64 iLimit = *(sqlite3_int64*)pArg;
  44233. if( iLimit<p->sz ){
  44234. if( iLimit<0 ){
  44235. iLimit = p->szMax;
  44236. }else{
  44237. iLimit = p->sz;
  44238. }
  44239. }
  44240. p->szMax = iLimit;
  44241. *(sqlite3_int64*)pArg = iLimit;
  44242. rc = SQLITE_OK;
  44243. }
  44244. return rc;
  44245. }
  44246. #if 0 /* Not used because of SQLITE_IOCAP_POWERSAFE_OVERWRITE */
  44247. /*
  44248. ** Return the sector-size in bytes for an memdb-file.
  44249. */
  44250. static int memdbSectorSize(sqlite3_file *pFile){
  44251. return 1024;
  44252. }
  44253. #endif
  44254. /*
  44255. ** Return the device characteristic flags supported by an memdb-file.
  44256. */
  44257. static int memdbDeviceCharacteristics(sqlite3_file *pFile){
  44258. return SQLITE_IOCAP_ATOMIC |
  44259. SQLITE_IOCAP_POWERSAFE_OVERWRITE |
  44260. SQLITE_IOCAP_SAFE_APPEND |
  44261. SQLITE_IOCAP_SEQUENTIAL;
  44262. }
  44263. /* Fetch a page of a memory-mapped file */
  44264. static int memdbFetch(
  44265. sqlite3_file *pFile,
  44266. sqlite3_int64 iOfst,
  44267. int iAmt,
  44268. void **pp
  44269. ){
  44270. MemFile *p = (MemFile *)pFile;
  44271. if( iOfst+iAmt>p->sz ){
  44272. *pp = 0;
  44273. }else{
  44274. p->nMmap++;
  44275. *pp = (void*)(p->aData + iOfst);
  44276. }
  44277. return SQLITE_OK;
  44278. }
  44279. /* Release a memory-mapped page */
  44280. static int memdbUnfetch(sqlite3_file *pFile, sqlite3_int64 iOfst, void *pPage){
  44281. MemFile *p = (MemFile *)pFile;
  44282. p->nMmap--;
  44283. return SQLITE_OK;
  44284. }
  44285. /*
  44286. ** Open an mem file handle.
  44287. */
  44288. static int memdbOpen(
  44289. sqlite3_vfs *pVfs,
  44290. const char *zName,
  44291. sqlite3_file *pFile,
  44292. int flags,
  44293. int *pOutFlags
  44294. ){
  44295. MemFile *p = (MemFile*)pFile;
  44296. if( (flags & SQLITE_OPEN_MAIN_DB)==0 ){
  44297. return ORIGVFS(pVfs)->xOpen(ORIGVFS(pVfs), zName, pFile, flags, pOutFlags);
  44298. }
  44299. memset(p, 0, sizeof(*p));
  44300. p->mFlags = SQLITE_DESERIALIZE_RESIZEABLE | SQLITE_DESERIALIZE_FREEONCLOSE;
  44301. assert( pOutFlags!=0 ); /* True because flags==SQLITE_OPEN_MAIN_DB */
  44302. *pOutFlags = flags | SQLITE_OPEN_MEMORY;
  44303. p->base.pMethods = &memdb_io_methods;
  44304. p->szMax = sqlite3GlobalConfig.mxMemdbSize;
  44305. return SQLITE_OK;
  44306. }
  44307. #if 0 /* Only used to delete rollback journals, master journals, and WAL
  44308. ** files, none of which exist in memdb. So this routine is never used */
  44309. /*
  44310. ** Delete the file located at zPath. If the dirSync argument is true,
  44311. ** ensure the file-system modifications are synced to disk before
  44312. ** returning.
  44313. */
  44314. static int memdbDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
  44315. return SQLITE_IOERR_DELETE;
  44316. }
  44317. #endif
  44318. /*
  44319. ** Test for access permissions. Return true if the requested permission
  44320. ** is available, or false otherwise.
  44321. **
  44322. ** With memdb, no files ever exist on disk. So always return false.
  44323. */
  44324. static int memdbAccess(
  44325. sqlite3_vfs *pVfs,
  44326. const char *zPath,
  44327. int flags,
  44328. int *pResOut
  44329. ){
  44330. *pResOut = 0;
  44331. return SQLITE_OK;
  44332. }
  44333. /*
  44334. ** Populate buffer zOut with the full canonical pathname corresponding
  44335. ** to the pathname in zPath. zOut is guaranteed to point to a buffer
  44336. ** of at least (INST_MAX_PATHNAME+1) bytes.
  44337. */
  44338. static int memdbFullPathname(
  44339. sqlite3_vfs *pVfs,
  44340. const char *zPath,
  44341. int nOut,
  44342. char *zOut
  44343. ){
  44344. sqlite3_snprintf(nOut, zOut, "%s", zPath);
  44345. return SQLITE_OK;
  44346. }
  44347. /*
  44348. ** Open the dynamic library located at zPath and return a handle.
  44349. */
  44350. static void *memdbDlOpen(sqlite3_vfs *pVfs, const char *zPath){
  44351. return ORIGVFS(pVfs)->xDlOpen(ORIGVFS(pVfs), zPath);
  44352. }
  44353. /*
  44354. ** Populate the buffer zErrMsg (size nByte bytes) with a human readable
  44355. ** utf-8 string describing the most recent error encountered associated
  44356. ** with dynamic libraries.
  44357. */
  44358. static void memdbDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
  44359. ORIGVFS(pVfs)->xDlError(ORIGVFS(pVfs), nByte, zErrMsg);
  44360. }
  44361. /*
  44362. ** Return a pointer to the symbol zSymbol in the dynamic library pHandle.
  44363. */
  44364. static void (*memdbDlSym(sqlite3_vfs *pVfs, void *p, const char *zSym))(void){
  44365. return ORIGVFS(pVfs)->xDlSym(ORIGVFS(pVfs), p, zSym);
  44366. }
  44367. /*
  44368. ** Close the dynamic library handle pHandle.
  44369. */
  44370. static void memdbDlClose(sqlite3_vfs *pVfs, void *pHandle){
  44371. ORIGVFS(pVfs)->xDlClose(ORIGVFS(pVfs), pHandle);
  44372. }
  44373. /*
  44374. ** Populate the buffer pointed to by zBufOut with nByte bytes of
  44375. ** random data.
  44376. */
  44377. static int memdbRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  44378. return ORIGVFS(pVfs)->xRandomness(ORIGVFS(pVfs), nByte, zBufOut);
  44379. }
  44380. /*
  44381. ** Sleep for nMicro microseconds. Return the number of microseconds
  44382. ** actually slept.
  44383. */
  44384. static int memdbSleep(sqlite3_vfs *pVfs, int nMicro){
  44385. return ORIGVFS(pVfs)->xSleep(ORIGVFS(pVfs), nMicro);
  44386. }
  44387. #if 0 /* Never used. Modern cores only call xCurrentTimeInt64() */
  44388. /*
  44389. ** Return the current time as a Julian Day number in *pTimeOut.
  44390. */
  44391. static int memdbCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
  44392. return ORIGVFS(pVfs)->xCurrentTime(ORIGVFS(pVfs), pTimeOut);
  44393. }
  44394. #endif
  44395. static int memdbGetLastError(sqlite3_vfs *pVfs, int a, char *b){
  44396. return ORIGVFS(pVfs)->xGetLastError(ORIGVFS(pVfs), a, b);
  44397. }
  44398. static int memdbCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *p){
  44399. return ORIGVFS(pVfs)->xCurrentTimeInt64(ORIGVFS(pVfs), p);
  44400. }
  44401. /*
  44402. ** Translate a database connection pointer and schema name into a
  44403. ** MemFile pointer.
  44404. */
  44405. static MemFile *memdbFromDbSchema(sqlite3 *db, const char *zSchema){
  44406. MemFile *p = 0;
  44407. int rc = sqlite3_file_control(db, zSchema, SQLITE_FCNTL_FILE_POINTER, &p);
  44408. if( rc ) return 0;
  44409. if( p->base.pMethods!=&memdb_io_methods ) return 0;
  44410. return p;
  44411. }
  44412. /*
  44413. ** Return the serialization of a database
  44414. */
  44415. SQLITE_API unsigned char *sqlite3_serialize(
  44416. sqlite3 *db, /* The database connection */
  44417. const char *zSchema, /* Which database within the connection */
  44418. sqlite3_int64 *piSize, /* Write size here, if not NULL */
  44419. unsigned int mFlags /* Maybe SQLITE_SERIALIZE_NOCOPY */
  44420. ){
  44421. MemFile *p;
  44422. int iDb;
  44423. Btree *pBt;
  44424. sqlite3_int64 sz;
  44425. int szPage = 0;
  44426. sqlite3_stmt *pStmt = 0;
  44427. unsigned char *pOut;
  44428. char *zSql;
  44429. int rc;
  44430. #ifdef SQLITE_ENABLE_API_ARMOR
  44431. if( !sqlite3SafetyCheckOk(db) ){
  44432. (void)SQLITE_MISUSE_BKPT;
  44433. return 0;
  44434. }
  44435. #endif
  44436. if( zSchema==0 ) zSchema = db->aDb[0].zDbSName;
  44437. p = memdbFromDbSchema(db, zSchema);
  44438. iDb = sqlite3FindDbName(db, zSchema);
  44439. if( piSize ) *piSize = -1;
  44440. if( iDb<0 ) return 0;
  44441. if( p ){
  44442. if( piSize ) *piSize = p->sz;
  44443. if( mFlags & SQLITE_SERIALIZE_NOCOPY ){
  44444. pOut = p->aData;
  44445. }else{
  44446. pOut = sqlite3_malloc64( p->sz );
  44447. if( pOut ) memcpy(pOut, p->aData, p->sz);
  44448. }
  44449. return pOut;
  44450. }
  44451. pBt = db->aDb[iDb].pBt;
  44452. if( pBt==0 ) return 0;
  44453. szPage = sqlite3BtreeGetPageSize(pBt);
  44454. zSql = sqlite3_mprintf("PRAGMA \"%w\".page_count", zSchema);
  44455. rc = zSql ? sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0) : SQLITE_NOMEM;
  44456. sqlite3_free(zSql);
  44457. if( rc ) return 0;
  44458. rc = sqlite3_step(pStmt);
  44459. if( rc!=SQLITE_ROW ){
  44460. pOut = 0;
  44461. }else{
  44462. sz = sqlite3_column_int64(pStmt, 0)*szPage;
  44463. if( piSize ) *piSize = sz;
  44464. if( mFlags & SQLITE_SERIALIZE_NOCOPY ){
  44465. pOut = 0;
  44466. }else{
  44467. pOut = sqlite3_malloc64( sz );
  44468. if( pOut ){
  44469. int nPage = sqlite3_column_int(pStmt, 0);
  44470. Pager *pPager = sqlite3BtreePager(pBt);
  44471. int pgno;
  44472. for(pgno=1; pgno<=nPage; pgno++){
  44473. DbPage *pPage = 0;
  44474. unsigned char *pTo = pOut + szPage*(sqlite3_int64)(pgno-1);
  44475. rc = sqlite3PagerGet(pPager, pgno, (DbPage**)&pPage, 0);
  44476. if( rc==SQLITE_OK ){
  44477. memcpy(pTo, sqlite3PagerGetData(pPage), szPage);
  44478. }else{
  44479. memset(pTo, 0, szPage);
  44480. }
  44481. sqlite3PagerUnref(pPage);
  44482. }
  44483. }
  44484. }
  44485. }
  44486. sqlite3_finalize(pStmt);
  44487. return pOut;
  44488. }
  44489. /* Convert zSchema to a MemDB and initialize its content.
  44490. */
  44491. SQLITE_API int sqlite3_deserialize(
  44492. sqlite3 *db, /* The database connection */
  44493. const char *zSchema, /* Which DB to reopen with the deserialization */
  44494. unsigned char *pData, /* The serialized database content */
  44495. sqlite3_int64 szDb, /* Number bytes in the deserialization */
  44496. sqlite3_int64 szBuf, /* Total size of buffer pData[] */
  44497. unsigned mFlags /* Zero or more SQLITE_DESERIALIZE_* flags */
  44498. ){
  44499. MemFile *p;
  44500. char *zSql;
  44501. sqlite3_stmt *pStmt = 0;
  44502. int rc;
  44503. int iDb;
  44504. #ifdef SQLITE_ENABLE_API_ARMOR
  44505. if( !sqlite3SafetyCheckOk(db) ){
  44506. return SQLITE_MISUSE_BKPT;
  44507. }
  44508. if( szDb<0 ) return SQLITE_MISUSE_BKPT;
  44509. if( szBuf<0 ) return SQLITE_MISUSE_BKPT;
  44510. #endif
  44511. sqlite3_mutex_enter(db->mutex);
  44512. if( zSchema==0 ) zSchema = db->aDb[0].zDbSName;
  44513. iDb = sqlite3FindDbName(db, zSchema);
  44514. if( iDb<0 ){
  44515. rc = SQLITE_ERROR;
  44516. goto end_deserialize;
  44517. }
  44518. zSql = sqlite3_mprintf("ATTACH x AS %Q", zSchema);
  44519. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  44520. sqlite3_free(zSql);
  44521. if( rc ) goto end_deserialize;
  44522. db->init.iDb = (u8)iDb;
  44523. db->init.reopenMemdb = 1;
  44524. rc = sqlite3_step(pStmt);
  44525. db->init.reopenMemdb = 0;
  44526. if( rc!=SQLITE_DONE ){
  44527. rc = SQLITE_ERROR;
  44528. goto end_deserialize;
  44529. }
  44530. p = memdbFromDbSchema(db, zSchema);
  44531. if( p==0 ){
  44532. rc = SQLITE_ERROR;
  44533. }else{
  44534. p->aData = pData;
  44535. p->sz = szDb;
  44536. p->szAlloc = szBuf;
  44537. p->szMax = szBuf;
  44538. if( p->szMax<sqlite3GlobalConfig.mxMemdbSize ){
  44539. p->szMax = sqlite3GlobalConfig.mxMemdbSize;
  44540. }
  44541. p->mFlags = mFlags;
  44542. rc = SQLITE_OK;
  44543. }
  44544. end_deserialize:
  44545. sqlite3_finalize(pStmt);
  44546. sqlite3_mutex_leave(db->mutex);
  44547. return rc;
  44548. }
  44549. /*
  44550. ** This routine is called when the extension is loaded.
  44551. ** Register the new VFS.
  44552. */
  44553. SQLITE_PRIVATE int sqlite3MemdbInit(void){
  44554. sqlite3_vfs *pLower = sqlite3_vfs_find(0);
  44555. int sz = pLower->szOsFile;
  44556. memdb_vfs.pAppData = pLower;
  44557. /* In all known configurations of SQLite, the size of a default
  44558. ** sqlite3_file is greater than the size of a memdb sqlite3_file.
  44559. ** Should that ever change, remove the following NEVER() */
  44560. if( NEVER(sz<sizeof(MemFile)) ) sz = sizeof(MemFile);
  44561. memdb_vfs.szOsFile = sz;
  44562. return sqlite3_vfs_register(&memdb_vfs, 0);
  44563. }
  44564. #endif /* SQLITE_ENABLE_DESERIALIZE */
  44565. /************** End of memdb.c ***********************************************/
  44566. /************** Begin file bitvec.c ******************************************/
  44567. /*
  44568. ** 2008 February 16
  44569. **
  44570. ** The author disclaims copyright to this source code. In place of
  44571. ** a legal notice, here is a blessing:
  44572. **
  44573. ** May you do good and not evil.
  44574. ** May you find forgiveness for yourself and forgive others.
  44575. ** May you share freely, never taking more than you give.
  44576. **
  44577. *************************************************************************
  44578. ** This file implements an object that represents a fixed-length
  44579. ** bitmap. Bits are numbered starting with 1.
  44580. **
  44581. ** A bitmap is used to record which pages of a database file have been
  44582. ** journalled during a transaction, or which pages have the "dont-write"
  44583. ** property. Usually only a few pages are meet either condition.
  44584. ** So the bitmap is usually sparse and has low cardinality.
  44585. ** But sometimes (for example when during a DROP of a large table) most
  44586. ** or all of the pages in a database can get journalled. In those cases,
  44587. ** the bitmap becomes dense with high cardinality. The algorithm needs
  44588. ** to handle both cases well.
  44589. **
  44590. ** The size of the bitmap is fixed when the object is created.
  44591. **
  44592. ** All bits are clear when the bitmap is created. Individual bits
  44593. ** may be set or cleared one at a time.
  44594. **
  44595. ** Test operations are about 100 times more common that set operations.
  44596. ** Clear operations are exceedingly rare. There are usually between
  44597. ** 5 and 500 set operations per Bitvec object, though the number of sets can
  44598. ** sometimes grow into tens of thousands or larger. The size of the
  44599. ** Bitvec object is the number of pages in the database file at the
  44600. ** start of a transaction, and is thus usually less than a few thousand,
  44601. ** but can be as large as 2 billion for a really big database.
  44602. */
  44603. /* #include "sqliteInt.h" */
  44604. /* Size of the Bitvec structure in bytes. */
  44605. #define BITVEC_SZ 512
  44606. /* Round the union size down to the nearest pointer boundary, since that's how
  44607. ** it will be aligned within the Bitvec struct. */
  44608. #define BITVEC_USIZE \
  44609. (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
  44610. /* Type of the array "element" for the bitmap representation.
  44611. ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
  44612. ** Setting this to the "natural word" size of your CPU may improve
  44613. ** performance. */
  44614. #define BITVEC_TELEM u8
  44615. /* Size, in bits, of the bitmap element. */
  44616. #define BITVEC_SZELEM 8
  44617. /* Number of elements in a bitmap array. */
  44618. #define BITVEC_NELEM (BITVEC_USIZE/sizeof(BITVEC_TELEM))
  44619. /* Number of bits in the bitmap array. */
  44620. #define BITVEC_NBIT (BITVEC_NELEM*BITVEC_SZELEM)
  44621. /* Number of u32 values in hash table. */
  44622. #define BITVEC_NINT (BITVEC_USIZE/sizeof(u32))
  44623. /* Maximum number of entries in hash table before
  44624. ** sub-dividing and re-hashing. */
  44625. #define BITVEC_MXHASH (BITVEC_NINT/2)
  44626. /* Hashing function for the aHash representation.
  44627. ** Empirical testing showed that the *37 multiplier
  44628. ** (an arbitrary prime)in the hash function provided
  44629. ** no fewer collisions than the no-op *1. */
  44630. #define BITVEC_HASH(X) (((X)*1)%BITVEC_NINT)
  44631. #define BITVEC_NPTR (BITVEC_USIZE/sizeof(Bitvec *))
  44632. /*
  44633. ** A bitmap is an instance of the following structure.
  44634. **
  44635. ** This bitmap records the existence of zero or more bits
  44636. ** with values between 1 and iSize, inclusive.
  44637. **
  44638. ** There are three possible representations of the bitmap.
  44639. ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
  44640. ** bitmap. The least significant bit is bit 1.
  44641. **
  44642. ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
  44643. ** a hash table that will hold up to BITVEC_MXHASH distinct values.
  44644. **
  44645. ** Otherwise, the value i is redirected into one of BITVEC_NPTR
  44646. ** sub-bitmaps pointed to by Bitvec.u.apSub[]. Each subbitmap
  44647. ** handles up to iDivisor separate values of i. apSub[0] holds
  44648. ** values between 1 and iDivisor. apSub[1] holds values between
  44649. ** iDivisor+1 and 2*iDivisor. apSub[N] holds values between
  44650. ** N*iDivisor+1 and (N+1)*iDivisor. Each subbitmap is normalized
  44651. ** to hold deal with values between 1 and iDivisor.
  44652. */
  44653. struct Bitvec {
  44654. u32 iSize; /* Maximum bit index. Max iSize is 4,294,967,296. */
  44655. u32 nSet; /* Number of bits that are set - only valid for aHash
  44656. ** element. Max is BITVEC_NINT. For BITVEC_SZ of 512,
  44657. ** this would be 125. */
  44658. u32 iDivisor; /* Number of bits handled by each apSub[] entry. */
  44659. /* Should >=0 for apSub element. */
  44660. /* Max iDivisor is max(u32) / BITVEC_NPTR + 1. */
  44661. /* For a BITVEC_SZ of 512, this would be 34,359,739. */
  44662. union {
  44663. BITVEC_TELEM aBitmap[BITVEC_NELEM]; /* Bitmap representation */
  44664. u32 aHash[BITVEC_NINT]; /* Hash table representation */
  44665. Bitvec *apSub[BITVEC_NPTR]; /* Recursive representation */
  44666. } u;
  44667. };
  44668. /*
  44669. ** Create a new bitmap object able to handle bits between 0 and iSize,
  44670. ** inclusive. Return a pointer to the new object. Return NULL if
  44671. ** malloc fails.
  44672. */
  44673. SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
  44674. Bitvec *p;
  44675. assert( sizeof(*p)==BITVEC_SZ );
  44676. p = sqlite3MallocZero( sizeof(*p) );
  44677. if( p ){
  44678. p->iSize = iSize;
  44679. }
  44680. return p;
  44681. }
  44682. /*
  44683. ** Check to see if the i-th bit is set. Return true or false.
  44684. ** If p is NULL (if the bitmap has not been created) or if
  44685. ** i is out of range, then return false.
  44686. */
  44687. SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec *p, u32 i){
  44688. assert( p!=0 );
  44689. i--;
  44690. if( i>=p->iSize ) return 0;
  44691. while( p->iDivisor ){
  44692. u32 bin = i/p->iDivisor;
  44693. i = i%p->iDivisor;
  44694. p = p->u.apSub[bin];
  44695. if (!p) {
  44696. return 0;
  44697. }
  44698. }
  44699. if( p->iSize<=BITVEC_NBIT ){
  44700. return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
  44701. } else{
  44702. u32 h = BITVEC_HASH(i++);
  44703. while( p->u.aHash[h] ){
  44704. if( p->u.aHash[h]==i ) return 1;
  44705. h = (h+1) % BITVEC_NINT;
  44706. }
  44707. return 0;
  44708. }
  44709. }
  44710. SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
  44711. return p!=0 && sqlite3BitvecTestNotNull(p,i);
  44712. }
  44713. /*
  44714. ** Set the i-th bit. Return 0 on success and an error code if
  44715. ** anything goes wrong.
  44716. **
  44717. ** This routine might cause sub-bitmaps to be allocated. Failing
  44718. ** to get the memory needed to hold the sub-bitmap is the only
  44719. ** that can go wrong with an insert, assuming p and i are valid.
  44720. **
  44721. ** The calling function must ensure that p is a valid Bitvec object
  44722. ** and that the value for "i" is within range of the Bitvec object.
  44723. ** Otherwise the behavior is undefined.
  44724. */
  44725. SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
  44726. u32 h;
  44727. if( p==0 ) return SQLITE_OK;
  44728. assert( i>0 );
  44729. assert( i<=p->iSize );
  44730. i--;
  44731. while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
  44732. u32 bin = i/p->iDivisor;
  44733. i = i%p->iDivisor;
  44734. if( p->u.apSub[bin]==0 ){
  44735. p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
  44736. if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM_BKPT;
  44737. }
  44738. p = p->u.apSub[bin];
  44739. }
  44740. if( p->iSize<=BITVEC_NBIT ){
  44741. p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
  44742. return SQLITE_OK;
  44743. }
  44744. h = BITVEC_HASH(i++);
  44745. /* if there wasn't a hash collision, and this doesn't */
  44746. /* completely fill the hash, then just add it without */
  44747. /* worring about sub-dividing and re-hashing. */
  44748. if( !p->u.aHash[h] ){
  44749. if (p->nSet<(BITVEC_NINT-1)) {
  44750. goto bitvec_set_end;
  44751. } else {
  44752. goto bitvec_set_rehash;
  44753. }
  44754. }
  44755. /* there was a collision, check to see if it's already */
  44756. /* in hash, if not, try to find a spot for it */
  44757. do {
  44758. if( p->u.aHash[h]==i ) return SQLITE_OK;
  44759. h++;
  44760. if( h>=BITVEC_NINT ) h = 0;
  44761. } while( p->u.aHash[h] );
  44762. /* we didn't find it in the hash. h points to the first */
  44763. /* available free spot. check to see if this is going to */
  44764. /* make our hash too "full". */
  44765. bitvec_set_rehash:
  44766. if( p->nSet>=BITVEC_MXHASH ){
  44767. unsigned int j;
  44768. int rc;
  44769. u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
  44770. if( aiValues==0 ){
  44771. return SQLITE_NOMEM_BKPT;
  44772. }else{
  44773. memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
  44774. memset(p->u.apSub, 0, sizeof(p->u.apSub));
  44775. p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
  44776. rc = sqlite3BitvecSet(p, i);
  44777. for(j=0; j<BITVEC_NINT; j++){
  44778. if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
  44779. }
  44780. sqlite3StackFree(0, aiValues);
  44781. return rc;
  44782. }
  44783. }
  44784. bitvec_set_end:
  44785. p->nSet++;
  44786. p->u.aHash[h] = i;
  44787. return SQLITE_OK;
  44788. }
  44789. /*
  44790. ** Clear the i-th bit.
  44791. **
  44792. ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
  44793. ** that BitvecClear can use to rebuilt its hash table.
  44794. */
  44795. SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
  44796. if( p==0 ) return;
  44797. assert( i>0 );
  44798. i--;
  44799. while( p->iDivisor ){
  44800. u32 bin = i/p->iDivisor;
  44801. i = i%p->iDivisor;
  44802. p = p->u.apSub[bin];
  44803. if (!p) {
  44804. return;
  44805. }
  44806. }
  44807. if( p->iSize<=BITVEC_NBIT ){
  44808. p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
  44809. }else{
  44810. unsigned int j;
  44811. u32 *aiValues = pBuf;
  44812. memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
  44813. memset(p->u.aHash, 0, sizeof(p->u.aHash));
  44814. p->nSet = 0;
  44815. for(j=0; j<BITVEC_NINT; j++){
  44816. if( aiValues[j] && aiValues[j]!=(i+1) ){
  44817. u32 h = BITVEC_HASH(aiValues[j]-1);
  44818. p->nSet++;
  44819. while( p->u.aHash[h] ){
  44820. h++;
  44821. if( h>=BITVEC_NINT ) h = 0;
  44822. }
  44823. p->u.aHash[h] = aiValues[j];
  44824. }
  44825. }
  44826. }
  44827. }
  44828. /*
  44829. ** Destroy a bitmap object. Reclaim all memory used.
  44830. */
  44831. SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
  44832. if( p==0 ) return;
  44833. if( p->iDivisor ){
  44834. unsigned int i;
  44835. for(i=0; i<BITVEC_NPTR; i++){
  44836. sqlite3BitvecDestroy(p->u.apSub[i]);
  44837. }
  44838. }
  44839. sqlite3_free(p);
  44840. }
  44841. /*
  44842. ** Return the value of the iSize parameter specified when Bitvec *p
  44843. ** was created.
  44844. */
  44845. SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
  44846. return p->iSize;
  44847. }
  44848. #ifndef SQLITE_UNTESTABLE
  44849. /*
  44850. ** Let V[] be an array of unsigned characters sufficient to hold
  44851. ** up to N bits. Let I be an integer between 0 and N. 0<=I<N.
  44852. ** Then the following macros can be used to set, clear, or test
  44853. ** individual bits within V.
  44854. */
  44855. #define SETBIT(V,I) V[I>>3] |= (1<<(I&7))
  44856. #define CLEARBIT(V,I) V[I>>3] &= ~(1<<(I&7))
  44857. #define TESTBIT(V,I) (V[I>>3]&(1<<(I&7)))!=0
  44858. /*
  44859. ** This routine runs an extensive test of the Bitvec code.
  44860. **
  44861. ** The input is an array of integers that acts as a program
  44862. ** to test the Bitvec. The integers are opcodes followed
  44863. ** by 0, 1, or 3 operands, depending on the opcode. Another
  44864. ** opcode follows immediately after the last operand.
  44865. **
  44866. ** There are 6 opcodes numbered from 0 through 5. 0 is the
  44867. ** "halt" opcode and causes the test to end.
  44868. **
  44869. ** 0 Halt and return the number of errors
  44870. ** 1 N S X Set N bits beginning with S and incrementing by X
  44871. ** 2 N S X Clear N bits beginning with S and incrementing by X
  44872. ** 3 N Set N randomly chosen bits
  44873. ** 4 N Clear N randomly chosen bits
  44874. ** 5 N S X Set N bits from S increment X in array only, not in bitvec
  44875. **
  44876. ** The opcodes 1 through 4 perform set and clear operations are performed
  44877. ** on both a Bitvec object and on a linear array of bits obtained from malloc.
  44878. ** Opcode 5 works on the linear array only, not on the Bitvec.
  44879. ** Opcode 5 is used to deliberately induce a fault in order to
  44880. ** confirm that error detection works.
  44881. **
  44882. ** At the conclusion of the test the linear array is compared
  44883. ** against the Bitvec object. If there are any differences,
  44884. ** an error is returned. If they are the same, zero is returned.
  44885. **
  44886. ** If a memory allocation error occurs, return -1.
  44887. */
  44888. SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
  44889. Bitvec *pBitvec = 0;
  44890. unsigned char *pV = 0;
  44891. int rc = -1;
  44892. int i, nx, pc, op;
  44893. void *pTmpSpace;
  44894. /* Allocate the Bitvec to be tested and a linear array of
  44895. ** bits to act as the reference */
  44896. pBitvec = sqlite3BitvecCreate( sz );
  44897. pV = sqlite3MallocZero( (sz+7)/8 + 1 );
  44898. pTmpSpace = sqlite3_malloc64(BITVEC_SZ);
  44899. if( pBitvec==0 || pV==0 || pTmpSpace==0 ) goto bitvec_end;
  44900. /* NULL pBitvec tests */
  44901. sqlite3BitvecSet(0, 1);
  44902. sqlite3BitvecClear(0, 1, pTmpSpace);
  44903. /* Run the program */
  44904. pc = 0;
  44905. while( (op = aOp[pc])!=0 ){
  44906. switch( op ){
  44907. case 1:
  44908. case 2:
  44909. case 5: {
  44910. nx = 4;
  44911. i = aOp[pc+2] - 1;
  44912. aOp[pc+2] += aOp[pc+3];
  44913. break;
  44914. }
  44915. case 3:
  44916. case 4:
  44917. default: {
  44918. nx = 2;
  44919. sqlite3_randomness(sizeof(i), &i);
  44920. break;
  44921. }
  44922. }
  44923. if( (--aOp[pc+1]) > 0 ) nx = 0;
  44924. pc += nx;
  44925. i = (i & 0x7fffffff)%sz;
  44926. if( (op & 1)!=0 ){
  44927. SETBIT(pV, (i+1));
  44928. if( op!=5 ){
  44929. if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
  44930. }
  44931. }else{
  44932. CLEARBIT(pV, (i+1));
  44933. sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
  44934. }
  44935. }
  44936. /* Test to make sure the linear array exactly matches the
  44937. ** Bitvec object. Start with the assumption that they do
  44938. ** match (rc==0). Change rc to non-zero if a discrepancy
  44939. ** is found.
  44940. */
  44941. rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
  44942. + sqlite3BitvecTest(pBitvec, 0)
  44943. + (sqlite3BitvecSize(pBitvec) - sz);
  44944. for(i=1; i<=sz; i++){
  44945. if( (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
  44946. rc = i;
  44947. break;
  44948. }
  44949. }
  44950. /* Free allocated structure */
  44951. bitvec_end:
  44952. sqlite3_free(pTmpSpace);
  44953. sqlite3_free(pV);
  44954. sqlite3BitvecDestroy(pBitvec);
  44955. return rc;
  44956. }
  44957. #endif /* SQLITE_UNTESTABLE */
  44958. /************** End of bitvec.c **********************************************/
  44959. /************** Begin file pcache.c ******************************************/
  44960. /*
  44961. ** 2008 August 05
  44962. **
  44963. ** The author disclaims copyright to this source code. In place of
  44964. ** a legal notice, here is a blessing:
  44965. **
  44966. ** May you do good and not evil.
  44967. ** May you find forgiveness for yourself and forgive others.
  44968. ** May you share freely, never taking more than you give.
  44969. **
  44970. *************************************************************************
  44971. ** This file implements that page cache.
  44972. */
  44973. /* #include "sqliteInt.h" */
  44974. /*
  44975. ** A complete page cache is an instance of this structure. Every
  44976. ** entry in the cache holds a single page of the database file. The
  44977. ** btree layer only operates on the cached copy of the database pages.
  44978. **
  44979. ** A page cache entry is "clean" if it exactly matches what is currently
  44980. ** on disk. A page is "dirty" if it has been modified and needs to be
  44981. ** persisted to disk.
  44982. **
  44983. ** pDirty, pDirtyTail, pSynced:
  44984. ** All dirty pages are linked into the doubly linked list using
  44985. ** PgHdr.pDirtyNext and pDirtyPrev. The list is maintained in LRU order
  44986. ** such that p was added to the list more recently than p->pDirtyNext.
  44987. ** PCache.pDirty points to the first (newest) element in the list and
  44988. ** pDirtyTail to the last (oldest).
  44989. **
  44990. ** The PCache.pSynced variable is used to optimize searching for a dirty
  44991. ** page to eject from the cache mid-transaction. It is better to eject
  44992. ** a page that does not require a journal sync than one that does.
  44993. ** Therefore, pSynced is maintained so that it *almost* always points
  44994. ** to either the oldest page in the pDirty/pDirtyTail list that has a
  44995. ** clear PGHDR_NEED_SYNC flag or to a page that is older than this one
  44996. ** (so that the right page to eject can be found by following pDirtyPrev
  44997. ** pointers).
  44998. */
  44999. struct PCache {
  45000. PgHdr *pDirty, *pDirtyTail; /* List of dirty pages in LRU order */
  45001. PgHdr *pSynced; /* Last synced page in dirty page list */
  45002. int nRefSum; /* Sum of ref counts over all pages */
  45003. int szCache; /* Configured cache size */
  45004. int szSpill; /* Size before spilling occurs */
  45005. int szPage; /* Size of every page in this cache */
  45006. int szExtra; /* Size of extra space for each page */
  45007. u8 bPurgeable; /* True if pages are on backing store */
  45008. u8 eCreate; /* eCreate value for for xFetch() */
  45009. int (*xStress)(void*,PgHdr*); /* Call to try make a page clean */
  45010. void *pStress; /* Argument to xStress */
  45011. sqlite3_pcache *pCache; /* Pluggable cache module */
  45012. };
  45013. /********************************** Test and Debug Logic **********************/
  45014. /*
  45015. ** Debug tracing macros. Enable by by changing the "0" to "1" and
  45016. ** recompiling.
  45017. **
  45018. ** When sqlite3PcacheTrace is 1, single line trace messages are issued.
  45019. ** When sqlite3PcacheTrace is 2, a dump of the pcache showing all cache entries
  45020. ** is displayed for many operations, resulting in a lot of output.
  45021. */
  45022. #if defined(SQLITE_DEBUG) && 0
  45023. int sqlite3PcacheTrace = 2; /* 0: off 1: simple 2: cache dumps */
  45024. int sqlite3PcacheMxDump = 9999; /* Max cache entries for pcacheDump() */
  45025. # define pcacheTrace(X) if(sqlite3PcacheTrace){sqlite3DebugPrintf X;}
  45026. void pcacheDump(PCache *pCache){
  45027. int N;
  45028. int i, j;
  45029. sqlite3_pcache_page *pLower;
  45030. PgHdr *pPg;
  45031. unsigned char *a;
  45032. if( sqlite3PcacheTrace<2 ) return;
  45033. if( pCache->pCache==0 ) return;
  45034. N = sqlite3PcachePagecount(pCache);
  45035. if( N>sqlite3PcacheMxDump ) N = sqlite3PcacheMxDump;
  45036. for(i=1; i<=N; i++){
  45037. pLower = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, i, 0);
  45038. if( pLower==0 ) continue;
  45039. pPg = (PgHdr*)pLower->pExtra;
  45040. printf("%3d: nRef %2d flgs %02x data ", i, pPg->nRef, pPg->flags);
  45041. a = (unsigned char *)pLower->pBuf;
  45042. for(j=0; j<12; j++) printf("%02x", a[j]);
  45043. printf("\n");
  45044. if( pPg->pPage==0 ){
  45045. sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, pLower, 0);
  45046. }
  45047. }
  45048. }
  45049. #else
  45050. # define pcacheTrace(X)
  45051. # define pcacheDump(X)
  45052. #endif
  45053. /*
  45054. ** Check invariants on a PgHdr entry. Return true if everything is OK.
  45055. ** Return false if any invariant is violated.
  45056. **
  45057. ** This routine is for use inside of assert() statements only. For
  45058. ** example:
  45059. **
  45060. ** assert( sqlite3PcachePageSanity(pPg) );
  45061. */
  45062. #ifdef SQLITE_DEBUG
  45063. SQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr *pPg){
  45064. PCache *pCache;
  45065. assert( pPg!=0 );
  45066. assert( pPg->pgno>0 || pPg->pPager==0 ); /* Page number is 1 or more */
  45067. pCache = pPg->pCache;
  45068. assert( pCache!=0 ); /* Every page has an associated PCache */
  45069. if( pPg->flags & PGHDR_CLEAN ){
  45070. assert( (pPg->flags & PGHDR_DIRTY)==0 );/* Cannot be both CLEAN and DIRTY */
  45071. assert( pCache->pDirty!=pPg ); /* CLEAN pages not on dirty list */
  45072. assert( pCache->pDirtyTail!=pPg );
  45073. }
  45074. /* WRITEABLE pages must also be DIRTY */
  45075. if( pPg->flags & PGHDR_WRITEABLE ){
  45076. assert( pPg->flags & PGHDR_DIRTY ); /* WRITEABLE implies DIRTY */
  45077. }
  45078. /* NEED_SYNC can be set independently of WRITEABLE. This can happen,
  45079. ** for example, when using the sqlite3PagerDontWrite() optimization:
  45080. ** (1) Page X is journalled, and gets WRITEABLE and NEED_SEEK.
  45081. ** (2) Page X moved to freelist, WRITEABLE is cleared
  45082. ** (3) Page X reused, WRITEABLE is set again
  45083. ** If NEED_SYNC had been cleared in step 2, then it would not be reset
  45084. ** in step 3, and page might be written into the database without first
  45085. ** syncing the rollback journal, which might cause corruption on a power
  45086. ** loss.
  45087. **
  45088. ** Another example is when the database page size is smaller than the
  45089. ** disk sector size. When any page of a sector is journalled, all pages
  45090. ** in that sector are marked NEED_SYNC even if they are still CLEAN, just
  45091. ** in case they are later modified, since all pages in the same sector
  45092. ** must be journalled and synced before any of those pages can be safely
  45093. ** written.
  45094. */
  45095. return 1;
  45096. }
  45097. #endif /* SQLITE_DEBUG */
  45098. /********************************** Linked List Management ********************/
  45099. /* Allowed values for second argument to pcacheManageDirtyList() */
  45100. #define PCACHE_DIRTYLIST_REMOVE 1 /* Remove pPage from dirty list */
  45101. #define PCACHE_DIRTYLIST_ADD 2 /* Add pPage to the dirty list */
  45102. #define PCACHE_DIRTYLIST_FRONT 3 /* Move pPage to the front of the list */
  45103. /*
  45104. ** Manage pPage's participation on the dirty list. Bits of the addRemove
  45105. ** argument determines what operation to do. The 0x01 bit means first
  45106. ** remove pPage from the dirty list. The 0x02 means add pPage back to
  45107. ** the dirty list. Doing both moves pPage to the front of the dirty list.
  45108. */
  45109. static void pcacheManageDirtyList(PgHdr *pPage, u8 addRemove){
  45110. PCache *p = pPage->pCache;
  45111. pcacheTrace(("%p.DIRTYLIST.%s %d\n", p,
  45112. addRemove==1 ? "REMOVE" : addRemove==2 ? "ADD" : "FRONT",
  45113. pPage->pgno));
  45114. if( addRemove & PCACHE_DIRTYLIST_REMOVE ){
  45115. assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
  45116. assert( pPage->pDirtyPrev || pPage==p->pDirty );
  45117. /* Update the PCache1.pSynced variable if necessary. */
  45118. if( p->pSynced==pPage ){
  45119. p->pSynced = pPage->pDirtyPrev;
  45120. }
  45121. if( pPage->pDirtyNext ){
  45122. pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
  45123. }else{
  45124. assert( pPage==p->pDirtyTail );
  45125. p->pDirtyTail = pPage->pDirtyPrev;
  45126. }
  45127. if( pPage->pDirtyPrev ){
  45128. pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
  45129. }else{
  45130. /* If there are now no dirty pages in the cache, set eCreate to 2.
  45131. ** This is an optimization that allows sqlite3PcacheFetch() to skip
  45132. ** searching for a dirty page to eject from the cache when it might
  45133. ** otherwise have to. */
  45134. assert( pPage==p->pDirty );
  45135. p->pDirty = pPage->pDirtyNext;
  45136. assert( p->bPurgeable || p->eCreate==2 );
  45137. if( p->pDirty==0 ){ /*OPTIMIZATION-IF-TRUE*/
  45138. assert( p->bPurgeable==0 || p->eCreate==1 );
  45139. p->eCreate = 2;
  45140. }
  45141. }
  45142. }
  45143. if( addRemove & PCACHE_DIRTYLIST_ADD ){
  45144. pPage->pDirtyPrev = 0;
  45145. pPage->pDirtyNext = p->pDirty;
  45146. if( pPage->pDirtyNext ){
  45147. assert( pPage->pDirtyNext->pDirtyPrev==0 );
  45148. pPage->pDirtyNext->pDirtyPrev = pPage;
  45149. }else{
  45150. p->pDirtyTail = pPage;
  45151. if( p->bPurgeable ){
  45152. assert( p->eCreate==2 );
  45153. p->eCreate = 1;
  45154. }
  45155. }
  45156. p->pDirty = pPage;
  45157. /* If pSynced is NULL and this page has a clear NEED_SYNC flag, set
  45158. ** pSynced to point to it. Checking the NEED_SYNC flag is an
  45159. ** optimization, as if pSynced points to a page with the NEED_SYNC
  45160. ** flag set sqlite3PcacheFetchStress() searches through all newer
  45161. ** entries of the dirty-list for a page with NEED_SYNC clear anyway. */
  45162. if( !p->pSynced
  45163. && 0==(pPage->flags&PGHDR_NEED_SYNC) /*OPTIMIZATION-IF-FALSE*/
  45164. ){
  45165. p->pSynced = pPage;
  45166. }
  45167. }
  45168. pcacheDump(p);
  45169. }
  45170. /*
  45171. ** Wrapper around the pluggable caches xUnpin method. If the cache is
  45172. ** being used for an in-memory database, this function is a no-op.
  45173. */
  45174. static void pcacheUnpin(PgHdr *p){
  45175. if( p->pCache->bPurgeable ){
  45176. pcacheTrace(("%p.UNPIN %d\n", p->pCache, p->pgno));
  45177. sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 0);
  45178. pcacheDump(p->pCache);
  45179. }
  45180. }
  45181. /*
  45182. ** Compute the number of pages of cache requested. p->szCache is the
  45183. ** cache size requested by the "PRAGMA cache_size" statement.
  45184. */
  45185. static int numberOfCachePages(PCache *p){
  45186. if( p->szCache>=0 ){
  45187. /* IMPLEMENTATION-OF: R-42059-47211 If the argument N is positive then the
  45188. ** suggested cache size is set to N. */
  45189. return p->szCache;
  45190. }else{
  45191. /* IMPLEMANTATION-OF: R-59858-46238 If the argument N is negative, then the
  45192. ** number of cache pages is adjusted to be a number of pages that would
  45193. ** use approximately abs(N*1024) bytes of memory based on the current
  45194. ** page size. */
  45195. return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
  45196. }
  45197. }
  45198. /*************************************************** General Interfaces ******
  45199. **
  45200. ** Initialize and shutdown the page cache subsystem. Neither of these
  45201. ** functions are threadsafe.
  45202. */
  45203. SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
  45204. if( sqlite3GlobalConfig.pcache2.xInit==0 ){
  45205. /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
  45206. ** built-in default page cache is used instead of the application defined
  45207. ** page cache. */
  45208. sqlite3PCacheSetDefault();
  45209. }
  45210. return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
  45211. }
  45212. SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
  45213. if( sqlite3GlobalConfig.pcache2.xShutdown ){
  45214. /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
  45215. sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
  45216. }
  45217. }
  45218. /*
  45219. ** Return the size in bytes of a PCache object.
  45220. */
  45221. SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
  45222. /*
  45223. ** Create a new PCache object. Storage space to hold the object
  45224. ** has already been allocated and is passed in as the p pointer.
  45225. ** The caller discovers how much space needs to be allocated by
  45226. ** calling sqlite3PcacheSize().
  45227. **
  45228. ** szExtra is some extra space allocated for each page. The first
  45229. ** 8 bytes of the extra space will be zeroed as the page is allocated,
  45230. ** but remaining content will be uninitialized. Though it is opaque
  45231. ** to this module, the extra space really ends up being the MemPage
  45232. ** structure in the pager.
  45233. */
  45234. SQLITE_PRIVATE int sqlite3PcacheOpen(
  45235. int szPage, /* Size of every page */
  45236. int szExtra, /* Extra space associated with each page */
  45237. int bPurgeable, /* True if pages are on backing store */
  45238. int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
  45239. void *pStress, /* Argument to xStress */
  45240. PCache *p /* Preallocated space for the PCache */
  45241. ){
  45242. memset(p, 0, sizeof(PCache));
  45243. p->szPage = 1;
  45244. p->szExtra = szExtra;
  45245. assert( szExtra>=8 ); /* First 8 bytes will be zeroed */
  45246. p->bPurgeable = bPurgeable;
  45247. p->eCreate = 2;
  45248. p->xStress = xStress;
  45249. p->pStress = pStress;
  45250. p->szCache = 100;
  45251. p->szSpill = 1;
  45252. pcacheTrace(("%p.OPEN szPage %d bPurgeable %d\n",p,szPage,bPurgeable));
  45253. return sqlite3PcacheSetPageSize(p, szPage);
  45254. }
  45255. /*
  45256. ** Change the page size for PCache object. The caller must ensure that there
  45257. ** are no outstanding page references when this function is called.
  45258. */
  45259. SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
  45260. assert( pCache->nRefSum==0 && pCache->pDirty==0 );
  45261. if( pCache->szPage ){
  45262. sqlite3_pcache *pNew;
  45263. pNew = sqlite3GlobalConfig.pcache2.xCreate(
  45264. szPage, pCache->szExtra + ROUND8(sizeof(PgHdr)),
  45265. pCache->bPurgeable
  45266. );
  45267. if( pNew==0 ) return SQLITE_NOMEM_BKPT;
  45268. sqlite3GlobalConfig.pcache2.xCachesize(pNew, numberOfCachePages(pCache));
  45269. if( pCache->pCache ){
  45270. sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
  45271. }
  45272. pCache->pCache = pNew;
  45273. pCache->szPage = szPage;
  45274. pcacheTrace(("%p.PAGESIZE %d\n",pCache,szPage));
  45275. }
  45276. return SQLITE_OK;
  45277. }
  45278. /*
  45279. ** Try to obtain a page from the cache.
  45280. **
  45281. ** This routine returns a pointer to an sqlite3_pcache_page object if
  45282. ** such an object is already in cache, or if a new one is created.
  45283. ** This routine returns a NULL pointer if the object was not in cache
  45284. ** and could not be created.
  45285. **
  45286. ** The createFlags should be 0 to check for existing pages and should
  45287. ** be 3 (not 1, but 3) to try to create a new page.
  45288. **
  45289. ** If the createFlag is 0, then NULL is always returned if the page
  45290. ** is not already in the cache. If createFlag is 1, then a new page
  45291. ** is created only if that can be done without spilling dirty pages
  45292. ** and without exceeding the cache size limit.
  45293. **
  45294. ** The caller needs to invoke sqlite3PcacheFetchFinish() to properly
  45295. ** initialize the sqlite3_pcache_page object and convert it into a
  45296. ** PgHdr object. The sqlite3PcacheFetch() and sqlite3PcacheFetchFinish()
  45297. ** routines are split this way for performance reasons. When separated
  45298. ** they can both (usually) operate without having to push values to
  45299. ** the stack on entry and pop them back off on exit, which saves a
  45300. ** lot of pushing and popping.
  45301. */
  45302. SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(
  45303. PCache *pCache, /* Obtain the page from this cache */
  45304. Pgno pgno, /* Page number to obtain */
  45305. int createFlag /* If true, create page if it does not exist already */
  45306. ){
  45307. int eCreate;
  45308. sqlite3_pcache_page *pRes;
  45309. assert( pCache!=0 );
  45310. assert( pCache->pCache!=0 );
  45311. assert( createFlag==3 || createFlag==0 );
  45312. assert( pCache->eCreate==((pCache->bPurgeable && pCache->pDirty) ? 1 : 2) );
  45313. /* eCreate defines what to do if the page does not exist.
  45314. ** 0 Do not allocate a new page. (createFlag==0)
  45315. ** 1 Allocate a new page if doing so is inexpensive.
  45316. ** (createFlag==1 AND bPurgeable AND pDirty)
  45317. ** 2 Allocate a new page even it doing so is difficult.
  45318. ** (createFlag==1 AND !(bPurgeable AND pDirty)
  45319. */
  45320. eCreate = createFlag & pCache->eCreate;
  45321. assert( eCreate==0 || eCreate==1 || eCreate==2 );
  45322. assert( createFlag==0 || pCache->eCreate==eCreate );
  45323. assert( createFlag==0 || eCreate==1+(!pCache->bPurgeable||!pCache->pDirty) );
  45324. pRes = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
  45325. pcacheTrace(("%p.FETCH %d%s (result: %p)\n",pCache,pgno,
  45326. createFlag?" create":"",pRes));
  45327. return pRes;
  45328. }
  45329. /*
  45330. ** If the sqlite3PcacheFetch() routine is unable to allocate a new
  45331. ** page because no clean pages are available for reuse and the cache
  45332. ** size limit has been reached, then this routine can be invoked to
  45333. ** try harder to allocate a page. This routine might invoke the stress
  45334. ** callback to spill dirty pages to the journal. It will then try to
  45335. ** allocate the new page and will only fail to allocate a new page on
  45336. ** an OOM error.
  45337. **
  45338. ** This routine should be invoked only after sqlite3PcacheFetch() fails.
  45339. */
  45340. SQLITE_PRIVATE int sqlite3PcacheFetchStress(
  45341. PCache *pCache, /* Obtain the page from this cache */
  45342. Pgno pgno, /* Page number to obtain */
  45343. sqlite3_pcache_page **ppPage /* Write result here */
  45344. ){
  45345. PgHdr *pPg;
  45346. if( pCache->eCreate==2 ) return 0;
  45347. if( sqlite3PcachePagecount(pCache)>pCache->szSpill ){
  45348. /* Find a dirty page to write-out and recycle. First try to find a
  45349. ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
  45350. ** cleared), but if that is not possible settle for any other
  45351. ** unreferenced dirty page.
  45352. **
  45353. ** If the LRU page in the dirty list that has a clear PGHDR_NEED_SYNC
  45354. ** flag is currently referenced, then the following may leave pSynced
  45355. ** set incorrectly (pointing to other than the LRU page with NEED_SYNC
  45356. ** cleared). This is Ok, as pSynced is just an optimization. */
  45357. for(pPg=pCache->pSynced;
  45358. pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
  45359. pPg=pPg->pDirtyPrev
  45360. );
  45361. pCache->pSynced = pPg;
  45362. if( !pPg ){
  45363. for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
  45364. }
  45365. if( pPg ){
  45366. int rc;
  45367. #ifdef SQLITE_LOG_CACHE_SPILL
  45368. sqlite3_log(SQLITE_FULL,
  45369. "spill page %d making room for %d - cache used: %d/%d",
  45370. pPg->pgno, pgno,
  45371. sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache),
  45372. numberOfCachePages(pCache));
  45373. #endif
  45374. pcacheTrace(("%p.SPILL %d\n",pCache,pPg->pgno));
  45375. rc = pCache->xStress(pCache->pStress, pPg);
  45376. pcacheDump(pCache);
  45377. if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
  45378. return rc;
  45379. }
  45380. }
  45381. }
  45382. *ppPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
  45383. return *ppPage==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK;
  45384. }
  45385. /*
  45386. ** This is a helper routine for sqlite3PcacheFetchFinish()
  45387. **
  45388. ** In the uncommon case where the page being fetched has not been
  45389. ** initialized, this routine is invoked to do the initialization.
  45390. ** This routine is broken out into a separate function since it
  45391. ** requires extra stack manipulation that can be avoided in the common
  45392. ** case.
  45393. */
  45394. static SQLITE_NOINLINE PgHdr *pcacheFetchFinishWithInit(
  45395. PCache *pCache, /* Obtain the page from this cache */
  45396. Pgno pgno, /* Page number obtained */
  45397. sqlite3_pcache_page *pPage /* Page obtained by prior PcacheFetch() call */
  45398. ){
  45399. PgHdr *pPgHdr;
  45400. assert( pPage!=0 );
  45401. pPgHdr = (PgHdr*)pPage->pExtra;
  45402. assert( pPgHdr->pPage==0 );
  45403. memset(&pPgHdr->pDirty, 0, sizeof(PgHdr) - offsetof(PgHdr,pDirty));
  45404. pPgHdr->pPage = pPage;
  45405. pPgHdr->pData = pPage->pBuf;
  45406. pPgHdr->pExtra = (void *)&pPgHdr[1];
  45407. memset(pPgHdr->pExtra, 0, 8);
  45408. pPgHdr->pCache = pCache;
  45409. pPgHdr->pgno = pgno;
  45410. pPgHdr->flags = PGHDR_CLEAN;
  45411. return sqlite3PcacheFetchFinish(pCache,pgno,pPage);
  45412. }
  45413. /*
  45414. ** This routine converts the sqlite3_pcache_page object returned by
  45415. ** sqlite3PcacheFetch() into an initialized PgHdr object. This routine
  45416. ** must be called after sqlite3PcacheFetch() in order to get a usable
  45417. ** result.
  45418. */
  45419. SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(
  45420. PCache *pCache, /* Obtain the page from this cache */
  45421. Pgno pgno, /* Page number obtained */
  45422. sqlite3_pcache_page *pPage /* Page obtained by prior PcacheFetch() call */
  45423. ){
  45424. PgHdr *pPgHdr;
  45425. assert( pPage!=0 );
  45426. pPgHdr = (PgHdr *)pPage->pExtra;
  45427. if( !pPgHdr->pPage ){
  45428. return pcacheFetchFinishWithInit(pCache, pgno, pPage);
  45429. }
  45430. pCache->nRefSum++;
  45431. pPgHdr->nRef++;
  45432. assert( sqlite3PcachePageSanity(pPgHdr) );
  45433. return pPgHdr;
  45434. }
  45435. /*
  45436. ** Decrement the reference count on a page. If the page is clean and the
  45437. ** reference count drops to 0, then it is made eligible for recycling.
  45438. */
  45439. SQLITE_PRIVATE void SQLITE_NOINLINE sqlite3PcacheRelease(PgHdr *p){
  45440. assert( p->nRef>0 );
  45441. p->pCache->nRefSum--;
  45442. if( (--p->nRef)==0 ){
  45443. if( p->flags&PGHDR_CLEAN ){
  45444. pcacheUnpin(p);
  45445. }else{
  45446. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
  45447. }
  45448. }
  45449. }
  45450. /*
  45451. ** Increase the reference count of a supplied page by 1.
  45452. */
  45453. SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
  45454. assert(p->nRef>0);
  45455. assert( sqlite3PcachePageSanity(p) );
  45456. p->nRef++;
  45457. p->pCache->nRefSum++;
  45458. }
  45459. /*
  45460. ** Drop a page from the cache. There must be exactly one reference to the
  45461. ** page. This function deletes that reference, so after it returns the
  45462. ** page pointed to by p is invalid.
  45463. */
  45464. SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
  45465. assert( p->nRef==1 );
  45466. assert( sqlite3PcachePageSanity(p) );
  45467. if( p->flags&PGHDR_DIRTY ){
  45468. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
  45469. }
  45470. p->pCache->nRefSum--;
  45471. sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 1);
  45472. }
  45473. /*
  45474. ** Make sure the page is marked as dirty. If it isn't dirty already,
  45475. ** make it so.
  45476. */
  45477. SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
  45478. assert( p->nRef>0 );
  45479. assert( sqlite3PcachePageSanity(p) );
  45480. if( p->flags & (PGHDR_CLEAN|PGHDR_DONT_WRITE) ){ /*OPTIMIZATION-IF-FALSE*/
  45481. p->flags &= ~PGHDR_DONT_WRITE;
  45482. if( p->flags & PGHDR_CLEAN ){
  45483. p->flags ^= (PGHDR_DIRTY|PGHDR_CLEAN);
  45484. pcacheTrace(("%p.DIRTY %d\n",p->pCache,p->pgno));
  45485. assert( (p->flags & (PGHDR_DIRTY|PGHDR_CLEAN))==PGHDR_DIRTY );
  45486. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_ADD);
  45487. }
  45488. assert( sqlite3PcachePageSanity(p) );
  45489. }
  45490. }
  45491. /*
  45492. ** Make sure the page is marked as clean. If it isn't clean already,
  45493. ** make it so.
  45494. */
  45495. SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
  45496. assert( sqlite3PcachePageSanity(p) );
  45497. assert( (p->flags & PGHDR_DIRTY)!=0 );
  45498. assert( (p->flags & PGHDR_CLEAN)==0 );
  45499. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
  45500. p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC|PGHDR_WRITEABLE);
  45501. p->flags |= PGHDR_CLEAN;
  45502. pcacheTrace(("%p.CLEAN %d\n",p->pCache,p->pgno));
  45503. assert( sqlite3PcachePageSanity(p) );
  45504. if( p->nRef==0 ){
  45505. pcacheUnpin(p);
  45506. }
  45507. }
  45508. /*
  45509. ** Make every page in the cache clean.
  45510. */
  45511. SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
  45512. PgHdr *p;
  45513. pcacheTrace(("%p.CLEAN-ALL\n",pCache));
  45514. while( (p = pCache->pDirty)!=0 ){
  45515. sqlite3PcacheMakeClean(p);
  45516. }
  45517. }
  45518. /*
  45519. ** Clear the PGHDR_NEED_SYNC and PGHDR_WRITEABLE flag from all dirty pages.
  45520. */
  45521. SQLITE_PRIVATE void sqlite3PcacheClearWritable(PCache *pCache){
  45522. PgHdr *p;
  45523. pcacheTrace(("%p.CLEAR-WRITEABLE\n",pCache));
  45524. for(p=pCache->pDirty; p; p=p->pDirtyNext){
  45525. p->flags &= ~(PGHDR_NEED_SYNC|PGHDR_WRITEABLE);
  45526. }
  45527. pCache->pSynced = pCache->pDirtyTail;
  45528. }
  45529. /*
  45530. ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
  45531. */
  45532. SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
  45533. PgHdr *p;
  45534. for(p=pCache->pDirty; p; p=p->pDirtyNext){
  45535. p->flags &= ~PGHDR_NEED_SYNC;
  45536. }
  45537. pCache->pSynced = pCache->pDirtyTail;
  45538. }
  45539. /*
  45540. ** Change the page number of page p to newPgno.
  45541. */
  45542. SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
  45543. PCache *pCache = p->pCache;
  45544. assert( p->nRef>0 );
  45545. assert( newPgno>0 );
  45546. assert( sqlite3PcachePageSanity(p) );
  45547. pcacheTrace(("%p.MOVE %d -> %d\n",pCache,p->pgno,newPgno));
  45548. sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
  45549. p->pgno = newPgno;
  45550. if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
  45551. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
  45552. }
  45553. }
  45554. /*
  45555. ** Drop every cache entry whose page number is greater than "pgno". The
  45556. ** caller must ensure that there are no outstanding references to any pages
  45557. ** other than page 1 with a page number greater than pgno.
  45558. **
  45559. ** If there is a reference to page 1 and the pgno parameter passed to this
  45560. ** function is 0, then the data area associated with page 1 is zeroed, but
  45561. ** the page object is not dropped.
  45562. */
  45563. SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
  45564. if( pCache->pCache ){
  45565. PgHdr *p;
  45566. PgHdr *pNext;
  45567. pcacheTrace(("%p.TRUNCATE %d\n",pCache,pgno));
  45568. for(p=pCache->pDirty; p; p=pNext){
  45569. pNext = p->pDirtyNext;
  45570. /* This routine never gets call with a positive pgno except right
  45571. ** after sqlite3PcacheCleanAll(). So if there are dirty pages,
  45572. ** it must be that pgno==0.
  45573. */
  45574. assert( p->pgno>0 );
  45575. if( p->pgno>pgno ){
  45576. assert( p->flags&PGHDR_DIRTY );
  45577. sqlite3PcacheMakeClean(p);
  45578. }
  45579. }
  45580. if( pgno==0 && pCache->nRefSum ){
  45581. sqlite3_pcache_page *pPage1;
  45582. pPage1 = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache,1,0);
  45583. if( ALWAYS(pPage1) ){ /* Page 1 is always available in cache, because
  45584. ** pCache->nRefSum>0 */
  45585. memset(pPage1->pBuf, 0, pCache->szPage);
  45586. pgno = 1;
  45587. }
  45588. }
  45589. sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
  45590. }
  45591. }
  45592. /*
  45593. ** Close a cache.
  45594. */
  45595. SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
  45596. assert( pCache->pCache!=0 );
  45597. pcacheTrace(("%p.CLOSE\n",pCache));
  45598. sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
  45599. }
  45600. /*
  45601. ** Discard the contents of the cache.
  45602. */
  45603. SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
  45604. sqlite3PcacheTruncate(pCache, 0);
  45605. }
  45606. /*
  45607. ** Merge two lists of pages connected by pDirty and in pgno order.
  45608. ** Do not bother fixing the pDirtyPrev pointers.
  45609. */
  45610. static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
  45611. PgHdr result, *pTail;
  45612. pTail = &result;
  45613. assert( pA!=0 && pB!=0 );
  45614. for(;;){
  45615. if( pA->pgno<pB->pgno ){
  45616. pTail->pDirty = pA;
  45617. pTail = pA;
  45618. pA = pA->pDirty;
  45619. if( pA==0 ){
  45620. pTail->pDirty = pB;
  45621. break;
  45622. }
  45623. }else{
  45624. pTail->pDirty = pB;
  45625. pTail = pB;
  45626. pB = pB->pDirty;
  45627. if( pB==0 ){
  45628. pTail->pDirty = pA;
  45629. break;
  45630. }
  45631. }
  45632. }
  45633. return result.pDirty;
  45634. }
  45635. /*
  45636. ** Sort the list of pages in accending order by pgno. Pages are
  45637. ** connected by pDirty pointers. The pDirtyPrev pointers are
  45638. ** corrupted by this sort.
  45639. **
  45640. ** Since there cannot be more than 2^31 distinct pages in a database,
  45641. ** there cannot be more than 31 buckets required by the merge sorter.
  45642. ** One extra bucket is added to catch overflow in case something
  45643. ** ever changes to make the previous sentence incorrect.
  45644. */
  45645. #define N_SORT_BUCKET 32
  45646. static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
  45647. PgHdr *a[N_SORT_BUCKET], *p;
  45648. int i;
  45649. memset(a, 0, sizeof(a));
  45650. while( pIn ){
  45651. p = pIn;
  45652. pIn = p->pDirty;
  45653. p->pDirty = 0;
  45654. for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
  45655. if( a[i]==0 ){
  45656. a[i] = p;
  45657. break;
  45658. }else{
  45659. p = pcacheMergeDirtyList(a[i], p);
  45660. a[i] = 0;
  45661. }
  45662. }
  45663. if( NEVER(i==N_SORT_BUCKET-1) ){
  45664. /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
  45665. ** the input list. But that is impossible.
  45666. */
  45667. a[i] = pcacheMergeDirtyList(a[i], p);
  45668. }
  45669. }
  45670. p = a[0];
  45671. for(i=1; i<N_SORT_BUCKET; i++){
  45672. if( a[i]==0 ) continue;
  45673. p = p ? pcacheMergeDirtyList(p, a[i]) : a[i];
  45674. }
  45675. return p;
  45676. }
  45677. /*
  45678. ** Return a list of all dirty pages in the cache, sorted by page number.
  45679. */
  45680. SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
  45681. PgHdr *p;
  45682. for(p=pCache->pDirty; p; p=p->pDirtyNext){
  45683. p->pDirty = p->pDirtyNext;
  45684. }
  45685. return pcacheSortDirtyList(pCache->pDirty);
  45686. }
  45687. /*
  45688. ** Return the total number of references to all pages held by the cache.
  45689. **
  45690. ** This is not the total number of pages referenced, but the sum of the
  45691. ** reference count for all pages.
  45692. */
  45693. SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
  45694. return pCache->nRefSum;
  45695. }
  45696. /*
  45697. ** Return the number of references to the page supplied as an argument.
  45698. */
  45699. SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
  45700. return p->nRef;
  45701. }
  45702. /*
  45703. ** Return the total number of pages in the cache.
  45704. */
  45705. SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
  45706. assert( pCache->pCache!=0 );
  45707. return sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
  45708. }
  45709. #ifdef SQLITE_TEST
  45710. /*
  45711. ** Get the suggested cache-size value.
  45712. */
  45713. SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
  45714. return numberOfCachePages(pCache);
  45715. }
  45716. #endif
  45717. /*
  45718. ** Set the suggested cache-size value.
  45719. */
  45720. SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
  45721. assert( pCache->pCache!=0 );
  45722. pCache->szCache = mxPage;
  45723. sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
  45724. numberOfCachePages(pCache));
  45725. }
  45726. /*
  45727. ** Set the suggested cache-spill value. Make no changes if if the
  45728. ** argument is zero. Return the effective cache-spill size, which will
  45729. ** be the larger of the szSpill and szCache.
  45730. */
  45731. SQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *p, int mxPage){
  45732. int res;
  45733. assert( p->pCache!=0 );
  45734. if( mxPage ){
  45735. if( mxPage<0 ){
  45736. mxPage = (int)((-1024*(i64)mxPage)/(p->szPage+p->szExtra));
  45737. }
  45738. p->szSpill = mxPage;
  45739. }
  45740. res = numberOfCachePages(p);
  45741. if( res<p->szSpill ) res = p->szSpill;
  45742. return res;
  45743. }
  45744. /*
  45745. ** Free up as much memory as possible from the page cache.
  45746. */
  45747. SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){
  45748. assert( pCache->pCache!=0 );
  45749. sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
  45750. }
  45751. /*
  45752. ** Return the size of the header added by this middleware layer
  45753. ** in the page-cache hierarchy.
  45754. */
  45755. SQLITE_PRIVATE int sqlite3HeaderSizePcache(void){ return ROUND8(sizeof(PgHdr)); }
  45756. /*
  45757. ** Return the number of dirty pages currently in the cache, as a percentage
  45758. ** of the configured cache size.
  45759. */
  45760. SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache *pCache){
  45761. PgHdr *pDirty;
  45762. int nDirty = 0;
  45763. int nCache = numberOfCachePages(pCache);
  45764. for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext) nDirty++;
  45765. return nCache ? (int)(((i64)nDirty * 100) / nCache) : 0;
  45766. }
  45767. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  45768. /*
  45769. ** Return true if there are one or more dirty pages in the cache. Else false.
  45770. */
  45771. SQLITE_PRIVATE int sqlite3PCacheIsDirty(PCache *pCache){
  45772. return (pCache->pDirty!=0);
  45773. }
  45774. #endif
  45775. #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
  45776. /*
  45777. ** For all dirty pages currently in the cache, invoke the specified
  45778. ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
  45779. ** defined.
  45780. */
  45781. SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
  45782. PgHdr *pDirty;
  45783. for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
  45784. xIter(pDirty);
  45785. }
  45786. }
  45787. #endif
  45788. /************** End of pcache.c **********************************************/
  45789. /************** Begin file pcache1.c *****************************************/
  45790. /*
  45791. ** 2008 November 05
  45792. **
  45793. ** The author disclaims copyright to this source code. In place of
  45794. ** a legal notice, here is a blessing:
  45795. **
  45796. ** May you do good and not evil.
  45797. ** May you find forgiveness for yourself and forgive others.
  45798. ** May you share freely, never taking more than you give.
  45799. **
  45800. *************************************************************************
  45801. **
  45802. ** This file implements the default page cache implementation (the
  45803. ** sqlite3_pcache interface). It also contains part of the implementation
  45804. ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
  45805. ** If the default page cache implementation is overridden, then neither of
  45806. ** these two features are available.
  45807. **
  45808. ** A Page cache line looks like this:
  45809. **
  45810. ** -------------------------------------------------------------
  45811. ** | database page content | PgHdr1 | MemPage | PgHdr |
  45812. ** -------------------------------------------------------------
  45813. **
  45814. ** The database page content is up front (so that buffer overreads tend to
  45815. ** flow harmlessly into the PgHdr1, MemPage, and PgHdr extensions). MemPage
  45816. ** is the extension added by the btree.c module containing information such
  45817. ** as the database page number and how that database page is used. PgHdr
  45818. ** is added by the pcache.c layer and contains information used to keep track
  45819. ** of which pages are "dirty". PgHdr1 is an extension added by this
  45820. ** module (pcache1.c). The PgHdr1 header is a subclass of sqlite3_pcache_page.
  45821. ** PgHdr1 contains information needed to look up a page by its page number.
  45822. ** The superclass sqlite3_pcache_page.pBuf points to the start of the
  45823. ** database page content and sqlite3_pcache_page.pExtra points to PgHdr.
  45824. **
  45825. ** The size of the extension (MemPage+PgHdr+PgHdr1) can be determined at
  45826. ** runtime using sqlite3_config(SQLITE_CONFIG_PCACHE_HDRSZ, &size). The
  45827. ** sizes of the extensions sum to 272 bytes on x64 for 3.8.10, but this
  45828. ** size can vary according to architecture, compile-time options, and
  45829. ** SQLite library version number.
  45830. **
  45831. ** If SQLITE_PCACHE_SEPARATE_HEADER is defined, then the extension is obtained
  45832. ** using a separate memory allocation from the database page content. This
  45833. ** seeks to overcome the "clownshoe" problem (also called "internal
  45834. ** fragmentation" in academic literature) of allocating a few bytes more
  45835. ** than a power of two with the memory allocator rounding up to the next
  45836. ** power of two, and leaving the rounded-up space unused.
  45837. **
  45838. ** This module tracks pointers to PgHdr1 objects. Only pcache.c communicates
  45839. ** with this module. Information is passed back and forth as PgHdr1 pointers.
  45840. **
  45841. ** The pcache.c and pager.c modules deal pointers to PgHdr objects.
  45842. ** The btree.c module deals with pointers to MemPage objects.
  45843. **
  45844. ** SOURCE OF PAGE CACHE MEMORY:
  45845. **
  45846. ** Memory for a page might come from any of three sources:
  45847. **
  45848. ** (1) The general-purpose memory allocator - sqlite3Malloc()
  45849. ** (2) Global page-cache memory provided using sqlite3_config() with
  45850. ** SQLITE_CONFIG_PAGECACHE.
  45851. ** (3) PCache-local bulk allocation.
  45852. **
  45853. ** The third case is a chunk of heap memory (defaulting to 100 pages worth)
  45854. ** that is allocated when the page cache is created. The size of the local
  45855. ** bulk allocation can be adjusted using
  45856. **
  45857. ** sqlite3_config(SQLITE_CONFIG_PAGECACHE, (void*)0, 0, N).
  45858. **
  45859. ** If N is positive, then N pages worth of memory are allocated using a single
  45860. ** sqlite3Malloc() call and that memory is used for the first N pages allocated.
  45861. ** Or if N is negative, then -1024*N bytes of memory are allocated and used
  45862. ** for as many pages as can be accomodated.
  45863. **
  45864. ** Only one of (2) or (3) can be used. Once the memory available to (2) or
  45865. ** (3) is exhausted, subsequent allocations fail over to the general-purpose
  45866. ** memory allocator (1).
  45867. **
  45868. ** Earlier versions of SQLite used only methods (1) and (2). But experiments
  45869. ** show that method (3) with N==100 provides about a 5% performance boost for
  45870. ** common workloads.
  45871. */
  45872. /* #include "sqliteInt.h" */
  45873. typedef struct PCache1 PCache1;
  45874. typedef struct PgHdr1 PgHdr1;
  45875. typedef struct PgFreeslot PgFreeslot;
  45876. typedef struct PGroup PGroup;
  45877. /*
  45878. ** Each cache entry is represented by an instance of the following
  45879. ** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
  45880. ** PgHdr1.pCache->szPage bytes is allocated directly before this structure
  45881. ** in memory.
  45882. **
  45883. ** Note: Variables isBulkLocal and isAnchor were once type "u8". That works,
  45884. ** but causes a 2-byte gap in the structure for most architectures (since
  45885. ** pointers must be either 4 or 8-byte aligned). As this structure is located
  45886. ** in memory directly after the associated page data, if the database is
  45887. ** corrupt, code at the b-tree layer may overread the page buffer and
  45888. ** read part of this structure before the corruption is detected. This
  45889. ** can cause a valgrind error if the unitialized gap is accessed. Using u16
  45890. ** ensures there is no such gap, and therefore no bytes of unitialized memory
  45891. ** in the structure.
  45892. */
  45893. struct PgHdr1 {
  45894. sqlite3_pcache_page page; /* Base class. Must be first. pBuf & pExtra */
  45895. unsigned int iKey; /* Key value (page number) */
  45896. u16 isBulkLocal; /* This page from bulk local storage */
  45897. u16 isAnchor; /* This is the PGroup.lru element */
  45898. PgHdr1 *pNext; /* Next in hash table chain */
  45899. PCache1 *pCache; /* Cache that currently owns this page */
  45900. PgHdr1 *pLruNext; /* Next in LRU list of unpinned pages */
  45901. PgHdr1 *pLruPrev; /* Previous in LRU list of unpinned pages */
  45902. /* NB: pLruPrev is only valid if pLruNext!=0 */
  45903. };
  45904. /*
  45905. ** A page is pinned if it is not on the LRU list. To be "pinned" means
  45906. ** that the page is in active use and must not be deallocated.
  45907. */
  45908. #define PAGE_IS_PINNED(p) ((p)->pLruNext==0)
  45909. #define PAGE_IS_UNPINNED(p) ((p)->pLruNext!=0)
  45910. /* Each page cache (or PCache) belongs to a PGroup. A PGroup is a set
  45911. ** of one or more PCaches that are able to recycle each other's unpinned
  45912. ** pages when they are under memory pressure. A PGroup is an instance of
  45913. ** the following object.
  45914. **
  45915. ** This page cache implementation works in one of two modes:
  45916. **
  45917. ** (1) Every PCache is the sole member of its own PGroup. There is
  45918. ** one PGroup per PCache.
  45919. **
  45920. ** (2) There is a single global PGroup that all PCaches are a member
  45921. ** of.
  45922. **
  45923. ** Mode 1 uses more memory (since PCache instances are not able to rob
  45924. ** unused pages from other PCaches) but it also operates without a mutex,
  45925. ** and is therefore often faster. Mode 2 requires a mutex in order to be
  45926. ** threadsafe, but recycles pages more efficiently.
  45927. **
  45928. ** For mode (1), PGroup.mutex is NULL. For mode (2) there is only a single
  45929. ** PGroup which is the pcache1.grp global variable and its mutex is
  45930. ** SQLITE_MUTEX_STATIC_LRU.
  45931. */
  45932. struct PGroup {
  45933. sqlite3_mutex *mutex; /* MUTEX_STATIC_LRU or NULL */
  45934. unsigned int nMaxPage; /* Sum of nMax for purgeable caches */
  45935. unsigned int nMinPage; /* Sum of nMin for purgeable caches */
  45936. unsigned int mxPinned; /* nMaxpage + 10 - nMinPage */
  45937. unsigned int nPurgeable; /* Number of purgeable pages allocated */
  45938. PgHdr1 lru; /* The beginning and end of the LRU list */
  45939. };
  45940. /* Each page cache is an instance of the following object. Every
  45941. ** open database file (including each in-memory database and each
  45942. ** temporary or transient database) has a single page cache which
  45943. ** is an instance of this object.
  45944. **
  45945. ** Pointers to structures of this type are cast and returned as
  45946. ** opaque sqlite3_pcache* handles.
  45947. */
  45948. struct PCache1 {
  45949. /* Cache configuration parameters. Page size (szPage) and the purgeable
  45950. ** flag (bPurgeable) and the pnPurgeable pointer are all set when the
  45951. ** cache is created and are never changed thereafter. nMax may be
  45952. ** modified at any time by a call to the pcache1Cachesize() method.
  45953. ** The PGroup mutex must be held when accessing nMax.
  45954. */
  45955. PGroup *pGroup; /* PGroup this cache belongs to */
  45956. unsigned int *pnPurgeable; /* Pointer to pGroup->nPurgeable */
  45957. int szPage; /* Size of database content section */
  45958. int szExtra; /* sizeof(MemPage)+sizeof(PgHdr) */
  45959. int szAlloc; /* Total size of one pcache line */
  45960. int bPurgeable; /* True if cache is purgeable */
  45961. unsigned int nMin; /* Minimum number of pages reserved */
  45962. unsigned int nMax; /* Configured "cache_size" value */
  45963. unsigned int n90pct; /* nMax*9/10 */
  45964. unsigned int iMaxKey; /* Largest key seen since xTruncate() */
  45965. unsigned int nPurgeableDummy; /* pnPurgeable points here when not used*/
  45966. /* Hash table of all pages. The following variables may only be accessed
  45967. ** when the accessor is holding the PGroup mutex.
  45968. */
  45969. unsigned int nRecyclable; /* Number of pages in the LRU list */
  45970. unsigned int nPage; /* Total number of pages in apHash */
  45971. unsigned int nHash; /* Number of slots in apHash[] */
  45972. PgHdr1 **apHash; /* Hash table for fast lookup by key */
  45973. PgHdr1 *pFree; /* List of unused pcache-local pages */
  45974. void *pBulk; /* Bulk memory used by pcache-local */
  45975. };
  45976. /*
  45977. ** Free slots in the allocator used to divide up the global page cache
  45978. ** buffer provided using the SQLITE_CONFIG_PAGECACHE mechanism.
  45979. */
  45980. struct PgFreeslot {
  45981. PgFreeslot *pNext; /* Next free slot */
  45982. };
  45983. /*
  45984. ** Global data used by this cache.
  45985. */
  45986. static SQLITE_WSD struct PCacheGlobal {
  45987. PGroup grp; /* The global PGroup for mode (2) */
  45988. /* Variables related to SQLITE_CONFIG_PAGECACHE settings. The
  45989. ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
  45990. ** fixed at sqlite3_initialize() time and do not require mutex protection.
  45991. ** The nFreeSlot and pFree values do require mutex protection.
  45992. */
  45993. int isInit; /* True if initialized */
  45994. int separateCache; /* Use a new PGroup for each PCache */
  45995. int nInitPage; /* Initial bulk allocation size */
  45996. int szSlot; /* Size of each free slot */
  45997. int nSlot; /* The number of pcache slots */
  45998. int nReserve; /* Try to keep nFreeSlot above this */
  45999. void *pStart, *pEnd; /* Bounds of global page cache memory */
  46000. /* Above requires no mutex. Use mutex below for variable that follow. */
  46001. sqlite3_mutex *mutex; /* Mutex for accessing the following: */
  46002. PgFreeslot *pFree; /* Free page blocks */
  46003. int nFreeSlot; /* Number of unused pcache slots */
  46004. /* The following value requires a mutex to change. We skip the mutex on
  46005. ** reading because (1) most platforms read a 32-bit integer atomically and
  46006. ** (2) even if an incorrect value is read, no great harm is done since this
  46007. ** is really just an optimization. */
  46008. int bUnderPressure; /* True if low on PAGECACHE memory */
  46009. } pcache1_g;
  46010. /*
  46011. ** All code in this file should access the global structure above via the
  46012. ** alias "pcache1". This ensures that the WSD emulation is used when
  46013. ** compiling for systems that do not support real WSD.
  46014. */
  46015. #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
  46016. /*
  46017. ** Macros to enter and leave the PCache LRU mutex.
  46018. */
  46019. #if !defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
  46020. # define pcache1EnterMutex(X) assert((X)->mutex==0)
  46021. # define pcache1LeaveMutex(X) assert((X)->mutex==0)
  46022. # define PCACHE1_MIGHT_USE_GROUP_MUTEX 0
  46023. #else
  46024. # define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
  46025. # define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
  46026. # define PCACHE1_MIGHT_USE_GROUP_MUTEX 1
  46027. #endif
  46028. /******************************************************************************/
  46029. /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
  46030. /*
  46031. ** This function is called during initialization if a static buffer is
  46032. ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
  46033. ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
  46034. ** enough to contain 'n' buffers of 'sz' bytes each.
  46035. **
  46036. ** This routine is called from sqlite3_initialize() and so it is guaranteed
  46037. ** to be serialized already. There is no need for further mutexing.
  46038. */
  46039. SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
  46040. if( pcache1.isInit ){
  46041. PgFreeslot *p;
  46042. if( pBuf==0 ) sz = n = 0;
  46043. if( n==0 ) sz = 0;
  46044. sz = ROUNDDOWN8(sz);
  46045. pcache1.szSlot = sz;
  46046. pcache1.nSlot = pcache1.nFreeSlot = n;
  46047. pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
  46048. pcache1.pStart = pBuf;
  46049. pcache1.pFree = 0;
  46050. pcache1.bUnderPressure = 0;
  46051. while( n-- ){
  46052. p = (PgFreeslot*)pBuf;
  46053. p->pNext = pcache1.pFree;
  46054. pcache1.pFree = p;
  46055. pBuf = (void*)&((char*)pBuf)[sz];
  46056. }
  46057. pcache1.pEnd = pBuf;
  46058. }
  46059. }
  46060. /*
  46061. ** Try to initialize the pCache->pFree and pCache->pBulk fields. Return
  46062. ** true if pCache->pFree ends up containing one or more free pages.
  46063. */
  46064. static int pcache1InitBulk(PCache1 *pCache){
  46065. i64 szBulk;
  46066. char *zBulk;
  46067. if( pcache1.nInitPage==0 ) return 0;
  46068. /* Do not bother with a bulk allocation if the cache size very small */
  46069. if( pCache->nMax<3 ) return 0;
  46070. sqlite3BeginBenignMalloc();
  46071. if( pcache1.nInitPage>0 ){
  46072. szBulk = pCache->szAlloc * (i64)pcache1.nInitPage;
  46073. }else{
  46074. szBulk = -1024 * (i64)pcache1.nInitPage;
  46075. }
  46076. if( szBulk > pCache->szAlloc*(i64)pCache->nMax ){
  46077. szBulk = pCache->szAlloc*(i64)pCache->nMax;
  46078. }
  46079. zBulk = pCache->pBulk = sqlite3Malloc( szBulk );
  46080. sqlite3EndBenignMalloc();
  46081. if( zBulk ){
  46082. int nBulk = sqlite3MallocSize(zBulk)/pCache->szAlloc;
  46083. do{
  46084. PgHdr1 *pX = (PgHdr1*)&zBulk[pCache->szPage];
  46085. pX->page.pBuf = zBulk;
  46086. pX->page.pExtra = &pX[1];
  46087. pX->isBulkLocal = 1;
  46088. pX->isAnchor = 0;
  46089. pX->pNext = pCache->pFree;
  46090. pX->pLruPrev = 0; /* Initializing this saves a valgrind error */
  46091. pCache->pFree = pX;
  46092. zBulk += pCache->szAlloc;
  46093. }while( --nBulk );
  46094. }
  46095. return pCache->pFree!=0;
  46096. }
  46097. /*
  46098. ** Malloc function used within this file to allocate space from the buffer
  46099. ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
  46100. ** such buffer exists or there is no space left in it, this function falls
  46101. ** back to sqlite3Malloc().
  46102. **
  46103. ** Multiple threads can run this routine at the same time. Global variables
  46104. ** in pcache1 need to be protected via mutex.
  46105. */
  46106. static void *pcache1Alloc(int nByte){
  46107. void *p = 0;
  46108. assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
  46109. if( nByte<=pcache1.szSlot ){
  46110. sqlite3_mutex_enter(pcache1.mutex);
  46111. p = (PgHdr1 *)pcache1.pFree;
  46112. if( p ){
  46113. pcache1.pFree = pcache1.pFree->pNext;
  46114. pcache1.nFreeSlot--;
  46115. pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
  46116. assert( pcache1.nFreeSlot>=0 );
  46117. sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
  46118. sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_USED, 1);
  46119. }
  46120. sqlite3_mutex_leave(pcache1.mutex);
  46121. }
  46122. if( p==0 ){
  46123. /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool. Get
  46124. ** it from sqlite3Malloc instead.
  46125. */
  46126. p = sqlite3Malloc(nByte);
  46127. #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
  46128. if( p ){
  46129. int sz = sqlite3MallocSize(p);
  46130. sqlite3_mutex_enter(pcache1.mutex);
  46131. sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
  46132. sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
  46133. sqlite3_mutex_leave(pcache1.mutex);
  46134. }
  46135. #endif
  46136. sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
  46137. }
  46138. return p;
  46139. }
  46140. /*
  46141. ** Free an allocated buffer obtained from pcache1Alloc().
  46142. */
  46143. static void pcache1Free(void *p){
  46144. if( p==0 ) return;
  46145. if( SQLITE_WITHIN(p, pcache1.pStart, pcache1.pEnd) ){
  46146. PgFreeslot *pSlot;
  46147. sqlite3_mutex_enter(pcache1.mutex);
  46148. sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_USED, 1);
  46149. pSlot = (PgFreeslot*)p;
  46150. pSlot->pNext = pcache1.pFree;
  46151. pcache1.pFree = pSlot;
  46152. pcache1.nFreeSlot++;
  46153. pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
  46154. assert( pcache1.nFreeSlot<=pcache1.nSlot );
  46155. sqlite3_mutex_leave(pcache1.mutex);
  46156. }else{
  46157. assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
  46158. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  46159. #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
  46160. {
  46161. int nFreed = 0;
  46162. nFreed = sqlite3MallocSize(p);
  46163. sqlite3_mutex_enter(pcache1.mutex);
  46164. sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_OVERFLOW, nFreed);
  46165. sqlite3_mutex_leave(pcache1.mutex);
  46166. }
  46167. #endif
  46168. sqlite3_free(p);
  46169. }
  46170. }
  46171. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  46172. /*
  46173. ** Return the size of a pcache allocation
  46174. */
  46175. static int pcache1MemSize(void *p){
  46176. if( p>=pcache1.pStart && p<pcache1.pEnd ){
  46177. return pcache1.szSlot;
  46178. }else{
  46179. int iSize;
  46180. assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
  46181. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  46182. iSize = sqlite3MallocSize(p);
  46183. sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
  46184. return iSize;
  46185. }
  46186. }
  46187. #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
  46188. /*
  46189. ** Allocate a new page object initially associated with cache pCache.
  46190. */
  46191. static PgHdr1 *pcache1AllocPage(PCache1 *pCache, int benignMalloc){
  46192. PgHdr1 *p = 0;
  46193. void *pPg;
  46194. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  46195. if( pCache->pFree || (pCache->nPage==0 && pcache1InitBulk(pCache)) ){
  46196. p = pCache->pFree;
  46197. pCache->pFree = p->pNext;
  46198. p->pNext = 0;
  46199. }else{
  46200. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  46201. /* The group mutex must be released before pcache1Alloc() is called. This
  46202. ** is because it might call sqlite3_release_memory(), which assumes that
  46203. ** this mutex is not held. */
  46204. assert( pcache1.separateCache==0 );
  46205. assert( pCache->pGroup==&pcache1.grp );
  46206. pcache1LeaveMutex(pCache->pGroup);
  46207. #endif
  46208. if( benignMalloc ){ sqlite3BeginBenignMalloc(); }
  46209. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  46210. pPg = pcache1Alloc(pCache->szPage);
  46211. p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
  46212. if( !pPg || !p ){
  46213. pcache1Free(pPg);
  46214. sqlite3_free(p);
  46215. pPg = 0;
  46216. }
  46217. #else
  46218. pPg = pcache1Alloc(pCache->szAlloc);
  46219. p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
  46220. #endif
  46221. if( benignMalloc ){ sqlite3EndBenignMalloc(); }
  46222. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  46223. pcache1EnterMutex(pCache->pGroup);
  46224. #endif
  46225. if( pPg==0 ) return 0;
  46226. p->page.pBuf = pPg;
  46227. p->page.pExtra = &p[1];
  46228. p->isBulkLocal = 0;
  46229. p->isAnchor = 0;
  46230. }
  46231. (*pCache->pnPurgeable)++;
  46232. return p;
  46233. }
  46234. /*
  46235. ** Free a page object allocated by pcache1AllocPage().
  46236. */
  46237. static void pcache1FreePage(PgHdr1 *p){
  46238. PCache1 *pCache;
  46239. assert( p!=0 );
  46240. pCache = p->pCache;
  46241. assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
  46242. if( p->isBulkLocal ){
  46243. p->pNext = pCache->pFree;
  46244. pCache->pFree = p;
  46245. }else{
  46246. pcache1Free(p->page.pBuf);
  46247. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  46248. sqlite3_free(p);
  46249. #endif
  46250. }
  46251. (*pCache->pnPurgeable)--;
  46252. }
  46253. /*
  46254. ** Malloc function used by SQLite to obtain space from the buffer configured
  46255. ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
  46256. ** exists, this function falls back to sqlite3Malloc().
  46257. */
  46258. SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
  46259. assert( sz<=65536+8 ); /* These allocations are never very large */
  46260. return pcache1Alloc(sz);
  46261. }
  46262. /*
  46263. ** Free an allocated buffer obtained from sqlite3PageMalloc().
  46264. */
  46265. SQLITE_PRIVATE void sqlite3PageFree(void *p){
  46266. pcache1Free(p);
  46267. }
  46268. /*
  46269. ** Return true if it desirable to avoid allocating a new page cache
  46270. ** entry.
  46271. **
  46272. ** If memory was allocated specifically to the page cache using
  46273. ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
  46274. ** it is desirable to avoid allocating a new page cache entry because
  46275. ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
  46276. ** for all page cache needs and we should not need to spill the
  46277. ** allocation onto the heap.
  46278. **
  46279. ** Or, the heap is used for all page cache memory but the heap is
  46280. ** under memory pressure, then again it is desirable to avoid
  46281. ** allocating a new page cache entry in order to avoid stressing
  46282. ** the heap even further.
  46283. */
  46284. static int pcache1UnderMemoryPressure(PCache1 *pCache){
  46285. if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
  46286. return pcache1.bUnderPressure;
  46287. }else{
  46288. return sqlite3HeapNearlyFull();
  46289. }
  46290. }
  46291. /******************************************************************************/
  46292. /******** General Implementation Functions ************************************/
  46293. /*
  46294. ** This function is used to resize the hash table used by the cache passed
  46295. ** as the first argument.
  46296. **
  46297. ** The PCache mutex must be held when this function is called.
  46298. */
  46299. static void pcache1ResizeHash(PCache1 *p){
  46300. PgHdr1 **apNew;
  46301. unsigned int nNew;
  46302. unsigned int i;
  46303. assert( sqlite3_mutex_held(p->pGroup->mutex) );
  46304. nNew = p->nHash*2;
  46305. if( nNew<256 ){
  46306. nNew = 256;
  46307. }
  46308. pcache1LeaveMutex(p->pGroup);
  46309. if( p->nHash ){ sqlite3BeginBenignMalloc(); }
  46310. apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);
  46311. if( p->nHash ){ sqlite3EndBenignMalloc(); }
  46312. pcache1EnterMutex(p->pGroup);
  46313. if( apNew ){
  46314. for(i=0; i<p->nHash; i++){
  46315. PgHdr1 *pPage;
  46316. PgHdr1 *pNext = p->apHash[i];
  46317. while( (pPage = pNext)!=0 ){
  46318. unsigned int h = pPage->iKey % nNew;
  46319. pNext = pPage->pNext;
  46320. pPage->pNext = apNew[h];
  46321. apNew[h] = pPage;
  46322. }
  46323. }
  46324. sqlite3_free(p->apHash);
  46325. p->apHash = apNew;
  46326. p->nHash = nNew;
  46327. }
  46328. }
  46329. /*
  46330. ** This function is used internally to remove the page pPage from the
  46331. ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
  46332. ** LRU list, then this function is a no-op.
  46333. **
  46334. ** The PGroup mutex must be held when this function is called.
  46335. */
  46336. static PgHdr1 *pcache1PinPage(PgHdr1 *pPage){
  46337. assert( pPage!=0 );
  46338. assert( PAGE_IS_UNPINNED(pPage) );
  46339. assert( pPage->pLruNext );
  46340. assert( pPage->pLruPrev );
  46341. assert( sqlite3_mutex_held(pPage->pCache->pGroup->mutex) );
  46342. pPage->pLruPrev->pLruNext = pPage->pLruNext;
  46343. pPage->pLruNext->pLruPrev = pPage->pLruPrev;
  46344. pPage->pLruNext = 0;
  46345. /* pPage->pLruPrev = 0;
  46346. ** No need to clear pLruPrev as it is never accessed if pLruNext is 0 */
  46347. assert( pPage->isAnchor==0 );
  46348. assert( pPage->pCache->pGroup->lru.isAnchor==1 );
  46349. pPage->pCache->nRecyclable--;
  46350. return pPage;
  46351. }
  46352. /*
  46353. ** Remove the page supplied as an argument from the hash table
  46354. ** (PCache1.apHash structure) that it is currently stored in.
  46355. ** Also free the page if freePage is true.
  46356. **
  46357. ** The PGroup mutex must be held when this function is called.
  46358. */
  46359. static void pcache1RemoveFromHash(PgHdr1 *pPage, int freeFlag){
  46360. unsigned int h;
  46361. PCache1 *pCache = pPage->pCache;
  46362. PgHdr1 **pp;
  46363. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  46364. h = pPage->iKey % pCache->nHash;
  46365. for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
  46366. *pp = (*pp)->pNext;
  46367. pCache->nPage--;
  46368. if( freeFlag ) pcache1FreePage(pPage);
  46369. }
  46370. /*
  46371. ** If there are currently more than nMaxPage pages allocated, try
  46372. ** to recycle pages to reduce the number allocated to nMaxPage.
  46373. */
  46374. static void pcache1EnforceMaxPage(PCache1 *pCache){
  46375. PGroup *pGroup = pCache->pGroup;
  46376. PgHdr1 *p;
  46377. assert( sqlite3_mutex_held(pGroup->mutex) );
  46378. while( pGroup->nPurgeable>pGroup->nMaxPage
  46379. && (p=pGroup->lru.pLruPrev)->isAnchor==0
  46380. ){
  46381. assert( p->pCache->pGroup==pGroup );
  46382. assert( PAGE_IS_UNPINNED(p) );
  46383. pcache1PinPage(p);
  46384. pcache1RemoveFromHash(p, 1);
  46385. }
  46386. if( pCache->nPage==0 && pCache->pBulk ){
  46387. sqlite3_free(pCache->pBulk);
  46388. pCache->pBulk = pCache->pFree = 0;
  46389. }
  46390. }
  46391. /*
  46392. ** Discard all pages from cache pCache with a page number (key value)
  46393. ** greater than or equal to iLimit. Any pinned pages that meet this
  46394. ** criteria are unpinned before they are discarded.
  46395. **
  46396. ** The PCache mutex must be held when this function is called.
  46397. */
  46398. static void pcache1TruncateUnsafe(
  46399. PCache1 *pCache, /* The cache to truncate */
  46400. unsigned int iLimit /* Drop pages with this pgno or larger */
  46401. ){
  46402. TESTONLY( int nPage = 0; ) /* To assert pCache->nPage is correct */
  46403. unsigned int h, iStop;
  46404. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  46405. assert( pCache->iMaxKey >= iLimit );
  46406. assert( pCache->nHash > 0 );
  46407. if( pCache->iMaxKey - iLimit < pCache->nHash ){
  46408. /* If we are just shaving the last few pages off the end of the
  46409. ** cache, then there is no point in scanning the entire hash table.
  46410. ** Only scan those hash slots that might contain pages that need to
  46411. ** be removed. */
  46412. h = iLimit % pCache->nHash;
  46413. iStop = pCache->iMaxKey % pCache->nHash;
  46414. TESTONLY( nPage = -10; ) /* Disable the pCache->nPage validity check */
  46415. }else{
  46416. /* This is the general case where many pages are being removed.
  46417. ** It is necessary to scan the entire hash table */
  46418. h = pCache->nHash/2;
  46419. iStop = h - 1;
  46420. }
  46421. for(;;){
  46422. PgHdr1 **pp;
  46423. PgHdr1 *pPage;
  46424. assert( h<pCache->nHash );
  46425. pp = &pCache->apHash[h];
  46426. while( (pPage = *pp)!=0 ){
  46427. if( pPage->iKey>=iLimit ){
  46428. pCache->nPage--;
  46429. *pp = pPage->pNext;
  46430. if( PAGE_IS_UNPINNED(pPage) ) pcache1PinPage(pPage);
  46431. pcache1FreePage(pPage);
  46432. }else{
  46433. pp = &pPage->pNext;
  46434. TESTONLY( if( nPage>=0 ) nPage++; )
  46435. }
  46436. }
  46437. if( h==iStop ) break;
  46438. h = (h+1) % pCache->nHash;
  46439. }
  46440. assert( nPage<0 || pCache->nPage==(unsigned)nPage );
  46441. }
  46442. /******************************************************************************/
  46443. /******** sqlite3_pcache Methods **********************************************/
  46444. /*
  46445. ** Implementation of the sqlite3_pcache.xInit method.
  46446. */
  46447. static int pcache1Init(void *NotUsed){
  46448. UNUSED_PARAMETER(NotUsed);
  46449. assert( pcache1.isInit==0 );
  46450. memset(&pcache1, 0, sizeof(pcache1));
  46451. /*
  46452. ** The pcache1.separateCache variable is true if each PCache has its own
  46453. ** private PGroup (mode-1). pcache1.separateCache is false if the single
  46454. ** PGroup in pcache1.grp is used for all page caches (mode-2).
  46455. **
  46456. ** * Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
  46457. **
  46458. ** * Use a unified cache in single-threaded applications that have
  46459. ** configured a start-time buffer for use as page-cache memory using
  46460. ** sqlite3_config(SQLITE_CONFIG_PAGECACHE, pBuf, sz, N) with non-NULL
  46461. ** pBuf argument.
  46462. **
  46463. ** * Otherwise use separate caches (mode-1)
  46464. */
  46465. #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT)
  46466. pcache1.separateCache = 0;
  46467. #elif SQLITE_THREADSAFE
  46468. pcache1.separateCache = sqlite3GlobalConfig.pPage==0
  46469. || sqlite3GlobalConfig.bCoreMutex>0;
  46470. #else
  46471. pcache1.separateCache = sqlite3GlobalConfig.pPage==0;
  46472. #endif
  46473. #if SQLITE_THREADSAFE
  46474. if( sqlite3GlobalConfig.bCoreMutex ){
  46475. pcache1.grp.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU);
  46476. pcache1.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PMEM);
  46477. }
  46478. #endif
  46479. if( pcache1.separateCache
  46480. && sqlite3GlobalConfig.nPage!=0
  46481. && sqlite3GlobalConfig.pPage==0
  46482. ){
  46483. pcache1.nInitPage = sqlite3GlobalConfig.nPage;
  46484. }else{
  46485. pcache1.nInitPage = 0;
  46486. }
  46487. pcache1.grp.mxPinned = 10;
  46488. pcache1.isInit = 1;
  46489. return SQLITE_OK;
  46490. }
  46491. /*
  46492. ** Implementation of the sqlite3_pcache.xShutdown method.
  46493. ** Note that the static mutex allocated in xInit does
  46494. ** not need to be freed.
  46495. */
  46496. static void pcache1Shutdown(void *NotUsed){
  46497. UNUSED_PARAMETER(NotUsed);
  46498. assert( pcache1.isInit!=0 );
  46499. memset(&pcache1, 0, sizeof(pcache1));
  46500. }
  46501. /* forward declaration */
  46502. static void pcache1Destroy(sqlite3_pcache *p);
  46503. /*
  46504. ** Implementation of the sqlite3_pcache.xCreate method.
  46505. **
  46506. ** Allocate a new cache.
  46507. */
  46508. static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
  46509. PCache1 *pCache; /* The newly created page cache */
  46510. PGroup *pGroup; /* The group the new page cache will belong to */
  46511. int sz; /* Bytes of memory required to allocate the new cache */
  46512. assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
  46513. assert( szExtra < 300 );
  46514. sz = sizeof(PCache1) + sizeof(PGroup)*pcache1.separateCache;
  46515. pCache = (PCache1 *)sqlite3MallocZero(sz);
  46516. if( pCache ){
  46517. if( pcache1.separateCache ){
  46518. pGroup = (PGroup*)&pCache[1];
  46519. pGroup->mxPinned = 10;
  46520. }else{
  46521. pGroup = &pcache1.grp;
  46522. }
  46523. pcache1EnterMutex(pGroup);
  46524. if( pGroup->lru.isAnchor==0 ){
  46525. pGroup->lru.isAnchor = 1;
  46526. pGroup->lru.pLruPrev = pGroup->lru.pLruNext = &pGroup->lru;
  46527. }
  46528. pCache->pGroup = pGroup;
  46529. pCache->szPage = szPage;
  46530. pCache->szExtra = szExtra;
  46531. pCache->szAlloc = szPage + szExtra + ROUND8(sizeof(PgHdr1));
  46532. pCache->bPurgeable = (bPurgeable ? 1 : 0);
  46533. pcache1ResizeHash(pCache);
  46534. if( bPurgeable ){
  46535. pCache->nMin = 10;
  46536. pGroup->nMinPage += pCache->nMin;
  46537. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  46538. pCache->pnPurgeable = &pGroup->nPurgeable;
  46539. }else{
  46540. pCache->pnPurgeable = &pCache->nPurgeableDummy;
  46541. }
  46542. pcache1LeaveMutex(pGroup);
  46543. if( pCache->nHash==0 ){
  46544. pcache1Destroy((sqlite3_pcache*)pCache);
  46545. pCache = 0;
  46546. }
  46547. }
  46548. return (sqlite3_pcache *)pCache;
  46549. }
  46550. /*
  46551. ** Implementation of the sqlite3_pcache.xCachesize method.
  46552. **
  46553. ** Configure the cache_size limit for a cache.
  46554. */
  46555. static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
  46556. PCache1 *pCache = (PCache1 *)p;
  46557. if( pCache->bPurgeable ){
  46558. PGroup *pGroup = pCache->pGroup;
  46559. pcache1EnterMutex(pGroup);
  46560. pGroup->nMaxPage += (nMax - pCache->nMax);
  46561. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  46562. pCache->nMax = nMax;
  46563. pCache->n90pct = pCache->nMax*9/10;
  46564. pcache1EnforceMaxPage(pCache);
  46565. pcache1LeaveMutex(pGroup);
  46566. }
  46567. }
  46568. /*
  46569. ** Implementation of the sqlite3_pcache.xShrink method.
  46570. **
  46571. ** Free up as much memory as possible.
  46572. */
  46573. static void pcache1Shrink(sqlite3_pcache *p){
  46574. PCache1 *pCache = (PCache1*)p;
  46575. if( pCache->bPurgeable ){
  46576. PGroup *pGroup = pCache->pGroup;
  46577. int savedMaxPage;
  46578. pcache1EnterMutex(pGroup);
  46579. savedMaxPage = pGroup->nMaxPage;
  46580. pGroup->nMaxPage = 0;
  46581. pcache1EnforceMaxPage(pCache);
  46582. pGroup->nMaxPage = savedMaxPage;
  46583. pcache1LeaveMutex(pGroup);
  46584. }
  46585. }
  46586. /*
  46587. ** Implementation of the sqlite3_pcache.xPagecount method.
  46588. */
  46589. static int pcache1Pagecount(sqlite3_pcache *p){
  46590. int n;
  46591. PCache1 *pCache = (PCache1*)p;
  46592. pcache1EnterMutex(pCache->pGroup);
  46593. n = pCache->nPage;
  46594. pcache1LeaveMutex(pCache->pGroup);
  46595. return n;
  46596. }
  46597. /*
  46598. ** Implement steps 3, 4, and 5 of the pcache1Fetch() algorithm described
  46599. ** in the header of the pcache1Fetch() procedure.
  46600. **
  46601. ** This steps are broken out into a separate procedure because they are
  46602. ** usually not needed, and by avoiding the stack initialization required
  46603. ** for these steps, the main pcache1Fetch() procedure can run faster.
  46604. */
  46605. static SQLITE_NOINLINE PgHdr1 *pcache1FetchStage2(
  46606. PCache1 *pCache,
  46607. unsigned int iKey,
  46608. int createFlag
  46609. ){
  46610. unsigned int nPinned;
  46611. PGroup *pGroup = pCache->pGroup;
  46612. PgHdr1 *pPage = 0;
  46613. /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
  46614. assert( pCache->nPage >= pCache->nRecyclable );
  46615. nPinned = pCache->nPage - pCache->nRecyclable;
  46616. assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
  46617. assert( pCache->n90pct == pCache->nMax*9/10 );
  46618. if( createFlag==1 && (
  46619. nPinned>=pGroup->mxPinned
  46620. || nPinned>=pCache->n90pct
  46621. || (pcache1UnderMemoryPressure(pCache) && pCache->nRecyclable<nPinned)
  46622. )){
  46623. return 0;
  46624. }
  46625. if( pCache->nPage>=pCache->nHash ) pcache1ResizeHash(pCache);
  46626. assert( pCache->nHash>0 && pCache->apHash );
  46627. /* Step 4. Try to recycle a page. */
  46628. if( pCache->bPurgeable
  46629. && !pGroup->lru.pLruPrev->isAnchor
  46630. && ((pCache->nPage+1>=pCache->nMax) || pcache1UnderMemoryPressure(pCache))
  46631. ){
  46632. PCache1 *pOther;
  46633. pPage = pGroup->lru.pLruPrev;
  46634. assert( PAGE_IS_UNPINNED(pPage) );
  46635. pcache1RemoveFromHash(pPage, 0);
  46636. pcache1PinPage(pPage);
  46637. pOther = pPage->pCache;
  46638. if( pOther->szAlloc != pCache->szAlloc ){
  46639. pcache1FreePage(pPage);
  46640. pPage = 0;
  46641. }else{
  46642. pGroup->nPurgeable -= (pOther->bPurgeable - pCache->bPurgeable);
  46643. }
  46644. }
  46645. /* Step 5. If a usable page buffer has still not been found,
  46646. ** attempt to allocate a new one.
  46647. */
  46648. if( !pPage ){
  46649. pPage = pcache1AllocPage(pCache, createFlag==1);
  46650. }
  46651. if( pPage ){
  46652. unsigned int h = iKey % pCache->nHash;
  46653. pCache->nPage++;
  46654. pPage->iKey = iKey;
  46655. pPage->pNext = pCache->apHash[h];
  46656. pPage->pCache = pCache;
  46657. pPage->pLruNext = 0;
  46658. /* pPage->pLruPrev = 0;
  46659. ** No need to clear pLruPrev since it is not accessed when pLruNext==0 */
  46660. *(void **)pPage->page.pExtra = 0;
  46661. pCache->apHash[h] = pPage;
  46662. if( iKey>pCache->iMaxKey ){
  46663. pCache->iMaxKey = iKey;
  46664. }
  46665. }
  46666. return pPage;
  46667. }
  46668. /*
  46669. ** Implementation of the sqlite3_pcache.xFetch method.
  46670. **
  46671. ** Fetch a page by key value.
  46672. **
  46673. ** Whether or not a new page may be allocated by this function depends on
  46674. ** the value of the createFlag argument. 0 means do not allocate a new
  46675. ** page. 1 means allocate a new page if space is easily available. 2
  46676. ** means to try really hard to allocate a new page.
  46677. **
  46678. ** For a non-purgeable cache (a cache used as the storage for an in-memory
  46679. ** database) there is really no difference between createFlag 1 and 2. So
  46680. ** the calling function (pcache.c) will never have a createFlag of 1 on
  46681. ** a non-purgeable cache.
  46682. **
  46683. ** There are three different approaches to obtaining space for a page,
  46684. ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
  46685. **
  46686. ** 1. Regardless of the value of createFlag, the cache is searched for a
  46687. ** copy of the requested page. If one is found, it is returned.
  46688. **
  46689. ** 2. If createFlag==0 and the page is not already in the cache, NULL is
  46690. ** returned.
  46691. **
  46692. ** 3. If createFlag is 1, and the page is not already in the cache, then
  46693. ** return NULL (do not allocate a new page) if any of the following
  46694. ** conditions are true:
  46695. **
  46696. ** (a) the number of pages pinned by the cache is greater than
  46697. ** PCache1.nMax, or
  46698. **
  46699. ** (b) the number of pages pinned by the cache is greater than
  46700. ** the sum of nMax for all purgeable caches, less the sum of
  46701. ** nMin for all other purgeable caches, or
  46702. **
  46703. ** 4. If none of the first three conditions apply and the cache is marked
  46704. ** as purgeable, and if one of the following is true:
  46705. **
  46706. ** (a) The number of pages allocated for the cache is already
  46707. ** PCache1.nMax, or
  46708. **
  46709. ** (b) The number of pages allocated for all purgeable caches is
  46710. ** already equal to or greater than the sum of nMax for all
  46711. ** purgeable caches,
  46712. **
  46713. ** (c) The system is under memory pressure and wants to avoid
  46714. ** unnecessary pages cache entry allocations
  46715. **
  46716. ** then attempt to recycle a page from the LRU list. If it is the right
  46717. ** size, return the recycled buffer. Otherwise, free the buffer and
  46718. ** proceed to step 5.
  46719. **
  46720. ** 5. Otherwise, allocate and return a new page buffer.
  46721. **
  46722. ** There are two versions of this routine. pcache1FetchWithMutex() is
  46723. ** the general case. pcache1FetchNoMutex() is a faster implementation for
  46724. ** the common case where pGroup->mutex is NULL. The pcache1Fetch() wrapper
  46725. ** invokes the appropriate routine.
  46726. */
  46727. static PgHdr1 *pcache1FetchNoMutex(
  46728. sqlite3_pcache *p,
  46729. unsigned int iKey,
  46730. int createFlag
  46731. ){
  46732. PCache1 *pCache = (PCache1 *)p;
  46733. PgHdr1 *pPage = 0;
  46734. /* Step 1: Search the hash table for an existing entry. */
  46735. pPage = pCache->apHash[iKey % pCache->nHash];
  46736. while( pPage && pPage->iKey!=iKey ){ pPage = pPage->pNext; }
  46737. /* Step 2: If the page was found in the hash table, then return it.
  46738. ** If the page was not in the hash table and createFlag is 0, abort.
  46739. ** Otherwise (page not in hash and createFlag!=0) continue with
  46740. ** subsequent steps to try to create the page. */
  46741. if( pPage ){
  46742. if( PAGE_IS_UNPINNED(pPage) ){
  46743. return pcache1PinPage(pPage);
  46744. }else{
  46745. return pPage;
  46746. }
  46747. }else if( createFlag ){
  46748. /* Steps 3, 4, and 5 implemented by this subroutine */
  46749. return pcache1FetchStage2(pCache, iKey, createFlag);
  46750. }else{
  46751. return 0;
  46752. }
  46753. }
  46754. #if PCACHE1_MIGHT_USE_GROUP_MUTEX
  46755. static PgHdr1 *pcache1FetchWithMutex(
  46756. sqlite3_pcache *p,
  46757. unsigned int iKey,
  46758. int createFlag
  46759. ){
  46760. PCache1 *pCache = (PCache1 *)p;
  46761. PgHdr1 *pPage;
  46762. pcache1EnterMutex(pCache->pGroup);
  46763. pPage = pcache1FetchNoMutex(p, iKey, createFlag);
  46764. assert( pPage==0 || pCache->iMaxKey>=iKey );
  46765. pcache1LeaveMutex(pCache->pGroup);
  46766. return pPage;
  46767. }
  46768. #endif
  46769. static sqlite3_pcache_page *pcache1Fetch(
  46770. sqlite3_pcache *p,
  46771. unsigned int iKey,
  46772. int createFlag
  46773. ){
  46774. #if PCACHE1_MIGHT_USE_GROUP_MUTEX || defined(SQLITE_DEBUG)
  46775. PCache1 *pCache = (PCache1 *)p;
  46776. #endif
  46777. assert( offsetof(PgHdr1,page)==0 );
  46778. assert( pCache->bPurgeable || createFlag!=1 );
  46779. assert( pCache->bPurgeable || pCache->nMin==0 );
  46780. assert( pCache->bPurgeable==0 || pCache->nMin==10 );
  46781. assert( pCache->nMin==0 || pCache->bPurgeable );
  46782. assert( pCache->nHash>0 );
  46783. #if PCACHE1_MIGHT_USE_GROUP_MUTEX
  46784. if( pCache->pGroup->mutex ){
  46785. return (sqlite3_pcache_page*)pcache1FetchWithMutex(p, iKey, createFlag);
  46786. }else
  46787. #endif
  46788. {
  46789. return (sqlite3_pcache_page*)pcache1FetchNoMutex(p, iKey, createFlag);
  46790. }
  46791. }
  46792. /*
  46793. ** Implementation of the sqlite3_pcache.xUnpin method.
  46794. **
  46795. ** Mark a page as unpinned (eligible for asynchronous recycling).
  46796. */
  46797. static void pcache1Unpin(
  46798. sqlite3_pcache *p,
  46799. sqlite3_pcache_page *pPg,
  46800. int reuseUnlikely
  46801. ){
  46802. PCache1 *pCache = (PCache1 *)p;
  46803. PgHdr1 *pPage = (PgHdr1 *)pPg;
  46804. PGroup *pGroup = pCache->pGroup;
  46805. assert( pPage->pCache==pCache );
  46806. pcache1EnterMutex(pGroup);
  46807. /* It is an error to call this function if the page is already
  46808. ** part of the PGroup LRU list.
  46809. */
  46810. assert( pPage->pLruNext==0 );
  46811. assert( PAGE_IS_PINNED(pPage) );
  46812. if( reuseUnlikely || pGroup->nPurgeable>pGroup->nMaxPage ){
  46813. pcache1RemoveFromHash(pPage, 1);
  46814. }else{
  46815. /* Add the page to the PGroup LRU list. */
  46816. PgHdr1 **ppFirst = &pGroup->lru.pLruNext;
  46817. pPage->pLruPrev = &pGroup->lru;
  46818. (pPage->pLruNext = *ppFirst)->pLruPrev = pPage;
  46819. *ppFirst = pPage;
  46820. pCache->nRecyclable++;
  46821. }
  46822. pcache1LeaveMutex(pCache->pGroup);
  46823. }
  46824. /*
  46825. ** Implementation of the sqlite3_pcache.xRekey method.
  46826. */
  46827. static void pcache1Rekey(
  46828. sqlite3_pcache *p,
  46829. sqlite3_pcache_page *pPg,
  46830. unsigned int iOld,
  46831. unsigned int iNew
  46832. ){
  46833. PCache1 *pCache = (PCache1 *)p;
  46834. PgHdr1 *pPage = (PgHdr1 *)pPg;
  46835. PgHdr1 **pp;
  46836. unsigned int h;
  46837. assert( pPage->iKey==iOld );
  46838. assert( pPage->pCache==pCache );
  46839. pcache1EnterMutex(pCache->pGroup);
  46840. h = iOld%pCache->nHash;
  46841. pp = &pCache->apHash[h];
  46842. while( (*pp)!=pPage ){
  46843. pp = &(*pp)->pNext;
  46844. }
  46845. *pp = pPage->pNext;
  46846. h = iNew%pCache->nHash;
  46847. pPage->iKey = iNew;
  46848. pPage->pNext = pCache->apHash[h];
  46849. pCache->apHash[h] = pPage;
  46850. if( iNew>pCache->iMaxKey ){
  46851. pCache->iMaxKey = iNew;
  46852. }
  46853. pcache1LeaveMutex(pCache->pGroup);
  46854. }
  46855. /*
  46856. ** Implementation of the sqlite3_pcache.xTruncate method.
  46857. **
  46858. ** Discard all unpinned pages in the cache with a page number equal to
  46859. ** or greater than parameter iLimit. Any pinned pages with a page number
  46860. ** equal to or greater than iLimit are implicitly unpinned.
  46861. */
  46862. static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
  46863. PCache1 *pCache = (PCache1 *)p;
  46864. pcache1EnterMutex(pCache->pGroup);
  46865. if( iLimit<=pCache->iMaxKey ){
  46866. pcache1TruncateUnsafe(pCache, iLimit);
  46867. pCache->iMaxKey = iLimit-1;
  46868. }
  46869. pcache1LeaveMutex(pCache->pGroup);
  46870. }
  46871. /*
  46872. ** Implementation of the sqlite3_pcache.xDestroy method.
  46873. **
  46874. ** Destroy a cache allocated using pcache1Create().
  46875. */
  46876. static void pcache1Destroy(sqlite3_pcache *p){
  46877. PCache1 *pCache = (PCache1 *)p;
  46878. PGroup *pGroup = pCache->pGroup;
  46879. assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
  46880. pcache1EnterMutex(pGroup);
  46881. if( pCache->nPage ) pcache1TruncateUnsafe(pCache, 0);
  46882. assert( pGroup->nMaxPage >= pCache->nMax );
  46883. pGroup->nMaxPage -= pCache->nMax;
  46884. assert( pGroup->nMinPage >= pCache->nMin );
  46885. pGroup->nMinPage -= pCache->nMin;
  46886. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  46887. pcache1EnforceMaxPage(pCache);
  46888. pcache1LeaveMutex(pGroup);
  46889. sqlite3_free(pCache->pBulk);
  46890. sqlite3_free(pCache->apHash);
  46891. sqlite3_free(pCache);
  46892. }
  46893. /*
  46894. ** This function is called during initialization (sqlite3_initialize()) to
  46895. ** install the default pluggable cache module, assuming the user has not
  46896. ** already provided an alternative.
  46897. */
  46898. SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
  46899. static const sqlite3_pcache_methods2 defaultMethods = {
  46900. 1, /* iVersion */
  46901. 0, /* pArg */
  46902. pcache1Init, /* xInit */
  46903. pcache1Shutdown, /* xShutdown */
  46904. pcache1Create, /* xCreate */
  46905. pcache1Cachesize, /* xCachesize */
  46906. pcache1Pagecount, /* xPagecount */
  46907. pcache1Fetch, /* xFetch */
  46908. pcache1Unpin, /* xUnpin */
  46909. pcache1Rekey, /* xRekey */
  46910. pcache1Truncate, /* xTruncate */
  46911. pcache1Destroy, /* xDestroy */
  46912. pcache1Shrink /* xShrink */
  46913. };
  46914. sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
  46915. }
  46916. /*
  46917. ** Return the size of the header on each page of this PCACHE implementation.
  46918. */
  46919. SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void){ return ROUND8(sizeof(PgHdr1)); }
  46920. /*
  46921. ** Return the global mutex used by this PCACHE implementation. The
  46922. ** sqlite3_status() routine needs access to this mutex.
  46923. */
  46924. SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void){
  46925. return pcache1.mutex;
  46926. }
  46927. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  46928. /*
  46929. ** This function is called to free superfluous dynamically allocated memory
  46930. ** held by the pager system. Memory in use by any SQLite pager allocated
  46931. ** by the current thread may be sqlite3_free()ed.
  46932. **
  46933. ** nReq is the number of bytes of memory required. Once this much has
  46934. ** been released, the function returns. The return value is the total number
  46935. ** of bytes of memory released.
  46936. */
  46937. SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
  46938. int nFree = 0;
  46939. assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
  46940. assert( sqlite3_mutex_notheld(pcache1.mutex) );
  46941. if( sqlite3GlobalConfig.pPage==0 ){
  46942. PgHdr1 *p;
  46943. pcache1EnterMutex(&pcache1.grp);
  46944. while( (nReq<0 || nFree<nReq)
  46945. && (p=pcache1.grp.lru.pLruPrev)!=0
  46946. && p->isAnchor==0
  46947. ){
  46948. nFree += pcache1MemSize(p->page.pBuf);
  46949. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  46950. nFree += sqlite3MemSize(p);
  46951. #endif
  46952. assert( PAGE_IS_UNPINNED(p) );
  46953. pcache1PinPage(p);
  46954. pcache1RemoveFromHash(p, 1);
  46955. }
  46956. pcache1LeaveMutex(&pcache1.grp);
  46957. }
  46958. return nFree;
  46959. }
  46960. #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
  46961. #ifdef SQLITE_TEST
  46962. /*
  46963. ** This function is used by test procedures to inspect the internal state
  46964. ** of the global cache.
  46965. */
  46966. SQLITE_PRIVATE void sqlite3PcacheStats(
  46967. int *pnCurrent, /* OUT: Total number of pages cached */
  46968. int *pnMax, /* OUT: Global maximum cache size */
  46969. int *pnMin, /* OUT: Sum of PCache1.nMin for purgeable caches */
  46970. int *pnRecyclable /* OUT: Total number of pages available for recycling */
  46971. ){
  46972. PgHdr1 *p;
  46973. int nRecyclable = 0;
  46974. for(p=pcache1.grp.lru.pLruNext; p && !p->isAnchor; p=p->pLruNext){
  46975. assert( PAGE_IS_UNPINNED(p) );
  46976. nRecyclable++;
  46977. }
  46978. *pnCurrent = pcache1.grp.nPurgeable;
  46979. *pnMax = (int)pcache1.grp.nMaxPage;
  46980. *pnMin = (int)pcache1.grp.nMinPage;
  46981. *pnRecyclable = nRecyclable;
  46982. }
  46983. #endif
  46984. /************** End of pcache1.c *********************************************/
  46985. /************** Begin file rowset.c ******************************************/
  46986. /*
  46987. ** 2008 December 3
  46988. **
  46989. ** The author disclaims copyright to this source code. In place of
  46990. ** a legal notice, here is a blessing:
  46991. **
  46992. ** May you do good and not evil.
  46993. ** May you find forgiveness for yourself and forgive others.
  46994. ** May you share freely, never taking more than you give.
  46995. **
  46996. *************************************************************************
  46997. **
  46998. ** This module implements an object we call a "RowSet".
  46999. **
  47000. ** The RowSet object is a collection of rowids. Rowids
  47001. ** are inserted into the RowSet in an arbitrary order. Inserts
  47002. ** can be intermixed with tests to see if a given rowid has been
  47003. ** previously inserted into the RowSet.
  47004. **
  47005. ** After all inserts are finished, it is possible to extract the
  47006. ** elements of the RowSet in sorted order. Once this extraction
  47007. ** process has started, no new elements may be inserted.
  47008. **
  47009. ** Hence, the primitive operations for a RowSet are:
  47010. **
  47011. ** CREATE
  47012. ** INSERT
  47013. ** TEST
  47014. ** SMALLEST
  47015. ** DESTROY
  47016. **
  47017. ** The CREATE and DESTROY primitives are the constructor and destructor,
  47018. ** obviously. The INSERT primitive adds a new element to the RowSet.
  47019. ** TEST checks to see if an element is already in the RowSet. SMALLEST
  47020. ** extracts the least value from the RowSet.
  47021. **
  47022. ** The INSERT primitive might allocate additional memory. Memory is
  47023. ** allocated in chunks so most INSERTs do no allocation. There is an
  47024. ** upper bound on the size of allocated memory. No memory is freed
  47025. ** until DESTROY.
  47026. **
  47027. ** The TEST primitive includes a "batch" number. The TEST primitive
  47028. ** will only see elements that were inserted before the last change
  47029. ** in the batch number. In other words, if an INSERT occurs between
  47030. ** two TESTs where the TESTs have the same batch nubmer, then the
  47031. ** value added by the INSERT will not be visible to the second TEST.
  47032. ** The initial batch number is zero, so if the very first TEST contains
  47033. ** a non-zero batch number, it will see all prior INSERTs.
  47034. **
  47035. ** No INSERTs may occurs after a SMALLEST. An assertion will fail if
  47036. ** that is attempted.
  47037. **
  47038. ** The cost of an INSERT is roughly constant. (Sometimes new memory
  47039. ** has to be allocated on an INSERT.) The cost of a TEST with a new
  47040. ** batch number is O(NlogN) where N is the number of elements in the RowSet.
  47041. ** The cost of a TEST using the same batch number is O(logN). The cost
  47042. ** of the first SMALLEST is O(NlogN). Second and subsequent SMALLEST
  47043. ** primitives are constant time. The cost of DESTROY is O(N).
  47044. **
  47045. ** TEST and SMALLEST may not be used by the same RowSet. This used to
  47046. ** be possible, but the feature was not used, so it was removed in order
  47047. ** to simplify the code.
  47048. */
  47049. /* #include "sqliteInt.h" */
  47050. /*
  47051. ** Target size for allocation chunks.
  47052. */
  47053. #define ROWSET_ALLOCATION_SIZE 1024
  47054. /*
  47055. ** The number of rowset entries per allocation chunk.
  47056. */
  47057. #define ROWSET_ENTRY_PER_CHUNK \
  47058. ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
  47059. /*
  47060. ** Each entry in a RowSet is an instance of the following object.
  47061. **
  47062. ** This same object is reused to store a linked list of trees of RowSetEntry
  47063. ** objects. In that alternative use, pRight points to the next entry
  47064. ** in the list, pLeft points to the tree, and v is unused. The
  47065. ** RowSet.pForest value points to the head of this forest list.
  47066. */
  47067. struct RowSetEntry {
  47068. i64 v; /* ROWID value for this entry */
  47069. struct RowSetEntry *pRight; /* Right subtree (larger entries) or list */
  47070. struct RowSetEntry *pLeft; /* Left subtree (smaller entries) */
  47071. };
  47072. /*
  47073. ** RowSetEntry objects are allocated in large chunks (instances of the
  47074. ** following structure) to reduce memory allocation overhead. The
  47075. ** chunks are kept on a linked list so that they can be deallocated
  47076. ** when the RowSet is destroyed.
  47077. */
  47078. struct RowSetChunk {
  47079. struct RowSetChunk *pNextChunk; /* Next chunk on list of them all */
  47080. struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
  47081. };
  47082. /*
  47083. ** A RowSet in an instance of the following structure.
  47084. **
  47085. ** A typedef of this structure if found in sqliteInt.h.
  47086. */
  47087. struct RowSet {
  47088. struct RowSetChunk *pChunk; /* List of all chunk allocations */
  47089. sqlite3 *db; /* The database connection */
  47090. struct RowSetEntry *pEntry; /* List of entries using pRight */
  47091. struct RowSetEntry *pLast; /* Last entry on the pEntry list */
  47092. struct RowSetEntry *pFresh; /* Source of new entry objects */
  47093. struct RowSetEntry *pForest; /* List of binary trees of entries */
  47094. u16 nFresh; /* Number of objects on pFresh */
  47095. u16 rsFlags; /* Various flags */
  47096. int iBatch; /* Current insert batch */
  47097. };
  47098. /*
  47099. ** Allowed values for RowSet.rsFlags
  47100. */
  47101. #define ROWSET_SORTED 0x01 /* True if RowSet.pEntry is sorted */
  47102. #define ROWSET_NEXT 0x02 /* True if sqlite3RowSetNext() has been called */
  47103. /*
  47104. ** Allocate a RowSet object. Return NULL if a memory allocation
  47105. ** error occurs.
  47106. */
  47107. SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db){
  47108. RowSet *p = sqlite3DbMallocRawNN(db, sizeof(*p));
  47109. if( p ){
  47110. int N = sqlite3DbMallocSize(db, p);
  47111. p->pChunk = 0;
  47112. p->db = db;
  47113. p->pEntry = 0;
  47114. p->pLast = 0;
  47115. p->pForest = 0;
  47116. p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
  47117. p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
  47118. p->rsFlags = ROWSET_SORTED;
  47119. p->iBatch = 0;
  47120. }
  47121. return p;
  47122. }
  47123. /*
  47124. ** Deallocate all chunks from a RowSet. This frees all memory that
  47125. ** the RowSet has allocated over its lifetime. This routine is
  47126. ** the destructor for the RowSet.
  47127. */
  47128. SQLITE_PRIVATE void sqlite3RowSetClear(void *pArg){
  47129. RowSet *p = (RowSet*)pArg;
  47130. struct RowSetChunk *pChunk, *pNextChunk;
  47131. for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
  47132. pNextChunk = pChunk->pNextChunk;
  47133. sqlite3DbFree(p->db, pChunk);
  47134. }
  47135. p->pChunk = 0;
  47136. p->nFresh = 0;
  47137. p->pEntry = 0;
  47138. p->pLast = 0;
  47139. p->pForest = 0;
  47140. p->rsFlags = ROWSET_SORTED;
  47141. }
  47142. /*
  47143. ** Deallocate all chunks from a RowSet. This frees all memory that
  47144. ** the RowSet has allocated over its lifetime. This routine is
  47145. ** the destructor for the RowSet.
  47146. */
  47147. SQLITE_PRIVATE void sqlite3RowSetDelete(void *pArg){
  47148. sqlite3RowSetClear(pArg);
  47149. sqlite3DbFree(((RowSet*)pArg)->db, pArg);
  47150. }
  47151. /*
  47152. ** Allocate a new RowSetEntry object that is associated with the
  47153. ** given RowSet. Return a pointer to the new and completely uninitialized
  47154. ** objected.
  47155. **
  47156. ** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
  47157. ** routine returns NULL.
  47158. */
  47159. static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
  47160. assert( p!=0 );
  47161. if( p->nFresh==0 ){ /*OPTIMIZATION-IF-FALSE*/
  47162. /* We could allocate a fresh RowSetEntry each time one is needed, but it
  47163. ** is more efficient to pull a preallocated entry from the pool */
  47164. struct RowSetChunk *pNew;
  47165. pNew = sqlite3DbMallocRawNN(p->db, sizeof(*pNew));
  47166. if( pNew==0 ){
  47167. return 0;
  47168. }
  47169. pNew->pNextChunk = p->pChunk;
  47170. p->pChunk = pNew;
  47171. p->pFresh = pNew->aEntry;
  47172. p->nFresh = ROWSET_ENTRY_PER_CHUNK;
  47173. }
  47174. p->nFresh--;
  47175. return p->pFresh++;
  47176. }
  47177. /*
  47178. ** Insert a new value into a RowSet.
  47179. **
  47180. ** The mallocFailed flag of the database connection is set if a
  47181. ** memory allocation fails.
  47182. */
  47183. SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
  47184. struct RowSetEntry *pEntry; /* The new entry */
  47185. struct RowSetEntry *pLast; /* The last prior entry */
  47186. /* This routine is never called after sqlite3RowSetNext() */
  47187. assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
  47188. pEntry = rowSetEntryAlloc(p);
  47189. if( pEntry==0 ) return;
  47190. pEntry->v = rowid;
  47191. pEntry->pRight = 0;
  47192. pLast = p->pLast;
  47193. if( pLast ){
  47194. if( rowid<=pLast->v ){ /*OPTIMIZATION-IF-FALSE*/
  47195. /* Avoid unnecessary sorts by preserving the ROWSET_SORTED flags
  47196. ** where possible */
  47197. p->rsFlags &= ~ROWSET_SORTED;
  47198. }
  47199. pLast->pRight = pEntry;
  47200. }else{
  47201. p->pEntry = pEntry;
  47202. }
  47203. p->pLast = pEntry;
  47204. }
  47205. /*
  47206. ** Merge two lists of RowSetEntry objects. Remove duplicates.
  47207. **
  47208. ** The input lists are connected via pRight pointers and are
  47209. ** assumed to each already be in sorted order.
  47210. */
  47211. static struct RowSetEntry *rowSetEntryMerge(
  47212. struct RowSetEntry *pA, /* First sorted list to be merged */
  47213. struct RowSetEntry *pB /* Second sorted list to be merged */
  47214. ){
  47215. struct RowSetEntry head;
  47216. struct RowSetEntry *pTail;
  47217. pTail = &head;
  47218. assert( pA!=0 && pB!=0 );
  47219. for(;;){
  47220. assert( pA->pRight==0 || pA->v<=pA->pRight->v );
  47221. assert( pB->pRight==0 || pB->v<=pB->pRight->v );
  47222. if( pA->v<=pB->v ){
  47223. if( pA->v<pB->v ) pTail = pTail->pRight = pA;
  47224. pA = pA->pRight;
  47225. if( pA==0 ){
  47226. pTail->pRight = pB;
  47227. break;
  47228. }
  47229. }else{
  47230. pTail = pTail->pRight = pB;
  47231. pB = pB->pRight;
  47232. if( pB==0 ){
  47233. pTail->pRight = pA;
  47234. break;
  47235. }
  47236. }
  47237. }
  47238. return head.pRight;
  47239. }
  47240. /*
  47241. ** Sort all elements on the list of RowSetEntry objects into order of
  47242. ** increasing v.
  47243. */
  47244. static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){
  47245. unsigned int i;
  47246. struct RowSetEntry *pNext, *aBucket[40];
  47247. memset(aBucket, 0, sizeof(aBucket));
  47248. while( pIn ){
  47249. pNext = pIn->pRight;
  47250. pIn->pRight = 0;
  47251. for(i=0; aBucket[i]; i++){
  47252. pIn = rowSetEntryMerge(aBucket[i], pIn);
  47253. aBucket[i] = 0;
  47254. }
  47255. aBucket[i] = pIn;
  47256. pIn = pNext;
  47257. }
  47258. pIn = aBucket[0];
  47259. for(i=1; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
  47260. if( aBucket[i]==0 ) continue;
  47261. pIn = pIn ? rowSetEntryMerge(pIn, aBucket[i]) : aBucket[i];
  47262. }
  47263. return pIn;
  47264. }
  47265. /*
  47266. ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
  47267. ** Convert this tree into a linked list connected by the pRight pointers
  47268. ** and return pointers to the first and last elements of the new list.
  47269. */
  47270. static void rowSetTreeToList(
  47271. struct RowSetEntry *pIn, /* Root of the input tree */
  47272. struct RowSetEntry **ppFirst, /* Write head of the output list here */
  47273. struct RowSetEntry **ppLast /* Write tail of the output list here */
  47274. ){
  47275. assert( pIn!=0 );
  47276. if( pIn->pLeft ){
  47277. struct RowSetEntry *p;
  47278. rowSetTreeToList(pIn->pLeft, ppFirst, &p);
  47279. p->pRight = pIn;
  47280. }else{
  47281. *ppFirst = pIn;
  47282. }
  47283. if( pIn->pRight ){
  47284. rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
  47285. }else{
  47286. *ppLast = pIn;
  47287. }
  47288. assert( (*ppLast)->pRight==0 );
  47289. }
  47290. /*
  47291. ** Convert a sorted list of elements (connected by pRight) into a binary
  47292. ** tree with depth of iDepth. A depth of 1 means the tree contains a single
  47293. ** node taken from the head of *ppList. A depth of 2 means a tree with
  47294. ** three nodes. And so forth.
  47295. **
  47296. ** Use as many entries from the input list as required and update the
  47297. ** *ppList to point to the unused elements of the list. If the input
  47298. ** list contains too few elements, then construct an incomplete tree
  47299. ** and leave *ppList set to NULL.
  47300. **
  47301. ** Return a pointer to the root of the constructed binary tree.
  47302. */
  47303. static struct RowSetEntry *rowSetNDeepTree(
  47304. struct RowSetEntry **ppList,
  47305. int iDepth
  47306. ){
  47307. struct RowSetEntry *p; /* Root of the new tree */
  47308. struct RowSetEntry *pLeft; /* Left subtree */
  47309. if( *ppList==0 ){ /*OPTIMIZATION-IF-TRUE*/
  47310. /* Prevent unnecessary deep recursion when we run out of entries */
  47311. return 0;
  47312. }
  47313. if( iDepth>1 ){ /*OPTIMIZATION-IF-TRUE*/
  47314. /* This branch causes a *balanced* tree to be generated. A valid tree
  47315. ** is still generated without this branch, but the tree is wildly
  47316. ** unbalanced and inefficient. */
  47317. pLeft = rowSetNDeepTree(ppList, iDepth-1);
  47318. p = *ppList;
  47319. if( p==0 ){ /*OPTIMIZATION-IF-FALSE*/
  47320. /* It is safe to always return here, but the resulting tree
  47321. ** would be unbalanced */
  47322. return pLeft;
  47323. }
  47324. p->pLeft = pLeft;
  47325. *ppList = p->pRight;
  47326. p->pRight = rowSetNDeepTree(ppList, iDepth-1);
  47327. }else{
  47328. p = *ppList;
  47329. *ppList = p->pRight;
  47330. p->pLeft = p->pRight = 0;
  47331. }
  47332. return p;
  47333. }
  47334. /*
  47335. ** Convert a sorted list of elements into a binary tree. Make the tree
  47336. ** as deep as it needs to be in order to contain the entire list.
  47337. */
  47338. static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
  47339. int iDepth; /* Depth of the tree so far */
  47340. struct RowSetEntry *p; /* Current tree root */
  47341. struct RowSetEntry *pLeft; /* Left subtree */
  47342. assert( pList!=0 );
  47343. p = pList;
  47344. pList = p->pRight;
  47345. p->pLeft = p->pRight = 0;
  47346. for(iDepth=1; pList; iDepth++){
  47347. pLeft = p;
  47348. p = pList;
  47349. pList = p->pRight;
  47350. p->pLeft = pLeft;
  47351. p->pRight = rowSetNDeepTree(&pList, iDepth);
  47352. }
  47353. return p;
  47354. }
  47355. /*
  47356. ** Extract the smallest element from the RowSet.
  47357. ** Write the element into *pRowid. Return 1 on success. Return
  47358. ** 0 if the RowSet is already empty.
  47359. **
  47360. ** After this routine has been called, the sqlite3RowSetInsert()
  47361. ** routine may not be called again.
  47362. **
  47363. ** This routine may not be called after sqlite3RowSetTest() has
  47364. ** been used. Older versions of RowSet allowed that, but as the
  47365. ** capability was not used by the code generator, it was removed
  47366. ** for code economy.
  47367. */
  47368. SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
  47369. assert( p!=0 );
  47370. assert( p->pForest==0 ); /* Cannot be used with sqlite3RowSetText() */
  47371. /* Merge the forest into a single sorted list on first call */
  47372. if( (p->rsFlags & ROWSET_NEXT)==0 ){ /*OPTIMIZATION-IF-FALSE*/
  47373. if( (p->rsFlags & ROWSET_SORTED)==0 ){ /*OPTIMIZATION-IF-FALSE*/
  47374. p->pEntry = rowSetEntrySort(p->pEntry);
  47375. }
  47376. p->rsFlags |= ROWSET_SORTED|ROWSET_NEXT;
  47377. }
  47378. /* Return the next entry on the list */
  47379. if( p->pEntry ){
  47380. *pRowid = p->pEntry->v;
  47381. p->pEntry = p->pEntry->pRight;
  47382. if( p->pEntry==0 ){ /*OPTIMIZATION-IF-TRUE*/
  47383. /* Free memory immediately, rather than waiting on sqlite3_finalize() */
  47384. sqlite3RowSetClear(p);
  47385. }
  47386. return 1;
  47387. }else{
  47388. return 0;
  47389. }
  47390. }
  47391. /*
  47392. ** Check to see if element iRowid was inserted into the rowset as
  47393. ** part of any insert batch prior to iBatch. Return 1 or 0.
  47394. **
  47395. ** If this is the first test of a new batch and if there exist entries
  47396. ** on pRowSet->pEntry, then sort those entries into the forest at
  47397. ** pRowSet->pForest so that they can be tested.
  47398. */
  47399. SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, int iBatch, sqlite3_int64 iRowid){
  47400. struct RowSetEntry *p, *pTree;
  47401. /* This routine is never called after sqlite3RowSetNext() */
  47402. assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
  47403. /* Sort entries into the forest on the first test of a new batch.
  47404. ** To save unnecessary work, only do this when the batch number changes.
  47405. */
  47406. if( iBatch!=pRowSet->iBatch ){ /*OPTIMIZATION-IF-FALSE*/
  47407. p = pRowSet->pEntry;
  47408. if( p ){
  47409. struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
  47410. if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){ /*OPTIMIZATION-IF-FALSE*/
  47411. /* Only sort the current set of entiries if they need it */
  47412. p = rowSetEntrySort(p);
  47413. }
  47414. for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
  47415. ppPrevTree = &pTree->pRight;
  47416. if( pTree->pLeft==0 ){
  47417. pTree->pLeft = rowSetListToTree(p);
  47418. break;
  47419. }else{
  47420. struct RowSetEntry *pAux, *pTail;
  47421. rowSetTreeToList(pTree->pLeft, &pAux, &pTail);
  47422. pTree->pLeft = 0;
  47423. p = rowSetEntryMerge(pAux, p);
  47424. }
  47425. }
  47426. if( pTree==0 ){
  47427. *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet);
  47428. if( pTree ){
  47429. pTree->v = 0;
  47430. pTree->pRight = 0;
  47431. pTree->pLeft = rowSetListToTree(p);
  47432. }
  47433. }
  47434. pRowSet->pEntry = 0;
  47435. pRowSet->pLast = 0;
  47436. pRowSet->rsFlags |= ROWSET_SORTED;
  47437. }
  47438. pRowSet->iBatch = iBatch;
  47439. }
  47440. /* Test to see if the iRowid value appears anywhere in the forest.
  47441. ** Return 1 if it does and 0 if not.
  47442. */
  47443. for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
  47444. p = pTree->pLeft;
  47445. while( p ){
  47446. if( p->v<iRowid ){
  47447. p = p->pRight;
  47448. }else if( p->v>iRowid ){
  47449. p = p->pLeft;
  47450. }else{
  47451. return 1;
  47452. }
  47453. }
  47454. }
  47455. return 0;
  47456. }
  47457. /************** End of rowset.c **********************************************/
  47458. /************** Begin file pager.c *******************************************/
  47459. /*
  47460. ** 2001 September 15
  47461. **
  47462. ** The author disclaims copyright to this source code. In place of
  47463. ** a legal notice, here is a blessing:
  47464. **
  47465. ** May you do good and not evil.
  47466. ** May you find forgiveness for yourself and forgive others.
  47467. ** May you share freely, never taking more than you give.
  47468. **
  47469. *************************************************************************
  47470. ** This is the implementation of the page cache subsystem or "pager".
  47471. **
  47472. ** The pager is used to access a database disk file. It implements
  47473. ** atomic commit and rollback through the use of a journal file that
  47474. ** is separate from the database file. The pager also implements file
  47475. ** locking to prevent two processes from writing the same database
  47476. ** file simultaneously, or one process from reading the database while
  47477. ** another is writing.
  47478. */
  47479. #ifndef SQLITE_OMIT_DISKIO
  47480. /* #include "sqliteInt.h" */
  47481. /************** Include wal.h in the middle of pager.c ***********************/
  47482. /************** Begin file wal.h *********************************************/
  47483. /*
  47484. ** 2010 February 1
  47485. **
  47486. ** The author disclaims copyright to this source code. In place of
  47487. ** a legal notice, here is a blessing:
  47488. **
  47489. ** May you do good and not evil.
  47490. ** May you find forgiveness for yourself and forgive others.
  47491. ** May you share freely, never taking more than you give.
  47492. **
  47493. *************************************************************************
  47494. ** This header file defines the interface to the write-ahead logging
  47495. ** system. Refer to the comments below and the header comment attached to
  47496. ** the implementation of each function in log.c for further details.
  47497. */
  47498. #ifndef SQLITE_WAL_H
  47499. #define SQLITE_WAL_H
  47500. /* #include "sqliteInt.h" */
  47501. /* Macros for extracting appropriate sync flags for either transaction
  47502. ** commits (WAL_SYNC_FLAGS(X)) or for checkpoint ops (CKPT_SYNC_FLAGS(X)):
  47503. */
  47504. #define WAL_SYNC_FLAGS(X) ((X)&0x03)
  47505. #define CKPT_SYNC_FLAGS(X) (((X)>>2)&0x03)
  47506. #ifdef SQLITE_OMIT_WAL
  47507. # define sqlite3WalOpen(x,y,z) 0
  47508. # define sqlite3WalLimit(x,y)
  47509. # define sqlite3WalClose(v,w,x,y,z) 0
  47510. # define sqlite3WalBeginReadTransaction(y,z) 0
  47511. # define sqlite3WalEndReadTransaction(z)
  47512. # define sqlite3WalDbsize(y) 0
  47513. # define sqlite3WalBeginWriteTransaction(y) 0
  47514. # define sqlite3WalEndWriteTransaction(x) 0
  47515. # define sqlite3WalUndo(x,y,z) 0
  47516. # define sqlite3WalSavepoint(y,z)
  47517. # define sqlite3WalSavepointUndo(y,z) 0
  47518. # define sqlite3WalFrames(u,v,w,x,y,z) 0
  47519. # define sqlite3WalCheckpoint(q,r,s,t,u,v,w,x,y,z) 0
  47520. # define sqlite3WalCallback(z) 0
  47521. # define sqlite3WalExclusiveMode(y,z) 0
  47522. # define sqlite3WalHeapMemory(z) 0
  47523. # define sqlite3WalFramesize(z) 0
  47524. # define sqlite3WalFindFrame(x,y,z) 0
  47525. # define sqlite3WalFile(x) 0
  47526. #else
  47527. #define WAL_SAVEPOINT_NDATA 4
  47528. /* Connection to a write-ahead log (WAL) file.
  47529. ** There is one object of this type for each pager.
  47530. */
  47531. typedef struct Wal Wal;
  47532. /* Open and close a connection to a write-ahead log. */
  47533. SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
  47534. SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, sqlite3*, int sync_flags, int, u8 *);
  47535. /* Set the limiting size of a WAL file. */
  47536. SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
  47537. /* Used by readers to open (lock) and close (unlock) a snapshot. A
  47538. ** snapshot is like a read-transaction. It is the state of the database
  47539. ** at an instant in time. sqlite3WalOpenSnapshot gets a read lock and
  47540. ** preserves the current state even if the other threads or processes
  47541. ** write to or checkpoint the WAL. sqlite3WalCloseSnapshot() closes the
  47542. ** transaction and releases the lock.
  47543. */
  47544. SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
  47545. SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
  47546. /* Read a page from the write-ahead log, if it is present. */
  47547. SQLITE_PRIVATE int sqlite3WalFindFrame(Wal *, Pgno, u32 *);
  47548. SQLITE_PRIVATE int sqlite3WalReadFrame(Wal *, u32, int, u8 *);
  47549. /* If the WAL is not empty, return the size of the database. */
  47550. SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
  47551. /* Obtain or release the WRITER lock. */
  47552. SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
  47553. SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
  47554. /* Undo any frames written (but not committed) to the log */
  47555. SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
  47556. /* Return an integer that records the current (uncommitted) write
  47557. ** position in the WAL */
  47558. SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
  47559. /* Move the write position of the WAL back to iFrame. Called in
  47560. ** response to a ROLLBACK TO command. */
  47561. SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
  47562. /* Write a frame or frames to the log. */
  47563. SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
  47564. /* Copy pages from the log to the database file */
  47565. SQLITE_PRIVATE int sqlite3WalCheckpoint(
  47566. Wal *pWal, /* Write-ahead log connection */
  47567. sqlite3 *db, /* Check this handle's interrupt flag */
  47568. int eMode, /* One of PASSIVE, FULL and RESTART */
  47569. int (*xBusy)(void*), /* Function to call when busy */
  47570. void *pBusyArg, /* Context argument for xBusyHandler */
  47571. int sync_flags, /* Flags to sync db file with (or 0) */
  47572. int nBuf, /* Size of buffer nBuf */
  47573. u8 *zBuf, /* Temporary buffer to use */
  47574. int *pnLog, /* OUT: Number of frames in WAL */
  47575. int *pnCkpt /* OUT: Number of backfilled frames in WAL */
  47576. );
  47577. /* Return the value to pass to a sqlite3_wal_hook callback, the
  47578. ** number of frames in the WAL at the point of the last commit since
  47579. ** sqlite3WalCallback() was called. If no commits have occurred since
  47580. ** the last call, then return 0.
  47581. */
  47582. SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
  47583. /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
  47584. ** by the pager layer on the database file.
  47585. */
  47586. SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
  47587. /* Return true if the argument is non-NULL and the WAL module is using
  47588. ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
  47589. ** WAL module is using shared-memory, return false.
  47590. */
  47591. SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
  47592. #ifdef SQLITE_ENABLE_SNAPSHOT
  47593. SQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot);
  47594. SQLITE_PRIVATE void sqlite3WalSnapshotOpen(Wal *pWal, sqlite3_snapshot *pSnapshot);
  47595. SQLITE_PRIVATE int sqlite3WalSnapshotRecover(Wal *pWal);
  47596. SQLITE_PRIVATE int sqlite3WalSnapshotCheck(Wal *pWal, sqlite3_snapshot *pSnapshot);
  47597. SQLITE_PRIVATE void sqlite3WalSnapshotUnlock(Wal *pWal);
  47598. #endif
  47599. #ifdef SQLITE_ENABLE_ZIPVFS
  47600. /* If the WAL file is not empty, return the number of bytes of content
  47601. ** stored in each frame (i.e. the db page-size when the WAL was created).
  47602. */
  47603. SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
  47604. #endif
  47605. /* Return the sqlite3_file object for the WAL file */
  47606. SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal);
  47607. #endif /* ifndef SQLITE_OMIT_WAL */
  47608. #endif /* SQLITE_WAL_H */
  47609. /************** End of wal.h *************************************************/
  47610. /************** Continuing where we left off in pager.c **********************/
  47611. /******************* NOTES ON THE DESIGN OF THE PAGER ************************
  47612. **
  47613. ** This comment block describes invariants that hold when using a rollback
  47614. ** journal. These invariants do not apply for journal_mode=WAL,
  47615. ** journal_mode=MEMORY, or journal_mode=OFF.
  47616. **
  47617. ** Within this comment block, a page is deemed to have been synced
  47618. ** automatically as soon as it is written when PRAGMA synchronous=OFF.
  47619. ** Otherwise, the page is not synced until the xSync method of the VFS
  47620. ** is called successfully on the file containing the page.
  47621. **
  47622. ** Definition: A page of the database file is said to be "overwriteable" if
  47623. ** one or more of the following are true about the page:
  47624. **
  47625. ** (a) The original content of the page as it was at the beginning of
  47626. ** the transaction has been written into the rollback journal and
  47627. ** synced.
  47628. **
  47629. ** (b) The page was a freelist leaf page at the start of the transaction.
  47630. **
  47631. ** (c) The page number is greater than the largest page that existed in
  47632. ** the database file at the start of the transaction.
  47633. **
  47634. ** (1) A page of the database file is never overwritten unless one of the
  47635. ** following are true:
  47636. **
  47637. ** (a) The page and all other pages on the same sector are overwriteable.
  47638. **
  47639. ** (b) The atomic page write optimization is enabled, and the entire
  47640. ** transaction other than the update of the transaction sequence
  47641. ** number consists of a single page change.
  47642. **
  47643. ** (2) The content of a page written into the rollback journal exactly matches
  47644. ** both the content in the database when the rollback journal was written
  47645. ** and the content in the database at the beginning of the current
  47646. ** transaction.
  47647. **
  47648. ** (3) Writes to the database file are an integer multiple of the page size
  47649. ** in length and are aligned on a page boundary.
  47650. **
  47651. ** (4) Reads from the database file are either aligned on a page boundary and
  47652. ** an integer multiple of the page size in length or are taken from the
  47653. ** first 100 bytes of the database file.
  47654. **
  47655. ** (5) All writes to the database file are synced prior to the rollback journal
  47656. ** being deleted, truncated, or zeroed.
  47657. **
  47658. ** (6) If a master journal file is used, then all writes to the database file
  47659. ** are synced prior to the master journal being deleted.
  47660. **
  47661. ** Definition: Two databases (or the same database at two points it time)
  47662. ** are said to be "logically equivalent" if they give the same answer to
  47663. ** all queries. Note in particular the content of freelist leaf
  47664. ** pages can be changed arbitrarily without affecting the logical equivalence
  47665. ** of the database.
  47666. **
  47667. ** (7) At any time, if any subset, including the empty set and the total set,
  47668. ** of the unsynced changes to a rollback journal are removed and the
  47669. ** journal is rolled back, the resulting database file will be logically
  47670. ** equivalent to the database file at the beginning of the transaction.
  47671. **
  47672. ** (8) When a transaction is rolled back, the xTruncate method of the VFS
  47673. ** is called to restore the database file to the same size it was at
  47674. ** the beginning of the transaction. (In some VFSes, the xTruncate
  47675. ** method is a no-op, but that does not change the fact the SQLite will
  47676. ** invoke it.)
  47677. **
  47678. ** (9) Whenever the database file is modified, at least one bit in the range
  47679. ** of bytes from 24 through 39 inclusive will be changed prior to releasing
  47680. ** the EXCLUSIVE lock, thus signaling other connections on the same
  47681. ** database to flush their caches.
  47682. **
  47683. ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
  47684. ** than one billion transactions.
  47685. **
  47686. ** (11) A database file is well-formed at the beginning and at the conclusion
  47687. ** of every transaction.
  47688. **
  47689. ** (12) An EXCLUSIVE lock is held on the database file when writing to
  47690. ** the database file.
  47691. **
  47692. ** (13) A SHARED lock is held on the database file while reading any
  47693. ** content out of the database file.
  47694. **
  47695. ******************************************************************************/
  47696. /*
  47697. ** Macros for troubleshooting. Normally turned off
  47698. */
  47699. #if 0
  47700. int sqlite3PagerTrace=1; /* True to enable tracing */
  47701. #define sqlite3DebugPrintf printf
  47702. #define PAGERTRACE(X) if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
  47703. #else
  47704. #define PAGERTRACE(X)
  47705. #endif
  47706. /*
  47707. ** The following two macros are used within the PAGERTRACE() macros above
  47708. ** to print out file-descriptors.
  47709. **
  47710. ** PAGERID() takes a pointer to a Pager struct as its argument. The
  47711. ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
  47712. ** struct as its argument.
  47713. */
  47714. #define PAGERID(p) (SQLITE_PTR_TO_INT(p->fd))
  47715. #define FILEHANDLEID(fd) (SQLITE_PTR_TO_INT(fd))
  47716. /*
  47717. ** The Pager.eState variable stores the current 'state' of a pager. A
  47718. ** pager may be in any one of the seven states shown in the following
  47719. ** state diagram.
  47720. **
  47721. ** OPEN <------+------+
  47722. ** | | |
  47723. ** V | |
  47724. ** +---------> READER-------+ |
  47725. ** | | |
  47726. ** | V |
  47727. ** |<-------WRITER_LOCKED------> ERROR
  47728. ** | | ^
  47729. ** | V |
  47730. ** |<------WRITER_CACHEMOD-------->|
  47731. ** | | |
  47732. ** | V |
  47733. ** |<-------WRITER_DBMOD---------->|
  47734. ** | | |
  47735. ** | V |
  47736. ** +<------WRITER_FINISHED-------->+
  47737. **
  47738. **
  47739. ** List of state transitions and the C [function] that performs each:
  47740. **
  47741. ** OPEN -> READER [sqlite3PagerSharedLock]
  47742. ** READER -> OPEN [pager_unlock]
  47743. **
  47744. ** READER -> WRITER_LOCKED [sqlite3PagerBegin]
  47745. ** WRITER_LOCKED -> WRITER_CACHEMOD [pager_open_journal]
  47746. ** WRITER_CACHEMOD -> WRITER_DBMOD [syncJournal]
  47747. ** WRITER_DBMOD -> WRITER_FINISHED [sqlite3PagerCommitPhaseOne]
  47748. ** WRITER_*** -> READER [pager_end_transaction]
  47749. **
  47750. ** WRITER_*** -> ERROR [pager_error]
  47751. ** ERROR -> OPEN [pager_unlock]
  47752. **
  47753. **
  47754. ** OPEN:
  47755. **
  47756. ** The pager starts up in this state. Nothing is guaranteed in this
  47757. ** state - the file may or may not be locked and the database size is
  47758. ** unknown. The database may not be read or written.
  47759. **
  47760. ** * No read or write transaction is active.
  47761. ** * Any lock, or no lock at all, may be held on the database file.
  47762. ** * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
  47763. **
  47764. ** READER:
  47765. **
  47766. ** In this state all the requirements for reading the database in
  47767. ** rollback (non-WAL) mode are met. Unless the pager is (or recently
  47768. ** was) in exclusive-locking mode, a user-level read transaction is
  47769. ** open. The database size is known in this state.
  47770. **
  47771. ** A connection running with locking_mode=normal enters this state when
  47772. ** it opens a read-transaction on the database and returns to state
  47773. ** OPEN after the read-transaction is completed. However a connection
  47774. ** running in locking_mode=exclusive (including temp databases) remains in
  47775. ** this state even after the read-transaction is closed. The only way
  47776. ** a locking_mode=exclusive connection can transition from READER to OPEN
  47777. ** is via the ERROR state (see below).
  47778. **
  47779. ** * A read transaction may be active (but a write-transaction cannot).
  47780. ** * A SHARED or greater lock is held on the database file.
  47781. ** * The dbSize variable may be trusted (even if a user-level read
  47782. ** transaction is not active). The dbOrigSize and dbFileSize variables
  47783. ** may not be trusted at this point.
  47784. ** * If the database is a WAL database, then the WAL connection is open.
  47785. ** * Even if a read-transaction is not open, it is guaranteed that
  47786. ** there is no hot-journal in the file-system.
  47787. **
  47788. ** WRITER_LOCKED:
  47789. **
  47790. ** The pager moves to this state from READER when a write-transaction
  47791. ** is first opened on the database. In WRITER_LOCKED state, all locks
  47792. ** required to start a write-transaction are held, but no actual
  47793. ** modifications to the cache or database have taken place.
  47794. **
  47795. ** In rollback mode, a RESERVED or (if the transaction was opened with
  47796. ** BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
  47797. ** moving to this state, but the journal file is not written to or opened
  47798. ** to in this state. If the transaction is committed or rolled back while
  47799. ** in WRITER_LOCKED state, all that is required is to unlock the database
  47800. ** file.
  47801. **
  47802. ** IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
  47803. ** If the connection is running with locking_mode=exclusive, an attempt
  47804. ** is made to obtain an EXCLUSIVE lock on the database file.
  47805. **
  47806. ** * A write transaction is active.
  47807. ** * If the connection is open in rollback-mode, a RESERVED or greater
  47808. ** lock is held on the database file.
  47809. ** * If the connection is open in WAL-mode, a WAL write transaction
  47810. ** is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
  47811. ** called).
  47812. ** * The dbSize, dbOrigSize and dbFileSize variables are all valid.
  47813. ** * The contents of the pager cache have not been modified.
  47814. ** * The journal file may or may not be open.
  47815. ** * Nothing (not even the first header) has been written to the journal.
  47816. **
  47817. ** WRITER_CACHEMOD:
  47818. **
  47819. ** A pager moves from WRITER_LOCKED state to this state when a page is
  47820. ** first modified by the upper layer. In rollback mode the journal file
  47821. ** is opened (if it is not already open) and a header written to the
  47822. ** start of it. The database file on disk has not been modified.
  47823. **
  47824. ** * A write transaction is active.
  47825. ** * A RESERVED or greater lock is held on the database file.
  47826. ** * The journal file is open and the first header has been written
  47827. ** to it, but the header has not been synced to disk.
  47828. ** * The contents of the page cache have been modified.
  47829. **
  47830. ** WRITER_DBMOD:
  47831. **
  47832. ** The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
  47833. ** when it modifies the contents of the database file. WAL connections
  47834. ** never enter this state (since they do not modify the database file,
  47835. ** just the log file).
  47836. **
  47837. ** * A write transaction is active.
  47838. ** * An EXCLUSIVE or greater lock is held on the database file.
  47839. ** * The journal file is open and the first header has been written
  47840. ** and synced to disk.
  47841. ** * The contents of the page cache have been modified (and possibly
  47842. ** written to disk).
  47843. **
  47844. ** WRITER_FINISHED:
  47845. **
  47846. ** It is not possible for a WAL connection to enter this state.
  47847. **
  47848. ** A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
  47849. ** state after the entire transaction has been successfully written into the
  47850. ** database file. In this state the transaction may be committed simply
  47851. ** by finalizing the journal file. Once in WRITER_FINISHED state, it is
  47852. ** not possible to modify the database further. At this point, the upper
  47853. ** layer must either commit or rollback the transaction.
  47854. **
  47855. ** * A write transaction is active.
  47856. ** * An EXCLUSIVE or greater lock is held on the database file.
  47857. ** * All writing and syncing of journal and database data has finished.
  47858. ** If no error occurred, all that remains is to finalize the journal to
  47859. ** commit the transaction. If an error did occur, the caller will need
  47860. ** to rollback the transaction.
  47861. **
  47862. ** ERROR:
  47863. **
  47864. ** The ERROR state is entered when an IO or disk-full error (including
  47865. ** SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
  47866. ** difficult to be sure that the in-memory pager state (cache contents,
  47867. ** db size etc.) are consistent with the contents of the file-system.
  47868. **
  47869. ** Temporary pager files may enter the ERROR state, but in-memory pagers
  47870. ** cannot.
  47871. **
  47872. ** For example, if an IO error occurs while performing a rollback,
  47873. ** the contents of the page-cache may be left in an inconsistent state.
  47874. ** At this point it would be dangerous to change back to READER state
  47875. ** (as usually happens after a rollback). Any subsequent readers might
  47876. ** report database corruption (due to the inconsistent cache), and if
  47877. ** they upgrade to writers, they may inadvertently corrupt the database
  47878. ** file. To avoid this hazard, the pager switches into the ERROR state
  47879. ** instead of READER following such an error.
  47880. **
  47881. ** Once it has entered the ERROR state, any attempt to use the pager
  47882. ** to read or write data returns an error. Eventually, once all
  47883. ** outstanding transactions have been abandoned, the pager is able to
  47884. ** transition back to OPEN state, discarding the contents of the
  47885. ** page-cache and any other in-memory state at the same time. Everything
  47886. ** is reloaded from disk (and, if necessary, hot-journal rollback peformed)
  47887. ** when a read-transaction is next opened on the pager (transitioning
  47888. ** the pager into READER state). At that point the system has recovered
  47889. ** from the error.
  47890. **
  47891. ** Specifically, the pager jumps into the ERROR state if:
  47892. **
  47893. ** 1. An error occurs while attempting a rollback. This happens in
  47894. ** function sqlite3PagerRollback().
  47895. **
  47896. ** 2. An error occurs while attempting to finalize a journal file
  47897. ** following a commit in function sqlite3PagerCommitPhaseTwo().
  47898. **
  47899. ** 3. An error occurs while attempting to write to the journal or
  47900. ** database file in function pagerStress() in order to free up
  47901. ** memory.
  47902. **
  47903. ** In other cases, the error is returned to the b-tree layer. The b-tree
  47904. ** layer then attempts a rollback operation. If the error condition
  47905. ** persists, the pager enters the ERROR state via condition (1) above.
  47906. **
  47907. ** Condition (3) is necessary because it can be triggered by a read-only
  47908. ** statement executed within a transaction. In this case, if the error
  47909. ** code were simply returned to the user, the b-tree layer would not
  47910. ** automatically attempt a rollback, as it assumes that an error in a
  47911. ** read-only statement cannot leave the pager in an internally inconsistent
  47912. ** state.
  47913. **
  47914. ** * The Pager.errCode variable is set to something other than SQLITE_OK.
  47915. ** * There are one or more outstanding references to pages (after the
  47916. ** last reference is dropped the pager should move back to OPEN state).
  47917. ** * The pager is not an in-memory pager.
  47918. **
  47919. **
  47920. ** Notes:
  47921. **
  47922. ** * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
  47923. ** connection is open in WAL mode. A WAL connection is always in one
  47924. ** of the first four states.
  47925. **
  47926. ** * Normally, a connection open in exclusive mode is never in PAGER_OPEN
  47927. ** state. There are two exceptions: immediately after exclusive-mode has
  47928. ** been turned on (and before any read or write transactions are
  47929. ** executed), and when the pager is leaving the "error state".
  47930. **
  47931. ** * See also: assert_pager_state().
  47932. */
  47933. #define PAGER_OPEN 0
  47934. #define PAGER_READER 1
  47935. #define PAGER_WRITER_LOCKED 2
  47936. #define PAGER_WRITER_CACHEMOD 3
  47937. #define PAGER_WRITER_DBMOD 4
  47938. #define PAGER_WRITER_FINISHED 5
  47939. #define PAGER_ERROR 6
  47940. /*
  47941. ** The Pager.eLock variable is almost always set to one of the
  47942. ** following locking-states, according to the lock currently held on
  47943. ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
  47944. ** This variable is kept up to date as locks are taken and released by
  47945. ** the pagerLockDb() and pagerUnlockDb() wrappers.
  47946. **
  47947. ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
  47948. ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
  47949. ** the operation was successful. In these circumstances pagerLockDb() and
  47950. ** pagerUnlockDb() take a conservative approach - eLock is always updated
  47951. ** when unlocking the file, and only updated when locking the file if the
  47952. ** VFS call is successful. This way, the Pager.eLock variable may be set
  47953. ** to a less exclusive (lower) value than the lock that is actually held
  47954. ** at the system level, but it is never set to a more exclusive value.
  47955. **
  47956. ** This is usually safe. If an xUnlock fails or appears to fail, there may
  47957. ** be a few redundant xLock() calls or a lock may be held for longer than
  47958. ** required, but nothing really goes wrong.
  47959. **
  47960. ** The exception is when the database file is unlocked as the pager moves
  47961. ** from ERROR to OPEN state. At this point there may be a hot-journal file
  47962. ** in the file-system that needs to be rolled back (as part of an OPEN->SHARED
  47963. ** transition, by the same pager or any other). If the call to xUnlock()
  47964. ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
  47965. ** can confuse the call to xCheckReservedLock() call made later as part
  47966. ** of hot-journal detection.
  47967. **
  47968. ** xCheckReservedLock() is defined as returning true "if there is a RESERVED
  47969. ** lock held by this process or any others". So xCheckReservedLock may
  47970. ** return true because the caller itself is holding an EXCLUSIVE lock (but
  47971. ** doesn't know it because of a previous error in xUnlock). If this happens
  47972. ** a hot-journal may be mistaken for a journal being created by an active
  47973. ** transaction in another process, causing SQLite to read from the database
  47974. ** without rolling it back.
  47975. **
  47976. ** To work around this, if a call to xUnlock() fails when unlocking the
  47977. ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
  47978. ** is only changed back to a real locking state after a successful call
  47979. ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
  47980. ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
  47981. ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
  47982. ** lock on the database file before attempting to roll it back. See function
  47983. ** PagerSharedLock() for more detail.
  47984. **
  47985. ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
  47986. ** PAGER_OPEN state.
  47987. */
  47988. #define UNKNOWN_LOCK (EXCLUSIVE_LOCK+1)
  47989. /*
  47990. ** A macro used for invoking the codec if there is one
  47991. */
  47992. #ifdef SQLITE_HAS_CODEC
  47993. # define CODEC1(P,D,N,X,E) \
  47994. if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
  47995. # define CODEC2(P,D,N,X,E,O) \
  47996. if( P->xCodec==0 ){ O=(char*)D; }else \
  47997. if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
  47998. #else
  47999. # define CODEC1(P,D,N,X,E) /* NO-OP */
  48000. # define CODEC2(P,D,N,X,E,O) O=(char*)D
  48001. #endif
  48002. /*
  48003. ** The maximum allowed sector size. 64KiB. If the xSectorsize() method
  48004. ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
  48005. ** This could conceivably cause corruption following a power failure on
  48006. ** such a system. This is currently an undocumented limit.
  48007. */
  48008. #define MAX_SECTOR_SIZE 0x10000
  48009. /*
  48010. ** An instance of the following structure is allocated for each active
  48011. ** savepoint and statement transaction in the system. All such structures
  48012. ** are stored in the Pager.aSavepoint[] array, which is allocated and
  48013. ** resized using sqlite3Realloc().
  48014. **
  48015. ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
  48016. ** set to 0. If a journal-header is written into the main journal while
  48017. ** the savepoint is active, then iHdrOffset is set to the byte offset
  48018. ** immediately following the last journal record written into the main
  48019. ** journal before the journal-header. This is required during savepoint
  48020. ** rollback (see pagerPlaybackSavepoint()).
  48021. */
  48022. typedef struct PagerSavepoint PagerSavepoint;
  48023. struct PagerSavepoint {
  48024. i64 iOffset; /* Starting offset in main journal */
  48025. i64 iHdrOffset; /* See above */
  48026. Bitvec *pInSavepoint; /* Set of pages in this savepoint */
  48027. Pgno nOrig; /* Original number of pages in file */
  48028. Pgno iSubRec; /* Index of first record in sub-journal */
  48029. #ifndef SQLITE_OMIT_WAL
  48030. u32 aWalData[WAL_SAVEPOINT_NDATA]; /* WAL savepoint context */
  48031. #endif
  48032. };
  48033. /*
  48034. ** Bits of the Pager.doNotSpill flag. See further description below.
  48035. */
  48036. #define SPILLFLAG_OFF 0x01 /* Never spill cache. Set via pragma */
  48037. #define SPILLFLAG_ROLLBACK 0x02 /* Current rolling back, so do not spill */
  48038. #define SPILLFLAG_NOSYNC 0x04 /* Spill is ok, but do not sync */
  48039. /*
  48040. ** An open page cache is an instance of struct Pager. A description of
  48041. ** some of the more important member variables follows:
  48042. **
  48043. ** eState
  48044. **
  48045. ** The current 'state' of the pager object. See the comment and state
  48046. ** diagram above for a description of the pager state.
  48047. **
  48048. ** eLock
  48049. **
  48050. ** For a real on-disk database, the current lock held on the database file -
  48051. ** NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
  48052. **
  48053. ** For a temporary or in-memory database (neither of which require any
  48054. ** locks), this variable is always set to EXCLUSIVE_LOCK. Since such
  48055. ** databases always have Pager.exclusiveMode==1, this tricks the pager
  48056. ** logic into thinking that it already has all the locks it will ever
  48057. ** need (and no reason to release them).
  48058. **
  48059. ** In some (obscure) circumstances, this variable may also be set to
  48060. ** UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
  48061. ** details.
  48062. **
  48063. ** changeCountDone
  48064. **
  48065. ** This boolean variable is used to make sure that the change-counter
  48066. ** (the 4-byte header field at byte offset 24 of the database file) is
  48067. ** not updated more often than necessary.
  48068. **
  48069. ** It is set to true when the change-counter field is updated, which
  48070. ** can only happen if an exclusive lock is held on the database file.
  48071. ** It is cleared (set to false) whenever an exclusive lock is
  48072. ** relinquished on the database file. Each time a transaction is committed,
  48073. ** The changeCountDone flag is inspected. If it is true, the work of
  48074. ** updating the change-counter is omitted for the current transaction.
  48075. **
  48076. ** This mechanism means that when running in exclusive mode, a connection
  48077. ** need only update the change-counter once, for the first transaction
  48078. ** committed.
  48079. **
  48080. ** setMaster
  48081. **
  48082. ** When PagerCommitPhaseOne() is called to commit a transaction, it may
  48083. ** (or may not) specify a master-journal name to be written into the
  48084. ** journal file before it is synced to disk.
  48085. **
  48086. ** Whether or not a journal file contains a master-journal pointer affects
  48087. ** the way in which the journal file is finalized after the transaction is
  48088. ** committed or rolled back when running in "journal_mode=PERSIST" mode.
  48089. ** If a journal file does not contain a master-journal pointer, it is
  48090. ** finalized by overwriting the first journal header with zeroes. If
  48091. ** it does contain a master-journal pointer the journal file is finalized
  48092. ** by truncating it to zero bytes, just as if the connection were
  48093. ** running in "journal_mode=truncate" mode.
  48094. **
  48095. ** Journal files that contain master journal pointers cannot be finalized
  48096. ** simply by overwriting the first journal-header with zeroes, as the
  48097. ** master journal pointer could interfere with hot-journal rollback of any
  48098. ** subsequently interrupted transaction that reuses the journal file.
  48099. **
  48100. ** The flag is cleared as soon as the journal file is finalized (either
  48101. ** by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
  48102. ** journal file from being successfully finalized, the setMaster flag
  48103. ** is cleared anyway (and the pager will move to ERROR state).
  48104. **
  48105. ** doNotSpill
  48106. **
  48107. ** This variables control the behavior of cache-spills (calls made by
  48108. ** the pcache module to the pagerStress() routine to write cached data
  48109. ** to the file-system in order to free up memory).
  48110. **
  48111. ** When bits SPILLFLAG_OFF or SPILLFLAG_ROLLBACK of doNotSpill are set,
  48112. ** writing to the database from pagerStress() is disabled altogether.
  48113. ** The SPILLFLAG_ROLLBACK case is done in a very obscure case that
  48114. ** comes up during savepoint rollback that requires the pcache module
  48115. ** to allocate a new page to prevent the journal file from being written
  48116. ** while it is being traversed by code in pager_playback(). The SPILLFLAG_OFF
  48117. ** case is a user preference.
  48118. **
  48119. ** If the SPILLFLAG_NOSYNC bit is set, writing to the database from
  48120. ** pagerStress() is permitted, but syncing the journal file is not.
  48121. ** This flag is set by sqlite3PagerWrite() when the file-system sector-size
  48122. ** is larger than the database page-size in order to prevent a journal sync
  48123. ** from happening in between the journalling of two pages on the same sector.
  48124. **
  48125. ** subjInMemory
  48126. **
  48127. ** This is a boolean variable. If true, then any required sub-journal
  48128. ** is opened as an in-memory journal file. If false, then in-memory
  48129. ** sub-journals are only used for in-memory pager files.
  48130. **
  48131. ** This variable is updated by the upper layer each time a new
  48132. ** write-transaction is opened.
  48133. **
  48134. ** dbSize, dbOrigSize, dbFileSize
  48135. **
  48136. ** Variable dbSize is set to the number of pages in the database file.
  48137. ** It is valid in PAGER_READER and higher states (all states except for
  48138. ** OPEN and ERROR).
  48139. **
  48140. ** dbSize is set based on the size of the database file, which may be
  48141. ** larger than the size of the database (the value stored at offset
  48142. ** 28 of the database header by the btree). If the size of the file
  48143. ** is not an integer multiple of the page-size, the value stored in
  48144. ** dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
  48145. ** Except, any file that is greater than 0 bytes in size is considered
  48146. ** to have at least one page. (i.e. a 1KB file with 2K page-size leads
  48147. ** to dbSize==1).
  48148. **
  48149. ** During a write-transaction, if pages with page-numbers greater than
  48150. ** dbSize are modified in the cache, dbSize is updated accordingly.
  48151. ** Similarly, if the database is truncated using PagerTruncateImage(),
  48152. ** dbSize is updated.
  48153. **
  48154. ** Variables dbOrigSize and dbFileSize are valid in states
  48155. ** PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
  48156. ** variable at the start of the transaction. It is used during rollback,
  48157. ** and to determine whether or not pages need to be journalled before
  48158. ** being modified.
  48159. **
  48160. ** Throughout a write-transaction, dbFileSize contains the size of
  48161. ** the file on disk in pages. It is set to a copy of dbSize when the
  48162. ** write-transaction is first opened, and updated when VFS calls are made
  48163. ** to write or truncate the database file on disk.
  48164. **
  48165. ** The only reason the dbFileSize variable is required is to suppress
  48166. ** unnecessary calls to xTruncate() after committing a transaction. If,
  48167. ** when a transaction is committed, the dbFileSize variable indicates
  48168. ** that the database file is larger than the database image (Pager.dbSize),
  48169. ** pager_truncate() is called. The pager_truncate() call uses xFilesize()
  48170. ** to measure the database file on disk, and then truncates it if required.
  48171. ** dbFileSize is not used when rolling back a transaction. In this case
  48172. ** pager_truncate() is called unconditionally (which means there may be
  48173. ** a call to xFilesize() that is not strictly required). In either case,
  48174. ** pager_truncate() may cause the file to become smaller or larger.
  48175. **
  48176. ** dbHintSize
  48177. **
  48178. ** The dbHintSize variable is used to limit the number of calls made to
  48179. ** the VFS xFileControl(FCNTL_SIZE_HINT) method.
  48180. **
  48181. ** dbHintSize is set to a copy of the dbSize variable when a
  48182. ** write-transaction is opened (at the same time as dbFileSize and
  48183. ** dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
  48184. ** dbHintSize is increased to the number of pages that correspond to the
  48185. ** size-hint passed to the method call. See pager_write_pagelist() for
  48186. ** details.
  48187. **
  48188. ** errCode
  48189. **
  48190. ** The Pager.errCode variable is only ever used in PAGER_ERROR state. It
  48191. ** is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
  48192. ** is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
  48193. ** sub-codes.
  48194. **
  48195. ** syncFlags, walSyncFlags
  48196. **
  48197. ** syncFlags is either SQLITE_SYNC_NORMAL (0x02) or SQLITE_SYNC_FULL (0x03).
  48198. ** syncFlags is used for rollback mode. walSyncFlags is used for WAL mode
  48199. ** and contains the flags used to sync the checkpoint operations in the
  48200. ** lower two bits, and sync flags used for transaction commits in the WAL
  48201. ** file in bits 0x04 and 0x08. In other words, to get the correct sync flags
  48202. ** for checkpoint operations, use (walSyncFlags&0x03) and to get the correct
  48203. ** sync flags for transaction commit, use ((walSyncFlags>>2)&0x03). Note
  48204. ** that with synchronous=NORMAL in WAL mode, transaction commit is not synced
  48205. ** meaning that the 0x04 and 0x08 bits are both zero.
  48206. */
  48207. struct Pager {
  48208. sqlite3_vfs *pVfs; /* OS functions to use for IO */
  48209. u8 exclusiveMode; /* Boolean. True if locking_mode==EXCLUSIVE */
  48210. u8 journalMode; /* One of the PAGER_JOURNALMODE_* values */
  48211. u8 useJournal; /* Use a rollback journal on this file */
  48212. u8 noSync; /* Do not sync the journal if true */
  48213. u8 fullSync; /* Do extra syncs of the journal for robustness */
  48214. u8 extraSync; /* sync directory after journal delete */
  48215. u8 syncFlags; /* SYNC_NORMAL or SYNC_FULL otherwise */
  48216. u8 walSyncFlags; /* See description above */
  48217. u8 tempFile; /* zFilename is a temporary or immutable file */
  48218. u8 noLock; /* Do not lock (except in WAL mode) */
  48219. u8 readOnly; /* True for a read-only database */
  48220. u8 memDb; /* True to inhibit all file I/O */
  48221. /**************************************************************************
  48222. ** The following block contains those class members that change during
  48223. ** routine operation. Class members not in this block are either fixed
  48224. ** when the pager is first created or else only change when there is a
  48225. ** significant mode change (such as changing the page_size, locking_mode,
  48226. ** or the journal_mode). From another view, these class members describe
  48227. ** the "state" of the pager, while other class members describe the
  48228. ** "configuration" of the pager.
  48229. */
  48230. u8 eState; /* Pager state (OPEN, READER, WRITER_LOCKED..) */
  48231. u8 eLock; /* Current lock held on database file */
  48232. u8 changeCountDone; /* Set after incrementing the change-counter */
  48233. u8 setMaster; /* True if a m-j name has been written to jrnl */
  48234. u8 doNotSpill; /* Do not spill the cache when non-zero */
  48235. u8 subjInMemory; /* True to use in-memory sub-journals */
  48236. u8 bUseFetch; /* True to use xFetch() */
  48237. u8 hasHeldSharedLock; /* True if a shared lock has ever been held */
  48238. Pgno dbSize; /* Number of pages in the database */
  48239. Pgno dbOrigSize; /* dbSize before the current transaction */
  48240. Pgno dbFileSize; /* Number of pages in the database file */
  48241. Pgno dbHintSize; /* Value passed to FCNTL_SIZE_HINT call */
  48242. int errCode; /* One of several kinds of errors */
  48243. int nRec; /* Pages journalled since last j-header written */
  48244. u32 cksumInit; /* Quasi-random value added to every checksum */
  48245. u32 nSubRec; /* Number of records written to sub-journal */
  48246. Bitvec *pInJournal; /* One bit for each page in the database file */
  48247. sqlite3_file *fd; /* File descriptor for database */
  48248. sqlite3_file *jfd; /* File descriptor for main journal */
  48249. sqlite3_file *sjfd; /* File descriptor for sub-journal */
  48250. i64 journalOff; /* Current write offset in the journal file */
  48251. i64 journalHdr; /* Byte offset to previous journal header */
  48252. sqlite3_backup *pBackup; /* Pointer to list of ongoing backup processes */
  48253. PagerSavepoint *aSavepoint; /* Array of active savepoints */
  48254. int nSavepoint; /* Number of elements in aSavepoint[] */
  48255. u32 iDataVersion; /* Changes whenever database content changes */
  48256. char dbFileVers[16]; /* Changes whenever database file changes */
  48257. int nMmapOut; /* Number of mmap pages currently outstanding */
  48258. sqlite3_int64 szMmap; /* Desired maximum mmap size */
  48259. PgHdr *pMmapFreelist; /* List of free mmap page headers (pDirty) */
  48260. /*
  48261. ** End of the routinely-changing class members
  48262. ***************************************************************************/
  48263. u16 nExtra; /* Add this many bytes to each in-memory page */
  48264. i16 nReserve; /* Number of unused bytes at end of each page */
  48265. u32 vfsFlags; /* Flags for sqlite3_vfs.xOpen() */
  48266. u32 sectorSize; /* Assumed sector size during rollback */
  48267. int pageSize; /* Number of bytes in a page */
  48268. Pgno mxPgno; /* Maximum allowed size of the database */
  48269. i64 journalSizeLimit; /* Size limit for persistent journal files */
  48270. char *zFilename; /* Name of the database file */
  48271. char *zJournal; /* Name of the journal file */
  48272. int (*xBusyHandler)(void*); /* Function to call when busy */
  48273. void *pBusyHandlerArg; /* Context argument for xBusyHandler */
  48274. int aStat[4]; /* Total cache hits, misses, writes, spills */
  48275. #ifdef SQLITE_TEST
  48276. int nRead; /* Database pages read */
  48277. #endif
  48278. void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
  48279. int (*xGet)(Pager*,Pgno,DbPage**,int); /* Routine to fetch a patch */
  48280. #ifdef SQLITE_HAS_CODEC
  48281. void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
  48282. void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
  48283. void (*xCodecFree)(void*); /* Destructor for the codec */
  48284. void *pCodec; /* First argument to xCodec... methods */
  48285. #endif
  48286. char *pTmpSpace; /* Pager.pageSize bytes of space for tmp use */
  48287. PCache *pPCache; /* Pointer to page cache object */
  48288. #ifndef SQLITE_OMIT_WAL
  48289. Wal *pWal; /* Write-ahead log used by "journal_mode=wal" */
  48290. char *zWal; /* File name for write-ahead log */
  48291. #endif
  48292. };
  48293. /*
  48294. ** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains
  48295. ** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS
  48296. ** or CACHE_WRITE to sqlite3_db_status().
  48297. */
  48298. #define PAGER_STAT_HIT 0
  48299. #define PAGER_STAT_MISS 1
  48300. #define PAGER_STAT_WRITE 2
  48301. #define PAGER_STAT_SPILL 3
  48302. /*
  48303. ** The following global variables hold counters used for
  48304. ** testing purposes only. These variables do not exist in
  48305. ** a non-testing build. These variables are not thread-safe.
  48306. */
  48307. #ifdef SQLITE_TEST
  48308. SQLITE_API int sqlite3_pager_readdb_count = 0; /* Number of full pages read from DB */
  48309. SQLITE_API int sqlite3_pager_writedb_count = 0; /* Number of full pages written to DB */
  48310. SQLITE_API int sqlite3_pager_writej_count = 0; /* Number of pages written to journal */
  48311. # define PAGER_INCR(v) v++
  48312. #else
  48313. # define PAGER_INCR(v)
  48314. #endif
  48315. /*
  48316. ** Journal files begin with the following magic string. The data
  48317. ** was obtained from /dev/random. It is used only as a sanity check.
  48318. **
  48319. ** Since version 2.8.0, the journal format contains additional sanity
  48320. ** checking information. If the power fails while the journal is being
  48321. ** written, semi-random garbage data might appear in the journal
  48322. ** file after power is restored. If an attempt is then made
  48323. ** to roll the journal back, the database could be corrupted. The additional
  48324. ** sanity checking data is an attempt to discover the garbage in the
  48325. ** journal and ignore it.
  48326. **
  48327. ** The sanity checking information for the new journal format consists
  48328. ** of a 32-bit checksum on each page of data. The checksum covers both
  48329. ** the page number and the pPager->pageSize bytes of data for the page.
  48330. ** This cksum is initialized to a 32-bit random value that appears in the
  48331. ** journal file right after the header. The random initializer is important,
  48332. ** because garbage data that appears at the end of a journal is likely
  48333. ** data that was once in other files that have now been deleted. If the
  48334. ** garbage data came from an obsolete journal file, the checksums might
  48335. ** be correct. But by initializing the checksum to random value which
  48336. ** is different for every journal, we minimize that risk.
  48337. */
  48338. static const unsigned char aJournalMagic[] = {
  48339. 0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
  48340. };
  48341. /*
  48342. ** The size of the of each page record in the journal is given by
  48343. ** the following macro.
  48344. */
  48345. #define JOURNAL_PG_SZ(pPager) ((pPager->pageSize) + 8)
  48346. /*
  48347. ** The journal header size for this pager. This is usually the same
  48348. ** size as a single disk sector. See also setSectorSize().
  48349. */
  48350. #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
  48351. /*
  48352. ** The macro MEMDB is true if we are dealing with an in-memory database.
  48353. ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
  48354. ** the value of MEMDB will be a constant and the compiler will optimize
  48355. ** out code that would never execute.
  48356. */
  48357. #ifdef SQLITE_OMIT_MEMORYDB
  48358. # define MEMDB 0
  48359. #else
  48360. # define MEMDB pPager->memDb
  48361. #endif
  48362. /*
  48363. ** The macro USEFETCH is true if we are allowed to use the xFetch and xUnfetch
  48364. ** interfaces to access the database using memory-mapped I/O.
  48365. */
  48366. #if SQLITE_MAX_MMAP_SIZE>0
  48367. # define USEFETCH(x) ((x)->bUseFetch)
  48368. #else
  48369. # define USEFETCH(x) 0
  48370. #endif
  48371. /*
  48372. ** The maximum legal page number is (2^31 - 1).
  48373. */
  48374. #define PAGER_MAX_PGNO 2147483647
  48375. /*
  48376. ** The argument to this macro is a file descriptor (type sqlite3_file*).
  48377. ** Return 0 if it is not open, or non-zero (but not 1) if it is.
  48378. **
  48379. ** This is so that expressions can be written as:
  48380. **
  48381. ** if( isOpen(pPager->jfd) ){ ...
  48382. **
  48383. ** instead of
  48384. **
  48385. ** if( pPager->jfd->pMethods ){ ...
  48386. */
  48387. #define isOpen(pFd) ((pFd)->pMethods!=0)
  48388. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  48389. /*
  48390. ** Return true if page pgno can be read directly from the database file
  48391. ** by the b-tree layer. This is the case if:
  48392. **
  48393. ** * the database file is open,
  48394. ** * there are no dirty pages in the cache, and
  48395. ** * the desired page is not currently in the wal file.
  48396. */
  48397. SQLITE_PRIVATE int sqlite3PagerDirectReadOk(Pager *pPager, Pgno pgno){
  48398. if( pPager->fd->pMethods==0 ) return 0;
  48399. if( sqlite3PCacheIsDirty(pPager->pPCache) ) return 0;
  48400. #ifdef SQLITE_HAS_CODEC
  48401. if( pPager->xCodec!=0 ) return 0;
  48402. #endif
  48403. #ifndef SQLITE_OMIT_WAL
  48404. if( pPager->pWal ){
  48405. u32 iRead = 0;
  48406. int rc;
  48407. rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iRead);
  48408. return (rc==SQLITE_OK && iRead==0);
  48409. }
  48410. #endif
  48411. return 1;
  48412. }
  48413. #endif
  48414. #ifndef SQLITE_OMIT_WAL
  48415. # define pagerUseWal(x) ((x)->pWal!=0)
  48416. #else
  48417. # define pagerUseWal(x) 0
  48418. # define pagerRollbackWal(x) 0
  48419. # define pagerWalFrames(v,w,x,y) 0
  48420. # define pagerOpenWalIfPresent(z) SQLITE_OK
  48421. # define pagerBeginReadTransaction(z) SQLITE_OK
  48422. #endif
  48423. #ifndef NDEBUG
  48424. /*
  48425. ** Usage:
  48426. **
  48427. ** assert( assert_pager_state(pPager) );
  48428. **
  48429. ** This function runs many asserts to try to find inconsistencies in
  48430. ** the internal state of the Pager object.
  48431. */
  48432. static int assert_pager_state(Pager *p){
  48433. Pager *pPager = p;
  48434. /* State must be valid. */
  48435. assert( p->eState==PAGER_OPEN
  48436. || p->eState==PAGER_READER
  48437. || p->eState==PAGER_WRITER_LOCKED
  48438. || p->eState==PAGER_WRITER_CACHEMOD
  48439. || p->eState==PAGER_WRITER_DBMOD
  48440. || p->eState==PAGER_WRITER_FINISHED
  48441. || p->eState==PAGER_ERROR
  48442. );
  48443. /* Regardless of the current state, a temp-file connection always behaves
  48444. ** as if it has an exclusive lock on the database file. It never updates
  48445. ** the change-counter field, so the changeCountDone flag is always set.
  48446. */
  48447. assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
  48448. assert( p->tempFile==0 || pPager->changeCountDone );
  48449. /* If the useJournal flag is clear, the journal-mode must be "OFF".
  48450. ** And if the journal-mode is "OFF", the journal file must not be open.
  48451. */
  48452. assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
  48453. assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
  48454. /* Check that MEMDB implies noSync. And an in-memory journal. Since
  48455. ** this means an in-memory pager performs no IO at all, it cannot encounter
  48456. ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
  48457. ** a journal file. (although the in-memory journal implementation may
  48458. ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
  48459. ** is therefore not possible for an in-memory pager to enter the ERROR
  48460. ** state.
  48461. */
  48462. if( MEMDB ){
  48463. assert( !isOpen(p->fd) );
  48464. assert( p->noSync );
  48465. assert( p->journalMode==PAGER_JOURNALMODE_OFF
  48466. || p->journalMode==PAGER_JOURNALMODE_MEMORY
  48467. );
  48468. assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
  48469. assert( pagerUseWal(p)==0 );
  48470. }
  48471. /* If changeCountDone is set, a RESERVED lock or greater must be held
  48472. ** on the file.
  48473. */
  48474. assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
  48475. assert( p->eLock!=PENDING_LOCK );
  48476. switch( p->eState ){
  48477. case PAGER_OPEN:
  48478. assert( !MEMDB );
  48479. assert( pPager->errCode==SQLITE_OK );
  48480. assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
  48481. break;
  48482. case PAGER_READER:
  48483. assert( pPager->errCode==SQLITE_OK );
  48484. assert( p->eLock!=UNKNOWN_LOCK );
  48485. assert( p->eLock>=SHARED_LOCK );
  48486. break;
  48487. case PAGER_WRITER_LOCKED:
  48488. assert( p->eLock!=UNKNOWN_LOCK );
  48489. assert( pPager->errCode==SQLITE_OK );
  48490. if( !pagerUseWal(pPager) ){
  48491. assert( p->eLock>=RESERVED_LOCK );
  48492. }
  48493. assert( pPager->dbSize==pPager->dbOrigSize );
  48494. assert( pPager->dbOrigSize==pPager->dbFileSize );
  48495. assert( pPager->dbOrigSize==pPager->dbHintSize );
  48496. assert( pPager->setMaster==0 );
  48497. break;
  48498. case PAGER_WRITER_CACHEMOD:
  48499. assert( p->eLock!=UNKNOWN_LOCK );
  48500. assert( pPager->errCode==SQLITE_OK );
  48501. if( !pagerUseWal(pPager) ){
  48502. /* It is possible that if journal_mode=wal here that neither the
  48503. ** journal file nor the WAL file are open. This happens during
  48504. ** a rollback transaction that switches from journal_mode=off
  48505. ** to journal_mode=wal.
  48506. */
  48507. assert( p->eLock>=RESERVED_LOCK );
  48508. assert( isOpen(p->jfd)
  48509. || p->journalMode==PAGER_JOURNALMODE_OFF
  48510. || p->journalMode==PAGER_JOURNALMODE_WAL
  48511. );
  48512. }
  48513. assert( pPager->dbOrigSize==pPager->dbFileSize );
  48514. assert( pPager->dbOrigSize==pPager->dbHintSize );
  48515. break;
  48516. case PAGER_WRITER_DBMOD:
  48517. assert( p->eLock==EXCLUSIVE_LOCK );
  48518. assert( pPager->errCode==SQLITE_OK );
  48519. assert( !pagerUseWal(pPager) );
  48520. assert( p->eLock>=EXCLUSIVE_LOCK );
  48521. assert( isOpen(p->jfd)
  48522. || p->journalMode==PAGER_JOURNALMODE_OFF
  48523. || p->journalMode==PAGER_JOURNALMODE_WAL
  48524. || (sqlite3OsDeviceCharacteristics(p->fd)&SQLITE_IOCAP_BATCH_ATOMIC)
  48525. );
  48526. assert( pPager->dbOrigSize<=pPager->dbHintSize );
  48527. break;
  48528. case PAGER_WRITER_FINISHED:
  48529. assert( p->eLock==EXCLUSIVE_LOCK );
  48530. assert( pPager->errCode==SQLITE_OK );
  48531. assert( !pagerUseWal(pPager) );
  48532. assert( isOpen(p->jfd)
  48533. || p->journalMode==PAGER_JOURNALMODE_OFF
  48534. || p->journalMode==PAGER_JOURNALMODE_WAL
  48535. || (sqlite3OsDeviceCharacteristics(p->fd)&SQLITE_IOCAP_BATCH_ATOMIC)
  48536. );
  48537. break;
  48538. case PAGER_ERROR:
  48539. /* There must be at least one outstanding reference to the pager if
  48540. ** in ERROR state. Otherwise the pager should have already dropped
  48541. ** back to OPEN state.
  48542. */
  48543. assert( pPager->errCode!=SQLITE_OK );
  48544. assert( sqlite3PcacheRefCount(pPager->pPCache)>0 || pPager->tempFile );
  48545. break;
  48546. }
  48547. return 1;
  48548. }
  48549. #endif /* ifndef NDEBUG */
  48550. #ifdef SQLITE_DEBUG
  48551. /*
  48552. ** Return a pointer to a human readable string in a static buffer
  48553. ** containing the state of the Pager object passed as an argument. This
  48554. ** is intended to be used within debuggers. For example, as an alternative
  48555. ** to "print *pPager" in gdb:
  48556. **
  48557. ** (gdb) printf "%s", print_pager_state(pPager)
  48558. **
  48559. ** This routine has external linkage in order to suppress compiler warnings
  48560. ** about an unused function. It is enclosed within SQLITE_DEBUG and so does
  48561. ** not appear in normal builds.
  48562. */
  48563. char *print_pager_state(Pager *p){
  48564. static char zRet[1024];
  48565. sqlite3_snprintf(1024, zRet,
  48566. "Filename: %s\n"
  48567. "State: %s errCode=%d\n"
  48568. "Lock: %s\n"
  48569. "Locking mode: locking_mode=%s\n"
  48570. "Journal mode: journal_mode=%s\n"
  48571. "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
  48572. "Journal: journalOff=%lld journalHdr=%lld\n"
  48573. "Size: dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
  48574. , p->zFilename
  48575. , p->eState==PAGER_OPEN ? "OPEN" :
  48576. p->eState==PAGER_READER ? "READER" :
  48577. p->eState==PAGER_WRITER_LOCKED ? "WRITER_LOCKED" :
  48578. p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
  48579. p->eState==PAGER_WRITER_DBMOD ? "WRITER_DBMOD" :
  48580. p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
  48581. p->eState==PAGER_ERROR ? "ERROR" : "?error?"
  48582. , (int)p->errCode
  48583. , p->eLock==NO_LOCK ? "NO_LOCK" :
  48584. p->eLock==RESERVED_LOCK ? "RESERVED" :
  48585. p->eLock==EXCLUSIVE_LOCK ? "EXCLUSIVE" :
  48586. p->eLock==SHARED_LOCK ? "SHARED" :
  48587. p->eLock==UNKNOWN_LOCK ? "UNKNOWN" : "?error?"
  48588. , p->exclusiveMode ? "exclusive" : "normal"
  48589. , p->journalMode==PAGER_JOURNALMODE_MEMORY ? "memory" :
  48590. p->journalMode==PAGER_JOURNALMODE_OFF ? "off" :
  48591. p->journalMode==PAGER_JOURNALMODE_DELETE ? "delete" :
  48592. p->journalMode==PAGER_JOURNALMODE_PERSIST ? "persist" :
  48593. p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
  48594. p->journalMode==PAGER_JOURNALMODE_WAL ? "wal" : "?error?"
  48595. , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
  48596. , p->journalOff, p->journalHdr
  48597. , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
  48598. );
  48599. return zRet;
  48600. }
  48601. #endif
  48602. /* Forward references to the various page getters */
  48603. static int getPageNormal(Pager*,Pgno,DbPage**,int);
  48604. static int getPageError(Pager*,Pgno,DbPage**,int);
  48605. #if SQLITE_MAX_MMAP_SIZE>0
  48606. static int getPageMMap(Pager*,Pgno,DbPage**,int);
  48607. #endif
  48608. /*
  48609. ** Set the Pager.xGet method for the appropriate routine used to fetch
  48610. ** content from the pager.
  48611. */
  48612. static void setGetterMethod(Pager *pPager){
  48613. if( pPager->errCode ){
  48614. pPager->xGet = getPageError;
  48615. #if SQLITE_MAX_MMAP_SIZE>0
  48616. }else if( USEFETCH(pPager)
  48617. #ifdef SQLITE_HAS_CODEC
  48618. && pPager->xCodec==0
  48619. #endif
  48620. ){
  48621. pPager->xGet = getPageMMap;
  48622. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  48623. }else{
  48624. pPager->xGet = getPageNormal;
  48625. }
  48626. }
  48627. /*
  48628. ** Return true if it is necessary to write page *pPg into the sub-journal.
  48629. ** A page needs to be written into the sub-journal if there exists one
  48630. ** or more open savepoints for which:
  48631. **
  48632. ** * The page-number is less than or equal to PagerSavepoint.nOrig, and
  48633. ** * The bit corresponding to the page-number is not set in
  48634. ** PagerSavepoint.pInSavepoint.
  48635. */
  48636. static int subjRequiresPage(PgHdr *pPg){
  48637. Pager *pPager = pPg->pPager;
  48638. PagerSavepoint *p;
  48639. Pgno pgno = pPg->pgno;
  48640. int i;
  48641. for(i=0; i<pPager->nSavepoint; i++){
  48642. p = &pPager->aSavepoint[i];
  48643. if( p->nOrig>=pgno && 0==sqlite3BitvecTestNotNull(p->pInSavepoint, pgno) ){
  48644. return 1;
  48645. }
  48646. }
  48647. return 0;
  48648. }
  48649. #ifdef SQLITE_DEBUG
  48650. /*
  48651. ** Return true if the page is already in the journal file.
  48652. */
  48653. static int pageInJournal(Pager *pPager, PgHdr *pPg){
  48654. return sqlite3BitvecTest(pPager->pInJournal, pPg->pgno);
  48655. }
  48656. #endif
  48657. /*
  48658. ** Read a 32-bit integer from the given file descriptor. Store the integer
  48659. ** that is read in *pRes. Return SQLITE_OK if everything worked, or an
  48660. ** error code is something goes wrong.
  48661. **
  48662. ** All values are stored on disk as big-endian.
  48663. */
  48664. static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
  48665. unsigned char ac[4];
  48666. int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
  48667. if( rc==SQLITE_OK ){
  48668. *pRes = sqlite3Get4byte(ac);
  48669. }
  48670. return rc;
  48671. }
  48672. /*
  48673. ** Write a 32-bit integer into a string buffer in big-endian byte order.
  48674. */
  48675. #define put32bits(A,B) sqlite3Put4byte((u8*)A,B)
  48676. /*
  48677. ** Write a 32-bit integer into the given file descriptor. Return SQLITE_OK
  48678. ** on success or an error code is something goes wrong.
  48679. */
  48680. static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
  48681. char ac[4];
  48682. put32bits(ac, val);
  48683. return sqlite3OsWrite(fd, ac, 4, offset);
  48684. }
  48685. /*
  48686. ** Unlock the database file to level eLock, which must be either NO_LOCK
  48687. ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
  48688. ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
  48689. **
  48690. ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
  48691. ** called, do not modify it. See the comment above the #define of
  48692. ** UNKNOWN_LOCK for an explanation of this.
  48693. */
  48694. static int pagerUnlockDb(Pager *pPager, int eLock){
  48695. int rc = SQLITE_OK;
  48696. assert( !pPager->exclusiveMode || pPager->eLock==eLock );
  48697. assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
  48698. assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
  48699. if( isOpen(pPager->fd) ){
  48700. assert( pPager->eLock>=eLock );
  48701. rc = pPager->noLock ? SQLITE_OK : sqlite3OsUnlock(pPager->fd, eLock);
  48702. if( pPager->eLock!=UNKNOWN_LOCK ){
  48703. pPager->eLock = (u8)eLock;
  48704. }
  48705. IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
  48706. }
  48707. return rc;
  48708. }
  48709. /*
  48710. ** Lock the database file to level eLock, which must be either SHARED_LOCK,
  48711. ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
  48712. ** Pager.eLock variable to the new locking state.
  48713. **
  48714. ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
  48715. ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
  48716. ** See the comment above the #define of UNKNOWN_LOCK for an explanation
  48717. ** of this.
  48718. */
  48719. static int pagerLockDb(Pager *pPager, int eLock){
  48720. int rc = SQLITE_OK;
  48721. assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
  48722. if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
  48723. rc = pPager->noLock ? SQLITE_OK : sqlite3OsLock(pPager->fd, eLock);
  48724. if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
  48725. pPager->eLock = (u8)eLock;
  48726. IOTRACE(("LOCK %p %d\n", pPager, eLock))
  48727. }
  48728. }
  48729. return rc;
  48730. }
  48731. /*
  48732. ** This function determines whether or not the atomic-write or
  48733. ** atomic-batch-write optimizations can be used with this pager. The
  48734. ** atomic-write optimization can be used if:
  48735. **
  48736. ** (a) the value returned by OsDeviceCharacteristics() indicates that
  48737. ** a database page may be written atomically, and
  48738. ** (b) the value returned by OsSectorSize() is less than or equal
  48739. ** to the page size.
  48740. **
  48741. ** If it can be used, then the value returned is the size of the journal
  48742. ** file when it contains rollback data for exactly one page.
  48743. **
  48744. ** The atomic-batch-write optimization can be used if OsDeviceCharacteristics()
  48745. ** returns a value with the SQLITE_IOCAP_BATCH_ATOMIC bit set. -1 is
  48746. ** returned in this case.
  48747. **
  48748. ** If neither optimization can be used, 0 is returned.
  48749. */
  48750. static int jrnlBufferSize(Pager *pPager){
  48751. assert( !MEMDB );
  48752. #if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
  48753. || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
  48754. int dc; /* Device characteristics */
  48755. assert( isOpen(pPager->fd) );
  48756. dc = sqlite3OsDeviceCharacteristics(pPager->fd);
  48757. #else
  48758. UNUSED_PARAMETER(pPager);
  48759. #endif
  48760. #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
  48761. if( pPager->dbSize>0 && (dc&SQLITE_IOCAP_BATCH_ATOMIC) ){
  48762. return -1;
  48763. }
  48764. #endif
  48765. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  48766. {
  48767. int nSector = pPager->sectorSize;
  48768. int szPage = pPager->pageSize;
  48769. assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
  48770. assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
  48771. if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
  48772. return 0;
  48773. }
  48774. }
  48775. return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
  48776. #endif
  48777. return 0;
  48778. }
  48779. /*
  48780. ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
  48781. ** on the cache using a hash function. This is used for testing
  48782. ** and debugging only.
  48783. */
  48784. #ifdef SQLITE_CHECK_PAGES
  48785. /*
  48786. ** Return a 32-bit hash of the page data for pPage.
  48787. */
  48788. static u32 pager_datahash(int nByte, unsigned char *pData){
  48789. u32 hash = 0;
  48790. int i;
  48791. for(i=0; i<nByte; i++){
  48792. hash = (hash*1039) + pData[i];
  48793. }
  48794. return hash;
  48795. }
  48796. static u32 pager_pagehash(PgHdr *pPage){
  48797. return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
  48798. }
  48799. static void pager_set_pagehash(PgHdr *pPage){
  48800. pPage->pageHash = pager_pagehash(pPage);
  48801. }
  48802. /*
  48803. ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
  48804. ** is defined, and NDEBUG is not defined, an assert() statement checks
  48805. ** that the page is either dirty or still matches the calculated page-hash.
  48806. */
  48807. #define CHECK_PAGE(x) checkPage(x)
  48808. static void checkPage(PgHdr *pPg){
  48809. Pager *pPager = pPg->pPager;
  48810. assert( pPager->eState!=PAGER_ERROR );
  48811. assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
  48812. }
  48813. #else
  48814. #define pager_datahash(X,Y) 0
  48815. #define pager_pagehash(X) 0
  48816. #define pager_set_pagehash(X)
  48817. #define CHECK_PAGE(x)
  48818. #endif /* SQLITE_CHECK_PAGES */
  48819. /*
  48820. ** When this is called the journal file for pager pPager must be open.
  48821. ** This function attempts to read a master journal file name from the
  48822. ** end of the file and, if successful, copies it into memory supplied
  48823. ** by the caller. See comments above writeMasterJournal() for the format
  48824. ** used to store a master journal file name at the end of a journal file.
  48825. **
  48826. ** zMaster must point to a buffer of at least nMaster bytes allocated by
  48827. ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
  48828. ** enough space to write the master journal name). If the master journal
  48829. ** name in the journal is longer than nMaster bytes (including a
  48830. ** nul-terminator), then this is handled as if no master journal name
  48831. ** were present in the journal.
  48832. **
  48833. ** If a master journal file name is present at the end of the journal
  48834. ** file, then it is copied into the buffer pointed to by zMaster. A
  48835. ** nul-terminator byte is appended to the buffer following the master
  48836. ** journal file name.
  48837. **
  48838. ** If it is determined that no master journal file name is present
  48839. ** zMaster[0] is set to 0 and SQLITE_OK returned.
  48840. **
  48841. ** If an error occurs while reading from the journal file, an SQLite
  48842. ** error code is returned.
  48843. */
  48844. static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
  48845. int rc; /* Return code */
  48846. u32 len; /* Length in bytes of master journal name */
  48847. i64 szJ; /* Total size in bytes of journal file pJrnl */
  48848. u32 cksum; /* MJ checksum value read from journal */
  48849. u32 u; /* Unsigned loop counter */
  48850. unsigned char aMagic[8]; /* A buffer to hold the magic header */
  48851. zMaster[0] = '\0';
  48852. if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
  48853. || szJ<16
  48854. || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
  48855. || len>=nMaster
  48856. || len>szJ-16
  48857. || len==0
  48858. || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
  48859. || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
  48860. || memcmp(aMagic, aJournalMagic, 8)
  48861. || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
  48862. ){
  48863. return rc;
  48864. }
  48865. /* See if the checksum matches the master journal name */
  48866. for(u=0; u<len; u++){
  48867. cksum -= zMaster[u];
  48868. }
  48869. if( cksum ){
  48870. /* If the checksum doesn't add up, then one or more of the disk sectors
  48871. ** containing the master journal filename is corrupted. This means
  48872. ** definitely roll back, so just return SQLITE_OK and report a (nul)
  48873. ** master-journal filename.
  48874. */
  48875. len = 0;
  48876. }
  48877. zMaster[len] = '\0';
  48878. return SQLITE_OK;
  48879. }
  48880. /*
  48881. ** Return the offset of the sector boundary at or immediately
  48882. ** following the value in pPager->journalOff, assuming a sector
  48883. ** size of pPager->sectorSize bytes.
  48884. **
  48885. ** i.e for a sector size of 512:
  48886. **
  48887. ** Pager.journalOff Return value
  48888. ** ---------------------------------------
  48889. ** 0 0
  48890. ** 512 512
  48891. ** 100 512
  48892. ** 2000 2048
  48893. **
  48894. */
  48895. static i64 journalHdrOffset(Pager *pPager){
  48896. i64 offset = 0;
  48897. i64 c = pPager->journalOff;
  48898. if( c ){
  48899. offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
  48900. }
  48901. assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
  48902. assert( offset>=c );
  48903. assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
  48904. return offset;
  48905. }
  48906. /*
  48907. ** The journal file must be open when this function is called.
  48908. **
  48909. ** This function is a no-op if the journal file has not been written to
  48910. ** within the current transaction (i.e. if Pager.journalOff==0).
  48911. **
  48912. ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
  48913. ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
  48914. ** zero the 28-byte header at the start of the journal file. In either case,
  48915. ** if the pager is not in no-sync mode, sync the journal file immediately
  48916. ** after writing or truncating it.
  48917. **
  48918. ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
  48919. ** following the truncation or zeroing described above the size of the
  48920. ** journal file in bytes is larger than this value, then truncate the
  48921. ** journal file to Pager.journalSizeLimit bytes. The journal file does
  48922. ** not need to be synced following this operation.
  48923. **
  48924. ** If an IO error occurs, abandon processing and return the IO error code.
  48925. ** Otherwise, return SQLITE_OK.
  48926. */
  48927. static int zeroJournalHdr(Pager *pPager, int doTruncate){
  48928. int rc = SQLITE_OK; /* Return code */
  48929. assert( isOpen(pPager->jfd) );
  48930. assert( !sqlite3JournalIsInMemory(pPager->jfd) );
  48931. if( pPager->journalOff ){
  48932. const i64 iLimit = pPager->journalSizeLimit; /* Local cache of jsl */
  48933. IOTRACE(("JZEROHDR %p\n", pPager))
  48934. if( doTruncate || iLimit==0 ){
  48935. rc = sqlite3OsTruncate(pPager->jfd, 0);
  48936. }else{
  48937. static const char zeroHdr[28] = {0};
  48938. rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
  48939. }
  48940. if( rc==SQLITE_OK && !pPager->noSync ){
  48941. rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
  48942. }
  48943. /* At this point the transaction is committed but the write lock
  48944. ** is still held on the file. If there is a size limit configured for
  48945. ** the persistent journal and the journal file currently consumes more
  48946. ** space than that limit allows for, truncate it now. There is no need
  48947. ** to sync the file following this operation.
  48948. */
  48949. if( rc==SQLITE_OK && iLimit>0 ){
  48950. i64 sz;
  48951. rc = sqlite3OsFileSize(pPager->jfd, &sz);
  48952. if( rc==SQLITE_OK && sz>iLimit ){
  48953. rc = sqlite3OsTruncate(pPager->jfd, iLimit);
  48954. }
  48955. }
  48956. }
  48957. return rc;
  48958. }
  48959. /*
  48960. ** The journal file must be open when this routine is called. A journal
  48961. ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
  48962. ** current location.
  48963. **
  48964. ** The format for the journal header is as follows:
  48965. ** - 8 bytes: Magic identifying journal format.
  48966. ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
  48967. ** - 4 bytes: Random number used for page hash.
  48968. ** - 4 bytes: Initial database page count.
  48969. ** - 4 bytes: Sector size used by the process that wrote this journal.
  48970. ** - 4 bytes: Database page size.
  48971. **
  48972. ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
  48973. */
  48974. static int writeJournalHdr(Pager *pPager){
  48975. int rc = SQLITE_OK; /* Return code */
  48976. char *zHeader = pPager->pTmpSpace; /* Temporary space used to build header */
  48977. u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
  48978. u32 nWrite; /* Bytes of header sector written */
  48979. int ii; /* Loop counter */
  48980. assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
  48981. if( nHeader>JOURNAL_HDR_SZ(pPager) ){
  48982. nHeader = JOURNAL_HDR_SZ(pPager);
  48983. }
  48984. /* If there are active savepoints and any of them were created
  48985. ** since the most recent journal header was written, update the
  48986. ** PagerSavepoint.iHdrOffset fields now.
  48987. */
  48988. for(ii=0; ii<pPager->nSavepoint; ii++){
  48989. if( pPager->aSavepoint[ii].iHdrOffset==0 ){
  48990. pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
  48991. }
  48992. }
  48993. pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
  48994. /*
  48995. ** Write the nRec Field - the number of page records that follow this
  48996. ** journal header. Normally, zero is written to this value at this time.
  48997. ** After the records are added to the journal (and the journal synced,
  48998. ** if in full-sync mode), the zero is overwritten with the true number
  48999. ** of records (see syncJournal()).
  49000. **
  49001. ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
  49002. ** reading the journal this value tells SQLite to assume that the
  49003. ** rest of the journal file contains valid page records. This assumption
  49004. ** is dangerous, as if a failure occurred whilst writing to the journal
  49005. ** file it may contain some garbage data. There are two scenarios
  49006. ** where this risk can be ignored:
  49007. **
  49008. ** * When the pager is in no-sync mode. Corruption can follow a
  49009. ** power failure in this case anyway.
  49010. **
  49011. ** * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
  49012. ** that garbage data is never appended to the journal file.
  49013. */
  49014. assert( isOpen(pPager->fd) || pPager->noSync );
  49015. if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
  49016. || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
  49017. ){
  49018. memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
  49019. put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
  49020. }else{
  49021. memset(zHeader, 0, sizeof(aJournalMagic)+4);
  49022. }
  49023. /* The random check-hash initializer */
  49024. sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
  49025. put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
  49026. /* The initial database size */
  49027. put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
  49028. /* The assumed sector size for this process */
  49029. put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
  49030. /* The page size */
  49031. put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
  49032. /* Initializing the tail of the buffer is not necessary. Everything
  49033. ** works find if the following memset() is omitted. But initializing
  49034. ** the memory prevents valgrind from complaining, so we are willing to
  49035. ** take the performance hit.
  49036. */
  49037. memset(&zHeader[sizeof(aJournalMagic)+20], 0,
  49038. nHeader-(sizeof(aJournalMagic)+20));
  49039. /* In theory, it is only necessary to write the 28 bytes that the
  49040. ** journal header consumes to the journal file here. Then increment the
  49041. ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
  49042. ** record is written to the following sector (leaving a gap in the file
  49043. ** that will be implicitly filled in by the OS).
  49044. **
  49045. ** However it has been discovered that on some systems this pattern can
  49046. ** be significantly slower than contiguously writing data to the file,
  49047. ** even if that means explicitly writing data to the block of
  49048. ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
  49049. ** is done.
  49050. **
  49051. ** The loop is required here in case the sector-size is larger than the
  49052. ** database page size. Since the zHeader buffer is only Pager.pageSize
  49053. ** bytes in size, more than one call to sqlite3OsWrite() may be required
  49054. ** to populate the entire journal header sector.
  49055. */
  49056. for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
  49057. IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
  49058. rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
  49059. assert( pPager->journalHdr <= pPager->journalOff );
  49060. pPager->journalOff += nHeader;
  49061. }
  49062. return rc;
  49063. }
  49064. /*
  49065. ** The journal file must be open when this is called. A journal header file
  49066. ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
  49067. ** file. The current location in the journal file is given by
  49068. ** pPager->journalOff. See comments above function writeJournalHdr() for
  49069. ** a description of the journal header format.
  49070. **
  49071. ** If the header is read successfully, *pNRec is set to the number of
  49072. ** page records following this header and *pDbSize is set to the size of the
  49073. ** database before the transaction began, in pages. Also, pPager->cksumInit
  49074. ** is set to the value read from the journal header. SQLITE_OK is returned
  49075. ** in this case.
  49076. **
  49077. ** If the journal header file appears to be corrupted, SQLITE_DONE is
  49078. ** returned and *pNRec and *PDbSize are undefined. If JOURNAL_HDR_SZ bytes
  49079. ** cannot be read from the journal file an error code is returned.
  49080. */
  49081. static int readJournalHdr(
  49082. Pager *pPager, /* Pager object */
  49083. int isHot,
  49084. i64 journalSize, /* Size of the open journal file in bytes */
  49085. u32 *pNRec, /* OUT: Value read from the nRec field */
  49086. u32 *pDbSize /* OUT: Value of original database size field */
  49087. ){
  49088. int rc; /* Return code */
  49089. unsigned char aMagic[8]; /* A buffer to hold the magic header */
  49090. i64 iHdrOff; /* Offset of journal header being read */
  49091. assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
  49092. /* Advance Pager.journalOff to the start of the next sector. If the
  49093. ** journal file is too small for there to be a header stored at this
  49094. ** point, return SQLITE_DONE.
  49095. */
  49096. pPager->journalOff = journalHdrOffset(pPager);
  49097. if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
  49098. return SQLITE_DONE;
  49099. }
  49100. iHdrOff = pPager->journalOff;
  49101. /* Read in the first 8 bytes of the journal header. If they do not match
  49102. ** the magic string found at the start of each journal header, return
  49103. ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
  49104. ** proceed.
  49105. */
  49106. if( isHot || iHdrOff!=pPager->journalHdr ){
  49107. rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
  49108. if( rc ){
  49109. return rc;
  49110. }
  49111. if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
  49112. return SQLITE_DONE;
  49113. }
  49114. }
  49115. /* Read the first three 32-bit fields of the journal header: The nRec
  49116. ** field, the checksum-initializer and the database size at the start
  49117. ** of the transaction. Return an error code if anything goes wrong.
  49118. */
  49119. if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
  49120. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
  49121. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
  49122. ){
  49123. return rc;
  49124. }
  49125. if( pPager->journalOff==0 ){
  49126. u32 iPageSize; /* Page-size field of journal header */
  49127. u32 iSectorSize; /* Sector-size field of journal header */
  49128. /* Read the page-size and sector-size journal header fields. */
  49129. if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
  49130. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
  49131. ){
  49132. return rc;
  49133. }
  49134. /* Versions of SQLite prior to 3.5.8 set the page-size field of the
  49135. ** journal header to zero. In this case, assume that the Pager.pageSize
  49136. ** variable is already set to the correct page size.
  49137. */
  49138. if( iPageSize==0 ){
  49139. iPageSize = pPager->pageSize;
  49140. }
  49141. /* Check that the values read from the page-size and sector-size fields
  49142. ** are within range. To be 'in range', both values need to be a power
  49143. ** of two greater than or equal to 512 or 32, and not greater than their
  49144. ** respective compile time maximum limits.
  49145. */
  49146. if( iPageSize<512 || iSectorSize<32
  49147. || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
  49148. || ((iPageSize-1)&iPageSize)!=0 || ((iSectorSize-1)&iSectorSize)!=0
  49149. ){
  49150. /* If the either the page-size or sector-size in the journal-header is
  49151. ** invalid, then the process that wrote the journal-header must have
  49152. ** crashed before the header was synced. In this case stop reading
  49153. ** the journal file here.
  49154. */
  49155. return SQLITE_DONE;
  49156. }
  49157. /* Update the page-size to match the value read from the journal.
  49158. ** Use a testcase() macro to make sure that malloc failure within
  49159. ** PagerSetPagesize() is tested.
  49160. */
  49161. rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
  49162. testcase( rc!=SQLITE_OK );
  49163. /* Update the assumed sector-size to match the value used by
  49164. ** the process that created this journal. If this journal was
  49165. ** created by a process other than this one, then this routine
  49166. ** is being called from within pager_playback(). The local value
  49167. ** of Pager.sectorSize is restored at the end of that routine.
  49168. */
  49169. pPager->sectorSize = iSectorSize;
  49170. }
  49171. pPager->journalOff += JOURNAL_HDR_SZ(pPager);
  49172. return rc;
  49173. }
  49174. /*
  49175. ** Write the supplied master journal name into the journal file for pager
  49176. ** pPager at the current location. The master journal name must be the last
  49177. ** thing written to a journal file. If the pager is in full-sync mode, the
  49178. ** journal file descriptor is advanced to the next sector boundary before
  49179. ** anything is written. The format is:
  49180. **
  49181. ** + 4 bytes: PAGER_MJ_PGNO.
  49182. ** + N bytes: Master journal filename in utf-8.
  49183. ** + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
  49184. ** + 4 bytes: Master journal name checksum.
  49185. ** + 8 bytes: aJournalMagic[].
  49186. **
  49187. ** The master journal page checksum is the sum of the bytes in the master
  49188. ** journal name, where each byte is interpreted as a signed 8-bit integer.
  49189. **
  49190. ** If zMaster is a NULL pointer (occurs for a single database transaction),
  49191. ** this call is a no-op.
  49192. */
  49193. static int writeMasterJournal(Pager *pPager, const char *zMaster){
  49194. int rc; /* Return code */
  49195. int nMaster; /* Length of string zMaster */
  49196. i64 iHdrOff; /* Offset of header in journal file */
  49197. i64 jrnlSize; /* Size of journal file on disk */
  49198. u32 cksum = 0; /* Checksum of string zMaster */
  49199. assert( pPager->setMaster==0 );
  49200. assert( !pagerUseWal(pPager) );
  49201. if( !zMaster
  49202. || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
  49203. || !isOpen(pPager->jfd)
  49204. ){
  49205. return SQLITE_OK;
  49206. }
  49207. pPager->setMaster = 1;
  49208. assert( pPager->journalHdr <= pPager->journalOff );
  49209. /* Calculate the length in bytes and the checksum of zMaster */
  49210. for(nMaster=0; zMaster[nMaster]; nMaster++){
  49211. cksum += zMaster[nMaster];
  49212. }
  49213. /* If in full-sync mode, advance to the next disk sector before writing
  49214. ** the master journal name. This is in case the previous page written to
  49215. ** the journal has already been synced.
  49216. */
  49217. if( pPager->fullSync ){
  49218. pPager->journalOff = journalHdrOffset(pPager);
  49219. }
  49220. iHdrOff = pPager->journalOff;
  49221. /* Write the master journal data to the end of the journal file. If
  49222. ** an error occurs, return the error code to the caller.
  49223. */
  49224. if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
  49225. || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
  49226. || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
  49227. || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
  49228. || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8,
  49229. iHdrOff+4+nMaster+8)))
  49230. ){
  49231. return rc;
  49232. }
  49233. pPager->journalOff += (nMaster+20);
  49234. /* If the pager is in peristent-journal mode, then the physical
  49235. ** journal-file may extend past the end of the master-journal name
  49236. ** and 8 bytes of magic data just written to the file. This is
  49237. ** dangerous because the code to rollback a hot-journal file
  49238. ** will not be able to find the master-journal name to determine
  49239. ** whether or not the journal is hot.
  49240. **
  49241. ** Easiest thing to do in this scenario is to truncate the journal
  49242. ** file to the required size.
  49243. */
  49244. if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
  49245. && jrnlSize>pPager->journalOff
  49246. ){
  49247. rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
  49248. }
  49249. return rc;
  49250. }
  49251. /*
  49252. ** Discard the entire contents of the in-memory page-cache.
  49253. */
  49254. static void pager_reset(Pager *pPager){
  49255. pPager->iDataVersion++;
  49256. sqlite3BackupRestart(pPager->pBackup);
  49257. sqlite3PcacheClear(pPager->pPCache);
  49258. }
  49259. /*
  49260. ** Return the pPager->iDataVersion value
  49261. */
  49262. SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager *pPager){
  49263. return pPager->iDataVersion;
  49264. }
  49265. /*
  49266. ** Free all structures in the Pager.aSavepoint[] array and set both
  49267. ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
  49268. ** if it is open and the pager is not in exclusive mode.
  49269. */
  49270. static void releaseAllSavepoints(Pager *pPager){
  49271. int ii; /* Iterator for looping through Pager.aSavepoint */
  49272. for(ii=0; ii<pPager->nSavepoint; ii++){
  49273. sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
  49274. }
  49275. if( !pPager->exclusiveMode || sqlite3JournalIsInMemory(pPager->sjfd) ){
  49276. sqlite3OsClose(pPager->sjfd);
  49277. }
  49278. sqlite3_free(pPager->aSavepoint);
  49279. pPager->aSavepoint = 0;
  49280. pPager->nSavepoint = 0;
  49281. pPager->nSubRec = 0;
  49282. }
  49283. /*
  49284. ** Set the bit number pgno in the PagerSavepoint.pInSavepoint
  49285. ** bitvecs of all open savepoints. Return SQLITE_OK if successful
  49286. ** or SQLITE_NOMEM if a malloc failure occurs.
  49287. */
  49288. static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
  49289. int ii; /* Loop counter */
  49290. int rc = SQLITE_OK; /* Result code */
  49291. for(ii=0; ii<pPager->nSavepoint; ii++){
  49292. PagerSavepoint *p = &pPager->aSavepoint[ii];
  49293. if( pgno<=p->nOrig ){
  49294. rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
  49295. testcase( rc==SQLITE_NOMEM );
  49296. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  49297. }
  49298. }
  49299. return rc;
  49300. }
  49301. /*
  49302. ** This function is a no-op if the pager is in exclusive mode and not
  49303. ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
  49304. ** state.
  49305. **
  49306. ** If the pager is not in exclusive-access mode, the database file is
  49307. ** completely unlocked. If the file is unlocked and the file-system does
  49308. ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
  49309. ** closed (if it is open).
  49310. **
  49311. ** If the pager is in ERROR state when this function is called, the
  49312. ** contents of the pager cache are discarded before switching back to
  49313. ** the OPEN state. Regardless of whether the pager is in exclusive-mode
  49314. ** or not, any journal file left in the file-system will be treated
  49315. ** as a hot-journal and rolled back the next time a read-transaction
  49316. ** is opened (by this or by any other connection).
  49317. */
  49318. static void pager_unlock(Pager *pPager){
  49319. assert( pPager->eState==PAGER_READER
  49320. || pPager->eState==PAGER_OPEN
  49321. || pPager->eState==PAGER_ERROR
  49322. );
  49323. sqlite3BitvecDestroy(pPager->pInJournal);
  49324. pPager->pInJournal = 0;
  49325. releaseAllSavepoints(pPager);
  49326. if( pagerUseWal(pPager) ){
  49327. assert( !isOpen(pPager->jfd) );
  49328. sqlite3WalEndReadTransaction(pPager->pWal);
  49329. pPager->eState = PAGER_OPEN;
  49330. }else if( !pPager->exclusiveMode ){
  49331. int rc; /* Error code returned by pagerUnlockDb() */
  49332. int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
  49333. /* If the operating system support deletion of open files, then
  49334. ** close the journal file when dropping the database lock. Otherwise
  49335. ** another connection with journal_mode=delete might delete the file
  49336. ** out from under us.
  49337. */
  49338. assert( (PAGER_JOURNALMODE_MEMORY & 5)!=1 );
  49339. assert( (PAGER_JOURNALMODE_OFF & 5)!=1 );
  49340. assert( (PAGER_JOURNALMODE_WAL & 5)!=1 );
  49341. assert( (PAGER_JOURNALMODE_DELETE & 5)!=1 );
  49342. assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
  49343. assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
  49344. if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
  49345. || 1!=(pPager->journalMode & 5)
  49346. ){
  49347. sqlite3OsClose(pPager->jfd);
  49348. }
  49349. /* If the pager is in the ERROR state and the call to unlock the database
  49350. ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
  49351. ** above the #define for UNKNOWN_LOCK for an explanation of why this
  49352. ** is necessary.
  49353. */
  49354. rc = pagerUnlockDb(pPager, NO_LOCK);
  49355. if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
  49356. pPager->eLock = UNKNOWN_LOCK;
  49357. }
  49358. /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
  49359. ** without clearing the error code. This is intentional - the error
  49360. ** code is cleared and the cache reset in the block below.
  49361. */
  49362. assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
  49363. pPager->changeCountDone = 0;
  49364. pPager->eState = PAGER_OPEN;
  49365. }
  49366. /* If Pager.errCode is set, the contents of the pager cache cannot be
  49367. ** trusted. Now that there are no outstanding references to the pager,
  49368. ** it can safely move back to PAGER_OPEN state. This happens in both
  49369. ** normal and exclusive-locking mode.
  49370. */
  49371. assert( pPager->errCode==SQLITE_OK || !MEMDB );
  49372. if( pPager->errCode ){
  49373. if( pPager->tempFile==0 ){
  49374. pager_reset(pPager);
  49375. pPager->changeCountDone = 0;
  49376. pPager->eState = PAGER_OPEN;
  49377. }else{
  49378. pPager->eState = (isOpen(pPager->jfd) ? PAGER_OPEN : PAGER_READER);
  49379. }
  49380. if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
  49381. pPager->errCode = SQLITE_OK;
  49382. setGetterMethod(pPager);
  49383. }
  49384. pPager->journalOff = 0;
  49385. pPager->journalHdr = 0;
  49386. pPager->setMaster = 0;
  49387. }
  49388. /*
  49389. ** This function is called whenever an IOERR or FULL error that requires
  49390. ** the pager to transition into the ERROR state may ahve occurred.
  49391. ** The first argument is a pointer to the pager structure, the second
  49392. ** the error-code about to be returned by a pager API function. The
  49393. ** value returned is a copy of the second argument to this function.
  49394. **
  49395. ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
  49396. ** IOERR sub-codes, the pager enters the ERROR state and the error code
  49397. ** is stored in Pager.errCode. While the pager remains in the ERROR state,
  49398. ** all major API calls on the Pager will immediately return Pager.errCode.
  49399. **
  49400. ** The ERROR state indicates that the contents of the pager-cache
  49401. ** cannot be trusted. This state can be cleared by completely discarding
  49402. ** the contents of the pager-cache. If a transaction was active when
  49403. ** the persistent error occurred, then the rollback journal may need
  49404. ** to be replayed to restore the contents of the database file (as if
  49405. ** it were a hot-journal).
  49406. */
  49407. static int pager_error(Pager *pPager, int rc){
  49408. int rc2 = rc & 0xff;
  49409. assert( rc==SQLITE_OK || !MEMDB );
  49410. assert(
  49411. pPager->errCode==SQLITE_FULL ||
  49412. pPager->errCode==SQLITE_OK ||
  49413. (pPager->errCode & 0xff)==SQLITE_IOERR
  49414. );
  49415. if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
  49416. pPager->errCode = rc;
  49417. pPager->eState = PAGER_ERROR;
  49418. setGetterMethod(pPager);
  49419. }
  49420. return rc;
  49421. }
  49422. static int pager_truncate(Pager *pPager, Pgno nPage);
  49423. /*
  49424. ** The write transaction open on pPager is being committed (bCommit==1)
  49425. ** or rolled back (bCommit==0).
  49426. **
  49427. ** Return TRUE if and only if all dirty pages should be flushed to disk.
  49428. **
  49429. ** Rules:
  49430. **
  49431. ** * For non-TEMP databases, always sync to disk. This is necessary
  49432. ** for transactions to be durable.
  49433. **
  49434. ** * Sync TEMP database only on a COMMIT (not a ROLLBACK) when the backing
  49435. ** file has been created already (via a spill on pagerStress()) and
  49436. ** when the number of dirty pages in memory exceeds 25% of the total
  49437. ** cache size.
  49438. */
  49439. static int pagerFlushOnCommit(Pager *pPager, int bCommit){
  49440. if( pPager->tempFile==0 ) return 1;
  49441. if( !bCommit ) return 0;
  49442. if( !isOpen(pPager->fd) ) return 0;
  49443. return (sqlite3PCachePercentDirty(pPager->pPCache)>=25);
  49444. }
  49445. /*
  49446. ** This routine ends a transaction. A transaction is usually ended by
  49447. ** either a COMMIT or a ROLLBACK operation. This routine may be called
  49448. ** after rollback of a hot-journal, or if an error occurs while opening
  49449. ** the journal file or writing the very first journal-header of a
  49450. ** database transaction.
  49451. **
  49452. ** This routine is never called in PAGER_ERROR state. If it is called
  49453. ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
  49454. ** exclusive than a RESERVED lock, it is a no-op.
  49455. **
  49456. ** Otherwise, any active savepoints are released.
  49457. **
  49458. ** If the journal file is open, then it is "finalized". Once a journal
  49459. ** file has been finalized it is not possible to use it to roll back a
  49460. ** transaction. Nor will it be considered to be a hot-journal by this
  49461. ** or any other database connection. Exactly how a journal is finalized
  49462. ** depends on whether or not the pager is running in exclusive mode and
  49463. ** the current journal-mode (Pager.journalMode value), as follows:
  49464. **
  49465. ** journalMode==MEMORY
  49466. ** Journal file descriptor is simply closed. This destroys an
  49467. ** in-memory journal.
  49468. **
  49469. ** journalMode==TRUNCATE
  49470. ** Journal file is truncated to zero bytes in size.
  49471. **
  49472. ** journalMode==PERSIST
  49473. ** The first 28 bytes of the journal file are zeroed. This invalidates
  49474. ** the first journal header in the file, and hence the entire journal
  49475. ** file. An invalid journal file cannot be rolled back.
  49476. **
  49477. ** journalMode==DELETE
  49478. ** The journal file is closed and deleted using sqlite3OsDelete().
  49479. **
  49480. ** If the pager is running in exclusive mode, this method of finalizing
  49481. ** the journal file is never used. Instead, if the journalMode is
  49482. ** DELETE and the pager is in exclusive mode, the method described under
  49483. ** journalMode==PERSIST is used instead.
  49484. **
  49485. ** After the journal is finalized, the pager moves to PAGER_READER state.
  49486. ** If running in non-exclusive rollback mode, the lock on the file is
  49487. ** downgraded to a SHARED_LOCK.
  49488. **
  49489. ** SQLITE_OK is returned if no error occurs. If an error occurs during
  49490. ** any of the IO operations to finalize the journal file or unlock the
  49491. ** database then the IO error code is returned to the user. If the
  49492. ** operation to finalize the journal file fails, then the code still
  49493. ** tries to unlock the database file if not in exclusive mode. If the
  49494. ** unlock operation fails as well, then the first error code related
  49495. ** to the first error encountered (the journal finalization one) is
  49496. ** returned.
  49497. */
  49498. static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){
  49499. int rc = SQLITE_OK; /* Error code from journal finalization operation */
  49500. int rc2 = SQLITE_OK; /* Error code from db file unlock operation */
  49501. /* Do nothing if the pager does not have an open write transaction
  49502. ** or at least a RESERVED lock. This function may be called when there
  49503. ** is no write-transaction active but a RESERVED or greater lock is
  49504. ** held under two circumstances:
  49505. **
  49506. ** 1. After a successful hot-journal rollback, it is called with
  49507. ** eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
  49508. **
  49509. ** 2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
  49510. ** lock switches back to locking_mode=normal and then executes a
  49511. ** read-transaction, this function is called with eState==PAGER_READER
  49512. ** and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
  49513. */
  49514. assert( assert_pager_state(pPager) );
  49515. assert( pPager->eState!=PAGER_ERROR );
  49516. if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
  49517. return SQLITE_OK;
  49518. }
  49519. releaseAllSavepoints(pPager);
  49520. assert( isOpen(pPager->jfd) || pPager->pInJournal==0
  49521. || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_BATCH_ATOMIC)
  49522. );
  49523. if( isOpen(pPager->jfd) ){
  49524. assert( !pagerUseWal(pPager) );
  49525. /* Finalize the journal file. */
  49526. if( sqlite3JournalIsInMemory(pPager->jfd) ){
  49527. /* assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ); */
  49528. sqlite3OsClose(pPager->jfd);
  49529. }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
  49530. if( pPager->journalOff==0 ){
  49531. rc = SQLITE_OK;
  49532. }else{
  49533. rc = sqlite3OsTruncate(pPager->jfd, 0);
  49534. if( rc==SQLITE_OK && pPager->fullSync ){
  49535. /* Make sure the new file size is written into the inode right away.
  49536. ** Otherwise the journal might resurrect following a power loss and
  49537. ** cause the last transaction to roll back. See
  49538. ** https://bugzilla.mozilla.org/show_bug.cgi?id=1072773
  49539. */
  49540. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
  49541. }
  49542. }
  49543. pPager->journalOff = 0;
  49544. }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
  49545. || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
  49546. ){
  49547. rc = zeroJournalHdr(pPager, hasMaster||pPager->tempFile);
  49548. pPager->journalOff = 0;
  49549. }else{
  49550. /* This branch may be executed with Pager.journalMode==MEMORY if
  49551. ** a hot-journal was just rolled back. In this case the journal
  49552. ** file should be closed and deleted. If this connection writes to
  49553. ** the database file, it will do so using an in-memory journal.
  49554. */
  49555. int bDelete = !pPager->tempFile;
  49556. assert( sqlite3JournalIsInMemory(pPager->jfd)==0 );
  49557. assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
  49558. || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
  49559. || pPager->journalMode==PAGER_JOURNALMODE_WAL
  49560. );
  49561. sqlite3OsClose(pPager->jfd);
  49562. if( bDelete ){
  49563. rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, pPager->extraSync);
  49564. }
  49565. }
  49566. }
  49567. #ifdef SQLITE_CHECK_PAGES
  49568. sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
  49569. if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
  49570. PgHdr *p = sqlite3PagerLookup(pPager, 1);
  49571. if( p ){
  49572. p->pageHash = 0;
  49573. sqlite3PagerUnrefNotNull(p);
  49574. }
  49575. }
  49576. #endif
  49577. sqlite3BitvecDestroy(pPager->pInJournal);
  49578. pPager->pInJournal = 0;
  49579. pPager->nRec = 0;
  49580. if( rc==SQLITE_OK ){
  49581. if( MEMDB || pagerFlushOnCommit(pPager, bCommit) ){
  49582. sqlite3PcacheCleanAll(pPager->pPCache);
  49583. }else{
  49584. sqlite3PcacheClearWritable(pPager->pPCache);
  49585. }
  49586. sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
  49587. }
  49588. if( pagerUseWal(pPager) ){
  49589. /* Drop the WAL write-lock, if any. Also, if the connection was in
  49590. ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
  49591. ** lock held on the database file.
  49592. */
  49593. rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
  49594. assert( rc2==SQLITE_OK );
  49595. }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){
  49596. /* This branch is taken when committing a transaction in rollback-journal
  49597. ** mode if the database file on disk is larger than the database image.
  49598. ** At this point the journal has been finalized and the transaction
  49599. ** successfully committed, but the EXCLUSIVE lock is still held on the
  49600. ** file. So it is safe to truncate the database file to its minimum
  49601. ** required size. */
  49602. assert( pPager->eLock==EXCLUSIVE_LOCK );
  49603. rc = pager_truncate(pPager, pPager->dbSize);
  49604. }
  49605. if( rc==SQLITE_OK && bCommit ){
  49606. rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_COMMIT_PHASETWO, 0);
  49607. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  49608. }
  49609. if( !pPager->exclusiveMode
  49610. && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
  49611. ){
  49612. rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
  49613. pPager->changeCountDone = 0;
  49614. }
  49615. pPager->eState = PAGER_READER;
  49616. pPager->setMaster = 0;
  49617. return (rc==SQLITE_OK?rc2:rc);
  49618. }
  49619. /*
  49620. ** Execute a rollback if a transaction is active and unlock the
  49621. ** database file.
  49622. **
  49623. ** If the pager has already entered the ERROR state, do not attempt
  49624. ** the rollback at this time. Instead, pager_unlock() is called. The
  49625. ** call to pager_unlock() will discard all in-memory pages, unlock
  49626. ** the database file and move the pager back to OPEN state. If this
  49627. ** means that there is a hot-journal left in the file-system, the next
  49628. ** connection to obtain a shared lock on the pager (which may be this one)
  49629. ** will roll it back.
  49630. **
  49631. ** If the pager has not already entered the ERROR state, but an IO or
  49632. ** malloc error occurs during a rollback, then this will itself cause
  49633. ** the pager to enter the ERROR state. Which will be cleared by the
  49634. ** call to pager_unlock(), as described above.
  49635. */
  49636. static void pagerUnlockAndRollback(Pager *pPager){
  49637. if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
  49638. assert( assert_pager_state(pPager) );
  49639. if( pPager->eState>=PAGER_WRITER_LOCKED ){
  49640. sqlite3BeginBenignMalloc();
  49641. sqlite3PagerRollback(pPager);
  49642. sqlite3EndBenignMalloc();
  49643. }else if( !pPager->exclusiveMode ){
  49644. assert( pPager->eState==PAGER_READER );
  49645. pager_end_transaction(pPager, 0, 0);
  49646. }
  49647. }
  49648. pager_unlock(pPager);
  49649. }
  49650. /*
  49651. ** Parameter aData must point to a buffer of pPager->pageSize bytes
  49652. ** of data. Compute and return a checksum based ont the contents of the
  49653. ** page of data and the current value of pPager->cksumInit.
  49654. **
  49655. ** This is not a real checksum. It is really just the sum of the
  49656. ** random initial value (pPager->cksumInit) and every 200th byte
  49657. ** of the page data, starting with byte offset (pPager->pageSize%200).
  49658. ** Each byte is interpreted as an 8-bit unsigned integer.
  49659. **
  49660. ** Changing the formula used to compute this checksum results in an
  49661. ** incompatible journal file format.
  49662. **
  49663. ** If journal corruption occurs due to a power failure, the most likely
  49664. ** scenario is that one end or the other of the record will be changed.
  49665. ** It is much less likely that the two ends of the journal record will be
  49666. ** correct and the middle be corrupt. Thus, this "checksum" scheme,
  49667. ** though fast and simple, catches the mostly likely kind of corruption.
  49668. */
  49669. static u32 pager_cksum(Pager *pPager, const u8 *aData){
  49670. u32 cksum = pPager->cksumInit; /* Checksum value to return */
  49671. int i = pPager->pageSize-200; /* Loop counter */
  49672. while( i>0 ){
  49673. cksum += aData[i];
  49674. i -= 200;
  49675. }
  49676. return cksum;
  49677. }
  49678. /*
  49679. ** Report the current page size and number of reserved bytes back
  49680. ** to the codec.
  49681. */
  49682. #ifdef SQLITE_HAS_CODEC
  49683. static void pagerReportSize(Pager *pPager){
  49684. if( pPager->xCodecSizeChng ){
  49685. pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
  49686. (int)pPager->nReserve);
  49687. }
  49688. }
  49689. #else
  49690. # define pagerReportSize(X) /* No-op if we do not support a codec */
  49691. #endif
  49692. #ifdef SQLITE_HAS_CODEC
  49693. /*
  49694. ** Make sure the number of reserved bits is the same in the destination
  49695. ** pager as it is in the source. This comes up when a VACUUM changes the
  49696. ** number of reserved bits to the "optimal" amount.
  49697. */
  49698. SQLITE_PRIVATE void sqlite3PagerAlignReserve(Pager *pDest, Pager *pSrc){
  49699. if( pDest->nReserve!=pSrc->nReserve ){
  49700. pDest->nReserve = pSrc->nReserve;
  49701. pagerReportSize(pDest);
  49702. }
  49703. }
  49704. #endif
  49705. /*
  49706. ** Read a single page from either the journal file (if isMainJrnl==1) or
  49707. ** from the sub-journal (if isMainJrnl==0) and playback that page.
  49708. ** The page begins at offset *pOffset into the file. The *pOffset
  49709. ** value is increased to the start of the next page in the journal.
  49710. **
  49711. ** The main rollback journal uses checksums - the statement journal does
  49712. ** not.
  49713. **
  49714. ** If the page number of the page record read from the (sub-)journal file
  49715. ** is greater than the current value of Pager.dbSize, then playback is
  49716. ** skipped and SQLITE_OK is returned.
  49717. **
  49718. ** If pDone is not NULL, then it is a record of pages that have already
  49719. ** been played back. If the page at *pOffset has already been played back
  49720. ** (if the corresponding pDone bit is set) then skip the playback.
  49721. ** Make sure the pDone bit corresponding to the *pOffset page is set
  49722. ** prior to returning.
  49723. **
  49724. ** If the page record is successfully read from the (sub-)journal file
  49725. ** and played back, then SQLITE_OK is returned. If an IO error occurs
  49726. ** while reading the record from the (sub-)journal file or while writing
  49727. ** to the database file, then the IO error code is returned. If data
  49728. ** is successfully read from the (sub-)journal file but appears to be
  49729. ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
  49730. ** two circumstances:
  49731. **
  49732. ** * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
  49733. ** * If the record is being rolled back from the main journal file
  49734. ** and the checksum field does not match the record content.
  49735. **
  49736. ** Neither of these two scenarios are possible during a savepoint rollback.
  49737. **
  49738. ** If this is a savepoint rollback, then memory may have to be dynamically
  49739. ** allocated by this function. If this is the case and an allocation fails,
  49740. ** SQLITE_NOMEM is returned.
  49741. */
  49742. static int pager_playback_one_page(
  49743. Pager *pPager, /* The pager being played back */
  49744. i64 *pOffset, /* Offset of record to playback */
  49745. Bitvec *pDone, /* Bitvec of pages already played back */
  49746. int isMainJrnl, /* 1 -> main journal. 0 -> sub-journal. */
  49747. int isSavepnt /* True for a savepoint rollback */
  49748. ){
  49749. int rc;
  49750. PgHdr *pPg; /* An existing page in the cache */
  49751. Pgno pgno; /* The page number of a page in journal */
  49752. u32 cksum; /* Checksum used for sanity checking */
  49753. char *aData; /* Temporary storage for the page */
  49754. sqlite3_file *jfd; /* The file descriptor for the journal file */
  49755. int isSynced; /* True if journal page is synced */
  49756. #ifdef SQLITE_HAS_CODEC
  49757. /* The jrnlEnc flag is true if Journal pages should be passed through
  49758. ** the codec. It is false for pure in-memory journals. */
  49759. const int jrnlEnc = (isMainJrnl || pPager->subjInMemory==0);
  49760. #endif
  49761. assert( (isMainJrnl&~1)==0 ); /* isMainJrnl is 0 or 1 */
  49762. assert( (isSavepnt&~1)==0 ); /* isSavepnt is 0 or 1 */
  49763. assert( isMainJrnl || pDone ); /* pDone always used on sub-journals */
  49764. assert( isSavepnt || pDone==0 ); /* pDone never used on non-savepoint */
  49765. aData = pPager->pTmpSpace;
  49766. assert( aData ); /* Temp storage must have already been allocated */
  49767. assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
  49768. /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
  49769. ** or savepoint rollback done at the request of the caller) or this is
  49770. ** a hot-journal rollback. If it is a hot-journal rollback, the pager
  49771. ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
  49772. ** only reads from the main journal, not the sub-journal.
  49773. */
  49774. assert( pPager->eState>=PAGER_WRITER_CACHEMOD
  49775. || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
  49776. );
  49777. assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
  49778. /* Read the page number and page data from the journal or sub-journal
  49779. ** file. Return an error code to the caller if an IO error occurs.
  49780. */
  49781. jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
  49782. rc = read32bits(jfd, *pOffset, &pgno);
  49783. if( rc!=SQLITE_OK ) return rc;
  49784. rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
  49785. if( rc!=SQLITE_OK ) return rc;
  49786. *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
  49787. /* Sanity checking on the page. This is more important that I originally
  49788. ** thought. If a power failure occurs while the journal is being written,
  49789. ** it could cause invalid data to be written into the journal. We need to
  49790. ** detect this invalid data (with high probability) and ignore it.
  49791. */
  49792. if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
  49793. assert( !isSavepnt );
  49794. return SQLITE_DONE;
  49795. }
  49796. if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
  49797. return SQLITE_OK;
  49798. }
  49799. if( isMainJrnl ){
  49800. rc = read32bits(jfd, (*pOffset)-4, &cksum);
  49801. if( rc ) return rc;
  49802. if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
  49803. return SQLITE_DONE;
  49804. }
  49805. }
  49806. /* If this page has already been played back before during the current
  49807. ** rollback, then don't bother to play it back again.
  49808. */
  49809. if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
  49810. return rc;
  49811. }
  49812. /* When playing back page 1, restore the nReserve setting
  49813. */
  49814. if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
  49815. pPager->nReserve = ((u8*)aData)[20];
  49816. pagerReportSize(pPager);
  49817. }
  49818. /* If the pager is in CACHEMOD state, then there must be a copy of this
  49819. ** page in the pager cache. In this case just update the pager cache,
  49820. ** not the database file. The page is left marked dirty in this case.
  49821. **
  49822. ** An exception to the above rule: If the database is in no-sync mode
  49823. ** and a page is moved during an incremental vacuum then the page may
  49824. ** not be in the pager cache. Later: if a malloc() or IO error occurs
  49825. ** during a Movepage() call, then the page may not be in the cache
  49826. ** either. So the condition described in the above paragraph is not
  49827. ** assert()able.
  49828. **
  49829. ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
  49830. ** pager cache if it exists and the main file. The page is then marked
  49831. ** not dirty. Since this code is only executed in PAGER_OPEN state for
  49832. ** a hot-journal rollback, it is guaranteed that the page-cache is empty
  49833. ** if the pager is in OPEN state.
  49834. **
  49835. ** Ticket #1171: The statement journal might contain page content that is
  49836. ** different from the page content at the start of the transaction.
  49837. ** This occurs when a page is changed prior to the start of a statement
  49838. ** then changed again within the statement. When rolling back such a
  49839. ** statement we must not write to the original database unless we know
  49840. ** for certain that original page contents are synced into the main rollback
  49841. ** journal. Otherwise, a power loss might leave modified data in the
  49842. ** database file without an entry in the rollback journal that can
  49843. ** restore the database to its original form. Two conditions must be
  49844. ** met before writing to the database files. (1) the database must be
  49845. ** locked. (2) we know that the original page content is fully synced
  49846. ** in the main journal either because the page is not in cache or else
  49847. ** the page is marked as needSync==0.
  49848. **
  49849. ** 2008-04-14: When attempting to vacuum a corrupt database file, it
  49850. ** is possible to fail a statement on a database that does not yet exist.
  49851. ** Do not attempt to write if database file has never been opened.
  49852. */
  49853. if( pagerUseWal(pPager) ){
  49854. pPg = 0;
  49855. }else{
  49856. pPg = sqlite3PagerLookup(pPager, pgno);
  49857. }
  49858. assert( pPg || !MEMDB );
  49859. assert( pPager->eState!=PAGER_OPEN || pPg==0 || pPager->tempFile );
  49860. PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
  49861. PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
  49862. (isMainJrnl?"main-journal":"sub-journal")
  49863. ));
  49864. if( isMainJrnl ){
  49865. isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
  49866. }else{
  49867. isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
  49868. }
  49869. if( isOpen(pPager->fd)
  49870. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  49871. && isSynced
  49872. ){
  49873. i64 ofst = (pgno-1)*(i64)pPager->pageSize;
  49874. testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
  49875. assert( !pagerUseWal(pPager) );
  49876. /* Write the data read from the journal back into the database file.
  49877. ** This is usually safe even for an encrypted database - as the data
  49878. ** was encrypted before it was written to the journal file. The exception
  49879. ** is if the data was just read from an in-memory sub-journal. In that
  49880. ** case it must be encrypted here before it is copied into the database
  49881. ** file. */
  49882. #ifdef SQLITE_HAS_CODEC
  49883. if( !jrnlEnc ){
  49884. CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM_BKPT, aData);
  49885. rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
  49886. CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM_BKPT);
  49887. }else
  49888. #endif
  49889. rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
  49890. if( pgno>pPager->dbFileSize ){
  49891. pPager->dbFileSize = pgno;
  49892. }
  49893. if( pPager->pBackup ){
  49894. #ifdef SQLITE_HAS_CODEC
  49895. if( jrnlEnc ){
  49896. CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM_BKPT);
  49897. sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
  49898. CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM_BKPT,aData);
  49899. }else
  49900. #endif
  49901. sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
  49902. }
  49903. }else if( !isMainJrnl && pPg==0 ){
  49904. /* If this is a rollback of a savepoint and data was not written to
  49905. ** the database and the page is not in-memory, there is a potential
  49906. ** problem. When the page is next fetched by the b-tree layer, it
  49907. ** will be read from the database file, which may or may not be
  49908. ** current.
  49909. **
  49910. ** There are a couple of different ways this can happen. All are quite
  49911. ** obscure. When running in synchronous mode, this can only happen
  49912. ** if the page is on the free-list at the start of the transaction, then
  49913. ** populated, then moved using sqlite3PagerMovepage().
  49914. **
  49915. ** The solution is to add an in-memory page to the cache containing
  49916. ** the data just read from the sub-journal. Mark the page as dirty
  49917. ** and if the pager requires a journal-sync, then mark the page as
  49918. ** requiring a journal-sync before it is written.
  49919. */
  49920. assert( isSavepnt );
  49921. assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)==0 );
  49922. pPager->doNotSpill |= SPILLFLAG_ROLLBACK;
  49923. rc = sqlite3PagerGet(pPager, pgno, &pPg, 1);
  49924. assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 );
  49925. pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK;
  49926. if( rc!=SQLITE_OK ) return rc;
  49927. sqlite3PcacheMakeDirty(pPg);
  49928. }
  49929. if( pPg ){
  49930. /* No page should ever be explicitly rolled back that is in use, except
  49931. ** for page 1 which is held in use in order to keep the lock on the
  49932. ** database active. However such a page may be rolled back as a result
  49933. ** of an internal error resulting in an automatic call to
  49934. ** sqlite3PagerRollback().
  49935. */
  49936. void *pData;
  49937. pData = pPg->pData;
  49938. memcpy(pData, (u8*)aData, pPager->pageSize);
  49939. pPager->xReiniter(pPg);
  49940. /* It used to be that sqlite3PcacheMakeClean(pPg) was called here. But
  49941. ** that call was dangerous and had no detectable benefit since the cache
  49942. ** is normally cleaned by sqlite3PcacheCleanAll() after rollback and so
  49943. ** has been removed. */
  49944. pager_set_pagehash(pPg);
  49945. /* If this was page 1, then restore the value of Pager.dbFileVers.
  49946. ** Do this before any decoding. */
  49947. if( pgno==1 ){
  49948. memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
  49949. }
  49950. /* Decode the page just read from disk */
  49951. #if SQLITE_HAS_CODEC
  49952. if( jrnlEnc ){ CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM_BKPT); }
  49953. #endif
  49954. sqlite3PcacheRelease(pPg);
  49955. }
  49956. return rc;
  49957. }
  49958. /*
  49959. ** Parameter zMaster is the name of a master journal file. A single journal
  49960. ** file that referred to the master journal file has just been rolled back.
  49961. ** This routine checks if it is possible to delete the master journal file,
  49962. ** and does so if it is.
  49963. **
  49964. ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
  49965. ** available for use within this function.
  49966. **
  49967. ** When a master journal file is created, it is populated with the names
  49968. ** of all of its child journals, one after another, formatted as utf-8
  49969. ** encoded text. The end of each child journal file is marked with a
  49970. ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
  49971. ** file for a transaction involving two databases might be:
  49972. **
  49973. ** "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
  49974. **
  49975. ** A master journal file may only be deleted once all of its child
  49976. ** journals have been rolled back.
  49977. **
  49978. ** This function reads the contents of the master-journal file into
  49979. ** memory and loops through each of the child journal names. For
  49980. ** each child journal, it checks if:
  49981. **
  49982. ** * if the child journal exists, and if so
  49983. ** * if the child journal contains a reference to master journal
  49984. ** file zMaster
  49985. **
  49986. ** If a child journal can be found that matches both of the criteria
  49987. ** above, this function returns without doing anything. Otherwise, if
  49988. ** no such child journal can be found, file zMaster is deleted from
  49989. ** the file-system using sqlite3OsDelete().
  49990. **
  49991. ** If an IO error within this function, an error code is returned. This
  49992. ** function allocates memory by calling sqlite3Malloc(). If an allocation
  49993. ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
  49994. ** occur, SQLITE_OK is returned.
  49995. **
  49996. ** TODO: This function allocates a single block of memory to load
  49997. ** the entire contents of the master journal file. This could be
  49998. ** a couple of kilobytes or so - potentially larger than the page
  49999. ** size.
  50000. */
  50001. static int pager_delmaster(Pager *pPager, const char *zMaster){
  50002. sqlite3_vfs *pVfs = pPager->pVfs;
  50003. int rc; /* Return code */
  50004. sqlite3_file *pMaster; /* Malloc'd master-journal file descriptor */
  50005. sqlite3_file *pJournal; /* Malloc'd child-journal file descriptor */
  50006. char *zMasterJournal = 0; /* Contents of master journal file */
  50007. i64 nMasterJournal; /* Size of master journal file */
  50008. char *zJournal; /* Pointer to one journal within MJ file */
  50009. char *zMasterPtr; /* Space to hold MJ filename from a journal file */
  50010. int nMasterPtr; /* Amount of space allocated to zMasterPtr[] */
  50011. /* Allocate space for both the pJournal and pMaster file descriptors.
  50012. ** If successful, open the master journal file for reading.
  50013. */
  50014. pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
  50015. pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
  50016. if( !pMaster ){
  50017. rc = SQLITE_NOMEM_BKPT;
  50018. }else{
  50019. const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
  50020. rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
  50021. }
  50022. if( rc!=SQLITE_OK ) goto delmaster_out;
  50023. /* Load the entire master journal file into space obtained from
  50024. ** sqlite3_malloc() and pointed to by zMasterJournal. Also obtain
  50025. ** sufficient space (in zMasterPtr) to hold the names of master
  50026. ** journal files extracted from regular rollback-journals.
  50027. */
  50028. rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
  50029. if( rc!=SQLITE_OK ) goto delmaster_out;
  50030. nMasterPtr = pVfs->mxPathname+1;
  50031. zMasterJournal = sqlite3Malloc(nMasterJournal + nMasterPtr + 1);
  50032. if( !zMasterJournal ){
  50033. rc = SQLITE_NOMEM_BKPT;
  50034. goto delmaster_out;
  50035. }
  50036. zMasterPtr = &zMasterJournal[nMasterJournal+1];
  50037. rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
  50038. if( rc!=SQLITE_OK ) goto delmaster_out;
  50039. zMasterJournal[nMasterJournal] = 0;
  50040. zJournal = zMasterJournal;
  50041. while( (zJournal-zMasterJournal)<nMasterJournal ){
  50042. int exists;
  50043. rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
  50044. if( rc!=SQLITE_OK ){
  50045. goto delmaster_out;
  50046. }
  50047. if( exists ){
  50048. /* One of the journals pointed to by the master journal exists.
  50049. ** Open it and check if it points at the master journal. If
  50050. ** so, return without deleting the master journal file.
  50051. */
  50052. int c;
  50053. int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
  50054. rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
  50055. if( rc!=SQLITE_OK ){
  50056. goto delmaster_out;
  50057. }
  50058. rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
  50059. sqlite3OsClose(pJournal);
  50060. if( rc!=SQLITE_OK ){
  50061. goto delmaster_out;
  50062. }
  50063. c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
  50064. if( c ){
  50065. /* We have a match. Do not delete the master journal file. */
  50066. goto delmaster_out;
  50067. }
  50068. }
  50069. zJournal += (sqlite3Strlen30(zJournal)+1);
  50070. }
  50071. sqlite3OsClose(pMaster);
  50072. rc = sqlite3OsDelete(pVfs, zMaster, 0);
  50073. delmaster_out:
  50074. sqlite3_free(zMasterJournal);
  50075. if( pMaster ){
  50076. sqlite3OsClose(pMaster);
  50077. assert( !isOpen(pJournal) );
  50078. sqlite3_free(pMaster);
  50079. }
  50080. return rc;
  50081. }
  50082. /*
  50083. ** This function is used to change the actual size of the database
  50084. ** file in the file-system. This only happens when committing a transaction,
  50085. ** or rolling back a transaction (including rolling back a hot-journal).
  50086. **
  50087. ** If the main database file is not open, or the pager is not in either
  50088. ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
  50089. ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
  50090. ** If the file on disk is currently larger than nPage pages, then use the VFS
  50091. ** xTruncate() method to truncate it.
  50092. **
  50093. ** Or, it might be the case that the file on disk is smaller than
  50094. ** nPage pages. Some operating system implementations can get confused if
  50095. ** you try to truncate a file to some size that is larger than it
  50096. ** currently is, so detect this case and write a single zero byte to
  50097. ** the end of the new file instead.
  50098. **
  50099. ** If successful, return SQLITE_OK. If an IO error occurs while modifying
  50100. ** the database file, return the error code to the caller.
  50101. */
  50102. static int pager_truncate(Pager *pPager, Pgno nPage){
  50103. int rc = SQLITE_OK;
  50104. assert( pPager->eState!=PAGER_ERROR );
  50105. assert( pPager->eState!=PAGER_READER );
  50106. if( isOpen(pPager->fd)
  50107. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  50108. ){
  50109. i64 currentSize, newSize;
  50110. int szPage = pPager->pageSize;
  50111. assert( pPager->eLock==EXCLUSIVE_LOCK );
  50112. /* TODO: Is it safe to use Pager.dbFileSize here? */
  50113. rc = sqlite3OsFileSize(pPager->fd, &currentSize);
  50114. newSize = szPage*(i64)nPage;
  50115. if( rc==SQLITE_OK && currentSize!=newSize ){
  50116. if( currentSize>newSize ){
  50117. rc = sqlite3OsTruncate(pPager->fd, newSize);
  50118. }else if( (currentSize+szPage)<=newSize ){
  50119. char *pTmp = pPager->pTmpSpace;
  50120. memset(pTmp, 0, szPage);
  50121. testcase( (newSize-szPage) == currentSize );
  50122. testcase( (newSize-szPage) > currentSize );
  50123. rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
  50124. }
  50125. if( rc==SQLITE_OK ){
  50126. pPager->dbFileSize = nPage;
  50127. }
  50128. }
  50129. }
  50130. return rc;
  50131. }
  50132. /*
  50133. ** Return a sanitized version of the sector-size of OS file pFile. The
  50134. ** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE.
  50135. */
  50136. SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){
  50137. int iRet = sqlite3OsSectorSize(pFile);
  50138. if( iRet<32 ){
  50139. iRet = 512;
  50140. }else if( iRet>MAX_SECTOR_SIZE ){
  50141. assert( MAX_SECTOR_SIZE>=512 );
  50142. iRet = MAX_SECTOR_SIZE;
  50143. }
  50144. return iRet;
  50145. }
  50146. /*
  50147. ** Set the value of the Pager.sectorSize variable for the given
  50148. ** pager based on the value returned by the xSectorSize method
  50149. ** of the open database file. The sector size will be used
  50150. ** to determine the size and alignment of journal header and
  50151. ** master journal pointers within created journal files.
  50152. **
  50153. ** For temporary files the effective sector size is always 512 bytes.
  50154. **
  50155. ** Otherwise, for non-temporary files, the effective sector size is
  50156. ** the value returned by the xSectorSize() method rounded up to 32 if
  50157. ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
  50158. ** is greater than MAX_SECTOR_SIZE.
  50159. **
  50160. ** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
  50161. ** the effective sector size to its minimum value (512). The purpose of
  50162. ** pPager->sectorSize is to define the "blast radius" of bytes that
  50163. ** might change if a crash occurs while writing to a single byte in
  50164. ** that range. But with POWERSAFE_OVERWRITE, the blast radius is zero
  50165. ** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
  50166. ** size. For backwards compatibility of the rollback journal file format,
  50167. ** we cannot reduce the effective sector size below 512.
  50168. */
  50169. static void setSectorSize(Pager *pPager){
  50170. assert( isOpen(pPager->fd) || pPager->tempFile );
  50171. if( pPager->tempFile
  50172. || (sqlite3OsDeviceCharacteristics(pPager->fd) &
  50173. SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
  50174. ){
  50175. /* Sector size doesn't matter for temporary files. Also, the file
  50176. ** may not have been opened yet, in which case the OsSectorSize()
  50177. ** call will segfault. */
  50178. pPager->sectorSize = 512;
  50179. }else{
  50180. pPager->sectorSize = sqlite3SectorSize(pPager->fd);
  50181. }
  50182. }
  50183. /*
  50184. ** Playback the journal and thus restore the database file to
  50185. ** the state it was in before we started making changes.
  50186. **
  50187. ** The journal file format is as follows:
  50188. **
  50189. ** (1) 8 byte prefix. A copy of aJournalMagic[].
  50190. ** (2) 4 byte big-endian integer which is the number of valid page records
  50191. ** in the journal. If this value is 0xffffffff, then compute the
  50192. ** number of page records from the journal size.
  50193. ** (3) 4 byte big-endian integer which is the initial value for the
  50194. ** sanity checksum.
  50195. ** (4) 4 byte integer which is the number of pages to truncate the
  50196. ** database to during a rollback.
  50197. ** (5) 4 byte big-endian integer which is the sector size. The header
  50198. ** is this many bytes in size.
  50199. ** (6) 4 byte big-endian integer which is the page size.
  50200. ** (7) zero padding out to the next sector size.
  50201. ** (8) Zero or more pages instances, each as follows:
  50202. ** + 4 byte page number.
  50203. ** + pPager->pageSize bytes of data.
  50204. ** + 4 byte checksum
  50205. **
  50206. ** When we speak of the journal header, we mean the first 7 items above.
  50207. ** Each entry in the journal is an instance of the 8th item.
  50208. **
  50209. ** Call the value from the second bullet "nRec". nRec is the number of
  50210. ** valid page entries in the journal. In most cases, you can compute the
  50211. ** value of nRec from the size of the journal file. But if a power
  50212. ** failure occurred while the journal was being written, it could be the
  50213. ** case that the size of the journal file had already been increased but
  50214. ** the extra entries had not yet made it safely to disk. In such a case,
  50215. ** the value of nRec computed from the file size would be too large. For
  50216. ** that reason, we always use the nRec value in the header.
  50217. **
  50218. ** If the nRec value is 0xffffffff it means that nRec should be computed
  50219. ** from the file size. This value is used when the user selects the
  50220. ** no-sync option for the journal. A power failure could lead to corruption
  50221. ** in this case. But for things like temporary table (which will be
  50222. ** deleted when the power is restored) we don't care.
  50223. **
  50224. ** If the file opened as the journal file is not a well-formed
  50225. ** journal file then all pages up to the first corrupted page are rolled
  50226. ** back (or no pages if the journal header is corrupted). The journal file
  50227. ** is then deleted and SQLITE_OK returned, just as if no corruption had
  50228. ** been encountered.
  50229. **
  50230. ** If an I/O or malloc() error occurs, the journal-file is not deleted
  50231. ** and an error code is returned.
  50232. **
  50233. ** The isHot parameter indicates that we are trying to rollback a journal
  50234. ** that might be a hot journal. Or, it could be that the journal is
  50235. ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
  50236. ** If the journal really is hot, reset the pager cache prior rolling
  50237. ** back any content. If the journal is merely persistent, no reset is
  50238. ** needed.
  50239. */
  50240. static int pager_playback(Pager *pPager, int isHot){
  50241. sqlite3_vfs *pVfs = pPager->pVfs;
  50242. i64 szJ; /* Size of the journal file in bytes */
  50243. u32 nRec; /* Number of Records in the journal */
  50244. u32 u; /* Unsigned loop counter */
  50245. Pgno mxPg = 0; /* Size of the original file in pages */
  50246. int rc; /* Result code of a subroutine */
  50247. int res = 1; /* Value returned by sqlite3OsAccess() */
  50248. char *zMaster = 0; /* Name of master journal file if any */
  50249. int needPagerReset; /* True to reset page prior to first page rollback */
  50250. int nPlayback = 0; /* Total number of pages restored from journal */
  50251. u32 savedPageSize = pPager->pageSize;
  50252. /* Figure out how many records are in the journal. Abort early if
  50253. ** the journal is empty.
  50254. */
  50255. assert( isOpen(pPager->jfd) );
  50256. rc = sqlite3OsFileSize(pPager->jfd, &szJ);
  50257. if( rc!=SQLITE_OK ){
  50258. goto end_playback;
  50259. }
  50260. /* Read the master journal name from the journal, if it is present.
  50261. ** If a master journal file name is specified, but the file is not
  50262. ** present on disk, then the journal is not hot and does not need to be
  50263. ** played back.
  50264. **
  50265. ** TODO: Technically the following is an error because it assumes that
  50266. ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
  50267. ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
  50268. ** mxPathname is 512, which is the same as the minimum allowable value
  50269. ** for pageSize.
  50270. */
  50271. zMaster = pPager->pTmpSpace;
  50272. rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
  50273. if( rc==SQLITE_OK && zMaster[0] ){
  50274. rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
  50275. }
  50276. zMaster = 0;
  50277. if( rc!=SQLITE_OK || !res ){
  50278. goto end_playback;
  50279. }
  50280. pPager->journalOff = 0;
  50281. needPagerReset = isHot;
  50282. /* This loop terminates either when a readJournalHdr() or
  50283. ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
  50284. ** occurs.
  50285. */
  50286. while( 1 ){
  50287. /* Read the next journal header from the journal file. If there are
  50288. ** not enough bytes left in the journal file for a complete header, or
  50289. ** it is corrupted, then a process must have failed while writing it.
  50290. ** This indicates nothing more needs to be rolled back.
  50291. */
  50292. rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
  50293. if( rc!=SQLITE_OK ){
  50294. if( rc==SQLITE_DONE ){
  50295. rc = SQLITE_OK;
  50296. }
  50297. goto end_playback;
  50298. }
  50299. /* If nRec is 0xffffffff, then this journal was created by a process
  50300. ** working in no-sync mode. This means that the rest of the journal
  50301. ** file consists of pages, there are no more journal headers. Compute
  50302. ** the value of nRec based on this assumption.
  50303. */
  50304. if( nRec==0xffffffff ){
  50305. assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
  50306. nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
  50307. }
  50308. /* If nRec is 0 and this rollback is of a transaction created by this
  50309. ** process and if this is the final header in the journal, then it means
  50310. ** that this part of the journal was being filled but has not yet been
  50311. ** synced to disk. Compute the number of pages based on the remaining
  50312. ** size of the file.
  50313. **
  50314. ** The third term of the test was added to fix ticket #2565.
  50315. ** When rolling back a hot journal, nRec==0 always means that the next
  50316. ** chunk of the journal contains zero pages to be rolled back. But
  50317. ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
  50318. ** the journal, it means that the journal might contain additional
  50319. ** pages that need to be rolled back and that the number of pages
  50320. ** should be computed based on the journal file size.
  50321. */
  50322. if( nRec==0 && !isHot &&
  50323. pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
  50324. nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
  50325. }
  50326. /* If this is the first header read from the journal, truncate the
  50327. ** database file back to its original size.
  50328. */
  50329. if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
  50330. rc = pager_truncate(pPager, mxPg);
  50331. if( rc!=SQLITE_OK ){
  50332. goto end_playback;
  50333. }
  50334. pPager->dbSize = mxPg;
  50335. }
  50336. /* Copy original pages out of the journal and back into the
  50337. ** database file and/or page cache.
  50338. */
  50339. for(u=0; u<nRec; u++){
  50340. if( needPagerReset ){
  50341. pager_reset(pPager);
  50342. needPagerReset = 0;
  50343. }
  50344. rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
  50345. if( rc==SQLITE_OK ){
  50346. nPlayback++;
  50347. }else{
  50348. if( rc==SQLITE_DONE ){
  50349. pPager->journalOff = szJ;
  50350. break;
  50351. }else if( rc==SQLITE_IOERR_SHORT_READ ){
  50352. /* If the journal has been truncated, simply stop reading and
  50353. ** processing the journal. This might happen if the journal was
  50354. ** not completely written and synced prior to a crash. In that
  50355. ** case, the database should have never been written in the
  50356. ** first place so it is OK to simply abandon the rollback. */
  50357. rc = SQLITE_OK;
  50358. goto end_playback;
  50359. }else{
  50360. /* If we are unable to rollback, quit and return the error
  50361. ** code. This will cause the pager to enter the error state
  50362. ** so that no further harm will be done. Perhaps the next
  50363. ** process to come along will be able to rollback the database.
  50364. */
  50365. goto end_playback;
  50366. }
  50367. }
  50368. }
  50369. }
  50370. /*NOTREACHED*/
  50371. assert( 0 );
  50372. end_playback:
  50373. if( rc==SQLITE_OK ){
  50374. rc = sqlite3PagerSetPagesize(pPager, &savedPageSize, -1);
  50375. }
  50376. /* Following a rollback, the database file should be back in its original
  50377. ** state prior to the start of the transaction, so invoke the
  50378. ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
  50379. ** assertion that the transaction counter was modified.
  50380. */
  50381. #ifdef SQLITE_DEBUG
  50382. sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
  50383. #endif
  50384. /* If this playback is happening automatically as a result of an IO or
  50385. ** malloc error that occurred after the change-counter was updated but
  50386. ** before the transaction was committed, then the change-counter
  50387. ** modification may just have been reverted. If this happens in exclusive
  50388. ** mode, then subsequent transactions performed by the connection will not
  50389. ** update the change-counter at all. This may lead to cache inconsistency
  50390. ** problems for other processes at some point in the future. So, just
  50391. ** in case this has happened, clear the changeCountDone flag now.
  50392. */
  50393. pPager->changeCountDone = pPager->tempFile;
  50394. if( rc==SQLITE_OK ){
  50395. zMaster = pPager->pTmpSpace;
  50396. rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
  50397. testcase( rc!=SQLITE_OK );
  50398. }
  50399. if( rc==SQLITE_OK
  50400. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  50401. ){
  50402. rc = sqlite3PagerSync(pPager, 0);
  50403. }
  50404. if( rc==SQLITE_OK ){
  50405. rc = pager_end_transaction(pPager, zMaster[0]!='\0', 0);
  50406. testcase( rc!=SQLITE_OK );
  50407. }
  50408. if( rc==SQLITE_OK && zMaster[0] && res ){
  50409. /* If there was a master journal and this routine will return success,
  50410. ** see if it is possible to delete the master journal.
  50411. */
  50412. rc = pager_delmaster(pPager, zMaster);
  50413. testcase( rc!=SQLITE_OK );
  50414. }
  50415. if( isHot && nPlayback ){
  50416. sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s",
  50417. nPlayback, pPager->zJournal);
  50418. }
  50419. /* The Pager.sectorSize variable may have been updated while rolling
  50420. ** back a journal created by a process with a different sector size
  50421. ** value. Reset it to the correct value for this process.
  50422. */
  50423. setSectorSize(pPager);
  50424. return rc;
  50425. }
  50426. /*
  50427. ** Read the content for page pPg out of the database file (or out of
  50428. ** the WAL if that is where the most recent copy if found) into
  50429. ** pPg->pData. A shared lock or greater must be held on the database
  50430. ** file before this function is called.
  50431. **
  50432. ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
  50433. ** the value read from the database file.
  50434. **
  50435. ** If an IO error occurs, then the IO error is returned to the caller.
  50436. ** Otherwise, SQLITE_OK is returned.
  50437. */
  50438. static int readDbPage(PgHdr *pPg){
  50439. Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
  50440. int rc = SQLITE_OK; /* Return code */
  50441. #ifndef SQLITE_OMIT_WAL
  50442. u32 iFrame = 0; /* Frame of WAL containing pgno */
  50443. assert( pPager->eState>=PAGER_READER && !MEMDB );
  50444. assert( isOpen(pPager->fd) );
  50445. if( pagerUseWal(pPager) ){
  50446. rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame);
  50447. if( rc ) return rc;
  50448. }
  50449. if( iFrame ){
  50450. rc = sqlite3WalReadFrame(pPager->pWal, iFrame,pPager->pageSize,pPg->pData);
  50451. }else
  50452. #endif
  50453. {
  50454. i64 iOffset = (pPg->pgno-1)*(i64)pPager->pageSize;
  50455. rc = sqlite3OsRead(pPager->fd, pPg->pData, pPager->pageSize, iOffset);
  50456. if( rc==SQLITE_IOERR_SHORT_READ ){
  50457. rc = SQLITE_OK;
  50458. }
  50459. }
  50460. if( pPg->pgno==1 ){
  50461. if( rc ){
  50462. /* If the read is unsuccessful, set the dbFileVers[] to something
  50463. ** that will never be a valid file version. dbFileVers[] is a copy
  50464. ** of bytes 24..39 of the database. Bytes 28..31 should always be
  50465. ** zero or the size of the database in page. Bytes 32..35 and 35..39
  50466. ** should be page numbers which are never 0xffffffff. So filling
  50467. ** pPager->dbFileVers[] with all 0xff bytes should suffice.
  50468. **
  50469. ** For an encrypted database, the situation is more complex: bytes
  50470. ** 24..39 of the database are white noise. But the probability of
  50471. ** white noise equaling 16 bytes of 0xff is vanishingly small so
  50472. ** we should still be ok.
  50473. */
  50474. memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
  50475. }else{
  50476. u8 *dbFileVers = &((u8*)pPg->pData)[24];
  50477. memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
  50478. }
  50479. }
  50480. CODEC1(pPager, pPg->pData, pPg->pgno, 3, rc = SQLITE_NOMEM_BKPT);
  50481. PAGER_INCR(sqlite3_pager_readdb_count);
  50482. PAGER_INCR(pPager->nRead);
  50483. IOTRACE(("PGIN %p %d\n", pPager, pPg->pgno));
  50484. PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
  50485. PAGERID(pPager), pPg->pgno, pager_pagehash(pPg)));
  50486. return rc;
  50487. }
  50488. /*
  50489. ** Update the value of the change-counter at offsets 24 and 92 in
  50490. ** the header and the sqlite version number at offset 96.
  50491. **
  50492. ** This is an unconditional update. See also the pager_incr_changecounter()
  50493. ** routine which only updates the change-counter if the update is actually
  50494. ** needed, as determined by the pPager->changeCountDone state variable.
  50495. */
  50496. static void pager_write_changecounter(PgHdr *pPg){
  50497. u32 change_counter;
  50498. /* Increment the value just read and write it back to byte 24. */
  50499. change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
  50500. put32bits(((char*)pPg->pData)+24, change_counter);
  50501. /* Also store the SQLite version number in bytes 96..99 and in
  50502. ** bytes 92..95 store the change counter for which the version number
  50503. ** is valid. */
  50504. put32bits(((char*)pPg->pData)+92, change_counter);
  50505. put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
  50506. }
  50507. #ifndef SQLITE_OMIT_WAL
  50508. /*
  50509. ** This function is invoked once for each page that has already been
  50510. ** written into the log file when a WAL transaction is rolled back.
  50511. ** Parameter iPg is the page number of said page. The pCtx argument
  50512. ** is actually a pointer to the Pager structure.
  50513. **
  50514. ** If page iPg is present in the cache, and has no outstanding references,
  50515. ** it is discarded. Otherwise, if there are one or more outstanding
  50516. ** references, the page content is reloaded from the database. If the
  50517. ** attempt to reload content from the database is required and fails,
  50518. ** return an SQLite error code. Otherwise, SQLITE_OK.
  50519. */
  50520. static int pagerUndoCallback(void *pCtx, Pgno iPg){
  50521. int rc = SQLITE_OK;
  50522. Pager *pPager = (Pager *)pCtx;
  50523. PgHdr *pPg;
  50524. assert( pagerUseWal(pPager) );
  50525. pPg = sqlite3PagerLookup(pPager, iPg);
  50526. if( pPg ){
  50527. if( sqlite3PcachePageRefcount(pPg)==1 ){
  50528. sqlite3PcacheDrop(pPg);
  50529. }else{
  50530. rc = readDbPage(pPg);
  50531. if( rc==SQLITE_OK ){
  50532. pPager->xReiniter(pPg);
  50533. }
  50534. sqlite3PagerUnrefNotNull(pPg);
  50535. }
  50536. }
  50537. /* Normally, if a transaction is rolled back, any backup processes are
  50538. ** updated as data is copied out of the rollback journal and into the
  50539. ** database. This is not generally possible with a WAL database, as
  50540. ** rollback involves simply truncating the log file. Therefore, if one
  50541. ** or more frames have already been written to the log (and therefore
  50542. ** also copied into the backup databases) as part of this transaction,
  50543. ** the backups must be restarted.
  50544. */
  50545. sqlite3BackupRestart(pPager->pBackup);
  50546. return rc;
  50547. }
  50548. /*
  50549. ** This function is called to rollback a transaction on a WAL database.
  50550. */
  50551. static int pagerRollbackWal(Pager *pPager){
  50552. int rc; /* Return Code */
  50553. PgHdr *pList; /* List of dirty pages to revert */
  50554. /* For all pages in the cache that are currently dirty or have already
  50555. ** been written (but not committed) to the log file, do one of the
  50556. ** following:
  50557. **
  50558. ** + Discard the cached page (if refcount==0), or
  50559. ** + Reload page content from the database (if refcount>0).
  50560. */
  50561. pPager->dbSize = pPager->dbOrigSize;
  50562. rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
  50563. pList = sqlite3PcacheDirtyList(pPager->pPCache);
  50564. while( pList && rc==SQLITE_OK ){
  50565. PgHdr *pNext = pList->pDirty;
  50566. rc = pagerUndoCallback((void *)pPager, pList->pgno);
  50567. pList = pNext;
  50568. }
  50569. return rc;
  50570. }
  50571. /*
  50572. ** This function is a wrapper around sqlite3WalFrames(). As well as logging
  50573. ** the contents of the list of pages headed by pList (connected by pDirty),
  50574. ** this function notifies any active backup processes that the pages have
  50575. ** changed.
  50576. **
  50577. ** The list of pages passed into this routine is always sorted by page number.
  50578. ** Hence, if page 1 appears anywhere on the list, it will be the first page.
  50579. */
  50580. static int pagerWalFrames(
  50581. Pager *pPager, /* Pager object */
  50582. PgHdr *pList, /* List of frames to log */
  50583. Pgno nTruncate, /* Database size after this commit */
  50584. int isCommit /* True if this is a commit */
  50585. ){
  50586. int rc; /* Return code */
  50587. int nList; /* Number of pages in pList */
  50588. PgHdr *p; /* For looping over pages */
  50589. assert( pPager->pWal );
  50590. assert( pList );
  50591. #ifdef SQLITE_DEBUG
  50592. /* Verify that the page list is in accending order */
  50593. for(p=pList; p && p->pDirty; p=p->pDirty){
  50594. assert( p->pgno < p->pDirty->pgno );
  50595. }
  50596. #endif
  50597. assert( pList->pDirty==0 || isCommit );
  50598. if( isCommit ){
  50599. /* If a WAL transaction is being committed, there is no point in writing
  50600. ** any pages with page numbers greater than nTruncate into the WAL file.
  50601. ** They will never be read by any client. So remove them from the pDirty
  50602. ** list here. */
  50603. PgHdr **ppNext = &pList;
  50604. nList = 0;
  50605. for(p=pList; (*ppNext = p)!=0; p=p->pDirty){
  50606. if( p->pgno<=nTruncate ){
  50607. ppNext = &p->pDirty;
  50608. nList++;
  50609. }
  50610. }
  50611. assert( pList );
  50612. }else{
  50613. nList = 1;
  50614. }
  50615. pPager->aStat[PAGER_STAT_WRITE] += nList;
  50616. if( pList->pgno==1 ) pager_write_changecounter(pList);
  50617. rc = sqlite3WalFrames(pPager->pWal,
  50618. pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
  50619. );
  50620. if( rc==SQLITE_OK && pPager->pBackup ){
  50621. for(p=pList; p; p=p->pDirty){
  50622. sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
  50623. }
  50624. }
  50625. #ifdef SQLITE_CHECK_PAGES
  50626. pList = sqlite3PcacheDirtyList(pPager->pPCache);
  50627. for(p=pList; p; p=p->pDirty){
  50628. pager_set_pagehash(p);
  50629. }
  50630. #endif
  50631. return rc;
  50632. }
  50633. /*
  50634. ** Begin a read transaction on the WAL.
  50635. **
  50636. ** This routine used to be called "pagerOpenSnapshot()" because it essentially
  50637. ** makes a snapshot of the database at the current point in time and preserves
  50638. ** that snapshot for use by the reader in spite of concurrently changes by
  50639. ** other writers or checkpointers.
  50640. */
  50641. static int pagerBeginReadTransaction(Pager *pPager){
  50642. int rc; /* Return code */
  50643. int changed = 0; /* True if cache must be reset */
  50644. assert( pagerUseWal(pPager) );
  50645. assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
  50646. /* sqlite3WalEndReadTransaction() was not called for the previous
  50647. ** transaction in locking_mode=EXCLUSIVE. So call it now. If we
  50648. ** are in locking_mode=NORMAL and EndRead() was previously called,
  50649. ** the duplicate call is harmless.
  50650. */
  50651. sqlite3WalEndReadTransaction(pPager->pWal);
  50652. rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
  50653. if( rc!=SQLITE_OK || changed ){
  50654. pager_reset(pPager);
  50655. if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
  50656. }
  50657. return rc;
  50658. }
  50659. #endif
  50660. /*
  50661. ** This function is called as part of the transition from PAGER_OPEN
  50662. ** to PAGER_READER state to determine the size of the database file
  50663. ** in pages (assuming the page size currently stored in Pager.pageSize).
  50664. **
  50665. ** If no error occurs, SQLITE_OK is returned and the size of the database
  50666. ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
  50667. ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
  50668. */
  50669. static int pagerPagecount(Pager *pPager, Pgno *pnPage){
  50670. Pgno nPage; /* Value to return via *pnPage */
  50671. /* Query the WAL sub-system for the database size. The WalDbsize()
  50672. ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
  50673. ** if the database size is not available. The database size is not
  50674. ** available from the WAL sub-system if the log file is empty or
  50675. ** contains no valid committed transactions.
  50676. */
  50677. assert( pPager->eState==PAGER_OPEN );
  50678. assert( pPager->eLock>=SHARED_LOCK );
  50679. assert( isOpen(pPager->fd) );
  50680. assert( pPager->tempFile==0 );
  50681. nPage = sqlite3WalDbsize(pPager->pWal);
  50682. /* If the number of pages in the database is not available from the
  50683. ** WAL sub-system, determine the page count based on the size of
  50684. ** the database file. If the size of the database file is not an
  50685. ** integer multiple of the page-size, round up the result.
  50686. */
  50687. if( nPage==0 && ALWAYS(isOpen(pPager->fd)) ){
  50688. i64 n = 0; /* Size of db file in bytes */
  50689. int rc = sqlite3OsFileSize(pPager->fd, &n);
  50690. if( rc!=SQLITE_OK ){
  50691. return rc;
  50692. }
  50693. nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
  50694. }
  50695. /* If the current number of pages in the file is greater than the
  50696. ** configured maximum pager number, increase the allowed limit so
  50697. ** that the file can be read.
  50698. */
  50699. if( nPage>pPager->mxPgno ){
  50700. pPager->mxPgno = (Pgno)nPage;
  50701. }
  50702. *pnPage = nPage;
  50703. return SQLITE_OK;
  50704. }
  50705. #ifndef SQLITE_OMIT_WAL
  50706. /*
  50707. ** Check if the *-wal file that corresponds to the database opened by pPager
  50708. ** exists if the database is not empy, or verify that the *-wal file does
  50709. ** not exist (by deleting it) if the database file is empty.
  50710. **
  50711. ** If the database is not empty and the *-wal file exists, open the pager
  50712. ** in WAL mode. If the database is empty or if no *-wal file exists and
  50713. ** if no error occurs, make sure Pager.journalMode is not set to
  50714. ** PAGER_JOURNALMODE_WAL.
  50715. **
  50716. ** Return SQLITE_OK or an error code.
  50717. **
  50718. ** The caller must hold a SHARED lock on the database file to call this
  50719. ** function. Because an EXCLUSIVE lock on the db file is required to delete
  50720. ** a WAL on a none-empty database, this ensures there is no race condition
  50721. ** between the xAccess() below and an xDelete() being executed by some
  50722. ** other connection.
  50723. */
  50724. static int pagerOpenWalIfPresent(Pager *pPager){
  50725. int rc = SQLITE_OK;
  50726. assert( pPager->eState==PAGER_OPEN );
  50727. assert( pPager->eLock>=SHARED_LOCK );
  50728. if( !pPager->tempFile ){
  50729. int isWal; /* True if WAL file exists */
  50730. rc = sqlite3OsAccess(
  50731. pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
  50732. );
  50733. if( rc==SQLITE_OK ){
  50734. if( isWal ){
  50735. Pgno nPage; /* Size of the database file */
  50736. rc = pagerPagecount(pPager, &nPage);
  50737. if( rc ) return rc;
  50738. if( nPage==0 ){
  50739. rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
  50740. }else{
  50741. testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
  50742. rc = sqlite3PagerOpenWal(pPager, 0);
  50743. }
  50744. }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
  50745. pPager->journalMode = PAGER_JOURNALMODE_DELETE;
  50746. }
  50747. }
  50748. }
  50749. return rc;
  50750. }
  50751. #endif
  50752. /*
  50753. ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
  50754. ** the entire master journal file. The case pSavepoint==NULL occurs when
  50755. ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
  50756. ** savepoint.
  50757. **
  50758. ** When pSavepoint is not NULL (meaning a non-transaction savepoint is
  50759. ** being rolled back), then the rollback consists of up to three stages,
  50760. ** performed in the order specified:
  50761. **
  50762. ** * Pages are played back from the main journal starting at byte
  50763. ** offset PagerSavepoint.iOffset and continuing to
  50764. ** PagerSavepoint.iHdrOffset, or to the end of the main journal
  50765. ** file if PagerSavepoint.iHdrOffset is zero.
  50766. **
  50767. ** * If PagerSavepoint.iHdrOffset is not zero, then pages are played
  50768. ** back starting from the journal header immediately following
  50769. ** PagerSavepoint.iHdrOffset to the end of the main journal file.
  50770. **
  50771. ** * Pages are then played back from the sub-journal file, starting
  50772. ** with the PagerSavepoint.iSubRec and continuing to the end of
  50773. ** the journal file.
  50774. **
  50775. ** Throughout the rollback process, each time a page is rolled back, the
  50776. ** corresponding bit is set in a bitvec structure (variable pDone in the
  50777. ** implementation below). This is used to ensure that a page is only
  50778. ** rolled back the first time it is encountered in either journal.
  50779. **
  50780. ** If pSavepoint is NULL, then pages are only played back from the main
  50781. ** journal file. There is no need for a bitvec in this case.
  50782. **
  50783. ** In either case, before playback commences the Pager.dbSize variable
  50784. ** is reset to the value that it held at the start of the savepoint
  50785. ** (or transaction). No page with a page-number greater than this value
  50786. ** is played back. If one is encountered it is simply skipped.
  50787. */
  50788. static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
  50789. i64 szJ; /* Effective size of the main journal */
  50790. i64 iHdrOff; /* End of first segment of main-journal records */
  50791. int rc = SQLITE_OK; /* Return code */
  50792. Bitvec *pDone = 0; /* Bitvec to ensure pages played back only once */
  50793. assert( pPager->eState!=PAGER_ERROR );
  50794. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  50795. /* Allocate a bitvec to use to store the set of pages rolled back */
  50796. if( pSavepoint ){
  50797. pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
  50798. if( !pDone ){
  50799. return SQLITE_NOMEM_BKPT;
  50800. }
  50801. }
  50802. /* Set the database size back to the value it was before the savepoint
  50803. ** being reverted was opened.
  50804. */
  50805. pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
  50806. pPager->changeCountDone = pPager->tempFile;
  50807. if( !pSavepoint && pagerUseWal(pPager) ){
  50808. return pagerRollbackWal(pPager);
  50809. }
  50810. /* Use pPager->journalOff as the effective size of the main rollback
  50811. ** journal. The actual file might be larger than this in
  50812. ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST. But anything
  50813. ** past pPager->journalOff is off-limits to us.
  50814. */
  50815. szJ = pPager->journalOff;
  50816. assert( pagerUseWal(pPager)==0 || szJ==0 );
  50817. /* Begin by rolling back records from the main journal starting at
  50818. ** PagerSavepoint.iOffset and continuing to the next journal header.
  50819. ** There might be records in the main journal that have a page number
  50820. ** greater than the current database size (pPager->dbSize) but those
  50821. ** will be skipped automatically. Pages are added to pDone as they
  50822. ** are played back.
  50823. */
  50824. if( pSavepoint && !pagerUseWal(pPager) ){
  50825. iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
  50826. pPager->journalOff = pSavepoint->iOffset;
  50827. while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
  50828. rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
  50829. }
  50830. assert( rc!=SQLITE_DONE );
  50831. }else{
  50832. pPager->journalOff = 0;
  50833. }
  50834. /* Continue rolling back records out of the main journal starting at
  50835. ** the first journal header seen and continuing until the effective end
  50836. ** of the main journal file. Continue to skip out-of-range pages and
  50837. ** continue adding pages rolled back to pDone.
  50838. */
  50839. while( rc==SQLITE_OK && pPager->journalOff<szJ ){
  50840. u32 ii; /* Loop counter */
  50841. u32 nJRec = 0; /* Number of Journal Records */
  50842. u32 dummy;
  50843. rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
  50844. assert( rc!=SQLITE_DONE );
  50845. /*
  50846. ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
  50847. ** test is related to ticket #2565. See the discussion in the
  50848. ** pager_playback() function for additional information.
  50849. */
  50850. if( nJRec==0
  50851. && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
  50852. ){
  50853. nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
  50854. }
  50855. for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
  50856. rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
  50857. }
  50858. assert( rc!=SQLITE_DONE );
  50859. }
  50860. assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
  50861. /* Finally, rollback pages from the sub-journal. Page that were
  50862. ** previously rolled back out of the main journal (and are hence in pDone)
  50863. ** will be skipped. Out-of-range pages are also skipped.
  50864. */
  50865. if( pSavepoint ){
  50866. u32 ii; /* Loop counter */
  50867. i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
  50868. if( pagerUseWal(pPager) ){
  50869. rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
  50870. }
  50871. for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
  50872. assert( offset==(i64)ii*(4+pPager->pageSize) );
  50873. rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
  50874. }
  50875. assert( rc!=SQLITE_DONE );
  50876. }
  50877. sqlite3BitvecDestroy(pDone);
  50878. if( rc==SQLITE_OK ){
  50879. pPager->journalOff = szJ;
  50880. }
  50881. return rc;
  50882. }
  50883. /*
  50884. ** Change the maximum number of in-memory pages that are allowed
  50885. ** before attempting to recycle clean and unused pages.
  50886. */
  50887. SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
  50888. sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
  50889. }
  50890. /*
  50891. ** Change the maximum number of in-memory pages that are allowed
  50892. ** before attempting to spill pages to journal.
  50893. */
  50894. SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager *pPager, int mxPage){
  50895. return sqlite3PcacheSetSpillsize(pPager->pPCache, mxPage);
  50896. }
  50897. /*
  50898. ** Invoke SQLITE_FCNTL_MMAP_SIZE based on the current value of szMmap.
  50899. */
  50900. static void pagerFixMaplimit(Pager *pPager){
  50901. #if SQLITE_MAX_MMAP_SIZE>0
  50902. sqlite3_file *fd = pPager->fd;
  50903. if( isOpen(fd) && fd->pMethods->iVersion>=3 ){
  50904. sqlite3_int64 sz;
  50905. sz = pPager->szMmap;
  50906. pPager->bUseFetch = (sz>0);
  50907. setGetterMethod(pPager);
  50908. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_MMAP_SIZE, &sz);
  50909. }
  50910. #endif
  50911. }
  50912. /*
  50913. ** Change the maximum size of any memory mapping made of the database file.
  50914. */
  50915. SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *pPager, sqlite3_int64 szMmap){
  50916. pPager->szMmap = szMmap;
  50917. pagerFixMaplimit(pPager);
  50918. }
  50919. /*
  50920. ** Free as much memory as possible from the pager.
  50921. */
  50922. SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){
  50923. sqlite3PcacheShrink(pPager->pPCache);
  50924. }
  50925. /*
  50926. ** Adjust settings of the pager to those specified in the pgFlags parameter.
  50927. **
  50928. ** The "level" in pgFlags & PAGER_SYNCHRONOUS_MASK sets the robustness
  50929. ** of the database to damage due to OS crashes or power failures by
  50930. ** changing the number of syncs()s when writing the journals.
  50931. ** There are four levels:
  50932. **
  50933. ** OFF sqlite3OsSync() is never called. This is the default
  50934. ** for temporary and transient files.
  50935. **
  50936. ** NORMAL The journal is synced once before writes begin on the
  50937. ** database. This is normally adequate protection, but
  50938. ** it is theoretically possible, though very unlikely,
  50939. ** that an inopertune power failure could leave the journal
  50940. ** in a state which would cause damage to the database
  50941. ** when it is rolled back.
  50942. **
  50943. ** FULL The journal is synced twice before writes begin on the
  50944. ** database (with some additional information - the nRec field
  50945. ** of the journal header - being written in between the two
  50946. ** syncs). If we assume that writing a
  50947. ** single disk sector is atomic, then this mode provides
  50948. ** assurance that the journal will not be corrupted to the
  50949. ** point of causing damage to the database during rollback.
  50950. **
  50951. ** EXTRA This is like FULL except that is also syncs the directory
  50952. ** that contains the rollback journal after the rollback
  50953. ** journal is unlinked.
  50954. **
  50955. ** The above is for a rollback-journal mode. For WAL mode, OFF continues
  50956. ** to mean that no syncs ever occur. NORMAL means that the WAL is synced
  50957. ** prior to the start of checkpoint and that the database file is synced
  50958. ** at the conclusion of the checkpoint if the entire content of the WAL
  50959. ** was written back into the database. But no sync operations occur for
  50960. ** an ordinary commit in NORMAL mode with WAL. FULL means that the WAL
  50961. ** file is synced following each commit operation, in addition to the
  50962. ** syncs associated with NORMAL. There is no difference between FULL
  50963. ** and EXTRA for WAL mode.
  50964. **
  50965. ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL. The
  50966. ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
  50967. ** using fcntl(F_FULLFSYNC). SQLITE_SYNC_NORMAL means to do an
  50968. ** ordinary fsync() call. There is no difference between SQLITE_SYNC_FULL
  50969. ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX. But the
  50970. ** synchronous=FULL versus synchronous=NORMAL setting determines when
  50971. ** the xSync primitive is called and is relevant to all platforms.
  50972. **
  50973. ** Numeric values associated with these states are OFF==1, NORMAL=2,
  50974. ** and FULL=3.
  50975. */
  50976. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  50977. SQLITE_PRIVATE void sqlite3PagerSetFlags(
  50978. Pager *pPager, /* The pager to set safety level for */
  50979. unsigned pgFlags /* Various flags */
  50980. ){
  50981. unsigned level = pgFlags & PAGER_SYNCHRONOUS_MASK;
  50982. if( pPager->tempFile ){
  50983. pPager->noSync = 1;
  50984. pPager->fullSync = 0;
  50985. pPager->extraSync = 0;
  50986. }else{
  50987. pPager->noSync = level==PAGER_SYNCHRONOUS_OFF ?1:0;
  50988. pPager->fullSync = level>=PAGER_SYNCHRONOUS_FULL ?1:0;
  50989. pPager->extraSync = level==PAGER_SYNCHRONOUS_EXTRA ?1:0;
  50990. }
  50991. if( pPager->noSync ){
  50992. pPager->syncFlags = 0;
  50993. }else if( pgFlags & PAGER_FULLFSYNC ){
  50994. pPager->syncFlags = SQLITE_SYNC_FULL;
  50995. }else{
  50996. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  50997. }
  50998. pPager->walSyncFlags = (pPager->syncFlags<<2);
  50999. if( pPager->fullSync ){
  51000. pPager->walSyncFlags |= pPager->syncFlags;
  51001. }
  51002. if( (pgFlags & PAGER_CKPT_FULLFSYNC) && !pPager->noSync ){
  51003. pPager->walSyncFlags |= (SQLITE_SYNC_FULL<<2);
  51004. }
  51005. if( pgFlags & PAGER_CACHESPILL ){
  51006. pPager->doNotSpill &= ~SPILLFLAG_OFF;
  51007. }else{
  51008. pPager->doNotSpill |= SPILLFLAG_OFF;
  51009. }
  51010. }
  51011. #endif
  51012. /*
  51013. ** The following global variable is incremented whenever the library
  51014. ** attempts to open a temporary file. This information is used for
  51015. ** testing and analysis only.
  51016. */
  51017. #ifdef SQLITE_TEST
  51018. SQLITE_API int sqlite3_opentemp_count = 0;
  51019. #endif
  51020. /*
  51021. ** Open a temporary file.
  51022. **
  51023. ** Write the file descriptor into *pFile. Return SQLITE_OK on success
  51024. ** or some other error code if we fail. The OS will automatically
  51025. ** delete the temporary file when it is closed.
  51026. **
  51027. ** The flags passed to the VFS layer xOpen() call are those specified
  51028. ** by parameter vfsFlags ORed with the following:
  51029. **
  51030. ** SQLITE_OPEN_READWRITE
  51031. ** SQLITE_OPEN_CREATE
  51032. ** SQLITE_OPEN_EXCLUSIVE
  51033. ** SQLITE_OPEN_DELETEONCLOSE
  51034. */
  51035. static int pagerOpentemp(
  51036. Pager *pPager, /* The pager object */
  51037. sqlite3_file *pFile, /* Write the file descriptor here */
  51038. int vfsFlags /* Flags passed through to the VFS */
  51039. ){
  51040. int rc; /* Return code */
  51041. #ifdef SQLITE_TEST
  51042. sqlite3_opentemp_count++; /* Used for testing and analysis only */
  51043. #endif
  51044. vfsFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  51045. SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
  51046. rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
  51047. assert( rc!=SQLITE_OK || isOpen(pFile) );
  51048. return rc;
  51049. }
  51050. /*
  51051. ** Set the busy handler function.
  51052. **
  51053. ** The pager invokes the busy-handler if sqlite3OsLock() returns
  51054. ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
  51055. ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
  51056. ** lock. It does *not* invoke the busy handler when upgrading from
  51057. ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
  51058. ** (which occurs during hot-journal rollback). Summary:
  51059. **
  51060. ** Transition | Invokes xBusyHandler
  51061. ** --------------------------------------------------------
  51062. ** NO_LOCK -> SHARED_LOCK | Yes
  51063. ** SHARED_LOCK -> RESERVED_LOCK | No
  51064. ** SHARED_LOCK -> EXCLUSIVE_LOCK | No
  51065. ** RESERVED_LOCK -> EXCLUSIVE_LOCK | Yes
  51066. **
  51067. ** If the busy-handler callback returns non-zero, the lock is
  51068. ** retried. If it returns zero, then the SQLITE_BUSY error is
  51069. ** returned to the caller of the pager API function.
  51070. */
  51071. SQLITE_PRIVATE void sqlite3PagerSetBusyHandler(
  51072. Pager *pPager, /* Pager object */
  51073. int (*xBusyHandler)(void *), /* Pointer to busy-handler function */
  51074. void *pBusyHandlerArg /* Argument to pass to xBusyHandler */
  51075. ){
  51076. void **ap;
  51077. pPager->xBusyHandler = xBusyHandler;
  51078. pPager->pBusyHandlerArg = pBusyHandlerArg;
  51079. ap = (void **)&pPager->xBusyHandler;
  51080. assert( ((int(*)(void *))(ap[0]))==xBusyHandler );
  51081. assert( ap[1]==pBusyHandlerArg );
  51082. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap);
  51083. }
  51084. /*
  51085. ** Change the page size used by the Pager object. The new page size
  51086. ** is passed in *pPageSize.
  51087. **
  51088. ** If the pager is in the error state when this function is called, it
  51089. ** is a no-op. The value returned is the error state error code (i.e.
  51090. ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
  51091. **
  51092. ** Otherwise, if all of the following are true:
  51093. **
  51094. ** * the new page size (value of *pPageSize) is valid (a power
  51095. ** of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
  51096. **
  51097. ** * there are no outstanding page references, and
  51098. **
  51099. ** * the database is either not an in-memory database or it is
  51100. ** an in-memory database that currently consists of zero pages.
  51101. **
  51102. ** then the pager object page size is set to *pPageSize.
  51103. **
  51104. ** If the page size is changed, then this function uses sqlite3PagerMalloc()
  51105. ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
  51106. ** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
  51107. ** In all other cases, SQLITE_OK is returned.
  51108. **
  51109. ** If the page size is not changed, either because one of the enumerated
  51110. ** conditions above is not true, the pager was in error state when this
  51111. ** function was called, or because the memory allocation attempt failed,
  51112. ** then *pPageSize is set to the old, retained page size before returning.
  51113. */
  51114. SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
  51115. int rc = SQLITE_OK;
  51116. /* It is not possible to do a full assert_pager_state() here, as this
  51117. ** function may be called from within PagerOpen(), before the state
  51118. ** of the Pager object is internally consistent.
  51119. **
  51120. ** At one point this function returned an error if the pager was in
  51121. ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
  51122. ** there is at least one outstanding page reference, this function
  51123. ** is a no-op for that case anyhow.
  51124. */
  51125. u32 pageSize = *pPageSize;
  51126. assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
  51127. if( (pPager->memDb==0 || pPager->dbSize==0)
  51128. && sqlite3PcacheRefCount(pPager->pPCache)==0
  51129. && pageSize && pageSize!=(u32)pPager->pageSize
  51130. ){
  51131. char *pNew = NULL; /* New temp space */
  51132. i64 nByte = 0;
  51133. if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
  51134. rc = sqlite3OsFileSize(pPager->fd, &nByte);
  51135. }
  51136. if( rc==SQLITE_OK ){
  51137. /* 8 bytes of zeroed overrun space is sufficient so that the b-tree
  51138. * cell header parser will never run off the end of the allocation */
  51139. pNew = (char *)sqlite3PageMalloc(pageSize+8);
  51140. if( !pNew ){
  51141. rc = SQLITE_NOMEM_BKPT;
  51142. }else{
  51143. memset(pNew+pageSize, 0, 8);
  51144. }
  51145. }
  51146. if( rc==SQLITE_OK ){
  51147. pager_reset(pPager);
  51148. rc = sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
  51149. }
  51150. if( rc==SQLITE_OK ){
  51151. sqlite3PageFree(pPager->pTmpSpace);
  51152. pPager->pTmpSpace = pNew;
  51153. pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
  51154. pPager->pageSize = pageSize;
  51155. }else{
  51156. sqlite3PageFree(pNew);
  51157. }
  51158. }
  51159. *pPageSize = pPager->pageSize;
  51160. if( rc==SQLITE_OK ){
  51161. if( nReserve<0 ) nReserve = pPager->nReserve;
  51162. assert( nReserve>=0 && nReserve<1000 );
  51163. pPager->nReserve = (i16)nReserve;
  51164. pagerReportSize(pPager);
  51165. pagerFixMaplimit(pPager);
  51166. }
  51167. return rc;
  51168. }
  51169. /*
  51170. ** Return a pointer to the "temporary page" buffer held internally
  51171. ** by the pager. This is a buffer that is big enough to hold the
  51172. ** entire content of a database page. This buffer is used internally
  51173. ** during rollback and will be overwritten whenever a rollback
  51174. ** occurs. But other modules are free to use it too, as long as
  51175. ** no rollbacks are happening.
  51176. */
  51177. SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
  51178. return pPager->pTmpSpace;
  51179. }
  51180. /*
  51181. ** Attempt to set the maximum database page count if mxPage is positive.
  51182. ** Make no changes if mxPage is zero or negative. And never reduce the
  51183. ** maximum page count below the current size of the database.
  51184. **
  51185. ** Regardless of mxPage, return the current maximum page count.
  51186. */
  51187. SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
  51188. if( mxPage>0 ){
  51189. pPager->mxPgno = mxPage;
  51190. }
  51191. assert( pPager->eState!=PAGER_OPEN ); /* Called only by OP_MaxPgcnt */
  51192. /* assert( pPager->mxPgno>=pPager->dbSize ); */
  51193. /* OP_MaxPgcnt ensures that the parameter passed to this function is not
  51194. ** less than the total number of valid pages in the database. But this
  51195. ** may be less than Pager.dbSize, and so the assert() above is not valid */
  51196. return pPager->mxPgno;
  51197. }
  51198. /*
  51199. ** The following set of routines are used to disable the simulated
  51200. ** I/O error mechanism. These routines are used to avoid simulated
  51201. ** errors in places where we do not care about errors.
  51202. **
  51203. ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
  51204. ** and generate no code.
  51205. */
  51206. #ifdef SQLITE_TEST
  51207. SQLITE_API extern int sqlite3_io_error_pending;
  51208. SQLITE_API extern int sqlite3_io_error_hit;
  51209. static int saved_cnt;
  51210. void disable_simulated_io_errors(void){
  51211. saved_cnt = sqlite3_io_error_pending;
  51212. sqlite3_io_error_pending = -1;
  51213. }
  51214. void enable_simulated_io_errors(void){
  51215. sqlite3_io_error_pending = saved_cnt;
  51216. }
  51217. #else
  51218. # define disable_simulated_io_errors()
  51219. # define enable_simulated_io_errors()
  51220. #endif
  51221. /*
  51222. ** Read the first N bytes from the beginning of the file into memory
  51223. ** that pDest points to.
  51224. **
  51225. ** If the pager was opened on a transient file (zFilename==""), or
  51226. ** opened on a file less than N bytes in size, the output buffer is
  51227. ** zeroed and SQLITE_OK returned. The rationale for this is that this
  51228. ** function is used to read database headers, and a new transient or
  51229. ** zero sized database has a header than consists entirely of zeroes.
  51230. **
  51231. ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
  51232. ** the error code is returned to the caller and the contents of the
  51233. ** output buffer undefined.
  51234. */
  51235. SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
  51236. int rc = SQLITE_OK;
  51237. memset(pDest, 0, N);
  51238. assert( isOpen(pPager->fd) || pPager->tempFile );
  51239. /* This routine is only called by btree immediately after creating
  51240. ** the Pager object. There has not been an opportunity to transition
  51241. ** to WAL mode yet.
  51242. */
  51243. assert( !pagerUseWal(pPager) );
  51244. if( isOpen(pPager->fd) ){
  51245. IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
  51246. rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
  51247. if( rc==SQLITE_IOERR_SHORT_READ ){
  51248. rc = SQLITE_OK;
  51249. }
  51250. }
  51251. return rc;
  51252. }
  51253. /*
  51254. ** This function may only be called when a read-transaction is open on
  51255. ** the pager. It returns the total number of pages in the database.
  51256. **
  51257. ** However, if the file is between 1 and <page-size> bytes in size, then
  51258. ** this is considered a 1 page file.
  51259. */
  51260. SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
  51261. assert( pPager->eState>=PAGER_READER );
  51262. assert( pPager->eState!=PAGER_WRITER_FINISHED );
  51263. *pnPage = (int)pPager->dbSize;
  51264. }
  51265. /*
  51266. ** Try to obtain a lock of type locktype on the database file. If
  51267. ** a similar or greater lock is already held, this function is a no-op
  51268. ** (returning SQLITE_OK immediately).
  51269. **
  51270. ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
  51271. ** the busy callback if the lock is currently not available. Repeat
  51272. ** until the busy callback returns false or until the attempt to
  51273. ** obtain the lock succeeds.
  51274. **
  51275. ** Return SQLITE_OK on success and an error code if we cannot obtain
  51276. ** the lock. If the lock is obtained successfully, set the Pager.state
  51277. ** variable to locktype before returning.
  51278. */
  51279. static int pager_wait_on_lock(Pager *pPager, int locktype){
  51280. int rc; /* Return code */
  51281. /* Check that this is either a no-op (because the requested lock is
  51282. ** already held), or one of the transitions that the busy-handler
  51283. ** may be invoked during, according to the comment above
  51284. ** sqlite3PagerSetBusyhandler().
  51285. */
  51286. assert( (pPager->eLock>=locktype)
  51287. || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
  51288. || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
  51289. );
  51290. do {
  51291. rc = pagerLockDb(pPager, locktype);
  51292. }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
  51293. return rc;
  51294. }
  51295. /*
  51296. ** Function assertTruncateConstraint(pPager) checks that one of the
  51297. ** following is true for all dirty pages currently in the page-cache:
  51298. **
  51299. ** a) The page number is less than or equal to the size of the
  51300. ** current database image, in pages, OR
  51301. **
  51302. ** b) if the page content were written at this time, it would not
  51303. ** be necessary to write the current content out to the sub-journal
  51304. ** (as determined by function subjRequiresPage()).
  51305. **
  51306. ** If the condition asserted by this function were not true, and the
  51307. ** dirty page were to be discarded from the cache via the pagerStress()
  51308. ** routine, pagerStress() would not write the current page content to
  51309. ** the database file. If a savepoint transaction were rolled back after
  51310. ** this happened, the correct behavior would be to restore the current
  51311. ** content of the page. However, since this content is not present in either
  51312. ** the database file or the portion of the rollback journal and
  51313. ** sub-journal rolled back the content could not be restored and the
  51314. ** database image would become corrupt. It is therefore fortunate that
  51315. ** this circumstance cannot arise.
  51316. */
  51317. #if defined(SQLITE_DEBUG)
  51318. static void assertTruncateConstraintCb(PgHdr *pPg){
  51319. assert( pPg->flags&PGHDR_DIRTY );
  51320. assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
  51321. }
  51322. static void assertTruncateConstraint(Pager *pPager){
  51323. sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
  51324. }
  51325. #else
  51326. # define assertTruncateConstraint(pPager)
  51327. #endif
  51328. /*
  51329. ** Truncate the in-memory database file image to nPage pages. This
  51330. ** function does not actually modify the database file on disk. It
  51331. ** just sets the internal state of the pager object so that the
  51332. ** truncation will be done when the current transaction is committed.
  51333. **
  51334. ** This function is only called right before committing a transaction.
  51335. ** Once this function has been called, the transaction must either be
  51336. ** rolled back or committed. It is not safe to call this function and
  51337. ** then continue writing to the database.
  51338. */
  51339. SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
  51340. assert( pPager->dbSize>=nPage );
  51341. assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
  51342. pPager->dbSize = nPage;
  51343. /* At one point the code here called assertTruncateConstraint() to
  51344. ** ensure that all pages being truncated away by this operation are,
  51345. ** if one or more savepoints are open, present in the savepoint
  51346. ** journal so that they can be restored if the savepoint is rolled
  51347. ** back. This is no longer necessary as this function is now only
  51348. ** called right before committing a transaction. So although the
  51349. ** Pager object may still have open savepoints (Pager.nSavepoint!=0),
  51350. ** they cannot be rolled back. So the assertTruncateConstraint() call
  51351. ** is no longer correct. */
  51352. }
  51353. /*
  51354. ** This function is called before attempting a hot-journal rollback. It
  51355. ** syncs the journal file to disk, then sets pPager->journalHdr to the
  51356. ** size of the journal file so that the pager_playback() routine knows
  51357. ** that the entire journal file has been synced.
  51358. **
  51359. ** Syncing a hot-journal to disk before attempting to roll it back ensures
  51360. ** that if a power-failure occurs during the rollback, the process that
  51361. ** attempts rollback following system recovery sees the same journal
  51362. ** content as this process.
  51363. **
  51364. ** If everything goes as planned, SQLITE_OK is returned. Otherwise,
  51365. ** an SQLite error code.
  51366. */
  51367. static int pagerSyncHotJournal(Pager *pPager){
  51368. int rc = SQLITE_OK;
  51369. if( !pPager->noSync ){
  51370. rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
  51371. }
  51372. if( rc==SQLITE_OK ){
  51373. rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
  51374. }
  51375. return rc;
  51376. }
  51377. #if SQLITE_MAX_MMAP_SIZE>0
  51378. /*
  51379. ** Obtain a reference to a memory mapped page object for page number pgno.
  51380. ** The new object will use the pointer pData, obtained from xFetch().
  51381. ** If successful, set *ppPage to point to the new page reference
  51382. ** and return SQLITE_OK. Otherwise, return an SQLite error code and set
  51383. ** *ppPage to zero.
  51384. **
  51385. ** Page references obtained by calling this function should be released
  51386. ** by calling pagerReleaseMapPage().
  51387. */
  51388. static int pagerAcquireMapPage(
  51389. Pager *pPager, /* Pager object */
  51390. Pgno pgno, /* Page number */
  51391. void *pData, /* xFetch()'d data for this page */
  51392. PgHdr **ppPage /* OUT: Acquired page object */
  51393. ){
  51394. PgHdr *p; /* Memory mapped page to return */
  51395. if( pPager->pMmapFreelist ){
  51396. *ppPage = p = pPager->pMmapFreelist;
  51397. pPager->pMmapFreelist = p->pDirty;
  51398. p->pDirty = 0;
  51399. assert( pPager->nExtra>=8 );
  51400. memset(p->pExtra, 0, 8);
  51401. }else{
  51402. *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra);
  51403. if( p==0 ){
  51404. sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData);
  51405. return SQLITE_NOMEM_BKPT;
  51406. }
  51407. p->pExtra = (void *)&p[1];
  51408. p->flags = PGHDR_MMAP;
  51409. p->nRef = 1;
  51410. p->pPager = pPager;
  51411. }
  51412. assert( p->pExtra==(void *)&p[1] );
  51413. assert( p->pPage==0 );
  51414. assert( p->flags==PGHDR_MMAP );
  51415. assert( p->pPager==pPager );
  51416. assert( p->nRef==1 );
  51417. p->pgno = pgno;
  51418. p->pData = pData;
  51419. pPager->nMmapOut++;
  51420. return SQLITE_OK;
  51421. }
  51422. #endif
  51423. /*
  51424. ** Release a reference to page pPg. pPg must have been returned by an
  51425. ** earlier call to pagerAcquireMapPage().
  51426. */
  51427. static void pagerReleaseMapPage(PgHdr *pPg){
  51428. Pager *pPager = pPg->pPager;
  51429. pPager->nMmapOut--;
  51430. pPg->pDirty = pPager->pMmapFreelist;
  51431. pPager->pMmapFreelist = pPg;
  51432. assert( pPager->fd->pMethods->iVersion>=3 );
  51433. sqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData);
  51434. }
  51435. /*
  51436. ** Free all PgHdr objects stored in the Pager.pMmapFreelist list.
  51437. */
  51438. static void pagerFreeMapHdrs(Pager *pPager){
  51439. PgHdr *p;
  51440. PgHdr *pNext;
  51441. for(p=pPager->pMmapFreelist; p; p=pNext){
  51442. pNext = p->pDirty;
  51443. sqlite3_free(p);
  51444. }
  51445. }
  51446. /* Verify that the database file has not be deleted or renamed out from
  51447. ** under the pager. Return SQLITE_OK if the database is still where it ought
  51448. ** to be on disk. Return non-zero (SQLITE_READONLY_DBMOVED or some other error
  51449. ** code from sqlite3OsAccess()) if the database has gone missing.
  51450. */
  51451. static int databaseIsUnmoved(Pager *pPager){
  51452. int bHasMoved = 0;
  51453. int rc;
  51454. if( pPager->tempFile ) return SQLITE_OK;
  51455. if( pPager->dbSize==0 ) return SQLITE_OK;
  51456. assert( pPager->zFilename && pPager->zFilename[0] );
  51457. rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_HAS_MOVED, &bHasMoved);
  51458. if( rc==SQLITE_NOTFOUND ){
  51459. /* If the HAS_MOVED file-control is unimplemented, assume that the file
  51460. ** has not been moved. That is the historical behavior of SQLite: prior to
  51461. ** version 3.8.3, it never checked */
  51462. rc = SQLITE_OK;
  51463. }else if( rc==SQLITE_OK && bHasMoved ){
  51464. rc = SQLITE_READONLY_DBMOVED;
  51465. }
  51466. return rc;
  51467. }
  51468. /*
  51469. ** Shutdown the page cache. Free all memory and close all files.
  51470. **
  51471. ** If a transaction was in progress when this routine is called, that
  51472. ** transaction is rolled back. All outstanding pages are invalidated
  51473. ** and their memory is freed. Any attempt to use a page associated
  51474. ** with this page cache after this function returns will likely
  51475. ** result in a coredump.
  51476. **
  51477. ** This function always succeeds. If a transaction is active an attempt
  51478. ** is made to roll it back. If an error occurs during the rollback
  51479. ** a hot journal may be left in the filesystem but no error is returned
  51480. ** to the caller.
  51481. */
  51482. SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager, sqlite3 *db){
  51483. u8 *pTmp = (u8*)pPager->pTmpSpace;
  51484. assert( db || pagerUseWal(pPager)==0 );
  51485. assert( assert_pager_state(pPager) );
  51486. disable_simulated_io_errors();
  51487. sqlite3BeginBenignMalloc();
  51488. pagerFreeMapHdrs(pPager);
  51489. /* pPager->errCode = 0; */
  51490. pPager->exclusiveMode = 0;
  51491. #ifndef SQLITE_OMIT_WAL
  51492. {
  51493. u8 *a = 0;
  51494. assert( db || pPager->pWal==0 );
  51495. if( db && 0==(db->flags & SQLITE_NoCkptOnClose)
  51496. && SQLITE_OK==databaseIsUnmoved(pPager)
  51497. ){
  51498. a = pTmp;
  51499. }
  51500. sqlite3WalClose(pPager->pWal, db, pPager->walSyncFlags, pPager->pageSize,a);
  51501. pPager->pWal = 0;
  51502. }
  51503. #endif
  51504. pager_reset(pPager);
  51505. if( MEMDB ){
  51506. pager_unlock(pPager);
  51507. }else{
  51508. /* If it is open, sync the journal file before calling UnlockAndRollback.
  51509. ** If this is not done, then an unsynced portion of the open journal
  51510. ** file may be played back into the database. If a power failure occurs
  51511. ** while this is happening, the database could become corrupt.
  51512. **
  51513. ** If an error occurs while trying to sync the journal, shift the pager
  51514. ** into the ERROR state. This causes UnlockAndRollback to unlock the
  51515. ** database and close the journal file without attempting to roll it
  51516. ** back or finalize it. The next database user will have to do hot-journal
  51517. ** rollback before accessing the database file.
  51518. */
  51519. if( isOpen(pPager->jfd) ){
  51520. pager_error(pPager, pagerSyncHotJournal(pPager));
  51521. }
  51522. pagerUnlockAndRollback(pPager);
  51523. }
  51524. sqlite3EndBenignMalloc();
  51525. enable_simulated_io_errors();
  51526. PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
  51527. IOTRACE(("CLOSE %p\n", pPager))
  51528. sqlite3OsClose(pPager->jfd);
  51529. sqlite3OsClose(pPager->fd);
  51530. sqlite3PageFree(pTmp);
  51531. sqlite3PcacheClose(pPager->pPCache);
  51532. #ifdef SQLITE_HAS_CODEC
  51533. if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
  51534. #endif
  51535. assert( !pPager->aSavepoint && !pPager->pInJournal );
  51536. assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
  51537. sqlite3_free(pPager);
  51538. return SQLITE_OK;
  51539. }
  51540. #if !defined(NDEBUG) || defined(SQLITE_TEST)
  51541. /*
  51542. ** Return the page number for page pPg.
  51543. */
  51544. SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
  51545. return pPg->pgno;
  51546. }
  51547. #endif
  51548. /*
  51549. ** Increment the reference count for page pPg.
  51550. */
  51551. SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
  51552. sqlite3PcacheRef(pPg);
  51553. }
  51554. /*
  51555. ** Sync the journal. In other words, make sure all the pages that have
  51556. ** been written to the journal have actually reached the surface of the
  51557. ** disk and can be restored in the event of a hot-journal rollback.
  51558. **
  51559. ** If the Pager.noSync flag is set, then this function is a no-op.
  51560. ** Otherwise, the actions required depend on the journal-mode and the
  51561. ** device characteristics of the file-system, as follows:
  51562. **
  51563. ** * If the journal file is an in-memory journal file, no action need
  51564. ** be taken.
  51565. **
  51566. ** * Otherwise, if the device does not support the SAFE_APPEND property,
  51567. ** then the nRec field of the most recently written journal header
  51568. ** is updated to contain the number of journal records that have
  51569. ** been written following it. If the pager is operating in full-sync
  51570. ** mode, then the journal file is synced before this field is updated.
  51571. **
  51572. ** * If the device does not support the SEQUENTIAL property, then
  51573. ** journal file is synced.
  51574. **
  51575. ** Or, in pseudo-code:
  51576. **
  51577. ** if( NOT <in-memory journal> ){
  51578. ** if( NOT SAFE_APPEND ){
  51579. ** if( <full-sync mode> ) xSync(<journal file>);
  51580. ** <update nRec field>
  51581. ** }
  51582. ** if( NOT SEQUENTIAL ) xSync(<journal file>);
  51583. ** }
  51584. **
  51585. ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
  51586. ** page currently held in memory before returning SQLITE_OK. If an IO
  51587. ** error is encountered, then the IO error code is returned to the caller.
  51588. */
  51589. static int syncJournal(Pager *pPager, int newHdr){
  51590. int rc; /* Return code */
  51591. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  51592. || pPager->eState==PAGER_WRITER_DBMOD
  51593. );
  51594. assert( assert_pager_state(pPager) );
  51595. assert( !pagerUseWal(pPager) );
  51596. rc = sqlite3PagerExclusiveLock(pPager);
  51597. if( rc!=SQLITE_OK ) return rc;
  51598. if( !pPager->noSync ){
  51599. assert( !pPager->tempFile );
  51600. if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
  51601. const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
  51602. assert( isOpen(pPager->jfd) );
  51603. if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
  51604. /* This block deals with an obscure problem. If the last connection
  51605. ** that wrote to this database was operating in persistent-journal
  51606. ** mode, then the journal file may at this point actually be larger
  51607. ** than Pager.journalOff bytes. If the next thing in the journal
  51608. ** file happens to be a journal-header (written as part of the
  51609. ** previous connection's transaction), and a crash or power-failure
  51610. ** occurs after nRec is updated but before this connection writes
  51611. ** anything else to the journal file (or commits/rolls back its
  51612. ** transaction), then SQLite may become confused when doing the
  51613. ** hot-journal rollback following recovery. It may roll back all
  51614. ** of this connections data, then proceed to rolling back the old,
  51615. ** out-of-date data that follows it. Database corruption.
  51616. **
  51617. ** To work around this, if the journal file does appear to contain
  51618. ** a valid header following Pager.journalOff, then write a 0x00
  51619. ** byte to the start of it to prevent it from being recognized.
  51620. **
  51621. ** Variable iNextHdrOffset is set to the offset at which this
  51622. ** problematic header will occur, if it exists. aMagic is used
  51623. ** as a temporary buffer to inspect the first couple of bytes of
  51624. ** the potential journal header.
  51625. */
  51626. i64 iNextHdrOffset;
  51627. u8 aMagic[8];
  51628. u8 zHeader[sizeof(aJournalMagic)+4];
  51629. memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
  51630. put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
  51631. iNextHdrOffset = journalHdrOffset(pPager);
  51632. rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
  51633. if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
  51634. static const u8 zerobyte = 0;
  51635. rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
  51636. }
  51637. if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
  51638. return rc;
  51639. }
  51640. /* Write the nRec value into the journal file header. If in
  51641. ** full-synchronous mode, sync the journal first. This ensures that
  51642. ** all data has really hit the disk before nRec is updated to mark
  51643. ** it as a candidate for rollback.
  51644. **
  51645. ** This is not required if the persistent media supports the
  51646. ** SAFE_APPEND property. Because in this case it is not possible
  51647. ** for garbage data to be appended to the file, the nRec field
  51648. ** is populated with 0xFFFFFFFF when the journal header is written
  51649. ** and never needs to be updated.
  51650. */
  51651. if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
  51652. PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
  51653. IOTRACE(("JSYNC %p\n", pPager))
  51654. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
  51655. if( rc!=SQLITE_OK ) return rc;
  51656. }
  51657. IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
  51658. rc = sqlite3OsWrite(
  51659. pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
  51660. );
  51661. if( rc!=SQLITE_OK ) return rc;
  51662. }
  51663. if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
  51664. PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
  51665. IOTRACE(("JSYNC %p\n", pPager))
  51666. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
  51667. (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
  51668. );
  51669. if( rc!=SQLITE_OK ) return rc;
  51670. }
  51671. pPager->journalHdr = pPager->journalOff;
  51672. if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
  51673. pPager->nRec = 0;
  51674. rc = writeJournalHdr(pPager);
  51675. if( rc!=SQLITE_OK ) return rc;
  51676. }
  51677. }else{
  51678. pPager->journalHdr = pPager->journalOff;
  51679. }
  51680. }
  51681. /* Unless the pager is in noSync mode, the journal file was just
  51682. ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
  51683. ** all pages.
  51684. */
  51685. sqlite3PcacheClearSyncFlags(pPager->pPCache);
  51686. pPager->eState = PAGER_WRITER_DBMOD;
  51687. assert( assert_pager_state(pPager) );
  51688. return SQLITE_OK;
  51689. }
  51690. /*
  51691. ** The argument is the first in a linked list of dirty pages connected
  51692. ** by the PgHdr.pDirty pointer. This function writes each one of the
  51693. ** in-memory pages in the list to the database file. The argument may
  51694. ** be NULL, representing an empty list. In this case this function is
  51695. ** a no-op.
  51696. **
  51697. ** The pager must hold at least a RESERVED lock when this function
  51698. ** is called. Before writing anything to the database file, this lock
  51699. ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
  51700. ** SQLITE_BUSY is returned and no data is written to the database file.
  51701. **
  51702. ** If the pager is a temp-file pager and the actual file-system file
  51703. ** is not yet open, it is created and opened before any data is
  51704. ** written out.
  51705. **
  51706. ** Once the lock has been upgraded and, if necessary, the file opened,
  51707. ** the pages are written out to the database file in list order. Writing
  51708. ** a page is skipped if it meets either of the following criteria:
  51709. **
  51710. ** * The page number is greater than Pager.dbSize, or
  51711. ** * The PGHDR_DONT_WRITE flag is set on the page.
  51712. **
  51713. ** If writing out a page causes the database file to grow, Pager.dbFileSize
  51714. ** is updated accordingly. If page 1 is written out, then the value cached
  51715. ** in Pager.dbFileVers[] is updated to match the new value stored in
  51716. ** the database file.
  51717. **
  51718. ** If everything is successful, SQLITE_OK is returned. If an IO error
  51719. ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
  51720. ** be obtained, SQLITE_BUSY is returned.
  51721. */
  51722. static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
  51723. int rc = SQLITE_OK; /* Return code */
  51724. /* This function is only called for rollback pagers in WRITER_DBMOD state. */
  51725. assert( !pagerUseWal(pPager) );
  51726. assert( pPager->tempFile || pPager->eState==PAGER_WRITER_DBMOD );
  51727. assert( pPager->eLock==EXCLUSIVE_LOCK );
  51728. assert( isOpen(pPager->fd) || pList->pDirty==0 );
  51729. /* If the file is a temp-file has not yet been opened, open it now. It
  51730. ** is not possible for rc to be other than SQLITE_OK if this branch
  51731. ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
  51732. */
  51733. if( !isOpen(pPager->fd) ){
  51734. assert( pPager->tempFile && rc==SQLITE_OK );
  51735. rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
  51736. }
  51737. /* Before the first write, give the VFS a hint of what the final
  51738. ** file size will be.
  51739. */
  51740. assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
  51741. if( rc==SQLITE_OK
  51742. && pPager->dbHintSize<pPager->dbSize
  51743. && (pList->pDirty || pList->pgno>pPager->dbHintSize)
  51744. ){
  51745. sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
  51746. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
  51747. pPager->dbHintSize = pPager->dbSize;
  51748. }
  51749. while( rc==SQLITE_OK && pList ){
  51750. Pgno pgno = pList->pgno;
  51751. /* If there are dirty pages in the page cache with page numbers greater
  51752. ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
  51753. ** make the file smaller (presumably by auto-vacuum code). Do not write
  51754. ** any such pages to the file.
  51755. **
  51756. ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
  51757. ** set (set by sqlite3PagerDontWrite()).
  51758. */
  51759. if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
  51760. i64 offset = (pgno-1)*(i64)pPager->pageSize; /* Offset to write */
  51761. char *pData; /* Data to write */
  51762. assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
  51763. if( pList->pgno==1 ) pager_write_changecounter(pList);
  51764. /* Encode the database */
  51765. CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM_BKPT, pData);
  51766. /* Write out the page data. */
  51767. rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
  51768. /* If page 1 was just written, update Pager.dbFileVers to match
  51769. ** the value now stored in the database file. If writing this
  51770. ** page caused the database file to grow, update dbFileSize.
  51771. */
  51772. if( pgno==1 ){
  51773. memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
  51774. }
  51775. if( pgno>pPager->dbFileSize ){
  51776. pPager->dbFileSize = pgno;
  51777. }
  51778. pPager->aStat[PAGER_STAT_WRITE]++;
  51779. /* Update any backup objects copying the contents of this pager. */
  51780. sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
  51781. PAGERTRACE(("STORE %d page %d hash(%08x)\n",
  51782. PAGERID(pPager), pgno, pager_pagehash(pList)));
  51783. IOTRACE(("PGOUT %p %d\n", pPager, pgno));
  51784. PAGER_INCR(sqlite3_pager_writedb_count);
  51785. }else{
  51786. PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
  51787. }
  51788. pager_set_pagehash(pList);
  51789. pList = pList->pDirty;
  51790. }
  51791. return rc;
  51792. }
  51793. /*
  51794. ** Ensure that the sub-journal file is open. If it is already open, this
  51795. ** function is a no-op.
  51796. **
  51797. ** SQLITE_OK is returned if everything goes according to plan. An
  51798. ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
  51799. ** fails.
  51800. */
  51801. static int openSubJournal(Pager *pPager){
  51802. int rc = SQLITE_OK;
  51803. if( !isOpen(pPager->sjfd) ){
  51804. const int flags = SQLITE_OPEN_SUBJOURNAL | SQLITE_OPEN_READWRITE
  51805. | SQLITE_OPEN_CREATE | SQLITE_OPEN_EXCLUSIVE
  51806. | SQLITE_OPEN_DELETEONCLOSE;
  51807. int nStmtSpill = sqlite3Config.nStmtSpill;
  51808. if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
  51809. nStmtSpill = -1;
  51810. }
  51811. rc = sqlite3JournalOpen(pPager->pVfs, 0, pPager->sjfd, flags, nStmtSpill);
  51812. }
  51813. return rc;
  51814. }
  51815. /*
  51816. ** Append a record of the current state of page pPg to the sub-journal.
  51817. **
  51818. ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
  51819. ** for all open savepoints before returning.
  51820. **
  51821. ** This function returns SQLITE_OK if everything is successful, an IO
  51822. ** error code if the attempt to write to the sub-journal fails, or
  51823. ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
  51824. ** bitvec.
  51825. */
  51826. static int subjournalPage(PgHdr *pPg){
  51827. int rc = SQLITE_OK;
  51828. Pager *pPager = pPg->pPager;
  51829. if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
  51830. /* Open the sub-journal, if it has not already been opened */
  51831. assert( pPager->useJournal );
  51832. assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
  51833. assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
  51834. assert( pagerUseWal(pPager)
  51835. || pageInJournal(pPager, pPg)
  51836. || pPg->pgno>pPager->dbOrigSize
  51837. );
  51838. rc = openSubJournal(pPager);
  51839. /* If the sub-journal was opened successfully (or was already open),
  51840. ** write the journal record into the file. */
  51841. if( rc==SQLITE_OK ){
  51842. void *pData = pPg->pData;
  51843. i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
  51844. char *pData2;
  51845. #if SQLITE_HAS_CODEC
  51846. if( !pPager->subjInMemory ){
  51847. CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM_BKPT, pData2);
  51848. }else
  51849. #endif
  51850. pData2 = pData;
  51851. PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
  51852. rc = write32bits(pPager->sjfd, offset, pPg->pgno);
  51853. if( rc==SQLITE_OK ){
  51854. rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
  51855. }
  51856. }
  51857. }
  51858. if( rc==SQLITE_OK ){
  51859. pPager->nSubRec++;
  51860. assert( pPager->nSavepoint>0 );
  51861. rc = addToSavepointBitvecs(pPager, pPg->pgno);
  51862. }
  51863. return rc;
  51864. }
  51865. static int subjournalPageIfRequired(PgHdr *pPg){
  51866. if( subjRequiresPage(pPg) ){
  51867. return subjournalPage(pPg);
  51868. }else{
  51869. return SQLITE_OK;
  51870. }
  51871. }
  51872. /*
  51873. ** This function is called by the pcache layer when it has reached some
  51874. ** soft memory limit. The first argument is a pointer to a Pager object
  51875. ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
  51876. ** database). The second argument is a reference to a page that is
  51877. ** currently dirty but has no outstanding references. The page
  51878. ** is always associated with the Pager object passed as the first
  51879. ** argument.
  51880. **
  51881. ** The job of this function is to make pPg clean by writing its contents
  51882. ** out to the database file, if possible. This may involve syncing the
  51883. ** journal file.
  51884. **
  51885. ** If successful, sqlite3PcacheMakeClean() is called on the page and
  51886. ** SQLITE_OK returned. If an IO error occurs while trying to make the
  51887. ** page clean, the IO error code is returned. If the page cannot be
  51888. ** made clean for some other reason, but no error occurs, then SQLITE_OK
  51889. ** is returned by sqlite3PcacheMakeClean() is not called.
  51890. */
  51891. static int pagerStress(void *p, PgHdr *pPg){
  51892. Pager *pPager = (Pager *)p;
  51893. int rc = SQLITE_OK;
  51894. assert( pPg->pPager==pPager );
  51895. assert( pPg->flags&PGHDR_DIRTY );
  51896. /* The doNotSpill NOSYNC bit is set during times when doing a sync of
  51897. ** journal (and adding a new header) is not allowed. This occurs
  51898. ** during calls to sqlite3PagerWrite() while trying to journal multiple
  51899. ** pages belonging to the same sector.
  51900. **
  51901. ** The doNotSpill ROLLBACK and OFF bits inhibits all cache spilling
  51902. ** regardless of whether or not a sync is required. This is set during
  51903. ** a rollback or by user request, respectively.
  51904. **
  51905. ** Spilling is also prohibited when in an error state since that could
  51906. ** lead to database corruption. In the current implementation it
  51907. ** is impossible for sqlite3PcacheFetch() to be called with createFlag==3
  51908. ** while in the error state, hence it is impossible for this routine to
  51909. ** be called in the error state. Nevertheless, we include a NEVER()
  51910. ** test for the error state as a safeguard against future changes.
  51911. */
  51912. if( NEVER(pPager->errCode) ) return SQLITE_OK;
  51913. testcase( pPager->doNotSpill & SPILLFLAG_ROLLBACK );
  51914. testcase( pPager->doNotSpill & SPILLFLAG_OFF );
  51915. testcase( pPager->doNotSpill & SPILLFLAG_NOSYNC );
  51916. if( pPager->doNotSpill
  51917. && ((pPager->doNotSpill & (SPILLFLAG_ROLLBACK|SPILLFLAG_OFF))!=0
  51918. || (pPg->flags & PGHDR_NEED_SYNC)!=0)
  51919. ){
  51920. return SQLITE_OK;
  51921. }
  51922. pPager->aStat[PAGER_STAT_SPILL]++;
  51923. pPg->pDirty = 0;
  51924. if( pagerUseWal(pPager) ){
  51925. /* Write a single frame for this page to the log. */
  51926. rc = subjournalPageIfRequired(pPg);
  51927. if( rc==SQLITE_OK ){
  51928. rc = pagerWalFrames(pPager, pPg, 0, 0);
  51929. }
  51930. }else{
  51931. #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
  51932. if( pPager->tempFile==0 ){
  51933. rc = sqlite3JournalCreate(pPager->jfd);
  51934. if( rc!=SQLITE_OK ) return pager_error(pPager, rc);
  51935. }
  51936. #endif
  51937. /* Sync the journal file if required. */
  51938. if( pPg->flags&PGHDR_NEED_SYNC
  51939. || pPager->eState==PAGER_WRITER_CACHEMOD
  51940. ){
  51941. rc = syncJournal(pPager, 1);
  51942. }
  51943. /* Write the contents of the page out to the database file. */
  51944. if( rc==SQLITE_OK ){
  51945. assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
  51946. rc = pager_write_pagelist(pPager, pPg);
  51947. }
  51948. }
  51949. /* Mark the page as clean. */
  51950. if( rc==SQLITE_OK ){
  51951. PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
  51952. sqlite3PcacheMakeClean(pPg);
  51953. }
  51954. return pager_error(pPager, rc);
  51955. }
  51956. /*
  51957. ** Flush all unreferenced dirty pages to disk.
  51958. */
  51959. SQLITE_PRIVATE int sqlite3PagerFlush(Pager *pPager){
  51960. int rc = pPager->errCode;
  51961. if( !MEMDB ){
  51962. PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
  51963. assert( assert_pager_state(pPager) );
  51964. while( rc==SQLITE_OK && pList ){
  51965. PgHdr *pNext = pList->pDirty;
  51966. if( pList->nRef==0 ){
  51967. rc = pagerStress((void*)pPager, pList);
  51968. }
  51969. pList = pNext;
  51970. }
  51971. }
  51972. return rc;
  51973. }
  51974. /*
  51975. ** Allocate and initialize a new Pager object and put a pointer to it
  51976. ** in *ppPager. The pager should eventually be freed by passing it
  51977. ** to sqlite3PagerClose().
  51978. **
  51979. ** The zFilename argument is the path to the database file to open.
  51980. ** If zFilename is NULL then a randomly-named temporary file is created
  51981. ** and used as the file to be cached. Temporary files are be deleted
  51982. ** automatically when they are closed. If zFilename is ":memory:" then
  51983. ** all information is held in cache. It is never written to disk.
  51984. ** This can be used to implement an in-memory database.
  51985. **
  51986. ** The nExtra parameter specifies the number of bytes of space allocated
  51987. ** along with each page reference. This space is available to the user
  51988. ** via the sqlite3PagerGetExtra() API. When a new page is allocated, the
  51989. ** first 8 bytes of this space are zeroed but the remainder is uninitialized.
  51990. ** (The extra space is used by btree as the MemPage object.)
  51991. **
  51992. ** The flags argument is used to specify properties that affect the
  51993. ** operation of the pager. It should be passed some bitwise combination
  51994. ** of the PAGER_* flags.
  51995. **
  51996. ** The vfsFlags parameter is a bitmask to pass to the flags parameter
  51997. ** of the xOpen() method of the supplied VFS when opening files.
  51998. **
  51999. ** If the pager object is allocated and the specified file opened
  52000. ** successfully, SQLITE_OK is returned and *ppPager set to point to
  52001. ** the new pager object. If an error occurs, *ppPager is set to NULL
  52002. ** and error code returned. This function may return SQLITE_NOMEM
  52003. ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
  52004. ** various SQLITE_IO_XXX errors.
  52005. */
  52006. SQLITE_PRIVATE int sqlite3PagerOpen(
  52007. sqlite3_vfs *pVfs, /* The virtual file system to use */
  52008. Pager **ppPager, /* OUT: Return the Pager structure here */
  52009. const char *zFilename, /* Name of the database file to open */
  52010. int nExtra, /* Extra bytes append to each in-memory page */
  52011. int flags, /* flags controlling this file */
  52012. int vfsFlags, /* flags passed through to sqlite3_vfs.xOpen() */
  52013. void (*xReinit)(DbPage*) /* Function to reinitialize pages */
  52014. ){
  52015. u8 *pPtr;
  52016. Pager *pPager = 0; /* Pager object to allocate and return */
  52017. int rc = SQLITE_OK; /* Return code */
  52018. int tempFile = 0; /* True for temp files (incl. in-memory files) */
  52019. int memDb = 0; /* True if this is an in-memory file */
  52020. #ifdef SQLITE_ENABLE_DESERIALIZE
  52021. int memJM = 0; /* Memory journal mode */
  52022. #else
  52023. # define memJM 0
  52024. #endif
  52025. int readOnly = 0; /* True if this is a read-only file */
  52026. int journalFileSize; /* Bytes to allocate for each journal fd */
  52027. char *zPathname = 0; /* Full path to database file */
  52028. int nPathname = 0; /* Number of bytes in zPathname */
  52029. int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
  52030. int pcacheSize = sqlite3PcacheSize(); /* Bytes to allocate for PCache */
  52031. u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE; /* Default page size */
  52032. const char *zUri = 0; /* URI args to copy */
  52033. int nUri = 0; /* Number of bytes of URI args at *zUri */
  52034. /* Figure out how much space is required for each journal file-handle
  52035. ** (there are two of them, the main journal and the sub-journal). */
  52036. journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
  52037. /* Set the output variable to NULL in case an error occurs. */
  52038. *ppPager = 0;
  52039. #ifndef SQLITE_OMIT_MEMORYDB
  52040. if( flags & PAGER_MEMORY ){
  52041. memDb = 1;
  52042. if( zFilename && zFilename[0] ){
  52043. zPathname = sqlite3DbStrDup(0, zFilename);
  52044. if( zPathname==0 ) return SQLITE_NOMEM_BKPT;
  52045. nPathname = sqlite3Strlen30(zPathname);
  52046. zFilename = 0;
  52047. }
  52048. }
  52049. #endif
  52050. /* Compute and store the full pathname in an allocated buffer pointed
  52051. ** to by zPathname, length nPathname. Or, if this is a temporary file,
  52052. ** leave both nPathname and zPathname set to 0.
  52053. */
  52054. if( zFilename && zFilename[0] ){
  52055. const char *z;
  52056. nPathname = pVfs->mxPathname+1;
  52057. zPathname = sqlite3DbMallocRaw(0, nPathname*2);
  52058. if( zPathname==0 ){
  52059. return SQLITE_NOMEM_BKPT;
  52060. }
  52061. zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
  52062. rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
  52063. nPathname = sqlite3Strlen30(zPathname);
  52064. z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
  52065. while( *z ){
  52066. z += sqlite3Strlen30(z)+1;
  52067. z += sqlite3Strlen30(z)+1;
  52068. }
  52069. nUri = (int)(&z[1] - zUri);
  52070. assert( nUri>=0 );
  52071. if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
  52072. /* This branch is taken when the journal path required by
  52073. ** the database being opened will be more than pVfs->mxPathname
  52074. ** bytes in length. This means the database cannot be opened,
  52075. ** as it will not be possible to open the journal file or even
  52076. ** check for a hot-journal before reading.
  52077. */
  52078. rc = SQLITE_CANTOPEN_BKPT;
  52079. }
  52080. if( rc!=SQLITE_OK ){
  52081. sqlite3DbFree(0, zPathname);
  52082. return rc;
  52083. }
  52084. }
  52085. /* Allocate memory for the Pager structure, PCache object, the
  52086. ** three file descriptors, the database file name and the journal
  52087. ** file name. The layout in memory is as follows:
  52088. **
  52089. ** Pager object (sizeof(Pager) bytes)
  52090. ** PCache object (sqlite3PcacheSize() bytes)
  52091. ** Database file handle (pVfs->szOsFile bytes)
  52092. ** Sub-journal file handle (journalFileSize bytes)
  52093. ** Main journal file handle (journalFileSize bytes)
  52094. ** Database file name (nPathname+1 bytes)
  52095. ** Journal file name (nPathname+8+1 bytes)
  52096. */
  52097. pPtr = (u8 *)sqlite3MallocZero(
  52098. ROUND8(sizeof(*pPager)) + /* Pager structure */
  52099. ROUND8(pcacheSize) + /* PCache object */
  52100. ROUND8(pVfs->szOsFile) + /* The main db file */
  52101. journalFileSize * 2 + /* The two journal files */
  52102. nPathname + 1 + nUri + /* zFilename */
  52103. nPathname + 8 + 2 /* zJournal */
  52104. #ifndef SQLITE_OMIT_WAL
  52105. + nPathname + 4 + 2 /* zWal */
  52106. #endif
  52107. );
  52108. assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
  52109. if( !pPtr ){
  52110. sqlite3DbFree(0, zPathname);
  52111. return SQLITE_NOMEM_BKPT;
  52112. }
  52113. pPager = (Pager*)(pPtr);
  52114. pPager->pPCache = (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
  52115. pPager->fd = (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
  52116. pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
  52117. pPager->jfd = (sqlite3_file*)(pPtr += journalFileSize);
  52118. pPager->zFilename = (char*)(pPtr += journalFileSize);
  52119. assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
  52120. /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
  52121. if( zPathname ){
  52122. assert( nPathname>0 );
  52123. pPager->zJournal = (char*)(pPtr += nPathname + 1 + nUri);
  52124. memcpy(pPager->zFilename, zPathname, nPathname);
  52125. if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
  52126. memcpy(pPager->zJournal, zPathname, nPathname);
  52127. memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+2);
  52128. sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
  52129. #ifndef SQLITE_OMIT_WAL
  52130. pPager->zWal = &pPager->zJournal[nPathname+8+1];
  52131. memcpy(pPager->zWal, zPathname, nPathname);
  52132. memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1);
  52133. sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
  52134. #endif
  52135. sqlite3DbFree(0, zPathname);
  52136. }
  52137. pPager->pVfs = pVfs;
  52138. pPager->vfsFlags = vfsFlags;
  52139. /* Open the pager file.
  52140. */
  52141. if( zFilename && zFilename[0] ){
  52142. int fout = 0; /* VFS flags returned by xOpen() */
  52143. rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
  52144. assert( !memDb );
  52145. #ifdef SQLITE_ENABLE_DESERIALIZE
  52146. memJM = (fout&SQLITE_OPEN_MEMORY)!=0;
  52147. #endif
  52148. readOnly = (fout&SQLITE_OPEN_READONLY)!=0;
  52149. /* If the file was successfully opened for read/write access,
  52150. ** choose a default page size in case we have to create the
  52151. ** database file. The default page size is the maximum of:
  52152. **
  52153. ** + SQLITE_DEFAULT_PAGE_SIZE,
  52154. ** + The value returned by sqlite3OsSectorSize()
  52155. ** + The largest page size that can be written atomically.
  52156. */
  52157. if( rc==SQLITE_OK ){
  52158. int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
  52159. if( !readOnly ){
  52160. setSectorSize(pPager);
  52161. assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
  52162. if( szPageDflt<pPager->sectorSize ){
  52163. if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
  52164. szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
  52165. }else{
  52166. szPageDflt = (u32)pPager->sectorSize;
  52167. }
  52168. }
  52169. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  52170. {
  52171. int ii;
  52172. assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
  52173. assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
  52174. assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
  52175. for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
  52176. if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
  52177. szPageDflt = ii;
  52178. }
  52179. }
  52180. }
  52181. #endif
  52182. }
  52183. pPager->noLock = sqlite3_uri_boolean(zFilename, "nolock", 0);
  52184. if( (iDc & SQLITE_IOCAP_IMMUTABLE)!=0
  52185. || sqlite3_uri_boolean(zFilename, "immutable", 0) ){
  52186. vfsFlags |= SQLITE_OPEN_READONLY;
  52187. goto act_like_temp_file;
  52188. }
  52189. }
  52190. }else{
  52191. /* If a temporary file is requested, it is not opened immediately.
  52192. ** In this case we accept the default page size and delay actually
  52193. ** opening the file until the first call to OsWrite().
  52194. **
  52195. ** This branch is also run for an in-memory database. An in-memory
  52196. ** database is the same as a temp-file that is never written out to
  52197. ** disk and uses an in-memory rollback journal.
  52198. **
  52199. ** This branch also runs for files marked as immutable.
  52200. */
  52201. act_like_temp_file:
  52202. tempFile = 1;
  52203. pPager->eState = PAGER_READER; /* Pretend we already have a lock */
  52204. pPager->eLock = EXCLUSIVE_LOCK; /* Pretend we are in EXCLUSIVE mode */
  52205. pPager->noLock = 1; /* Do no locking */
  52206. readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
  52207. }
  52208. /* The following call to PagerSetPagesize() serves to set the value of
  52209. ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
  52210. */
  52211. if( rc==SQLITE_OK ){
  52212. assert( pPager->memDb==0 );
  52213. rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
  52214. testcase( rc!=SQLITE_OK );
  52215. }
  52216. /* Initialize the PCache object. */
  52217. if( rc==SQLITE_OK ){
  52218. nExtra = ROUND8(nExtra);
  52219. assert( nExtra>=8 && nExtra<1000 );
  52220. rc = sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
  52221. !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
  52222. }
  52223. /* If an error occurred above, free the Pager structure and close the file.
  52224. */
  52225. if( rc!=SQLITE_OK ){
  52226. sqlite3OsClose(pPager->fd);
  52227. sqlite3PageFree(pPager->pTmpSpace);
  52228. sqlite3_free(pPager);
  52229. return rc;
  52230. }
  52231. PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
  52232. IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
  52233. pPager->useJournal = (u8)useJournal;
  52234. /* pPager->stmtOpen = 0; */
  52235. /* pPager->stmtInUse = 0; */
  52236. /* pPager->nRef = 0; */
  52237. /* pPager->stmtSize = 0; */
  52238. /* pPager->stmtJSize = 0; */
  52239. /* pPager->nPage = 0; */
  52240. pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
  52241. /* pPager->state = PAGER_UNLOCK; */
  52242. /* pPager->errMask = 0; */
  52243. pPager->tempFile = (u8)tempFile;
  52244. assert( tempFile==PAGER_LOCKINGMODE_NORMAL
  52245. || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
  52246. assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
  52247. pPager->exclusiveMode = (u8)tempFile;
  52248. pPager->changeCountDone = pPager->tempFile;
  52249. pPager->memDb = (u8)memDb;
  52250. pPager->readOnly = (u8)readOnly;
  52251. assert( useJournal || pPager->tempFile );
  52252. pPager->noSync = pPager->tempFile;
  52253. if( pPager->noSync ){
  52254. assert( pPager->fullSync==0 );
  52255. assert( pPager->extraSync==0 );
  52256. assert( pPager->syncFlags==0 );
  52257. assert( pPager->walSyncFlags==0 );
  52258. }else{
  52259. pPager->fullSync = 1;
  52260. pPager->extraSync = 0;
  52261. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  52262. pPager->walSyncFlags = SQLITE_SYNC_NORMAL | (SQLITE_SYNC_NORMAL<<2);
  52263. }
  52264. /* pPager->pFirst = 0; */
  52265. /* pPager->pFirstSynced = 0; */
  52266. /* pPager->pLast = 0; */
  52267. pPager->nExtra = (u16)nExtra;
  52268. pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
  52269. assert( isOpen(pPager->fd) || tempFile );
  52270. setSectorSize(pPager);
  52271. if( !useJournal ){
  52272. pPager->journalMode = PAGER_JOURNALMODE_OFF;
  52273. }else if( memDb || memJM ){
  52274. pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
  52275. }
  52276. /* pPager->xBusyHandler = 0; */
  52277. /* pPager->pBusyHandlerArg = 0; */
  52278. pPager->xReiniter = xReinit;
  52279. setGetterMethod(pPager);
  52280. /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
  52281. /* pPager->szMmap = SQLITE_DEFAULT_MMAP_SIZE // will be set by btree.c */
  52282. *ppPager = pPager;
  52283. return SQLITE_OK;
  52284. }
  52285. /*
  52286. ** This function is called after transitioning from PAGER_UNLOCK to
  52287. ** PAGER_SHARED state. It tests if there is a hot journal present in
  52288. ** the file-system for the given pager. A hot journal is one that
  52289. ** needs to be played back. According to this function, a hot-journal
  52290. ** file exists if the following criteria are met:
  52291. **
  52292. ** * The journal file exists in the file system, and
  52293. ** * No process holds a RESERVED or greater lock on the database file, and
  52294. ** * The database file itself is greater than 0 bytes in size, and
  52295. ** * The first byte of the journal file exists and is not 0x00.
  52296. **
  52297. ** If the current size of the database file is 0 but a journal file
  52298. ** exists, that is probably an old journal left over from a prior
  52299. ** database with the same name. In this case the journal file is
  52300. ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
  52301. ** is returned.
  52302. **
  52303. ** This routine does not check if there is a master journal filename
  52304. ** at the end of the file. If there is, and that master journal file
  52305. ** does not exist, then the journal file is not really hot. In this
  52306. ** case this routine will return a false-positive. The pager_playback()
  52307. ** routine will discover that the journal file is not really hot and
  52308. ** will not roll it back.
  52309. **
  52310. ** If a hot-journal file is found to exist, *pExists is set to 1 and
  52311. ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
  52312. ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
  52313. ** to determine whether or not a hot-journal file exists, the IO error
  52314. ** code is returned and the value of *pExists is undefined.
  52315. */
  52316. static int hasHotJournal(Pager *pPager, int *pExists){
  52317. sqlite3_vfs * const pVfs = pPager->pVfs;
  52318. int rc = SQLITE_OK; /* Return code */
  52319. int exists = 1; /* True if a journal file is present */
  52320. int jrnlOpen = !!isOpen(pPager->jfd);
  52321. assert( pPager->useJournal );
  52322. assert( isOpen(pPager->fd) );
  52323. assert( pPager->eState==PAGER_OPEN );
  52324. assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
  52325. SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
  52326. ));
  52327. *pExists = 0;
  52328. if( !jrnlOpen ){
  52329. rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
  52330. }
  52331. if( rc==SQLITE_OK && exists ){
  52332. int locked = 0; /* True if some process holds a RESERVED lock */
  52333. /* Race condition here: Another process might have been holding the
  52334. ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
  52335. ** call above, but then delete the journal and drop the lock before
  52336. ** we get to the following sqlite3OsCheckReservedLock() call. If that
  52337. ** is the case, this routine might think there is a hot journal when
  52338. ** in fact there is none. This results in a false-positive which will
  52339. ** be dealt with by the playback routine. Ticket #3883.
  52340. */
  52341. rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
  52342. if( rc==SQLITE_OK && !locked ){
  52343. Pgno nPage; /* Number of pages in database file */
  52344. assert( pPager->tempFile==0 );
  52345. rc = pagerPagecount(pPager, &nPage);
  52346. if( rc==SQLITE_OK ){
  52347. /* If the database is zero pages in size, that means that either (1) the
  52348. ** journal is a remnant from a prior database with the same name where
  52349. ** the database file but not the journal was deleted, or (2) the initial
  52350. ** transaction that populates a new database is being rolled back.
  52351. ** In either case, the journal file can be deleted. However, take care
  52352. ** not to delete the journal file if it is already open due to
  52353. ** journal_mode=PERSIST.
  52354. */
  52355. if( nPage==0 && !jrnlOpen ){
  52356. sqlite3BeginBenignMalloc();
  52357. if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
  52358. sqlite3OsDelete(pVfs, pPager->zJournal, 0);
  52359. if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
  52360. }
  52361. sqlite3EndBenignMalloc();
  52362. }else{
  52363. /* The journal file exists and no other connection has a reserved
  52364. ** or greater lock on the database file. Now check that there is
  52365. ** at least one non-zero bytes at the start of the journal file.
  52366. ** If there is, then we consider this journal to be hot. If not,
  52367. ** it can be ignored.
  52368. */
  52369. if( !jrnlOpen ){
  52370. int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
  52371. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
  52372. }
  52373. if( rc==SQLITE_OK ){
  52374. u8 first = 0;
  52375. rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
  52376. if( rc==SQLITE_IOERR_SHORT_READ ){
  52377. rc = SQLITE_OK;
  52378. }
  52379. if( !jrnlOpen ){
  52380. sqlite3OsClose(pPager->jfd);
  52381. }
  52382. *pExists = (first!=0);
  52383. }else if( rc==SQLITE_CANTOPEN ){
  52384. /* If we cannot open the rollback journal file in order to see if
  52385. ** it has a zero header, that might be due to an I/O error, or
  52386. ** it might be due to the race condition described above and in
  52387. ** ticket #3883. Either way, assume that the journal is hot.
  52388. ** This might be a false positive. But if it is, then the
  52389. ** automatic journal playback and recovery mechanism will deal
  52390. ** with it under an EXCLUSIVE lock where we do not need to
  52391. ** worry so much with race conditions.
  52392. */
  52393. *pExists = 1;
  52394. rc = SQLITE_OK;
  52395. }
  52396. }
  52397. }
  52398. }
  52399. }
  52400. return rc;
  52401. }
  52402. /*
  52403. ** This function is called to obtain a shared lock on the database file.
  52404. ** It is illegal to call sqlite3PagerGet() until after this function
  52405. ** has been successfully called. If a shared-lock is already held when
  52406. ** this function is called, it is a no-op.
  52407. **
  52408. ** The following operations are also performed by this function.
  52409. **
  52410. ** 1) If the pager is currently in PAGER_OPEN state (no lock held
  52411. ** on the database file), then an attempt is made to obtain a
  52412. ** SHARED lock on the database file. Immediately after obtaining
  52413. ** the SHARED lock, the file-system is checked for a hot-journal,
  52414. ** which is played back if present. Following any hot-journal
  52415. ** rollback, the contents of the cache are validated by checking
  52416. ** the 'change-counter' field of the database file header and
  52417. ** discarded if they are found to be invalid.
  52418. **
  52419. ** 2) If the pager is running in exclusive-mode, and there are currently
  52420. ** no outstanding references to any pages, and is in the error state,
  52421. ** then an attempt is made to clear the error state by discarding
  52422. ** the contents of the page cache and rolling back any open journal
  52423. ** file.
  52424. **
  52425. ** If everything is successful, SQLITE_OK is returned. If an IO error
  52426. ** occurs while locking the database, checking for a hot-journal file or
  52427. ** rolling back a journal file, the IO error code is returned.
  52428. */
  52429. SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
  52430. int rc = SQLITE_OK; /* Return code */
  52431. /* This routine is only called from b-tree and only when there are no
  52432. ** outstanding pages. This implies that the pager state should either
  52433. ** be OPEN or READER. READER is only possible if the pager is or was in
  52434. ** exclusive access mode. */
  52435. assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
  52436. assert( assert_pager_state(pPager) );
  52437. assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
  52438. assert( pPager->errCode==SQLITE_OK );
  52439. if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
  52440. int bHotJournal = 1; /* True if there exists a hot journal-file */
  52441. assert( !MEMDB );
  52442. assert( pPager->tempFile==0 || pPager->eLock==EXCLUSIVE_LOCK );
  52443. rc = pager_wait_on_lock(pPager, SHARED_LOCK);
  52444. if( rc!=SQLITE_OK ){
  52445. assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
  52446. goto failed;
  52447. }
  52448. /* If a journal file exists, and there is no RESERVED lock on the
  52449. ** database file, then it either needs to be played back or deleted.
  52450. */
  52451. if( pPager->eLock<=SHARED_LOCK ){
  52452. rc = hasHotJournal(pPager, &bHotJournal);
  52453. }
  52454. if( rc!=SQLITE_OK ){
  52455. goto failed;
  52456. }
  52457. if( bHotJournal ){
  52458. if( pPager->readOnly ){
  52459. rc = SQLITE_READONLY_ROLLBACK;
  52460. goto failed;
  52461. }
  52462. /* Get an EXCLUSIVE lock on the database file. At this point it is
  52463. ** important that a RESERVED lock is not obtained on the way to the
  52464. ** EXCLUSIVE lock. If it were, another process might open the
  52465. ** database file, detect the RESERVED lock, and conclude that the
  52466. ** database is safe to read while this process is still rolling the
  52467. ** hot-journal back.
  52468. **
  52469. ** Because the intermediate RESERVED lock is not requested, any
  52470. ** other process attempting to access the database file will get to
  52471. ** this point in the code and fail to obtain its own EXCLUSIVE lock
  52472. ** on the database file.
  52473. **
  52474. ** Unless the pager is in locking_mode=exclusive mode, the lock is
  52475. ** downgraded to SHARED_LOCK before this function returns.
  52476. */
  52477. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  52478. if( rc!=SQLITE_OK ){
  52479. goto failed;
  52480. }
  52481. /* If it is not already open and the file exists on disk, open the
  52482. ** journal for read/write access. Write access is required because
  52483. ** in exclusive-access mode the file descriptor will be kept open
  52484. ** and possibly used for a transaction later on. Also, write-access
  52485. ** is usually required to finalize the journal in journal_mode=persist
  52486. ** mode (and also for journal_mode=truncate on some systems).
  52487. **
  52488. ** If the journal does not exist, it usually means that some
  52489. ** other connection managed to get in and roll it back before
  52490. ** this connection obtained the exclusive lock above. Or, it
  52491. ** may mean that the pager was in the error-state when this
  52492. ** function was called and the journal file does not exist.
  52493. */
  52494. if( !isOpen(pPager->jfd) ){
  52495. sqlite3_vfs * const pVfs = pPager->pVfs;
  52496. int bExists; /* True if journal file exists */
  52497. rc = sqlite3OsAccess(
  52498. pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
  52499. if( rc==SQLITE_OK && bExists ){
  52500. int fout = 0;
  52501. int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
  52502. assert( !pPager->tempFile );
  52503. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
  52504. assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
  52505. if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
  52506. rc = SQLITE_CANTOPEN_BKPT;
  52507. sqlite3OsClose(pPager->jfd);
  52508. }
  52509. }
  52510. }
  52511. /* Playback and delete the journal. Drop the database write
  52512. ** lock and reacquire the read lock. Purge the cache before
  52513. ** playing back the hot-journal so that we don't end up with
  52514. ** an inconsistent cache. Sync the hot journal before playing
  52515. ** it back since the process that crashed and left the hot journal
  52516. ** probably did not sync it and we are required to always sync
  52517. ** the journal before playing it back.
  52518. */
  52519. if( isOpen(pPager->jfd) ){
  52520. assert( rc==SQLITE_OK );
  52521. rc = pagerSyncHotJournal(pPager);
  52522. if( rc==SQLITE_OK ){
  52523. rc = pager_playback(pPager, !pPager->tempFile);
  52524. pPager->eState = PAGER_OPEN;
  52525. }
  52526. }else if( !pPager->exclusiveMode ){
  52527. pagerUnlockDb(pPager, SHARED_LOCK);
  52528. }
  52529. if( rc!=SQLITE_OK ){
  52530. /* This branch is taken if an error occurs while trying to open
  52531. ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
  52532. ** pager_unlock() routine will be called before returning to unlock
  52533. ** the file. If the unlock attempt fails, then Pager.eLock must be
  52534. ** set to UNKNOWN_LOCK (see the comment above the #define for
  52535. ** UNKNOWN_LOCK above for an explanation).
  52536. **
  52537. ** In order to get pager_unlock() to do this, set Pager.eState to
  52538. ** PAGER_ERROR now. This is not actually counted as a transition
  52539. ** to ERROR state in the state diagram at the top of this file,
  52540. ** since we know that the same call to pager_unlock() will very
  52541. ** shortly transition the pager object to the OPEN state. Calling
  52542. ** assert_pager_state() would fail now, as it should not be possible
  52543. ** to be in ERROR state when there are zero outstanding page
  52544. ** references.
  52545. */
  52546. pager_error(pPager, rc);
  52547. goto failed;
  52548. }
  52549. assert( pPager->eState==PAGER_OPEN );
  52550. assert( (pPager->eLock==SHARED_LOCK)
  52551. || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
  52552. );
  52553. }
  52554. if( !pPager->tempFile && pPager->hasHeldSharedLock ){
  52555. /* The shared-lock has just been acquired then check to
  52556. ** see if the database has been modified. If the database has changed,
  52557. ** flush the cache. The hasHeldSharedLock flag prevents this from
  52558. ** occurring on the very first access to a file, in order to save a
  52559. ** single unnecessary sqlite3OsRead() call at the start-up.
  52560. **
  52561. ** Database changes are detected by looking at 15 bytes beginning
  52562. ** at offset 24 into the file. The first 4 of these 16 bytes are
  52563. ** a 32-bit counter that is incremented with each change. The
  52564. ** other bytes change randomly with each file change when
  52565. ** a codec is in use.
  52566. **
  52567. ** There is a vanishingly small chance that a change will not be
  52568. ** detected. The chance of an undetected change is so small that
  52569. ** it can be neglected.
  52570. */
  52571. char dbFileVers[sizeof(pPager->dbFileVers)];
  52572. IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
  52573. rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
  52574. if( rc!=SQLITE_OK ){
  52575. if( rc!=SQLITE_IOERR_SHORT_READ ){
  52576. goto failed;
  52577. }
  52578. memset(dbFileVers, 0, sizeof(dbFileVers));
  52579. }
  52580. if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
  52581. pager_reset(pPager);
  52582. /* Unmap the database file. It is possible that external processes
  52583. ** may have truncated the database file and then extended it back
  52584. ** to its original size while this process was not holding a lock.
  52585. ** In this case there may exist a Pager.pMap mapping that appears
  52586. ** to be the right size but is not actually valid. Avoid this
  52587. ** possibility by unmapping the db here. */
  52588. if( USEFETCH(pPager) ){
  52589. sqlite3OsUnfetch(pPager->fd, 0, 0);
  52590. }
  52591. }
  52592. }
  52593. /* If there is a WAL file in the file-system, open this database in WAL
  52594. ** mode. Otherwise, the following function call is a no-op.
  52595. */
  52596. rc = pagerOpenWalIfPresent(pPager);
  52597. #ifndef SQLITE_OMIT_WAL
  52598. assert( pPager->pWal==0 || rc==SQLITE_OK );
  52599. #endif
  52600. }
  52601. if( pagerUseWal(pPager) ){
  52602. assert( rc==SQLITE_OK );
  52603. rc = pagerBeginReadTransaction(pPager);
  52604. }
  52605. if( pPager->tempFile==0 && pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
  52606. rc = pagerPagecount(pPager, &pPager->dbSize);
  52607. }
  52608. failed:
  52609. if( rc!=SQLITE_OK ){
  52610. assert( !MEMDB );
  52611. pager_unlock(pPager);
  52612. assert( pPager->eState==PAGER_OPEN );
  52613. }else{
  52614. pPager->eState = PAGER_READER;
  52615. pPager->hasHeldSharedLock = 1;
  52616. }
  52617. return rc;
  52618. }
  52619. /*
  52620. ** If the reference count has reached zero, rollback any active
  52621. ** transaction and unlock the pager.
  52622. **
  52623. ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
  52624. ** the rollback journal, the unlock is not performed and there is
  52625. ** nothing to rollback, so this routine is a no-op.
  52626. */
  52627. static void pagerUnlockIfUnused(Pager *pPager){
  52628. if( sqlite3PcacheRefCount(pPager->pPCache)==0 ){
  52629. assert( pPager->nMmapOut==0 ); /* because page1 is never memory mapped */
  52630. pagerUnlockAndRollback(pPager);
  52631. }
  52632. }
  52633. /*
  52634. ** The page getter methods each try to acquire a reference to a
  52635. ** page with page number pgno. If the requested reference is
  52636. ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
  52637. **
  52638. ** There are different implementations of the getter method depending
  52639. ** on the current state of the pager.
  52640. **
  52641. ** getPageNormal() -- The normal getter
  52642. ** getPageError() -- Used if the pager is in an error state
  52643. ** getPageMmap() -- Used if memory-mapped I/O is enabled
  52644. **
  52645. ** If the requested page is already in the cache, it is returned.
  52646. ** Otherwise, a new page object is allocated and populated with data
  52647. ** read from the database file. In some cases, the pcache module may
  52648. ** choose not to allocate a new page object and may reuse an existing
  52649. ** object with no outstanding references.
  52650. **
  52651. ** The extra data appended to a page is always initialized to zeros the
  52652. ** first time a page is loaded into memory. If the page requested is
  52653. ** already in the cache when this function is called, then the extra
  52654. ** data is left as it was when the page object was last used.
  52655. **
  52656. ** If the database image is smaller than the requested page or if
  52657. ** the flags parameter contains the PAGER_GET_NOCONTENT bit and the
  52658. ** requested page is not already stored in the cache, then no
  52659. ** actual disk read occurs. In this case the memory image of the
  52660. ** page is initialized to all zeros.
  52661. **
  52662. ** If PAGER_GET_NOCONTENT is true, it means that we do not care about
  52663. ** the contents of the page. This occurs in two scenarios:
  52664. **
  52665. ** a) When reading a free-list leaf page from the database, and
  52666. **
  52667. ** b) When a savepoint is being rolled back and we need to load
  52668. ** a new page into the cache to be filled with the data read
  52669. ** from the savepoint journal.
  52670. **
  52671. ** If PAGER_GET_NOCONTENT is true, then the data returned is zeroed instead
  52672. ** of being read from the database. Additionally, the bits corresponding
  52673. ** to pgno in Pager.pInJournal (bitvec of pages already written to the
  52674. ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
  52675. ** savepoints are set. This means if the page is made writable at any
  52676. ** point in the future, using a call to sqlite3PagerWrite(), its contents
  52677. ** will not be journaled. This saves IO.
  52678. **
  52679. ** The acquisition might fail for several reasons. In all cases,
  52680. ** an appropriate error code is returned and *ppPage is set to NULL.
  52681. **
  52682. ** See also sqlite3PagerLookup(). Both this routine and Lookup() attempt
  52683. ** to find a page in the in-memory cache first. If the page is not already
  52684. ** in memory, this routine goes to disk to read it in whereas Lookup()
  52685. ** just returns 0. This routine acquires a read-lock the first time it
  52686. ** has to go to disk, and could also playback an old journal if necessary.
  52687. ** Since Lookup() never goes to disk, it never has to deal with locks
  52688. ** or journal files.
  52689. */
  52690. static int getPageNormal(
  52691. Pager *pPager, /* The pager open on the database file */
  52692. Pgno pgno, /* Page number to fetch */
  52693. DbPage **ppPage, /* Write a pointer to the page here */
  52694. int flags /* PAGER_GET_XXX flags */
  52695. ){
  52696. int rc = SQLITE_OK;
  52697. PgHdr *pPg;
  52698. u8 noContent; /* True if PAGER_GET_NOCONTENT is set */
  52699. sqlite3_pcache_page *pBase;
  52700. assert( pPager->errCode==SQLITE_OK );
  52701. assert( pPager->eState>=PAGER_READER );
  52702. assert( assert_pager_state(pPager) );
  52703. assert( pPager->hasHeldSharedLock==1 );
  52704. if( pgno==0 ) return SQLITE_CORRUPT_BKPT;
  52705. pBase = sqlite3PcacheFetch(pPager->pPCache, pgno, 3);
  52706. if( pBase==0 ){
  52707. pPg = 0;
  52708. rc = sqlite3PcacheFetchStress(pPager->pPCache, pgno, &pBase);
  52709. if( rc!=SQLITE_OK ) goto pager_acquire_err;
  52710. if( pBase==0 ){
  52711. rc = SQLITE_NOMEM_BKPT;
  52712. goto pager_acquire_err;
  52713. }
  52714. }
  52715. pPg = *ppPage = sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pBase);
  52716. assert( pPg==(*ppPage) );
  52717. assert( pPg->pgno==pgno );
  52718. assert( pPg->pPager==pPager || pPg->pPager==0 );
  52719. noContent = (flags & PAGER_GET_NOCONTENT)!=0;
  52720. if( pPg->pPager && !noContent ){
  52721. /* In this case the pcache already contains an initialized copy of
  52722. ** the page. Return without further ado. */
  52723. assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
  52724. pPager->aStat[PAGER_STAT_HIT]++;
  52725. return SQLITE_OK;
  52726. }else{
  52727. /* The pager cache has created a new page. Its content needs to
  52728. ** be initialized. But first some error checks:
  52729. **
  52730. ** (1) The maximum page number is 2^31
  52731. ** (2) Never try to fetch the locking page
  52732. */
  52733. if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
  52734. rc = SQLITE_CORRUPT_BKPT;
  52735. goto pager_acquire_err;
  52736. }
  52737. pPg->pPager = pPager;
  52738. assert( !isOpen(pPager->fd) || !MEMDB );
  52739. if( !isOpen(pPager->fd) || pPager->dbSize<pgno || noContent ){
  52740. if( pgno>pPager->mxPgno ){
  52741. rc = SQLITE_FULL;
  52742. goto pager_acquire_err;
  52743. }
  52744. if( noContent ){
  52745. /* Failure to set the bits in the InJournal bit-vectors is benign.
  52746. ** It merely means that we might do some extra work to journal a
  52747. ** page that does not need to be journaled. Nevertheless, be sure
  52748. ** to test the case where a malloc error occurs while trying to set
  52749. ** a bit in a bit vector.
  52750. */
  52751. sqlite3BeginBenignMalloc();
  52752. if( pgno<=pPager->dbOrigSize ){
  52753. TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
  52754. testcase( rc==SQLITE_NOMEM );
  52755. }
  52756. TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
  52757. testcase( rc==SQLITE_NOMEM );
  52758. sqlite3EndBenignMalloc();
  52759. }
  52760. memset(pPg->pData, 0, pPager->pageSize);
  52761. IOTRACE(("ZERO %p %d\n", pPager, pgno));
  52762. }else{
  52763. assert( pPg->pPager==pPager );
  52764. pPager->aStat[PAGER_STAT_MISS]++;
  52765. rc = readDbPage(pPg);
  52766. if( rc!=SQLITE_OK ){
  52767. goto pager_acquire_err;
  52768. }
  52769. }
  52770. pager_set_pagehash(pPg);
  52771. }
  52772. return SQLITE_OK;
  52773. pager_acquire_err:
  52774. assert( rc!=SQLITE_OK );
  52775. if( pPg ){
  52776. sqlite3PcacheDrop(pPg);
  52777. }
  52778. pagerUnlockIfUnused(pPager);
  52779. *ppPage = 0;
  52780. return rc;
  52781. }
  52782. #if SQLITE_MAX_MMAP_SIZE>0
  52783. /* The page getter for when memory-mapped I/O is enabled */
  52784. static int getPageMMap(
  52785. Pager *pPager, /* The pager open on the database file */
  52786. Pgno pgno, /* Page number to fetch */
  52787. DbPage **ppPage, /* Write a pointer to the page here */
  52788. int flags /* PAGER_GET_XXX flags */
  52789. ){
  52790. int rc = SQLITE_OK;
  52791. PgHdr *pPg = 0;
  52792. u32 iFrame = 0; /* Frame to read from WAL file */
  52793. /* It is acceptable to use a read-only (mmap) page for any page except
  52794. ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY
  52795. ** flag was specified by the caller. And so long as the db is not a
  52796. ** temporary or in-memory database. */
  52797. const int bMmapOk = (pgno>1
  52798. && (pPager->eState==PAGER_READER || (flags & PAGER_GET_READONLY))
  52799. );
  52800. assert( USEFETCH(pPager) );
  52801. #ifdef SQLITE_HAS_CODEC
  52802. assert( pPager->xCodec==0 );
  52803. #endif
  52804. /* Optimization note: Adding the "pgno<=1" term before "pgno==0" here
  52805. ** allows the compiler optimizer to reuse the results of the "pgno>1"
  52806. ** test in the previous statement, and avoid testing pgno==0 in the
  52807. ** common case where pgno is large. */
  52808. if( pgno<=1 && pgno==0 ){
  52809. return SQLITE_CORRUPT_BKPT;
  52810. }
  52811. assert( pPager->eState>=PAGER_READER );
  52812. assert( assert_pager_state(pPager) );
  52813. assert( pPager->hasHeldSharedLock==1 );
  52814. assert( pPager->errCode==SQLITE_OK );
  52815. if( bMmapOk && pagerUseWal(pPager) ){
  52816. rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
  52817. if( rc!=SQLITE_OK ){
  52818. *ppPage = 0;
  52819. return rc;
  52820. }
  52821. }
  52822. if( bMmapOk && iFrame==0 ){
  52823. void *pData = 0;
  52824. rc = sqlite3OsFetch(pPager->fd,
  52825. (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData
  52826. );
  52827. if( rc==SQLITE_OK && pData ){
  52828. if( pPager->eState>PAGER_READER || pPager->tempFile ){
  52829. pPg = sqlite3PagerLookup(pPager, pgno);
  52830. }
  52831. if( pPg==0 ){
  52832. rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg);
  52833. }else{
  52834. sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData);
  52835. }
  52836. if( pPg ){
  52837. assert( rc==SQLITE_OK );
  52838. *ppPage = pPg;
  52839. return SQLITE_OK;
  52840. }
  52841. }
  52842. if( rc!=SQLITE_OK ){
  52843. *ppPage = 0;
  52844. return rc;
  52845. }
  52846. }
  52847. return getPageNormal(pPager, pgno, ppPage, flags);
  52848. }
  52849. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  52850. /* The page getter method for when the pager is an error state */
  52851. static int getPageError(
  52852. Pager *pPager, /* The pager open on the database file */
  52853. Pgno pgno, /* Page number to fetch */
  52854. DbPage **ppPage, /* Write a pointer to the page here */
  52855. int flags /* PAGER_GET_XXX flags */
  52856. ){
  52857. UNUSED_PARAMETER(pgno);
  52858. UNUSED_PARAMETER(flags);
  52859. assert( pPager->errCode!=SQLITE_OK );
  52860. *ppPage = 0;
  52861. return pPager->errCode;
  52862. }
  52863. /* Dispatch all page fetch requests to the appropriate getter method.
  52864. */
  52865. SQLITE_PRIVATE int sqlite3PagerGet(
  52866. Pager *pPager, /* The pager open on the database file */
  52867. Pgno pgno, /* Page number to fetch */
  52868. DbPage **ppPage, /* Write a pointer to the page here */
  52869. int flags /* PAGER_GET_XXX flags */
  52870. ){
  52871. return pPager->xGet(pPager, pgno, ppPage, flags);
  52872. }
  52873. /*
  52874. ** Acquire a page if it is already in the in-memory cache. Do
  52875. ** not read the page from disk. Return a pointer to the page,
  52876. ** or 0 if the page is not in cache.
  52877. **
  52878. ** See also sqlite3PagerGet(). The difference between this routine
  52879. ** and sqlite3PagerGet() is that _get() will go to the disk and read
  52880. ** in the page if the page is not already in cache. This routine
  52881. ** returns NULL if the page is not in cache or if a disk I/O error
  52882. ** has ever happened.
  52883. */
  52884. SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
  52885. sqlite3_pcache_page *pPage;
  52886. assert( pPager!=0 );
  52887. assert( pgno!=0 );
  52888. assert( pPager->pPCache!=0 );
  52889. pPage = sqlite3PcacheFetch(pPager->pPCache, pgno, 0);
  52890. assert( pPage==0 || pPager->hasHeldSharedLock );
  52891. if( pPage==0 ) return 0;
  52892. return sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pPage);
  52893. }
  52894. /*
  52895. ** Release a page reference.
  52896. **
  52897. ** The sqlite3PagerUnref() and sqlite3PagerUnrefNotNull() may only be
  52898. ** used if we know that the page being released is not the last page.
  52899. ** The btree layer always holds page1 open until the end, so these first
  52900. ** to routines can be used to release any page other than BtShared.pPage1.
  52901. **
  52902. ** Use sqlite3PagerUnrefPageOne() to release page1. This latter routine
  52903. ** checks the total number of outstanding pages and if the number of
  52904. ** pages reaches zero it drops the database lock.
  52905. */
  52906. SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage *pPg){
  52907. TESTONLY( Pager *pPager = pPg->pPager; )
  52908. assert( pPg!=0 );
  52909. if( pPg->flags & PGHDR_MMAP ){
  52910. assert( pPg->pgno!=1 ); /* Page1 is never memory mapped */
  52911. pagerReleaseMapPage(pPg);
  52912. }else{
  52913. sqlite3PcacheRelease(pPg);
  52914. }
  52915. /* Do not use this routine to release the last reference to page1 */
  52916. assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
  52917. }
  52918. SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
  52919. if( pPg ) sqlite3PagerUnrefNotNull(pPg);
  52920. }
  52921. SQLITE_PRIVATE void sqlite3PagerUnrefPageOne(DbPage *pPg){
  52922. Pager *pPager;
  52923. assert( pPg!=0 );
  52924. assert( pPg->pgno==1 );
  52925. assert( (pPg->flags & PGHDR_MMAP)==0 ); /* Page1 is never memory mapped */
  52926. pPager = pPg->pPager;
  52927. sqlite3PagerResetLockTimeout(pPager);
  52928. sqlite3PcacheRelease(pPg);
  52929. pagerUnlockIfUnused(pPager);
  52930. }
  52931. /*
  52932. ** This function is called at the start of every write transaction.
  52933. ** There must already be a RESERVED or EXCLUSIVE lock on the database
  52934. ** file when this routine is called.
  52935. **
  52936. ** Open the journal file for pager pPager and write a journal header
  52937. ** to the start of it. If there are active savepoints, open the sub-journal
  52938. ** as well. This function is only used when the journal file is being
  52939. ** opened to write a rollback log for a transaction. It is not used
  52940. ** when opening a hot journal file to roll it back.
  52941. **
  52942. ** If the journal file is already open (as it may be in exclusive mode),
  52943. ** then this function just writes a journal header to the start of the
  52944. ** already open file.
  52945. **
  52946. ** Whether or not the journal file is opened by this function, the
  52947. ** Pager.pInJournal bitvec structure is allocated.
  52948. **
  52949. ** Return SQLITE_OK if everything is successful. Otherwise, return
  52950. ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
  52951. ** an IO error code if opening or writing the journal file fails.
  52952. */
  52953. static int pager_open_journal(Pager *pPager){
  52954. int rc = SQLITE_OK; /* Return code */
  52955. sqlite3_vfs * const pVfs = pPager->pVfs; /* Local cache of vfs pointer */
  52956. assert( pPager->eState==PAGER_WRITER_LOCKED );
  52957. assert( assert_pager_state(pPager) );
  52958. assert( pPager->pInJournal==0 );
  52959. /* If already in the error state, this function is a no-op. But on
  52960. ** the other hand, this routine is never called if we are already in
  52961. ** an error state. */
  52962. if( NEVER(pPager->errCode) ) return pPager->errCode;
  52963. if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
  52964. pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
  52965. if( pPager->pInJournal==0 ){
  52966. return SQLITE_NOMEM_BKPT;
  52967. }
  52968. /* Open the journal file if it is not already open. */
  52969. if( !isOpen(pPager->jfd) ){
  52970. if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
  52971. sqlite3MemJournalOpen(pPager->jfd);
  52972. }else{
  52973. int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
  52974. int nSpill;
  52975. if( pPager->tempFile ){
  52976. flags |= (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL);
  52977. nSpill = sqlite3Config.nStmtSpill;
  52978. }else{
  52979. flags |= SQLITE_OPEN_MAIN_JOURNAL;
  52980. nSpill = jrnlBufferSize(pPager);
  52981. }
  52982. /* Verify that the database still has the same name as it did when
  52983. ** it was originally opened. */
  52984. rc = databaseIsUnmoved(pPager);
  52985. if( rc==SQLITE_OK ){
  52986. rc = sqlite3JournalOpen (
  52987. pVfs, pPager->zJournal, pPager->jfd, flags, nSpill
  52988. );
  52989. }
  52990. }
  52991. assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
  52992. }
  52993. /* Write the first journal header to the journal file and open
  52994. ** the sub-journal if necessary.
  52995. */
  52996. if( rc==SQLITE_OK ){
  52997. /* TODO: Check if all of these are really required. */
  52998. pPager->nRec = 0;
  52999. pPager->journalOff = 0;
  53000. pPager->setMaster = 0;
  53001. pPager->journalHdr = 0;
  53002. rc = writeJournalHdr(pPager);
  53003. }
  53004. }
  53005. if( rc!=SQLITE_OK ){
  53006. sqlite3BitvecDestroy(pPager->pInJournal);
  53007. pPager->pInJournal = 0;
  53008. }else{
  53009. assert( pPager->eState==PAGER_WRITER_LOCKED );
  53010. pPager->eState = PAGER_WRITER_CACHEMOD;
  53011. }
  53012. return rc;
  53013. }
  53014. /*
  53015. ** Begin a write-transaction on the specified pager object. If a
  53016. ** write-transaction has already been opened, this function is a no-op.
  53017. **
  53018. ** If the exFlag argument is false, then acquire at least a RESERVED
  53019. ** lock on the database file. If exFlag is true, then acquire at least
  53020. ** an EXCLUSIVE lock. If such a lock is already held, no locking
  53021. ** functions need be called.
  53022. **
  53023. ** If the subjInMemory argument is non-zero, then any sub-journal opened
  53024. ** within this transaction will be opened as an in-memory file. This
  53025. ** has no effect if the sub-journal is already opened (as it may be when
  53026. ** running in exclusive mode) or if the transaction does not require a
  53027. ** sub-journal. If the subjInMemory argument is zero, then any required
  53028. ** sub-journal is implemented in-memory if pPager is an in-memory database,
  53029. ** or using a temporary file otherwise.
  53030. */
  53031. SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
  53032. int rc = SQLITE_OK;
  53033. if( pPager->errCode ) return pPager->errCode;
  53034. assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
  53035. pPager->subjInMemory = (u8)subjInMemory;
  53036. if( ALWAYS(pPager->eState==PAGER_READER) ){
  53037. assert( pPager->pInJournal==0 );
  53038. if( pagerUseWal(pPager) ){
  53039. /* If the pager is configured to use locking_mode=exclusive, and an
  53040. ** exclusive lock on the database is not already held, obtain it now.
  53041. */
  53042. if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
  53043. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  53044. if( rc!=SQLITE_OK ){
  53045. return rc;
  53046. }
  53047. (void)sqlite3WalExclusiveMode(pPager->pWal, 1);
  53048. }
  53049. /* Grab the write lock on the log file. If successful, upgrade to
  53050. ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
  53051. ** The busy-handler is not invoked if another connection already
  53052. ** holds the write-lock. If possible, the upper layer will call it.
  53053. */
  53054. rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
  53055. }else{
  53056. /* Obtain a RESERVED lock on the database file. If the exFlag parameter
  53057. ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
  53058. ** busy-handler callback can be used when upgrading to the EXCLUSIVE
  53059. ** lock, but not when obtaining the RESERVED lock.
  53060. */
  53061. rc = pagerLockDb(pPager, RESERVED_LOCK);
  53062. if( rc==SQLITE_OK && exFlag ){
  53063. rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
  53064. }
  53065. }
  53066. if( rc==SQLITE_OK ){
  53067. /* Change to WRITER_LOCKED state.
  53068. **
  53069. ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
  53070. ** when it has an open transaction, but never to DBMOD or FINISHED.
  53071. ** This is because in those states the code to roll back savepoint
  53072. ** transactions may copy data from the sub-journal into the database
  53073. ** file as well as into the page cache. Which would be incorrect in
  53074. ** WAL mode.
  53075. */
  53076. pPager->eState = PAGER_WRITER_LOCKED;
  53077. pPager->dbHintSize = pPager->dbSize;
  53078. pPager->dbFileSize = pPager->dbSize;
  53079. pPager->dbOrigSize = pPager->dbSize;
  53080. pPager->journalOff = 0;
  53081. }
  53082. assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
  53083. assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
  53084. assert( assert_pager_state(pPager) );
  53085. }
  53086. PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
  53087. return rc;
  53088. }
  53089. /*
  53090. ** Write page pPg onto the end of the rollback journal.
  53091. */
  53092. static SQLITE_NOINLINE int pagerAddPageToRollbackJournal(PgHdr *pPg){
  53093. Pager *pPager = pPg->pPager;
  53094. int rc;
  53095. u32 cksum;
  53096. char *pData2;
  53097. i64 iOff = pPager->journalOff;
  53098. /* We should never write to the journal file the page that
  53099. ** contains the database locks. The following assert verifies
  53100. ** that we do not. */
  53101. assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
  53102. assert( pPager->journalHdr<=pPager->journalOff );
  53103. CODEC2(pPager, pPg->pData, pPg->pgno, 7, return SQLITE_NOMEM_BKPT, pData2);
  53104. cksum = pager_cksum(pPager, (u8*)pData2);
  53105. /* Even if an IO or diskfull error occurs while journalling the
  53106. ** page in the block above, set the need-sync flag for the page.
  53107. ** Otherwise, when the transaction is rolled back, the logic in
  53108. ** playback_one_page() will think that the page needs to be restored
  53109. ** in the database file. And if an IO error occurs while doing so,
  53110. ** then corruption may follow.
  53111. */
  53112. pPg->flags |= PGHDR_NEED_SYNC;
  53113. rc = write32bits(pPager->jfd, iOff, pPg->pgno);
  53114. if( rc!=SQLITE_OK ) return rc;
  53115. rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
  53116. if( rc!=SQLITE_OK ) return rc;
  53117. rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
  53118. if( rc!=SQLITE_OK ) return rc;
  53119. IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
  53120. pPager->journalOff, pPager->pageSize));
  53121. PAGER_INCR(sqlite3_pager_writej_count);
  53122. PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
  53123. PAGERID(pPager), pPg->pgno,
  53124. ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
  53125. pPager->journalOff += 8 + pPager->pageSize;
  53126. pPager->nRec++;
  53127. assert( pPager->pInJournal!=0 );
  53128. rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
  53129. testcase( rc==SQLITE_NOMEM );
  53130. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  53131. rc |= addToSavepointBitvecs(pPager, pPg->pgno);
  53132. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  53133. return rc;
  53134. }
  53135. /*
  53136. ** Mark a single data page as writeable. The page is written into the
  53137. ** main journal or sub-journal as required. If the page is written into
  53138. ** one of the journals, the corresponding bit is set in the
  53139. ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
  53140. ** of any open savepoints as appropriate.
  53141. */
  53142. static int pager_write(PgHdr *pPg){
  53143. Pager *pPager = pPg->pPager;
  53144. int rc = SQLITE_OK;
  53145. /* This routine is not called unless a write-transaction has already
  53146. ** been started. The journal file may or may not be open at this point.
  53147. ** It is never called in the ERROR state.
  53148. */
  53149. assert( pPager->eState==PAGER_WRITER_LOCKED
  53150. || pPager->eState==PAGER_WRITER_CACHEMOD
  53151. || pPager->eState==PAGER_WRITER_DBMOD
  53152. );
  53153. assert( assert_pager_state(pPager) );
  53154. assert( pPager->errCode==0 );
  53155. assert( pPager->readOnly==0 );
  53156. CHECK_PAGE(pPg);
  53157. /* The journal file needs to be opened. Higher level routines have already
  53158. ** obtained the necessary locks to begin the write-transaction, but the
  53159. ** rollback journal might not yet be open. Open it now if this is the case.
  53160. **
  53161. ** This is done before calling sqlite3PcacheMakeDirty() on the page.
  53162. ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
  53163. ** an error might occur and the pager would end up in WRITER_LOCKED state
  53164. ** with pages marked as dirty in the cache.
  53165. */
  53166. if( pPager->eState==PAGER_WRITER_LOCKED ){
  53167. rc = pager_open_journal(pPager);
  53168. if( rc!=SQLITE_OK ) return rc;
  53169. }
  53170. assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
  53171. assert( assert_pager_state(pPager) );
  53172. /* Mark the page that is about to be modified as dirty. */
  53173. sqlite3PcacheMakeDirty(pPg);
  53174. /* If a rollback journal is in use, them make sure the page that is about
  53175. ** to change is in the rollback journal, or if the page is a new page off
  53176. ** then end of the file, make sure it is marked as PGHDR_NEED_SYNC.
  53177. */
  53178. assert( (pPager->pInJournal!=0) == isOpen(pPager->jfd) );
  53179. if( pPager->pInJournal!=0
  53180. && sqlite3BitvecTestNotNull(pPager->pInJournal, pPg->pgno)==0
  53181. ){
  53182. assert( pagerUseWal(pPager)==0 );
  53183. if( pPg->pgno<=pPager->dbOrigSize ){
  53184. rc = pagerAddPageToRollbackJournal(pPg);
  53185. if( rc!=SQLITE_OK ){
  53186. return rc;
  53187. }
  53188. }else{
  53189. if( pPager->eState!=PAGER_WRITER_DBMOD ){
  53190. pPg->flags |= PGHDR_NEED_SYNC;
  53191. }
  53192. PAGERTRACE(("APPEND %d page %d needSync=%d\n",
  53193. PAGERID(pPager), pPg->pgno,
  53194. ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
  53195. }
  53196. }
  53197. /* The PGHDR_DIRTY bit is set above when the page was added to the dirty-list
  53198. ** and before writing the page into the rollback journal. Wait until now,
  53199. ** after the page has been successfully journalled, before setting the
  53200. ** PGHDR_WRITEABLE bit that indicates that the page can be safely modified.
  53201. */
  53202. pPg->flags |= PGHDR_WRITEABLE;
  53203. /* If the statement journal is open and the page is not in it,
  53204. ** then write the page into the statement journal.
  53205. */
  53206. if( pPager->nSavepoint>0 ){
  53207. rc = subjournalPageIfRequired(pPg);
  53208. }
  53209. /* Update the database size and return. */
  53210. if( pPager->dbSize<pPg->pgno ){
  53211. pPager->dbSize = pPg->pgno;
  53212. }
  53213. return rc;
  53214. }
  53215. /*
  53216. ** This is a variant of sqlite3PagerWrite() that runs when the sector size
  53217. ** is larger than the page size. SQLite makes the (reasonable) assumption that
  53218. ** all bytes of a sector are written together by hardware. Hence, all bytes of
  53219. ** a sector need to be journalled in case of a power loss in the middle of
  53220. ** a write.
  53221. **
  53222. ** Usually, the sector size is less than or equal to the page size, in which
  53223. ** case pages can be individually written. This routine only runs in the
  53224. ** exceptional case where the page size is smaller than the sector size.
  53225. */
  53226. static SQLITE_NOINLINE int pagerWriteLargeSector(PgHdr *pPg){
  53227. int rc = SQLITE_OK; /* Return code */
  53228. Pgno nPageCount; /* Total number of pages in database file */
  53229. Pgno pg1; /* First page of the sector pPg is located on. */
  53230. int nPage = 0; /* Number of pages starting at pg1 to journal */
  53231. int ii; /* Loop counter */
  53232. int needSync = 0; /* True if any page has PGHDR_NEED_SYNC */
  53233. Pager *pPager = pPg->pPager; /* The pager that owns pPg */
  53234. Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
  53235. /* Set the doNotSpill NOSYNC bit to 1. This is because we cannot allow
  53236. ** a journal header to be written between the pages journaled by
  53237. ** this function.
  53238. */
  53239. assert( !MEMDB );
  53240. assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)==0 );
  53241. pPager->doNotSpill |= SPILLFLAG_NOSYNC;
  53242. /* This trick assumes that both the page-size and sector-size are
  53243. ** an integer power of 2. It sets variable pg1 to the identifier
  53244. ** of the first page of the sector pPg is located on.
  53245. */
  53246. pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
  53247. nPageCount = pPager->dbSize;
  53248. if( pPg->pgno>nPageCount ){
  53249. nPage = (pPg->pgno - pg1)+1;
  53250. }else if( (pg1+nPagePerSector-1)>nPageCount ){
  53251. nPage = nPageCount+1-pg1;
  53252. }else{
  53253. nPage = nPagePerSector;
  53254. }
  53255. assert(nPage>0);
  53256. assert(pg1<=pPg->pgno);
  53257. assert((pg1+nPage)>pPg->pgno);
  53258. for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
  53259. Pgno pg = pg1+ii;
  53260. PgHdr *pPage;
  53261. if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
  53262. if( pg!=PAGER_MJ_PGNO(pPager) ){
  53263. rc = sqlite3PagerGet(pPager, pg, &pPage, 0);
  53264. if( rc==SQLITE_OK ){
  53265. rc = pager_write(pPage);
  53266. if( pPage->flags&PGHDR_NEED_SYNC ){
  53267. needSync = 1;
  53268. }
  53269. sqlite3PagerUnrefNotNull(pPage);
  53270. }
  53271. }
  53272. }else if( (pPage = sqlite3PagerLookup(pPager, pg))!=0 ){
  53273. if( pPage->flags&PGHDR_NEED_SYNC ){
  53274. needSync = 1;
  53275. }
  53276. sqlite3PagerUnrefNotNull(pPage);
  53277. }
  53278. }
  53279. /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
  53280. ** starting at pg1, then it needs to be set for all of them. Because
  53281. ** writing to any of these nPage pages may damage the others, the
  53282. ** journal file must contain sync()ed copies of all of them
  53283. ** before any of them can be written out to the database file.
  53284. */
  53285. if( rc==SQLITE_OK && needSync ){
  53286. assert( !MEMDB );
  53287. for(ii=0; ii<nPage; ii++){
  53288. PgHdr *pPage = sqlite3PagerLookup(pPager, pg1+ii);
  53289. if( pPage ){
  53290. pPage->flags |= PGHDR_NEED_SYNC;
  53291. sqlite3PagerUnrefNotNull(pPage);
  53292. }
  53293. }
  53294. }
  53295. assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)!=0 );
  53296. pPager->doNotSpill &= ~SPILLFLAG_NOSYNC;
  53297. return rc;
  53298. }
  53299. /*
  53300. ** Mark a data page as writeable. This routine must be called before
  53301. ** making changes to a page. The caller must check the return value
  53302. ** of this function and be careful not to change any page data unless
  53303. ** this routine returns SQLITE_OK.
  53304. **
  53305. ** The difference between this function and pager_write() is that this
  53306. ** function also deals with the special case where 2 or more pages
  53307. ** fit on a single disk sector. In this case all co-resident pages
  53308. ** must have been written to the journal file before returning.
  53309. **
  53310. ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
  53311. ** as appropriate. Otherwise, SQLITE_OK.
  53312. */
  53313. SQLITE_PRIVATE int sqlite3PagerWrite(PgHdr *pPg){
  53314. Pager *pPager = pPg->pPager;
  53315. assert( (pPg->flags & PGHDR_MMAP)==0 );
  53316. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  53317. assert( assert_pager_state(pPager) );
  53318. if( (pPg->flags & PGHDR_WRITEABLE)!=0 && pPager->dbSize>=pPg->pgno ){
  53319. if( pPager->nSavepoint ) return subjournalPageIfRequired(pPg);
  53320. return SQLITE_OK;
  53321. }else if( pPager->errCode ){
  53322. return pPager->errCode;
  53323. }else if( pPager->sectorSize > (u32)pPager->pageSize ){
  53324. assert( pPager->tempFile==0 );
  53325. return pagerWriteLargeSector(pPg);
  53326. }else{
  53327. return pager_write(pPg);
  53328. }
  53329. }
  53330. /*
  53331. ** Return TRUE if the page given in the argument was previously passed
  53332. ** to sqlite3PagerWrite(). In other words, return TRUE if it is ok
  53333. ** to change the content of the page.
  53334. */
  53335. #ifndef NDEBUG
  53336. SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
  53337. return pPg->flags & PGHDR_WRITEABLE;
  53338. }
  53339. #endif
  53340. /*
  53341. ** A call to this routine tells the pager that it is not necessary to
  53342. ** write the information on page pPg back to the disk, even though
  53343. ** that page might be marked as dirty. This happens, for example, when
  53344. ** the page has been added as a leaf of the freelist and so its
  53345. ** content no longer matters.
  53346. **
  53347. ** The overlying software layer calls this routine when all of the data
  53348. ** on the given page is unused. The pager marks the page as clean so
  53349. ** that it does not get written to disk.
  53350. **
  53351. ** Tests show that this optimization can quadruple the speed of large
  53352. ** DELETE operations.
  53353. **
  53354. ** This optimization cannot be used with a temp-file, as the page may
  53355. ** have been dirty at the start of the transaction. In that case, if
  53356. ** memory pressure forces page pPg out of the cache, the data does need
  53357. ** to be written out to disk so that it may be read back in if the
  53358. ** current transaction is rolled back.
  53359. */
  53360. SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
  53361. Pager *pPager = pPg->pPager;
  53362. if( !pPager->tempFile && (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
  53363. PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
  53364. IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
  53365. pPg->flags |= PGHDR_DONT_WRITE;
  53366. pPg->flags &= ~PGHDR_WRITEABLE;
  53367. testcase( pPg->flags & PGHDR_NEED_SYNC );
  53368. pager_set_pagehash(pPg);
  53369. }
  53370. }
  53371. /*
  53372. ** This routine is called to increment the value of the database file
  53373. ** change-counter, stored as a 4-byte big-endian integer starting at
  53374. ** byte offset 24 of the pager file. The secondary change counter at
  53375. ** 92 is also updated, as is the SQLite version number at offset 96.
  53376. **
  53377. ** But this only happens if the pPager->changeCountDone flag is false.
  53378. ** To avoid excess churning of page 1, the update only happens once.
  53379. ** See also the pager_write_changecounter() routine that does an
  53380. ** unconditional update of the change counters.
  53381. **
  53382. ** If the isDirectMode flag is zero, then this is done by calling
  53383. ** sqlite3PagerWrite() on page 1, then modifying the contents of the
  53384. ** page data. In this case the file will be updated when the current
  53385. ** transaction is committed.
  53386. **
  53387. ** The isDirectMode flag may only be non-zero if the library was compiled
  53388. ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
  53389. ** if isDirect is non-zero, then the database file is updated directly
  53390. ** by writing an updated version of page 1 using a call to the
  53391. ** sqlite3OsWrite() function.
  53392. */
  53393. static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
  53394. int rc = SQLITE_OK;
  53395. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  53396. || pPager->eState==PAGER_WRITER_DBMOD
  53397. );
  53398. assert( assert_pager_state(pPager) );
  53399. /* Declare and initialize constant integer 'isDirect'. If the
  53400. ** atomic-write optimization is enabled in this build, then isDirect
  53401. ** is initialized to the value passed as the isDirectMode parameter
  53402. ** to this function. Otherwise, it is always set to zero.
  53403. **
  53404. ** The idea is that if the atomic-write optimization is not
  53405. ** enabled at compile time, the compiler can omit the tests of
  53406. ** 'isDirect' below, as well as the block enclosed in the
  53407. ** "if( isDirect )" condition.
  53408. */
  53409. #ifndef SQLITE_ENABLE_ATOMIC_WRITE
  53410. # define DIRECT_MODE 0
  53411. assert( isDirectMode==0 );
  53412. UNUSED_PARAMETER(isDirectMode);
  53413. #else
  53414. # define DIRECT_MODE isDirectMode
  53415. #endif
  53416. if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){
  53417. PgHdr *pPgHdr; /* Reference to page 1 */
  53418. assert( !pPager->tempFile && isOpen(pPager->fd) );
  53419. /* Open page 1 of the file for writing. */
  53420. rc = sqlite3PagerGet(pPager, 1, &pPgHdr, 0);
  53421. assert( pPgHdr==0 || rc==SQLITE_OK );
  53422. /* If page one was fetched successfully, and this function is not
  53423. ** operating in direct-mode, make page 1 writable. When not in
  53424. ** direct mode, page 1 is always held in cache and hence the PagerGet()
  53425. ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
  53426. */
  53427. if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
  53428. rc = sqlite3PagerWrite(pPgHdr);
  53429. }
  53430. if( rc==SQLITE_OK ){
  53431. /* Actually do the update of the change counter */
  53432. pager_write_changecounter(pPgHdr);
  53433. /* If running in direct mode, write the contents of page 1 to the file. */
  53434. if( DIRECT_MODE ){
  53435. const void *zBuf;
  53436. assert( pPager->dbFileSize>0 );
  53437. CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM_BKPT, zBuf);
  53438. if( rc==SQLITE_OK ){
  53439. rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
  53440. pPager->aStat[PAGER_STAT_WRITE]++;
  53441. }
  53442. if( rc==SQLITE_OK ){
  53443. /* Update the pager's copy of the change-counter. Otherwise, the
  53444. ** next time a read transaction is opened the cache will be
  53445. ** flushed (as the change-counter values will not match). */
  53446. const void *pCopy = (const void *)&((const char *)zBuf)[24];
  53447. memcpy(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers));
  53448. pPager->changeCountDone = 1;
  53449. }
  53450. }else{
  53451. pPager->changeCountDone = 1;
  53452. }
  53453. }
  53454. /* Release the page reference. */
  53455. sqlite3PagerUnref(pPgHdr);
  53456. }
  53457. return rc;
  53458. }
  53459. /*
  53460. ** Sync the database file to disk. This is a no-op for in-memory databases
  53461. ** or pages with the Pager.noSync flag set.
  53462. **
  53463. ** If successful, or if called on a pager for which it is a no-op, this
  53464. ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
  53465. */
  53466. SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster){
  53467. int rc = SQLITE_OK;
  53468. void *pArg = (void*)zMaster;
  53469. rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC, pArg);
  53470. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  53471. if( rc==SQLITE_OK && !pPager->noSync ){
  53472. assert( !MEMDB );
  53473. rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
  53474. }
  53475. return rc;
  53476. }
  53477. /*
  53478. ** This function may only be called while a write-transaction is active in
  53479. ** rollback. If the connection is in WAL mode, this call is a no-op.
  53480. ** Otherwise, if the connection does not already have an EXCLUSIVE lock on
  53481. ** the database file, an attempt is made to obtain one.
  53482. **
  53483. ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
  53484. ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
  53485. ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
  53486. ** returned.
  53487. */
  53488. SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
  53489. int rc = pPager->errCode;
  53490. assert( assert_pager_state(pPager) );
  53491. if( rc==SQLITE_OK ){
  53492. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  53493. || pPager->eState==PAGER_WRITER_DBMOD
  53494. || pPager->eState==PAGER_WRITER_LOCKED
  53495. );
  53496. assert( assert_pager_state(pPager) );
  53497. if( 0==pagerUseWal(pPager) ){
  53498. rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
  53499. }
  53500. }
  53501. return rc;
  53502. }
  53503. /*
  53504. ** Sync the database file for the pager pPager. zMaster points to the name
  53505. ** of a master journal file that should be written into the individual
  53506. ** journal file. zMaster may be NULL, which is interpreted as no master
  53507. ** journal (a single database transaction).
  53508. **
  53509. ** This routine ensures that:
  53510. **
  53511. ** * The database file change-counter is updated,
  53512. ** * the journal is synced (unless the atomic-write optimization is used),
  53513. ** * all dirty pages are written to the database file,
  53514. ** * the database file is truncated (if required), and
  53515. ** * the database file synced.
  53516. **
  53517. ** The only thing that remains to commit the transaction is to finalize
  53518. ** (delete, truncate or zero the first part of) the journal file (or
  53519. ** delete the master journal file if specified).
  53520. **
  53521. ** Note that if zMaster==NULL, this does not overwrite a previous value
  53522. ** passed to an sqlite3PagerCommitPhaseOne() call.
  53523. **
  53524. ** If the final parameter - noSync - is true, then the database file itself
  53525. ** is not synced. The caller must call sqlite3PagerSync() directly to
  53526. ** sync the database file before calling CommitPhaseTwo() to delete the
  53527. ** journal file in this case.
  53528. */
  53529. SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
  53530. Pager *pPager, /* Pager object */
  53531. const char *zMaster, /* If not NULL, the master journal name */
  53532. int noSync /* True to omit the xSync on the db file */
  53533. ){
  53534. int rc = SQLITE_OK; /* Return code */
  53535. assert( pPager->eState==PAGER_WRITER_LOCKED
  53536. || pPager->eState==PAGER_WRITER_CACHEMOD
  53537. || pPager->eState==PAGER_WRITER_DBMOD
  53538. || pPager->eState==PAGER_ERROR
  53539. );
  53540. assert( assert_pager_state(pPager) );
  53541. /* If a prior error occurred, report that error again. */
  53542. if( NEVER(pPager->errCode) ) return pPager->errCode;
  53543. /* Provide the ability to easily simulate an I/O error during testing */
  53544. if( sqlite3FaultSim(400) ) return SQLITE_IOERR;
  53545. PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
  53546. pPager->zFilename, zMaster, pPager->dbSize));
  53547. /* If no database changes have been made, return early. */
  53548. if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
  53549. assert( MEMDB==0 || pPager->tempFile );
  53550. assert( isOpen(pPager->fd) || pPager->tempFile );
  53551. if( 0==pagerFlushOnCommit(pPager, 1) ){
  53552. /* If this is an in-memory db, or no pages have been written to, or this
  53553. ** function has already been called, it is mostly a no-op. However, any
  53554. ** backup in progress needs to be restarted. */
  53555. sqlite3BackupRestart(pPager->pBackup);
  53556. }else{
  53557. PgHdr *pList;
  53558. if( pagerUseWal(pPager) ){
  53559. PgHdr *pPageOne = 0;
  53560. pList = sqlite3PcacheDirtyList(pPager->pPCache);
  53561. if( pList==0 ){
  53562. /* Must have at least one page for the WAL commit flag.
  53563. ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
  53564. rc = sqlite3PagerGet(pPager, 1, &pPageOne, 0);
  53565. pList = pPageOne;
  53566. pList->pDirty = 0;
  53567. }
  53568. assert( rc==SQLITE_OK );
  53569. if( ALWAYS(pList) ){
  53570. rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
  53571. }
  53572. sqlite3PagerUnref(pPageOne);
  53573. if( rc==SQLITE_OK ){
  53574. sqlite3PcacheCleanAll(pPager->pPCache);
  53575. }
  53576. }else{
  53577. /* The bBatch boolean is true if the batch-atomic-write commit method
  53578. ** should be used. No rollback journal is created if batch-atomic-write
  53579. ** is enabled.
  53580. */
  53581. #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
  53582. sqlite3_file *fd = pPager->fd;
  53583. int bBatch = zMaster==0 /* An SQLITE_IOCAP_BATCH_ATOMIC commit */
  53584. && (sqlite3OsDeviceCharacteristics(fd) & SQLITE_IOCAP_BATCH_ATOMIC)
  53585. && !pPager->noSync
  53586. && sqlite3JournalIsInMemory(pPager->jfd);
  53587. #else
  53588. # define bBatch 0
  53589. #endif
  53590. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  53591. /* The following block updates the change-counter. Exactly how it
  53592. ** does this depends on whether or not the atomic-update optimization
  53593. ** was enabled at compile time, and if this transaction meets the
  53594. ** runtime criteria to use the operation:
  53595. **
  53596. ** * The file-system supports the atomic-write property for
  53597. ** blocks of size page-size, and
  53598. ** * This commit is not part of a multi-file transaction, and
  53599. ** * Exactly one page has been modified and store in the journal file.
  53600. **
  53601. ** If the optimization was not enabled at compile time, then the
  53602. ** pager_incr_changecounter() function is called to update the change
  53603. ** counter in 'indirect-mode'. If the optimization is compiled in but
  53604. ** is not applicable to this transaction, call sqlite3JournalCreate()
  53605. ** to make sure the journal file has actually been created, then call
  53606. ** pager_incr_changecounter() to update the change-counter in indirect
  53607. ** mode.
  53608. **
  53609. ** Otherwise, if the optimization is both enabled and applicable,
  53610. ** then call pager_incr_changecounter() to update the change-counter
  53611. ** in 'direct' mode. In this case the journal file will never be
  53612. ** created for this transaction.
  53613. */
  53614. if( bBatch==0 ){
  53615. PgHdr *pPg;
  53616. assert( isOpen(pPager->jfd)
  53617. || pPager->journalMode==PAGER_JOURNALMODE_OFF
  53618. || pPager->journalMode==PAGER_JOURNALMODE_WAL
  53619. );
  53620. if( !zMaster && isOpen(pPager->jfd)
  53621. && pPager->journalOff==jrnlBufferSize(pPager)
  53622. && pPager->dbSize>=pPager->dbOrigSize
  53623. && (!(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
  53624. ){
  53625. /* Update the db file change counter via the direct-write method. The
  53626. ** following call will modify the in-memory representation of page 1
  53627. ** to include the updated change counter and then write page 1
  53628. ** directly to the database file. Because of the atomic-write
  53629. ** property of the host file-system, this is safe.
  53630. */
  53631. rc = pager_incr_changecounter(pPager, 1);
  53632. }else{
  53633. rc = sqlite3JournalCreate(pPager->jfd);
  53634. if( rc==SQLITE_OK ){
  53635. rc = pager_incr_changecounter(pPager, 0);
  53636. }
  53637. }
  53638. }
  53639. #else /* SQLITE_ENABLE_ATOMIC_WRITE */
  53640. #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
  53641. if( zMaster ){
  53642. rc = sqlite3JournalCreate(pPager->jfd);
  53643. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  53644. assert( bBatch==0 );
  53645. }
  53646. #endif
  53647. rc = pager_incr_changecounter(pPager, 0);
  53648. #endif /* !SQLITE_ENABLE_ATOMIC_WRITE */
  53649. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  53650. /* Write the master journal name into the journal file. If a master
  53651. ** journal file name has already been written to the journal file,
  53652. ** or if zMaster is NULL (no master journal), then this call is a no-op.
  53653. */
  53654. rc = writeMasterJournal(pPager, zMaster);
  53655. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  53656. /* Sync the journal file and write all dirty pages to the database.
  53657. ** If the atomic-update optimization is being used, this sync will not
  53658. ** create the journal file or perform any real IO.
  53659. **
  53660. ** Because the change-counter page was just modified, unless the
  53661. ** atomic-update optimization is used it is almost certain that the
  53662. ** journal requires a sync here. However, in locking_mode=exclusive
  53663. ** on a system under memory pressure it is just possible that this is
  53664. ** not the case. In this case it is likely enough that the redundant
  53665. ** xSync() call will be changed to a no-op by the OS anyhow.
  53666. */
  53667. rc = syncJournal(pPager, 0);
  53668. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  53669. pList = sqlite3PcacheDirtyList(pPager->pPCache);
  53670. #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
  53671. if( bBatch ){
  53672. rc = sqlite3OsFileControl(fd, SQLITE_FCNTL_BEGIN_ATOMIC_WRITE, 0);
  53673. if( rc==SQLITE_OK ){
  53674. rc = pager_write_pagelist(pPager, pList);
  53675. if( rc==SQLITE_OK ){
  53676. rc = sqlite3OsFileControl(fd, SQLITE_FCNTL_COMMIT_ATOMIC_WRITE, 0);
  53677. }
  53678. if( rc!=SQLITE_OK ){
  53679. sqlite3OsFileControlHint(fd, SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE, 0);
  53680. }
  53681. }
  53682. if( (rc&0xFF)==SQLITE_IOERR && rc!=SQLITE_IOERR_NOMEM ){
  53683. rc = sqlite3JournalCreate(pPager->jfd);
  53684. if( rc!=SQLITE_OK ){
  53685. sqlite3OsClose(pPager->jfd);
  53686. goto commit_phase_one_exit;
  53687. }
  53688. bBatch = 0;
  53689. }else{
  53690. sqlite3OsClose(pPager->jfd);
  53691. }
  53692. }
  53693. #endif /* SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
  53694. if( bBatch==0 ){
  53695. rc = pager_write_pagelist(pPager, pList);
  53696. }
  53697. if( rc!=SQLITE_OK ){
  53698. assert( rc!=SQLITE_IOERR_BLOCKED );
  53699. goto commit_phase_one_exit;
  53700. }
  53701. sqlite3PcacheCleanAll(pPager->pPCache);
  53702. /* If the file on disk is smaller than the database image, use
  53703. ** pager_truncate to grow the file here. This can happen if the database
  53704. ** image was extended as part of the current transaction and then the
  53705. ** last page in the db image moved to the free-list. In this case the
  53706. ** last page is never written out to disk, leaving the database file
  53707. ** undersized. Fix this now if it is the case. */
  53708. if( pPager->dbSize>pPager->dbFileSize ){
  53709. Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
  53710. assert( pPager->eState==PAGER_WRITER_DBMOD );
  53711. rc = pager_truncate(pPager, nNew);
  53712. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  53713. }
  53714. /* Finally, sync the database file. */
  53715. if( !noSync ){
  53716. rc = sqlite3PagerSync(pPager, zMaster);
  53717. }
  53718. IOTRACE(("DBSYNC %p\n", pPager))
  53719. }
  53720. }
  53721. commit_phase_one_exit:
  53722. if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
  53723. pPager->eState = PAGER_WRITER_FINISHED;
  53724. }
  53725. return rc;
  53726. }
  53727. /*
  53728. ** When this function is called, the database file has been completely
  53729. ** updated to reflect the changes made by the current transaction and
  53730. ** synced to disk. The journal file still exists in the file-system
  53731. ** though, and if a failure occurs at this point it will eventually
  53732. ** be used as a hot-journal and the current transaction rolled back.
  53733. **
  53734. ** This function finalizes the journal file, either by deleting,
  53735. ** truncating or partially zeroing it, so that it cannot be used
  53736. ** for hot-journal rollback. Once this is done the transaction is
  53737. ** irrevocably committed.
  53738. **
  53739. ** If an error occurs, an IO error code is returned and the pager
  53740. ** moves into the error state. Otherwise, SQLITE_OK is returned.
  53741. */
  53742. SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
  53743. int rc = SQLITE_OK; /* Return code */
  53744. /* This routine should not be called if a prior error has occurred.
  53745. ** But if (due to a coding error elsewhere in the system) it does get
  53746. ** called, just return the same error code without doing anything. */
  53747. if( NEVER(pPager->errCode) ) return pPager->errCode;
  53748. assert( pPager->eState==PAGER_WRITER_LOCKED
  53749. || pPager->eState==PAGER_WRITER_FINISHED
  53750. || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
  53751. );
  53752. assert( assert_pager_state(pPager) );
  53753. /* An optimization. If the database was not actually modified during
  53754. ** this transaction, the pager is running in exclusive-mode and is
  53755. ** using persistent journals, then this function is a no-op.
  53756. **
  53757. ** The start of the journal file currently contains a single journal
  53758. ** header with the nRec field set to 0. If such a journal is used as
  53759. ** a hot-journal during hot-journal rollback, 0 changes will be made
  53760. ** to the database file. So there is no need to zero the journal
  53761. ** header. Since the pager is in exclusive mode, there is no need
  53762. ** to drop any locks either.
  53763. */
  53764. if( pPager->eState==PAGER_WRITER_LOCKED
  53765. && pPager->exclusiveMode
  53766. && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
  53767. ){
  53768. assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
  53769. pPager->eState = PAGER_READER;
  53770. return SQLITE_OK;
  53771. }
  53772. PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
  53773. pPager->iDataVersion++;
  53774. rc = pager_end_transaction(pPager, pPager->setMaster, 1);
  53775. return pager_error(pPager, rc);
  53776. }
  53777. /*
  53778. ** If a write transaction is open, then all changes made within the
  53779. ** transaction are reverted and the current write-transaction is closed.
  53780. ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
  53781. ** state if an error occurs.
  53782. **
  53783. ** If the pager is already in PAGER_ERROR state when this function is called,
  53784. ** it returns Pager.errCode immediately. No work is performed in this case.
  53785. **
  53786. ** Otherwise, in rollback mode, this function performs two functions:
  53787. **
  53788. ** 1) It rolls back the journal file, restoring all database file and
  53789. ** in-memory cache pages to the state they were in when the transaction
  53790. ** was opened, and
  53791. **
  53792. ** 2) It finalizes the journal file, so that it is not used for hot
  53793. ** rollback at any point in the future.
  53794. **
  53795. ** Finalization of the journal file (task 2) is only performed if the
  53796. ** rollback is successful.
  53797. **
  53798. ** In WAL mode, all cache-entries containing data modified within the
  53799. ** current transaction are either expelled from the cache or reverted to
  53800. ** their pre-transaction state by re-reading data from the database or
  53801. ** WAL files. The WAL transaction is then closed.
  53802. */
  53803. SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
  53804. int rc = SQLITE_OK; /* Return code */
  53805. PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
  53806. /* PagerRollback() is a no-op if called in READER or OPEN state. If
  53807. ** the pager is already in the ERROR state, the rollback is not
  53808. ** attempted here. Instead, the error code is returned to the caller.
  53809. */
  53810. assert( assert_pager_state(pPager) );
  53811. if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
  53812. if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
  53813. if( pagerUseWal(pPager) ){
  53814. int rc2;
  53815. rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
  53816. rc2 = pager_end_transaction(pPager, pPager->setMaster, 0);
  53817. if( rc==SQLITE_OK ) rc = rc2;
  53818. }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
  53819. int eState = pPager->eState;
  53820. rc = pager_end_transaction(pPager, 0, 0);
  53821. if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
  53822. /* This can happen using journal_mode=off. Move the pager to the error
  53823. ** state to indicate that the contents of the cache may not be trusted.
  53824. ** Any active readers will get SQLITE_ABORT.
  53825. */
  53826. pPager->errCode = SQLITE_ABORT;
  53827. pPager->eState = PAGER_ERROR;
  53828. setGetterMethod(pPager);
  53829. return rc;
  53830. }
  53831. }else{
  53832. rc = pager_playback(pPager, 0);
  53833. }
  53834. assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
  53835. assert( rc==SQLITE_OK || rc==SQLITE_FULL || rc==SQLITE_CORRUPT
  53836. || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR
  53837. || rc==SQLITE_CANTOPEN
  53838. );
  53839. /* If an error occurs during a ROLLBACK, we can no longer trust the pager
  53840. ** cache. So call pager_error() on the way out to make any error persistent.
  53841. */
  53842. return pager_error(pPager, rc);
  53843. }
  53844. /*
  53845. ** Return TRUE if the database file is opened read-only. Return FALSE
  53846. ** if the database is (in theory) writable.
  53847. */
  53848. SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
  53849. return pPager->readOnly;
  53850. }
  53851. #ifdef SQLITE_DEBUG
  53852. /*
  53853. ** Return the sum of the reference counts for all pages held by pPager.
  53854. */
  53855. SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
  53856. return sqlite3PcacheRefCount(pPager->pPCache);
  53857. }
  53858. #endif
  53859. /*
  53860. ** Return the approximate number of bytes of memory currently
  53861. ** used by the pager and its associated cache.
  53862. */
  53863. SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
  53864. int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
  53865. + 5*sizeof(void*);
  53866. return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
  53867. + sqlite3MallocSize(pPager)
  53868. + pPager->pageSize;
  53869. }
  53870. /*
  53871. ** Return the number of references to the specified page.
  53872. */
  53873. SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
  53874. return sqlite3PcachePageRefcount(pPage);
  53875. }
  53876. #ifdef SQLITE_TEST
  53877. /*
  53878. ** This routine is used for testing and analysis only.
  53879. */
  53880. SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
  53881. static int a[11];
  53882. a[0] = sqlite3PcacheRefCount(pPager->pPCache);
  53883. a[1] = sqlite3PcachePagecount(pPager->pPCache);
  53884. a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
  53885. a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
  53886. a[4] = pPager->eState;
  53887. a[5] = pPager->errCode;
  53888. a[6] = pPager->aStat[PAGER_STAT_HIT];
  53889. a[7] = pPager->aStat[PAGER_STAT_MISS];
  53890. a[8] = 0; /* Used to be pPager->nOvfl */
  53891. a[9] = pPager->nRead;
  53892. a[10] = pPager->aStat[PAGER_STAT_WRITE];
  53893. return a;
  53894. }
  53895. #endif
  53896. /*
  53897. ** Parameter eStat must be one of SQLITE_DBSTATUS_CACHE_HIT, _MISS, _WRITE,
  53898. ** or _WRITE+1. The SQLITE_DBSTATUS_CACHE_WRITE+1 case is a translation
  53899. ** of SQLITE_DBSTATUS_CACHE_SPILL. The _SPILL case is not contiguous because
  53900. ** it was added later.
  53901. **
  53902. ** Before returning, *pnVal is incremented by the
  53903. ** current cache hit or miss count, according to the value of eStat. If the
  53904. ** reset parameter is non-zero, the cache hit or miss count is zeroed before
  53905. ** returning.
  53906. */
  53907. SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
  53908. assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
  53909. || eStat==SQLITE_DBSTATUS_CACHE_MISS
  53910. || eStat==SQLITE_DBSTATUS_CACHE_WRITE
  53911. || eStat==SQLITE_DBSTATUS_CACHE_WRITE+1
  53912. );
  53913. assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS );
  53914. assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE );
  53915. assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1
  53916. && PAGER_STAT_WRITE==2 && PAGER_STAT_SPILL==3 );
  53917. eStat -= SQLITE_DBSTATUS_CACHE_HIT;
  53918. *pnVal += pPager->aStat[eStat];
  53919. if( reset ){
  53920. pPager->aStat[eStat] = 0;
  53921. }
  53922. }
  53923. /*
  53924. ** Return true if this is an in-memory or temp-file backed pager.
  53925. */
  53926. SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
  53927. return pPager->tempFile;
  53928. }
  53929. /*
  53930. ** Check that there are at least nSavepoint savepoints open. If there are
  53931. ** currently less than nSavepoints open, then open one or more savepoints
  53932. ** to make up the difference. If the number of savepoints is already
  53933. ** equal to nSavepoint, then this function is a no-op.
  53934. **
  53935. ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
  53936. ** occurs while opening the sub-journal file, then an IO error code is
  53937. ** returned. Otherwise, SQLITE_OK.
  53938. */
  53939. static SQLITE_NOINLINE int pagerOpenSavepoint(Pager *pPager, int nSavepoint){
  53940. int rc = SQLITE_OK; /* Return code */
  53941. int nCurrent = pPager->nSavepoint; /* Current number of savepoints */
  53942. int ii; /* Iterator variable */
  53943. PagerSavepoint *aNew; /* New Pager.aSavepoint array */
  53944. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  53945. assert( assert_pager_state(pPager) );
  53946. assert( nSavepoint>nCurrent && pPager->useJournal );
  53947. /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
  53948. ** if the allocation fails. Otherwise, zero the new portion in case a
  53949. ** malloc failure occurs while populating it in the for(...) loop below.
  53950. */
  53951. aNew = (PagerSavepoint *)sqlite3Realloc(
  53952. pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
  53953. );
  53954. if( !aNew ){
  53955. return SQLITE_NOMEM_BKPT;
  53956. }
  53957. memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
  53958. pPager->aSavepoint = aNew;
  53959. /* Populate the PagerSavepoint structures just allocated. */
  53960. for(ii=nCurrent; ii<nSavepoint; ii++){
  53961. aNew[ii].nOrig = pPager->dbSize;
  53962. if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
  53963. aNew[ii].iOffset = pPager->journalOff;
  53964. }else{
  53965. aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
  53966. }
  53967. aNew[ii].iSubRec = pPager->nSubRec;
  53968. aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
  53969. if( !aNew[ii].pInSavepoint ){
  53970. return SQLITE_NOMEM_BKPT;
  53971. }
  53972. if( pagerUseWal(pPager) ){
  53973. sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
  53974. }
  53975. pPager->nSavepoint = ii+1;
  53976. }
  53977. assert( pPager->nSavepoint==nSavepoint );
  53978. assertTruncateConstraint(pPager);
  53979. return rc;
  53980. }
  53981. SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
  53982. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  53983. assert( assert_pager_state(pPager) );
  53984. if( nSavepoint>pPager->nSavepoint && pPager->useJournal ){
  53985. return pagerOpenSavepoint(pPager, nSavepoint);
  53986. }else{
  53987. return SQLITE_OK;
  53988. }
  53989. }
  53990. /*
  53991. ** This function is called to rollback or release (commit) a savepoint.
  53992. ** The savepoint to release or rollback need not be the most recently
  53993. ** created savepoint.
  53994. **
  53995. ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
  53996. ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
  53997. ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
  53998. ** that have occurred since the specified savepoint was created.
  53999. **
  54000. ** The savepoint to rollback or release is identified by parameter
  54001. ** iSavepoint. A value of 0 means to operate on the outermost savepoint
  54002. ** (the first created). A value of (Pager.nSavepoint-1) means operate
  54003. ** on the most recently created savepoint. If iSavepoint is greater than
  54004. ** (Pager.nSavepoint-1), then this function is a no-op.
  54005. **
  54006. ** If a negative value is passed to this function, then the current
  54007. ** transaction is rolled back. This is different to calling
  54008. ** sqlite3PagerRollback() because this function does not terminate
  54009. ** the transaction or unlock the database, it just restores the
  54010. ** contents of the database to its original state.
  54011. **
  54012. ** In any case, all savepoints with an index greater than iSavepoint
  54013. ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
  54014. ** then savepoint iSavepoint is also destroyed.
  54015. **
  54016. ** This function may return SQLITE_NOMEM if a memory allocation fails,
  54017. ** or an IO error code if an IO error occurs while rolling back a
  54018. ** savepoint. If no errors occur, SQLITE_OK is returned.
  54019. */
  54020. SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
  54021. int rc = pPager->errCode;
  54022. #ifdef SQLITE_ENABLE_ZIPVFS
  54023. if( op==SAVEPOINT_RELEASE ) rc = SQLITE_OK;
  54024. #endif
  54025. assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
  54026. assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
  54027. if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
  54028. int ii; /* Iterator variable */
  54029. int nNew; /* Number of remaining savepoints after this op. */
  54030. /* Figure out how many savepoints will still be active after this
  54031. ** operation. Store this value in nNew. Then free resources associated
  54032. ** with any savepoints that are destroyed by this operation.
  54033. */
  54034. nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
  54035. for(ii=nNew; ii<pPager->nSavepoint; ii++){
  54036. sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
  54037. }
  54038. pPager->nSavepoint = nNew;
  54039. /* If this is a release of the outermost savepoint, truncate
  54040. ** the sub-journal to zero bytes in size. */
  54041. if( op==SAVEPOINT_RELEASE ){
  54042. if( nNew==0 && isOpen(pPager->sjfd) ){
  54043. /* Only truncate if it is an in-memory sub-journal. */
  54044. if( sqlite3JournalIsInMemory(pPager->sjfd) ){
  54045. rc = sqlite3OsTruncate(pPager->sjfd, 0);
  54046. assert( rc==SQLITE_OK );
  54047. }
  54048. pPager->nSubRec = 0;
  54049. }
  54050. }
  54051. /* Else this is a rollback operation, playback the specified savepoint.
  54052. ** If this is a temp-file, it is possible that the journal file has
  54053. ** not yet been opened. In this case there have been no changes to
  54054. ** the database file, so the playback operation can be skipped.
  54055. */
  54056. else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
  54057. PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
  54058. rc = pagerPlaybackSavepoint(pPager, pSavepoint);
  54059. assert(rc!=SQLITE_DONE);
  54060. }
  54061. #ifdef SQLITE_ENABLE_ZIPVFS
  54062. /* If the cache has been modified but the savepoint cannot be rolled
  54063. ** back journal_mode=off, put the pager in the error state. This way,
  54064. ** if the VFS used by this pager includes ZipVFS, the entire transaction
  54065. ** can be rolled back at the ZipVFS level. */
  54066. else if(
  54067. pPager->journalMode==PAGER_JOURNALMODE_OFF
  54068. && pPager->eState>=PAGER_WRITER_CACHEMOD
  54069. ){
  54070. pPager->errCode = SQLITE_ABORT;
  54071. pPager->eState = PAGER_ERROR;
  54072. setGetterMethod(pPager);
  54073. }
  54074. #endif
  54075. }
  54076. return rc;
  54077. }
  54078. /*
  54079. ** Return the full pathname of the database file.
  54080. **
  54081. ** Except, if the pager is in-memory only, then return an empty string if
  54082. ** nullIfMemDb is true. This routine is called with nullIfMemDb==1 when
  54083. ** used to report the filename to the user, for compatibility with legacy
  54084. ** behavior. But when the Btree needs to know the filename for matching to
  54085. ** shared cache, it uses nullIfMemDb==0 so that in-memory databases can
  54086. ** participate in shared-cache.
  54087. */
  54088. SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){
  54089. return (nullIfMemDb && pPager->memDb) ? "" : pPager->zFilename;
  54090. }
  54091. /*
  54092. ** Return the VFS structure for the pager.
  54093. */
  54094. SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
  54095. return pPager->pVfs;
  54096. }
  54097. /*
  54098. ** Return the file handle for the database file associated
  54099. ** with the pager. This might return NULL if the file has
  54100. ** not yet been opened.
  54101. */
  54102. SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
  54103. return pPager->fd;
  54104. }
  54105. #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
  54106. /*
  54107. ** Reset the lock timeout for pager.
  54108. */
  54109. SQLITE_PRIVATE void sqlite3PagerResetLockTimeout(Pager *pPager){
  54110. int x = 0;
  54111. sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_LOCK_TIMEOUT, &x);
  54112. }
  54113. #endif
  54114. /*
  54115. ** Return the file handle for the journal file (if it exists).
  54116. ** This will be either the rollback journal or the WAL file.
  54117. */
  54118. SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager *pPager){
  54119. #if SQLITE_OMIT_WAL
  54120. return pPager->jfd;
  54121. #else
  54122. return pPager->pWal ? sqlite3WalFile(pPager->pWal) : pPager->jfd;
  54123. #endif
  54124. }
  54125. /*
  54126. ** Return the full pathname of the journal file.
  54127. */
  54128. SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
  54129. return pPager->zJournal;
  54130. }
  54131. #ifdef SQLITE_HAS_CODEC
  54132. /*
  54133. ** Set or retrieve the codec for this pager
  54134. */
  54135. SQLITE_PRIVATE void sqlite3PagerSetCodec(
  54136. Pager *pPager,
  54137. void *(*xCodec)(void*,void*,Pgno,int),
  54138. void (*xCodecSizeChng)(void*,int,int),
  54139. void (*xCodecFree)(void*),
  54140. void *pCodec
  54141. ){
  54142. if( pPager->xCodecFree ){
  54143. pPager->xCodecFree(pPager->pCodec);
  54144. }else{
  54145. pager_reset(pPager);
  54146. }
  54147. pPager->xCodec = pPager->memDb ? 0 : xCodec;
  54148. pPager->xCodecSizeChng = xCodecSizeChng;
  54149. pPager->xCodecFree = xCodecFree;
  54150. pPager->pCodec = pCodec;
  54151. setGetterMethod(pPager);
  54152. pagerReportSize(pPager);
  54153. }
  54154. SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
  54155. return pPager->pCodec;
  54156. }
  54157. /*
  54158. ** This function is called by the wal module when writing page content
  54159. ** into the log file.
  54160. **
  54161. ** This function returns a pointer to a buffer containing the encrypted
  54162. ** page content. If a malloc fails, this function may return NULL.
  54163. */
  54164. SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
  54165. void *aData = 0;
  54166. CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
  54167. return aData;
  54168. }
  54169. /*
  54170. ** Return the current pager state
  54171. */
  54172. SQLITE_PRIVATE int sqlite3PagerState(Pager *pPager){
  54173. return pPager->eState;
  54174. }
  54175. #endif /* SQLITE_HAS_CODEC */
  54176. #ifndef SQLITE_OMIT_AUTOVACUUM
  54177. /*
  54178. ** Move the page pPg to location pgno in the file.
  54179. **
  54180. ** There must be no references to the page previously located at
  54181. ** pgno (which we call pPgOld) though that page is allowed to be
  54182. ** in cache. If the page previously located at pgno is not already
  54183. ** in the rollback journal, it is not put there by by this routine.
  54184. **
  54185. ** References to the page pPg remain valid. Updating any
  54186. ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
  54187. ** allocated along with the page) is the responsibility of the caller.
  54188. **
  54189. ** A transaction must be active when this routine is called. It used to be
  54190. ** required that a statement transaction was not active, but this restriction
  54191. ** has been removed (CREATE INDEX needs to move a page when a statement
  54192. ** transaction is active).
  54193. **
  54194. ** If the fourth argument, isCommit, is non-zero, then this page is being
  54195. ** moved as part of a database reorganization just before the transaction
  54196. ** is being committed. In this case, it is guaranteed that the database page
  54197. ** pPg refers to will not be written to again within this transaction.
  54198. **
  54199. ** This function may return SQLITE_NOMEM or an IO error code if an error
  54200. ** occurs. Otherwise, it returns SQLITE_OK.
  54201. */
  54202. SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
  54203. PgHdr *pPgOld; /* The page being overwritten. */
  54204. Pgno needSyncPgno = 0; /* Old value of pPg->pgno, if sync is required */
  54205. int rc; /* Return code */
  54206. Pgno origPgno; /* The original page number */
  54207. assert( pPg->nRef>0 );
  54208. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  54209. || pPager->eState==PAGER_WRITER_DBMOD
  54210. );
  54211. assert( assert_pager_state(pPager) );
  54212. /* In order to be able to rollback, an in-memory database must journal
  54213. ** the page we are moving from.
  54214. */
  54215. assert( pPager->tempFile || !MEMDB );
  54216. if( pPager->tempFile ){
  54217. rc = sqlite3PagerWrite(pPg);
  54218. if( rc ) return rc;
  54219. }
  54220. /* If the page being moved is dirty and has not been saved by the latest
  54221. ** savepoint, then save the current contents of the page into the
  54222. ** sub-journal now. This is required to handle the following scenario:
  54223. **
  54224. ** BEGIN;
  54225. ** <journal page X, then modify it in memory>
  54226. ** SAVEPOINT one;
  54227. ** <Move page X to location Y>
  54228. ** ROLLBACK TO one;
  54229. **
  54230. ** If page X were not written to the sub-journal here, it would not
  54231. ** be possible to restore its contents when the "ROLLBACK TO one"
  54232. ** statement were is processed.
  54233. **
  54234. ** subjournalPage() may need to allocate space to store pPg->pgno into
  54235. ** one or more savepoint bitvecs. This is the reason this function
  54236. ** may return SQLITE_NOMEM.
  54237. */
  54238. if( (pPg->flags & PGHDR_DIRTY)!=0
  54239. && SQLITE_OK!=(rc = subjournalPageIfRequired(pPg))
  54240. ){
  54241. return rc;
  54242. }
  54243. PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
  54244. PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
  54245. IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
  54246. /* If the journal needs to be sync()ed before page pPg->pgno can
  54247. ** be written to, store pPg->pgno in local variable needSyncPgno.
  54248. **
  54249. ** If the isCommit flag is set, there is no need to remember that
  54250. ** the journal needs to be sync()ed before database page pPg->pgno
  54251. ** can be written to. The caller has already promised not to write to it.
  54252. */
  54253. if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
  54254. needSyncPgno = pPg->pgno;
  54255. assert( pPager->journalMode==PAGER_JOURNALMODE_OFF ||
  54256. pageInJournal(pPager, pPg) || pPg->pgno>pPager->dbOrigSize );
  54257. assert( pPg->flags&PGHDR_DIRTY );
  54258. }
  54259. /* If the cache contains a page with page-number pgno, remove it
  54260. ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
  54261. ** page pgno before the 'move' operation, it needs to be retained
  54262. ** for the page moved there.
  54263. */
  54264. pPg->flags &= ~PGHDR_NEED_SYNC;
  54265. pPgOld = sqlite3PagerLookup(pPager, pgno);
  54266. assert( !pPgOld || pPgOld->nRef==1 || CORRUPT_DB );
  54267. if( pPgOld ){
  54268. if( pPgOld->nRef>1 ){
  54269. sqlite3PagerUnrefNotNull(pPgOld);
  54270. return SQLITE_CORRUPT_BKPT;
  54271. }
  54272. pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
  54273. if( pPager->tempFile ){
  54274. /* Do not discard pages from an in-memory database since we might
  54275. ** need to rollback later. Just move the page out of the way. */
  54276. sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
  54277. }else{
  54278. sqlite3PcacheDrop(pPgOld);
  54279. }
  54280. }
  54281. origPgno = pPg->pgno;
  54282. sqlite3PcacheMove(pPg, pgno);
  54283. sqlite3PcacheMakeDirty(pPg);
  54284. /* For an in-memory database, make sure the original page continues
  54285. ** to exist, in case the transaction needs to roll back. Use pPgOld
  54286. ** as the original page since it has already been allocated.
  54287. */
  54288. if( pPager->tempFile && pPgOld ){
  54289. sqlite3PcacheMove(pPgOld, origPgno);
  54290. sqlite3PagerUnrefNotNull(pPgOld);
  54291. }
  54292. if( needSyncPgno ){
  54293. /* If needSyncPgno is non-zero, then the journal file needs to be
  54294. ** sync()ed before any data is written to database file page needSyncPgno.
  54295. ** Currently, no such page exists in the page-cache and the
  54296. ** "is journaled" bitvec flag has been set. This needs to be remedied by
  54297. ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
  54298. ** flag.
  54299. **
  54300. ** If the attempt to load the page into the page-cache fails, (due
  54301. ** to a malloc() or IO failure), clear the bit in the pInJournal[]
  54302. ** array. Otherwise, if the page is loaded and written again in
  54303. ** this transaction, it may be written to the database file before
  54304. ** it is synced into the journal file. This way, it may end up in
  54305. ** the journal file twice, but that is not a problem.
  54306. */
  54307. PgHdr *pPgHdr;
  54308. rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr, 0);
  54309. if( rc!=SQLITE_OK ){
  54310. if( needSyncPgno<=pPager->dbOrigSize ){
  54311. assert( pPager->pTmpSpace!=0 );
  54312. sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
  54313. }
  54314. return rc;
  54315. }
  54316. pPgHdr->flags |= PGHDR_NEED_SYNC;
  54317. sqlite3PcacheMakeDirty(pPgHdr);
  54318. sqlite3PagerUnrefNotNull(pPgHdr);
  54319. }
  54320. return SQLITE_OK;
  54321. }
  54322. #endif
  54323. /*
  54324. ** The page handle passed as the first argument refers to a dirty page
  54325. ** with a page number other than iNew. This function changes the page's
  54326. ** page number to iNew and sets the value of the PgHdr.flags field to
  54327. ** the value passed as the third parameter.
  54328. */
  54329. SQLITE_PRIVATE void sqlite3PagerRekey(DbPage *pPg, Pgno iNew, u16 flags){
  54330. assert( pPg->pgno!=iNew );
  54331. pPg->flags = flags;
  54332. sqlite3PcacheMove(pPg, iNew);
  54333. }
  54334. /*
  54335. ** Return a pointer to the data for the specified page.
  54336. */
  54337. SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
  54338. assert( pPg->nRef>0 || pPg->pPager->memDb );
  54339. return pPg->pData;
  54340. }
  54341. /*
  54342. ** Return a pointer to the Pager.nExtra bytes of "extra" space
  54343. ** allocated along with the specified page.
  54344. */
  54345. SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
  54346. return pPg->pExtra;
  54347. }
  54348. /*
  54349. ** Get/set the locking-mode for this pager. Parameter eMode must be one
  54350. ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
  54351. ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
  54352. ** the locking-mode is set to the value specified.
  54353. **
  54354. ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
  54355. ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
  54356. ** locking-mode.
  54357. */
  54358. SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
  54359. assert( eMode==PAGER_LOCKINGMODE_QUERY
  54360. || eMode==PAGER_LOCKINGMODE_NORMAL
  54361. || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
  54362. assert( PAGER_LOCKINGMODE_QUERY<0 );
  54363. assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
  54364. assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
  54365. if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
  54366. pPager->exclusiveMode = (u8)eMode;
  54367. }
  54368. return (int)pPager->exclusiveMode;
  54369. }
  54370. /*
  54371. ** Set the journal-mode for this pager. Parameter eMode must be one of:
  54372. **
  54373. ** PAGER_JOURNALMODE_DELETE
  54374. ** PAGER_JOURNALMODE_TRUNCATE
  54375. ** PAGER_JOURNALMODE_PERSIST
  54376. ** PAGER_JOURNALMODE_OFF
  54377. ** PAGER_JOURNALMODE_MEMORY
  54378. ** PAGER_JOURNALMODE_WAL
  54379. **
  54380. ** The journalmode is set to the value specified if the change is allowed.
  54381. ** The change may be disallowed for the following reasons:
  54382. **
  54383. ** * An in-memory database can only have its journal_mode set to _OFF
  54384. ** or _MEMORY.
  54385. **
  54386. ** * Temporary databases cannot have _WAL journalmode.
  54387. **
  54388. ** The returned indicate the current (possibly updated) journal-mode.
  54389. */
  54390. SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
  54391. u8 eOld = pPager->journalMode; /* Prior journalmode */
  54392. /* The eMode parameter is always valid */
  54393. assert( eMode==PAGER_JOURNALMODE_DELETE
  54394. || eMode==PAGER_JOURNALMODE_TRUNCATE
  54395. || eMode==PAGER_JOURNALMODE_PERSIST
  54396. || eMode==PAGER_JOURNALMODE_OFF
  54397. || eMode==PAGER_JOURNALMODE_WAL
  54398. || eMode==PAGER_JOURNALMODE_MEMORY );
  54399. /* This routine is only called from the OP_JournalMode opcode, and
  54400. ** the logic there will never allow a temporary file to be changed
  54401. ** to WAL mode.
  54402. */
  54403. assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
  54404. /* Do allow the journalmode of an in-memory database to be set to
  54405. ** anything other than MEMORY or OFF
  54406. */
  54407. if( MEMDB ){
  54408. assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
  54409. if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
  54410. eMode = eOld;
  54411. }
  54412. }
  54413. if( eMode!=eOld ){
  54414. /* Change the journal mode. */
  54415. assert( pPager->eState!=PAGER_ERROR );
  54416. pPager->journalMode = (u8)eMode;
  54417. /* When transistioning from TRUNCATE or PERSIST to any other journal
  54418. ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
  54419. ** delete the journal file.
  54420. */
  54421. assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
  54422. assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
  54423. assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
  54424. assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
  54425. assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
  54426. assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
  54427. assert( isOpen(pPager->fd) || pPager->exclusiveMode );
  54428. if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
  54429. /* In this case we would like to delete the journal file. If it is
  54430. ** not possible, then that is not a problem. Deleting the journal file
  54431. ** here is an optimization only.
  54432. **
  54433. ** Before deleting the journal file, obtain a RESERVED lock on the
  54434. ** database file. This ensures that the journal file is not deleted
  54435. ** while it is in use by some other client.
  54436. */
  54437. sqlite3OsClose(pPager->jfd);
  54438. if( pPager->eLock>=RESERVED_LOCK ){
  54439. sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  54440. }else{
  54441. int rc = SQLITE_OK;
  54442. int state = pPager->eState;
  54443. assert( state==PAGER_OPEN || state==PAGER_READER );
  54444. if( state==PAGER_OPEN ){
  54445. rc = sqlite3PagerSharedLock(pPager);
  54446. }
  54447. if( pPager->eState==PAGER_READER ){
  54448. assert( rc==SQLITE_OK );
  54449. rc = pagerLockDb(pPager, RESERVED_LOCK);
  54450. }
  54451. if( rc==SQLITE_OK ){
  54452. sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  54453. }
  54454. if( rc==SQLITE_OK && state==PAGER_READER ){
  54455. pagerUnlockDb(pPager, SHARED_LOCK);
  54456. }else if( state==PAGER_OPEN ){
  54457. pager_unlock(pPager);
  54458. }
  54459. assert( state==pPager->eState );
  54460. }
  54461. }else if( eMode==PAGER_JOURNALMODE_OFF ){
  54462. sqlite3OsClose(pPager->jfd);
  54463. }
  54464. }
  54465. /* Return the new journal mode */
  54466. return (int)pPager->journalMode;
  54467. }
  54468. /*
  54469. ** Return the current journal mode.
  54470. */
  54471. SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
  54472. return (int)pPager->journalMode;
  54473. }
  54474. /*
  54475. ** Return TRUE if the pager is in a state where it is OK to change the
  54476. ** journalmode. Journalmode changes can only happen when the database
  54477. ** is unmodified.
  54478. */
  54479. SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
  54480. assert( assert_pager_state(pPager) );
  54481. if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
  54482. if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
  54483. return 1;
  54484. }
  54485. /*
  54486. ** Get/set the size-limit used for persistent journal files.
  54487. **
  54488. ** Setting the size limit to -1 means no limit is enforced.
  54489. ** An attempt to set a limit smaller than -1 is a no-op.
  54490. */
  54491. SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
  54492. if( iLimit>=-1 ){
  54493. pPager->journalSizeLimit = iLimit;
  54494. sqlite3WalLimit(pPager->pWal, iLimit);
  54495. }
  54496. return pPager->journalSizeLimit;
  54497. }
  54498. /*
  54499. ** Return a pointer to the pPager->pBackup variable. The backup module
  54500. ** in backup.c maintains the content of this variable. This module
  54501. ** uses it opaquely as an argument to sqlite3BackupRestart() and
  54502. ** sqlite3BackupUpdate() only.
  54503. */
  54504. SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
  54505. return &pPager->pBackup;
  54506. }
  54507. #ifndef SQLITE_OMIT_VACUUM
  54508. /*
  54509. ** Unless this is an in-memory or temporary database, clear the pager cache.
  54510. */
  54511. SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
  54512. assert( MEMDB==0 || pPager->tempFile );
  54513. if( pPager->tempFile==0 ) pager_reset(pPager);
  54514. }
  54515. #endif
  54516. #ifndef SQLITE_OMIT_WAL
  54517. /*
  54518. ** This function is called when the user invokes "PRAGMA wal_checkpoint",
  54519. ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
  54520. ** or wal_blocking_checkpoint() API functions.
  54521. **
  54522. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  54523. */
  54524. SQLITE_PRIVATE int sqlite3PagerCheckpoint(
  54525. Pager *pPager, /* Checkpoint on this pager */
  54526. sqlite3 *db, /* Db handle used to check for interrupts */
  54527. int eMode, /* Type of checkpoint */
  54528. int *pnLog, /* OUT: Final number of frames in log */
  54529. int *pnCkpt /* OUT: Final number of checkpointed frames */
  54530. ){
  54531. int rc = SQLITE_OK;
  54532. if( pPager->pWal ){
  54533. rc = sqlite3WalCheckpoint(pPager->pWal, db, eMode,
  54534. (eMode==SQLITE_CHECKPOINT_PASSIVE ? 0 : pPager->xBusyHandler),
  54535. pPager->pBusyHandlerArg,
  54536. pPager->walSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
  54537. pnLog, pnCkpt
  54538. );
  54539. sqlite3PagerResetLockTimeout(pPager);
  54540. }
  54541. return rc;
  54542. }
  54543. SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
  54544. return sqlite3WalCallback(pPager->pWal);
  54545. }
  54546. /*
  54547. ** Return true if the underlying VFS for the given pager supports the
  54548. ** primitives necessary for write-ahead logging.
  54549. */
  54550. SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
  54551. const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
  54552. if( pPager->noLock ) return 0;
  54553. return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
  54554. }
  54555. /*
  54556. ** Attempt to take an exclusive lock on the database file. If a PENDING lock
  54557. ** is obtained instead, immediately release it.
  54558. */
  54559. static int pagerExclusiveLock(Pager *pPager){
  54560. int rc; /* Return code */
  54561. assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
  54562. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  54563. if( rc!=SQLITE_OK ){
  54564. /* If the attempt to grab the exclusive lock failed, release the
  54565. ** pending lock that may have been obtained instead. */
  54566. pagerUnlockDb(pPager, SHARED_LOCK);
  54567. }
  54568. return rc;
  54569. }
  54570. /*
  54571. ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
  54572. ** exclusive-locking mode when this function is called, take an EXCLUSIVE
  54573. ** lock on the database file and use heap-memory to store the wal-index
  54574. ** in. Otherwise, use the normal shared-memory.
  54575. */
  54576. static int pagerOpenWal(Pager *pPager){
  54577. int rc = SQLITE_OK;
  54578. assert( pPager->pWal==0 && pPager->tempFile==0 );
  54579. assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
  54580. /* If the pager is already in exclusive-mode, the WAL module will use
  54581. ** heap-memory for the wal-index instead of the VFS shared-memory
  54582. ** implementation. Take the exclusive lock now, before opening the WAL
  54583. ** file, to make sure this is safe.
  54584. */
  54585. if( pPager->exclusiveMode ){
  54586. rc = pagerExclusiveLock(pPager);
  54587. }
  54588. /* Open the connection to the log file. If this operation fails,
  54589. ** (e.g. due to malloc() failure), return an error code.
  54590. */
  54591. if( rc==SQLITE_OK ){
  54592. rc = sqlite3WalOpen(pPager->pVfs,
  54593. pPager->fd, pPager->zWal, pPager->exclusiveMode,
  54594. pPager->journalSizeLimit, &pPager->pWal
  54595. );
  54596. }
  54597. pagerFixMaplimit(pPager);
  54598. return rc;
  54599. }
  54600. /*
  54601. ** The caller must be holding a SHARED lock on the database file to call
  54602. ** this function.
  54603. **
  54604. ** If the pager passed as the first argument is open on a real database
  54605. ** file (not a temp file or an in-memory database), and the WAL file
  54606. ** is not already open, make an attempt to open it now. If successful,
  54607. ** return SQLITE_OK. If an error occurs or the VFS used by the pager does
  54608. ** not support the xShmXXX() methods, return an error code. *pbOpen is
  54609. ** not modified in either case.
  54610. **
  54611. ** If the pager is open on a temp-file (or in-memory database), or if
  54612. ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
  54613. ** without doing anything.
  54614. */
  54615. SQLITE_PRIVATE int sqlite3PagerOpenWal(
  54616. Pager *pPager, /* Pager object */
  54617. int *pbOpen /* OUT: Set to true if call is a no-op */
  54618. ){
  54619. int rc = SQLITE_OK; /* Return code */
  54620. assert( assert_pager_state(pPager) );
  54621. assert( pPager->eState==PAGER_OPEN || pbOpen );
  54622. assert( pPager->eState==PAGER_READER || !pbOpen );
  54623. assert( pbOpen==0 || *pbOpen==0 );
  54624. assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
  54625. if( !pPager->tempFile && !pPager->pWal ){
  54626. if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
  54627. /* Close any rollback journal previously open */
  54628. sqlite3OsClose(pPager->jfd);
  54629. rc = pagerOpenWal(pPager);
  54630. if( rc==SQLITE_OK ){
  54631. pPager->journalMode = PAGER_JOURNALMODE_WAL;
  54632. pPager->eState = PAGER_OPEN;
  54633. }
  54634. }else{
  54635. *pbOpen = 1;
  54636. }
  54637. return rc;
  54638. }
  54639. /*
  54640. ** This function is called to close the connection to the log file prior
  54641. ** to switching from WAL to rollback mode.
  54642. **
  54643. ** Before closing the log file, this function attempts to take an
  54644. ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
  54645. ** error (SQLITE_BUSY) is returned and the log connection is not closed.
  54646. ** If successful, the EXCLUSIVE lock is not released before returning.
  54647. */
  54648. SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager, sqlite3 *db){
  54649. int rc = SQLITE_OK;
  54650. assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
  54651. /* If the log file is not already open, but does exist in the file-system,
  54652. ** it may need to be checkpointed before the connection can switch to
  54653. ** rollback mode. Open it now so this can happen.
  54654. */
  54655. if( !pPager->pWal ){
  54656. int logexists = 0;
  54657. rc = pagerLockDb(pPager, SHARED_LOCK);
  54658. if( rc==SQLITE_OK ){
  54659. rc = sqlite3OsAccess(
  54660. pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
  54661. );
  54662. }
  54663. if( rc==SQLITE_OK && logexists ){
  54664. rc = pagerOpenWal(pPager);
  54665. }
  54666. }
  54667. /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
  54668. ** the database file, the log and log-summary files will be deleted.
  54669. */
  54670. if( rc==SQLITE_OK && pPager->pWal ){
  54671. rc = pagerExclusiveLock(pPager);
  54672. if( rc==SQLITE_OK ){
  54673. rc = sqlite3WalClose(pPager->pWal, db, pPager->walSyncFlags,
  54674. pPager->pageSize, (u8*)pPager->pTmpSpace);
  54675. pPager->pWal = 0;
  54676. pagerFixMaplimit(pPager);
  54677. if( rc && !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
  54678. }
  54679. }
  54680. return rc;
  54681. }
  54682. #ifdef SQLITE_ENABLE_SNAPSHOT
  54683. /*
  54684. ** If this is a WAL database, obtain a snapshot handle for the snapshot
  54685. ** currently open. Otherwise, return an error.
  54686. */
  54687. SQLITE_PRIVATE int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppSnapshot){
  54688. int rc = SQLITE_ERROR;
  54689. if( pPager->pWal ){
  54690. rc = sqlite3WalSnapshotGet(pPager->pWal, ppSnapshot);
  54691. }
  54692. return rc;
  54693. }
  54694. /*
  54695. ** If this is a WAL database, store a pointer to pSnapshot. Next time a
  54696. ** read transaction is opened, attempt to read from the snapshot it
  54697. ** identifies. If this is not a WAL database, return an error.
  54698. */
  54699. SQLITE_PRIVATE int sqlite3PagerSnapshotOpen(Pager *pPager, sqlite3_snapshot *pSnapshot){
  54700. int rc = SQLITE_OK;
  54701. if( pPager->pWal ){
  54702. sqlite3WalSnapshotOpen(pPager->pWal, pSnapshot);
  54703. }else{
  54704. rc = SQLITE_ERROR;
  54705. }
  54706. return rc;
  54707. }
  54708. /*
  54709. ** If this is a WAL database, call sqlite3WalSnapshotRecover(). If this
  54710. ** is not a WAL database, return an error.
  54711. */
  54712. SQLITE_PRIVATE int sqlite3PagerSnapshotRecover(Pager *pPager){
  54713. int rc;
  54714. if( pPager->pWal ){
  54715. rc = sqlite3WalSnapshotRecover(pPager->pWal);
  54716. }else{
  54717. rc = SQLITE_ERROR;
  54718. }
  54719. return rc;
  54720. }
  54721. /*
  54722. ** The caller currently has a read transaction open on the database.
  54723. ** If this is not a WAL database, SQLITE_ERROR is returned. Otherwise,
  54724. ** this function takes a SHARED lock on the CHECKPOINTER slot and then
  54725. ** checks if the snapshot passed as the second argument is still
  54726. ** available. If so, SQLITE_OK is returned.
  54727. **
  54728. ** If the snapshot is not available, SQLITE_ERROR is returned. Or, if
  54729. ** the CHECKPOINTER lock cannot be obtained, SQLITE_BUSY. If any error
  54730. ** occurs (any value other than SQLITE_OK is returned), the CHECKPOINTER
  54731. ** lock is released before returning.
  54732. */
  54733. SQLITE_PRIVATE int sqlite3PagerSnapshotCheck(Pager *pPager, sqlite3_snapshot *pSnapshot){
  54734. int rc;
  54735. if( pPager->pWal ){
  54736. rc = sqlite3WalSnapshotCheck(pPager->pWal, pSnapshot);
  54737. }else{
  54738. rc = SQLITE_ERROR;
  54739. }
  54740. return rc;
  54741. }
  54742. /*
  54743. ** Release a lock obtained by an earlier successful call to
  54744. ** sqlite3PagerSnapshotCheck().
  54745. */
  54746. SQLITE_PRIVATE void sqlite3PagerSnapshotUnlock(Pager *pPager){
  54747. assert( pPager->pWal );
  54748. sqlite3WalSnapshotUnlock(pPager->pWal);
  54749. }
  54750. #endif /* SQLITE_ENABLE_SNAPSHOT */
  54751. #endif /* !SQLITE_OMIT_WAL */
  54752. #ifdef SQLITE_ENABLE_ZIPVFS
  54753. /*
  54754. ** A read-lock must be held on the pager when this function is called. If
  54755. ** the pager is in WAL mode and the WAL file currently contains one or more
  54756. ** frames, return the size in bytes of the page images stored within the
  54757. ** WAL frames. Otherwise, if this is not a WAL database or the WAL file
  54758. ** is empty, return 0.
  54759. */
  54760. SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
  54761. assert( pPager->eState>=PAGER_READER );
  54762. return sqlite3WalFramesize(pPager->pWal);
  54763. }
  54764. #endif
  54765. #endif /* SQLITE_OMIT_DISKIO */
  54766. /************** End of pager.c ***********************************************/
  54767. /************** Begin file wal.c *********************************************/
  54768. /*
  54769. ** 2010 February 1
  54770. **
  54771. ** The author disclaims copyright to this source code. In place of
  54772. ** a legal notice, here is a blessing:
  54773. **
  54774. ** May you do good and not evil.
  54775. ** May you find forgiveness for yourself and forgive others.
  54776. ** May you share freely, never taking more than you give.
  54777. **
  54778. *************************************************************************
  54779. **
  54780. ** This file contains the implementation of a write-ahead log (WAL) used in
  54781. ** "journal_mode=WAL" mode.
  54782. **
  54783. ** WRITE-AHEAD LOG (WAL) FILE FORMAT
  54784. **
  54785. ** A WAL file consists of a header followed by zero or more "frames".
  54786. ** Each frame records the revised content of a single page from the
  54787. ** database file. All changes to the database are recorded by writing
  54788. ** frames into the WAL. Transactions commit when a frame is written that
  54789. ** contains a commit marker. A single WAL can and usually does record
  54790. ** multiple transactions. Periodically, the content of the WAL is
  54791. ** transferred back into the database file in an operation called a
  54792. ** "checkpoint".
  54793. **
  54794. ** A single WAL file can be used multiple times. In other words, the
  54795. ** WAL can fill up with frames and then be checkpointed and then new
  54796. ** frames can overwrite the old ones. A WAL always grows from beginning
  54797. ** toward the end. Checksums and counters attached to each frame are
  54798. ** used to determine which frames within the WAL are valid and which
  54799. ** are leftovers from prior checkpoints.
  54800. **
  54801. ** The WAL header is 32 bytes in size and consists of the following eight
  54802. ** big-endian 32-bit unsigned integer values:
  54803. **
  54804. ** 0: Magic number. 0x377f0682 or 0x377f0683
  54805. ** 4: File format version. Currently 3007000
  54806. ** 8: Database page size. Example: 1024
  54807. ** 12: Checkpoint sequence number
  54808. ** 16: Salt-1, random integer incremented with each checkpoint
  54809. ** 20: Salt-2, a different random integer changing with each ckpt
  54810. ** 24: Checksum-1 (first part of checksum for first 24 bytes of header).
  54811. ** 28: Checksum-2 (second part of checksum for first 24 bytes of header).
  54812. **
  54813. ** Immediately following the wal-header are zero or more frames. Each
  54814. ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
  54815. ** of page data. The frame-header is six big-endian 32-bit unsigned
  54816. ** integer values, as follows:
  54817. **
  54818. ** 0: Page number.
  54819. ** 4: For commit records, the size of the database image in pages
  54820. ** after the commit. For all other records, zero.
  54821. ** 8: Salt-1 (copied from the header)
  54822. ** 12: Salt-2 (copied from the header)
  54823. ** 16: Checksum-1.
  54824. ** 20: Checksum-2.
  54825. **
  54826. ** A frame is considered valid if and only if the following conditions are
  54827. ** true:
  54828. **
  54829. ** (1) The salt-1 and salt-2 values in the frame-header match
  54830. ** salt values in the wal-header
  54831. **
  54832. ** (2) The checksum values in the final 8 bytes of the frame-header
  54833. ** exactly match the checksum computed consecutively on the
  54834. ** WAL header and the first 8 bytes and the content of all frames
  54835. ** up to and including the current frame.
  54836. **
  54837. ** The checksum is computed using 32-bit big-endian integers if the
  54838. ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
  54839. ** is computed using little-endian if the magic number is 0x377f0682.
  54840. ** The checksum values are always stored in the frame header in a
  54841. ** big-endian format regardless of which byte order is used to compute
  54842. ** the checksum. The checksum is computed by interpreting the input as
  54843. ** an even number of unsigned 32-bit integers: x[0] through x[N]. The
  54844. ** algorithm used for the checksum is as follows:
  54845. **
  54846. ** for i from 0 to n-1 step 2:
  54847. ** s0 += x[i] + s1;
  54848. ** s1 += x[i+1] + s0;
  54849. ** endfor
  54850. **
  54851. ** Note that s0 and s1 are both weighted checksums using fibonacci weights
  54852. ** in reverse order (the largest fibonacci weight occurs on the first element
  54853. ** of the sequence being summed.) The s1 value spans all 32-bit
  54854. ** terms of the sequence whereas s0 omits the final term.
  54855. **
  54856. ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
  54857. ** WAL is transferred into the database, then the database is VFS.xSync-ed.
  54858. ** The VFS.xSync operations serve as write barriers - all writes launched
  54859. ** before the xSync must complete before any write that launches after the
  54860. ** xSync begins.
  54861. **
  54862. ** After each checkpoint, the salt-1 value is incremented and the salt-2
  54863. ** value is randomized. This prevents old and new frames in the WAL from
  54864. ** being considered valid at the same time and being checkpointing together
  54865. ** following a crash.
  54866. **
  54867. ** READER ALGORITHM
  54868. **
  54869. ** To read a page from the database (call it page number P), a reader
  54870. ** first checks the WAL to see if it contains page P. If so, then the
  54871. ** last valid instance of page P that is a followed by a commit frame
  54872. ** or is a commit frame itself becomes the value read. If the WAL
  54873. ** contains no copies of page P that are valid and which are a commit
  54874. ** frame or are followed by a commit frame, then page P is read from
  54875. ** the database file.
  54876. **
  54877. ** To start a read transaction, the reader records the index of the last
  54878. ** valid frame in the WAL. The reader uses this recorded "mxFrame" value
  54879. ** for all subsequent read operations. New transactions can be appended
  54880. ** to the WAL, but as long as the reader uses its original mxFrame value
  54881. ** and ignores the newly appended content, it will see a consistent snapshot
  54882. ** of the database from a single point in time. This technique allows
  54883. ** multiple concurrent readers to view different versions of the database
  54884. ** content simultaneously.
  54885. **
  54886. ** The reader algorithm in the previous paragraphs works correctly, but
  54887. ** because frames for page P can appear anywhere within the WAL, the
  54888. ** reader has to scan the entire WAL looking for page P frames. If the
  54889. ** WAL is large (multiple megabytes is typical) that scan can be slow,
  54890. ** and read performance suffers. To overcome this problem, a separate
  54891. ** data structure called the wal-index is maintained to expedite the
  54892. ** search for frames of a particular page.
  54893. **
  54894. ** WAL-INDEX FORMAT
  54895. **
  54896. ** Conceptually, the wal-index is shared memory, though VFS implementations
  54897. ** might choose to implement the wal-index using a mmapped file. Because
  54898. ** the wal-index is shared memory, SQLite does not support journal_mode=WAL
  54899. ** on a network filesystem. All users of the database must be able to
  54900. ** share memory.
  54901. **
  54902. ** In the default unix and windows implementation, the wal-index is a mmapped
  54903. ** file whose name is the database name with a "-shm" suffix added. For that
  54904. ** reason, the wal-index is sometimes called the "shm" file.
  54905. **
  54906. ** The wal-index is transient. After a crash, the wal-index can (and should
  54907. ** be) reconstructed from the original WAL file. In fact, the VFS is required
  54908. ** to either truncate or zero the header of the wal-index when the last
  54909. ** connection to it closes. Because the wal-index is transient, it can
  54910. ** use an architecture-specific format; it does not have to be cross-platform.
  54911. ** Hence, unlike the database and WAL file formats which store all values
  54912. ** as big endian, the wal-index can store multi-byte values in the native
  54913. ** byte order of the host computer.
  54914. **
  54915. ** The purpose of the wal-index is to answer this question quickly: Given
  54916. ** a page number P and a maximum frame index M, return the index of the
  54917. ** last frame in the wal before frame M for page P in the WAL, or return
  54918. ** NULL if there are no frames for page P in the WAL prior to M.
  54919. **
  54920. ** The wal-index consists of a header region, followed by an one or
  54921. ** more index blocks.
  54922. **
  54923. ** The wal-index header contains the total number of frames within the WAL
  54924. ** in the mxFrame field.
  54925. **
  54926. ** Each index block except for the first contains information on
  54927. ** HASHTABLE_NPAGE frames. The first index block contains information on
  54928. ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
  54929. ** HASHTABLE_NPAGE are selected so that together the wal-index header and
  54930. ** first index block are the same size as all other index blocks in the
  54931. ** wal-index.
  54932. **
  54933. ** Each index block contains two sections, a page-mapping that contains the
  54934. ** database page number associated with each wal frame, and a hash-table
  54935. ** that allows readers to query an index block for a specific page number.
  54936. ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
  54937. ** for the first index block) 32-bit page numbers. The first entry in the
  54938. ** first index-block contains the database page number corresponding to the
  54939. ** first frame in the WAL file. The first entry in the second index block
  54940. ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
  54941. ** the log, and so on.
  54942. **
  54943. ** The last index block in a wal-index usually contains less than the full
  54944. ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
  54945. ** depending on the contents of the WAL file. This does not change the
  54946. ** allocated size of the page-mapping array - the page-mapping array merely
  54947. ** contains unused entries.
  54948. **
  54949. ** Even without using the hash table, the last frame for page P
  54950. ** can be found by scanning the page-mapping sections of each index block
  54951. ** starting with the last index block and moving toward the first, and
  54952. ** within each index block, starting at the end and moving toward the
  54953. ** beginning. The first entry that equals P corresponds to the frame
  54954. ** holding the content for that page.
  54955. **
  54956. ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
  54957. ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
  54958. ** hash table for each page number in the mapping section, so the hash
  54959. ** table is never more than half full. The expected number of collisions
  54960. ** prior to finding a match is 1. Each entry of the hash table is an
  54961. ** 1-based index of an entry in the mapping section of the same
  54962. ** index block. Let K be the 1-based index of the largest entry in
  54963. ** the mapping section. (For index blocks other than the last, K will
  54964. ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
  54965. ** K will be (mxFrame%HASHTABLE_NPAGE).) Unused slots of the hash table
  54966. ** contain a value of 0.
  54967. **
  54968. ** To look for page P in the hash table, first compute a hash iKey on
  54969. ** P as follows:
  54970. **
  54971. ** iKey = (P * 383) % HASHTABLE_NSLOT
  54972. **
  54973. ** Then start scanning entries of the hash table, starting with iKey
  54974. ** (wrapping around to the beginning when the end of the hash table is
  54975. ** reached) until an unused hash slot is found. Let the first unused slot
  54976. ** be at index iUnused. (iUnused might be less than iKey if there was
  54977. ** wrap-around.) Because the hash table is never more than half full,
  54978. ** the search is guaranteed to eventually hit an unused entry. Let
  54979. ** iMax be the value between iKey and iUnused, closest to iUnused,
  54980. ** where aHash[iMax]==P. If there is no iMax entry (if there exists
  54981. ** no hash slot such that aHash[i]==p) then page P is not in the
  54982. ** current index block. Otherwise the iMax-th mapping entry of the
  54983. ** current index block corresponds to the last entry that references
  54984. ** page P.
  54985. **
  54986. ** A hash search begins with the last index block and moves toward the
  54987. ** first index block, looking for entries corresponding to page P. On
  54988. ** average, only two or three slots in each index block need to be
  54989. ** examined in order to either find the last entry for page P, or to
  54990. ** establish that no such entry exists in the block. Each index block
  54991. ** holds over 4000 entries. So two or three index blocks are sufficient
  54992. ** to cover a typical 10 megabyte WAL file, assuming 1K pages. 8 or 10
  54993. ** comparisons (on average) suffice to either locate a frame in the
  54994. ** WAL or to establish that the frame does not exist in the WAL. This
  54995. ** is much faster than scanning the entire 10MB WAL.
  54996. **
  54997. ** Note that entries are added in order of increasing K. Hence, one
  54998. ** reader might be using some value K0 and a second reader that started
  54999. ** at a later time (after additional transactions were added to the WAL
  55000. ** and to the wal-index) might be using a different value K1, where K1>K0.
  55001. ** Both readers can use the same hash table and mapping section to get
  55002. ** the correct result. There may be entries in the hash table with
  55003. ** K>K0 but to the first reader, those entries will appear to be unused
  55004. ** slots in the hash table and so the first reader will get an answer as
  55005. ** if no values greater than K0 had ever been inserted into the hash table
  55006. ** in the first place - which is what reader one wants. Meanwhile, the
  55007. ** second reader using K1 will see additional values that were inserted
  55008. ** later, which is exactly what reader two wants.
  55009. **
  55010. ** When a rollback occurs, the value of K is decreased. Hash table entries
  55011. ** that correspond to frames greater than the new K value are removed
  55012. ** from the hash table at this point.
  55013. */
  55014. #ifndef SQLITE_OMIT_WAL
  55015. /* #include "wal.h" */
  55016. /*
  55017. ** Trace output macros
  55018. */
  55019. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  55020. SQLITE_PRIVATE int sqlite3WalTrace = 0;
  55021. # define WALTRACE(X) if(sqlite3WalTrace) sqlite3DebugPrintf X
  55022. #else
  55023. # define WALTRACE(X)
  55024. #endif
  55025. /*
  55026. ** WAL mode depends on atomic aligned 32-bit loads and stores in a few
  55027. ** places. The following macros try to make this explicit.
  55028. */
  55029. #if GCC_VESRION>=5004000
  55030. # define AtomicLoad(PTR) __atomic_load_n((PTR),__ATOMIC_RELAXED)
  55031. # define AtomicStore(PTR,VAL) __atomic_store_n((PTR),(VAL),__ATOMIC_RELAXED)
  55032. #else
  55033. # define AtomicLoad(PTR) (*(PTR))
  55034. # define AtomicStore(PTR,VAL) (*(PTR) = (VAL))
  55035. #endif
  55036. /*
  55037. ** The maximum (and only) versions of the wal and wal-index formats
  55038. ** that may be interpreted by this version of SQLite.
  55039. **
  55040. ** If a client begins recovering a WAL file and finds that (a) the checksum
  55041. ** values in the wal-header are correct and (b) the version field is not
  55042. ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
  55043. **
  55044. ** Similarly, if a client successfully reads a wal-index header (i.e. the
  55045. ** checksum test is successful) and finds that the version field is not
  55046. ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
  55047. ** returns SQLITE_CANTOPEN.
  55048. */
  55049. #define WAL_MAX_VERSION 3007000
  55050. #define WALINDEX_MAX_VERSION 3007000
  55051. /*
  55052. ** Index numbers for various locking bytes. WAL_NREADER is the number
  55053. ** of available reader locks and should be at least 3. The default
  55054. ** is SQLITE_SHM_NLOCK==8 and WAL_NREADER==5.
  55055. **
  55056. ** Technically, the various VFSes are free to implement these locks however
  55057. ** they see fit. However, compatibility is encouraged so that VFSes can
  55058. ** interoperate. The standard implemention used on both unix and windows
  55059. ** is for the index number to indicate a byte offset into the
  55060. ** WalCkptInfo.aLock[] array in the wal-index header. In other words, all
  55061. ** locks are on the shm file. The WALINDEX_LOCK_OFFSET constant (which
  55062. ** should be 120) is the location in the shm file for the first locking
  55063. ** byte.
  55064. */
  55065. #define WAL_WRITE_LOCK 0
  55066. #define WAL_ALL_BUT_WRITE 1
  55067. #define WAL_CKPT_LOCK 1
  55068. #define WAL_RECOVER_LOCK 2
  55069. #define WAL_READ_LOCK(I) (3+(I))
  55070. #define WAL_NREADER (SQLITE_SHM_NLOCK-3)
  55071. /* Object declarations */
  55072. typedef struct WalIndexHdr WalIndexHdr;
  55073. typedef struct WalIterator WalIterator;
  55074. typedef struct WalCkptInfo WalCkptInfo;
  55075. /*
  55076. ** The following object holds a copy of the wal-index header content.
  55077. **
  55078. ** The actual header in the wal-index consists of two copies of this
  55079. ** object followed by one instance of the WalCkptInfo object.
  55080. ** For all versions of SQLite through 3.10.0 and probably beyond,
  55081. ** the locking bytes (WalCkptInfo.aLock) start at offset 120 and
  55082. ** the total header size is 136 bytes.
  55083. **
  55084. ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
  55085. ** Or it can be 1 to represent a 65536-byte page. The latter case was
  55086. ** added in 3.7.1 when support for 64K pages was added.
  55087. */
  55088. struct WalIndexHdr {
  55089. u32 iVersion; /* Wal-index version */
  55090. u32 unused; /* Unused (padding) field */
  55091. u32 iChange; /* Counter incremented each transaction */
  55092. u8 isInit; /* 1 when initialized */
  55093. u8 bigEndCksum; /* True if checksums in WAL are big-endian */
  55094. u16 szPage; /* Database page size in bytes. 1==64K */
  55095. u32 mxFrame; /* Index of last valid frame in the WAL */
  55096. u32 nPage; /* Size of database in pages */
  55097. u32 aFrameCksum[2]; /* Checksum of last frame in log */
  55098. u32 aSalt[2]; /* Two salt values copied from WAL header */
  55099. u32 aCksum[2]; /* Checksum over all prior fields */
  55100. };
  55101. /*
  55102. ** A copy of the following object occurs in the wal-index immediately
  55103. ** following the second copy of the WalIndexHdr. This object stores
  55104. ** information used by checkpoint.
  55105. **
  55106. ** nBackfill is the number of frames in the WAL that have been written
  55107. ** back into the database. (We call the act of moving content from WAL to
  55108. ** database "backfilling".) The nBackfill number is never greater than
  55109. ** WalIndexHdr.mxFrame. nBackfill can only be increased by threads
  55110. ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
  55111. ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
  55112. ** mxFrame back to zero when the WAL is reset.
  55113. **
  55114. ** nBackfillAttempted is the largest value of nBackfill that a checkpoint
  55115. ** has attempted to achieve. Normally nBackfill==nBackfillAtempted, however
  55116. ** the nBackfillAttempted is set before any backfilling is done and the
  55117. ** nBackfill is only set after all backfilling completes. So if a checkpoint
  55118. ** crashes, nBackfillAttempted might be larger than nBackfill. The
  55119. ** WalIndexHdr.mxFrame must never be less than nBackfillAttempted.
  55120. **
  55121. ** The aLock[] field is a set of bytes used for locking. These bytes should
  55122. ** never be read or written.
  55123. **
  55124. ** There is one entry in aReadMark[] for each reader lock. If a reader
  55125. ** holds read-lock K, then the value in aReadMark[K] is no greater than
  55126. ** the mxFrame for that reader. The value READMARK_NOT_USED (0xffffffff)
  55127. ** for any aReadMark[] means that entry is unused. aReadMark[0] is
  55128. ** a special case; its value is never used and it exists as a place-holder
  55129. ** to avoid having to offset aReadMark[] indexs by one. Readers holding
  55130. ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
  55131. ** directly from the database.
  55132. **
  55133. ** The value of aReadMark[K] may only be changed by a thread that
  55134. ** is holding an exclusive lock on WAL_READ_LOCK(K). Thus, the value of
  55135. ** aReadMark[K] cannot changed while there is a reader is using that mark
  55136. ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
  55137. **
  55138. ** The checkpointer may only transfer frames from WAL to database where
  55139. ** the frame numbers are less than or equal to every aReadMark[] that is
  55140. ** in use (that is, every aReadMark[j] for which there is a corresponding
  55141. ** WAL_READ_LOCK(j)). New readers (usually) pick the aReadMark[] with the
  55142. ** largest value and will increase an unused aReadMark[] to mxFrame if there
  55143. ** is not already an aReadMark[] equal to mxFrame. The exception to the
  55144. ** previous sentence is when nBackfill equals mxFrame (meaning that everything
  55145. ** in the WAL has been backfilled into the database) then new readers
  55146. ** will choose aReadMark[0] which has value 0 and hence such reader will
  55147. ** get all their all content directly from the database file and ignore
  55148. ** the WAL.
  55149. **
  55150. ** Writers normally append new frames to the end of the WAL. However,
  55151. ** if nBackfill equals mxFrame (meaning that all WAL content has been
  55152. ** written back into the database) and if no readers are using the WAL
  55153. ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
  55154. ** the writer will first "reset" the WAL back to the beginning and start
  55155. ** writing new content beginning at frame 1.
  55156. **
  55157. ** We assume that 32-bit loads are atomic and so no locks are needed in
  55158. ** order to read from any aReadMark[] entries.
  55159. */
  55160. struct WalCkptInfo {
  55161. u32 nBackfill; /* Number of WAL frames backfilled into DB */
  55162. u32 aReadMark[WAL_NREADER]; /* Reader marks */
  55163. u8 aLock[SQLITE_SHM_NLOCK]; /* Reserved space for locks */
  55164. u32 nBackfillAttempted; /* WAL frames perhaps written, or maybe not */
  55165. u32 notUsed0; /* Available for future enhancements */
  55166. };
  55167. #define READMARK_NOT_USED 0xffffffff
  55168. /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
  55169. ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
  55170. ** only support mandatory file-locks, we do not read or write data
  55171. ** from the region of the file on which locks are applied.
  55172. */
  55173. #define WALINDEX_LOCK_OFFSET (sizeof(WalIndexHdr)*2+offsetof(WalCkptInfo,aLock))
  55174. #define WALINDEX_HDR_SIZE (sizeof(WalIndexHdr)*2+sizeof(WalCkptInfo))
  55175. /* Size of header before each frame in wal */
  55176. #define WAL_FRAME_HDRSIZE 24
  55177. /* Size of write ahead log header, including checksum. */
  55178. #define WAL_HDRSIZE 32
  55179. /* WAL magic value. Either this value, or the same value with the least
  55180. ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
  55181. ** big-endian format in the first 4 bytes of a WAL file.
  55182. **
  55183. ** If the LSB is set, then the checksums for each frame within the WAL
  55184. ** file are calculated by treating all data as an array of 32-bit
  55185. ** big-endian words. Otherwise, they are calculated by interpreting
  55186. ** all data as 32-bit little-endian words.
  55187. */
  55188. #define WAL_MAGIC 0x377f0682
  55189. /*
  55190. ** Return the offset of frame iFrame in the write-ahead log file,
  55191. ** assuming a database page size of szPage bytes. The offset returned
  55192. ** is to the start of the write-ahead log frame-header.
  55193. */
  55194. #define walFrameOffset(iFrame, szPage) ( \
  55195. WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE) \
  55196. )
  55197. /*
  55198. ** An open write-ahead log file is represented by an instance of the
  55199. ** following object.
  55200. */
  55201. struct Wal {
  55202. sqlite3_vfs *pVfs; /* The VFS used to create pDbFd */
  55203. sqlite3_file *pDbFd; /* File handle for the database file */
  55204. sqlite3_file *pWalFd; /* File handle for WAL file */
  55205. u32 iCallback; /* Value to pass to log callback (or 0) */
  55206. i64 mxWalSize; /* Truncate WAL to this size upon reset */
  55207. int nWiData; /* Size of array apWiData */
  55208. int szFirstBlock; /* Size of first block written to WAL file */
  55209. volatile u32 **apWiData; /* Pointer to wal-index content in memory */
  55210. u32 szPage; /* Database page size */
  55211. i16 readLock; /* Which read lock is being held. -1 for none */
  55212. u8 syncFlags; /* Flags to use to sync header writes */
  55213. u8 exclusiveMode; /* Non-zero if connection is in exclusive mode */
  55214. u8 writeLock; /* True if in a write transaction */
  55215. u8 ckptLock; /* True if holding a checkpoint lock */
  55216. u8 readOnly; /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
  55217. u8 truncateOnCommit; /* True to truncate WAL file on commit */
  55218. u8 syncHeader; /* Fsync the WAL header if true */
  55219. u8 padToSectorBoundary; /* Pad transactions out to the next sector */
  55220. u8 bShmUnreliable; /* SHM content is read-only and unreliable */
  55221. WalIndexHdr hdr; /* Wal-index header for current transaction */
  55222. u32 minFrame; /* Ignore wal frames before this one */
  55223. u32 iReCksum; /* On commit, recalculate checksums from here */
  55224. const char *zWalName; /* Name of WAL file */
  55225. u32 nCkpt; /* Checkpoint sequence counter in the wal-header */
  55226. #ifdef SQLITE_DEBUG
  55227. u8 lockError; /* True if a locking error has occurred */
  55228. #endif
  55229. #ifdef SQLITE_ENABLE_SNAPSHOT
  55230. WalIndexHdr *pSnapshot; /* Start transaction here if not NULL */
  55231. #endif
  55232. };
  55233. /*
  55234. ** Candidate values for Wal.exclusiveMode.
  55235. */
  55236. #define WAL_NORMAL_MODE 0
  55237. #define WAL_EXCLUSIVE_MODE 1
  55238. #define WAL_HEAPMEMORY_MODE 2
  55239. /*
  55240. ** Possible values for WAL.readOnly
  55241. */
  55242. #define WAL_RDWR 0 /* Normal read/write connection */
  55243. #define WAL_RDONLY 1 /* The WAL file is readonly */
  55244. #define WAL_SHM_RDONLY 2 /* The SHM file is readonly */
  55245. /*
  55246. ** Each page of the wal-index mapping contains a hash-table made up of
  55247. ** an array of HASHTABLE_NSLOT elements of the following type.
  55248. */
  55249. typedef u16 ht_slot;
  55250. /*
  55251. ** This structure is used to implement an iterator that loops through
  55252. ** all frames in the WAL in database page order. Where two or more frames
  55253. ** correspond to the same database page, the iterator visits only the
  55254. ** frame most recently written to the WAL (in other words, the frame with
  55255. ** the largest index).
  55256. **
  55257. ** The internals of this structure are only accessed by:
  55258. **
  55259. ** walIteratorInit() - Create a new iterator,
  55260. ** walIteratorNext() - Step an iterator,
  55261. ** walIteratorFree() - Free an iterator.
  55262. **
  55263. ** This functionality is used by the checkpoint code (see walCheckpoint()).
  55264. */
  55265. struct WalIterator {
  55266. int iPrior; /* Last result returned from the iterator */
  55267. int nSegment; /* Number of entries in aSegment[] */
  55268. struct WalSegment {
  55269. int iNext; /* Next slot in aIndex[] not yet returned */
  55270. ht_slot *aIndex; /* i0, i1, i2... such that aPgno[iN] ascend */
  55271. u32 *aPgno; /* Array of page numbers. */
  55272. int nEntry; /* Nr. of entries in aPgno[] and aIndex[] */
  55273. int iZero; /* Frame number associated with aPgno[0] */
  55274. } aSegment[1]; /* One for every 32KB page in the wal-index */
  55275. };
  55276. /*
  55277. ** Define the parameters of the hash tables in the wal-index file. There
  55278. ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
  55279. ** wal-index.
  55280. **
  55281. ** Changing any of these constants will alter the wal-index format and
  55282. ** create incompatibilities.
  55283. */
  55284. #define HASHTABLE_NPAGE 4096 /* Must be power of 2 */
  55285. #define HASHTABLE_HASH_1 383 /* Should be prime */
  55286. #define HASHTABLE_NSLOT (HASHTABLE_NPAGE*2) /* Must be a power of 2 */
  55287. /*
  55288. ** The block of page numbers associated with the first hash-table in a
  55289. ** wal-index is smaller than usual. This is so that there is a complete
  55290. ** hash-table on each aligned 32KB page of the wal-index.
  55291. */
  55292. #define HASHTABLE_NPAGE_ONE (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
  55293. /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
  55294. #define WALINDEX_PGSZ ( \
  55295. sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
  55296. )
  55297. /*
  55298. ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
  55299. ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
  55300. ** numbered from zero.
  55301. **
  55302. ** If the wal-index is currently smaller the iPage pages then the size
  55303. ** of the wal-index might be increased, but only if it is safe to do
  55304. ** so. It is safe to enlarge the wal-index if pWal->writeLock is true
  55305. ** or pWal->exclusiveMode==WAL_HEAPMEMORY_MODE.
  55306. **
  55307. ** If this call is successful, *ppPage is set to point to the wal-index
  55308. ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
  55309. ** then an SQLite error code is returned and *ppPage is set to 0.
  55310. */
  55311. static SQLITE_NOINLINE int walIndexPageRealloc(
  55312. Wal *pWal, /* The WAL context */
  55313. int iPage, /* The page we seek */
  55314. volatile u32 **ppPage /* Write the page pointer here */
  55315. ){
  55316. int rc = SQLITE_OK;
  55317. /* Enlarge the pWal->apWiData[] array if required */
  55318. if( pWal->nWiData<=iPage ){
  55319. sqlite3_int64 nByte = sizeof(u32*)*(iPage+1);
  55320. volatile u32 **apNew;
  55321. apNew = (volatile u32 **)sqlite3_realloc64((void *)pWal->apWiData, nByte);
  55322. if( !apNew ){
  55323. *ppPage = 0;
  55324. return SQLITE_NOMEM_BKPT;
  55325. }
  55326. memset((void*)&apNew[pWal->nWiData], 0,
  55327. sizeof(u32*)*(iPage+1-pWal->nWiData));
  55328. pWal->apWiData = apNew;
  55329. pWal->nWiData = iPage+1;
  55330. }
  55331. /* Request a pointer to the required page from the VFS */
  55332. assert( pWal->apWiData[iPage]==0 );
  55333. if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
  55334. pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
  55335. if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM_BKPT;
  55336. }else{
  55337. rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
  55338. pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
  55339. );
  55340. assert( pWal->apWiData[iPage]!=0 || rc!=SQLITE_OK || pWal->writeLock==0 );
  55341. testcase( pWal->apWiData[iPage]==0 && rc==SQLITE_OK );
  55342. if( (rc&0xff)==SQLITE_READONLY ){
  55343. pWal->readOnly |= WAL_SHM_RDONLY;
  55344. if( rc==SQLITE_READONLY ){
  55345. rc = SQLITE_OK;
  55346. }
  55347. }
  55348. }
  55349. *ppPage = pWal->apWiData[iPage];
  55350. assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
  55351. return rc;
  55352. }
  55353. static int walIndexPage(
  55354. Wal *pWal, /* The WAL context */
  55355. int iPage, /* The page we seek */
  55356. volatile u32 **ppPage /* Write the page pointer here */
  55357. ){
  55358. if( pWal->nWiData<=iPage || (*ppPage = pWal->apWiData[iPage])==0 ){
  55359. return walIndexPageRealloc(pWal, iPage, ppPage);
  55360. }
  55361. return SQLITE_OK;
  55362. }
  55363. /*
  55364. ** Return a pointer to the WalCkptInfo structure in the wal-index.
  55365. */
  55366. static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
  55367. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  55368. return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
  55369. }
  55370. /*
  55371. ** Return a pointer to the WalIndexHdr structure in the wal-index.
  55372. */
  55373. static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
  55374. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  55375. return (volatile WalIndexHdr*)pWal->apWiData[0];
  55376. }
  55377. /*
  55378. ** The argument to this macro must be of type u32. On a little-endian
  55379. ** architecture, it returns the u32 value that results from interpreting
  55380. ** the 4 bytes as a big-endian value. On a big-endian architecture, it
  55381. ** returns the value that would be produced by interpreting the 4 bytes
  55382. ** of the input value as a little-endian integer.
  55383. */
  55384. #define BYTESWAP32(x) ( \
  55385. (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8) \
  55386. + (((x)&0x00FF0000)>>8) + (((x)&0xFF000000)>>24) \
  55387. )
  55388. /*
  55389. ** Generate or extend an 8 byte checksum based on the data in
  55390. ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
  55391. ** initial values of 0 and 0 if aIn==NULL).
  55392. **
  55393. ** The checksum is written back into aOut[] before returning.
  55394. **
  55395. ** nByte must be a positive multiple of 8.
  55396. */
  55397. static void walChecksumBytes(
  55398. int nativeCksum, /* True for native byte-order, false for non-native */
  55399. u8 *a, /* Content to be checksummed */
  55400. int nByte, /* Bytes of content in a[]. Must be a multiple of 8. */
  55401. const u32 *aIn, /* Initial checksum value input */
  55402. u32 *aOut /* OUT: Final checksum value output */
  55403. ){
  55404. u32 s1, s2;
  55405. u32 *aData = (u32 *)a;
  55406. u32 *aEnd = (u32 *)&a[nByte];
  55407. if( aIn ){
  55408. s1 = aIn[0];
  55409. s2 = aIn[1];
  55410. }else{
  55411. s1 = s2 = 0;
  55412. }
  55413. assert( nByte>=8 );
  55414. assert( (nByte&0x00000007)==0 );
  55415. assert( nByte<=65536 );
  55416. if( nativeCksum ){
  55417. do {
  55418. s1 += *aData++ + s2;
  55419. s2 += *aData++ + s1;
  55420. }while( aData<aEnd );
  55421. }else{
  55422. do {
  55423. s1 += BYTESWAP32(aData[0]) + s2;
  55424. s2 += BYTESWAP32(aData[1]) + s1;
  55425. aData += 2;
  55426. }while( aData<aEnd );
  55427. }
  55428. aOut[0] = s1;
  55429. aOut[1] = s2;
  55430. }
  55431. static void walShmBarrier(Wal *pWal){
  55432. if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
  55433. sqlite3OsShmBarrier(pWal->pDbFd);
  55434. }
  55435. }
  55436. /*
  55437. ** Write the header information in pWal->hdr into the wal-index.
  55438. **
  55439. ** The checksum on pWal->hdr is updated before it is written.
  55440. */
  55441. static void walIndexWriteHdr(Wal *pWal){
  55442. volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
  55443. const int nCksum = offsetof(WalIndexHdr, aCksum);
  55444. assert( pWal->writeLock );
  55445. pWal->hdr.isInit = 1;
  55446. pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
  55447. walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
  55448. memcpy((void*)&aHdr[1], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
  55449. walShmBarrier(pWal);
  55450. memcpy((void*)&aHdr[0], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
  55451. }
  55452. /*
  55453. ** This function encodes a single frame header and writes it to a buffer
  55454. ** supplied by the caller. A frame-header is made up of a series of
  55455. ** 4-byte big-endian integers, as follows:
  55456. **
  55457. ** 0: Page number.
  55458. ** 4: For commit records, the size of the database image in pages
  55459. ** after the commit. For all other records, zero.
  55460. ** 8: Salt-1 (copied from the wal-header)
  55461. ** 12: Salt-2 (copied from the wal-header)
  55462. ** 16: Checksum-1.
  55463. ** 20: Checksum-2.
  55464. */
  55465. static void walEncodeFrame(
  55466. Wal *pWal, /* The write-ahead log */
  55467. u32 iPage, /* Database page number for frame */
  55468. u32 nTruncate, /* New db size (or 0 for non-commit frames) */
  55469. u8 *aData, /* Pointer to page data */
  55470. u8 *aFrame /* OUT: Write encoded frame here */
  55471. ){
  55472. int nativeCksum; /* True for native byte-order checksums */
  55473. u32 *aCksum = pWal->hdr.aFrameCksum;
  55474. assert( WAL_FRAME_HDRSIZE==24 );
  55475. sqlite3Put4byte(&aFrame[0], iPage);
  55476. sqlite3Put4byte(&aFrame[4], nTruncate);
  55477. if( pWal->iReCksum==0 ){
  55478. memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
  55479. nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
  55480. walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
  55481. walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
  55482. sqlite3Put4byte(&aFrame[16], aCksum[0]);
  55483. sqlite3Put4byte(&aFrame[20], aCksum[1]);
  55484. }else{
  55485. memset(&aFrame[8], 0, 16);
  55486. }
  55487. }
  55488. /*
  55489. ** Check to see if the frame with header in aFrame[] and content
  55490. ** in aData[] is valid. If it is a valid frame, fill *piPage and
  55491. ** *pnTruncate and return true. Return if the frame is not valid.
  55492. */
  55493. static int walDecodeFrame(
  55494. Wal *pWal, /* The write-ahead log */
  55495. u32 *piPage, /* OUT: Database page number for frame */
  55496. u32 *pnTruncate, /* OUT: New db size (or 0 if not commit) */
  55497. u8 *aData, /* Pointer to page data (for checksum) */
  55498. u8 *aFrame /* Frame data */
  55499. ){
  55500. int nativeCksum; /* True for native byte-order checksums */
  55501. u32 *aCksum = pWal->hdr.aFrameCksum;
  55502. u32 pgno; /* Page number of the frame */
  55503. assert( WAL_FRAME_HDRSIZE==24 );
  55504. /* A frame is only valid if the salt values in the frame-header
  55505. ** match the salt values in the wal-header.
  55506. */
  55507. if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
  55508. return 0;
  55509. }
  55510. /* A frame is only valid if the page number is creater than zero.
  55511. */
  55512. pgno = sqlite3Get4byte(&aFrame[0]);
  55513. if( pgno==0 ){
  55514. return 0;
  55515. }
  55516. /* A frame is only valid if a checksum of the WAL header,
  55517. ** all prior frams, the first 16 bytes of this frame-header,
  55518. ** and the frame-data matches the checksum in the last 8
  55519. ** bytes of this frame-header.
  55520. */
  55521. nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
  55522. walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
  55523. walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
  55524. if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
  55525. || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
  55526. ){
  55527. /* Checksum failed. */
  55528. return 0;
  55529. }
  55530. /* If we reach this point, the frame is valid. Return the page number
  55531. ** and the new database size.
  55532. */
  55533. *piPage = pgno;
  55534. *pnTruncate = sqlite3Get4byte(&aFrame[4]);
  55535. return 1;
  55536. }
  55537. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  55538. /*
  55539. ** Names of locks. This routine is used to provide debugging output and is not
  55540. ** a part of an ordinary build.
  55541. */
  55542. static const char *walLockName(int lockIdx){
  55543. if( lockIdx==WAL_WRITE_LOCK ){
  55544. return "WRITE-LOCK";
  55545. }else if( lockIdx==WAL_CKPT_LOCK ){
  55546. return "CKPT-LOCK";
  55547. }else if( lockIdx==WAL_RECOVER_LOCK ){
  55548. return "RECOVER-LOCK";
  55549. }else{
  55550. static char zName[15];
  55551. sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
  55552. lockIdx-WAL_READ_LOCK(0));
  55553. return zName;
  55554. }
  55555. }
  55556. #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
  55557. /*
  55558. ** Set or release locks on the WAL. Locks are either shared or exclusive.
  55559. ** A lock cannot be moved directly between shared and exclusive - it must go
  55560. ** through the unlocked state first.
  55561. **
  55562. ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
  55563. */
  55564. static int walLockShared(Wal *pWal, int lockIdx){
  55565. int rc;
  55566. if( pWal->exclusiveMode ) return SQLITE_OK;
  55567. rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
  55568. SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
  55569. WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
  55570. walLockName(lockIdx), rc ? "failed" : "ok"));
  55571. VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
  55572. return rc;
  55573. }
  55574. static void walUnlockShared(Wal *pWal, int lockIdx){
  55575. if( pWal->exclusiveMode ) return;
  55576. (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
  55577. SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
  55578. WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
  55579. }
  55580. static int walLockExclusive(Wal *pWal, int lockIdx, int n){
  55581. int rc;
  55582. if( pWal->exclusiveMode ) return SQLITE_OK;
  55583. rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
  55584. SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
  55585. WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
  55586. walLockName(lockIdx), n, rc ? "failed" : "ok"));
  55587. VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
  55588. return rc;
  55589. }
  55590. static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
  55591. if( pWal->exclusiveMode ) return;
  55592. (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
  55593. SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
  55594. WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
  55595. walLockName(lockIdx), n));
  55596. }
  55597. /*
  55598. ** Compute a hash on a page number. The resulting hash value must land
  55599. ** between 0 and (HASHTABLE_NSLOT-1). The walHashNext() function advances
  55600. ** the hash to the next value in the event of a collision.
  55601. */
  55602. static int walHash(u32 iPage){
  55603. assert( iPage>0 );
  55604. assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
  55605. return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
  55606. }
  55607. static int walNextHash(int iPriorHash){
  55608. return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
  55609. }
  55610. /*
  55611. ** An instance of the WalHashLoc object is used to describe the location
  55612. ** of a page hash table in the wal-index. This becomes the return value
  55613. ** from walHashGet().
  55614. */
  55615. typedef struct WalHashLoc WalHashLoc;
  55616. struct WalHashLoc {
  55617. volatile ht_slot *aHash; /* Start of the wal-index hash table */
  55618. volatile u32 *aPgno; /* aPgno[1] is the page of first frame indexed */
  55619. u32 iZero; /* One less than the frame number of first indexed*/
  55620. };
  55621. /*
  55622. ** Return pointers to the hash table and page number array stored on
  55623. ** page iHash of the wal-index. The wal-index is broken into 32KB pages
  55624. ** numbered starting from 0.
  55625. **
  55626. ** Set output variable pLoc->aHash to point to the start of the hash table
  55627. ** in the wal-index file. Set pLoc->iZero to one less than the frame
  55628. ** number of the first frame indexed by this hash table. If a
  55629. ** slot in the hash table is set to N, it refers to frame number
  55630. ** (pLoc->iZero+N) in the log.
  55631. **
  55632. ** Finally, set pLoc->aPgno so that pLoc->aPgno[1] is the page number of the
  55633. ** first frame indexed by the hash table, frame (pLoc->iZero+1).
  55634. */
  55635. static int walHashGet(
  55636. Wal *pWal, /* WAL handle */
  55637. int iHash, /* Find the iHash'th table */
  55638. WalHashLoc *pLoc /* OUT: Hash table location */
  55639. ){
  55640. int rc; /* Return code */
  55641. rc = walIndexPage(pWal, iHash, &pLoc->aPgno);
  55642. assert( rc==SQLITE_OK || iHash>0 );
  55643. if( rc==SQLITE_OK ){
  55644. pLoc->aHash = (volatile ht_slot *)&pLoc->aPgno[HASHTABLE_NPAGE];
  55645. if( iHash==0 ){
  55646. pLoc->aPgno = &pLoc->aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
  55647. pLoc->iZero = 0;
  55648. }else{
  55649. pLoc->iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
  55650. }
  55651. pLoc->aPgno = &pLoc->aPgno[-1];
  55652. }
  55653. return rc;
  55654. }
  55655. /*
  55656. ** Return the number of the wal-index page that contains the hash-table
  55657. ** and page-number array that contain entries corresponding to WAL frame
  55658. ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
  55659. ** are numbered starting from 0.
  55660. */
  55661. static int walFramePage(u32 iFrame){
  55662. int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
  55663. assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
  55664. && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
  55665. && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
  55666. && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
  55667. && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
  55668. );
  55669. return iHash;
  55670. }
  55671. /*
  55672. ** Return the page number associated with frame iFrame in this WAL.
  55673. */
  55674. static u32 walFramePgno(Wal *pWal, u32 iFrame){
  55675. int iHash = walFramePage(iFrame);
  55676. if( iHash==0 ){
  55677. return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
  55678. }
  55679. return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
  55680. }
  55681. /*
  55682. ** Remove entries from the hash table that point to WAL slots greater
  55683. ** than pWal->hdr.mxFrame.
  55684. **
  55685. ** This function is called whenever pWal->hdr.mxFrame is decreased due
  55686. ** to a rollback or savepoint.
  55687. **
  55688. ** At most only the hash table containing pWal->hdr.mxFrame needs to be
  55689. ** updated. Any later hash tables will be automatically cleared when
  55690. ** pWal->hdr.mxFrame advances to the point where those hash tables are
  55691. ** actually needed.
  55692. */
  55693. static void walCleanupHash(Wal *pWal){
  55694. WalHashLoc sLoc; /* Hash table location */
  55695. int iLimit = 0; /* Zero values greater than this */
  55696. int nByte; /* Number of bytes to zero in aPgno[] */
  55697. int i; /* Used to iterate through aHash[] */
  55698. int rc; /* Return code form walHashGet() */
  55699. assert( pWal->writeLock );
  55700. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
  55701. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
  55702. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
  55703. if( pWal->hdr.mxFrame==0 ) return;
  55704. /* Obtain pointers to the hash-table and page-number array containing
  55705. ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
  55706. ** that the page said hash-table and array reside on is already mapped.(1)
  55707. */
  55708. assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
  55709. assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
  55710. rc = walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &sLoc);
  55711. if( NEVER(rc) ) return; /* Defense-in-depth, in case (1) above is wrong */
  55712. /* Zero all hash-table entries that correspond to frame numbers greater
  55713. ** than pWal->hdr.mxFrame.
  55714. */
  55715. iLimit = pWal->hdr.mxFrame - sLoc.iZero;
  55716. assert( iLimit>0 );
  55717. for(i=0; i<HASHTABLE_NSLOT; i++){
  55718. if( sLoc.aHash[i]>iLimit ){
  55719. sLoc.aHash[i] = 0;
  55720. }
  55721. }
  55722. /* Zero the entries in the aPgno array that correspond to frames with
  55723. ** frame numbers greater than pWal->hdr.mxFrame.
  55724. */
  55725. nByte = (int)((char *)sLoc.aHash - (char *)&sLoc.aPgno[iLimit+1]);
  55726. memset((void *)&sLoc.aPgno[iLimit+1], 0, nByte);
  55727. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  55728. /* Verify that the every entry in the mapping region is still reachable
  55729. ** via the hash table even after the cleanup.
  55730. */
  55731. if( iLimit ){
  55732. int j; /* Loop counter */
  55733. int iKey; /* Hash key */
  55734. for(j=1; j<=iLimit; j++){
  55735. for(iKey=walHash(sLoc.aPgno[j]);sLoc.aHash[iKey];iKey=walNextHash(iKey)){
  55736. if( sLoc.aHash[iKey]==j ) break;
  55737. }
  55738. assert( sLoc.aHash[iKey]==j );
  55739. }
  55740. }
  55741. #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
  55742. }
  55743. /*
  55744. ** Set an entry in the wal-index that will map database page number
  55745. ** pPage into WAL frame iFrame.
  55746. */
  55747. static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
  55748. int rc; /* Return code */
  55749. WalHashLoc sLoc; /* Wal-index hash table location */
  55750. rc = walHashGet(pWal, walFramePage(iFrame), &sLoc);
  55751. /* Assuming the wal-index file was successfully mapped, populate the
  55752. ** page number array and hash table entry.
  55753. */
  55754. if( rc==SQLITE_OK ){
  55755. int iKey; /* Hash table key */
  55756. int idx; /* Value to write to hash-table slot */
  55757. int nCollide; /* Number of hash collisions */
  55758. idx = iFrame - sLoc.iZero;
  55759. assert( idx <= HASHTABLE_NSLOT/2 + 1 );
  55760. /* If this is the first entry to be added to this hash-table, zero the
  55761. ** entire hash table and aPgno[] array before proceeding.
  55762. */
  55763. if( idx==1 ){
  55764. int nByte = (int)((u8 *)&sLoc.aHash[HASHTABLE_NSLOT]
  55765. - (u8 *)&sLoc.aPgno[1]);
  55766. memset((void*)&sLoc.aPgno[1], 0, nByte);
  55767. }
  55768. /* If the entry in aPgno[] is already set, then the previous writer
  55769. ** must have exited unexpectedly in the middle of a transaction (after
  55770. ** writing one or more dirty pages to the WAL to free up memory).
  55771. ** Remove the remnants of that writers uncommitted transaction from
  55772. ** the hash-table before writing any new entries.
  55773. */
  55774. if( sLoc.aPgno[idx] ){
  55775. walCleanupHash(pWal);
  55776. assert( !sLoc.aPgno[idx] );
  55777. }
  55778. /* Write the aPgno[] array entry and the hash-table slot. */
  55779. nCollide = idx;
  55780. for(iKey=walHash(iPage); sLoc.aHash[iKey]; iKey=walNextHash(iKey)){
  55781. if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
  55782. }
  55783. sLoc.aPgno[idx] = iPage;
  55784. sLoc.aHash[iKey] = (ht_slot)idx;
  55785. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  55786. /* Verify that the number of entries in the hash table exactly equals
  55787. ** the number of entries in the mapping region.
  55788. */
  55789. {
  55790. int i; /* Loop counter */
  55791. int nEntry = 0; /* Number of entries in the hash table */
  55792. for(i=0; i<HASHTABLE_NSLOT; i++){ if( sLoc.aHash[i] ) nEntry++; }
  55793. assert( nEntry==idx );
  55794. }
  55795. /* Verify that the every entry in the mapping region is reachable
  55796. ** via the hash table. This turns out to be a really, really expensive
  55797. ** thing to check, so only do this occasionally - not on every
  55798. ** iteration.
  55799. */
  55800. if( (idx&0x3ff)==0 ){
  55801. int i; /* Loop counter */
  55802. for(i=1; i<=idx; i++){
  55803. for(iKey=walHash(sLoc.aPgno[i]);
  55804. sLoc.aHash[iKey];
  55805. iKey=walNextHash(iKey)){
  55806. if( sLoc.aHash[iKey]==i ) break;
  55807. }
  55808. assert( sLoc.aHash[iKey]==i );
  55809. }
  55810. }
  55811. #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
  55812. }
  55813. return rc;
  55814. }
  55815. /*
  55816. ** Recover the wal-index by reading the write-ahead log file.
  55817. **
  55818. ** This routine first tries to establish an exclusive lock on the
  55819. ** wal-index to prevent other threads/processes from doing anything
  55820. ** with the WAL or wal-index while recovery is running. The
  55821. ** WAL_RECOVER_LOCK is also held so that other threads will know
  55822. ** that this thread is running recovery. If unable to establish
  55823. ** the necessary locks, this routine returns SQLITE_BUSY.
  55824. */
  55825. static int walIndexRecover(Wal *pWal){
  55826. int rc; /* Return Code */
  55827. i64 nSize; /* Size of log file */
  55828. u32 aFrameCksum[2] = {0, 0};
  55829. int iLock; /* Lock offset to lock for checkpoint */
  55830. /* Obtain an exclusive lock on all byte in the locking range not already
  55831. ** locked by the caller. The caller is guaranteed to have locked the
  55832. ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
  55833. ** If successful, the same bytes that are locked here are unlocked before
  55834. ** this function returns.
  55835. */
  55836. assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
  55837. assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
  55838. assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
  55839. assert( pWal->writeLock );
  55840. iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
  55841. rc = walLockExclusive(pWal, iLock, WAL_READ_LOCK(0)-iLock);
  55842. if( rc==SQLITE_OK ){
  55843. rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  55844. if( rc!=SQLITE_OK ){
  55845. walUnlockExclusive(pWal, iLock, WAL_READ_LOCK(0)-iLock);
  55846. }
  55847. }
  55848. if( rc ){
  55849. return rc;
  55850. }
  55851. WALTRACE(("WAL%p: recovery begin...\n", pWal));
  55852. memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
  55853. rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
  55854. if( rc!=SQLITE_OK ){
  55855. goto recovery_error;
  55856. }
  55857. if( nSize>WAL_HDRSIZE ){
  55858. u8 aBuf[WAL_HDRSIZE]; /* Buffer to load WAL header into */
  55859. u8 *aFrame = 0; /* Malloc'd buffer to load entire frame */
  55860. int szFrame; /* Number of bytes in buffer aFrame[] */
  55861. u8 *aData; /* Pointer to data part of aFrame buffer */
  55862. int iFrame; /* Index of last frame read */
  55863. i64 iOffset; /* Next offset to read from log file */
  55864. int szPage; /* Page size according to the log */
  55865. u32 magic; /* Magic value read from WAL header */
  55866. u32 version; /* Magic value read from WAL header */
  55867. int isValid; /* True if this frame is valid */
  55868. /* Read in the WAL header. */
  55869. rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
  55870. if( rc!=SQLITE_OK ){
  55871. goto recovery_error;
  55872. }
  55873. /* If the database page size is not a power of two, or is greater than
  55874. ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
  55875. ** data. Similarly, if the 'magic' value is invalid, ignore the whole
  55876. ** WAL file.
  55877. */
  55878. magic = sqlite3Get4byte(&aBuf[0]);
  55879. szPage = sqlite3Get4byte(&aBuf[8]);
  55880. if( (magic&0xFFFFFFFE)!=WAL_MAGIC
  55881. || szPage&(szPage-1)
  55882. || szPage>SQLITE_MAX_PAGE_SIZE
  55883. || szPage<512
  55884. ){
  55885. goto finished;
  55886. }
  55887. pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
  55888. pWal->szPage = szPage;
  55889. pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
  55890. memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
  55891. /* Verify that the WAL header checksum is correct */
  55892. walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
  55893. aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
  55894. );
  55895. if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
  55896. || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
  55897. ){
  55898. goto finished;
  55899. }
  55900. /* Verify that the version number on the WAL format is one that
  55901. ** are able to understand */
  55902. version = sqlite3Get4byte(&aBuf[4]);
  55903. if( version!=WAL_MAX_VERSION ){
  55904. rc = SQLITE_CANTOPEN_BKPT;
  55905. goto finished;
  55906. }
  55907. /* Malloc a buffer to read frames into. */
  55908. szFrame = szPage + WAL_FRAME_HDRSIZE;
  55909. aFrame = (u8 *)sqlite3_malloc64(szFrame);
  55910. if( !aFrame ){
  55911. rc = SQLITE_NOMEM_BKPT;
  55912. goto recovery_error;
  55913. }
  55914. aData = &aFrame[WAL_FRAME_HDRSIZE];
  55915. /* Read all frames from the log file. */
  55916. iFrame = 0;
  55917. for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
  55918. u32 pgno; /* Database page number for frame */
  55919. u32 nTruncate; /* dbsize field from frame header */
  55920. /* Read and decode the next log frame. */
  55921. iFrame++;
  55922. rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
  55923. if( rc!=SQLITE_OK ) break;
  55924. isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
  55925. if( !isValid ) break;
  55926. rc = walIndexAppend(pWal, iFrame, pgno);
  55927. if( rc!=SQLITE_OK ) break;
  55928. /* If nTruncate is non-zero, this is a commit record. */
  55929. if( nTruncate ){
  55930. pWal->hdr.mxFrame = iFrame;
  55931. pWal->hdr.nPage = nTruncate;
  55932. pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
  55933. testcase( szPage<=32768 );
  55934. testcase( szPage>=65536 );
  55935. aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
  55936. aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
  55937. }
  55938. }
  55939. sqlite3_free(aFrame);
  55940. }
  55941. finished:
  55942. if( rc==SQLITE_OK ){
  55943. volatile WalCkptInfo *pInfo;
  55944. int i;
  55945. pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
  55946. pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
  55947. walIndexWriteHdr(pWal);
  55948. /* Reset the checkpoint-header. This is safe because this thread is
  55949. ** currently holding locks that exclude all other readers, writers and
  55950. ** checkpointers.
  55951. */
  55952. pInfo = walCkptInfo(pWal);
  55953. pInfo->nBackfill = 0;
  55954. pInfo->nBackfillAttempted = pWal->hdr.mxFrame;
  55955. pInfo->aReadMark[0] = 0;
  55956. for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
  55957. if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame;
  55958. /* If more than one frame was recovered from the log file, report an
  55959. ** event via sqlite3_log(). This is to help with identifying performance
  55960. ** problems caused by applications routinely shutting down without
  55961. ** checkpointing the log file.
  55962. */
  55963. if( pWal->hdr.nPage ){
  55964. sqlite3_log(SQLITE_NOTICE_RECOVER_WAL,
  55965. "recovered %d frames from WAL file %s",
  55966. pWal->hdr.mxFrame, pWal->zWalName
  55967. );
  55968. }
  55969. }
  55970. recovery_error:
  55971. WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
  55972. walUnlockExclusive(pWal, iLock, WAL_READ_LOCK(0)-iLock);
  55973. walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  55974. return rc;
  55975. }
  55976. /*
  55977. ** Close an open wal-index.
  55978. */
  55979. static void walIndexClose(Wal *pWal, int isDelete){
  55980. if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE || pWal->bShmUnreliable ){
  55981. int i;
  55982. for(i=0; i<pWal->nWiData; i++){
  55983. sqlite3_free((void *)pWal->apWiData[i]);
  55984. pWal->apWiData[i] = 0;
  55985. }
  55986. }
  55987. if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
  55988. sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
  55989. }
  55990. }
  55991. /*
  55992. ** Open a connection to the WAL file zWalName. The database file must
  55993. ** already be opened on connection pDbFd. The buffer that zWalName points
  55994. ** to must remain valid for the lifetime of the returned Wal* handle.
  55995. **
  55996. ** A SHARED lock should be held on the database file when this function
  55997. ** is called. The purpose of this SHARED lock is to prevent any other
  55998. ** client from unlinking the WAL or wal-index file. If another process
  55999. ** were to do this just after this client opened one of these files, the
  56000. ** system would be badly broken.
  56001. **
  56002. ** If the log file is successfully opened, SQLITE_OK is returned and
  56003. ** *ppWal is set to point to a new WAL handle. If an error occurs,
  56004. ** an SQLite error code is returned and *ppWal is left unmodified.
  56005. */
  56006. SQLITE_PRIVATE int sqlite3WalOpen(
  56007. sqlite3_vfs *pVfs, /* vfs module to open wal and wal-index */
  56008. sqlite3_file *pDbFd, /* The open database file */
  56009. const char *zWalName, /* Name of the WAL file */
  56010. int bNoShm, /* True to run in heap-memory mode */
  56011. i64 mxWalSize, /* Truncate WAL to this size on reset */
  56012. Wal **ppWal /* OUT: Allocated Wal handle */
  56013. ){
  56014. int rc; /* Return Code */
  56015. Wal *pRet; /* Object to allocate and return */
  56016. int flags; /* Flags passed to OsOpen() */
  56017. assert( zWalName && zWalName[0] );
  56018. assert( pDbFd );
  56019. /* In the amalgamation, the os_unix.c and os_win.c source files come before
  56020. ** this source file. Verify that the #defines of the locking byte offsets
  56021. ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
  56022. ** For that matter, if the lock offset ever changes from its initial design
  56023. ** value of 120, we need to know that so there is an assert() to check it.
  56024. */
  56025. assert( 120==WALINDEX_LOCK_OFFSET );
  56026. assert( 136==WALINDEX_HDR_SIZE );
  56027. #ifdef WIN_SHM_BASE
  56028. assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
  56029. #endif
  56030. #ifdef UNIX_SHM_BASE
  56031. assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
  56032. #endif
  56033. /* Allocate an instance of struct Wal to return. */
  56034. *ppWal = 0;
  56035. pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
  56036. if( !pRet ){
  56037. return SQLITE_NOMEM_BKPT;
  56038. }
  56039. pRet->pVfs = pVfs;
  56040. pRet->pWalFd = (sqlite3_file *)&pRet[1];
  56041. pRet->pDbFd = pDbFd;
  56042. pRet->readLock = -1;
  56043. pRet->mxWalSize = mxWalSize;
  56044. pRet->zWalName = zWalName;
  56045. pRet->syncHeader = 1;
  56046. pRet->padToSectorBoundary = 1;
  56047. pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
  56048. /* Open file handle on the write-ahead log file. */
  56049. flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
  56050. rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
  56051. if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
  56052. pRet->readOnly = WAL_RDONLY;
  56053. }
  56054. if( rc!=SQLITE_OK ){
  56055. walIndexClose(pRet, 0);
  56056. sqlite3OsClose(pRet->pWalFd);
  56057. sqlite3_free(pRet);
  56058. }else{
  56059. int iDC = sqlite3OsDeviceCharacteristics(pDbFd);
  56060. if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
  56061. if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
  56062. pRet->padToSectorBoundary = 0;
  56063. }
  56064. *ppWal = pRet;
  56065. WALTRACE(("WAL%d: opened\n", pRet));
  56066. }
  56067. return rc;
  56068. }
  56069. /*
  56070. ** Change the size to which the WAL file is trucated on each reset.
  56071. */
  56072. SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
  56073. if( pWal ) pWal->mxWalSize = iLimit;
  56074. }
  56075. /*
  56076. ** Find the smallest page number out of all pages held in the WAL that
  56077. ** has not been returned by any prior invocation of this method on the
  56078. ** same WalIterator object. Write into *piFrame the frame index where
  56079. ** that page was last written into the WAL. Write into *piPage the page
  56080. ** number.
  56081. **
  56082. ** Return 0 on success. If there are no pages in the WAL with a page
  56083. ** number larger than *piPage, then return 1.
  56084. */
  56085. static int walIteratorNext(
  56086. WalIterator *p, /* Iterator */
  56087. u32 *piPage, /* OUT: The page number of the next page */
  56088. u32 *piFrame /* OUT: Wal frame index of next page */
  56089. ){
  56090. u32 iMin; /* Result pgno must be greater than iMin */
  56091. u32 iRet = 0xFFFFFFFF; /* 0xffffffff is never a valid page number */
  56092. int i; /* For looping through segments */
  56093. iMin = p->iPrior;
  56094. assert( iMin<0xffffffff );
  56095. for(i=p->nSegment-1; i>=0; i--){
  56096. struct WalSegment *pSegment = &p->aSegment[i];
  56097. while( pSegment->iNext<pSegment->nEntry ){
  56098. u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
  56099. if( iPg>iMin ){
  56100. if( iPg<iRet ){
  56101. iRet = iPg;
  56102. *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
  56103. }
  56104. break;
  56105. }
  56106. pSegment->iNext++;
  56107. }
  56108. }
  56109. *piPage = p->iPrior = iRet;
  56110. return (iRet==0xFFFFFFFF);
  56111. }
  56112. /*
  56113. ** This function merges two sorted lists into a single sorted list.
  56114. **
  56115. ** aLeft[] and aRight[] are arrays of indices. The sort key is
  56116. ** aContent[aLeft[]] and aContent[aRight[]]. Upon entry, the following
  56117. ** is guaranteed for all J<K:
  56118. **
  56119. ** aContent[aLeft[J]] < aContent[aLeft[K]]
  56120. ** aContent[aRight[J]] < aContent[aRight[K]]
  56121. **
  56122. ** This routine overwrites aRight[] with a new (probably longer) sequence
  56123. ** of indices such that the aRight[] contains every index that appears in
  56124. ** either aLeft[] or the old aRight[] and such that the second condition
  56125. ** above is still met.
  56126. **
  56127. ** The aContent[aLeft[X]] values will be unique for all X. And the
  56128. ** aContent[aRight[X]] values will be unique too. But there might be
  56129. ** one or more combinations of X and Y such that
  56130. **
  56131. ** aLeft[X]!=aRight[Y] && aContent[aLeft[X]] == aContent[aRight[Y]]
  56132. **
  56133. ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
  56134. */
  56135. static void walMerge(
  56136. const u32 *aContent, /* Pages in wal - keys for the sort */
  56137. ht_slot *aLeft, /* IN: Left hand input list */
  56138. int nLeft, /* IN: Elements in array *paLeft */
  56139. ht_slot **paRight, /* IN/OUT: Right hand input list */
  56140. int *pnRight, /* IN/OUT: Elements in *paRight */
  56141. ht_slot *aTmp /* Temporary buffer */
  56142. ){
  56143. int iLeft = 0; /* Current index in aLeft */
  56144. int iRight = 0; /* Current index in aRight */
  56145. int iOut = 0; /* Current index in output buffer */
  56146. int nRight = *pnRight;
  56147. ht_slot *aRight = *paRight;
  56148. assert( nLeft>0 && nRight>0 );
  56149. while( iRight<nRight || iLeft<nLeft ){
  56150. ht_slot logpage;
  56151. Pgno dbpage;
  56152. if( (iLeft<nLeft)
  56153. && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
  56154. ){
  56155. logpage = aLeft[iLeft++];
  56156. }else{
  56157. logpage = aRight[iRight++];
  56158. }
  56159. dbpage = aContent[logpage];
  56160. aTmp[iOut++] = logpage;
  56161. if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
  56162. assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
  56163. assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
  56164. }
  56165. *paRight = aLeft;
  56166. *pnRight = iOut;
  56167. memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
  56168. }
  56169. /*
  56170. ** Sort the elements in list aList using aContent[] as the sort key.
  56171. ** Remove elements with duplicate keys, preferring to keep the
  56172. ** larger aList[] values.
  56173. **
  56174. ** The aList[] entries are indices into aContent[]. The values in
  56175. ** aList[] are to be sorted so that for all J<K:
  56176. **
  56177. ** aContent[aList[J]] < aContent[aList[K]]
  56178. **
  56179. ** For any X and Y such that
  56180. **
  56181. ** aContent[aList[X]] == aContent[aList[Y]]
  56182. **
  56183. ** Keep the larger of the two values aList[X] and aList[Y] and discard
  56184. ** the smaller.
  56185. */
  56186. static void walMergesort(
  56187. const u32 *aContent, /* Pages in wal */
  56188. ht_slot *aBuffer, /* Buffer of at least *pnList items to use */
  56189. ht_slot *aList, /* IN/OUT: List to sort */
  56190. int *pnList /* IN/OUT: Number of elements in aList[] */
  56191. ){
  56192. struct Sublist {
  56193. int nList; /* Number of elements in aList */
  56194. ht_slot *aList; /* Pointer to sub-list content */
  56195. };
  56196. const int nList = *pnList; /* Size of input list */
  56197. int nMerge = 0; /* Number of elements in list aMerge */
  56198. ht_slot *aMerge = 0; /* List to be merged */
  56199. int iList; /* Index into input list */
  56200. u32 iSub = 0; /* Index into aSub array */
  56201. struct Sublist aSub[13]; /* Array of sub-lists */
  56202. memset(aSub, 0, sizeof(aSub));
  56203. assert( nList<=HASHTABLE_NPAGE && nList>0 );
  56204. assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
  56205. for(iList=0; iList<nList; iList++){
  56206. nMerge = 1;
  56207. aMerge = &aList[iList];
  56208. for(iSub=0; iList & (1<<iSub); iSub++){
  56209. struct Sublist *p;
  56210. assert( iSub<ArraySize(aSub) );
  56211. p = &aSub[iSub];
  56212. assert( p->aList && p->nList<=(1<<iSub) );
  56213. assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
  56214. walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
  56215. }
  56216. aSub[iSub].aList = aMerge;
  56217. aSub[iSub].nList = nMerge;
  56218. }
  56219. for(iSub++; iSub<ArraySize(aSub); iSub++){
  56220. if( nList & (1<<iSub) ){
  56221. struct Sublist *p;
  56222. assert( iSub<ArraySize(aSub) );
  56223. p = &aSub[iSub];
  56224. assert( p->nList<=(1<<iSub) );
  56225. assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
  56226. walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
  56227. }
  56228. }
  56229. assert( aMerge==aList );
  56230. *pnList = nMerge;
  56231. #ifdef SQLITE_DEBUG
  56232. {
  56233. int i;
  56234. for(i=1; i<*pnList; i++){
  56235. assert( aContent[aList[i]] > aContent[aList[i-1]] );
  56236. }
  56237. }
  56238. #endif
  56239. }
  56240. /*
  56241. ** Free an iterator allocated by walIteratorInit().
  56242. */
  56243. static void walIteratorFree(WalIterator *p){
  56244. sqlite3_free(p);
  56245. }
  56246. /*
  56247. ** Construct a WalInterator object that can be used to loop over all
  56248. ** pages in the WAL following frame nBackfill in ascending order. Frames
  56249. ** nBackfill or earlier may be included - excluding them is an optimization
  56250. ** only. The caller must hold the checkpoint lock.
  56251. **
  56252. ** On success, make *pp point to the newly allocated WalInterator object
  56253. ** return SQLITE_OK. Otherwise, return an error code. If this routine
  56254. ** returns an error, the value of *pp is undefined.
  56255. **
  56256. ** The calling routine should invoke walIteratorFree() to destroy the
  56257. ** WalIterator object when it has finished with it.
  56258. */
  56259. static int walIteratorInit(Wal *pWal, u32 nBackfill, WalIterator **pp){
  56260. WalIterator *p; /* Return value */
  56261. int nSegment; /* Number of segments to merge */
  56262. u32 iLast; /* Last frame in log */
  56263. sqlite3_int64 nByte; /* Number of bytes to allocate */
  56264. int i; /* Iterator variable */
  56265. ht_slot *aTmp; /* Temp space used by merge-sort */
  56266. int rc = SQLITE_OK; /* Return Code */
  56267. /* This routine only runs while holding the checkpoint lock. And
  56268. ** it only runs if there is actually content in the log (mxFrame>0).
  56269. */
  56270. assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
  56271. iLast = pWal->hdr.mxFrame;
  56272. /* Allocate space for the WalIterator object. */
  56273. nSegment = walFramePage(iLast) + 1;
  56274. nByte = sizeof(WalIterator)
  56275. + (nSegment-1)*sizeof(struct WalSegment)
  56276. + iLast*sizeof(ht_slot);
  56277. p = (WalIterator *)sqlite3_malloc64(nByte);
  56278. if( !p ){
  56279. return SQLITE_NOMEM_BKPT;
  56280. }
  56281. memset(p, 0, nByte);
  56282. p->nSegment = nSegment;
  56283. /* Allocate temporary space used by the merge-sort routine. This block
  56284. ** of memory will be freed before this function returns.
  56285. */
  56286. aTmp = (ht_slot *)sqlite3_malloc64(
  56287. sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
  56288. );
  56289. if( !aTmp ){
  56290. rc = SQLITE_NOMEM_BKPT;
  56291. }
  56292. for(i=walFramePage(nBackfill+1); rc==SQLITE_OK && i<nSegment; i++){
  56293. WalHashLoc sLoc;
  56294. rc = walHashGet(pWal, i, &sLoc);
  56295. if( rc==SQLITE_OK ){
  56296. int j; /* Counter variable */
  56297. int nEntry; /* Number of entries in this segment */
  56298. ht_slot *aIndex; /* Sorted index for this segment */
  56299. sLoc.aPgno++;
  56300. if( (i+1)==nSegment ){
  56301. nEntry = (int)(iLast - sLoc.iZero);
  56302. }else{
  56303. nEntry = (int)((u32*)sLoc.aHash - (u32*)sLoc.aPgno);
  56304. }
  56305. aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[sLoc.iZero];
  56306. sLoc.iZero++;
  56307. for(j=0; j<nEntry; j++){
  56308. aIndex[j] = (ht_slot)j;
  56309. }
  56310. walMergesort((u32 *)sLoc.aPgno, aTmp, aIndex, &nEntry);
  56311. p->aSegment[i].iZero = sLoc.iZero;
  56312. p->aSegment[i].nEntry = nEntry;
  56313. p->aSegment[i].aIndex = aIndex;
  56314. p->aSegment[i].aPgno = (u32 *)sLoc.aPgno;
  56315. }
  56316. }
  56317. sqlite3_free(aTmp);
  56318. if( rc!=SQLITE_OK ){
  56319. walIteratorFree(p);
  56320. p = 0;
  56321. }
  56322. *pp = p;
  56323. return rc;
  56324. }
  56325. /*
  56326. ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
  56327. ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
  56328. ** busy-handler function. Invoke it and retry the lock until either the
  56329. ** lock is successfully obtained or the busy-handler returns 0.
  56330. */
  56331. static int walBusyLock(
  56332. Wal *pWal, /* WAL connection */
  56333. int (*xBusy)(void*), /* Function to call when busy */
  56334. void *pBusyArg, /* Context argument for xBusyHandler */
  56335. int lockIdx, /* Offset of first byte to lock */
  56336. int n /* Number of bytes to lock */
  56337. ){
  56338. int rc;
  56339. do {
  56340. rc = walLockExclusive(pWal, lockIdx, n);
  56341. }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
  56342. return rc;
  56343. }
  56344. /*
  56345. ** The cache of the wal-index header must be valid to call this function.
  56346. ** Return the page-size in bytes used by the database.
  56347. */
  56348. static int walPagesize(Wal *pWal){
  56349. return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
  56350. }
  56351. /*
  56352. ** The following is guaranteed when this function is called:
  56353. **
  56354. ** a) the WRITER lock is held,
  56355. ** b) the entire log file has been checkpointed, and
  56356. ** c) any existing readers are reading exclusively from the database
  56357. ** file - there are no readers that may attempt to read a frame from
  56358. ** the log file.
  56359. **
  56360. ** This function updates the shared-memory structures so that the next
  56361. ** client to write to the database (which may be this one) does so by
  56362. ** writing frames into the start of the log file.
  56363. **
  56364. ** The value of parameter salt1 is used as the aSalt[1] value in the
  56365. ** new wal-index header. It should be passed a pseudo-random value (i.e.
  56366. ** one obtained from sqlite3_randomness()).
  56367. */
  56368. static void walRestartHdr(Wal *pWal, u32 salt1){
  56369. volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
  56370. int i; /* Loop counter */
  56371. u32 *aSalt = pWal->hdr.aSalt; /* Big-endian salt values */
  56372. pWal->nCkpt++;
  56373. pWal->hdr.mxFrame = 0;
  56374. sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
  56375. memcpy(&pWal->hdr.aSalt[1], &salt1, 4);
  56376. walIndexWriteHdr(pWal);
  56377. pInfo->nBackfill = 0;
  56378. pInfo->nBackfillAttempted = 0;
  56379. pInfo->aReadMark[1] = 0;
  56380. for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
  56381. assert( pInfo->aReadMark[0]==0 );
  56382. }
  56383. /*
  56384. ** Copy as much content as we can from the WAL back into the database file
  56385. ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
  56386. **
  56387. ** The amount of information copies from WAL to database might be limited
  56388. ** by active readers. This routine will never overwrite a database page
  56389. ** that a concurrent reader might be using.
  56390. **
  56391. ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
  56392. ** SQLite is in WAL-mode in synchronous=NORMAL. That means that if
  56393. ** checkpoints are always run by a background thread or background
  56394. ** process, foreground threads will never block on a lengthy fsync call.
  56395. **
  56396. ** Fsync is called on the WAL before writing content out of the WAL and
  56397. ** into the database. This ensures that if the new content is persistent
  56398. ** in the WAL and can be recovered following a power-loss or hard reset.
  56399. **
  56400. ** Fsync is also called on the database file if (and only if) the entire
  56401. ** WAL content is copied into the database file. This second fsync makes
  56402. ** it safe to delete the WAL since the new content will persist in the
  56403. ** database file.
  56404. **
  56405. ** This routine uses and updates the nBackfill field of the wal-index header.
  56406. ** This is the only routine that will increase the value of nBackfill.
  56407. ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
  56408. ** its value.)
  56409. **
  56410. ** The caller must be holding sufficient locks to ensure that no other
  56411. ** checkpoint is running (in any other thread or process) at the same
  56412. ** time.
  56413. */
  56414. static int walCheckpoint(
  56415. Wal *pWal, /* Wal connection */
  56416. sqlite3 *db, /* Check for interrupts on this handle */
  56417. int eMode, /* One of PASSIVE, FULL or RESTART */
  56418. int (*xBusy)(void*), /* Function to call when busy */
  56419. void *pBusyArg, /* Context argument for xBusyHandler */
  56420. int sync_flags, /* Flags for OsSync() (or 0) */
  56421. u8 *zBuf /* Temporary buffer to use */
  56422. ){
  56423. int rc = SQLITE_OK; /* Return code */
  56424. int szPage; /* Database page-size */
  56425. WalIterator *pIter = 0; /* Wal iterator context */
  56426. u32 iDbpage = 0; /* Next database page to write */
  56427. u32 iFrame = 0; /* Wal frame containing data for iDbpage */
  56428. u32 mxSafeFrame; /* Max frame that can be backfilled */
  56429. u32 mxPage; /* Max database page to write */
  56430. int i; /* Loop counter */
  56431. volatile WalCkptInfo *pInfo; /* The checkpoint status information */
  56432. szPage = walPagesize(pWal);
  56433. testcase( szPage<=32768 );
  56434. testcase( szPage>=65536 );
  56435. pInfo = walCkptInfo(pWal);
  56436. if( pInfo->nBackfill<pWal->hdr.mxFrame ){
  56437. /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
  56438. ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
  56439. assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
  56440. /* Compute in mxSafeFrame the index of the last frame of the WAL that is
  56441. ** safe to write into the database. Frames beyond mxSafeFrame might
  56442. ** overwrite database pages that are in use by active readers and thus
  56443. ** cannot be backfilled from the WAL.
  56444. */
  56445. mxSafeFrame = pWal->hdr.mxFrame;
  56446. mxPage = pWal->hdr.nPage;
  56447. for(i=1; i<WAL_NREADER; i++){
  56448. /* Thread-sanitizer reports that the following is an unsafe read,
  56449. ** as some other thread may be in the process of updating the value
  56450. ** of the aReadMark[] slot. The assumption here is that if that is
  56451. ** happening, the other client may only be increasing the value,
  56452. ** not decreasing it. So assuming either that either the "old" or
  56453. ** "new" version of the value is read, and not some arbitrary value
  56454. ** that would never be written by a real client, things are still
  56455. ** safe. */
  56456. u32 y = pInfo->aReadMark[i];
  56457. if( mxSafeFrame>y ){
  56458. assert( y<=pWal->hdr.mxFrame );
  56459. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
  56460. if( rc==SQLITE_OK ){
  56461. pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
  56462. walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
  56463. }else if( rc==SQLITE_BUSY ){
  56464. mxSafeFrame = y;
  56465. xBusy = 0;
  56466. }else{
  56467. goto walcheckpoint_out;
  56468. }
  56469. }
  56470. }
  56471. /* Allocate the iterator */
  56472. if( pInfo->nBackfill<mxSafeFrame ){
  56473. rc = walIteratorInit(pWal, pInfo->nBackfill, &pIter);
  56474. assert( rc==SQLITE_OK || pIter==0 );
  56475. }
  56476. if( pIter
  56477. && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0),1))==SQLITE_OK
  56478. ){
  56479. u32 nBackfill = pInfo->nBackfill;
  56480. pInfo->nBackfillAttempted = mxSafeFrame;
  56481. /* Sync the WAL to disk */
  56482. rc = sqlite3OsSync(pWal->pWalFd, CKPT_SYNC_FLAGS(sync_flags));
  56483. /* If the database may grow as a result of this checkpoint, hint
  56484. ** about the eventual size of the db file to the VFS layer.
  56485. */
  56486. if( rc==SQLITE_OK ){
  56487. i64 nReq = ((i64)mxPage * szPage);
  56488. i64 nSize; /* Current size of database file */
  56489. rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
  56490. if( rc==SQLITE_OK && nSize<nReq ){
  56491. sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
  56492. }
  56493. }
  56494. /* Iterate through the contents of the WAL, copying data to the db file */
  56495. while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
  56496. i64 iOffset;
  56497. assert( walFramePgno(pWal, iFrame)==iDbpage );
  56498. if( db->u1.isInterrupted ){
  56499. rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT;
  56500. break;
  56501. }
  56502. if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ){
  56503. continue;
  56504. }
  56505. iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
  56506. /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
  56507. rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
  56508. if( rc!=SQLITE_OK ) break;
  56509. iOffset = (iDbpage-1)*(i64)szPage;
  56510. testcase( IS_BIG_INT(iOffset) );
  56511. rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
  56512. if( rc!=SQLITE_OK ) break;
  56513. }
  56514. /* If work was actually accomplished... */
  56515. if( rc==SQLITE_OK ){
  56516. if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
  56517. i64 szDb = pWal->hdr.nPage*(i64)szPage;
  56518. testcase( IS_BIG_INT(szDb) );
  56519. rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
  56520. if( rc==SQLITE_OK ){
  56521. rc = sqlite3OsSync(pWal->pDbFd, CKPT_SYNC_FLAGS(sync_flags));
  56522. }
  56523. }
  56524. if( rc==SQLITE_OK ){
  56525. pInfo->nBackfill = mxSafeFrame;
  56526. }
  56527. }
  56528. /* Release the reader lock held while backfilling */
  56529. walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
  56530. }
  56531. if( rc==SQLITE_BUSY ){
  56532. /* Reset the return code so as not to report a checkpoint failure
  56533. ** just because there are active readers. */
  56534. rc = SQLITE_OK;
  56535. }
  56536. }
  56537. /* If this is an SQLITE_CHECKPOINT_RESTART or TRUNCATE operation, and the
  56538. ** entire wal file has been copied into the database file, then block
  56539. ** until all readers have finished using the wal file. This ensures that
  56540. ** the next process to write to the database restarts the wal file.
  56541. */
  56542. if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
  56543. assert( pWal->writeLock );
  56544. if( pInfo->nBackfill<pWal->hdr.mxFrame ){
  56545. rc = SQLITE_BUSY;
  56546. }else if( eMode>=SQLITE_CHECKPOINT_RESTART ){
  56547. u32 salt1;
  56548. sqlite3_randomness(4, &salt1);
  56549. assert( pInfo->nBackfill==pWal->hdr.mxFrame );
  56550. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
  56551. if( rc==SQLITE_OK ){
  56552. if( eMode==SQLITE_CHECKPOINT_TRUNCATE ){
  56553. /* IMPLEMENTATION-OF: R-44699-57140 This mode works the same way as
  56554. ** SQLITE_CHECKPOINT_RESTART with the addition that it also
  56555. ** truncates the log file to zero bytes just prior to a
  56556. ** successful return.
  56557. **
  56558. ** In theory, it might be safe to do this without updating the
  56559. ** wal-index header in shared memory, as all subsequent reader or
  56560. ** writer clients should see that the entire log file has been
  56561. ** checkpointed and behave accordingly. This seems unsafe though,
  56562. ** as it would leave the system in a state where the contents of
  56563. ** the wal-index header do not match the contents of the
  56564. ** file-system. To avoid this, update the wal-index header to
  56565. ** indicate that the log file contains zero valid frames. */
  56566. walRestartHdr(pWal, salt1);
  56567. rc = sqlite3OsTruncate(pWal->pWalFd, 0);
  56568. }
  56569. walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  56570. }
  56571. }
  56572. }
  56573. walcheckpoint_out:
  56574. walIteratorFree(pIter);
  56575. return rc;
  56576. }
  56577. /*
  56578. ** If the WAL file is currently larger than nMax bytes in size, truncate
  56579. ** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
  56580. */
  56581. static void walLimitSize(Wal *pWal, i64 nMax){
  56582. i64 sz;
  56583. int rx;
  56584. sqlite3BeginBenignMalloc();
  56585. rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
  56586. if( rx==SQLITE_OK && (sz > nMax ) ){
  56587. rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
  56588. }
  56589. sqlite3EndBenignMalloc();
  56590. if( rx ){
  56591. sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
  56592. }
  56593. }
  56594. /*
  56595. ** Close a connection to a log file.
  56596. */
  56597. SQLITE_PRIVATE int sqlite3WalClose(
  56598. Wal *pWal, /* Wal to close */
  56599. sqlite3 *db, /* For interrupt flag */
  56600. int sync_flags, /* Flags to pass to OsSync() (or 0) */
  56601. int nBuf,
  56602. u8 *zBuf /* Buffer of at least nBuf bytes */
  56603. ){
  56604. int rc = SQLITE_OK;
  56605. if( pWal ){
  56606. int isDelete = 0; /* True to unlink wal and wal-index files */
  56607. /* If an EXCLUSIVE lock can be obtained on the database file (using the
  56608. ** ordinary, rollback-mode locking methods, this guarantees that the
  56609. ** connection associated with this log file is the only connection to
  56610. ** the database. In this case checkpoint the database and unlink both
  56611. ** the wal and wal-index files.
  56612. **
  56613. ** The EXCLUSIVE lock is not released before returning.
  56614. */
  56615. if( zBuf!=0
  56616. && SQLITE_OK==(rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE))
  56617. ){
  56618. if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
  56619. pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
  56620. }
  56621. rc = sqlite3WalCheckpoint(pWal, db,
  56622. SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
  56623. );
  56624. if( rc==SQLITE_OK ){
  56625. int bPersist = -1;
  56626. sqlite3OsFileControlHint(
  56627. pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
  56628. );
  56629. if( bPersist!=1 ){
  56630. /* Try to delete the WAL file if the checkpoint completed and
  56631. ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
  56632. ** mode (!bPersist) */
  56633. isDelete = 1;
  56634. }else if( pWal->mxWalSize>=0 ){
  56635. /* Try to truncate the WAL file to zero bytes if the checkpoint
  56636. ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
  56637. ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
  56638. ** non-negative value (pWal->mxWalSize>=0). Note that we truncate
  56639. ** to zero bytes as truncating to the journal_size_limit might
  56640. ** leave a corrupt WAL file on disk. */
  56641. walLimitSize(pWal, 0);
  56642. }
  56643. }
  56644. }
  56645. walIndexClose(pWal, isDelete);
  56646. sqlite3OsClose(pWal->pWalFd);
  56647. if( isDelete ){
  56648. sqlite3BeginBenignMalloc();
  56649. sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
  56650. sqlite3EndBenignMalloc();
  56651. }
  56652. WALTRACE(("WAL%p: closed\n", pWal));
  56653. sqlite3_free((void *)pWal->apWiData);
  56654. sqlite3_free(pWal);
  56655. }
  56656. return rc;
  56657. }
  56658. /*
  56659. ** Try to read the wal-index header. Return 0 on success and 1 if
  56660. ** there is a problem.
  56661. **
  56662. ** The wal-index is in shared memory. Another thread or process might
  56663. ** be writing the header at the same time this procedure is trying to
  56664. ** read it, which might result in inconsistency. A dirty read is detected
  56665. ** by verifying that both copies of the header are the same and also by
  56666. ** a checksum on the header.
  56667. **
  56668. ** If and only if the read is consistent and the header is different from
  56669. ** pWal->hdr, then pWal->hdr is updated to the content of the new header
  56670. ** and *pChanged is set to 1.
  56671. **
  56672. ** If the checksum cannot be verified return non-zero. If the header
  56673. ** is read successfully and the checksum verified, return zero.
  56674. */
  56675. static int walIndexTryHdr(Wal *pWal, int *pChanged){
  56676. u32 aCksum[2]; /* Checksum on the header content */
  56677. WalIndexHdr h1, h2; /* Two copies of the header content */
  56678. WalIndexHdr volatile *aHdr; /* Header in shared memory */
  56679. /* The first page of the wal-index must be mapped at this point. */
  56680. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  56681. /* Read the header. This might happen concurrently with a write to the
  56682. ** same area of shared memory on a different CPU in a SMP,
  56683. ** meaning it is possible that an inconsistent snapshot is read
  56684. ** from the file. If this happens, return non-zero.
  56685. **
  56686. ** There are two copies of the header at the beginning of the wal-index.
  56687. ** When reading, read [0] first then [1]. Writes are in the reverse order.
  56688. ** Memory barriers are used to prevent the compiler or the hardware from
  56689. ** reordering the reads and writes.
  56690. */
  56691. aHdr = walIndexHdr(pWal);
  56692. memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
  56693. walShmBarrier(pWal);
  56694. memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
  56695. if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
  56696. return 1; /* Dirty read */
  56697. }
  56698. if( h1.isInit==0 ){
  56699. return 1; /* Malformed header - probably all zeros */
  56700. }
  56701. walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
  56702. if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
  56703. return 1; /* Checksum does not match */
  56704. }
  56705. if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
  56706. *pChanged = 1;
  56707. memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
  56708. pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
  56709. testcase( pWal->szPage<=32768 );
  56710. testcase( pWal->szPage>=65536 );
  56711. }
  56712. /* The header was successfully read. Return zero. */
  56713. return 0;
  56714. }
  56715. /*
  56716. ** This is the value that walTryBeginRead returns when it needs to
  56717. ** be retried.
  56718. */
  56719. #define WAL_RETRY (-1)
  56720. /*
  56721. ** Read the wal-index header from the wal-index and into pWal->hdr.
  56722. ** If the wal-header appears to be corrupt, try to reconstruct the
  56723. ** wal-index from the WAL before returning.
  56724. **
  56725. ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
  56726. ** changed by this operation. If pWal->hdr is unchanged, set *pChanged
  56727. ** to 0.
  56728. **
  56729. ** If the wal-index header is successfully read, return SQLITE_OK.
  56730. ** Otherwise an SQLite error code.
  56731. */
  56732. static int walIndexReadHdr(Wal *pWal, int *pChanged){
  56733. int rc; /* Return code */
  56734. int badHdr; /* True if a header read failed */
  56735. volatile u32 *page0; /* Chunk of wal-index containing header */
  56736. /* Ensure that page 0 of the wal-index (the page that contains the
  56737. ** wal-index header) is mapped. Return early if an error occurs here.
  56738. */
  56739. assert( pChanged );
  56740. rc = walIndexPage(pWal, 0, &page0);
  56741. if( rc!=SQLITE_OK ){
  56742. assert( rc!=SQLITE_READONLY ); /* READONLY changed to OK in walIndexPage */
  56743. if( rc==SQLITE_READONLY_CANTINIT ){
  56744. /* The SQLITE_READONLY_CANTINIT return means that the shared-memory
  56745. ** was openable but is not writable, and this thread is unable to
  56746. ** confirm that another write-capable connection has the shared-memory
  56747. ** open, and hence the content of the shared-memory is unreliable,
  56748. ** since the shared-memory might be inconsistent with the WAL file
  56749. ** and there is no writer on hand to fix it. */
  56750. assert( page0==0 );
  56751. assert( pWal->writeLock==0 );
  56752. assert( pWal->readOnly & WAL_SHM_RDONLY );
  56753. pWal->bShmUnreliable = 1;
  56754. pWal->exclusiveMode = WAL_HEAPMEMORY_MODE;
  56755. *pChanged = 1;
  56756. }else{
  56757. return rc; /* Any other non-OK return is just an error */
  56758. }
  56759. }else{
  56760. /* page0 can be NULL if the SHM is zero bytes in size and pWal->writeLock
  56761. ** is zero, which prevents the SHM from growing */
  56762. testcase( page0!=0 );
  56763. }
  56764. assert( page0!=0 || pWal->writeLock==0 );
  56765. /* If the first page of the wal-index has been mapped, try to read the
  56766. ** wal-index header immediately, without holding any lock. This usually
  56767. ** works, but may fail if the wal-index header is corrupt or currently
  56768. ** being modified by another thread or process.
  56769. */
  56770. badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
  56771. /* If the first attempt failed, it might have been due to a race
  56772. ** with a writer. So get a WRITE lock and try again.
  56773. */
  56774. assert( badHdr==0 || pWal->writeLock==0 );
  56775. if( badHdr ){
  56776. if( pWal->bShmUnreliable==0 && (pWal->readOnly & WAL_SHM_RDONLY) ){
  56777. if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
  56778. walUnlockShared(pWal, WAL_WRITE_LOCK);
  56779. rc = SQLITE_READONLY_RECOVERY;
  56780. }
  56781. }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
  56782. pWal->writeLock = 1;
  56783. if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
  56784. badHdr = walIndexTryHdr(pWal, pChanged);
  56785. if( badHdr ){
  56786. /* If the wal-index header is still malformed even while holding
  56787. ** a WRITE lock, it can only mean that the header is corrupted and
  56788. ** needs to be reconstructed. So run recovery to do exactly that.
  56789. */
  56790. rc = walIndexRecover(pWal);
  56791. *pChanged = 1;
  56792. }
  56793. }
  56794. pWal->writeLock = 0;
  56795. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  56796. }
  56797. }
  56798. /* If the header is read successfully, check the version number to make
  56799. ** sure the wal-index was not constructed with some future format that
  56800. ** this version of SQLite cannot understand.
  56801. */
  56802. if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
  56803. rc = SQLITE_CANTOPEN_BKPT;
  56804. }
  56805. if( pWal->bShmUnreliable ){
  56806. if( rc!=SQLITE_OK ){
  56807. walIndexClose(pWal, 0);
  56808. pWal->bShmUnreliable = 0;
  56809. assert( pWal->nWiData>0 && pWal->apWiData[0]==0 );
  56810. /* walIndexRecover() might have returned SHORT_READ if a concurrent
  56811. ** writer truncated the WAL out from under it. If that happens, it
  56812. ** indicates that a writer has fixed the SHM file for us, so retry */
  56813. if( rc==SQLITE_IOERR_SHORT_READ ) rc = WAL_RETRY;
  56814. }
  56815. pWal->exclusiveMode = WAL_NORMAL_MODE;
  56816. }
  56817. return rc;
  56818. }
  56819. /*
  56820. ** Open a transaction in a connection where the shared-memory is read-only
  56821. ** and where we cannot verify that there is a separate write-capable connection
  56822. ** on hand to keep the shared-memory up-to-date with the WAL file.
  56823. **
  56824. ** This can happen, for example, when the shared-memory is implemented by
  56825. ** memory-mapping a *-shm file, where a prior writer has shut down and
  56826. ** left the *-shm file on disk, and now the present connection is trying
  56827. ** to use that database but lacks write permission on the *-shm file.
  56828. ** Other scenarios are also possible, depending on the VFS implementation.
  56829. **
  56830. ** Precondition:
  56831. **
  56832. ** The *-wal file has been read and an appropriate wal-index has been
  56833. ** constructed in pWal->apWiData[] using heap memory instead of shared
  56834. ** memory.
  56835. **
  56836. ** If this function returns SQLITE_OK, then the read transaction has
  56837. ** been successfully opened. In this case output variable (*pChanged)
  56838. ** is set to true before returning if the caller should discard the
  56839. ** contents of the page cache before proceeding. Or, if it returns
  56840. ** WAL_RETRY, then the heap memory wal-index has been discarded and
  56841. ** the caller should retry opening the read transaction from the
  56842. ** beginning (including attempting to map the *-shm file).
  56843. **
  56844. ** If an error occurs, an SQLite error code is returned.
  56845. */
  56846. static int walBeginShmUnreliable(Wal *pWal, int *pChanged){
  56847. i64 szWal; /* Size of wal file on disk in bytes */
  56848. i64 iOffset; /* Current offset when reading wal file */
  56849. u8 aBuf[WAL_HDRSIZE]; /* Buffer to load WAL header into */
  56850. u8 *aFrame = 0; /* Malloc'd buffer to load entire frame */
  56851. int szFrame; /* Number of bytes in buffer aFrame[] */
  56852. u8 *aData; /* Pointer to data part of aFrame buffer */
  56853. volatile void *pDummy; /* Dummy argument for xShmMap */
  56854. int rc; /* Return code */
  56855. u32 aSaveCksum[2]; /* Saved copy of pWal->hdr.aFrameCksum */
  56856. assert( pWal->bShmUnreliable );
  56857. assert( pWal->readOnly & WAL_SHM_RDONLY );
  56858. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  56859. /* Take WAL_READ_LOCK(0). This has the effect of preventing any
  56860. ** writers from running a checkpoint, but does not stop them
  56861. ** from running recovery. */
  56862. rc = walLockShared(pWal, WAL_READ_LOCK(0));
  56863. if( rc!=SQLITE_OK ){
  56864. if( rc==SQLITE_BUSY ) rc = WAL_RETRY;
  56865. goto begin_unreliable_shm_out;
  56866. }
  56867. pWal->readLock = 0;
  56868. /* Check to see if a separate writer has attached to the shared-memory area,
  56869. ** thus making the shared-memory "reliable" again. Do this by invoking
  56870. ** the xShmMap() routine of the VFS and looking to see if the return
  56871. ** is SQLITE_READONLY instead of SQLITE_READONLY_CANTINIT.
  56872. **
  56873. ** If the shared-memory is now "reliable" return WAL_RETRY, which will
  56874. ** cause the heap-memory WAL-index to be discarded and the actual
  56875. ** shared memory to be used in its place.
  56876. **
  56877. ** This step is important because, even though this connection is holding
  56878. ** the WAL_READ_LOCK(0) which prevents a checkpoint, a writer might
  56879. ** have already checkpointed the WAL file and, while the current
  56880. ** is active, wrap the WAL and start overwriting frames that this
  56881. ** process wants to use.
  56882. **
  56883. ** Once sqlite3OsShmMap() has been called for an sqlite3_file and has
  56884. ** returned any SQLITE_READONLY value, it must return only SQLITE_READONLY
  56885. ** or SQLITE_READONLY_CANTINIT or some error for all subsequent invocations,
  56886. ** even if some external agent does a "chmod" to make the shared-memory
  56887. ** writable by us, until sqlite3OsShmUnmap() has been called.
  56888. ** This is a requirement on the VFS implementation.
  56889. */
  56890. rc = sqlite3OsShmMap(pWal->pDbFd, 0, WALINDEX_PGSZ, 0, &pDummy);
  56891. assert( rc!=SQLITE_OK ); /* SQLITE_OK not possible for read-only connection */
  56892. if( rc!=SQLITE_READONLY_CANTINIT ){
  56893. rc = (rc==SQLITE_READONLY ? WAL_RETRY : rc);
  56894. goto begin_unreliable_shm_out;
  56895. }
  56896. /* We reach this point only if the real shared-memory is still unreliable.
  56897. ** Assume the in-memory WAL-index substitute is correct and load it
  56898. ** into pWal->hdr.
  56899. */
  56900. memcpy(&pWal->hdr, (void*)walIndexHdr(pWal), sizeof(WalIndexHdr));
  56901. /* Make sure some writer hasn't come in and changed the WAL file out
  56902. ** from under us, then disconnected, while we were not looking.
  56903. */
  56904. rc = sqlite3OsFileSize(pWal->pWalFd, &szWal);
  56905. if( rc!=SQLITE_OK ){
  56906. goto begin_unreliable_shm_out;
  56907. }
  56908. if( szWal<WAL_HDRSIZE ){
  56909. /* If the wal file is too small to contain a wal-header and the
  56910. ** wal-index header has mxFrame==0, then it must be safe to proceed
  56911. ** reading the database file only. However, the page cache cannot
  56912. ** be trusted, as a read/write connection may have connected, written
  56913. ** the db, run a checkpoint, truncated the wal file and disconnected
  56914. ** since this client's last read transaction. */
  56915. *pChanged = 1;
  56916. rc = (pWal->hdr.mxFrame==0 ? SQLITE_OK : WAL_RETRY);
  56917. goto begin_unreliable_shm_out;
  56918. }
  56919. /* Check the salt keys at the start of the wal file still match. */
  56920. rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
  56921. if( rc!=SQLITE_OK ){
  56922. goto begin_unreliable_shm_out;
  56923. }
  56924. if( memcmp(&pWal->hdr.aSalt, &aBuf[16], 8) ){
  56925. /* Some writer has wrapped the WAL file while we were not looking.
  56926. ** Return WAL_RETRY which will cause the in-memory WAL-index to be
  56927. ** rebuilt. */
  56928. rc = WAL_RETRY;
  56929. goto begin_unreliable_shm_out;
  56930. }
  56931. /* Allocate a buffer to read frames into */
  56932. szFrame = pWal->hdr.szPage + WAL_FRAME_HDRSIZE;
  56933. aFrame = (u8 *)sqlite3_malloc64(szFrame);
  56934. if( aFrame==0 ){
  56935. rc = SQLITE_NOMEM_BKPT;
  56936. goto begin_unreliable_shm_out;
  56937. }
  56938. aData = &aFrame[WAL_FRAME_HDRSIZE];
  56939. /* Check to see if a complete transaction has been appended to the
  56940. ** wal file since the heap-memory wal-index was created. If so, the
  56941. ** heap-memory wal-index is discarded and WAL_RETRY returned to
  56942. ** the caller. */
  56943. aSaveCksum[0] = pWal->hdr.aFrameCksum[0];
  56944. aSaveCksum[1] = pWal->hdr.aFrameCksum[1];
  56945. for(iOffset=walFrameOffset(pWal->hdr.mxFrame+1, pWal->hdr.szPage);
  56946. iOffset+szFrame<=szWal;
  56947. iOffset+=szFrame
  56948. ){
  56949. u32 pgno; /* Database page number for frame */
  56950. u32 nTruncate; /* dbsize field from frame header */
  56951. /* Read and decode the next log frame. */
  56952. rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
  56953. if( rc!=SQLITE_OK ) break;
  56954. if( !walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame) ) break;
  56955. /* If nTruncate is non-zero, then a complete transaction has been
  56956. ** appended to this wal file. Set rc to WAL_RETRY and break out of
  56957. ** the loop. */
  56958. if( nTruncate ){
  56959. rc = WAL_RETRY;
  56960. break;
  56961. }
  56962. }
  56963. pWal->hdr.aFrameCksum[0] = aSaveCksum[0];
  56964. pWal->hdr.aFrameCksum[1] = aSaveCksum[1];
  56965. begin_unreliable_shm_out:
  56966. sqlite3_free(aFrame);
  56967. if( rc!=SQLITE_OK ){
  56968. int i;
  56969. for(i=0; i<pWal->nWiData; i++){
  56970. sqlite3_free((void*)pWal->apWiData[i]);
  56971. pWal->apWiData[i] = 0;
  56972. }
  56973. pWal->bShmUnreliable = 0;
  56974. sqlite3WalEndReadTransaction(pWal);
  56975. *pChanged = 1;
  56976. }
  56977. return rc;
  56978. }
  56979. /*
  56980. ** Attempt to start a read transaction. This might fail due to a race or
  56981. ** other transient condition. When that happens, it returns WAL_RETRY to
  56982. ** indicate to the caller that it is safe to retry immediately.
  56983. **
  56984. ** On success return SQLITE_OK. On a permanent failure (such an
  56985. ** I/O error or an SQLITE_BUSY because another process is running
  56986. ** recovery) return a positive error code.
  56987. **
  56988. ** The useWal parameter is true to force the use of the WAL and disable
  56989. ** the case where the WAL is bypassed because it has been completely
  56990. ** checkpointed. If useWal==0 then this routine calls walIndexReadHdr()
  56991. ** to make a copy of the wal-index header into pWal->hdr. If the
  56992. ** wal-index header has changed, *pChanged is set to 1 (as an indication
  56993. ** to the caller that the local page cache is obsolete and needs to be
  56994. ** flushed.) When useWal==1, the wal-index header is assumed to already
  56995. ** be loaded and the pChanged parameter is unused.
  56996. **
  56997. ** The caller must set the cnt parameter to the number of prior calls to
  56998. ** this routine during the current read attempt that returned WAL_RETRY.
  56999. ** This routine will start taking more aggressive measures to clear the
  57000. ** race conditions after multiple WAL_RETRY returns, and after an excessive
  57001. ** number of errors will ultimately return SQLITE_PROTOCOL. The
  57002. ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
  57003. ** and is not honoring the locking protocol. There is a vanishingly small
  57004. ** chance that SQLITE_PROTOCOL could be returned because of a run of really
  57005. ** bad luck when there is lots of contention for the wal-index, but that
  57006. ** possibility is so small that it can be safely neglected, we believe.
  57007. **
  57008. ** On success, this routine obtains a read lock on
  57009. ** WAL_READ_LOCK(pWal->readLock). The pWal->readLock integer is
  57010. ** in the range 0 <= pWal->readLock < WAL_NREADER. If pWal->readLock==(-1)
  57011. ** that means the Wal does not hold any read lock. The reader must not
  57012. ** access any database page that is modified by a WAL frame up to and
  57013. ** including frame number aReadMark[pWal->readLock]. The reader will
  57014. ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
  57015. ** Or if pWal->readLock==0, then the reader will ignore the WAL
  57016. ** completely and get all content directly from the database file.
  57017. ** If the useWal parameter is 1 then the WAL will never be ignored and
  57018. ** this routine will always set pWal->readLock>0 on success.
  57019. ** When the read transaction is completed, the caller must release the
  57020. ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
  57021. **
  57022. ** This routine uses the nBackfill and aReadMark[] fields of the header
  57023. ** to select a particular WAL_READ_LOCK() that strives to let the
  57024. ** checkpoint process do as much work as possible. This routine might
  57025. ** update values of the aReadMark[] array in the header, but if it does
  57026. ** so it takes care to hold an exclusive lock on the corresponding
  57027. ** WAL_READ_LOCK() while changing values.
  57028. */
  57029. static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
  57030. volatile WalCkptInfo *pInfo; /* Checkpoint information in wal-index */
  57031. u32 mxReadMark; /* Largest aReadMark[] value */
  57032. int mxI; /* Index of largest aReadMark[] value */
  57033. int i; /* Loop counter */
  57034. int rc = SQLITE_OK; /* Return code */
  57035. u32 mxFrame; /* Wal frame to lock to */
  57036. assert( pWal->readLock<0 ); /* Not currently locked */
  57037. /* useWal may only be set for read/write connections */
  57038. assert( (pWal->readOnly & WAL_SHM_RDONLY)==0 || useWal==0 );
  57039. /* Take steps to avoid spinning forever if there is a protocol error.
  57040. **
  57041. ** Circumstances that cause a RETRY should only last for the briefest
  57042. ** instances of time. No I/O or other system calls are done while the
  57043. ** locks are held, so the locks should not be held for very long. But
  57044. ** if we are unlucky, another process that is holding a lock might get
  57045. ** paged out or take a page-fault that is time-consuming to resolve,
  57046. ** during the few nanoseconds that it is holding the lock. In that case,
  57047. ** it might take longer than normal for the lock to free.
  57048. **
  57049. ** After 5 RETRYs, we begin calling sqlite3OsSleep(). The first few
  57050. ** calls to sqlite3OsSleep() have a delay of 1 microsecond. Really this
  57051. ** is more of a scheduler yield than an actual delay. But on the 10th
  57052. ** an subsequent retries, the delays start becoming longer and longer,
  57053. ** so that on the 100th (and last) RETRY we delay for 323 milliseconds.
  57054. ** The total delay time before giving up is less than 10 seconds.
  57055. */
  57056. if( cnt>5 ){
  57057. int nDelay = 1; /* Pause time in microseconds */
  57058. if( cnt>100 ){
  57059. VVA_ONLY( pWal->lockError = 1; )
  57060. return SQLITE_PROTOCOL;
  57061. }
  57062. if( cnt>=10 ) nDelay = (cnt-9)*(cnt-9)*39;
  57063. sqlite3OsSleep(pWal->pVfs, nDelay);
  57064. }
  57065. if( !useWal ){
  57066. assert( rc==SQLITE_OK );
  57067. if( pWal->bShmUnreliable==0 ){
  57068. rc = walIndexReadHdr(pWal, pChanged);
  57069. }
  57070. if( rc==SQLITE_BUSY ){
  57071. /* If there is not a recovery running in another thread or process
  57072. ** then convert BUSY errors to WAL_RETRY. If recovery is known to
  57073. ** be running, convert BUSY to BUSY_RECOVERY. There is a race here
  57074. ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
  57075. ** would be technically correct. But the race is benign since with
  57076. ** WAL_RETRY this routine will be called again and will probably be
  57077. ** right on the second iteration.
  57078. */
  57079. if( pWal->apWiData[0]==0 ){
  57080. /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
  57081. ** We assume this is a transient condition, so return WAL_RETRY. The
  57082. ** xShmMap() implementation used by the default unix and win32 VFS
  57083. ** modules may return SQLITE_BUSY due to a race condition in the
  57084. ** code that determines whether or not the shared-memory region
  57085. ** must be zeroed before the requested page is returned.
  57086. */
  57087. rc = WAL_RETRY;
  57088. }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
  57089. walUnlockShared(pWal, WAL_RECOVER_LOCK);
  57090. rc = WAL_RETRY;
  57091. }else if( rc==SQLITE_BUSY ){
  57092. rc = SQLITE_BUSY_RECOVERY;
  57093. }
  57094. }
  57095. if( rc!=SQLITE_OK ){
  57096. return rc;
  57097. }
  57098. else if( pWal->bShmUnreliable ){
  57099. return walBeginShmUnreliable(pWal, pChanged);
  57100. }
  57101. }
  57102. assert( pWal->nWiData>0 );
  57103. assert( pWal->apWiData[0]!=0 );
  57104. pInfo = walCkptInfo(pWal);
  57105. if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame
  57106. #ifdef SQLITE_ENABLE_SNAPSHOT
  57107. && (pWal->pSnapshot==0 || pWal->hdr.mxFrame==0)
  57108. #endif
  57109. ){
  57110. /* The WAL has been completely backfilled (or it is empty).
  57111. ** and can be safely ignored.
  57112. */
  57113. rc = walLockShared(pWal, WAL_READ_LOCK(0));
  57114. walShmBarrier(pWal);
  57115. if( rc==SQLITE_OK ){
  57116. if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
  57117. /* It is not safe to allow the reader to continue here if frames
  57118. ** may have been appended to the log before READ_LOCK(0) was obtained.
  57119. ** When holding READ_LOCK(0), the reader ignores the entire log file,
  57120. ** which implies that the database file contains a trustworthy
  57121. ** snapshot. Since holding READ_LOCK(0) prevents a checkpoint from
  57122. ** happening, this is usually correct.
  57123. **
  57124. ** However, if frames have been appended to the log (or if the log
  57125. ** is wrapped and written for that matter) before the READ_LOCK(0)
  57126. ** is obtained, that is not necessarily true. A checkpointer may
  57127. ** have started to backfill the appended frames but crashed before
  57128. ** it finished. Leaving a corrupt image in the database file.
  57129. */
  57130. walUnlockShared(pWal, WAL_READ_LOCK(0));
  57131. return WAL_RETRY;
  57132. }
  57133. pWal->readLock = 0;
  57134. return SQLITE_OK;
  57135. }else if( rc!=SQLITE_BUSY ){
  57136. return rc;
  57137. }
  57138. }
  57139. /* If we get this far, it means that the reader will want to use
  57140. ** the WAL to get at content from recent commits. The job now is
  57141. ** to select one of the aReadMark[] entries that is closest to
  57142. ** but not exceeding pWal->hdr.mxFrame and lock that entry.
  57143. */
  57144. mxReadMark = 0;
  57145. mxI = 0;
  57146. mxFrame = pWal->hdr.mxFrame;
  57147. #ifdef SQLITE_ENABLE_SNAPSHOT
  57148. if( pWal->pSnapshot && pWal->pSnapshot->mxFrame<mxFrame ){
  57149. mxFrame = pWal->pSnapshot->mxFrame;
  57150. }
  57151. #endif
  57152. for(i=1; i<WAL_NREADER; i++){
  57153. u32 thisMark = AtomicLoad(pInfo->aReadMark+i);
  57154. if( mxReadMark<=thisMark && thisMark<=mxFrame ){
  57155. assert( thisMark!=READMARK_NOT_USED );
  57156. mxReadMark = thisMark;
  57157. mxI = i;
  57158. }
  57159. }
  57160. if( (pWal->readOnly & WAL_SHM_RDONLY)==0
  57161. && (mxReadMark<mxFrame || mxI==0)
  57162. ){
  57163. for(i=1; i<WAL_NREADER; i++){
  57164. rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
  57165. if( rc==SQLITE_OK ){
  57166. mxReadMark = AtomicStore(pInfo->aReadMark+i,mxFrame);
  57167. mxI = i;
  57168. walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
  57169. break;
  57170. }else if( rc!=SQLITE_BUSY ){
  57171. return rc;
  57172. }
  57173. }
  57174. }
  57175. if( mxI==0 ){
  57176. assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
  57177. return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTINIT;
  57178. }
  57179. rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
  57180. if( rc ){
  57181. return rc==SQLITE_BUSY ? WAL_RETRY : rc;
  57182. }
  57183. /* Now that the read-lock has been obtained, check that neither the
  57184. ** value in the aReadMark[] array or the contents of the wal-index
  57185. ** header have changed.
  57186. **
  57187. ** It is necessary to check that the wal-index header did not change
  57188. ** between the time it was read and when the shared-lock was obtained
  57189. ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
  57190. ** that the log file may have been wrapped by a writer, or that frames
  57191. ** that occur later in the log than pWal->hdr.mxFrame may have been
  57192. ** copied into the database by a checkpointer. If either of these things
  57193. ** happened, then reading the database with the current value of
  57194. ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
  57195. ** instead.
  57196. **
  57197. ** Before checking that the live wal-index header has not changed
  57198. ** since it was read, set Wal.minFrame to the first frame in the wal
  57199. ** file that has not yet been checkpointed. This client will not need
  57200. ** to read any frames earlier than minFrame from the wal file - they
  57201. ** can be safely read directly from the database file.
  57202. **
  57203. ** Because a ShmBarrier() call is made between taking the copy of
  57204. ** nBackfill and checking that the wal-header in shared-memory still
  57205. ** matches the one cached in pWal->hdr, it is guaranteed that the
  57206. ** checkpointer that set nBackfill was not working with a wal-index
  57207. ** header newer than that cached in pWal->hdr. If it were, that could
  57208. ** cause a problem. The checkpointer could omit to checkpoint
  57209. ** a version of page X that lies before pWal->minFrame (call that version
  57210. ** A) on the basis that there is a newer version (version B) of the same
  57211. ** page later in the wal file. But if version B happens to like past
  57212. ** frame pWal->hdr.mxFrame - then the client would incorrectly assume
  57213. ** that it can read version A from the database file. However, since
  57214. ** we can guarantee that the checkpointer that set nBackfill could not
  57215. ** see any pages past pWal->hdr.mxFrame, this problem does not come up.
  57216. */
  57217. pWal->minFrame = AtomicLoad(&pInfo->nBackfill)+1;
  57218. walShmBarrier(pWal);
  57219. if( AtomicLoad(pInfo->aReadMark+mxI)!=mxReadMark
  57220. || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
  57221. ){
  57222. walUnlockShared(pWal, WAL_READ_LOCK(mxI));
  57223. return WAL_RETRY;
  57224. }else{
  57225. assert( mxReadMark<=pWal->hdr.mxFrame );
  57226. pWal->readLock = (i16)mxI;
  57227. }
  57228. return rc;
  57229. }
  57230. #ifdef SQLITE_ENABLE_SNAPSHOT
  57231. /*
  57232. ** Attempt to reduce the value of the WalCkptInfo.nBackfillAttempted
  57233. ** variable so that older snapshots can be accessed. To do this, loop
  57234. ** through all wal frames from nBackfillAttempted to (nBackfill+1),
  57235. ** comparing their content to the corresponding page with the database
  57236. ** file, if any. Set nBackfillAttempted to the frame number of the
  57237. ** first frame for which the wal file content matches the db file.
  57238. **
  57239. ** This is only really safe if the file-system is such that any page
  57240. ** writes made by earlier checkpointers were atomic operations, which
  57241. ** is not always true. It is also possible that nBackfillAttempted
  57242. ** may be left set to a value larger than expected, if a wal frame
  57243. ** contains content that duplicate of an earlier version of the same
  57244. ** page.
  57245. **
  57246. ** SQLITE_OK is returned if successful, or an SQLite error code if an
  57247. ** error occurs. It is not an error if nBackfillAttempted cannot be
  57248. ** decreased at all.
  57249. */
  57250. SQLITE_PRIVATE int sqlite3WalSnapshotRecover(Wal *pWal){
  57251. int rc;
  57252. assert( pWal->readLock>=0 );
  57253. rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
  57254. if( rc==SQLITE_OK ){
  57255. volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
  57256. int szPage = (int)pWal->szPage;
  57257. i64 szDb; /* Size of db file in bytes */
  57258. rc = sqlite3OsFileSize(pWal->pDbFd, &szDb);
  57259. if( rc==SQLITE_OK ){
  57260. void *pBuf1 = sqlite3_malloc(szPage);
  57261. void *pBuf2 = sqlite3_malloc(szPage);
  57262. if( pBuf1==0 || pBuf2==0 ){
  57263. rc = SQLITE_NOMEM;
  57264. }else{
  57265. u32 i = pInfo->nBackfillAttempted;
  57266. for(i=pInfo->nBackfillAttempted; i>pInfo->nBackfill; i--){
  57267. WalHashLoc sLoc; /* Hash table location */
  57268. u32 pgno; /* Page number in db file */
  57269. i64 iDbOff; /* Offset of db file entry */
  57270. i64 iWalOff; /* Offset of wal file entry */
  57271. rc = walHashGet(pWal, walFramePage(i), &sLoc);
  57272. if( rc!=SQLITE_OK ) break;
  57273. pgno = sLoc.aPgno[i-sLoc.iZero];
  57274. iDbOff = (i64)(pgno-1) * szPage;
  57275. if( iDbOff+szPage<=szDb ){
  57276. iWalOff = walFrameOffset(i, szPage) + WAL_FRAME_HDRSIZE;
  57277. rc = sqlite3OsRead(pWal->pWalFd, pBuf1, szPage, iWalOff);
  57278. if( rc==SQLITE_OK ){
  57279. rc = sqlite3OsRead(pWal->pDbFd, pBuf2, szPage, iDbOff);
  57280. }
  57281. if( rc!=SQLITE_OK || 0==memcmp(pBuf1, pBuf2, szPage) ){
  57282. break;
  57283. }
  57284. }
  57285. pInfo->nBackfillAttempted = i-1;
  57286. }
  57287. }
  57288. sqlite3_free(pBuf1);
  57289. sqlite3_free(pBuf2);
  57290. }
  57291. walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
  57292. }
  57293. return rc;
  57294. }
  57295. #endif /* SQLITE_ENABLE_SNAPSHOT */
  57296. /*
  57297. ** Begin a read transaction on the database.
  57298. **
  57299. ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
  57300. ** it takes a snapshot of the state of the WAL and wal-index for the current
  57301. ** instant in time. The current thread will continue to use this snapshot.
  57302. ** Other threads might append new content to the WAL and wal-index but
  57303. ** that extra content is ignored by the current thread.
  57304. **
  57305. ** If the database contents have changes since the previous read
  57306. ** transaction, then *pChanged is set to 1 before returning. The
  57307. ** Pager layer will use this to know that its cache is stale and
  57308. ** needs to be flushed.
  57309. */
  57310. SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
  57311. int rc; /* Return code */
  57312. int cnt = 0; /* Number of TryBeginRead attempts */
  57313. #ifdef SQLITE_ENABLE_SNAPSHOT
  57314. int bChanged = 0;
  57315. WalIndexHdr *pSnapshot = pWal->pSnapshot;
  57316. if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
  57317. bChanged = 1;
  57318. }
  57319. #endif
  57320. do{
  57321. rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
  57322. }while( rc==WAL_RETRY );
  57323. testcase( (rc&0xff)==SQLITE_BUSY );
  57324. testcase( (rc&0xff)==SQLITE_IOERR );
  57325. testcase( rc==SQLITE_PROTOCOL );
  57326. testcase( rc==SQLITE_OK );
  57327. #ifdef SQLITE_ENABLE_SNAPSHOT
  57328. if( rc==SQLITE_OK ){
  57329. if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
  57330. /* At this point the client has a lock on an aReadMark[] slot holding
  57331. ** a value equal to or smaller than pSnapshot->mxFrame, but pWal->hdr
  57332. ** is populated with the wal-index header corresponding to the head
  57333. ** of the wal file. Verify that pSnapshot is still valid before
  57334. ** continuing. Reasons why pSnapshot might no longer be valid:
  57335. **
  57336. ** (1) The WAL file has been reset since the snapshot was taken.
  57337. ** In this case, the salt will have changed.
  57338. **
  57339. ** (2) A checkpoint as been attempted that wrote frames past
  57340. ** pSnapshot->mxFrame into the database file. Note that the
  57341. ** checkpoint need not have completed for this to cause problems.
  57342. */
  57343. volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
  57344. assert( pWal->readLock>0 || pWal->hdr.mxFrame==0 );
  57345. assert( pInfo->aReadMark[pWal->readLock]<=pSnapshot->mxFrame );
  57346. /* It is possible that there is a checkpointer thread running
  57347. ** concurrent with this code. If this is the case, it may be that the
  57348. ** checkpointer has already determined that it will checkpoint
  57349. ** snapshot X, where X is later in the wal file than pSnapshot, but
  57350. ** has not yet set the pInfo->nBackfillAttempted variable to indicate
  57351. ** its intent. To avoid the race condition this leads to, ensure that
  57352. ** there is no checkpointer process by taking a shared CKPT lock
  57353. ** before checking pInfo->nBackfillAttempted.
  57354. **
  57355. ** TODO: Does the aReadMark[] lock prevent a checkpointer from doing
  57356. ** this already?
  57357. */
  57358. rc = walLockShared(pWal, WAL_CKPT_LOCK);
  57359. if( rc==SQLITE_OK ){
  57360. /* Check that the wal file has not been wrapped. Assuming that it has
  57361. ** not, also check that no checkpointer has attempted to checkpoint any
  57362. ** frames beyond pSnapshot->mxFrame. If either of these conditions are
  57363. ** true, return SQLITE_ERROR_SNAPSHOT. Otherwise, overwrite pWal->hdr
  57364. ** with *pSnapshot and set *pChanged as appropriate for opening the
  57365. ** snapshot. */
  57366. if( !memcmp(pSnapshot->aSalt, pWal->hdr.aSalt, sizeof(pWal->hdr.aSalt))
  57367. && pSnapshot->mxFrame>=pInfo->nBackfillAttempted
  57368. ){
  57369. assert( pWal->readLock>0 );
  57370. memcpy(&pWal->hdr, pSnapshot, sizeof(WalIndexHdr));
  57371. *pChanged = bChanged;
  57372. }else{
  57373. rc = SQLITE_ERROR_SNAPSHOT;
  57374. }
  57375. /* Release the shared CKPT lock obtained above. */
  57376. walUnlockShared(pWal, WAL_CKPT_LOCK);
  57377. pWal->minFrame = 1;
  57378. }
  57379. if( rc!=SQLITE_OK ){
  57380. sqlite3WalEndReadTransaction(pWal);
  57381. }
  57382. }
  57383. }
  57384. #endif
  57385. return rc;
  57386. }
  57387. /*
  57388. ** Finish with a read transaction. All this does is release the
  57389. ** read-lock.
  57390. */
  57391. SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
  57392. sqlite3WalEndWriteTransaction(pWal);
  57393. if( pWal->readLock>=0 ){
  57394. walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
  57395. pWal->readLock = -1;
  57396. }
  57397. }
  57398. /*
  57399. ** Search the wal file for page pgno. If found, set *piRead to the frame that
  57400. ** contains the page. Otherwise, if pgno is not in the wal file, set *piRead
  57401. ** to zero.
  57402. **
  57403. ** Return SQLITE_OK if successful, or an error code if an error occurs. If an
  57404. ** error does occur, the final value of *piRead is undefined.
  57405. */
  57406. SQLITE_PRIVATE int sqlite3WalFindFrame(
  57407. Wal *pWal, /* WAL handle */
  57408. Pgno pgno, /* Database page number to read data for */
  57409. u32 *piRead /* OUT: Frame number (or zero) */
  57410. ){
  57411. u32 iRead = 0; /* If !=0, WAL frame to return data from */
  57412. u32 iLast = pWal->hdr.mxFrame; /* Last page in WAL for this reader */
  57413. int iHash; /* Used to loop through N hash tables */
  57414. int iMinHash;
  57415. /* This routine is only be called from within a read transaction. */
  57416. assert( pWal->readLock>=0 || pWal->lockError );
  57417. /* If the "last page" field of the wal-index header snapshot is 0, then
  57418. ** no data will be read from the wal under any circumstances. Return early
  57419. ** in this case as an optimization. Likewise, if pWal->readLock==0,
  57420. ** then the WAL is ignored by the reader so return early, as if the
  57421. ** WAL were empty.
  57422. */
  57423. if( iLast==0 || (pWal->readLock==0 && pWal->bShmUnreliable==0) ){
  57424. *piRead = 0;
  57425. return SQLITE_OK;
  57426. }
  57427. /* Search the hash table or tables for an entry matching page number
  57428. ** pgno. Each iteration of the following for() loop searches one
  57429. ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
  57430. **
  57431. ** This code might run concurrently to the code in walIndexAppend()
  57432. ** that adds entries to the wal-index (and possibly to this hash
  57433. ** table). This means the value just read from the hash
  57434. ** slot (aHash[iKey]) may have been added before or after the
  57435. ** current read transaction was opened. Values added after the
  57436. ** read transaction was opened may have been written incorrectly -
  57437. ** i.e. these slots may contain garbage data. However, we assume
  57438. ** that any slots written before the current read transaction was
  57439. ** opened remain unmodified.
  57440. **
  57441. ** For the reasons above, the if(...) condition featured in the inner
  57442. ** loop of the following block is more stringent that would be required
  57443. ** if we had exclusive access to the hash-table:
  57444. **
  57445. ** (aPgno[iFrame]==pgno):
  57446. ** This condition filters out normal hash-table collisions.
  57447. **
  57448. ** (iFrame<=iLast):
  57449. ** This condition filters out entries that were added to the hash
  57450. ** table after the current read-transaction had started.
  57451. */
  57452. iMinHash = walFramePage(pWal->minFrame);
  57453. for(iHash=walFramePage(iLast); iHash>=iMinHash; iHash--){
  57454. WalHashLoc sLoc; /* Hash table location */
  57455. int iKey; /* Hash slot index */
  57456. int nCollide; /* Number of hash collisions remaining */
  57457. int rc; /* Error code */
  57458. rc = walHashGet(pWal, iHash, &sLoc);
  57459. if( rc!=SQLITE_OK ){
  57460. return rc;
  57461. }
  57462. nCollide = HASHTABLE_NSLOT;
  57463. for(iKey=walHash(pgno); sLoc.aHash[iKey]; iKey=walNextHash(iKey)){
  57464. u32 iH = sLoc.aHash[iKey];
  57465. u32 iFrame = iH + sLoc.iZero;
  57466. if( iFrame<=iLast && iFrame>=pWal->minFrame && sLoc.aPgno[iH]==pgno ){
  57467. assert( iFrame>iRead || CORRUPT_DB );
  57468. iRead = iFrame;
  57469. }
  57470. if( (nCollide--)==0 ){
  57471. return SQLITE_CORRUPT_BKPT;
  57472. }
  57473. }
  57474. if( iRead ) break;
  57475. }
  57476. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  57477. /* If expensive assert() statements are available, do a linear search
  57478. ** of the wal-index file content. Make sure the results agree with the
  57479. ** result obtained using the hash indexes above. */
  57480. {
  57481. u32 iRead2 = 0;
  57482. u32 iTest;
  57483. assert( pWal->bShmUnreliable || pWal->minFrame>0 );
  57484. for(iTest=iLast; iTest>=pWal->minFrame && iTest>0; iTest--){
  57485. if( walFramePgno(pWal, iTest)==pgno ){
  57486. iRead2 = iTest;
  57487. break;
  57488. }
  57489. }
  57490. assert( iRead==iRead2 );
  57491. }
  57492. #endif
  57493. *piRead = iRead;
  57494. return SQLITE_OK;
  57495. }
  57496. /*
  57497. ** Read the contents of frame iRead from the wal file into buffer pOut
  57498. ** (which is nOut bytes in size). Return SQLITE_OK if successful, or an
  57499. ** error code otherwise.
  57500. */
  57501. SQLITE_PRIVATE int sqlite3WalReadFrame(
  57502. Wal *pWal, /* WAL handle */
  57503. u32 iRead, /* Frame to read */
  57504. int nOut, /* Size of buffer pOut in bytes */
  57505. u8 *pOut /* Buffer to write page data to */
  57506. ){
  57507. int sz;
  57508. i64 iOffset;
  57509. sz = pWal->hdr.szPage;
  57510. sz = (sz&0xfe00) + ((sz&0x0001)<<16);
  57511. testcase( sz<=32768 );
  57512. testcase( sz>=65536 );
  57513. iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
  57514. /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
  57515. return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
  57516. }
  57517. /*
  57518. ** Return the size of the database in pages (or zero, if unknown).
  57519. */
  57520. SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
  57521. if( pWal && ALWAYS(pWal->readLock>=0) ){
  57522. return pWal->hdr.nPage;
  57523. }
  57524. return 0;
  57525. }
  57526. /*
  57527. ** This function starts a write transaction on the WAL.
  57528. **
  57529. ** A read transaction must have already been started by a prior call
  57530. ** to sqlite3WalBeginReadTransaction().
  57531. **
  57532. ** If another thread or process has written into the database since
  57533. ** the read transaction was started, then it is not possible for this
  57534. ** thread to write as doing so would cause a fork. So this routine
  57535. ** returns SQLITE_BUSY in that case and no write transaction is started.
  57536. **
  57537. ** There can only be a single writer active at a time.
  57538. */
  57539. SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
  57540. int rc;
  57541. /* Cannot start a write transaction without first holding a read
  57542. ** transaction. */
  57543. assert( pWal->readLock>=0 );
  57544. assert( pWal->writeLock==0 && pWal->iReCksum==0 );
  57545. if( pWal->readOnly ){
  57546. return SQLITE_READONLY;
  57547. }
  57548. /* Only one writer allowed at a time. Get the write lock. Return
  57549. ** SQLITE_BUSY if unable.
  57550. */
  57551. rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
  57552. if( rc ){
  57553. return rc;
  57554. }
  57555. pWal->writeLock = 1;
  57556. /* If another connection has written to the database file since the
  57557. ** time the read transaction on this connection was started, then
  57558. ** the write is disallowed.
  57559. */
  57560. if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
  57561. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  57562. pWal->writeLock = 0;
  57563. rc = SQLITE_BUSY_SNAPSHOT;
  57564. }
  57565. return rc;
  57566. }
  57567. /*
  57568. ** End a write transaction. The commit has already been done. This
  57569. ** routine merely releases the lock.
  57570. */
  57571. SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
  57572. if( pWal->writeLock ){
  57573. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  57574. pWal->writeLock = 0;
  57575. pWal->iReCksum = 0;
  57576. pWal->truncateOnCommit = 0;
  57577. }
  57578. return SQLITE_OK;
  57579. }
  57580. /*
  57581. ** If any data has been written (but not committed) to the log file, this
  57582. ** function moves the write-pointer back to the start of the transaction.
  57583. **
  57584. ** Additionally, the callback function is invoked for each frame written
  57585. ** to the WAL since the start of the transaction. If the callback returns
  57586. ** other than SQLITE_OK, it is not invoked again and the error code is
  57587. ** returned to the caller.
  57588. **
  57589. ** Otherwise, if the callback function does not return an error, this
  57590. ** function returns SQLITE_OK.
  57591. */
  57592. SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
  57593. int rc = SQLITE_OK;
  57594. if( ALWAYS(pWal->writeLock) ){
  57595. Pgno iMax = pWal->hdr.mxFrame;
  57596. Pgno iFrame;
  57597. /* Restore the clients cache of the wal-index header to the state it
  57598. ** was in before the client began writing to the database.
  57599. */
  57600. memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
  57601. for(iFrame=pWal->hdr.mxFrame+1;
  57602. ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
  57603. iFrame++
  57604. ){
  57605. /* This call cannot fail. Unless the page for which the page number
  57606. ** is passed as the second argument is (a) in the cache and
  57607. ** (b) has an outstanding reference, then xUndo is either a no-op
  57608. ** (if (a) is false) or simply expels the page from the cache (if (b)
  57609. ** is false).
  57610. **
  57611. ** If the upper layer is doing a rollback, it is guaranteed that there
  57612. ** are no outstanding references to any page other than page 1. And
  57613. ** page 1 is never written to the log until the transaction is
  57614. ** committed. As a result, the call to xUndo may not fail.
  57615. */
  57616. assert( walFramePgno(pWal, iFrame)!=1 );
  57617. rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
  57618. }
  57619. if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
  57620. }
  57621. return rc;
  57622. }
  57623. /*
  57624. ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
  57625. ** values. This function populates the array with values required to
  57626. ** "rollback" the write position of the WAL handle back to the current
  57627. ** point in the event of a savepoint rollback (via WalSavepointUndo()).
  57628. */
  57629. SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
  57630. assert( pWal->writeLock );
  57631. aWalData[0] = pWal->hdr.mxFrame;
  57632. aWalData[1] = pWal->hdr.aFrameCksum[0];
  57633. aWalData[2] = pWal->hdr.aFrameCksum[1];
  57634. aWalData[3] = pWal->nCkpt;
  57635. }
  57636. /*
  57637. ** Move the write position of the WAL back to the point identified by
  57638. ** the values in the aWalData[] array. aWalData must point to an array
  57639. ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
  57640. ** by a call to WalSavepoint().
  57641. */
  57642. SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
  57643. int rc = SQLITE_OK;
  57644. assert( pWal->writeLock );
  57645. assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
  57646. if( aWalData[3]!=pWal->nCkpt ){
  57647. /* This savepoint was opened immediately after the write-transaction
  57648. ** was started. Right after that, the writer decided to wrap around
  57649. ** to the start of the log. Update the savepoint values to match.
  57650. */
  57651. aWalData[0] = 0;
  57652. aWalData[3] = pWal->nCkpt;
  57653. }
  57654. if( aWalData[0]<pWal->hdr.mxFrame ){
  57655. pWal->hdr.mxFrame = aWalData[0];
  57656. pWal->hdr.aFrameCksum[0] = aWalData[1];
  57657. pWal->hdr.aFrameCksum[1] = aWalData[2];
  57658. walCleanupHash(pWal);
  57659. }
  57660. return rc;
  57661. }
  57662. /*
  57663. ** This function is called just before writing a set of frames to the log
  57664. ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
  57665. ** to the current log file, it is possible to overwrite the start of the
  57666. ** existing log file with the new frames (i.e. "reset" the log). If so,
  57667. ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
  57668. ** unchanged.
  57669. **
  57670. ** SQLITE_OK is returned if no error is encountered (regardless of whether
  57671. ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
  57672. ** if an error occurs.
  57673. */
  57674. static int walRestartLog(Wal *pWal){
  57675. int rc = SQLITE_OK;
  57676. int cnt;
  57677. if( pWal->readLock==0 ){
  57678. volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
  57679. assert( pInfo->nBackfill==pWal->hdr.mxFrame );
  57680. if( pInfo->nBackfill>0 ){
  57681. u32 salt1;
  57682. sqlite3_randomness(4, &salt1);
  57683. rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  57684. if( rc==SQLITE_OK ){
  57685. /* If all readers are using WAL_READ_LOCK(0) (in other words if no
  57686. ** readers are currently using the WAL), then the transactions
  57687. ** frames will overwrite the start of the existing log. Update the
  57688. ** wal-index header to reflect this.
  57689. **
  57690. ** In theory it would be Ok to update the cache of the header only
  57691. ** at this point. But updating the actual wal-index header is also
  57692. ** safe and means there is no special case for sqlite3WalUndo()
  57693. ** to handle if this transaction is rolled back. */
  57694. walRestartHdr(pWal, salt1);
  57695. walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  57696. }else if( rc!=SQLITE_BUSY ){
  57697. return rc;
  57698. }
  57699. }
  57700. walUnlockShared(pWal, WAL_READ_LOCK(0));
  57701. pWal->readLock = -1;
  57702. cnt = 0;
  57703. do{
  57704. int notUsed;
  57705. rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
  57706. }while( rc==WAL_RETRY );
  57707. assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
  57708. testcase( (rc&0xff)==SQLITE_IOERR );
  57709. testcase( rc==SQLITE_PROTOCOL );
  57710. testcase( rc==SQLITE_OK );
  57711. }
  57712. return rc;
  57713. }
  57714. /*
  57715. ** Information about the current state of the WAL file and where
  57716. ** the next fsync should occur - passed from sqlite3WalFrames() into
  57717. ** walWriteToLog().
  57718. */
  57719. typedef struct WalWriter {
  57720. Wal *pWal; /* The complete WAL information */
  57721. sqlite3_file *pFd; /* The WAL file to which we write */
  57722. sqlite3_int64 iSyncPoint; /* Fsync at this offset */
  57723. int syncFlags; /* Flags for the fsync */
  57724. int szPage; /* Size of one page */
  57725. } WalWriter;
  57726. /*
  57727. ** Write iAmt bytes of content into the WAL file beginning at iOffset.
  57728. ** Do a sync when crossing the p->iSyncPoint boundary.
  57729. **
  57730. ** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
  57731. ** first write the part before iSyncPoint, then sync, then write the
  57732. ** rest.
  57733. */
  57734. static int walWriteToLog(
  57735. WalWriter *p, /* WAL to write to */
  57736. void *pContent, /* Content to be written */
  57737. int iAmt, /* Number of bytes to write */
  57738. sqlite3_int64 iOffset /* Start writing at this offset */
  57739. ){
  57740. int rc;
  57741. if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
  57742. int iFirstAmt = (int)(p->iSyncPoint - iOffset);
  57743. rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
  57744. if( rc ) return rc;
  57745. iOffset += iFirstAmt;
  57746. iAmt -= iFirstAmt;
  57747. pContent = (void*)(iFirstAmt + (char*)pContent);
  57748. assert( WAL_SYNC_FLAGS(p->syncFlags)!=0 );
  57749. rc = sqlite3OsSync(p->pFd, WAL_SYNC_FLAGS(p->syncFlags));
  57750. if( iAmt==0 || rc ) return rc;
  57751. }
  57752. rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
  57753. return rc;
  57754. }
  57755. /*
  57756. ** Write out a single frame of the WAL
  57757. */
  57758. static int walWriteOneFrame(
  57759. WalWriter *p, /* Where to write the frame */
  57760. PgHdr *pPage, /* The page of the frame to be written */
  57761. int nTruncate, /* The commit flag. Usually 0. >0 for commit */
  57762. sqlite3_int64 iOffset /* Byte offset at which to write */
  57763. ){
  57764. int rc; /* Result code from subfunctions */
  57765. void *pData; /* Data actually written */
  57766. u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-header in */
  57767. #if defined(SQLITE_HAS_CODEC)
  57768. if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM_BKPT;
  57769. #else
  57770. pData = pPage->pData;
  57771. #endif
  57772. walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
  57773. rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
  57774. if( rc ) return rc;
  57775. /* Write the page data */
  57776. rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
  57777. return rc;
  57778. }
  57779. /*
  57780. ** This function is called as part of committing a transaction within which
  57781. ** one or more frames have been overwritten. It updates the checksums for
  57782. ** all frames written to the wal file by the current transaction starting
  57783. ** with the earliest to have been overwritten.
  57784. **
  57785. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  57786. */
  57787. static int walRewriteChecksums(Wal *pWal, u32 iLast){
  57788. const int szPage = pWal->szPage;/* Database page size */
  57789. int rc = SQLITE_OK; /* Return code */
  57790. u8 *aBuf; /* Buffer to load data from wal file into */
  57791. u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-headers in */
  57792. u32 iRead; /* Next frame to read from wal file */
  57793. i64 iCksumOff;
  57794. aBuf = sqlite3_malloc(szPage + WAL_FRAME_HDRSIZE);
  57795. if( aBuf==0 ) return SQLITE_NOMEM_BKPT;
  57796. /* Find the checksum values to use as input for the recalculating the
  57797. ** first checksum. If the first frame is frame 1 (implying that the current
  57798. ** transaction restarted the wal file), these values must be read from the
  57799. ** wal-file header. Otherwise, read them from the frame header of the
  57800. ** previous frame. */
  57801. assert( pWal->iReCksum>0 );
  57802. if( pWal->iReCksum==1 ){
  57803. iCksumOff = 24;
  57804. }else{
  57805. iCksumOff = walFrameOffset(pWal->iReCksum-1, szPage) + 16;
  57806. }
  57807. rc = sqlite3OsRead(pWal->pWalFd, aBuf, sizeof(u32)*2, iCksumOff);
  57808. pWal->hdr.aFrameCksum[0] = sqlite3Get4byte(aBuf);
  57809. pWal->hdr.aFrameCksum[1] = sqlite3Get4byte(&aBuf[sizeof(u32)]);
  57810. iRead = pWal->iReCksum;
  57811. pWal->iReCksum = 0;
  57812. for(; rc==SQLITE_OK && iRead<=iLast; iRead++){
  57813. i64 iOff = walFrameOffset(iRead, szPage);
  57814. rc = sqlite3OsRead(pWal->pWalFd, aBuf, szPage+WAL_FRAME_HDRSIZE, iOff);
  57815. if( rc==SQLITE_OK ){
  57816. u32 iPgno, nDbSize;
  57817. iPgno = sqlite3Get4byte(aBuf);
  57818. nDbSize = sqlite3Get4byte(&aBuf[4]);
  57819. walEncodeFrame(pWal, iPgno, nDbSize, &aBuf[WAL_FRAME_HDRSIZE], aFrame);
  57820. rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOff);
  57821. }
  57822. }
  57823. sqlite3_free(aBuf);
  57824. return rc;
  57825. }
  57826. /*
  57827. ** Write a set of frames to the log. The caller must hold the write-lock
  57828. ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
  57829. */
  57830. SQLITE_PRIVATE int sqlite3WalFrames(
  57831. Wal *pWal, /* Wal handle to write to */
  57832. int szPage, /* Database page-size in bytes */
  57833. PgHdr *pList, /* List of dirty pages to write */
  57834. Pgno nTruncate, /* Database size after this commit */
  57835. int isCommit, /* True if this is a commit */
  57836. int sync_flags /* Flags to pass to OsSync() (or 0) */
  57837. ){
  57838. int rc; /* Used to catch return codes */
  57839. u32 iFrame; /* Next frame address */
  57840. PgHdr *p; /* Iterator to run through pList with. */
  57841. PgHdr *pLast = 0; /* Last frame in list */
  57842. int nExtra = 0; /* Number of extra copies of last page */
  57843. int szFrame; /* The size of a single frame */
  57844. i64 iOffset; /* Next byte to write in WAL file */
  57845. WalWriter w; /* The writer */
  57846. u32 iFirst = 0; /* First frame that may be overwritten */
  57847. WalIndexHdr *pLive; /* Pointer to shared header */
  57848. assert( pList );
  57849. assert( pWal->writeLock );
  57850. /* If this frame set completes a transaction, then nTruncate>0. If
  57851. ** nTruncate==0 then this frame set does not complete the transaction. */
  57852. assert( (isCommit!=0)==(nTruncate!=0) );
  57853. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  57854. { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
  57855. WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
  57856. pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
  57857. }
  57858. #endif
  57859. pLive = (WalIndexHdr*)walIndexHdr(pWal);
  57860. if( memcmp(&pWal->hdr, (void *)pLive, sizeof(WalIndexHdr))!=0 ){
  57861. iFirst = pLive->mxFrame+1;
  57862. }
  57863. /* See if it is possible to write these frames into the start of the
  57864. ** log file, instead of appending to it at pWal->hdr.mxFrame.
  57865. */
  57866. if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
  57867. return rc;
  57868. }
  57869. /* If this is the first frame written into the log, write the WAL
  57870. ** header to the start of the WAL file. See comments at the top of
  57871. ** this source file for a description of the WAL header format.
  57872. */
  57873. iFrame = pWal->hdr.mxFrame;
  57874. if( iFrame==0 ){
  57875. u8 aWalHdr[WAL_HDRSIZE]; /* Buffer to assemble wal-header in */
  57876. u32 aCksum[2]; /* Checksum for wal-header */
  57877. sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
  57878. sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
  57879. sqlite3Put4byte(&aWalHdr[8], szPage);
  57880. sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
  57881. if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
  57882. memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
  57883. walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
  57884. sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
  57885. sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
  57886. pWal->szPage = szPage;
  57887. pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
  57888. pWal->hdr.aFrameCksum[0] = aCksum[0];
  57889. pWal->hdr.aFrameCksum[1] = aCksum[1];
  57890. pWal->truncateOnCommit = 1;
  57891. rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
  57892. WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
  57893. if( rc!=SQLITE_OK ){
  57894. return rc;
  57895. }
  57896. /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
  57897. ** all syncing is turned off by PRAGMA synchronous=OFF). Otherwise
  57898. ** an out-of-order write following a WAL restart could result in
  57899. ** database corruption. See the ticket:
  57900. **
  57901. ** https://sqlite.org/src/info/ff5be73dee
  57902. */
  57903. if( pWal->syncHeader ){
  57904. rc = sqlite3OsSync(pWal->pWalFd, CKPT_SYNC_FLAGS(sync_flags));
  57905. if( rc ) return rc;
  57906. }
  57907. }
  57908. assert( (int)pWal->szPage==szPage );
  57909. /* Setup information needed to write frames into the WAL */
  57910. w.pWal = pWal;
  57911. w.pFd = pWal->pWalFd;
  57912. w.iSyncPoint = 0;
  57913. w.syncFlags = sync_flags;
  57914. w.szPage = szPage;
  57915. iOffset = walFrameOffset(iFrame+1, szPage);
  57916. szFrame = szPage + WAL_FRAME_HDRSIZE;
  57917. /* Write all frames into the log file exactly once */
  57918. for(p=pList; p; p=p->pDirty){
  57919. int nDbSize; /* 0 normally. Positive == commit flag */
  57920. /* Check if this page has already been written into the wal file by
  57921. ** the current transaction. If so, overwrite the existing frame and
  57922. ** set Wal.writeLock to WAL_WRITELOCK_RECKSUM - indicating that
  57923. ** checksums must be recomputed when the transaction is committed. */
  57924. if( iFirst && (p->pDirty || isCommit==0) ){
  57925. u32 iWrite = 0;
  57926. VVA_ONLY(rc =) sqlite3WalFindFrame(pWal, p->pgno, &iWrite);
  57927. assert( rc==SQLITE_OK || iWrite==0 );
  57928. if( iWrite>=iFirst ){
  57929. i64 iOff = walFrameOffset(iWrite, szPage) + WAL_FRAME_HDRSIZE;
  57930. void *pData;
  57931. if( pWal->iReCksum==0 || iWrite<pWal->iReCksum ){
  57932. pWal->iReCksum = iWrite;
  57933. }
  57934. #if defined(SQLITE_HAS_CODEC)
  57935. if( (pData = sqlite3PagerCodec(p))==0 ) return SQLITE_NOMEM;
  57936. #else
  57937. pData = p->pData;
  57938. #endif
  57939. rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOff);
  57940. if( rc ) return rc;
  57941. p->flags &= ~PGHDR_WAL_APPEND;
  57942. continue;
  57943. }
  57944. }
  57945. iFrame++;
  57946. assert( iOffset==walFrameOffset(iFrame, szPage) );
  57947. nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
  57948. rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
  57949. if( rc ) return rc;
  57950. pLast = p;
  57951. iOffset += szFrame;
  57952. p->flags |= PGHDR_WAL_APPEND;
  57953. }
  57954. /* Recalculate checksums within the wal file if required. */
  57955. if( isCommit && pWal->iReCksum ){
  57956. rc = walRewriteChecksums(pWal, iFrame);
  57957. if( rc ) return rc;
  57958. }
  57959. /* If this is the end of a transaction, then we might need to pad
  57960. ** the transaction and/or sync the WAL file.
  57961. **
  57962. ** Padding and syncing only occur if this set of frames complete a
  57963. ** transaction and if PRAGMA synchronous=FULL. If synchronous==NORMAL
  57964. ** or synchronous==OFF, then no padding or syncing are needed.
  57965. **
  57966. ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
  57967. ** needed and only the sync is done. If padding is needed, then the
  57968. ** final frame is repeated (with its commit mark) until the next sector
  57969. ** boundary is crossed. Only the part of the WAL prior to the last
  57970. ** sector boundary is synced; the part of the last frame that extends
  57971. ** past the sector boundary is written after the sync.
  57972. */
  57973. if( isCommit && WAL_SYNC_FLAGS(sync_flags)!=0 ){
  57974. int bSync = 1;
  57975. if( pWal->padToSectorBoundary ){
  57976. int sectorSize = sqlite3SectorSize(pWal->pWalFd);
  57977. w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
  57978. bSync = (w.iSyncPoint==iOffset);
  57979. testcase( bSync );
  57980. while( iOffset<w.iSyncPoint ){
  57981. rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
  57982. if( rc ) return rc;
  57983. iOffset += szFrame;
  57984. nExtra++;
  57985. }
  57986. }
  57987. if( bSync ){
  57988. assert( rc==SQLITE_OK );
  57989. rc = sqlite3OsSync(w.pFd, WAL_SYNC_FLAGS(sync_flags));
  57990. }
  57991. }
  57992. /* If this frame set completes the first transaction in the WAL and
  57993. ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
  57994. ** journal size limit, if possible.
  57995. */
  57996. if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
  57997. i64 sz = pWal->mxWalSize;
  57998. if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
  57999. sz = walFrameOffset(iFrame+nExtra+1, szPage);
  58000. }
  58001. walLimitSize(pWal, sz);
  58002. pWal->truncateOnCommit = 0;
  58003. }
  58004. /* Append data to the wal-index. It is not necessary to lock the
  58005. ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
  58006. ** guarantees that there are no other writers, and no data that may
  58007. ** be in use by existing readers is being overwritten.
  58008. */
  58009. iFrame = pWal->hdr.mxFrame;
  58010. for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
  58011. if( (p->flags & PGHDR_WAL_APPEND)==0 ) continue;
  58012. iFrame++;
  58013. rc = walIndexAppend(pWal, iFrame, p->pgno);
  58014. }
  58015. while( rc==SQLITE_OK && nExtra>0 ){
  58016. iFrame++;
  58017. nExtra--;
  58018. rc = walIndexAppend(pWal, iFrame, pLast->pgno);
  58019. }
  58020. if( rc==SQLITE_OK ){
  58021. /* Update the private copy of the header. */
  58022. pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
  58023. testcase( szPage<=32768 );
  58024. testcase( szPage>=65536 );
  58025. pWal->hdr.mxFrame = iFrame;
  58026. if( isCommit ){
  58027. pWal->hdr.iChange++;
  58028. pWal->hdr.nPage = nTruncate;
  58029. }
  58030. /* If this is a commit, update the wal-index header too. */
  58031. if( isCommit ){
  58032. walIndexWriteHdr(pWal);
  58033. pWal->iCallback = iFrame;
  58034. }
  58035. }
  58036. WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
  58037. return rc;
  58038. }
  58039. /*
  58040. ** This routine is called to implement sqlite3_wal_checkpoint() and
  58041. ** related interfaces.
  58042. **
  58043. ** Obtain a CHECKPOINT lock and then backfill as much information as
  58044. ** we can from WAL into the database.
  58045. **
  58046. ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
  58047. ** callback. In this case this function runs a blocking checkpoint.
  58048. */
  58049. SQLITE_PRIVATE int sqlite3WalCheckpoint(
  58050. Wal *pWal, /* Wal connection */
  58051. sqlite3 *db, /* Check this handle's interrupt flag */
  58052. int eMode, /* PASSIVE, FULL, RESTART, or TRUNCATE */
  58053. int (*xBusy)(void*), /* Function to call when busy */
  58054. void *pBusyArg, /* Context argument for xBusyHandler */
  58055. int sync_flags, /* Flags to sync db file with (or 0) */
  58056. int nBuf, /* Size of temporary buffer */
  58057. u8 *zBuf, /* Temporary buffer to use */
  58058. int *pnLog, /* OUT: Number of frames in WAL */
  58059. int *pnCkpt /* OUT: Number of backfilled frames in WAL */
  58060. ){
  58061. int rc; /* Return code */
  58062. int isChanged = 0; /* True if a new wal-index header is loaded */
  58063. int eMode2 = eMode; /* Mode to pass to walCheckpoint() */
  58064. int (*xBusy2)(void*) = xBusy; /* Busy handler for eMode2 */
  58065. assert( pWal->ckptLock==0 );
  58066. assert( pWal->writeLock==0 );
  58067. /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
  58068. ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
  58069. assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
  58070. if( pWal->readOnly ) return SQLITE_READONLY;
  58071. WALTRACE(("WAL%p: checkpoint begins\n", pWal));
  58072. /* IMPLEMENTATION-OF: R-62028-47212 All calls obtain an exclusive
  58073. ** "checkpoint" lock on the database file. */
  58074. rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
  58075. if( rc ){
  58076. /* EVIDENCE-OF: R-10421-19736 If any other process is running a
  58077. ** checkpoint operation at the same time, the lock cannot be obtained and
  58078. ** SQLITE_BUSY is returned.
  58079. ** EVIDENCE-OF: R-53820-33897 Even if there is a busy-handler configured,
  58080. ** it will not be invoked in this case.
  58081. */
  58082. testcase( rc==SQLITE_BUSY );
  58083. testcase( xBusy!=0 );
  58084. return rc;
  58085. }
  58086. pWal->ckptLock = 1;
  58087. /* IMPLEMENTATION-OF: R-59782-36818 The SQLITE_CHECKPOINT_FULL, RESTART and
  58088. ** TRUNCATE modes also obtain the exclusive "writer" lock on the database
  58089. ** file.
  58090. **
  58091. ** EVIDENCE-OF: R-60642-04082 If the writer lock cannot be obtained
  58092. ** immediately, and a busy-handler is configured, it is invoked and the
  58093. ** writer lock retried until either the busy-handler returns 0 or the
  58094. ** lock is successfully obtained.
  58095. */
  58096. if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
  58097. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
  58098. if( rc==SQLITE_OK ){
  58099. pWal->writeLock = 1;
  58100. }else if( rc==SQLITE_BUSY ){
  58101. eMode2 = SQLITE_CHECKPOINT_PASSIVE;
  58102. xBusy2 = 0;
  58103. rc = SQLITE_OK;
  58104. }
  58105. }
  58106. /* Read the wal-index header. */
  58107. if( rc==SQLITE_OK ){
  58108. rc = walIndexReadHdr(pWal, &isChanged);
  58109. if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){
  58110. sqlite3OsUnfetch(pWal->pDbFd, 0, 0);
  58111. }
  58112. }
  58113. /* Copy data from the log to the database file. */
  58114. if( rc==SQLITE_OK ){
  58115. if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
  58116. rc = SQLITE_CORRUPT_BKPT;
  58117. }else{
  58118. rc = walCheckpoint(pWal, db, eMode2, xBusy2, pBusyArg, sync_flags, zBuf);
  58119. }
  58120. /* If no error occurred, set the output variables. */
  58121. if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
  58122. if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
  58123. if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
  58124. }
  58125. }
  58126. if( isChanged ){
  58127. /* If a new wal-index header was loaded before the checkpoint was
  58128. ** performed, then the pager-cache associated with pWal is now
  58129. ** out of date. So zero the cached wal-index header to ensure that
  58130. ** next time the pager opens a snapshot on this database it knows that
  58131. ** the cache needs to be reset.
  58132. */
  58133. memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
  58134. }
  58135. /* Release the locks. */
  58136. sqlite3WalEndWriteTransaction(pWal);
  58137. walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
  58138. pWal->ckptLock = 0;
  58139. WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
  58140. return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
  58141. }
  58142. /* Return the value to pass to a sqlite3_wal_hook callback, the
  58143. ** number of frames in the WAL at the point of the last commit since
  58144. ** sqlite3WalCallback() was called. If no commits have occurred since
  58145. ** the last call, then return 0.
  58146. */
  58147. SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
  58148. u32 ret = 0;
  58149. if( pWal ){
  58150. ret = pWal->iCallback;
  58151. pWal->iCallback = 0;
  58152. }
  58153. return (int)ret;
  58154. }
  58155. /*
  58156. ** This function is called to change the WAL subsystem into or out
  58157. ** of locking_mode=EXCLUSIVE.
  58158. **
  58159. ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
  58160. ** into locking_mode=NORMAL. This means that we must acquire a lock
  58161. ** on the pWal->readLock byte. If the WAL is already in locking_mode=NORMAL
  58162. ** or if the acquisition of the lock fails, then return 0. If the
  58163. ** transition out of exclusive-mode is successful, return 1. This
  58164. ** operation must occur while the pager is still holding the exclusive
  58165. ** lock on the main database file.
  58166. **
  58167. ** If op is one, then change from locking_mode=NORMAL into
  58168. ** locking_mode=EXCLUSIVE. This means that the pWal->readLock must
  58169. ** be released. Return 1 if the transition is made and 0 if the
  58170. ** WAL is already in exclusive-locking mode - meaning that this
  58171. ** routine is a no-op. The pager must already hold the exclusive lock
  58172. ** on the main database file before invoking this operation.
  58173. **
  58174. ** If op is negative, then do a dry-run of the op==1 case but do
  58175. ** not actually change anything. The pager uses this to see if it
  58176. ** should acquire the database exclusive lock prior to invoking
  58177. ** the op==1 case.
  58178. */
  58179. SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
  58180. int rc;
  58181. assert( pWal->writeLock==0 );
  58182. assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
  58183. /* pWal->readLock is usually set, but might be -1 if there was a
  58184. ** prior error while attempting to acquire are read-lock. This cannot
  58185. ** happen if the connection is actually in exclusive mode (as no xShmLock
  58186. ** locks are taken in this case). Nor should the pager attempt to
  58187. ** upgrade to exclusive-mode following such an error.
  58188. */
  58189. assert( pWal->readLock>=0 || pWal->lockError );
  58190. assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
  58191. if( op==0 ){
  58192. if( pWal->exclusiveMode!=WAL_NORMAL_MODE ){
  58193. pWal->exclusiveMode = WAL_NORMAL_MODE;
  58194. if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
  58195. pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
  58196. }
  58197. rc = pWal->exclusiveMode==WAL_NORMAL_MODE;
  58198. }else{
  58199. /* Already in locking_mode=NORMAL */
  58200. rc = 0;
  58201. }
  58202. }else if( op>0 ){
  58203. assert( pWal->exclusiveMode==WAL_NORMAL_MODE );
  58204. assert( pWal->readLock>=0 );
  58205. walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
  58206. pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
  58207. rc = 1;
  58208. }else{
  58209. rc = pWal->exclusiveMode==WAL_NORMAL_MODE;
  58210. }
  58211. return rc;
  58212. }
  58213. /*
  58214. ** Return true if the argument is non-NULL and the WAL module is using
  58215. ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
  58216. ** WAL module is using shared-memory, return false.
  58217. */
  58218. SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
  58219. return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
  58220. }
  58221. #ifdef SQLITE_ENABLE_SNAPSHOT
  58222. /* Create a snapshot object. The content of a snapshot is opaque to
  58223. ** every other subsystem, so the WAL module can put whatever it needs
  58224. ** in the object.
  58225. */
  58226. SQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot){
  58227. int rc = SQLITE_OK;
  58228. WalIndexHdr *pRet;
  58229. static const u32 aZero[4] = { 0, 0, 0, 0 };
  58230. assert( pWal->readLock>=0 && pWal->writeLock==0 );
  58231. if( memcmp(&pWal->hdr.aFrameCksum[0],aZero,16)==0 ){
  58232. *ppSnapshot = 0;
  58233. return SQLITE_ERROR;
  58234. }
  58235. pRet = (WalIndexHdr*)sqlite3_malloc(sizeof(WalIndexHdr));
  58236. if( pRet==0 ){
  58237. rc = SQLITE_NOMEM_BKPT;
  58238. }else{
  58239. memcpy(pRet, &pWal->hdr, sizeof(WalIndexHdr));
  58240. *ppSnapshot = (sqlite3_snapshot*)pRet;
  58241. }
  58242. return rc;
  58243. }
  58244. /* Try to open on pSnapshot when the next read-transaction starts
  58245. */
  58246. SQLITE_PRIVATE void sqlite3WalSnapshotOpen(Wal *pWal, sqlite3_snapshot *pSnapshot){
  58247. pWal->pSnapshot = (WalIndexHdr*)pSnapshot;
  58248. }
  58249. /*
  58250. ** Return a +ve value if snapshot p1 is newer than p2. A -ve value if
  58251. ** p1 is older than p2 and zero if p1 and p2 are the same snapshot.
  58252. */
  58253. SQLITE_API int sqlite3_snapshot_cmp(sqlite3_snapshot *p1, sqlite3_snapshot *p2){
  58254. WalIndexHdr *pHdr1 = (WalIndexHdr*)p1;
  58255. WalIndexHdr *pHdr2 = (WalIndexHdr*)p2;
  58256. /* aSalt[0] is a copy of the value stored in the wal file header. It
  58257. ** is incremented each time the wal file is restarted. */
  58258. if( pHdr1->aSalt[0]<pHdr2->aSalt[0] ) return -1;
  58259. if( pHdr1->aSalt[0]>pHdr2->aSalt[0] ) return +1;
  58260. if( pHdr1->mxFrame<pHdr2->mxFrame ) return -1;
  58261. if( pHdr1->mxFrame>pHdr2->mxFrame ) return +1;
  58262. return 0;
  58263. }
  58264. /*
  58265. ** The caller currently has a read transaction open on the database.
  58266. ** This function takes a SHARED lock on the CHECKPOINTER slot and then
  58267. ** checks if the snapshot passed as the second argument is still
  58268. ** available. If so, SQLITE_OK is returned.
  58269. **
  58270. ** If the snapshot is not available, SQLITE_ERROR is returned. Or, if
  58271. ** the CHECKPOINTER lock cannot be obtained, SQLITE_BUSY. If any error
  58272. ** occurs (any value other than SQLITE_OK is returned), the CHECKPOINTER
  58273. ** lock is released before returning.
  58274. */
  58275. SQLITE_PRIVATE int sqlite3WalSnapshotCheck(Wal *pWal, sqlite3_snapshot *pSnapshot){
  58276. int rc;
  58277. rc = walLockShared(pWal, WAL_CKPT_LOCK);
  58278. if( rc==SQLITE_OK ){
  58279. WalIndexHdr *pNew = (WalIndexHdr*)pSnapshot;
  58280. if( memcmp(pNew->aSalt, pWal->hdr.aSalt, sizeof(pWal->hdr.aSalt))
  58281. || pNew->mxFrame<walCkptInfo(pWal)->nBackfillAttempted
  58282. ){
  58283. rc = SQLITE_ERROR_SNAPSHOT;
  58284. walUnlockShared(pWal, WAL_CKPT_LOCK);
  58285. }
  58286. }
  58287. return rc;
  58288. }
  58289. /*
  58290. ** Release a lock obtained by an earlier successful call to
  58291. ** sqlite3WalSnapshotCheck().
  58292. */
  58293. SQLITE_PRIVATE void sqlite3WalSnapshotUnlock(Wal *pWal){
  58294. assert( pWal );
  58295. walUnlockShared(pWal, WAL_CKPT_LOCK);
  58296. }
  58297. #endif /* SQLITE_ENABLE_SNAPSHOT */
  58298. #ifdef SQLITE_ENABLE_ZIPVFS
  58299. /*
  58300. ** If the argument is not NULL, it points to a Wal object that holds a
  58301. ** read-lock. This function returns the database page-size if it is known,
  58302. ** or zero if it is not (or if pWal is NULL).
  58303. */
  58304. SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){
  58305. assert( pWal==0 || pWal->readLock>=0 );
  58306. return (pWal ? pWal->szPage : 0);
  58307. }
  58308. #endif
  58309. /* Return the sqlite3_file object for the WAL file
  58310. */
  58311. SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal){
  58312. return pWal->pWalFd;
  58313. }
  58314. #endif /* #ifndef SQLITE_OMIT_WAL */
  58315. /************** End of wal.c *************************************************/
  58316. /************** Begin file btmutex.c *****************************************/
  58317. /*
  58318. ** 2007 August 27
  58319. **
  58320. ** The author disclaims copyright to this source code. In place of
  58321. ** a legal notice, here is a blessing:
  58322. **
  58323. ** May you do good and not evil.
  58324. ** May you find forgiveness for yourself and forgive others.
  58325. ** May you share freely, never taking more than you give.
  58326. **
  58327. *************************************************************************
  58328. **
  58329. ** This file contains code used to implement mutexes on Btree objects.
  58330. ** This code really belongs in btree.c. But btree.c is getting too
  58331. ** big and we want to break it down some. This packaged seemed like
  58332. ** a good breakout.
  58333. */
  58334. /************** Include btreeInt.h in the middle of btmutex.c ****************/
  58335. /************** Begin file btreeInt.h ****************************************/
  58336. /*
  58337. ** 2004 April 6
  58338. **
  58339. ** The author disclaims copyright to this source code. In place of
  58340. ** a legal notice, here is a blessing:
  58341. **
  58342. ** May you do good and not evil.
  58343. ** May you find forgiveness for yourself and forgive others.
  58344. ** May you share freely, never taking more than you give.
  58345. **
  58346. *************************************************************************
  58347. ** This file implements an external (disk-based) database using BTrees.
  58348. ** For a detailed discussion of BTrees, refer to
  58349. **
  58350. ** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
  58351. ** "Sorting And Searching", pages 473-480. Addison-Wesley
  58352. ** Publishing Company, Reading, Massachusetts.
  58353. **
  58354. ** The basic idea is that each page of the file contains N database
  58355. ** entries and N+1 pointers to subpages.
  58356. **
  58357. ** ----------------------------------------------------------------
  58358. ** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
  58359. ** ----------------------------------------------------------------
  58360. **
  58361. ** All of the keys on the page that Ptr(0) points to have values less
  58362. ** than Key(0). All of the keys on page Ptr(1) and its subpages have
  58363. ** values greater than Key(0) and less than Key(1). All of the keys
  58364. ** on Ptr(N) and its subpages have values greater than Key(N-1). And
  58365. ** so forth.
  58366. **
  58367. ** Finding a particular key requires reading O(log(M)) pages from the
  58368. ** disk where M is the number of entries in the tree.
  58369. **
  58370. ** In this implementation, a single file can hold one or more separate
  58371. ** BTrees. Each BTree is identified by the index of its root page. The
  58372. ** key and data for any entry are combined to form the "payload". A
  58373. ** fixed amount of payload can be carried directly on the database
  58374. ** page. If the payload is larger than the preset amount then surplus
  58375. ** bytes are stored on overflow pages. The payload for an entry
  58376. ** and the preceding pointer are combined to form a "Cell". Each
  58377. ** page has a small header which contains the Ptr(N) pointer and other
  58378. ** information such as the size of key and data.
  58379. **
  58380. ** FORMAT DETAILS
  58381. **
  58382. ** The file is divided into pages. The first page is called page 1,
  58383. ** the second is page 2, and so forth. A page number of zero indicates
  58384. ** "no such page". The page size can be any power of 2 between 512 and 65536.
  58385. ** Each page can be either a btree page, a freelist page, an overflow
  58386. ** page, or a pointer-map page.
  58387. **
  58388. ** The first page is always a btree page. The first 100 bytes of the first
  58389. ** page contain a special header (the "file header") that describes the file.
  58390. ** The format of the file header is as follows:
  58391. **
  58392. ** OFFSET SIZE DESCRIPTION
  58393. ** 0 16 Header string: "SQLite format 3\000"
  58394. ** 16 2 Page size in bytes. (1 means 65536)
  58395. ** 18 1 File format write version
  58396. ** 19 1 File format read version
  58397. ** 20 1 Bytes of unused space at the end of each page
  58398. ** 21 1 Max embedded payload fraction (must be 64)
  58399. ** 22 1 Min embedded payload fraction (must be 32)
  58400. ** 23 1 Min leaf payload fraction (must be 32)
  58401. ** 24 4 File change counter
  58402. ** 28 4 Reserved for future use
  58403. ** 32 4 First freelist page
  58404. ** 36 4 Number of freelist pages in the file
  58405. ** 40 60 15 4-byte meta values passed to higher layers
  58406. **
  58407. ** 40 4 Schema cookie
  58408. ** 44 4 File format of schema layer
  58409. ** 48 4 Size of page cache
  58410. ** 52 4 Largest root-page (auto/incr_vacuum)
  58411. ** 56 4 1=UTF-8 2=UTF16le 3=UTF16be
  58412. ** 60 4 User version
  58413. ** 64 4 Incremental vacuum mode
  58414. ** 68 4 Application-ID
  58415. ** 72 20 unused
  58416. ** 92 4 The version-valid-for number
  58417. ** 96 4 SQLITE_VERSION_NUMBER
  58418. **
  58419. ** All of the integer values are big-endian (most significant byte first).
  58420. **
  58421. ** The file change counter is incremented when the database is changed
  58422. ** This counter allows other processes to know when the file has changed
  58423. ** and thus when they need to flush their cache.
  58424. **
  58425. ** The max embedded payload fraction is the amount of the total usable
  58426. ** space in a page that can be consumed by a single cell for standard
  58427. ** B-tree (non-LEAFDATA) tables. A value of 255 means 100%. The default
  58428. ** is to limit the maximum cell size so that at least 4 cells will fit
  58429. ** on one page. Thus the default max embedded payload fraction is 64.
  58430. **
  58431. ** If the payload for a cell is larger than the max payload, then extra
  58432. ** payload is spilled to overflow pages. Once an overflow page is allocated,
  58433. ** as many bytes as possible are moved into the overflow pages without letting
  58434. ** the cell size drop below the min embedded payload fraction.
  58435. **
  58436. ** The min leaf payload fraction is like the min embedded payload fraction
  58437. ** except that it applies to leaf nodes in a LEAFDATA tree. The maximum
  58438. ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
  58439. ** not specified in the header.
  58440. **
  58441. ** Each btree pages is divided into three sections: The header, the
  58442. ** cell pointer array, and the cell content area. Page 1 also has a 100-byte
  58443. ** file header that occurs before the page header.
  58444. **
  58445. ** |----------------|
  58446. ** | file header | 100 bytes. Page 1 only.
  58447. ** |----------------|
  58448. ** | page header | 8 bytes for leaves. 12 bytes for interior nodes
  58449. ** |----------------|
  58450. ** | cell pointer | | 2 bytes per cell. Sorted order.
  58451. ** | array | | Grows downward
  58452. ** | | v
  58453. ** |----------------|
  58454. ** | unallocated |
  58455. ** | space |
  58456. ** |----------------| ^ Grows upwards
  58457. ** | cell content | | Arbitrary order interspersed with freeblocks.
  58458. ** | area | | and free space fragments.
  58459. ** |----------------|
  58460. **
  58461. ** The page headers looks like this:
  58462. **
  58463. ** OFFSET SIZE DESCRIPTION
  58464. ** 0 1 Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
  58465. ** 1 2 byte offset to the first freeblock
  58466. ** 3 2 number of cells on this page
  58467. ** 5 2 first byte of the cell content area
  58468. ** 7 1 number of fragmented free bytes
  58469. ** 8 4 Right child (the Ptr(N) value). Omitted on leaves.
  58470. **
  58471. ** The flags define the format of this btree page. The leaf flag means that
  58472. ** this page has no children. The zerodata flag means that this page carries
  58473. ** only keys and no data. The intkey flag means that the key is an integer
  58474. ** which is stored in the key size entry of the cell header rather than in
  58475. ** the payload area.
  58476. **
  58477. ** The cell pointer array begins on the first byte after the page header.
  58478. ** The cell pointer array contains zero or more 2-byte numbers which are
  58479. ** offsets from the beginning of the page to the cell content in the cell
  58480. ** content area. The cell pointers occur in sorted order. The system strives
  58481. ** to keep free space after the last cell pointer so that new cells can
  58482. ** be easily added without having to defragment the page.
  58483. **
  58484. ** Cell content is stored at the very end of the page and grows toward the
  58485. ** beginning of the page.
  58486. **
  58487. ** Unused space within the cell content area is collected into a linked list of
  58488. ** freeblocks. Each freeblock is at least 4 bytes in size. The byte offset
  58489. ** to the first freeblock is given in the header. Freeblocks occur in
  58490. ** increasing order. Because a freeblock must be at least 4 bytes in size,
  58491. ** any group of 3 or fewer unused bytes in the cell content area cannot
  58492. ** exist on the freeblock chain. A group of 3 or fewer free bytes is called
  58493. ** a fragment. The total number of bytes in all fragments is recorded.
  58494. ** in the page header at offset 7.
  58495. **
  58496. ** SIZE DESCRIPTION
  58497. ** 2 Byte offset of the next freeblock
  58498. ** 2 Bytes in this freeblock
  58499. **
  58500. ** Cells are of variable length. Cells are stored in the cell content area at
  58501. ** the end of the page. Pointers to the cells are in the cell pointer array
  58502. ** that immediately follows the page header. Cells is not necessarily
  58503. ** contiguous or in order, but cell pointers are contiguous and in order.
  58504. **
  58505. ** Cell content makes use of variable length integers. A variable
  58506. ** length integer is 1 to 9 bytes where the lower 7 bits of each
  58507. ** byte are used. The integer consists of all bytes that have bit 8 set and
  58508. ** the first byte with bit 8 clear. The most significant byte of the integer
  58509. ** appears first. A variable-length integer may not be more than 9 bytes long.
  58510. ** As a special case, all 8 bytes of the 9th byte are used as data. This
  58511. ** allows a 64-bit integer to be encoded in 9 bytes.
  58512. **
  58513. ** 0x00 becomes 0x00000000
  58514. ** 0x7f becomes 0x0000007f
  58515. ** 0x81 0x00 becomes 0x00000080
  58516. ** 0x82 0x00 becomes 0x00000100
  58517. ** 0x80 0x7f becomes 0x0000007f
  58518. ** 0x8a 0x91 0xd1 0xac 0x78 becomes 0x12345678
  58519. ** 0x81 0x81 0x81 0x81 0x01 becomes 0x10204081
  58520. **
  58521. ** Variable length integers are used for rowids and to hold the number of
  58522. ** bytes of key and data in a btree cell.
  58523. **
  58524. ** The content of a cell looks like this:
  58525. **
  58526. ** SIZE DESCRIPTION
  58527. ** 4 Page number of the left child. Omitted if leaf flag is set.
  58528. ** var Number of bytes of data. Omitted if the zerodata flag is set.
  58529. ** var Number of bytes of key. Or the key itself if intkey flag is set.
  58530. ** * Payload
  58531. ** 4 First page of the overflow chain. Omitted if no overflow
  58532. **
  58533. ** Overflow pages form a linked list. Each page except the last is completely
  58534. ** filled with data (pagesize - 4 bytes). The last page can have as little
  58535. ** as 1 byte of data.
  58536. **
  58537. ** SIZE DESCRIPTION
  58538. ** 4 Page number of next overflow page
  58539. ** * Data
  58540. **
  58541. ** Freelist pages come in two subtypes: trunk pages and leaf pages. The
  58542. ** file header points to the first in a linked list of trunk page. Each trunk
  58543. ** page points to multiple leaf pages. The content of a leaf page is
  58544. ** unspecified. A trunk page looks like this:
  58545. **
  58546. ** SIZE DESCRIPTION
  58547. ** 4 Page number of next trunk page
  58548. ** 4 Number of leaf pointers on this page
  58549. ** * zero or more pages numbers of leaves
  58550. */
  58551. /* #include "sqliteInt.h" */
  58552. /* The following value is the maximum cell size assuming a maximum page
  58553. ** size give above.
  58554. */
  58555. #define MX_CELL_SIZE(pBt) ((int)(pBt->pageSize-8))
  58556. /* The maximum number of cells on a single page of the database. This
  58557. ** assumes a minimum cell size of 6 bytes (4 bytes for the cell itself
  58558. ** plus 2 bytes for the index to the cell in the page header). Such
  58559. ** small cells will be rare, but they are possible.
  58560. */
  58561. #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
  58562. /* Forward declarations */
  58563. typedef struct MemPage MemPage;
  58564. typedef struct BtLock BtLock;
  58565. typedef struct CellInfo CellInfo;
  58566. /*
  58567. ** This is a magic string that appears at the beginning of every
  58568. ** SQLite database in order to identify the file as a real database.
  58569. **
  58570. ** You can change this value at compile-time by specifying a
  58571. ** -DSQLITE_FILE_HEADER="..." on the compiler command-line. The
  58572. ** header must be exactly 16 bytes including the zero-terminator so
  58573. ** the string itself should be 15 characters long. If you change
  58574. ** the header, then your custom library will not be able to read
  58575. ** databases generated by the standard tools and the standard tools
  58576. ** will not be able to read databases created by your custom library.
  58577. */
  58578. #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
  58579. # define SQLITE_FILE_HEADER "SQLite format 3"
  58580. #endif
  58581. /*
  58582. ** Page type flags. An ORed combination of these flags appear as the
  58583. ** first byte of on-disk image of every BTree page.
  58584. */
  58585. #define PTF_INTKEY 0x01
  58586. #define PTF_ZERODATA 0x02
  58587. #define PTF_LEAFDATA 0x04
  58588. #define PTF_LEAF 0x08
  58589. /*
  58590. ** An instance of this object stores information about each a single database
  58591. ** page that has been loaded into memory. The information in this object
  58592. ** is derived from the raw on-disk page content.
  58593. **
  58594. ** As each database page is loaded into memory, the pager allocats an
  58595. ** instance of this object and zeros the first 8 bytes. (This is the
  58596. ** "extra" information associated with each page of the pager.)
  58597. **
  58598. ** Access to all fields of this structure is controlled by the mutex
  58599. ** stored in MemPage.pBt->mutex.
  58600. */
  58601. struct MemPage {
  58602. u8 isInit; /* True if previously initialized. MUST BE FIRST! */
  58603. u8 bBusy; /* Prevent endless loops on corrupt database files */
  58604. u8 intKey; /* True if table b-trees. False for index b-trees */
  58605. u8 intKeyLeaf; /* True if the leaf of an intKey table */
  58606. Pgno pgno; /* Page number for this page */
  58607. /* Only the first 8 bytes (above) are zeroed by pager.c when a new page
  58608. ** is allocated. All fields that follow must be initialized before use */
  58609. u8 leaf; /* True if a leaf page */
  58610. u8 hdrOffset; /* 100 for page 1. 0 otherwise */
  58611. u8 childPtrSize; /* 0 if leaf==1. 4 if leaf==0 */
  58612. u8 max1bytePayload; /* min(maxLocal,127) */
  58613. u8 nOverflow; /* Number of overflow cell bodies in aCell[] */
  58614. u16 maxLocal; /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
  58615. u16 minLocal; /* Copy of BtShared.minLocal or BtShared.minLeaf */
  58616. u16 cellOffset; /* Index in aData of first cell pointer */
  58617. int nFree; /* Number of free bytes on the page. -1 for unknown */
  58618. u16 nCell; /* Number of cells on this page, local and ovfl */
  58619. u16 maskPage; /* Mask for page offset */
  58620. u16 aiOvfl[4]; /* Insert the i-th overflow cell before the aiOvfl-th
  58621. ** non-overflow cell */
  58622. u8 *apOvfl[4]; /* Pointers to the body of overflow cells */
  58623. BtShared *pBt; /* Pointer to BtShared that this page is part of */
  58624. u8 *aData; /* Pointer to disk image of the page data */
  58625. u8 *aDataEnd; /* One byte past the end of usable data */
  58626. u8 *aCellIdx; /* The cell index area */
  58627. u8 *aDataOfst; /* Same as aData for leaves. aData+4 for interior */
  58628. DbPage *pDbPage; /* Pager page handle */
  58629. u16 (*xCellSize)(MemPage*,u8*); /* cellSizePtr method */
  58630. void (*xParseCell)(MemPage*,u8*,CellInfo*); /* btreeParseCell method */
  58631. };
  58632. /*
  58633. ** A linked list of the following structures is stored at BtShared.pLock.
  58634. ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
  58635. ** is opened on the table with root page BtShared.iTable. Locks are removed
  58636. ** from this list when a transaction is committed or rolled back, or when
  58637. ** a btree handle is closed.
  58638. */
  58639. struct BtLock {
  58640. Btree *pBtree; /* Btree handle holding this lock */
  58641. Pgno iTable; /* Root page of table */
  58642. u8 eLock; /* READ_LOCK or WRITE_LOCK */
  58643. BtLock *pNext; /* Next in BtShared.pLock list */
  58644. };
  58645. /* Candidate values for BtLock.eLock */
  58646. #define READ_LOCK 1
  58647. #define WRITE_LOCK 2
  58648. /* A Btree handle
  58649. **
  58650. ** A database connection contains a pointer to an instance of
  58651. ** this object for every database file that it has open. This structure
  58652. ** is opaque to the database connection. The database connection cannot
  58653. ** see the internals of this structure and only deals with pointers to
  58654. ** this structure.
  58655. **
  58656. ** For some database files, the same underlying database cache might be
  58657. ** shared between multiple connections. In that case, each connection
  58658. ** has it own instance of this object. But each instance of this object
  58659. ** points to the same BtShared object. The database cache and the
  58660. ** schema associated with the database file are all contained within
  58661. ** the BtShared object.
  58662. **
  58663. ** All fields in this structure are accessed under sqlite3.mutex.
  58664. ** The pBt pointer itself may not be changed while there exists cursors
  58665. ** in the referenced BtShared that point back to this Btree since those
  58666. ** cursors have to go through this Btree to find their BtShared and
  58667. ** they often do so without holding sqlite3.mutex.
  58668. */
  58669. struct Btree {
  58670. sqlite3 *db; /* The database connection holding this btree */
  58671. BtShared *pBt; /* Sharable content of this btree */
  58672. u8 inTrans; /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
  58673. u8 sharable; /* True if we can share pBt with another db */
  58674. u8 locked; /* True if db currently has pBt locked */
  58675. u8 hasIncrblobCur; /* True if there are one or more Incrblob cursors */
  58676. int wantToLock; /* Number of nested calls to sqlite3BtreeEnter() */
  58677. int nBackup; /* Number of backup operations reading this btree */
  58678. u32 iDataVersion; /* Combines with pBt->pPager->iDataVersion */
  58679. Btree *pNext; /* List of other sharable Btrees from the same db */
  58680. Btree *pPrev; /* Back pointer of the same list */
  58681. #ifndef SQLITE_OMIT_SHARED_CACHE
  58682. BtLock lock; /* Object used to lock page 1 */
  58683. #endif
  58684. };
  58685. /*
  58686. ** Btree.inTrans may take one of the following values.
  58687. **
  58688. ** If the shared-data extension is enabled, there may be multiple users
  58689. ** of the Btree structure. At most one of these may open a write transaction,
  58690. ** but any number may have active read transactions.
  58691. */
  58692. #define TRANS_NONE 0
  58693. #define TRANS_READ 1
  58694. #define TRANS_WRITE 2
  58695. /*
  58696. ** An instance of this object represents a single database file.
  58697. **
  58698. ** A single database file can be in use at the same time by two
  58699. ** or more database connections. When two or more connections are
  58700. ** sharing the same database file, each connection has it own
  58701. ** private Btree object for the file and each of those Btrees points
  58702. ** to this one BtShared object. BtShared.nRef is the number of
  58703. ** connections currently sharing this database file.
  58704. **
  58705. ** Fields in this structure are accessed under the BtShared.mutex
  58706. ** mutex, except for nRef and pNext which are accessed under the
  58707. ** global SQLITE_MUTEX_STATIC_MASTER mutex. The pPager field
  58708. ** may not be modified once it is initially set as long as nRef>0.
  58709. ** The pSchema field may be set once under BtShared.mutex and
  58710. ** thereafter is unchanged as long as nRef>0.
  58711. **
  58712. ** isPending:
  58713. **
  58714. ** If a BtShared client fails to obtain a write-lock on a database
  58715. ** table (because there exists one or more read-locks on the table),
  58716. ** the shared-cache enters 'pending-lock' state and isPending is
  58717. ** set to true.
  58718. **
  58719. ** The shared-cache leaves the 'pending lock' state when either of
  58720. ** the following occur:
  58721. **
  58722. ** 1) The current writer (BtShared.pWriter) concludes its transaction, OR
  58723. ** 2) The number of locks held by other connections drops to zero.
  58724. **
  58725. ** while in the 'pending-lock' state, no connection may start a new
  58726. ** transaction.
  58727. **
  58728. ** This feature is included to help prevent writer-starvation.
  58729. */
  58730. struct BtShared {
  58731. Pager *pPager; /* The page cache */
  58732. sqlite3 *db; /* Database connection currently using this Btree */
  58733. BtCursor *pCursor; /* A list of all open cursors */
  58734. MemPage *pPage1; /* First page of the database */
  58735. u8 openFlags; /* Flags to sqlite3BtreeOpen() */
  58736. #ifndef SQLITE_OMIT_AUTOVACUUM
  58737. u8 autoVacuum; /* True if auto-vacuum is enabled */
  58738. u8 incrVacuum; /* True if incr-vacuum is enabled */
  58739. u8 bDoTruncate; /* True to truncate db on commit */
  58740. #endif
  58741. u8 inTransaction; /* Transaction state */
  58742. u8 max1bytePayload; /* Maximum first byte of cell for a 1-byte payload */
  58743. #ifdef SQLITE_HAS_CODEC
  58744. u8 optimalReserve; /* Desired amount of reserved space per page */
  58745. #endif
  58746. u16 btsFlags; /* Boolean parameters. See BTS_* macros below */
  58747. u16 maxLocal; /* Maximum local payload in non-LEAFDATA tables */
  58748. u16 minLocal; /* Minimum local payload in non-LEAFDATA tables */
  58749. u16 maxLeaf; /* Maximum local payload in a LEAFDATA table */
  58750. u16 minLeaf; /* Minimum local payload in a LEAFDATA table */
  58751. u32 pageSize; /* Total number of bytes on a page */
  58752. u32 usableSize; /* Number of usable bytes on each page */
  58753. int nTransaction; /* Number of open transactions (read + write) */
  58754. u32 nPage; /* Number of pages in the database */
  58755. void *pSchema; /* Pointer to space allocated by sqlite3BtreeSchema() */
  58756. void (*xFreeSchema)(void*); /* Destructor for BtShared.pSchema */
  58757. sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
  58758. Bitvec *pHasContent; /* Set of pages moved to free-list this transaction */
  58759. #ifndef SQLITE_OMIT_SHARED_CACHE
  58760. int nRef; /* Number of references to this structure */
  58761. BtShared *pNext; /* Next on a list of sharable BtShared structs */
  58762. BtLock *pLock; /* List of locks held on this shared-btree struct */
  58763. Btree *pWriter; /* Btree with currently open write transaction */
  58764. #endif
  58765. u8 *pTmpSpace; /* Temp space sufficient to hold a single cell */
  58766. };
  58767. /*
  58768. ** Allowed values for BtShared.btsFlags
  58769. */
  58770. #define BTS_READ_ONLY 0x0001 /* Underlying file is readonly */
  58771. #define BTS_PAGESIZE_FIXED 0x0002 /* Page size can no longer be changed */
  58772. #define BTS_SECURE_DELETE 0x0004 /* PRAGMA secure_delete is enabled */
  58773. #define BTS_OVERWRITE 0x0008 /* Overwrite deleted content with zeros */
  58774. #define BTS_FAST_SECURE 0x000c /* Combination of the previous two */
  58775. #define BTS_INITIALLY_EMPTY 0x0010 /* Database was empty at trans start */
  58776. #define BTS_NO_WAL 0x0020 /* Do not open write-ahead-log files */
  58777. #define BTS_EXCLUSIVE 0x0040 /* pWriter has an exclusive lock */
  58778. #define BTS_PENDING 0x0080 /* Waiting for read-locks to clear */
  58779. /*
  58780. ** An instance of the following structure is used to hold information
  58781. ** about a cell. The parseCellPtr() function fills in this structure
  58782. ** based on information extract from the raw disk page.
  58783. */
  58784. struct CellInfo {
  58785. i64 nKey; /* The key for INTKEY tables, or nPayload otherwise */
  58786. u8 *pPayload; /* Pointer to the start of payload */
  58787. u32 nPayload; /* Bytes of payload */
  58788. u16 nLocal; /* Amount of payload held locally, not on overflow */
  58789. u16 nSize; /* Size of the cell content on the main b-tree page */
  58790. };
  58791. /*
  58792. ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
  58793. ** this will be declared corrupt. This value is calculated based on a
  58794. ** maximum database size of 2^31 pages a minimum fanout of 2 for a
  58795. ** root-node and 3 for all other internal nodes.
  58796. **
  58797. ** If a tree that appears to be taller than this is encountered, it is
  58798. ** assumed that the database is corrupt.
  58799. */
  58800. #define BTCURSOR_MAX_DEPTH 20
  58801. /*
  58802. ** A cursor is a pointer to a particular entry within a particular
  58803. ** b-tree within a database file.
  58804. **
  58805. ** The entry is identified by its MemPage and the index in
  58806. ** MemPage.aCell[] of the entry.
  58807. **
  58808. ** A single database file can be shared by two more database connections,
  58809. ** but cursors cannot be shared. Each cursor is associated with a
  58810. ** particular database connection identified BtCursor.pBtree.db.
  58811. **
  58812. ** Fields in this structure are accessed under the BtShared.mutex
  58813. ** found at self->pBt->mutex.
  58814. **
  58815. ** skipNext meaning:
  58816. ** The meaning of skipNext depends on the value of eState:
  58817. **
  58818. ** eState Meaning of skipNext
  58819. ** VALID skipNext is meaningless and is ignored
  58820. ** INVALID skipNext is meaningless and is ignored
  58821. ** SKIPNEXT sqlite3BtreeNext() is a no-op if skipNext>0 and
  58822. ** sqlite3BtreePrevious() is no-op if skipNext<0.
  58823. ** REQUIRESEEK restoreCursorPosition() restores the cursor to
  58824. ** eState=SKIPNEXT if skipNext!=0
  58825. ** FAULT skipNext holds the cursor fault error code.
  58826. */
  58827. struct BtCursor {
  58828. u8 eState; /* One of the CURSOR_XXX constants (see below) */
  58829. u8 curFlags; /* zero or more BTCF_* flags defined below */
  58830. u8 curPagerFlags; /* Flags to send to sqlite3PagerGet() */
  58831. u8 hints; /* As configured by CursorSetHints() */
  58832. int skipNext; /* Prev() is noop if negative. Next() is noop if positive.
  58833. ** Error code if eState==CURSOR_FAULT */
  58834. Btree *pBtree; /* The Btree to which this cursor belongs */
  58835. Pgno *aOverflow; /* Cache of overflow page locations */
  58836. void *pKey; /* Saved key that was cursor last known position */
  58837. /* All fields above are zeroed when the cursor is allocated. See
  58838. ** sqlite3BtreeCursorZero(). Fields that follow must be manually
  58839. ** initialized. */
  58840. #define BTCURSOR_FIRST_UNINIT pBt /* Name of first uninitialized field */
  58841. BtShared *pBt; /* The BtShared this cursor points to */
  58842. BtCursor *pNext; /* Forms a linked list of all cursors */
  58843. CellInfo info; /* A parse of the cell we are pointing at */
  58844. i64 nKey; /* Size of pKey, or last integer key */
  58845. Pgno pgnoRoot; /* The root page of this tree */
  58846. i8 iPage; /* Index of current page in apPage */
  58847. u8 curIntKey; /* Value of apPage[0]->intKey */
  58848. u16 ix; /* Current index for apPage[iPage] */
  58849. u16 aiIdx[BTCURSOR_MAX_DEPTH-1]; /* Current index in apPage[i] */
  58850. struct KeyInfo *pKeyInfo; /* Arg passed to comparison function */
  58851. MemPage *pPage; /* Current page */
  58852. MemPage *apPage[BTCURSOR_MAX_DEPTH-1]; /* Stack of parents of current page */
  58853. };
  58854. /*
  58855. ** Legal values for BtCursor.curFlags
  58856. */
  58857. #define BTCF_WriteFlag 0x01 /* True if a write cursor */
  58858. #define BTCF_ValidNKey 0x02 /* True if info.nKey is valid */
  58859. #define BTCF_ValidOvfl 0x04 /* True if aOverflow is valid */
  58860. #define BTCF_AtLast 0x08 /* Cursor is pointing ot the last entry */
  58861. #define BTCF_Incrblob 0x10 /* True if an incremental I/O handle */
  58862. #define BTCF_Multiple 0x20 /* Maybe another cursor on the same btree */
  58863. /*
  58864. ** Potential values for BtCursor.eState.
  58865. **
  58866. ** CURSOR_INVALID:
  58867. ** Cursor does not point to a valid entry. This can happen (for example)
  58868. ** because the table is empty or because BtreeCursorFirst() has not been
  58869. ** called.
  58870. **
  58871. ** CURSOR_VALID:
  58872. ** Cursor points to a valid entry. getPayload() etc. may be called.
  58873. **
  58874. ** CURSOR_SKIPNEXT:
  58875. ** Cursor is valid except that the Cursor.skipNext field is non-zero
  58876. ** indicating that the next sqlite3BtreeNext() or sqlite3BtreePrevious()
  58877. ** operation should be a no-op.
  58878. **
  58879. ** CURSOR_REQUIRESEEK:
  58880. ** The table that this cursor was opened on still exists, but has been
  58881. ** modified since the cursor was last used. The cursor position is saved
  58882. ** in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
  58883. ** this state, restoreCursorPosition() can be called to attempt to
  58884. ** seek the cursor to the saved position.
  58885. **
  58886. ** CURSOR_FAULT:
  58887. ** An unrecoverable error (an I/O error or a malloc failure) has occurred
  58888. ** on a different connection that shares the BtShared cache with this
  58889. ** cursor. The error has left the cache in an inconsistent state.
  58890. ** Do nothing else with this cursor. Any attempt to use the cursor
  58891. ** should return the error code stored in BtCursor.skipNext
  58892. */
  58893. #define CURSOR_VALID 0
  58894. #define CURSOR_INVALID 1
  58895. #define CURSOR_SKIPNEXT 2
  58896. #define CURSOR_REQUIRESEEK 3
  58897. #define CURSOR_FAULT 4
  58898. /*
  58899. ** The database page the PENDING_BYTE occupies. This page is never used.
  58900. */
  58901. # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
  58902. /*
  58903. ** These macros define the location of the pointer-map entry for a
  58904. ** database page. The first argument to each is the number of usable
  58905. ** bytes on each page of the database (often 1024). The second is the
  58906. ** page number to look up in the pointer map.
  58907. **
  58908. ** PTRMAP_PAGENO returns the database page number of the pointer-map
  58909. ** page that stores the required pointer. PTRMAP_PTROFFSET returns
  58910. ** the offset of the requested map entry.
  58911. **
  58912. ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
  58913. ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
  58914. ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
  58915. ** this test.
  58916. */
  58917. #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
  58918. #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
  58919. #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
  58920. /*
  58921. ** The pointer map is a lookup table that identifies the parent page for
  58922. ** each child page in the database file. The parent page is the page that
  58923. ** contains a pointer to the child. Every page in the database contains
  58924. ** 0 or 1 parent pages. (In this context 'database page' refers
  58925. ** to any page that is not part of the pointer map itself.) Each pointer map
  58926. ** entry consists of a single byte 'type' and a 4 byte parent page number.
  58927. ** The PTRMAP_XXX identifiers below are the valid types.
  58928. **
  58929. ** The purpose of the pointer map is to facility moving pages from one
  58930. ** position in the file to another as part of autovacuum. When a page
  58931. ** is moved, the pointer in its parent must be updated to point to the
  58932. ** new location. The pointer map is used to locate the parent page quickly.
  58933. **
  58934. ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
  58935. ** used in this case.
  58936. **
  58937. ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
  58938. ** is not used in this case.
  58939. **
  58940. ** PTRMAP_OVERFLOW1: The database page is the first page in a list of
  58941. ** overflow pages. The page number identifies the page that
  58942. ** contains the cell with a pointer to this overflow page.
  58943. **
  58944. ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
  58945. ** overflow pages. The page-number identifies the previous
  58946. ** page in the overflow page list.
  58947. **
  58948. ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
  58949. ** identifies the parent page in the btree.
  58950. */
  58951. #define PTRMAP_ROOTPAGE 1
  58952. #define PTRMAP_FREEPAGE 2
  58953. #define PTRMAP_OVERFLOW1 3
  58954. #define PTRMAP_OVERFLOW2 4
  58955. #define PTRMAP_BTREE 5
  58956. /* A bunch of assert() statements to check the transaction state variables
  58957. ** of handle p (type Btree*) are internally consistent.
  58958. */
  58959. #define btreeIntegrity(p) \
  58960. assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
  58961. assert( p->pBt->inTransaction>=p->inTrans );
  58962. /*
  58963. ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
  58964. ** if the database supports auto-vacuum or not. Because it is used
  58965. ** within an expression that is an argument to another macro
  58966. ** (sqliteMallocRaw), it is not possible to use conditional compilation.
  58967. ** So, this macro is defined instead.
  58968. */
  58969. #ifndef SQLITE_OMIT_AUTOVACUUM
  58970. #define ISAUTOVACUUM (pBt->autoVacuum)
  58971. #else
  58972. #define ISAUTOVACUUM 0
  58973. #endif
  58974. /*
  58975. ** This structure is passed around through all the sanity checking routines
  58976. ** in order to keep track of some global state information.
  58977. **
  58978. ** The aRef[] array is allocated so that there is 1 bit for each page in
  58979. ** the database. As the integrity-check proceeds, for each page used in
  58980. ** the database the corresponding bit is set. This allows integrity-check to
  58981. ** detect pages that are used twice and orphaned pages (both of which
  58982. ** indicate corruption).
  58983. */
  58984. typedef struct IntegrityCk IntegrityCk;
  58985. struct IntegrityCk {
  58986. BtShared *pBt; /* The tree being checked out */
  58987. Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
  58988. u8 *aPgRef; /* 1 bit per page in the db (see above) */
  58989. Pgno nPage; /* Number of pages in the database */
  58990. int mxErr; /* Stop accumulating errors when this reaches zero */
  58991. int nErr; /* Number of messages written to zErrMsg so far */
  58992. int mallocFailed; /* A memory allocation error has occurred */
  58993. const char *zPfx; /* Error message prefix */
  58994. int v1, v2; /* Values for up to two %d fields in zPfx */
  58995. StrAccum errMsg; /* Accumulate the error message text here */
  58996. u32 *heap; /* Min-heap used for analyzing cell coverage */
  58997. };
  58998. /*
  58999. ** Routines to read or write a two- and four-byte big-endian integer values.
  59000. */
  59001. #define get2byte(x) ((x)[0]<<8 | (x)[1])
  59002. #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
  59003. #define get4byte sqlite3Get4byte
  59004. #define put4byte sqlite3Put4byte
  59005. /*
  59006. ** get2byteAligned(), unlike get2byte(), requires that its argument point to a
  59007. ** two-byte aligned address. get2bytea() is only used for accessing the
  59008. ** cell addresses in a btree header.
  59009. */
  59010. #if SQLITE_BYTEORDER==4321
  59011. # define get2byteAligned(x) (*(u16*)(x))
  59012. #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4008000
  59013. # define get2byteAligned(x) __builtin_bswap16(*(u16*)(x))
  59014. #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  59015. # define get2byteAligned(x) _byteswap_ushort(*(u16*)(x))
  59016. #else
  59017. # define get2byteAligned(x) ((x)[0]<<8 | (x)[1])
  59018. #endif
  59019. /************** End of btreeInt.h ********************************************/
  59020. /************** Continuing where we left off in btmutex.c ********************/
  59021. #ifndef SQLITE_OMIT_SHARED_CACHE
  59022. #if SQLITE_THREADSAFE
  59023. /*
  59024. ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
  59025. ** set BtShared.db to the database handle associated with p and the
  59026. ** p->locked boolean to true.
  59027. */
  59028. static void lockBtreeMutex(Btree *p){
  59029. assert( p->locked==0 );
  59030. assert( sqlite3_mutex_notheld(p->pBt->mutex) );
  59031. assert( sqlite3_mutex_held(p->db->mutex) );
  59032. sqlite3_mutex_enter(p->pBt->mutex);
  59033. p->pBt->db = p->db;
  59034. p->locked = 1;
  59035. }
  59036. /*
  59037. ** Release the BtShared mutex associated with B-Tree handle p and
  59038. ** clear the p->locked boolean.
  59039. */
  59040. static void SQLITE_NOINLINE unlockBtreeMutex(Btree *p){
  59041. BtShared *pBt = p->pBt;
  59042. assert( p->locked==1 );
  59043. assert( sqlite3_mutex_held(pBt->mutex) );
  59044. assert( sqlite3_mutex_held(p->db->mutex) );
  59045. assert( p->db==pBt->db );
  59046. sqlite3_mutex_leave(pBt->mutex);
  59047. p->locked = 0;
  59048. }
  59049. /* Forward reference */
  59050. static void SQLITE_NOINLINE btreeLockCarefully(Btree *p);
  59051. /*
  59052. ** Enter a mutex on the given BTree object.
  59053. **
  59054. ** If the object is not sharable, then no mutex is ever required
  59055. ** and this routine is a no-op. The underlying mutex is non-recursive.
  59056. ** But we keep a reference count in Btree.wantToLock so the behavior
  59057. ** of this interface is recursive.
  59058. **
  59059. ** To avoid deadlocks, multiple Btrees are locked in the same order
  59060. ** by all database connections. The p->pNext is a list of other
  59061. ** Btrees belonging to the same database connection as the p Btree
  59062. ** which need to be locked after p. If we cannot get a lock on
  59063. ** p, then first unlock all of the others on p->pNext, then wait
  59064. ** for the lock to become available on p, then relock all of the
  59065. ** subsequent Btrees that desire a lock.
  59066. */
  59067. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
  59068. /* Some basic sanity checking on the Btree. The list of Btrees
  59069. ** connected by pNext and pPrev should be in sorted order by
  59070. ** Btree.pBt value. All elements of the list should belong to
  59071. ** the same connection. Only shared Btrees are on the list. */
  59072. assert( p->pNext==0 || p->pNext->pBt>p->pBt );
  59073. assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
  59074. assert( p->pNext==0 || p->pNext->db==p->db );
  59075. assert( p->pPrev==0 || p->pPrev->db==p->db );
  59076. assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
  59077. /* Check for locking consistency */
  59078. assert( !p->locked || p->wantToLock>0 );
  59079. assert( p->sharable || p->wantToLock==0 );
  59080. /* We should already hold a lock on the database connection */
  59081. assert( sqlite3_mutex_held(p->db->mutex) );
  59082. /* Unless the database is sharable and unlocked, then BtShared.db
  59083. ** should already be set correctly. */
  59084. assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
  59085. if( !p->sharable ) return;
  59086. p->wantToLock++;
  59087. if( p->locked ) return;
  59088. btreeLockCarefully(p);
  59089. }
  59090. /* This is a helper function for sqlite3BtreeLock(). By moving
  59091. ** complex, but seldom used logic, out of sqlite3BtreeLock() and
  59092. ** into this routine, we avoid unnecessary stack pointer changes
  59093. ** and thus help the sqlite3BtreeLock() routine to run much faster
  59094. ** in the common case.
  59095. */
  59096. static void SQLITE_NOINLINE btreeLockCarefully(Btree *p){
  59097. Btree *pLater;
  59098. /* In most cases, we should be able to acquire the lock we
  59099. ** want without having to go through the ascending lock
  59100. ** procedure that follows. Just be sure not to block.
  59101. */
  59102. if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
  59103. p->pBt->db = p->db;
  59104. p->locked = 1;
  59105. return;
  59106. }
  59107. /* To avoid deadlock, first release all locks with a larger
  59108. ** BtShared address. Then acquire our lock. Then reacquire
  59109. ** the other BtShared locks that we used to hold in ascending
  59110. ** order.
  59111. */
  59112. for(pLater=p->pNext; pLater; pLater=pLater->pNext){
  59113. assert( pLater->sharable );
  59114. assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
  59115. assert( !pLater->locked || pLater->wantToLock>0 );
  59116. if( pLater->locked ){
  59117. unlockBtreeMutex(pLater);
  59118. }
  59119. }
  59120. lockBtreeMutex(p);
  59121. for(pLater=p->pNext; pLater; pLater=pLater->pNext){
  59122. if( pLater->wantToLock ){
  59123. lockBtreeMutex(pLater);
  59124. }
  59125. }
  59126. }
  59127. /*
  59128. ** Exit the recursive mutex on a Btree.
  59129. */
  59130. SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
  59131. assert( sqlite3_mutex_held(p->db->mutex) );
  59132. if( p->sharable ){
  59133. assert( p->wantToLock>0 );
  59134. p->wantToLock--;
  59135. if( p->wantToLock==0 ){
  59136. unlockBtreeMutex(p);
  59137. }
  59138. }
  59139. }
  59140. #ifndef NDEBUG
  59141. /*
  59142. ** Return true if the BtShared mutex is held on the btree, or if the
  59143. ** B-Tree is not marked as sharable.
  59144. **
  59145. ** This routine is used only from within assert() statements.
  59146. */
  59147. SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
  59148. assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
  59149. assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
  59150. assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
  59151. assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
  59152. return (p->sharable==0 || p->locked);
  59153. }
  59154. #endif
  59155. /*
  59156. ** Enter the mutex on every Btree associated with a database
  59157. ** connection. This is needed (for example) prior to parsing
  59158. ** a statement since we will be comparing table and column names
  59159. ** against all schemas and we do not want those schemas being
  59160. ** reset out from under us.
  59161. **
  59162. ** There is a corresponding leave-all procedures.
  59163. **
  59164. ** Enter the mutexes in accending order by BtShared pointer address
  59165. ** to avoid the possibility of deadlock when two threads with
  59166. ** two or more btrees in common both try to lock all their btrees
  59167. ** at the same instant.
  59168. */
  59169. static void SQLITE_NOINLINE btreeEnterAll(sqlite3 *db){
  59170. int i;
  59171. int skipOk = 1;
  59172. Btree *p;
  59173. assert( sqlite3_mutex_held(db->mutex) );
  59174. for(i=0; i<db->nDb; i++){
  59175. p = db->aDb[i].pBt;
  59176. if( p && p->sharable ){
  59177. sqlite3BtreeEnter(p);
  59178. skipOk = 0;
  59179. }
  59180. }
  59181. db->noSharedCache = skipOk;
  59182. }
  59183. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
  59184. if( db->noSharedCache==0 ) btreeEnterAll(db);
  59185. }
  59186. static void SQLITE_NOINLINE btreeLeaveAll(sqlite3 *db){
  59187. int i;
  59188. Btree *p;
  59189. assert( sqlite3_mutex_held(db->mutex) );
  59190. for(i=0; i<db->nDb; i++){
  59191. p = db->aDb[i].pBt;
  59192. if( p ) sqlite3BtreeLeave(p);
  59193. }
  59194. }
  59195. SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
  59196. if( db->noSharedCache==0 ) btreeLeaveAll(db);
  59197. }
  59198. #ifndef NDEBUG
  59199. /*
  59200. ** Return true if the current thread holds the database connection
  59201. ** mutex and all required BtShared mutexes.
  59202. **
  59203. ** This routine is used inside assert() statements only.
  59204. */
  59205. SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
  59206. int i;
  59207. if( !sqlite3_mutex_held(db->mutex) ){
  59208. return 0;
  59209. }
  59210. for(i=0; i<db->nDb; i++){
  59211. Btree *p;
  59212. p = db->aDb[i].pBt;
  59213. if( p && p->sharable &&
  59214. (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
  59215. return 0;
  59216. }
  59217. }
  59218. return 1;
  59219. }
  59220. #endif /* NDEBUG */
  59221. #ifndef NDEBUG
  59222. /*
  59223. ** Return true if the correct mutexes are held for accessing the
  59224. ** db->aDb[iDb].pSchema structure. The mutexes required for schema
  59225. ** access are:
  59226. **
  59227. ** (1) The mutex on db
  59228. ** (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
  59229. **
  59230. ** If pSchema is not NULL, then iDb is computed from pSchema and
  59231. ** db using sqlite3SchemaToIndex().
  59232. */
  59233. SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
  59234. Btree *p;
  59235. assert( db!=0 );
  59236. if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
  59237. assert( iDb>=0 && iDb<db->nDb );
  59238. if( !sqlite3_mutex_held(db->mutex) ) return 0;
  59239. if( iDb==1 ) return 1;
  59240. p = db->aDb[iDb].pBt;
  59241. assert( p!=0 );
  59242. return p->sharable==0 || p->locked==1;
  59243. }
  59244. #endif /* NDEBUG */
  59245. #else /* SQLITE_THREADSAFE>0 above. SQLITE_THREADSAFE==0 below */
  59246. /*
  59247. ** The following are special cases for mutex enter routines for use
  59248. ** in single threaded applications that use shared cache. Except for
  59249. ** these two routines, all mutex operations are no-ops in that case and
  59250. ** are null #defines in btree.h.
  59251. **
  59252. ** If shared cache is disabled, then all btree mutex routines, including
  59253. ** the ones below, are no-ops and are null #defines in btree.h.
  59254. */
  59255. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
  59256. p->pBt->db = p->db;
  59257. }
  59258. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
  59259. int i;
  59260. for(i=0; i<db->nDb; i++){
  59261. Btree *p = db->aDb[i].pBt;
  59262. if( p ){
  59263. p->pBt->db = p->db;
  59264. }
  59265. }
  59266. }
  59267. #endif /* if SQLITE_THREADSAFE */
  59268. #ifndef SQLITE_OMIT_INCRBLOB
  59269. /*
  59270. ** Enter a mutex on a Btree given a cursor owned by that Btree.
  59271. **
  59272. ** These entry points are used by incremental I/O only. Enter() is required
  59273. ** any time OMIT_SHARED_CACHE is not defined, regardless of whether or not
  59274. ** the build is threadsafe. Leave() is only required by threadsafe builds.
  59275. */
  59276. SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
  59277. sqlite3BtreeEnter(pCur->pBtree);
  59278. }
  59279. # if SQLITE_THREADSAFE
  59280. SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
  59281. sqlite3BtreeLeave(pCur->pBtree);
  59282. }
  59283. # endif
  59284. #endif /* ifndef SQLITE_OMIT_INCRBLOB */
  59285. #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
  59286. /************** End of btmutex.c *********************************************/
  59287. /************** Begin file btree.c *******************************************/
  59288. /*
  59289. ** 2004 April 6
  59290. **
  59291. ** The author disclaims copyright to this source code. In place of
  59292. ** a legal notice, here is a blessing:
  59293. **
  59294. ** May you do good and not evil.
  59295. ** May you find forgiveness for yourself and forgive others.
  59296. ** May you share freely, never taking more than you give.
  59297. **
  59298. *************************************************************************
  59299. ** This file implements an external (disk-based) database using BTrees.
  59300. ** See the header comment on "btreeInt.h" for additional information.
  59301. ** Including a description of file format and an overview of operation.
  59302. */
  59303. /* #include "btreeInt.h" */
  59304. /*
  59305. ** The header string that appears at the beginning of every
  59306. ** SQLite database.
  59307. */
  59308. static const char zMagicHeader[] = SQLITE_FILE_HEADER;
  59309. /*
  59310. ** Set this global variable to 1 to enable tracing using the TRACE
  59311. ** macro.
  59312. */
  59313. #if 0
  59314. int sqlite3BtreeTrace=1; /* True to enable tracing */
  59315. # define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);}
  59316. #else
  59317. # define TRACE(X)
  59318. #endif
  59319. /*
  59320. ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
  59321. ** But if the value is zero, make it 65536.
  59322. **
  59323. ** This routine is used to extract the "offset to cell content area" value
  59324. ** from the header of a btree page. If the page size is 65536 and the page
  59325. ** is empty, the offset should be 65536, but the 2-byte value stores zero.
  59326. ** This routine makes the necessary adjustment to 65536.
  59327. */
  59328. #define get2byteNotZero(X) (((((int)get2byte(X))-1)&0xffff)+1)
  59329. /*
  59330. ** Values passed as the 5th argument to allocateBtreePage()
  59331. */
  59332. #define BTALLOC_ANY 0 /* Allocate any page */
  59333. #define BTALLOC_EXACT 1 /* Allocate exact page if possible */
  59334. #define BTALLOC_LE 2 /* Allocate any page <= the parameter */
  59335. /*
  59336. ** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not
  59337. ** defined, or 0 if it is. For example:
  59338. **
  59339. ** bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
  59340. */
  59341. #ifndef SQLITE_OMIT_AUTOVACUUM
  59342. #define IfNotOmitAV(expr) (expr)
  59343. #else
  59344. #define IfNotOmitAV(expr) 0
  59345. #endif
  59346. #ifndef SQLITE_OMIT_SHARED_CACHE
  59347. /*
  59348. ** A list of BtShared objects that are eligible for participation
  59349. ** in shared cache. This variable has file scope during normal builds,
  59350. ** but the test harness needs to access it so we make it global for
  59351. ** test builds.
  59352. **
  59353. ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
  59354. */
  59355. #ifdef SQLITE_TEST
  59356. SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
  59357. #else
  59358. static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
  59359. #endif
  59360. #endif /* SQLITE_OMIT_SHARED_CACHE */
  59361. #ifndef SQLITE_OMIT_SHARED_CACHE
  59362. /*
  59363. ** Enable or disable the shared pager and schema features.
  59364. **
  59365. ** This routine has no effect on existing database connections.
  59366. ** The shared cache setting effects only future calls to
  59367. ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
  59368. */
  59369. SQLITE_API int sqlite3_enable_shared_cache(int enable){
  59370. sqlite3GlobalConfig.sharedCacheEnabled = enable;
  59371. return SQLITE_OK;
  59372. }
  59373. #endif
  59374. #ifdef SQLITE_OMIT_SHARED_CACHE
  59375. /*
  59376. ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
  59377. ** and clearAllSharedCacheTableLocks()
  59378. ** manipulate entries in the BtShared.pLock linked list used to store
  59379. ** shared-cache table level locks. If the library is compiled with the
  59380. ** shared-cache feature disabled, then there is only ever one user
  59381. ** of each BtShared structure and so this locking is not necessary.
  59382. ** So define the lock related functions as no-ops.
  59383. */
  59384. #define querySharedCacheTableLock(a,b,c) SQLITE_OK
  59385. #define setSharedCacheTableLock(a,b,c) SQLITE_OK
  59386. #define clearAllSharedCacheTableLocks(a)
  59387. #define downgradeAllSharedCacheTableLocks(a)
  59388. #define hasSharedCacheTableLock(a,b,c,d) 1
  59389. #define hasReadConflicts(a, b) 0
  59390. #endif
  59391. /*
  59392. ** Implementation of the SQLITE_CORRUPT_PAGE() macro. Takes a single
  59393. ** (MemPage*) as an argument. The (MemPage*) must not be NULL.
  59394. **
  59395. ** If SQLITE_DEBUG is not defined, then this macro is equivalent to
  59396. ** SQLITE_CORRUPT_BKPT. Or, if SQLITE_DEBUG is set, then the log message
  59397. ** normally produced as a side-effect of SQLITE_CORRUPT_BKPT is augmented
  59398. ** with the page number and filename associated with the (MemPage*).
  59399. */
  59400. #ifdef SQLITE_DEBUG
  59401. int corruptPageError(int lineno, MemPage *p){
  59402. char *zMsg;
  59403. sqlite3BeginBenignMalloc();
  59404. zMsg = sqlite3_mprintf("database corruption page %d of %s",
  59405. (int)p->pgno, sqlite3PagerFilename(p->pBt->pPager, 0)
  59406. );
  59407. sqlite3EndBenignMalloc();
  59408. if( zMsg ){
  59409. sqlite3ReportError(SQLITE_CORRUPT, lineno, zMsg);
  59410. }
  59411. sqlite3_free(zMsg);
  59412. return SQLITE_CORRUPT_BKPT;
  59413. }
  59414. # define SQLITE_CORRUPT_PAGE(pMemPage) corruptPageError(__LINE__, pMemPage)
  59415. #else
  59416. # define SQLITE_CORRUPT_PAGE(pMemPage) SQLITE_CORRUPT_PGNO(pMemPage->pgno)
  59417. #endif
  59418. #ifndef SQLITE_OMIT_SHARED_CACHE
  59419. #ifdef SQLITE_DEBUG
  59420. /*
  59421. **** This function is only used as part of an assert() statement. ***
  59422. **
  59423. ** Check to see if pBtree holds the required locks to read or write to the
  59424. ** table with root page iRoot. Return 1 if it does and 0 if not.
  59425. **
  59426. ** For example, when writing to a table with root-page iRoot via
  59427. ** Btree connection pBtree:
  59428. **
  59429. ** assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
  59430. **
  59431. ** When writing to an index that resides in a sharable database, the
  59432. ** caller should have first obtained a lock specifying the root page of
  59433. ** the corresponding table. This makes things a bit more complicated,
  59434. ** as this module treats each table as a separate structure. To determine
  59435. ** the table corresponding to the index being written, this
  59436. ** function has to search through the database schema.
  59437. **
  59438. ** Instead of a lock on the table/index rooted at page iRoot, the caller may
  59439. ** hold a write-lock on the schema table (root page 1). This is also
  59440. ** acceptable.
  59441. */
  59442. static int hasSharedCacheTableLock(
  59443. Btree *pBtree, /* Handle that must hold lock */
  59444. Pgno iRoot, /* Root page of b-tree */
  59445. int isIndex, /* True if iRoot is the root of an index b-tree */
  59446. int eLockType /* Required lock type (READ_LOCK or WRITE_LOCK) */
  59447. ){
  59448. Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
  59449. Pgno iTab = 0;
  59450. BtLock *pLock;
  59451. /* If this database is not shareable, or if the client is reading
  59452. ** and has the read-uncommitted flag set, then no lock is required.
  59453. ** Return true immediately.
  59454. */
  59455. if( (pBtree->sharable==0)
  59456. || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommit))
  59457. ){
  59458. return 1;
  59459. }
  59460. /* If the client is reading or writing an index and the schema is
  59461. ** not loaded, then it is too difficult to actually check to see if
  59462. ** the correct locks are held. So do not bother - just return true.
  59463. ** This case does not come up very often anyhow.
  59464. */
  59465. if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded)==0) ){
  59466. return 1;
  59467. }
  59468. /* Figure out the root-page that the lock should be held on. For table
  59469. ** b-trees, this is just the root page of the b-tree being read or
  59470. ** written. For index b-trees, it is the root page of the associated
  59471. ** table. */
  59472. if( isIndex ){
  59473. HashElem *p;
  59474. for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
  59475. Index *pIdx = (Index *)sqliteHashData(p);
  59476. if( pIdx->tnum==(int)iRoot ){
  59477. if( iTab ){
  59478. /* Two or more indexes share the same root page. There must
  59479. ** be imposter tables. So just return true. The assert is not
  59480. ** useful in that case. */
  59481. return 1;
  59482. }
  59483. iTab = pIdx->pTable->tnum;
  59484. }
  59485. }
  59486. }else{
  59487. iTab = iRoot;
  59488. }
  59489. /* Search for the required lock. Either a write-lock on root-page iTab, a
  59490. ** write-lock on the schema table, or (if the client is reading) a
  59491. ** read-lock on iTab will suffice. Return 1 if any of these are found. */
  59492. for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
  59493. if( pLock->pBtree==pBtree
  59494. && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
  59495. && pLock->eLock>=eLockType
  59496. ){
  59497. return 1;
  59498. }
  59499. }
  59500. /* Failed to find the required lock. */
  59501. return 0;
  59502. }
  59503. #endif /* SQLITE_DEBUG */
  59504. #ifdef SQLITE_DEBUG
  59505. /*
  59506. **** This function may be used as part of assert() statements only. ****
  59507. **
  59508. ** Return true if it would be illegal for pBtree to write into the
  59509. ** table or index rooted at iRoot because other shared connections are
  59510. ** simultaneously reading that same table or index.
  59511. **
  59512. ** It is illegal for pBtree to write if some other Btree object that
  59513. ** shares the same BtShared object is currently reading or writing
  59514. ** the iRoot table. Except, if the other Btree object has the
  59515. ** read-uncommitted flag set, then it is OK for the other object to
  59516. ** have a read cursor.
  59517. **
  59518. ** For example, before writing to any part of the table or index
  59519. ** rooted at page iRoot, one should call:
  59520. **
  59521. ** assert( !hasReadConflicts(pBtree, iRoot) );
  59522. */
  59523. static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
  59524. BtCursor *p;
  59525. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  59526. if( p->pgnoRoot==iRoot
  59527. && p->pBtree!=pBtree
  59528. && 0==(p->pBtree->db->flags & SQLITE_ReadUncommit)
  59529. ){
  59530. return 1;
  59531. }
  59532. }
  59533. return 0;
  59534. }
  59535. #endif /* #ifdef SQLITE_DEBUG */
  59536. /*
  59537. ** Query to see if Btree handle p may obtain a lock of type eLock
  59538. ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
  59539. ** SQLITE_OK if the lock may be obtained (by calling
  59540. ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
  59541. */
  59542. static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
  59543. BtShared *pBt = p->pBt;
  59544. BtLock *pIter;
  59545. assert( sqlite3BtreeHoldsMutex(p) );
  59546. assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
  59547. assert( p->db!=0 );
  59548. assert( !(p->db->flags&SQLITE_ReadUncommit)||eLock==WRITE_LOCK||iTab==1 );
  59549. /* If requesting a write-lock, then the Btree must have an open write
  59550. ** transaction on this file. And, obviously, for this to be so there
  59551. ** must be an open write transaction on the file itself.
  59552. */
  59553. assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
  59554. assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
  59555. /* This routine is a no-op if the shared-cache is not enabled */
  59556. if( !p->sharable ){
  59557. return SQLITE_OK;
  59558. }
  59559. /* If some other connection is holding an exclusive lock, the
  59560. ** requested lock may not be obtained.
  59561. */
  59562. if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
  59563. sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
  59564. return SQLITE_LOCKED_SHAREDCACHE;
  59565. }
  59566. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  59567. /* The condition (pIter->eLock!=eLock) in the following if(...)
  59568. ** statement is a simplification of:
  59569. **
  59570. ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
  59571. **
  59572. ** since we know that if eLock==WRITE_LOCK, then no other connection
  59573. ** may hold a WRITE_LOCK on any table in this file (since there can
  59574. ** only be a single writer).
  59575. */
  59576. assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
  59577. assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
  59578. if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
  59579. sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
  59580. if( eLock==WRITE_LOCK ){
  59581. assert( p==pBt->pWriter );
  59582. pBt->btsFlags |= BTS_PENDING;
  59583. }
  59584. return SQLITE_LOCKED_SHAREDCACHE;
  59585. }
  59586. }
  59587. return SQLITE_OK;
  59588. }
  59589. #endif /* !SQLITE_OMIT_SHARED_CACHE */
  59590. #ifndef SQLITE_OMIT_SHARED_CACHE
  59591. /*
  59592. ** Add a lock on the table with root-page iTable to the shared-btree used
  59593. ** by Btree handle p. Parameter eLock must be either READ_LOCK or
  59594. ** WRITE_LOCK.
  59595. **
  59596. ** This function assumes the following:
  59597. **
  59598. ** (a) The specified Btree object p is connected to a sharable
  59599. ** database (one with the BtShared.sharable flag set), and
  59600. **
  59601. ** (b) No other Btree objects hold a lock that conflicts
  59602. ** with the requested lock (i.e. querySharedCacheTableLock() has
  59603. ** already been called and returned SQLITE_OK).
  59604. **
  59605. ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
  59606. ** is returned if a malloc attempt fails.
  59607. */
  59608. static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
  59609. BtShared *pBt = p->pBt;
  59610. BtLock *pLock = 0;
  59611. BtLock *pIter;
  59612. assert( sqlite3BtreeHoldsMutex(p) );
  59613. assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
  59614. assert( p->db!=0 );
  59615. /* A connection with the read-uncommitted flag set will never try to
  59616. ** obtain a read-lock using this function. The only read-lock obtained
  59617. ** by a connection in read-uncommitted mode is on the sqlite_master
  59618. ** table, and that lock is obtained in BtreeBeginTrans(). */
  59619. assert( 0==(p->db->flags&SQLITE_ReadUncommit) || eLock==WRITE_LOCK );
  59620. /* This function should only be called on a sharable b-tree after it
  59621. ** has been determined that no other b-tree holds a conflicting lock. */
  59622. assert( p->sharable );
  59623. assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
  59624. /* First search the list for an existing lock on this table. */
  59625. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  59626. if( pIter->iTable==iTable && pIter->pBtree==p ){
  59627. pLock = pIter;
  59628. break;
  59629. }
  59630. }
  59631. /* If the above search did not find a BtLock struct associating Btree p
  59632. ** with table iTable, allocate one and link it into the list.
  59633. */
  59634. if( !pLock ){
  59635. pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
  59636. if( !pLock ){
  59637. return SQLITE_NOMEM_BKPT;
  59638. }
  59639. pLock->iTable = iTable;
  59640. pLock->pBtree = p;
  59641. pLock->pNext = pBt->pLock;
  59642. pBt->pLock = pLock;
  59643. }
  59644. /* Set the BtLock.eLock variable to the maximum of the current lock
  59645. ** and the requested lock. This means if a write-lock was already held
  59646. ** and a read-lock requested, we don't incorrectly downgrade the lock.
  59647. */
  59648. assert( WRITE_LOCK>READ_LOCK );
  59649. if( eLock>pLock->eLock ){
  59650. pLock->eLock = eLock;
  59651. }
  59652. return SQLITE_OK;
  59653. }
  59654. #endif /* !SQLITE_OMIT_SHARED_CACHE */
  59655. #ifndef SQLITE_OMIT_SHARED_CACHE
  59656. /*
  59657. ** Release all the table locks (locks obtained via calls to
  59658. ** the setSharedCacheTableLock() procedure) held by Btree object p.
  59659. **
  59660. ** This function assumes that Btree p has an open read or write
  59661. ** transaction. If it does not, then the BTS_PENDING flag
  59662. ** may be incorrectly cleared.
  59663. */
  59664. static void clearAllSharedCacheTableLocks(Btree *p){
  59665. BtShared *pBt = p->pBt;
  59666. BtLock **ppIter = &pBt->pLock;
  59667. assert( sqlite3BtreeHoldsMutex(p) );
  59668. assert( p->sharable || 0==*ppIter );
  59669. assert( p->inTrans>0 );
  59670. while( *ppIter ){
  59671. BtLock *pLock = *ppIter;
  59672. assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
  59673. assert( pLock->pBtree->inTrans>=pLock->eLock );
  59674. if( pLock->pBtree==p ){
  59675. *ppIter = pLock->pNext;
  59676. assert( pLock->iTable!=1 || pLock==&p->lock );
  59677. if( pLock->iTable!=1 ){
  59678. sqlite3_free(pLock);
  59679. }
  59680. }else{
  59681. ppIter = &pLock->pNext;
  59682. }
  59683. }
  59684. assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
  59685. if( pBt->pWriter==p ){
  59686. pBt->pWriter = 0;
  59687. pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
  59688. }else if( pBt->nTransaction==2 ){
  59689. /* This function is called when Btree p is concluding its
  59690. ** transaction. If there currently exists a writer, and p is not
  59691. ** that writer, then the number of locks held by connections other
  59692. ** than the writer must be about to drop to zero. In this case
  59693. ** set the BTS_PENDING flag to 0.
  59694. **
  59695. ** If there is not currently a writer, then BTS_PENDING must
  59696. ** be zero already. So this next line is harmless in that case.
  59697. */
  59698. pBt->btsFlags &= ~BTS_PENDING;
  59699. }
  59700. }
  59701. /*
  59702. ** This function changes all write-locks held by Btree p into read-locks.
  59703. */
  59704. static void downgradeAllSharedCacheTableLocks(Btree *p){
  59705. BtShared *pBt = p->pBt;
  59706. if( pBt->pWriter==p ){
  59707. BtLock *pLock;
  59708. pBt->pWriter = 0;
  59709. pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
  59710. for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
  59711. assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
  59712. pLock->eLock = READ_LOCK;
  59713. }
  59714. }
  59715. }
  59716. #endif /* SQLITE_OMIT_SHARED_CACHE */
  59717. static void releasePage(MemPage *pPage); /* Forward reference */
  59718. static void releasePageOne(MemPage *pPage); /* Forward reference */
  59719. static void releasePageNotNull(MemPage *pPage); /* Forward reference */
  59720. /*
  59721. ***** This routine is used inside of assert() only ****
  59722. **
  59723. ** Verify that the cursor holds the mutex on its BtShared
  59724. */
  59725. #ifdef SQLITE_DEBUG
  59726. static int cursorHoldsMutex(BtCursor *p){
  59727. return sqlite3_mutex_held(p->pBt->mutex);
  59728. }
  59729. /* Verify that the cursor and the BtShared agree about what is the current
  59730. ** database connetion. This is important in shared-cache mode. If the database
  59731. ** connection pointers get out-of-sync, it is possible for routines like
  59732. ** btreeInitPage() to reference an stale connection pointer that references a
  59733. ** a connection that has already closed. This routine is used inside assert()
  59734. ** statements only and for the purpose of double-checking that the btree code
  59735. ** does keep the database connection pointers up-to-date.
  59736. */
  59737. static int cursorOwnsBtShared(BtCursor *p){
  59738. assert( cursorHoldsMutex(p) );
  59739. return (p->pBtree->db==p->pBt->db);
  59740. }
  59741. #endif
  59742. /*
  59743. ** Invalidate the overflow cache of the cursor passed as the first argument.
  59744. ** on the shared btree structure pBt.
  59745. */
  59746. #define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl)
  59747. /*
  59748. ** Invalidate the overflow page-list cache for all cursors opened
  59749. ** on the shared btree structure pBt.
  59750. */
  59751. static void invalidateAllOverflowCache(BtShared *pBt){
  59752. BtCursor *p;
  59753. assert( sqlite3_mutex_held(pBt->mutex) );
  59754. for(p=pBt->pCursor; p; p=p->pNext){
  59755. invalidateOverflowCache(p);
  59756. }
  59757. }
  59758. #ifndef SQLITE_OMIT_INCRBLOB
  59759. /*
  59760. ** This function is called before modifying the contents of a table
  59761. ** to invalidate any incrblob cursors that are open on the
  59762. ** row or one of the rows being modified.
  59763. **
  59764. ** If argument isClearTable is true, then the entire contents of the
  59765. ** table is about to be deleted. In this case invalidate all incrblob
  59766. ** cursors open on any row within the table with root-page pgnoRoot.
  59767. **
  59768. ** Otherwise, if argument isClearTable is false, then the row with
  59769. ** rowid iRow is being replaced or deleted. In this case invalidate
  59770. ** only those incrblob cursors open on that specific row.
  59771. */
  59772. static void invalidateIncrblobCursors(
  59773. Btree *pBtree, /* The database file to check */
  59774. Pgno pgnoRoot, /* The table that might be changing */
  59775. i64 iRow, /* The rowid that might be changing */
  59776. int isClearTable /* True if all rows are being deleted */
  59777. ){
  59778. BtCursor *p;
  59779. if( pBtree->hasIncrblobCur==0 ) return;
  59780. assert( sqlite3BtreeHoldsMutex(pBtree) );
  59781. pBtree->hasIncrblobCur = 0;
  59782. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  59783. if( (p->curFlags & BTCF_Incrblob)!=0 ){
  59784. pBtree->hasIncrblobCur = 1;
  59785. if( p->pgnoRoot==pgnoRoot && (isClearTable || p->info.nKey==iRow) ){
  59786. p->eState = CURSOR_INVALID;
  59787. }
  59788. }
  59789. }
  59790. }
  59791. #else
  59792. /* Stub function when INCRBLOB is omitted */
  59793. #define invalidateIncrblobCursors(w,x,y,z)
  59794. #endif /* SQLITE_OMIT_INCRBLOB */
  59795. /*
  59796. ** Set bit pgno of the BtShared.pHasContent bitvec. This is called
  59797. ** when a page that previously contained data becomes a free-list leaf
  59798. ** page.
  59799. **
  59800. ** The BtShared.pHasContent bitvec exists to work around an obscure
  59801. ** bug caused by the interaction of two useful IO optimizations surrounding
  59802. ** free-list leaf pages:
  59803. **
  59804. ** 1) When all data is deleted from a page and the page becomes
  59805. ** a free-list leaf page, the page is not written to the database
  59806. ** (as free-list leaf pages contain no meaningful data). Sometimes
  59807. ** such a page is not even journalled (as it will not be modified,
  59808. ** why bother journalling it?).
  59809. **
  59810. ** 2) When a free-list leaf page is reused, its content is not read
  59811. ** from the database or written to the journal file (why should it
  59812. ** be, if it is not at all meaningful?).
  59813. **
  59814. ** By themselves, these optimizations work fine and provide a handy
  59815. ** performance boost to bulk delete or insert operations. However, if
  59816. ** a page is moved to the free-list and then reused within the same
  59817. ** transaction, a problem comes up. If the page is not journalled when
  59818. ** it is moved to the free-list and it is also not journalled when it
  59819. ** is extracted from the free-list and reused, then the original data
  59820. ** may be lost. In the event of a rollback, it may not be possible
  59821. ** to restore the database to its original configuration.
  59822. **
  59823. ** The solution is the BtShared.pHasContent bitvec. Whenever a page is
  59824. ** moved to become a free-list leaf page, the corresponding bit is
  59825. ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
  59826. ** optimization 2 above is omitted if the corresponding bit is already
  59827. ** set in BtShared.pHasContent. The contents of the bitvec are cleared
  59828. ** at the end of every transaction.
  59829. */
  59830. static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
  59831. int rc = SQLITE_OK;
  59832. if( !pBt->pHasContent ){
  59833. assert( pgno<=pBt->nPage );
  59834. pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
  59835. if( !pBt->pHasContent ){
  59836. rc = SQLITE_NOMEM_BKPT;
  59837. }
  59838. }
  59839. if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
  59840. rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
  59841. }
  59842. return rc;
  59843. }
  59844. /*
  59845. ** Query the BtShared.pHasContent vector.
  59846. **
  59847. ** This function is called when a free-list leaf page is removed from the
  59848. ** free-list for reuse. It returns false if it is safe to retrieve the
  59849. ** page from the pager layer with the 'no-content' flag set. True otherwise.
  59850. */
  59851. static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
  59852. Bitvec *p = pBt->pHasContent;
  59853. return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
  59854. }
  59855. /*
  59856. ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
  59857. ** invoked at the conclusion of each write-transaction.
  59858. */
  59859. static void btreeClearHasContent(BtShared *pBt){
  59860. sqlite3BitvecDestroy(pBt->pHasContent);
  59861. pBt->pHasContent = 0;
  59862. }
  59863. /*
  59864. ** Release all of the apPage[] pages for a cursor.
  59865. */
  59866. static void btreeReleaseAllCursorPages(BtCursor *pCur){
  59867. int i;
  59868. if( pCur->iPage>=0 ){
  59869. for(i=0; i<pCur->iPage; i++){
  59870. releasePageNotNull(pCur->apPage[i]);
  59871. }
  59872. releasePageNotNull(pCur->pPage);
  59873. pCur->iPage = -1;
  59874. }
  59875. }
  59876. /*
  59877. ** The cursor passed as the only argument must point to a valid entry
  59878. ** when this function is called (i.e. have eState==CURSOR_VALID). This
  59879. ** function saves the current cursor key in variables pCur->nKey and
  59880. ** pCur->pKey. SQLITE_OK is returned if successful or an SQLite error
  59881. ** code otherwise.
  59882. **
  59883. ** If the cursor is open on an intkey table, then the integer key
  59884. ** (the rowid) is stored in pCur->nKey and pCur->pKey is left set to
  59885. ** NULL. If the cursor is open on a non-intkey table, then pCur->pKey is
  59886. ** set to point to a malloced buffer pCur->nKey bytes in size containing
  59887. ** the key.
  59888. */
  59889. static int saveCursorKey(BtCursor *pCur){
  59890. int rc = SQLITE_OK;
  59891. assert( CURSOR_VALID==pCur->eState );
  59892. assert( 0==pCur->pKey );
  59893. assert( cursorHoldsMutex(pCur) );
  59894. if( pCur->curIntKey ){
  59895. /* Only the rowid is required for a table btree */
  59896. pCur->nKey = sqlite3BtreeIntegerKey(pCur);
  59897. }else{
  59898. /* For an index btree, save the complete key content. It is possible
  59899. ** that the current key is corrupt. In that case, it is possible that
  59900. ** the sqlite3VdbeRecordUnpack() function may overread the buffer by
  59901. ** up to the size of 1 varint plus 1 8-byte value when the cursor
  59902. ** position is restored. Hence the 17 bytes of padding allocated
  59903. ** below. */
  59904. void *pKey;
  59905. pCur->nKey = sqlite3BtreePayloadSize(pCur);
  59906. pKey = sqlite3Malloc( pCur->nKey + 9 + 8 );
  59907. if( pKey ){
  59908. rc = sqlite3BtreePayload(pCur, 0, (int)pCur->nKey, pKey);
  59909. if( rc==SQLITE_OK ){
  59910. memset(((u8*)pKey)+pCur->nKey, 0, 9+8);
  59911. pCur->pKey = pKey;
  59912. }else{
  59913. sqlite3_free(pKey);
  59914. }
  59915. }else{
  59916. rc = SQLITE_NOMEM_BKPT;
  59917. }
  59918. }
  59919. assert( !pCur->curIntKey || !pCur->pKey );
  59920. return rc;
  59921. }
  59922. /*
  59923. ** Save the current cursor position in the variables BtCursor.nKey
  59924. ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
  59925. **
  59926. ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
  59927. ** prior to calling this routine.
  59928. */
  59929. static int saveCursorPosition(BtCursor *pCur){
  59930. int rc;
  59931. assert( CURSOR_VALID==pCur->eState || CURSOR_SKIPNEXT==pCur->eState );
  59932. assert( 0==pCur->pKey );
  59933. assert( cursorHoldsMutex(pCur) );
  59934. if( pCur->eState==CURSOR_SKIPNEXT ){
  59935. pCur->eState = CURSOR_VALID;
  59936. }else{
  59937. pCur->skipNext = 0;
  59938. }
  59939. rc = saveCursorKey(pCur);
  59940. if( rc==SQLITE_OK ){
  59941. btreeReleaseAllCursorPages(pCur);
  59942. pCur->eState = CURSOR_REQUIRESEEK;
  59943. }
  59944. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl|BTCF_AtLast);
  59945. return rc;
  59946. }
  59947. /* Forward reference */
  59948. static int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*);
  59949. /*
  59950. ** Save the positions of all cursors (except pExcept) that are open on
  59951. ** the table with root-page iRoot. "Saving the cursor position" means that
  59952. ** the location in the btree is remembered in such a way that it can be
  59953. ** moved back to the same spot after the btree has been modified. This
  59954. ** routine is called just before cursor pExcept is used to modify the
  59955. ** table, for example in BtreeDelete() or BtreeInsert().
  59956. **
  59957. ** If there are two or more cursors on the same btree, then all such
  59958. ** cursors should have their BTCF_Multiple flag set. The btreeCursor()
  59959. ** routine enforces that rule. This routine only needs to be called in
  59960. ** the uncommon case when pExpect has the BTCF_Multiple flag set.
  59961. **
  59962. ** If pExpect!=NULL and if no other cursors are found on the same root-page,
  59963. ** then the BTCF_Multiple flag on pExpect is cleared, to avoid another
  59964. ** pointless call to this routine.
  59965. **
  59966. ** Implementation note: This routine merely checks to see if any cursors
  59967. ** need to be saved. It calls out to saveCursorsOnList() in the (unusual)
  59968. ** event that cursors are in need to being saved.
  59969. */
  59970. static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
  59971. BtCursor *p;
  59972. assert( sqlite3_mutex_held(pBt->mutex) );
  59973. assert( pExcept==0 || pExcept->pBt==pBt );
  59974. for(p=pBt->pCursor; p; p=p->pNext){
  59975. if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break;
  59976. }
  59977. if( p ) return saveCursorsOnList(p, iRoot, pExcept);
  59978. if( pExcept ) pExcept->curFlags &= ~BTCF_Multiple;
  59979. return SQLITE_OK;
  59980. }
  59981. /* This helper routine to saveAllCursors does the actual work of saving
  59982. ** the cursors if and when a cursor is found that actually requires saving.
  59983. ** The common case is that no cursors need to be saved, so this routine is
  59984. ** broken out from its caller to avoid unnecessary stack pointer movement.
  59985. */
  59986. static int SQLITE_NOINLINE saveCursorsOnList(
  59987. BtCursor *p, /* The first cursor that needs saving */
  59988. Pgno iRoot, /* Only save cursor with this iRoot. Save all if zero */
  59989. BtCursor *pExcept /* Do not save this cursor */
  59990. ){
  59991. do{
  59992. if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
  59993. if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
  59994. int rc = saveCursorPosition(p);
  59995. if( SQLITE_OK!=rc ){
  59996. return rc;
  59997. }
  59998. }else{
  59999. testcase( p->iPage>=0 );
  60000. btreeReleaseAllCursorPages(p);
  60001. }
  60002. }
  60003. p = p->pNext;
  60004. }while( p );
  60005. return SQLITE_OK;
  60006. }
  60007. /*
  60008. ** Clear the current cursor position.
  60009. */
  60010. SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
  60011. assert( cursorHoldsMutex(pCur) );
  60012. sqlite3_free(pCur->pKey);
  60013. pCur->pKey = 0;
  60014. pCur->eState = CURSOR_INVALID;
  60015. }
  60016. /*
  60017. ** In this version of BtreeMoveto, pKey is a packed index record
  60018. ** such as is generated by the OP_MakeRecord opcode. Unpack the
  60019. ** record and then call BtreeMovetoUnpacked() to do the work.
  60020. */
  60021. static int btreeMoveto(
  60022. BtCursor *pCur, /* Cursor open on the btree to be searched */
  60023. const void *pKey, /* Packed key if the btree is an index */
  60024. i64 nKey, /* Integer key for tables. Size of pKey for indices */
  60025. int bias, /* Bias search to the high end */
  60026. int *pRes /* Write search results here */
  60027. ){
  60028. int rc; /* Status code */
  60029. UnpackedRecord *pIdxKey; /* Unpacked index key */
  60030. if( pKey ){
  60031. KeyInfo *pKeyInfo = pCur->pKeyInfo;
  60032. assert( nKey==(i64)(int)nKey );
  60033. pIdxKey = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);
  60034. if( pIdxKey==0 ) return SQLITE_NOMEM_BKPT;
  60035. sqlite3VdbeRecordUnpack(pKeyInfo, (int)nKey, pKey, pIdxKey);
  60036. if( pIdxKey->nField==0 || pIdxKey->nField>pKeyInfo->nAllField ){
  60037. rc = SQLITE_CORRUPT_BKPT;
  60038. goto moveto_done;
  60039. }
  60040. }else{
  60041. pIdxKey = 0;
  60042. }
  60043. rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
  60044. moveto_done:
  60045. if( pIdxKey ){
  60046. sqlite3DbFree(pCur->pKeyInfo->db, pIdxKey);
  60047. }
  60048. return rc;
  60049. }
  60050. /*
  60051. ** Restore the cursor to the position it was in (or as close to as possible)
  60052. ** when saveCursorPosition() was called. Note that this call deletes the
  60053. ** saved position info stored by saveCursorPosition(), so there can be
  60054. ** at most one effective restoreCursorPosition() call after each
  60055. ** saveCursorPosition().
  60056. */
  60057. static int btreeRestoreCursorPosition(BtCursor *pCur){
  60058. int rc;
  60059. int skipNext = 0;
  60060. assert( cursorOwnsBtShared(pCur) );
  60061. assert( pCur->eState>=CURSOR_REQUIRESEEK );
  60062. if( pCur->eState==CURSOR_FAULT ){
  60063. return pCur->skipNext;
  60064. }
  60065. pCur->eState = CURSOR_INVALID;
  60066. if( sqlite3FaultSim(410) ){
  60067. rc = SQLITE_IOERR;
  60068. }else{
  60069. rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &skipNext);
  60070. }
  60071. if( rc==SQLITE_OK ){
  60072. sqlite3_free(pCur->pKey);
  60073. pCur->pKey = 0;
  60074. assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
  60075. if( skipNext ) pCur->skipNext = skipNext;
  60076. if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
  60077. pCur->eState = CURSOR_SKIPNEXT;
  60078. }
  60079. }
  60080. return rc;
  60081. }
  60082. #define restoreCursorPosition(p) \
  60083. (p->eState>=CURSOR_REQUIRESEEK ? \
  60084. btreeRestoreCursorPosition(p) : \
  60085. SQLITE_OK)
  60086. /*
  60087. ** Determine whether or not a cursor has moved from the position where
  60088. ** it was last placed, or has been invalidated for any other reason.
  60089. ** Cursors can move when the row they are pointing at is deleted out
  60090. ** from under them, for example. Cursor might also move if a btree
  60091. ** is rebalanced.
  60092. **
  60093. ** Calling this routine with a NULL cursor pointer returns false.
  60094. **
  60095. ** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor
  60096. ** back to where it ought to be if this routine returns true.
  60097. */
  60098. SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur){
  60099. assert( EIGHT_BYTE_ALIGNMENT(pCur)
  60100. || pCur==sqlite3BtreeFakeValidCursor() );
  60101. assert( offsetof(BtCursor, eState)==0 );
  60102. assert( sizeof(pCur->eState)==1 );
  60103. return CURSOR_VALID != *(u8*)pCur;
  60104. }
  60105. /*
  60106. ** Return a pointer to a fake BtCursor object that will always answer
  60107. ** false to the sqlite3BtreeCursorHasMoved() routine above. The fake
  60108. ** cursor returned must not be used with any other Btree interface.
  60109. */
  60110. SQLITE_PRIVATE BtCursor *sqlite3BtreeFakeValidCursor(void){
  60111. static u8 fakeCursor = CURSOR_VALID;
  60112. assert( offsetof(BtCursor, eState)==0 );
  60113. return (BtCursor*)&fakeCursor;
  60114. }
  60115. /*
  60116. ** This routine restores a cursor back to its original position after it
  60117. ** has been moved by some outside activity (such as a btree rebalance or
  60118. ** a row having been deleted out from under the cursor).
  60119. **
  60120. ** On success, the *pDifferentRow parameter is false if the cursor is left
  60121. ** pointing at exactly the same row. *pDifferntRow is the row the cursor
  60122. ** was pointing to has been deleted, forcing the cursor to point to some
  60123. ** nearby row.
  60124. **
  60125. ** This routine should only be called for a cursor that just returned
  60126. ** TRUE from sqlite3BtreeCursorHasMoved().
  60127. */
  60128. SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){
  60129. int rc;
  60130. assert( pCur!=0 );
  60131. assert( pCur->eState!=CURSOR_VALID );
  60132. rc = restoreCursorPosition(pCur);
  60133. if( rc ){
  60134. *pDifferentRow = 1;
  60135. return rc;
  60136. }
  60137. if( pCur->eState!=CURSOR_VALID ){
  60138. *pDifferentRow = 1;
  60139. }else{
  60140. *pDifferentRow = 0;
  60141. }
  60142. return SQLITE_OK;
  60143. }
  60144. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  60145. /*
  60146. ** Provide hints to the cursor. The particular hint given (and the type
  60147. ** and number of the varargs parameters) is determined by the eHintType
  60148. ** parameter. See the definitions of the BTREE_HINT_* macros for details.
  60149. */
  60150. SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor *pCur, int eHintType, ...){
  60151. /* Used only by system that substitute their own storage engine */
  60152. }
  60153. #endif
  60154. /*
  60155. ** Provide flag hints to the cursor.
  60156. */
  60157. SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor *pCur, unsigned x){
  60158. assert( x==BTREE_SEEK_EQ || x==BTREE_BULKLOAD || x==0 );
  60159. pCur->hints = x;
  60160. }
  60161. #ifndef SQLITE_OMIT_AUTOVACUUM
  60162. /*
  60163. ** Given a page number of a regular database page, return the page
  60164. ** number for the pointer-map page that contains the entry for the
  60165. ** input page number.
  60166. **
  60167. ** Return 0 (not a valid page) for pgno==1 since there is
  60168. ** no pointer map associated with page 1. The integrity_check logic
  60169. ** requires that ptrmapPageno(*,1)!=1.
  60170. */
  60171. static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
  60172. int nPagesPerMapPage;
  60173. Pgno iPtrMap, ret;
  60174. assert( sqlite3_mutex_held(pBt->mutex) );
  60175. if( pgno<2 ) return 0;
  60176. nPagesPerMapPage = (pBt->usableSize/5)+1;
  60177. iPtrMap = (pgno-2)/nPagesPerMapPage;
  60178. ret = (iPtrMap*nPagesPerMapPage) + 2;
  60179. if( ret==PENDING_BYTE_PAGE(pBt) ){
  60180. ret++;
  60181. }
  60182. return ret;
  60183. }
  60184. /*
  60185. ** Write an entry into the pointer map.
  60186. **
  60187. ** This routine updates the pointer map entry for page number 'key'
  60188. ** so that it maps to type 'eType' and parent page number 'pgno'.
  60189. **
  60190. ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
  60191. ** a no-op. If an error occurs, the appropriate error code is written
  60192. ** into *pRC.
  60193. */
  60194. static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
  60195. DbPage *pDbPage; /* The pointer map page */
  60196. u8 *pPtrmap; /* The pointer map data */
  60197. Pgno iPtrmap; /* The pointer map page number */
  60198. int offset; /* Offset in pointer map page */
  60199. int rc; /* Return code from subfunctions */
  60200. if( *pRC ) return;
  60201. assert( sqlite3_mutex_held(pBt->mutex) );
  60202. /* The master-journal page number must never be used as a pointer map page */
  60203. assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
  60204. assert( pBt->autoVacuum );
  60205. if( key==0 ){
  60206. *pRC = SQLITE_CORRUPT_BKPT;
  60207. return;
  60208. }
  60209. iPtrmap = PTRMAP_PAGENO(pBt, key);
  60210. rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
  60211. if( rc!=SQLITE_OK ){
  60212. *pRC = rc;
  60213. return;
  60214. }
  60215. if( ((char*)sqlite3PagerGetExtra(pDbPage))[0]!=0 ){
  60216. /* The first byte of the extra data is the MemPage.isInit byte.
  60217. ** If that byte is set, it means this page is also being used
  60218. ** as a btree page. */
  60219. *pRC = SQLITE_CORRUPT_BKPT;
  60220. goto ptrmap_exit;
  60221. }
  60222. offset = PTRMAP_PTROFFSET(iPtrmap, key);
  60223. if( offset<0 ){
  60224. *pRC = SQLITE_CORRUPT_BKPT;
  60225. goto ptrmap_exit;
  60226. }
  60227. assert( offset <= (int)pBt->usableSize-5 );
  60228. pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
  60229. if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
  60230. TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
  60231. *pRC= rc = sqlite3PagerWrite(pDbPage);
  60232. if( rc==SQLITE_OK ){
  60233. pPtrmap[offset] = eType;
  60234. put4byte(&pPtrmap[offset+1], parent);
  60235. }
  60236. }
  60237. ptrmap_exit:
  60238. sqlite3PagerUnref(pDbPage);
  60239. }
  60240. /*
  60241. ** Read an entry from the pointer map.
  60242. **
  60243. ** This routine retrieves the pointer map entry for page 'key', writing
  60244. ** the type and parent page number to *pEType and *pPgno respectively.
  60245. ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
  60246. */
  60247. static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
  60248. DbPage *pDbPage; /* The pointer map page */
  60249. int iPtrmap; /* Pointer map page index */
  60250. u8 *pPtrmap; /* Pointer map page data */
  60251. int offset; /* Offset of entry in pointer map */
  60252. int rc;
  60253. assert( sqlite3_mutex_held(pBt->mutex) );
  60254. iPtrmap = PTRMAP_PAGENO(pBt, key);
  60255. rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
  60256. if( rc!=0 ){
  60257. return rc;
  60258. }
  60259. pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
  60260. offset = PTRMAP_PTROFFSET(iPtrmap, key);
  60261. if( offset<0 ){
  60262. sqlite3PagerUnref(pDbPage);
  60263. return SQLITE_CORRUPT_BKPT;
  60264. }
  60265. assert( offset <= (int)pBt->usableSize-5 );
  60266. assert( pEType!=0 );
  60267. *pEType = pPtrmap[offset];
  60268. if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
  60269. sqlite3PagerUnref(pDbPage);
  60270. if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_PGNO(iPtrmap);
  60271. return SQLITE_OK;
  60272. }
  60273. #else /* if defined SQLITE_OMIT_AUTOVACUUM */
  60274. #define ptrmapPut(w,x,y,z,rc)
  60275. #define ptrmapGet(w,x,y,z) SQLITE_OK
  60276. #define ptrmapPutOvflPtr(x, y, z, rc)
  60277. #endif
  60278. /*
  60279. ** Given a btree page and a cell index (0 means the first cell on
  60280. ** the page, 1 means the second cell, and so forth) return a pointer
  60281. ** to the cell content.
  60282. **
  60283. ** findCellPastPtr() does the same except it skips past the initial
  60284. ** 4-byte child pointer found on interior pages, if there is one.
  60285. **
  60286. ** This routine works only for pages that do not contain overflow cells.
  60287. */
  60288. #define findCell(P,I) \
  60289. ((P)->aData + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
  60290. #define findCellPastPtr(P,I) \
  60291. ((P)->aDataOfst + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
  60292. /*
  60293. ** This is common tail processing for btreeParseCellPtr() and
  60294. ** btreeParseCellPtrIndex() for the case when the cell does not fit entirely
  60295. ** on a single B-tree page. Make necessary adjustments to the CellInfo
  60296. ** structure.
  60297. */
  60298. static SQLITE_NOINLINE void btreeParseCellAdjustSizeForOverflow(
  60299. MemPage *pPage, /* Page containing the cell */
  60300. u8 *pCell, /* Pointer to the cell text. */
  60301. CellInfo *pInfo /* Fill in this structure */
  60302. ){
  60303. /* If the payload will not fit completely on the local page, we have
  60304. ** to decide how much to store locally and how much to spill onto
  60305. ** overflow pages. The strategy is to minimize the amount of unused
  60306. ** space on overflow pages while keeping the amount of local storage
  60307. ** in between minLocal and maxLocal.
  60308. **
  60309. ** Warning: changing the way overflow payload is distributed in any
  60310. ** way will result in an incompatible file format.
  60311. */
  60312. int minLocal; /* Minimum amount of payload held locally */
  60313. int maxLocal; /* Maximum amount of payload held locally */
  60314. int surplus; /* Overflow payload available for local storage */
  60315. minLocal = pPage->minLocal;
  60316. maxLocal = pPage->maxLocal;
  60317. surplus = minLocal + (pInfo->nPayload - minLocal)%(pPage->pBt->usableSize-4);
  60318. testcase( surplus==maxLocal );
  60319. testcase( surplus==maxLocal+1 );
  60320. if( surplus <= maxLocal ){
  60321. pInfo->nLocal = (u16)surplus;
  60322. }else{
  60323. pInfo->nLocal = (u16)minLocal;
  60324. }
  60325. pInfo->nSize = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell) + 4;
  60326. }
  60327. /*
  60328. ** The following routines are implementations of the MemPage.xParseCell()
  60329. ** method.
  60330. **
  60331. ** Parse a cell content block and fill in the CellInfo structure.
  60332. **
  60333. ** btreeParseCellPtr() => table btree leaf nodes
  60334. ** btreeParseCellNoPayload() => table btree internal nodes
  60335. ** btreeParseCellPtrIndex() => index btree nodes
  60336. **
  60337. ** There is also a wrapper function btreeParseCell() that works for
  60338. ** all MemPage types and that references the cell by index rather than
  60339. ** by pointer.
  60340. */
  60341. static void btreeParseCellPtrNoPayload(
  60342. MemPage *pPage, /* Page containing the cell */
  60343. u8 *pCell, /* Pointer to the cell text. */
  60344. CellInfo *pInfo /* Fill in this structure */
  60345. ){
  60346. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  60347. assert( pPage->leaf==0 );
  60348. assert( pPage->childPtrSize==4 );
  60349. #ifndef SQLITE_DEBUG
  60350. UNUSED_PARAMETER(pPage);
  60351. #endif
  60352. pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey);
  60353. pInfo->nPayload = 0;
  60354. pInfo->nLocal = 0;
  60355. pInfo->pPayload = 0;
  60356. return;
  60357. }
  60358. static void btreeParseCellPtr(
  60359. MemPage *pPage, /* Page containing the cell */
  60360. u8 *pCell, /* Pointer to the cell text. */
  60361. CellInfo *pInfo /* Fill in this structure */
  60362. ){
  60363. u8 *pIter; /* For scanning through pCell */
  60364. u32 nPayload; /* Number of bytes of cell payload */
  60365. u64 iKey; /* Extracted Key value */
  60366. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  60367. assert( pPage->leaf==0 || pPage->leaf==1 );
  60368. assert( pPage->intKeyLeaf );
  60369. assert( pPage->childPtrSize==0 );
  60370. pIter = pCell;
  60371. /* The next block of code is equivalent to:
  60372. **
  60373. ** pIter += getVarint32(pIter, nPayload);
  60374. **
  60375. ** The code is inlined to avoid a function call.
  60376. */
  60377. nPayload = *pIter;
  60378. if( nPayload>=0x80 ){
  60379. u8 *pEnd = &pIter[8];
  60380. nPayload &= 0x7f;
  60381. do{
  60382. nPayload = (nPayload<<7) | (*++pIter & 0x7f);
  60383. }while( (*pIter)>=0x80 && pIter<pEnd );
  60384. }
  60385. pIter++;
  60386. /* The next block of code is equivalent to:
  60387. **
  60388. ** pIter += getVarint(pIter, (u64*)&pInfo->nKey);
  60389. **
  60390. ** The code is inlined to avoid a function call.
  60391. */
  60392. iKey = *pIter;
  60393. if( iKey>=0x80 ){
  60394. u8 *pEnd = &pIter[7];
  60395. iKey &= 0x7f;
  60396. while(1){
  60397. iKey = (iKey<<7) | (*++pIter & 0x7f);
  60398. if( (*pIter)<0x80 ) break;
  60399. if( pIter>=pEnd ){
  60400. iKey = (iKey<<8) | *++pIter;
  60401. break;
  60402. }
  60403. }
  60404. }
  60405. pIter++;
  60406. pInfo->nKey = *(i64*)&iKey;
  60407. pInfo->nPayload = nPayload;
  60408. pInfo->pPayload = pIter;
  60409. testcase( nPayload==pPage->maxLocal );
  60410. testcase( nPayload==pPage->maxLocal+1 );
  60411. if( nPayload<=pPage->maxLocal ){
  60412. /* This is the (easy) common case where the entire payload fits
  60413. ** on the local page. No overflow is required.
  60414. */
  60415. pInfo->nSize = nPayload + (u16)(pIter - pCell);
  60416. if( pInfo->nSize<4 ) pInfo->nSize = 4;
  60417. pInfo->nLocal = (u16)nPayload;
  60418. }else{
  60419. btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
  60420. }
  60421. }
  60422. static void btreeParseCellPtrIndex(
  60423. MemPage *pPage, /* Page containing the cell */
  60424. u8 *pCell, /* Pointer to the cell text. */
  60425. CellInfo *pInfo /* Fill in this structure */
  60426. ){
  60427. u8 *pIter; /* For scanning through pCell */
  60428. u32 nPayload; /* Number of bytes of cell payload */
  60429. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  60430. assert( pPage->leaf==0 || pPage->leaf==1 );
  60431. assert( pPage->intKeyLeaf==0 );
  60432. pIter = pCell + pPage->childPtrSize;
  60433. nPayload = *pIter;
  60434. if( nPayload>=0x80 ){
  60435. u8 *pEnd = &pIter[8];
  60436. nPayload &= 0x7f;
  60437. do{
  60438. nPayload = (nPayload<<7) | (*++pIter & 0x7f);
  60439. }while( *(pIter)>=0x80 && pIter<pEnd );
  60440. }
  60441. pIter++;
  60442. pInfo->nKey = nPayload;
  60443. pInfo->nPayload = nPayload;
  60444. pInfo->pPayload = pIter;
  60445. testcase( nPayload==pPage->maxLocal );
  60446. testcase( nPayload==pPage->maxLocal+1 );
  60447. if( nPayload<=pPage->maxLocal ){
  60448. /* This is the (easy) common case where the entire payload fits
  60449. ** on the local page. No overflow is required.
  60450. */
  60451. pInfo->nSize = nPayload + (u16)(pIter - pCell);
  60452. if( pInfo->nSize<4 ) pInfo->nSize = 4;
  60453. pInfo->nLocal = (u16)nPayload;
  60454. }else{
  60455. btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
  60456. }
  60457. }
  60458. static void btreeParseCell(
  60459. MemPage *pPage, /* Page containing the cell */
  60460. int iCell, /* The cell index. First cell is 0 */
  60461. CellInfo *pInfo /* Fill in this structure */
  60462. ){
  60463. pPage->xParseCell(pPage, findCell(pPage, iCell), pInfo);
  60464. }
  60465. /*
  60466. ** The following routines are implementations of the MemPage.xCellSize
  60467. ** method.
  60468. **
  60469. ** Compute the total number of bytes that a Cell needs in the cell
  60470. ** data area of the btree-page. The return number includes the cell
  60471. ** data header and the local payload, but not any overflow page or
  60472. ** the space used by the cell pointer.
  60473. **
  60474. ** cellSizePtrNoPayload() => table internal nodes
  60475. ** cellSizePtr() => all index nodes & table leaf nodes
  60476. */
  60477. static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
  60478. u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */
  60479. u8 *pEnd; /* End mark for a varint */
  60480. u32 nSize; /* Size value to return */
  60481. #ifdef SQLITE_DEBUG
  60482. /* The value returned by this function should always be the same as
  60483. ** the (CellInfo.nSize) value found by doing a full parse of the
  60484. ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
  60485. ** this function verifies that this invariant is not violated. */
  60486. CellInfo debuginfo;
  60487. pPage->xParseCell(pPage, pCell, &debuginfo);
  60488. #endif
  60489. nSize = *pIter;
  60490. if( nSize>=0x80 ){
  60491. pEnd = &pIter[8];
  60492. nSize &= 0x7f;
  60493. do{
  60494. nSize = (nSize<<7) | (*++pIter & 0x7f);
  60495. }while( *(pIter)>=0x80 && pIter<pEnd );
  60496. }
  60497. pIter++;
  60498. if( pPage->intKey ){
  60499. /* pIter now points at the 64-bit integer key value, a variable length
  60500. ** integer. The following block moves pIter to point at the first byte
  60501. ** past the end of the key value. */
  60502. pEnd = &pIter[9];
  60503. while( (*pIter++)&0x80 && pIter<pEnd );
  60504. }
  60505. testcase( nSize==pPage->maxLocal );
  60506. testcase( nSize==pPage->maxLocal+1 );
  60507. if( nSize<=pPage->maxLocal ){
  60508. nSize += (u32)(pIter - pCell);
  60509. if( nSize<4 ) nSize = 4;
  60510. }else{
  60511. int minLocal = pPage->minLocal;
  60512. nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
  60513. testcase( nSize==pPage->maxLocal );
  60514. testcase( nSize==pPage->maxLocal+1 );
  60515. if( nSize>pPage->maxLocal ){
  60516. nSize = minLocal;
  60517. }
  60518. nSize += 4 + (u16)(pIter - pCell);
  60519. }
  60520. assert( nSize==debuginfo.nSize || CORRUPT_DB );
  60521. return (u16)nSize;
  60522. }
  60523. static u16 cellSizePtrNoPayload(MemPage *pPage, u8 *pCell){
  60524. u8 *pIter = pCell + 4; /* For looping over bytes of pCell */
  60525. u8 *pEnd; /* End mark for a varint */
  60526. #ifdef SQLITE_DEBUG
  60527. /* The value returned by this function should always be the same as
  60528. ** the (CellInfo.nSize) value found by doing a full parse of the
  60529. ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
  60530. ** this function verifies that this invariant is not violated. */
  60531. CellInfo debuginfo;
  60532. pPage->xParseCell(pPage, pCell, &debuginfo);
  60533. #else
  60534. UNUSED_PARAMETER(pPage);
  60535. #endif
  60536. assert( pPage->childPtrSize==4 );
  60537. pEnd = pIter + 9;
  60538. while( (*pIter++)&0x80 && pIter<pEnd );
  60539. assert( debuginfo.nSize==(u16)(pIter - pCell) || CORRUPT_DB );
  60540. return (u16)(pIter - pCell);
  60541. }
  60542. #ifdef SQLITE_DEBUG
  60543. /* This variation on cellSizePtr() is used inside of assert() statements
  60544. ** only. */
  60545. static u16 cellSize(MemPage *pPage, int iCell){
  60546. return pPage->xCellSize(pPage, findCell(pPage, iCell));
  60547. }
  60548. #endif
  60549. #ifndef SQLITE_OMIT_AUTOVACUUM
  60550. /*
  60551. ** The cell pCell is currently part of page pSrc but will ultimately be part
  60552. ** of pPage. (pSrc and pPager are often the same.) If pCell contains a
  60553. ** pointer to an overflow page, insert an entry into the pointer-map for
  60554. ** the overflow page that will be valid after pCell has been moved to pPage.
  60555. */
  60556. static void ptrmapPutOvflPtr(MemPage *pPage, MemPage *pSrc, u8 *pCell,int *pRC){
  60557. CellInfo info;
  60558. if( *pRC ) return;
  60559. assert( pCell!=0 );
  60560. pPage->xParseCell(pPage, pCell, &info);
  60561. if( info.nLocal<info.nPayload ){
  60562. Pgno ovfl;
  60563. if( SQLITE_WITHIN(pSrc->aDataEnd, pCell, pCell+info.nLocal) ){
  60564. testcase( pSrc!=pPage );
  60565. *pRC = SQLITE_CORRUPT_BKPT;
  60566. return;
  60567. }
  60568. ovfl = get4byte(&pCell[info.nSize-4]);
  60569. ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
  60570. }
  60571. }
  60572. #endif
  60573. /*
  60574. ** Defragment the page given. This routine reorganizes cells within the
  60575. ** page so that there are no free-blocks on the free-block list.
  60576. **
  60577. ** Parameter nMaxFrag is the maximum amount of fragmented space that may be
  60578. ** present in the page after this routine returns.
  60579. **
  60580. ** EVIDENCE-OF: R-44582-60138 SQLite may from time to time reorganize a
  60581. ** b-tree page so that there are no freeblocks or fragment bytes, all
  60582. ** unused bytes are contained in the unallocated space region, and all
  60583. ** cells are packed tightly at the end of the page.
  60584. */
  60585. static int defragmentPage(MemPage *pPage, int nMaxFrag){
  60586. int i; /* Loop counter */
  60587. int pc; /* Address of the i-th cell */
  60588. int hdr; /* Offset to the page header */
  60589. int size; /* Size of a cell */
  60590. int usableSize; /* Number of usable bytes on a page */
  60591. int cellOffset; /* Offset to the cell pointer array */
  60592. int cbrk; /* Offset to the cell content area */
  60593. int nCell; /* Number of cells on the page */
  60594. unsigned char *data; /* The page data */
  60595. unsigned char *temp; /* Temp area for cell content */
  60596. unsigned char *src; /* Source of content */
  60597. int iCellFirst; /* First allowable cell index */
  60598. int iCellLast; /* Last possible cell index */
  60599. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  60600. assert( pPage->pBt!=0 );
  60601. assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
  60602. assert( pPage->nOverflow==0 );
  60603. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  60604. temp = 0;
  60605. src = data = pPage->aData;
  60606. hdr = pPage->hdrOffset;
  60607. cellOffset = pPage->cellOffset;
  60608. nCell = pPage->nCell;
  60609. assert( nCell==get2byte(&data[hdr+3]) || CORRUPT_DB );
  60610. iCellFirst = cellOffset + 2*nCell;
  60611. usableSize = pPage->pBt->usableSize;
  60612. /* This block handles pages with two or fewer free blocks and nMaxFrag
  60613. ** or fewer fragmented bytes. In this case it is faster to move the
  60614. ** two (or one) blocks of cells using memmove() and add the required
  60615. ** offsets to each pointer in the cell-pointer array than it is to
  60616. ** reconstruct the entire page. */
  60617. if( (int)data[hdr+7]<=nMaxFrag ){
  60618. int iFree = get2byte(&data[hdr+1]);
  60619. if( iFree>usableSize-4 ) return SQLITE_CORRUPT_PAGE(pPage);
  60620. if( iFree ){
  60621. int iFree2 = get2byte(&data[iFree]);
  60622. if( iFree2>usableSize-4 ) return SQLITE_CORRUPT_PAGE(pPage);
  60623. if( 0==iFree2 || (data[iFree2]==0 && data[iFree2+1]==0) ){
  60624. u8 *pEnd = &data[cellOffset + nCell*2];
  60625. u8 *pAddr;
  60626. int sz2 = 0;
  60627. int sz = get2byte(&data[iFree+2]);
  60628. int top = get2byte(&data[hdr+5]);
  60629. if( top>=iFree ){
  60630. return SQLITE_CORRUPT_PAGE(pPage);
  60631. }
  60632. if( iFree2 ){
  60633. if( iFree+sz>iFree2 ) return SQLITE_CORRUPT_PAGE(pPage);
  60634. sz2 = get2byte(&data[iFree2+2]);
  60635. if( iFree2+sz2 > usableSize ) return SQLITE_CORRUPT_PAGE(pPage);
  60636. memmove(&data[iFree+sz+sz2], &data[iFree+sz], iFree2-(iFree+sz));
  60637. sz += sz2;
  60638. }else if( iFree+sz>usableSize ){
  60639. return SQLITE_CORRUPT_PAGE(pPage);
  60640. }
  60641. cbrk = top+sz;
  60642. assert( cbrk+(iFree-top) <= usableSize );
  60643. memmove(&data[cbrk], &data[top], iFree-top);
  60644. for(pAddr=&data[cellOffset]; pAddr<pEnd; pAddr+=2){
  60645. pc = get2byte(pAddr);
  60646. if( pc<iFree ){ put2byte(pAddr, pc+sz); }
  60647. else if( pc<iFree2 ){ put2byte(pAddr, pc+sz2); }
  60648. }
  60649. goto defragment_out;
  60650. }
  60651. }
  60652. }
  60653. cbrk = usableSize;
  60654. iCellLast = usableSize - 4;
  60655. for(i=0; i<nCell; i++){
  60656. u8 *pAddr; /* The i-th cell pointer */
  60657. pAddr = &data[cellOffset + i*2];
  60658. pc = get2byte(pAddr);
  60659. testcase( pc==iCellFirst );
  60660. testcase( pc==iCellLast );
  60661. /* These conditions have already been verified in btreeInitPage()
  60662. ** if PRAGMA cell_size_check=ON.
  60663. */
  60664. if( pc<iCellFirst || pc>iCellLast ){
  60665. return SQLITE_CORRUPT_PAGE(pPage);
  60666. }
  60667. assert( pc>=iCellFirst && pc<=iCellLast );
  60668. size = pPage->xCellSize(pPage, &src[pc]);
  60669. cbrk -= size;
  60670. if( cbrk<iCellFirst || pc+size>usableSize ){
  60671. return SQLITE_CORRUPT_PAGE(pPage);
  60672. }
  60673. assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
  60674. testcase( cbrk+size==usableSize );
  60675. testcase( pc+size==usableSize );
  60676. put2byte(pAddr, cbrk);
  60677. if( temp==0 ){
  60678. int x;
  60679. if( cbrk==pc ) continue;
  60680. temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
  60681. x = get2byte(&data[hdr+5]);
  60682. memcpy(&temp[x], &data[x], (cbrk+size) - x);
  60683. src = temp;
  60684. }
  60685. memcpy(&data[cbrk], &src[pc], size);
  60686. }
  60687. data[hdr+7] = 0;
  60688. defragment_out:
  60689. assert( pPage->nFree>=0 );
  60690. if( data[hdr+7]+cbrk-iCellFirst!=pPage->nFree ){
  60691. return SQLITE_CORRUPT_PAGE(pPage);
  60692. }
  60693. assert( cbrk>=iCellFirst );
  60694. put2byte(&data[hdr+5], cbrk);
  60695. data[hdr+1] = 0;
  60696. data[hdr+2] = 0;
  60697. memset(&data[iCellFirst], 0, cbrk-iCellFirst);
  60698. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  60699. return SQLITE_OK;
  60700. }
  60701. /*
  60702. ** Search the free-list on page pPg for space to store a cell nByte bytes in
  60703. ** size. If one can be found, return a pointer to the space and remove it
  60704. ** from the free-list.
  60705. **
  60706. ** If no suitable space can be found on the free-list, return NULL.
  60707. **
  60708. ** This function may detect corruption within pPg. If corruption is
  60709. ** detected then *pRc is set to SQLITE_CORRUPT and NULL is returned.
  60710. **
  60711. ** Slots on the free list that are between 1 and 3 bytes larger than nByte
  60712. ** will be ignored if adding the extra space to the fragmentation count
  60713. ** causes the fragmentation count to exceed 60.
  60714. */
  60715. static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc){
  60716. const int hdr = pPg->hdrOffset; /* Offset to page header */
  60717. u8 * const aData = pPg->aData; /* Page data */
  60718. int iAddr = hdr + 1; /* Address of ptr to pc */
  60719. int pc = get2byte(&aData[iAddr]); /* Address of a free slot */
  60720. int x; /* Excess size of the slot */
  60721. int maxPC = pPg->pBt->usableSize - nByte; /* Max address for a usable slot */
  60722. int size; /* Size of the free slot */
  60723. assert( pc>0 );
  60724. while( pc<=maxPC ){
  60725. /* EVIDENCE-OF: R-22710-53328 The third and fourth bytes of each
  60726. ** freeblock form a big-endian integer which is the size of the freeblock
  60727. ** in bytes, including the 4-byte header. */
  60728. size = get2byte(&aData[pc+2]);
  60729. if( (x = size - nByte)>=0 ){
  60730. testcase( x==4 );
  60731. testcase( x==3 );
  60732. if( x<4 ){
  60733. /* EVIDENCE-OF: R-11498-58022 In a well-formed b-tree page, the total
  60734. ** number of bytes in fragments may not exceed 60. */
  60735. if( aData[hdr+7]>57 ) return 0;
  60736. /* Remove the slot from the free-list. Update the number of
  60737. ** fragmented bytes within the page. */
  60738. memcpy(&aData[iAddr], &aData[pc], 2);
  60739. aData[hdr+7] += (u8)x;
  60740. }else if( x+pc > maxPC ){
  60741. /* This slot extends off the end of the usable part of the page */
  60742. *pRc = SQLITE_CORRUPT_PAGE(pPg);
  60743. return 0;
  60744. }else{
  60745. /* The slot remains on the free-list. Reduce its size to account
  60746. ** for the portion used by the new allocation. */
  60747. put2byte(&aData[pc+2], x);
  60748. }
  60749. return &aData[pc + x];
  60750. }
  60751. iAddr = pc;
  60752. pc = get2byte(&aData[pc]);
  60753. if( pc<=iAddr+size ){
  60754. if( pc ){
  60755. /* The next slot in the chain is not past the end of the current slot */
  60756. *pRc = SQLITE_CORRUPT_PAGE(pPg);
  60757. }
  60758. return 0;
  60759. }
  60760. }
  60761. if( pc>maxPC+nByte-4 ){
  60762. /* The free slot chain extends off the end of the page */
  60763. *pRc = SQLITE_CORRUPT_PAGE(pPg);
  60764. }
  60765. return 0;
  60766. }
  60767. /*
  60768. ** Allocate nByte bytes of space from within the B-Tree page passed
  60769. ** as the first argument. Write into *pIdx the index into pPage->aData[]
  60770. ** of the first byte of allocated space. Return either SQLITE_OK or
  60771. ** an error code (usually SQLITE_CORRUPT).
  60772. **
  60773. ** The caller guarantees that there is sufficient space to make the
  60774. ** allocation. This routine might need to defragment in order to bring
  60775. ** all the space together, however. This routine will avoid using
  60776. ** the first two bytes past the cell pointer area since presumably this
  60777. ** allocation is being made in order to insert a new cell, so we will
  60778. ** also end up needing a new cell pointer.
  60779. */
  60780. static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
  60781. const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */
  60782. u8 * const data = pPage->aData; /* Local cache of pPage->aData */
  60783. int top; /* First byte of cell content area */
  60784. int rc = SQLITE_OK; /* Integer return code */
  60785. int gap; /* First byte of gap between cell pointers and cell content */
  60786. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  60787. assert( pPage->pBt );
  60788. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  60789. assert( nByte>=0 ); /* Minimum cell size is 4 */
  60790. assert( pPage->nFree>=nByte );
  60791. assert( pPage->nOverflow==0 );
  60792. assert( nByte < (int)(pPage->pBt->usableSize-8) );
  60793. assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
  60794. gap = pPage->cellOffset + 2*pPage->nCell;
  60795. assert( gap<=65536 );
  60796. /* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size
  60797. ** and the reserved space is zero (the usual value for reserved space)
  60798. ** then the cell content offset of an empty page wants to be 65536.
  60799. ** However, that integer is too large to be stored in a 2-byte unsigned
  60800. ** integer, so a value of 0 is used in its place. */
  60801. top = get2byte(&data[hdr+5]);
  60802. assert( top<=(int)pPage->pBt->usableSize ); /* by btreeComputeFreeSpace() */
  60803. if( gap>top ){
  60804. if( top==0 && pPage->pBt->usableSize==65536 ){
  60805. top = 65536;
  60806. }else{
  60807. return SQLITE_CORRUPT_PAGE(pPage);
  60808. }
  60809. }
  60810. /* If there is enough space between gap and top for one more cell pointer,
  60811. ** and if the freelist is not empty, then search the
  60812. ** freelist looking for a slot big enough to satisfy the request.
  60813. */
  60814. testcase( gap+2==top );
  60815. testcase( gap+1==top );
  60816. testcase( gap==top );
  60817. if( (data[hdr+2] || data[hdr+1]) && gap+2<=top ){
  60818. u8 *pSpace = pageFindSlot(pPage, nByte, &rc);
  60819. if( pSpace ){
  60820. assert( pSpace>=data && (pSpace - data)<65536 );
  60821. *pIdx = (int)(pSpace - data);
  60822. return SQLITE_OK;
  60823. }else if( rc ){
  60824. return rc;
  60825. }
  60826. }
  60827. /* The request could not be fulfilled using a freelist slot. Check
  60828. ** to see if defragmentation is necessary.
  60829. */
  60830. testcase( gap+2+nByte==top );
  60831. if( gap+2+nByte>top ){
  60832. assert( pPage->nCell>0 || CORRUPT_DB );
  60833. assert( pPage->nFree>=0 );
  60834. rc = defragmentPage(pPage, MIN(4, pPage->nFree - (2+nByte)));
  60835. if( rc ) return rc;
  60836. top = get2byteNotZero(&data[hdr+5]);
  60837. assert( gap+2+nByte<=top );
  60838. }
  60839. /* Allocate memory from the gap in between the cell pointer array
  60840. ** and the cell content area. The btreeComputeFreeSpace() call has already
  60841. ** validated the freelist. Given that the freelist is valid, there
  60842. ** is no way that the allocation can extend off the end of the page.
  60843. ** The assert() below verifies the previous sentence.
  60844. */
  60845. top -= nByte;
  60846. put2byte(&data[hdr+5], top);
  60847. assert( top+nByte <= (int)pPage->pBt->usableSize );
  60848. *pIdx = top;
  60849. return SQLITE_OK;
  60850. }
  60851. /*
  60852. ** Return a section of the pPage->aData to the freelist.
  60853. ** The first byte of the new free block is pPage->aData[iStart]
  60854. ** and the size of the block is iSize bytes.
  60855. **
  60856. ** Adjacent freeblocks are coalesced.
  60857. **
  60858. ** Even though the freeblock list was checked by btreeComputeFreeSpace(),
  60859. ** that routine will not detect overlap between cells or freeblocks. Nor
  60860. ** does it detect cells or freeblocks that encrouch into the reserved bytes
  60861. ** at the end of the page. So do additional corruption checks inside this
  60862. ** routine and return SQLITE_CORRUPT if any problems are found.
  60863. */
  60864. static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){
  60865. u16 iPtr; /* Address of ptr to next freeblock */
  60866. u16 iFreeBlk; /* Address of the next freeblock */
  60867. u8 hdr; /* Page header size. 0 or 100 */
  60868. u8 nFrag = 0; /* Reduction in fragmentation */
  60869. u16 iOrigSize = iSize; /* Original value of iSize */
  60870. u16 x; /* Offset to cell content area */
  60871. u32 iEnd = iStart + iSize; /* First byte past the iStart buffer */
  60872. unsigned char *data = pPage->aData; /* Page content */
  60873. assert( pPage->pBt!=0 );
  60874. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  60875. assert( CORRUPT_DB || iStart>=pPage->hdrOffset+6+pPage->childPtrSize );
  60876. assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize );
  60877. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  60878. assert( iSize>=4 ); /* Minimum cell size is 4 */
  60879. assert( iStart<=pPage->pBt->usableSize-4 );
  60880. /* The list of freeblocks must be in ascending order. Find the
  60881. ** spot on the list where iStart should be inserted.
  60882. */
  60883. hdr = pPage->hdrOffset;
  60884. iPtr = hdr + 1;
  60885. if( data[iPtr+1]==0 && data[iPtr]==0 ){
  60886. iFreeBlk = 0; /* Shortcut for the case when the freelist is empty */
  60887. }else{
  60888. while( (iFreeBlk = get2byte(&data[iPtr]))<iStart ){
  60889. if( iFreeBlk<iPtr+4 ){
  60890. if( iFreeBlk==0 ) break;
  60891. return SQLITE_CORRUPT_PAGE(pPage);
  60892. }
  60893. iPtr = iFreeBlk;
  60894. }
  60895. if( iFreeBlk>pPage->pBt->usableSize-4 ){
  60896. return SQLITE_CORRUPT_PAGE(pPage);
  60897. }
  60898. assert( iFreeBlk>iPtr || iFreeBlk==0 );
  60899. /* At this point:
  60900. ** iFreeBlk: First freeblock after iStart, or zero if none
  60901. ** iPtr: The address of a pointer to iFreeBlk
  60902. **
  60903. ** Check to see if iFreeBlk should be coalesced onto the end of iStart.
  60904. */
  60905. if( iFreeBlk && iEnd+3>=iFreeBlk ){
  60906. nFrag = iFreeBlk - iEnd;
  60907. if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_PAGE(pPage);
  60908. iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]);
  60909. if( iEnd > pPage->pBt->usableSize ){
  60910. return SQLITE_CORRUPT_PAGE(pPage);
  60911. }
  60912. iSize = iEnd - iStart;
  60913. iFreeBlk = get2byte(&data[iFreeBlk]);
  60914. }
  60915. /* If iPtr is another freeblock (that is, if iPtr is not the freelist
  60916. ** pointer in the page header) then check to see if iStart should be
  60917. ** coalesced onto the end of iPtr.
  60918. */
  60919. if( iPtr>hdr+1 ){
  60920. int iPtrEnd = iPtr + get2byte(&data[iPtr+2]);
  60921. if( iPtrEnd+3>=iStart ){
  60922. if( iPtrEnd>iStart ) return SQLITE_CORRUPT_PAGE(pPage);
  60923. nFrag += iStart - iPtrEnd;
  60924. iSize = iEnd - iPtr;
  60925. iStart = iPtr;
  60926. }
  60927. }
  60928. if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_PAGE(pPage);
  60929. data[hdr+7] -= nFrag;
  60930. }
  60931. x = get2byte(&data[hdr+5]);
  60932. if( iStart<=x ){
  60933. /* The new freeblock is at the beginning of the cell content area,
  60934. ** so just extend the cell content area rather than create another
  60935. ** freelist entry */
  60936. if( iStart<x || iPtr!=hdr+1 ) return SQLITE_CORRUPT_PAGE(pPage);
  60937. put2byte(&data[hdr+1], iFreeBlk);
  60938. put2byte(&data[hdr+5], iEnd);
  60939. }else{
  60940. /* Insert the new freeblock into the freelist */
  60941. put2byte(&data[iPtr], iStart);
  60942. }
  60943. if( pPage->pBt->btsFlags & BTS_FAST_SECURE ){
  60944. /* Overwrite deleted information with zeros when the secure_delete
  60945. ** option is enabled */
  60946. memset(&data[iStart], 0, iSize);
  60947. }
  60948. put2byte(&data[iStart], iFreeBlk);
  60949. put2byte(&data[iStart+2], iSize);
  60950. pPage->nFree += iOrigSize;
  60951. return SQLITE_OK;
  60952. }
  60953. /*
  60954. ** Decode the flags byte (the first byte of the header) for a page
  60955. ** and initialize fields of the MemPage structure accordingly.
  60956. **
  60957. ** Only the following combinations are supported. Anything different
  60958. ** indicates a corrupt database files:
  60959. **
  60960. ** PTF_ZERODATA
  60961. ** PTF_ZERODATA | PTF_LEAF
  60962. ** PTF_LEAFDATA | PTF_INTKEY
  60963. ** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
  60964. */
  60965. static int decodeFlags(MemPage *pPage, int flagByte){
  60966. BtShared *pBt; /* A copy of pPage->pBt */
  60967. assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
  60968. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  60969. pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 );
  60970. flagByte &= ~PTF_LEAF;
  60971. pPage->childPtrSize = 4-4*pPage->leaf;
  60972. pPage->xCellSize = cellSizePtr;
  60973. pBt = pPage->pBt;
  60974. if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
  60975. /* EVIDENCE-OF: R-07291-35328 A value of 5 (0x05) means the page is an
  60976. ** interior table b-tree page. */
  60977. assert( (PTF_LEAFDATA|PTF_INTKEY)==5 );
  60978. /* EVIDENCE-OF: R-26900-09176 A value of 13 (0x0d) means the page is a
  60979. ** leaf table b-tree page. */
  60980. assert( (PTF_LEAFDATA|PTF_INTKEY|PTF_LEAF)==13 );
  60981. pPage->intKey = 1;
  60982. if( pPage->leaf ){
  60983. pPage->intKeyLeaf = 1;
  60984. pPage->xParseCell = btreeParseCellPtr;
  60985. }else{
  60986. pPage->intKeyLeaf = 0;
  60987. pPage->xCellSize = cellSizePtrNoPayload;
  60988. pPage->xParseCell = btreeParseCellPtrNoPayload;
  60989. }
  60990. pPage->maxLocal = pBt->maxLeaf;
  60991. pPage->minLocal = pBt->minLeaf;
  60992. }else if( flagByte==PTF_ZERODATA ){
  60993. /* EVIDENCE-OF: R-43316-37308 A value of 2 (0x02) means the page is an
  60994. ** interior index b-tree page. */
  60995. assert( (PTF_ZERODATA)==2 );
  60996. /* EVIDENCE-OF: R-59615-42828 A value of 10 (0x0a) means the page is a
  60997. ** leaf index b-tree page. */
  60998. assert( (PTF_ZERODATA|PTF_LEAF)==10 );
  60999. pPage->intKey = 0;
  61000. pPage->intKeyLeaf = 0;
  61001. pPage->xParseCell = btreeParseCellPtrIndex;
  61002. pPage->maxLocal = pBt->maxLocal;
  61003. pPage->minLocal = pBt->minLocal;
  61004. }else{
  61005. /* EVIDENCE-OF: R-47608-56469 Any other value for the b-tree page type is
  61006. ** an error. */
  61007. return SQLITE_CORRUPT_PAGE(pPage);
  61008. }
  61009. pPage->max1bytePayload = pBt->max1bytePayload;
  61010. return SQLITE_OK;
  61011. }
  61012. /*
  61013. ** Compute the amount of freespace on the page. In other words, fill
  61014. ** in the pPage->nFree field.
  61015. */
  61016. static int btreeComputeFreeSpace(MemPage *pPage){
  61017. int pc; /* Address of a freeblock within pPage->aData[] */
  61018. u8 hdr; /* Offset to beginning of page header */
  61019. u8 *data; /* Equal to pPage->aData */
  61020. int usableSize; /* Amount of usable space on each page */
  61021. int nFree; /* Number of unused bytes on the page */
  61022. int top; /* First byte of the cell content area */
  61023. int iCellFirst; /* First allowable cell or freeblock offset */
  61024. int iCellLast; /* Last possible cell or freeblock offset */
  61025. assert( pPage->pBt!=0 );
  61026. assert( pPage->pBt->db!=0 );
  61027. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  61028. assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
  61029. assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
  61030. assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
  61031. assert( pPage->isInit==1 );
  61032. assert( pPage->nFree<0 );
  61033. usableSize = pPage->pBt->usableSize;
  61034. hdr = pPage->hdrOffset;
  61035. data = pPage->aData;
  61036. /* EVIDENCE-OF: R-58015-48175 The two-byte integer at offset 5 designates
  61037. ** the start of the cell content area. A zero value for this integer is
  61038. ** interpreted as 65536. */
  61039. top = get2byteNotZero(&data[hdr+5]);
  61040. iCellFirst = hdr + 8 + pPage->childPtrSize + 2*pPage->nCell;
  61041. iCellLast = usableSize - 4;
  61042. /* Compute the total free space on the page
  61043. ** EVIDENCE-OF: R-23588-34450 The two-byte integer at offset 1 gives the
  61044. ** start of the first freeblock on the page, or is zero if there are no
  61045. ** freeblocks. */
  61046. pc = get2byte(&data[hdr+1]);
  61047. nFree = data[hdr+7] + top; /* Init nFree to non-freeblock free space */
  61048. if( pc>0 ){
  61049. u32 next, size;
  61050. if( pc<iCellFirst ){
  61051. /* EVIDENCE-OF: R-55530-52930 In a well-formed b-tree page, there will
  61052. ** always be at least one cell before the first freeblock.
  61053. */
  61054. return SQLITE_CORRUPT_PAGE(pPage);
  61055. }
  61056. while( 1 ){
  61057. if( pc>iCellLast ){
  61058. /* Freeblock off the end of the page */
  61059. return SQLITE_CORRUPT_PAGE(pPage);
  61060. }
  61061. next = get2byte(&data[pc]);
  61062. size = get2byte(&data[pc+2]);
  61063. nFree = nFree + size;
  61064. if( next<=pc+size+3 ) break;
  61065. pc = next;
  61066. }
  61067. if( next>0 ){
  61068. /* Freeblock not in ascending order */
  61069. return SQLITE_CORRUPT_PAGE(pPage);
  61070. }
  61071. if( pc+size>(unsigned int)usableSize ){
  61072. /* Last freeblock extends past page end */
  61073. return SQLITE_CORRUPT_PAGE(pPage);
  61074. }
  61075. }
  61076. /* At this point, nFree contains the sum of the offset to the start
  61077. ** of the cell-content area plus the number of free bytes within
  61078. ** the cell-content area. If this is greater than the usable-size
  61079. ** of the page, then the page must be corrupted. This check also
  61080. ** serves to verify that the offset to the start of the cell-content
  61081. ** area, according to the page header, lies within the page.
  61082. */
  61083. if( nFree>usableSize || nFree<iCellFirst ){
  61084. return SQLITE_CORRUPT_PAGE(pPage);
  61085. }
  61086. pPage->nFree = (u16)(nFree - iCellFirst);
  61087. return SQLITE_OK;
  61088. }
  61089. /*
  61090. ** Do additional sanity check after btreeInitPage() if
  61091. ** PRAGMA cell_size_check=ON
  61092. */
  61093. static SQLITE_NOINLINE int btreeCellSizeCheck(MemPage *pPage){
  61094. int iCellFirst; /* First allowable cell or freeblock offset */
  61095. int iCellLast; /* Last possible cell or freeblock offset */
  61096. int i; /* Index into the cell pointer array */
  61097. int sz; /* Size of a cell */
  61098. int pc; /* Address of a freeblock within pPage->aData[] */
  61099. u8 *data; /* Equal to pPage->aData */
  61100. int usableSize; /* Maximum usable space on the page */
  61101. int cellOffset; /* Start of cell content area */
  61102. iCellFirst = pPage->cellOffset + 2*pPage->nCell;
  61103. usableSize = pPage->pBt->usableSize;
  61104. iCellLast = usableSize - 4;
  61105. data = pPage->aData;
  61106. cellOffset = pPage->cellOffset;
  61107. if( !pPage->leaf ) iCellLast--;
  61108. for(i=0; i<pPage->nCell; i++){
  61109. pc = get2byteAligned(&data[cellOffset+i*2]);
  61110. testcase( pc==iCellFirst );
  61111. testcase( pc==iCellLast );
  61112. if( pc<iCellFirst || pc>iCellLast ){
  61113. return SQLITE_CORRUPT_PAGE(pPage);
  61114. }
  61115. sz = pPage->xCellSize(pPage, &data[pc]);
  61116. testcase( pc+sz==usableSize );
  61117. if( pc+sz>usableSize ){
  61118. return SQLITE_CORRUPT_PAGE(pPage);
  61119. }
  61120. }
  61121. return SQLITE_OK;
  61122. }
  61123. /*
  61124. ** Initialize the auxiliary information for a disk block.
  61125. **
  61126. ** Return SQLITE_OK on success. If we see that the page does
  61127. ** not contain a well-formed database page, then return
  61128. ** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
  61129. ** guarantee that the page is well-formed. It only shows that
  61130. ** we failed to detect any corruption.
  61131. */
  61132. static int btreeInitPage(MemPage *pPage){
  61133. u8 *data; /* Equal to pPage->aData */
  61134. BtShared *pBt; /* The main btree structure */
  61135. assert( pPage->pBt!=0 );
  61136. assert( pPage->pBt->db!=0 );
  61137. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  61138. assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
  61139. assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
  61140. assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
  61141. assert( pPage->isInit==0 );
  61142. pBt = pPage->pBt;
  61143. data = pPage->aData + pPage->hdrOffset;
  61144. /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating
  61145. ** the b-tree page type. */
  61146. if( decodeFlags(pPage, data[0]) ){
  61147. return SQLITE_CORRUPT_PAGE(pPage);
  61148. }
  61149. assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
  61150. pPage->maskPage = (u16)(pBt->pageSize - 1);
  61151. pPage->nOverflow = 0;
  61152. pPage->cellOffset = pPage->hdrOffset + 8 + pPage->childPtrSize;
  61153. pPage->aCellIdx = data + pPage->childPtrSize + 8;
  61154. pPage->aDataEnd = pPage->aData + pBt->usableSize;
  61155. pPage->aDataOfst = pPage->aData + pPage->childPtrSize;
  61156. /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
  61157. ** number of cells on the page. */
  61158. pPage->nCell = get2byte(&data[3]);
  61159. if( pPage->nCell>MX_CELL(pBt) ){
  61160. /* To many cells for a single page. The page must be corrupt */
  61161. return SQLITE_CORRUPT_PAGE(pPage);
  61162. }
  61163. testcase( pPage->nCell==MX_CELL(pBt) );
  61164. /* EVIDENCE-OF: R-24089-57979 If a page contains no cells (which is only
  61165. ** possible for a root page of a table that contains no rows) then the
  61166. ** offset to the cell content area will equal the page size minus the
  61167. ** bytes of reserved space. */
  61168. assert( pPage->nCell>0
  61169. || get2byteNotZero(&data[5])==(int)pBt->usableSize
  61170. || CORRUPT_DB );
  61171. pPage->nFree = -1; /* Indicate that this value is yet uncomputed */
  61172. pPage->isInit = 1;
  61173. if( pBt->db->flags & SQLITE_CellSizeCk ){
  61174. return btreeCellSizeCheck(pPage);
  61175. }
  61176. return SQLITE_OK;
  61177. }
  61178. /*
  61179. ** Set up a raw page so that it looks like a database page holding
  61180. ** no entries.
  61181. */
  61182. static void zeroPage(MemPage *pPage, int flags){
  61183. unsigned char *data = pPage->aData;
  61184. BtShared *pBt = pPage->pBt;
  61185. u8 hdr = pPage->hdrOffset;
  61186. u16 first;
  61187. assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
  61188. assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
  61189. assert( sqlite3PagerGetData(pPage->pDbPage) == data );
  61190. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  61191. assert( sqlite3_mutex_held(pBt->mutex) );
  61192. if( pBt->btsFlags & BTS_FAST_SECURE ){
  61193. memset(&data[hdr], 0, pBt->usableSize - hdr);
  61194. }
  61195. data[hdr] = (char)flags;
  61196. first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);
  61197. memset(&data[hdr+1], 0, 4);
  61198. data[hdr+7] = 0;
  61199. put2byte(&data[hdr+5], pBt->usableSize);
  61200. pPage->nFree = (u16)(pBt->usableSize - first);
  61201. decodeFlags(pPage, flags);
  61202. pPage->cellOffset = first;
  61203. pPage->aDataEnd = &data[pBt->usableSize];
  61204. pPage->aCellIdx = &data[first];
  61205. pPage->aDataOfst = &data[pPage->childPtrSize];
  61206. pPage->nOverflow = 0;
  61207. assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
  61208. pPage->maskPage = (u16)(pBt->pageSize - 1);
  61209. pPage->nCell = 0;
  61210. pPage->isInit = 1;
  61211. }
  61212. /*
  61213. ** Convert a DbPage obtained from the pager into a MemPage used by
  61214. ** the btree layer.
  61215. */
  61216. static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
  61217. MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
  61218. if( pgno!=pPage->pgno ){
  61219. pPage->aData = sqlite3PagerGetData(pDbPage);
  61220. pPage->pDbPage = pDbPage;
  61221. pPage->pBt = pBt;
  61222. pPage->pgno = pgno;
  61223. pPage->hdrOffset = pgno==1 ? 100 : 0;
  61224. }
  61225. assert( pPage->aData==sqlite3PagerGetData(pDbPage) );
  61226. return pPage;
  61227. }
  61228. /*
  61229. ** Get a page from the pager. Initialize the MemPage.pBt and
  61230. ** MemPage.aData elements if needed. See also: btreeGetUnusedPage().
  61231. **
  61232. ** If the PAGER_GET_NOCONTENT flag is set, it means that we do not care
  61233. ** about the content of the page at this time. So do not go to the disk
  61234. ** to fetch the content. Just fill in the content with zeros for now.
  61235. ** If in the future we call sqlite3PagerWrite() on this page, that
  61236. ** means we have started to be concerned about content and the disk
  61237. ** read should occur at that point.
  61238. */
  61239. static int btreeGetPage(
  61240. BtShared *pBt, /* The btree */
  61241. Pgno pgno, /* Number of the page to fetch */
  61242. MemPage **ppPage, /* Return the page in this parameter */
  61243. int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
  61244. ){
  61245. int rc;
  61246. DbPage *pDbPage;
  61247. assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
  61248. assert( sqlite3_mutex_held(pBt->mutex) );
  61249. rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
  61250. if( rc ) return rc;
  61251. *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
  61252. return SQLITE_OK;
  61253. }
  61254. /*
  61255. ** Retrieve a page from the pager cache. If the requested page is not
  61256. ** already in the pager cache return NULL. Initialize the MemPage.pBt and
  61257. ** MemPage.aData elements if needed.
  61258. */
  61259. static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
  61260. DbPage *pDbPage;
  61261. assert( sqlite3_mutex_held(pBt->mutex) );
  61262. pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
  61263. if( pDbPage ){
  61264. return btreePageFromDbPage(pDbPage, pgno, pBt);
  61265. }
  61266. return 0;
  61267. }
  61268. /*
  61269. ** Return the size of the database file in pages. If there is any kind of
  61270. ** error, return ((unsigned int)-1).
  61271. */
  61272. static Pgno btreePagecount(BtShared *pBt){
  61273. return pBt->nPage;
  61274. }
  61275. SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
  61276. assert( sqlite3BtreeHoldsMutex(p) );
  61277. assert( ((p->pBt->nPage)&0x80000000)==0 );
  61278. return btreePagecount(p->pBt);
  61279. }
  61280. /*
  61281. ** Get a page from the pager and initialize it.
  61282. **
  61283. ** If pCur!=0 then the page is being fetched as part of a moveToChild()
  61284. ** call. Do additional sanity checking on the page in this case.
  61285. ** And if the fetch fails, this routine must decrement pCur->iPage.
  61286. **
  61287. ** The page is fetched as read-write unless pCur is not NULL and is
  61288. ** a read-only cursor.
  61289. **
  61290. ** If an error occurs, then *ppPage is undefined. It
  61291. ** may remain unchanged, or it may be set to an invalid value.
  61292. */
  61293. static int getAndInitPage(
  61294. BtShared *pBt, /* The database file */
  61295. Pgno pgno, /* Number of the page to get */
  61296. MemPage **ppPage, /* Write the page pointer here */
  61297. BtCursor *pCur, /* Cursor to receive the page, or NULL */
  61298. int bReadOnly /* True for a read-only page */
  61299. ){
  61300. int rc;
  61301. DbPage *pDbPage;
  61302. assert( sqlite3_mutex_held(pBt->mutex) );
  61303. assert( pCur==0 || ppPage==&pCur->pPage );
  61304. assert( pCur==0 || bReadOnly==pCur->curPagerFlags );
  61305. assert( pCur==0 || pCur->iPage>0 );
  61306. if( pgno>btreePagecount(pBt) ){
  61307. rc = SQLITE_CORRUPT_BKPT;
  61308. goto getAndInitPage_error1;
  61309. }
  61310. rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, bReadOnly);
  61311. if( rc ){
  61312. goto getAndInitPage_error1;
  61313. }
  61314. *ppPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
  61315. if( (*ppPage)->isInit==0 ){
  61316. btreePageFromDbPage(pDbPage, pgno, pBt);
  61317. rc = btreeInitPage(*ppPage);
  61318. if( rc!=SQLITE_OK ){
  61319. goto getAndInitPage_error2;
  61320. }
  61321. }
  61322. assert( (*ppPage)->pgno==pgno );
  61323. assert( (*ppPage)->aData==sqlite3PagerGetData(pDbPage) );
  61324. /* If obtaining a child page for a cursor, we must verify that the page is
  61325. ** compatible with the root page. */
  61326. if( pCur && ((*ppPage)->nCell<1 || (*ppPage)->intKey!=pCur->curIntKey) ){
  61327. rc = SQLITE_CORRUPT_PGNO(pgno);
  61328. goto getAndInitPage_error2;
  61329. }
  61330. return SQLITE_OK;
  61331. getAndInitPage_error2:
  61332. releasePage(*ppPage);
  61333. getAndInitPage_error1:
  61334. if( pCur ){
  61335. pCur->iPage--;
  61336. pCur->pPage = pCur->apPage[pCur->iPage];
  61337. }
  61338. testcase( pgno==0 );
  61339. assert( pgno!=0 || rc==SQLITE_CORRUPT );
  61340. return rc;
  61341. }
  61342. /*
  61343. ** Release a MemPage. This should be called once for each prior
  61344. ** call to btreeGetPage.
  61345. **
  61346. ** Page1 is a special case and must be released using releasePageOne().
  61347. */
  61348. static void releasePageNotNull(MemPage *pPage){
  61349. assert( pPage->aData );
  61350. assert( pPage->pBt );
  61351. assert( pPage->pDbPage!=0 );
  61352. assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
  61353. assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
  61354. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  61355. sqlite3PagerUnrefNotNull(pPage->pDbPage);
  61356. }
  61357. static void releasePage(MemPage *pPage){
  61358. if( pPage ) releasePageNotNull(pPage);
  61359. }
  61360. static void releasePageOne(MemPage *pPage){
  61361. assert( pPage!=0 );
  61362. assert( pPage->aData );
  61363. assert( pPage->pBt );
  61364. assert( pPage->pDbPage!=0 );
  61365. assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
  61366. assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
  61367. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  61368. sqlite3PagerUnrefPageOne(pPage->pDbPage);
  61369. }
  61370. /*
  61371. ** Get an unused page.
  61372. **
  61373. ** This works just like btreeGetPage() with the addition:
  61374. **
  61375. ** * If the page is already in use for some other purpose, immediately
  61376. ** release it and return an SQLITE_CURRUPT error.
  61377. ** * Make sure the isInit flag is clear
  61378. */
  61379. static int btreeGetUnusedPage(
  61380. BtShared *pBt, /* The btree */
  61381. Pgno pgno, /* Number of the page to fetch */
  61382. MemPage **ppPage, /* Return the page in this parameter */
  61383. int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
  61384. ){
  61385. int rc = btreeGetPage(pBt, pgno, ppPage, flags);
  61386. if( rc==SQLITE_OK ){
  61387. if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
  61388. releasePage(*ppPage);
  61389. *ppPage = 0;
  61390. return SQLITE_CORRUPT_BKPT;
  61391. }
  61392. (*ppPage)->isInit = 0;
  61393. }else{
  61394. *ppPage = 0;
  61395. }
  61396. return rc;
  61397. }
  61398. /*
  61399. ** During a rollback, when the pager reloads information into the cache
  61400. ** so that the cache is restored to its original state at the start of
  61401. ** the transaction, for each page restored this routine is called.
  61402. **
  61403. ** This routine needs to reset the extra data section at the end of the
  61404. ** page to agree with the restored data.
  61405. */
  61406. static void pageReinit(DbPage *pData){
  61407. MemPage *pPage;
  61408. pPage = (MemPage *)sqlite3PagerGetExtra(pData);
  61409. assert( sqlite3PagerPageRefcount(pData)>0 );
  61410. if( pPage->isInit ){
  61411. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  61412. pPage->isInit = 0;
  61413. if( sqlite3PagerPageRefcount(pData)>1 ){
  61414. /* pPage might not be a btree page; it might be an overflow page
  61415. ** or ptrmap page or a free page. In those cases, the following
  61416. ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
  61417. ** But no harm is done by this. And it is very important that
  61418. ** btreeInitPage() be called on every btree page so we make
  61419. ** the call for every page that comes in for re-initing. */
  61420. btreeInitPage(pPage);
  61421. }
  61422. }
  61423. }
  61424. /*
  61425. ** Invoke the busy handler for a btree.
  61426. */
  61427. static int btreeInvokeBusyHandler(void *pArg){
  61428. BtShared *pBt = (BtShared*)pArg;
  61429. assert( pBt->db );
  61430. assert( sqlite3_mutex_held(pBt->db->mutex) );
  61431. return sqlite3InvokeBusyHandler(&pBt->db->busyHandler,
  61432. sqlite3PagerFile(pBt->pPager));
  61433. }
  61434. /*
  61435. ** Open a database file.
  61436. **
  61437. ** zFilename is the name of the database file. If zFilename is NULL
  61438. ** then an ephemeral database is created. The ephemeral database might
  61439. ** be exclusively in memory, or it might use a disk-based memory cache.
  61440. ** Either way, the ephemeral database will be automatically deleted
  61441. ** when sqlite3BtreeClose() is called.
  61442. **
  61443. ** If zFilename is ":memory:" then an in-memory database is created
  61444. ** that is automatically destroyed when it is closed.
  61445. **
  61446. ** The "flags" parameter is a bitmask that might contain bits like
  61447. ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
  61448. **
  61449. ** If the database is already opened in the same database connection
  61450. ** and we are in shared cache mode, then the open will fail with an
  61451. ** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
  61452. ** objects in the same database connection since doing so will lead
  61453. ** to problems with locking.
  61454. */
  61455. SQLITE_PRIVATE int sqlite3BtreeOpen(
  61456. sqlite3_vfs *pVfs, /* VFS to use for this b-tree */
  61457. const char *zFilename, /* Name of the file containing the BTree database */
  61458. sqlite3 *db, /* Associated database handle */
  61459. Btree **ppBtree, /* Pointer to new Btree object written here */
  61460. int flags, /* Options */
  61461. int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
  61462. ){
  61463. BtShared *pBt = 0; /* Shared part of btree structure */
  61464. Btree *p; /* Handle to return */
  61465. sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
  61466. int rc = SQLITE_OK; /* Result code from this function */
  61467. u8 nReserve; /* Byte of unused space on each page */
  61468. unsigned char zDbHeader[100]; /* Database header content */
  61469. /* True if opening an ephemeral, temporary database */
  61470. const int isTempDb = zFilename==0 || zFilename[0]==0;
  61471. /* Set the variable isMemdb to true for an in-memory database, or
  61472. ** false for a file-based database.
  61473. */
  61474. #ifdef SQLITE_OMIT_MEMORYDB
  61475. const int isMemdb = 0;
  61476. #else
  61477. const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
  61478. || (isTempDb && sqlite3TempInMemory(db))
  61479. || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
  61480. #endif
  61481. assert( db!=0 );
  61482. assert( pVfs!=0 );
  61483. assert( sqlite3_mutex_held(db->mutex) );
  61484. assert( (flags&0xff)==flags ); /* flags fit in 8 bits */
  61485. /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
  61486. assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
  61487. /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
  61488. assert( (flags & BTREE_SINGLE)==0 || isTempDb );
  61489. if( isMemdb ){
  61490. flags |= BTREE_MEMORY;
  61491. }
  61492. if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
  61493. vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
  61494. }
  61495. p = sqlite3MallocZero(sizeof(Btree));
  61496. if( !p ){
  61497. return SQLITE_NOMEM_BKPT;
  61498. }
  61499. p->inTrans = TRANS_NONE;
  61500. p->db = db;
  61501. #ifndef SQLITE_OMIT_SHARED_CACHE
  61502. p->lock.pBtree = p;
  61503. p->lock.iTable = 1;
  61504. #endif
  61505. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  61506. /*
  61507. ** If this Btree is a candidate for shared cache, try to find an
  61508. ** existing BtShared object that we can share with
  61509. */
  61510. if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
  61511. if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
  61512. int nFilename = sqlite3Strlen30(zFilename)+1;
  61513. int nFullPathname = pVfs->mxPathname+1;
  61514. char *zFullPathname = sqlite3Malloc(MAX(nFullPathname,nFilename));
  61515. MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
  61516. p->sharable = 1;
  61517. if( !zFullPathname ){
  61518. sqlite3_free(p);
  61519. return SQLITE_NOMEM_BKPT;
  61520. }
  61521. if( isMemdb ){
  61522. memcpy(zFullPathname, zFilename, nFilename);
  61523. }else{
  61524. rc = sqlite3OsFullPathname(pVfs, zFilename,
  61525. nFullPathname, zFullPathname);
  61526. if( rc ){
  61527. sqlite3_free(zFullPathname);
  61528. sqlite3_free(p);
  61529. return rc;
  61530. }
  61531. }
  61532. #if SQLITE_THREADSAFE
  61533. mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
  61534. sqlite3_mutex_enter(mutexOpen);
  61535. mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  61536. sqlite3_mutex_enter(mutexShared);
  61537. #endif
  61538. for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
  61539. assert( pBt->nRef>0 );
  61540. if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
  61541. && sqlite3PagerVfs(pBt->pPager)==pVfs ){
  61542. int iDb;
  61543. for(iDb=db->nDb-1; iDb>=0; iDb--){
  61544. Btree *pExisting = db->aDb[iDb].pBt;
  61545. if( pExisting && pExisting->pBt==pBt ){
  61546. sqlite3_mutex_leave(mutexShared);
  61547. sqlite3_mutex_leave(mutexOpen);
  61548. sqlite3_free(zFullPathname);
  61549. sqlite3_free(p);
  61550. return SQLITE_CONSTRAINT;
  61551. }
  61552. }
  61553. p->pBt = pBt;
  61554. pBt->nRef++;
  61555. break;
  61556. }
  61557. }
  61558. sqlite3_mutex_leave(mutexShared);
  61559. sqlite3_free(zFullPathname);
  61560. }
  61561. #ifdef SQLITE_DEBUG
  61562. else{
  61563. /* In debug mode, we mark all persistent databases as sharable
  61564. ** even when they are not. This exercises the locking code and
  61565. ** gives more opportunity for asserts(sqlite3_mutex_held())
  61566. ** statements to find locking problems.
  61567. */
  61568. p->sharable = 1;
  61569. }
  61570. #endif
  61571. }
  61572. #endif
  61573. if( pBt==0 ){
  61574. /*
  61575. ** The following asserts make sure that structures used by the btree are
  61576. ** the right size. This is to guard against size changes that result
  61577. ** when compiling on a different architecture.
  61578. */
  61579. assert( sizeof(i64)==8 );
  61580. assert( sizeof(u64)==8 );
  61581. assert( sizeof(u32)==4 );
  61582. assert( sizeof(u16)==2 );
  61583. assert( sizeof(Pgno)==4 );
  61584. pBt = sqlite3MallocZero( sizeof(*pBt) );
  61585. if( pBt==0 ){
  61586. rc = SQLITE_NOMEM_BKPT;
  61587. goto btree_open_out;
  61588. }
  61589. rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
  61590. sizeof(MemPage), flags, vfsFlags, pageReinit);
  61591. if( rc==SQLITE_OK ){
  61592. sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
  61593. rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
  61594. }
  61595. if( rc!=SQLITE_OK ){
  61596. goto btree_open_out;
  61597. }
  61598. pBt->openFlags = (u8)flags;
  61599. pBt->db = db;
  61600. sqlite3PagerSetBusyHandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
  61601. p->pBt = pBt;
  61602. pBt->pCursor = 0;
  61603. pBt->pPage1 = 0;
  61604. if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
  61605. #if defined(SQLITE_SECURE_DELETE)
  61606. pBt->btsFlags |= BTS_SECURE_DELETE;
  61607. #elif defined(SQLITE_FAST_SECURE_DELETE)
  61608. pBt->btsFlags |= BTS_OVERWRITE;
  61609. #endif
  61610. /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
  61611. ** determined by the 2-byte integer located at an offset of 16 bytes from
  61612. ** the beginning of the database file. */
  61613. pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
  61614. if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
  61615. || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
  61616. pBt->pageSize = 0;
  61617. #ifndef SQLITE_OMIT_AUTOVACUUM
  61618. /* If the magic name ":memory:" will create an in-memory database, then
  61619. ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
  61620. ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
  61621. ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
  61622. ** regular file-name. In this case the auto-vacuum applies as per normal.
  61623. */
  61624. if( zFilename && !isMemdb ){
  61625. pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
  61626. pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
  61627. }
  61628. #endif
  61629. nReserve = 0;
  61630. }else{
  61631. /* EVIDENCE-OF: R-37497-42412 The size of the reserved region is
  61632. ** determined by the one-byte unsigned integer found at an offset of 20
  61633. ** into the database file header. */
  61634. nReserve = zDbHeader[20];
  61635. pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  61636. #ifndef SQLITE_OMIT_AUTOVACUUM
  61637. pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
  61638. pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
  61639. #endif
  61640. }
  61641. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
  61642. if( rc ) goto btree_open_out;
  61643. pBt->usableSize = pBt->pageSize - nReserve;
  61644. assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
  61645. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  61646. /* Add the new BtShared object to the linked list sharable BtShareds.
  61647. */
  61648. pBt->nRef = 1;
  61649. if( p->sharable ){
  61650. MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
  61651. MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
  61652. if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
  61653. pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
  61654. if( pBt->mutex==0 ){
  61655. rc = SQLITE_NOMEM_BKPT;
  61656. goto btree_open_out;
  61657. }
  61658. }
  61659. sqlite3_mutex_enter(mutexShared);
  61660. pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
  61661. GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
  61662. sqlite3_mutex_leave(mutexShared);
  61663. }
  61664. #endif
  61665. }
  61666. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  61667. /* If the new Btree uses a sharable pBtShared, then link the new
  61668. ** Btree into the list of all sharable Btrees for the same connection.
  61669. ** The list is kept in ascending order by pBt address.
  61670. */
  61671. if( p->sharable ){
  61672. int i;
  61673. Btree *pSib;
  61674. for(i=0; i<db->nDb; i++){
  61675. if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
  61676. while( pSib->pPrev ){ pSib = pSib->pPrev; }
  61677. if( (uptr)p->pBt<(uptr)pSib->pBt ){
  61678. p->pNext = pSib;
  61679. p->pPrev = 0;
  61680. pSib->pPrev = p;
  61681. }else{
  61682. while( pSib->pNext && (uptr)pSib->pNext->pBt<(uptr)p->pBt ){
  61683. pSib = pSib->pNext;
  61684. }
  61685. p->pNext = pSib->pNext;
  61686. p->pPrev = pSib;
  61687. if( p->pNext ){
  61688. p->pNext->pPrev = p;
  61689. }
  61690. pSib->pNext = p;
  61691. }
  61692. break;
  61693. }
  61694. }
  61695. }
  61696. #endif
  61697. *ppBtree = p;
  61698. btree_open_out:
  61699. if( rc!=SQLITE_OK ){
  61700. if( pBt && pBt->pPager ){
  61701. sqlite3PagerClose(pBt->pPager, 0);
  61702. }
  61703. sqlite3_free(pBt);
  61704. sqlite3_free(p);
  61705. *ppBtree = 0;
  61706. }else{
  61707. sqlite3_file *pFile;
  61708. /* If the B-Tree was successfully opened, set the pager-cache size to the
  61709. ** default value. Except, when opening on an existing shared pager-cache,
  61710. ** do not change the pager-cache size.
  61711. */
  61712. if( sqlite3BtreeSchema(p, 0, 0)==0 ){
  61713. sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
  61714. }
  61715. pFile = sqlite3PagerFile(pBt->pPager);
  61716. if( pFile->pMethods ){
  61717. sqlite3OsFileControlHint(pFile, SQLITE_FCNTL_PDB, (void*)&pBt->db);
  61718. }
  61719. }
  61720. if( mutexOpen ){
  61721. assert( sqlite3_mutex_held(mutexOpen) );
  61722. sqlite3_mutex_leave(mutexOpen);
  61723. }
  61724. assert( rc!=SQLITE_OK || sqlite3BtreeConnectionCount(*ppBtree)>0 );
  61725. return rc;
  61726. }
  61727. /*
  61728. ** Decrement the BtShared.nRef counter. When it reaches zero,
  61729. ** remove the BtShared structure from the sharing list. Return
  61730. ** true if the BtShared.nRef counter reaches zero and return
  61731. ** false if it is still positive.
  61732. */
  61733. static int removeFromSharingList(BtShared *pBt){
  61734. #ifndef SQLITE_OMIT_SHARED_CACHE
  61735. MUTEX_LOGIC( sqlite3_mutex *pMaster; )
  61736. BtShared *pList;
  61737. int removed = 0;
  61738. assert( sqlite3_mutex_notheld(pBt->mutex) );
  61739. MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  61740. sqlite3_mutex_enter(pMaster);
  61741. pBt->nRef--;
  61742. if( pBt->nRef<=0 ){
  61743. if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
  61744. GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
  61745. }else{
  61746. pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
  61747. while( ALWAYS(pList) && pList->pNext!=pBt ){
  61748. pList=pList->pNext;
  61749. }
  61750. if( ALWAYS(pList) ){
  61751. pList->pNext = pBt->pNext;
  61752. }
  61753. }
  61754. if( SQLITE_THREADSAFE ){
  61755. sqlite3_mutex_free(pBt->mutex);
  61756. }
  61757. removed = 1;
  61758. }
  61759. sqlite3_mutex_leave(pMaster);
  61760. return removed;
  61761. #else
  61762. return 1;
  61763. #endif
  61764. }
  61765. /*
  61766. ** Make sure pBt->pTmpSpace points to an allocation of
  61767. ** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child
  61768. ** pointer.
  61769. */
  61770. static void allocateTempSpace(BtShared *pBt){
  61771. if( !pBt->pTmpSpace ){
  61772. pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
  61773. /* One of the uses of pBt->pTmpSpace is to format cells before
  61774. ** inserting them into a leaf page (function fillInCell()). If
  61775. ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
  61776. ** by the various routines that manipulate binary cells. Which
  61777. ** can mean that fillInCell() only initializes the first 2 or 3
  61778. ** bytes of pTmpSpace, but that the first 4 bytes are copied from
  61779. ** it into a database page. This is not actually a problem, but it
  61780. ** does cause a valgrind error when the 1 or 2 bytes of unitialized
  61781. ** data is passed to system call write(). So to avoid this error,
  61782. ** zero the first 4 bytes of temp space here.
  61783. **
  61784. ** Also: Provide four bytes of initialized space before the
  61785. ** beginning of pTmpSpace as an area available to prepend the
  61786. ** left-child pointer to the beginning of a cell.
  61787. */
  61788. if( pBt->pTmpSpace ){
  61789. memset(pBt->pTmpSpace, 0, 8);
  61790. pBt->pTmpSpace += 4;
  61791. }
  61792. }
  61793. }
  61794. /*
  61795. ** Free the pBt->pTmpSpace allocation
  61796. */
  61797. static void freeTempSpace(BtShared *pBt){
  61798. if( pBt->pTmpSpace ){
  61799. pBt->pTmpSpace -= 4;
  61800. sqlite3PageFree(pBt->pTmpSpace);
  61801. pBt->pTmpSpace = 0;
  61802. }
  61803. }
  61804. /*
  61805. ** Close an open database and invalidate all cursors.
  61806. */
  61807. SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
  61808. BtShared *pBt = p->pBt;
  61809. BtCursor *pCur;
  61810. /* Close all cursors opened via this handle. */
  61811. assert( sqlite3_mutex_held(p->db->mutex) );
  61812. sqlite3BtreeEnter(p);
  61813. pCur = pBt->pCursor;
  61814. while( pCur ){
  61815. BtCursor *pTmp = pCur;
  61816. pCur = pCur->pNext;
  61817. if( pTmp->pBtree==p ){
  61818. sqlite3BtreeCloseCursor(pTmp);
  61819. }
  61820. }
  61821. /* Rollback any active transaction and free the handle structure.
  61822. ** The call to sqlite3BtreeRollback() drops any table-locks held by
  61823. ** this handle.
  61824. */
  61825. sqlite3BtreeRollback(p, SQLITE_OK, 0);
  61826. sqlite3BtreeLeave(p);
  61827. /* If there are still other outstanding references to the shared-btree
  61828. ** structure, return now. The remainder of this procedure cleans
  61829. ** up the shared-btree.
  61830. */
  61831. assert( p->wantToLock==0 && p->locked==0 );
  61832. if( !p->sharable || removeFromSharingList(pBt) ){
  61833. /* The pBt is no longer on the sharing list, so we can access
  61834. ** it without having to hold the mutex.
  61835. **
  61836. ** Clean out and delete the BtShared object.
  61837. */
  61838. assert( !pBt->pCursor );
  61839. sqlite3PagerClose(pBt->pPager, p->db);
  61840. if( pBt->xFreeSchema && pBt->pSchema ){
  61841. pBt->xFreeSchema(pBt->pSchema);
  61842. }
  61843. sqlite3DbFree(0, pBt->pSchema);
  61844. freeTempSpace(pBt);
  61845. sqlite3_free(pBt);
  61846. }
  61847. #ifndef SQLITE_OMIT_SHARED_CACHE
  61848. assert( p->wantToLock==0 );
  61849. assert( p->locked==0 );
  61850. if( p->pPrev ) p->pPrev->pNext = p->pNext;
  61851. if( p->pNext ) p->pNext->pPrev = p->pPrev;
  61852. #endif
  61853. sqlite3_free(p);
  61854. return SQLITE_OK;
  61855. }
  61856. /*
  61857. ** Change the "soft" limit on the number of pages in the cache.
  61858. ** Unused and unmodified pages will be recycled when the number of
  61859. ** pages in the cache exceeds this soft limit. But the size of the
  61860. ** cache is allowed to grow larger than this limit if it contains
  61861. ** dirty pages or pages still in active use.
  61862. */
  61863. SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
  61864. BtShared *pBt = p->pBt;
  61865. assert( sqlite3_mutex_held(p->db->mutex) );
  61866. sqlite3BtreeEnter(p);
  61867. sqlite3PagerSetCachesize(pBt->pPager, mxPage);
  61868. sqlite3BtreeLeave(p);
  61869. return SQLITE_OK;
  61870. }
  61871. /*
  61872. ** Change the "spill" limit on the number of pages in the cache.
  61873. ** If the number of pages exceeds this limit during a write transaction,
  61874. ** the pager might attempt to "spill" pages to the journal early in
  61875. ** order to free up memory.
  61876. **
  61877. ** The value returned is the current spill size. If zero is passed
  61878. ** as an argument, no changes are made to the spill size setting, so
  61879. ** using mxPage of 0 is a way to query the current spill size.
  61880. */
  61881. SQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree *p, int mxPage){
  61882. BtShared *pBt = p->pBt;
  61883. int res;
  61884. assert( sqlite3_mutex_held(p->db->mutex) );
  61885. sqlite3BtreeEnter(p);
  61886. res = sqlite3PagerSetSpillsize(pBt->pPager, mxPage);
  61887. sqlite3BtreeLeave(p);
  61888. return res;
  61889. }
  61890. #if SQLITE_MAX_MMAP_SIZE>0
  61891. /*
  61892. ** Change the limit on the amount of the database file that may be
  61893. ** memory mapped.
  61894. */
  61895. SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
  61896. BtShared *pBt = p->pBt;
  61897. assert( sqlite3_mutex_held(p->db->mutex) );
  61898. sqlite3BtreeEnter(p);
  61899. sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
  61900. sqlite3BtreeLeave(p);
  61901. return SQLITE_OK;
  61902. }
  61903. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  61904. /*
  61905. ** Change the way data is synced to disk in order to increase or decrease
  61906. ** how well the database resists damage due to OS crashes and power
  61907. ** failures. Level 1 is the same as asynchronous (no syncs() occur and
  61908. ** there is a high probability of damage) Level 2 is the default. There
  61909. ** is a very low but non-zero probability of damage. Level 3 reduces the
  61910. ** probability of damage to near zero but with a write performance reduction.
  61911. */
  61912. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  61913. SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(
  61914. Btree *p, /* The btree to set the safety level on */
  61915. unsigned pgFlags /* Various PAGER_* flags */
  61916. ){
  61917. BtShared *pBt = p->pBt;
  61918. assert( sqlite3_mutex_held(p->db->mutex) );
  61919. sqlite3BtreeEnter(p);
  61920. sqlite3PagerSetFlags(pBt->pPager, pgFlags);
  61921. sqlite3BtreeLeave(p);
  61922. return SQLITE_OK;
  61923. }
  61924. #endif
  61925. /*
  61926. ** Change the default pages size and the number of reserved bytes per page.
  61927. ** Or, if the page size has already been fixed, return SQLITE_READONLY
  61928. ** without changing anything.
  61929. **
  61930. ** The page size must be a power of 2 between 512 and 65536. If the page
  61931. ** size supplied does not meet this constraint then the page size is not
  61932. ** changed.
  61933. **
  61934. ** Page sizes are constrained to be a power of two so that the region
  61935. ** of the database file used for locking (beginning at PENDING_BYTE,
  61936. ** the first byte past the 1GB boundary, 0x40000000) needs to occur
  61937. ** at the beginning of a page.
  61938. **
  61939. ** If parameter nReserve is less than zero, then the number of reserved
  61940. ** bytes per page is left unchanged.
  61941. **
  61942. ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
  61943. ** and autovacuum mode can no longer be changed.
  61944. */
  61945. SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
  61946. int rc = SQLITE_OK;
  61947. BtShared *pBt = p->pBt;
  61948. assert( nReserve>=-1 && nReserve<=255 );
  61949. sqlite3BtreeEnter(p);
  61950. #if SQLITE_HAS_CODEC
  61951. if( nReserve>pBt->optimalReserve ) pBt->optimalReserve = (u8)nReserve;
  61952. #endif
  61953. if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
  61954. sqlite3BtreeLeave(p);
  61955. return SQLITE_READONLY;
  61956. }
  61957. if( nReserve<0 ){
  61958. nReserve = pBt->pageSize - pBt->usableSize;
  61959. }
  61960. assert( nReserve>=0 && nReserve<=255 );
  61961. if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
  61962. ((pageSize-1)&pageSize)==0 ){
  61963. assert( (pageSize & 7)==0 );
  61964. assert( !pBt->pCursor );
  61965. pBt->pageSize = (u32)pageSize;
  61966. freeTempSpace(pBt);
  61967. }
  61968. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
  61969. pBt->usableSize = pBt->pageSize - (u16)nReserve;
  61970. if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  61971. sqlite3BtreeLeave(p);
  61972. return rc;
  61973. }
  61974. /*
  61975. ** Return the currently defined page size
  61976. */
  61977. SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
  61978. return p->pBt->pageSize;
  61979. }
  61980. /*
  61981. ** This function is similar to sqlite3BtreeGetReserve(), except that it
  61982. ** may only be called if it is guaranteed that the b-tree mutex is already
  61983. ** held.
  61984. **
  61985. ** This is useful in one special case in the backup API code where it is
  61986. ** known that the shared b-tree mutex is held, but the mutex on the
  61987. ** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
  61988. ** were to be called, it might collide with some other operation on the
  61989. ** database handle that owns *p, causing undefined behavior.
  61990. */
  61991. SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p){
  61992. int n;
  61993. assert( sqlite3_mutex_held(p->pBt->mutex) );
  61994. n = p->pBt->pageSize - p->pBt->usableSize;
  61995. return n;
  61996. }
  61997. /*
  61998. ** Return the number of bytes of space at the end of every page that
  61999. ** are intentually left unused. This is the "reserved" space that is
  62000. ** sometimes used by extensions.
  62001. **
  62002. ** If SQLITE_HAS_MUTEX is defined then the number returned is the
  62003. ** greater of the current reserved space and the maximum requested
  62004. ** reserve space.
  62005. */
  62006. SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree *p){
  62007. int n;
  62008. sqlite3BtreeEnter(p);
  62009. n = sqlite3BtreeGetReserveNoMutex(p);
  62010. #ifdef SQLITE_HAS_CODEC
  62011. if( n<p->pBt->optimalReserve ) n = p->pBt->optimalReserve;
  62012. #endif
  62013. sqlite3BtreeLeave(p);
  62014. return n;
  62015. }
  62016. /*
  62017. ** Set the maximum page count for a database if mxPage is positive.
  62018. ** No changes are made if mxPage is 0 or negative.
  62019. ** Regardless of the value of mxPage, return the maximum page count.
  62020. */
  62021. SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
  62022. int n;
  62023. sqlite3BtreeEnter(p);
  62024. n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
  62025. sqlite3BtreeLeave(p);
  62026. return n;
  62027. }
  62028. /*
  62029. ** Change the values for the BTS_SECURE_DELETE and BTS_OVERWRITE flags:
  62030. **
  62031. ** newFlag==0 Both BTS_SECURE_DELETE and BTS_OVERWRITE are cleared
  62032. ** newFlag==1 BTS_SECURE_DELETE set and BTS_OVERWRITE is cleared
  62033. ** newFlag==2 BTS_SECURE_DELETE cleared and BTS_OVERWRITE is set
  62034. ** newFlag==(-1) No changes
  62035. **
  62036. ** This routine acts as a query if newFlag is less than zero
  62037. **
  62038. ** With BTS_OVERWRITE set, deleted content is overwritten by zeros, but
  62039. ** freelist leaf pages are not written back to the database. Thus in-page
  62040. ** deleted content is cleared, but freelist deleted content is not.
  62041. **
  62042. ** With BTS_SECURE_DELETE, operation is like BTS_OVERWRITE with the addition
  62043. ** that freelist leaf pages are written back into the database, increasing
  62044. ** the amount of disk I/O.
  62045. */
  62046. SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
  62047. int b;
  62048. if( p==0 ) return 0;
  62049. sqlite3BtreeEnter(p);
  62050. assert( BTS_OVERWRITE==BTS_SECURE_DELETE*2 );
  62051. assert( BTS_FAST_SECURE==(BTS_OVERWRITE|BTS_SECURE_DELETE) );
  62052. if( newFlag>=0 ){
  62053. p->pBt->btsFlags &= ~BTS_FAST_SECURE;
  62054. p->pBt->btsFlags |= BTS_SECURE_DELETE*newFlag;
  62055. }
  62056. b = (p->pBt->btsFlags & BTS_FAST_SECURE)/BTS_SECURE_DELETE;
  62057. sqlite3BtreeLeave(p);
  62058. return b;
  62059. }
  62060. /*
  62061. ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
  62062. ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
  62063. ** is disabled. The default value for the auto-vacuum property is
  62064. ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
  62065. */
  62066. SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
  62067. #ifdef SQLITE_OMIT_AUTOVACUUM
  62068. return SQLITE_READONLY;
  62069. #else
  62070. BtShared *pBt = p->pBt;
  62071. int rc = SQLITE_OK;
  62072. u8 av = (u8)autoVacuum;
  62073. sqlite3BtreeEnter(p);
  62074. if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
  62075. rc = SQLITE_READONLY;
  62076. }else{
  62077. pBt->autoVacuum = av ?1:0;
  62078. pBt->incrVacuum = av==2 ?1:0;
  62079. }
  62080. sqlite3BtreeLeave(p);
  62081. return rc;
  62082. #endif
  62083. }
  62084. /*
  62085. ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
  62086. ** enabled 1 is returned. Otherwise 0.
  62087. */
  62088. SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
  62089. #ifdef SQLITE_OMIT_AUTOVACUUM
  62090. return BTREE_AUTOVACUUM_NONE;
  62091. #else
  62092. int rc;
  62093. sqlite3BtreeEnter(p);
  62094. rc = (
  62095. (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
  62096. (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
  62097. BTREE_AUTOVACUUM_INCR
  62098. );
  62099. sqlite3BtreeLeave(p);
  62100. return rc;
  62101. #endif
  62102. }
  62103. /*
  62104. ** If the user has not set the safety-level for this database connection
  62105. ** using "PRAGMA synchronous", and if the safety-level is not already
  62106. ** set to the value passed to this function as the second parameter,
  62107. ** set it so.
  62108. */
  62109. #if SQLITE_DEFAULT_SYNCHRONOUS!=SQLITE_DEFAULT_WAL_SYNCHRONOUS \
  62110. && !defined(SQLITE_OMIT_WAL)
  62111. static void setDefaultSyncFlag(BtShared *pBt, u8 safety_level){
  62112. sqlite3 *db;
  62113. Db *pDb;
  62114. if( (db=pBt->db)!=0 && (pDb=db->aDb)!=0 ){
  62115. while( pDb->pBt==0 || pDb->pBt->pBt!=pBt ){ pDb++; }
  62116. if( pDb->bSyncSet==0
  62117. && pDb->safety_level!=safety_level
  62118. && pDb!=&db->aDb[1]
  62119. ){
  62120. pDb->safety_level = safety_level;
  62121. sqlite3PagerSetFlags(pBt->pPager,
  62122. pDb->safety_level | (db->flags & PAGER_FLAGS_MASK));
  62123. }
  62124. }
  62125. }
  62126. #else
  62127. # define setDefaultSyncFlag(pBt,safety_level)
  62128. #endif
  62129. /* Forward declaration */
  62130. static int newDatabase(BtShared*);
  62131. /*
  62132. ** Get a reference to pPage1 of the database file. This will
  62133. ** also acquire a readlock on that file.
  62134. **
  62135. ** SQLITE_OK is returned on success. If the file is not a
  62136. ** well-formed database file, then SQLITE_CORRUPT is returned.
  62137. ** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
  62138. ** is returned if we run out of memory.
  62139. */
  62140. static int lockBtree(BtShared *pBt){
  62141. int rc; /* Result code from subfunctions */
  62142. MemPage *pPage1; /* Page 1 of the database file */
  62143. u32 nPage; /* Number of pages in the database */
  62144. u32 nPageFile = 0; /* Number of pages in the database file */
  62145. u32 nPageHeader; /* Number of pages in the database according to hdr */
  62146. assert( sqlite3_mutex_held(pBt->mutex) );
  62147. assert( pBt->pPage1==0 );
  62148. rc = sqlite3PagerSharedLock(pBt->pPager);
  62149. if( rc!=SQLITE_OK ) return rc;
  62150. rc = btreeGetPage(pBt, 1, &pPage1, 0);
  62151. if( rc!=SQLITE_OK ) return rc;
  62152. /* Do some checking to help insure the file we opened really is
  62153. ** a valid database file.
  62154. */
  62155. nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
  62156. sqlite3PagerPagecount(pBt->pPager, (int*)&nPageFile);
  62157. if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
  62158. nPage = nPageFile;
  62159. }
  62160. if( (pBt->db->flags & SQLITE_ResetDatabase)!=0 ){
  62161. nPage = 0;
  62162. }
  62163. if( nPage>0 ){
  62164. u32 pageSize;
  62165. u32 usableSize;
  62166. u8 *page1 = pPage1->aData;
  62167. rc = SQLITE_NOTADB;
  62168. /* EVIDENCE-OF: R-43737-39999 Every valid SQLite database file begins
  62169. ** with the following 16 bytes (in hex): 53 51 4c 69 74 65 20 66 6f 72 6d
  62170. ** 61 74 20 33 00. */
  62171. if( memcmp(page1, zMagicHeader, 16)!=0 ){
  62172. goto page1_init_failed;
  62173. }
  62174. #ifdef SQLITE_OMIT_WAL
  62175. if( page1[18]>1 ){
  62176. pBt->btsFlags |= BTS_READ_ONLY;
  62177. }
  62178. if( page1[19]>1 ){
  62179. goto page1_init_failed;
  62180. }
  62181. #else
  62182. if( page1[18]>2 ){
  62183. pBt->btsFlags |= BTS_READ_ONLY;
  62184. }
  62185. if( page1[19]>2 ){
  62186. goto page1_init_failed;
  62187. }
  62188. /* If the write version is set to 2, this database should be accessed
  62189. ** in WAL mode. If the log is not already open, open it now. Then
  62190. ** return SQLITE_OK and return without populating BtShared.pPage1.
  62191. ** The caller detects this and calls this function again. This is
  62192. ** required as the version of page 1 currently in the page1 buffer
  62193. ** may not be the latest version - there may be a newer one in the log
  62194. ** file.
  62195. */
  62196. if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
  62197. int isOpen = 0;
  62198. rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
  62199. if( rc!=SQLITE_OK ){
  62200. goto page1_init_failed;
  62201. }else{
  62202. setDefaultSyncFlag(pBt, SQLITE_DEFAULT_WAL_SYNCHRONOUS+1);
  62203. if( isOpen==0 ){
  62204. releasePageOne(pPage1);
  62205. return SQLITE_OK;
  62206. }
  62207. }
  62208. rc = SQLITE_NOTADB;
  62209. }else{
  62210. setDefaultSyncFlag(pBt, SQLITE_DEFAULT_SYNCHRONOUS+1);
  62211. }
  62212. #endif
  62213. /* EVIDENCE-OF: R-15465-20813 The maximum and minimum embedded payload
  62214. ** fractions and the leaf payload fraction values must be 64, 32, and 32.
  62215. **
  62216. ** The original design allowed these amounts to vary, but as of
  62217. ** version 3.6.0, we require them to be fixed.
  62218. */
  62219. if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
  62220. goto page1_init_failed;
  62221. }
  62222. /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
  62223. ** determined by the 2-byte integer located at an offset of 16 bytes from
  62224. ** the beginning of the database file. */
  62225. pageSize = (page1[16]<<8) | (page1[17]<<16);
  62226. /* EVIDENCE-OF: R-25008-21688 The size of a page is a power of two
  62227. ** between 512 and 65536 inclusive. */
  62228. if( ((pageSize-1)&pageSize)!=0
  62229. || pageSize>SQLITE_MAX_PAGE_SIZE
  62230. || pageSize<=256
  62231. ){
  62232. goto page1_init_failed;
  62233. }
  62234. pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  62235. assert( (pageSize & 7)==0 );
  62236. /* EVIDENCE-OF: R-59310-51205 The "reserved space" size in the 1-byte
  62237. ** integer at offset 20 is the number of bytes of space at the end of
  62238. ** each page to reserve for extensions.
  62239. **
  62240. ** EVIDENCE-OF: R-37497-42412 The size of the reserved region is
  62241. ** determined by the one-byte unsigned integer found at an offset of 20
  62242. ** into the database file header. */
  62243. usableSize = pageSize - page1[20];
  62244. if( (u32)pageSize!=pBt->pageSize ){
  62245. /* After reading the first page of the database assuming a page size
  62246. ** of BtShared.pageSize, we have discovered that the page-size is
  62247. ** actually pageSize. Unlock the database, leave pBt->pPage1 at
  62248. ** zero and return SQLITE_OK. The caller will call this function
  62249. ** again with the correct page-size.
  62250. */
  62251. releasePageOne(pPage1);
  62252. pBt->usableSize = usableSize;
  62253. pBt->pageSize = pageSize;
  62254. freeTempSpace(pBt);
  62255. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
  62256. pageSize-usableSize);
  62257. return rc;
  62258. }
  62259. if( sqlite3WritableSchema(pBt->db)==0 && nPage>nPageFile ){
  62260. rc = SQLITE_CORRUPT_BKPT;
  62261. goto page1_init_failed;
  62262. }
  62263. /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to
  62264. ** be less than 480. In other words, if the page size is 512, then the
  62265. ** reserved space size cannot exceed 32. */
  62266. if( usableSize<480 ){
  62267. goto page1_init_failed;
  62268. }
  62269. pBt->pageSize = pageSize;
  62270. pBt->usableSize = usableSize;
  62271. #ifndef SQLITE_OMIT_AUTOVACUUM
  62272. pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
  62273. pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
  62274. #endif
  62275. }
  62276. /* maxLocal is the maximum amount of payload to store locally for
  62277. ** a cell. Make sure it is small enough so that at least minFanout
  62278. ** cells can will fit on one page. We assume a 10-byte page header.
  62279. ** Besides the payload, the cell must store:
  62280. ** 2-byte pointer to the cell
  62281. ** 4-byte child pointer
  62282. ** 9-byte nKey value
  62283. ** 4-byte nData value
  62284. ** 4-byte overflow page pointer
  62285. ** So a cell consists of a 2-byte pointer, a header which is as much as
  62286. ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
  62287. ** page pointer.
  62288. */
  62289. pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
  62290. pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
  62291. pBt->maxLeaf = (u16)(pBt->usableSize - 35);
  62292. pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
  62293. if( pBt->maxLocal>127 ){
  62294. pBt->max1bytePayload = 127;
  62295. }else{
  62296. pBt->max1bytePayload = (u8)pBt->maxLocal;
  62297. }
  62298. assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
  62299. pBt->pPage1 = pPage1;
  62300. pBt->nPage = nPage;
  62301. return SQLITE_OK;
  62302. page1_init_failed:
  62303. releasePageOne(pPage1);
  62304. pBt->pPage1 = 0;
  62305. return rc;
  62306. }
  62307. #ifndef NDEBUG
  62308. /*
  62309. ** Return the number of cursors open on pBt. This is for use
  62310. ** in assert() expressions, so it is only compiled if NDEBUG is not
  62311. ** defined.
  62312. **
  62313. ** Only write cursors are counted if wrOnly is true. If wrOnly is
  62314. ** false then all cursors are counted.
  62315. **
  62316. ** For the purposes of this routine, a cursor is any cursor that
  62317. ** is capable of reading or writing to the database. Cursors that
  62318. ** have been tripped into the CURSOR_FAULT state are not counted.
  62319. */
  62320. static int countValidCursors(BtShared *pBt, int wrOnly){
  62321. BtCursor *pCur;
  62322. int r = 0;
  62323. for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
  62324. if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
  62325. && pCur->eState!=CURSOR_FAULT ) r++;
  62326. }
  62327. return r;
  62328. }
  62329. #endif
  62330. /*
  62331. ** If there are no outstanding cursors and we are not in the middle
  62332. ** of a transaction but there is a read lock on the database, then
  62333. ** this routine unrefs the first page of the database file which
  62334. ** has the effect of releasing the read lock.
  62335. **
  62336. ** If there is a transaction in progress, this routine is a no-op.
  62337. */
  62338. static void unlockBtreeIfUnused(BtShared *pBt){
  62339. assert( sqlite3_mutex_held(pBt->mutex) );
  62340. assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
  62341. if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
  62342. MemPage *pPage1 = pBt->pPage1;
  62343. assert( pPage1->aData );
  62344. assert( sqlite3PagerRefcount(pBt->pPager)==1 );
  62345. pBt->pPage1 = 0;
  62346. releasePageOne(pPage1);
  62347. }
  62348. }
  62349. /*
  62350. ** If pBt points to an empty file then convert that empty file
  62351. ** into a new empty database by initializing the first page of
  62352. ** the database.
  62353. */
  62354. static int newDatabase(BtShared *pBt){
  62355. MemPage *pP1;
  62356. unsigned char *data;
  62357. int rc;
  62358. assert( sqlite3_mutex_held(pBt->mutex) );
  62359. if( pBt->nPage>0 ){
  62360. return SQLITE_OK;
  62361. }
  62362. pP1 = pBt->pPage1;
  62363. assert( pP1!=0 );
  62364. data = pP1->aData;
  62365. rc = sqlite3PagerWrite(pP1->pDbPage);
  62366. if( rc ) return rc;
  62367. memcpy(data, zMagicHeader, sizeof(zMagicHeader));
  62368. assert( sizeof(zMagicHeader)==16 );
  62369. data[16] = (u8)((pBt->pageSize>>8)&0xff);
  62370. data[17] = (u8)((pBt->pageSize>>16)&0xff);
  62371. data[18] = 1;
  62372. data[19] = 1;
  62373. assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
  62374. data[20] = (u8)(pBt->pageSize - pBt->usableSize);
  62375. data[21] = 64;
  62376. data[22] = 32;
  62377. data[23] = 32;
  62378. memset(&data[24], 0, 100-24);
  62379. zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
  62380. pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  62381. #ifndef SQLITE_OMIT_AUTOVACUUM
  62382. assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
  62383. assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
  62384. put4byte(&data[36 + 4*4], pBt->autoVacuum);
  62385. put4byte(&data[36 + 7*4], pBt->incrVacuum);
  62386. #endif
  62387. pBt->nPage = 1;
  62388. data[31] = 1;
  62389. return SQLITE_OK;
  62390. }
  62391. /*
  62392. ** Initialize the first page of the database file (creating a database
  62393. ** consisting of a single page and no schema objects). Return SQLITE_OK
  62394. ** if successful, or an SQLite error code otherwise.
  62395. */
  62396. SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){
  62397. int rc;
  62398. sqlite3BtreeEnter(p);
  62399. p->pBt->nPage = 0;
  62400. rc = newDatabase(p->pBt);
  62401. sqlite3BtreeLeave(p);
  62402. return rc;
  62403. }
  62404. /*
  62405. ** Attempt to start a new transaction. A write-transaction
  62406. ** is started if the second argument is nonzero, otherwise a read-
  62407. ** transaction. If the second argument is 2 or more and exclusive
  62408. ** transaction is started, meaning that no other process is allowed
  62409. ** to access the database. A preexisting transaction may not be
  62410. ** upgraded to exclusive by calling this routine a second time - the
  62411. ** exclusivity flag only works for a new transaction.
  62412. **
  62413. ** A write-transaction must be started before attempting any
  62414. ** changes to the database. None of the following routines
  62415. ** will work unless a transaction is started first:
  62416. **
  62417. ** sqlite3BtreeCreateTable()
  62418. ** sqlite3BtreeCreateIndex()
  62419. ** sqlite3BtreeClearTable()
  62420. ** sqlite3BtreeDropTable()
  62421. ** sqlite3BtreeInsert()
  62422. ** sqlite3BtreeDelete()
  62423. ** sqlite3BtreeUpdateMeta()
  62424. **
  62425. ** If an initial attempt to acquire the lock fails because of lock contention
  62426. ** and the database was previously unlocked, then invoke the busy handler
  62427. ** if there is one. But if there was previously a read-lock, do not
  62428. ** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
  62429. ** returned when there is already a read-lock in order to avoid a deadlock.
  62430. **
  62431. ** Suppose there are two processes A and B. A has a read lock and B has
  62432. ** a reserved lock. B tries to promote to exclusive but is blocked because
  62433. ** of A's read lock. A tries to promote to reserved but is blocked by B.
  62434. ** One or the other of the two processes must give way or there can be
  62435. ** no progress. By returning SQLITE_BUSY and not invoking the busy callback
  62436. ** when A already has a read lock, we encourage A to give up and let B
  62437. ** proceed.
  62438. */
  62439. SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag, int *pSchemaVersion){
  62440. BtShared *pBt = p->pBt;
  62441. int rc = SQLITE_OK;
  62442. sqlite3BtreeEnter(p);
  62443. btreeIntegrity(p);
  62444. /* If the btree is already in a write-transaction, or it
  62445. ** is already in a read-transaction and a read-transaction
  62446. ** is requested, this is a no-op.
  62447. */
  62448. if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
  62449. goto trans_begun;
  62450. }
  62451. assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
  62452. if( (p->db->flags & SQLITE_ResetDatabase)
  62453. && sqlite3PagerIsreadonly(pBt->pPager)==0
  62454. ){
  62455. pBt->btsFlags &= ~BTS_READ_ONLY;
  62456. }
  62457. /* Write transactions are not possible on a read-only database */
  62458. if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
  62459. rc = SQLITE_READONLY;
  62460. goto trans_begun;
  62461. }
  62462. #ifndef SQLITE_OMIT_SHARED_CACHE
  62463. {
  62464. sqlite3 *pBlock = 0;
  62465. /* If another database handle has already opened a write transaction
  62466. ** on this shared-btree structure and a second write transaction is
  62467. ** requested, return SQLITE_LOCKED.
  62468. */
  62469. if( (wrflag && pBt->inTransaction==TRANS_WRITE)
  62470. || (pBt->btsFlags & BTS_PENDING)!=0
  62471. ){
  62472. pBlock = pBt->pWriter->db;
  62473. }else if( wrflag>1 ){
  62474. BtLock *pIter;
  62475. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  62476. if( pIter->pBtree!=p ){
  62477. pBlock = pIter->pBtree->db;
  62478. break;
  62479. }
  62480. }
  62481. }
  62482. if( pBlock ){
  62483. sqlite3ConnectionBlocked(p->db, pBlock);
  62484. rc = SQLITE_LOCKED_SHAREDCACHE;
  62485. goto trans_begun;
  62486. }
  62487. }
  62488. #endif
  62489. /* Any read-only or read-write transaction implies a read-lock on
  62490. ** page 1. So if some other shared-cache client already has a write-lock
  62491. ** on page 1, the transaction cannot be opened. */
  62492. rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
  62493. if( SQLITE_OK!=rc ) goto trans_begun;
  62494. pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
  62495. if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
  62496. do {
  62497. /* Call lockBtree() until either pBt->pPage1 is populated or
  62498. ** lockBtree() returns something other than SQLITE_OK. lockBtree()
  62499. ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
  62500. ** reading page 1 it discovers that the page-size of the database
  62501. ** file is not pBt->pageSize. In this case lockBtree() will update
  62502. ** pBt->pageSize to the page-size of the file on disk.
  62503. */
  62504. while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
  62505. if( rc==SQLITE_OK && wrflag ){
  62506. if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
  62507. rc = SQLITE_READONLY;
  62508. }else{
  62509. rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
  62510. if( rc==SQLITE_OK ){
  62511. rc = newDatabase(pBt);
  62512. }else if( rc==SQLITE_BUSY_SNAPSHOT && pBt->inTransaction==TRANS_NONE ){
  62513. /* if there was no transaction opened when this function was
  62514. ** called and SQLITE_BUSY_SNAPSHOT is returned, change the error
  62515. ** code to SQLITE_BUSY. */
  62516. rc = SQLITE_BUSY;
  62517. }
  62518. }
  62519. }
  62520. if( rc!=SQLITE_OK ){
  62521. unlockBtreeIfUnused(pBt);
  62522. }
  62523. }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
  62524. btreeInvokeBusyHandler(pBt) );
  62525. sqlite3PagerResetLockTimeout(pBt->pPager);
  62526. if( rc==SQLITE_OK ){
  62527. if( p->inTrans==TRANS_NONE ){
  62528. pBt->nTransaction++;
  62529. #ifndef SQLITE_OMIT_SHARED_CACHE
  62530. if( p->sharable ){
  62531. assert( p->lock.pBtree==p && p->lock.iTable==1 );
  62532. p->lock.eLock = READ_LOCK;
  62533. p->lock.pNext = pBt->pLock;
  62534. pBt->pLock = &p->lock;
  62535. }
  62536. #endif
  62537. }
  62538. p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
  62539. if( p->inTrans>pBt->inTransaction ){
  62540. pBt->inTransaction = p->inTrans;
  62541. }
  62542. if( wrflag ){
  62543. MemPage *pPage1 = pBt->pPage1;
  62544. #ifndef SQLITE_OMIT_SHARED_CACHE
  62545. assert( !pBt->pWriter );
  62546. pBt->pWriter = p;
  62547. pBt->btsFlags &= ~BTS_EXCLUSIVE;
  62548. if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
  62549. #endif
  62550. /* If the db-size header field is incorrect (as it may be if an old
  62551. ** client has been writing the database file), update it now. Doing
  62552. ** this sooner rather than later means the database size can safely
  62553. ** re-read the database size from page 1 if a savepoint or transaction
  62554. ** rollback occurs within the transaction.
  62555. */
  62556. if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
  62557. rc = sqlite3PagerWrite(pPage1->pDbPage);
  62558. if( rc==SQLITE_OK ){
  62559. put4byte(&pPage1->aData[28], pBt->nPage);
  62560. }
  62561. }
  62562. }
  62563. }
  62564. trans_begun:
  62565. if( rc==SQLITE_OK ){
  62566. if( pSchemaVersion ){
  62567. *pSchemaVersion = get4byte(&pBt->pPage1->aData[40]);
  62568. }
  62569. if( wrflag ){
  62570. /* This call makes sure that the pager has the correct number of
  62571. ** open savepoints. If the second parameter is greater than 0 and
  62572. ** the sub-journal is not already open, then it will be opened here.
  62573. */
  62574. rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
  62575. }
  62576. }
  62577. btreeIntegrity(p);
  62578. sqlite3BtreeLeave(p);
  62579. return rc;
  62580. }
  62581. #ifndef SQLITE_OMIT_AUTOVACUUM
  62582. /*
  62583. ** Set the pointer-map entries for all children of page pPage. Also, if
  62584. ** pPage contains cells that point to overflow pages, set the pointer
  62585. ** map entries for the overflow pages as well.
  62586. */
  62587. static int setChildPtrmaps(MemPage *pPage){
  62588. int i; /* Counter variable */
  62589. int nCell; /* Number of cells in page pPage */
  62590. int rc; /* Return code */
  62591. BtShared *pBt = pPage->pBt;
  62592. Pgno pgno = pPage->pgno;
  62593. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  62594. rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
  62595. if( rc!=SQLITE_OK ) return rc;
  62596. nCell = pPage->nCell;
  62597. for(i=0; i<nCell; i++){
  62598. u8 *pCell = findCell(pPage, i);
  62599. ptrmapPutOvflPtr(pPage, pPage, pCell, &rc);
  62600. if( !pPage->leaf ){
  62601. Pgno childPgno = get4byte(pCell);
  62602. ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
  62603. }
  62604. }
  62605. if( !pPage->leaf ){
  62606. Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  62607. ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
  62608. }
  62609. return rc;
  62610. }
  62611. /*
  62612. ** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so
  62613. ** that it points to iTo. Parameter eType describes the type of pointer to
  62614. ** be modified, as follows:
  62615. **
  62616. ** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
  62617. ** page of pPage.
  62618. **
  62619. ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
  62620. ** page pointed to by one of the cells on pPage.
  62621. **
  62622. ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
  62623. ** overflow page in the list.
  62624. */
  62625. static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
  62626. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  62627. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  62628. if( eType==PTRMAP_OVERFLOW2 ){
  62629. /* The pointer is always the first 4 bytes of the page in this case. */
  62630. if( get4byte(pPage->aData)!=iFrom ){
  62631. return SQLITE_CORRUPT_PAGE(pPage);
  62632. }
  62633. put4byte(pPage->aData, iTo);
  62634. }else{
  62635. int i;
  62636. int nCell;
  62637. int rc;
  62638. rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
  62639. if( rc ) return rc;
  62640. nCell = pPage->nCell;
  62641. for(i=0; i<nCell; i++){
  62642. u8 *pCell = findCell(pPage, i);
  62643. if( eType==PTRMAP_OVERFLOW1 ){
  62644. CellInfo info;
  62645. pPage->xParseCell(pPage, pCell, &info);
  62646. if( info.nLocal<info.nPayload ){
  62647. if( pCell+info.nSize > pPage->aData+pPage->pBt->usableSize ){
  62648. return SQLITE_CORRUPT_PAGE(pPage);
  62649. }
  62650. if( iFrom==get4byte(pCell+info.nSize-4) ){
  62651. put4byte(pCell+info.nSize-4, iTo);
  62652. break;
  62653. }
  62654. }
  62655. }else{
  62656. if( get4byte(pCell)==iFrom ){
  62657. put4byte(pCell, iTo);
  62658. break;
  62659. }
  62660. }
  62661. }
  62662. if( i==nCell ){
  62663. if( eType!=PTRMAP_BTREE ||
  62664. get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
  62665. return SQLITE_CORRUPT_PAGE(pPage);
  62666. }
  62667. put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
  62668. }
  62669. }
  62670. return SQLITE_OK;
  62671. }
  62672. /*
  62673. ** Move the open database page pDbPage to location iFreePage in the
  62674. ** database. The pDbPage reference remains valid.
  62675. **
  62676. ** The isCommit flag indicates that there is no need to remember that
  62677. ** the journal needs to be sync()ed before database page pDbPage->pgno
  62678. ** can be written to. The caller has already promised not to write to that
  62679. ** page.
  62680. */
  62681. static int relocatePage(
  62682. BtShared *pBt, /* Btree */
  62683. MemPage *pDbPage, /* Open page to move */
  62684. u8 eType, /* Pointer map 'type' entry for pDbPage */
  62685. Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
  62686. Pgno iFreePage, /* The location to move pDbPage to */
  62687. int isCommit /* isCommit flag passed to sqlite3PagerMovepage */
  62688. ){
  62689. MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
  62690. Pgno iDbPage = pDbPage->pgno;
  62691. Pager *pPager = pBt->pPager;
  62692. int rc;
  62693. assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
  62694. eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
  62695. assert( sqlite3_mutex_held(pBt->mutex) );
  62696. assert( pDbPage->pBt==pBt );
  62697. if( iDbPage<3 ) return SQLITE_CORRUPT_BKPT;
  62698. /* Move page iDbPage from its current location to page number iFreePage */
  62699. TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
  62700. iDbPage, iFreePage, iPtrPage, eType));
  62701. rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
  62702. if( rc!=SQLITE_OK ){
  62703. return rc;
  62704. }
  62705. pDbPage->pgno = iFreePage;
  62706. /* If pDbPage was a btree-page, then it may have child pages and/or cells
  62707. ** that point to overflow pages. The pointer map entries for all these
  62708. ** pages need to be changed.
  62709. **
  62710. ** If pDbPage is an overflow page, then the first 4 bytes may store a
  62711. ** pointer to a subsequent overflow page. If this is the case, then
  62712. ** the pointer map needs to be updated for the subsequent overflow page.
  62713. */
  62714. if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
  62715. rc = setChildPtrmaps(pDbPage);
  62716. if( rc!=SQLITE_OK ){
  62717. return rc;
  62718. }
  62719. }else{
  62720. Pgno nextOvfl = get4byte(pDbPage->aData);
  62721. if( nextOvfl!=0 ){
  62722. ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
  62723. if( rc!=SQLITE_OK ){
  62724. return rc;
  62725. }
  62726. }
  62727. }
  62728. /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
  62729. ** that it points at iFreePage. Also fix the pointer map entry for
  62730. ** iPtrPage.
  62731. */
  62732. if( eType!=PTRMAP_ROOTPAGE ){
  62733. rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
  62734. if( rc!=SQLITE_OK ){
  62735. return rc;
  62736. }
  62737. rc = sqlite3PagerWrite(pPtrPage->pDbPage);
  62738. if( rc!=SQLITE_OK ){
  62739. releasePage(pPtrPage);
  62740. return rc;
  62741. }
  62742. rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
  62743. releasePage(pPtrPage);
  62744. if( rc==SQLITE_OK ){
  62745. ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
  62746. }
  62747. }
  62748. return rc;
  62749. }
  62750. /* Forward declaration required by incrVacuumStep(). */
  62751. static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
  62752. /*
  62753. ** Perform a single step of an incremental-vacuum. If successful, return
  62754. ** SQLITE_OK. If there is no work to do (and therefore no point in
  62755. ** calling this function again), return SQLITE_DONE. Or, if an error
  62756. ** occurs, return some other error code.
  62757. **
  62758. ** More specifically, this function attempts to re-organize the database so
  62759. ** that the last page of the file currently in use is no longer in use.
  62760. **
  62761. ** Parameter nFin is the number of pages that this database would contain
  62762. ** were this function called until it returns SQLITE_DONE.
  62763. **
  62764. ** If the bCommit parameter is non-zero, this function assumes that the
  62765. ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
  62766. ** or an error. bCommit is passed true for an auto-vacuum-on-commit
  62767. ** operation, or false for an incremental vacuum.
  62768. */
  62769. static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
  62770. Pgno nFreeList; /* Number of pages still on the free-list */
  62771. int rc;
  62772. assert( sqlite3_mutex_held(pBt->mutex) );
  62773. assert( iLastPg>nFin );
  62774. if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
  62775. u8 eType;
  62776. Pgno iPtrPage;
  62777. nFreeList = get4byte(&pBt->pPage1->aData[36]);
  62778. if( nFreeList==0 ){
  62779. return SQLITE_DONE;
  62780. }
  62781. rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
  62782. if( rc!=SQLITE_OK ){
  62783. return rc;
  62784. }
  62785. if( eType==PTRMAP_ROOTPAGE ){
  62786. return SQLITE_CORRUPT_BKPT;
  62787. }
  62788. if( eType==PTRMAP_FREEPAGE ){
  62789. if( bCommit==0 ){
  62790. /* Remove the page from the files free-list. This is not required
  62791. ** if bCommit is non-zero. In that case, the free-list will be
  62792. ** truncated to zero after this function returns, so it doesn't
  62793. ** matter if it still contains some garbage entries.
  62794. */
  62795. Pgno iFreePg;
  62796. MemPage *pFreePg;
  62797. rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
  62798. if( rc!=SQLITE_OK ){
  62799. return rc;
  62800. }
  62801. assert( iFreePg==iLastPg );
  62802. releasePage(pFreePg);
  62803. }
  62804. } else {
  62805. Pgno iFreePg; /* Index of free page to move pLastPg to */
  62806. MemPage *pLastPg;
  62807. u8 eMode = BTALLOC_ANY; /* Mode parameter for allocateBtreePage() */
  62808. Pgno iNear = 0; /* nearby parameter for allocateBtreePage() */
  62809. rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
  62810. if( rc!=SQLITE_OK ){
  62811. return rc;
  62812. }
  62813. /* If bCommit is zero, this loop runs exactly once and page pLastPg
  62814. ** is swapped with the first free page pulled off the free list.
  62815. **
  62816. ** On the other hand, if bCommit is greater than zero, then keep
  62817. ** looping until a free-page located within the first nFin pages
  62818. ** of the file is found.
  62819. */
  62820. if( bCommit==0 ){
  62821. eMode = BTALLOC_LE;
  62822. iNear = nFin;
  62823. }
  62824. do {
  62825. MemPage *pFreePg;
  62826. rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
  62827. if( rc!=SQLITE_OK ){
  62828. releasePage(pLastPg);
  62829. return rc;
  62830. }
  62831. releasePage(pFreePg);
  62832. }while( bCommit && iFreePg>nFin );
  62833. assert( iFreePg<iLastPg );
  62834. rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
  62835. releasePage(pLastPg);
  62836. if( rc!=SQLITE_OK ){
  62837. return rc;
  62838. }
  62839. }
  62840. }
  62841. if( bCommit==0 ){
  62842. do {
  62843. iLastPg--;
  62844. }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
  62845. pBt->bDoTruncate = 1;
  62846. pBt->nPage = iLastPg;
  62847. }
  62848. return SQLITE_OK;
  62849. }
  62850. /*
  62851. ** The database opened by the first argument is an auto-vacuum database
  62852. ** nOrig pages in size containing nFree free pages. Return the expected
  62853. ** size of the database in pages following an auto-vacuum operation.
  62854. */
  62855. static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
  62856. int nEntry; /* Number of entries on one ptrmap page */
  62857. Pgno nPtrmap; /* Number of PtrMap pages to be freed */
  62858. Pgno nFin; /* Return value */
  62859. nEntry = pBt->usableSize/5;
  62860. nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
  62861. nFin = nOrig - nFree - nPtrmap;
  62862. if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
  62863. nFin--;
  62864. }
  62865. while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
  62866. nFin--;
  62867. }
  62868. return nFin;
  62869. }
  62870. /*
  62871. ** A write-transaction must be opened before calling this function.
  62872. ** It performs a single unit of work towards an incremental vacuum.
  62873. **
  62874. ** If the incremental vacuum is finished after this function has run,
  62875. ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
  62876. ** SQLITE_OK is returned. Otherwise an SQLite error code.
  62877. */
  62878. SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
  62879. int rc;
  62880. BtShared *pBt = p->pBt;
  62881. sqlite3BtreeEnter(p);
  62882. assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
  62883. if( !pBt->autoVacuum ){
  62884. rc = SQLITE_DONE;
  62885. }else{
  62886. Pgno nOrig = btreePagecount(pBt);
  62887. Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
  62888. Pgno nFin = finalDbSize(pBt, nOrig, nFree);
  62889. if( nOrig<nFin ){
  62890. rc = SQLITE_CORRUPT_BKPT;
  62891. }else if( nFree>0 ){
  62892. rc = saveAllCursors(pBt, 0, 0);
  62893. if( rc==SQLITE_OK ){
  62894. invalidateAllOverflowCache(pBt);
  62895. rc = incrVacuumStep(pBt, nFin, nOrig, 0);
  62896. }
  62897. if( rc==SQLITE_OK ){
  62898. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  62899. put4byte(&pBt->pPage1->aData[28], pBt->nPage);
  62900. }
  62901. }else{
  62902. rc = SQLITE_DONE;
  62903. }
  62904. }
  62905. sqlite3BtreeLeave(p);
  62906. return rc;
  62907. }
  62908. /*
  62909. ** This routine is called prior to sqlite3PagerCommit when a transaction
  62910. ** is committed for an auto-vacuum database.
  62911. **
  62912. ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
  62913. ** the database file should be truncated to during the commit process.
  62914. ** i.e. the database has been reorganized so that only the first *pnTrunc
  62915. ** pages are in use.
  62916. */
  62917. static int autoVacuumCommit(BtShared *pBt){
  62918. int rc = SQLITE_OK;
  62919. Pager *pPager = pBt->pPager;
  62920. VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager); )
  62921. assert( sqlite3_mutex_held(pBt->mutex) );
  62922. invalidateAllOverflowCache(pBt);
  62923. assert(pBt->autoVacuum);
  62924. if( !pBt->incrVacuum ){
  62925. Pgno nFin; /* Number of pages in database after autovacuuming */
  62926. Pgno nFree; /* Number of pages on the freelist initially */
  62927. Pgno iFree; /* The next page to be freed */
  62928. Pgno nOrig; /* Database size before freeing */
  62929. nOrig = btreePagecount(pBt);
  62930. if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
  62931. /* It is not possible to create a database for which the final page
  62932. ** is either a pointer-map page or the pending-byte page. If one
  62933. ** is encountered, this indicates corruption.
  62934. */
  62935. return SQLITE_CORRUPT_BKPT;
  62936. }
  62937. nFree = get4byte(&pBt->pPage1->aData[36]);
  62938. nFin = finalDbSize(pBt, nOrig, nFree);
  62939. if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
  62940. if( nFin<nOrig ){
  62941. rc = saveAllCursors(pBt, 0, 0);
  62942. }
  62943. for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
  62944. rc = incrVacuumStep(pBt, nFin, iFree, 1);
  62945. }
  62946. if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
  62947. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  62948. put4byte(&pBt->pPage1->aData[32], 0);
  62949. put4byte(&pBt->pPage1->aData[36], 0);
  62950. put4byte(&pBt->pPage1->aData[28], nFin);
  62951. pBt->bDoTruncate = 1;
  62952. pBt->nPage = nFin;
  62953. }
  62954. if( rc!=SQLITE_OK ){
  62955. sqlite3PagerRollback(pPager);
  62956. }
  62957. }
  62958. assert( nRef>=sqlite3PagerRefcount(pPager) );
  62959. return rc;
  62960. }
  62961. #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
  62962. # define setChildPtrmaps(x) SQLITE_OK
  62963. #endif
  62964. /*
  62965. ** This routine does the first phase of a two-phase commit. This routine
  62966. ** causes a rollback journal to be created (if it does not already exist)
  62967. ** and populated with enough information so that if a power loss occurs
  62968. ** the database can be restored to its original state by playing back
  62969. ** the journal. Then the contents of the journal are flushed out to
  62970. ** the disk. After the journal is safely on oxide, the changes to the
  62971. ** database are written into the database file and flushed to oxide.
  62972. ** At the end of this call, the rollback journal still exists on the
  62973. ** disk and we are still holding all locks, so the transaction has not
  62974. ** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
  62975. ** commit process.
  62976. **
  62977. ** This call is a no-op if no write-transaction is currently active on pBt.
  62978. **
  62979. ** Otherwise, sync the database file for the btree pBt. zMaster points to
  62980. ** the name of a master journal file that should be written into the
  62981. ** individual journal file, or is NULL, indicating no master journal file
  62982. ** (single database transaction).
  62983. **
  62984. ** When this is called, the master journal should already have been
  62985. ** created, populated with this journal pointer and synced to disk.
  62986. **
  62987. ** Once this is routine has returned, the only thing required to commit
  62988. ** the write-transaction for this database file is to delete the journal.
  62989. */
  62990. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
  62991. int rc = SQLITE_OK;
  62992. if( p->inTrans==TRANS_WRITE ){
  62993. BtShared *pBt = p->pBt;
  62994. sqlite3BtreeEnter(p);
  62995. #ifndef SQLITE_OMIT_AUTOVACUUM
  62996. if( pBt->autoVacuum ){
  62997. rc = autoVacuumCommit(pBt);
  62998. if( rc!=SQLITE_OK ){
  62999. sqlite3BtreeLeave(p);
  63000. return rc;
  63001. }
  63002. }
  63003. if( pBt->bDoTruncate ){
  63004. sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
  63005. }
  63006. #endif
  63007. rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
  63008. sqlite3BtreeLeave(p);
  63009. }
  63010. return rc;
  63011. }
  63012. /*
  63013. ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
  63014. ** at the conclusion of a transaction.
  63015. */
  63016. static void btreeEndTransaction(Btree *p){
  63017. BtShared *pBt = p->pBt;
  63018. sqlite3 *db = p->db;
  63019. assert( sqlite3BtreeHoldsMutex(p) );
  63020. #ifndef SQLITE_OMIT_AUTOVACUUM
  63021. pBt->bDoTruncate = 0;
  63022. #endif
  63023. if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
  63024. /* If there are other active statements that belong to this database
  63025. ** handle, downgrade to a read-only transaction. The other statements
  63026. ** may still be reading from the database. */
  63027. downgradeAllSharedCacheTableLocks(p);
  63028. p->inTrans = TRANS_READ;
  63029. }else{
  63030. /* If the handle had any kind of transaction open, decrement the
  63031. ** transaction count of the shared btree. If the transaction count
  63032. ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
  63033. ** call below will unlock the pager. */
  63034. if( p->inTrans!=TRANS_NONE ){
  63035. clearAllSharedCacheTableLocks(p);
  63036. pBt->nTransaction--;
  63037. if( 0==pBt->nTransaction ){
  63038. pBt->inTransaction = TRANS_NONE;
  63039. }
  63040. }
  63041. /* Set the current transaction state to TRANS_NONE and unlock the
  63042. ** pager if this call closed the only read or write transaction. */
  63043. p->inTrans = TRANS_NONE;
  63044. unlockBtreeIfUnused(pBt);
  63045. }
  63046. btreeIntegrity(p);
  63047. }
  63048. /*
  63049. ** Commit the transaction currently in progress.
  63050. **
  63051. ** This routine implements the second phase of a 2-phase commit. The
  63052. ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
  63053. ** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
  63054. ** routine did all the work of writing information out to disk and flushing the
  63055. ** contents so that they are written onto the disk platter. All this
  63056. ** routine has to do is delete or truncate or zero the header in the
  63057. ** the rollback journal (which causes the transaction to commit) and
  63058. ** drop locks.
  63059. **
  63060. ** Normally, if an error occurs while the pager layer is attempting to
  63061. ** finalize the underlying journal file, this function returns an error and
  63062. ** the upper layer will attempt a rollback. However, if the second argument
  63063. ** is non-zero then this b-tree transaction is part of a multi-file
  63064. ** transaction. In this case, the transaction has already been committed
  63065. ** (by deleting a master journal file) and the caller will ignore this
  63066. ** functions return code. So, even if an error occurs in the pager layer,
  63067. ** reset the b-tree objects internal state to indicate that the write
  63068. ** transaction has been closed. This is quite safe, as the pager will have
  63069. ** transitioned to the error state.
  63070. **
  63071. ** This will release the write lock on the database file. If there
  63072. ** are no active cursors, it also releases the read lock.
  63073. */
  63074. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
  63075. if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
  63076. sqlite3BtreeEnter(p);
  63077. btreeIntegrity(p);
  63078. /* If the handle has a write-transaction open, commit the shared-btrees
  63079. ** transaction and set the shared state to TRANS_READ.
  63080. */
  63081. if( p->inTrans==TRANS_WRITE ){
  63082. int rc;
  63083. BtShared *pBt = p->pBt;
  63084. assert( pBt->inTransaction==TRANS_WRITE );
  63085. assert( pBt->nTransaction>0 );
  63086. rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
  63087. if( rc!=SQLITE_OK && bCleanup==0 ){
  63088. sqlite3BtreeLeave(p);
  63089. return rc;
  63090. }
  63091. p->iDataVersion--; /* Compensate for pPager->iDataVersion++; */
  63092. pBt->inTransaction = TRANS_READ;
  63093. btreeClearHasContent(pBt);
  63094. }
  63095. btreeEndTransaction(p);
  63096. sqlite3BtreeLeave(p);
  63097. return SQLITE_OK;
  63098. }
  63099. /*
  63100. ** Do both phases of a commit.
  63101. */
  63102. SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
  63103. int rc;
  63104. sqlite3BtreeEnter(p);
  63105. rc = sqlite3BtreeCommitPhaseOne(p, 0);
  63106. if( rc==SQLITE_OK ){
  63107. rc = sqlite3BtreeCommitPhaseTwo(p, 0);
  63108. }
  63109. sqlite3BtreeLeave(p);
  63110. return rc;
  63111. }
  63112. /*
  63113. ** This routine sets the state to CURSOR_FAULT and the error
  63114. ** code to errCode for every cursor on any BtShared that pBtree
  63115. ** references. Or if the writeOnly flag is set to 1, then only
  63116. ** trip write cursors and leave read cursors unchanged.
  63117. **
  63118. ** Every cursor is a candidate to be tripped, including cursors
  63119. ** that belong to other database connections that happen to be
  63120. ** sharing the cache with pBtree.
  63121. **
  63122. ** This routine gets called when a rollback occurs. If the writeOnly
  63123. ** flag is true, then only write-cursors need be tripped - read-only
  63124. ** cursors save their current positions so that they may continue
  63125. ** following the rollback. Or, if writeOnly is false, all cursors are
  63126. ** tripped. In general, writeOnly is false if the transaction being
  63127. ** rolled back modified the database schema. In this case b-tree root
  63128. ** pages may be moved or deleted from the database altogether, making
  63129. ** it unsafe for read cursors to continue.
  63130. **
  63131. ** If the writeOnly flag is true and an error is encountered while
  63132. ** saving the current position of a read-only cursor, all cursors,
  63133. ** including all read-cursors are tripped.
  63134. **
  63135. ** SQLITE_OK is returned if successful, or if an error occurs while
  63136. ** saving a cursor position, an SQLite error code.
  63137. */
  63138. SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){
  63139. BtCursor *p;
  63140. int rc = SQLITE_OK;
  63141. assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 );
  63142. if( pBtree ){
  63143. sqlite3BtreeEnter(pBtree);
  63144. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  63145. if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){
  63146. if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
  63147. rc = saveCursorPosition(p);
  63148. if( rc!=SQLITE_OK ){
  63149. (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0);
  63150. break;
  63151. }
  63152. }
  63153. }else{
  63154. sqlite3BtreeClearCursor(p);
  63155. p->eState = CURSOR_FAULT;
  63156. p->skipNext = errCode;
  63157. }
  63158. btreeReleaseAllCursorPages(p);
  63159. }
  63160. sqlite3BtreeLeave(pBtree);
  63161. }
  63162. return rc;
  63163. }
  63164. /*
  63165. ** Set the pBt->nPage field correctly, according to the current
  63166. ** state of the database. Assume pBt->pPage1 is valid.
  63167. */
  63168. static void btreeSetNPage(BtShared *pBt, MemPage *pPage1){
  63169. int nPage = get4byte(&pPage1->aData[28]);
  63170. testcase( nPage==0 );
  63171. if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
  63172. testcase( pBt->nPage!=nPage );
  63173. pBt->nPage = nPage;
  63174. }
  63175. /*
  63176. ** Rollback the transaction in progress.
  63177. **
  63178. ** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped).
  63179. ** Only write cursors are tripped if writeOnly is true but all cursors are
  63180. ** tripped if writeOnly is false. Any attempt to use
  63181. ** a tripped cursor will result in an error.
  63182. **
  63183. ** This will release the write lock on the database file. If there
  63184. ** are no active cursors, it also releases the read lock.
  63185. */
  63186. SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){
  63187. int rc;
  63188. BtShared *pBt = p->pBt;
  63189. MemPage *pPage1;
  63190. assert( writeOnly==1 || writeOnly==0 );
  63191. assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK );
  63192. sqlite3BtreeEnter(p);
  63193. if( tripCode==SQLITE_OK ){
  63194. rc = tripCode = saveAllCursors(pBt, 0, 0);
  63195. if( rc ) writeOnly = 0;
  63196. }else{
  63197. rc = SQLITE_OK;
  63198. }
  63199. if( tripCode ){
  63200. int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly);
  63201. assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) );
  63202. if( rc2!=SQLITE_OK ) rc = rc2;
  63203. }
  63204. btreeIntegrity(p);
  63205. if( p->inTrans==TRANS_WRITE ){
  63206. int rc2;
  63207. assert( TRANS_WRITE==pBt->inTransaction );
  63208. rc2 = sqlite3PagerRollback(pBt->pPager);
  63209. if( rc2!=SQLITE_OK ){
  63210. rc = rc2;
  63211. }
  63212. /* The rollback may have destroyed the pPage1->aData value. So
  63213. ** call btreeGetPage() on page 1 again to make
  63214. ** sure pPage1->aData is set correctly. */
  63215. if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
  63216. btreeSetNPage(pBt, pPage1);
  63217. releasePageOne(pPage1);
  63218. }
  63219. assert( countValidCursors(pBt, 1)==0 );
  63220. pBt->inTransaction = TRANS_READ;
  63221. btreeClearHasContent(pBt);
  63222. }
  63223. btreeEndTransaction(p);
  63224. sqlite3BtreeLeave(p);
  63225. return rc;
  63226. }
  63227. /*
  63228. ** Start a statement subtransaction. The subtransaction can be rolled
  63229. ** back independently of the main transaction. You must start a transaction
  63230. ** before starting a subtransaction. The subtransaction is ended automatically
  63231. ** if the main transaction commits or rolls back.
  63232. **
  63233. ** Statement subtransactions are used around individual SQL statements
  63234. ** that are contained within a BEGIN...COMMIT block. If a constraint
  63235. ** error occurs within the statement, the effect of that one statement
  63236. ** can be rolled back without having to rollback the entire transaction.
  63237. **
  63238. ** A statement sub-transaction is implemented as an anonymous savepoint. The
  63239. ** value passed as the second parameter is the total number of savepoints,
  63240. ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
  63241. ** are no active savepoints and no other statement-transactions open,
  63242. ** iStatement is 1. This anonymous savepoint can be released or rolled back
  63243. ** using the sqlite3BtreeSavepoint() function.
  63244. */
  63245. SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
  63246. int rc;
  63247. BtShared *pBt = p->pBt;
  63248. sqlite3BtreeEnter(p);
  63249. assert( p->inTrans==TRANS_WRITE );
  63250. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  63251. assert( iStatement>0 );
  63252. assert( iStatement>p->db->nSavepoint );
  63253. assert( pBt->inTransaction==TRANS_WRITE );
  63254. /* At the pager level, a statement transaction is a savepoint with
  63255. ** an index greater than all savepoints created explicitly using
  63256. ** SQL statements. It is illegal to open, release or rollback any
  63257. ** such savepoints while the statement transaction savepoint is active.
  63258. */
  63259. rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
  63260. sqlite3BtreeLeave(p);
  63261. return rc;
  63262. }
  63263. /*
  63264. ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
  63265. ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
  63266. ** savepoint identified by parameter iSavepoint, depending on the value
  63267. ** of op.
  63268. **
  63269. ** Normally, iSavepoint is greater than or equal to zero. However, if op is
  63270. ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
  63271. ** contents of the entire transaction are rolled back. This is different
  63272. ** from a normal transaction rollback, as no locks are released and the
  63273. ** transaction remains open.
  63274. */
  63275. SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
  63276. int rc = SQLITE_OK;
  63277. if( p && p->inTrans==TRANS_WRITE ){
  63278. BtShared *pBt = p->pBt;
  63279. assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
  63280. assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
  63281. sqlite3BtreeEnter(p);
  63282. if( op==SAVEPOINT_ROLLBACK ){
  63283. rc = saveAllCursors(pBt, 0, 0);
  63284. }
  63285. if( rc==SQLITE_OK ){
  63286. rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
  63287. }
  63288. if( rc==SQLITE_OK ){
  63289. if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
  63290. pBt->nPage = 0;
  63291. }
  63292. rc = newDatabase(pBt);
  63293. btreeSetNPage(pBt, pBt->pPage1);
  63294. /* pBt->nPage might be zero if the database was corrupt when
  63295. ** the transaction was started. Otherwise, it must be at least 1. */
  63296. assert( CORRUPT_DB || pBt->nPage>0 );
  63297. }
  63298. sqlite3BtreeLeave(p);
  63299. }
  63300. return rc;
  63301. }
  63302. /*
  63303. ** Create a new cursor for the BTree whose root is on the page
  63304. ** iTable. If a read-only cursor is requested, it is assumed that
  63305. ** the caller already has at least a read-only transaction open
  63306. ** on the database already. If a write-cursor is requested, then
  63307. ** the caller is assumed to have an open write transaction.
  63308. **
  63309. ** If the BTREE_WRCSR bit of wrFlag is clear, then the cursor can only
  63310. ** be used for reading. If the BTREE_WRCSR bit is set, then the cursor
  63311. ** can be used for reading or for writing if other conditions for writing
  63312. ** are also met. These are the conditions that must be met in order
  63313. ** for writing to be allowed:
  63314. **
  63315. ** 1: The cursor must have been opened with wrFlag containing BTREE_WRCSR
  63316. **
  63317. ** 2: Other database connections that share the same pager cache
  63318. ** but which are not in the READ_UNCOMMITTED state may not have
  63319. ** cursors open with wrFlag==0 on the same table. Otherwise
  63320. ** the changes made by this write cursor would be visible to
  63321. ** the read cursors in the other database connection.
  63322. **
  63323. ** 3: The database must be writable (not on read-only media)
  63324. **
  63325. ** 4: There must be an active transaction.
  63326. **
  63327. ** The BTREE_FORDELETE bit of wrFlag may optionally be set if BTREE_WRCSR
  63328. ** is set. If FORDELETE is set, that is a hint to the implementation that
  63329. ** this cursor will only be used to seek to and delete entries of an index
  63330. ** as part of a larger DELETE statement. The FORDELETE hint is not used by
  63331. ** this implementation. But in a hypothetical alternative storage engine
  63332. ** in which index entries are automatically deleted when corresponding table
  63333. ** rows are deleted, the FORDELETE flag is a hint that all SEEK and DELETE
  63334. ** operations on this cursor can be no-ops and all READ operations can
  63335. ** return a null row (2-bytes: 0x01 0x00).
  63336. **
  63337. ** No checking is done to make sure that page iTable really is the
  63338. ** root page of a b-tree. If it is not, then the cursor acquired
  63339. ** will not work correctly.
  63340. **
  63341. ** It is assumed that the sqlite3BtreeCursorZero() has been called
  63342. ** on pCur to initialize the memory space prior to invoking this routine.
  63343. */
  63344. static int btreeCursor(
  63345. Btree *p, /* The btree */
  63346. int iTable, /* Root page of table to open */
  63347. int wrFlag, /* 1 to write. 0 read-only */
  63348. struct KeyInfo *pKeyInfo, /* First arg to comparison function */
  63349. BtCursor *pCur /* Space for new cursor */
  63350. ){
  63351. BtShared *pBt = p->pBt; /* Shared b-tree handle */
  63352. BtCursor *pX; /* Looping over other all cursors */
  63353. assert( sqlite3BtreeHoldsMutex(p) );
  63354. assert( wrFlag==0
  63355. || wrFlag==BTREE_WRCSR
  63356. || wrFlag==(BTREE_WRCSR|BTREE_FORDELETE)
  63357. );
  63358. /* The following assert statements verify that if this is a sharable
  63359. ** b-tree database, the connection is holding the required table locks,
  63360. ** and that no other connection has any open cursor that conflicts with
  63361. ** this lock. */
  63362. assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, (wrFlag?2:1)) );
  63363. assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
  63364. /* Assert that the caller has opened the required transaction. */
  63365. assert( p->inTrans>TRANS_NONE );
  63366. assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
  63367. assert( pBt->pPage1 && pBt->pPage1->aData );
  63368. assert( wrFlag==0 || (pBt->btsFlags & BTS_READ_ONLY)==0 );
  63369. if( wrFlag ){
  63370. allocateTempSpace(pBt);
  63371. if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM_BKPT;
  63372. }
  63373. if( iTable==1 && btreePagecount(pBt)==0 ){
  63374. assert( wrFlag==0 );
  63375. iTable = 0;
  63376. }
  63377. /* Now that no other errors can occur, finish filling in the BtCursor
  63378. ** variables and link the cursor into the BtShared list. */
  63379. pCur->pgnoRoot = (Pgno)iTable;
  63380. pCur->iPage = -1;
  63381. pCur->pKeyInfo = pKeyInfo;
  63382. pCur->pBtree = p;
  63383. pCur->pBt = pBt;
  63384. pCur->curFlags = wrFlag ? BTCF_WriteFlag : 0;
  63385. pCur->curPagerFlags = wrFlag ? 0 : PAGER_GET_READONLY;
  63386. /* If there are two or more cursors on the same btree, then all such
  63387. ** cursors *must* have the BTCF_Multiple flag set. */
  63388. for(pX=pBt->pCursor; pX; pX=pX->pNext){
  63389. if( pX->pgnoRoot==(Pgno)iTable ){
  63390. pX->curFlags |= BTCF_Multiple;
  63391. pCur->curFlags |= BTCF_Multiple;
  63392. }
  63393. }
  63394. pCur->pNext = pBt->pCursor;
  63395. pBt->pCursor = pCur;
  63396. pCur->eState = CURSOR_INVALID;
  63397. return SQLITE_OK;
  63398. }
  63399. SQLITE_PRIVATE int sqlite3BtreeCursor(
  63400. Btree *p, /* The btree */
  63401. int iTable, /* Root page of table to open */
  63402. int wrFlag, /* 1 to write. 0 read-only */
  63403. struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
  63404. BtCursor *pCur /* Write new cursor here */
  63405. ){
  63406. int rc;
  63407. if( iTable<1 ){
  63408. rc = SQLITE_CORRUPT_BKPT;
  63409. }else{
  63410. sqlite3BtreeEnter(p);
  63411. rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
  63412. sqlite3BtreeLeave(p);
  63413. }
  63414. return rc;
  63415. }
  63416. /*
  63417. ** Return the size of a BtCursor object in bytes.
  63418. **
  63419. ** This interfaces is needed so that users of cursors can preallocate
  63420. ** sufficient storage to hold a cursor. The BtCursor object is opaque
  63421. ** to users so they cannot do the sizeof() themselves - they must call
  63422. ** this routine.
  63423. */
  63424. SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
  63425. return ROUND8(sizeof(BtCursor));
  63426. }
  63427. /*
  63428. ** Initialize memory that will be converted into a BtCursor object.
  63429. **
  63430. ** The simple approach here would be to memset() the entire object
  63431. ** to zero. But it turns out that the apPage[] and aiIdx[] arrays
  63432. ** do not need to be zeroed and they are large, so we can save a lot
  63433. ** of run-time by skipping the initialization of those elements.
  63434. */
  63435. SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
  63436. memset(p, 0, offsetof(BtCursor, BTCURSOR_FIRST_UNINIT));
  63437. }
  63438. /*
  63439. ** Close a cursor. The read lock on the database file is released
  63440. ** when the last cursor is closed.
  63441. */
  63442. SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
  63443. Btree *pBtree = pCur->pBtree;
  63444. if( pBtree ){
  63445. BtShared *pBt = pCur->pBt;
  63446. sqlite3BtreeEnter(pBtree);
  63447. assert( pBt->pCursor!=0 );
  63448. if( pBt->pCursor==pCur ){
  63449. pBt->pCursor = pCur->pNext;
  63450. }else{
  63451. BtCursor *pPrev = pBt->pCursor;
  63452. do{
  63453. if( pPrev->pNext==pCur ){
  63454. pPrev->pNext = pCur->pNext;
  63455. break;
  63456. }
  63457. pPrev = pPrev->pNext;
  63458. }while( ALWAYS(pPrev) );
  63459. }
  63460. btreeReleaseAllCursorPages(pCur);
  63461. unlockBtreeIfUnused(pBt);
  63462. sqlite3_free(pCur->aOverflow);
  63463. sqlite3_free(pCur->pKey);
  63464. sqlite3BtreeLeave(pBtree);
  63465. pCur->pBtree = 0;
  63466. }
  63467. return SQLITE_OK;
  63468. }
  63469. /*
  63470. ** Make sure the BtCursor* given in the argument has a valid
  63471. ** BtCursor.info structure. If it is not already valid, call
  63472. ** btreeParseCell() to fill it in.
  63473. **
  63474. ** BtCursor.info is a cache of the information in the current cell.
  63475. ** Using this cache reduces the number of calls to btreeParseCell().
  63476. */
  63477. #ifndef NDEBUG
  63478. static int cellInfoEqual(CellInfo *a, CellInfo *b){
  63479. if( a->nKey!=b->nKey ) return 0;
  63480. if( a->pPayload!=b->pPayload ) return 0;
  63481. if( a->nPayload!=b->nPayload ) return 0;
  63482. if( a->nLocal!=b->nLocal ) return 0;
  63483. if( a->nSize!=b->nSize ) return 0;
  63484. return 1;
  63485. }
  63486. static void assertCellInfo(BtCursor *pCur){
  63487. CellInfo info;
  63488. memset(&info, 0, sizeof(info));
  63489. btreeParseCell(pCur->pPage, pCur->ix, &info);
  63490. assert( CORRUPT_DB || cellInfoEqual(&info, &pCur->info) );
  63491. }
  63492. #else
  63493. #define assertCellInfo(x)
  63494. #endif
  63495. static SQLITE_NOINLINE void getCellInfo(BtCursor *pCur){
  63496. if( pCur->info.nSize==0 ){
  63497. pCur->curFlags |= BTCF_ValidNKey;
  63498. btreeParseCell(pCur->pPage,pCur->ix,&pCur->info);
  63499. }else{
  63500. assertCellInfo(pCur);
  63501. }
  63502. }
  63503. #ifndef NDEBUG /* The next routine used only within assert() statements */
  63504. /*
  63505. ** Return true if the given BtCursor is valid. A valid cursor is one
  63506. ** that is currently pointing to a row in a (non-empty) table.
  63507. ** This is a verification routine is used only within assert() statements.
  63508. */
  63509. SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
  63510. return pCur && pCur->eState==CURSOR_VALID;
  63511. }
  63512. #endif /* NDEBUG */
  63513. SQLITE_PRIVATE int sqlite3BtreeCursorIsValidNN(BtCursor *pCur){
  63514. assert( pCur!=0 );
  63515. return pCur->eState==CURSOR_VALID;
  63516. }
  63517. /*
  63518. ** Return the value of the integer key or "rowid" for a table btree.
  63519. ** This routine is only valid for a cursor that is pointing into a
  63520. ** ordinary table btree. If the cursor points to an index btree or
  63521. ** is invalid, the result of this routine is undefined.
  63522. */
  63523. SQLITE_PRIVATE i64 sqlite3BtreeIntegerKey(BtCursor *pCur){
  63524. assert( cursorHoldsMutex(pCur) );
  63525. assert( pCur->eState==CURSOR_VALID );
  63526. assert( pCur->curIntKey );
  63527. getCellInfo(pCur);
  63528. return pCur->info.nKey;
  63529. }
  63530. #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
  63531. /*
  63532. ** Return the offset into the database file for the start of the
  63533. ** payload to which the cursor is pointing.
  63534. */
  63535. SQLITE_PRIVATE i64 sqlite3BtreeOffset(BtCursor *pCur){
  63536. assert( cursorHoldsMutex(pCur) );
  63537. assert( pCur->eState==CURSOR_VALID );
  63538. getCellInfo(pCur);
  63539. return (i64)pCur->pBt->pageSize*((i64)pCur->pPage->pgno - 1) +
  63540. (i64)(pCur->info.pPayload - pCur->pPage->aData);
  63541. }
  63542. #endif /* SQLITE_ENABLE_OFFSET_SQL_FUNC */
  63543. /*
  63544. ** Return the number of bytes of payload for the entry that pCur is
  63545. ** currently pointing to. For table btrees, this will be the amount
  63546. ** of data. For index btrees, this will be the size of the key.
  63547. **
  63548. ** The caller must guarantee that the cursor is pointing to a non-NULL
  63549. ** valid entry. In other words, the calling procedure must guarantee
  63550. ** that the cursor has Cursor.eState==CURSOR_VALID.
  63551. */
  63552. SQLITE_PRIVATE u32 sqlite3BtreePayloadSize(BtCursor *pCur){
  63553. assert( cursorHoldsMutex(pCur) );
  63554. assert( pCur->eState==CURSOR_VALID );
  63555. getCellInfo(pCur);
  63556. return pCur->info.nPayload;
  63557. }
  63558. /*
  63559. ** Return an upper bound on the size of any record for the table
  63560. ** that the cursor is pointing into.
  63561. **
  63562. ** This is an optimization. Everything will still work if this
  63563. ** routine always returns 2147483647 (which is the largest record
  63564. ** that SQLite can handle) or more. But returning a smaller value might
  63565. ** prevent large memory allocations when trying to interpret a
  63566. ** corrupt datrabase.
  63567. **
  63568. ** The current implementation merely returns the size of the underlying
  63569. ** database file.
  63570. */
  63571. SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeMaxRecordSize(BtCursor *pCur){
  63572. assert( cursorHoldsMutex(pCur) );
  63573. assert( pCur->eState==CURSOR_VALID );
  63574. return pCur->pBt->pageSize * (sqlite3_int64)pCur->pBt->nPage;
  63575. }
  63576. /*
  63577. ** Given the page number of an overflow page in the database (parameter
  63578. ** ovfl), this function finds the page number of the next page in the
  63579. ** linked list of overflow pages. If possible, it uses the auto-vacuum
  63580. ** pointer-map data instead of reading the content of page ovfl to do so.
  63581. **
  63582. ** If an error occurs an SQLite error code is returned. Otherwise:
  63583. **
  63584. ** The page number of the next overflow page in the linked list is
  63585. ** written to *pPgnoNext. If page ovfl is the last page in its linked
  63586. ** list, *pPgnoNext is set to zero.
  63587. **
  63588. ** If ppPage is not NULL, and a reference to the MemPage object corresponding
  63589. ** to page number pOvfl was obtained, then *ppPage is set to point to that
  63590. ** reference. It is the responsibility of the caller to call releasePage()
  63591. ** on *ppPage to free the reference. In no reference was obtained (because
  63592. ** the pointer-map was used to obtain the value for *pPgnoNext), then
  63593. ** *ppPage is set to zero.
  63594. */
  63595. static int getOverflowPage(
  63596. BtShared *pBt, /* The database file */
  63597. Pgno ovfl, /* Current overflow page number */
  63598. MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */
  63599. Pgno *pPgnoNext /* OUT: Next overflow page number */
  63600. ){
  63601. Pgno next = 0;
  63602. MemPage *pPage = 0;
  63603. int rc = SQLITE_OK;
  63604. assert( sqlite3_mutex_held(pBt->mutex) );
  63605. assert(pPgnoNext);
  63606. #ifndef SQLITE_OMIT_AUTOVACUUM
  63607. /* Try to find the next page in the overflow list using the
  63608. ** autovacuum pointer-map pages. Guess that the next page in
  63609. ** the overflow list is page number (ovfl+1). If that guess turns
  63610. ** out to be wrong, fall back to loading the data of page
  63611. ** number ovfl to determine the next page number.
  63612. */
  63613. if( pBt->autoVacuum ){
  63614. Pgno pgno;
  63615. Pgno iGuess = ovfl+1;
  63616. u8 eType;
  63617. while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
  63618. iGuess++;
  63619. }
  63620. if( iGuess<=btreePagecount(pBt) ){
  63621. rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
  63622. if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
  63623. next = iGuess;
  63624. rc = SQLITE_DONE;
  63625. }
  63626. }
  63627. }
  63628. #endif
  63629. assert( next==0 || rc==SQLITE_DONE );
  63630. if( rc==SQLITE_OK ){
  63631. rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
  63632. assert( rc==SQLITE_OK || pPage==0 );
  63633. if( rc==SQLITE_OK ){
  63634. next = get4byte(pPage->aData);
  63635. }
  63636. }
  63637. *pPgnoNext = next;
  63638. if( ppPage ){
  63639. *ppPage = pPage;
  63640. }else{
  63641. releasePage(pPage);
  63642. }
  63643. return (rc==SQLITE_DONE ? SQLITE_OK : rc);
  63644. }
  63645. /*
  63646. ** Copy data from a buffer to a page, or from a page to a buffer.
  63647. **
  63648. ** pPayload is a pointer to data stored on database page pDbPage.
  63649. ** If argument eOp is false, then nByte bytes of data are copied
  63650. ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
  63651. ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
  63652. ** of data are copied from the buffer pBuf to pPayload.
  63653. **
  63654. ** SQLITE_OK is returned on success, otherwise an error code.
  63655. */
  63656. static int copyPayload(
  63657. void *pPayload, /* Pointer to page data */
  63658. void *pBuf, /* Pointer to buffer */
  63659. int nByte, /* Number of bytes to copy */
  63660. int eOp, /* 0 -> copy from page, 1 -> copy to page */
  63661. DbPage *pDbPage /* Page containing pPayload */
  63662. ){
  63663. if( eOp ){
  63664. /* Copy data from buffer to page (a write operation) */
  63665. int rc = sqlite3PagerWrite(pDbPage);
  63666. if( rc!=SQLITE_OK ){
  63667. return rc;
  63668. }
  63669. memcpy(pPayload, pBuf, nByte);
  63670. }else{
  63671. /* Copy data from page to buffer (a read operation) */
  63672. memcpy(pBuf, pPayload, nByte);
  63673. }
  63674. return SQLITE_OK;
  63675. }
  63676. /*
  63677. ** This function is used to read or overwrite payload information
  63678. ** for the entry that the pCur cursor is pointing to. The eOp
  63679. ** argument is interpreted as follows:
  63680. **
  63681. ** 0: The operation is a read. Populate the overflow cache.
  63682. ** 1: The operation is a write. Populate the overflow cache.
  63683. **
  63684. ** A total of "amt" bytes are read or written beginning at "offset".
  63685. ** Data is read to or from the buffer pBuf.
  63686. **
  63687. ** The content being read or written might appear on the main page
  63688. ** or be scattered out on multiple overflow pages.
  63689. **
  63690. ** If the current cursor entry uses one or more overflow pages
  63691. ** this function may allocate space for and lazily populate
  63692. ** the overflow page-list cache array (BtCursor.aOverflow).
  63693. ** Subsequent calls use this cache to make seeking to the supplied offset
  63694. ** more efficient.
  63695. **
  63696. ** Once an overflow page-list cache has been allocated, it must be
  63697. ** invalidated if some other cursor writes to the same table, or if
  63698. ** the cursor is moved to a different row. Additionally, in auto-vacuum
  63699. ** mode, the following events may invalidate an overflow page-list cache.
  63700. **
  63701. ** * An incremental vacuum,
  63702. ** * A commit in auto_vacuum="full" mode,
  63703. ** * Creating a table (may require moving an overflow page).
  63704. */
  63705. static int accessPayload(
  63706. BtCursor *pCur, /* Cursor pointing to entry to read from */
  63707. u32 offset, /* Begin reading this far into payload */
  63708. u32 amt, /* Read this many bytes */
  63709. unsigned char *pBuf, /* Write the bytes into this buffer */
  63710. int eOp /* zero to read. non-zero to write. */
  63711. ){
  63712. unsigned char *aPayload;
  63713. int rc = SQLITE_OK;
  63714. int iIdx = 0;
  63715. MemPage *pPage = pCur->pPage; /* Btree page of current entry */
  63716. BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
  63717. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  63718. unsigned char * const pBufStart = pBuf; /* Start of original out buffer */
  63719. #endif
  63720. assert( pPage );
  63721. assert( eOp==0 || eOp==1 );
  63722. assert( pCur->eState==CURSOR_VALID );
  63723. assert( pCur->ix<pPage->nCell );
  63724. assert( cursorHoldsMutex(pCur) );
  63725. getCellInfo(pCur);
  63726. aPayload = pCur->info.pPayload;
  63727. assert( offset+amt <= pCur->info.nPayload );
  63728. assert( aPayload > pPage->aData );
  63729. if( (uptr)(aPayload - pPage->aData) > (pBt->usableSize - pCur->info.nLocal) ){
  63730. /* Trying to read or write past the end of the data is an error. The
  63731. ** conditional above is really:
  63732. ** &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
  63733. ** but is recast into its current form to avoid integer overflow problems
  63734. */
  63735. return SQLITE_CORRUPT_PAGE(pPage);
  63736. }
  63737. /* Check if data must be read/written to/from the btree page itself. */
  63738. if( offset<pCur->info.nLocal ){
  63739. int a = amt;
  63740. if( a+offset>pCur->info.nLocal ){
  63741. a = pCur->info.nLocal - offset;
  63742. }
  63743. rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
  63744. offset = 0;
  63745. pBuf += a;
  63746. amt -= a;
  63747. }else{
  63748. offset -= pCur->info.nLocal;
  63749. }
  63750. if( rc==SQLITE_OK && amt>0 ){
  63751. const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
  63752. Pgno nextPage;
  63753. nextPage = get4byte(&aPayload[pCur->info.nLocal]);
  63754. /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
  63755. **
  63756. ** The aOverflow[] array is sized at one entry for each overflow page
  63757. ** in the overflow chain. The page number of the first overflow page is
  63758. ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
  63759. ** means "not yet known" (the cache is lazily populated).
  63760. */
  63761. if( (pCur->curFlags & BTCF_ValidOvfl)==0 ){
  63762. int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
  63763. if( pCur->aOverflow==0
  63764. || nOvfl*(int)sizeof(Pgno) > sqlite3MallocSize(pCur->aOverflow)
  63765. ){
  63766. Pgno *aNew = (Pgno*)sqlite3Realloc(
  63767. pCur->aOverflow, nOvfl*2*sizeof(Pgno)
  63768. );
  63769. if( aNew==0 ){
  63770. return SQLITE_NOMEM_BKPT;
  63771. }else{
  63772. pCur->aOverflow = aNew;
  63773. }
  63774. }
  63775. memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
  63776. pCur->curFlags |= BTCF_ValidOvfl;
  63777. }else{
  63778. /* If the overflow page-list cache has been allocated and the
  63779. ** entry for the first required overflow page is valid, skip
  63780. ** directly to it.
  63781. */
  63782. if( pCur->aOverflow[offset/ovflSize] ){
  63783. iIdx = (offset/ovflSize);
  63784. nextPage = pCur->aOverflow[iIdx];
  63785. offset = (offset%ovflSize);
  63786. }
  63787. }
  63788. assert( rc==SQLITE_OK && amt>0 );
  63789. while( nextPage ){
  63790. /* If required, populate the overflow page-list cache. */
  63791. assert( pCur->aOverflow[iIdx]==0
  63792. || pCur->aOverflow[iIdx]==nextPage
  63793. || CORRUPT_DB );
  63794. pCur->aOverflow[iIdx] = nextPage;
  63795. if( offset>=ovflSize ){
  63796. /* The only reason to read this page is to obtain the page
  63797. ** number for the next page in the overflow chain. The page
  63798. ** data is not required. So first try to lookup the overflow
  63799. ** page-list cache, if any, then fall back to the getOverflowPage()
  63800. ** function.
  63801. */
  63802. assert( pCur->curFlags & BTCF_ValidOvfl );
  63803. assert( pCur->pBtree->db==pBt->db );
  63804. if( pCur->aOverflow[iIdx+1] ){
  63805. nextPage = pCur->aOverflow[iIdx+1];
  63806. }else{
  63807. rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
  63808. }
  63809. offset -= ovflSize;
  63810. }else{
  63811. /* Need to read this page properly. It contains some of the
  63812. ** range of data that is being read (eOp==0) or written (eOp!=0).
  63813. */
  63814. int a = amt;
  63815. if( a + offset > ovflSize ){
  63816. a = ovflSize - offset;
  63817. }
  63818. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  63819. /* If all the following are true:
  63820. **
  63821. ** 1) this is a read operation, and
  63822. ** 2) data is required from the start of this overflow page, and
  63823. ** 3) there are no dirty pages in the page-cache
  63824. ** 4) the database is file-backed, and
  63825. ** 5) the page is not in the WAL file
  63826. ** 6) at least 4 bytes have already been read into the output buffer
  63827. **
  63828. ** then data can be read directly from the database file into the
  63829. ** output buffer, bypassing the page-cache altogether. This speeds
  63830. ** up loading large records that span many overflow pages.
  63831. */
  63832. if( eOp==0 /* (1) */
  63833. && offset==0 /* (2) */
  63834. && sqlite3PagerDirectReadOk(pBt->pPager, nextPage) /* (3,4,5) */
  63835. && &pBuf[-4]>=pBufStart /* (6) */
  63836. ){
  63837. sqlite3_file *fd = sqlite3PagerFile(pBt->pPager);
  63838. u8 aSave[4];
  63839. u8 *aWrite = &pBuf[-4];
  63840. assert( aWrite>=pBufStart ); /* due to (6) */
  63841. memcpy(aSave, aWrite, 4);
  63842. rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
  63843. nextPage = get4byte(aWrite);
  63844. memcpy(aWrite, aSave, 4);
  63845. }else
  63846. #endif
  63847. {
  63848. DbPage *pDbPage;
  63849. rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage,
  63850. (eOp==0 ? PAGER_GET_READONLY : 0)
  63851. );
  63852. if( rc==SQLITE_OK ){
  63853. aPayload = sqlite3PagerGetData(pDbPage);
  63854. nextPage = get4byte(aPayload);
  63855. rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
  63856. sqlite3PagerUnref(pDbPage);
  63857. offset = 0;
  63858. }
  63859. }
  63860. amt -= a;
  63861. if( amt==0 ) return rc;
  63862. pBuf += a;
  63863. }
  63864. if( rc ) break;
  63865. iIdx++;
  63866. }
  63867. }
  63868. if( rc==SQLITE_OK && amt>0 ){
  63869. /* Overflow chain ends prematurely */
  63870. return SQLITE_CORRUPT_PAGE(pPage);
  63871. }
  63872. return rc;
  63873. }
  63874. /*
  63875. ** Read part of the payload for the row at which that cursor pCur is currently
  63876. ** pointing. "amt" bytes will be transferred into pBuf[]. The transfer
  63877. ** begins at "offset".
  63878. **
  63879. ** pCur can be pointing to either a table or an index b-tree.
  63880. ** If pointing to a table btree, then the content section is read. If
  63881. ** pCur is pointing to an index b-tree then the key section is read.
  63882. **
  63883. ** For sqlite3BtreePayload(), the caller must ensure that pCur is pointing
  63884. ** to a valid row in the table. For sqlite3BtreePayloadChecked(), the
  63885. ** cursor might be invalid or might need to be restored before being read.
  63886. **
  63887. ** Return SQLITE_OK on success or an error code if anything goes
  63888. ** wrong. An error is returned if "offset+amt" is larger than
  63889. ** the available payload.
  63890. */
  63891. SQLITE_PRIVATE int sqlite3BtreePayload(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
  63892. assert( cursorHoldsMutex(pCur) );
  63893. assert( pCur->eState==CURSOR_VALID );
  63894. assert( pCur->iPage>=0 && pCur->pPage );
  63895. assert( pCur->ix<pCur->pPage->nCell );
  63896. return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
  63897. }
  63898. /*
  63899. ** This variant of sqlite3BtreePayload() works even if the cursor has not
  63900. ** in the CURSOR_VALID state. It is only used by the sqlite3_blob_read()
  63901. ** interface.
  63902. */
  63903. #ifndef SQLITE_OMIT_INCRBLOB
  63904. static SQLITE_NOINLINE int accessPayloadChecked(
  63905. BtCursor *pCur,
  63906. u32 offset,
  63907. u32 amt,
  63908. void *pBuf
  63909. ){
  63910. int rc;
  63911. if ( pCur->eState==CURSOR_INVALID ){
  63912. return SQLITE_ABORT;
  63913. }
  63914. assert( cursorOwnsBtShared(pCur) );
  63915. rc = btreeRestoreCursorPosition(pCur);
  63916. return rc ? rc : accessPayload(pCur, offset, amt, pBuf, 0);
  63917. }
  63918. SQLITE_PRIVATE int sqlite3BtreePayloadChecked(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
  63919. if( pCur->eState==CURSOR_VALID ){
  63920. assert( cursorOwnsBtShared(pCur) );
  63921. return accessPayload(pCur, offset, amt, pBuf, 0);
  63922. }else{
  63923. return accessPayloadChecked(pCur, offset, amt, pBuf);
  63924. }
  63925. }
  63926. #endif /* SQLITE_OMIT_INCRBLOB */
  63927. /*
  63928. ** Return a pointer to payload information from the entry that the
  63929. ** pCur cursor is pointing to. The pointer is to the beginning of
  63930. ** the key if index btrees (pPage->intKey==0) and is the data for
  63931. ** table btrees (pPage->intKey==1). The number of bytes of available
  63932. ** key/data is written into *pAmt. If *pAmt==0, then the value
  63933. ** returned will not be a valid pointer.
  63934. **
  63935. ** This routine is an optimization. It is common for the entire key
  63936. ** and data to fit on the local page and for there to be no overflow
  63937. ** pages. When that is so, this routine can be used to access the
  63938. ** key and data without making a copy. If the key and/or data spills
  63939. ** onto overflow pages, then accessPayload() must be used to reassemble
  63940. ** the key/data and copy it into a preallocated buffer.
  63941. **
  63942. ** The pointer returned by this routine looks directly into the cached
  63943. ** page of the database. The data might change or move the next time
  63944. ** any btree routine is called.
  63945. */
  63946. static const void *fetchPayload(
  63947. BtCursor *pCur, /* Cursor pointing to entry to read from */
  63948. u32 *pAmt /* Write the number of available bytes here */
  63949. ){
  63950. int amt;
  63951. assert( pCur!=0 && pCur->iPage>=0 && pCur->pPage);
  63952. assert( pCur->eState==CURSOR_VALID );
  63953. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  63954. assert( cursorOwnsBtShared(pCur) );
  63955. assert( pCur->ix<pCur->pPage->nCell );
  63956. assert( pCur->info.nSize>0 );
  63957. assert( pCur->info.pPayload>pCur->pPage->aData || CORRUPT_DB );
  63958. assert( pCur->info.pPayload<pCur->pPage->aDataEnd ||CORRUPT_DB);
  63959. amt = pCur->info.nLocal;
  63960. if( amt>(int)(pCur->pPage->aDataEnd - pCur->info.pPayload) ){
  63961. /* There is too little space on the page for the expected amount
  63962. ** of local content. Database must be corrupt. */
  63963. assert( CORRUPT_DB );
  63964. amt = MAX(0, (int)(pCur->pPage->aDataEnd - pCur->info.pPayload));
  63965. }
  63966. *pAmt = (u32)amt;
  63967. return (void*)pCur->info.pPayload;
  63968. }
  63969. /*
  63970. ** For the entry that cursor pCur is point to, return as
  63971. ** many bytes of the key or data as are available on the local
  63972. ** b-tree page. Write the number of available bytes into *pAmt.
  63973. **
  63974. ** The pointer returned is ephemeral. The key/data may move
  63975. ** or be destroyed on the next call to any Btree routine,
  63976. ** including calls from other threads against the same cache.
  63977. ** Hence, a mutex on the BtShared should be held prior to calling
  63978. ** this routine.
  63979. **
  63980. ** These routines is used to get quick access to key and data
  63981. ** in the common case where no overflow pages are used.
  63982. */
  63983. SQLITE_PRIVATE const void *sqlite3BtreePayloadFetch(BtCursor *pCur, u32 *pAmt){
  63984. return fetchPayload(pCur, pAmt);
  63985. }
  63986. /*
  63987. ** Move the cursor down to a new child page. The newPgno argument is the
  63988. ** page number of the child page to move to.
  63989. **
  63990. ** This function returns SQLITE_CORRUPT if the page-header flags field of
  63991. ** the new child page does not match the flags field of the parent (i.e.
  63992. ** if an intkey page appears to be the parent of a non-intkey page, or
  63993. ** vice-versa).
  63994. */
  63995. static int moveToChild(BtCursor *pCur, u32 newPgno){
  63996. BtShared *pBt = pCur->pBt;
  63997. assert( cursorOwnsBtShared(pCur) );
  63998. assert( pCur->eState==CURSOR_VALID );
  63999. assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
  64000. assert( pCur->iPage>=0 );
  64001. if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
  64002. return SQLITE_CORRUPT_BKPT;
  64003. }
  64004. pCur->info.nSize = 0;
  64005. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
  64006. pCur->aiIdx[pCur->iPage] = pCur->ix;
  64007. pCur->apPage[pCur->iPage] = pCur->pPage;
  64008. pCur->ix = 0;
  64009. pCur->iPage++;
  64010. return getAndInitPage(pBt, newPgno, &pCur->pPage, pCur, pCur->curPagerFlags);
  64011. }
  64012. #ifdef SQLITE_DEBUG
  64013. /*
  64014. ** Page pParent is an internal (non-leaf) tree page. This function
  64015. ** asserts that page number iChild is the left-child if the iIdx'th
  64016. ** cell in page pParent. Or, if iIdx is equal to the total number of
  64017. ** cells in pParent, that page number iChild is the right-child of
  64018. ** the page.
  64019. */
  64020. static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
  64021. if( CORRUPT_DB ) return; /* The conditions tested below might not be true
  64022. ** in a corrupt database */
  64023. assert( iIdx<=pParent->nCell );
  64024. if( iIdx==pParent->nCell ){
  64025. assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
  64026. }else{
  64027. assert( get4byte(findCell(pParent, iIdx))==iChild );
  64028. }
  64029. }
  64030. #else
  64031. # define assertParentIndex(x,y,z)
  64032. #endif
  64033. /*
  64034. ** Move the cursor up to the parent page.
  64035. **
  64036. ** pCur->idx is set to the cell index that contains the pointer
  64037. ** to the page we are coming from. If we are coming from the
  64038. ** right-most child page then pCur->idx is set to one more than
  64039. ** the largest cell index.
  64040. */
  64041. static void moveToParent(BtCursor *pCur){
  64042. MemPage *pLeaf;
  64043. assert( cursorOwnsBtShared(pCur) );
  64044. assert( pCur->eState==CURSOR_VALID );
  64045. assert( pCur->iPage>0 );
  64046. assert( pCur->pPage );
  64047. assertParentIndex(
  64048. pCur->apPage[pCur->iPage-1],
  64049. pCur->aiIdx[pCur->iPage-1],
  64050. pCur->pPage->pgno
  64051. );
  64052. testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
  64053. pCur->info.nSize = 0;
  64054. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
  64055. pCur->ix = pCur->aiIdx[pCur->iPage-1];
  64056. pLeaf = pCur->pPage;
  64057. pCur->pPage = pCur->apPage[--pCur->iPage];
  64058. releasePageNotNull(pLeaf);
  64059. }
  64060. /*
  64061. ** Move the cursor to point to the root page of its b-tree structure.
  64062. **
  64063. ** If the table has a virtual root page, then the cursor is moved to point
  64064. ** to the virtual root page instead of the actual root page. A table has a
  64065. ** virtual root page when the actual root page contains no cells and a
  64066. ** single child page. This can only happen with the table rooted at page 1.
  64067. **
  64068. ** If the b-tree structure is empty, the cursor state is set to
  64069. ** CURSOR_INVALID and this routine returns SQLITE_EMPTY. Otherwise,
  64070. ** the cursor is set to point to the first cell located on the root
  64071. ** (or virtual root) page and the cursor state is set to CURSOR_VALID.
  64072. **
  64073. ** If this function returns successfully, it may be assumed that the
  64074. ** page-header flags indicate that the [virtual] root-page is the expected
  64075. ** kind of b-tree page (i.e. if when opening the cursor the caller did not
  64076. ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
  64077. ** indicating a table b-tree, or if the caller did specify a KeyInfo
  64078. ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
  64079. ** b-tree).
  64080. */
  64081. static int moveToRoot(BtCursor *pCur){
  64082. MemPage *pRoot;
  64083. int rc = SQLITE_OK;
  64084. assert( cursorOwnsBtShared(pCur) );
  64085. assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
  64086. assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
  64087. assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
  64088. assert( pCur->eState < CURSOR_REQUIRESEEK || pCur->iPage<0 );
  64089. assert( pCur->pgnoRoot>0 || pCur->iPage<0 );
  64090. if( pCur->iPage>=0 ){
  64091. if( pCur->iPage ){
  64092. releasePageNotNull(pCur->pPage);
  64093. while( --pCur->iPage ){
  64094. releasePageNotNull(pCur->apPage[pCur->iPage]);
  64095. }
  64096. pCur->pPage = pCur->apPage[0];
  64097. goto skip_init;
  64098. }
  64099. }else if( pCur->pgnoRoot==0 ){
  64100. pCur->eState = CURSOR_INVALID;
  64101. return SQLITE_EMPTY;
  64102. }else{
  64103. assert( pCur->iPage==(-1) );
  64104. if( pCur->eState>=CURSOR_REQUIRESEEK ){
  64105. if( pCur->eState==CURSOR_FAULT ){
  64106. assert( pCur->skipNext!=SQLITE_OK );
  64107. return pCur->skipNext;
  64108. }
  64109. sqlite3BtreeClearCursor(pCur);
  64110. }
  64111. rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->pPage,
  64112. 0, pCur->curPagerFlags);
  64113. if( rc!=SQLITE_OK ){
  64114. pCur->eState = CURSOR_INVALID;
  64115. return rc;
  64116. }
  64117. pCur->iPage = 0;
  64118. pCur->curIntKey = pCur->pPage->intKey;
  64119. }
  64120. pRoot = pCur->pPage;
  64121. assert( pRoot->pgno==pCur->pgnoRoot );
  64122. /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
  64123. ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
  64124. ** NULL, the caller expects a table b-tree. If this is not the case,
  64125. ** return an SQLITE_CORRUPT error.
  64126. **
  64127. ** Earlier versions of SQLite assumed that this test could not fail
  64128. ** if the root page was already loaded when this function was called (i.e.
  64129. ** if pCur->iPage>=0). But this is not so if the database is corrupted
  64130. ** in such a way that page pRoot is linked into a second b-tree table
  64131. ** (or the freelist). */
  64132. assert( pRoot->intKey==1 || pRoot->intKey==0 );
  64133. if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
  64134. return SQLITE_CORRUPT_PAGE(pCur->pPage);
  64135. }
  64136. skip_init:
  64137. pCur->ix = 0;
  64138. pCur->info.nSize = 0;
  64139. pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
  64140. pRoot = pCur->pPage;
  64141. if( pRoot->nCell>0 ){
  64142. pCur->eState = CURSOR_VALID;
  64143. }else if( !pRoot->leaf ){
  64144. Pgno subpage;
  64145. if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
  64146. subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
  64147. pCur->eState = CURSOR_VALID;
  64148. rc = moveToChild(pCur, subpage);
  64149. }else{
  64150. pCur->eState = CURSOR_INVALID;
  64151. rc = SQLITE_EMPTY;
  64152. }
  64153. return rc;
  64154. }
  64155. /*
  64156. ** Move the cursor down to the left-most leaf entry beneath the
  64157. ** entry to which it is currently pointing.
  64158. **
  64159. ** The left-most leaf is the one with the smallest key - the first
  64160. ** in ascending order.
  64161. */
  64162. static int moveToLeftmost(BtCursor *pCur){
  64163. Pgno pgno;
  64164. int rc = SQLITE_OK;
  64165. MemPage *pPage;
  64166. assert( cursorOwnsBtShared(pCur) );
  64167. assert( pCur->eState==CURSOR_VALID );
  64168. while( rc==SQLITE_OK && !(pPage = pCur->pPage)->leaf ){
  64169. assert( pCur->ix<pPage->nCell );
  64170. pgno = get4byte(findCell(pPage, pCur->ix));
  64171. rc = moveToChild(pCur, pgno);
  64172. }
  64173. return rc;
  64174. }
  64175. /*
  64176. ** Move the cursor down to the right-most leaf entry beneath the
  64177. ** page to which it is currently pointing. Notice the difference
  64178. ** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
  64179. ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
  64180. ** finds the right-most entry beneath the *page*.
  64181. **
  64182. ** The right-most entry is the one with the largest key - the last
  64183. ** key in ascending order.
  64184. */
  64185. static int moveToRightmost(BtCursor *pCur){
  64186. Pgno pgno;
  64187. int rc = SQLITE_OK;
  64188. MemPage *pPage = 0;
  64189. assert( cursorOwnsBtShared(pCur) );
  64190. assert( pCur->eState==CURSOR_VALID );
  64191. while( !(pPage = pCur->pPage)->leaf ){
  64192. pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  64193. pCur->ix = pPage->nCell;
  64194. rc = moveToChild(pCur, pgno);
  64195. if( rc ) return rc;
  64196. }
  64197. pCur->ix = pPage->nCell-1;
  64198. assert( pCur->info.nSize==0 );
  64199. assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
  64200. return SQLITE_OK;
  64201. }
  64202. /* Move the cursor to the first entry in the table. Return SQLITE_OK
  64203. ** on success. Set *pRes to 0 if the cursor actually points to something
  64204. ** or set *pRes to 1 if the table is empty.
  64205. */
  64206. SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
  64207. int rc;
  64208. assert( cursorOwnsBtShared(pCur) );
  64209. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  64210. rc = moveToRoot(pCur);
  64211. if( rc==SQLITE_OK ){
  64212. assert( pCur->pPage->nCell>0 );
  64213. *pRes = 0;
  64214. rc = moveToLeftmost(pCur);
  64215. }else if( rc==SQLITE_EMPTY ){
  64216. assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
  64217. *pRes = 1;
  64218. rc = SQLITE_OK;
  64219. }
  64220. return rc;
  64221. }
  64222. /* Move the cursor to the last entry in the table. Return SQLITE_OK
  64223. ** on success. Set *pRes to 0 if the cursor actually points to something
  64224. ** or set *pRes to 1 if the table is empty.
  64225. */
  64226. SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
  64227. int rc;
  64228. assert( cursorOwnsBtShared(pCur) );
  64229. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  64230. /* If the cursor already points to the last entry, this is a no-op. */
  64231. if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
  64232. #ifdef SQLITE_DEBUG
  64233. /* This block serves to assert() that the cursor really does point
  64234. ** to the last entry in the b-tree. */
  64235. int ii;
  64236. for(ii=0; ii<pCur->iPage; ii++){
  64237. assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
  64238. }
  64239. assert( pCur->ix==pCur->pPage->nCell-1 );
  64240. assert( pCur->pPage->leaf );
  64241. #endif
  64242. *pRes = 0;
  64243. return SQLITE_OK;
  64244. }
  64245. rc = moveToRoot(pCur);
  64246. if( rc==SQLITE_OK ){
  64247. assert( pCur->eState==CURSOR_VALID );
  64248. *pRes = 0;
  64249. rc = moveToRightmost(pCur);
  64250. if( rc==SQLITE_OK ){
  64251. pCur->curFlags |= BTCF_AtLast;
  64252. }else{
  64253. pCur->curFlags &= ~BTCF_AtLast;
  64254. }
  64255. }else if( rc==SQLITE_EMPTY ){
  64256. assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
  64257. *pRes = 1;
  64258. rc = SQLITE_OK;
  64259. }
  64260. return rc;
  64261. }
  64262. /* Move the cursor so that it points to an entry near the key
  64263. ** specified by pIdxKey or intKey. Return a success code.
  64264. **
  64265. ** For INTKEY tables, the intKey parameter is used. pIdxKey
  64266. ** must be NULL. For index tables, pIdxKey is used and intKey
  64267. ** is ignored.
  64268. **
  64269. ** If an exact match is not found, then the cursor is always
  64270. ** left pointing at a leaf page which would hold the entry if it
  64271. ** were present. The cursor might point to an entry that comes
  64272. ** before or after the key.
  64273. **
  64274. ** An integer is written into *pRes which is the result of
  64275. ** comparing the key with the entry to which the cursor is
  64276. ** pointing. The meaning of the integer written into
  64277. ** *pRes is as follows:
  64278. **
  64279. ** *pRes<0 The cursor is left pointing at an entry that
  64280. ** is smaller than intKey/pIdxKey or if the table is empty
  64281. ** and the cursor is therefore left point to nothing.
  64282. **
  64283. ** *pRes==0 The cursor is left pointing at an entry that
  64284. ** exactly matches intKey/pIdxKey.
  64285. **
  64286. ** *pRes>0 The cursor is left pointing at an entry that
  64287. ** is larger than intKey/pIdxKey.
  64288. **
  64289. ** For index tables, the pIdxKey->eqSeen field is set to 1 if there
  64290. ** exists an entry in the table that exactly matches pIdxKey.
  64291. */
  64292. SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
  64293. BtCursor *pCur, /* The cursor to be moved */
  64294. UnpackedRecord *pIdxKey, /* Unpacked index key */
  64295. i64 intKey, /* The table key */
  64296. int biasRight, /* If true, bias the search to the high end */
  64297. int *pRes /* Write search results here */
  64298. ){
  64299. int rc;
  64300. RecordCompare xRecordCompare;
  64301. assert( cursorOwnsBtShared(pCur) );
  64302. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  64303. assert( pRes );
  64304. assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
  64305. assert( pCur->eState!=CURSOR_VALID || (pIdxKey==0)==(pCur->curIntKey!=0) );
  64306. /* If the cursor is already positioned at the point we are trying
  64307. ** to move to, then just return without doing any work */
  64308. if( pIdxKey==0
  64309. && pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0
  64310. ){
  64311. if( pCur->info.nKey==intKey ){
  64312. *pRes = 0;
  64313. return SQLITE_OK;
  64314. }
  64315. if( pCur->info.nKey<intKey ){
  64316. if( (pCur->curFlags & BTCF_AtLast)!=0 ){
  64317. *pRes = -1;
  64318. return SQLITE_OK;
  64319. }
  64320. /* If the requested key is one more than the previous key, then
  64321. ** try to get there using sqlite3BtreeNext() rather than a full
  64322. ** binary search. This is an optimization only. The correct answer
  64323. ** is still obtained without this case, only a little more slowely */
  64324. if( pCur->info.nKey+1==intKey ){
  64325. *pRes = 0;
  64326. rc = sqlite3BtreeNext(pCur, 0);
  64327. if( rc==SQLITE_OK ){
  64328. getCellInfo(pCur);
  64329. if( pCur->info.nKey==intKey ){
  64330. return SQLITE_OK;
  64331. }
  64332. }else if( rc==SQLITE_DONE ){
  64333. rc = SQLITE_OK;
  64334. }else{
  64335. return rc;
  64336. }
  64337. }
  64338. }
  64339. }
  64340. if( pIdxKey ){
  64341. xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
  64342. pIdxKey->errCode = 0;
  64343. assert( pIdxKey->default_rc==1
  64344. || pIdxKey->default_rc==0
  64345. || pIdxKey->default_rc==-1
  64346. );
  64347. }else{
  64348. xRecordCompare = 0; /* All keys are integers */
  64349. }
  64350. rc = moveToRoot(pCur);
  64351. if( rc ){
  64352. if( rc==SQLITE_EMPTY ){
  64353. assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
  64354. *pRes = -1;
  64355. return SQLITE_OK;
  64356. }
  64357. return rc;
  64358. }
  64359. assert( pCur->pPage );
  64360. assert( pCur->pPage->isInit );
  64361. assert( pCur->eState==CURSOR_VALID );
  64362. assert( pCur->pPage->nCell > 0 );
  64363. assert( pCur->iPage==0 || pCur->apPage[0]->intKey==pCur->curIntKey );
  64364. assert( pCur->curIntKey || pIdxKey );
  64365. for(;;){
  64366. int lwr, upr, idx, c;
  64367. Pgno chldPg;
  64368. MemPage *pPage = pCur->pPage;
  64369. u8 *pCell; /* Pointer to current cell in pPage */
  64370. /* pPage->nCell must be greater than zero. If this is the root-page
  64371. ** the cursor would have been INVALID above and this for(;;) loop
  64372. ** not run. If this is not the root-page, then the moveToChild() routine
  64373. ** would have already detected db corruption. Similarly, pPage must
  64374. ** be the right kind (index or table) of b-tree page. Otherwise
  64375. ** a moveToChild() or moveToRoot() call would have detected corruption. */
  64376. assert( pPage->nCell>0 );
  64377. assert( pPage->intKey==(pIdxKey==0) );
  64378. lwr = 0;
  64379. upr = pPage->nCell-1;
  64380. assert( biasRight==0 || biasRight==1 );
  64381. idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
  64382. pCur->ix = (u16)idx;
  64383. if( xRecordCompare==0 ){
  64384. for(;;){
  64385. i64 nCellKey;
  64386. pCell = findCellPastPtr(pPage, idx);
  64387. if( pPage->intKeyLeaf ){
  64388. while( 0x80 <= *(pCell++) ){
  64389. if( pCell>=pPage->aDataEnd ){
  64390. return SQLITE_CORRUPT_PAGE(pPage);
  64391. }
  64392. }
  64393. }
  64394. getVarint(pCell, (u64*)&nCellKey);
  64395. if( nCellKey<intKey ){
  64396. lwr = idx+1;
  64397. if( lwr>upr ){ c = -1; break; }
  64398. }else if( nCellKey>intKey ){
  64399. upr = idx-1;
  64400. if( lwr>upr ){ c = +1; break; }
  64401. }else{
  64402. assert( nCellKey==intKey );
  64403. pCur->ix = (u16)idx;
  64404. if( !pPage->leaf ){
  64405. lwr = idx;
  64406. goto moveto_next_layer;
  64407. }else{
  64408. pCur->curFlags |= BTCF_ValidNKey;
  64409. pCur->info.nKey = nCellKey;
  64410. pCur->info.nSize = 0;
  64411. *pRes = 0;
  64412. return SQLITE_OK;
  64413. }
  64414. }
  64415. assert( lwr+upr>=0 );
  64416. idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2; */
  64417. }
  64418. }else{
  64419. for(;;){
  64420. int nCell; /* Size of the pCell cell in bytes */
  64421. pCell = findCellPastPtr(pPage, idx);
  64422. /* The maximum supported page-size is 65536 bytes. This means that
  64423. ** the maximum number of record bytes stored on an index B-Tree
  64424. ** page is less than 16384 bytes and may be stored as a 2-byte
  64425. ** varint. This information is used to attempt to avoid parsing
  64426. ** the entire cell by checking for the cases where the record is
  64427. ** stored entirely within the b-tree page by inspecting the first
  64428. ** 2 bytes of the cell.
  64429. */
  64430. nCell = pCell[0];
  64431. if( nCell<=pPage->max1bytePayload ){
  64432. /* This branch runs if the record-size field of the cell is a
  64433. ** single byte varint and the record fits entirely on the main
  64434. ** b-tree page. */
  64435. testcase( pCell+nCell+1==pPage->aDataEnd );
  64436. c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
  64437. }else if( !(pCell[1] & 0x80)
  64438. && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
  64439. ){
  64440. /* The record-size field is a 2 byte varint and the record
  64441. ** fits entirely on the main b-tree page. */
  64442. testcase( pCell+nCell+2==pPage->aDataEnd );
  64443. c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
  64444. }else{
  64445. /* The record flows over onto one or more overflow pages. In
  64446. ** this case the whole cell needs to be parsed, a buffer allocated
  64447. ** and accessPayload() used to retrieve the record into the
  64448. ** buffer before VdbeRecordCompare() can be called.
  64449. **
  64450. ** If the record is corrupt, the xRecordCompare routine may read
  64451. ** up to two varints past the end of the buffer. An extra 18
  64452. ** bytes of padding is allocated at the end of the buffer in
  64453. ** case this happens. */
  64454. void *pCellKey;
  64455. u8 * const pCellBody = pCell - pPage->childPtrSize;
  64456. const int nOverrun = 18; /* Size of the overrun padding */
  64457. pPage->xParseCell(pPage, pCellBody, &pCur->info);
  64458. nCell = (int)pCur->info.nKey;
  64459. testcase( nCell<0 ); /* True if key size is 2^32 or more */
  64460. testcase( nCell==0 ); /* Invalid key size: 0x80 0x80 0x00 */
  64461. testcase( nCell==1 ); /* Invalid key size: 0x80 0x80 0x01 */
  64462. testcase( nCell==2 ); /* Minimum legal index key size */
  64463. if( nCell<2 || nCell/pCur->pBt->usableSize>pCur->pBt->nPage ){
  64464. rc = SQLITE_CORRUPT_PAGE(pPage);
  64465. goto moveto_finish;
  64466. }
  64467. pCellKey = sqlite3Malloc( nCell+nOverrun );
  64468. if( pCellKey==0 ){
  64469. rc = SQLITE_NOMEM_BKPT;
  64470. goto moveto_finish;
  64471. }
  64472. pCur->ix = (u16)idx;
  64473. rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
  64474. memset(((u8*)pCellKey)+nCell,0,nOverrun); /* Fix uninit warnings */
  64475. pCur->curFlags &= ~BTCF_ValidOvfl;
  64476. if( rc ){
  64477. sqlite3_free(pCellKey);
  64478. goto moveto_finish;
  64479. }
  64480. c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
  64481. sqlite3_free(pCellKey);
  64482. }
  64483. assert(
  64484. (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
  64485. && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
  64486. );
  64487. if( c<0 ){
  64488. lwr = idx+1;
  64489. }else if( c>0 ){
  64490. upr = idx-1;
  64491. }else{
  64492. assert( c==0 );
  64493. *pRes = 0;
  64494. rc = SQLITE_OK;
  64495. pCur->ix = (u16)idx;
  64496. if( pIdxKey->errCode ) rc = SQLITE_CORRUPT_BKPT;
  64497. goto moveto_finish;
  64498. }
  64499. if( lwr>upr ) break;
  64500. assert( lwr+upr>=0 );
  64501. idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2 */
  64502. }
  64503. }
  64504. assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
  64505. assert( pPage->isInit );
  64506. if( pPage->leaf ){
  64507. assert( pCur->ix<pCur->pPage->nCell );
  64508. pCur->ix = (u16)idx;
  64509. *pRes = c;
  64510. rc = SQLITE_OK;
  64511. goto moveto_finish;
  64512. }
  64513. moveto_next_layer:
  64514. if( lwr>=pPage->nCell ){
  64515. chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  64516. }else{
  64517. chldPg = get4byte(findCell(pPage, lwr));
  64518. }
  64519. pCur->ix = (u16)lwr;
  64520. rc = moveToChild(pCur, chldPg);
  64521. if( rc ) break;
  64522. }
  64523. moveto_finish:
  64524. pCur->info.nSize = 0;
  64525. assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
  64526. return rc;
  64527. }
  64528. /*
  64529. ** Return TRUE if the cursor is not pointing at an entry of the table.
  64530. **
  64531. ** TRUE will be returned after a call to sqlite3BtreeNext() moves
  64532. ** past the last entry in the table or sqlite3BtreePrev() moves past
  64533. ** the first entry. TRUE is also returned if the table is empty.
  64534. */
  64535. SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
  64536. /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
  64537. ** have been deleted? This API will need to change to return an error code
  64538. ** as well as the boolean result value.
  64539. */
  64540. return (CURSOR_VALID!=pCur->eState);
  64541. }
  64542. /*
  64543. ** Return an estimate for the number of rows in the table that pCur is
  64544. ** pointing to. Return a negative number if no estimate is currently
  64545. ** available.
  64546. */
  64547. SQLITE_PRIVATE i64 sqlite3BtreeRowCountEst(BtCursor *pCur){
  64548. i64 n;
  64549. u8 i;
  64550. assert( cursorOwnsBtShared(pCur) );
  64551. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  64552. /* Currently this interface is only called by the OP_IfSmaller
  64553. ** opcode, and it that case the cursor will always be valid and
  64554. ** will always point to a leaf node. */
  64555. if( NEVER(pCur->eState!=CURSOR_VALID) ) return -1;
  64556. if( NEVER(pCur->pPage->leaf==0) ) return -1;
  64557. n = pCur->pPage->nCell;
  64558. for(i=0; i<pCur->iPage; i++){
  64559. n *= pCur->apPage[i]->nCell;
  64560. }
  64561. return n;
  64562. }
  64563. /*
  64564. ** Advance the cursor to the next entry in the database.
  64565. ** Return value:
  64566. **
  64567. ** SQLITE_OK success
  64568. ** SQLITE_DONE cursor is already pointing at the last element
  64569. ** otherwise some kind of error occurred
  64570. **
  64571. ** The main entry point is sqlite3BtreeNext(). That routine is optimized
  64572. ** for the common case of merely incrementing the cell counter BtCursor.aiIdx
  64573. ** to the next cell on the current page. The (slower) btreeNext() helper
  64574. ** routine is called when it is necessary to move to a different page or
  64575. ** to restore the cursor.
  64576. **
  64577. ** If bit 0x01 of the F argument in sqlite3BtreeNext(C,F) is 1, then the
  64578. ** cursor corresponds to an SQL index and this routine could have been
  64579. ** skipped if the SQL index had been a unique index. The F argument
  64580. ** is a hint to the implement. SQLite btree implementation does not use
  64581. ** this hint, but COMDB2 does.
  64582. */
  64583. static SQLITE_NOINLINE int btreeNext(BtCursor *pCur){
  64584. int rc;
  64585. int idx;
  64586. MemPage *pPage;
  64587. assert( cursorOwnsBtShared(pCur) );
  64588. if( pCur->eState!=CURSOR_VALID ){
  64589. assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
  64590. rc = restoreCursorPosition(pCur);
  64591. if( rc!=SQLITE_OK ){
  64592. return rc;
  64593. }
  64594. if( CURSOR_INVALID==pCur->eState ){
  64595. return SQLITE_DONE;
  64596. }
  64597. if( pCur->eState==CURSOR_SKIPNEXT ){
  64598. pCur->eState = CURSOR_VALID;
  64599. if( pCur->skipNext>0 ) return SQLITE_OK;
  64600. }
  64601. }
  64602. pPage = pCur->pPage;
  64603. idx = ++pCur->ix;
  64604. if( !pPage->isInit ){
  64605. /* The only known way for this to happen is for there to be a
  64606. ** recursive SQL function that does a DELETE operation as part of a
  64607. ** SELECT which deletes content out from under an active cursor
  64608. ** in a corrupt database file where the table being DELETE-ed from
  64609. ** has pages in common with the table being queried. See TH3
  64610. ** module cov1/btree78.test testcase 220 (2018-06-08) for an
  64611. ** example. */
  64612. return SQLITE_CORRUPT_BKPT;
  64613. }
  64614. /* If the database file is corrupt, it is possible for the value of idx
  64615. ** to be invalid here. This can only occur if a second cursor modifies
  64616. ** the page while cursor pCur is holding a reference to it. Which can
  64617. ** only happen if the database is corrupt in such a way as to link the
  64618. ** page into more than one b-tree structure. */
  64619. testcase( idx>pPage->nCell );
  64620. if( idx>=pPage->nCell ){
  64621. if( !pPage->leaf ){
  64622. rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
  64623. if( rc ) return rc;
  64624. return moveToLeftmost(pCur);
  64625. }
  64626. do{
  64627. if( pCur->iPage==0 ){
  64628. pCur->eState = CURSOR_INVALID;
  64629. return SQLITE_DONE;
  64630. }
  64631. moveToParent(pCur);
  64632. pPage = pCur->pPage;
  64633. }while( pCur->ix>=pPage->nCell );
  64634. if( pPage->intKey ){
  64635. return sqlite3BtreeNext(pCur, 0);
  64636. }else{
  64637. return SQLITE_OK;
  64638. }
  64639. }
  64640. if( pPage->leaf ){
  64641. return SQLITE_OK;
  64642. }else{
  64643. return moveToLeftmost(pCur);
  64644. }
  64645. }
  64646. SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int flags){
  64647. MemPage *pPage;
  64648. UNUSED_PARAMETER( flags ); /* Used in COMDB2 but not native SQLite */
  64649. assert( cursorOwnsBtShared(pCur) );
  64650. assert( flags==0 || flags==1 );
  64651. pCur->info.nSize = 0;
  64652. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
  64653. if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur);
  64654. pPage = pCur->pPage;
  64655. if( (++pCur->ix)>=pPage->nCell ){
  64656. pCur->ix--;
  64657. return btreeNext(pCur);
  64658. }
  64659. if( pPage->leaf ){
  64660. return SQLITE_OK;
  64661. }else{
  64662. return moveToLeftmost(pCur);
  64663. }
  64664. }
  64665. /*
  64666. ** Step the cursor to the back to the previous entry in the database.
  64667. ** Return values:
  64668. **
  64669. ** SQLITE_OK success
  64670. ** SQLITE_DONE the cursor is already on the first element of the table
  64671. ** otherwise some kind of error occurred
  64672. **
  64673. ** The main entry point is sqlite3BtreePrevious(). That routine is optimized
  64674. ** for the common case of merely decrementing the cell counter BtCursor.aiIdx
  64675. ** to the previous cell on the current page. The (slower) btreePrevious()
  64676. ** helper routine is called when it is necessary to move to a different page
  64677. ** or to restore the cursor.
  64678. **
  64679. ** If bit 0x01 of the F argument to sqlite3BtreePrevious(C,F) is 1, then
  64680. ** the cursor corresponds to an SQL index and this routine could have been
  64681. ** skipped if the SQL index had been a unique index. The F argument is a
  64682. ** hint to the implement. The native SQLite btree implementation does not
  64683. ** use this hint, but COMDB2 does.
  64684. */
  64685. static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur){
  64686. int rc;
  64687. MemPage *pPage;
  64688. assert( cursorOwnsBtShared(pCur) );
  64689. assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );
  64690. assert( pCur->info.nSize==0 );
  64691. if( pCur->eState!=CURSOR_VALID ){
  64692. rc = restoreCursorPosition(pCur);
  64693. if( rc!=SQLITE_OK ){
  64694. return rc;
  64695. }
  64696. if( CURSOR_INVALID==pCur->eState ){
  64697. return SQLITE_DONE;
  64698. }
  64699. if( CURSOR_SKIPNEXT==pCur->eState ){
  64700. pCur->eState = CURSOR_VALID;
  64701. if( pCur->skipNext<0 ) return SQLITE_OK;
  64702. }
  64703. }
  64704. pPage = pCur->pPage;
  64705. assert( pPage->isInit );
  64706. if( !pPage->leaf ){
  64707. int idx = pCur->ix;
  64708. rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
  64709. if( rc ) return rc;
  64710. rc = moveToRightmost(pCur);
  64711. }else{
  64712. while( pCur->ix==0 ){
  64713. if( pCur->iPage==0 ){
  64714. pCur->eState = CURSOR_INVALID;
  64715. return SQLITE_DONE;
  64716. }
  64717. moveToParent(pCur);
  64718. }
  64719. assert( pCur->info.nSize==0 );
  64720. assert( (pCur->curFlags & (BTCF_ValidOvfl))==0 );
  64721. pCur->ix--;
  64722. pPage = pCur->pPage;
  64723. if( pPage->intKey && !pPage->leaf ){
  64724. rc = sqlite3BtreePrevious(pCur, 0);
  64725. }else{
  64726. rc = SQLITE_OK;
  64727. }
  64728. }
  64729. return rc;
  64730. }
  64731. SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int flags){
  64732. assert( cursorOwnsBtShared(pCur) );
  64733. assert( flags==0 || flags==1 );
  64734. UNUSED_PARAMETER( flags ); /* Used in COMDB2 but not native SQLite */
  64735. pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey);
  64736. pCur->info.nSize = 0;
  64737. if( pCur->eState!=CURSOR_VALID
  64738. || pCur->ix==0
  64739. || pCur->pPage->leaf==0
  64740. ){
  64741. return btreePrevious(pCur);
  64742. }
  64743. pCur->ix--;
  64744. return SQLITE_OK;
  64745. }
  64746. /*
  64747. ** Allocate a new page from the database file.
  64748. **
  64749. ** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
  64750. ** has already been called on the new page.) The new page has also
  64751. ** been referenced and the calling routine is responsible for calling
  64752. ** sqlite3PagerUnref() on the new page when it is done.
  64753. **
  64754. ** SQLITE_OK is returned on success. Any other return value indicates
  64755. ** an error. *ppPage is set to NULL in the event of an error.
  64756. **
  64757. ** If the "nearby" parameter is not 0, then an effort is made to
  64758. ** locate a page close to the page number "nearby". This can be used in an
  64759. ** attempt to keep related pages close to each other in the database file,
  64760. ** which in turn can make database access faster.
  64761. **
  64762. ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
  64763. ** anywhere on the free-list, then it is guaranteed to be returned. If
  64764. ** eMode is BTALLOC_LT then the page returned will be less than or equal
  64765. ** to nearby if any such page exists. If eMode is BTALLOC_ANY then there
  64766. ** are no restrictions on which page is returned.
  64767. */
  64768. static int allocateBtreePage(
  64769. BtShared *pBt, /* The btree */
  64770. MemPage **ppPage, /* Store pointer to the allocated page here */
  64771. Pgno *pPgno, /* Store the page number here */
  64772. Pgno nearby, /* Search for a page near this one */
  64773. u8 eMode /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
  64774. ){
  64775. MemPage *pPage1;
  64776. int rc;
  64777. u32 n; /* Number of pages on the freelist */
  64778. u32 k; /* Number of leaves on the trunk of the freelist */
  64779. MemPage *pTrunk = 0;
  64780. MemPage *pPrevTrunk = 0;
  64781. Pgno mxPage; /* Total size of the database file */
  64782. assert( sqlite3_mutex_held(pBt->mutex) );
  64783. assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
  64784. pPage1 = pBt->pPage1;
  64785. mxPage = btreePagecount(pBt);
  64786. /* EVIDENCE-OF: R-05119-02637 The 4-byte big-endian integer at offset 36
  64787. ** stores stores the total number of pages on the freelist. */
  64788. n = get4byte(&pPage1->aData[36]);
  64789. testcase( n==mxPage-1 );
  64790. if( n>=mxPage ){
  64791. return SQLITE_CORRUPT_BKPT;
  64792. }
  64793. if( n>0 ){
  64794. /* There are pages on the freelist. Reuse one of those pages. */
  64795. Pgno iTrunk;
  64796. u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
  64797. u32 nSearch = 0; /* Count of the number of search attempts */
  64798. /* If eMode==BTALLOC_EXACT and a query of the pointer-map
  64799. ** shows that the page 'nearby' is somewhere on the free-list, then
  64800. ** the entire-list will be searched for that page.
  64801. */
  64802. #ifndef SQLITE_OMIT_AUTOVACUUM
  64803. if( eMode==BTALLOC_EXACT ){
  64804. if( nearby<=mxPage ){
  64805. u8 eType;
  64806. assert( nearby>0 );
  64807. assert( pBt->autoVacuum );
  64808. rc = ptrmapGet(pBt, nearby, &eType, 0);
  64809. if( rc ) return rc;
  64810. if( eType==PTRMAP_FREEPAGE ){
  64811. searchList = 1;
  64812. }
  64813. }
  64814. }else if( eMode==BTALLOC_LE ){
  64815. searchList = 1;
  64816. }
  64817. #endif
  64818. /* Decrement the free-list count by 1. Set iTrunk to the index of the
  64819. ** first free-list trunk page. iPrevTrunk is initially 1.
  64820. */
  64821. rc = sqlite3PagerWrite(pPage1->pDbPage);
  64822. if( rc ) return rc;
  64823. put4byte(&pPage1->aData[36], n-1);
  64824. /* The code within this loop is run only once if the 'searchList' variable
  64825. ** is not true. Otherwise, it runs once for each trunk-page on the
  64826. ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
  64827. ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
  64828. */
  64829. do {
  64830. pPrevTrunk = pTrunk;
  64831. if( pPrevTrunk ){
  64832. /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page
  64833. ** is the page number of the next freelist trunk page in the list or
  64834. ** zero if this is the last freelist trunk page. */
  64835. iTrunk = get4byte(&pPrevTrunk->aData[0]);
  64836. }else{
  64837. /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32
  64838. ** stores the page number of the first page of the freelist, or zero if
  64839. ** the freelist is empty. */
  64840. iTrunk = get4byte(&pPage1->aData[32]);
  64841. }
  64842. testcase( iTrunk==mxPage );
  64843. if( iTrunk>mxPage || nSearch++ > n ){
  64844. rc = SQLITE_CORRUPT_PGNO(pPrevTrunk ? pPrevTrunk->pgno : 1);
  64845. }else{
  64846. rc = btreeGetUnusedPage(pBt, iTrunk, &pTrunk, 0);
  64847. }
  64848. if( rc ){
  64849. pTrunk = 0;
  64850. goto end_allocate_page;
  64851. }
  64852. assert( pTrunk!=0 );
  64853. assert( pTrunk->aData!=0 );
  64854. /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page
  64855. ** is the number of leaf page pointers to follow. */
  64856. k = get4byte(&pTrunk->aData[4]);
  64857. if( k==0 && !searchList ){
  64858. /* The trunk has no leaves and the list is not being searched.
  64859. ** So extract the trunk page itself and use it as the newly
  64860. ** allocated page */
  64861. assert( pPrevTrunk==0 );
  64862. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  64863. if( rc ){
  64864. goto end_allocate_page;
  64865. }
  64866. *pPgno = iTrunk;
  64867. memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
  64868. *ppPage = pTrunk;
  64869. pTrunk = 0;
  64870. TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
  64871. }else if( k>(u32)(pBt->usableSize/4 - 2) ){
  64872. /* Value of k is out of range. Database corruption */
  64873. rc = SQLITE_CORRUPT_PGNO(iTrunk);
  64874. goto end_allocate_page;
  64875. #ifndef SQLITE_OMIT_AUTOVACUUM
  64876. }else if( searchList
  64877. && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
  64878. ){
  64879. /* The list is being searched and this trunk page is the page
  64880. ** to allocate, regardless of whether it has leaves.
  64881. */
  64882. *pPgno = iTrunk;
  64883. *ppPage = pTrunk;
  64884. searchList = 0;
  64885. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  64886. if( rc ){
  64887. goto end_allocate_page;
  64888. }
  64889. if( k==0 ){
  64890. if( !pPrevTrunk ){
  64891. memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
  64892. }else{
  64893. rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
  64894. if( rc!=SQLITE_OK ){
  64895. goto end_allocate_page;
  64896. }
  64897. memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
  64898. }
  64899. }else{
  64900. /* The trunk page is required by the caller but it contains
  64901. ** pointers to free-list leaves. The first leaf becomes a trunk
  64902. ** page in this case.
  64903. */
  64904. MemPage *pNewTrunk;
  64905. Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
  64906. if( iNewTrunk>mxPage ){
  64907. rc = SQLITE_CORRUPT_PGNO(iTrunk);
  64908. goto end_allocate_page;
  64909. }
  64910. testcase( iNewTrunk==mxPage );
  64911. rc = btreeGetUnusedPage(pBt, iNewTrunk, &pNewTrunk, 0);
  64912. if( rc!=SQLITE_OK ){
  64913. goto end_allocate_page;
  64914. }
  64915. rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
  64916. if( rc!=SQLITE_OK ){
  64917. releasePage(pNewTrunk);
  64918. goto end_allocate_page;
  64919. }
  64920. memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
  64921. put4byte(&pNewTrunk->aData[4], k-1);
  64922. memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
  64923. releasePage(pNewTrunk);
  64924. if( !pPrevTrunk ){
  64925. assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
  64926. put4byte(&pPage1->aData[32], iNewTrunk);
  64927. }else{
  64928. rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
  64929. if( rc ){
  64930. goto end_allocate_page;
  64931. }
  64932. put4byte(&pPrevTrunk->aData[0], iNewTrunk);
  64933. }
  64934. }
  64935. pTrunk = 0;
  64936. TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
  64937. #endif
  64938. }else if( k>0 ){
  64939. /* Extract a leaf from the trunk */
  64940. u32 closest;
  64941. Pgno iPage;
  64942. unsigned char *aData = pTrunk->aData;
  64943. if( nearby>0 ){
  64944. u32 i;
  64945. closest = 0;
  64946. if( eMode==BTALLOC_LE ){
  64947. for(i=0; i<k; i++){
  64948. iPage = get4byte(&aData[8+i*4]);
  64949. if( iPage<=nearby ){
  64950. closest = i;
  64951. break;
  64952. }
  64953. }
  64954. }else{
  64955. int dist;
  64956. dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
  64957. for(i=1; i<k; i++){
  64958. int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
  64959. if( d2<dist ){
  64960. closest = i;
  64961. dist = d2;
  64962. }
  64963. }
  64964. }
  64965. }else{
  64966. closest = 0;
  64967. }
  64968. iPage = get4byte(&aData[8+closest*4]);
  64969. testcase( iPage==mxPage );
  64970. if( iPage>mxPage ){
  64971. rc = SQLITE_CORRUPT_PGNO(iTrunk);
  64972. goto end_allocate_page;
  64973. }
  64974. testcase( iPage==mxPage );
  64975. if( !searchList
  64976. || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
  64977. ){
  64978. int noContent;
  64979. *pPgno = iPage;
  64980. TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
  64981. ": %d more free pages\n",
  64982. *pPgno, closest+1, k, pTrunk->pgno, n-1));
  64983. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  64984. if( rc ) goto end_allocate_page;
  64985. if( closest<k-1 ){
  64986. memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
  64987. }
  64988. put4byte(&aData[4], k-1);
  64989. noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0;
  64990. rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, noContent);
  64991. if( rc==SQLITE_OK ){
  64992. rc = sqlite3PagerWrite((*ppPage)->pDbPage);
  64993. if( rc!=SQLITE_OK ){
  64994. releasePage(*ppPage);
  64995. *ppPage = 0;
  64996. }
  64997. }
  64998. searchList = 0;
  64999. }
  65000. }
  65001. releasePage(pPrevTrunk);
  65002. pPrevTrunk = 0;
  65003. }while( searchList );
  65004. }else{
  65005. /* There are no pages on the freelist, so append a new page to the
  65006. ** database image.
  65007. **
  65008. ** Normally, new pages allocated by this block can be requested from the
  65009. ** pager layer with the 'no-content' flag set. This prevents the pager
  65010. ** from trying to read the pages content from disk. However, if the
  65011. ** current transaction has already run one or more incremental-vacuum
  65012. ** steps, then the page we are about to allocate may contain content
  65013. ** that is required in the event of a rollback. In this case, do
  65014. ** not set the no-content flag. This causes the pager to load and journal
  65015. ** the current page content before overwriting it.
  65016. **
  65017. ** Note that the pager will not actually attempt to load or journal
  65018. ** content for any page that really does lie past the end of the database
  65019. ** file on disk. So the effects of disabling the no-content optimization
  65020. ** here are confined to those pages that lie between the end of the
  65021. ** database image and the end of the database file.
  65022. */
  65023. int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
  65024. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  65025. if( rc ) return rc;
  65026. pBt->nPage++;
  65027. if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
  65028. #ifndef SQLITE_OMIT_AUTOVACUUM
  65029. if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
  65030. /* If *pPgno refers to a pointer-map page, allocate two new pages
  65031. ** at the end of the file instead of one. The first allocated page
  65032. ** becomes a new pointer-map page, the second is used by the caller.
  65033. */
  65034. MemPage *pPg = 0;
  65035. TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
  65036. assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
  65037. rc = btreeGetUnusedPage(pBt, pBt->nPage, &pPg, bNoContent);
  65038. if( rc==SQLITE_OK ){
  65039. rc = sqlite3PagerWrite(pPg->pDbPage);
  65040. releasePage(pPg);
  65041. }
  65042. if( rc ) return rc;
  65043. pBt->nPage++;
  65044. if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
  65045. }
  65046. #endif
  65047. put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
  65048. *pPgno = pBt->nPage;
  65049. assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
  65050. rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, bNoContent);
  65051. if( rc ) return rc;
  65052. rc = sqlite3PagerWrite((*ppPage)->pDbPage);
  65053. if( rc!=SQLITE_OK ){
  65054. releasePage(*ppPage);
  65055. *ppPage = 0;
  65056. }
  65057. TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
  65058. }
  65059. assert( CORRUPT_DB || *pPgno!=PENDING_BYTE_PAGE(pBt) );
  65060. end_allocate_page:
  65061. releasePage(pTrunk);
  65062. releasePage(pPrevTrunk);
  65063. assert( rc!=SQLITE_OK || sqlite3PagerPageRefcount((*ppPage)->pDbPage)<=1 );
  65064. assert( rc!=SQLITE_OK || (*ppPage)->isInit==0 );
  65065. return rc;
  65066. }
  65067. /*
  65068. ** This function is used to add page iPage to the database file free-list.
  65069. ** It is assumed that the page is not already a part of the free-list.
  65070. **
  65071. ** The value passed as the second argument to this function is optional.
  65072. ** If the caller happens to have a pointer to the MemPage object
  65073. ** corresponding to page iPage handy, it may pass it as the second value.
  65074. ** Otherwise, it may pass NULL.
  65075. **
  65076. ** If a pointer to a MemPage object is passed as the second argument,
  65077. ** its reference count is not altered by this function.
  65078. */
  65079. static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
  65080. MemPage *pTrunk = 0; /* Free-list trunk page */
  65081. Pgno iTrunk = 0; /* Page number of free-list trunk page */
  65082. MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
  65083. MemPage *pPage; /* Page being freed. May be NULL. */
  65084. int rc; /* Return Code */
  65085. u32 nFree; /* Initial number of pages on free-list */
  65086. assert( sqlite3_mutex_held(pBt->mutex) );
  65087. assert( CORRUPT_DB || iPage>1 );
  65088. assert( !pMemPage || pMemPage->pgno==iPage );
  65089. if( iPage<2 || iPage>pBt->nPage ){
  65090. return SQLITE_CORRUPT_BKPT;
  65091. }
  65092. if( pMemPage ){
  65093. pPage = pMemPage;
  65094. sqlite3PagerRef(pPage->pDbPage);
  65095. }else{
  65096. pPage = btreePageLookup(pBt, iPage);
  65097. }
  65098. /* Increment the free page count on pPage1 */
  65099. rc = sqlite3PagerWrite(pPage1->pDbPage);
  65100. if( rc ) goto freepage_out;
  65101. nFree = get4byte(&pPage1->aData[36]);
  65102. put4byte(&pPage1->aData[36], nFree+1);
  65103. if( pBt->btsFlags & BTS_SECURE_DELETE ){
  65104. /* If the secure_delete option is enabled, then
  65105. ** always fully overwrite deleted information with zeros.
  65106. */
  65107. if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
  65108. || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
  65109. ){
  65110. goto freepage_out;
  65111. }
  65112. memset(pPage->aData, 0, pPage->pBt->pageSize);
  65113. }
  65114. /* If the database supports auto-vacuum, write an entry in the pointer-map
  65115. ** to indicate that the page is free.
  65116. */
  65117. if( ISAUTOVACUUM ){
  65118. ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
  65119. if( rc ) goto freepage_out;
  65120. }
  65121. /* Now manipulate the actual database free-list structure. There are two
  65122. ** possibilities. If the free-list is currently empty, or if the first
  65123. ** trunk page in the free-list is full, then this page will become a
  65124. ** new free-list trunk page. Otherwise, it will become a leaf of the
  65125. ** first trunk page in the current free-list. This block tests if it
  65126. ** is possible to add the page as a new free-list leaf.
  65127. */
  65128. if( nFree!=0 ){
  65129. u32 nLeaf; /* Initial number of leaf cells on trunk page */
  65130. iTrunk = get4byte(&pPage1->aData[32]);
  65131. rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
  65132. if( rc!=SQLITE_OK ){
  65133. goto freepage_out;
  65134. }
  65135. nLeaf = get4byte(&pTrunk->aData[4]);
  65136. assert( pBt->usableSize>32 );
  65137. if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
  65138. rc = SQLITE_CORRUPT_BKPT;
  65139. goto freepage_out;
  65140. }
  65141. if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
  65142. /* In this case there is room on the trunk page to insert the page
  65143. ** being freed as a new leaf.
  65144. **
  65145. ** Note that the trunk page is not really full until it contains
  65146. ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
  65147. ** coded. But due to a coding error in versions of SQLite prior to
  65148. ** 3.6.0, databases with freelist trunk pages holding more than
  65149. ** usableSize/4 - 8 entries will be reported as corrupt. In order
  65150. ** to maintain backwards compatibility with older versions of SQLite,
  65151. ** we will continue to restrict the number of entries to usableSize/4 - 8
  65152. ** for now. At some point in the future (once everyone has upgraded
  65153. ** to 3.6.0 or later) we should consider fixing the conditional above
  65154. ** to read "usableSize/4-2" instead of "usableSize/4-8".
  65155. **
  65156. ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still
  65157. ** avoid using the last six entries in the freelist trunk page array in
  65158. ** order that database files created by newer versions of SQLite can be
  65159. ** read by older versions of SQLite.
  65160. */
  65161. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  65162. if( rc==SQLITE_OK ){
  65163. put4byte(&pTrunk->aData[4], nLeaf+1);
  65164. put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
  65165. if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
  65166. sqlite3PagerDontWrite(pPage->pDbPage);
  65167. }
  65168. rc = btreeSetHasContent(pBt, iPage);
  65169. }
  65170. TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
  65171. goto freepage_out;
  65172. }
  65173. }
  65174. /* If control flows to this point, then it was not possible to add the
  65175. ** the page being freed as a leaf page of the first trunk in the free-list.
  65176. ** Possibly because the free-list is empty, or possibly because the
  65177. ** first trunk in the free-list is full. Either way, the page being freed
  65178. ** will become the new first trunk page in the free-list.
  65179. */
  65180. if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
  65181. goto freepage_out;
  65182. }
  65183. rc = sqlite3PagerWrite(pPage->pDbPage);
  65184. if( rc!=SQLITE_OK ){
  65185. goto freepage_out;
  65186. }
  65187. put4byte(pPage->aData, iTrunk);
  65188. put4byte(&pPage->aData[4], 0);
  65189. put4byte(&pPage1->aData[32], iPage);
  65190. TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
  65191. freepage_out:
  65192. if( pPage ){
  65193. pPage->isInit = 0;
  65194. }
  65195. releasePage(pPage);
  65196. releasePage(pTrunk);
  65197. return rc;
  65198. }
  65199. static void freePage(MemPage *pPage, int *pRC){
  65200. if( (*pRC)==SQLITE_OK ){
  65201. *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
  65202. }
  65203. }
  65204. /*
  65205. ** Free any overflow pages associated with the given Cell. Store
  65206. ** size information about the cell in pInfo.
  65207. */
  65208. static int clearCell(
  65209. MemPage *pPage, /* The page that contains the Cell */
  65210. unsigned char *pCell, /* First byte of the Cell */
  65211. CellInfo *pInfo /* Size information about the cell */
  65212. ){
  65213. BtShared *pBt;
  65214. Pgno ovflPgno;
  65215. int rc;
  65216. int nOvfl;
  65217. u32 ovflPageSize;
  65218. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  65219. pPage->xParseCell(pPage, pCell, pInfo);
  65220. if( pInfo->nLocal==pInfo->nPayload ){
  65221. return SQLITE_OK; /* No overflow pages. Return without doing anything */
  65222. }
  65223. testcase( pCell + pInfo->nSize == pPage->aDataEnd );
  65224. testcase( pCell + (pInfo->nSize-1) == pPage->aDataEnd );
  65225. if( pCell + pInfo->nSize > pPage->aDataEnd ){
  65226. /* Cell extends past end of page */
  65227. return SQLITE_CORRUPT_PAGE(pPage);
  65228. }
  65229. ovflPgno = get4byte(pCell + pInfo->nSize - 4);
  65230. pBt = pPage->pBt;
  65231. assert( pBt->usableSize > 4 );
  65232. ovflPageSize = pBt->usableSize - 4;
  65233. nOvfl = (pInfo->nPayload - pInfo->nLocal + ovflPageSize - 1)/ovflPageSize;
  65234. assert( nOvfl>0 ||
  65235. (CORRUPT_DB && (pInfo->nPayload + ovflPageSize)<ovflPageSize)
  65236. );
  65237. while( nOvfl-- ){
  65238. Pgno iNext = 0;
  65239. MemPage *pOvfl = 0;
  65240. if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
  65241. /* 0 is not a legal page number and page 1 cannot be an
  65242. ** overflow page. Therefore if ovflPgno<2 or past the end of the
  65243. ** file the database must be corrupt. */
  65244. return SQLITE_CORRUPT_BKPT;
  65245. }
  65246. if( nOvfl ){
  65247. rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
  65248. if( rc ) return rc;
  65249. }
  65250. if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
  65251. && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
  65252. ){
  65253. /* There is no reason any cursor should have an outstanding reference
  65254. ** to an overflow page belonging to a cell that is being deleted/updated.
  65255. ** So if there exists more than one reference to this page, then it
  65256. ** must not really be an overflow page and the database must be corrupt.
  65257. ** It is helpful to detect this before calling freePage2(), as
  65258. ** freePage2() may zero the page contents if secure-delete mode is
  65259. ** enabled. If this 'overflow' page happens to be a page that the
  65260. ** caller is iterating through or using in some other way, this
  65261. ** can be problematic.
  65262. */
  65263. rc = SQLITE_CORRUPT_BKPT;
  65264. }else{
  65265. rc = freePage2(pBt, pOvfl, ovflPgno);
  65266. }
  65267. if( pOvfl ){
  65268. sqlite3PagerUnref(pOvfl->pDbPage);
  65269. }
  65270. if( rc ) return rc;
  65271. ovflPgno = iNext;
  65272. }
  65273. return SQLITE_OK;
  65274. }
  65275. /*
  65276. ** Create the byte sequence used to represent a cell on page pPage
  65277. ** and write that byte sequence into pCell[]. Overflow pages are
  65278. ** allocated and filled in as necessary. The calling procedure
  65279. ** is responsible for making sure sufficient space has been allocated
  65280. ** for pCell[].
  65281. **
  65282. ** Note that pCell does not necessary need to point to the pPage->aData
  65283. ** area. pCell might point to some temporary storage. The cell will
  65284. ** be constructed in this temporary area then copied into pPage->aData
  65285. ** later.
  65286. */
  65287. static int fillInCell(
  65288. MemPage *pPage, /* The page that contains the cell */
  65289. unsigned char *pCell, /* Complete text of the cell */
  65290. const BtreePayload *pX, /* Payload with which to construct the cell */
  65291. int *pnSize /* Write cell size here */
  65292. ){
  65293. int nPayload;
  65294. const u8 *pSrc;
  65295. int nSrc, n, rc, mn;
  65296. int spaceLeft;
  65297. MemPage *pToRelease;
  65298. unsigned char *pPrior;
  65299. unsigned char *pPayload;
  65300. BtShared *pBt;
  65301. Pgno pgnoOvfl;
  65302. int nHeader;
  65303. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  65304. /* pPage is not necessarily writeable since pCell might be auxiliary
  65305. ** buffer space that is separate from the pPage buffer area */
  65306. assert( pCell<pPage->aData || pCell>=&pPage->aData[pPage->pBt->pageSize]
  65307. || sqlite3PagerIswriteable(pPage->pDbPage) );
  65308. /* Fill in the header. */
  65309. nHeader = pPage->childPtrSize;
  65310. if( pPage->intKey ){
  65311. nPayload = pX->nData + pX->nZero;
  65312. pSrc = pX->pData;
  65313. nSrc = pX->nData;
  65314. assert( pPage->intKeyLeaf ); /* fillInCell() only called for leaves */
  65315. nHeader += putVarint32(&pCell[nHeader], nPayload);
  65316. nHeader += putVarint(&pCell[nHeader], *(u64*)&pX->nKey);
  65317. }else{
  65318. assert( pX->nKey<=0x7fffffff && pX->pKey!=0 );
  65319. nSrc = nPayload = (int)pX->nKey;
  65320. pSrc = pX->pKey;
  65321. nHeader += putVarint32(&pCell[nHeader], nPayload);
  65322. }
  65323. /* Fill in the payload */
  65324. pPayload = &pCell[nHeader];
  65325. if( nPayload<=pPage->maxLocal ){
  65326. /* This is the common case where everything fits on the btree page
  65327. ** and no overflow pages are required. */
  65328. n = nHeader + nPayload;
  65329. testcase( n==3 );
  65330. testcase( n==4 );
  65331. if( n<4 ) n = 4;
  65332. *pnSize = n;
  65333. assert( nSrc<=nPayload );
  65334. testcase( nSrc<nPayload );
  65335. memcpy(pPayload, pSrc, nSrc);
  65336. memset(pPayload+nSrc, 0, nPayload-nSrc);
  65337. return SQLITE_OK;
  65338. }
  65339. /* If we reach this point, it means that some of the content will need
  65340. ** to spill onto overflow pages.
  65341. */
  65342. mn = pPage->minLocal;
  65343. n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
  65344. testcase( n==pPage->maxLocal );
  65345. testcase( n==pPage->maxLocal+1 );
  65346. if( n > pPage->maxLocal ) n = mn;
  65347. spaceLeft = n;
  65348. *pnSize = n + nHeader + 4;
  65349. pPrior = &pCell[nHeader+n];
  65350. pToRelease = 0;
  65351. pgnoOvfl = 0;
  65352. pBt = pPage->pBt;
  65353. /* At this point variables should be set as follows:
  65354. **
  65355. ** nPayload Total payload size in bytes
  65356. ** pPayload Begin writing payload here
  65357. ** spaceLeft Space available at pPayload. If nPayload>spaceLeft,
  65358. ** that means content must spill into overflow pages.
  65359. ** *pnSize Size of the local cell (not counting overflow pages)
  65360. ** pPrior Where to write the pgno of the first overflow page
  65361. **
  65362. ** Use a call to btreeParseCellPtr() to verify that the values above
  65363. ** were computed correctly.
  65364. */
  65365. #ifdef SQLITE_DEBUG
  65366. {
  65367. CellInfo info;
  65368. pPage->xParseCell(pPage, pCell, &info);
  65369. assert( nHeader==(int)(info.pPayload - pCell) );
  65370. assert( info.nKey==pX->nKey );
  65371. assert( *pnSize == info.nSize );
  65372. assert( spaceLeft == info.nLocal );
  65373. }
  65374. #endif
  65375. /* Write the payload into the local Cell and any extra into overflow pages */
  65376. while( 1 ){
  65377. n = nPayload;
  65378. if( n>spaceLeft ) n = spaceLeft;
  65379. /* If pToRelease is not zero than pPayload points into the data area
  65380. ** of pToRelease. Make sure pToRelease is still writeable. */
  65381. assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
  65382. /* If pPayload is part of the data area of pPage, then make sure pPage
  65383. ** is still writeable */
  65384. assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
  65385. || sqlite3PagerIswriteable(pPage->pDbPage) );
  65386. if( nSrc>=n ){
  65387. memcpy(pPayload, pSrc, n);
  65388. }else if( nSrc>0 ){
  65389. n = nSrc;
  65390. memcpy(pPayload, pSrc, n);
  65391. }else{
  65392. memset(pPayload, 0, n);
  65393. }
  65394. nPayload -= n;
  65395. if( nPayload<=0 ) break;
  65396. pPayload += n;
  65397. pSrc += n;
  65398. nSrc -= n;
  65399. spaceLeft -= n;
  65400. if( spaceLeft==0 ){
  65401. MemPage *pOvfl = 0;
  65402. #ifndef SQLITE_OMIT_AUTOVACUUM
  65403. Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
  65404. if( pBt->autoVacuum ){
  65405. do{
  65406. pgnoOvfl++;
  65407. } while(
  65408. PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
  65409. );
  65410. }
  65411. #endif
  65412. rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
  65413. #ifndef SQLITE_OMIT_AUTOVACUUM
  65414. /* If the database supports auto-vacuum, and the second or subsequent
  65415. ** overflow page is being allocated, add an entry to the pointer-map
  65416. ** for that page now.
  65417. **
  65418. ** If this is the first overflow page, then write a partial entry
  65419. ** to the pointer-map. If we write nothing to this pointer-map slot,
  65420. ** then the optimistic overflow chain processing in clearCell()
  65421. ** may misinterpret the uninitialized values and delete the
  65422. ** wrong pages from the database.
  65423. */
  65424. if( pBt->autoVacuum && rc==SQLITE_OK ){
  65425. u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
  65426. ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
  65427. if( rc ){
  65428. releasePage(pOvfl);
  65429. }
  65430. }
  65431. #endif
  65432. if( rc ){
  65433. releasePage(pToRelease);
  65434. return rc;
  65435. }
  65436. /* If pToRelease is not zero than pPrior points into the data area
  65437. ** of pToRelease. Make sure pToRelease is still writeable. */
  65438. assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
  65439. /* If pPrior is part of the data area of pPage, then make sure pPage
  65440. ** is still writeable */
  65441. assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
  65442. || sqlite3PagerIswriteable(pPage->pDbPage) );
  65443. put4byte(pPrior, pgnoOvfl);
  65444. releasePage(pToRelease);
  65445. pToRelease = pOvfl;
  65446. pPrior = pOvfl->aData;
  65447. put4byte(pPrior, 0);
  65448. pPayload = &pOvfl->aData[4];
  65449. spaceLeft = pBt->usableSize - 4;
  65450. }
  65451. }
  65452. releasePage(pToRelease);
  65453. return SQLITE_OK;
  65454. }
  65455. /*
  65456. ** Remove the i-th cell from pPage. This routine effects pPage only.
  65457. ** The cell content is not freed or deallocated. It is assumed that
  65458. ** the cell content has been copied someplace else. This routine just
  65459. ** removes the reference to the cell from pPage.
  65460. **
  65461. ** "sz" must be the number of bytes in the cell.
  65462. */
  65463. static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
  65464. u32 pc; /* Offset to cell content of cell being deleted */
  65465. u8 *data; /* pPage->aData */
  65466. u8 *ptr; /* Used to move bytes around within data[] */
  65467. int rc; /* The return code */
  65468. int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */
  65469. if( *pRC ) return;
  65470. assert( idx>=0 && idx<pPage->nCell );
  65471. assert( CORRUPT_DB || sz==cellSize(pPage, idx) );
  65472. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  65473. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  65474. assert( pPage->nFree>=0 );
  65475. data = pPage->aData;
  65476. ptr = &pPage->aCellIdx[2*idx];
  65477. pc = get2byte(ptr);
  65478. hdr = pPage->hdrOffset;
  65479. testcase( pc==get2byte(&data[hdr+5]) );
  65480. testcase( pc+sz==pPage->pBt->usableSize );
  65481. if( pc+sz > pPage->pBt->usableSize ){
  65482. *pRC = SQLITE_CORRUPT_BKPT;
  65483. return;
  65484. }
  65485. rc = freeSpace(pPage, pc, sz);
  65486. if( rc ){
  65487. *pRC = rc;
  65488. return;
  65489. }
  65490. pPage->nCell--;
  65491. if( pPage->nCell==0 ){
  65492. memset(&data[hdr+1], 0, 4);
  65493. data[hdr+7] = 0;
  65494. put2byte(&data[hdr+5], pPage->pBt->usableSize);
  65495. pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset
  65496. - pPage->childPtrSize - 8;
  65497. }else{
  65498. memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
  65499. put2byte(&data[hdr+3], pPage->nCell);
  65500. pPage->nFree += 2;
  65501. }
  65502. }
  65503. /*
  65504. ** Insert a new cell on pPage at cell index "i". pCell points to the
  65505. ** content of the cell.
  65506. **
  65507. ** If the cell content will fit on the page, then put it there. If it
  65508. ** will not fit, then make a copy of the cell content into pTemp if
  65509. ** pTemp is not null. Regardless of pTemp, allocate a new entry
  65510. ** in pPage->apOvfl[] and make it point to the cell content (either
  65511. ** in pTemp or the original pCell) and also record its index.
  65512. ** Allocating a new entry in pPage->aCell[] implies that
  65513. ** pPage->nOverflow is incremented.
  65514. **
  65515. ** *pRC must be SQLITE_OK when this routine is called.
  65516. */
  65517. static void insertCell(
  65518. MemPage *pPage, /* Page into which we are copying */
  65519. int i, /* New cell becomes the i-th cell of the page */
  65520. u8 *pCell, /* Content of the new cell */
  65521. int sz, /* Bytes of content in pCell */
  65522. u8 *pTemp, /* Temp storage space for pCell, if needed */
  65523. Pgno iChild, /* If non-zero, replace first 4 bytes with this value */
  65524. int *pRC /* Read and write return code from here */
  65525. ){
  65526. int idx = 0; /* Where to write new cell content in data[] */
  65527. int j; /* Loop counter */
  65528. u8 *data; /* The content of the whole page */
  65529. u8 *pIns; /* The point in pPage->aCellIdx[] where no cell inserted */
  65530. assert( *pRC==SQLITE_OK );
  65531. assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
  65532. assert( MX_CELL(pPage->pBt)<=10921 );
  65533. assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
  65534. assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
  65535. assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
  65536. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  65537. /* The cell should normally be sized correctly. However, when moving a
  65538. ** malformed cell from a leaf page to an interior page, if the cell size
  65539. ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
  65540. ** might be less than 8 (leaf-size + pointer) on the interior node. Hence
  65541. ** the term after the || in the following assert(). */
  65542. assert( sz==pPage->xCellSize(pPage, pCell) || (sz==8 && iChild>0) );
  65543. assert( pPage->nFree>=0 );
  65544. if( pPage->nOverflow || sz+2>pPage->nFree ){
  65545. if( pTemp ){
  65546. memcpy(pTemp, pCell, sz);
  65547. pCell = pTemp;
  65548. }
  65549. if( iChild ){
  65550. put4byte(pCell, iChild);
  65551. }
  65552. j = pPage->nOverflow++;
  65553. /* Comparison against ArraySize-1 since we hold back one extra slot
  65554. ** as a contingency. In other words, never need more than 3 overflow
  65555. ** slots but 4 are allocated, just to be safe. */
  65556. assert( j < ArraySize(pPage->apOvfl)-1 );
  65557. pPage->apOvfl[j] = pCell;
  65558. pPage->aiOvfl[j] = (u16)i;
  65559. /* When multiple overflows occur, they are always sequential and in
  65560. ** sorted order. This invariants arise because multiple overflows can
  65561. ** only occur when inserting divider cells into the parent page during
  65562. ** balancing, and the dividers are adjacent and sorted.
  65563. */
  65564. assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */
  65565. assert( j==0 || i==pPage->aiOvfl[j-1]+1 ); /* Overflows are sequential */
  65566. }else{
  65567. int rc = sqlite3PagerWrite(pPage->pDbPage);
  65568. if( rc!=SQLITE_OK ){
  65569. *pRC = rc;
  65570. return;
  65571. }
  65572. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  65573. data = pPage->aData;
  65574. assert( &data[pPage->cellOffset]==pPage->aCellIdx );
  65575. rc = allocateSpace(pPage, sz, &idx);
  65576. if( rc ){ *pRC = rc; return; }
  65577. /* The allocateSpace() routine guarantees the following properties
  65578. ** if it returns successfully */
  65579. assert( idx >= 0 );
  65580. assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB );
  65581. assert( idx+sz <= (int)pPage->pBt->usableSize );
  65582. pPage->nFree -= (u16)(2 + sz);
  65583. if( iChild ){
  65584. /* In a corrupt database where an entry in the cell index section of
  65585. ** a btree page has a value of 3 or less, the pCell value might point
  65586. ** as many as 4 bytes in front of the start of the aData buffer for
  65587. ** the source page. Make sure this does not cause problems by not
  65588. ** reading the first 4 bytes */
  65589. memcpy(&data[idx+4], pCell+4, sz-4);
  65590. put4byte(&data[idx], iChild);
  65591. }else{
  65592. memcpy(&data[idx], pCell, sz);
  65593. }
  65594. pIns = pPage->aCellIdx + i*2;
  65595. memmove(pIns+2, pIns, 2*(pPage->nCell - i));
  65596. put2byte(pIns, idx);
  65597. pPage->nCell++;
  65598. /* increment the cell count */
  65599. if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++;
  65600. assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell || CORRUPT_DB );
  65601. #ifndef SQLITE_OMIT_AUTOVACUUM
  65602. if( pPage->pBt->autoVacuum ){
  65603. /* The cell may contain a pointer to an overflow page. If so, write
  65604. ** the entry for the overflow page into the pointer map.
  65605. */
  65606. ptrmapPutOvflPtr(pPage, pPage, pCell, pRC);
  65607. }
  65608. #endif
  65609. }
  65610. }
  65611. /*
  65612. ** The following parameters determine how many adjacent pages get involved
  65613. ** in a balancing operation. NN is the number of neighbors on either side
  65614. ** of the page that participate in the balancing operation. NB is the
  65615. ** total number of pages that participate, including the target page and
  65616. ** NN neighbors on either side.
  65617. **
  65618. ** The minimum value of NN is 1 (of course). Increasing NN above 1
  65619. ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
  65620. ** in exchange for a larger degradation in INSERT and UPDATE performance.
  65621. ** The value of NN appears to give the best results overall.
  65622. **
  65623. ** (Later:) The description above makes it seem as if these values are
  65624. ** tunable - as if you could change them and recompile and it would all work.
  65625. ** But that is unlikely. NB has been 3 since the inception of SQLite and
  65626. ** we have never tested any other value.
  65627. */
  65628. #define NN 1 /* Number of neighbors on either side of pPage */
  65629. #define NB 3 /* (NN*2+1): Total pages involved in the balance */
  65630. /*
  65631. ** A CellArray object contains a cache of pointers and sizes for a
  65632. ** consecutive sequence of cells that might be held on multiple pages.
  65633. **
  65634. ** The cells in this array are the divider cell or cells from the pParent
  65635. ** page plus up to three child pages. There are a total of nCell cells.
  65636. **
  65637. ** pRef is a pointer to one of the pages that contributes cells. This is
  65638. ** used to access information such as MemPage.intKey and MemPage.pBt->pageSize
  65639. ** which should be common to all pages that contribute cells to this array.
  65640. **
  65641. ** apCell[] and szCell[] hold, respectively, pointers to the start of each
  65642. ** cell and the size of each cell. Some of the apCell[] pointers might refer
  65643. ** to overflow cells. In other words, some apCel[] pointers might not point
  65644. ** to content area of the pages.
  65645. **
  65646. ** A szCell[] of zero means the size of that cell has not yet been computed.
  65647. **
  65648. ** The cells come from as many as four different pages:
  65649. **
  65650. ** -----------
  65651. ** | Parent |
  65652. ** -----------
  65653. ** / | \
  65654. ** / | \
  65655. ** --------- --------- ---------
  65656. ** |Child-1| |Child-2| |Child-3|
  65657. ** --------- --------- ---------
  65658. **
  65659. ** The order of cells is in the array is for an index btree is:
  65660. **
  65661. ** 1. All cells from Child-1 in order
  65662. ** 2. The first divider cell from Parent
  65663. ** 3. All cells from Child-2 in order
  65664. ** 4. The second divider cell from Parent
  65665. ** 5. All cells from Child-3 in order
  65666. **
  65667. ** For a table-btree (with rowids) the items 2 and 4 are empty because
  65668. ** content exists only in leaves and there are no divider cells.
  65669. **
  65670. ** For an index btree, the apEnd[] array holds pointer to the end of page
  65671. ** for Child-1, the Parent, Child-2, the Parent (again), and Child-3,
  65672. ** respectively. The ixNx[] array holds the number of cells contained in
  65673. ** each of these 5 stages, and all stages to the left. Hence:
  65674. **
  65675. ** ixNx[0] = Number of cells in Child-1.
  65676. ** ixNx[1] = Number of cells in Child-1 plus 1 for first divider.
  65677. ** ixNx[2] = Number of cells in Child-1 and Child-2 + 1 for 1st divider.
  65678. ** ixNx[3] = Number of cells in Child-1 and Child-2 + both divider cells
  65679. ** ixNx[4] = Total number of cells.
  65680. **
  65681. ** For a table-btree, the concept is similar, except only apEnd[0]..apEnd[2]
  65682. ** are used and they point to the leaf pages only, and the ixNx value are:
  65683. **
  65684. ** ixNx[0] = Number of cells in Child-1.
  65685. ** ixNx[1] = Number of cells in Child-1 and Child-2.
  65686. ** ixNx[2] = Total number of cells.
  65687. **
  65688. ** Sometimes when deleting, a child page can have zero cells. In those
  65689. ** cases, ixNx[] entries with higher indexes, and the corresponding apEnd[]
  65690. ** entries, shift down. The end result is that each ixNx[] entry should
  65691. ** be larger than the previous
  65692. */
  65693. typedef struct CellArray CellArray;
  65694. struct CellArray {
  65695. int nCell; /* Number of cells in apCell[] */
  65696. MemPage *pRef; /* Reference page */
  65697. u8 **apCell; /* All cells begin balanced */
  65698. u16 *szCell; /* Local size of all cells in apCell[] */
  65699. u8 *apEnd[NB*2]; /* MemPage.aDataEnd values */
  65700. int ixNx[NB*2]; /* Index of at which we move to the next apEnd[] */
  65701. };
  65702. /*
  65703. ** Make sure the cell sizes at idx, idx+1, ..., idx+N-1 have been
  65704. ** computed.
  65705. */
  65706. static void populateCellCache(CellArray *p, int idx, int N){
  65707. assert( idx>=0 && idx+N<=p->nCell );
  65708. while( N>0 ){
  65709. assert( p->apCell[idx]!=0 );
  65710. if( p->szCell[idx]==0 ){
  65711. p->szCell[idx] = p->pRef->xCellSize(p->pRef, p->apCell[idx]);
  65712. }else{
  65713. assert( CORRUPT_DB ||
  65714. p->szCell[idx]==p->pRef->xCellSize(p->pRef, p->apCell[idx]) );
  65715. }
  65716. idx++;
  65717. N--;
  65718. }
  65719. }
  65720. /*
  65721. ** Return the size of the Nth element of the cell array
  65722. */
  65723. static SQLITE_NOINLINE u16 computeCellSize(CellArray *p, int N){
  65724. assert( N>=0 && N<p->nCell );
  65725. assert( p->szCell[N]==0 );
  65726. p->szCell[N] = p->pRef->xCellSize(p->pRef, p->apCell[N]);
  65727. return p->szCell[N];
  65728. }
  65729. static u16 cachedCellSize(CellArray *p, int N){
  65730. assert( N>=0 && N<p->nCell );
  65731. if( p->szCell[N] ) return p->szCell[N];
  65732. return computeCellSize(p, N);
  65733. }
  65734. /*
  65735. ** Array apCell[] contains pointers to nCell b-tree page cells. The
  65736. ** szCell[] array contains the size in bytes of each cell. This function
  65737. ** replaces the current contents of page pPg with the contents of the cell
  65738. ** array.
  65739. **
  65740. ** Some of the cells in apCell[] may currently be stored in pPg. This
  65741. ** function works around problems caused by this by making a copy of any
  65742. ** such cells before overwriting the page data.
  65743. **
  65744. ** The MemPage.nFree field is invalidated by this function. It is the
  65745. ** responsibility of the caller to set it correctly.
  65746. */
  65747. static int rebuildPage(
  65748. CellArray *pCArray, /* Content to be added to page pPg */
  65749. int iFirst, /* First cell in pCArray to use */
  65750. int nCell, /* Final number of cells on page */
  65751. MemPage *pPg /* The page to be reconstructed */
  65752. ){
  65753. const int hdr = pPg->hdrOffset; /* Offset of header on pPg */
  65754. u8 * const aData = pPg->aData; /* Pointer to data for pPg */
  65755. const int usableSize = pPg->pBt->usableSize;
  65756. u8 * const pEnd = &aData[usableSize];
  65757. int i = iFirst; /* Which cell to copy from pCArray*/
  65758. u32 j; /* Start of cell content area */
  65759. int iEnd = i+nCell; /* Loop terminator */
  65760. u8 *pCellptr = pPg->aCellIdx;
  65761. u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
  65762. u8 *pData;
  65763. int k; /* Current slot in pCArray->apEnd[] */
  65764. u8 *pSrcEnd; /* Current pCArray->apEnd[k] value */
  65765. assert( i<iEnd );
  65766. j = get2byte(&aData[hdr+5]);
  65767. if( NEVER(j>(u32)usableSize) ){ j = 0; }
  65768. memcpy(&pTmp[j], &aData[j], usableSize - j);
  65769. for(k=0; pCArray->ixNx[k]<=i && ALWAYS(k<NB*2); k++){}
  65770. pSrcEnd = pCArray->apEnd[k];
  65771. pData = pEnd;
  65772. while( 1/*exit by break*/ ){
  65773. u8 *pCell = pCArray->apCell[i];
  65774. u16 sz = pCArray->szCell[i];
  65775. assert( sz>0 );
  65776. if( SQLITE_WITHIN(pCell,aData,pEnd) ){
  65777. if( ((uptr)(pCell+sz))>(uptr)pEnd ) return SQLITE_CORRUPT_BKPT;
  65778. pCell = &pTmp[pCell - aData];
  65779. }else if( (uptr)(pCell+sz)>(uptr)pSrcEnd
  65780. && (uptr)(pCell)<(uptr)pSrcEnd
  65781. ){
  65782. return SQLITE_CORRUPT_BKPT;
  65783. }
  65784. pData -= sz;
  65785. put2byte(pCellptr, (pData - aData));
  65786. pCellptr += 2;
  65787. if( pData < pCellptr ) return SQLITE_CORRUPT_BKPT;
  65788. memcpy(pData, pCell, sz);
  65789. assert( sz==pPg->xCellSize(pPg, pCell) || CORRUPT_DB );
  65790. testcase( sz!=pPg->xCellSize(pPg,pCell) );
  65791. i++;
  65792. if( i>=iEnd ) break;
  65793. if( pCArray->ixNx[k]<=i ){
  65794. k++;
  65795. pSrcEnd = pCArray->apEnd[k];
  65796. }
  65797. }
  65798. /* The pPg->nFree field is now set incorrectly. The caller will fix it. */
  65799. pPg->nCell = nCell;
  65800. pPg->nOverflow = 0;
  65801. put2byte(&aData[hdr+1], 0);
  65802. put2byte(&aData[hdr+3], pPg->nCell);
  65803. put2byte(&aData[hdr+5], pData - aData);
  65804. aData[hdr+7] = 0x00;
  65805. return SQLITE_OK;
  65806. }
  65807. /*
  65808. ** The pCArray objects contains pointers to b-tree cells and the cell sizes.
  65809. ** This function attempts to add the cells stored in the array to page pPg.
  65810. ** If it cannot (because the page needs to be defragmented before the cells
  65811. ** will fit), non-zero is returned. Otherwise, if the cells are added
  65812. ** successfully, zero is returned.
  65813. **
  65814. ** Argument pCellptr points to the first entry in the cell-pointer array
  65815. ** (part of page pPg) to populate. After cell apCell[0] is written to the
  65816. ** page body, a 16-bit offset is written to pCellptr. And so on, for each
  65817. ** cell in the array. It is the responsibility of the caller to ensure
  65818. ** that it is safe to overwrite this part of the cell-pointer array.
  65819. **
  65820. ** When this function is called, *ppData points to the start of the
  65821. ** content area on page pPg. If the size of the content area is extended,
  65822. ** *ppData is updated to point to the new start of the content area
  65823. ** before returning.
  65824. **
  65825. ** Finally, argument pBegin points to the byte immediately following the
  65826. ** end of the space required by this page for the cell-pointer area (for
  65827. ** all cells - not just those inserted by the current call). If the content
  65828. ** area must be extended to before this point in order to accomodate all
  65829. ** cells in apCell[], then the cells do not fit and non-zero is returned.
  65830. */
  65831. static int pageInsertArray(
  65832. MemPage *pPg, /* Page to add cells to */
  65833. u8 *pBegin, /* End of cell-pointer array */
  65834. u8 **ppData, /* IN/OUT: Page content-area pointer */
  65835. u8 *pCellptr, /* Pointer to cell-pointer area */
  65836. int iFirst, /* Index of first cell to add */
  65837. int nCell, /* Number of cells to add to pPg */
  65838. CellArray *pCArray /* Array of cells */
  65839. ){
  65840. int i = iFirst; /* Loop counter - cell index to insert */
  65841. u8 *aData = pPg->aData; /* Complete page */
  65842. u8 *pData = *ppData; /* Content area. A subset of aData[] */
  65843. int iEnd = iFirst + nCell; /* End of loop. One past last cell to ins */
  65844. int k; /* Current slot in pCArray->apEnd[] */
  65845. u8 *pEnd; /* Maximum extent of cell data */
  65846. assert( CORRUPT_DB || pPg->hdrOffset==0 ); /* Never called on page 1 */
  65847. if( iEnd<=iFirst ) return 0;
  65848. for(k=0; pCArray->ixNx[k]<=i && ALWAYS(k<NB*2); k++){}
  65849. pEnd = pCArray->apEnd[k];
  65850. while( 1 /*Exit by break*/ ){
  65851. int sz, rc;
  65852. u8 *pSlot;
  65853. sz = cachedCellSize(pCArray, i);
  65854. if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){
  65855. if( (pData - pBegin)<sz ) return 1;
  65856. pData -= sz;
  65857. pSlot = pData;
  65858. }
  65859. /* pSlot and pCArray->apCell[i] will never overlap on a well-formed
  65860. ** database. But they might for a corrupt database. Hence use memmove()
  65861. ** since memcpy() sends SIGABORT with overlapping buffers on OpenBSD */
  65862. assert( (pSlot+sz)<=pCArray->apCell[i]
  65863. || pSlot>=(pCArray->apCell[i]+sz)
  65864. || CORRUPT_DB );
  65865. if( (uptr)(pCArray->apCell[i]+sz)>(uptr)pEnd
  65866. && (uptr)(pCArray->apCell[i])<(uptr)pEnd
  65867. ){
  65868. assert( CORRUPT_DB );
  65869. (void)SQLITE_CORRUPT_BKPT;
  65870. return 1;
  65871. }
  65872. memmove(pSlot, pCArray->apCell[i], sz);
  65873. put2byte(pCellptr, (pSlot - aData));
  65874. pCellptr += 2;
  65875. i++;
  65876. if( i>=iEnd ) break;
  65877. if( pCArray->ixNx[k]<=i ){
  65878. k++;
  65879. pEnd = pCArray->apEnd[k];
  65880. }
  65881. }
  65882. *ppData = pData;
  65883. return 0;
  65884. }
  65885. /*
  65886. ** The pCArray object contains pointers to b-tree cells and their sizes.
  65887. **
  65888. ** This function adds the space associated with each cell in the array
  65889. ** that is currently stored within the body of pPg to the pPg free-list.
  65890. ** The cell-pointers and other fields of the page are not updated.
  65891. **
  65892. ** This function returns the total number of cells added to the free-list.
  65893. */
  65894. static int pageFreeArray(
  65895. MemPage *pPg, /* Page to edit */
  65896. int iFirst, /* First cell to delete */
  65897. int nCell, /* Cells to delete */
  65898. CellArray *pCArray /* Array of cells */
  65899. ){
  65900. u8 * const aData = pPg->aData;
  65901. u8 * const pEnd = &aData[pPg->pBt->usableSize];
  65902. u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize];
  65903. int nRet = 0;
  65904. int i;
  65905. int iEnd = iFirst + nCell;
  65906. u8 *pFree = 0;
  65907. int szFree = 0;
  65908. for(i=iFirst; i<iEnd; i++){
  65909. u8 *pCell = pCArray->apCell[i];
  65910. if( SQLITE_WITHIN(pCell, pStart, pEnd) ){
  65911. int sz;
  65912. /* No need to use cachedCellSize() here. The sizes of all cells that
  65913. ** are to be freed have already been computing while deciding which
  65914. ** cells need freeing */
  65915. sz = pCArray->szCell[i]; assert( sz>0 );
  65916. if( pFree!=(pCell + sz) ){
  65917. if( pFree ){
  65918. assert( pFree>aData && (pFree - aData)<65536 );
  65919. freeSpace(pPg, (u16)(pFree - aData), szFree);
  65920. }
  65921. pFree = pCell;
  65922. szFree = sz;
  65923. if( pFree+sz>pEnd ) return 0;
  65924. }else{
  65925. pFree = pCell;
  65926. szFree += sz;
  65927. }
  65928. nRet++;
  65929. }
  65930. }
  65931. if( pFree ){
  65932. assert( pFree>aData && (pFree - aData)<65536 );
  65933. freeSpace(pPg, (u16)(pFree - aData), szFree);
  65934. }
  65935. return nRet;
  65936. }
  65937. /*
  65938. ** pCArray contains pointers to and sizes of all cells in the page being
  65939. ** balanced. The current page, pPg, has pPg->nCell cells starting with
  65940. ** pCArray->apCell[iOld]. After balancing, this page should hold nNew cells
  65941. ** starting at apCell[iNew].
  65942. **
  65943. ** This routine makes the necessary adjustments to pPg so that it contains
  65944. ** the correct cells after being balanced.
  65945. **
  65946. ** The pPg->nFree field is invalid when this function returns. It is the
  65947. ** responsibility of the caller to set it correctly.
  65948. */
  65949. static int editPage(
  65950. MemPage *pPg, /* Edit this page */
  65951. int iOld, /* Index of first cell currently on page */
  65952. int iNew, /* Index of new first cell on page */
  65953. int nNew, /* Final number of cells on page */
  65954. CellArray *pCArray /* Array of cells and sizes */
  65955. ){
  65956. u8 * const aData = pPg->aData;
  65957. const int hdr = pPg->hdrOffset;
  65958. u8 *pBegin = &pPg->aCellIdx[nNew * 2];
  65959. int nCell = pPg->nCell; /* Cells stored on pPg */
  65960. u8 *pData;
  65961. u8 *pCellptr;
  65962. int i;
  65963. int iOldEnd = iOld + pPg->nCell + pPg->nOverflow;
  65964. int iNewEnd = iNew + nNew;
  65965. #ifdef SQLITE_DEBUG
  65966. u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
  65967. memcpy(pTmp, aData, pPg->pBt->usableSize);
  65968. #endif
  65969. /* Remove cells from the start and end of the page */
  65970. assert( nCell>=0 );
  65971. if( iOld<iNew ){
  65972. int nShift = pageFreeArray(pPg, iOld, iNew-iOld, pCArray);
  65973. if( nShift>nCell ) return SQLITE_CORRUPT_BKPT;
  65974. memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2);
  65975. nCell -= nShift;
  65976. }
  65977. if( iNewEnd < iOldEnd ){
  65978. int nTail = pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray);
  65979. assert( nCell>=nTail );
  65980. nCell -= nTail;
  65981. }
  65982. pData = &aData[get2byteNotZero(&aData[hdr+5])];
  65983. if( pData<pBegin ) goto editpage_fail;
  65984. /* Add cells to the start of the page */
  65985. if( iNew<iOld ){
  65986. int nAdd = MIN(nNew,iOld-iNew);
  65987. assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB );
  65988. assert( nAdd>=0 );
  65989. pCellptr = pPg->aCellIdx;
  65990. memmove(&pCellptr[nAdd*2], pCellptr, nCell*2);
  65991. if( pageInsertArray(
  65992. pPg, pBegin, &pData, pCellptr,
  65993. iNew, nAdd, pCArray
  65994. ) ) goto editpage_fail;
  65995. nCell += nAdd;
  65996. }
  65997. /* Add any overflow cells */
  65998. for(i=0; i<pPg->nOverflow; i++){
  65999. int iCell = (iOld + pPg->aiOvfl[i]) - iNew;
  66000. if( iCell>=0 && iCell<nNew ){
  66001. pCellptr = &pPg->aCellIdx[iCell * 2];
  66002. if( nCell>iCell ){
  66003. memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2);
  66004. }
  66005. nCell++;
  66006. if( pageInsertArray(
  66007. pPg, pBegin, &pData, pCellptr,
  66008. iCell+iNew, 1, pCArray
  66009. ) ) goto editpage_fail;
  66010. }
  66011. }
  66012. /* Append cells to the end of the page */
  66013. assert( nCell>=0 );
  66014. pCellptr = &pPg->aCellIdx[nCell*2];
  66015. if( pageInsertArray(
  66016. pPg, pBegin, &pData, pCellptr,
  66017. iNew+nCell, nNew-nCell, pCArray
  66018. ) ) goto editpage_fail;
  66019. pPg->nCell = nNew;
  66020. pPg->nOverflow = 0;
  66021. put2byte(&aData[hdr+3], pPg->nCell);
  66022. put2byte(&aData[hdr+5], pData - aData);
  66023. #ifdef SQLITE_DEBUG
  66024. for(i=0; i<nNew && !CORRUPT_DB; i++){
  66025. u8 *pCell = pCArray->apCell[i+iNew];
  66026. int iOff = get2byteAligned(&pPg->aCellIdx[i*2]);
  66027. if( SQLITE_WITHIN(pCell, aData, &aData[pPg->pBt->usableSize]) ){
  66028. pCell = &pTmp[pCell - aData];
  66029. }
  66030. assert( 0==memcmp(pCell, &aData[iOff],
  66031. pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) );
  66032. }
  66033. #endif
  66034. return SQLITE_OK;
  66035. editpage_fail:
  66036. /* Unable to edit this page. Rebuild it from scratch instead. */
  66037. populateCellCache(pCArray, iNew, nNew);
  66038. return rebuildPage(pCArray, iNew, nNew, pPg);
  66039. }
  66040. #ifndef SQLITE_OMIT_QUICKBALANCE
  66041. /*
  66042. ** This version of balance() handles the common special case where
  66043. ** a new entry is being inserted on the extreme right-end of the
  66044. ** tree, in other words, when the new entry will become the largest
  66045. ** entry in the tree.
  66046. **
  66047. ** Instead of trying to balance the 3 right-most leaf pages, just add
  66048. ** a new page to the right-hand side and put the one new entry in
  66049. ** that page. This leaves the right side of the tree somewhat
  66050. ** unbalanced. But odds are that we will be inserting new entries
  66051. ** at the end soon afterwards so the nearly empty page will quickly
  66052. ** fill up. On average.
  66053. **
  66054. ** pPage is the leaf page which is the right-most page in the tree.
  66055. ** pParent is its parent. pPage must have a single overflow entry
  66056. ** which is also the right-most entry on the page.
  66057. **
  66058. ** The pSpace buffer is used to store a temporary copy of the divider
  66059. ** cell that will be inserted into pParent. Such a cell consists of a 4
  66060. ** byte page number followed by a variable length integer. In other
  66061. ** words, at most 13 bytes. Hence the pSpace buffer must be at
  66062. ** least 13 bytes in size.
  66063. */
  66064. static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
  66065. BtShared *const pBt = pPage->pBt; /* B-Tree Database */
  66066. MemPage *pNew; /* Newly allocated page */
  66067. int rc; /* Return Code */
  66068. Pgno pgnoNew; /* Page number of pNew */
  66069. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  66070. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  66071. assert( pPage->nOverflow==1 );
  66072. if( pPage->nCell==0 ) return SQLITE_CORRUPT_BKPT; /* dbfuzz001.test */
  66073. assert( pPage->nFree>=0 );
  66074. assert( pParent->nFree>=0 );
  66075. /* Allocate a new page. This page will become the right-sibling of
  66076. ** pPage. Make the parent page writable, so that the new divider cell
  66077. ** may be inserted. If both these operations are successful, proceed.
  66078. */
  66079. rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
  66080. if( rc==SQLITE_OK ){
  66081. u8 *pOut = &pSpace[4];
  66082. u8 *pCell = pPage->apOvfl[0];
  66083. u16 szCell = pPage->xCellSize(pPage, pCell);
  66084. u8 *pStop;
  66085. CellArray b;
  66086. assert( sqlite3PagerIswriteable(pNew->pDbPage) );
  66087. assert( CORRUPT_DB || pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
  66088. zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
  66089. b.nCell = 1;
  66090. b.pRef = pPage;
  66091. b.apCell = &pCell;
  66092. b.szCell = &szCell;
  66093. b.apEnd[0] = pPage->aDataEnd;
  66094. b.ixNx[0] = 2;
  66095. rc = rebuildPage(&b, 0, 1, pNew);
  66096. if( NEVER(rc) ){
  66097. releasePage(pNew);
  66098. return rc;
  66099. }
  66100. pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;
  66101. /* If this is an auto-vacuum database, update the pointer map
  66102. ** with entries for the new page, and any pointer from the
  66103. ** cell on the page to an overflow page. If either of these
  66104. ** operations fails, the return code is set, but the contents
  66105. ** of the parent page are still manipulated by thh code below.
  66106. ** That is Ok, at this point the parent page is guaranteed to
  66107. ** be marked as dirty. Returning an error code will cause a
  66108. ** rollback, undoing any changes made to the parent page.
  66109. */
  66110. if( ISAUTOVACUUM ){
  66111. ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
  66112. if( szCell>pNew->minLocal ){
  66113. ptrmapPutOvflPtr(pNew, pNew, pCell, &rc);
  66114. }
  66115. }
  66116. /* Create a divider cell to insert into pParent. The divider cell
  66117. ** consists of a 4-byte page number (the page number of pPage) and
  66118. ** a variable length key value (which must be the same value as the
  66119. ** largest key on pPage).
  66120. **
  66121. ** To find the largest key value on pPage, first find the right-most
  66122. ** cell on pPage. The first two fields of this cell are the
  66123. ** record-length (a variable length integer at most 32-bits in size)
  66124. ** and the key value (a variable length integer, may have any value).
  66125. ** The first of the while(...) loops below skips over the record-length
  66126. ** field. The second while(...) loop copies the key value from the
  66127. ** cell on pPage into the pSpace buffer.
  66128. */
  66129. pCell = findCell(pPage, pPage->nCell-1);
  66130. pStop = &pCell[9];
  66131. while( (*(pCell++)&0x80) && pCell<pStop );
  66132. pStop = &pCell[9];
  66133. while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
  66134. /* Insert the new divider cell into pParent. */
  66135. if( rc==SQLITE_OK ){
  66136. insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
  66137. 0, pPage->pgno, &rc);
  66138. }
  66139. /* Set the right-child pointer of pParent to point to the new page. */
  66140. put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
  66141. /* Release the reference to the new page. */
  66142. releasePage(pNew);
  66143. }
  66144. return rc;
  66145. }
  66146. #endif /* SQLITE_OMIT_QUICKBALANCE */
  66147. #if 0
  66148. /*
  66149. ** This function does not contribute anything to the operation of SQLite.
  66150. ** it is sometimes activated temporarily while debugging code responsible
  66151. ** for setting pointer-map entries.
  66152. */
  66153. static int ptrmapCheckPages(MemPage **apPage, int nPage){
  66154. int i, j;
  66155. for(i=0; i<nPage; i++){
  66156. Pgno n;
  66157. u8 e;
  66158. MemPage *pPage = apPage[i];
  66159. BtShared *pBt = pPage->pBt;
  66160. assert( pPage->isInit );
  66161. for(j=0; j<pPage->nCell; j++){
  66162. CellInfo info;
  66163. u8 *z;
  66164. z = findCell(pPage, j);
  66165. pPage->xParseCell(pPage, z, &info);
  66166. if( info.nLocal<info.nPayload ){
  66167. Pgno ovfl = get4byte(&z[info.nSize-4]);
  66168. ptrmapGet(pBt, ovfl, &e, &n);
  66169. assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
  66170. }
  66171. if( !pPage->leaf ){
  66172. Pgno child = get4byte(z);
  66173. ptrmapGet(pBt, child, &e, &n);
  66174. assert( n==pPage->pgno && e==PTRMAP_BTREE );
  66175. }
  66176. }
  66177. if( !pPage->leaf ){
  66178. Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  66179. ptrmapGet(pBt, child, &e, &n);
  66180. assert( n==pPage->pgno && e==PTRMAP_BTREE );
  66181. }
  66182. }
  66183. return 1;
  66184. }
  66185. #endif
  66186. /*
  66187. ** This function is used to copy the contents of the b-tree node stored
  66188. ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
  66189. ** the pointer-map entries for each child page are updated so that the
  66190. ** parent page stored in the pointer map is page pTo. If pFrom contained
  66191. ** any cells with overflow page pointers, then the corresponding pointer
  66192. ** map entries are also updated so that the parent page is page pTo.
  66193. **
  66194. ** If pFrom is currently carrying any overflow cells (entries in the
  66195. ** MemPage.apOvfl[] array), they are not copied to pTo.
  66196. **
  66197. ** Before returning, page pTo is reinitialized using btreeInitPage().
  66198. **
  66199. ** The performance of this function is not critical. It is only used by
  66200. ** the balance_shallower() and balance_deeper() procedures, neither of
  66201. ** which are called often under normal circumstances.
  66202. */
  66203. static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
  66204. if( (*pRC)==SQLITE_OK ){
  66205. BtShared * const pBt = pFrom->pBt;
  66206. u8 * const aFrom = pFrom->aData;
  66207. u8 * const aTo = pTo->aData;
  66208. int const iFromHdr = pFrom->hdrOffset;
  66209. int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
  66210. int rc;
  66211. int iData;
  66212. assert( pFrom->isInit );
  66213. assert( pFrom->nFree>=iToHdr );
  66214. assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
  66215. /* Copy the b-tree node content from page pFrom to page pTo. */
  66216. iData = get2byte(&aFrom[iFromHdr+5]);
  66217. memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
  66218. memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
  66219. /* Reinitialize page pTo so that the contents of the MemPage structure
  66220. ** match the new data. The initialization of pTo can actually fail under
  66221. ** fairly obscure circumstances, even though it is a copy of initialized
  66222. ** page pFrom.
  66223. */
  66224. pTo->isInit = 0;
  66225. rc = btreeInitPage(pTo);
  66226. if( rc==SQLITE_OK ) rc = btreeComputeFreeSpace(pTo);
  66227. if( rc!=SQLITE_OK ){
  66228. *pRC = rc;
  66229. return;
  66230. }
  66231. /* If this is an auto-vacuum database, update the pointer-map entries
  66232. ** for any b-tree or overflow pages that pTo now contains the pointers to.
  66233. */
  66234. if( ISAUTOVACUUM ){
  66235. *pRC = setChildPtrmaps(pTo);
  66236. }
  66237. }
  66238. }
  66239. /*
  66240. ** This routine redistributes cells on the iParentIdx'th child of pParent
  66241. ** (hereafter "the page") and up to 2 siblings so that all pages have about the
  66242. ** same amount of free space. Usually a single sibling on either side of the
  66243. ** page are used in the balancing, though both siblings might come from one
  66244. ** side if the page is the first or last child of its parent. If the page
  66245. ** has fewer than 2 siblings (something which can only happen if the page
  66246. ** is a root page or a child of a root page) then all available siblings
  66247. ** participate in the balancing.
  66248. **
  66249. ** The number of siblings of the page might be increased or decreased by
  66250. ** one or two in an effort to keep pages nearly full but not over full.
  66251. **
  66252. ** Note that when this routine is called, some of the cells on the page
  66253. ** might not actually be stored in MemPage.aData[]. This can happen
  66254. ** if the page is overfull. This routine ensures that all cells allocated
  66255. ** to the page and its siblings fit into MemPage.aData[] before returning.
  66256. **
  66257. ** In the course of balancing the page and its siblings, cells may be
  66258. ** inserted into or removed from the parent page (pParent). Doing so
  66259. ** may cause the parent page to become overfull or underfull. If this
  66260. ** happens, it is the responsibility of the caller to invoke the correct
  66261. ** balancing routine to fix this problem (see the balance() routine).
  66262. **
  66263. ** If this routine fails for any reason, it might leave the database
  66264. ** in a corrupted state. So if this routine fails, the database should
  66265. ** be rolled back.
  66266. **
  66267. ** The third argument to this function, aOvflSpace, is a pointer to a
  66268. ** buffer big enough to hold one page. If while inserting cells into the parent
  66269. ** page (pParent) the parent page becomes overfull, this buffer is
  66270. ** used to store the parent's overflow cells. Because this function inserts
  66271. ** a maximum of four divider cells into the parent page, and the maximum
  66272. ** size of a cell stored within an internal node is always less than 1/4
  66273. ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
  66274. ** enough for all overflow cells.
  66275. **
  66276. ** If aOvflSpace is set to a null pointer, this function returns
  66277. ** SQLITE_NOMEM.
  66278. */
  66279. static int balance_nonroot(
  66280. MemPage *pParent, /* Parent page of siblings being balanced */
  66281. int iParentIdx, /* Index of "the page" in pParent */
  66282. u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */
  66283. int isRoot, /* True if pParent is a root-page */
  66284. int bBulk /* True if this call is part of a bulk load */
  66285. ){
  66286. BtShared *pBt; /* The whole database */
  66287. int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
  66288. int nNew = 0; /* Number of pages in apNew[] */
  66289. int nOld; /* Number of pages in apOld[] */
  66290. int i, j, k; /* Loop counters */
  66291. int nxDiv; /* Next divider slot in pParent->aCell[] */
  66292. int rc = SQLITE_OK; /* The return code */
  66293. u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */
  66294. int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
  66295. int usableSpace; /* Bytes in pPage beyond the header */
  66296. int pageFlags; /* Value of pPage->aData[0] */
  66297. int iSpace1 = 0; /* First unused byte of aSpace1[] */
  66298. int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */
  66299. int szScratch; /* Size of scratch memory requested */
  66300. MemPage *apOld[NB]; /* pPage and up to two siblings */
  66301. MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
  66302. u8 *pRight; /* Location in parent of right-sibling pointer */
  66303. u8 *apDiv[NB-1]; /* Divider cells in pParent */
  66304. int cntNew[NB+2]; /* Index in b.paCell[] of cell after i-th page */
  66305. int cntOld[NB+2]; /* Old index in b.apCell[] */
  66306. int szNew[NB+2]; /* Combined size of cells placed on i-th page */
  66307. u8 *aSpace1; /* Space for copies of dividers cells */
  66308. Pgno pgno; /* Temp var to store a page number in */
  66309. u8 abDone[NB+2]; /* True after i'th new page is populated */
  66310. Pgno aPgno[NB+2]; /* Page numbers of new pages before shuffling */
  66311. Pgno aPgOrder[NB+2]; /* Copy of aPgno[] used for sorting pages */
  66312. u16 aPgFlags[NB+2]; /* flags field of new pages before shuffling */
  66313. CellArray b; /* Parsed information on cells being balanced */
  66314. memset(abDone, 0, sizeof(abDone));
  66315. b.nCell = 0;
  66316. b.apCell = 0;
  66317. pBt = pParent->pBt;
  66318. assert( sqlite3_mutex_held(pBt->mutex) );
  66319. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  66320. /* At this point pParent may have at most one overflow cell. And if
  66321. ** this overflow cell is present, it must be the cell with
  66322. ** index iParentIdx. This scenario comes about when this function
  66323. ** is called (indirectly) from sqlite3BtreeDelete().
  66324. */
  66325. assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
  66326. assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
  66327. if( !aOvflSpace ){
  66328. return SQLITE_NOMEM_BKPT;
  66329. }
  66330. assert( pParent->nFree>=0 );
  66331. /* Find the sibling pages to balance. Also locate the cells in pParent
  66332. ** that divide the siblings. An attempt is made to find NN siblings on
  66333. ** either side of pPage. More siblings are taken from one side, however,
  66334. ** if there are fewer than NN siblings on the other side. If pParent
  66335. ** has NB or fewer children then all children of pParent are taken.
  66336. **
  66337. ** This loop also drops the divider cells from the parent page. This
  66338. ** way, the remainder of the function does not have to deal with any
  66339. ** overflow cells in the parent page, since if any existed they will
  66340. ** have already been removed.
  66341. */
  66342. i = pParent->nOverflow + pParent->nCell;
  66343. if( i<2 ){
  66344. nxDiv = 0;
  66345. }else{
  66346. assert( bBulk==0 || bBulk==1 );
  66347. if( iParentIdx==0 ){
  66348. nxDiv = 0;
  66349. }else if( iParentIdx==i ){
  66350. nxDiv = i-2+bBulk;
  66351. }else{
  66352. nxDiv = iParentIdx-1;
  66353. }
  66354. i = 2-bBulk;
  66355. }
  66356. nOld = i+1;
  66357. if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
  66358. pRight = &pParent->aData[pParent->hdrOffset+8];
  66359. }else{
  66360. pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
  66361. }
  66362. pgno = get4byte(pRight);
  66363. while( 1 ){
  66364. rc = getAndInitPage(pBt, pgno, &apOld[i], 0, 0);
  66365. if( rc ){
  66366. memset(apOld, 0, (i+1)*sizeof(MemPage*));
  66367. goto balance_cleanup;
  66368. }
  66369. if( apOld[i]->nFree<0 ){
  66370. rc = btreeComputeFreeSpace(apOld[i]);
  66371. if( rc ){
  66372. memset(apOld, 0, (i)*sizeof(MemPage*));
  66373. goto balance_cleanup;
  66374. }
  66375. }
  66376. if( (i--)==0 ) break;
  66377. if( pParent->nOverflow && i+nxDiv==pParent->aiOvfl[0] ){
  66378. apDiv[i] = pParent->apOvfl[0];
  66379. pgno = get4byte(apDiv[i]);
  66380. szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
  66381. pParent->nOverflow = 0;
  66382. }else{
  66383. apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
  66384. pgno = get4byte(apDiv[i]);
  66385. szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
  66386. /* Drop the cell from the parent page. apDiv[i] still points to
  66387. ** the cell within the parent, even though it has been dropped.
  66388. ** This is safe because dropping a cell only overwrites the first
  66389. ** four bytes of it, and this function does not need the first
  66390. ** four bytes of the divider cell. So the pointer is safe to use
  66391. ** later on.
  66392. **
  66393. ** But not if we are in secure-delete mode. In secure-delete mode,
  66394. ** the dropCell() routine will overwrite the entire cell with zeroes.
  66395. ** In this case, temporarily copy the cell into the aOvflSpace[]
  66396. ** buffer. It will be copied out again as soon as the aSpace[] buffer
  66397. ** is allocated. */
  66398. if( pBt->btsFlags & BTS_FAST_SECURE ){
  66399. int iOff;
  66400. iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
  66401. if( (iOff+szNew[i])>(int)pBt->usableSize ){
  66402. rc = SQLITE_CORRUPT_BKPT;
  66403. memset(apOld, 0, (i+1)*sizeof(MemPage*));
  66404. goto balance_cleanup;
  66405. }else{
  66406. memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
  66407. apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
  66408. }
  66409. }
  66410. dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
  66411. }
  66412. }
  66413. /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
  66414. ** alignment */
  66415. nMaxCells = nOld*(MX_CELL(pBt) + ArraySize(pParent->apOvfl));
  66416. nMaxCells = (nMaxCells + 3)&~3;
  66417. /*
  66418. ** Allocate space for memory structures
  66419. */
  66420. szScratch =
  66421. nMaxCells*sizeof(u8*) /* b.apCell */
  66422. + nMaxCells*sizeof(u16) /* b.szCell */
  66423. + pBt->pageSize; /* aSpace1 */
  66424. assert( szScratch<=7*(int)pBt->pageSize );
  66425. b.apCell = sqlite3StackAllocRaw(0, szScratch );
  66426. if( b.apCell==0 ){
  66427. rc = SQLITE_NOMEM_BKPT;
  66428. goto balance_cleanup;
  66429. }
  66430. b.szCell = (u16*)&b.apCell[nMaxCells];
  66431. aSpace1 = (u8*)&b.szCell[nMaxCells];
  66432. assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
  66433. /*
  66434. ** Load pointers to all cells on sibling pages and the divider cells
  66435. ** into the local b.apCell[] array. Make copies of the divider cells
  66436. ** into space obtained from aSpace1[]. The divider cells have already
  66437. ** been removed from pParent.
  66438. **
  66439. ** If the siblings are on leaf pages, then the child pointers of the
  66440. ** divider cells are stripped from the cells before they are copied
  66441. ** into aSpace1[]. In this way, all cells in b.apCell[] are without
  66442. ** child pointers. If siblings are not leaves, then all cell in
  66443. ** b.apCell[] include child pointers. Either way, all cells in b.apCell[]
  66444. ** are alike.
  66445. **
  66446. ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
  66447. ** leafData: 1 if pPage holds key+data and pParent holds only keys.
  66448. */
  66449. b.pRef = apOld[0];
  66450. leafCorrection = b.pRef->leaf*4;
  66451. leafData = b.pRef->intKeyLeaf;
  66452. for(i=0; i<nOld; i++){
  66453. MemPage *pOld = apOld[i];
  66454. int limit = pOld->nCell;
  66455. u8 *aData = pOld->aData;
  66456. u16 maskPage = pOld->maskPage;
  66457. u8 *piCell = aData + pOld->cellOffset;
  66458. u8 *piEnd;
  66459. VVA_ONLY( int nCellAtStart = b.nCell; )
  66460. /* Verify that all sibling pages are of the same "type" (table-leaf,
  66461. ** table-interior, index-leaf, or index-interior).
  66462. */
  66463. if( pOld->aData[0]!=apOld[0]->aData[0] ){
  66464. rc = SQLITE_CORRUPT_BKPT;
  66465. goto balance_cleanup;
  66466. }
  66467. /* Load b.apCell[] with pointers to all cells in pOld. If pOld
  66468. ** contains overflow cells, include them in the b.apCell[] array
  66469. ** in the correct spot.
  66470. **
  66471. ** Note that when there are multiple overflow cells, it is always the
  66472. ** case that they are sequential and adjacent. This invariant arises
  66473. ** because multiple overflows can only occurs when inserting divider
  66474. ** cells into a parent on a prior balance, and divider cells are always
  66475. ** adjacent and are inserted in order. There is an assert() tagged
  66476. ** with "NOTE 1" in the overflow cell insertion loop to prove this
  66477. ** invariant.
  66478. **
  66479. ** This must be done in advance. Once the balance starts, the cell
  66480. ** offset section of the btree page will be overwritten and we will no
  66481. ** long be able to find the cells if a pointer to each cell is not saved
  66482. ** first.
  66483. */
  66484. memset(&b.szCell[b.nCell], 0, sizeof(b.szCell[0])*(limit+pOld->nOverflow));
  66485. if( pOld->nOverflow>0 ){
  66486. if( limit<pOld->aiOvfl[0] ){
  66487. rc = SQLITE_CORRUPT_BKPT;
  66488. goto balance_cleanup;
  66489. }
  66490. limit = pOld->aiOvfl[0];
  66491. for(j=0; j<limit; j++){
  66492. b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
  66493. piCell += 2;
  66494. b.nCell++;
  66495. }
  66496. for(k=0; k<pOld->nOverflow; k++){
  66497. assert( k==0 || pOld->aiOvfl[k-1]+1==pOld->aiOvfl[k] );/* NOTE 1 */
  66498. b.apCell[b.nCell] = pOld->apOvfl[k];
  66499. b.nCell++;
  66500. }
  66501. }
  66502. piEnd = aData + pOld->cellOffset + 2*pOld->nCell;
  66503. while( piCell<piEnd ){
  66504. assert( b.nCell<nMaxCells );
  66505. b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
  66506. piCell += 2;
  66507. b.nCell++;
  66508. }
  66509. assert( (b.nCell-nCellAtStart)==(pOld->nCell+pOld->nOverflow) );
  66510. cntOld[i] = b.nCell;
  66511. if( i<nOld-1 && !leafData){
  66512. u16 sz = (u16)szNew[i];
  66513. u8 *pTemp;
  66514. assert( b.nCell<nMaxCells );
  66515. b.szCell[b.nCell] = sz;
  66516. pTemp = &aSpace1[iSpace1];
  66517. iSpace1 += sz;
  66518. assert( sz<=pBt->maxLocal+23 );
  66519. assert( iSpace1 <= (int)pBt->pageSize );
  66520. memcpy(pTemp, apDiv[i], sz);
  66521. b.apCell[b.nCell] = pTemp+leafCorrection;
  66522. assert( leafCorrection==0 || leafCorrection==4 );
  66523. b.szCell[b.nCell] = b.szCell[b.nCell] - leafCorrection;
  66524. if( !pOld->leaf ){
  66525. assert( leafCorrection==0 );
  66526. assert( pOld->hdrOffset==0 );
  66527. /* The right pointer of the child page pOld becomes the left
  66528. ** pointer of the divider cell */
  66529. memcpy(b.apCell[b.nCell], &pOld->aData[8], 4);
  66530. }else{
  66531. assert( leafCorrection==4 );
  66532. while( b.szCell[b.nCell]<4 ){
  66533. /* Do not allow any cells smaller than 4 bytes. If a smaller cell
  66534. ** does exist, pad it with 0x00 bytes. */
  66535. assert( b.szCell[b.nCell]==3 || CORRUPT_DB );
  66536. assert( b.apCell[b.nCell]==&aSpace1[iSpace1-3] || CORRUPT_DB );
  66537. aSpace1[iSpace1++] = 0x00;
  66538. b.szCell[b.nCell]++;
  66539. }
  66540. }
  66541. b.nCell++;
  66542. }
  66543. }
  66544. /*
  66545. ** Figure out the number of pages needed to hold all b.nCell cells.
  66546. ** Store this number in "k". Also compute szNew[] which is the total
  66547. ** size of all cells on the i-th page and cntNew[] which is the index
  66548. ** in b.apCell[] of the cell that divides page i from page i+1.
  66549. ** cntNew[k] should equal b.nCell.
  66550. **
  66551. ** Values computed by this block:
  66552. **
  66553. ** k: The total number of sibling pages
  66554. ** szNew[i]: Spaced used on the i-th sibling page.
  66555. ** cntNew[i]: Index in b.apCell[] and b.szCell[] for the first cell to
  66556. ** the right of the i-th sibling page.
  66557. ** usableSpace: Number of bytes of space available on each sibling.
  66558. **
  66559. */
  66560. usableSpace = pBt->usableSize - 12 + leafCorrection;
  66561. for(i=k=0; i<nOld; i++, k++){
  66562. MemPage *p = apOld[i];
  66563. b.apEnd[k] = p->aDataEnd;
  66564. b.ixNx[k] = cntOld[i];
  66565. if( k && b.ixNx[k]==b.ixNx[k-1] ){
  66566. k--; /* Omit b.ixNx[] entry for child pages with no cells */
  66567. }
  66568. if( !leafData ){
  66569. k++;
  66570. b.apEnd[k] = pParent->aDataEnd;
  66571. b.ixNx[k] = cntOld[i]+1;
  66572. }
  66573. assert( p->nFree>=0 );
  66574. szNew[i] = usableSpace - p->nFree;
  66575. for(j=0; j<p->nOverflow; j++){
  66576. szNew[i] += 2 + p->xCellSize(p, p->apOvfl[j]);
  66577. }
  66578. cntNew[i] = cntOld[i];
  66579. }
  66580. k = nOld;
  66581. for(i=0; i<k; i++){
  66582. int sz;
  66583. while( szNew[i]>usableSpace ){
  66584. if( i+1>=k ){
  66585. k = i+2;
  66586. if( k>NB+2 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
  66587. szNew[k-1] = 0;
  66588. cntNew[k-1] = b.nCell;
  66589. }
  66590. sz = 2 + cachedCellSize(&b, cntNew[i]-1);
  66591. szNew[i] -= sz;
  66592. if( !leafData ){
  66593. if( cntNew[i]<b.nCell ){
  66594. sz = 2 + cachedCellSize(&b, cntNew[i]);
  66595. }else{
  66596. sz = 0;
  66597. }
  66598. }
  66599. szNew[i+1] += sz;
  66600. cntNew[i]--;
  66601. }
  66602. while( cntNew[i]<b.nCell ){
  66603. sz = 2 + cachedCellSize(&b, cntNew[i]);
  66604. if( szNew[i]+sz>usableSpace ) break;
  66605. szNew[i] += sz;
  66606. cntNew[i]++;
  66607. if( !leafData ){
  66608. if( cntNew[i]<b.nCell ){
  66609. sz = 2 + cachedCellSize(&b, cntNew[i]);
  66610. }else{
  66611. sz = 0;
  66612. }
  66613. }
  66614. szNew[i+1] -= sz;
  66615. }
  66616. if( cntNew[i]>=b.nCell ){
  66617. k = i+1;
  66618. }else if( cntNew[i] <= (i>0 ? cntNew[i-1] : 0) ){
  66619. rc = SQLITE_CORRUPT_BKPT;
  66620. goto balance_cleanup;
  66621. }
  66622. }
  66623. /*
  66624. ** The packing computed by the previous block is biased toward the siblings
  66625. ** on the left side (siblings with smaller keys). The left siblings are
  66626. ** always nearly full, while the right-most sibling might be nearly empty.
  66627. ** The next block of code attempts to adjust the packing of siblings to
  66628. ** get a better balance.
  66629. **
  66630. ** This adjustment is more than an optimization. The packing above might
  66631. ** be so out of balance as to be illegal. For example, the right-most
  66632. ** sibling might be completely empty. This adjustment is not optional.
  66633. */
  66634. for(i=k-1; i>0; i--){
  66635. int szRight = szNew[i]; /* Size of sibling on the right */
  66636. int szLeft = szNew[i-1]; /* Size of sibling on the left */
  66637. int r; /* Index of right-most cell in left sibling */
  66638. int d; /* Index of first cell to the left of right sibling */
  66639. r = cntNew[i-1] - 1;
  66640. d = r + 1 - leafData;
  66641. (void)cachedCellSize(&b, d);
  66642. do{
  66643. assert( d<nMaxCells );
  66644. assert( r<nMaxCells );
  66645. (void)cachedCellSize(&b, r);
  66646. if( szRight!=0
  66647. && (bBulk || szRight+b.szCell[d]+2 > szLeft-(b.szCell[r]+(i==k-1?0:2)))){
  66648. break;
  66649. }
  66650. szRight += b.szCell[d] + 2;
  66651. szLeft -= b.szCell[r] + 2;
  66652. cntNew[i-1] = r;
  66653. r--;
  66654. d--;
  66655. }while( r>=0 );
  66656. szNew[i] = szRight;
  66657. szNew[i-1] = szLeft;
  66658. if( cntNew[i-1] <= (i>1 ? cntNew[i-2] : 0) ){
  66659. rc = SQLITE_CORRUPT_BKPT;
  66660. goto balance_cleanup;
  66661. }
  66662. }
  66663. /* Sanity check: For a non-corrupt database file one of the follwing
  66664. ** must be true:
  66665. ** (1) We found one or more cells (cntNew[0])>0), or
  66666. ** (2) pPage is a virtual root page. A virtual root page is when
  66667. ** the real root page is page 1 and we are the only child of
  66668. ** that page.
  66669. */
  66670. assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB);
  66671. TRACE(("BALANCE: old: %d(nc=%d) %d(nc=%d) %d(nc=%d)\n",
  66672. apOld[0]->pgno, apOld[0]->nCell,
  66673. nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0,
  66674. nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0
  66675. ));
  66676. /*
  66677. ** Allocate k new pages. Reuse old pages where possible.
  66678. */
  66679. pageFlags = apOld[0]->aData[0];
  66680. for(i=0; i<k; i++){
  66681. MemPage *pNew;
  66682. if( i<nOld ){
  66683. pNew = apNew[i] = apOld[i];
  66684. apOld[i] = 0;
  66685. rc = sqlite3PagerWrite(pNew->pDbPage);
  66686. nNew++;
  66687. if( rc ) goto balance_cleanup;
  66688. }else{
  66689. assert( i>0 );
  66690. rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
  66691. if( rc ) goto balance_cleanup;
  66692. zeroPage(pNew, pageFlags);
  66693. apNew[i] = pNew;
  66694. nNew++;
  66695. cntOld[i] = b.nCell;
  66696. /* Set the pointer-map entry for the new sibling page. */
  66697. if( ISAUTOVACUUM ){
  66698. ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
  66699. if( rc!=SQLITE_OK ){
  66700. goto balance_cleanup;
  66701. }
  66702. }
  66703. }
  66704. }
  66705. /*
  66706. ** Reassign page numbers so that the new pages are in ascending order.
  66707. ** This helps to keep entries in the disk file in order so that a scan
  66708. ** of the table is closer to a linear scan through the file. That in turn
  66709. ** helps the operating system to deliver pages from the disk more rapidly.
  66710. **
  66711. ** An O(n^2) insertion sort algorithm is used, but since n is never more
  66712. ** than (NB+2) (a small constant), that should not be a problem.
  66713. **
  66714. ** When NB==3, this one optimization makes the database about 25% faster
  66715. ** for large insertions and deletions.
  66716. */
  66717. for(i=0; i<nNew; i++){
  66718. aPgOrder[i] = aPgno[i] = apNew[i]->pgno;
  66719. aPgFlags[i] = apNew[i]->pDbPage->flags;
  66720. for(j=0; j<i; j++){
  66721. if( aPgno[j]==aPgno[i] ){
  66722. /* This branch is taken if the set of sibling pages somehow contains
  66723. ** duplicate entries. This can happen if the database is corrupt.
  66724. ** It would be simpler to detect this as part of the loop below, but
  66725. ** we do the detection here in order to avoid populating the pager
  66726. ** cache with two separate objects associated with the same
  66727. ** page number. */
  66728. assert( CORRUPT_DB );
  66729. rc = SQLITE_CORRUPT_BKPT;
  66730. goto balance_cleanup;
  66731. }
  66732. }
  66733. }
  66734. for(i=0; i<nNew; i++){
  66735. int iBest = 0; /* aPgno[] index of page number to use */
  66736. for(j=1; j<nNew; j++){
  66737. if( aPgOrder[j]<aPgOrder[iBest] ) iBest = j;
  66738. }
  66739. pgno = aPgOrder[iBest];
  66740. aPgOrder[iBest] = 0xffffffff;
  66741. if( iBest!=i ){
  66742. if( iBest>i ){
  66743. sqlite3PagerRekey(apNew[iBest]->pDbPage, pBt->nPage+iBest+1, 0);
  66744. }
  66745. sqlite3PagerRekey(apNew[i]->pDbPage, pgno, aPgFlags[iBest]);
  66746. apNew[i]->pgno = pgno;
  66747. }
  66748. }
  66749. TRACE(("BALANCE: new: %d(%d nc=%d) %d(%d nc=%d) %d(%d nc=%d) "
  66750. "%d(%d nc=%d) %d(%d nc=%d)\n",
  66751. apNew[0]->pgno, szNew[0], cntNew[0],
  66752. nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
  66753. nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0,
  66754. nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
  66755. nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0,
  66756. nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
  66757. nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0,
  66758. nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0,
  66759. nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0
  66760. ));
  66761. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  66762. put4byte(pRight, apNew[nNew-1]->pgno);
  66763. /* If the sibling pages are not leaves, ensure that the right-child pointer
  66764. ** of the right-most new sibling page is set to the value that was
  66765. ** originally in the same field of the right-most old sibling page. */
  66766. if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){
  66767. MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1];
  66768. memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4);
  66769. }
  66770. /* Make any required updates to pointer map entries associated with
  66771. ** cells stored on sibling pages following the balance operation. Pointer
  66772. ** map entries associated with divider cells are set by the insertCell()
  66773. ** routine. The associated pointer map entries are:
  66774. **
  66775. ** a) if the cell contains a reference to an overflow chain, the
  66776. ** entry associated with the first page in the overflow chain, and
  66777. **
  66778. ** b) if the sibling pages are not leaves, the child page associated
  66779. ** with the cell.
  66780. **
  66781. ** If the sibling pages are not leaves, then the pointer map entry
  66782. ** associated with the right-child of each sibling may also need to be
  66783. ** updated. This happens below, after the sibling pages have been
  66784. ** populated, not here.
  66785. */
  66786. if( ISAUTOVACUUM ){
  66787. MemPage *pOld;
  66788. MemPage *pNew = pOld = apNew[0];
  66789. int cntOldNext = pNew->nCell + pNew->nOverflow;
  66790. int iNew = 0;
  66791. int iOld = 0;
  66792. for(i=0; i<b.nCell; i++){
  66793. u8 *pCell = b.apCell[i];
  66794. while( i==cntOldNext ){
  66795. iOld++;
  66796. assert( iOld<nNew || iOld<nOld );
  66797. assert( iOld>=0 && iOld<NB );
  66798. pOld = iOld<nNew ? apNew[iOld] : apOld[iOld];
  66799. cntOldNext += pOld->nCell + pOld->nOverflow + !leafData;
  66800. }
  66801. if( i==cntNew[iNew] ){
  66802. pNew = apNew[++iNew];
  66803. if( !leafData ) continue;
  66804. }
  66805. /* Cell pCell is destined for new sibling page pNew. Originally, it
  66806. ** was either part of sibling page iOld (possibly an overflow cell),
  66807. ** or else the divider cell to the left of sibling page iOld. So,
  66808. ** if sibling page iOld had the same page number as pNew, and if
  66809. ** pCell really was a part of sibling page iOld (not a divider or
  66810. ** overflow cell), we can skip updating the pointer map entries. */
  66811. if( iOld>=nNew
  66812. || pNew->pgno!=aPgno[iOld]
  66813. || !SQLITE_WITHIN(pCell,pOld->aData,pOld->aDataEnd)
  66814. ){
  66815. if( !leafCorrection ){
  66816. ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc);
  66817. }
  66818. if( cachedCellSize(&b,i)>pNew->minLocal ){
  66819. ptrmapPutOvflPtr(pNew, pOld, pCell, &rc);
  66820. }
  66821. if( rc ) goto balance_cleanup;
  66822. }
  66823. }
  66824. }
  66825. /* Insert new divider cells into pParent. */
  66826. for(i=0; i<nNew-1; i++){
  66827. u8 *pCell;
  66828. u8 *pTemp;
  66829. int sz;
  66830. MemPage *pNew = apNew[i];
  66831. j = cntNew[i];
  66832. assert( j<nMaxCells );
  66833. assert( b.apCell[j]!=0 );
  66834. pCell = b.apCell[j];
  66835. sz = b.szCell[j] + leafCorrection;
  66836. pTemp = &aOvflSpace[iOvflSpace];
  66837. if( !pNew->leaf ){
  66838. memcpy(&pNew->aData[8], pCell, 4);
  66839. }else if( leafData ){
  66840. /* If the tree is a leaf-data tree, and the siblings are leaves,
  66841. ** then there is no divider cell in b.apCell[]. Instead, the divider
  66842. ** cell consists of the integer key for the right-most cell of
  66843. ** the sibling-page assembled above only.
  66844. */
  66845. CellInfo info;
  66846. j--;
  66847. pNew->xParseCell(pNew, b.apCell[j], &info);
  66848. pCell = pTemp;
  66849. sz = 4 + putVarint(&pCell[4], info.nKey);
  66850. pTemp = 0;
  66851. }else{
  66852. pCell -= 4;
  66853. /* Obscure case for non-leaf-data trees: If the cell at pCell was
  66854. ** previously stored on a leaf node, and its reported size was 4
  66855. ** bytes, then it may actually be smaller than this
  66856. ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
  66857. ** any cell). But it is important to pass the correct size to
  66858. ** insertCell(), so reparse the cell now.
  66859. **
  66860. ** This can only happen for b-trees used to evaluate "IN (SELECT ...)"
  66861. ** and WITHOUT ROWID tables with exactly one column which is the
  66862. ** primary key.
  66863. */
  66864. if( b.szCell[j]==4 ){
  66865. assert(leafCorrection==4);
  66866. sz = pParent->xCellSize(pParent, pCell);
  66867. }
  66868. }
  66869. iOvflSpace += sz;
  66870. assert( sz<=pBt->maxLocal+23 );
  66871. assert( iOvflSpace <= (int)pBt->pageSize );
  66872. insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno, &rc);
  66873. if( rc!=SQLITE_OK ) goto balance_cleanup;
  66874. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  66875. }
  66876. /* Now update the actual sibling pages. The order in which they are updated
  66877. ** is important, as this code needs to avoid disrupting any page from which
  66878. ** cells may still to be read. In practice, this means:
  66879. **
  66880. ** (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1])
  66881. ** then it is not safe to update page apNew[iPg] until after
  66882. ** the left-hand sibling apNew[iPg-1] has been updated.
  66883. **
  66884. ** (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1])
  66885. ** then it is not safe to update page apNew[iPg] until after
  66886. ** the right-hand sibling apNew[iPg+1] has been updated.
  66887. **
  66888. ** If neither of the above apply, the page is safe to update.
  66889. **
  66890. ** The iPg value in the following loop starts at nNew-1 goes down
  66891. ** to 0, then back up to nNew-1 again, thus making two passes over
  66892. ** the pages. On the initial downward pass, only condition (1) above
  66893. ** needs to be tested because (2) will always be true from the previous
  66894. ** step. On the upward pass, both conditions are always true, so the
  66895. ** upwards pass simply processes pages that were missed on the downward
  66896. ** pass.
  66897. */
  66898. for(i=1-nNew; i<nNew; i++){
  66899. int iPg = i<0 ? -i : i;
  66900. assert( iPg>=0 && iPg<nNew );
  66901. if( abDone[iPg] ) continue; /* Skip pages already processed */
  66902. if( i>=0 /* On the upwards pass, or... */
  66903. || cntOld[iPg-1]>=cntNew[iPg-1] /* Condition (1) is true */
  66904. ){
  66905. int iNew;
  66906. int iOld;
  66907. int nNewCell;
  66908. /* Verify condition (1): If cells are moving left, update iPg
  66909. ** only after iPg-1 has already been updated. */
  66910. assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] );
  66911. /* Verify condition (2): If cells are moving right, update iPg
  66912. ** only after iPg+1 has already been updated. */
  66913. assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] );
  66914. if( iPg==0 ){
  66915. iNew = iOld = 0;
  66916. nNewCell = cntNew[0];
  66917. }else{
  66918. iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : b.nCell;
  66919. iNew = cntNew[iPg-1] + !leafData;
  66920. nNewCell = cntNew[iPg] - iNew;
  66921. }
  66922. rc = editPage(apNew[iPg], iOld, iNew, nNewCell, &b);
  66923. if( rc ) goto balance_cleanup;
  66924. abDone[iPg]++;
  66925. apNew[iPg]->nFree = usableSpace-szNew[iPg];
  66926. assert( apNew[iPg]->nOverflow==0 );
  66927. assert( apNew[iPg]->nCell==nNewCell );
  66928. }
  66929. }
  66930. /* All pages have been processed exactly once */
  66931. assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 );
  66932. assert( nOld>0 );
  66933. assert( nNew>0 );
  66934. if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
  66935. /* The root page of the b-tree now contains no cells. The only sibling
  66936. ** page is the right-child of the parent. Copy the contents of the
  66937. ** child page into the parent, decreasing the overall height of the
  66938. ** b-tree structure by one. This is described as the "balance-shallower"
  66939. ** sub-algorithm in some documentation.
  66940. **
  66941. ** If this is an auto-vacuum database, the call to copyNodeContent()
  66942. ** sets all pointer-map entries corresponding to database image pages
  66943. ** for which the pointer is stored within the content being copied.
  66944. **
  66945. ** It is critical that the child page be defragmented before being
  66946. ** copied into the parent, because if the parent is page 1 then it will
  66947. ** by smaller than the child due to the database header, and so all the
  66948. ** free space needs to be up front.
  66949. */
  66950. assert( nNew==1 || CORRUPT_DB );
  66951. rc = defragmentPage(apNew[0], -1);
  66952. testcase( rc!=SQLITE_OK );
  66953. assert( apNew[0]->nFree ==
  66954. (get2byteNotZero(&apNew[0]->aData[5]) - apNew[0]->cellOffset
  66955. - apNew[0]->nCell*2)
  66956. || rc!=SQLITE_OK
  66957. );
  66958. copyNodeContent(apNew[0], pParent, &rc);
  66959. freePage(apNew[0], &rc);
  66960. }else if( ISAUTOVACUUM && !leafCorrection ){
  66961. /* Fix the pointer map entries associated with the right-child of each
  66962. ** sibling page. All other pointer map entries have already been taken
  66963. ** care of. */
  66964. for(i=0; i<nNew; i++){
  66965. u32 key = get4byte(&apNew[i]->aData[8]);
  66966. ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
  66967. }
  66968. }
  66969. assert( pParent->isInit );
  66970. TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
  66971. nOld, nNew, b.nCell));
  66972. /* Free any old pages that were not reused as new pages.
  66973. */
  66974. for(i=nNew; i<nOld; i++){
  66975. freePage(apOld[i], &rc);
  66976. }
  66977. #if 0
  66978. if( ISAUTOVACUUM && rc==SQLITE_OK && apNew[0]->isInit ){
  66979. /* The ptrmapCheckPages() contains assert() statements that verify that
  66980. ** all pointer map pages are set correctly. This is helpful while
  66981. ** debugging. This is usually disabled because a corrupt database may
  66982. ** cause an assert() statement to fail. */
  66983. ptrmapCheckPages(apNew, nNew);
  66984. ptrmapCheckPages(&pParent, 1);
  66985. }
  66986. #endif
  66987. /*
  66988. ** Cleanup before returning.
  66989. */
  66990. balance_cleanup:
  66991. sqlite3StackFree(0, b.apCell);
  66992. for(i=0; i<nOld; i++){
  66993. releasePage(apOld[i]);
  66994. }
  66995. for(i=0; i<nNew; i++){
  66996. releasePage(apNew[i]);
  66997. }
  66998. return rc;
  66999. }
  67000. /*
  67001. ** This function is called when the root page of a b-tree structure is
  67002. ** overfull (has one or more overflow pages).
  67003. **
  67004. ** A new child page is allocated and the contents of the current root
  67005. ** page, including overflow cells, are copied into the child. The root
  67006. ** page is then overwritten to make it an empty page with the right-child
  67007. ** pointer pointing to the new page.
  67008. **
  67009. ** Before returning, all pointer-map entries corresponding to pages
  67010. ** that the new child-page now contains pointers to are updated. The
  67011. ** entry corresponding to the new right-child pointer of the root
  67012. ** page is also updated.
  67013. **
  67014. ** If successful, *ppChild is set to contain a reference to the child
  67015. ** page and SQLITE_OK is returned. In this case the caller is required
  67016. ** to call releasePage() on *ppChild exactly once. If an error occurs,
  67017. ** an error code is returned and *ppChild is set to 0.
  67018. */
  67019. static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
  67020. int rc; /* Return value from subprocedures */
  67021. MemPage *pChild = 0; /* Pointer to a new child page */
  67022. Pgno pgnoChild = 0; /* Page number of the new child page */
  67023. BtShared *pBt = pRoot->pBt; /* The BTree */
  67024. assert( pRoot->nOverflow>0 );
  67025. assert( sqlite3_mutex_held(pBt->mutex) );
  67026. /* Make pRoot, the root page of the b-tree, writable. Allocate a new
  67027. ** page that will become the new right-child of pPage. Copy the contents
  67028. ** of the node stored on pRoot into the new child page.
  67029. */
  67030. rc = sqlite3PagerWrite(pRoot->pDbPage);
  67031. if( rc==SQLITE_OK ){
  67032. rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
  67033. copyNodeContent(pRoot, pChild, &rc);
  67034. if( ISAUTOVACUUM ){
  67035. ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
  67036. }
  67037. }
  67038. if( rc ){
  67039. *ppChild = 0;
  67040. releasePage(pChild);
  67041. return rc;
  67042. }
  67043. assert( sqlite3PagerIswriteable(pChild->pDbPage) );
  67044. assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
  67045. assert( pChild->nCell==pRoot->nCell || CORRUPT_DB );
  67046. TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
  67047. /* Copy the overflow cells from pRoot to pChild */
  67048. memcpy(pChild->aiOvfl, pRoot->aiOvfl,
  67049. pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
  67050. memcpy(pChild->apOvfl, pRoot->apOvfl,
  67051. pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
  67052. pChild->nOverflow = pRoot->nOverflow;
  67053. /* Zero the contents of pRoot. Then install pChild as the right-child. */
  67054. zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
  67055. put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
  67056. *ppChild = pChild;
  67057. return SQLITE_OK;
  67058. }
  67059. /*
  67060. ** The page that pCur currently points to has just been modified in
  67061. ** some way. This function figures out if this modification means the
  67062. ** tree needs to be balanced, and if so calls the appropriate balancing
  67063. ** routine. Balancing routines are:
  67064. **
  67065. ** balance_quick()
  67066. ** balance_deeper()
  67067. ** balance_nonroot()
  67068. */
  67069. static int balance(BtCursor *pCur){
  67070. int rc = SQLITE_OK;
  67071. const int nMin = pCur->pBt->usableSize * 2 / 3;
  67072. u8 aBalanceQuickSpace[13];
  67073. u8 *pFree = 0;
  67074. VVA_ONLY( int balance_quick_called = 0 );
  67075. VVA_ONLY( int balance_deeper_called = 0 );
  67076. do {
  67077. int iPage = pCur->iPage;
  67078. MemPage *pPage = pCur->pPage;
  67079. if( NEVER(pPage->nFree<0) && btreeComputeFreeSpace(pPage) ) break;
  67080. if( iPage==0 ){
  67081. if( pPage->nOverflow ){
  67082. /* The root page of the b-tree is overfull. In this case call the
  67083. ** balance_deeper() function to create a new child for the root-page
  67084. ** and copy the current contents of the root-page to it. The
  67085. ** next iteration of the do-loop will balance the child page.
  67086. */
  67087. assert( balance_deeper_called==0 );
  67088. VVA_ONLY( balance_deeper_called++ );
  67089. rc = balance_deeper(pPage, &pCur->apPage[1]);
  67090. if( rc==SQLITE_OK ){
  67091. pCur->iPage = 1;
  67092. pCur->ix = 0;
  67093. pCur->aiIdx[0] = 0;
  67094. pCur->apPage[0] = pPage;
  67095. pCur->pPage = pCur->apPage[1];
  67096. assert( pCur->pPage->nOverflow );
  67097. }
  67098. }else{
  67099. break;
  67100. }
  67101. }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
  67102. break;
  67103. }else{
  67104. MemPage * const pParent = pCur->apPage[iPage-1];
  67105. int const iIdx = pCur->aiIdx[iPage-1];
  67106. rc = sqlite3PagerWrite(pParent->pDbPage);
  67107. if( rc==SQLITE_OK && pParent->nFree<0 ){
  67108. rc = btreeComputeFreeSpace(pParent);
  67109. }
  67110. if( rc==SQLITE_OK ){
  67111. #ifndef SQLITE_OMIT_QUICKBALANCE
  67112. if( pPage->intKeyLeaf
  67113. && pPage->nOverflow==1
  67114. && pPage->aiOvfl[0]==pPage->nCell
  67115. && pParent->pgno!=1
  67116. && pParent->nCell==iIdx
  67117. ){
  67118. /* Call balance_quick() to create a new sibling of pPage on which
  67119. ** to store the overflow cell. balance_quick() inserts a new cell
  67120. ** into pParent, which may cause pParent overflow. If this
  67121. ** happens, the next iteration of the do-loop will balance pParent
  67122. ** use either balance_nonroot() or balance_deeper(). Until this
  67123. ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
  67124. ** buffer.
  67125. **
  67126. ** The purpose of the following assert() is to check that only a
  67127. ** single call to balance_quick() is made for each call to this
  67128. ** function. If this were not verified, a subtle bug involving reuse
  67129. ** of the aBalanceQuickSpace[] might sneak in.
  67130. */
  67131. assert( balance_quick_called==0 );
  67132. VVA_ONLY( balance_quick_called++ );
  67133. rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
  67134. }else
  67135. #endif
  67136. {
  67137. /* In this case, call balance_nonroot() to redistribute cells
  67138. ** between pPage and up to 2 of its sibling pages. This involves
  67139. ** modifying the contents of pParent, which may cause pParent to
  67140. ** become overfull or underfull. The next iteration of the do-loop
  67141. ** will balance the parent page to correct this.
  67142. **
  67143. ** If the parent page becomes overfull, the overflow cell or cells
  67144. ** are stored in the pSpace buffer allocated immediately below.
  67145. ** A subsequent iteration of the do-loop will deal with this by
  67146. ** calling balance_nonroot() (balance_deeper() may be called first,
  67147. ** but it doesn't deal with overflow cells - just moves them to a
  67148. ** different page). Once this subsequent call to balance_nonroot()
  67149. ** has completed, it is safe to release the pSpace buffer used by
  67150. ** the previous call, as the overflow cell data will have been
  67151. ** copied either into the body of a database page or into the new
  67152. ** pSpace buffer passed to the latter call to balance_nonroot().
  67153. */
  67154. u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
  67155. rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1,
  67156. pCur->hints&BTREE_BULKLOAD);
  67157. if( pFree ){
  67158. /* If pFree is not NULL, it points to the pSpace buffer used
  67159. ** by a previous call to balance_nonroot(). Its contents are
  67160. ** now stored either on real database pages or within the
  67161. ** new pSpace buffer, so it may be safely freed here. */
  67162. sqlite3PageFree(pFree);
  67163. }
  67164. /* The pSpace buffer will be freed after the next call to
  67165. ** balance_nonroot(), or just before this function returns, whichever
  67166. ** comes first. */
  67167. pFree = pSpace;
  67168. }
  67169. }
  67170. pPage->nOverflow = 0;
  67171. /* The next iteration of the do-loop balances the parent page. */
  67172. releasePage(pPage);
  67173. pCur->iPage--;
  67174. assert( pCur->iPage>=0 );
  67175. pCur->pPage = pCur->apPage[pCur->iPage];
  67176. }
  67177. }while( rc==SQLITE_OK );
  67178. if( pFree ){
  67179. sqlite3PageFree(pFree);
  67180. }
  67181. return rc;
  67182. }
  67183. /* Overwrite content from pX into pDest. Only do the write if the
  67184. ** content is different from what is already there.
  67185. */
  67186. static int btreeOverwriteContent(
  67187. MemPage *pPage, /* MemPage on which writing will occur */
  67188. u8 *pDest, /* Pointer to the place to start writing */
  67189. const BtreePayload *pX, /* Source of data to write */
  67190. int iOffset, /* Offset of first byte to write */
  67191. int iAmt /* Number of bytes to be written */
  67192. ){
  67193. int nData = pX->nData - iOffset;
  67194. if( nData<=0 ){
  67195. /* Overwritting with zeros */
  67196. int i;
  67197. for(i=0; i<iAmt && pDest[i]==0; i++){}
  67198. if( i<iAmt ){
  67199. int rc = sqlite3PagerWrite(pPage->pDbPage);
  67200. if( rc ) return rc;
  67201. memset(pDest + i, 0, iAmt - i);
  67202. }
  67203. }else{
  67204. if( nData<iAmt ){
  67205. /* Mixed read data and zeros at the end. Make a recursive call
  67206. ** to write the zeros then fall through to write the real data */
  67207. int rc = btreeOverwriteContent(pPage, pDest+nData, pX, iOffset+nData,
  67208. iAmt-nData);
  67209. if( rc ) return rc;
  67210. iAmt = nData;
  67211. }
  67212. if( memcmp(pDest, ((u8*)pX->pData) + iOffset, iAmt)!=0 ){
  67213. int rc = sqlite3PagerWrite(pPage->pDbPage);
  67214. if( rc ) return rc;
  67215. /* In a corrupt database, it is possible for the source and destination
  67216. ** buffers to overlap. This is harmless since the database is already
  67217. ** corrupt but it does cause valgrind and ASAN warnings. So use
  67218. ** memmove(). */
  67219. memmove(pDest, ((u8*)pX->pData) + iOffset, iAmt);
  67220. }
  67221. }
  67222. return SQLITE_OK;
  67223. }
  67224. /*
  67225. ** Overwrite the cell that cursor pCur is pointing to with fresh content
  67226. ** contained in pX.
  67227. */
  67228. static int btreeOverwriteCell(BtCursor *pCur, const BtreePayload *pX){
  67229. int iOffset; /* Next byte of pX->pData to write */
  67230. int nTotal = pX->nData + pX->nZero; /* Total bytes of to write */
  67231. int rc; /* Return code */
  67232. MemPage *pPage = pCur->pPage; /* Page being written */
  67233. BtShared *pBt; /* Btree */
  67234. Pgno ovflPgno; /* Next overflow page to write */
  67235. u32 ovflPageSize; /* Size to write on overflow page */
  67236. if( pCur->info.pPayload + pCur->info.nLocal > pPage->aDataEnd ){
  67237. return SQLITE_CORRUPT_BKPT;
  67238. }
  67239. /* Overwrite the local portion first */
  67240. rc = btreeOverwriteContent(pPage, pCur->info.pPayload, pX,
  67241. 0, pCur->info.nLocal);
  67242. if( rc ) return rc;
  67243. if( pCur->info.nLocal==nTotal ) return SQLITE_OK;
  67244. /* Now overwrite the overflow pages */
  67245. iOffset = pCur->info.nLocal;
  67246. assert( nTotal>=0 );
  67247. assert( iOffset>=0 );
  67248. ovflPgno = get4byte(pCur->info.pPayload + iOffset);
  67249. pBt = pPage->pBt;
  67250. ovflPageSize = pBt->usableSize - 4;
  67251. do{
  67252. rc = btreeGetPage(pBt, ovflPgno, &pPage, 0);
  67253. if( rc ) return rc;
  67254. if( sqlite3PagerPageRefcount(pPage->pDbPage)!=1 ){
  67255. rc = SQLITE_CORRUPT_BKPT;
  67256. }else{
  67257. if( iOffset+ovflPageSize<(u32)nTotal ){
  67258. ovflPgno = get4byte(pPage->aData);
  67259. }else{
  67260. ovflPageSize = nTotal - iOffset;
  67261. }
  67262. rc = btreeOverwriteContent(pPage, pPage->aData+4, pX,
  67263. iOffset, ovflPageSize);
  67264. }
  67265. sqlite3PagerUnref(pPage->pDbPage);
  67266. if( rc ) return rc;
  67267. iOffset += ovflPageSize;
  67268. }while( iOffset<nTotal );
  67269. return SQLITE_OK;
  67270. }
  67271. /*
  67272. ** Insert a new record into the BTree. The content of the new record
  67273. ** is described by the pX object. The pCur cursor is used only to
  67274. ** define what table the record should be inserted into, and is left
  67275. ** pointing at a random location.
  67276. **
  67277. ** For a table btree (used for rowid tables), only the pX.nKey value of
  67278. ** the key is used. The pX.pKey value must be NULL. The pX.nKey is the
  67279. ** rowid or INTEGER PRIMARY KEY of the row. The pX.nData,pData,nZero fields
  67280. ** hold the content of the row.
  67281. **
  67282. ** For an index btree (used for indexes and WITHOUT ROWID tables), the
  67283. ** key is an arbitrary byte sequence stored in pX.pKey,nKey. The
  67284. ** pX.pData,nData,nZero fields must be zero.
  67285. **
  67286. ** If the seekResult parameter is non-zero, then a successful call to
  67287. ** MovetoUnpacked() to seek cursor pCur to (pKey,nKey) has already
  67288. ** been performed. In other words, if seekResult!=0 then the cursor
  67289. ** is currently pointing to a cell that will be adjacent to the cell
  67290. ** to be inserted. If seekResult<0 then pCur points to a cell that is
  67291. ** smaller then (pKey,nKey). If seekResult>0 then pCur points to a cell
  67292. ** that is larger than (pKey,nKey).
  67293. **
  67294. ** If seekResult==0, that means pCur is pointing at some unknown location.
  67295. ** In that case, this routine must seek the cursor to the correct insertion
  67296. ** point for (pKey,nKey) before doing the insertion. For index btrees,
  67297. ** if pX->nMem is non-zero, then pX->aMem contains pointers to the unpacked
  67298. ** key values and pX->aMem can be used instead of pX->pKey to avoid having
  67299. ** to decode the key.
  67300. */
  67301. SQLITE_PRIVATE int sqlite3BtreeInsert(
  67302. BtCursor *pCur, /* Insert data into the table of this cursor */
  67303. const BtreePayload *pX, /* Content of the row to be inserted */
  67304. int flags, /* True if this is likely an append */
  67305. int seekResult /* Result of prior MovetoUnpacked() call */
  67306. ){
  67307. int rc;
  67308. int loc = seekResult; /* -1: before desired location +1: after */
  67309. int szNew = 0;
  67310. int idx;
  67311. MemPage *pPage;
  67312. Btree *p = pCur->pBtree;
  67313. BtShared *pBt = p->pBt;
  67314. unsigned char *oldCell;
  67315. unsigned char *newCell = 0;
  67316. assert( (flags & (BTREE_SAVEPOSITION|BTREE_APPEND))==flags );
  67317. if( pCur->eState==CURSOR_FAULT ){
  67318. assert( pCur->skipNext!=SQLITE_OK );
  67319. return pCur->skipNext;
  67320. }
  67321. assert( cursorOwnsBtShared(pCur) );
  67322. assert( (pCur->curFlags & BTCF_WriteFlag)!=0
  67323. && pBt->inTransaction==TRANS_WRITE
  67324. && (pBt->btsFlags & BTS_READ_ONLY)==0 );
  67325. assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
  67326. /* Assert that the caller has been consistent. If this cursor was opened
  67327. ** expecting an index b-tree, then the caller should be inserting blob
  67328. ** keys with no associated data. If the cursor was opened expecting an
  67329. ** intkey table, the caller should be inserting integer keys with a
  67330. ** blob of associated data. */
  67331. assert( (pX->pKey==0)==(pCur->pKeyInfo==0) );
  67332. /* Save the positions of any other cursors open on this table.
  67333. **
  67334. ** In some cases, the call to btreeMoveto() below is a no-op. For
  67335. ** example, when inserting data into a table with auto-generated integer
  67336. ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
  67337. ** integer key to use. It then calls this function to actually insert the
  67338. ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
  67339. ** that the cursor is already where it needs to be and returns without
  67340. ** doing any work. To avoid thwarting these optimizations, it is important
  67341. ** not to clear the cursor here.
  67342. */
  67343. if( pCur->curFlags & BTCF_Multiple ){
  67344. rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
  67345. if( rc ) return rc;
  67346. }
  67347. if( pCur->pKeyInfo==0 ){
  67348. assert( pX->pKey==0 );
  67349. /* If this is an insert into a table b-tree, invalidate any incrblob
  67350. ** cursors open on the row being replaced */
  67351. invalidateIncrblobCursors(p, pCur->pgnoRoot, pX->nKey, 0);
  67352. /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
  67353. ** to a row with the same key as the new entry being inserted.
  67354. */
  67355. #ifdef SQLITE_DEBUG
  67356. if( flags & BTREE_SAVEPOSITION ){
  67357. assert( pCur->curFlags & BTCF_ValidNKey );
  67358. assert( pX->nKey==pCur->info.nKey );
  67359. assert( pCur->info.nSize!=0 );
  67360. assert( loc==0 );
  67361. }
  67362. #endif
  67363. /* On the other hand, BTREE_SAVEPOSITION==0 does not imply
  67364. ** that the cursor is not pointing to a row to be overwritten.
  67365. ** So do a complete check.
  67366. */
  67367. if( (pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey ){
  67368. /* The cursor is pointing to the entry that is to be
  67369. ** overwritten */
  67370. assert( pX->nData>=0 && pX->nZero>=0 );
  67371. if( pCur->info.nSize!=0
  67372. && pCur->info.nPayload==(u32)pX->nData+pX->nZero
  67373. ){
  67374. /* New entry is the same size as the old. Do an overwrite */
  67375. return btreeOverwriteCell(pCur, pX);
  67376. }
  67377. assert( loc==0 );
  67378. }else if( loc==0 ){
  67379. /* The cursor is *not* pointing to the cell to be overwritten, nor
  67380. ** to an adjacent cell. Move the cursor so that it is pointing either
  67381. ** to the cell to be overwritten or an adjacent cell.
  67382. */
  67383. rc = sqlite3BtreeMovetoUnpacked(pCur, 0, pX->nKey, flags!=0, &loc);
  67384. if( rc ) return rc;
  67385. }
  67386. }else{
  67387. /* This is an index or a WITHOUT ROWID table */
  67388. /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
  67389. ** to a row with the same key as the new entry being inserted.
  67390. */
  67391. assert( (flags & BTREE_SAVEPOSITION)==0 || loc==0 );
  67392. /* If the cursor is not already pointing either to the cell to be
  67393. ** overwritten, or if a new cell is being inserted, if the cursor is
  67394. ** not pointing to an immediately adjacent cell, then move the cursor
  67395. ** so that it does.
  67396. */
  67397. if( loc==0 && (flags & BTREE_SAVEPOSITION)==0 ){
  67398. if( pX->nMem ){
  67399. UnpackedRecord r;
  67400. r.pKeyInfo = pCur->pKeyInfo;
  67401. r.aMem = pX->aMem;
  67402. r.nField = pX->nMem;
  67403. r.default_rc = 0;
  67404. r.errCode = 0;
  67405. r.r1 = 0;
  67406. r.r2 = 0;
  67407. r.eqSeen = 0;
  67408. rc = sqlite3BtreeMovetoUnpacked(pCur, &r, 0, flags!=0, &loc);
  67409. }else{
  67410. rc = btreeMoveto(pCur, pX->pKey, pX->nKey, flags!=0, &loc);
  67411. }
  67412. if( rc ) return rc;
  67413. }
  67414. /* If the cursor is currently pointing to an entry to be overwritten
  67415. ** and the new content is the same as as the old, then use the
  67416. ** overwrite optimization.
  67417. */
  67418. if( loc==0 ){
  67419. getCellInfo(pCur);
  67420. if( pCur->info.nKey==pX->nKey ){
  67421. BtreePayload x2;
  67422. x2.pData = pX->pKey;
  67423. x2.nData = pX->nKey;
  67424. x2.nZero = 0;
  67425. return btreeOverwriteCell(pCur, &x2);
  67426. }
  67427. }
  67428. }
  67429. assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
  67430. pPage = pCur->pPage;
  67431. assert( pPage->intKey || pX->nKey>=0 );
  67432. assert( pPage->leaf || !pPage->intKey );
  67433. if( pPage->nFree<0 ){
  67434. rc = btreeComputeFreeSpace(pPage);
  67435. if( rc ) return rc;
  67436. }
  67437. TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
  67438. pCur->pgnoRoot, pX->nKey, pX->nData, pPage->pgno,
  67439. loc==0 ? "overwrite" : "new entry"));
  67440. assert( pPage->isInit );
  67441. newCell = pBt->pTmpSpace;
  67442. assert( newCell!=0 );
  67443. rc = fillInCell(pPage, newCell, pX, &szNew);
  67444. if( rc ) goto end_insert;
  67445. assert( szNew==pPage->xCellSize(pPage, newCell) );
  67446. assert( szNew <= MX_CELL_SIZE(pBt) );
  67447. idx = pCur->ix;
  67448. if( loc==0 ){
  67449. CellInfo info;
  67450. assert( idx<pPage->nCell );
  67451. rc = sqlite3PagerWrite(pPage->pDbPage);
  67452. if( rc ){
  67453. goto end_insert;
  67454. }
  67455. oldCell = findCell(pPage, idx);
  67456. if( !pPage->leaf ){
  67457. memcpy(newCell, oldCell, 4);
  67458. }
  67459. rc = clearCell(pPage, oldCell, &info);
  67460. if( info.nSize==szNew && info.nLocal==info.nPayload
  67461. && (!ISAUTOVACUUM || szNew<pPage->minLocal)
  67462. ){
  67463. /* Overwrite the old cell with the new if they are the same size.
  67464. ** We could also try to do this if the old cell is smaller, then add
  67465. ** the leftover space to the free list. But experiments show that
  67466. ** doing that is no faster then skipping this optimization and just
  67467. ** calling dropCell() and insertCell().
  67468. **
  67469. ** This optimization cannot be used on an autovacuum database if the
  67470. ** new entry uses overflow pages, as the insertCell() call below is
  67471. ** necessary to add the PTRMAP_OVERFLOW1 pointer-map entry. */
  67472. assert( rc==SQLITE_OK ); /* clearCell never fails when nLocal==nPayload */
  67473. if( oldCell+szNew > pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT;
  67474. memcpy(oldCell, newCell, szNew);
  67475. return SQLITE_OK;
  67476. }
  67477. dropCell(pPage, idx, info.nSize, &rc);
  67478. if( rc ) goto end_insert;
  67479. }else if( loc<0 && pPage->nCell>0 ){
  67480. assert( pPage->leaf );
  67481. idx = ++pCur->ix;
  67482. pCur->curFlags &= ~BTCF_ValidNKey;
  67483. }else{
  67484. assert( pPage->leaf );
  67485. }
  67486. insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
  67487. assert( pPage->nOverflow==0 || rc==SQLITE_OK );
  67488. assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
  67489. /* If no error has occurred and pPage has an overflow cell, call balance()
  67490. ** to redistribute the cells within the tree. Since balance() may move
  67491. ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
  67492. ** variables.
  67493. **
  67494. ** Previous versions of SQLite called moveToRoot() to move the cursor
  67495. ** back to the root page as balance() used to invalidate the contents
  67496. ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
  67497. ** set the cursor state to "invalid". This makes common insert operations
  67498. ** slightly faster.
  67499. **
  67500. ** There is a subtle but important optimization here too. When inserting
  67501. ** multiple records into an intkey b-tree using a single cursor (as can
  67502. ** happen while processing an "INSERT INTO ... SELECT" statement), it
  67503. ** is advantageous to leave the cursor pointing to the last entry in
  67504. ** the b-tree if possible. If the cursor is left pointing to the last
  67505. ** entry in the table, and the next row inserted has an integer key
  67506. ** larger than the largest existing key, it is possible to insert the
  67507. ** row without seeking the cursor. This can be a big performance boost.
  67508. */
  67509. pCur->info.nSize = 0;
  67510. if( pPage->nOverflow ){
  67511. assert( rc==SQLITE_OK );
  67512. pCur->curFlags &= ~(BTCF_ValidNKey);
  67513. rc = balance(pCur);
  67514. /* Must make sure nOverflow is reset to zero even if the balance()
  67515. ** fails. Internal data structure corruption will result otherwise.
  67516. ** Also, set the cursor state to invalid. This stops saveCursorPosition()
  67517. ** from trying to save the current position of the cursor. */
  67518. pCur->pPage->nOverflow = 0;
  67519. pCur->eState = CURSOR_INVALID;
  67520. if( (flags & BTREE_SAVEPOSITION) && rc==SQLITE_OK ){
  67521. btreeReleaseAllCursorPages(pCur);
  67522. if( pCur->pKeyInfo ){
  67523. assert( pCur->pKey==0 );
  67524. pCur->pKey = sqlite3Malloc( pX->nKey );
  67525. if( pCur->pKey==0 ){
  67526. rc = SQLITE_NOMEM;
  67527. }else{
  67528. memcpy(pCur->pKey, pX->pKey, pX->nKey);
  67529. }
  67530. }
  67531. pCur->eState = CURSOR_REQUIRESEEK;
  67532. pCur->nKey = pX->nKey;
  67533. }
  67534. }
  67535. assert( pCur->iPage<0 || pCur->pPage->nOverflow==0 );
  67536. end_insert:
  67537. return rc;
  67538. }
  67539. /*
  67540. ** Delete the entry that the cursor is pointing to.
  67541. **
  67542. ** If the BTREE_SAVEPOSITION bit of the flags parameter is zero, then
  67543. ** the cursor is left pointing at an arbitrary location after the delete.
  67544. ** But if that bit is set, then the cursor is left in a state such that
  67545. ** the next call to BtreeNext() or BtreePrev() moves it to the same row
  67546. ** as it would have been on if the call to BtreeDelete() had been omitted.
  67547. **
  67548. ** The BTREE_AUXDELETE bit of flags indicates that is one of several deletes
  67549. ** associated with a single table entry and its indexes. Only one of those
  67550. ** deletes is considered the "primary" delete. The primary delete occurs
  67551. ** on a cursor that is not a BTREE_FORDELETE cursor. All but one delete
  67552. ** operation on non-FORDELETE cursors is tagged with the AUXDELETE flag.
  67553. ** The BTREE_AUXDELETE bit is a hint that is not used by this implementation,
  67554. ** but which might be used by alternative storage engines.
  67555. */
  67556. SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){
  67557. Btree *p = pCur->pBtree;
  67558. BtShared *pBt = p->pBt;
  67559. int rc; /* Return code */
  67560. MemPage *pPage; /* Page to delete cell from */
  67561. unsigned char *pCell; /* Pointer to cell to delete */
  67562. int iCellIdx; /* Index of cell to delete */
  67563. int iCellDepth; /* Depth of node containing pCell */
  67564. CellInfo info; /* Size of the cell being deleted */
  67565. int bSkipnext = 0; /* Leaf cursor in SKIPNEXT state */
  67566. u8 bPreserve = flags & BTREE_SAVEPOSITION; /* Keep cursor valid */
  67567. assert( cursorOwnsBtShared(pCur) );
  67568. assert( pBt->inTransaction==TRANS_WRITE );
  67569. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  67570. assert( pCur->curFlags & BTCF_WriteFlag );
  67571. assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
  67572. assert( !hasReadConflicts(p, pCur->pgnoRoot) );
  67573. assert( (flags & ~(BTREE_SAVEPOSITION | BTREE_AUXDELETE))==0 );
  67574. if( pCur->eState==CURSOR_REQUIRESEEK ){
  67575. rc = btreeRestoreCursorPosition(pCur);
  67576. if( rc ) return rc;
  67577. }
  67578. assert( pCur->eState==CURSOR_VALID );
  67579. iCellDepth = pCur->iPage;
  67580. iCellIdx = pCur->ix;
  67581. pPage = pCur->pPage;
  67582. pCell = findCell(pPage, iCellIdx);
  67583. if( pPage->nFree<0 && btreeComputeFreeSpace(pPage) ) return SQLITE_CORRUPT;
  67584. /* If the bPreserve flag is set to true, then the cursor position must
  67585. ** be preserved following this delete operation. If the current delete
  67586. ** will cause a b-tree rebalance, then this is done by saving the cursor
  67587. ** key and leaving the cursor in CURSOR_REQUIRESEEK state before
  67588. ** returning.
  67589. **
  67590. ** Or, if the current delete will not cause a rebalance, then the cursor
  67591. ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately
  67592. ** before or after the deleted entry. In this case set bSkipnext to true. */
  67593. if( bPreserve ){
  67594. if( !pPage->leaf
  67595. || (pPage->nFree+cellSizePtr(pPage,pCell)+2)>(int)(pBt->usableSize*2/3)
  67596. || pPage->nCell==1 /* See dbfuzz001.test for a test case */
  67597. ){
  67598. /* A b-tree rebalance will be required after deleting this entry.
  67599. ** Save the cursor key. */
  67600. rc = saveCursorKey(pCur);
  67601. if( rc ) return rc;
  67602. }else{
  67603. bSkipnext = 1;
  67604. }
  67605. }
  67606. /* If the page containing the entry to delete is not a leaf page, move
  67607. ** the cursor to the largest entry in the tree that is smaller than
  67608. ** the entry being deleted. This cell will replace the cell being deleted
  67609. ** from the internal node. The 'previous' entry is used for this instead
  67610. ** of the 'next' entry, as the previous entry is always a part of the
  67611. ** sub-tree headed by the child page of the cell being deleted. This makes
  67612. ** balancing the tree following the delete operation easier. */
  67613. if( !pPage->leaf ){
  67614. rc = sqlite3BtreePrevious(pCur, 0);
  67615. assert( rc!=SQLITE_DONE );
  67616. if( rc ) return rc;
  67617. }
  67618. /* Save the positions of any other cursors open on this table before
  67619. ** making any modifications. */
  67620. if( pCur->curFlags & BTCF_Multiple ){
  67621. rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
  67622. if( rc ) return rc;
  67623. }
  67624. /* If this is a delete operation to remove a row from a table b-tree,
  67625. ** invalidate any incrblob cursors open on the row being deleted. */
  67626. if( pCur->pKeyInfo==0 ){
  67627. invalidateIncrblobCursors(p, pCur->pgnoRoot, pCur->info.nKey, 0);
  67628. }
  67629. /* Make the page containing the entry to be deleted writable. Then free any
  67630. ** overflow pages associated with the entry and finally remove the cell
  67631. ** itself from within the page. */
  67632. rc = sqlite3PagerWrite(pPage->pDbPage);
  67633. if( rc ) return rc;
  67634. rc = clearCell(pPage, pCell, &info);
  67635. dropCell(pPage, iCellIdx, info.nSize, &rc);
  67636. if( rc ) return rc;
  67637. /* If the cell deleted was not located on a leaf page, then the cursor
  67638. ** is currently pointing to the largest entry in the sub-tree headed
  67639. ** by the child-page of the cell that was just deleted from an internal
  67640. ** node. The cell from the leaf node needs to be moved to the internal
  67641. ** node to replace the deleted cell. */
  67642. if( !pPage->leaf ){
  67643. MemPage *pLeaf = pCur->pPage;
  67644. int nCell;
  67645. Pgno n;
  67646. unsigned char *pTmp;
  67647. if( pLeaf->nFree<0 ){
  67648. rc = btreeComputeFreeSpace(pLeaf);
  67649. if( rc ) return rc;
  67650. }
  67651. if( iCellDepth<pCur->iPage-1 ){
  67652. n = pCur->apPage[iCellDepth+1]->pgno;
  67653. }else{
  67654. n = pCur->pPage->pgno;
  67655. }
  67656. pCell = findCell(pLeaf, pLeaf->nCell-1);
  67657. if( pCell<&pLeaf->aData[4] ) return SQLITE_CORRUPT_BKPT;
  67658. nCell = pLeaf->xCellSize(pLeaf, pCell);
  67659. assert( MX_CELL_SIZE(pBt) >= nCell );
  67660. pTmp = pBt->pTmpSpace;
  67661. assert( pTmp!=0 );
  67662. rc = sqlite3PagerWrite(pLeaf->pDbPage);
  67663. if( rc==SQLITE_OK ){
  67664. insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
  67665. }
  67666. dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
  67667. if( rc ) return rc;
  67668. }
  67669. /* Balance the tree. If the entry deleted was located on a leaf page,
  67670. ** then the cursor still points to that page. In this case the first
  67671. ** call to balance() repairs the tree, and the if(...) condition is
  67672. ** never true.
  67673. **
  67674. ** Otherwise, if the entry deleted was on an internal node page, then
  67675. ** pCur is pointing to the leaf page from which a cell was removed to
  67676. ** replace the cell deleted from the internal node. This is slightly
  67677. ** tricky as the leaf node may be underfull, and the internal node may
  67678. ** be either under or overfull. In this case run the balancing algorithm
  67679. ** on the leaf node first. If the balance proceeds far enough up the
  67680. ** tree that we can be sure that any problem in the internal node has
  67681. ** been corrected, so be it. Otherwise, after balancing the leaf node,
  67682. ** walk the cursor up the tree to the internal node and balance it as
  67683. ** well. */
  67684. rc = balance(pCur);
  67685. if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
  67686. releasePageNotNull(pCur->pPage);
  67687. pCur->iPage--;
  67688. while( pCur->iPage>iCellDepth ){
  67689. releasePage(pCur->apPage[pCur->iPage--]);
  67690. }
  67691. pCur->pPage = pCur->apPage[pCur->iPage];
  67692. rc = balance(pCur);
  67693. }
  67694. if( rc==SQLITE_OK ){
  67695. if( bSkipnext ){
  67696. assert( bPreserve && (pCur->iPage==iCellDepth || CORRUPT_DB) );
  67697. assert( pPage==pCur->pPage || CORRUPT_DB );
  67698. assert( (pPage->nCell>0 || CORRUPT_DB) && iCellIdx<=pPage->nCell );
  67699. pCur->eState = CURSOR_SKIPNEXT;
  67700. if( iCellIdx>=pPage->nCell ){
  67701. pCur->skipNext = -1;
  67702. pCur->ix = pPage->nCell-1;
  67703. }else{
  67704. pCur->skipNext = 1;
  67705. }
  67706. }else{
  67707. rc = moveToRoot(pCur);
  67708. if( bPreserve ){
  67709. btreeReleaseAllCursorPages(pCur);
  67710. pCur->eState = CURSOR_REQUIRESEEK;
  67711. }
  67712. if( rc==SQLITE_EMPTY ) rc = SQLITE_OK;
  67713. }
  67714. }
  67715. return rc;
  67716. }
  67717. /*
  67718. ** Create a new BTree table. Write into *piTable the page
  67719. ** number for the root page of the new table.
  67720. **
  67721. ** The type of type is determined by the flags parameter. Only the
  67722. ** following values of flags are currently in use. Other values for
  67723. ** flags might not work:
  67724. **
  67725. ** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
  67726. ** BTREE_ZERODATA Used for SQL indices
  67727. */
  67728. static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
  67729. BtShared *pBt = p->pBt;
  67730. MemPage *pRoot;
  67731. Pgno pgnoRoot;
  67732. int rc;
  67733. int ptfFlags; /* Page-type flage for the root page of new table */
  67734. assert( sqlite3BtreeHoldsMutex(p) );
  67735. assert( pBt->inTransaction==TRANS_WRITE );
  67736. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  67737. #ifdef SQLITE_OMIT_AUTOVACUUM
  67738. rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
  67739. if( rc ){
  67740. return rc;
  67741. }
  67742. #else
  67743. if( pBt->autoVacuum ){
  67744. Pgno pgnoMove; /* Move a page here to make room for the root-page */
  67745. MemPage *pPageMove; /* The page to move to. */
  67746. /* Creating a new table may probably require moving an existing database
  67747. ** to make room for the new tables root page. In case this page turns
  67748. ** out to be an overflow page, delete all overflow page-map caches
  67749. ** held by open cursors.
  67750. */
  67751. invalidateAllOverflowCache(pBt);
  67752. /* Read the value of meta[3] from the database to determine where the
  67753. ** root page of the new table should go. meta[3] is the largest root-page
  67754. ** created so far, so the new root-page is (meta[3]+1).
  67755. */
  67756. sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
  67757. pgnoRoot++;
  67758. /* The new root-page may not be allocated on a pointer-map page, or the
  67759. ** PENDING_BYTE page.
  67760. */
  67761. while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
  67762. pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
  67763. pgnoRoot++;
  67764. }
  67765. assert( pgnoRoot>=3 || CORRUPT_DB );
  67766. testcase( pgnoRoot<3 );
  67767. /* Allocate a page. The page that currently resides at pgnoRoot will
  67768. ** be moved to the allocated page (unless the allocated page happens
  67769. ** to reside at pgnoRoot).
  67770. */
  67771. rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
  67772. if( rc!=SQLITE_OK ){
  67773. return rc;
  67774. }
  67775. if( pgnoMove!=pgnoRoot ){
  67776. /* pgnoRoot is the page that will be used for the root-page of
  67777. ** the new table (assuming an error did not occur). But we were
  67778. ** allocated pgnoMove. If required (i.e. if it was not allocated
  67779. ** by extending the file), the current page at position pgnoMove
  67780. ** is already journaled.
  67781. */
  67782. u8 eType = 0;
  67783. Pgno iPtrPage = 0;
  67784. /* Save the positions of any open cursors. This is required in
  67785. ** case they are holding a reference to an xFetch reference
  67786. ** corresponding to page pgnoRoot. */
  67787. rc = saveAllCursors(pBt, 0, 0);
  67788. releasePage(pPageMove);
  67789. if( rc!=SQLITE_OK ){
  67790. return rc;
  67791. }
  67792. /* Move the page currently at pgnoRoot to pgnoMove. */
  67793. rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
  67794. if( rc!=SQLITE_OK ){
  67795. return rc;
  67796. }
  67797. rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
  67798. if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
  67799. rc = SQLITE_CORRUPT_BKPT;
  67800. }
  67801. if( rc!=SQLITE_OK ){
  67802. releasePage(pRoot);
  67803. return rc;
  67804. }
  67805. assert( eType!=PTRMAP_ROOTPAGE );
  67806. assert( eType!=PTRMAP_FREEPAGE );
  67807. rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
  67808. releasePage(pRoot);
  67809. /* Obtain the page at pgnoRoot */
  67810. if( rc!=SQLITE_OK ){
  67811. return rc;
  67812. }
  67813. rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
  67814. if( rc!=SQLITE_OK ){
  67815. return rc;
  67816. }
  67817. rc = sqlite3PagerWrite(pRoot->pDbPage);
  67818. if( rc!=SQLITE_OK ){
  67819. releasePage(pRoot);
  67820. return rc;
  67821. }
  67822. }else{
  67823. pRoot = pPageMove;
  67824. }
  67825. /* Update the pointer-map and meta-data with the new root-page number. */
  67826. ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
  67827. if( rc ){
  67828. releasePage(pRoot);
  67829. return rc;
  67830. }
  67831. /* When the new root page was allocated, page 1 was made writable in
  67832. ** order either to increase the database filesize, or to decrement the
  67833. ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
  67834. */
  67835. assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
  67836. rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
  67837. if( NEVER(rc) ){
  67838. releasePage(pRoot);
  67839. return rc;
  67840. }
  67841. }else{
  67842. rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
  67843. if( rc ) return rc;
  67844. }
  67845. #endif
  67846. assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
  67847. if( createTabFlags & BTREE_INTKEY ){
  67848. ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
  67849. }else{
  67850. ptfFlags = PTF_ZERODATA | PTF_LEAF;
  67851. }
  67852. zeroPage(pRoot, ptfFlags);
  67853. sqlite3PagerUnref(pRoot->pDbPage);
  67854. assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
  67855. *piTable = (int)pgnoRoot;
  67856. return SQLITE_OK;
  67857. }
  67858. SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
  67859. int rc;
  67860. sqlite3BtreeEnter(p);
  67861. rc = btreeCreateTable(p, piTable, flags);
  67862. sqlite3BtreeLeave(p);
  67863. return rc;
  67864. }
  67865. /*
  67866. ** Erase the given database page and all its children. Return
  67867. ** the page to the freelist.
  67868. */
  67869. static int clearDatabasePage(
  67870. BtShared *pBt, /* The BTree that contains the table */
  67871. Pgno pgno, /* Page number to clear */
  67872. int freePageFlag, /* Deallocate page if true */
  67873. int *pnChange /* Add number of Cells freed to this counter */
  67874. ){
  67875. MemPage *pPage;
  67876. int rc;
  67877. unsigned char *pCell;
  67878. int i;
  67879. int hdr;
  67880. CellInfo info;
  67881. assert( sqlite3_mutex_held(pBt->mutex) );
  67882. if( pgno>btreePagecount(pBt) ){
  67883. return SQLITE_CORRUPT_BKPT;
  67884. }
  67885. rc = getAndInitPage(pBt, pgno, &pPage, 0, 0);
  67886. if( rc ) return rc;
  67887. if( pPage->bBusy ){
  67888. rc = SQLITE_CORRUPT_BKPT;
  67889. goto cleardatabasepage_out;
  67890. }
  67891. pPage->bBusy = 1;
  67892. hdr = pPage->hdrOffset;
  67893. for(i=0; i<pPage->nCell; i++){
  67894. pCell = findCell(pPage, i);
  67895. if( !pPage->leaf ){
  67896. rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
  67897. if( rc ) goto cleardatabasepage_out;
  67898. }
  67899. rc = clearCell(pPage, pCell, &info);
  67900. if( rc ) goto cleardatabasepage_out;
  67901. }
  67902. if( !pPage->leaf ){
  67903. rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
  67904. if( rc ) goto cleardatabasepage_out;
  67905. }else if( pnChange ){
  67906. assert( pPage->intKey || CORRUPT_DB );
  67907. testcase( !pPage->intKey );
  67908. *pnChange += pPage->nCell;
  67909. }
  67910. if( freePageFlag ){
  67911. freePage(pPage, &rc);
  67912. }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
  67913. zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
  67914. }
  67915. cleardatabasepage_out:
  67916. pPage->bBusy = 0;
  67917. releasePage(pPage);
  67918. return rc;
  67919. }
  67920. /*
  67921. ** Delete all information from a single table in the database. iTable is
  67922. ** the page number of the root of the table. After this routine returns,
  67923. ** the root page is empty, but still exists.
  67924. **
  67925. ** This routine will fail with SQLITE_LOCKED if there are any open
  67926. ** read cursors on the table. Open write cursors are moved to the
  67927. ** root of the table.
  67928. **
  67929. ** If pnChange is not NULL, then table iTable must be an intkey table. The
  67930. ** integer value pointed to by pnChange is incremented by the number of
  67931. ** entries in the table.
  67932. */
  67933. SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
  67934. int rc;
  67935. BtShared *pBt = p->pBt;
  67936. sqlite3BtreeEnter(p);
  67937. assert( p->inTrans==TRANS_WRITE );
  67938. rc = saveAllCursors(pBt, (Pgno)iTable, 0);
  67939. if( SQLITE_OK==rc ){
  67940. /* Invalidate all incrblob cursors open on table iTable (assuming iTable
  67941. ** is the root of a table b-tree - if it is not, the following call is
  67942. ** a no-op). */
  67943. invalidateIncrblobCursors(p, (Pgno)iTable, 0, 1);
  67944. rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
  67945. }
  67946. sqlite3BtreeLeave(p);
  67947. return rc;
  67948. }
  67949. /*
  67950. ** Delete all information from the single table that pCur is open on.
  67951. **
  67952. ** This routine only work for pCur on an ephemeral table.
  67953. */
  67954. SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
  67955. return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
  67956. }
  67957. /*
  67958. ** Erase all information in a table and add the root of the table to
  67959. ** the freelist. Except, the root of the principle table (the one on
  67960. ** page 1) is never added to the freelist.
  67961. **
  67962. ** This routine will fail with SQLITE_LOCKED if there are any open
  67963. ** cursors on the table.
  67964. **
  67965. ** If AUTOVACUUM is enabled and the page at iTable is not the last
  67966. ** root page in the database file, then the last root page
  67967. ** in the database file is moved into the slot formerly occupied by
  67968. ** iTable and that last slot formerly occupied by the last root page
  67969. ** is added to the freelist instead of iTable. In this say, all
  67970. ** root pages are kept at the beginning of the database file, which
  67971. ** is necessary for AUTOVACUUM to work right. *piMoved is set to the
  67972. ** page number that used to be the last root page in the file before
  67973. ** the move. If no page gets moved, *piMoved is set to 0.
  67974. ** The last root page is recorded in meta[3] and the value of
  67975. ** meta[3] is updated by this procedure.
  67976. */
  67977. static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
  67978. int rc;
  67979. MemPage *pPage = 0;
  67980. BtShared *pBt = p->pBt;
  67981. assert( sqlite3BtreeHoldsMutex(p) );
  67982. assert( p->inTrans==TRANS_WRITE );
  67983. assert( iTable>=2 );
  67984. if( iTable>btreePagecount(pBt) ){
  67985. return SQLITE_CORRUPT_BKPT;
  67986. }
  67987. rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
  67988. if( rc ) return rc;
  67989. rc = sqlite3BtreeClearTable(p, iTable, 0);
  67990. if( rc ){
  67991. releasePage(pPage);
  67992. return rc;
  67993. }
  67994. *piMoved = 0;
  67995. #ifdef SQLITE_OMIT_AUTOVACUUM
  67996. freePage(pPage, &rc);
  67997. releasePage(pPage);
  67998. #else
  67999. if( pBt->autoVacuum ){
  68000. Pgno maxRootPgno;
  68001. sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
  68002. if( iTable==maxRootPgno ){
  68003. /* If the table being dropped is the table with the largest root-page
  68004. ** number in the database, put the root page on the free list.
  68005. */
  68006. freePage(pPage, &rc);
  68007. releasePage(pPage);
  68008. if( rc!=SQLITE_OK ){
  68009. return rc;
  68010. }
  68011. }else{
  68012. /* The table being dropped does not have the largest root-page
  68013. ** number in the database. So move the page that does into the
  68014. ** gap left by the deleted root-page.
  68015. */
  68016. MemPage *pMove;
  68017. releasePage(pPage);
  68018. rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
  68019. if( rc!=SQLITE_OK ){
  68020. return rc;
  68021. }
  68022. rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
  68023. releasePage(pMove);
  68024. if( rc!=SQLITE_OK ){
  68025. return rc;
  68026. }
  68027. pMove = 0;
  68028. rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
  68029. freePage(pMove, &rc);
  68030. releasePage(pMove);
  68031. if( rc!=SQLITE_OK ){
  68032. return rc;
  68033. }
  68034. *piMoved = maxRootPgno;
  68035. }
  68036. /* Set the new 'max-root-page' value in the database header. This
  68037. ** is the old value less one, less one more if that happens to
  68038. ** be a root-page number, less one again if that is the
  68039. ** PENDING_BYTE_PAGE.
  68040. */
  68041. maxRootPgno--;
  68042. while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
  68043. || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
  68044. maxRootPgno--;
  68045. }
  68046. assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
  68047. rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
  68048. }else{
  68049. freePage(pPage, &rc);
  68050. releasePage(pPage);
  68051. }
  68052. #endif
  68053. return rc;
  68054. }
  68055. SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
  68056. int rc;
  68057. sqlite3BtreeEnter(p);
  68058. rc = btreeDropTable(p, iTable, piMoved);
  68059. sqlite3BtreeLeave(p);
  68060. return rc;
  68061. }
  68062. /*
  68063. ** This function may only be called if the b-tree connection already
  68064. ** has a read or write transaction open on the database.
  68065. **
  68066. ** Read the meta-information out of a database file. Meta[0]
  68067. ** is the number of free pages currently in the database. Meta[1]
  68068. ** through meta[15] are available for use by higher layers. Meta[0]
  68069. ** is read-only, the others are read/write.
  68070. **
  68071. ** The schema layer numbers meta values differently. At the schema
  68072. ** layer (and the SetCookie and ReadCookie opcodes) the number of
  68073. ** free pages is not visible. So Cookie[0] is the same as Meta[1].
  68074. **
  68075. ** This routine treats Meta[BTREE_DATA_VERSION] as a special case. Instead
  68076. ** of reading the value out of the header, it instead loads the "DataVersion"
  68077. ** from the pager. The BTREE_DATA_VERSION value is not actually stored in the
  68078. ** database file. It is a number computed by the pager. But its access
  68079. ** pattern is the same as header meta values, and so it is convenient to
  68080. ** read it from this routine.
  68081. */
  68082. SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
  68083. BtShared *pBt = p->pBt;
  68084. sqlite3BtreeEnter(p);
  68085. assert( p->inTrans>TRANS_NONE );
  68086. assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
  68087. assert( pBt->pPage1 );
  68088. assert( idx>=0 && idx<=15 );
  68089. if( idx==BTREE_DATA_VERSION ){
  68090. *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iDataVersion;
  68091. }else{
  68092. *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
  68093. }
  68094. /* If auto-vacuum is disabled in this build and this is an auto-vacuum
  68095. ** database, mark the database as read-only. */
  68096. #ifdef SQLITE_OMIT_AUTOVACUUM
  68097. if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
  68098. pBt->btsFlags |= BTS_READ_ONLY;
  68099. }
  68100. #endif
  68101. sqlite3BtreeLeave(p);
  68102. }
  68103. /*
  68104. ** Write meta-information back into the database. Meta[0] is
  68105. ** read-only and may not be written.
  68106. */
  68107. SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
  68108. BtShared *pBt = p->pBt;
  68109. unsigned char *pP1;
  68110. int rc;
  68111. assert( idx>=1 && idx<=15 );
  68112. sqlite3BtreeEnter(p);
  68113. assert( p->inTrans==TRANS_WRITE );
  68114. assert( pBt->pPage1!=0 );
  68115. pP1 = pBt->pPage1->aData;
  68116. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  68117. if( rc==SQLITE_OK ){
  68118. put4byte(&pP1[36 + idx*4], iMeta);
  68119. #ifndef SQLITE_OMIT_AUTOVACUUM
  68120. if( idx==BTREE_INCR_VACUUM ){
  68121. assert( pBt->autoVacuum || iMeta==0 );
  68122. assert( iMeta==0 || iMeta==1 );
  68123. pBt->incrVacuum = (u8)iMeta;
  68124. }
  68125. #endif
  68126. }
  68127. sqlite3BtreeLeave(p);
  68128. return rc;
  68129. }
  68130. #ifndef SQLITE_OMIT_BTREECOUNT
  68131. /*
  68132. ** The first argument, pCur, is a cursor opened on some b-tree. Count the
  68133. ** number of entries in the b-tree and write the result to *pnEntry.
  68134. **
  68135. ** SQLITE_OK is returned if the operation is successfully executed.
  68136. ** Otherwise, if an error is encountered (i.e. an IO error or database
  68137. ** corruption) an SQLite error code is returned.
  68138. */
  68139. SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
  68140. i64 nEntry = 0; /* Value to return in *pnEntry */
  68141. int rc; /* Return code */
  68142. rc = moveToRoot(pCur);
  68143. if( rc==SQLITE_EMPTY ){
  68144. *pnEntry = 0;
  68145. return SQLITE_OK;
  68146. }
  68147. /* Unless an error occurs, the following loop runs one iteration for each
  68148. ** page in the B-Tree structure (not including overflow pages).
  68149. */
  68150. while( rc==SQLITE_OK ){
  68151. int iIdx; /* Index of child node in parent */
  68152. MemPage *pPage; /* Current page of the b-tree */
  68153. /* If this is a leaf page or the tree is not an int-key tree, then
  68154. ** this page contains countable entries. Increment the entry counter
  68155. ** accordingly.
  68156. */
  68157. pPage = pCur->pPage;
  68158. if( pPage->leaf || !pPage->intKey ){
  68159. nEntry += pPage->nCell;
  68160. }
  68161. /* pPage is a leaf node. This loop navigates the cursor so that it
  68162. ** points to the first interior cell that it points to the parent of
  68163. ** the next page in the tree that has not yet been visited. The
  68164. ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
  68165. ** of the page, or to the number of cells in the page if the next page
  68166. ** to visit is the right-child of its parent.
  68167. **
  68168. ** If all pages in the tree have been visited, return SQLITE_OK to the
  68169. ** caller.
  68170. */
  68171. if( pPage->leaf ){
  68172. do {
  68173. if( pCur->iPage==0 ){
  68174. /* All pages of the b-tree have been visited. Return successfully. */
  68175. *pnEntry = nEntry;
  68176. return moveToRoot(pCur);
  68177. }
  68178. moveToParent(pCur);
  68179. }while ( pCur->ix>=pCur->pPage->nCell );
  68180. pCur->ix++;
  68181. pPage = pCur->pPage;
  68182. }
  68183. /* Descend to the child node of the cell that the cursor currently
  68184. ** points at. This is the right-child if (iIdx==pPage->nCell).
  68185. */
  68186. iIdx = pCur->ix;
  68187. if( iIdx==pPage->nCell ){
  68188. rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
  68189. }else{
  68190. rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
  68191. }
  68192. }
  68193. /* An error has occurred. Return an error code. */
  68194. return rc;
  68195. }
  68196. #endif
  68197. /*
  68198. ** Return the pager associated with a BTree. This routine is used for
  68199. ** testing and debugging only.
  68200. */
  68201. SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
  68202. return p->pBt->pPager;
  68203. }
  68204. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  68205. /*
  68206. ** Append a message to the error message string.
  68207. */
  68208. static void checkAppendMsg(
  68209. IntegrityCk *pCheck,
  68210. const char *zFormat,
  68211. ...
  68212. ){
  68213. va_list ap;
  68214. if( !pCheck->mxErr ) return;
  68215. pCheck->mxErr--;
  68216. pCheck->nErr++;
  68217. va_start(ap, zFormat);
  68218. if( pCheck->errMsg.nChar ){
  68219. sqlite3_str_append(&pCheck->errMsg, "\n", 1);
  68220. }
  68221. if( pCheck->zPfx ){
  68222. sqlite3_str_appendf(&pCheck->errMsg, pCheck->zPfx, pCheck->v1, pCheck->v2);
  68223. }
  68224. sqlite3_str_vappendf(&pCheck->errMsg, zFormat, ap);
  68225. va_end(ap);
  68226. if( pCheck->errMsg.accError==SQLITE_NOMEM ){
  68227. pCheck->mallocFailed = 1;
  68228. }
  68229. }
  68230. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  68231. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  68232. /*
  68233. ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
  68234. ** corresponds to page iPg is already set.
  68235. */
  68236. static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
  68237. assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
  68238. return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
  68239. }
  68240. /*
  68241. ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
  68242. */
  68243. static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
  68244. assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
  68245. pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
  68246. }
  68247. /*
  68248. ** Add 1 to the reference count for page iPage. If this is the second
  68249. ** reference to the page, add an error message to pCheck->zErrMsg.
  68250. ** Return 1 if there are 2 or more references to the page and 0 if
  68251. ** if this is the first reference to the page.
  68252. **
  68253. ** Also check that the page number is in bounds.
  68254. */
  68255. static int checkRef(IntegrityCk *pCheck, Pgno iPage){
  68256. if( iPage>pCheck->nPage || iPage==0 ){
  68257. checkAppendMsg(pCheck, "invalid page number %d", iPage);
  68258. return 1;
  68259. }
  68260. if( getPageReferenced(pCheck, iPage) ){
  68261. checkAppendMsg(pCheck, "2nd reference to page %d", iPage);
  68262. return 1;
  68263. }
  68264. setPageReferenced(pCheck, iPage);
  68265. return 0;
  68266. }
  68267. #ifndef SQLITE_OMIT_AUTOVACUUM
  68268. /*
  68269. ** Check that the entry in the pointer-map for page iChild maps to
  68270. ** page iParent, pointer type ptrType. If not, append an error message
  68271. ** to pCheck.
  68272. */
  68273. static void checkPtrmap(
  68274. IntegrityCk *pCheck, /* Integrity check context */
  68275. Pgno iChild, /* Child page number */
  68276. u8 eType, /* Expected pointer map type */
  68277. Pgno iParent /* Expected pointer map parent page number */
  68278. ){
  68279. int rc;
  68280. u8 ePtrmapType;
  68281. Pgno iPtrmapParent;
  68282. rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
  68283. if( rc!=SQLITE_OK ){
  68284. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
  68285. checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild);
  68286. return;
  68287. }
  68288. if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
  68289. checkAppendMsg(pCheck,
  68290. "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
  68291. iChild, eType, iParent, ePtrmapType, iPtrmapParent);
  68292. }
  68293. }
  68294. #endif
  68295. /*
  68296. ** Check the integrity of the freelist or of an overflow page list.
  68297. ** Verify that the number of pages on the list is N.
  68298. */
  68299. static void checkList(
  68300. IntegrityCk *pCheck, /* Integrity checking context */
  68301. int isFreeList, /* True for a freelist. False for overflow page list */
  68302. int iPage, /* Page number for first page in the list */
  68303. u32 N /* Expected number of pages in the list */
  68304. ){
  68305. int i;
  68306. u32 expected = N;
  68307. int nErrAtStart = pCheck->nErr;
  68308. while( iPage!=0 && pCheck->mxErr ){
  68309. DbPage *pOvflPage;
  68310. unsigned char *pOvflData;
  68311. if( checkRef(pCheck, iPage) ) break;
  68312. N--;
  68313. if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage, 0) ){
  68314. checkAppendMsg(pCheck, "failed to get page %d", iPage);
  68315. break;
  68316. }
  68317. pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
  68318. if( isFreeList ){
  68319. u32 n = (u32)get4byte(&pOvflData[4]);
  68320. #ifndef SQLITE_OMIT_AUTOVACUUM
  68321. if( pCheck->pBt->autoVacuum ){
  68322. checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
  68323. }
  68324. #endif
  68325. if( n>pCheck->pBt->usableSize/4-2 ){
  68326. checkAppendMsg(pCheck,
  68327. "freelist leaf count too big on page %d", iPage);
  68328. N--;
  68329. }else{
  68330. for(i=0; i<(int)n; i++){
  68331. Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
  68332. #ifndef SQLITE_OMIT_AUTOVACUUM
  68333. if( pCheck->pBt->autoVacuum ){
  68334. checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
  68335. }
  68336. #endif
  68337. checkRef(pCheck, iFreePage);
  68338. }
  68339. N -= n;
  68340. }
  68341. }
  68342. #ifndef SQLITE_OMIT_AUTOVACUUM
  68343. else{
  68344. /* If this database supports auto-vacuum and iPage is not the last
  68345. ** page in this overflow list, check that the pointer-map entry for
  68346. ** the following page matches iPage.
  68347. */
  68348. if( pCheck->pBt->autoVacuum && N>0 ){
  68349. i = get4byte(pOvflData);
  68350. checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);
  68351. }
  68352. }
  68353. #endif
  68354. iPage = get4byte(pOvflData);
  68355. sqlite3PagerUnref(pOvflPage);
  68356. }
  68357. if( N && nErrAtStart==pCheck->nErr ){
  68358. checkAppendMsg(pCheck,
  68359. "%s is %d but should be %d",
  68360. isFreeList ? "size" : "overflow list length",
  68361. expected-N, expected);
  68362. }
  68363. }
  68364. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  68365. /*
  68366. ** An implementation of a min-heap.
  68367. **
  68368. ** aHeap[0] is the number of elements on the heap. aHeap[1] is the
  68369. ** root element. The daughter nodes of aHeap[N] are aHeap[N*2]
  68370. ** and aHeap[N*2+1].
  68371. **
  68372. ** The heap property is this: Every node is less than or equal to both
  68373. ** of its daughter nodes. A consequence of the heap property is that the
  68374. ** root node aHeap[1] is always the minimum value currently in the heap.
  68375. **
  68376. ** The btreeHeapInsert() routine inserts an unsigned 32-bit number onto
  68377. ** the heap, preserving the heap property. The btreeHeapPull() routine
  68378. ** removes the root element from the heap (the minimum value in the heap)
  68379. ** and then moves other nodes around as necessary to preserve the heap
  68380. ** property.
  68381. **
  68382. ** This heap is used for cell overlap and coverage testing. Each u32
  68383. ** entry represents the span of a cell or freeblock on a btree page.
  68384. ** The upper 16 bits are the index of the first byte of a range and the
  68385. ** lower 16 bits are the index of the last byte of that range.
  68386. */
  68387. static void btreeHeapInsert(u32 *aHeap, u32 x){
  68388. u32 j, i = ++aHeap[0];
  68389. aHeap[i] = x;
  68390. while( (j = i/2)>0 && aHeap[j]>aHeap[i] ){
  68391. x = aHeap[j];
  68392. aHeap[j] = aHeap[i];
  68393. aHeap[i] = x;
  68394. i = j;
  68395. }
  68396. }
  68397. static int btreeHeapPull(u32 *aHeap, u32 *pOut){
  68398. u32 j, i, x;
  68399. if( (x = aHeap[0])==0 ) return 0;
  68400. *pOut = aHeap[1];
  68401. aHeap[1] = aHeap[x];
  68402. aHeap[x] = 0xffffffff;
  68403. aHeap[0]--;
  68404. i = 1;
  68405. while( (j = i*2)<=aHeap[0] ){
  68406. if( aHeap[j]>aHeap[j+1] ) j++;
  68407. if( aHeap[i]<aHeap[j] ) break;
  68408. x = aHeap[i];
  68409. aHeap[i] = aHeap[j];
  68410. aHeap[j] = x;
  68411. i = j;
  68412. }
  68413. return 1;
  68414. }
  68415. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  68416. /*
  68417. ** Do various sanity checks on a single page of a tree. Return
  68418. ** the tree depth. Root pages return 0. Parents of root pages
  68419. ** return 1, and so forth.
  68420. **
  68421. ** These checks are done:
  68422. **
  68423. ** 1. Make sure that cells and freeblocks do not overlap
  68424. ** but combine to completely cover the page.
  68425. ** 2. Make sure integer cell keys are in order.
  68426. ** 3. Check the integrity of overflow pages.
  68427. ** 4. Recursively call checkTreePage on all children.
  68428. ** 5. Verify that the depth of all children is the same.
  68429. */
  68430. static int checkTreePage(
  68431. IntegrityCk *pCheck, /* Context for the sanity check */
  68432. int iPage, /* Page number of the page to check */
  68433. i64 *piMinKey, /* Write minimum integer primary key here */
  68434. i64 maxKey /* Error if integer primary key greater than this */
  68435. ){
  68436. MemPage *pPage = 0; /* The page being analyzed */
  68437. int i; /* Loop counter */
  68438. int rc; /* Result code from subroutine call */
  68439. int depth = -1, d2; /* Depth of a subtree */
  68440. int pgno; /* Page number */
  68441. int nFrag; /* Number of fragmented bytes on the page */
  68442. int hdr; /* Offset to the page header */
  68443. int cellStart; /* Offset to the start of the cell pointer array */
  68444. int nCell; /* Number of cells */
  68445. int doCoverageCheck = 1; /* True if cell coverage checking should be done */
  68446. int keyCanBeEqual = 1; /* True if IPK can be equal to maxKey
  68447. ** False if IPK must be strictly less than maxKey */
  68448. u8 *data; /* Page content */
  68449. u8 *pCell; /* Cell content */
  68450. u8 *pCellIdx; /* Next element of the cell pointer array */
  68451. BtShared *pBt; /* The BtShared object that owns pPage */
  68452. u32 pc; /* Address of a cell */
  68453. u32 usableSize; /* Usable size of the page */
  68454. u32 contentOffset; /* Offset to the start of the cell content area */
  68455. u32 *heap = 0; /* Min-heap used for checking cell coverage */
  68456. u32 x, prev = 0; /* Next and previous entry on the min-heap */
  68457. const char *saved_zPfx = pCheck->zPfx;
  68458. int saved_v1 = pCheck->v1;
  68459. int saved_v2 = pCheck->v2;
  68460. u8 savedIsInit = 0;
  68461. /* Check that the page exists
  68462. */
  68463. pBt = pCheck->pBt;
  68464. usableSize = pBt->usableSize;
  68465. if( iPage==0 ) return 0;
  68466. if( checkRef(pCheck, iPage) ) return 0;
  68467. pCheck->zPfx = "Page %d: ";
  68468. pCheck->v1 = iPage;
  68469. if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
  68470. checkAppendMsg(pCheck,
  68471. "unable to get the page. error code=%d", rc);
  68472. goto end_of_check;
  68473. }
  68474. /* Clear MemPage.isInit to make sure the corruption detection code in
  68475. ** btreeInitPage() is executed. */
  68476. savedIsInit = pPage->isInit;
  68477. pPage->isInit = 0;
  68478. if( (rc = btreeInitPage(pPage))!=0 ){
  68479. assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
  68480. checkAppendMsg(pCheck,
  68481. "btreeInitPage() returns error code %d", rc);
  68482. goto end_of_check;
  68483. }
  68484. if( (rc = btreeComputeFreeSpace(pPage))!=0 ){
  68485. assert( rc==SQLITE_CORRUPT );
  68486. checkAppendMsg(pCheck, "free space corruption", rc);
  68487. goto end_of_check;
  68488. }
  68489. data = pPage->aData;
  68490. hdr = pPage->hdrOffset;
  68491. /* Set up for cell analysis */
  68492. pCheck->zPfx = "On tree page %d cell %d: ";
  68493. contentOffset = get2byteNotZero(&data[hdr+5]);
  68494. assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */
  68495. /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
  68496. ** number of cells on the page. */
  68497. nCell = get2byte(&data[hdr+3]);
  68498. assert( pPage->nCell==nCell );
  68499. /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page
  68500. ** immediately follows the b-tree page header. */
  68501. cellStart = hdr + 12 - 4*pPage->leaf;
  68502. assert( pPage->aCellIdx==&data[cellStart] );
  68503. pCellIdx = &data[cellStart + 2*(nCell-1)];
  68504. if( !pPage->leaf ){
  68505. /* Analyze the right-child page of internal pages */
  68506. pgno = get4byte(&data[hdr+8]);
  68507. #ifndef SQLITE_OMIT_AUTOVACUUM
  68508. if( pBt->autoVacuum ){
  68509. pCheck->zPfx = "On page %d at right child: ";
  68510. checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
  68511. }
  68512. #endif
  68513. depth = checkTreePage(pCheck, pgno, &maxKey, maxKey);
  68514. keyCanBeEqual = 0;
  68515. }else{
  68516. /* For leaf pages, the coverage check will occur in the same loop
  68517. ** as the other cell checks, so initialize the heap. */
  68518. heap = pCheck->heap;
  68519. heap[0] = 0;
  68520. }
  68521. /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte
  68522. ** integer offsets to the cell contents. */
  68523. for(i=nCell-1; i>=0 && pCheck->mxErr; i--){
  68524. CellInfo info;
  68525. /* Check cell size */
  68526. pCheck->v2 = i;
  68527. assert( pCellIdx==&data[cellStart + i*2] );
  68528. pc = get2byteAligned(pCellIdx);
  68529. pCellIdx -= 2;
  68530. if( pc<contentOffset || pc>usableSize-4 ){
  68531. checkAppendMsg(pCheck, "Offset %d out of range %d..%d",
  68532. pc, contentOffset, usableSize-4);
  68533. doCoverageCheck = 0;
  68534. continue;
  68535. }
  68536. pCell = &data[pc];
  68537. pPage->xParseCell(pPage, pCell, &info);
  68538. if( pc+info.nSize>usableSize ){
  68539. checkAppendMsg(pCheck, "Extends off end of page");
  68540. doCoverageCheck = 0;
  68541. continue;
  68542. }
  68543. /* Check for integer primary key out of range */
  68544. if( pPage->intKey ){
  68545. if( keyCanBeEqual ? (info.nKey > maxKey) : (info.nKey >= maxKey) ){
  68546. checkAppendMsg(pCheck, "Rowid %lld out of order", info.nKey);
  68547. }
  68548. maxKey = info.nKey;
  68549. keyCanBeEqual = 0; /* Only the first key on the page may ==maxKey */
  68550. }
  68551. /* Check the content overflow list */
  68552. if( info.nPayload>info.nLocal ){
  68553. u32 nPage; /* Number of pages on the overflow chain */
  68554. Pgno pgnoOvfl; /* First page of the overflow chain */
  68555. assert( pc + info.nSize - 4 <= usableSize );
  68556. nPage = (info.nPayload - info.nLocal + usableSize - 5)/(usableSize - 4);
  68557. pgnoOvfl = get4byte(&pCell[info.nSize - 4]);
  68558. #ifndef SQLITE_OMIT_AUTOVACUUM
  68559. if( pBt->autoVacuum ){
  68560. checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);
  68561. }
  68562. #endif
  68563. checkList(pCheck, 0, pgnoOvfl, nPage);
  68564. }
  68565. if( !pPage->leaf ){
  68566. /* Check sanity of left child page for internal pages */
  68567. pgno = get4byte(pCell);
  68568. #ifndef SQLITE_OMIT_AUTOVACUUM
  68569. if( pBt->autoVacuum ){
  68570. checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
  68571. }
  68572. #endif
  68573. d2 = checkTreePage(pCheck, pgno, &maxKey, maxKey);
  68574. keyCanBeEqual = 0;
  68575. if( d2!=depth ){
  68576. checkAppendMsg(pCheck, "Child page depth differs");
  68577. depth = d2;
  68578. }
  68579. }else{
  68580. /* Populate the coverage-checking heap for leaf pages */
  68581. btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1));
  68582. }
  68583. }
  68584. *piMinKey = maxKey;
  68585. /* Check for complete coverage of the page
  68586. */
  68587. pCheck->zPfx = 0;
  68588. if( doCoverageCheck && pCheck->mxErr>0 ){
  68589. /* For leaf pages, the min-heap has already been initialized and the
  68590. ** cells have already been inserted. But for internal pages, that has
  68591. ** not yet been done, so do it now */
  68592. if( !pPage->leaf ){
  68593. heap = pCheck->heap;
  68594. heap[0] = 0;
  68595. for(i=nCell-1; i>=0; i--){
  68596. u32 size;
  68597. pc = get2byteAligned(&data[cellStart+i*2]);
  68598. size = pPage->xCellSize(pPage, &data[pc]);
  68599. btreeHeapInsert(heap, (pc<<16)|(pc+size-1));
  68600. }
  68601. }
  68602. /* Add the freeblocks to the min-heap
  68603. **
  68604. ** EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header
  68605. ** is the offset of the first freeblock, or zero if there are no
  68606. ** freeblocks on the page.
  68607. */
  68608. i = get2byte(&data[hdr+1]);
  68609. while( i>0 ){
  68610. int size, j;
  68611. assert( (u32)i<=usableSize-4 ); /* Enforced by btreeComputeFreeSpace() */
  68612. size = get2byte(&data[i+2]);
  68613. assert( (u32)(i+size)<=usableSize ); /* due to btreeComputeFreeSpace() */
  68614. btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1));
  68615. /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a
  68616. ** big-endian integer which is the offset in the b-tree page of the next
  68617. ** freeblock in the chain, or zero if the freeblock is the last on the
  68618. ** chain. */
  68619. j = get2byte(&data[i]);
  68620. /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
  68621. ** increasing offset. */
  68622. assert( j==0 || j>i+size ); /* Enforced by btreeComputeFreeSpace() */
  68623. assert( (u32)j<=usableSize-4 ); /* Enforced by btreeComputeFreeSpace() */
  68624. i = j;
  68625. }
  68626. /* Analyze the min-heap looking for overlap between cells and/or
  68627. ** freeblocks, and counting the number of untracked bytes in nFrag.
  68628. **
  68629. ** Each min-heap entry is of the form: (start_address<<16)|end_address.
  68630. ** There is an implied first entry the covers the page header, the cell
  68631. ** pointer index, and the gap between the cell pointer index and the start
  68632. ** of cell content.
  68633. **
  68634. ** The loop below pulls entries from the min-heap in order and compares
  68635. ** the start_address against the previous end_address. If there is an
  68636. ** overlap, that means bytes are used multiple times. If there is a gap,
  68637. ** that gap is added to the fragmentation count.
  68638. */
  68639. nFrag = 0;
  68640. prev = contentOffset - 1; /* Implied first min-heap entry */
  68641. while( btreeHeapPull(heap,&x) ){
  68642. if( (prev&0xffff)>=(x>>16) ){
  68643. checkAppendMsg(pCheck,
  68644. "Multiple uses for byte %u of page %d", x>>16, iPage);
  68645. break;
  68646. }else{
  68647. nFrag += (x>>16) - (prev&0xffff) - 1;
  68648. prev = x;
  68649. }
  68650. }
  68651. nFrag += usableSize - (prev&0xffff) - 1;
  68652. /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments
  68653. ** is stored in the fifth field of the b-tree page header.
  68654. ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the
  68655. ** number of fragmented free bytes within the cell content area.
  68656. */
  68657. if( heap[0]==0 && nFrag!=data[hdr+7] ){
  68658. checkAppendMsg(pCheck,
  68659. "Fragmentation of %d bytes reported as %d on page %d",
  68660. nFrag, data[hdr+7], iPage);
  68661. }
  68662. }
  68663. end_of_check:
  68664. if( !doCoverageCheck ) pPage->isInit = savedIsInit;
  68665. releasePage(pPage);
  68666. pCheck->zPfx = saved_zPfx;
  68667. pCheck->v1 = saved_v1;
  68668. pCheck->v2 = saved_v2;
  68669. return depth+1;
  68670. }
  68671. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  68672. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  68673. /*
  68674. ** This routine does a complete check of the given BTree file. aRoot[] is
  68675. ** an array of pages numbers were each page number is the root page of
  68676. ** a table. nRoot is the number of entries in aRoot.
  68677. **
  68678. ** A read-only or read-write transaction must be opened before calling
  68679. ** this function.
  68680. **
  68681. ** Write the number of error seen in *pnErr. Except for some memory
  68682. ** allocation errors, an error message held in memory obtained from
  68683. ** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
  68684. ** returned. If a memory allocation error occurs, NULL is returned.
  68685. */
  68686. SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
  68687. Btree *p, /* The btree to be checked */
  68688. int *aRoot, /* An array of root pages numbers for individual trees */
  68689. int nRoot, /* Number of entries in aRoot[] */
  68690. int mxErr, /* Stop reporting errors after this many */
  68691. int *pnErr /* Write number of errors seen to this variable */
  68692. ){
  68693. Pgno i;
  68694. IntegrityCk sCheck;
  68695. BtShared *pBt = p->pBt;
  68696. u64 savedDbFlags = pBt->db->flags;
  68697. char zErr[100];
  68698. VVA_ONLY( int nRef );
  68699. sqlite3BtreeEnter(p);
  68700. assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
  68701. VVA_ONLY( nRef = sqlite3PagerRefcount(pBt->pPager) );
  68702. assert( nRef>=0 );
  68703. sCheck.pBt = pBt;
  68704. sCheck.pPager = pBt->pPager;
  68705. sCheck.nPage = btreePagecount(sCheck.pBt);
  68706. sCheck.mxErr = mxErr;
  68707. sCheck.nErr = 0;
  68708. sCheck.mallocFailed = 0;
  68709. sCheck.zPfx = 0;
  68710. sCheck.v1 = 0;
  68711. sCheck.v2 = 0;
  68712. sCheck.aPgRef = 0;
  68713. sCheck.heap = 0;
  68714. sqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
  68715. sCheck.errMsg.printfFlags = SQLITE_PRINTF_INTERNAL;
  68716. if( sCheck.nPage==0 ){
  68717. goto integrity_ck_cleanup;
  68718. }
  68719. sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
  68720. if( !sCheck.aPgRef ){
  68721. sCheck.mallocFailed = 1;
  68722. goto integrity_ck_cleanup;
  68723. }
  68724. sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize );
  68725. if( sCheck.heap==0 ){
  68726. sCheck.mallocFailed = 1;
  68727. goto integrity_ck_cleanup;
  68728. }
  68729. i = PENDING_BYTE_PAGE(pBt);
  68730. if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
  68731. /* Check the integrity of the freelist
  68732. */
  68733. sCheck.zPfx = "Main freelist: ";
  68734. checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
  68735. get4byte(&pBt->pPage1->aData[36]));
  68736. sCheck.zPfx = 0;
  68737. /* Check all the tables.
  68738. */
  68739. #ifndef SQLITE_OMIT_AUTOVACUUM
  68740. if( pBt->autoVacuum ){
  68741. int mx = 0;
  68742. int mxInHdr;
  68743. for(i=0; (int)i<nRoot; i++) if( mx<aRoot[i] ) mx = aRoot[i];
  68744. mxInHdr = get4byte(&pBt->pPage1->aData[52]);
  68745. if( mx!=mxInHdr ){
  68746. checkAppendMsg(&sCheck,
  68747. "max rootpage (%d) disagrees with header (%d)",
  68748. mx, mxInHdr
  68749. );
  68750. }
  68751. }else if( get4byte(&pBt->pPage1->aData[64])!=0 ){
  68752. checkAppendMsg(&sCheck,
  68753. "incremental_vacuum enabled with a max rootpage of zero"
  68754. );
  68755. }
  68756. #endif
  68757. testcase( pBt->db->flags & SQLITE_CellSizeCk );
  68758. pBt->db->flags &= ~(u64)SQLITE_CellSizeCk;
  68759. for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
  68760. i64 notUsed;
  68761. if( aRoot[i]==0 ) continue;
  68762. #ifndef SQLITE_OMIT_AUTOVACUUM
  68763. if( pBt->autoVacuum && aRoot[i]>1 ){
  68764. checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
  68765. }
  68766. #endif
  68767. checkTreePage(&sCheck, aRoot[i], &notUsed, LARGEST_INT64);
  68768. }
  68769. pBt->db->flags = savedDbFlags;
  68770. /* Make sure every page in the file is referenced
  68771. */
  68772. for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
  68773. #ifdef SQLITE_OMIT_AUTOVACUUM
  68774. if( getPageReferenced(&sCheck, i)==0 ){
  68775. checkAppendMsg(&sCheck, "Page %d is never used", i);
  68776. }
  68777. #else
  68778. /* If the database supports auto-vacuum, make sure no tables contain
  68779. ** references to pointer-map pages.
  68780. */
  68781. if( getPageReferenced(&sCheck, i)==0 &&
  68782. (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
  68783. checkAppendMsg(&sCheck, "Page %d is never used", i);
  68784. }
  68785. if( getPageReferenced(&sCheck, i)!=0 &&
  68786. (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
  68787. checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i);
  68788. }
  68789. #endif
  68790. }
  68791. /* Clean up and report errors.
  68792. */
  68793. integrity_ck_cleanup:
  68794. sqlite3PageFree(sCheck.heap);
  68795. sqlite3_free(sCheck.aPgRef);
  68796. if( sCheck.mallocFailed ){
  68797. sqlite3_str_reset(&sCheck.errMsg);
  68798. sCheck.nErr++;
  68799. }
  68800. *pnErr = sCheck.nErr;
  68801. if( sCheck.nErr==0 ) sqlite3_str_reset(&sCheck.errMsg);
  68802. /* Make sure this analysis did not leave any unref() pages. */
  68803. assert( nRef==sqlite3PagerRefcount(pBt->pPager) );
  68804. sqlite3BtreeLeave(p);
  68805. return sqlite3StrAccumFinish(&sCheck.errMsg);
  68806. }
  68807. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  68808. /*
  68809. ** Return the full pathname of the underlying database file. Return
  68810. ** an empty string if the database is in-memory or a TEMP database.
  68811. **
  68812. ** The pager filename is invariant as long as the pager is
  68813. ** open so it is safe to access without the BtShared mutex.
  68814. */
  68815. SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
  68816. assert( p->pBt->pPager!=0 );
  68817. return sqlite3PagerFilename(p->pBt->pPager, 1);
  68818. }
  68819. /*
  68820. ** Return the pathname of the journal file for this database. The return
  68821. ** value of this routine is the same regardless of whether the journal file
  68822. ** has been created or not.
  68823. **
  68824. ** The pager journal filename is invariant as long as the pager is
  68825. ** open so it is safe to access without the BtShared mutex.
  68826. */
  68827. SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
  68828. assert( p->pBt->pPager!=0 );
  68829. return sqlite3PagerJournalname(p->pBt->pPager);
  68830. }
  68831. /*
  68832. ** Return non-zero if a transaction is active.
  68833. */
  68834. SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
  68835. assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
  68836. return (p && (p->inTrans==TRANS_WRITE));
  68837. }
  68838. #ifndef SQLITE_OMIT_WAL
  68839. /*
  68840. ** Run a checkpoint on the Btree passed as the first argument.
  68841. **
  68842. ** Return SQLITE_LOCKED if this or any other connection has an open
  68843. ** transaction on the shared-cache the argument Btree is connected to.
  68844. **
  68845. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  68846. */
  68847. SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
  68848. int rc = SQLITE_OK;
  68849. if( p ){
  68850. BtShared *pBt = p->pBt;
  68851. sqlite3BtreeEnter(p);
  68852. if( pBt->inTransaction!=TRANS_NONE ){
  68853. rc = SQLITE_LOCKED;
  68854. }else{
  68855. rc = sqlite3PagerCheckpoint(pBt->pPager, p->db, eMode, pnLog, pnCkpt);
  68856. }
  68857. sqlite3BtreeLeave(p);
  68858. }
  68859. return rc;
  68860. }
  68861. #endif
  68862. /*
  68863. ** Return non-zero if a read (or write) transaction is active.
  68864. */
  68865. SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
  68866. assert( p );
  68867. assert( sqlite3_mutex_held(p->db->mutex) );
  68868. return p->inTrans!=TRANS_NONE;
  68869. }
  68870. SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
  68871. assert( p );
  68872. assert( sqlite3_mutex_held(p->db->mutex) );
  68873. return p->nBackup!=0;
  68874. }
  68875. /*
  68876. ** This function returns a pointer to a blob of memory associated with
  68877. ** a single shared-btree. The memory is used by client code for its own
  68878. ** purposes (for example, to store a high-level schema associated with
  68879. ** the shared-btree). The btree layer manages reference counting issues.
  68880. **
  68881. ** The first time this is called on a shared-btree, nBytes bytes of memory
  68882. ** are allocated, zeroed, and returned to the caller. For each subsequent
  68883. ** call the nBytes parameter is ignored and a pointer to the same blob
  68884. ** of memory returned.
  68885. **
  68886. ** If the nBytes parameter is 0 and the blob of memory has not yet been
  68887. ** allocated, a null pointer is returned. If the blob has already been
  68888. ** allocated, it is returned as normal.
  68889. **
  68890. ** Just before the shared-btree is closed, the function passed as the
  68891. ** xFree argument when the memory allocation was made is invoked on the
  68892. ** blob of allocated memory. The xFree function should not call sqlite3_free()
  68893. ** on the memory, the btree layer does that.
  68894. */
  68895. SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
  68896. BtShared *pBt = p->pBt;
  68897. sqlite3BtreeEnter(p);
  68898. if( !pBt->pSchema && nBytes ){
  68899. pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
  68900. pBt->xFreeSchema = xFree;
  68901. }
  68902. sqlite3BtreeLeave(p);
  68903. return pBt->pSchema;
  68904. }
  68905. /*
  68906. ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
  68907. ** btree as the argument handle holds an exclusive lock on the
  68908. ** sqlite_master table. Otherwise SQLITE_OK.
  68909. */
  68910. SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
  68911. int rc;
  68912. assert( sqlite3_mutex_held(p->db->mutex) );
  68913. sqlite3BtreeEnter(p);
  68914. rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
  68915. assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
  68916. sqlite3BtreeLeave(p);
  68917. return rc;
  68918. }
  68919. #ifndef SQLITE_OMIT_SHARED_CACHE
  68920. /*
  68921. ** Obtain a lock on the table whose root page is iTab. The
  68922. ** lock is a write lock if isWritelock is true or a read lock
  68923. ** if it is false.
  68924. */
  68925. SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
  68926. int rc = SQLITE_OK;
  68927. assert( p->inTrans!=TRANS_NONE );
  68928. if( p->sharable ){
  68929. u8 lockType = READ_LOCK + isWriteLock;
  68930. assert( READ_LOCK+1==WRITE_LOCK );
  68931. assert( isWriteLock==0 || isWriteLock==1 );
  68932. sqlite3BtreeEnter(p);
  68933. rc = querySharedCacheTableLock(p, iTab, lockType);
  68934. if( rc==SQLITE_OK ){
  68935. rc = setSharedCacheTableLock(p, iTab, lockType);
  68936. }
  68937. sqlite3BtreeLeave(p);
  68938. }
  68939. return rc;
  68940. }
  68941. #endif
  68942. #ifndef SQLITE_OMIT_INCRBLOB
  68943. /*
  68944. ** Argument pCsr must be a cursor opened for writing on an
  68945. ** INTKEY table currently pointing at a valid table entry.
  68946. ** This function modifies the data stored as part of that entry.
  68947. **
  68948. ** Only the data content may only be modified, it is not possible to
  68949. ** change the length of the data stored. If this function is called with
  68950. ** parameters that attempt to write past the end of the existing data,
  68951. ** no modifications are made and SQLITE_CORRUPT is returned.
  68952. */
  68953. SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
  68954. int rc;
  68955. assert( cursorOwnsBtShared(pCsr) );
  68956. assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
  68957. assert( pCsr->curFlags & BTCF_Incrblob );
  68958. rc = restoreCursorPosition(pCsr);
  68959. if( rc!=SQLITE_OK ){
  68960. return rc;
  68961. }
  68962. assert( pCsr->eState!=CURSOR_REQUIRESEEK );
  68963. if( pCsr->eState!=CURSOR_VALID ){
  68964. return SQLITE_ABORT;
  68965. }
  68966. /* Save the positions of all other cursors open on this table. This is
  68967. ** required in case any of them are holding references to an xFetch
  68968. ** version of the b-tree page modified by the accessPayload call below.
  68969. **
  68970. ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()
  68971. ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
  68972. ** saveAllCursors can only return SQLITE_OK.
  68973. */
  68974. VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
  68975. assert( rc==SQLITE_OK );
  68976. /* Check some assumptions:
  68977. ** (a) the cursor is open for writing,
  68978. ** (b) there is a read/write transaction open,
  68979. ** (c) the connection holds a write-lock on the table (if required),
  68980. ** (d) there are no conflicting read-locks, and
  68981. ** (e) the cursor points at a valid row of an intKey table.
  68982. */
  68983. if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
  68984. return SQLITE_READONLY;
  68985. }
  68986. assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
  68987. && pCsr->pBt->inTransaction==TRANS_WRITE );
  68988. assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
  68989. assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
  68990. assert( pCsr->pPage->intKey );
  68991. return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
  68992. }
  68993. /*
  68994. ** Mark this cursor as an incremental blob cursor.
  68995. */
  68996. SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
  68997. pCur->curFlags |= BTCF_Incrblob;
  68998. pCur->pBtree->hasIncrblobCur = 1;
  68999. }
  69000. #endif
  69001. /*
  69002. ** Set both the "read version" (single byte at byte offset 18) and
  69003. ** "write version" (single byte at byte offset 19) fields in the database
  69004. ** header to iVersion.
  69005. */
  69006. SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
  69007. BtShared *pBt = pBtree->pBt;
  69008. int rc; /* Return code */
  69009. assert( iVersion==1 || iVersion==2 );
  69010. /* If setting the version fields to 1, do not automatically open the
  69011. ** WAL connection, even if the version fields are currently set to 2.
  69012. */
  69013. pBt->btsFlags &= ~BTS_NO_WAL;
  69014. if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
  69015. rc = sqlite3BtreeBeginTrans(pBtree, 0, 0);
  69016. if( rc==SQLITE_OK ){
  69017. u8 *aData = pBt->pPage1->aData;
  69018. if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
  69019. rc = sqlite3BtreeBeginTrans(pBtree, 2, 0);
  69020. if( rc==SQLITE_OK ){
  69021. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  69022. if( rc==SQLITE_OK ){
  69023. aData[18] = (u8)iVersion;
  69024. aData[19] = (u8)iVersion;
  69025. }
  69026. }
  69027. }
  69028. }
  69029. pBt->btsFlags &= ~BTS_NO_WAL;
  69030. return rc;
  69031. }
  69032. /*
  69033. ** Return true if the cursor has a hint specified. This routine is
  69034. ** only used from within assert() statements
  69035. */
  69036. SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){
  69037. return (pCsr->hints & mask)!=0;
  69038. }
  69039. /*
  69040. ** Return true if the given Btree is read-only.
  69041. */
  69042. SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *p){
  69043. return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
  69044. }
  69045. /*
  69046. ** Return the size of the header added to each page by this module.
  69047. */
  69048. SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage)); }
  69049. #if !defined(SQLITE_OMIT_SHARED_CACHE)
  69050. /*
  69051. ** Return true if the Btree passed as the only argument is sharable.
  69052. */
  69053. SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
  69054. return p->sharable;
  69055. }
  69056. /*
  69057. ** Return the number of connections to the BtShared object accessed by
  69058. ** the Btree handle passed as the only argument. For private caches
  69059. ** this is always 1. For shared caches it may be 1 or greater.
  69060. */
  69061. SQLITE_PRIVATE int sqlite3BtreeConnectionCount(Btree *p){
  69062. testcase( p->sharable );
  69063. return p->pBt->nRef;
  69064. }
  69065. #endif
  69066. /************** End of btree.c ***********************************************/
  69067. /************** Begin file backup.c ******************************************/
  69068. /*
  69069. ** 2009 January 28
  69070. **
  69071. ** The author disclaims copyright to this source code. In place of
  69072. ** a legal notice, here is a blessing:
  69073. **
  69074. ** May you do good and not evil.
  69075. ** May you find forgiveness for yourself and forgive others.
  69076. ** May you share freely, never taking more than you give.
  69077. **
  69078. *************************************************************************
  69079. ** This file contains the implementation of the sqlite3_backup_XXX()
  69080. ** API functions and the related features.
  69081. */
  69082. /* #include "sqliteInt.h" */
  69083. /* #include "btreeInt.h" */
  69084. /*
  69085. ** Structure allocated for each backup operation.
  69086. */
  69087. struct sqlite3_backup {
  69088. sqlite3* pDestDb; /* Destination database handle */
  69089. Btree *pDest; /* Destination b-tree file */
  69090. u32 iDestSchema; /* Original schema cookie in destination */
  69091. int bDestLocked; /* True once a write-transaction is open on pDest */
  69092. Pgno iNext; /* Page number of the next source page to copy */
  69093. sqlite3* pSrcDb; /* Source database handle */
  69094. Btree *pSrc; /* Source b-tree file */
  69095. int rc; /* Backup process error code */
  69096. /* These two variables are set by every call to backup_step(). They are
  69097. ** read by calls to backup_remaining() and backup_pagecount().
  69098. */
  69099. Pgno nRemaining; /* Number of pages left to copy */
  69100. Pgno nPagecount; /* Total number of pages to copy */
  69101. int isAttached; /* True once backup has been registered with pager */
  69102. sqlite3_backup *pNext; /* Next backup associated with source pager */
  69103. };
  69104. /*
  69105. ** THREAD SAFETY NOTES:
  69106. **
  69107. ** Once it has been created using backup_init(), a single sqlite3_backup
  69108. ** structure may be accessed via two groups of thread-safe entry points:
  69109. **
  69110. ** * Via the sqlite3_backup_XXX() API function backup_step() and
  69111. ** backup_finish(). Both these functions obtain the source database
  69112. ** handle mutex and the mutex associated with the source BtShared
  69113. ** structure, in that order.
  69114. **
  69115. ** * Via the BackupUpdate() and BackupRestart() functions, which are
  69116. ** invoked by the pager layer to report various state changes in
  69117. ** the page cache associated with the source database. The mutex
  69118. ** associated with the source database BtShared structure will always
  69119. ** be held when either of these functions are invoked.
  69120. **
  69121. ** The other sqlite3_backup_XXX() API functions, backup_remaining() and
  69122. ** backup_pagecount() are not thread-safe functions. If they are called
  69123. ** while some other thread is calling backup_step() or backup_finish(),
  69124. ** the values returned may be invalid. There is no way for a call to
  69125. ** BackupUpdate() or BackupRestart() to interfere with backup_remaining()
  69126. ** or backup_pagecount().
  69127. **
  69128. ** Depending on the SQLite configuration, the database handles and/or
  69129. ** the Btree objects may have their own mutexes that require locking.
  69130. ** Non-sharable Btrees (in-memory databases for example), do not have
  69131. ** associated mutexes.
  69132. */
  69133. /*
  69134. ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
  69135. ** in connection handle pDb. If such a database cannot be found, return
  69136. ** a NULL pointer and write an error message to pErrorDb.
  69137. **
  69138. ** If the "temp" database is requested, it may need to be opened by this
  69139. ** function. If an error occurs while doing so, return 0 and write an
  69140. ** error message to pErrorDb.
  69141. */
  69142. static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
  69143. int i = sqlite3FindDbName(pDb, zDb);
  69144. if( i==1 ){
  69145. Parse sParse;
  69146. int rc = 0;
  69147. memset(&sParse, 0, sizeof(sParse));
  69148. sParse.db = pDb;
  69149. if( sqlite3OpenTempDatabase(&sParse) ){
  69150. sqlite3ErrorWithMsg(pErrorDb, sParse.rc, "%s", sParse.zErrMsg);
  69151. rc = SQLITE_ERROR;
  69152. }
  69153. sqlite3DbFree(pErrorDb, sParse.zErrMsg);
  69154. sqlite3ParserReset(&sParse);
  69155. if( rc ){
  69156. return 0;
  69157. }
  69158. }
  69159. if( i<0 ){
  69160. sqlite3ErrorWithMsg(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
  69161. return 0;
  69162. }
  69163. return pDb->aDb[i].pBt;
  69164. }
  69165. /*
  69166. ** Attempt to set the page size of the destination to match the page size
  69167. ** of the source.
  69168. */
  69169. static int setDestPgsz(sqlite3_backup *p){
  69170. int rc;
  69171. rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
  69172. return rc;
  69173. }
  69174. /*
  69175. ** Check that there is no open read-transaction on the b-tree passed as the
  69176. ** second argument. If there is not, return SQLITE_OK. Otherwise, if there
  69177. ** is an open read-transaction, return SQLITE_ERROR and leave an error
  69178. ** message in database handle db.
  69179. */
  69180. static int checkReadTransaction(sqlite3 *db, Btree *p){
  69181. if( sqlite3BtreeIsInReadTrans(p) ){
  69182. sqlite3ErrorWithMsg(db, SQLITE_ERROR, "destination database is in use");
  69183. return SQLITE_ERROR;
  69184. }
  69185. return SQLITE_OK;
  69186. }
  69187. /*
  69188. ** Create an sqlite3_backup process to copy the contents of zSrcDb from
  69189. ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
  69190. ** a pointer to the new sqlite3_backup object.
  69191. **
  69192. ** If an error occurs, NULL is returned and an error code and error message
  69193. ** stored in database handle pDestDb.
  69194. */
  69195. SQLITE_API sqlite3_backup *sqlite3_backup_init(
  69196. sqlite3* pDestDb, /* Database to write to */
  69197. const char *zDestDb, /* Name of database within pDestDb */
  69198. sqlite3* pSrcDb, /* Database connection to read from */
  69199. const char *zSrcDb /* Name of database within pSrcDb */
  69200. ){
  69201. sqlite3_backup *p; /* Value to return */
  69202. #ifdef SQLITE_ENABLE_API_ARMOR
  69203. if( !sqlite3SafetyCheckOk(pSrcDb)||!sqlite3SafetyCheckOk(pDestDb) ){
  69204. (void)SQLITE_MISUSE_BKPT;
  69205. return 0;
  69206. }
  69207. #endif
  69208. /* Lock the source database handle. The destination database
  69209. ** handle is not locked in this routine, but it is locked in
  69210. ** sqlite3_backup_step(). The user is required to ensure that no
  69211. ** other thread accesses the destination handle for the duration
  69212. ** of the backup operation. Any attempt to use the destination
  69213. ** database connection while a backup is in progress may cause
  69214. ** a malfunction or a deadlock.
  69215. */
  69216. sqlite3_mutex_enter(pSrcDb->mutex);
  69217. sqlite3_mutex_enter(pDestDb->mutex);
  69218. if( pSrcDb==pDestDb ){
  69219. sqlite3ErrorWithMsg(
  69220. pDestDb, SQLITE_ERROR, "source and destination must be distinct"
  69221. );
  69222. p = 0;
  69223. }else {
  69224. /* Allocate space for a new sqlite3_backup object...
  69225. ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
  69226. ** call to sqlite3_backup_init() and is destroyed by a call to
  69227. ** sqlite3_backup_finish(). */
  69228. p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));
  69229. if( !p ){
  69230. sqlite3Error(pDestDb, SQLITE_NOMEM_BKPT);
  69231. }
  69232. }
  69233. /* If the allocation succeeded, populate the new object. */
  69234. if( p ){
  69235. p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
  69236. p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
  69237. p->pDestDb = pDestDb;
  69238. p->pSrcDb = pSrcDb;
  69239. p->iNext = 1;
  69240. p->isAttached = 0;
  69241. if( 0==p->pSrc || 0==p->pDest
  69242. || checkReadTransaction(pDestDb, p->pDest)!=SQLITE_OK
  69243. ){
  69244. /* One (or both) of the named databases did not exist or an OOM
  69245. ** error was hit. Or there is a transaction open on the destination
  69246. ** database. The error has already been written into the pDestDb
  69247. ** handle. All that is left to do here is free the sqlite3_backup
  69248. ** structure. */
  69249. sqlite3_free(p);
  69250. p = 0;
  69251. }
  69252. }
  69253. if( p ){
  69254. p->pSrc->nBackup++;
  69255. }
  69256. sqlite3_mutex_leave(pDestDb->mutex);
  69257. sqlite3_mutex_leave(pSrcDb->mutex);
  69258. return p;
  69259. }
  69260. /*
  69261. ** Argument rc is an SQLite error code. Return true if this error is
  69262. ** considered fatal if encountered during a backup operation. All errors
  69263. ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
  69264. */
  69265. static int isFatalError(int rc){
  69266. return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
  69267. }
  69268. /*
  69269. ** Parameter zSrcData points to a buffer containing the data for
  69270. ** page iSrcPg from the source database. Copy this data into the
  69271. ** destination database.
  69272. */
  69273. static int backupOnePage(
  69274. sqlite3_backup *p, /* Backup handle */
  69275. Pgno iSrcPg, /* Source database page to backup */
  69276. const u8 *zSrcData, /* Source database page data */
  69277. int bUpdate /* True for an update, false otherwise */
  69278. ){
  69279. Pager * const pDestPager = sqlite3BtreePager(p->pDest);
  69280. const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
  69281. int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
  69282. const int nCopy = MIN(nSrcPgsz, nDestPgsz);
  69283. const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
  69284. #ifdef SQLITE_HAS_CODEC
  69285. /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is
  69286. ** guaranteed that the shared-mutex is held by this thread, handle
  69287. ** p->pSrc may not actually be the owner. */
  69288. int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc);
  69289. int nDestReserve = sqlite3BtreeGetOptimalReserve(p->pDest);
  69290. #endif
  69291. int rc = SQLITE_OK;
  69292. i64 iOff;
  69293. assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
  69294. assert( p->bDestLocked );
  69295. assert( !isFatalError(p->rc) );
  69296. assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
  69297. assert( zSrcData );
  69298. /* Catch the case where the destination is an in-memory database and the
  69299. ** page sizes of the source and destination differ.
  69300. */
  69301. if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
  69302. rc = SQLITE_READONLY;
  69303. }
  69304. #ifdef SQLITE_HAS_CODEC
  69305. /* Backup is not possible if the page size of the destination is changing
  69306. ** and a codec is in use.
  69307. */
  69308. if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
  69309. rc = SQLITE_READONLY;
  69310. }
  69311. /* Backup is not possible if the number of bytes of reserve space differ
  69312. ** between source and destination. If there is a difference, try to
  69313. ** fix the destination to agree with the source. If that is not possible,
  69314. ** then the backup cannot proceed.
  69315. */
  69316. if( nSrcReserve!=nDestReserve ){
  69317. u32 newPgsz = nSrcPgsz;
  69318. rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
  69319. if( rc==SQLITE_OK && newPgsz!=(u32)nSrcPgsz ) rc = SQLITE_READONLY;
  69320. }
  69321. #endif
  69322. /* This loop runs once for each destination page spanned by the source
  69323. ** page. For each iteration, variable iOff is set to the byte offset
  69324. ** of the destination page.
  69325. */
  69326. for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
  69327. DbPage *pDestPg = 0;
  69328. Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
  69329. if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
  69330. if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg, 0))
  69331. && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
  69332. ){
  69333. const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
  69334. u8 *zDestData = sqlite3PagerGetData(pDestPg);
  69335. u8 *zOut = &zDestData[iOff%nDestPgsz];
  69336. /* Copy the data from the source page into the destination page.
  69337. ** Then clear the Btree layer MemPage.isInit flag. Both this module
  69338. ** and the pager code use this trick (clearing the first byte
  69339. ** of the page 'extra' space to invalidate the Btree layers
  69340. ** cached parse of the page). MemPage.isInit is marked
  69341. ** "MUST BE FIRST" for this purpose.
  69342. */
  69343. memcpy(zOut, zIn, nCopy);
  69344. ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
  69345. if( iOff==0 && bUpdate==0 ){
  69346. sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
  69347. }
  69348. }
  69349. sqlite3PagerUnref(pDestPg);
  69350. }
  69351. return rc;
  69352. }
  69353. /*
  69354. ** If pFile is currently larger than iSize bytes, then truncate it to
  69355. ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
  69356. ** this function is a no-op.
  69357. **
  69358. ** Return SQLITE_OK if everything is successful, or an SQLite error
  69359. ** code if an error occurs.
  69360. */
  69361. static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
  69362. i64 iCurrent;
  69363. int rc = sqlite3OsFileSize(pFile, &iCurrent);
  69364. if( rc==SQLITE_OK && iCurrent>iSize ){
  69365. rc = sqlite3OsTruncate(pFile, iSize);
  69366. }
  69367. return rc;
  69368. }
  69369. /*
  69370. ** Register this backup object with the associated source pager for
  69371. ** callbacks when pages are changed or the cache invalidated.
  69372. */
  69373. static void attachBackupObject(sqlite3_backup *p){
  69374. sqlite3_backup **pp;
  69375. assert( sqlite3BtreeHoldsMutex(p->pSrc) );
  69376. pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
  69377. p->pNext = *pp;
  69378. *pp = p;
  69379. p->isAttached = 1;
  69380. }
  69381. /*
  69382. ** Copy nPage pages from the source b-tree to the destination.
  69383. */
  69384. SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
  69385. int rc;
  69386. int destMode; /* Destination journal mode */
  69387. int pgszSrc = 0; /* Source page size */
  69388. int pgszDest = 0; /* Destination page size */
  69389. #ifdef SQLITE_ENABLE_API_ARMOR
  69390. if( p==0 ) return SQLITE_MISUSE_BKPT;
  69391. #endif
  69392. sqlite3_mutex_enter(p->pSrcDb->mutex);
  69393. sqlite3BtreeEnter(p->pSrc);
  69394. if( p->pDestDb ){
  69395. sqlite3_mutex_enter(p->pDestDb->mutex);
  69396. }
  69397. rc = p->rc;
  69398. if( !isFatalError(rc) ){
  69399. Pager * const pSrcPager = sqlite3BtreePager(p->pSrc); /* Source pager */
  69400. Pager * const pDestPager = sqlite3BtreePager(p->pDest); /* Dest pager */
  69401. int ii; /* Iterator variable */
  69402. int nSrcPage = -1; /* Size of source db in pages */
  69403. int bCloseTrans = 0; /* True if src db requires unlocking */
  69404. /* If the source pager is currently in a write-transaction, return
  69405. ** SQLITE_BUSY immediately.
  69406. */
  69407. if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
  69408. rc = SQLITE_BUSY;
  69409. }else{
  69410. rc = SQLITE_OK;
  69411. }
  69412. /* If there is no open read-transaction on the source database, open
  69413. ** one now. If a transaction is opened here, then it will be closed
  69414. ** before this function exits.
  69415. */
  69416. if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
  69417. rc = sqlite3BtreeBeginTrans(p->pSrc, 0, 0);
  69418. bCloseTrans = 1;
  69419. }
  69420. /* If the destination database has not yet been locked (i.e. if this
  69421. ** is the first call to backup_step() for the current backup operation),
  69422. ** try to set its page size to the same as the source database. This
  69423. ** is especially important on ZipVFS systems, as in that case it is
  69424. ** not possible to create a database file that uses one page size by
  69425. ** writing to it with another. */
  69426. if( p->bDestLocked==0 && rc==SQLITE_OK && setDestPgsz(p)==SQLITE_NOMEM ){
  69427. rc = SQLITE_NOMEM;
  69428. }
  69429. /* Lock the destination database, if it is not locked already. */
  69430. if( SQLITE_OK==rc && p->bDestLocked==0
  69431. && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2,
  69432. (int*)&p->iDestSchema))
  69433. ){
  69434. p->bDestLocked = 1;
  69435. }
  69436. /* Do not allow backup if the destination database is in WAL mode
  69437. ** and the page sizes are different between source and destination */
  69438. pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
  69439. pgszDest = sqlite3BtreeGetPageSize(p->pDest);
  69440. destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
  69441. if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
  69442. rc = SQLITE_READONLY;
  69443. }
  69444. /* Now that there is a read-lock on the source database, query the
  69445. ** source pager for the number of pages in the database.
  69446. */
  69447. nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
  69448. assert( nSrcPage>=0 );
  69449. for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
  69450. const Pgno iSrcPg = p->iNext; /* Source page number */
  69451. if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
  69452. DbPage *pSrcPg; /* Source page object */
  69453. rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg,PAGER_GET_READONLY);
  69454. if( rc==SQLITE_OK ){
  69455. rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0);
  69456. sqlite3PagerUnref(pSrcPg);
  69457. }
  69458. }
  69459. p->iNext++;
  69460. }
  69461. if( rc==SQLITE_OK ){
  69462. p->nPagecount = nSrcPage;
  69463. p->nRemaining = nSrcPage+1-p->iNext;
  69464. if( p->iNext>(Pgno)nSrcPage ){
  69465. rc = SQLITE_DONE;
  69466. }else if( !p->isAttached ){
  69467. attachBackupObject(p);
  69468. }
  69469. }
  69470. /* Update the schema version field in the destination database. This
  69471. ** is to make sure that the schema-version really does change in
  69472. ** the case where the source and destination databases have the
  69473. ** same schema version.
  69474. */
  69475. if( rc==SQLITE_DONE ){
  69476. if( nSrcPage==0 ){
  69477. rc = sqlite3BtreeNewDb(p->pDest);
  69478. nSrcPage = 1;
  69479. }
  69480. if( rc==SQLITE_OK || rc==SQLITE_DONE ){
  69481. rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
  69482. }
  69483. if( rc==SQLITE_OK ){
  69484. if( p->pDestDb ){
  69485. sqlite3ResetAllSchemasOfConnection(p->pDestDb);
  69486. }
  69487. if( destMode==PAGER_JOURNALMODE_WAL ){
  69488. rc = sqlite3BtreeSetVersion(p->pDest, 2);
  69489. }
  69490. }
  69491. if( rc==SQLITE_OK ){
  69492. int nDestTruncate;
  69493. /* Set nDestTruncate to the final number of pages in the destination
  69494. ** database. The complication here is that the destination page
  69495. ** size may be different to the source page size.
  69496. **
  69497. ** If the source page size is smaller than the destination page size,
  69498. ** round up. In this case the call to sqlite3OsTruncate() below will
  69499. ** fix the size of the file. However it is important to call
  69500. ** sqlite3PagerTruncateImage() here so that any pages in the
  69501. ** destination file that lie beyond the nDestTruncate page mark are
  69502. ** journalled by PagerCommitPhaseOne() before they are destroyed
  69503. ** by the file truncation.
  69504. */
  69505. assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
  69506. assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
  69507. if( pgszSrc<pgszDest ){
  69508. int ratio = pgszDest/pgszSrc;
  69509. nDestTruncate = (nSrcPage+ratio-1)/ratio;
  69510. if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
  69511. nDestTruncate--;
  69512. }
  69513. }else{
  69514. nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
  69515. }
  69516. assert( nDestTruncate>0 );
  69517. if( pgszSrc<pgszDest ){
  69518. /* If the source page-size is smaller than the destination page-size,
  69519. ** two extra things may need to happen:
  69520. **
  69521. ** * The destination may need to be truncated, and
  69522. **
  69523. ** * Data stored on the pages immediately following the
  69524. ** pending-byte page in the source database may need to be
  69525. ** copied into the destination database.
  69526. */
  69527. const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
  69528. sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
  69529. Pgno iPg;
  69530. int nDstPage;
  69531. i64 iOff;
  69532. i64 iEnd;
  69533. assert( pFile );
  69534. assert( nDestTruncate==0
  69535. || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
  69536. nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
  69537. && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
  69538. ));
  69539. /* This block ensures that all data required to recreate the original
  69540. ** database has been stored in the journal for pDestPager and the
  69541. ** journal synced to disk. So at this point we may safely modify
  69542. ** the database file in any way, knowing that if a power failure
  69543. ** occurs, the original database will be reconstructed from the
  69544. ** journal file. */
  69545. sqlite3PagerPagecount(pDestPager, &nDstPage);
  69546. for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){
  69547. if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){
  69548. DbPage *pPg;
  69549. rc = sqlite3PagerGet(pDestPager, iPg, &pPg, 0);
  69550. if( rc==SQLITE_OK ){
  69551. rc = sqlite3PagerWrite(pPg);
  69552. sqlite3PagerUnref(pPg);
  69553. }
  69554. }
  69555. }
  69556. if( rc==SQLITE_OK ){
  69557. rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
  69558. }
  69559. /* Write the extra pages and truncate the database file as required */
  69560. iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
  69561. for(
  69562. iOff=PENDING_BYTE+pgszSrc;
  69563. rc==SQLITE_OK && iOff<iEnd;
  69564. iOff+=pgszSrc
  69565. ){
  69566. PgHdr *pSrcPg = 0;
  69567. const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
  69568. rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg, 0);
  69569. if( rc==SQLITE_OK ){
  69570. u8 *zData = sqlite3PagerGetData(pSrcPg);
  69571. rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
  69572. }
  69573. sqlite3PagerUnref(pSrcPg);
  69574. }
  69575. if( rc==SQLITE_OK ){
  69576. rc = backupTruncateFile(pFile, iSize);
  69577. }
  69578. /* Sync the database file to disk. */
  69579. if( rc==SQLITE_OK ){
  69580. rc = sqlite3PagerSync(pDestPager, 0);
  69581. }
  69582. }else{
  69583. sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
  69584. rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
  69585. }
  69586. /* Finish committing the transaction to the destination database. */
  69587. if( SQLITE_OK==rc
  69588. && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
  69589. ){
  69590. rc = SQLITE_DONE;
  69591. }
  69592. }
  69593. }
  69594. /* If bCloseTrans is true, then this function opened a read transaction
  69595. ** on the source database. Close the read transaction here. There is
  69596. ** no need to check the return values of the btree methods here, as
  69597. ** "committing" a read-only transaction cannot fail.
  69598. */
  69599. if( bCloseTrans ){
  69600. TESTONLY( int rc2 );
  69601. TESTONLY( rc2 = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
  69602. TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
  69603. assert( rc2==SQLITE_OK );
  69604. }
  69605. if( rc==SQLITE_IOERR_NOMEM ){
  69606. rc = SQLITE_NOMEM_BKPT;
  69607. }
  69608. p->rc = rc;
  69609. }
  69610. if( p->pDestDb ){
  69611. sqlite3_mutex_leave(p->pDestDb->mutex);
  69612. }
  69613. sqlite3BtreeLeave(p->pSrc);
  69614. sqlite3_mutex_leave(p->pSrcDb->mutex);
  69615. return rc;
  69616. }
  69617. /*
  69618. ** Release all resources associated with an sqlite3_backup* handle.
  69619. */
  69620. SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
  69621. sqlite3_backup **pp; /* Ptr to head of pagers backup list */
  69622. sqlite3 *pSrcDb; /* Source database connection */
  69623. int rc; /* Value to return */
  69624. /* Enter the mutexes */
  69625. if( p==0 ) return SQLITE_OK;
  69626. pSrcDb = p->pSrcDb;
  69627. sqlite3_mutex_enter(pSrcDb->mutex);
  69628. sqlite3BtreeEnter(p->pSrc);
  69629. if( p->pDestDb ){
  69630. sqlite3_mutex_enter(p->pDestDb->mutex);
  69631. }
  69632. /* Detach this backup from the source pager. */
  69633. if( p->pDestDb ){
  69634. p->pSrc->nBackup--;
  69635. }
  69636. if( p->isAttached ){
  69637. pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
  69638. while( *pp!=p ){
  69639. pp = &(*pp)->pNext;
  69640. }
  69641. *pp = p->pNext;
  69642. }
  69643. /* If a transaction is still open on the Btree, roll it back. */
  69644. sqlite3BtreeRollback(p->pDest, SQLITE_OK, 0);
  69645. /* Set the error code of the destination database handle. */
  69646. rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
  69647. if( p->pDestDb ){
  69648. sqlite3Error(p->pDestDb, rc);
  69649. /* Exit the mutexes and free the backup context structure. */
  69650. sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
  69651. }
  69652. sqlite3BtreeLeave(p->pSrc);
  69653. if( p->pDestDb ){
  69654. /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
  69655. ** call to sqlite3_backup_init() and is destroyed by a call to
  69656. ** sqlite3_backup_finish(). */
  69657. sqlite3_free(p);
  69658. }
  69659. sqlite3LeaveMutexAndCloseZombie(pSrcDb);
  69660. return rc;
  69661. }
  69662. /*
  69663. ** Return the number of pages still to be backed up as of the most recent
  69664. ** call to sqlite3_backup_step().
  69665. */
  69666. SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
  69667. #ifdef SQLITE_ENABLE_API_ARMOR
  69668. if( p==0 ){
  69669. (void)SQLITE_MISUSE_BKPT;
  69670. return 0;
  69671. }
  69672. #endif
  69673. return p->nRemaining;
  69674. }
  69675. /*
  69676. ** Return the total number of pages in the source database as of the most
  69677. ** recent call to sqlite3_backup_step().
  69678. */
  69679. SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
  69680. #ifdef SQLITE_ENABLE_API_ARMOR
  69681. if( p==0 ){
  69682. (void)SQLITE_MISUSE_BKPT;
  69683. return 0;
  69684. }
  69685. #endif
  69686. return p->nPagecount;
  69687. }
  69688. /*
  69689. ** This function is called after the contents of page iPage of the
  69690. ** source database have been modified. If page iPage has already been
  69691. ** copied into the destination database, then the data written to the
  69692. ** destination is now invalidated. The destination copy of iPage needs
  69693. ** to be updated with the new data before the backup operation is
  69694. ** complete.
  69695. **
  69696. ** It is assumed that the mutex associated with the BtShared object
  69697. ** corresponding to the source database is held when this function is
  69698. ** called.
  69699. */
  69700. static SQLITE_NOINLINE void backupUpdate(
  69701. sqlite3_backup *p,
  69702. Pgno iPage,
  69703. const u8 *aData
  69704. ){
  69705. assert( p!=0 );
  69706. do{
  69707. assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
  69708. if( !isFatalError(p->rc) && iPage<p->iNext ){
  69709. /* The backup process p has already copied page iPage. But now it
  69710. ** has been modified by a transaction on the source pager. Copy
  69711. ** the new data into the backup.
  69712. */
  69713. int rc;
  69714. assert( p->pDestDb );
  69715. sqlite3_mutex_enter(p->pDestDb->mutex);
  69716. rc = backupOnePage(p, iPage, aData, 1);
  69717. sqlite3_mutex_leave(p->pDestDb->mutex);
  69718. assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
  69719. if( rc!=SQLITE_OK ){
  69720. p->rc = rc;
  69721. }
  69722. }
  69723. }while( (p = p->pNext)!=0 );
  69724. }
  69725. SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
  69726. if( pBackup ) backupUpdate(pBackup, iPage, aData);
  69727. }
  69728. /*
  69729. ** Restart the backup process. This is called when the pager layer
  69730. ** detects that the database has been modified by an external database
  69731. ** connection. In this case there is no way of knowing which of the
  69732. ** pages that have been copied into the destination database are still
  69733. ** valid and which are not, so the entire process needs to be restarted.
  69734. **
  69735. ** It is assumed that the mutex associated with the BtShared object
  69736. ** corresponding to the source database is held when this function is
  69737. ** called.
  69738. */
  69739. SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
  69740. sqlite3_backup *p; /* Iterator variable */
  69741. for(p=pBackup; p; p=p->pNext){
  69742. assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
  69743. p->iNext = 1;
  69744. }
  69745. }
  69746. #ifndef SQLITE_OMIT_VACUUM
  69747. /*
  69748. ** Copy the complete content of pBtFrom into pBtTo. A transaction
  69749. ** must be active for both files.
  69750. **
  69751. ** The size of file pTo may be reduced by this operation. If anything
  69752. ** goes wrong, the transaction on pTo is rolled back. If successful, the
  69753. ** transaction is committed before returning.
  69754. */
  69755. SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
  69756. int rc;
  69757. sqlite3_file *pFd; /* File descriptor for database pTo */
  69758. sqlite3_backup b;
  69759. sqlite3BtreeEnter(pTo);
  69760. sqlite3BtreeEnter(pFrom);
  69761. assert( sqlite3BtreeIsInTrans(pTo) );
  69762. pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
  69763. if( pFd->pMethods ){
  69764. i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
  69765. rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
  69766. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  69767. if( rc ) goto copy_finished;
  69768. }
  69769. /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
  69770. ** to 0. This is used by the implementations of sqlite3_backup_step()
  69771. ** and sqlite3_backup_finish() to detect that they are being called
  69772. ** from this function, not directly by the user.
  69773. */
  69774. memset(&b, 0, sizeof(b));
  69775. b.pSrcDb = pFrom->db;
  69776. b.pSrc = pFrom;
  69777. b.pDest = pTo;
  69778. b.iNext = 1;
  69779. #ifdef SQLITE_HAS_CODEC
  69780. sqlite3PagerAlignReserve(sqlite3BtreePager(pTo), sqlite3BtreePager(pFrom));
  69781. #endif
  69782. /* 0x7FFFFFFF is the hard limit for the number of pages in a database
  69783. ** file. By passing this as the number of pages to copy to
  69784. ** sqlite3_backup_step(), we can guarantee that the copy finishes
  69785. ** within a single call (unless an error occurs). The assert() statement
  69786. ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
  69787. ** or an error code. */
  69788. sqlite3_backup_step(&b, 0x7FFFFFFF);
  69789. assert( b.rc!=SQLITE_OK );
  69790. rc = sqlite3_backup_finish(&b);
  69791. if( rc==SQLITE_OK ){
  69792. pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
  69793. }else{
  69794. sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
  69795. }
  69796. assert( sqlite3BtreeIsInTrans(pTo)==0 );
  69797. copy_finished:
  69798. sqlite3BtreeLeave(pFrom);
  69799. sqlite3BtreeLeave(pTo);
  69800. return rc;
  69801. }
  69802. #endif /* SQLITE_OMIT_VACUUM */
  69803. /************** End of backup.c **********************************************/
  69804. /************** Begin file vdbemem.c *****************************************/
  69805. /*
  69806. ** 2004 May 26
  69807. **
  69808. ** The author disclaims copyright to this source code. In place of
  69809. ** a legal notice, here is a blessing:
  69810. **
  69811. ** May you do good and not evil.
  69812. ** May you find forgiveness for yourself and forgive others.
  69813. ** May you share freely, never taking more than you give.
  69814. **
  69815. *************************************************************************
  69816. **
  69817. ** This file contains code use to manipulate "Mem" structure. A "Mem"
  69818. ** stores a single value in the VDBE. Mem is an opaque structure visible
  69819. ** only within the VDBE. Interface routines refer to a Mem using the
  69820. ** name sqlite_value
  69821. */
  69822. /* #include "sqliteInt.h" */
  69823. /* #include "vdbeInt.h" */
  69824. /* True if X is a power of two. 0 is considered a power of two here.
  69825. ** In other words, return true if X has at most one bit set.
  69826. */
  69827. #define ISPOWEROF2(X) (((X)&((X)-1))==0)
  69828. #ifdef SQLITE_DEBUG
  69829. /*
  69830. ** Check invariants on a Mem object.
  69831. **
  69832. ** This routine is intended for use inside of assert() statements, like
  69833. ** this: assert( sqlite3VdbeCheckMemInvariants(pMem) );
  69834. */
  69835. SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem *p){
  69836. /* If MEM_Dyn is set then Mem.xDel!=0.
  69837. ** Mem.xDel might not be initialized if MEM_Dyn is clear.
  69838. */
  69839. assert( (p->flags & MEM_Dyn)==0 || p->xDel!=0 );
  69840. /* MEM_Dyn may only be set if Mem.szMalloc==0. In this way we
  69841. ** ensure that if Mem.szMalloc>0 then it is safe to do
  69842. ** Mem.z = Mem.zMalloc without having to check Mem.flags&MEM_Dyn.
  69843. ** That saves a few cycles in inner loops. */
  69844. assert( (p->flags & MEM_Dyn)==0 || p->szMalloc==0 );
  69845. /* Cannot have more than one of MEM_Int, MEM_Real, or MEM_IntReal */
  69846. assert( ISPOWEROF2(p->flags & (MEM_Int|MEM_Real|MEM_IntReal)) );
  69847. if( p->flags & MEM_Null ){
  69848. /* Cannot be both MEM_Null and some other type */
  69849. assert( (p->flags & (MEM_Int|MEM_Real|MEM_Str|MEM_Blob|MEM_Agg))==0 );
  69850. /* If MEM_Null is set, then either the value is a pure NULL (the usual
  69851. ** case) or it is a pointer set using sqlite3_bind_pointer() or
  69852. ** sqlite3_result_pointer(). If a pointer, then MEM_Term must also be
  69853. ** set.
  69854. */
  69855. if( (p->flags & (MEM_Term|MEM_Subtype))==(MEM_Term|MEM_Subtype) ){
  69856. /* This is a pointer type. There may be a flag to indicate what to
  69857. ** do with the pointer. */
  69858. assert( ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
  69859. ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
  69860. ((p->flags&MEM_Static)!=0 ? 1 : 0) <= 1 );
  69861. /* No other bits set */
  69862. assert( (p->flags & ~(MEM_Null|MEM_Term|MEM_Subtype|MEM_FromBind
  69863. |MEM_Dyn|MEM_Ephem|MEM_Static))==0 );
  69864. }else{
  69865. /* A pure NULL might have other flags, such as MEM_Static, MEM_Dyn,
  69866. ** MEM_Ephem, MEM_Cleared, or MEM_Subtype */
  69867. }
  69868. }else{
  69869. /* The MEM_Cleared bit is only allowed on NULLs */
  69870. assert( (p->flags & MEM_Cleared)==0 );
  69871. }
  69872. /* The szMalloc field holds the correct memory allocation size */
  69873. assert( p->szMalloc==0
  69874. || p->szMalloc==sqlite3DbMallocSize(p->db,p->zMalloc) );
  69875. /* If p holds a string or blob, the Mem.z must point to exactly
  69876. ** one of the following:
  69877. **
  69878. ** (1) Memory in Mem.zMalloc and managed by the Mem object
  69879. ** (2) Memory to be freed using Mem.xDel
  69880. ** (3) An ephemeral string or blob
  69881. ** (4) A static string or blob
  69882. */
  69883. if( (p->flags & (MEM_Str|MEM_Blob)) && p->n>0 ){
  69884. assert(
  69885. ((p->szMalloc>0 && p->z==p->zMalloc)? 1 : 0) +
  69886. ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
  69887. ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
  69888. ((p->flags&MEM_Static)!=0 ? 1 : 0) == 1
  69889. );
  69890. }
  69891. return 1;
  69892. }
  69893. #endif
  69894. /*
  69895. ** Render a Mem object which is one of MEM_Int, MEM_Real, or MEM_IntReal
  69896. ** into a buffer.
  69897. */
  69898. static void vdbeMemRenderNum(int sz, char *zBuf, Mem *p){
  69899. StrAccum acc;
  69900. assert( p->flags & (MEM_Int|MEM_Real|MEM_IntReal) );
  69901. sqlite3StrAccumInit(&acc, 0, zBuf, sz, 0);
  69902. if( p->flags & MEM_Int ){
  69903. sqlite3_str_appendf(&acc, "%lld", p->u.i);
  69904. }else if( p->flags & MEM_IntReal ){
  69905. sqlite3_str_appendf(&acc, "%!.15g", (double)p->u.i);
  69906. }else{
  69907. sqlite3_str_appendf(&acc, "%!.15g", p->u.r);
  69908. }
  69909. assert( acc.zText==zBuf && acc.mxAlloc<=0 );
  69910. zBuf[acc.nChar] = 0; /* Fast version of sqlite3StrAccumFinish(&acc) */
  69911. }
  69912. #ifdef SQLITE_DEBUG
  69913. /*
  69914. ** Validity checks on pMem. pMem holds a string.
  69915. **
  69916. ** (1) Check that string value of pMem agrees with its integer or real value.
  69917. ** (2) Check that the string is correctly zero terminated
  69918. **
  69919. ** A single int or real value always converts to the same strings. But
  69920. ** many different strings can be converted into the same int or real.
  69921. ** If a table contains a numeric value and an index is based on the
  69922. ** corresponding string value, then it is important that the string be
  69923. ** derived from the numeric value, not the other way around, to ensure
  69924. ** that the index and table are consistent. See ticket
  69925. ** https://www.sqlite.org/src/info/343634942dd54ab (2018-01-31) for
  69926. ** an example.
  69927. **
  69928. ** This routine looks at pMem to verify that if it has both a numeric
  69929. ** representation and a string representation then the string rep has
  69930. ** been derived from the numeric and not the other way around. It returns
  69931. ** true if everything is ok and false if there is a problem.
  69932. **
  69933. ** This routine is for use inside of assert() statements only.
  69934. */
  69935. SQLITE_PRIVATE int sqlite3VdbeMemValidStrRep(Mem *p){
  69936. char zBuf[100];
  69937. char *z;
  69938. int i, j, incr;
  69939. if( (p->flags & MEM_Str)==0 ) return 1;
  69940. if( p->flags & MEM_Term ){
  69941. /* Insure that the string is properly zero-terminated. Pay particular
  69942. ** attention to the case where p->n is odd */
  69943. if( p->szMalloc>0 && p->z==p->zMalloc ){
  69944. assert( p->enc==SQLITE_UTF8 || p->szMalloc >= ((p->n+1)&~1)+2 );
  69945. assert( p->enc!=SQLITE_UTF8 || p->szMalloc >= p->n+1 );
  69946. }
  69947. assert( p->z[p->n]==0 );
  69948. assert( p->enc==SQLITE_UTF8 || p->z[(p->n+1)&~1]==0 );
  69949. assert( p->enc==SQLITE_UTF8 || p->z[((p->n+1)&~1)+1]==0 );
  69950. }
  69951. if( (p->flags & (MEM_Int|MEM_Real|MEM_IntReal))==0 ) return 1;
  69952. vdbeMemRenderNum(sizeof(zBuf), zBuf, p);
  69953. z = p->z;
  69954. i = j = 0;
  69955. incr = 1;
  69956. if( p->enc!=SQLITE_UTF8 ){
  69957. incr = 2;
  69958. if( p->enc==SQLITE_UTF16BE ) z++;
  69959. }
  69960. while( zBuf[j] ){
  69961. if( zBuf[j++]!=z[i] ) return 0;
  69962. i += incr;
  69963. }
  69964. return 1;
  69965. }
  69966. #endif /* SQLITE_DEBUG */
  69967. /*
  69968. ** If pMem is an object with a valid string representation, this routine
  69969. ** ensures the internal encoding for the string representation is
  69970. ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
  69971. **
  69972. ** If pMem is not a string object, or the encoding of the string
  69973. ** representation is already stored using the requested encoding, then this
  69974. ** routine is a no-op.
  69975. **
  69976. ** SQLITE_OK is returned if the conversion is successful (or not required).
  69977. ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
  69978. ** between formats.
  69979. */
  69980. SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
  69981. #ifndef SQLITE_OMIT_UTF16
  69982. int rc;
  69983. #endif
  69984. assert( !sqlite3VdbeMemIsRowSet(pMem) );
  69985. assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
  69986. || desiredEnc==SQLITE_UTF16BE );
  69987. if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
  69988. return SQLITE_OK;
  69989. }
  69990. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  69991. #ifdef SQLITE_OMIT_UTF16
  69992. return SQLITE_ERROR;
  69993. #else
  69994. /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
  69995. ** then the encoding of the value may not have changed.
  69996. */
  69997. rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
  69998. assert(rc==SQLITE_OK || rc==SQLITE_NOMEM);
  69999. assert(rc==SQLITE_OK || pMem->enc!=desiredEnc);
  70000. assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
  70001. return rc;
  70002. #endif
  70003. }
  70004. /*
  70005. ** Make sure pMem->z points to a writable allocation of at least n bytes.
  70006. **
  70007. ** If the bPreserve argument is true, then copy of the content of
  70008. ** pMem->z into the new allocation. pMem must be either a string or
  70009. ** blob if bPreserve is true. If bPreserve is false, any prior content
  70010. ** in pMem->z is discarded.
  70011. */
  70012. SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemGrow(Mem *pMem, int n, int bPreserve){
  70013. assert( sqlite3VdbeCheckMemInvariants(pMem) );
  70014. assert( !sqlite3VdbeMemIsRowSet(pMem) );
  70015. testcase( pMem->db==0 );
  70016. /* If the bPreserve flag is set to true, then the memory cell must already
  70017. ** contain a valid string or blob value. */
  70018. assert( bPreserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
  70019. testcase( bPreserve && pMem->z==0 );
  70020. assert( pMem->szMalloc==0
  70021. || pMem->szMalloc==sqlite3DbMallocSize(pMem->db, pMem->zMalloc) );
  70022. if( pMem->szMalloc>0 && bPreserve && pMem->z==pMem->zMalloc ){
  70023. pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
  70024. bPreserve = 0;
  70025. }else{
  70026. if( pMem->szMalloc>0 ) sqlite3DbFreeNN(pMem->db, pMem->zMalloc);
  70027. pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
  70028. }
  70029. if( pMem->zMalloc==0 ){
  70030. sqlite3VdbeMemSetNull(pMem);
  70031. pMem->z = 0;
  70032. pMem->szMalloc = 0;
  70033. return SQLITE_NOMEM_BKPT;
  70034. }else{
  70035. pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
  70036. }
  70037. if( bPreserve && pMem->z ){
  70038. assert( pMem->z!=pMem->zMalloc );
  70039. memcpy(pMem->zMalloc, pMem->z, pMem->n);
  70040. }
  70041. if( (pMem->flags&MEM_Dyn)!=0 ){
  70042. assert( pMem->xDel!=0 && pMem->xDel!=SQLITE_DYNAMIC );
  70043. pMem->xDel((void *)(pMem->z));
  70044. }
  70045. pMem->z = pMem->zMalloc;
  70046. pMem->flags &= ~(MEM_Dyn|MEM_Ephem|MEM_Static);
  70047. return SQLITE_OK;
  70048. }
  70049. /*
  70050. ** Change the pMem->zMalloc allocation to be at least szNew bytes.
  70051. ** If pMem->zMalloc already meets or exceeds the requested size, this
  70052. ** routine is a no-op.
  70053. **
  70054. ** Any prior string or blob content in the pMem object may be discarded.
  70055. ** The pMem->xDel destructor is called, if it exists. Though MEM_Str
  70056. ** and MEM_Blob values may be discarded, MEM_Int, MEM_Real, MEM_IntReal,
  70057. ** and MEM_Null values are preserved.
  70058. **
  70059. ** Return SQLITE_OK on success or an error code (probably SQLITE_NOMEM)
  70060. ** if unable to complete the resizing.
  70061. */
  70062. SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int szNew){
  70063. assert( CORRUPT_DB || szNew>0 );
  70064. assert( (pMem->flags & MEM_Dyn)==0 || pMem->szMalloc==0 );
  70065. if( pMem->szMalloc<szNew ){
  70066. return sqlite3VdbeMemGrow(pMem, szNew, 0);
  70067. }
  70068. assert( (pMem->flags & MEM_Dyn)==0 );
  70069. pMem->z = pMem->zMalloc;
  70070. pMem->flags &= (MEM_Null|MEM_Int|MEM_Real|MEM_IntReal);
  70071. return SQLITE_OK;
  70072. }
  70073. /*
  70074. ** It is already known that pMem contains an unterminated string.
  70075. ** Add the zero terminator.
  70076. **
  70077. ** Three bytes of zero are added. In this way, there is guaranteed
  70078. ** to be a double-zero byte at an even byte boundary in order to
  70079. ** terminate a UTF16 string, even if the initial size of the buffer
  70080. ** is an odd number of bytes.
  70081. */
  70082. static SQLITE_NOINLINE int vdbeMemAddTerminator(Mem *pMem){
  70083. if( sqlite3VdbeMemGrow(pMem, pMem->n+3, 1) ){
  70084. return SQLITE_NOMEM_BKPT;
  70085. }
  70086. pMem->z[pMem->n] = 0;
  70087. pMem->z[pMem->n+1] = 0;
  70088. pMem->z[pMem->n+2] = 0;
  70089. pMem->flags |= MEM_Term;
  70090. return SQLITE_OK;
  70091. }
  70092. /*
  70093. ** Change pMem so that its MEM_Str or MEM_Blob value is stored in
  70094. ** MEM.zMalloc, where it can be safely written.
  70095. **
  70096. ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
  70097. */
  70098. SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
  70099. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  70100. assert( !sqlite3VdbeMemIsRowSet(pMem) );
  70101. if( (pMem->flags & (MEM_Str|MEM_Blob))!=0 ){
  70102. if( ExpandBlob(pMem) ) return SQLITE_NOMEM;
  70103. if( pMem->szMalloc==0 || pMem->z!=pMem->zMalloc ){
  70104. int rc = vdbeMemAddTerminator(pMem);
  70105. if( rc ) return rc;
  70106. }
  70107. }
  70108. pMem->flags &= ~MEM_Ephem;
  70109. #ifdef SQLITE_DEBUG
  70110. pMem->pScopyFrom = 0;
  70111. #endif
  70112. return SQLITE_OK;
  70113. }
  70114. /*
  70115. ** If the given Mem* has a zero-filled tail, turn it into an ordinary
  70116. ** blob stored in dynamically allocated space.
  70117. */
  70118. #ifndef SQLITE_OMIT_INCRBLOB
  70119. SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
  70120. int nByte;
  70121. assert( pMem->flags & MEM_Zero );
  70122. assert( (pMem->flags&MEM_Blob)!=0 || MemNullNochng(pMem) );
  70123. testcase( sqlite3_value_nochange(pMem) );
  70124. assert( !sqlite3VdbeMemIsRowSet(pMem) );
  70125. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  70126. /* Set nByte to the number of bytes required to store the expanded blob. */
  70127. nByte = pMem->n + pMem->u.nZero;
  70128. if( nByte<=0 ){
  70129. if( (pMem->flags & MEM_Blob)==0 ) return SQLITE_OK;
  70130. nByte = 1;
  70131. }
  70132. if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
  70133. return SQLITE_NOMEM_BKPT;
  70134. }
  70135. memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
  70136. pMem->n += pMem->u.nZero;
  70137. pMem->flags &= ~(MEM_Zero|MEM_Term);
  70138. return SQLITE_OK;
  70139. }
  70140. #endif
  70141. /*
  70142. ** Make sure the given Mem is \u0000 terminated.
  70143. */
  70144. SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
  70145. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  70146. testcase( (pMem->flags & (MEM_Term|MEM_Str))==(MEM_Term|MEM_Str) );
  70147. testcase( (pMem->flags & (MEM_Term|MEM_Str))==0 );
  70148. if( (pMem->flags & (MEM_Term|MEM_Str))!=MEM_Str ){
  70149. return SQLITE_OK; /* Nothing to do */
  70150. }else{
  70151. return vdbeMemAddTerminator(pMem);
  70152. }
  70153. }
  70154. /*
  70155. ** Add MEM_Str to the set of representations for the given Mem. This
  70156. ** routine is only called if pMem is a number of some kind, not a NULL
  70157. ** or a BLOB.
  70158. **
  70159. ** Existing representations MEM_Int, MEM_Real, or MEM_IntReal are invalidated
  70160. ** if bForce is true but are retained if bForce is false.
  70161. **
  70162. ** A MEM_Null value will never be passed to this function. This function is
  70163. ** used for converting values to text for returning to the user (i.e. via
  70164. ** sqlite3_value_text()), or for ensuring that values to be used as btree
  70165. ** keys are strings. In the former case a NULL pointer is returned the
  70166. ** user and the latter is an internal programming error.
  70167. */
  70168. SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, u8 enc, u8 bForce){
  70169. const int nByte = 32;
  70170. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  70171. assert( !(pMem->flags&MEM_Zero) );
  70172. assert( !(pMem->flags&(MEM_Str|MEM_Blob)) );
  70173. assert( pMem->flags&(MEM_Int|MEM_Real|MEM_IntReal) );
  70174. assert( !sqlite3VdbeMemIsRowSet(pMem) );
  70175. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  70176. if( sqlite3VdbeMemClearAndResize(pMem, nByte) ){
  70177. pMem->enc = 0;
  70178. return SQLITE_NOMEM_BKPT;
  70179. }
  70180. vdbeMemRenderNum(nByte, pMem->z, pMem);
  70181. assert( pMem->z!=0 );
  70182. pMem->n = sqlite3Strlen30NN(pMem->z);
  70183. pMem->enc = SQLITE_UTF8;
  70184. pMem->flags |= MEM_Str|MEM_Term;
  70185. if( bForce ) pMem->flags &= ~(MEM_Int|MEM_Real|MEM_IntReal);
  70186. sqlite3VdbeChangeEncoding(pMem, enc);
  70187. return SQLITE_OK;
  70188. }
  70189. /*
  70190. ** Memory cell pMem contains the context of an aggregate function.
  70191. ** This routine calls the finalize method for that function. The
  70192. ** result of the aggregate is stored back into pMem.
  70193. **
  70194. ** Return SQLITE_ERROR if the finalizer reports an error. SQLITE_OK
  70195. ** otherwise.
  70196. */
  70197. SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
  70198. sqlite3_context ctx;
  70199. Mem t;
  70200. assert( pFunc!=0 );
  70201. assert( pFunc->xFinalize!=0 );
  70202. assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
  70203. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  70204. memset(&ctx, 0, sizeof(ctx));
  70205. memset(&t, 0, sizeof(t));
  70206. t.flags = MEM_Null;
  70207. t.db = pMem->db;
  70208. ctx.pOut = &t;
  70209. ctx.pMem = pMem;
  70210. ctx.pFunc = pFunc;
  70211. pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
  70212. assert( (pMem->flags & MEM_Dyn)==0 );
  70213. if( pMem->szMalloc>0 ) sqlite3DbFreeNN(pMem->db, pMem->zMalloc);
  70214. memcpy(pMem, &t, sizeof(t));
  70215. return ctx.isError;
  70216. }
  70217. /*
  70218. ** Memory cell pAccum contains the context of an aggregate function.
  70219. ** This routine calls the xValue method for that function and stores
  70220. ** the results in memory cell pMem.
  70221. **
  70222. ** SQLITE_ERROR is returned if xValue() reports an error. SQLITE_OK
  70223. ** otherwise.
  70224. */
  70225. #ifndef SQLITE_OMIT_WINDOWFUNC
  70226. SQLITE_PRIVATE int sqlite3VdbeMemAggValue(Mem *pAccum, Mem *pOut, FuncDef *pFunc){
  70227. sqlite3_context ctx;
  70228. Mem t;
  70229. assert( pFunc!=0 );
  70230. assert( pFunc->xValue!=0 );
  70231. assert( (pAccum->flags & MEM_Null)!=0 || pFunc==pAccum->u.pDef );
  70232. assert( pAccum->db==0 || sqlite3_mutex_held(pAccum->db->mutex) );
  70233. memset(&ctx, 0, sizeof(ctx));
  70234. memset(&t, 0, sizeof(t));
  70235. t.flags = MEM_Null;
  70236. t.db = pAccum->db;
  70237. sqlite3VdbeMemSetNull(pOut);
  70238. ctx.pOut = pOut;
  70239. ctx.pMem = pAccum;
  70240. ctx.pFunc = pFunc;
  70241. pFunc->xValue(&ctx);
  70242. return ctx.isError;
  70243. }
  70244. #endif /* SQLITE_OMIT_WINDOWFUNC */
  70245. /*
  70246. ** If the memory cell contains a value that must be freed by
  70247. ** invoking the external callback in Mem.xDel, then this routine
  70248. ** will free that value. It also sets Mem.flags to MEM_Null.
  70249. **
  70250. ** This is a helper routine for sqlite3VdbeMemSetNull() and
  70251. ** for sqlite3VdbeMemRelease(). Use those other routines as the
  70252. ** entry point for releasing Mem resources.
  70253. */
  70254. static SQLITE_NOINLINE void vdbeMemClearExternAndSetNull(Mem *p){
  70255. assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
  70256. assert( VdbeMemDynamic(p) );
  70257. if( p->flags&MEM_Agg ){
  70258. sqlite3VdbeMemFinalize(p, p->u.pDef);
  70259. assert( (p->flags & MEM_Agg)==0 );
  70260. testcase( p->flags & MEM_Dyn );
  70261. }
  70262. if( p->flags&MEM_Dyn ){
  70263. assert( p->xDel!=SQLITE_DYNAMIC && p->xDel!=0 );
  70264. p->xDel((void *)p->z);
  70265. }
  70266. p->flags = MEM_Null;
  70267. }
  70268. /*
  70269. ** Release memory held by the Mem p, both external memory cleared
  70270. ** by p->xDel and memory in p->zMalloc.
  70271. **
  70272. ** This is a helper routine invoked by sqlite3VdbeMemRelease() in
  70273. ** the unusual case where there really is memory in p that needs
  70274. ** to be freed.
  70275. */
  70276. static SQLITE_NOINLINE void vdbeMemClear(Mem *p){
  70277. if( VdbeMemDynamic(p) ){
  70278. vdbeMemClearExternAndSetNull(p);
  70279. }
  70280. if( p->szMalloc ){
  70281. sqlite3DbFreeNN(p->db, p->zMalloc);
  70282. p->szMalloc = 0;
  70283. }
  70284. p->z = 0;
  70285. }
  70286. /*
  70287. ** Release any memory resources held by the Mem. Both the memory that is
  70288. ** free by Mem.xDel and the Mem.zMalloc allocation are freed.
  70289. **
  70290. ** Use this routine prior to clean up prior to abandoning a Mem, or to
  70291. ** reset a Mem back to its minimum memory utilization.
  70292. **
  70293. ** Use sqlite3VdbeMemSetNull() to release just the Mem.xDel space
  70294. ** prior to inserting new content into the Mem.
  70295. */
  70296. SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
  70297. assert( sqlite3VdbeCheckMemInvariants(p) );
  70298. if( VdbeMemDynamic(p) || p->szMalloc ){
  70299. vdbeMemClear(p);
  70300. }
  70301. }
  70302. /*
  70303. ** Convert a 64-bit IEEE double into a 64-bit signed integer.
  70304. ** If the double is out of range of a 64-bit signed integer then
  70305. ** return the closest available 64-bit signed integer.
  70306. */
  70307. static SQLITE_NOINLINE i64 doubleToInt64(double r){
  70308. #ifdef SQLITE_OMIT_FLOATING_POINT
  70309. /* When floating-point is omitted, double and int64 are the same thing */
  70310. return r;
  70311. #else
  70312. /*
  70313. ** Many compilers we encounter do not define constants for the
  70314. ** minimum and maximum 64-bit integers, or they define them
  70315. ** inconsistently. And many do not understand the "LL" notation.
  70316. ** So we define our own static constants here using nothing
  70317. ** larger than a 32-bit integer constant.
  70318. */
  70319. static const i64 maxInt = LARGEST_INT64;
  70320. static const i64 minInt = SMALLEST_INT64;
  70321. if( r<=(double)minInt ){
  70322. return minInt;
  70323. }else if( r>=(double)maxInt ){
  70324. return maxInt;
  70325. }else{
  70326. return (i64)r;
  70327. }
  70328. #endif
  70329. }
  70330. /*
  70331. ** Return some kind of integer value which is the best we can do
  70332. ** at representing the value that *pMem describes as an integer.
  70333. ** If pMem is an integer, then the value is exact. If pMem is
  70334. ** a floating-point then the value returned is the integer part.
  70335. ** If pMem is a string or blob, then we make an attempt to convert
  70336. ** it into an integer and return that. If pMem represents an
  70337. ** an SQL-NULL value, return 0.
  70338. **
  70339. ** If pMem represents a string value, its encoding might be changed.
  70340. */
  70341. static SQLITE_NOINLINE i64 memIntValue(Mem *pMem){
  70342. i64 value = 0;
  70343. sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
  70344. return value;
  70345. }
  70346. SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
  70347. int flags;
  70348. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  70349. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  70350. flags = pMem->flags;
  70351. if( flags & (MEM_Int|MEM_IntReal) ){
  70352. testcase( flags & MEM_IntReal );
  70353. return pMem->u.i;
  70354. }else if( flags & MEM_Real ){
  70355. return doubleToInt64(pMem->u.r);
  70356. }else if( flags & (MEM_Str|MEM_Blob) ){
  70357. assert( pMem->z || pMem->n==0 );
  70358. return memIntValue(pMem);
  70359. }else{
  70360. return 0;
  70361. }
  70362. }
  70363. /*
  70364. ** Return the best representation of pMem that we can get into a
  70365. ** double. If pMem is already a double or an integer, return its
  70366. ** value. If it is a string or blob, try to convert it to a double.
  70367. ** If it is a NULL, return 0.0.
  70368. */
  70369. static SQLITE_NOINLINE double memRealValue(Mem *pMem){
  70370. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  70371. double val = (double)0;
  70372. sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
  70373. return val;
  70374. }
  70375. SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
  70376. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  70377. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  70378. if( pMem->flags & MEM_Real ){
  70379. return pMem->u.r;
  70380. }else if( pMem->flags & (MEM_Int|MEM_IntReal) ){
  70381. testcase( pMem->flags & MEM_IntReal );
  70382. return (double)pMem->u.i;
  70383. }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
  70384. return memRealValue(pMem);
  70385. }else{
  70386. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  70387. return (double)0;
  70388. }
  70389. }
  70390. /*
  70391. ** Return 1 if pMem represents true, and return 0 if pMem represents false.
  70392. ** Return the value ifNull if pMem is NULL.
  70393. */
  70394. SQLITE_PRIVATE int sqlite3VdbeBooleanValue(Mem *pMem, int ifNull){
  70395. testcase( pMem->flags & MEM_IntReal );
  70396. if( pMem->flags & (MEM_Int|MEM_IntReal) ) return pMem->u.i!=0;
  70397. if( pMem->flags & MEM_Null ) return ifNull;
  70398. return sqlite3VdbeRealValue(pMem)!=0.0;
  70399. }
  70400. /*
  70401. ** The MEM structure is already a MEM_Real. Try to also make it a
  70402. ** MEM_Int if we can.
  70403. */
  70404. SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
  70405. i64 ix;
  70406. assert( pMem->flags & MEM_Real );
  70407. assert( !sqlite3VdbeMemIsRowSet(pMem) );
  70408. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  70409. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  70410. ix = doubleToInt64(pMem->u.r);
  70411. /* Only mark the value as an integer if
  70412. **
  70413. ** (1) the round-trip conversion real->int->real is a no-op, and
  70414. ** (2) The integer is neither the largest nor the smallest
  70415. ** possible integer (ticket #3922)
  70416. **
  70417. ** The second and third terms in the following conditional enforces
  70418. ** the second condition under the assumption that addition overflow causes
  70419. ** values to wrap around.
  70420. */
  70421. if( pMem->u.r==ix && ix>SMALLEST_INT64 && ix<LARGEST_INT64 ){
  70422. pMem->u.i = ix;
  70423. MemSetTypeFlag(pMem, MEM_Int);
  70424. }
  70425. }
  70426. /*
  70427. ** Convert pMem to type integer. Invalidate any prior representations.
  70428. */
  70429. SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
  70430. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  70431. assert( !sqlite3VdbeMemIsRowSet(pMem) );
  70432. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  70433. pMem->u.i = sqlite3VdbeIntValue(pMem);
  70434. MemSetTypeFlag(pMem, MEM_Int);
  70435. return SQLITE_OK;
  70436. }
  70437. /*
  70438. ** Convert pMem so that it is of type MEM_Real.
  70439. ** Invalidate any prior representations.
  70440. */
  70441. SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
  70442. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  70443. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  70444. pMem->u.r = sqlite3VdbeRealValue(pMem);
  70445. MemSetTypeFlag(pMem, MEM_Real);
  70446. return SQLITE_OK;
  70447. }
  70448. /* Compare a floating point value to an integer. Return true if the two
  70449. ** values are the same within the precision of the floating point value.
  70450. **
  70451. ** This function assumes that i was obtained by assignment from r1.
  70452. **
  70453. ** For some versions of GCC on 32-bit machines, if you do the more obvious
  70454. ** comparison of "r1==(double)i" you sometimes get an answer of false even
  70455. ** though the r1 and (double)i values are bit-for-bit the same.
  70456. */
  70457. SQLITE_PRIVATE int sqlite3RealSameAsInt(double r1, sqlite3_int64 i){
  70458. double r2 = (double)i;
  70459. return r1==0.0
  70460. || (memcmp(&r1, &r2, sizeof(r1))==0
  70461. && i >= -2251799813685248LL && i < 2251799813685248LL);
  70462. }
  70463. /*
  70464. ** Convert pMem so that it has type MEM_Real or MEM_Int.
  70465. ** Invalidate any prior representations.
  70466. **
  70467. ** Every effort is made to force the conversion, even if the input
  70468. ** is a string that does not look completely like a number. Convert
  70469. ** as much of the string as we can and ignore the rest.
  70470. */
  70471. SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
  70472. testcase( pMem->flags & MEM_Int );
  70473. testcase( pMem->flags & MEM_Real );
  70474. testcase( pMem->flags & MEM_IntReal );
  70475. testcase( pMem->flags & MEM_Null );
  70476. if( (pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal|MEM_Null))==0 ){
  70477. int rc;
  70478. sqlite3_int64 ix;
  70479. assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
  70480. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  70481. rc = sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc);
  70482. if( ((rc==0 || rc==1) && sqlite3Atoi64(pMem->z, &ix, pMem->n, pMem->enc)<=1)
  70483. || sqlite3RealSameAsInt(pMem->u.r, (ix = (i64)pMem->u.r))
  70484. ){
  70485. pMem->u.i = ix;
  70486. MemSetTypeFlag(pMem, MEM_Int);
  70487. }else{
  70488. MemSetTypeFlag(pMem, MEM_Real);
  70489. }
  70490. }
  70491. assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal|MEM_Null))!=0 );
  70492. pMem->flags &= ~(MEM_Str|MEM_Blob|MEM_Zero);
  70493. return SQLITE_OK;
  70494. }
  70495. /*
  70496. ** Cast the datatype of the value in pMem according to the affinity
  70497. ** "aff". Casting is different from applying affinity in that a cast
  70498. ** is forced. In other words, the value is converted into the desired
  70499. ** affinity even if that results in loss of data. This routine is
  70500. ** used (for example) to implement the SQL "cast()" operator.
  70501. */
  70502. SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem *pMem, u8 aff, u8 encoding){
  70503. if( pMem->flags & MEM_Null ) return;
  70504. switch( aff ){
  70505. case SQLITE_AFF_BLOB: { /* Really a cast to BLOB */
  70506. if( (pMem->flags & MEM_Blob)==0 ){
  70507. sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
  70508. assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
  70509. if( pMem->flags & MEM_Str ) MemSetTypeFlag(pMem, MEM_Blob);
  70510. }else{
  70511. pMem->flags &= ~(MEM_TypeMask&~MEM_Blob);
  70512. }
  70513. break;
  70514. }
  70515. case SQLITE_AFF_NUMERIC: {
  70516. sqlite3VdbeMemNumerify(pMem);
  70517. break;
  70518. }
  70519. case SQLITE_AFF_INTEGER: {
  70520. sqlite3VdbeMemIntegerify(pMem);
  70521. break;
  70522. }
  70523. case SQLITE_AFF_REAL: {
  70524. sqlite3VdbeMemRealify(pMem);
  70525. break;
  70526. }
  70527. default: {
  70528. assert( aff==SQLITE_AFF_TEXT );
  70529. assert( MEM_Str==(MEM_Blob>>3) );
  70530. pMem->flags |= (pMem->flags&MEM_Blob)>>3;
  70531. sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
  70532. assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
  70533. pMem->flags &= ~(MEM_Int|MEM_Real|MEM_IntReal|MEM_Blob|MEM_Zero);
  70534. break;
  70535. }
  70536. }
  70537. }
  70538. /*
  70539. ** Initialize bulk memory to be a consistent Mem object.
  70540. **
  70541. ** The minimum amount of initialization feasible is performed.
  70542. */
  70543. SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem *pMem, sqlite3 *db, u16 flags){
  70544. assert( (flags & ~MEM_TypeMask)==0 );
  70545. pMem->flags = flags;
  70546. pMem->db = db;
  70547. pMem->szMalloc = 0;
  70548. }
  70549. /*
  70550. ** Delete any previous value and set the value stored in *pMem to NULL.
  70551. **
  70552. ** This routine calls the Mem.xDel destructor to dispose of values that
  70553. ** require the destructor. But it preserves the Mem.zMalloc memory allocation.
  70554. ** To free all resources, use sqlite3VdbeMemRelease(), which both calls this
  70555. ** routine to invoke the destructor and deallocates Mem.zMalloc.
  70556. **
  70557. ** Use this routine to reset the Mem prior to insert a new value.
  70558. **
  70559. ** Use sqlite3VdbeMemRelease() to complete erase the Mem prior to abandoning it.
  70560. */
  70561. SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
  70562. if( VdbeMemDynamic(pMem) ){
  70563. vdbeMemClearExternAndSetNull(pMem);
  70564. }else{
  70565. pMem->flags = MEM_Null;
  70566. }
  70567. }
  70568. SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value *p){
  70569. sqlite3VdbeMemSetNull((Mem*)p);
  70570. }
  70571. /*
  70572. ** Delete any previous value and set the value to be a BLOB of length
  70573. ** n containing all zeros.
  70574. */
  70575. SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
  70576. sqlite3VdbeMemRelease(pMem);
  70577. pMem->flags = MEM_Blob|MEM_Zero;
  70578. pMem->n = 0;
  70579. if( n<0 ) n = 0;
  70580. pMem->u.nZero = n;
  70581. pMem->enc = SQLITE_UTF8;
  70582. pMem->z = 0;
  70583. }
  70584. /*
  70585. ** The pMem is known to contain content that needs to be destroyed prior
  70586. ** to a value change. So invoke the destructor, then set the value to
  70587. ** a 64-bit integer.
  70588. */
  70589. static SQLITE_NOINLINE void vdbeReleaseAndSetInt64(Mem *pMem, i64 val){
  70590. sqlite3VdbeMemSetNull(pMem);
  70591. pMem->u.i = val;
  70592. pMem->flags = MEM_Int;
  70593. }
  70594. /*
  70595. ** Delete any previous value and set the value stored in *pMem to val,
  70596. ** manifest type INTEGER.
  70597. */
  70598. SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
  70599. if( VdbeMemDynamic(pMem) ){
  70600. vdbeReleaseAndSetInt64(pMem, val);
  70601. }else{
  70602. pMem->u.i = val;
  70603. pMem->flags = MEM_Int;
  70604. }
  70605. }
  70606. /* A no-op destructor */
  70607. SQLITE_PRIVATE void sqlite3NoopDestructor(void *p){ UNUSED_PARAMETER(p); }
  70608. /*
  70609. ** Set the value stored in *pMem should already be a NULL.
  70610. ** Also store a pointer to go with it.
  70611. */
  70612. SQLITE_PRIVATE void sqlite3VdbeMemSetPointer(
  70613. Mem *pMem,
  70614. void *pPtr,
  70615. const char *zPType,
  70616. void (*xDestructor)(void*)
  70617. ){
  70618. assert( pMem->flags==MEM_Null );
  70619. pMem->u.zPType = zPType ? zPType : "";
  70620. pMem->z = pPtr;
  70621. pMem->flags = MEM_Null|MEM_Dyn|MEM_Subtype|MEM_Term;
  70622. pMem->eSubtype = 'p';
  70623. pMem->xDel = xDestructor ? xDestructor : sqlite3NoopDestructor;
  70624. }
  70625. #ifndef SQLITE_OMIT_FLOATING_POINT
  70626. /*
  70627. ** Delete any previous value and set the value stored in *pMem to val,
  70628. ** manifest type REAL.
  70629. */
  70630. SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
  70631. sqlite3VdbeMemSetNull(pMem);
  70632. if( !sqlite3IsNaN(val) ){
  70633. pMem->u.r = val;
  70634. pMem->flags = MEM_Real;
  70635. }
  70636. }
  70637. #endif
  70638. #ifdef SQLITE_DEBUG
  70639. /*
  70640. ** Return true if the Mem holds a RowSet object. This routine is intended
  70641. ** for use inside of assert() statements.
  70642. */
  70643. SQLITE_PRIVATE int sqlite3VdbeMemIsRowSet(const Mem *pMem){
  70644. return (pMem->flags&(MEM_Blob|MEM_Dyn))==(MEM_Blob|MEM_Dyn)
  70645. && pMem->xDel==sqlite3RowSetDelete;
  70646. }
  70647. #endif
  70648. /*
  70649. ** Delete any previous value and set the value of pMem to be an
  70650. ** empty boolean index.
  70651. **
  70652. ** Return SQLITE_OK on success and SQLITE_NOMEM if a memory allocation
  70653. ** error occurs.
  70654. */
  70655. SQLITE_PRIVATE int sqlite3VdbeMemSetRowSet(Mem *pMem){
  70656. sqlite3 *db = pMem->db;
  70657. RowSet *p;
  70658. assert( db!=0 );
  70659. assert( !sqlite3VdbeMemIsRowSet(pMem) );
  70660. sqlite3VdbeMemRelease(pMem);
  70661. p = sqlite3RowSetInit(db);
  70662. if( p==0 ) return SQLITE_NOMEM;
  70663. pMem->z = (char*)p;
  70664. pMem->flags = MEM_Blob|MEM_Dyn;
  70665. pMem->xDel = sqlite3RowSetDelete;
  70666. return SQLITE_OK;
  70667. }
  70668. /*
  70669. ** Return true if the Mem object contains a TEXT or BLOB that is
  70670. ** too large - whose size exceeds SQLITE_MAX_LENGTH.
  70671. */
  70672. SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
  70673. assert( p->db!=0 );
  70674. if( p->flags & (MEM_Str|MEM_Blob) ){
  70675. int n = p->n;
  70676. if( p->flags & MEM_Zero ){
  70677. n += p->u.nZero;
  70678. }
  70679. return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
  70680. }
  70681. return 0;
  70682. }
  70683. #ifdef SQLITE_DEBUG
  70684. /*
  70685. ** This routine prepares a memory cell for modification by breaking
  70686. ** its link to a shallow copy and by marking any current shallow
  70687. ** copies of this cell as invalid.
  70688. **
  70689. ** This is used for testing and debugging only - to make sure shallow
  70690. ** copies are not misused.
  70691. */
  70692. SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
  70693. int i;
  70694. Mem *pX;
  70695. for(i=0, pX=pVdbe->aMem; i<pVdbe->nMem; i++, pX++){
  70696. if( pX->pScopyFrom==pMem ){
  70697. /* If pX is marked as a shallow copy of pMem, then verify that
  70698. ** no significant changes have been made to pX since the OP_SCopy.
  70699. ** A significant change would indicated a missed call to this
  70700. ** function for pX. Minor changes, such as adding or removing a
  70701. ** dual type, are allowed, as long as the underlying value is the
  70702. ** same. */
  70703. u16 mFlags = pMem->flags & pX->flags & pX->mScopyFlags;
  70704. assert( (mFlags&(MEM_Int|MEM_IntReal))==0 || pMem->u.i==pX->u.i );
  70705. assert( (mFlags&MEM_Real)==0 || pMem->u.r==pX->u.r );
  70706. assert( (mFlags&MEM_Str)==0 || (pMem->n==pX->n && pMem->z==pX->z) );
  70707. assert( (mFlags&MEM_Blob)==0 || sqlite3BlobCompare(pMem,pX)==0 );
  70708. /* pMem is the register that is changing. But also mark pX as
  70709. ** undefined so that we can quickly detect the shallow-copy error */
  70710. pX->flags = MEM_Undefined;
  70711. pX->pScopyFrom = 0;
  70712. }
  70713. }
  70714. pMem->pScopyFrom = 0;
  70715. }
  70716. #endif /* SQLITE_DEBUG */
  70717. /*
  70718. ** Make an shallow copy of pFrom into pTo. Prior contents of
  70719. ** pTo are freed. The pFrom->z field is not duplicated. If
  70720. ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
  70721. ** and flags gets srcType (either MEM_Ephem or MEM_Static).
  70722. */
  70723. static SQLITE_NOINLINE void vdbeClrCopy(Mem *pTo, const Mem *pFrom, int eType){
  70724. vdbeMemClearExternAndSetNull(pTo);
  70725. assert( !VdbeMemDynamic(pTo) );
  70726. sqlite3VdbeMemShallowCopy(pTo, pFrom, eType);
  70727. }
  70728. SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
  70729. assert( !sqlite3VdbeMemIsRowSet(pFrom) );
  70730. assert( pTo->db==pFrom->db );
  70731. if( VdbeMemDynamic(pTo) ){ vdbeClrCopy(pTo,pFrom,srcType); return; }
  70732. memcpy(pTo, pFrom, MEMCELLSIZE);
  70733. if( (pFrom->flags&MEM_Static)==0 ){
  70734. pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
  70735. assert( srcType==MEM_Ephem || srcType==MEM_Static );
  70736. pTo->flags |= srcType;
  70737. }
  70738. }
  70739. /*
  70740. ** Make a full copy of pFrom into pTo. Prior contents of pTo are
  70741. ** freed before the copy is made.
  70742. */
  70743. SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
  70744. int rc = SQLITE_OK;
  70745. assert( !sqlite3VdbeMemIsRowSet(pFrom) );
  70746. if( VdbeMemDynamic(pTo) ) vdbeMemClearExternAndSetNull(pTo);
  70747. memcpy(pTo, pFrom, MEMCELLSIZE);
  70748. pTo->flags &= ~MEM_Dyn;
  70749. if( pTo->flags&(MEM_Str|MEM_Blob) ){
  70750. if( 0==(pFrom->flags&MEM_Static) ){
  70751. pTo->flags |= MEM_Ephem;
  70752. rc = sqlite3VdbeMemMakeWriteable(pTo);
  70753. }
  70754. }
  70755. return rc;
  70756. }
  70757. /*
  70758. ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
  70759. ** freed. If pFrom contains ephemeral data, a copy is made.
  70760. **
  70761. ** pFrom contains an SQL NULL when this routine returns.
  70762. */
  70763. SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
  70764. assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
  70765. assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
  70766. assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
  70767. sqlite3VdbeMemRelease(pTo);
  70768. memcpy(pTo, pFrom, sizeof(Mem));
  70769. pFrom->flags = MEM_Null;
  70770. pFrom->szMalloc = 0;
  70771. }
  70772. /*
  70773. ** Change the value of a Mem to be a string or a BLOB.
  70774. **
  70775. ** The memory management strategy depends on the value of the xDel
  70776. ** parameter. If the value passed is SQLITE_TRANSIENT, then the
  70777. ** string is copied into a (possibly existing) buffer managed by the
  70778. ** Mem structure. Otherwise, any existing buffer is freed and the
  70779. ** pointer copied.
  70780. **
  70781. ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
  70782. ** size limit) then no memory allocation occurs. If the string can be
  70783. ** stored without allocating memory, then it is. If a memory allocation
  70784. ** is required to store the string, then value of pMem is unchanged. In
  70785. ** either case, SQLITE_TOOBIG is returned.
  70786. */
  70787. SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
  70788. Mem *pMem, /* Memory cell to set to string value */
  70789. const char *z, /* String pointer */
  70790. int n, /* Bytes in string, or negative */
  70791. u8 enc, /* Encoding of z. 0 for BLOBs */
  70792. void (*xDel)(void*) /* Destructor function */
  70793. ){
  70794. int nByte = n; /* New value for pMem->n */
  70795. int iLimit; /* Maximum allowed string or blob size */
  70796. u16 flags = 0; /* New value for pMem->flags */
  70797. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  70798. assert( !sqlite3VdbeMemIsRowSet(pMem) );
  70799. /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
  70800. if( !z ){
  70801. sqlite3VdbeMemSetNull(pMem);
  70802. return SQLITE_OK;
  70803. }
  70804. if( pMem->db ){
  70805. iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
  70806. }else{
  70807. iLimit = SQLITE_MAX_LENGTH;
  70808. }
  70809. flags = (enc==0?MEM_Blob:MEM_Str);
  70810. if( nByte<0 ){
  70811. assert( enc!=0 );
  70812. if( enc==SQLITE_UTF8 ){
  70813. nByte = 0x7fffffff & (int)strlen(z);
  70814. }else{
  70815. for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
  70816. }
  70817. flags |= MEM_Term;
  70818. }
  70819. /* The following block sets the new values of Mem.z and Mem.xDel. It
  70820. ** also sets a flag in local variable "flags" to indicate the memory
  70821. ** management (one of MEM_Dyn or MEM_Static).
  70822. */
  70823. if( xDel==SQLITE_TRANSIENT ){
  70824. u32 nAlloc = nByte;
  70825. if( flags&MEM_Term ){
  70826. nAlloc += (enc==SQLITE_UTF8?1:2);
  70827. }
  70828. if( nByte>iLimit ){
  70829. return sqlite3ErrorToParser(pMem->db, SQLITE_TOOBIG);
  70830. }
  70831. testcase( nAlloc==0 );
  70832. testcase( nAlloc==31 );
  70833. testcase( nAlloc==32 );
  70834. if( sqlite3VdbeMemClearAndResize(pMem, (int)MAX(nAlloc,32)) ){
  70835. return SQLITE_NOMEM_BKPT;
  70836. }
  70837. memcpy(pMem->z, z, nAlloc);
  70838. }else{
  70839. sqlite3VdbeMemRelease(pMem);
  70840. pMem->z = (char *)z;
  70841. if( xDel==SQLITE_DYNAMIC ){
  70842. pMem->zMalloc = pMem->z;
  70843. pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
  70844. }else{
  70845. pMem->xDel = xDel;
  70846. flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
  70847. }
  70848. }
  70849. pMem->n = nByte;
  70850. pMem->flags = flags;
  70851. pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
  70852. #ifndef SQLITE_OMIT_UTF16
  70853. if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
  70854. return SQLITE_NOMEM_BKPT;
  70855. }
  70856. #endif
  70857. if( nByte>iLimit ){
  70858. return SQLITE_TOOBIG;
  70859. }
  70860. return SQLITE_OK;
  70861. }
  70862. /*
  70863. ** Move data out of a btree key or data field and into a Mem structure.
  70864. ** The data is payload from the entry that pCur is currently pointing
  70865. ** to. offset and amt determine what portion of the data or key to retrieve.
  70866. ** The result is written into the pMem element.
  70867. **
  70868. ** The pMem object must have been initialized. This routine will use
  70869. ** pMem->zMalloc to hold the content from the btree, if possible. New
  70870. ** pMem->zMalloc space will be allocated if necessary. The calling routine
  70871. ** is responsible for making sure that the pMem object is eventually
  70872. ** destroyed.
  70873. **
  70874. ** If this routine fails for any reason (malloc returns NULL or unable
  70875. ** to read from the disk) then the pMem is left in an inconsistent state.
  70876. */
  70877. static SQLITE_NOINLINE int vdbeMemFromBtreeResize(
  70878. BtCursor *pCur, /* Cursor pointing at record to retrieve. */
  70879. u32 offset, /* Offset from the start of data to return bytes from. */
  70880. u32 amt, /* Number of bytes to return. */
  70881. Mem *pMem /* OUT: Return data in this Mem structure. */
  70882. ){
  70883. int rc;
  70884. pMem->flags = MEM_Null;
  70885. if( sqlite3BtreeMaxRecordSize(pCur)<offset+amt ){
  70886. return SQLITE_CORRUPT_BKPT;
  70887. }
  70888. if( SQLITE_OK==(rc = sqlite3VdbeMemClearAndResize(pMem, amt+1)) ){
  70889. rc = sqlite3BtreePayload(pCur, offset, amt, pMem->z);
  70890. if( rc==SQLITE_OK ){
  70891. pMem->z[amt] = 0; /* Overrun area used when reading malformed records */
  70892. pMem->flags = MEM_Blob;
  70893. pMem->n = (int)amt;
  70894. }else{
  70895. sqlite3VdbeMemRelease(pMem);
  70896. }
  70897. }
  70898. return rc;
  70899. }
  70900. SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
  70901. BtCursor *pCur, /* Cursor pointing at record to retrieve. */
  70902. u32 offset, /* Offset from the start of data to return bytes from. */
  70903. u32 amt, /* Number of bytes to return. */
  70904. Mem *pMem /* OUT: Return data in this Mem structure. */
  70905. ){
  70906. char *zData; /* Data from the btree layer */
  70907. u32 available = 0; /* Number of bytes available on the local btree page */
  70908. int rc = SQLITE_OK; /* Return code */
  70909. assert( sqlite3BtreeCursorIsValid(pCur) );
  70910. assert( !VdbeMemDynamic(pMem) );
  70911. /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
  70912. ** that both the BtShared and database handle mutexes are held. */
  70913. assert( !sqlite3VdbeMemIsRowSet(pMem) );
  70914. zData = (char *)sqlite3BtreePayloadFetch(pCur, &available);
  70915. assert( zData!=0 );
  70916. if( offset+amt<=available ){
  70917. pMem->z = &zData[offset];
  70918. pMem->flags = MEM_Blob|MEM_Ephem;
  70919. pMem->n = (int)amt;
  70920. }else{
  70921. rc = vdbeMemFromBtreeResize(pCur, offset, amt, pMem);
  70922. }
  70923. return rc;
  70924. }
  70925. /*
  70926. ** The pVal argument is known to be a value other than NULL.
  70927. ** Convert it into a string with encoding enc and return a pointer
  70928. ** to a zero-terminated version of that string.
  70929. */
  70930. static SQLITE_NOINLINE const void *valueToText(sqlite3_value* pVal, u8 enc){
  70931. assert( pVal!=0 );
  70932. assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
  70933. assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
  70934. assert( !sqlite3VdbeMemIsRowSet(pVal) );
  70935. assert( (pVal->flags & (MEM_Null))==0 );
  70936. if( pVal->flags & (MEM_Blob|MEM_Str) ){
  70937. if( ExpandBlob(pVal) ) return 0;
  70938. pVal->flags |= MEM_Str;
  70939. if( pVal->enc != (enc & ~SQLITE_UTF16_ALIGNED) ){
  70940. sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
  70941. }
  70942. if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
  70943. assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
  70944. if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
  70945. return 0;
  70946. }
  70947. }
  70948. sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
  70949. }else{
  70950. sqlite3VdbeMemStringify(pVal, enc, 0);
  70951. assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
  70952. }
  70953. assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
  70954. || pVal->db->mallocFailed );
  70955. if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
  70956. assert( sqlite3VdbeMemValidStrRep(pVal) );
  70957. return pVal->z;
  70958. }else{
  70959. return 0;
  70960. }
  70961. }
  70962. /* This function is only available internally, it is not part of the
  70963. ** external API. It works in a similar way to sqlite3_value_text(),
  70964. ** except the data returned is in the encoding specified by the second
  70965. ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
  70966. ** SQLITE_UTF8.
  70967. **
  70968. ** (2006-02-16:) The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
  70969. ** If that is the case, then the result must be aligned on an even byte
  70970. ** boundary.
  70971. */
  70972. SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
  70973. if( !pVal ) return 0;
  70974. assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
  70975. assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
  70976. assert( !sqlite3VdbeMemIsRowSet(pVal) );
  70977. if( (pVal->flags&(MEM_Str|MEM_Term))==(MEM_Str|MEM_Term) && pVal->enc==enc ){
  70978. assert( sqlite3VdbeMemValidStrRep(pVal) );
  70979. return pVal->z;
  70980. }
  70981. if( pVal->flags&MEM_Null ){
  70982. return 0;
  70983. }
  70984. return valueToText(pVal, enc);
  70985. }
  70986. /*
  70987. ** Create a new sqlite3_value object.
  70988. */
  70989. SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
  70990. Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
  70991. if( p ){
  70992. p->flags = MEM_Null;
  70993. p->db = db;
  70994. }
  70995. return p;
  70996. }
  70997. /*
  70998. ** Context object passed by sqlite3Stat4ProbeSetValue() through to
  70999. ** valueNew(). See comments above valueNew() for details.
  71000. */
  71001. struct ValueNewStat4Ctx {
  71002. Parse *pParse;
  71003. Index *pIdx;
  71004. UnpackedRecord **ppRec;
  71005. int iVal;
  71006. };
  71007. /*
  71008. ** Allocate and return a pointer to a new sqlite3_value object. If
  71009. ** the second argument to this function is NULL, the object is allocated
  71010. ** by calling sqlite3ValueNew().
  71011. **
  71012. ** Otherwise, if the second argument is non-zero, then this function is
  71013. ** being called indirectly by sqlite3Stat4ProbeSetValue(). If it has not
  71014. ** already been allocated, allocate the UnpackedRecord structure that
  71015. ** that function will return to its caller here. Then return a pointer to
  71016. ** an sqlite3_value within the UnpackedRecord.a[] array.
  71017. */
  71018. static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){
  71019. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  71020. if( p ){
  71021. UnpackedRecord *pRec = p->ppRec[0];
  71022. if( pRec==0 ){
  71023. Index *pIdx = p->pIdx; /* Index being probed */
  71024. int nByte; /* Bytes of space to allocate */
  71025. int i; /* Counter variable */
  71026. int nCol = pIdx->nColumn; /* Number of index columns including rowid */
  71027. nByte = sizeof(Mem) * nCol + ROUND8(sizeof(UnpackedRecord));
  71028. pRec = (UnpackedRecord*)sqlite3DbMallocZero(db, nByte);
  71029. if( pRec ){
  71030. pRec->pKeyInfo = sqlite3KeyInfoOfIndex(p->pParse, pIdx);
  71031. if( pRec->pKeyInfo ){
  71032. assert( pRec->pKeyInfo->nAllField==nCol );
  71033. assert( pRec->pKeyInfo->enc==ENC(db) );
  71034. pRec->aMem = (Mem *)((u8*)pRec + ROUND8(sizeof(UnpackedRecord)));
  71035. for(i=0; i<nCol; i++){
  71036. pRec->aMem[i].flags = MEM_Null;
  71037. pRec->aMem[i].db = db;
  71038. }
  71039. }else{
  71040. sqlite3DbFreeNN(db, pRec);
  71041. pRec = 0;
  71042. }
  71043. }
  71044. if( pRec==0 ) return 0;
  71045. p->ppRec[0] = pRec;
  71046. }
  71047. pRec->nField = p->iVal+1;
  71048. return &pRec->aMem[p->iVal];
  71049. }
  71050. #else
  71051. UNUSED_PARAMETER(p);
  71052. #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
  71053. return sqlite3ValueNew(db);
  71054. }
  71055. /*
  71056. ** The expression object indicated by the second argument is guaranteed
  71057. ** to be a scalar SQL function. If
  71058. **
  71059. ** * all function arguments are SQL literals,
  71060. ** * one of the SQLITE_FUNC_CONSTANT or _SLOCHNG function flags is set, and
  71061. ** * the SQLITE_FUNC_NEEDCOLL function flag is not set,
  71062. **
  71063. ** then this routine attempts to invoke the SQL function. Assuming no
  71064. ** error occurs, output parameter (*ppVal) is set to point to a value
  71065. ** object containing the result before returning SQLITE_OK.
  71066. **
  71067. ** Affinity aff is applied to the result of the function before returning.
  71068. ** If the result is a text value, the sqlite3_value object uses encoding
  71069. ** enc.
  71070. **
  71071. ** If the conditions above are not met, this function returns SQLITE_OK
  71072. ** and sets (*ppVal) to NULL. Or, if an error occurs, (*ppVal) is set to
  71073. ** NULL and an SQLite error code returned.
  71074. */
  71075. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  71076. static int valueFromFunction(
  71077. sqlite3 *db, /* The database connection */
  71078. Expr *p, /* The expression to evaluate */
  71079. u8 enc, /* Encoding to use */
  71080. u8 aff, /* Affinity to use */
  71081. sqlite3_value **ppVal, /* Write the new value here */
  71082. struct ValueNewStat4Ctx *pCtx /* Second argument for valueNew() */
  71083. ){
  71084. sqlite3_context ctx; /* Context object for function invocation */
  71085. sqlite3_value **apVal = 0; /* Function arguments */
  71086. int nVal = 0; /* Size of apVal[] array */
  71087. FuncDef *pFunc = 0; /* Function definition */
  71088. sqlite3_value *pVal = 0; /* New value */
  71089. int rc = SQLITE_OK; /* Return code */
  71090. ExprList *pList = 0; /* Function arguments */
  71091. int i; /* Iterator variable */
  71092. assert( pCtx!=0 );
  71093. assert( (p->flags & EP_TokenOnly)==0 );
  71094. pList = p->x.pList;
  71095. if( pList ) nVal = pList->nExpr;
  71096. pFunc = sqlite3FindFunction(db, p->u.zToken, nVal, enc, 0);
  71097. assert( pFunc );
  71098. if( (pFunc->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG))==0
  71099. || (pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)
  71100. ){
  71101. return SQLITE_OK;
  71102. }
  71103. if( pList ){
  71104. apVal = (sqlite3_value**)sqlite3DbMallocZero(db, sizeof(apVal[0]) * nVal);
  71105. if( apVal==0 ){
  71106. rc = SQLITE_NOMEM_BKPT;
  71107. goto value_from_function_out;
  71108. }
  71109. for(i=0; i<nVal; i++){
  71110. rc = sqlite3ValueFromExpr(db, pList->a[i].pExpr, enc, aff, &apVal[i]);
  71111. if( apVal[i]==0 || rc!=SQLITE_OK ) goto value_from_function_out;
  71112. }
  71113. }
  71114. pVal = valueNew(db, pCtx);
  71115. if( pVal==0 ){
  71116. rc = SQLITE_NOMEM_BKPT;
  71117. goto value_from_function_out;
  71118. }
  71119. assert( pCtx->pParse->rc==SQLITE_OK );
  71120. memset(&ctx, 0, sizeof(ctx));
  71121. ctx.pOut = pVal;
  71122. ctx.pFunc = pFunc;
  71123. pFunc->xSFunc(&ctx, nVal, apVal);
  71124. if( ctx.isError ){
  71125. rc = ctx.isError;
  71126. sqlite3ErrorMsg(pCtx->pParse, "%s", sqlite3_value_text(pVal));
  71127. }else{
  71128. sqlite3ValueApplyAffinity(pVal, aff, SQLITE_UTF8);
  71129. assert( rc==SQLITE_OK );
  71130. rc = sqlite3VdbeChangeEncoding(pVal, enc);
  71131. if( rc==SQLITE_OK && sqlite3VdbeMemTooBig(pVal) ){
  71132. rc = SQLITE_TOOBIG;
  71133. pCtx->pParse->nErr++;
  71134. }
  71135. }
  71136. pCtx->pParse->rc = rc;
  71137. value_from_function_out:
  71138. if( rc!=SQLITE_OK ){
  71139. pVal = 0;
  71140. }
  71141. if( apVal ){
  71142. for(i=0; i<nVal; i++){
  71143. sqlite3ValueFree(apVal[i]);
  71144. }
  71145. sqlite3DbFreeNN(db, apVal);
  71146. }
  71147. *ppVal = pVal;
  71148. return rc;
  71149. }
  71150. #else
  71151. # define valueFromFunction(a,b,c,d,e,f) SQLITE_OK
  71152. #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
  71153. /*
  71154. ** Extract a value from the supplied expression in the manner described
  71155. ** above sqlite3ValueFromExpr(). Allocate the sqlite3_value object
  71156. ** using valueNew().
  71157. **
  71158. ** If pCtx is NULL and an error occurs after the sqlite3_value object
  71159. ** has been allocated, it is freed before returning. Or, if pCtx is not
  71160. ** NULL, it is assumed that the caller will free any allocated object
  71161. ** in all cases.
  71162. */
  71163. static int valueFromExpr(
  71164. sqlite3 *db, /* The database connection */
  71165. Expr *pExpr, /* The expression to evaluate */
  71166. u8 enc, /* Encoding to use */
  71167. u8 affinity, /* Affinity to use */
  71168. sqlite3_value **ppVal, /* Write the new value here */
  71169. struct ValueNewStat4Ctx *pCtx /* Second argument for valueNew() */
  71170. ){
  71171. int op;
  71172. char *zVal = 0;
  71173. sqlite3_value *pVal = 0;
  71174. int negInt = 1;
  71175. const char *zNeg = "";
  71176. int rc = SQLITE_OK;
  71177. assert( pExpr!=0 );
  71178. while( (op = pExpr->op)==TK_UPLUS || op==TK_SPAN ) pExpr = pExpr->pLeft;
  71179. #if defined(SQLITE_ENABLE_STAT3_OR_STAT4)
  71180. if( op==TK_REGISTER ) op = pExpr->op2;
  71181. #else
  71182. if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
  71183. #endif
  71184. /* Compressed expressions only appear when parsing the DEFAULT clause
  71185. ** on a table column definition, and hence only when pCtx==0. This
  71186. ** check ensures that an EP_TokenOnly expression is never passed down
  71187. ** into valueFromFunction(). */
  71188. assert( (pExpr->flags & EP_TokenOnly)==0 || pCtx==0 );
  71189. if( op==TK_CAST ){
  71190. u8 aff = sqlite3AffinityType(pExpr->u.zToken,0);
  71191. rc = valueFromExpr(db, pExpr->pLeft, enc, aff, ppVal, pCtx);
  71192. testcase( rc!=SQLITE_OK );
  71193. if( *ppVal ){
  71194. sqlite3VdbeMemCast(*ppVal, aff, SQLITE_UTF8);
  71195. sqlite3ValueApplyAffinity(*ppVal, affinity, SQLITE_UTF8);
  71196. }
  71197. return rc;
  71198. }
  71199. /* Handle negative integers in a single step. This is needed in the
  71200. ** case when the value is -9223372036854775808.
  71201. */
  71202. if( op==TK_UMINUS
  71203. && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
  71204. pExpr = pExpr->pLeft;
  71205. op = pExpr->op;
  71206. negInt = -1;
  71207. zNeg = "-";
  71208. }
  71209. if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
  71210. pVal = valueNew(db, pCtx);
  71211. if( pVal==0 ) goto no_mem;
  71212. if( ExprHasProperty(pExpr, EP_IntValue) ){
  71213. sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
  71214. }else{
  71215. zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
  71216. if( zVal==0 ) goto no_mem;
  71217. sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
  71218. }
  71219. if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_BLOB ){
  71220. sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
  71221. }else{
  71222. sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
  71223. }
  71224. assert( (pVal->flags & MEM_IntReal)==0 );
  71225. if( pVal->flags & (MEM_Int|MEM_IntReal|MEM_Real) ){
  71226. testcase( pVal->flags & MEM_Int );
  71227. testcase( pVal->flags & MEM_Real );
  71228. pVal->flags &= ~MEM_Str;
  71229. }
  71230. if( enc!=SQLITE_UTF8 ){
  71231. rc = sqlite3VdbeChangeEncoding(pVal, enc);
  71232. }
  71233. }else if( op==TK_UMINUS ) {
  71234. /* This branch happens for multiple negative signs. Ex: -(-5) */
  71235. if( SQLITE_OK==valueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal,pCtx)
  71236. && pVal!=0
  71237. ){
  71238. sqlite3VdbeMemNumerify(pVal);
  71239. if( pVal->flags & MEM_Real ){
  71240. pVal->u.r = -pVal->u.r;
  71241. }else if( pVal->u.i==SMALLEST_INT64 ){
  71242. pVal->u.r = -(double)SMALLEST_INT64;
  71243. MemSetTypeFlag(pVal, MEM_Real);
  71244. }else{
  71245. pVal->u.i = -pVal->u.i;
  71246. }
  71247. sqlite3ValueApplyAffinity(pVal, affinity, enc);
  71248. }
  71249. }else if( op==TK_NULL ){
  71250. pVal = valueNew(db, pCtx);
  71251. if( pVal==0 ) goto no_mem;
  71252. sqlite3VdbeMemSetNull(pVal);
  71253. }
  71254. #ifndef SQLITE_OMIT_BLOB_LITERAL
  71255. else if( op==TK_BLOB ){
  71256. int nVal;
  71257. assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
  71258. assert( pExpr->u.zToken[1]=='\'' );
  71259. pVal = valueNew(db, pCtx);
  71260. if( !pVal ) goto no_mem;
  71261. zVal = &pExpr->u.zToken[2];
  71262. nVal = sqlite3Strlen30(zVal)-1;
  71263. assert( zVal[nVal]=='\'' );
  71264. sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
  71265. 0, SQLITE_DYNAMIC);
  71266. }
  71267. #endif
  71268. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  71269. else if( op==TK_FUNCTION && pCtx!=0 ){
  71270. rc = valueFromFunction(db, pExpr, enc, affinity, &pVal, pCtx);
  71271. }
  71272. #endif
  71273. else if( op==TK_TRUEFALSE ){
  71274. pVal = valueNew(db, pCtx);
  71275. if( pVal ){
  71276. pVal->flags = MEM_Int;
  71277. pVal->u.i = pExpr->u.zToken[4]==0;
  71278. }
  71279. }
  71280. *ppVal = pVal;
  71281. return rc;
  71282. no_mem:
  71283. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  71284. if( pCtx==0 || pCtx->pParse->nErr==0 )
  71285. #endif
  71286. sqlite3OomFault(db);
  71287. sqlite3DbFree(db, zVal);
  71288. assert( *ppVal==0 );
  71289. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  71290. if( pCtx==0 ) sqlite3ValueFree(pVal);
  71291. #else
  71292. assert( pCtx==0 ); sqlite3ValueFree(pVal);
  71293. #endif
  71294. return SQLITE_NOMEM_BKPT;
  71295. }
  71296. /*
  71297. ** Create a new sqlite3_value object, containing the value of pExpr.
  71298. **
  71299. ** This only works for very simple expressions that consist of one constant
  71300. ** token (i.e. "5", "5.1", "'a string'"). If the expression can
  71301. ** be converted directly into a value, then the value is allocated and
  71302. ** a pointer written to *ppVal. The caller is responsible for deallocating
  71303. ** the value by passing it to sqlite3ValueFree() later on. If the expression
  71304. ** cannot be converted to a value, then *ppVal is set to NULL.
  71305. */
  71306. SQLITE_PRIVATE int sqlite3ValueFromExpr(
  71307. sqlite3 *db, /* The database connection */
  71308. Expr *pExpr, /* The expression to evaluate */
  71309. u8 enc, /* Encoding to use */
  71310. u8 affinity, /* Affinity to use */
  71311. sqlite3_value **ppVal /* Write the new value here */
  71312. ){
  71313. return pExpr ? valueFromExpr(db, pExpr, enc, affinity, ppVal, 0) : 0;
  71314. }
  71315. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  71316. /*
  71317. ** The implementation of the sqlite_record() function. This function accepts
  71318. ** a single argument of any type. The return value is a formatted database
  71319. ** record (a blob) containing the argument value.
  71320. **
  71321. ** This is used to convert the value stored in the 'sample' column of the
  71322. ** sqlite_stat3 table to the record format SQLite uses internally.
  71323. */
  71324. static void recordFunc(
  71325. sqlite3_context *context,
  71326. int argc,
  71327. sqlite3_value **argv
  71328. ){
  71329. const int file_format = 1;
  71330. u32 iSerial; /* Serial type */
  71331. int nSerial; /* Bytes of space for iSerial as varint */
  71332. u32 nVal; /* Bytes of space required for argv[0] */
  71333. int nRet;
  71334. sqlite3 *db;
  71335. u8 *aRet;
  71336. UNUSED_PARAMETER( argc );
  71337. iSerial = sqlite3VdbeSerialType(argv[0], file_format, &nVal);
  71338. nSerial = sqlite3VarintLen(iSerial);
  71339. db = sqlite3_context_db_handle(context);
  71340. nRet = 1 + nSerial + nVal;
  71341. aRet = sqlite3DbMallocRawNN(db, nRet);
  71342. if( aRet==0 ){
  71343. sqlite3_result_error_nomem(context);
  71344. }else{
  71345. aRet[0] = nSerial+1;
  71346. putVarint32(&aRet[1], iSerial);
  71347. sqlite3VdbeSerialPut(&aRet[1+nSerial], argv[0], iSerial);
  71348. sqlite3_result_blob(context, aRet, nRet, SQLITE_TRANSIENT);
  71349. sqlite3DbFreeNN(db, aRet);
  71350. }
  71351. }
  71352. /*
  71353. ** Register built-in functions used to help read ANALYZE data.
  71354. */
  71355. SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void){
  71356. static FuncDef aAnalyzeTableFuncs[] = {
  71357. FUNCTION(sqlite_record, 1, 0, 0, recordFunc),
  71358. };
  71359. sqlite3InsertBuiltinFuncs(aAnalyzeTableFuncs, ArraySize(aAnalyzeTableFuncs));
  71360. }
  71361. /*
  71362. ** Attempt to extract a value from pExpr and use it to construct *ppVal.
  71363. **
  71364. ** If pAlloc is not NULL, then an UnpackedRecord object is created for
  71365. ** pAlloc if one does not exist and the new value is added to the
  71366. ** UnpackedRecord object.
  71367. **
  71368. ** A value is extracted in the following cases:
  71369. **
  71370. ** * (pExpr==0). In this case the value is assumed to be an SQL NULL,
  71371. **
  71372. ** * The expression is a bound variable, and this is a reprepare, or
  71373. **
  71374. ** * The expression is a literal value.
  71375. **
  71376. ** On success, *ppVal is made to point to the extracted value. The caller
  71377. ** is responsible for ensuring that the value is eventually freed.
  71378. */
  71379. static int stat4ValueFromExpr(
  71380. Parse *pParse, /* Parse context */
  71381. Expr *pExpr, /* The expression to extract a value from */
  71382. u8 affinity, /* Affinity to use */
  71383. struct ValueNewStat4Ctx *pAlloc,/* How to allocate space. Or NULL */
  71384. sqlite3_value **ppVal /* OUT: New value object (or NULL) */
  71385. ){
  71386. int rc = SQLITE_OK;
  71387. sqlite3_value *pVal = 0;
  71388. sqlite3 *db = pParse->db;
  71389. /* Skip over any TK_COLLATE nodes */
  71390. pExpr = sqlite3ExprSkipCollate(pExpr);
  71391. assert( pExpr==0 || pExpr->op!=TK_REGISTER || pExpr->op2!=TK_VARIABLE );
  71392. if( !pExpr ){
  71393. pVal = valueNew(db, pAlloc);
  71394. if( pVal ){
  71395. sqlite3VdbeMemSetNull((Mem*)pVal);
  71396. }
  71397. }else if( pExpr->op==TK_VARIABLE && (db->flags & SQLITE_EnableQPSG)==0 ){
  71398. Vdbe *v;
  71399. int iBindVar = pExpr->iColumn;
  71400. sqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar);
  71401. if( (v = pParse->pReprepare)!=0 ){
  71402. pVal = valueNew(db, pAlloc);
  71403. if( pVal ){
  71404. rc = sqlite3VdbeMemCopy((Mem*)pVal, &v->aVar[iBindVar-1]);
  71405. sqlite3ValueApplyAffinity(pVal, affinity, ENC(db));
  71406. pVal->db = pParse->db;
  71407. }
  71408. }
  71409. }else{
  71410. rc = valueFromExpr(db, pExpr, ENC(db), affinity, &pVal, pAlloc);
  71411. }
  71412. assert( pVal==0 || pVal->db==db );
  71413. *ppVal = pVal;
  71414. return rc;
  71415. }
  71416. /*
  71417. ** This function is used to allocate and populate UnpackedRecord
  71418. ** structures intended to be compared against sample index keys stored
  71419. ** in the sqlite_stat4 table.
  71420. **
  71421. ** A single call to this function populates zero or more fields of the
  71422. ** record starting with field iVal (fields are numbered from left to
  71423. ** right starting with 0). A single field is populated if:
  71424. **
  71425. ** * (pExpr==0). In this case the value is assumed to be an SQL NULL,
  71426. **
  71427. ** * The expression is a bound variable, and this is a reprepare, or
  71428. **
  71429. ** * The sqlite3ValueFromExpr() function is able to extract a value
  71430. ** from the expression (i.e. the expression is a literal value).
  71431. **
  71432. ** Or, if pExpr is a TK_VECTOR, one field is populated for each of the
  71433. ** vector components that match either of the two latter criteria listed
  71434. ** above.
  71435. **
  71436. ** Before any value is appended to the record, the affinity of the
  71437. ** corresponding column within index pIdx is applied to it. Before
  71438. ** this function returns, output parameter *pnExtract is set to the
  71439. ** number of values appended to the record.
  71440. **
  71441. ** When this function is called, *ppRec must either point to an object
  71442. ** allocated by an earlier call to this function, or must be NULL. If it
  71443. ** is NULL and a value can be successfully extracted, a new UnpackedRecord
  71444. ** is allocated (and *ppRec set to point to it) before returning.
  71445. **
  71446. ** Unless an error is encountered, SQLITE_OK is returned. It is not an
  71447. ** error if a value cannot be extracted from pExpr. If an error does
  71448. ** occur, an SQLite error code is returned.
  71449. */
  71450. SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
  71451. Parse *pParse, /* Parse context */
  71452. Index *pIdx, /* Index being probed */
  71453. UnpackedRecord **ppRec, /* IN/OUT: Probe record */
  71454. Expr *pExpr, /* The expression to extract a value from */
  71455. int nElem, /* Maximum number of values to append */
  71456. int iVal, /* Array element to populate */
  71457. int *pnExtract /* OUT: Values appended to the record */
  71458. ){
  71459. int rc = SQLITE_OK;
  71460. int nExtract = 0;
  71461. if( pExpr==0 || pExpr->op!=TK_SELECT ){
  71462. int i;
  71463. struct ValueNewStat4Ctx alloc;
  71464. alloc.pParse = pParse;
  71465. alloc.pIdx = pIdx;
  71466. alloc.ppRec = ppRec;
  71467. for(i=0; i<nElem; i++){
  71468. sqlite3_value *pVal = 0;
  71469. Expr *pElem = (pExpr ? sqlite3VectorFieldSubexpr(pExpr, i) : 0);
  71470. u8 aff = sqlite3IndexColumnAffinity(pParse->db, pIdx, iVal+i);
  71471. alloc.iVal = iVal+i;
  71472. rc = stat4ValueFromExpr(pParse, pElem, aff, &alloc, &pVal);
  71473. if( !pVal ) break;
  71474. nExtract++;
  71475. }
  71476. }
  71477. *pnExtract = nExtract;
  71478. return rc;
  71479. }
  71480. /*
  71481. ** Attempt to extract a value from expression pExpr using the methods
  71482. ** as described for sqlite3Stat4ProbeSetValue() above.
  71483. **
  71484. ** If successful, set *ppVal to point to a new value object and return
  71485. ** SQLITE_OK. If no value can be extracted, but no other error occurs
  71486. ** (e.g. OOM), return SQLITE_OK and set *ppVal to NULL. Or, if an error
  71487. ** does occur, return an SQLite error code. The final value of *ppVal
  71488. ** is undefined in this case.
  71489. */
  71490. SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(
  71491. Parse *pParse, /* Parse context */
  71492. Expr *pExpr, /* The expression to extract a value from */
  71493. u8 affinity, /* Affinity to use */
  71494. sqlite3_value **ppVal /* OUT: New value object (or NULL) */
  71495. ){
  71496. return stat4ValueFromExpr(pParse, pExpr, affinity, 0, ppVal);
  71497. }
  71498. /*
  71499. ** Extract the iCol-th column from the nRec-byte record in pRec. Write
  71500. ** the column value into *ppVal. If *ppVal is initially NULL then a new
  71501. ** sqlite3_value object is allocated.
  71502. **
  71503. ** If *ppVal is initially NULL then the caller is responsible for
  71504. ** ensuring that the value written into *ppVal is eventually freed.
  71505. */
  71506. SQLITE_PRIVATE int sqlite3Stat4Column(
  71507. sqlite3 *db, /* Database handle */
  71508. const void *pRec, /* Pointer to buffer containing record */
  71509. int nRec, /* Size of buffer pRec in bytes */
  71510. int iCol, /* Column to extract */
  71511. sqlite3_value **ppVal /* OUT: Extracted value */
  71512. ){
  71513. u32 t = 0; /* a column type code */
  71514. int nHdr; /* Size of the header in the record */
  71515. int iHdr; /* Next unread header byte */
  71516. int iField; /* Next unread data byte */
  71517. int szField = 0; /* Size of the current data field */
  71518. int i; /* Column index */
  71519. u8 *a = (u8*)pRec; /* Typecast byte array */
  71520. Mem *pMem = *ppVal; /* Write result into this Mem object */
  71521. assert( iCol>0 );
  71522. iHdr = getVarint32(a, nHdr);
  71523. if( nHdr>nRec || iHdr>=nHdr ) return SQLITE_CORRUPT_BKPT;
  71524. iField = nHdr;
  71525. for(i=0; i<=iCol; i++){
  71526. iHdr += getVarint32(&a[iHdr], t);
  71527. testcase( iHdr==nHdr );
  71528. testcase( iHdr==nHdr+1 );
  71529. if( iHdr>nHdr ) return SQLITE_CORRUPT_BKPT;
  71530. szField = sqlite3VdbeSerialTypeLen(t);
  71531. iField += szField;
  71532. }
  71533. testcase( iField==nRec );
  71534. testcase( iField==nRec+1 );
  71535. if( iField>nRec ) return SQLITE_CORRUPT_BKPT;
  71536. if( pMem==0 ){
  71537. pMem = *ppVal = sqlite3ValueNew(db);
  71538. if( pMem==0 ) return SQLITE_NOMEM_BKPT;
  71539. }
  71540. sqlite3VdbeSerialGet(&a[iField-szField], t, pMem);
  71541. pMem->enc = ENC(db);
  71542. return SQLITE_OK;
  71543. }
  71544. /*
  71545. ** Unless it is NULL, the argument must be an UnpackedRecord object returned
  71546. ** by an earlier call to sqlite3Stat4ProbeSetValue(). This call deletes
  71547. ** the object.
  71548. */
  71549. SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord *pRec){
  71550. if( pRec ){
  71551. int i;
  71552. int nCol = pRec->pKeyInfo->nAllField;
  71553. Mem *aMem = pRec->aMem;
  71554. sqlite3 *db = aMem[0].db;
  71555. for(i=0; i<nCol; i++){
  71556. sqlite3VdbeMemRelease(&aMem[i]);
  71557. }
  71558. sqlite3KeyInfoUnref(pRec->pKeyInfo);
  71559. sqlite3DbFreeNN(db, pRec);
  71560. }
  71561. }
  71562. #endif /* ifdef SQLITE_ENABLE_STAT4 */
  71563. /*
  71564. ** Change the string value of an sqlite3_value object
  71565. */
  71566. SQLITE_PRIVATE void sqlite3ValueSetStr(
  71567. sqlite3_value *v, /* Value to be set */
  71568. int n, /* Length of string z */
  71569. const void *z, /* Text of the new string */
  71570. u8 enc, /* Encoding to use */
  71571. void (*xDel)(void*) /* Destructor for the string */
  71572. ){
  71573. if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
  71574. }
  71575. /*
  71576. ** Free an sqlite3_value object
  71577. */
  71578. SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
  71579. if( !v ) return;
  71580. sqlite3VdbeMemRelease((Mem *)v);
  71581. sqlite3DbFreeNN(((Mem*)v)->db, v);
  71582. }
  71583. /*
  71584. ** The sqlite3ValueBytes() routine returns the number of bytes in the
  71585. ** sqlite3_value object assuming that it uses the encoding "enc".
  71586. ** The valueBytes() routine is a helper function.
  71587. */
  71588. static SQLITE_NOINLINE int valueBytes(sqlite3_value *pVal, u8 enc){
  71589. return valueToText(pVal, enc)!=0 ? pVal->n : 0;
  71590. }
  71591. SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
  71592. Mem *p = (Mem*)pVal;
  71593. assert( (p->flags & MEM_Null)==0 || (p->flags & (MEM_Str|MEM_Blob))==0 );
  71594. if( (p->flags & MEM_Str)!=0 && pVal->enc==enc ){
  71595. return p->n;
  71596. }
  71597. if( (p->flags & MEM_Blob)!=0 ){
  71598. if( p->flags & MEM_Zero ){
  71599. return p->n + p->u.nZero;
  71600. }else{
  71601. return p->n;
  71602. }
  71603. }
  71604. if( p->flags & MEM_Null ) return 0;
  71605. return valueBytes(pVal, enc);
  71606. }
  71607. /************** End of vdbemem.c *********************************************/
  71608. /************** Begin file vdbeaux.c *****************************************/
  71609. /*
  71610. ** 2003 September 6
  71611. **
  71612. ** The author disclaims copyright to this source code. In place of
  71613. ** a legal notice, here is a blessing:
  71614. **
  71615. ** May you do good and not evil.
  71616. ** May you find forgiveness for yourself and forgive others.
  71617. ** May you share freely, never taking more than you give.
  71618. **
  71619. *************************************************************************
  71620. ** This file contains code used for creating, destroying, and populating
  71621. ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)
  71622. */
  71623. /* #include "sqliteInt.h" */
  71624. /* #include "vdbeInt.h" */
  71625. /*
  71626. ** Create a new virtual database engine.
  71627. */
  71628. SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse *pParse){
  71629. sqlite3 *db = pParse->db;
  71630. Vdbe *p;
  71631. p = sqlite3DbMallocRawNN(db, sizeof(Vdbe) );
  71632. if( p==0 ) return 0;
  71633. memset(&p->aOp, 0, sizeof(Vdbe)-offsetof(Vdbe,aOp));
  71634. p->db = db;
  71635. if( db->pVdbe ){
  71636. db->pVdbe->pPrev = p;
  71637. }
  71638. p->pNext = db->pVdbe;
  71639. p->pPrev = 0;
  71640. db->pVdbe = p;
  71641. p->magic = VDBE_MAGIC_INIT;
  71642. p->pParse = pParse;
  71643. pParse->pVdbe = p;
  71644. assert( pParse->aLabel==0 );
  71645. assert( pParse->nLabel==0 );
  71646. assert( p->nOpAlloc==0 );
  71647. assert( pParse->szOpAlloc==0 );
  71648. sqlite3VdbeAddOp2(p, OP_Init, 0, 1);
  71649. return p;
  71650. }
  71651. /*
  71652. ** Change the error string stored in Vdbe.zErrMsg
  71653. */
  71654. SQLITE_PRIVATE void sqlite3VdbeError(Vdbe *p, const char *zFormat, ...){
  71655. va_list ap;
  71656. sqlite3DbFree(p->db, p->zErrMsg);
  71657. va_start(ap, zFormat);
  71658. p->zErrMsg = sqlite3VMPrintf(p->db, zFormat, ap);
  71659. va_end(ap);
  71660. }
  71661. /*
  71662. ** Remember the SQL string for a prepared statement.
  71663. */
  71664. SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, u8 prepFlags){
  71665. if( p==0 ) return;
  71666. p->prepFlags = prepFlags;
  71667. if( (prepFlags & SQLITE_PREPARE_SAVESQL)==0 ){
  71668. p->expmask = 0;
  71669. }
  71670. assert( p->zSql==0 );
  71671. p->zSql = sqlite3DbStrNDup(p->db, z, n);
  71672. }
  71673. #ifdef SQLITE_ENABLE_NORMALIZE
  71674. /*
  71675. ** Add a new element to the Vdbe->pDblStr list.
  71676. */
  71677. SQLITE_PRIVATE void sqlite3VdbeAddDblquoteStr(sqlite3 *db, Vdbe *p, const char *z){
  71678. if( p ){
  71679. int n = sqlite3Strlen30(z);
  71680. DblquoteStr *pStr = sqlite3DbMallocRawNN(db,
  71681. sizeof(*pStr)+n+1-sizeof(pStr->z));
  71682. if( pStr ){
  71683. pStr->pNextStr = p->pDblStr;
  71684. p->pDblStr = pStr;
  71685. memcpy(pStr->z, z, n+1);
  71686. }
  71687. }
  71688. }
  71689. #endif
  71690. #ifdef SQLITE_ENABLE_NORMALIZE
  71691. /*
  71692. ** zId of length nId is a double-quoted identifier. Check to see if
  71693. ** that identifier is really used as a string literal.
  71694. */
  71695. SQLITE_PRIVATE int sqlite3VdbeUsesDoubleQuotedString(
  71696. Vdbe *pVdbe, /* The prepared statement */
  71697. const char *zId /* The double-quoted identifier, already dequoted */
  71698. ){
  71699. DblquoteStr *pStr;
  71700. assert( zId!=0 );
  71701. if( pVdbe->pDblStr==0 ) return 0;
  71702. for(pStr=pVdbe->pDblStr; pStr; pStr=pStr->pNextStr){
  71703. if( strcmp(zId, pStr->z)==0 ) return 1;
  71704. }
  71705. return 0;
  71706. }
  71707. #endif
  71708. /*
  71709. ** Swap all content between two VDBE structures.
  71710. */
  71711. SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
  71712. Vdbe tmp, *pTmp;
  71713. char *zTmp;
  71714. assert( pA->db==pB->db );
  71715. tmp = *pA;
  71716. *pA = *pB;
  71717. *pB = tmp;
  71718. pTmp = pA->pNext;
  71719. pA->pNext = pB->pNext;
  71720. pB->pNext = pTmp;
  71721. pTmp = pA->pPrev;
  71722. pA->pPrev = pB->pPrev;
  71723. pB->pPrev = pTmp;
  71724. zTmp = pA->zSql;
  71725. pA->zSql = pB->zSql;
  71726. pB->zSql = zTmp;
  71727. #if 0
  71728. zTmp = pA->zNormSql;
  71729. pA->zNormSql = pB->zNormSql;
  71730. pB->zNormSql = zTmp;
  71731. #endif
  71732. pB->expmask = pA->expmask;
  71733. pB->prepFlags = pA->prepFlags;
  71734. memcpy(pB->aCounter, pA->aCounter, sizeof(pB->aCounter));
  71735. pB->aCounter[SQLITE_STMTSTATUS_REPREPARE]++;
  71736. }
  71737. /*
  71738. ** Resize the Vdbe.aOp array so that it is at least nOp elements larger
  71739. ** than its current size. nOp is guaranteed to be less than or equal
  71740. ** to 1024/sizeof(Op).
  71741. **
  71742. ** If an out-of-memory error occurs while resizing the array, return
  71743. ** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain
  71744. ** unchanged (this is so that any opcodes already allocated can be
  71745. ** correctly deallocated along with the rest of the Vdbe).
  71746. */
  71747. static int growOpArray(Vdbe *v, int nOp){
  71748. VdbeOp *pNew;
  71749. Parse *p = v->pParse;
  71750. /* The SQLITE_TEST_REALLOC_STRESS compile-time option is designed to force
  71751. ** more frequent reallocs and hence provide more opportunities for
  71752. ** simulated OOM faults. SQLITE_TEST_REALLOC_STRESS is generally used
  71753. ** during testing only. With SQLITE_TEST_REALLOC_STRESS grow the op array
  71754. ** by the minimum* amount required until the size reaches 512. Normal
  71755. ** operation (without SQLITE_TEST_REALLOC_STRESS) is to double the current
  71756. ** size of the op array or add 1KB of space, whichever is smaller. */
  71757. #ifdef SQLITE_TEST_REALLOC_STRESS
  71758. sqlite3_int64 nNew = (v->nOpAlloc>=512 ? 2*(sqlite3_int64)v->nOpAlloc
  71759. : (sqlite3_int64)v->nOpAlloc+nOp);
  71760. #else
  71761. sqlite3_int64 nNew = (v->nOpAlloc ? 2*(sqlite3_int64)v->nOpAlloc
  71762. : (sqlite3_int64)(1024/sizeof(Op)));
  71763. UNUSED_PARAMETER(nOp);
  71764. #endif
  71765. /* Ensure that the size of a VDBE does not grow too large */
  71766. if( nNew > p->db->aLimit[SQLITE_LIMIT_VDBE_OP] ){
  71767. sqlite3OomFault(p->db);
  71768. return SQLITE_NOMEM;
  71769. }
  71770. assert( nOp<=(1024/sizeof(Op)) );
  71771. assert( nNew>=(v->nOpAlloc+nOp) );
  71772. pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op));
  71773. if( pNew ){
  71774. p->szOpAlloc = sqlite3DbMallocSize(p->db, pNew);
  71775. v->nOpAlloc = p->szOpAlloc/sizeof(Op);
  71776. v->aOp = pNew;
  71777. }
  71778. return (pNew ? SQLITE_OK : SQLITE_NOMEM_BKPT);
  71779. }
  71780. #ifdef SQLITE_DEBUG
  71781. /* This routine is just a convenient place to set a breakpoint that will
  71782. ** fire after each opcode is inserted and displayed using
  71783. ** "PRAGMA vdbe_addoptrace=on".
  71784. */
  71785. static void test_addop_breakpoint(void){
  71786. static int n = 0;
  71787. n++;
  71788. }
  71789. #endif
  71790. /*
  71791. ** Add a new instruction to the list of instructions current in the
  71792. ** VDBE. Return the address of the new instruction.
  71793. **
  71794. ** Parameters:
  71795. **
  71796. ** p Pointer to the VDBE
  71797. **
  71798. ** op The opcode for this instruction
  71799. **
  71800. ** p1, p2, p3 Operands
  71801. **
  71802. ** Use the sqlite3VdbeResolveLabel() function to fix an address and
  71803. ** the sqlite3VdbeChangeP4() function to change the value of the P4
  71804. ** operand.
  71805. */
  71806. static SQLITE_NOINLINE int growOp3(Vdbe *p, int op, int p1, int p2, int p3){
  71807. assert( p->nOpAlloc<=p->nOp );
  71808. if( growOpArray(p, 1) ) return 1;
  71809. assert( p->nOpAlloc>p->nOp );
  71810. return sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  71811. }
  71812. SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
  71813. int i;
  71814. VdbeOp *pOp;
  71815. i = p->nOp;
  71816. assert( p->magic==VDBE_MAGIC_INIT );
  71817. assert( op>=0 && op<0xff );
  71818. if( p->nOpAlloc<=i ){
  71819. return growOp3(p, op, p1, p2, p3);
  71820. }
  71821. p->nOp++;
  71822. pOp = &p->aOp[i];
  71823. pOp->opcode = (u8)op;
  71824. pOp->p5 = 0;
  71825. pOp->p1 = p1;
  71826. pOp->p2 = p2;
  71827. pOp->p3 = p3;
  71828. pOp->p4.p = 0;
  71829. pOp->p4type = P4_NOTUSED;
  71830. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  71831. pOp->zComment = 0;
  71832. #endif
  71833. #ifdef SQLITE_DEBUG
  71834. if( p->db->flags & SQLITE_VdbeAddopTrace ){
  71835. sqlite3VdbePrintOp(0, i, &p->aOp[i]);
  71836. test_addop_breakpoint();
  71837. }
  71838. #endif
  71839. #ifdef VDBE_PROFILE
  71840. pOp->cycles = 0;
  71841. pOp->cnt = 0;
  71842. #endif
  71843. #ifdef SQLITE_VDBE_COVERAGE
  71844. pOp->iSrcLine = 0;
  71845. #endif
  71846. return i;
  71847. }
  71848. SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
  71849. return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
  71850. }
  71851. SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
  71852. return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
  71853. }
  71854. SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
  71855. return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
  71856. }
  71857. /* Generate code for an unconditional jump to instruction iDest
  71858. */
  71859. SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe *p, int iDest){
  71860. return sqlite3VdbeAddOp3(p, OP_Goto, 0, iDest, 0);
  71861. }
  71862. /* Generate code to cause the string zStr to be loaded into
  71863. ** register iDest
  71864. */
  71865. SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe *p, int iDest, const char *zStr){
  71866. return sqlite3VdbeAddOp4(p, OP_String8, 0, iDest, 0, zStr, 0);
  71867. }
  71868. /*
  71869. ** Generate code that initializes multiple registers to string or integer
  71870. ** constants. The registers begin with iDest and increase consecutively.
  71871. ** One register is initialized for each characgter in zTypes[]. For each
  71872. ** "s" character in zTypes[], the register is a string if the argument is
  71873. ** not NULL, or OP_Null if the value is a null pointer. For each "i" character
  71874. ** in zTypes[], the register is initialized to an integer.
  71875. **
  71876. ** If the input string does not end with "X" then an OP_ResultRow instruction
  71877. ** is generated for the values inserted.
  71878. */
  71879. SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe *p, int iDest, const char *zTypes, ...){
  71880. va_list ap;
  71881. int i;
  71882. char c;
  71883. va_start(ap, zTypes);
  71884. for(i=0; (c = zTypes[i])!=0; i++){
  71885. if( c=='s' ){
  71886. const char *z = va_arg(ap, const char*);
  71887. sqlite3VdbeAddOp4(p, z==0 ? OP_Null : OP_String8, 0, iDest+i, 0, z, 0);
  71888. }else if( c=='i' ){
  71889. sqlite3VdbeAddOp2(p, OP_Integer, va_arg(ap, int), iDest+i);
  71890. }else{
  71891. goto skip_op_resultrow;
  71892. }
  71893. }
  71894. sqlite3VdbeAddOp2(p, OP_ResultRow, iDest, i);
  71895. skip_op_resultrow:
  71896. va_end(ap);
  71897. }
  71898. /*
  71899. ** Add an opcode that includes the p4 value as a pointer.
  71900. */
  71901. SQLITE_PRIVATE int sqlite3VdbeAddOp4(
  71902. Vdbe *p, /* Add the opcode to this VM */
  71903. int op, /* The new opcode */
  71904. int p1, /* The P1 operand */
  71905. int p2, /* The P2 operand */
  71906. int p3, /* The P3 operand */
  71907. const char *zP4, /* The P4 operand */
  71908. int p4type /* P4 operand type */
  71909. ){
  71910. int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  71911. sqlite3VdbeChangeP4(p, addr, zP4, p4type);
  71912. return addr;
  71913. }
  71914. /*
  71915. ** Add an opcode that includes the p4 value with a P4_INT64 or
  71916. ** P4_REAL type.
  71917. */
  71918. SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(
  71919. Vdbe *p, /* Add the opcode to this VM */
  71920. int op, /* The new opcode */
  71921. int p1, /* The P1 operand */
  71922. int p2, /* The P2 operand */
  71923. int p3, /* The P3 operand */
  71924. const u8 *zP4, /* The P4 operand */
  71925. int p4type /* P4 operand type */
  71926. ){
  71927. char *p4copy = sqlite3DbMallocRawNN(sqlite3VdbeDb(p), 8);
  71928. if( p4copy ) memcpy(p4copy, zP4, 8);
  71929. return sqlite3VdbeAddOp4(p, op, p1, p2, p3, p4copy, p4type);
  71930. }
  71931. #ifndef SQLITE_OMIT_EXPLAIN
  71932. /*
  71933. ** Return the address of the current EXPLAIN QUERY PLAN baseline.
  71934. ** 0 means "none".
  71935. */
  71936. SQLITE_PRIVATE int sqlite3VdbeExplainParent(Parse *pParse){
  71937. VdbeOp *pOp;
  71938. if( pParse->addrExplain==0 ) return 0;
  71939. pOp = sqlite3VdbeGetOp(pParse->pVdbe, pParse->addrExplain);
  71940. return pOp->p2;
  71941. }
  71942. /*
  71943. ** Set a debugger breakpoint on the following routine in order to
  71944. ** monitor the EXPLAIN QUERY PLAN code generation.
  71945. */
  71946. #if defined(SQLITE_DEBUG)
  71947. SQLITE_PRIVATE void sqlite3ExplainBreakpoint(const char *z1, const char *z2){
  71948. (void)z1;
  71949. (void)z2;
  71950. }
  71951. #endif
  71952. /*
  71953. ** Add a new OP_ opcode.
  71954. **
  71955. ** If the bPush flag is true, then make this opcode the parent for
  71956. ** subsequent Explains until sqlite3VdbeExplainPop() is called.
  71957. */
  71958. SQLITE_PRIVATE void sqlite3VdbeExplain(Parse *pParse, u8 bPush, const char *zFmt, ...){
  71959. #ifndef SQLITE_DEBUG
  71960. /* Always include the OP_Explain opcodes if SQLITE_DEBUG is defined.
  71961. ** But omit them (for performance) during production builds */
  71962. if( pParse->explain==2 )
  71963. #endif
  71964. {
  71965. char *zMsg;
  71966. Vdbe *v;
  71967. va_list ap;
  71968. int iThis;
  71969. va_start(ap, zFmt);
  71970. zMsg = sqlite3VMPrintf(pParse->db, zFmt, ap);
  71971. va_end(ap);
  71972. v = pParse->pVdbe;
  71973. iThis = v->nOp;
  71974. sqlite3VdbeAddOp4(v, OP_Explain, iThis, pParse->addrExplain, 0,
  71975. zMsg, P4_DYNAMIC);
  71976. sqlite3ExplainBreakpoint(bPush?"PUSH":"", sqlite3VdbeGetOp(v,-1)->p4.z);
  71977. if( bPush){
  71978. pParse->addrExplain = iThis;
  71979. }
  71980. }
  71981. }
  71982. /*
  71983. ** Pop the EXPLAIN QUERY PLAN stack one level.
  71984. */
  71985. SQLITE_PRIVATE void sqlite3VdbeExplainPop(Parse *pParse){
  71986. sqlite3ExplainBreakpoint("POP", 0);
  71987. pParse->addrExplain = sqlite3VdbeExplainParent(pParse);
  71988. }
  71989. #endif /* SQLITE_OMIT_EXPLAIN */
  71990. /*
  71991. ** Add an OP_ParseSchema opcode. This routine is broken out from
  71992. ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
  71993. ** as having been used.
  71994. **
  71995. ** The zWhere string must have been obtained from sqlite3_malloc().
  71996. ** This routine will take ownership of the allocated memory.
  71997. */
  71998. SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
  71999. int j;
  72000. sqlite3VdbeAddOp4(p, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
  72001. for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
  72002. }
  72003. /*
  72004. ** Add an opcode that includes the p4 value as an integer.
  72005. */
  72006. SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
  72007. Vdbe *p, /* Add the opcode to this VM */
  72008. int op, /* The new opcode */
  72009. int p1, /* The P1 operand */
  72010. int p2, /* The P2 operand */
  72011. int p3, /* The P3 operand */
  72012. int p4 /* The P4 operand as an integer */
  72013. ){
  72014. int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  72015. if( p->db->mallocFailed==0 ){
  72016. VdbeOp *pOp = &p->aOp[addr];
  72017. pOp->p4type = P4_INT32;
  72018. pOp->p4.i = p4;
  72019. }
  72020. return addr;
  72021. }
  72022. /* Insert the end of a co-routine
  72023. */
  72024. SQLITE_PRIVATE void sqlite3VdbeEndCoroutine(Vdbe *v, int regYield){
  72025. sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
  72026. /* Clear the temporary register cache, thereby ensuring that each
  72027. ** co-routine has its own independent set of registers, because co-routines
  72028. ** might expect their registers to be preserved across an OP_Yield, and
  72029. ** that could cause problems if two or more co-routines are using the same
  72030. ** temporary register.
  72031. */
  72032. v->pParse->nTempReg = 0;
  72033. v->pParse->nRangeReg = 0;
  72034. }
  72035. /*
  72036. ** Create a new symbolic label for an instruction that has yet to be
  72037. ** coded. The symbolic label is really just a negative number. The
  72038. ** label can be used as the P2 value of an operation. Later, when
  72039. ** the label is resolved to a specific address, the VDBE will scan
  72040. ** through its operation list and change all values of P2 which match
  72041. ** the label into the resolved address.
  72042. **
  72043. ** The VDBE knows that a P2 value is a label because labels are
  72044. ** always negative and P2 values are suppose to be non-negative.
  72045. ** Hence, a negative P2 value is a label that has yet to be resolved.
  72046. ** (Later:) This is only true for opcodes that have the OPFLG_JUMP
  72047. ** property.
  72048. **
  72049. ** Variable usage notes:
  72050. **
  72051. ** Parse.aLabel[x] Stores the address that the x-th label resolves
  72052. ** into. For testing (SQLITE_DEBUG), unresolved
  72053. ** labels stores -1, but that is not required.
  72054. ** Parse.nLabelAlloc Number of slots allocated to Parse.aLabel[]
  72055. ** Parse.nLabel The *negative* of the number of labels that have
  72056. ** been issued. The negative is stored because
  72057. ** that gives a performance improvement over storing
  72058. ** the equivalent positive value.
  72059. */
  72060. SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Parse *pParse){
  72061. return --pParse->nLabel;
  72062. }
  72063. /*
  72064. ** Resolve label "x" to be the address of the next instruction to
  72065. ** be inserted. The parameter "x" must have been obtained from
  72066. ** a prior call to sqlite3VdbeMakeLabel().
  72067. */
  72068. static SQLITE_NOINLINE void resizeResolveLabel(Parse *p, Vdbe *v, int j){
  72069. int nNewSize = 10 - p->nLabel;
  72070. p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
  72071. nNewSize*sizeof(p->aLabel[0]));
  72072. if( p->aLabel==0 ){
  72073. p->nLabelAlloc = 0;
  72074. }else{
  72075. #ifdef SQLITE_DEBUG
  72076. int i;
  72077. for(i=p->nLabelAlloc; i<nNewSize; i++) p->aLabel[i] = -1;
  72078. #endif
  72079. p->nLabelAlloc = nNewSize;
  72080. p->aLabel[j] = v->nOp;
  72081. }
  72082. }
  72083. SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *v, int x){
  72084. Parse *p = v->pParse;
  72085. int j = ADDR(x);
  72086. assert( v->magic==VDBE_MAGIC_INIT );
  72087. assert( j<-p->nLabel );
  72088. assert( j>=0 );
  72089. #ifdef SQLITE_DEBUG
  72090. if( p->db->flags & SQLITE_VdbeAddopTrace ){
  72091. printf("RESOLVE LABEL %d to %d\n", x, v->nOp);
  72092. }
  72093. #endif
  72094. if( p->nLabelAlloc + p->nLabel < 0 ){
  72095. resizeResolveLabel(p,v,j);
  72096. }else{
  72097. assert( p->aLabel[j]==(-1) ); /* Labels may only be resolved once */
  72098. p->aLabel[j] = v->nOp;
  72099. }
  72100. }
  72101. /*
  72102. ** Mark the VDBE as one that can only be run one time.
  72103. */
  72104. SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
  72105. p->runOnlyOnce = 1;
  72106. }
  72107. /*
  72108. ** Mark the VDBE as one that can only be run multiple times.
  72109. */
  72110. SQLITE_PRIVATE void sqlite3VdbeReusable(Vdbe *p){
  72111. p->runOnlyOnce = 0;
  72112. }
  72113. #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
  72114. /*
  72115. ** The following type and function are used to iterate through all opcodes
  72116. ** in a Vdbe main program and each of the sub-programs (triggers) it may
  72117. ** invoke directly or indirectly. It should be used as follows:
  72118. **
  72119. ** Op *pOp;
  72120. ** VdbeOpIter sIter;
  72121. **
  72122. ** memset(&sIter, 0, sizeof(sIter));
  72123. ** sIter.v = v; // v is of type Vdbe*
  72124. ** while( (pOp = opIterNext(&sIter)) ){
  72125. ** // Do something with pOp
  72126. ** }
  72127. ** sqlite3DbFree(v->db, sIter.apSub);
  72128. **
  72129. */
  72130. typedef struct VdbeOpIter VdbeOpIter;
  72131. struct VdbeOpIter {
  72132. Vdbe *v; /* Vdbe to iterate through the opcodes of */
  72133. SubProgram **apSub; /* Array of subprograms */
  72134. int nSub; /* Number of entries in apSub */
  72135. int iAddr; /* Address of next instruction to return */
  72136. int iSub; /* 0 = main program, 1 = first sub-program etc. */
  72137. };
  72138. static Op *opIterNext(VdbeOpIter *p){
  72139. Vdbe *v = p->v;
  72140. Op *pRet = 0;
  72141. Op *aOp;
  72142. int nOp;
  72143. if( p->iSub<=p->nSub ){
  72144. if( p->iSub==0 ){
  72145. aOp = v->aOp;
  72146. nOp = v->nOp;
  72147. }else{
  72148. aOp = p->apSub[p->iSub-1]->aOp;
  72149. nOp = p->apSub[p->iSub-1]->nOp;
  72150. }
  72151. assert( p->iAddr<nOp );
  72152. pRet = &aOp[p->iAddr];
  72153. p->iAddr++;
  72154. if( p->iAddr==nOp ){
  72155. p->iSub++;
  72156. p->iAddr = 0;
  72157. }
  72158. if( pRet->p4type==P4_SUBPROGRAM ){
  72159. int nByte = (p->nSub+1)*sizeof(SubProgram*);
  72160. int j;
  72161. for(j=0; j<p->nSub; j++){
  72162. if( p->apSub[j]==pRet->p4.pProgram ) break;
  72163. }
  72164. if( j==p->nSub ){
  72165. p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
  72166. if( !p->apSub ){
  72167. pRet = 0;
  72168. }else{
  72169. p->apSub[p->nSub++] = pRet->p4.pProgram;
  72170. }
  72171. }
  72172. }
  72173. }
  72174. return pRet;
  72175. }
  72176. /*
  72177. ** Check if the program stored in the VM associated with pParse may
  72178. ** throw an ABORT exception (causing the statement, but not entire transaction
  72179. ** to be rolled back). This condition is true if the main program or any
  72180. ** sub-programs contains any of the following:
  72181. **
  72182. ** * OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
  72183. ** * OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
  72184. ** * OP_Destroy
  72185. ** * OP_VUpdate
  72186. ** * OP_VRename
  72187. ** * OP_FkCounter with P2==0 (immediate foreign key constraint)
  72188. ** * OP_CreateBtree/BTREE_INTKEY and OP_InitCoroutine
  72189. ** (for CREATE TABLE AS SELECT ...)
  72190. **
  72191. ** Then check that the value of Parse.mayAbort is true if an
  72192. ** ABORT may be thrown, or false otherwise. Return true if it does
  72193. ** match, or false otherwise. This function is intended to be used as
  72194. ** part of an assert statement in the compiler. Similar to:
  72195. **
  72196. ** assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
  72197. */
  72198. SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
  72199. int hasAbort = 0;
  72200. int hasFkCounter = 0;
  72201. int hasCreateTable = 0;
  72202. int hasCreateIndex = 0;
  72203. int hasInitCoroutine = 0;
  72204. Op *pOp;
  72205. VdbeOpIter sIter;
  72206. memset(&sIter, 0, sizeof(sIter));
  72207. sIter.v = v;
  72208. while( (pOp = opIterNext(&sIter))!=0 ){
  72209. int opcode = pOp->opcode;
  72210. if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
  72211. || opcode==OP_VDestroy
  72212. || (opcode==OP_Function0 && pOp->p4.pFunc->funcFlags&SQLITE_FUNC_INTERNAL)
  72213. || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
  72214. && ((pOp->p1)!=SQLITE_OK && pOp->p2==OE_Abort))
  72215. ){
  72216. hasAbort = 1;
  72217. break;
  72218. }
  72219. if( opcode==OP_CreateBtree && pOp->p3==BTREE_INTKEY ) hasCreateTable = 1;
  72220. if( mayAbort ){
  72221. /* hasCreateIndex may also be set for some DELETE statements that use
  72222. ** OP_Clear. So this routine may end up returning true in the case
  72223. ** where a "DELETE FROM tbl" has a statement-journal but does not
  72224. ** require one. This is not so bad - it is an inefficiency, not a bug. */
  72225. if( opcode==OP_CreateBtree && pOp->p3==BTREE_BLOBKEY ) hasCreateIndex = 1;
  72226. if( opcode==OP_Clear ) hasCreateIndex = 1;
  72227. }
  72228. if( opcode==OP_InitCoroutine ) hasInitCoroutine = 1;
  72229. #ifndef SQLITE_OMIT_FOREIGN_KEY
  72230. if( opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1 ){
  72231. hasFkCounter = 1;
  72232. }
  72233. #endif
  72234. }
  72235. sqlite3DbFree(v->db, sIter.apSub);
  72236. /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
  72237. ** If malloc failed, then the while() loop above may not have iterated
  72238. ** through all opcodes and hasAbort may be set incorrectly. Return
  72239. ** true for this case to prevent the assert() in the callers frame
  72240. ** from failing. */
  72241. return ( v->db->mallocFailed || hasAbort==mayAbort || hasFkCounter
  72242. || (hasCreateTable && hasInitCoroutine) || hasCreateIndex
  72243. );
  72244. }
  72245. #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
  72246. #ifdef SQLITE_DEBUG
  72247. /*
  72248. ** Increment the nWrite counter in the VDBE if the cursor is not an
  72249. ** ephemeral cursor, or if the cursor argument is NULL.
  72250. */
  72251. SQLITE_PRIVATE void sqlite3VdbeIncrWriteCounter(Vdbe *p, VdbeCursor *pC){
  72252. if( pC==0
  72253. || (pC->eCurType!=CURTYPE_SORTER
  72254. && pC->eCurType!=CURTYPE_PSEUDO
  72255. && !pC->isEphemeral)
  72256. ){
  72257. p->nWrite++;
  72258. }
  72259. }
  72260. #endif
  72261. #ifdef SQLITE_DEBUG
  72262. /*
  72263. ** Assert if an Abort at this point in time might result in a corrupt
  72264. ** database.
  72265. */
  72266. SQLITE_PRIVATE void sqlite3VdbeAssertAbortable(Vdbe *p){
  72267. assert( p->nWrite==0 || p->usesStmtJournal );
  72268. }
  72269. #endif
  72270. /*
  72271. ** This routine is called after all opcodes have been inserted. It loops
  72272. ** through all the opcodes and fixes up some details.
  72273. **
  72274. ** (1) For each jump instruction with a negative P2 value (a label)
  72275. ** resolve the P2 value to an actual address.
  72276. **
  72277. ** (2) Compute the maximum number of arguments used by any SQL function
  72278. ** and store that value in *pMaxFuncArgs.
  72279. **
  72280. ** (3) Update the Vdbe.readOnly and Vdbe.bIsReader flags to accurately
  72281. ** indicate what the prepared statement actually does.
  72282. **
  72283. ** (4) Initialize the p4.xAdvance pointer on opcodes that use it.
  72284. **
  72285. ** (5) Reclaim the memory allocated for storing labels.
  72286. **
  72287. ** This routine will only function correctly if the mkopcodeh.tcl generator
  72288. ** script numbers the opcodes correctly. Changes to this routine must be
  72289. ** coordinated with changes to mkopcodeh.tcl.
  72290. */
  72291. static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
  72292. int nMaxArgs = *pMaxFuncArgs;
  72293. Op *pOp;
  72294. Parse *pParse = p->pParse;
  72295. int *aLabel = pParse->aLabel;
  72296. p->readOnly = 1;
  72297. p->bIsReader = 0;
  72298. pOp = &p->aOp[p->nOp-1];
  72299. while(1){
  72300. /* Only JUMP opcodes and the short list of special opcodes in the switch
  72301. ** below need to be considered. The mkopcodeh.tcl generator script groups
  72302. ** all these opcodes together near the front of the opcode list. Skip
  72303. ** any opcode that does not need processing by virtual of the fact that
  72304. ** it is larger than SQLITE_MX_JUMP_OPCODE, as a performance optimization.
  72305. */
  72306. if( pOp->opcode<=SQLITE_MX_JUMP_OPCODE ){
  72307. /* NOTE: Be sure to update mkopcodeh.tcl when adding or removing
  72308. ** cases from this switch! */
  72309. switch( pOp->opcode ){
  72310. case OP_Transaction: {
  72311. if( pOp->p2!=0 ) p->readOnly = 0;
  72312. /* fall thru */
  72313. }
  72314. case OP_AutoCommit:
  72315. case OP_Savepoint: {
  72316. p->bIsReader = 1;
  72317. break;
  72318. }
  72319. #ifndef SQLITE_OMIT_WAL
  72320. case OP_Checkpoint:
  72321. #endif
  72322. case OP_Vacuum:
  72323. case OP_JournalMode: {
  72324. p->readOnly = 0;
  72325. p->bIsReader = 1;
  72326. break;
  72327. }
  72328. case OP_Next:
  72329. case OP_SorterNext: {
  72330. pOp->p4.xAdvance = sqlite3BtreeNext;
  72331. pOp->p4type = P4_ADVANCE;
  72332. /* The code generator never codes any of these opcodes as a jump
  72333. ** to a label. They are always coded as a jump backwards to a
  72334. ** known address */
  72335. assert( pOp->p2>=0 );
  72336. break;
  72337. }
  72338. case OP_Prev: {
  72339. pOp->p4.xAdvance = sqlite3BtreePrevious;
  72340. pOp->p4type = P4_ADVANCE;
  72341. /* The code generator never codes any of these opcodes as a jump
  72342. ** to a label. They are always coded as a jump backwards to a
  72343. ** known address */
  72344. assert( pOp->p2>=0 );
  72345. break;
  72346. }
  72347. #ifndef SQLITE_OMIT_VIRTUALTABLE
  72348. case OP_VUpdate: {
  72349. if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
  72350. break;
  72351. }
  72352. case OP_VFilter: {
  72353. int n;
  72354. assert( (pOp - p->aOp) >= 3 );
  72355. assert( pOp[-1].opcode==OP_Integer );
  72356. n = pOp[-1].p1;
  72357. if( n>nMaxArgs ) nMaxArgs = n;
  72358. /* Fall through into the default case */
  72359. }
  72360. #endif
  72361. default: {
  72362. if( pOp->p2<0 ){
  72363. /* The mkopcodeh.tcl script has so arranged things that the only
  72364. ** non-jump opcodes less than SQLITE_MX_JUMP_CODE are guaranteed to
  72365. ** have non-negative values for P2. */
  72366. assert( (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_JUMP)!=0 );
  72367. assert( ADDR(pOp->p2)<-pParse->nLabel );
  72368. pOp->p2 = aLabel[ADDR(pOp->p2)];
  72369. }
  72370. break;
  72371. }
  72372. }
  72373. /* The mkopcodeh.tcl script has so arranged things that the only
  72374. ** non-jump opcodes less than SQLITE_MX_JUMP_CODE are guaranteed to
  72375. ** have non-negative values for P2. */
  72376. assert( (sqlite3OpcodeProperty[pOp->opcode]&OPFLG_JUMP)==0 || pOp->p2>=0);
  72377. }
  72378. if( pOp==p->aOp ) break;
  72379. pOp--;
  72380. }
  72381. sqlite3DbFree(p->db, pParse->aLabel);
  72382. pParse->aLabel = 0;
  72383. pParse->nLabel = 0;
  72384. *pMaxFuncArgs = nMaxArgs;
  72385. assert( p->bIsReader!=0 || DbMaskAllZero(p->btreeMask) );
  72386. }
  72387. /*
  72388. ** Return the address of the next instruction to be inserted.
  72389. */
  72390. SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
  72391. assert( p->magic==VDBE_MAGIC_INIT );
  72392. return p->nOp;
  72393. }
  72394. /*
  72395. ** Verify that at least N opcode slots are available in p without
  72396. ** having to malloc for more space (except when compiled using
  72397. ** SQLITE_TEST_REALLOC_STRESS). This interface is used during testing
  72398. ** to verify that certain calls to sqlite3VdbeAddOpList() can never
  72399. ** fail due to a OOM fault and hence that the return value from
  72400. ** sqlite3VdbeAddOpList() will always be non-NULL.
  72401. */
  72402. #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
  72403. SQLITE_PRIVATE void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N){
  72404. assert( p->nOp + N <= p->nOpAlloc );
  72405. }
  72406. #endif
  72407. /*
  72408. ** Verify that the VM passed as the only argument does not contain
  72409. ** an OP_ResultRow opcode. Fail an assert() if it does. This is used
  72410. ** by code in pragma.c to ensure that the implementation of certain
  72411. ** pragmas comports with the flags specified in the mkpragmatab.tcl
  72412. ** script.
  72413. */
  72414. #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
  72415. SQLITE_PRIVATE void sqlite3VdbeVerifyNoResultRow(Vdbe *p){
  72416. int i;
  72417. for(i=0; i<p->nOp; i++){
  72418. assert( p->aOp[i].opcode!=OP_ResultRow );
  72419. }
  72420. }
  72421. #endif
  72422. /*
  72423. ** Generate code (a single OP_Abortable opcode) that will
  72424. ** verify that the VDBE program can safely call Abort in the current
  72425. ** context.
  72426. */
  72427. #if defined(SQLITE_DEBUG)
  72428. SQLITE_PRIVATE void sqlite3VdbeVerifyAbortable(Vdbe *p, int onError){
  72429. if( onError==OE_Abort ) sqlite3VdbeAddOp0(p, OP_Abortable);
  72430. }
  72431. #endif
  72432. /*
  72433. ** This function returns a pointer to the array of opcodes associated with
  72434. ** the Vdbe passed as the first argument. It is the callers responsibility
  72435. ** to arrange for the returned array to be eventually freed using the
  72436. ** vdbeFreeOpArray() function.
  72437. **
  72438. ** Before returning, *pnOp is set to the number of entries in the returned
  72439. ** array. Also, *pnMaxArg is set to the larger of its current value and
  72440. ** the number of entries in the Vdbe.apArg[] array required to execute the
  72441. ** returned program.
  72442. */
  72443. SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
  72444. VdbeOp *aOp = p->aOp;
  72445. assert( aOp && !p->db->mallocFailed );
  72446. /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
  72447. assert( DbMaskAllZero(p->btreeMask) );
  72448. resolveP2Values(p, pnMaxArg);
  72449. *pnOp = p->nOp;
  72450. p->aOp = 0;
  72451. return aOp;
  72452. }
  72453. /*
  72454. ** Add a whole list of operations to the operation stack. Return a
  72455. ** pointer to the first operation inserted.
  72456. **
  72457. ** Non-zero P2 arguments to jump instructions are automatically adjusted
  72458. ** so that the jump target is relative to the first operation inserted.
  72459. */
  72460. SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList(
  72461. Vdbe *p, /* Add opcodes to the prepared statement */
  72462. int nOp, /* Number of opcodes to add */
  72463. VdbeOpList const *aOp, /* The opcodes to be added */
  72464. int iLineno /* Source-file line number of first opcode */
  72465. ){
  72466. int i;
  72467. VdbeOp *pOut, *pFirst;
  72468. assert( nOp>0 );
  72469. assert( p->magic==VDBE_MAGIC_INIT );
  72470. if( p->nOp + nOp > p->nOpAlloc && growOpArray(p, nOp) ){
  72471. return 0;
  72472. }
  72473. pFirst = pOut = &p->aOp[p->nOp];
  72474. for(i=0; i<nOp; i++, aOp++, pOut++){
  72475. pOut->opcode = aOp->opcode;
  72476. pOut->p1 = aOp->p1;
  72477. pOut->p2 = aOp->p2;
  72478. assert( aOp->p2>=0 );
  72479. if( (sqlite3OpcodeProperty[aOp->opcode] & OPFLG_JUMP)!=0 && aOp->p2>0 ){
  72480. pOut->p2 += p->nOp;
  72481. }
  72482. pOut->p3 = aOp->p3;
  72483. pOut->p4type = P4_NOTUSED;
  72484. pOut->p4.p = 0;
  72485. pOut->p5 = 0;
  72486. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  72487. pOut->zComment = 0;
  72488. #endif
  72489. #ifdef SQLITE_VDBE_COVERAGE
  72490. pOut->iSrcLine = iLineno+i;
  72491. #else
  72492. (void)iLineno;
  72493. #endif
  72494. #ifdef SQLITE_DEBUG
  72495. if( p->db->flags & SQLITE_VdbeAddopTrace ){
  72496. sqlite3VdbePrintOp(0, i+p->nOp, &p->aOp[i+p->nOp]);
  72497. }
  72498. #endif
  72499. }
  72500. p->nOp += nOp;
  72501. return pFirst;
  72502. }
  72503. #if defined(SQLITE_ENABLE_STMT_SCANSTATUS)
  72504. /*
  72505. ** Add an entry to the array of counters managed by sqlite3_stmt_scanstatus().
  72506. */
  72507. SQLITE_PRIVATE void sqlite3VdbeScanStatus(
  72508. Vdbe *p, /* VM to add scanstatus() to */
  72509. int addrExplain, /* Address of OP_Explain (or 0) */
  72510. int addrLoop, /* Address of loop counter */
  72511. int addrVisit, /* Address of rows visited counter */
  72512. LogEst nEst, /* Estimated number of output rows */
  72513. const char *zName /* Name of table or index being scanned */
  72514. ){
  72515. sqlite3_int64 nByte = (p->nScan+1) * sizeof(ScanStatus);
  72516. ScanStatus *aNew;
  72517. aNew = (ScanStatus*)sqlite3DbRealloc(p->db, p->aScan, nByte);
  72518. if( aNew ){
  72519. ScanStatus *pNew = &aNew[p->nScan++];
  72520. pNew->addrExplain = addrExplain;
  72521. pNew->addrLoop = addrLoop;
  72522. pNew->addrVisit = addrVisit;
  72523. pNew->nEst = nEst;
  72524. pNew->zName = sqlite3DbStrDup(p->db, zName);
  72525. p->aScan = aNew;
  72526. }
  72527. }
  72528. #endif
  72529. /*
  72530. ** Change the value of the opcode, or P1, P2, P3, or P5 operands
  72531. ** for a specific instruction.
  72532. */
  72533. SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe *p, u32 addr, u8 iNewOpcode){
  72534. sqlite3VdbeGetOp(p,addr)->opcode = iNewOpcode;
  72535. }
  72536. SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
  72537. sqlite3VdbeGetOp(p,addr)->p1 = val;
  72538. }
  72539. SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
  72540. sqlite3VdbeGetOp(p,addr)->p2 = val;
  72541. }
  72542. SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
  72543. sqlite3VdbeGetOp(p,addr)->p3 = val;
  72544. }
  72545. SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u16 p5){
  72546. assert( p->nOp>0 || p->db->mallocFailed );
  72547. if( p->nOp>0 ) p->aOp[p->nOp-1].p5 = p5;
  72548. }
  72549. /*
  72550. ** Change the P2 operand of instruction addr so that it points to
  72551. ** the address of the next instruction to be coded.
  72552. */
  72553. SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
  72554. sqlite3VdbeChangeP2(p, addr, p->nOp);
  72555. }
  72556. /*
  72557. ** If the input FuncDef structure is ephemeral, then free it. If
  72558. ** the FuncDef is not ephermal, then do nothing.
  72559. */
  72560. static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
  72561. if( (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){
  72562. sqlite3DbFreeNN(db, pDef);
  72563. }
  72564. }
  72565. static void vdbeFreeOpArray(sqlite3 *, Op *, int);
  72566. /*
  72567. ** Delete a P4 value if necessary.
  72568. */
  72569. static SQLITE_NOINLINE void freeP4Mem(sqlite3 *db, Mem *p){
  72570. if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
  72571. sqlite3DbFreeNN(db, p);
  72572. }
  72573. static SQLITE_NOINLINE void freeP4FuncCtx(sqlite3 *db, sqlite3_context *p){
  72574. freeEphemeralFunction(db, p->pFunc);
  72575. sqlite3DbFreeNN(db, p);
  72576. }
  72577. static void freeP4(sqlite3 *db, int p4type, void *p4){
  72578. assert( db );
  72579. switch( p4type ){
  72580. case P4_FUNCCTX: {
  72581. freeP4FuncCtx(db, (sqlite3_context*)p4);
  72582. break;
  72583. }
  72584. case P4_REAL:
  72585. case P4_INT64:
  72586. case P4_DYNAMIC:
  72587. case P4_DYNBLOB:
  72588. case P4_INTARRAY: {
  72589. sqlite3DbFree(db, p4);
  72590. break;
  72591. }
  72592. case P4_KEYINFO: {
  72593. if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4);
  72594. break;
  72595. }
  72596. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  72597. case P4_EXPR: {
  72598. sqlite3ExprDelete(db, (Expr*)p4);
  72599. break;
  72600. }
  72601. #endif
  72602. case P4_FUNCDEF: {
  72603. freeEphemeralFunction(db, (FuncDef*)p4);
  72604. break;
  72605. }
  72606. case P4_MEM: {
  72607. if( db->pnBytesFreed==0 ){
  72608. sqlite3ValueFree((sqlite3_value*)p4);
  72609. }else{
  72610. freeP4Mem(db, (Mem*)p4);
  72611. }
  72612. break;
  72613. }
  72614. case P4_VTAB : {
  72615. if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
  72616. break;
  72617. }
  72618. }
  72619. }
  72620. /*
  72621. ** Free the space allocated for aOp and any p4 values allocated for the
  72622. ** opcodes contained within. If aOp is not NULL it is assumed to contain
  72623. ** nOp entries.
  72624. */
  72625. static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
  72626. if( aOp ){
  72627. Op *pOp;
  72628. for(pOp=&aOp[nOp-1]; pOp>=aOp; pOp--){
  72629. if( pOp->p4type <= P4_FREE_IF_LE ) freeP4(db, pOp->p4type, pOp->p4.p);
  72630. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  72631. sqlite3DbFree(db, pOp->zComment);
  72632. #endif
  72633. }
  72634. sqlite3DbFreeNN(db, aOp);
  72635. }
  72636. }
  72637. /*
  72638. ** Link the SubProgram object passed as the second argument into the linked
  72639. ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
  72640. ** objects when the VM is no longer required.
  72641. */
  72642. SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
  72643. p->pNext = pVdbe->pProgram;
  72644. pVdbe->pProgram = p;
  72645. }
  72646. /*
  72647. ** Change the opcode at addr into OP_Noop
  72648. */
  72649. SQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
  72650. VdbeOp *pOp;
  72651. if( p->db->mallocFailed ) return 0;
  72652. assert( addr>=0 && addr<p->nOp );
  72653. pOp = &p->aOp[addr];
  72654. freeP4(p->db, pOp->p4type, pOp->p4.p);
  72655. pOp->p4type = P4_NOTUSED;
  72656. pOp->p4.z = 0;
  72657. pOp->opcode = OP_Noop;
  72658. return 1;
  72659. }
  72660. /*
  72661. ** If the last opcode is "op" and it is not a jump destination,
  72662. ** then remove it. Return true if and only if an opcode was removed.
  72663. */
  72664. SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe *p, u8 op){
  72665. if( p->nOp>0 && p->aOp[p->nOp-1].opcode==op ){
  72666. return sqlite3VdbeChangeToNoop(p, p->nOp-1);
  72667. }else{
  72668. return 0;
  72669. }
  72670. }
  72671. /*
  72672. ** Change the value of the P4 operand for a specific instruction.
  72673. ** This routine is useful when a large program is loaded from a
  72674. ** static array using sqlite3VdbeAddOpList but we want to make a
  72675. ** few minor changes to the program.
  72676. **
  72677. ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
  72678. ** the string is made into memory obtained from sqlite3_malloc().
  72679. ** A value of n==0 means copy bytes of zP4 up to and including the
  72680. ** first null byte. If n>0 then copy n+1 bytes of zP4.
  72681. **
  72682. ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
  72683. ** to a string or structure that is guaranteed to exist for the lifetime of
  72684. ** the Vdbe. In these cases we can just copy the pointer.
  72685. **
  72686. ** If addr<0 then change P4 on the most recently inserted instruction.
  72687. */
  72688. static void SQLITE_NOINLINE vdbeChangeP4Full(
  72689. Vdbe *p,
  72690. Op *pOp,
  72691. const char *zP4,
  72692. int n
  72693. ){
  72694. if( pOp->p4type ){
  72695. freeP4(p->db, pOp->p4type, pOp->p4.p);
  72696. pOp->p4type = 0;
  72697. pOp->p4.p = 0;
  72698. }
  72699. if( n<0 ){
  72700. sqlite3VdbeChangeP4(p, (int)(pOp - p->aOp), zP4, n);
  72701. }else{
  72702. if( n==0 ) n = sqlite3Strlen30(zP4);
  72703. pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
  72704. pOp->p4type = P4_DYNAMIC;
  72705. }
  72706. }
  72707. SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
  72708. Op *pOp;
  72709. sqlite3 *db;
  72710. assert( p!=0 );
  72711. db = p->db;
  72712. assert( p->magic==VDBE_MAGIC_INIT );
  72713. assert( p->aOp!=0 || db->mallocFailed );
  72714. if( db->mallocFailed ){
  72715. if( n!=P4_VTAB ) freeP4(db, n, (void*)*(char**)&zP4);
  72716. return;
  72717. }
  72718. assert( p->nOp>0 );
  72719. assert( addr<p->nOp );
  72720. if( addr<0 ){
  72721. addr = p->nOp - 1;
  72722. }
  72723. pOp = &p->aOp[addr];
  72724. if( n>=0 || pOp->p4type ){
  72725. vdbeChangeP4Full(p, pOp, zP4, n);
  72726. return;
  72727. }
  72728. if( n==P4_INT32 ){
  72729. /* Note: this cast is safe, because the origin data point was an int
  72730. ** that was cast to a (const char *). */
  72731. pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
  72732. pOp->p4type = P4_INT32;
  72733. }else if( zP4!=0 ){
  72734. assert( n<0 );
  72735. pOp->p4.p = (void*)zP4;
  72736. pOp->p4type = (signed char)n;
  72737. if( n==P4_VTAB ) sqlite3VtabLock((VTable*)zP4);
  72738. }
  72739. }
  72740. /*
  72741. ** Change the P4 operand of the most recently coded instruction
  72742. ** to the value defined by the arguments. This is a high-speed
  72743. ** version of sqlite3VdbeChangeP4().
  72744. **
  72745. ** The P4 operand must not have been previously defined. And the new
  72746. ** P4 must not be P4_INT32. Use sqlite3VdbeChangeP4() in either of
  72747. ** those cases.
  72748. */
  72749. SQLITE_PRIVATE void sqlite3VdbeAppendP4(Vdbe *p, void *pP4, int n){
  72750. VdbeOp *pOp;
  72751. assert( n!=P4_INT32 && n!=P4_VTAB );
  72752. assert( n<=0 );
  72753. if( p->db->mallocFailed ){
  72754. freeP4(p->db, n, pP4);
  72755. }else{
  72756. assert( pP4!=0 );
  72757. assert( p->nOp>0 );
  72758. pOp = &p->aOp[p->nOp-1];
  72759. assert( pOp->p4type==P4_NOTUSED );
  72760. pOp->p4type = n;
  72761. pOp->p4.p = pP4;
  72762. }
  72763. }
  72764. /*
  72765. ** Set the P4 on the most recently added opcode to the KeyInfo for the
  72766. ** index given.
  72767. */
  72768. SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){
  72769. Vdbe *v = pParse->pVdbe;
  72770. KeyInfo *pKeyInfo;
  72771. assert( v!=0 );
  72772. assert( pIdx!=0 );
  72773. pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pIdx);
  72774. if( pKeyInfo ) sqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO);
  72775. }
  72776. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  72777. /*
  72778. ** Change the comment on the most recently coded instruction. Or
  72779. ** insert a No-op and add the comment to that new instruction. This
  72780. ** makes the code easier to read during debugging. None of this happens
  72781. ** in a production build.
  72782. */
  72783. static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
  72784. assert( p->nOp>0 || p->aOp==0 );
  72785. assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
  72786. if( p->nOp ){
  72787. assert( p->aOp );
  72788. sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
  72789. p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
  72790. }
  72791. }
  72792. SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
  72793. va_list ap;
  72794. if( p ){
  72795. va_start(ap, zFormat);
  72796. vdbeVComment(p, zFormat, ap);
  72797. va_end(ap);
  72798. }
  72799. }
  72800. SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
  72801. va_list ap;
  72802. if( p ){
  72803. sqlite3VdbeAddOp0(p, OP_Noop);
  72804. va_start(ap, zFormat);
  72805. vdbeVComment(p, zFormat, ap);
  72806. va_end(ap);
  72807. }
  72808. }
  72809. #endif /* NDEBUG */
  72810. #ifdef SQLITE_VDBE_COVERAGE
  72811. /*
  72812. ** Set the value if the iSrcLine field for the previously coded instruction.
  72813. */
  72814. SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe *v, int iLine){
  72815. sqlite3VdbeGetOp(v,-1)->iSrcLine = iLine;
  72816. }
  72817. #endif /* SQLITE_VDBE_COVERAGE */
  72818. /*
  72819. ** Return the opcode for a given address. If the address is -1, then
  72820. ** return the most recently inserted opcode.
  72821. **
  72822. ** If a memory allocation error has occurred prior to the calling of this
  72823. ** routine, then a pointer to a dummy VdbeOp will be returned. That opcode
  72824. ** is readable but not writable, though it is cast to a writable value.
  72825. ** The return of a dummy opcode allows the call to continue functioning
  72826. ** after an OOM fault without having to check to see if the return from
  72827. ** this routine is a valid pointer. But because the dummy.opcode is 0,
  72828. ** dummy will never be written to. This is verified by code inspection and
  72829. ** by running with Valgrind.
  72830. */
  72831. SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
  72832. /* C89 specifies that the constant "dummy" will be initialized to all
  72833. ** zeros, which is correct. MSVC generates a warning, nevertheless. */
  72834. static VdbeOp dummy; /* Ignore the MSVC warning about no initializer */
  72835. assert( p->magic==VDBE_MAGIC_INIT );
  72836. if( addr<0 ){
  72837. addr = p->nOp - 1;
  72838. }
  72839. assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
  72840. if( p->db->mallocFailed ){
  72841. return (VdbeOp*)&dummy;
  72842. }else{
  72843. return &p->aOp[addr];
  72844. }
  72845. }
  72846. #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
  72847. /*
  72848. ** Return an integer value for one of the parameters to the opcode pOp
  72849. ** determined by character c.
  72850. */
  72851. static int translateP(char c, const Op *pOp){
  72852. if( c=='1' ) return pOp->p1;
  72853. if( c=='2' ) return pOp->p2;
  72854. if( c=='3' ) return pOp->p3;
  72855. if( c=='4' ) return pOp->p4.i;
  72856. return pOp->p5;
  72857. }
  72858. /*
  72859. ** Compute a string for the "comment" field of a VDBE opcode listing.
  72860. **
  72861. ** The Synopsis: field in comments in the vdbe.c source file gets converted
  72862. ** to an extra string that is appended to the sqlite3OpcodeName(). In the
  72863. ** absence of other comments, this synopsis becomes the comment on the opcode.
  72864. ** Some translation occurs:
  72865. **
  72866. ** "PX" -> "r[X]"
  72867. ** "PX@PY" -> "r[X..X+Y-1]" or "r[x]" if y is 0 or 1
  72868. ** "PX@PY+1" -> "r[X..X+Y]" or "r[x]" if y is 0
  72869. ** "PY..PY" -> "r[X..Y]" or "r[x]" if y<=x
  72870. */
  72871. static int displayComment(
  72872. const Op *pOp, /* The opcode to be commented */
  72873. const char *zP4, /* Previously obtained value for P4 */
  72874. char *zTemp, /* Write result here */
  72875. int nTemp /* Space available in zTemp[] */
  72876. ){
  72877. const char *zOpName;
  72878. const char *zSynopsis;
  72879. int nOpName;
  72880. int ii, jj;
  72881. char zAlt[50];
  72882. zOpName = sqlite3OpcodeName(pOp->opcode);
  72883. nOpName = sqlite3Strlen30(zOpName);
  72884. if( zOpName[nOpName+1] ){
  72885. int seenCom = 0;
  72886. char c;
  72887. zSynopsis = zOpName += nOpName + 1;
  72888. if( strncmp(zSynopsis,"IF ",3)==0 ){
  72889. if( pOp->p5 & SQLITE_STOREP2 ){
  72890. sqlite3_snprintf(sizeof(zAlt), zAlt, "r[P2] = (%s)", zSynopsis+3);
  72891. }else{
  72892. sqlite3_snprintf(sizeof(zAlt), zAlt, "if %s goto P2", zSynopsis+3);
  72893. }
  72894. zSynopsis = zAlt;
  72895. }
  72896. for(ii=jj=0; jj<nTemp-1 && (c = zSynopsis[ii])!=0; ii++){
  72897. if( c=='P' ){
  72898. c = zSynopsis[++ii];
  72899. if( c=='4' ){
  72900. sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", zP4);
  72901. }else if( c=='X' ){
  72902. sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", pOp->zComment);
  72903. seenCom = 1;
  72904. }else{
  72905. int v1 = translateP(c, pOp);
  72906. int v2;
  72907. sqlite3_snprintf(nTemp-jj, zTemp+jj, "%d", v1);
  72908. if( strncmp(zSynopsis+ii+1, "@P", 2)==0 ){
  72909. ii += 3;
  72910. jj += sqlite3Strlen30(zTemp+jj);
  72911. v2 = translateP(zSynopsis[ii], pOp);
  72912. if( strncmp(zSynopsis+ii+1,"+1",2)==0 ){
  72913. ii += 2;
  72914. v2++;
  72915. }
  72916. if( v2>1 ){
  72917. sqlite3_snprintf(nTemp-jj, zTemp+jj, "..%d", v1+v2-1);
  72918. }
  72919. }else if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){
  72920. ii += 4;
  72921. }
  72922. }
  72923. jj += sqlite3Strlen30(zTemp+jj);
  72924. }else{
  72925. zTemp[jj++] = c;
  72926. }
  72927. }
  72928. if( !seenCom && jj<nTemp-5 && pOp->zComment ){
  72929. sqlite3_snprintf(nTemp-jj, zTemp+jj, "; %s", pOp->zComment);
  72930. jj += sqlite3Strlen30(zTemp+jj);
  72931. }
  72932. if( jj<nTemp ) zTemp[jj] = 0;
  72933. }else if( pOp->zComment ){
  72934. sqlite3_snprintf(nTemp, zTemp, "%s", pOp->zComment);
  72935. jj = sqlite3Strlen30(zTemp);
  72936. }else{
  72937. zTemp[0] = 0;
  72938. jj = 0;
  72939. }
  72940. return jj;
  72941. }
  72942. #endif /* SQLITE_DEBUG */
  72943. #if VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS)
  72944. /*
  72945. ** Translate the P4.pExpr value for an OP_CursorHint opcode into text
  72946. ** that can be displayed in the P4 column of EXPLAIN output.
  72947. */
  72948. static void displayP4Expr(StrAccum *p, Expr *pExpr){
  72949. const char *zOp = 0;
  72950. switch( pExpr->op ){
  72951. case TK_STRING:
  72952. sqlite3_str_appendf(p, "%Q", pExpr->u.zToken);
  72953. break;
  72954. case TK_INTEGER:
  72955. sqlite3_str_appendf(p, "%d", pExpr->u.iValue);
  72956. break;
  72957. case TK_NULL:
  72958. sqlite3_str_appendf(p, "NULL");
  72959. break;
  72960. case TK_REGISTER: {
  72961. sqlite3_str_appendf(p, "r[%d]", pExpr->iTable);
  72962. break;
  72963. }
  72964. case TK_COLUMN: {
  72965. if( pExpr->iColumn<0 ){
  72966. sqlite3_str_appendf(p, "rowid");
  72967. }else{
  72968. sqlite3_str_appendf(p, "c%d", (int)pExpr->iColumn);
  72969. }
  72970. break;
  72971. }
  72972. case TK_LT: zOp = "LT"; break;
  72973. case TK_LE: zOp = "LE"; break;
  72974. case TK_GT: zOp = "GT"; break;
  72975. case TK_GE: zOp = "GE"; break;
  72976. case TK_NE: zOp = "NE"; break;
  72977. case TK_EQ: zOp = "EQ"; break;
  72978. case TK_IS: zOp = "IS"; break;
  72979. case TK_ISNOT: zOp = "ISNOT"; break;
  72980. case TK_AND: zOp = "AND"; break;
  72981. case TK_OR: zOp = "OR"; break;
  72982. case TK_PLUS: zOp = "ADD"; break;
  72983. case TK_STAR: zOp = "MUL"; break;
  72984. case TK_MINUS: zOp = "SUB"; break;
  72985. case TK_REM: zOp = "REM"; break;
  72986. case TK_BITAND: zOp = "BITAND"; break;
  72987. case TK_BITOR: zOp = "BITOR"; break;
  72988. case TK_SLASH: zOp = "DIV"; break;
  72989. case TK_LSHIFT: zOp = "LSHIFT"; break;
  72990. case TK_RSHIFT: zOp = "RSHIFT"; break;
  72991. case TK_CONCAT: zOp = "CONCAT"; break;
  72992. case TK_UMINUS: zOp = "MINUS"; break;
  72993. case TK_UPLUS: zOp = "PLUS"; break;
  72994. case TK_BITNOT: zOp = "BITNOT"; break;
  72995. case TK_NOT: zOp = "NOT"; break;
  72996. case TK_ISNULL: zOp = "ISNULL"; break;
  72997. case TK_NOTNULL: zOp = "NOTNULL"; break;
  72998. default:
  72999. sqlite3_str_appendf(p, "%s", "expr");
  73000. break;
  73001. }
  73002. if( zOp ){
  73003. sqlite3_str_appendf(p, "%s(", zOp);
  73004. displayP4Expr(p, pExpr->pLeft);
  73005. if( pExpr->pRight ){
  73006. sqlite3_str_append(p, ",", 1);
  73007. displayP4Expr(p, pExpr->pRight);
  73008. }
  73009. sqlite3_str_append(p, ")", 1);
  73010. }
  73011. }
  73012. #endif /* VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS) */
  73013. #if VDBE_DISPLAY_P4
  73014. /*
  73015. ** Compute a string that describes the P4 parameter for an opcode.
  73016. ** Use zTemp for any required temporary buffer space.
  73017. */
  73018. static char *displayP4(Op *pOp, char *zTemp, int nTemp){
  73019. char *zP4 = zTemp;
  73020. StrAccum x;
  73021. assert( nTemp>=20 );
  73022. sqlite3StrAccumInit(&x, 0, zTemp, nTemp, 0);
  73023. switch( pOp->p4type ){
  73024. case P4_KEYINFO: {
  73025. int j;
  73026. KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
  73027. assert( pKeyInfo->aSortOrder!=0 );
  73028. sqlite3_str_appendf(&x, "k(%d", pKeyInfo->nKeyField);
  73029. for(j=0; j<pKeyInfo->nKeyField; j++){
  73030. CollSeq *pColl = pKeyInfo->aColl[j];
  73031. const char *zColl = pColl ? pColl->zName : "";
  73032. if( strcmp(zColl, "BINARY")==0 ) zColl = "B";
  73033. sqlite3_str_appendf(&x, ",%s%s",
  73034. pKeyInfo->aSortOrder[j] ? "-" : "", zColl);
  73035. }
  73036. sqlite3_str_append(&x, ")", 1);
  73037. break;
  73038. }
  73039. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  73040. case P4_EXPR: {
  73041. displayP4Expr(&x, pOp->p4.pExpr);
  73042. break;
  73043. }
  73044. #endif
  73045. case P4_COLLSEQ: {
  73046. CollSeq *pColl = pOp->p4.pColl;
  73047. sqlite3_str_appendf(&x, "(%.20s)", pColl->zName);
  73048. break;
  73049. }
  73050. case P4_FUNCDEF: {
  73051. FuncDef *pDef = pOp->p4.pFunc;
  73052. sqlite3_str_appendf(&x, "%s(%d)", pDef->zName, pDef->nArg);
  73053. break;
  73054. }
  73055. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  73056. case P4_FUNCCTX: {
  73057. FuncDef *pDef = pOp->p4.pCtx->pFunc;
  73058. sqlite3_str_appendf(&x, "%s(%d)", pDef->zName, pDef->nArg);
  73059. break;
  73060. }
  73061. #endif
  73062. case P4_INT64: {
  73063. sqlite3_str_appendf(&x, "%lld", *pOp->p4.pI64);
  73064. break;
  73065. }
  73066. case P4_INT32: {
  73067. sqlite3_str_appendf(&x, "%d", pOp->p4.i);
  73068. break;
  73069. }
  73070. case P4_REAL: {
  73071. sqlite3_str_appendf(&x, "%.16g", *pOp->p4.pReal);
  73072. break;
  73073. }
  73074. case P4_MEM: {
  73075. Mem *pMem = pOp->p4.pMem;
  73076. if( pMem->flags & MEM_Str ){
  73077. zP4 = pMem->z;
  73078. }else if( pMem->flags & (MEM_Int|MEM_IntReal) ){
  73079. sqlite3_str_appendf(&x, "%lld", pMem->u.i);
  73080. }else if( pMem->flags & MEM_Real ){
  73081. sqlite3_str_appendf(&x, "%.16g", pMem->u.r);
  73082. }else if( pMem->flags & MEM_Null ){
  73083. zP4 = "NULL";
  73084. }else{
  73085. assert( pMem->flags & MEM_Blob );
  73086. zP4 = "(blob)";
  73087. }
  73088. break;
  73089. }
  73090. #ifndef SQLITE_OMIT_VIRTUALTABLE
  73091. case P4_VTAB: {
  73092. sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
  73093. sqlite3_str_appendf(&x, "vtab:%p", pVtab);
  73094. break;
  73095. }
  73096. #endif
  73097. case P4_INTARRAY: {
  73098. int i;
  73099. int *ai = pOp->p4.ai;
  73100. int n = ai[0]; /* The first element of an INTARRAY is always the
  73101. ** count of the number of elements to follow */
  73102. for(i=1; i<=n; i++){
  73103. sqlite3_str_appendf(&x, ",%d", ai[i]);
  73104. }
  73105. zTemp[0] = '[';
  73106. sqlite3_str_append(&x, "]", 1);
  73107. break;
  73108. }
  73109. case P4_SUBPROGRAM: {
  73110. sqlite3_str_appendf(&x, "program");
  73111. break;
  73112. }
  73113. case P4_DYNBLOB:
  73114. case P4_ADVANCE: {
  73115. zTemp[0] = 0;
  73116. break;
  73117. }
  73118. case P4_TABLE: {
  73119. sqlite3_str_appendf(&x, "%s", pOp->p4.pTab->zName);
  73120. break;
  73121. }
  73122. default: {
  73123. zP4 = pOp->p4.z;
  73124. if( zP4==0 ){
  73125. zP4 = zTemp;
  73126. zTemp[0] = 0;
  73127. }
  73128. }
  73129. }
  73130. sqlite3StrAccumFinish(&x);
  73131. assert( zP4!=0 );
  73132. return zP4;
  73133. }
  73134. #endif /* VDBE_DISPLAY_P4 */
  73135. /*
  73136. ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
  73137. **
  73138. ** The prepared statements need to know in advance the complete set of
  73139. ** attached databases that will be use. A mask of these databases
  73140. ** is maintained in p->btreeMask. The p->lockMask value is the subset of
  73141. ** p->btreeMask of databases that will require a lock.
  73142. */
  73143. SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
  73144. assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
  73145. assert( i<(int)sizeof(p->btreeMask)*8 );
  73146. DbMaskSet(p->btreeMask, i);
  73147. if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
  73148. DbMaskSet(p->lockMask, i);
  73149. }
  73150. }
  73151. #if !defined(SQLITE_OMIT_SHARED_CACHE)
  73152. /*
  73153. ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
  73154. ** this routine obtains the mutex associated with each BtShared structure
  73155. ** that may be accessed by the VM passed as an argument. In doing so it also
  73156. ** sets the BtShared.db member of each of the BtShared structures, ensuring
  73157. ** that the correct busy-handler callback is invoked if required.
  73158. **
  73159. ** If SQLite is not threadsafe but does support shared-cache mode, then
  73160. ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
  73161. ** of all of BtShared structures accessible via the database handle
  73162. ** associated with the VM.
  73163. **
  73164. ** If SQLite is not threadsafe and does not support shared-cache mode, this
  73165. ** function is a no-op.
  73166. **
  73167. ** The p->btreeMask field is a bitmask of all btrees that the prepared
  73168. ** statement p will ever use. Let N be the number of bits in p->btreeMask
  73169. ** corresponding to btrees that use shared cache. Then the runtime of
  73170. ** this routine is N*N. But as N is rarely more than 1, this should not
  73171. ** be a problem.
  73172. */
  73173. SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
  73174. int i;
  73175. sqlite3 *db;
  73176. Db *aDb;
  73177. int nDb;
  73178. if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
  73179. db = p->db;
  73180. aDb = db->aDb;
  73181. nDb = db->nDb;
  73182. for(i=0; i<nDb; i++){
  73183. if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
  73184. sqlite3BtreeEnter(aDb[i].pBt);
  73185. }
  73186. }
  73187. }
  73188. #endif
  73189. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
  73190. /*
  73191. ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
  73192. */
  73193. static SQLITE_NOINLINE void vdbeLeave(Vdbe *p){
  73194. int i;
  73195. sqlite3 *db;
  73196. Db *aDb;
  73197. int nDb;
  73198. db = p->db;
  73199. aDb = db->aDb;
  73200. nDb = db->nDb;
  73201. for(i=0; i<nDb; i++){
  73202. if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
  73203. sqlite3BtreeLeave(aDb[i].pBt);
  73204. }
  73205. }
  73206. }
  73207. SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
  73208. if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
  73209. vdbeLeave(p);
  73210. }
  73211. #endif
  73212. #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  73213. /*
  73214. ** Print a single opcode. This routine is used for debugging only.
  73215. */
  73216. SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, VdbeOp *pOp){
  73217. char *zP4;
  73218. char zPtr[50];
  73219. char zCom[100];
  73220. static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n";
  73221. if( pOut==0 ) pOut = stdout;
  73222. zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
  73223. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  73224. displayComment(pOp, zP4, zCom, sizeof(zCom));
  73225. #else
  73226. zCom[0] = 0;
  73227. #endif
  73228. /* NB: The sqlite3OpcodeName() function is implemented by code created
  73229. ** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the
  73230. ** information from the vdbe.c source text */
  73231. fprintf(pOut, zFormat1, pc,
  73232. sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
  73233. zCom
  73234. );
  73235. fflush(pOut);
  73236. }
  73237. #endif
  73238. /*
  73239. ** Initialize an array of N Mem element.
  73240. */
  73241. static void initMemArray(Mem *p, int N, sqlite3 *db, u16 flags){
  73242. while( (N--)>0 ){
  73243. p->db = db;
  73244. p->flags = flags;
  73245. p->szMalloc = 0;
  73246. #ifdef SQLITE_DEBUG
  73247. p->pScopyFrom = 0;
  73248. #endif
  73249. p++;
  73250. }
  73251. }
  73252. /*
  73253. ** Release an array of N Mem elements
  73254. */
  73255. static void releaseMemArray(Mem *p, int N){
  73256. if( p && N ){
  73257. Mem *pEnd = &p[N];
  73258. sqlite3 *db = p->db;
  73259. if( db->pnBytesFreed ){
  73260. do{
  73261. if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
  73262. }while( (++p)<pEnd );
  73263. return;
  73264. }
  73265. do{
  73266. assert( (&p[1])==pEnd || p[0].db==p[1].db );
  73267. assert( sqlite3VdbeCheckMemInvariants(p) );
  73268. /* This block is really an inlined version of sqlite3VdbeMemRelease()
  73269. ** that takes advantage of the fact that the memory cell value is
  73270. ** being set to NULL after releasing any dynamic resources.
  73271. **
  73272. ** The justification for duplicating code is that according to
  73273. ** callgrind, this causes a certain test case to hit the CPU 4.7
  73274. ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
  73275. ** sqlite3MemRelease() were called from here. With -O2, this jumps
  73276. ** to 6.6 percent. The test case is inserting 1000 rows into a table
  73277. ** with no indexes using a single prepared INSERT statement, bind()
  73278. ** and reset(). Inserts are grouped into a transaction.
  73279. */
  73280. testcase( p->flags & MEM_Agg );
  73281. testcase( p->flags & MEM_Dyn );
  73282. testcase( p->xDel==sqlite3VdbeFrameMemDel );
  73283. if( p->flags&(MEM_Agg|MEM_Dyn) ){
  73284. sqlite3VdbeMemRelease(p);
  73285. }else if( p->szMalloc ){
  73286. sqlite3DbFreeNN(db, p->zMalloc);
  73287. p->szMalloc = 0;
  73288. }
  73289. p->flags = MEM_Undefined;
  73290. }while( (++p)<pEnd );
  73291. }
  73292. }
  73293. #ifdef SQLITE_DEBUG
  73294. /*
  73295. ** Verify that pFrame is a valid VdbeFrame pointer. Return true if it is
  73296. ** and false if something is wrong.
  73297. **
  73298. ** This routine is intended for use inside of assert() statements only.
  73299. */
  73300. SQLITE_PRIVATE int sqlite3VdbeFrameIsValid(VdbeFrame *pFrame){
  73301. if( pFrame->iFrameMagic!=SQLITE_FRAME_MAGIC ) return 0;
  73302. return 1;
  73303. }
  73304. #endif
  73305. /*
  73306. ** This is a destructor on a Mem object (which is really an sqlite3_value)
  73307. ** that deletes the Frame object that is attached to it as a blob.
  73308. **
  73309. ** This routine does not delete the Frame right away. It merely adds the
  73310. ** frame to a list of frames to be deleted when the Vdbe halts.
  73311. */
  73312. SQLITE_PRIVATE void sqlite3VdbeFrameMemDel(void *pArg){
  73313. VdbeFrame *pFrame = (VdbeFrame*)pArg;
  73314. assert( sqlite3VdbeFrameIsValid(pFrame) );
  73315. pFrame->pParent = pFrame->v->pDelFrame;
  73316. pFrame->v->pDelFrame = pFrame;
  73317. }
  73318. /*
  73319. ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
  73320. ** allocated by the OP_Program opcode in sqlite3VdbeExec().
  73321. */
  73322. SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
  73323. int i;
  73324. Mem *aMem = VdbeFrameMem(p);
  73325. VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
  73326. assert( sqlite3VdbeFrameIsValid(p) );
  73327. for(i=0; i<p->nChildCsr; i++){
  73328. sqlite3VdbeFreeCursor(p->v, apCsr[i]);
  73329. }
  73330. releaseMemArray(aMem, p->nChildMem);
  73331. sqlite3VdbeDeleteAuxData(p->v->db, &p->pAuxData, -1, 0);
  73332. sqlite3DbFree(p->v->db, p);
  73333. }
  73334. #ifndef SQLITE_OMIT_EXPLAIN
  73335. /*
  73336. ** Give a listing of the program in the virtual machine.
  73337. **
  73338. ** The interface is the same as sqlite3VdbeExec(). But instead of
  73339. ** running the code, it invokes the callback once for each instruction.
  73340. ** This feature is used to implement "EXPLAIN".
  73341. **
  73342. ** When p->explain==1, each instruction is listed. When
  73343. ** p->explain==2, only OP_Explain instructions are listed and these
  73344. ** are shown in a different format. p->explain==2 is used to implement
  73345. ** EXPLAIN QUERY PLAN.
  73346. ** 2018-04-24: In p->explain==2 mode, the OP_Init opcodes of triggers
  73347. ** are also shown, so that the boundaries between the main program and
  73348. ** each trigger are clear.
  73349. **
  73350. ** When p->explain==1, first the main program is listed, then each of
  73351. ** the trigger subprograms are listed one by one.
  73352. */
  73353. SQLITE_PRIVATE int sqlite3VdbeList(
  73354. Vdbe *p /* The VDBE */
  73355. ){
  73356. int nRow; /* Stop when row count reaches this */
  73357. int nSub = 0; /* Number of sub-vdbes seen so far */
  73358. SubProgram **apSub = 0; /* Array of sub-vdbes */
  73359. Mem *pSub = 0; /* Memory cell hold array of subprogs */
  73360. sqlite3 *db = p->db; /* The database connection */
  73361. int i; /* Loop counter */
  73362. int rc = SQLITE_OK; /* Return code */
  73363. Mem *pMem = &p->aMem[1]; /* First Mem of result set */
  73364. int bListSubprogs = (p->explain==1 || (db->flags & SQLITE_TriggerEQP)!=0);
  73365. Op *pOp = 0;
  73366. assert( p->explain );
  73367. assert( p->magic==VDBE_MAGIC_RUN );
  73368. assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
  73369. /* Even though this opcode does not use dynamic strings for
  73370. ** the result, result columns may become dynamic if the user calls
  73371. ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
  73372. */
  73373. releaseMemArray(pMem, 8);
  73374. p->pResultSet = 0;
  73375. if( p->rc==SQLITE_NOMEM ){
  73376. /* This happens if a malloc() inside a call to sqlite3_column_text() or
  73377. ** sqlite3_column_text16() failed. */
  73378. sqlite3OomFault(db);
  73379. return SQLITE_ERROR;
  73380. }
  73381. /* When the number of output rows reaches nRow, that means the
  73382. ** listing has finished and sqlite3_step() should return SQLITE_DONE.
  73383. ** nRow is the sum of the number of rows in the main program, plus
  73384. ** the sum of the number of rows in all trigger subprograms encountered
  73385. ** so far. The nRow value will increase as new trigger subprograms are
  73386. ** encountered, but p->pc will eventually catch up to nRow.
  73387. */
  73388. nRow = p->nOp;
  73389. if( bListSubprogs ){
  73390. /* The first 8 memory cells are used for the result set. So we will
  73391. ** commandeer the 9th cell to use as storage for an array of pointers
  73392. ** to trigger subprograms. The VDBE is guaranteed to have at least 9
  73393. ** cells. */
  73394. assert( p->nMem>9 );
  73395. pSub = &p->aMem[9];
  73396. if( pSub->flags&MEM_Blob ){
  73397. /* On the first call to sqlite3_step(), pSub will hold a NULL. It is
  73398. ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
  73399. nSub = pSub->n/sizeof(Vdbe*);
  73400. apSub = (SubProgram **)pSub->z;
  73401. }
  73402. for(i=0; i<nSub; i++){
  73403. nRow += apSub[i]->nOp;
  73404. }
  73405. }
  73406. while(1){ /* Loop exits via break */
  73407. i = p->pc++;
  73408. if( i>=nRow ){
  73409. p->rc = SQLITE_OK;
  73410. rc = SQLITE_DONE;
  73411. break;
  73412. }
  73413. if( i<p->nOp ){
  73414. /* The output line number is small enough that we are still in the
  73415. ** main program. */
  73416. pOp = &p->aOp[i];
  73417. }else{
  73418. /* We are currently listing subprograms. Figure out which one and
  73419. ** pick up the appropriate opcode. */
  73420. int j;
  73421. i -= p->nOp;
  73422. for(j=0; i>=apSub[j]->nOp; j++){
  73423. i -= apSub[j]->nOp;
  73424. }
  73425. pOp = &apSub[j]->aOp[i];
  73426. }
  73427. /* When an OP_Program opcode is encounter (the only opcode that has
  73428. ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
  73429. ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
  73430. ** has not already been seen.
  73431. */
  73432. if( bListSubprogs && pOp->p4type==P4_SUBPROGRAM ){
  73433. int nByte = (nSub+1)*sizeof(SubProgram*);
  73434. int j;
  73435. for(j=0; j<nSub; j++){
  73436. if( apSub[j]==pOp->p4.pProgram ) break;
  73437. }
  73438. if( j==nSub ){
  73439. p->rc = sqlite3VdbeMemGrow(pSub, nByte, nSub!=0);
  73440. if( p->rc!=SQLITE_OK ){
  73441. rc = SQLITE_ERROR;
  73442. break;
  73443. }
  73444. apSub = (SubProgram **)pSub->z;
  73445. apSub[nSub++] = pOp->p4.pProgram;
  73446. pSub->flags |= MEM_Blob;
  73447. pSub->n = nSub*sizeof(SubProgram*);
  73448. nRow += pOp->p4.pProgram->nOp;
  73449. }
  73450. }
  73451. if( p->explain<2 ) break;
  73452. if( pOp->opcode==OP_Explain ) break;
  73453. if( pOp->opcode==OP_Init && p->pc>1 ) break;
  73454. }
  73455. if( rc==SQLITE_OK ){
  73456. if( db->u1.isInterrupted ){
  73457. p->rc = SQLITE_INTERRUPT;
  73458. rc = SQLITE_ERROR;
  73459. sqlite3VdbeError(p, sqlite3ErrStr(p->rc));
  73460. }else{
  73461. char *zP4;
  73462. if( p->explain==1 ){
  73463. pMem->flags = MEM_Int;
  73464. pMem->u.i = i; /* Program counter */
  73465. pMem++;
  73466. pMem->flags = MEM_Static|MEM_Str|MEM_Term;
  73467. pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
  73468. assert( pMem->z!=0 );
  73469. pMem->n = sqlite3Strlen30(pMem->z);
  73470. pMem->enc = SQLITE_UTF8;
  73471. pMem++;
  73472. }
  73473. pMem->flags = MEM_Int;
  73474. pMem->u.i = pOp->p1; /* P1 */
  73475. pMem++;
  73476. pMem->flags = MEM_Int;
  73477. pMem->u.i = pOp->p2; /* P2 */
  73478. pMem++;
  73479. pMem->flags = MEM_Int;
  73480. pMem->u.i = pOp->p3; /* P3 */
  73481. pMem++;
  73482. if( sqlite3VdbeMemClearAndResize(pMem, 100) ){ /* P4 */
  73483. assert( p->db->mallocFailed );
  73484. return SQLITE_ERROR;
  73485. }
  73486. pMem->flags = MEM_Str|MEM_Term;
  73487. zP4 = displayP4(pOp, pMem->z, pMem->szMalloc);
  73488. if( zP4!=pMem->z ){
  73489. pMem->n = 0;
  73490. sqlite3VdbeMemSetStr(pMem, zP4, -1, SQLITE_UTF8, 0);
  73491. }else{
  73492. assert( pMem->z!=0 );
  73493. pMem->n = sqlite3Strlen30(pMem->z);
  73494. pMem->enc = SQLITE_UTF8;
  73495. }
  73496. pMem++;
  73497. if( p->explain==1 ){
  73498. if( sqlite3VdbeMemClearAndResize(pMem, 4) ){
  73499. assert( p->db->mallocFailed );
  73500. return SQLITE_ERROR;
  73501. }
  73502. pMem->flags = MEM_Str|MEM_Term;
  73503. pMem->n = 2;
  73504. sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5); /* P5 */
  73505. pMem->enc = SQLITE_UTF8;
  73506. pMem++;
  73507. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  73508. if( sqlite3VdbeMemClearAndResize(pMem, 500) ){
  73509. assert( p->db->mallocFailed );
  73510. return SQLITE_ERROR;
  73511. }
  73512. pMem->flags = MEM_Str|MEM_Term;
  73513. pMem->n = displayComment(pOp, zP4, pMem->z, 500);
  73514. pMem->enc = SQLITE_UTF8;
  73515. #else
  73516. pMem->flags = MEM_Null; /* Comment */
  73517. #endif
  73518. }
  73519. p->nResColumn = 8 - 4*(p->explain-1);
  73520. p->pResultSet = &p->aMem[1];
  73521. p->rc = SQLITE_OK;
  73522. rc = SQLITE_ROW;
  73523. }
  73524. }
  73525. return rc;
  73526. }
  73527. #endif /* SQLITE_OMIT_EXPLAIN */
  73528. #ifdef SQLITE_DEBUG
  73529. /*
  73530. ** Print the SQL that was used to generate a VDBE program.
  73531. */
  73532. SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
  73533. const char *z = 0;
  73534. if( p->zSql ){
  73535. z = p->zSql;
  73536. }else if( p->nOp>=1 ){
  73537. const VdbeOp *pOp = &p->aOp[0];
  73538. if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
  73539. z = pOp->p4.z;
  73540. while( sqlite3Isspace(*z) ) z++;
  73541. }
  73542. }
  73543. if( z ) printf("SQL: [%s]\n", z);
  73544. }
  73545. #endif
  73546. #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
  73547. /*
  73548. ** Print an IOTRACE message showing SQL content.
  73549. */
  73550. SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
  73551. int nOp = p->nOp;
  73552. VdbeOp *pOp;
  73553. if( sqlite3IoTrace==0 ) return;
  73554. if( nOp<1 ) return;
  73555. pOp = &p->aOp[0];
  73556. if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
  73557. int i, j;
  73558. char z[1000];
  73559. sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
  73560. for(i=0; sqlite3Isspace(z[i]); i++){}
  73561. for(j=0; z[i]; i++){
  73562. if( sqlite3Isspace(z[i]) ){
  73563. if( z[i-1]!=' ' ){
  73564. z[j++] = ' ';
  73565. }
  73566. }else{
  73567. z[j++] = z[i];
  73568. }
  73569. }
  73570. z[j] = 0;
  73571. sqlite3IoTrace("SQL %s\n", z);
  73572. }
  73573. }
  73574. #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
  73575. /* An instance of this object describes bulk memory available for use
  73576. ** by subcomponents of a prepared statement. Space is allocated out
  73577. ** of a ReusableSpace object by the allocSpace() routine below.
  73578. */
  73579. struct ReusableSpace {
  73580. u8 *pSpace; /* Available memory */
  73581. sqlite3_int64 nFree; /* Bytes of available memory */
  73582. sqlite3_int64 nNeeded; /* Total bytes that could not be allocated */
  73583. };
  73584. /* Try to allocate nByte bytes of 8-byte aligned bulk memory for pBuf
  73585. ** from the ReusableSpace object. Return a pointer to the allocated
  73586. ** memory on success. If insufficient memory is available in the
  73587. ** ReusableSpace object, increase the ReusableSpace.nNeeded
  73588. ** value by the amount needed and return NULL.
  73589. **
  73590. ** If pBuf is not initially NULL, that means that the memory has already
  73591. ** been allocated by a prior call to this routine, so just return a copy
  73592. ** of pBuf and leave ReusableSpace unchanged.
  73593. **
  73594. ** This allocator is employed to repurpose unused slots at the end of the
  73595. ** opcode array of prepared state for other memory needs of the prepared
  73596. ** statement.
  73597. */
  73598. static void *allocSpace(
  73599. struct ReusableSpace *p, /* Bulk memory available for allocation */
  73600. void *pBuf, /* Pointer to a prior allocation */
  73601. sqlite3_int64 nByte /* Bytes of memory needed */
  73602. ){
  73603. assert( EIGHT_BYTE_ALIGNMENT(p->pSpace) );
  73604. if( pBuf==0 ){
  73605. nByte = ROUND8(nByte);
  73606. if( nByte <= p->nFree ){
  73607. p->nFree -= nByte;
  73608. pBuf = &p->pSpace[p->nFree];
  73609. }else{
  73610. p->nNeeded += nByte;
  73611. }
  73612. }
  73613. assert( EIGHT_BYTE_ALIGNMENT(pBuf) );
  73614. return pBuf;
  73615. }
  73616. /*
  73617. ** Rewind the VDBE back to the beginning in preparation for
  73618. ** running it.
  73619. */
  73620. SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
  73621. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  73622. int i;
  73623. #endif
  73624. assert( p!=0 );
  73625. assert( p->magic==VDBE_MAGIC_INIT || p->magic==VDBE_MAGIC_RESET );
  73626. /* There should be at least one opcode.
  73627. */
  73628. assert( p->nOp>0 );
  73629. /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
  73630. p->magic = VDBE_MAGIC_RUN;
  73631. #ifdef SQLITE_DEBUG
  73632. for(i=0; i<p->nMem; i++){
  73633. assert( p->aMem[i].db==p->db );
  73634. }
  73635. #endif
  73636. p->pc = -1;
  73637. p->rc = SQLITE_OK;
  73638. p->errorAction = OE_Abort;
  73639. p->nChange = 0;
  73640. p->cacheCtr = 1;
  73641. p->minWriteFileFormat = 255;
  73642. p->iStatement = 0;
  73643. p->nFkConstraint = 0;
  73644. #ifdef VDBE_PROFILE
  73645. for(i=0; i<p->nOp; i++){
  73646. p->aOp[i].cnt = 0;
  73647. p->aOp[i].cycles = 0;
  73648. }
  73649. #endif
  73650. }
  73651. /*
  73652. ** Prepare a virtual machine for execution for the first time after
  73653. ** creating the virtual machine. This involves things such
  73654. ** as allocating registers and initializing the program counter.
  73655. ** After the VDBE has be prepped, it can be executed by one or more
  73656. ** calls to sqlite3VdbeExec().
  73657. **
  73658. ** This function may be called exactly once on each virtual machine.
  73659. ** After this routine is called the VM has been "packaged" and is ready
  73660. ** to run. After this routine is called, further calls to
  73661. ** sqlite3VdbeAddOp() functions are prohibited. This routine disconnects
  73662. ** the Vdbe from the Parse object that helped generate it so that the
  73663. ** the Vdbe becomes an independent entity and the Parse object can be
  73664. ** destroyed.
  73665. **
  73666. ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
  73667. ** to its initial state after it has been run.
  73668. */
  73669. SQLITE_PRIVATE void sqlite3VdbeMakeReady(
  73670. Vdbe *p, /* The VDBE */
  73671. Parse *pParse /* Parsing context */
  73672. ){
  73673. sqlite3 *db; /* The database connection */
  73674. int nVar; /* Number of parameters */
  73675. int nMem; /* Number of VM memory registers */
  73676. int nCursor; /* Number of cursors required */
  73677. int nArg; /* Number of arguments in subprograms */
  73678. int n; /* Loop counter */
  73679. struct ReusableSpace x; /* Reusable bulk memory */
  73680. assert( p!=0 );
  73681. assert( p->nOp>0 );
  73682. assert( pParse!=0 );
  73683. assert( p->magic==VDBE_MAGIC_INIT );
  73684. assert( pParse==p->pParse );
  73685. db = p->db;
  73686. assert( db->mallocFailed==0 );
  73687. nVar = pParse->nVar;
  73688. nMem = pParse->nMem;
  73689. nCursor = pParse->nTab;
  73690. nArg = pParse->nMaxArg;
  73691. /* Each cursor uses a memory cell. The first cursor (cursor 0) can
  73692. ** use aMem[0] which is not otherwise used by the VDBE program. Allocate
  73693. ** space at the end of aMem[] for cursors 1 and greater.
  73694. ** See also: allocateCursor().
  73695. */
  73696. nMem += nCursor;
  73697. if( nCursor==0 && nMem>0 ) nMem++; /* Space for aMem[0] even if not used */
  73698. /* Figure out how much reusable memory is available at the end of the
  73699. ** opcode array. This extra memory will be reallocated for other elements
  73700. ** of the prepared statement.
  73701. */
  73702. n = ROUND8(sizeof(Op)*p->nOp); /* Bytes of opcode memory used */
  73703. x.pSpace = &((u8*)p->aOp)[n]; /* Unused opcode memory */
  73704. assert( EIGHT_BYTE_ALIGNMENT(x.pSpace) );
  73705. x.nFree = ROUNDDOWN8(pParse->szOpAlloc - n); /* Bytes of unused memory */
  73706. assert( x.nFree>=0 );
  73707. assert( EIGHT_BYTE_ALIGNMENT(&x.pSpace[x.nFree]) );
  73708. resolveP2Values(p, &nArg);
  73709. p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
  73710. if( pParse->explain && nMem<10 ){
  73711. nMem = 10;
  73712. }
  73713. p->expired = 0;
  73714. /* Memory for registers, parameters, cursor, etc, is allocated in one or two
  73715. ** passes. On the first pass, we try to reuse unused memory at the
  73716. ** end of the opcode array. If we are unable to satisfy all memory
  73717. ** requirements by reusing the opcode array tail, then the second
  73718. ** pass will fill in the remainder using a fresh memory allocation.
  73719. **
  73720. ** This two-pass approach that reuses as much memory as possible from
  73721. ** the leftover memory at the end of the opcode array. This can significantly
  73722. ** reduce the amount of memory held by a prepared statement.
  73723. */
  73724. x.nNeeded = 0;
  73725. p->aMem = allocSpace(&x, 0, nMem*sizeof(Mem));
  73726. p->aVar = allocSpace(&x, 0, nVar*sizeof(Mem));
  73727. p->apArg = allocSpace(&x, 0, nArg*sizeof(Mem*));
  73728. p->apCsr = allocSpace(&x, 0, nCursor*sizeof(VdbeCursor*));
  73729. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  73730. p->anExec = allocSpace(&x, 0, p->nOp*sizeof(i64));
  73731. #endif
  73732. if( x.nNeeded ){
  73733. x.pSpace = p->pFree = sqlite3DbMallocRawNN(db, x.nNeeded);
  73734. x.nFree = x.nNeeded;
  73735. if( !db->mallocFailed ){
  73736. p->aMem = allocSpace(&x, p->aMem, nMem*sizeof(Mem));
  73737. p->aVar = allocSpace(&x, p->aVar, nVar*sizeof(Mem));
  73738. p->apArg = allocSpace(&x, p->apArg, nArg*sizeof(Mem*));
  73739. p->apCsr = allocSpace(&x, p->apCsr, nCursor*sizeof(VdbeCursor*));
  73740. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  73741. p->anExec = allocSpace(&x, p->anExec, p->nOp*sizeof(i64));
  73742. #endif
  73743. }
  73744. }
  73745. p->pVList = pParse->pVList;
  73746. pParse->pVList = 0;
  73747. p->explain = pParse->explain;
  73748. if( db->mallocFailed ){
  73749. p->nVar = 0;
  73750. p->nCursor = 0;
  73751. p->nMem = 0;
  73752. }else{
  73753. p->nCursor = nCursor;
  73754. p->nVar = (ynVar)nVar;
  73755. initMemArray(p->aVar, nVar, db, MEM_Null);
  73756. p->nMem = nMem;
  73757. initMemArray(p->aMem, nMem, db, MEM_Undefined);
  73758. memset(p->apCsr, 0, nCursor*sizeof(VdbeCursor*));
  73759. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  73760. memset(p->anExec, 0, p->nOp*sizeof(i64));
  73761. #endif
  73762. }
  73763. sqlite3VdbeRewind(p);
  73764. }
  73765. /*
  73766. ** Close a VDBE cursor and release all the resources that cursor
  73767. ** happens to hold.
  73768. */
  73769. SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
  73770. if( pCx==0 ){
  73771. return;
  73772. }
  73773. assert( pCx->pBtx==0 || pCx->eCurType==CURTYPE_BTREE );
  73774. switch( pCx->eCurType ){
  73775. case CURTYPE_SORTER: {
  73776. sqlite3VdbeSorterClose(p->db, pCx);
  73777. break;
  73778. }
  73779. case CURTYPE_BTREE: {
  73780. if( pCx->isEphemeral ){
  73781. if( pCx->pBtx ) sqlite3BtreeClose(pCx->pBtx);
  73782. /* The pCx->pCursor will be close automatically, if it exists, by
  73783. ** the call above. */
  73784. }else{
  73785. assert( pCx->uc.pCursor!=0 );
  73786. sqlite3BtreeCloseCursor(pCx->uc.pCursor);
  73787. }
  73788. break;
  73789. }
  73790. #ifndef SQLITE_OMIT_VIRTUALTABLE
  73791. case CURTYPE_VTAB: {
  73792. sqlite3_vtab_cursor *pVCur = pCx->uc.pVCur;
  73793. const sqlite3_module *pModule = pVCur->pVtab->pModule;
  73794. assert( pVCur->pVtab->nRef>0 );
  73795. pVCur->pVtab->nRef--;
  73796. pModule->xClose(pVCur);
  73797. break;
  73798. }
  73799. #endif
  73800. }
  73801. }
  73802. /*
  73803. ** Close all cursors in the current frame.
  73804. */
  73805. static void closeCursorsInFrame(Vdbe *p){
  73806. if( p->apCsr ){
  73807. int i;
  73808. for(i=0; i<p->nCursor; i++){
  73809. VdbeCursor *pC = p->apCsr[i];
  73810. if( pC ){
  73811. sqlite3VdbeFreeCursor(p, pC);
  73812. p->apCsr[i] = 0;
  73813. }
  73814. }
  73815. }
  73816. }
  73817. /*
  73818. ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
  73819. ** is used, for example, when a trigger sub-program is halted to restore
  73820. ** control to the main program.
  73821. */
  73822. SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
  73823. Vdbe *v = pFrame->v;
  73824. closeCursorsInFrame(v);
  73825. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  73826. v->anExec = pFrame->anExec;
  73827. #endif
  73828. v->aOp = pFrame->aOp;
  73829. v->nOp = pFrame->nOp;
  73830. v->aMem = pFrame->aMem;
  73831. v->nMem = pFrame->nMem;
  73832. v->apCsr = pFrame->apCsr;
  73833. v->nCursor = pFrame->nCursor;
  73834. v->db->lastRowid = pFrame->lastRowid;
  73835. v->nChange = pFrame->nChange;
  73836. v->db->nChange = pFrame->nDbChange;
  73837. sqlite3VdbeDeleteAuxData(v->db, &v->pAuxData, -1, 0);
  73838. v->pAuxData = pFrame->pAuxData;
  73839. pFrame->pAuxData = 0;
  73840. return pFrame->pc;
  73841. }
  73842. /*
  73843. ** Close all cursors.
  73844. **
  73845. ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
  73846. ** cell array. This is necessary as the memory cell array may contain
  73847. ** pointers to VdbeFrame objects, which may in turn contain pointers to
  73848. ** open cursors.
  73849. */
  73850. static void closeAllCursors(Vdbe *p){
  73851. if( p->pFrame ){
  73852. VdbeFrame *pFrame;
  73853. for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
  73854. sqlite3VdbeFrameRestore(pFrame);
  73855. p->pFrame = 0;
  73856. p->nFrame = 0;
  73857. }
  73858. assert( p->nFrame==0 );
  73859. closeCursorsInFrame(p);
  73860. if( p->aMem ){
  73861. releaseMemArray(p->aMem, p->nMem);
  73862. }
  73863. while( p->pDelFrame ){
  73864. VdbeFrame *pDel = p->pDelFrame;
  73865. p->pDelFrame = pDel->pParent;
  73866. sqlite3VdbeFrameDelete(pDel);
  73867. }
  73868. /* Delete any auxdata allocations made by the VM */
  73869. if( p->pAuxData ) sqlite3VdbeDeleteAuxData(p->db, &p->pAuxData, -1, 0);
  73870. assert( p->pAuxData==0 );
  73871. }
  73872. /*
  73873. ** Set the number of result columns that will be returned by this SQL
  73874. ** statement. This is now set at compile time, rather than during
  73875. ** execution of the vdbe program so that sqlite3_column_count() can
  73876. ** be called on an SQL statement before sqlite3_step().
  73877. */
  73878. SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
  73879. int n;
  73880. sqlite3 *db = p->db;
  73881. if( p->nResColumn ){
  73882. releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
  73883. sqlite3DbFree(db, p->aColName);
  73884. }
  73885. n = nResColumn*COLNAME_N;
  73886. p->nResColumn = (u16)nResColumn;
  73887. p->aColName = (Mem*)sqlite3DbMallocRawNN(db, sizeof(Mem)*n );
  73888. if( p->aColName==0 ) return;
  73889. initMemArray(p->aColName, n, db, MEM_Null);
  73890. }
  73891. /*
  73892. ** Set the name of the idx'th column to be returned by the SQL statement.
  73893. ** zName must be a pointer to a nul terminated string.
  73894. **
  73895. ** This call must be made after a call to sqlite3VdbeSetNumCols().
  73896. **
  73897. ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
  73898. ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
  73899. ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
  73900. */
  73901. SQLITE_PRIVATE int sqlite3VdbeSetColName(
  73902. Vdbe *p, /* Vdbe being configured */
  73903. int idx, /* Index of column zName applies to */
  73904. int var, /* One of the COLNAME_* constants */
  73905. const char *zName, /* Pointer to buffer containing name */
  73906. void (*xDel)(void*) /* Memory management strategy for zName */
  73907. ){
  73908. int rc;
  73909. Mem *pColName;
  73910. assert( idx<p->nResColumn );
  73911. assert( var<COLNAME_N );
  73912. if( p->db->mallocFailed ){
  73913. assert( !zName || xDel!=SQLITE_DYNAMIC );
  73914. return SQLITE_NOMEM_BKPT;
  73915. }
  73916. assert( p->aColName!=0 );
  73917. pColName = &(p->aColName[idx+var*p->nResColumn]);
  73918. rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
  73919. assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
  73920. return rc;
  73921. }
  73922. /*
  73923. ** A read or write transaction may or may not be active on database handle
  73924. ** db. If a transaction is active, commit it. If there is a
  73925. ** write-transaction spanning more than one database file, this routine
  73926. ** takes care of the master journal trickery.
  73927. */
  73928. static int vdbeCommit(sqlite3 *db, Vdbe *p){
  73929. int i;
  73930. int nTrans = 0; /* Number of databases with an active write-transaction
  73931. ** that are candidates for a two-phase commit using a
  73932. ** master-journal */
  73933. int rc = SQLITE_OK;
  73934. int needXcommit = 0;
  73935. #ifdef SQLITE_OMIT_VIRTUALTABLE
  73936. /* With this option, sqlite3VtabSync() is defined to be simply
  73937. ** SQLITE_OK so p is not used.
  73938. */
  73939. UNUSED_PARAMETER(p);
  73940. #endif
  73941. /* Before doing anything else, call the xSync() callback for any
  73942. ** virtual module tables written in this transaction. This has to
  73943. ** be done before determining whether a master journal file is
  73944. ** required, as an xSync() callback may add an attached database
  73945. ** to the transaction.
  73946. */
  73947. rc = sqlite3VtabSync(db, p);
  73948. /* This loop determines (a) if the commit hook should be invoked and
  73949. ** (b) how many database files have open write transactions, not
  73950. ** including the temp database. (b) is important because if more than
  73951. ** one database file has an open write transaction, a master journal
  73952. ** file is required for an atomic commit.
  73953. */
  73954. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  73955. Btree *pBt = db->aDb[i].pBt;
  73956. if( sqlite3BtreeIsInTrans(pBt) ){
  73957. /* Whether or not a database might need a master journal depends upon
  73958. ** its journal mode (among other things). This matrix determines which
  73959. ** journal modes use a master journal and which do not */
  73960. static const u8 aMJNeeded[] = {
  73961. /* DELETE */ 1,
  73962. /* PERSIST */ 1,
  73963. /* OFF */ 0,
  73964. /* TRUNCATE */ 1,
  73965. /* MEMORY */ 0,
  73966. /* WAL */ 0
  73967. };
  73968. Pager *pPager; /* Pager associated with pBt */
  73969. needXcommit = 1;
  73970. sqlite3BtreeEnter(pBt);
  73971. pPager = sqlite3BtreePager(pBt);
  73972. if( db->aDb[i].safety_level!=PAGER_SYNCHRONOUS_OFF
  73973. && aMJNeeded[sqlite3PagerGetJournalMode(pPager)]
  73974. && sqlite3PagerIsMemdb(pPager)==0
  73975. ){
  73976. assert( i!=1 );
  73977. nTrans++;
  73978. }
  73979. rc = sqlite3PagerExclusiveLock(pPager);
  73980. sqlite3BtreeLeave(pBt);
  73981. }
  73982. }
  73983. if( rc!=SQLITE_OK ){
  73984. return rc;
  73985. }
  73986. /* If there are any write-transactions at all, invoke the commit hook */
  73987. if( needXcommit && db->xCommitCallback ){
  73988. rc = db->xCommitCallback(db->pCommitArg);
  73989. if( rc ){
  73990. return SQLITE_CONSTRAINT_COMMITHOOK;
  73991. }
  73992. }
  73993. /* The simple case - no more than one database file (not counting the
  73994. ** TEMP database) has a transaction active. There is no need for the
  73995. ** master-journal.
  73996. **
  73997. ** If the return value of sqlite3BtreeGetFilename() is a zero length
  73998. ** string, it means the main database is :memory: or a temp file. In
  73999. ** that case we do not support atomic multi-file commits, so use the
  74000. ** simple case then too.
  74001. */
  74002. if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
  74003. || nTrans<=1
  74004. ){
  74005. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  74006. Btree *pBt = db->aDb[i].pBt;
  74007. if( pBt ){
  74008. rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
  74009. }
  74010. }
  74011. /* Do the commit only if all databases successfully complete phase 1.
  74012. ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
  74013. ** IO error while deleting or truncating a journal file. It is unlikely,
  74014. ** but could happen. In this case abandon processing and return the error.
  74015. */
  74016. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  74017. Btree *pBt = db->aDb[i].pBt;
  74018. if( pBt ){
  74019. rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
  74020. }
  74021. }
  74022. if( rc==SQLITE_OK ){
  74023. sqlite3VtabCommit(db);
  74024. }
  74025. }
  74026. /* The complex case - There is a multi-file write-transaction active.
  74027. ** This requires a master journal file to ensure the transaction is
  74028. ** committed atomically.
  74029. */
  74030. #ifndef SQLITE_OMIT_DISKIO
  74031. else{
  74032. sqlite3_vfs *pVfs = db->pVfs;
  74033. char *zMaster = 0; /* File-name for the master journal */
  74034. char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
  74035. sqlite3_file *pMaster = 0;
  74036. i64 offset = 0;
  74037. int res;
  74038. int retryCount = 0;
  74039. int nMainFile;
  74040. /* Select a master journal file name */
  74041. nMainFile = sqlite3Strlen30(zMainFile);
  74042. zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
  74043. if( zMaster==0 ) return SQLITE_NOMEM_BKPT;
  74044. do {
  74045. u32 iRandom;
  74046. if( retryCount ){
  74047. if( retryCount>100 ){
  74048. sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
  74049. sqlite3OsDelete(pVfs, zMaster, 0);
  74050. break;
  74051. }else if( retryCount==1 ){
  74052. sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
  74053. }
  74054. }
  74055. retryCount++;
  74056. sqlite3_randomness(sizeof(iRandom), &iRandom);
  74057. sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
  74058. (iRandom>>8)&0xffffff, iRandom&0xff);
  74059. /* The antipenultimate character of the master journal name must
  74060. ** be "9" to avoid name collisions when using 8+3 filenames. */
  74061. assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
  74062. sqlite3FileSuffix3(zMainFile, zMaster);
  74063. rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
  74064. }while( rc==SQLITE_OK && res );
  74065. if( rc==SQLITE_OK ){
  74066. /* Open the master journal. */
  74067. rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
  74068. SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
  74069. SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
  74070. );
  74071. }
  74072. if( rc!=SQLITE_OK ){
  74073. sqlite3DbFree(db, zMaster);
  74074. return rc;
  74075. }
  74076. /* Write the name of each database file in the transaction into the new
  74077. ** master journal file. If an error occurs at this point close
  74078. ** and delete the master journal file. All the individual journal files
  74079. ** still have 'null' as the master journal pointer, so they will roll
  74080. ** back independently if a failure occurs.
  74081. */
  74082. for(i=0; i<db->nDb; i++){
  74083. Btree *pBt = db->aDb[i].pBt;
  74084. if( sqlite3BtreeIsInTrans(pBt) ){
  74085. char const *zFile = sqlite3BtreeGetJournalname(pBt);
  74086. if( zFile==0 ){
  74087. continue; /* Ignore TEMP and :memory: databases */
  74088. }
  74089. assert( zFile[0]!=0 );
  74090. rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
  74091. offset += sqlite3Strlen30(zFile)+1;
  74092. if( rc!=SQLITE_OK ){
  74093. sqlite3OsCloseFree(pMaster);
  74094. sqlite3OsDelete(pVfs, zMaster, 0);
  74095. sqlite3DbFree(db, zMaster);
  74096. return rc;
  74097. }
  74098. }
  74099. }
  74100. /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
  74101. ** flag is set this is not required.
  74102. */
  74103. if( 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
  74104. && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
  74105. ){
  74106. sqlite3OsCloseFree(pMaster);
  74107. sqlite3OsDelete(pVfs, zMaster, 0);
  74108. sqlite3DbFree(db, zMaster);
  74109. return rc;
  74110. }
  74111. /* Sync all the db files involved in the transaction. The same call
  74112. ** sets the master journal pointer in each individual journal. If
  74113. ** an error occurs here, do not delete the master journal file.
  74114. **
  74115. ** If the error occurs during the first call to
  74116. ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
  74117. ** master journal file will be orphaned. But we cannot delete it,
  74118. ** in case the master journal file name was written into the journal
  74119. ** file before the failure occurred.
  74120. */
  74121. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  74122. Btree *pBt = db->aDb[i].pBt;
  74123. if( pBt ){
  74124. rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
  74125. }
  74126. }
  74127. sqlite3OsCloseFree(pMaster);
  74128. assert( rc!=SQLITE_BUSY );
  74129. if( rc!=SQLITE_OK ){
  74130. sqlite3DbFree(db, zMaster);
  74131. return rc;
  74132. }
  74133. /* Delete the master journal file. This commits the transaction. After
  74134. ** doing this the directory is synced again before any individual
  74135. ** transaction files are deleted.
  74136. */
  74137. rc = sqlite3OsDelete(pVfs, zMaster, 1);
  74138. sqlite3DbFree(db, zMaster);
  74139. zMaster = 0;
  74140. if( rc ){
  74141. return rc;
  74142. }
  74143. /* All files and directories have already been synced, so the following
  74144. ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
  74145. ** deleting or truncating journals. If something goes wrong while
  74146. ** this is happening we don't really care. The integrity of the
  74147. ** transaction is already guaranteed, but some stray 'cold' journals
  74148. ** may be lying around. Returning an error code won't help matters.
  74149. */
  74150. disable_simulated_io_errors();
  74151. sqlite3BeginBenignMalloc();
  74152. for(i=0; i<db->nDb; i++){
  74153. Btree *pBt = db->aDb[i].pBt;
  74154. if( pBt ){
  74155. sqlite3BtreeCommitPhaseTwo(pBt, 1);
  74156. }
  74157. }
  74158. sqlite3EndBenignMalloc();
  74159. enable_simulated_io_errors();
  74160. sqlite3VtabCommit(db);
  74161. }
  74162. #endif
  74163. return rc;
  74164. }
  74165. /*
  74166. ** This routine checks that the sqlite3.nVdbeActive count variable
  74167. ** matches the number of vdbe's in the list sqlite3.pVdbe that are
  74168. ** currently active. An assertion fails if the two counts do not match.
  74169. ** This is an internal self-check only - it is not an essential processing
  74170. ** step.
  74171. **
  74172. ** This is a no-op if NDEBUG is defined.
  74173. */
  74174. #ifndef NDEBUG
  74175. static void checkActiveVdbeCnt(sqlite3 *db){
  74176. Vdbe *p;
  74177. int cnt = 0;
  74178. int nWrite = 0;
  74179. int nRead = 0;
  74180. p = db->pVdbe;
  74181. while( p ){
  74182. if( sqlite3_stmt_busy((sqlite3_stmt*)p) ){
  74183. cnt++;
  74184. if( p->readOnly==0 ) nWrite++;
  74185. if( p->bIsReader ) nRead++;
  74186. }
  74187. p = p->pNext;
  74188. }
  74189. assert( cnt==db->nVdbeActive );
  74190. assert( nWrite==db->nVdbeWrite );
  74191. assert( nRead==db->nVdbeRead );
  74192. }
  74193. #else
  74194. #define checkActiveVdbeCnt(x)
  74195. #endif
  74196. /*
  74197. ** If the Vdbe passed as the first argument opened a statement-transaction,
  74198. ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
  74199. ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
  74200. ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
  74201. ** statement transaction is committed.
  74202. **
  74203. ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
  74204. ** Otherwise SQLITE_OK.
  74205. */
  74206. static SQLITE_NOINLINE int vdbeCloseStatement(Vdbe *p, int eOp){
  74207. sqlite3 *const db = p->db;
  74208. int rc = SQLITE_OK;
  74209. int i;
  74210. const int iSavepoint = p->iStatement-1;
  74211. assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
  74212. assert( db->nStatement>0 );
  74213. assert( p->iStatement==(db->nStatement+db->nSavepoint) );
  74214. for(i=0; i<db->nDb; i++){
  74215. int rc2 = SQLITE_OK;
  74216. Btree *pBt = db->aDb[i].pBt;
  74217. if( pBt ){
  74218. if( eOp==SAVEPOINT_ROLLBACK ){
  74219. rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
  74220. }
  74221. if( rc2==SQLITE_OK ){
  74222. rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
  74223. }
  74224. if( rc==SQLITE_OK ){
  74225. rc = rc2;
  74226. }
  74227. }
  74228. }
  74229. db->nStatement--;
  74230. p->iStatement = 0;
  74231. if( rc==SQLITE_OK ){
  74232. if( eOp==SAVEPOINT_ROLLBACK ){
  74233. rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
  74234. }
  74235. if( rc==SQLITE_OK ){
  74236. rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
  74237. }
  74238. }
  74239. /* If the statement transaction is being rolled back, also restore the
  74240. ** database handles deferred constraint counter to the value it had when
  74241. ** the statement transaction was opened. */
  74242. if( eOp==SAVEPOINT_ROLLBACK ){
  74243. db->nDeferredCons = p->nStmtDefCons;
  74244. db->nDeferredImmCons = p->nStmtDefImmCons;
  74245. }
  74246. return rc;
  74247. }
  74248. SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
  74249. if( p->db->nStatement && p->iStatement ){
  74250. return vdbeCloseStatement(p, eOp);
  74251. }
  74252. return SQLITE_OK;
  74253. }
  74254. /*
  74255. ** This function is called when a transaction opened by the database
  74256. ** handle associated with the VM passed as an argument is about to be
  74257. ** committed. If there are outstanding deferred foreign key constraint
  74258. ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
  74259. **
  74260. ** If there are outstanding FK violations and this function returns
  74261. ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
  74262. ** and write an error message to it. Then return SQLITE_ERROR.
  74263. */
  74264. #ifndef SQLITE_OMIT_FOREIGN_KEY
  74265. SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
  74266. sqlite3 *db = p->db;
  74267. if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0)
  74268. || (!deferred && p->nFkConstraint>0)
  74269. ){
  74270. p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
  74271. p->errorAction = OE_Abort;
  74272. sqlite3VdbeError(p, "FOREIGN KEY constraint failed");
  74273. return SQLITE_ERROR;
  74274. }
  74275. return SQLITE_OK;
  74276. }
  74277. #endif
  74278. /*
  74279. ** This routine is called the when a VDBE tries to halt. If the VDBE
  74280. ** has made changes and is in autocommit mode, then commit those
  74281. ** changes. If a rollback is needed, then do the rollback.
  74282. **
  74283. ** This routine is the only way to move the state of a VM from
  74284. ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT. It is harmless to
  74285. ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
  74286. **
  74287. ** Return an error code. If the commit could not complete because of
  74288. ** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it
  74289. ** means the close did not happen and needs to be repeated.
  74290. */
  74291. SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
  74292. int rc; /* Used to store transient return codes */
  74293. sqlite3 *db = p->db;
  74294. /* This function contains the logic that determines if a statement or
  74295. ** transaction will be committed or rolled back as a result of the
  74296. ** execution of this virtual machine.
  74297. **
  74298. ** If any of the following errors occur:
  74299. **
  74300. ** SQLITE_NOMEM
  74301. ** SQLITE_IOERR
  74302. ** SQLITE_FULL
  74303. ** SQLITE_INTERRUPT
  74304. **
  74305. ** Then the internal cache might have been left in an inconsistent
  74306. ** state. We need to rollback the statement transaction, if there is
  74307. ** one, or the complete transaction if there is no statement transaction.
  74308. */
  74309. if( p->magic!=VDBE_MAGIC_RUN ){
  74310. return SQLITE_OK;
  74311. }
  74312. if( db->mallocFailed ){
  74313. p->rc = SQLITE_NOMEM_BKPT;
  74314. }
  74315. closeAllCursors(p);
  74316. checkActiveVdbeCnt(db);
  74317. /* No commit or rollback needed if the program never started or if the
  74318. ** SQL statement does not read or write a database file. */
  74319. if( p->pc>=0 && p->bIsReader ){
  74320. int mrc; /* Primary error code from p->rc */
  74321. int eStatementOp = 0;
  74322. int isSpecialError; /* Set to true if a 'special' error */
  74323. /* Lock all btrees used by the statement */
  74324. sqlite3VdbeEnter(p);
  74325. /* Check for one of the special errors */
  74326. mrc = p->rc & 0xff;
  74327. isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
  74328. || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
  74329. if( isSpecialError ){
  74330. /* If the query was read-only and the error code is SQLITE_INTERRUPT,
  74331. ** no rollback is necessary. Otherwise, at least a savepoint
  74332. ** transaction must be rolled back to restore the database to a
  74333. ** consistent state.
  74334. **
  74335. ** Even if the statement is read-only, it is important to perform
  74336. ** a statement or transaction rollback operation. If the error
  74337. ** occurred while writing to the journal, sub-journal or database
  74338. ** file as part of an effort to free up cache space (see function
  74339. ** pagerStress() in pager.c), the rollback is required to restore
  74340. ** the pager to a consistent state.
  74341. */
  74342. if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
  74343. if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
  74344. eStatementOp = SAVEPOINT_ROLLBACK;
  74345. }else{
  74346. /* We are forced to roll back the active transaction. Before doing
  74347. ** so, abort any other statements this handle currently has active.
  74348. */
  74349. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  74350. sqlite3CloseSavepoints(db);
  74351. db->autoCommit = 1;
  74352. p->nChange = 0;
  74353. }
  74354. }
  74355. }
  74356. /* Check for immediate foreign key violations. */
  74357. if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
  74358. sqlite3VdbeCheckFk(p, 0);
  74359. }
  74360. /* If the auto-commit flag is set and this is the only active writer
  74361. ** VM, then we do either a commit or rollback of the current transaction.
  74362. **
  74363. ** Note: This block also runs if one of the special errors handled
  74364. ** above has occurred.
  74365. */
  74366. if( !sqlite3VtabInSync(db)
  74367. && db->autoCommit
  74368. && db->nVdbeWrite==(p->readOnly==0)
  74369. ){
  74370. if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
  74371. rc = sqlite3VdbeCheckFk(p, 1);
  74372. if( rc!=SQLITE_OK ){
  74373. if( NEVER(p->readOnly) ){
  74374. sqlite3VdbeLeave(p);
  74375. return SQLITE_ERROR;
  74376. }
  74377. rc = SQLITE_CONSTRAINT_FOREIGNKEY;
  74378. }else{
  74379. /* The auto-commit flag is true, the vdbe program was successful
  74380. ** or hit an 'OR FAIL' constraint and there are no deferred foreign
  74381. ** key constraints to hold up the transaction. This means a commit
  74382. ** is required. */
  74383. rc = vdbeCommit(db, p);
  74384. }
  74385. if( rc==SQLITE_BUSY && p->readOnly ){
  74386. sqlite3VdbeLeave(p);
  74387. return SQLITE_BUSY;
  74388. }else if( rc!=SQLITE_OK ){
  74389. p->rc = rc;
  74390. sqlite3RollbackAll(db, SQLITE_OK);
  74391. p->nChange = 0;
  74392. }else{
  74393. db->nDeferredCons = 0;
  74394. db->nDeferredImmCons = 0;
  74395. db->flags &= ~(u64)SQLITE_DeferFKs;
  74396. sqlite3CommitInternalChanges(db);
  74397. }
  74398. }else{
  74399. sqlite3RollbackAll(db, SQLITE_OK);
  74400. p->nChange = 0;
  74401. }
  74402. db->nStatement = 0;
  74403. }else if( eStatementOp==0 ){
  74404. if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
  74405. eStatementOp = SAVEPOINT_RELEASE;
  74406. }else if( p->errorAction==OE_Abort ){
  74407. eStatementOp = SAVEPOINT_ROLLBACK;
  74408. }else{
  74409. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  74410. sqlite3CloseSavepoints(db);
  74411. db->autoCommit = 1;
  74412. p->nChange = 0;
  74413. }
  74414. }
  74415. /* If eStatementOp is non-zero, then a statement transaction needs to
  74416. ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
  74417. ** do so. If this operation returns an error, and the current statement
  74418. ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
  74419. ** current statement error code.
  74420. */
  74421. if( eStatementOp ){
  74422. rc = sqlite3VdbeCloseStatement(p, eStatementOp);
  74423. if( rc ){
  74424. if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
  74425. p->rc = rc;
  74426. sqlite3DbFree(db, p->zErrMsg);
  74427. p->zErrMsg = 0;
  74428. }
  74429. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  74430. sqlite3CloseSavepoints(db);
  74431. db->autoCommit = 1;
  74432. p->nChange = 0;
  74433. }
  74434. }
  74435. /* If this was an INSERT, UPDATE or DELETE and no statement transaction
  74436. ** has been rolled back, update the database connection change-counter.
  74437. */
  74438. if( p->changeCntOn ){
  74439. if( eStatementOp!=SAVEPOINT_ROLLBACK ){
  74440. sqlite3VdbeSetChanges(db, p->nChange);
  74441. }else{
  74442. sqlite3VdbeSetChanges(db, 0);
  74443. }
  74444. p->nChange = 0;
  74445. }
  74446. /* Release the locks */
  74447. sqlite3VdbeLeave(p);
  74448. }
  74449. /* We have successfully halted and closed the VM. Record this fact. */
  74450. if( p->pc>=0 ){
  74451. db->nVdbeActive--;
  74452. if( !p->readOnly ) db->nVdbeWrite--;
  74453. if( p->bIsReader ) db->nVdbeRead--;
  74454. assert( db->nVdbeActive>=db->nVdbeRead );
  74455. assert( db->nVdbeRead>=db->nVdbeWrite );
  74456. assert( db->nVdbeWrite>=0 );
  74457. }
  74458. p->magic = VDBE_MAGIC_HALT;
  74459. checkActiveVdbeCnt(db);
  74460. if( db->mallocFailed ){
  74461. p->rc = SQLITE_NOMEM_BKPT;
  74462. }
  74463. /* If the auto-commit flag is set to true, then any locks that were held
  74464. ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
  74465. ** to invoke any required unlock-notify callbacks.
  74466. */
  74467. if( db->autoCommit ){
  74468. sqlite3ConnectionUnlocked(db);
  74469. }
  74470. assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
  74471. return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
  74472. }
  74473. /*
  74474. ** Each VDBE holds the result of the most recent sqlite3_step() call
  74475. ** in p->rc. This routine sets that result back to SQLITE_OK.
  74476. */
  74477. SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
  74478. p->rc = SQLITE_OK;
  74479. }
  74480. /*
  74481. ** Copy the error code and error message belonging to the VDBE passed
  74482. ** as the first argument to its database handle (so that they will be
  74483. ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
  74484. **
  74485. ** This function does not clear the VDBE error code or message, just
  74486. ** copies them to the database handle.
  74487. */
  74488. SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
  74489. sqlite3 *db = p->db;
  74490. int rc = p->rc;
  74491. if( p->zErrMsg ){
  74492. db->bBenignMalloc++;
  74493. sqlite3BeginBenignMalloc();
  74494. if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db);
  74495. sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
  74496. sqlite3EndBenignMalloc();
  74497. db->bBenignMalloc--;
  74498. }else if( db->pErr ){
  74499. sqlite3ValueSetNull(db->pErr);
  74500. }
  74501. db->errCode = rc;
  74502. return rc;
  74503. }
  74504. #ifdef SQLITE_ENABLE_SQLLOG
  74505. /*
  74506. ** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
  74507. ** invoke it.
  74508. */
  74509. static void vdbeInvokeSqllog(Vdbe *v){
  74510. if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
  74511. char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
  74512. assert( v->db->init.busy==0 );
  74513. if( zExpanded ){
  74514. sqlite3GlobalConfig.xSqllog(
  74515. sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
  74516. );
  74517. sqlite3DbFree(v->db, zExpanded);
  74518. }
  74519. }
  74520. }
  74521. #else
  74522. # define vdbeInvokeSqllog(x)
  74523. #endif
  74524. /*
  74525. ** Clean up a VDBE after execution but do not delete the VDBE just yet.
  74526. ** Write any error messages into *pzErrMsg. Return the result code.
  74527. **
  74528. ** After this routine is run, the VDBE should be ready to be executed
  74529. ** again.
  74530. **
  74531. ** To look at it another way, this routine resets the state of the
  74532. ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
  74533. ** VDBE_MAGIC_INIT.
  74534. */
  74535. SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
  74536. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  74537. int i;
  74538. #endif
  74539. sqlite3 *db;
  74540. db = p->db;
  74541. /* If the VM did not run to completion or if it encountered an
  74542. ** error, then it might not have been halted properly. So halt
  74543. ** it now.
  74544. */
  74545. sqlite3VdbeHalt(p);
  74546. /* If the VDBE has been run even partially, then transfer the error code
  74547. ** and error message from the VDBE into the main database structure. But
  74548. ** if the VDBE has just been set to run but has not actually executed any
  74549. ** instructions yet, leave the main database error information unchanged.
  74550. */
  74551. if( p->pc>=0 ){
  74552. vdbeInvokeSqllog(p);
  74553. sqlite3VdbeTransferError(p);
  74554. if( p->runOnlyOnce ) p->expired = 1;
  74555. }else if( p->rc && p->expired ){
  74556. /* The expired flag was set on the VDBE before the first call
  74557. ** to sqlite3_step(). For consistency (since sqlite3_step() was
  74558. ** called), set the database error in this case as well.
  74559. */
  74560. sqlite3ErrorWithMsg(db, p->rc, p->zErrMsg ? "%s" : 0, p->zErrMsg);
  74561. }
  74562. /* Reset register contents and reclaim error message memory.
  74563. */
  74564. #ifdef SQLITE_DEBUG
  74565. /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
  74566. ** Vdbe.aMem[] arrays have already been cleaned up. */
  74567. if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
  74568. if( p->aMem ){
  74569. for(i=0; i<p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined );
  74570. }
  74571. #endif
  74572. sqlite3DbFree(db, p->zErrMsg);
  74573. p->zErrMsg = 0;
  74574. p->pResultSet = 0;
  74575. #ifdef SQLITE_DEBUG
  74576. p->nWrite = 0;
  74577. #endif
  74578. /* Save profiling information from this VDBE run.
  74579. */
  74580. #ifdef VDBE_PROFILE
  74581. {
  74582. FILE *out = fopen("vdbe_profile.out", "a");
  74583. if( out ){
  74584. fprintf(out, "---- ");
  74585. for(i=0; i<p->nOp; i++){
  74586. fprintf(out, "%02x", p->aOp[i].opcode);
  74587. }
  74588. fprintf(out, "\n");
  74589. if( p->zSql ){
  74590. char c, pc = 0;
  74591. fprintf(out, "-- ");
  74592. for(i=0; (c = p->zSql[i])!=0; i++){
  74593. if( pc=='\n' ) fprintf(out, "-- ");
  74594. putc(c, out);
  74595. pc = c;
  74596. }
  74597. if( pc!='\n' ) fprintf(out, "\n");
  74598. }
  74599. for(i=0; i<p->nOp; i++){
  74600. char zHdr[100];
  74601. sqlite3_snprintf(sizeof(zHdr), zHdr, "%6u %12llu %8llu ",
  74602. p->aOp[i].cnt,
  74603. p->aOp[i].cycles,
  74604. p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
  74605. );
  74606. fprintf(out, "%s", zHdr);
  74607. sqlite3VdbePrintOp(out, i, &p->aOp[i]);
  74608. }
  74609. fclose(out);
  74610. }
  74611. }
  74612. #endif
  74613. p->magic = VDBE_MAGIC_RESET;
  74614. return p->rc & db->errMask;
  74615. }
  74616. /*
  74617. ** Clean up and delete a VDBE after execution. Return an integer which is
  74618. ** the result code. Write any error message text into *pzErrMsg.
  74619. */
  74620. SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
  74621. int rc = SQLITE_OK;
  74622. if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
  74623. rc = sqlite3VdbeReset(p);
  74624. assert( (rc & p->db->errMask)==rc );
  74625. }
  74626. sqlite3VdbeDelete(p);
  74627. return rc;
  74628. }
  74629. /*
  74630. ** If parameter iOp is less than zero, then invoke the destructor for
  74631. ** all auxiliary data pointers currently cached by the VM passed as
  74632. ** the first argument.
  74633. **
  74634. ** Or, if iOp is greater than or equal to zero, then the destructor is
  74635. ** only invoked for those auxiliary data pointers created by the user
  74636. ** function invoked by the OP_Function opcode at instruction iOp of
  74637. ** VM pVdbe, and only then if:
  74638. **
  74639. ** * the associated function parameter is the 32nd or later (counting
  74640. ** from left to right), or
  74641. **
  74642. ** * the corresponding bit in argument mask is clear (where the first
  74643. ** function parameter corresponds to bit 0 etc.).
  74644. */
  74645. SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3 *db, AuxData **pp, int iOp, int mask){
  74646. while( *pp ){
  74647. AuxData *pAux = *pp;
  74648. if( (iOp<0)
  74649. || (pAux->iAuxOp==iOp
  74650. && pAux->iAuxArg>=0
  74651. && (pAux->iAuxArg>31 || !(mask & MASKBIT32(pAux->iAuxArg))))
  74652. ){
  74653. testcase( pAux->iAuxArg==31 );
  74654. if( pAux->xDeleteAux ){
  74655. pAux->xDeleteAux(pAux->pAux);
  74656. }
  74657. *pp = pAux->pNextAux;
  74658. sqlite3DbFree(db, pAux);
  74659. }else{
  74660. pp= &pAux->pNextAux;
  74661. }
  74662. }
  74663. }
  74664. /*
  74665. ** Free all memory associated with the Vdbe passed as the second argument,
  74666. ** except for object itself, which is preserved.
  74667. **
  74668. ** The difference between this function and sqlite3VdbeDelete() is that
  74669. ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
  74670. ** the database connection and frees the object itself.
  74671. */
  74672. SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
  74673. SubProgram *pSub, *pNext;
  74674. assert( p->db==0 || p->db==db );
  74675. releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
  74676. for(pSub=p->pProgram; pSub; pSub=pNext){
  74677. pNext = pSub->pNext;
  74678. vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
  74679. sqlite3DbFree(db, pSub);
  74680. }
  74681. if( p->magic!=VDBE_MAGIC_INIT ){
  74682. releaseMemArray(p->aVar, p->nVar);
  74683. sqlite3DbFree(db, p->pVList);
  74684. sqlite3DbFree(db, p->pFree);
  74685. }
  74686. vdbeFreeOpArray(db, p->aOp, p->nOp);
  74687. sqlite3DbFree(db, p->aColName);
  74688. sqlite3DbFree(db, p->zSql);
  74689. #ifdef SQLITE_ENABLE_NORMALIZE
  74690. sqlite3DbFree(db, p->zNormSql);
  74691. {
  74692. DblquoteStr *pThis, *pNext;
  74693. for(pThis=p->pDblStr; pThis; pThis=pNext){
  74694. pNext = pThis->pNextStr;
  74695. sqlite3DbFree(db, pThis);
  74696. }
  74697. }
  74698. #endif
  74699. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  74700. {
  74701. int i;
  74702. for(i=0; i<p->nScan; i++){
  74703. sqlite3DbFree(db, p->aScan[i].zName);
  74704. }
  74705. sqlite3DbFree(db, p->aScan);
  74706. }
  74707. #endif
  74708. }
  74709. /*
  74710. ** Delete an entire VDBE.
  74711. */
  74712. SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
  74713. sqlite3 *db;
  74714. assert( p!=0 );
  74715. db = p->db;
  74716. assert( sqlite3_mutex_held(db->mutex) );
  74717. sqlite3VdbeClearObject(db, p);
  74718. if( p->pPrev ){
  74719. p->pPrev->pNext = p->pNext;
  74720. }else{
  74721. assert( db->pVdbe==p );
  74722. db->pVdbe = p->pNext;
  74723. }
  74724. if( p->pNext ){
  74725. p->pNext->pPrev = p->pPrev;
  74726. }
  74727. p->magic = VDBE_MAGIC_DEAD;
  74728. p->db = 0;
  74729. sqlite3DbFreeNN(db, p);
  74730. }
  74731. /*
  74732. ** The cursor "p" has a pending seek operation that has not yet been
  74733. ** carried out. Seek the cursor now. If an error occurs, return
  74734. ** the appropriate error code.
  74735. */
  74736. static int SQLITE_NOINLINE handleDeferredMoveto(VdbeCursor *p){
  74737. int res, rc;
  74738. #ifdef SQLITE_TEST
  74739. extern int sqlite3_search_count;
  74740. #endif
  74741. assert( p->deferredMoveto );
  74742. assert( p->isTable );
  74743. assert( p->eCurType==CURTYPE_BTREE );
  74744. rc = sqlite3BtreeMovetoUnpacked(p->uc.pCursor, 0, p->movetoTarget, 0, &res);
  74745. if( rc ) return rc;
  74746. if( res!=0 ) return SQLITE_CORRUPT_BKPT;
  74747. #ifdef SQLITE_TEST
  74748. sqlite3_search_count++;
  74749. #endif
  74750. p->deferredMoveto = 0;
  74751. p->cacheStatus = CACHE_STALE;
  74752. return SQLITE_OK;
  74753. }
  74754. /*
  74755. ** Something has moved cursor "p" out of place. Maybe the row it was
  74756. ** pointed to was deleted out from under it. Or maybe the btree was
  74757. ** rebalanced. Whatever the cause, try to restore "p" to the place it
  74758. ** is supposed to be pointing. If the row was deleted out from under the
  74759. ** cursor, set the cursor to point to a NULL row.
  74760. */
  74761. static int SQLITE_NOINLINE handleMovedCursor(VdbeCursor *p){
  74762. int isDifferentRow, rc;
  74763. assert( p->eCurType==CURTYPE_BTREE );
  74764. assert( p->uc.pCursor!=0 );
  74765. assert( sqlite3BtreeCursorHasMoved(p->uc.pCursor) );
  74766. rc = sqlite3BtreeCursorRestore(p->uc.pCursor, &isDifferentRow);
  74767. p->cacheStatus = CACHE_STALE;
  74768. if( isDifferentRow ) p->nullRow = 1;
  74769. return rc;
  74770. }
  74771. /*
  74772. ** Check to ensure that the cursor is valid. Restore the cursor
  74773. ** if need be. Return any I/O error from the restore operation.
  74774. */
  74775. SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor *p){
  74776. assert( p->eCurType==CURTYPE_BTREE );
  74777. if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
  74778. return handleMovedCursor(p);
  74779. }
  74780. return SQLITE_OK;
  74781. }
  74782. /*
  74783. ** Make sure the cursor p is ready to read or write the row to which it
  74784. ** was last positioned. Return an error code if an OOM fault or I/O error
  74785. ** prevents us from positioning the cursor to its correct position.
  74786. **
  74787. ** If a MoveTo operation is pending on the given cursor, then do that
  74788. ** MoveTo now. If no move is pending, check to see if the row has been
  74789. ** deleted out from under the cursor and if it has, mark the row as
  74790. ** a NULL row.
  74791. **
  74792. ** If the cursor is already pointing to the correct row and that row has
  74793. ** not been deleted out from under the cursor, then this routine is a no-op.
  74794. */
  74795. SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor **pp, int *piCol){
  74796. VdbeCursor *p = *pp;
  74797. assert( p->eCurType==CURTYPE_BTREE || p->eCurType==CURTYPE_PSEUDO );
  74798. if( p->deferredMoveto ){
  74799. int iMap;
  74800. if( p->aAltMap && (iMap = p->aAltMap[1+*piCol])>0 ){
  74801. *pp = p->pAltCursor;
  74802. *piCol = iMap - 1;
  74803. return SQLITE_OK;
  74804. }
  74805. return handleDeferredMoveto(p);
  74806. }
  74807. if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
  74808. return handleMovedCursor(p);
  74809. }
  74810. return SQLITE_OK;
  74811. }
  74812. /*
  74813. ** The following functions:
  74814. **
  74815. ** sqlite3VdbeSerialType()
  74816. ** sqlite3VdbeSerialTypeLen()
  74817. ** sqlite3VdbeSerialLen()
  74818. ** sqlite3VdbeSerialPut()
  74819. ** sqlite3VdbeSerialGet()
  74820. **
  74821. ** encapsulate the code that serializes values for storage in SQLite
  74822. ** data and index records. Each serialized value consists of a
  74823. ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
  74824. ** integer, stored as a varint.
  74825. **
  74826. ** In an SQLite index record, the serial type is stored directly before
  74827. ** the blob of data that it corresponds to. In a table record, all serial
  74828. ** types are stored at the start of the record, and the blobs of data at
  74829. ** the end. Hence these functions allow the caller to handle the
  74830. ** serial-type and data blob separately.
  74831. **
  74832. ** The following table describes the various storage classes for data:
  74833. **
  74834. ** serial type bytes of data type
  74835. ** -------------- --------------- ---------------
  74836. ** 0 0 NULL
  74837. ** 1 1 signed integer
  74838. ** 2 2 signed integer
  74839. ** 3 3 signed integer
  74840. ** 4 4 signed integer
  74841. ** 5 6 signed integer
  74842. ** 6 8 signed integer
  74843. ** 7 8 IEEE float
  74844. ** 8 0 Integer constant 0
  74845. ** 9 0 Integer constant 1
  74846. ** 10,11 reserved for expansion
  74847. ** N>=12 and even (N-12)/2 BLOB
  74848. ** N>=13 and odd (N-13)/2 text
  74849. **
  74850. ** The 8 and 9 types were added in 3.3.0, file format 4. Prior versions
  74851. ** of SQLite will not understand those serial types.
  74852. */
  74853. /*
  74854. ** Return the serial-type for the value stored in pMem.
  74855. **
  74856. ** This routine might convert a large MEM_IntReal value into MEM_Real.
  74857. */
  74858. SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format, u32 *pLen){
  74859. int flags = pMem->flags;
  74860. u32 n;
  74861. assert( pLen!=0 );
  74862. if( flags&MEM_Null ){
  74863. *pLen = 0;
  74864. return 0;
  74865. }
  74866. if( flags&(MEM_Int|MEM_IntReal) ){
  74867. /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
  74868. # define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
  74869. i64 i = pMem->u.i;
  74870. u64 u;
  74871. testcase( flags & MEM_Int );
  74872. testcase( flags & MEM_IntReal );
  74873. if( i<0 ){
  74874. u = ~i;
  74875. }else{
  74876. u = i;
  74877. }
  74878. if( u<=127 ){
  74879. if( (i&1)==i && file_format>=4 ){
  74880. *pLen = 0;
  74881. return 8+(u32)u;
  74882. }else{
  74883. *pLen = 1;
  74884. return 1;
  74885. }
  74886. }
  74887. if( u<=32767 ){ *pLen = 2; return 2; }
  74888. if( u<=8388607 ){ *pLen = 3; return 3; }
  74889. if( u<=2147483647 ){ *pLen = 4; return 4; }
  74890. if( u<=MAX_6BYTE ){ *pLen = 6; return 5; }
  74891. *pLen = 8;
  74892. if( flags&MEM_IntReal ){
  74893. /* If the value is IntReal and is going to take up 8 bytes to store
  74894. ** as an integer, then we might as well make it an 8-byte floating
  74895. ** point value */
  74896. pMem->u.r = (double)pMem->u.i;
  74897. pMem->flags &= ~MEM_IntReal;
  74898. pMem->flags |= MEM_Real;
  74899. return 7;
  74900. }
  74901. return 6;
  74902. }
  74903. if( flags&MEM_Real ){
  74904. *pLen = 8;
  74905. return 7;
  74906. }
  74907. assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
  74908. assert( pMem->n>=0 );
  74909. n = (u32)pMem->n;
  74910. if( flags & MEM_Zero ){
  74911. n += pMem->u.nZero;
  74912. }
  74913. *pLen = n;
  74914. return ((n*2) + 12 + ((flags&MEM_Str)!=0));
  74915. }
  74916. /*
  74917. ** The sizes for serial types less than 128
  74918. */
  74919. static const u8 sqlite3SmallTypeSizes[] = {
  74920. /* 0 1 2 3 4 5 6 7 8 9 */
  74921. /* 0 */ 0, 1, 2, 3, 4, 6, 8, 8, 0, 0,
  74922. /* 10 */ 0, 0, 0, 0, 1, 1, 2, 2, 3, 3,
  74923. /* 20 */ 4, 4, 5, 5, 6, 6, 7, 7, 8, 8,
  74924. /* 30 */ 9, 9, 10, 10, 11, 11, 12, 12, 13, 13,
  74925. /* 40 */ 14, 14, 15, 15, 16, 16, 17, 17, 18, 18,
  74926. /* 50 */ 19, 19, 20, 20, 21, 21, 22, 22, 23, 23,
  74927. /* 60 */ 24, 24, 25, 25, 26, 26, 27, 27, 28, 28,
  74928. /* 70 */ 29, 29, 30, 30, 31, 31, 32, 32, 33, 33,
  74929. /* 80 */ 34, 34, 35, 35, 36, 36, 37, 37, 38, 38,
  74930. /* 90 */ 39, 39, 40, 40, 41, 41, 42, 42, 43, 43,
  74931. /* 100 */ 44, 44, 45, 45, 46, 46, 47, 47, 48, 48,
  74932. /* 110 */ 49, 49, 50, 50, 51, 51, 52, 52, 53, 53,
  74933. /* 120 */ 54, 54, 55, 55, 56, 56, 57, 57
  74934. };
  74935. /*
  74936. ** Return the length of the data corresponding to the supplied serial-type.
  74937. */
  74938. SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
  74939. if( serial_type>=128 ){
  74940. return (serial_type-12)/2;
  74941. }else{
  74942. assert( serial_type<12
  74943. || sqlite3SmallTypeSizes[serial_type]==(serial_type - 12)/2 );
  74944. return sqlite3SmallTypeSizes[serial_type];
  74945. }
  74946. }
  74947. SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8 serial_type){
  74948. assert( serial_type<128 );
  74949. return sqlite3SmallTypeSizes[serial_type];
  74950. }
  74951. /*
  74952. ** If we are on an architecture with mixed-endian floating
  74953. ** points (ex: ARM7) then swap the lower 4 bytes with the
  74954. ** upper 4 bytes. Return the result.
  74955. **
  74956. ** For most architectures, this is a no-op.
  74957. **
  74958. ** (later): It is reported to me that the mixed-endian problem
  74959. ** on ARM7 is an issue with GCC, not with the ARM7 chip. It seems
  74960. ** that early versions of GCC stored the two words of a 64-bit
  74961. ** float in the wrong order. And that error has been propagated
  74962. ** ever since. The blame is not necessarily with GCC, though.
  74963. ** GCC might have just copying the problem from a prior compiler.
  74964. ** I am also told that newer versions of GCC that follow a different
  74965. ** ABI get the byte order right.
  74966. **
  74967. ** Developers using SQLite on an ARM7 should compile and run their
  74968. ** application using -DSQLITE_DEBUG=1 at least once. With DEBUG
  74969. ** enabled, some asserts below will ensure that the byte order of
  74970. ** floating point values is correct.
  74971. **
  74972. ** (2007-08-30) Frank van Vugt has studied this problem closely
  74973. ** and has send his findings to the SQLite developers. Frank
  74974. ** writes that some Linux kernels offer floating point hardware
  74975. ** emulation that uses only 32-bit mantissas instead of a full
  74976. ** 48-bits as required by the IEEE standard. (This is the
  74977. ** CONFIG_FPE_FASTFPE option.) On such systems, floating point
  74978. ** byte swapping becomes very complicated. To avoid problems,
  74979. ** the necessary byte swapping is carried out using a 64-bit integer
  74980. ** rather than a 64-bit float. Frank assures us that the code here
  74981. ** works for him. We, the developers, have no way to independently
  74982. ** verify this, but Frank seems to know what he is talking about
  74983. ** so we trust him.
  74984. */
  74985. #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  74986. static u64 floatSwap(u64 in){
  74987. union {
  74988. u64 r;
  74989. u32 i[2];
  74990. } u;
  74991. u32 t;
  74992. u.r = in;
  74993. t = u.i[0];
  74994. u.i[0] = u.i[1];
  74995. u.i[1] = t;
  74996. return u.r;
  74997. }
  74998. # define swapMixedEndianFloat(X) X = floatSwap(X)
  74999. #else
  75000. # define swapMixedEndianFloat(X)
  75001. #endif
  75002. /*
  75003. ** Write the serialized data blob for the value stored in pMem into
  75004. ** buf. It is assumed that the caller has allocated sufficient space.
  75005. ** Return the number of bytes written.
  75006. **
  75007. ** nBuf is the amount of space left in buf[]. The caller is responsible
  75008. ** for allocating enough space to buf[] to hold the entire field, exclusive
  75009. ** of the pMem->u.nZero bytes for a MEM_Zero value.
  75010. **
  75011. ** Return the number of bytes actually written into buf[]. The number
  75012. ** of bytes in the zero-filled tail is included in the return value only
  75013. ** if those bytes were zeroed in buf[].
  75014. */
  75015. SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){
  75016. u32 len;
  75017. /* Integer and Real */
  75018. if( serial_type<=7 && serial_type>0 ){
  75019. u64 v;
  75020. u32 i;
  75021. if( serial_type==7 ){
  75022. assert( sizeof(v)==sizeof(pMem->u.r) );
  75023. memcpy(&v, &pMem->u.r, sizeof(v));
  75024. swapMixedEndianFloat(v);
  75025. }else{
  75026. v = pMem->u.i;
  75027. }
  75028. len = i = sqlite3SmallTypeSizes[serial_type];
  75029. assert( i>0 );
  75030. do{
  75031. buf[--i] = (u8)(v&0xFF);
  75032. v >>= 8;
  75033. }while( i );
  75034. return len;
  75035. }
  75036. /* String or blob */
  75037. if( serial_type>=12 ){
  75038. assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
  75039. == (int)sqlite3VdbeSerialTypeLen(serial_type) );
  75040. len = pMem->n;
  75041. if( len>0 ) memcpy(buf, pMem->z, len);
  75042. return len;
  75043. }
  75044. /* NULL or constants 0 or 1 */
  75045. return 0;
  75046. }
  75047. /* Input "x" is a sequence of unsigned characters that represent a
  75048. ** big-endian integer. Return the equivalent native integer
  75049. */
  75050. #define ONE_BYTE_INT(x) ((i8)(x)[0])
  75051. #define TWO_BYTE_INT(x) (256*(i8)((x)[0])|(x)[1])
  75052. #define THREE_BYTE_INT(x) (65536*(i8)((x)[0])|((x)[1]<<8)|(x)[2])
  75053. #define FOUR_BYTE_UINT(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
  75054. #define FOUR_BYTE_INT(x) (16777216*(i8)((x)[0])|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
  75055. /*
  75056. ** Deserialize the data blob pointed to by buf as serial type serial_type
  75057. ** and store the result in pMem. Return the number of bytes read.
  75058. **
  75059. ** This function is implemented as two separate routines for performance.
  75060. ** The few cases that require local variables are broken out into a separate
  75061. ** routine so that in most cases the overhead of moving the stack pointer
  75062. ** is avoided.
  75063. */
  75064. static u32 serialGet(
  75065. const unsigned char *buf, /* Buffer to deserialize from */
  75066. u32 serial_type, /* Serial type to deserialize */
  75067. Mem *pMem /* Memory cell to write value into */
  75068. ){
  75069. u64 x = FOUR_BYTE_UINT(buf);
  75070. u32 y = FOUR_BYTE_UINT(buf+4);
  75071. x = (x<<32) + y;
  75072. if( serial_type==6 ){
  75073. /* EVIDENCE-OF: R-29851-52272 Value is a big-endian 64-bit
  75074. ** twos-complement integer. */
  75075. pMem->u.i = *(i64*)&x;
  75076. pMem->flags = MEM_Int;
  75077. testcase( pMem->u.i<0 );
  75078. }else{
  75079. /* EVIDENCE-OF: R-57343-49114 Value is a big-endian IEEE 754-2008 64-bit
  75080. ** floating point number. */
  75081. #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
  75082. /* Verify that integers and floating point values use the same
  75083. ** byte order. Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
  75084. ** defined that 64-bit floating point values really are mixed
  75085. ** endian.
  75086. */
  75087. static const u64 t1 = ((u64)0x3ff00000)<<32;
  75088. static const double r1 = 1.0;
  75089. u64 t2 = t1;
  75090. swapMixedEndianFloat(t2);
  75091. assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
  75092. #endif
  75093. assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 );
  75094. swapMixedEndianFloat(x);
  75095. memcpy(&pMem->u.r, &x, sizeof(x));
  75096. pMem->flags = IsNaN(x) ? MEM_Null : MEM_Real;
  75097. }
  75098. return 8;
  75099. }
  75100. SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
  75101. const unsigned char *buf, /* Buffer to deserialize from */
  75102. u32 serial_type, /* Serial type to deserialize */
  75103. Mem *pMem /* Memory cell to write value into */
  75104. ){
  75105. switch( serial_type ){
  75106. case 10: { /* Internal use only: NULL with virtual table
  75107. ** UPDATE no-change flag set */
  75108. pMem->flags = MEM_Null|MEM_Zero;
  75109. pMem->n = 0;
  75110. pMem->u.nZero = 0;
  75111. break;
  75112. }
  75113. case 11: /* Reserved for future use */
  75114. case 0: { /* Null */
  75115. /* EVIDENCE-OF: R-24078-09375 Value is a NULL. */
  75116. pMem->flags = MEM_Null;
  75117. break;
  75118. }
  75119. case 1: {
  75120. /* EVIDENCE-OF: R-44885-25196 Value is an 8-bit twos-complement
  75121. ** integer. */
  75122. pMem->u.i = ONE_BYTE_INT(buf);
  75123. pMem->flags = MEM_Int;
  75124. testcase( pMem->u.i<0 );
  75125. return 1;
  75126. }
  75127. case 2: { /* 2-byte signed integer */
  75128. /* EVIDENCE-OF: R-49794-35026 Value is a big-endian 16-bit
  75129. ** twos-complement integer. */
  75130. pMem->u.i = TWO_BYTE_INT(buf);
  75131. pMem->flags = MEM_Int;
  75132. testcase( pMem->u.i<0 );
  75133. return 2;
  75134. }
  75135. case 3: { /* 3-byte signed integer */
  75136. /* EVIDENCE-OF: R-37839-54301 Value is a big-endian 24-bit
  75137. ** twos-complement integer. */
  75138. pMem->u.i = THREE_BYTE_INT(buf);
  75139. pMem->flags = MEM_Int;
  75140. testcase( pMem->u.i<0 );
  75141. return 3;
  75142. }
  75143. case 4: { /* 4-byte signed integer */
  75144. /* EVIDENCE-OF: R-01849-26079 Value is a big-endian 32-bit
  75145. ** twos-complement integer. */
  75146. pMem->u.i = FOUR_BYTE_INT(buf);
  75147. #ifdef __HP_cc
  75148. /* Work around a sign-extension bug in the HP compiler for HP/UX */
  75149. if( buf[0]&0x80 ) pMem->u.i |= 0xffffffff80000000LL;
  75150. #endif
  75151. pMem->flags = MEM_Int;
  75152. testcase( pMem->u.i<0 );
  75153. return 4;
  75154. }
  75155. case 5: { /* 6-byte signed integer */
  75156. /* EVIDENCE-OF: R-50385-09674 Value is a big-endian 48-bit
  75157. ** twos-complement integer. */
  75158. pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf);
  75159. pMem->flags = MEM_Int;
  75160. testcase( pMem->u.i<0 );
  75161. return 6;
  75162. }
  75163. case 6: /* 8-byte signed integer */
  75164. case 7: { /* IEEE floating point */
  75165. /* These use local variables, so do them in a separate routine
  75166. ** to avoid having to move the frame pointer in the common case */
  75167. return serialGet(buf,serial_type,pMem);
  75168. }
  75169. case 8: /* Integer 0 */
  75170. case 9: { /* Integer 1 */
  75171. /* EVIDENCE-OF: R-12976-22893 Value is the integer 0. */
  75172. /* EVIDENCE-OF: R-18143-12121 Value is the integer 1. */
  75173. pMem->u.i = serial_type-8;
  75174. pMem->flags = MEM_Int;
  75175. return 0;
  75176. }
  75177. default: {
  75178. /* EVIDENCE-OF: R-14606-31564 Value is a BLOB that is (N-12)/2 bytes in
  75179. ** length.
  75180. ** EVIDENCE-OF: R-28401-00140 Value is a string in the text encoding and
  75181. ** (N-13)/2 bytes in length. */
  75182. static const u16 aFlag[] = { MEM_Blob|MEM_Ephem, MEM_Str|MEM_Ephem };
  75183. pMem->z = (char *)buf;
  75184. pMem->n = (serial_type-12)/2;
  75185. pMem->flags = aFlag[serial_type&1];
  75186. return pMem->n;
  75187. }
  75188. }
  75189. return 0;
  75190. }
  75191. /*
  75192. ** This routine is used to allocate sufficient space for an UnpackedRecord
  75193. ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
  75194. ** the first argument is a pointer to KeyInfo structure pKeyInfo.
  75195. **
  75196. ** The space is either allocated using sqlite3DbMallocRaw() or from within
  75197. ** the unaligned buffer passed via the second and third arguments (presumably
  75198. ** stack space). If the former, then *ppFree is set to a pointer that should
  75199. ** be eventually freed by the caller using sqlite3DbFree(). Or, if the
  75200. ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
  75201. ** before returning.
  75202. **
  75203. ** If an OOM error occurs, NULL is returned.
  75204. */
  75205. SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
  75206. KeyInfo *pKeyInfo /* Description of the record */
  75207. ){
  75208. UnpackedRecord *p; /* Unpacked record to return */
  75209. int nByte; /* Number of bytes required for *p */
  75210. nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nKeyField+1);
  75211. p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
  75212. if( !p ) return 0;
  75213. p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
  75214. assert( pKeyInfo->aSortOrder!=0 );
  75215. p->pKeyInfo = pKeyInfo;
  75216. p->nField = pKeyInfo->nKeyField + 1;
  75217. return p;
  75218. }
  75219. /*
  75220. ** Given the nKey-byte encoding of a record in pKey[], populate the
  75221. ** UnpackedRecord structure indicated by the fourth argument with the
  75222. ** contents of the decoded record.
  75223. */
  75224. SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
  75225. KeyInfo *pKeyInfo, /* Information about the record format */
  75226. int nKey, /* Size of the binary record */
  75227. const void *pKey, /* The binary record */
  75228. UnpackedRecord *p /* Populate this structure before returning. */
  75229. ){
  75230. const unsigned char *aKey = (const unsigned char *)pKey;
  75231. u32 d;
  75232. u32 idx; /* Offset in aKey[] to read from */
  75233. u16 u; /* Unsigned loop counter */
  75234. u32 szHdr;
  75235. Mem *pMem = p->aMem;
  75236. p->default_rc = 0;
  75237. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  75238. idx = getVarint32(aKey, szHdr);
  75239. d = szHdr;
  75240. u = 0;
  75241. while( idx<szHdr && d<=(u32)nKey ){
  75242. u32 serial_type;
  75243. idx += getVarint32(&aKey[idx], serial_type);
  75244. pMem->enc = pKeyInfo->enc;
  75245. pMem->db = pKeyInfo->db;
  75246. /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
  75247. pMem->szMalloc = 0;
  75248. pMem->z = 0;
  75249. d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
  75250. pMem++;
  75251. if( (++u)>=p->nField ) break;
  75252. }
  75253. if( d>(u32)nKey && u ){
  75254. assert( CORRUPT_DB );
  75255. /* In a corrupt record entry, the last pMem might have been set up using
  75256. ** uninitialized memory. Overwrite its value with NULL, to prevent
  75257. ** warnings from MSAN. */
  75258. sqlite3VdbeMemSetNull(pMem-1);
  75259. }
  75260. assert( u<=pKeyInfo->nKeyField + 1 );
  75261. p->nField = u;
  75262. }
  75263. #ifdef SQLITE_DEBUG
  75264. /*
  75265. ** This function compares two index or table record keys in the same way
  75266. ** as the sqlite3VdbeRecordCompare() routine. Unlike VdbeRecordCompare(),
  75267. ** this function deserializes and compares values using the
  75268. ** sqlite3VdbeSerialGet() and sqlite3MemCompare() functions. It is used
  75269. ** in assert() statements to ensure that the optimized code in
  75270. ** sqlite3VdbeRecordCompare() returns results with these two primitives.
  75271. **
  75272. ** Return true if the result of comparison is equivalent to desiredResult.
  75273. ** Return false if there is a disagreement.
  75274. */
  75275. static int vdbeRecordCompareDebug(
  75276. int nKey1, const void *pKey1, /* Left key */
  75277. const UnpackedRecord *pPKey2, /* Right key */
  75278. int desiredResult /* Correct answer */
  75279. ){
  75280. u32 d1; /* Offset into aKey[] of next data element */
  75281. u32 idx1; /* Offset into aKey[] of next header element */
  75282. u32 szHdr1; /* Number of bytes in header */
  75283. int i = 0;
  75284. int rc = 0;
  75285. const unsigned char *aKey1 = (const unsigned char *)pKey1;
  75286. KeyInfo *pKeyInfo;
  75287. Mem mem1;
  75288. pKeyInfo = pPKey2->pKeyInfo;
  75289. if( pKeyInfo->db==0 ) return 1;
  75290. mem1.enc = pKeyInfo->enc;
  75291. mem1.db = pKeyInfo->db;
  75292. /* mem1.flags = 0; // Will be initialized by sqlite3VdbeSerialGet() */
  75293. VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
  75294. /* Compilers may complain that mem1.u.i is potentially uninitialized.
  75295. ** We could initialize it, as shown here, to silence those complaints.
  75296. ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
  75297. ** the unnecessary initialization has a measurable negative performance
  75298. ** impact, since this routine is a very high runner. And so, we choose
  75299. ** to ignore the compiler warnings and leave this variable uninitialized.
  75300. */
  75301. /* mem1.u.i = 0; // not needed, here to silence compiler warning */
  75302. idx1 = getVarint32(aKey1, szHdr1);
  75303. if( szHdr1>98307 ) return SQLITE_CORRUPT;
  75304. d1 = szHdr1;
  75305. assert( pKeyInfo->nAllField>=pPKey2->nField || CORRUPT_DB );
  75306. assert( pKeyInfo->aSortOrder!=0 );
  75307. assert( pKeyInfo->nKeyField>0 );
  75308. assert( idx1<=szHdr1 || CORRUPT_DB );
  75309. do{
  75310. u32 serial_type1;
  75311. /* Read the serial types for the next element in each key. */
  75312. idx1 += getVarint32( aKey1+idx1, serial_type1 );
  75313. /* Verify that there is enough key space remaining to avoid
  75314. ** a buffer overread. The "d1+serial_type1+2" subexpression will
  75315. ** always be greater than or equal to the amount of required key space.
  75316. ** Use that approximation to avoid the more expensive call to
  75317. ** sqlite3VdbeSerialTypeLen() in the common case.
  75318. */
  75319. if( d1+(u64)serial_type1+2>(u64)nKey1
  75320. && d1+(u64)sqlite3VdbeSerialTypeLen(serial_type1)>(u64)nKey1
  75321. ){
  75322. break;
  75323. }
  75324. /* Extract the values to be compared.
  75325. */
  75326. d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
  75327. /* Do the comparison
  75328. */
  75329. rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
  75330. pKeyInfo->nAllField>i ? pKeyInfo->aColl[i] : 0);
  75331. if( rc!=0 ){
  75332. assert( mem1.szMalloc==0 ); /* See comment below */
  75333. if( pKeyInfo->aSortOrder[i] ){
  75334. rc = -rc; /* Invert the result for DESC sort order. */
  75335. }
  75336. goto debugCompareEnd;
  75337. }
  75338. i++;
  75339. }while( idx1<szHdr1 && i<pPKey2->nField );
  75340. /* No memory allocation is ever used on mem1. Prove this using
  75341. ** the following assert(). If the assert() fails, it indicates a
  75342. ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
  75343. */
  75344. assert( mem1.szMalloc==0 );
  75345. /* rc==0 here means that one of the keys ran out of fields and
  75346. ** all the fields up to that point were equal. Return the default_rc
  75347. ** value. */
  75348. rc = pPKey2->default_rc;
  75349. debugCompareEnd:
  75350. if( desiredResult==0 && rc==0 ) return 1;
  75351. if( desiredResult<0 && rc<0 ) return 1;
  75352. if( desiredResult>0 && rc>0 ) return 1;
  75353. if( CORRUPT_DB ) return 1;
  75354. if( pKeyInfo->db->mallocFailed ) return 1;
  75355. return 0;
  75356. }
  75357. #endif
  75358. #ifdef SQLITE_DEBUG
  75359. /*
  75360. ** Count the number of fields (a.k.a. columns) in the record given by
  75361. ** pKey,nKey. The verify that this count is less than or equal to the
  75362. ** limit given by pKeyInfo->nAllField.
  75363. **
  75364. ** If this constraint is not satisfied, it means that the high-speed
  75365. ** vdbeRecordCompareInt() and vdbeRecordCompareString() routines will
  75366. ** not work correctly. If this assert() ever fires, it probably means
  75367. ** that the KeyInfo.nKeyField or KeyInfo.nAllField values were computed
  75368. ** incorrectly.
  75369. */
  75370. static void vdbeAssertFieldCountWithinLimits(
  75371. int nKey, const void *pKey, /* The record to verify */
  75372. const KeyInfo *pKeyInfo /* Compare size with this KeyInfo */
  75373. ){
  75374. int nField = 0;
  75375. u32 szHdr;
  75376. u32 idx;
  75377. u32 notUsed;
  75378. const unsigned char *aKey = (const unsigned char*)pKey;
  75379. if( CORRUPT_DB ) return;
  75380. idx = getVarint32(aKey, szHdr);
  75381. assert( nKey>=0 );
  75382. assert( szHdr<=(u32)nKey );
  75383. while( idx<szHdr ){
  75384. idx += getVarint32(aKey+idx, notUsed);
  75385. nField++;
  75386. }
  75387. assert( nField <= pKeyInfo->nAllField );
  75388. }
  75389. #else
  75390. # define vdbeAssertFieldCountWithinLimits(A,B,C)
  75391. #endif
  75392. /*
  75393. ** Both *pMem1 and *pMem2 contain string values. Compare the two values
  75394. ** using the collation sequence pColl. As usual, return a negative , zero
  75395. ** or positive value if *pMem1 is less than, equal to or greater than
  75396. ** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);".
  75397. */
  75398. static int vdbeCompareMemString(
  75399. const Mem *pMem1,
  75400. const Mem *pMem2,
  75401. const CollSeq *pColl,
  75402. u8 *prcErr /* If an OOM occurs, set to SQLITE_NOMEM */
  75403. ){
  75404. if( pMem1->enc==pColl->enc ){
  75405. /* The strings are already in the correct encoding. Call the
  75406. ** comparison function directly */
  75407. return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
  75408. }else{
  75409. int rc;
  75410. const void *v1, *v2;
  75411. Mem c1;
  75412. Mem c2;
  75413. sqlite3VdbeMemInit(&c1, pMem1->db, MEM_Null);
  75414. sqlite3VdbeMemInit(&c2, pMem1->db, MEM_Null);
  75415. sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
  75416. sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
  75417. v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
  75418. v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
  75419. if( (v1==0 || v2==0) ){
  75420. if( prcErr ) *prcErr = SQLITE_NOMEM_BKPT;
  75421. rc = 0;
  75422. }else{
  75423. rc = pColl->xCmp(pColl->pUser, c1.n, v1, c2.n, v2);
  75424. }
  75425. sqlite3VdbeMemRelease(&c1);
  75426. sqlite3VdbeMemRelease(&c2);
  75427. return rc;
  75428. }
  75429. }
  75430. /*
  75431. ** The input pBlob is guaranteed to be a Blob that is not marked
  75432. ** with MEM_Zero. Return true if it could be a zero-blob.
  75433. */
  75434. static int isAllZero(const char *z, int n){
  75435. int i;
  75436. for(i=0; i<n; i++){
  75437. if( z[i] ) return 0;
  75438. }
  75439. return 1;
  75440. }
  75441. /*
  75442. ** Compare two blobs. Return negative, zero, or positive if the first
  75443. ** is less than, equal to, or greater than the second, respectively.
  75444. ** If one blob is a prefix of the other, then the shorter is the lessor.
  75445. */
  75446. SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3BlobCompare(const Mem *pB1, const Mem *pB2){
  75447. int c;
  75448. int n1 = pB1->n;
  75449. int n2 = pB2->n;
  75450. /* It is possible to have a Blob value that has some non-zero content
  75451. ** followed by zero content. But that only comes up for Blobs formed
  75452. ** by the OP_MakeRecord opcode, and such Blobs never get passed into
  75453. ** sqlite3MemCompare(). */
  75454. assert( (pB1->flags & MEM_Zero)==0 || n1==0 );
  75455. assert( (pB2->flags & MEM_Zero)==0 || n2==0 );
  75456. if( (pB1->flags|pB2->flags) & MEM_Zero ){
  75457. if( pB1->flags & pB2->flags & MEM_Zero ){
  75458. return pB1->u.nZero - pB2->u.nZero;
  75459. }else if( pB1->flags & MEM_Zero ){
  75460. if( !isAllZero(pB2->z, pB2->n) ) return -1;
  75461. return pB1->u.nZero - n2;
  75462. }else{
  75463. if( !isAllZero(pB1->z, pB1->n) ) return +1;
  75464. return n1 - pB2->u.nZero;
  75465. }
  75466. }
  75467. c = memcmp(pB1->z, pB2->z, n1>n2 ? n2 : n1);
  75468. if( c ) return c;
  75469. return n1 - n2;
  75470. }
  75471. /*
  75472. ** Do a comparison between a 64-bit signed integer and a 64-bit floating-point
  75473. ** number. Return negative, zero, or positive if the first (i64) is less than,
  75474. ** equal to, or greater than the second (double).
  75475. */
  75476. static int sqlite3IntFloatCompare(i64 i, double r){
  75477. if( sizeof(LONGDOUBLE_TYPE)>8 ){
  75478. LONGDOUBLE_TYPE x = (LONGDOUBLE_TYPE)i;
  75479. if( x<r ) return -1;
  75480. if( x>r ) return +1;
  75481. return 0;
  75482. }else{
  75483. i64 y;
  75484. double s;
  75485. if( r<-9223372036854775808.0 ) return +1;
  75486. if( r>=9223372036854775808.0 ) return -1;
  75487. y = (i64)r;
  75488. if( i<y ) return -1;
  75489. if( i>y ) return +1;
  75490. s = (double)i;
  75491. if( s<r ) return -1;
  75492. if( s>r ) return +1;
  75493. return 0;
  75494. }
  75495. }
  75496. /*
  75497. ** Compare the values contained by the two memory cells, returning
  75498. ** negative, zero or positive if pMem1 is less than, equal to, or greater
  75499. ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
  75500. ** and reals) sorted numerically, followed by text ordered by the collating
  75501. ** sequence pColl and finally blob's ordered by memcmp().
  75502. **
  75503. ** Two NULL values are considered equal by this function.
  75504. */
  75505. SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
  75506. int f1, f2;
  75507. int combined_flags;
  75508. f1 = pMem1->flags;
  75509. f2 = pMem2->flags;
  75510. combined_flags = f1|f2;
  75511. assert( !sqlite3VdbeMemIsRowSet(pMem1) && !sqlite3VdbeMemIsRowSet(pMem2) );
  75512. /* If one value is NULL, it is less than the other. If both values
  75513. ** are NULL, return 0.
  75514. */
  75515. if( combined_flags&MEM_Null ){
  75516. return (f2&MEM_Null) - (f1&MEM_Null);
  75517. }
  75518. /* At least one of the two values is a number
  75519. */
  75520. if( combined_flags&(MEM_Int|MEM_Real|MEM_IntReal) ){
  75521. testcase( combined_flags & MEM_Int );
  75522. testcase( combined_flags & MEM_Real );
  75523. testcase( combined_flags & MEM_IntReal );
  75524. if( (f1 & f2 & (MEM_Int|MEM_IntReal))!=0 ){
  75525. testcase( f1 & f2 & MEM_Int );
  75526. testcase( f1 & f2 & MEM_IntReal );
  75527. if( pMem1->u.i < pMem2->u.i ) return -1;
  75528. if( pMem1->u.i > pMem2->u.i ) return +1;
  75529. return 0;
  75530. }
  75531. if( (f1 & f2 & MEM_Real)!=0 ){
  75532. if( pMem1->u.r < pMem2->u.r ) return -1;
  75533. if( pMem1->u.r > pMem2->u.r ) return +1;
  75534. return 0;
  75535. }
  75536. if( (f1&(MEM_Int|MEM_IntReal))!=0 ){
  75537. testcase( f1 & MEM_Int );
  75538. testcase( f1 & MEM_IntReal );
  75539. if( (f2&MEM_Real)!=0 ){
  75540. return sqlite3IntFloatCompare(pMem1->u.i, pMem2->u.r);
  75541. }else if( (f2&(MEM_Int|MEM_IntReal))!=0 ){
  75542. if( pMem1->u.i < pMem2->u.i ) return -1;
  75543. if( pMem1->u.i > pMem2->u.i ) return +1;
  75544. return 0;
  75545. }else{
  75546. return -1;
  75547. }
  75548. }
  75549. if( (f1&MEM_Real)!=0 ){
  75550. if( (f2&(MEM_Int|MEM_IntReal))!=0 ){
  75551. testcase( f2 & MEM_Int );
  75552. testcase( f2 & MEM_IntReal );
  75553. return -sqlite3IntFloatCompare(pMem2->u.i, pMem1->u.r);
  75554. }else{
  75555. return -1;
  75556. }
  75557. }
  75558. return +1;
  75559. }
  75560. /* If one value is a string and the other is a blob, the string is less.
  75561. ** If both are strings, compare using the collating functions.
  75562. */
  75563. if( combined_flags&MEM_Str ){
  75564. if( (f1 & MEM_Str)==0 ){
  75565. return 1;
  75566. }
  75567. if( (f2 & MEM_Str)==0 ){
  75568. return -1;
  75569. }
  75570. assert( pMem1->enc==pMem2->enc || pMem1->db->mallocFailed );
  75571. assert( pMem1->enc==SQLITE_UTF8 ||
  75572. pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
  75573. /* The collation sequence must be defined at this point, even if
  75574. ** the user deletes the collation sequence after the vdbe program is
  75575. ** compiled (this was not always the case).
  75576. */
  75577. assert( !pColl || pColl->xCmp );
  75578. if( pColl ){
  75579. return vdbeCompareMemString(pMem1, pMem2, pColl, 0);
  75580. }
  75581. /* If a NULL pointer was passed as the collate function, fall through
  75582. ** to the blob case and use memcmp(). */
  75583. }
  75584. /* Both values must be blobs. Compare using memcmp(). */
  75585. return sqlite3BlobCompare(pMem1, pMem2);
  75586. }
  75587. /*
  75588. ** The first argument passed to this function is a serial-type that
  75589. ** corresponds to an integer - all values between 1 and 9 inclusive
  75590. ** except 7. The second points to a buffer containing an integer value
  75591. ** serialized according to serial_type. This function deserializes
  75592. ** and returns the value.
  75593. */
  75594. static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){
  75595. u32 y;
  75596. assert( CORRUPT_DB || (serial_type>=1 && serial_type<=9 && serial_type!=7) );
  75597. switch( serial_type ){
  75598. case 0:
  75599. case 1:
  75600. testcase( aKey[0]&0x80 );
  75601. return ONE_BYTE_INT(aKey);
  75602. case 2:
  75603. testcase( aKey[0]&0x80 );
  75604. return TWO_BYTE_INT(aKey);
  75605. case 3:
  75606. testcase( aKey[0]&0x80 );
  75607. return THREE_BYTE_INT(aKey);
  75608. case 4: {
  75609. testcase( aKey[0]&0x80 );
  75610. y = FOUR_BYTE_UINT(aKey);
  75611. return (i64)*(int*)&y;
  75612. }
  75613. case 5: {
  75614. testcase( aKey[0]&0x80 );
  75615. return FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
  75616. }
  75617. case 6: {
  75618. u64 x = FOUR_BYTE_UINT(aKey);
  75619. testcase( aKey[0]&0x80 );
  75620. x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
  75621. return (i64)*(i64*)&x;
  75622. }
  75623. }
  75624. return (serial_type - 8);
  75625. }
  75626. /*
  75627. ** This function compares the two table rows or index records
  75628. ** specified by {nKey1, pKey1} and pPKey2. It returns a negative, zero
  75629. ** or positive integer if key1 is less than, equal to or
  75630. ** greater than key2. The {nKey1, pKey1} key must be a blob
  75631. ** created by the OP_MakeRecord opcode of the VDBE. The pPKey2
  75632. ** key must be a parsed key such as obtained from
  75633. ** sqlite3VdbeParseRecord.
  75634. **
  75635. ** If argument bSkip is non-zero, it is assumed that the caller has already
  75636. ** determined that the first fields of the keys are equal.
  75637. **
  75638. ** Key1 and Key2 do not have to contain the same number of fields. If all
  75639. ** fields that appear in both keys are equal, then pPKey2->default_rc is
  75640. ** returned.
  75641. **
  75642. ** If database corruption is discovered, set pPKey2->errCode to
  75643. ** SQLITE_CORRUPT and return 0. If an OOM error is encountered,
  75644. ** pPKey2->errCode is set to SQLITE_NOMEM and, if it is not NULL, the
  75645. ** malloc-failed flag set on database handle (pPKey2->pKeyInfo->db).
  75646. */
  75647. SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(
  75648. int nKey1, const void *pKey1, /* Left key */
  75649. UnpackedRecord *pPKey2, /* Right key */
  75650. int bSkip /* If true, skip the first field */
  75651. ){
  75652. u32 d1; /* Offset into aKey[] of next data element */
  75653. int i; /* Index of next field to compare */
  75654. u32 szHdr1; /* Size of record header in bytes */
  75655. u32 idx1; /* Offset of first type in header */
  75656. int rc = 0; /* Return value */
  75657. Mem *pRhs = pPKey2->aMem; /* Next field of pPKey2 to compare */
  75658. KeyInfo *pKeyInfo;
  75659. const unsigned char *aKey1 = (const unsigned char *)pKey1;
  75660. Mem mem1;
  75661. /* If bSkip is true, then the caller has already determined that the first
  75662. ** two elements in the keys are equal. Fix the various stack variables so
  75663. ** that this routine begins comparing at the second field. */
  75664. if( bSkip ){
  75665. u32 s1;
  75666. idx1 = 1 + getVarint32(&aKey1[1], s1);
  75667. szHdr1 = aKey1[0];
  75668. d1 = szHdr1 + sqlite3VdbeSerialTypeLen(s1);
  75669. i = 1;
  75670. pRhs++;
  75671. }else{
  75672. idx1 = getVarint32(aKey1, szHdr1);
  75673. d1 = szHdr1;
  75674. i = 0;
  75675. }
  75676. if( d1>(unsigned)nKey1 ){
  75677. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  75678. return 0; /* Corruption */
  75679. }
  75680. VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
  75681. assert( pPKey2->pKeyInfo->nAllField>=pPKey2->nField
  75682. || CORRUPT_DB );
  75683. assert( pPKey2->pKeyInfo->aSortOrder!=0 );
  75684. assert( pPKey2->pKeyInfo->nKeyField>0 );
  75685. assert( idx1<=szHdr1 || CORRUPT_DB );
  75686. do{
  75687. u32 serial_type;
  75688. /* RHS is an integer */
  75689. if( pRhs->flags & (MEM_Int|MEM_IntReal) ){
  75690. testcase( pRhs->flags & MEM_Int );
  75691. testcase( pRhs->flags & MEM_IntReal );
  75692. serial_type = aKey1[idx1];
  75693. testcase( serial_type==12 );
  75694. if( serial_type>=10 ){
  75695. rc = +1;
  75696. }else if( serial_type==0 ){
  75697. rc = -1;
  75698. }else if( serial_type==7 ){
  75699. sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
  75700. rc = -sqlite3IntFloatCompare(pRhs->u.i, mem1.u.r);
  75701. }else{
  75702. i64 lhs = vdbeRecordDecodeInt(serial_type, &aKey1[d1]);
  75703. i64 rhs = pRhs->u.i;
  75704. if( lhs<rhs ){
  75705. rc = -1;
  75706. }else if( lhs>rhs ){
  75707. rc = +1;
  75708. }
  75709. }
  75710. }
  75711. /* RHS is real */
  75712. else if( pRhs->flags & MEM_Real ){
  75713. serial_type = aKey1[idx1];
  75714. if( serial_type>=10 ){
  75715. /* Serial types 12 or greater are strings and blobs (greater than
  75716. ** numbers). Types 10 and 11 are currently "reserved for future
  75717. ** use", so it doesn't really matter what the results of comparing
  75718. ** them to numberic values are. */
  75719. rc = +1;
  75720. }else if( serial_type==0 ){
  75721. rc = -1;
  75722. }else{
  75723. sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
  75724. if( serial_type==7 ){
  75725. if( mem1.u.r<pRhs->u.r ){
  75726. rc = -1;
  75727. }else if( mem1.u.r>pRhs->u.r ){
  75728. rc = +1;
  75729. }
  75730. }else{
  75731. rc = sqlite3IntFloatCompare(mem1.u.i, pRhs->u.r);
  75732. }
  75733. }
  75734. }
  75735. /* RHS is a string */
  75736. else if( pRhs->flags & MEM_Str ){
  75737. getVarint32(&aKey1[idx1], serial_type);
  75738. testcase( serial_type==12 );
  75739. if( serial_type<12 ){
  75740. rc = -1;
  75741. }else if( !(serial_type & 0x01) ){
  75742. rc = +1;
  75743. }else{
  75744. mem1.n = (serial_type - 12) / 2;
  75745. testcase( (d1+mem1.n)==(unsigned)nKey1 );
  75746. testcase( (d1+mem1.n+1)==(unsigned)nKey1 );
  75747. if( (d1+mem1.n) > (unsigned)nKey1
  75748. || (pKeyInfo = pPKey2->pKeyInfo)->nAllField<=i
  75749. ){
  75750. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  75751. return 0; /* Corruption */
  75752. }else if( pKeyInfo->aColl[i] ){
  75753. mem1.enc = pKeyInfo->enc;
  75754. mem1.db = pKeyInfo->db;
  75755. mem1.flags = MEM_Str;
  75756. mem1.z = (char*)&aKey1[d1];
  75757. rc = vdbeCompareMemString(
  75758. &mem1, pRhs, pKeyInfo->aColl[i], &pPKey2->errCode
  75759. );
  75760. }else{
  75761. int nCmp = MIN(mem1.n, pRhs->n);
  75762. rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
  75763. if( rc==0 ) rc = mem1.n - pRhs->n;
  75764. }
  75765. }
  75766. }
  75767. /* RHS is a blob */
  75768. else if( pRhs->flags & MEM_Blob ){
  75769. assert( (pRhs->flags & MEM_Zero)==0 || pRhs->n==0 );
  75770. getVarint32(&aKey1[idx1], serial_type);
  75771. testcase( serial_type==12 );
  75772. if( serial_type<12 || (serial_type & 0x01) ){
  75773. rc = -1;
  75774. }else{
  75775. int nStr = (serial_type - 12) / 2;
  75776. testcase( (d1+nStr)==(unsigned)nKey1 );
  75777. testcase( (d1+nStr+1)==(unsigned)nKey1 );
  75778. if( (d1+nStr) > (unsigned)nKey1 ){
  75779. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  75780. return 0; /* Corruption */
  75781. }else if( pRhs->flags & MEM_Zero ){
  75782. if( !isAllZero((const char*)&aKey1[d1],nStr) ){
  75783. rc = 1;
  75784. }else{
  75785. rc = nStr - pRhs->u.nZero;
  75786. }
  75787. }else{
  75788. int nCmp = MIN(nStr, pRhs->n);
  75789. rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
  75790. if( rc==0 ) rc = nStr - pRhs->n;
  75791. }
  75792. }
  75793. }
  75794. /* RHS is null */
  75795. else{
  75796. serial_type = aKey1[idx1];
  75797. rc = (serial_type!=0);
  75798. }
  75799. if( rc!=0 ){
  75800. if( pPKey2->pKeyInfo->aSortOrder[i] ){
  75801. rc = -rc;
  75802. }
  75803. assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, rc) );
  75804. assert( mem1.szMalloc==0 ); /* See comment below */
  75805. return rc;
  75806. }
  75807. i++;
  75808. if( i==pPKey2->nField ) break;
  75809. pRhs++;
  75810. d1 += sqlite3VdbeSerialTypeLen(serial_type);
  75811. idx1 += sqlite3VarintLen(serial_type);
  75812. }while( idx1<(unsigned)szHdr1 && d1<=(unsigned)nKey1 );
  75813. /* No memory allocation is ever used on mem1. Prove this using
  75814. ** the following assert(). If the assert() fails, it indicates a
  75815. ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1). */
  75816. assert( mem1.szMalloc==0 );
  75817. /* rc==0 here means that one or both of the keys ran out of fields and
  75818. ** all the fields up to that point were equal. Return the default_rc
  75819. ** value. */
  75820. assert( CORRUPT_DB
  75821. || vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, pPKey2->default_rc)
  75822. || pPKey2->pKeyInfo->db->mallocFailed
  75823. );
  75824. pPKey2->eqSeen = 1;
  75825. return pPKey2->default_rc;
  75826. }
  75827. SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
  75828. int nKey1, const void *pKey1, /* Left key */
  75829. UnpackedRecord *pPKey2 /* Right key */
  75830. ){
  75831. return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 0);
  75832. }
  75833. /*
  75834. ** This function is an optimized version of sqlite3VdbeRecordCompare()
  75835. ** that (a) the first field of pPKey2 is an integer, and (b) the
  75836. ** size-of-header varint at the start of (pKey1/nKey1) fits in a single
  75837. ** byte (i.e. is less than 128).
  75838. **
  75839. ** To avoid concerns about buffer overreads, this routine is only used
  75840. ** on schemas where the maximum valid header size is 63 bytes or less.
  75841. */
  75842. static int vdbeRecordCompareInt(
  75843. int nKey1, const void *pKey1, /* Left key */
  75844. UnpackedRecord *pPKey2 /* Right key */
  75845. ){
  75846. const u8 *aKey = &((const u8*)pKey1)[*(const u8*)pKey1 & 0x3F];
  75847. int serial_type = ((const u8*)pKey1)[1];
  75848. int res;
  75849. u32 y;
  75850. u64 x;
  75851. i64 v;
  75852. i64 lhs;
  75853. vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
  75854. assert( (*(u8*)pKey1)<=0x3F || CORRUPT_DB );
  75855. switch( serial_type ){
  75856. case 1: { /* 1-byte signed integer */
  75857. lhs = ONE_BYTE_INT(aKey);
  75858. testcase( lhs<0 );
  75859. break;
  75860. }
  75861. case 2: { /* 2-byte signed integer */
  75862. lhs = TWO_BYTE_INT(aKey);
  75863. testcase( lhs<0 );
  75864. break;
  75865. }
  75866. case 3: { /* 3-byte signed integer */
  75867. lhs = THREE_BYTE_INT(aKey);
  75868. testcase( lhs<0 );
  75869. break;
  75870. }
  75871. case 4: { /* 4-byte signed integer */
  75872. y = FOUR_BYTE_UINT(aKey);
  75873. lhs = (i64)*(int*)&y;
  75874. testcase( lhs<0 );
  75875. break;
  75876. }
  75877. case 5: { /* 6-byte signed integer */
  75878. lhs = FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
  75879. testcase( lhs<0 );
  75880. break;
  75881. }
  75882. case 6: { /* 8-byte signed integer */
  75883. x = FOUR_BYTE_UINT(aKey);
  75884. x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
  75885. lhs = *(i64*)&x;
  75886. testcase( lhs<0 );
  75887. break;
  75888. }
  75889. case 8:
  75890. lhs = 0;
  75891. break;
  75892. case 9:
  75893. lhs = 1;
  75894. break;
  75895. /* This case could be removed without changing the results of running
  75896. ** this code. Including it causes gcc to generate a faster switch
  75897. ** statement (since the range of switch targets now starts at zero and
  75898. ** is contiguous) but does not cause any duplicate code to be generated
  75899. ** (as gcc is clever enough to combine the two like cases). Other
  75900. ** compilers might be similar. */
  75901. case 0: case 7:
  75902. return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
  75903. default:
  75904. return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
  75905. }
  75906. v = pPKey2->aMem[0].u.i;
  75907. if( v>lhs ){
  75908. res = pPKey2->r1;
  75909. }else if( v<lhs ){
  75910. res = pPKey2->r2;
  75911. }else if( pPKey2->nField>1 ){
  75912. /* The first fields of the two keys are equal. Compare the trailing
  75913. ** fields. */
  75914. res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
  75915. }else{
  75916. /* The first fields of the two keys are equal and there are no trailing
  75917. ** fields. Return pPKey2->default_rc in this case. */
  75918. res = pPKey2->default_rc;
  75919. pPKey2->eqSeen = 1;
  75920. }
  75921. assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res) );
  75922. return res;
  75923. }
  75924. /*
  75925. ** This function is an optimized version of sqlite3VdbeRecordCompare()
  75926. ** that (a) the first field of pPKey2 is a string, that (b) the first field
  75927. ** uses the collation sequence BINARY and (c) that the size-of-header varint
  75928. ** at the start of (pKey1/nKey1) fits in a single byte.
  75929. */
  75930. static int vdbeRecordCompareString(
  75931. int nKey1, const void *pKey1, /* Left key */
  75932. UnpackedRecord *pPKey2 /* Right key */
  75933. ){
  75934. const u8 *aKey1 = (const u8*)pKey1;
  75935. int serial_type;
  75936. int res;
  75937. assert( pPKey2->aMem[0].flags & MEM_Str );
  75938. vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
  75939. getVarint32(&aKey1[1], serial_type);
  75940. if( serial_type<12 ){
  75941. res = pPKey2->r1; /* (pKey1/nKey1) is a number or a null */
  75942. }else if( !(serial_type & 0x01) ){
  75943. res = pPKey2->r2; /* (pKey1/nKey1) is a blob */
  75944. }else{
  75945. int nCmp;
  75946. int nStr;
  75947. int szHdr = aKey1[0];
  75948. nStr = (serial_type-12) / 2;
  75949. if( (szHdr + nStr) > nKey1 ){
  75950. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  75951. return 0; /* Corruption */
  75952. }
  75953. nCmp = MIN( pPKey2->aMem[0].n, nStr );
  75954. res = memcmp(&aKey1[szHdr], pPKey2->aMem[0].z, nCmp);
  75955. if( res==0 ){
  75956. res = nStr - pPKey2->aMem[0].n;
  75957. if( res==0 ){
  75958. if( pPKey2->nField>1 ){
  75959. res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
  75960. }else{
  75961. res = pPKey2->default_rc;
  75962. pPKey2->eqSeen = 1;
  75963. }
  75964. }else if( res>0 ){
  75965. res = pPKey2->r2;
  75966. }else{
  75967. res = pPKey2->r1;
  75968. }
  75969. }else if( res>0 ){
  75970. res = pPKey2->r2;
  75971. }else{
  75972. res = pPKey2->r1;
  75973. }
  75974. }
  75975. assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res)
  75976. || CORRUPT_DB
  75977. || pPKey2->pKeyInfo->db->mallocFailed
  75978. );
  75979. return res;
  75980. }
  75981. /*
  75982. ** Return a pointer to an sqlite3VdbeRecordCompare() compatible function
  75983. ** suitable for comparing serialized records to the unpacked record passed
  75984. ** as the only argument.
  75985. */
  75986. SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){
  75987. /* varintRecordCompareInt() and varintRecordCompareString() both assume
  75988. ** that the size-of-header varint that occurs at the start of each record
  75989. ** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt()
  75990. ** also assumes that it is safe to overread a buffer by at least the
  75991. ** maximum possible legal header size plus 8 bytes. Because there is
  75992. ** guaranteed to be at least 74 (but not 136) bytes of padding following each
  75993. ** buffer passed to varintRecordCompareInt() this makes it convenient to
  75994. ** limit the size of the header to 64 bytes in cases where the first field
  75995. ** is an integer.
  75996. **
  75997. ** The easiest way to enforce this limit is to consider only records with
  75998. ** 13 fields or less. If the first field is an integer, the maximum legal
  75999. ** header size is (12*5 + 1 + 1) bytes. */
  76000. if( p->pKeyInfo->nAllField<=13 ){
  76001. int flags = p->aMem[0].flags;
  76002. if( p->pKeyInfo->aSortOrder[0] ){
  76003. p->r1 = 1;
  76004. p->r2 = -1;
  76005. }else{
  76006. p->r1 = -1;
  76007. p->r2 = 1;
  76008. }
  76009. if( (flags & MEM_Int) ){
  76010. return vdbeRecordCompareInt;
  76011. }
  76012. testcase( flags & MEM_Real );
  76013. testcase( flags & MEM_Null );
  76014. testcase( flags & MEM_Blob );
  76015. if( (flags & (MEM_Real|MEM_IntReal|MEM_Null|MEM_Blob))==0
  76016. && p->pKeyInfo->aColl[0]==0
  76017. ){
  76018. assert( flags & MEM_Str );
  76019. return vdbeRecordCompareString;
  76020. }
  76021. }
  76022. return sqlite3VdbeRecordCompare;
  76023. }
  76024. /*
  76025. ** pCur points at an index entry created using the OP_MakeRecord opcode.
  76026. ** Read the rowid (the last field in the record) and store it in *rowid.
  76027. ** Return SQLITE_OK if everything works, or an error code otherwise.
  76028. **
  76029. ** pCur might be pointing to text obtained from a corrupt database file.
  76030. ** So the content cannot be trusted. Do appropriate checks on the content.
  76031. */
  76032. SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
  76033. i64 nCellKey = 0;
  76034. int rc;
  76035. u32 szHdr; /* Size of the header */
  76036. u32 typeRowid; /* Serial type of the rowid */
  76037. u32 lenRowid; /* Size of the rowid */
  76038. Mem m, v;
  76039. /* Get the size of the index entry. Only indices entries of less
  76040. ** than 2GiB are support - anything large must be database corruption.
  76041. ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
  76042. ** this code can safely assume that nCellKey is 32-bits
  76043. */
  76044. assert( sqlite3BtreeCursorIsValid(pCur) );
  76045. nCellKey = sqlite3BtreePayloadSize(pCur);
  76046. assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
  76047. /* Read in the complete content of the index entry */
  76048. sqlite3VdbeMemInit(&m, db, 0);
  76049. rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, &m);
  76050. if( rc ){
  76051. return rc;
  76052. }
  76053. /* The index entry must begin with a header size */
  76054. (void)getVarint32((u8*)m.z, szHdr);
  76055. testcase( szHdr==3 );
  76056. testcase( szHdr==m.n );
  76057. testcase( szHdr>0x7fffffff );
  76058. assert( m.n>=0 );
  76059. if( unlikely(szHdr<3 || szHdr>(unsigned)m.n) ){
  76060. goto idx_rowid_corruption;
  76061. }
  76062. /* The last field of the index should be an integer - the ROWID.
  76063. ** Verify that the last entry really is an integer. */
  76064. (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
  76065. testcase( typeRowid==1 );
  76066. testcase( typeRowid==2 );
  76067. testcase( typeRowid==3 );
  76068. testcase( typeRowid==4 );
  76069. testcase( typeRowid==5 );
  76070. testcase( typeRowid==6 );
  76071. testcase( typeRowid==8 );
  76072. testcase( typeRowid==9 );
  76073. if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
  76074. goto idx_rowid_corruption;
  76075. }
  76076. lenRowid = sqlite3SmallTypeSizes[typeRowid];
  76077. testcase( (u32)m.n==szHdr+lenRowid );
  76078. if( unlikely((u32)m.n<szHdr+lenRowid) ){
  76079. goto idx_rowid_corruption;
  76080. }
  76081. /* Fetch the integer off the end of the index record */
  76082. sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
  76083. *rowid = v.u.i;
  76084. sqlite3VdbeMemRelease(&m);
  76085. return SQLITE_OK;
  76086. /* Jump here if database corruption is detected after m has been
  76087. ** allocated. Free the m object and return SQLITE_CORRUPT. */
  76088. idx_rowid_corruption:
  76089. testcase( m.szMalloc!=0 );
  76090. sqlite3VdbeMemRelease(&m);
  76091. return SQLITE_CORRUPT_BKPT;
  76092. }
  76093. /*
  76094. ** Compare the key of the index entry that cursor pC is pointing to against
  76095. ** the key string in pUnpacked. Write into *pRes a number
  76096. ** that is negative, zero, or positive if pC is less than, equal to,
  76097. ** or greater than pUnpacked. Return SQLITE_OK on success.
  76098. **
  76099. ** pUnpacked is either created without a rowid or is truncated so that it
  76100. ** omits the rowid at the end. The rowid at the end of the index entry
  76101. ** is ignored as well. Hence, this routine only compares the prefixes
  76102. ** of the keys prior to the final rowid, not the entire key.
  76103. */
  76104. SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
  76105. sqlite3 *db, /* Database connection */
  76106. VdbeCursor *pC, /* The cursor to compare against */
  76107. UnpackedRecord *pUnpacked, /* Unpacked version of key */
  76108. int *res /* Write the comparison result here */
  76109. ){
  76110. i64 nCellKey = 0;
  76111. int rc;
  76112. BtCursor *pCur;
  76113. Mem m;
  76114. assert( pC->eCurType==CURTYPE_BTREE );
  76115. pCur = pC->uc.pCursor;
  76116. assert( sqlite3BtreeCursorIsValid(pCur) );
  76117. nCellKey = sqlite3BtreePayloadSize(pCur);
  76118. /* nCellKey will always be between 0 and 0xffffffff because of the way
  76119. ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
  76120. if( nCellKey<=0 || nCellKey>0x7fffffff ){
  76121. *res = 0;
  76122. return SQLITE_CORRUPT_BKPT;
  76123. }
  76124. sqlite3VdbeMemInit(&m, db, 0);
  76125. rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, &m);
  76126. if( rc ){
  76127. return rc;
  76128. }
  76129. *res = sqlite3VdbeRecordCompareWithSkip(m.n, m.z, pUnpacked, 0);
  76130. sqlite3VdbeMemRelease(&m);
  76131. return SQLITE_OK;
  76132. }
  76133. /*
  76134. ** This routine sets the value to be returned by subsequent calls to
  76135. ** sqlite3_changes() on the database handle 'db'.
  76136. */
  76137. SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
  76138. assert( sqlite3_mutex_held(db->mutex) );
  76139. db->nChange = nChange;
  76140. db->nTotalChange += nChange;
  76141. }
  76142. /*
  76143. ** Set a flag in the vdbe to update the change counter when it is finalised
  76144. ** or reset.
  76145. */
  76146. SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
  76147. v->changeCntOn = 1;
  76148. }
  76149. /*
  76150. ** Mark every prepared statement associated with a database connection
  76151. ** as expired.
  76152. **
  76153. ** An expired statement means that recompilation of the statement is
  76154. ** recommend. Statements expire when things happen that make their
  76155. ** programs obsolete. Removing user-defined functions or collating
  76156. ** sequences, or changing an authorization function are the types of
  76157. ** things that make prepared statements obsolete.
  76158. **
  76159. ** If iCode is 1, then expiration is advisory. The statement should
  76160. ** be reprepared before being restarted, but if it is already running
  76161. ** it is allowed to run to completion.
  76162. **
  76163. ** Internally, this function just sets the Vdbe.expired flag on all
  76164. ** prepared statements. The flag is set to 1 for an immediate expiration
  76165. ** and set to 2 for an advisory expiration.
  76166. */
  76167. SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db, int iCode){
  76168. Vdbe *p;
  76169. for(p = db->pVdbe; p; p=p->pNext){
  76170. p->expired = iCode+1;
  76171. }
  76172. }
  76173. /*
  76174. ** Return the database associated with the Vdbe.
  76175. */
  76176. SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
  76177. return v->db;
  76178. }
  76179. /*
  76180. ** Return the SQLITE_PREPARE flags for a Vdbe.
  76181. */
  76182. SQLITE_PRIVATE u8 sqlite3VdbePrepareFlags(Vdbe *v){
  76183. return v->prepFlags;
  76184. }
  76185. /*
  76186. ** Return a pointer to an sqlite3_value structure containing the value bound
  76187. ** parameter iVar of VM v. Except, if the value is an SQL NULL, return
  76188. ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
  76189. ** constants) to the value before returning it.
  76190. **
  76191. ** The returned value must be freed by the caller using sqlite3ValueFree().
  76192. */
  76193. SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
  76194. assert( iVar>0 );
  76195. if( v ){
  76196. Mem *pMem = &v->aVar[iVar-1];
  76197. assert( (v->db->flags & SQLITE_EnableQPSG)==0 );
  76198. if( 0==(pMem->flags & MEM_Null) ){
  76199. sqlite3_value *pRet = sqlite3ValueNew(v->db);
  76200. if( pRet ){
  76201. sqlite3VdbeMemCopy((Mem *)pRet, pMem);
  76202. sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
  76203. }
  76204. return pRet;
  76205. }
  76206. }
  76207. return 0;
  76208. }
  76209. /*
  76210. ** Configure SQL variable iVar so that binding a new value to it signals
  76211. ** to sqlite3_reoptimize() that re-preparing the statement may result
  76212. ** in a better query plan.
  76213. */
  76214. SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
  76215. assert( iVar>0 );
  76216. assert( (v->db->flags & SQLITE_EnableQPSG)==0 );
  76217. if( iVar>=32 ){
  76218. v->expmask |= 0x80000000;
  76219. }else{
  76220. v->expmask |= ((u32)1 << (iVar-1));
  76221. }
  76222. }
  76223. /*
  76224. ** Cause a function to throw an error if it was call from OP_PureFunc
  76225. ** rather than OP_Function.
  76226. **
  76227. ** OP_PureFunc means that the function must be deterministic, and should
  76228. ** throw an error if it is given inputs that would make it non-deterministic.
  76229. ** This routine is invoked by date/time functions that use non-deterministic
  76230. ** features such as 'now'.
  76231. */
  76232. SQLITE_PRIVATE int sqlite3NotPureFunc(sqlite3_context *pCtx){
  76233. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  76234. if( pCtx->pVdbe==0 ) return 1;
  76235. #endif
  76236. if( pCtx->pVdbe->aOp[pCtx->iOp].opcode==OP_PureFunc ){
  76237. sqlite3_result_error(pCtx,
  76238. "non-deterministic function in index expression or CHECK constraint",
  76239. -1);
  76240. return 0;
  76241. }
  76242. return 1;
  76243. }
  76244. #ifndef SQLITE_OMIT_VIRTUALTABLE
  76245. /*
  76246. ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
  76247. ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
  76248. ** in memory obtained from sqlite3DbMalloc).
  76249. */
  76250. SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){
  76251. if( pVtab->zErrMsg ){
  76252. sqlite3 *db = p->db;
  76253. sqlite3DbFree(db, p->zErrMsg);
  76254. p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
  76255. sqlite3_free(pVtab->zErrMsg);
  76256. pVtab->zErrMsg = 0;
  76257. }
  76258. }
  76259. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  76260. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  76261. /*
  76262. ** If the second argument is not NULL, release any allocations associated
  76263. ** with the memory cells in the p->aMem[] array. Also free the UnpackedRecord
  76264. ** structure itself, using sqlite3DbFree().
  76265. **
  76266. ** This function is used to free UnpackedRecord structures allocated by
  76267. ** the vdbeUnpackRecord() function found in vdbeapi.c.
  76268. */
  76269. static void vdbeFreeUnpacked(sqlite3 *db, int nField, UnpackedRecord *p){
  76270. if( p ){
  76271. int i;
  76272. for(i=0; i<nField; i++){
  76273. Mem *pMem = &p->aMem[i];
  76274. if( pMem->zMalloc ) sqlite3VdbeMemRelease(pMem);
  76275. }
  76276. sqlite3DbFreeNN(db, p);
  76277. }
  76278. }
  76279. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  76280. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  76281. /*
  76282. ** Invoke the pre-update hook. If this is an UPDATE or DELETE pre-update call,
  76283. ** then cursor passed as the second argument should point to the row about
  76284. ** to be update or deleted. If the application calls sqlite3_preupdate_old(),
  76285. ** the required value will be read from the row the cursor points to.
  76286. */
  76287. SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(
  76288. Vdbe *v, /* Vdbe pre-update hook is invoked by */
  76289. VdbeCursor *pCsr, /* Cursor to grab old.* values from */
  76290. int op, /* SQLITE_INSERT, UPDATE or DELETE */
  76291. const char *zDb, /* Database name */
  76292. Table *pTab, /* Modified table */
  76293. i64 iKey1, /* Initial key value */
  76294. int iReg /* Register for new.* record */
  76295. ){
  76296. sqlite3 *db = v->db;
  76297. i64 iKey2;
  76298. PreUpdate preupdate;
  76299. const char *zTbl = pTab->zName;
  76300. static const u8 fakeSortOrder = 0;
  76301. assert( db->pPreUpdate==0 );
  76302. memset(&preupdate, 0, sizeof(PreUpdate));
  76303. if( HasRowid(pTab)==0 ){
  76304. iKey1 = iKey2 = 0;
  76305. preupdate.pPk = sqlite3PrimaryKeyIndex(pTab);
  76306. }else{
  76307. if( op==SQLITE_UPDATE ){
  76308. iKey2 = v->aMem[iReg].u.i;
  76309. }else{
  76310. iKey2 = iKey1;
  76311. }
  76312. }
  76313. assert( pCsr->nField==pTab->nCol
  76314. || (pCsr->nField==pTab->nCol+1 && op==SQLITE_DELETE && iReg==-1)
  76315. );
  76316. preupdate.v = v;
  76317. preupdate.pCsr = pCsr;
  76318. preupdate.op = op;
  76319. preupdate.iNewReg = iReg;
  76320. preupdate.keyinfo.db = db;
  76321. preupdate.keyinfo.enc = ENC(db);
  76322. preupdate.keyinfo.nKeyField = pTab->nCol;
  76323. preupdate.keyinfo.aSortOrder = (u8*)&fakeSortOrder;
  76324. preupdate.iKey1 = iKey1;
  76325. preupdate.iKey2 = iKey2;
  76326. preupdate.pTab = pTab;
  76327. db->pPreUpdate = &preupdate;
  76328. db->xPreUpdateCallback(db->pPreUpdateArg, db, op, zDb, zTbl, iKey1, iKey2);
  76329. db->pPreUpdate = 0;
  76330. sqlite3DbFree(db, preupdate.aRecord);
  76331. vdbeFreeUnpacked(db, preupdate.keyinfo.nKeyField+1, preupdate.pUnpacked);
  76332. vdbeFreeUnpacked(db, preupdate.keyinfo.nKeyField+1, preupdate.pNewUnpacked);
  76333. if( preupdate.aNew ){
  76334. int i;
  76335. for(i=0; i<pCsr->nField; i++){
  76336. sqlite3VdbeMemRelease(&preupdate.aNew[i]);
  76337. }
  76338. sqlite3DbFreeNN(db, preupdate.aNew);
  76339. }
  76340. }
  76341. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  76342. /************** End of vdbeaux.c *********************************************/
  76343. /************** Begin file vdbeapi.c *****************************************/
  76344. /*
  76345. ** 2004 May 26
  76346. **
  76347. ** The author disclaims copyright to this source code. In place of
  76348. ** a legal notice, here is a blessing:
  76349. **
  76350. ** May you do good and not evil.
  76351. ** May you find forgiveness for yourself and forgive others.
  76352. ** May you share freely, never taking more than you give.
  76353. **
  76354. *************************************************************************
  76355. **
  76356. ** This file contains code use to implement APIs that are part of the
  76357. ** VDBE.
  76358. */
  76359. /* #include "sqliteInt.h" */
  76360. /* #include "vdbeInt.h" */
  76361. #ifndef SQLITE_OMIT_DEPRECATED
  76362. /*
  76363. ** Return TRUE (non-zero) of the statement supplied as an argument needs
  76364. ** to be recompiled. A statement needs to be recompiled whenever the
  76365. ** execution environment changes in a way that would alter the program
  76366. ** that sqlite3_prepare() generates. For example, if new functions or
  76367. ** collating sequences are registered or if an authorizer function is
  76368. ** added or changed.
  76369. */
  76370. SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
  76371. Vdbe *p = (Vdbe*)pStmt;
  76372. return p==0 || p->expired;
  76373. }
  76374. #endif
  76375. /*
  76376. ** Check on a Vdbe to make sure it has not been finalized. Log
  76377. ** an error and return true if it has been finalized (or is otherwise
  76378. ** invalid). Return false if it is ok.
  76379. */
  76380. static int vdbeSafety(Vdbe *p){
  76381. if( p->db==0 ){
  76382. sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
  76383. return 1;
  76384. }else{
  76385. return 0;
  76386. }
  76387. }
  76388. static int vdbeSafetyNotNull(Vdbe *p){
  76389. if( p==0 ){
  76390. sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
  76391. return 1;
  76392. }else{
  76393. return vdbeSafety(p);
  76394. }
  76395. }
  76396. #ifndef SQLITE_OMIT_TRACE
  76397. /*
  76398. ** Invoke the profile callback. This routine is only called if we already
  76399. ** know that the profile callback is defined and needs to be invoked.
  76400. */
  76401. static SQLITE_NOINLINE void invokeProfileCallback(sqlite3 *db, Vdbe *p){
  76402. sqlite3_int64 iNow;
  76403. sqlite3_int64 iElapse;
  76404. assert( p->startTime>0 );
  76405. assert( (db->mTrace & (SQLITE_TRACE_PROFILE|SQLITE_TRACE_XPROFILE))!=0 );
  76406. assert( db->init.busy==0 );
  76407. assert( p->zSql!=0 );
  76408. sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
  76409. iElapse = (iNow - p->startTime)*1000000;
  76410. #ifndef SQLITE_OMIT_DEPRECATED
  76411. if( db->xProfile ){
  76412. db->xProfile(db->pProfileArg, p->zSql, iElapse);
  76413. }
  76414. #endif
  76415. if( db->mTrace & SQLITE_TRACE_PROFILE ){
  76416. db->xTrace(SQLITE_TRACE_PROFILE, db->pTraceArg, p, (void*)&iElapse);
  76417. }
  76418. p->startTime = 0;
  76419. }
  76420. /*
  76421. ** The checkProfileCallback(DB,P) macro checks to see if a profile callback
  76422. ** is needed, and it invokes the callback if it is needed.
  76423. */
  76424. # define checkProfileCallback(DB,P) \
  76425. if( ((P)->startTime)>0 ){ invokeProfileCallback(DB,P); }
  76426. #else
  76427. # define checkProfileCallback(DB,P) /*no-op*/
  76428. #endif
  76429. /*
  76430. ** The following routine destroys a virtual machine that is created by
  76431. ** the sqlite3_compile() routine. The integer returned is an SQLITE_
  76432. ** success/failure code that describes the result of executing the virtual
  76433. ** machine.
  76434. **
  76435. ** This routine sets the error code and string returned by
  76436. ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
  76437. */
  76438. SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
  76439. int rc;
  76440. if( pStmt==0 ){
  76441. /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
  76442. ** pointer is a harmless no-op. */
  76443. rc = SQLITE_OK;
  76444. }else{
  76445. Vdbe *v = (Vdbe*)pStmt;
  76446. sqlite3 *db = v->db;
  76447. if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
  76448. sqlite3_mutex_enter(db->mutex);
  76449. checkProfileCallback(db, v);
  76450. rc = sqlite3VdbeFinalize(v);
  76451. rc = sqlite3ApiExit(db, rc);
  76452. sqlite3LeaveMutexAndCloseZombie(db);
  76453. }
  76454. return rc;
  76455. }
  76456. /*
  76457. ** Terminate the current execution of an SQL statement and reset it
  76458. ** back to its starting state so that it can be reused. A success code from
  76459. ** the prior execution is returned.
  76460. **
  76461. ** This routine sets the error code and string returned by
  76462. ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
  76463. */
  76464. SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
  76465. int rc;
  76466. if( pStmt==0 ){
  76467. rc = SQLITE_OK;
  76468. }else{
  76469. Vdbe *v = (Vdbe*)pStmt;
  76470. sqlite3 *db = v->db;
  76471. sqlite3_mutex_enter(db->mutex);
  76472. checkProfileCallback(db, v);
  76473. rc = sqlite3VdbeReset(v);
  76474. sqlite3VdbeRewind(v);
  76475. assert( (rc & (db->errMask))==rc );
  76476. rc = sqlite3ApiExit(db, rc);
  76477. sqlite3_mutex_leave(db->mutex);
  76478. }
  76479. return rc;
  76480. }
  76481. /*
  76482. ** Set all the parameters in the compiled SQL statement to NULL.
  76483. */
  76484. SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
  76485. int i;
  76486. int rc = SQLITE_OK;
  76487. Vdbe *p = (Vdbe*)pStmt;
  76488. #if SQLITE_THREADSAFE
  76489. sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
  76490. #endif
  76491. sqlite3_mutex_enter(mutex);
  76492. for(i=0; i<p->nVar; i++){
  76493. sqlite3VdbeMemRelease(&p->aVar[i]);
  76494. p->aVar[i].flags = MEM_Null;
  76495. }
  76496. assert( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || p->expmask==0 );
  76497. if( p->expmask ){
  76498. p->expired = 1;
  76499. }
  76500. sqlite3_mutex_leave(mutex);
  76501. return rc;
  76502. }
  76503. /**************************** sqlite3_value_ *******************************
  76504. ** The following routines extract information from a Mem or sqlite3_value
  76505. ** structure.
  76506. */
  76507. SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
  76508. Mem *p = (Mem*)pVal;
  76509. if( p->flags & (MEM_Blob|MEM_Str) ){
  76510. if( ExpandBlob(p)!=SQLITE_OK ){
  76511. assert( p->flags==MEM_Null && p->z==0 );
  76512. return 0;
  76513. }
  76514. p->flags |= MEM_Blob;
  76515. return p->n ? p->z : 0;
  76516. }else{
  76517. return sqlite3_value_text(pVal);
  76518. }
  76519. }
  76520. SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
  76521. return sqlite3ValueBytes(pVal, SQLITE_UTF8);
  76522. }
  76523. SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
  76524. return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
  76525. }
  76526. SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
  76527. return sqlite3VdbeRealValue((Mem*)pVal);
  76528. }
  76529. SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
  76530. return (int)sqlite3VdbeIntValue((Mem*)pVal);
  76531. }
  76532. SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
  76533. return sqlite3VdbeIntValue((Mem*)pVal);
  76534. }
  76535. SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value *pVal){
  76536. Mem *pMem = (Mem*)pVal;
  76537. return ((pMem->flags & MEM_Subtype) ? pMem->eSubtype : 0);
  76538. }
  76539. SQLITE_API void *sqlite3_value_pointer(sqlite3_value *pVal, const char *zPType){
  76540. Mem *p = (Mem*)pVal;
  76541. if( (p->flags&(MEM_TypeMask|MEM_Term|MEM_Subtype)) ==
  76542. (MEM_Null|MEM_Term|MEM_Subtype)
  76543. && zPType!=0
  76544. && p->eSubtype=='p'
  76545. && strcmp(p->u.zPType, zPType)==0
  76546. ){
  76547. return (void*)p->z;
  76548. }else{
  76549. return 0;
  76550. }
  76551. }
  76552. SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
  76553. return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
  76554. }
  76555. #ifndef SQLITE_OMIT_UTF16
  76556. SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
  76557. return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
  76558. }
  76559. SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
  76560. return sqlite3ValueText(pVal, SQLITE_UTF16BE);
  76561. }
  76562. SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
  76563. return sqlite3ValueText(pVal, SQLITE_UTF16LE);
  76564. }
  76565. #endif /* SQLITE_OMIT_UTF16 */
  76566. /* EVIDENCE-OF: R-12793-43283 Every value in SQLite has one of five
  76567. ** fundamental datatypes: 64-bit signed integer 64-bit IEEE floating
  76568. ** point number string BLOB NULL
  76569. */
  76570. SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
  76571. static const u8 aType[] = {
  76572. SQLITE_BLOB, /* 0x00 (not possible) */
  76573. SQLITE_NULL, /* 0x01 NULL */
  76574. SQLITE_TEXT, /* 0x02 TEXT */
  76575. SQLITE_NULL, /* 0x03 (not possible) */
  76576. SQLITE_INTEGER, /* 0x04 INTEGER */
  76577. SQLITE_NULL, /* 0x05 (not possible) */
  76578. SQLITE_INTEGER, /* 0x06 INTEGER + TEXT */
  76579. SQLITE_NULL, /* 0x07 (not possible) */
  76580. SQLITE_FLOAT, /* 0x08 FLOAT */
  76581. SQLITE_NULL, /* 0x09 (not possible) */
  76582. SQLITE_FLOAT, /* 0x0a FLOAT + TEXT */
  76583. SQLITE_NULL, /* 0x0b (not possible) */
  76584. SQLITE_INTEGER, /* 0x0c (not possible) */
  76585. SQLITE_NULL, /* 0x0d (not possible) */
  76586. SQLITE_INTEGER, /* 0x0e (not possible) */
  76587. SQLITE_NULL, /* 0x0f (not possible) */
  76588. SQLITE_BLOB, /* 0x10 BLOB */
  76589. SQLITE_NULL, /* 0x11 (not possible) */
  76590. SQLITE_TEXT, /* 0x12 (not possible) */
  76591. SQLITE_NULL, /* 0x13 (not possible) */
  76592. SQLITE_INTEGER, /* 0x14 INTEGER + BLOB */
  76593. SQLITE_NULL, /* 0x15 (not possible) */
  76594. SQLITE_INTEGER, /* 0x16 (not possible) */
  76595. SQLITE_NULL, /* 0x17 (not possible) */
  76596. SQLITE_FLOAT, /* 0x18 FLOAT + BLOB */
  76597. SQLITE_NULL, /* 0x19 (not possible) */
  76598. SQLITE_FLOAT, /* 0x1a (not possible) */
  76599. SQLITE_NULL, /* 0x1b (not possible) */
  76600. SQLITE_INTEGER, /* 0x1c (not possible) */
  76601. SQLITE_NULL, /* 0x1d (not possible) */
  76602. SQLITE_INTEGER, /* 0x1e (not possible) */
  76603. SQLITE_NULL, /* 0x1f (not possible) */
  76604. SQLITE_FLOAT, /* 0x20 INTREAL */
  76605. SQLITE_NULL, /* 0x21 (not possible) */
  76606. SQLITE_TEXT, /* 0x22 INTREAL + TEXT */
  76607. SQLITE_NULL, /* 0x23 (not possible) */
  76608. SQLITE_FLOAT, /* 0x24 (not possible) */
  76609. SQLITE_NULL, /* 0x25 (not possible) */
  76610. SQLITE_FLOAT, /* 0x26 (not possible) */
  76611. SQLITE_NULL, /* 0x27 (not possible) */
  76612. SQLITE_FLOAT, /* 0x28 (not possible) */
  76613. SQLITE_NULL, /* 0x29 (not possible) */
  76614. SQLITE_FLOAT, /* 0x2a (not possible) */
  76615. SQLITE_NULL, /* 0x2b (not possible) */
  76616. SQLITE_FLOAT, /* 0x2c (not possible) */
  76617. SQLITE_NULL, /* 0x2d (not possible) */
  76618. SQLITE_FLOAT, /* 0x2e (not possible) */
  76619. SQLITE_NULL, /* 0x2f (not possible) */
  76620. SQLITE_BLOB, /* 0x30 (not possible) */
  76621. SQLITE_NULL, /* 0x31 (not possible) */
  76622. SQLITE_TEXT, /* 0x32 (not possible) */
  76623. SQLITE_NULL, /* 0x33 (not possible) */
  76624. SQLITE_FLOAT, /* 0x34 (not possible) */
  76625. SQLITE_NULL, /* 0x35 (not possible) */
  76626. SQLITE_FLOAT, /* 0x36 (not possible) */
  76627. SQLITE_NULL, /* 0x37 (not possible) */
  76628. SQLITE_FLOAT, /* 0x38 (not possible) */
  76629. SQLITE_NULL, /* 0x39 (not possible) */
  76630. SQLITE_FLOAT, /* 0x3a (not possible) */
  76631. SQLITE_NULL, /* 0x3b (not possible) */
  76632. SQLITE_FLOAT, /* 0x3c (not possible) */
  76633. SQLITE_NULL, /* 0x3d (not possible) */
  76634. SQLITE_FLOAT, /* 0x3e (not possible) */
  76635. SQLITE_NULL, /* 0x3f (not possible) */
  76636. };
  76637. #ifdef SQLITE_DEBUG
  76638. {
  76639. int eType = SQLITE_BLOB;
  76640. if( pVal->flags & MEM_Null ){
  76641. eType = SQLITE_NULL;
  76642. }else if( pVal->flags & (MEM_Real|MEM_IntReal) ){
  76643. eType = SQLITE_FLOAT;
  76644. }else if( pVal->flags & MEM_Int ){
  76645. eType = SQLITE_INTEGER;
  76646. }else if( pVal->flags & MEM_Str ){
  76647. eType = SQLITE_TEXT;
  76648. }
  76649. assert( eType == aType[pVal->flags&MEM_AffMask] );
  76650. }
  76651. #endif
  76652. return aType[pVal->flags&MEM_AffMask];
  76653. }
  76654. /* Return true if a parameter to xUpdate represents an unchanged column */
  76655. SQLITE_API int sqlite3_value_nochange(sqlite3_value *pVal){
  76656. return (pVal->flags&(MEM_Null|MEM_Zero))==(MEM_Null|MEM_Zero);
  76657. }
  76658. /* Return true if a parameter value originated from an sqlite3_bind() */
  76659. SQLITE_API int sqlite3_value_frombind(sqlite3_value *pVal){
  76660. return (pVal->flags&MEM_FromBind)!=0;
  76661. }
  76662. /* Make a copy of an sqlite3_value object
  76663. */
  76664. SQLITE_API sqlite3_value *sqlite3_value_dup(const sqlite3_value *pOrig){
  76665. sqlite3_value *pNew;
  76666. if( pOrig==0 ) return 0;
  76667. pNew = sqlite3_malloc( sizeof(*pNew) );
  76668. if( pNew==0 ) return 0;
  76669. memset(pNew, 0, sizeof(*pNew));
  76670. memcpy(pNew, pOrig, MEMCELLSIZE);
  76671. pNew->flags &= ~MEM_Dyn;
  76672. pNew->db = 0;
  76673. if( pNew->flags&(MEM_Str|MEM_Blob) ){
  76674. pNew->flags &= ~(MEM_Static|MEM_Dyn);
  76675. pNew->flags |= MEM_Ephem;
  76676. if( sqlite3VdbeMemMakeWriteable(pNew)!=SQLITE_OK ){
  76677. sqlite3ValueFree(pNew);
  76678. pNew = 0;
  76679. }
  76680. }
  76681. return pNew;
  76682. }
  76683. /* Destroy an sqlite3_value object previously obtained from
  76684. ** sqlite3_value_dup().
  76685. */
  76686. SQLITE_API void sqlite3_value_free(sqlite3_value *pOld){
  76687. sqlite3ValueFree(pOld);
  76688. }
  76689. /**************************** sqlite3_result_ *******************************
  76690. ** The following routines are used by user-defined functions to specify
  76691. ** the function result.
  76692. **
  76693. ** The setStrOrError() function calls sqlite3VdbeMemSetStr() to store the
  76694. ** result as a string or blob but if the string or blob is too large, it
  76695. ** then sets the error code to SQLITE_TOOBIG
  76696. **
  76697. ** The invokeValueDestructor(P,X) routine invokes destructor function X()
  76698. ** on value P is not going to be used and need to be destroyed.
  76699. */
  76700. static void setResultStrOrError(
  76701. sqlite3_context *pCtx, /* Function context */
  76702. const char *z, /* String pointer */
  76703. int n, /* Bytes in string, or negative */
  76704. u8 enc, /* Encoding of z. 0 for BLOBs */
  76705. void (*xDel)(void*) /* Destructor function */
  76706. ){
  76707. if( sqlite3VdbeMemSetStr(pCtx->pOut, z, n, enc, xDel)==SQLITE_TOOBIG ){
  76708. sqlite3_result_error_toobig(pCtx);
  76709. }
  76710. }
  76711. static int invokeValueDestructor(
  76712. const void *p, /* Value to destroy */
  76713. void (*xDel)(void*), /* The destructor */
  76714. sqlite3_context *pCtx /* Set a SQLITE_TOOBIG error if no NULL */
  76715. ){
  76716. assert( xDel!=SQLITE_DYNAMIC );
  76717. if( xDel==0 ){
  76718. /* noop */
  76719. }else if( xDel==SQLITE_TRANSIENT ){
  76720. /* noop */
  76721. }else{
  76722. xDel((void*)p);
  76723. }
  76724. if( pCtx ) sqlite3_result_error_toobig(pCtx);
  76725. return SQLITE_TOOBIG;
  76726. }
  76727. SQLITE_API void sqlite3_result_blob(
  76728. sqlite3_context *pCtx,
  76729. const void *z,
  76730. int n,
  76731. void (*xDel)(void *)
  76732. ){
  76733. assert( n>=0 );
  76734. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  76735. setResultStrOrError(pCtx, z, n, 0, xDel);
  76736. }
  76737. SQLITE_API void sqlite3_result_blob64(
  76738. sqlite3_context *pCtx,
  76739. const void *z,
  76740. sqlite3_uint64 n,
  76741. void (*xDel)(void *)
  76742. ){
  76743. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  76744. assert( xDel!=SQLITE_DYNAMIC );
  76745. if( n>0x7fffffff ){
  76746. (void)invokeValueDestructor(z, xDel, pCtx);
  76747. }else{
  76748. setResultStrOrError(pCtx, z, (int)n, 0, xDel);
  76749. }
  76750. }
  76751. SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
  76752. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  76753. sqlite3VdbeMemSetDouble(pCtx->pOut, rVal);
  76754. }
  76755. SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
  76756. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  76757. pCtx->isError = SQLITE_ERROR;
  76758. sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
  76759. }
  76760. #ifndef SQLITE_OMIT_UTF16
  76761. SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
  76762. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  76763. pCtx->isError = SQLITE_ERROR;
  76764. sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
  76765. }
  76766. #endif
  76767. SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
  76768. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  76769. sqlite3VdbeMemSetInt64(pCtx->pOut, (i64)iVal);
  76770. }
  76771. SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
  76772. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  76773. sqlite3VdbeMemSetInt64(pCtx->pOut, iVal);
  76774. }
  76775. SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
  76776. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  76777. sqlite3VdbeMemSetNull(pCtx->pOut);
  76778. }
  76779. SQLITE_API void sqlite3_result_pointer(
  76780. sqlite3_context *pCtx,
  76781. void *pPtr,
  76782. const char *zPType,
  76783. void (*xDestructor)(void*)
  76784. ){
  76785. Mem *pOut = pCtx->pOut;
  76786. assert( sqlite3_mutex_held(pOut->db->mutex) );
  76787. sqlite3VdbeMemRelease(pOut);
  76788. pOut->flags = MEM_Null;
  76789. sqlite3VdbeMemSetPointer(pOut, pPtr, zPType, xDestructor);
  76790. }
  76791. SQLITE_API void sqlite3_result_subtype(sqlite3_context *pCtx, unsigned int eSubtype){
  76792. Mem *pOut = pCtx->pOut;
  76793. assert( sqlite3_mutex_held(pOut->db->mutex) );
  76794. pOut->eSubtype = eSubtype & 0xff;
  76795. pOut->flags |= MEM_Subtype;
  76796. }
  76797. SQLITE_API void sqlite3_result_text(
  76798. sqlite3_context *pCtx,
  76799. const char *z,
  76800. int n,
  76801. void (*xDel)(void *)
  76802. ){
  76803. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  76804. setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
  76805. }
  76806. SQLITE_API void sqlite3_result_text64(
  76807. sqlite3_context *pCtx,
  76808. const char *z,
  76809. sqlite3_uint64 n,
  76810. void (*xDel)(void *),
  76811. unsigned char enc
  76812. ){
  76813. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  76814. assert( xDel!=SQLITE_DYNAMIC );
  76815. if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
  76816. if( n>0x7fffffff ){
  76817. (void)invokeValueDestructor(z, xDel, pCtx);
  76818. }else{
  76819. setResultStrOrError(pCtx, z, (int)n, enc, xDel);
  76820. }
  76821. }
  76822. #ifndef SQLITE_OMIT_UTF16
  76823. SQLITE_API void sqlite3_result_text16(
  76824. sqlite3_context *pCtx,
  76825. const void *z,
  76826. int n,
  76827. void (*xDel)(void *)
  76828. ){
  76829. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  76830. setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
  76831. }
  76832. SQLITE_API void sqlite3_result_text16be(
  76833. sqlite3_context *pCtx,
  76834. const void *z,
  76835. int n,
  76836. void (*xDel)(void *)
  76837. ){
  76838. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  76839. setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
  76840. }
  76841. SQLITE_API void sqlite3_result_text16le(
  76842. sqlite3_context *pCtx,
  76843. const void *z,
  76844. int n,
  76845. void (*xDel)(void *)
  76846. ){
  76847. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  76848. setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
  76849. }
  76850. #endif /* SQLITE_OMIT_UTF16 */
  76851. SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
  76852. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  76853. sqlite3VdbeMemCopy(pCtx->pOut, pValue);
  76854. }
  76855. SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
  76856. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  76857. sqlite3VdbeMemSetZeroBlob(pCtx->pOut, n);
  76858. }
  76859. SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context *pCtx, u64 n){
  76860. Mem *pOut = pCtx->pOut;
  76861. assert( sqlite3_mutex_held(pOut->db->mutex) );
  76862. if( n>(u64)pOut->db->aLimit[SQLITE_LIMIT_LENGTH] ){
  76863. return SQLITE_TOOBIG;
  76864. }
  76865. sqlite3VdbeMemSetZeroBlob(pCtx->pOut, (int)n);
  76866. return SQLITE_OK;
  76867. }
  76868. SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
  76869. pCtx->isError = errCode ? errCode : -1;
  76870. #ifdef SQLITE_DEBUG
  76871. if( pCtx->pVdbe ) pCtx->pVdbe->rcApp = errCode;
  76872. #endif
  76873. if( pCtx->pOut->flags & MEM_Null ){
  76874. sqlite3VdbeMemSetStr(pCtx->pOut, sqlite3ErrStr(errCode), -1,
  76875. SQLITE_UTF8, SQLITE_STATIC);
  76876. }
  76877. }
  76878. /* Force an SQLITE_TOOBIG error. */
  76879. SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
  76880. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  76881. pCtx->isError = SQLITE_TOOBIG;
  76882. sqlite3VdbeMemSetStr(pCtx->pOut, "string or blob too big", -1,
  76883. SQLITE_UTF8, SQLITE_STATIC);
  76884. }
  76885. /* An SQLITE_NOMEM error. */
  76886. SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
  76887. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  76888. sqlite3VdbeMemSetNull(pCtx->pOut);
  76889. pCtx->isError = SQLITE_NOMEM_BKPT;
  76890. sqlite3OomFault(pCtx->pOut->db);
  76891. }
  76892. #ifndef SQLITE_UNTESTABLE
  76893. /* Force the INT64 value currently stored as the result to be
  76894. ** a MEM_IntReal value. See the SQLITE_TESTCTRL_RESULT_INTREAL
  76895. ** test-control.
  76896. */
  76897. SQLITE_PRIVATE void sqlite3ResultIntReal(sqlite3_context *pCtx){
  76898. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  76899. if( pCtx->pOut->flags & MEM_Int ){
  76900. pCtx->pOut->flags &= ~MEM_Int;
  76901. pCtx->pOut->flags |= MEM_IntReal;
  76902. }
  76903. }
  76904. #endif
  76905. /*
  76906. ** This function is called after a transaction has been committed. It
  76907. ** invokes callbacks registered with sqlite3_wal_hook() as required.
  76908. */
  76909. static int doWalCallbacks(sqlite3 *db){
  76910. int rc = SQLITE_OK;
  76911. #ifndef SQLITE_OMIT_WAL
  76912. int i;
  76913. for(i=0; i<db->nDb; i++){
  76914. Btree *pBt = db->aDb[i].pBt;
  76915. if( pBt ){
  76916. int nEntry;
  76917. sqlite3BtreeEnter(pBt);
  76918. nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
  76919. sqlite3BtreeLeave(pBt);
  76920. if( nEntry>0 && db->xWalCallback && rc==SQLITE_OK ){
  76921. rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zDbSName, nEntry);
  76922. }
  76923. }
  76924. }
  76925. #endif
  76926. return rc;
  76927. }
  76928. /*
  76929. ** Execute the statement pStmt, either until a row of data is ready, the
  76930. ** statement is completely executed or an error occurs.
  76931. **
  76932. ** This routine implements the bulk of the logic behind the sqlite_step()
  76933. ** API. The only thing omitted is the automatic recompile if a
  76934. ** schema change has occurred. That detail is handled by the
  76935. ** outer sqlite3_step() wrapper procedure.
  76936. */
  76937. static int sqlite3Step(Vdbe *p){
  76938. sqlite3 *db;
  76939. int rc;
  76940. assert(p);
  76941. if( p->magic!=VDBE_MAGIC_RUN ){
  76942. /* We used to require that sqlite3_reset() be called before retrying
  76943. ** sqlite3_step() after any error or after SQLITE_DONE. But beginning
  76944. ** with version 3.7.0, we changed this so that sqlite3_reset() would
  76945. ** be called automatically instead of throwing the SQLITE_MISUSE error.
  76946. ** This "automatic-reset" change is not technically an incompatibility,
  76947. ** since any application that receives an SQLITE_MISUSE is broken by
  76948. ** definition.
  76949. **
  76950. ** Nevertheless, some published applications that were originally written
  76951. ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
  76952. ** returns, and those were broken by the automatic-reset change. As a
  76953. ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
  76954. ** legacy behavior of returning SQLITE_MISUSE for cases where the
  76955. ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
  76956. ** or SQLITE_BUSY error.
  76957. */
  76958. #ifdef SQLITE_OMIT_AUTORESET
  76959. if( (rc = p->rc&0xff)==SQLITE_BUSY || rc==SQLITE_LOCKED ){
  76960. sqlite3_reset((sqlite3_stmt*)p);
  76961. }else{
  76962. return SQLITE_MISUSE_BKPT;
  76963. }
  76964. #else
  76965. sqlite3_reset((sqlite3_stmt*)p);
  76966. #endif
  76967. }
  76968. /* Check that malloc() has not failed. If it has, return early. */
  76969. db = p->db;
  76970. if( db->mallocFailed ){
  76971. p->rc = SQLITE_NOMEM;
  76972. return SQLITE_NOMEM_BKPT;
  76973. }
  76974. if( p->pc<0 && p->expired ){
  76975. p->rc = SQLITE_SCHEMA;
  76976. rc = SQLITE_ERROR;
  76977. goto end_of_step;
  76978. }
  76979. if( p->pc<0 ){
  76980. /* If there are no other statements currently running, then
  76981. ** reset the interrupt flag. This prevents a call to sqlite3_interrupt
  76982. ** from interrupting a statement that has not yet started.
  76983. */
  76984. if( db->nVdbeActive==0 ){
  76985. db->u1.isInterrupted = 0;
  76986. }
  76987. assert( db->nVdbeWrite>0 || db->autoCommit==0
  76988. || (db->nDeferredCons==0 && db->nDeferredImmCons==0)
  76989. );
  76990. #ifndef SQLITE_OMIT_TRACE
  76991. if( (db->mTrace & (SQLITE_TRACE_PROFILE|SQLITE_TRACE_XPROFILE))!=0
  76992. && !db->init.busy && p->zSql ){
  76993. sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
  76994. }else{
  76995. assert( p->startTime==0 );
  76996. }
  76997. #endif
  76998. db->nVdbeActive++;
  76999. if( p->readOnly==0 ) db->nVdbeWrite++;
  77000. if( p->bIsReader ) db->nVdbeRead++;
  77001. p->pc = 0;
  77002. }
  77003. #ifdef SQLITE_DEBUG
  77004. p->rcApp = SQLITE_OK;
  77005. #endif
  77006. #ifndef SQLITE_OMIT_EXPLAIN
  77007. if( p->explain ){
  77008. rc = sqlite3VdbeList(p);
  77009. }else
  77010. #endif /* SQLITE_OMIT_EXPLAIN */
  77011. {
  77012. db->nVdbeExec++;
  77013. rc = sqlite3VdbeExec(p);
  77014. db->nVdbeExec--;
  77015. }
  77016. if( rc!=SQLITE_ROW ){
  77017. #ifndef SQLITE_OMIT_TRACE
  77018. /* If the statement completed successfully, invoke the profile callback */
  77019. checkProfileCallback(db, p);
  77020. #endif
  77021. if( rc==SQLITE_DONE && db->autoCommit ){
  77022. assert( p->rc==SQLITE_OK );
  77023. p->rc = doWalCallbacks(db);
  77024. if( p->rc!=SQLITE_OK ){
  77025. rc = SQLITE_ERROR;
  77026. }
  77027. }
  77028. }
  77029. db->errCode = rc;
  77030. if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
  77031. p->rc = SQLITE_NOMEM_BKPT;
  77032. }
  77033. end_of_step:
  77034. /* At this point local variable rc holds the value that should be
  77035. ** returned if this statement was compiled using the legacy
  77036. ** sqlite3_prepare() interface. According to the docs, this can only
  77037. ** be one of the values in the first assert() below. Variable p->rc
  77038. ** contains the value that would be returned if sqlite3_finalize()
  77039. ** were called on statement p.
  77040. */
  77041. assert( rc==SQLITE_ROW || rc==SQLITE_DONE || rc==SQLITE_ERROR
  77042. || (rc&0xff)==SQLITE_BUSY || rc==SQLITE_MISUSE
  77043. );
  77044. assert( (p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE) || p->rc==p->rcApp );
  77045. if( rc!=SQLITE_ROW
  77046. && rc!=SQLITE_DONE
  77047. && (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0
  77048. ){
  77049. /* If this statement was prepared using saved SQL and an
  77050. ** error has occurred, then return the error code in p->rc to the
  77051. ** caller. Set the error code in the database handle to the same value.
  77052. */
  77053. rc = sqlite3VdbeTransferError(p);
  77054. }
  77055. return (rc&db->errMask);
  77056. }
  77057. /*
  77058. ** This is the top-level implementation of sqlite3_step(). Call
  77059. ** sqlite3Step() to do most of the work. If a schema error occurs,
  77060. ** call sqlite3Reprepare() and try again.
  77061. */
  77062. SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
  77063. int rc = SQLITE_OK; /* Result from sqlite3Step() */
  77064. Vdbe *v = (Vdbe*)pStmt; /* the prepared statement */
  77065. int cnt = 0; /* Counter to prevent infinite loop of reprepares */
  77066. sqlite3 *db; /* The database connection */
  77067. if( vdbeSafetyNotNull(v) ){
  77068. return SQLITE_MISUSE_BKPT;
  77069. }
  77070. db = v->db;
  77071. sqlite3_mutex_enter(db->mutex);
  77072. v->doingRerun = 0;
  77073. while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
  77074. && cnt++ < SQLITE_MAX_SCHEMA_RETRY ){
  77075. int savedPc = v->pc;
  77076. rc = sqlite3Reprepare(v);
  77077. if( rc!=SQLITE_OK ){
  77078. /* This case occurs after failing to recompile an sql statement.
  77079. ** The error message from the SQL compiler has already been loaded
  77080. ** into the database handle. This block copies the error message
  77081. ** from the database handle into the statement and sets the statement
  77082. ** program counter to 0 to ensure that when the statement is
  77083. ** finalized or reset the parser error message is available via
  77084. ** sqlite3_errmsg() and sqlite3_errcode().
  77085. */
  77086. const char *zErr = (const char *)sqlite3_value_text(db->pErr);
  77087. sqlite3DbFree(db, v->zErrMsg);
  77088. if( !db->mallocFailed ){
  77089. v->zErrMsg = sqlite3DbStrDup(db, zErr);
  77090. v->rc = rc = sqlite3ApiExit(db, rc);
  77091. } else {
  77092. v->zErrMsg = 0;
  77093. v->rc = rc = SQLITE_NOMEM_BKPT;
  77094. }
  77095. break;
  77096. }
  77097. sqlite3_reset(pStmt);
  77098. if( savedPc>=0 ) v->doingRerun = 1;
  77099. assert( v->expired==0 );
  77100. }
  77101. sqlite3_mutex_leave(db->mutex);
  77102. return rc;
  77103. }
  77104. /*
  77105. ** Extract the user data from a sqlite3_context structure and return a
  77106. ** pointer to it.
  77107. */
  77108. SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
  77109. assert( p && p->pFunc );
  77110. return p->pFunc->pUserData;
  77111. }
  77112. /*
  77113. ** Extract the user data from a sqlite3_context structure and return a
  77114. ** pointer to it.
  77115. **
  77116. ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
  77117. ** returns a copy of the pointer to the database connection (the 1st
  77118. ** parameter) of the sqlite3_create_function() and
  77119. ** sqlite3_create_function16() routines that originally registered the
  77120. ** application defined function.
  77121. */
  77122. SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
  77123. assert( p && p->pOut );
  77124. return p->pOut->db;
  77125. }
  77126. /*
  77127. ** If this routine is invoked from within an xColumn method of a virtual
  77128. ** table, then it returns true if and only if the the call is during an
  77129. ** UPDATE operation and the value of the column will not be modified
  77130. ** by the UPDATE.
  77131. **
  77132. ** If this routine is called from any context other than within the
  77133. ** xColumn method of a virtual table, then the return value is meaningless
  77134. ** and arbitrary.
  77135. **
  77136. ** Virtual table implements might use this routine to optimize their
  77137. ** performance by substituting a NULL result, or some other light-weight
  77138. ** value, as a signal to the xUpdate routine that the column is unchanged.
  77139. */
  77140. SQLITE_API int sqlite3_vtab_nochange(sqlite3_context *p){
  77141. assert( p );
  77142. return sqlite3_value_nochange(p->pOut);
  77143. }
  77144. /*
  77145. ** Return the current time for a statement. If the current time
  77146. ** is requested more than once within the same run of a single prepared
  77147. ** statement, the exact same time is returned for each invocation regardless
  77148. ** of the amount of time that elapses between invocations. In other words,
  77149. ** the time returned is always the time of the first call.
  77150. */
  77151. SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context *p){
  77152. int rc;
  77153. #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
  77154. sqlite3_int64 *piTime = &p->pVdbe->iCurrentTime;
  77155. assert( p->pVdbe!=0 );
  77156. #else
  77157. sqlite3_int64 iTime = 0;
  77158. sqlite3_int64 *piTime = p->pVdbe!=0 ? &p->pVdbe->iCurrentTime : &iTime;
  77159. #endif
  77160. if( *piTime==0 ){
  77161. rc = sqlite3OsCurrentTimeInt64(p->pOut->db->pVfs, piTime);
  77162. if( rc ) *piTime = 0;
  77163. }
  77164. return *piTime;
  77165. }
  77166. /*
  77167. ** Create a new aggregate context for p and return a pointer to
  77168. ** its pMem->z element.
  77169. */
  77170. static SQLITE_NOINLINE void *createAggContext(sqlite3_context *p, int nByte){
  77171. Mem *pMem = p->pMem;
  77172. assert( (pMem->flags & MEM_Agg)==0 );
  77173. if( nByte<=0 ){
  77174. sqlite3VdbeMemSetNull(pMem);
  77175. pMem->z = 0;
  77176. }else{
  77177. sqlite3VdbeMemClearAndResize(pMem, nByte);
  77178. pMem->flags = MEM_Agg;
  77179. pMem->u.pDef = p->pFunc;
  77180. if( pMem->z ){
  77181. memset(pMem->z, 0, nByte);
  77182. }
  77183. }
  77184. return (void*)pMem->z;
  77185. }
  77186. /*
  77187. ** Allocate or return the aggregate context for a user function. A new
  77188. ** context is allocated on the first call. Subsequent calls return the
  77189. ** same context that was returned on prior calls.
  77190. */
  77191. SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
  77192. assert( p && p->pFunc && p->pFunc->xFinalize );
  77193. assert( sqlite3_mutex_held(p->pOut->db->mutex) );
  77194. testcase( nByte<0 );
  77195. if( (p->pMem->flags & MEM_Agg)==0 ){
  77196. return createAggContext(p, nByte);
  77197. }else{
  77198. return (void*)p->pMem->z;
  77199. }
  77200. }
  77201. /*
  77202. ** Return the auxiliary data pointer, if any, for the iArg'th argument to
  77203. ** the user-function defined by pCtx.
  77204. **
  77205. ** The left-most argument is 0.
  77206. **
  77207. ** Undocumented behavior: If iArg is negative then access a cache of
  77208. ** auxiliary data pointers that is available to all functions within a
  77209. ** single prepared statement. The iArg values must match.
  77210. */
  77211. SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
  77212. AuxData *pAuxData;
  77213. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  77214. #if SQLITE_ENABLE_STAT3_OR_STAT4
  77215. if( pCtx->pVdbe==0 ) return 0;
  77216. #else
  77217. assert( pCtx->pVdbe!=0 );
  77218. #endif
  77219. for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNextAux){
  77220. if( pAuxData->iAuxArg==iArg && (pAuxData->iAuxOp==pCtx->iOp || iArg<0) ){
  77221. return pAuxData->pAux;
  77222. }
  77223. }
  77224. return 0;
  77225. }
  77226. /*
  77227. ** Set the auxiliary data pointer and delete function, for the iArg'th
  77228. ** argument to the user-function defined by pCtx. Any previous value is
  77229. ** deleted by calling the delete function specified when it was set.
  77230. **
  77231. ** The left-most argument is 0.
  77232. **
  77233. ** Undocumented behavior: If iArg is negative then make the data available
  77234. ** to all functions within the current prepared statement using iArg as an
  77235. ** access code.
  77236. */
  77237. SQLITE_API void sqlite3_set_auxdata(
  77238. sqlite3_context *pCtx,
  77239. int iArg,
  77240. void *pAux,
  77241. void (*xDelete)(void*)
  77242. ){
  77243. AuxData *pAuxData;
  77244. Vdbe *pVdbe = pCtx->pVdbe;
  77245. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  77246. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  77247. if( pVdbe==0 ) goto failed;
  77248. #else
  77249. assert( pVdbe!=0 );
  77250. #endif
  77251. for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNextAux){
  77252. if( pAuxData->iAuxArg==iArg && (pAuxData->iAuxOp==pCtx->iOp || iArg<0) ){
  77253. break;
  77254. }
  77255. }
  77256. if( pAuxData==0 ){
  77257. pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData));
  77258. if( !pAuxData ) goto failed;
  77259. pAuxData->iAuxOp = pCtx->iOp;
  77260. pAuxData->iAuxArg = iArg;
  77261. pAuxData->pNextAux = pVdbe->pAuxData;
  77262. pVdbe->pAuxData = pAuxData;
  77263. if( pCtx->isError==0 ) pCtx->isError = -1;
  77264. }else if( pAuxData->xDeleteAux ){
  77265. pAuxData->xDeleteAux(pAuxData->pAux);
  77266. }
  77267. pAuxData->pAux = pAux;
  77268. pAuxData->xDeleteAux = xDelete;
  77269. return;
  77270. failed:
  77271. if( xDelete ){
  77272. xDelete(pAux);
  77273. }
  77274. }
  77275. #ifndef SQLITE_OMIT_DEPRECATED
  77276. /*
  77277. ** Return the number of times the Step function of an aggregate has been
  77278. ** called.
  77279. **
  77280. ** This function is deprecated. Do not use it for new code. It is
  77281. ** provide only to avoid breaking legacy code. New aggregate function
  77282. ** implementations should keep their own counts within their aggregate
  77283. ** context.
  77284. */
  77285. SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
  77286. assert( p && p->pMem && p->pFunc && p->pFunc->xFinalize );
  77287. return p->pMem->n;
  77288. }
  77289. #endif
  77290. /*
  77291. ** Return the number of columns in the result set for the statement pStmt.
  77292. */
  77293. SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
  77294. Vdbe *pVm = (Vdbe *)pStmt;
  77295. return pVm ? pVm->nResColumn : 0;
  77296. }
  77297. /*
  77298. ** Return the number of values available from the current row of the
  77299. ** currently executing statement pStmt.
  77300. */
  77301. SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
  77302. Vdbe *pVm = (Vdbe *)pStmt;
  77303. if( pVm==0 || pVm->pResultSet==0 ) return 0;
  77304. return pVm->nResColumn;
  77305. }
  77306. /*
  77307. ** Return a pointer to static memory containing an SQL NULL value.
  77308. */
  77309. static const Mem *columnNullValue(void){
  77310. /* Even though the Mem structure contains an element
  77311. ** of type i64, on certain architectures (x86) with certain compiler
  77312. ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
  77313. ** instead of an 8-byte one. This all works fine, except that when
  77314. ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
  77315. ** that a Mem structure is located on an 8-byte boundary. To prevent
  77316. ** these assert()s from failing, when building with SQLITE_DEBUG defined
  77317. ** using gcc, we force nullMem to be 8-byte aligned using the magical
  77318. ** __attribute__((aligned(8))) macro. */
  77319. static const Mem nullMem
  77320. #if defined(SQLITE_DEBUG) && defined(__GNUC__)
  77321. __attribute__((aligned(8)))
  77322. #endif
  77323. = {
  77324. /* .u = */ {0},
  77325. /* .flags = */ (u16)MEM_Null,
  77326. /* .enc = */ (u8)0,
  77327. /* .eSubtype = */ (u8)0,
  77328. /* .n = */ (int)0,
  77329. /* .z = */ (char*)0,
  77330. /* .zMalloc = */ (char*)0,
  77331. /* .szMalloc = */ (int)0,
  77332. /* .uTemp = */ (u32)0,
  77333. /* .db = */ (sqlite3*)0,
  77334. /* .xDel = */ (void(*)(void*))0,
  77335. #ifdef SQLITE_DEBUG
  77336. /* .pScopyFrom = */ (Mem*)0,
  77337. /* .mScopyFlags= */ 0,
  77338. #endif
  77339. };
  77340. return &nullMem;
  77341. }
  77342. /*
  77343. ** Check to see if column iCol of the given statement is valid. If
  77344. ** it is, return a pointer to the Mem for the value of that column.
  77345. ** If iCol is not valid, return a pointer to a Mem which has a value
  77346. ** of NULL.
  77347. */
  77348. static Mem *columnMem(sqlite3_stmt *pStmt, int i){
  77349. Vdbe *pVm;
  77350. Mem *pOut;
  77351. pVm = (Vdbe *)pStmt;
  77352. if( pVm==0 ) return (Mem*)columnNullValue();
  77353. assert( pVm->db );
  77354. sqlite3_mutex_enter(pVm->db->mutex);
  77355. if( pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
  77356. pOut = &pVm->pResultSet[i];
  77357. }else{
  77358. sqlite3Error(pVm->db, SQLITE_RANGE);
  77359. pOut = (Mem*)columnNullValue();
  77360. }
  77361. return pOut;
  77362. }
  77363. /*
  77364. ** This function is called after invoking an sqlite3_value_XXX function on a
  77365. ** column value (i.e. a value returned by evaluating an SQL expression in the
  77366. ** select list of a SELECT statement) that may cause a malloc() failure. If
  77367. ** malloc() has failed, the threads mallocFailed flag is cleared and the result
  77368. ** code of statement pStmt set to SQLITE_NOMEM.
  77369. **
  77370. ** Specifically, this is called from within:
  77371. **
  77372. ** sqlite3_column_int()
  77373. ** sqlite3_column_int64()
  77374. ** sqlite3_column_text()
  77375. ** sqlite3_column_text16()
  77376. ** sqlite3_column_real()
  77377. ** sqlite3_column_bytes()
  77378. ** sqlite3_column_bytes16()
  77379. ** sqiite3_column_blob()
  77380. */
  77381. static void columnMallocFailure(sqlite3_stmt *pStmt)
  77382. {
  77383. /* If malloc() failed during an encoding conversion within an
  77384. ** sqlite3_column_XXX API, then set the return code of the statement to
  77385. ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
  77386. ** and _finalize() will return NOMEM.
  77387. */
  77388. Vdbe *p = (Vdbe *)pStmt;
  77389. if( p ){
  77390. assert( p->db!=0 );
  77391. assert( sqlite3_mutex_held(p->db->mutex) );
  77392. p->rc = sqlite3ApiExit(p->db, p->rc);
  77393. sqlite3_mutex_leave(p->db->mutex);
  77394. }
  77395. }
  77396. /**************************** sqlite3_column_ *******************************
  77397. ** The following routines are used to access elements of the current row
  77398. ** in the result set.
  77399. */
  77400. SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
  77401. const void *val;
  77402. val = sqlite3_value_blob( columnMem(pStmt,i) );
  77403. /* Even though there is no encoding conversion, value_blob() might
  77404. ** need to call malloc() to expand the result of a zeroblob()
  77405. ** expression.
  77406. */
  77407. columnMallocFailure(pStmt);
  77408. return val;
  77409. }
  77410. SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
  77411. int val = sqlite3_value_bytes( columnMem(pStmt,i) );
  77412. columnMallocFailure(pStmt);
  77413. return val;
  77414. }
  77415. SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
  77416. int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
  77417. columnMallocFailure(pStmt);
  77418. return val;
  77419. }
  77420. SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
  77421. double val = sqlite3_value_double( columnMem(pStmt,i) );
  77422. columnMallocFailure(pStmt);
  77423. return val;
  77424. }
  77425. SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
  77426. int val = sqlite3_value_int( columnMem(pStmt,i) );
  77427. columnMallocFailure(pStmt);
  77428. return val;
  77429. }
  77430. SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
  77431. sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
  77432. columnMallocFailure(pStmt);
  77433. return val;
  77434. }
  77435. SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
  77436. const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
  77437. columnMallocFailure(pStmt);
  77438. return val;
  77439. }
  77440. SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
  77441. Mem *pOut = columnMem(pStmt, i);
  77442. if( pOut->flags&MEM_Static ){
  77443. pOut->flags &= ~MEM_Static;
  77444. pOut->flags |= MEM_Ephem;
  77445. }
  77446. columnMallocFailure(pStmt);
  77447. return (sqlite3_value *)pOut;
  77448. }
  77449. #ifndef SQLITE_OMIT_UTF16
  77450. SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
  77451. const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
  77452. columnMallocFailure(pStmt);
  77453. return val;
  77454. }
  77455. #endif /* SQLITE_OMIT_UTF16 */
  77456. SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
  77457. int iType = sqlite3_value_type( columnMem(pStmt,i) );
  77458. columnMallocFailure(pStmt);
  77459. return iType;
  77460. }
  77461. /*
  77462. ** Convert the N-th element of pStmt->pColName[] into a string using
  77463. ** xFunc() then return that string. If N is out of range, return 0.
  77464. **
  77465. ** There are up to 5 names for each column. useType determines which
  77466. ** name is returned. Here are the names:
  77467. **
  77468. ** 0 The column name as it should be displayed for output
  77469. ** 1 The datatype name for the column
  77470. ** 2 The name of the database that the column derives from
  77471. ** 3 The name of the table that the column derives from
  77472. ** 4 The name of the table column that the result column derives from
  77473. **
  77474. ** If the result is not a simple column reference (if it is an expression
  77475. ** or a constant) then useTypes 2, 3, and 4 return NULL.
  77476. */
  77477. static const void *columnName(
  77478. sqlite3_stmt *pStmt, /* The statement */
  77479. int N, /* Which column to get the name for */
  77480. int useUtf16, /* True to return the name as UTF16 */
  77481. int useType /* What type of name */
  77482. ){
  77483. const void *ret;
  77484. Vdbe *p;
  77485. int n;
  77486. sqlite3 *db;
  77487. #ifdef SQLITE_ENABLE_API_ARMOR
  77488. if( pStmt==0 ){
  77489. (void)SQLITE_MISUSE_BKPT;
  77490. return 0;
  77491. }
  77492. #endif
  77493. ret = 0;
  77494. p = (Vdbe *)pStmt;
  77495. db = p->db;
  77496. assert( db!=0 );
  77497. n = sqlite3_column_count(pStmt);
  77498. if( N<n && N>=0 ){
  77499. N += useType*n;
  77500. sqlite3_mutex_enter(db->mutex);
  77501. assert( db->mallocFailed==0 );
  77502. #ifndef SQLITE_OMIT_UTF16
  77503. if( useUtf16 ){
  77504. ret = sqlite3_value_text16((sqlite3_value*)&p->aColName[N]);
  77505. }else
  77506. #endif
  77507. {
  77508. ret = sqlite3_value_text((sqlite3_value*)&p->aColName[N]);
  77509. }
  77510. /* A malloc may have failed inside of the _text() call. If this
  77511. ** is the case, clear the mallocFailed flag and return NULL.
  77512. */
  77513. if( db->mallocFailed ){
  77514. sqlite3OomClear(db);
  77515. ret = 0;
  77516. }
  77517. sqlite3_mutex_leave(db->mutex);
  77518. }
  77519. return ret;
  77520. }
  77521. /*
  77522. ** Return the name of the Nth column of the result set returned by SQL
  77523. ** statement pStmt.
  77524. */
  77525. SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
  77526. return columnName(pStmt, N, 0, COLNAME_NAME);
  77527. }
  77528. #ifndef SQLITE_OMIT_UTF16
  77529. SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
  77530. return columnName(pStmt, N, 1, COLNAME_NAME);
  77531. }
  77532. #endif
  77533. /*
  77534. ** Constraint: If you have ENABLE_COLUMN_METADATA then you must
  77535. ** not define OMIT_DECLTYPE.
  77536. */
  77537. #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
  77538. # error "Must not define both SQLITE_OMIT_DECLTYPE \
  77539. and SQLITE_ENABLE_COLUMN_METADATA"
  77540. #endif
  77541. #ifndef SQLITE_OMIT_DECLTYPE
  77542. /*
  77543. ** Return the column declaration type (if applicable) of the 'i'th column
  77544. ** of the result set of SQL statement pStmt.
  77545. */
  77546. SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
  77547. return columnName(pStmt, N, 0, COLNAME_DECLTYPE);
  77548. }
  77549. #ifndef SQLITE_OMIT_UTF16
  77550. SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
  77551. return columnName(pStmt, N, 1, COLNAME_DECLTYPE);
  77552. }
  77553. #endif /* SQLITE_OMIT_UTF16 */
  77554. #endif /* SQLITE_OMIT_DECLTYPE */
  77555. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  77556. /*
  77557. ** Return the name of the database from which a result column derives.
  77558. ** NULL is returned if the result column is an expression or constant or
  77559. ** anything else which is not an unambiguous reference to a database column.
  77560. */
  77561. SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
  77562. return columnName(pStmt, N, 0, COLNAME_DATABASE);
  77563. }
  77564. #ifndef SQLITE_OMIT_UTF16
  77565. SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
  77566. return columnName(pStmt, N, 1, COLNAME_DATABASE);
  77567. }
  77568. #endif /* SQLITE_OMIT_UTF16 */
  77569. /*
  77570. ** Return the name of the table from which a result column derives.
  77571. ** NULL is returned if the result column is an expression or constant or
  77572. ** anything else which is not an unambiguous reference to a database column.
  77573. */
  77574. SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
  77575. return columnName(pStmt, N, 0, COLNAME_TABLE);
  77576. }
  77577. #ifndef SQLITE_OMIT_UTF16
  77578. SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
  77579. return columnName(pStmt, N, 1, COLNAME_TABLE);
  77580. }
  77581. #endif /* SQLITE_OMIT_UTF16 */
  77582. /*
  77583. ** Return the name of the table column from which a result column derives.
  77584. ** NULL is returned if the result column is an expression or constant or
  77585. ** anything else which is not an unambiguous reference to a database column.
  77586. */
  77587. SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
  77588. return columnName(pStmt, N, 0, COLNAME_COLUMN);
  77589. }
  77590. #ifndef SQLITE_OMIT_UTF16
  77591. SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
  77592. return columnName(pStmt, N, 1, COLNAME_COLUMN);
  77593. }
  77594. #endif /* SQLITE_OMIT_UTF16 */
  77595. #endif /* SQLITE_ENABLE_COLUMN_METADATA */
  77596. /******************************* sqlite3_bind_ ***************************
  77597. **
  77598. ** Routines used to attach values to wildcards in a compiled SQL statement.
  77599. */
  77600. /*
  77601. ** Unbind the value bound to variable i in virtual machine p. This is the
  77602. ** the same as binding a NULL value to the column. If the "i" parameter is
  77603. ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
  77604. **
  77605. ** A successful evaluation of this routine acquires the mutex on p.
  77606. ** the mutex is released if any kind of error occurs.
  77607. **
  77608. ** The error code stored in database p->db is overwritten with the return
  77609. ** value in any case.
  77610. */
  77611. static int vdbeUnbind(Vdbe *p, int i){
  77612. Mem *pVar;
  77613. if( vdbeSafetyNotNull(p) ){
  77614. return SQLITE_MISUSE_BKPT;
  77615. }
  77616. sqlite3_mutex_enter(p->db->mutex);
  77617. if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
  77618. sqlite3Error(p->db, SQLITE_MISUSE);
  77619. sqlite3_mutex_leave(p->db->mutex);
  77620. sqlite3_log(SQLITE_MISUSE,
  77621. "bind on a busy prepared statement: [%s]", p->zSql);
  77622. return SQLITE_MISUSE_BKPT;
  77623. }
  77624. if( i<1 || i>p->nVar ){
  77625. sqlite3Error(p->db, SQLITE_RANGE);
  77626. sqlite3_mutex_leave(p->db->mutex);
  77627. return SQLITE_RANGE;
  77628. }
  77629. i--;
  77630. pVar = &p->aVar[i];
  77631. sqlite3VdbeMemRelease(pVar);
  77632. pVar->flags = MEM_Null;
  77633. p->db->errCode = SQLITE_OK;
  77634. /* If the bit corresponding to this variable in Vdbe.expmask is set, then
  77635. ** binding a new value to this variable invalidates the current query plan.
  77636. **
  77637. ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
  77638. ** parameter in the WHERE clause might influence the choice of query plan
  77639. ** for a statement, then the statement will be automatically recompiled,
  77640. ** as if there had been a schema change, on the first sqlite3_step() call
  77641. ** following any change to the bindings of that parameter.
  77642. */
  77643. assert( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || p->expmask==0 );
  77644. if( p->expmask!=0 && (p->expmask & (i>=31 ? 0x80000000 : (u32)1<<i))!=0 ){
  77645. p->expired = 1;
  77646. }
  77647. return SQLITE_OK;
  77648. }
  77649. /*
  77650. ** Bind a text or BLOB value.
  77651. */
  77652. static int bindText(
  77653. sqlite3_stmt *pStmt, /* The statement to bind against */
  77654. int i, /* Index of the parameter to bind */
  77655. const void *zData, /* Pointer to the data to be bound */
  77656. int nData, /* Number of bytes of data to be bound */
  77657. void (*xDel)(void*), /* Destructor for the data */
  77658. u8 encoding /* Encoding for the data */
  77659. ){
  77660. Vdbe *p = (Vdbe *)pStmt;
  77661. Mem *pVar;
  77662. int rc;
  77663. rc = vdbeUnbind(p, i);
  77664. if( rc==SQLITE_OK ){
  77665. if( zData!=0 ){
  77666. pVar = &p->aVar[i-1];
  77667. rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
  77668. if( rc==SQLITE_OK && encoding!=0 ){
  77669. rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
  77670. }
  77671. if( rc ){
  77672. sqlite3Error(p->db, rc);
  77673. rc = sqlite3ApiExit(p->db, rc);
  77674. }
  77675. }
  77676. sqlite3_mutex_leave(p->db->mutex);
  77677. }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
  77678. xDel((void*)zData);
  77679. }
  77680. return rc;
  77681. }
  77682. /*
  77683. ** Bind a blob value to an SQL statement variable.
  77684. */
  77685. SQLITE_API int sqlite3_bind_blob(
  77686. sqlite3_stmt *pStmt,
  77687. int i,
  77688. const void *zData,
  77689. int nData,
  77690. void (*xDel)(void*)
  77691. ){
  77692. #ifdef SQLITE_ENABLE_API_ARMOR
  77693. if( nData<0 ) return SQLITE_MISUSE_BKPT;
  77694. #endif
  77695. return bindText(pStmt, i, zData, nData, xDel, 0);
  77696. }
  77697. SQLITE_API int sqlite3_bind_blob64(
  77698. sqlite3_stmt *pStmt,
  77699. int i,
  77700. const void *zData,
  77701. sqlite3_uint64 nData,
  77702. void (*xDel)(void*)
  77703. ){
  77704. assert( xDel!=SQLITE_DYNAMIC );
  77705. if( nData>0x7fffffff ){
  77706. return invokeValueDestructor(zData, xDel, 0);
  77707. }else{
  77708. return bindText(pStmt, i, zData, (int)nData, xDel, 0);
  77709. }
  77710. }
  77711. SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
  77712. int rc;
  77713. Vdbe *p = (Vdbe *)pStmt;
  77714. rc = vdbeUnbind(p, i);
  77715. if( rc==SQLITE_OK ){
  77716. sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
  77717. sqlite3_mutex_leave(p->db->mutex);
  77718. }
  77719. return rc;
  77720. }
  77721. SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
  77722. return sqlite3_bind_int64(p, i, (i64)iValue);
  77723. }
  77724. SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
  77725. int rc;
  77726. Vdbe *p = (Vdbe *)pStmt;
  77727. rc = vdbeUnbind(p, i);
  77728. if( rc==SQLITE_OK ){
  77729. sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
  77730. sqlite3_mutex_leave(p->db->mutex);
  77731. }
  77732. return rc;
  77733. }
  77734. SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
  77735. int rc;
  77736. Vdbe *p = (Vdbe*)pStmt;
  77737. rc = vdbeUnbind(p, i);
  77738. if( rc==SQLITE_OK ){
  77739. sqlite3_mutex_leave(p->db->mutex);
  77740. }
  77741. return rc;
  77742. }
  77743. SQLITE_API int sqlite3_bind_pointer(
  77744. sqlite3_stmt *pStmt,
  77745. int i,
  77746. void *pPtr,
  77747. const char *zPTtype,
  77748. void (*xDestructor)(void*)
  77749. ){
  77750. int rc;
  77751. Vdbe *p = (Vdbe*)pStmt;
  77752. rc = vdbeUnbind(p, i);
  77753. if( rc==SQLITE_OK ){
  77754. sqlite3VdbeMemSetPointer(&p->aVar[i-1], pPtr, zPTtype, xDestructor);
  77755. sqlite3_mutex_leave(p->db->mutex);
  77756. }else if( xDestructor ){
  77757. xDestructor(pPtr);
  77758. }
  77759. return rc;
  77760. }
  77761. SQLITE_API int sqlite3_bind_text(
  77762. sqlite3_stmt *pStmt,
  77763. int i,
  77764. const char *zData,
  77765. int nData,
  77766. void (*xDel)(void*)
  77767. ){
  77768. return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
  77769. }
  77770. SQLITE_API int sqlite3_bind_text64(
  77771. sqlite3_stmt *pStmt,
  77772. int i,
  77773. const char *zData,
  77774. sqlite3_uint64 nData,
  77775. void (*xDel)(void*),
  77776. unsigned char enc
  77777. ){
  77778. assert( xDel!=SQLITE_DYNAMIC );
  77779. if( nData>0x7fffffff ){
  77780. return invokeValueDestructor(zData, xDel, 0);
  77781. }else{
  77782. if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
  77783. return bindText(pStmt, i, zData, (int)nData, xDel, enc);
  77784. }
  77785. }
  77786. #ifndef SQLITE_OMIT_UTF16
  77787. SQLITE_API int sqlite3_bind_text16(
  77788. sqlite3_stmt *pStmt,
  77789. int i,
  77790. const void *zData,
  77791. int nData,
  77792. void (*xDel)(void*)
  77793. ){
  77794. return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
  77795. }
  77796. #endif /* SQLITE_OMIT_UTF16 */
  77797. SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
  77798. int rc;
  77799. switch( sqlite3_value_type((sqlite3_value*)pValue) ){
  77800. case SQLITE_INTEGER: {
  77801. rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
  77802. break;
  77803. }
  77804. case SQLITE_FLOAT: {
  77805. rc = sqlite3_bind_double(pStmt, i, pValue->u.r);
  77806. break;
  77807. }
  77808. case SQLITE_BLOB: {
  77809. if( pValue->flags & MEM_Zero ){
  77810. rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
  77811. }else{
  77812. rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
  77813. }
  77814. break;
  77815. }
  77816. case SQLITE_TEXT: {
  77817. rc = bindText(pStmt,i, pValue->z, pValue->n, SQLITE_TRANSIENT,
  77818. pValue->enc);
  77819. break;
  77820. }
  77821. default: {
  77822. rc = sqlite3_bind_null(pStmt, i);
  77823. break;
  77824. }
  77825. }
  77826. return rc;
  77827. }
  77828. SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
  77829. int rc;
  77830. Vdbe *p = (Vdbe *)pStmt;
  77831. rc = vdbeUnbind(p, i);
  77832. if( rc==SQLITE_OK ){
  77833. sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
  77834. sqlite3_mutex_leave(p->db->mutex);
  77835. }
  77836. return rc;
  77837. }
  77838. SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt *pStmt, int i, sqlite3_uint64 n){
  77839. int rc;
  77840. Vdbe *p = (Vdbe *)pStmt;
  77841. sqlite3_mutex_enter(p->db->mutex);
  77842. if( n>(u64)p->db->aLimit[SQLITE_LIMIT_LENGTH] ){
  77843. rc = SQLITE_TOOBIG;
  77844. }else{
  77845. assert( (n & 0x7FFFFFFF)==n );
  77846. rc = sqlite3_bind_zeroblob(pStmt, i, n);
  77847. }
  77848. rc = sqlite3ApiExit(p->db, rc);
  77849. sqlite3_mutex_leave(p->db->mutex);
  77850. return rc;
  77851. }
  77852. /*
  77853. ** Return the number of wildcards that can be potentially bound to.
  77854. ** This routine is added to support DBD::SQLite.
  77855. */
  77856. SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
  77857. Vdbe *p = (Vdbe*)pStmt;
  77858. return p ? p->nVar : 0;
  77859. }
  77860. /*
  77861. ** Return the name of a wildcard parameter. Return NULL if the index
  77862. ** is out of range or if the wildcard is unnamed.
  77863. **
  77864. ** The result is always UTF-8.
  77865. */
  77866. SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
  77867. Vdbe *p = (Vdbe*)pStmt;
  77868. if( p==0 ) return 0;
  77869. return sqlite3VListNumToName(p->pVList, i);
  77870. }
  77871. /*
  77872. ** Given a wildcard parameter name, return the index of the variable
  77873. ** with that name. If there is no variable with the given name,
  77874. ** return 0.
  77875. */
  77876. SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
  77877. if( p==0 || zName==0 ) return 0;
  77878. return sqlite3VListNameToNum(p->pVList, zName, nName);
  77879. }
  77880. SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
  77881. return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
  77882. }
  77883. /*
  77884. ** Transfer all bindings from the first statement over to the second.
  77885. */
  77886. SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
  77887. Vdbe *pFrom = (Vdbe*)pFromStmt;
  77888. Vdbe *pTo = (Vdbe*)pToStmt;
  77889. int i;
  77890. assert( pTo->db==pFrom->db );
  77891. assert( pTo->nVar==pFrom->nVar );
  77892. sqlite3_mutex_enter(pTo->db->mutex);
  77893. for(i=0; i<pFrom->nVar; i++){
  77894. sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
  77895. }
  77896. sqlite3_mutex_leave(pTo->db->mutex);
  77897. return SQLITE_OK;
  77898. }
  77899. #ifndef SQLITE_OMIT_DEPRECATED
  77900. /*
  77901. ** Deprecated external interface. Internal/core SQLite code
  77902. ** should call sqlite3TransferBindings.
  77903. **
  77904. ** It is misuse to call this routine with statements from different
  77905. ** database connections. But as this is a deprecated interface, we
  77906. ** will not bother to check for that condition.
  77907. **
  77908. ** If the two statements contain a different number of bindings, then
  77909. ** an SQLITE_ERROR is returned. Nothing else can go wrong, so otherwise
  77910. ** SQLITE_OK is returned.
  77911. */
  77912. SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
  77913. Vdbe *pFrom = (Vdbe*)pFromStmt;
  77914. Vdbe *pTo = (Vdbe*)pToStmt;
  77915. if( pFrom->nVar!=pTo->nVar ){
  77916. return SQLITE_ERROR;
  77917. }
  77918. assert( (pTo->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || pTo->expmask==0 );
  77919. if( pTo->expmask ){
  77920. pTo->expired = 1;
  77921. }
  77922. assert( (pFrom->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || pFrom->expmask==0 );
  77923. if( pFrom->expmask ){
  77924. pFrom->expired = 1;
  77925. }
  77926. return sqlite3TransferBindings(pFromStmt, pToStmt);
  77927. }
  77928. #endif
  77929. /*
  77930. ** Return the sqlite3* database handle to which the prepared statement given
  77931. ** in the argument belongs. This is the same database handle that was
  77932. ** the first argument to the sqlite3_prepare() that was used to create
  77933. ** the statement in the first place.
  77934. */
  77935. SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
  77936. return pStmt ? ((Vdbe*)pStmt)->db : 0;
  77937. }
  77938. /*
  77939. ** Return true if the prepared statement is guaranteed to not modify the
  77940. ** database.
  77941. */
  77942. SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
  77943. return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
  77944. }
  77945. /*
  77946. ** Return 1 if the statement is an EXPLAIN and return 2 if the
  77947. ** statement is an EXPLAIN QUERY PLAN
  77948. */
  77949. SQLITE_API int sqlite3_stmt_isexplain(sqlite3_stmt *pStmt){
  77950. return pStmt ? ((Vdbe*)pStmt)->explain : 0;
  77951. }
  77952. /*
  77953. ** Return true if the prepared statement is in need of being reset.
  77954. */
  77955. SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt *pStmt){
  77956. Vdbe *v = (Vdbe*)pStmt;
  77957. return v!=0 && v->magic==VDBE_MAGIC_RUN && v->pc>=0;
  77958. }
  77959. /*
  77960. ** Return a pointer to the next prepared statement after pStmt associated
  77961. ** with database connection pDb. If pStmt is NULL, return the first
  77962. ** prepared statement for the database connection. Return NULL if there
  77963. ** are no more.
  77964. */
  77965. SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
  77966. sqlite3_stmt *pNext;
  77967. #ifdef SQLITE_ENABLE_API_ARMOR
  77968. if( !sqlite3SafetyCheckOk(pDb) ){
  77969. (void)SQLITE_MISUSE_BKPT;
  77970. return 0;
  77971. }
  77972. #endif
  77973. sqlite3_mutex_enter(pDb->mutex);
  77974. if( pStmt==0 ){
  77975. pNext = (sqlite3_stmt*)pDb->pVdbe;
  77976. }else{
  77977. pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
  77978. }
  77979. sqlite3_mutex_leave(pDb->mutex);
  77980. return pNext;
  77981. }
  77982. /*
  77983. ** Return the value of a status counter for a prepared statement
  77984. */
  77985. SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
  77986. Vdbe *pVdbe = (Vdbe*)pStmt;
  77987. u32 v;
  77988. #ifdef SQLITE_ENABLE_API_ARMOR
  77989. if( !pStmt
  77990. || (op!=SQLITE_STMTSTATUS_MEMUSED && (op<0||op>=ArraySize(pVdbe->aCounter)))
  77991. ){
  77992. (void)SQLITE_MISUSE_BKPT;
  77993. return 0;
  77994. }
  77995. #endif
  77996. if( op==SQLITE_STMTSTATUS_MEMUSED ){
  77997. sqlite3 *db = pVdbe->db;
  77998. sqlite3_mutex_enter(db->mutex);
  77999. v = 0;
  78000. db->pnBytesFreed = (int*)&v;
  78001. sqlite3VdbeClearObject(db, pVdbe);
  78002. sqlite3DbFree(db, pVdbe);
  78003. db->pnBytesFreed = 0;
  78004. sqlite3_mutex_leave(db->mutex);
  78005. }else{
  78006. v = pVdbe->aCounter[op];
  78007. if( resetFlag ) pVdbe->aCounter[op] = 0;
  78008. }
  78009. return (int)v;
  78010. }
  78011. /*
  78012. ** Return the SQL associated with a prepared statement
  78013. */
  78014. SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
  78015. Vdbe *p = (Vdbe *)pStmt;
  78016. return p ? p->zSql : 0;
  78017. }
  78018. /*
  78019. ** Return the SQL associated with a prepared statement with
  78020. ** bound parameters expanded. Space to hold the returned string is
  78021. ** obtained from sqlite3_malloc(). The caller is responsible for
  78022. ** freeing the returned string by passing it to sqlite3_free().
  78023. **
  78024. ** The SQLITE_TRACE_SIZE_LIMIT puts an upper bound on the size of
  78025. ** expanded bound parameters.
  78026. */
  78027. SQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt){
  78028. #ifdef SQLITE_OMIT_TRACE
  78029. return 0;
  78030. #else
  78031. char *z = 0;
  78032. const char *zSql = sqlite3_sql(pStmt);
  78033. if( zSql ){
  78034. Vdbe *p = (Vdbe *)pStmt;
  78035. sqlite3_mutex_enter(p->db->mutex);
  78036. z = sqlite3VdbeExpandSql(p, zSql);
  78037. sqlite3_mutex_leave(p->db->mutex);
  78038. }
  78039. return z;
  78040. #endif
  78041. }
  78042. #ifdef SQLITE_ENABLE_NORMALIZE
  78043. /*
  78044. ** Return the normalized SQL associated with a prepared statement.
  78045. */
  78046. SQLITE_API const char *sqlite3_normalized_sql(sqlite3_stmt *pStmt){
  78047. Vdbe *p = (Vdbe *)pStmt;
  78048. if( p==0 ) return 0;
  78049. if( p->zNormSql==0 && ALWAYS(p->zSql!=0) ){
  78050. sqlite3_mutex_enter(p->db->mutex);
  78051. p->zNormSql = sqlite3Normalize(p, p->zSql);
  78052. sqlite3_mutex_leave(p->db->mutex);
  78053. }
  78054. return p->zNormSql;
  78055. }
  78056. #endif /* SQLITE_ENABLE_NORMALIZE */
  78057. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  78058. /*
  78059. ** Allocate and populate an UnpackedRecord structure based on the serialized
  78060. ** record in nKey/pKey. Return a pointer to the new UnpackedRecord structure
  78061. ** if successful, or a NULL pointer if an OOM error is encountered.
  78062. */
  78063. static UnpackedRecord *vdbeUnpackRecord(
  78064. KeyInfo *pKeyInfo,
  78065. int nKey,
  78066. const void *pKey
  78067. ){
  78068. UnpackedRecord *pRet; /* Return value */
  78069. pRet = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);
  78070. if( pRet ){
  78071. memset(pRet->aMem, 0, sizeof(Mem)*(pKeyInfo->nKeyField+1));
  78072. sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, pRet);
  78073. }
  78074. return pRet;
  78075. }
  78076. /*
  78077. ** This function is called from within a pre-update callback to retrieve
  78078. ** a field of the row currently being updated or deleted.
  78079. */
  78080. SQLITE_API int sqlite3_preupdate_old(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
  78081. PreUpdate *p = db->pPreUpdate;
  78082. Mem *pMem;
  78083. int rc = SQLITE_OK;
  78084. /* Test that this call is being made from within an SQLITE_DELETE or
  78085. ** SQLITE_UPDATE pre-update callback, and that iIdx is within range. */
  78086. if( !p || p->op==SQLITE_INSERT ){
  78087. rc = SQLITE_MISUSE_BKPT;
  78088. goto preupdate_old_out;
  78089. }
  78090. if( p->pPk ){
  78091. iIdx = sqlite3ColumnOfIndex(p->pPk, iIdx);
  78092. }
  78093. if( iIdx>=p->pCsr->nField || iIdx<0 ){
  78094. rc = SQLITE_RANGE;
  78095. goto preupdate_old_out;
  78096. }
  78097. /* If the old.* record has not yet been loaded into memory, do so now. */
  78098. if( p->pUnpacked==0 ){
  78099. u32 nRec;
  78100. u8 *aRec;
  78101. nRec = sqlite3BtreePayloadSize(p->pCsr->uc.pCursor);
  78102. aRec = sqlite3DbMallocRaw(db, nRec);
  78103. if( !aRec ) goto preupdate_old_out;
  78104. rc = sqlite3BtreePayload(p->pCsr->uc.pCursor, 0, nRec, aRec);
  78105. if( rc==SQLITE_OK ){
  78106. p->pUnpacked = vdbeUnpackRecord(&p->keyinfo, nRec, aRec);
  78107. if( !p->pUnpacked ) rc = SQLITE_NOMEM;
  78108. }
  78109. if( rc!=SQLITE_OK ){
  78110. sqlite3DbFree(db, aRec);
  78111. goto preupdate_old_out;
  78112. }
  78113. p->aRecord = aRec;
  78114. }
  78115. pMem = *ppValue = &p->pUnpacked->aMem[iIdx];
  78116. if( iIdx==p->pTab->iPKey ){
  78117. sqlite3VdbeMemSetInt64(pMem, p->iKey1);
  78118. }else if( iIdx>=p->pUnpacked->nField ){
  78119. *ppValue = (sqlite3_value *)columnNullValue();
  78120. }else if( p->pTab->aCol[iIdx].affinity==SQLITE_AFF_REAL ){
  78121. if( pMem->flags & (MEM_Int|MEM_IntReal) ){
  78122. testcase( pMem->flags & MEM_Int );
  78123. testcase( pMem->flags & MEM_IntReal );
  78124. sqlite3VdbeMemRealify(pMem);
  78125. }
  78126. }
  78127. preupdate_old_out:
  78128. sqlite3Error(db, rc);
  78129. return sqlite3ApiExit(db, rc);
  78130. }
  78131. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  78132. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  78133. /*
  78134. ** This function is called from within a pre-update callback to retrieve
  78135. ** the number of columns in the row being updated, deleted or inserted.
  78136. */
  78137. SQLITE_API int sqlite3_preupdate_count(sqlite3 *db){
  78138. PreUpdate *p = db->pPreUpdate;
  78139. return (p ? p->keyinfo.nKeyField : 0);
  78140. }
  78141. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  78142. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  78143. /*
  78144. ** This function is designed to be called from within a pre-update callback
  78145. ** only. It returns zero if the change that caused the callback was made
  78146. ** immediately by a user SQL statement. Or, if the change was made by a
  78147. ** trigger program, it returns the number of trigger programs currently
  78148. ** on the stack (1 for a top-level trigger, 2 for a trigger fired by a
  78149. ** top-level trigger etc.).
  78150. **
  78151. ** For the purposes of the previous paragraph, a foreign key CASCADE, SET NULL
  78152. ** or SET DEFAULT action is considered a trigger.
  78153. */
  78154. SQLITE_API int sqlite3_preupdate_depth(sqlite3 *db){
  78155. PreUpdate *p = db->pPreUpdate;
  78156. return (p ? p->v->nFrame : 0);
  78157. }
  78158. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  78159. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  78160. /*
  78161. ** This function is called from within a pre-update callback to retrieve
  78162. ** a field of the row currently being updated or inserted.
  78163. */
  78164. SQLITE_API int sqlite3_preupdate_new(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
  78165. PreUpdate *p = db->pPreUpdate;
  78166. int rc = SQLITE_OK;
  78167. Mem *pMem;
  78168. if( !p || p->op==SQLITE_DELETE ){
  78169. rc = SQLITE_MISUSE_BKPT;
  78170. goto preupdate_new_out;
  78171. }
  78172. if( p->pPk && p->op!=SQLITE_UPDATE ){
  78173. iIdx = sqlite3ColumnOfIndex(p->pPk, iIdx);
  78174. }
  78175. if( iIdx>=p->pCsr->nField || iIdx<0 ){
  78176. rc = SQLITE_RANGE;
  78177. goto preupdate_new_out;
  78178. }
  78179. if( p->op==SQLITE_INSERT ){
  78180. /* For an INSERT, memory cell p->iNewReg contains the serialized record
  78181. ** that is being inserted. Deserialize it. */
  78182. UnpackedRecord *pUnpack = p->pNewUnpacked;
  78183. if( !pUnpack ){
  78184. Mem *pData = &p->v->aMem[p->iNewReg];
  78185. rc = ExpandBlob(pData);
  78186. if( rc!=SQLITE_OK ) goto preupdate_new_out;
  78187. pUnpack = vdbeUnpackRecord(&p->keyinfo, pData->n, pData->z);
  78188. if( !pUnpack ){
  78189. rc = SQLITE_NOMEM;
  78190. goto preupdate_new_out;
  78191. }
  78192. p->pNewUnpacked = pUnpack;
  78193. }
  78194. pMem = &pUnpack->aMem[iIdx];
  78195. if( iIdx==p->pTab->iPKey ){
  78196. sqlite3VdbeMemSetInt64(pMem, p->iKey2);
  78197. }else if( iIdx>=pUnpack->nField ){
  78198. pMem = (sqlite3_value *)columnNullValue();
  78199. }
  78200. }else{
  78201. /* For an UPDATE, memory cell (p->iNewReg+1+iIdx) contains the required
  78202. ** value. Make a copy of the cell contents and return a pointer to it.
  78203. ** It is not safe to return a pointer to the memory cell itself as the
  78204. ** caller may modify the value text encoding.
  78205. */
  78206. assert( p->op==SQLITE_UPDATE );
  78207. if( !p->aNew ){
  78208. p->aNew = (Mem *)sqlite3DbMallocZero(db, sizeof(Mem) * p->pCsr->nField);
  78209. if( !p->aNew ){
  78210. rc = SQLITE_NOMEM;
  78211. goto preupdate_new_out;
  78212. }
  78213. }
  78214. assert( iIdx>=0 && iIdx<p->pCsr->nField );
  78215. pMem = &p->aNew[iIdx];
  78216. if( pMem->flags==0 ){
  78217. if( iIdx==p->pTab->iPKey ){
  78218. sqlite3VdbeMemSetInt64(pMem, p->iKey2);
  78219. }else{
  78220. rc = sqlite3VdbeMemCopy(pMem, &p->v->aMem[p->iNewReg+1+iIdx]);
  78221. if( rc!=SQLITE_OK ) goto preupdate_new_out;
  78222. }
  78223. }
  78224. }
  78225. *ppValue = pMem;
  78226. preupdate_new_out:
  78227. sqlite3Error(db, rc);
  78228. return sqlite3ApiExit(db, rc);
  78229. }
  78230. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  78231. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  78232. /*
  78233. ** Return status data for a single loop within query pStmt.
  78234. */
  78235. SQLITE_API int sqlite3_stmt_scanstatus(
  78236. sqlite3_stmt *pStmt, /* Prepared statement being queried */
  78237. int idx, /* Index of loop to report on */
  78238. int iScanStatusOp, /* Which metric to return */
  78239. void *pOut /* OUT: Write the answer here */
  78240. ){
  78241. Vdbe *p = (Vdbe*)pStmt;
  78242. ScanStatus *pScan;
  78243. if( idx<0 || idx>=p->nScan ) return 1;
  78244. pScan = &p->aScan[idx];
  78245. switch( iScanStatusOp ){
  78246. case SQLITE_SCANSTAT_NLOOP: {
  78247. *(sqlite3_int64*)pOut = p->anExec[pScan->addrLoop];
  78248. break;
  78249. }
  78250. case SQLITE_SCANSTAT_NVISIT: {
  78251. *(sqlite3_int64*)pOut = p->anExec[pScan->addrVisit];
  78252. break;
  78253. }
  78254. case SQLITE_SCANSTAT_EST: {
  78255. double r = 1.0;
  78256. LogEst x = pScan->nEst;
  78257. while( x<100 ){
  78258. x += 10;
  78259. r *= 0.5;
  78260. }
  78261. *(double*)pOut = r*sqlite3LogEstToInt(x);
  78262. break;
  78263. }
  78264. case SQLITE_SCANSTAT_NAME: {
  78265. *(const char**)pOut = pScan->zName;
  78266. break;
  78267. }
  78268. case SQLITE_SCANSTAT_EXPLAIN: {
  78269. if( pScan->addrExplain ){
  78270. *(const char**)pOut = p->aOp[ pScan->addrExplain ].p4.z;
  78271. }else{
  78272. *(const char**)pOut = 0;
  78273. }
  78274. break;
  78275. }
  78276. case SQLITE_SCANSTAT_SELECTID: {
  78277. if( pScan->addrExplain ){
  78278. *(int*)pOut = p->aOp[ pScan->addrExplain ].p1;
  78279. }else{
  78280. *(int*)pOut = -1;
  78281. }
  78282. break;
  78283. }
  78284. default: {
  78285. return 1;
  78286. }
  78287. }
  78288. return 0;
  78289. }
  78290. /*
  78291. ** Zero all counters associated with the sqlite3_stmt_scanstatus() data.
  78292. */
  78293. SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt *pStmt){
  78294. Vdbe *p = (Vdbe*)pStmt;
  78295. memset(p->anExec, 0, p->nOp * sizeof(i64));
  78296. }
  78297. #endif /* SQLITE_ENABLE_STMT_SCANSTATUS */
  78298. /************** End of vdbeapi.c *********************************************/
  78299. /************** Begin file vdbetrace.c ***************************************/
  78300. /*
  78301. ** 2009 November 25
  78302. **
  78303. ** The author disclaims copyright to this source code. In place of
  78304. ** a legal notice, here is a blessing:
  78305. **
  78306. ** May you do good and not evil.
  78307. ** May you find forgiveness for yourself and forgive others.
  78308. ** May you share freely, never taking more than you give.
  78309. **
  78310. *************************************************************************
  78311. **
  78312. ** This file contains code used to insert the values of host parameters
  78313. ** (aka "wildcards") into the SQL text output by sqlite3_trace().
  78314. **
  78315. ** The Vdbe parse-tree explainer is also found here.
  78316. */
  78317. /* #include "sqliteInt.h" */
  78318. /* #include "vdbeInt.h" */
  78319. #ifndef SQLITE_OMIT_TRACE
  78320. /*
  78321. ** zSql is a zero-terminated string of UTF-8 SQL text. Return the number of
  78322. ** bytes in this text up to but excluding the first character in
  78323. ** a host parameter. If the text contains no host parameters, return
  78324. ** the total number of bytes in the text.
  78325. */
  78326. static int findNextHostParameter(const char *zSql, int *pnToken){
  78327. int tokenType;
  78328. int nTotal = 0;
  78329. int n;
  78330. *pnToken = 0;
  78331. while( zSql[0] ){
  78332. n = sqlite3GetToken((u8*)zSql, &tokenType);
  78333. assert( n>0 && tokenType!=TK_ILLEGAL );
  78334. if( tokenType==TK_VARIABLE ){
  78335. *pnToken = n;
  78336. break;
  78337. }
  78338. nTotal += n;
  78339. zSql += n;
  78340. }
  78341. return nTotal;
  78342. }
  78343. /*
  78344. ** This function returns a pointer to a nul-terminated string in memory
  78345. ** obtained from sqlite3DbMalloc(). If sqlite3.nVdbeExec is 1, then the
  78346. ** string contains a copy of zRawSql but with host parameters expanded to
  78347. ** their current bindings. Or, if sqlite3.nVdbeExec is greater than 1,
  78348. ** then the returned string holds a copy of zRawSql with "-- " prepended
  78349. ** to each line of text.
  78350. **
  78351. ** If the SQLITE_TRACE_SIZE_LIMIT macro is defined to an integer, then
  78352. ** then long strings and blobs are truncated to that many bytes. This
  78353. ** can be used to prevent unreasonably large trace strings when dealing
  78354. ** with large (multi-megabyte) strings and blobs.
  78355. **
  78356. ** The calling function is responsible for making sure the memory returned
  78357. ** is eventually freed.
  78358. **
  78359. ** ALGORITHM: Scan the input string looking for host parameters in any of
  78360. ** these forms: ?, ?N, $A, @A, :A. Take care to avoid text within
  78361. ** string literals, quoted identifier names, and comments. For text forms,
  78362. ** the host parameter index is found by scanning the prepared
  78363. ** statement for the corresponding OP_Variable opcode. Once the host
  78364. ** parameter index is known, locate the value in p->aVar[]. Then render
  78365. ** the value as a literal in place of the host parameter name.
  78366. */
  78367. SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
  78368. Vdbe *p, /* The prepared statement being evaluated */
  78369. const char *zRawSql /* Raw text of the SQL statement */
  78370. ){
  78371. sqlite3 *db; /* The database connection */
  78372. int idx = 0; /* Index of a host parameter */
  78373. int nextIndex = 1; /* Index of next ? host parameter */
  78374. int n; /* Length of a token prefix */
  78375. int nToken; /* Length of the parameter token */
  78376. int i; /* Loop counter */
  78377. Mem *pVar; /* Value of a host parameter */
  78378. StrAccum out; /* Accumulate the output here */
  78379. #ifndef SQLITE_OMIT_UTF16
  78380. Mem utf8; /* Used to convert UTF16 into UTF8 for display */
  78381. #endif
  78382. char zBase[100]; /* Initial working space */
  78383. db = p->db;
  78384. sqlite3StrAccumInit(&out, 0, zBase, sizeof(zBase),
  78385. db->aLimit[SQLITE_LIMIT_LENGTH]);
  78386. if( db->nVdbeExec>1 ){
  78387. while( *zRawSql ){
  78388. const char *zStart = zRawSql;
  78389. while( *(zRawSql++)!='\n' && *zRawSql );
  78390. sqlite3_str_append(&out, "-- ", 3);
  78391. assert( (zRawSql - zStart) > 0 );
  78392. sqlite3_str_append(&out, zStart, (int)(zRawSql-zStart));
  78393. }
  78394. }else if( p->nVar==0 ){
  78395. sqlite3_str_append(&out, zRawSql, sqlite3Strlen30(zRawSql));
  78396. }else{
  78397. while( zRawSql[0] ){
  78398. n = findNextHostParameter(zRawSql, &nToken);
  78399. assert( n>0 );
  78400. sqlite3_str_append(&out, zRawSql, n);
  78401. zRawSql += n;
  78402. assert( zRawSql[0] || nToken==0 );
  78403. if( nToken==0 ) break;
  78404. if( zRawSql[0]=='?' ){
  78405. if( nToken>1 ){
  78406. assert( sqlite3Isdigit(zRawSql[1]) );
  78407. sqlite3GetInt32(&zRawSql[1], &idx);
  78408. }else{
  78409. idx = nextIndex;
  78410. }
  78411. }else{
  78412. assert( zRawSql[0]==':' || zRawSql[0]=='$' ||
  78413. zRawSql[0]=='@' || zRawSql[0]=='#' );
  78414. testcase( zRawSql[0]==':' );
  78415. testcase( zRawSql[0]=='$' );
  78416. testcase( zRawSql[0]=='@' );
  78417. testcase( zRawSql[0]=='#' );
  78418. idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
  78419. assert( idx>0 );
  78420. }
  78421. zRawSql += nToken;
  78422. nextIndex = idx + 1;
  78423. assert( idx>0 && idx<=p->nVar );
  78424. pVar = &p->aVar[idx-1];
  78425. if( pVar->flags & MEM_Null ){
  78426. sqlite3_str_append(&out, "NULL", 4);
  78427. }else if( pVar->flags & (MEM_Int|MEM_IntReal) ){
  78428. sqlite3_str_appendf(&out, "%lld", pVar->u.i);
  78429. }else if( pVar->flags & MEM_Real ){
  78430. sqlite3_str_appendf(&out, "%!.15g", pVar->u.r);
  78431. }else if( pVar->flags & MEM_Str ){
  78432. int nOut; /* Number of bytes of the string text to include in output */
  78433. #ifndef SQLITE_OMIT_UTF16
  78434. u8 enc = ENC(db);
  78435. if( enc!=SQLITE_UTF8 ){
  78436. memset(&utf8, 0, sizeof(utf8));
  78437. utf8.db = db;
  78438. sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
  78439. if( SQLITE_NOMEM==sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8) ){
  78440. out.accError = SQLITE_NOMEM;
  78441. out.nAlloc = 0;
  78442. }
  78443. pVar = &utf8;
  78444. }
  78445. #endif
  78446. nOut = pVar->n;
  78447. #ifdef SQLITE_TRACE_SIZE_LIMIT
  78448. if( nOut>SQLITE_TRACE_SIZE_LIMIT ){
  78449. nOut = SQLITE_TRACE_SIZE_LIMIT;
  78450. while( nOut<pVar->n && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; }
  78451. }
  78452. #endif
  78453. sqlite3_str_appendf(&out, "'%.*q'", nOut, pVar->z);
  78454. #ifdef SQLITE_TRACE_SIZE_LIMIT
  78455. if( nOut<pVar->n ){
  78456. sqlite3_str_appendf(&out, "/*+%d bytes*/", pVar->n-nOut);
  78457. }
  78458. #endif
  78459. #ifndef SQLITE_OMIT_UTF16
  78460. if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8);
  78461. #endif
  78462. }else if( pVar->flags & MEM_Zero ){
  78463. sqlite3_str_appendf(&out, "zeroblob(%d)", pVar->u.nZero);
  78464. }else{
  78465. int nOut; /* Number of bytes of the blob to include in output */
  78466. assert( pVar->flags & MEM_Blob );
  78467. sqlite3_str_append(&out, "x'", 2);
  78468. nOut = pVar->n;
  78469. #ifdef SQLITE_TRACE_SIZE_LIMIT
  78470. if( nOut>SQLITE_TRACE_SIZE_LIMIT ) nOut = SQLITE_TRACE_SIZE_LIMIT;
  78471. #endif
  78472. for(i=0; i<nOut; i++){
  78473. sqlite3_str_appendf(&out, "%02x", pVar->z[i]&0xff);
  78474. }
  78475. sqlite3_str_append(&out, "'", 1);
  78476. #ifdef SQLITE_TRACE_SIZE_LIMIT
  78477. if( nOut<pVar->n ){
  78478. sqlite3_str_appendf(&out, "/*+%d bytes*/", pVar->n-nOut);
  78479. }
  78480. #endif
  78481. }
  78482. }
  78483. }
  78484. if( out.accError ) sqlite3_str_reset(&out);
  78485. return sqlite3StrAccumFinish(&out);
  78486. }
  78487. #endif /* #ifndef SQLITE_OMIT_TRACE */
  78488. /************** End of vdbetrace.c *******************************************/
  78489. /************** Begin file vdbe.c ********************************************/
  78490. /*
  78491. ** 2001 September 15
  78492. **
  78493. ** The author disclaims copyright to this source code. In place of
  78494. ** a legal notice, here is a blessing:
  78495. **
  78496. ** May you do good and not evil.
  78497. ** May you find forgiveness for yourself and forgive others.
  78498. ** May you share freely, never taking more than you give.
  78499. **
  78500. *************************************************************************
  78501. ** The code in this file implements the function that runs the
  78502. ** bytecode of a prepared statement.
  78503. **
  78504. ** Various scripts scan this source file in order to generate HTML
  78505. ** documentation, headers files, or other derived files. The formatting
  78506. ** of the code in this file is, therefore, important. See other comments
  78507. ** in this file for details. If in doubt, do not deviate from existing
  78508. ** commenting and indentation practices when changing or adding code.
  78509. */
  78510. /* #include "sqliteInt.h" */
  78511. /* #include "vdbeInt.h" */
  78512. /*
  78513. ** Invoke this macro on memory cells just prior to changing the
  78514. ** value of the cell. This macro verifies that shallow copies are
  78515. ** not misused. A shallow copy of a string or blob just copies a
  78516. ** pointer to the string or blob, not the content. If the original
  78517. ** is changed while the copy is still in use, the string or blob might
  78518. ** be changed out from under the copy. This macro verifies that nothing
  78519. ** like that ever happens.
  78520. */
  78521. #ifdef SQLITE_DEBUG
  78522. # define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
  78523. #else
  78524. # define memAboutToChange(P,M)
  78525. #endif
  78526. /*
  78527. ** The following global variable is incremented every time a cursor
  78528. ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes. The test
  78529. ** procedures use this information to make sure that indices are
  78530. ** working correctly. This variable has no function other than to
  78531. ** help verify the correct operation of the library.
  78532. */
  78533. #ifdef SQLITE_TEST
  78534. SQLITE_API int sqlite3_search_count = 0;
  78535. #endif
  78536. /*
  78537. ** When this global variable is positive, it gets decremented once before
  78538. ** each instruction in the VDBE. When it reaches zero, the u1.isInterrupted
  78539. ** field of the sqlite3 structure is set in order to simulate an interrupt.
  78540. **
  78541. ** This facility is used for testing purposes only. It does not function
  78542. ** in an ordinary build.
  78543. */
  78544. #ifdef SQLITE_TEST
  78545. SQLITE_API int sqlite3_interrupt_count = 0;
  78546. #endif
  78547. /*
  78548. ** The next global variable is incremented each type the OP_Sort opcode
  78549. ** is executed. The test procedures use this information to make sure that
  78550. ** sorting is occurring or not occurring at appropriate times. This variable
  78551. ** has no function other than to help verify the correct operation of the
  78552. ** library.
  78553. */
  78554. #ifdef SQLITE_TEST
  78555. SQLITE_API int sqlite3_sort_count = 0;
  78556. #endif
  78557. /*
  78558. ** The next global variable records the size of the largest MEM_Blob
  78559. ** or MEM_Str that has been used by a VDBE opcode. The test procedures
  78560. ** use this information to make sure that the zero-blob functionality
  78561. ** is working correctly. This variable has no function other than to
  78562. ** help verify the correct operation of the library.
  78563. */
  78564. #ifdef SQLITE_TEST
  78565. SQLITE_API int sqlite3_max_blobsize = 0;
  78566. static void updateMaxBlobsize(Mem *p){
  78567. if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
  78568. sqlite3_max_blobsize = p->n;
  78569. }
  78570. }
  78571. #endif
  78572. /*
  78573. ** This macro evaluates to true if either the update hook or the preupdate
  78574. ** hook are enabled for database connect DB.
  78575. */
  78576. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  78577. # define HAS_UPDATE_HOOK(DB) ((DB)->xPreUpdateCallback||(DB)->xUpdateCallback)
  78578. #else
  78579. # define HAS_UPDATE_HOOK(DB) ((DB)->xUpdateCallback)
  78580. #endif
  78581. /*
  78582. ** The next global variable is incremented each time the OP_Found opcode
  78583. ** is executed. This is used to test whether or not the foreign key
  78584. ** operation implemented using OP_FkIsZero is working. This variable
  78585. ** has no function other than to help verify the correct operation of the
  78586. ** library.
  78587. */
  78588. #ifdef SQLITE_TEST
  78589. SQLITE_API int sqlite3_found_count = 0;
  78590. #endif
  78591. /*
  78592. ** Test a register to see if it exceeds the current maximum blob size.
  78593. ** If it does, record the new maximum blob size.
  78594. */
  78595. #if defined(SQLITE_TEST) && !defined(SQLITE_UNTESTABLE)
  78596. # define UPDATE_MAX_BLOBSIZE(P) updateMaxBlobsize(P)
  78597. #else
  78598. # define UPDATE_MAX_BLOBSIZE(P)
  78599. #endif
  78600. /*
  78601. ** Invoke the VDBE coverage callback, if that callback is defined. This
  78602. ** feature is used for test suite validation only and does not appear an
  78603. ** production builds.
  78604. **
  78605. ** M is the type of branch. I is the direction taken for this instance of
  78606. ** the branch.
  78607. **
  78608. ** M: 2 - two-way branch (I=0: fall-thru 1: jump )
  78609. ** 3 - two-way + NULL (I=0: fall-thru 1: jump 2: NULL )
  78610. ** 4 - OP_Jump (I=0: jump p1 1: jump p2 2: jump p3)
  78611. **
  78612. ** In other words, if M is 2, then I is either 0 (for fall-through) or
  78613. ** 1 (for when the branch is taken). If M is 3, the I is 0 for an
  78614. ** ordinary fall-through, I is 1 if the branch was taken, and I is 2
  78615. ** if the result of comparison is NULL. For M=3, I=2 the jump may or
  78616. ** may not be taken, depending on the SQLITE_JUMPIFNULL flags in p5.
  78617. ** When M is 4, that means that an OP_Jump is being run. I is 0, 1, or 2
  78618. ** depending on if the operands are less than, equal, or greater than.
  78619. **
  78620. ** iSrcLine is the source code line (from the __LINE__ macro) that
  78621. ** generated the VDBE instruction combined with flag bits. The source
  78622. ** code line number is in the lower 24 bits of iSrcLine and the upper
  78623. ** 8 bytes are flags. The lower three bits of the flags indicate
  78624. ** values for I that should never occur. For example, if the branch is
  78625. ** always taken, the flags should be 0x05 since the fall-through and
  78626. ** alternate branch are never taken. If a branch is never taken then
  78627. ** flags should be 0x06 since only the fall-through approach is allowed.
  78628. **
  78629. ** Bit 0x08 of the flags indicates an OP_Jump opcode that is only
  78630. ** interested in equal or not-equal. In other words, I==0 and I==2
  78631. ** should be treated as equivalent
  78632. **
  78633. ** Since only a line number is retained, not the filename, this macro
  78634. ** only works for amalgamation builds. But that is ok, since these macros
  78635. ** should be no-ops except for special builds used to measure test coverage.
  78636. */
  78637. #if !defined(SQLITE_VDBE_COVERAGE)
  78638. # define VdbeBranchTaken(I,M)
  78639. #else
  78640. # define VdbeBranchTaken(I,M) vdbeTakeBranch(pOp->iSrcLine,I,M)
  78641. static void vdbeTakeBranch(u32 iSrcLine, u8 I, u8 M){
  78642. u8 mNever;
  78643. assert( I<=2 ); /* 0: fall through, 1: taken, 2: alternate taken */
  78644. assert( M<=4 ); /* 2: two-way branch, 3: three-way branch, 4: OP_Jump */
  78645. assert( I<M ); /* I can only be 2 if M is 3 or 4 */
  78646. /* Transform I from a integer [0,1,2] into a bitmask of [1,2,4] */
  78647. I = 1<<I;
  78648. /* The upper 8 bits of iSrcLine are flags. The lower three bits of
  78649. ** the flags indicate directions that the branch can never go. If
  78650. ** a branch really does go in one of those directions, assert right
  78651. ** away. */
  78652. mNever = iSrcLine >> 24;
  78653. assert( (I & mNever)==0 );
  78654. if( sqlite3GlobalConfig.xVdbeBranch==0 ) return; /*NO_TEST*/
  78655. /* Invoke the branch coverage callback with three arguments:
  78656. ** iSrcLine - the line number of the VdbeCoverage() macro, with
  78657. ** flags removed.
  78658. ** I - Mask of bits 0x07 indicating which cases are are
  78659. ** fulfilled by this instance of the jump. 0x01 means
  78660. ** fall-thru, 0x02 means taken, 0x04 means NULL. Any
  78661. ** impossible cases (ex: if the comparison is never NULL)
  78662. ** are filled in automatically so that the coverage
  78663. ** measurement logic does not flag those impossible cases
  78664. ** as missed coverage.
  78665. ** M - Type of jump. Same as M argument above
  78666. */
  78667. I |= mNever;
  78668. if( M==2 ) I |= 0x04;
  78669. if( M==4 ){
  78670. I |= 0x08;
  78671. if( (mNever&0x08)!=0 && (I&0x05)!=0) I |= 0x05; /*NO_TEST*/
  78672. }
  78673. sqlite3GlobalConfig.xVdbeBranch(sqlite3GlobalConfig.pVdbeBranchArg,
  78674. iSrcLine&0xffffff, I, M);
  78675. }
  78676. #endif
  78677. /*
  78678. ** An ephemeral string value (signified by the MEM_Ephem flag) contains
  78679. ** a pointer to a dynamically allocated string where some other entity
  78680. ** is responsible for deallocating that string. Because the register
  78681. ** does not control the string, it might be deleted without the register
  78682. ** knowing it.
  78683. **
  78684. ** This routine converts an ephemeral string into a dynamically allocated
  78685. ** string that the register itself controls. In other words, it
  78686. ** converts an MEM_Ephem string into a string with P.z==P.zMalloc.
  78687. */
  78688. #define Deephemeralize(P) \
  78689. if( ((P)->flags&MEM_Ephem)!=0 \
  78690. && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
  78691. /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
  78692. #define isSorter(x) ((x)->eCurType==CURTYPE_SORTER)
  78693. /*
  78694. ** Allocate VdbeCursor number iCur. Return a pointer to it. Return NULL
  78695. ** if we run out of memory.
  78696. */
  78697. static VdbeCursor *allocateCursor(
  78698. Vdbe *p, /* The virtual machine */
  78699. int iCur, /* Index of the new VdbeCursor */
  78700. int nField, /* Number of fields in the table or index */
  78701. int iDb, /* Database the cursor belongs to, or -1 */
  78702. u8 eCurType /* Type of the new cursor */
  78703. ){
  78704. /* Find the memory cell that will be used to store the blob of memory
  78705. ** required for this VdbeCursor structure. It is convenient to use a
  78706. ** vdbe memory cell to manage the memory allocation required for a
  78707. ** VdbeCursor structure for the following reasons:
  78708. **
  78709. ** * Sometimes cursor numbers are used for a couple of different
  78710. ** purposes in a vdbe program. The different uses might require
  78711. ** different sized allocations. Memory cells provide growable
  78712. ** allocations.
  78713. **
  78714. ** * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
  78715. ** be freed lazily via the sqlite3_release_memory() API. This
  78716. ** minimizes the number of malloc calls made by the system.
  78717. **
  78718. ** The memory cell for cursor 0 is aMem[0]. The rest are allocated from
  78719. ** the top of the register space. Cursor 1 is at Mem[p->nMem-1].
  78720. ** Cursor 2 is at Mem[p->nMem-2]. And so forth.
  78721. */
  78722. Mem *pMem = iCur>0 ? &p->aMem[p->nMem-iCur] : p->aMem;
  78723. int nByte;
  78724. VdbeCursor *pCx = 0;
  78725. nByte =
  78726. ROUND8(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField +
  78727. (eCurType==CURTYPE_BTREE?sqlite3BtreeCursorSize():0);
  78728. assert( iCur>=0 && iCur<p->nCursor );
  78729. if( p->apCsr[iCur] ){ /*OPTIMIZATION-IF-FALSE*/
  78730. /* Before calling sqlite3VdbeFreeCursor(), ensure the isEphemeral flag
  78731. ** is clear. Otherwise, if this is an ephemeral cursor created by
  78732. ** OP_OpenDup, the cursor will not be closed and will still be part
  78733. ** of a BtShared.pCursor list. */
  78734. if( p->apCsr[iCur]->pBtx==0 ) p->apCsr[iCur]->isEphemeral = 0;
  78735. sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
  78736. p->apCsr[iCur] = 0;
  78737. }
  78738. if( SQLITE_OK==sqlite3VdbeMemClearAndResize(pMem, nByte) ){
  78739. p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
  78740. memset(pCx, 0, offsetof(VdbeCursor,pAltCursor));
  78741. pCx->eCurType = eCurType;
  78742. pCx->iDb = iDb;
  78743. pCx->nField = nField;
  78744. pCx->aOffset = &pCx->aType[nField];
  78745. if( eCurType==CURTYPE_BTREE ){
  78746. pCx->uc.pCursor = (BtCursor*)
  78747. &pMem->z[ROUND8(sizeof(VdbeCursor))+2*sizeof(u32)*nField];
  78748. sqlite3BtreeCursorZero(pCx->uc.pCursor);
  78749. }
  78750. }
  78751. return pCx;
  78752. }
  78753. /*
  78754. ** The string in pRec is known to look like an integer and to have a
  78755. ** floating point value of rValue. Return true and set *piValue to the
  78756. ** integer value if the string is in range to be an integer. Otherwise,
  78757. ** return false.
  78758. */
  78759. static int alsoAnInt(Mem *pRec, double rValue, i64 *piValue){
  78760. i64 iValue = (double)rValue;
  78761. if( sqlite3RealSameAsInt(rValue,iValue) ){
  78762. *piValue = iValue;
  78763. return 1;
  78764. }
  78765. return 0==sqlite3Atoi64(pRec->z, piValue, pRec->n, pRec->enc);
  78766. }
  78767. /*
  78768. ** Try to convert a value into a numeric representation if we can
  78769. ** do so without loss of information. In other words, if the string
  78770. ** looks like a number, convert it into a number. If it does not
  78771. ** look like a number, leave it alone.
  78772. **
  78773. ** If the bTryForInt flag is true, then extra effort is made to give
  78774. ** an integer representation. Strings that look like floating point
  78775. ** values but which have no fractional component (example: '48.00')
  78776. ** will have a MEM_Int representation when bTryForInt is true.
  78777. **
  78778. ** If bTryForInt is false, then if the input string contains a decimal
  78779. ** point or exponential notation, the result is only MEM_Real, even
  78780. ** if there is an exact integer representation of the quantity.
  78781. */
  78782. static void applyNumericAffinity(Mem *pRec, int bTryForInt){
  78783. double rValue;
  78784. u8 enc = pRec->enc;
  78785. int rc;
  78786. assert( (pRec->flags & (MEM_Str|MEM_Int|MEM_Real|MEM_IntReal))==MEM_Str );
  78787. rc = sqlite3AtoF(pRec->z, &rValue, pRec->n, enc);
  78788. if( rc<=0 ) return;
  78789. if( rc==1 && alsoAnInt(pRec, rValue, &pRec->u.i) ){
  78790. pRec->flags |= MEM_Int;
  78791. }else{
  78792. pRec->u.r = rValue;
  78793. pRec->flags |= MEM_Real;
  78794. if( bTryForInt ) sqlite3VdbeIntegerAffinity(pRec);
  78795. }
  78796. /* TEXT->NUMERIC is many->one. Hence, it is important to invalidate the
  78797. ** string representation after computing a numeric equivalent, because the
  78798. ** string representation might not be the canonical representation for the
  78799. ** numeric value. Ticket [343634942dd54ab57b7024] 2018-01-31. */
  78800. pRec->flags &= ~MEM_Str;
  78801. }
  78802. /*
  78803. ** Processing is determine by the affinity parameter:
  78804. **
  78805. ** SQLITE_AFF_INTEGER:
  78806. ** SQLITE_AFF_REAL:
  78807. ** SQLITE_AFF_NUMERIC:
  78808. ** Try to convert pRec to an integer representation or a
  78809. ** floating-point representation if an integer representation
  78810. ** is not possible. Note that the integer representation is
  78811. ** always preferred, even if the affinity is REAL, because
  78812. ** an integer representation is more space efficient on disk.
  78813. **
  78814. ** SQLITE_AFF_TEXT:
  78815. ** Convert pRec to a text representation.
  78816. **
  78817. ** SQLITE_AFF_BLOB:
  78818. ** No-op. pRec is unchanged.
  78819. */
  78820. static void applyAffinity(
  78821. Mem *pRec, /* The value to apply affinity to */
  78822. char affinity, /* The affinity to be applied */
  78823. u8 enc /* Use this text encoding */
  78824. ){
  78825. if( affinity>=SQLITE_AFF_NUMERIC ){
  78826. assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
  78827. || affinity==SQLITE_AFF_NUMERIC );
  78828. if( (pRec->flags & MEM_Int)==0 ){ /*OPTIMIZATION-IF-FALSE*/
  78829. if( (pRec->flags & MEM_Real)==0 ){
  78830. if( pRec->flags & MEM_Str ) applyNumericAffinity(pRec,1);
  78831. }else{
  78832. sqlite3VdbeIntegerAffinity(pRec);
  78833. }
  78834. }
  78835. }else if( affinity==SQLITE_AFF_TEXT ){
  78836. /* Only attempt the conversion to TEXT if there is an integer or real
  78837. ** representation (blob and NULL do not get converted) but no string
  78838. ** representation. It would be harmless to repeat the conversion if
  78839. ** there is already a string rep, but it is pointless to waste those
  78840. ** CPU cycles. */
  78841. if( 0==(pRec->flags&MEM_Str) ){ /*OPTIMIZATION-IF-FALSE*/
  78842. if( (pRec->flags&(MEM_Real|MEM_Int|MEM_IntReal)) ){
  78843. testcase( pRec->flags & MEM_Int );
  78844. testcase( pRec->flags & MEM_Real );
  78845. testcase( pRec->flags & MEM_IntReal );
  78846. sqlite3VdbeMemStringify(pRec, enc, 1);
  78847. }
  78848. }
  78849. pRec->flags &= ~(MEM_Real|MEM_Int|MEM_IntReal);
  78850. }
  78851. }
  78852. /*
  78853. ** Try to convert the type of a function argument or a result column
  78854. ** into a numeric representation. Use either INTEGER or REAL whichever
  78855. ** is appropriate. But only do the conversion if it is possible without
  78856. ** loss of information and return the revised type of the argument.
  78857. */
  78858. SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
  78859. int eType = sqlite3_value_type(pVal);
  78860. if( eType==SQLITE_TEXT ){
  78861. Mem *pMem = (Mem*)pVal;
  78862. applyNumericAffinity(pMem, 0);
  78863. eType = sqlite3_value_type(pVal);
  78864. }
  78865. return eType;
  78866. }
  78867. /*
  78868. ** Exported version of applyAffinity(). This one works on sqlite3_value*,
  78869. ** not the internal Mem* type.
  78870. */
  78871. SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
  78872. sqlite3_value *pVal,
  78873. u8 affinity,
  78874. u8 enc
  78875. ){
  78876. applyAffinity((Mem *)pVal, affinity, enc);
  78877. }
  78878. /*
  78879. ** pMem currently only holds a string type (or maybe a BLOB that we can
  78880. ** interpret as a string if we want to). Compute its corresponding
  78881. ** numeric type, if has one. Set the pMem->u.r and pMem->u.i fields
  78882. ** accordingly.
  78883. */
  78884. static u16 SQLITE_NOINLINE computeNumericType(Mem *pMem){
  78885. int rc;
  78886. sqlite3_int64 ix;
  78887. assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal))==0 );
  78888. assert( (pMem->flags & (MEM_Str|MEM_Blob))!=0 );
  78889. ExpandBlob(pMem);
  78890. rc = sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc);
  78891. if( rc<=0 ){
  78892. if( rc==0 && sqlite3Atoi64(pMem->z, &ix, pMem->n, pMem->enc)<=1 ){
  78893. pMem->u.i = ix;
  78894. return MEM_Int;
  78895. }else{
  78896. return MEM_Real;
  78897. }
  78898. }else if( rc==1 && sqlite3Atoi64(pMem->z, &ix, pMem->n, pMem->enc)==0 ){
  78899. pMem->u.i = ix;
  78900. return MEM_Int;
  78901. }
  78902. return MEM_Real;
  78903. }
  78904. /*
  78905. ** Return the numeric type for pMem, either MEM_Int or MEM_Real or both or
  78906. ** none.
  78907. **
  78908. ** Unlike applyNumericAffinity(), this routine does not modify pMem->flags.
  78909. ** But it does set pMem->u.r and pMem->u.i appropriately.
  78910. */
  78911. static u16 numericType(Mem *pMem){
  78912. if( pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal) ){
  78913. testcase( pMem->flags & MEM_Int );
  78914. testcase( pMem->flags & MEM_Real );
  78915. testcase( pMem->flags & MEM_IntReal );
  78916. return pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal);
  78917. }
  78918. if( pMem->flags & (MEM_Str|MEM_Blob) ){
  78919. testcase( pMem->flags & MEM_Str );
  78920. testcase( pMem->flags & MEM_Blob );
  78921. return computeNumericType(pMem);
  78922. }
  78923. return 0;
  78924. }
  78925. #ifdef SQLITE_DEBUG
  78926. /*
  78927. ** Write a nice string representation of the contents of cell pMem
  78928. ** into buffer zBuf, length nBuf.
  78929. */
  78930. SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
  78931. char *zCsr = zBuf;
  78932. int f = pMem->flags;
  78933. static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
  78934. if( f&MEM_Blob ){
  78935. int i;
  78936. char c;
  78937. if( f & MEM_Dyn ){
  78938. c = 'z';
  78939. assert( (f & (MEM_Static|MEM_Ephem))==0 );
  78940. }else if( f & MEM_Static ){
  78941. c = 't';
  78942. assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
  78943. }else if( f & MEM_Ephem ){
  78944. c = 'e';
  78945. assert( (f & (MEM_Static|MEM_Dyn))==0 );
  78946. }else{
  78947. c = 's';
  78948. }
  78949. *(zCsr++) = c;
  78950. sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
  78951. zCsr += sqlite3Strlen30(zCsr);
  78952. for(i=0; i<16 && i<pMem->n; i++){
  78953. sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
  78954. zCsr += sqlite3Strlen30(zCsr);
  78955. }
  78956. for(i=0; i<16 && i<pMem->n; i++){
  78957. char z = pMem->z[i];
  78958. if( z<32 || z>126 ) *zCsr++ = '.';
  78959. else *zCsr++ = z;
  78960. }
  78961. *(zCsr++) = ']';
  78962. if( f & MEM_Zero ){
  78963. sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
  78964. zCsr += sqlite3Strlen30(zCsr);
  78965. }
  78966. *zCsr = '\0';
  78967. }else if( f & MEM_Str ){
  78968. int j, k;
  78969. zBuf[0] = ' ';
  78970. if( f & MEM_Dyn ){
  78971. zBuf[1] = 'z';
  78972. assert( (f & (MEM_Static|MEM_Ephem))==0 );
  78973. }else if( f & MEM_Static ){
  78974. zBuf[1] = 't';
  78975. assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
  78976. }else if( f & MEM_Ephem ){
  78977. zBuf[1] = 'e';
  78978. assert( (f & (MEM_Static|MEM_Dyn))==0 );
  78979. }else{
  78980. zBuf[1] = 's';
  78981. }
  78982. k = 2;
  78983. sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
  78984. k += sqlite3Strlen30(&zBuf[k]);
  78985. zBuf[k++] = '[';
  78986. for(j=0; j<15 && j<pMem->n; j++){
  78987. u8 c = pMem->z[j];
  78988. if( c>=0x20 && c<0x7f ){
  78989. zBuf[k++] = c;
  78990. }else{
  78991. zBuf[k++] = '.';
  78992. }
  78993. }
  78994. zBuf[k++] = ']';
  78995. sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
  78996. k += sqlite3Strlen30(&zBuf[k]);
  78997. zBuf[k++] = 0;
  78998. }
  78999. }
  79000. #endif
  79001. #ifdef SQLITE_DEBUG
  79002. /*
  79003. ** Print the value of a register for tracing purposes:
  79004. */
  79005. static void memTracePrint(Mem *p){
  79006. if( p->flags & MEM_Undefined ){
  79007. printf(" undefined");
  79008. }else if( p->flags & MEM_Null ){
  79009. printf(p->flags & MEM_Zero ? " NULL-nochng" : " NULL");
  79010. }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
  79011. printf(" si:%lld", p->u.i);
  79012. }else if( (p->flags & (MEM_IntReal))!=0 ){
  79013. printf(" ir:%lld", p->u.i);
  79014. }else if( p->flags & MEM_Int ){
  79015. printf(" i:%lld", p->u.i);
  79016. #ifndef SQLITE_OMIT_FLOATING_POINT
  79017. }else if( p->flags & MEM_Real ){
  79018. printf(" r:%g", p->u.r);
  79019. #endif
  79020. }else if( sqlite3VdbeMemIsRowSet(p) ){
  79021. printf(" (rowset)");
  79022. }else{
  79023. char zBuf[200];
  79024. sqlite3VdbeMemPrettyPrint(p, zBuf);
  79025. printf(" %s", zBuf);
  79026. }
  79027. if( p->flags & MEM_Subtype ) printf(" subtype=0x%02x", p->eSubtype);
  79028. }
  79029. static void registerTrace(int iReg, Mem *p){
  79030. printf("REG[%d] = ", iReg);
  79031. memTracePrint(p);
  79032. printf("\n");
  79033. sqlite3VdbeCheckMemInvariants(p);
  79034. }
  79035. #endif
  79036. #ifdef SQLITE_DEBUG
  79037. # define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M)
  79038. #else
  79039. # define REGISTER_TRACE(R,M)
  79040. #endif
  79041. #ifdef VDBE_PROFILE
  79042. /*
  79043. ** hwtime.h contains inline assembler code for implementing
  79044. ** high-performance timing routines.
  79045. */
  79046. /************** Include hwtime.h in the middle of vdbe.c *********************/
  79047. /************** Begin file hwtime.h ******************************************/
  79048. /*
  79049. ** 2008 May 27
  79050. **
  79051. ** The author disclaims copyright to this source code. In place of
  79052. ** a legal notice, here is a blessing:
  79053. **
  79054. ** May you do good and not evil.
  79055. ** May you find forgiveness for yourself and forgive others.
  79056. ** May you share freely, never taking more than you give.
  79057. **
  79058. ******************************************************************************
  79059. **
  79060. ** This file contains inline asm code for retrieving "high-performance"
  79061. ** counters for x86 class CPUs.
  79062. */
  79063. #ifndef SQLITE_HWTIME_H
  79064. #define SQLITE_HWTIME_H
  79065. /*
  79066. ** The following routine only works on pentium-class (or newer) processors.
  79067. ** It uses the RDTSC opcode to read the cycle count value out of the
  79068. ** processor and returns that value. This can be used for high-res
  79069. ** profiling.
  79070. */
  79071. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  79072. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  79073. #if defined(__GNUC__)
  79074. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  79075. unsigned int lo, hi;
  79076. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  79077. return (sqlite_uint64)hi << 32 | lo;
  79078. }
  79079. #elif defined(_MSC_VER)
  79080. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  79081. __asm {
  79082. rdtsc
  79083. ret ; return value at EDX:EAX
  79084. }
  79085. }
  79086. #endif
  79087. #elif (defined(__GNUC__) && defined(__x86_64__))
  79088. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  79089. unsigned long val;
  79090. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  79091. return val;
  79092. }
  79093. #elif (defined(__GNUC__) && defined(__ppc__))
  79094. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  79095. unsigned long long retval;
  79096. unsigned long junk;
  79097. __asm__ __volatile__ ("\n\
  79098. 1: mftbu %1\n\
  79099. mftb %L0\n\
  79100. mftbu %0\n\
  79101. cmpw %0,%1\n\
  79102. bne 1b"
  79103. : "=r" (retval), "=r" (junk));
  79104. return retval;
  79105. }
  79106. #else
  79107. #error Need implementation of sqlite3Hwtime() for your platform.
  79108. /*
  79109. ** To compile without implementing sqlite3Hwtime() for your platform,
  79110. ** you can remove the above #error and use the following
  79111. ** stub function. You will lose timing support for many
  79112. ** of the debugging and testing utilities, but it should at
  79113. ** least compile and run.
  79114. */
  79115. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  79116. #endif
  79117. #endif /* !defined(SQLITE_HWTIME_H) */
  79118. /************** End of hwtime.h **********************************************/
  79119. /************** Continuing where we left off in vdbe.c ***********************/
  79120. #endif
  79121. #ifndef NDEBUG
  79122. /*
  79123. ** This function is only called from within an assert() expression. It
  79124. ** checks that the sqlite3.nTransaction variable is correctly set to
  79125. ** the number of non-transaction savepoints currently in the
  79126. ** linked list starting at sqlite3.pSavepoint.
  79127. **
  79128. ** Usage:
  79129. **
  79130. ** assert( checkSavepointCount(db) );
  79131. */
  79132. static int checkSavepointCount(sqlite3 *db){
  79133. int n = 0;
  79134. Savepoint *p;
  79135. for(p=db->pSavepoint; p; p=p->pNext) n++;
  79136. assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
  79137. return 1;
  79138. }
  79139. #endif
  79140. /*
  79141. ** Return the register of pOp->p2 after first preparing it to be
  79142. ** overwritten with an integer value.
  79143. */
  79144. static SQLITE_NOINLINE Mem *out2PrereleaseWithClear(Mem *pOut){
  79145. sqlite3VdbeMemSetNull(pOut);
  79146. pOut->flags = MEM_Int;
  79147. return pOut;
  79148. }
  79149. static Mem *out2Prerelease(Vdbe *p, VdbeOp *pOp){
  79150. Mem *pOut;
  79151. assert( pOp->p2>0 );
  79152. assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
  79153. pOut = &p->aMem[pOp->p2];
  79154. memAboutToChange(p, pOut);
  79155. if( VdbeMemDynamic(pOut) ){ /*OPTIMIZATION-IF-FALSE*/
  79156. return out2PrereleaseWithClear(pOut);
  79157. }else{
  79158. pOut->flags = MEM_Int;
  79159. return pOut;
  79160. }
  79161. }
  79162. /*
  79163. ** Execute as much of a VDBE program as we can.
  79164. ** This is the core of sqlite3_step().
  79165. */
  79166. SQLITE_PRIVATE int sqlite3VdbeExec(
  79167. Vdbe *p /* The VDBE */
  79168. ){
  79169. Op *aOp = p->aOp; /* Copy of p->aOp */
  79170. Op *pOp = aOp; /* Current operation */
  79171. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  79172. Op *pOrigOp; /* Value of pOp at the top of the loop */
  79173. #endif
  79174. #ifdef SQLITE_DEBUG
  79175. int nExtraDelete = 0; /* Verifies FORDELETE and AUXDELETE flags */
  79176. #endif
  79177. int rc = SQLITE_OK; /* Value to return */
  79178. sqlite3 *db = p->db; /* The database */
  79179. u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
  79180. u8 encoding = ENC(db); /* The database encoding */
  79181. int iCompare = 0; /* Result of last comparison */
  79182. unsigned nVmStep = 0; /* Number of virtual machine steps */
  79183. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  79184. unsigned nProgressLimit; /* Invoke xProgress() when nVmStep reaches this */
  79185. #endif
  79186. Mem *aMem = p->aMem; /* Copy of p->aMem */
  79187. Mem *pIn1 = 0; /* 1st input operand */
  79188. Mem *pIn2 = 0; /* 2nd input operand */
  79189. Mem *pIn3 = 0; /* 3rd input operand */
  79190. Mem *pOut = 0; /* Output operand */
  79191. #ifdef VDBE_PROFILE
  79192. u64 start; /* CPU clock count at start of opcode */
  79193. #endif
  79194. /*** INSERT STACK UNION HERE ***/
  79195. assert( p->magic==VDBE_MAGIC_RUN ); /* sqlite3_step() verifies this */
  79196. sqlite3VdbeEnter(p);
  79197. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  79198. if( db->xProgress ){
  79199. u32 iPrior = p->aCounter[SQLITE_STMTSTATUS_VM_STEP];
  79200. assert( 0 < db->nProgressOps );
  79201. nProgressLimit = db->nProgressOps - (iPrior % db->nProgressOps);
  79202. }else{
  79203. nProgressLimit = 0xffffffff;
  79204. }
  79205. #endif
  79206. if( p->rc==SQLITE_NOMEM ){
  79207. /* This happens if a malloc() inside a call to sqlite3_column_text() or
  79208. ** sqlite3_column_text16() failed. */
  79209. goto no_mem;
  79210. }
  79211. assert( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_BUSY );
  79212. assert( p->bIsReader || p->readOnly!=0 );
  79213. p->iCurrentTime = 0;
  79214. assert( p->explain==0 );
  79215. p->pResultSet = 0;
  79216. db->busyHandler.nBusy = 0;
  79217. if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
  79218. sqlite3VdbeIOTraceSql(p);
  79219. #ifdef SQLITE_DEBUG
  79220. sqlite3BeginBenignMalloc();
  79221. if( p->pc==0
  79222. && (p->db->flags & (SQLITE_VdbeListing|SQLITE_VdbeEQP|SQLITE_VdbeTrace))!=0
  79223. ){
  79224. int i;
  79225. int once = 1;
  79226. sqlite3VdbePrintSql(p);
  79227. if( p->db->flags & SQLITE_VdbeListing ){
  79228. printf("VDBE Program Listing:\n");
  79229. for(i=0; i<p->nOp; i++){
  79230. sqlite3VdbePrintOp(stdout, i, &aOp[i]);
  79231. }
  79232. }
  79233. if( p->db->flags & SQLITE_VdbeEQP ){
  79234. for(i=0; i<p->nOp; i++){
  79235. if( aOp[i].opcode==OP_Explain ){
  79236. if( once ) printf("VDBE Query Plan:\n");
  79237. printf("%s\n", aOp[i].p4.z);
  79238. once = 0;
  79239. }
  79240. }
  79241. }
  79242. if( p->db->flags & SQLITE_VdbeTrace ) printf("VDBE Trace:\n");
  79243. }
  79244. sqlite3EndBenignMalloc();
  79245. #endif
  79246. for(pOp=&aOp[p->pc]; 1; pOp++){
  79247. /* Errors are detected by individual opcodes, with an immediate
  79248. ** jumps to abort_due_to_error. */
  79249. assert( rc==SQLITE_OK );
  79250. assert( pOp>=aOp && pOp<&aOp[p->nOp]);
  79251. #ifdef VDBE_PROFILE
  79252. start = sqlite3NProfileCnt ? sqlite3NProfileCnt : sqlite3Hwtime();
  79253. #endif
  79254. nVmStep++;
  79255. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  79256. if( p->anExec ) p->anExec[(int)(pOp-aOp)]++;
  79257. #endif
  79258. /* Only allow tracing if SQLITE_DEBUG is defined.
  79259. */
  79260. #ifdef SQLITE_DEBUG
  79261. if( db->flags & SQLITE_VdbeTrace ){
  79262. sqlite3VdbePrintOp(stdout, (int)(pOp - aOp), pOp);
  79263. }
  79264. #endif
  79265. /* Check to see if we need to simulate an interrupt. This only happens
  79266. ** if we have a special test build.
  79267. */
  79268. #ifdef SQLITE_TEST
  79269. if( sqlite3_interrupt_count>0 ){
  79270. sqlite3_interrupt_count--;
  79271. if( sqlite3_interrupt_count==0 ){
  79272. sqlite3_interrupt(db);
  79273. }
  79274. }
  79275. #endif
  79276. /* Sanity checking on other operands */
  79277. #ifdef SQLITE_DEBUG
  79278. {
  79279. u8 opProperty = sqlite3OpcodeProperty[pOp->opcode];
  79280. if( (opProperty & OPFLG_IN1)!=0 ){
  79281. assert( pOp->p1>0 );
  79282. assert( pOp->p1<=(p->nMem+1 - p->nCursor) );
  79283. assert( memIsValid(&aMem[pOp->p1]) );
  79284. assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) );
  79285. REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
  79286. }
  79287. if( (opProperty & OPFLG_IN2)!=0 ){
  79288. assert( pOp->p2>0 );
  79289. assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
  79290. assert( memIsValid(&aMem[pOp->p2]) );
  79291. assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) );
  79292. REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
  79293. }
  79294. if( (opProperty & OPFLG_IN3)!=0 ){
  79295. assert( pOp->p3>0 );
  79296. assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
  79297. assert( memIsValid(&aMem[pOp->p3]) );
  79298. assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) );
  79299. REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
  79300. }
  79301. if( (opProperty & OPFLG_OUT2)!=0 ){
  79302. assert( pOp->p2>0 );
  79303. assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
  79304. memAboutToChange(p, &aMem[pOp->p2]);
  79305. }
  79306. if( (opProperty & OPFLG_OUT3)!=0 ){
  79307. assert( pOp->p3>0 );
  79308. assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
  79309. memAboutToChange(p, &aMem[pOp->p3]);
  79310. }
  79311. }
  79312. #endif
  79313. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  79314. pOrigOp = pOp;
  79315. #endif
  79316. switch( pOp->opcode ){
  79317. /*****************************************************************************
  79318. ** What follows is a massive switch statement where each case implements a
  79319. ** separate instruction in the virtual machine. If we follow the usual
  79320. ** indentation conventions, each case should be indented by 6 spaces. But
  79321. ** that is a lot of wasted space on the left margin. So the code within
  79322. ** the switch statement will break with convention and be flush-left. Another
  79323. ** big comment (similar to this one) will mark the point in the code where
  79324. ** we transition back to normal indentation.
  79325. **
  79326. ** The formatting of each case is important. The makefile for SQLite
  79327. ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
  79328. ** file looking for lines that begin with "case OP_". The opcodes.h files
  79329. ** will be filled with #defines that give unique integer values to each
  79330. ** opcode and the opcodes.c file is filled with an array of strings where
  79331. ** each string is the symbolic name for the corresponding opcode. If the
  79332. ** case statement is followed by a comment of the form "/# same as ... #/"
  79333. ** that comment is used to determine the particular value of the opcode.
  79334. **
  79335. ** Other keywords in the comment that follows each case are used to
  79336. ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
  79337. ** Keywords include: in1, in2, in3, out2, out3. See
  79338. ** the mkopcodeh.awk script for additional information.
  79339. **
  79340. ** Documentation about VDBE opcodes is generated by scanning this file
  79341. ** for lines of that contain "Opcode:". That line and all subsequent
  79342. ** comment lines are used in the generation of the opcode.html documentation
  79343. ** file.
  79344. **
  79345. ** SUMMARY:
  79346. **
  79347. ** Formatting is important to scripts that scan this file.
  79348. ** Do not deviate from the formatting style currently in use.
  79349. **
  79350. *****************************************************************************/
  79351. /* Opcode: Goto * P2 * * *
  79352. **
  79353. ** An unconditional jump to address P2.
  79354. ** The next instruction executed will be
  79355. ** the one at index P2 from the beginning of
  79356. ** the program.
  79357. **
  79358. ** The P1 parameter is not actually used by this opcode. However, it
  79359. ** is sometimes set to 1 instead of 0 as a hint to the command-line shell
  79360. ** that this Goto is the bottom of a loop and that the lines from P2 down
  79361. ** to the current line should be indented for EXPLAIN output.
  79362. */
  79363. case OP_Goto: { /* jump */
  79364. jump_to_p2_and_check_for_interrupt:
  79365. pOp = &aOp[pOp->p2 - 1];
  79366. /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev,
  79367. ** OP_VNext, or OP_SorterNext) all jump here upon
  79368. ** completion. Check to see if sqlite3_interrupt() has been called
  79369. ** or if the progress callback needs to be invoked.
  79370. **
  79371. ** This code uses unstructured "goto" statements and does not look clean.
  79372. ** But that is not due to sloppy coding habits. The code is written this
  79373. ** way for performance, to avoid having to run the interrupt and progress
  79374. ** checks on every opcode. This helps sqlite3_step() to run about 1.5%
  79375. ** faster according to "valgrind --tool=cachegrind" */
  79376. check_for_interrupt:
  79377. if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
  79378. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  79379. /* Call the progress callback if it is configured and the required number
  79380. ** of VDBE ops have been executed (either since this invocation of
  79381. ** sqlite3VdbeExec() or since last time the progress callback was called).
  79382. ** If the progress callback returns non-zero, exit the virtual machine with
  79383. ** a return code SQLITE_ABORT.
  79384. */
  79385. while( nVmStep>=nProgressLimit && db->xProgress!=0 ){
  79386. assert( db->nProgressOps!=0 );
  79387. nProgressLimit += db->nProgressOps;
  79388. if( db->xProgress(db->pProgressArg) ){
  79389. nProgressLimit = 0xffffffff;
  79390. rc = SQLITE_INTERRUPT;
  79391. goto abort_due_to_error;
  79392. }
  79393. }
  79394. #endif
  79395. break;
  79396. }
  79397. /* Opcode: Gosub P1 P2 * * *
  79398. **
  79399. ** Write the current address onto register P1
  79400. ** and then jump to address P2.
  79401. */
  79402. case OP_Gosub: { /* jump */
  79403. assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
  79404. pIn1 = &aMem[pOp->p1];
  79405. assert( VdbeMemDynamic(pIn1)==0 );
  79406. memAboutToChange(p, pIn1);
  79407. pIn1->flags = MEM_Int;
  79408. pIn1->u.i = (int)(pOp-aOp);
  79409. REGISTER_TRACE(pOp->p1, pIn1);
  79410. /* Most jump operations do a goto to this spot in order to update
  79411. ** the pOp pointer. */
  79412. jump_to_p2:
  79413. pOp = &aOp[pOp->p2 - 1];
  79414. break;
  79415. }
  79416. /* Opcode: Return P1 * * * *
  79417. **
  79418. ** Jump to the next instruction after the address in register P1. After
  79419. ** the jump, register P1 becomes undefined.
  79420. */
  79421. case OP_Return: { /* in1 */
  79422. pIn1 = &aMem[pOp->p1];
  79423. assert( pIn1->flags==MEM_Int );
  79424. pOp = &aOp[pIn1->u.i];
  79425. pIn1->flags = MEM_Undefined;
  79426. break;
  79427. }
  79428. /* Opcode: InitCoroutine P1 P2 P3 * *
  79429. **
  79430. ** Set up register P1 so that it will Yield to the coroutine
  79431. ** located at address P3.
  79432. **
  79433. ** If P2!=0 then the coroutine implementation immediately follows
  79434. ** this opcode. So jump over the coroutine implementation to
  79435. ** address P2.
  79436. **
  79437. ** See also: EndCoroutine
  79438. */
  79439. case OP_InitCoroutine: { /* jump */
  79440. assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
  79441. assert( pOp->p2>=0 && pOp->p2<p->nOp );
  79442. assert( pOp->p3>=0 && pOp->p3<p->nOp );
  79443. pOut = &aMem[pOp->p1];
  79444. assert( !VdbeMemDynamic(pOut) );
  79445. pOut->u.i = pOp->p3 - 1;
  79446. pOut->flags = MEM_Int;
  79447. if( pOp->p2 ) goto jump_to_p2;
  79448. break;
  79449. }
  79450. /* Opcode: EndCoroutine P1 * * * *
  79451. **
  79452. ** The instruction at the address in register P1 is a Yield.
  79453. ** Jump to the P2 parameter of that Yield.
  79454. ** After the jump, register P1 becomes undefined.
  79455. **
  79456. ** See also: InitCoroutine
  79457. */
  79458. case OP_EndCoroutine: { /* in1 */
  79459. VdbeOp *pCaller;
  79460. pIn1 = &aMem[pOp->p1];
  79461. assert( pIn1->flags==MEM_Int );
  79462. assert( pIn1->u.i>=0 && pIn1->u.i<p->nOp );
  79463. pCaller = &aOp[pIn1->u.i];
  79464. assert( pCaller->opcode==OP_Yield );
  79465. assert( pCaller->p2>=0 && pCaller->p2<p->nOp );
  79466. pOp = &aOp[pCaller->p2 - 1];
  79467. pIn1->flags = MEM_Undefined;
  79468. break;
  79469. }
  79470. /* Opcode: Yield P1 P2 * * *
  79471. **
  79472. ** Swap the program counter with the value in register P1. This
  79473. ** has the effect of yielding to a coroutine.
  79474. **
  79475. ** If the coroutine that is launched by this instruction ends with
  79476. ** Yield or Return then continue to the next instruction. But if
  79477. ** the coroutine launched by this instruction ends with
  79478. ** EndCoroutine, then jump to P2 rather than continuing with the
  79479. ** next instruction.
  79480. **
  79481. ** See also: InitCoroutine
  79482. */
  79483. case OP_Yield: { /* in1, jump */
  79484. int pcDest;
  79485. pIn1 = &aMem[pOp->p1];
  79486. assert( VdbeMemDynamic(pIn1)==0 );
  79487. pIn1->flags = MEM_Int;
  79488. pcDest = (int)pIn1->u.i;
  79489. pIn1->u.i = (int)(pOp - aOp);
  79490. REGISTER_TRACE(pOp->p1, pIn1);
  79491. pOp = &aOp[pcDest];
  79492. break;
  79493. }
  79494. /* Opcode: HaltIfNull P1 P2 P3 P4 P5
  79495. ** Synopsis: if r[P3]=null halt
  79496. **
  79497. ** Check the value in register P3. If it is NULL then Halt using
  79498. ** parameter P1, P2, and P4 as if this were a Halt instruction. If the
  79499. ** value in register P3 is not NULL, then this routine is a no-op.
  79500. ** The P5 parameter should be 1.
  79501. */
  79502. case OP_HaltIfNull: { /* in3 */
  79503. pIn3 = &aMem[pOp->p3];
  79504. #ifdef SQLITE_DEBUG
  79505. if( pOp->p2==OE_Abort ){ sqlite3VdbeAssertAbortable(p); }
  79506. #endif
  79507. if( (pIn3->flags & MEM_Null)==0 ) break;
  79508. /* Fall through into OP_Halt */
  79509. }
  79510. /* Opcode: Halt P1 P2 * P4 P5
  79511. **
  79512. ** Exit immediately. All open cursors, etc are closed
  79513. ** automatically.
  79514. **
  79515. ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
  79516. ** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0).
  79517. ** For errors, it can be some other value. If P1!=0 then P2 will determine
  79518. ** whether or not to rollback the current transaction. Do not rollback
  79519. ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort,
  79520. ** then back out all changes that have occurred during this execution of the
  79521. ** VDBE, but do not rollback the transaction.
  79522. **
  79523. ** If P4 is not null then it is an error message string.
  79524. **
  79525. ** P5 is a value between 0 and 4, inclusive, that modifies the P4 string.
  79526. **
  79527. ** 0: (no change)
  79528. ** 1: NOT NULL contraint failed: P4
  79529. ** 2: UNIQUE constraint failed: P4
  79530. ** 3: CHECK constraint failed: P4
  79531. ** 4: FOREIGN KEY constraint failed: P4
  79532. **
  79533. ** If P5 is not zero and P4 is NULL, then everything after the ":" is
  79534. ** omitted.
  79535. **
  79536. ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
  79537. ** every program. So a jump past the last instruction of the program
  79538. ** is the same as executing Halt.
  79539. */
  79540. case OP_Halt: {
  79541. VdbeFrame *pFrame;
  79542. int pcx;
  79543. pcx = (int)(pOp - aOp);
  79544. #ifdef SQLITE_DEBUG
  79545. if( pOp->p2==OE_Abort ){ sqlite3VdbeAssertAbortable(p); }
  79546. #endif
  79547. if( pOp->p1==SQLITE_OK && p->pFrame ){
  79548. /* Halt the sub-program. Return control to the parent frame. */
  79549. pFrame = p->pFrame;
  79550. p->pFrame = pFrame->pParent;
  79551. p->nFrame--;
  79552. sqlite3VdbeSetChanges(db, p->nChange);
  79553. pcx = sqlite3VdbeFrameRestore(pFrame);
  79554. if( pOp->p2==OE_Ignore ){
  79555. /* Instruction pcx is the OP_Program that invoked the sub-program
  79556. ** currently being halted. If the p2 instruction of this OP_Halt
  79557. ** instruction is set to OE_Ignore, then the sub-program is throwing
  79558. ** an IGNORE exception. In this case jump to the address specified
  79559. ** as the p2 of the calling OP_Program. */
  79560. pcx = p->aOp[pcx].p2-1;
  79561. }
  79562. aOp = p->aOp;
  79563. aMem = p->aMem;
  79564. pOp = &aOp[pcx];
  79565. break;
  79566. }
  79567. p->rc = pOp->p1;
  79568. p->errorAction = (u8)pOp->p2;
  79569. p->pc = pcx;
  79570. assert( pOp->p5<=4 );
  79571. if( p->rc ){
  79572. if( pOp->p5 ){
  79573. static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK",
  79574. "FOREIGN KEY" };
  79575. testcase( pOp->p5==1 );
  79576. testcase( pOp->p5==2 );
  79577. testcase( pOp->p5==3 );
  79578. testcase( pOp->p5==4 );
  79579. sqlite3VdbeError(p, "%s constraint failed", azType[pOp->p5-1]);
  79580. if( pOp->p4.z ){
  79581. p->zErrMsg = sqlite3MPrintf(db, "%z: %s", p->zErrMsg, pOp->p4.z);
  79582. }
  79583. }else{
  79584. sqlite3VdbeError(p, "%s", pOp->p4.z);
  79585. }
  79586. sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pcx, p->zSql, p->zErrMsg);
  79587. }
  79588. rc = sqlite3VdbeHalt(p);
  79589. assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
  79590. if( rc==SQLITE_BUSY ){
  79591. p->rc = SQLITE_BUSY;
  79592. }else{
  79593. assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
  79594. assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
  79595. rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
  79596. }
  79597. goto vdbe_return;
  79598. }
  79599. /* Opcode: Integer P1 P2 * * *
  79600. ** Synopsis: r[P2]=P1
  79601. **
  79602. ** The 32-bit integer value P1 is written into register P2.
  79603. */
  79604. case OP_Integer: { /* out2 */
  79605. pOut = out2Prerelease(p, pOp);
  79606. pOut->u.i = pOp->p1;
  79607. break;
  79608. }
  79609. /* Opcode: Int64 * P2 * P4 *
  79610. ** Synopsis: r[P2]=P4
  79611. **
  79612. ** P4 is a pointer to a 64-bit integer value.
  79613. ** Write that value into register P2.
  79614. */
  79615. case OP_Int64: { /* out2 */
  79616. pOut = out2Prerelease(p, pOp);
  79617. assert( pOp->p4.pI64!=0 );
  79618. pOut->u.i = *pOp->p4.pI64;
  79619. break;
  79620. }
  79621. #ifndef SQLITE_OMIT_FLOATING_POINT
  79622. /* Opcode: Real * P2 * P4 *
  79623. ** Synopsis: r[P2]=P4
  79624. **
  79625. ** P4 is a pointer to a 64-bit floating point value.
  79626. ** Write that value into register P2.
  79627. */
  79628. case OP_Real: { /* same as TK_FLOAT, out2 */
  79629. pOut = out2Prerelease(p, pOp);
  79630. pOut->flags = MEM_Real;
  79631. assert( !sqlite3IsNaN(*pOp->p4.pReal) );
  79632. pOut->u.r = *pOp->p4.pReal;
  79633. break;
  79634. }
  79635. #endif
  79636. /* Opcode: String8 * P2 * P4 *
  79637. ** Synopsis: r[P2]='P4'
  79638. **
  79639. ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
  79640. ** into a String opcode before it is executed for the first time. During
  79641. ** this transformation, the length of string P4 is computed and stored
  79642. ** as the P1 parameter.
  79643. */
  79644. case OP_String8: { /* same as TK_STRING, out2 */
  79645. assert( pOp->p4.z!=0 );
  79646. pOut = out2Prerelease(p, pOp);
  79647. pOp->opcode = OP_String;
  79648. pOp->p1 = sqlite3Strlen30(pOp->p4.z);
  79649. #ifndef SQLITE_OMIT_UTF16
  79650. if( encoding!=SQLITE_UTF8 ){
  79651. rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
  79652. assert( rc==SQLITE_OK || rc==SQLITE_TOOBIG );
  79653. if( rc ) goto too_big;
  79654. if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
  79655. assert( pOut->szMalloc>0 && pOut->zMalloc==pOut->z );
  79656. assert( VdbeMemDynamic(pOut)==0 );
  79657. pOut->szMalloc = 0;
  79658. pOut->flags |= MEM_Static;
  79659. if( pOp->p4type==P4_DYNAMIC ){
  79660. sqlite3DbFree(db, pOp->p4.z);
  79661. }
  79662. pOp->p4type = P4_DYNAMIC;
  79663. pOp->p4.z = pOut->z;
  79664. pOp->p1 = pOut->n;
  79665. }
  79666. #endif
  79667. if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  79668. goto too_big;
  79669. }
  79670. assert( rc==SQLITE_OK );
  79671. /* Fall through to the next case, OP_String */
  79672. }
  79673. /* Opcode: String P1 P2 P3 P4 P5
  79674. ** Synopsis: r[P2]='P4' (len=P1)
  79675. **
  79676. ** The string value P4 of length P1 (bytes) is stored in register P2.
  79677. **
  79678. ** If P3 is not zero and the content of register P3 is equal to P5, then
  79679. ** the datatype of the register P2 is converted to BLOB. The content is
  79680. ** the same sequence of bytes, it is merely interpreted as a BLOB instead
  79681. ** of a string, as if it had been CAST. In other words:
  79682. **
  79683. ** if( P3!=0 and reg[P3]==P5 ) reg[P2] := CAST(reg[P2] as BLOB)
  79684. */
  79685. case OP_String: { /* out2 */
  79686. assert( pOp->p4.z!=0 );
  79687. pOut = out2Prerelease(p, pOp);
  79688. pOut->flags = MEM_Str|MEM_Static|MEM_Term;
  79689. pOut->z = pOp->p4.z;
  79690. pOut->n = pOp->p1;
  79691. pOut->enc = encoding;
  79692. UPDATE_MAX_BLOBSIZE(pOut);
  79693. #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  79694. if( pOp->p3>0 ){
  79695. assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
  79696. pIn3 = &aMem[pOp->p3];
  79697. assert( pIn3->flags & MEM_Int );
  79698. if( pIn3->u.i==pOp->p5 ) pOut->flags = MEM_Blob|MEM_Static|MEM_Term;
  79699. }
  79700. #endif
  79701. break;
  79702. }
  79703. /* Opcode: Null P1 P2 P3 * *
  79704. ** Synopsis: r[P2..P3]=NULL
  79705. **
  79706. ** Write a NULL into registers P2. If P3 greater than P2, then also write
  79707. ** NULL into register P3 and every register in between P2 and P3. If P3
  79708. ** is less than P2 (typically P3 is zero) then only register P2 is
  79709. ** set to NULL.
  79710. **
  79711. ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
  79712. ** NULL values will not compare equal even if SQLITE_NULLEQ is set on
  79713. ** OP_Ne or OP_Eq.
  79714. */
  79715. case OP_Null: { /* out2 */
  79716. int cnt;
  79717. u16 nullFlag;
  79718. pOut = out2Prerelease(p, pOp);
  79719. cnt = pOp->p3-pOp->p2;
  79720. assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
  79721. pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
  79722. pOut->n = 0;
  79723. #ifdef SQLITE_DEBUG
  79724. pOut->uTemp = 0;
  79725. #endif
  79726. while( cnt>0 ){
  79727. pOut++;
  79728. memAboutToChange(p, pOut);
  79729. sqlite3VdbeMemSetNull(pOut);
  79730. pOut->flags = nullFlag;
  79731. pOut->n = 0;
  79732. cnt--;
  79733. }
  79734. break;
  79735. }
  79736. /* Opcode: SoftNull P1 * * * *
  79737. ** Synopsis: r[P1]=NULL
  79738. **
  79739. ** Set register P1 to have the value NULL as seen by the OP_MakeRecord
  79740. ** instruction, but do not free any string or blob memory associated with
  79741. ** the register, so that if the value was a string or blob that was
  79742. ** previously copied using OP_SCopy, the copies will continue to be valid.
  79743. */
  79744. case OP_SoftNull: {
  79745. assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
  79746. pOut = &aMem[pOp->p1];
  79747. pOut->flags = (pOut->flags&~(MEM_Undefined|MEM_AffMask))|MEM_Null;
  79748. break;
  79749. }
  79750. /* Opcode: Blob P1 P2 * P4 *
  79751. ** Synopsis: r[P2]=P4 (len=P1)
  79752. **
  79753. ** P4 points to a blob of data P1 bytes long. Store this
  79754. ** blob in register P2.
  79755. */
  79756. case OP_Blob: { /* out2 */
  79757. assert( pOp->p1 <= SQLITE_MAX_LENGTH );
  79758. pOut = out2Prerelease(p, pOp);
  79759. sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
  79760. pOut->enc = encoding;
  79761. UPDATE_MAX_BLOBSIZE(pOut);
  79762. break;
  79763. }
  79764. /* Opcode: Variable P1 P2 * P4 *
  79765. ** Synopsis: r[P2]=parameter(P1,P4)
  79766. **
  79767. ** Transfer the values of bound parameter P1 into register P2
  79768. **
  79769. ** If the parameter is named, then its name appears in P4.
  79770. ** The P4 value is used by sqlite3_bind_parameter_name().
  79771. */
  79772. case OP_Variable: { /* out2 */
  79773. Mem *pVar; /* Value being transferred */
  79774. assert( pOp->p1>0 && pOp->p1<=p->nVar );
  79775. assert( pOp->p4.z==0 || pOp->p4.z==sqlite3VListNumToName(p->pVList,pOp->p1) );
  79776. pVar = &p->aVar[pOp->p1 - 1];
  79777. if( sqlite3VdbeMemTooBig(pVar) ){
  79778. goto too_big;
  79779. }
  79780. pOut = &aMem[pOp->p2];
  79781. if( VdbeMemDynamic(pOut) ) sqlite3VdbeMemSetNull(pOut);
  79782. memcpy(pOut, pVar, MEMCELLSIZE);
  79783. pOut->flags &= ~(MEM_Dyn|MEM_Ephem);
  79784. pOut->flags |= MEM_Static|MEM_FromBind;
  79785. UPDATE_MAX_BLOBSIZE(pOut);
  79786. break;
  79787. }
  79788. /* Opcode: Move P1 P2 P3 * *
  79789. ** Synopsis: r[P2@P3]=r[P1@P3]
  79790. **
  79791. ** Move the P3 values in register P1..P1+P3-1 over into
  79792. ** registers P2..P2+P3-1. Registers P1..P1+P3-1 are
  79793. ** left holding a NULL. It is an error for register ranges
  79794. ** P1..P1+P3-1 and P2..P2+P3-1 to overlap. It is an error
  79795. ** for P3 to be less than 1.
  79796. */
  79797. case OP_Move: {
  79798. int n; /* Number of registers left to copy */
  79799. int p1; /* Register to copy from */
  79800. int p2; /* Register to copy to */
  79801. n = pOp->p3;
  79802. p1 = pOp->p1;
  79803. p2 = pOp->p2;
  79804. assert( n>0 && p1>0 && p2>0 );
  79805. assert( p1+n<=p2 || p2+n<=p1 );
  79806. pIn1 = &aMem[p1];
  79807. pOut = &aMem[p2];
  79808. do{
  79809. assert( pOut<=&aMem[(p->nMem+1 - p->nCursor)] );
  79810. assert( pIn1<=&aMem[(p->nMem+1 - p->nCursor)] );
  79811. assert( memIsValid(pIn1) );
  79812. memAboutToChange(p, pOut);
  79813. sqlite3VdbeMemMove(pOut, pIn1);
  79814. #ifdef SQLITE_DEBUG
  79815. if( pOut->pScopyFrom>=&aMem[p1] && pOut->pScopyFrom<pOut ){
  79816. pOut->pScopyFrom += pOp->p2 - p1;
  79817. }
  79818. #endif
  79819. Deephemeralize(pOut);
  79820. REGISTER_TRACE(p2++, pOut);
  79821. pIn1++;
  79822. pOut++;
  79823. }while( --n );
  79824. break;
  79825. }
  79826. /* Opcode: Copy P1 P2 P3 * *
  79827. ** Synopsis: r[P2@P3+1]=r[P1@P3+1]
  79828. **
  79829. ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
  79830. **
  79831. ** This instruction makes a deep copy of the value. A duplicate
  79832. ** is made of any string or blob constant. See also OP_SCopy.
  79833. */
  79834. case OP_Copy: {
  79835. int n;
  79836. n = pOp->p3;
  79837. pIn1 = &aMem[pOp->p1];
  79838. pOut = &aMem[pOp->p2];
  79839. assert( pOut!=pIn1 );
  79840. while( 1 ){
  79841. memAboutToChange(p, pOut);
  79842. sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
  79843. Deephemeralize(pOut);
  79844. #ifdef SQLITE_DEBUG
  79845. pOut->pScopyFrom = 0;
  79846. #endif
  79847. REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut);
  79848. if( (n--)==0 ) break;
  79849. pOut++;
  79850. pIn1++;
  79851. }
  79852. break;
  79853. }
  79854. /* Opcode: SCopy P1 P2 * * *
  79855. ** Synopsis: r[P2]=r[P1]
  79856. **
  79857. ** Make a shallow copy of register P1 into register P2.
  79858. **
  79859. ** This instruction makes a shallow copy of the value. If the value
  79860. ** is a string or blob, then the copy is only a pointer to the
  79861. ** original and hence if the original changes so will the copy.
  79862. ** Worse, if the original is deallocated, the copy becomes invalid.
  79863. ** Thus the program must guarantee that the original will not change
  79864. ** during the lifetime of the copy. Use OP_Copy to make a complete
  79865. ** copy.
  79866. */
  79867. case OP_SCopy: { /* out2 */
  79868. pIn1 = &aMem[pOp->p1];
  79869. pOut = &aMem[pOp->p2];
  79870. assert( pOut!=pIn1 );
  79871. sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
  79872. #ifdef SQLITE_DEBUG
  79873. pOut->pScopyFrom = pIn1;
  79874. pOut->mScopyFlags = pIn1->flags;
  79875. #endif
  79876. break;
  79877. }
  79878. /* Opcode: IntCopy P1 P2 * * *
  79879. ** Synopsis: r[P2]=r[P1]
  79880. **
  79881. ** Transfer the integer value held in register P1 into register P2.
  79882. **
  79883. ** This is an optimized version of SCopy that works only for integer
  79884. ** values.
  79885. */
  79886. case OP_IntCopy: { /* out2 */
  79887. pIn1 = &aMem[pOp->p1];
  79888. assert( (pIn1->flags & MEM_Int)!=0 );
  79889. pOut = &aMem[pOp->p2];
  79890. sqlite3VdbeMemSetInt64(pOut, pIn1->u.i);
  79891. break;
  79892. }
  79893. /* Opcode: ResultRow P1 P2 * * *
  79894. ** Synopsis: output=r[P1@P2]
  79895. **
  79896. ** The registers P1 through P1+P2-1 contain a single row of
  79897. ** results. This opcode causes the sqlite3_step() call to terminate
  79898. ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
  79899. ** structure to provide access to the r(P1)..r(P1+P2-1) values as
  79900. ** the result row.
  79901. */
  79902. case OP_ResultRow: {
  79903. Mem *pMem;
  79904. int i;
  79905. assert( p->nResColumn==pOp->p2 );
  79906. assert( pOp->p1>0 );
  79907. assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 );
  79908. /* If this statement has violated immediate foreign key constraints, do
  79909. ** not return the number of rows modified. And do not RELEASE the statement
  79910. ** transaction. It needs to be rolled back. */
  79911. if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
  79912. assert( db->flags&SQLITE_CountRows );
  79913. assert( p->usesStmtJournal );
  79914. goto abort_due_to_error;
  79915. }
  79916. /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
  79917. ** DML statements invoke this opcode to return the number of rows
  79918. ** modified to the user. This is the only way that a VM that
  79919. ** opens a statement transaction may invoke this opcode.
  79920. **
  79921. ** In case this is such a statement, close any statement transaction
  79922. ** opened by this VM before returning control to the user. This is to
  79923. ** ensure that statement-transactions are always nested, not overlapping.
  79924. ** If the open statement-transaction is not closed here, then the user
  79925. ** may step another VM that opens its own statement transaction. This
  79926. ** may lead to overlapping statement transactions.
  79927. **
  79928. ** The statement transaction is never a top-level transaction. Hence
  79929. ** the RELEASE call below can never fail.
  79930. */
  79931. assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
  79932. rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
  79933. assert( rc==SQLITE_OK );
  79934. /* Invalidate all ephemeral cursor row caches */
  79935. p->cacheCtr = (p->cacheCtr + 2)|1;
  79936. /* Make sure the results of the current row are \000 terminated
  79937. ** and have an assigned type. The results are de-ephemeralized as
  79938. ** a side effect.
  79939. */
  79940. pMem = p->pResultSet = &aMem[pOp->p1];
  79941. for(i=0; i<pOp->p2; i++){
  79942. assert( memIsValid(&pMem[i]) );
  79943. Deephemeralize(&pMem[i]);
  79944. assert( (pMem[i].flags & MEM_Ephem)==0
  79945. || (pMem[i].flags & (MEM_Str|MEM_Blob))==0 );
  79946. sqlite3VdbeMemNulTerminate(&pMem[i]);
  79947. REGISTER_TRACE(pOp->p1+i, &pMem[i]);
  79948. }
  79949. if( db->mallocFailed ) goto no_mem;
  79950. if( db->mTrace & SQLITE_TRACE_ROW ){
  79951. db->xTrace(SQLITE_TRACE_ROW, db->pTraceArg, p, 0);
  79952. }
  79953. /* Return SQLITE_ROW
  79954. */
  79955. p->pc = (int)(pOp - aOp) + 1;
  79956. rc = SQLITE_ROW;
  79957. goto vdbe_return;
  79958. }
  79959. /* Opcode: Concat P1 P2 P3 * *
  79960. ** Synopsis: r[P3]=r[P2]+r[P1]
  79961. **
  79962. ** Add the text in register P1 onto the end of the text in
  79963. ** register P2 and store the result in register P3.
  79964. ** If either the P1 or P2 text are NULL then store NULL in P3.
  79965. **
  79966. ** P3 = P2 || P1
  79967. **
  79968. ** It is illegal for P1 and P3 to be the same register. Sometimes,
  79969. ** if P3 is the same register as P2, the implementation is able
  79970. ** to avoid a memcpy().
  79971. */
  79972. case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */
  79973. i64 nByte; /* Total size of the output string or blob */
  79974. u16 flags1; /* Initial flags for P1 */
  79975. u16 flags2; /* Initial flags for P2 */
  79976. pIn1 = &aMem[pOp->p1];
  79977. pIn2 = &aMem[pOp->p2];
  79978. pOut = &aMem[pOp->p3];
  79979. testcase( pIn1==pIn2 );
  79980. testcase( pOut==pIn2 );
  79981. assert( pIn1!=pOut );
  79982. flags1 = pIn1->flags;
  79983. testcase( flags1 & MEM_Null );
  79984. testcase( pIn2->flags & MEM_Null );
  79985. if( (flags1 | pIn2->flags) & MEM_Null ){
  79986. sqlite3VdbeMemSetNull(pOut);
  79987. break;
  79988. }
  79989. if( (flags1 & (MEM_Str|MEM_Blob))==0 ){
  79990. if( sqlite3VdbeMemStringify(pIn1,encoding,0) ) goto no_mem;
  79991. flags1 = pIn1->flags & ~MEM_Str;
  79992. }else if( (flags1 & MEM_Zero)!=0 ){
  79993. if( sqlite3VdbeMemExpandBlob(pIn1) ) goto no_mem;
  79994. flags1 = pIn1->flags & ~MEM_Str;
  79995. }
  79996. flags2 = pIn2->flags;
  79997. if( (flags2 & (MEM_Str|MEM_Blob))==0 ){
  79998. if( sqlite3VdbeMemStringify(pIn2,encoding,0) ) goto no_mem;
  79999. flags2 = pIn2->flags & ~MEM_Str;
  80000. }else if( (flags2 & MEM_Zero)!=0 ){
  80001. if( sqlite3VdbeMemExpandBlob(pIn2) ) goto no_mem;
  80002. flags2 = pIn2->flags & ~MEM_Str;
  80003. }
  80004. nByte = pIn1->n + pIn2->n;
  80005. if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  80006. goto too_big;
  80007. }
  80008. if( sqlite3VdbeMemGrow(pOut, (int)nByte+3, pOut==pIn2) ){
  80009. goto no_mem;
  80010. }
  80011. MemSetTypeFlag(pOut, MEM_Str);
  80012. if( pOut!=pIn2 ){
  80013. memcpy(pOut->z, pIn2->z, pIn2->n);
  80014. assert( (pIn2->flags & MEM_Dyn) == (flags2 & MEM_Dyn) );
  80015. pIn2->flags = flags2;
  80016. }
  80017. memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
  80018. assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) );
  80019. pIn1->flags = flags1;
  80020. pOut->z[nByte]=0;
  80021. pOut->z[nByte+1] = 0;
  80022. pOut->z[nByte+2] = 0;
  80023. pOut->flags |= MEM_Term;
  80024. pOut->n = (int)nByte;
  80025. pOut->enc = encoding;
  80026. UPDATE_MAX_BLOBSIZE(pOut);
  80027. break;
  80028. }
  80029. /* Opcode: Add P1 P2 P3 * *
  80030. ** Synopsis: r[P3]=r[P1]+r[P2]
  80031. **
  80032. ** Add the value in register P1 to the value in register P2
  80033. ** and store the result in register P3.
  80034. ** If either input is NULL, the result is NULL.
  80035. */
  80036. /* Opcode: Multiply P1 P2 P3 * *
  80037. ** Synopsis: r[P3]=r[P1]*r[P2]
  80038. **
  80039. **
  80040. ** Multiply the value in register P1 by the value in register P2
  80041. ** and store the result in register P3.
  80042. ** If either input is NULL, the result is NULL.
  80043. */
  80044. /* Opcode: Subtract P1 P2 P3 * *
  80045. ** Synopsis: r[P3]=r[P2]-r[P1]
  80046. **
  80047. ** Subtract the value in register P1 from the value in register P2
  80048. ** and store the result in register P3.
  80049. ** If either input is NULL, the result is NULL.
  80050. */
  80051. /* Opcode: Divide P1 P2 P3 * *
  80052. ** Synopsis: r[P3]=r[P2]/r[P1]
  80053. **
  80054. ** Divide the value in register P1 by the value in register P2
  80055. ** and store the result in register P3 (P3=P2/P1). If the value in
  80056. ** register P1 is zero, then the result is NULL. If either input is
  80057. ** NULL, the result is NULL.
  80058. */
  80059. /* Opcode: Remainder P1 P2 P3 * *
  80060. ** Synopsis: r[P3]=r[P2]%r[P1]
  80061. **
  80062. ** Compute the remainder after integer register P2 is divided by
  80063. ** register P1 and store the result in register P3.
  80064. ** If the value in register P1 is zero the result is NULL.
  80065. ** If either operand is NULL, the result is NULL.
  80066. */
  80067. case OP_Add: /* same as TK_PLUS, in1, in2, out3 */
  80068. case OP_Subtract: /* same as TK_MINUS, in1, in2, out3 */
  80069. case OP_Multiply: /* same as TK_STAR, in1, in2, out3 */
  80070. case OP_Divide: /* same as TK_SLASH, in1, in2, out3 */
  80071. case OP_Remainder: { /* same as TK_REM, in1, in2, out3 */
  80072. u16 flags; /* Combined MEM_* flags from both inputs */
  80073. u16 type1; /* Numeric type of left operand */
  80074. u16 type2; /* Numeric type of right operand */
  80075. i64 iA; /* Integer value of left operand */
  80076. i64 iB; /* Integer value of right operand */
  80077. double rA; /* Real value of left operand */
  80078. double rB; /* Real value of right operand */
  80079. pIn1 = &aMem[pOp->p1];
  80080. type1 = numericType(pIn1);
  80081. pIn2 = &aMem[pOp->p2];
  80082. type2 = numericType(pIn2);
  80083. pOut = &aMem[pOp->p3];
  80084. flags = pIn1->flags | pIn2->flags;
  80085. if( (type1 & type2 & MEM_Int)!=0 ){
  80086. iA = pIn1->u.i;
  80087. iB = pIn2->u.i;
  80088. switch( pOp->opcode ){
  80089. case OP_Add: if( sqlite3AddInt64(&iB,iA) ) goto fp_math; break;
  80090. case OP_Subtract: if( sqlite3SubInt64(&iB,iA) ) goto fp_math; break;
  80091. case OP_Multiply: if( sqlite3MulInt64(&iB,iA) ) goto fp_math; break;
  80092. case OP_Divide: {
  80093. if( iA==0 ) goto arithmetic_result_is_null;
  80094. if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math;
  80095. iB /= iA;
  80096. break;
  80097. }
  80098. default: {
  80099. if( iA==0 ) goto arithmetic_result_is_null;
  80100. if( iA==-1 ) iA = 1;
  80101. iB %= iA;
  80102. break;
  80103. }
  80104. }
  80105. pOut->u.i = iB;
  80106. MemSetTypeFlag(pOut, MEM_Int);
  80107. }else if( (flags & MEM_Null)!=0 ){
  80108. goto arithmetic_result_is_null;
  80109. }else{
  80110. fp_math:
  80111. rA = sqlite3VdbeRealValue(pIn1);
  80112. rB = sqlite3VdbeRealValue(pIn2);
  80113. switch( pOp->opcode ){
  80114. case OP_Add: rB += rA; break;
  80115. case OP_Subtract: rB -= rA; break;
  80116. case OP_Multiply: rB *= rA; break;
  80117. case OP_Divide: {
  80118. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  80119. if( rA==(double)0 ) goto arithmetic_result_is_null;
  80120. rB /= rA;
  80121. break;
  80122. }
  80123. default: {
  80124. iA = sqlite3VdbeIntValue(pIn1);
  80125. iB = sqlite3VdbeIntValue(pIn2);
  80126. if( iA==0 ) goto arithmetic_result_is_null;
  80127. if( iA==-1 ) iA = 1;
  80128. rB = (double)(iB % iA);
  80129. break;
  80130. }
  80131. }
  80132. #ifdef SQLITE_OMIT_FLOATING_POINT
  80133. pOut->u.i = rB;
  80134. MemSetTypeFlag(pOut, MEM_Int);
  80135. #else
  80136. if( sqlite3IsNaN(rB) ){
  80137. goto arithmetic_result_is_null;
  80138. }
  80139. pOut->u.r = rB;
  80140. MemSetTypeFlag(pOut, MEM_Real);
  80141. #endif
  80142. }
  80143. break;
  80144. arithmetic_result_is_null:
  80145. sqlite3VdbeMemSetNull(pOut);
  80146. break;
  80147. }
  80148. /* Opcode: CollSeq P1 * * P4
  80149. **
  80150. ** P4 is a pointer to a CollSeq object. If the next call to a user function
  80151. ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
  80152. ** be returned. This is used by the built-in min(), max() and nullif()
  80153. ** functions.
  80154. **
  80155. ** If P1 is not zero, then it is a register that a subsequent min() or
  80156. ** max() aggregate will set to 1 if the current row is not the minimum or
  80157. ** maximum. The P1 register is initialized to 0 by this instruction.
  80158. **
  80159. ** The interface used by the implementation of the aforementioned functions
  80160. ** to retrieve the collation sequence set by this opcode is not available
  80161. ** publicly. Only built-in functions have access to this feature.
  80162. */
  80163. case OP_CollSeq: {
  80164. assert( pOp->p4type==P4_COLLSEQ );
  80165. if( pOp->p1 ){
  80166. sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
  80167. }
  80168. break;
  80169. }
  80170. /* Opcode: BitAnd P1 P2 P3 * *
  80171. ** Synopsis: r[P3]=r[P1]&r[P2]
  80172. **
  80173. ** Take the bit-wise AND of the values in register P1 and P2 and
  80174. ** store the result in register P3.
  80175. ** If either input is NULL, the result is NULL.
  80176. */
  80177. /* Opcode: BitOr P1 P2 P3 * *
  80178. ** Synopsis: r[P3]=r[P1]|r[P2]
  80179. **
  80180. ** Take the bit-wise OR of the values in register P1 and P2 and
  80181. ** store the result in register P3.
  80182. ** If either input is NULL, the result is NULL.
  80183. */
  80184. /* Opcode: ShiftLeft P1 P2 P3 * *
  80185. ** Synopsis: r[P3]=r[P2]<<r[P1]
  80186. **
  80187. ** Shift the integer value in register P2 to the left by the
  80188. ** number of bits specified by the integer in register P1.
  80189. ** Store the result in register P3.
  80190. ** If either input is NULL, the result is NULL.
  80191. */
  80192. /* Opcode: ShiftRight P1 P2 P3 * *
  80193. ** Synopsis: r[P3]=r[P2]>>r[P1]
  80194. **
  80195. ** Shift the integer value in register P2 to the right by the
  80196. ** number of bits specified by the integer in register P1.
  80197. ** Store the result in register P3.
  80198. ** If either input is NULL, the result is NULL.
  80199. */
  80200. case OP_BitAnd: /* same as TK_BITAND, in1, in2, out3 */
  80201. case OP_BitOr: /* same as TK_BITOR, in1, in2, out3 */
  80202. case OP_ShiftLeft: /* same as TK_LSHIFT, in1, in2, out3 */
  80203. case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */
  80204. i64 iA;
  80205. u64 uA;
  80206. i64 iB;
  80207. u8 op;
  80208. pIn1 = &aMem[pOp->p1];
  80209. pIn2 = &aMem[pOp->p2];
  80210. pOut = &aMem[pOp->p3];
  80211. if( (pIn1->flags | pIn2->flags) & MEM_Null ){
  80212. sqlite3VdbeMemSetNull(pOut);
  80213. break;
  80214. }
  80215. iA = sqlite3VdbeIntValue(pIn2);
  80216. iB = sqlite3VdbeIntValue(pIn1);
  80217. op = pOp->opcode;
  80218. if( op==OP_BitAnd ){
  80219. iA &= iB;
  80220. }else if( op==OP_BitOr ){
  80221. iA |= iB;
  80222. }else if( iB!=0 ){
  80223. assert( op==OP_ShiftRight || op==OP_ShiftLeft );
  80224. /* If shifting by a negative amount, shift in the other direction */
  80225. if( iB<0 ){
  80226. assert( OP_ShiftRight==OP_ShiftLeft+1 );
  80227. op = 2*OP_ShiftLeft + 1 - op;
  80228. iB = iB>(-64) ? -iB : 64;
  80229. }
  80230. if( iB>=64 ){
  80231. iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1;
  80232. }else{
  80233. memcpy(&uA, &iA, sizeof(uA));
  80234. if( op==OP_ShiftLeft ){
  80235. uA <<= iB;
  80236. }else{
  80237. uA >>= iB;
  80238. /* Sign-extend on a right shift of a negative number */
  80239. if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB);
  80240. }
  80241. memcpy(&iA, &uA, sizeof(iA));
  80242. }
  80243. }
  80244. pOut->u.i = iA;
  80245. MemSetTypeFlag(pOut, MEM_Int);
  80246. break;
  80247. }
  80248. /* Opcode: AddImm P1 P2 * * *
  80249. ** Synopsis: r[P1]=r[P1]+P2
  80250. **
  80251. ** Add the constant P2 to the value in register P1.
  80252. ** The result is always an integer.
  80253. **
  80254. ** To force any register to be an integer, just add 0.
  80255. */
  80256. case OP_AddImm: { /* in1 */
  80257. pIn1 = &aMem[pOp->p1];
  80258. memAboutToChange(p, pIn1);
  80259. sqlite3VdbeMemIntegerify(pIn1);
  80260. pIn1->u.i += pOp->p2;
  80261. break;
  80262. }
  80263. /* Opcode: MustBeInt P1 P2 * * *
  80264. **
  80265. ** Force the value in register P1 to be an integer. If the value
  80266. ** in P1 is not an integer and cannot be converted into an integer
  80267. ** without data loss, then jump immediately to P2, or if P2==0
  80268. ** raise an SQLITE_MISMATCH exception.
  80269. */
  80270. case OP_MustBeInt: { /* jump, in1 */
  80271. pIn1 = &aMem[pOp->p1];
  80272. if( (pIn1->flags & MEM_Int)==0 ){
  80273. applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
  80274. if( (pIn1->flags & MEM_Int)==0 ){
  80275. VdbeBranchTaken(1, 2);
  80276. if( pOp->p2==0 ){
  80277. rc = SQLITE_MISMATCH;
  80278. goto abort_due_to_error;
  80279. }else{
  80280. goto jump_to_p2;
  80281. }
  80282. }
  80283. }
  80284. VdbeBranchTaken(0, 2);
  80285. MemSetTypeFlag(pIn1, MEM_Int);
  80286. break;
  80287. }
  80288. #ifndef SQLITE_OMIT_FLOATING_POINT
  80289. /* Opcode: RealAffinity P1 * * * *
  80290. **
  80291. ** If register P1 holds an integer convert it to a real value.
  80292. **
  80293. ** This opcode is used when extracting information from a column that
  80294. ** has REAL affinity. Such column values may still be stored as
  80295. ** integers, for space efficiency, but after extraction we want them
  80296. ** to have only a real value.
  80297. */
  80298. case OP_RealAffinity: { /* in1 */
  80299. pIn1 = &aMem[pOp->p1];
  80300. if( pIn1->flags & (MEM_Int|MEM_IntReal) ){
  80301. testcase( pIn1->flags & MEM_Int );
  80302. testcase( pIn1->flags & MEM_IntReal );
  80303. sqlite3VdbeMemRealify(pIn1);
  80304. }
  80305. break;
  80306. }
  80307. #endif
  80308. #ifndef SQLITE_OMIT_CAST
  80309. /* Opcode: Cast P1 P2 * * *
  80310. ** Synopsis: affinity(r[P1])
  80311. **
  80312. ** Force the value in register P1 to be the type defined by P2.
  80313. **
  80314. ** <ul>
  80315. ** <li> P2=='A' &rarr; BLOB
  80316. ** <li> P2=='B' &rarr; TEXT
  80317. ** <li> P2=='C' &rarr; NUMERIC
  80318. ** <li> P2=='D' &rarr; INTEGER
  80319. ** <li> P2=='E' &rarr; REAL
  80320. ** </ul>
  80321. **
  80322. ** A NULL value is not changed by this routine. It remains NULL.
  80323. */
  80324. case OP_Cast: { /* in1 */
  80325. assert( pOp->p2>=SQLITE_AFF_BLOB && pOp->p2<=SQLITE_AFF_REAL );
  80326. testcase( pOp->p2==SQLITE_AFF_TEXT );
  80327. testcase( pOp->p2==SQLITE_AFF_BLOB );
  80328. testcase( pOp->p2==SQLITE_AFF_NUMERIC );
  80329. testcase( pOp->p2==SQLITE_AFF_INTEGER );
  80330. testcase( pOp->p2==SQLITE_AFF_REAL );
  80331. pIn1 = &aMem[pOp->p1];
  80332. memAboutToChange(p, pIn1);
  80333. rc = ExpandBlob(pIn1);
  80334. sqlite3VdbeMemCast(pIn1, pOp->p2, encoding);
  80335. UPDATE_MAX_BLOBSIZE(pIn1);
  80336. if( rc ) goto abort_due_to_error;
  80337. break;
  80338. }
  80339. #endif /* SQLITE_OMIT_CAST */
  80340. /* Opcode: Eq P1 P2 P3 P4 P5
  80341. ** Synopsis: IF r[P3]==r[P1]
  80342. **
  80343. ** Compare the values in register P1 and P3. If reg(P3)==reg(P1) then
  80344. ** jump to address P2. Or if the SQLITE_STOREP2 flag is set in P5, then
  80345. ** store the result of comparison in register P2.
  80346. **
  80347. ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
  80348. ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
  80349. ** to coerce both inputs according to this affinity before the
  80350. ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
  80351. ** affinity is used. Note that the affinity conversions are stored
  80352. ** back into the input registers P1 and P3. So this opcode can cause
  80353. ** persistent changes to registers P1 and P3.
  80354. **
  80355. ** Once any conversions have taken place, and neither value is NULL,
  80356. ** the values are compared. If both values are blobs then memcmp() is
  80357. ** used to determine the results of the comparison. If both values
  80358. ** are text, then the appropriate collating function specified in
  80359. ** P4 is used to do the comparison. If P4 is not specified then
  80360. ** memcmp() is used to compare text string. If both values are
  80361. ** numeric, then a numeric comparison is used. If the two values
  80362. ** are of different types, then numbers are considered less than
  80363. ** strings and strings are considered less than blobs.
  80364. **
  80365. ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
  80366. ** true or false and is never NULL. If both operands are NULL then the result
  80367. ** of comparison is true. If either operand is NULL then the result is false.
  80368. ** If neither operand is NULL the result is the same as it would be if
  80369. ** the SQLITE_NULLEQ flag were omitted from P5.
  80370. **
  80371. ** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the
  80372. ** content of r[P2] is only changed if the new value is NULL or 0 (false).
  80373. ** In other words, a prior r[P2] value will not be overwritten by 1 (true).
  80374. */
  80375. /* Opcode: Ne P1 P2 P3 P4 P5
  80376. ** Synopsis: IF r[P3]!=r[P1]
  80377. **
  80378. ** This works just like the Eq opcode except that the jump is taken if
  80379. ** the operands in registers P1 and P3 are not equal. See the Eq opcode for
  80380. ** additional information.
  80381. **
  80382. ** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the
  80383. ** content of r[P2] is only changed if the new value is NULL or 1 (true).
  80384. ** In other words, a prior r[P2] value will not be overwritten by 0 (false).
  80385. */
  80386. /* Opcode: Lt P1 P2 P3 P4 P5
  80387. ** Synopsis: IF r[P3]<r[P1]
  80388. **
  80389. ** Compare the values in register P1 and P3. If reg(P3)<reg(P1) then
  80390. ** jump to address P2. Or if the SQLITE_STOREP2 flag is set in P5 store
  80391. ** the result of comparison (0 or 1 or NULL) into register P2.
  80392. **
  80393. ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
  80394. ** reg(P3) is NULL then the take the jump. If the SQLITE_JUMPIFNULL
  80395. ** bit is clear then fall through if either operand is NULL.
  80396. **
  80397. ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
  80398. ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
  80399. ** to coerce both inputs according to this affinity before the
  80400. ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
  80401. ** affinity is used. Note that the affinity conversions are stored
  80402. ** back into the input registers P1 and P3. So this opcode can cause
  80403. ** persistent changes to registers P1 and P3.
  80404. **
  80405. ** Once any conversions have taken place, and neither value is NULL,
  80406. ** the values are compared. If both values are blobs then memcmp() is
  80407. ** used to determine the results of the comparison. If both values
  80408. ** are text, then the appropriate collating function specified in
  80409. ** P4 is used to do the comparison. If P4 is not specified then
  80410. ** memcmp() is used to compare text string. If both values are
  80411. ** numeric, then a numeric comparison is used. If the two values
  80412. ** are of different types, then numbers are considered less than
  80413. ** strings and strings are considered less than blobs.
  80414. */
  80415. /* Opcode: Le P1 P2 P3 P4 P5
  80416. ** Synopsis: IF r[P3]<=r[P1]
  80417. **
  80418. ** This works just like the Lt opcode except that the jump is taken if
  80419. ** the content of register P3 is less than or equal to the content of
  80420. ** register P1. See the Lt opcode for additional information.
  80421. */
  80422. /* Opcode: Gt P1 P2 P3 P4 P5
  80423. ** Synopsis: IF r[P3]>r[P1]
  80424. **
  80425. ** This works just like the Lt opcode except that the jump is taken if
  80426. ** the content of register P3 is greater than the content of
  80427. ** register P1. See the Lt opcode for additional information.
  80428. */
  80429. /* Opcode: Ge P1 P2 P3 P4 P5
  80430. ** Synopsis: IF r[P3]>=r[P1]
  80431. **
  80432. ** This works just like the Lt opcode except that the jump is taken if
  80433. ** the content of register P3 is greater than or equal to the content of
  80434. ** register P1. See the Lt opcode for additional information.
  80435. */
  80436. case OP_Eq: /* same as TK_EQ, jump, in1, in3 */
  80437. case OP_Ne: /* same as TK_NE, jump, in1, in3 */
  80438. case OP_Lt: /* same as TK_LT, jump, in1, in3 */
  80439. case OP_Le: /* same as TK_LE, jump, in1, in3 */
  80440. case OP_Gt: /* same as TK_GT, jump, in1, in3 */
  80441. case OP_Ge: { /* same as TK_GE, jump, in1, in3 */
  80442. int res, res2; /* Result of the comparison of pIn1 against pIn3 */
  80443. char affinity; /* Affinity to use for comparison */
  80444. u16 flags1; /* Copy of initial value of pIn1->flags */
  80445. u16 flags3; /* Copy of initial value of pIn3->flags */
  80446. pIn1 = &aMem[pOp->p1];
  80447. pIn3 = &aMem[pOp->p3];
  80448. flags1 = pIn1->flags;
  80449. flags3 = pIn3->flags;
  80450. if( (flags1 | flags3)&MEM_Null ){
  80451. /* One or both operands are NULL */
  80452. if( pOp->p5 & SQLITE_NULLEQ ){
  80453. /* If SQLITE_NULLEQ is set (which will only happen if the operator is
  80454. ** OP_Eq or OP_Ne) then take the jump or not depending on whether
  80455. ** or not both operands are null.
  80456. */
  80457. assert( (flags1 & MEM_Cleared)==0 );
  80458. assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 || CORRUPT_DB );
  80459. testcase( (pOp->p5 & SQLITE_JUMPIFNULL)!=0 );
  80460. if( (flags1&flags3&MEM_Null)!=0
  80461. && (flags3&MEM_Cleared)==0
  80462. ){
  80463. res = 0; /* Operands are equal */
  80464. }else{
  80465. res = ((flags3 & MEM_Null) ? -1 : +1); /* Operands are not equal */
  80466. }
  80467. }else{
  80468. /* SQLITE_NULLEQ is clear and at least one operand is NULL,
  80469. ** then the result is always NULL.
  80470. ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
  80471. */
  80472. if( pOp->p5 & SQLITE_STOREP2 ){
  80473. pOut = &aMem[pOp->p2];
  80474. iCompare = 1; /* Operands are not equal */
  80475. memAboutToChange(p, pOut);
  80476. MemSetTypeFlag(pOut, MEM_Null);
  80477. REGISTER_TRACE(pOp->p2, pOut);
  80478. }else{
  80479. VdbeBranchTaken(2,3);
  80480. if( pOp->p5 & SQLITE_JUMPIFNULL ){
  80481. goto jump_to_p2;
  80482. }
  80483. }
  80484. break;
  80485. }
  80486. }else{
  80487. /* Neither operand is NULL. Do a comparison. */
  80488. affinity = pOp->p5 & SQLITE_AFF_MASK;
  80489. if( affinity>=SQLITE_AFF_NUMERIC ){
  80490. if( (flags1 | flags3)&MEM_Str ){
  80491. if( (flags1 & (MEM_Int|MEM_IntReal|MEM_Real|MEM_Str))==MEM_Str ){
  80492. applyNumericAffinity(pIn1,0);
  80493. assert( flags3==pIn3->flags );
  80494. /* testcase( flags3!=pIn3->flags );
  80495. ** this used to be possible with pIn1==pIn3, but not since
  80496. ** the column cache was removed. The following assignment
  80497. ** is essentially a no-op. But, it provides defense-in-depth
  80498. ** in case our analysis is incorrect, so it is left in. */
  80499. flags3 = pIn3->flags;
  80500. }
  80501. if( (flags3 & (MEM_Int|MEM_IntReal|MEM_Real|MEM_Str))==MEM_Str ){
  80502. applyNumericAffinity(pIn3,0);
  80503. }
  80504. }
  80505. /* Handle the common case of integer comparison here, as an
  80506. ** optimization, to avoid a call to sqlite3MemCompare() */
  80507. if( (pIn1->flags & pIn3->flags & MEM_Int)!=0 ){
  80508. if( pIn3->u.i > pIn1->u.i ){ res = +1; goto compare_op; }
  80509. if( pIn3->u.i < pIn1->u.i ){ res = -1; goto compare_op; }
  80510. res = 0;
  80511. goto compare_op;
  80512. }
  80513. }else if( affinity==SQLITE_AFF_TEXT ){
  80514. if( (flags1 & MEM_Str)==0 && (flags1&(MEM_Int|MEM_Real|MEM_IntReal))!=0 ){
  80515. testcase( pIn1->flags & MEM_Int );
  80516. testcase( pIn1->flags & MEM_Real );
  80517. testcase( pIn1->flags & MEM_IntReal );
  80518. sqlite3VdbeMemStringify(pIn1, encoding, 1);
  80519. testcase( (flags1&MEM_Dyn) != (pIn1->flags&MEM_Dyn) );
  80520. flags1 = (pIn1->flags & ~MEM_TypeMask) | (flags1 & MEM_TypeMask);
  80521. assert( pIn1!=pIn3 );
  80522. }
  80523. if( (flags3 & MEM_Str)==0 && (flags3&(MEM_Int|MEM_Real|MEM_IntReal))!=0 ){
  80524. testcase( pIn3->flags & MEM_Int );
  80525. testcase( pIn3->flags & MEM_Real );
  80526. testcase( pIn3->flags & MEM_IntReal );
  80527. sqlite3VdbeMemStringify(pIn3, encoding, 1);
  80528. testcase( (flags3&MEM_Dyn) != (pIn3->flags&MEM_Dyn) );
  80529. flags3 = (pIn3->flags & ~MEM_TypeMask) | (flags3 & MEM_TypeMask);
  80530. }
  80531. }
  80532. assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
  80533. res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
  80534. }
  80535. compare_op:
  80536. /* At this point, res is negative, zero, or positive if reg[P1] is
  80537. ** less than, equal to, or greater than reg[P3], respectively. Compute
  80538. ** the answer to this operator in res2, depending on what the comparison
  80539. ** operator actually is. The next block of code depends on the fact
  80540. ** that the 6 comparison operators are consecutive integers in this
  80541. ** order: NE, EQ, GT, LE, LT, GE */
  80542. assert( OP_Eq==OP_Ne+1 ); assert( OP_Gt==OP_Ne+2 ); assert( OP_Le==OP_Ne+3 );
  80543. assert( OP_Lt==OP_Ne+4 ); assert( OP_Ge==OP_Ne+5 );
  80544. if( res<0 ){ /* ne, eq, gt, le, lt, ge */
  80545. static const unsigned char aLTb[] = { 1, 0, 0, 1, 1, 0 };
  80546. res2 = aLTb[pOp->opcode - OP_Ne];
  80547. }else if( res==0 ){
  80548. static const unsigned char aEQb[] = { 0, 1, 0, 1, 0, 1 };
  80549. res2 = aEQb[pOp->opcode - OP_Ne];
  80550. }else{
  80551. static const unsigned char aGTb[] = { 1, 0, 1, 0, 0, 1 };
  80552. res2 = aGTb[pOp->opcode - OP_Ne];
  80553. }
  80554. /* Undo any changes made by applyAffinity() to the input registers. */
  80555. assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) );
  80556. pIn1->flags = flags1;
  80557. assert( (pIn3->flags & MEM_Dyn) == (flags3 & MEM_Dyn) );
  80558. pIn3->flags = flags3;
  80559. if( pOp->p5 & SQLITE_STOREP2 ){
  80560. pOut = &aMem[pOp->p2];
  80561. iCompare = res;
  80562. if( (pOp->p5 & SQLITE_KEEPNULL)!=0 ){
  80563. /* The KEEPNULL flag prevents OP_Eq from overwriting a NULL with 1
  80564. ** and prevents OP_Ne from overwriting NULL with 0. This flag
  80565. ** is only used in contexts where either:
  80566. ** (1) op==OP_Eq && (r[P2]==NULL || r[P2]==0)
  80567. ** (2) op==OP_Ne && (r[P2]==NULL || r[P2]==1)
  80568. ** Therefore it is not necessary to check the content of r[P2] for
  80569. ** NULL. */
  80570. assert( pOp->opcode==OP_Ne || pOp->opcode==OP_Eq );
  80571. assert( res2==0 || res2==1 );
  80572. testcase( res2==0 && pOp->opcode==OP_Eq );
  80573. testcase( res2==1 && pOp->opcode==OP_Eq );
  80574. testcase( res2==0 && pOp->opcode==OP_Ne );
  80575. testcase( res2==1 && pOp->opcode==OP_Ne );
  80576. if( (pOp->opcode==OP_Eq)==res2 ) break;
  80577. }
  80578. memAboutToChange(p, pOut);
  80579. MemSetTypeFlag(pOut, MEM_Int);
  80580. pOut->u.i = res2;
  80581. REGISTER_TRACE(pOp->p2, pOut);
  80582. }else{
  80583. VdbeBranchTaken(res2!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
  80584. if( res2 ){
  80585. goto jump_to_p2;
  80586. }
  80587. }
  80588. break;
  80589. }
  80590. /* Opcode: ElseNotEq * P2 * * *
  80591. **
  80592. ** This opcode must immediately follow an OP_Lt or OP_Gt comparison operator.
  80593. ** If result of an OP_Eq comparison on the same two operands
  80594. ** would have be NULL or false (0), then then jump to P2.
  80595. ** If the result of an OP_Eq comparison on the two previous operands
  80596. ** would have been true (1), then fall through.
  80597. */
  80598. case OP_ElseNotEq: { /* same as TK_ESCAPE, jump */
  80599. assert( pOp>aOp );
  80600. assert( pOp[-1].opcode==OP_Lt || pOp[-1].opcode==OP_Gt );
  80601. assert( pOp[-1].p5 & SQLITE_STOREP2 );
  80602. VdbeBranchTaken(iCompare!=0, 2);
  80603. if( iCompare!=0 ) goto jump_to_p2;
  80604. break;
  80605. }
  80606. /* Opcode: Permutation * * * P4 *
  80607. **
  80608. ** Set the permutation used by the OP_Compare operator in the next
  80609. ** instruction. The permutation is stored in the P4 operand.
  80610. **
  80611. ** The permutation is only valid until the next OP_Compare that has
  80612. ** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should
  80613. ** occur immediately prior to the OP_Compare.
  80614. **
  80615. ** The first integer in the P4 integer array is the length of the array
  80616. ** and does not become part of the permutation.
  80617. */
  80618. case OP_Permutation: {
  80619. assert( pOp->p4type==P4_INTARRAY );
  80620. assert( pOp->p4.ai );
  80621. assert( pOp[1].opcode==OP_Compare );
  80622. assert( pOp[1].p5 & OPFLAG_PERMUTE );
  80623. break;
  80624. }
  80625. /* Opcode: Compare P1 P2 P3 P4 P5
  80626. ** Synopsis: r[P1@P3] <-> r[P2@P3]
  80627. **
  80628. ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
  80629. ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of
  80630. ** the comparison for use by the next OP_Jump instruct.
  80631. **
  80632. ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
  80633. ** determined by the most recent OP_Permutation operator. If the
  80634. ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
  80635. ** order.
  80636. **
  80637. ** P4 is a KeyInfo structure that defines collating sequences and sort
  80638. ** orders for the comparison. The permutation applies to registers
  80639. ** only. The KeyInfo elements are used sequentially.
  80640. **
  80641. ** The comparison is a sort comparison, so NULLs compare equal,
  80642. ** NULLs are less than numbers, numbers are less than strings,
  80643. ** and strings are less than blobs.
  80644. */
  80645. case OP_Compare: {
  80646. int n;
  80647. int i;
  80648. int p1;
  80649. int p2;
  80650. const KeyInfo *pKeyInfo;
  80651. int idx;
  80652. CollSeq *pColl; /* Collating sequence to use on this term */
  80653. int bRev; /* True for DESCENDING sort order */
  80654. int *aPermute; /* The permutation */
  80655. if( (pOp->p5 & OPFLAG_PERMUTE)==0 ){
  80656. aPermute = 0;
  80657. }else{
  80658. assert( pOp>aOp );
  80659. assert( pOp[-1].opcode==OP_Permutation );
  80660. assert( pOp[-1].p4type==P4_INTARRAY );
  80661. aPermute = pOp[-1].p4.ai + 1;
  80662. assert( aPermute!=0 );
  80663. }
  80664. n = pOp->p3;
  80665. pKeyInfo = pOp->p4.pKeyInfo;
  80666. assert( n>0 );
  80667. assert( pKeyInfo!=0 );
  80668. p1 = pOp->p1;
  80669. p2 = pOp->p2;
  80670. #ifdef SQLITE_DEBUG
  80671. if( aPermute ){
  80672. int k, mx = 0;
  80673. for(k=0; k<n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
  80674. assert( p1>0 && p1+mx<=(p->nMem+1 - p->nCursor)+1 );
  80675. assert( p2>0 && p2+mx<=(p->nMem+1 - p->nCursor)+1 );
  80676. }else{
  80677. assert( p1>0 && p1+n<=(p->nMem+1 - p->nCursor)+1 );
  80678. assert( p2>0 && p2+n<=(p->nMem+1 - p->nCursor)+1 );
  80679. }
  80680. #endif /* SQLITE_DEBUG */
  80681. for(i=0; i<n; i++){
  80682. idx = aPermute ? aPermute[i] : i;
  80683. assert( memIsValid(&aMem[p1+idx]) );
  80684. assert( memIsValid(&aMem[p2+idx]) );
  80685. REGISTER_TRACE(p1+idx, &aMem[p1+idx]);
  80686. REGISTER_TRACE(p2+idx, &aMem[p2+idx]);
  80687. assert( i<pKeyInfo->nKeyField );
  80688. pColl = pKeyInfo->aColl[i];
  80689. bRev = pKeyInfo->aSortOrder[i];
  80690. iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl);
  80691. if( iCompare ){
  80692. if( bRev ) iCompare = -iCompare;
  80693. break;
  80694. }
  80695. }
  80696. break;
  80697. }
  80698. /* Opcode: Jump P1 P2 P3 * *
  80699. **
  80700. ** Jump to the instruction at address P1, P2, or P3 depending on whether
  80701. ** in the most recent OP_Compare instruction the P1 vector was less than
  80702. ** equal to, or greater than the P2 vector, respectively.
  80703. */
  80704. case OP_Jump: { /* jump */
  80705. if( iCompare<0 ){
  80706. VdbeBranchTaken(0,4); pOp = &aOp[pOp->p1 - 1];
  80707. }else if( iCompare==0 ){
  80708. VdbeBranchTaken(1,4); pOp = &aOp[pOp->p2 - 1];
  80709. }else{
  80710. VdbeBranchTaken(2,4); pOp = &aOp[pOp->p3 - 1];
  80711. }
  80712. break;
  80713. }
  80714. /* Opcode: And P1 P2 P3 * *
  80715. ** Synopsis: r[P3]=(r[P1] && r[P2])
  80716. **
  80717. ** Take the logical AND of the values in registers P1 and P2 and
  80718. ** write the result into register P3.
  80719. **
  80720. ** If either P1 or P2 is 0 (false) then the result is 0 even if
  80721. ** the other input is NULL. A NULL and true or two NULLs give
  80722. ** a NULL output.
  80723. */
  80724. /* Opcode: Or P1 P2 P3 * *
  80725. ** Synopsis: r[P3]=(r[P1] || r[P2])
  80726. **
  80727. ** Take the logical OR of the values in register P1 and P2 and
  80728. ** store the answer in register P3.
  80729. **
  80730. ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
  80731. ** even if the other input is NULL. A NULL and false or two NULLs
  80732. ** give a NULL output.
  80733. */
  80734. case OP_And: /* same as TK_AND, in1, in2, out3 */
  80735. case OP_Or: { /* same as TK_OR, in1, in2, out3 */
  80736. int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  80737. int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  80738. v1 = sqlite3VdbeBooleanValue(&aMem[pOp->p1], 2);
  80739. v2 = sqlite3VdbeBooleanValue(&aMem[pOp->p2], 2);
  80740. if( pOp->opcode==OP_And ){
  80741. static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
  80742. v1 = and_logic[v1*3+v2];
  80743. }else{
  80744. static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
  80745. v1 = or_logic[v1*3+v2];
  80746. }
  80747. pOut = &aMem[pOp->p3];
  80748. if( v1==2 ){
  80749. MemSetTypeFlag(pOut, MEM_Null);
  80750. }else{
  80751. pOut->u.i = v1;
  80752. MemSetTypeFlag(pOut, MEM_Int);
  80753. }
  80754. break;
  80755. }
  80756. /* Opcode: IsTrue P1 P2 P3 P4 *
  80757. ** Synopsis: r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4
  80758. **
  80759. ** This opcode implements the IS TRUE, IS FALSE, IS NOT TRUE, and
  80760. ** IS NOT FALSE operators.
  80761. **
  80762. ** Interpret the value in register P1 as a boolean value. Store that
  80763. ** boolean (a 0 or 1) in register P2. Or if the value in register P1 is
  80764. ** NULL, then the P3 is stored in register P2. Invert the answer if P4
  80765. ** is 1.
  80766. **
  80767. ** The logic is summarized like this:
  80768. **
  80769. ** <ul>
  80770. ** <li> If P3==0 and P4==0 then r[P2] := r[P1] IS TRUE
  80771. ** <li> If P3==1 and P4==1 then r[P2] := r[P1] IS FALSE
  80772. ** <li> If P3==0 and P4==1 then r[P2] := r[P1] IS NOT TRUE
  80773. ** <li> If P3==1 and P4==0 then r[P2] := r[P1] IS NOT FALSE
  80774. ** </ul>
  80775. */
  80776. case OP_IsTrue: { /* in1, out2 */
  80777. assert( pOp->p4type==P4_INT32 );
  80778. assert( pOp->p4.i==0 || pOp->p4.i==1 );
  80779. assert( pOp->p3==0 || pOp->p3==1 );
  80780. sqlite3VdbeMemSetInt64(&aMem[pOp->p2],
  80781. sqlite3VdbeBooleanValue(&aMem[pOp->p1], pOp->p3) ^ pOp->p4.i);
  80782. break;
  80783. }
  80784. /* Opcode: Not P1 P2 * * *
  80785. ** Synopsis: r[P2]= !r[P1]
  80786. **
  80787. ** Interpret the value in register P1 as a boolean value. Store the
  80788. ** boolean complement in register P2. If the value in register P1 is
  80789. ** NULL, then a NULL is stored in P2.
  80790. */
  80791. case OP_Not: { /* same as TK_NOT, in1, out2 */
  80792. pIn1 = &aMem[pOp->p1];
  80793. pOut = &aMem[pOp->p2];
  80794. if( (pIn1->flags & MEM_Null)==0 ){
  80795. sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeBooleanValue(pIn1,0));
  80796. }else{
  80797. sqlite3VdbeMemSetNull(pOut);
  80798. }
  80799. break;
  80800. }
  80801. /* Opcode: BitNot P1 P2 * * *
  80802. ** Synopsis: r[P2]= ~r[P1]
  80803. **
  80804. ** Interpret the content of register P1 as an integer. Store the
  80805. ** ones-complement of the P1 value into register P2. If P1 holds
  80806. ** a NULL then store a NULL in P2.
  80807. */
  80808. case OP_BitNot: { /* same as TK_BITNOT, in1, out2 */
  80809. pIn1 = &aMem[pOp->p1];
  80810. pOut = &aMem[pOp->p2];
  80811. sqlite3VdbeMemSetNull(pOut);
  80812. if( (pIn1->flags & MEM_Null)==0 ){
  80813. pOut->flags = MEM_Int;
  80814. pOut->u.i = ~sqlite3VdbeIntValue(pIn1);
  80815. }
  80816. break;
  80817. }
  80818. /* Opcode: Once P1 P2 * * *
  80819. **
  80820. ** Fall through to the next instruction the first time this opcode is
  80821. ** encountered on each invocation of the byte-code program. Jump to P2
  80822. ** on the second and all subsequent encounters during the same invocation.
  80823. **
  80824. ** Top-level programs determine first invocation by comparing the P1
  80825. ** operand against the P1 operand on the OP_Init opcode at the beginning
  80826. ** of the program. If the P1 values differ, then fall through and make
  80827. ** the P1 of this opcode equal to the P1 of OP_Init. If P1 values are
  80828. ** the same then take the jump.
  80829. **
  80830. ** For subprograms, there is a bitmask in the VdbeFrame that determines
  80831. ** whether or not the jump should be taken. The bitmask is necessary
  80832. ** because the self-altering code trick does not work for recursive
  80833. ** triggers.
  80834. */
  80835. case OP_Once: { /* jump */
  80836. u32 iAddr; /* Address of this instruction */
  80837. assert( p->aOp[0].opcode==OP_Init );
  80838. if( p->pFrame ){
  80839. iAddr = (int)(pOp - p->aOp);
  80840. if( (p->pFrame->aOnce[iAddr/8] & (1<<(iAddr & 7)))!=0 ){
  80841. VdbeBranchTaken(1, 2);
  80842. goto jump_to_p2;
  80843. }
  80844. p->pFrame->aOnce[iAddr/8] |= 1<<(iAddr & 7);
  80845. }else{
  80846. if( p->aOp[0].p1==pOp->p1 ){
  80847. VdbeBranchTaken(1, 2);
  80848. goto jump_to_p2;
  80849. }
  80850. }
  80851. VdbeBranchTaken(0, 2);
  80852. pOp->p1 = p->aOp[0].p1;
  80853. break;
  80854. }
  80855. /* Opcode: If P1 P2 P3 * *
  80856. **
  80857. ** Jump to P2 if the value in register P1 is true. The value
  80858. ** is considered true if it is numeric and non-zero. If the value
  80859. ** in P1 is NULL then take the jump if and only if P3 is non-zero.
  80860. */
  80861. case OP_If: { /* jump, in1 */
  80862. int c;
  80863. c = sqlite3VdbeBooleanValue(&aMem[pOp->p1], pOp->p3);
  80864. VdbeBranchTaken(c!=0, 2);
  80865. if( c ) goto jump_to_p2;
  80866. break;
  80867. }
  80868. /* Opcode: IfNot P1 P2 P3 * *
  80869. **
  80870. ** Jump to P2 if the value in register P1 is False. The value
  80871. ** is considered false if it has a numeric value of zero. If the value
  80872. ** in P1 is NULL then take the jump if and only if P3 is non-zero.
  80873. */
  80874. case OP_IfNot: { /* jump, in1 */
  80875. int c;
  80876. c = !sqlite3VdbeBooleanValue(&aMem[pOp->p1], !pOp->p3);
  80877. VdbeBranchTaken(c!=0, 2);
  80878. if( c ) goto jump_to_p2;
  80879. break;
  80880. }
  80881. /* Opcode: IsNull P1 P2 * * *
  80882. ** Synopsis: if r[P1]==NULL goto P2
  80883. **
  80884. ** Jump to P2 if the value in register P1 is NULL.
  80885. */
  80886. case OP_IsNull: { /* same as TK_ISNULL, jump, in1 */
  80887. pIn1 = &aMem[pOp->p1];
  80888. VdbeBranchTaken( (pIn1->flags & MEM_Null)!=0, 2);
  80889. if( (pIn1->flags & MEM_Null)!=0 ){
  80890. goto jump_to_p2;
  80891. }
  80892. break;
  80893. }
  80894. /* Opcode: NotNull P1 P2 * * *
  80895. ** Synopsis: if r[P1]!=NULL goto P2
  80896. **
  80897. ** Jump to P2 if the value in register P1 is not NULL.
  80898. */
  80899. case OP_NotNull: { /* same as TK_NOTNULL, jump, in1 */
  80900. pIn1 = &aMem[pOp->p1];
  80901. VdbeBranchTaken( (pIn1->flags & MEM_Null)==0, 2);
  80902. if( (pIn1->flags & MEM_Null)==0 ){
  80903. goto jump_to_p2;
  80904. }
  80905. break;
  80906. }
  80907. /* Opcode: IfNullRow P1 P2 P3 * *
  80908. ** Synopsis: if P1.nullRow then r[P3]=NULL, goto P2
  80909. **
  80910. ** Check the cursor P1 to see if it is currently pointing at a NULL row.
  80911. ** If it is, then set register P3 to NULL and jump immediately to P2.
  80912. ** If P1 is not on a NULL row, then fall through without making any
  80913. ** changes.
  80914. */
  80915. case OP_IfNullRow: { /* jump */
  80916. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  80917. assert( p->apCsr[pOp->p1]!=0 );
  80918. if( p->apCsr[pOp->p1]->nullRow ){
  80919. sqlite3VdbeMemSetNull(aMem + pOp->p3);
  80920. goto jump_to_p2;
  80921. }
  80922. break;
  80923. }
  80924. #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
  80925. /* Opcode: Offset P1 P2 P3 * *
  80926. ** Synopsis: r[P3] = sqlite_offset(P1)
  80927. **
  80928. ** Store in register r[P3] the byte offset into the database file that is the
  80929. ** start of the payload for the record at which that cursor P1 is currently
  80930. ** pointing.
  80931. **
  80932. ** P2 is the column number for the argument to the sqlite_offset() function.
  80933. ** This opcode does not use P2 itself, but the P2 value is used by the
  80934. ** code generator. The P1, P2, and P3 operands to this opcode are the
  80935. ** same as for OP_Column.
  80936. **
  80937. ** This opcode is only available if SQLite is compiled with the
  80938. ** -DSQLITE_ENABLE_OFFSET_SQL_FUNC option.
  80939. */
  80940. case OP_Offset: { /* out3 */
  80941. VdbeCursor *pC; /* The VDBE cursor */
  80942. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  80943. pC = p->apCsr[pOp->p1];
  80944. pOut = &p->aMem[pOp->p3];
  80945. if( NEVER(pC==0) || pC->eCurType!=CURTYPE_BTREE ){
  80946. sqlite3VdbeMemSetNull(pOut);
  80947. }else{
  80948. sqlite3VdbeMemSetInt64(pOut, sqlite3BtreeOffset(pC->uc.pCursor));
  80949. }
  80950. break;
  80951. }
  80952. #endif /* SQLITE_ENABLE_OFFSET_SQL_FUNC */
  80953. /* Opcode: Column P1 P2 P3 P4 P5
  80954. ** Synopsis: r[P3]=PX
  80955. **
  80956. ** Interpret the data that cursor P1 points to as a structure built using
  80957. ** the MakeRecord instruction. (See the MakeRecord opcode for additional
  80958. ** information about the format of the data.) Extract the P2-th column
  80959. ** from this record. If there are less that (P2+1)
  80960. ** values in the record, extract a NULL.
  80961. **
  80962. ** The value extracted is stored in register P3.
  80963. **
  80964. ** If the record contains fewer than P2 fields, then extract a NULL. Or,
  80965. ** if the P4 argument is a P4_MEM use the value of the P4 argument as
  80966. ** the result.
  80967. **
  80968. ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
  80969. ** then the cache of the cursor is reset prior to extracting the column.
  80970. ** The first OP_Column against a pseudo-table after the value of the content
  80971. ** register has changed should have this bit set.
  80972. **
  80973. ** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 then
  80974. ** the result is guaranteed to only be used as the argument of a length()
  80975. ** or typeof() function, respectively. The loading of large blobs can be
  80976. ** skipped for length() and all content loading can be skipped for typeof().
  80977. */
  80978. case OP_Column: {
  80979. int p2; /* column number to retrieve */
  80980. VdbeCursor *pC; /* The VDBE cursor */
  80981. BtCursor *pCrsr; /* The BTree cursor */
  80982. u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
  80983. int len; /* The length of the serialized data for the column */
  80984. int i; /* Loop counter */
  80985. Mem *pDest; /* Where to write the extracted value */
  80986. Mem sMem; /* For storing the record being decoded */
  80987. const u8 *zData; /* Part of the record being decoded */
  80988. const u8 *zHdr; /* Next unparsed byte of the header */
  80989. const u8 *zEndHdr; /* Pointer to first byte after the header */
  80990. u64 offset64; /* 64-bit offset */
  80991. u32 t; /* A type code from the record header */
  80992. Mem *pReg; /* PseudoTable input register */
  80993. pC = p->apCsr[pOp->p1];
  80994. p2 = pOp->p2;
  80995. /* If the cursor cache is stale (meaning it is not currently point at
  80996. ** the correct row) then bring it up-to-date by doing the necessary
  80997. ** B-Tree seek. */
  80998. rc = sqlite3VdbeCursorMoveto(&pC, &p2);
  80999. if( rc ) goto abort_due_to_error;
  81000. assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
  81001. pDest = &aMem[pOp->p3];
  81002. memAboutToChange(p, pDest);
  81003. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  81004. assert( pC!=0 );
  81005. assert( p2<pC->nField );
  81006. aOffset = pC->aOffset;
  81007. assert( pC->eCurType!=CURTYPE_VTAB );
  81008. assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
  81009. assert( pC->eCurType!=CURTYPE_SORTER );
  81010. if( pC->cacheStatus!=p->cacheCtr ){ /*OPTIMIZATION-IF-FALSE*/
  81011. if( pC->nullRow ){
  81012. if( pC->eCurType==CURTYPE_PSEUDO ){
  81013. /* For the special case of as pseudo-cursor, the seekResult field
  81014. ** identifies the register that holds the record */
  81015. assert( pC->seekResult>0 );
  81016. pReg = &aMem[pC->seekResult];
  81017. assert( pReg->flags & MEM_Blob );
  81018. assert( memIsValid(pReg) );
  81019. pC->payloadSize = pC->szRow = pReg->n;
  81020. pC->aRow = (u8*)pReg->z;
  81021. }else{
  81022. sqlite3VdbeMemSetNull(pDest);
  81023. goto op_column_out;
  81024. }
  81025. }else{
  81026. pCrsr = pC->uc.pCursor;
  81027. assert( pC->eCurType==CURTYPE_BTREE );
  81028. assert( pCrsr );
  81029. assert( sqlite3BtreeCursorIsValid(pCrsr) );
  81030. pC->payloadSize = sqlite3BtreePayloadSize(pCrsr);
  81031. pC->aRow = sqlite3BtreePayloadFetch(pCrsr, &pC->szRow);
  81032. assert( pC->szRow<=pC->payloadSize );
  81033. assert( pC->szRow<=65536 ); /* Maximum page size is 64KiB */
  81034. if( pC->payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  81035. goto too_big;
  81036. }
  81037. }
  81038. pC->cacheStatus = p->cacheCtr;
  81039. pC->iHdrOffset = getVarint32(pC->aRow, aOffset[0]);
  81040. pC->nHdrParsed = 0;
  81041. if( pC->szRow<aOffset[0] ){ /*OPTIMIZATION-IF-FALSE*/
  81042. /* pC->aRow does not have to hold the entire row, but it does at least
  81043. ** need to cover the header of the record. If pC->aRow does not contain
  81044. ** the complete header, then set it to zero, forcing the header to be
  81045. ** dynamically allocated. */
  81046. pC->aRow = 0;
  81047. pC->szRow = 0;
  81048. /* Make sure a corrupt database has not given us an oversize header.
  81049. ** Do this now to avoid an oversize memory allocation.
  81050. **
  81051. ** Type entries can be between 1 and 5 bytes each. But 4 and 5 byte
  81052. ** types use so much data space that there can only be 4096 and 32 of
  81053. ** them, respectively. So the maximum header length results from a
  81054. ** 3-byte type for each of the maximum of 32768 columns plus three
  81055. ** extra bytes for the header length itself. 32768*3 + 3 = 98307.
  81056. */
  81057. if( aOffset[0] > 98307 || aOffset[0] > pC->payloadSize ){
  81058. goto op_column_corrupt;
  81059. }
  81060. }else{
  81061. /* This is an optimization. By skipping over the first few tests
  81062. ** (ex: pC->nHdrParsed<=p2) in the next section, we achieve a
  81063. ** measurable performance gain.
  81064. **
  81065. ** This branch is taken even if aOffset[0]==0. Such a record is never
  81066. ** generated by SQLite, and could be considered corruption, but we
  81067. ** accept it for historical reasons. When aOffset[0]==0, the code this
  81068. ** branch jumps to reads past the end of the record, but never more
  81069. ** than a few bytes. Even if the record occurs at the end of the page
  81070. ** content area, the "page header" comes after the page content and so
  81071. ** this overread is harmless. Similar overreads can occur for a corrupt
  81072. ** database file.
  81073. */
  81074. zData = pC->aRow;
  81075. assert( pC->nHdrParsed<=p2 ); /* Conditional skipped */
  81076. testcase( aOffset[0]==0 );
  81077. goto op_column_read_header;
  81078. }
  81079. }
  81080. /* Make sure at least the first p2+1 entries of the header have been
  81081. ** parsed and valid information is in aOffset[] and pC->aType[].
  81082. */
  81083. if( pC->nHdrParsed<=p2 ){
  81084. /* If there is more header available for parsing in the record, try
  81085. ** to extract additional fields up through the p2+1-th field
  81086. */
  81087. if( pC->iHdrOffset<aOffset[0] ){
  81088. /* Make sure zData points to enough of the record to cover the header. */
  81089. if( pC->aRow==0 ){
  81090. memset(&sMem, 0, sizeof(sMem));
  81091. rc = sqlite3VdbeMemFromBtree(pC->uc.pCursor, 0, aOffset[0], &sMem);
  81092. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  81093. zData = (u8*)sMem.z;
  81094. }else{
  81095. zData = pC->aRow;
  81096. }
  81097. /* Fill in pC->aType[i] and aOffset[i] values through the p2-th field. */
  81098. op_column_read_header:
  81099. i = pC->nHdrParsed;
  81100. offset64 = aOffset[i];
  81101. zHdr = zData + pC->iHdrOffset;
  81102. zEndHdr = zData + aOffset[0];
  81103. testcase( zHdr>=zEndHdr );
  81104. do{
  81105. if( (pC->aType[i] = t = zHdr[0])<0x80 ){
  81106. zHdr++;
  81107. offset64 += sqlite3VdbeOneByteSerialTypeLen(t);
  81108. }else{
  81109. zHdr += sqlite3GetVarint32(zHdr, &t);
  81110. pC->aType[i] = t;
  81111. offset64 += sqlite3VdbeSerialTypeLen(t);
  81112. }
  81113. aOffset[++i] = (u32)(offset64 & 0xffffffff);
  81114. }while( i<=p2 && zHdr<zEndHdr );
  81115. /* The record is corrupt if any of the following are true:
  81116. ** (1) the bytes of the header extend past the declared header size
  81117. ** (2) the entire header was used but not all data was used
  81118. ** (3) the end of the data extends beyond the end of the record.
  81119. */
  81120. if( (zHdr>=zEndHdr && (zHdr>zEndHdr || offset64!=pC->payloadSize))
  81121. || (offset64 > pC->payloadSize)
  81122. ){
  81123. if( aOffset[0]==0 ){
  81124. i = 0;
  81125. zHdr = zEndHdr;
  81126. }else{
  81127. if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
  81128. goto op_column_corrupt;
  81129. }
  81130. }
  81131. pC->nHdrParsed = i;
  81132. pC->iHdrOffset = (u32)(zHdr - zData);
  81133. if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
  81134. }else{
  81135. t = 0;
  81136. }
  81137. /* If after trying to extract new entries from the header, nHdrParsed is
  81138. ** still not up to p2, that means that the record has fewer than p2
  81139. ** columns. So the result will be either the default value or a NULL.
  81140. */
  81141. if( pC->nHdrParsed<=p2 ){
  81142. if( pOp->p4type==P4_MEM ){
  81143. sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
  81144. }else{
  81145. sqlite3VdbeMemSetNull(pDest);
  81146. }
  81147. goto op_column_out;
  81148. }
  81149. }else{
  81150. t = pC->aType[p2];
  81151. }
  81152. /* Extract the content for the p2+1-th column. Control can only
  81153. ** reach this point if aOffset[p2], aOffset[p2+1], and pC->aType[p2] are
  81154. ** all valid.
  81155. */
  81156. assert( p2<pC->nHdrParsed );
  81157. assert( rc==SQLITE_OK );
  81158. assert( sqlite3VdbeCheckMemInvariants(pDest) );
  81159. if( VdbeMemDynamic(pDest) ){
  81160. sqlite3VdbeMemSetNull(pDest);
  81161. }
  81162. assert( t==pC->aType[p2] );
  81163. if( pC->szRow>=aOffset[p2+1] ){
  81164. /* This is the common case where the desired content fits on the original
  81165. ** page - where the content is not on an overflow page */
  81166. zData = pC->aRow + aOffset[p2];
  81167. if( t<12 ){
  81168. sqlite3VdbeSerialGet(zData, t, pDest);
  81169. }else{
  81170. /* If the column value is a string, we need a persistent value, not
  81171. ** a MEM_Ephem value. This branch is a fast short-cut that is equivalent
  81172. ** to calling sqlite3VdbeSerialGet() and sqlite3VdbeDeephemeralize().
  81173. */
  81174. static const u16 aFlag[] = { MEM_Blob, MEM_Str|MEM_Term };
  81175. pDest->n = len = (t-12)/2;
  81176. pDest->enc = encoding;
  81177. if( pDest->szMalloc < len+2 ){
  81178. pDest->flags = MEM_Null;
  81179. if( sqlite3VdbeMemGrow(pDest, len+2, 0) ) goto no_mem;
  81180. }else{
  81181. pDest->z = pDest->zMalloc;
  81182. }
  81183. memcpy(pDest->z, zData, len);
  81184. pDest->z[len] = 0;
  81185. pDest->z[len+1] = 0;
  81186. pDest->flags = aFlag[t&1];
  81187. }
  81188. }else{
  81189. pDest->enc = encoding;
  81190. /* This branch happens only when content is on overflow pages */
  81191. if( ((pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
  81192. && ((t>=12 && (t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0))
  81193. || (len = sqlite3VdbeSerialTypeLen(t))==0
  81194. ){
  81195. /* Content is irrelevant for
  81196. ** 1. the typeof() function,
  81197. ** 2. the length(X) function if X is a blob, and
  81198. ** 3. if the content length is zero.
  81199. ** So we might as well use bogus content rather than reading
  81200. ** content from disk.
  81201. **
  81202. ** Although sqlite3VdbeSerialGet() may read at most 8 bytes from the
  81203. ** buffer passed to it, debugging function VdbeMemPrettyPrint() may
  81204. ** read up to 16. So 16 bytes of bogus content is supplied.
  81205. */
  81206. static u8 aZero[16]; /* This is the bogus content */
  81207. sqlite3VdbeSerialGet(aZero, t, pDest);
  81208. }else{
  81209. rc = sqlite3VdbeMemFromBtree(pC->uc.pCursor, aOffset[p2], len, pDest);
  81210. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  81211. sqlite3VdbeSerialGet((const u8*)pDest->z, t, pDest);
  81212. pDest->flags &= ~MEM_Ephem;
  81213. }
  81214. }
  81215. op_column_out:
  81216. UPDATE_MAX_BLOBSIZE(pDest);
  81217. REGISTER_TRACE(pOp->p3, pDest);
  81218. break;
  81219. op_column_corrupt:
  81220. if( aOp[0].p3>0 ){
  81221. pOp = &aOp[aOp[0].p3-1];
  81222. break;
  81223. }else{
  81224. rc = SQLITE_CORRUPT_BKPT;
  81225. goto abort_due_to_error;
  81226. }
  81227. }
  81228. /* Opcode: Affinity P1 P2 * P4 *
  81229. ** Synopsis: affinity(r[P1@P2])
  81230. **
  81231. ** Apply affinities to a range of P2 registers starting with P1.
  81232. **
  81233. ** P4 is a string that is P2 characters long. The N-th character of the
  81234. ** string indicates the column affinity that should be used for the N-th
  81235. ** memory cell in the range.
  81236. */
  81237. case OP_Affinity: {
  81238. const char *zAffinity; /* The affinity to be applied */
  81239. zAffinity = pOp->p4.z;
  81240. assert( zAffinity!=0 );
  81241. assert( pOp->p2>0 );
  81242. assert( zAffinity[pOp->p2]==0 );
  81243. pIn1 = &aMem[pOp->p1];
  81244. while( 1 /*edit-by-break*/ ){
  81245. assert( pIn1 <= &p->aMem[(p->nMem+1 - p->nCursor)] );
  81246. assert( memIsValid(pIn1) );
  81247. applyAffinity(pIn1, zAffinity[0], encoding);
  81248. if( zAffinity[0]==SQLITE_AFF_REAL && (pIn1->flags & MEM_Int)!=0 ){
  81249. /* When applying REAL affinity, if the result is still MEM_Int,
  81250. ** indicate that REAL is actually desired */
  81251. pIn1->flags |= MEM_IntReal;
  81252. pIn1->flags &= ~MEM_Int;
  81253. }
  81254. REGISTER_TRACE((int)(pIn1-aMem), pIn1);
  81255. zAffinity++;
  81256. if( zAffinity[0]==0 ) break;
  81257. pIn1++;
  81258. }
  81259. break;
  81260. }
  81261. /* Opcode: MakeRecord P1 P2 P3 P4 *
  81262. ** Synopsis: r[P3]=mkrec(r[P1@P2])
  81263. **
  81264. ** Convert P2 registers beginning with P1 into the [record format]
  81265. ** use as a data record in a database table or as a key
  81266. ** in an index. The OP_Column opcode can decode the record later.
  81267. **
  81268. ** P4 may be a string that is P2 characters long. The N-th character of the
  81269. ** string indicates the column affinity that should be used for the N-th
  81270. ** field of the index key.
  81271. **
  81272. ** The mapping from character to affinity is given by the SQLITE_AFF_
  81273. ** macros defined in sqliteInt.h.
  81274. **
  81275. ** If P4 is NULL then all index fields have the affinity BLOB.
  81276. */
  81277. case OP_MakeRecord: {
  81278. Mem *pRec; /* The new record */
  81279. u64 nData; /* Number of bytes of data space */
  81280. int nHdr; /* Number of bytes of header space */
  81281. i64 nByte; /* Data space required for this record */
  81282. i64 nZero; /* Number of zero bytes at the end of the record */
  81283. int nVarint; /* Number of bytes in a varint */
  81284. u32 serial_type; /* Type field */
  81285. Mem *pData0; /* First field to be combined into the record */
  81286. Mem *pLast; /* Last field of the record */
  81287. int nField; /* Number of fields in the record */
  81288. char *zAffinity; /* The affinity string for the record */
  81289. int file_format; /* File format to use for encoding */
  81290. u32 len; /* Length of a field */
  81291. u8 *zHdr; /* Where to write next byte of the header */
  81292. u8 *zPayload; /* Where to write next byte of the payload */
  81293. /* Assuming the record contains N fields, the record format looks
  81294. ** like this:
  81295. **
  81296. ** ------------------------------------------------------------------------
  81297. ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
  81298. ** ------------------------------------------------------------------------
  81299. **
  81300. ** Data(0) is taken from register P1. Data(1) comes from register P1+1
  81301. ** and so forth.
  81302. **
  81303. ** Each type field is a varint representing the serial type of the
  81304. ** corresponding data element (see sqlite3VdbeSerialType()). The
  81305. ** hdr-size field is also a varint which is the offset from the beginning
  81306. ** of the record to data0.
  81307. */
  81308. nData = 0; /* Number of bytes of data space */
  81309. nHdr = 0; /* Number of bytes of header space */
  81310. nZero = 0; /* Number of zero bytes at the end of the record */
  81311. nField = pOp->p1;
  81312. zAffinity = pOp->p4.z;
  81313. assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem+1 - p->nCursor)+1 );
  81314. pData0 = &aMem[nField];
  81315. nField = pOp->p2;
  81316. pLast = &pData0[nField-1];
  81317. file_format = p->minWriteFileFormat;
  81318. /* Identify the output register */
  81319. assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
  81320. pOut = &aMem[pOp->p3];
  81321. memAboutToChange(p, pOut);
  81322. /* Apply the requested affinity to all inputs
  81323. */
  81324. assert( pData0<=pLast );
  81325. if( zAffinity ){
  81326. pRec = pData0;
  81327. do{
  81328. applyAffinity(pRec, zAffinity[0], encoding);
  81329. if( zAffinity[0]==SQLITE_AFF_REAL && (pRec->flags & MEM_Int) ){
  81330. pRec->flags |= MEM_IntReal;
  81331. pRec->flags &= ~(MEM_Int);
  81332. }
  81333. REGISTER_TRACE((int)(pRec-aMem), pRec);
  81334. zAffinity++;
  81335. pRec++;
  81336. assert( zAffinity[0]==0 || pRec<=pLast );
  81337. }while( zAffinity[0] );
  81338. }
  81339. #ifdef SQLITE_ENABLE_NULL_TRIM
  81340. /* NULLs can be safely trimmed from the end of the record, as long as
  81341. ** as the schema format is 2 or more and none of the omitted columns
  81342. ** have a non-NULL default value. Also, the record must be left with
  81343. ** at least one field. If P5>0 then it will be one more than the
  81344. ** index of the right-most column with a non-NULL default value */
  81345. if( pOp->p5 ){
  81346. while( (pLast->flags & MEM_Null)!=0 && nField>pOp->p5 ){
  81347. pLast--;
  81348. nField--;
  81349. }
  81350. }
  81351. #endif
  81352. /* Loop through the elements that will make up the record to figure
  81353. ** out how much space is required for the new record.
  81354. */
  81355. pRec = pLast;
  81356. do{
  81357. assert( memIsValid(pRec) );
  81358. serial_type = sqlite3VdbeSerialType(pRec, file_format, &len);
  81359. if( pRec->flags & MEM_Zero ){
  81360. if( serial_type==0 ){
  81361. /* Values with MEM_Null and MEM_Zero are created by xColumn virtual
  81362. ** table methods that never invoke sqlite3_result_xxxxx() while
  81363. ** computing an unchanging column value in an UPDATE statement.
  81364. ** Give such values a special internal-use-only serial-type of 10
  81365. ** so that they can be passed through to xUpdate and have
  81366. ** a true sqlite3_value_nochange(). */
  81367. assert( pOp->p5==OPFLAG_NOCHNG_MAGIC || CORRUPT_DB );
  81368. serial_type = 10;
  81369. }else if( nData ){
  81370. if( sqlite3VdbeMemExpandBlob(pRec) ) goto no_mem;
  81371. }else{
  81372. nZero += pRec->u.nZero;
  81373. len -= pRec->u.nZero;
  81374. }
  81375. }
  81376. nData += len;
  81377. testcase( serial_type==127 );
  81378. testcase( serial_type==128 );
  81379. nHdr += serial_type<=127 ? 1 : sqlite3VarintLen(serial_type);
  81380. pRec->uTemp = serial_type;
  81381. if( pRec==pData0 ) break;
  81382. pRec--;
  81383. }while(1);
  81384. /* EVIDENCE-OF: R-22564-11647 The header begins with a single varint
  81385. ** which determines the total number of bytes in the header. The varint
  81386. ** value is the size of the header in bytes including the size varint
  81387. ** itself. */
  81388. testcase( nHdr==126 );
  81389. testcase( nHdr==127 );
  81390. if( nHdr<=126 ){
  81391. /* The common case */
  81392. nHdr += 1;
  81393. }else{
  81394. /* Rare case of a really large header */
  81395. nVarint = sqlite3VarintLen(nHdr);
  81396. nHdr += nVarint;
  81397. if( nVarint<sqlite3VarintLen(nHdr) ) nHdr++;
  81398. }
  81399. nByte = nHdr+nData;
  81400. /* Make sure the output register has a buffer large enough to store
  81401. ** the new record. The output register (pOp->p3) is not allowed to
  81402. ** be one of the input registers (because the following call to
  81403. ** sqlite3VdbeMemClearAndResize() could clobber the value before it is used).
  81404. */
  81405. if( nByte+nZero<=pOut->szMalloc ){
  81406. /* The output register is already large enough to hold the record.
  81407. ** No error checks or buffer enlargement is required */
  81408. pOut->z = pOut->zMalloc;
  81409. }else{
  81410. /* Need to make sure that the output is not too big and then enlarge
  81411. ** the output register to hold the full result */
  81412. if( nByte+nZero>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  81413. goto too_big;
  81414. }
  81415. if( sqlite3VdbeMemClearAndResize(pOut, (int)nByte) ){
  81416. goto no_mem;
  81417. }
  81418. }
  81419. pOut->n = (int)nByte;
  81420. pOut->flags = MEM_Blob;
  81421. if( nZero ){
  81422. pOut->u.nZero = nZero;
  81423. pOut->flags |= MEM_Zero;
  81424. }
  81425. UPDATE_MAX_BLOBSIZE(pOut);
  81426. zHdr = (u8 *)pOut->z;
  81427. zPayload = zHdr + nHdr;
  81428. /* Write the record */
  81429. zHdr += putVarint32(zHdr, nHdr);
  81430. assert( pData0<=pLast );
  81431. pRec = pData0;
  81432. do{
  81433. serial_type = pRec->uTemp;
  81434. /* EVIDENCE-OF: R-06529-47362 Following the size varint are one or more
  81435. ** additional varints, one per column. */
  81436. zHdr += putVarint32(zHdr, serial_type); /* serial type */
  81437. /* EVIDENCE-OF: R-64536-51728 The values for each column in the record
  81438. ** immediately follow the header. */
  81439. zPayload += sqlite3VdbeSerialPut(zPayload, pRec, serial_type); /* content */
  81440. }while( (++pRec)<=pLast );
  81441. assert( nHdr==(int)(zHdr - (u8*)pOut->z) );
  81442. assert( nByte==(int)(zPayload - (u8*)pOut->z) );
  81443. assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
  81444. REGISTER_TRACE(pOp->p3, pOut);
  81445. break;
  81446. }
  81447. /* Opcode: Count P1 P2 * * *
  81448. ** Synopsis: r[P2]=count()
  81449. **
  81450. ** Store the number of entries (an integer value) in the table or index
  81451. ** opened by cursor P1 in register P2
  81452. */
  81453. #ifndef SQLITE_OMIT_BTREECOUNT
  81454. case OP_Count: { /* out2 */
  81455. i64 nEntry;
  81456. BtCursor *pCrsr;
  81457. assert( p->apCsr[pOp->p1]->eCurType==CURTYPE_BTREE );
  81458. pCrsr = p->apCsr[pOp->p1]->uc.pCursor;
  81459. assert( pCrsr );
  81460. nEntry = 0; /* Not needed. Only used to silence a warning. */
  81461. rc = sqlite3BtreeCount(pCrsr, &nEntry);
  81462. if( rc ) goto abort_due_to_error;
  81463. pOut = out2Prerelease(p, pOp);
  81464. pOut->u.i = nEntry;
  81465. break;
  81466. }
  81467. #endif
  81468. /* Opcode: Savepoint P1 * * P4 *
  81469. **
  81470. ** Open, release or rollback the savepoint named by parameter P4, depending
  81471. ** on the value of P1. To open a new savepoint set P1==0 (SAVEPOINT_BEGIN).
  81472. ** To release (commit) an existing savepoint set P1==1 (SAVEPOINT_RELEASE).
  81473. ** To rollback an existing savepoint set P1==2 (SAVEPOINT_ROLLBACK).
  81474. */
  81475. case OP_Savepoint: {
  81476. int p1; /* Value of P1 operand */
  81477. char *zName; /* Name of savepoint */
  81478. int nName;
  81479. Savepoint *pNew;
  81480. Savepoint *pSavepoint;
  81481. Savepoint *pTmp;
  81482. int iSavepoint;
  81483. int ii;
  81484. p1 = pOp->p1;
  81485. zName = pOp->p4.z;
  81486. /* Assert that the p1 parameter is valid. Also that if there is no open
  81487. ** transaction, then there cannot be any savepoints.
  81488. */
  81489. assert( db->pSavepoint==0 || db->autoCommit==0 );
  81490. assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK );
  81491. assert( db->pSavepoint || db->isTransactionSavepoint==0 );
  81492. assert( checkSavepointCount(db) );
  81493. assert( p->bIsReader );
  81494. if( p1==SAVEPOINT_BEGIN ){
  81495. if( db->nVdbeWrite>0 ){
  81496. /* A new savepoint cannot be created if there are active write
  81497. ** statements (i.e. open read/write incremental blob handles).
  81498. */
  81499. sqlite3VdbeError(p, "cannot open savepoint - SQL statements in progress");
  81500. rc = SQLITE_BUSY;
  81501. }else{
  81502. nName = sqlite3Strlen30(zName);
  81503. #ifndef SQLITE_OMIT_VIRTUALTABLE
  81504. /* This call is Ok even if this savepoint is actually a transaction
  81505. ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
  81506. ** If this is a transaction savepoint being opened, it is guaranteed
  81507. ** that the db->aVTrans[] array is empty. */
  81508. assert( db->autoCommit==0 || db->nVTrans==0 );
  81509. rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
  81510. db->nStatement+db->nSavepoint);
  81511. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  81512. #endif
  81513. /* Create a new savepoint structure. */
  81514. pNew = sqlite3DbMallocRawNN(db, sizeof(Savepoint)+nName+1);
  81515. if( pNew ){
  81516. pNew->zName = (char *)&pNew[1];
  81517. memcpy(pNew->zName, zName, nName+1);
  81518. /* If there is no open transaction, then mark this as a special
  81519. ** "transaction savepoint". */
  81520. if( db->autoCommit ){
  81521. db->autoCommit = 0;
  81522. db->isTransactionSavepoint = 1;
  81523. }else{
  81524. db->nSavepoint++;
  81525. }
  81526. /* Link the new savepoint into the database handle's list. */
  81527. pNew->pNext = db->pSavepoint;
  81528. db->pSavepoint = pNew;
  81529. pNew->nDeferredCons = db->nDeferredCons;
  81530. pNew->nDeferredImmCons = db->nDeferredImmCons;
  81531. }
  81532. }
  81533. }else{
  81534. assert( p1==SAVEPOINT_RELEASE || p1==SAVEPOINT_ROLLBACK );
  81535. iSavepoint = 0;
  81536. /* Find the named savepoint. If there is no such savepoint, then an
  81537. ** an error is returned to the user. */
  81538. for(
  81539. pSavepoint = db->pSavepoint;
  81540. pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
  81541. pSavepoint = pSavepoint->pNext
  81542. ){
  81543. iSavepoint++;
  81544. }
  81545. if( !pSavepoint ){
  81546. sqlite3VdbeError(p, "no such savepoint: %s", zName);
  81547. rc = SQLITE_ERROR;
  81548. }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){
  81549. /* It is not possible to release (commit) a savepoint if there are
  81550. ** active write statements.
  81551. */
  81552. sqlite3VdbeError(p, "cannot release savepoint - "
  81553. "SQL statements in progress");
  81554. rc = SQLITE_BUSY;
  81555. }else{
  81556. /* Determine whether or not this is a transaction savepoint. If so,
  81557. ** and this is a RELEASE command, then the current transaction
  81558. ** is committed.
  81559. */
  81560. int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
  81561. if( isTransaction && p1==SAVEPOINT_RELEASE ){
  81562. if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
  81563. goto vdbe_return;
  81564. }
  81565. db->autoCommit = 1;
  81566. if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
  81567. p->pc = (int)(pOp - aOp);
  81568. db->autoCommit = 0;
  81569. p->rc = rc = SQLITE_BUSY;
  81570. goto vdbe_return;
  81571. }
  81572. db->isTransactionSavepoint = 0;
  81573. rc = p->rc;
  81574. }else{
  81575. int isSchemaChange;
  81576. iSavepoint = db->nSavepoint - iSavepoint - 1;
  81577. if( p1==SAVEPOINT_ROLLBACK ){
  81578. isSchemaChange = (db->mDbFlags & DBFLAG_SchemaChange)!=0;
  81579. for(ii=0; ii<db->nDb; ii++){
  81580. rc = sqlite3BtreeTripAllCursors(db->aDb[ii].pBt,
  81581. SQLITE_ABORT_ROLLBACK,
  81582. isSchemaChange==0);
  81583. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  81584. }
  81585. }else{
  81586. assert( p1==SAVEPOINT_RELEASE );
  81587. isSchemaChange = 0;
  81588. }
  81589. for(ii=0; ii<db->nDb; ii++){
  81590. rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
  81591. if( rc!=SQLITE_OK ){
  81592. goto abort_due_to_error;
  81593. }
  81594. }
  81595. if( isSchemaChange ){
  81596. sqlite3ExpirePreparedStatements(db, 0);
  81597. sqlite3ResetAllSchemasOfConnection(db);
  81598. db->mDbFlags |= DBFLAG_SchemaChange;
  81599. }
  81600. }
  81601. /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
  81602. ** savepoints nested inside of the savepoint being operated on. */
  81603. while( db->pSavepoint!=pSavepoint ){
  81604. pTmp = db->pSavepoint;
  81605. db->pSavepoint = pTmp->pNext;
  81606. sqlite3DbFree(db, pTmp);
  81607. db->nSavepoint--;
  81608. }
  81609. /* If it is a RELEASE, then destroy the savepoint being operated on
  81610. ** too. If it is a ROLLBACK TO, then set the number of deferred
  81611. ** constraint violations present in the database to the value stored
  81612. ** when the savepoint was created. */
  81613. if( p1==SAVEPOINT_RELEASE ){
  81614. assert( pSavepoint==db->pSavepoint );
  81615. db->pSavepoint = pSavepoint->pNext;
  81616. sqlite3DbFree(db, pSavepoint);
  81617. if( !isTransaction ){
  81618. db->nSavepoint--;
  81619. }
  81620. }else{
  81621. assert( p1==SAVEPOINT_ROLLBACK );
  81622. db->nDeferredCons = pSavepoint->nDeferredCons;
  81623. db->nDeferredImmCons = pSavepoint->nDeferredImmCons;
  81624. }
  81625. if( !isTransaction || p1==SAVEPOINT_ROLLBACK ){
  81626. rc = sqlite3VtabSavepoint(db, p1, iSavepoint);
  81627. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  81628. }
  81629. }
  81630. }
  81631. if( rc ) goto abort_due_to_error;
  81632. break;
  81633. }
  81634. /* Opcode: AutoCommit P1 P2 * * *
  81635. **
  81636. ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
  81637. ** back any currently active btree transactions. If there are any active
  81638. ** VMs (apart from this one), then a ROLLBACK fails. A COMMIT fails if
  81639. ** there are active writing VMs or active VMs that use shared cache.
  81640. **
  81641. ** This instruction causes the VM to halt.
  81642. */
  81643. case OP_AutoCommit: {
  81644. int desiredAutoCommit;
  81645. int iRollback;
  81646. desiredAutoCommit = pOp->p1;
  81647. iRollback = pOp->p2;
  81648. assert( desiredAutoCommit==1 || desiredAutoCommit==0 );
  81649. assert( desiredAutoCommit==1 || iRollback==0 );
  81650. assert( db->nVdbeActive>0 ); /* At least this one VM is active */
  81651. assert( p->bIsReader );
  81652. if( desiredAutoCommit!=db->autoCommit ){
  81653. if( iRollback ){
  81654. assert( desiredAutoCommit==1 );
  81655. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  81656. db->autoCommit = 1;
  81657. }else if( desiredAutoCommit && db->nVdbeWrite>0 ){
  81658. /* If this instruction implements a COMMIT and other VMs are writing
  81659. ** return an error indicating that the other VMs must complete first.
  81660. */
  81661. sqlite3VdbeError(p, "cannot commit transaction - "
  81662. "SQL statements in progress");
  81663. rc = SQLITE_BUSY;
  81664. goto abort_due_to_error;
  81665. }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
  81666. goto vdbe_return;
  81667. }else{
  81668. db->autoCommit = (u8)desiredAutoCommit;
  81669. }
  81670. if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
  81671. p->pc = (int)(pOp - aOp);
  81672. db->autoCommit = (u8)(1-desiredAutoCommit);
  81673. p->rc = rc = SQLITE_BUSY;
  81674. goto vdbe_return;
  81675. }
  81676. assert( db->nStatement==0 );
  81677. sqlite3CloseSavepoints(db);
  81678. if( p->rc==SQLITE_OK ){
  81679. rc = SQLITE_DONE;
  81680. }else{
  81681. rc = SQLITE_ERROR;
  81682. }
  81683. goto vdbe_return;
  81684. }else{
  81685. sqlite3VdbeError(p,
  81686. (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
  81687. (iRollback)?"cannot rollback - no transaction is active":
  81688. "cannot commit - no transaction is active"));
  81689. rc = SQLITE_ERROR;
  81690. goto abort_due_to_error;
  81691. }
  81692. break;
  81693. }
  81694. /* Opcode: Transaction P1 P2 P3 P4 P5
  81695. **
  81696. ** Begin a transaction on database P1 if a transaction is not already
  81697. ** active.
  81698. ** If P2 is non-zero, then a write-transaction is started, or if a
  81699. ** read-transaction is already active, it is upgraded to a write-transaction.
  81700. ** If P2 is zero, then a read-transaction is started.
  81701. **
  81702. ** P1 is the index of the database file on which the transaction is
  81703. ** started. Index 0 is the main database file and index 1 is the
  81704. ** file used for temporary tables. Indices of 2 or more are used for
  81705. ** attached databases.
  81706. **
  81707. ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
  81708. ** true (this flag is set if the Vdbe may modify more than one row and may
  81709. ** throw an ABORT exception), a statement transaction may also be opened.
  81710. ** More specifically, a statement transaction is opened iff the database
  81711. ** connection is currently not in autocommit mode, or if there are other
  81712. ** active statements. A statement transaction allows the changes made by this
  81713. ** VDBE to be rolled back after an error without having to roll back the
  81714. ** entire transaction. If no error is encountered, the statement transaction
  81715. ** will automatically commit when the VDBE halts.
  81716. **
  81717. ** If P5!=0 then this opcode also checks the schema cookie against P3
  81718. ** and the schema generation counter against P4.
  81719. ** The cookie changes its value whenever the database schema changes.
  81720. ** This operation is used to detect when that the cookie has changed
  81721. ** and that the current process needs to reread the schema. If the schema
  81722. ** cookie in P3 differs from the schema cookie in the database header or
  81723. ** if the schema generation counter in P4 differs from the current
  81724. ** generation counter, then an SQLITE_SCHEMA error is raised and execution
  81725. ** halts. The sqlite3_step() wrapper function might then reprepare the
  81726. ** statement and rerun it from the beginning.
  81727. */
  81728. case OP_Transaction: {
  81729. Btree *pBt;
  81730. int iMeta = 0;
  81731. assert( p->bIsReader );
  81732. assert( p->readOnly==0 || pOp->p2==0 );
  81733. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  81734. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  81735. if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){
  81736. rc = SQLITE_READONLY;
  81737. goto abort_due_to_error;
  81738. }
  81739. pBt = db->aDb[pOp->p1].pBt;
  81740. if( pBt ){
  81741. rc = sqlite3BtreeBeginTrans(pBt, pOp->p2, &iMeta);
  81742. testcase( rc==SQLITE_BUSY_SNAPSHOT );
  81743. testcase( rc==SQLITE_BUSY_RECOVERY );
  81744. if( rc!=SQLITE_OK ){
  81745. if( (rc&0xff)==SQLITE_BUSY ){
  81746. p->pc = (int)(pOp - aOp);
  81747. p->rc = rc;
  81748. goto vdbe_return;
  81749. }
  81750. goto abort_due_to_error;
  81751. }
  81752. if( pOp->p2 && p->usesStmtJournal
  81753. && (db->autoCommit==0 || db->nVdbeRead>1)
  81754. ){
  81755. assert( sqlite3BtreeIsInTrans(pBt) );
  81756. if( p->iStatement==0 ){
  81757. assert( db->nStatement>=0 && db->nSavepoint>=0 );
  81758. db->nStatement++;
  81759. p->iStatement = db->nSavepoint + db->nStatement;
  81760. }
  81761. rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
  81762. if( rc==SQLITE_OK ){
  81763. rc = sqlite3BtreeBeginStmt(pBt, p->iStatement);
  81764. }
  81765. /* Store the current value of the database handles deferred constraint
  81766. ** counter. If the statement transaction needs to be rolled back,
  81767. ** the value of this counter needs to be restored too. */
  81768. p->nStmtDefCons = db->nDeferredCons;
  81769. p->nStmtDefImmCons = db->nDeferredImmCons;
  81770. }
  81771. }
  81772. assert( pOp->p5==0 || pOp->p4type==P4_INT32 );
  81773. if( pOp->p5
  81774. && (iMeta!=pOp->p3
  81775. || db->aDb[pOp->p1].pSchema->iGeneration!=pOp->p4.i)
  81776. ){
  81777. /*
  81778. ** IMPLEMENTATION-OF: R-03189-51135 As each SQL statement runs, the schema
  81779. ** version is checked to ensure that the schema has not changed since the
  81780. ** SQL statement was prepared.
  81781. */
  81782. sqlite3DbFree(db, p->zErrMsg);
  81783. p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
  81784. /* If the schema-cookie from the database file matches the cookie
  81785. ** stored with the in-memory representation of the schema, do
  81786. ** not reload the schema from the database file.
  81787. **
  81788. ** If virtual-tables are in use, this is not just an optimization.
  81789. ** Often, v-tables store their data in other SQLite tables, which
  81790. ** are queried from within xNext() and other v-table methods using
  81791. ** prepared queries. If such a query is out-of-date, we do not want to
  81792. ** discard the database schema, as the user code implementing the
  81793. ** v-table would have to be ready for the sqlite3_vtab structure itself
  81794. ** to be invalidated whenever sqlite3_step() is called from within
  81795. ** a v-table method.
  81796. */
  81797. if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
  81798. sqlite3ResetOneSchema(db, pOp->p1);
  81799. }
  81800. p->expired = 1;
  81801. rc = SQLITE_SCHEMA;
  81802. }
  81803. if( rc ) goto abort_due_to_error;
  81804. break;
  81805. }
  81806. /* Opcode: ReadCookie P1 P2 P3 * *
  81807. **
  81808. ** Read cookie number P3 from database P1 and write it into register P2.
  81809. ** P3==1 is the schema version. P3==2 is the database format.
  81810. ** P3==3 is the recommended pager cache size, and so forth. P1==0 is
  81811. ** the main database file and P1==1 is the database file used to store
  81812. ** temporary tables.
  81813. **
  81814. ** There must be a read-lock on the database (either a transaction
  81815. ** must be started or there must be an open cursor) before
  81816. ** executing this instruction.
  81817. */
  81818. case OP_ReadCookie: { /* out2 */
  81819. int iMeta;
  81820. int iDb;
  81821. int iCookie;
  81822. assert( p->bIsReader );
  81823. iDb = pOp->p1;
  81824. iCookie = pOp->p3;
  81825. assert( pOp->p3<SQLITE_N_BTREE_META );
  81826. assert( iDb>=0 && iDb<db->nDb );
  81827. assert( db->aDb[iDb].pBt!=0 );
  81828. assert( DbMaskTest(p->btreeMask, iDb) );
  81829. sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta);
  81830. pOut = out2Prerelease(p, pOp);
  81831. pOut->u.i = iMeta;
  81832. break;
  81833. }
  81834. /* Opcode: SetCookie P1 P2 P3 * *
  81835. **
  81836. ** Write the integer value P3 into cookie number P2 of database P1.
  81837. ** P2==1 is the schema version. P2==2 is the database format.
  81838. ** P2==3 is the recommended pager cache
  81839. ** size, and so forth. P1==0 is the main database file and P1==1 is the
  81840. ** database file used to store temporary tables.
  81841. **
  81842. ** A transaction must be started before executing this opcode.
  81843. */
  81844. case OP_SetCookie: {
  81845. Db *pDb;
  81846. sqlite3VdbeIncrWriteCounter(p, 0);
  81847. assert( pOp->p2<SQLITE_N_BTREE_META );
  81848. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  81849. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  81850. assert( p->readOnly==0 );
  81851. pDb = &db->aDb[pOp->p1];
  81852. assert( pDb->pBt!=0 );
  81853. assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
  81854. /* See note about index shifting on OP_ReadCookie */
  81855. rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, pOp->p3);
  81856. if( pOp->p2==BTREE_SCHEMA_VERSION ){
  81857. /* When the schema cookie changes, record the new cookie internally */
  81858. pDb->pSchema->schema_cookie = pOp->p3;
  81859. db->mDbFlags |= DBFLAG_SchemaChange;
  81860. }else if( pOp->p2==BTREE_FILE_FORMAT ){
  81861. /* Record changes in the file format */
  81862. pDb->pSchema->file_format = pOp->p3;
  81863. }
  81864. if( pOp->p1==1 ){
  81865. /* Invalidate all prepared statements whenever the TEMP database
  81866. ** schema is changed. Ticket #1644 */
  81867. sqlite3ExpirePreparedStatements(db, 0);
  81868. p->expired = 0;
  81869. }
  81870. if( rc ) goto abort_due_to_error;
  81871. break;
  81872. }
  81873. /* Opcode: OpenRead P1 P2 P3 P4 P5
  81874. ** Synopsis: root=P2 iDb=P3
  81875. **
  81876. ** Open a read-only cursor for the database table whose root page is
  81877. ** P2 in a database file. The database file is determined by P3.
  81878. ** P3==0 means the main database, P3==1 means the database used for
  81879. ** temporary tables, and P3>1 means used the corresponding attached
  81880. ** database. Give the new cursor an identifier of P1. The P1
  81881. ** values need not be contiguous but all P1 values should be small integers.
  81882. ** It is an error for P1 to be negative.
  81883. **
  81884. ** Allowed P5 bits:
  81885. ** <ul>
  81886. ** <li> <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for
  81887. ** equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT
  81888. ** of OP_SeekLE/OP_IdxGT)
  81889. ** </ul>
  81890. **
  81891. ** The P4 value may be either an integer (P4_INT32) or a pointer to
  81892. ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
  81893. ** object, then table being opened must be an [index b-tree] where the
  81894. ** KeyInfo object defines the content and collating
  81895. ** sequence of that index b-tree. Otherwise, if P4 is an integer
  81896. ** value, then the table being opened must be a [table b-tree] with a
  81897. ** number of columns no less than the value of P4.
  81898. **
  81899. ** See also: OpenWrite, ReopenIdx
  81900. */
  81901. /* Opcode: ReopenIdx P1 P2 P3 P4 P5
  81902. ** Synopsis: root=P2 iDb=P3
  81903. **
  81904. ** The ReopenIdx opcode works like OP_OpenRead except that it first
  81905. ** checks to see if the cursor on P1 is already open on the same
  81906. ** b-tree and if it is this opcode becomes a no-op. In other words,
  81907. ** if the cursor is already open, do not reopen it.
  81908. **
  81909. ** The ReopenIdx opcode may only be used with P5==0 or P5==OPFLAG_SEEKEQ
  81910. ** and with P4 being a P4_KEYINFO object. Furthermore, the P3 value must
  81911. ** be the same as every other ReopenIdx or OpenRead for the same cursor
  81912. ** number.
  81913. **
  81914. ** Allowed P5 bits:
  81915. ** <ul>
  81916. ** <li> <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for
  81917. ** equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT
  81918. ** of OP_SeekLE/OP_IdxGT)
  81919. ** </ul>
  81920. **
  81921. ** See also: OP_OpenRead, OP_OpenWrite
  81922. */
  81923. /* Opcode: OpenWrite P1 P2 P3 P4 P5
  81924. ** Synopsis: root=P2 iDb=P3
  81925. **
  81926. ** Open a read/write cursor named P1 on the table or index whose root
  81927. ** page is P2 (or whose root page is held in register P2 if the
  81928. ** OPFLAG_P2ISREG bit is set in P5 - see below).
  81929. **
  81930. ** The P4 value may be either an integer (P4_INT32) or a pointer to
  81931. ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
  81932. ** object, then table being opened must be an [index b-tree] where the
  81933. ** KeyInfo object defines the content and collating
  81934. ** sequence of that index b-tree. Otherwise, if P4 is an integer
  81935. ** value, then the table being opened must be a [table b-tree] with a
  81936. ** number of columns no less than the value of P4.
  81937. **
  81938. ** Allowed P5 bits:
  81939. ** <ul>
  81940. ** <li> <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for
  81941. ** equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT
  81942. ** of OP_SeekLE/OP_IdxGT)
  81943. ** <li> <b>0x08 OPFLAG_FORDELETE</b>: This cursor is used only to seek
  81944. ** and subsequently delete entries in an index btree. This is a
  81945. ** hint to the storage engine that the storage engine is allowed to
  81946. ** ignore. The hint is not used by the official SQLite b*tree storage
  81947. ** engine, but is used by COMDB2.
  81948. ** <li> <b>0x10 OPFLAG_P2ISREG</b>: Use the content of register P2
  81949. ** as the root page, not the value of P2 itself.
  81950. ** </ul>
  81951. **
  81952. ** This instruction works like OpenRead except that it opens the cursor
  81953. ** in read/write mode.
  81954. **
  81955. ** See also: OP_OpenRead, OP_ReopenIdx
  81956. */
  81957. case OP_ReopenIdx: {
  81958. int nField;
  81959. KeyInfo *pKeyInfo;
  81960. int p2;
  81961. int iDb;
  81962. int wrFlag;
  81963. Btree *pX;
  81964. VdbeCursor *pCur;
  81965. Db *pDb;
  81966. assert( pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
  81967. assert( pOp->p4type==P4_KEYINFO );
  81968. pCur = p->apCsr[pOp->p1];
  81969. if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){
  81970. assert( pCur->iDb==pOp->p3 ); /* Guaranteed by the code generator */
  81971. goto open_cursor_set_hints;
  81972. }
  81973. /* If the cursor is not currently open or is open on a different
  81974. ** index, then fall through into OP_OpenRead to force a reopen */
  81975. case OP_OpenRead:
  81976. case OP_OpenWrite:
  81977. assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
  81978. assert( p->bIsReader );
  81979. assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx
  81980. || p->readOnly==0 );
  81981. if( p->expired==1 ){
  81982. rc = SQLITE_ABORT_ROLLBACK;
  81983. goto abort_due_to_error;
  81984. }
  81985. nField = 0;
  81986. pKeyInfo = 0;
  81987. p2 = pOp->p2;
  81988. iDb = pOp->p3;
  81989. assert( iDb>=0 && iDb<db->nDb );
  81990. assert( DbMaskTest(p->btreeMask, iDb) );
  81991. pDb = &db->aDb[iDb];
  81992. pX = pDb->pBt;
  81993. assert( pX!=0 );
  81994. if( pOp->opcode==OP_OpenWrite ){
  81995. assert( OPFLAG_FORDELETE==BTREE_FORDELETE );
  81996. wrFlag = BTREE_WRCSR | (pOp->p5 & OPFLAG_FORDELETE);
  81997. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  81998. if( pDb->pSchema->file_format < p->minWriteFileFormat ){
  81999. p->minWriteFileFormat = pDb->pSchema->file_format;
  82000. }
  82001. }else{
  82002. wrFlag = 0;
  82003. }
  82004. if( pOp->p5 & OPFLAG_P2ISREG ){
  82005. assert( p2>0 );
  82006. assert( p2<=(p->nMem+1 - p->nCursor) );
  82007. assert( pOp->opcode==OP_OpenWrite );
  82008. pIn2 = &aMem[p2];
  82009. assert( memIsValid(pIn2) );
  82010. assert( (pIn2->flags & MEM_Int)!=0 );
  82011. sqlite3VdbeMemIntegerify(pIn2);
  82012. p2 = (int)pIn2->u.i;
  82013. /* The p2 value always comes from a prior OP_CreateBtree opcode and
  82014. ** that opcode will always set the p2 value to 2 or more or else fail.
  82015. ** If there were a failure, the prepared statement would have halted
  82016. ** before reaching this instruction. */
  82017. assert( p2>=2 );
  82018. }
  82019. if( pOp->p4type==P4_KEYINFO ){
  82020. pKeyInfo = pOp->p4.pKeyInfo;
  82021. assert( pKeyInfo->enc==ENC(db) );
  82022. assert( pKeyInfo->db==db );
  82023. nField = pKeyInfo->nAllField;
  82024. }else if( pOp->p4type==P4_INT32 ){
  82025. nField = pOp->p4.i;
  82026. }
  82027. assert( pOp->p1>=0 );
  82028. assert( nField>=0 );
  82029. testcase( nField==0 ); /* Table with INTEGER PRIMARY KEY and nothing else */
  82030. pCur = allocateCursor(p, pOp->p1, nField, iDb, CURTYPE_BTREE);
  82031. if( pCur==0 ) goto no_mem;
  82032. pCur->nullRow = 1;
  82033. pCur->isOrdered = 1;
  82034. pCur->pgnoRoot = p2;
  82035. #ifdef SQLITE_DEBUG
  82036. pCur->wrFlag = wrFlag;
  82037. #endif
  82038. rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->uc.pCursor);
  82039. pCur->pKeyInfo = pKeyInfo;
  82040. /* Set the VdbeCursor.isTable variable. Previous versions of
  82041. ** SQLite used to check if the root-page flags were sane at this point
  82042. ** and report database corruption if they were not, but this check has
  82043. ** since moved into the btree layer. */
  82044. pCur->isTable = pOp->p4type!=P4_KEYINFO;
  82045. open_cursor_set_hints:
  82046. assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
  82047. assert( OPFLAG_SEEKEQ==BTREE_SEEK_EQ );
  82048. testcase( pOp->p5 & OPFLAG_BULKCSR );
  82049. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  82050. testcase( pOp->p2 & OPFLAG_SEEKEQ );
  82051. #endif
  82052. sqlite3BtreeCursorHintFlags(pCur->uc.pCursor,
  82053. (pOp->p5 & (OPFLAG_BULKCSR|OPFLAG_SEEKEQ)));
  82054. if( rc ) goto abort_due_to_error;
  82055. break;
  82056. }
  82057. /* Opcode: OpenDup P1 P2 * * *
  82058. **
  82059. ** Open a new cursor P1 that points to the same ephemeral table as
  82060. ** cursor P2. The P2 cursor must have been opened by a prior OP_OpenEphemeral
  82061. ** opcode. Only ephemeral cursors may be duplicated.
  82062. **
  82063. ** Duplicate ephemeral cursors are used for self-joins of materialized views.
  82064. */
  82065. case OP_OpenDup: {
  82066. VdbeCursor *pOrig; /* The original cursor to be duplicated */
  82067. VdbeCursor *pCx; /* The new cursor */
  82068. pOrig = p->apCsr[pOp->p2];
  82069. assert( pOrig->pBtx!=0 ); /* Only ephemeral cursors can be duplicated */
  82070. pCx = allocateCursor(p, pOp->p1, pOrig->nField, -1, CURTYPE_BTREE);
  82071. if( pCx==0 ) goto no_mem;
  82072. pCx->nullRow = 1;
  82073. pCx->isEphemeral = 1;
  82074. pCx->pKeyInfo = pOrig->pKeyInfo;
  82075. pCx->isTable = pOrig->isTable;
  82076. pCx->pgnoRoot = pOrig->pgnoRoot;
  82077. pCx->isOrdered = pOrig->isOrdered;
  82078. rc = sqlite3BtreeCursor(pOrig->pBtx, pCx->pgnoRoot, BTREE_WRCSR,
  82079. pCx->pKeyInfo, pCx->uc.pCursor);
  82080. /* The sqlite3BtreeCursor() routine can only fail for the first cursor
  82081. ** opened for a database. Since there is already an open cursor when this
  82082. ** opcode is run, the sqlite3BtreeCursor() cannot fail */
  82083. assert( rc==SQLITE_OK );
  82084. break;
  82085. }
  82086. /* Opcode: OpenEphemeral P1 P2 * P4 P5
  82087. ** Synopsis: nColumn=P2
  82088. **
  82089. ** Open a new cursor P1 to a transient table.
  82090. ** The cursor is always opened read/write even if
  82091. ** the main database is read-only. The ephemeral
  82092. ** table is deleted automatically when the cursor is closed.
  82093. **
  82094. ** If the cursor P1 is already opened on an ephemeral table, the table
  82095. ** is cleared (all content is erased).
  82096. **
  82097. ** P2 is the number of columns in the ephemeral table.
  82098. ** The cursor points to a BTree table if P4==0 and to a BTree index
  82099. ** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure
  82100. ** that defines the format of keys in the index.
  82101. **
  82102. ** The P5 parameter can be a mask of the BTREE_* flags defined
  82103. ** in btree.h. These flags control aspects of the operation of
  82104. ** the btree. The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
  82105. ** added automatically.
  82106. */
  82107. /* Opcode: OpenAutoindex P1 P2 * P4 *
  82108. ** Synopsis: nColumn=P2
  82109. **
  82110. ** This opcode works the same as OP_OpenEphemeral. It has a
  82111. ** different name to distinguish its use. Tables created using
  82112. ** by this opcode will be used for automatically created transient
  82113. ** indices in joins.
  82114. */
  82115. case OP_OpenAutoindex:
  82116. case OP_OpenEphemeral: {
  82117. VdbeCursor *pCx;
  82118. KeyInfo *pKeyInfo;
  82119. static const int vfsFlags =
  82120. SQLITE_OPEN_READWRITE |
  82121. SQLITE_OPEN_CREATE |
  82122. SQLITE_OPEN_EXCLUSIVE |
  82123. SQLITE_OPEN_DELETEONCLOSE |
  82124. SQLITE_OPEN_TRANSIENT_DB;
  82125. assert( pOp->p1>=0 );
  82126. assert( pOp->p2>=0 );
  82127. pCx = p->apCsr[pOp->p1];
  82128. if( pCx ){
  82129. /* If the ephermeral table is already open, erase all existing content
  82130. ** so that the table is empty again, rather than creating a new table. */
  82131. assert( pCx->isEphemeral );
  82132. pCx->seqCount = 0;
  82133. pCx->cacheStatus = CACHE_STALE;
  82134. if( pCx->pBtx ){
  82135. rc = sqlite3BtreeClearTable(pCx->pBtx, pCx->pgnoRoot, 0);
  82136. }
  82137. }else{
  82138. pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_BTREE);
  82139. if( pCx==0 ) goto no_mem;
  82140. pCx->isEphemeral = 1;
  82141. rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBtx,
  82142. BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5,
  82143. vfsFlags);
  82144. if( rc==SQLITE_OK ){
  82145. rc = sqlite3BtreeBeginTrans(pCx->pBtx, 1, 0);
  82146. }
  82147. if( rc==SQLITE_OK ){
  82148. /* If a transient index is required, create it by calling
  82149. ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
  82150. ** opening it. If a transient table is required, just use the
  82151. ** automatically created table with root-page 1 (an BLOB_INTKEY table).
  82152. */
  82153. if( (pCx->pKeyInfo = pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
  82154. assert( pOp->p4type==P4_KEYINFO );
  82155. rc = sqlite3BtreeCreateTable(pCx->pBtx, (int*)&pCx->pgnoRoot,
  82156. BTREE_BLOBKEY | pOp->p5);
  82157. if( rc==SQLITE_OK ){
  82158. assert( pCx->pgnoRoot==MASTER_ROOT+1 );
  82159. assert( pKeyInfo->db==db );
  82160. assert( pKeyInfo->enc==ENC(db) );
  82161. rc = sqlite3BtreeCursor(pCx->pBtx, pCx->pgnoRoot, BTREE_WRCSR,
  82162. pKeyInfo, pCx->uc.pCursor);
  82163. }
  82164. pCx->isTable = 0;
  82165. }else{
  82166. pCx->pgnoRoot = MASTER_ROOT;
  82167. rc = sqlite3BtreeCursor(pCx->pBtx, MASTER_ROOT, BTREE_WRCSR,
  82168. 0, pCx->uc.pCursor);
  82169. pCx->isTable = 1;
  82170. }
  82171. }
  82172. pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
  82173. }
  82174. if( rc ) goto abort_due_to_error;
  82175. pCx->nullRow = 1;
  82176. break;
  82177. }
  82178. /* Opcode: SorterOpen P1 P2 P3 P4 *
  82179. **
  82180. ** This opcode works like OP_OpenEphemeral except that it opens
  82181. ** a transient index that is specifically designed to sort large
  82182. ** tables using an external merge-sort algorithm.
  82183. **
  82184. ** If argument P3 is non-zero, then it indicates that the sorter may
  82185. ** assume that a stable sort considering the first P3 fields of each
  82186. ** key is sufficient to produce the required results.
  82187. */
  82188. case OP_SorterOpen: {
  82189. VdbeCursor *pCx;
  82190. assert( pOp->p1>=0 );
  82191. assert( pOp->p2>=0 );
  82192. pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_SORTER);
  82193. if( pCx==0 ) goto no_mem;
  82194. pCx->pKeyInfo = pOp->p4.pKeyInfo;
  82195. assert( pCx->pKeyInfo->db==db );
  82196. assert( pCx->pKeyInfo->enc==ENC(db) );
  82197. rc = sqlite3VdbeSorterInit(db, pOp->p3, pCx);
  82198. if( rc ) goto abort_due_to_error;
  82199. break;
  82200. }
  82201. /* Opcode: SequenceTest P1 P2 * * *
  82202. ** Synopsis: if( cursor[P1].ctr++ ) pc = P2
  82203. **
  82204. ** P1 is a sorter cursor. If the sequence counter is currently zero, jump
  82205. ** to P2. Regardless of whether or not the jump is taken, increment the
  82206. ** the sequence value.
  82207. */
  82208. case OP_SequenceTest: {
  82209. VdbeCursor *pC;
  82210. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  82211. pC = p->apCsr[pOp->p1];
  82212. assert( isSorter(pC) );
  82213. if( (pC->seqCount++)==0 ){
  82214. goto jump_to_p2;
  82215. }
  82216. break;
  82217. }
  82218. /* Opcode: OpenPseudo P1 P2 P3 * *
  82219. ** Synopsis: P3 columns in r[P2]
  82220. **
  82221. ** Open a new cursor that points to a fake table that contains a single
  82222. ** row of data. The content of that one row is the content of memory
  82223. ** register P2. In other words, cursor P1 becomes an alias for the
  82224. ** MEM_Blob content contained in register P2.
  82225. **
  82226. ** A pseudo-table created by this opcode is used to hold a single
  82227. ** row output from the sorter so that the row can be decomposed into
  82228. ** individual columns using the OP_Column opcode. The OP_Column opcode
  82229. ** is the only cursor opcode that works with a pseudo-table.
  82230. **
  82231. ** P3 is the number of fields in the records that will be stored by
  82232. ** the pseudo-table.
  82233. */
  82234. case OP_OpenPseudo: {
  82235. VdbeCursor *pCx;
  82236. assert( pOp->p1>=0 );
  82237. assert( pOp->p3>=0 );
  82238. pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, CURTYPE_PSEUDO);
  82239. if( pCx==0 ) goto no_mem;
  82240. pCx->nullRow = 1;
  82241. pCx->seekResult = pOp->p2;
  82242. pCx->isTable = 1;
  82243. /* Give this pseudo-cursor a fake BtCursor pointer so that pCx
  82244. ** can be safely passed to sqlite3VdbeCursorMoveto(). This avoids a test
  82245. ** for pCx->eCurType==CURTYPE_BTREE inside of sqlite3VdbeCursorMoveto()
  82246. ** which is a performance optimization */
  82247. pCx->uc.pCursor = sqlite3BtreeFakeValidCursor();
  82248. assert( pOp->p5==0 );
  82249. break;
  82250. }
  82251. /* Opcode: Close P1 * * * *
  82252. **
  82253. ** Close a cursor previously opened as P1. If P1 is not
  82254. ** currently open, this instruction is a no-op.
  82255. */
  82256. case OP_Close: {
  82257. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  82258. sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
  82259. p->apCsr[pOp->p1] = 0;
  82260. break;
  82261. }
  82262. #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
  82263. /* Opcode: ColumnsUsed P1 * * P4 *
  82264. **
  82265. ** This opcode (which only exists if SQLite was compiled with
  82266. ** SQLITE_ENABLE_COLUMN_USED_MASK) identifies which columns of the
  82267. ** table or index for cursor P1 are used. P4 is a 64-bit integer
  82268. ** (P4_INT64) in which the first 63 bits are one for each of the
  82269. ** first 63 columns of the table or index that are actually used
  82270. ** by the cursor. The high-order bit is set if any column after
  82271. ** the 64th is used.
  82272. */
  82273. case OP_ColumnsUsed: {
  82274. VdbeCursor *pC;
  82275. pC = p->apCsr[pOp->p1];
  82276. assert( pC->eCurType==CURTYPE_BTREE );
  82277. pC->maskUsed = *(u64*)pOp->p4.pI64;
  82278. break;
  82279. }
  82280. #endif
  82281. /* Opcode: SeekGE P1 P2 P3 P4 *
  82282. ** Synopsis: key=r[P3@P4]
  82283. **
  82284. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  82285. ** use the value in register P3 as the key. If cursor P1 refers
  82286. ** to an SQL index, then P3 is the first in an array of P4 registers
  82287. ** that are used as an unpacked index key.
  82288. **
  82289. ** Reposition cursor P1 so that it points to the smallest entry that
  82290. ** is greater than or equal to the key value. If there are no records
  82291. ** greater than or equal to the key and P2 is not zero, then jump to P2.
  82292. **
  82293. ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
  82294. ** opcode will always land on a record that equally equals the key, or
  82295. ** else jump immediately to P2. When the cursor is OPFLAG_SEEKEQ, this
  82296. ** opcode must be followed by an IdxLE opcode with the same arguments.
  82297. ** The IdxLE opcode will be skipped if this opcode succeeds, but the
  82298. ** IdxLE opcode will be used on subsequent loop iterations.
  82299. **
  82300. ** This opcode leaves the cursor configured to move in forward order,
  82301. ** from the beginning toward the end. In other words, the cursor is
  82302. ** configured to use Next, not Prev.
  82303. **
  82304. ** See also: Found, NotFound, SeekLt, SeekGt, SeekLe
  82305. */
  82306. /* Opcode: SeekGT P1 P2 P3 P4 *
  82307. ** Synopsis: key=r[P3@P4]
  82308. **
  82309. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  82310. ** use the value in register P3 as a key. If cursor P1 refers
  82311. ** to an SQL index, then P3 is the first in an array of P4 registers
  82312. ** that are used as an unpacked index key.
  82313. **
  82314. ** Reposition cursor P1 so that it points to the smallest entry that
  82315. ** is greater than the key value. If there are no records greater than
  82316. ** the key and P2 is not zero, then jump to P2.
  82317. **
  82318. ** This opcode leaves the cursor configured to move in forward order,
  82319. ** from the beginning toward the end. In other words, the cursor is
  82320. ** configured to use Next, not Prev.
  82321. **
  82322. ** See also: Found, NotFound, SeekLt, SeekGe, SeekLe
  82323. */
  82324. /* Opcode: SeekLT P1 P2 P3 P4 *
  82325. ** Synopsis: key=r[P3@P4]
  82326. **
  82327. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  82328. ** use the value in register P3 as a key. If cursor P1 refers
  82329. ** to an SQL index, then P3 is the first in an array of P4 registers
  82330. ** that are used as an unpacked index key.
  82331. **
  82332. ** Reposition cursor P1 so that it points to the largest entry that
  82333. ** is less than the key value. If there are no records less than
  82334. ** the key and P2 is not zero, then jump to P2.
  82335. **
  82336. ** This opcode leaves the cursor configured to move in reverse order,
  82337. ** from the end toward the beginning. In other words, the cursor is
  82338. ** configured to use Prev, not Next.
  82339. **
  82340. ** See also: Found, NotFound, SeekGt, SeekGe, SeekLe
  82341. */
  82342. /* Opcode: SeekLE P1 P2 P3 P4 *
  82343. ** Synopsis: key=r[P3@P4]
  82344. **
  82345. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  82346. ** use the value in register P3 as a key. If cursor P1 refers
  82347. ** to an SQL index, then P3 is the first in an array of P4 registers
  82348. ** that are used as an unpacked index key.
  82349. **
  82350. ** Reposition cursor P1 so that it points to the largest entry that
  82351. ** is less than or equal to the key value. If there are no records
  82352. ** less than or equal to the key and P2 is not zero, then jump to P2.
  82353. **
  82354. ** This opcode leaves the cursor configured to move in reverse order,
  82355. ** from the end toward the beginning. In other words, the cursor is
  82356. ** configured to use Prev, not Next.
  82357. **
  82358. ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
  82359. ** opcode will always land on a record that equally equals the key, or
  82360. ** else jump immediately to P2. When the cursor is OPFLAG_SEEKEQ, this
  82361. ** opcode must be followed by an IdxGE opcode with the same arguments.
  82362. ** The IdxGE opcode will be skipped if this opcode succeeds, but the
  82363. ** IdxGE opcode will be used on subsequent loop iterations.
  82364. **
  82365. ** See also: Found, NotFound, SeekGt, SeekGe, SeekLt
  82366. */
  82367. case OP_SeekLT: /* jump, in3, group */
  82368. case OP_SeekLE: /* jump, in3, group */
  82369. case OP_SeekGE: /* jump, in3, group */
  82370. case OP_SeekGT: { /* jump, in3, group */
  82371. int res; /* Comparison result */
  82372. int oc; /* Opcode */
  82373. VdbeCursor *pC; /* The cursor to seek */
  82374. UnpackedRecord r; /* The key to seek for */
  82375. int nField; /* Number of columns or fields in the key */
  82376. i64 iKey; /* The rowid we are to seek to */
  82377. int eqOnly; /* Only interested in == results */
  82378. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  82379. assert( pOp->p2!=0 );
  82380. pC = p->apCsr[pOp->p1];
  82381. assert( pC!=0 );
  82382. assert( pC->eCurType==CURTYPE_BTREE );
  82383. assert( OP_SeekLE == OP_SeekLT+1 );
  82384. assert( OP_SeekGE == OP_SeekLT+2 );
  82385. assert( OP_SeekGT == OP_SeekLT+3 );
  82386. assert( pC->isOrdered );
  82387. assert( pC->uc.pCursor!=0 );
  82388. oc = pOp->opcode;
  82389. eqOnly = 0;
  82390. pC->nullRow = 0;
  82391. #ifdef SQLITE_DEBUG
  82392. pC->seekOp = pOp->opcode;
  82393. #endif
  82394. pC->deferredMoveto = 0;
  82395. pC->cacheStatus = CACHE_STALE;
  82396. if( pC->isTable ){
  82397. /* The BTREE_SEEK_EQ flag is only set on index cursors */
  82398. assert( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ)==0
  82399. || CORRUPT_DB );
  82400. /* The input value in P3 might be of any type: integer, real, string,
  82401. ** blob, or NULL. But it needs to be an integer before we can do
  82402. ** the seek, so convert it. */
  82403. pIn3 = &aMem[pOp->p3];
  82404. if( (pIn3->flags & (MEM_Int|MEM_Real|MEM_IntReal|MEM_Str))==MEM_Str ){
  82405. applyNumericAffinity(pIn3, 0);
  82406. }
  82407. iKey = sqlite3VdbeIntValue(pIn3);
  82408. /* If the P3 value could not be converted into an integer without
  82409. ** loss of information, then special processing is required... */
  82410. if( (pIn3->flags & (MEM_Int|MEM_IntReal))==0 ){
  82411. if( (pIn3->flags & MEM_Real)==0 ){
  82412. if( (pIn3->flags & MEM_Null) || oc>=OP_SeekGE ){
  82413. VdbeBranchTaken(1,2); goto jump_to_p2;
  82414. break;
  82415. }else{
  82416. rc = sqlite3BtreeLast(pC->uc.pCursor, &res);
  82417. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  82418. goto seek_not_found;
  82419. }
  82420. }else
  82421. /* If the approximation iKey is larger than the actual real search
  82422. ** term, substitute >= for > and < for <=. e.g. if the search term
  82423. ** is 4.9 and the integer approximation 5:
  82424. **
  82425. ** (x > 4.9) -> (x >= 5)
  82426. ** (x <= 4.9) -> (x < 5)
  82427. */
  82428. if( pIn3->u.r<(double)iKey ){
  82429. assert( OP_SeekGE==(OP_SeekGT-1) );
  82430. assert( OP_SeekLT==(OP_SeekLE-1) );
  82431. assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) );
  82432. if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--;
  82433. }
  82434. /* If the approximation iKey is smaller than the actual real search
  82435. ** term, substitute <= for < and > for >=. */
  82436. else if( pIn3->u.r>(double)iKey ){
  82437. assert( OP_SeekLE==(OP_SeekLT+1) );
  82438. assert( OP_SeekGT==(OP_SeekGE+1) );
  82439. assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) );
  82440. if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++;
  82441. }
  82442. }
  82443. rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)iKey, 0, &res);
  82444. pC->movetoTarget = iKey; /* Used by OP_Delete */
  82445. if( rc!=SQLITE_OK ){
  82446. goto abort_due_to_error;
  82447. }
  82448. }else{
  82449. /* For a cursor with the BTREE_SEEK_EQ hint, only the OP_SeekGE and
  82450. ** OP_SeekLE opcodes are allowed, and these must be immediately followed
  82451. ** by an OP_IdxGT or OP_IdxLT opcode, respectively, with the same key.
  82452. */
  82453. if( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ) ){
  82454. eqOnly = 1;
  82455. assert( pOp->opcode==OP_SeekGE || pOp->opcode==OP_SeekLE );
  82456. assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
  82457. assert( pOp[1].p1==pOp[0].p1 );
  82458. assert( pOp[1].p2==pOp[0].p2 );
  82459. assert( pOp[1].p3==pOp[0].p3 );
  82460. assert( pOp[1].p4.i==pOp[0].p4.i );
  82461. }
  82462. nField = pOp->p4.i;
  82463. assert( pOp->p4type==P4_INT32 );
  82464. assert( nField>0 );
  82465. r.pKeyInfo = pC->pKeyInfo;
  82466. r.nField = (u16)nField;
  82467. /* The next line of code computes as follows, only faster:
  82468. ** if( oc==OP_SeekGT || oc==OP_SeekLE ){
  82469. ** r.default_rc = -1;
  82470. ** }else{
  82471. ** r.default_rc = +1;
  82472. ** }
  82473. */
  82474. r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1);
  82475. assert( oc!=OP_SeekGT || r.default_rc==-1 );
  82476. assert( oc!=OP_SeekLE || r.default_rc==-1 );
  82477. assert( oc!=OP_SeekGE || r.default_rc==+1 );
  82478. assert( oc!=OP_SeekLT || r.default_rc==+1 );
  82479. r.aMem = &aMem[pOp->p3];
  82480. #ifdef SQLITE_DEBUG
  82481. { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
  82482. #endif
  82483. r.eqSeen = 0;
  82484. rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, &r, 0, 0, &res);
  82485. if( rc!=SQLITE_OK ){
  82486. goto abort_due_to_error;
  82487. }
  82488. if( eqOnly && r.eqSeen==0 ){
  82489. assert( res!=0 );
  82490. goto seek_not_found;
  82491. }
  82492. }
  82493. #ifdef SQLITE_TEST
  82494. sqlite3_search_count++;
  82495. #endif
  82496. if( oc>=OP_SeekGE ){ assert( oc==OP_SeekGE || oc==OP_SeekGT );
  82497. if( res<0 || (res==0 && oc==OP_SeekGT) ){
  82498. res = 0;
  82499. rc = sqlite3BtreeNext(pC->uc.pCursor, 0);
  82500. if( rc!=SQLITE_OK ){
  82501. if( rc==SQLITE_DONE ){
  82502. rc = SQLITE_OK;
  82503. res = 1;
  82504. }else{
  82505. goto abort_due_to_error;
  82506. }
  82507. }
  82508. }else{
  82509. res = 0;
  82510. }
  82511. }else{
  82512. assert( oc==OP_SeekLT || oc==OP_SeekLE );
  82513. if( res>0 || (res==0 && oc==OP_SeekLT) ){
  82514. res = 0;
  82515. rc = sqlite3BtreePrevious(pC->uc.pCursor, 0);
  82516. if( rc!=SQLITE_OK ){
  82517. if( rc==SQLITE_DONE ){
  82518. rc = SQLITE_OK;
  82519. res = 1;
  82520. }else{
  82521. goto abort_due_to_error;
  82522. }
  82523. }
  82524. }else{
  82525. /* res might be negative because the table is empty. Check to
  82526. ** see if this is the case.
  82527. */
  82528. res = sqlite3BtreeEof(pC->uc.pCursor);
  82529. }
  82530. }
  82531. seek_not_found:
  82532. assert( pOp->p2>0 );
  82533. VdbeBranchTaken(res!=0,2);
  82534. if( res ){
  82535. goto jump_to_p2;
  82536. }else if( eqOnly ){
  82537. assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
  82538. pOp++; /* Skip the OP_IdxLt or OP_IdxGT that follows */
  82539. }
  82540. break;
  82541. }
  82542. /* Opcode: SeekHit P1 P2 * * *
  82543. ** Synopsis: seekHit=P2
  82544. **
  82545. ** Set the seekHit flag on cursor P1 to the value in P2.
  82546. ** The seekHit flag is used by the IfNoHope opcode.
  82547. **
  82548. ** P1 must be a valid b-tree cursor. P2 must be a boolean value,
  82549. ** either 0 or 1.
  82550. */
  82551. case OP_SeekHit: {
  82552. VdbeCursor *pC;
  82553. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  82554. pC = p->apCsr[pOp->p1];
  82555. assert( pC!=0 );
  82556. assert( pOp->p2==0 || pOp->p2==1 );
  82557. pC->seekHit = pOp->p2 & 1;
  82558. break;
  82559. }
  82560. /* Opcode: Found P1 P2 P3 P4 *
  82561. ** Synopsis: key=r[P3@P4]
  82562. **
  82563. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  82564. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  82565. ** record.
  82566. **
  82567. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  82568. ** is a prefix of any entry in P1 then a jump is made to P2 and
  82569. ** P1 is left pointing at the matching entry.
  82570. **
  82571. ** This operation leaves the cursor in a state where it can be
  82572. ** advanced in the forward direction. The Next instruction will work,
  82573. ** but not the Prev instruction.
  82574. **
  82575. ** See also: NotFound, NoConflict, NotExists. SeekGe
  82576. */
  82577. /* Opcode: NotFound P1 P2 P3 P4 *
  82578. ** Synopsis: key=r[P3@P4]
  82579. **
  82580. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  82581. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  82582. ** record.
  82583. **
  82584. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  82585. ** is not the prefix of any entry in P1 then a jump is made to P2. If P1
  82586. ** does contain an entry whose prefix matches the P3/P4 record then control
  82587. ** falls through to the next instruction and P1 is left pointing at the
  82588. ** matching entry.
  82589. **
  82590. ** This operation leaves the cursor in a state where it cannot be
  82591. ** advanced in either direction. In other words, the Next and Prev
  82592. ** opcodes do not work after this operation.
  82593. **
  82594. ** See also: Found, NotExists, NoConflict, IfNoHope
  82595. */
  82596. /* Opcode: IfNoHope P1 P2 P3 P4 *
  82597. ** Synopsis: key=r[P3@P4]
  82598. **
  82599. ** Register P3 is the first of P4 registers that form an unpacked
  82600. ** record.
  82601. **
  82602. ** Cursor P1 is on an index btree. If the seekHit flag is set on P1, then
  82603. ** this opcode is a no-op. But if the seekHit flag of P1 is clear, then
  82604. ** check to see if there is any entry in P1 that matches the
  82605. ** prefix identified by P3 and P4. If no entry matches the prefix,
  82606. ** jump to P2. Otherwise fall through.
  82607. **
  82608. ** This opcode behaves like OP_NotFound if the seekHit
  82609. ** flag is clear and it behaves like OP_Noop if the seekHit flag is set.
  82610. **
  82611. ** This opcode is used in IN clause processing for a multi-column key.
  82612. ** If an IN clause is attached to an element of the key other than the
  82613. ** left-most element, and if there are no matches on the most recent
  82614. ** seek over the whole key, then it might be that one of the key element
  82615. ** to the left is prohibiting a match, and hence there is "no hope" of
  82616. ** any match regardless of how many IN clause elements are checked.
  82617. ** In such a case, we abandon the IN clause search early, using this
  82618. ** opcode. The opcode name comes from the fact that the
  82619. ** jump is taken if there is "no hope" of achieving a match.
  82620. **
  82621. ** See also: NotFound, SeekHit
  82622. */
  82623. /* Opcode: NoConflict P1 P2 P3 P4 *
  82624. ** Synopsis: key=r[P3@P4]
  82625. **
  82626. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  82627. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  82628. ** record.
  82629. **
  82630. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  82631. ** contains any NULL value, jump immediately to P2. If all terms of the
  82632. ** record are not-NULL then a check is done to determine if any row in the
  82633. ** P1 index btree has a matching key prefix. If there are no matches, jump
  82634. ** immediately to P2. If there is a match, fall through and leave the P1
  82635. ** cursor pointing to the matching row.
  82636. **
  82637. ** This opcode is similar to OP_NotFound with the exceptions that the
  82638. ** branch is always taken if any part of the search key input is NULL.
  82639. **
  82640. ** This operation leaves the cursor in a state where it cannot be
  82641. ** advanced in either direction. In other words, the Next and Prev
  82642. ** opcodes do not work after this operation.
  82643. **
  82644. ** See also: NotFound, Found, NotExists
  82645. */
  82646. case OP_IfNoHope: { /* jump, in3 */
  82647. VdbeCursor *pC;
  82648. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  82649. pC = p->apCsr[pOp->p1];
  82650. assert( pC!=0 );
  82651. if( pC->seekHit ) break;
  82652. /* Fall through into OP_NotFound */
  82653. }
  82654. case OP_NoConflict: /* jump, in3 */
  82655. case OP_NotFound: /* jump, in3 */
  82656. case OP_Found: { /* jump, in3 */
  82657. int alreadyExists;
  82658. int takeJump;
  82659. int ii;
  82660. VdbeCursor *pC;
  82661. int res;
  82662. UnpackedRecord *pFree;
  82663. UnpackedRecord *pIdxKey;
  82664. UnpackedRecord r;
  82665. #ifdef SQLITE_TEST
  82666. if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++;
  82667. #endif
  82668. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  82669. assert( pOp->p4type==P4_INT32 );
  82670. pC = p->apCsr[pOp->p1];
  82671. assert( pC!=0 );
  82672. #ifdef SQLITE_DEBUG
  82673. pC->seekOp = pOp->opcode;
  82674. #endif
  82675. pIn3 = &aMem[pOp->p3];
  82676. assert( pC->eCurType==CURTYPE_BTREE );
  82677. assert( pC->uc.pCursor!=0 );
  82678. assert( pC->isTable==0 );
  82679. if( pOp->p4.i>0 ){
  82680. r.pKeyInfo = pC->pKeyInfo;
  82681. r.nField = (u16)pOp->p4.i;
  82682. r.aMem = pIn3;
  82683. #ifdef SQLITE_DEBUG
  82684. for(ii=0; ii<r.nField; ii++){
  82685. assert( memIsValid(&r.aMem[ii]) );
  82686. assert( (r.aMem[ii].flags & MEM_Zero)==0 || r.aMem[ii].n==0 );
  82687. if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]);
  82688. }
  82689. #endif
  82690. pIdxKey = &r;
  82691. pFree = 0;
  82692. }else{
  82693. assert( pIn3->flags & MEM_Blob );
  82694. rc = ExpandBlob(pIn3);
  82695. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  82696. if( rc ) goto no_mem;
  82697. pFree = pIdxKey = sqlite3VdbeAllocUnpackedRecord(pC->pKeyInfo);
  82698. if( pIdxKey==0 ) goto no_mem;
  82699. sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey);
  82700. }
  82701. pIdxKey->default_rc = 0;
  82702. takeJump = 0;
  82703. if( pOp->opcode==OP_NoConflict ){
  82704. /* For the OP_NoConflict opcode, take the jump if any of the
  82705. ** input fields are NULL, since any key with a NULL will not
  82706. ** conflict */
  82707. for(ii=0; ii<pIdxKey->nField; ii++){
  82708. if( pIdxKey->aMem[ii].flags & MEM_Null ){
  82709. takeJump = 1;
  82710. break;
  82711. }
  82712. }
  82713. }
  82714. rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, pIdxKey, 0, 0, &res);
  82715. if( pFree ) sqlite3DbFreeNN(db, pFree);
  82716. if( rc!=SQLITE_OK ){
  82717. goto abort_due_to_error;
  82718. }
  82719. pC->seekResult = res;
  82720. alreadyExists = (res==0);
  82721. pC->nullRow = 1-alreadyExists;
  82722. pC->deferredMoveto = 0;
  82723. pC->cacheStatus = CACHE_STALE;
  82724. if( pOp->opcode==OP_Found ){
  82725. VdbeBranchTaken(alreadyExists!=0,2);
  82726. if( alreadyExists ) goto jump_to_p2;
  82727. }else{
  82728. VdbeBranchTaken(takeJump||alreadyExists==0,2);
  82729. if( takeJump || !alreadyExists ) goto jump_to_p2;
  82730. }
  82731. break;
  82732. }
  82733. /* Opcode: SeekRowid P1 P2 P3 * *
  82734. ** Synopsis: intkey=r[P3]
  82735. **
  82736. ** P1 is the index of a cursor open on an SQL table btree (with integer
  82737. ** keys). If register P3 does not contain an integer or if P1 does not
  82738. ** contain a record with rowid P3 then jump immediately to P2.
  82739. ** Or, if P2 is 0, raise an SQLITE_CORRUPT error. If P1 does contain
  82740. ** a record with rowid P3 then
  82741. ** leave the cursor pointing at that record and fall through to the next
  82742. ** instruction.
  82743. **
  82744. ** The OP_NotExists opcode performs the same operation, but with OP_NotExists
  82745. ** the P3 register must be guaranteed to contain an integer value. With this
  82746. ** opcode, register P3 might not contain an integer.
  82747. **
  82748. ** The OP_NotFound opcode performs the same operation on index btrees
  82749. ** (with arbitrary multi-value keys).
  82750. **
  82751. ** This opcode leaves the cursor in a state where it cannot be advanced
  82752. ** in either direction. In other words, the Next and Prev opcodes will
  82753. ** not work following this opcode.
  82754. **
  82755. ** See also: Found, NotFound, NoConflict, SeekRowid
  82756. */
  82757. /* Opcode: NotExists P1 P2 P3 * *
  82758. ** Synopsis: intkey=r[P3]
  82759. **
  82760. ** P1 is the index of a cursor open on an SQL table btree (with integer
  82761. ** keys). P3 is an integer rowid. If P1 does not contain a record with
  82762. ** rowid P3 then jump immediately to P2. Or, if P2 is 0, raise an
  82763. ** SQLITE_CORRUPT error. If P1 does contain a record with rowid P3 then
  82764. ** leave the cursor pointing at that record and fall through to the next
  82765. ** instruction.
  82766. **
  82767. ** The OP_SeekRowid opcode performs the same operation but also allows the
  82768. ** P3 register to contain a non-integer value, in which case the jump is
  82769. ** always taken. This opcode requires that P3 always contain an integer.
  82770. **
  82771. ** The OP_NotFound opcode performs the same operation on index btrees
  82772. ** (with arbitrary multi-value keys).
  82773. **
  82774. ** This opcode leaves the cursor in a state where it cannot be advanced
  82775. ** in either direction. In other words, the Next and Prev opcodes will
  82776. ** not work following this opcode.
  82777. **
  82778. ** See also: Found, NotFound, NoConflict, SeekRowid
  82779. */
  82780. case OP_SeekRowid: { /* jump, in3 */
  82781. VdbeCursor *pC;
  82782. BtCursor *pCrsr;
  82783. int res;
  82784. u64 iKey;
  82785. pIn3 = &aMem[pOp->p3];
  82786. testcase( pIn3->flags & MEM_Int );
  82787. testcase( pIn3->flags & MEM_IntReal );
  82788. if( (pIn3->flags & (MEM_Int|MEM_IntReal))==0 ){
  82789. /* Make sure pIn3->u.i contains a valid integer representation of
  82790. ** the key value, but do not change the datatype of the register, as
  82791. ** other parts of the perpared statement might be depending on the
  82792. ** current datatype. */
  82793. u16 origFlags = pIn3->flags;
  82794. int isNotInt;
  82795. applyAffinity(pIn3, SQLITE_AFF_NUMERIC, encoding);
  82796. isNotInt = (pIn3->flags & MEM_Int)==0;
  82797. pIn3->flags = origFlags;
  82798. if( isNotInt ) goto jump_to_p2;
  82799. }
  82800. /* Fall through into OP_NotExists */
  82801. case OP_NotExists: /* jump, in3 */
  82802. pIn3 = &aMem[pOp->p3];
  82803. assert( (pIn3->flags & MEM_Int)!=0 || pOp->opcode==OP_SeekRowid );
  82804. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  82805. pC = p->apCsr[pOp->p1];
  82806. assert( pC!=0 );
  82807. #ifdef SQLITE_DEBUG
  82808. if( pOp->opcode==OP_SeekRowid ) pC->seekOp = OP_SeekRowid;
  82809. #endif
  82810. assert( pC->isTable );
  82811. assert( pC->eCurType==CURTYPE_BTREE );
  82812. pCrsr = pC->uc.pCursor;
  82813. assert( pCrsr!=0 );
  82814. res = 0;
  82815. iKey = pIn3->u.i;
  82816. rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res);
  82817. assert( rc==SQLITE_OK || res==0 );
  82818. pC->movetoTarget = iKey; /* Used by OP_Delete */
  82819. pC->nullRow = 0;
  82820. pC->cacheStatus = CACHE_STALE;
  82821. pC->deferredMoveto = 0;
  82822. VdbeBranchTaken(res!=0,2);
  82823. pC->seekResult = res;
  82824. if( res!=0 ){
  82825. assert( rc==SQLITE_OK );
  82826. if( pOp->p2==0 ){
  82827. rc = SQLITE_CORRUPT_BKPT;
  82828. }else{
  82829. goto jump_to_p2;
  82830. }
  82831. }
  82832. if( rc ) goto abort_due_to_error;
  82833. break;
  82834. }
  82835. /* Opcode: Sequence P1 P2 * * *
  82836. ** Synopsis: r[P2]=cursor[P1].ctr++
  82837. **
  82838. ** Find the next available sequence number for cursor P1.
  82839. ** Write the sequence number into register P2.
  82840. ** The sequence number on the cursor is incremented after this
  82841. ** instruction.
  82842. */
  82843. case OP_Sequence: { /* out2 */
  82844. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  82845. assert( p->apCsr[pOp->p1]!=0 );
  82846. assert( p->apCsr[pOp->p1]->eCurType!=CURTYPE_VTAB );
  82847. pOut = out2Prerelease(p, pOp);
  82848. pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
  82849. break;
  82850. }
  82851. /* Opcode: NewRowid P1 P2 P3 * *
  82852. ** Synopsis: r[P2]=rowid
  82853. **
  82854. ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
  82855. ** The record number is not previously used as a key in the database
  82856. ** table that cursor P1 points to. The new record number is written
  82857. ** written to register P2.
  82858. **
  82859. ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
  82860. ** the largest previously generated record number. No new record numbers are
  82861. ** allowed to be less than this value. When this value reaches its maximum,
  82862. ** an SQLITE_FULL error is generated. The P3 register is updated with the '
  82863. ** generated record number. This P3 mechanism is used to help implement the
  82864. ** AUTOINCREMENT feature.
  82865. */
  82866. case OP_NewRowid: { /* out2 */
  82867. i64 v; /* The new rowid */
  82868. VdbeCursor *pC; /* Cursor of table to get the new rowid */
  82869. int res; /* Result of an sqlite3BtreeLast() */
  82870. int cnt; /* Counter to limit the number of searches */
  82871. Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */
  82872. VdbeFrame *pFrame; /* Root frame of VDBE */
  82873. v = 0;
  82874. res = 0;
  82875. pOut = out2Prerelease(p, pOp);
  82876. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  82877. pC = p->apCsr[pOp->p1];
  82878. assert( pC!=0 );
  82879. assert( pC->isTable );
  82880. assert( pC->eCurType==CURTYPE_BTREE );
  82881. assert( pC->uc.pCursor!=0 );
  82882. {
  82883. /* The next rowid or record number (different terms for the same
  82884. ** thing) is obtained in a two-step algorithm.
  82885. **
  82886. ** First we attempt to find the largest existing rowid and add one
  82887. ** to that. But if the largest existing rowid is already the maximum
  82888. ** positive integer, we have to fall through to the second
  82889. ** probabilistic algorithm
  82890. **
  82891. ** The second algorithm is to select a rowid at random and see if
  82892. ** it already exists in the table. If it does not exist, we have
  82893. ** succeeded. If the random rowid does exist, we select a new one
  82894. ** and try again, up to 100 times.
  82895. */
  82896. assert( pC->isTable );
  82897. #ifdef SQLITE_32BIT_ROWID
  82898. # define MAX_ROWID 0x7fffffff
  82899. #else
  82900. /* Some compilers complain about constants of the form 0x7fffffffffffffff.
  82901. ** Others complain about 0x7ffffffffffffffffLL. The following macro seems
  82902. ** to provide the constant while making all compilers happy.
  82903. */
  82904. # define MAX_ROWID (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
  82905. #endif
  82906. if( !pC->useRandomRowid ){
  82907. rc = sqlite3BtreeLast(pC->uc.pCursor, &res);
  82908. if( rc!=SQLITE_OK ){
  82909. goto abort_due_to_error;
  82910. }
  82911. if( res ){
  82912. v = 1; /* IMP: R-61914-48074 */
  82913. }else{
  82914. assert( sqlite3BtreeCursorIsValid(pC->uc.pCursor) );
  82915. v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
  82916. if( v>=MAX_ROWID ){
  82917. pC->useRandomRowid = 1;
  82918. }else{
  82919. v++; /* IMP: R-29538-34987 */
  82920. }
  82921. }
  82922. }
  82923. #ifndef SQLITE_OMIT_AUTOINCREMENT
  82924. if( pOp->p3 ){
  82925. /* Assert that P3 is a valid memory cell. */
  82926. assert( pOp->p3>0 );
  82927. if( p->pFrame ){
  82928. for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
  82929. /* Assert that P3 is a valid memory cell. */
  82930. assert( pOp->p3<=pFrame->nMem );
  82931. pMem = &pFrame->aMem[pOp->p3];
  82932. }else{
  82933. /* Assert that P3 is a valid memory cell. */
  82934. assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
  82935. pMem = &aMem[pOp->p3];
  82936. memAboutToChange(p, pMem);
  82937. }
  82938. assert( memIsValid(pMem) );
  82939. REGISTER_TRACE(pOp->p3, pMem);
  82940. sqlite3VdbeMemIntegerify(pMem);
  82941. assert( (pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */
  82942. if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
  82943. rc = SQLITE_FULL; /* IMP: R-17817-00630 */
  82944. goto abort_due_to_error;
  82945. }
  82946. if( v<pMem->u.i+1 ){
  82947. v = pMem->u.i + 1;
  82948. }
  82949. pMem->u.i = v;
  82950. }
  82951. #endif
  82952. if( pC->useRandomRowid ){
  82953. /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
  82954. ** largest possible integer (9223372036854775807) then the database
  82955. ** engine starts picking positive candidate ROWIDs at random until
  82956. ** it finds one that is not previously used. */
  82957. assert( pOp->p3==0 ); /* We cannot be in random rowid mode if this is
  82958. ** an AUTOINCREMENT table. */
  82959. cnt = 0;
  82960. do{
  82961. sqlite3_randomness(sizeof(v), &v);
  82962. v &= (MAX_ROWID>>1); v++; /* Ensure that v is greater than zero */
  82963. }while( ((rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)v,
  82964. 0, &res))==SQLITE_OK)
  82965. && (res==0)
  82966. && (++cnt<100));
  82967. if( rc ) goto abort_due_to_error;
  82968. if( res==0 ){
  82969. rc = SQLITE_FULL; /* IMP: R-38219-53002 */
  82970. goto abort_due_to_error;
  82971. }
  82972. assert( v>0 ); /* EV: R-40812-03570 */
  82973. }
  82974. pC->deferredMoveto = 0;
  82975. pC->cacheStatus = CACHE_STALE;
  82976. }
  82977. pOut->u.i = v;
  82978. break;
  82979. }
  82980. /* Opcode: Insert P1 P2 P3 P4 P5
  82981. ** Synopsis: intkey=r[P3] data=r[P2]
  82982. **
  82983. ** Write an entry into the table of cursor P1. A new entry is
  82984. ** created if it doesn't already exist or the data for an existing
  82985. ** entry is overwritten. The data is the value MEM_Blob stored in register
  82986. ** number P2. The key is stored in register P3. The key must
  82987. ** be a MEM_Int.
  82988. **
  82989. ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
  82990. ** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P5 is set,
  82991. ** then rowid is stored for subsequent return by the
  82992. ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
  82993. **
  82994. ** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
  82995. ** run faster by avoiding an unnecessary seek on cursor P1. However,
  82996. ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
  82997. ** seeks on the cursor or if the most recent seek used a key equal to P3.
  82998. **
  82999. ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
  83000. ** UPDATE operation. Otherwise (if the flag is clear) then this opcode
  83001. ** is part of an INSERT operation. The difference is only important to
  83002. ** the update hook.
  83003. **
  83004. ** Parameter P4 may point to a Table structure, or may be NULL. If it is
  83005. ** not NULL, then the update-hook (sqlite3.xUpdateCallback) is invoked
  83006. ** following a successful insert.
  83007. **
  83008. ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
  83009. ** allocated, then ownership of P2 is transferred to the pseudo-cursor
  83010. ** and register P2 becomes ephemeral. If the cursor is changed, the
  83011. ** value of register P2 will then change. Make sure this does not
  83012. ** cause any problems.)
  83013. **
  83014. ** This instruction only works on tables. The equivalent instruction
  83015. ** for indices is OP_IdxInsert.
  83016. */
  83017. case OP_Insert: {
  83018. Mem *pData; /* MEM cell holding data for the record to be inserted */
  83019. Mem *pKey; /* MEM cell holding key for the record */
  83020. VdbeCursor *pC; /* Cursor to table into which insert is written */
  83021. int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */
  83022. const char *zDb; /* database name - used by the update hook */
  83023. Table *pTab; /* Table structure - used by update and pre-update hooks */
  83024. BtreePayload x; /* Payload to be inserted */
  83025. pData = &aMem[pOp->p2];
  83026. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  83027. assert( memIsValid(pData) );
  83028. pC = p->apCsr[pOp->p1];
  83029. assert( pC!=0 );
  83030. assert( pC->eCurType==CURTYPE_BTREE );
  83031. assert( pC->uc.pCursor!=0 );
  83032. assert( (pOp->p5 & OPFLAG_ISNOOP) || pC->isTable );
  83033. assert( pOp->p4type==P4_TABLE || pOp->p4type>=P4_STATIC );
  83034. REGISTER_TRACE(pOp->p2, pData);
  83035. sqlite3VdbeIncrWriteCounter(p, pC);
  83036. pKey = &aMem[pOp->p3];
  83037. assert( pKey->flags & MEM_Int );
  83038. assert( memIsValid(pKey) );
  83039. REGISTER_TRACE(pOp->p3, pKey);
  83040. x.nKey = pKey->u.i;
  83041. if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
  83042. assert( pC->iDb>=0 );
  83043. zDb = db->aDb[pC->iDb].zDbSName;
  83044. pTab = pOp->p4.pTab;
  83045. assert( (pOp->p5 & OPFLAG_ISNOOP) || HasRowid(pTab) );
  83046. }else{
  83047. pTab = 0;
  83048. zDb = 0; /* Not needed. Silence a compiler warning. */
  83049. }
  83050. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  83051. /* Invoke the pre-update hook, if any */
  83052. if( pTab ){
  83053. if( db->xPreUpdateCallback && !(pOp->p5 & OPFLAG_ISUPDATE) ){
  83054. sqlite3VdbePreUpdateHook(p, pC, SQLITE_INSERT, zDb, pTab, x.nKey,pOp->p2);
  83055. }
  83056. if( db->xUpdateCallback==0 || pTab->aCol==0 ){
  83057. /* Prevent post-update hook from running in cases when it should not */
  83058. pTab = 0;
  83059. }
  83060. }
  83061. if( pOp->p5 & OPFLAG_ISNOOP ) break;
  83062. #endif
  83063. if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
  83064. if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = x.nKey;
  83065. assert( pData->flags & (MEM_Blob|MEM_Str) );
  83066. x.pData = pData->z;
  83067. x.nData = pData->n;
  83068. seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
  83069. if( pData->flags & MEM_Zero ){
  83070. x.nZero = pData->u.nZero;
  83071. }else{
  83072. x.nZero = 0;
  83073. }
  83074. x.pKey = 0;
  83075. rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
  83076. (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION)), seekResult
  83077. );
  83078. pC->deferredMoveto = 0;
  83079. pC->cacheStatus = CACHE_STALE;
  83080. /* Invoke the update-hook if required. */
  83081. if( rc ) goto abort_due_to_error;
  83082. if( pTab ){
  83083. assert( db->xUpdateCallback!=0 );
  83084. assert( pTab->aCol!=0 );
  83085. db->xUpdateCallback(db->pUpdateArg,
  83086. (pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT,
  83087. zDb, pTab->zName, x.nKey);
  83088. }
  83089. break;
  83090. }
  83091. /* Opcode: Delete P1 P2 P3 P4 P5
  83092. **
  83093. ** Delete the record at which the P1 cursor is currently pointing.
  83094. **
  83095. ** If the OPFLAG_SAVEPOSITION bit of the P5 parameter is set, then
  83096. ** the cursor will be left pointing at either the next or the previous
  83097. ** record in the table. If it is left pointing at the next record, then
  83098. ** the next Next instruction will be a no-op. As a result, in this case
  83099. ** it is ok to delete a record from within a Next loop. If
  83100. ** OPFLAG_SAVEPOSITION bit of P5 is clear, then the cursor will be
  83101. ** left in an undefined state.
  83102. **
  83103. ** If the OPFLAG_AUXDELETE bit is set on P5, that indicates that this
  83104. ** delete one of several associated with deleting a table row and all its
  83105. ** associated index entries. Exactly one of those deletes is the "primary"
  83106. ** delete. The others are all on OPFLAG_FORDELETE cursors or else are
  83107. ** marked with the AUXDELETE flag.
  83108. **
  83109. ** If the OPFLAG_NCHANGE flag of P2 (NB: P2 not P5) is set, then the row
  83110. ** change count is incremented (otherwise not).
  83111. **
  83112. ** P1 must not be pseudo-table. It has to be a real table with
  83113. ** multiple rows.
  83114. **
  83115. ** If P4 is not NULL then it points to a Table object. In this case either
  83116. ** the update or pre-update hook, or both, may be invoked. The P1 cursor must
  83117. ** have been positioned using OP_NotFound prior to invoking this opcode in
  83118. ** this case. Specifically, if one is configured, the pre-update hook is
  83119. ** invoked if P4 is not NULL. The update-hook is invoked if one is configured,
  83120. ** P4 is not NULL, and the OPFLAG_NCHANGE flag is set in P2.
  83121. **
  83122. ** If the OPFLAG_ISUPDATE flag is set in P2, then P3 contains the address
  83123. ** of the memory cell that contains the value that the rowid of the row will
  83124. ** be set to by the update.
  83125. */
  83126. case OP_Delete: {
  83127. VdbeCursor *pC;
  83128. const char *zDb;
  83129. Table *pTab;
  83130. int opflags;
  83131. opflags = pOp->p2;
  83132. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  83133. pC = p->apCsr[pOp->p1];
  83134. assert( pC!=0 );
  83135. assert( pC->eCurType==CURTYPE_BTREE );
  83136. assert( pC->uc.pCursor!=0 );
  83137. assert( pC->deferredMoveto==0 );
  83138. sqlite3VdbeIncrWriteCounter(p, pC);
  83139. #ifdef SQLITE_DEBUG
  83140. if( pOp->p4type==P4_TABLE && HasRowid(pOp->p4.pTab) && pOp->p5==0 ){
  83141. /* If p5 is zero, the seek operation that positioned the cursor prior to
  83142. ** OP_Delete will have also set the pC->movetoTarget field to the rowid of
  83143. ** the row that is being deleted */
  83144. i64 iKey = sqlite3BtreeIntegerKey(pC->uc.pCursor);
  83145. assert( CORRUPT_DB || pC->movetoTarget==iKey );
  83146. }
  83147. #endif
  83148. /* If the update-hook or pre-update-hook will be invoked, set zDb to
  83149. ** the name of the db to pass as to it. Also set local pTab to a copy
  83150. ** of p4.pTab. Finally, if p5 is true, indicating that this cursor was
  83151. ** last moved with OP_Next or OP_Prev, not Seek or NotFound, set
  83152. ** VdbeCursor.movetoTarget to the current rowid. */
  83153. if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
  83154. assert( pC->iDb>=0 );
  83155. assert( pOp->p4.pTab!=0 );
  83156. zDb = db->aDb[pC->iDb].zDbSName;
  83157. pTab = pOp->p4.pTab;
  83158. if( (pOp->p5 & OPFLAG_SAVEPOSITION)!=0 && pC->isTable ){
  83159. pC->movetoTarget = sqlite3BtreeIntegerKey(pC->uc.pCursor);
  83160. }
  83161. }else{
  83162. zDb = 0; /* Not needed. Silence a compiler warning. */
  83163. pTab = 0; /* Not needed. Silence a compiler warning. */
  83164. }
  83165. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  83166. /* Invoke the pre-update-hook if required. */
  83167. if( db->xPreUpdateCallback && pOp->p4.pTab ){
  83168. assert( !(opflags & OPFLAG_ISUPDATE)
  83169. || HasRowid(pTab)==0
  83170. || (aMem[pOp->p3].flags & MEM_Int)
  83171. );
  83172. sqlite3VdbePreUpdateHook(p, pC,
  83173. (opflags & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_DELETE,
  83174. zDb, pTab, pC->movetoTarget,
  83175. pOp->p3
  83176. );
  83177. }
  83178. if( opflags & OPFLAG_ISNOOP ) break;
  83179. #endif
  83180. /* Only flags that can be set are SAVEPOISTION and AUXDELETE */
  83181. assert( (pOp->p5 & ~(OPFLAG_SAVEPOSITION|OPFLAG_AUXDELETE))==0 );
  83182. assert( OPFLAG_SAVEPOSITION==BTREE_SAVEPOSITION );
  83183. assert( OPFLAG_AUXDELETE==BTREE_AUXDELETE );
  83184. #ifdef SQLITE_DEBUG
  83185. if( p->pFrame==0 ){
  83186. if( pC->isEphemeral==0
  83187. && (pOp->p5 & OPFLAG_AUXDELETE)==0
  83188. && (pC->wrFlag & OPFLAG_FORDELETE)==0
  83189. ){
  83190. nExtraDelete++;
  83191. }
  83192. if( pOp->p2 & OPFLAG_NCHANGE ){
  83193. nExtraDelete--;
  83194. }
  83195. }
  83196. #endif
  83197. rc = sqlite3BtreeDelete(pC->uc.pCursor, pOp->p5);
  83198. pC->cacheStatus = CACHE_STALE;
  83199. pC->seekResult = 0;
  83200. if( rc ) goto abort_due_to_error;
  83201. /* Invoke the update-hook if required. */
  83202. if( opflags & OPFLAG_NCHANGE ){
  83203. p->nChange++;
  83204. if( db->xUpdateCallback && HasRowid(pTab) ){
  83205. db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, pTab->zName,
  83206. pC->movetoTarget);
  83207. assert( pC->iDb>=0 );
  83208. }
  83209. }
  83210. break;
  83211. }
  83212. /* Opcode: ResetCount * * * * *
  83213. **
  83214. ** The value of the change counter is copied to the database handle
  83215. ** change counter (returned by subsequent calls to sqlite3_changes()).
  83216. ** Then the VMs internal change counter resets to 0.
  83217. ** This is used by trigger programs.
  83218. */
  83219. case OP_ResetCount: {
  83220. sqlite3VdbeSetChanges(db, p->nChange);
  83221. p->nChange = 0;
  83222. break;
  83223. }
  83224. /* Opcode: SorterCompare P1 P2 P3 P4
  83225. ** Synopsis: if key(P1)!=trim(r[P3],P4) goto P2
  83226. **
  83227. ** P1 is a sorter cursor. This instruction compares a prefix of the
  83228. ** record blob in register P3 against a prefix of the entry that
  83229. ** the sorter cursor currently points to. Only the first P4 fields
  83230. ** of r[P3] and the sorter record are compared.
  83231. **
  83232. ** If either P3 or the sorter contains a NULL in one of their significant
  83233. ** fields (not counting the P4 fields at the end which are ignored) then
  83234. ** the comparison is assumed to be equal.
  83235. **
  83236. ** Fall through to next instruction if the two records compare equal to
  83237. ** each other. Jump to P2 if they are different.
  83238. */
  83239. case OP_SorterCompare: {
  83240. VdbeCursor *pC;
  83241. int res;
  83242. int nKeyCol;
  83243. pC = p->apCsr[pOp->p1];
  83244. assert( isSorter(pC) );
  83245. assert( pOp->p4type==P4_INT32 );
  83246. pIn3 = &aMem[pOp->p3];
  83247. nKeyCol = pOp->p4.i;
  83248. res = 0;
  83249. rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res);
  83250. VdbeBranchTaken(res!=0,2);
  83251. if( rc ) goto abort_due_to_error;
  83252. if( res ) goto jump_to_p2;
  83253. break;
  83254. };
  83255. /* Opcode: SorterData P1 P2 P3 * *
  83256. ** Synopsis: r[P2]=data
  83257. **
  83258. ** Write into register P2 the current sorter data for sorter cursor P1.
  83259. ** Then clear the column header cache on cursor P3.
  83260. **
  83261. ** This opcode is normally use to move a record out of the sorter and into
  83262. ** a register that is the source for a pseudo-table cursor created using
  83263. ** OpenPseudo. That pseudo-table cursor is the one that is identified by
  83264. ** parameter P3. Clearing the P3 column cache as part of this opcode saves
  83265. ** us from having to issue a separate NullRow instruction to clear that cache.
  83266. */
  83267. case OP_SorterData: {
  83268. VdbeCursor *pC;
  83269. pOut = &aMem[pOp->p2];
  83270. pC = p->apCsr[pOp->p1];
  83271. assert( isSorter(pC) );
  83272. rc = sqlite3VdbeSorterRowkey(pC, pOut);
  83273. assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) );
  83274. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  83275. if( rc ) goto abort_due_to_error;
  83276. p->apCsr[pOp->p3]->cacheStatus = CACHE_STALE;
  83277. break;
  83278. }
  83279. /* Opcode: RowData P1 P2 P3 * *
  83280. ** Synopsis: r[P2]=data
  83281. **
  83282. ** Write into register P2 the complete row content for the row at
  83283. ** which cursor P1 is currently pointing.
  83284. ** There is no interpretation of the data.
  83285. ** It is just copied onto the P2 register exactly as
  83286. ** it is found in the database file.
  83287. **
  83288. ** If cursor P1 is an index, then the content is the key of the row.
  83289. ** If cursor P2 is a table, then the content extracted is the data.
  83290. **
  83291. ** If the P1 cursor must be pointing to a valid row (not a NULL row)
  83292. ** of a real table, not a pseudo-table.
  83293. **
  83294. ** If P3!=0 then this opcode is allowed to make an ephemeral pointer
  83295. ** into the database page. That means that the content of the output
  83296. ** register will be invalidated as soon as the cursor moves - including
  83297. ** moves caused by other cursors that "save" the current cursors
  83298. ** position in order that they can write to the same table. If P3==0
  83299. ** then a copy of the data is made into memory. P3!=0 is faster, but
  83300. ** P3==0 is safer.
  83301. **
  83302. ** If P3!=0 then the content of the P2 register is unsuitable for use
  83303. ** in OP_Result and any OP_Result will invalidate the P2 register content.
  83304. ** The P2 register content is invalidated by opcodes like OP_Function or
  83305. ** by any use of another cursor pointing to the same table.
  83306. */
  83307. case OP_RowData: {
  83308. VdbeCursor *pC;
  83309. BtCursor *pCrsr;
  83310. u32 n;
  83311. pOut = out2Prerelease(p, pOp);
  83312. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  83313. pC = p->apCsr[pOp->p1];
  83314. assert( pC!=0 );
  83315. assert( pC->eCurType==CURTYPE_BTREE );
  83316. assert( isSorter(pC)==0 );
  83317. assert( pC->nullRow==0 );
  83318. assert( pC->uc.pCursor!=0 );
  83319. pCrsr = pC->uc.pCursor;
  83320. /* The OP_RowData opcodes always follow OP_NotExists or
  83321. ** OP_SeekRowid or OP_Rewind/Op_Next with no intervening instructions
  83322. ** that might invalidate the cursor.
  83323. ** If this where not the case, on of the following assert()s
  83324. ** would fail. Should this ever change (because of changes in the code
  83325. ** generator) then the fix would be to insert a call to
  83326. ** sqlite3VdbeCursorMoveto().
  83327. */
  83328. assert( pC->deferredMoveto==0 );
  83329. assert( sqlite3BtreeCursorIsValid(pCrsr) );
  83330. #if 0 /* Not required due to the previous to assert() statements */
  83331. rc = sqlite3VdbeCursorMoveto(pC);
  83332. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  83333. #endif
  83334. n = sqlite3BtreePayloadSize(pCrsr);
  83335. if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  83336. goto too_big;
  83337. }
  83338. testcase( n==0 );
  83339. rc = sqlite3VdbeMemFromBtree(pCrsr, 0, n, pOut);
  83340. if( rc ) goto abort_due_to_error;
  83341. if( !pOp->p3 ) Deephemeralize(pOut);
  83342. UPDATE_MAX_BLOBSIZE(pOut);
  83343. REGISTER_TRACE(pOp->p2, pOut);
  83344. break;
  83345. }
  83346. /* Opcode: Rowid P1 P2 * * *
  83347. ** Synopsis: r[P2]=rowid
  83348. **
  83349. ** Store in register P2 an integer which is the key of the table entry that
  83350. ** P1 is currently point to.
  83351. **
  83352. ** P1 can be either an ordinary table or a virtual table. There used to
  83353. ** be a separate OP_VRowid opcode for use with virtual tables, but this
  83354. ** one opcode now works for both table types.
  83355. */
  83356. case OP_Rowid: { /* out2 */
  83357. VdbeCursor *pC;
  83358. i64 v;
  83359. sqlite3_vtab *pVtab;
  83360. const sqlite3_module *pModule;
  83361. pOut = out2Prerelease(p, pOp);
  83362. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  83363. pC = p->apCsr[pOp->p1];
  83364. assert( pC!=0 );
  83365. assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
  83366. if( pC->nullRow ){
  83367. pOut->flags = MEM_Null;
  83368. break;
  83369. }else if( pC->deferredMoveto ){
  83370. v = pC->movetoTarget;
  83371. #ifndef SQLITE_OMIT_VIRTUALTABLE
  83372. }else if( pC->eCurType==CURTYPE_VTAB ){
  83373. assert( pC->uc.pVCur!=0 );
  83374. pVtab = pC->uc.pVCur->pVtab;
  83375. pModule = pVtab->pModule;
  83376. assert( pModule->xRowid );
  83377. rc = pModule->xRowid(pC->uc.pVCur, &v);
  83378. sqlite3VtabImportErrmsg(p, pVtab);
  83379. if( rc ) goto abort_due_to_error;
  83380. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  83381. }else{
  83382. assert( pC->eCurType==CURTYPE_BTREE );
  83383. assert( pC->uc.pCursor!=0 );
  83384. rc = sqlite3VdbeCursorRestore(pC);
  83385. if( rc ) goto abort_due_to_error;
  83386. if( pC->nullRow ){
  83387. pOut->flags = MEM_Null;
  83388. break;
  83389. }
  83390. v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
  83391. }
  83392. pOut->u.i = v;
  83393. break;
  83394. }
  83395. /* Opcode: NullRow P1 * * * *
  83396. **
  83397. ** Move the cursor P1 to a null row. Any OP_Column operations
  83398. ** that occur while the cursor is on the null row will always
  83399. ** write a NULL.
  83400. */
  83401. case OP_NullRow: {
  83402. VdbeCursor *pC;
  83403. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  83404. pC = p->apCsr[pOp->p1];
  83405. assert( pC!=0 );
  83406. pC->nullRow = 1;
  83407. pC->cacheStatus = CACHE_STALE;
  83408. if( pC->eCurType==CURTYPE_BTREE ){
  83409. assert( pC->uc.pCursor!=0 );
  83410. sqlite3BtreeClearCursor(pC->uc.pCursor);
  83411. }
  83412. #ifdef SQLITE_DEBUG
  83413. if( pC->seekOp==0 ) pC->seekOp = OP_NullRow;
  83414. #endif
  83415. break;
  83416. }
  83417. /* Opcode: SeekEnd P1 * * * *
  83418. **
  83419. ** Position cursor P1 at the end of the btree for the purpose of
  83420. ** appending a new entry onto the btree.
  83421. **
  83422. ** It is assumed that the cursor is used only for appending and so
  83423. ** if the cursor is valid, then the cursor must already be pointing
  83424. ** at the end of the btree and so no changes are made to
  83425. ** the cursor.
  83426. */
  83427. /* Opcode: Last P1 P2 * * *
  83428. **
  83429. ** The next use of the Rowid or Column or Prev instruction for P1
  83430. ** will refer to the last entry in the database table or index.
  83431. ** If the table or index is empty and P2>0, then jump immediately to P2.
  83432. ** If P2 is 0 or if the table or index is not empty, fall through
  83433. ** to the following instruction.
  83434. **
  83435. ** This opcode leaves the cursor configured to move in reverse order,
  83436. ** from the end toward the beginning. In other words, the cursor is
  83437. ** configured to use Prev, not Next.
  83438. */
  83439. case OP_SeekEnd:
  83440. case OP_Last: { /* jump */
  83441. VdbeCursor *pC;
  83442. BtCursor *pCrsr;
  83443. int res;
  83444. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  83445. pC = p->apCsr[pOp->p1];
  83446. assert( pC!=0 );
  83447. assert( pC->eCurType==CURTYPE_BTREE );
  83448. pCrsr = pC->uc.pCursor;
  83449. res = 0;
  83450. assert( pCrsr!=0 );
  83451. #ifdef SQLITE_DEBUG
  83452. pC->seekOp = pOp->opcode;
  83453. #endif
  83454. if( pOp->opcode==OP_SeekEnd ){
  83455. assert( pOp->p2==0 );
  83456. pC->seekResult = -1;
  83457. if( sqlite3BtreeCursorIsValidNN(pCrsr) ){
  83458. break;
  83459. }
  83460. }
  83461. rc = sqlite3BtreeLast(pCrsr, &res);
  83462. pC->nullRow = (u8)res;
  83463. pC->deferredMoveto = 0;
  83464. pC->cacheStatus = CACHE_STALE;
  83465. if( rc ) goto abort_due_to_error;
  83466. if( pOp->p2>0 ){
  83467. VdbeBranchTaken(res!=0,2);
  83468. if( res ) goto jump_to_p2;
  83469. }
  83470. break;
  83471. }
  83472. /* Opcode: IfSmaller P1 P2 P3 * *
  83473. **
  83474. ** Estimate the number of rows in the table P1. Jump to P2 if that
  83475. ** estimate is less than approximately 2**(0.1*P3).
  83476. */
  83477. case OP_IfSmaller: { /* jump */
  83478. VdbeCursor *pC;
  83479. BtCursor *pCrsr;
  83480. int res;
  83481. i64 sz;
  83482. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  83483. pC = p->apCsr[pOp->p1];
  83484. assert( pC!=0 );
  83485. pCrsr = pC->uc.pCursor;
  83486. assert( pCrsr );
  83487. rc = sqlite3BtreeFirst(pCrsr, &res);
  83488. if( rc ) goto abort_due_to_error;
  83489. if( res==0 ){
  83490. sz = sqlite3BtreeRowCountEst(pCrsr);
  83491. if( ALWAYS(sz>=0) && sqlite3LogEst((u64)sz)<pOp->p3 ) res = 1;
  83492. }
  83493. VdbeBranchTaken(res!=0,2);
  83494. if( res ) goto jump_to_p2;
  83495. break;
  83496. }
  83497. /* Opcode: SorterSort P1 P2 * * *
  83498. **
  83499. ** After all records have been inserted into the Sorter object
  83500. ** identified by P1, invoke this opcode to actually do the sorting.
  83501. ** Jump to P2 if there are no records to be sorted.
  83502. **
  83503. ** This opcode is an alias for OP_Sort and OP_Rewind that is used
  83504. ** for Sorter objects.
  83505. */
  83506. /* Opcode: Sort P1 P2 * * *
  83507. **
  83508. ** This opcode does exactly the same thing as OP_Rewind except that
  83509. ** it increments an undocumented global variable used for testing.
  83510. **
  83511. ** Sorting is accomplished by writing records into a sorting index,
  83512. ** then rewinding that index and playing it back from beginning to
  83513. ** end. We use the OP_Sort opcode instead of OP_Rewind to do the
  83514. ** rewinding so that the global variable will be incremented and
  83515. ** regression tests can determine whether or not the optimizer is
  83516. ** correctly optimizing out sorts.
  83517. */
  83518. case OP_SorterSort: /* jump */
  83519. case OP_Sort: { /* jump */
  83520. #ifdef SQLITE_TEST
  83521. sqlite3_sort_count++;
  83522. sqlite3_search_count--;
  83523. #endif
  83524. p->aCounter[SQLITE_STMTSTATUS_SORT]++;
  83525. /* Fall through into OP_Rewind */
  83526. }
  83527. /* Opcode: Rewind P1 P2 * * *
  83528. **
  83529. ** The next use of the Rowid or Column or Next instruction for P1
  83530. ** will refer to the first entry in the database table or index.
  83531. ** If the table or index is empty, jump immediately to P2.
  83532. ** If the table or index is not empty, fall through to the following
  83533. ** instruction.
  83534. **
  83535. ** This opcode leaves the cursor configured to move in forward order,
  83536. ** from the beginning toward the end. In other words, the cursor is
  83537. ** configured to use Next, not Prev.
  83538. */
  83539. case OP_Rewind: { /* jump */
  83540. VdbeCursor *pC;
  83541. BtCursor *pCrsr;
  83542. int res;
  83543. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  83544. assert( pOp->p5==0 );
  83545. pC = p->apCsr[pOp->p1];
  83546. assert( pC!=0 );
  83547. assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) );
  83548. res = 1;
  83549. #ifdef SQLITE_DEBUG
  83550. pC->seekOp = OP_Rewind;
  83551. #endif
  83552. if( isSorter(pC) ){
  83553. rc = sqlite3VdbeSorterRewind(pC, &res);
  83554. }else{
  83555. assert( pC->eCurType==CURTYPE_BTREE );
  83556. pCrsr = pC->uc.pCursor;
  83557. assert( pCrsr );
  83558. rc = sqlite3BtreeFirst(pCrsr, &res);
  83559. pC->deferredMoveto = 0;
  83560. pC->cacheStatus = CACHE_STALE;
  83561. }
  83562. if( rc ) goto abort_due_to_error;
  83563. pC->nullRow = (u8)res;
  83564. assert( pOp->p2>0 && pOp->p2<p->nOp );
  83565. VdbeBranchTaken(res!=0,2);
  83566. if( res ) goto jump_to_p2;
  83567. break;
  83568. }
  83569. /* Opcode: Next P1 P2 P3 P4 P5
  83570. **
  83571. ** Advance cursor P1 so that it points to the next key/data pair in its
  83572. ** table or index. If there are no more key/value pairs then fall through
  83573. ** to the following instruction. But if the cursor advance was successful,
  83574. ** jump immediately to P2.
  83575. **
  83576. ** The Next opcode is only valid following an SeekGT, SeekGE, or
  83577. ** OP_Rewind opcode used to position the cursor. Next is not allowed
  83578. ** to follow SeekLT, SeekLE, or OP_Last.
  83579. **
  83580. ** The P1 cursor must be for a real table, not a pseudo-table. P1 must have
  83581. ** been opened prior to this opcode or the program will segfault.
  83582. **
  83583. ** The P3 value is a hint to the btree implementation. If P3==1, that
  83584. ** means P1 is an SQL index and that this instruction could have been
  83585. ** omitted if that index had been unique. P3 is usually 0. P3 is
  83586. ** always either 0 or 1.
  83587. **
  83588. ** P4 is always of type P4_ADVANCE. The function pointer points to
  83589. ** sqlite3BtreeNext().
  83590. **
  83591. ** If P5 is positive and the jump is taken, then event counter
  83592. ** number P5-1 in the prepared statement is incremented.
  83593. **
  83594. ** See also: Prev
  83595. */
  83596. /* Opcode: Prev P1 P2 P3 P4 P5
  83597. **
  83598. ** Back up cursor P1 so that it points to the previous key/data pair in its
  83599. ** table or index. If there is no previous key/value pairs then fall through
  83600. ** to the following instruction. But if the cursor backup was successful,
  83601. ** jump immediately to P2.
  83602. **
  83603. **
  83604. ** The Prev opcode is only valid following an SeekLT, SeekLE, or
  83605. ** OP_Last opcode used to position the cursor. Prev is not allowed
  83606. ** to follow SeekGT, SeekGE, or OP_Rewind.
  83607. **
  83608. ** The P1 cursor must be for a real table, not a pseudo-table. If P1 is
  83609. ** not open then the behavior is undefined.
  83610. **
  83611. ** The P3 value is a hint to the btree implementation. If P3==1, that
  83612. ** means P1 is an SQL index and that this instruction could have been
  83613. ** omitted if that index had been unique. P3 is usually 0. P3 is
  83614. ** always either 0 or 1.
  83615. **
  83616. ** P4 is always of type P4_ADVANCE. The function pointer points to
  83617. ** sqlite3BtreePrevious().
  83618. **
  83619. ** If P5 is positive and the jump is taken, then event counter
  83620. ** number P5-1 in the prepared statement is incremented.
  83621. */
  83622. /* Opcode: SorterNext P1 P2 * * P5
  83623. **
  83624. ** This opcode works just like OP_Next except that P1 must be a
  83625. ** sorter object for which the OP_SorterSort opcode has been
  83626. ** invoked. This opcode advances the cursor to the next sorted
  83627. ** record, or jumps to P2 if there are no more sorted records.
  83628. */
  83629. case OP_SorterNext: { /* jump */
  83630. VdbeCursor *pC;
  83631. pC = p->apCsr[pOp->p1];
  83632. assert( isSorter(pC) );
  83633. rc = sqlite3VdbeSorterNext(db, pC);
  83634. goto next_tail;
  83635. case OP_Prev: /* jump */
  83636. case OP_Next: /* jump */
  83637. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  83638. assert( pOp->p5<ArraySize(p->aCounter) );
  83639. pC = p->apCsr[pOp->p1];
  83640. assert( pC!=0 );
  83641. assert( pC->deferredMoveto==0 );
  83642. assert( pC->eCurType==CURTYPE_BTREE );
  83643. assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
  83644. assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
  83645. /* The Next opcode is only used after SeekGT, SeekGE, Rewind, and Found.
  83646. ** The Prev opcode is only used after SeekLT, SeekLE, and Last. */
  83647. assert( pOp->opcode!=OP_Next
  83648. || pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE
  83649. || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found
  83650. || pC->seekOp==OP_NullRow|| pC->seekOp==OP_SeekRowid);
  83651. assert( pOp->opcode!=OP_Prev
  83652. || pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE
  83653. || pC->seekOp==OP_Last
  83654. || pC->seekOp==OP_NullRow);
  83655. rc = pOp->p4.xAdvance(pC->uc.pCursor, pOp->p3);
  83656. next_tail:
  83657. pC->cacheStatus = CACHE_STALE;
  83658. VdbeBranchTaken(rc==SQLITE_OK,2);
  83659. if( rc==SQLITE_OK ){
  83660. pC->nullRow = 0;
  83661. p->aCounter[pOp->p5]++;
  83662. #ifdef SQLITE_TEST
  83663. sqlite3_search_count++;
  83664. #endif
  83665. goto jump_to_p2_and_check_for_interrupt;
  83666. }
  83667. if( rc!=SQLITE_DONE ) goto abort_due_to_error;
  83668. rc = SQLITE_OK;
  83669. pC->nullRow = 1;
  83670. goto check_for_interrupt;
  83671. }
  83672. /* Opcode: IdxInsert P1 P2 P3 P4 P5
  83673. ** Synopsis: key=r[P2]
  83674. **
  83675. ** Register P2 holds an SQL index key made using the
  83676. ** MakeRecord instructions. This opcode writes that key
  83677. ** into the index P1. Data for the entry is nil.
  83678. **
  83679. ** If P4 is not zero, then it is the number of values in the unpacked
  83680. ** key of reg(P2). In that case, P3 is the index of the first register
  83681. ** for the unpacked key. The availability of the unpacked key can sometimes
  83682. ** be an optimization.
  83683. **
  83684. ** If P5 has the OPFLAG_APPEND bit set, that is a hint to the b-tree layer
  83685. ** that this insert is likely to be an append.
  83686. **
  83687. ** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is
  83688. ** incremented by this instruction. If the OPFLAG_NCHANGE bit is clear,
  83689. ** then the change counter is unchanged.
  83690. **
  83691. ** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
  83692. ** run faster by avoiding an unnecessary seek on cursor P1. However,
  83693. ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
  83694. ** seeks on the cursor or if the most recent seek used a key equivalent
  83695. ** to P2.
  83696. **
  83697. ** This instruction only works for indices. The equivalent instruction
  83698. ** for tables is OP_Insert.
  83699. */
  83700. /* Opcode: SorterInsert P1 P2 * * *
  83701. ** Synopsis: key=r[P2]
  83702. **
  83703. ** Register P2 holds an SQL index key made using the
  83704. ** MakeRecord instructions. This opcode writes that key
  83705. ** into the sorter P1. Data for the entry is nil.
  83706. */
  83707. case OP_SorterInsert: /* in2 */
  83708. case OP_IdxInsert: { /* in2 */
  83709. VdbeCursor *pC;
  83710. BtreePayload x;
  83711. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  83712. pC = p->apCsr[pOp->p1];
  83713. sqlite3VdbeIncrWriteCounter(p, pC);
  83714. assert( pC!=0 );
  83715. assert( isSorter(pC)==(pOp->opcode==OP_SorterInsert) );
  83716. pIn2 = &aMem[pOp->p2];
  83717. assert( pIn2->flags & MEM_Blob );
  83718. if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
  83719. assert( pC->eCurType==CURTYPE_BTREE || pOp->opcode==OP_SorterInsert );
  83720. assert( pC->isTable==0 );
  83721. rc = ExpandBlob(pIn2);
  83722. if( rc ) goto abort_due_to_error;
  83723. if( pOp->opcode==OP_SorterInsert ){
  83724. rc = sqlite3VdbeSorterWrite(pC, pIn2);
  83725. }else{
  83726. x.nKey = pIn2->n;
  83727. x.pKey = pIn2->z;
  83728. x.aMem = aMem + pOp->p3;
  83729. x.nMem = (u16)pOp->p4.i;
  83730. rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
  83731. (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION)),
  83732. ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
  83733. );
  83734. assert( pC->deferredMoveto==0 );
  83735. pC->cacheStatus = CACHE_STALE;
  83736. }
  83737. if( rc) goto abort_due_to_error;
  83738. break;
  83739. }
  83740. /* Opcode: IdxDelete P1 P2 P3 * *
  83741. ** Synopsis: key=r[P2@P3]
  83742. **
  83743. ** The content of P3 registers starting at register P2 form
  83744. ** an unpacked index key. This opcode removes that entry from the
  83745. ** index opened by cursor P1.
  83746. */
  83747. case OP_IdxDelete: {
  83748. VdbeCursor *pC;
  83749. BtCursor *pCrsr;
  83750. int res;
  83751. UnpackedRecord r;
  83752. assert( pOp->p3>0 );
  83753. assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem+1 - p->nCursor)+1 );
  83754. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  83755. pC = p->apCsr[pOp->p1];
  83756. assert( pC!=0 );
  83757. assert( pC->eCurType==CURTYPE_BTREE );
  83758. sqlite3VdbeIncrWriteCounter(p, pC);
  83759. pCrsr = pC->uc.pCursor;
  83760. assert( pCrsr!=0 );
  83761. assert( pOp->p5==0 );
  83762. r.pKeyInfo = pC->pKeyInfo;
  83763. r.nField = (u16)pOp->p3;
  83764. r.default_rc = 0;
  83765. r.aMem = &aMem[pOp->p2];
  83766. rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res);
  83767. if( rc ) goto abort_due_to_error;
  83768. if( res==0 ){
  83769. rc = sqlite3BtreeDelete(pCrsr, BTREE_AUXDELETE);
  83770. if( rc ) goto abort_due_to_error;
  83771. }
  83772. assert( pC->deferredMoveto==0 );
  83773. pC->cacheStatus = CACHE_STALE;
  83774. pC->seekResult = 0;
  83775. break;
  83776. }
  83777. /* Opcode: DeferredSeek P1 * P3 P4 *
  83778. ** Synopsis: Move P3 to P1.rowid if needed
  83779. **
  83780. ** P1 is an open index cursor and P3 is a cursor on the corresponding
  83781. ** table. This opcode does a deferred seek of the P3 table cursor
  83782. ** to the row that corresponds to the current row of P1.
  83783. **
  83784. ** This is a deferred seek. Nothing actually happens until
  83785. ** the cursor is used to read a record. That way, if no reads
  83786. ** occur, no unnecessary I/O happens.
  83787. **
  83788. ** P4 may be an array of integers (type P4_INTARRAY) containing
  83789. ** one entry for each column in the P3 table. If array entry a(i)
  83790. ** is non-zero, then reading column a(i)-1 from cursor P3 is
  83791. ** equivalent to performing the deferred seek and then reading column i
  83792. ** from P1. This information is stored in P3 and used to redirect
  83793. ** reads against P3 over to P1, thus possibly avoiding the need to
  83794. ** seek and read cursor P3.
  83795. */
  83796. /* Opcode: IdxRowid P1 P2 * * *
  83797. ** Synopsis: r[P2]=rowid
  83798. **
  83799. ** Write into register P2 an integer which is the last entry in the record at
  83800. ** the end of the index key pointed to by cursor P1. This integer should be
  83801. ** the rowid of the table entry to which this index entry points.
  83802. **
  83803. ** See also: Rowid, MakeRecord.
  83804. */
  83805. case OP_DeferredSeek:
  83806. case OP_IdxRowid: { /* out2 */
  83807. VdbeCursor *pC; /* The P1 index cursor */
  83808. VdbeCursor *pTabCur; /* The P2 table cursor (OP_DeferredSeek only) */
  83809. i64 rowid; /* Rowid that P1 current points to */
  83810. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  83811. pC = p->apCsr[pOp->p1];
  83812. assert( pC!=0 );
  83813. assert( pC->eCurType==CURTYPE_BTREE );
  83814. assert( pC->uc.pCursor!=0 );
  83815. assert( pC->isTable==0 );
  83816. assert( pC->deferredMoveto==0 );
  83817. assert( !pC->nullRow || pOp->opcode==OP_IdxRowid );
  83818. /* The IdxRowid and Seek opcodes are combined because of the commonality
  83819. ** of sqlite3VdbeCursorRestore() and sqlite3VdbeIdxRowid(). */
  83820. rc = sqlite3VdbeCursorRestore(pC);
  83821. /* sqlite3VbeCursorRestore() can only fail if the record has been deleted
  83822. ** out from under the cursor. That will never happens for an IdxRowid
  83823. ** or Seek opcode */
  83824. if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
  83825. if( !pC->nullRow ){
  83826. rowid = 0; /* Not needed. Only used to silence a warning. */
  83827. rc = sqlite3VdbeIdxRowid(db, pC->uc.pCursor, &rowid);
  83828. if( rc!=SQLITE_OK ){
  83829. goto abort_due_to_error;
  83830. }
  83831. if( pOp->opcode==OP_DeferredSeek ){
  83832. assert( pOp->p3>=0 && pOp->p3<p->nCursor );
  83833. pTabCur = p->apCsr[pOp->p3];
  83834. assert( pTabCur!=0 );
  83835. assert( pTabCur->eCurType==CURTYPE_BTREE );
  83836. assert( pTabCur->uc.pCursor!=0 );
  83837. assert( pTabCur->isTable );
  83838. pTabCur->nullRow = 0;
  83839. pTabCur->movetoTarget = rowid;
  83840. pTabCur->deferredMoveto = 1;
  83841. assert( pOp->p4type==P4_INTARRAY || pOp->p4.ai==0 );
  83842. pTabCur->aAltMap = pOp->p4.ai;
  83843. pTabCur->pAltCursor = pC;
  83844. }else{
  83845. pOut = out2Prerelease(p, pOp);
  83846. pOut->u.i = rowid;
  83847. }
  83848. }else{
  83849. assert( pOp->opcode==OP_IdxRowid );
  83850. sqlite3VdbeMemSetNull(&aMem[pOp->p2]);
  83851. }
  83852. break;
  83853. }
  83854. /* Opcode: IdxGE P1 P2 P3 P4 P5
  83855. ** Synopsis: key=r[P3@P4]
  83856. **
  83857. ** The P4 register values beginning with P3 form an unpacked index
  83858. ** key that omits the PRIMARY KEY. Compare this key value against the index
  83859. ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
  83860. ** fields at the end.
  83861. **
  83862. ** If the P1 index entry is greater than or equal to the key value
  83863. ** then jump to P2. Otherwise fall through to the next instruction.
  83864. */
  83865. /* Opcode: IdxGT P1 P2 P3 P4 P5
  83866. ** Synopsis: key=r[P3@P4]
  83867. **
  83868. ** The P4 register values beginning with P3 form an unpacked index
  83869. ** key that omits the PRIMARY KEY. Compare this key value against the index
  83870. ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
  83871. ** fields at the end.
  83872. **
  83873. ** If the P1 index entry is greater than the key value
  83874. ** then jump to P2. Otherwise fall through to the next instruction.
  83875. */
  83876. /* Opcode: IdxLT P1 P2 P3 P4 P5
  83877. ** Synopsis: key=r[P3@P4]
  83878. **
  83879. ** The P4 register values beginning with P3 form an unpacked index
  83880. ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
  83881. ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
  83882. ** ROWID on the P1 index.
  83883. **
  83884. ** If the P1 index entry is less than the key value then jump to P2.
  83885. ** Otherwise fall through to the next instruction.
  83886. */
  83887. /* Opcode: IdxLE P1 P2 P3 P4 P5
  83888. ** Synopsis: key=r[P3@P4]
  83889. **
  83890. ** The P4 register values beginning with P3 form an unpacked index
  83891. ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
  83892. ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
  83893. ** ROWID on the P1 index.
  83894. **
  83895. ** If the P1 index entry is less than or equal to the key value then jump
  83896. ** to P2. Otherwise fall through to the next instruction.
  83897. */
  83898. case OP_IdxLE: /* jump */
  83899. case OP_IdxGT: /* jump */
  83900. case OP_IdxLT: /* jump */
  83901. case OP_IdxGE: { /* jump */
  83902. VdbeCursor *pC;
  83903. int res;
  83904. UnpackedRecord r;
  83905. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  83906. pC = p->apCsr[pOp->p1];
  83907. assert( pC!=0 );
  83908. assert( pC->isOrdered );
  83909. assert( pC->eCurType==CURTYPE_BTREE );
  83910. assert( pC->uc.pCursor!=0);
  83911. assert( pC->deferredMoveto==0 );
  83912. assert( pOp->p5==0 || pOp->p5==1 );
  83913. assert( pOp->p4type==P4_INT32 );
  83914. r.pKeyInfo = pC->pKeyInfo;
  83915. r.nField = (u16)pOp->p4.i;
  83916. if( pOp->opcode<OP_IdxLT ){
  83917. assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT );
  83918. r.default_rc = -1;
  83919. }else{
  83920. assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT );
  83921. r.default_rc = 0;
  83922. }
  83923. r.aMem = &aMem[pOp->p3];
  83924. #ifdef SQLITE_DEBUG
  83925. {
  83926. int i;
  83927. for(i=0; i<r.nField; i++){
  83928. assert( memIsValid(&r.aMem[i]) );
  83929. REGISTER_TRACE(pOp->p3+i, &aMem[pOp->p3+i]);
  83930. }
  83931. }
  83932. #endif
  83933. res = 0; /* Not needed. Only used to silence a warning. */
  83934. rc = sqlite3VdbeIdxKeyCompare(db, pC, &r, &res);
  83935. assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) );
  83936. if( (pOp->opcode&1)==(OP_IdxLT&1) ){
  83937. assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );
  83938. res = -res;
  83939. }else{
  83940. assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT );
  83941. res++;
  83942. }
  83943. VdbeBranchTaken(res>0,2);
  83944. if( rc ) goto abort_due_to_error;
  83945. if( res>0 ) goto jump_to_p2;
  83946. break;
  83947. }
  83948. /* Opcode: Destroy P1 P2 P3 * *
  83949. **
  83950. ** Delete an entire database table or index whose root page in the database
  83951. ** file is given by P1.
  83952. **
  83953. ** The table being destroyed is in the main database file if P3==0. If
  83954. ** P3==1 then the table to be clear is in the auxiliary database file
  83955. ** that is used to store tables create using CREATE TEMPORARY TABLE.
  83956. **
  83957. ** If AUTOVACUUM is enabled then it is possible that another root page
  83958. ** might be moved into the newly deleted root page in order to keep all
  83959. ** root pages contiguous at the beginning of the database. The former
  83960. ** value of the root page that moved - its value before the move occurred -
  83961. ** is stored in register P2. If no page movement was required (because the
  83962. ** table being dropped was already the last one in the database) then a
  83963. ** zero is stored in register P2. If AUTOVACUUM is disabled then a zero
  83964. ** is stored in register P2.
  83965. **
  83966. ** This opcode throws an error if there are any active reader VMs when
  83967. ** it is invoked. This is done to avoid the difficulty associated with
  83968. ** updating existing cursors when a root page is moved in an AUTOVACUUM
  83969. ** database. This error is thrown even if the database is not an AUTOVACUUM
  83970. ** db in order to avoid introducing an incompatibility between autovacuum
  83971. ** and non-autovacuum modes.
  83972. **
  83973. ** See also: Clear
  83974. */
  83975. case OP_Destroy: { /* out2 */
  83976. int iMoved;
  83977. int iDb;
  83978. sqlite3VdbeIncrWriteCounter(p, 0);
  83979. assert( p->readOnly==0 );
  83980. assert( pOp->p1>1 );
  83981. pOut = out2Prerelease(p, pOp);
  83982. pOut->flags = MEM_Null;
  83983. if( db->nVdbeRead > db->nVDestroy+1 ){
  83984. rc = SQLITE_LOCKED;
  83985. p->errorAction = OE_Abort;
  83986. goto abort_due_to_error;
  83987. }else{
  83988. iDb = pOp->p3;
  83989. assert( DbMaskTest(p->btreeMask, iDb) );
  83990. iMoved = 0; /* Not needed. Only to silence a warning. */
  83991. rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
  83992. pOut->flags = MEM_Int;
  83993. pOut->u.i = iMoved;
  83994. if( rc ) goto abort_due_to_error;
  83995. #ifndef SQLITE_OMIT_AUTOVACUUM
  83996. if( iMoved!=0 ){
  83997. sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1);
  83998. /* All OP_Destroy operations occur on the same btree */
  83999. assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 );
  84000. resetSchemaOnFault = iDb+1;
  84001. }
  84002. #endif
  84003. }
  84004. break;
  84005. }
  84006. /* Opcode: Clear P1 P2 P3
  84007. **
  84008. ** Delete all contents of the database table or index whose root page
  84009. ** in the database file is given by P1. But, unlike Destroy, do not
  84010. ** remove the table or index from the database file.
  84011. **
  84012. ** The table being clear is in the main database file if P2==0. If
  84013. ** P2==1 then the table to be clear is in the auxiliary database file
  84014. ** that is used to store tables create using CREATE TEMPORARY TABLE.
  84015. **
  84016. ** If the P3 value is non-zero, then the table referred to must be an
  84017. ** intkey table (an SQL table, not an index). In this case the row change
  84018. ** count is incremented by the number of rows in the table being cleared.
  84019. ** If P3 is greater than zero, then the value stored in register P3 is
  84020. ** also incremented by the number of rows in the table being cleared.
  84021. **
  84022. ** See also: Destroy
  84023. */
  84024. case OP_Clear: {
  84025. int nChange;
  84026. sqlite3VdbeIncrWriteCounter(p, 0);
  84027. nChange = 0;
  84028. assert( p->readOnly==0 );
  84029. assert( DbMaskTest(p->btreeMask, pOp->p2) );
  84030. rc = sqlite3BtreeClearTable(
  84031. db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0)
  84032. );
  84033. if( pOp->p3 ){
  84034. p->nChange += nChange;
  84035. if( pOp->p3>0 ){
  84036. assert( memIsValid(&aMem[pOp->p3]) );
  84037. memAboutToChange(p, &aMem[pOp->p3]);
  84038. aMem[pOp->p3].u.i += nChange;
  84039. }
  84040. }
  84041. if( rc ) goto abort_due_to_error;
  84042. break;
  84043. }
  84044. /* Opcode: ResetSorter P1 * * * *
  84045. **
  84046. ** Delete all contents from the ephemeral table or sorter
  84047. ** that is open on cursor P1.
  84048. **
  84049. ** This opcode only works for cursors used for sorting and
  84050. ** opened with OP_OpenEphemeral or OP_SorterOpen.
  84051. */
  84052. case OP_ResetSorter: {
  84053. VdbeCursor *pC;
  84054. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  84055. pC = p->apCsr[pOp->p1];
  84056. assert( pC!=0 );
  84057. if( isSorter(pC) ){
  84058. sqlite3VdbeSorterReset(db, pC->uc.pSorter);
  84059. }else{
  84060. assert( pC->eCurType==CURTYPE_BTREE );
  84061. assert( pC->isEphemeral );
  84062. rc = sqlite3BtreeClearTableOfCursor(pC->uc.pCursor);
  84063. if( rc ) goto abort_due_to_error;
  84064. }
  84065. break;
  84066. }
  84067. /* Opcode: CreateBtree P1 P2 P3 * *
  84068. ** Synopsis: r[P2]=root iDb=P1 flags=P3
  84069. **
  84070. ** Allocate a new b-tree in the main database file if P1==0 or in the
  84071. ** TEMP database file if P1==1 or in an attached database if
  84072. ** P1>1. The P3 argument must be 1 (BTREE_INTKEY) for a rowid table
  84073. ** it must be 2 (BTREE_BLOBKEY) for an index or WITHOUT ROWID table.
  84074. ** The root page number of the new b-tree is stored in register P2.
  84075. */
  84076. case OP_CreateBtree: { /* out2 */
  84077. int pgno;
  84078. Db *pDb;
  84079. sqlite3VdbeIncrWriteCounter(p, 0);
  84080. pOut = out2Prerelease(p, pOp);
  84081. pgno = 0;
  84082. assert( pOp->p3==BTREE_INTKEY || pOp->p3==BTREE_BLOBKEY );
  84083. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  84084. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  84085. assert( p->readOnly==0 );
  84086. pDb = &db->aDb[pOp->p1];
  84087. assert( pDb->pBt!=0 );
  84088. rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, pOp->p3);
  84089. if( rc ) goto abort_due_to_error;
  84090. pOut->u.i = pgno;
  84091. break;
  84092. }
  84093. /* Opcode: SqlExec * * * P4 *
  84094. **
  84095. ** Run the SQL statement or statements specified in the P4 string.
  84096. */
  84097. case OP_SqlExec: {
  84098. sqlite3VdbeIncrWriteCounter(p, 0);
  84099. db->nSqlExec++;
  84100. rc = sqlite3_exec(db, pOp->p4.z, 0, 0, 0);
  84101. db->nSqlExec--;
  84102. if( rc ) goto abort_due_to_error;
  84103. break;
  84104. }
  84105. /* Opcode: ParseSchema P1 * * P4 *
  84106. **
  84107. ** Read and parse all entries from the SQLITE_MASTER table of database P1
  84108. ** that match the WHERE clause P4. If P4 is a NULL pointer, then the
  84109. ** entire schema for P1 is reparsed.
  84110. **
  84111. ** This opcode invokes the parser to create a new virtual machine,
  84112. ** then runs the new virtual machine. It is thus a re-entrant opcode.
  84113. */
  84114. case OP_ParseSchema: {
  84115. int iDb;
  84116. const char *zMaster;
  84117. char *zSql;
  84118. InitData initData;
  84119. /* Any prepared statement that invokes this opcode will hold mutexes
  84120. ** on every btree. This is a prerequisite for invoking
  84121. ** sqlite3InitCallback().
  84122. */
  84123. #ifdef SQLITE_DEBUG
  84124. for(iDb=0; iDb<db->nDb; iDb++){
  84125. assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
  84126. }
  84127. #endif
  84128. iDb = pOp->p1;
  84129. assert( iDb>=0 && iDb<db->nDb );
  84130. assert( DbHasProperty(db, iDb, DB_SchemaLoaded) );
  84131. #ifndef SQLITE_OMIT_ALTERTABLE
  84132. if( pOp->p4.z==0 ){
  84133. sqlite3SchemaClear(db->aDb[iDb].pSchema);
  84134. db->mDbFlags &= ~DBFLAG_SchemaKnownOk;
  84135. rc = sqlite3InitOne(db, iDb, &p->zErrMsg, INITFLAG_AlterTable);
  84136. db->mDbFlags |= DBFLAG_SchemaChange;
  84137. p->expired = 0;
  84138. }else
  84139. #endif
  84140. {
  84141. zMaster = MASTER_NAME;
  84142. initData.db = db;
  84143. initData.iDb = iDb;
  84144. initData.pzErrMsg = &p->zErrMsg;
  84145. initData.mInitFlags = 0;
  84146. zSql = sqlite3MPrintf(db,
  84147. "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
  84148. db->aDb[iDb].zDbSName, zMaster, pOp->p4.z);
  84149. if( zSql==0 ){
  84150. rc = SQLITE_NOMEM_BKPT;
  84151. }else{
  84152. assert( db->init.busy==0 );
  84153. db->init.busy = 1;
  84154. initData.rc = SQLITE_OK;
  84155. initData.nInitRow = 0;
  84156. assert( !db->mallocFailed );
  84157. rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
  84158. if( rc==SQLITE_OK ) rc = initData.rc;
  84159. if( rc==SQLITE_OK && initData.nInitRow==0 ){
  84160. /* The OP_ParseSchema opcode with a non-NULL P4 argument should parse
  84161. ** at least one SQL statement. Any less than that indicates that
  84162. ** the sqlite_master table is corrupt. */
  84163. rc = SQLITE_CORRUPT_BKPT;
  84164. }
  84165. sqlite3DbFreeNN(db, zSql);
  84166. db->init.busy = 0;
  84167. }
  84168. }
  84169. if( rc ){
  84170. sqlite3ResetAllSchemasOfConnection(db);
  84171. if( rc==SQLITE_NOMEM ){
  84172. goto no_mem;
  84173. }
  84174. goto abort_due_to_error;
  84175. }
  84176. break;
  84177. }
  84178. #if !defined(SQLITE_OMIT_ANALYZE)
  84179. /* Opcode: LoadAnalysis P1 * * * *
  84180. **
  84181. ** Read the sqlite_stat1 table for database P1 and load the content
  84182. ** of that table into the internal index hash table. This will cause
  84183. ** the analysis to be used when preparing all subsequent queries.
  84184. */
  84185. case OP_LoadAnalysis: {
  84186. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  84187. rc = sqlite3AnalysisLoad(db, pOp->p1);
  84188. if( rc ) goto abort_due_to_error;
  84189. break;
  84190. }
  84191. #endif /* !defined(SQLITE_OMIT_ANALYZE) */
  84192. /* Opcode: DropTable P1 * * P4 *
  84193. **
  84194. ** Remove the internal (in-memory) data structures that describe
  84195. ** the table named P4 in database P1. This is called after a table
  84196. ** is dropped from disk (using the Destroy opcode) in order to keep
  84197. ** the internal representation of the
  84198. ** schema consistent with what is on disk.
  84199. */
  84200. case OP_DropTable: {
  84201. sqlite3VdbeIncrWriteCounter(p, 0);
  84202. sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
  84203. break;
  84204. }
  84205. /* Opcode: DropIndex P1 * * P4 *
  84206. **
  84207. ** Remove the internal (in-memory) data structures that describe
  84208. ** the index named P4 in database P1. This is called after an index
  84209. ** is dropped from disk (using the Destroy opcode)
  84210. ** in order to keep the internal representation of the
  84211. ** schema consistent with what is on disk.
  84212. */
  84213. case OP_DropIndex: {
  84214. sqlite3VdbeIncrWriteCounter(p, 0);
  84215. sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
  84216. break;
  84217. }
  84218. /* Opcode: DropTrigger P1 * * P4 *
  84219. **
  84220. ** Remove the internal (in-memory) data structures that describe
  84221. ** the trigger named P4 in database P1. This is called after a trigger
  84222. ** is dropped from disk (using the Destroy opcode) in order to keep
  84223. ** the internal representation of the
  84224. ** schema consistent with what is on disk.
  84225. */
  84226. case OP_DropTrigger: {
  84227. sqlite3VdbeIncrWriteCounter(p, 0);
  84228. sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
  84229. break;
  84230. }
  84231. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  84232. /* Opcode: IntegrityCk P1 P2 P3 P4 P5
  84233. **
  84234. ** Do an analysis of the currently open database. Store in
  84235. ** register P1 the text of an error message describing any problems.
  84236. ** If no problems are found, store a NULL in register P1.
  84237. **
  84238. ** The register P3 contains one less than the maximum number of allowed errors.
  84239. ** At most reg(P3) errors will be reported.
  84240. ** In other words, the analysis stops as soon as reg(P1) errors are
  84241. ** seen. Reg(P1) is updated with the number of errors remaining.
  84242. **
  84243. ** The root page numbers of all tables in the database are integers
  84244. ** stored in P4_INTARRAY argument.
  84245. **
  84246. ** If P5 is not zero, the check is done on the auxiliary database
  84247. ** file, not the main database file.
  84248. **
  84249. ** This opcode is used to implement the integrity_check pragma.
  84250. */
  84251. case OP_IntegrityCk: {
  84252. int nRoot; /* Number of tables to check. (Number of root pages.) */
  84253. int *aRoot; /* Array of rootpage numbers for tables to be checked */
  84254. int nErr; /* Number of errors reported */
  84255. char *z; /* Text of the error report */
  84256. Mem *pnErr; /* Register keeping track of errors remaining */
  84257. assert( p->bIsReader );
  84258. nRoot = pOp->p2;
  84259. aRoot = pOp->p4.ai;
  84260. assert( nRoot>0 );
  84261. assert( aRoot[0]==nRoot );
  84262. assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
  84263. pnErr = &aMem[pOp->p3];
  84264. assert( (pnErr->flags & MEM_Int)!=0 );
  84265. assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
  84266. pIn1 = &aMem[pOp->p1];
  84267. assert( pOp->p5<db->nDb );
  84268. assert( DbMaskTest(p->btreeMask, pOp->p5) );
  84269. z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, &aRoot[1], nRoot,
  84270. (int)pnErr->u.i+1, &nErr);
  84271. sqlite3VdbeMemSetNull(pIn1);
  84272. if( nErr==0 ){
  84273. assert( z==0 );
  84274. }else if( z==0 ){
  84275. goto no_mem;
  84276. }else{
  84277. pnErr->u.i -= nErr-1;
  84278. sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
  84279. }
  84280. UPDATE_MAX_BLOBSIZE(pIn1);
  84281. sqlite3VdbeChangeEncoding(pIn1, encoding);
  84282. break;
  84283. }
  84284. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  84285. /* Opcode: RowSetAdd P1 P2 * * *
  84286. ** Synopsis: rowset(P1)=r[P2]
  84287. **
  84288. ** Insert the integer value held by register P2 into a RowSet object
  84289. ** held in register P1.
  84290. **
  84291. ** An assertion fails if P2 is not an integer.
  84292. */
  84293. case OP_RowSetAdd: { /* in1, in2 */
  84294. pIn1 = &aMem[pOp->p1];
  84295. pIn2 = &aMem[pOp->p2];
  84296. assert( (pIn2->flags & MEM_Int)!=0 );
  84297. if( (pIn1->flags & MEM_Blob)==0 ){
  84298. if( sqlite3VdbeMemSetRowSet(pIn1) ) goto no_mem;
  84299. }
  84300. assert( sqlite3VdbeMemIsRowSet(pIn1) );
  84301. sqlite3RowSetInsert((RowSet*)pIn1->z, pIn2->u.i);
  84302. break;
  84303. }
  84304. /* Opcode: RowSetRead P1 P2 P3 * *
  84305. ** Synopsis: r[P3]=rowset(P1)
  84306. **
  84307. ** Extract the smallest value from the RowSet object in P1
  84308. ** and put that value into register P3.
  84309. ** Or, if RowSet object P1 is initially empty, leave P3
  84310. ** unchanged and jump to instruction P2.
  84311. */
  84312. case OP_RowSetRead: { /* jump, in1, out3 */
  84313. i64 val;
  84314. pIn1 = &aMem[pOp->p1];
  84315. assert( (pIn1->flags & MEM_Blob)==0 || sqlite3VdbeMemIsRowSet(pIn1) );
  84316. if( (pIn1->flags & MEM_Blob)==0
  84317. || sqlite3RowSetNext((RowSet*)pIn1->z, &val)==0
  84318. ){
  84319. /* The boolean index is empty */
  84320. sqlite3VdbeMemSetNull(pIn1);
  84321. VdbeBranchTaken(1,2);
  84322. goto jump_to_p2_and_check_for_interrupt;
  84323. }else{
  84324. /* A value was pulled from the index */
  84325. VdbeBranchTaken(0,2);
  84326. sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val);
  84327. }
  84328. goto check_for_interrupt;
  84329. }
  84330. /* Opcode: RowSetTest P1 P2 P3 P4
  84331. ** Synopsis: if r[P3] in rowset(P1) goto P2
  84332. **
  84333. ** Register P3 is assumed to hold a 64-bit integer value. If register P1
  84334. ** contains a RowSet object and that RowSet object contains
  84335. ** the value held in P3, jump to register P2. Otherwise, insert the
  84336. ** integer in P3 into the RowSet and continue on to the
  84337. ** next opcode.
  84338. **
  84339. ** The RowSet object is optimized for the case where sets of integers
  84340. ** are inserted in distinct phases, which each set contains no duplicates.
  84341. ** Each set is identified by a unique P4 value. The first set
  84342. ** must have P4==0, the final set must have P4==-1, and for all other sets
  84343. ** must have P4>0.
  84344. **
  84345. ** This allows optimizations: (a) when P4==0 there is no need to test
  84346. ** the RowSet object for P3, as it is guaranteed not to contain it,
  84347. ** (b) when P4==-1 there is no need to insert the value, as it will
  84348. ** never be tested for, and (c) when a value that is part of set X is
  84349. ** inserted, there is no need to search to see if the same value was
  84350. ** previously inserted as part of set X (only if it was previously
  84351. ** inserted as part of some other set).
  84352. */
  84353. case OP_RowSetTest: { /* jump, in1, in3 */
  84354. int iSet;
  84355. int exists;
  84356. pIn1 = &aMem[pOp->p1];
  84357. pIn3 = &aMem[pOp->p3];
  84358. iSet = pOp->p4.i;
  84359. assert( pIn3->flags&MEM_Int );
  84360. /* If there is anything other than a rowset object in memory cell P1,
  84361. ** delete it now and initialize P1 with an empty rowset
  84362. */
  84363. if( (pIn1->flags & MEM_Blob)==0 ){
  84364. if( sqlite3VdbeMemSetRowSet(pIn1) ) goto no_mem;
  84365. }
  84366. assert( sqlite3VdbeMemIsRowSet(pIn1) );
  84367. assert( pOp->p4type==P4_INT32 );
  84368. assert( iSet==-1 || iSet>=0 );
  84369. if( iSet ){
  84370. exists = sqlite3RowSetTest((RowSet*)pIn1->z, iSet, pIn3->u.i);
  84371. VdbeBranchTaken(exists!=0,2);
  84372. if( exists ) goto jump_to_p2;
  84373. }
  84374. if( iSet>=0 ){
  84375. sqlite3RowSetInsert((RowSet*)pIn1->z, pIn3->u.i);
  84376. }
  84377. break;
  84378. }
  84379. #ifndef SQLITE_OMIT_TRIGGER
  84380. /* Opcode: Program P1 P2 P3 P4 P5
  84381. **
  84382. ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
  84383. **
  84384. ** P1 contains the address of the memory cell that contains the first memory
  84385. ** cell in an array of values used as arguments to the sub-program. P2
  84386. ** contains the address to jump to if the sub-program throws an IGNORE
  84387. ** exception using the RAISE() function. Register P3 contains the address
  84388. ** of a memory cell in this (the parent) VM that is used to allocate the
  84389. ** memory required by the sub-vdbe at runtime.
  84390. **
  84391. ** P4 is a pointer to the VM containing the trigger program.
  84392. **
  84393. ** If P5 is non-zero, then recursive program invocation is enabled.
  84394. */
  84395. case OP_Program: { /* jump */
  84396. int nMem; /* Number of memory registers for sub-program */
  84397. int nByte; /* Bytes of runtime space required for sub-program */
  84398. Mem *pRt; /* Register to allocate runtime space */
  84399. Mem *pMem; /* Used to iterate through memory cells */
  84400. Mem *pEnd; /* Last memory cell in new array */
  84401. VdbeFrame *pFrame; /* New vdbe frame to execute in */
  84402. SubProgram *pProgram; /* Sub-program to execute */
  84403. void *t; /* Token identifying trigger */
  84404. pProgram = pOp->p4.pProgram;
  84405. pRt = &aMem[pOp->p3];
  84406. assert( pProgram->nOp>0 );
  84407. /* If the p5 flag is clear, then recursive invocation of triggers is
  84408. ** disabled for backwards compatibility (p5 is set if this sub-program
  84409. ** is really a trigger, not a foreign key action, and the flag set
  84410. ** and cleared by the "PRAGMA recursive_triggers" command is clear).
  84411. **
  84412. ** It is recursive invocation of triggers, at the SQL level, that is
  84413. ** disabled. In some cases a single trigger may generate more than one
  84414. ** SubProgram (if the trigger may be executed with more than one different
  84415. ** ON CONFLICT algorithm). SubProgram structures associated with a
  84416. ** single trigger all have the same value for the SubProgram.token
  84417. ** variable. */
  84418. if( pOp->p5 ){
  84419. t = pProgram->token;
  84420. for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
  84421. if( pFrame ) break;
  84422. }
  84423. if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
  84424. rc = SQLITE_ERROR;
  84425. sqlite3VdbeError(p, "too many levels of trigger recursion");
  84426. goto abort_due_to_error;
  84427. }
  84428. /* Register pRt is used to store the memory required to save the state
  84429. ** of the current program, and the memory required at runtime to execute
  84430. ** the trigger program. If this trigger has been fired before, then pRt
  84431. ** is already allocated. Otherwise, it must be initialized. */
  84432. if( (pRt->flags&MEM_Blob)==0 ){
  84433. /* SubProgram.nMem is set to the number of memory cells used by the
  84434. ** program stored in SubProgram.aOp. As well as these, one memory
  84435. ** cell is required for each cursor used by the program. Set local
  84436. ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
  84437. */
  84438. nMem = pProgram->nMem + pProgram->nCsr;
  84439. assert( nMem>0 );
  84440. if( pProgram->nCsr==0 ) nMem++;
  84441. nByte = ROUND8(sizeof(VdbeFrame))
  84442. + nMem * sizeof(Mem)
  84443. + pProgram->nCsr * sizeof(VdbeCursor*)
  84444. + (pProgram->nOp + 7)/8;
  84445. pFrame = sqlite3DbMallocZero(db, nByte);
  84446. if( !pFrame ){
  84447. goto no_mem;
  84448. }
  84449. sqlite3VdbeMemRelease(pRt);
  84450. pRt->flags = MEM_Blob|MEM_Dyn;
  84451. pRt->z = (char*)pFrame;
  84452. pRt->n = nByte;
  84453. pRt->xDel = sqlite3VdbeFrameMemDel;
  84454. pFrame->v = p;
  84455. pFrame->nChildMem = nMem;
  84456. pFrame->nChildCsr = pProgram->nCsr;
  84457. pFrame->pc = (int)(pOp - aOp);
  84458. pFrame->aMem = p->aMem;
  84459. pFrame->nMem = p->nMem;
  84460. pFrame->apCsr = p->apCsr;
  84461. pFrame->nCursor = p->nCursor;
  84462. pFrame->aOp = p->aOp;
  84463. pFrame->nOp = p->nOp;
  84464. pFrame->token = pProgram->token;
  84465. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  84466. pFrame->anExec = p->anExec;
  84467. #endif
  84468. #ifdef SQLITE_DEBUG
  84469. pFrame->iFrameMagic = SQLITE_FRAME_MAGIC;
  84470. #endif
  84471. pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
  84472. for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){
  84473. pMem->flags = MEM_Undefined;
  84474. pMem->db = db;
  84475. }
  84476. }else{
  84477. pFrame = (VdbeFrame*)pRt->z;
  84478. assert( pRt->xDel==sqlite3VdbeFrameMemDel );
  84479. assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem
  84480. || (pProgram->nCsr==0 && pProgram->nMem+1==pFrame->nChildMem) );
  84481. assert( pProgram->nCsr==pFrame->nChildCsr );
  84482. assert( (int)(pOp - aOp)==pFrame->pc );
  84483. }
  84484. p->nFrame++;
  84485. pFrame->pParent = p->pFrame;
  84486. pFrame->lastRowid = db->lastRowid;
  84487. pFrame->nChange = p->nChange;
  84488. pFrame->nDbChange = p->db->nChange;
  84489. assert( pFrame->pAuxData==0 );
  84490. pFrame->pAuxData = p->pAuxData;
  84491. p->pAuxData = 0;
  84492. p->nChange = 0;
  84493. p->pFrame = pFrame;
  84494. p->aMem = aMem = VdbeFrameMem(pFrame);
  84495. p->nMem = pFrame->nChildMem;
  84496. p->nCursor = (u16)pFrame->nChildCsr;
  84497. p->apCsr = (VdbeCursor **)&aMem[p->nMem];
  84498. pFrame->aOnce = (u8*)&p->apCsr[pProgram->nCsr];
  84499. memset(pFrame->aOnce, 0, (pProgram->nOp + 7)/8);
  84500. p->aOp = aOp = pProgram->aOp;
  84501. p->nOp = pProgram->nOp;
  84502. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  84503. p->anExec = 0;
  84504. #endif
  84505. #ifdef SQLITE_DEBUG
  84506. /* Verify that second and subsequent executions of the same trigger do not
  84507. ** try to reuse register values from the first use. */
  84508. {
  84509. int i;
  84510. for(i=0; i<p->nMem; i++){
  84511. aMem[i].pScopyFrom = 0; /* Prevent false-positive AboutToChange() errs */
  84512. aMem[i].flags |= MEM_Undefined; /* Cause a fault if this reg is reused */
  84513. }
  84514. }
  84515. #endif
  84516. pOp = &aOp[-1];
  84517. goto check_for_interrupt;
  84518. }
  84519. /* Opcode: Param P1 P2 * * *
  84520. **
  84521. ** This opcode is only ever present in sub-programs called via the
  84522. ** OP_Program instruction. Copy a value currently stored in a memory
  84523. ** cell of the calling (parent) frame to cell P2 in the current frames
  84524. ** address space. This is used by trigger programs to access the new.*
  84525. ** and old.* values.
  84526. **
  84527. ** The address of the cell in the parent frame is determined by adding
  84528. ** the value of the P1 argument to the value of the P1 argument to the
  84529. ** calling OP_Program instruction.
  84530. */
  84531. case OP_Param: { /* out2 */
  84532. VdbeFrame *pFrame;
  84533. Mem *pIn;
  84534. pOut = out2Prerelease(p, pOp);
  84535. pFrame = p->pFrame;
  84536. pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];
  84537. sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem);
  84538. break;
  84539. }
  84540. #endif /* #ifndef SQLITE_OMIT_TRIGGER */
  84541. #ifndef SQLITE_OMIT_FOREIGN_KEY
  84542. /* Opcode: FkCounter P1 P2 * * *
  84543. ** Synopsis: fkctr[P1]+=P2
  84544. **
  84545. ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
  84546. ** If P1 is non-zero, the database constraint counter is incremented
  84547. ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
  84548. ** statement counter is incremented (immediate foreign key constraints).
  84549. */
  84550. case OP_FkCounter: {
  84551. if( db->flags & SQLITE_DeferFKs ){
  84552. db->nDeferredImmCons += pOp->p2;
  84553. }else if( pOp->p1 ){
  84554. db->nDeferredCons += pOp->p2;
  84555. }else{
  84556. p->nFkConstraint += pOp->p2;
  84557. }
  84558. break;
  84559. }
  84560. /* Opcode: FkIfZero P1 P2 * * *
  84561. ** Synopsis: if fkctr[P1]==0 goto P2
  84562. **
  84563. ** This opcode tests if a foreign key constraint-counter is currently zero.
  84564. ** If so, jump to instruction P2. Otherwise, fall through to the next
  84565. ** instruction.
  84566. **
  84567. ** If P1 is non-zero, then the jump is taken if the database constraint-counter
  84568. ** is zero (the one that counts deferred constraint violations). If P1 is
  84569. ** zero, the jump is taken if the statement constraint-counter is zero
  84570. ** (immediate foreign key constraint violations).
  84571. */
  84572. case OP_FkIfZero: { /* jump */
  84573. if( pOp->p1 ){
  84574. VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2);
  84575. if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
  84576. }else{
  84577. VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2);
  84578. if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
  84579. }
  84580. break;
  84581. }
  84582. #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
  84583. #ifndef SQLITE_OMIT_AUTOINCREMENT
  84584. /* Opcode: MemMax P1 P2 * * *
  84585. ** Synopsis: r[P1]=max(r[P1],r[P2])
  84586. **
  84587. ** P1 is a register in the root frame of this VM (the root frame is
  84588. ** different from the current frame if this instruction is being executed
  84589. ** within a sub-program). Set the value of register P1 to the maximum of
  84590. ** its current value and the value in register P2.
  84591. **
  84592. ** This instruction throws an error if the memory cell is not initially
  84593. ** an integer.
  84594. */
  84595. case OP_MemMax: { /* in2 */
  84596. VdbeFrame *pFrame;
  84597. if( p->pFrame ){
  84598. for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
  84599. pIn1 = &pFrame->aMem[pOp->p1];
  84600. }else{
  84601. pIn1 = &aMem[pOp->p1];
  84602. }
  84603. assert( memIsValid(pIn1) );
  84604. sqlite3VdbeMemIntegerify(pIn1);
  84605. pIn2 = &aMem[pOp->p2];
  84606. sqlite3VdbeMemIntegerify(pIn2);
  84607. if( pIn1->u.i<pIn2->u.i){
  84608. pIn1->u.i = pIn2->u.i;
  84609. }
  84610. break;
  84611. }
  84612. #endif /* SQLITE_OMIT_AUTOINCREMENT */
  84613. /* Opcode: IfPos P1 P2 P3 * *
  84614. ** Synopsis: if r[P1]>0 then r[P1]-=P3, goto P2
  84615. **
  84616. ** Register P1 must contain an integer.
  84617. ** If the value of register P1 is 1 or greater, subtract P3 from the
  84618. ** value in P1 and jump to P2.
  84619. **
  84620. ** If the initial value of register P1 is less than 1, then the
  84621. ** value is unchanged and control passes through to the next instruction.
  84622. */
  84623. case OP_IfPos: { /* jump, in1 */
  84624. pIn1 = &aMem[pOp->p1];
  84625. assert( pIn1->flags&MEM_Int );
  84626. VdbeBranchTaken( pIn1->u.i>0, 2);
  84627. if( pIn1->u.i>0 ){
  84628. pIn1->u.i -= pOp->p3;
  84629. goto jump_to_p2;
  84630. }
  84631. break;
  84632. }
  84633. /* Opcode: OffsetLimit P1 P2 P3 * *
  84634. ** Synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)
  84635. **
  84636. ** This opcode performs a commonly used computation associated with
  84637. ** LIMIT and OFFSET process. r[P1] holds the limit counter. r[P3]
  84638. ** holds the offset counter. The opcode computes the combined value
  84639. ** of the LIMIT and OFFSET and stores that value in r[P2]. The r[P2]
  84640. ** value computed is the total number of rows that will need to be
  84641. ** visited in order to complete the query.
  84642. **
  84643. ** If r[P3] is zero or negative, that means there is no OFFSET
  84644. ** and r[P2] is set to be the value of the LIMIT, r[P1].
  84645. **
  84646. ** if r[P1] is zero or negative, that means there is no LIMIT
  84647. ** and r[P2] is set to -1.
  84648. **
  84649. ** Otherwise, r[P2] is set to the sum of r[P1] and r[P3].
  84650. */
  84651. case OP_OffsetLimit: { /* in1, out2, in3 */
  84652. i64 x;
  84653. pIn1 = &aMem[pOp->p1];
  84654. pIn3 = &aMem[pOp->p3];
  84655. pOut = out2Prerelease(p, pOp);
  84656. assert( pIn1->flags & MEM_Int );
  84657. assert( pIn3->flags & MEM_Int );
  84658. x = pIn1->u.i;
  84659. if( x<=0 || sqlite3AddInt64(&x, pIn3->u.i>0?pIn3->u.i:0) ){
  84660. /* If the LIMIT is less than or equal to zero, loop forever. This
  84661. ** is documented. But also, if the LIMIT+OFFSET exceeds 2^63 then
  84662. ** also loop forever. This is undocumented. In fact, one could argue
  84663. ** that the loop should terminate. But assuming 1 billion iterations
  84664. ** per second (far exceeding the capabilities of any current hardware)
  84665. ** it would take nearly 300 years to actually reach the limit. So
  84666. ** looping forever is a reasonable approximation. */
  84667. pOut->u.i = -1;
  84668. }else{
  84669. pOut->u.i = x;
  84670. }
  84671. break;
  84672. }
  84673. /* Opcode: IfNotZero P1 P2 * * *
  84674. ** Synopsis: if r[P1]!=0 then r[P1]--, goto P2
  84675. **
  84676. ** Register P1 must contain an integer. If the content of register P1 is
  84677. ** initially greater than zero, then decrement the value in register P1.
  84678. ** If it is non-zero (negative or positive) and then also jump to P2.
  84679. ** If register P1 is initially zero, leave it unchanged and fall through.
  84680. */
  84681. case OP_IfNotZero: { /* jump, in1 */
  84682. pIn1 = &aMem[pOp->p1];
  84683. assert( pIn1->flags&MEM_Int );
  84684. VdbeBranchTaken(pIn1->u.i<0, 2);
  84685. if( pIn1->u.i ){
  84686. if( pIn1->u.i>0 ) pIn1->u.i--;
  84687. goto jump_to_p2;
  84688. }
  84689. break;
  84690. }
  84691. /* Opcode: DecrJumpZero P1 P2 * * *
  84692. ** Synopsis: if (--r[P1])==0 goto P2
  84693. **
  84694. ** Register P1 must hold an integer. Decrement the value in P1
  84695. ** and jump to P2 if the new value is exactly zero.
  84696. */
  84697. case OP_DecrJumpZero: { /* jump, in1 */
  84698. pIn1 = &aMem[pOp->p1];
  84699. assert( pIn1->flags&MEM_Int );
  84700. if( pIn1->u.i>SMALLEST_INT64 ) pIn1->u.i--;
  84701. VdbeBranchTaken(pIn1->u.i==0, 2);
  84702. if( pIn1->u.i==0 ) goto jump_to_p2;
  84703. break;
  84704. }
  84705. /* Opcode: AggStep * P2 P3 P4 P5
  84706. ** Synopsis: accum=r[P3] step(r[P2@P5])
  84707. **
  84708. ** Execute the xStep function for an aggregate.
  84709. ** The function has P5 arguments. P4 is a pointer to the
  84710. ** FuncDef structure that specifies the function. Register P3 is the
  84711. ** accumulator.
  84712. **
  84713. ** The P5 arguments are taken from register P2 and its
  84714. ** successors.
  84715. */
  84716. /* Opcode: AggInverse * P2 P3 P4 P5
  84717. ** Synopsis: accum=r[P3] inverse(r[P2@P5])
  84718. **
  84719. ** Execute the xInverse function for an aggregate.
  84720. ** The function has P5 arguments. P4 is a pointer to the
  84721. ** FuncDef structure that specifies the function. Register P3 is the
  84722. ** accumulator.
  84723. **
  84724. ** The P5 arguments are taken from register P2 and its
  84725. ** successors.
  84726. */
  84727. /* Opcode: AggStep1 P1 P2 P3 P4 P5
  84728. ** Synopsis: accum=r[P3] step(r[P2@P5])
  84729. **
  84730. ** Execute the xStep (if P1==0) or xInverse (if P1!=0) function for an
  84731. ** aggregate. The function has P5 arguments. P4 is a pointer to the
  84732. ** FuncDef structure that specifies the function. Register P3 is the
  84733. ** accumulator.
  84734. **
  84735. ** The P5 arguments are taken from register P2 and its
  84736. ** successors.
  84737. **
  84738. ** This opcode is initially coded as OP_AggStep0. On first evaluation,
  84739. ** the FuncDef stored in P4 is converted into an sqlite3_context and
  84740. ** the opcode is changed. In this way, the initialization of the
  84741. ** sqlite3_context only happens once, instead of on each call to the
  84742. ** step function.
  84743. */
  84744. case OP_AggInverse:
  84745. case OP_AggStep: {
  84746. int n;
  84747. sqlite3_context *pCtx;
  84748. assert( pOp->p4type==P4_FUNCDEF );
  84749. n = pOp->p5;
  84750. assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
  84751. assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
  84752. assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
  84753. pCtx = sqlite3DbMallocRawNN(db, n*sizeof(sqlite3_value*) +
  84754. (sizeof(pCtx[0]) + sizeof(Mem) - sizeof(sqlite3_value*)));
  84755. if( pCtx==0 ) goto no_mem;
  84756. pCtx->pMem = 0;
  84757. pCtx->pOut = (Mem*)&(pCtx->argv[n]);
  84758. sqlite3VdbeMemInit(pCtx->pOut, db, MEM_Null);
  84759. pCtx->pFunc = pOp->p4.pFunc;
  84760. pCtx->iOp = (int)(pOp - aOp);
  84761. pCtx->pVdbe = p;
  84762. pCtx->skipFlag = 0;
  84763. pCtx->isError = 0;
  84764. pCtx->argc = n;
  84765. pOp->p4type = P4_FUNCCTX;
  84766. pOp->p4.pCtx = pCtx;
  84767. /* OP_AggInverse must have P1==1 and OP_AggStep must have P1==0 */
  84768. assert( pOp->p1==(pOp->opcode==OP_AggInverse) );
  84769. pOp->opcode = OP_AggStep1;
  84770. /* Fall through into OP_AggStep */
  84771. }
  84772. case OP_AggStep1: {
  84773. int i;
  84774. sqlite3_context *pCtx;
  84775. Mem *pMem;
  84776. assert( pOp->p4type==P4_FUNCCTX );
  84777. pCtx = pOp->p4.pCtx;
  84778. pMem = &aMem[pOp->p3];
  84779. #ifdef SQLITE_DEBUG
  84780. if( pOp->p1 ){
  84781. /* This is an OP_AggInverse call. Verify that xStep has always
  84782. ** been called at least once prior to any xInverse call. */
  84783. assert( pMem->uTemp==0x1122e0e3 );
  84784. }else{
  84785. /* This is an OP_AggStep call. Mark it as such. */
  84786. pMem->uTemp = 0x1122e0e3;
  84787. }
  84788. #endif
  84789. /* If this function is inside of a trigger, the register array in aMem[]
  84790. ** might change from one evaluation to the next. The next block of code
  84791. ** checks to see if the register array has changed, and if so it
  84792. ** reinitializes the relavant parts of the sqlite3_context object */
  84793. if( pCtx->pMem != pMem ){
  84794. pCtx->pMem = pMem;
  84795. for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
  84796. }
  84797. #ifdef SQLITE_DEBUG
  84798. for(i=0; i<pCtx->argc; i++){
  84799. assert( memIsValid(pCtx->argv[i]) );
  84800. REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
  84801. }
  84802. #endif
  84803. pMem->n++;
  84804. assert( pCtx->pOut->flags==MEM_Null );
  84805. assert( pCtx->isError==0 );
  84806. assert( pCtx->skipFlag==0 );
  84807. #ifndef SQLITE_OMIT_WINDOWFUNC
  84808. if( pOp->p1 ){
  84809. (pCtx->pFunc->xInverse)(pCtx,pCtx->argc,pCtx->argv);
  84810. }else
  84811. #endif
  84812. (pCtx->pFunc->xSFunc)(pCtx,pCtx->argc,pCtx->argv); /* IMP: R-24505-23230 */
  84813. if( pCtx->isError ){
  84814. if( pCtx->isError>0 ){
  84815. sqlite3VdbeError(p, "%s", sqlite3_value_text(pCtx->pOut));
  84816. rc = pCtx->isError;
  84817. }
  84818. if( pCtx->skipFlag ){
  84819. assert( pOp[-1].opcode==OP_CollSeq );
  84820. i = pOp[-1].p1;
  84821. if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1);
  84822. pCtx->skipFlag = 0;
  84823. }
  84824. sqlite3VdbeMemRelease(pCtx->pOut);
  84825. pCtx->pOut->flags = MEM_Null;
  84826. pCtx->isError = 0;
  84827. if( rc ) goto abort_due_to_error;
  84828. }
  84829. assert( pCtx->pOut->flags==MEM_Null );
  84830. assert( pCtx->skipFlag==0 );
  84831. break;
  84832. }
  84833. /* Opcode: AggFinal P1 P2 * P4 *
  84834. ** Synopsis: accum=r[P1] N=P2
  84835. **
  84836. ** P1 is the memory location that is the accumulator for an aggregate
  84837. ** or window function. Execute the finalizer function
  84838. ** for an aggregate and store the result in P1.
  84839. **
  84840. ** P2 is the number of arguments that the step function takes and
  84841. ** P4 is a pointer to the FuncDef for this function. The P2
  84842. ** argument is not used by this opcode. It is only there to disambiguate
  84843. ** functions that can take varying numbers of arguments. The
  84844. ** P4 argument is only needed for the case where
  84845. ** the step function was not previously called.
  84846. */
  84847. /* Opcode: AggValue * P2 P3 P4 *
  84848. ** Synopsis: r[P3]=value N=P2
  84849. **
  84850. ** Invoke the xValue() function and store the result in register P3.
  84851. **
  84852. ** P2 is the number of arguments that the step function takes and
  84853. ** P4 is a pointer to the FuncDef for this function. The P2
  84854. ** argument is not used by this opcode. It is only there to disambiguate
  84855. ** functions that can take varying numbers of arguments. The
  84856. ** P4 argument is only needed for the case where
  84857. ** the step function was not previously called.
  84858. */
  84859. case OP_AggValue:
  84860. case OP_AggFinal: {
  84861. Mem *pMem;
  84862. assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
  84863. assert( pOp->p3==0 || pOp->opcode==OP_AggValue );
  84864. pMem = &aMem[pOp->p1];
  84865. assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
  84866. #ifndef SQLITE_OMIT_WINDOWFUNC
  84867. if( pOp->p3 ){
  84868. memAboutToChange(p, &aMem[pOp->p3]);
  84869. rc = sqlite3VdbeMemAggValue(pMem, &aMem[pOp->p3], pOp->p4.pFunc);
  84870. pMem = &aMem[pOp->p3];
  84871. }else
  84872. #endif
  84873. {
  84874. rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
  84875. }
  84876. if( rc ){
  84877. sqlite3VdbeError(p, "%s", sqlite3_value_text(pMem));
  84878. goto abort_due_to_error;
  84879. }
  84880. sqlite3VdbeChangeEncoding(pMem, encoding);
  84881. UPDATE_MAX_BLOBSIZE(pMem);
  84882. if( sqlite3VdbeMemTooBig(pMem) ){
  84883. goto too_big;
  84884. }
  84885. break;
  84886. }
  84887. #ifndef SQLITE_OMIT_WAL
  84888. /* Opcode: Checkpoint P1 P2 P3 * *
  84889. **
  84890. ** Checkpoint database P1. This is a no-op if P1 is not currently in
  84891. ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL,
  84892. ** RESTART, or TRUNCATE. Write 1 or 0 into mem[P3] if the checkpoint returns
  84893. ** SQLITE_BUSY or not, respectively. Write the number of pages in the
  84894. ** WAL after the checkpoint into mem[P3+1] and the number of pages
  84895. ** in the WAL that have been checkpointed after the checkpoint
  84896. ** completes into mem[P3+2]. However on an error, mem[P3+1] and
  84897. ** mem[P3+2] are initialized to -1.
  84898. */
  84899. case OP_Checkpoint: {
  84900. int i; /* Loop counter */
  84901. int aRes[3]; /* Results */
  84902. Mem *pMem; /* Write results here */
  84903. assert( p->readOnly==0 );
  84904. aRes[0] = 0;
  84905. aRes[1] = aRes[2] = -1;
  84906. assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
  84907. || pOp->p2==SQLITE_CHECKPOINT_FULL
  84908. || pOp->p2==SQLITE_CHECKPOINT_RESTART
  84909. || pOp->p2==SQLITE_CHECKPOINT_TRUNCATE
  84910. );
  84911. rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);
  84912. if( rc ){
  84913. if( rc!=SQLITE_BUSY ) goto abort_due_to_error;
  84914. rc = SQLITE_OK;
  84915. aRes[0] = 1;
  84916. }
  84917. for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){
  84918. sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]);
  84919. }
  84920. break;
  84921. };
  84922. #endif
  84923. #ifndef SQLITE_OMIT_PRAGMA
  84924. /* Opcode: JournalMode P1 P2 P3 * *
  84925. **
  84926. ** Change the journal mode of database P1 to P3. P3 must be one of the
  84927. ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
  84928. ** modes (delete, truncate, persist, off and memory), this is a simple
  84929. ** operation. No IO is required.
  84930. **
  84931. ** If changing into or out of WAL mode the procedure is more complicated.
  84932. **
  84933. ** Write a string containing the final journal-mode to register P2.
  84934. */
  84935. case OP_JournalMode: { /* out2 */
  84936. Btree *pBt; /* Btree to change journal mode of */
  84937. Pager *pPager; /* Pager associated with pBt */
  84938. int eNew; /* New journal mode */
  84939. int eOld; /* The old journal mode */
  84940. #ifndef SQLITE_OMIT_WAL
  84941. const char *zFilename; /* Name of database file for pPager */
  84942. #endif
  84943. pOut = out2Prerelease(p, pOp);
  84944. eNew = pOp->p3;
  84945. assert( eNew==PAGER_JOURNALMODE_DELETE
  84946. || eNew==PAGER_JOURNALMODE_TRUNCATE
  84947. || eNew==PAGER_JOURNALMODE_PERSIST
  84948. || eNew==PAGER_JOURNALMODE_OFF
  84949. || eNew==PAGER_JOURNALMODE_MEMORY
  84950. || eNew==PAGER_JOURNALMODE_WAL
  84951. || eNew==PAGER_JOURNALMODE_QUERY
  84952. );
  84953. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  84954. assert( p->readOnly==0 );
  84955. pBt = db->aDb[pOp->p1].pBt;
  84956. pPager = sqlite3BtreePager(pBt);
  84957. eOld = sqlite3PagerGetJournalMode(pPager);
  84958. if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld;
  84959. if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld;
  84960. #ifndef SQLITE_OMIT_WAL
  84961. zFilename = sqlite3PagerFilename(pPager, 1);
  84962. /* Do not allow a transition to journal_mode=WAL for a database
  84963. ** in temporary storage or if the VFS does not support shared memory
  84964. */
  84965. if( eNew==PAGER_JOURNALMODE_WAL
  84966. && (sqlite3Strlen30(zFilename)==0 /* Temp file */
  84967. || !sqlite3PagerWalSupported(pPager)) /* No shared-memory support */
  84968. ){
  84969. eNew = eOld;
  84970. }
  84971. if( (eNew!=eOld)
  84972. && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL)
  84973. ){
  84974. if( !db->autoCommit || db->nVdbeRead>1 ){
  84975. rc = SQLITE_ERROR;
  84976. sqlite3VdbeError(p,
  84977. "cannot change %s wal mode from within a transaction",
  84978. (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
  84979. );
  84980. goto abort_due_to_error;
  84981. }else{
  84982. if( eOld==PAGER_JOURNALMODE_WAL ){
  84983. /* If leaving WAL mode, close the log file. If successful, the call
  84984. ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
  84985. ** file. An EXCLUSIVE lock may still be held on the database file
  84986. ** after a successful return.
  84987. */
  84988. rc = sqlite3PagerCloseWal(pPager, db);
  84989. if( rc==SQLITE_OK ){
  84990. sqlite3PagerSetJournalMode(pPager, eNew);
  84991. }
  84992. }else if( eOld==PAGER_JOURNALMODE_MEMORY ){
  84993. /* Cannot transition directly from MEMORY to WAL. Use mode OFF
  84994. ** as an intermediate */
  84995. sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF);
  84996. }
  84997. /* Open a transaction on the database file. Regardless of the journal
  84998. ** mode, this transaction always uses a rollback journal.
  84999. */
  85000. assert( sqlite3BtreeIsInTrans(pBt)==0 );
  85001. if( rc==SQLITE_OK ){
  85002. rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
  85003. }
  85004. }
  85005. }
  85006. #endif /* ifndef SQLITE_OMIT_WAL */
  85007. if( rc ) eNew = eOld;
  85008. eNew = sqlite3PagerSetJournalMode(pPager, eNew);
  85009. pOut->flags = MEM_Str|MEM_Static|MEM_Term;
  85010. pOut->z = (char *)sqlite3JournalModename(eNew);
  85011. pOut->n = sqlite3Strlen30(pOut->z);
  85012. pOut->enc = SQLITE_UTF8;
  85013. sqlite3VdbeChangeEncoding(pOut, encoding);
  85014. if( rc ) goto abort_due_to_error;
  85015. break;
  85016. };
  85017. #endif /* SQLITE_OMIT_PRAGMA */
  85018. #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
  85019. /* Opcode: Vacuum P1 P2 * * *
  85020. **
  85021. ** Vacuum the entire database P1. P1 is 0 for "main", and 2 or more
  85022. ** for an attached database. The "temp" database may not be vacuumed.
  85023. **
  85024. ** If P2 is not zero, then it is a register holding a string which is
  85025. ** the file into which the result of vacuum should be written. When
  85026. ** P2 is zero, the vacuum overwrites the original database.
  85027. */
  85028. case OP_Vacuum: {
  85029. assert( p->readOnly==0 );
  85030. rc = sqlite3RunVacuum(&p->zErrMsg, db, pOp->p1,
  85031. pOp->p2 ? &aMem[pOp->p2] : 0);
  85032. if( rc ) goto abort_due_to_error;
  85033. break;
  85034. }
  85035. #endif
  85036. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  85037. /* Opcode: IncrVacuum P1 P2 * * *
  85038. **
  85039. ** Perform a single step of the incremental vacuum procedure on
  85040. ** the P1 database. If the vacuum has finished, jump to instruction
  85041. ** P2. Otherwise, fall through to the next instruction.
  85042. */
  85043. case OP_IncrVacuum: { /* jump */
  85044. Btree *pBt;
  85045. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  85046. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  85047. assert( p->readOnly==0 );
  85048. pBt = db->aDb[pOp->p1].pBt;
  85049. rc = sqlite3BtreeIncrVacuum(pBt);
  85050. VdbeBranchTaken(rc==SQLITE_DONE,2);
  85051. if( rc ){
  85052. if( rc!=SQLITE_DONE ) goto abort_due_to_error;
  85053. rc = SQLITE_OK;
  85054. goto jump_to_p2;
  85055. }
  85056. break;
  85057. }
  85058. #endif
  85059. /* Opcode: Expire P1 P2 * * *
  85060. **
  85061. ** Cause precompiled statements to expire. When an expired statement
  85062. ** is executed using sqlite3_step() it will either automatically
  85063. ** reprepare itself (if it was originally created using sqlite3_prepare_v2())
  85064. ** or it will fail with SQLITE_SCHEMA.
  85065. **
  85066. ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
  85067. ** then only the currently executing statement is expired.
  85068. **
  85069. ** If P2 is 0, then SQL statements are expired immediately. If P2 is 1,
  85070. ** then running SQL statements are allowed to continue to run to completion.
  85071. ** The P2==1 case occurs when a CREATE INDEX or similar schema change happens
  85072. ** that might help the statement run faster but which does not affect the
  85073. ** correctness of operation.
  85074. */
  85075. case OP_Expire: {
  85076. assert( pOp->p2==0 || pOp->p2==1 );
  85077. if( !pOp->p1 ){
  85078. sqlite3ExpirePreparedStatements(db, pOp->p2);
  85079. }else{
  85080. p->expired = pOp->p2+1;
  85081. }
  85082. break;
  85083. }
  85084. #ifndef SQLITE_OMIT_SHARED_CACHE
  85085. /* Opcode: TableLock P1 P2 P3 P4 *
  85086. ** Synopsis: iDb=P1 root=P2 write=P3
  85087. **
  85088. ** Obtain a lock on a particular table. This instruction is only used when
  85089. ** the shared-cache feature is enabled.
  85090. **
  85091. ** P1 is the index of the database in sqlite3.aDb[] of the database
  85092. ** on which the lock is acquired. A readlock is obtained if P3==0 or
  85093. ** a write lock if P3==1.
  85094. **
  85095. ** P2 contains the root-page of the table to lock.
  85096. **
  85097. ** P4 contains a pointer to the name of the table being locked. This is only
  85098. ** used to generate an error message if the lock cannot be obtained.
  85099. */
  85100. case OP_TableLock: {
  85101. u8 isWriteLock = (u8)pOp->p3;
  85102. if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommit) ){
  85103. int p1 = pOp->p1;
  85104. assert( p1>=0 && p1<db->nDb );
  85105. assert( DbMaskTest(p->btreeMask, p1) );
  85106. assert( isWriteLock==0 || isWriteLock==1 );
  85107. rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
  85108. if( rc ){
  85109. if( (rc&0xFF)==SQLITE_LOCKED ){
  85110. const char *z = pOp->p4.z;
  85111. sqlite3VdbeError(p, "database table is locked: %s", z);
  85112. }
  85113. goto abort_due_to_error;
  85114. }
  85115. }
  85116. break;
  85117. }
  85118. #endif /* SQLITE_OMIT_SHARED_CACHE */
  85119. #ifndef SQLITE_OMIT_VIRTUALTABLE
  85120. /* Opcode: VBegin * * * P4 *
  85121. **
  85122. ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
  85123. ** xBegin method for that table.
  85124. **
  85125. ** Also, whether or not P4 is set, check that this is not being called from
  85126. ** within a callback to a virtual table xSync() method. If it is, the error
  85127. ** code will be set to SQLITE_LOCKED.
  85128. */
  85129. case OP_VBegin: {
  85130. VTable *pVTab;
  85131. pVTab = pOp->p4.pVtab;
  85132. rc = sqlite3VtabBegin(db, pVTab);
  85133. if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab);
  85134. if( rc ) goto abort_due_to_error;
  85135. break;
  85136. }
  85137. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  85138. #ifndef SQLITE_OMIT_VIRTUALTABLE
  85139. /* Opcode: VCreate P1 P2 * * *
  85140. **
  85141. ** P2 is a register that holds the name of a virtual table in database
  85142. ** P1. Call the xCreate method for that table.
  85143. */
  85144. case OP_VCreate: {
  85145. Mem sMem; /* For storing the record being decoded */
  85146. const char *zTab; /* Name of the virtual table */
  85147. memset(&sMem, 0, sizeof(sMem));
  85148. sMem.db = db;
  85149. /* Because P2 is always a static string, it is impossible for the
  85150. ** sqlite3VdbeMemCopy() to fail */
  85151. assert( (aMem[pOp->p2].flags & MEM_Str)!=0 );
  85152. assert( (aMem[pOp->p2].flags & MEM_Static)!=0 );
  85153. rc = sqlite3VdbeMemCopy(&sMem, &aMem[pOp->p2]);
  85154. assert( rc==SQLITE_OK );
  85155. zTab = (const char*)sqlite3_value_text(&sMem);
  85156. assert( zTab || db->mallocFailed );
  85157. if( zTab ){
  85158. rc = sqlite3VtabCallCreate(db, pOp->p1, zTab, &p->zErrMsg);
  85159. }
  85160. sqlite3VdbeMemRelease(&sMem);
  85161. if( rc ) goto abort_due_to_error;
  85162. break;
  85163. }
  85164. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  85165. #ifndef SQLITE_OMIT_VIRTUALTABLE
  85166. /* Opcode: VDestroy P1 * * P4 *
  85167. **
  85168. ** P4 is the name of a virtual table in database P1. Call the xDestroy method
  85169. ** of that table.
  85170. */
  85171. case OP_VDestroy: {
  85172. db->nVDestroy++;
  85173. rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
  85174. db->nVDestroy--;
  85175. assert( p->errorAction==OE_Abort && p->usesStmtJournal );
  85176. if( rc ) goto abort_due_to_error;
  85177. break;
  85178. }
  85179. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  85180. #ifndef SQLITE_OMIT_VIRTUALTABLE
  85181. /* Opcode: VOpen P1 * * P4 *
  85182. **
  85183. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  85184. ** P1 is a cursor number. This opcode opens a cursor to the virtual
  85185. ** table and stores that cursor in P1.
  85186. */
  85187. case OP_VOpen: {
  85188. VdbeCursor *pCur;
  85189. sqlite3_vtab_cursor *pVCur;
  85190. sqlite3_vtab *pVtab;
  85191. const sqlite3_module *pModule;
  85192. assert( p->bIsReader );
  85193. pCur = 0;
  85194. pVCur = 0;
  85195. pVtab = pOp->p4.pVtab->pVtab;
  85196. if( pVtab==0 || NEVER(pVtab->pModule==0) ){
  85197. rc = SQLITE_LOCKED;
  85198. goto abort_due_to_error;
  85199. }
  85200. pModule = pVtab->pModule;
  85201. rc = pModule->xOpen(pVtab, &pVCur);
  85202. sqlite3VtabImportErrmsg(p, pVtab);
  85203. if( rc ) goto abort_due_to_error;
  85204. /* Initialize sqlite3_vtab_cursor base class */
  85205. pVCur->pVtab = pVtab;
  85206. /* Initialize vdbe cursor object */
  85207. pCur = allocateCursor(p, pOp->p1, 0, -1, CURTYPE_VTAB);
  85208. if( pCur ){
  85209. pCur->uc.pVCur = pVCur;
  85210. pVtab->nRef++;
  85211. }else{
  85212. assert( db->mallocFailed );
  85213. pModule->xClose(pVCur);
  85214. goto no_mem;
  85215. }
  85216. break;
  85217. }
  85218. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  85219. #ifndef SQLITE_OMIT_VIRTUALTABLE
  85220. /* Opcode: VFilter P1 P2 P3 P4 *
  85221. ** Synopsis: iplan=r[P3] zplan='P4'
  85222. **
  85223. ** P1 is a cursor opened using VOpen. P2 is an address to jump to if
  85224. ** the filtered result set is empty.
  85225. **
  85226. ** P4 is either NULL or a string that was generated by the xBestIndex
  85227. ** method of the module. The interpretation of the P4 string is left
  85228. ** to the module implementation.
  85229. **
  85230. ** This opcode invokes the xFilter method on the virtual table specified
  85231. ** by P1. The integer query plan parameter to xFilter is stored in register
  85232. ** P3. Register P3+1 stores the argc parameter to be passed to the
  85233. ** xFilter method. Registers P3+2..P3+1+argc are the argc
  85234. ** additional parameters which are passed to
  85235. ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
  85236. **
  85237. ** A jump is made to P2 if the result set after filtering would be empty.
  85238. */
  85239. case OP_VFilter: { /* jump */
  85240. int nArg;
  85241. int iQuery;
  85242. const sqlite3_module *pModule;
  85243. Mem *pQuery;
  85244. Mem *pArgc;
  85245. sqlite3_vtab_cursor *pVCur;
  85246. sqlite3_vtab *pVtab;
  85247. VdbeCursor *pCur;
  85248. int res;
  85249. int i;
  85250. Mem **apArg;
  85251. pQuery = &aMem[pOp->p3];
  85252. pArgc = &pQuery[1];
  85253. pCur = p->apCsr[pOp->p1];
  85254. assert( memIsValid(pQuery) );
  85255. REGISTER_TRACE(pOp->p3, pQuery);
  85256. assert( pCur->eCurType==CURTYPE_VTAB );
  85257. pVCur = pCur->uc.pVCur;
  85258. pVtab = pVCur->pVtab;
  85259. pModule = pVtab->pModule;
  85260. /* Grab the index number and argc parameters */
  85261. assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
  85262. nArg = (int)pArgc->u.i;
  85263. iQuery = (int)pQuery->u.i;
  85264. /* Invoke the xFilter method */
  85265. res = 0;
  85266. apArg = p->apArg;
  85267. for(i = 0; i<nArg; i++){
  85268. apArg[i] = &pArgc[i+1];
  85269. }
  85270. rc = pModule->xFilter(pVCur, iQuery, pOp->p4.z, nArg, apArg);
  85271. sqlite3VtabImportErrmsg(p, pVtab);
  85272. if( rc ) goto abort_due_to_error;
  85273. res = pModule->xEof(pVCur);
  85274. pCur->nullRow = 0;
  85275. VdbeBranchTaken(res!=0,2);
  85276. if( res ) goto jump_to_p2;
  85277. break;
  85278. }
  85279. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  85280. #ifndef SQLITE_OMIT_VIRTUALTABLE
  85281. /* Opcode: VColumn P1 P2 P3 * P5
  85282. ** Synopsis: r[P3]=vcolumn(P2)
  85283. **
  85284. ** Store in register P3 the value of the P2-th column of
  85285. ** the current row of the virtual-table of cursor P1.
  85286. **
  85287. ** If the VColumn opcode is being used to fetch the value of
  85288. ** an unchanging column during an UPDATE operation, then the P5
  85289. ** value is OPFLAG_NOCHNG. This will cause the sqlite3_vtab_nochange()
  85290. ** function to return true inside the xColumn method of the virtual
  85291. ** table implementation. The P5 column might also contain other
  85292. ** bits (OPFLAG_LENGTHARG or OPFLAG_TYPEOFARG) but those bits are
  85293. ** unused by OP_VColumn.
  85294. */
  85295. case OP_VColumn: {
  85296. sqlite3_vtab *pVtab;
  85297. const sqlite3_module *pModule;
  85298. Mem *pDest;
  85299. sqlite3_context sContext;
  85300. VdbeCursor *pCur = p->apCsr[pOp->p1];
  85301. assert( pCur->eCurType==CURTYPE_VTAB );
  85302. assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
  85303. pDest = &aMem[pOp->p3];
  85304. memAboutToChange(p, pDest);
  85305. if( pCur->nullRow ){
  85306. sqlite3VdbeMemSetNull(pDest);
  85307. break;
  85308. }
  85309. pVtab = pCur->uc.pVCur->pVtab;
  85310. pModule = pVtab->pModule;
  85311. assert( pModule->xColumn );
  85312. memset(&sContext, 0, sizeof(sContext));
  85313. sContext.pOut = pDest;
  85314. testcase( (pOp->p5 & OPFLAG_NOCHNG)==0 && pOp->p5!=0 );
  85315. if( pOp->p5 & OPFLAG_NOCHNG ){
  85316. sqlite3VdbeMemSetNull(pDest);
  85317. pDest->flags = MEM_Null|MEM_Zero;
  85318. pDest->u.nZero = 0;
  85319. }else{
  85320. MemSetTypeFlag(pDest, MEM_Null);
  85321. }
  85322. rc = pModule->xColumn(pCur->uc.pVCur, &sContext, pOp->p2);
  85323. sqlite3VtabImportErrmsg(p, pVtab);
  85324. if( sContext.isError>0 ){
  85325. sqlite3VdbeError(p, "%s", sqlite3_value_text(pDest));
  85326. rc = sContext.isError;
  85327. }
  85328. sqlite3VdbeChangeEncoding(pDest, encoding);
  85329. REGISTER_TRACE(pOp->p3, pDest);
  85330. UPDATE_MAX_BLOBSIZE(pDest);
  85331. if( sqlite3VdbeMemTooBig(pDest) ){
  85332. goto too_big;
  85333. }
  85334. if( rc ) goto abort_due_to_error;
  85335. break;
  85336. }
  85337. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  85338. #ifndef SQLITE_OMIT_VIRTUALTABLE
  85339. /* Opcode: VNext P1 P2 * * *
  85340. **
  85341. ** Advance virtual table P1 to the next row in its result set and
  85342. ** jump to instruction P2. Or, if the virtual table has reached
  85343. ** the end of its result set, then fall through to the next instruction.
  85344. */
  85345. case OP_VNext: { /* jump */
  85346. sqlite3_vtab *pVtab;
  85347. const sqlite3_module *pModule;
  85348. int res;
  85349. VdbeCursor *pCur;
  85350. res = 0;
  85351. pCur = p->apCsr[pOp->p1];
  85352. assert( pCur->eCurType==CURTYPE_VTAB );
  85353. if( pCur->nullRow ){
  85354. break;
  85355. }
  85356. pVtab = pCur->uc.pVCur->pVtab;
  85357. pModule = pVtab->pModule;
  85358. assert( pModule->xNext );
  85359. /* Invoke the xNext() method of the module. There is no way for the
  85360. ** underlying implementation to return an error if one occurs during
  85361. ** xNext(). Instead, if an error occurs, true is returned (indicating that
  85362. ** data is available) and the error code returned when xColumn or
  85363. ** some other method is next invoked on the save virtual table cursor.
  85364. */
  85365. rc = pModule->xNext(pCur->uc.pVCur);
  85366. sqlite3VtabImportErrmsg(p, pVtab);
  85367. if( rc ) goto abort_due_to_error;
  85368. res = pModule->xEof(pCur->uc.pVCur);
  85369. VdbeBranchTaken(!res,2);
  85370. if( !res ){
  85371. /* If there is data, jump to P2 */
  85372. goto jump_to_p2_and_check_for_interrupt;
  85373. }
  85374. goto check_for_interrupt;
  85375. }
  85376. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  85377. #ifndef SQLITE_OMIT_VIRTUALTABLE
  85378. /* Opcode: VRename P1 * * P4 *
  85379. **
  85380. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  85381. ** This opcode invokes the corresponding xRename method. The value
  85382. ** in register P1 is passed as the zName argument to the xRename method.
  85383. */
  85384. case OP_VRename: {
  85385. sqlite3_vtab *pVtab;
  85386. Mem *pName;
  85387. int isLegacy;
  85388. isLegacy = (db->flags & SQLITE_LegacyAlter);
  85389. db->flags |= SQLITE_LegacyAlter;
  85390. pVtab = pOp->p4.pVtab->pVtab;
  85391. pName = &aMem[pOp->p1];
  85392. assert( pVtab->pModule->xRename );
  85393. assert( memIsValid(pName) );
  85394. assert( p->readOnly==0 );
  85395. REGISTER_TRACE(pOp->p1, pName);
  85396. assert( pName->flags & MEM_Str );
  85397. testcase( pName->enc==SQLITE_UTF8 );
  85398. testcase( pName->enc==SQLITE_UTF16BE );
  85399. testcase( pName->enc==SQLITE_UTF16LE );
  85400. rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8);
  85401. if( rc ) goto abort_due_to_error;
  85402. rc = pVtab->pModule->xRename(pVtab, pName->z);
  85403. if( isLegacy==0 ) db->flags &= ~(u64)SQLITE_LegacyAlter;
  85404. sqlite3VtabImportErrmsg(p, pVtab);
  85405. p->expired = 0;
  85406. if( rc ) goto abort_due_to_error;
  85407. break;
  85408. }
  85409. #endif
  85410. #ifndef SQLITE_OMIT_VIRTUALTABLE
  85411. /* Opcode: VUpdate P1 P2 P3 P4 P5
  85412. ** Synopsis: data=r[P3@P2]
  85413. **
  85414. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  85415. ** This opcode invokes the corresponding xUpdate method. P2 values
  85416. ** are contiguous memory cells starting at P3 to pass to the xUpdate
  85417. ** invocation. The value in register (P3+P2-1) corresponds to the
  85418. ** p2th element of the argv array passed to xUpdate.
  85419. **
  85420. ** The xUpdate method will do a DELETE or an INSERT or both.
  85421. ** The argv[0] element (which corresponds to memory cell P3)
  85422. ** is the rowid of a row to delete. If argv[0] is NULL then no
  85423. ** deletion occurs. The argv[1] element is the rowid of the new
  85424. ** row. This can be NULL to have the virtual table select the new
  85425. ** rowid for itself. The subsequent elements in the array are
  85426. ** the values of columns in the new row.
  85427. **
  85428. ** If P2==1 then no insert is performed. argv[0] is the rowid of
  85429. ** a row to delete.
  85430. **
  85431. ** P1 is a boolean flag. If it is set to true and the xUpdate call
  85432. ** is successful, then the value returned by sqlite3_last_insert_rowid()
  85433. ** is set to the value of the rowid for the row just inserted.
  85434. **
  85435. ** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to
  85436. ** apply in the case of a constraint failure on an insert or update.
  85437. */
  85438. case OP_VUpdate: {
  85439. sqlite3_vtab *pVtab;
  85440. const sqlite3_module *pModule;
  85441. int nArg;
  85442. int i;
  85443. sqlite_int64 rowid;
  85444. Mem **apArg;
  85445. Mem *pX;
  85446. assert( pOp->p2==1 || pOp->p5==OE_Fail || pOp->p5==OE_Rollback
  85447. || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
  85448. );
  85449. assert( p->readOnly==0 );
  85450. if( db->mallocFailed ) goto no_mem;
  85451. sqlite3VdbeIncrWriteCounter(p, 0);
  85452. pVtab = pOp->p4.pVtab->pVtab;
  85453. if( pVtab==0 || NEVER(pVtab->pModule==0) ){
  85454. rc = SQLITE_LOCKED;
  85455. goto abort_due_to_error;
  85456. }
  85457. pModule = pVtab->pModule;
  85458. nArg = pOp->p2;
  85459. assert( pOp->p4type==P4_VTAB );
  85460. if( ALWAYS(pModule->xUpdate) ){
  85461. u8 vtabOnConflict = db->vtabOnConflict;
  85462. apArg = p->apArg;
  85463. pX = &aMem[pOp->p3];
  85464. for(i=0; i<nArg; i++){
  85465. assert( memIsValid(pX) );
  85466. memAboutToChange(p, pX);
  85467. apArg[i] = pX;
  85468. pX++;
  85469. }
  85470. db->vtabOnConflict = pOp->p5;
  85471. rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
  85472. db->vtabOnConflict = vtabOnConflict;
  85473. sqlite3VtabImportErrmsg(p, pVtab);
  85474. if( rc==SQLITE_OK && pOp->p1 ){
  85475. assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
  85476. db->lastRowid = rowid;
  85477. }
  85478. if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
  85479. if( pOp->p5==OE_Ignore ){
  85480. rc = SQLITE_OK;
  85481. }else{
  85482. p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
  85483. }
  85484. }else{
  85485. p->nChange++;
  85486. }
  85487. if( rc ) goto abort_due_to_error;
  85488. }
  85489. break;
  85490. }
  85491. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  85492. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  85493. /* Opcode: Pagecount P1 P2 * * *
  85494. **
  85495. ** Write the current number of pages in database P1 to memory cell P2.
  85496. */
  85497. case OP_Pagecount: { /* out2 */
  85498. pOut = out2Prerelease(p, pOp);
  85499. pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
  85500. break;
  85501. }
  85502. #endif
  85503. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  85504. /* Opcode: MaxPgcnt P1 P2 P3 * *
  85505. **
  85506. ** Try to set the maximum page count for database P1 to the value in P3.
  85507. ** Do not let the maximum page count fall below the current page count and
  85508. ** do not change the maximum page count value if P3==0.
  85509. **
  85510. ** Store the maximum page count after the change in register P2.
  85511. */
  85512. case OP_MaxPgcnt: { /* out2 */
  85513. unsigned int newMax;
  85514. Btree *pBt;
  85515. pOut = out2Prerelease(p, pOp);
  85516. pBt = db->aDb[pOp->p1].pBt;
  85517. newMax = 0;
  85518. if( pOp->p3 ){
  85519. newMax = sqlite3BtreeLastPage(pBt);
  85520. if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
  85521. }
  85522. pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
  85523. break;
  85524. }
  85525. #endif
  85526. /* Opcode: Function0 P1 P2 P3 P4 P5
  85527. ** Synopsis: r[P3]=func(r[P2@P5])
  85528. **
  85529. ** Invoke a user function (P4 is a pointer to a FuncDef object that
  85530. ** defines the function) with P5 arguments taken from register P2 and
  85531. ** successors. The result of the function is stored in register P3.
  85532. ** Register P3 must not be one of the function inputs.
  85533. **
  85534. ** P1 is a 32-bit bitmask indicating whether or not each argument to the
  85535. ** function was determined to be constant at compile time. If the first
  85536. ** argument was constant then bit 0 of P1 is set. This is used to determine
  85537. ** whether meta data associated with a user function argument using the
  85538. ** sqlite3_set_auxdata() API may be safely retained until the next
  85539. ** invocation of this opcode.
  85540. **
  85541. ** See also: Function, AggStep, AggFinal
  85542. */
  85543. /* Opcode: Function P1 P2 P3 P4 P5
  85544. ** Synopsis: r[P3]=func(r[P2@P5])
  85545. **
  85546. ** Invoke a user function (P4 is a pointer to an sqlite3_context object that
  85547. ** contains a pointer to the function to be run) with P5 arguments taken
  85548. ** from register P2 and successors. The result of the function is stored
  85549. ** in register P3. Register P3 must not be one of the function inputs.
  85550. **
  85551. ** P1 is a 32-bit bitmask indicating whether or not each argument to the
  85552. ** function was determined to be constant at compile time. If the first
  85553. ** argument was constant then bit 0 of P1 is set. This is used to determine
  85554. ** whether meta data associated with a user function argument using the
  85555. ** sqlite3_set_auxdata() API may be safely retained until the next
  85556. ** invocation of this opcode.
  85557. **
  85558. ** SQL functions are initially coded as OP_Function0 with P4 pointing
  85559. ** to a FuncDef object. But on first evaluation, the P4 operand is
  85560. ** automatically converted into an sqlite3_context object and the operation
  85561. ** changed to this OP_Function opcode. In this way, the initialization of
  85562. ** the sqlite3_context object occurs only once, rather than once for each
  85563. ** evaluation of the function.
  85564. **
  85565. ** See also: Function0, AggStep, AggFinal
  85566. */
  85567. case OP_PureFunc0: /* group */
  85568. case OP_Function0: { /* group */
  85569. int n;
  85570. sqlite3_context *pCtx;
  85571. assert( pOp->p4type==P4_FUNCDEF );
  85572. n = pOp->p5;
  85573. assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
  85574. assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
  85575. assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
  85576. pCtx = sqlite3DbMallocRawNN(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*));
  85577. if( pCtx==0 ) goto no_mem;
  85578. pCtx->pOut = 0;
  85579. pCtx->pFunc = pOp->p4.pFunc;
  85580. pCtx->iOp = (int)(pOp - aOp);
  85581. pCtx->pVdbe = p;
  85582. pCtx->isError = 0;
  85583. pCtx->argc = n;
  85584. pOp->p4type = P4_FUNCCTX;
  85585. pOp->p4.pCtx = pCtx;
  85586. assert( OP_PureFunc == OP_PureFunc0+2 );
  85587. assert( OP_Function == OP_Function0+2 );
  85588. pOp->opcode += 2;
  85589. /* Fall through into OP_Function */
  85590. }
  85591. case OP_PureFunc: /* group */
  85592. case OP_Function: { /* group */
  85593. int i;
  85594. sqlite3_context *pCtx;
  85595. assert( pOp->p4type==P4_FUNCCTX );
  85596. pCtx = pOp->p4.pCtx;
  85597. /* If this function is inside of a trigger, the register array in aMem[]
  85598. ** might change from one evaluation to the next. The next block of code
  85599. ** checks to see if the register array has changed, and if so it
  85600. ** reinitializes the relavant parts of the sqlite3_context object */
  85601. pOut = &aMem[pOp->p3];
  85602. if( pCtx->pOut != pOut ){
  85603. pCtx->pOut = pOut;
  85604. for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
  85605. }
  85606. memAboutToChange(p, pOut);
  85607. #ifdef SQLITE_DEBUG
  85608. for(i=0; i<pCtx->argc; i++){
  85609. assert( memIsValid(pCtx->argv[i]) );
  85610. REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
  85611. }
  85612. #endif
  85613. MemSetTypeFlag(pOut, MEM_Null);
  85614. assert( pCtx->isError==0 );
  85615. (*pCtx->pFunc->xSFunc)(pCtx, pCtx->argc, pCtx->argv);/* IMP: R-24505-23230 */
  85616. /* If the function returned an error, throw an exception */
  85617. if( pCtx->isError ){
  85618. if( pCtx->isError>0 ){
  85619. sqlite3VdbeError(p, "%s", sqlite3_value_text(pOut));
  85620. rc = pCtx->isError;
  85621. }
  85622. sqlite3VdbeDeleteAuxData(db, &p->pAuxData, pCtx->iOp, pOp->p1);
  85623. pCtx->isError = 0;
  85624. if( rc ) goto abort_due_to_error;
  85625. }
  85626. /* Copy the result of the function into register P3 */
  85627. if( pOut->flags & (MEM_Str|MEM_Blob) ){
  85628. sqlite3VdbeChangeEncoding(pOut, encoding);
  85629. if( sqlite3VdbeMemTooBig(pOut) ) goto too_big;
  85630. }
  85631. REGISTER_TRACE(pOp->p3, pOut);
  85632. UPDATE_MAX_BLOBSIZE(pOut);
  85633. break;
  85634. }
  85635. /* Opcode: Trace P1 P2 * P4 *
  85636. **
  85637. ** Write P4 on the statement trace output if statement tracing is
  85638. ** enabled.
  85639. **
  85640. ** Operand P1 must be 0x7fffffff and P2 must positive.
  85641. */
  85642. /* Opcode: Init P1 P2 P3 P4 *
  85643. ** Synopsis: Start at P2
  85644. **
  85645. ** Programs contain a single instance of this opcode as the very first
  85646. ** opcode.
  85647. **
  85648. ** If tracing is enabled (by the sqlite3_trace()) interface, then
  85649. ** the UTF-8 string contained in P4 is emitted on the trace callback.
  85650. ** Or if P4 is blank, use the string returned by sqlite3_sql().
  85651. **
  85652. ** If P2 is not zero, jump to instruction P2.
  85653. **
  85654. ** Increment the value of P1 so that OP_Once opcodes will jump the
  85655. ** first time they are evaluated for this run.
  85656. **
  85657. ** If P3 is not zero, then it is an address to jump to if an SQLITE_CORRUPT
  85658. ** error is encountered.
  85659. */
  85660. case OP_Trace:
  85661. case OP_Init: { /* jump */
  85662. int i;
  85663. #ifndef SQLITE_OMIT_TRACE
  85664. char *zTrace;
  85665. #endif
  85666. /* If the P4 argument is not NULL, then it must be an SQL comment string.
  85667. ** The "--" string is broken up to prevent false-positives with srcck1.c.
  85668. **
  85669. ** This assert() provides evidence for:
  85670. ** EVIDENCE-OF: R-50676-09860 The callback can compute the same text that
  85671. ** would have been returned by the legacy sqlite3_trace() interface by
  85672. ** using the X argument when X begins with "--" and invoking
  85673. ** sqlite3_expanded_sql(P) otherwise.
  85674. */
  85675. assert( pOp->p4.z==0 || strncmp(pOp->p4.z, "-" "- ", 3)==0 );
  85676. /* OP_Init is always instruction 0 */
  85677. assert( pOp==p->aOp || pOp->opcode==OP_Trace );
  85678. #ifndef SQLITE_OMIT_TRACE
  85679. if( (db->mTrace & (SQLITE_TRACE_STMT|SQLITE_TRACE_LEGACY))!=0
  85680. && !p->doingRerun
  85681. && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
  85682. ){
  85683. #ifndef SQLITE_OMIT_DEPRECATED
  85684. if( db->mTrace & SQLITE_TRACE_LEGACY ){
  85685. void (*x)(void*,const char*) = (void(*)(void*,const char*))db->xTrace;
  85686. char *z = sqlite3VdbeExpandSql(p, zTrace);
  85687. x(db->pTraceArg, z);
  85688. sqlite3_free(z);
  85689. }else
  85690. #endif
  85691. if( db->nVdbeExec>1 ){
  85692. char *z = sqlite3MPrintf(db, "-- %s", zTrace);
  85693. (void)db->xTrace(SQLITE_TRACE_STMT, db->pTraceArg, p, z);
  85694. sqlite3DbFree(db, z);
  85695. }else{
  85696. (void)db->xTrace(SQLITE_TRACE_STMT, db->pTraceArg, p, zTrace);
  85697. }
  85698. }
  85699. #ifdef SQLITE_USE_FCNTL_TRACE
  85700. zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
  85701. if( zTrace ){
  85702. int j;
  85703. for(j=0; j<db->nDb; j++){
  85704. if( DbMaskTest(p->btreeMask, j)==0 ) continue;
  85705. sqlite3_file_control(db, db->aDb[j].zDbSName, SQLITE_FCNTL_TRACE, zTrace);
  85706. }
  85707. }
  85708. #endif /* SQLITE_USE_FCNTL_TRACE */
  85709. #ifdef SQLITE_DEBUG
  85710. if( (db->flags & SQLITE_SqlTrace)!=0
  85711. && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
  85712. ){
  85713. sqlite3DebugPrintf("SQL-trace: %s\n", zTrace);
  85714. }
  85715. #endif /* SQLITE_DEBUG */
  85716. #endif /* SQLITE_OMIT_TRACE */
  85717. assert( pOp->p2>0 );
  85718. if( pOp->p1>=sqlite3GlobalConfig.iOnceResetThreshold ){
  85719. if( pOp->opcode==OP_Trace ) break;
  85720. for(i=1; i<p->nOp; i++){
  85721. if( p->aOp[i].opcode==OP_Once ) p->aOp[i].p1 = 0;
  85722. }
  85723. pOp->p1 = 0;
  85724. }
  85725. pOp->p1++;
  85726. p->aCounter[SQLITE_STMTSTATUS_RUN]++;
  85727. goto jump_to_p2;
  85728. }
  85729. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  85730. /* Opcode: CursorHint P1 * * P4 *
  85731. **
  85732. ** Provide a hint to cursor P1 that it only needs to return rows that
  85733. ** satisfy the Expr in P4. TK_REGISTER terms in the P4 expression refer
  85734. ** to values currently held in registers. TK_COLUMN terms in the P4
  85735. ** expression refer to columns in the b-tree to which cursor P1 is pointing.
  85736. */
  85737. case OP_CursorHint: {
  85738. VdbeCursor *pC;
  85739. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  85740. assert( pOp->p4type==P4_EXPR );
  85741. pC = p->apCsr[pOp->p1];
  85742. if( pC ){
  85743. assert( pC->eCurType==CURTYPE_BTREE );
  85744. sqlite3BtreeCursorHint(pC->uc.pCursor, BTREE_HINT_RANGE,
  85745. pOp->p4.pExpr, aMem);
  85746. }
  85747. break;
  85748. }
  85749. #endif /* SQLITE_ENABLE_CURSOR_HINTS */
  85750. #ifdef SQLITE_DEBUG
  85751. /* Opcode: Abortable * * * * *
  85752. **
  85753. ** Verify that an Abort can happen. Assert if an Abort at this point
  85754. ** might cause database corruption. This opcode only appears in debugging
  85755. ** builds.
  85756. **
  85757. ** An Abort is safe if either there have been no writes, or if there is
  85758. ** an active statement journal.
  85759. */
  85760. case OP_Abortable: {
  85761. sqlite3VdbeAssertAbortable(p);
  85762. break;
  85763. }
  85764. #endif
  85765. /* Opcode: Noop * * * * *
  85766. **
  85767. ** Do nothing. This instruction is often useful as a jump
  85768. ** destination.
  85769. */
  85770. /*
  85771. ** The magic Explain opcode are only inserted when explain==2 (which
  85772. ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
  85773. ** This opcode records information from the optimizer. It is the
  85774. ** the same as a no-op. This opcodesnever appears in a real VM program.
  85775. */
  85776. default: { /* This is really OP_Noop, OP_Explain */
  85777. assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
  85778. break;
  85779. }
  85780. /*****************************************************************************
  85781. ** The cases of the switch statement above this line should all be indented
  85782. ** by 6 spaces. But the left-most 6 spaces have been removed to improve the
  85783. ** readability. From this point on down, the normal indentation rules are
  85784. ** restored.
  85785. *****************************************************************************/
  85786. }
  85787. #ifdef VDBE_PROFILE
  85788. {
  85789. u64 endTime = sqlite3NProfileCnt ? sqlite3NProfileCnt : sqlite3Hwtime();
  85790. if( endTime>start ) pOrigOp->cycles += endTime - start;
  85791. pOrigOp->cnt++;
  85792. }
  85793. #endif
  85794. /* The following code adds nothing to the actual functionality
  85795. ** of the program. It is only here for testing and debugging.
  85796. ** On the other hand, it does burn CPU cycles every time through
  85797. ** the evaluator loop. So we can leave it out when NDEBUG is defined.
  85798. */
  85799. #ifndef NDEBUG
  85800. assert( pOp>=&aOp[-1] && pOp<&aOp[p->nOp-1] );
  85801. #ifdef SQLITE_DEBUG
  85802. if( db->flags & SQLITE_VdbeTrace ){
  85803. u8 opProperty = sqlite3OpcodeProperty[pOrigOp->opcode];
  85804. if( rc!=0 ) printf("rc=%d\n",rc);
  85805. if( opProperty & (OPFLG_OUT2) ){
  85806. registerTrace(pOrigOp->p2, &aMem[pOrigOp->p2]);
  85807. }
  85808. if( opProperty & OPFLG_OUT3 ){
  85809. registerTrace(pOrigOp->p3, &aMem[pOrigOp->p3]);
  85810. }
  85811. }
  85812. #endif /* SQLITE_DEBUG */
  85813. #endif /* NDEBUG */
  85814. } /* The end of the for(;;) loop the loops through opcodes */
  85815. /* If we reach this point, it means that execution is finished with
  85816. ** an error of some kind.
  85817. */
  85818. abort_due_to_error:
  85819. if( db->mallocFailed ) rc = SQLITE_NOMEM_BKPT;
  85820. assert( rc );
  85821. if( p->zErrMsg==0 && rc!=SQLITE_IOERR_NOMEM ){
  85822. sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
  85823. }
  85824. p->rc = rc;
  85825. sqlite3SystemError(db, rc);
  85826. testcase( sqlite3GlobalConfig.xLog!=0 );
  85827. sqlite3_log(rc, "statement aborts at %d: [%s] %s",
  85828. (int)(pOp - aOp), p->zSql, p->zErrMsg);
  85829. sqlite3VdbeHalt(p);
  85830. if( rc==SQLITE_IOERR_NOMEM ) sqlite3OomFault(db);
  85831. rc = SQLITE_ERROR;
  85832. if( resetSchemaOnFault>0 ){
  85833. sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
  85834. }
  85835. /* This is the only way out of this procedure. We have to
  85836. ** release the mutexes on btrees that were acquired at the
  85837. ** top. */
  85838. vdbe_return:
  85839. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  85840. while( nVmStep>=nProgressLimit && db->xProgress!=0 ){
  85841. nProgressLimit += db->nProgressOps;
  85842. if( db->xProgress(db->pProgressArg) ){
  85843. nProgressLimit = 0xffffffff;
  85844. rc = SQLITE_INTERRUPT;
  85845. goto abort_due_to_error;
  85846. }
  85847. }
  85848. #endif
  85849. p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
  85850. sqlite3VdbeLeave(p);
  85851. assert( rc!=SQLITE_OK || nExtraDelete==0
  85852. || sqlite3_strlike("DELETE%",p->zSql,0)!=0
  85853. );
  85854. return rc;
  85855. /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
  85856. ** is encountered.
  85857. */
  85858. too_big:
  85859. sqlite3VdbeError(p, "string or blob too big");
  85860. rc = SQLITE_TOOBIG;
  85861. goto abort_due_to_error;
  85862. /* Jump to here if a malloc() fails.
  85863. */
  85864. no_mem:
  85865. sqlite3OomFault(db);
  85866. sqlite3VdbeError(p, "out of memory");
  85867. rc = SQLITE_NOMEM_BKPT;
  85868. goto abort_due_to_error;
  85869. /* Jump to here if the sqlite3_interrupt() API sets the interrupt
  85870. ** flag.
  85871. */
  85872. abort_due_to_interrupt:
  85873. assert( db->u1.isInterrupted );
  85874. rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT;
  85875. p->rc = rc;
  85876. sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
  85877. goto abort_due_to_error;
  85878. }
  85879. /************** End of vdbe.c ************************************************/
  85880. /************** Begin file vdbeblob.c ****************************************/
  85881. /*
  85882. ** 2007 May 1
  85883. **
  85884. ** The author disclaims copyright to this source code. In place of
  85885. ** a legal notice, here is a blessing:
  85886. **
  85887. ** May you do good and not evil.
  85888. ** May you find forgiveness for yourself and forgive others.
  85889. ** May you share freely, never taking more than you give.
  85890. **
  85891. *************************************************************************
  85892. **
  85893. ** This file contains code used to implement incremental BLOB I/O.
  85894. */
  85895. /* #include "sqliteInt.h" */
  85896. /* #include "vdbeInt.h" */
  85897. #ifndef SQLITE_OMIT_INCRBLOB
  85898. /*
  85899. ** Valid sqlite3_blob* handles point to Incrblob structures.
  85900. */
  85901. typedef struct Incrblob Incrblob;
  85902. struct Incrblob {
  85903. int nByte; /* Size of open blob, in bytes */
  85904. int iOffset; /* Byte offset of blob in cursor data */
  85905. u16 iCol; /* Table column this handle is open on */
  85906. BtCursor *pCsr; /* Cursor pointing at blob row */
  85907. sqlite3_stmt *pStmt; /* Statement holding cursor open */
  85908. sqlite3 *db; /* The associated database */
  85909. char *zDb; /* Database name */
  85910. Table *pTab; /* Table object */
  85911. };
  85912. /*
  85913. ** This function is used by both blob_open() and blob_reopen(). It seeks
  85914. ** the b-tree cursor associated with blob handle p to point to row iRow.
  85915. ** If successful, SQLITE_OK is returned and subsequent calls to
  85916. ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
  85917. **
  85918. ** If an error occurs, or if the specified row does not exist or does not
  85919. ** contain a value of type TEXT or BLOB in the column nominated when the
  85920. ** blob handle was opened, then an error code is returned and *pzErr may
  85921. ** be set to point to a buffer containing an error message. It is the
  85922. ** responsibility of the caller to free the error message buffer using
  85923. ** sqlite3DbFree().
  85924. **
  85925. ** If an error does occur, then the b-tree cursor is closed. All subsequent
  85926. ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will
  85927. ** immediately return SQLITE_ABORT.
  85928. */
  85929. static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
  85930. int rc; /* Error code */
  85931. char *zErr = 0; /* Error message */
  85932. Vdbe *v = (Vdbe *)p->pStmt;
  85933. /* Set the value of register r[1] in the SQL statement to integer iRow.
  85934. ** This is done directly as a performance optimization
  85935. */
  85936. v->aMem[1].flags = MEM_Int;
  85937. v->aMem[1].u.i = iRow;
  85938. /* If the statement has been run before (and is paused at the OP_ResultRow)
  85939. ** then back it up to the point where it does the OP_NotExists. This could
  85940. ** have been down with an extra OP_Goto, but simply setting the program
  85941. ** counter is faster. */
  85942. if( v->pc>4 ){
  85943. v->pc = 4;
  85944. assert( v->aOp[v->pc].opcode==OP_NotExists );
  85945. rc = sqlite3VdbeExec(v);
  85946. }else{
  85947. rc = sqlite3_step(p->pStmt);
  85948. }
  85949. if( rc==SQLITE_ROW ){
  85950. VdbeCursor *pC = v->apCsr[0];
  85951. u32 type = pC->nHdrParsed>p->iCol ? pC->aType[p->iCol] : 0;
  85952. testcase( pC->nHdrParsed==p->iCol );
  85953. testcase( pC->nHdrParsed==p->iCol+1 );
  85954. if( type<12 ){
  85955. zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
  85956. type==0?"null": type==7?"real": "integer"
  85957. );
  85958. rc = SQLITE_ERROR;
  85959. sqlite3_finalize(p->pStmt);
  85960. p->pStmt = 0;
  85961. }else{
  85962. p->iOffset = pC->aType[p->iCol + pC->nField];
  85963. p->nByte = sqlite3VdbeSerialTypeLen(type);
  85964. p->pCsr = pC->uc.pCursor;
  85965. sqlite3BtreeIncrblobCursor(p->pCsr);
  85966. }
  85967. }
  85968. if( rc==SQLITE_ROW ){
  85969. rc = SQLITE_OK;
  85970. }else if( p->pStmt ){
  85971. rc = sqlite3_finalize(p->pStmt);
  85972. p->pStmt = 0;
  85973. if( rc==SQLITE_OK ){
  85974. zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
  85975. rc = SQLITE_ERROR;
  85976. }else{
  85977. zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
  85978. }
  85979. }
  85980. assert( rc!=SQLITE_OK || zErr==0 );
  85981. assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
  85982. *pzErr = zErr;
  85983. return rc;
  85984. }
  85985. /*
  85986. ** Open a blob handle.
  85987. */
  85988. SQLITE_API int sqlite3_blob_open(
  85989. sqlite3* db, /* The database connection */
  85990. const char *zDb, /* The attached database containing the blob */
  85991. const char *zTable, /* The table containing the blob */
  85992. const char *zColumn, /* The column containing the blob */
  85993. sqlite_int64 iRow, /* The row containing the glob */
  85994. int wrFlag, /* True -> read/write access, false -> read-only */
  85995. sqlite3_blob **ppBlob /* Handle for accessing the blob returned here */
  85996. ){
  85997. int nAttempt = 0;
  85998. int iCol; /* Index of zColumn in row-record */
  85999. int rc = SQLITE_OK;
  86000. char *zErr = 0;
  86001. Table *pTab;
  86002. Incrblob *pBlob = 0;
  86003. Parse sParse;
  86004. #ifdef SQLITE_ENABLE_API_ARMOR
  86005. if( ppBlob==0 ){
  86006. return SQLITE_MISUSE_BKPT;
  86007. }
  86008. #endif
  86009. *ppBlob = 0;
  86010. #ifdef SQLITE_ENABLE_API_ARMOR
  86011. if( !sqlite3SafetyCheckOk(db) || zTable==0 ){
  86012. return SQLITE_MISUSE_BKPT;
  86013. }
  86014. #endif
  86015. wrFlag = !!wrFlag; /* wrFlag = (wrFlag ? 1 : 0); */
  86016. sqlite3_mutex_enter(db->mutex);
  86017. pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
  86018. do {
  86019. memset(&sParse, 0, sizeof(Parse));
  86020. if( !pBlob ) goto blob_open_out;
  86021. sParse.db = db;
  86022. sqlite3DbFree(db, zErr);
  86023. zErr = 0;
  86024. sqlite3BtreeEnterAll(db);
  86025. pTab = sqlite3LocateTable(&sParse, 0, zTable, zDb);
  86026. if( pTab && IsVirtual(pTab) ){
  86027. pTab = 0;
  86028. sqlite3ErrorMsg(&sParse, "cannot open virtual table: %s", zTable);
  86029. }
  86030. if( pTab && !HasRowid(pTab) ){
  86031. pTab = 0;
  86032. sqlite3ErrorMsg(&sParse, "cannot open table without rowid: %s", zTable);
  86033. }
  86034. #ifndef SQLITE_OMIT_VIEW
  86035. if( pTab && pTab->pSelect ){
  86036. pTab = 0;
  86037. sqlite3ErrorMsg(&sParse, "cannot open view: %s", zTable);
  86038. }
  86039. #endif
  86040. if( !pTab ){
  86041. if( sParse.zErrMsg ){
  86042. sqlite3DbFree(db, zErr);
  86043. zErr = sParse.zErrMsg;
  86044. sParse.zErrMsg = 0;
  86045. }
  86046. rc = SQLITE_ERROR;
  86047. sqlite3BtreeLeaveAll(db);
  86048. goto blob_open_out;
  86049. }
  86050. pBlob->pTab = pTab;
  86051. pBlob->zDb = db->aDb[sqlite3SchemaToIndex(db, pTab->pSchema)].zDbSName;
  86052. /* Now search pTab for the exact column. */
  86053. for(iCol=0; iCol<pTab->nCol; iCol++) {
  86054. if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
  86055. break;
  86056. }
  86057. }
  86058. if( iCol==pTab->nCol ){
  86059. sqlite3DbFree(db, zErr);
  86060. zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
  86061. rc = SQLITE_ERROR;
  86062. sqlite3BtreeLeaveAll(db);
  86063. goto blob_open_out;
  86064. }
  86065. /* If the value is being opened for writing, check that the
  86066. ** column is not indexed, and that it is not part of a foreign key.
  86067. */
  86068. if( wrFlag ){
  86069. const char *zFault = 0;
  86070. Index *pIdx;
  86071. #ifndef SQLITE_OMIT_FOREIGN_KEY
  86072. if( db->flags&SQLITE_ForeignKeys ){
  86073. /* Check that the column is not part of an FK child key definition. It
  86074. ** is not necessary to check if it is part of a parent key, as parent
  86075. ** key columns must be indexed. The check below will pick up this
  86076. ** case. */
  86077. FKey *pFKey;
  86078. for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
  86079. int j;
  86080. for(j=0; j<pFKey->nCol; j++){
  86081. if( pFKey->aCol[j].iFrom==iCol ){
  86082. zFault = "foreign key";
  86083. }
  86084. }
  86085. }
  86086. }
  86087. #endif
  86088. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  86089. int j;
  86090. for(j=0; j<pIdx->nKeyCol; j++){
  86091. /* FIXME: Be smarter about indexes that use expressions */
  86092. if( pIdx->aiColumn[j]==iCol || pIdx->aiColumn[j]==XN_EXPR ){
  86093. zFault = "indexed";
  86094. }
  86095. }
  86096. }
  86097. if( zFault ){
  86098. sqlite3DbFree(db, zErr);
  86099. zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
  86100. rc = SQLITE_ERROR;
  86101. sqlite3BtreeLeaveAll(db);
  86102. goto blob_open_out;
  86103. }
  86104. }
  86105. pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(&sParse);
  86106. assert( pBlob->pStmt || db->mallocFailed );
  86107. if( pBlob->pStmt ){
  86108. /* This VDBE program seeks a btree cursor to the identified
  86109. ** db/table/row entry. The reason for using a vdbe program instead
  86110. ** of writing code to use the b-tree layer directly is that the
  86111. ** vdbe program will take advantage of the various transaction,
  86112. ** locking and error handling infrastructure built into the vdbe.
  86113. **
  86114. ** After seeking the cursor, the vdbe executes an OP_ResultRow.
  86115. ** Code external to the Vdbe then "borrows" the b-tree cursor and
  86116. ** uses it to implement the blob_read(), blob_write() and
  86117. ** blob_bytes() functions.
  86118. **
  86119. ** The sqlite3_blob_close() function finalizes the vdbe program,
  86120. ** which closes the b-tree cursor and (possibly) commits the
  86121. ** transaction.
  86122. */
  86123. static const int iLn = VDBE_OFFSET_LINENO(2);
  86124. static const VdbeOpList openBlob[] = {
  86125. {OP_TableLock, 0, 0, 0}, /* 0: Acquire a read or write lock */
  86126. {OP_OpenRead, 0, 0, 0}, /* 1: Open a cursor */
  86127. /* blobSeekToRow() will initialize r[1] to the desired rowid */
  86128. {OP_NotExists, 0, 5, 1}, /* 2: Seek the cursor to rowid=r[1] */
  86129. {OP_Column, 0, 0, 1}, /* 3 */
  86130. {OP_ResultRow, 1, 0, 0}, /* 4 */
  86131. {OP_Halt, 0, 0, 0}, /* 5 */
  86132. };
  86133. Vdbe *v = (Vdbe *)pBlob->pStmt;
  86134. int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  86135. VdbeOp *aOp;
  86136. sqlite3VdbeAddOp4Int(v, OP_Transaction, iDb, wrFlag,
  86137. pTab->pSchema->schema_cookie,
  86138. pTab->pSchema->iGeneration);
  86139. sqlite3VdbeChangeP5(v, 1);
  86140. assert( sqlite3VdbeCurrentAddr(v)==2 || db->mallocFailed );
  86141. aOp = sqlite3VdbeAddOpList(v, ArraySize(openBlob), openBlob, iLn);
  86142. /* Make sure a mutex is held on the table to be accessed */
  86143. sqlite3VdbeUsesBtree(v, iDb);
  86144. if( db->mallocFailed==0 ){
  86145. assert( aOp!=0 );
  86146. /* Configure the OP_TableLock instruction */
  86147. #ifdef SQLITE_OMIT_SHARED_CACHE
  86148. aOp[0].opcode = OP_Noop;
  86149. #else
  86150. aOp[0].p1 = iDb;
  86151. aOp[0].p2 = pTab->tnum;
  86152. aOp[0].p3 = wrFlag;
  86153. sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
  86154. }
  86155. if( db->mallocFailed==0 ){
  86156. #endif
  86157. /* Remove either the OP_OpenWrite or OpenRead. Set the P2
  86158. ** parameter of the other to pTab->tnum. */
  86159. if( wrFlag ) aOp[1].opcode = OP_OpenWrite;
  86160. aOp[1].p2 = pTab->tnum;
  86161. aOp[1].p3 = iDb;
  86162. /* Configure the number of columns. Configure the cursor to
  86163. ** think that the table has one more column than it really
  86164. ** does. An OP_Column to retrieve this imaginary column will
  86165. ** always return an SQL NULL. This is useful because it means
  86166. ** we can invoke OP_Column to fill in the vdbe cursors type
  86167. ** and offset cache without causing any IO.
  86168. */
  86169. aOp[1].p4type = P4_INT32;
  86170. aOp[1].p4.i = pTab->nCol+1;
  86171. aOp[3].p2 = pTab->nCol;
  86172. sParse.nVar = 0;
  86173. sParse.nMem = 1;
  86174. sParse.nTab = 1;
  86175. sqlite3VdbeMakeReady(v, &sParse);
  86176. }
  86177. }
  86178. pBlob->iCol = iCol;
  86179. pBlob->db = db;
  86180. sqlite3BtreeLeaveAll(db);
  86181. if( db->mallocFailed ){
  86182. goto blob_open_out;
  86183. }
  86184. rc = blobSeekToRow(pBlob, iRow, &zErr);
  86185. } while( (++nAttempt)<SQLITE_MAX_SCHEMA_RETRY && rc==SQLITE_SCHEMA );
  86186. blob_open_out:
  86187. if( rc==SQLITE_OK && db->mallocFailed==0 ){
  86188. *ppBlob = (sqlite3_blob *)pBlob;
  86189. }else{
  86190. if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
  86191. sqlite3DbFree(db, pBlob);
  86192. }
  86193. sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
  86194. sqlite3DbFree(db, zErr);
  86195. sqlite3ParserReset(&sParse);
  86196. rc = sqlite3ApiExit(db, rc);
  86197. sqlite3_mutex_leave(db->mutex);
  86198. return rc;
  86199. }
  86200. /*
  86201. ** Close a blob handle that was previously created using
  86202. ** sqlite3_blob_open().
  86203. */
  86204. SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
  86205. Incrblob *p = (Incrblob *)pBlob;
  86206. int rc;
  86207. sqlite3 *db;
  86208. if( p ){
  86209. db = p->db;
  86210. sqlite3_mutex_enter(db->mutex);
  86211. rc = sqlite3_finalize(p->pStmt);
  86212. sqlite3DbFree(db, p);
  86213. sqlite3_mutex_leave(db->mutex);
  86214. }else{
  86215. rc = SQLITE_OK;
  86216. }
  86217. return rc;
  86218. }
  86219. /*
  86220. ** Perform a read or write operation on a blob
  86221. */
  86222. static int blobReadWrite(
  86223. sqlite3_blob *pBlob,
  86224. void *z,
  86225. int n,
  86226. int iOffset,
  86227. int (*xCall)(BtCursor*, u32, u32, void*)
  86228. ){
  86229. int rc;
  86230. Incrblob *p = (Incrblob *)pBlob;
  86231. Vdbe *v;
  86232. sqlite3 *db;
  86233. if( p==0 ) return SQLITE_MISUSE_BKPT;
  86234. db = p->db;
  86235. sqlite3_mutex_enter(db->mutex);
  86236. v = (Vdbe*)p->pStmt;
  86237. if( n<0 || iOffset<0 || ((sqlite3_int64)iOffset+n)>p->nByte ){
  86238. /* Request is out of range. Return a transient error. */
  86239. rc = SQLITE_ERROR;
  86240. }else if( v==0 ){
  86241. /* If there is no statement handle, then the blob-handle has
  86242. ** already been invalidated. Return SQLITE_ABORT in this case.
  86243. */
  86244. rc = SQLITE_ABORT;
  86245. }else{
  86246. /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
  86247. ** returned, clean-up the statement handle.
  86248. */
  86249. assert( db == v->db );
  86250. sqlite3BtreeEnterCursor(p->pCsr);
  86251. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  86252. if( xCall==sqlite3BtreePutData && db->xPreUpdateCallback ){
  86253. /* If a pre-update hook is registered and this is a write cursor,
  86254. ** invoke it here.
  86255. **
  86256. ** TODO: The preupdate-hook is passed SQLITE_DELETE, even though this
  86257. ** operation should really be an SQLITE_UPDATE. This is probably
  86258. ** incorrect, but is convenient because at this point the new.* values
  86259. ** are not easily obtainable. And for the sessions module, an
  86260. ** SQLITE_UPDATE where the PK columns do not change is handled in the
  86261. ** same way as an SQLITE_DELETE (the SQLITE_DELETE code is actually
  86262. ** slightly more efficient). Since you cannot write to a PK column
  86263. ** using the incremental-blob API, this works. For the sessions module
  86264. ** anyhow.
  86265. */
  86266. sqlite3_int64 iKey;
  86267. iKey = sqlite3BtreeIntegerKey(p->pCsr);
  86268. sqlite3VdbePreUpdateHook(
  86269. v, v->apCsr[0], SQLITE_DELETE, p->zDb, p->pTab, iKey, -1
  86270. );
  86271. }
  86272. #endif
  86273. rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
  86274. sqlite3BtreeLeaveCursor(p->pCsr);
  86275. if( rc==SQLITE_ABORT ){
  86276. sqlite3VdbeFinalize(v);
  86277. p->pStmt = 0;
  86278. }else{
  86279. v->rc = rc;
  86280. }
  86281. }
  86282. sqlite3Error(db, rc);
  86283. rc = sqlite3ApiExit(db, rc);
  86284. sqlite3_mutex_leave(db->mutex);
  86285. return rc;
  86286. }
  86287. /*
  86288. ** Read data from a blob handle.
  86289. */
  86290. SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
  86291. return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreePayloadChecked);
  86292. }
  86293. /*
  86294. ** Write data to a blob handle.
  86295. */
  86296. SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
  86297. return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
  86298. }
  86299. /*
  86300. ** Query a blob handle for the size of the data.
  86301. **
  86302. ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
  86303. ** so no mutex is required for access.
  86304. */
  86305. SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
  86306. Incrblob *p = (Incrblob *)pBlob;
  86307. return (p && p->pStmt) ? p->nByte : 0;
  86308. }
  86309. /*
  86310. ** Move an existing blob handle to point to a different row of the same
  86311. ** database table.
  86312. **
  86313. ** If an error occurs, or if the specified row does not exist or does not
  86314. ** contain a blob or text value, then an error code is returned and the
  86315. ** database handle error code and message set. If this happens, then all
  86316. ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
  86317. ** immediately return SQLITE_ABORT.
  86318. */
  86319. SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
  86320. int rc;
  86321. Incrblob *p = (Incrblob *)pBlob;
  86322. sqlite3 *db;
  86323. if( p==0 ) return SQLITE_MISUSE_BKPT;
  86324. db = p->db;
  86325. sqlite3_mutex_enter(db->mutex);
  86326. if( p->pStmt==0 ){
  86327. /* If there is no statement handle, then the blob-handle has
  86328. ** already been invalidated. Return SQLITE_ABORT in this case.
  86329. */
  86330. rc = SQLITE_ABORT;
  86331. }else{
  86332. char *zErr;
  86333. rc = blobSeekToRow(p, iRow, &zErr);
  86334. if( rc!=SQLITE_OK ){
  86335. sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
  86336. sqlite3DbFree(db, zErr);
  86337. }
  86338. assert( rc!=SQLITE_SCHEMA );
  86339. }
  86340. rc = sqlite3ApiExit(db, rc);
  86341. assert( rc==SQLITE_OK || p->pStmt==0 );
  86342. sqlite3_mutex_leave(db->mutex);
  86343. return rc;
  86344. }
  86345. #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
  86346. /************** End of vdbeblob.c ********************************************/
  86347. /************** Begin file vdbesort.c ****************************************/
  86348. /*
  86349. ** 2011-07-09
  86350. **
  86351. ** The author disclaims copyright to this source code. In place of
  86352. ** a legal notice, here is a blessing:
  86353. **
  86354. ** May you do good and not evil.
  86355. ** May you find forgiveness for yourself and forgive others.
  86356. ** May you share freely, never taking more than you give.
  86357. **
  86358. *************************************************************************
  86359. ** This file contains code for the VdbeSorter object, used in concert with
  86360. ** a VdbeCursor to sort large numbers of keys for CREATE INDEX statements
  86361. ** or by SELECT statements with ORDER BY clauses that cannot be satisfied
  86362. ** using indexes and without LIMIT clauses.
  86363. **
  86364. ** The VdbeSorter object implements a multi-threaded external merge sort
  86365. ** algorithm that is efficient even if the number of elements being sorted
  86366. ** exceeds the available memory.
  86367. **
  86368. ** Here is the (internal, non-API) interface between this module and the
  86369. ** rest of the SQLite system:
  86370. **
  86371. ** sqlite3VdbeSorterInit() Create a new VdbeSorter object.
  86372. **
  86373. ** sqlite3VdbeSorterWrite() Add a single new row to the VdbeSorter
  86374. ** object. The row is a binary blob in the
  86375. ** OP_MakeRecord format that contains both
  86376. ** the ORDER BY key columns and result columns
  86377. ** in the case of a SELECT w/ ORDER BY, or
  86378. ** the complete record for an index entry
  86379. ** in the case of a CREATE INDEX.
  86380. **
  86381. ** sqlite3VdbeSorterRewind() Sort all content previously added.
  86382. ** Position the read cursor on the
  86383. ** first sorted element.
  86384. **
  86385. ** sqlite3VdbeSorterNext() Advance the read cursor to the next sorted
  86386. ** element.
  86387. **
  86388. ** sqlite3VdbeSorterRowkey() Return the complete binary blob for the
  86389. ** row currently under the read cursor.
  86390. **
  86391. ** sqlite3VdbeSorterCompare() Compare the binary blob for the row
  86392. ** currently under the read cursor against
  86393. ** another binary blob X and report if
  86394. ** X is strictly less than the read cursor.
  86395. ** Used to enforce uniqueness in a
  86396. ** CREATE UNIQUE INDEX statement.
  86397. **
  86398. ** sqlite3VdbeSorterClose() Close the VdbeSorter object and reclaim
  86399. ** all resources.
  86400. **
  86401. ** sqlite3VdbeSorterReset() Refurbish the VdbeSorter for reuse. This
  86402. ** is like Close() followed by Init() only
  86403. ** much faster.
  86404. **
  86405. ** The interfaces above must be called in a particular order. Write() can
  86406. ** only occur in between Init()/Reset() and Rewind(). Next(), Rowkey(), and
  86407. ** Compare() can only occur in between Rewind() and Close()/Reset(). i.e.
  86408. **
  86409. ** Init()
  86410. ** for each record: Write()
  86411. ** Rewind()
  86412. ** Rowkey()/Compare()
  86413. ** Next()
  86414. ** Close()
  86415. **
  86416. ** Algorithm:
  86417. **
  86418. ** Records passed to the sorter via calls to Write() are initially held
  86419. ** unsorted in main memory. Assuming the amount of memory used never exceeds
  86420. ** a threshold, when Rewind() is called the set of records is sorted using
  86421. ** an in-memory merge sort. In this case, no temporary files are required
  86422. ** and subsequent calls to Rowkey(), Next() and Compare() read records
  86423. ** directly from main memory.
  86424. **
  86425. ** If the amount of space used to store records in main memory exceeds the
  86426. ** threshold, then the set of records currently in memory are sorted and
  86427. ** written to a temporary file in "Packed Memory Array" (PMA) format.
  86428. ** A PMA created at this point is known as a "level-0 PMA". Higher levels
  86429. ** of PMAs may be created by merging existing PMAs together - for example
  86430. ** merging two or more level-0 PMAs together creates a level-1 PMA.
  86431. **
  86432. ** The threshold for the amount of main memory to use before flushing
  86433. ** records to a PMA is roughly the same as the limit configured for the
  86434. ** page-cache of the main database. Specifically, the threshold is set to
  86435. ** the value returned by "PRAGMA main.page_size" multipled by
  86436. ** that returned by "PRAGMA main.cache_size", in bytes.
  86437. **
  86438. ** If the sorter is running in single-threaded mode, then all PMAs generated
  86439. ** are appended to a single temporary file. Or, if the sorter is running in
  86440. ** multi-threaded mode then up to (N+1) temporary files may be opened, where
  86441. ** N is the configured number of worker threads. In this case, instead of
  86442. ** sorting the records and writing the PMA to a temporary file itself, the
  86443. ** calling thread usually launches a worker thread to do so. Except, if
  86444. ** there are already N worker threads running, the main thread does the work
  86445. ** itself.
  86446. **
  86447. ** The sorter is running in multi-threaded mode if (a) the library was built
  86448. ** with pre-processor symbol SQLITE_MAX_WORKER_THREADS set to a value greater
  86449. ** than zero, and (b) worker threads have been enabled at runtime by calling
  86450. ** "PRAGMA threads=N" with some value of N greater than 0.
  86451. **
  86452. ** When Rewind() is called, any data remaining in memory is flushed to a
  86453. ** final PMA. So at this point the data is stored in some number of sorted
  86454. ** PMAs within temporary files on disk.
  86455. **
  86456. ** If there are fewer than SORTER_MAX_MERGE_COUNT PMAs in total and the
  86457. ** sorter is running in single-threaded mode, then these PMAs are merged
  86458. ** incrementally as keys are retreived from the sorter by the VDBE. The
  86459. ** MergeEngine object, described in further detail below, performs this
  86460. ** merge.
  86461. **
  86462. ** Or, if running in multi-threaded mode, then a background thread is
  86463. ** launched to merge the existing PMAs. Once the background thread has
  86464. ** merged T bytes of data into a single sorted PMA, the main thread
  86465. ** begins reading keys from that PMA while the background thread proceeds
  86466. ** with merging the next T bytes of data. And so on.
  86467. **
  86468. ** Parameter T is set to half the value of the memory threshold used
  86469. ** by Write() above to determine when to create a new PMA.
  86470. **
  86471. ** If there are more than SORTER_MAX_MERGE_COUNT PMAs in total when
  86472. ** Rewind() is called, then a hierarchy of incremental-merges is used.
  86473. ** First, T bytes of data from the first SORTER_MAX_MERGE_COUNT PMAs on
  86474. ** disk are merged together. Then T bytes of data from the second set, and
  86475. ** so on, such that no operation ever merges more than SORTER_MAX_MERGE_COUNT
  86476. ** PMAs at a time. This done is to improve locality.
  86477. **
  86478. ** If running in multi-threaded mode and there are more than
  86479. ** SORTER_MAX_MERGE_COUNT PMAs on disk when Rewind() is called, then more
  86480. ** than one background thread may be created. Specifically, there may be
  86481. ** one background thread for each temporary file on disk, and one background
  86482. ** thread to merge the output of each of the others to a single PMA for
  86483. ** the main thread to read from.
  86484. */
  86485. /* #include "sqliteInt.h" */
  86486. /* #include "vdbeInt.h" */
  86487. /*
  86488. ** If SQLITE_DEBUG_SORTER_THREADS is defined, this module outputs various
  86489. ** messages to stderr that may be helpful in understanding the performance
  86490. ** characteristics of the sorter in multi-threaded mode.
  86491. */
  86492. #if 0
  86493. # define SQLITE_DEBUG_SORTER_THREADS 1
  86494. #endif
  86495. /*
  86496. ** Hard-coded maximum amount of data to accumulate in memory before flushing
  86497. ** to a level 0 PMA. The purpose of this limit is to prevent various integer
  86498. ** overflows. 512MiB.
  86499. */
  86500. #define SQLITE_MAX_PMASZ (1<<29)
  86501. /*
  86502. ** Private objects used by the sorter
  86503. */
  86504. typedef struct MergeEngine MergeEngine; /* Merge PMAs together */
  86505. typedef struct PmaReader PmaReader; /* Incrementally read one PMA */
  86506. typedef struct PmaWriter PmaWriter; /* Incrementally write one PMA */
  86507. typedef struct SorterRecord SorterRecord; /* A record being sorted */
  86508. typedef struct SortSubtask SortSubtask; /* A sub-task in the sort process */
  86509. typedef struct SorterFile SorterFile; /* Temporary file object wrapper */
  86510. typedef struct SorterList SorterList; /* In-memory list of records */
  86511. typedef struct IncrMerger IncrMerger; /* Read & merge multiple PMAs */
  86512. /*
  86513. ** A container for a temp file handle and the current amount of data
  86514. ** stored in the file.
  86515. */
  86516. struct SorterFile {
  86517. sqlite3_file *pFd; /* File handle */
  86518. i64 iEof; /* Bytes of data stored in pFd */
  86519. };
  86520. /*
  86521. ** An in-memory list of objects to be sorted.
  86522. **
  86523. ** If aMemory==0 then each object is allocated separately and the objects
  86524. ** are connected using SorterRecord.u.pNext. If aMemory!=0 then all objects
  86525. ** are stored in the aMemory[] bulk memory, one right after the other, and
  86526. ** are connected using SorterRecord.u.iNext.
  86527. */
  86528. struct SorterList {
  86529. SorterRecord *pList; /* Linked list of records */
  86530. u8 *aMemory; /* If non-NULL, bulk memory to hold pList */
  86531. int szPMA; /* Size of pList as PMA in bytes */
  86532. };
  86533. /*
  86534. ** The MergeEngine object is used to combine two or more smaller PMAs into
  86535. ** one big PMA using a merge operation. Separate PMAs all need to be
  86536. ** combined into one big PMA in order to be able to step through the sorted
  86537. ** records in order.
  86538. **
  86539. ** The aReadr[] array contains a PmaReader object for each of the PMAs being
  86540. ** merged. An aReadr[] object either points to a valid key or else is at EOF.
  86541. ** ("EOF" means "End Of File". When aReadr[] is at EOF there is no more data.)
  86542. ** For the purposes of the paragraphs below, we assume that the array is
  86543. ** actually N elements in size, where N is the smallest power of 2 greater
  86544. ** to or equal to the number of PMAs being merged. The extra aReadr[] elements
  86545. ** are treated as if they are empty (always at EOF).
  86546. **
  86547. ** The aTree[] array is also N elements in size. The value of N is stored in
  86548. ** the MergeEngine.nTree variable.
  86549. **
  86550. ** The final (N/2) elements of aTree[] contain the results of comparing
  86551. ** pairs of PMA keys together. Element i contains the result of
  86552. ** comparing aReadr[2*i-N] and aReadr[2*i-N+1]. Whichever key is smaller, the
  86553. ** aTree element is set to the index of it.
  86554. **
  86555. ** For the purposes of this comparison, EOF is considered greater than any
  86556. ** other key value. If the keys are equal (only possible with two EOF
  86557. ** values), it doesn't matter which index is stored.
  86558. **
  86559. ** The (N/4) elements of aTree[] that precede the final (N/2) described
  86560. ** above contains the index of the smallest of each block of 4 PmaReaders
  86561. ** And so on. So that aTree[1] contains the index of the PmaReader that
  86562. ** currently points to the smallest key value. aTree[0] is unused.
  86563. **
  86564. ** Example:
  86565. **
  86566. ** aReadr[0] -> Banana
  86567. ** aReadr[1] -> Feijoa
  86568. ** aReadr[2] -> Elderberry
  86569. ** aReadr[3] -> Currant
  86570. ** aReadr[4] -> Grapefruit
  86571. ** aReadr[5] -> Apple
  86572. ** aReadr[6] -> Durian
  86573. ** aReadr[7] -> EOF
  86574. **
  86575. ** aTree[] = { X, 5 0, 5 0, 3, 5, 6 }
  86576. **
  86577. ** The current element is "Apple" (the value of the key indicated by
  86578. ** PmaReader 5). When the Next() operation is invoked, PmaReader 5 will
  86579. ** be advanced to the next key in its segment. Say the next key is
  86580. ** "Eggplant":
  86581. **
  86582. ** aReadr[5] -> Eggplant
  86583. **
  86584. ** The contents of aTree[] are updated first by comparing the new PmaReader
  86585. ** 5 key to the current key of PmaReader 4 (still "Grapefruit"). The PmaReader
  86586. ** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
  86587. ** The value of PmaReader 6 - "Durian" - is now smaller than that of PmaReader
  86588. ** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
  86589. ** so the value written into element 1 of the array is 0. As follows:
  86590. **
  86591. ** aTree[] = { X, 0 0, 6 0, 3, 5, 6 }
  86592. **
  86593. ** In other words, each time we advance to the next sorter element, log2(N)
  86594. ** key comparison operations are required, where N is the number of segments
  86595. ** being merged (rounded up to the next power of 2).
  86596. */
  86597. struct MergeEngine {
  86598. int nTree; /* Used size of aTree/aReadr (power of 2) */
  86599. SortSubtask *pTask; /* Used by this thread only */
  86600. int *aTree; /* Current state of incremental merge */
  86601. PmaReader *aReadr; /* Array of PmaReaders to merge data from */
  86602. };
  86603. /*
  86604. ** This object represents a single thread of control in a sort operation.
  86605. ** Exactly VdbeSorter.nTask instances of this object are allocated
  86606. ** as part of each VdbeSorter object. Instances are never allocated any
  86607. ** other way. VdbeSorter.nTask is set to the number of worker threads allowed
  86608. ** (see SQLITE_CONFIG_WORKER_THREADS) plus one (the main thread). Thus for
  86609. ** single-threaded operation, there is exactly one instance of this object
  86610. ** and for multi-threaded operation there are two or more instances.
  86611. **
  86612. ** Essentially, this structure contains all those fields of the VdbeSorter
  86613. ** structure for which each thread requires a separate instance. For example,
  86614. ** each thread requries its own UnpackedRecord object to unpack records in
  86615. ** as part of comparison operations.
  86616. **
  86617. ** Before a background thread is launched, variable bDone is set to 0. Then,
  86618. ** right before it exits, the thread itself sets bDone to 1. This is used for
  86619. ** two purposes:
  86620. **
  86621. ** 1. When flushing the contents of memory to a level-0 PMA on disk, to
  86622. ** attempt to select a SortSubtask for which there is not already an
  86623. ** active background thread (since doing so causes the main thread
  86624. ** to block until it finishes).
  86625. **
  86626. ** 2. If SQLITE_DEBUG_SORTER_THREADS is defined, to determine if a call
  86627. ** to sqlite3ThreadJoin() is likely to block. Cases that are likely to
  86628. ** block provoke debugging output.
  86629. **
  86630. ** In both cases, the effects of the main thread seeing (bDone==0) even
  86631. ** after the thread has finished are not dire. So we don't worry about
  86632. ** memory barriers and such here.
  86633. */
  86634. typedef int (*SorterCompare)(SortSubtask*,int*,const void*,int,const void*,int);
  86635. struct SortSubtask {
  86636. SQLiteThread *pThread; /* Background thread, if any */
  86637. int bDone; /* Set if thread is finished but not joined */
  86638. VdbeSorter *pSorter; /* Sorter that owns this sub-task */
  86639. UnpackedRecord *pUnpacked; /* Space to unpack a record */
  86640. SorterList list; /* List for thread to write to a PMA */
  86641. int nPMA; /* Number of PMAs currently in file */
  86642. SorterCompare xCompare; /* Compare function to use */
  86643. SorterFile file; /* Temp file for level-0 PMAs */
  86644. SorterFile file2; /* Space for other PMAs */
  86645. };
  86646. /*
  86647. ** Main sorter structure. A single instance of this is allocated for each
  86648. ** sorter cursor created by the VDBE.
  86649. **
  86650. ** mxKeysize:
  86651. ** As records are added to the sorter by calls to sqlite3VdbeSorterWrite(),
  86652. ** this variable is updated so as to be set to the size on disk of the
  86653. ** largest record in the sorter.
  86654. */
  86655. struct VdbeSorter {
  86656. int mnPmaSize; /* Minimum PMA size, in bytes */
  86657. int mxPmaSize; /* Maximum PMA size, in bytes. 0==no limit */
  86658. int mxKeysize; /* Largest serialized key seen so far */
  86659. int pgsz; /* Main database page size */
  86660. PmaReader *pReader; /* Readr data from here after Rewind() */
  86661. MergeEngine *pMerger; /* Or here, if bUseThreads==0 */
  86662. sqlite3 *db; /* Database connection */
  86663. KeyInfo *pKeyInfo; /* How to compare records */
  86664. UnpackedRecord *pUnpacked; /* Used by VdbeSorterCompare() */
  86665. SorterList list; /* List of in-memory records */
  86666. int iMemory; /* Offset of free space in list.aMemory */
  86667. int nMemory; /* Size of list.aMemory allocation in bytes */
  86668. u8 bUsePMA; /* True if one or more PMAs created */
  86669. u8 bUseThreads; /* True to use background threads */
  86670. u8 iPrev; /* Previous thread used to flush PMA */
  86671. u8 nTask; /* Size of aTask[] array */
  86672. u8 typeMask;
  86673. SortSubtask aTask[1]; /* One or more subtasks */
  86674. };
  86675. #define SORTER_TYPE_INTEGER 0x01
  86676. #define SORTER_TYPE_TEXT 0x02
  86677. /*
  86678. ** An instance of the following object is used to read records out of a
  86679. ** PMA, in sorted order. The next key to be read is cached in nKey/aKey.
  86680. ** aKey might point into aMap or into aBuffer. If neither of those locations
  86681. ** contain a contiguous representation of the key, then aAlloc is allocated
  86682. ** and the key is copied into aAlloc and aKey is made to poitn to aAlloc.
  86683. **
  86684. ** pFd==0 at EOF.
  86685. */
  86686. struct PmaReader {
  86687. i64 iReadOff; /* Current read offset */
  86688. i64 iEof; /* 1 byte past EOF for this PmaReader */
  86689. int nAlloc; /* Bytes of space at aAlloc */
  86690. int nKey; /* Number of bytes in key */
  86691. sqlite3_file *pFd; /* File handle we are reading from */
  86692. u8 *aAlloc; /* Space for aKey if aBuffer and pMap wont work */
  86693. u8 *aKey; /* Pointer to current key */
  86694. u8 *aBuffer; /* Current read buffer */
  86695. int nBuffer; /* Size of read buffer in bytes */
  86696. u8 *aMap; /* Pointer to mapping of entire file */
  86697. IncrMerger *pIncr; /* Incremental merger */
  86698. };
  86699. /*
  86700. ** Normally, a PmaReader object iterates through an existing PMA stored
  86701. ** within a temp file. However, if the PmaReader.pIncr variable points to
  86702. ** an object of the following type, it may be used to iterate/merge through
  86703. ** multiple PMAs simultaneously.
  86704. **
  86705. ** There are two types of IncrMerger object - single (bUseThread==0) and
  86706. ** multi-threaded (bUseThread==1).
  86707. **
  86708. ** A multi-threaded IncrMerger object uses two temporary files - aFile[0]
  86709. ** and aFile[1]. Neither file is allowed to grow to more than mxSz bytes in
  86710. ** size. When the IncrMerger is initialized, it reads enough data from
  86711. ** pMerger to populate aFile[0]. It then sets variables within the
  86712. ** corresponding PmaReader object to read from that file and kicks off
  86713. ** a background thread to populate aFile[1] with the next mxSz bytes of
  86714. ** sorted record data from pMerger.
  86715. **
  86716. ** When the PmaReader reaches the end of aFile[0], it blocks until the
  86717. ** background thread has finished populating aFile[1]. It then exchanges
  86718. ** the contents of the aFile[0] and aFile[1] variables within this structure,
  86719. ** sets the PmaReader fields to read from the new aFile[0] and kicks off
  86720. ** another background thread to populate the new aFile[1]. And so on, until
  86721. ** the contents of pMerger are exhausted.
  86722. **
  86723. ** A single-threaded IncrMerger does not open any temporary files of its
  86724. ** own. Instead, it has exclusive access to mxSz bytes of space beginning
  86725. ** at offset iStartOff of file pTask->file2. And instead of using a
  86726. ** background thread to prepare data for the PmaReader, with a single
  86727. ** threaded IncrMerger the allocate part of pTask->file2 is "refilled" with
  86728. ** keys from pMerger by the calling thread whenever the PmaReader runs out
  86729. ** of data.
  86730. */
  86731. struct IncrMerger {
  86732. SortSubtask *pTask; /* Task that owns this merger */
  86733. MergeEngine *pMerger; /* Merge engine thread reads data from */
  86734. i64 iStartOff; /* Offset to start writing file at */
  86735. int mxSz; /* Maximum bytes of data to store */
  86736. int bEof; /* Set to true when merge is finished */
  86737. int bUseThread; /* True to use a bg thread for this object */
  86738. SorterFile aFile[2]; /* aFile[0] for reading, [1] for writing */
  86739. };
  86740. /*
  86741. ** An instance of this object is used for writing a PMA.
  86742. **
  86743. ** The PMA is written one record at a time. Each record is of an arbitrary
  86744. ** size. But I/O is more efficient if it occurs in page-sized blocks where
  86745. ** each block is aligned on a page boundary. This object caches writes to
  86746. ** the PMA so that aligned, page-size blocks are written.
  86747. */
  86748. struct PmaWriter {
  86749. int eFWErr; /* Non-zero if in an error state */
  86750. u8 *aBuffer; /* Pointer to write buffer */
  86751. int nBuffer; /* Size of write buffer in bytes */
  86752. int iBufStart; /* First byte of buffer to write */
  86753. int iBufEnd; /* Last byte of buffer to write */
  86754. i64 iWriteOff; /* Offset of start of buffer in file */
  86755. sqlite3_file *pFd; /* File handle to write to */
  86756. };
  86757. /*
  86758. ** This object is the header on a single record while that record is being
  86759. ** held in memory and prior to being written out as part of a PMA.
  86760. **
  86761. ** How the linked list is connected depends on how memory is being managed
  86762. ** by this module. If using a separate allocation for each in-memory record
  86763. ** (VdbeSorter.list.aMemory==0), then the list is always connected using the
  86764. ** SorterRecord.u.pNext pointers.
  86765. **
  86766. ** Or, if using the single large allocation method (VdbeSorter.list.aMemory!=0),
  86767. ** then while records are being accumulated the list is linked using the
  86768. ** SorterRecord.u.iNext offset. This is because the aMemory[] array may
  86769. ** be sqlite3Realloc()ed while records are being accumulated. Once the VM
  86770. ** has finished passing records to the sorter, or when the in-memory buffer
  86771. ** is full, the list is sorted. As part of the sorting process, it is
  86772. ** converted to use the SorterRecord.u.pNext pointers. See function
  86773. ** vdbeSorterSort() for details.
  86774. */
  86775. struct SorterRecord {
  86776. int nVal; /* Size of the record in bytes */
  86777. union {
  86778. SorterRecord *pNext; /* Pointer to next record in list */
  86779. int iNext; /* Offset within aMemory of next record */
  86780. } u;
  86781. /* The data for the record immediately follows this header */
  86782. };
  86783. /* Return a pointer to the buffer containing the record data for SorterRecord
  86784. ** object p. Should be used as if:
  86785. **
  86786. ** void *SRVAL(SorterRecord *p) { return (void*)&p[1]; }
  86787. */
  86788. #define SRVAL(p) ((void*)((SorterRecord*)(p) + 1))
  86789. /* Maximum number of PMAs that a single MergeEngine can merge */
  86790. #define SORTER_MAX_MERGE_COUNT 16
  86791. static int vdbeIncrSwap(IncrMerger*);
  86792. static void vdbeIncrFree(IncrMerger *);
  86793. /*
  86794. ** Free all memory belonging to the PmaReader object passed as the
  86795. ** argument. All structure fields are set to zero before returning.
  86796. */
  86797. static void vdbePmaReaderClear(PmaReader *pReadr){
  86798. sqlite3_free(pReadr->aAlloc);
  86799. sqlite3_free(pReadr->aBuffer);
  86800. if( pReadr->aMap ) sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
  86801. vdbeIncrFree(pReadr->pIncr);
  86802. memset(pReadr, 0, sizeof(PmaReader));
  86803. }
  86804. /*
  86805. ** Read the next nByte bytes of data from the PMA p.
  86806. ** If successful, set *ppOut to point to a buffer containing the data
  86807. ** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite
  86808. ** error code.
  86809. **
  86810. ** The buffer returned in *ppOut is only valid until the
  86811. ** next call to this function.
  86812. */
  86813. static int vdbePmaReadBlob(
  86814. PmaReader *p, /* PmaReader from which to take the blob */
  86815. int nByte, /* Bytes of data to read */
  86816. u8 **ppOut /* OUT: Pointer to buffer containing data */
  86817. ){
  86818. int iBuf; /* Offset within buffer to read from */
  86819. int nAvail; /* Bytes of data available in buffer */
  86820. if( p->aMap ){
  86821. *ppOut = &p->aMap[p->iReadOff];
  86822. p->iReadOff += nByte;
  86823. return SQLITE_OK;
  86824. }
  86825. assert( p->aBuffer );
  86826. /* If there is no more data to be read from the buffer, read the next
  86827. ** p->nBuffer bytes of data from the file into it. Or, if there are less
  86828. ** than p->nBuffer bytes remaining in the PMA, read all remaining data. */
  86829. iBuf = p->iReadOff % p->nBuffer;
  86830. if( iBuf==0 ){
  86831. int nRead; /* Bytes to read from disk */
  86832. int rc; /* sqlite3OsRead() return code */
  86833. /* Determine how many bytes of data to read. */
  86834. if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){
  86835. nRead = p->nBuffer;
  86836. }else{
  86837. nRead = (int)(p->iEof - p->iReadOff);
  86838. }
  86839. assert( nRead>0 );
  86840. /* Readr data from the file. Return early if an error occurs. */
  86841. rc = sqlite3OsRead(p->pFd, p->aBuffer, nRead, p->iReadOff);
  86842. assert( rc!=SQLITE_IOERR_SHORT_READ );
  86843. if( rc!=SQLITE_OK ) return rc;
  86844. }
  86845. nAvail = p->nBuffer - iBuf;
  86846. if( nByte<=nAvail ){
  86847. /* The requested data is available in the in-memory buffer. In this
  86848. ** case there is no need to make a copy of the data, just return a
  86849. ** pointer into the buffer to the caller. */
  86850. *ppOut = &p->aBuffer[iBuf];
  86851. p->iReadOff += nByte;
  86852. }else{
  86853. /* The requested data is not all available in the in-memory buffer.
  86854. ** In this case, allocate space at p->aAlloc[] to copy the requested
  86855. ** range into. Then return a copy of pointer p->aAlloc to the caller. */
  86856. int nRem; /* Bytes remaining to copy */
  86857. /* Extend the p->aAlloc[] allocation if required. */
  86858. if( p->nAlloc<nByte ){
  86859. u8 *aNew;
  86860. sqlite3_int64 nNew = MAX(128, 2*(sqlite3_int64)p->nAlloc);
  86861. while( nByte>nNew ) nNew = nNew*2;
  86862. aNew = sqlite3Realloc(p->aAlloc, nNew);
  86863. if( !aNew ) return SQLITE_NOMEM_BKPT;
  86864. p->nAlloc = nNew;
  86865. p->aAlloc = aNew;
  86866. }
  86867. /* Copy as much data as is available in the buffer into the start of
  86868. ** p->aAlloc[]. */
  86869. memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);
  86870. p->iReadOff += nAvail;
  86871. nRem = nByte - nAvail;
  86872. /* The following loop copies up to p->nBuffer bytes per iteration into
  86873. ** the p->aAlloc[] buffer. */
  86874. while( nRem>0 ){
  86875. int rc; /* vdbePmaReadBlob() return code */
  86876. int nCopy; /* Number of bytes to copy */
  86877. u8 *aNext; /* Pointer to buffer to copy data from */
  86878. nCopy = nRem;
  86879. if( nRem>p->nBuffer ) nCopy = p->nBuffer;
  86880. rc = vdbePmaReadBlob(p, nCopy, &aNext);
  86881. if( rc!=SQLITE_OK ) return rc;
  86882. assert( aNext!=p->aAlloc );
  86883. memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);
  86884. nRem -= nCopy;
  86885. }
  86886. *ppOut = p->aAlloc;
  86887. }
  86888. return SQLITE_OK;
  86889. }
  86890. /*
  86891. ** Read a varint from the stream of data accessed by p. Set *pnOut to
  86892. ** the value read.
  86893. */
  86894. static int vdbePmaReadVarint(PmaReader *p, u64 *pnOut){
  86895. int iBuf;
  86896. if( p->aMap ){
  86897. p->iReadOff += sqlite3GetVarint(&p->aMap[p->iReadOff], pnOut);
  86898. }else{
  86899. iBuf = p->iReadOff % p->nBuffer;
  86900. if( iBuf && (p->nBuffer-iBuf)>=9 ){
  86901. p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);
  86902. }else{
  86903. u8 aVarint[16], *a;
  86904. int i = 0, rc;
  86905. do{
  86906. rc = vdbePmaReadBlob(p, 1, &a);
  86907. if( rc ) return rc;
  86908. aVarint[(i++)&0xf] = a[0];
  86909. }while( (a[0]&0x80)!=0 );
  86910. sqlite3GetVarint(aVarint, pnOut);
  86911. }
  86912. }
  86913. return SQLITE_OK;
  86914. }
  86915. /*
  86916. ** Attempt to memory map file pFile. If successful, set *pp to point to the
  86917. ** new mapping and return SQLITE_OK. If the mapping is not attempted
  86918. ** (because the file is too large or the VFS layer is configured not to use
  86919. ** mmap), return SQLITE_OK and set *pp to NULL.
  86920. **
  86921. ** Or, if an error occurs, return an SQLite error code. The final value of
  86922. ** *pp is undefined in this case.
  86923. */
  86924. static int vdbeSorterMapFile(SortSubtask *pTask, SorterFile *pFile, u8 **pp){
  86925. int rc = SQLITE_OK;
  86926. if( pFile->iEof<=(i64)(pTask->pSorter->db->nMaxSorterMmap) ){
  86927. sqlite3_file *pFd = pFile->pFd;
  86928. if( pFd->pMethods->iVersion>=3 ){
  86929. rc = sqlite3OsFetch(pFd, 0, (int)pFile->iEof, (void**)pp);
  86930. testcase( rc!=SQLITE_OK );
  86931. }
  86932. }
  86933. return rc;
  86934. }
  86935. /*
  86936. ** Attach PmaReader pReadr to file pFile (if it is not already attached to
  86937. ** that file) and seek it to offset iOff within the file. Return SQLITE_OK
  86938. ** if successful, or an SQLite error code if an error occurs.
  86939. */
  86940. static int vdbePmaReaderSeek(
  86941. SortSubtask *pTask, /* Task context */
  86942. PmaReader *pReadr, /* Reader whose cursor is to be moved */
  86943. SorterFile *pFile, /* Sorter file to read from */
  86944. i64 iOff /* Offset in pFile */
  86945. ){
  86946. int rc = SQLITE_OK;
  86947. assert( pReadr->pIncr==0 || pReadr->pIncr->bEof==0 );
  86948. if( sqlite3FaultSim(201) ) return SQLITE_IOERR_READ;
  86949. if( pReadr->aMap ){
  86950. sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
  86951. pReadr->aMap = 0;
  86952. }
  86953. pReadr->iReadOff = iOff;
  86954. pReadr->iEof = pFile->iEof;
  86955. pReadr->pFd = pFile->pFd;
  86956. rc = vdbeSorterMapFile(pTask, pFile, &pReadr->aMap);
  86957. if( rc==SQLITE_OK && pReadr->aMap==0 ){
  86958. int pgsz = pTask->pSorter->pgsz;
  86959. int iBuf = pReadr->iReadOff % pgsz;
  86960. if( pReadr->aBuffer==0 ){
  86961. pReadr->aBuffer = (u8*)sqlite3Malloc(pgsz);
  86962. if( pReadr->aBuffer==0 ) rc = SQLITE_NOMEM_BKPT;
  86963. pReadr->nBuffer = pgsz;
  86964. }
  86965. if( rc==SQLITE_OK && iBuf ){
  86966. int nRead = pgsz - iBuf;
  86967. if( (pReadr->iReadOff + nRead) > pReadr->iEof ){
  86968. nRead = (int)(pReadr->iEof - pReadr->iReadOff);
  86969. }
  86970. rc = sqlite3OsRead(
  86971. pReadr->pFd, &pReadr->aBuffer[iBuf], nRead, pReadr->iReadOff
  86972. );
  86973. testcase( rc!=SQLITE_OK );
  86974. }
  86975. }
  86976. return rc;
  86977. }
  86978. /*
  86979. ** Advance PmaReader pReadr to the next key in its PMA. Return SQLITE_OK if
  86980. ** no error occurs, or an SQLite error code if one does.
  86981. */
  86982. static int vdbePmaReaderNext(PmaReader *pReadr){
  86983. int rc = SQLITE_OK; /* Return Code */
  86984. u64 nRec = 0; /* Size of record in bytes */
  86985. if( pReadr->iReadOff>=pReadr->iEof ){
  86986. IncrMerger *pIncr = pReadr->pIncr;
  86987. int bEof = 1;
  86988. if( pIncr ){
  86989. rc = vdbeIncrSwap(pIncr);
  86990. if( rc==SQLITE_OK && pIncr->bEof==0 ){
  86991. rc = vdbePmaReaderSeek(
  86992. pIncr->pTask, pReadr, &pIncr->aFile[0], pIncr->iStartOff
  86993. );
  86994. bEof = 0;
  86995. }
  86996. }
  86997. if( bEof ){
  86998. /* This is an EOF condition */
  86999. vdbePmaReaderClear(pReadr);
  87000. testcase( rc!=SQLITE_OK );
  87001. return rc;
  87002. }
  87003. }
  87004. if( rc==SQLITE_OK ){
  87005. rc = vdbePmaReadVarint(pReadr, &nRec);
  87006. }
  87007. if( rc==SQLITE_OK ){
  87008. pReadr->nKey = (int)nRec;
  87009. rc = vdbePmaReadBlob(pReadr, (int)nRec, &pReadr->aKey);
  87010. testcase( rc!=SQLITE_OK );
  87011. }
  87012. return rc;
  87013. }
  87014. /*
  87015. ** Initialize PmaReader pReadr to scan through the PMA stored in file pFile
  87016. ** starting at offset iStart and ending at offset iEof-1. This function
  87017. ** leaves the PmaReader pointing to the first key in the PMA (or EOF if the
  87018. ** PMA is empty).
  87019. **
  87020. ** If the pnByte parameter is NULL, then it is assumed that the file
  87021. ** contains a single PMA, and that that PMA omits the initial length varint.
  87022. */
  87023. static int vdbePmaReaderInit(
  87024. SortSubtask *pTask, /* Task context */
  87025. SorterFile *pFile, /* Sorter file to read from */
  87026. i64 iStart, /* Start offset in pFile */
  87027. PmaReader *pReadr, /* PmaReader to populate */
  87028. i64 *pnByte /* IN/OUT: Increment this value by PMA size */
  87029. ){
  87030. int rc;
  87031. assert( pFile->iEof>iStart );
  87032. assert( pReadr->aAlloc==0 && pReadr->nAlloc==0 );
  87033. assert( pReadr->aBuffer==0 );
  87034. assert( pReadr->aMap==0 );
  87035. rc = vdbePmaReaderSeek(pTask, pReadr, pFile, iStart);
  87036. if( rc==SQLITE_OK ){
  87037. u64 nByte = 0; /* Size of PMA in bytes */
  87038. rc = vdbePmaReadVarint(pReadr, &nByte);
  87039. pReadr->iEof = pReadr->iReadOff + nByte;
  87040. *pnByte += nByte;
  87041. }
  87042. if( rc==SQLITE_OK ){
  87043. rc = vdbePmaReaderNext(pReadr);
  87044. }
  87045. return rc;
  87046. }
  87047. /*
  87048. ** A version of vdbeSorterCompare() that assumes that it has already been
  87049. ** determined that the first field of key1 is equal to the first field of
  87050. ** key2.
  87051. */
  87052. static int vdbeSorterCompareTail(
  87053. SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
  87054. int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
  87055. const void *pKey1, int nKey1, /* Left side of comparison */
  87056. const void *pKey2, int nKey2 /* Right side of comparison */
  87057. ){
  87058. UnpackedRecord *r2 = pTask->pUnpacked;
  87059. if( *pbKey2Cached==0 ){
  87060. sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
  87061. *pbKey2Cached = 1;
  87062. }
  87063. return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, r2, 1);
  87064. }
  87065. /*
  87066. ** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2,
  87067. ** size nKey2 bytes). Use (pTask->pKeyInfo) for the collation sequences
  87068. ** used by the comparison. Return the result of the comparison.
  87069. **
  87070. ** If IN/OUT parameter *pbKey2Cached is true when this function is called,
  87071. ** it is assumed that (pTask->pUnpacked) contains the unpacked version
  87072. ** of key2. If it is false, (pTask->pUnpacked) is populated with the unpacked
  87073. ** version of key2 and *pbKey2Cached set to true before returning.
  87074. **
  87075. ** If an OOM error is encountered, (pTask->pUnpacked->error_rc) is set
  87076. ** to SQLITE_NOMEM.
  87077. */
  87078. static int vdbeSorterCompare(
  87079. SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
  87080. int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
  87081. const void *pKey1, int nKey1, /* Left side of comparison */
  87082. const void *pKey2, int nKey2 /* Right side of comparison */
  87083. ){
  87084. UnpackedRecord *r2 = pTask->pUnpacked;
  87085. if( !*pbKey2Cached ){
  87086. sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
  87087. *pbKey2Cached = 1;
  87088. }
  87089. return sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
  87090. }
  87091. /*
  87092. ** A specially optimized version of vdbeSorterCompare() that assumes that
  87093. ** the first field of each key is a TEXT value and that the collation
  87094. ** sequence to compare them with is BINARY.
  87095. */
  87096. static int vdbeSorterCompareText(
  87097. SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
  87098. int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
  87099. const void *pKey1, int nKey1, /* Left side of comparison */
  87100. const void *pKey2, int nKey2 /* Right side of comparison */
  87101. ){
  87102. const u8 * const p1 = (const u8 * const)pKey1;
  87103. const u8 * const p2 = (const u8 * const)pKey2;
  87104. const u8 * const v1 = &p1[ p1[0] ]; /* Pointer to value 1 */
  87105. const u8 * const v2 = &p2[ p2[0] ]; /* Pointer to value 2 */
  87106. int n1;
  87107. int n2;
  87108. int res;
  87109. getVarint32(&p1[1], n1);
  87110. getVarint32(&p2[1], n2);
  87111. res = memcmp(v1, v2, (MIN(n1, n2) - 13)/2);
  87112. if( res==0 ){
  87113. res = n1 - n2;
  87114. }
  87115. if( res==0 ){
  87116. if( pTask->pSorter->pKeyInfo->nKeyField>1 ){
  87117. res = vdbeSorterCompareTail(
  87118. pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
  87119. );
  87120. }
  87121. }else{
  87122. if( pTask->pSorter->pKeyInfo->aSortOrder[0] ){
  87123. res = res * -1;
  87124. }
  87125. }
  87126. return res;
  87127. }
  87128. /*
  87129. ** A specially optimized version of vdbeSorterCompare() that assumes that
  87130. ** the first field of each key is an INTEGER value.
  87131. */
  87132. static int vdbeSorterCompareInt(
  87133. SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
  87134. int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
  87135. const void *pKey1, int nKey1, /* Left side of comparison */
  87136. const void *pKey2, int nKey2 /* Right side of comparison */
  87137. ){
  87138. const u8 * const p1 = (const u8 * const)pKey1;
  87139. const u8 * const p2 = (const u8 * const)pKey2;
  87140. const int s1 = p1[1]; /* Left hand serial type */
  87141. const int s2 = p2[1]; /* Right hand serial type */
  87142. const u8 * const v1 = &p1[ p1[0] ]; /* Pointer to value 1 */
  87143. const u8 * const v2 = &p2[ p2[0] ]; /* Pointer to value 2 */
  87144. int res; /* Return value */
  87145. assert( (s1>0 && s1<7) || s1==8 || s1==9 );
  87146. assert( (s2>0 && s2<7) || s2==8 || s2==9 );
  87147. if( s1==s2 ){
  87148. /* The two values have the same sign. Compare using memcmp(). */
  87149. static const u8 aLen[] = {0, 1, 2, 3, 4, 6, 8, 0, 0, 0 };
  87150. const u8 n = aLen[s1];
  87151. int i;
  87152. res = 0;
  87153. for(i=0; i<n; i++){
  87154. if( (res = v1[i] - v2[i])!=0 ){
  87155. if( ((v1[0] ^ v2[0]) & 0x80)!=0 ){
  87156. res = v1[0] & 0x80 ? -1 : +1;
  87157. }
  87158. break;
  87159. }
  87160. }
  87161. }else if( s1>7 && s2>7 ){
  87162. res = s1 - s2;
  87163. }else{
  87164. if( s2>7 ){
  87165. res = +1;
  87166. }else if( s1>7 ){
  87167. res = -1;
  87168. }else{
  87169. res = s1 - s2;
  87170. }
  87171. assert( res!=0 );
  87172. if( res>0 ){
  87173. if( *v1 & 0x80 ) res = -1;
  87174. }else{
  87175. if( *v2 & 0x80 ) res = +1;
  87176. }
  87177. }
  87178. if( res==0 ){
  87179. if( pTask->pSorter->pKeyInfo->nKeyField>1 ){
  87180. res = vdbeSorterCompareTail(
  87181. pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
  87182. );
  87183. }
  87184. }else if( pTask->pSorter->pKeyInfo->aSortOrder[0] ){
  87185. res = res * -1;
  87186. }
  87187. return res;
  87188. }
  87189. /*
  87190. ** Initialize the temporary index cursor just opened as a sorter cursor.
  87191. **
  87192. ** Usually, the sorter module uses the value of (pCsr->pKeyInfo->nKeyField)
  87193. ** to determine the number of fields that should be compared from the
  87194. ** records being sorted. However, if the value passed as argument nField
  87195. ** is non-zero and the sorter is able to guarantee a stable sort, nField
  87196. ** is used instead. This is used when sorting records for a CREATE INDEX
  87197. ** statement. In this case, keys are always delivered to the sorter in
  87198. ** order of the primary key, which happens to be make up the final part
  87199. ** of the records being sorted. So if the sort is stable, there is never
  87200. ** any reason to compare PK fields and they can be ignored for a small
  87201. ** performance boost.
  87202. **
  87203. ** The sorter can guarantee a stable sort when running in single-threaded
  87204. ** mode, but not in multi-threaded mode.
  87205. **
  87206. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  87207. */
  87208. SQLITE_PRIVATE int sqlite3VdbeSorterInit(
  87209. sqlite3 *db, /* Database connection (for malloc()) */
  87210. int nField, /* Number of key fields in each record */
  87211. VdbeCursor *pCsr /* Cursor that holds the new sorter */
  87212. ){
  87213. int pgsz; /* Page size of main database */
  87214. int i; /* Used to iterate through aTask[] */
  87215. VdbeSorter *pSorter; /* The new sorter */
  87216. KeyInfo *pKeyInfo; /* Copy of pCsr->pKeyInfo with db==0 */
  87217. int szKeyInfo; /* Size of pCsr->pKeyInfo in bytes */
  87218. int sz; /* Size of pSorter in bytes */
  87219. int rc = SQLITE_OK;
  87220. #if SQLITE_MAX_WORKER_THREADS==0
  87221. # define nWorker 0
  87222. #else
  87223. int nWorker;
  87224. #endif
  87225. /* Initialize the upper limit on the number of worker threads */
  87226. #if SQLITE_MAX_WORKER_THREADS>0
  87227. if( sqlite3TempInMemory(db) || sqlite3GlobalConfig.bCoreMutex==0 ){
  87228. nWorker = 0;
  87229. }else{
  87230. nWorker = db->aLimit[SQLITE_LIMIT_WORKER_THREADS];
  87231. }
  87232. #endif
  87233. /* Do not allow the total number of threads (main thread + all workers)
  87234. ** to exceed the maximum merge count */
  87235. #if SQLITE_MAX_WORKER_THREADS>=SORTER_MAX_MERGE_COUNT
  87236. if( nWorker>=SORTER_MAX_MERGE_COUNT ){
  87237. nWorker = SORTER_MAX_MERGE_COUNT-1;
  87238. }
  87239. #endif
  87240. assert( pCsr->pKeyInfo && pCsr->pBtx==0 );
  87241. assert( pCsr->eCurType==CURTYPE_SORTER );
  87242. szKeyInfo = sizeof(KeyInfo) + (pCsr->pKeyInfo->nKeyField-1)*sizeof(CollSeq*);
  87243. sz = sizeof(VdbeSorter) + nWorker * sizeof(SortSubtask);
  87244. pSorter = (VdbeSorter*)sqlite3DbMallocZero(db, sz + szKeyInfo);
  87245. pCsr->uc.pSorter = pSorter;
  87246. if( pSorter==0 ){
  87247. rc = SQLITE_NOMEM_BKPT;
  87248. }else{
  87249. pSorter->pKeyInfo = pKeyInfo = (KeyInfo*)((u8*)pSorter + sz);
  87250. memcpy(pKeyInfo, pCsr->pKeyInfo, szKeyInfo);
  87251. pKeyInfo->db = 0;
  87252. if( nField && nWorker==0 ){
  87253. pKeyInfo->nKeyField = nField;
  87254. }
  87255. pSorter->pgsz = pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
  87256. pSorter->nTask = nWorker + 1;
  87257. pSorter->iPrev = (u8)(nWorker - 1);
  87258. pSorter->bUseThreads = (pSorter->nTask>1);
  87259. pSorter->db = db;
  87260. for(i=0; i<pSorter->nTask; i++){
  87261. SortSubtask *pTask = &pSorter->aTask[i];
  87262. pTask->pSorter = pSorter;
  87263. }
  87264. if( !sqlite3TempInMemory(db) ){
  87265. i64 mxCache; /* Cache size in bytes*/
  87266. u32 szPma = sqlite3GlobalConfig.szPma;
  87267. pSorter->mnPmaSize = szPma * pgsz;
  87268. mxCache = db->aDb[0].pSchema->cache_size;
  87269. if( mxCache<0 ){
  87270. /* A negative cache-size value C indicates that the cache is abs(C)
  87271. ** KiB in size. */
  87272. mxCache = mxCache * -1024;
  87273. }else{
  87274. mxCache = mxCache * pgsz;
  87275. }
  87276. mxCache = MIN(mxCache, SQLITE_MAX_PMASZ);
  87277. pSorter->mxPmaSize = MAX(pSorter->mnPmaSize, (int)mxCache);
  87278. /* Avoid large memory allocations if the application has requested
  87279. ** SQLITE_CONFIG_SMALL_MALLOC. */
  87280. if( sqlite3GlobalConfig.bSmallMalloc==0 ){
  87281. assert( pSorter->iMemory==0 );
  87282. pSorter->nMemory = pgsz;
  87283. pSorter->list.aMemory = (u8*)sqlite3Malloc(pgsz);
  87284. if( !pSorter->list.aMemory ) rc = SQLITE_NOMEM_BKPT;
  87285. }
  87286. }
  87287. if( pKeyInfo->nAllField<13
  87288. && (pKeyInfo->aColl[0]==0 || pKeyInfo->aColl[0]==db->pDfltColl)
  87289. ){
  87290. pSorter->typeMask = SORTER_TYPE_INTEGER | SORTER_TYPE_TEXT;
  87291. }
  87292. }
  87293. return rc;
  87294. }
  87295. #undef nWorker /* Defined at the top of this function */
  87296. /*
  87297. ** Free the list of sorted records starting at pRecord.
  87298. */
  87299. static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
  87300. SorterRecord *p;
  87301. SorterRecord *pNext;
  87302. for(p=pRecord; p; p=pNext){
  87303. pNext = p->u.pNext;
  87304. sqlite3DbFree(db, p);
  87305. }
  87306. }
  87307. /*
  87308. ** Free all resources owned by the object indicated by argument pTask. All
  87309. ** fields of *pTask are zeroed before returning.
  87310. */
  87311. static void vdbeSortSubtaskCleanup(sqlite3 *db, SortSubtask *pTask){
  87312. sqlite3DbFree(db, pTask->pUnpacked);
  87313. #if SQLITE_MAX_WORKER_THREADS>0
  87314. /* pTask->list.aMemory can only be non-zero if it was handed memory
  87315. ** from the main thread. That only occurs SQLITE_MAX_WORKER_THREADS>0 */
  87316. if( pTask->list.aMemory ){
  87317. sqlite3_free(pTask->list.aMemory);
  87318. }else
  87319. #endif
  87320. {
  87321. assert( pTask->list.aMemory==0 );
  87322. vdbeSorterRecordFree(0, pTask->list.pList);
  87323. }
  87324. if( pTask->file.pFd ){
  87325. sqlite3OsCloseFree(pTask->file.pFd);
  87326. }
  87327. if( pTask->file2.pFd ){
  87328. sqlite3OsCloseFree(pTask->file2.pFd);
  87329. }
  87330. memset(pTask, 0, sizeof(SortSubtask));
  87331. }
  87332. #ifdef SQLITE_DEBUG_SORTER_THREADS
  87333. static void vdbeSorterWorkDebug(SortSubtask *pTask, const char *zEvent){
  87334. i64 t;
  87335. int iTask = (pTask - pTask->pSorter->aTask);
  87336. sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
  87337. fprintf(stderr, "%lld:%d %s\n", t, iTask, zEvent);
  87338. }
  87339. static void vdbeSorterRewindDebug(const char *zEvent){
  87340. i64 t;
  87341. sqlite3OsCurrentTimeInt64(sqlite3_vfs_find(0), &t);
  87342. fprintf(stderr, "%lld:X %s\n", t, zEvent);
  87343. }
  87344. static void vdbeSorterPopulateDebug(
  87345. SortSubtask *pTask,
  87346. const char *zEvent
  87347. ){
  87348. i64 t;
  87349. int iTask = (pTask - pTask->pSorter->aTask);
  87350. sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
  87351. fprintf(stderr, "%lld:bg%d %s\n", t, iTask, zEvent);
  87352. }
  87353. static void vdbeSorterBlockDebug(
  87354. SortSubtask *pTask,
  87355. int bBlocked,
  87356. const char *zEvent
  87357. ){
  87358. if( bBlocked ){
  87359. i64 t;
  87360. sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
  87361. fprintf(stderr, "%lld:main %s\n", t, zEvent);
  87362. }
  87363. }
  87364. #else
  87365. # define vdbeSorterWorkDebug(x,y)
  87366. # define vdbeSorterRewindDebug(y)
  87367. # define vdbeSorterPopulateDebug(x,y)
  87368. # define vdbeSorterBlockDebug(x,y,z)
  87369. #endif
  87370. #if SQLITE_MAX_WORKER_THREADS>0
  87371. /*
  87372. ** Join thread pTask->thread.
  87373. */
  87374. static int vdbeSorterJoinThread(SortSubtask *pTask){
  87375. int rc = SQLITE_OK;
  87376. if( pTask->pThread ){
  87377. #ifdef SQLITE_DEBUG_SORTER_THREADS
  87378. int bDone = pTask->bDone;
  87379. #endif
  87380. void *pRet = SQLITE_INT_TO_PTR(SQLITE_ERROR);
  87381. vdbeSorterBlockDebug(pTask, !bDone, "enter");
  87382. (void)sqlite3ThreadJoin(pTask->pThread, &pRet);
  87383. vdbeSorterBlockDebug(pTask, !bDone, "exit");
  87384. rc = SQLITE_PTR_TO_INT(pRet);
  87385. assert( pTask->bDone==1 );
  87386. pTask->bDone = 0;
  87387. pTask->pThread = 0;
  87388. }
  87389. return rc;
  87390. }
  87391. /*
  87392. ** Launch a background thread to run xTask(pIn).
  87393. */
  87394. static int vdbeSorterCreateThread(
  87395. SortSubtask *pTask, /* Thread will use this task object */
  87396. void *(*xTask)(void*), /* Routine to run in a separate thread */
  87397. void *pIn /* Argument passed into xTask() */
  87398. ){
  87399. assert( pTask->pThread==0 && pTask->bDone==0 );
  87400. return sqlite3ThreadCreate(&pTask->pThread, xTask, pIn);
  87401. }
  87402. /*
  87403. ** Join all outstanding threads launched by SorterWrite() to create
  87404. ** level-0 PMAs.
  87405. */
  87406. static int vdbeSorterJoinAll(VdbeSorter *pSorter, int rcin){
  87407. int rc = rcin;
  87408. int i;
  87409. /* This function is always called by the main user thread.
  87410. **
  87411. ** If this function is being called after SorterRewind() has been called,
  87412. ** it is possible that thread pSorter->aTask[pSorter->nTask-1].pThread
  87413. ** is currently attempt to join one of the other threads. To avoid a race
  87414. ** condition where this thread also attempts to join the same object, join
  87415. ** thread pSorter->aTask[pSorter->nTask-1].pThread first. */
  87416. for(i=pSorter->nTask-1; i>=0; i--){
  87417. SortSubtask *pTask = &pSorter->aTask[i];
  87418. int rc2 = vdbeSorterJoinThread(pTask);
  87419. if( rc==SQLITE_OK ) rc = rc2;
  87420. }
  87421. return rc;
  87422. }
  87423. #else
  87424. # define vdbeSorterJoinAll(x,rcin) (rcin)
  87425. # define vdbeSorterJoinThread(pTask) SQLITE_OK
  87426. #endif
  87427. /*
  87428. ** Allocate a new MergeEngine object capable of handling up to
  87429. ** nReader PmaReader inputs.
  87430. **
  87431. ** nReader is automatically rounded up to the next power of two.
  87432. ** nReader may not exceed SORTER_MAX_MERGE_COUNT even after rounding up.
  87433. */
  87434. static MergeEngine *vdbeMergeEngineNew(int nReader){
  87435. int N = 2; /* Smallest power of two >= nReader */
  87436. int nByte; /* Total bytes of space to allocate */
  87437. MergeEngine *pNew; /* Pointer to allocated object to return */
  87438. assert( nReader<=SORTER_MAX_MERGE_COUNT );
  87439. while( N<nReader ) N += N;
  87440. nByte = sizeof(MergeEngine) + N * (sizeof(int) + sizeof(PmaReader));
  87441. pNew = sqlite3FaultSim(100) ? 0 : (MergeEngine*)sqlite3MallocZero(nByte);
  87442. if( pNew ){
  87443. pNew->nTree = N;
  87444. pNew->pTask = 0;
  87445. pNew->aReadr = (PmaReader*)&pNew[1];
  87446. pNew->aTree = (int*)&pNew->aReadr[N];
  87447. }
  87448. return pNew;
  87449. }
  87450. /*
  87451. ** Free the MergeEngine object passed as the only argument.
  87452. */
  87453. static void vdbeMergeEngineFree(MergeEngine *pMerger){
  87454. int i;
  87455. if( pMerger ){
  87456. for(i=0; i<pMerger->nTree; i++){
  87457. vdbePmaReaderClear(&pMerger->aReadr[i]);
  87458. }
  87459. }
  87460. sqlite3_free(pMerger);
  87461. }
  87462. /*
  87463. ** Free all resources associated with the IncrMerger object indicated by
  87464. ** the first argument.
  87465. */
  87466. static void vdbeIncrFree(IncrMerger *pIncr){
  87467. if( pIncr ){
  87468. #if SQLITE_MAX_WORKER_THREADS>0
  87469. if( pIncr->bUseThread ){
  87470. vdbeSorterJoinThread(pIncr->pTask);
  87471. if( pIncr->aFile[0].pFd ) sqlite3OsCloseFree(pIncr->aFile[0].pFd);
  87472. if( pIncr->aFile[1].pFd ) sqlite3OsCloseFree(pIncr->aFile[1].pFd);
  87473. }
  87474. #endif
  87475. vdbeMergeEngineFree(pIncr->pMerger);
  87476. sqlite3_free(pIncr);
  87477. }
  87478. }
  87479. /*
  87480. ** Reset a sorting cursor back to its original empty state.
  87481. */
  87482. SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *db, VdbeSorter *pSorter){
  87483. int i;
  87484. (void)vdbeSorterJoinAll(pSorter, SQLITE_OK);
  87485. assert( pSorter->bUseThreads || pSorter->pReader==0 );
  87486. #if SQLITE_MAX_WORKER_THREADS>0
  87487. if( pSorter->pReader ){
  87488. vdbePmaReaderClear(pSorter->pReader);
  87489. sqlite3DbFree(db, pSorter->pReader);
  87490. pSorter->pReader = 0;
  87491. }
  87492. #endif
  87493. vdbeMergeEngineFree(pSorter->pMerger);
  87494. pSorter->pMerger = 0;
  87495. for(i=0; i<pSorter->nTask; i++){
  87496. SortSubtask *pTask = &pSorter->aTask[i];
  87497. vdbeSortSubtaskCleanup(db, pTask);
  87498. pTask->pSorter = pSorter;
  87499. }
  87500. if( pSorter->list.aMemory==0 ){
  87501. vdbeSorterRecordFree(0, pSorter->list.pList);
  87502. }
  87503. pSorter->list.pList = 0;
  87504. pSorter->list.szPMA = 0;
  87505. pSorter->bUsePMA = 0;
  87506. pSorter->iMemory = 0;
  87507. pSorter->mxKeysize = 0;
  87508. sqlite3DbFree(db, pSorter->pUnpacked);
  87509. pSorter->pUnpacked = 0;
  87510. }
  87511. /*
  87512. ** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
  87513. */
  87514. SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
  87515. VdbeSorter *pSorter;
  87516. assert( pCsr->eCurType==CURTYPE_SORTER );
  87517. pSorter = pCsr->uc.pSorter;
  87518. if( pSorter ){
  87519. sqlite3VdbeSorterReset(db, pSorter);
  87520. sqlite3_free(pSorter->list.aMemory);
  87521. sqlite3DbFree(db, pSorter);
  87522. pCsr->uc.pSorter = 0;
  87523. }
  87524. }
  87525. #if SQLITE_MAX_MMAP_SIZE>0
  87526. /*
  87527. ** The first argument is a file-handle open on a temporary file. The file
  87528. ** is guaranteed to be nByte bytes or smaller in size. This function
  87529. ** attempts to extend the file to nByte bytes in size and to ensure that
  87530. ** the VFS has memory mapped it.
  87531. **
  87532. ** Whether or not the file does end up memory mapped of course depends on
  87533. ** the specific VFS implementation.
  87534. */
  87535. static void vdbeSorterExtendFile(sqlite3 *db, sqlite3_file *pFd, i64 nByte){
  87536. if( nByte<=(i64)(db->nMaxSorterMmap) && pFd->pMethods->iVersion>=3 ){
  87537. void *p = 0;
  87538. int chunksize = 4*1024;
  87539. sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_CHUNK_SIZE, &chunksize);
  87540. sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_SIZE_HINT, &nByte);
  87541. sqlite3OsFetch(pFd, 0, (int)nByte, &p);
  87542. sqlite3OsUnfetch(pFd, 0, p);
  87543. }
  87544. }
  87545. #else
  87546. # define vdbeSorterExtendFile(x,y,z)
  87547. #endif
  87548. /*
  87549. ** Allocate space for a file-handle and open a temporary file. If successful,
  87550. ** set *ppFd to point to the malloc'd file-handle and return SQLITE_OK.
  87551. ** Otherwise, set *ppFd to 0 and return an SQLite error code.
  87552. */
  87553. static int vdbeSorterOpenTempFile(
  87554. sqlite3 *db, /* Database handle doing sort */
  87555. i64 nExtend, /* Attempt to extend file to this size */
  87556. sqlite3_file **ppFd
  87557. ){
  87558. int rc;
  87559. if( sqlite3FaultSim(202) ) return SQLITE_IOERR_ACCESS;
  87560. rc = sqlite3OsOpenMalloc(db->pVfs, 0, ppFd,
  87561. SQLITE_OPEN_TEMP_JOURNAL |
  87562. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  87563. SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE, &rc
  87564. );
  87565. if( rc==SQLITE_OK ){
  87566. i64 max = SQLITE_MAX_MMAP_SIZE;
  87567. sqlite3OsFileControlHint(*ppFd, SQLITE_FCNTL_MMAP_SIZE, (void*)&max);
  87568. if( nExtend>0 ){
  87569. vdbeSorterExtendFile(db, *ppFd, nExtend);
  87570. }
  87571. }
  87572. return rc;
  87573. }
  87574. /*
  87575. ** If it has not already been allocated, allocate the UnpackedRecord
  87576. ** structure at pTask->pUnpacked. Return SQLITE_OK if successful (or
  87577. ** if no allocation was required), or SQLITE_NOMEM otherwise.
  87578. */
  87579. static int vdbeSortAllocUnpacked(SortSubtask *pTask){
  87580. if( pTask->pUnpacked==0 ){
  87581. pTask->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pTask->pSorter->pKeyInfo);
  87582. if( pTask->pUnpacked==0 ) return SQLITE_NOMEM_BKPT;
  87583. pTask->pUnpacked->nField = pTask->pSorter->pKeyInfo->nKeyField;
  87584. pTask->pUnpacked->errCode = 0;
  87585. }
  87586. return SQLITE_OK;
  87587. }
  87588. /*
  87589. ** Merge the two sorted lists p1 and p2 into a single list.
  87590. */
  87591. static SorterRecord *vdbeSorterMerge(
  87592. SortSubtask *pTask, /* Calling thread context */
  87593. SorterRecord *p1, /* First list to merge */
  87594. SorterRecord *p2 /* Second list to merge */
  87595. ){
  87596. SorterRecord *pFinal = 0;
  87597. SorterRecord **pp = &pFinal;
  87598. int bCached = 0;
  87599. assert( p1!=0 && p2!=0 );
  87600. for(;;){
  87601. int res;
  87602. res = pTask->xCompare(
  87603. pTask, &bCached, SRVAL(p1), p1->nVal, SRVAL(p2), p2->nVal
  87604. );
  87605. if( res<=0 ){
  87606. *pp = p1;
  87607. pp = &p1->u.pNext;
  87608. p1 = p1->u.pNext;
  87609. if( p1==0 ){
  87610. *pp = p2;
  87611. break;
  87612. }
  87613. }else{
  87614. *pp = p2;
  87615. pp = &p2->u.pNext;
  87616. p2 = p2->u.pNext;
  87617. bCached = 0;
  87618. if( p2==0 ){
  87619. *pp = p1;
  87620. break;
  87621. }
  87622. }
  87623. }
  87624. return pFinal;
  87625. }
  87626. /*
  87627. ** Return the SorterCompare function to compare values collected by the
  87628. ** sorter object passed as the only argument.
  87629. */
  87630. static SorterCompare vdbeSorterGetCompare(VdbeSorter *p){
  87631. if( p->typeMask==SORTER_TYPE_INTEGER ){
  87632. return vdbeSorterCompareInt;
  87633. }else if( p->typeMask==SORTER_TYPE_TEXT ){
  87634. return vdbeSorterCompareText;
  87635. }
  87636. return vdbeSorterCompare;
  87637. }
  87638. /*
  87639. ** Sort the linked list of records headed at pTask->pList. Return
  87640. ** SQLITE_OK if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if
  87641. ** an error occurs.
  87642. */
  87643. static int vdbeSorterSort(SortSubtask *pTask, SorterList *pList){
  87644. int i;
  87645. SorterRecord **aSlot;
  87646. SorterRecord *p;
  87647. int rc;
  87648. rc = vdbeSortAllocUnpacked(pTask);
  87649. if( rc!=SQLITE_OK ) return rc;
  87650. p = pList->pList;
  87651. pTask->xCompare = vdbeSorterGetCompare(pTask->pSorter);
  87652. aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
  87653. if( !aSlot ){
  87654. return SQLITE_NOMEM_BKPT;
  87655. }
  87656. while( p ){
  87657. SorterRecord *pNext;
  87658. if( pList->aMemory ){
  87659. if( (u8*)p==pList->aMemory ){
  87660. pNext = 0;
  87661. }else{
  87662. assert( p->u.iNext<sqlite3MallocSize(pList->aMemory) );
  87663. pNext = (SorterRecord*)&pList->aMemory[p->u.iNext];
  87664. }
  87665. }else{
  87666. pNext = p->u.pNext;
  87667. }
  87668. p->u.pNext = 0;
  87669. for(i=0; aSlot[i]; i++){
  87670. p = vdbeSorterMerge(pTask, p, aSlot[i]);
  87671. aSlot[i] = 0;
  87672. }
  87673. aSlot[i] = p;
  87674. p = pNext;
  87675. }
  87676. p = 0;
  87677. for(i=0; i<64; i++){
  87678. if( aSlot[i]==0 ) continue;
  87679. p = p ? vdbeSorterMerge(pTask, p, aSlot[i]) : aSlot[i];
  87680. }
  87681. pList->pList = p;
  87682. sqlite3_free(aSlot);
  87683. assert( pTask->pUnpacked->errCode==SQLITE_OK
  87684. || pTask->pUnpacked->errCode==SQLITE_NOMEM
  87685. );
  87686. return pTask->pUnpacked->errCode;
  87687. }
  87688. /*
  87689. ** Initialize a PMA-writer object.
  87690. */
  87691. static void vdbePmaWriterInit(
  87692. sqlite3_file *pFd, /* File handle to write to */
  87693. PmaWriter *p, /* Object to populate */
  87694. int nBuf, /* Buffer size */
  87695. i64 iStart /* Offset of pFd to begin writing at */
  87696. ){
  87697. memset(p, 0, sizeof(PmaWriter));
  87698. p->aBuffer = (u8*)sqlite3Malloc(nBuf);
  87699. if( !p->aBuffer ){
  87700. p->eFWErr = SQLITE_NOMEM_BKPT;
  87701. }else{
  87702. p->iBufEnd = p->iBufStart = (iStart % nBuf);
  87703. p->iWriteOff = iStart - p->iBufStart;
  87704. p->nBuffer = nBuf;
  87705. p->pFd = pFd;
  87706. }
  87707. }
  87708. /*
  87709. ** Write nData bytes of data to the PMA. Return SQLITE_OK
  87710. ** if successful, or an SQLite error code if an error occurs.
  87711. */
  87712. static void vdbePmaWriteBlob(PmaWriter *p, u8 *pData, int nData){
  87713. int nRem = nData;
  87714. while( nRem>0 && p->eFWErr==0 ){
  87715. int nCopy = nRem;
  87716. if( nCopy>(p->nBuffer - p->iBufEnd) ){
  87717. nCopy = p->nBuffer - p->iBufEnd;
  87718. }
  87719. memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);
  87720. p->iBufEnd += nCopy;
  87721. if( p->iBufEnd==p->nBuffer ){
  87722. p->eFWErr = sqlite3OsWrite(p->pFd,
  87723. &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
  87724. p->iWriteOff + p->iBufStart
  87725. );
  87726. p->iBufStart = p->iBufEnd = 0;
  87727. p->iWriteOff += p->nBuffer;
  87728. }
  87729. assert( p->iBufEnd<p->nBuffer );
  87730. nRem -= nCopy;
  87731. }
  87732. }
  87733. /*
  87734. ** Flush any buffered data to disk and clean up the PMA-writer object.
  87735. ** The results of using the PMA-writer after this call are undefined.
  87736. ** Return SQLITE_OK if flushing the buffered data succeeds or is not
  87737. ** required. Otherwise, return an SQLite error code.
  87738. **
  87739. ** Before returning, set *piEof to the offset immediately following the
  87740. ** last byte written to the file.
  87741. */
  87742. static int vdbePmaWriterFinish(PmaWriter *p, i64 *piEof){
  87743. int rc;
  87744. if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){
  87745. p->eFWErr = sqlite3OsWrite(p->pFd,
  87746. &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
  87747. p->iWriteOff + p->iBufStart
  87748. );
  87749. }
  87750. *piEof = (p->iWriteOff + p->iBufEnd);
  87751. sqlite3_free(p->aBuffer);
  87752. rc = p->eFWErr;
  87753. memset(p, 0, sizeof(PmaWriter));
  87754. return rc;
  87755. }
  87756. /*
  87757. ** Write value iVal encoded as a varint to the PMA. Return
  87758. ** SQLITE_OK if successful, or an SQLite error code if an error occurs.
  87759. */
  87760. static void vdbePmaWriteVarint(PmaWriter *p, u64 iVal){
  87761. int nByte;
  87762. u8 aByte[10];
  87763. nByte = sqlite3PutVarint(aByte, iVal);
  87764. vdbePmaWriteBlob(p, aByte, nByte);
  87765. }
  87766. /*
  87767. ** Write the current contents of in-memory linked-list pList to a level-0
  87768. ** PMA in the temp file belonging to sub-task pTask. Return SQLITE_OK if
  87769. ** successful, or an SQLite error code otherwise.
  87770. **
  87771. ** The format of a PMA is:
  87772. **
  87773. ** * A varint. This varint contains the total number of bytes of content
  87774. ** in the PMA (not including the varint itself).
  87775. **
  87776. ** * One or more records packed end-to-end in order of ascending keys.
  87777. ** Each record consists of a varint followed by a blob of data (the
  87778. ** key). The varint is the number of bytes in the blob of data.
  87779. */
  87780. static int vdbeSorterListToPMA(SortSubtask *pTask, SorterList *pList){
  87781. sqlite3 *db = pTask->pSorter->db;
  87782. int rc = SQLITE_OK; /* Return code */
  87783. PmaWriter writer; /* Object used to write to the file */
  87784. #ifdef SQLITE_DEBUG
  87785. /* Set iSz to the expected size of file pTask->file after writing the PMA.
  87786. ** This is used by an assert() statement at the end of this function. */
  87787. i64 iSz = pList->szPMA + sqlite3VarintLen(pList->szPMA) + pTask->file.iEof;
  87788. #endif
  87789. vdbeSorterWorkDebug(pTask, "enter");
  87790. memset(&writer, 0, sizeof(PmaWriter));
  87791. assert( pList->szPMA>0 );
  87792. /* If the first temporary PMA file has not been opened, open it now. */
  87793. if( pTask->file.pFd==0 ){
  87794. rc = vdbeSorterOpenTempFile(db, 0, &pTask->file.pFd);
  87795. assert( rc!=SQLITE_OK || pTask->file.pFd );
  87796. assert( pTask->file.iEof==0 );
  87797. assert( pTask->nPMA==0 );
  87798. }
  87799. /* Try to get the file to memory map */
  87800. if( rc==SQLITE_OK ){
  87801. vdbeSorterExtendFile(db, pTask->file.pFd, pTask->file.iEof+pList->szPMA+9);
  87802. }
  87803. /* Sort the list */
  87804. if( rc==SQLITE_OK ){
  87805. rc = vdbeSorterSort(pTask, pList);
  87806. }
  87807. if( rc==SQLITE_OK ){
  87808. SorterRecord *p;
  87809. SorterRecord *pNext = 0;
  87810. vdbePmaWriterInit(pTask->file.pFd, &writer, pTask->pSorter->pgsz,
  87811. pTask->file.iEof);
  87812. pTask->nPMA++;
  87813. vdbePmaWriteVarint(&writer, pList->szPMA);
  87814. for(p=pList->pList; p; p=pNext){
  87815. pNext = p->u.pNext;
  87816. vdbePmaWriteVarint(&writer, p->nVal);
  87817. vdbePmaWriteBlob(&writer, SRVAL(p), p->nVal);
  87818. if( pList->aMemory==0 ) sqlite3_free(p);
  87819. }
  87820. pList->pList = p;
  87821. rc = vdbePmaWriterFinish(&writer, &pTask->file.iEof);
  87822. }
  87823. vdbeSorterWorkDebug(pTask, "exit");
  87824. assert( rc!=SQLITE_OK || pList->pList==0 );
  87825. assert( rc!=SQLITE_OK || pTask->file.iEof==iSz );
  87826. return rc;
  87827. }
  87828. /*
  87829. ** Advance the MergeEngine to its next entry.
  87830. ** Set *pbEof to true there is no next entry because
  87831. ** the MergeEngine has reached the end of all its inputs.
  87832. **
  87833. ** Return SQLITE_OK if successful or an error code if an error occurs.
  87834. */
  87835. static int vdbeMergeEngineStep(
  87836. MergeEngine *pMerger, /* The merge engine to advance to the next row */
  87837. int *pbEof /* Set TRUE at EOF. Set false for more content */
  87838. ){
  87839. int rc;
  87840. int iPrev = pMerger->aTree[1];/* Index of PmaReader to advance */
  87841. SortSubtask *pTask = pMerger->pTask;
  87842. /* Advance the current PmaReader */
  87843. rc = vdbePmaReaderNext(&pMerger->aReadr[iPrev]);
  87844. /* Update contents of aTree[] */
  87845. if( rc==SQLITE_OK ){
  87846. int i; /* Index of aTree[] to recalculate */
  87847. PmaReader *pReadr1; /* First PmaReader to compare */
  87848. PmaReader *pReadr2; /* Second PmaReader to compare */
  87849. int bCached = 0;
  87850. /* Find the first two PmaReaders to compare. The one that was just
  87851. ** advanced (iPrev) and the one next to it in the array. */
  87852. pReadr1 = &pMerger->aReadr[(iPrev & 0xFFFE)];
  87853. pReadr2 = &pMerger->aReadr[(iPrev | 0x0001)];
  87854. for(i=(pMerger->nTree+iPrev)/2; i>0; i=i/2){
  87855. /* Compare pReadr1 and pReadr2. Store the result in variable iRes. */
  87856. int iRes;
  87857. if( pReadr1->pFd==0 ){
  87858. iRes = +1;
  87859. }else if( pReadr2->pFd==0 ){
  87860. iRes = -1;
  87861. }else{
  87862. iRes = pTask->xCompare(pTask, &bCached,
  87863. pReadr1->aKey, pReadr1->nKey, pReadr2->aKey, pReadr2->nKey
  87864. );
  87865. }
  87866. /* If pReadr1 contained the smaller value, set aTree[i] to its index.
  87867. ** Then set pReadr2 to the next PmaReader to compare to pReadr1. In this
  87868. ** case there is no cache of pReadr2 in pTask->pUnpacked, so set
  87869. ** pKey2 to point to the record belonging to pReadr2.
  87870. **
  87871. ** Alternatively, if pReadr2 contains the smaller of the two values,
  87872. ** set aTree[i] to its index and update pReadr1. If vdbeSorterCompare()
  87873. ** was actually called above, then pTask->pUnpacked now contains
  87874. ** a value equivalent to pReadr2. So set pKey2 to NULL to prevent
  87875. ** vdbeSorterCompare() from decoding pReadr2 again.
  87876. **
  87877. ** If the two values were equal, then the value from the oldest
  87878. ** PMA should be considered smaller. The VdbeSorter.aReadr[] array
  87879. ** is sorted from oldest to newest, so pReadr1 contains older values
  87880. ** than pReadr2 iff (pReadr1<pReadr2). */
  87881. if( iRes<0 || (iRes==0 && pReadr1<pReadr2) ){
  87882. pMerger->aTree[i] = (int)(pReadr1 - pMerger->aReadr);
  87883. pReadr2 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
  87884. bCached = 0;
  87885. }else{
  87886. if( pReadr1->pFd ) bCached = 0;
  87887. pMerger->aTree[i] = (int)(pReadr2 - pMerger->aReadr);
  87888. pReadr1 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
  87889. }
  87890. }
  87891. *pbEof = (pMerger->aReadr[pMerger->aTree[1]].pFd==0);
  87892. }
  87893. return (rc==SQLITE_OK ? pTask->pUnpacked->errCode : rc);
  87894. }
  87895. #if SQLITE_MAX_WORKER_THREADS>0
  87896. /*
  87897. ** The main routine for background threads that write level-0 PMAs.
  87898. */
  87899. static void *vdbeSorterFlushThread(void *pCtx){
  87900. SortSubtask *pTask = (SortSubtask*)pCtx;
  87901. int rc; /* Return code */
  87902. assert( pTask->bDone==0 );
  87903. rc = vdbeSorterListToPMA(pTask, &pTask->list);
  87904. pTask->bDone = 1;
  87905. return SQLITE_INT_TO_PTR(rc);
  87906. }
  87907. #endif /* SQLITE_MAX_WORKER_THREADS>0 */
  87908. /*
  87909. ** Flush the current contents of VdbeSorter.list to a new PMA, possibly
  87910. ** using a background thread.
  87911. */
  87912. static int vdbeSorterFlushPMA(VdbeSorter *pSorter){
  87913. #if SQLITE_MAX_WORKER_THREADS==0
  87914. pSorter->bUsePMA = 1;
  87915. return vdbeSorterListToPMA(&pSorter->aTask[0], &pSorter->list);
  87916. #else
  87917. int rc = SQLITE_OK;
  87918. int i;
  87919. SortSubtask *pTask = 0; /* Thread context used to create new PMA */
  87920. int nWorker = (pSorter->nTask-1);
  87921. /* Set the flag to indicate that at least one PMA has been written.
  87922. ** Or will be, anyhow. */
  87923. pSorter->bUsePMA = 1;
  87924. /* Select a sub-task to sort and flush the current list of in-memory
  87925. ** records to disk. If the sorter is running in multi-threaded mode,
  87926. ** round-robin between the first (pSorter->nTask-1) tasks. Except, if
  87927. ** the background thread from a sub-tasks previous turn is still running,
  87928. ** skip it. If the first (pSorter->nTask-1) sub-tasks are all still busy,
  87929. ** fall back to using the final sub-task. The first (pSorter->nTask-1)
  87930. ** sub-tasks are prefered as they use background threads - the final
  87931. ** sub-task uses the main thread. */
  87932. for(i=0; i<nWorker; i++){
  87933. int iTest = (pSorter->iPrev + i + 1) % nWorker;
  87934. pTask = &pSorter->aTask[iTest];
  87935. if( pTask->bDone ){
  87936. rc = vdbeSorterJoinThread(pTask);
  87937. }
  87938. if( rc!=SQLITE_OK || pTask->pThread==0 ) break;
  87939. }
  87940. if( rc==SQLITE_OK ){
  87941. if( i==nWorker ){
  87942. /* Use the foreground thread for this operation */
  87943. rc = vdbeSorterListToPMA(&pSorter->aTask[nWorker], &pSorter->list);
  87944. }else{
  87945. /* Launch a background thread for this operation */
  87946. u8 *aMem = pTask->list.aMemory;
  87947. void *pCtx = (void*)pTask;
  87948. assert( pTask->pThread==0 && pTask->bDone==0 );
  87949. assert( pTask->list.pList==0 );
  87950. assert( pTask->list.aMemory==0 || pSorter->list.aMemory!=0 );
  87951. pSorter->iPrev = (u8)(pTask - pSorter->aTask);
  87952. pTask->list = pSorter->list;
  87953. pSorter->list.pList = 0;
  87954. pSorter->list.szPMA = 0;
  87955. if( aMem ){
  87956. pSorter->list.aMemory = aMem;
  87957. pSorter->nMemory = sqlite3MallocSize(aMem);
  87958. }else if( pSorter->list.aMemory ){
  87959. pSorter->list.aMemory = sqlite3Malloc(pSorter->nMemory);
  87960. if( !pSorter->list.aMemory ) return SQLITE_NOMEM_BKPT;
  87961. }
  87962. rc = vdbeSorterCreateThread(pTask, vdbeSorterFlushThread, pCtx);
  87963. }
  87964. }
  87965. return rc;
  87966. #endif /* SQLITE_MAX_WORKER_THREADS!=0 */
  87967. }
  87968. /*
  87969. ** Add a record to the sorter.
  87970. */
  87971. SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
  87972. const VdbeCursor *pCsr, /* Sorter cursor */
  87973. Mem *pVal /* Memory cell containing record */
  87974. ){
  87975. VdbeSorter *pSorter;
  87976. int rc = SQLITE_OK; /* Return Code */
  87977. SorterRecord *pNew; /* New list element */
  87978. int bFlush; /* True to flush contents of memory to PMA */
  87979. int nReq; /* Bytes of memory required */
  87980. int nPMA; /* Bytes of PMA space required */
  87981. int t; /* serial type of first record field */
  87982. assert( pCsr->eCurType==CURTYPE_SORTER );
  87983. pSorter = pCsr->uc.pSorter;
  87984. getVarint32((const u8*)&pVal->z[1], t);
  87985. if( t>0 && t<10 && t!=7 ){
  87986. pSorter->typeMask &= SORTER_TYPE_INTEGER;
  87987. }else if( t>10 && (t & 0x01) ){
  87988. pSorter->typeMask &= SORTER_TYPE_TEXT;
  87989. }else{
  87990. pSorter->typeMask = 0;
  87991. }
  87992. assert( pSorter );
  87993. /* Figure out whether or not the current contents of memory should be
  87994. ** flushed to a PMA before continuing. If so, do so.
  87995. **
  87996. ** If using the single large allocation mode (pSorter->aMemory!=0), then
  87997. ** flush the contents of memory to a new PMA if (a) at least one value is
  87998. ** already in memory and (b) the new value will not fit in memory.
  87999. **
  88000. ** Or, if using separate allocations for each record, flush the contents
  88001. ** of memory to a PMA if either of the following are true:
  88002. **
  88003. ** * The total memory allocated for the in-memory list is greater
  88004. ** than (page-size * cache-size), or
  88005. **
  88006. ** * The total memory allocated for the in-memory list is greater
  88007. ** than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
  88008. */
  88009. nReq = pVal->n + sizeof(SorterRecord);
  88010. nPMA = pVal->n + sqlite3VarintLen(pVal->n);
  88011. if( pSorter->mxPmaSize ){
  88012. if( pSorter->list.aMemory ){
  88013. bFlush = pSorter->iMemory && (pSorter->iMemory+nReq) > pSorter->mxPmaSize;
  88014. }else{
  88015. bFlush = (
  88016. (pSorter->list.szPMA > pSorter->mxPmaSize)
  88017. || (pSorter->list.szPMA > pSorter->mnPmaSize && sqlite3HeapNearlyFull())
  88018. );
  88019. }
  88020. if( bFlush ){
  88021. rc = vdbeSorterFlushPMA(pSorter);
  88022. pSorter->list.szPMA = 0;
  88023. pSorter->iMemory = 0;
  88024. assert( rc!=SQLITE_OK || pSorter->list.pList==0 );
  88025. }
  88026. }
  88027. pSorter->list.szPMA += nPMA;
  88028. if( nPMA>pSorter->mxKeysize ){
  88029. pSorter->mxKeysize = nPMA;
  88030. }
  88031. if( pSorter->list.aMemory ){
  88032. int nMin = pSorter->iMemory + nReq;
  88033. if( nMin>pSorter->nMemory ){
  88034. u8 *aNew;
  88035. sqlite3_int64 nNew = 2 * (sqlite3_int64)pSorter->nMemory;
  88036. int iListOff = -1;
  88037. if( pSorter->list.pList ){
  88038. iListOff = (u8*)pSorter->list.pList - pSorter->list.aMemory;
  88039. }
  88040. while( nNew < nMin ) nNew = nNew*2;
  88041. if( nNew > pSorter->mxPmaSize ) nNew = pSorter->mxPmaSize;
  88042. if( nNew < nMin ) nNew = nMin;
  88043. aNew = sqlite3Realloc(pSorter->list.aMemory, nNew);
  88044. if( !aNew ) return SQLITE_NOMEM_BKPT;
  88045. if( iListOff>=0 ){
  88046. pSorter->list.pList = (SorterRecord*)&aNew[iListOff];
  88047. }
  88048. pSorter->list.aMemory = aNew;
  88049. pSorter->nMemory = nNew;
  88050. }
  88051. pNew = (SorterRecord*)&pSorter->list.aMemory[pSorter->iMemory];
  88052. pSorter->iMemory += ROUND8(nReq);
  88053. if( pSorter->list.pList ){
  88054. pNew->u.iNext = (int)((u8*)(pSorter->list.pList) - pSorter->list.aMemory);
  88055. }
  88056. }else{
  88057. pNew = (SorterRecord *)sqlite3Malloc(nReq);
  88058. if( pNew==0 ){
  88059. return SQLITE_NOMEM_BKPT;
  88060. }
  88061. pNew->u.pNext = pSorter->list.pList;
  88062. }
  88063. memcpy(SRVAL(pNew), pVal->z, pVal->n);
  88064. pNew->nVal = pVal->n;
  88065. pSorter->list.pList = pNew;
  88066. return rc;
  88067. }
  88068. /*
  88069. ** Read keys from pIncr->pMerger and populate pIncr->aFile[1]. The format
  88070. ** of the data stored in aFile[1] is the same as that used by regular PMAs,
  88071. ** except that the number-of-bytes varint is omitted from the start.
  88072. */
  88073. static int vdbeIncrPopulate(IncrMerger *pIncr){
  88074. int rc = SQLITE_OK;
  88075. int rc2;
  88076. i64 iStart = pIncr->iStartOff;
  88077. SorterFile *pOut = &pIncr->aFile[1];
  88078. SortSubtask *pTask = pIncr->pTask;
  88079. MergeEngine *pMerger = pIncr->pMerger;
  88080. PmaWriter writer;
  88081. assert( pIncr->bEof==0 );
  88082. vdbeSorterPopulateDebug(pTask, "enter");
  88083. vdbePmaWriterInit(pOut->pFd, &writer, pTask->pSorter->pgsz, iStart);
  88084. while( rc==SQLITE_OK ){
  88085. int dummy;
  88086. PmaReader *pReader = &pMerger->aReadr[ pMerger->aTree[1] ];
  88087. int nKey = pReader->nKey;
  88088. i64 iEof = writer.iWriteOff + writer.iBufEnd;
  88089. /* Check if the output file is full or if the input has been exhausted.
  88090. ** In either case exit the loop. */
  88091. if( pReader->pFd==0 ) break;
  88092. if( (iEof + nKey + sqlite3VarintLen(nKey))>(iStart + pIncr->mxSz) ) break;
  88093. /* Write the next key to the output. */
  88094. vdbePmaWriteVarint(&writer, nKey);
  88095. vdbePmaWriteBlob(&writer, pReader->aKey, nKey);
  88096. assert( pIncr->pMerger->pTask==pTask );
  88097. rc = vdbeMergeEngineStep(pIncr->pMerger, &dummy);
  88098. }
  88099. rc2 = vdbePmaWriterFinish(&writer, &pOut->iEof);
  88100. if( rc==SQLITE_OK ) rc = rc2;
  88101. vdbeSorterPopulateDebug(pTask, "exit");
  88102. return rc;
  88103. }
  88104. #if SQLITE_MAX_WORKER_THREADS>0
  88105. /*
  88106. ** The main routine for background threads that populate aFile[1] of
  88107. ** multi-threaded IncrMerger objects.
  88108. */
  88109. static void *vdbeIncrPopulateThread(void *pCtx){
  88110. IncrMerger *pIncr = (IncrMerger*)pCtx;
  88111. void *pRet = SQLITE_INT_TO_PTR( vdbeIncrPopulate(pIncr) );
  88112. pIncr->pTask->bDone = 1;
  88113. return pRet;
  88114. }
  88115. /*
  88116. ** Launch a background thread to populate aFile[1] of pIncr.
  88117. */
  88118. static int vdbeIncrBgPopulate(IncrMerger *pIncr){
  88119. void *p = (void*)pIncr;
  88120. assert( pIncr->bUseThread );
  88121. return vdbeSorterCreateThread(pIncr->pTask, vdbeIncrPopulateThread, p);
  88122. }
  88123. #endif
  88124. /*
  88125. ** This function is called when the PmaReader corresponding to pIncr has
  88126. ** finished reading the contents of aFile[0]. Its purpose is to "refill"
  88127. ** aFile[0] such that the PmaReader should start rereading it from the
  88128. ** beginning.
  88129. **
  88130. ** For single-threaded objects, this is accomplished by literally reading
  88131. ** keys from pIncr->pMerger and repopulating aFile[0].
  88132. **
  88133. ** For multi-threaded objects, all that is required is to wait until the
  88134. ** background thread is finished (if it is not already) and then swap
  88135. ** aFile[0] and aFile[1] in place. If the contents of pMerger have not
  88136. ** been exhausted, this function also launches a new background thread
  88137. ** to populate the new aFile[1].
  88138. **
  88139. ** SQLITE_OK is returned on success, or an SQLite error code otherwise.
  88140. */
  88141. static int vdbeIncrSwap(IncrMerger *pIncr){
  88142. int rc = SQLITE_OK;
  88143. #if SQLITE_MAX_WORKER_THREADS>0
  88144. if( pIncr->bUseThread ){
  88145. rc = vdbeSorterJoinThread(pIncr->pTask);
  88146. if( rc==SQLITE_OK ){
  88147. SorterFile f0 = pIncr->aFile[0];
  88148. pIncr->aFile[0] = pIncr->aFile[1];
  88149. pIncr->aFile[1] = f0;
  88150. }
  88151. if( rc==SQLITE_OK ){
  88152. if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
  88153. pIncr->bEof = 1;
  88154. }else{
  88155. rc = vdbeIncrBgPopulate(pIncr);
  88156. }
  88157. }
  88158. }else
  88159. #endif
  88160. {
  88161. rc = vdbeIncrPopulate(pIncr);
  88162. pIncr->aFile[0] = pIncr->aFile[1];
  88163. if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
  88164. pIncr->bEof = 1;
  88165. }
  88166. }
  88167. return rc;
  88168. }
  88169. /*
  88170. ** Allocate and return a new IncrMerger object to read data from pMerger.
  88171. **
  88172. ** If an OOM condition is encountered, return NULL. In this case free the
  88173. ** pMerger argument before returning.
  88174. */
  88175. static int vdbeIncrMergerNew(
  88176. SortSubtask *pTask, /* The thread that will be using the new IncrMerger */
  88177. MergeEngine *pMerger, /* The MergeEngine that the IncrMerger will control */
  88178. IncrMerger **ppOut /* Write the new IncrMerger here */
  88179. ){
  88180. int rc = SQLITE_OK;
  88181. IncrMerger *pIncr = *ppOut = (IncrMerger*)
  88182. (sqlite3FaultSim(100) ? 0 : sqlite3MallocZero(sizeof(*pIncr)));
  88183. if( pIncr ){
  88184. pIncr->pMerger = pMerger;
  88185. pIncr->pTask = pTask;
  88186. pIncr->mxSz = MAX(pTask->pSorter->mxKeysize+9,pTask->pSorter->mxPmaSize/2);
  88187. pTask->file2.iEof += pIncr->mxSz;
  88188. }else{
  88189. vdbeMergeEngineFree(pMerger);
  88190. rc = SQLITE_NOMEM_BKPT;
  88191. }
  88192. return rc;
  88193. }
  88194. #if SQLITE_MAX_WORKER_THREADS>0
  88195. /*
  88196. ** Set the "use-threads" flag on object pIncr.
  88197. */
  88198. static void vdbeIncrMergerSetThreads(IncrMerger *pIncr){
  88199. pIncr->bUseThread = 1;
  88200. pIncr->pTask->file2.iEof -= pIncr->mxSz;
  88201. }
  88202. #endif /* SQLITE_MAX_WORKER_THREADS>0 */
  88203. /*
  88204. ** Recompute pMerger->aTree[iOut] by comparing the next keys on the
  88205. ** two PmaReaders that feed that entry. Neither of the PmaReaders
  88206. ** are advanced. This routine merely does the comparison.
  88207. */
  88208. static void vdbeMergeEngineCompare(
  88209. MergeEngine *pMerger, /* Merge engine containing PmaReaders to compare */
  88210. int iOut /* Store the result in pMerger->aTree[iOut] */
  88211. ){
  88212. int i1;
  88213. int i2;
  88214. int iRes;
  88215. PmaReader *p1;
  88216. PmaReader *p2;
  88217. assert( iOut<pMerger->nTree && iOut>0 );
  88218. if( iOut>=(pMerger->nTree/2) ){
  88219. i1 = (iOut - pMerger->nTree/2) * 2;
  88220. i2 = i1 + 1;
  88221. }else{
  88222. i1 = pMerger->aTree[iOut*2];
  88223. i2 = pMerger->aTree[iOut*2+1];
  88224. }
  88225. p1 = &pMerger->aReadr[i1];
  88226. p2 = &pMerger->aReadr[i2];
  88227. if( p1->pFd==0 ){
  88228. iRes = i2;
  88229. }else if( p2->pFd==0 ){
  88230. iRes = i1;
  88231. }else{
  88232. SortSubtask *pTask = pMerger->pTask;
  88233. int bCached = 0;
  88234. int res;
  88235. assert( pTask->pUnpacked!=0 ); /* from vdbeSortSubtaskMain() */
  88236. res = pTask->xCompare(
  88237. pTask, &bCached, p1->aKey, p1->nKey, p2->aKey, p2->nKey
  88238. );
  88239. if( res<=0 ){
  88240. iRes = i1;
  88241. }else{
  88242. iRes = i2;
  88243. }
  88244. }
  88245. pMerger->aTree[iOut] = iRes;
  88246. }
  88247. /*
  88248. ** Allowed values for the eMode parameter to vdbeMergeEngineInit()
  88249. ** and vdbePmaReaderIncrMergeInit().
  88250. **
  88251. ** Only INCRINIT_NORMAL is valid in single-threaded builds (when
  88252. ** SQLITE_MAX_WORKER_THREADS==0). The other values are only used
  88253. ** when there exists one or more separate worker threads.
  88254. */
  88255. #define INCRINIT_NORMAL 0
  88256. #define INCRINIT_TASK 1
  88257. #define INCRINIT_ROOT 2
  88258. /*
  88259. ** Forward reference required as the vdbeIncrMergeInit() and
  88260. ** vdbePmaReaderIncrInit() routines are called mutually recursively when
  88261. ** building a merge tree.
  88262. */
  88263. static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode);
  88264. /*
  88265. ** Initialize the MergeEngine object passed as the second argument. Once this
  88266. ** function returns, the first key of merged data may be read from the
  88267. ** MergeEngine object in the usual fashion.
  88268. **
  88269. ** If argument eMode is INCRINIT_ROOT, then it is assumed that any IncrMerge
  88270. ** objects attached to the PmaReader objects that the merger reads from have
  88271. ** already been populated, but that they have not yet populated aFile[0] and
  88272. ** set the PmaReader objects up to read from it. In this case all that is
  88273. ** required is to call vdbePmaReaderNext() on each PmaReader to point it at
  88274. ** its first key.
  88275. **
  88276. ** Otherwise, if eMode is any value other than INCRINIT_ROOT, then use
  88277. ** vdbePmaReaderIncrMergeInit() to initialize each PmaReader that feeds data
  88278. ** to pMerger.
  88279. **
  88280. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  88281. */
  88282. static int vdbeMergeEngineInit(
  88283. SortSubtask *pTask, /* Thread that will run pMerger */
  88284. MergeEngine *pMerger, /* MergeEngine to initialize */
  88285. int eMode /* One of the INCRINIT_XXX constants */
  88286. ){
  88287. int rc = SQLITE_OK; /* Return code */
  88288. int i; /* For looping over PmaReader objects */
  88289. int nTree; /* Number of subtrees to merge */
  88290. /* Failure to allocate the merge would have been detected prior to
  88291. ** invoking this routine */
  88292. assert( pMerger!=0 );
  88293. /* eMode is always INCRINIT_NORMAL in single-threaded mode */
  88294. assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
  88295. /* Verify that the MergeEngine is assigned to a single thread */
  88296. assert( pMerger->pTask==0 );
  88297. pMerger->pTask = pTask;
  88298. nTree = pMerger->nTree;
  88299. for(i=0; i<nTree; i++){
  88300. if( SQLITE_MAX_WORKER_THREADS>0 && eMode==INCRINIT_ROOT ){
  88301. /* PmaReaders should be normally initialized in order, as if they are
  88302. ** reading from the same temp file this makes for more linear file IO.
  88303. ** However, in the INCRINIT_ROOT case, if PmaReader aReadr[nTask-1] is
  88304. ** in use it will block the vdbePmaReaderNext() call while it uses
  88305. ** the main thread to fill its buffer. So calling PmaReaderNext()
  88306. ** on this PmaReader before any of the multi-threaded PmaReaders takes
  88307. ** better advantage of multi-processor hardware. */
  88308. rc = vdbePmaReaderNext(&pMerger->aReadr[nTree-i-1]);
  88309. }else{
  88310. rc = vdbePmaReaderIncrInit(&pMerger->aReadr[i], INCRINIT_NORMAL);
  88311. }
  88312. if( rc!=SQLITE_OK ) return rc;
  88313. }
  88314. for(i=pMerger->nTree-1; i>0; i--){
  88315. vdbeMergeEngineCompare(pMerger, i);
  88316. }
  88317. return pTask->pUnpacked->errCode;
  88318. }
  88319. /*
  88320. ** The PmaReader passed as the first argument is guaranteed to be an
  88321. ** incremental-reader (pReadr->pIncr!=0). This function serves to open
  88322. ** and/or initialize the temp file related fields of the IncrMerge
  88323. ** object at (pReadr->pIncr).
  88324. **
  88325. ** If argument eMode is set to INCRINIT_NORMAL, then all PmaReaders
  88326. ** in the sub-tree headed by pReadr are also initialized. Data is then
  88327. ** loaded into the buffers belonging to pReadr and it is set to point to
  88328. ** the first key in its range.
  88329. **
  88330. ** If argument eMode is set to INCRINIT_TASK, then pReadr is guaranteed
  88331. ** to be a multi-threaded PmaReader and this function is being called in a
  88332. ** background thread. In this case all PmaReaders in the sub-tree are
  88333. ** initialized as for INCRINIT_NORMAL and the aFile[1] buffer belonging to
  88334. ** pReadr is populated. However, pReadr itself is not set up to point
  88335. ** to its first key. A call to vdbePmaReaderNext() is still required to do
  88336. ** that.
  88337. **
  88338. ** The reason this function does not call vdbePmaReaderNext() immediately
  88339. ** in the INCRINIT_TASK case is that vdbePmaReaderNext() assumes that it has
  88340. ** to block on thread (pTask->thread) before accessing aFile[1]. But, since
  88341. ** this entire function is being run by thread (pTask->thread), that will
  88342. ** lead to the current background thread attempting to join itself.
  88343. **
  88344. ** Finally, if argument eMode is set to INCRINIT_ROOT, it may be assumed
  88345. ** that pReadr->pIncr is a multi-threaded IncrMerge objects, and that all
  88346. ** child-trees have already been initialized using IncrInit(INCRINIT_TASK).
  88347. ** In this case vdbePmaReaderNext() is called on all child PmaReaders and
  88348. ** the current PmaReader set to point to the first key in its range.
  88349. **
  88350. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  88351. */
  88352. static int vdbePmaReaderIncrMergeInit(PmaReader *pReadr, int eMode){
  88353. int rc = SQLITE_OK;
  88354. IncrMerger *pIncr = pReadr->pIncr;
  88355. SortSubtask *pTask = pIncr->pTask;
  88356. sqlite3 *db = pTask->pSorter->db;
  88357. /* eMode is always INCRINIT_NORMAL in single-threaded mode */
  88358. assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
  88359. rc = vdbeMergeEngineInit(pTask, pIncr->pMerger, eMode);
  88360. /* Set up the required files for pIncr. A multi-theaded IncrMerge object
  88361. ** requires two temp files to itself, whereas a single-threaded object
  88362. ** only requires a region of pTask->file2. */
  88363. if( rc==SQLITE_OK ){
  88364. int mxSz = pIncr->mxSz;
  88365. #if SQLITE_MAX_WORKER_THREADS>0
  88366. if( pIncr->bUseThread ){
  88367. rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[0].pFd);
  88368. if( rc==SQLITE_OK ){
  88369. rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[1].pFd);
  88370. }
  88371. }else
  88372. #endif
  88373. /*if( !pIncr->bUseThread )*/{
  88374. if( pTask->file2.pFd==0 ){
  88375. assert( pTask->file2.iEof>0 );
  88376. rc = vdbeSorterOpenTempFile(db, pTask->file2.iEof, &pTask->file2.pFd);
  88377. pTask->file2.iEof = 0;
  88378. }
  88379. if( rc==SQLITE_OK ){
  88380. pIncr->aFile[1].pFd = pTask->file2.pFd;
  88381. pIncr->iStartOff = pTask->file2.iEof;
  88382. pTask->file2.iEof += mxSz;
  88383. }
  88384. }
  88385. }
  88386. #if SQLITE_MAX_WORKER_THREADS>0
  88387. if( rc==SQLITE_OK && pIncr->bUseThread ){
  88388. /* Use the current thread to populate aFile[1], even though this
  88389. ** PmaReader is multi-threaded. If this is an INCRINIT_TASK object,
  88390. ** then this function is already running in background thread
  88391. ** pIncr->pTask->thread.
  88392. **
  88393. ** If this is the INCRINIT_ROOT object, then it is running in the
  88394. ** main VDBE thread. But that is Ok, as that thread cannot return
  88395. ** control to the VDBE or proceed with anything useful until the
  88396. ** first results are ready from this merger object anyway.
  88397. */
  88398. assert( eMode==INCRINIT_ROOT || eMode==INCRINIT_TASK );
  88399. rc = vdbeIncrPopulate(pIncr);
  88400. }
  88401. #endif
  88402. if( rc==SQLITE_OK && (SQLITE_MAX_WORKER_THREADS==0 || eMode!=INCRINIT_TASK) ){
  88403. rc = vdbePmaReaderNext(pReadr);
  88404. }
  88405. return rc;
  88406. }
  88407. #if SQLITE_MAX_WORKER_THREADS>0
  88408. /*
  88409. ** The main routine for vdbePmaReaderIncrMergeInit() operations run in
  88410. ** background threads.
  88411. */
  88412. static void *vdbePmaReaderBgIncrInit(void *pCtx){
  88413. PmaReader *pReader = (PmaReader*)pCtx;
  88414. void *pRet = SQLITE_INT_TO_PTR(
  88415. vdbePmaReaderIncrMergeInit(pReader,INCRINIT_TASK)
  88416. );
  88417. pReader->pIncr->pTask->bDone = 1;
  88418. return pRet;
  88419. }
  88420. #endif
  88421. /*
  88422. ** If the PmaReader passed as the first argument is not an incremental-reader
  88423. ** (if pReadr->pIncr==0), then this function is a no-op. Otherwise, it invokes
  88424. ** the vdbePmaReaderIncrMergeInit() function with the parameters passed to
  88425. ** this routine to initialize the incremental merge.
  88426. **
  88427. ** If the IncrMerger object is multi-threaded (IncrMerger.bUseThread==1),
  88428. ** then a background thread is launched to call vdbePmaReaderIncrMergeInit().
  88429. ** Or, if the IncrMerger is single threaded, the same function is called
  88430. ** using the current thread.
  88431. */
  88432. static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode){
  88433. IncrMerger *pIncr = pReadr->pIncr; /* Incremental merger */
  88434. int rc = SQLITE_OK; /* Return code */
  88435. if( pIncr ){
  88436. #if SQLITE_MAX_WORKER_THREADS>0
  88437. assert( pIncr->bUseThread==0 || eMode==INCRINIT_TASK );
  88438. if( pIncr->bUseThread ){
  88439. void *pCtx = (void*)pReadr;
  88440. rc = vdbeSorterCreateThread(pIncr->pTask, vdbePmaReaderBgIncrInit, pCtx);
  88441. }else
  88442. #endif
  88443. {
  88444. rc = vdbePmaReaderIncrMergeInit(pReadr, eMode);
  88445. }
  88446. }
  88447. return rc;
  88448. }
  88449. /*
  88450. ** Allocate a new MergeEngine object to merge the contents of nPMA level-0
  88451. ** PMAs from pTask->file. If no error occurs, set *ppOut to point to
  88452. ** the new object and return SQLITE_OK. Or, if an error does occur, set *ppOut
  88453. ** to NULL and return an SQLite error code.
  88454. **
  88455. ** When this function is called, *piOffset is set to the offset of the
  88456. ** first PMA to read from pTask->file. Assuming no error occurs, it is
  88457. ** set to the offset immediately following the last byte of the last
  88458. ** PMA before returning. If an error does occur, then the final value of
  88459. ** *piOffset is undefined.
  88460. */
  88461. static int vdbeMergeEngineLevel0(
  88462. SortSubtask *pTask, /* Sorter task to read from */
  88463. int nPMA, /* Number of PMAs to read */
  88464. i64 *piOffset, /* IN/OUT: Readr offset in pTask->file */
  88465. MergeEngine **ppOut /* OUT: New merge-engine */
  88466. ){
  88467. MergeEngine *pNew; /* Merge engine to return */
  88468. i64 iOff = *piOffset;
  88469. int i;
  88470. int rc = SQLITE_OK;
  88471. *ppOut = pNew = vdbeMergeEngineNew(nPMA);
  88472. if( pNew==0 ) rc = SQLITE_NOMEM_BKPT;
  88473. for(i=0; i<nPMA && rc==SQLITE_OK; i++){
  88474. i64 nDummy = 0;
  88475. PmaReader *pReadr = &pNew->aReadr[i];
  88476. rc = vdbePmaReaderInit(pTask, &pTask->file, iOff, pReadr, &nDummy);
  88477. iOff = pReadr->iEof;
  88478. }
  88479. if( rc!=SQLITE_OK ){
  88480. vdbeMergeEngineFree(pNew);
  88481. *ppOut = 0;
  88482. }
  88483. *piOffset = iOff;
  88484. return rc;
  88485. }
  88486. /*
  88487. ** Return the depth of a tree comprising nPMA PMAs, assuming a fanout of
  88488. ** SORTER_MAX_MERGE_COUNT. The returned value does not include leaf nodes.
  88489. **
  88490. ** i.e.
  88491. **
  88492. ** nPMA<=16 -> TreeDepth() == 0
  88493. ** nPMA<=256 -> TreeDepth() == 1
  88494. ** nPMA<=65536 -> TreeDepth() == 2
  88495. */
  88496. static int vdbeSorterTreeDepth(int nPMA){
  88497. int nDepth = 0;
  88498. i64 nDiv = SORTER_MAX_MERGE_COUNT;
  88499. while( nDiv < (i64)nPMA ){
  88500. nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
  88501. nDepth++;
  88502. }
  88503. return nDepth;
  88504. }
  88505. /*
  88506. ** pRoot is the root of an incremental merge-tree with depth nDepth (according
  88507. ** to vdbeSorterTreeDepth()). pLeaf is the iSeq'th leaf to be added to the
  88508. ** tree, counting from zero. This function adds pLeaf to the tree.
  88509. **
  88510. ** If successful, SQLITE_OK is returned. If an error occurs, an SQLite error
  88511. ** code is returned and pLeaf is freed.
  88512. */
  88513. static int vdbeSorterAddToTree(
  88514. SortSubtask *pTask, /* Task context */
  88515. int nDepth, /* Depth of tree according to TreeDepth() */
  88516. int iSeq, /* Sequence number of leaf within tree */
  88517. MergeEngine *pRoot, /* Root of tree */
  88518. MergeEngine *pLeaf /* Leaf to add to tree */
  88519. ){
  88520. int rc = SQLITE_OK;
  88521. int nDiv = 1;
  88522. int i;
  88523. MergeEngine *p = pRoot;
  88524. IncrMerger *pIncr;
  88525. rc = vdbeIncrMergerNew(pTask, pLeaf, &pIncr);
  88526. for(i=1; i<nDepth; i++){
  88527. nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
  88528. }
  88529. for(i=1; i<nDepth && rc==SQLITE_OK; i++){
  88530. int iIter = (iSeq / nDiv) % SORTER_MAX_MERGE_COUNT;
  88531. PmaReader *pReadr = &p->aReadr[iIter];
  88532. if( pReadr->pIncr==0 ){
  88533. MergeEngine *pNew = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
  88534. if( pNew==0 ){
  88535. rc = SQLITE_NOMEM_BKPT;
  88536. }else{
  88537. rc = vdbeIncrMergerNew(pTask, pNew, &pReadr->pIncr);
  88538. }
  88539. }
  88540. if( rc==SQLITE_OK ){
  88541. p = pReadr->pIncr->pMerger;
  88542. nDiv = nDiv / SORTER_MAX_MERGE_COUNT;
  88543. }
  88544. }
  88545. if( rc==SQLITE_OK ){
  88546. p->aReadr[iSeq % SORTER_MAX_MERGE_COUNT].pIncr = pIncr;
  88547. }else{
  88548. vdbeIncrFree(pIncr);
  88549. }
  88550. return rc;
  88551. }
  88552. /*
  88553. ** This function is called as part of a SorterRewind() operation on a sorter
  88554. ** that has already written two or more level-0 PMAs to one or more temp
  88555. ** files. It builds a tree of MergeEngine/IncrMerger/PmaReader objects that
  88556. ** can be used to incrementally merge all PMAs on disk.
  88557. **
  88558. ** If successful, SQLITE_OK is returned and *ppOut set to point to the
  88559. ** MergeEngine object at the root of the tree before returning. Or, if an
  88560. ** error occurs, an SQLite error code is returned and the final value
  88561. ** of *ppOut is undefined.
  88562. */
  88563. static int vdbeSorterMergeTreeBuild(
  88564. VdbeSorter *pSorter, /* The VDBE cursor that implements the sort */
  88565. MergeEngine **ppOut /* Write the MergeEngine here */
  88566. ){
  88567. MergeEngine *pMain = 0;
  88568. int rc = SQLITE_OK;
  88569. int iTask;
  88570. #if SQLITE_MAX_WORKER_THREADS>0
  88571. /* If the sorter uses more than one task, then create the top-level
  88572. ** MergeEngine here. This MergeEngine will read data from exactly
  88573. ** one PmaReader per sub-task. */
  88574. assert( pSorter->bUseThreads || pSorter->nTask==1 );
  88575. if( pSorter->nTask>1 ){
  88576. pMain = vdbeMergeEngineNew(pSorter->nTask);
  88577. if( pMain==0 ) rc = SQLITE_NOMEM_BKPT;
  88578. }
  88579. #endif
  88580. for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
  88581. SortSubtask *pTask = &pSorter->aTask[iTask];
  88582. assert( pTask->nPMA>0 || SQLITE_MAX_WORKER_THREADS>0 );
  88583. if( SQLITE_MAX_WORKER_THREADS==0 || pTask->nPMA ){
  88584. MergeEngine *pRoot = 0; /* Root node of tree for this task */
  88585. int nDepth = vdbeSorterTreeDepth(pTask->nPMA);
  88586. i64 iReadOff = 0;
  88587. if( pTask->nPMA<=SORTER_MAX_MERGE_COUNT ){
  88588. rc = vdbeMergeEngineLevel0(pTask, pTask->nPMA, &iReadOff, &pRoot);
  88589. }else{
  88590. int i;
  88591. int iSeq = 0;
  88592. pRoot = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
  88593. if( pRoot==0 ) rc = SQLITE_NOMEM_BKPT;
  88594. for(i=0; i<pTask->nPMA && rc==SQLITE_OK; i += SORTER_MAX_MERGE_COUNT){
  88595. MergeEngine *pMerger = 0; /* New level-0 PMA merger */
  88596. int nReader; /* Number of level-0 PMAs to merge */
  88597. nReader = MIN(pTask->nPMA - i, SORTER_MAX_MERGE_COUNT);
  88598. rc = vdbeMergeEngineLevel0(pTask, nReader, &iReadOff, &pMerger);
  88599. if( rc==SQLITE_OK ){
  88600. rc = vdbeSorterAddToTree(pTask, nDepth, iSeq++, pRoot, pMerger);
  88601. }
  88602. }
  88603. }
  88604. if( rc==SQLITE_OK ){
  88605. #if SQLITE_MAX_WORKER_THREADS>0
  88606. if( pMain!=0 ){
  88607. rc = vdbeIncrMergerNew(pTask, pRoot, &pMain->aReadr[iTask].pIncr);
  88608. }else
  88609. #endif
  88610. {
  88611. assert( pMain==0 );
  88612. pMain = pRoot;
  88613. }
  88614. }else{
  88615. vdbeMergeEngineFree(pRoot);
  88616. }
  88617. }
  88618. }
  88619. if( rc!=SQLITE_OK ){
  88620. vdbeMergeEngineFree(pMain);
  88621. pMain = 0;
  88622. }
  88623. *ppOut = pMain;
  88624. return rc;
  88625. }
  88626. /*
  88627. ** This function is called as part of an sqlite3VdbeSorterRewind() operation
  88628. ** on a sorter that has written two or more PMAs to temporary files. It sets
  88629. ** up either VdbeSorter.pMerger (for single threaded sorters) or pReader
  88630. ** (for multi-threaded sorters) so that it can be used to iterate through
  88631. ** all records stored in the sorter.
  88632. **
  88633. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  88634. */
  88635. static int vdbeSorterSetupMerge(VdbeSorter *pSorter){
  88636. int rc; /* Return code */
  88637. SortSubtask *pTask0 = &pSorter->aTask[0];
  88638. MergeEngine *pMain = 0;
  88639. #if SQLITE_MAX_WORKER_THREADS
  88640. sqlite3 *db = pTask0->pSorter->db;
  88641. int i;
  88642. SorterCompare xCompare = vdbeSorterGetCompare(pSorter);
  88643. for(i=0; i<pSorter->nTask; i++){
  88644. pSorter->aTask[i].xCompare = xCompare;
  88645. }
  88646. #endif
  88647. rc = vdbeSorterMergeTreeBuild(pSorter, &pMain);
  88648. if( rc==SQLITE_OK ){
  88649. #if SQLITE_MAX_WORKER_THREADS
  88650. assert( pSorter->bUseThreads==0 || pSorter->nTask>1 );
  88651. if( pSorter->bUseThreads ){
  88652. int iTask;
  88653. PmaReader *pReadr = 0;
  88654. SortSubtask *pLast = &pSorter->aTask[pSorter->nTask-1];
  88655. rc = vdbeSortAllocUnpacked(pLast);
  88656. if( rc==SQLITE_OK ){
  88657. pReadr = (PmaReader*)sqlite3DbMallocZero(db, sizeof(PmaReader));
  88658. pSorter->pReader = pReadr;
  88659. if( pReadr==0 ) rc = SQLITE_NOMEM_BKPT;
  88660. }
  88661. if( rc==SQLITE_OK ){
  88662. rc = vdbeIncrMergerNew(pLast, pMain, &pReadr->pIncr);
  88663. if( rc==SQLITE_OK ){
  88664. vdbeIncrMergerSetThreads(pReadr->pIncr);
  88665. for(iTask=0; iTask<(pSorter->nTask-1); iTask++){
  88666. IncrMerger *pIncr;
  88667. if( (pIncr = pMain->aReadr[iTask].pIncr) ){
  88668. vdbeIncrMergerSetThreads(pIncr);
  88669. assert( pIncr->pTask!=pLast );
  88670. }
  88671. }
  88672. for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
  88673. /* Check that:
  88674. **
  88675. ** a) The incremental merge object is configured to use the
  88676. ** right task, and
  88677. ** b) If it is using task (nTask-1), it is configured to run
  88678. ** in single-threaded mode. This is important, as the
  88679. ** root merge (INCRINIT_ROOT) will be using the same task
  88680. ** object.
  88681. */
  88682. PmaReader *p = &pMain->aReadr[iTask];
  88683. assert( p->pIncr==0 || (
  88684. (p->pIncr->pTask==&pSorter->aTask[iTask]) /* a */
  88685. && (iTask!=pSorter->nTask-1 || p->pIncr->bUseThread==0) /* b */
  88686. ));
  88687. rc = vdbePmaReaderIncrInit(p, INCRINIT_TASK);
  88688. }
  88689. }
  88690. pMain = 0;
  88691. }
  88692. if( rc==SQLITE_OK ){
  88693. rc = vdbePmaReaderIncrMergeInit(pReadr, INCRINIT_ROOT);
  88694. }
  88695. }else
  88696. #endif
  88697. {
  88698. rc = vdbeMergeEngineInit(pTask0, pMain, INCRINIT_NORMAL);
  88699. pSorter->pMerger = pMain;
  88700. pMain = 0;
  88701. }
  88702. }
  88703. if( rc!=SQLITE_OK ){
  88704. vdbeMergeEngineFree(pMain);
  88705. }
  88706. return rc;
  88707. }
  88708. /*
  88709. ** Once the sorter has been populated by calls to sqlite3VdbeSorterWrite,
  88710. ** this function is called to prepare for iterating through the records
  88711. ** in sorted order.
  88712. */
  88713. SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *pCsr, int *pbEof){
  88714. VdbeSorter *pSorter;
  88715. int rc = SQLITE_OK; /* Return code */
  88716. assert( pCsr->eCurType==CURTYPE_SORTER );
  88717. pSorter = pCsr->uc.pSorter;
  88718. assert( pSorter );
  88719. /* If no data has been written to disk, then do not do so now. Instead,
  88720. ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
  88721. ** from the in-memory list. */
  88722. if( pSorter->bUsePMA==0 ){
  88723. if( pSorter->list.pList ){
  88724. *pbEof = 0;
  88725. rc = vdbeSorterSort(&pSorter->aTask[0], &pSorter->list);
  88726. }else{
  88727. *pbEof = 1;
  88728. }
  88729. return rc;
  88730. }
  88731. /* Write the current in-memory list to a PMA. When the VdbeSorterWrite()
  88732. ** function flushes the contents of memory to disk, it immediately always
  88733. ** creates a new list consisting of a single key immediately afterwards.
  88734. ** So the list is never empty at this point. */
  88735. assert( pSorter->list.pList );
  88736. rc = vdbeSorterFlushPMA(pSorter);
  88737. /* Join all threads */
  88738. rc = vdbeSorterJoinAll(pSorter, rc);
  88739. vdbeSorterRewindDebug("rewind");
  88740. /* Assuming no errors have occurred, set up a merger structure to
  88741. ** incrementally read and merge all remaining PMAs. */
  88742. assert( pSorter->pReader==0 );
  88743. if( rc==SQLITE_OK ){
  88744. rc = vdbeSorterSetupMerge(pSorter);
  88745. *pbEof = 0;
  88746. }
  88747. vdbeSorterRewindDebug("rewinddone");
  88748. return rc;
  88749. }
  88750. /*
  88751. ** Advance to the next element in the sorter. Return value:
  88752. **
  88753. ** SQLITE_OK success
  88754. ** SQLITE_DONE end of data
  88755. ** otherwise some kind of error.
  88756. */
  88757. SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr){
  88758. VdbeSorter *pSorter;
  88759. int rc; /* Return code */
  88760. assert( pCsr->eCurType==CURTYPE_SORTER );
  88761. pSorter = pCsr->uc.pSorter;
  88762. assert( pSorter->bUsePMA || (pSorter->pReader==0 && pSorter->pMerger==0) );
  88763. if( pSorter->bUsePMA ){
  88764. assert( pSorter->pReader==0 || pSorter->pMerger==0 );
  88765. assert( pSorter->bUseThreads==0 || pSorter->pReader );
  88766. assert( pSorter->bUseThreads==1 || pSorter->pMerger );
  88767. #if SQLITE_MAX_WORKER_THREADS>0
  88768. if( pSorter->bUseThreads ){
  88769. rc = vdbePmaReaderNext(pSorter->pReader);
  88770. if( rc==SQLITE_OK && pSorter->pReader->pFd==0 ) rc = SQLITE_DONE;
  88771. }else
  88772. #endif
  88773. /*if( !pSorter->bUseThreads )*/ {
  88774. int res = 0;
  88775. assert( pSorter->pMerger!=0 );
  88776. assert( pSorter->pMerger->pTask==(&pSorter->aTask[0]) );
  88777. rc = vdbeMergeEngineStep(pSorter->pMerger, &res);
  88778. if( rc==SQLITE_OK && res ) rc = SQLITE_DONE;
  88779. }
  88780. }else{
  88781. SorterRecord *pFree = pSorter->list.pList;
  88782. pSorter->list.pList = pFree->u.pNext;
  88783. pFree->u.pNext = 0;
  88784. if( pSorter->list.aMemory==0 ) vdbeSorterRecordFree(db, pFree);
  88785. rc = pSorter->list.pList ? SQLITE_OK : SQLITE_DONE;
  88786. }
  88787. return rc;
  88788. }
  88789. /*
  88790. ** Return a pointer to a buffer owned by the sorter that contains the
  88791. ** current key.
  88792. */
  88793. static void *vdbeSorterRowkey(
  88794. const VdbeSorter *pSorter, /* Sorter object */
  88795. int *pnKey /* OUT: Size of current key in bytes */
  88796. ){
  88797. void *pKey;
  88798. if( pSorter->bUsePMA ){
  88799. PmaReader *pReader;
  88800. #if SQLITE_MAX_WORKER_THREADS>0
  88801. if( pSorter->bUseThreads ){
  88802. pReader = pSorter->pReader;
  88803. }else
  88804. #endif
  88805. /*if( !pSorter->bUseThreads )*/{
  88806. pReader = &pSorter->pMerger->aReadr[pSorter->pMerger->aTree[1]];
  88807. }
  88808. *pnKey = pReader->nKey;
  88809. pKey = pReader->aKey;
  88810. }else{
  88811. *pnKey = pSorter->list.pList->nVal;
  88812. pKey = SRVAL(pSorter->list.pList);
  88813. }
  88814. return pKey;
  88815. }
  88816. /*
  88817. ** Copy the current sorter key into the memory cell pOut.
  88818. */
  88819. SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){
  88820. VdbeSorter *pSorter;
  88821. void *pKey; int nKey; /* Sorter key to copy into pOut */
  88822. assert( pCsr->eCurType==CURTYPE_SORTER );
  88823. pSorter = pCsr->uc.pSorter;
  88824. pKey = vdbeSorterRowkey(pSorter, &nKey);
  88825. if( sqlite3VdbeMemClearAndResize(pOut, nKey) ){
  88826. return SQLITE_NOMEM_BKPT;
  88827. }
  88828. pOut->n = nKey;
  88829. MemSetTypeFlag(pOut, MEM_Blob);
  88830. memcpy(pOut->z, pKey, nKey);
  88831. return SQLITE_OK;
  88832. }
  88833. /*
  88834. ** Compare the key in memory cell pVal with the key that the sorter cursor
  88835. ** passed as the first argument currently points to. For the purposes of
  88836. ** the comparison, ignore the rowid field at the end of each record.
  88837. **
  88838. ** If the sorter cursor key contains any NULL values, consider it to be
  88839. ** less than pVal. Even if pVal also contains NULL values.
  88840. **
  88841. ** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
  88842. ** Otherwise, set *pRes to a negative, zero or positive value if the
  88843. ** key in pVal is smaller than, equal to or larger than the current sorter
  88844. ** key.
  88845. **
  88846. ** This routine forms the core of the OP_SorterCompare opcode, which in
  88847. ** turn is used to verify uniqueness when constructing a UNIQUE INDEX.
  88848. */
  88849. SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
  88850. const VdbeCursor *pCsr, /* Sorter cursor */
  88851. Mem *pVal, /* Value to compare to current sorter key */
  88852. int nKeyCol, /* Compare this many columns */
  88853. int *pRes /* OUT: Result of comparison */
  88854. ){
  88855. VdbeSorter *pSorter;
  88856. UnpackedRecord *r2;
  88857. KeyInfo *pKeyInfo;
  88858. int i;
  88859. void *pKey; int nKey; /* Sorter key to compare pVal with */
  88860. assert( pCsr->eCurType==CURTYPE_SORTER );
  88861. pSorter = pCsr->uc.pSorter;
  88862. r2 = pSorter->pUnpacked;
  88863. pKeyInfo = pCsr->pKeyInfo;
  88864. if( r2==0 ){
  88865. r2 = pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);
  88866. if( r2==0 ) return SQLITE_NOMEM_BKPT;
  88867. r2->nField = nKeyCol;
  88868. }
  88869. assert( r2->nField==nKeyCol );
  88870. pKey = vdbeSorterRowkey(pSorter, &nKey);
  88871. sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, r2);
  88872. for(i=0; i<nKeyCol; i++){
  88873. if( r2->aMem[i].flags & MEM_Null ){
  88874. *pRes = -1;
  88875. return SQLITE_OK;
  88876. }
  88877. }
  88878. *pRes = sqlite3VdbeRecordCompare(pVal->n, pVal->z, r2);
  88879. return SQLITE_OK;
  88880. }
  88881. /************** End of vdbesort.c ********************************************/
  88882. /************** Begin file memjournal.c **************************************/
  88883. /*
  88884. ** 2008 October 7
  88885. **
  88886. ** The author disclaims copyright to this source code. In place of
  88887. ** a legal notice, here is a blessing:
  88888. **
  88889. ** May you do good and not evil.
  88890. ** May you find forgiveness for yourself and forgive others.
  88891. ** May you share freely, never taking more than you give.
  88892. **
  88893. *************************************************************************
  88894. **
  88895. ** This file contains code use to implement an in-memory rollback journal.
  88896. ** The in-memory rollback journal is used to journal transactions for
  88897. ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
  88898. **
  88899. ** Update: The in-memory journal is also used to temporarily cache
  88900. ** smaller journals that are not critical for power-loss recovery.
  88901. ** For example, statement journals that are not too big will be held
  88902. ** entirely in memory, thus reducing the number of file I/O calls, and
  88903. ** more importantly, reducing temporary file creation events. If these
  88904. ** journals become too large for memory, they are spilled to disk. But
  88905. ** in the common case, they are usually small and no file I/O needs to
  88906. ** occur.
  88907. */
  88908. /* #include "sqliteInt.h" */
  88909. /* Forward references to internal structures */
  88910. typedef struct MemJournal MemJournal;
  88911. typedef struct FilePoint FilePoint;
  88912. typedef struct FileChunk FileChunk;
  88913. /*
  88914. ** The rollback journal is composed of a linked list of these structures.
  88915. **
  88916. ** The zChunk array is always at least 8 bytes in size - usually much more.
  88917. ** Its actual size is stored in the MemJournal.nChunkSize variable.
  88918. */
  88919. struct FileChunk {
  88920. FileChunk *pNext; /* Next chunk in the journal */
  88921. u8 zChunk[8]; /* Content of this chunk */
  88922. };
  88923. /*
  88924. ** By default, allocate this many bytes of memory for each FileChunk object.
  88925. */
  88926. #define MEMJOURNAL_DFLT_FILECHUNKSIZE 1024
  88927. /*
  88928. ** For chunk size nChunkSize, return the number of bytes that should
  88929. ** be allocated for each FileChunk structure.
  88930. */
  88931. #define fileChunkSize(nChunkSize) (sizeof(FileChunk) + ((nChunkSize)-8))
  88932. /*
  88933. ** An instance of this object serves as a cursor into the rollback journal.
  88934. ** The cursor can be either for reading or writing.
  88935. */
  88936. struct FilePoint {
  88937. sqlite3_int64 iOffset; /* Offset from the beginning of the file */
  88938. FileChunk *pChunk; /* Specific chunk into which cursor points */
  88939. };
  88940. /*
  88941. ** This structure is a subclass of sqlite3_file. Each open memory-journal
  88942. ** is an instance of this class.
  88943. */
  88944. struct MemJournal {
  88945. const sqlite3_io_methods *pMethod; /* Parent class. MUST BE FIRST */
  88946. int nChunkSize; /* In-memory chunk-size */
  88947. int nSpill; /* Bytes of data before flushing */
  88948. int nSize; /* Bytes of data currently in memory */
  88949. FileChunk *pFirst; /* Head of in-memory chunk-list */
  88950. FilePoint endpoint; /* Pointer to the end of the file */
  88951. FilePoint readpoint; /* Pointer to the end of the last xRead() */
  88952. int flags; /* xOpen flags */
  88953. sqlite3_vfs *pVfs; /* The "real" underlying VFS */
  88954. const char *zJournal; /* Name of the journal file */
  88955. };
  88956. /*
  88957. ** Read data from the in-memory journal file. This is the implementation
  88958. ** of the sqlite3_vfs.xRead method.
  88959. */
  88960. static int memjrnlRead(
  88961. sqlite3_file *pJfd, /* The journal file from which to read */
  88962. void *zBuf, /* Put the results here */
  88963. int iAmt, /* Number of bytes to read */
  88964. sqlite_int64 iOfst /* Begin reading at this offset */
  88965. ){
  88966. MemJournal *p = (MemJournal *)pJfd;
  88967. u8 *zOut = zBuf;
  88968. int nRead = iAmt;
  88969. int iChunkOffset;
  88970. FileChunk *pChunk;
  88971. #if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
  88972. || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
  88973. if( (iAmt+iOfst)>p->endpoint.iOffset ){
  88974. return SQLITE_IOERR_SHORT_READ;
  88975. }
  88976. #endif
  88977. assert( (iAmt+iOfst)<=p->endpoint.iOffset );
  88978. assert( p->readpoint.iOffset==0 || p->readpoint.pChunk!=0 );
  88979. if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
  88980. sqlite3_int64 iOff = 0;
  88981. for(pChunk=p->pFirst;
  88982. ALWAYS(pChunk) && (iOff+p->nChunkSize)<=iOfst;
  88983. pChunk=pChunk->pNext
  88984. ){
  88985. iOff += p->nChunkSize;
  88986. }
  88987. }else{
  88988. pChunk = p->readpoint.pChunk;
  88989. assert( pChunk!=0 );
  88990. }
  88991. iChunkOffset = (int)(iOfst%p->nChunkSize);
  88992. do {
  88993. int iSpace = p->nChunkSize - iChunkOffset;
  88994. int nCopy = MIN(nRead, (p->nChunkSize - iChunkOffset));
  88995. memcpy(zOut, (u8*)pChunk->zChunk + iChunkOffset, nCopy);
  88996. zOut += nCopy;
  88997. nRead -= iSpace;
  88998. iChunkOffset = 0;
  88999. } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
  89000. p->readpoint.iOffset = pChunk ? iOfst+iAmt : 0;
  89001. p->readpoint.pChunk = pChunk;
  89002. return SQLITE_OK;
  89003. }
  89004. /*
  89005. ** Free the list of FileChunk structures headed at MemJournal.pFirst.
  89006. */
  89007. static void memjrnlFreeChunks(MemJournal *p){
  89008. FileChunk *pIter;
  89009. FileChunk *pNext;
  89010. for(pIter=p->pFirst; pIter; pIter=pNext){
  89011. pNext = pIter->pNext;
  89012. sqlite3_free(pIter);
  89013. }
  89014. p->pFirst = 0;
  89015. }
  89016. /*
  89017. ** Flush the contents of memory to a real file on disk.
  89018. */
  89019. static int memjrnlCreateFile(MemJournal *p){
  89020. int rc;
  89021. sqlite3_file *pReal = (sqlite3_file*)p;
  89022. MemJournal copy = *p;
  89023. memset(p, 0, sizeof(MemJournal));
  89024. rc = sqlite3OsOpen(copy.pVfs, copy.zJournal, pReal, copy.flags, 0);
  89025. if( rc==SQLITE_OK ){
  89026. int nChunk = copy.nChunkSize;
  89027. i64 iOff = 0;
  89028. FileChunk *pIter;
  89029. for(pIter=copy.pFirst; pIter; pIter=pIter->pNext){
  89030. if( iOff + nChunk > copy.endpoint.iOffset ){
  89031. nChunk = copy.endpoint.iOffset - iOff;
  89032. }
  89033. rc = sqlite3OsWrite(pReal, (u8*)pIter->zChunk, nChunk, iOff);
  89034. if( rc ) break;
  89035. iOff += nChunk;
  89036. }
  89037. if( rc==SQLITE_OK ){
  89038. /* No error has occurred. Free the in-memory buffers. */
  89039. memjrnlFreeChunks(&copy);
  89040. }
  89041. }
  89042. if( rc!=SQLITE_OK ){
  89043. /* If an error occurred while creating or writing to the file, restore
  89044. ** the original before returning. This way, SQLite uses the in-memory
  89045. ** journal data to roll back changes made to the internal page-cache
  89046. ** before this function was called. */
  89047. sqlite3OsClose(pReal);
  89048. *p = copy;
  89049. }
  89050. return rc;
  89051. }
  89052. /*
  89053. ** Write data to the file.
  89054. */
  89055. static int memjrnlWrite(
  89056. sqlite3_file *pJfd, /* The journal file into which to write */
  89057. const void *zBuf, /* Take data to be written from here */
  89058. int iAmt, /* Number of bytes to write */
  89059. sqlite_int64 iOfst /* Begin writing at this offset into the file */
  89060. ){
  89061. MemJournal *p = (MemJournal *)pJfd;
  89062. int nWrite = iAmt;
  89063. u8 *zWrite = (u8 *)zBuf;
  89064. /* If the file should be created now, create it and write the new data
  89065. ** into the file on disk. */
  89066. if( p->nSpill>0 && (iAmt+iOfst)>p->nSpill ){
  89067. int rc = memjrnlCreateFile(p);
  89068. if( rc==SQLITE_OK ){
  89069. rc = sqlite3OsWrite(pJfd, zBuf, iAmt, iOfst);
  89070. }
  89071. return rc;
  89072. }
  89073. /* If the contents of this write should be stored in memory */
  89074. else{
  89075. /* An in-memory journal file should only ever be appended to. Random
  89076. ** access writes are not required. The only exception to this is when
  89077. ** the in-memory journal is being used by a connection using the
  89078. ** atomic-write optimization. In this case the first 28 bytes of the
  89079. ** journal file may be written as part of committing the transaction. */
  89080. assert( iOfst==p->endpoint.iOffset || iOfst==0 );
  89081. #if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
  89082. || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
  89083. if( iOfst==0 && p->pFirst ){
  89084. assert( p->nChunkSize>iAmt );
  89085. memcpy((u8*)p->pFirst->zChunk, zBuf, iAmt);
  89086. }else
  89087. #else
  89088. assert( iOfst>0 || p->pFirst==0 );
  89089. #endif
  89090. {
  89091. while( nWrite>0 ){
  89092. FileChunk *pChunk = p->endpoint.pChunk;
  89093. int iChunkOffset = (int)(p->endpoint.iOffset%p->nChunkSize);
  89094. int iSpace = MIN(nWrite, p->nChunkSize - iChunkOffset);
  89095. if( iChunkOffset==0 ){
  89096. /* New chunk is required to extend the file. */
  89097. FileChunk *pNew = sqlite3_malloc(fileChunkSize(p->nChunkSize));
  89098. if( !pNew ){
  89099. return SQLITE_IOERR_NOMEM_BKPT;
  89100. }
  89101. pNew->pNext = 0;
  89102. if( pChunk ){
  89103. assert( p->pFirst );
  89104. pChunk->pNext = pNew;
  89105. }else{
  89106. assert( !p->pFirst );
  89107. p->pFirst = pNew;
  89108. }
  89109. p->endpoint.pChunk = pNew;
  89110. }
  89111. memcpy((u8*)p->endpoint.pChunk->zChunk + iChunkOffset, zWrite, iSpace);
  89112. zWrite += iSpace;
  89113. nWrite -= iSpace;
  89114. p->endpoint.iOffset += iSpace;
  89115. }
  89116. p->nSize = iAmt + iOfst;
  89117. }
  89118. }
  89119. return SQLITE_OK;
  89120. }
  89121. /*
  89122. ** Truncate the file.
  89123. **
  89124. ** If the journal file is already on disk, truncate it there. Or, if it
  89125. ** is still in main memory but is being truncated to zero bytes in size,
  89126. ** ignore
  89127. */
  89128. static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
  89129. MemJournal *p = (MemJournal *)pJfd;
  89130. if( ALWAYS(size==0) ){
  89131. memjrnlFreeChunks(p);
  89132. p->nSize = 0;
  89133. p->endpoint.pChunk = 0;
  89134. p->endpoint.iOffset = 0;
  89135. p->readpoint.pChunk = 0;
  89136. p->readpoint.iOffset = 0;
  89137. }
  89138. return SQLITE_OK;
  89139. }
  89140. /*
  89141. ** Close the file.
  89142. */
  89143. static int memjrnlClose(sqlite3_file *pJfd){
  89144. MemJournal *p = (MemJournal *)pJfd;
  89145. memjrnlFreeChunks(p);
  89146. return SQLITE_OK;
  89147. }
  89148. /*
  89149. ** Sync the file.
  89150. **
  89151. ** If the real file has been created, call its xSync method. Otherwise,
  89152. ** syncing an in-memory journal is a no-op.
  89153. */
  89154. static int memjrnlSync(sqlite3_file *pJfd, int flags){
  89155. UNUSED_PARAMETER2(pJfd, flags);
  89156. return SQLITE_OK;
  89157. }
  89158. /*
  89159. ** Query the size of the file in bytes.
  89160. */
  89161. static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
  89162. MemJournal *p = (MemJournal *)pJfd;
  89163. *pSize = (sqlite_int64) p->endpoint.iOffset;
  89164. return SQLITE_OK;
  89165. }
  89166. /*
  89167. ** Table of methods for MemJournal sqlite3_file object.
  89168. */
  89169. static const struct sqlite3_io_methods MemJournalMethods = {
  89170. 1, /* iVersion */
  89171. memjrnlClose, /* xClose */
  89172. memjrnlRead, /* xRead */
  89173. memjrnlWrite, /* xWrite */
  89174. memjrnlTruncate, /* xTruncate */
  89175. memjrnlSync, /* xSync */
  89176. memjrnlFileSize, /* xFileSize */
  89177. 0, /* xLock */
  89178. 0, /* xUnlock */
  89179. 0, /* xCheckReservedLock */
  89180. 0, /* xFileControl */
  89181. 0, /* xSectorSize */
  89182. 0, /* xDeviceCharacteristics */
  89183. 0, /* xShmMap */
  89184. 0, /* xShmLock */
  89185. 0, /* xShmBarrier */
  89186. 0, /* xShmUnmap */
  89187. 0, /* xFetch */
  89188. 0 /* xUnfetch */
  89189. };
  89190. /*
  89191. ** Open a journal file.
  89192. **
  89193. ** The behaviour of the journal file depends on the value of parameter
  89194. ** nSpill. If nSpill is 0, then the journal file is always create and
  89195. ** accessed using the underlying VFS. If nSpill is less than zero, then
  89196. ** all content is always stored in main-memory. Finally, if nSpill is a
  89197. ** positive value, then the journal file is initially created in-memory
  89198. ** but may be flushed to disk later on. In this case the journal file is
  89199. ** flushed to disk either when it grows larger than nSpill bytes in size,
  89200. ** or when sqlite3JournalCreate() is called.
  89201. */
  89202. SQLITE_PRIVATE int sqlite3JournalOpen(
  89203. sqlite3_vfs *pVfs, /* The VFS to use for actual file I/O */
  89204. const char *zName, /* Name of the journal file */
  89205. sqlite3_file *pJfd, /* Preallocated, blank file handle */
  89206. int flags, /* Opening flags */
  89207. int nSpill /* Bytes buffered before opening the file */
  89208. ){
  89209. MemJournal *p = (MemJournal*)pJfd;
  89210. /* Zero the file-handle object. If nSpill was passed zero, initialize
  89211. ** it using the sqlite3OsOpen() function of the underlying VFS. In this
  89212. ** case none of the code in this module is executed as a result of calls
  89213. ** made on the journal file-handle. */
  89214. memset(p, 0, sizeof(MemJournal));
  89215. if( nSpill==0 ){
  89216. return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
  89217. }
  89218. if( nSpill>0 ){
  89219. p->nChunkSize = nSpill;
  89220. }else{
  89221. p->nChunkSize = 8 + MEMJOURNAL_DFLT_FILECHUNKSIZE - sizeof(FileChunk);
  89222. assert( MEMJOURNAL_DFLT_FILECHUNKSIZE==fileChunkSize(p->nChunkSize) );
  89223. }
  89224. p->pMethod = (const sqlite3_io_methods*)&MemJournalMethods;
  89225. p->nSpill = nSpill;
  89226. p->flags = flags;
  89227. p->zJournal = zName;
  89228. p->pVfs = pVfs;
  89229. return SQLITE_OK;
  89230. }
  89231. /*
  89232. ** Open an in-memory journal file.
  89233. */
  89234. SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
  89235. sqlite3JournalOpen(0, 0, pJfd, 0, -1);
  89236. }
  89237. #if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
  89238. || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
  89239. /*
  89240. ** If the argument p points to a MemJournal structure that is not an
  89241. ** in-memory-only journal file (i.e. is one that was opened with a +ve
  89242. ** nSpill parameter or as SQLITE_OPEN_MAIN_JOURNAL), and the underlying
  89243. ** file has not yet been created, create it now.
  89244. */
  89245. SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *pJfd){
  89246. int rc = SQLITE_OK;
  89247. MemJournal *p = (MemJournal*)pJfd;
  89248. if( p->pMethod==&MemJournalMethods && (
  89249. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  89250. p->nSpill>0
  89251. #else
  89252. /* While this appears to not be possible without ATOMIC_WRITE, the
  89253. ** paths are complex, so it seems prudent to leave the test in as
  89254. ** a NEVER(), in case our analysis is subtly flawed. */
  89255. NEVER(p->nSpill>0)
  89256. #endif
  89257. #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
  89258. || (p->flags & SQLITE_OPEN_MAIN_JOURNAL)
  89259. #endif
  89260. )){
  89261. rc = memjrnlCreateFile(p);
  89262. }
  89263. return rc;
  89264. }
  89265. #endif
  89266. /*
  89267. ** The file-handle passed as the only argument is open on a journal file.
  89268. ** Return true if this "journal file" is currently stored in heap memory,
  89269. ** or false otherwise.
  89270. */
  89271. SQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p){
  89272. return p->pMethods==&MemJournalMethods;
  89273. }
  89274. /*
  89275. ** Return the number of bytes required to store a JournalFile that uses vfs
  89276. ** pVfs to create the underlying on-disk files.
  89277. */
  89278. SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
  89279. return MAX(pVfs->szOsFile, (int)sizeof(MemJournal));
  89280. }
  89281. /************** End of memjournal.c ******************************************/
  89282. /************** Begin file walker.c ******************************************/
  89283. /*
  89284. ** 2008 August 16
  89285. **
  89286. ** The author disclaims copyright to this source code. In place of
  89287. ** a legal notice, here is a blessing:
  89288. **
  89289. ** May you do good and not evil.
  89290. ** May you find forgiveness for yourself and forgive others.
  89291. ** May you share freely, never taking more than you give.
  89292. **
  89293. *************************************************************************
  89294. ** This file contains routines used for walking the parser tree for
  89295. ** an SQL statement.
  89296. */
  89297. /* #include "sqliteInt.h" */
  89298. /* #include <stdlib.h> */
  89299. /* #include <string.h> */
  89300. #if !defined(SQLITE_OMIT_WINDOWFUNC)
  89301. /*
  89302. ** Walk all expressions linked into the list of Window objects passed
  89303. ** as the second argument.
  89304. */
  89305. static int walkWindowList(Walker *pWalker, Window *pList){
  89306. Window *pWin;
  89307. for(pWin=pList; pWin; pWin=pWin->pNextWin){
  89308. if( sqlite3WalkExprList(pWalker, pWin->pOrderBy) ) return WRC_Abort;
  89309. if( sqlite3WalkExprList(pWalker, pWin->pPartition) ) return WRC_Abort;
  89310. if( sqlite3WalkExpr(pWalker, pWin->pFilter) ) return WRC_Abort;
  89311. }
  89312. return WRC_Continue;
  89313. }
  89314. #endif
  89315. /*
  89316. ** Walk an expression tree. Invoke the callback once for each node
  89317. ** of the expression, while descending. (In other words, the callback
  89318. ** is invoked before visiting children.)
  89319. **
  89320. ** The return value from the callback should be one of the WRC_*
  89321. ** constants to specify how to proceed with the walk.
  89322. **
  89323. ** WRC_Continue Continue descending down the tree.
  89324. **
  89325. ** WRC_Prune Do not descend into child nodes, but allow
  89326. ** the walk to continue with sibling nodes.
  89327. **
  89328. ** WRC_Abort Do no more callbacks. Unwind the stack and
  89329. ** return from the top-level walk call.
  89330. **
  89331. ** The return value from this routine is WRC_Abort to abandon the tree walk
  89332. ** and WRC_Continue to continue.
  89333. */
  89334. static SQLITE_NOINLINE int walkExpr(Walker *pWalker, Expr *pExpr){
  89335. int rc;
  89336. testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
  89337. testcase( ExprHasProperty(pExpr, EP_Reduced) );
  89338. while(1){
  89339. rc = pWalker->xExprCallback(pWalker, pExpr);
  89340. if( rc ) return rc & WRC_Abort;
  89341. if( !ExprHasProperty(pExpr,(EP_TokenOnly|EP_Leaf)) ){
  89342. if( pExpr->pLeft && walkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
  89343. assert( pExpr->x.pList==0 || pExpr->pRight==0 );
  89344. if( pExpr->pRight ){
  89345. pExpr = pExpr->pRight;
  89346. continue;
  89347. }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  89348. if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
  89349. }else if( pExpr->x.pList ){
  89350. if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
  89351. }
  89352. #ifndef SQLITE_OMIT_WINDOWFUNC
  89353. if( ExprHasProperty(pExpr, EP_WinFunc) ){
  89354. if( walkWindowList(pWalker, pExpr->y.pWin) ) return WRC_Abort;
  89355. }
  89356. #endif
  89357. }
  89358. break;
  89359. }
  89360. return WRC_Continue;
  89361. }
  89362. SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
  89363. return pExpr ? walkExpr(pWalker,pExpr) : WRC_Continue;
  89364. }
  89365. /*
  89366. ** Call sqlite3WalkExpr() for every expression in list p or until
  89367. ** an abort request is seen.
  89368. */
  89369. SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
  89370. int i;
  89371. struct ExprList_item *pItem;
  89372. if( p ){
  89373. for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
  89374. if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
  89375. }
  89376. }
  89377. return WRC_Continue;
  89378. }
  89379. /*
  89380. ** Walk all expressions associated with SELECT statement p. Do
  89381. ** not invoke the SELECT callback on p, but do (of course) invoke
  89382. ** any expr callbacks and SELECT callbacks that come from subqueries.
  89383. ** Return WRC_Abort or WRC_Continue.
  89384. */
  89385. SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
  89386. if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
  89387. if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
  89388. if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
  89389. if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
  89390. if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
  89391. if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
  89392. #if !defined(SQLITE_OMIT_WINDOWFUNC) && !defined(SQLITE_OMIT_ALTERTABLE)
  89393. {
  89394. Parse *pParse = pWalker->pParse;
  89395. if( pParse && IN_RENAME_OBJECT ){
  89396. int rc = walkWindowList(pWalker, p->pWinDefn);
  89397. assert( rc==WRC_Continue );
  89398. return rc;
  89399. }
  89400. }
  89401. #endif
  89402. return WRC_Continue;
  89403. }
  89404. /*
  89405. ** Walk the parse trees associated with all subqueries in the
  89406. ** FROM clause of SELECT statement p. Do not invoke the select
  89407. ** callback on p, but do invoke it on each FROM clause subquery
  89408. ** and on any subqueries further down in the tree. Return
  89409. ** WRC_Abort or WRC_Continue;
  89410. */
  89411. SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
  89412. SrcList *pSrc;
  89413. int i;
  89414. struct SrcList_item *pItem;
  89415. pSrc = p->pSrc;
  89416. assert( pSrc!=0 );
  89417. for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
  89418. if( pItem->pSelect && sqlite3WalkSelect(pWalker, pItem->pSelect) ){
  89419. return WRC_Abort;
  89420. }
  89421. if( pItem->fg.isTabFunc
  89422. && sqlite3WalkExprList(pWalker, pItem->u1.pFuncArg)
  89423. ){
  89424. return WRC_Abort;
  89425. }
  89426. }
  89427. return WRC_Continue;
  89428. }
  89429. /*
  89430. ** Call sqlite3WalkExpr() for every expression in Select statement p.
  89431. ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
  89432. ** on the compound select chain, p->pPrior.
  89433. **
  89434. ** If it is not NULL, the xSelectCallback() callback is invoked before
  89435. ** the walk of the expressions and FROM clause. The xSelectCallback2()
  89436. ** method is invoked following the walk of the expressions and FROM clause,
  89437. ** but only if both xSelectCallback and xSelectCallback2 are both non-NULL
  89438. ** and if the expressions and FROM clause both return WRC_Continue;
  89439. **
  89440. ** Return WRC_Continue under normal conditions. Return WRC_Abort if
  89441. ** there is an abort request.
  89442. **
  89443. ** If the Walker does not have an xSelectCallback() then this routine
  89444. ** is a no-op returning WRC_Continue.
  89445. */
  89446. SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
  89447. int rc;
  89448. if( p==0 ) return WRC_Continue;
  89449. if( pWalker->xSelectCallback==0 ) return WRC_Continue;
  89450. do{
  89451. rc = pWalker->xSelectCallback(pWalker, p);
  89452. if( rc ) return rc & WRC_Abort;
  89453. if( sqlite3WalkSelectExpr(pWalker, p)
  89454. || sqlite3WalkSelectFrom(pWalker, p)
  89455. ){
  89456. return WRC_Abort;
  89457. }
  89458. if( pWalker->xSelectCallback2 ){
  89459. pWalker->xSelectCallback2(pWalker, p);
  89460. }
  89461. p = p->pPrior;
  89462. }while( p!=0 );
  89463. return WRC_Continue;
  89464. }
  89465. /************** End of walker.c **********************************************/
  89466. /************** Begin file resolve.c *****************************************/
  89467. /*
  89468. ** 2008 August 18
  89469. **
  89470. ** The author disclaims copyright to this source code. In place of
  89471. ** a legal notice, here is a blessing:
  89472. **
  89473. ** May you do good and not evil.
  89474. ** May you find forgiveness for yourself and forgive others.
  89475. ** May you share freely, never taking more than you give.
  89476. **
  89477. *************************************************************************
  89478. **
  89479. ** This file contains routines used for walking the parser tree and
  89480. ** resolve all identifiers by associating them with a particular
  89481. ** table and column.
  89482. */
  89483. /* #include "sqliteInt.h" */
  89484. /*
  89485. ** Walk the expression tree pExpr and increase the aggregate function
  89486. ** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
  89487. ** This needs to occur when copying a TK_AGG_FUNCTION node from an
  89488. ** outer query into an inner subquery.
  89489. **
  89490. ** incrAggFunctionDepth(pExpr,n) is the main routine. incrAggDepth(..)
  89491. ** is a helper function - a callback for the tree walker.
  89492. */
  89493. static int incrAggDepth(Walker *pWalker, Expr *pExpr){
  89494. if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.n;
  89495. return WRC_Continue;
  89496. }
  89497. static void incrAggFunctionDepth(Expr *pExpr, int N){
  89498. if( N>0 ){
  89499. Walker w;
  89500. memset(&w, 0, sizeof(w));
  89501. w.xExprCallback = incrAggDepth;
  89502. w.u.n = N;
  89503. sqlite3WalkExpr(&w, pExpr);
  89504. }
  89505. }
  89506. /*
  89507. ** Turn the pExpr expression into an alias for the iCol-th column of the
  89508. ** result set in pEList.
  89509. **
  89510. ** If the reference is followed by a COLLATE operator, then make sure
  89511. ** the COLLATE operator is preserved. For example:
  89512. **
  89513. ** SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
  89514. **
  89515. ** Should be transformed into:
  89516. **
  89517. ** SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
  89518. **
  89519. ** The nSubquery parameter specifies how many levels of subquery the
  89520. ** alias is removed from the original expression. The usual value is
  89521. ** zero but it might be more if the alias is contained within a subquery
  89522. ** of the original expression. The Expr.op2 field of TK_AGG_FUNCTION
  89523. ** structures must be increased by the nSubquery amount.
  89524. */
  89525. static void resolveAlias(
  89526. Parse *pParse, /* Parsing context */
  89527. ExprList *pEList, /* A result set */
  89528. int iCol, /* A column in the result set. 0..pEList->nExpr-1 */
  89529. Expr *pExpr, /* Transform this into an alias to the result set */
  89530. const char *zType, /* "GROUP" or "ORDER" or "" */
  89531. int nSubquery /* Number of subqueries that the label is moving */
  89532. ){
  89533. Expr *pOrig; /* The iCol-th column of the result set */
  89534. Expr *pDup; /* Copy of pOrig */
  89535. sqlite3 *db; /* The database connection */
  89536. assert( iCol>=0 && iCol<pEList->nExpr );
  89537. pOrig = pEList->a[iCol].pExpr;
  89538. assert( pOrig!=0 );
  89539. db = pParse->db;
  89540. pDup = sqlite3ExprDup(db, pOrig, 0);
  89541. if( pDup!=0 ){
  89542. if( zType[0]!='G' ) incrAggFunctionDepth(pDup, nSubquery);
  89543. if( pExpr->op==TK_COLLATE ){
  89544. pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
  89545. }
  89546. /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
  89547. ** prevents ExprDelete() from deleting the Expr structure itself,
  89548. ** allowing it to be repopulated by the memcpy() on the following line.
  89549. ** The pExpr->u.zToken might point into memory that will be freed by the
  89550. ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
  89551. ** make a copy of the token before doing the sqlite3DbFree().
  89552. */
  89553. ExprSetProperty(pExpr, EP_Static);
  89554. sqlite3ExprDelete(db, pExpr);
  89555. memcpy(pExpr, pDup, sizeof(*pExpr));
  89556. if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
  89557. assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
  89558. pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
  89559. pExpr->flags |= EP_MemToken;
  89560. }
  89561. sqlite3DbFree(db, pDup);
  89562. }
  89563. ExprSetProperty(pExpr, EP_Alias);
  89564. }
  89565. /*
  89566. ** Return TRUE if the name zCol occurs anywhere in the USING clause.
  89567. **
  89568. ** Return FALSE if the USING clause is NULL or if it does not contain
  89569. ** zCol.
  89570. */
  89571. static int nameInUsingClause(IdList *pUsing, const char *zCol){
  89572. if( pUsing ){
  89573. int k;
  89574. for(k=0; k<pUsing->nId; k++){
  89575. if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
  89576. }
  89577. }
  89578. return 0;
  89579. }
  89580. /*
  89581. ** Subqueries stores the original database, table and column names for their
  89582. ** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN".
  89583. ** Check to see if the zSpan given to this routine matches the zDb, zTab,
  89584. ** and zCol. If any of zDb, zTab, and zCol are NULL then those fields will
  89585. ** match anything.
  89586. */
  89587. SQLITE_PRIVATE int sqlite3MatchSpanName(
  89588. const char *zSpan,
  89589. const char *zCol,
  89590. const char *zTab,
  89591. const char *zDb
  89592. ){
  89593. int n;
  89594. for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
  89595. if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
  89596. return 0;
  89597. }
  89598. zSpan += n+1;
  89599. for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
  89600. if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){
  89601. return 0;
  89602. }
  89603. zSpan += n+1;
  89604. if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){
  89605. return 0;
  89606. }
  89607. return 1;
  89608. }
  89609. /*
  89610. ** Return TRUE if the double-quoted string mis-feature should be supported.
  89611. */
  89612. static int areDoubleQuotedStringsEnabled(sqlite3 *db, NameContext *pTopNC){
  89613. if( db->init.busy ) return 1; /* Always support for legacy schemas */
  89614. if( pTopNC->ncFlags & NC_IsDDL ){
  89615. /* Currently parsing a DDL statement */
  89616. if( sqlite3WritableSchema(db) && (db->flags & SQLITE_DqsDML)!=0 ){
  89617. return 1;
  89618. }
  89619. return (db->flags & SQLITE_DqsDDL)!=0;
  89620. }else{
  89621. /* Currently parsing a DML statement */
  89622. return (db->flags & SQLITE_DqsDML)!=0;
  89623. }
  89624. }
  89625. /*
  89626. ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
  89627. ** that name in the set of source tables in pSrcList and make the pExpr
  89628. ** expression node refer back to that source column. The following changes
  89629. ** are made to pExpr:
  89630. **
  89631. ** pExpr->iDb Set the index in db->aDb[] of the database X
  89632. ** (even if X is implied).
  89633. ** pExpr->iTable Set to the cursor number for the table obtained
  89634. ** from pSrcList.
  89635. ** pExpr->y.pTab Points to the Table structure of X.Y (even if
  89636. ** X and/or Y are implied.)
  89637. ** pExpr->iColumn Set to the column number within the table.
  89638. ** pExpr->op Set to TK_COLUMN.
  89639. ** pExpr->pLeft Any expression this points to is deleted
  89640. ** pExpr->pRight Any expression this points to is deleted.
  89641. **
  89642. ** The zDb variable is the name of the database (the "X"). This value may be
  89643. ** NULL meaning that name is of the form Y.Z or Z. Any available database
  89644. ** can be used. The zTable variable is the name of the table (the "Y"). This
  89645. ** value can be NULL if zDb is also NULL. If zTable is NULL it
  89646. ** means that the form of the name is Z and that columns from any table
  89647. ** can be used.
  89648. **
  89649. ** If the name cannot be resolved unambiguously, leave an error message
  89650. ** in pParse and return WRC_Abort. Return WRC_Prune on success.
  89651. */
  89652. static int lookupName(
  89653. Parse *pParse, /* The parsing context */
  89654. const char *zDb, /* Name of the database containing table, or NULL */
  89655. const char *zTab, /* Name of table containing column, or NULL */
  89656. const char *zCol, /* Name of the column. */
  89657. NameContext *pNC, /* The name context used to resolve the name */
  89658. Expr *pExpr /* Make this EXPR node point to the selected column */
  89659. ){
  89660. int i, j; /* Loop counters */
  89661. int cnt = 0; /* Number of matching column names */
  89662. int cntTab = 0; /* Number of matching table names */
  89663. int nSubquery = 0; /* How many levels of subquery */
  89664. sqlite3 *db = pParse->db; /* The database connection */
  89665. struct SrcList_item *pItem; /* Use for looping over pSrcList items */
  89666. struct SrcList_item *pMatch = 0; /* The matching pSrcList item */
  89667. NameContext *pTopNC = pNC; /* First namecontext in the list */
  89668. Schema *pSchema = 0; /* Schema of the expression */
  89669. int eNewExprOp = TK_COLUMN; /* New value for pExpr->op on success */
  89670. Table *pTab = 0; /* Table hold the row */
  89671. Column *pCol; /* A column of pTab */
  89672. assert( pNC ); /* the name context cannot be NULL. */
  89673. assert( zCol ); /* The Z in X.Y.Z cannot be NULL */
  89674. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  89675. /* Initialize the node to no-match */
  89676. pExpr->iTable = -1;
  89677. ExprSetVVAProperty(pExpr, EP_NoReduce);
  89678. /* Translate the schema name in zDb into a pointer to the corresponding
  89679. ** schema. If not found, pSchema will remain NULL and nothing will match
  89680. ** resulting in an appropriate error message toward the end of this routine
  89681. */
  89682. if( zDb ){
  89683. testcase( pNC->ncFlags & NC_PartIdx );
  89684. testcase( pNC->ncFlags & NC_IsCheck );
  89685. if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){
  89686. /* Silently ignore database qualifiers inside CHECK constraints and
  89687. ** partial indices. Do not raise errors because that might break
  89688. ** legacy and because it does not hurt anything to just ignore the
  89689. ** database name. */
  89690. zDb = 0;
  89691. }else{
  89692. for(i=0; i<db->nDb; i++){
  89693. assert( db->aDb[i].zDbSName );
  89694. if( sqlite3StrICmp(db->aDb[i].zDbSName,zDb)==0 ){
  89695. pSchema = db->aDb[i].pSchema;
  89696. break;
  89697. }
  89698. }
  89699. }
  89700. }
  89701. /* Start at the inner-most context and move outward until a match is found */
  89702. assert( pNC && cnt==0 );
  89703. do{
  89704. ExprList *pEList;
  89705. SrcList *pSrcList = pNC->pSrcList;
  89706. if( pSrcList ){
  89707. for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
  89708. pTab = pItem->pTab;
  89709. assert( pTab!=0 && pTab->zName!=0 );
  89710. assert( pTab->nCol>0 );
  89711. if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){
  89712. int hit = 0;
  89713. pEList = pItem->pSelect->pEList;
  89714. for(j=0; j<pEList->nExpr; j++){
  89715. if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){
  89716. cnt++;
  89717. cntTab = 2;
  89718. pMatch = pItem;
  89719. pExpr->iColumn = j;
  89720. hit = 1;
  89721. }
  89722. }
  89723. if( hit || zTab==0 ) continue;
  89724. }
  89725. if( zDb && pTab->pSchema!=pSchema ){
  89726. continue;
  89727. }
  89728. if( zTab ){
  89729. const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;
  89730. assert( zTabName!=0 );
  89731. if( sqlite3StrICmp(zTabName, zTab)!=0 ){
  89732. continue;
  89733. }
  89734. if( IN_RENAME_OBJECT && pItem->zAlias ){
  89735. sqlite3RenameTokenRemap(pParse, 0, (void*)&pExpr->y.pTab);
  89736. }
  89737. }
  89738. if( 0==(cntTab++) ){
  89739. pMatch = pItem;
  89740. }
  89741. for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
  89742. if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
  89743. /* If there has been exactly one prior match and this match
  89744. ** is for the right-hand table of a NATURAL JOIN or is in a
  89745. ** USING clause, then skip this match.
  89746. */
  89747. if( cnt==1 ){
  89748. if( pItem->fg.jointype & JT_NATURAL ) continue;
  89749. if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
  89750. }
  89751. cnt++;
  89752. pMatch = pItem;
  89753. /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
  89754. pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
  89755. break;
  89756. }
  89757. }
  89758. }
  89759. if( pMatch ){
  89760. pExpr->iTable = pMatch->iCursor;
  89761. pExpr->y.pTab = pMatch->pTab;
  89762. /* RIGHT JOIN not (yet) supported */
  89763. assert( (pMatch->fg.jointype & JT_RIGHT)==0 );
  89764. if( (pMatch->fg.jointype & JT_LEFT)!=0 ){
  89765. ExprSetProperty(pExpr, EP_CanBeNull);
  89766. }
  89767. pSchema = pExpr->y.pTab->pSchema;
  89768. }
  89769. } /* if( pSrcList ) */
  89770. #if !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT)
  89771. /* If we have not already resolved the name, then maybe
  89772. ** it is a new.* or old.* trigger argument reference. Or
  89773. ** maybe it is an excluded.* from an upsert.
  89774. */
  89775. if( zDb==0 && zTab!=0 && cntTab==0 ){
  89776. pTab = 0;
  89777. #ifndef SQLITE_OMIT_TRIGGER
  89778. if( pParse->pTriggerTab!=0 ){
  89779. int op = pParse->eTriggerOp;
  89780. assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
  89781. if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
  89782. pExpr->iTable = 1;
  89783. pTab = pParse->pTriggerTab;
  89784. }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
  89785. pExpr->iTable = 0;
  89786. pTab = pParse->pTriggerTab;
  89787. }
  89788. }
  89789. #endif /* SQLITE_OMIT_TRIGGER */
  89790. #ifndef SQLITE_OMIT_UPSERT
  89791. if( (pNC->ncFlags & NC_UUpsert)!=0 ){
  89792. Upsert *pUpsert = pNC->uNC.pUpsert;
  89793. if( pUpsert && sqlite3StrICmp("excluded",zTab)==0 ){
  89794. pTab = pUpsert->pUpsertSrc->a[0].pTab;
  89795. pExpr->iTable = 2;
  89796. }
  89797. }
  89798. #endif /* SQLITE_OMIT_UPSERT */
  89799. if( pTab ){
  89800. int iCol;
  89801. pSchema = pTab->pSchema;
  89802. cntTab++;
  89803. for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){
  89804. if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
  89805. if( iCol==pTab->iPKey ){
  89806. iCol = -1;
  89807. }
  89808. break;
  89809. }
  89810. }
  89811. if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && VisibleRowid(pTab) ){
  89812. /* IMP: R-51414-32910 */
  89813. iCol = -1;
  89814. }
  89815. if( iCol<pTab->nCol ){
  89816. cnt++;
  89817. #ifndef SQLITE_OMIT_UPSERT
  89818. if( pExpr->iTable==2 ){
  89819. testcase( iCol==(-1) );
  89820. if( IN_RENAME_OBJECT ){
  89821. pExpr->iColumn = iCol;
  89822. pExpr->y.pTab = pTab;
  89823. eNewExprOp = TK_COLUMN;
  89824. }else{
  89825. pExpr->iTable = pNC->uNC.pUpsert->regData + iCol;
  89826. eNewExprOp = TK_REGISTER;
  89827. ExprSetProperty(pExpr, EP_Alias);
  89828. }
  89829. }else
  89830. #endif /* SQLITE_OMIT_UPSERT */
  89831. {
  89832. #ifndef SQLITE_OMIT_TRIGGER
  89833. if( iCol<0 ){
  89834. pExpr->affinity = SQLITE_AFF_INTEGER;
  89835. }else if( pExpr->iTable==0 ){
  89836. testcase( iCol==31 );
  89837. testcase( iCol==32 );
  89838. pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
  89839. }else{
  89840. testcase( iCol==31 );
  89841. testcase( iCol==32 );
  89842. pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
  89843. }
  89844. pExpr->y.pTab = pTab;
  89845. pExpr->iColumn = (i16)iCol;
  89846. eNewExprOp = TK_TRIGGER;
  89847. #endif /* SQLITE_OMIT_TRIGGER */
  89848. }
  89849. }
  89850. }
  89851. }
  89852. #endif /* !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT) */
  89853. /*
  89854. ** Perhaps the name is a reference to the ROWID
  89855. */
  89856. if( cnt==0
  89857. && cntTab==1
  89858. && pMatch
  89859. && (pNC->ncFlags & NC_IdxExpr)==0
  89860. && sqlite3IsRowid(zCol)
  89861. && VisibleRowid(pMatch->pTab)
  89862. ){
  89863. cnt = 1;
  89864. pExpr->iColumn = -1;
  89865. pExpr->affinity = SQLITE_AFF_INTEGER;
  89866. }
  89867. /*
  89868. ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
  89869. ** might refer to an result-set alias. This happens, for example, when
  89870. ** we are resolving names in the WHERE clause of the following command:
  89871. **
  89872. ** SELECT a+b AS x FROM table WHERE x<10;
  89873. **
  89874. ** In cases like this, replace pExpr with a copy of the expression that
  89875. ** forms the result set entry ("a+b" in the example) and return immediately.
  89876. ** Note that the expression in the result set should have already been
  89877. ** resolved by the time the WHERE clause is resolved.
  89878. **
  89879. ** The ability to use an output result-set column in the WHERE, GROUP BY,
  89880. ** or HAVING clauses, or as part of a larger expression in the ORDER BY
  89881. ** clause is not standard SQL. This is a (goofy) SQLite extension, that
  89882. ** is supported for backwards compatibility only. Hence, we issue a warning
  89883. ** on sqlite3_log() whenever the capability is used.
  89884. */
  89885. if( (pNC->ncFlags & NC_UEList)!=0
  89886. && cnt==0
  89887. && zTab==0
  89888. ){
  89889. pEList = pNC->uNC.pEList;
  89890. assert( pEList!=0 );
  89891. for(j=0; j<pEList->nExpr; j++){
  89892. char *zAs = pEList->a[j].zName;
  89893. if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
  89894. Expr *pOrig;
  89895. assert( pExpr->pLeft==0 && pExpr->pRight==0 );
  89896. assert( pExpr->x.pList==0 );
  89897. assert( pExpr->x.pSelect==0 );
  89898. pOrig = pEList->a[j].pExpr;
  89899. if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
  89900. sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
  89901. return WRC_Abort;
  89902. }
  89903. if( (pNC->ncFlags&NC_AllowWin)==0 && ExprHasProperty(pOrig, EP_Win) ){
  89904. sqlite3ErrorMsg(pParse, "misuse of aliased window function %s",zAs);
  89905. return WRC_Abort;
  89906. }
  89907. if( sqlite3ExprVectorSize(pOrig)!=1 ){
  89908. sqlite3ErrorMsg(pParse, "row value misused");
  89909. return WRC_Abort;
  89910. }
  89911. resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
  89912. cnt = 1;
  89913. pMatch = 0;
  89914. assert( zTab==0 && zDb==0 );
  89915. if( IN_RENAME_OBJECT ){
  89916. sqlite3RenameTokenRemap(pParse, 0, (void*)pExpr);
  89917. }
  89918. goto lookupname_end;
  89919. }
  89920. }
  89921. }
  89922. /* Advance to the next name context. The loop will exit when either
  89923. ** we have a match (cnt>0) or when we run out of name contexts.
  89924. */
  89925. if( cnt ) break;
  89926. pNC = pNC->pNext;
  89927. nSubquery++;
  89928. }while( pNC );
  89929. /*
  89930. ** If X and Y are NULL (in other words if only the column name Z is
  89931. ** supplied) and the value of Z is enclosed in double-quotes, then
  89932. ** Z is a string literal if it doesn't match any column names. In that
  89933. ** case, we need to return right away and not make any changes to
  89934. ** pExpr.
  89935. **
  89936. ** Because no reference was made to outer contexts, the pNC->nRef
  89937. ** fields are not changed in any context.
  89938. */
  89939. if( cnt==0 && zTab==0 ){
  89940. assert( pExpr->op==TK_ID );
  89941. if( ExprHasProperty(pExpr,EP_DblQuoted)
  89942. && areDoubleQuotedStringsEnabled(db, pTopNC)
  89943. ){
  89944. /* If a double-quoted identifier does not match any known column name,
  89945. ** then treat it as a string.
  89946. **
  89947. ** This hack was added in the early days of SQLite in a misguided attempt
  89948. ** to be compatible with MySQL 3.x, which used double-quotes for strings.
  89949. ** I now sorely regret putting in this hack. The effect of this hack is
  89950. ** that misspelled identifier names are silently converted into strings
  89951. ** rather than causing an error, to the frustration of countless
  89952. ** programmers. To all those frustrated programmers, my apologies.
  89953. **
  89954. ** Someday, I hope to get rid of this hack. Unfortunately there is
  89955. ** a huge amount of legacy SQL that uses it. So for now, we just
  89956. ** issue a warning.
  89957. */
  89958. sqlite3_log(SQLITE_WARNING,
  89959. "double-quoted string literal: \"%w\"", zCol);
  89960. #ifdef SQLITE_ENABLE_NORMALIZE
  89961. sqlite3VdbeAddDblquoteStr(db, pParse->pVdbe, zCol);
  89962. #endif
  89963. pExpr->op = TK_STRING;
  89964. pExpr->y.pTab = 0;
  89965. return WRC_Prune;
  89966. }
  89967. if( sqlite3ExprIdToTrueFalse(pExpr) ){
  89968. return WRC_Prune;
  89969. }
  89970. }
  89971. /*
  89972. ** cnt==0 means there was not match. cnt>1 means there were two or
  89973. ** more matches. Either way, we have an error.
  89974. */
  89975. if( cnt!=1 ){
  89976. const char *zErr;
  89977. zErr = cnt==0 ? "no such column" : "ambiguous column name";
  89978. if( zDb ){
  89979. sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
  89980. }else if( zTab ){
  89981. sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
  89982. }else{
  89983. sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
  89984. }
  89985. pParse->checkSchema = 1;
  89986. pTopNC->nErr++;
  89987. }
  89988. /* If a column from a table in pSrcList is referenced, then record
  89989. ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
  89990. ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the
  89991. ** column number is greater than the number of bits in the bitmask
  89992. ** then set the high-order bit of the bitmask.
  89993. */
  89994. if( pExpr->iColumn>=0 && pMatch!=0 ){
  89995. int n = pExpr->iColumn;
  89996. testcase( n==BMS-1 );
  89997. if( n>=BMS ){
  89998. n = BMS-1;
  89999. }
  90000. assert( pMatch->iCursor==pExpr->iTable );
  90001. pMatch->colUsed |= ((Bitmask)1)<<n;
  90002. }
  90003. /* Clean up and return
  90004. */
  90005. sqlite3ExprDelete(db, pExpr->pLeft);
  90006. pExpr->pLeft = 0;
  90007. sqlite3ExprDelete(db, pExpr->pRight);
  90008. pExpr->pRight = 0;
  90009. pExpr->op = eNewExprOp;
  90010. ExprSetProperty(pExpr, EP_Leaf);
  90011. lookupname_end:
  90012. if( cnt==1 ){
  90013. assert( pNC!=0 );
  90014. if( !ExprHasProperty(pExpr, EP_Alias) ){
  90015. sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
  90016. }
  90017. /* Increment the nRef value on all name contexts from TopNC up to
  90018. ** the point where the name matched. */
  90019. for(;;){
  90020. assert( pTopNC!=0 );
  90021. pTopNC->nRef++;
  90022. if( pTopNC==pNC ) break;
  90023. pTopNC = pTopNC->pNext;
  90024. }
  90025. return WRC_Prune;
  90026. } else {
  90027. return WRC_Abort;
  90028. }
  90029. }
  90030. /*
  90031. ** Allocate and return a pointer to an expression to load the column iCol
  90032. ** from datasource iSrc in SrcList pSrc.
  90033. */
  90034. SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
  90035. Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
  90036. if( p ){
  90037. struct SrcList_item *pItem = &pSrc->a[iSrc];
  90038. p->y.pTab = pItem->pTab;
  90039. p->iTable = pItem->iCursor;
  90040. if( p->y.pTab->iPKey==iCol ){
  90041. p->iColumn = -1;
  90042. }else{
  90043. p->iColumn = (ynVar)iCol;
  90044. testcase( iCol==BMS );
  90045. testcase( iCol==BMS-1 );
  90046. pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
  90047. }
  90048. }
  90049. return p;
  90050. }
  90051. /*
  90052. ** Report an error that an expression is not valid for some set of
  90053. ** pNC->ncFlags values determined by validMask.
  90054. */
  90055. static void notValid(
  90056. Parse *pParse, /* Leave error message here */
  90057. NameContext *pNC, /* The name context */
  90058. const char *zMsg, /* Type of error */
  90059. int validMask /* Set of contexts for which prohibited */
  90060. ){
  90061. assert( (validMask&~(NC_IsCheck|NC_PartIdx|NC_IdxExpr))==0 );
  90062. if( (pNC->ncFlags & validMask)!=0 ){
  90063. const char *zIn = "partial index WHERE clauses";
  90064. if( pNC->ncFlags & NC_IdxExpr ) zIn = "index expressions";
  90065. #ifndef SQLITE_OMIT_CHECK
  90066. else if( pNC->ncFlags & NC_IsCheck ) zIn = "CHECK constraints";
  90067. #endif
  90068. sqlite3ErrorMsg(pParse, "%s prohibited in %s", zMsg, zIn);
  90069. }
  90070. }
  90071. /*
  90072. ** Expression p should encode a floating point value between 1.0 and 0.0.
  90073. ** Return 1024 times this value. Or return -1 if p is not a floating point
  90074. ** value between 1.0 and 0.0.
  90075. */
  90076. static int exprProbability(Expr *p){
  90077. double r = -1.0;
  90078. if( p->op!=TK_FLOAT ) return -1;
  90079. sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8);
  90080. assert( r>=0.0 );
  90081. if( r>1.0 ) return -1;
  90082. return (int)(r*134217728.0);
  90083. }
  90084. /*
  90085. ** This routine is callback for sqlite3WalkExpr().
  90086. **
  90087. ** Resolve symbolic names into TK_COLUMN operators for the current
  90088. ** node in the expression tree. Return 0 to continue the search down
  90089. ** the tree or 2 to abort the tree walk.
  90090. **
  90091. ** This routine also does error checking and name resolution for
  90092. ** function names. The operator for aggregate functions is changed
  90093. ** to TK_AGG_FUNCTION.
  90094. */
  90095. static int resolveExprStep(Walker *pWalker, Expr *pExpr){
  90096. NameContext *pNC;
  90097. Parse *pParse;
  90098. pNC = pWalker->u.pNC;
  90099. assert( pNC!=0 );
  90100. pParse = pNC->pParse;
  90101. assert( pParse==pWalker->pParse );
  90102. #ifndef NDEBUG
  90103. if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
  90104. SrcList *pSrcList = pNC->pSrcList;
  90105. int i;
  90106. for(i=0; i<pNC->pSrcList->nSrc; i++){
  90107. assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
  90108. }
  90109. }
  90110. #endif
  90111. switch( pExpr->op ){
  90112. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  90113. /* The special operator TK_ROW means use the rowid for the first
  90114. ** column in the FROM clause. This is used by the LIMIT and ORDER BY
  90115. ** clause processing on UPDATE and DELETE statements.
  90116. */
  90117. case TK_ROW: {
  90118. SrcList *pSrcList = pNC->pSrcList;
  90119. struct SrcList_item *pItem;
  90120. assert( pSrcList && pSrcList->nSrc==1 );
  90121. pItem = pSrcList->a;
  90122. assert( HasRowid(pItem->pTab) && pItem->pTab->pSelect==0 );
  90123. pExpr->op = TK_COLUMN;
  90124. pExpr->y.pTab = pItem->pTab;
  90125. pExpr->iTable = pItem->iCursor;
  90126. pExpr->iColumn = -1;
  90127. pExpr->affinity = SQLITE_AFF_INTEGER;
  90128. break;
  90129. }
  90130. #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)
  90131. && !defined(SQLITE_OMIT_SUBQUERY) */
  90132. /* A column name: ID
  90133. ** Or table name and column name: ID.ID
  90134. ** Or a database, table and column: ID.ID.ID
  90135. **
  90136. ** The TK_ID and TK_OUT cases are combined so that there will only
  90137. ** be one call to lookupName(). Then the compiler will in-line
  90138. ** lookupName() for a size reduction and performance increase.
  90139. */
  90140. case TK_ID:
  90141. case TK_DOT: {
  90142. const char *zColumn;
  90143. const char *zTable;
  90144. const char *zDb;
  90145. Expr *pRight;
  90146. if( pExpr->op==TK_ID ){
  90147. zDb = 0;
  90148. zTable = 0;
  90149. zColumn = pExpr->u.zToken;
  90150. }else{
  90151. Expr *pLeft = pExpr->pLeft;
  90152. notValid(pParse, pNC, "the \".\" operator", NC_IdxExpr);
  90153. pRight = pExpr->pRight;
  90154. if( pRight->op==TK_ID ){
  90155. zDb = 0;
  90156. }else{
  90157. assert( pRight->op==TK_DOT );
  90158. zDb = pLeft->u.zToken;
  90159. pLeft = pRight->pLeft;
  90160. pRight = pRight->pRight;
  90161. }
  90162. zTable = pLeft->u.zToken;
  90163. zColumn = pRight->u.zToken;
  90164. if( IN_RENAME_OBJECT ){
  90165. sqlite3RenameTokenRemap(pParse, (void*)pExpr, (void*)pRight);
  90166. sqlite3RenameTokenRemap(pParse, (void*)&pExpr->y.pTab, (void*)pLeft);
  90167. }
  90168. }
  90169. return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
  90170. }
  90171. /* Resolve function names
  90172. */
  90173. case TK_FUNCTION: {
  90174. ExprList *pList = pExpr->x.pList; /* The argument list */
  90175. int n = pList ? pList->nExpr : 0; /* Number of arguments */
  90176. int no_such_func = 0; /* True if no such function exists */
  90177. int wrong_num_args = 0; /* True if wrong number of arguments */
  90178. int is_agg = 0; /* True if is an aggregate function */
  90179. int nId; /* Number of characters in function name */
  90180. const char *zId; /* The function name. */
  90181. FuncDef *pDef; /* Information about the function */
  90182. u8 enc = ENC(pParse->db); /* The database encoding */
  90183. int savedAllowFlags = (pNC->ncFlags & (NC_AllowAgg | NC_AllowWin));
  90184. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  90185. zId = pExpr->u.zToken;
  90186. nId = sqlite3Strlen30(zId);
  90187. pDef = sqlite3FindFunction(pParse->db, zId, n, enc, 0);
  90188. if( pDef==0 ){
  90189. pDef = sqlite3FindFunction(pParse->db, zId, -2, enc, 0);
  90190. if( pDef==0 ){
  90191. no_such_func = 1;
  90192. }else{
  90193. wrong_num_args = 1;
  90194. }
  90195. }else{
  90196. is_agg = pDef->xFinalize!=0;
  90197. if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
  90198. ExprSetProperty(pExpr, EP_Unlikely);
  90199. if( n==2 ){
  90200. pExpr->iTable = exprProbability(pList->a[1].pExpr);
  90201. if( pExpr->iTable<0 ){
  90202. sqlite3ErrorMsg(pParse,
  90203. "second argument to likelihood() must be a "
  90204. "constant between 0.0 and 1.0");
  90205. pNC->nErr++;
  90206. }
  90207. }else{
  90208. /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is
  90209. ** equivalent to likelihood(X, 0.0625).
  90210. ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is
  90211. ** short-hand for likelihood(X,0.0625).
  90212. ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand
  90213. ** for likelihood(X,0.9375).
  90214. ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent
  90215. ** to likelihood(X,0.9375). */
  90216. /* TUNING: unlikely() probability is 0.0625. likely() is 0.9375 */
  90217. pExpr->iTable = pDef->zName[0]=='u' ? 8388608 : 125829120;
  90218. }
  90219. }
  90220. #ifndef SQLITE_OMIT_AUTHORIZATION
  90221. {
  90222. int auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0,pDef->zName,0);
  90223. if( auth!=SQLITE_OK ){
  90224. if( auth==SQLITE_DENY ){
  90225. sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
  90226. pDef->zName);
  90227. pNC->nErr++;
  90228. }
  90229. pExpr->op = TK_NULL;
  90230. return WRC_Prune;
  90231. }
  90232. }
  90233. #endif
  90234. if( pDef->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG) ){
  90235. /* For the purposes of the EP_ConstFunc flag, date and time
  90236. ** functions and other functions that change slowly are considered
  90237. ** constant because they are constant for the duration of one query */
  90238. ExprSetProperty(pExpr,EP_ConstFunc);
  90239. }
  90240. if( (pDef->funcFlags & SQLITE_FUNC_CONSTANT)==0 ){
  90241. /* Date/time functions that use 'now', and other functions like
  90242. ** sqlite_version() that might change over time cannot be used
  90243. ** in an index. */
  90244. notValid(pParse, pNC, "non-deterministic functions",
  90245. NC_IdxExpr|NC_PartIdx);
  90246. }
  90247. if( (pDef->funcFlags & SQLITE_FUNC_INTERNAL)!=0
  90248. && pParse->nested==0
  90249. && sqlite3Config.bInternalFunctions==0
  90250. ){
  90251. /* Internal-use-only functions are disallowed unless the
  90252. ** SQL is being compiled using sqlite3NestedParse() */
  90253. no_such_func = 1;
  90254. pDef = 0;
  90255. }
  90256. }
  90257. if( 0==IN_RENAME_OBJECT ){
  90258. #ifndef SQLITE_OMIT_WINDOWFUNC
  90259. assert( is_agg==0 || (pDef->funcFlags & SQLITE_FUNC_MINMAX)
  90260. || (pDef->xValue==0 && pDef->xInverse==0)
  90261. || (pDef->xValue && pDef->xInverse && pDef->xSFunc && pDef->xFinalize)
  90262. );
  90263. if( pDef && pDef->xValue==0 && ExprHasProperty(pExpr, EP_WinFunc) ){
  90264. sqlite3ErrorMsg(pParse,
  90265. "%.*s() may not be used as a window function", nId, zId
  90266. );
  90267. pNC->nErr++;
  90268. }else if(
  90269. (is_agg && (pNC->ncFlags & NC_AllowAgg)==0)
  90270. || (is_agg && (pDef->funcFlags&SQLITE_FUNC_WINDOW) && !pExpr->y.pWin)
  90271. || (is_agg && pExpr->y.pWin && (pNC->ncFlags & NC_AllowWin)==0)
  90272. ){
  90273. const char *zType;
  90274. if( (pDef->funcFlags & SQLITE_FUNC_WINDOW) || pExpr->y.pWin ){
  90275. zType = "window";
  90276. }else{
  90277. zType = "aggregate";
  90278. }
  90279. sqlite3ErrorMsg(pParse, "misuse of %s function %.*s()",zType,nId,zId);
  90280. pNC->nErr++;
  90281. is_agg = 0;
  90282. }
  90283. #else
  90284. if( (is_agg && (pNC->ncFlags & NC_AllowAgg)==0) ){
  90285. sqlite3ErrorMsg(pParse,"misuse of aggregate function %.*s()",nId,zId);
  90286. pNC->nErr++;
  90287. is_agg = 0;
  90288. }
  90289. #endif
  90290. else if( no_such_func && pParse->db->init.busy==0
  90291. #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
  90292. && pParse->explain==0
  90293. #endif
  90294. ){
  90295. sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
  90296. pNC->nErr++;
  90297. }else if( wrong_num_args ){
  90298. sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
  90299. nId, zId);
  90300. pNC->nErr++;
  90301. }
  90302. if( is_agg ){
  90303. /* Window functions may not be arguments of aggregate functions.
  90304. ** Or arguments of other window functions. But aggregate functions
  90305. ** may be arguments for window functions. */
  90306. #ifndef SQLITE_OMIT_WINDOWFUNC
  90307. pNC->ncFlags &= ~(NC_AllowWin | (!pExpr->y.pWin ? NC_AllowAgg : 0));
  90308. #else
  90309. pNC->ncFlags &= ~NC_AllowAgg;
  90310. #endif
  90311. }
  90312. }
  90313. sqlite3WalkExprList(pWalker, pList);
  90314. if( is_agg ){
  90315. #ifndef SQLITE_OMIT_WINDOWFUNC
  90316. if( pExpr->y.pWin ){
  90317. Select *pSel = pNC->pWinSelect;
  90318. if( IN_RENAME_OBJECT==0 ){
  90319. sqlite3WindowUpdate(pParse, pSel->pWinDefn, pExpr->y.pWin, pDef);
  90320. }
  90321. sqlite3WalkExprList(pWalker, pExpr->y.pWin->pPartition);
  90322. sqlite3WalkExprList(pWalker, pExpr->y.pWin->pOrderBy);
  90323. sqlite3WalkExpr(pWalker, pExpr->y.pWin->pFilter);
  90324. if( 0==pSel->pWin
  90325. || 0==sqlite3WindowCompare(pParse, pSel->pWin, pExpr->y.pWin)
  90326. ){
  90327. pExpr->y.pWin->pNextWin = pSel->pWin;
  90328. pSel->pWin = pExpr->y.pWin;
  90329. }
  90330. pNC->ncFlags |= NC_HasWin;
  90331. }else
  90332. #endif /* SQLITE_OMIT_WINDOWFUNC */
  90333. {
  90334. NameContext *pNC2 = pNC;
  90335. pExpr->op = TK_AGG_FUNCTION;
  90336. pExpr->op2 = 0;
  90337. while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
  90338. pExpr->op2++;
  90339. pNC2 = pNC2->pNext;
  90340. }
  90341. assert( pDef!=0 );
  90342. if( pNC2 ){
  90343. assert( SQLITE_FUNC_MINMAX==NC_MinMaxAgg );
  90344. testcase( (pDef->funcFlags & SQLITE_FUNC_MINMAX)!=0 );
  90345. pNC2->ncFlags |= NC_HasAgg | (pDef->funcFlags & SQLITE_FUNC_MINMAX);
  90346. }
  90347. }
  90348. pNC->ncFlags |= savedAllowFlags;
  90349. }
  90350. /* FIX ME: Compute pExpr->affinity based on the expected return
  90351. ** type of the function
  90352. */
  90353. return WRC_Prune;
  90354. }
  90355. #ifndef SQLITE_OMIT_SUBQUERY
  90356. case TK_SELECT:
  90357. case TK_EXISTS: testcase( pExpr->op==TK_EXISTS );
  90358. #endif
  90359. case TK_IN: {
  90360. testcase( pExpr->op==TK_IN );
  90361. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  90362. int nRef = pNC->nRef;
  90363. notValid(pParse, pNC, "subqueries", NC_IsCheck|NC_PartIdx|NC_IdxExpr);
  90364. sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
  90365. assert( pNC->nRef>=nRef );
  90366. if( nRef!=pNC->nRef ){
  90367. ExprSetProperty(pExpr, EP_VarSelect);
  90368. pNC->ncFlags |= NC_VarSelect;
  90369. }
  90370. }
  90371. break;
  90372. }
  90373. case TK_VARIABLE: {
  90374. notValid(pParse, pNC, "parameters", NC_IsCheck|NC_PartIdx|NC_IdxExpr);
  90375. break;
  90376. }
  90377. case TK_IS:
  90378. case TK_ISNOT: {
  90379. Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
  90380. assert( !ExprHasProperty(pExpr, EP_Reduced) );
  90381. /* Handle special cases of "x IS TRUE", "x IS FALSE", "x IS NOT TRUE",
  90382. ** and "x IS NOT FALSE". */
  90383. if( pRight->op==TK_ID ){
  90384. int rc = resolveExprStep(pWalker, pRight);
  90385. if( rc==WRC_Abort ) return WRC_Abort;
  90386. if( pRight->op==TK_TRUEFALSE ){
  90387. pExpr->op2 = pExpr->op;
  90388. pExpr->op = TK_TRUTH;
  90389. return WRC_Continue;
  90390. }
  90391. }
  90392. /* Fall thru */
  90393. }
  90394. case TK_BETWEEN:
  90395. case TK_EQ:
  90396. case TK_NE:
  90397. case TK_LT:
  90398. case TK_LE:
  90399. case TK_GT:
  90400. case TK_GE: {
  90401. int nLeft, nRight;
  90402. if( pParse->db->mallocFailed ) break;
  90403. assert( pExpr->pLeft!=0 );
  90404. nLeft = sqlite3ExprVectorSize(pExpr->pLeft);
  90405. if( pExpr->op==TK_BETWEEN ){
  90406. nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[0].pExpr);
  90407. if( nRight==nLeft ){
  90408. nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[1].pExpr);
  90409. }
  90410. }else{
  90411. assert( pExpr->pRight!=0 );
  90412. nRight = sqlite3ExprVectorSize(pExpr->pRight);
  90413. }
  90414. if( nLeft!=nRight ){
  90415. testcase( pExpr->op==TK_EQ );
  90416. testcase( pExpr->op==TK_NE );
  90417. testcase( pExpr->op==TK_LT );
  90418. testcase( pExpr->op==TK_LE );
  90419. testcase( pExpr->op==TK_GT );
  90420. testcase( pExpr->op==TK_GE );
  90421. testcase( pExpr->op==TK_IS );
  90422. testcase( pExpr->op==TK_ISNOT );
  90423. testcase( pExpr->op==TK_BETWEEN );
  90424. sqlite3ErrorMsg(pParse, "row value misused");
  90425. }
  90426. break;
  90427. }
  90428. }
  90429. return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
  90430. }
  90431. /*
  90432. ** pEList is a list of expressions which are really the result set of the
  90433. ** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
  90434. ** This routine checks to see if pE is a simple identifier which corresponds
  90435. ** to the AS-name of one of the terms of the expression list. If it is,
  90436. ** this routine return an integer between 1 and N where N is the number of
  90437. ** elements in pEList, corresponding to the matching entry. If there is
  90438. ** no match, or if pE is not a simple identifier, then this routine
  90439. ** return 0.
  90440. **
  90441. ** pEList has been resolved. pE has not.
  90442. */
  90443. static int resolveAsName(
  90444. Parse *pParse, /* Parsing context for error messages */
  90445. ExprList *pEList, /* List of expressions to scan */
  90446. Expr *pE /* Expression we are trying to match */
  90447. ){
  90448. int i; /* Loop counter */
  90449. UNUSED_PARAMETER(pParse);
  90450. if( pE->op==TK_ID ){
  90451. char *zCol = pE->u.zToken;
  90452. for(i=0; i<pEList->nExpr; i++){
  90453. char *zAs = pEList->a[i].zName;
  90454. if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
  90455. return i+1;
  90456. }
  90457. }
  90458. }
  90459. return 0;
  90460. }
  90461. /*
  90462. ** pE is a pointer to an expression which is a single term in the
  90463. ** ORDER BY of a compound SELECT. The expression has not been
  90464. ** name resolved.
  90465. **
  90466. ** At the point this routine is called, we already know that the
  90467. ** ORDER BY term is not an integer index into the result set. That
  90468. ** case is handled by the calling routine.
  90469. **
  90470. ** Attempt to match pE against result set columns in the left-most
  90471. ** SELECT statement. Return the index i of the matching column,
  90472. ** as an indication to the caller that it should sort by the i-th column.
  90473. ** The left-most column is 1. In other words, the value returned is the
  90474. ** same integer value that would be used in the SQL statement to indicate
  90475. ** the column.
  90476. **
  90477. ** If there is no match, return 0. Return -1 if an error occurs.
  90478. */
  90479. static int resolveOrderByTermToExprList(
  90480. Parse *pParse, /* Parsing context for error messages */
  90481. Select *pSelect, /* The SELECT statement with the ORDER BY clause */
  90482. Expr *pE /* The specific ORDER BY term */
  90483. ){
  90484. int i; /* Loop counter */
  90485. ExprList *pEList; /* The columns of the result set */
  90486. NameContext nc; /* Name context for resolving pE */
  90487. sqlite3 *db; /* Database connection */
  90488. int rc; /* Return code from subprocedures */
  90489. u8 savedSuppErr; /* Saved value of db->suppressErr */
  90490. assert( sqlite3ExprIsInteger(pE, &i)==0 );
  90491. pEList = pSelect->pEList;
  90492. /* Resolve all names in the ORDER BY term expression
  90493. */
  90494. memset(&nc, 0, sizeof(nc));
  90495. nc.pParse = pParse;
  90496. nc.pSrcList = pSelect->pSrc;
  90497. nc.uNC.pEList = pEList;
  90498. nc.ncFlags = NC_AllowAgg|NC_UEList;
  90499. nc.nErr = 0;
  90500. db = pParse->db;
  90501. savedSuppErr = db->suppressErr;
  90502. db->suppressErr = 1;
  90503. rc = sqlite3ResolveExprNames(&nc, pE);
  90504. db->suppressErr = savedSuppErr;
  90505. if( rc ) return 0;
  90506. /* Try to match the ORDER BY expression against an expression
  90507. ** in the result set. Return an 1-based index of the matching
  90508. ** result-set entry.
  90509. */
  90510. for(i=0; i<pEList->nExpr; i++){
  90511. if( sqlite3ExprCompare(0, pEList->a[i].pExpr, pE, -1)<2 ){
  90512. return i+1;
  90513. }
  90514. }
  90515. /* If no match, return 0. */
  90516. return 0;
  90517. }
  90518. /*
  90519. ** Generate an ORDER BY or GROUP BY term out-of-range error.
  90520. */
  90521. static void resolveOutOfRangeError(
  90522. Parse *pParse, /* The error context into which to write the error */
  90523. const char *zType, /* "ORDER" or "GROUP" */
  90524. int i, /* The index (1-based) of the term out of range */
  90525. int mx /* Largest permissible value of i */
  90526. ){
  90527. sqlite3ErrorMsg(pParse,
  90528. "%r %s BY term out of range - should be "
  90529. "between 1 and %d", i, zType, mx);
  90530. }
  90531. /*
  90532. ** Analyze the ORDER BY clause in a compound SELECT statement. Modify
  90533. ** each term of the ORDER BY clause is a constant integer between 1
  90534. ** and N where N is the number of columns in the compound SELECT.
  90535. **
  90536. ** ORDER BY terms that are already an integer between 1 and N are
  90537. ** unmodified. ORDER BY terms that are integers outside the range of
  90538. ** 1 through N generate an error. ORDER BY terms that are expressions
  90539. ** are matched against result set expressions of compound SELECT
  90540. ** beginning with the left-most SELECT and working toward the right.
  90541. ** At the first match, the ORDER BY expression is transformed into
  90542. ** the integer column number.
  90543. **
  90544. ** Return the number of errors seen.
  90545. */
  90546. static int resolveCompoundOrderBy(
  90547. Parse *pParse, /* Parsing context. Leave error messages here */
  90548. Select *pSelect /* The SELECT statement containing the ORDER BY */
  90549. ){
  90550. int i;
  90551. ExprList *pOrderBy;
  90552. ExprList *pEList;
  90553. sqlite3 *db;
  90554. int moreToDo = 1;
  90555. pOrderBy = pSelect->pOrderBy;
  90556. if( pOrderBy==0 ) return 0;
  90557. db = pParse->db;
  90558. if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  90559. sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
  90560. return 1;
  90561. }
  90562. for(i=0; i<pOrderBy->nExpr; i++){
  90563. pOrderBy->a[i].done = 0;
  90564. }
  90565. pSelect->pNext = 0;
  90566. while( pSelect->pPrior ){
  90567. pSelect->pPrior->pNext = pSelect;
  90568. pSelect = pSelect->pPrior;
  90569. }
  90570. while( pSelect && moreToDo ){
  90571. struct ExprList_item *pItem;
  90572. moreToDo = 0;
  90573. pEList = pSelect->pEList;
  90574. assert( pEList!=0 );
  90575. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  90576. int iCol = -1;
  90577. Expr *pE, *pDup;
  90578. if( pItem->done ) continue;
  90579. pE = sqlite3ExprSkipCollate(pItem->pExpr);
  90580. if( sqlite3ExprIsInteger(pE, &iCol) ){
  90581. if( iCol<=0 || iCol>pEList->nExpr ){
  90582. resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
  90583. return 1;
  90584. }
  90585. }else{
  90586. iCol = resolveAsName(pParse, pEList, pE);
  90587. if( iCol==0 ){
  90588. /* Now test if expression pE matches one of the values returned
  90589. ** by pSelect. In the usual case this is done by duplicating the
  90590. ** expression, resolving any symbols in it, and then comparing
  90591. ** it against each expression returned by the SELECT statement.
  90592. ** Once the comparisons are finished, the duplicate expression
  90593. ** is deleted.
  90594. **
  90595. ** Or, if this is running as part of an ALTER TABLE operation,
  90596. ** resolve the symbols in the actual expression, not a duplicate.
  90597. ** And, if one of the comparisons is successful, leave the expression
  90598. ** as is instead of transforming it to an integer as in the usual
  90599. ** case. This allows the code in alter.c to modify column
  90600. ** refererences within the ORDER BY expression as required. */
  90601. if( IN_RENAME_OBJECT ){
  90602. pDup = pE;
  90603. }else{
  90604. pDup = sqlite3ExprDup(db, pE, 0);
  90605. }
  90606. if( !db->mallocFailed ){
  90607. assert(pDup);
  90608. iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
  90609. }
  90610. if( !IN_RENAME_OBJECT ){
  90611. sqlite3ExprDelete(db, pDup);
  90612. }
  90613. }
  90614. }
  90615. if( iCol>0 ){
  90616. /* Convert the ORDER BY term into an integer column number iCol,
  90617. ** taking care to preserve the COLLATE clause if it exists */
  90618. if( !IN_RENAME_OBJECT ){
  90619. Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
  90620. if( pNew==0 ) return 1;
  90621. pNew->flags |= EP_IntValue;
  90622. pNew->u.iValue = iCol;
  90623. if( pItem->pExpr==pE ){
  90624. pItem->pExpr = pNew;
  90625. }else{
  90626. Expr *pParent = pItem->pExpr;
  90627. assert( pParent->op==TK_COLLATE );
  90628. while( pParent->pLeft->op==TK_COLLATE ) pParent = pParent->pLeft;
  90629. assert( pParent->pLeft==pE );
  90630. pParent->pLeft = pNew;
  90631. }
  90632. sqlite3ExprDelete(db, pE);
  90633. pItem->u.x.iOrderByCol = (u16)iCol;
  90634. }
  90635. pItem->done = 1;
  90636. }else{
  90637. moreToDo = 1;
  90638. }
  90639. }
  90640. pSelect = pSelect->pNext;
  90641. }
  90642. for(i=0; i<pOrderBy->nExpr; i++){
  90643. if( pOrderBy->a[i].done==0 ){
  90644. sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
  90645. "column in the result set", i+1);
  90646. return 1;
  90647. }
  90648. }
  90649. return 0;
  90650. }
  90651. /*
  90652. ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
  90653. ** the SELECT statement pSelect. If any term is reference to a
  90654. ** result set expression (as determined by the ExprList.a.u.x.iOrderByCol
  90655. ** field) then convert that term into a copy of the corresponding result set
  90656. ** column.
  90657. **
  90658. ** If any errors are detected, add an error message to pParse and
  90659. ** return non-zero. Return zero if no errors are seen.
  90660. */
  90661. SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
  90662. Parse *pParse, /* Parsing context. Leave error messages here */
  90663. Select *pSelect, /* The SELECT statement containing the clause */
  90664. ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
  90665. const char *zType /* "ORDER" or "GROUP" */
  90666. ){
  90667. int i;
  90668. sqlite3 *db = pParse->db;
  90669. ExprList *pEList;
  90670. struct ExprList_item *pItem;
  90671. if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
  90672. if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  90673. sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
  90674. return 1;
  90675. }
  90676. pEList = pSelect->pEList;
  90677. assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */
  90678. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  90679. if( pItem->u.x.iOrderByCol ){
  90680. if( pItem->u.x.iOrderByCol>pEList->nExpr ){
  90681. resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
  90682. return 1;
  90683. }
  90684. resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr,
  90685. zType,0);
  90686. }
  90687. }
  90688. return 0;
  90689. }
  90690. #ifndef SQLITE_OMIT_WINDOWFUNC
  90691. /*
  90692. ** Walker callback for resolveRemoveWindows().
  90693. */
  90694. static int resolveRemoveWindowsCb(Walker *pWalker, Expr *pExpr){
  90695. if( ExprHasProperty(pExpr, EP_WinFunc) ){
  90696. Window **pp;
  90697. for(pp=&pWalker->u.pSelect->pWin; *pp; pp=&(*pp)->pNextWin){
  90698. if( *pp==pExpr->y.pWin ){
  90699. *pp = (*pp)->pNextWin;
  90700. break;
  90701. }
  90702. }
  90703. }
  90704. return WRC_Continue;
  90705. }
  90706. /*
  90707. ** Remove any Window objects owned by the expression pExpr from the
  90708. ** Select.pWin list of Select object pSelect.
  90709. */
  90710. static void resolveRemoveWindows(Select *pSelect, Expr *pExpr){
  90711. Walker sWalker;
  90712. memset(&sWalker, 0, sizeof(Walker));
  90713. sWalker.xExprCallback = resolveRemoveWindowsCb;
  90714. sWalker.u.pSelect = pSelect;
  90715. sqlite3WalkExpr(&sWalker, pExpr);
  90716. }
  90717. #else
  90718. # define resolveRemoveWindows(x,y)
  90719. #endif
  90720. /*
  90721. ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
  90722. ** The Name context of the SELECT statement is pNC. zType is either
  90723. ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
  90724. **
  90725. ** This routine resolves each term of the clause into an expression.
  90726. ** If the order-by term is an integer I between 1 and N (where N is the
  90727. ** number of columns in the result set of the SELECT) then the expression
  90728. ** in the resolution is a copy of the I-th result-set expression. If
  90729. ** the order-by term is an identifier that corresponds to the AS-name of
  90730. ** a result-set expression, then the term resolves to a copy of the
  90731. ** result-set expression. Otherwise, the expression is resolved in
  90732. ** the usual way - using sqlite3ResolveExprNames().
  90733. **
  90734. ** This routine returns the number of errors. If errors occur, then
  90735. ** an appropriate error message might be left in pParse. (OOM errors
  90736. ** excepted.)
  90737. */
  90738. static int resolveOrderGroupBy(
  90739. NameContext *pNC, /* The name context of the SELECT statement */
  90740. Select *pSelect, /* The SELECT statement holding pOrderBy */
  90741. ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
  90742. const char *zType /* Either "ORDER" or "GROUP", as appropriate */
  90743. ){
  90744. int i, j; /* Loop counters */
  90745. int iCol; /* Column number */
  90746. struct ExprList_item *pItem; /* A term of the ORDER BY clause */
  90747. Parse *pParse; /* Parsing context */
  90748. int nResult; /* Number of terms in the result set */
  90749. if( pOrderBy==0 ) return 0;
  90750. nResult = pSelect->pEList->nExpr;
  90751. pParse = pNC->pParse;
  90752. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  90753. Expr *pE = pItem->pExpr;
  90754. Expr *pE2 = sqlite3ExprSkipCollate(pE);
  90755. if( zType[0]!='G' ){
  90756. iCol = resolveAsName(pParse, pSelect->pEList, pE2);
  90757. if( iCol>0 ){
  90758. /* If an AS-name match is found, mark this ORDER BY column as being
  90759. ** a copy of the iCol-th result-set column. The subsequent call to
  90760. ** sqlite3ResolveOrderGroupBy() will convert the expression to a
  90761. ** copy of the iCol-th result-set expression. */
  90762. pItem->u.x.iOrderByCol = (u16)iCol;
  90763. continue;
  90764. }
  90765. }
  90766. if( sqlite3ExprIsInteger(pE2, &iCol) ){
  90767. /* The ORDER BY term is an integer constant. Again, set the column
  90768. ** number so that sqlite3ResolveOrderGroupBy() will convert the
  90769. ** order-by term to a copy of the result-set expression */
  90770. if( iCol<1 || iCol>0xffff ){
  90771. resolveOutOfRangeError(pParse, zType, i+1, nResult);
  90772. return 1;
  90773. }
  90774. pItem->u.x.iOrderByCol = (u16)iCol;
  90775. continue;
  90776. }
  90777. /* Otherwise, treat the ORDER BY term as an ordinary expression */
  90778. pItem->u.x.iOrderByCol = 0;
  90779. if( sqlite3ResolveExprNames(pNC, pE) ){
  90780. return 1;
  90781. }
  90782. for(j=0; j<pSelect->pEList->nExpr; j++){
  90783. if( sqlite3ExprCompare(0, pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
  90784. /* Since this expresion is being changed into a reference
  90785. ** to an identical expression in the result set, remove all Window
  90786. ** objects belonging to the expression from the Select.pWin list. */
  90787. resolveRemoveWindows(pSelect, pE);
  90788. pItem->u.x.iOrderByCol = j+1;
  90789. }
  90790. }
  90791. }
  90792. return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
  90793. }
  90794. /*
  90795. ** Resolve names in the SELECT statement p and all of its descendants.
  90796. */
  90797. static int resolveSelectStep(Walker *pWalker, Select *p){
  90798. NameContext *pOuterNC; /* Context that contains this SELECT */
  90799. NameContext sNC; /* Name context of this SELECT */
  90800. int isCompound; /* True if p is a compound select */
  90801. int nCompound; /* Number of compound terms processed so far */
  90802. Parse *pParse; /* Parsing context */
  90803. int i; /* Loop counter */
  90804. ExprList *pGroupBy; /* The GROUP BY clause */
  90805. Select *pLeftmost; /* Left-most of SELECT of a compound */
  90806. sqlite3 *db; /* Database connection */
  90807. assert( p!=0 );
  90808. if( p->selFlags & SF_Resolved ){
  90809. return WRC_Prune;
  90810. }
  90811. pOuterNC = pWalker->u.pNC;
  90812. pParse = pWalker->pParse;
  90813. db = pParse->db;
  90814. /* Normally sqlite3SelectExpand() will be called first and will have
  90815. ** already expanded this SELECT. However, if this is a subquery within
  90816. ** an expression, sqlite3ResolveExprNames() will be called without a
  90817. ** prior call to sqlite3SelectExpand(). When that happens, let
  90818. ** sqlite3SelectPrep() do all of the processing for this SELECT.
  90819. ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
  90820. ** this routine in the correct order.
  90821. */
  90822. if( (p->selFlags & SF_Expanded)==0 ){
  90823. sqlite3SelectPrep(pParse, p, pOuterNC);
  90824. return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
  90825. }
  90826. isCompound = p->pPrior!=0;
  90827. nCompound = 0;
  90828. pLeftmost = p;
  90829. while( p ){
  90830. assert( (p->selFlags & SF_Expanded)!=0 );
  90831. assert( (p->selFlags & SF_Resolved)==0 );
  90832. p->selFlags |= SF_Resolved;
  90833. /* Resolve the expressions in the LIMIT and OFFSET clauses. These
  90834. ** are not allowed to refer to any names, so pass an empty NameContext.
  90835. */
  90836. memset(&sNC, 0, sizeof(sNC));
  90837. sNC.pParse = pParse;
  90838. sNC.pWinSelect = p;
  90839. if( sqlite3ResolveExprNames(&sNC, p->pLimit) ){
  90840. return WRC_Abort;
  90841. }
  90842. /* If the SF_Converted flags is set, then this Select object was
  90843. ** was created by the convertCompoundSelectToSubquery() function.
  90844. ** In this case the ORDER BY clause (p->pOrderBy) should be resolved
  90845. ** as if it were part of the sub-query, not the parent. This block
  90846. ** moves the pOrderBy down to the sub-query. It will be moved back
  90847. ** after the names have been resolved. */
  90848. if( p->selFlags & SF_Converted ){
  90849. Select *pSub = p->pSrc->a[0].pSelect;
  90850. assert( p->pSrc->nSrc==1 && p->pOrderBy );
  90851. assert( pSub->pPrior && pSub->pOrderBy==0 );
  90852. pSub->pOrderBy = p->pOrderBy;
  90853. p->pOrderBy = 0;
  90854. }
  90855. /* Recursively resolve names in all subqueries
  90856. */
  90857. for(i=0; i<p->pSrc->nSrc; i++){
  90858. struct SrcList_item *pItem = &p->pSrc->a[i];
  90859. if( pItem->pSelect && (pItem->pSelect->selFlags & SF_Resolved)==0 ){
  90860. NameContext *pNC; /* Used to iterate name contexts */
  90861. int nRef = 0; /* Refcount for pOuterNC and outer contexts */
  90862. const char *zSavedContext = pParse->zAuthContext;
  90863. /* Count the total number of references to pOuterNC and all of its
  90864. ** parent contexts. After resolving references to expressions in
  90865. ** pItem->pSelect, check if this value has changed. If so, then
  90866. ** SELECT statement pItem->pSelect must be correlated. Set the
  90867. ** pItem->fg.isCorrelated flag if this is the case. */
  90868. for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
  90869. if( pItem->zName ) pParse->zAuthContext = pItem->zName;
  90870. sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
  90871. pParse->zAuthContext = zSavedContext;
  90872. if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
  90873. for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
  90874. assert( pItem->fg.isCorrelated==0 && nRef<=0 );
  90875. pItem->fg.isCorrelated = (nRef!=0);
  90876. }
  90877. }
  90878. /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
  90879. ** resolve the result-set expression list.
  90880. */
  90881. sNC.ncFlags = NC_AllowAgg|NC_AllowWin;
  90882. sNC.pSrcList = p->pSrc;
  90883. sNC.pNext = pOuterNC;
  90884. /* Resolve names in the result set. */
  90885. if( sqlite3ResolveExprListNames(&sNC, p->pEList) ) return WRC_Abort;
  90886. sNC.ncFlags &= ~NC_AllowWin;
  90887. /* If there are no aggregate functions in the result-set, and no GROUP BY
  90888. ** expression, do not allow aggregates in any of the other expressions.
  90889. */
  90890. assert( (p->selFlags & SF_Aggregate)==0 );
  90891. pGroupBy = p->pGroupBy;
  90892. if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
  90893. assert( NC_MinMaxAgg==SF_MinMaxAgg );
  90894. p->selFlags |= SF_Aggregate | (sNC.ncFlags&NC_MinMaxAgg);
  90895. }else{
  90896. sNC.ncFlags &= ~NC_AllowAgg;
  90897. }
  90898. /* If a HAVING clause is present, then there must be a GROUP BY clause.
  90899. */
  90900. if( p->pHaving && !pGroupBy ){
  90901. sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
  90902. return WRC_Abort;
  90903. }
  90904. /* Add the output column list to the name-context before parsing the
  90905. ** other expressions in the SELECT statement. This is so that
  90906. ** expressions in the WHERE clause (etc.) can refer to expressions by
  90907. ** aliases in the result set.
  90908. **
  90909. ** Minor point: If this is the case, then the expression will be
  90910. ** re-evaluated for each reference to it.
  90911. */
  90912. assert( (sNC.ncFlags & (NC_UAggInfo|NC_UUpsert))==0 );
  90913. sNC.uNC.pEList = p->pEList;
  90914. sNC.ncFlags |= NC_UEList;
  90915. if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
  90916. if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
  90917. /* Resolve names in table-valued-function arguments */
  90918. for(i=0; i<p->pSrc->nSrc; i++){
  90919. struct SrcList_item *pItem = &p->pSrc->a[i];
  90920. if( pItem->fg.isTabFunc
  90921. && sqlite3ResolveExprListNames(&sNC, pItem->u1.pFuncArg)
  90922. ){
  90923. return WRC_Abort;
  90924. }
  90925. }
  90926. /* The ORDER BY and GROUP BY clauses may not refer to terms in
  90927. ** outer queries
  90928. */
  90929. sNC.pNext = 0;
  90930. sNC.ncFlags |= NC_AllowAgg|NC_AllowWin;
  90931. /* If this is a converted compound query, move the ORDER BY clause from
  90932. ** the sub-query back to the parent query. At this point each term
  90933. ** within the ORDER BY clause has been transformed to an integer value.
  90934. ** These integers will be replaced by copies of the corresponding result
  90935. ** set expressions by the call to resolveOrderGroupBy() below. */
  90936. if( p->selFlags & SF_Converted ){
  90937. Select *pSub = p->pSrc->a[0].pSelect;
  90938. p->pOrderBy = pSub->pOrderBy;
  90939. pSub->pOrderBy = 0;
  90940. }
  90941. /* Process the ORDER BY clause for singleton SELECT statements.
  90942. ** The ORDER BY clause for compounds SELECT statements is handled
  90943. ** below, after all of the result-sets for all of the elements of
  90944. ** the compound have been resolved.
  90945. **
  90946. ** If there is an ORDER BY clause on a term of a compound-select other
  90947. ** than the right-most term, then that is a syntax error. But the error
  90948. ** is not detected until much later, and so we need to go ahead and
  90949. ** resolve those symbols on the incorrect ORDER BY for consistency.
  90950. */
  90951. if( isCompound<=nCompound /* Defer right-most ORDER BY of a compound */
  90952. && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER")
  90953. ){
  90954. return WRC_Abort;
  90955. }
  90956. if( db->mallocFailed ){
  90957. return WRC_Abort;
  90958. }
  90959. sNC.ncFlags &= ~NC_AllowWin;
  90960. /* Resolve the GROUP BY clause. At the same time, make sure
  90961. ** the GROUP BY clause does not contain aggregate functions.
  90962. */
  90963. if( pGroupBy ){
  90964. struct ExprList_item *pItem;
  90965. if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
  90966. return WRC_Abort;
  90967. }
  90968. for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
  90969. if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
  90970. sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
  90971. "the GROUP BY clause");
  90972. return WRC_Abort;
  90973. }
  90974. }
  90975. }
  90976. #ifndef SQLITE_OMIT_WINDOWFUNC
  90977. if( IN_RENAME_OBJECT ){
  90978. Window *pWin;
  90979. for(pWin=p->pWinDefn; pWin; pWin=pWin->pNextWin){
  90980. if( sqlite3ResolveExprListNames(&sNC, pWin->pOrderBy)
  90981. || sqlite3ResolveExprListNames(&sNC, pWin->pPartition)
  90982. ){
  90983. return WRC_Abort;
  90984. }
  90985. }
  90986. }
  90987. #endif
  90988. /* If this is part of a compound SELECT, check that it has the right
  90989. ** number of expressions in the select list. */
  90990. if( p->pNext && p->pEList->nExpr!=p->pNext->pEList->nExpr ){
  90991. sqlite3SelectWrongNumTermsError(pParse, p->pNext);
  90992. return WRC_Abort;
  90993. }
  90994. /* Advance to the next term of the compound
  90995. */
  90996. p = p->pPrior;
  90997. nCompound++;
  90998. }
  90999. /* Resolve the ORDER BY on a compound SELECT after all terms of
  91000. ** the compound have been resolved.
  91001. */
  91002. if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
  91003. return WRC_Abort;
  91004. }
  91005. return WRC_Prune;
  91006. }
  91007. /*
  91008. ** This routine walks an expression tree and resolves references to
  91009. ** table columns and result-set columns. At the same time, do error
  91010. ** checking on function usage and set a flag if any aggregate functions
  91011. ** are seen.
  91012. **
  91013. ** To resolve table columns references we look for nodes (or subtrees) of the
  91014. ** form X.Y.Z or Y.Z or just Z where
  91015. **
  91016. ** X: The name of a database. Ex: "main" or "temp" or
  91017. ** the symbolic name assigned to an ATTACH-ed database.
  91018. **
  91019. ** Y: The name of a table in a FROM clause. Or in a trigger
  91020. ** one of the special names "old" or "new".
  91021. **
  91022. ** Z: The name of a column in table Y.
  91023. **
  91024. ** The node at the root of the subtree is modified as follows:
  91025. **
  91026. ** Expr.op Changed to TK_COLUMN
  91027. ** Expr.pTab Points to the Table object for X.Y
  91028. ** Expr.iColumn The column index in X.Y. -1 for the rowid.
  91029. ** Expr.iTable The VDBE cursor number for X.Y
  91030. **
  91031. **
  91032. ** To resolve result-set references, look for expression nodes of the
  91033. ** form Z (with no X and Y prefix) where the Z matches the right-hand
  91034. ** size of an AS clause in the result-set of a SELECT. The Z expression
  91035. ** is replaced by a copy of the left-hand side of the result-set expression.
  91036. ** Table-name and function resolution occurs on the substituted expression
  91037. ** tree. For example, in:
  91038. **
  91039. ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
  91040. **
  91041. ** The "x" term of the order by is replaced by "a+b" to render:
  91042. **
  91043. ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
  91044. **
  91045. ** Function calls are checked to make sure that the function is
  91046. ** defined and that the correct number of arguments are specified.
  91047. ** If the function is an aggregate function, then the NC_HasAgg flag is
  91048. ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
  91049. ** If an expression contains aggregate functions then the EP_Agg
  91050. ** property on the expression is set.
  91051. **
  91052. ** An error message is left in pParse if anything is amiss. The number
  91053. ** if errors is returned.
  91054. */
  91055. SQLITE_PRIVATE int sqlite3ResolveExprNames(
  91056. NameContext *pNC, /* Namespace to resolve expressions in. */
  91057. Expr *pExpr /* The expression to be analyzed. */
  91058. ){
  91059. int savedHasAgg;
  91060. Walker w;
  91061. if( pExpr==0 ) return SQLITE_OK;
  91062. savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin);
  91063. pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg|NC_HasWin);
  91064. w.pParse = pNC->pParse;
  91065. w.xExprCallback = resolveExprStep;
  91066. w.xSelectCallback = resolveSelectStep;
  91067. w.xSelectCallback2 = 0;
  91068. w.u.pNC = pNC;
  91069. #if SQLITE_MAX_EXPR_DEPTH>0
  91070. w.pParse->nHeight += pExpr->nHeight;
  91071. if( sqlite3ExprCheckHeight(w.pParse, w.pParse->nHeight) ){
  91072. return SQLITE_ERROR;
  91073. }
  91074. #endif
  91075. sqlite3WalkExpr(&w, pExpr);
  91076. #if SQLITE_MAX_EXPR_DEPTH>0
  91077. w.pParse->nHeight -= pExpr->nHeight;
  91078. #endif
  91079. assert( EP_Agg==NC_HasAgg );
  91080. assert( EP_Win==NC_HasWin );
  91081. testcase( pNC->ncFlags & NC_HasAgg );
  91082. testcase( pNC->ncFlags & NC_HasWin );
  91083. ExprSetProperty(pExpr, pNC->ncFlags & (NC_HasAgg|NC_HasWin) );
  91084. pNC->ncFlags |= savedHasAgg;
  91085. return pNC->nErr>0 || w.pParse->nErr>0;
  91086. }
  91087. /*
  91088. ** Resolve all names for all expression in an expression list. This is
  91089. ** just like sqlite3ResolveExprNames() except that it works for an expression
  91090. ** list rather than a single expression.
  91091. */
  91092. SQLITE_PRIVATE int sqlite3ResolveExprListNames(
  91093. NameContext *pNC, /* Namespace to resolve expressions in. */
  91094. ExprList *pList /* The expression list to be analyzed. */
  91095. ){
  91096. int i;
  91097. if( pList ){
  91098. for(i=0; i<pList->nExpr; i++){
  91099. if( sqlite3ResolveExprNames(pNC, pList->a[i].pExpr) ) return WRC_Abort;
  91100. }
  91101. }
  91102. return WRC_Continue;
  91103. }
  91104. /*
  91105. ** Resolve all names in all expressions of a SELECT and in all
  91106. ** decendents of the SELECT, including compounds off of p->pPrior,
  91107. ** subqueries in expressions, and subqueries used as FROM clause
  91108. ** terms.
  91109. **
  91110. ** See sqlite3ResolveExprNames() for a description of the kinds of
  91111. ** transformations that occur.
  91112. **
  91113. ** All SELECT statements should have been expanded using
  91114. ** sqlite3SelectExpand() prior to invoking this routine.
  91115. */
  91116. SQLITE_PRIVATE void sqlite3ResolveSelectNames(
  91117. Parse *pParse, /* The parser context */
  91118. Select *p, /* The SELECT statement being coded. */
  91119. NameContext *pOuterNC /* Name context for parent SELECT statement */
  91120. ){
  91121. Walker w;
  91122. assert( p!=0 );
  91123. w.xExprCallback = resolveExprStep;
  91124. w.xSelectCallback = resolveSelectStep;
  91125. w.xSelectCallback2 = 0;
  91126. w.pParse = pParse;
  91127. w.u.pNC = pOuterNC;
  91128. sqlite3WalkSelect(&w, p);
  91129. }
  91130. /*
  91131. ** Resolve names in expressions that can only reference a single table
  91132. ** or which cannot reference any tables at all. Examples:
  91133. **
  91134. ** (1) CHECK constraints
  91135. ** (2) WHERE clauses on partial indices
  91136. ** (3) Expressions in indexes on expressions
  91137. ** (4) Expression arguments to VACUUM INTO.
  91138. **
  91139. ** In all cases except (4), the Expr.iTable value for Expr.op==TK_COLUMN
  91140. ** nodes of the expression is set to -1 and the Expr.iColumn value is
  91141. ** set to the column number. In case (4), TK_COLUMN nodes cause an error.
  91142. **
  91143. ** Any errors cause an error message to be set in pParse.
  91144. */
  91145. SQLITE_PRIVATE int sqlite3ResolveSelfReference(
  91146. Parse *pParse, /* Parsing context */
  91147. Table *pTab, /* The table being referenced, or NULL */
  91148. int type, /* NC_IsCheck or NC_PartIdx or NC_IdxExpr, or 0 */
  91149. Expr *pExpr, /* Expression to resolve. May be NULL. */
  91150. ExprList *pList /* Expression list to resolve. May be NULL. */
  91151. ){
  91152. SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
  91153. NameContext sNC; /* Name context for pParse->pNewTable */
  91154. int rc;
  91155. assert( type==0 || pTab!=0 );
  91156. assert( type==NC_IsCheck || type==NC_PartIdx || type==NC_IdxExpr || pTab==0 );
  91157. memset(&sNC, 0, sizeof(sNC));
  91158. memset(&sSrc, 0, sizeof(sSrc));
  91159. if( pTab ){
  91160. sSrc.nSrc = 1;
  91161. sSrc.a[0].zName = pTab->zName;
  91162. sSrc.a[0].pTab = pTab;
  91163. sSrc.a[0].iCursor = -1;
  91164. }
  91165. sNC.pParse = pParse;
  91166. sNC.pSrcList = &sSrc;
  91167. sNC.ncFlags = type | NC_IsDDL;
  91168. if( (rc = sqlite3ResolveExprNames(&sNC, pExpr))!=SQLITE_OK ) return rc;
  91169. if( pList ) rc = sqlite3ResolveExprListNames(&sNC, pList);
  91170. return rc;
  91171. }
  91172. /************** End of resolve.c *********************************************/
  91173. /************** Begin file expr.c ********************************************/
  91174. /*
  91175. ** 2001 September 15
  91176. **
  91177. ** The author disclaims copyright to this source code. In place of
  91178. ** a legal notice, here is a blessing:
  91179. **
  91180. ** May you do good and not evil.
  91181. ** May you find forgiveness for yourself and forgive others.
  91182. ** May you share freely, never taking more than you give.
  91183. **
  91184. *************************************************************************
  91185. ** This file contains routines used for analyzing expressions and
  91186. ** for generating VDBE code that evaluates expressions in SQLite.
  91187. */
  91188. /* #include "sqliteInt.h" */
  91189. /* Forward declarations */
  91190. static void exprCodeBetween(Parse*,Expr*,int,void(*)(Parse*,Expr*,int,int),int);
  91191. static int exprCodeVector(Parse *pParse, Expr *p, int *piToFree);
  91192. /*
  91193. ** Return the affinity character for a single column of a table.
  91194. */
  91195. SQLITE_PRIVATE char sqlite3TableColumnAffinity(Table *pTab, int iCol){
  91196. assert( iCol<pTab->nCol );
  91197. return iCol>=0 ? pTab->aCol[iCol].affinity : SQLITE_AFF_INTEGER;
  91198. }
  91199. /*
  91200. ** Return the 'affinity' of the expression pExpr if any.
  91201. **
  91202. ** If pExpr is a column, a reference to a column via an 'AS' alias,
  91203. ** or a sub-select with a column as the return value, then the
  91204. ** affinity of that column is returned. Otherwise, 0x00 is returned,
  91205. ** indicating no affinity for the expression.
  91206. **
  91207. ** i.e. the WHERE clause expressions in the following statements all
  91208. ** have an affinity:
  91209. **
  91210. ** CREATE TABLE t1(a);
  91211. ** SELECT * FROM t1 WHERE a;
  91212. ** SELECT a AS b FROM t1 WHERE b;
  91213. ** SELECT * FROM t1 WHERE (select a from t1);
  91214. */
  91215. SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
  91216. int op;
  91217. if( pExpr->flags & EP_Generic ) return 0;
  91218. while( ExprHasProperty(pExpr, EP_Skip) ){
  91219. assert( pExpr->op==TK_COLLATE );
  91220. pExpr = pExpr->pLeft;
  91221. assert( pExpr!=0 );
  91222. }
  91223. op = pExpr->op;
  91224. if( op==TK_SELECT ){
  91225. assert( pExpr->flags&EP_xIsSelect );
  91226. return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
  91227. }
  91228. if( op==TK_REGISTER ) op = pExpr->op2;
  91229. #ifndef SQLITE_OMIT_CAST
  91230. if( op==TK_CAST ){
  91231. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  91232. return sqlite3AffinityType(pExpr->u.zToken, 0);
  91233. }
  91234. #endif
  91235. if( (op==TK_AGG_COLUMN || op==TK_COLUMN) && pExpr->y.pTab ){
  91236. return sqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn);
  91237. }
  91238. if( op==TK_SELECT_COLUMN ){
  91239. assert( pExpr->pLeft->flags&EP_xIsSelect );
  91240. return sqlite3ExprAffinity(
  91241. pExpr->pLeft->x.pSelect->pEList->a[pExpr->iColumn].pExpr
  91242. );
  91243. }
  91244. return pExpr->affinity;
  91245. }
  91246. /*
  91247. ** Set the collating sequence for expression pExpr to be the collating
  91248. ** sequence named by pToken. Return a pointer to a new Expr node that
  91249. ** implements the COLLATE operator.
  91250. **
  91251. ** If a memory allocation error occurs, that fact is recorded in pParse->db
  91252. ** and the pExpr parameter is returned unchanged.
  91253. */
  91254. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(
  91255. Parse *pParse, /* Parsing context */
  91256. Expr *pExpr, /* Add the "COLLATE" clause to this expression */
  91257. const Token *pCollName, /* Name of collating sequence */
  91258. int dequote /* True to dequote pCollName */
  91259. ){
  91260. if( pCollName->n>0 ){
  91261. Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote);
  91262. if( pNew ){
  91263. pNew->pLeft = pExpr;
  91264. pNew->flags |= EP_Collate|EP_Skip;
  91265. pExpr = pNew;
  91266. }
  91267. }
  91268. return pExpr;
  91269. }
  91270. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
  91271. Token s;
  91272. assert( zC!=0 );
  91273. sqlite3TokenInit(&s, (char*)zC);
  91274. return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0);
  91275. }
  91276. /*
  91277. ** Skip over any TK_COLLATE operators and any unlikely()
  91278. ** or likelihood() function at the root of an expression.
  91279. */
  91280. SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){
  91281. while( pExpr && ExprHasProperty(pExpr, EP_Skip|EP_Unlikely) ){
  91282. if( ExprHasProperty(pExpr, EP_Unlikely) ){
  91283. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  91284. assert( pExpr->x.pList->nExpr>0 );
  91285. assert( pExpr->op==TK_FUNCTION );
  91286. pExpr = pExpr->x.pList->a[0].pExpr;
  91287. }else{
  91288. assert( pExpr->op==TK_COLLATE );
  91289. pExpr = pExpr->pLeft;
  91290. }
  91291. }
  91292. return pExpr;
  91293. }
  91294. /*
  91295. ** Return the collation sequence for the expression pExpr. If
  91296. ** there is no defined collating sequence, return NULL.
  91297. **
  91298. ** See also: sqlite3ExprNNCollSeq()
  91299. **
  91300. ** The sqlite3ExprNNCollSeq() works the same exact that it returns the
  91301. ** default collation if pExpr has no defined collation.
  91302. **
  91303. ** The collating sequence might be determined by a COLLATE operator
  91304. ** or by the presence of a column with a defined collating sequence.
  91305. ** COLLATE operators take first precedence. Left operands take
  91306. ** precedence over right operands.
  91307. */
  91308. SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
  91309. sqlite3 *db = pParse->db;
  91310. CollSeq *pColl = 0;
  91311. Expr *p = pExpr;
  91312. while( p ){
  91313. int op = p->op;
  91314. if( p->flags & EP_Generic ) break;
  91315. if( op==TK_REGISTER ) op = p->op2;
  91316. if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_TRIGGER)
  91317. && p->y.pTab!=0
  91318. ){
  91319. /* op==TK_REGISTER && p->y.pTab!=0 happens when pExpr was originally
  91320. ** a TK_COLUMN but was previously evaluated and cached in a register */
  91321. int j = p->iColumn;
  91322. if( j>=0 ){
  91323. const char *zColl = p->y.pTab->aCol[j].zColl;
  91324. pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
  91325. }
  91326. break;
  91327. }
  91328. if( op==TK_CAST || op==TK_UPLUS ){
  91329. p = p->pLeft;
  91330. continue;
  91331. }
  91332. if( op==TK_COLLATE ){
  91333. pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
  91334. break;
  91335. }
  91336. if( p->flags & EP_Collate ){
  91337. if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){
  91338. p = p->pLeft;
  91339. }else{
  91340. Expr *pNext = p->pRight;
  91341. /* The Expr.x union is never used at the same time as Expr.pRight */
  91342. assert( p->x.pList==0 || p->pRight==0 );
  91343. /* p->flags holds EP_Collate and p->pLeft->flags does not. And
  91344. ** p->x.pSelect cannot. So if p->x.pLeft exists, it must hold at
  91345. ** least one EP_Collate. Thus the following two ALWAYS. */
  91346. if( p->x.pList!=0 && ALWAYS(!ExprHasProperty(p, EP_xIsSelect)) ){
  91347. int i;
  91348. for(i=0; ALWAYS(i<p->x.pList->nExpr); i++){
  91349. if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){
  91350. pNext = p->x.pList->a[i].pExpr;
  91351. break;
  91352. }
  91353. }
  91354. }
  91355. p = pNext;
  91356. }
  91357. }else{
  91358. break;
  91359. }
  91360. }
  91361. if( sqlite3CheckCollSeq(pParse, pColl) ){
  91362. pColl = 0;
  91363. }
  91364. return pColl;
  91365. }
  91366. /*
  91367. ** Return the collation sequence for the expression pExpr. If
  91368. ** there is no defined collating sequence, return a pointer to the
  91369. ** defautl collation sequence.
  91370. **
  91371. ** See also: sqlite3ExprCollSeq()
  91372. **
  91373. ** The sqlite3ExprCollSeq() routine works the same except that it
  91374. ** returns NULL if there is no defined collation.
  91375. */
  91376. SQLITE_PRIVATE CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, Expr *pExpr){
  91377. CollSeq *p = sqlite3ExprCollSeq(pParse, pExpr);
  91378. if( p==0 ) p = pParse->db->pDfltColl;
  91379. assert( p!=0 );
  91380. return p;
  91381. }
  91382. /*
  91383. ** Return TRUE if the two expressions have equivalent collating sequences.
  91384. */
  91385. SQLITE_PRIVATE int sqlite3ExprCollSeqMatch(Parse *pParse, Expr *pE1, Expr *pE2){
  91386. CollSeq *pColl1 = sqlite3ExprNNCollSeq(pParse, pE1);
  91387. CollSeq *pColl2 = sqlite3ExprNNCollSeq(pParse, pE2);
  91388. return sqlite3StrICmp(pColl1->zName, pColl2->zName)==0;
  91389. }
  91390. /*
  91391. ** pExpr is an operand of a comparison operator. aff2 is the
  91392. ** type affinity of the other operand. This routine returns the
  91393. ** type affinity that should be used for the comparison operator.
  91394. */
  91395. SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
  91396. char aff1 = sqlite3ExprAffinity(pExpr);
  91397. if( aff1 && aff2 ){
  91398. /* Both sides of the comparison are columns. If one has numeric
  91399. ** affinity, use that. Otherwise use no affinity.
  91400. */
  91401. if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
  91402. return SQLITE_AFF_NUMERIC;
  91403. }else{
  91404. return SQLITE_AFF_BLOB;
  91405. }
  91406. }else if( !aff1 && !aff2 ){
  91407. /* Neither side of the comparison is a column. Compare the
  91408. ** results directly.
  91409. */
  91410. return SQLITE_AFF_BLOB;
  91411. }else{
  91412. /* One side is a column, the other is not. Use the columns affinity. */
  91413. assert( aff1==0 || aff2==0 );
  91414. return (aff1 + aff2);
  91415. }
  91416. }
  91417. /*
  91418. ** pExpr is a comparison operator. Return the type affinity that should
  91419. ** be applied to both operands prior to doing the comparison.
  91420. */
  91421. static char comparisonAffinity(Expr *pExpr){
  91422. char aff;
  91423. assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
  91424. pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
  91425. pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
  91426. assert( pExpr->pLeft );
  91427. aff = sqlite3ExprAffinity(pExpr->pLeft);
  91428. if( pExpr->pRight ){
  91429. aff = sqlite3CompareAffinity(pExpr->pRight, aff);
  91430. }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  91431. aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
  91432. }else if( aff==0 ){
  91433. aff = SQLITE_AFF_BLOB;
  91434. }
  91435. return aff;
  91436. }
  91437. /*
  91438. ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
  91439. ** idx_affinity is the affinity of an indexed column. Return true
  91440. ** if the index with affinity idx_affinity may be used to implement
  91441. ** the comparison in pExpr.
  91442. */
  91443. SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
  91444. char aff = comparisonAffinity(pExpr);
  91445. switch( aff ){
  91446. case SQLITE_AFF_BLOB:
  91447. return 1;
  91448. case SQLITE_AFF_TEXT:
  91449. return idx_affinity==SQLITE_AFF_TEXT;
  91450. default:
  91451. return sqlite3IsNumericAffinity(idx_affinity);
  91452. }
  91453. }
  91454. /*
  91455. ** Return the P5 value that should be used for a binary comparison
  91456. ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
  91457. */
  91458. static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
  91459. u8 aff = (char)sqlite3ExprAffinity(pExpr2);
  91460. aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
  91461. return aff;
  91462. }
  91463. /*
  91464. ** Return a pointer to the collation sequence that should be used by
  91465. ** a binary comparison operator comparing pLeft and pRight.
  91466. **
  91467. ** If the left hand expression has a collating sequence type, then it is
  91468. ** used. Otherwise the collation sequence for the right hand expression
  91469. ** is used, or the default (BINARY) if neither expression has a collating
  91470. ** type.
  91471. **
  91472. ** Argument pRight (but not pLeft) may be a null pointer. In this case,
  91473. ** it is not considered.
  91474. */
  91475. SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
  91476. Parse *pParse,
  91477. Expr *pLeft,
  91478. Expr *pRight
  91479. ){
  91480. CollSeq *pColl;
  91481. assert( pLeft );
  91482. if( pLeft->flags & EP_Collate ){
  91483. pColl = sqlite3ExprCollSeq(pParse, pLeft);
  91484. }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
  91485. pColl = sqlite3ExprCollSeq(pParse, pRight);
  91486. }else{
  91487. pColl = sqlite3ExprCollSeq(pParse, pLeft);
  91488. if( !pColl ){
  91489. pColl = sqlite3ExprCollSeq(pParse, pRight);
  91490. }
  91491. }
  91492. return pColl;
  91493. }
  91494. /*
  91495. ** Generate code for a comparison operator.
  91496. */
  91497. static int codeCompare(
  91498. Parse *pParse, /* The parsing (and code generating) context */
  91499. Expr *pLeft, /* The left operand */
  91500. Expr *pRight, /* The right operand */
  91501. int opcode, /* The comparison opcode */
  91502. int in1, int in2, /* Register holding operands */
  91503. int dest, /* Jump here if true. */
  91504. int jumpIfNull /* If true, jump if either operand is NULL */
  91505. ){
  91506. int p5;
  91507. int addr;
  91508. CollSeq *p4;
  91509. p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
  91510. p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
  91511. addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
  91512. (void*)p4, P4_COLLSEQ);
  91513. sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
  91514. return addr;
  91515. }
  91516. /*
  91517. ** Return true if expression pExpr is a vector, or false otherwise.
  91518. **
  91519. ** A vector is defined as any expression that results in two or more
  91520. ** columns of result. Every TK_VECTOR node is an vector because the
  91521. ** parser will not generate a TK_VECTOR with fewer than two entries.
  91522. ** But a TK_SELECT might be either a vector or a scalar. It is only
  91523. ** considered a vector if it has two or more result columns.
  91524. */
  91525. SQLITE_PRIVATE int sqlite3ExprIsVector(Expr *pExpr){
  91526. return sqlite3ExprVectorSize(pExpr)>1;
  91527. }
  91528. /*
  91529. ** If the expression passed as the only argument is of type TK_VECTOR
  91530. ** return the number of expressions in the vector. Or, if the expression
  91531. ** is a sub-select, return the number of columns in the sub-select. For
  91532. ** any other type of expression, return 1.
  91533. */
  91534. SQLITE_PRIVATE int sqlite3ExprVectorSize(Expr *pExpr){
  91535. u8 op = pExpr->op;
  91536. if( op==TK_REGISTER ) op = pExpr->op2;
  91537. if( op==TK_VECTOR ){
  91538. return pExpr->x.pList->nExpr;
  91539. }else if( op==TK_SELECT ){
  91540. return pExpr->x.pSelect->pEList->nExpr;
  91541. }else{
  91542. return 1;
  91543. }
  91544. }
  91545. /*
  91546. ** Return a pointer to a subexpression of pVector that is the i-th
  91547. ** column of the vector (numbered starting with 0). The caller must
  91548. ** ensure that i is within range.
  91549. **
  91550. ** If pVector is really a scalar (and "scalar" here includes subqueries
  91551. ** that return a single column!) then return pVector unmodified.
  91552. **
  91553. ** pVector retains ownership of the returned subexpression.
  91554. **
  91555. ** If the vector is a (SELECT ...) then the expression returned is
  91556. ** just the expression for the i-th term of the result set, and may
  91557. ** not be ready for evaluation because the table cursor has not yet
  91558. ** been positioned.
  91559. */
  91560. SQLITE_PRIVATE Expr *sqlite3VectorFieldSubexpr(Expr *pVector, int i){
  91561. assert( i<sqlite3ExprVectorSize(pVector) );
  91562. if( sqlite3ExprIsVector(pVector) ){
  91563. assert( pVector->op2==0 || pVector->op==TK_REGISTER );
  91564. if( pVector->op==TK_SELECT || pVector->op2==TK_SELECT ){
  91565. return pVector->x.pSelect->pEList->a[i].pExpr;
  91566. }else{
  91567. return pVector->x.pList->a[i].pExpr;
  91568. }
  91569. }
  91570. return pVector;
  91571. }
  91572. /*
  91573. ** Compute and return a new Expr object which when passed to
  91574. ** sqlite3ExprCode() will generate all necessary code to compute
  91575. ** the iField-th column of the vector expression pVector.
  91576. **
  91577. ** It is ok for pVector to be a scalar (as long as iField==0).
  91578. ** In that case, this routine works like sqlite3ExprDup().
  91579. **
  91580. ** The caller owns the returned Expr object and is responsible for
  91581. ** ensuring that the returned value eventually gets freed.
  91582. **
  91583. ** The caller retains ownership of pVector. If pVector is a TK_SELECT,
  91584. ** then the returned object will reference pVector and so pVector must remain
  91585. ** valid for the life of the returned object. If pVector is a TK_VECTOR
  91586. ** or a scalar expression, then it can be deleted as soon as this routine
  91587. ** returns.
  91588. **
  91589. ** A trick to cause a TK_SELECT pVector to be deleted together with
  91590. ** the returned Expr object is to attach the pVector to the pRight field
  91591. ** of the returned TK_SELECT_COLUMN Expr object.
  91592. */
  91593. SQLITE_PRIVATE Expr *sqlite3ExprForVectorField(
  91594. Parse *pParse, /* Parsing context */
  91595. Expr *pVector, /* The vector. List of expressions or a sub-SELECT */
  91596. int iField /* Which column of the vector to return */
  91597. ){
  91598. Expr *pRet;
  91599. if( pVector->op==TK_SELECT ){
  91600. assert( pVector->flags & EP_xIsSelect );
  91601. /* The TK_SELECT_COLUMN Expr node:
  91602. **
  91603. ** pLeft: pVector containing TK_SELECT. Not deleted.
  91604. ** pRight: not used. But recursively deleted.
  91605. ** iColumn: Index of a column in pVector
  91606. ** iTable: 0 or the number of columns on the LHS of an assignment
  91607. ** pLeft->iTable: First in an array of register holding result, or 0
  91608. ** if the result is not yet computed.
  91609. **
  91610. ** sqlite3ExprDelete() specifically skips the recursive delete of
  91611. ** pLeft on TK_SELECT_COLUMN nodes. But pRight is followed, so pVector
  91612. ** can be attached to pRight to cause this node to take ownership of
  91613. ** pVector. Typically there will be multiple TK_SELECT_COLUMN nodes
  91614. ** with the same pLeft pointer to the pVector, but only one of them
  91615. ** will own the pVector.
  91616. */
  91617. pRet = sqlite3PExpr(pParse, TK_SELECT_COLUMN, 0, 0);
  91618. if( pRet ){
  91619. pRet->iColumn = iField;
  91620. pRet->pLeft = pVector;
  91621. }
  91622. assert( pRet==0 || pRet->iTable==0 );
  91623. }else{
  91624. if( pVector->op==TK_VECTOR ) pVector = pVector->x.pList->a[iField].pExpr;
  91625. pRet = sqlite3ExprDup(pParse->db, pVector, 0);
  91626. sqlite3RenameTokenRemap(pParse, pRet, pVector);
  91627. }
  91628. return pRet;
  91629. }
  91630. /*
  91631. ** If expression pExpr is of type TK_SELECT, generate code to evaluate
  91632. ** it. Return the register in which the result is stored (or, if the
  91633. ** sub-select returns more than one column, the first in an array
  91634. ** of registers in which the result is stored).
  91635. **
  91636. ** If pExpr is not a TK_SELECT expression, return 0.
  91637. */
  91638. static int exprCodeSubselect(Parse *pParse, Expr *pExpr){
  91639. int reg = 0;
  91640. #ifndef SQLITE_OMIT_SUBQUERY
  91641. if( pExpr->op==TK_SELECT ){
  91642. reg = sqlite3CodeSubselect(pParse, pExpr);
  91643. }
  91644. #endif
  91645. return reg;
  91646. }
  91647. /*
  91648. ** Argument pVector points to a vector expression - either a TK_VECTOR
  91649. ** or TK_SELECT that returns more than one column. This function returns
  91650. ** the register number of a register that contains the value of
  91651. ** element iField of the vector.
  91652. **
  91653. ** If pVector is a TK_SELECT expression, then code for it must have
  91654. ** already been generated using the exprCodeSubselect() routine. In this
  91655. ** case parameter regSelect should be the first in an array of registers
  91656. ** containing the results of the sub-select.
  91657. **
  91658. ** If pVector is of type TK_VECTOR, then code for the requested field
  91659. ** is generated. In this case (*pRegFree) may be set to the number of
  91660. ** a temporary register to be freed by the caller before returning.
  91661. **
  91662. ** Before returning, output parameter (*ppExpr) is set to point to the
  91663. ** Expr object corresponding to element iElem of the vector.
  91664. */
  91665. static int exprVectorRegister(
  91666. Parse *pParse, /* Parse context */
  91667. Expr *pVector, /* Vector to extract element from */
  91668. int iField, /* Field to extract from pVector */
  91669. int regSelect, /* First in array of registers */
  91670. Expr **ppExpr, /* OUT: Expression element */
  91671. int *pRegFree /* OUT: Temp register to free */
  91672. ){
  91673. u8 op = pVector->op;
  91674. assert( op==TK_VECTOR || op==TK_REGISTER || op==TK_SELECT );
  91675. if( op==TK_REGISTER ){
  91676. *ppExpr = sqlite3VectorFieldSubexpr(pVector, iField);
  91677. return pVector->iTable+iField;
  91678. }
  91679. if( op==TK_SELECT ){
  91680. *ppExpr = pVector->x.pSelect->pEList->a[iField].pExpr;
  91681. return regSelect+iField;
  91682. }
  91683. *ppExpr = pVector->x.pList->a[iField].pExpr;
  91684. return sqlite3ExprCodeTemp(pParse, *ppExpr, pRegFree);
  91685. }
  91686. /*
  91687. ** Expression pExpr is a comparison between two vector values. Compute
  91688. ** the result of the comparison (1, 0, or NULL) and write that
  91689. ** result into register dest.
  91690. **
  91691. ** The caller must satisfy the following preconditions:
  91692. **
  91693. ** if pExpr->op==TK_IS: op==TK_EQ and p5==SQLITE_NULLEQ
  91694. ** if pExpr->op==TK_ISNOT: op==TK_NE and p5==SQLITE_NULLEQ
  91695. ** otherwise: op==pExpr->op and p5==0
  91696. */
  91697. static void codeVectorCompare(
  91698. Parse *pParse, /* Code generator context */
  91699. Expr *pExpr, /* The comparison operation */
  91700. int dest, /* Write results into this register */
  91701. u8 op, /* Comparison operator */
  91702. u8 p5 /* SQLITE_NULLEQ or zero */
  91703. ){
  91704. Vdbe *v = pParse->pVdbe;
  91705. Expr *pLeft = pExpr->pLeft;
  91706. Expr *pRight = pExpr->pRight;
  91707. int nLeft = sqlite3ExprVectorSize(pLeft);
  91708. int i;
  91709. int regLeft = 0;
  91710. int regRight = 0;
  91711. u8 opx = op;
  91712. int addrDone = sqlite3VdbeMakeLabel(pParse);
  91713. if( nLeft!=sqlite3ExprVectorSize(pRight) ){
  91714. sqlite3ErrorMsg(pParse, "row value misused");
  91715. return;
  91716. }
  91717. assert( pExpr->op==TK_EQ || pExpr->op==TK_NE
  91718. || pExpr->op==TK_IS || pExpr->op==TK_ISNOT
  91719. || pExpr->op==TK_LT || pExpr->op==TK_GT
  91720. || pExpr->op==TK_LE || pExpr->op==TK_GE
  91721. );
  91722. assert( pExpr->op==op || (pExpr->op==TK_IS && op==TK_EQ)
  91723. || (pExpr->op==TK_ISNOT && op==TK_NE) );
  91724. assert( p5==0 || pExpr->op!=op );
  91725. assert( p5==SQLITE_NULLEQ || pExpr->op==op );
  91726. p5 |= SQLITE_STOREP2;
  91727. if( opx==TK_LE ) opx = TK_LT;
  91728. if( opx==TK_GE ) opx = TK_GT;
  91729. regLeft = exprCodeSubselect(pParse, pLeft);
  91730. regRight = exprCodeSubselect(pParse, pRight);
  91731. for(i=0; 1 /*Loop exits by "break"*/; i++){
  91732. int regFree1 = 0, regFree2 = 0;
  91733. Expr *pL, *pR;
  91734. int r1, r2;
  91735. assert( i>=0 && i<nLeft );
  91736. r1 = exprVectorRegister(pParse, pLeft, i, regLeft, &pL, &regFree1);
  91737. r2 = exprVectorRegister(pParse, pRight, i, regRight, &pR, &regFree2);
  91738. codeCompare(pParse, pL, pR, opx, r1, r2, dest, p5);
  91739. testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
  91740. testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
  91741. testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
  91742. testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
  91743. testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
  91744. testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
  91745. sqlite3ReleaseTempReg(pParse, regFree1);
  91746. sqlite3ReleaseTempReg(pParse, regFree2);
  91747. if( i==nLeft-1 ){
  91748. break;
  91749. }
  91750. if( opx==TK_EQ ){
  91751. sqlite3VdbeAddOp2(v, OP_IfNot, dest, addrDone); VdbeCoverage(v);
  91752. p5 |= SQLITE_KEEPNULL;
  91753. }else if( opx==TK_NE ){
  91754. sqlite3VdbeAddOp2(v, OP_If, dest, addrDone); VdbeCoverage(v);
  91755. p5 |= SQLITE_KEEPNULL;
  91756. }else{
  91757. assert( op==TK_LT || op==TK_GT || op==TK_LE || op==TK_GE );
  91758. sqlite3VdbeAddOp2(v, OP_ElseNotEq, 0, addrDone);
  91759. VdbeCoverageIf(v, op==TK_LT);
  91760. VdbeCoverageIf(v, op==TK_GT);
  91761. VdbeCoverageIf(v, op==TK_LE);
  91762. VdbeCoverageIf(v, op==TK_GE);
  91763. if( i==nLeft-2 ) opx = op;
  91764. }
  91765. }
  91766. sqlite3VdbeResolveLabel(v, addrDone);
  91767. }
  91768. #if SQLITE_MAX_EXPR_DEPTH>0
  91769. /*
  91770. ** Check that argument nHeight is less than or equal to the maximum
  91771. ** expression depth allowed. If it is not, leave an error message in
  91772. ** pParse.
  91773. */
  91774. SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
  91775. int rc = SQLITE_OK;
  91776. int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
  91777. if( nHeight>mxHeight ){
  91778. sqlite3ErrorMsg(pParse,
  91779. "Expression tree is too large (maximum depth %d)", mxHeight
  91780. );
  91781. rc = SQLITE_ERROR;
  91782. }
  91783. return rc;
  91784. }
  91785. /* The following three functions, heightOfExpr(), heightOfExprList()
  91786. ** and heightOfSelect(), are used to determine the maximum height
  91787. ** of any expression tree referenced by the structure passed as the
  91788. ** first argument.
  91789. **
  91790. ** If this maximum height is greater than the current value pointed
  91791. ** to by pnHeight, the second parameter, then set *pnHeight to that
  91792. ** value.
  91793. */
  91794. static void heightOfExpr(Expr *p, int *pnHeight){
  91795. if( p ){
  91796. if( p->nHeight>*pnHeight ){
  91797. *pnHeight = p->nHeight;
  91798. }
  91799. }
  91800. }
  91801. static void heightOfExprList(ExprList *p, int *pnHeight){
  91802. if( p ){
  91803. int i;
  91804. for(i=0; i<p->nExpr; i++){
  91805. heightOfExpr(p->a[i].pExpr, pnHeight);
  91806. }
  91807. }
  91808. }
  91809. static void heightOfSelect(Select *pSelect, int *pnHeight){
  91810. Select *p;
  91811. for(p=pSelect; p; p=p->pPrior){
  91812. heightOfExpr(p->pWhere, pnHeight);
  91813. heightOfExpr(p->pHaving, pnHeight);
  91814. heightOfExpr(p->pLimit, pnHeight);
  91815. heightOfExprList(p->pEList, pnHeight);
  91816. heightOfExprList(p->pGroupBy, pnHeight);
  91817. heightOfExprList(p->pOrderBy, pnHeight);
  91818. }
  91819. }
  91820. /*
  91821. ** Set the Expr.nHeight variable in the structure passed as an
  91822. ** argument. An expression with no children, Expr.pList or
  91823. ** Expr.pSelect member has a height of 1. Any other expression
  91824. ** has a height equal to the maximum height of any other
  91825. ** referenced Expr plus one.
  91826. **
  91827. ** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
  91828. ** if appropriate.
  91829. */
  91830. static void exprSetHeight(Expr *p){
  91831. int nHeight = 0;
  91832. heightOfExpr(p->pLeft, &nHeight);
  91833. heightOfExpr(p->pRight, &nHeight);
  91834. if( ExprHasProperty(p, EP_xIsSelect) ){
  91835. heightOfSelect(p->x.pSelect, &nHeight);
  91836. }else if( p->x.pList ){
  91837. heightOfExprList(p->x.pList, &nHeight);
  91838. p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
  91839. }
  91840. p->nHeight = nHeight + 1;
  91841. }
  91842. /*
  91843. ** Set the Expr.nHeight variable using the exprSetHeight() function. If
  91844. ** the height is greater than the maximum allowed expression depth,
  91845. ** leave an error in pParse.
  91846. **
  91847. ** Also propagate all EP_Propagate flags from the Expr.x.pList into
  91848. ** Expr.flags.
  91849. */
  91850. SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
  91851. if( pParse->nErr ) return;
  91852. exprSetHeight(p);
  91853. sqlite3ExprCheckHeight(pParse, p->nHeight);
  91854. }
  91855. /*
  91856. ** Return the maximum height of any expression tree referenced
  91857. ** by the select statement passed as an argument.
  91858. */
  91859. SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
  91860. int nHeight = 0;
  91861. heightOfSelect(p, &nHeight);
  91862. return nHeight;
  91863. }
  91864. #else /* ABOVE: Height enforcement enabled. BELOW: Height enforcement off */
  91865. /*
  91866. ** Propagate all EP_Propagate flags from the Expr.x.pList into
  91867. ** Expr.flags.
  91868. */
  91869. SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
  91870. if( p && p->x.pList && !ExprHasProperty(p, EP_xIsSelect) ){
  91871. p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
  91872. }
  91873. }
  91874. #define exprSetHeight(y)
  91875. #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
  91876. /*
  91877. ** This routine is the core allocator for Expr nodes.
  91878. **
  91879. ** Construct a new expression node and return a pointer to it. Memory
  91880. ** for this node and for the pToken argument is a single allocation
  91881. ** obtained from sqlite3DbMalloc(). The calling function
  91882. ** is responsible for making sure the node eventually gets freed.
  91883. **
  91884. ** If dequote is true, then the token (if it exists) is dequoted.
  91885. ** If dequote is false, no dequoting is performed. The deQuote
  91886. ** parameter is ignored if pToken is NULL or if the token does not
  91887. ** appear to be quoted. If the quotes were of the form "..." (double-quotes)
  91888. ** then the EP_DblQuoted flag is set on the expression node.
  91889. **
  91890. ** Special case: If op==TK_INTEGER and pToken points to a string that
  91891. ** can be translated into a 32-bit integer, then the token is not
  91892. ** stored in u.zToken. Instead, the integer values is written
  91893. ** into u.iValue and the EP_IntValue flag is set. No extra storage
  91894. ** is allocated to hold the integer text and the dequote flag is ignored.
  91895. */
  91896. SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
  91897. sqlite3 *db, /* Handle for sqlite3DbMallocRawNN() */
  91898. int op, /* Expression opcode */
  91899. const Token *pToken, /* Token argument. Might be NULL */
  91900. int dequote /* True to dequote */
  91901. ){
  91902. Expr *pNew;
  91903. int nExtra = 0;
  91904. int iValue = 0;
  91905. assert( db!=0 );
  91906. if( pToken ){
  91907. if( op!=TK_INTEGER || pToken->z==0
  91908. || sqlite3GetInt32(pToken->z, &iValue)==0 ){
  91909. nExtra = pToken->n+1;
  91910. assert( iValue>=0 );
  91911. }
  91912. }
  91913. pNew = sqlite3DbMallocRawNN(db, sizeof(Expr)+nExtra);
  91914. if( pNew ){
  91915. memset(pNew, 0, sizeof(Expr));
  91916. pNew->op = (u8)op;
  91917. pNew->iAgg = -1;
  91918. if( pToken ){
  91919. if( nExtra==0 ){
  91920. pNew->flags |= EP_IntValue|EP_Leaf|(iValue?EP_IsTrue:EP_IsFalse);
  91921. pNew->u.iValue = iValue;
  91922. }else{
  91923. pNew->u.zToken = (char*)&pNew[1];
  91924. assert( pToken->z!=0 || pToken->n==0 );
  91925. if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
  91926. pNew->u.zToken[pToken->n] = 0;
  91927. if( dequote && sqlite3Isquote(pNew->u.zToken[0]) ){
  91928. sqlite3DequoteExpr(pNew);
  91929. }
  91930. }
  91931. }
  91932. #if SQLITE_MAX_EXPR_DEPTH>0
  91933. pNew->nHeight = 1;
  91934. #endif
  91935. }
  91936. return pNew;
  91937. }
  91938. /*
  91939. ** Allocate a new expression node from a zero-terminated token that has
  91940. ** already been dequoted.
  91941. */
  91942. SQLITE_PRIVATE Expr *sqlite3Expr(
  91943. sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
  91944. int op, /* Expression opcode */
  91945. const char *zToken /* Token argument. Might be NULL */
  91946. ){
  91947. Token x;
  91948. x.z = zToken;
  91949. x.n = sqlite3Strlen30(zToken);
  91950. return sqlite3ExprAlloc(db, op, &x, 0);
  91951. }
  91952. /*
  91953. ** Attach subtrees pLeft and pRight to the Expr node pRoot.
  91954. **
  91955. ** If pRoot==NULL that means that a memory allocation error has occurred.
  91956. ** In that case, delete the subtrees pLeft and pRight.
  91957. */
  91958. SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
  91959. sqlite3 *db,
  91960. Expr *pRoot,
  91961. Expr *pLeft,
  91962. Expr *pRight
  91963. ){
  91964. if( pRoot==0 ){
  91965. assert( db->mallocFailed );
  91966. sqlite3ExprDelete(db, pLeft);
  91967. sqlite3ExprDelete(db, pRight);
  91968. }else{
  91969. if( pRight ){
  91970. pRoot->pRight = pRight;
  91971. pRoot->flags |= EP_Propagate & pRight->flags;
  91972. }
  91973. if( pLeft ){
  91974. pRoot->pLeft = pLeft;
  91975. pRoot->flags |= EP_Propagate & pLeft->flags;
  91976. }
  91977. exprSetHeight(pRoot);
  91978. }
  91979. }
  91980. /*
  91981. ** Allocate an Expr node which joins as many as two subtrees.
  91982. **
  91983. ** One or both of the subtrees can be NULL. Return a pointer to the new
  91984. ** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
  91985. ** free the subtrees and return NULL.
  91986. */
  91987. SQLITE_PRIVATE Expr *sqlite3PExpr(
  91988. Parse *pParse, /* Parsing context */
  91989. int op, /* Expression opcode */
  91990. Expr *pLeft, /* Left operand */
  91991. Expr *pRight /* Right operand */
  91992. ){
  91993. Expr *p;
  91994. p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr));
  91995. if( p ){
  91996. memset(p, 0, sizeof(Expr));
  91997. p->op = op & 0xff;
  91998. p->iAgg = -1;
  91999. sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
  92000. sqlite3ExprCheckHeight(pParse, p->nHeight);
  92001. }else{
  92002. sqlite3ExprDelete(pParse->db, pLeft);
  92003. sqlite3ExprDelete(pParse->db, pRight);
  92004. }
  92005. return p;
  92006. }
  92007. /*
  92008. ** Add pSelect to the Expr.x.pSelect field. Or, if pExpr is NULL (due
  92009. ** do a memory allocation failure) then delete the pSelect object.
  92010. */
  92011. SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse *pParse, Expr *pExpr, Select *pSelect){
  92012. if( pExpr ){
  92013. pExpr->x.pSelect = pSelect;
  92014. ExprSetProperty(pExpr, EP_xIsSelect|EP_Subquery);
  92015. sqlite3ExprSetHeightAndFlags(pParse, pExpr);
  92016. }else{
  92017. assert( pParse->db->mallocFailed );
  92018. sqlite3SelectDelete(pParse->db, pSelect);
  92019. }
  92020. }
  92021. /*
  92022. ** Join two expressions using an AND operator. If either expression is
  92023. ** NULL, then just return the other expression.
  92024. **
  92025. ** If one side or the other of the AND is known to be false, then instead
  92026. ** of returning an AND expression, just return a constant expression with
  92027. ** a value of false.
  92028. */
  92029. SQLITE_PRIVATE Expr *sqlite3ExprAnd(Parse *pParse, Expr *pLeft, Expr *pRight){
  92030. sqlite3 *db = pParse->db;
  92031. if( pLeft==0 ){
  92032. return pRight;
  92033. }else if( pRight==0 ){
  92034. return pLeft;
  92035. }else if( ExprAlwaysFalse(pLeft) || ExprAlwaysFalse(pRight) ){
  92036. sqlite3ExprUnmapAndDelete(pParse, pLeft);
  92037. sqlite3ExprUnmapAndDelete(pParse, pRight);
  92038. return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
  92039. }else{
  92040. return sqlite3PExpr(pParse, TK_AND, pLeft, pRight);
  92041. }
  92042. }
  92043. /*
  92044. ** Construct a new expression node for a function with multiple
  92045. ** arguments.
  92046. */
  92047. SQLITE_PRIVATE Expr *sqlite3ExprFunction(
  92048. Parse *pParse, /* Parsing context */
  92049. ExprList *pList, /* Argument list */
  92050. Token *pToken, /* Name of the function */
  92051. int eDistinct /* SF_Distinct or SF_ALL or 0 */
  92052. ){
  92053. Expr *pNew;
  92054. sqlite3 *db = pParse->db;
  92055. assert( pToken );
  92056. pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
  92057. if( pNew==0 ){
  92058. sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
  92059. return 0;
  92060. }
  92061. if( pList && pList->nExpr > pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
  92062. sqlite3ErrorMsg(pParse, "too many arguments on function %T", pToken);
  92063. }
  92064. pNew->x.pList = pList;
  92065. ExprSetProperty(pNew, EP_HasFunc);
  92066. assert( !ExprHasProperty(pNew, EP_xIsSelect) );
  92067. sqlite3ExprSetHeightAndFlags(pParse, pNew);
  92068. if( eDistinct==SF_Distinct ) ExprSetProperty(pNew, EP_Distinct);
  92069. return pNew;
  92070. }
  92071. /*
  92072. ** Assign a variable number to an expression that encodes a wildcard
  92073. ** in the original SQL statement.
  92074. **
  92075. ** Wildcards consisting of a single "?" are assigned the next sequential
  92076. ** variable number.
  92077. **
  92078. ** Wildcards of the form "?nnn" are assigned the number "nnn". We make
  92079. ** sure "nnn" is not too big to avoid a denial of service attack when
  92080. ** the SQL statement comes from an external source.
  92081. **
  92082. ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
  92083. ** as the previous instance of the same wildcard. Or if this is the first
  92084. ** instance of the wildcard, the next sequential variable number is
  92085. ** assigned.
  92086. */
  92087. SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr, u32 n){
  92088. sqlite3 *db = pParse->db;
  92089. const char *z;
  92090. ynVar x;
  92091. if( pExpr==0 ) return;
  92092. assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
  92093. z = pExpr->u.zToken;
  92094. assert( z!=0 );
  92095. assert( z[0]!=0 );
  92096. assert( n==(u32)sqlite3Strlen30(z) );
  92097. if( z[1]==0 ){
  92098. /* Wildcard of the form "?". Assign the next variable number */
  92099. assert( z[0]=='?' );
  92100. x = (ynVar)(++pParse->nVar);
  92101. }else{
  92102. int doAdd = 0;
  92103. if( z[0]=='?' ){
  92104. /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
  92105. ** use it as the variable number */
  92106. i64 i;
  92107. int bOk;
  92108. if( n==2 ){ /*OPTIMIZATION-IF-TRUE*/
  92109. i = z[1]-'0'; /* The common case of ?N for a single digit N */
  92110. bOk = 1;
  92111. }else{
  92112. bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
  92113. }
  92114. testcase( i==0 );
  92115. testcase( i==1 );
  92116. testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
  92117. testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
  92118. if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
  92119. sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
  92120. db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
  92121. return;
  92122. }
  92123. x = (ynVar)i;
  92124. if( x>pParse->nVar ){
  92125. pParse->nVar = (int)x;
  92126. doAdd = 1;
  92127. }else if( sqlite3VListNumToName(pParse->pVList, x)==0 ){
  92128. doAdd = 1;
  92129. }
  92130. }else{
  92131. /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable
  92132. ** number as the prior appearance of the same name, or if the name
  92133. ** has never appeared before, reuse the same variable number
  92134. */
  92135. x = (ynVar)sqlite3VListNameToNum(pParse->pVList, z, n);
  92136. if( x==0 ){
  92137. x = (ynVar)(++pParse->nVar);
  92138. doAdd = 1;
  92139. }
  92140. }
  92141. if( doAdd ){
  92142. pParse->pVList = sqlite3VListAdd(db, pParse->pVList, z, n, x);
  92143. }
  92144. }
  92145. pExpr->iColumn = x;
  92146. if( x>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
  92147. sqlite3ErrorMsg(pParse, "too many SQL variables");
  92148. }
  92149. }
  92150. /*
  92151. ** Recursively delete an expression tree.
  92152. */
  92153. static SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p){
  92154. assert( p!=0 );
  92155. /* Sanity check: Assert that the IntValue is non-negative if it exists */
  92156. assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
  92157. assert( !ExprHasProperty(p, EP_WinFunc) || p->y.pWin!=0 || db->mallocFailed );
  92158. assert( p->op!=TK_FUNCTION || ExprHasProperty(p, EP_TokenOnly|EP_Reduced)
  92159. || p->y.pWin==0 || ExprHasProperty(p, EP_WinFunc) );
  92160. #ifdef SQLITE_DEBUG
  92161. if( ExprHasProperty(p, EP_Leaf) && !ExprHasProperty(p, EP_TokenOnly) ){
  92162. assert( p->pLeft==0 );
  92163. assert( p->pRight==0 );
  92164. assert( p->x.pSelect==0 );
  92165. }
  92166. #endif
  92167. if( !ExprHasProperty(p, (EP_TokenOnly|EP_Leaf)) ){
  92168. /* The Expr.x union is never used at the same time as Expr.pRight */
  92169. assert( p->x.pList==0 || p->pRight==0 );
  92170. if( p->pLeft && p->op!=TK_SELECT_COLUMN ) sqlite3ExprDeleteNN(db, p->pLeft);
  92171. if( p->pRight ){
  92172. sqlite3ExprDeleteNN(db, p->pRight);
  92173. }else if( ExprHasProperty(p, EP_xIsSelect) ){
  92174. sqlite3SelectDelete(db, p->x.pSelect);
  92175. }else{
  92176. sqlite3ExprListDelete(db, p->x.pList);
  92177. }
  92178. if( ExprHasProperty(p, EP_WinFunc) ){
  92179. assert( p->op==TK_FUNCTION );
  92180. sqlite3WindowDelete(db, p->y.pWin);
  92181. }
  92182. }
  92183. if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
  92184. if( !ExprHasProperty(p, EP_Static) ){
  92185. sqlite3DbFreeNN(db, p);
  92186. }
  92187. }
  92188. SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
  92189. if( p ) sqlite3ExprDeleteNN(db, p);
  92190. }
  92191. /* Invoke sqlite3RenameExprUnmap() and sqlite3ExprDelete() on the
  92192. ** expression.
  92193. */
  92194. SQLITE_PRIVATE void sqlite3ExprUnmapAndDelete(Parse *pParse, Expr *p){
  92195. if( p ){
  92196. if( IN_RENAME_OBJECT ){
  92197. sqlite3RenameExprUnmap(pParse, p);
  92198. }
  92199. sqlite3ExprDeleteNN(pParse->db, p);
  92200. }
  92201. }
  92202. /*
  92203. ** Return the number of bytes allocated for the expression structure
  92204. ** passed as the first argument. This is always one of EXPR_FULLSIZE,
  92205. ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
  92206. */
  92207. static int exprStructSize(Expr *p){
  92208. if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
  92209. if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
  92210. return EXPR_FULLSIZE;
  92211. }
  92212. /*
  92213. ** Copy the complete content of an Expr node, taking care not to read
  92214. ** past the end of the structure for a reduced-size version of the source
  92215. ** Expr.
  92216. */
  92217. static void exprNodeCopy(Expr *pDest, Expr *pSrc){
  92218. memset(pDest, 0, sizeof(Expr));
  92219. memcpy(pDest, pSrc, exprStructSize(pSrc));
  92220. }
  92221. /*
  92222. ** The dupedExpr*Size() routines each return the number of bytes required
  92223. ** to store a copy of an expression or expression tree. They differ in
  92224. ** how much of the tree is measured.
  92225. **
  92226. ** dupedExprStructSize() Size of only the Expr structure
  92227. ** dupedExprNodeSize() Size of Expr + space for token
  92228. ** dupedExprSize() Expr + token + subtree components
  92229. **
  92230. ***************************************************************************
  92231. **
  92232. ** The dupedExprStructSize() function returns two values OR-ed together:
  92233. ** (1) the space required for a copy of the Expr structure only and
  92234. ** (2) the EP_xxx flags that indicate what the structure size should be.
  92235. ** The return values is always one of:
  92236. **
  92237. ** EXPR_FULLSIZE
  92238. ** EXPR_REDUCEDSIZE | EP_Reduced
  92239. ** EXPR_TOKENONLYSIZE | EP_TokenOnly
  92240. **
  92241. ** The size of the structure can be found by masking the return value
  92242. ** of this routine with 0xfff. The flags can be found by masking the
  92243. ** return value with EP_Reduced|EP_TokenOnly.
  92244. **
  92245. ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
  92246. ** (unreduced) Expr objects as they or originally constructed by the parser.
  92247. ** During expression analysis, extra information is computed and moved into
  92248. ** later parts of the Expr object and that extra information might get chopped
  92249. ** off if the expression is reduced. Note also that it does not work to
  92250. ** make an EXPRDUP_REDUCE copy of a reduced expression. It is only legal
  92251. ** to reduce a pristine expression tree from the parser. The implementation
  92252. ** of dupedExprStructSize() contain multiple assert() statements that attempt
  92253. ** to enforce this constraint.
  92254. */
  92255. static int dupedExprStructSize(Expr *p, int flags){
  92256. int nSize;
  92257. assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
  92258. assert( EXPR_FULLSIZE<=0xfff );
  92259. assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
  92260. if( 0==flags || p->op==TK_SELECT_COLUMN
  92261. #ifndef SQLITE_OMIT_WINDOWFUNC
  92262. || ExprHasProperty(p, EP_WinFunc)
  92263. #endif
  92264. ){
  92265. nSize = EXPR_FULLSIZE;
  92266. }else{
  92267. assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
  92268. assert( !ExprHasProperty(p, EP_FromJoin) );
  92269. assert( !ExprHasProperty(p, EP_MemToken) );
  92270. assert( !ExprHasProperty(p, EP_NoReduce) );
  92271. if( p->pLeft || p->x.pList ){
  92272. nSize = EXPR_REDUCEDSIZE | EP_Reduced;
  92273. }else{
  92274. assert( p->pRight==0 );
  92275. nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
  92276. }
  92277. }
  92278. return nSize;
  92279. }
  92280. /*
  92281. ** This function returns the space in bytes required to store the copy
  92282. ** of the Expr structure and a copy of the Expr.u.zToken string (if that
  92283. ** string is defined.)
  92284. */
  92285. static int dupedExprNodeSize(Expr *p, int flags){
  92286. int nByte = dupedExprStructSize(p, flags) & 0xfff;
  92287. if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
  92288. nByte += sqlite3Strlen30NN(p->u.zToken)+1;
  92289. }
  92290. return ROUND8(nByte);
  92291. }
  92292. /*
  92293. ** Return the number of bytes required to create a duplicate of the
  92294. ** expression passed as the first argument. The second argument is a
  92295. ** mask containing EXPRDUP_XXX flags.
  92296. **
  92297. ** The value returned includes space to create a copy of the Expr struct
  92298. ** itself and the buffer referred to by Expr.u.zToken, if any.
  92299. **
  92300. ** If the EXPRDUP_REDUCE flag is set, then the return value includes
  92301. ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
  92302. ** and Expr.pRight variables (but not for any structures pointed to or
  92303. ** descended from the Expr.x.pList or Expr.x.pSelect variables).
  92304. */
  92305. static int dupedExprSize(Expr *p, int flags){
  92306. int nByte = 0;
  92307. if( p ){
  92308. nByte = dupedExprNodeSize(p, flags);
  92309. if( flags&EXPRDUP_REDUCE ){
  92310. nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
  92311. }
  92312. }
  92313. return nByte;
  92314. }
  92315. /*
  92316. ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
  92317. ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
  92318. ** to store the copy of expression p, the copies of p->u.zToken
  92319. ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
  92320. ** if any. Before returning, *pzBuffer is set to the first byte past the
  92321. ** portion of the buffer copied into by this function.
  92322. */
  92323. static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){
  92324. Expr *pNew; /* Value to return */
  92325. u8 *zAlloc; /* Memory space from which to build Expr object */
  92326. u32 staticFlag; /* EP_Static if space not obtained from malloc */
  92327. assert( db!=0 );
  92328. assert( p );
  92329. assert( dupFlags==0 || dupFlags==EXPRDUP_REDUCE );
  92330. assert( pzBuffer==0 || dupFlags==EXPRDUP_REDUCE );
  92331. /* Figure out where to write the new Expr structure. */
  92332. if( pzBuffer ){
  92333. zAlloc = *pzBuffer;
  92334. staticFlag = EP_Static;
  92335. }else{
  92336. zAlloc = sqlite3DbMallocRawNN(db, dupedExprSize(p, dupFlags));
  92337. staticFlag = 0;
  92338. }
  92339. pNew = (Expr *)zAlloc;
  92340. if( pNew ){
  92341. /* Set nNewSize to the size allocated for the structure pointed to
  92342. ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
  92343. ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
  92344. ** by the copy of the p->u.zToken string (if any).
  92345. */
  92346. const unsigned nStructSize = dupedExprStructSize(p, dupFlags);
  92347. const int nNewSize = nStructSize & 0xfff;
  92348. int nToken;
  92349. if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
  92350. nToken = sqlite3Strlen30(p->u.zToken) + 1;
  92351. }else{
  92352. nToken = 0;
  92353. }
  92354. if( dupFlags ){
  92355. assert( ExprHasProperty(p, EP_Reduced)==0 );
  92356. memcpy(zAlloc, p, nNewSize);
  92357. }else{
  92358. u32 nSize = (u32)exprStructSize(p);
  92359. memcpy(zAlloc, p, nSize);
  92360. if( nSize<EXPR_FULLSIZE ){
  92361. memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
  92362. }
  92363. }
  92364. /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
  92365. pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
  92366. pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
  92367. pNew->flags |= staticFlag;
  92368. /* Copy the p->u.zToken string, if any. */
  92369. if( nToken ){
  92370. char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
  92371. memcpy(zToken, p->u.zToken, nToken);
  92372. }
  92373. if( 0==((p->flags|pNew->flags) & (EP_TokenOnly|EP_Leaf)) ){
  92374. /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
  92375. if( ExprHasProperty(p, EP_xIsSelect) ){
  92376. pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, dupFlags);
  92377. }else{
  92378. pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, dupFlags);
  92379. }
  92380. }
  92381. /* Fill in pNew->pLeft and pNew->pRight. */
  92382. if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly|EP_WinFunc) ){
  92383. zAlloc += dupedExprNodeSize(p, dupFlags);
  92384. if( !ExprHasProperty(pNew, EP_TokenOnly|EP_Leaf) ){
  92385. pNew->pLeft = p->pLeft ?
  92386. exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc) : 0;
  92387. pNew->pRight = p->pRight ?
  92388. exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc) : 0;
  92389. }
  92390. #ifndef SQLITE_OMIT_WINDOWFUNC
  92391. if( ExprHasProperty(p, EP_WinFunc) ){
  92392. pNew->y.pWin = sqlite3WindowDup(db, pNew, p->y.pWin);
  92393. assert( ExprHasProperty(pNew, EP_WinFunc) );
  92394. }
  92395. #endif /* SQLITE_OMIT_WINDOWFUNC */
  92396. if( pzBuffer ){
  92397. *pzBuffer = zAlloc;
  92398. }
  92399. }else{
  92400. if( !ExprHasProperty(p, EP_TokenOnly|EP_Leaf) ){
  92401. if( pNew->op==TK_SELECT_COLUMN ){
  92402. pNew->pLeft = p->pLeft;
  92403. assert( p->iColumn==0 || p->pRight==0 );
  92404. assert( p->pRight==0 || p->pRight==p->pLeft );
  92405. }else{
  92406. pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
  92407. }
  92408. pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
  92409. }
  92410. }
  92411. }
  92412. return pNew;
  92413. }
  92414. /*
  92415. ** Create and return a deep copy of the object passed as the second
  92416. ** argument. If an OOM condition is encountered, NULL is returned
  92417. ** and the db->mallocFailed flag set.
  92418. */
  92419. #ifndef SQLITE_OMIT_CTE
  92420. static With *withDup(sqlite3 *db, With *p){
  92421. With *pRet = 0;
  92422. if( p ){
  92423. sqlite3_int64 nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
  92424. pRet = sqlite3DbMallocZero(db, nByte);
  92425. if( pRet ){
  92426. int i;
  92427. pRet->nCte = p->nCte;
  92428. for(i=0; i<p->nCte; i++){
  92429. pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
  92430. pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
  92431. pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
  92432. }
  92433. }
  92434. }
  92435. return pRet;
  92436. }
  92437. #else
  92438. # define withDup(x,y) 0
  92439. #endif
  92440. #ifndef SQLITE_OMIT_WINDOWFUNC
  92441. /*
  92442. ** The gatherSelectWindows() procedure and its helper routine
  92443. ** gatherSelectWindowsCallback() are used to scan all the expressions
  92444. ** an a newly duplicated SELECT statement and gather all of the Window
  92445. ** objects found there, assembling them onto the linked list at Select->pWin.
  92446. */
  92447. static int gatherSelectWindowsCallback(Walker *pWalker, Expr *pExpr){
  92448. if( pExpr->op==TK_FUNCTION && pExpr->y.pWin!=0 ){
  92449. assert( ExprHasProperty(pExpr, EP_WinFunc) );
  92450. pExpr->y.pWin->pNextWin = pWalker->u.pSelect->pWin;
  92451. pWalker->u.pSelect->pWin = pExpr->y.pWin;
  92452. }
  92453. return WRC_Continue;
  92454. }
  92455. static int gatherSelectWindowsSelectCallback(Walker *pWalker, Select *p){
  92456. return p==pWalker->u.pSelect ? WRC_Continue : WRC_Prune;
  92457. }
  92458. static void gatherSelectWindows(Select *p){
  92459. Walker w;
  92460. w.xExprCallback = gatherSelectWindowsCallback;
  92461. w.xSelectCallback = gatherSelectWindowsSelectCallback;
  92462. w.xSelectCallback2 = 0;
  92463. w.pParse = 0;
  92464. w.u.pSelect = p;
  92465. sqlite3WalkSelect(&w, p);
  92466. }
  92467. #endif
  92468. /*
  92469. ** The following group of routines make deep copies of expressions,
  92470. ** expression lists, ID lists, and select statements. The copies can
  92471. ** be deleted (by being passed to their respective ...Delete() routines)
  92472. ** without effecting the originals.
  92473. **
  92474. ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
  92475. ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
  92476. ** by subsequent calls to sqlite*ListAppend() routines.
  92477. **
  92478. ** Any tables that the SrcList might point to are not duplicated.
  92479. **
  92480. ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
  92481. ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
  92482. ** truncated version of the usual Expr structure that will be stored as
  92483. ** part of the in-memory representation of the database schema.
  92484. */
  92485. SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
  92486. assert( flags==0 || flags==EXPRDUP_REDUCE );
  92487. return p ? exprDup(db, p, flags, 0) : 0;
  92488. }
  92489. SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
  92490. ExprList *pNew;
  92491. struct ExprList_item *pItem, *pOldItem;
  92492. int i;
  92493. Expr *pPriorSelectCol = 0;
  92494. assert( db!=0 );
  92495. if( p==0 ) return 0;
  92496. pNew = sqlite3DbMallocRawNN(db, sqlite3DbMallocSize(db, p));
  92497. if( pNew==0 ) return 0;
  92498. pNew->nExpr = p->nExpr;
  92499. pItem = pNew->a;
  92500. pOldItem = p->a;
  92501. for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
  92502. Expr *pOldExpr = pOldItem->pExpr;
  92503. Expr *pNewExpr;
  92504. pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
  92505. if( pOldExpr
  92506. && pOldExpr->op==TK_SELECT_COLUMN
  92507. && (pNewExpr = pItem->pExpr)!=0
  92508. ){
  92509. assert( pNewExpr->iColumn==0 || i>0 );
  92510. if( pNewExpr->iColumn==0 ){
  92511. assert( pOldExpr->pLeft==pOldExpr->pRight );
  92512. pPriorSelectCol = pNewExpr->pLeft = pNewExpr->pRight;
  92513. }else{
  92514. assert( i>0 );
  92515. assert( pItem[-1].pExpr!=0 );
  92516. assert( pNewExpr->iColumn==pItem[-1].pExpr->iColumn+1 );
  92517. assert( pPriorSelectCol==pItem[-1].pExpr->pLeft );
  92518. pNewExpr->pLeft = pPriorSelectCol;
  92519. }
  92520. }
  92521. pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  92522. pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
  92523. pItem->sortOrder = pOldItem->sortOrder;
  92524. pItem->done = 0;
  92525. pItem->bSpanIsTab = pOldItem->bSpanIsTab;
  92526. pItem->bSorterRef = pOldItem->bSorterRef;
  92527. pItem->u = pOldItem->u;
  92528. }
  92529. return pNew;
  92530. }
  92531. /*
  92532. ** If cursors, triggers, views and subqueries are all omitted from
  92533. ** the build, then none of the following routines, except for
  92534. ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
  92535. ** called with a NULL argument.
  92536. */
  92537. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
  92538. || !defined(SQLITE_OMIT_SUBQUERY)
  92539. SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
  92540. SrcList *pNew;
  92541. int i;
  92542. int nByte;
  92543. assert( db!=0 );
  92544. if( p==0 ) return 0;
  92545. nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
  92546. pNew = sqlite3DbMallocRawNN(db, nByte );
  92547. if( pNew==0 ) return 0;
  92548. pNew->nSrc = pNew->nAlloc = p->nSrc;
  92549. for(i=0; i<p->nSrc; i++){
  92550. struct SrcList_item *pNewItem = &pNew->a[i];
  92551. struct SrcList_item *pOldItem = &p->a[i];
  92552. Table *pTab;
  92553. pNewItem->pSchema = pOldItem->pSchema;
  92554. pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
  92555. pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  92556. pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
  92557. pNewItem->fg = pOldItem->fg;
  92558. pNewItem->iCursor = pOldItem->iCursor;
  92559. pNewItem->addrFillSub = pOldItem->addrFillSub;
  92560. pNewItem->regReturn = pOldItem->regReturn;
  92561. if( pNewItem->fg.isIndexedBy ){
  92562. pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy);
  92563. }
  92564. pNewItem->pIBIndex = pOldItem->pIBIndex;
  92565. if( pNewItem->fg.isTabFunc ){
  92566. pNewItem->u1.pFuncArg =
  92567. sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags);
  92568. }
  92569. pTab = pNewItem->pTab = pOldItem->pTab;
  92570. if( pTab ){
  92571. pTab->nTabRef++;
  92572. }
  92573. pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
  92574. pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
  92575. pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
  92576. pNewItem->colUsed = pOldItem->colUsed;
  92577. }
  92578. return pNew;
  92579. }
  92580. SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
  92581. IdList *pNew;
  92582. int i;
  92583. assert( db!=0 );
  92584. if( p==0 ) return 0;
  92585. pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
  92586. if( pNew==0 ) return 0;
  92587. pNew->nId = p->nId;
  92588. pNew->a = sqlite3DbMallocRawNN(db, p->nId*sizeof(p->a[0]) );
  92589. if( pNew->a==0 ){
  92590. sqlite3DbFreeNN(db, pNew);
  92591. return 0;
  92592. }
  92593. /* Note that because the size of the allocation for p->a[] is not
  92594. ** necessarily a power of two, sqlite3IdListAppend() may not be called
  92595. ** on the duplicate created by this function. */
  92596. for(i=0; i<p->nId; i++){
  92597. struct IdList_item *pNewItem = &pNew->a[i];
  92598. struct IdList_item *pOldItem = &p->a[i];
  92599. pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  92600. pNewItem->idx = pOldItem->idx;
  92601. }
  92602. return pNew;
  92603. }
  92604. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *pDup, int flags){
  92605. Select *pRet = 0;
  92606. Select *pNext = 0;
  92607. Select **pp = &pRet;
  92608. Select *p;
  92609. assert( db!=0 );
  92610. for(p=pDup; p; p=p->pPrior){
  92611. Select *pNew = sqlite3DbMallocRawNN(db, sizeof(*p) );
  92612. if( pNew==0 ) break;
  92613. pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
  92614. pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
  92615. pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
  92616. pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
  92617. pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
  92618. pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
  92619. pNew->op = p->op;
  92620. pNew->pNext = pNext;
  92621. pNew->pPrior = 0;
  92622. pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
  92623. pNew->iLimit = 0;
  92624. pNew->iOffset = 0;
  92625. pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
  92626. pNew->addrOpenEphm[0] = -1;
  92627. pNew->addrOpenEphm[1] = -1;
  92628. pNew->nSelectRow = p->nSelectRow;
  92629. pNew->pWith = withDup(db, p->pWith);
  92630. #ifndef SQLITE_OMIT_WINDOWFUNC
  92631. pNew->pWin = 0;
  92632. pNew->pWinDefn = sqlite3WindowListDup(db, p->pWinDefn);
  92633. if( p->pWin ) gatherSelectWindows(pNew);
  92634. #endif
  92635. pNew->selId = p->selId;
  92636. *pp = pNew;
  92637. pp = &pNew->pPrior;
  92638. pNext = pNew;
  92639. }
  92640. return pRet;
  92641. }
  92642. #else
  92643. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
  92644. assert( p==0 );
  92645. return 0;
  92646. }
  92647. #endif
  92648. /*
  92649. ** Add a new element to the end of an expression list. If pList is
  92650. ** initially NULL, then create a new expression list.
  92651. **
  92652. ** The pList argument must be either NULL or a pointer to an ExprList
  92653. ** obtained from a prior call to sqlite3ExprListAppend(). This routine
  92654. ** may not be used with an ExprList obtained from sqlite3ExprListDup().
  92655. ** Reason: This routine assumes that the number of slots in pList->a[]
  92656. ** is a power of two. That is true for sqlite3ExprListAppend() returns
  92657. ** but is not necessarily true from the return value of sqlite3ExprListDup().
  92658. **
  92659. ** If a memory allocation error occurs, the entire list is freed and
  92660. ** NULL is returned. If non-NULL is returned, then it is guaranteed
  92661. ** that the new entry was successfully appended.
  92662. */
  92663. SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
  92664. Parse *pParse, /* Parsing context */
  92665. ExprList *pList, /* List to which to append. Might be NULL */
  92666. Expr *pExpr /* Expression to be appended. Might be NULL */
  92667. ){
  92668. struct ExprList_item *pItem;
  92669. sqlite3 *db = pParse->db;
  92670. assert( db!=0 );
  92671. if( pList==0 ){
  92672. pList = sqlite3DbMallocRawNN(db, sizeof(ExprList) );
  92673. if( pList==0 ){
  92674. goto no_mem;
  92675. }
  92676. pList->nExpr = 0;
  92677. }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
  92678. ExprList *pNew;
  92679. pNew = sqlite3DbRealloc(db, pList,
  92680. sizeof(*pList)+(2*(sqlite3_int64)pList->nExpr-1)*sizeof(pList->a[0]));
  92681. if( pNew==0 ){
  92682. goto no_mem;
  92683. }
  92684. pList = pNew;
  92685. }
  92686. pItem = &pList->a[pList->nExpr++];
  92687. assert( offsetof(struct ExprList_item,zName)==sizeof(pItem->pExpr) );
  92688. assert( offsetof(struct ExprList_item,pExpr)==0 );
  92689. memset(&pItem->zName,0,sizeof(*pItem)-offsetof(struct ExprList_item,zName));
  92690. pItem->pExpr = pExpr;
  92691. return pList;
  92692. no_mem:
  92693. /* Avoid leaking memory if malloc has failed. */
  92694. sqlite3ExprDelete(db, pExpr);
  92695. sqlite3ExprListDelete(db, pList);
  92696. return 0;
  92697. }
  92698. /*
  92699. ** pColumns and pExpr form a vector assignment which is part of the SET
  92700. ** clause of an UPDATE statement. Like this:
  92701. **
  92702. ** (a,b,c) = (expr1,expr2,expr3)
  92703. ** Or: (a,b,c) = (SELECT x,y,z FROM ....)
  92704. **
  92705. ** For each term of the vector assignment, append new entries to the
  92706. ** expression list pList. In the case of a subquery on the RHS, append
  92707. ** TK_SELECT_COLUMN expressions.
  92708. */
  92709. SQLITE_PRIVATE ExprList *sqlite3ExprListAppendVector(
  92710. Parse *pParse, /* Parsing context */
  92711. ExprList *pList, /* List to which to append. Might be NULL */
  92712. IdList *pColumns, /* List of names of LHS of the assignment */
  92713. Expr *pExpr /* Vector expression to be appended. Might be NULL */
  92714. ){
  92715. sqlite3 *db = pParse->db;
  92716. int n;
  92717. int i;
  92718. int iFirst = pList ? pList->nExpr : 0;
  92719. /* pColumns can only be NULL due to an OOM but an OOM will cause an
  92720. ** exit prior to this routine being invoked */
  92721. if( NEVER(pColumns==0) ) goto vector_append_error;
  92722. if( pExpr==0 ) goto vector_append_error;
  92723. /* If the RHS is a vector, then we can immediately check to see that
  92724. ** the size of the RHS and LHS match. But if the RHS is a SELECT,
  92725. ** wildcards ("*") in the result set of the SELECT must be expanded before
  92726. ** we can do the size check, so defer the size check until code generation.
  92727. */
  92728. if( pExpr->op!=TK_SELECT && pColumns->nId!=(n=sqlite3ExprVectorSize(pExpr)) ){
  92729. sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
  92730. pColumns->nId, n);
  92731. goto vector_append_error;
  92732. }
  92733. for(i=0; i<pColumns->nId; i++){
  92734. Expr *pSubExpr = sqlite3ExprForVectorField(pParse, pExpr, i);
  92735. pList = sqlite3ExprListAppend(pParse, pList, pSubExpr);
  92736. if( pList ){
  92737. assert( pList->nExpr==iFirst+i+1 );
  92738. pList->a[pList->nExpr-1].zName = pColumns->a[i].zName;
  92739. pColumns->a[i].zName = 0;
  92740. }
  92741. }
  92742. if( !db->mallocFailed && pExpr->op==TK_SELECT && ALWAYS(pList!=0) ){
  92743. Expr *pFirst = pList->a[iFirst].pExpr;
  92744. assert( pFirst!=0 );
  92745. assert( pFirst->op==TK_SELECT_COLUMN );
  92746. /* Store the SELECT statement in pRight so it will be deleted when
  92747. ** sqlite3ExprListDelete() is called */
  92748. pFirst->pRight = pExpr;
  92749. pExpr = 0;
  92750. /* Remember the size of the LHS in iTable so that we can check that
  92751. ** the RHS and LHS sizes match during code generation. */
  92752. pFirst->iTable = pColumns->nId;
  92753. }
  92754. vector_append_error:
  92755. sqlite3ExprUnmapAndDelete(pParse, pExpr);
  92756. sqlite3IdListDelete(db, pColumns);
  92757. return pList;
  92758. }
  92759. /*
  92760. ** Set the sort order for the last element on the given ExprList.
  92761. */
  92762. SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder){
  92763. if( p==0 ) return;
  92764. assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC>=0 && SQLITE_SO_DESC>0 );
  92765. assert( p->nExpr>0 );
  92766. if( iSortOrder<0 ){
  92767. assert( p->a[p->nExpr-1].sortOrder==SQLITE_SO_ASC );
  92768. return;
  92769. }
  92770. p->a[p->nExpr-1].sortOrder = (u8)iSortOrder;
  92771. }
  92772. /*
  92773. ** Set the ExprList.a[].zName element of the most recently added item
  92774. ** on the expression list.
  92775. **
  92776. ** pList might be NULL following an OOM error. But pName should never be
  92777. ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
  92778. ** is set.
  92779. */
  92780. SQLITE_PRIVATE void sqlite3ExprListSetName(
  92781. Parse *pParse, /* Parsing context */
  92782. ExprList *pList, /* List to which to add the span. */
  92783. Token *pName, /* Name to be added */
  92784. int dequote /* True to cause the name to be dequoted */
  92785. ){
  92786. assert( pList!=0 || pParse->db->mallocFailed!=0 );
  92787. if( pList ){
  92788. struct ExprList_item *pItem;
  92789. assert( pList->nExpr>0 );
  92790. pItem = &pList->a[pList->nExpr-1];
  92791. assert( pItem->zName==0 );
  92792. pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
  92793. if( dequote ) sqlite3Dequote(pItem->zName);
  92794. if( IN_RENAME_OBJECT ){
  92795. sqlite3RenameTokenMap(pParse, (void*)pItem->zName, pName);
  92796. }
  92797. }
  92798. }
  92799. /*
  92800. ** Set the ExprList.a[].zSpan element of the most recently added item
  92801. ** on the expression list.
  92802. **
  92803. ** pList might be NULL following an OOM error. But pSpan should never be
  92804. ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
  92805. ** is set.
  92806. */
  92807. SQLITE_PRIVATE void sqlite3ExprListSetSpan(
  92808. Parse *pParse, /* Parsing context */
  92809. ExprList *pList, /* List to which to add the span. */
  92810. const char *zStart, /* Start of the span */
  92811. const char *zEnd /* End of the span */
  92812. ){
  92813. sqlite3 *db = pParse->db;
  92814. assert( pList!=0 || db->mallocFailed!=0 );
  92815. if( pList ){
  92816. struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
  92817. assert( pList->nExpr>0 );
  92818. sqlite3DbFree(db, pItem->zSpan);
  92819. pItem->zSpan = sqlite3DbSpanDup(db, zStart, zEnd);
  92820. }
  92821. }
  92822. /*
  92823. ** If the expression list pEList contains more than iLimit elements,
  92824. ** leave an error message in pParse.
  92825. */
  92826. SQLITE_PRIVATE void sqlite3ExprListCheckLength(
  92827. Parse *pParse,
  92828. ExprList *pEList,
  92829. const char *zObject
  92830. ){
  92831. int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
  92832. testcase( pEList && pEList->nExpr==mx );
  92833. testcase( pEList && pEList->nExpr==mx+1 );
  92834. if( pEList && pEList->nExpr>mx ){
  92835. sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
  92836. }
  92837. }
  92838. /*
  92839. ** Delete an entire expression list.
  92840. */
  92841. static SQLITE_NOINLINE void exprListDeleteNN(sqlite3 *db, ExprList *pList){
  92842. int i = pList->nExpr;
  92843. struct ExprList_item *pItem = pList->a;
  92844. assert( pList->nExpr>0 );
  92845. do{
  92846. sqlite3ExprDelete(db, pItem->pExpr);
  92847. sqlite3DbFree(db, pItem->zName);
  92848. sqlite3DbFree(db, pItem->zSpan);
  92849. pItem++;
  92850. }while( --i>0 );
  92851. sqlite3DbFreeNN(db, pList);
  92852. }
  92853. SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
  92854. if( pList ) exprListDeleteNN(db, pList);
  92855. }
  92856. /*
  92857. ** Return the bitwise-OR of all Expr.flags fields in the given
  92858. ** ExprList.
  92859. */
  92860. SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList *pList){
  92861. int i;
  92862. u32 m = 0;
  92863. assert( pList!=0 );
  92864. for(i=0; i<pList->nExpr; i++){
  92865. Expr *pExpr = pList->a[i].pExpr;
  92866. assert( pExpr!=0 );
  92867. m |= pExpr->flags;
  92868. }
  92869. return m;
  92870. }
  92871. /*
  92872. ** This is a SELECT-node callback for the expression walker that
  92873. ** always "fails". By "fail" in this case, we mean set
  92874. ** pWalker->eCode to zero and abort.
  92875. **
  92876. ** This callback is used by multiple expression walkers.
  92877. */
  92878. SQLITE_PRIVATE int sqlite3SelectWalkFail(Walker *pWalker, Select *NotUsed){
  92879. UNUSED_PARAMETER(NotUsed);
  92880. pWalker->eCode = 0;
  92881. return WRC_Abort;
  92882. }
  92883. /*
  92884. ** If the input expression is an ID with the name "true" or "false"
  92885. ** then convert it into an TK_TRUEFALSE term. Return non-zero if
  92886. ** the conversion happened, and zero if the expression is unaltered.
  92887. */
  92888. SQLITE_PRIVATE int sqlite3ExprIdToTrueFalse(Expr *pExpr){
  92889. assert( pExpr->op==TK_ID || pExpr->op==TK_STRING );
  92890. if( !ExprHasProperty(pExpr, EP_Quoted)
  92891. && (sqlite3StrICmp(pExpr->u.zToken, "true")==0
  92892. || sqlite3StrICmp(pExpr->u.zToken, "false")==0)
  92893. ){
  92894. pExpr->op = TK_TRUEFALSE;
  92895. ExprSetProperty(pExpr, pExpr->u.zToken[4]==0 ? EP_IsTrue : EP_IsFalse);
  92896. return 1;
  92897. }
  92898. return 0;
  92899. }
  92900. /*
  92901. ** The argument must be a TK_TRUEFALSE Expr node. Return 1 if it is TRUE
  92902. ** and 0 if it is FALSE.
  92903. */
  92904. SQLITE_PRIVATE int sqlite3ExprTruthValue(const Expr *pExpr){
  92905. pExpr = sqlite3ExprSkipCollate((Expr*)pExpr);
  92906. assert( pExpr->op==TK_TRUEFALSE );
  92907. assert( sqlite3StrICmp(pExpr->u.zToken,"true")==0
  92908. || sqlite3StrICmp(pExpr->u.zToken,"false")==0 );
  92909. return pExpr->u.zToken[4]==0;
  92910. }
  92911. /*
  92912. ** If pExpr is an AND or OR expression, try to simplify it by eliminating
  92913. ** terms that are always true or false. Return the simplified expression.
  92914. ** Or return the original expression if no simplification is possible.
  92915. **
  92916. ** Examples:
  92917. **
  92918. ** (x<10) AND true => (x<10)
  92919. ** (x<10) AND false => false
  92920. ** (x<10) AND (y=22 OR false) => (x<10) AND (y=22)
  92921. ** (x<10) AND (y=22 OR true) => (x<10)
  92922. ** (y=22) OR true => true
  92923. */
  92924. SQLITE_PRIVATE Expr *sqlite3ExprSimplifiedAndOr(Expr *pExpr){
  92925. assert( pExpr!=0 );
  92926. if( pExpr->op==TK_AND || pExpr->op==TK_OR ){
  92927. Expr *pRight = sqlite3ExprSimplifiedAndOr(pExpr->pRight);
  92928. Expr *pLeft = sqlite3ExprSimplifiedAndOr(pExpr->pLeft);
  92929. if( ExprAlwaysTrue(pLeft) || ExprAlwaysFalse(pRight) ){
  92930. pExpr = pExpr->op==TK_AND ? pRight : pLeft;
  92931. }else if( ExprAlwaysTrue(pRight) || ExprAlwaysFalse(pLeft) ){
  92932. pExpr = pExpr->op==TK_AND ? pLeft : pRight;
  92933. }
  92934. }
  92935. return pExpr;
  92936. }
  92937. /*
  92938. ** These routines are Walker callbacks used to check expressions to
  92939. ** see if they are "constant" for some definition of constant. The
  92940. ** Walker.eCode value determines the type of "constant" we are looking
  92941. ** for.
  92942. **
  92943. ** These callback routines are used to implement the following:
  92944. **
  92945. ** sqlite3ExprIsConstant() pWalker->eCode==1
  92946. ** sqlite3ExprIsConstantNotJoin() pWalker->eCode==2
  92947. ** sqlite3ExprIsTableConstant() pWalker->eCode==3
  92948. ** sqlite3ExprIsConstantOrFunction() pWalker->eCode==4 or 5
  92949. **
  92950. ** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
  92951. ** is found to not be a constant.
  92952. **
  92953. ** The sqlite3ExprIsConstantOrFunction() is used for evaluating expressions
  92954. ** in a CREATE TABLE statement. The Walker.eCode value is 5 when parsing
  92955. ** an existing schema and 4 when processing a new statement. A bound
  92956. ** parameter raises an error for new statements, but is silently converted
  92957. ** to NULL for existing schemas. This allows sqlite_master tables that
  92958. ** contain a bound parameter because they were generated by older versions
  92959. ** of SQLite to be parsed by newer versions of SQLite without raising a
  92960. ** malformed schema error.
  92961. */
  92962. static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
  92963. /* If pWalker->eCode is 2 then any term of the expression that comes from
  92964. ** the ON or USING clauses of a left join disqualifies the expression
  92965. ** from being considered constant. */
  92966. if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_FromJoin) ){
  92967. pWalker->eCode = 0;
  92968. return WRC_Abort;
  92969. }
  92970. switch( pExpr->op ){
  92971. /* Consider functions to be constant if all their arguments are constant
  92972. ** and either pWalker->eCode==4 or 5 or the function has the
  92973. ** SQLITE_FUNC_CONST flag. */
  92974. case TK_FUNCTION:
  92975. if( pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc) ){
  92976. return WRC_Continue;
  92977. }else{
  92978. pWalker->eCode = 0;
  92979. return WRC_Abort;
  92980. }
  92981. case TK_ID:
  92982. /* Convert "true" or "false" in a DEFAULT clause into the
  92983. ** appropriate TK_TRUEFALSE operator */
  92984. if( sqlite3ExprIdToTrueFalse(pExpr) ){
  92985. return WRC_Prune;
  92986. }
  92987. /* Fall thru */
  92988. case TK_COLUMN:
  92989. case TK_AGG_FUNCTION:
  92990. case TK_AGG_COLUMN:
  92991. testcase( pExpr->op==TK_ID );
  92992. testcase( pExpr->op==TK_COLUMN );
  92993. testcase( pExpr->op==TK_AGG_FUNCTION );
  92994. testcase( pExpr->op==TK_AGG_COLUMN );
  92995. if( ExprHasProperty(pExpr, EP_FixedCol) && pWalker->eCode!=2 ){
  92996. return WRC_Continue;
  92997. }
  92998. if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){
  92999. return WRC_Continue;
  93000. }
  93001. /* Fall through */
  93002. case TK_IF_NULL_ROW:
  93003. case TK_REGISTER:
  93004. testcase( pExpr->op==TK_REGISTER );
  93005. testcase( pExpr->op==TK_IF_NULL_ROW );
  93006. pWalker->eCode = 0;
  93007. return WRC_Abort;
  93008. case TK_VARIABLE:
  93009. if( pWalker->eCode==5 ){
  93010. /* Silently convert bound parameters that appear inside of CREATE
  93011. ** statements into a NULL when parsing the CREATE statement text out
  93012. ** of the sqlite_master table */
  93013. pExpr->op = TK_NULL;
  93014. }else if( pWalker->eCode==4 ){
  93015. /* A bound parameter in a CREATE statement that originates from
  93016. ** sqlite3_prepare() causes an error */
  93017. pWalker->eCode = 0;
  93018. return WRC_Abort;
  93019. }
  93020. /* Fall through */
  93021. default:
  93022. testcase( pExpr->op==TK_SELECT ); /* sqlite3SelectWalkFail() disallows */
  93023. testcase( pExpr->op==TK_EXISTS ); /* sqlite3SelectWalkFail() disallows */
  93024. return WRC_Continue;
  93025. }
  93026. }
  93027. static int exprIsConst(Expr *p, int initFlag, int iCur){
  93028. Walker w;
  93029. w.eCode = initFlag;
  93030. w.xExprCallback = exprNodeIsConstant;
  93031. w.xSelectCallback = sqlite3SelectWalkFail;
  93032. #ifdef SQLITE_DEBUG
  93033. w.xSelectCallback2 = sqlite3SelectWalkAssert2;
  93034. #endif
  93035. w.u.iCur = iCur;
  93036. sqlite3WalkExpr(&w, p);
  93037. return w.eCode;
  93038. }
  93039. /*
  93040. ** Walk an expression tree. Return non-zero if the expression is constant
  93041. ** and 0 if it involves variables or function calls.
  93042. **
  93043. ** For the purposes of this function, a double-quoted string (ex: "abc")
  93044. ** is considered a variable but a single-quoted string (ex: 'abc') is
  93045. ** a constant.
  93046. */
  93047. SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
  93048. return exprIsConst(p, 1, 0);
  93049. }
  93050. /*
  93051. ** Walk an expression tree. Return non-zero if
  93052. **
  93053. ** (1) the expression is constant, and
  93054. ** (2) the expression does originate in the ON or USING clause
  93055. ** of a LEFT JOIN, and
  93056. ** (3) the expression does not contain any EP_FixedCol TK_COLUMN
  93057. ** operands created by the constant propagation optimization.
  93058. **
  93059. ** When this routine returns true, it indicates that the expression
  93060. ** can be added to the pParse->pConstExpr list and evaluated once when
  93061. ** the prepared statement starts up. See sqlite3ExprCodeAtInit().
  93062. */
  93063. SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
  93064. return exprIsConst(p, 2, 0);
  93065. }
  93066. /*
  93067. ** Walk an expression tree. Return non-zero if the expression is constant
  93068. ** for any single row of the table with cursor iCur. In other words, the
  93069. ** expression must not refer to any non-deterministic function nor any
  93070. ** table other than iCur.
  93071. */
  93072. SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr *p, int iCur){
  93073. return exprIsConst(p, 3, iCur);
  93074. }
  93075. /*
  93076. ** sqlite3WalkExpr() callback used by sqlite3ExprIsConstantOrGroupBy().
  93077. */
  93078. static int exprNodeIsConstantOrGroupBy(Walker *pWalker, Expr *pExpr){
  93079. ExprList *pGroupBy = pWalker->u.pGroupBy;
  93080. int i;
  93081. /* Check if pExpr is identical to any GROUP BY term. If so, consider
  93082. ** it constant. */
  93083. for(i=0; i<pGroupBy->nExpr; i++){
  93084. Expr *p = pGroupBy->a[i].pExpr;
  93085. if( sqlite3ExprCompare(0, pExpr, p, -1)<2 ){
  93086. CollSeq *pColl = sqlite3ExprNNCollSeq(pWalker->pParse, p);
  93087. if( sqlite3IsBinary(pColl) ){
  93088. return WRC_Prune;
  93089. }
  93090. }
  93091. }
  93092. /* Check if pExpr is a sub-select. If so, consider it variable. */
  93093. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  93094. pWalker->eCode = 0;
  93095. return WRC_Abort;
  93096. }
  93097. return exprNodeIsConstant(pWalker, pExpr);
  93098. }
  93099. /*
  93100. ** Walk the expression tree passed as the first argument. Return non-zero
  93101. ** if the expression consists entirely of constants or copies of terms
  93102. ** in pGroupBy that sort with the BINARY collation sequence.
  93103. **
  93104. ** This routine is used to determine if a term of the HAVING clause can
  93105. ** be promoted into the WHERE clause. In order for such a promotion to work,
  93106. ** the value of the HAVING clause term must be the same for all members of
  93107. ** a "group". The requirement that the GROUP BY term must be BINARY
  93108. ** assumes that no other collating sequence will have a finer-grained
  93109. ** grouping than binary. In other words (A=B COLLATE binary) implies
  93110. ** A=B in every other collating sequence. The requirement that the
  93111. ** GROUP BY be BINARY is stricter than necessary. It would also work
  93112. ** to promote HAVING clauses that use the same alternative collating
  93113. ** sequence as the GROUP BY term, but that is much harder to check,
  93114. ** alternative collating sequences are uncommon, and this is only an
  93115. ** optimization, so we take the easy way out and simply require the
  93116. ** GROUP BY to use the BINARY collating sequence.
  93117. */
  93118. SQLITE_PRIVATE int sqlite3ExprIsConstantOrGroupBy(Parse *pParse, Expr *p, ExprList *pGroupBy){
  93119. Walker w;
  93120. w.eCode = 1;
  93121. w.xExprCallback = exprNodeIsConstantOrGroupBy;
  93122. w.xSelectCallback = 0;
  93123. w.u.pGroupBy = pGroupBy;
  93124. w.pParse = pParse;
  93125. sqlite3WalkExpr(&w, p);
  93126. return w.eCode;
  93127. }
  93128. /*
  93129. ** Walk an expression tree. Return non-zero if the expression is constant
  93130. ** or a function call with constant arguments. Return and 0 if there
  93131. ** are any variables.
  93132. **
  93133. ** For the purposes of this function, a double-quoted string (ex: "abc")
  93134. ** is considered a variable but a single-quoted string (ex: 'abc') is
  93135. ** a constant.
  93136. */
  93137. SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){
  93138. assert( isInit==0 || isInit==1 );
  93139. return exprIsConst(p, 4+isInit, 0);
  93140. }
  93141. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  93142. /*
  93143. ** Walk an expression tree. Return 1 if the expression contains a
  93144. ** subquery of some kind. Return 0 if there are no subqueries.
  93145. */
  93146. SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr *p){
  93147. Walker w;
  93148. w.eCode = 1;
  93149. w.xExprCallback = sqlite3ExprWalkNoop;
  93150. w.xSelectCallback = sqlite3SelectWalkFail;
  93151. #ifdef SQLITE_DEBUG
  93152. w.xSelectCallback2 = sqlite3SelectWalkAssert2;
  93153. #endif
  93154. sqlite3WalkExpr(&w, p);
  93155. return w.eCode==0;
  93156. }
  93157. #endif
  93158. /*
  93159. ** If the expression p codes a constant integer that is small enough
  93160. ** to fit in a 32-bit integer, return 1 and put the value of the integer
  93161. ** in *pValue. If the expression is not an integer or if it is too big
  93162. ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
  93163. */
  93164. SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
  93165. int rc = 0;
  93166. if( NEVER(p==0) ) return 0; /* Used to only happen following on OOM */
  93167. /* If an expression is an integer literal that fits in a signed 32-bit
  93168. ** integer, then the EP_IntValue flag will have already been set */
  93169. assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
  93170. || sqlite3GetInt32(p->u.zToken, &rc)==0 );
  93171. if( p->flags & EP_IntValue ){
  93172. *pValue = p->u.iValue;
  93173. return 1;
  93174. }
  93175. switch( p->op ){
  93176. case TK_UPLUS: {
  93177. rc = sqlite3ExprIsInteger(p->pLeft, pValue);
  93178. break;
  93179. }
  93180. case TK_UMINUS: {
  93181. int v;
  93182. if( sqlite3ExprIsInteger(p->pLeft, &v) ){
  93183. assert( v!=(-2147483647-1) );
  93184. *pValue = -v;
  93185. rc = 1;
  93186. }
  93187. break;
  93188. }
  93189. default: break;
  93190. }
  93191. return rc;
  93192. }
  93193. /*
  93194. ** Return FALSE if there is no chance that the expression can be NULL.
  93195. **
  93196. ** If the expression might be NULL or if the expression is too complex
  93197. ** to tell return TRUE.
  93198. **
  93199. ** This routine is used as an optimization, to skip OP_IsNull opcodes
  93200. ** when we know that a value cannot be NULL. Hence, a false positive
  93201. ** (returning TRUE when in fact the expression can never be NULL) might
  93202. ** be a small performance hit but is otherwise harmless. On the other
  93203. ** hand, a false negative (returning FALSE when the result could be NULL)
  93204. ** will likely result in an incorrect answer. So when in doubt, return
  93205. ** TRUE.
  93206. */
  93207. SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
  93208. u8 op;
  93209. while( p->op==TK_UPLUS || p->op==TK_UMINUS ){
  93210. p = p->pLeft;
  93211. }
  93212. op = p->op;
  93213. if( op==TK_REGISTER ) op = p->op2;
  93214. switch( op ){
  93215. case TK_INTEGER:
  93216. case TK_STRING:
  93217. case TK_FLOAT:
  93218. case TK_BLOB:
  93219. return 0;
  93220. case TK_COLUMN:
  93221. return ExprHasProperty(p, EP_CanBeNull) ||
  93222. p->y.pTab==0 || /* Reference to column of index on expression */
  93223. (p->iColumn>=0 && p->y.pTab->aCol[p->iColumn].notNull==0);
  93224. default:
  93225. return 1;
  93226. }
  93227. }
  93228. /*
  93229. ** Return TRUE if the given expression is a constant which would be
  93230. ** unchanged by OP_Affinity with the affinity given in the second
  93231. ** argument.
  93232. **
  93233. ** This routine is used to determine if the OP_Affinity operation
  93234. ** can be omitted. When in doubt return FALSE. A false negative
  93235. ** is harmless. A false positive, however, can result in the wrong
  93236. ** answer.
  93237. */
  93238. SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
  93239. u8 op;
  93240. if( aff==SQLITE_AFF_BLOB ) return 1;
  93241. while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
  93242. op = p->op;
  93243. if( op==TK_REGISTER ) op = p->op2;
  93244. switch( op ){
  93245. case TK_INTEGER: {
  93246. return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
  93247. }
  93248. case TK_FLOAT: {
  93249. return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
  93250. }
  93251. case TK_STRING: {
  93252. return aff==SQLITE_AFF_TEXT;
  93253. }
  93254. case TK_BLOB: {
  93255. return 1;
  93256. }
  93257. case TK_COLUMN: {
  93258. assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */
  93259. return p->iColumn<0
  93260. && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
  93261. }
  93262. default: {
  93263. return 0;
  93264. }
  93265. }
  93266. }
  93267. /*
  93268. ** Return TRUE if the given string is a row-id column name.
  93269. */
  93270. SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
  93271. if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
  93272. if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
  93273. if( sqlite3StrICmp(z, "OID")==0 ) return 1;
  93274. return 0;
  93275. }
  93276. /*
  93277. ** pX is the RHS of an IN operator. If pX is a SELECT statement
  93278. ** that can be simplified to a direct table access, then return
  93279. ** a pointer to the SELECT statement. If pX is not a SELECT statement,
  93280. ** or if the SELECT statement needs to be manifested into a transient
  93281. ** table, then return NULL.
  93282. */
  93283. #ifndef SQLITE_OMIT_SUBQUERY
  93284. static Select *isCandidateForInOpt(Expr *pX){
  93285. Select *p;
  93286. SrcList *pSrc;
  93287. ExprList *pEList;
  93288. Table *pTab;
  93289. int i;
  93290. if( !ExprHasProperty(pX, EP_xIsSelect) ) return 0; /* Not a subquery */
  93291. if( ExprHasProperty(pX, EP_VarSelect) ) return 0; /* Correlated subq */
  93292. p = pX->x.pSelect;
  93293. if( p->pPrior ) return 0; /* Not a compound SELECT */
  93294. if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
  93295. testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
  93296. testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
  93297. return 0; /* No DISTINCT keyword and no aggregate functions */
  93298. }
  93299. assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */
  93300. if( p->pLimit ) return 0; /* Has no LIMIT clause */
  93301. if( p->pWhere ) return 0; /* Has no WHERE clause */
  93302. pSrc = p->pSrc;
  93303. assert( pSrc!=0 );
  93304. if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */
  93305. if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */
  93306. pTab = pSrc->a[0].pTab;
  93307. assert( pTab!=0 );
  93308. assert( pTab->pSelect==0 ); /* FROM clause is not a view */
  93309. if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */
  93310. pEList = p->pEList;
  93311. assert( pEList!=0 );
  93312. /* All SELECT results must be columns. */
  93313. for(i=0; i<pEList->nExpr; i++){
  93314. Expr *pRes = pEList->a[i].pExpr;
  93315. if( pRes->op!=TK_COLUMN ) return 0;
  93316. assert( pRes->iTable==pSrc->a[0].iCursor ); /* Not a correlated subquery */
  93317. }
  93318. return p;
  93319. }
  93320. #endif /* SQLITE_OMIT_SUBQUERY */
  93321. #ifndef SQLITE_OMIT_SUBQUERY
  93322. /*
  93323. ** Generate code that checks the left-most column of index table iCur to see if
  93324. ** it contains any NULL entries. Cause the register at regHasNull to be set
  93325. ** to a non-NULL value if iCur contains no NULLs. Cause register regHasNull
  93326. ** to be set to NULL if iCur contains one or more NULL values.
  93327. */
  93328. static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
  93329. int addr1;
  93330. sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
  93331. addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
  93332. sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
  93333. sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
  93334. VdbeComment((v, "first_entry_in(%d)", iCur));
  93335. sqlite3VdbeJumpHere(v, addr1);
  93336. }
  93337. #endif
  93338. #ifndef SQLITE_OMIT_SUBQUERY
  93339. /*
  93340. ** The argument is an IN operator with a list (not a subquery) on the
  93341. ** right-hand side. Return TRUE if that list is constant.
  93342. */
  93343. static int sqlite3InRhsIsConstant(Expr *pIn){
  93344. Expr *pLHS;
  93345. int res;
  93346. assert( !ExprHasProperty(pIn, EP_xIsSelect) );
  93347. pLHS = pIn->pLeft;
  93348. pIn->pLeft = 0;
  93349. res = sqlite3ExprIsConstant(pIn);
  93350. pIn->pLeft = pLHS;
  93351. return res;
  93352. }
  93353. #endif
  93354. /*
  93355. ** This function is used by the implementation of the IN (...) operator.
  93356. ** The pX parameter is the expression on the RHS of the IN operator, which
  93357. ** might be either a list of expressions or a subquery.
  93358. **
  93359. ** The job of this routine is to find or create a b-tree object that can
  93360. ** be used either to test for membership in the RHS set or to iterate through
  93361. ** all members of the RHS set, skipping duplicates.
  93362. **
  93363. ** A cursor is opened on the b-tree object that is the RHS of the IN operator
  93364. ** and pX->iTable is set to the index of that cursor.
  93365. **
  93366. ** The returned value of this function indicates the b-tree type, as follows:
  93367. **
  93368. ** IN_INDEX_ROWID - The cursor was opened on a database table.
  93369. ** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index.
  93370. ** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
  93371. ** IN_INDEX_EPH - The cursor was opened on a specially created and
  93372. ** populated epheremal table.
  93373. ** IN_INDEX_NOOP - No cursor was allocated. The IN operator must be
  93374. ** implemented as a sequence of comparisons.
  93375. **
  93376. ** An existing b-tree might be used if the RHS expression pX is a simple
  93377. ** subquery such as:
  93378. **
  93379. ** SELECT <column1>, <column2>... FROM <table>
  93380. **
  93381. ** If the RHS of the IN operator is a list or a more complex subquery, then
  93382. ** an ephemeral table might need to be generated from the RHS and then
  93383. ** pX->iTable made to point to the ephemeral table instead of an
  93384. ** existing table.
  93385. **
  93386. ** The inFlags parameter must contain, at a minimum, one of the bits
  93387. ** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP but not both. If inFlags contains
  93388. ** IN_INDEX_MEMBERSHIP, then the generated table will be used for a fast
  93389. ** membership test. When the IN_INDEX_LOOP bit is set, the IN index will
  93390. ** be used to loop over all values of the RHS of the IN operator.
  93391. **
  93392. ** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
  93393. ** through the set members) then the b-tree must not contain duplicates.
  93394. ** An epheremal table will be created unless the selected columns are guaranteed
  93395. ** to be unique - either because it is an INTEGER PRIMARY KEY or due to
  93396. ** a UNIQUE constraint or index.
  93397. **
  93398. ** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
  93399. ** for fast set membership tests) then an epheremal table must
  93400. ** be used unless <columns> is a single INTEGER PRIMARY KEY column or an
  93401. ** index can be found with the specified <columns> as its left-most.
  93402. **
  93403. ** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
  93404. ** if the RHS of the IN operator is a list (not a subquery) then this
  93405. ** routine might decide that creating an ephemeral b-tree for membership
  93406. ** testing is too expensive and return IN_INDEX_NOOP. In that case, the
  93407. ** calling routine should implement the IN operator using a sequence
  93408. ** of Eq or Ne comparison operations.
  93409. **
  93410. ** When the b-tree is being used for membership tests, the calling function
  93411. ** might need to know whether or not the RHS side of the IN operator
  93412. ** contains a NULL. If prRhsHasNull is not a NULL pointer and
  93413. ** if there is any chance that the (...) might contain a NULL value at
  93414. ** runtime, then a register is allocated and the register number written
  93415. ** to *prRhsHasNull. If there is no chance that the (...) contains a
  93416. ** NULL value, then *prRhsHasNull is left unchanged.
  93417. **
  93418. ** If a register is allocated and its location stored in *prRhsHasNull, then
  93419. ** the value in that register will be NULL if the b-tree contains one or more
  93420. ** NULL values, and it will be some non-NULL value if the b-tree contains no
  93421. ** NULL values.
  93422. **
  93423. ** If the aiMap parameter is not NULL, it must point to an array containing
  93424. ** one element for each column returned by the SELECT statement on the RHS
  93425. ** of the IN(...) operator. The i'th entry of the array is populated with the
  93426. ** offset of the index column that matches the i'th column returned by the
  93427. ** SELECT. For example, if the expression and selected index are:
  93428. **
  93429. ** (?,?,?) IN (SELECT a, b, c FROM t1)
  93430. ** CREATE INDEX i1 ON t1(b, c, a);
  93431. **
  93432. ** then aiMap[] is populated with {2, 0, 1}.
  93433. */
  93434. #ifndef SQLITE_OMIT_SUBQUERY
  93435. SQLITE_PRIVATE int sqlite3FindInIndex(
  93436. Parse *pParse, /* Parsing context */
  93437. Expr *pX, /* The right-hand side (RHS) of the IN operator */
  93438. u32 inFlags, /* IN_INDEX_LOOP, _MEMBERSHIP, and/or _NOOP_OK */
  93439. int *prRhsHasNull, /* Register holding NULL status. See notes */
  93440. int *aiMap, /* Mapping from Index fields to RHS fields */
  93441. int *piTab /* OUT: index to use */
  93442. ){
  93443. Select *p; /* SELECT to the right of IN operator */
  93444. int eType = 0; /* Type of RHS table. IN_INDEX_* */
  93445. int iTab = pParse->nTab++; /* Cursor of the RHS table */
  93446. int mustBeUnique; /* True if RHS must be unique */
  93447. Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
  93448. assert( pX->op==TK_IN );
  93449. mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
  93450. /* If the RHS of this IN(...) operator is a SELECT, and if it matters
  93451. ** whether or not the SELECT result contains NULL values, check whether
  93452. ** or not NULL is actually possible (it may not be, for example, due
  93453. ** to NOT NULL constraints in the schema). If no NULL values are possible,
  93454. ** set prRhsHasNull to 0 before continuing. */
  93455. if( prRhsHasNull && (pX->flags & EP_xIsSelect) ){
  93456. int i;
  93457. ExprList *pEList = pX->x.pSelect->pEList;
  93458. for(i=0; i<pEList->nExpr; i++){
  93459. if( sqlite3ExprCanBeNull(pEList->a[i].pExpr) ) break;
  93460. }
  93461. if( i==pEList->nExpr ){
  93462. prRhsHasNull = 0;
  93463. }
  93464. }
  93465. /* Check to see if an existing table or index can be used to
  93466. ** satisfy the query. This is preferable to generating a new
  93467. ** ephemeral table. */
  93468. if( pParse->nErr==0 && (p = isCandidateForInOpt(pX))!=0 ){
  93469. sqlite3 *db = pParse->db; /* Database connection */
  93470. Table *pTab; /* Table <table>. */
  93471. i16 iDb; /* Database idx for pTab */
  93472. ExprList *pEList = p->pEList;
  93473. int nExpr = pEList->nExpr;
  93474. assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */
  93475. assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
  93476. assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */
  93477. pTab = p->pSrc->a[0].pTab;
  93478. /* Code an OP_Transaction and OP_TableLock for <table>. */
  93479. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  93480. sqlite3CodeVerifySchema(pParse, iDb);
  93481. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  93482. assert(v); /* sqlite3GetVdbe() has always been previously called */
  93483. if( nExpr==1 && pEList->a[0].pExpr->iColumn<0 ){
  93484. /* The "x IN (SELECT rowid FROM table)" case */
  93485. int iAddr = sqlite3VdbeAddOp0(v, OP_Once);
  93486. VdbeCoverage(v);
  93487. sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  93488. eType = IN_INDEX_ROWID;
  93489. ExplainQueryPlan((pParse, 0,
  93490. "USING ROWID SEARCH ON TABLE %s FOR IN-OPERATOR",pTab->zName));
  93491. sqlite3VdbeJumpHere(v, iAddr);
  93492. }else{
  93493. Index *pIdx; /* Iterator variable */
  93494. int affinity_ok = 1;
  93495. int i;
  93496. /* Check that the affinity that will be used to perform each
  93497. ** comparison is the same as the affinity of each column in table
  93498. ** on the RHS of the IN operator. If it not, it is not possible to
  93499. ** use any index of the RHS table. */
  93500. for(i=0; i<nExpr && affinity_ok; i++){
  93501. Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
  93502. int iCol = pEList->a[i].pExpr->iColumn;
  93503. char idxaff = sqlite3TableColumnAffinity(pTab,iCol); /* RHS table */
  93504. char cmpaff = sqlite3CompareAffinity(pLhs, idxaff);
  93505. testcase( cmpaff==SQLITE_AFF_BLOB );
  93506. testcase( cmpaff==SQLITE_AFF_TEXT );
  93507. switch( cmpaff ){
  93508. case SQLITE_AFF_BLOB:
  93509. break;
  93510. case SQLITE_AFF_TEXT:
  93511. /* sqlite3CompareAffinity() only returns TEXT if one side or the
  93512. ** other has no affinity and the other side is TEXT. Hence,
  93513. ** the only way for cmpaff to be TEXT is for idxaff to be TEXT
  93514. ** and for the term on the LHS of the IN to have no affinity. */
  93515. assert( idxaff==SQLITE_AFF_TEXT );
  93516. break;
  93517. default:
  93518. affinity_ok = sqlite3IsNumericAffinity(idxaff);
  93519. }
  93520. }
  93521. if( affinity_ok ){
  93522. /* Search for an existing index that will work for this IN operator */
  93523. for(pIdx=pTab->pIndex; pIdx && eType==0; pIdx=pIdx->pNext){
  93524. Bitmask colUsed; /* Columns of the index used */
  93525. Bitmask mCol; /* Mask for the current column */
  93526. if( pIdx->nColumn<nExpr ) continue;
  93527. if( pIdx->pPartIdxWhere!=0 ) continue;
  93528. /* Maximum nColumn is BMS-2, not BMS-1, so that we can compute
  93529. ** BITMASK(nExpr) without overflowing */
  93530. testcase( pIdx->nColumn==BMS-2 );
  93531. testcase( pIdx->nColumn==BMS-1 );
  93532. if( pIdx->nColumn>=BMS-1 ) continue;
  93533. if( mustBeUnique ){
  93534. if( pIdx->nKeyCol>nExpr
  93535. ||(pIdx->nColumn>nExpr && !IsUniqueIndex(pIdx))
  93536. ){
  93537. continue; /* This index is not unique over the IN RHS columns */
  93538. }
  93539. }
  93540. colUsed = 0; /* Columns of index used so far */
  93541. for(i=0; i<nExpr; i++){
  93542. Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
  93543. Expr *pRhs = pEList->a[i].pExpr;
  93544. CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
  93545. int j;
  93546. assert( pReq!=0 || pRhs->iColumn==XN_ROWID || pParse->nErr );
  93547. for(j=0; j<nExpr; j++){
  93548. if( pIdx->aiColumn[j]!=pRhs->iColumn ) continue;
  93549. assert( pIdx->azColl[j] );
  93550. if( pReq!=0 && sqlite3StrICmp(pReq->zName, pIdx->azColl[j])!=0 ){
  93551. continue;
  93552. }
  93553. break;
  93554. }
  93555. if( j==nExpr ) break;
  93556. mCol = MASKBIT(j);
  93557. if( mCol & colUsed ) break; /* Each column used only once */
  93558. colUsed |= mCol;
  93559. if( aiMap ) aiMap[i] = j;
  93560. }
  93561. assert( i==nExpr || colUsed!=(MASKBIT(nExpr)-1) );
  93562. if( colUsed==(MASKBIT(nExpr)-1) ){
  93563. /* If we reach this point, that means the index pIdx is usable */
  93564. int iAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  93565. ExplainQueryPlan((pParse, 0,
  93566. "USING INDEX %s FOR IN-OPERATOR",pIdx->zName));
  93567. sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
  93568. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  93569. VdbeComment((v, "%s", pIdx->zName));
  93570. assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
  93571. eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
  93572. if( prRhsHasNull ){
  93573. #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
  93574. i64 mask = (1<<nExpr)-1;
  93575. sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed,
  93576. iTab, 0, 0, (u8*)&mask, P4_INT64);
  93577. #endif
  93578. *prRhsHasNull = ++pParse->nMem;
  93579. if( nExpr==1 ){
  93580. sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
  93581. }
  93582. }
  93583. sqlite3VdbeJumpHere(v, iAddr);
  93584. }
  93585. } /* End loop over indexes */
  93586. } /* End if( affinity_ok ) */
  93587. } /* End if not an rowid index */
  93588. } /* End attempt to optimize using an index */
  93589. /* If no preexisting index is available for the IN clause
  93590. ** and IN_INDEX_NOOP is an allowed reply
  93591. ** and the RHS of the IN operator is a list, not a subquery
  93592. ** and the RHS is not constant or has two or fewer terms,
  93593. ** then it is not worth creating an ephemeral table to evaluate
  93594. ** the IN operator so return IN_INDEX_NOOP.
  93595. */
  93596. if( eType==0
  93597. && (inFlags & IN_INDEX_NOOP_OK)
  93598. && !ExprHasProperty(pX, EP_xIsSelect)
  93599. && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
  93600. ){
  93601. eType = IN_INDEX_NOOP;
  93602. }
  93603. if( eType==0 ){
  93604. /* Could not find an existing table or index to use as the RHS b-tree.
  93605. ** We will have to generate an ephemeral table to do the job.
  93606. */
  93607. u32 savedNQueryLoop = pParse->nQueryLoop;
  93608. int rMayHaveNull = 0;
  93609. eType = IN_INDEX_EPH;
  93610. if( inFlags & IN_INDEX_LOOP ){
  93611. pParse->nQueryLoop = 0;
  93612. }else if( prRhsHasNull ){
  93613. *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
  93614. }
  93615. assert( pX->op==TK_IN );
  93616. sqlite3CodeRhsOfIN(pParse, pX, iTab);
  93617. if( rMayHaveNull ){
  93618. sqlite3SetHasNullFlag(v, iTab, rMayHaveNull);
  93619. }
  93620. pParse->nQueryLoop = savedNQueryLoop;
  93621. }
  93622. if( aiMap && eType!=IN_INDEX_INDEX_ASC && eType!=IN_INDEX_INDEX_DESC ){
  93623. int i, n;
  93624. n = sqlite3ExprVectorSize(pX->pLeft);
  93625. for(i=0; i<n; i++) aiMap[i] = i;
  93626. }
  93627. *piTab = iTab;
  93628. return eType;
  93629. }
  93630. #endif
  93631. #ifndef SQLITE_OMIT_SUBQUERY
  93632. /*
  93633. ** Argument pExpr is an (?, ?...) IN(...) expression. This
  93634. ** function allocates and returns a nul-terminated string containing
  93635. ** the affinities to be used for each column of the comparison.
  93636. **
  93637. ** It is the responsibility of the caller to ensure that the returned
  93638. ** string is eventually freed using sqlite3DbFree().
  93639. */
  93640. static char *exprINAffinity(Parse *pParse, Expr *pExpr){
  93641. Expr *pLeft = pExpr->pLeft;
  93642. int nVal = sqlite3ExprVectorSize(pLeft);
  93643. Select *pSelect = (pExpr->flags & EP_xIsSelect) ? pExpr->x.pSelect : 0;
  93644. char *zRet;
  93645. assert( pExpr->op==TK_IN );
  93646. zRet = sqlite3DbMallocRaw(pParse->db, nVal+1);
  93647. if( zRet ){
  93648. int i;
  93649. for(i=0; i<nVal; i++){
  93650. Expr *pA = sqlite3VectorFieldSubexpr(pLeft, i);
  93651. char a = sqlite3ExprAffinity(pA);
  93652. if( pSelect ){
  93653. zRet[i] = sqlite3CompareAffinity(pSelect->pEList->a[i].pExpr, a);
  93654. }else{
  93655. zRet[i] = a;
  93656. }
  93657. }
  93658. zRet[nVal] = '\0';
  93659. }
  93660. return zRet;
  93661. }
  93662. #endif
  93663. #ifndef SQLITE_OMIT_SUBQUERY
  93664. /*
  93665. ** Load the Parse object passed as the first argument with an error
  93666. ** message of the form:
  93667. **
  93668. ** "sub-select returns N columns - expected M"
  93669. */
  93670. SQLITE_PRIVATE void sqlite3SubselectError(Parse *pParse, int nActual, int nExpect){
  93671. const char *zFmt = "sub-select returns %d columns - expected %d";
  93672. sqlite3ErrorMsg(pParse, zFmt, nActual, nExpect);
  93673. }
  93674. #endif
  93675. /*
  93676. ** Expression pExpr is a vector that has been used in a context where
  93677. ** it is not permitted. If pExpr is a sub-select vector, this routine
  93678. ** loads the Parse object with a message of the form:
  93679. **
  93680. ** "sub-select returns N columns - expected 1"
  93681. **
  93682. ** Or, if it is a regular scalar vector:
  93683. **
  93684. ** "row value misused"
  93685. */
  93686. SQLITE_PRIVATE void sqlite3VectorErrorMsg(Parse *pParse, Expr *pExpr){
  93687. #ifndef SQLITE_OMIT_SUBQUERY
  93688. if( pExpr->flags & EP_xIsSelect ){
  93689. sqlite3SubselectError(pParse, pExpr->x.pSelect->pEList->nExpr, 1);
  93690. }else
  93691. #endif
  93692. {
  93693. sqlite3ErrorMsg(pParse, "row value misused");
  93694. }
  93695. }
  93696. #ifndef SQLITE_OMIT_SUBQUERY
  93697. /*
  93698. ** Generate code that will construct an ephemeral table containing all terms
  93699. ** in the RHS of an IN operator. The IN operator can be in either of two
  93700. ** forms:
  93701. **
  93702. ** x IN (4,5,11) -- IN operator with list on right-hand side
  93703. ** x IN (SELECT a FROM b) -- IN operator with subquery on the right
  93704. **
  93705. ** The pExpr parameter is the IN operator. The cursor number for the
  93706. ** constructed ephermeral table is returned. The first time the ephemeral
  93707. ** table is computed, the cursor number is also stored in pExpr->iTable,
  93708. ** however the cursor number returned might not be the same, as it might
  93709. ** have been duplicated using OP_OpenDup.
  93710. **
  93711. ** If the LHS expression ("x" in the examples) is a column value, or
  93712. ** the SELECT statement returns a column value, then the affinity of that
  93713. ** column is used to build the index keys. If both 'x' and the
  93714. ** SELECT... statement are columns, then numeric affinity is used
  93715. ** if either column has NUMERIC or INTEGER affinity. If neither
  93716. ** 'x' nor the SELECT... statement are columns, then numeric affinity
  93717. ** is used.
  93718. */
  93719. SQLITE_PRIVATE void sqlite3CodeRhsOfIN(
  93720. Parse *pParse, /* Parsing context */
  93721. Expr *pExpr, /* The IN operator */
  93722. int iTab /* Use this cursor number */
  93723. ){
  93724. int addrOnce = 0; /* Address of the OP_Once instruction at top */
  93725. int addr; /* Address of OP_OpenEphemeral instruction */
  93726. Expr *pLeft; /* the LHS of the IN operator */
  93727. KeyInfo *pKeyInfo = 0; /* Key information */
  93728. int nVal; /* Size of vector pLeft */
  93729. Vdbe *v; /* The prepared statement under construction */
  93730. v = pParse->pVdbe;
  93731. assert( v!=0 );
  93732. /* The evaluation of the IN must be repeated every time it
  93733. ** is encountered if any of the following is true:
  93734. **
  93735. ** * The right-hand side is a correlated subquery
  93736. ** * The right-hand side is an expression list containing variables
  93737. ** * We are inside a trigger
  93738. **
  93739. ** If all of the above are false, then we can compute the RHS just once
  93740. ** and reuse it many names.
  93741. */
  93742. if( !ExprHasProperty(pExpr, EP_VarSelect) && pParse->iSelfTab==0 ){
  93743. /* Reuse of the RHS is allowed */
  93744. /* If this routine has already been coded, but the previous code
  93745. ** might not have been invoked yet, so invoke it now as a subroutine.
  93746. */
  93747. if( ExprHasProperty(pExpr, EP_Subrtn) ){
  93748. addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  93749. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  93750. ExplainQueryPlan((pParse, 0, "REUSE LIST SUBQUERY %d",
  93751. pExpr->x.pSelect->selId));
  93752. }
  93753. sqlite3VdbeAddOp2(v, OP_Gosub, pExpr->y.sub.regReturn,
  93754. pExpr->y.sub.iAddr);
  93755. sqlite3VdbeAddOp2(v, OP_OpenDup, iTab, pExpr->iTable);
  93756. sqlite3VdbeJumpHere(v, addrOnce);
  93757. return;
  93758. }
  93759. /* Begin coding the subroutine */
  93760. ExprSetProperty(pExpr, EP_Subrtn);
  93761. pExpr->y.sub.regReturn = ++pParse->nMem;
  93762. pExpr->y.sub.iAddr =
  93763. sqlite3VdbeAddOp2(v, OP_Integer, 0, pExpr->y.sub.regReturn) + 1;
  93764. VdbeComment((v, "return address"));
  93765. addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  93766. }
  93767. /* Check to see if this is a vector IN operator */
  93768. pLeft = pExpr->pLeft;
  93769. nVal = sqlite3ExprVectorSize(pLeft);
  93770. /* Construct the ephemeral table that will contain the content of
  93771. ** RHS of the IN operator.
  93772. */
  93773. pExpr->iTable = iTab;
  93774. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, nVal);
  93775. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  93776. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  93777. VdbeComment((v, "Result of SELECT %u", pExpr->x.pSelect->selId));
  93778. }else{
  93779. VdbeComment((v, "RHS of IN operator"));
  93780. }
  93781. #endif
  93782. pKeyInfo = sqlite3KeyInfoAlloc(pParse->db, nVal, 1);
  93783. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  93784. /* Case 1: expr IN (SELECT ...)
  93785. **
  93786. ** Generate code to write the results of the select into the temporary
  93787. ** table allocated and opened above.
  93788. */
  93789. Select *pSelect = pExpr->x.pSelect;
  93790. ExprList *pEList = pSelect->pEList;
  93791. ExplainQueryPlan((pParse, 1, "%sLIST SUBQUERY %d",
  93792. addrOnce?"":"CORRELATED ", pSelect->selId
  93793. ));
  93794. /* If the LHS and RHS of the IN operator do not match, that
  93795. ** error will have been caught long before we reach this point. */
  93796. if( ALWAYS(pEList->nExpr==nVal) ){
  93797. SelectDest dest;
  93798. int i;
  93799. sqlite3SelectDestInit(&dest, SRT_Set, iTab);
  93800. dest.zAffSdst = exprINAffinity(pParse, pExpr);
  93801. pSelect->iLimit = 0;
  93802. testcase( pSelect->selFlags & SF_Distinct );
  93803. testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
  93804. if( sqlite3Select(pParse, pSelect, &dest) ){
  93805. sqlite3DbFree(pParse->db, dest.zAffSdst);
  93806. sqlite3KeyInfoUnref(pKeyInfo);
  93807. return;
  93808. }
  93809. sqlite3DbFree(pParse->db, dest.zAffSdst);
  93810. assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
  93811. assert( pEList!=0 );
  93812. assert( pEList->nExpr>0 );
  93813. assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
  93814. for(i=0; i<nVal; i++){
  93815. Expr *p = sqlite3VectorFieldSubexpr(pLeft, i);
  93816. pKeyInfo->aColl[i] = sqlite3BinaryCompareCollSeq(
  93817. pParse, p, pEList->a[i].pExpr
  93818. );
  93819. }
  93820. }
  93821. }else if( ALWAYS(pExpr->x.pList!=0) ){
  93822. /* Case 2: expr IN (exprlist)
  93823. **
  93824. ** For each expression, build an index key from the evaluation and
  93825. ** store it in the temporary table. If <expr> is a column, then use
  93826. ** that columns affinity when building index keys. If <expr> is not
  93827. ** a column, use numeric affinity.
  93828. */
  93829. char affinity; /* Affinity of the LHS of the IN */
  93830. int i;
  93831. ExprList *pList = pExpr->x.pList;
  93832. struct ExprList_item *pItem;
  93833. int r1, r2, r3;
  93834. affinity = sqlite3ExprAffinity(pLeft);
  93835. if( !affinity ){
  93836. affinity = SQLITE_AFF_BLOB;
  93837. }
  93838. if( pKeyInfo ){
  93839. assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
  93840. pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
  93841. }
  93842. /* Loop through each expression in <exprlist>. */
  93843. r1 = sqlite3GetTempReg(pParse);
  93844. r2 = sqlite3GetTempReg(pParse);
  93845. for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
  93846. Expr *pE2 = pItem->pExpr;
  93847. /* If the expression is not constant then we will need to
  93848. ** disable the test that was generated above that makes sure
  93849. ** this code only executes once. Because for a non-constant
  93850. ** expression we need to rerun this code each time.
  93851. */
  93852. if( addrOnce && !sqlite3ExprIsConstant(pE2) ){
  93853. sqlite3VdbeChangeToNoop(v, addrOnce);
  93854. ExprClearProperty(pExpr, EP_Subrtn);
  93855. addrOnce = 0;
  93856. }
  93857. /* Evaluate the expression and insert it into the temp table */
  93858. r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
  93859. sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
  93860. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r2, r3, 1);
  93861. }
  93862. sqlite3ReleaseTempReg(pParse, r1);
  93863. sqlite3ReleaseTempReg(pParse, r2);
  93864. }
  93865. if( pKeyInfo ){
  93866. sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
  93867. }
  93868. if( addrOnce ){
  93869. sqlite3VdbeJumpHere(v, addrOnce);
  93870. /* Subroutine return */
  93871. sqlite3VdbeAddOp1(v, OP_Return, pExpr->y.sub.regReturn);
  93872. sqlite3VdbeChangeP1(v, pExpr->y.sub.iAddr-1, sqlite3VdbeCurrentAddr(v)-1);
  93873. }
  93874. }
  93875. #endif /* SQLITE_OMIT_SUBQUERY */
  93876. /*
  93877. ** Generate code for scalar subqueries used as a subquery expression
  93878. ** or EXISTS operator:
  93879. **
  93880. ** (SELECT a FROM b) -- subquery
  93881. ** EXISTS (SELECT a FROM b) -- EXISTS subquery
  93882. **
  93883. ** The pExpr parameter is the SELECT or EXISTS operator to be coded.
  93884. **
  93885. ** The register that holds the result. For a multi-column SELECT,
  93886. ** the result is stored in a contiguous array of registers and the
  93887. ** return value is the register of the left-most result column.
  93888. ** Return 0 if an error occurs.
  93889. */
  93890. #ifndef SQLITE_OMIT_SUBQUERY
  93891. SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){
  93892. int addrOnce = 0; /* Address of OP_Once at top of subroutine */
  93893. int rReg = 0; /* Register storing resulting */
  93894. Select *pSel; /* SELECT statement to encode */
  93895. SelectDest dest; /* How to deal with SELECT result */
  93896. int nReg; /* Registers to allocate */
  93897. Expr *pLimit; /* New limit expression */
  93898. Vdbe *v = pParse->pVdbe;
  93899. assert( v!=0 );
  93900. testcase( pExpr->op==TK_EXISTS );
  93901. testcase( pExpr->op==TK_SELECT );
  93902. assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
  93903. assert( ExprHasProperty(pExpr, EP_xIsSelect) );
  93904. pSel = pExpr->x.pSelect;
  93905. /* The evaluation of the EXISTS/SELECT must be repeated every time it
  93906. ** is encountered if any of the following is true:
  93907. **
  93908. ** * The right-hand side is a correlated subquery
  93909. ** * The right-hand side is an expression list containing variables
  93910. ** * We are inside a trigger
  93911. **
  93912. ** If all of the above are false, then we can run this code just once
  93913. ** save the results, and reuse the same result on subsequent invocations.
  93914. */
  93915. if( !ExprHasProperty(pExpr, EP_VarSelect) ){
  93916. /* If this routine has already been coded, then invoke it as a
  93917. ** subroutine. */
  93918. if( ExprHasProperty(pExpr, EP_Subrtn) ){
  93919. ExplainQueryPlan((pParse, 0, "REUSE SUBQUERY %d", pSel->selId));
  93920. sqlite3VdbeAddOp2(v, OP_Gosub, pExpr->y.sub.regReturn,
  93921. pExpr->y.sub.iAddr);
  93922. return pExpr->iTable;
  93923. }
  93924. /* Begin coding the subroutine */
  93925. ExprSetProperty(pExpr, EP_Subrtn);
  93926. pExpr->y.sub.regReturn = ++pParse->nMem;
  93927. pExpr->y.sub.iAddr =
  93928. sqlite3VdbeAddOp2(v, OP_Integer, 0, pExpr->y.sub.regReturn) + 1;
  93929. VdbeComment((v, "return address"));
  93930. addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  93931. }
  93932. /* For a SELECT, generate code to put the values for all columns of
  93933. ** the first row into an array of registers and return the index of
  93934. ** the first register.
  93935. **
  93936. ** If this is an EXISTS, write an integer 0 (not exists) or 1 (exists)
  93937. ** into a register and return that register number.
  93938. **
  93939. ** In both cases, the query is augmented with "LIMIT 1". Any
  93940. ** preexisting limit is discarded in place of the new LIMIT 1.
  93941. */
  93942. ExplainQueryPlan((pParse, 1, "%sSCALAR SUBQUERY %d",
  93943. addrOnce?"":"CORRELATED ", pSel->selId));
  93944. nReg = pExpr->op==TK_SELECT ? pSel->pEList->nExpr : 1;
  93945. sqlite3SelectDestInit(&dest, 0, pParse->nMem+1);
  93946. pParse->nMem += nReg;
  93947. if( pExpr->op==TK_SELECT ){
  93948. dest.eDest = SRT_Mem;
  93949. dest.iSdst = dest.iSDParm;
  93950. dest.nSdst = nReg;
  93951. sqlite3VdbeAddOp3(v, OP_Null, 0, dest.iSDParm, dest.iSDParm+nReg-1);
  93952. VdbeComment((v, "Init subquery result"));
  93953. }else{
  93954. dest.eDest = SRT_Exists;
  93955. sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
  93956. VdbeComment((v, "Init EXISTS result"));
  93957. }
  93958. pLimit = sqlite3ExprAlloc(pParse->db, TK_INTEGER,&sqlite3IntTokens[1], 0);
  93959. if( pSel->pLimit ){
  93960. sqlite3ExprDelete(pParse->db, pSel->pLimit->pLeft);
  93961. pSel->pLimit->pLeft = pLimit;
  93962. }else{
  93963. pSel->pLimit = sqlite3PExpr(pParse, TK_LIMIT, pLimit, 0);
  93964. }
  93965. pSel->iLimit = 0;
  93966. if( sqlite3Select(pParse, pSel, &dest) ){
  93967. return 0;
  93968. }
  93969. pExpr->iTable = rReg = dest.iSDParm;
  93970. ExprSetVVAProperty(pExpr, EP_NoReduce);
  93971. if( addrOnce ){
  93972. sqlite3VdbeJumpHere(v, addrOnce);
  93973. /* Subroutine return */
  93974. sqlite3VdbeAddOp1(v, OP_Return, pExpr->y.sub.regReturn);
  93975. sqlite3VdbeChangeP1(v, pExpr->y.sub.iAddr-1, sqlite3VdbeCurrentAddr(v)-1);
  93976. }
  93977. return rReg;
  93978. }
  93979. #endif /* SQLITE_OMIT_SUBQUERY */
  93980. #ifndef SQLITE_OMIT_SUBQUERY
  93981. /*
  93982. ** Expr pIn is an IN(...) expression. This function checks that the
  93983. ** sub-select on the RHS of the IN() operator has the same number of
  93984. ** columns as the vector on the LHS. Or, if the RHS of the IN() is not
  93985. ** a sub-query, that the LHS is a vector of size 1.
  93986. */
  93987. SQLITE_PRIVATE int sqlite3ExprCheckIN(Parse *pParse, Expr *pIn){
  93988. int nVector = sqlite3ExprVectorSize(pIn->pLeft);
  93989. if( (pIn->flags & EP_xIsSelect) ){
  93990. if( nVector!=pIn->x.pSelect->pEList->nExpr ){
  93991. sqlite3SubselectError(pParse, pIn->x.pSelect->pEList->nExpr, nVector);
  93992. return 1;
  93993. }
  93994. }else if( nVector!=1 ){
  93995. sqlite3VectorErrorMsg(pParse, pIn->pLeft);
  93996. return 1;
  93997. }
  93998. return 0;
  93999. }
  94000. #endif
  94001. #ifndef SQLITE_OMIT_SUBQUERY
  94002. /*
  94003. ** Generate code for an IN expression.
  94004. **
  94005. ** x IN (SELECT ...)
  94006. ** x IN (value, value, ...)
  94007. **
  94008. ** The left-hand side (LHS) is a scalar or vector expression. The
  94009. ** right-hand side (RHS) is an array of zero or more scalar values, or a
  94010. ** subquery. If the RHS is a subquery, the number of result columns must
  94011. ** match the number of columns in the vector on the LHS. If the RHS is
  94012. ** a list of values, the LHS must be a scalar.
  94013. **
  94014. ** The IN operator is true if the LHS value is contained within the RHS.
  94015. ** The result is false if the LHS is definitely not in the RHS. The
  94016. ** result is NULL if the presence of the LHS in the RHS cannot be
  94017. ** determined due to NULLs.
  94018. **
  94019. ** This routine generates code that jumps to destIfFalse if the LHS is not
  94020. ** contained within the RHS. If due to NULLs we cannot determine if the LHS
  94021. ** is contained in the RHS then jump to destIfNull. If the LHS is contained
  94022. ** within the RHS then fall through.
  94023. **
  94024. ** See the separate in-operator.md documentation file in the canonical
  94025. ** SQLite source tree for additional information.
  94026. */
  94027. static void sqlite3ExprCodeIN(
  94028. Parse *pParse, /* Parsing and code generating context */
  94029. Expr *pExpr, /* The IN expression */
  94030. int destIfFalse, /* Jump here if LHS is not contained in the RHS */
  94031. int destIfNull /* Jump here if the results are unknown due to NULLs */
  94032. ){
  94033. int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */
  94034. int eType; /* Type of the RHS */
  94035. int rLhs; /* Register(s) holding the LHS values */
  94036. int rLhsOrig; /* LHS values prior to reordering by aiMap[] */
  94037. Vdbe *v; /* Statement under construction */
  94038. int *aiMap = 0; /* Map from vector field to index column */
  94039. char *zAff = 0; /* Affinity string for comparisons */
  94040. int nVector; /* Size of vectors for this IN operator */
  94041. int iDummy; /* Dummy parameter to exprCodeVector() */
  94042. Expr *pLeft; /* The LHS of the IN operator */
  94043. int i; /* loop counter */
  94044. int destStep2; /* Where to jump when NULLs seen in step 2 */
  94045. int destStep6 = 0; /* Start of code for Step 6 */
  94046. int addrTruthOp; /* Address of opcode that determines the IN is true */
  94047. int destNotNull; /* Jump here if a comparison is not true in step 6 */
  94048. int addrTop; /* Top of the step-6 loop */
  94049. int iTab = 0; /* Index to use */
  94050. pLeft = pExpr->pLeft;
  94051. if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
  94052. zAff = exprINAffinity(pParse, pExpr);
  94053. nVector = sqlite3ExprVectorSize(pExpr->pLeft);
  94054. aiMap = (int*)sqlite3DbMallocZero(
  94055. pParse->db, nVector*(sizeof(int) + sizeof(char)) + 1
  94056. );
  94057. if( pParse->db->mallocFailed ) goto sqlite3ExprCodeIN_oom_error;
  94058. /* Attempt to compute the RHS. After this step, if anything other than
  94059. ** IN_INDEX_NOOP is returned, the table opened with cursor iTab
  94060. ** contains the values that make up the RHS. If IN_INDEX_NOOP is returned,
  94061. ** the RHS has not yet been coded. */
  94062. v = pParse->pVdbe;
  94063. assert( v!=0 ); /* OOM detected prior to this routine */
  94064. VdbeNoopComment((v, "begin IN expr"));
  94065. eType = sqlite3FindInIndex(pParse, pExpr,
  94066. IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
  94067. destIfFalse==destIfNull ? 0 : &rRhsHasNull,
  94068. aiMap, &iTab);
  94069. assert( pParse->nErr || nVector==1 || eType==IN_INDEX_EPH
  94070. || eType==IN_INDEX_INDEX_ASC || eType==IN_INDEX_INDEX_DESC
  94071. );
  94072. #ifdef SQLITE_DEBUG
  94073. /* Confirm that aiMap[] contains nVector integer values between 0 and
  94074. ** nVector-1. */
  94075. for(i=0; i<nVector; i++){
  94076. int j, cnt;
  94077. for(cnt=j=0; j<nVector; j++) if( aiMap[j]==i ) cnt++;
  94078. assert( cnt==1 );
  94079. }
  94080. #endif
  94081. /* Code the LHS, the <expr> from "<expr> IN (...)". If the LHS is a
  94082. ** vector, then it is stored in an array of nVector registers starting
  94083. ** at r1.
  94084. **
  94085. ** sqlite3FindInIndex() might have reordered the fields of the LHS vector
  94086. ** so that the fields are in the same order as an existing index. The
  94087. ** aiMap[] array contains a mapping from the original LHS field order to
  94088. ** the field order that matches the RHS index.
  94089. */
  94090. rLhsOrig = exprCodeVector(pParse, pLeft, &iDummy);
  94091. for(i=0; i<nVector && aiMap[i]==i; i++){} /* Are LHS fields reordered? */
  94092. if( i==nVector ){
  94093. /* LHS fields are not reordered */
  94094. rLhs = rLhsOrig;
  94095. }else{
  94096. /* Need to reorder the LHS fields according to aiMap */
  94097. rLhs = sqlite3GetTempRange(pParse, nVector);
  94098. for(i=0; i<nVector; i++){
  94099. sqlite3VdbeAddOp3(v, OP_Copy, rLhsOrig+i, rLhs+aiMap[i], 0);
  94100. }
  94101. }
  94102. /* If sqlite3FindInIndex() did not find or create an index that is
  94103. ** suitable for evaluating the IN operator, then evaluate using a
  94104. ** sequence of comparisons.
  94105. **
  94106. ** This is step (1) in the in-operator.md optimized algorithm.
  94107. */
  94108. if( eType==IN_INDEX_NOOP ){
  94109. ExprList *pList = pExpr->x.pList;
  94110. CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
  94111. int labelOk = sqlite3VdbeMakeLabel(pParse);
  94112. int r2, regToFree;
  94113. int regCkNull = 0;
  94114. int ii;
  94115. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  94116. if( destIfNull!=destIfFalse ){
  94117. regCkNull = sqlite3GetTempReg(pParse);
  94118. sqlite3VdbeAddOp3(v, OP_BitAnd, rLhs, rLhs, regCkNull);
  94119. }
  94120. for(ii=0; ii<pList->nExpr; ii++){
  94121. r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
  94122. if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
  94123. sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
  94124. }
  94125. if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
  94126. sqlite3VdbeAddOp4(v, OP_Eq, rLhs, labelOk, r2,
  94127. (void*)pColl, P4_COLLSEQ);
  94128. VdbeCoverageIf(v, ii<pList->nExpr-1);
  94129. VdbeCoverageIf(v, ii==pList->nExpr-1);
  94130. sqlite3VdbeChangeP5(v, zAff[0]);
  94131. }else{
  94132. assert( destIfNull==destIfFalse );
  94133. sqlite3VdbeAddOp4(v, OP_Ne, rLhs, destIfFalse, r2,
  94134. (void*)pColl, P4_COLLSEQ); VdbeCoverage(v);
  94135. sqlite3VdbeChangeP5(v, zAff[0] | SQLITE_JUMPIFNULL);
  94136. }
  94137. sqlite3ReleaseTempReg(pParse, regToFree);
  94138. }
  94139. if( regCkNull ){
  94140. sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
  94141. sqlite3VdbeGoto(v, destIfFalse);
  94142. }
  94143. sqlite3VdbeResolveLabel(v, labelOk);
  94144. sqlite3ReleaseTempReg(pParse, regCkNull);
  94145. goto sqlite3ExprCodeIN_finished;
  94146. }
  94147. /* Step 2: Check to see if the LHS contains any NULL columns. If the
  94148. ** LHS does contain NULLs then the result must be either FALSE or NULL.
  94149. ** We will then skip the binary search of the RHS.
  94150. */
  94151. if( destIfNull==destIfFalse ){
  94152. destStep2 = destIfFalse;
  94153. }else{
  94154. destStep2 = destStep6 = sqlite3VdbeMakeLabel(pParse);
  94155. }
  94156. for(i=0; i<nVector; i++){
  94157. Expr *p = sqlite3VectorFieldSubexpr(pExpr->pLeft, i);
  94158. if( sqlite3ExprCanBeNull(p) ){
  94159. sqlite3VdbeAddOp2(v, OP_IsNull, rLhs+i, destStep2);
  94160. VdbeCoverage(v);
  94161. }
  94162. }
  94163. /* Step 3. The LHS is now known to be non-NULL. Do the binary search
  94164. ** of the RHS using the LHS as a probe. If found, the result is
  94165. ** true.
  94166. */
  94167. if( eType==IN_INDEX_ROWID ){
  94168. /* In this case, the RHS is the ROWID of table b-tree and so we also
  94169. ** know that the RHS is non-NULL. Hence, we combine steps 3 and 4
  94170. ** into a single opcode. */
  94171. sqlite3VdbeAddOp3(v, OP_SeekRowid, iTab, destIfFalse, rLhs);
  94172. VdbeCoverage(v);
  94173. addrTruthOp = sqlite3VdbeAddOp0(v, OP_Goto); /* Return True */
  94174. }else{
  94175. sqlite3VdbeAddOp4(v, OP_Affinity, rLhs, nVector, 0, zAff, nVector);
  94176. if( destIfFalse==destIfNull ){
  94177. /* Combine Step 3 and Step 5 into a single opcode */
  94178. sqlite3VdbeAddOp4Int(v, OP_NotFound, iTab, destIfFalse,
  94179. rLhs, nVector); VdbeCoverage(v);
  94180. goto sqlite3ExprCodeIN_finished;
  94181. }
  94182. /* Ordinary Step 3, for the case where FALSE and NULL are distinct */
  94183. addrTruthOp = sqlite3VdbeAddOp4Int(v, OP_Found, iTab, 0,
  94184. rLhs, nVector); VdbeCoverage(v);
  94185. }
  94186. /* Step 4. If the RHS is known to be non-NULL and we did not find
  94187. ** an match on the search above, then the result must be FALSE.
  94188. */
  94189. if( rRhsHasNull && nVector==1 ){
  94190. sqlite3VdbeAddOp2(v, OP_NotNull, rRhsHasNull, destIfFalse);
  94191. VdbeCoverage(v);
  94192. }
  94193. /* Step 5. If we do not care about the difference between NULL and
  94194. ** FALSE, then just return false.
  94195. */
  94196. if( destIfFalse==destIfNull ) sqlite3VdbeGoto(v, destIfFalse);
  94197. /* Step 6: Loop through rows of the RHS. Compare each row to the LHS.
  94198. ** If any comparison is NULL, then the result is NULL. If all
  94199. ** comparisons are FALSE then the final result is FALSE.
  94200. **
  94201. ** For a scalar LHS, it is sufficient to check just the first row
  94202. ** of the RHS.
  94203. */
  94204. if( destStep6 ) sqlite3VdbeResolveLabel(v, destStep6);
  94205. addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, destIfFalse);
  94206. VdbeCoverage(v);
  94207. if( nVector>1 ){
  94208. destNotNull = sqlite3VdbeMakeLabel(pParse);
  94209. }else{
  94210. /* For nVector==1, combine steps 6 and 7 by immediately returning
  94211. ** FALSE if the first comparison is not NULL */
  94212. destNotNull = destIfFalse;
  94213. }
  94214. for(i=0; i<nVector; i++){
  94215. Expr *p;
  94216. CollSeq *pColl;
  94217. int r3 = sqlite3GetTempReg(pParse);
  94218. p = sqlite3VectorFieldSubexpr(pLeft, i);
  94219. pColl = sqlite3ExprCollSeq(pParse, p);
  94220. sqlite3VdbeAddOp3(v, OP_Column, iTab, i, r3);
  94221. sqlite3VdbeAddOp4(v, OP_Ne, rLhs+i, destNotNull, r3,
  94222. (void*)pColl, P4_COLLSEQ);
  94223. VdbeCoverage(v);
  94224. sqlite3ReleaseTempReg(pParse, r3);
  94225. }
  94226. sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
  94227. if( nVector>1 ){
  94228. sqlite3VdbeResolveLabel(v, destNotNull);
  94229. sqlite3VdbeAddOp2(v, OP_Next, iTab, addrTop+1);
  94230. VdbeCoverage(v);
  94231. /* Step 7: If we reach this point, we know that the result must
  94232. ** be false. */
  94233. sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
  94234. }
  94235. /* Jumps here in order to return true. */
  94236. sqlite3VdbeJumpHere(v, addrTruthOp);
  94237. sqlite3ExprCodeIN_finished:
  94238. if( rLhs!=rLhsOrig ) sqlite3ReleaseTempReg(pParse, rLhs);
  94239. VdbeComment((v, "end IN expr"));
  94240. sqlite3ExprCodeIN_oom_error:
  94241. sqlite3DbFree(pParse->db, aiMap);
  94242. sqlite3DbFree(pParse->db, zAff);
  94243. }
  94244. #endif /* SQLITE_OMIT_SUBQUERY */
  94245. #ifndef SQLITE_OMIT_FLOATING_POINT
  94246. /*
  94247. ** Generate an instruction that will put the floating point
  94248. ** value described by z[0..n-1] into register iMem.
  94249. **
  94250. ** The z[] string will probably not be zero-terminated. But the
  94251. ** z[n] character is guaranteed to be something that does not look
  94252. ** like the continuation of the number.
  94253. */
  94254. static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
  94255. if( ALWAYS(z!=0) ){
  94256. double value;
  94257. sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
  94258. assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
  94259. if( negateFlag ) value = -value;
  94260. sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL);
  94261. }
  94262. }
  94263. #endif
  94264. /*
  94265. ** Generate an instruction that will put the integer describe by
  94266. ** text z[0..n-1] into register iMem.
  94267. **
  94268. ** Expr.u.zToken is always UTF8 and zero-terminated.
  94269. */
  94270. static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
  94271. Vdbe *v = pParse->pVdbe;
  94272. if( pExpr->flags & EP_IntValue ){
  94273. int i = pExpr->u.iValue;
  94274. assert( i>=0 );
  94275. if( negFlag ) i = -i;
  94276. sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
  94277. }else{
  94278. int c;
  94279. i64 value;
  94280. const char *z = pExpr->u.zToken;
  94281. assert( z!=0 );
  94282. c = sqlite3DecOrHexToI64(z, &value);
  94283. if( (c==3 && !negFlag) || (c==2) || (negFlag && value==SMALLEST_INT64)){
  94284. #ifdef SQLITE_OMIT_FLOATING_POINT
  94285. sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
  94286. #else
  94287. #ifndef SQLITE_OMIT_HEX_INTEGER
  94288. if( sqlite3_strnicmp(z,"0x",2)==0 ){
  94289. sqlite3ErrorMsg(pParse, "hex literal too big: %s%s", negFlag?"-":"",z);
  94290. }else
  94291. #endif
  94292. {
  94293. codeReal(v, z, negFlag, iMem);
  94294. }
  94295. #endif
  94296. }else{
  94297. if( negFlag ){ value = c==3 ? SMALLEST_INT64 : -value; }
  94298. sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64);
  94299. }
  94300. }
  94301. }
  94302. /* Generate code that will load into register regOut a value that is
  94303. ** appropriate for the iIdxCol-th column of index pIdx.
  94304. */
  94305. SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(
  94306. Parse *pParse, /* The parsing context */
  94307. Index *pIdx, /* The index whose column is to be loaded */
  94308. int iTabCur, /* Cursor pointing to a table row */
  94309. int iIdxCol, /* The column of the index to be loaded */
  94310. int regOut /* Store the index column value in this register */
  94311. ){
  94312. i16 iTabCol = pIdx->aiColumn[iIdxCol];
  94313. if( iTabCol==XN_EXPR ){
  94314. assert( pIdx->aColExpr );
  94315. assert( pIdx->aColExpr->nExpr>iIdxCol );
  94316. pParse->iSelfTab = iTabCur + 1;
  94317. sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut);
  94318. pParse->iSelfTab = 0;
  94319. }else{
  94320. sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur,
  94321. iTabCol, regOut);
  94322. }
  94323. }
  94324. /*
  94325. ** Generate code to extract the value of the iCol-th column of a table.
  94326. */
  94327. SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
  94328. Vdbe *v, /* The VDBE under construction */
  94329. Table *pTab, /* The table containing the value */
  94330. int iTabCur, /* The table cursor. Or the PK cursor for WITHOUT ROWID */
  94331. int iCol, /* Index of the column to extract */
  94332. int regOut /* Extract the value into this register */
  94333. ){
  94334. if( pTab==0 ){
  94335. sqlite3VdbeAddOp3(v, OP_Column, iTabCur, iCol, regOut);
  94336. return;
  94337. }
  94338. if( iCol<0 || iCol==pTab->iPKey ){
  94339. sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
  94340. }else{
  94341. int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
  94342. int x = iCol;
  94343. if( !HasRowid(pTab) && !IsVirtual(pTab) ){
  94344. x = sqlite3ColumnOfIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
  94345. }
  94346. sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
  94347. }
  94348. if( iCol>=0 ){
  94349. sqlite3ColumnDefault(v, pTab, iCol, regOut);
  94350. }
  94351. }
  94352. /*
  94353. ** Generate code that will extract the iColumn-th column from
  94354. ** table pTab and store the column value in register iReg.
  94355. **
  94356. ** There must be an open cursor to pTab in iTable when this routine
  94357. ** is called. If iColumn<0 then code is generated that extracts the rowid.
  94358. */
  94359. SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
  94360. Parse *pParse, /* Parsing and code generating context */
  94361. Table *pTab, /* Description of the table we are reading from */
  94362. int iColumn, /* Index of the table column */
  94363. int iTable, /* The cursor pointing to the table */
  94364. int iReg, /* Store results here */
  94365. u8 p5 /* P5 value for OP_Column + FLAGS */
  94366. ){
  94367. Vdbe *v = pParse->pVdbe;
  94368. assert( v!=0 );
  94369. sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
  94370. if( p5 ){
  94371. sqlite3VdbeChangeP5(v, p5);
  94372. }
  94373. return iReg;
  94374. }
  94375. /*
  94376. ** Generate code to move content from registers iFrom...iFrom+nReg-1
  94377. ** over to iTo..iTo+nReg-1.
  94378. */
  94379. SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
  94380. assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
  94381. sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
  94382. }
  94383. /*
  94384. ** Convert a scalar expression node to a TK_REGISTER referencing
  94385. ** register iReg. The caller must ensure that iReg already contains
  94386. ** the correct value for the expression.
  94387. */
  94388. static void exprToRegister(Expr *pExpr, int iReg){
  94389. Expr *p = sqlite3ExprSkipCollate(pExpr);
  94390. p->op2 = p->op;
  94391. p->op = TK_REGISTER;
  94392. p->iTable = iReg;
  94393. ExprClearProperty(p, EP_Skip);
  94394. }
  94395. /*
  94396. ** Evaluate an expression (either a vector or a scalar expression) and store
  94397. ** the result in continguous temporary registers. Return the index of
  94398. ** the first register used to store the result.
  94399. **
  94400. ** If the returned result register is a temporary scalar, then also write
  94401. ** that register number into *piFreeable. If the returned result register
  94402. ** is not a temporary or if the expression is a vector set *piFreeable
  94403. ** to 0.
  94404. */
  94405. static int exprCodeVector(Parse *pParse, Expr *p, int *piFreeable){
  94406. int iResult;
  94407. int nResult = sqlite3ExprVectorSize(p);
  94408. if( nResult==1 ){
  94409. iResult = sqlite3ExprCodeTemp(pParse, p, piFreeable);
  94410. }else{
  94411. *piFreeable = 0;
  94412. if( p->op==TK_SELECT ){
  94413. #if SQLITE_OMIT_SUBQUERY
  94414. iResult = 0;
  94415. #else
  94416. iResult = sqlite3CodeSubselect(pParse, p);
  94417. #endif
  94418. }else{
  94419. int i;
  94420. iResult = pParse->nMem+1;
  94421. pParse->nMem += nResult;
  94422. for(i=0; i<nResult; i++){
  94423. sqlite3ExprCodeFactorable(pParse, p->x.pList->a[i].pExpr, i+iResult);
  94424. }
  94425. }
  94426. }
  94427. return iResult;
  94428. }
  94429. /*
  94430. ** Generate code into the current Vdbe to evaluate the given
  94431. ** expression. Attempt to store the results in register "target".
  94432. ** Return the register where results are stored.
  94433. **
  94434. ** With this routine, there is no guarantee that results will
  94435. ** be stored in target. The result might be stored in some other
  94436. ** register if it is convenient to do so. The calling function
  94437. ** must check the return code and move the results to the desired
  94438. ** register.
  94439. */
  94440. SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
  94441. Vdbe *v = pParse->pVdbe; /* The VM under construction */
  94442. int op; /* The opcode being coded */
  94443. int inReg = target; /* Results stored in register inReg */
  94444. int regFree1 = 0; /* If non-zero free this temporary register */
  94445. int regFree2 = 0; /* If non-zero free this temporary register */
  94446. int r1, r2; /* Various register numbers */
  94447. Expr tempX; /* Temporary expression node */
  94448. int p5 = 0;
  94449. assert( target>0 && target<=pParse->nMem );
  94450. if( v==0 ){
  94451. assert( pParse->db->mallocFailed );
  94452. return 0;
  94453. }
  94454. expr_code_doover:
  94455. if( pExpr==0 ){
  94456. op = TK_NULL;
  94457. }else{
  94458. op = pExpr->op;
  94459. }
  94460. switch( op ){
  94461. case TK_AGG_COLUMN: {
  94462. AggInfo *pAggInfo = pExpr->pAggInfo;
  94463. struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
  94464. if( !pAggInfo->directMode ){
  94465. assert( pCol->iMem>0 );
  94466. return pCol->iMem;
  94467. }else if( pAggInfo->useSortingIdx ){
  94468. sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
  94469. pCol->iSorterColumn, target);
  94470. return target;
  94471. }
  94472. /* Otherwise, fall thru into the TK_COLUMN case */
  94473. }
  94474. case TK_COLUMN: {
  94475. int iTab = pExpr->iTable;
  94476. if( ExprHasProperty(pExpr, EP_FixedCol) ){
  94477. /* This COLUMN expression is really a constant due to WHERE clause
  94478. ** constraints, and that constant is coded by the pExpr->pLeft
  94479. ** expresssion. However, make sure the constant has the correct
  94480. ** datatype by applying the Affinity of the table column to the
  94481. ** constant.
  94482. */
  94483. int iReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft,target);
  94484. int aff = sqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn);
  94485. if( aff!=SQLITE_AFF_BLOB ){
  94486. static const char zAff[] = "B\000C\000D\000E";
  94487. assert( SQLITE_AFF_BLOB=='A' );
  94488. assert( SQLITE_AFF_TEXT=='B' );
  94489. if( iReg!=target ){
  94490. sqlite3VdbeAddOp2(v, OP_SCopy, iReg, target);
  94491. iReg = target;
  94492. }
  94493. sqlite3VdbeAddOp4(v, OP_Affinity, iReg, 1, 0,
  94494. &zAff[(aff-'B')*2], P4_STATIC);
  94495. }
  94496. return iReg;
  94497. }
  94498. if( iTab<0 ){
  94499. if( pParse->iSelfTab<0 ){
  94500. /* Generating CHECK constraints or inserting into partial index */
  94501. return pExpr->iColumn - pParse->iSelfTab;
  94502. }else{
  94503. /* Coding an expression that is part of an index where column names
  94504. ** in the index refer to the table to which the index belongs */
  94505. iTab = pParse->iSelfTab - 1;
  94506. }
  94507. }
  94508. return sqlite3ExprCodeGetColumn(pParse, pExpr->y.pTab,
  94509. pExpr->iColumn, iTab, target,
  94510. pExpr->op2);
  94511. }
  94512. case TK_INTEGER: {
  94513. codeInteger(pParse, pExpr, 0, target);
  94514. return target;
  94515. }
  94516. case TK_TRUEFALSE: {
  94517. sqlite3VdbeAddOp2(v, OP_Integer, sqlite3ExprTruthValue(pExpr), target);
  94518. return target;
  94519. }
  94520. #ifndef SQLITE_OMIT_FLOATING_POINT
  94521. case TK_FLOAT: {
  94522. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  94523. codeReal(v, pExpr->u.zToken, 0, target);
  94524. return target;
  94525. }
  94526. #endif
  94527. case TK_STRING: {
  94528. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  94529. sqlite3VdbeLoadString(v, target, pExpr->u.zToken);
  94530. return target;
  94531. }
  94532. case TK_NULL: {
  94533. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  94534. return target;
  94535. }
  94536. #ifndef SQLITE_OMIT_BLOB_LITERAL
  94537. case TK_BLOB: {
  94538. int n;
  94539. const char *z;
  94540. char *zBlob;
  94541. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  94542. assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
  94543. assert( pExpr->u.zToken[1]=='\'' );
  94544. z = &pExpr->u.zToken[2];
  94545. n = sqlite3Strlen30(z) - 1;
  94546. assert( z[n]=='\'' );
  94547. zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
  94548. sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
  94549. return target;
  94550. }
  94551. #endif
  94552. case TK_VARIABLE: {
  94553. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  94554. assert( pExpr->u.zToken!=0 );
  94555. assert( pExpr->u.zToken[0]!=0 );
  94556. sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
  94557. if( pExpr->u.zToken[1]!=0 ){
  94558. const char *z = sqlite3VListNumToName(pParse->pVList, pExpr->iColumn);
  94559. assert( pExpr->u.zToken[0]=='?' || strcmp(pExpr->u.zToken, z)==0 );
  94560. pParse->pVList[0] = 0; /* Indicate VList may no longer be enlarged */
  94561. sqlite3VdbeAppendP4(v, (char*)z, P4_STATIC);
  94562. }
  94563. return target;
  94564. }
  94565. case TK_REGISTER: {
  94566. return pExpr->iTable;
  94567. }
  94568. #ifndef SQLITE_OMIT_CAST
  94569. case TK_CAST: {
  94570. /* Expressions of the form: CAST(pLeft AS token) */
  94571. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  94572. if( inReg!=target ){
  94573. sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
  94574. inReg = target;
  94575. }
  94576. sqlite3VdbeAddOp2(v, OP_Cast, target,
  94577. sqlite3AffinityType(pExpr->u.zToken, 0));
  94578. return inReg;
  94579. }
  94580. #endif /* SQLITE_OMIT_CAST */
  94581. case TK_IS:
  94582. case TK_ISNOT:
  94583. op = (op==TK_IS) ? TK_EQ : TK_NE;
  94584. p5 = SQLITE_NULLEQ;
  94585. /* fall-through */
  94586. case TK_LT:
  94587. case TK_LE:
  94588. case TK_GT:
  94589. case TK_GE:
  94590. case TK_NE:
  94591. case TK_EQ: {
  94592. Expr *pLeft = pExpr->pLeft;
  94593. if( sqlite3ExprIsVector(pLeft) ){
  94594. codeVectorCompare(pParse, pExpr, target, op, p5);
  94595. }else{
  94596. r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
  94597. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  94598. codeCompare(pParse, pLeft, pExpr->pRight, op,
  94599. r1, r2, inReg, SQLITE_STOREP2 | p5);
  94600. assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
  94601. assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
  94602. assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
  94603. assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
  94604. assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
  94605. assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
  94606. testcase( regFree1==0 );
  94607. testcase( regFree2==0 );
  94608. }
  94609. break;
  94610. }
  94611. case TK_AND:
  94612. case TK_OR:
  94613. case TK_PLUS:
  94614. case TK_STAR:
  94615. case TK_MINUS:
  94616. case TK_REM:
  94617. case TK_BITAND:
  94618. case TK_BITOR:
  94619. case TK_SLASH:
  94620. case TK_LSHIFT:
  94621. case TK_RSHIFT:
  94622. case TK_CONCAT: {
  94623. assert( TK_AND==OP_And ); testcase( op==TK_AND );
  94624. assert( TK_OR==OP_Or ); testcase( op==TK_OR );
  94625. assert( TK_PLUS==OP_Add ); testcase( op==TK_PLUS );
  94626. assert( TK_MINUS==OP_Subtract ); testcase( op==TK_MINUS );
  94627. assert( TK_REM==OP_Remainder ); testcase( op==TK_REM );
  94628. assert( TK_BITAND==OP_BitAnd ); testcase( op==TK_BITAND );
  94629. assert( TK_BITOR==OP_BitOr ); testcase( op==TK_BITOR );
  94630. assert( TK_SLASH==OP_Divide ); testcase( op==TK_SLASH );
  94631. assert( TK_LSHIFT==OP_ShiftLeft ); testcase( op==TK_LSHIFT );
  94632. assert( TK_RSHIFT==OP_ShiftRight ); testcase( op==TK_RSHIFT );
  94633. assert( TK_CONCAT==OP_Concat ); testcase( op==TK_CONCAT );
  94634. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  94635. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  94636. sqlite3VdbeAddOp3(v, op, r2, r1, target);
  94637. testcase( regFree1==0 );
  94638. testcase( regFree2==0 );
  94639. break;
  94640. }
  94641. case TK_UMINUS: {
  94642. Expr *pLeft = pExpr->pLeft;
  94643. assert( pLeft );
  94644. if( pLeft->op==TK_INTEGER ){
  94645. codeInteger(pParse, pLeft, 1, target);
  94646. return target;
  94647. #ifndef SQLITE_OMIT_FLOATING_POINT
  94648. }else if( pLeft->op==TK_FLOAT ){
  94649. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  94650. codeReal(v, pLeft->u.zToken, 1, target);
  94651. return target;
  94652. #endif
  94653. }else{
  94654. tempX.op = TK_INTEGER;
  94655. tempX.flags = EP_IntValue|EP_TokenOnly;
  94656. tempX.u.iValue = 0;
  94657. r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
  94658. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
  94659. sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
  94660. testcase( regFree2==0 );
  94661. }
  94662. break;
  94663. }
  94664. case TK_BITNOT:
  94665. case TK_NOT: {
  94666. assert( TK_BITNOT==OP_BitNot ); testcase( op==TK_BITNOT );
  94667. assert( TK_NOT==OP_Not ); testcase( op==TK_NOT );
  94668. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  94669. testcase( regFree1==0 );
  94670. sqlite3VdbeAddOp2(v, op, r1, inReg);
  94671. break;
  94672. }
  94673. case TK_TRUTH: {
  94674. int isTrue; /* IS TRUE or IS NOT TRUE */
  94675. int bNormal; /* IS TRUE or IS FALSE */
  94676. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  94677. testcase( regFree1==0 );
  94678. isTrue = sqlite3ExprTruthValue(pExpr->pRight);
  94679. bNormal = pExpr->op2==TK_IS;
  94680. testcase( isTrue && bNormal);
  94681. testcase( !isTrue && bNormal);
  94682. sqlite3VdbeAddOp4Int(v, OP_IsTrue, r1, inReg, !isTrue, isTrue ^ bNormal);
  94683. break;
  94684. }
  94685. case TK_ISNULL:
  94686. case TK_NOTNULL: {
  94687. int addr;
  94688. assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
  94689. assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
  94690. sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
  94691. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  94692. testcase( regFree1==0 );
  94693. addr = sqlite3VdbeAddOp1(v, op, r1);
  94694. VdbeCoverageIf(v, op==TK_ISNULL);
  94695. VdbeCoverageIf(v, op==TK_NOTNULL);
  94696. sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
  94697. sqlite3VdbeJumpHere(v, addr);
  94698. break;
  94699. }
  94700. case TK_AGG_FUNCTION: {
  94701. AggInfo *pInfo = pExpr->pAggInfo;
  94702. if( pInfo==0 ){
  94703. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  94704. sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
  94705. }else{
  94706. return pInfo->aFunc[pExpr->iAgg].iMem;
  94707. }
  94708. break;
  94709. }
  94710. case TK_FUNCTION: {
  94711. ExprList *pFarg; /* List of function arguments */
  94712. int nFarg; /* Number of function arguments */
  94713. FuncDef *pDef; /* The function definition object */
  94714. const char *zId; /* The function name */
  94715. u32 constMask = 0; /* Mask of function arguments that are constant */
  94716. int i; /* Loop counter */
  94717. sqlite3 *db = pParse->db; /* The database connection */
  94718. u8 enc = ENC(db); /* The text encoding used by this database */
  94719. CollSeq *pColl = 0; /* A collating sequence */
  94720. #ifndef SQLITE_OMIT_WINDOWFUNC
  94721. if( ExprHasProperty(pExpr, EP_WinFunc) ){
  94722. return pExpr->y.pWin->regResult;
  94723. }
  94724. #endif
  94725. if( ConstFactorOk(pParse) && sqlite3ExprIsConstantNotJoin(pExpr) ){
  94726. /* SQL functions can be expensive. So try to move constant functions
  94727. ** out of the inner loop, even if that means an extra OP_Copy. */
  94728. return sqlite3ExprCodeAtInit(pParse, pExpr, -1);
  94729. }
  94730. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  94731. if( ExprHasProperty(pExpr, EP_TokenOnly) ){
  94732. pFarg = 0;
  94733. }else{
  94734. pFarg = pExpr->x.pList;
  94735. }
  94736. nFarg = pFarg ? pFarg->nExpr : 0;
  94737. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  94738. zId = pExpr->u.zToken;
  94739. pDef = sqlite3FindFunction(db, zId, nFarg, enc, 0);
  94740. #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
  94741. if( pDef==0 && pParse->explain ){
  94742. pDef = sqlite3FindFunction(db, "unknown", nFarg, enc, 0);
  94743. }
  94744. #endif
  94745. if( pDef==0 || pDef->xFinalize!=0 ){
  94746. sqlite3ErrorMsg(pParse, "unknown function: %s()", zId);
  94747. break;
  94748. }
  94749. /* Attempt a direct implementation of the built-in COALESCE() and
  94750. ** IFNULL() functions. This avoids unnecessary evaluation of
  94751. ** arguments past the first non-NULL argument.
  94752. */
  94753. if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
  94754. int endCoalesce = sqlite3VdbeMakeLabel(pParse);
  94755. assert( nFarg>=2 );
  94756. sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
  94757. for(i=1; i<nFarg; i++){
  94758. sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
  94759. VdbeCoverage(v);
  94760. sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
  94761. }
  94762. sqlite3VdbeResolveLabel(v, endCoalesce);
  94763. break;
  94764. }
  94765. /* The UNLIKELY() function is a no-op. The result is the value
  94766. ** of the first argument.
  94767. */
  94768. if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
  94769. assert( nFarg>=1 );
  94770. return sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target);
  94771. }
  94772. #ifdef SQLITE_DEBUG
  94773. /* The AFFINITY() function evaluates to a string that describes
  94774. ** the type affinity of the argument. This is used for testing of
  94775. ** the SQLite type logic.
  94776. */
  94777. if( pDef->funcFlags & SQLITE_FUNC_AFFINITY ){
  94778. const char *azAff[] = { "blob", "text", "numeric", "integer", "real" };
  94779. char aff;
  94780. assert( nFarg==1 );
  94781. aff = sqlite3ExprAffinity(pFarg->a[0].pExpr);
  94782. sqlite3VdbeLoadString(v, target,
  94783. aff ? azAff[aff-SQLITE_AFF_BLOB] : "none");
  94784. return target;
  94785. }
  94786. #endif
  94787. for(i=0; i<nFarg; i++){
  94788. if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
  94789. testcase( i==31 );
  94790. constMask |= MASKBIT32(i);
  94791. }
  94792. if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
  94793. pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
  94794. }
  94795. }
  94796. if( pFarg ){
  94797. if( constMask ){
  94798. r1 = pParse->nMem+1;
  94799. pParse->nMem += nFarg;
  94800. }else{
  94801. r1 = sqlite3GetTempRange(pParse, nFarg);
  94802. }
  94803. /* For length() and typeof() functions with a column argument,
  94804. ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
  94805. ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
  94806. ** loading.
  94807. */
  94808. if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
  94809. u8 exprOp;
  94810. assert( nFarg==1 );
  94811. assert( pFarg->a[0].pExpr!=0 );
  94812. exprOp = pFarg->a[0].pExpr->op;
  94813. if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
  94814. assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
  94815. assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
  94816. testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
  94817. pFarg->a[0].pExpr->op2 =
  94818. pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
  94819. }
  94820. }
  94821. sqlite3ExprCodeExprList(pParse, pFarg, r1, 0,
  94822. SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);
  94823. }else{
  94824. r1 = 0;
  94825. }
  94826. #ifndef SQLITE_OMIT_VIRTUALTABLE
  94827. /* Possibly overload the function if the first argument is
  94828. ** a virtual table column.
  94829. **
  94830. ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
  94831. ** second argument, not the first, as the argument to test to
  94832. ** see if it is a column in a virtual table. This is done because
  94833. ** the left operand of infix functions (the operand we want to
  94834. ** control overloading) ends up as the second argument to the
  94835. ** function. The expression "A glob B" is equivalent to
  94836. ** "glob(B,A). We want to use the A in "A glob B" to test
  94837. ** for function overloading. But we use the B term in "glob(B,A)".
  94838. */
  94839. if( nFarg>=2 && ExprHasProperty(pExpr, EP_InfixFunc) ){
  94840. pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
  94841. }else if( nFarg>0 ){
  94842. pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
  94843. }
  94844. #endif
  94845. if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
  94846. if( !pColl ) pColl = db->pDfltColl;
  94847. sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
  94848. }
  94849. #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
  94850. if( pDef->funcFlags & SQLITE_FUNC_OFFSET ){
  94851. Expr *pArg = pFarg->a[0].pExpr;
  94852. if( pArg->op==TK_COLUMN ){
  94853. sqlite3VdbeAddOp3(v, OP_Offset, pArg->iTable, pArg->iColumn, target);
  94854. }else{
  94855. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  94856. }
  94857. }else
  94858. #endif
  94859. {
  94860. sqlite3VdbeAddOp4(v, pParse->iSelfTab ? OP_PureFunc0 : OP_Function0,
  94861. constMask, r1, target, (char*)pDef, P4_FUNCDEF);
  94862. sqlite3VdbeChangeP5(v, (u8)nFarg);
  94863. }
  94864. if( nFarg && constMask==0 ){
  94865. sqlite3ReleaseTempRange(pParse, r1, nFarg);
  94866. }
  94867. return target;
  94868. }
  94869. #ifndef SQLITE_OMIT_SUBQUERY
  94870. case TK_EXISTS:
  94871. case TK_SELECT: {
  94872. int nCol;
  94873. testcase( op==TK_EXISTS );
  94874. testcase( op==TK_SELECT );
  94875. if( op==TK_SELECT && (nCol = pExpr->x.pSelect->pEList->nExpr)!=1 ){
  94876. sqlite3SubselectError(pParse, nCol, 1);
  94877. }else{
  94878. return sqlite3CodeSubselect(pParse, pExpr);
  94879. }
  94880. break;
  94881. }
  94882. case TK_SELECT_COLUMN: {
  94883. int n;
  94884. if( pExpr->pLeft->iTable==0 ){
  94885. pExpr->pLeft->iTable = sqlite3CodeSubselect(pParse, pExpr->pLeft);
  94886. }
  94887. assert( pExpr->iTable==0 || pExpr->pLeft->op==TK_SELECT );
  94888. if( pExpr->iTable
  94889. && pExpr->iTable!=(n = sqlite3ExprVectorSize(pExpr->pLeft))
  94890. ){
  94891. sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
  94892. pExpr->iTable, n);
  94893. }
  94894. return pExpr->pLeft->iTable + pExpr->iColumn;
  94895. }
  94896. case TK_IN: {
  94897. int destIfFalse = sqlite3VdbeMakeLabel(pParse);
  94898. int destIfNull = sqlite3VdbeMakeLabel(pParse);
  94899. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  94900. sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
  94901. sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
  94902. sqlite3VdbeResolveLabel(v, destIfFalse);
  94903. sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
  94904. sqlite3VdbeResolveLabel(v, destIfNull);
  94905. return target;
  94906. }
  94907. #endif /* SQLITE_OMIT_SUBQUERY */
  94908. /*
  94909. ** x BETWEEN y AND z
  94910. **
  94911. ** This is equivalent to
  94912. **
  94913. ** x>=y AND x<=z
  94914. **
  94915. ** X is stored in pExpr->pLeft.
  94916. ** Y is stored in pExpr->pList->a[0].pExpr.
  94917. ** Z is stored in pExpr->pList->a[1].pExpr.
  94918. */
  94919. case TK_BETWEEN: {
  94920. exprCodeBetween(pParse, pExpr, target, 0, 0);
  94921. return target;
  94922. }
  94923. case TK_SPAN:
  94924. case TK_COLLATE:
  94925. case TK_UPLUS: {
  94926. pExpr = pExpr->pLeft;
  94927. goto expr_code_doover; /* 2018-04-28: Prevent deep recursion. OSSFuzz. */
  94928. }
  94929. case TK_TRIGGER: {
  94930. /* If the opcode is TK_TRIGGER, then the expression is a reference
  94931. ** to a column in the new.* or old.* pseudo-tables available to
  94932. ** trigger programs. In this case Expr.iTable is set to 1 for the
  94933. ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
  94934. ** is set to the column of the pseudo-table to read, or to -1 to
  94935. ** read the rowid field.
  94936. **
  94937. ** The expression is implemented using an OP_Param opcode. The p1
  94938. ** parameter is set to 0 for an old.rowid reference, or to (i+1)
  94939. ** to reference another column of the old.* pseudo-table, where
  94940. ** i is the index of the column. For a new.rowid reference, p1 is
  94941. ** set to (n+1), where n is the number of columns in each pseudo-table.
  94942. ** For a reference to any other column in the new.* pseudo-table, p1
  94943. ** is set to (n+2+i), where n and i are as defined previously. For
  94944. ** example, if the table on which triggers are being fired is
  94945. ** declared as:
  94946. **
  94947. ** CREATE TABLE t1(a, b);
  94948. **
  94949. ** Then p1 is interpreted as follows:
  94950. **
  94951. ** p1==0 -> old.rowid p1==3 -> new.rowid
  94952. ** p1==1 -> old.a p1==4 -> new.a
  94953. ** p1==2 -> old.b p1==5 -> new.b
  94954. */
  94955. Table *pTab = pExpr->y.pTab;
  94956. int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
  94957. assert( pExpr->iTable==0 || pExpr->iTable==1 );
  94958. assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
  94959. assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
  94960. assert( p1>=0 && p1<(pTab->nCol*2+2) );
  94961. sqlite3VdbeAddOp2(v, OP_Param, p1, target);
  94962. VdbeComment((v, "r[%d]=%s.%s", target,
  94963. (pExpr->iTable ? "new" : "old"),
  94964. (pExpr->iColumn<0 ? "rowid" : pExpr->y.pTab->aCol[pExpr->iColumn].zName)
  94965. ));
  94966. #ifndef SQLITE_OMIT_FLOATING_POINT
  94967. /* If the column has REAL affinity, it may currently be stored as an
  94968. ** integer. Use OP_RealAffinity to make sure it is really real.
  94969. **
  94970. ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
  94971. ** floating point when extracting it from the record. */
  94972. if( pExpr->iColumn>=0
  94973. && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
  94974. ){
  94975. sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
  94976. }
  94977. #endif
  94978. break;
  94979. }
  94980. case TK_VECTOR: {
  94981. sqlite3ErrorMsg(pParse, "row value misused");
  94982. break;
  94983. }
  94984. case TK_IF_NULL_ROW: {
  94985. int addrINR;
  94986. addrINR = sqlite3VdbeAddOp1(v, OP_IfNullRow, pExpr->iTable);
  94987. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  94988. sqlite3VdbeJumpHere(v, addrINR);
  94989. sqlite3VdbeChangeP3(v, addrINR, inReg);
  94990. break;
  94991. }
  94992. /*
  94993. ** Form A:
  94994. ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
  94995. **
  94996. ** Form B:
  94997. ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
  94998. **
  94999. ** Form A is can be transformed into the equivalent form B as follows:
  95000. ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
  95001. ** WHEN x=eN THEN rN ELSE y END
  95002. **
  95003. ** X (if it exists) is in pExpr->pLeft.
  95004. ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
  95005. ** odd. The Y is also optional. If the number of elements in x.pList
  95006. ** is even, then Y is omitted and the "otherwise" result is NULL.
  95007. ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
  95008. **
  95009. ** The result of the expression is the Ri for the first matching Ei,
  95010. ** or if there is no matching Ei, the ELSE term Y, or if there is
  95011. ** no ELSE term, NULL.
  95012. */
  95013. default: assert( op==TK_CASE ); {
  95014. int endLabel; /* GOTO label for end of CASE stmt */
  95015. int nextCase; /* GOTO label for next WHEN clause */
  95016. int nExpr; /* 2x number of WHEN terms */
  95017. int i; /* Loop counter */
  95018. ExprList *pEList; /* List of WHEN terms */
  95019. struct ExprList_item *aListelem; /* Array of WHEN terms */
  95020. Expr opCompare; /* The X==Ei expression */
  95021. Expr *pX; /* The X expression */
  95022. Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
  95023. assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
  95024. assert(pExpr->x.pList->nExpr > 0);
  95025. pEList = pExpr->x.pList;
  95026. aListelem = pEList->a;
  95027. nExpr = pEList->nExpr;
  95028. endLabel = sqlite3VdbeMakeLabel(pParse);
  95029. if( (pX = pExpr->pLeft)!=0 ){
  95030. exprNodeCopy(&tempX, pX);
  95031. testcase( pX->op==TK_COLUMN );
  95032. exprToRegister(&tempX, exprCodeVector(pParse, &tempX, &regFree1));
  95033. testcase( regFree1==0 );
  95034. memset(&opCompare, 0, sizeof(opCompare));
  95035. opCompare.op = TK_EQ;
  95036. opCompare.pLeft = &tempX;
  95037. pTest = &opCompare;
  95038. /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
  95039. ** The value in regFree1 might get SCopy-ed into the file result.
  95040. ** So make sure that the regFree1 register is not reused for other
  95041. ** purposes and possibly overwritten. */
  95042. regFree1 = 0;
  95043. }
  95044. for(i=0; i<nExpr-1; i=i+2){
  95045. if( pX ){
  95046. assert( pTest!=0 );
  95047. opCompare.pRight = aListelem[i].pExpr;
  95048. }else{
  95049. pTest = aListelem[i].pExpr;
  95050. }
  95051. nextCase = sqlite3VdbeMakeLabel(pParse);
  95052. testcase( pTest->op==TK_COLUMN );
  95053. sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
  95054. testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
  95055. sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
  95056. sqlite3VdbeGoto(v, endLabel);
  95057. sqlite3VdbeResolveLabel(v, nextCase);
  95058. }
  95059. if( (nExpr&1)!=0 ){
  95060. sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
  95061. }else{
  95062. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  95063. }
  95064. sqlite3VdbeResolveLabel(v, endLabel);
  95065. break;
  95066. }
  95067. #ifndef SQLITE_OMIT_TRIGGER
  95068. case TK_RAISE: {
  95069. assert( pExpr->affinity==OE_Rollback
  95070. || pExpr->affinity==OE_Abort
  95071. || pExpr->affinity==OE_Fail
  95072. || pExpr->affinity==OE_Ignore
  95073. );
  95074. if( !pParse->pTriggerTab ){
  95075. sqlite3ErrorMsg(pParse,
  95076. "RAISE() may only be used within a trigger-program");
  95077. return 0;
  95078. }
  95079. if( pExpr->affinity==OE_Abort ){
  95080. sqlite3MayAbort(pParse);
  95081. }
  95082. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  95083. if( pExpr->affinity==OE_Ignore ){
  95084. sqlite3VdbeAddOp4(
  95085. v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
  95086. VdbeCoverage(v);
  95087. }else{
  95088. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
  95089. pExpr->affinity, pExpr->u.zToken, 0, 0);
  95090. }
  95091. break;
  95092. }
  95093. #endif
  95094. }
  95095. sqlite3ReleaseTempReg(pParse, regFree1);
  95096. sqlite3ReleaseTempReg(pParse, regFree2);
  95097. return inReg;
  95098. }
  95099. /*
  95100. ** Factor out the code of the given expression to initialization time.
  95101. **
  95102. ** If regDest>=0 then the result is always stored in that register and the
  95103. ** result is not reusable. If regDest<0 then this routine is free to
  95104. ** store the value whereever it wants. The register where the expression
  95105. ** is stored is returned. When regDest<0, two identical expressions will
  95106. ** code to the same register.
  95107. */
  95108. SQLITE_PRIVATE int sqlite3ExprCodeAtInit(
  95109. Parse *pParse, /* Parsing context */
  95110. Expr *pExpr, /* The expression to code when the VDBE initializes */
  95111. int regDest /* Store the value in this register */
  95112. ){
  95113. ExprList *p;
  95114. assert( ConstFactorOk(pParse) );
  95115. p = pParse->pConstExpr;
  95116. if( regDest<0 && p ){
  95117. struct ExprList_item *pItem;
  95118. int i;
  95119. for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
  95120. if( pItem->reusable && sqlite3ExprCompare(0,pItem->pExpr,pExpr,-1)==0 ){
  95121. return pItem->u.iConstExprReg;
  95122. }
  95123. }
  95124. }
  95125. pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
  95126. p = sqlite3ExprListAppend(pParse, p, pExpr);
  95127. if( p ){
  95128. struct ExprList_item *pItem = &p->a[p->nExpr-1];
  95129. pItem->reusable = regDest<0;
  95130. if( regDest<0 ) regDest = ++pParse->nMem;
  95131. pItem->u.iConstExprReg = regDest;
  95132. }
  95133. pParse->pConstExpr = p;
  95134. return regDest;
  95135. }
  95136. /*
  95137. ** Generate code to evaluate an expression and store the results
  95138. ** into a register. Return the register number where the results
  95139. ** are stored.
  95140. **
  95141. ** If the register is a temporary register that can be deallocated,
  95142. ** then write its number into *pReg. If the result register is not
  95143. ** a temporary, then set *pReg to zero.
  95144. **
  95145. ** If pExpr is a constant, then this routine might generate this
  95146. ** code to fill the register in the initialization section of the
  95147. ** VDBE program, in order to factor it out of the evaluation loop.
  95148. */
  95149. SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
  95150. int r2;
  95151. pExpr = sqlite3ExprSkipCollate(pExpr);
  95152. if( ConstFactorOk(pParse)
  95153. && pExpr->op!=TK_REGISTER
  95154. && sqlite3ExprIsConstantNotJoin(pExpr)
  95155. ){
  95156. *pReg = 0;
  95157. r2 = sqlite3ExprCodeAtInit(pParse, pExpr, -1);
  95158. }else{
  95159. int r1 = sqlite3GetTempReg(pParse);
  95160. r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
  95161. if( r2==r1 ){
  95162. *pReg = r1;
  95163. }else{
  95164. sqlite3ReleaseTempReg(pParse, r1);
  95165. *pReg = 0;
  95166. }
  95167. }
  95168. return r2;
  95169. }
  95170. /*
  95171. ** Generate code that will evaluate expression pExpr and store the
  95172. ** results in register target. The results are guaranteed to appear
  95173. ** in register target.
  95174. */
  95175. SQLITE_PRIVATE void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
  95176. int inReg;
  95177. assert( target>0 && target<=pParse->nMem );
  95178. if( pExpr && pExpr->op==TK_REGISTER ){
  95179. sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
  95180. }else{
  95181. inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
  95182. assert( pParse->pVdbe!=0 || pParse->db->mallocFailed );
  95183. if( inReg!=target && pParse->pVdbe ){
  95184. sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
  95185. }
  95186. }
  95187. }
  95188. /*
  95189. ** Make a transient copy of expression pExpr and then code it using
  95190. ** sqlite3ExprCode(). This routine works just like sqlite3ExprCode()
  95191. ** except that the input expression is guaranteed to be unchanged.
  95192. */
  95193. SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, Expr *pExpr, int target){
  95194. sqlite3 *db = pParse->db;
  95195. pExpr = sqlite3ExprDup(db, pExpr, 0);
  95196. if( !db->mallocFailed ) sqlite3ExprCode(pParse, pExpr, target);
  95197. sqlite3ExprDelete(db, pExpr);
  95198. }
  95199. /*
  95200. ** Generate code that will evaluate expression pExpr and store the
  95201. ** results in register target. The results are guaranteed to appear
  95202. ** in register target. If the expression is constant, then this routine
  95203. ** might choose to code the expression at initialization time.
  95204. */
  95205. SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
  95206. if( pParse->okConstFactor && sqlite3ExprIsConstantNotJoin(pExpr) ){
  95207. sqlite3ExprCodeAtInit(pParse, pExpr, target);
  95208. }else{
  95209. sqlite3ExprCode(pParse, pExpr, target);
  95210. }
  95211. }
  95212. /*
  95213. ** Generate code that evaluates the given expression and puts the result
  95214. ** in register target.
  95215. **
  95216. ** Also make a copy of the expression results into another "cache" register
  95217. ** and modify the expression so that the next time it is evaluated,
  95218. ** the result is a copy of the cache register.
  95219. **
  95220. ** This routine is used for expressions that are used multiple
  95221. ** times. They are evaluated once and the results of the expression
  95222. ** are reused.
  95223. */
  95224. SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
  95225. Vdbe *v = pParse->pVdbe;
  95226. int iMem;
  95227. assert( target>0 );
  95228. assert( pExpr->op!=TK_REGISTER );
  95229. sqlite3ExprCode(pParse, pExpr, target);
  95230. iMem = ++pParse->nMem;
  95231. sqlite3VdbeAddOp2(v, OP_Copy, target, iMem);
  95232. exprToRegister(pExpr, iMem);
  95233. }
  95234. /*
  95235. ** Generate code that pushes the value of every element of the given
  95236. ** expression list into a sequence of registers beginning at target.
  95237. **
  95238. ** Return the number of elements evaluated. The number returned will
  95239. ** usually be pList->nExpr but might be reduced if SQLITE_ECEL_OMITREF
  95240. ** is defined.
  95241. **
  95242. ** The SQLITE_ECEL_DUP flag prevents the arguments from being
  95243. ** filled using OP_SCopy. OP_Copy must be used instead.
  95244. **
  95245. ** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
  95246. ** factored out into initialization code.
  95247. **
  95248. ** The SQLITE_ECEL_REF flag means that expressions in the list with
  95249. ** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored
  95250. ** in registers at srcReg, and so the value can be copied from there.
  95251. ** If SQLITE_ECEL_OMITREF is also set, then the values with u.x.iOrderByCol>0
  95252. ** are simply omitted rather than being copied from srcReg.
  95253. */
  95254. SQLITE_PRIVATE int sqlite3ExprCodeExprList(
  95255. Parse *pParse, /* Parsing context */
  95256. ExprList *pList, /* The expression list to be coded */
  95257. int target, /* Where to write results */
  95258. int srcReg, /* Source registers if SQLITE_ECEL_REF */
  95259. u8 flags /* SQLITE_ECEL_* flags */
  95260. ){
  95261. struct ExprList_item *pItem;
  95262. int i, j, n;
  95263. u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
  95264. Vdbe *v = pParse->pVdbe;
  95265. assert( pList!=0 );
  95266. assert( target>0 );
  95267. assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */
  95268. n = pList->nExpr;
  95269. if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
  95270. for(pItem=pList->a, i=0; i<n; i++, pItem++){
  95271. Expr *pExpr = pItem->pExpr;
  95272. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  95273. if( pItem->bSorterRef ){
  95274. i--;
  95275. n--;
  95276. }else
  95277. #endif
  95278. if( (flags & SQLITE_ECEL_REF)!=0 && (j = pItem->u.x.iOrderByCol)>0 ){
  95279. if( flags & SQLITE_ECEL_OMITREF ){
  95280. i--;
  95281. n--;
  95282. }else{
  95283. sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i);
  95284. }
  95285. }else if( (flags & SQLITE_ECEL_FACTOR)!=0
  95286. && sqlite3ExprIsConstantNotJoin(pExpr)
  95287. ){
  95288. sqlite3ExprCodeAtInit(pParse, pExpr, target+i);
  95289. }else{
  95290. int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
  95291. if( inReg!=target+i ){
  95292. VdbeOp *pOp;
  95293. if( copyOp==OP_Copy
  95294. && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
  95295. && pOp->p1+pOp->p3+1==inReg
  95296. && pOp->p2+pOp->p3+1==target+i
  95297. ){
  95298. pOp->p3++;
  95299. }else{
  95300. sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
  95301. }
  95302. }
  95303. }
  95304. }
  95305. return n;
  95306. }
  95307. /*
  95308. ** Generate code for a BETWEEN operator.
  95309. **
  95310. ** x BETWEEN y AND z
  95311. **
  95312. ** The above is equivalent to
  95313. **
  95314. ** x>=y AND x<=z
  95315. **
  95316. ** Code it as such, taking care to do the common subexpression
  95317. ** elimination of x.
  95318. **
  95319. ** The xJumpIf parameter determines details:
  95320. **
  95321. ** NULL: Store the boolean result in reg[dest]
  95322. ** sqlite3ExprIfTrue: Jump to dest if true
  95323. ** sqlite3ExprIfFalse: Jump to dest if false
  95324. **
  95325. ** The jumpIfNull parameter is ignored if xJumpIf is NULL.
  95326. */
  95327. static void exprCodeBetween(
  95328. Parse *pParse, /* Parsing and code generating context */
  95329. Expr *pExpr, /* The BETWEEN expression */
  95330. int dest, /* Jump destination or storage location */
  95331. void (*xJump)(Parse*,Expr*,int,int), /* Action to take */
  95332. int jumpIfNull /* Take the jump if the BETWEEN is NULL */
  95333. ){
  95334. Expr exprAnd; /* The AND operator in x>=y AND x<=z */
  95335. Expr compLeft; /* The x>=y term */
  95336. Expr compRight; /* The x<=z term */
  95337. Expr exprX; /* The x subexpression */
  95338. int regFree1 = 0; /* Temporary use register */
  95339. memset(&compLeft, 0, sizeof(Expr));
  95340. memset(&compRight, 0, sizeof(Expr));
  95341. memset(&exprAnd, 0, sizeof(Expr));
  95342. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  95343. exprNodeCopy(&exprX, pExpr->pLeft);
  95344. exprAnd.op = TK_AND;
  95345. exprAnd.pLeft = &compLeft;
  95346. exprAnd.pRight = &compRight;
  95347. compLeft.op = TK_GE;
  95348. compLeft.pLeft = &exprX;
  95349. compLeft.pRight = pExpr->x.pList->a[0].pExpr;
  95350. compRight.op = TK_LE;
  95351. compRight.pLeft = &exprX;
  95352. compRight.pRight = pExpr->x.pList->a[1].pExpr;
  95353. exprToRegister(&exprX, exprCodeVector(pParse, &exprX, &regFree1));
  95354. if( xJump ){
  95355. xJump(pParse, &exprAnd, dest, jumpIfNull);
  95356. }else{
  95357. /* Mark the expression is being from the ON or USING clause of a join
  95358. ** so that the sqlite3ExprCodeTarget() routine will not attempt to move
  95359. ** it into the Parse.pConstExpr list. We should use a new bit for this,
  95360. ** for clarity, but we are out of bits in the Expr.flags field so we
  95361. ** have to reuse the EP_FromJoin bit. Bummer. */
  95362. exprX.flags |= EP_FromJoin;
  95363. sqlite3ExprCodeTarget(pParse, &exprAnd, dest);
  95364. }
  95365. sqlite3ReleaseTempReg(pParse, regFree1);
  95366. /* Ensure adequate test coverage */
  95367. testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1==0 );
  95368. testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1!=0 );
  95369. testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1==0 );
  95370. testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1!=0 );
  95371. testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1==0 );
  95372. testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1!=0 );
  95373. testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1==0 );
  95374. testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1!=0 );
  95375. testcase( xJump==0 );
  95376. }
  95377. /*
  95378. ** Generate code for a boolean expression such that a jump is made
  95379. ** to the label "dest" if the expression is true but execution
  95380. ** continues straight thru if the expression is false.
  95381. **
  95382. ** If the expression evaluates to NULL (neither true nor false), then
  95383. ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
  95384. **
  95385. ** This code depends on the fact that certain token values (ex: TK_EQ)
  95386. ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
  95387. ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
  95388. ** the make process cause these values to align. Assert()s in the code
  95389. ** below verify that the numbers are aligned correctly.
  95390. */
  95391. SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
  95392. Vdbe *v = pParse->pVdbe;
  95393. int op = 0;
  95394. int regFree1 = 0;
  95395. int regFree2 = 0;
  95396. int r1, r2;
  95397. assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
  95398. if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
  95399. if( NEVER(pExpr==0) ) return; /* No way this can happen */
  95400. op = pExpr->op;
  95401. switch( op ){
  95402. case TK_AND:
  95403. case TK_OR: {
  95404. Expr *pAlt = sqlite3ExprSimplifiedAndOr(pExpr);
  95405. if( pAlt!=pExpr ){
  95406. sqlite3ExprIfTrue(pParse, pAlt, dest, jumpIfNull);
  95407. }else if( op==TK_AND ){
  95408. int d2 = sqlite3VdbeMakeLabel(pParse);
  95409. testcase( jumpIfNull==0 );
  95410. sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,
  95411. jumpIfNull^SQLITE_JUMPIFNULL);
  95412. sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
  95413. sqlite3VdbeResolveLabel(v, d2);
  95414. }else{
  95415. testcase( jumpIfNull==0 );
  95416. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
  95417. sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
  95418. }
  95419. break;
  95420. }
  95421. case TK_NOT: {
  95422. testcase( jumpIfNull==0 );
  95423. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
  95424. break;
  95425. }
  95426. case TK_TRUTH: {
  95427. int isNot; /* IS NOT TRUE or IS NOT FALSE */
  95428. int isTrue; /* IS TRUE or IS NOT TRUE */
  95429. testcase( jumpIfNull==0 );
  95430. isNot = pExpr->op2==TK_ISNOT;
  95431. isTrue = sqlite3ExprTruthValue(pExpr->pRight);
  95432. testcase( isTrue && isNot );
  95433. testcase( !isTrue && isNot );
  95434. if( isTrue ^ isNot ){
  95435. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest,
  95436. isNot ? SQLITE_JUMPIFNULL : 0);
  95437. }else{
  95438. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest,
  95439. isNot ? SQLITE_JUMPIFNULL : 0);
  95440. }
  95441. break;
  95442. }
  95443. case TK_IS:
  95444. case TK_ISNOT:
  95445. testcase( op==TK_IS );
  95446. testcase( op==TK_ISNOT );
  95447. op = (op==TK_IS) ? TK_EQ : TK_NE;
  95448. jumpIfNull = SQLITE_NULLEQ;
  95449. /* Fall thru */
  95450. case TK_LT:
  95451. case TK_LE:
  95452. case TK_GT:
  95453. case TK_GE:
  95454. case TK_NE:
  95455. case TK_EQ: {
  95456. if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
  95457. testcase( jumpIfNull==0 );
  95458. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  95459. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  95460. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  95461. r1, r2, dest, jumpIfNull);
  95462. assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
  95463. assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
  95464. assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
  95465. assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
  95466. assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
  95467. VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
  95468. VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
  95469. assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
  95470. VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
  95471. VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
  95472. testcase( regFree1==0 );
  95473. testcase( regFree2==0 );
  95474. break;
  95475. }
  95476. case TK_ISNULL:
  95477. case TK_NOTNULL: {
  95478. assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
  95479. assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
  95480. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  95481. sqlite3VdbeAddOp2(v, op, r1, dest);
  95482. VdbeCoverageIf(v, op==TK_ISNULL);
  95483. VdbeCoverageIf(v, op==TK_NOTNULL);
  95484. testcase( regFree1==0 );
  95485. break;
  95486. }
  95487. case TK_BETWEEN: {
  95488. testcase( jumpIfNull==0 );
  95489. exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfTrue, jumpIfNull);
  95490. break;
  95491. }
  95492. #ifndef SQLITE_OMIT_SUBQUERY
  95493. case TK_IN: {
  95494. int destIfFalse = sqlite3VdbeMakeLabel(pParse);
  95495. int destIfNull = jumpIfNull ? dest : destIfFalse;
  95496. sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
  95497. sqlite3VdbeGoto(v, dest);
  95498. sqlite3VdbeResolveLabel(v, destIfFalse);
  95499. break;
  95500. }
  95501. #endif
  95502. default: {
  95503. default_expr:
  95504. if( ExprAlwaysTrue(pExpr) ){
  95505. sqlite3VdbeGoto(v, dest);
  95506. }else if( ExprAlwaysFalse(pExpr) ){
  95507. /* No-op */
  95508. }else{
  95509. r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
  95510. sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
  95511. VdbeCoverage(v);
  95512. testcase( regFree1==0 );
  95513. testcase( jumpIfNull==0 );
  95514. }
  95515. break;
  95516. }
  95517. }
  95518. sqlite3ReleaseTempReg(pParse, regFree1);
  95519. sqlite3ReleaseTempReg(pParse, regFree2);
  95520. }
  95521. /*
  95522. ** Generate code for a boolean expression such that a jump is made
  95523. ** to the label "dest" if the expression is false but execution
  95524. ** continues straight thru if the expression is true.
  95525. **
  95526. ** If the expression evaluates to NULL (neither true nor false) then
  95527. ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
  95528. ** is 0.
  95529. */
  95530. SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
  95531. Vdbe *v = pParse->pVdbe;
  95532. int op = 0;
  95533. int regFree1 = 0;
  95534. int regFree2 = 0;
  95535. int r1, r2;
  95536. assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
  95537. if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
  95538. if( pExpr==0 ) return;
  95539. /* The value of pExpr->op and op are related as follows:
  95540. **
  95541. ** pExpr->op op
  95542. ** --------- ----------
  95543. ** TK_ISNULL OP_NotNull
  95544. ** TK_NOTNULL OP_IsNull
  95545. ** TK_NE OP_Eq
  95546. ** TK_EQ OP_Ne
  95547. ** TK_GT OP_Le
  95548. ** TK_LE OP_Gt
  95549. ** TK_GE OP_Lt
  95550. ** TK_LT OP_Ge
  95551. **
  95552. ** For other values of pExpr->op, op is undefined and unused.
  95553. ** The value of TK_ and OP_ constants are arranged such that we
  95554. ** can compute the mapping above using the following expression.
  95555. ** Assert()s verify that the computation is correct.
  95556. */
  95557. op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
  95558. /* Verify correct alignment of TK_ and OP_ constants
  95559. */
  95560. assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
  95561. assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
  95562. assert( pExpr->op!=TK_NE || op==OP_Eq );
  95563. assert( pExpr->op!=TK_EQ || op==OP_Ne );
  95564. assert( pExpr->op!=TK_LT || op==OP_Ge );
  95565. assert( pExpr->op!=TK_LE || op==OP_Gt );
  95566. assert( pExpr->op!=TK_GT || op==OP_Le );
  95567. assert( pExpr->op!=TK_GE || op==OP_Lt );
  95568. switch( pExpr->op ){
  95569. case TK_AND:
  95570. case TK_OR: {
  95571. Expr *pAlt = sqlite3ExprSimplifiedAndOr(pExpr);
  95572. if( pAlt!=pExpr ){
  95573. sqlite3ExprIfFalse(pParse, pAlt, dest, jumpIfNull);
  95574. }else if( pExpr->op==TK_AND ){
  95575. testcase( jumpIfNull==0 );
  95576. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
  95577. sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
  95578. }else{
  95579. int d2 = sqlite3VdbeMakeLabel(pParse);
  95580. testcase( jumpIfNull==0 );
  95581. sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2,
  95582. jumpIfNull^SQLITE_JUMPIFNULL);
  95583. sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
  95584. sqlite3VdbeResolveLabel(v, d2);
  95585. }
  95586. break;
  95587. }
  95588. case TK_NOT: {
  95589. testcase( jumpIfNull==0 );
  95590. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
  95591. break;
  95592. }
  95593. case TK_TRUTH: {
  95594. int isNot; /* IS NOT TRUE or IS NOT FALSE */
  95595. int isTrue; /* IS TRUE or IS NOT TRUE */
  95596. testcase( jumpIfNull==0 );
  95597. isNot = pExpr->op2==TK_ISNOT;
  95598. isTrue = sqlite3ExprTruthValue(pExpr->pRight);
  95599. testcase( isTrue && isNot );
  95600. testcase( !isTrue && isNot );
  95601. if( isTrue ^ isNot ){
  95602. /* IS TRUE and IS NOT FALSE */
  95603. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest,
  95604. isNot ? 0 : SQLITE_JUMPIFNULL);
  95605. }else{
  95606. /* IS FALSE and IS NOT TRUE */
  95607. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest,
  95608. isNot ? 0 : SQLITE_JUMPIFNULL);
  95609. }
  95610. break;
  95611. }
  95612. case TK_IS:
  95613. case TK_ISNOT:
  95614. testcase( pExpr->op==TK_IS );
  95615. testcase( pExpr->op==TK_ISNOT );
  95616. op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
  95617. jumpIfNull = SQLITE_NULLEQ;
  95618. /* Fall thru */
  95619. case TK_LT:
  95620. case TK_LE:
  95621. case TK_GT:
  95622. case TK_GE:
  95623. case TK_NE:
  95624. case TK_EQ: {
  95625. if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
  95626. testcase( jumpIfNull==0 );
  95627. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  95628. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  95629. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  95630. r1, r2, dest, jumpIfNull);
  95631. assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
  95632. assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
  95633. assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
  95634. assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
  95635. assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
  95636. VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
  95637. VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
  95638. assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
  95639. VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
  95640. VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
  95641. testcase( regFree1==0 );
  95642. testcase( regFree2==0 );
  95643. break;
  95644. }
  95645. case TK_ISNULL:
  95646. case TK_NOTNULL: {
  95647. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  95648. sqlite3VdbeAddOp2(v, op, r1, dest);
  95649. testcase( op==TK_ISNULL ); VdbeCoverageIf(v, op==TK_ISNULL);
  95650. testcase( op==TK_NOTNULL ); VdbeCoverageIf(v, op==TK_NOTNULL);
  95651. testcase( regFree1==0 );
  95652. break;
  95653. }
  95654. case TK_BETWEEN: {
  95655. testcase( jumpIfNull==0 );
  95656. exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfFalse, jumpIfNull);
  95657. break;
  95658. }
  95659. #ifndef SQLITE_OMIT_SUBQUERY
  95660. case TK_IN: {
  95661. if( jumpIfNull ){
  95662. sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
  95663. }else{
  95664. int destIfNull = sqlite3VdbeMakeLabel(pParse);
  95665. sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
  95666. sqlite3VdbeResolveLabel(v, destIfNull);
  95667. }
  95668. break;
  95669. }
  95670. #endif
  95671. default: {
  95672. default_expr:
  95673. if( ExprAlwaysFalse(pExpr) ){
  95674. sqlite3VdbeGoto(v, dest);
  95675. }else if( ExprAlwaysTrue(pExpr) ){
  95676. /* no-op */
  95677. }else{
  95678. r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
  95679. sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
  95680. VdbeCoverage(v);
  95681. testcase( regFree1==0 );
  95682. testcase( jumpIfNull==0 );
  95683. }
  95684. break;
  95685. }
  95686. }
  95687. sqlite3ReleaseTempReg(pParse, regFree1);
  95688. sqlite3ReleaseTempReg(pParse, regFree2);
  95689. }
  95690. /*
  95691. ** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before
  95692. ** code generation, and that copy is deleted after code generation. This
  95693. ** ensures that the original pExpr is unchanged.
  95694. */
  95695. SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){
  95696. sqlite3 *db = pParse->db;
  95697. Expr *pCopy = sqlite3ExprDup(db, pExpr, 0);
  95698. if( db->mallocFailed==0 ){
  95699. sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull);
  95700. }
  95701. sqlite3ExprDelete(db, pCopy);
  95702. }
  95703. /*
  95704. ** Expression pVar is guaranteed to be an SQL variable. pExpr may be any
  95705. ** type of expression.
  95706. **
  95707. ** If pExpr is a simple SQL value - an integer, real, string, blob
  95708. ** or NULL value - then the VDBE currently being prepared is configured
  95709. ** to re-prepare each time a new value is bound to variable pVar.
  95710. **
  95711. ** Additionally, if pExpr is a simple SQL value and the value is the
  95712. ** same as that currently bound to variable pVar, non-zero is returned.
  95713. ** Otherwise, if the values are not the same or if pExpr is not a simple
  95714. ** SQL value, zero is returned.
  95715. */
  95716. static int exprCompareVariable(Parse *pParse, Expr *pVar, Expr *pExpr){
  95717. int res = 0;
  95718. int iVar;
  95719. sqlite3_value *pL, *pR = 0;
  95720. sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, SQLITE_AFF_BLOB, &pR);
  95721. if( pR ){
  95722. iVar = pVar->iColumn;
  95723. sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
  95724. pL = sqlite3VdbeGetBoundValue(pParse->pReprepare, iVar, SQLITE_AFF_BLOB);
  95725. if( pL ){
  95726. if( sqlite3_value_type(pL)==SQLITE_TEXT ){
  95727. sqlite3_value_text(pL); /* Make sure the encoding is UTF-8 */
  95728. }
  95729. res = 0==sqlite3MemCompare(pL, pR, 0);
  95730. }
  95731. sqlite3ValueFree(pR);
  95732. sqlite3ValueFree(pL);
  95733. }
  95734. return res;
  95735. }
  95736. /*
  95737. ** Do a deep comparison of two expression trees. Return 0 if the two
  95738. ** expressions are completely identical. Return 1 if they differ only
  95739. ** by a COLLATE operator at the top level. Return 2 if there are differences
  95740. ** other than the top-level COLLATE operator.
  95741. **
  95742. ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
  95743. ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
  95744. **
  95745. ** The pA side might be using TK_REGISTER. If that is the case and pB is
  95746. ** not using TK_REGISTER but is otherwise equivalent, then still return 0.
  95747. **
  95748. ** Sometimes this routine will return 2 even if the two expressions
  95749. ** really are equivalent. If we cannot prove that the expressions are
  95750. ** identical, we return 2 just to be safe. So if this routine
  95751. ** returns 2, then you do not really know for certain if the two
  95752. ** expressions are the same. But if you get a 0 or 1 return, then you
  95753. ** can be sure the expressions are the same. In the places where
  95754. ** this routine is used, it does not hurt to get an extra 2 - that
  95755. ** just might result in some slightly slower code. But returning
  95756. ** an incorrect 0 or 1 could lead to a malfunction.
  95757. **
  95758. ** If pParse is not NULL then TK_VARIABLE terms in pA with bindings in
  95759. ** pParse->pReprepare can be matched against literals in pB. The
  95760. ** pParse->pVdbe->expmask bitmask is updated for each variable referenced.
  95761. ** If pParse is NULL (the normal case) then any TK_VARIABLE term in
  95762. ** Argument pParse should normally be NULL. If it is not NULL and pA or
  95763. ** pB causes a return value of 2.
  95764. */
  95765. SQLITE_PRIVATE int sqlite3ExprCompare(Parse *pParse, Expr *pA, Expr *pB, int iTab){
  95766. u32 combinedFlags;
  95767. if( pA==0 || pB==0 ){
  95768. return pB==pA ? 0 : 2;
  95769. }
  95770. if( pParse && pA->op==TK_VARIABLE && exprCompareVariable(pParse, pA, pB) ){
  95771. return 0;
  95772. }
  95773. combinedFlags = pA->flags | pB->flags;
  95774. if( combinedFlags & EP_IntValue ){
  95775. if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
  95776. return 0;
  95777. }
  95778. return 2;
  95779. }
  95780. if( pA->op!=pB->op || pA->op==TK_RAISE ){
  95781. if( pA->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA->pLeft,pB,iTab)<2 ){
  95782. return 1;
  95783. }
  95784. if( pB->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA,pB->pLeft,iTab)<2 ){
  95785. return 1;
  95786. }
  95787. return 2;
  95788. }
  95789. if( pA->op!=TK_COLUMN && pA->op!=TK_AGG_COLUMN && pA->u.zToken ){
  95790. if( pA->op==TK_FUNCTION ){
  95791. if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
  95792. #ifndef SQLITE_OMIT_WINDOWFUNC
  95793. /* Justification for the assert():
  95794. ** window functions have p->op==TK_FUNCTION but aggregate functions
  95795. ** have p->op==TK_AGG_FUNCTION. So any comparison between an aggregate
  95796. ** function and a window function should have failed before reaching
  95797. ** this point. And, it is not possible to have a window function and
  95798. ** a scalar function with the same name and number of arguments. So
  95799. ** if we reach this point, either A and B both window functions or
  95800. ** neither are a window functions. */
  95801. assert( ExprHasProperty(pA,EP_WinFunc)==ExprHasProperty(pB,EP_WinFunc) );
  95802. if( ExprHasProperty(pA,EP_WinFunc) ){
  95803. if( sqlite3WindowCompare(pParse,pA->y.pWin,pB->y.pWin)!=0 ) return 2;
  95804. }
  95805. #endif
  95806. }else if( pA->op==TK_NULL ){
  95807. return 0;
  95808. }else if( pA->op==TK_COLLATE ){
  95809. if( sqlite3_stricmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
  95810. }else if( ALWAYS(pB->u.zToken!=0) && strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
  95811. return 2;
  95812. }
  95813. }
  95814. if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
  95815. if( (combinedFlags & EP_TokenOnly)==0 ){
  95816. if( combinedFlags & EP_xIsSelect ) return 2;
  95817. if( (combinedFlags & EP_FixedCol)==0
  95818. && sqlite3ExprCompare(pParse, pA->pLeft, pB->pLeft, iTab) ) return 2;
  95819. if( sqlite3ExprCompare(pParse, pA->pRight, pB->pRight, iTab) ) return 2;
  95820. if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
  95821. if( pA->op!=TK_STRING
  95822. && pA->op!=TK_TRUEFALSE
  95823. && (combinedFlags & EP_Reduced)==0
  95824. ){
  95825. if( pA->iColumn!=pB->iColumn ) return 2;
  95826. if( pA->op2!=pB->op2 ) return 2;
  95827. if( pA->iTable!=pB->iTable
  95828. && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
  95829. }
  95830. }
  95831. return 0;
  95832. }
  95833. /*
  95834. ** Compare two ExprList objects. Return 0 if they are identical and
  95835. ** non-zero if they differ in any way.
  95836. **
  95837. ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
  95838. ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
  95839. **
  95840. ** This routine might return non-zero for equivalent ExprLists. The
  95841. ** only consequence will be disabled optimizations. But this routine
  95842. ** must never return 0 if the two ExprList objects are different, or
  95843. ** a malfunction will result.
  95844. **
  95845. ** Two NULL pointers are considered to be the same. But a NULL pointer
  95846. ** always differs from a non-NULL pointer.
  95847. */
  95848. SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
  95849. int i;
  95850. if( pA==0 && pB==0 ) return 0;
  95851. if( pA==0 || pB==0 ) return 1;
  95852. if( pA->nExpr!=pB->nExpr ) return 1;
  95853. for(i=0; i<pA->nExpr; i++){
  95854. Expr *pExprA = pA->a[i].pExpr;
  95855. Expr *pExprB = pB->a[i].pExpr;
  95856. if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
  95857. if( sqlite3ExprCompare(0, pExprA, pExprB, iTab) ) return 1;
  95858. }
  95859. return 0;
  95860. }
  95861. /*
  95862. ** Like sqlite3ExprCompare() except COLLATE operators at the top-level
  95863. ** are ignored.
  95864. */
  95865. SQLITE_PRIVATE int sqlite3ExprCompareSkip(Expr *pA, Expr *pB, int iTab){
  95866. return sqlite3ExprCompare(0,
  95867. sqlite3ExprSkipCollate(pA),
  95868. sqlite3ExprSkipCollate(pB),
  95869. iTab);
  95870. }
  95871. /*
  95872. ** Return non-zero if Expr p can only be true if pNN is not NULL.
  95873. */
  95874. static int exprImpliesNotNull(
  95875. Parse *pParse, /* Parsing context */
  95876. Expr *p, /* The expression to be checked */
  95877. Expr *pNN, /* The expression that is NOT NULL */
  95878. int iTab, /* Table being evaluated */
  95879. int seenNot /* True if p is an operand of NOT */
  95880. ){
  95881. assert( p );
  95882. assert( pNN );
  95883. if( sqlite3ExprCompare(pParse, p, pNN, iTab)==0 ) return 1;
  95884. switch( p->op ){
  95885. case TK_IN: {
  95886. if( seenNot && ExprHasProperty(p, EP_xIsSelect) ) return 0;
  95887. assert( ExprHasProperty(p,EP_xIsSelect)
  95888. || (p->x.pList!=0 && p->x.pList->nExpr>0) );
  95889. return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, seenNot);
  95890. }
  95891. case TK_BETWEEN: {
  95892. ExprList *pList = p->x.pList;
  95893. assert( pList!=0 );
  95894. assert( pList->nExpr==2 );
  95895. if( seenNot ) return 0;
  95896. if( exprImpliesNotNull(pParse, pList->a[0].pExpr, pNN, iTab, seenNot)
  95897. || exprImpliesNotNull(pParse, pList->a[1].pExpr, pNN, iTab, seenNot)
  95898. ){
  95899. return 1;
  95900. }
  95901. return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, seenNot);
  95902. }
  95903. case TK_EQ:
  95904. case TK_NE:
  95905. case TK_LT:
  95906. case TK_LE:
  95907. case TK_GT:
  95908. case TK_GE:
  95909. case TK_PLUS:
  95910. case TK_MINUS:
  95911. case TK_STAR:
  95912. case TK_REM:
  95913. case TK_BITAND:
  95914. case TK_BITOR:
  95915. case TK_SLASH:
  95916. case TK_LSHIFT:
  95917. case TK_RSHIFT:
  95918. case TK_CONCAT: {
  95919. if( exprImpliesNotNull(pParse, p->pRight, pNN, iTab, seenNot) ) return 1;
  95920. /* Fall thru into the next case */
  95921. }
  95922. case TK_SPAN:
  95923. case TK_COLLATE:
  95924. case TK_BITNOT:
  95925. case TK_UPLUS:
  95926. case TK_UMINUS: {
  95927. return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, seenNot);
  95928. }
  95929. case TK_TRUTH: {
  95930. if( seenNot ) return 0;
  95931. if( p->op2!=TK_IS ) return 0;
  95932. return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, seenNot);
  95933. }
  95934. case TK_NOT: {
  95935. return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
  95936. }
  95937. }
  95938. return 0;
  95939. }
  95940. /*
  95941. ** Return true if we can prove the pE2 will always be true if pE1 is
  95942. ** true. Return false if we cannot complete the proof or if pE2 might
  95943. ** be false. Examples:
  95944. **
  95945. ** pE1: x==5 pE2: x==5 Result: true
  95946. ** pE1: x>0 pE2: x==5 Result: false
  95947. ** pE1: x=21 pE2: x=21 OR y=43 Result: true
  95948. ** pE1: x!=123 pE2: x IS NOT NULL Result: true
  95949. ** pE1: x!=?1 pE2: x IS NOT NULL Result: true
  95950. ** pE1: x IS NULL pE2: x IS NOT NULL Result: false
  95951. ** pE1: x IS ?2 pE2: x IS NOT NULL Reuslt: false
  95952. **
  95953. ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
  95954. ** Expr.iTable<0 then assume a table number given by iTab.
  95955. **
  95956. ** If pParse is not NULL, then the values of bound variables in pE1 are
  95957. ** compared against literal values in pE2 and pParse->pVdbe->expmask is
  95958. ** modified to record which bound variables are referenced. If pParse
  95959. ** is NULL, then false will be returned if pE1 contains any bound variables.
  95960. **
  95961. ** When in doubt, return false. Returning true might give a performance
  95962. ** improvement. Returning false might cause a performance reduction, but
  95963. ** it will always give the correct answer and is hence always safe.
  95964. */
  95965. SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Parse *pParse, Expr *pE1, Expr *pE2, int iTab){
  95966. if( sqlite3ExprCompare(pParse, pE1, pE2, iTab)==0 ){
  95967. return 1;
  95968. }
  95969. if( pE2->op==TK_OR
  95970. && (sqlite3ExprImpliesExpr(pParse, pE1, pE2->pLeft, iTab)
  95971. || sqlite3ExprImpliesExpr(pParse, pE1, pE2->pRight, iTab) )
  95972. ){
  95973. return 1;
  95974. }
  95975. if( pE2->op==TK_NOTNULL
  95976. && exprImpliesNotNull(pParse, pE1, pE2->pLeft, iTab, 0)
  95977. ){
  95978. return 1;
  95979. }
  95980. return 0;
  95981. }
  95982. /*
  95983. ** This is the Expr node callback for sqlite3ExprImpliesNotNullRow().
  95984. ** If the expression node requires that the table at pWalker->iCur
  95985. ** have one or more non-NULL column, then set pWalker->eCode to 1 and abort.
  95986. **
  95987. ** This routine controls an optimization. False positives (setting
  95988. ** pWalker->eCode to 1 when it should not be) are deadly, but false-negatives
  95989. ** (never setting pWalker->eCode) is a harmless missed optimization.
  95990. */
  95991. static int impliesNotNullRow(Walker *pWalker, Expr *pExpr){
  95992. testcase( pExpr->op==TK_AGG_COLUMN );
  95993. testcase( pExpr->op==TK_AGG_FUNCTION );
  95994. if( ExprHasProperty(pExpr, EP_FromJoin) ) return WRC_Prune;
  95995. switch( pExpr->op ){
  95996. case TK_ISNOT:
  95997. case TK_NOT:
  95998. case TK_ISNULL:
  95999. case TK_NOTNULL:
  96000. case TK_IS:
  96001. case TK_OR:
  96002. case TK_CASE:
  96003. case TK_IN:
  96004. case TK_FUNCTION:
  96005. testcase( pExpr->op==TK_ISNOT );
  96006. testcase( pExpr->op==TK_NOT );
  96007. testcase( pExpr->op==TK_ISNULL );
  96008. testcase( pExpr->op==TK_NOTNULL );
  96009. testcase( pExpr->op==TK_IS );
  96010. testcase( pExpr->op==TK_OR );
  96011. testcase( pExpr->op==TK_CASE );
  96012. testcase( pExpr->op==TK_IN );
  96013. testcase( pExpr->op==TK_FUNCTION );
  96014. return WRC_Prune;
  96015. case TK_COLUMN:
  96016. if( pWalker->u.iCur==pExpr->iTable ){
  96017. pWalker->eCode = 1;
  96018. return WRC_Abort;
  96019. }
  96020. return WRC_Prune;
  96021. /* Virtual tables are allowed to use constraints like x=NULL. So
  96022. ** a term of the form x=y does not prove that y is not null if x
  96023. ** is the column of a virtual table */
  96024. case TK_EQ:
  96025. case TK_NE:
  96026. case TK_LT:
  96027. case TK_LE:
  96028. case TK_GT:
  96029. case TK_GE:
  96030. testcase( pExpr->op==TK_EQ );
  96031. testcase( pExpr->op==TK_NE );
  96032. testcase( pExpr->op==TK_LT );
  96033. testcase( pExpr->op==TK_LE );
  96034. testcase( pExpr->op==TK_GT );
  96035. testcase( pExpr->op==TK_GE );
  96036. if( (pExpr->pLeft->op==TK_COLUMN && IsVirtual(pExpr->pLeft->y.pTab))
  96037. || (pExpr->pRight->op==TK_COLUMN && IsVirtual(pExpr->pRight->y.pTab))
  96038. ){
  96039. return WRC_Prune;
  96040. }
  96041. default:
  96042. return WRC_Continue;
  96043. }
  96044. }
  96045. /*
  96046. ** Return true (non-zero) if expression p can only be true if at least
  96047. ** one column of table iTab is non-null. In other words, return true
  96048. ** if expression p will always be NULL or false if every column of iTab
  96049. ** is NULL.
  96050. **
  96051. ** False negatives are acceptable. In other words, it is ok to return
  96052. ** zero even if expression p will never be true of every column of iTab
  96053. ** is NULL. A false negative is merely a missed optimization opportunity.
  96054. **
  96055. ** False positives are not allowed, however. A false positive may result
  96056. ** in an incorrect answer.
  96057. **
  96058. ** Terms of p that are marked with EP_FromJoin (and hence that come from
  96059. ** the ON or USING clauses of LEFT JOINS) are excluded from the analysis.
  96060. **
  96061. ** This routine is used to check if a LEFT JOIN can be converted into
  96062. ** an ordinary JOIN. The p argument is the WHERE clause. If the WHERE
  96063. ** clause requires that some column of the right table of the LEFT JOIN
  96064. ** be non-NULL, then the LEFT JOIN can be safely converted into an
  96065. ** ordinary join.
  96066. */
  96067. SQLITE_PRIVATE int sqlite3ExprImpliesNonNullRow(Expr *p, int iTab){
  96068. Walker w;
  96069. p = sqlite3ExprSkipCollate(p);
  96070. while( p ){
  96071. if( p->op==TK_NOTNULL ){
  96072. p = p->pLeft;
  96073. }else if( p->op==TK_AND ){
  96074. if( sqlite3ExprImpliesNonNullRow(p->pLeft, iTab) ) return 1;
  96075. p = p->pRight;
  96076. }else{
  96077. break;
  96078. }
  96079. }
  96080. w.xExprCallback = impliesNotNullRow;
  96081. w.xSelectCallback = 0;
  96082. w.xSelectCallback2 = 0;
  96083. w.eCode = 0;
  96084. w.u.iCur = iTab;
  96085. sqlite3WalkExpr(&w, p);
  96086. return w.eCode;
  96087. }
  96088. /*
  96089. ** An instance of the following structure is used by the tree walker
  96090. ** to determine if an expression can be evaluated by reference to the
  96091. ** index only, without having to do a search for the corresponding
  96092. ** table entry. The IdxCover.pIdx field is the index. IdxCover.iCur
  96093. ** is the cursor for the table.
  96094. */
  96095. struct IdxCover {
  96096. Index *pIdx; /* The index to be tested for coverage */
  96097. int iCur; /* Cursor number for the table corresponding to the index */
  96098. };
  96099. /*
  96100. ** Check to see if there are references to columns in table
  96101. ** pWalker->u.pIdxCover->iCur can be satisfied using the index
  96102. ** pWalker->u.pIdxCover->pIdx.
  96103. */
  96104. static int exprIdxCover(Walker *pWalker, Expr *pExpr){
  96105. if( pExpr->op==TK_COLUMN
  96106. && pExpr->iTable==pWalker->u.pIdxCover->iCur
  96107. && sqlite3ColumnOfIndex(pWalker->u.pIdxCover->pIdx, pExpr->iColumn)<0
  96108. ){
  96109. pWalker->eCode = 1;
  96110. return WRC_Abort;
  96111. }
  96112. return WRC_Continue;
  96113. }
  96114. /*
  96115. ** Determine if an index pIdx on table with cursor iCur contains will
  96116. ** the expression pExpr. Return true if the index does cover the
  96117. ** expression and false if the pExpr expression references table columns
  96118. ** that are not found in the index pIdx.
  96119. **
  96120. ** An index covering an expression means that the expression can be
  96121. ** evaluated using only the index and without having to lookup the
  96122. ** corresponding table entry.
  96123. */
  96124. SQLITE_PRIVATE int sqlite3ExprCoveredByIndex(
  96125. Expr *pExpr, /* The index to be tested */
  96126. int iCur, /* The cursor number for the corresponding table */
  96127. Index *pIdx /* The index that might be used for coverage */
  96128. ){
  96129. Walker w;
  96130. struct IdxCover xcov;
  96131. memset(&w, 0, sizeof(w));
  96132. xcov.iCur = iCur;
  96133. xcov.pIdx = pIdx;
  96134. w.xExprCallback = exprIdxCover;
  96135. w.u.pIdxCover = &xcov;
  96136. sqlite3WalkExpr(&w, pExpr);
  96137. return !w.eCode;
  96138. }
  96139. /*
  96140. ** An instance of the following structure is used by the tree walker
  96141. ** to count references to table columns in the arguments of an
  96142. ** aggregate function, in order to implement the
  96143. ** sqlite3FunctionThisSrc() routine.
  96144. */
  96145. struct SrcCount {
  96146. SrcList *pSrc; /* One particular FROM clause in a nested query */
  96147. int nThis; /* Number of references to columns in pSrcList */
  96148. int nOther; /* Number of references to columns in other FROM clauses */
  96149. };
  96150. /*
  96151. ** Count the number of references to columns.
  96152. */
  96153. static int exprSrcCount(Walker *pWalker, Expr *pExpr){
  96154. /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
  96155. ** is always called before sqlite3ExprAnalyzeAggregates() and so the
  96156. ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN. If
  96157. ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
  96158. ** NEVER() will need to be removed. */
  96159. if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
  96160. int i;
  96161. struct SrcCount *p = pWalker->u.pSrcCount;
  96162. SrcList *pSrc = p->pSrc;
  96163. int nSrc = pSrc ? pSrc->nSrc : 0;
  96164. for(i=0; i<nSrc; i++){
  96165. if( pExpr->iTable==pSrc->a[i].iCursor ) break;
  96166. }
  96167. if( i<nSrc ){
  96168. p->nThis++;
  96169. }else{
  96170. p->nOther++;
  96171. }
  96172. }
  96173. return WRC_Continue;
  96174. }
  96175. /*
  96176. ** Determine if any of the arguments to the pExpr Function reference
  96177. ** pSrcList. Return true if they do. Also return true if the function
  96178. ** has no arguments or has only constant arguments. Return false if pExpr
  96179. ** references columns but not columns of tables found in pSrcList.
  96180. */
  96181. SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
  96182. Walker w;
  96183. struct SrcCount cnt;
  96184. assert( pExpr->op==TK_AGG_FUNCTION );
  96185. w.xExprCallback = exprSrcCount;
  96186. w.xSelectCallback = 0;
  96187. w.u.pSrcCount = &cnt;
  96188. cnt.pSrc = pSrcList;
  96189. cnt.nThis = 0;
  96190. cnt.nOther = 0;
  96191. sqlite3WalkExprList(&w, pExpr->x.pList);
  96192. return cnt.nThis>0 || cnt.nOther==0;
  96193. }
  96194. /*
  96195. ** Add a new element to the pAggInfo->aCol[] array. Return the index of
  96196. ** the new element. Return a negative number if malloc fails.
  96197. */
  96198. static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
  96199. int i;
  96200. pInfo->aCol = sqlite3ArrayAllocate(
  96201. db,
  96202. pInfo->aCol,
  96203. sizeof(pInfo->aCol[0]),
  96204. &pInfo->nColumn,
  96205. &i
  96206. );
  96207. return i;
  96208. }
  96209. /*
  96210. ** Add a new element to the pAggInfo->aFunc[] array. Return the index of
  96211. ** the new element. Return a negative number if malloc fails.
  96212. */
  96213. static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
  96214. int i;
  96215. pInfo->aFunc = sqlite3ArrayAllocate(
  96216. db,
  96217. pInfo->aFunc,
  96218. sizeof(pInfo->aFunc[0]),
  96219. &pInfo->nFunc,
  96220. &i
  96221. );
  96222. return i;
  96223. }
  96224. /*
  96225. ** This is the xExprCallback for a tree walker. It is used to
  96226. ** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
  96227. ** for additional information.
  96228. */
  96229. static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
  96230. int i;
  96231. NameContext *pNC = pWalker->u.pNC;
  96232. Parse *pParse = pNC->pParse;
  96233. SrcList *pSrcList = pNC->pSrcList;
  96234. AggInfo *pAggInfo = pNC->uNC.pAggInfo;
  96235. assert( pNC->ncFlags & NC_UAggInfo );
  96236. switch( pExpr->op ){
  96237. case TK_AGG_COLUMN:
  96238. case TK_COLUMN: {
  96239. testcase( pExpr->op==TK_AGG_COLUMN );
  96240. testcase( pExpr->op==TK_COLUMN );
  96241. /* Check to see if the column is in one of the tables in the FROM
  96242. ** clause of the aggregate query */
  96243. if( ALWAYS(pSrcList!=0) ){
  96244. struct SrcList_item *pItem = pSrcList->a;
  96245. for(i=0; i<pSrcList->nSrc; i++, pItem++){
  96246. struct AggInfo_col *pCol;
  96247. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  96248. if( pExpr->iTable==pItem->iCursor ){
  96249. /* If we reach this point, it means that pExpr refers to a table
  96250. ** that is in the FROM clause of the aggregate query.
  96251. **
  96252. ** Make an entry for the column in pAggInfo->aCol[] if there
  96253. ** is not an entry there already.
  96254. */
  96255. int k;
  96256. pCol = pAggInfo->aCol;
  96257. for(k=0; k<pAggInfo->nColumn; k++, pCol++){
  96258. if( pCol->iTable==pExpr->iTable &&
  96259. pCol->iColumn==pExpr->iColumn ){
  96260. break;
  96261. }
  96262. }
  96263. if( (k>=pAggInfo->nColumn)
  96264. && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
  96265. ){
  96266. pCol = &pAggInfo->aCol[k];
  96267. pCol->pTab = pExpr->y.pTab;
  96268. pCol->iTable = pExpr->iTable;
  96269. pCol->iColumn = pExpr->iColumn;
  96270. pCol->iMem = ++pParse->nMem;
  96271. pCol->iSorterColumn = -1;
  96272. pCol->pExpr = pExpr;
  96273. if( pAggInfo->pGroupBy ){
  96274. int j, n;
  96275. ExprList *pGB = pAggInfo->pGroupBy;
  96276. struct ExprList_item *pTerm = pGB->a;
  96277. n = pGB->nExpr;
  96278. for(j=0; j<n; j++, pTerm++){
  96279. Expr *pE = pTerm->pExpr;
  96280. if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
  96281. pE->iColumn==pExpr->iColumn ){
  96282. pCol->iSorterColumn = j;
  96283. break;
  96284. }
  96285. }
  96286. }
  96287. if( pCol->iSorterColumn<0 ){
  96288. pCol->iSorterColumn = pAggInfo->nSortingColumn++;
  96289. }
  96290. }
  96291. /* There is now an entry for pExpr in pAggInfo->aCol[] (either
  96292. ** because it was there before or because we just created it).
  96293. ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
  96294. ** pAggInfo->aCol[] entry.
  96295. */
  96296. ExprSetVVAProperty(pExpr, EP_NoReduce);
  96297. pExpr->pAggInfo = pAggInfo;
  96298. pExpr->op = TK_AGG_COLUMN;
  96299. pExpr->iAgg = (i16)k;
  96300. break;
  96301. } /* endif pExpr->iTable==pItem->iCursor */
  96302. } /* end loop over pSrcList */
  96303. }
  96304. return WRC_Prune;
  96305. }
  96306. case TK_AGG_FUNCTION: {
  96307. if( (pNC->ncFlags & NC_InAggFunc)==0
  96308. && pWalker->walkerDepth==pExpr->op2
  96309. ){
  96310. /* Check to see if pExpr is a duplicate of another aggregate
  96311. ** function that is already in the pAggInfo structure
  96312. */
  96313. struct AggInfo_func *pItem = pAggInfo->aFunc;
  96314. for(i=0; i<pAggInfo->nFunc; i++, pItem++){
  96315. if( sqlite3ExprCompare(0, pItem->pExpr, pExpr, -1)==0 ){
  96316. break;
  96317. }
  96318. }
  96319. if( i>=pAggInfo->nFunc ){
  96320. /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
  96321. */
  96322. u8 enc = ENC(pParse->db);
  96323. i = addAggInfoFunc(pParse->db, pAggInfo);
  96324. if( i>=0 ){
  96325. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  96326. pItem = &pAggInfo->aFunc[i];
  96327. pItem->pExpr = pExpr;
  96328. pItem->iMem = ++pParse->nMem;
  96329. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  96330. pItem->pFunc = sqlite3FindFunction(pParse->db,
  96331. pExpr->u.zToken,
  96332. pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
  96333. if( pExpr->flags & EP_Distinct ){
  96334. pItem->iDistinct = pParse->nTab++;
  96335. }else{
  96336. pItem->iDistinct = -1;
  96337. }
  96338. }
  96339. }
  96340. /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
  96341. */
  96342. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  96343. ExprSetVVAProperty(pExpr, EP_NoReduce);
  96344. pExpr->iAgg = (i16)i;
  96345. pExpr->pAggInfo = pAggInfo;
  96346. return WRC_Prune;
  96347. }else{
  96348. return WRC_Continue;
  96349. }
  96350. }
  96351. }
  96352. return WRC_Continue;
  96353. }
  96354. static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
  96355. UNUSED_PARAMETER(pSelect);
  96356. pWalker->walkerDepth++;
  96357. return WRC_Continue;
  96358. }
  96359. static void analyzeAggregatesInSelectEnd(Walker *pWalker, Select *pSelect){
  96360. UNUSED_PARAMETER(pSelect);
  96361. pWalker->walkerDepth--;
  96362. }
  96363. /*
  96364. ** Analyze the pExpr expression looking for aggregate functions and
  96365. ** for variables that need to be added to AggInfo object that pNC->pAggInfo
  96366. ** points to. Additional entries are made on the AggInfo object as
  96367. ** necessary.
  96368. **
  96369. ** This routine should only be called after the expression has been
  96370. ** analyzed by sqlite3ResolveExprNames().
  96371. */
  96372. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
  96373. Walker w;
  96374. w.xExprCallback = analyzeAggregate;
  96375. w.xSelectCallback = analyzeAggregatesInSelect;
  96376. w.xSelectCallback2 = analyzeAggregatesInSelectEnd;
  96377. w.walkerDepth = 0;
  96378. w.u.pNC = pNC;
  96379. w.pParse = 0;
  96380. assert( pNC->pSrcList!=0 );
  96381. sqlite3WalkExpr(&w, pExpr);
  96382. }
  96383. /*
  96384. ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
  96385. ** expression list. Return the number of errors.
  96386. **
  96387. ** If an error is found, the analysis is cut short.
  96388. */
  96389. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
  96390. struct ExprList_item *pItem;
  96391. int i;
  96392. if( pList ){
  96393. for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
  96394. sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
  96395. }
  96396. }
  96397. }
  96398. /*
  96399. ** Allocate a single new register for use to hold some intermediate result.
  96400. */
  96401. SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
  96402. if( pParse->nTempReg==0 ){
  96403. return ++pParse->nMem;
  96404. }
  96405. return pParse->aTempReg[--pParse->nTempReg];
  96406. }
  96407. /*
  96408. ** Deallocate a register, making available for reuse for some other
  96409. ** purpose.
  96410. */
  96411. SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
  96412. if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
  96413. pParse->aTempReg[pParse->nTempReg++] = iReg;
  96414. }
  96415. }
  96416. /*
  96417. ** Allocate or deallocate a block of nReg consecutive registers.
  96418. */
  96419. SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
  96420. int i, n;
  96421. if( nReg==1 ) return sqlite3GetTempReg(pParse);
  96422. i = pParse->iRangeReg;
  96423. n = pParse->nRangeReg;
  96424. if( nReg<=n ){
  96425. pParse->iRangeReg += nReg;
  96426. pParse->nRangeReg -= nReg;
  96427. }else{
  96428. i = pParse->nMem+1;
  96429. pParse->nMem += nReg;
  96430. }
  96431. return i;
  96432. }
  96433. SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
  96434. if( nReg==1 ){
  96435. sqlite3ReleaseTempReg(pParse, iReg);
  96436. return;
  96437. }
  96438. if( nReg>pParse->nRangeReg ){
  96439. pParse->nRangeReg = nReg;
  96440. pParse->iRangeReg = iReg;
  96441. }
  96442. }
  96443. /*
  96444. ** Mark all temporary registers as being unavailable for reuse.
  96445. */
  96446. SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
  96447. pParse->nTempReg = 0;
  96448. pParse->nRangeReg = 0;
  96449. }
  96450. /*
  96451. ** Validate that no temporary register falls within the range of
  96452. ** iFirst..iLast, inclusive. This routine is only call from within assert()
  96453. ** statements.
  96454. */
  96455. #ifdef SQLITE_DEBUG
  96456. SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){
  96457. int i;
  96458. if( pParse->nRangeReg>0
  96459. && pParse->iRangeReg+pParse->nRangeReg > iFirst
  96460. && pParse->iRangeReg <= iLast
  96461. ){
  96462. return 0;
  96463. }
  96464. for(i=0; i<pParse->nTempReg; i++){
  96465. if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){
  96466. return 0;
  96467. }
  96468. }
  96469. return 1;
  96470. }
  96471. #endif /* SQLITE_DEBUG */
  96472. /************** End of expr.c ************************************************/
  96473. /************** Begin file alter.c *******************************************/
  96474. /*
  96475. ** 2005 February 15
  96476. **
  96477. ** The author disclaims copyright to this source code. In place of
  96478. ** a legal notice, here is a blessing:
  96479. **
  96480. ** May you do good and not evil.
  96481. ** May you find forgiveness for yourself and forgive others.
  96482. ** May you share freely, never taking more than you give.
  96483. **
  96484. *************************************************************************
  96485. ** This file contains C code routines that used to generate VDBE code
  96486. ** that implements the ALTER TABLE command.
  96487. */
  96488. /* #include "sqliteInt.h" */
  96489. /*
  96490. ** The code in this file only exists if we are not omitting the
  96491. ** ALTER TABLE logic from the build.
  96492. */
  96493. #ifndef SQLITE_OMIT_ALTERTABLE
  96494. /*
  96495. ** Parameter zName is the name of a table that is about to be altered
  96496. ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
  96497. ** If the table is a system table, this function leaves an error message
  96498. ** in pParse->zErr (system tables may not be altered) and returns non-zero.
  96499. **
  96500. ** Or, if zName is not a system table, zero is returned.
  96501. */
  96502. static int isAlterableTable(Parse *pParse, Table *pTab){
  96503. if( 0==sqlite3StrNICmp(pTab->zName, "sqlite_", 7)
  96504. #ifndef SQLITE_OMIT_VIRTUALTABLE
  96505. || ( (pTab->tabFlags & TF_Shadow)
  96506. && (pParse->db->flags & SQLITE_Defensive)
  96507. && pParse->db->nVdbeExec==0
  96508. )
  96509. #endif
  96510. ){
  96511. sqlite3ErrorMsg(pParse, "table %s may not be altered", pTab->zName);
  96512. return 1;
  96513. }
  96514. return 0;
  96515. }
  96516. /*
  96517. ** Generate code to verify that the schemas of database zDb and, if
  96518. ** bTemp is not true, database "temp", can still be parsed. This is
  96519. ** called at the end of the generation of an ALTER TABLE ... RENAME ...
  96520. ** statement to ensure that the operation has not rendered any schema
  96521. ** objects unusable.
  96522. */
  96523. static void renameTestSchema(Parse *pParse, const char *zDb, int bTemp){
  96524. sqlite3NestedParse(pParse,
  96525. "SELECT 1 "
  96526. "FROM \"%w\".%s "
  96527. "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
  96528. " AND sql NOT LIKE 'create virtual%%'"
  96529. " AND sqlite_rename_test(%Q, sql, type, name, %d)=NULL ",
  96530. zDb, MASTER_NAME,
  96531. zDb, bTemp
  96532. );
  96533. if( bTemp==0 ){
  96534. sqlite3NestedParse(pParse,
  96535. "SELECT 1 "
  96536. "FROM temp.%s "
  96537. "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
  96538. " AND sql NOT LIKE 'create virtual%%'"
  96539. " AND sqlite_rename_test(%Q, sql, type, name, 1)=NULL ",
  96540. MASTER_NAME, zDb
  96541. );
  96542. }
  96543. }
  96544. /*
  96545. ** Generate code to reload the schema for database iDb. And, if iDb!=1, for
  96546. ** the temp database as well.
  96547. */
  96548. static void renameReloadSchema(Parse *pParse, int iDb){
  96549. Vdbe *v = pParse->pVdbe;
  96550. if( v ){
  96551. sqlite3ChangeCookie(pParse, iDb);
  96552. sqlite3VdbeAddParseSchemaOp(pParse->pVdbe, iDb, 0);
  96553. if( iDb!=1 ) sqlite3VdbeAddParseSchemaOp(pParse->pVdbe, 1, 0);
  96554. }
  96555. }
  96556. /*
  96557. ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
  96558. ** command.
  96559. */
  96560. SQLITE_PRIVATE void sqlite3AlterRenameTable(
  96561. Parse *pParse, /* Parser context. */
  96562. SrcList *pSrc, /* The table to rename. */
  96563. Token *pName /* The new table name. */
  96564. ){
  96565. int iDb; /* Database that contains the table */
  96566. char *zDb; /* Name of database iDb */
  96567. Table *pTab; /* Table being renamed */
  96568. char *zName = 0; /* NULL-terminated version of pName */
  96569. sqlite3 *db = pParse->db; /* Database connection */
  96570. int nTabName; /* Number of UTF-8 characters in zTabName */
  96571. const char *zTabName; /* Original name of the table */
  96572. Vdbe *v;
  96573. VTable *pVTab = 0; /* Non-zero if this is a v-tab with an xRename() */
  96574. u32 savedDbFlags; /* Saved value of db->mDbFlags */
  96575. savedDbFlags = db->mDbFlags;
  96576. if( NEVER(db->mallocFailed) ) goto exit_rename_table;
  96577. assert( pSrc->nSrc==1 );
  96578. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  96579. pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
  96580. if( !pTab ) goto exit_rename_table;
  96581. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  96582. zDb = db->aDb[iDb].zDbSName;
  96583. db->mDbFlags |= DBFLAG_PreferBuiltin;
  96584. /* Get a NULL terminated version of the new table name. */
  96585. zName = sqlite3NameFromToken(db, pName);
  96586. if( !zName ) goto exit_rename_table;
  96587. /* Check that a table or index named 'zName' does not already exist
  96588. ** in database iDb. If so, this is an error.
  96589. */
  96590. if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
  96591. sqlite3ErrorMsg(pParse,
  96592. "there is already another table or index with this name: %s", zName);
  96593. goto exit_rename_table;
  96594. }
  96595. /* Make sure it is not a system table being altered, or a reserved name
  96596. ** that the table is being renamed to.
  96597. */
  96598. if( SQLITE_OK!=isAlterableTable(pParse, pTab) ){
  96599. goto exit_rename_table;
  96600. }
  96601. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
  96602. exit_rename_table;
  96603. }
  96604. #ifndef SQLITE_OMIT_VIEW
  96605. if( pTab->pSelect ){
  96606. sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
  96607. goto exit_rename_table;
  96608. }
  96609. #endif
  96610. #ifndef SQLITE_OMIT_AUTHORIZATION
  96611. /* Invoke the authorization callback. */
  96612. if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
  96613. goto exit_rename_table;
  96614. }
  96615. #endif
  96616. #ifndef SQLITE_OMIT_VIRTUALTABLE
  96617. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  96618. goto exit_rename_table;
  96619. }
  96620. if( IsVirtual(pTab) ){
  96621. pVTab = sqlite3GetVTable(db, pTab);
  96622. if( pVTab->pVtab->pModule->xRename==0 ){
  96623. pVTab = 0;
  96624. }
  96625. }
  96626. #endif
  96627. /* Begin a transaction for database iDb. Then modify the schema cookie
  96628. ** (since the ALTER TABLE modifies the schema). Call sqlite3MayAbort(),
  96629. ** as the scalar functions (e.g. sqlite_rename_table()) invoked by the
  96630. ** nested SQL may raise an exception. */
  96631. v = sqlite3GetVdbe(pParse);
  96632. if( v==0 ){
  96633. goto exit_rename_table;
  96634. }
  96635. sqlite3MayAbort(pParse);
  96636. /* figure out how many UTF-8 characters are in zName */
  96637. zTabName = pTab->zName;
  96638. nTabName = sqlite3Utf8CharLen(zTabName, -1);
  96639. /* Rewrite all CREATE TABLE, INDEX, TRIGGER or VIEW statements in
  96640. ** the schema to use the new table name. */
  96641. sqlite3NestedParse(pParse,
  96642. "UPDATE \"%w\".%s SET "
  96643. "sql = sqlite_rename_table(%Q, type, name, sql, %Q, %Q, %d) "
  96644. "WHERE (type!='index' OR tbl_name=%Q COLLATE nocase)"
  96645. "AND name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
  96646. , zDb, MASTER_NAME, zDb, zTabName, zName, (iDb==1), zTabName
  96647. );
  96648. /* Update the tbl_name and name columns of the sqlite_master table
  96649. ** as required. */
  96650. sqlite3NestedParse(pParse,
  96651. "UPDATE %Q.%s SET "
  96652. "tbl_name = %Q, "
  96653. "name = CASE "
  96654. "WHEN type='table' THEN %Q "
  96655. "WHEN name LIKE 'sqliteX_autoindex%%' ESCAPE 'X' "
  96656. " AND type='index' THEN "
  96657. "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
  96658. "ELSE name END "
  96659. "WHERE tbl_name=%Q COLLATE nocase AND "
  96660. "(type='table' OR type='index' OR type='trigger');",
  96661. zDb, MASTER_NAME,
  96662. zName, zName, zName,
  96663. nTabName, zTabName
  96664. );
  96665. #ifndef SQLITE_OMIT_AUTOINCREMENT
  96666. /* If the sqlite_sequence table exists in this database, then update
  96667. ** it with the new table name.
  96668. */
  96669. if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
  96670. sqlite3NestedParse(pParse,
  96671. "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
  96672. zDb, zName, pTab->zName);
  96673. }
  96674. #endif
  96675. /* If the table being renamed is not itself part of the temp database,
  96676. ** edit view and trigger definitions within the temp database
  96677. ** as required. */
  96678. if( iDb!=1 ){
  96679. sqlite3NestedParse(pParse,
  96680. "UPDATE sqlite_temp_master SET "
  96681. "sql = sqlite_rename_table(%Q, type, name, sql, %Q, %Q, 1), "
  96682. "tbl_name = "
  96683. "CASE WHEN tbl_name=%Q COLLATE nocase AND "
  96684. " sqlite_rename_test(%Q, sql, type, name, 1) "
  96685. "THEN %Q ELSE tbl_name END "
  96686. "WHERE type IN ('view', 'trigger')"
  96687. , zDb, zTabName, zName, zTabName, zDb, zName);
  96688. }
  96689. /* If this is a virtual table, invoke the xRename() function if
  96690. ** one is defined. The xRename() callback will modify the names
  96691. ** of any resources used by the v-table implementation (including other
  96692. ** SQLite tables) that are identified by the name of the virtual table.
  96693. */
  96694. #ifndef SQLITE_OMIT_VIRTUALTABLE
  96695. if( pVTab ){
  96696. int i = ++pParse->nMem;
  96697. sqlite3VdbeLoadString(v, i, zName);
  96698. sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
  96699. }
  96700. #endif
  96701. renameReloadSchema(pParse, iDb);
  96702. renameTestSchema(pParse, zDb, iDb==1);
  96703. exit_rename_table:
  96704. sqlite3SrcListDelete(db, pSrc);
  96705. sqlite3DbFree(db, zName);
  96706. db->mDbFlags = savedDbFlags;
  96707. }
  96708. /*
  96709. ** This function is called after an "ALTER TABLE ... ADD" statement
  96710. ** has been parsed. Argument pColDef contains the text of the new
  96711. ** column definition.
  96712. **
  96713. ** The Table structure pParse->pNewTable was extended to include
  96714. ** the new column during parsing.
  96715. */
  96716. SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
  96717. Table *pNew; /* Copy of pParse->pNewTable */
  96718. Table *pTab; /* Table being altered */
  96719. int iDb; /* Database number */
  96720. const char *zDb; /* Database name */
  96721. const char *zTab; /* Table name */
  96722. char *zCol; /* Null-terminated column definition */
  96723. Column *pCol; /* The new column */
  96724. Expr *pDflt; /* Default value for the new column */
  96725. sqlite3 *db; /* The database connection; */
  96726. Vdbe *v; /* The prepared statement under construction */
  96727. int r1; /* Temporary registers */
  96728. db = pParse->db;
  96729. if( pParse->nErr || db->mallocFailed ) return;
  96730. pNew = pParse->pNewTable;
  96731. assert( pNew );
  96732. assert( sqlite3BtreeHoldsAllMutexes(db) );
  96733. iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
  96734. zDb = db->aDb[iDb].zDbSName;
  96735. zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */
  96736. pCol = &pNew->aCol[pNew->nCol-1];
  96737. pDflt = pCol->pDflt;
  96738. pTab = sqlite3FindTable(db, zTab, zDb);
  96739. assert( pTab );
  96740. #ifndef SQLITE_OMIT_AUTHORIZATION
  96741. /* Invoke the authorization callback. */
  96742. if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
  96743. return;
  96744. }
  96745. #endif
  96746. /* If the default value for the new column was specified with a
  96747. ** literal NULL, then set pDflt to 0. This simplifies checking
  96748. ** for an SQL NULL default below.
  96749. */
  96750. assert( pDflt==0 || pDflt->op==TK_SPAN );
  96751. if( pDflt && pDflt->pLeft->op==TK_NULL ){
  96752. pDflt = 0;
  96753. }
  96754. /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
  96755. ** If there is a NOT NULL constraint, then the default value for the
  96756. ** column must not be NULL.
  96757. */
  96758. if( pCol->colFlags & COLFLAG_PRIMKEY ){
  96759. sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
  96760. return;
  96761. }
  96762. if( pNew->pIndex ){
  96763. sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
  96764. return;
  96765. }
  96766. if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
  96767. sqlite3ErrorMsg(pParse,
  96768. "Cannot add a REFERENCES column with non-NULL default value");
  96769. return;
  96770. }
  96771. if( pCol->notNull && !pDflt ){
  96772. sqlite3ErrorMsg(pParse,
  96773. "Cannot add a NOT NULL column with default value NULL");
  96774. return;
  96775. }
  96776. /* Ensure the default expression is something that sqlite3ValueFromExpr()
  96777. ** can handle (i.e. not CURRENT_TIME etc.)
  96778. */
  96779. if( pDflt ){
  96780. sqlite3_value *pVal = 0;
  96781. int rc;
  96782. rc = sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_BLOB, &pVal);
  96783. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  96784. if( rc!=SQLITE_OK ){
  96785. assert( db->mallocFailed == 1 );
  96786. return;
  96787. }
  96788. if( !pVal ){
  96789. sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
  96790. return;
  96791. }
  96792. sqlite3ValueFree(pVal);
  96793. }
  96794. /* Modify the CREATE TABLE statement. */
  96795. zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
  96796. if( zCol ){
  96797. char *zEnd = &zCol[pColDef->n-1];
  96798. u32 savedDbFlags = db->mDbFlags;
  96799. while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
  96800. *zEnd-- = '\0';
  96801. }
  96802. db->mDbFlags |= DBFLAG_PreferBuiltin;
  96803. sqlite3NestedParse(pParse,
  96804. "UPDATE \"%w\".%s SET "
  96805. "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
  96806. "WHERE type = 'table' AND name = %Q",
  96807. zDb, MASTER_NAME, pNew->addColOffset, zCol, pNew->addColOffset+1,
  96808. zTab
  96809. );
  96810. sqlite3DbFree(db, zCol);
  96811. db->mDbFlags = savedDbFlags;
  96812. }
  96813. /* Make sure the schema version is at least 3. But do not upgrade
  96814. ** from less than 3 to 4, as that will corrupt any preexisting DESC
  96815. ** index.
  96816. */
  96817. v = sqlite3GetVdbe(pParse);
  96818. if( v ){
  96819. r1 = sqlite3GetTempReg(pParse);
  96820. sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
  96821. sqlite3VdbeUsesBtree(v, iDb);
  96822. sqlite3VdbeAddOp2(v, OP_AddImm, r1, -2);
  96823. sqlite3VdbeAddOp2(v, OP_IfPos, r1, sqlite3VdbeCurrentAddr(v)+2);
  96824. VdbeCoverage(v);
  96825. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, 3);
  96826. sqlite3ReleaseTempReg(pParse, r1);
  96827. }
  96828. /* Reload the table definition */
  96829. renameReloadSchema(pParse, iDb);
  96830. }
  96831. /*
  96832. ** This function is called by the parser after the table-name in
  96833. ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
  96834. ** pSrc is the full-name of the table being altered.
  96835. **
  96836. ** This routine makes a (partial) copy of the Table structure
  96837. ** for the table being altered and sets Parse.pNewTable to point
  96838. ** to it. Routines called by the parser as the column definition
  96839. ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
  96840. ** the copy. The copy of the Table structure is deleted by tokenize.c
  96841. ** after parsing is finished.
  96842. **
  96843. ** Routine sqlite3AlterFinishAddColumn() will be called to complete
  96844. ** coding the "ALTER TABLE ... ADD" statement.
  96845. */
  96846. SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
  96847. Table *pNew;
  96848. Table *pTab;
  96849. int iDb;
  96850. int i;
  96851. int nAlloc;
  96852. sqlite3 *db = pParse->db;
  96853. /* Look up the table being altered. */
  96854. assert( pParse->pNewTable==0 );
  96855. assert( sqlite3BtreeHoldsAllMutexes(db) );
  96856. if( db->mallocFailed ) goto exit_begin_add_column;
  96857. pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
  96858. if( !pTab ) goto exit_begin_add_column;
  96859. #ifndef SQLITE_OMIT_VIRTUALTABLE
  96860. if( IsVirtual(pTab) ){
  96861. sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
  96862. goto exit_begin_add_column;
  96863. }
  96864. #endif
  96865. /* Make sure this is not an attempt to ALTER a view. */
  96866. if( pTab->pSelect ){
  96867. sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
  96868. goto exit_begin_add_column;
  96869. }
  96870. if( SQLITE_OK!=isAlterableTable(pParse, pTab) ){
  96871. goto exit_begin_add_column;
  96872. }
  96873. assert( pTab->addColOffset>0 );
  96874. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  96875. /* Put a copy of the Table struct in Parse.pNewTable for the
  96876. ** sqlite3AddColumn() function and friends to modify. But modify
  96877. ** the name by adding an "sqlite_altertab_" prefix. By adding this
  96878. ** prefix, we insure that the name will not collide with an existing
  96879. ** table because user table are not allowed to have the "sqlite_"
  96880. ** prefix on their name.
  96881. */
  96882. pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
  96883. if( !pNew ) goto exit_begin_add_column;
  96884. pParse->pNewTable = pNew;
  96885. pNew->nTabRef = 1;
  96886. pNew->nCol = pTab->nCol;
  96887. assert( pNew->nCol>0 );
  96888. nAlloc = (((pNew->nCol-1)/8)*8)+8;
  96889. assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
  96890. pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
  96891. pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
  96892. if( !pNew->aCol || !pNew->zName ){
  96893. assert( db->mallocFailed );
  96894. goto exit_begin_add_column;
  96895. }
  96896. memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
  96897. for(i=0; i<pNew->nCol; i++){
  96898. Column *pCol = &pNew->aCol[i];
  96899. pCol->zName = sqlite3DbStrDup(db, pCol->zName);
  96900. pCol->zColl = 0;
  96901. pCol->pDflt = 0;
  96902. }
  96903. pNew->pSchema = db->aDb[iDb].pSchema;
  96904. pNew->addColOffset = pTab->addColOffset;
  96905. pNew->nTabRef = 1;
  96906. exit_begin_add_column:
  96907. sqlite3SrcListDelete(db, pSrc);
  96908. return;
  96909. }
  96910. /*
  96911. ** Parameter pTab is the subject of an ALTER TABLE ... RENAME COLUMN
  96912. ** command. This function checks if the table is a view or virtual
  96913. ** table (columns of views or virtual tables may not be renamed). If so,
  96914. ** it loads an error message into pParse and returns non-zero.
  96915. **
  96916. ** Or, if pTab is not a view or virtual table, zero is returned.
  96917. */
  96918. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  96919. static int isRealTable(Parse *pParse, Table *pTab){
  96920. const char *zType = 0;
  96921. #ifndef SQLITE_OMIT_VIEW
  96922. if( pTab->pSelect ){
  96923. zType = "view";
  96924. }
  96925. #endif
  96926. #ifndef SQLITE_OMIT_VIRTUALTABLE
  96927. if( IsVirtual(pTab) ){
  96928. zType = "virtual table";
  96929. }
  96930. #endif
  96931. if( zType ){
  96932. sqlite3ErrorMsg(
  96933. pParse, "cannot rename columns of %s \"%s\"", zType, pTab->zName
  96934. );
  96935. return 1;
  96936. }
  96937. return 0;
  96938. }
  96939. #else /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
  96940. # define isRealTable(x,y) (0)
  96941. #endif
  96942. /*
  96943. ** Handles the following parser reduction:
  96944. **
  96945. ** cmd ::= ALTER TABLE pSrc RENAME COLUMN pOld TO pNew
  96946. */
  96947. SQLITE_PRIVATE void sqlite3AlterRenameColumn(
  96948. Parse *pParse, /* Parsing context */
  96949. SrcList *pSrc, /* Table being altered. pSrc->nSrc==1 */
  96950. Token *pOld, /* Name of column being changed */
  96951. Token *pNew /* New column name */
  96952. ){
  96953. sqlite3 *db = pParse->db; /* Database connection */
  96954. Table *pTab; /* Table being updated */
  96955. int iCol; /* Index of column being renamed */
  96956. char *zOld = 0; /* Old column name */
  96957. char *zNew = 0; /* New column name */
  96958. const char *zDb; /* Name of schema containing the table */
  96959. int iSchema; /* Index of the schema */
  96960. int bQuote; /* True to quote the new name */
  96961. /* Locate the table to be altered */
  96962. pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
  96963. if( !pTab ) goto exit_rename_column;
  96964. /* Cannot alter a system table */
  96965. if( SQLITE_OK!=isAlterableTable(pParse, pTab) ) goto exit_rename_column;
  96966. if( SQLITE_OK!=isRealTable(pParse, pTab) ) goto exit_rename_column;
  96967. /* Which schema holds the table to be altered */
  96968. iSchema = sqlite3SchemaToIndex(db, pTab->pSchema);
  96969. assert( iSchema>=0 );
  96970. zDb = db->aDb[iSchema].zDbSName;
  96971. #ifndef SQLITE_OMIT_AUTHORIZATION
  96972. /* Invoke the authorization callback. */
  96973. if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
  96974. goto exit_rename_column;
  96975. }
  96976. #endif
  96977. /* Make sure the old name really is a column name in the table to be
  96978. ** altered. Set iCol to be the index of the column being renamed */
  96979. zOld = sqlite3NameFromToken(db, pOld);
  96980. if( !zOld ) goto exit_rename_column;
  96981. for(iCol=0; iCol<pTab->nCol; iCol++){
  96982. if( 0==sqlite3StrICmp(pTab->aCol[iCol].zName, zOld) ) break;
  96983. }
  96984. if( iCol==pTab->nCol ){
  96985. sqlite3ErrorMsg(pParse, "no such column: \"%s\"", zOld);
  96986. goto exit_rename_column;
  96987. }
  96988. /* Do the rename operation using a recursive UPDATE statement that
  96989. ** uses the sqlite_rename_column() SQL function to compute the new
  96990. ** CREATE statement text for the sqlite_master table.
  96991. */
  96992. sqlite3MayAbort(pParse);
  96993. zNew = sqlite3NameFromToken(db, pNew);
  96994. if( !zNew ) goto exit_rename_column;
  96995. assert( pNew->n>0 );
  96996. bQuote = sqlite3Isquote(pNew->z[0]);
  96997. sqlite3NestedParse(pParse,
  96998. "UPDATE \"%w\".%s SET "
  96999. "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, %d) "
  97000. "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X' "
  97001. " AND (type != 'index' OR tbl_name = %Q)"
  97002. " AND sql NOT LIKE 'create virtual%%'",
  97003. zDb, MASTER_NAME,
  97004. zDb, pTab->zName, iCol, zNew, bQuote, iSchema==1,
  97005. pTab->zName
  97006. );
  97007. sqlite3NestedParse(pParse,
  97008. "UPDATE temp.%s SET "
  97009. "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, 1) "
  97010. "WHERE type IN ('trigger', 'view')",
  97011. MASTER_NAME,
  97012. zDb, pTab->zName, iCol, zNew, bQuote
  97013. );
  97014. /* Drop and reload the database schema. */
  97015. renameReloadSchema(pParse, iSchema);
  97016. renameTestSchema(pParse, zDb, iSchema==1);
  97017. exit_rename_column:
  97018. sqlite3SrcListDelete(db, pSrc);
  97019. sqlite3DbFree(db, zOld);
  97020. sqlite3DbFree(db, zNew);
  97021. return;
  97022. }
  97023. /*
  97024. ** Each RenameToken object maps an element of the parse tree into
  97025. ** the token that generated that element. The parse tree element
  97026. ** might be one of:
  97027. **
  97028. ** * A pointer to an Expr that represents an ID
  97029. ** * The name of a table column in Column.zName
  97030. **
  97031. ** A list of RenameToken objects can be constructed during parsing.
  97032. ** Each new object is created by sqlite3RenameTokenMap().
  97033. ** As the parse tree is transformed, the sqlite3RenameTokenRemap()
  97034. ** routine is used to keep the mapping current.
  97035. **
  97036. ** After the parse finishes, renameTokenFind() routine can be used
  97037. ** to look up the actual token value that created some element in
  97038. ** the parse tree.
  97039. */
  97040. struct RenameToken {
  97041. void *p; /* Parse tree element created by token t */
  97042. Token t; /* The token that created parse tree element p */
  97043. RenameToken *pNext; /* Next is a list of all RenameToken objects */
  97044. };
  97045. /*
  97046. ** The context of an ALTER TABLE RENAME COLUMN operation that gets passed
  97047. ** down into the Walker.
  97048. */
  97049. typedef struct RenameCtx RenameCtx;
  97050. struct RenameCtx {
  97051. RenameToken *pList; /* List of tokens to overwrite */
  97052. int nList; /* Number of tokens in pList */
  97053. int iCol; /* Index of column being renamed */
  97054. Table *pTab; /* Table being ALTERed */
  97055. const char *zOld; /* Old column name */
  97056. };
  97057. #ifdef SQLITE_DEBUG
  97058. /*
  97059. ** This function is only for debugging. It performs two tasks:
  97060. **
  97061. ** 1. Checks that pointer pPtr does not already appear in the
  97062. ** rename-token list.
  97063. **
  97064. ** 2. Dereferences each pointer in the rename-token list.
  97065. **
  97066. ** The second is most effective when debugging under valgrind or
  97067. ** address-sanitizer or similar. If any of these pointers no longer
  97068. ** point to valid objects, an exception is raised by the memory-checking
  97069. ** tool.
  97070. **
  97071. ** The point of this is to prevent comparisons of invalid pointer values.
  97072. ** Even though this always seems to work, it is undefined according to the
  97073. ** C standard. Example of undefined comparison:
  97074. **
  97075. ** sqlite3_free(x);
  97076. ** if( x==y ) ...
  97077. **
  97078. ** Technically, as x no longer points into a valid object or to the byte
  97079. ** following a valid object, it may not be used in comparison operations.
  97080. */
  97081. static void renameTokenCheckAll(Parse *pParse, void *pPtr){
  97082. if( pParse->nErr==0 && pParse->db->mallocFailed==0 ){
  97083. RenameToken *p;
  97084. u8 i = 0;
  97085. for(p=pParse->pRename; p; p=p->pNext){
  97086. if( p->p ){
  97087. assert( p->p!=pPtr );
  97088. i += *(u8*)(p->p);
  97089. }
  97090. }
  97091. }
  97092. }
  97093. #else
  97094. # define renameTokenCheckAll(x,y)
  97095. #endif
  97096. /*
  97097. ** Remember that the parser tree element pPtr was created using
  97098. ** the token pToken.
  97099. **
  97100. ** In other words, construct a new RenameToken object and add it
  97101. ** to the list of RenameToken objects currently being built up
  97102. ** in pParse->pRename.
  97103. **
  97104. ** The pPtr argument is returned so that this routine can be used
  97105. ** with tail recursion in tokenExpr() routine, for a small performance
  97106. ** improvement.
  97107. */
  97108. SQLITE_PRIVATE void *sqlite3RenameTokenMap(Parse *pParse, void *pPtr, Token *pToken){
  97109. RenameToken *pNew;
  97110. assert( pPtr || pParse->db->mallocFailed );
  97111. renameTokenCheckAll(pParse, pPtr);
  97112. pNew = sqlite3DbMallocZero(pParse->db, sizeof(RenameToken));
  97113. if( pNew ){
  97114. pNew->p = pPtr;
  97115. pNew->t = *pToken;
  97116. pNew->pNext = pParse->pRename;
  97117. pParse->pRename = pNew;
  97118. }
  97119. return pPtr;
  97120. }
  97121. /*
  97122. ** It is assumed that there is already a RenameToken object associated
  97123. ** with parse tree element pFrom. This function remaps the associated token
  97124. ** to parse tree element pTo.
  97125. */
  97126. SQLITE_PRIVATE void sqlite3RenameTokenRemap(Parse *pParse, void *pTo, void *pFrom){
  97127. RenameToken *p;
  97128. renameTokenCheckAll(pParse, pTo);
  97129. for(p=pParse->pRename; p; p=p->pNext){
  97130. if( p->p==pFrom ){
  97131. p->p = pTo;
  97132. break;
  97133. }
  97134. }
  97135. }
  97136. /*
  97137. ** Walker callback used by sqlite3RenameExprUnmap().
  97138. */
  97139. static int renameUnmapExprCb(Walker *pWalker, Expr *pExpr){
  97140. Parse *pParse = pWalker->pParse;
  97141. sqlite3RenameTokenRemap(pParse, 0, (void*)pExpr);
  97142. return WRC_Continue;
  97143. }
  97144. /*
  97145. ** Walker callback used by sqlite3RenameExprUnmap().
  97146. */
  97147. static int renameUnmapSelectCb(Walker *pWalker, Select *p){
  97148. Parse *pParse = pWalker->pParse;
  97149. int i;
  97150. if( ALWAYS(p->pEList) ){
  97151. ExprList *pList = p->pEList;
  97152. for(i=0; i<pList->nExpr; i++){
  97153. if( pList->a[i].zName ){
  97154. sqlite3RenameTokenRemap(pParse, 0, (void*)pList->a[i].zName);
  97155. }
  97156. }
  97157. }
  97158. if( ALWAYS(p->pSrc) ){ /* Every Select as a SrcList, even if it is empty */
  97159. SrcList *pSrc = p->pSrc;
  97160. for(i=0; i<pSrc->nSrc; i++){
  97161. sqlite3RenameTokenRemap(pParse, 0, (void*)pSrc->a[i].zName);
  97162. }
  97163. }
  97164. return WRC_Continue;
  97165. }
  97166. /*
  97167. ** Remove all nodes that are part of expression pExpr from the rename list.
  97168. */
  97169. SQLITE_PRIVATE void sqlite3RenameExprUnmap(Parse *pParse, Expr *pExpr){
  97170. Walker sWalker;
  97171. memset(&sWalker, 0, sizeof(Walker));
  97172. sWalker.pParse = pParse;
  97173. sWalker.xExprCallback = renameUnmapExprCb;
  97174. sWalker.xSelectCallback = renameUnmapSelectCb;
  97175. sqlite3WalkExpr(&sWalker, pExpr);
  97176. }
  97177. /*
  97178. ** Remove all nodes that are part of expression-list pEList from the
  97179. ** rename list.
  97180. */
  97181. SQLITE_PRIVATE void sqlite3RenameExprlistUnmap(Parse *pParse, ExprList *pEList){
  97182. if( pEList ){
  97183. int i;
  97184. Walker sWalker;
  97185. memset(&sWalker, 0, sizeof(Walker));
  97186. sWalker.pParse = pParse;
  97187. sWalker.xExprCallback = renameUnmapExprCb;
  97188. sqlite3WalkExprList(&sWalker, pEList);
  97189. for(i=0; i<pEList->nExpr; i++){
  97190. sqlite3RenameTokenRemap(pParse, 0, (void*)pEList->a[i].zName);
  97191. }
  97192. }
  97193. }
  97194. /*
  97195. ** Free the list of RenameToken objects given in the second argument
  97196. */
  97197. static void renameTokenFree(sqlite3 *db, RenameToken *pToken){
  97198. RenameToken *pNext;
  97199. RenameToken *p;
  97200. for(p=pToken; p; p=pNext){
  97201. pNext = p->pNext;
  97202. sqlite3DbFree(db, p);
  97203. }
  97204. }
  97205. /*
  97206. ** Search the Parse object passed as the first argument for a RenameToken
  97207. ** object associated with parse tree element pPtr. If found, remove it
  97208. ** from the Parse object and add it to the list maintained by the
  97209. ** RenameCtx object passed as the second argument.
  97210. */
  97211. static void renameTokenFind(Parse *pParse, struct RenameCtx *pCtx, void *pPtr){
  97212. RenameToken **pp;
  97213. assert( pPtr!=0 );
  97214. for(pp=&pParse->pRename; (*pp); pp=&(*pp)->pNext){
  97215. if( (*pp)->p==pPtr ){
  97216. RenameToken *pToken = *pp;
  97217. *pp = pToken->pNext;
  97218. pToken->pNext = pCtx->pList;
  97219. pCtx->pList = pToken;
  97220. pCtx->nList++;
  97221. break;
  97222. }
  97223. }
  97224. }
  97225. /*
  97226. ** Iterate through the Select objects that are part of WITH clauses attached
  97227. ** to select statement pSelect.
  97228. */
  97229. static void renameWalkWith(Walker *pWalker, Select *pSelect){
  97230. if( pSelect->pWith ){
  97231. int i;
  97232. for(i=0; i<pSelect->pWith->nCte; i++){
  97233. Select *p = pSelect->pWith->a[i].pSelect;
  97234. NameContext sNC;
  97235. memset(&sNC, 0, sizeof(sNC));
  97236. sNC.pParse = pWalker->pParse;
  97237. sqlite3SelectPrep(sNC.pParse, p, &sNC);
  97238. sqlite3WalkSelect(pWalker, p);
  97239. }
  97240. }
  97241. }
  97242. /*
  97243. ** This is a Walker select callback. It does nothing. It is only required
  97244. ** because without a dummy callback, sqlite3WalkExpr() and similar do not
  97245. ** descend into sub-select statements.
  97246. */
  97247. static int renameColumnSelectCb(Walker *pWalker, Select *p){
  97248. renameWalkWith(pWalker, p);
  97249. return WRC_Continue;
  97250. }
  97251. /*
  97252. ** This is a Walker expression callback.
  97253. **
  97254. ** For every TK_COLUMN node in the expression tree, search to see
  97255. ** if the column being references is the column being renamed by an
  97256. ** ALTER TABLE statement. If it is, then attach its associated
  97257. ** RenameToken object to the list of RenameToken objects being
  97258. ** constructed in RenameCtx object at pWalker->u.pRename.
  97259. */
  97260. static int renameColumnExprCb(Walker *pWalker, Expr *pExpr){
  97261. RenameCtx *p = pWalker->u.pRename;
  97262. if( pExpr->op==TK_TRIGGER
  97263. && pExpr->iColumn==p->iCol
  97264. && pWalker->pParse->pTriggerTab==p->pTab
  97265. ){
  97266. renameTokenFind(pWalker->pParse, p, (void*)pExpr);
  97267. }else if( pExpr->op==TK_COLUMN
  97268. && pExpr->iColumn==p->iCol
  97269. && p->pTab==pExpr->y.pTab
  97270. ){
  97271. renameTokenFind(pWalker->pParse, p, (void*)pExpr);
  97272. }
  97273. return WRC_Continue;
  97274. }
  97275. /*
  97276. ** The RenameCtx contains a list of tokens that reference a column that
  97277. ** is being renamed by an ALTER TABLE statement. Return the "last"
  97278. ** RenameToken in the RenameCtx and remove that RenameToken from the
  97279. ** RenameContext. "Last" means the last RenameToken encountered when
  97280. ** the input SQL is parsed from left to right. Repeated calls to this routine
  97281. ** return all column name tokens in the order that they are encountered
  97282. ** in the SQL statement.
  97283. */
  97284. static RenameToken *renameColumnTokenNext(RenameCtx *pCtx){
  97285. RenameToken *pBest = pCtx->pList;
  97286. RenameToken *pToken;
  97287. RenameToken **pp;
  97288. for(pToken=pBest->pNext; pToken; pToken=pToken->pNext){
  97289. if( pToken->t.z>pBest->t.z ) pBest = pToken;
  97290. }
  97291. for(pp=&pCtx->pList; *pp!=pBest; pp=&(*pp)->pNext);
  97292. *pp = pBest->pNext;
  97293. return pBest;
  97294. }
  97295. /*
  97296. ** An error occured while parsing or otherwise processing a database
  97297. ** object (either pParse->pNewTable, pNewIndex or pNewTrigger) as part of an
  97298. ** ALTER TABLE RENAME COLUMN program. The error message emitted by the
  97299. ** sub-routine is currently stored in pParse->zErrMsg. This function
  97300. ** adds context to the error message and then stores it in pCtx.
  97301. */
  97302. static void renameColumnParseError(
  97303. sqlite3_context *pCtx,
  97304. int bPost,
  97305. sqlite3_value *pType,
  97306. sqlite3_value *pObject,
  97307. Parse *pParse
  97308. ){
  97309. const char *zT = (const char*)sqlite3_value_text(pType);
  97310. const char *zN = (const char*)sqlite3_value_text(pObject);
  97311. char *zErr;
  97312. zErr = sqlite3_mprintf("error in %s %s%s: %s",
  97313. zT, zN, (bPost ? " after rename" : ""),
  97314. pParse->zErrMsg
  97315. );
  97316. sqlite3_result_error(pCtx, zErr, -1);
  97317. sqlite3_free(zErr);
  97318. }
  97319. /*
  97320. ** For each name in the the expression-list pEList (i.e. each
  97321. ** pEList->a[i].zName) that matches the string in zOld, extract the
  97322. ** corresponding rename-token from Parse object pParse and add it
  97323. ** to the RenameCtx pCtx.
  97324. */
  97325. static void renameColumnElistNames(
  97326. Parse *pParse,
  97327. RenameCtx *pCtx,
  97328. ExprList *pEList,
  97329. const char *zOld
  97330. ){
  97331. if( pEList ){
  97332. int i;
  97333. for(i=0; i<pEList->nExpr; i++){
  97334. char *zName = pEList->a[i].zName;
  97335. if( 0==sqlite3_stricmp(zName, zOld) ){
  97336. renameTokenFind(pParse, pCtx, (void*)zName);
  97337. }
  97338. }
  97339. }
  97340. }
  97341. /*
  97342. ** For each name in the the id-list pIdList (i.e. each pIdList->a[i].zName)
  97343. ** that matches the string in zOld, extract the corresponding rename-token
  97344. ** from Parse object pParse and add it to the RenameCtx pCtx.
  97345. */
  97346. static void renameColumnIdlistNames(
  97347. Parse *pParse,
  97348. RenameCtx *pCtx,
  97349. IdList *pIdList,
  97350. const char *zOld
  97351. ){
  97352. if( pIdList ){
  97353. int i;
  97354. for(i=0; i<pIdList->nId; i++){
  97355. char *zName = pIdList->a[i].zName;
  97356. if( 0==sqlite3_stricmp(zName, zOld) ){
  97357. renameTokenFind(pParse, pCtx, (void*)zName);
  97358. }
  97359. }
  97360. }
  97361. }
  97362. /*
  97363. ** Parse the SQL statement zSql using Parse object (*p). The Parse object
  97364. ** is initialized by this function before it is used.
  97365. */
  97366. static int renameParseSql(
  97367. Parse *p, /* Memory to use for Parse object */
  97368. const char *zDb, /* Name of schema SQL belongs to */
  97369. int bTable, /* 1 -> RENAME TABLE, 0 -> RENAME COLUMN */
  97370. sqlite3 *db, /* Database handle */
  97371. const char *zSql, /* SQL to parse */
  97372. int bTemp /* True if SQL is from temp schema */
  97373. ){
  97374. int rc;
  97375. char *zErr = 0;
  97376. db->init.iDb = bTemp ? 1 : sqlite3FindDbName(db, zDb);
  97377. /* Parse the SQL statement passed as the first argument. If no error
  97378. ** occurs and the parse does not result in a new table, index or
  97379. ** trigger object, the database must be corrupt. */
  97380. memset(p, 0, sizeof(Parse));
  97381. p->eParseMode = (bTable ? PARSE_MODE_RENAME_TABLE : PARSE_MODE_RENAME_COLUMN);
  97382. p->db = db;
  97383. p->nQueryLoop = 1;
  97384. rc = sqlite3RunParser(p, zSql, &zErr);
  97385. assert( p->zErrMsg==0 );
  97386. assert( rc!=SQLITE_OK || zErr==0 );
  97387. p->zErrMsg = zErr;
  97388. if( db->mallocFailed ) rc = SQLITE_NOMEM;
  97389. if( rc==SQLITE_OK
  97390. && p->pNewTable==0 && p->pNewIndex==0 && p->pNewTrigger==0
  97391. ){
  97392. rc = SQLITE_CORRUPT_BKPT;
  97393. }
  97394. #ifdef SQLITE_DEBUG
  97395. /* Ensure that all mappings in the Parse.pRename list really do map to
  97396. ** a part of the input string. */
  97397. if( rc==SQLITE_OK ){
  97398. int nSql = sqlite3Strlen30(zSql);
  97399. RenameToken *pToken;
  97400. for(pToken=p->pRename; pToken; pToken=pToken->pNext){
  97401. assert( pToken->t.z>=zSql && &pToken->t.z[pToken->t.n]<=&zSql[nSql] );
  97402. }
  97403. }
  97404. #endif
  97405. db->init.iDb = 0;
  97406. return rc;
  97407. }
  97408. /*
  97409. ** This function edits SQL statement zSql, replacing each token identified
  97410. ** by the linked list pRename with the text of zNew. If argument bQuote is
  97411. ** true, then zNew is always quoted first. If no error occurs, the result
  97412. ** is loaded into context object pCtx as the result.
  97413. **
  97414. ** Or, if an error occurs (i.e. an OOM condition), an error is left in
  97415. ** pCtx and an SQLite error code returned.
  97416. */
  97417. static int renameEditSql(
  97418. sqlite3_context *pCtx, /* Return result here */
  97419. RenameCtx *pRename, /* Rename context */
  97420. const char *zSql, /* SQL statement to edit */
  97421. const char *zNew, /* New token text */
  97422. int bQuote /* True to always quote token */
  97423. ){
  97424. int nNew = sqlite3Strlen30(zNew);
  97425. int nSql = sqlite3Strlen30(zSql);
  97426. sqlite3 *db = sqlite3_context_db_handle(pCtx);
  97427. int rc = SQLITE_OK;
  97428. char *zQuot;
  97429. char *zOut;
  97430. int nQuot;
  97431. /* Set zQuot to point to a buffer containing a quoted copy of the
  97432. ** identifier zNew. If the corresponding identifier in the original
  97433. ** ALTER TABLE statement was quoted (bQuote==1), then set zNew to
  97434. ** point to zQuot so that all substitutions are made using the
  97435. ** quoted version of the new column name. */
  97436. zQuot = sqlite3MPrintf(db, "\"%w\"", zNew);
  97437. if( zQuot==0 ){
  97438. return SQLITE_NOMEM;
  97439. }else{
  97440. nQuot = sqlite3Strlen30(zQuot);
  97441. }
  97442. if( bQuote ){
  97443. zNew = zQuot;
  97444. nNew = nQuot;
  97445. }
  97446. /* At this point pRename->pList contains a list of RenameToken objects
  97447. ** corresponding to all tokens in the input SQL that must be replaced
  97448. ** with the new column name. All that remains is to construct and
  97449. ** return the edited SQL string. */
  97450. assert( nQuot>=nNew );
  97451. zOut = sqlite3DbMallocZero(db, nSql + pRename->nList*nQuot + 1);
  97452. if( zOut ){
  97453. int nOut = nSql;
  97454. memcpy(zOut, zSql, nSql);
  97455. while( pRename->pList ){
  97456. int iOff; /* Offset of token to replace in zOut */
  97457. RenameToken *pBest = renameColumnTokenNext(pRename);
  97458. u32 nReplace;
  97459. const char *zReplace;
  97460. if( sqlite3IsIdChar(*pBest->t.z) ){
  97461. nReplace = nNew;
  97462. zReplace = zNew;
  97463. }else{
  97464. nReplace = nQuot;
  97465. zReplace = zQuot;
  97466. }
  97467. iOff = pBest->t.z - zSql;
  97468. if( pBest->t.n!=nReplace ){
  97469. memmove(&zOut[iOff + nReplace], &zOut[iOff + pBest->t.n],
  97470. nOut - (iOff + pBest->t.n)
  97471. );
  97472. nOut += nReplace - pBest->t.n;
  97473. zOut[nOut] = '\0';
  97474. }
  97475. memcpy(&zOut[iOff], zReplace, nReplace);
  97476. sqlite3DbFree(db, pBest);
  97477. }
  97478. sqlite3_result_text(pCtx, zOut, -1, SQLITE_TRANSIENT);
  97479. sqlite3DbFree(db, zOut);
  97480. }else{
  97481. rc = SQLITE_NOMEM;
  97482. }
  97483. sqlite3_free(zQuot);
  97484. return rc;
  97485. }
  97486. /*
  97487. ** Resolve all symbols in the trigger at pParse->pNewTrigger, assuming
  97488. ** it was read from the schema of database zDb. Return SQLITE_OK if
  97489. ** successful. Otherwise, return an SQLite error code and leave an error
  97490. ** message in the Parse object.
  97491. */
  97492. static int renameResolveTrigger(Parse *pParse, const char *zDb){
  97493. sqlite3 *db = pParse->db;
  97494. Trigger *pNew = pParse->pNewTrigger;
  97495. TriggerStep *pStep;
  97496. NameContext sNC;
  97497. int rc = SQLITE_OK;
  97498. memset(&sNC, 0, sizeof(sNC));
  97499. sNC.pParse = pParse;
  97500. assert( pNew->pTabSchema );
  97501. pParse->pTriggerTab = sqlite3FindTable(db, pNew->table,
  97502. db->aDb[sqlite3SchemaToIndex(db, pNew->pTabSchema)].zDbSName
  97503. );
  97504. pParse->eTriggerOp = pNew->op;
  97505. /* ALWAYS() because if the table of the trigger does not exist, the
  97506. ** error would have been hit before this point */
  97507. if( ALWAYS(pParse->pTriggerTab) ){
  97508. rc = sqlite3ViewGetColumnNames(pParse, pParse->pTriggerTab);
  97509. }
  97510. /* Resolve symbols in WHEN clause */
  97511. if( rc==SQLITE_OK && pNew->pWhen ){
  97512. rc = sqlite3ResolveExprNames(&sNC, pNew->pWhen);
  97513. }
  97514. for(pStep=pNew->step_list; rc==SQLITE_OK && pStep; pStep=pStep->pNext){
  97515. if( pStep->pSelect ){
  97516. sqlite3SelectPrep(pParse, pStep->pSelect, &sNC);
  97517. if( pParse->nErr ) rc = pParse->rc;
  97518. }
  97519. if( rc==SQLITE_OK && pStep->zTarget ){
  97520. Table *pTarget = sqlite3LocateTable(pParse, 0, pStep->zTarget, zDb);
  97521. if( pTarget==0 ){
  97522. rc = SQLITE_ERROR;
  97523. }else if( SQLITE_OK==(rc = sqlite3ViewGetColumnNames(pParse, pTarget)) ){
  97524. SrcList sSrc;
  97525. memset(&sSrc, 0, sizeof(sSrc));
  97526. sSrc.nSrc = 1;
  97527. sSrc.a[0].zName = pStep->zTarget;
  97528. sSrc.a[0].pTab = pTarget;
  97529. sNC.pSrcList = &sSrc;
  97530. if( pStep->pWhere ){
  97531. rc = sqlite3ResolveExprNames(&sNC, pStep->pWhere);
  97532. }
  97533. if( rc==SQLITE_OK ){
  97534. rc = sqlite3ResolveExprListNames(&sNC, pStep->pExprList);
  97535. }
  97536. assert( !pStep->pUpsert || (!pStep->pWhere && !pStep->pExprList) );
  97537. if( pStep->pUpsert ){
  97538. Upsert *pUpsert = pStep->pUpsert;
  97539. assert( rc==SQLITE_OK );
  97540. pUpsert->pUpsertSrc = &sSrc;
  97541. sNC.uNC.pUpsert = pUpsert;
  97542. sNC.ncFlags = NC_UUpsert;
  97543. rc = sqlite3ResolveExprListNames(&sNC, pUpsert->pUpsertTarget);
  97544. if( rc==SQLITE_OK ){
  97545. ExprList *pUpsertSet = pUpsert->pUpsertSet;
  97546. rc = sqlite3ResolveExprListNames(&sNC, pUpsertSet);
  97547. }
  97548. if( rc==SQLITE_OK ){
  97549. rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertWhere);
  97550. }
  97551. if( rc==SQLITE_OK ){
  97552. rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertTargetWhere);
  97553. }
  97554. sNC.ncFlags = 0;
  97555. }
  97556. sNC.pSrcList = 0;
  97557. }
  97558. }
  97559. }
  97560. return rc;
  97561. }
  97562. /*
  97563. ** Invoke sqlite3WalkExpr() or sqlite3WalkSelect() on all Select or Expr
  97564. ** objects that are part of the trigger passed as the second argument.
  97565. */
  97566. static void renameWalkTrigger(Walker *pWalker, Trigger *pTrigger){
  97567. TriggerStep *pStep;
  97568. /* Find tokens to edit in WHEN clause */
  97569. sqlite3WalkExpr(pWalker, pTrigger->pWhen);
  97570. /* Find tokens to edit in trigger steps */
  97571. for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
  97572. sqlite3WalkSelect(pWalker, pStep->pSelect);
  97573. sqlite3WalkExpr(pWalker, pStep->pWhere);
  97574. sqlite3WalkExprList(pWalker, pStep->pExprList);
  97575. if( pStep->pUpsert ){
  97576. Upsert *pUpsert = pStep->pUpsert;
  97577. sqlite3WalkExprList(pWalker, pUpsert->pUpsertTarget);
  97578. sqlite3WalkExprList(pWalker, pUpsert->pUpsertSet);
  97579. sqlite3WalkExpr(pWalker, pUpsert->pUpsertWhere);
  97580. sqlite3WalkExpr(pWalker, pUpsert->pUpsertTargetWhere);
  97581. }
  97582. }
  97583. }
  97584. /*
  97585. ** Free the contents of Parse object (*pParse). Do not free the memory
  97586. ** occupied by the Parse object itself.
  97587. */
  97588. static void renameParseCleanup(Parse *pParse){
  97589. sqlite3 *db = pParse->db;
  97590. Index *pIdx;
  97591. if( pParse->pVdbe ){
  97592. sqlite3VdbeFinalize(pParse->pVdbe);
  97593. }
  97594. sqlite3DeleteTable(db, pParse->pNewTable);
  97595. while( (pIdx = pParse->pNewIndex)!=0 ){
  97596. pParse->pNewIndex = pIdx->pNext;
  97597. sqlite3FreeIndex(db, pIdx);
  97598. }
  97599. sqlite3DeleteTrigger(db, pParse->pNewTrigger);
  97600. sqlite3DbFree(db, pParse->zErrMsg);
  97601. renameTokenFree(db, pParse->pRename);
  97602. sqlite3ParserReset(pParse);
  97603. }
  97604. /*
  97605. ** SQL function:
  97606. **
  97607. ** sqlite_rename_column(zSql, iCol, bQuote, zNew, zTable, zOld)
  97608. **
  97609. ** 0. zSql: SQL statement to rewrite
  97610. ** 1. type: Type of object ("table", "view" etc.)
  97611. ** 2. object: Name of object
  97612. ** 3. Database: Database name (e.g. "main")
  97613. ** 4. Table: Table name
  97614. ** 5. iCol: Index of column to rename
  97615. ** 6. zNew: New column name
  97616. ** 7. bQuote: Non-zero if the new column name should be quoted.
  97617. ** 8. bTemp: True if zSql comes from temp schema
  97618. **
  97619. ** Do a column rename operation on the CREATE statement given in zSql.
  97620. ** The iCol-th column (left-most is 0) of table zTable is renamed from zCol
  97621. ** into zNew. The name should be quoted if bQuote is true.
  97622. **
  97623. ** This function is used internally by the ALTER TABLE RENAME COLUMN command.
  97624. ** It is only accessible to SQL created using sqlite3NestedParse(). It is
  97625. ** not reachable from ordinary SQL passed into sqlite3_prepare().
  97626. */
  97627. static void renameColumnFunc(
  97628. sqlite3_context *context,
  97629. int NotUsed,
  97630. sqlite3_value **argv
  97631. ){
  97632. sqlite3 *db = sqlite3_context_db_handle(context);
  97633. RenameCtx sCtx;
  97634. const char *zSql = (const char*)sqlite3_value_text(argv[0]);
  97635. const char *zDb = (const char*)sqlite3_value_text(argv[3]);
  97636. const char *zTable = (const char*)sqlite3_value_text(argv[4]);
  97637. int iCol = sqlite3_value_int(argv[5]);
  97638. const char *zNew = (const char*)sqlite3_value_text(argv[6]);
  97639. int bQuote = sqlite3_value_int(argv[7]);
  97640. int bTemp = sqlite3_value_int(argv[8]);
  97641. const char *zOld;
  97642. int rc;
  97643. Parse sParse;
  97644. Walker sWalker;
  97645. Index *pIdx;
  97646. int i;
  97647. Table *pTab;
  97648. #ifndef SQLITE_OMIT_AUTHORIZATION
  97649. sqlite3_xauth xAuth = db->xAuth;
  97650. #endif
  97651. UNUSED_PARAMETER(NotUsed);
  97652. if( zSql==0 ) return;
  97653. if( zTable==0 ) return;
  97654. if( zNew==0 ) return;
  97655. if( iCol<0 ) return;
  97656. sqlite3BtreeEnterAll(db);
  97657. pTab = sqlite3FindTable(db, zTable, zDb);
  97658. if( pTab==0 || iCol>=pTab->nCol ){
  97659. sqlite3BtreeLeaveAll(db);
  97660. return;
  97661. }
  97662. zOld = pTab->aCol[iCol].zName;
  97663. memset(&sCtx, 0, sizeof(sCtx));
  97664. sCtx.iCol = ((iCol==pTab->iPKey) ? -1 : iCol);
  97665. #ifndef SQLITE_OMIT_AUTHORIZATION
  97666. db->xAuth = 0;
  97667. #endif
  97668. rc = renameParseSql(&sParse, zDb, 0, db, zSql, bTemp);
  97669. /* Find tokens that need to be replaced. */
  97670. memset(&sWalker, 0, sizeof(Walker));
  97671. sWalker.pParse = &sParse;
  97672. sWalker.xExprCallback = renameColumnExprCb;
  97673. sWalker.xSelectCallback = renameColumnSelectCb;
  97674. sWalker.u.pRename = &sCtx;
  97675. sCtx.pTab = pTab;
  97676. if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
  97677. if( sParse.pNewTable ){
  97678. Select *pSelect = sParse.pNewTable->pSelect;
  97679. if( pSelect ){
  97680. sParse.rc = SQLITE_OK;
  97681. sqlite3SelectPrep(&sParse, sParse.pNewTable->pSelect, 0);
  97682. rc = (db->mallocFailed ? SQLITE_NOMEM : sParse.rc);
  97683. if( rc==SQLITE_OK ){
  97684. sqlite3WalkSelect(&sWalker, pSelect);
  97685. }
  97686. if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
  97687. }else{
  97688. /* A regular table */
  97689. int bFKOnly = sqlite3_stricmp(zTable, sParse.pNewTable->zName);
  97690. FKey *pFKey;
  97691. assert( sParse.pNewTable->pSelect==0 );
  97692. sCtx.pTab = sParse.pNewTable;
  97693. if( bFKOnly==0 ){
  97694. renameTokenFind(
  97695. &sParse, &sCtx, (void*)sParse.pNewTable->aCol[iCol].zName
  97696. );
  97697. if( sCtx.iCol<0 ){
  97698. renameTokenFind(&sParse, &sCtx, (void*)&sParse.pNewTable->iPKey);
  97699. }
  97700. sqlite3WalkExprList(&sWalker, sParse.pNewTable->pCheck);
  97701. for(pIdx=sParse.pNewTable->pIndex; pIdx; pIdx=pIdx->pNext){
  97702. sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
  97703. }
  97704. for(pIdx=sParse.pNewIndex; pIdx; pIdx=pIdx->pNext){
  97705. sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
  97706. }
  97707. }
  97708. for(pFKey=sParse.pNewTable->pFKey; pFKey; pFKey=pFKey->pNextFrom){
  97709. for(i=0; i<pFKey->nCol; i++){
  97710. if( bFKOnly==0 && pFKey->aCol[i].iFrom==iCol ){
  97711. renameTokenFind(&sParse, &sCtx, (void*)&pFKey->aCol[i]);
  97712. }
  97713. if( 0==sqlite3_stricmp(pFKey->zTo, zTable)
  97714. && 0==sqlite3_stricmp(pFKey->aCol[i].zCol, zOld)
  97715. ){
  97716. renameTokenFind(&sParse, &sCtx, (void*)pFKey->aCol[i].zCol);
  97717. }
  97718. }
  97719. }
  97720. }
  97721. }else if( sParse.pNewIndex ){
  97722. sqlite3WalkExprList(&sWalker, sParse.pNewIndex->aColExpr);
  97723. sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
  97724. }else{
  97725. /* A trigger */
  97726. TriggerStep *pStep;
  97727. rc = renameResolveTrigger(&sParse, (bTemp ? 0 : zDb));
  97728. if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
  97729. for(pStep=sParse.pNewTrigger->step_list; pStep; pStep=pStep->pNext){
  97730. if( pStep->zTarget ){
  97731. Table *pTarget = sqlite3LocateTable(&sParse, 0, pStep->zTarget, zDb);
  97732. if( pTarget==pTab ){
  97733. if( pStep->pUpsert ){
  97734. ExprList *pUpsertSet = pStep->pUpsert->pUpsertSet;
  97735. renameColumnElistNames(&sParse, &sCtx, pUpsertSet, zOld);
  97736. }
  97737. renameColumnIdlistNames(&sParse, &sCtx, pStep->pIdList, zOld);
  97738. renameColumnElistNames(&sParse, &sCtx, pStep->pExprList, zOld);
  97739. }
  97740. }
  97741. }
  97742. /* Find tokens to edit in UPDATE OF clause */
  97743. if( sParse.pTriggerTab==pTab ){
  97744. renameColumnIdlistNames(&sParse, &sCtx,sParse.pNewTrigger->pColumns,zOld);
  97745. }
  97746. /* Find tokens to edit in various expressions and selects */
  97747. renameWalkTrigger(&sWalker, sParse.pNewTrigger);
  97748. }
  97749. assert( rc==SQLITE_OK );
  97750. rc = renameEditSql(context, &sCtx, zSql, zNew, bQuote);
  97751. renameColumnFunc_done:
  97752. if( rc!=SQLITE_OK ){
  97753. if( sParse.zErrMsg ){
  97754. renameColumnParseError(context, 0, argv[1], argv[2], &sParse);
  97755. }else{
  97756. sqlite3_result_error_code(context, rc);
  97757. }
  97758. }
  97759. renameParseCleanup(&sParse);
  97760. renameTokenFree(db, sCtx.pList);
  97761. #ifndef SQLITE_OMIT_AUTHORIZATION
  97762. db->xAuth = xAuth;
  97763. #endif
  97764. sqlite3BtreeLeaveAll(db);
  97765. }
  97766. /*
  97767. ** Walker expression callback used by "RENAME TABLE".
  97768. */
  97769. static int renameTableExprCb(Walker *pWalker, Expr *pExpr){
  97770. RenameCtx *p = pWalker->u.pRename;
  97771. if( pExpr->op==TK_COLUMN && p->pTab==pExpr->y.pTab ){
  97772. renameTokenFind(pWalker->pParse, p, (void*)&pExpr->y.pTab);
  97773. }
  97774. return WRC_Continue;
  97775. }
  97776. /*
  97777. ** Walker select callback used by "RENAME TABLE".
  97778. */
  97779. static int renameTableSelectCb(Walker *pWalker, Select *pSelect){
  97780. int i;
  97781. RenameCtx *p = pWalker->u.pRename;
  97782. SrcList *pSrc = pSelect->pSrc;
  97783. if( pSrc==0 ){
  97784. assert( pWalker->pParse->db->mallocFailed );
  97785. return WRC_Abort;
  97786. }
  97787. for(i=0; i<pSrc->nSrc; i++){
  97788. struct SrcList_item *pItem = &pSrc->a[i];
  97789. if( pItem->pTab==p->pTab ){
  97790. renameTokenFind(pWalker->pParse, p, pItem->zName);
  97791. }
  97792. }
  97793. renameWalkWith(pWalker, pSelect);
  97794. return WRC_Continue;
  97795. }
  97796. /*
  97797. ** This C function implements an SQL user function that is used by SQL code
  97798. ** generated by the ALTER TABLE ... RENAME command to modify the definition
  97799. ** of any foreign key constraints that use the table being renamed as the
  97800. ** parent table. It is passed three arguments:
  97801. **
  97802. ** 0: The database containing the table being renamed.
  97803. ** 1. type: Type of object ("table", "view" etc.)
  97804. ** 2. object: Name of object
  97805. ** 3: The complete text of the schema statement being modified,
  97806. ** 4: The old name of the table being renamed, and
  97807. ** 5: The new name of the table being renamed.
  97808. ** 6: True if the schema statement comes from the temp db.
  97809. **
  97810. ** It returns the new schema statement. For example:
  97811. **
  97812. ** sqlite_rename_table('main', 'CREATE TABLE t1(a REFERENCES t2)','t2','t3',0)
  97813. ** -> 'CREATE TABLE t1(a REFERENCES t3)'
  97814. */
  97815. static void renameTableFunc(
  97816. sqlite3_context *context,
  97817. int NotUsed,
  97818. sqlite3_value **argv
  97819. ){
  97820. sqlite3 *db = sqlite3_context_db_handle(context);
  97821. const char *zDb = (const char*)sqlite3_value_text(argv[0]);
  97822. const char *zInput = (const char*)sqlite3_value_text(argv[3]);
  97823. const char *zOld = (const char*)sqlite3_value_text(argv[4]);
  97824. const char *zNew = (const char*)sqlite3_value_text(argv[5]);
  97825. int bTemp = sqlite3_value_int(argv[6]);
  97826. UNUSED_PARAMETER(NotUsed);
  97827. if( zInput && zOld && zNew ){
  97828. Parse sParse;
  97829. int rc;
  97830. int bQuote = 1;
  97831. RenameCtx sCtx;
  97832. Walker sWalker;
  97833. #ifndef SQLITE_OMIT_AUTHORIZATION
  97834. sqlite3_xauth xAuth = db->xAuth;
  97835. db->xAuth = 0;
  97836. #endif
  97837. sqlite3BtreeEnterAll(db);
  97838. memset(&sCtx, 0, sizeof(RenameCtx));
  97839. sCtx.pTab = sqlite3FindTable(db, zOld, zDb);
  97840. memset(&sWalker, 0, sizeof(Walker));
  97841. sWalker.pParse = &sParse;
  97842. sWalker.xExprCallback = renameTableExprCb;
  97843. sWalker.xSelectCallback = renameTableSelectCb;
  97844. sWalker.u.pRename = &sCtx;
  97845. rc = renameParseSql(&sParse, zDb, 1, db, zInput, bTemp);
  97846. if( rc==SQLITE_OK ){
  97847. int isLegacy = (db->flags & SQLITE_LegacyAlter);
  97848. if( sParse.pNewTable ){
  97849. Table *pTab = sParse.pNewTable;
  97850. if( pTab->pSelect ){
  97851. if( isLegacy==0 ){
  97852. NameContext sNC;
  97853. memset(&sNC, 0, sizeof(sNC));
  97854. sNC.pParse = &sParse;
  97855. sqlite3SelectPrep(&sParse, pTab->pSelect, &sNC);
  97856. if( sParse.nErr ) rc = sParse.rc;
  97857. sqlite3WalkSelect(&sWalker, pTab->pSelect);
  97858. }
  97859. }else{
  97860. /* Modify any FK definitions to point to the new table. */
  97861. #ifndef SQLITE_OMIT_FOREIGN_KEY
  97862. if( isLegacy==0 || (db->flags & SQLITE_ForeignKeys) ){
  97863. FKey *pFKey;
  97864. for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
  97865. if( sqlite3_stricmp(pFKey->zTo, zOld)==0 ){
  97866. renameTokenFind(&sParse, &sCtx, (void*)pFKey->zTo);
  97867. }
  97868. }
  97869. }
  97870. #endif
  97871. /* If this is the table being altered, fix any table refs in CHECK
  97872. ** expressions. Also update the name that appears right after the
  97873. ** "CREATE [VIRTUAL] TABLE" bit. */
  97874. if( sqlite3_stricmp(zOld, pTab->zName)==0 ){
  97875. sCtx.pTab = pTab;
  97876. if( isLegacy==0 ){
  97877. sqlite3WalkExprList(&sWalker, pTab->pCheck);
  97878. }
  97879. renameTokenFind(&sParse, &sCtx, pTab->zName);
  97880. }
  97881. }
  97882. }
  97883. else if( sParse.pNewIndex ){
  97884. renameTokenFind(&sParse, &sCtx, sParse.pNewIndex->zName);
  97885. if( isLegacy==0 ){
  97886. sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
  97887. }
  97888. }
  97889. #ifndef SQLITE_OMIT_TRIGGER
  97890. else{
  97891. Trigger *pTrigger = sParse.pNewTrigger;
  97892. TriggerStep *pStep;
  97893. if( 0==sqlite3_stricmp(sParse.pNewTrigger->table, zOld)
  97894. && sCtx.pTab->pSchema==pTrigger->pTabSchema
  97895. ){
  97896. renameTokenFind(&sParse, &sCtx, sParse.pNewTrigger->table);
  97897. }
  97898. if( isLegacy==0 ){
  97899. rc = renameResolveTrigger(&sParse, bTemp ? 0 : zDb);
  97900. if( rc==SQLITE_OK ){
  97901. renameWalkTrigger(&sWalker, pTrigger);
  97902. for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
  97903. if( pStep->zTarget && 0==sqlite3_stricmp(pStep->zTarget, zOld) ){
  97904. renameTokenFind(&sParse, &sCtx, pStep->zTarget);
  97905. }
  97906. }
  97907. }
  97908. }
  97909. }
  97910. #endif
  97911. }
  97912. if( rc==SQLITE_OK ){
  97913. rc = renameEditSql(context, &sCtx, zInput, zNew, bQuote);
  97914. }
  97915. if( rc!=SQLITE_OK ){
  97916. if( sParse.zErrMsg ){
  97917. renameColumnParseError(context, 0, argv[1], argv[2], &sParse);
  97918. }else{
  97919. sqlite3_result_error_code(context, rc);
  97920. }
  97921. }
  97922. renameParseCleanup(&sParse);
  97923. renameTokenFree(db, sCtx.pList);
  97924. sqlite3BtreeLeaveAll(db);
  97925. #ifndef SQLITE_OMIT_AUTHORIZATION
  97926. db->xAuth = xAuth;
  97927. #endif
  97928. }
  97929. return;
  97930. }
  97931. /*
  97932. ** An SQL user function that checks that there are no parse or symbol
  97933. ** resolution problems in a CREATE TRIGGER|TABLE|VIEW|INDEX statement.
  97934. ** After an ALTER TABLE .. RENAME operation is performed and the schema
  97935. ** reloaded, this function is called on each SQL statement in the schema
  97936. ** to ensure that it is still usable.
  97937. **
  97938. ** 0: Database name ("main", "temp" etc.).
  97939. ** 1: SQL statement.
  97940. ** 2: Object type ("view", "table", "trigger" or "index").
  97941. ** 3: Object name.
  97942. ** 4: True if object is from temp schema.
  97943. **
  97944. ** Unless it finds an error, this function normally returns NULL. However, it
  97945. ** returns integer value 1 if:
  97946. **
  97947. ** * the SQL argument creates a trigger, and
  97948. ** * the table that the trigger is attached to is in database zDb.
  97949. */
  97950. static void renameTableTest(
  97951. sqlite3_context *context,
  97952. int NotUsed,
  97953. sqlite3_value **argv
  97954. ){
  97955. sqlite3 *db = sqlite3_context_db_handle(context);
  97956. char const *zDb = (const char*)sqlite3_value_text(argv[0]);
  97957. char const *zInput = (const char*)sqlite3_value_text(argv[1]);
  97958. int bTemp = sqlite3_value_int(argv[4]);
  97959. int isLegacy = (db->flags & SQLITE_LegacyAlter);
  97960. #ifndef SQLITE_OMIT_AUTHORIZATION
  97961. sqlite3_xauth xAuth = db->xAuth;
  97962. db->xAuth = 0;
  97963. #endif
  97964. UNUSED_PARAMETER(NotUsed);
  97965. if( zDb && zInput ){
  97966. int rc;
  97967. Parse sParse;
  97968. rc = renameParseSql(&sParse, zDb, 1, db, zInput, bTemp);
  97969. if( rc==SQLITE_OK ){
  97970. if( isLegacy==0 && sParse.pNewTable && sParse.pNewTable->pSelect ){
  97971. NameContext sNC;
  97972. memset(&sNC, 0, sizeof(sNC));
  97973. sNC.pParse = &sParse;
  97974. sqlite3SelectPrep(&sParse, sParse.pNewTable->pSelect, &sNC);
  97975. if( sParse.nErr ) rc = sParse.rc;
  97976. }
  97977. else if( sParse.pNewTrigger ){
  97978. if( isLegacy==0 ){
  97979. rc = renameResolveTrigger(&sParse, bTemp ? 0 : zDb);
  97980. }
  97981. if( rc==SQLITE_OK ){
  97982. int i1 = sqlite3SchemaToIndex(db, sParse.pNewTrigger->pTabSchema);
  97983. int i2 = sqlite3FindDbName(db, zDb);
  97984. if( i1==i2 ) sqlite3_result_int(context, 1);
  97985. }
  97986. }
  97987. }
  97988. if( rc!=SQLITE_OK ){
  97989. renameColumnParseError(context, 1, argv[2], argv[3], &sParse);
  97990. }
  97991. renameParseCleanup(&sParse);
  97992. }
  97993. #ifndef SQLITE_OMIT_AUTHORIZATION
  97994. db->xAuth = xAuth;
  97995. #endif
  97996. }
  97997. /*
  97998. ** Register built-in functions used to help implement ALTER TABLE
  97999. */
  98000. SQLITE_PRIVATE void sqlite3AlterFunctions(void){
  98001. static FuncDef aAlterTableFuncs[] = {
  98002. INTERNAL_FUNCTION(sqlite_rename_column, 9, renameColumnFunc),
  98003. INTERNAL_FUNCTION(sqlite_rename_table, 7, renameTableFunc),
  98004. INTERNAL_FUNCTION(sqlite_rename_test, 5, renameTableTest),
  98005. };
  98006. sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs));
  98007. }
  98008. #endif /* SQLITE_ALTER_TABLE */
  98009. /************** End of alter.c ***********************************************/
  98010. /************** Begin file analyze.c *****************************************/
  98011. /*
  98012. ** 2005-07-08
  98013. **
  98014. ** The author disclaims copyright to this source code. In place of
  98015. ** a legal notice, here is a blessing:
  98016. **
  98017. ** May you do good and not evil.
  98018. ** May you find forgiveness for yourself and forgive others.
  98019. ** May you share freely, never taking more than you give.
  98020. **
  98021. *************************************************************************
  98022. ** This file contains code associated with the ANALYZE command.
  98023. **
  98024. ** The ANALYZE command gather statistics about the content of tables
  98025. ** and indices. These statistics are made available to the query planner
  98026. ** to help it make better decisions about how to perform queries.
  98027. **
  98028. ** The following system tables are or have been supported:
  98029. **
  98030. ** CREATE TABLE sqlite_stat1(tbl, idx, stat);
  98031. ** CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
  98032. ** CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
  98033. ** CREATE TABLE sqlite_stat4(tbl, idx, nEq, nLt, nDLt, sample);
  98034. **
  98035. ** Additional tables might be added in future releases of SQLite.
  98036. ** The sqlite_stat2 table is not created or used unless the SQLite version
  98037. ** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
  98038. ** with SQLITE_ENABLE_STAT2. The sqlite_stat2 table is deprecated.
  98039. ** The sqlite_stat2 table is superseded by sqlite_stat3, which is only
  98040. ** created and used by SQLite versions 3.7.9 and later and with
  98041. ** SQLITE_ENABLE_STAT3 defined. The functionality of sqlite_stat3
  98042. ** is a superset of sqlite_stat2. The sqlite_stat4 is an enhanced
  98043. ** version of sqlite_stat3 and is only available when compiled with
  98044. ** SQLITE_ENABLE_STAT4 and in SQLite versions 3.8.1 and later. It is
  98045. ** not possible to enable both STAT3 and STAT4 at the same time. If they
  98046. ** are both enabled, then STAT4 takes precedence.
  98047. **
  98048. ** For most applications, sqlite_stat1 provides all the statistics required
  98049. ** for the query planner to make good choices.
  98050. **
  98051. ** Format of sqlite_stat1:
  98052. **
  98053. ** There is normally one row per index, with the index identified by the
  98054. ** name in the idx column. The tbl column is the name of the table to
  98055. ** which the index belongs. In each such row, the stat column will be
  98056. ** a string consisting of a list of integers. The first integer in this
  98057. ** list is the number of rows in the index. (This is the same as the
  98058. ** number of rows in the table, except for partial indices.) The second
  98059. ** integer is the average number of rows in the index that have the same
  98060. ** value in the first column of the index. The third integer is the average
  98061. ** number of rows in the index that have the same value for the first two
  98062. ** columns. The N-th integer (for N>1) is the average number of rows in
  98063. ** the index which have the same value for the first N-1 columns. For
  98064. ** a K-column index, there will be K+1 integers in the stat column. If
  98065. ** the index is unique, then the last integer will be 1.
  98066. **
  98067. ** The list of integers in the stat column can optionally be followed
  98068. ** by the keyword "unordered". The "unordered" keyword, if it is present,
  98069. ** must be separated from the last integer by a single space. If the
  98070. ** "unordered" keyword is present, then the query planner assumes that
  98071. ** the index is unordered and will not use the index for a range query.
  98072. **
  98073. ** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
  98074. ** column contains a single integer which is the (estimated) number of
  98075. ** rows in the table identified by sqlite_stat1.tbl.
  98076. **
  98077. ** Format of sqlite_stat2:
  98078. **
  98079. ** The sqlite_stat2 is only created and is only used if SQLite is compiled
  98080. ** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
  98081. ** 3.6.18 and 3.7.8. The "stat2" table contains additional information
  98082. ** about the distribution of keys within an index. The index is identified by
  98083. ** the "idx" column and the "tbl" column is the name of the table to which
  98084. ** the index belongs. There are usually 10 rows in the sqlite_stat2
  98085. ** table for each index.
  98086. **
  98087. ** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
  98088. ** inclusive are samples of the left-most key value in the index taken at
  98089. ** evenly spaced points along the index. Let the number of samples be S
  98090. ** (10 in the standard build) and let C be the number of rows in the index.
  98091. ** Then the sampled rows are given by:
  98092. **
  98093. ** rownumber = (i*C*2 + C)/(S*2)
  98094. **
  98095. ** For i between 0 and S-1. Conceptually, the index space is divided into
  98096. ** S uniform buckets and the samples are the middle row from each bucket.
  98097. **
  98098. ** The format for sqlite_stat2 is recorded here for legacy reference. This
  98099. ** version of SQLite does not support sqlite_stat2. It neither reads nor
  98100. ** writes the sqlite_stat2 table. This version of SQLite only supports
  98101. ** sqlite_stat3.
  98102. **
  98103. ** Format for sqlite_stat3:
  98104. **
  98105. ** The sqlite_stat3 format is a subset of sqlite_stat4. Hence, the
  98106. ** sqlite_stat4 format will be described first. Further information
  98107. ** about sqlite_stat3 follows the sqlite_stat4 description.
  98108. **
  98109. ** Format for sqlite_stat4:
  98110. **
  98111. ** As with sqlite_stat2, the sqlite_stat4 table contains histogram data
  98112. ** to aid the query planner in choosing good indices based on the values
  98113. ** that indexed columns are compared against in the WHERE clauses of
  98114. ** queries.
  98115. **
  98116. ** The sqlite_stat4 table contains multiple entries for each index.
  98117. ** The idx column names the index and the tbl column is the table of the
  98118. ** index. If the idx and tbl columns are the same, then the sample is
  98119. ** of the INTEGER PRIMARY KEY. The sample column is a blob which is the
  98120. ** binary encoding of a key from the index. The nEq column is a
  98121. ** list of integers. The first integer is the approximate number
  98122. ** of entries in the index whose left-most column exactly matches
  98123. ** the left-most column of the sample. The second integer in nEq
  98124. ** is the approximate number of entries in the index where the
  98125. ** first two columns match the first two columns of the sample.
  98126. ** And so forth. nLt is another list of integers that show the approximate
  98127. ** number of entries that are strictly less than the sample. The first
  98128. ** integer in nLt contains the number of entries in the index where the
  98129. ** left-most column is less than the left-most column of the sample.
  98130. ** The K-th integer in the nLt entry is the number of index entries
  98131. ** where the first K columns are less than the first K columns of the
  98132. ** sample. The nDLt column is like nLt except that it contains the
  98133. ** number of distinct entries in the index that are less than the
  98134. ** sample.
  98135. **
  98136. ** There can be an arbitrary number of sqlite_stat4 entries per index.
  98137. ** The ANALYZE command will typically generate sqlite_stat4 tables
  98138. ** that contain between 10 and 40 samples which are distributed across
  98139. ** the key space, though not uniformly, and which include samples with
  98140. ** large nEq values.
  98141. **
  98142. ** Format for sqlite_stat3 redux:
  98143. **
  98144. ** The sqlite_stat3 table is like sqlite_stat4 except that it only
  98145. ** looks at the left-most column of the index. The sqlite_stat3.sample
  98146. ** column contains the actual value of the left-most column instead
  98147. ** of a blob encoding of the complete index key as is found in
  98148. ** sqlite_stat4.sample. The nEq, nLt, and nDLt entries of sqlite_stat3
  98149. ** all contain just a single integer which is the same as the first
  98150. ** integer in the equivalent columns in sqlite_stat4.
  98151. */
  98152. #ifndef SQLITE_OMIT_ANALYZE
  98153. /* #include "sqliteInt.h" */
  98154. #if defined(SQLITE_ENABLE_STAT4)
  98155. # define IsStat4 1
  98156. # define IsStat3 0
  98157. #elif defined(SQLITE_ENABLE_STAT3)
  98158. # define IsStat4 0
  98159. # define IsStat3 1
  98160. #else
  98161. # define IsStat4 0
  98162. # define IsStat3 0
  98163. # undef SQLITE_STAT4_SAMPLES
  98164. # define SQLITE_STAT4_SAMPLES 1
  98165. #endif
  98166. #define IsStat34 (IsStat3+IsStat4) /* 1 for STAT3 or STAT4. 0 otherwise */
  98167. /*
  98168. ** This routine generates code that opens the sqlite_statN tables.
  98169. ** The sqlite_stat1 table is always relevant. sqlite_stat2 is now
  98170. ** obsolete. sqlite_stat3 and sqlite_stat4 are only opened when
  98171. ** appropriate compile-time options are provided.
  98172. **
  98173. ** If the sqlite_statN tables do not previously exist, it is created.
  98174. **
  98175. ** Argument zWhere may be a pointer to a buffer containing a table name,
  98176. ** or it may be a NULL pointer. If it is not NULL, then all entries in
  98177. ** the sqlite_statN tables associated with the named table are deleted.
  98178. ** If zWhere==0, then code is generated to delete all stat table entries.
  98179. */
  98180. static void openStatTable(
  98181. Parse *pParse, /* Parsing context */
  98182. int iDb, /* The database we are looking in */
  98183. int iStatCur, /* Open the sqlite_stat1 table on this cursor */
  98184. const char *zWhere, /* Delete entries for this table or index */
  98185. const char *zWhereType /* Either "tbl" or "idx" */
  98186. ){
  98187. static const struct {
  98188. const char *zName;
  98189. const char *zCols;
  98190. } aTable[] = {
  98191. { "sqlite_stat1", "tbl,idx,stat" },
  98192. #if defined(SQLITE_ENABLE_STAT4)
  98193. { "sqlite_stat4", "tbl,idx,neq,nlt,ndlt,sample" },
  98194. { "sqlite_stat3", 0 },
  98195. #elif defined(SQLITE_ENABLE_STAT3)
  98196. { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
  98197. { "sqlite_stat4", 0 },
  98198. #else
  98199. { "sqlite_stat3", 0 },
  98200. { "sqlite_stat4", 0 },
  98201. #endif
  98202. };
  98203. int i;
  98204. sqlite3 *db = pParse->db;
  98205. Db *pDb;
  98206. Vdbe *v = sqlite3GetVdbe(pParse);
  98207. int aRoot[ArraySize(aTable)];
  98208. u8 aCreateTbl[ArraySize(aTable)];
  98209. if( v==0 ) return;
  98210. assert( sqlite3BtreeHoldsAllMutexes(db) );
  98211. assert( sqlite3VdbeDb(v)==db );
  98212. pDb = &db->aDb[iDb];
  98213. /* Create new statistic tables if they do not exist, or clear them
  98214. ** if they do already exist.
  98215. */
  98216. for(i=0; i<ArraySize(aTable); i++){
  98217. const char *zTab = aTable[i].zName;
  98218. Table *pStat;
  98219. if( (pStat = sqlite3FindTable(db, zTab, pDb->zDbSName))==0 ){
  98220. if( aTable[i].zCols ){
  98221. /* The sqlite_statN table does not exist. Create it. Note that a
  98222. ** side-effect of the CREATE TABLE statement is to leave the rootpage
  98223. ** of the new table in register pParse->regRoot. This is important
  98224. ** because the OpenWrite opcode below will be needing it. */
  98225. sqlite3NestedParse(pParse,
  98226. "CREATE TABLE %Q.%s(%s)", pDb->zDbSName, zTab, aTable[i].zCols
  98227. );
  98228. aRoot[i] = pParse->regRoot;
  98229. aCreateTbl[i] = OPFLAG_P2ISREG;
  98230. }
  98231. }else{
  98232. /* The table already exists. If zWhere is not NULL, delete all entries
  98233. ** associated with the table zWhere. If zWhere is NULL, delete the
  98234. ** entire contents of the table. */
  98235. aRoot[i] = pStat->tnum;
  98236. aCreateTbl[i] = 0;
  98237. sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
  98238. if( zWhere ){
  98239. sqlite3NestedParse(pParse,
  98240. "DELETE FROM %Q.%s WHERE %s=%Q",
  98241. pDb->zDbSName, zTab, zWhereType, zWhere
  98242. );
  98243. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  98244. }else if( db->xPreUpdateCallback ){
  98245. sqlite3NestedParse(pParse, "DELETE FROM %Q.%s", pDb->zDbSName, zTab);
  98246. #endif
  98247. }else{
  98248. /* The sqlite_stat[134] table already exists. Delete all rows. */
  98249. sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
  98250. }
  98251. }
  98252. }
  98253. /* Open the sqlite_stat[134] tables for writing. */
  98254. for(i=0; aTable[i].zCols; i++){
  98255. assert( i<ArraySize(aTable) );
  98256. sqlite3VdbeAddOp4Int(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb, 3);
  98257. sqlite3VdbeChangeP5(v, aCreateTbl[i]);
  98258. VdbeComment((v, aTable[i].zName));
  98259. }
  98260. }
  98261. /*
  98262. ** Recommended number of samples for sqlite_stat4
  98263. */
  98264. #ifndef SQLITE_STAT4_SAMPLES
  98265. # define SQLITE_STAT4_SAMPLES 24
  98266. #endif
  98267. /*
  98268. ** Three SQL functions - stat_init(), stat_push(), and stat_get() -
  98269. ** share an instance of the following structure to hold their state
  98270. ** information.
  98271. */
  98272. typedef struct Stat4Accum Stat4Accum;
  98273. typedef struct Stat4Sample Stat4Sample;
  98274. struct Stat4Sample {
  98275. tRowcnt *anEq; /* sqlite_stat4.nEq */
  98276. tRowcnt *anDLt; /* sqlite_stat4.nDLt */
  98277. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  98278. tRowcnt *anLt; /* sqlite_stat4.nLt */
  98279. union {
  98280. i64 iRowid; /* Rowid in main table of the key */
  98281. u8 *aRowid; /* Key for WITHOUT ROWID tables */
  98282. } u;
  98283. u32 nRowid; /* Sizeof aRowid[] */
  98284. u8 isPSample; /* True if a periodic sample */
  98285. int iCol; /* If !isPSample, the reason for inclusion */
  98286. u32 iHash; /* Tiebreaker hash */
  98287. #endif
  98288. };
  98289. struct Stat4Accum {
  98290. tRowcnt nRow; /* Number of rows in the entire table */
  98291. tRowcnt nPSample; /* How often to do a periodic sample */
  98292. int nCol; /* Number of columns in index + pk/rowid */
  98293. int nKeyCol; /* Number of index columns w/o the pk/rowid */
  98294. int mxSample; /* Maximum number of samples to accumulate */
  98295. Stat4Sample current; /* Current row as a Stat4Sample */
  98296. u32 iPrn; /* Pseudo-random number used for sampling */
  98297. Stat4Sample *aBest; /* Array of nCol best samples */
  98298. int iMin; /* Index in a[] of entry with minimum score */
  98299. int nSample; /* Current number of samples */
  98300. int nMaxEqZero; /* Max leading 0 in anEq[] for any a[] entry */
  98301. int iGet; /* Index of current sample accessed by stat_get() */
  98302. Stat4Sample *a; /* Array of mxSample Stat4Sample objects */
  98303. sqlite3 *db; /* Database connection, for malloc() */
  98304. };
  98305. /* Reclaim memory used by a Stat4Sample
  98306. */
  98307. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  98308. static void sampleClear(sqlite3 *db, Stat4Sample *p){
  98309. assert( db!=0 );
  98310. if( p->nRowid ){
  98311. sqlite3DbFree(db, p->u.aRowid);
  98312. p->nRowid = 0;
  98313. }
  98314. }
  98315. #endif
  98316. /* Initialize the BLOB value of a ROWID
  98317. */
  98318. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  98319. static void sampleSetRowid(sqlite3 *db, Stat4Sample *p, int n, const u8 *pData){
  98320. assert( db!=0 );
  98321. if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
  98322. p->u.aRowid = sqlite3DbMallocRawNN(db, n);
  98323. if( p->u.aRowid ){
  98324. p->nRowid = n;
  98325. memcpy(p->u.aRowid, pData, n);
  98326. }else{
  98327. p->nRowid = 0;
  98328. }
  98329. }
  98330. #endif
  98331. /* Initialize the INTEGER value of a ROWID.
  98332. */
  98333. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  98334. static void sampleSetRowidInt64(sqlite3 *db, Stat4Sample *p, i64 iRowid){
  98335. assert( db!=0 );
  98336. if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
  98337. p->nRowid = 0;
  98338. p->u.iRowid = iRowid;
  98339. }
  98340. #endif
  98341. /*
  98342. ** Copy the contents of object (*pFrom) into (*pTo).
  98343. */
  98344. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  98345. static void sampleCopy(Stat4Accum *p, Stat4Sample *pTo, Stat4Sample *pFrom){
  98346. pTo->isPSample = pFrom->isPSample;
  98347. pTo->iCol = pFrom->iCol;
  98348. pTo->iHash = pFrom->iHash;
  98349. memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol);
  98350. memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol);
  98351. memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol);
  98352. if( pFrom->nRowid ){
  98353. sampleSetRowid(p->db, pTo, pFrom->nRowid, pFrom->u.aRowid);
  98354. }else{
  98355. sampleSetRowidInt64(p->db, pTo, pFrom->u.iRowid);
  98356. }
  98357. }
  98358. #endif
  98359. /*
  98360. ** Reclaim all memory of a Stat4Accum structure.
  98361. */
  98362. static void stat4Destructor(void *pOld){
  98363. Stat4Accum *p = (Stat4Accum*)pOld;
  98364. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  98365. int i;
  98366. for(i=0; i<p->nCol; i++) sampleClear(p->db, p->aBest+i);
  98367. for(i=0; i<p->mxSample; i++) sampleClear(p->db, p->a+i);
  98368. sampleClear(p->db, &p->current);
  98369. #endif
  98370. sqlite3DbFree(p->db, p);
  98371. }
  98372. /*
  98373. ** Implementation of the stat_init(N,K,C) SQL function. The three parameters
  98374. ** are:
  98375. ** N: The number of columns in the index including the rowid/pk (note 1)
  98376. ** K: The number of columns in the index excluding the rowid/pk.
  98377. ** C: The number of rows in the index (note 2)
  98378. **
  98379. ** Note 1: In the special case of the covering index that implements a
  98380. ** WITHOUT ROWID table, N is the number of PRIMARY KEY columns, not the
  98381. ** total number of columns in the table.
  98382. **
  98383. ** Note 2: C is only used for STAT3 and STAT4.
  98384. **
  98385. ** For indexes on ordinary rowid tables, N==K+1. But for indexes on
  98386. ** WITHOUT ROWID tables, N=K+P where P is the number of columns in the
  98387. ** PRIMARY KEY of the table. The covering index that implements the
  98388. ** original WITHOUT ROWID table as N==K as a special case.
  98389. **
  98390. ** This routine allocates the Stat4Accum object in heap memory. The return
  98391. ** value is a pointer to the Stat4Accum object. The datatype of the
  98392. ** return value is BLOB, but it is really just a pointer to the Stat4Accum
  98393. ** object.
  98394. */
  98395. static void statInit(
  98396. sqlite3_context *context,
  98397. int argc,
  98398. sqlite3_value **argv
  98399. ){
  98400. Stat4Accum *p;
  98401. int nCol; /* Number of columns in index being sampled */
  98402. int nKeyCol; /* Number of key columns */
  98403. int nColUp; /* nCol rounded up for alignment */
  98404. int n; /* Bytes of space to allocate */
  98405. sqlite3 *db; /* Database connection */
  98406. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  98407. int mxSample = SQLITE_STAT4_SAMPLES;
  98408. #endif
  98409. /* Decode the three function arguments */
  98410. UNUSED_PARAMETER(argc);
  98411. nCol = sqlite3_value_int(argv[0]);
  98412. assert( nCol>0 );
  98413. nColUp = sizeof(tRowcnt)<8 ? (nCol+1)&~1 : nCol;
  98414. nKeyCol = sqlite3_value_int(argv[1]);
  98415. assert( nKeyCol<=nCol );
  98416. assert( nKeyCol>0 );
  98417. /* Allocate the space required for the Stat4Accum object */
  98418. n = sizeof(*p)
  98419. + sizeof(tRowcnt)*nColUp /* Stat4Accum.anEq */
  98420. + sizeof(tRowcnt)*nColUp /* Stat4Accum.anDLt */
  98421. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  98422. + sizeof(tRowcnt)*nColUp /* Stat4Accum.anLt */
  98423. + sizeof(Stat4Sample)*(nCol+mxSample) /* Stat4Accum.aBest[], a[] */
  98424. + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample)
  98425. #endif
  98426. ;
  98427. db = sqlite3_context_db_handle(context);
  98428. p = sqlite3DbMallocZero(db, n);
  98429. if( p==0 ){
  98430. sqlite3_result_error_nomem(context);
  98431. return;
  98432. }
  98433. p->db = db;
  98434. p->nRow = 0;
  98435. p->nCol = nCol;
  98436. p->nKeyCol = nKeyCol;
  98437. p->current.anDLt = (tRowcnt*)&p[1];
  98438. p->current.anEq = &p->current.anDLt[nColUp];
  98439. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  98440. {
  98441. u8 *pSpace; /* Allocated space not yet assigned */
  98442. int i; /* Used to iterate through p->aSample[] */
  98443. p->iGet = -1;
  98444. p->mxSample = mxSample;
  98445. p->nPSample = (tRowcnt)(sqlite3_value_int64(argv[2])/(mxSample/3+1) + 1);
  98446. p->current.anLt = &p->current.anEq[nColUp];
  98447. p->iPrn = 0x689e962d*(u32)nCol ^ 0xd0944565*(u32)sqlite3_value_int(argv[2]);
  98448. /* Set up the Stat4Accum.a[] and aBest[] arrays */
  98449. p->a = (struct Stat4Sample*)&p->current.anLt[nColUp];
  98450. p->aBest = &p->a[mxSample];
  98451. pSpace = (u8*)(&p->a[mxSample+nCol]);
  98452. for(i=0; i<(mxSample+nCol); i++){
  98453. p->a[i].anEq = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  98454. p->a[i].anLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  98455. p->a[i].anDLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  98456. }
  98457. assert( (pSpace - (u8*)p)==n );
  98458. for(i=0; i<nCol; i++){
  98459. p->aBest[i].iCol = i;
  98460. }
  98461. }
  98462. #endif
  98463. /* Return a pointer to the allocated object to the caller. Note that
  98464. ** only the pointer (the 2nd parameter) matters. The size of the object
  98465. ** (given by the 3rd parameter) is never used and can be any positive
  98466. ** value. */
  98467. sqlite3_result_blob(context, p, sizeof(*p), stat4Destructor);
  98468. }
  98469. static const FuncDef statInitFuncdef = {
  98470. 2+IsStat34, /* nArg */
  98471. SQLITE_UTF8, /* funcFlags */
  98472. 0, /* pUserData */
  98473. 0, /* pNext */
  98474. statInit, /* xSFunc */
  98475. 0, /* xFinalize */
  98476. 0, 0, /* xValue, xInverse */
  98477. "stat_init", /* zName */
  98478. {0}
  98479. };
  98480. #ifdef SQLITE_ENABLE_STAT4
  98481. /*
  98482. ** pNew and pOld are both candidate non-periodic samples selected for
  98483. ** the same column (pNew->iCol==pOld->iCol). Ignoring this column and
  98484. ** considering only any trailing columns and the sample hash value, this
  98485. ** function returns true if sample pNew is to be preferred over pOld.
  98486. ** In other words, if we assume that the cardinalities of the selected
  98487. ** column for pNew and pOld are equal, is pNew to be preferred over pOld.
  98488. **
  98489. ** This function assumes that for each argument sample, the contents of
  98490. ** the anEq[] array from pSample->anEq[pSample->iCol+1] onwards are valid.
  98491. */
  98492. static int sampleIsBetterPost(
  98493. Stat4Accum *pAccum,
  98494. Stat4Sample *pNew,
  98495. Stat4Sample *pOld
  98496. ){
  98497. int nCol = pAccum->nCol;
  98498. int i;
  98499. assert( pNew->iCol==pOld->iCol );
  98500. for(i=pNew->iCol+1; i<nCol; i++){
  98501. if( pNew->anEq[i]>pOld->anEq[i] ) return 1;
  98502. if( pNew->anEq[i]<pOld->anEq[i] ) return 0;
  98503. }
  98504. if( pNew->iHash>pOld->iHash ) return 1;
  98505. return 0;
  98506. }
  98507. #endif
  98508. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  98509. /*
  98510. ** Return true if pNew is to be preferred over pOld.
  98511. **
  98512. ** This function assumes that for each argument sample, the contents of
  98513. ** the anEq[] array from pSample->anEq[pSample->iCol] onwards are valid.
  98514. */
  98515. static int sampleIsBetter(
  98516. Stat4Accum *pAccum,
  98517. Stat4Sample *pNew,
  98518. Stat4Sample *pOld
  98519. ){
  98520. tRowcnt nEqNew = pNew->anEq[pNew->iCol];
  98521. tRowcnt nEqOld = pOld->anEq[pOld->iCol];
  98522. assert( pOld->isPSample==0 && pNew->isPSample==0 );
  98523. assert( IsStat4 || (pNew->iCol==0 && pOld->iCol==0) );
  98524. if( (nEqNew>nEqOld) ) return 1;
  98525. #ifdef SQLITE_ENABLE_STAT4
  98526. if( nEqNew==nEqOld ){
  98527. if( pNew->iCol<pOld->iCol ) return 1;
  98528. return (pNew->iCol==pOld->iCol && sampleIsBetterPost(pAccum, pNew, pOld));
  98529. }
  98530. return 0;
  98531. #else
  98532. return (nEqNew==nEqOld && pNew->iHash>pOld->iHash);
  98533. #endif
  98534. }
  98535. /*
  98536. ** Copy the contents of sample *pNew into the p->a[] array. If necessary,
  98537. ** remove the least desirable sample from p->a[] to make room.
  98538. */
  98539. static void sampleInsert(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){
  98540. Stat4Sample *pSample = 0;
  98541. int i;
  98542. assert( IsStat4 || nEqZero==0 );
  98543. #ifdef SQLITE_ENABLE_STAT4
  98544. /* Stat4Accum.nMaxEqZero is set to the maximum number of leading 0
  98545. ** values in the anEq[] array of any sample in Stat4Accum.a[]. In
  98546. ** other words, if nMaxEqZero is n, then it is guaranteed that there
  98547. ** are no samples with Stat4Sample.anEq[m]==0 for (m>=n). */
  98548. if( nEqZero>p->nMaxEqZero ){
  98549. p->nMaxEqZero = nEqZero;
  98550. }
  98551. if( pNew->isPSample==0 ){
  98552. Stat4Sample *pUpgrade = 0;
  98553. assert( pNew->anEq[pNew->iCol]>0 );
  98554. /* This sample is being added because the prefix that ends in column
  98555. ** iCol occurs many times in the table. However, if we have already
  98556. ** added a sample that shares this prefix, there is no need to add
  98557. ** this one. Instead, upgrade the priority of the highest priority
  98558. ** existing sample that shares this prefix. */
  98559. for(i=p->nSample-1; i>=0; i--){
  98560. Stat4Sample *pOld = &p->a[i];
  98561. if( pOld->anEq[pNew->iCol]==0 ){
  98562. if( pOld->isPSample ) return;
  98563. assert( pOld->iCol>pNew->iCol );
  98564. assert( sampleIsBetter(p, pNew, pOld) );
  98565. if( pUpgrade==0 || sampleIsBetter(p, pOld, pUpgrade) ){
  98566. pUpgrade = pOld;
  98567. }
  98568. }
  98569. }
  98570. if( pUpgrade ){
  98571. pUpgrade->iCol = pNew->iCol;
  98572. pUpgrade->anEq[pUpgrade->iCol] = pNew->anEq[pUpgrade->iCol];
  98573. goto find_new_min;
  98574. }
  98575. }
  98576. #endif
  98577. /* If necessary, remove sample iMin to make room for the new sample. */
  98578. if( p->nSample>=p->mxSample ){
  98579. Stat4Sample *pMin = &p->a[p->iMin];
  98580. tRowcnt *anEq = pMin->anEq;
  98581. tRowcnt *anLt = pMin->anLt;
  98582. tRowcnt *anDLt = pMin->anDLt;
  98583. sampleClear(p->db, pMin);
  98584. memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1));
  98585. pSample = &p->a[p->nSample-1];
  98586. pSample->nRowid = 0;
  98587. pSample->anEq = anEq;
  98588. pSample->anDLt = anDLt;
  98589. pSample->anLt = anLt;
  98590. p->nSample = p->mxSample-1;
  98591. }
  98592. /* The "rows less-than" for the rowid column must be greater than that
  98593. ** for the last sample in the p->a[] array. Otherwise, the samples would
  98594. ** be out of order. */
  98595. #ifdef SQLITE_ENABLE_STAT4
  98596. assert( p->nSample==0
  98597. || pNew->anLt[p->nCol-1] > p->a[p->nSample-1].anLt[p->nCol-1] );
  98598. #endif
  98599. /* Insert the new sample */
  98600. pSample = &p->a[p->nSample];
  98601. sampleCopy(p, pSample, pNew);
  98602. p->nSample++;
  98603. /* Zero the first nEqZero entries in the anEq[] array. */
  98604. memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero);
  98605. #ifdef SQLITE_ENABLE_STAT4
  98606. find_new_min:
  98607. #endif
  98608. if( p->nSample>=p->mxSample ){
  98609. int iMin = -1;
  98610. for(i=0; i<p->mxSample; i++){
  98611. if( p->a[i].isPSample ) continue;
  98612. if( iMin<0 || sampleIsBetter(p, &p->a[iMin], &p->a[i]) ){
  98613. iMin = i;
  98614. }
  98615. }
  98616. assert( iMin>=0 );
  98617. p->iMin = iMin;
  98618. }
  98619. }
  98620. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  98621. /*
  98622. ** Field iChng of the index being scanned has changed. So at this point
  98623. ** p->current contains a sample that reflects the previous row of the
  98624. ** index. The value of anEq[iChng] and subsequent anEq[] elements are
  98625. ** correct at this point.
  98626. */
  98627. static void samplePushPrevious(Stat4Accum *p, int iChng){
  98628. #ifdef SQLITE_ENABLE_STAT4
  98629. int i;
  98630. /* Check if any samples from the aBest[] array should be pushed
  98631. ** into IndexSample.a[] at this point. */
  98632. for(i=(p->nCol-2); i>=iChng; i--){
  98633. Stat4Sample *pBest = &p->aBest[i];
  98634. pBest->anEq[i] = p->current.anEq[i];
  98635. if( p->nSample<p->mxSample || sampleIsBetter(p, pBest, &p->a[p->iMin]) ){
  98636. sampleInsert(p, pBest, i);
  98637. }
  98638. }
  98639. /* Check that no sample contains an anEq[] entry with an index of
  98640. ** p->nMaxEqZero or greater set to zero. */
  98641. for(i=p->nSample-1; i>=0; i--){
  98642. int j;
  98643. for(j=p->nMaxEqZero; j<p->nCol; j++) assert( p->a[i].anEq[j]>0 );
  98644. }
  98645. /* Update the anEq[] fields of any samples already collected. */
  98646. if( iChng<p->nMaxEqZero ){
  98647. for(i=p->nSample-1; i>=0; i--){
  98648. int j;
  98649. for(j=iChng; j<p->nCol; j++){
  98650. if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j];
  98651. }
  98652. }
  98653. p->nMaxEqZero = iChng;
  98654. }
  98655. #endif
  98656. #if defined(SQLITE_ENABLE_STAT3) && !defined(SQLITE_ENABLE_STAT4)
  98657. if( iChng==0 ){
  98658. tRowcnt nLt = p->current.anLt[0];
  98659. tRowcnt nEq = p->current.anEq[0];
  98660. /* Check if this is to be a periodic sample. If so, add it. */
  98661. if( (nLt/p->nPSample)!=(nLt+nEq)/p->nPSample ){
  98662. p->current.isPSample = 1;
  98663. sampleInsert(p, &p->current, 0);
  98664. p->current.isPSample = 0;
  98665. }else
  98666. /* Or if it is a non-periodic sample. Add it in this case too. */
  98667. if( p->nSample<p->mxSample
  98668. || sampleIsBetter(p, &p->current, &p->a[p->iMin])
  98669. ){
  98670. sampleInsert(p, &p->current, 0);
  98671. }
  98672. }
  98673. #endif
  98674. #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
  98675. UNUSED_PARAMETER( p );
  98676. UNUSED_PARAMETER( iChng );
  98677. #endif
  98678. }
  98679. /*
  98680. ** Implementation of the stat_push SQL function: stat_push(P,C,R)
  98681. ** Arguments:
  98682. **
  98683. ** P Pointer to the Stat4Accum object created by stat_init()
  98684. ** C Index of left-most column to differ from previous row
  98685. ** R Rowid for the current row. Might be a key record for
  98686. ** WITHOUT ROWID tables.
  98687. **
  98688. ** This SQL function always returns NULL. It's purpose it to accumulate
  98689. ** statistical data and/or samples in the Stat4Accum object about the
  98690. ** index being analyzed. The stat_get() SQL function will later be used to
  98691. ** extract relevant information for constructing the sqlite_statN tables.
  98692. **
  98693. ** The R parameter is only used for STAT3 and STAT4
  98694. */
  98695. static void statPush(
  98696. sqlite3_context *context,
  98697. int argc,
  98698. sqlite3_value **argv
  98699. ){
  98700. int i;
  98701. /* The three function arguments */
  98702. Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
  98703. int iChng = sqlite3_value_int(argv[1]);
  98704. UNUSED_PARAMETER( argc );
  98705. UNUSED_PARAMETER( context );
  98706. assert( p->nCol>0 );
  98707. assert( iChng<p->nCol );
  98708. if( p->nRow==0 ){
  98709. /* This is the first call to this function. Do initialization. */
  98710. for(i=0; i<p->nCol; i++) p->current.anEq[i] = 1;
  98711. }else{
  98712. /* Second and subsequent calls get processed here */
  98713. samplePushPrevious(p, iChng);
  98714. /* Update anDLt[], anLt[] and anEq[] to reflect the values that apply
  98715. ** to the current row of the index. */
  98716. for(i=0; i<iChng; i++){
  98717. p->current.anEq[i]++;
  98718. }
  98719. for(i=iChng; i<p->nCol; i++){
  98720. p->current.anDLt[i]++;
  98721. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  98722. p->current.anLt[i] += p->current.anEq[i];
  98723. #endif
  98724. p->current.anEq[i] = 1;
  98725. }
  98726. }
  98727. p->nRow++;
  98728. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  98729. if( sqlite3_value_type(argv[2])==SQLITE_INTEGER ){
  98730. sampleSetRowidInt64(p->db, &p->current, sqlite3_value_int64(argv[2]));
  98731. }else{
  98732. sampleSetRowid(p->db, &p->current, sqlite3_value_bytes(argv[2]),
  98733. sqlite3_value_blob(argv[2]));
  98734. }
  98735. p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345;
  98736. #endif
  98737. #ifdef SQLITE_ENABLE_STAT4
  98738. {
  98739. tRowcnt nLt = p->current.anLt[p->nCol-1];
  98740. /* Check if this is to be a periodic sample. If so, add it. */
  98741. if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){
  98742. p->current.isPSample = 1;
  98743. p->current.iCol = 0;
  98744. sampleInsert(p, &p->current, p->nCol-1);
  98745. p->current.isPSample = 0;
  98746. }
  98747. /* Update the aBest[] array. */
  98748. for(i=0; i<(p->nCol-1); i++){
  98749. p->current.iCol = i;
  98750. if( i>=iChng || sampleIsBetterPost(p, &p->current, &p->aBest[i]) ){
  98751. sampleCopy(p, &p->aBest[i], &p->current);
  98752. }
  98753. }
  98754. }
  98755. #endif
  98756. }
  98757. static const FuncDef statPushFuncdef = {
  98758. 2+IsStat34, /* nArg */
  98759. SQLITE_UTF8, /* funcFlags */
  98760. 0, /* pUserData */
  98761. 0, /* pNext */
  98762. statPush, /* xSFunc */
  98763. 0, /* xFinalize */
  98764. 0, 0, /* xValue, xInverse */
  98765. "stat_push", /* zName */
  98766. {0}
  98767. };
  98768. #define STAT_GET_STAT1 0 /* "stat" column of stat1 table */
  98769. #define STAT_GET_ROWID 1 /* "rowid" column of stat[34] entry */
  98770. #define STAT_GET_NEQ 2 /* "neq" column of stat[34] entry */
  98771. #define STAT_GET_NLT 3 /* "nlt" column of stat[34] entry */
  98772. #define STAT_GET_NDLT 4 /* "ndlt" column of stat[34] entry */
  98773. /*
  98774. ** Implementation of the stat_get(P,J) SQL function. This routine is
  98775. ** used to query statistical information that has been gathered into
  98776. ** the Stat4Accum object by prior calls to stat_push(). The P parameter
  98777. ** has type BLOB but it is really just a pointer to the Stat4Accum object.
  98778. ** The content to returned is determined by the parameter J
  98779. ** which is one of the STAT_GET_xxxx values defined above.
  98780. **
  98781. ** The stat_get(P,J) function is not available to generic SQL. It is
  98782. ** inserted as part of a manually constructed bytecode program. (See
  98783. ** the callStatGet() routine below.) It is guaranteed that the P
  98784. ** parameter will always be a poiner to a Stat4Accum object, never a
  98785. ** NULL.
  98786. **
  98787. ** If neither STAT3 nor STAT4 are enabled, then J is always
  98788. ** STAT_GET_STAT1 and is hence omitted and this routine becomes
  98789. ** a one-parameter function, stat_get(P), that always returns the
  98790. ** stat1 table entry information.
  98791. */
  98792. static void statGet(
  98793. sqlite3_context *context,
  98794. int argc,
  98795. sqlite3_value **argv
  98796. ){
  98797. Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
  98798. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  98799. /* STAT3 and STAT4 have a parameter on this routine. */
  98800. int eCall = sqlite3_value_int(argv[1]);
  98801. assert( argc==2 );
  98802. assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ
  98803. || eCall==STAT_GET_ROWID || eCall==STAT_GET_NLT
  98804. || eCall==STAT_GET_NDLT
  98805. );
  98806. if( eCall==STAT_GET_STAT1 )
  98807. #else
  98808. assert( argc==1 );
  98809. #endif
  98810. {
  98811. /* Return the value to store in the "stat" column of the sqlite_stat1
  98812. ** table for this index.
  98813. **
  98814. ** The value is a string composed of a list of integers describing
  98815. ** the index. The first integer in the list is the total number of
  98816. ** entries in the index. There is one additional integer in the list
  98817. ** for each indexed column. This additional integer is an estimate of
  98818. ** the number of rows matched by a stabbing query on the index using
  98819. ** a key with the corresponding number of fields. In other words,
  98820. ** if the index is on columns (a,b) and the sqlite_stat1 value is
  98821. ** "100 10 2", then SQLite estimates that:
  98822. **
  98823. ** * the index contains 100 rows,
  98824. ** * "WHERE a=?" matches 10 rows, and
  98825. ** * "WHERE a=? AND b=?" matches 2 rows.
  98826. **
  98827. ** If D is the count of distinct values and K is the total number of
  98828. ** rows, then each estimate is computed as:
  98829. **
  98830. ** I = (K+D-1)/D
  98831. */
  98832. char *z;
  98833. int i;
  98834. char *zRet = sqlite3MallocZero( (p->nKeyCol+1)*25 );
  98835. if( zRet==0 ){
  98836. sqlite3_result_error_nomem(context);
  98837. return;
  98838. }
  98839. sqlite3_snprintf(24, zRet, "%llu", (u64)p->nRow);
  98840. z = zRet + sqlite3Strlen30(zRet);
  98841. for(i=0; i<p->nKeyCol; i++){
  98842. u64 nDistinct = p->current.anDLt[i] + 1;
  98843. u64 iVal = (p->nRow + nDistinct - 1) / nDistinct;
  98844. sqlite3_snprintf(24, z, " %llu", iVal);
  98845. z += sqlite3Strlen30(z);
  98846. assert( p->current.anEq[i] );
  98847. }
  98848. assert( z[0]=='\0' && z>zRet );
  98849. sqlite3_result_text(context, zRet, -1, sqlite3_free);
  98850. }
  98851. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  98852. else if( eCall==STAT_GET_ROWID ){
  98853. if( p->iGet<0 ){
  98854. samplePushPrevious(p, 0);
  98855. p->iGet = 0;
  98856. }
  98857. if( p->iGet<p->nSample ){
  98858. Stat4Sample *pS = p->a + p->iGet;
  98859. if( pS->nRowid==0 ){
  98860. sqlite3_result_int64(context, pS->u.iRowid);
  98861. }else{
  98862. sqlite3_result_blob(context, pS->u.aRowid, pS->nRowid,
  98863. SQLITE_TRANSIENT);
  98864. }
  98865. }
  98866. }else{
  98867. tRowcnt *aCnt = 0;
  98868. assert( p->iGet<p->nSample );
  98869. switch( eCall ){
  98870. case STAT_GET_NEQ: aCnt = p->a[p->iGet].anEq; break;
  98871. case STAT_GET_NLT: aCnt = p->a[p->iGet].anLt; break;
  98872. default: {
  98873. aCnt = p->a[p->iGet].anDLt;
  98874. p->iGet++;
  98875. break;
  98876. }
  98877. }
  98878. if( IsStat3 ){
  98879. sqlite3_result_int64(context, (i64)aCnt[0]);
  98880. }else{
  98881. char *zRet = sqlite3MallocZero(p->nCol * 25);
  98882. if( zRet==0 ){
  98883. sqlite3_result_error_nomem(context);
  98884. }else{
  98885. int i;
  98886. char *z = zRet;
  98887. for(i=0; i<p->nCol; i++){
  98888. sqlite3_snprintf(24, z, "%llu ", (u64)aCnt[i]);
  98889. z += sqlite3Strlen30(z);
  98890. }
  98891. assert( z[0]=='\0' && z>zRet );
  98892. z[-1] = '\0';
  98893. sqlite3_result_text(context, zRet, -1, sqlite3_free);
  98894. }
  98895. }
  98896. }
  98897. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  98898. #ifndef SQLITE_DEBUG
  98899. UNUSED_PARAMETER( argc );
  98900. #endif
  98901. }
  98902. static const FuncDef statGetFuncdef = {
  98903. 1+IsStat34, /* nArg */
  98904. SQLITE_UTF8, /* funcFlags */
  98905. 0, /* pUserData */
  98906. 0, /* pNext */
  98907. statGet, /* xSFunc */
  98908. 0, /* xFinalize */
  98909. 0, 0, /* xValue, xInverse */
  98910. "stat_get", /* zName */
  98911. {0}
  98912. };
  98913. static void callStatGet(Vdbe *v, int regStat4, int iParam, int regOut){
  98914. assert( regOut!=regStat4 && regOut!=regStat4+1 );
  98915. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  98916. sqlite3VdbeAddOp2(v, OP_Integer, iParam, regStat4+1);
  98917. #elif SQLITE_DEBUG
  98918. assert( iParam==STAT_GET_STAT1 );
  98919. #else
  98920. UNUSED_PARAMETER( iParam );
  98921. #endif
  98922. sqlite3VdbeAddOp4(v, OP_Function0, 0, regStat4, regOut,
  98923. (char*)&statGetFuncdef, P4_FUNCDEF);
  98924. sqlite3VdbeChangeP5(v, 1 + IsStat34);
  98925. }
  98926. /*
  98927. ** Generate code to do an analysis of all indices associated with
  98928. ** a single table.
  98929. */
  98930. static void analyzeOneTable(
  98931. Parse *pParse, /* Parser context */
  98932. Table *pTab, /* Table whose indices are to be analyzed */
  98933. Index *pOnlyIdx, /* If not NULL, only analyze this one index */
  98934. int iStatCur, /* Index of VdbeCursor that writes the sqlite_stat1 table */
  98935. int iMem, /* Available memory locations begin here */
  98936. int iTab /* Next available cursor */
  98937. ){
  98938. sqlite3 *db = pParse->db; /* Database handle */
  98939. Index *pIdx; /* An index to being analyzed */
  98940. int iIdxCur; /* Cursor open on index being analyzed */
  98941. int iTabCur; /* Table cursor */
  98942. Vdbe *v; /* The virtual machine being built up */
  98943. int i; /* Loop counter */
  98944. int jZeroRows = -1; /* Jump from here if number of rows is zero */
  98945. int iDb; /* Index of database containing pTab */
  98946. u8 needTableCnt = 1; /* True to count the table */
  98947. int regNewRowid = iMem++; /* Rowid for the inserted record */
  98948. int regStat4 = iMem++; /* Register to hold Stat4Accum object */
  98949. int regChng = iMem++; /* Index of changed index field */
  98950. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  98951. int regRowid = iMem++; /* Rowid argument passed to stat_push() */
  98952. #endif
  98953. int regTemp = iMem++; /* Temporary use register */
  98954. int regTabname = iMem++; /* Register containing table name */
  98955. int regIdxname = iMem++; /* Register containing index name */
  98956. int regStat1 = iMem++; /* Value for the stat column of sqlite_stat1 */
  98957. int regPrev = iMem; /* MUST BE LAST (see below) */
  98958. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  98959. Table *pStat1 = 0;
  98960. #endif
  98961. pParse->nMem = MAX(pParse->nMem, iMem);
  98962. v = sqlite3GetVdbe(pParse);
  98963. if( v==0 || NEVER(pTab==0) ){
  98964. return;
  98965. }
  98966. if( pTab->tnum==0 ){
  98967. /* Do not gather statistics on views or virtual tables */
  98968. return;
  98969. }
  98970. if( sqlite3_strlike("sqlite\\_%", pTab->zName, '\\')==0 ){
  98971. /* Do not gather statistics on system tables */
  98972. return;
  98973. }
  98974. assert( sqlite3BtreeHoldsAllMutexes(db) );
  98975. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  98976. assert( iDb>=0 );
  98977. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  98978. #ifndef SQLITE_OMIT_AUTHORIZATION
  98979. if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
  98980. db->aDb[iDb].zDbSName ) ){
  98981. return;
  98982. }
  98983. #endif
  98984. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  98985. if( db->xPreUpdateCallback ){
  98986. pStat1 = (Table*)sqlite3DbMallocZero(db, sizeof(Table) + 13);
  98987. if( pStat1==0 ) return;
  98988. pStat1->zName = (char*)&pStat1[1];
  98989. memcpy(pStat1->zName, "sqlite_stat1", 13);
  98990. pStat1->nCol = 3;
  98991. pStat1->iPKey = -1;
  98992. sqlite3VdbeAddOp4(pParse->pVdbe, OP_Noop, 0, 0, 0,(char*)pStat1,P4_DYNBLOB);
  98993. }
  98994. #endif
  98995. /* Establish a read-lock on the table at the shared-cache level.
  98996. ** Open a read-only cursor on the table. Also allocate a cursor number
  98997. ** to use for scanning indexes (iIdxCur). No index cursor is opened at
  98998. ** this time though. */
  98999. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  99000. iTabCur = iTab++;
  99001. iIdxCur = iTab++;
  99002. pParse->nTab = MAX(pParse->nTab, iTab);
  99003. sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
  99004. sqlite3VdbeLoadString(v, regTabname, pTab->zName);
  99005. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  99006. int nCol; /* Number of columns in pIdx. "N" */
  99007. int addrRewind; /* Address of "OP_Rewind iIdxCur" */
  99008. int addrNextRow; /* Address of "next_row:" */
  99009. const char *zIdxName; /* Name of the index */
  99010. int nColTest; /* Number of columns to test for changes */
  99011. if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
  99012. if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0;
  99013. if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIdx) ){
  99014. nCol = pIdx->nKeyCol;
  99015. zIdxName = pTab->zName;
  99016. nColTest = nCol - 1;
  99017. }else{
  99018. nCol = pIdx->nColumn;
  99019. zIdxName = pIdx->zName;
  99020. nColTest = pIdx->uniqNotNull ? pIdx->nKeyCol-1 : nCol-1;
  99021. }
  99022. /* Populate the register containing the index name. */
  99023. sqlite3VdbeLoadString(v, regIdxname, zIdxName);
  99024. VdbeComment((v, "Analysis for %s.%s", pTab->zName, zIdxName));
  99025. /*
  99026. ** Pseudo-code for loop that calls stat_push():
  99027. **
  99028. ** Rewind csr
  99029. ** if eof(csr) goto end_of_scan;
  99030. ** regChng = 0
  99031. ** goto chng_addr_0;
  99032. **
  99033. ** next_row:
  99034. ** regChng = 0
  99035. ** if( idx(0) != regPrev(0) ) goto chng_addr_0
  99036. ** regChng = 1
  99037. ** if( idx(1) != regPrev(1) ) goto chng_addr_1
  99038. ** ...
  99039. ** regChng = N
  99040. ** goto chng_addr_N
  99041. **
  99042. ** chng_addr_0:
  99043. ** regPrev(0) = idx(0)
  99044. ** chng_addr_1:
  99045. ** regPrev(1) = idx(1)
  99046. ** ...
  99047. **
  99048. ** endDistinctTest:
  99049. ** regRowid = idx(rowid)
  99050. ** stat_push(P, regChng, regRowid)
  99051. ** Next csr
  99052. ** if !eof(csr) goto next_row;
  99053. **
  99054. ** end_of_scan:
  99055. */
  99056. /* Make sure there are enough memory cells allocated to accommodate
  99057. ** the regPrev array and a trailing rowid (the rowid slot is required
  99058. ** when building a record to insert into the sample column of
  99059. ** the sqlite_stat4 table. */
  99060. pParse->nMem = MAX(pParse->nMem, regPrev+nColTest);
  99061. /* Open a read-only cursor on the index being analyzed. */
  99062. assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
  99063. sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb);
  99064. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  99065. VdbeComment((v, "%s", pIdx->zName));
  99066. /* Invoke the stat_init() function. The arguments are:
  99067. **
  99068. ** (1) the number of columns in the index including the rowid
  99069. ** (or for a WITHOUT ROWID table, the number of PK columns),
  99070. ** (2) the number of columns in the key without the rowid/pk
  99071. ** (3) the number of rows in the index,
  99072. **
  99073. **
  99074. ** The third argument is only used for STAT3 and STAT4
  99075. */
  99076. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  99077. sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat4+3);
  99078. #endif
  99079. sqlite3VdbeAddOp2(v, OP_Integer, nCol, regStat4+1);
  99080. sqlite3VdbeAddOp2(v, OP_Integer, pIdx->nKeyCol, regStat4+2);
  99081. sqlite3VdbeAddOp4(v, OP_Function0, 0, regStat4+1, regStat4,
  99082. (char*)&statInitFuncdef, P4_FUNCDEF);
  99083. sqlite3VdbeChangeP5(v, 2+IsStat34);
  99084. /* Implementation of the following:
  99085. **
  99086. ** Rewind csr
  99087. ** if eof(csr) goto end_of_scan;
  99088. ** regChng = 0
  99089. ** goto next_push_0;
  99090. **
  99091. */
  99092. addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);
  99093. VdbeCoverage(v);
  99094. sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng);
  99095. addrNextRow = sqlite3VdbeCurrentAddr(v);
  99096. if( nColTest>0 ){
  99097. int endDistinctTest = sqlite3VdbeMakeLabel(pParse);
  99098. int *aGotoChng; /* Array of jump instruction addresses */
  99099. aGotoChng = sqlite3DbMallocRawNN(db, sizeof(int)*nColTest);
  99100. if( aGotoChng==0 ) continue;
  99101. /*
  99102. ** next_row:
  99103. ** regChng = 0
  99104. ** if( idx(0) != regPrev(0) ) goto chng_addr_0
  99105. ** regChng = 1
  99106. ** if( idx(1) != regPrev(1) ) goto chng_addr_1
  99107. ** ...
  99108. ** regChng = N
  99109. ** goto endDistinctTest
  99110. */
  99111. sqlite3VdbeAddOp0(v, OP_Goto);
  99112. addrNextRow = sqlite3VdbeCurrentAddr(v);
  99113. if( nColTest==1 && pIdx->nKeyCol==1 && IsUniqueIndex(pIdx) ){
  99114. /* For a single-column UNIQUE index, once we have found a non-NULL
  99115. ** row, we know that all the rest will be distinct, so skip
  99116. ** subsequent distinctness tests. */
  99117. sqlite3VdbeAddOp2(v, OP_NotNull, regPrev, endDistinctTest);
  99118. VdbeCoverage(v);
  99119. }
  99120. for(i=0; i<nColTest; i++){
  99121. char *pColl = (char*)sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
  99122. sqlite3VdbeAddOp2(v, OP_Integer, i, regChng);
  99123. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp);
  99124. aGotoChng[i] =
  99125. sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ);
  99126. sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
  99127. VdbeCoverage(v);
  99128. }
  99129. sqlite3VdbeAddOp2(v, OP_Integer, nColTest, regChng);
  99130. sqlite3VdbeGoto(v, endDistinctTest);
  99131. /*
  99132. ** chng_addr_0:
  99133. ** regPrev(0) = idx(0)
  99134. ** chng_addr_1:
  99135. ** regPrev(1) = idx(1)
  99136. ** ...
  99137. */
  99138. sqlite3VdbeJumpHere(v, addrNextRow-1);
  99139. for(i=0; i<nColTest; i++){
  99140. sqlite3VdbeJumpHere(v, aGotoChng[i]);
  99141. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regPrev+i);
  99142. }
  99143. sqlite3VdbeResolveLabel(v, endDistinctTest);
  99144. sqlite3DbFree(db, aGotoChng);
  99145. }
  99146. /*
  99147. ** chng_addr_N:
  99148. ** regRowid = idx(rowid) // STAT34 only
  99149. ** stat_push(P, regChng, regRowid) // 3rd parameter STAT34 only
  99150. ** Next csr
  99151. ** if !eof(csr) goto next_row;
  99152. */
  99153. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  99154. assert( regRowid==(regStat4+2) );
  99155. if( HasRowid(pTab) ){
  99156. sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, regRowid);
  99157. }else{
  99158. Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
  99159. int j, k, regKey;
  99160. regKey = sqlite3GetTempRange(pParse, pPk->nKeyCol);
  99161. for(j=0; j<pPk->nKeyCol; j++){
  99162. k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
  99163. assert( k>=0 && k<pIdx->nColumn );
  99164. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, regKey+j);
  99165. VdbeComment((v, "%s", pTab->aCol[pPk->aiColumn[j]].zName));
  99166. }
  99167. sqlite3VdbeAddOp3(v, OP_MakeRecord, regKey, pPk->nKeyCol, regRowid);
  99168. sqlite3ReleaseTempRange(pParse, regKey, pPk->nKeyCol);
  99169. }
  99170. #endif
  99171. assert( regChng==(regStat4+1) );
  99172. sqlite3VdbeAddOp4(v, OP_Function0, 1, regStat4, regTemp,
  99173. (char*)&statPushFuncdef, P4_FUNCDEF);
  99174. sqlite3VdbeChangeP5(v, 2+IsStat34);
  99175. sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v);
  99176. /* Add the entry to the stat1 table. */
  99177. callStatGet(v, regStat4, STAT_GET_STAT1, regStat1);
  99178. assert( "BBB"[0]==SQLITE_AFF_TEXT );
  99179. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
  99180. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
  99181. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
  99182. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  99183. sqlite3VdbeChangeP4(v, -1, (char*)pStat1, P4_TABLE);
  99184. #endif
  99185. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  99186. /* Add the entries to the stat3 or stat4 table. */
  99187. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  99188. {
  99189. int regEq = regStat1;
  99190. int regLt = regStat1+1;
  99191. int regDLt = regStat1+2;
  99192. int regSample = regStat1+3;
  99193. int regCol = regStat1+4;
  99194. int regSampleRowid = regCol + nCol;
  99195. int addrNext;
  99196. int addrIsNull;
  99197. u8 seekOp = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
  99198. pParse->nMem = MAX(pParse->nMem, regCol+nCol);
  99199. addrNext = sqlite3VdbeCurrentAddr(v);
  99200. callStatGet(v, regStat4, STAT_GET_ROWID, regSampleRowid);
  99201. addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid);
  99202. VdbeCoverage(v);
  99203. callStatGet(v, regStat4, STAT_GET_NEQ, regEq);
  99204. callStatGet(v, regStat4, STAT_GET_NLT, regLt);
  99205. callStatGet(v, regStat4, STAT_GET_NDLT, regDLt);
  99206. sqlite3VdbeAddOp4Int(v, seekOp, iTabCur, addrNext, regSampleRowid, 0);
  99207. VdbeCoverage(v);
  99208. #ifdef SQLITE_ENABLE_STAT3
  99209. sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, 0, regSample);
  99210. #else
  99211. for(i=0; i<nCol; i++){
  99212. sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, i, regCol+i);
  99213. }
  99214. sqlite3VdbeAddOp3(v, OP_MakeRecord, regCol, nCol, regSample);
  99215. #endif
  99216. sqlite3VdbeAddOp3(v, OP_MakeRecord, regTabname, 6, regTemp);
  99217. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
  99218. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regTemp, regNewRowid);
  99219. sqlite3VdbeAddOp2(v, OP_Goto, 1, addrNext); /* P1==1 for end-of-loop */
  99220. sqlite3VdbeJumpHere(v, addrIsNull);
  99221. }
  99222. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  99223. /* End of analysis */
  99224. sqlite3VdbeJumpHere(v, addrRewind);
  99225. }
  99226. /* Create a single sqlite_stat1 entry containing NULL as the index
  99227. ** name and the row count as the content.
  99228. */
  99229. if( pOnlyIdx==0 && needTableCnt ){
  99230. VdbeComment((v, "%s", pTab->zName));
  99231. sqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1);
  99232. jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1); VdbeCoverage(v);
  99233. sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
  99234. assert( "BBB"[0]==SQLITE_AFF_TEXT );
  99235. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
  99236. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
  99237. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
  99238. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  99239. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  99240. sqlite3VdbeChangeP4(v, -1, (char*)pStat1, P4_TABLE);
  99241. #endif
  99242. sqlite3VdbeJumpHere(v, jZeroRows);
  99243. }
  99244. }
  99245. /*
  99246. ** Generate code that will cause the most recent index analysis to
  99247. ** be loaded into internal hash tables where is can be used.
  99248. */
  99249. static void loadAnalysis(Parse *pParse, int iDb){
  99250. Vdbe *v = sqlite3GetVdbe(pParse);
  99251. if( v ){
  99252. sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
  99253. }
  99254. }
  99255. /*
  99256. ** Generate code that will do an analysis of an entire database
  99257. */
  99258. static void analyzeDatabase(Parse *pParse, int iDb){
  99259. sqlite3 *db = pParse->db;
  99260. Schema *pSchema = db->aDb[iDb].pSchema; /* Schema of database iDb */
  99261. HashElem *k;
  99262. int iStatCur;
  99263. int iMem;
  99264. int iTab;
  99265. sqlite3BeginWriteOperation(pParse, 0, iDb);
  99266. iStatCur = pParse->nTab;
  99267. pParse->nTab += 3;
  99268. openStatTable(pParse, iDb, iStatCur, 0, 0);
  99269. iMem = pParse->nMem+1;
  99270. iTab = pParse->nTab;
  99271. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  99272. for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
  99273. Table *pTab = (Table*)sqliteHashData(k);
  99274. analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab);
  99275. }
  99276. loadAnalysis(pParse, iDb);
  99277. }
  99278. /*
  99279. ** Generate code that will do an analysis of a single table in
  99280. ** a database. If pOnlyIdx is not NULL then it is a single index
  99281. ** in pTab that should be analyzed.
  99282. */
  99283. static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
  99284. int iDb;
  99285. int iStatCur;
  99286. assert( pTab!=0 );
  99287. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  99288. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  99289. sqlite3BeginWriteOperation(pParse, 0, iDb);
  99290. iStatCur = pParse->nTab;
  99291. pParse->nTab += 3;
  99292. if( pOnlyIdx ){
  99293. openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
  99294. }else{
  99295. openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
  99296. }
  99297. analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur,pParse->nMem+1,pParse->nTab);
  99298. loadAnalysis(pParse, iDb);
  99299. }
  99300. /*
  99301. ** Generate code for the ANALYZE command. The parser calls this routine
  99302. ** when it recognizes an ANALYZE command.
  99303. **
  99304. ** ANALYZE -- 1
  99305. ** ANALYZE <database> -- 2
  99306. ** ANALYZE ?<database>.?<tablename> -- 3
  99307. **
  99308. ** Form 1 causes all indices in all attached databases to be analyzed.
  99309. ** Form 2 analyzes all indices the single database named.
  99310. ** Form 3 analyzes all indices associated with the named table.
  99311. */
  99312. SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
  99313. sqlite3 *db = pParse->db;
  99314. int iDb;
  99315. int i;
  99316. char *z, *zDb;
  99317. Table *pTab;
  99318. Index *pIdx;
  99319. Token *pTableName;
  99320. Vdbe *v;
  99321. /* Read the database schema. If an error occurs, leave an error message
  99322. ** and code in pParse and return NULL. */
  99323. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  99324. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  99325. return;
  99326. }
  99327. assert( pName2!=0 || pName1==0 );
  99328. if( pName1==0 ){
  99329. /* Form 1: Analyze everything */
  99330. for(i=0; i<db->nDb; i++){
  99331. if( i==1 ) continue; /* Do not analyze the TEMP database */
  99332. analyzeDatabase(pParse, i);
  99333. }
  99334. }else if( pName2->n==0 && (iDb = sqlite3FindDb(db, pName1))>=0 ){
  99335. /* Analyze the schema named as the argument */
  99336. analyzeDatabase(pParse, iDb);
  99337. }else{
  99338. /* Form 3: Analyze the table or index named as an argument */
  99339. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
  99340. if( iDb>=0 ){
  99341. zDb = pName2->n ? db->aDb[iDb].zDbSName : 0;
  99342. z = sqlite3NameFromToken(db, pTableName);
  99343. if( z ){
  99344. if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
  99345. analyzeTable(pParse, pIdx->pTable, pIdx);
  99346. }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
  99347. analyzeTable(pParse, pTab, 0);
  99348. }
  99349. sqlite3DbFree(db, z);
  99350. }
  99351. }
  99352. }
  99353. if( db->nSqlExec==0 && (v = sqlite3GetVdbe(pParse))!=0 ){
  99354. sqlite3VdbeAddOp0(v, OP_Expire);
  99355. }
  99356. }
  99357. /*
  99358. ** Used to pass information from the analyzer reader through to the
  99359. ** callback routine.
  99360. */
  99361. typedef struct analysisInfo analysisInfo;
  99362. struct analysisInfo {
  99363. sqlite3 *db;
  99364. const char *zDatabase;
  99365. };
  99366. /*
  99367. ** The first argument points to a nul-terminated string containing a
  99368. ** list of space separated integers. Read the first nOut of these into
  99369. ** the array aOut[].
  99370. */
  99371. static void decodeIntArray(
  99372. char *zIntArray, /* String containing int array to decode */
  99373. int nOut, /* Number of slots in aOut[] */
  99374. tRowcnt *aOut, /* Store integers here */
  99375. LogEst *aLog, /* Or, if aOut==0, here */
  99376. Index *pIndex /* Handle extra flags for this index, if not NULL */
  99377. ){
  99378. char *z = zIntArray;
  99379. int c;
  99380. int i;
  99381. tRowcnt v;
  99382. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  99383. if( z==0 ) z = "";
  99384. #else
  99385. assert( z!=0 );
  99386. #endif
  99387. for(i=0; *z && i<nOut; i++){
  99388. v = 0;
  99389. while( (c=z[0])>='0' && c<='9' ){
  99390. v = v*10 + c - '0';
  99391. z++;
  99392. }
  99393. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  99394. if( aOut ) aOut[i] = v;
  99395. if( aLog ) aLog[i] = sqlite3LogEst(v);
  99396. #else
  99397. assert( aOut==0 );
  99398. UNUSED_PARAMETER(aOut);
  99399. assert( aLog!=0 );
  99400. aLog[i] = sqlite3LogEst(v);
  99401. #endif
  99402. if( *z==' ' ) z++;
  99403. }
  99404. #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
  99405. assert( pIndex!=0 ); {
  99406. #else
  99407. if( pIndex ){
  99408. #endif
  99409. pIndex->bUnordered = 0;
  99410. pIndex->noSkipScan = 0;
  99411. while( z[0] ){
  99412. if( sqlite3_strglob("unordered*", z)==0 ){
  99413. pIndex->bUnordered = 1;
  99414. }else if( sqlite3_strglob("sz=[0-9]*", z)==0 ){
  99415. pIndex->szIdxRow = sqlite3LogEst(sqlite3Atoi(z+3));
  99416. }else if( sqlite3_strglob("noskipscan*", z)==0 ){
  99417. pIndex->noSkipScan = 1;
  99418. }
  99419. #ifdef SQLITE_ENABLE_COSTMULT
  99420. else if( sqlite3_strglob("costmult=[0-9]*",z)==0 ){
  99421. pIndex->pTable->costMult = sqlite3LogEst(sqlite3Atoi(z+9));
  99422. }
  99423. #endif
  99424. while( z[0]!=0 && z[0]!=' ' ) z++;
  99425. while( z[0]==' ' ) z++;
  99426. }
  99427. }
  99428. }
  99429. /*
  99430. ** This callback is invoked once for each index when reading the
  99431. ** sqlite_stat1 table.
  99432. **
  99433. ** argv[0] = name of the table
  99434. ** argv[1] = name of the index (might be NULL)
  99435. ** argv[2] = results of analysis - on integer for each column
  99436. **
  99437. ** Entries for which argv[1]==NULL simply record the number of rows in
  99438. ** the table.
  99439. */
  99440. static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
  99441. analysisInfo *pInfo = (analysisInfo*)pData;
  99442. Index *pIndex;
  99443. Table *pTable;
  99444. const char *z;
  99445. assert( argc==3 );
  99446. UNUSED_PARAMETER2(NotUsed, argc);
  99447. if( argv==0 || argv[0]==0 || argv[2]==0 ){
  99448. return 0;
  99449. }
  99450. pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
  99451. if( pTable==0 ){
  99452. return 0;
  99453. }
  99454. if( argv[1]==0 ){
  99455. pIndex = 0;
  99456. }else if( sqlite3_stricmp(argv[0],argv[1])==0 ){
  99457. pIndex = sqlite3PrimaryKeyIndex(pTable);
  99458. }else{
  99459. pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
  99460. }
  99461. z = argv[2];
  99462. if( pIndex ){
  99463. tRowcnt *aiRowEst = 0;
  99464. int nCol = pIndex->nKeyCol+1;
  99465. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  99466. /* Index.aiRowEst may already be set here if there are duplicate
  99467. ** sqlite_stat1 entries for this index. In that case just clobber
  99468. ** the old data with the new instead of allocating a new array. */
  99469. if( pIndex->aiRowEst==0 ){
  99470. pIndex->aiRowEst = (tRowcnt*)sqlite3MallocZero(sizeof(tRowcnt) * nCol);
  99471. if( pIndex->aiRowEst==0 ) sqlite3OomFault(pInfo->db);
  99472. }
  99473. aiRowEst = pIndex->aiRowEst;
  99474. #endif
  99475. pIndex->bUnordered = 0;
  99476. decodeIntArray((char*)z, nCol, aiRowEst, pIndex->aiRowLogEst, pIndex);
  99477. pIndex->hasStat1 = 1;
  99478. if( pIndex->pPartIdxWhere==0 ){
  99479. pTable->nRowLogEst = pIndex->aiRowLogEst[0];
  99480. pTable->tabFlags |= TF_HasStat1;
  99481. }
  99482. }else{
  99483. Index fakeIdx;
  99484. fakeIdx.szIdxRow = pTable->szTabRow;
  99485. #ifdef SQLITE_ENABLE_COSTMULT
  99486. fakeIdx.pTable = pTable;
  99487. #endif
  99488. decodeIntArray((char*)z, 1, 0, &pTable->nRowLogEst, &fakeIdx);
  99489. pTable->szTabRow = fakeIdx.szIdxRow;
  99490. pTable->tabFlags |= TF_HasStat1;
  99491. }
  99492. return 0;
  99493. }
  99494. /*
  99495. ** If the Index.aSample variable is not NULL, delete the aSample[] array
  99496. ** and its contents.
  99497. */
  99498. SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
  99499. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  99500. if( pIdx->aSample ){
  99501. int j;
  99502. for(j=0; j<pIdx->nSample; j++){
  99503. IndexSample *p = &pIdx->aSample[j];
  99504. sqlite3DbFree(db, p->p);
  99505. }
  99506. sqlite3DbFree(db, pIdx->aSample);
  99507. }
  99508. if( db && db->pnBytesFreed==0 ){
  99509. pIdx->nSample = 0;
  99510. pIdx->aSample = 0;
  99511. }
  99512. #else
  99513. UNUSED_PARAMETER(db);
  99514. UNUSED_PARAMETER(pIdx);
  99515. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  99516. }
  99517. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  99518. /*
  99519. ** Populate the pIdx->aAvgEq[] array based on the samples currently
  99520. ** stored in pIdx->aSample[].
  99521. */
  99522. static void initAvgEq(Index *pIdx){
  99523. if( pIdx ){
  99524. IndexSample *aSample = pIdx->aSample;
  99525. IndexSample *pFinal = &aSample[pIdx->nSample-1];
  99526. int iCol;
  99527. int nCol = 1;
  99528. if( pIdx->nSampleCol>1 ){
  99529. /* If this is stat4 data, then calculate aAvgEq[] values for all
  99530. ** sample columns except the last. The last is always set to 1, as
  99531. ** once the trailing PK fields are considered all index keys are
  99532. ** unique. */
  99533. nCol = pIdx->nSampleCol-1;
  99534. pIdx->aAvgEq[nCol] = 1;
  99535. }
  99536. for(iCol=0; iCol<nCol; iCol++){
  99537. int nSample = pIdx->nSample;
  99538. int i; /* Used to iterate through samples */
  99539. tRowcnt sumEq = 0; /* Sum of the nEq values */
  99540. tRowcnt avgEq = 0;
  99541. tRowcnt nRow; /* Number of rows in index */
  99542. i64 nSum100 = 0; /* Number of terms contributing to sumEq */
  99543. i64 nDist100; /* Number of distinct values in index */
  99544. if( !pIdx->aiRowEst || iCol>=pIdx->nKeyCol || pIdx->aiRowEst[iCol+1]==0 ){
  99545. nRow = pFinal->anLt[iCol];
  99546. nDist100 = (i64)100 * pFinal->anDLt[iCol];
  99547. nSample--;
  99548. }else{
  99549. nRow = pIdx->aiRowEst[0];
  99550. nDist100 = ((i64)100 * pIdx->aiRowEst[0]) / pIdx->aiRowEst[iCol+1];
  99551. }
  99552. pIdx->nRowEst0 = nRow;
  99553. /* Set nSum to the number of distinct (iCol+1) field prefixes that
  99554. ** occur in the stat4 table for this index. Set sumEq to the sum of
  99555. ** the nEq values for column iCol for the same set (adding the value
  99556. ** only once where there exist duplicate prefixes). */
  99557. for(i=0; i<nSample; i++){
  99558. if( i==(pIdx->nSample-1)
  99559. || aSample[i].anDLt[iCol]!=aSample[i+1].anDLt[iCol]
  99560. ){
  99561. sumEq += aSample[i].anEq[iCol];
  99562. nSum100 += 100;
  99563. }
  99564. }
  99565. if( nDist100>nSum100 && sumEq<nRow ){
  99566. avgEq = ((i64)100 * (nRow - sumEq))/(nDist100 - nSum100);
  99567. }
  99568. if( avgEq==0 ) avgEq = 1;
  99569. pIdx->aAvgEq[iCol] = avgEq;
  99570. }
  99571. }
  99572. }
  99573. /*
  99574. ** Look up an index by name. Or, if the name of a WITHOUT ROWID table
  99575. ** is supplied instead, find the PRIMARY KEY index for that table.
  99576. */
  99577. static Index *findIndexOrPrimaryKey(
  99578. sqlite3 *db,
  99579. const char *zName,
  99580. const char *zDb
  99581. ){
  99582. Index *pIdx = sqlite3FindIndex(db, zName, zDb);
  99583. if( pIdx==0 ){
  99584. Table *pTab = sqlite3FindTable(db, zName, zDb);
  99585. if( pTab && !HasRowid(pTab) ) pIdx = sqlite3PrimaryKeyIndex(pTab);
  99586. }
  99587. return pIdx;
  99588. }
  99589. /*
  99590. ** Load the content from either the sqlite_stat4 or sqlite_stat3 table
  99591. ** into the relevant Index.aSample[] arrays.
  99592. **
  99593. ** Arguments zSql1 and zSql2 must point to SQL statements that return
  99594. ** data equivalent to the following (statements are different for stat3,
  99595. ** see the caller of this function for details):
  99596. **
  99597. ** zSql1: SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx
  99598. ** zSql2: SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4
  99599. **
  99600. ** where %Q is replaced with the database name before the SQL is executed.
  99601. */
  99602. static int loadStatTbl(
  99603. sqlite3 *db, /* Database handle */
  99604. int bStat3, /* Assume single column records only */
  99605. const char *zSql1, /* SQL statement 1 (see above) */
  99606. const char *zSql2, /* SQL statement 2 (see above) */
  99607. const char *zDb /* Database name (e.g. "main") */
  99608. ){
  99609. int rc; /* Result codes from subroutines */
  99610. sqlite3_stmt *pStmt = 0; /* An SQL statement being run */
  99611. char *zSql; /* Text of the SQL statement */
  99612. Index *pPrevIdx = 0; /* Previous index in the loop */
  99613. IndexSample *pSample; /* A slot in pIdx->aSample[] */
  99614. assert( db->lookaside.bDisable );
  99615. zSql = sqlite3MPrintf(db, zSql1, zDb);
  99616. if( !zSql ){
  99617. return SQLITE_NOMEM_BKPT;
  99618. }
  99619. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  99620. sqlite3DbFree(db, zSql);
  99621. if( rc ) return rc;
  99622. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  99623. int nIdxCol = 1; /* Number of columns in stat4 records */
  99624. char *zIndex; /* Index name */
  99625. Index *pIdx; /* Pointer to the index object */
  99626. int nSample; /* Number of samples */
  99627. int nByte; /* Bytes of space required */
  99628. int i; /* Bytes of space required */
  99629. tRowcnt *pSpace;
  99630. zIndex = (char *)sqlite3_column_text(pStmt, 0);
  99631. if( zIndex==0 ) continue;
  99632. nSample = sqlite3_column_int(pStmt, 1);
  99633. pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
  99634. assert( pIdx==0 || bStat3 || pIdx->nSample==0 );
  99635. /* Index.nSample is non-zero at this point if data has already been
  99636. ** loaded from the stat4 table. In this case ignore stat3 data. */
  99637. if( pIdx==0 || pIdx->nSample ) continue;
  99638. if( bStat3==0 ){
  99639. assert( !HasRowid(pIdx->pTable) || pIdx->nColumn==pIdx->nKeyCol+1 );
  99640. if( !HasRowid(pIdx->pTable) && IsPrimaryKeyIndex(pIdx) ){
  99641. nIdxCol = pIdx->nKeyCol;
  99642. }else{
  99643. nIdxCol = pIdx->nColumn;
  99644. }
  99645. }
  99646. pIdx->nSampleCol = nIdxCol;
  99647. nByte = sizeof(IndexSample) * nSample;
  99648. nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample;
  99649. nByte += nIdxCol * sizeof(tRowcnt); /* Space for Index.aAvgEq[] */
  99650. pIdx->aSample = sqlite3DbMallocZero(db, nByte);
  99651. if( pIdx->aSample==0 ){
  99652. sqlite3_finalize(pStmt);
  99653. return SQLITE_NOMEM_BKPT;
  99654. }
  99655. pSpace = (tRowcnt*)&pIdx->aSample[nSample];
  99656. pIdx->aAvgEq = pSpace; pSpace += nIdxCol;
  99657. for(i=0; i<nSample; i++){
  99658. pIdx->aSample[i].anEq = pSpace; pSpace += nIdxCol;
  99659. pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol;
  99660. pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol;
  99661. }
  99662. assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) );
  99663. }
  99664. rc = sqlite3_finalize(pStmt);
  99665. if( rc ) return rc;
  99666. zSql = sqlite3MPrintf(db, zSql2, zDb);
  99667. if( !zSql ){
  99668. return SQLITE_NOMEM_BKPT;
  99669. }
  99670. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  99671. sqlite3DbFree(db, zSql);
  99672. if( rc ) return rc;
  99673. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  99674. char *zIndex; /* Index name */
  99675. Index *pIdx; /* Pointer to the index object */
  99676. int nCol = 1; /* Number of columns in index */
  99677. zIndex = (char *)sqlite3_column_text(pStmt, 0);
  99678. if( zIndex==0 ) continue;
  99679. pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
  99680. if( pIdx==0 ) continue;
  99681. /* This next condition is true if data has already been loaded from
  99682. ** the sqlite_stat4 table. In this case ignore stat3 data. */
  99683. nCol = pIdx->nSampleCol;
  99684. if( bStat3 && nCol>1 ) continue;
  99685. if( pIdx!=pPrevIdx ){
  99686. initAvgEq(pPrevIdx);
  99687. pPrevIdx = pIdx;
  99688. }
  99689. pSample = &pIdx->aSample[pIdx->nSample];
  99690. decodeIntArray((char*)sqlite3_column_text(pStmt,1),nCol,pSample->anEq,0,0);
  99691. decodeIntArray((char*)sqlite3_column_text(pStmt,2),nCol,pSample->anLt,0,0);
  99692. decodeIntArray((char*)sqlite3_column_text(pStmt,3),nCol,pSample->anDLt,0,0);
  99693. /* Take a copy of the sample. Add two 0x00 bytes the end of the buffer.
  99694. ** This is in case the sample record is corrupted. In that case, the
  99695. ** sqlite3VdbeRecordCompare() may read up to two varints past the
  99696. ** end of the allocated buffer before it realizes it is dealing with
  99697. ** a corrupt record. Adding the two 0x00 bytes prevents this from causing
  99698. ** a buffer overread. */
  99699. pSample->n = sqlite3_column_bytes(pStmt, 4);
  99700. pSample->p = sqlite3DbMallocZero(db, pSample->n + 2);
  99701. if( pSample->p==0 ){
  99702. sqlite3_finalize(pStmt);
  99703. return SQLITE_NOMEM_BKPT;
  99704. }
  99705. if( pSample->n ){
  99706. memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n);
  99707. }
  99708. pIdx->nSample++;
  99709. }
  99710. rc = sqlite3_finalize(pStmt);
  99711. if( rc==SQLITE_OK ) initAvgEq(pPrevIdx);
  99712. return rc;
  99713. }
  99714. /*
  99715. ** Load content from the sqlite_stat4 and sqlite_stat3 tables into
  99716. ** the Index.aSample[] arrays of all indices.
  99717. */
  99718. static int loadStat4(sqlite3 *db, const char *zDb){
  99719. int rc = SQLITE_OK; /* Result codes from subroutines */
  99720. assert( db->lookaside.bDisable );
  99721. if( sqlite3FindTable(db, "sqlite_stat4", zDb) ){
  99722. rc = loadStatTbl(db, 0,
  99723. "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx",
  99724. "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4",
  99725. zDb
  99726. );
  99727. }
  99728. if( rc==SQLITE_OK && sqlite3FindTable(db, "sqlite_stat3", zDb) ){
  99729. rc = loadStatTbl(db, 1,
  99730. "SELECT idx,count(*) FROM %Q.sqlite_stat3 GROUP BY idx",
  99731. "SELECT idx,neq,nlt,ndlt,sqlite_record(sample) FROM %Q.sqlite_stat3",
  99732. zDb
  99733. );
  99734. }
  99735. return rc;
  99736. }
  99737. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  99738. /*
  99739. ** Load the content of the sqlite_stat1 and sqlite_stat3/4 tables. The
  99740. ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
  99741. ** arrays. The contents of sqlite_stat3/4 are used to populate the
  99742. ** Index.aSample[] arrays.
  99743. **
  99744. ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
  99745. ** is returned. In this case, even if SQLITE_ENABLE_STAT3/4 was defined
  99746. ** during compilation and the sqlite_stat3/4 table is present, no data is
  99747. ** read from it.
  99748. **
  99749. ** If SQLITE_ENABLE_STAT3/4 was defined during compilation and the
  99750. ** sqlite_stat4 table is not present in the database, SQLITE_ERROR is
  99751. ** returned. However, in this case, data is read from the sqlite_stat1
  99752. ** table (if it is present) before returning.
  99753. **
  99754. ** If an OOM error occurs, this function always sets db->mallocFailed.
  99755. ** This means if the caller does not care about other errors, the return
  99756. ** code may be ignored.
  99757. */
  99758. SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
  99759. analysisInfo sInfo;
  99760. HashElem *i;
  99761. char *zSql;
  99762. int rc = SQLITE_OK;
  99763. Schema *pSchema = db->aDb[iDb].pSchema;
  99764. assert( iDb>=0 && iDb<db->nDb );
  99765. assert( db->aDb[iDb].pBt!=0 );
  99766. /* Clear any prior statistics */
  99767. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  99768. for(i=sqliteHashFirst(&pSchema->tblHash); i; i=sqliteHashNext(i)){
  99769. Table *pTab = sqliteHashData(i);
  99770. pTab->tabFlags &= ~TF_HasStat1;
  99771. }
  99772. for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
  99773. Index *pIdx = sqliteHashData(i);
  99774. pIdx->hasStat1 = 0;
  99775. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  99776. sqlite3DeleteIndexSamples(db, pIdx);
  99777. pIdx->aSample = 0;
  99778. #endif
  99779. }
  99780. /* Load new statistics out of the sqlite_stat1 table */
  99781. sInfo.db = db;
  99782. sInfo.zDatabase = db->aDb[iDb].zDbSName;
  99783. if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)!=0 ){
  99784. zSql = sqlite3MPrintf(db,
  99785. "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
  99786. if( zSql==0 ){
  99787. rc = SQLITE_NOMEM_BKPT;
  99788. }else{
  99789. rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
  99790. sqlite3DbFree(db, zSql);
  99791. }
  99792. }
  99793. /* Set appropriate defaults on all indexes not in the sqlite_stat1 table */
  99794. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  99795. for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
  99796. Index *pIdx = sqliteHashData(i);
  99797. if( !pIdx->hasStat1 ) sqlite3DefaultRowEst(pIdx);
  99798. }
  99799. /* Load the statistics from the sqlite_stat4 table. */
  99800. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  99801. if( rc==SQLITE_OK ){
  99802. db->lookaside.bDisable++;
  99803. rc = loadStat4(db, sInfo.zDatabase);
  99804. db->lookaside.bDisable--;
  99805. }
  99806. for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
  99807. Index *pIdx = sqliteHashData(i);
  99808. sqlite3_free(pIdx->aiRowEst);
  99809. pIdx->aiRowEst = 0;
  99810. }
  99811. #endif
  99812. if( rc==SQLITE_NOMEM ){
  99813. sqlite3OomFault(db);
  99814. }
  99815. return rc;
  99816. }
  99817. #endif /* SQLITE_OMIT_ANALYZE */
  99818. /************** End of analyze.c *********************************************/
  99819. /************** Begin file attach.c ******************************************/
  99820. /*
  99821. ** 2003 April 6
  99822. **
  99823. ** The author disclaims copyright to this source code. In place of
  99824. ** a legal notice, here is a blessing:
  99825. **
  99826. ** May you do good and not evil.
  99827. ** May you find forgiveness for yourself and forgive others.
  99828. ** May you share freely, never taking more than you give.
  99829. **
  99830. *************************************************************************
  99831. ** This file contains code used to implement the ATTACH and DETACH commands.
  99832. */
  99833. /* #include "sqliteInt.h" */
  99834. #ifndef SQLITE_OMIT_ATTACH
  99835. /*
  99836. ** Resolve an expression that was part of an ATTACH or DETACH statement. This
  99837. ** is slightly different from resolving a normal SQL expression, because simple
  99838. ** identifiers are treated as strings, not possible column names or aliases.
  99839. **
  99840. ** i.e. if the parser sees:
  99841. **
  99842. ** ATTACH DATABASE abc AS def
  99843. **
  99844. ** it treats the two expressions as literal strings 'abc' and 'def' instead of
  99845. ** looking for columns of the same name.
  99846. **
  99847. ** This only applies to the root node of pExpr, so the statement:
  99848. **
  99849. ** ATTACH DATABASE abc||def AS 'db2'
  99850. **
  99851. ** will fail because neither abc or def can be resolved.
  99852. */
  99853. static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
  99854. {
  99855. int rc = SQLITE_OK;
  99856. if( pExpr ){
  99857. if( pExpr->op!=TK_ID ){
  99858. rc = sqlite3ResolveExprNames(pName, pExpr);
  99859. }else{
  99860. pExpr->op = TK_STRING;
  99861. }
  99862. }
  99863. return rc;
  99864. }
  99865. /*
  99866. ** An SQL user-function registered to do the work of an ATTACH statement. The
  99867. ** three arguments to the function come directly from an attach statement:
  99868. **
  99869. ** ATTACH DATABASE x AS y KEY z
  99870. **
  99871. ** SELECT sqlite_attach(x, y, z)
  99872. **
  99873. ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
  99874. ** third argument.
  99875. **
  99876. ** If the db->init.reopenMemdb flags is set, then instead of attaching a
  99877. ** new database, close the database on db->init.iDb and reopen it as an
  99878. ** empty MemDB.
  99879. */
  99880. static void attachFunc(
  99881. sqlite3_context *context,
  99882. int NotUsed,
  99883. sqlite3_value **argv
  99884. ){
  99885. int i;
  99886. int rc = 0;
  99887. sqlite3 *db = sqlite3_context_db_handle(context);
  99888. const char *zName;
  99889. const char *zFile;
  99890. char *zPath = 0;
  99891. char *zErr = 0;
  99892. unsigned int flags;
  99893. Db *aNew; /* New array of Db pointers */
  99894. Db *pNew; /* Db object for the newly attached database */
  99895. char *zErrDyn = 0;
  99896. sqlite3_vfs *pVfs;
  99897. UNUSED_PARAMETER(NotUsed);
  99898. zFile = (const char *)sqlite3_value_text(argv[0]);
  99899. zName = (const char *)sqlite3_value_text(argv[1]);
  99900. if( zFile==0 ) zFile = "";
  99901. if( zName==0 ) zName = "";
  99902. #ifdef SQLITE_ENABLE_DESERIALIZE
  99903. # define REOPEN_AS_MEMDB(db) (db->init.reopenMemdb)
  99904. #else
  99905. # define REOPEN_AS_MEMDB(db) (0)
  99906. #endif
  99907. if( REOPEN_AS_MEMDB(db) ){
  99908. /* This is not a real ATTACH. Instead, this routine is being called
  99909. ** from sqlite3_deserialize() to close database db->init.iDb and
  99910. ** reopen it as a MemDB */
  99911. pVfs = sqlite3_vfs_find("memdb");
  99912. if( pVfs==0 ) return;
  99913. pNew = &db->aDb[db->init.iDb];
  99914. if( pNew->pBt ) sqlite3BtreeClose(pNew->pBt);
  99915. pNew->pBt = 0;
  99916. pNew->pSchema = 0;
  99917. rc = sqlite3BtreeOpen(pVfs, "x\0", db, &pNew->pBt, 0, SQLITE_OPEN_MAIN_DB);
  99918. }else{
  99919. /* This is a real ATTACH
  99920. **
  99921. ** Check for the following errors:
  99922. **
  99923. ** * Too many attached databases,
  99924. ** * Transaction currently open
  99925. ** * Specified database name already being used.
  99926. */
  99927. if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
  99928. zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
  99929. db->aLimit[SQLITE_LIMIT_ATTACHED]
  99930. );
  99931. goto attach_error;
  99932. }
  99933. for(i=0; i<db->nDb; i++){
  99934. char *z = db->aDb[i].zDbSName;
  99935. assert( z && zName );
  99936. if( sqlite3StrICmp(z, zName)==0 ){
  99937. zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
  99938. goto attach_error;
  99939. }
  99940. }
  99941. /* Allocate the new entry in the db->aDb[] array and initialize the schema
  99942. ** hash tables.
  99943. */
  99944. if( db->aDb==db->aDbStatic ){
  99945. aNew = sqlite3DbMallocRawNN(db, sizeof(db->aDb[0])*3 );
  99946. if( aNew==0 ) return;
  99947. memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
  99948. }else{
  99949. aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
  99950. if( aNew==0 ) return;
  99951. }
  99952. db->aDb = aNew;
  99953. pNew = &db->aDb[db->nDb];
  99954. memset(pNew, 0, sizeof(*pNew));
  99955. /* Open the database file. If the btree is successfully opened, use
  99956. ** it to obtain the database schema. At this point the schema may
  99957. ** or may not be initialized.
  99958. */
  99959. flags = db->openFlags;
  99960. rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
  99961. if( rc!=SQLITE_OK ){
  99962. if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
  99963. sqlite3_result_error(context, zErr, -1);
  99964. sqlite3_free(zErr);
  99965. return;
  99966. }
  99967. assert( pVfs );
  99968. flags |= SQLITE_OPEN_MAIN_DB;
  99969. rc = sqlite3BtreeOpen(pVfs, zPath, db, &pNew->pBt, 0, flags);
  99970. db->nDb++;
  99971. pNew->zDbSName = sqlite3DbStrDup(db, zName);
  99972. }
  99973. db->noSharedCache = 0;
  99974. if( rc==SQLITE_CONSTRAINT ){
  99975. rc = SQLITE_ERROR;
  99976. zErrDyn = sqlite3MPrintf(db, "database is already attached");
  99977. }else if( rc==SQLITE_OK ){
  99978. Pager *pPager;
  99979. pNew->pSchema = sqlite3SchemaGet(db, pNew->pBt);
  99980. if( !pNew->pSchema ){
  99981. rc = SQLITE_NOMEM_BKPT;
  99982. }else if( pNew->pSchema->file_format && pNew->pSchema->enc!=ENC(db) ){
  99983. zErrDyn = sqlite3MPrintf(db,
  99984. "attached databases must use the same text encoding as main database");
  99985. rc = SQLITE_ERROR;
  99986. }
  99987. sqlite3BtreeEnter(pNew->pBt);
  99988. pPager = sqlite3BtreePager(pNew->pBt);
  99989. sqlite3PagerLockingMode(pPager, db->dfltLockMode);
  99990. sqlite3BtreeSecureDelete(pNew->pBt,
  99991. sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
  99992. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  99993. sqlite3BtreeSetPagerFlags(pNew->pBt,
  99994. PAGER_SYNCHRONOUS_FULL | (db->flags & PAGER_FLAGS_MASK));
  99995. #endif
  99996. sqlite3BtreeLeave(pNew->pBt);
  99997. }
  99998. pNew->safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
  99999. if( rc==SQLITE_OK && pNew->zDbSName==0 ){
  100000. rc = SQLITE_NOMEM_BKPT;
  100001. }
  100002. #ifdef SQLITE_HAS_CODEC
  100003. if( rc==SQLITE_OK ){
  100004. extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
  100005. extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
  100006. int nKey;
  100007. char *zKey;
  100008. int t = sqlite3_value_type(argv[2]);
  100009. switch( t ){
  100010. case SQLITE_INTEGER:
  100011. case SQLITE_FLOAT:
  100012. zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
  100013. rc = SQLITE_ERROR;
  100014. break;
  100015. case SQLITE_TEXT:
  100016. case SQLITE_BLOB:
  100017. nKey = sqlite3_value_bytes(argv[2]);
  100018. zKey = (char *)sqlite3_value_blob(argv[2]);
  100019. rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
  100020. break;
  100021. case SQLITE_NULL:
  100022. /* No key specified. Use the key from URI filename, or if none,
  100023. ** use the key from the main database. */
  100024. if( sqlite3CodecQueryParameters(db, zName, zPath)==0 ){
  100025. sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
  100026. if( nKey || sqlite3BtreeGetOptimalReserve(db->aDb[0].pBt)>0 ){
  100027. rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
  100028. }
  100029. }
  100030. break;
  100031. }
  100032. }
  100033. #endif
  100034. sqlite3_free( zPath );
  100035. /* If the file was opened successfully, read the schema for the new database.
  100036. ** If this fails, or if opening the file failed, then close the file and
  100037. ** remove the entry from the db->aDb[] array. i.e. put everything back the
  100038. ** way we found it.
  100039. */
  100040. if( rc==SQLITE_OK ){
  100041. sqlite3BtreeEnterAll(db);
  100042. db->init.iDb = 0;
  100043. db->mDbFlags &= ~(DBFLAG_SchemaKnownOk);
  100044. if( !REOPEN_AS_MEMDB(db) ){
  100045. rc = sqlite3Init(db, &zErrDyn);
  100046. }
  100047. sqlite3BtreeLeaveAll(db);
  100048. assert( zErrDyn==0 || rc!=SQLITE_OK );
  100049. }
  100050. #ifdef SQLITE_USER_AUTHENTICATION
  100051. if( rc==SQLITE_OK && !REOPEN_AS_MEMDB(db) ){
  100052. u8 newAuth = 0;
  100053. rc = sqlite3UserAuthCheckLogin(db, zName, &newAuth);
  100054. if( newAuth<db->auth.authLevel ){
  100055. rc = SQLITE_AUTH_USER;
  100056. }
  100057. }
  100058. #endif
  100059. if( rc ){
  100060. if( !REOPEN_AS_MEMDB(db) ){
  100061. int iDb = db->nDb - 1;
  100062. assert( iDb>=2 );
  100063. if( db->aDb[iDb].pBt ){
  100064. sqlite3BtreeClose(db->aDb[iDb].pBt);
  100065. db->aDb[iDb].pBt = 0;
  100066. db->aDb[iDb].pSchema = 0;
  100067. }
  100068. sqlite3ResetAllSchemasOfConnection(db);
  100069. db->nDb = iDb;
  100070. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  100071. sqlite3OomFault(db);
  100072. sqlite3DbFree(db, zErrDyn);
  100073. zErrDyn = sqlite3MPrintf(db, "out of memory");
  100074. }else if( zErrDyn==0 ){
  100075. zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
  100076. }
  100077. }
  100078. goto attach_error;
  100079. }
  100080. return;
  100081. attach_error:
  100082. /* Return an error if we get here */
  100083. if( zErrDyn ){
  100084. sqlite3_result_error(context, zErrDyn, -1);
  100085. sqlite3DbFree(db, zErrDyn);
  100086. }
  100087. if( rc ) sqlite3_result_error_code(context, rc);
  100088. }
  100089. /*
  100090. ** An SQL user-function registered to do the work of an DETACH statement. The
  100091. ** three arguments to the function come directly from a detach statement:
  100092. **
  100093. ** DETACH DATABASE x
  100094. **
  100095. ** SELECT sqlite_detach(x)
  100096. */
  100097. static void detachFunc(
  100098. sqlite3_context *context,
  100099. int NotUsed,
  100100. sqlite3_value **argv
  100101. ){
  100102. const char *zName = (const char *)sqlite3_value_text(argv[0]);
  100103. sqlite3 *db = sqlite3_context_db_handle(context);
  100104. int i;
  100105. Db *pDb = 0;
  100106. char zErr[128];
  100107. UNUSED_PARAMETER(NotUsed);
  100108. if( zName==0 ) zName = "";
  100109. for(i=0; i<db->nDb; i++){
  100110. pDb = &db->aDb[i];
  100111. if( pDb->pBt==0 ) continue;
  100112. if( sqlite3StrICmp(pDb->zDbSName, zName)==0 ) break;
  100113. }
  100114. if( i>=db->nDb ){
  100115. sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
  100116. goto detach_error;
  100117. }
  100118. if( i<2 ){
  100119. sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
  100120. goto detach_error;
  100121. }
  100122. if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
  100123. sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
  100124. goto detach_error;
  100125. }
  100126. sqlite3BtreeClose(pDb->pBt);
  100127. pDb->pBt = 0;
  100128. pDb->pSchema = 0;
  100129. sqlite3CollapseDatabaseArray(db);
  100130. return;
  100131. detach_error:
  100132. sqlite3_result_error(context, zErr, -1);
  100133. }
  100134. /*
  100135. ** This procedure generates VDBE code for a single invocation of either the
  100136. ** sqlite_detach() or sqlite_attach() SQL user functions.
  100137. */
  100138. static void codeAttach(
  100139. Parse *pParse, /* The parser context */
  100140. int type, /* Either SQLITE_ATTACH or SQLITE_DETACH */
  100141. FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
  100142. Expr *pAuthArg, /* Expression to pass to authorization callback */
  100143. Expr *pFilename, /* Name of database file */
  100144. Expr *pDbname, /* Name of the database to use internally */
  100145. Expr *pKey /* Database key for encryption extension */
  100146. ){
  100147. int rc;
  100148. NameContext sName;
  100149. Vdbe *v;
  100150. sqlite3* db = pParse->db;
  100151. int regArgs;
  100152. if( pParse->nErr ) goto attach_end;
  100153. memset(&sName, 0, sizeof(NameContext));
  100154. sName.pParse = pParse;
  100155. if(
  100156. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
  100157. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
  100158. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
  100159. ){
  100160. goto attach_end;
  100161. }
  100162. #ifndef SQLITE_OMIT_AUTHORIZATION
  100163. if( pAuthArg ){
  100164. char *zAuthArg;
  100165. if( pAuthArg->op==TK_STRING ){
  100166. zAuthArg = pAuthArg->u.zToken;
  100167. }else{
  100168. zAuthArg = 0;
  100169. }
  100170. rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
  100171. if(rc!=SQLITE_OK ){
  100172. goto attach_end;
  100173. }
  100174. }
  100175. #endif /* SQLITE_OMIT_AUTHORIZATION */
  100176. v = sqlite3GetVdbe(pParse);
  100177. regArgs = sqlite3GetTempRange(pParse, 4);
  100178. sqlite3ExprCode(pParse, pFilename, regArgs);
  100179. sqlite3ExprCode(pParse, pDbname, regArgs+1);
  100180. sqlite3ExprCode(pParse, pKey, regArgs+2);
  100181. assert( v || db->mallocFailed );
  100182. if( v ){
  100183. sqlite3VdbeAddOp4(v, OP_Function0, 0, regArgs+3-pFunc->nArg, regArgs+3,
  100184. (char *)pFunc, P4_FUNCDEF);
  100185. assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
  100186. sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
  100187. /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
  100188. ** statement only). For DETACH, set it to false (expire all existing
  100189. ** statements).
  100190. */
  100191. sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
  100192. }
  100193. attach_end:
  100194. sqlite3ExprDelete(db, pFilename);
  100195. sqlite3ExprDelete(db, pDbname);
  100196. sqlite3ExprDelete(db, pKey);
  100197. }
  100198. /*
  100199. ** Called by the parser to compile a DETACH statement.
  100200. **
  100201. ** DETACH pDbname
  100202. */
  100203. SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
  100204. static const FuncDef detach_func = {
  100205. 1, /* nArg */
  100206. SQLITE_UTF8, /* funcFlags */
  100207. 0, /* pUserData */
  100208. 0, /* pNext */
  100209. detachFunc, /* xSFunc */
  100210. 0, /* xFinalize */
  100211. 0, 0, /* xValue, xInverse */
  100212. "sqlite_detach", /* zName */
  100213. {0}
  100214. };
  100215. codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
  100216. }
  100217. /*
  100218. ** Called by the parser to compile an ATTACH statement.
  100219. **
  100220. ** ATTACH p AS pDbname KEY pKey
  100221. */
  100222. SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
  100223. static const FuncDef attach_func = {
  100224. 3, /* nArg */
  100225. SQLITE_UTF8, /* funcFlags */
  100226. 0, /* pUserData */
  100227. 0, /* pNext */
  100228. attachFunc, /* xSFunc */
  100229. 0, /* xFinalize */
  100230. 0, 0, /* xValue, xInverse */
  100231. "sqlite_attach", /* zName */
  100232. {0}
  100233. };
  100234. codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
  100235. }
  100236. #endif /* SQLITE_OMIT_ATTACH */
  100237. /*
  100238. ** Initialize a DbFixer structure. This routine must be called prior
  100239. ** to passing the structure to one of the sqliteFixAAAA() routines below.
  100240. */
  100241. SQLITE_PRIVATE void sqlite3FixInit(
  100242. DbFixer *pFix, /* The fixer to be initialized */
  100243. Parse *pParse, /* Error messages will be written here */
  100244. int iDb, /* This is the database that must be used */
  100245. const char *zType, /* "view", "trigger", or "index" */
  100246. const Token *pName /* Name of the view, trigger, or index */
  100247. ){
  100248. sqlite3 *db;
  100249. db = pParse->db;
  100250. assert( db->nDb>iDb );
  100251. pFix->pParse = pParse;
  100252. pFix->zDb = db->aDb[iDb].zDbSName;
  100253. pFix->pSchema = db->aDb[iDb].pSchema;
  100254. pFix->zType = zType;
  100255. pFix->pName = pName;
  100256. pFix->bVarOnly = (iDb==1);
  100257. }
  100258. /*
  100259. ** The following set of routines walk through the parse tree and assign
  100260. ** a specific database to all table references where the database name
  100261. ** was left unspecified in the original SQL statement. The pFix structure
  100262. ** must have been initialized by a prior call to sqlite3FixInit().
  100263. **
  100264. ** These routines are used to make sure that an index, trigger, or
  100265. ** view in one database does not refer to objects in a different database.
  100266. ** (Exception: indices, triggers, and views in the TEMP database are
  100267. ** allowed to refer to anything.) If a reference is explicitly made
  100268. ** to an object in a different database, an error message is added to
  100269. ** pParse->zErrMsg and these routines return non-zero. If everything
  100270. ** checks out, these routines return 0.
  100271. */
  100272. SQLITE_PRIVATE int sqlite3FixSrcList(
  100273. DbFixer *pFix, /* Context of the fixation */
  100274. SrcList *pList /* The Source list to check and modify */
  100275. ){
  100276. int i;
  100277. const char *zDb;
  100278. struct SrcList_item *pItem;
  100279. if( NEVER(pList==0) ) return 0;
  100280. zDb = pFix->zDb;
  100281. for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
  100282. if( pFix->bVarOnly==0 ){
  100283. if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){
  100284. sqlite3ErrorMsg(pFix->pParse,
  100285. "%s %T cannot reference objects in database %s",
  100286. pFix->zType, pFix->pName, pItem->zDatabase);
  100287. return 1;
  100288. }
  100289. sqlite3DbFree(pFix->pParse->db, pItem->zDatabase);
  100290. pItem->zDatabase = 0;
  100291. pItem->pSchema = pFix->pSchema;
  100292. }
  100293. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
  100294. if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
  100295. if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
  100296. #endif
  100297. if( pItem->fg.isTabFunc && sqlite3FixExprList(pFix, pItem->u1.pFuncArg) ){
  100298. return 1;
  100299. }
  100300. }
  100301. return 0;
  100302. }
  100303. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
  100304. SQLITE_PRIVATE int sqlite3FixSelect(
  100305. DbFixer *pFix, /* Context of the fixation */
  100306. Select *pSelect /* The SELECT statement to be fixed to one database */
  100307. ){
  100308. while( pSelect ){
  100309. if( sqlite3FixExprList(pFix, pSelect->pEList) ){
  100310. return 1;
  100311. }
  100312. if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
  100313. return 1;
  100314. }
  100315. if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
  100316. return 1;
  100317. }
  100318. if( sqlite3FixExprList(pFix, pSelect->pGroupBy) ){
  100319. return 1;
  100320. }
  100321. if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
  100322. return 1;
  100323. }
  100324. if( sqlite3FixExprList(pFix, pSelect->pOrderBy) ){
  100325. return 1;
  100326. }
  100327. if( sqlite3FixExpr(pFix, pSelect->pLimit) ){
  100328. return 1;
  100329. }
  100330. if( pSelect->pWith ){
  100331. int i;
  100332. for(i=0; i<pSelect->pWith->nCte; i++){
  100333. if( sqlite3FixSelect(pFix, pSelect->pWith->a[i].pSelect) ){
  100334. return 1;
  100335. }
  100336. }
  100337. }
  100338. pSelect = pSelect->pPrior;
  100339. }
  100340. return 0;
  100341. }
  100342. SQLITE_PRIVATE int sqlite3FixExpr(
  100343. DbFixer *pFix, /* Context of the fixation */
  100344. Expr *pExpr /* The expression to be fixed to one database */
  100345. ){
  100346. while( pExpr ){
  100347. if( pExpr->op==TK_VARIABLE ){
  100348. if( pFix->pParse->db->init.busy ){
  100349. pExpr->op = TK_NULL;
  100350. }else{
  100351. sqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType);
  100352. return 1;
  100353. }
  100354. }
  100355. if( ExprHasProperty(pExpr, EP_TokenOnly|EP_Leaf) ) break;
  100356. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  100357. if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
  100358. }else{
  100359. if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
  100360. }
  100361. if( sqlite3FixExpr(pFix, pExpr->pRight) ){
  100362. return 1;
  100363. }
  100364. pExpr = pExpr->pLeft;
  100365. }
  100366. return 0;
  100367. }
  100368. SQLITE_PRIVATE int sqlite3FixExprList(
  100369. DbFixer *pFix, /* Context of the fixation */
  100370. ExprList *pList /* The expression to be fixed to one database */
  100371. ){
  100372. int i;
  100373. struct ExprList_item *pItem;
  100374. if( pList==0 ) return 0;
  100375. for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
  100376. if( sqlite3FixExpr(pFix, pItem->pExpr) ){
  100377. return 1;
  100378. }
  100379. }
  100380. return 0;
  100381. }
  100382. #endif
  100383. #ifndef SQLITE_OMIT_TRIGGER
  100384. SQLITE_PRIVATE int sqlite3FixTriggerStep(
  100385. DbFixer *pFix, /* Context of the fixation */
  100386. TriggerStep *pStep /* The trigger step be fixed to one database */
  100387. ){
  100388. while( pStep ){
  100389. if( sqlite3FixSelect(pFix, pStep->pSelect) ){
  100390. return 1;
  100391. }
  100392. if( sqlite3FixExpr(pFix, pStep->pWhere) ){
  100393. return 1;
  100394. }
  100395. if( sqlite3FixExprList(pFix, pStep->pExprList) ){
  100396. return 1;
  100397. }
  100398. #ifndef SQLITE_OMIT_UPSERT
  100399. if( pStep->pUpsert ){
  100400. Upsert *pUp = pStep->pUpsert;
  100401. if( sqlite3FixExprList(pFix, pUp->pUpsertTarget)
  100402. || sqlite3FixExpr(pFix, pUp->pUpsertTargetWhere)
  100403. || sqlite3FixExprList(pFix, pUp->pUpsertSet)
  100404. || sqlite3FixExpr(pFix, pUp->pUpsertWhere)
  100405. ){
  100406. return 1;
  100407. }
  100408. }
  100409. #endif
  100410. pStep = pStep->pNext;
  100411. }
  100412. return 0;
  100413. }
  100414. #endif
  100415. /************** End of attach.c **********************************************/
  100416. /************** Begin file auth.c ********************************************/
  100417. /*
  100418. ** 2003 January 11
  100419. **
  100420. ** The author disclaims copyright to this source code. In place of
  100421. ** a legal notice, here is a blessing:
  100422. **
  100423. ** May you do good and not evil.
  100424. ** May you find forgiveness for yourself and forgive others.
  100425. ** May you share freely, never taking more than you give.
  100426. **
  100427. *************************************************************************
  100428. ** This file contains code used to implement the sqlite3_set_authorizer()
  100429. ** API. This facility is an optional feature of the library. Embedded
  100430. ** systems that do not need this facility may omit it by recompiling
  100431. ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
  100432. */
  100433. /* #include "sqliteInt.h" */
  100434. /*
  100435. ** All of the code in this file may be omitted by defining a single
  100436. ** macro.
  100437. */
  100438. #ifndef SQLITE_OMIT_AUTHORIZATION
  100439. /*
  100440. ** Set or clear the access authorization function.
  100441. **
  100442. ** The access authorization function is be called during the compilation
  100443. ** phase to verify that the user has read and/or write access permission on
  100444. ** various fields of the database. The first argument to the auth function
  100445. ** is a copy of the 3rd argument to this routine. The second argument
  100446. ** to the auth function is one of these constants:
  100447. **
  100448. ** SQLITE_CREATE_INDEX
  100449. ** SQLITE_CREATE_TABLE
  100450. ** SQLITE_CREATE_TEMP_INDEX
  100451. ** SQLITE_CREATE_TEMP_TABLE
  100452. ** SQLITE_CREATE_TEMP_TRIGGER
  100453. ** SQLITE_CREATE_TEMP_VIEW
  100454. ** SQLITE_CREATE_TRIGGER
  100455. ** SQLITE_CREATE_VIEW
  100456. ** SQLITE_DELETE
  100457. ** SQLITE_DROP_INDEX
  100458. ** SQLITE_DROP_TABLE
  100459. ** SQLITE_DROP_TEMP_INDEX
  100460. ** SQLITE_DROP_TEMP_TABLE
  100461. ** SQLITE_DROP_TEMP_TRIGGER
  100462. ** SQLITE_DROP_TEMP_VIEW
  100463. ** SQLITE_DROP_TRIGGER
  100464. ** SQLITE_DROP_VIEW
  100465. ** SQLITE_INSERT
  100466. ** SQLITE_PRAGMA
  100467. ** SQLITE_READ
  100468. ** SQLITE_SELECT
  100469. ** SQLITE_TRANSACTION
  100470. ** SQLITE_UPDATE
  100471. **
  100472. ** The third and fourth arguments to the auth function are the name of
  100473. ** the table and the column that are being accessed. The auth function
  100474. ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE. If
  100475. ** SQLITE_OK is returned, it means that access is allowed. SQLITE_DENY
  100476. ** means that the SQL statement will never-run - the sqlite3_exec() call
  100477. ** will return with an error. SQLITE_IGNORE means that the SQL statement
  100478. ** should run but attempts to read the specified column will return NULL
  100479. ** and attempts to write the column will be ignored.
  100480. **
  100481. ** Setting the auth function to NULL disables this hook. The default
  100482. ** setting of the auth function is NULL.
  100483. */
  100484. SQLITE_API int sqlite3_set_authorizer(
  100485. sqlite3 *db,
  100486. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  100487. void *pArg
  100488. ){
  100489. #ifdef SQLITE_ENABLE_API_ARMOR
  100490. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  100491. #endif
  100492. sqlite3_mutex_enter(db->mutex);
  100493. db->xAuth = (sqlite3_xauth)xAuth;
  100494. db->pAuthArg = pArg;
  100495. sqlite3ExpirePreparedStatements(db, 0);
  100496. sqlite3_mutex_leave(db->mutex);
  100497. return SQLITE_OK;
  100498. }
  100499. /*
  100500. ** Write an error message into pParse->zErrMsg that explains that the
  100501. ** user-supplied authorization function returned an illegal value.
  100502. */
  100503. static void sqliteAuthBadReturnCode(Parse *pParse){
  100504. sqlite3ErrorMsg(pParse, "authorizer malfunction");
  100505. pParse->rc = SQLITE_ERROR;
  100506. }
  100507. /*
  100508. ** Invoke the authorization callback for permission to read column zCol from
  100509. ** table zTab in database zDb. This function assumes that an authorization
  100510. ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
  100511. **
  100512. ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
  100513. ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
  100514. ** is treated as SQLITE_DENY. In this case an error is left in pParse.
  100515. */
  100516. SQLITE_PRIVATE int sqlite3AuthReadCol(
  100517. Parse *pParse, /* The parser context */
  100518. const char *zTab, /* Table name */
  100519. const char *zCol, /* Column name */
  100520. int iDb /* Index of containing database. */
  100521. ){
  100522. sqlite3 *db = pParse->db; /* Database handle */
  100523. char *zDb = db->aDb[iDb].zDbSName; /* Schema name of attached database */
  100524. int rc; /* Auth callback return code */
  100525. if( db->init.busy ) return SQLITE_OK;
  100526. rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext
  100527. #ifdef SQLITE_USER_AUTHENTICATION
  100528. ,db->auth.zAuthUser
  100529. #endif
  100530. );
  100531. if( rc==SQLITE_DENY ){
  100532. char *z = sqlite3_mprintf("%s.%s", zTab, zCol);
  100533. if( db->nDb>2 || iDb!=0 ) z = sqlite3_mprintf("%s.%z", zDb, z);
  100534. sqlite3ErrorMsg(pParse, "access to %z is prohibited", z);
  100535. pParse->rc = SQLITE_AUTH;
  100536. }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
  100537. sqliteAuthBadReturnCode(pParse);
  100538. }
  100539. return rc;
  100540. }
  100541. /*
  100542. ** The pExpr should be a TK_COLUMN expression. The table referred to
  100543. ** is in pTabList or else it is the NEW or OLD table of a trigger.
  100544. ** Check to see if it is OK to read this particular column.
  100545. **
  100546. ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
  100547. ** instruction into a TK_NULL. If the auth function returns SQLITE_DENY,
  100548. ** then generate an error.
  100549. */
  100550. SQLITE_PRIVATE void sqlite3AuthRead(
  100551. Parse *pParse, /* The parser context */
  100552. Expr *pExpr, /* The expression to check authorization on */
  100553. Schema *pSchema, /* The schema of the expression */
  100554. SrcList *pTabList /* All table that pExpr might refer to */
  100555. ){
  100556. sqlite3 *db = pParse->db;
  100557. Table *pTab = 0; /* The table being read */
  100558. const char *zCol; /* Name of the column of the table */
  100559. int iSrc; /* Index in pTabList->a[] of table being read */
  100560. int iDb; /* The index of the database the expression refers to */
  100561. int iCol; /* Index of column in table */
  100562. assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
  100563. assert( !IN_RENAME_OBJECT || db->xAuth==0 );
  100564. if( db->xAuth==0 ) return;
  100565. iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
  100566. if( iDb<0 ){
  100567. /* An attempt to read a column out of a subquery or other
  100568. ** temporary table. */
  100569. return;
  100570. }
  100571. if( pExpr->op==TK_TRIGGER ){
  100572. pTab = pParse->pTriggerTab;
  100573. }else{
  100574. assert( pTabList );
  100575. for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
  100576. if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
  100577. pTab = pTabList->a[iSrc].pTab;
  100578. break;
  100579. }
  100580. }
  100581. }
  100582. iCol = pExpr->iColumn;
  100583. if( NEVER(pTab==0) ) return;
  100584. if( iCol>=0 ){
  100585. assert( iCol<pTab->nCol );
  100586. zCol = pTab->aCol[iCol].zName;
  100587. }else if( pTab->iPKey>=0 ){
  100588. assert( pTab->iPKey<pTab->nCol );
  100589. zCol = pTab->aCol[pTab->iPKey].zName;
  100590. }else{
  100591. zCol = "ROWID";
  100592. }
  100593. assert( iDb>=0 && iDb<db->nDb );
  100594. if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
  100595. pExpr->op = TK_NULL;
  100596. }
  100597. }
  100598. /*
  100599. ** Do an authorization check using the code and arguments given. Return
  100600. ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY. If SQLITE_DENY
  100601. ** is returned, then the error count and error message in pParse are
  100602. ** modified appropriately.
  100603. */
  100604. SQLITE_PRIVATE int sqlite3AuthCheck(
  100605. Parse *pParse,
  100606. int code,
  100607. const char *zArg1,
  100608. const char *zArg2,
  100609. const char *zArg3
  100610. ){
  100611. sqlite3 *db = pParse->db;
  100612. int rc;
  100613. /* Don't do any authorization checks if the database is initialising
  100614. ** or if the parser is being invoked from within sqlite3_declare_vtab.
  100615. */
  100616. assert( !IN_RENAME_OBJECT || db->xAuth==0 );
  100617. if( db->init.busy || IN_SPECIAL_PARSE ){
  100618. return SQLITE_OK;
  100619. }
  100620. if( db->xAuth==0 ){
  100621. return SQLITE_OK;
  100622. }
  100623. /* EVIDENCE-OF: R-43249-19882 The third through sixth parameters to the
  100624. ** callback are either NULL pointers or zero-terminated strings that
  100625. ** contain additional details about the action to be authorized.
  100626. **
  100627. ** The following testcase() macros show that any of the 3rd through 6th
  100628. ** parameters can be either NULL or a string. */
  100629. testcase( zArg1==0 );
  100630. testcase( zArg2==0 );
  100631. testcase( zArg3==0 );
  100632. testcase( pParse->zAuthContext==0 );
  100633. rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext
  100634. #ifdef SQLITE_USER_AUTHENTICATION
  100635. ,db->auth.zAuthUser
  100636. #endif
  100637. );
  100638. if( rc==SQLITE_DENY ){
  100639. sqlite3ErrorMsg(pParse, "not authorized");
  100640. pParse->rc = SQLITE_AUTH;
  100641. }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
  100642. rc = SQLITE_DENY;
  100643. sqliteAuthBadReturnCode(pParse);
  100644. }
  100645. return rc;
  100646. }
  100647. /*
  100648. ** Push an authorization context. After this routine is called, the
  100649. ** zArg3 argument to authorization callbacks will be zContext until
  100650. ** popped. Or if pParse==0, this routine is a no-op.
  100651. */
  100652. SQLITE_PRIVATE void sqlite3AuthContextPush(
  100653. Parse *pParse,
  100654. AuthContext *pContext,
  100655. const char *zContext
  100656. ){
  100657. assert( pParse );
  100658. pContext->pParse = pParse;
  100659. pContext->zAuthContext = pParse->zAuthContext;
  100660. pParse->zAuthContext = zContext;
  100661. }
  100662. /*
  100663. ** Pop an authorization context that was previously pushed
  100664. ** by sqlite3AuthContextPush
  100665. */
  100666. SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
  100667. if( pContext->pParse ){
  100668. pContext->pParse->zAuthContext = pContext->zAuthContext;
  100669. pContext->pParse = 0;
  100670. }
  100671. }
  100672. #endif /* SQLITE_OMIT_AUTHORIZATION */
  100673. /************** End of auth.c ************************************************/
  100674. /************** Begin file build.c *******************************************/
  100675. /*
  100676. ** 2001 September 15
  100677. **
  100678. ** The author disclaims copyright to this source code. In place of
  100679. ** a legal notice, here is a blessing:
  100680. **
  100681. ** May you do good and not evil.
  100682. ** May you find forgiveness for yourself and forgive others.
  100683. ** May you share freely, never taking more than you give.
  100684. **
  100685. *************************************************************************
  100686. ** This file contains C code routines that are called by the SQLite parser
  100687. ** when syntax rules are reduced. The routines in this file handle the
  100688. ** following kinds of SQL syntax:
  100689. **
  100690. ** CREATE TABLE
  100691. ** DROP TABLE
  100692. ** CREATE INDEX
  100693. ** DROP INDEX
  100694. ** creating ID lists
  100695. ** BEGIN TRANSACTION
  100696. ** COMMIT
  100697. ** ROLLBACK
  100698. */
  100699. /* #include "sqliteInt.h" */
  100700. #ifndef SQLITE_OMIT_SHARED_CACHE
  100701. /*
  100702. ** The TableLock structure is only used by the sqlite3TableLock() and
  100703. ** codeTableLocks() functions.
  100704. */
  100705. struct TableLock {
  100706. int iDb; /* The database containing the table to be locked */
  100707. int iTab; /* The root page of the table to be locked */
  100708. u8 isWriteLock; /* True for write lock. False for a read lock */
  100709. const char *zLockName; /* Name of the table */
  100710. };
  100711. /*
  100712. ** Record the fact that we want to lock a table at run-time.
  100713. **
  100714. ** The table to be locked has root page iTab and is found in database iDb.
  100715. ** A read or a write lock can be taken depending on isWritelock.
  100716. **
  100717. ** This routine just records the fact that the lock is desired. The
  100718. ** code to make the lock occur is generated by a later call to
  100719. ** codeTableLocks() which occurs during sqlite3FinishCoding().
  100720. */
  100721. SQLITE_PRIVATE void sqlite3TableLock(
  100722. Parse *pParse, /* Parsing context */
  100723. int iDb, /* Index of the database containing the table to lock */
  100724. int iTab, /* Root page number of the table to be locked */
  100725. u8 isWriteLock, /* True for a write lock */
  100726. const char *zName /* Name of the table to be locked */
  100727. ){
  100728. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  100729. int i;
  100730. int nBytes;
  100731. TableLock *p;
  100732. assert( iDb>=0 );
  100733. if( iDb==1 ) return;
  100734. if( !sqlite3BtreeSharable(pParse->db->aDb[iDb].pBt) ) return;
  100735. for(i=0; i<pToplevel->nTableLock; i++){
  100736. p = &pToplevel->aTableLock[i];
  100737. if( p->iDb==iDb && p->iTab==iTab ){
  100738. p->isWriteLock = (p->isWriteLock || isWriteLock);
  100739. return;
  100740. }
  100741. }
  100742. nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
  100743. pToplevel->aTableLock =
  100744. sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
  100745. if( pToplevel->aTableLock ){
  100746. p = &pToplevel->aTableLock[pToplevel->nTableLock++];
  100747. p->iDb = iDb;
  100748. p->iTab = iTab;
  100749. p->isWriteLock = isWriteLock;
  100750. p->zLockName = zName;
  100751. }else{
  100752. pToplevel->nTableLock = 0;
  100753. sqlite3OomFault(pToplevel->db);
  100754. }
  100755. }
  100756. /*
  100757. ** Code an OP_TableLock instruction for each table locked by the
  100758. ** statement (configured by calls to sqlite3TableLock()).
  100759. */
  100760. static void codeTableLocks(Parse *pParse){
  100761. int i;
  100762. Vdbe *pVdbe;
  100763. pVdbe = sqlite3GetVdbe(pParse);
  100764. assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
  100765. for(i=0; i<pParse->nTableLock; i++){
  100766. TableLock *p = &pParse->aTableLock[i];
  100767. int p1 = p->iDb;
  100768. sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
  100769. p->zLockName, P4_STATIC);
  100770. }
  100771. }
  100772. #else
  100773. #define codeTableLocks(x)
  100774. #endif
  100775. /*
  100776. ** Return TRUE if the given yDbMask object is empty - if it contains no
  100777. ** 1 bits. This routine is used by the DbMaskAllZero() and DbMaskNotZero()
  100778. ** macros when SQLITE_MAX_ATTACHED is greater than 30.
  100779. */
  100780. #if SQLITE_MAX_ATTACHED>30
  100781. SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask m){
  100782. int i;
  100783. for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0;
  100784. return 1;
  100785. }
  100786. #endif
  100787. /*
  100788. ** This routine is called after a single SQL statement has been
  100789. ** parsed and a VDBE program to execute that statement has been
  100790. ** prepared. This routine puts the finishing touches on the
  100791. ** VDBE program and resets the pParse structure for the next
  100792. ** parse.
  100793. **
  100794. ** Note that if an error occurred, it might be the case that
  100795. ** no VDBE code was generated.
  100796. */
  100797. SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
  100798. sqlite3 *db;
  100799. Vdbe *v;
  100800. assert( pParse->pToplevel==0 );
  100801. db = pParse->db;
  100802. if( pParse->nested ) return;
  100803. if( db->mallocFailed || pParse->nErr ){
  100804. if( pParse->rc==SQLITE_OK ) pParse->rc = SQLITE_ERROR;
  100805. return;
  100806. }
  100807. /* Begin by generating some termination code at the end of the
  100808. ** vdbe program
  100809. */
  100810. v = sqlite3GetVdbe(pParse);
  100811. assert( !pParse->isMultiWrite
  100812. || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
  100813. if( v ){
  100814. sqlite3VdbeAddOp0(v, OP_Halt);
  100815. #if SQLITE_USER_AUTHENTICATION
  100816. if( pParse->nTableLock>0 && db->init.busy==0 ){
  100817. sqlite3UserAuthInit(db);
  100818. if( db->auth.authLevel<UAUTH_User ){
  100819. sqlite3ErrorMsg(pParse, "user not authenticated");
  100820. pParse->rc = SQLITE_AUTH_USER;
  100821. return;
  100822. }
  100823. }
  100824. #endif
  100825. /* The cookie mask contains one bit for each database file open.
  100826. ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
  100827. ** set for each database that is used. Generate code to start a
  100828. ** transaction on each used database and to verify the schema cookie
  100829. ** on each used database.
  100830. */
  100831. if( db->mallocFailed==0
  100832. && (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr)
  100833. ){
  100834. int iDb, i;
  100835. assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );
  100836. sqlite3VdbeJumpHere(v, 0);
  100837. for(iDb=0; iDb<db->nDb; iDb++){
  100838. Schema *pSchema;
  100839. if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue;
  100840. sqlite3VdbeUsesBtree(v, iDb);
  100841. pSchema = db->aDb[iDb].pSchema;
  100842. sqlite3VdbeAddOp4Int(v,
  100843. OP_Transaction, /* Opcode */
  100844. iDb, /* P1 */
  100845. DbMaskTest(pParse->writeMask,iDb), /* P2 */
  100846. pSchema->schema_cookie, /* P3 */
  100847. pSchema->iGeneration /* P4 */
  100848. );
  100849. if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);
  100850. VdbeComment((v,
  100851. "usesStmtJournal=%d", pParse->mayAbort && pParse->isMultiWrite));
  100852. }
  100853. #ifndef SQLITE_OMIT_VIRTUALTABLE
  100854. for(i=0; i<pParse->nVtabLock; i++){
  100855. char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
  100856. sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
  100857. }
  100858. pParse->nVtabLock = 0;
  100859. #endif
  100860. /* Once all the cookies have been verified and transactions opened,
  100861. ** obtain the required table-locks. This is a no-op unless the
  100862. ** shared-cache feature is enabled.
  100863. */
  100864. codeTableLocks(pParse);
  100865. /* Initialize any AUTOINCREMENT data structures required.
  100866. */
  100867. sqlite3AutoincrementBegin(pParse);
  100868. /* Code constant expressions that where factored out of inner loops */
  100869. if( pParse->pConstExpr ){
  100870. ExprList *pEL = pParse->pConstExpr;
  100871. pParse->okConstFactor = 0;
  100872. for(i=0; i<pEL->nExpr; i++){
  100873. sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
  100874. }
  100875. }
  100876. /* Finally, jump back to the beginning of the executable code. */
  100877. sqlite3VdbeGoto(v, 1);
  100878. }
  100879. }
  100880. /* Get the VDBE program ready for execution
  100881. */
  100882. if( v && pParse->nErr==0 && !db->mallocFailed ){
  100883. /* A minimum of one cursor is required if autoincrement is used
  100884. * See ticket [a696379c1f08866] */
  100885. assert( pParse->pAinc==0 || pParse->nTab>0 );
  100886. sqlite3VdbeMakeReady(v, pParse);
  100887. pParse->rc = SQLITE_DONE;
  100888. }else{
  100889. pParse->rc = SQLITE_ERROR;
  100890. }
  100891. }
  100892. /*
  100893. ** Run the parser and code generator recursively in order to generate
  100894. ** code for the SQL statement given onto the end of the pParse context
  100895. ** currently under construction. When the parser is run recursively
  100896. ** this way, the final OP_Halt is not appended and other initialization
  100897. ** and finalization steps are omitted because those are handling by the
  100898. ** outermost parser.
  100899. **
  100900. ** Not everything is nestable. This facility is designed to permit
  100901. ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
  100902. ** care if you decide to try to use this routine for some other purposes.
  100903. */
  100904. SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
  100905. va_list ap;
  100906. char *zSql;
  100907. char *zErrMsg = 0;
  100908. sqlite3 *db = pParse->db;
  100909. char saveBuf[PARSE_TAIL_SZ];
  100910. if( pParse->nErr ) return;
  100911. assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
  100912. va_start(ap, zFormat);
  100913. zSql = sqlite3VMPrintf(db, zFormat, ap);
  100914. va_end(ap);
  100915. if( zSql==0 ){
  100916. /* This can result either from an OOM or because the formatted string
  100917. ** exceeds SQLITE_LIMIT_LENGTH. In the latter case, we need to set
  100918. ** an error */
  100919. if( !db->mallocFailed ) pParse->rc = SQLITE_TOOBIG;
  100920. pParse->nErr++;
  100921. return;
  100922. }
  100923. pParse->nested++;
  100924. memcpy(saveBuf, PARSE_TAIL(pParse), PARSE_TAIL_SZ);
  100925. memset(PARSE_TAIL(pParse), 0, PARSE_TAIL_SZ);
  100926. sqlite3RunParser(pParse, zSql, &zErrMsg);
  100927. sqlite3DbFree(db, zErrMsg);
  100928. sqlite3DbFree(db, zSql);
  100929. memcpy(PARSE_TAIL(pParse), saveBuf, PARSE_TAIL_SZ);
  100930. pParse->nested--;
  100931. }
  100932. #if SQLITE_USER_AUTHENTICATION
  100933. /*
  100934. ** Return TRUE if zTable is the name of the system table that stores the
  100935. ** list of users and their access credentials.
  100936. */
  100937. SQLITE_PRIVATE int sqlite3UserAuthTable(const char *zTable){
  100938. return sqlite3_stricmp(zTable, "sqlite_user")==0;
  100939. }
  100940. #endif
  100941. /*
  100942. ** Locate the in-memory structure that describes a particular database
  100943. ** table given the name of that table and (optionally) the name of the
  100944. ** database containing the table. Return NULL if not found.
  100945. **
  100946. ** If zDatabase is 0, all databases are searched for the table and the
  100947. ** first matching table is returned. (No checking for duplicate table
  100948. ** names is done.) The search order is TEMP first, then MAIN, then any
  100949. ** auxiliary databases added using the ATTACH command.
  100950. **
  100951. ** See also sqlite3LocateTable().
  100952. */
  100953. SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
  100954. Table *p = 0;
  100955. int i;
  100956. /* All mutexes are required for schema access. Make sure we hold them. */
  100957. assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  100958. #if SQLITE_USER_AUTHENTICATION
  100959. /* Only the admin user is allowed to know that the sqlite_user table
  100960. ** exists */
  100961. if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){
  100962. return 0;
  100963. }
  100964. #endif
  100965. while(1){
  100966. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  100967. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  100968. if( zDatabase==0 || sqlite3StrICmp(zDatabase, db->aDb[j].zDbSName)==0 ){
  100969. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  100970. p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName);
  100971. if( p ) return p;
  100972. }
  100973. }
  100974. /* Not found. If the name we were looking for was temp.sqlite_master
  100975. ** then change the name to sqlite_temp_master and try again. */
  100976. if( sqlite3StrICmp(zName, MASTER_NAME)!=0 ) break;
  100977. if( sqlite3_stricmp(zDatabase, db->aDb[1].zDbSName)!=0 ) break;
  100978. zName = TEMP_MASTER_NAME;
  100979. }
  100980. return 0;
  100981. }
  100982. /*
  100983. ** Locate the in-memory structure that describes a particular database
  100984. ** table given the name of that table and (optionally) the name of the
  100985. ** database containing the table. Return NULL if not found. Also leave an
  100986. ** error message in pParse->zErrMsg.
  100987. **
  100988. ** The difference between this routine and sqlite3FindTable() is that this
  100989. ** routine leaves an error message in pParse->zErrMsg where
  100990. ** sqlite3FindTable() does not.
  100991. */
  100992. SQLITE_PRIVATE Table *sqlite3LocateTable(
  100993. Parse *pParse, /* context in which to report errors */
  100994. u32 flags, /* LOCATE_VIEW or LOCATE_NOERR */
  100995. const char *zName, /* Name of the table we are looking for */
  100996. const char *zDbase /* Name of the database. Might be NULL */
  100997. ){
  100998. Table *p;
  100999. sqlite3 *db = pParse->db;
  101000. /* Read the database schema. If an error occurs, leave an error message
  101001. ** and code in pParse and return NULL. */
  101002. if( (db->mDbFlags & DBFLAG_SchemaKnownOk)==0
  101003. && SQLITE_OK!=sqlite3ReadSchema(pParse)
  101004. ){
  101005. return 0;
  101006. }
  101007. p = sqlite3FindTable(db, zName, zDbase);
  101008. if( p==0 ){
  101009. #ifndef SQLITE_OMIT_VIRTUALTABLE
  101010. /* If zName is the not the name of a table in the schema created using
  101011. ** CREATE, then check to see if it is the name of an virtual table that
  101012. ** can be an eponymous virtual table. */
  101013. if( pParse->disableVtab==0 ){
  101014. Module *pMod = (Module*)sqlite3HashFind(&db->aModule, zName);
  101015. if( pMod==0 && sqlite3_strnicmp(zName, "pragma_", 7)==0 ){
  101016. pMod = sqlite3PragmaVtabRegister(db, zName);
  101017. }
  101018. if( pMod && sqlite3VtabEponymousTableInit(pParse, pMod) ){
  101019. return pMod->pEpoTab;
  101020. }
  101021. }
  101022. #endif
  101023. if( flags & LOCATE_NOERR ) return 0;
  101024. pParse->checkSchema = 1;
  101025. }else if( IsVirtual(p) && pParse->disableVtab ){
  101026. p = 0;
  101027. }
  101028. if( p==0 ){
  101029. const char *zMsg = flags & LOCATE_VIEW ? "no such view" : "no such table";
  101030. if( zDbase ){
  101031. sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
  101032. }else{
  101033. sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
  101034. }
  101035. }
  101036. return p;
  101037. }
  101038. /*
  101039. ** Locate the table identified by *p.
  101040. **
  101041. ** This is a wrapper around sqlite3LocateTable(). The difference between
  101042. ** sqlite3LocateTable() and this function is that this function restricts
  101043. ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
  101044. ** non-NULL if it is part of a view or trigger program definition. See
  101045. ** sqlite3FixSrcList() for details.
  101046. */
  101047. SQLITE_PRIVATE Table *sqlite3LocateTableItem(
  101048. Parse *pParse,
  101049. u32 flags,
  101050. struct SrcList_item *p
  101051. ){
  101052. const char *zDb;
  101053. assert( p->pSchema==0 || p->zDatabase==0 );
  101054. if( p->pSchema ){
  101055. int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
  101056. zDb = pParse->db->aDb[iDb].zDbSName;
  101057. }else{
  101058. zDb = p->zDatabase;
  101059. }
  101060. return sqlite3LocateTable(pParse, flags, p->zName, zDb);
  101061. }
  101062. /*
  101063. ** Locate the in-memory structure that describes
  101064. ** a particular index given the name of that index
  101065. ** and the name of the database that contains the index.
  101066. ** Return NULL if not found.
  101067. **
  101068. ** If zDatabase is 0, all databases are searched for the
  101069. ** table and the first matching index is returned. (No checking
  101070. ** for duplicate index names is done.) The search order is
  101071. ** TEMP first, then MAIN, then any auxiliary databases added
  101072. ** using the ATTACH command.
  101073. */
  101074. SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
  101075. Index *p = 0;
  101076. int i;
  101077. /* All mutexes are required for schema access. Make sure we hold them. */
  101078. assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  101079. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  101080. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  101081. Schema *pSchema = db->aDb[j].pSchema;
  101082. assert( pSchema );
  101083. if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zDbSName) ) continue;
  101084. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  101085. p = sqlite3HashFind(&pSchema->idxHash, zName);
  101086. if( p ) break;
  101087. }
  101088. return p;
  101089. }
  101090. /*
  101091. ** Reclaim the memory used by an index
  101092. */
  101093. SQLITE_PRIVATE void sqlite3FreeIndex(sqlite3 *db, Index *p){
  101094. #ifndef SQLITE_OMIT_ANALYZE
  101095. sqlite3DeleteIndexSamples(db, p);
  101096. #endif
  101097. sqlite3ExprDelete(db, p->pPartIdxWhere);
  101098. sqlite3ExprListDelete(db, p->aColExpr);
  101099. sqlite3DbFree(db, p->zColAff);
  101100. if( p->isResized ) sqlite3DbFree(db, (void *)p->azColl);
  101101. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  101102. sqlite3_free(p->aiRowEst);
  101103. #endif
  101104. sqlite3DbFree(db, p);
  101105. }
  101106. /*
  101107. ** For the index called zIdxName which is found in the database iDb,
  101108. ** unlike that index from its Table then remove the index from
  101109. ** the index hash table and free all memory structures associated
  101110. ** with the index.
  101111. */
  101112. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
  101113. Index *pIndex;
  101114. Hash *pHash;
  101115. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  101116. pHash = &db->aDb[iDb].pSchema->idxHash;
  101117. pIndex = sqlite3HashInsert(pHash, zIdxName, 0);
  101118. if( ALWAYS(pIndex) ){
  101119. if( pIndex->pTable->pIndex==pIndex ){
  101120. pIndex->pTable->pIndex = pIndex->pNext;
  101121. }else{
  101122. Index *p;
  101123. /* Justification of ALWAYS(); The index must be on the list of
  101124. ** indices. */
  101125. p = pIndex->pTable->pIndex;
  101126. while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
  101127. if( ALWAYS(p && p->pNext==pIndex) ){
  101128. p->pNext = pIndex->pNext;
  101129. }
  101130. }
  101131. sqlite3FreeIndex(db, pIndex);
  101132. }
  101133. db->mDbFlags |= DBFLAG_SchemaChange;
  101134. }
  101135. /*
  101136. ** Look through the list of open database files in db->aDb[] and if
  101137. ** any have been closed, remove them from the list. Reallocate the
  101138. ** db->aDb[] structure to a smaller size, if possible.
  101139. **
  101140. ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
  101141. ** are never candidates for being collapsed.
  101142. */
  101143. SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){
  101144. int i, j;
  101145. for(i=j=2; i<db->nDb; i++){
  101146. struct Db *pDb = &db->aDb[i];
  101147. if( pDb->pBt==0 ){
  101148. sqlite3DbFree(db, pDb->zDbSName);
  101149. pDb->zDbSName = 0;
  101150. continue;
  101151. }
  101152. if( j<i ){
  101153. db->aDb[j] = db->aDb[i];
  101154. }
  101155. j++;
  101156. }
  101157. db->nDb = j;
  101158. if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
  101159. memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
  101160. sqlite3DbFree(db, db->aDb);
  101161. db->aDb = db->aDbStatic;
  101162. }
  101163. }
  101164. /*
  101165. ** Reset the schema for the database at index iDb. Also reset the
  101166. ** TEMP schema. The reset is deferred if db->nSchemaLock is not zero.
  101167. ** Deferred resets may be run by calling with iDb<0.
  101168. */
  101169. SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
  101170. int i;
  101171. assert( iDb<db->nDb );
  101172. if( iDb>=0 ){
  101173. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  101174. DbSetProperty(db, iDb, DB_ResetWanted);
  101175. DbSetProperty(db, 1, DB_ResetWanted);
  101176. db->mDbFlags &= ~DBFLAG_SchemaKnownOk;
  101177. }
  101178. if( db->nSchemaLock==0 ){
  101179. for(i=0; i<db->nDb; i++){
  101180. if( DbHasProperty(db, i, DB_ResetWanted) ){
  101181. sqlite3SchemaClear(db->aDb[i].pSchema);
  101182. }
  101183. }
  101184. }
  101185. }
  101186. /*
  101187. ** Erase all schema information from all attached databases (including
  101188. ** "main" and "temp") for a single database connection.
  101189. */
  101190. SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
  101191. int i;
  101192. sqlite3BtreeEnterAll(db);
  101193. for(i=0; i<db->nDb; i++){
  101194. Db *pDb = &db->aDb[i];
  101195. if( pDb->pSchema ){
  101196. if( db->nSchemaLock==0 ){
  101197. sqlite3SchemaClear(pDb->pSchema);
  101198. }else{
  101199. DbSetProperty(db, i, DB_ResetWanted);
  101200. }
  101201. }
  101202. }
  101203. db->mDbFlags &= ~(DBFLAG_SchemaChange|DBFLAG_SchemaKnownOk);
  101204. sqlite3VtabUnlockList(db);
  101205. sqlite3BtreeLeaveAll(db);
  101206. if( db->nSchemaLock==0 ){
  101207. sqlite3CollapseDatabaseArray(db);
  101208. }
  101209. }
  101210. /*
  101211. ** This routine is called when a commit occurs.
  101212. */
  101213. SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
  101214. db->mDbFlags &= ~DBFLAG_SchemaChange;
  101215. }
  101216. /*
  101217. ** Delete memory allocated for the column names of a table or view (the
  101218. ** Table.aCol[] array).
  101219. */
  101220. SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3 *db, Table *pTable){
  101221. int i;
  101222. Column *pCol;
  101223. assert( pTable!=0 );
  101224. if( (pCol = pTable->aCol)!=0 ){
  101225. for(i=0; i<pTable->nCol; i++, pCol++){
  101226. sqlite3DbFree(db, pCol->zName);
  101227. sqlite3ExprDelete(db, pCol->pDflt);
  101228. sqlite3DbFree(db, pCol->zColl);
  101229. }
  101230. sqlite3DbFree(db, pTable->aCol);
  101231. }
  101232. }
  101233. /*
  101234. ** Remove the memory data structures associated with the given
  101235. ** Table. No changes are made to disk by this routine.
  101236. **
  101237. ** This routine just deletes the data structure. It does not unlink
  101238. ** the table data structure from the hash table. But it does destroy
  101239. ** memory structures of the indices and foreign keys associated with
  101240. ** the table.
  101241. **
  101242. ** The db parameter is optional. It is needed if the Table object
  101243. ** contains lookaside memory. (Table objects in the schema do not use
  101244. ** lookaside memory, but some ephemeral Table objects do.) Or the
  101245. ** db parameter can be used with db->pnBytesFreed to measure the memory
  101246. ** used by the Table object.
  101247. */
  101248. static void SQLITE_NOINLINE deleteTable(sqlite3 *db, Table *pTable){
  101249. Index *pIndex, *pNext;
  101250. #ifdef SQLITE_DEBUG
  101251. /* Record the number of outstanding lookaside allocations in schema Tables
  101252. ** prior to doing any free() operations. Since schema Tables do not use
  101253. ** lookaside, this number should not change.
  101254. **
  101255. ** If malloc has already failed, it may be that it failed while allocating
  101256. ** a Table object that was going to be marked ephemeral. So do not check
  101257. ** that no lookaside memory is used in this case either. */
  101258. int nLookaside = 0;
  101259. if( db && !db->mallocFailed && (pTable->tabFlags & TF_Ephemeral)==0 ){
  101260. nLookaside = sqlite3LookasideUsed(db, 0);
  101261. }
  101262. #endif
  101263. /* Delete all indices associated with this table. */
  101264. for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
  101265. pNext = pIndex->pNext;
  101266. assert( pIndex->pSchema==pTable->pSchema
  101267. || (IsVirtual(pTable) && pIndex->idxType!=SQLITE_IDXTYPE_APPDEF) );
  101268. if( (db==0 || db->pnBytesFreed==0) && !IsVirtual(pTable) ){
  101269. char *zName = pIndex->zName;
  101270. TESTONLY ( Index *pOld = ) sqlite3HashInsert(
  101271. &pIndex->pSchema->idxHash, zName, 0
  101272. );
  101273. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
  101274. assert( pOld==pIndex || pOld==0 );
  101275. }
  101276. sqlite3FreeIndex(db, pIndex);
  101277. }
  101278. /* Delete any foreign keys attached to this table. */
  101279. sqlite3FkDelete(db, pTable);
  101280. /* Delete the Table structure itself.
  101281. */
  101282. sqlite3DeleteColumnNames(db, pTable);
  101283. sqlite3DbFree(db, pTable->zName);
  101284. sqlite3DbFree(db, pTable->zColAff);
  101285. sqlite3SelectDelete(db, pTable->pSelect);
  101286. sqlite3ExprListDelete(db, pTable->pCheck);
  101287. #ifndef SQLITE_OMIT_VIRTUALTABLE
  101288. sqlite3VtabClear(db, pTable);
  101289. #endif
  101290. sqlite3DbFree(db, pTable);
  101291. /* Verify that no lookaside memory was used by schema tables */
  101292. assert( nLookaside==0 || nLookaside==sqlite3LookasideUsed(db,0) );
  101293. }
  101294. SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
  101295. /* Do not delete the table until the reference count reaches zero. */
  101296. if( !pTable ) return;
  101297. if( ((!db || db->pnBytesFreed==0) && (--pTable->nTabRef)>0) ) return;
  101298. deleteTable(db, pTable);
  101299. }
  101300. /*
  101301. ** Unlink the given table from the hash tables and the delete the
  101302. ** table structure with all its indices and foreign keys.
  101303. */
  101304. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
  101305. Table *p;
  101306. Db *pDb;
  101307. assert( db!=0 );
  101308. assert( iDb>=0 && iDb<db->nDb );
  101309. assert( zTabName );
  101310. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  101311. testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
  101312. pDb = &db->aDb[iDb];
  101313. p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);
  101314. sqlite3DeleteTable(db, p);
  101315. db->mDbFlags |= DBFLAG_SchemaChange;
  101316. }
  101317. /*
  101318. ** Given a token, return a string that consists of the text of that
  101319. ** token. Space to hold the returned string
  101320. ** is obtained from sqliteMalloc() and must be freed by the calling
  101321. ** function.
  101322. **
  101323. ** Any quotation marks (ex: "name", 'name', [name], or `name`) that
  101324. ** surround the body of the token are removed.
  101325. **
  101326. ** Tokens are often just pointers into the original SQL text and so
  101327. ** are not \000 terminated and are not persistent. The returned string
  101328. ** is \000 terminated and is persistent.
  101329. */
  101330. SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
  101331. char *zName;
  101332. if( pName ){
  101333. zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
  101334. sqlite3Dequote(zName);
  101335. }else{
  101336. zName = 0;
  101337. }
  101338. return zName;
  101339. }
  101340. /*
  101341. ** Open the sqlite_master table stored in database number iDb for
  101342. ** writing. The table is opened using cursor 0.
  101343. */
  101344. SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
  101345. Vdbe *v = sqlite3GetVdbe(p);
  101346. sqlite3TableLock(p, iDb, MASTER_ROOT, 1, MASTER_NAME);
  101347. sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5);
  101348. if( p->nTab==0 ){
  101349. p->nTab = 1;
  101350. }
  101351. }
  101352. /*
  101353. ** Parameter zName points to a nul-terminated buffer containing the name
  101354. ** of a database ("main", "temp" or the name of an attached db). This
  101355. ** function returns the index of the named database in db->aDb[], or
  101356. ** -1 if the named db cannot be found.
  101357. */
  101358. SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
  101359. int i = -1; /* Database number */
  101360. if( zName ){
  101361. Db *pDb;
  101362. for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
  101363. if( 0==sqlite3_stricmp(pDb->zDbSName, zName) ) break;
  101364. /* "main" is always an acceptable alias for the primary database
  101365. ** even if it has been renamed using SQLITE_DBCONFIG_MAINDBNAME. */
  101366. if( i==0 && 0==sqlite3_stricmp("main", zName) ) break;
  101367. }
  101368. }
  101369. return i;
  101370. }
  101371. /*
  101372. ** The token *pName contains the name of a database (either "main" or
  101373. ** "temp" or the name of an attached db). This routine returns the
  101374. ** index of the named database in db->aDb[], or -1 if the named db
  101375. ** does not exist.
  101376. */
  101377. SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
  101378. int i; /* Database number */
  101379. char *zName; /* Name we are searching for */
  101380. zName = sqlite3NameFromToken(db, pName);
  101381. i = sqlite3FindDbName(db, zName);
  101382. sqlite3DbFree(db, zName);
  101383. return i;
  101384. }
  101385. /* The table or view or trigger name is passed to this routine via tokens
  101386. ** pName1 and pName2. If the table name was fully qualified, for example:
  101387. **
  101388. ** CREATE TABLE xxx.yyy (...);
  101389. **
  101390. ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
  101391. ** the table name is not fully qualified, i.e.:
  101392. **
  101393. ** CREATE TABLE yyy(...);
  101394. **
  101395. ** Then pName1 is set to "yyy" and pName2 is "".
  101396. **
  101397. ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
  101398. ** pName2) that stores the unqualified table name. The index of the
  101399. ** database "xxx" is returned.
  101400. */
  101401. SQLITE_PRIVATE int sqlite3TwoPartName(
  101402. Parse *pParse, /* Parsing and code generating context */
  101403. Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
  101404. Token *pName2, /* The "yyy" in the name "xxx.yyy" */
  101405. Token **pUnqual /* Write the unqualified object name here */
  101406. ){
  101407. int iDb; /* Database holding the object */
  101408. sqlite3 *db = pParse->db;
  101409. assert( pName2!=0 );
  101410. if( pName2->n>0 ){
  101411. if( db->init.busy ) {
  101412. sqlite3ErrorMsg(pParse, "corrupt database");
  101413. return -1;
  101414. }
  101415. *pUnqual = pName2;
  101416. iDb = sqlite3FindDb(db, pName1);
  101417. if( iDb<0 ){
  101418. sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
  101419. return -1;
  101420. }
  101421. }else{
  101422. assert( db->init.iDb==0 || db->init.busy || IN_RENAME_OBJECT
  101423. || (db->mDbFlags & DBFLAG_Vacuum)!=0);
  101424. iDb = db->init.iDb;
  101425. *pUnqual = pName1;
  101426. }
  101427. return iDb;
  101428. }
  101429. /*
  101430. ** True if PRAGMA writable_schema is ON
  101431. */
  101432. SQLITE_PRIVATE int sqlite3WritableSchema(sqlite3 *db){
  101433. testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==0 );
  101434. testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==
  101435. SQLITE_WriteSchema );
  101436. testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==
  101437. SQLITE_Defensive );
  101438. testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==
  101439. (SQLITE_WriteSchema|SQLITE_Defensive) );
  101440. return (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==SQLITE_WriteSchema;
  101441. }
  101442. /*
  101443. ** This routine is used to check if the UTF-8 string zName is a legal
  101444. ** unqualified name for a new schema object (table, index, view or
  101445. ** trigger). All names are legal except those that begin with the string
  101446. ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
  101447. ** is reserved for internal use.
  101448. */
  101449. SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
  101450. if( !pParse->db->init.busy && pParse->nested==0
  101451. && sqlite3WritableSchema(pParse->db)==0
  101452. && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
  101453. sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
  101454. return SQLITE_ERROR;
  101455. }
  101456. return SQLITE_OK;
  101457. }
  101458. /*
  101459. ** Return the PRIMARY KEY index of a table
  101460. */
  101461. SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table *pTab){
  101462. Index *p;
  101463. for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
  101464. return p;
  101465. }
  101466. /*
  101467. ** Return the column of index pIdx that corresponds to table
  101468. ** column iCol. Return -1 if not found.
  101469. */
  101470. SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){
  101471. int i;
  101472. for(i=0; i<pIdx->nColumn; i++){
  101473. if( iCol==pIdx->aiColumn[i] ) return i;
  101474. }
  101475. return -1;
  101476. }
  101477. /*
  101478. ** Begin constructing a new table representation in memory. This is
  101479. ** the first of several action routines that get called in response
  101480. ** to a CREATE TABLE statement. In particular, this routine is called
  101481. ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
  101482. ** flag is true if the table should be stored in the auxiliary database
  101483. ** file instead of in the main database file. This is normally the case
  101484. ** when the "TEMP" or "TEMPORARY" keyword occurs in between
  101485. ** CREATE and TABLE.
  101486. **
  101487. ** The new table record is initialized and put in pParse->pNewTable.
  101488. ** As more of the CREATE TABLE statement is parsed, additional action
  101489. ** routines will be called to add more information to this record.
  101490. ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
  101491. ** is called to complete the construction of the new table record.
  101492. */
  101493. SQLITE_PRIVATE void sqlite3StartTable(
  101494. Parse *pParse, /* Parser context */
  101495. Token *pName1, /* First part of the name of the table or view */
  101496. Token *pName2, /* Second part of the name of the table or view */
  101497. int isTemp, /* True if this is a TEMP table */
  101498. int isView, /* True if this is a VIEW */
  101499. int isVirtual, /* True if this is a VIRTUAL table */
  101500. int noErr /* Do nothing if table already exists */
  101501. ){
  101502. Table *pTable;
  101503. char *zName = 0; /* The name of the new table */
  101504. sqlite3 *db = pParse->db;
  101505. Vdbe *v;
  101506. int iDb; /* Database number to create the table in */
  101507. Token *pName; /* Unqualified name of the table to create */
  101508. if( db->init.busy && db->init.newTnum==1 ){
  101509. /* Special case: Parsing the sqlite_master or sqlite_temp_master schema */
  101510. iDb = db->init.iDb;
  101511. zName = sqlite3DbStrDup(db, SCHEMA_TABLE(iDb));
  101512. pName = pName1;
  101513. }else{
  101514. /* The common case */
  101515. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  101516. if( iDb<0 ) return;
  101517. if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
  101518. /* If creating a temp table, the name may not be qualified. Unless
  101519. ** the database name is "temp" anyway. */
  101520. sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
  101521. return;
  101522. }
  101523. if( !OMIT_TEMPDB && isTemp ) iDb = 1;
  101524. zName = sqlite3NameFromToken(db, pName);
  101525. if( IN_RENAME_OBJECT ){
  101526. sqlite3RenameTokenMap(pParse, (void*)zName, pName);
  101527. }
  101528. }
  101529. pParse->sNameToken = *pName;
  101530. if( zName==0 ) return;
  101531. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  101532. goto begin_table_error;
  101533. }
  101534. if( db->init.iDb==1 ) isTemp = 1;
  101535. #ifndef SQLITE_OMIT_AUTHORIZATION
  101536. assert( isTemp==0 || isTemp==1 );
  101537. assert( isView==0 || isView==1 );
  101538. {
  101539. static const u8 aCode[] = {
  101540. SQLITE_CREATE_TABLE,
  101541. SQLITE_CREATE_TEMP_TABLE,
  101542. SQLITE_CREATE_VIEW,
  101543. SQLITE_CREATE_TEMP_VIEW
  101544. };
  101545. char *zDb = db->aDb[iDb].zDbSName;
  101546. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
  101547. goto begin_table_error;
  101548. }
  101549. if( !isVirtual && sqlite3AuthCheck(pParse, (int)aCode[isTemp+2*isView],
  101550. zName, 0, zDb) ){
  101551. goto begin_table_error;
  101552. }
  101553. }
  101554. #endif
  101555. /* Make sure the new table name does not collide with an existing
  101556. ** index or table name in the same database. Issue an error message if
  101557. ** it does. The exception is if the statement being parsed was passed
  101558. ** to an sqlite3_declare_vtab() call. In that case only the column names
  101559. ** and types will be used, so there is no need to test for namespace
  101560. ** collisions.
  101561. */
  101562. if( !IN_SPECIAL_PARSE ){
  101563. char *zDb = db->aDb[iDb].zDbSName;
  101564. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  101565. goto begin_table_error;
  101566. }
  101567. pTable = sqlite3FindTable(db, zName, zDb);
  101568. if( pTable ){
  101569. if( !noErr ){
  101570. sqlite3ErrorMsg(pParse, "table %T already exists", pName);
  101571. }else{
  101572. assert( !db->init.busy || CORRUPT_DB );
  101573. sqlite3CodeVerifySchema(pParse, iDb);
  101574. }
  101575. goto begin_table_error;
  101576. }
  101577. if( sqlite3FindIndex(db, zName, zDb)!=0 ){
  101578. sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
  101579. goto begin_table_error;
  101580. }
  101581. }
  101582. pTable = sqlite3DbMallocZero(db, sizeof(Table));
  101583. if( pTable==0 ){
  101584. assert( db->mallocFailed );
  101585. pParse->rc = SQLITE_NOMEM_BKPT;
  101586. pParse->nErr++;
  101587. goto begin_table_error;
  101588. }
  101589. pTable->zName = zName;
  101590. pTable->iPKey = -1;
  101591. pTable->pSchema = db->aDb[iDb].pSchema;
  101592. pTable->nTabRef = 1;
  101593. #ifdef SQLITE_DEFAULT_ROWEST
  101594. pTable->nRowLogEst = sqlite3LogEst(SQLITE_DEFAULT_ROWEST);
  101595. #else
  101596. pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  101597. #endif
  101598. assert( pParse->pNewTable==0 );
  101599. pParse->pNewTable = pTable;
  101600. /* If this is the magic sqlite_sequence table used by autoincrement,
  101601. ** then record a pointer to this table in the main database structure
  101602. ** so that INSERT can find the table easily.
  101603. */
  101604. #ifndef SQLITE_OMIT_AUTOINCREMENT
  101605. if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
  101606. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  101607. pTable->pSchema->pSeqTab = pTable;
  101608. }
  101609. #endif
  101610. /* Begin generating the code that will insert the table record into
  101611. ** the SQLITE_MASTER table. Note in particular that we must go ahead
  101612. ** and allocate the record number for the table entry now. Before any
  101613. ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
  101614. ** indices to be created and the table record must come before the
  101615. ** indices. Hence, the record number for the table must be allocated
  101616. ** now.
  101617. */
  101618. if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
  101619. int addr1;
  101620. int fileFormat;
  101621. int reg1, reg2, reg3;
  101622. /* nullRow[] is an OP_Record encoding of a row containing 5 NULLs */
  101623. static const char nullRow[] = { 6, 0, 0, 0, 0, 0 };
  101624. sqlite3BeginWriteOperation(pParse, 1, iDb);
  101625. #ifndef SQLITE_OMIT_VIRTUALTABLE
  101626. if( isVirtual ){
  101627. sqlite3VdbeAddOp0(v, OP_VBegin);
  101628. }
  101629. #endif
  101630. /* If the file format and encoding in the database have not been set,
  101631. ** set them now.
  101632. */
  101633. reg1 = pParse->regRowid = ++pParse->nMem;
  101634. reg2 = pParse->regRoot = ++pParse->nMem;
  101635. reg3 = ++pParse->nMem;
  101636. sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
  101637. sqlite3VdbeUsesBtree(v, iDb);
  101638. addr1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
  101639. fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
  101640. 1 : SQLITE_MAX_FILE_FORMAT;
  101641. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, fileFormat);
  101642. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, ENC(db));
  101643. sqlite3VdbeJumpHere(v, addr1);
  101644. /* This just creates a place-holder record in the sqlite_master table.
  101645. ** The record created does not contain anything yet. It will be replaced
  101646. ** by the real entry in code generated at sqlite3EndTable().
  101647. **
  101648. ** The rowid for the new entry is left in register pParse->regRowid.
  101649. ** The root page number of the new table is left in reg pParse->regRoot.
  101650. ** The rowid and root page number values are needed by the code that
  101651. ** sqlite3EndTable will generate.
  101652. */
  101653. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  101654. if( isView || isVirtual ){
  101655. sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
  101656. }else
  101657. #endif
  101658. {
  101659. pParse->addrCrTab =
  101660. sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, reg2, BTREE_INTKEY);
  101661. }
  101662. sqlite3OpenMasterTable(pParse, iDb);
  101663. sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
  101664. sqlite3VdbeAddOp4(v, OP_Blob, 6, reg3, 0, nullRow, P4_STATIC);
  101665. sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
  101666. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  101667. sqlite3VdbeAddOp0(v, OP_Close);
  101668. }
  101669. /* Normal (non-error) return. */
  101670. return;
  101671. /* If an error occurs, we jump here */
  101672. begin_table_error:
  101673. sqlite3DbFree(db, zName);
  101674. return;
  101675. }
  101676. /* Set properties of a table column based on the (magical)
  101677. ** name of the column.
  101678. */
  101679. #if SQLITE_ENABLE_HIDDEN_COLUMNS
  101680. SQLITE_PRIVATE void sqlite3ColumnPropertiesFromName(Table *pTab, Column *pCol){
  101681. if( sqlite3_strnicmp(pCol->zName, "__hidden__", 10)==0 ){
  101682. pCol->colFlags |= COLFLAG_HIDDEN;
  101683. }else if( pTab && pCol!=pTab->aCol && (pCol[-1].colFlags & COLFLAG_HIDDEN) ){
  101684. pTab->tabFlags |= TF_OOOHidden;
  101685. }
  101686. }
  101687. #endif
  101688. /*
  101689. ** Add a new column to the table currently being constructed.
  101690. **
  101691. ** The parser calls this routine once for each column declaration
  101692. ** in a CREATE TABLE statement. sqlite3StartTable() gets called
  101693. ** first to get things going. Then this routine is called for each
  101694. ** column.
  101695. */
  101696. SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName, Token *pType){
  101697. Table *p;
  101698. int i;
  101699. char *z;
  101700. char *zType;
  101701. Column *pCol;
  101702. sqlite3 *db = pParse->db;
  101703. if( (p = pParse->pNewTable)==0 ) return;
  101704. if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  101705. sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
  101706. return;
  101707. }
  101708. z = sqlite3DbMallocRaw(db, pName->n + pType->n + 2);
  101709. if( z==0 ) return;
  101710. if( IN_RENAME_OBJECT ) sqlite3RenameTokenMap(pParse, (void*)z, pName);
  101711. memcpy(z, pName->z, pName->n);
  101712. z[pName->n] = 0;
  101713. sqlite3Dequote(z);
  101714. for(i=0; i<p->nCol; i++){
  101715. if( sqlite3_stricmp(z, p->aCol[i].zName)==0 ){
  101716. sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
  101717. sqlite3DbFree(db, z);
  101718. return;
  101719. }
  101720. }
  101721. if( (p->nCol & 0x7)==0 ){
  101722. Column *aNew;
  101723. aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
  101724. if( aNew==0 ){
  101725. sqlite3DbFree(db, z);
  101726. return;
  101727. }
  101728. p->aCol = aNew;
  101729. }
  101730. pCol = &p->aCol[p->nCol];
  101731. memset(pCol, 0, sizeof(p->aCol[0]));
  101732. pCol->zName = z;
  101733. sqlite3ColumnPropertiesFromName(p, pCol);
  101734. if( pType->n==0 ){
  101735. /* If there is no type specified, columns have the default affinity
  101736. ** 'BLOB' with a default size of 4 bytes. */
  101737. pCol->affinity = SQLITE_AFF_BLOB;
  101738. pCol->szEst = 1;
  101739. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  101740. if( 4>=sqlite3GlobalConfig.szSorterRef ){
  101741. pCol->colFlags |= COLFLAG_SORTERREF;
  101742. }
  101743. #endif
  101744. }else{
  101745. zType = z + sqlite3Strlen30(z) + 1;
  101746. memcpy(zType, pType->z, pType->n);
  101747. zType[pType->n] = 0;
  101748. sqlite3Dequote(zType);
  101749. pCol->affinity = sqlite3AffinityType(zType, pCol);
  101750. pCol->colFlags |= COLFLAG_HASTYPE;
  101751. }
  101752. p->nCol++;
  101753. pParse->constraintName.n = 0;
  101754. }
  101755. /*
  101756. ** This routine is called by the parser while in the middle of
  101757. ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
  101758. ** been seen on a column. This routine sets the notNull flag on
  101759. ** the column currently under construction.
  101760. */
  101761. SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
  101762. Table *p;
  101763. Column *pCol;
  101764. p = pParse->pNewTable;
  101765. if( p==0 || NEVER(p->nCol<1) ) return;
  101766. pCol = &p->aCol[p->nCol-1];
  101767. pCol->notNull = (u8)onError;
  101768. p->tabFlags |= TF_HasNotNull;
  101769. /* Set the uniqNotNull flag on any UNIQUE or PK indexes already created
  101770. ** on this column. */
  101771. if( pCol->colFlags & COLFLAG_UNIQUE ){
  101772. Index *pIdx;
  101773. for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
  101774. assert( pIdx->nKeyCol==1 && pIdx->onError!=OE_None );
  101775. if( pIdx->aiColumn[0]==p->nCol-1 ){
  101776. pIdx->uniqNotNull = 1;
  101777. }
  101778. }
  101779. }
  101780. }
  101781. /*
  101782. ** Scan the column type name zType (length nType) and return the
  101783. ** associated affinity type.
  101784. **
  101785. ** This routine does a case-independent search of zType for the
  101786. ** substrings in the following table. If one of the substrings is
  101787. ** found, the corresponding affinity is returned. If zType contains
  101788. ** more than one of the substrings, entries toward the top of
  101789. ** the table take priority. For example, if zType is 'BLOBINT',
  101790. ** SQLITE_AFF_INTEGER is returned.
  101791. **
  101792. ** Substring | Affinity
  101793. ** --------------------------------
  101794. ** 'INT' | SQLITE_AFF_INTEGER
  101795. ** 'CHAR' | SQLITE_AFF_TEXT
  101796. ** 'CLOB' | SQLITE_AFF_TEXT
  101797. ** 'TEXT' | SQLITE_AFF_TEXT
  101798. ** 'BLOB' | SQLITE_AFF_BLOB
  101799. ** 'REAL' | SQLITE_AFF_REAL
  101800. ** 'FLOA' | SQLITE_AFF_REAL
  101801. ** 'DOUB' | SQLITE_AFF_REAL
  101802. **
  101803. ** If none of the substrings in the above table are found,
  101804. ** SQLITE_AFF_NUMERIC is returned.
  101805. */
  101806. SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn, Column *pCol){
  101807. u32 h = 0;
  101808. char aff = SQLITE_AFF_NUMERIC;
  101809. const char *zChar = 0;
  101810. assert( zIn!=0 );
  101811. while( zIn[0] ){
  101812. h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
  101813. zIn++;
  101814. if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
  101815. aff = SQLITE_AFF_TEXT;
  101816. zChar = zIn;
  101817. }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
  101818. aff = SQLITE_AFF_TEXT;
  101819. }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
  101820. aff = SQLITE_AFF_TEXT;
  101821. }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
  101822. && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
  101823. aff = SQLITE_AFF_BLOB;
  101824. if( zIn[0]=='(' ) zChar = zIn;
  101825. #ifndef SQLITE_OMIT_FLOATING_POINT
  101826. }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
  101827. && aff==SQLITE_AFF_NUMERIC ){
  101828. aff = SQLITE_AFF_REAL;
  101829. }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
  101830. && aff==SQLITE_AFF_NUMERIC ){
  101831. aff = SQLITE_AFF_REAL;
  101832. }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
  101833. && aff==SQLITE_AFF_NUMERIC ){
  101834. aff = SQLITE_AFF_REAL;
  101835. #endif
  101836. }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
  101837. aff = SQLITE_AFF_INTEGER;
  101838. break;
  101839. }
  101840. }
  101841. /* If pCol is not NULL, store an estimate of the field size. The
  101842. ** estimate is scaled so that the size of an integer is 1. */
  101843. if( pCol ){
  101844. int v = 0; /* default size is approx 4 bytes */
  101845. if( aff<SQLITE_AFF_NUMERIC ){
  101846. if( zChar ){
  101847. while( zChar[0] ){
  101848. if( sqlite3Isdigit(zChar[0]) ){
  101849. /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
  101850. sqlite3GetInt32(zChar, &v);
  101851. break;
  101852. }
  101853. zChar++;
  101854. }
  101855. }else{
  101856. v = 16; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/
  101857. }
  101858. }
  101859. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  101860. if( v>=sqlite3GlobalConfig.szSorterRef ){
  101861. pCol->colFlags |= COLFLAG_SORTERREF;
  101862. }
  101863. #endif
  101864. v = v/4 + 1;
  101865. if( v>255 ) v = 255;
  101866. pCol->szEst = v;
  101867. }
  101868. return aff;
  101869. }
  101870. /*
  101871. ** The expression is the default value for the most recently added column
  101872. ** of the table currently under construction.
  101873. **
  101874. ** Default value expressions must be constant. Raise an exception if this
  101875. ** is not the case.
  101876. **
  101877. ** This routine is called by the parser while in the middle of
  101878. ** parsing a CREATE TABLE statement.
  101879. */
  101880. SQLITE_PRIVATE void sqlite3AddDefaultValue(
  101881. Parse *pParse, /* Parsing context */
  101882. Expr *pExpr, /* The parsed expression of the default value */
  101883. const char *zStart, /* Start of the default value text */
  101884. const char *zEnd /* First character past end of defaut value text */
  101885. ){
  101886. Table *p;
  101887. Column *pCol;
  101888. sqlite3 *db = pParse->db;
  101889. p = pParse->pNewTable;
  101890. if( p!=0 ){
  101891. pCol = &(p->aCol[p->nCol-1]);
  101892. if( !sqlite3ExprIsConstantOrFunction(pExpr, db->init.busy) ){
  101893. sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
  101894. pCol->zName);
  101895. }else{
  101896. /* A copy of pExpr is used instead of the original, as pExpr contains
  101897. ** tokens that point to volatile memory.
  101898. */
  101899. Expr x;
  101900. sqlite3ExprDelete(db, pCol->pDflt);
  101901. memset(&x, 0, sizeof(x));
  101902. x.op = TK_SPAN;
  101903. x.u.zToken = sqlite3DbSpanDup(db, zStart, zEnd);
  101904. x.pLeft = pExpr;
  101905. x.flags = EP_Skip;
  101906. pCol->pDflt = sqlite3ExprDup(db, &x, EXPRDUP_REDUCE);
  101907. sqlite3DbFree(db, x.u.zToken);
  101908. }
  101909. }
  101910. if( IN_RENAME_OBJECT ){
  101911. sqlite3RenameExprUnmap(pParse, pExpr);
  101912. }
  101913. sqlite3ExprDelete(db, pExpr);
  101914. }
  101915. /*
  101916. ** Backwards Compatibility Hack:
  101917. **
  101918. ** Historical versions of SQLite accepted strings as column names in
  101919. ** indexes and PRIMARY KEY constraints and in UNIQUE constraints. Example:
  101920. **
  101921. ** CREATE TABLE xyz(a,b,c,d,e,PRIMARY KEY('a'),UNIQUE('b','c' COLLATE trim)
  101922. ** CREATE INDEX abc ON xyz('c','d' DESC,'e' COLLATE nocase DESC);
  101923. **
  101924. ** This is goofy. But to preserve backwards compatibility we continue to
  101925. ** accept it. This routine does the necessary conversion. It converts
  101926. ** the expression given in its argument from a TK_STRING into a TK_ID
  101927. ** if the expression is just a TK_STRING with an optional COLLATE clause.
  101928. ** If the expression is anything other than TK_STRING, the expression is
  101929. ** unchanged.
  101930. */
  101931. static void sqlite3StringToId(Expr *p){
  101932. if( p->op==TK_STRING ){
  101933. p->op = TK_ID;
  101934. }else if( p->op==TK_COLLATE && p->pLeft->op==TK_STRING ){
  101935. p->pLeft->op = TK_ID;
  101936. }
  101937. }
  101938. /*
  101939. ** Designate the PRIMARY KEY for the table. pList is a list of names
  101940. ** of columns that form the primary key. If pList is NULL, then the
  101941. ** most recently added column of the table is the primary key.
  101942. **
  101943. ** A table can have at most one primary key. If the table already has
  101944. ** a primary key (and this is the second primary key) then create an
  101945. ** error.
  101946. **
  101947. ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
  101948. ** then we will try to use that column as the rowid. Set the Table.iPKey
  101949. ** field of the table under construction to be the index of the
  101950. ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
  101951. ** no INTEGER PRIMARY KEY.
  101952. **
  101953. ** If the key is not an INTEGER PRIMARY KEY, then create a unique
  101954. ** index for the key. No index is created for INTEGER PRIMARY KEYs.
  101955. */
  101956. SQLITE_PRIVATE void sqlite3AddPrimaryKey(
  101957. Parse *pParse, /* Parsing context */
  101958. ExprList *pList, /* List of field names to be indexed */
  101959. int onError, /* What to do with a uniqueness conflict */
  101960. int autoInc, /* True if the AUTOINCREMENT keyword is present */
  101961. int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
  101962. ){
  101963. Table *pTab = pParse->pNewTable;
  101964. Column *pCol = 0;
  101965. int iCol = -1, i;
  101966. int nTerm;
  101967. if( pTab==0 ) goto primary_key_exit;
  101968. if( pTab->tabFlags & TF_HasPrimaryKey ){
  101969. sqlite3ErrorMsg(pParse,
  101970. "table \"%s\" has more than one primary key", pTab->zName);
  101971. goto primary_key_exit;
  101972. }
  101973. pTab->tabFlags |= TF_HasPrimaryKey;
  101974. if( pList==0 ){
  101975. iCol = pTab->nCol - 1;
  101976. pCol = &pTab->aCol[iCol];
  101977. pCol->colFlags |= COLFLAG_PRIMKEY;
  101978. nTerm = 1;
  101979. }else{
  101980. nTerm = pList->nExpr;
  101981. for(i=0; i<nTerm; i++){
  101982. Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[i].pExpr);
  101983. assert( pCExpr!=0 );
  101984. sqlite3StringToId(pCExpr);
  101985. if( pCExpr->op==TK_ID ){
  101986. const char *zCName = pCExpr->u.zToken;
  101987. for(iCol=0; iCol<pTab->nCol; iCol++){
  101988. if( sqlite3StrICmp(zCName, pTab->aCol[iCol].zName)==0 ){
  101989. pCol = &pTab->aCol[iCol];
  101990. pCol->colFlags |= COLFLAG_PRIMKEY;
  101991. break;
  101992. }
  101993. }
  101994. }
  101995. }
  101996. }
  101997. if( nTerm==1
  101998. && pCol
  101999. && sqlite3StrICmp(sqlite3ColumnType(pCol,""), "INTEGER")==0
  102000. && sortOrder!=SQLITE_SO_DESC
  102001. ){
  102002. if( IN_RENAME_OBJECT && pList ){
  102003. Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[0].pExpr);
  102004. sqlite3RenameTokenRemap(pParse, &pTab->iPKey, pCExpr);
  102005. }
  102006. pTab->iPKey = iCol;
  102007. pTab->keyConf = (u8)onError;
  102008. assert( autoInc==0 || autoInc==1 );
  102009. pTab->tabFlags |= autoInc*TF_Autoincrement;
  102010. if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder;
  102011. }else if( autoInc ){
  102012. #ifndef SQLITE_OMIT_AUTOINCREMENT
  102013. sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
  102014. "INTEGER PRIMARY KEY");
  102015. #endif
  102016. }else{
  102017. sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
  102018. 0, sortOrder, 0, SQLITE_IDXTYPE_PRIMARYKEY);
  102019. pList = 0;
  102020. }
  102021. primary_key_exit:
  102022. sqlite3ExprListDelete(pParse->db, pList);
  102023. return;
  102024. }
  102025. /*
  102026. ** Add a new CHECK constraint to the table currently under construction.
  102027. */
  102028. SQLITE_PRIVATE void sqlite3AddCheckConstraint(
  102029. Parse *pParse, /* Parsing context */
  102030. Expr *pCheckExpr /* The check expression */
  102031. ){
  102032. #ifndef SQLITE_OMIT_CHECK
  102033. Table *pTab = pParse->pNewTable;
  102034. sqlite3 *db = pParse->db;
  102035. if( pTab && !IN_DECLARE_VTAB
  102036. && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
  102037. ){
  102038. pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
  102039. if( pParse->constraintName.n ){
  102040. sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
  102041. }
  102042. }else
  102043. #endif
  102044. {
  102045. sqlite3ExprDelete(pParse->db, pCheckExpr);
  102046. }
  102047. }
  102048. /*
  102049. ** Set the collation function of the most recently parsed table column
  102050. ** to the CollSeq given.
  102051. */
  102052. SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
  102053. Table *p;
  102054. int i;
  102055. char *zColl; /* Dequoted name of collation sequence */
  102056. sqlite3 *db;
  102057. if( (p = pParse->pNewTable)==0 ) return;
  102058. i = p->nCol-1;
  102059. db = pParse->db;
  102060. zColl = sqlite3NameFromToken(db, pToken);
  102061. if( !zColl ) return;
  102062. if( sqlite3LocateCollSeq(pParse, zColl) ){
  102063. Index *pIdx;
  102064. sqlite3DbFree(db, p->aCol[i].zColl);
  102065. p->aCol[i].zColl = zColl;
  102066. /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
  102067. ** then an index may have been created on this column before the
  102068. ** collation type was added. Correct this if it is the case.
  102069. */
  102070. for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
  102071. assert( pIdx->nKeyCol==1 );
  102072. if( pIdx->aiColumn[0]==i ){
  102073. pIdx->azColl[0] = p->aCol[i].zColl;
  102074. }
  102075. }
  102076. }else{
  102077. sqlite3DbFree(db, zColl);
  102078. }
  102079. }
  102080. /*
  102081. ** This function returns the collation sequence for database native text
  102082. ** encoding identified by the string zName, length nName.
  102083. **
  102084. ** If the requested collation sequence is not available, or not available
  102085. ** in the database native encoding, the collation factory is invoked to
  102086. ** request it. If the collation factory does not supply such a sequence,
  102087. ** and the sequence is available in another text encoding, then that is
  102088. ** returned instead.
  102089. **
  102090. ** If no versions of the requested collations sequence are available, or
  102091. ** another error occurs, NULL is returned and an error message written into
  102092. ** pParse.
  102093. **
  102094. ** This routine is a wrapper around sqlite3FindCollSeq(). This routine
  102095. ** invokes the collation factory if the named collation cannot be found
  102096. ** and generates an error message.
  102097. **
  102098. ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
  102099. */
  102100. SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
  102101. sqlite3 *db = pParse->db;
  102102. u8 enc = ENC(db);
  102103. u8 initbusy = db->init.busy;
  102104. CollSeq *pColl;
  102105. pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
  102106. if( !initbusy && (!pColl || !pColl->xCmp) ){
  102107. pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
  102108. }
  102109. return pColl;
  102110. }
  102111. /*
  102112. ** Generate code that will increment the schema cookie.
  102113. **
  102114. ** The schema cookie is used to determine when the schema for the
  102115. ** database changes. After each schema change, the cookie value
  102116. ** changes. When a process first reads the schema it records the
  102117. ** cookie. Thereafter, whenever it goes to access the database,
  102118. ** it checks the cookie to make sure the schema has not changed
  102119. ** since it was last read.
  102120. **
  102121. ** This plan is not completely bullet-proof. It is possible for
  102122. ** the schema to change multiple times and for the cookie to be
  102123. ** set back to prior value. But schema changes are infrequent
  102124. ** and the probability of hitting the same cookie value is only
  102125. ** 1 chance in 2^32. So we're safe enough.
  102126. **
  102127. ** IMPLEMENTATION-OF: R-34230-56049 SQLite automatically increments
  102128. ** the schema-version whenever the schema changes.
  102129. */
  102130. SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
  102131. sqlite3 *db = pParse->db;
  102132. Vdbe *v = pParse->pVdbe;
  102133. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  102134. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION,
  102135. (int)(1+(unsigned)db->aDb[iDb].pSchema->schema_cookie));
  102136. }
  102137. /*
  102138. ** Measure the number of characters needed to output the given
  102139. ** identifier. The number returned includes any quotes used
  102140. ** but does not include the null terminator.
  102141. **
  102142. ** The estimate is conservative. It might be larger that what is
  102143. ** really needed.
  102144. */
  102145. static int identLength(const char *z){
  102146. int n;
  102147. for(n=0; *z; n++, z++){
  102148. if( *z=='"' ){ n++; }
  102149. }
  102150. return n + 2;
  102151. }
  102152. /*
  102153. ** The first parameter is a pointer to an output buffer. The second
  102154. ** parameter is a pointer to an integer that contains the offset at
  102155. ** which to write into the output buffer. This function copies the
  102156. ** nul-terminated string pointed to by the third parameter, zSignedIdent,
  102157. ** to the specified offset in the buffer and updates *pIdx to refer
  102158. ** to the first byte after the last byte written before returning.
  102159. **
  102160. ** If the string zSignedIdent consists entirely of alpha-numeric
  102161. ** characters, does not begin with a digit and is not an SQL keyword,
  102162. ** then it is copied to the output buffer exactly as it is. Otherwise,
  102163. ** it is quoted using double-quotes.
  102164. */
  102165. static void identPut(char *z, int *pIdx, char *zSignedIdent){
  102166. unsigned char *zIdent = (unsigned char*)zSignedIdent;
  102167. int i, j, needQuote;
  102168. i = *pIdx;
  102169. for(j=0; zIdent[j]; j++){
  102170. if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
  102171. }
  102172. needQuote = sqlite3Isdigit(zIdent[0])
  102173. || sqlite3KeywordCode(zIdent, j)!=TK_ID
  102174. || zIdent[j]!=0
  102175. || j==0;
  102176. if( needQuote ) z[i++] = '"';
  102177. for(j=0; zIdent[j]; j++){
  102178. z[i++] = zIdent[j];
  102179. if( zIdent[j]=='"' ) z[i++] = '"';
  102180. }
  102181. if( needQuote ) z[i++] = '"';
  102182. z[i] = 0;
  102183. *pIdx = i;
  102184. }
  102185. /*
  102186. ** Generate a CREATE TABLE statement appropriate for the given
  102187. ** table. Memory to hold the text of the statement is obtained
  102188. ** from sqliteMalloc() and must be freed by the calling function.
  102189. */
  102190. static char *createTableStmt(sqlite3 *db, Table *p){
  102191. int i, k, n;
  102192. char *zStmt;
  102193. char *zSep, *zSep2, *zEnd;
  102194. Column *pCol;
  102195. n = 0;
  102196. for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
  102197. n += identLength(pCol->zName) + 5;
  102198. }
  102199. n += identLength(p->zName);
  102200. if( n<50 ){
  102201. zSep = "";
  102202. zSep2 = ",";
  102203. zEnd = ")";
  102204. }else{
  102205. zSep = "\n ";
  102206. zSep2 = ",\n ";
  102207. zEnd = "\n)";
  102208. }
  102209. n += 35 + 6*p->nCol;
  102210. zStmt = sqlite3DbMallocRaw(0, n);
  102211. if( zStmt==0 ){
  102212. sqlite3OomFault(db);
  102213. return 0;
  102214. }
  102215. sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
  102216. k = sqlite3Strlen30(zStmt);
  102217. identPut(zStmt, &k, p->zName);
  102218. zStmt[k++] = '(';
  102219. for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
  102220. static const char * const azType[] = {
  102221. /* SQLITE_AFF_BLOB */ "",
  102222. /* SQLITE_AFF_TEXT */ " TEXT",
  102223. /* SQLITE_AFF_NUMERIC */ " NUM",
  102224. /* SQLITE_AFF_INTEGER */ " INT",
  102225. /* SQLITE_AFF_REAL */ " REAL"
  102226. };
  102227. int len;
  102228. const char *zType;
  102229. sqlite3_snprintf(n-k, &zStmt[k], zSep);
  102230. k += sqlite3Strlen30(&zStmt[k]);
  102231. zSep = zSep2;
  102232. identPut(zStmt, &k, pCol->zName);
  102233. assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 );
  102234. assert( pCol->affinity-SQLITE_AFF_BLOB < ArraySize(azType) );
  102235. testcase( pCol->affinity==SQLITE_AFF_BLOB );
  102236. testcase( pCol->affinity==SQLITE_AFF_TEXT );
  102237. testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
  102238. testcase( pCol->affinity==SQLITE_AFF_INTEGER );
  102239. testcase( pCol->affinity==SQLITE_AFF_REAL );
  102240. zType = azType[pCol->affinity - SQLITE_AFF_BLOB];
  102241. len = sqlite3Strlen30(zType);
  102242. assert( pCol->affinity==SQLITE_AFF_BLOB
  102243. || pCol->affinity==sqlite3AffinityType(zType, 0) );
  102244. memcpy(&zStmt[k], zType, len);
  102245. k += len;
  102246. assert( k<=n );
  102247. }
  102248. sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
  102249. return zStmt;
  102250. }
  102251. /*
  102252. ** Resize an Index object to hold N columns total. Return SQLITE_OK
  102253. ** on success and SQLITE_NOMEM on an OOM error.
  102254. */
  102255. static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
  102256. char *zExtra;
  102257. int nByte;
  102258. if( pIdx->nColumn>=N ) return SQLITE_OK;
  102259. assert( pIdx->isResized==0 );
  102260. nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
  102261. zExtra = sqlite3DbMallocZero(db, nByte);
  102262. if( zExtra==0 ) return SQLITE_NOMEM_BKPT;
  102263. memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
  102264. pIdx->azColl = (const char**)zExtra;
  102265. zExtra += sizeof(char*)*N;
  102266. memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
  102267. pIdx->aiColumn = (i16*)zExtra;
  102268. zExtra += sizeof(i16)*N;
  102269. memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
  102270. pIdx->aSortOrder = (u8*)zExtra;
  102271. pIdx->nColumn = N;
  102272. pIdx->isResized = 1;
  102273. return SQLITE_OK;
  102274. }
  102275. /*
  102276. ** Estimate the total row width for a table.
  102277. */
  102278. static void estimateTableWidth(Table *pTab){
  102279. unsigned wTable = 0;
  102280. const Column *pTabCol;
  102281. int i;
  102282. for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
  102283. wTable += pTabCol->szEst;
  102284. }
  102285. if( pTab->iPKey<0 ) wTable++;
  102286. pTab->szTabRow = sqlite3LogEst(wTable*4);
  102287. }
  102288. /*
  102289. ** Estimate the average size of a row for an index.
  102290. */
  102291. static void estimateIndexWidth(Index *pIdx){
  102292. unsigned wIndex = 0;
  102293. int i;
  102294. const Column *aCol = pIdx->pTable->aCol;
  102295. for(i=0; i<pIdx->nColumn; i++){
  102296. i16 x = pIdx->aiColumn[i];
  102297. assert( x<pIdx->pTable->nCol );
  102298. wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
  102299. }
  102300. pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
  102301. }
  102302. /* Return true if column number x is any of the first nCol entries of aiCol[].
  102303. ** This is used to determine if the column number x appears in any of the
  102304. ** first nCol entries of an index.
  102305. */
  102306. static int hasColumn(const i16 *aiCol, int nCol, int x){
  102307. while( nCol-- > 0 ){
  102308. assert( aiCol[0]>=0 );
  102309. if( x==*(aiCol++) ){
  102310. return 1;
  102311. }
  102312. }
  102313. return 0;
  102314. }
  102315. /*
  102316. ** Return true if any of the first nKey entries of index pIdx exactly
  102317. ** match the iCol-th entry of pPk. pPk is always a WITHOUT ROWID
  102318. ** PRIMARY KEY index. pIdx is an index on the same table. pIdx may
  102319. ** or may not be the same index as pPk.
  102320. **
  102321. ** The first nKey entries of pIdx are guaranteed to be ordinary columns,
  102322. ** not a rowid or expression.
  102323. **
  102324. ** This routine differs from hasColumn() in that both the column and the
  102325. ** collating sequence must match for this routine, but for hasColumn() only
  102326. ** the column name must match.
  102327. */
  102328. static int isDupColumn(Index *pIdx, int nKey, Index *pPk, int iCol){
  102329. int i, j;
  102330. assert( nKey<=pIdx->nColumn );
  102331. assert( iCol<MAX(pPk->nColumn,pPk->nKeyCol) );
  102332. assert( pPk->idxType==SQLITE_IDXTYPE_PRIMARYKEY );
  102333. assert( pPk->pTable->tabFlags & TF_WithoutRowid );
  102334. assert( pPk->pTable==pIdx->pTable );
  102335. testcase( pPk==pIdx );
  102336. j = pPk->aiColumn[iCol];
  102337. assert( j!=XN_ROWID && j!=XN_EXPR );
  102338. for(i=0; i<nKey; i++){
  102339. assert( pIdx->aiColumn[i]>=0 || j>=0 );
  102340. if( pIdx->aiColumn[i]==j
  102341. && sqlite3StrICmp(pIdx->azColl[i], pPk->azColl[iCol])==0
  102342. ){
  102343. return 1;
  102344. }
  102345. }
  102346. return 0;
  102347. }
  102348. /* Recompute the colNotIdxed field of the Index.
  102349. **
  102350. ** colNotIdxed is a bitmask that has a 0 bit representing each indexed
  102351. ** columns that are within the first 63 columns of the table. The
  102352. ** high-order bit of colNotIdxed is always 1. All unindexed columns
  102353. ** of the table have a 1.
  102354. **
  102355. ** The colNotIdxed mask is AND-ed with the SrcList.a[].colUsed mask
  102356. ** to determine if the index is covering index.
  102357. */
  102358. static void recomputeColumnsNotIndexed(Index *pIdx){
  102359. Bitmask m = 0;
  102360. int j;
  102361. for(j=pIdx->nColumn-1; j>=0; j--){
  102362. int x = pIdx->aiColumn[j];
  102363. if( x>=0 ){
  102364. testcase( x==BMS-1 );
  102365. testcase( x==BMS-2 );
  102366. if( x<BMS-1 ) m |= MASKBIT(x);
  102367. }
  102368. }
  102369. pIdx->colNotIdxed = ~m;
  102370. assert( (pIdx->colNotIdxed>>63)==1 );
  102371. }
  102372. /*
  102373. ** This routine runs at the end of parsing a CREATE TABLE statement that
  102374. ** has a WITHOUT ROWID clause. The job of this routine is to convert both
  102375. ** internal schema data structures and the generated VDBE code so that they
  102376. ** are appropriate for a WITHOUT ROWID table instead of a rowid table.
  102377. ** Changes include:
  102378. **
  102379. ** (1) Set all columns of the PRIMARY KEY schema object to be NOT NULL.
  102380. ** (2) Convert P3 parameter of the OP_CreateBtree from BTREE_INTKEY
  102381. ** into BTREE_BLOBKEY.
  102382. ** (3) Bypass the creation of the sqlite_master table entry
  102383. ** for the PRIMARY KEY as the primary key index is now
  102384. ** identified by the sqlite_master table entry of the table itself.
  102385. ** (4) Set the Index.tnum of the PRIMARY KEY Index object in the
  102386. ** schema to the rootpage from the main table.
  102387. ** (5) Add all table columns to the PRIMARY KEY Index object
  102388. ** so that the PRIMARY KEY is a covering index. The surplus
  102389. ** columns are part of KeyInfo.nAllField and are not used for
  102390. ** sorting or lookup or uniqueness checks.
  102391. ** (6) Replace the rowid tail on all automatically generated UNIQUE
  102392. ** indices with the PRIMARY KEY columns.
  102393. **
  102394. ** For virtual tables, only (1) is performed.
  102395. */
  102396. static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
  102397. Index *pIdx;
  102398. Index *pPk;
  102399. int nPk;
  102400. int i, j;
  102401. sqlite3 *db = pParse->db;
  102402. Vdbe *v = pParse->pVdbe;
  102403. /* Mark every PRIMARY KEY column as NOT NULL (except for imposter tables)
  102404. */
  102405. if( !db->init.imposterTable ){
  102406. for(i=0; i<pTab->nCol; i++){
  102407. if( (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0 ){
  102408. pTab->aCol[i].notNull = OE_Abort;
  102409. }
  102410. }
  102411. }
  102412. /* Convert the P3 operand of the OP_CreateBtree opcode from BTREE_INTKEY
  102413. ** into BTREE_BLOBKEY.
  102414. */
  102415. if( pParse->addrCrTab ){
  102416. assert( v );
  102417. sqlite3VdbeChangeP3(v, pParse->addrCrTab, BTREE_BLOBKEY);
  102418. }
  102419. /* Locate the PRIMARY KEY index. Or, if this table was originally
  102420. ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
  102421. */
  102422. if( pTab->iPKey>=0 ){
  102423. ExprList *pList;
  102424. Token ipkToken;
  102425. sqlite3TokenInit(&ipkToken, pTab->aCol[pTab->iPKey].zName);
  102426. pList = sqlite3ExprListAppend(pParse, 0,
  102427. sqlite3ExprAlloc(db, TK_ID, &ipkToken, 0));
  102428. if( pList==0 ) return;
  102429. if( IN_RENAME_OBJECT ){
  102430. sqlite3RenameTokenRemap(pParse, pList->a[0].pExpr, &pTab->iPKey);
  102431. }
  102432. pList->a[0].sortOrder = pParse->iPkSortOrder;
  102433. assert( pParse->pNewTable==pTab );
  102434. pTab->iPKey = -1;
  102435. sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0,
  102436. SQLITE_IDXTYPE_PRIMARYKEY);
  102437. if( db->mallocFailed || pParse->nErr ) return;
  102438. pPk = sqlite3PrimaryKeyIndex(pTab);
  102439. }else{
  102440. pPk = sqlite3PrimaryKeyIndex(pTab);
  102441. assert( pPk!=0 );
  102442. /*
  102443. ** Remove all redundant columns from the PRIMARY KEY. For example, change
  102444. ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)". Later
  102445. ** code assumes the PRIMARY KEY contains no repeated columns.
  102446. */
  102447. for(i=j=1; i<pPk->nKeyCol; i++){
  102448. if( isDupColumn(pPk, j, pPk, i) ){
  102449. pPk->nColumn--;
  102450. }else{
  102451. testcase( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) );
  102452. pPk->aiColumn[j++] = pPk->aiColumn[i];
  102453. }
  102454. }
  102455. pPk->nKeyCol = j;
  102456. }
  102457. assert( pPk!=0 );
  102458. pPk->isCovering = 1;
  102459. if( !db->init.imposterTable ) pPk->uniqNotNull = 1;
  102460. nPk = pPk->nKeyCol;
  102461. /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
  102462. ** table entry. This is only required if currently generating VDBE
  102463. ** code for a CREATE TABLE (not when parsing one as part of reading
  102464. ** a database schema). */
  102465. if( v && pPk->tnum>0 ){
  102466. assert( db->init.busy==0 );
  102467. sqlite3VdbeChangeOpcode(v, pPk->tnum, OP_Goto);
  102468. }
  102469. /* The root page of the PRIMARY KEY is the table root page */
  102470. pPk->tnum = pTab->tnum;
  102471. /* Update the in-memory representation of all UNIQUE indices by converting
  102472. ** the final rowid column into one or more columns of the PRIMARY KEY.
  102473. */
  102474. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  102475. int n;
  102476. if( IsPrimaryKeyIndex(pIdx) ) continue;
  102477. for(i=n=0; i<nPk; i++){
  102478. if( !isDupColumn(pIdx, pIdx->nKeyCol, pPk, i) ){
  102479. testcase( hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) );
  102480. n++;
  102481. }
  102482. }
  102483. if( n==0 ){
  102484. /* This index is a superset of the primary key */
  102485. pIdx->nColumn = pIdx->nKeyCol;
  102486. continue;
  102487. }
  102488. if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
  102489. for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
  102490. if( !isDupColumn(pIdx, pIdx->nKeyCol, pPk, i) ){
  102491. testcase( hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) );
  102492. pIdx->aiColumn[j] = pPk->aiColumn[i];
  102493. pIdx->azColl[j] = pPk->azColl[i];
  102494. if( pPk->aSortOrder[i] ){
  102495. /* See ticket https://www.sqlite.org/src/info/bba7b69f9849b5bf */
  102496. pIdx->bAscKeyBug = 1;
  102497. }
  102498. j++;
  102499. }
  102500. }
  102501. assert( pIdx->nColumn>=pIdx->nKeyCol+n );
  102502. assert( pIdx->nColumn>=j );
  102503. }
  102504. /* Add all table columns to the PRIMARY KEY index
  102505. */
  102506. if( nPk<pTab->nCol ){
  102507. if( resizeIndexObject(db, pPk, pTab->nCol) ) return;
  102508. for(i=0, j=nPk; i<pTab->nCol; i++){
  102509. if( !hasColumn(pPk->aiColumn, j, i) ){
  102510. assert( j<pPk->nColumn );
  102511. pPk->aiColumn[j] = i;
  102512. pPk->azColl[j] = sqlite3StrBINARY;
  102513. j++;
  102514. }
  102515. }
  102516. assert( pPk->nColumn==j );
  102517. assert( pTab->nCol==j );
  102518. }else{
  102519. pPk->nColumn = pTab->nCol;
  102520. }
  102521. recomputeColumnsNotIndexed(pPk);
  102522. }
  102523. #ifndef SQLITE_OMIT_VIRTUALTABLE
  102524. /*
  102525. ** Return true if zName is a shadow table name in the current database
  102526. ** connection.
  102527. **
  102528. ** zName is temporarily modified while this routine is running, but is
  102529. ** restored to its original value prior to this routine returning.
  102530. */
  102531. static int isShadowTableName(sqlite3 *db, char *zName){
  102532. char *zTail; /* Pointer to the last "_" in zName */
  102533. Table *pTab; /* Table that zName is a shadow of */
  102534. Module *pMod; /* Module for the virtual table */
  102535. zTail = strrchr(zName, '_');
  102536. if( zTail==0 ) return 0;
  102537. *zTail = 0;
  102538. pTab = sqlite3FindTable(db, zName, 0);
  102539. *zTail = '_';
  102540. if( pTab==0 ) return 0;
  102541. if( !IsVirtual(pTab) ) return 0;
  102542. pMod = (Module*)sqlite3HashFind(&db->aModule, pTab->azModuleArg[0]);
  102543. if( pMod==0 ) return 0;
  102544. if( pMod->pModule->iVersion<3 ) return 0;
  102545. if( pMod->pModule->xShadowName==0 ) return 0;
  102546. return pMod->pModule->xShadowName(zTail+1);
  102547. }
  102548. #else
  102549. # define isShadowTableName(x,y) 0
  102550. #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
  102551. /*
  102552. ** This routine is called to report the final ")" that terminates
  102553. ** a CREATE TABLE statement.
  102554. **
  102555. ** The table structure that other action routines have been building
  102556. ** is added to the internal hash tables, assuming no errors have
  102557. ** occurred.
  102558. **
  102559. ** An entry for the table is made in the master table on disk, unless
  102560. ** this is a temporary table or db->init.busy==1. When db->init.busy==1
  102561. ** it means we are reading the sqlite_master table because we just
  102562. ** connected to the database or because the sqlite_master table has
  102563. ** recently changed, so the entry for this table already exists in
  102564. ** the sqlite_master table. We do not want to create it again.
  102565. **
  102566. ** If the pSelect argument is not NULL, it means that this routine
  102567. ** was called to create a table generated from a
  102568. ** "CREATE TABLE ... AS SELECT ..." statement. The column names of
  102569. ** the new table will match the result set of the SELECT.
  102570. */
  102571. SQLITE_PRIVATE void sqlite3EndTable(
  102572. Parse *pParse, /* Parse context */
  102573. Token *pCons, /* The ',' token after the last column defn. */
  102574. Token *pEnd, /* The ')' before options in the CREATE TABLE */
  102575. u8 tabOpts, /* Extra table options. Usually 0. */
  102576. Select *pSelect /* Select from a "CREATE ... AS SELECT" */
  102577. ){
  102578. Table *p; /* The new table */
  102579. sqlite3 *db = pParse->db; /* The database connection */
  102580. int iDb; /* Database in which the table lives */
  102581. Index *pIdx; /* An implied index of the table */
  102582. if( pEnd==0 && pSelect==0 ){
  102583. return;
  102584. }
  102585. assert( !db->mallocFailed );
  102586. p = pParse->pNewTable;
  102587. if( p==0 ) return;
  102588. if( pSelect==0 && isShadowTableName(db, p->zName) ){
  102589. p->tabFlags |= TF_Shadow;
  102590. }
  102591. /* If the db->init.busy is 1 it means we are reading the SQL off the
  102592. ** "sqlite_master" or "sqlite_temp_master" table on the disk.
  102593. ** So do not write to the disk again. Extract the root page number
  102594. ** for the table from the db->init.newTnum field. (The page number
  102595. ** should have been put there by the sqliteOpenCb routine.)
  102596. **
  102597. ** If the root page number is 1, that means this is the sqlite_master
  102598. ** table itself. So mark it read-only.
  102599. */
  102600. if( db->init.busy ){
  102601. if( pSelect ){
  102602. sqlite3ErrorMsg(pParse, "");
  102603. return;
  102604. }
  102605. p->tnum = db->init.newTnum;
  102606. if( p->tnum==1 ) p->tabFlags |= TF_Readonly;
  102607. }
  102608. assert( (p->tabFlags & TF_HasPrimaryKey)==0
  102609. || p->iPKey>=0 || sqlite3PrimaryKeyIndex(p)!=0 );
  102610. assert( (p->tabFlags & TF_HasPrimaryKey)!=0
  102611. || (p->iPKey<0 && sqlite3PrimaryKeyIndex(p)==0) );
  102612. /* Special processing for WITHOUT ROWID Tables */
  102613. if( tabOpts & TF_WithoutRowid ){
  102614. if( (p->tabFlags & TF_Autoincrement) ){
  102615. sqlite3ErrorMsg(pParse,
  102616. "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
  102617. return;
  102618. }
  102619. if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
  102620. sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
  102621. }else{
  102622. p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid;
  102623. convertToWithoutRowidTable(pParse, p);
  102624. }
  102625. }
  102626. iDb = sqlite3SchemaToIndex(db, p->pSchema);
  102627. #ifndef SQLITE_OMIT_CHECK
  102628. /* Resolve names in all CHECK constraint expressions.
  102629. */
  102630. if( p->pCheck ){
  102631. sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
  102632. }
  102633. #endif /* !defined(SQLITE_OMIT_CHECK) */
  102634. /* Estimate the average row size for the table and for all implied indices */
  102635. estimateTableWidth(p);
  102636. for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
  102637. estimateIndexWidth(pIdx);
  102638. }
  102639. /* If not initializing, then create a record for the new table
  102640. ** in the SQLITE_MASTER table of the database.
  102641. **
  102642. ** If this is a TEMPORARY table, write the entry into the auxiliary
  102643. ** file instead of into the main database file.
  102644. */
  102645. if( !db->init.busy ){
  102646. int n;
  102647. Vdbe *v;
  102648. char *zType; /* "view" or "table" */
  102649. char *zType2; /* "VIEW" or "TABLE" */
  102650. char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
  102651. v = sqlite3GetVdbe(pParse);
  102652. if( NEVER(v==0) ) return;
  102653. sqlite3VdbeAddOp1(v, OP_Close, 0);
  102654. /*
  102655. ** Initialize zType for the new view or table.
  102656. */
  102657. if( p->pSelect==0 ){
  102658. /* A regular table */
  102659. zType = "table";
  102660. zType2 = "TABLE";
  102661. #ifndef SQLITE_OMIT_VIEW
  102662. }else{
  102663. /* A view */
  102664. zType = "view";
  102665. zType2 = "VIEW";
  102666. #endif
  102667. }
  102668. /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
  102669. ** statement to populate the new table. The root-page number for the
  102670. ** new table is in register pParse->regRoot.
  102671. **
  102672. ** Once the SELECT has been coded by sqlite3Select(), it is in a
  102673. ** suitable state to query for the column names and types to be used
  102674. ** by the new table.
  102675. **
  102676. ** A shared-cache write-lock is not required to write to the new table,
  102677. ** as a schema-lock must have already been obtained to create it. Since
  102678. ** a schema-lock excludes all other database users, the write-lock would
  102679. ** be redundant.
  102680. */
  102681. if( pSelect ){
  102682. SelectDest dest; /* Where the SELECT should store results */
  102683. int regYield; /* Register holding co-routine entry-point */
  102684. int addrTop; /* Top of the co-routine */
  102685. int regRec; /* A record to be insert into the new table */
  102686. int regRowid; /* Rowid of the next row to insert */
  102687. int addrInsLoop; /* Top of the loop for inserting rows */
  102688. Table *pSelTab; /* A table that describes the SELECT results */
  102689. regYield = ++pParse->nMem;
  102690. regRec = ++pParse->nMem;
  102691. regRowid = ++pParse->nMem;
  102692. assert(pParse->nTab==1);
  102693. sqlite3MayAbort(pParse);
  102694. sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
  102695. sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
  102696. pParse->nTab = 2;
  102697. addrTop = sqlite3VdbeCurrentAddr(v) + 1;
  102698. sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
  102699. if( pParse->nErr ) return;
  102700. pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
  102701. if( pSelTab==0 ) return;
  102702. assert( p->aCol==0 );
  102703. p->nCol = pSelTab->nCol;
  102704. p->aCol = pSelTab->aCol;
  102705. pSelTab->nCol = 0;
  102706. pSelTab->aCol = 0;
  102707. sqlite3DeleteTable(db, pSelTab);
  102708. sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
  102709. sqlite3Select(pParse, pSelect, &dest);
  102710. if( pParse->nErr ) return;
  102711. sqlite3VdbeEndCoroutine(v, regYield);
  102712. sqlite3VdbeJumpHere(v, addrTop - 1);
  102713. addrInsLoop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
  102714. VdbeCoverage(v);
  102715. sqlite3VdbeAddOp3(v, OP_MakeRecord, dest.iSdst, dest.nSdst, regRec);
  102716. sqlite3TableAffinity(v, p, 0);
  102717. sqlite3VdbeAddOp2(v, OP_NewRowid, 1, regRowid);
  102718. sqlite3VdbeAddOp3(v, OP_Insert, 1, regRec, regRowid);
  102719. sqlite3VdbeGoto(v, addrInsLoop);
  102720. sqlite3VdbeJumpHere(v, addrInsLoop);
  102721. sqlite3VdbeAddOp1(v, OP_Close, 1);
  102722. }
  102723. /* Compute the complete text of the CREATE statement */
  102724. if( pSelect ){
  102725. zStmt = createTableStmt(db, p);
  102726. }else{
  102727. Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
  102728. n = (int)(pEnd2->z - pParse->sNameToken.z);
  102729. if( pEnd2->z[0]!=';' ) n += pEnd2->n;
  102730. zStmt = sqlite3MPrintf(db,
  102731. "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
  102732. );
  102733. }
  102734. /* A slot for the record has already been allocated in the
  102735. ** SQLITE_MASTER table. We just need to update that slot with all
  102736. ** the information we've collected.
  102737. */
  102738. sqlite3NestedParse(pParse,
  102739. "UPDATE %Q.%s "
  102740. "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
  102741. "WHERE rowid=#%d",
  102742. db->aDb[iDb].zDbSName, MASTER_NAME,
  102743. zType,
  102744. p->zName,
  102745. p->zName,
  102746. pParse->regRoot,
  102747. zStmt,
  102748. pParse->regRowid
  102749. );
  102750. sqlite3DbFree(db, zStmt);
  102751. sqlite3ChangeCookie(pParse, iDb);
  102752. #ifndef SQLITE_OMIT_AUTOINCREMENT
  102753. /* Check to see if we need to create an sqlite_sequence table for
  102754. ** keeping track of autoincrement keys.
  102755. */
  102756. if( (p->tabFlags & TF_Autoincrement)!=0 ){
  102757. Db *pDb = &db->aDb[iDb];
  102758. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  102759. if( pDb->pSchema->pSeqTab==0 ){
  102760. sqlite3NestedParse(pParse,
  102761. "CREATE TABLE %Q.sqlite_sequence(name,seq)",
  102762. pDb->zDbSName
  102763. );
  102764. }
  102765. }
  102766. #endif
  102767. /* Reparse everything to update our internal data structures */
  102768. sqlite3VdbeAddParseSchemaOp(v, iDb,
  102769. sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
  102770. }
  102771. /* Add the table to the in-memory representation of the database.
  102772. */
  102773. if( db->init.busy ){
  102774. Table *pOld;
  102775. Schema *pSchema = p->pSchema;
  102776. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  102777. pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
  102778. if( pOld ){
  102779. assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
  102780. sqlite3OomFault(db);
  102781. return;
  102782. }
  102783. pParse->pNewTable = 0;
  102784. db->mDbFlags |= DBFLAG_SchemaChange;
  102785. #ifndef SQLITE_OMIT_ALTERTABLE
  102786. if( !p->pSelect ){
  102787. const char *zName = (const char *)pParse->sNameToken.z;
  102788. int nName;
  102789. assert( !pSelect && pCons && pEnd );
  102790. if( pCons->z==0 ){
  102791. pCons = pEnd;
  102792. }
  102793. nName = (int)((const char *)pCons->z - zName);
  102794. p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
  102795. }
  102796. #endif
  102797. }
  102798. }
  102799. #ifndef SQLITE_OMIT_VIEW
  102800. /*
  102801. ** The parser calls this routine in order to create a new VIEW
  102802. */
  102803. SQLITE_PRIVATE void sqlite3CreateView(
  102804. Parse *pParse, /* The parsing context */
  102805. Token *pBegin, /* The CREATE token that begins the statement */
  102806. Token *pName1, /* The token that holds the name of the view */
  102807. Token *pName2, /* The token that holds the name of the view */
  102808. ExprList *pCNames, /* Optional list of view column names */
  102809. Select *pSelect, /* A SELECT statement that will become the new view */
  102810. int isTemp, /* TRUE for a TEMPORARY view */
  102811. int noErr /* Suppress error messages if VIEW already exists */
  102812. ){
  102813. Table *p;
  102814. int n;
  102815. const char *z;
  102816. Token sEnd;
  102817. DbFixer sFix;
  102818. Token *pName = 0;
  102819. int iDb;
  102820. sqlite3 *db = pParse->db;
  102821. if( pParse->nVar>0 ){
  102822. sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
  102823. goto create_view_fail;
  102824. }
  102825. sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
  102826. p = pParse->pNewTable;
  102827. if( p==0 || pParse->nErr ) goto create_view_fail;
  102828. sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  102829. iDb = sqlite3SchemaToIndex(db, p->pSchema);
  102830. sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
  102831. if( sqlite3FixSelect(&sFix, pSelect) ) goto create_view_fail;
  102832. /* Make a copy of the entire SELECT statement that defines the view.
  102833. ** This will force all the Expr.token.z values to be dynamically
  102834. ** allocated rather than point to the input string - which means that
  102835. ** they will persist after the current sqlite3_exec() call returns.
  102836. */
  102837. if( IN_RENAME_OBJECT ){
  102838. p->pSelect = pSelect;
  102839. pSelect = 0;
  102840. }else{
  102841. p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  102842. }
  102843. p->pCheck = sqlite3ExprListDup(db, pCNames, EXPRDUP_REDUCE);
  102844. if( db->mallocFailed ) goto create_view_fail;
  102845. /* Locate the end of the CREATE VIEW statement. Make sEnd point to
  102846. ** the end.
  102847. */
  102848. sEnd = pParse->sLastToken;
  102849. assert( sEnd.z[0]!=0 || sEnd.n==0 );
  102850. if( sEnd.z[0]!=';' ){
  102851. sEnd.z += sEnd.n;
  102852. }
  102853. sEnd.n = 0;
  102854. n = (int)(sEnd.z - pBegin->z);
  102855. assert( n>0 );
  102856. z = pBegin->z;
  102857. while( sqlite3Isspace(z[n-1]) ){ n--; }
  102858. sEnd.z = &z[n-1];
  102859. sEnd.n = 1;
  102860. /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
  102861. sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
  102862. create_view_fail:
  102863. sqlite3SelectDelete(db, pSelect);
  102864. if( IN_RENAME_OBJECT ){
  102865. sqlite3RenameExprlistUnmap(pParse, pCNames);
  102866. }
  102867. sqlite3ExprListDelete(db, pCNames);
  102868. return;
  102869. }
  102870. #endif /* SQLITE_OMIT_VIEW */
  102871. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  102872. /*
  102873. ** The Table structure pTable is really a VIEW. Fill in the names of
  102874. ** the columns of the view in the pTable structure. Return the number
  102875. ** of errors. If an error is seen leave an error message in pParse->zErrMsg.
  102876. */
  102877. SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
  102878. Table *pSelTab; /* A fake table from which we get the result set */
  102879. Select *pSel; /* Copy of the SELECT that implements the view */
  102880. int nErr = 0; /* Number of errors encountered */
  102881. int n; /* Temporarily holds the number of cursors assigned */
  102882. sqlite3 *db = pParse->db; /* Database connection for malloc errors */
  102883. #ifndef SQLITE_OMIT_VIRTUALTABLE
  102884. int rc;
  102885. #endif
  102886. #ifndef SQLITE_OMIT_AUTHORIZATION
  102887. sqlite3_xauth xAuth; /* Saved xAuth pointer */
  102888. #endif
  102889. assert( pTable );
  102890. #ifndef SQLITE_OMIT_VIRTUALTABLE
  102891. db->nSchemaLock++;
  102892. rc = sqlite3VtabCallConnect(pParse, pTable);
  102893. db->nSchemaLock--;
  102894. if( rc ){
  102895. return 1;
  102896. }
  102897. if( IsVirtual(pTable) ) return 0;
  102898. #endif
  102899. #ifndef SQLITE_OMIT_VIEW
  102900. /* A positive nCol means the columns names for this view are
  102901. ** already known.
  102902. */
  102903. if( pTable->nCol>0 ) return 0;
  102904. /* A negative nCol is a special marker meaning that we are currently
  102905. ** trying to compute the column names. If we enter this routine with
  102906. ** a negative nCol, it means two or more views form a loop, like this:
  102907. **
  102908. ** CREATE VIEW one AS SELECT * FROM two;
  102909. ** CREATE VIEW two AS SELECT * FROM one;
  102910. **
  102911. ** Actually, the error above is now caught prior to reaching this point.
  102912. ** But the following test is still important as it does come up
  102913. ** in the following:
  102914. **
  102915. ** CREATE TABLE main.ex1(a);
  102916. ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
  102917. ** SELECT * FROM temp.ex1;
  102918. */
  102919. if( pTable->nCol<0 ){
  102920. sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
  102921. return 1;
  102922. }
  102923. assert( pTable->nCol>=0 );
  102924. /* If we get this far, it means we need to compute the table names.
  102925. ** Note that the call to sqlite3ResultSetOfSelect() will expand any
  102926. ** "*" elements in the results set of the view and will assign cursors
  102927. ** to the elements of the FROM clause. But we do not want these changes
  102928. ** to be permanent. So the computation is done on a copy of the SELECT
  102929. ** statement that defines the view.
  102930. */
  102931. assert( pTable->pSelect );
  102932. pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
  102933. if( pSel ){
  102934. #ifndef SQLITE_OMIT_ALTERTABLE
  102935. u8 eParseMode = pParse->eParseMode;
  102936. pParse->eParseMode = PARSE_MODE_NORMAL;
  102937. #endif
  102938. n = pParse->nTab;
  102939. sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
  102940. pTable->nCol = -1;
  102941. db->lookaside.bDisable++;
  102942. #ifndef SQLITE_OMIT_AUTHORIZATION
  102943. xAuth = db->xAuth;
  102944. db->xAuth = 0;
  102945. pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
  102946. db->xAuth = xAuth;
  102947. #else
  102948. pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
  102949. #endif
  102950. pParse->nTab = n;
  102951. if( pTable->pCheck ){
  102952. /* CREATE VIEW name(arglist) AS ...
  102953. ** The names of the columns in the table are taken from
  102954. ** arglist which is stored in pTable->pCheck. The pCheck field
  102955. ** normally holds CHECK constraints on an ordinary table, but for
  102956. ** a VIEW it holds the list of column names.
  102957. */
  102958. sqlite3ColumnsFromExprList(pParse, pTable->pCheck,
  102959. &pTable->nCol, &pTable->aCol);
  102960. if( db->mallocFailed==0
  102961. && pParse->nErr==0
  102962. && pTable->nCol==pSel->pEList->nExpr
  102963. ){
  102964. sqlite3SelectAddColumnTypeAndCollation(pParse, pTable, pSel);
  102965. }
  102966. }else if( pSelTab ){
  102967. /* CREATE VIEW name AS... without an argument list. Construct
  102968. ** the column names from the SELECT statement that defines the view.
  102969. */
  102970. assert( pTable->aCol==0 );
  102971. pTable->nCol = pSelTab->nCol;
  102972. pTable->aCol = pSelTab->aCol;
  102973. pSelTab->nCol = 0;
  102974. pSelTab->aCol = 0;
  102975. assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
  102976. }else{
  102977. pTable->nCol = 0;
  102978. nErr++;
  102979. }
  102980. sqlite3DeleteTable(db, pSelTab);
  102981. sqlite3SelectDelete(db, pSel);
  102982. db->lookaside.bDisable--;
  102983. #ifndef SQLITE_OMIT_ALTERTABLE
  102984. pParse->eParseMode = eParseMode;
  102985. #endif
  102986. } else {
  102987. nErr++;
  102988. }
  102989. pTable->pSchema->schemaFlags |= DB_UnresetViews;
  102990. if( db->mallocFailed ){
  102991. sqlite3DeleteColumnNames(db, pTable);
  102992. pTable->aCol = 0;
  102993. pTable->nCol = 0;
  102994. }
  102995. #endif /* SQLITE_OMIT_VIEW */
  102996. return nErr;
  102997. }
  102998. #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
  102999. #ifndef SQLITE_OMIT_VIEW
  103000. /*
  103001. ** Clear the column names from every VIEW in database idx.
  103002. */
  103003. static void sqliteViewResetAll(sqlite3 *db, int idx){
  103004. HashElem *i;
  103005. assert( sqlite3SchemaMutexHeld(db, idx, 0) );
  103006. if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
  103007. for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
  103008. Table *pTab = sqliteHashData(i);
  103009. if( pTab->pSelect ){
  103010. sqlite3DeleteColumnNames(db, pTab);
  103011. pTab->aCol = 0;
  103012. pTab->nCol = 0;
  103013. }
  103014. }
  103015. DbClearProperty(db, idx, DB_UnresetViews);
  103016. }
  103017. #else
  103018. # define sqliteViewResetAll(A,B)
  103019. #endif /* SQLITE_OMIT_VIEW */
  103020. /*
  103021. ** This function is called by the VDBE to adjust the internal schema
  103022. ** used by SQLite when the btree layer moves a table root page. The
  103023. ** root-page of a table or index in database iDb has changed from iFrom
  103024. ** to iTo.
  103025. **
  103026. ** Ticket #1728: The symbol table might still contain information
  103027. ** on tables and/or indices that are the process of being deleted.
  103028. ** If you are unlucky, one of those deleted indices or tables might
  103029. ** have the same rootpage number as the real table or index that is
  103030. ** being moved. So we cannot stop searching after the first match
  103031. ** because the first match might be for one of the deleted indices
  103032. ** or tables and not the table/index that is actually being moved.
  103033. ** We must continue looping until all tables and indices with
  103034. ** rootpage==iFrom have been converted to have a rootpage of iTo
  103035. ** in order to be certain that we got the right one.
  103036. */
  103037. #ifndef SQLITE_OMIT_AUTOVACUUM
  103038. SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
  103039. HashElem *pElem;
  103040. Hash *pHash;
  103041. Db *pDb;
  103042. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  103043. pDb = &db->aDb[iDb];
  103044. pHash = &pDb->pSchema->tblHash;
  103045. for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
  103046. Table *pTab = sqliteHashData(pElem);
  103047. if( pTab->tnum==iFrom ){
  103048. pTab->tnum = iTo;
  103049. }
  103050. }
  103051. pHash = &pDb->pSchema->idxHash;
  103052. for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
  103053. Index *pIdx = sqliteHashData(pElem);
  103054. if( pIdx->tnum==iFrom ){
  103055. pIdx->tnum = iTo;
  103056. }
  103057. }
  103058. }
  103059. #endif
  103060. /*
  103061. ** Write code to erase the table with root-page iTable from database iDb.
  103062. ** Also write code to modify the sqlite_master table and internal schema
  103063. ** if a root-page of another table is moved by the btree-layer whilst
  103064. ** erasing iTable (this can happen with an auto-vacuum database).
  103065. */
  103066. static void destroyRootPage(Parse *pParse, int iTable, int iDb){
  103067. Vdbe *v = sqlite3GetVdbe(pParse);
  103068. int r1 = sqlite3GetTempReg(pParse);
  103069. if( iTable<2 ) sqlite3ErrorMsg(pParse, "corrupt schema");
  103070. sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
  103071. sqlite3MayAbort(pParse);
  103072. #ifndef SQLITE_OMIT_AUTOVACUUM
  103073. /* OP_Destroy stores an in integer r1. If this integer
  103074. ** is non-zero, then it is the root page number of a table moved to
  103075. ** location iTable. The following code modifies the sqlite_master table to
  103076. ** reflect this.
  103077. **
  103078. ** The "#NNN" in the SQL is a special constant that means whatever value
  103079. ** is in register NNN. See grammar rules associated with the TK_REGISTER
  103080. ** token for additional information.
  103081. */
  103082. sqlite3NestedParse(pParse,
  103083. "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
  103084. pParse->db->aDb[iDb].zDbSName, MASTER_NAME, iTable, r1, r1);
  103085. #endif
  103086. sqlite3ReleaseTempReg(pParse, r1);
  103087. }
  103088. /*
  103089. ** Write VDBE code to erase table pTab and all associated indices on disk.
  103090. ** Code to update the sqlite_master tables and internal schema definitions
  103091. ** in case a root-page belonging to another table is moved by the btree layer
  103092. ** is also added (this can happen with an auto-vacuum database).
  103093. */
  103094. static void destroyTable(Parse *pParse, Table *pTab){
  103095. /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
  103096. ** is not defined), then it is important to call OP_Destroy on the
  103097. ** table and index root-pages in order, starting with the numerically
  103098. ** largest root-page number. This guarantees that none of the root-pages
  103099. ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
  103100. ** following were coded:
  103101. **
  103102. ** OP_Destroy 4 0
  103103. ** ...
  103104. ** OP_Destroy 5 0
  103105. **
  103106. ** and root page 5 happened to be the largest root-page number in the
  103107. ** database, then root page 5 would be moved to page 4 by the
  103108. ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
  103109. ** a free-list page.
  103110. */
  103111. int iTab = pTab->tnum;
  103112. int iDestroyed = 0;
  103113. while( 1 ){
  103114. Index *pIdx;
  103115. int iLargest = 0;
  103116. if( iDestroyed==0 || iTab<iDestroyed ){
  103117. iLargest = iTab;
  103118. }
  103119. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  103120. int iIdx = pIdx->tnum;
  103121. assert( pIdx->pSchema==pTab->pSchema );
  103122. if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
  103123. iLargest = iIdx;
  103124. }
  103125. }
  103126. if( iLargest==0 ){
  103127. return;
  103128. }else{
  103129. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  103130. assert( iDb>=0 && iDb<pParse->db->nDb );
  103131. destroyRootPage(pParse, iLargest, iDb);
  103132. iDestroyed = iLargest;
  103133. }
  103134. }
  103135. }
  103136. /*
  103137. ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
  103138. ** after a DROP INDEX or DROP TABLE command.
  103139. */
  103140. static void sqlite3ClearStatTables(
  103141. Parse *pParse, /* The parsing context */
  103142. int iDb, /* The database number */
  103143. const char *zType, /* "idx" or "tbl" */
  103144. const char *zName /* Name of index or table */
  103145. ){
  103146. int i;
  103147. const char *zDbName = pParse->db->aDb[iDb].zDbSName;
  103148. for(i=1; i<=4; i++){
  103149. char zTab[24];
  103150. sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
  103151. if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
  103152. sqlite3NestedParse(pParse,
  103153. "DELETE FROM %Q.%s WHERE %s=%Q",
  103154. zDbName, zTab, zType, zName
  103155. );
  103156. }
  103157. }
  103158. }
  103159. /*
  103160. ** Generate code to drop a table.
  103161. */
  103162. SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
  103163. Vdbe *v;
  103164. sqlite3 *db = pParse->db;
  103165. Trigger *pTrigger;
  103166. Db *pDb = &db->aDb[iDb];
  103167. v = sqlite3GetVdbe(pParse);
  103168. assert( v!=0 );
  103169. sqlite3BeginWriteOperation(pParse, 1, iDb);
  103170. #ifndef SQLITE_OMIT_VIRTUALTABLE
  103171. if( IsVirtual(pTab) ){
  103172. sqlite3VdbeAddOp0(v, OP_VBegin);
  103173. }
  103174. #endif
  103175. /* Drop all triggers associated with the table being dropped. Code
  103176. ** is generated to remove entries from sqlite_master and/or
  103177. ** sqlite_temp_master if required.
  103178. */
  103179. pTrigger = sqlite3TriggerList(pParse, pTab);
  103180. while( pTrigger ){
  103181. assert( pTrigger->pSchema==pTab->pSchema ||
  103182. pTrigger->pSchema==db->aDb[1].pSchema );
  103183. sqlite3DropTriggerPtr(pParse, pTrigger);
  103184. pTrigger = pTrigger->pNext;
  103185. }
  103186. #ifndef SQLITE_OMIT_AUTOINCREMENT
  103187. /* Remove any entries of the sqlite_sequence table associated with
  103188. ** the table being dropped. This is done before the table is dropped
  103189. ** at the btree level, in case the sqlite_sequence table needs to
  103190. ** move as a result of the drop (can happen in auto-vacuum mode).
  103191. */
  103192. if( pTab->tabFlags & TF_Autoincrement ){
  103193. sqlite3NestedParse(pParse,
  103194. "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
  103195. pDb->zDbSName, pTab->zName
  103196. );
  103197. }
  103198. #endif
  103199. /* Drop all SQLITE_MASTER table and index entries that refer to the
  103200. ** table. The program name loops through the master table and deletes
  103201. ** every row that refers to a table of the same name as the one being
  103202. ** dropped. Triggers are handled separately because a trigger can be
  103203. ** created in the temp database that refers to a table in another
  103204. ** database.
  103205. */
  103206. sqlite3NestedParse(pParse,
  103207. "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
  103208. pDb->zDbSName, MASTER_NAME, pTab->zName);
  103209. if( !isView && !IsVirtual(pTab) ){
  103210. destroyTable(pParse, pTab);
  103211. }
  103212. /* Remove the table entry from SQLite's internal schema and modify
  103213. ** the schema cookie.
  103214. */
  103215. if( IsVirtual(pTab) ){
  103216. sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
  103217. sqlite3MayAbort(pParse);
  103218. }
  103219. sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
  103220. sqlite3ChangeCookie(pParse, iDb);
  103221. sqliteViewResetAll(db, iDb);
  103222. }
  103223. /*
  103224. ** This routine is called to do the work of a DROP TABLE statement.
  103225. ** pName is the name of the table to be dropped.
  103226. */
  103227. SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
  103228. Table *pTab;
  103229. Vdbe *v;
  103230. sqlite3 *db = pParse->db;
  103231. int iDb;
  103232. if( db->mallocFailed ){
  103233. goto exit_drop_table;
  103234. }
  103235. assert( pParse->nErr==0 );
  103236. assert( pName->nSrc==1 );
  103237. if( sqlite3ReadSchema(pParse) ) goto exit_drop_table;
  103238. if( noErr ) db->suppressErr++;
  103239. assert( isView==0 || isView==LOCATE_VIEW );
  103240. pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
  103241. if( noErr ) db->suppressErr--;
  103242. if( pTab==0 ){
  103243. if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
  103244. goto exit_drop_table;
  103245. }
  103246. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  103247. assert( iDb>=0 && iDb<db->nDb );
  103248. /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
  103249. ** it is initialized.
  103250. */
  103251. if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
  103252. goto exit_drop_table;
  103253. }
  103254. #ifndef SQLITE_OMIT_AUTHORIZATION
  103255. {
  103256. int code;
  103257. const char *zTab = SCHEMA_TABLE(iDb);
  103258. const char *zDb = db->aDb[iDb].zDbSName;
  103259. const char *zArg2 = 0;
  103260. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
  103261. goto exit_drop_table;
  103262. }
  103263. if( isView ){
  103264. if( !OMIT_TEMPDB && iDb==1 ){
  103265. code = SQLITE_DROP_TEMP_VIEW;
  103266. }else{
  103267. code = SQLITE_DROP_VIEW;
  103268. }
  103269. #ifndef SQLITE_OMIT_VIRTUALTABLE
  103270. }else if( IsVirtual(pTab) ){
  103271. code = SQLITE_DROP_VTABLE;
  103272. zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
  103273. #endif
  103274. }else{
  103275. if( !OMIT_TEMPDB && iDb==1 ){
  103276. code = SQLITE_DROP_TEMP_TABLE;
  103277. }else{
  103278. code = SQLITE_DROP_TABLE;
  103279. }
  103280. }
  103281. if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
  103282. goto exit_drop_table;
  103283. }
  103284. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
  103285. goto exit_drop_table;
  103286. }
  103287. }
  103288. #endif
  103289. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
  103290. && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
  103291. sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
  103292. goto exit_drop_table;
  103293. }
  103294. #ifndef SQLITE_OMIT_VIEW
  103295. /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
  103296. ** on a table.
  103297. */
  103298. if( isView && pTab->pSelect==0 ){
  103299. sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
  103300. goto exit_drop_table;
  103301. }
  103302. if( !isView && pTab->pSelect ){
  103303. sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
  103304. goto exit_drop_table;
  103305. }
  103306. #endif
  103307. /* Generate code to remove the table from the master table
  103308. ** on disk.
  103309. */
  103310. v = sqlite3GetVdbe(pParse);
  103311. if( v ){
  103312. sqlite3BeginWriteOperation(pParse, 1, iDb);
  103313. if( !isView ){
  103314. sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
  103315. sqlite3FkDropTable(pParse, pName, pTab);
  103316. }
  103317. sqlite3CodeDropTable(pParse, pTab, iDb, isView);
  103318. }
  103319. exit_drop_table:
  103320. sqlite3SrcListDelete(db, pName);
  103321. }
  103322. /*
  103323. ** This routine is called to create a new foreign key on the table
  103324. ** currently under construction. pFromCol determines which columns
  103325. ** in the current table point to the foreign key. If pFromCol==0 then
  103326. ** connect the key to the last column inserted. pTo is the name of
  103327. ** the table referred to (a.k.a the "parent" table). pToCol is a list
  103328. ** of tables in the parent pTo table. flags contains all
  103329. ** information about the conflict resolution algorithms specified
  103330. ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
  103331. **
  103332. ** An FKey structure is created and added to the table currently
  103333. ** under construction in the pParse->pNewTable field.
  103334. **
  103335. ** The foreign key is set for IMMEDIATE processing. A subsequent call
  103336. ** to sqlite3DeferForeignKey() might change this to DEFERRED.
  103337. */
  103338. SQLITE_PRIVATE void sqlite3CreateForeignKey(
  103339. Parse *pParse, /* Parsing context */
  103340. ExprList *pFromCol, /* Columns in this table that point to other table */
  103341. Token *pTo, /* Name of the other table */
  103342. ExprList *pToCol, /* Columns in the other table */
  103343. int flags /* Conflict resolution algorithms. */
  103344. ){
  103345. sqlite3 *db = pParse->db;
  103346. #ifndef SQLITE_OMIT_FOREIGN_KEY
  103347. FKey *pFKey = 0;
  103348. FKey *pNextTo;
  103349. Table *p = pParse->pNewTable;
  103350. int nByte;
  103351. int i;
  103352. int nCol;
  103353. char *z;
  103354. assert( pTo!=0 );
  103355. if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
  103356. if( pFromCol==0 ){
  103357. int iCol = p->nCol-1;
  103358. if( NEVER(iCol<0) ) goto fk_end;
  103359. if( pToCol && pToCol->nExpr!=1 ){
  103360. sqlite3ErrorMsg(pParse, "foreign key on %s"
  103361. " should reference only one column of table %T",
  103362. p->aCol[iCol].zName, pTo);
  103363. goto fk_end;
  103364. }
  103365. nCol = 1;
  103366. }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
  103367. sqlite3ErrorMsg(pParse,
  103368. "number of columns in foreign key does not match the number of "
  103369. "columns in the referenced table");
  103370. goto fk_end;
  103371. }else{
  103372. nCol = pFromCol->nExpr;
  103373. }
  103374. nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
  103375. if( pToCol ){
  103376. for(i=0; i<pToCol->nExpr; i++){
  103377. nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
  103378. }
  103379. }
  103380. pFKey = sqlite3DbMallocZero(db, nByte );
  103381. if( pFKey==0 ){
  103382. goto fk_end;
  103383. }
  103384. pFKey->pFrom = p;
  103385. pFKey->pNextFrom = p->pFKey;
  103386. z = (char*)&pFKey->aCol[nCol];
  103387. pFKey->zTo = z;
  103388. if( IN_RENAME_OBJECT ){
  103389. sqlite3RenameTokenMap(pParse, (void*)z, pTo);
  103390. }
  103391. memcpy(z, pTo->z, pTo->n);
  103392. z[pTo->n] = 0;
  103393. sqlite3Dequote(z);
  103394. z += pTo->n+1;
  103395. pFKey->nCol = nCol;
  103396. if( pFromCol==0 ){
  103397. pFKey->aCol[0].iFrom = p->nCol-1;
  103398. }else{
  103399. for(i=0; i<nCol; i++){
  103400. int j;
  103401. for(j=0; j<p->nCol; j++){
  103402. if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
  103403. pFKey->aCol[i].iFrom = j;
  103404. break;
  103405. }
  103406. }
  103407. if( j>=p->nCol ){
  103408. sqlite3ErrorMsg(pParse,
  103409. "unknown column \"%s\" in foreign key definition",
  103410. pFromCol->a[i].zName);
  103411. goto fk_end;
  103412. }
  103413. if( IN_RENAME_OBJECT ){
  103414. sqlite3RenameTokenRemap(pParse, &pFKey->aCol[i], pFromCol->a[i].zName);
  103415. }
  103416. }
  103417. }
  103418. if( pToCol ){
  103419. for(i=0; i<nCol; i++){
  103420. int n = sqlite3Strlen30(pToCol->a[i].zName);
  103421. pFKey->aCol[i].zCol = z;
  103422. if( IN_RENAME_OBJECT ){
  103423. sqlite3RenameTokenRemap(pParse, z, pToCol->a[i].zName);
  103424. }
  103425. memcpy(z, pToCol->a[i].zName, n);
  103426. z[n] = 0;
  103427. z += n+1;
  103428. }
  103429. }
  103430. pFKey->isDeferred = 0;
  103431. pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
  103432. pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
  103433. assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
  103434. pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
  103435. pFKey->zTo, (void *)pFKey
  103436. );
  103437. if( pNextTo==pFKey ){
  103438. sqlite3OomFault(db);
  103439. goto fk_end;
  103440. }
  103441. if( pNextTo ){
  103442. assert( pNextTo->pPrevTo==0 );
  103443. pFKey->pNextTo = pNextTo;
  103444. pNextTo->pPrevTo = pFKey;
  103445. }
  103446. /* Link the foreign key to the table as the last step.
  103447. */
  103448. p->pFKey = pFKey;
  103449. pFKey = 0;
  103450. fk_end:
  103451. sqlite3DbFree(db, pFKey);
  103452. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  103453. sqlite3ExprListDelete(db, pFromCol);
  103454. sqlite3ExprListDelete(db, pToCol);
  103455. }
  103456. /*
  103457. ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
  103458. ** clause is seen as part of a foreign key definition. The isDeferred
  103459. ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
  103460. ** The behavior of the most recently created foreign key is adjusted
  103461. ** accordingly.
  103462. */
  103463. SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
  103464. #ifndef SQLITE_OMIT_FOREIGN_KEY
  103465. Table *pTab;
  103466. FKey *pFKey;
  103467. if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
  103468. assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
  103469. pFKey->isDeferred = (u8)isDeferred;
  103470. #endif
  103471. }
  103472. /*
  103473. ** Generate code that will erase and refill index *pIdx. This is
  103474. ** used to initialize a newly created index or to recompute the
  103475. ** content of an index in response to a REINDEX command.
  103476. **
  103477. ** if memRootPage is not negative, it means that the index is newly
  103478. ** created. The register specified by memRootPage contains the
  103479. ** root page number of the index. If memRootPage is negative, then
  103480. ** the index already exists and must be cleared before being refilled and
  103481. ** the root page number of the index is taken from pIndex->tnum.
  103482. */
  103483. static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
  103484. Table *pTab = pIndex->pTable; /* The table that is indexed */
  103485. int iTab = pParse->nTab++; /* Btree cursor used for pTab */
  103486. int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
  103487. int iSorter; /* Cursor opened by OpenSorter (if in use) */
  103488. int addr1; /* Address of top of loop */
  103489. int addr2; /* Address to jump to for next iteration */
  103490. int tnum; /* Root page of index */
  103491. int iPartIdxLabel; /* Jump to this label to skip a row */
  103492. Vdbe *v; /* Generate code into this virtual machine */
  103493. KeyInfo *pKey; /* KeyInfo for index */
  103494. int regRecord; /* Register holding assembled index record */
  103495. sqlite3 *db = pParse->db; /* The database connection */
  103496. int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
  103497. #ifndef SQLITE_OMIT_AUTHORIZATION
  103498. if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
  103499. db->aDb[iDb].zDbSName ) ){
  103500. return;
  103501. }
  103502. #endif
  103503. /* Require a write-lock on the table to perform this operation */
  103504. sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
  103505. v = sqlite3GetVdbe(pParse);
  103506. if( v==0 ) return;
  103507. if( memRootPage>=0 ){
  103508. tnum = memRootPage;
  103509. }else{
  103510. tnum = pIndex->tnum;
  103511. }
  103512. pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
  103513. assert( pKey!=0 || db->mallocFailed || pParse->nErr );
  103514. /* Open the sorter cursor if we are to use one. */
  103515. iSorter = pParse->nTab++;
  103516. sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
  103517. sqlite3KeyInfoRef(pKey), P4_KEYINFO);
  103518. /* Open the table. Loop through all rows of the table, inserting index
  103519. ** records into the sorter. */
  103520. sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  103521. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
  103522. regRecord = sqlite3GetTempReg(pParse);
  103523. sqlite3MultiWrite(pParse);
  103524. sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
  103525. sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
  103526. sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
  103527. sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
  103528. sqlite3VdbeJumpHere(v, addr1);
  103529. if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
  103530. sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
  103531. (char *)pKey, P4_KEYINFO);
  103532. sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
  103533. addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
  103534. if( IsUniqueIndex(pIndex) ){
  103535. int j2 = sqlite3VdbeGoto(v, 1);
  103536. addr2 = sqlite3VdbeCurrentAddr(v);
  103537. sqlite3VdbeVerifyAbortable(v, OE_Abort);
  103538. sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
  103539. pIndex->nKeyCol); VdbeCoverage(v);
  103540. sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
  103541. sqlite3VdbeJumpHere(v, j2);
  103542. }else{
  103543. /* Most CREATE INDEX and REINDEX statements that are not UNIQUE can not
  103544. ** abort. The exception is if one of the indexed expressions contains a
  103545. ** user function that throws an exception when it is evaluated. But the
  103546. ** overhead of adding a statement journal to a CREATE INDEX statement is
  103547. ** very small (since most of the pages written do not contain content that
  103548. ** needs to be restored if the statement aborts), so we call
  103549. ** sqlite3MayAbort() for all CREATE INDEX statements. */
  103550. sqlite3MayAbort(pParse);
  103551. addr2 = sqlite3VdbeCurrentAddr(v);
  103552. }
  103553. sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
  103554. if( !pIndex->bAscKeyBug ){
  103555. /* This OP_SeekEnd opcode makes index insert for a REINDEX go much
  103556. ** faster by avoiding unnecessary seeks. But the optimization does
  103557. ** not work for UNIQUE constraint indexes on WITHOUT ROWID tables
  103558. ** with DESC primary keys, since those indexes have there keys in
  103559. ** a different order from the main table.
  103560. ** See ticket: https://www.sqlite.org/src/info/bba7b69f9849b5bf
  103561. */
  103562. sqlite3VdbeAddOp1(v, OP_SeekEnd, iIdx);
  103563. }
  103564. sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
  103565. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  103566. sqlite3ReleaseTempReg(pParse, regRecord);
  103567. sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
  103568. sqlite3VdbeJumpHere(v, addr1);
  103569. sqlite3VdbeAddOp1(v, OP_Close, iTab);
  103570. sqlite3VdbeAddOp1(v, OP_Close, iIdx);
  103571. sqlite3VdbeAddOp1(v, OP_Close, iSorter);
  103572. }
  103573. /*
  103574. ** Allocate heap space to hold an Index object with nCol columns.
  103575. **
  103576. ** Increase the allocation size to provide an extra nExtra bytes
  103577. ** of 8-byte aligned space after the Index object and return a
  103578. ** pointer to this extra space in *ppExtra.
  103579. */
  103580. SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(
  103581. sqlite3 *db, /* Database connection */
  103582. i16 nCol, /* Total number of columns in the index */
  103583. int nExtra, /* Number of bytes of extra space to alloc */
  103584. char **ppExtra /* Pointer to the "extra" space */
  103585. ){
  103586. Index *p; /* Allocated index object */
  103587. int nByte; /* Bytes of space for Index object + arrays */
  103588. nByte = ROUND8(sizeof(Index)) + /* Index structure */
  103589. ROUND8(sizeof(char*)*nCol) + /* Index.azColl */
  103590. ROUND8(sizeof(LogEst)*(nCol+1) + /* Index.aiRowLogEst */
  103591. sizeof(i16)*nCol + /* Index.aiColumn */
  103592. sizeof(u8)*nCol); /* Index.aSortOrder */
  103593. p = sqlite3DbMallocZero(db, nByte + nExtra);
  103594. if( p ){
  103595. char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
  103596. p->azColl = (const char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
  103597. p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
  103598. p->aiColumn = (i16*)pExtra; pExtra += sizeof(i16)*nCol;
  103599. p->aSortOrder = (u8*)pExtra;
  103600. p->nColumn = nCol;
  103601. p->nKeyCol = nCol - 1;
  103602. *ppExtra = ((char*)p) + nByte;
  103603. }
  103604. return p;
  103605. }
  103606. /*
  103607. ** Create a new index for an SQL table. pName1.pName2 is the name of the index
  103608. ** and pTblList is the name of the table that is to be indexed. Both will
  103609. ** be NULL for a primary key or an index that is created to satisfy a
  103610. ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
  103611. ** as the table to be indexed. pParse->pNewTable is a table that is
  103612. ** currently being constructed by a CREATE TABLE statement.
  103613. **
  103614. ** pList is a list of columns to be indexed. pList will be NULL if this
  103615. ** is a primary key or unique-constraint on the most recent column added
  103616. ** to the table currently under construction.
  103617. */
  103618. SQLITE_PRIVATE void sqlite3CreateIndex(
  103619. Parse *pParse, /* All information about this parse */
  103620. Token *pName1, /* First part of index name. May be NULL */
  103621. Token *pName2, /* Second part of index name. May be NULL */
  103622. SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
  103623. ExprList *pList, /* A list of columns to be indexed */
  103624. int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  103625. Token *pStart, /* The CREATE token that begins this statement */
  103626. Expr *pPIWhere, /* WHERE clause for partial indices */
  103627. int sortOrder, /* Sort order of primary key when pList==NULL */
  103628. int ifNotExist, /* Omit error if index already exists */
  103629. u8 idxType /* The index type */
  103630. ){
  103631. Table *pTab = 0; /* Table to be indexed */
  103632. Index *pIndex = 0; /* The index to be created */
  103633. char *zName = 0; /* Name of the index */
  103634. int nName; /* Number of characters in zName */
  103635. int i, j;
  103636. DbFixer sFix; /* For assigning database names to pTable */
  103637. int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
  103638. sqlite3 *db = pParse->db;
  103639. Db *pDb; /* The specific table containing the indexed database */
  103640. int iDb; /* Index of the database that is being written */
  103641. Token *pName = 0; /* Unqualified name of the index to create */
  103642. struct ExprList_item *pListItem; /* For looping over pList */
  103643. int nExtra = 0; /* Space allocated for zExtra[] */
  103644. int nExtraCol; /* Number of extra columns needed */
  103645. char *zExtra = 0; /* Extra space after the Index object */
  103646. Index *pPk = 0; /* PRIMARY KEY index for WITHOUT ROWID tables */
  103647. if( db->mallocFailed || pParse->nErr>0 ){
  103648. goto exit_create_index;
  103649. }
  103650. if( IN_DECLARE_VTAB && idxType!=SQLITE_IDXTYPE_PRIMARYKEY ){
  103651. goto exit_create_index;
  103652. }
  103653. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  103654. goto exit_create_index;
  103655. }
  103656. /*
  103657. ** Find the table that is to be indexed. Return early if not found.
  103658. */
  103659. if( pTblName!=0 ){
  103660. /* Use the two-part index name to determine the database
  103661. ** to search for the table. 'Fix' the table name to this db
  103662. ** before looking up the table.
  103663. */
  103664. assert( pName1 && pName2 );
  103665. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  103666. if( iDb<0 ) goto exit_create_index;
  103667. assert( pName && pName->z );
  103668. #ifndef SQLITE_OMIT_TEMPDB
  103669. /* If the index name was unqualified, check if the table
  103670. ** is a temp table. If so, set the database to 1. Do not do this
  103671. ** if initialising a database schema.
  103672. */
  103673. if( !db->init.busy ){
  103674. pTab = sqlite3SrcListLookup(pParse, pTblName);
  103675. if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
  103676. iDb = 1;
  103677. }
  103678. }
  103679. #endif
  103680. sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
  103681. if( sqlite3FixSrcList(&sFix, pTblName) ){
  103682. /* Because the parser constructs pTblName from a single identifier,
  103683. ** sqlite3FixSrcList can never fail. */
  103684. assert(0);
  103685. }
  103686. pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
  103687. assert( db->mallocFailed==0 || pTab==0 );
  103688. if( pTab==0 ) goto exit_create_index;
  103689. if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
  103690. sqlite3ErrorMsg(pParse,
  103691. "cannot create a TEMP index on non-TEMP table \"%s\"",
  103692. pTab->zName);
  103693. goto exit_create_index;
  103694. }
  103695. if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
  103696. }else{
  103697. assert( pName==0 );
  103698. assert( pStart==0 );
  103699. pTab = pParse->pNewTable;
  103700. if( !pTab ) goto exit_create_index;
  103701. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  103702. }
  103703. pDb = &db->aDb[iDb];
  103704. assert( pTab!=0 );
  103705. assert( pParse->nErr==0 );
  103706. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
  103707. && db->init.busy==0
  103708. && pTblName!=0
  103709. #if SQLITE_USER_AUTHENTICATION
  103710. && sqlite3UserAuthTable(pTab->zName)==0
  103711. #endif
  103712. #ifdef SQLITE_ALLOW_SQLITE_MASTER_INDEX
  103713. && sqlite3StrICmp(&pTab->zName[7],"master")!=0
  103714. #endif
  103715. ){
  103716. sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
  103717. goto exit_create_index;
  103718. }
  103719. #ifndef SQLITE_OMIT_VIEW
  103720. if( pTab->pSelect ){
  103721. sqlite3ErrorMsg(pParse, "views may not be indexed");
  103722. goto exit_create_index;
  103723. }
  103724. #endif
  103725. #ifndef SQLITE_OMIT_VIRTUALTABLE
  103726. if( IsVirtual(pTab) ){
  103727. sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
  103728. goto exit_create_index;
  103729. }
  103730. #endif
  103731. /*
  103732. ** Find the name of the index. Make sure there is not already another
  103733. ** index or table with the same name.
  103734. **
  103735. ** Exception: If we are reading the names of permanent indices from the
  103736. ** sqlite_master table (because some other process changed the schema) and
  103737. ** one of the index names collides with the name of a temporary table or
  103738. ** index, then we will continue to process this index.
  103739. **
  103740. ** If pName==0 it means that we are
  103741. ** dealing with a primary key or UNIQUE constraint. We have to invent our
  103742. ** own name.
  103743. */
  103744. if( pName ){
  103745. zName = sqlite3NameFromToken(db, pName);
  103746. if( zName==0 ) goto exit_create_index;
  103747. assert( pName->z!=0 );
  103748. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  103749. goto exit_create_index;
  103750. }
  103751. if( !IN_RENAME_OBJECT ){
  103752. if( !db->init.busy ){
  103753. if( sqlite3FindTable(db, zName, 0)!=0 ){
  103754. sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
  103755. goto exit_create_index;
  103756. }
  103757. }
  103758. if( sqlite3FindIndex(db, zName, pDb->zDbSName)!=0 ){
  103759. if( !ifNotExist ){
  103760. sqlite3ErrorMsg(pParse, "index %s already exists", zName);
  103761. }else{
  103762. assert( !db->init.busy );
  103763. sqlite3CodeVerifySchema(pParse, iDb);
  103764. }
  103765. goto exit_create_index;
  103766. }
  103767. }
  103768. }else{
  103769. int n;
  103770. Index *pLoop;
  103771. for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
  103772. zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
  103773. if( zName==0 ){
  103774. goto exit_create_index;
  103775. }
  103776. /* Automatic index names generated from within sqlite3_declare_vtab()
  103777. ** must have names that are distinct from normal automatic index names.
  103778. ** The following statement converts "sqlite3_autoindex..." into
  103779. ** "sqlite3_butoindex..." in order to make the names distinct.
  103780. ** The "vtab_err.test" test demonstrates the need of this statement. */
  103781. if( IN_SPECIAL_PARSE ) zName[7]++;
  103782. }
  103783. /* Check for authorization to create an index.
  103784. */
  103785. #ifndef SQLITE_OMIT_AUTHORIZATION
  103786. if( !IN_RENAME_OBJECT ){
  103787. const char *zDb = pDb->zDbSName;
  103788. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
  103789. goto exit_create_index;
  103790. }
  103791. i = SQLITE_CREATE_INDEX;
  103792. if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
  103793. if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
  103794. goto exit_create_index;
  103795. }
  103796. }
  103797. #endif
  103798. /* If pList==0, it means this routine was called to make a primary
  103799. ** key out of the last column added to the table under construction.
  103800. ** So create a fake list to simulate this.
  103801. */
  103802. if( pList==0 ){
  103803. Token prevCol;
  103804. Column *pCol = &pTab->aCol[pTab->nCol-1];
  103805. pCol->colFlags |= COLFLAG_UNIQUE;
  103806. sqlite3TokenInit(&prevCol, pCol->zName);
  103807. pList = sqlite3ExprListAppend(pParse, 0,
  103808. sqlite3ExprAlloc(db, TK_ID, &prevCol, 0));
  103809. if( pList==0 ) goto exit_create_index;
  103810. assert( pList->nExpr==1 );
  103811. sqlite3ExprListSetSortOrder(pList, sortOrder);
  103812. }else{
  103813. sqlite3ExprListCheckLength(pParse, pList, "index");
  103814. if( pParse->nErr ) goto exit_create_index;
  103815. }
  103816. /* Figure out how many bytes of space are required to store explicitly
  103817. ** specified collation sequence names.
  103818. */
  103819. for(i=0; i<pList->nExpr; i++){
  103820. Expr *pExpr = pList->a[i].pExpr;
  103821. assert( pExpr!=0 );
  103822. if( pExpr->op==TK_COLLATE ){
  103823. nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
  103824. }
  103825. }
  103826. /*
  103827. ** Allocate the index structure.
  103828. */
  103829. nName = sqlite3Strlen30(zName);
  103830. nExtraCol = pPk ? pPk->nKeyCol : 1;
  103831. assert( pList->nExpr + nExtraCol <= 32767 /* Fits in i16 */ );
  103832. pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
  103833. nName + nExtra + 1, &zExtra);
  103834. if( db->mallocFailed ){
  103835. goto exit_create_index;
  103836. }
  103837. assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
  103838. assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
  103839. pIndex->zName = zExtra;
  103840. zExtra += nName + 1;
  103841. memcpy(pIndex->zName, zName, nName+1);
  103842. pIndex->pTable = pTab;
  103843. pIndex->onError = (u8)onError;
  103844. pIndex->uniqNotNull = onError!=OE_None;
  103845. pIndex->idxType = idxType;
  103846. pIndex->pSchema = db->aDb[iDb].pSchema;
  103847. pIndex->nKeyCol = pList->nExpr;
  103848. if( pPIWhere ){
  103849. sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
  103850. pIndex->pPartIdxWhere = pPIWhere;
  103851. pPIWhere = 0;
  103852. }
  103853. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  103854. /* Check to see if we should honor DESC requests on index columns
  103855. */
  103856. if( pDb->pSchema->file_format>=4 ){
  103857. sortOrderMask = -1; /* Honor DESC */
  103858. }else{
  103859. sortOrderMask = 0; /* Ignore DESC */
  103860. }
  103861. /* Analyze the list of expressions that form the terms of the index and
  103862. ** report any errors. In the common case where the expression is exactly
  103863. ** a table column, store that column in aiColumn[]. For general expressions,
  103864. ** populate pIndex->aColExpr and store XN_EXPR (-2) in aiColumn[].
  103865. **
  103866. ** TODO: Issue a warning if two or more columns of the index are identical.
  103867. ** TODO: Issue a warning if the table primary key is used as part of the
  103868. ** index key.
  103869. */
  103870. pListItem = pList->a;
  103871. if( IN_RENAME_OBJECT ){
  103872. pIndex->aColExpr = pList;
  103873. pList = 0;
  103874. }
  103875. for(i=0; i<pIndex->nKeyCol; i++, pListItem++){
  103876. Expr *pCExpr; /* The i-th index expression */
  103877. int requestedSortOrder; /* ASC or DESC on the i-th expression */
  103878. const char *zColl; /* Collation sequence name */
  103879. sqlite3StringToId(pListItem->pExpr);
  103880. sqlite3ResolveSelfReference(pParse, pTab, NC_IdxExpr, pListItem->pExpr, 0);
  103881. if( pParse->nErr ) goto exit_create_index;
  103882. pCExpr = sqlite3ExprSkipCollate(pListItem->pExpr);
  103883. if( pCExpr->op!=TK_COLUMN ){
  103884. if( pTab==pParse->pNewTable ){
  103885. sqlite3ErrorMsg(pParse, "expressions prohibited in PRIMARY KEY and "
  103886. "UNIQUE constraints");
  103887. goto exit_create_index;
  103888. }
  103889. if( pIndex->aColExpr==0 ){
  103890. pIndex->aColExpr = pList;
  103891. pList = 0;
  103892. }
  103893. j = XN_EXPR;
  103894. pIndex->aiColumn[i] = XN_EXPR;
  103895. pIndex->uniqNotNull = 0;
  103896. }else{
  103897. j = pCExpr->iColumn;
  103898. assert( j<=0x7fff );
  103899. if( j<0 ){
  103900. j = pTab->iPKey;
  103901. }else if( pTab->aCol[j].notNull==0 ){
  103902. pIndex->uniqNotNull = 0;
  103903. }
  103904. pIndex->aiColumn[i] = (i16)j;
  103905. }
  103906. zColl = 0;
  103907. if( pListItem->pExpr->op==TK_COLLATE ){
  103908. int nColl;
  103909. zColl = pListItem->pExpr->u.zToken;
  103910. nColl = sqlite3Strlen30(zColl) + 1;
  103911. assert( nExtra>=nColl );
  103912. memcpy(zExtra, zColl, nColl);
  103913. zColl = zExtra;
  103914. zExtra += nColl;
  103915. nExtra -= nColl;
  103916. }else if( j>=0 ){
  103917. zColl = pTab->aCol[j].zColl;
  103918. }
  103919. if( !zColl ) zColl = sqlite3StrBINARY;
  103920. if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
  103921. goto exit_create_index;
  103922. }
  103923. pIndex->azColl[i] = zColl;
  103924. requestedSortOrder = pListItem->sortOrder & sortOrderMask;
  103925. pIndex->aSortOrder[i] = (u8)requestedSortOrder;
  103926. }
  103927. /* Append the table key to the end of the index. For WITHOUT ROWID
  103928. ** tables (when pPk!=0) this will be the declared PRIMARY KEY. For
  103929. ** normal tables (when pPk==0) this will be the rowid.
  103930. */
  103931. if( pPk ){
  103932. for(j=0; j<pPk->nKeyCol; j++){
  103933. int x = pPk->aiColumn[j];
  103934. assert( x>=0 );
  103935. if( isDupColumn(pIndex, pIndex->nKeyCol, pPk, j) ){
  103936. pIndex->nColumn--;
  103937. }else{
  103938. testcase( hasColumn(pIndex->aiColumn,pIndex->nKeyCol,x) );
  103939. pIndex->aiColumn[i] = x;
  103940. pIndex->azColl[i] = pPk->azColl[j];
  103941. pIndex->aSortOrder[i] = pPk->aSortOrder[j];
  103942. i++;
  103943. }
  103944. }
  103945. assert( i==pIndex->nColumn );
  103946. }else{
  103947. pIndex->aiColumn[i] = XN_ROWID;
  103948. pIndex->azColl[i] = sqlite3StrBINARY;
  103949. }
  103950. sqlite3DefaultRowEst(pIndex);
  103951. if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
  103952. /* If this index contains every column of its table, then mark
  103953. ** it as a covering index */
  103954. assert( HasRowid(pTab)
  103955. || pTab->iPKey<0 || sqlite3ColumnOfIndex(pIndex, pTab->iPKey)>=0 );
  103956. recomputeColumnsNotIndexed(pIndex);
  103957. if( pTblName!=0 && pIndex->nColumn>=pTab->nCol ){
  103958. pIndex->isCovering = 1;
  103959. for(j=0; j<pTab->nCol; j++){
  103960. if( j==pTab->iPKey ) continue;
  103961. if( sqlite3ColumnOfIndex(pIndex,j)>=0 ) continue;
  103962. pIndex->isCovering = 0;
  103963. break;
  103964. }
  103965. }
  103966. if( pTab==pParse->pNewTable ){
  103967. /* This routine has been called to create an automatic index as a
  103968. ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
  103969. ** a PRIMARY KEY or UNIQUE clause following the column definitions.
  103970. ** i.e. one of:
  103971. **
  103972. ** CREATE TABLE t(x PRIMARY KEY, y);
  103973. ** CREATE TABLE t(x, y, UNIQUE(x, y));
  103974. **
  103975. ** Either way, check to see if the table already has such an index. If
  103976. ** so, don't bother creating this one. This only applies to
  103977. ** automatically created indices. Users can do as they wish with
  103978. ** explicit indices.
  103979. **
  103980. ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
  103981. ** (and thus suppressing the second one) even if they have different
  103982. ** sort orders.
  103983. **
  103984. ** If there are different collating sequences or if the columns of
  103985. ** the constraint occur in different orders, then the constraints are
  103986. ** considered distinct and both result in separate indices.
  103987. */
  103988. Index *pIdx;
  103989. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  103990. int k;
  103991. assert( IsUniqueIndex(pIdx) );
  103992. assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
  103993. assert( IsUniqueIndex(pIndex) );
  103994. if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
  103995. for(k=0; k<pIdx->nKeyCol; k++){
  103996. const char *z1;
  103997. const char *z2;
  103998. assert( pIdx->aiColumn[k]>=0 );
  103999. if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
  104000. z1 = pIdx->azColl[k];
  104001. z2 = pIndex->azColl[k];
  104002. if( sqlite3StrICmp(z1, z2) ) break;
  104003. }
  104004. if( k==pIdx->nKeyCol ){
  104005. if( pIdx->onError!=pIndex->onError ){
  104006. /* This constraint creates the same index as a previous
  104007. ** constraint specified somewhere in the CREATE TABLE statement.
  104008. ** However the ON CONFLICT clauses are different. If both this
  104009. ** constraint and the previous equivalent constraint have explicit
  104010. ** ON CONFLICT clauses this is an error. Otherwise, use the
  104011. ** explicitly specified behavior for the index.
  104012. */
  104013. if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
  104014. sqlite3ErrorMsg(pParse,
  104015. "conflicting ON CONFLICT clauses specified", 0);
  104016. }
  104017. if( pIdx->onError==OE_Default ){
  104018. pIdx->onError = pIndex->onError;
  104019. }
  104020. }
  104021. if( idxType==SQLITE_IDXTYPE_PRIMARYKEY ) pIdx->idxType = idxType;
  104022. if( IN_RENAME_OBJECT ){
  104023. pIndex->pNext = pParse->pNewIndex;
  104024. pParse->pNewIndex = pIndex;
  104025. pIndex = 0;
  104026. }
  104027. goto exit_create_index;
  104028. }
  104029. }
  104030. }
  104031. if( !IN_RENAME_OBJECT ){
  104032. /* Link the new Index structure to its table and to the other
  104033. ** in-memory database structures.
  104034. */
  104035. assert( pParse->nErr==0 );
  104036. if( db->init.busy ){
  104037. Index *p;
  104038. assert( !IN_SPECIAL_PARSE );
  104039. assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
  104040. if( pTblName!=0 ){
  104041. pIndex->tnum = db->init.newTnum;
  104042. if( sqlite3IndexHasDuplicateRootPage(pIndex) ){
  104043. sqlite3ErrorMsg(pParse, "invalid rootpage");
  104044. pParse->rc = SQLITE_CORRUPT_BKPT;
  104045. goto exit_create_index;
  104046. }
  104047. }
  104048. p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
  104049. pIndex->zName, pIndex);
  104050. if( p ){
  104051. assert( p==pIndex ); /* Malloc must have failed */
  104052. sqlite3OomFault(db);
  104053. goto exit_create_index;
  104054. }
  104055. db->mDbFlags |= DBFLAG_SchemaChange;
  104056. }
  104057. /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
  104058. ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
  104059. ** emit code to allocate the index rootpage on disk and make an entry for
  104060. ** the index in the sqlite_master table and populate the index with
  104061. ** content. But, do not do this if we are simply reading the sqlite_master
  104062. ** table to parse the schema, or if this index is the PRIMARY KEY index
  104063. ** of a WITHOUT ROWID table.
  104064. **
  104065. ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
  104066. ** or UNIQUE index in a CREATE TABLE statement. Since the table
  104067. ** has just been created, it contains no data and the index initialization
  104068. ** step can be skipped.
  104069. */
  104070. else if( HasRowid(pTab) || pTblName!=0 ){
  104071. Vdbe *v;
  104072. char *zStmt;
  104073. int iMem = ++pParse->nMem;
  104074. v = sqlite3GetVdbe(pParse);
  104075. if( v==0 ) goto exit_create_index;
  104076. sqlite3BeginWriteOperation(pParse, 1, iDb);
  104077. /* Create the rootpage for the index using CreateIndex. But before
  104078. ** doing so, code a Noop instruction and store its address in
  104079. ** Index.tnum. This is required in case this index is actually a
  104080. ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In
  104081. ** that case the convertToWithoutRowidTable() routine will replace
  104082. ** the Noop with a Goto to jump over the VDBE code generated below. */
  104083. pIndex->tnum = sqlite3VdbeAddOp0(v, OP_Noop);
  104084. sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, iMem, BTREE_BLOBKEY);
  104085. /* Gather the complete text of the CREATE INDEX statement into
  104086. ** the zStmt variable
  104087. */
  104088. if( pStart ){
  104089. int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
  104090. if( pName->z[n-1]==';' ) n--;
  104091. /* A named index with an explicit CREATE INDEX statement */
  104092. zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
  104093. onError==OE_None ? "" : " UNIQUE", n, pName->z);
  104094. }else{
  104095. /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
  104096. /* zStmt = sqlite3MPrintf(""); */
  104097. zStmt = 0;
  104098. }
  104099. /* Add an entry in sqlite_master for this index
  104100. */
  104101. sqlite3NestedParse(pParse,
  104102. "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
  104103. db->aDb[iDb].zDbSName, MASTER_NAME,
  104104. pIndex->zName,
  104105. pTab->zName,
  104106. iMem,
  104107. zStmt
  104108. );
  104109. sqlite3DbFree(db, zStmt);
  104110. /* Fill the index with data and reparse the schema. Code an OP_Expire
  104111. ** to invalidate all pre-compiled statements.
  104112. */
  104113. if( pTblName ){
  104114. sqlite3RefillIndex(pParse, pIndex, iMem);
  104115. sqlite3ChangeCookie(pParse, iDb);
  104116. sqlite3VdbeAddParseSchemaOp(v, iDb,
  104117. sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
  104118. sqlite3VdbeAddOp2(v, OP_Expire, 0, 1);
  104119. }
  104120. sqlite3VdbeJumpHere(v, pIndex->tnum);
  104121. }
  104122. }
  104123. /* When adding an index to the list of indices for a table, make
  104124. ** sure all indices labeled OE_Replace come after all those labeled
  104125. ** OE_Ignore. This is necessary for the correct constraint check
  104126. ** processing (in sqlite3GenerateConstraintChecks()) as part of
  104127. ** UPDATE and INSERT statements.
  104128. */
  104129. if( db->init.busy || pTblName==0 ){
  104130. if( onError!=OE_Replace || pTab->pIndex==0
  104131. || pTab->pIndex->onError==OE_Replace){
  104132. pIndex->pNext = pTab->pIndex;
  104133. pTab->pIndex = pIndex;
  104134. }else{
  104135. Index *pOther = pTab->pIndex;
  104136. while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
  104137. pOther = pOther->pNext;
  104138. }
  104139. pIndex->pNext = pOther->pNext;
  104140. pOther->pNext = pIndex;
  104141. }
  104142. pIndex = 0;
  104143. }
  104144. else if( IN_RENAME_OBJECT ){
  104145. assert( pParse->pNewIndex==0 );
  104146. pParse->pNewIndex = pIndex;
  104147. pIndex = 0;
  104148. }
  104149. /* Clean up before exiting */
  104150. exit_create_index:
  104151. if( pIndex ) sqlite3FreeIndex(db, pIndex);
  104152. sqlite3ExprDelete(db, pPIWhere);
  104153. sqlite3ExprListDelete(db, pList);
  104154. sqlite3SrcListDelete(db, pTblName);
  104155. sqlite3DbFree(db, zName);
  104156. }
  104157. /*
  104158. ** Fill the Index.aiRowEst[] array with default information - information
  104159. ** to be used when we have not run the ANALYZE command.
  104160. **
  104161. ** aiRowEst[0] is supposed to contain the number of elements in the index.
  104162. ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
  104163. ** number of rows in the table that match any particular value of the
  104164. ** first column of the index. aiRowEst[2] is an estimate of the number
  104165. ** of rows that match any particular combination of the first 2 columns
  104166. ** of the index. And so forth. It must always be the case that
  104167. *
  104168. ** aiRowEst[N]<=aiRowEst[N-1]
  104169. ** aiRowEst[N]>=1
  104170. **
  104171. ** Apart from that, we have little to go on besides intuition as to
  104172. ** how aiRowEst[] should be initialized. The numbers generated here
  104173. ** are based on typical values found in actual indices.
  104174. */
  104175. SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
  104176. /* 10, 9, 8, 7, 6 */
  104177. LogEst aVal[] = { 33, 32, 30, 28, 26 };
  104178. LogEst *a = pIdx->aiRowLogEst;
  104179. int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
  104180. int i;
  104181. /* Indexes with default row estimates should not have stat1 data */
  104182. assert( !pIdx->hasStat1 );
  104183. /* Set the first entry (number of rows in the index) to the estimated
  104184. ** number of rows in the table, or half the number of rows in the table
  104185. ** for a partial index. But do not let the estimate drop below 10. */
  104186. a[0] = pIdx->pTable->nRowLogEst;
  104187. if( pIdx->pPartIdxWhere!=0 ) a[0] -= 10; assert( 10==sqlite3LogEst(2) );
  104188. if( a[0]<33 ) a[0] = 33; assert( 33==sqlite3LogEst(10) );
  104189. /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
  104190. ** 6 and each subsequent value (if any) is 5. */
  104191. memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
  104192. for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
  104193. a[i] = 23; assert( 23==sqlite3LogEst(5) );
  104194. }
  104195. assert( 0==sqlite3LogEst(1) );
  104196. if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
  104197. }
  104198. /*
  104199. ** This routine will drop an existing named index. This routine
  104200. ** implements the DROP INDEX statement.
  104201. */
  104202. SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
  104203. Index *pIndex;
  104204. Vdbe *v;
  104205. sqlite3 *db = pParse->db;
  104206. int iDb;
  104207. assert( pParse->nErr==0 ); /* Never called with prior errors */
  104208. if( db->mallocFailed ){
  104209. goto exit_drop_index;
  104210. }
  104211. assert( pName->nSrc==1 );
  104212. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  104213. goto exit_drop_index;
  104214. }
  104215. pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
  104216. if( pIndex==0 ){
  104217. if( !ifExists ){
  104218. sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
  104219. }else{
  104220. sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
  104221. }
  104222. pParse->checkSchema = 1;
  104223. goto exit_drop_index;
  104224. }
  104225. if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
  104226. sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
  104227. "or PRIMARY KEY constraint cannot be dropped", 0);
  104228. goto exit_drop_index;
  104229. }
  104230. iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
  104231. #ifndef SQLITE_OMIT_AUTHORIZATION
  104232. {
  104233. int code = SQLITE_DROP_INDEX;
  104234. Table *pTab = pIndex->pTable;
  104235. const char *zDb = db->aDb[iDb].zDbSName;
  104236. const char *zTab = SCHEMA_TABLE(iDb);
  104237. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
  104238. goto exit_drop_index;
  104239. }
  104240. if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
  104241. if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
  104242. goto exit_drop_index;
  104243. }
  104244. }
  104245. #endif
  104246. /* Generate code to remove the index and from the master table */
  104247. v = sqlite3GetVdbe(pParse);
  104248. if( v ){
  104249. sqlite3BeginWriteOperation(pParse, 1, iDb);
  104250. sqlite3NestedParse(pParse,
  104251. "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
  104252. db->aDb[iDb].zDbSName, MASTER_NAME, pIndex->zName
  104253. );
  104254. sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
  104255. sqlite3ChangeCookie(pParse, iDb);
  104256. destroyRootPage(pParse, pIndex->tnum, iDb);
  104257. sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
  104258. }
  104259. exit_drop_index:
  104260. sqlite3SrcListDelete(db, pName);
  104261. }
  104262. /*
  104263. ** pArray is a pointer to an array of objects. Each object in the
  104264. ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
  104265. ** to extend the array so that there is space for a new object at the end.
  104266. **
  104267. ** When this function is called, *pnEntry contains the current size of
  104268. ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
  104269. ** in total).
  104270. **
  104271. ** If the realloc() is successful (i.e. if no OOM condition occurs), the
  104272. ** space allocated for the new object is zeroed, *pnEntry updated to
  104273. ** reflect the new size of the array and a pointer to the new allocation
  104274. ** returned. *pIdx is set to the index of the new array entry in this case.
  104275. **
  104276. ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
  104277. ** unchanged and a copy of pArray returned.
  104278. */
  104279. SQLITE_PRIVATE void *sqlite3ArrayAllocate(
  104280. sqlite3 *db, /* Connection to notify of malloc failures */
  104281. void *pArray, /* Array of objects. Might be reallocated */
  104282. int szEntry, /* Size of each object in the array */
  104283. int *pnEntry, /* Number of objects currently in use */
  104284. int *pIdx /* Write the index of a new slot here */
  104285. ){
  104286. char *z;
  104287. sqlite3_int64 n = *pIdx = *pnEntry;
  104288. if( (n & (n-1))==0 ){
  104289. sqlite3_int64 sz = (n==0) ? 1 : 2*n;
  104290. void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
  104291. if( pNew==0 ){
  104292. *pIdx = -1;
  104293. return pArray;
  104294. }
  104295. pArray = pNew;
  104296. }
  104297. z = (char*)pArray;
  104298. memset(&z[n * szEntry], 0, szEntry);
  104299. ++*pnEntry;
  104300. return pArray;
  104301. }
  104302. /*
  104303. ** Append a new element to the given IdList. Create a new IdList if
  104304. ** need be.
  104305. **
  104306. ** A new IdList is returned, or NULL if malloc() fails.
  104307. */
  104308. SQLITE_PRIVATE IdList *sqlite3IdListAppend(Parse *pParse, IdList *pList, Token *pToken){
  104309. sqlite3 *db = pParse->db;
  104310. int i;
  104311. if( pList==0 ){
  104312. pList = sqlite3DbMallocZero(db, sizeof(IdList) );
  104313. if( pList==0 ) return 0;
  104314. }
  104315. pList->a = sqlite3ArrayAllocate(
  104316. db,
  104317. pList->a,
  104318. sizeof(pList->a[0]),
  104319. &pList->nId,
  104320. &i
  104321. );
  104322. if( i<0 ){
  104323. sqlite3IdListDelete(db, pList);
  104324. return 0;
  104325. }
  104326. pList->a[i].zName = sqlite3NameFromToken(db, pToken);
  104327. if( IN_RENAME_OBJECT && pList->a[i].zName ){
  104328. sqlite3RenameTokenMap(pParse, (void*)pList->a[i].zName, pToken);
  104329. }
  104330. return pList;
  104331. }
  104332. /*
  104333. ** Delete an IdList.
  104334. */
  104335. SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
  104336. int i;
  104337. if( pList==0 ) return;
  104338. for(i=0; i<pList->nId; i++){
  104339. sqlite3DbFree(db, pList->a[i].zName);
  104340. }
  104341. sqlite3DbFree(db, pList->a);
  104342. sqlite3DbFreeNN(db, pList);
  104343. }
  104344. /*
  104345. ** Return the index in pList of the identifier named zId. Return -1
  104346. ** if not found.
  104347. */
  104348. SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
  104349. int i;
  104350. if( pList==0 ) return -1;
  104351. for(i=0; i<pList->nId; i++){
  104352. if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
  104353. }
  104354. return -1;
  104355. }
  104356. /*
  104357. ** Maximum size of a SrcList object.
  104358. ** The SrcList object is used to represent the FROM clause of a
  104359. ** SELECT statement, and the query planner cannot deal with more
  104360. ** than 64 tables in a join. So any value larger than 64 here
  104361. ** is sufficient for most uses. Smaller values, like say 10, are
  104362. ** appropriate for small and memory-limited applications.
  104363. */
  104364. #ifndef SQLITE_MAX_SRCLIST
  104365. # define SQLITE_MAX_SRCLIST 200
  104366. #endif
  104367. /*
  104368. ** Expand the space allocated for the given SrcList object by
  104369. ** creating nExtra new slots beginning at iStart. iStart is zero based.
  104370. ** New slots are zeroed.
  104371. **
  104372. ** For example, suppose a SrcList initially contains two entries: A,B.
  104373. ** To append 3 new entries onto the end, do this:
  104374. **
  104375. ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
  104376. **
  104377. ** After the call above it would contain: A, B, nil, nil, nil.
  104378. ** If the iStart argument had been 1 instead of 2, then the result
  104379. ** would have been: A, nil, nil, nil, B. To prepend the new slots,
  104380. ** the iStart value would be 0. The result then would
  104381. ** be: nil, nil, nil, A, B.
  104382. **
  104383. ** If a memory allocation fails or the SrcList becomes too large, leave
  104384. ** the original SrcList unchanged, return NULL, and leave an error message
  104385. ** in pParse.
  104386. */
  104387. SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
  104388. Parse *pParse, /* Parsing context into which errors are reported */
  104389. SrcList *pSrc, /* The SrcList to be enlarged */
  104390. int nExtra, /* Number of new slots to add to pSrc->a[] */
  104391. int iStart /* Index in pSrc->a[] of first new slot */
  104392. ){
  104393. int i;
  104394. /* Sanity checking on calling parameters */
  104395. assert( iStart>=0 );
  104396. assert( nExtra>=1 );
  104397. assert( pSrc!=0 );
  104398. assert( iStart<=pSrc->nSrc );
  104399. /* Allocate additional space if needed */
  104400. if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
  104401. SrcList *pNew;
  104402. sqlite3_int64 nAlloc = 2*(sqlite3_int64)pSrc->nSrc+nExtra;
  104403. sqlite3 *db = pParse->db;
  104404. if( pSrc->nSrc+nExtra>=SQLITE_MAX_SRCLIST ){
  104405. sqlite3ErrorMsg(pParse, "too many FROM clause terms, max: %d",
  104406. SQLITE_MAX_SRCLIST);
  104407. return 0;
  104408. }
  104409. if( nAlloc>SQLITE_MAX_SRCLIST ) nAlloc = SQLITE_MAX_SRCLIST;
  104410. pNew = sqlite3DbRealloc(db, pSrc,
  104411. sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
  104412. if( pNew==0 ){
  104413. assert( db->mallocFailed );
  104414. return 0;
  104415. }
  104416. pSrc = pNew;
  104417. pSrc->nAlloc = nAlloc;
  104418. }
  104419. /* Move existing slots that come after the newly inserted slots
  104420. ** out of the way */
  104421. for(i=pSrc->nSrc-1; i>=iStart; i--){
  104422. pSrc->a[i+nExtra] = pSrc->a[i];
  104423. }
  104424. pSrc->nSrc += nExtra;
  104425. /* Zero the newly allocated slots */
  104426. memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
  104427. for(i=iStart; i<iStart+nExtra; i++){
  104428. pSrc->a[i].iCursor = -1;
  104429. }
  104430. /* Return a pointer to the enlarged SrcList */
  104431. return pSrc;
  104432. }
  104433. /*
  104434. ** Append a new table name to the given SrcList. Create a new SrcList if
  104435. ** need be. A new entry is created in the SrcList even if pTable is NULL.
  104436. **
  104437. ** A SrcList is returned, or NULL if there is an OOM error or if the
  104438. ** SrcList grows to large. The returned
  104439. ** SrcList might be the same as the SrcList that was input or it might be
  104440. ** a new one. If an OOM error does occurs, then the prior value of pList
  104441. ** that is input to this routine is automatically freed.
  104442. **
  104443. ** If pDatabase is not null, it means that the table has an optional
  104444. ** database name prefix. Like this: "database.table". The pDatabase
  104445. ** points to the table name and the pTable points to the database name.
  104446. ** The SrcList.a[].zName field is filled with the table name which might
  104447. ** come from pTable (if pDatabase is NULL) or from pDatabase.
  104448. ** SrcList.a[].zDatabase is filled with the database name from pTable,
  104449. ** or with NULL if no database is specified.
  104450. **
  104451. ** In other words, if call like this:
  104452. **
  104453. ** sqlite3SrcListAppend(D,A,B,0);
  104454. **
  104455. ** Then B is a table name and the database name is unspecified. If called
  104456. ** like this:
  104457. **
  104458. ** sqlite3SrcListAppend(D,A,B,C);
  104459. **
  104460. ** Then C is the table name and B is the database name. If C is defined
  104461. ** then so is B. In other words, we never have a case where:
  104462. **
  104463. ** sqlite3SrcListAppend(D,A,0,C);
  104464. **
  104465. ** Both pTable and pDatabase are assumed to be quoted. They are dequoted
  104466. ** before being added to the SrcList.
  104467. */
  104468. SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
  104469. Parse *pParse, /* Parsing context, in which errors are reported */
  104470. SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
  104471. Token *pTable, /* Table to append */
  104472. Token *pDatabase /* Database of the table */
  104473. ){
  104474. struct SrcList_item *pItem;
  104475. sqlite3 *db;
  104476. assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
  104477. assert( pParse!=0 );
  104478. assert( pParse->db!=0 );
  104479. db = pParse->db;
  104480. if( pList==0 ){
  104481. pList = sqlite3DbMallocRawNN(pParse->db, sizeof(SrcList) );
  104482. if( pList==0 ) return 0;
  104483. pList->nAlloc = 1;
  104484. pList->nSrc = 1;
  104485. memset(&pList->a[0], 0, sizeof(pList->a[0]));
  104486. pList->a[0].iCursor = -1;
  104487. }else{
  104488. SrcList *pNew = sqlite3SrcListEnlarge(pParse, pList, 1, pList->nSrc);
  104489. if( pNew==0 ){
  104490. sqlite3SrcListDelete(db, pList);
  104491. return 0;
  104492. }else{
  104493. pList = pNew;
  104494. }
  104495. }
  104496. pItem = &pList->a[pList->nSrc-1];
  104497. if( pDatabase && pDatabase->z==0 ){
  104498. pDatabase = 0;
  104499. }
  104500. if( pDatabase ){
  104501. pItem->zName = sqlite3NameFromToken(db, pDatabase);
  104502. pItem->zDatabase = sqlite3NameFromToken(db, pTable);
  104503. }else{
  104504. pItem->zName = sqlite3NameFromToken(db, pTable);
  104505. pItem->zDatabase = 0;
  104506. }
  104507. return pList;
  104508. }
  104509. /*
  104510. ** Assign VdbeCursor index numbers to all tables in a SrcList
  104511. */
  104512. SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
  104513. int i;
  104514. struct SrcList_item *pItem;
  104515. assert(pList || pParse->db->mallocFailed );
  104516. if( pList ){
  104517. for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
  104518. if( pItem->iCursor>=0 ) break;
  104519. pItem->iCursor = pParse->nTab++;
  104520. if( pItem->pSelect ){
  104521. sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
  104522. }
  104523. }
  104524. }
  104525. }
  104526. /*
  104527. ** Delete an entire SrcList including all its substructure.
  104528. */
  104529. SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
  104530. int i;
  104531. struct SrcList_item *pItem;
  104532. if( pList==0 ) return;
  104533. for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
  104534. sqlite3DbFree(db, pItem->zDatabase);
  104535. sqlite3DbFree(db, pItem->zName);
  104536. sqlite3DbFree(db, pItem->zAlias);
  104537. if( pItem->fg.isIndexedBy ) sqlite3DbFree(db, pItem->u1.zIndexedBy);
  104538. if( pItem->fg.isTabFunc ) sqlite3ExprListDelete(db, pItem->u1.pFuncArg);
  104539. sqlite3DeleteTable(db, pItem->pTab);
  104540. sqlite3SelectDelete(db, pItem->pSelect);
  104541. sqlite3ExprDelete(db, pItem->pOn);
  104542. sqlite3IdListDelete(db, pItem->pUsing);
  104543. }
  104544. sqlite3DbFreeNN(db, pList);
  104545. }
  104546. /*
  104547. ** This routine is called by the parser to add a new term to the
  104548. ** end of a growing FROM clause. The "p" parameter is the part of
  104549. ** the FROM clause that has already been constructed. "p" is NULL
  104550. ** if this is the first term of the FROM clause. pTable and pDatabase
  104551. ** are the name of the table and database named in the FROM clause term.
  104552. ** pDatabase is NULL if the database name qualifier is missing - the
  104553. ** usual case. If the term has an alias, then pAlias points to the
  104554. ** alias token. If the term is a subquery, then pSubquery is the
  104555. ** SELECT statement that the subquery encodes. The pTable and
  104556. ** pDatabase parameters are NULL for subqueries. The pOn and pUsing
  104557. ** parameters are the content of the ON and USING clauses.
  104558. **
  104559. ** Return a new SrcList which encodes is the FROM with the new
  104560. ** term added.
  104561. */
  104562. SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
  104563. Parse *pParse, /* Parsing context */
  104564. SrcList *p, /* The left part of the FROM clause already seen */
  104565. Token *pTable, /* Name of the table to add to the FROM clause */
  104566. Token *pDatabase, /* Name of the database containing pTable */
  104567. Token *pAlias, /* The right-hand side of the AS subexpression */
  104568. Select *pSubquery, /* A subquery used in place of a table name */
  104569. Expr *pOn, /* The ON clause of a join */
  104570. IdList *pUsing /* The USING clause of a join */
  104571. ){
  104572. struct SrcList_item *pItem;
  104573. sqlite3 *db = pParse->db;
  104574. if( !p && (pOn || pUsing) ){
  104575. sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
  104576. (pOn ? "ON" : "USING")
  104577. );
  104578. goto append_from_error;
  104579. }
  104580. p = sqlite3SrcListAppend(pParse, p, pTable, pDatabase);
  104581. if( p==0 ){
  104582. goto append_from_error;
  104583. }
  104584. assert( p->nSrc>0 );
  104585. pItem = &p->a[p->nSrc-1];
  104586. assert( (pTable==0)==(pDatabase==0) );
  104587. assert( pItem->zName==0 || pDatabase!=0 );
  104588. if( IN_RENAME_OBJECT && pItem->zName ){
  104589. Token *pToken = (ALWAYS(pDatabase) && pDatabase->z) ? pDatabase : pTable;
  104590. sqlite3RenameTokenMap(pParse, pItem->zName, pToken);
  104591. }
  104592. assert( pAlias!=0 );
  104593. if( pAlias->n ){
  104594. pItem->zAlias = sqlite3NameFromToken(db, pAlias);
  104595. }
  104596. pItem->pSelect = pSubquery;
  104597. pItem->pOn = pOn;
  104598. pItem->pUsing = pUsing;
  104599. return p;
  104600. append_from_error:
  104601. assert( p==0 );
  104602. sqlite3ExprDelete(db, pOn);
  104603. sqlite3IdListDelete(db, pUsing);
  104604. sqlite3SelectDelete(db, pSubquery);
  104605. return 0;
  104606. }
  104607. /*
  104608. ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
  104609. ** element of the source-list passed as the second argument.
  104610. */
  104611. SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
  104612. assert( pIndexedBy!=0 );
  104613. if( p && pIndexedBy->n>0 ){
  104614. struct SrcList_item *pItem;
  104615. assert( p->nSrc>0 );
  104616. pItem = &p->a[p->nSrc-1];
  104617. assert( pItem->fg.notIndexed==0 );
  104618. assert( pItem->fg.isIndexedBy==0 );
  104619. assert( pItem->fg.isTabFunc==0 );
  104620. if( pIndexedBy->n==1 && !pIndexedBy->z ){
  104621. /* A "NOT INDEXED" clause was supplied. See parse.y
  104622. ** construct "indexed_opt" for details. */
  104623. pItem->fg.notIndexed = 1;
  104624. }else{
  104625. pItem->u1.zIndexedBy = sqlite3NameFromToken(pParse->db, pIndexedBy);
  104626. pItem->fg.isIndexedBy = 1;
  104627. }
  104628. }
  104629. }
  104630. /*
  104631. ** Add the list of function arguments to the SrcList entry for a
  104632. ** table-valued-function.
  104633. */
  104634. SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse *pParse, SrcList *p, ExprList *pList){
  104635. if( p ){
  104636. struct SrcList_item *pItem = &p->a[p->nSrc-1];
  104637. assert( pItem->fg.notIndexed==0 );
  104638. assert( pItem->fg.isIndexedBy==0 );
  104639. assert( pItem->fg.isTabFunc==0 );
  104640. pItem->u1.pFuncArg = pList;
  104641. pItem->fg.isTabFunc = 1;
  104642. }else{
  104643. sqlite3ExprListDelete(pParse->db, pList);
  104644. }
  104645. }
  104646. /*
  104647. ** When building up a FROM clause in the parser, the join operator
  104648. ** is initially attached to the left operand. But the code generator
  104649. ** expects the join operator to be on the right operand. This routine
  104650. ** Shifts all join operators from left to right for an entire FROM
  104651. ** clause.
  104652. **
  104653. ** Example: Suppose the join is like this:
  104654. **
  104655. ** A natural cross join B
  104656. **
  104657. ** The operator is "natural cross join". The A and B operands are stored
  104658. ** in p->a[0] and p->a[1], respectively. The parser initially stores the
  104659. ** operator with A. This routine shifts that operator over to B.
  104660. */
  104661. SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
  104662. if( p ){
  104663. int i;
  104664. for(i=p->nSrc-1; i>0; i--){
  104665. p->a[i].fg.jointype = p->a[i-1].fg.jointype;
  104666. }
  104667. p->a[0].fg.jointype = 0;
  104668. }
  104669. }
  104670. /*
  104671. ** Generate VDBE code for a BEGIN statement.
  104672. */
  104673. SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
  104674. sqlite3 *db;
  104675. Vdbe *v;
  104676. int i;
  104677. assert( pParse!=0 );
  104678. db = pParse->db;
  104679. assert( db!=0 );
  104680. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
  104681. return;
  104682. }
  104683. v = sqlite3GetVdbe(pParse);
  104684. if( !v ) return;
  104685. if( type!=TK_DEFERRED ){
  104686. for(i=0; i<db->nDb; i++){
  104687. sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
  104688. sqlite3VdbeUsesBtree(v, i);
  104689. }
  104690. }
  104691. sqlite3VdbeAddOp0(v, OP_AutoCommit);
  104692. }
  104693. /*
  104694. ** Generate VDBE code for a COMMIT or ROLLBACK statement.
  104695. ** Code for ROLLBACK is generated if eType==TK_ROLLBACK. Otherwise
  104696. ** code is generated for a COMMIT.
  104697. */
  104698. SQLITE_PRIVATE void sqlite3EndTransaction(Parse *pParse, int eType){
  104699. Vdbe *v;
  104700. int isRollback;
  104701. assert( pParse!=0 );
  104702. assert( pParse->db!=0 );
  104703. assert( eType==TK_COMMIT || eType==TK_END || eType==TK_ROLLBACK );
  104704. isRollback = eType==TK_ROLLBACK;
  104705. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION,
  104706. isRollback ? "ROLLBACK" : "COMMIT", 0, 0) ){
  104707. return;
  104708. }
  104709. v = sqlite3GetVdbe(pParse);
  104710. if( v ){
  104711. sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, isRollback);
  104712. }
  104713. }
  104714. /*
  104715. ** This function is called by the parser when it parses a command to create,
  104716. ** release or rollback an SQL savepoint.
  104717. */
  104718. SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
  104719. char *zName = sqlite3NameFromToken(pParse->db, pName);
  104720. if( zName ){
  104721. Vdbe *v = sqlite3GetVdbe(pParse);
  104722. #ifndef SQLITE_OMIT_AUTHORIZATION
  104723. static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
  104724. assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
  104725. #endif
  104726. if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
  104727. sqlite3DbFree(pParse->db, zName);
  104728. return;
  104729. }
  104730. sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
  104731. }
  104732. }
  104733. /*
  104734. ** Make sure the TEMP database is open and available for use. Return
  104735. ** the number of errors. Leave any error messages in the pParse structure.
  104736. */
  104737. SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
  104738. sqlite3 *db = pParse->db;
  104739. if( db->aDb[1].pBt==0 && !pParse->explain ){
  104740. int rc;
  104741. Btree *pBt;
  104742. static const int flags =
  104743. SQLITE_OPEN_READWRITE |
  104744. SQLITE_OPEN_CREATE |
  104745. SQLITE_OPEN_EXCLUSIVE |
  104746. SQLITE_OPEN_DELETEONCLOSE |
  104747. SQLITE_OPEN_TEMP_DB;
  104748. rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
  104749. if( rc!=SQLITE_OK ){
  104750. sqlite3ErrorMsg(pParse, "unable to open a temporary database "
  104751. "file for storing temporary tables");
  104752. pParse->rc = rc;
  104753. return 1;
  104754. }
  104755. db->aDb[1].pBt = pBt;
  104756. assert( db->aDb[1].pSchema );
  104757. if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
  104758. sqlite3OomFault(db);
  104759. return 1;
  104760. }
  104761. }
  104762. return 0;
  104763. }
  104764. /*
  104765. ** Record the fact that the schema cookie will need to be verified
  104766. ** for database iDb. The code to actually verify the schema cookie
  104767. ** will occur at the end of the top-level VDBE and will be generated
  104768. ** later, by sqlite3FinishCoding().
  104769. */
  104770. SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
  104771. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  104772. assert( iDb>=0 && iDb<pParse->db->nDb );
  104773. assert( pParse->db->aDb[iDb].pBt!=0 || iDb==1 );
  104774. assert( iDb<SQLITE_MAX_ATTACHED+2 );
  104775. assert( sqlite3SchemaMutexHeld(pParse->db, iDb, 0) );
  104776. if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
  104777. DbMaskSet(pToplevel->cookieMask, iDb);
  104778. if( !OMIT_TEMPDB && iDb==1 ){
  104779. sqlite3OpenTempDatabase(pToplevel);
  104780. }
  104781. }
  104782. }
  104783. /*
  104784. ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
  104785. ** attached database. Otherwise, invoke it for the database named zDb only.
  104786. */
  104787. SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
  104788. sqlite3 *db = pParse->db;
  104789. int i;
  104790. for(i=0; i<db->nDb; i++){
  104791. Db *pDb = &db->aDb[i];
  104792. if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zDbSName)) ){
  104793. sqlite3CodeVerifySchema(pParse, i);
  104794. }
  104795. }
  104796. }
  104797. /*
  104798. ** Generate VDBE code that prepares for doing an operation that
  104799. ** might change the database.
  104800. **
  104801. ** This routine starts a new transaction if we are not already within
  104802. ** a transaction. If we are already within a transaction, then a checkpoint
  104803. ** is set if the setStatement parameter is true. A checkpoint should
  104804. ** be set for operations that might fail (due to a constraint) part of
  104805. ** the way through and which will need to undo some writes without having to
  104806. ** rollback the whole transaction. For operations where all constraints
  104807. ** can be checked before any changes are made to the database, it is never
  104808. ** necessary to undo a write and the checkpoint should not be set.
  104809. */
  104810. SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
  104811. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  104812. sqlite3CodeVerifySchema(pParse, iDb);
  104813. DbMaskSet(pToplevel->writeMask, iDb);
  104814. pToplevel->isMultiWrite |= setStatement;
  104815. }
  104816. /*
  104817. ** Indicate that the statement currently under construction might write
  104818. ** more than one entry (example: deleting one row then inserting another,
  104819. ** inserting multiple rows in a table, or inserting a row and index entries.)
  104820. ** If an abort occurs after some of these writes have completed, then it will
  104821. ** be necessary to undo the completed writes.
  104822. */
  104823. SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
  104824. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  104825. pToplevel->isMultiWrite = 1;
  104826. }
  104827. /*
  104828. ** The code generator calls this routine if is discovers that it is
  104829. ** possible to abort a statement prior to completion. In order to
  104830. ** perform this abort without corrupting the database, we need to make
  104831. ** sure that the statement is protected by a statement transaction.
  104832. **
  104833. ** Technically, we only need to set the mayAbort flag if the
  104834. ** isMultiWrite flag was previously set. There is a time dependency
  104835. ** such that the abort must occur after the multiwrite. This makes
  104836. ** some statements involving the REPLACE conflict resolution algorithm
  104837. ** go a little faster. But taking advantage of this time dependency
  104838. ** makes it more difficult to prove that the code is correct (in
  104839. ** particular, it prevents us from writing an effective
  104840. ** implementation of sqlite3AssertMayAbort()) and so we have chosen
  104841. ** to take the safe route and skip the optimization.
  104842. */
  104843. SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
  104844. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  104845. pToplevel->mayAbort = 1;
  104846. }
  104847. /*
  104848. ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
  104849. ** error. The onError parameter determines which (if any) of the statement
  104850. ** and/or current transaction is rolled back.
  104851. */
  104852. SQLITE_PRIVATE void sqlite3HaltConstraint(
  104853. Parse *pParse, /* Parsing context */
  104854. int errCode, /* extended error code */
  104855. int onError, /* Constraint type */
  104856. char *p4, /* Error message */
  104857. i8 p4type, /* P4_STATIC or P4_TRANSIENT */
  104858. u8 p5Errmsg /* P5_ErrMsg type */
  104859. ){
  104860. Vdbe *v = sqlite3GetVdbe(pParse);
  104861. assert( (errCode&0xff)==SQLITE_CONSTRAINT );
  104862. if( onError==OE_Abort ){
  104863. sqlite3MayAbort(pParse);
  104864. }
  104865. sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
  104866. sqlite3VdbeChangeP5(v, p5Errmsg);
  104867. }
  104868. /*
  104869. ** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
  104870. */
  104871. SQLITE_PRIVATE void sqlite3UniqueConstraint(
  104872. Parse *pParse, /* Parsing context */
  104873. int onError, /* Constraint type */
  104874. Index *pIdx /* The index that triggers the constraint */
  104875. ){
  104876. char *zErr;
  104877. int j;
  104878. StrAccum errMsg;
  104879. Table *pTab = pIdx->pTable;
  104880. sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0,
  104881. pParse->db->aLimit[SQLITE_LIMIT_LENGTH]);
  104882. if( pIdx->aColExpr ){
  104883. sqlite3_str_appendf(&errMsg, "index '%q'", pIdx->zName);
  104884. }else{
  104885. for(j=0; j<pIdx->nKeyCol; j++){
  104886. char *zCol;
  104887. assert( pIdx->aiColumn[j]>=0 );
  104888. zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
  104889. if( j ) sqlite3_str_append(&errMsg, ", ", 2);
  104890. sqlite3_str_appendall(&errMsg, pTab->zName);
  104891. sqlite3_str_append(&errMsg, ".", 1);
  104892. sqlite3_str_appendall(&errMsg, zCol);
  104893. }
  104894. }
  104895. zErr = sqlite3StrAccumFinish(&errMsg);
  104896. sqlite3HaltConstraint(pParse,
  104897. IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY
  104898. : SQLITE_CONSTRAINT_UNIQUE,
  104899. onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
  104900. }
  104901. /*
  104902. ** Code an OP_Halt due to non-unique rowid.
  104903. */
  104904. SQLITE_PRIVATE void sqlite3RowidConstraint(
  104905. Parse *pParse, /* Parsing context */
  104906. int onError, /* Conflict resolution algorithm */
  104907. Table *pTab /* The table with the non-unique rowid */
  104908. ){
  104909. char *zMsg;
  104910. int rc;
  104911. if( pTab->iPKey>=0 ){
  104912. zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
  104913. pTab->aCol[pTab->iPKey].zName);
  104914. rc = SQLITE_CONSTRAINT_PRIMARYKEY;
  104915. }else{
  104916. zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
  104917. rc = SQLITE_CONSTRAINT_ROWID;
  104918. }
  104919. sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
  104920. P5_ConstraintUnique);
  104921. }
  104922. /*
  104923. ** Check to see if pIndex uses the collating sequence pColl. Return
  104924. ** true if it does and false if it does not.
  104925. */
  104926. #ifndef SQLITE_OMIT_REINDEX
  104927. static int collationMatch(const char *zColl, Index *pIndex){
  104928. int i;
  104929. assert( zColl!=0 );
  104930. for(i=0; i<pIndex->nColumn; i++){
  104931. const char *z = pIndex->azColl[i];
  104932. assert( z!=0 || pIndex->aiColumn[i]<0 );
  104933. if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
  104934. return 1;
  104935. }
  104936. }
  104937. return 0;
  104938. }
  104939. #endif
  104940. /*
  104941. ** Recompute all indices of pTab that use the collating sequence pColl.
  104942. ** If pColl==0 then recompute all indices of pTab.
  104943. */
  104944. #ifndef SQLITE_OMIT_REINDEX
  104945. static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
  104946. if( !IsVirtual(pTab) ){
  104947. Index *pIndex; /* An index associated with pTab */
  104948. for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
  104949. if( zColl==0 || collationMatch(zColl, pIndex) ){
  104950. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  104951. sqlite3BeginWriteOperation(pParse, 0, iDb);
  104952. sqlite3RefillIndex(pParse, pIndex, -1);
  104953. }
  104954. }
  104955. }
  104956. }
  104957. #endif
  104958. /*
  104959. ** Recompute all indices of all tables in all databases where the
  104960. ** indices use the collating sequence pColl. If pColl==0 then recompute
  104961. ** all indices everywhere.
  104962. */
  104963. #ifndef SQLITE_OMIT_REINDEX
  104964. static void reindexDatabases(Parse *pParse, char const *zColl){
  104965. Db *pDb; /* A single database */
  104966. int iDb; /* The database index number */
  104967. sqlite3 *db = pParse->db; /* The database connection */
  104968. HashElem *k; /* For looping over tables in pDb */
  104969. Table *pTab; /* A table in the database */
  104970. assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
  104971. for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
  104972. assert( pDb!=0 );
  104973. for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
  104974. pTab = (Table*)sqliteHashData(k);
  104975. reindexTable(pParse, pTab, zColl);
  104976. }
  104977. }
  104978. }
  104979. #endif
  104980. /*
  104981. ** Generate code for the REINDEX command.
  104982. **
  104983. ** REINDEX -- 1
  104984. ** REINDEX <collation> -- 2
  104985. ** REINDEX ?<database>.?<tablename> -- 3
  104986. ** REINDEX ?<database>.?<indexname> -- 4
  104987. **
  104988. ** Form 1 causes all indices in all attached databases to be rebuilt.
  104989. ** Form 2 rebuilds all indices in all databases that use the named
  104990. ** collating function. Forms 3 and 4 rebuild the named index or all
  104991. ** indices associated with the named table.
  104992. */
  104993. #ifndef SQLITE_OMIT_REINDEX
  104994. SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
  104995. CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
  104996. char *z; /* Name of a table or index */
  104997. const char *zDb; /* Name of the database */
  104998. Table *pTab; /* A table in the database */
  104999. Index *pIndex; /* An index associated with pTab */
  105000. int iDb; /* The database index number */
  105001. sqlite3 *db = pParse->db; /* The database connection */
  105002. Token *pObjName; /* Name of the table or index to be reindexed */
  105003. /* Read the database schema. If an error occurs, leave an error message
  105004. ** and code in pParse and return NULL. */
  105005. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  105006. return;
  105007. }
  105008. if( pName1==0 ){
  105009. reindexDatabases(pParse, 0);
  105010. return;
  105011. }else if( NEVER(pName2==0) || pName2->z==0 ){
  105012. char *zColl;
  105013. assert( pName1->z );
  105014. zColl = sqlite3NameFromToken(pParse->db, pName1);
  105015. if( !zColl ) return;
  105016. pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
  105017. if( pColl ){
  105018. reindexDatabases(pParse, zColl);
  105019. sqlite3DbFree(db, zColl);
  105020. return;
  105021. }
  105022. sqlite3DbFree(db, zColl);
  105023. }
  105024. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
  105025. if( iDb<0 ) return;
  105026. z = sqlite3NameFromToken(db, pObjName);
  105027. if( z==0 ) return;
  105028. zDb = db->aDb[iDb].zDbSName;
  105029. pTab = sqlite3FindTable(db, z, zDb);
  105030. if( pTab ){
  105031. reindexTable(pParse, pTab, 0);
  105032. sqlite3DbFree(db, z);
  105033. return;
  105034. }
  105035. pIndex = sqlite3FindIndex(db, z, zDb);
  105036. sqlite3DbFree(db, z);
  105037. if( pIndex ){
  105038. sqlite3BeginWriteOperation(pParse, 0, iDb);
  105039. sqlite3RefillIndex(pParse, pIndex, -1);
  105040. return;
  105041. }
  105042. sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
  105043. }
  105044. #endif
  105045. /*
  105046. ** Return a KeyInfo structure that is appropriate for the given Index.
  105047. **
  105048. ** The caller should invoke sqlite3KeyInfoUnref() on the returned object
  105049. ** when it has finished using it.
  105050. */
  105051. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
  105052. int i;
  105053. int nCol = pIdx->nColumn;
  105054. int nKey = pIdx->nKeyCol;
  105055. KeyInfo *pKey;
  105056. if( pParse->nErr ) return 0;
  105057. if( pIdx->uniqNotNull ){
  105058. pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
  105059. }else{
  105060. pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
  105061. }
  105062. if( pKey ){
  105063. assert( sqlite3KeyInfoIsWriteable(pKey) );
  105064. for(i=0; i<nCol; i++){
  105065. const char *zColl = pIdx->azColl[i];
  105066. pKey->aColl[i] = zColl==sqlite3StrBINARY ? 0 :
  105067. sqlite3LocateCollSeq(pParse, zColl);
  105068. pKey->aSortOrder[i] = pIdx->aSortOrder[i];
  105069. }
  105070. if( pParse->nErr ){
  105071. assert( pParse->rc==SQLITE_ERROR_MISSING_COLLSEQ );
  105072. if( pIdx->bNoQuery==0 ){
  105073. /* Deactivate the index because it contains an unknown collating
  105074. ** sequence. The only way to reactive the index is to reload the
  105075. ** schema. Adding the missing collating sequence later does not
  105076. ** reactive the index. The application had the chance to register
  105077. ** the missing index using the collation-needed callback. For
  105078. ** simplicity, SQLite will not give the application a second chance.
  105079. */
  105080. pIdx->bNoQuery = 1;
  105081. pParse->rc = SQLITE_ERROR_RETRY;
  105082. }
  105083. sqlite3KeyInfoUnref(pKey);
  105084. pKey = 0;
  105085. }
  105086. }
  105087. return pKey;
  105088. }
  105089. #ifndef SQLITE_OMIT_CTE
  105090. /*
  105091. ** This routine is invoked once per CTE by the parser while parsing a
  105092. ** WITH clause.
  105093. */
  105094. SQLITE_PRIVATE With *sqlite3WithAdd(
  105095. Parse *pParse, /* Parsing context */
  105096. With *pWith, /* Existing WITH clause, or NULL */
  105097. Token *pName, /* Name of the common-table */
  105098. ExprList *pArglist, /* Optional column name list for the table */
  105099. Select *pQuery /* Query used to initialize the table */
  105100. ){
  105101. sqlite3 *db = pParse->db;
  105102. With *pNew;
  105103. char *zName;
  105104. /* Check that the CTE name is unique within this WITH clause. If
  105105. ** not, store an error in the Parse structure. */
  105106. zName = sqlite3NameFromToken(pParse->db, pName);
  105107. if( zName && pWith ){
  105108. int i;
  105109. for(i=0; i<pWith->nCte; i++){
  105110. if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
  105111. sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
  105112. }
  105113. }
  105114. }
  105115. if( pWith ){
  105116. sqlite3_int64 nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
  105117. pNew = sqlite3DbRealloc(db, pWith, nByte);
  105118. }else{
  105119. pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
  105120. }
  105121. assert( (pNew!=0 && zName!=0) || db->mallocFailed );
  105122. if( db->mallocFailed ){
  105123. sqlite3ExprListDelete(db, pArglist);
  105124. sqlite3SelectDelete(db, pQuery);
  105125. sqlite3DbFree(db, zName);
  105126. pNew = pWith;
  105127. }else{
  105128. pNew->a[pNew->nCte].pSelect = pQuery;
  105129. pNew->a[pNew->nCte].pCols = pArglist;
  105130. pNew->a[pNew->nCte].zName = zName;
  105131. pNew->a[pNew->nCte].zCteErr = 0;
  105132. pNew->nCte++;
  105133. }
  105134. return pNew;
  105135. }
  105136. /*
  105137. ** Free the contents of the With object passed as the second argument.
  105138. */
  105139. SQLITE_PRIVATE void sqlite3WithDelete(sqlite3 *db, With *pWith){
  105140. if( pWith ){
  105141. int i;
  105142. for(i=0; i<pWith->nCte; i++){
  105143. struct Cte *pCte = &pWith->a[i];
  105144. sqlite3ExprListDelete(db, pCte->pCols);
  105145. sqlite3SelectDelete(db, pCte->pSelect);
  105146. sqlite3DbFree(db, pCte->zName);
  105147. }
  105148. sqlite3DbFree(db, pWith);
  105149. }
  105150. }
  105151. #endif /* !defined(SQLITE_OMIT_CTE) */
  105152. /************** End of build.c ***********************************************/
  105153. /************** Begin file callback.c ****************************************/
  105154. /*
  105155. ** 2005 May 23
  105156. **
  105157. ** The author disclaims copyright to this source code. In place of
  105158. ** a legal notice, here is a blessing:
  105159. **
  105160. ** May you do good and not evil.
  105161. ** May you find forgiveness for yourself and forgive others.
  105162. ** May you share freely, never taking more than you give.
  105163. **
  105164. *************************************************************************
  105165. **
  105166. ** This file contains functions used to access the internal hash tables
  105167. ** of user defined functions and collation sequences.
  105168. */
  105169. /* #include "sqliteInt.h" */
  105170. /*
  105171. ** Invoke the 'collation needed' callback to request a collation sequence
  105172. ** in the encoding enc of name zName, length nName.
  105173. */
  105174. static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
  105175. assert( !db->xCollNeeded || !db->xCollNeeded16 );
  105176. if( db->xCollNeeded ){
  105177. char *zExternal = sqlite3DbStrDup(db, zName);
  105178. if( !zExternal ) return;
  105179. db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
  105180. sqlite3DbFree(db, zExternal);
  105181. }
  105182. #ifndef SQLITE_OMIT_UTF16
  105183. if( db->xCollNeeded16 ){
  105184. char const *zExternal;
  105185. sqlite3_value *pTmp = sqlite3ValueNew(db);
  105186. sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
  105187. zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
  105188. if( zExternal ){
  105189. db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
  105190. }
  105191. sqlite3ValueFree(pTmp);
  105192. }
  105193. #endif
  105194. }
  105195. /*
  105196. ** This routine is called if the collation factory fails to deliver a
  105197. ** collation function in the best encoding but there may be other versions
  105198. ** of this collation function (for other text encodings) available. Use one
  105199. ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
  105200. ** possible.
  105201. */
  105202. static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
  105203. CollSeq *pColl2;
  105204. char *z = pColl->zName;
  105205. int i;
  105206. static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
  105207. for(i=0; i<3; i++){
  105208. pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
  105209. if( pColl2->xCmp!=0 ){
  105210. memcpy(pColl, pColl2, sizeof(CollSeq));
  105211. pColl->xDel = 0; /* Do not copy the destructor */
  105212. return SQLITE_OK;
  105213. }
  105214. }
  105215. return SQLITE_ERROR;
  105216. }
  105217. /*
  105218. ** This function is responsible for invoking the collation factory callback
  105219. ** or substituting a collation sequence of a different encoding when the
  105220. ** requested collation sequence is not available in the desired encoding.
  105221. **
  105222. ** If it is not NULL, then pColl must point to the database native encoding
  105223. ** collation sequence with name zName, length nName.
  105224. **
  105225. ** The return value is either the collation sequence to be used in database
  105226. ** db for collation type name zName, length nName, or NULL, if no collation
  105227. ** sequence can be found. If no collation is found, leave an error message.
  105228. **
  105229. ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
  105230. */
  105231. SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
  105232. Parse *pParse, /* Parsing context */
  105233. u8 enc, /* The desired encoding for the collating sequence */
  105234. CollSeq *pColl, /* Collating sequence with native encoding, or NULL */
  105235. const char *zName /* Collating sequence name */
  105236. ){
  105237. CollSeq *p;
  105238. sqlite3 *db = pParse->db;
  105239. p = pColl;
  105240. if( !p ){
  105241. p = sqlite3FindCollSeq(db, enc, zName, 0);
  105242. }
  105243. if( !p || !p->xCmp ){
  105244. /* No collation sequence of this type for this encoding is registered.
  105245. ** Call the collation factory to see if it can supply us with one.
  105246. */
  105247. callCollNeeded(db, enc, zName);
  105248. p = sqlite3FindCollSeq(db, enc, zName, 0);
  105249. }
  105250. if( p && !p->xCmp && synthCollSeq(db, p) ){
  105251. p = 0;
  105252. }
  105253. assert( !p || p->xCmp );
  105254. if( p==0 ){
  105255. sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
  105256. pParse->rc = SQLITE_ERROR_MISSING_COLLSEQ;
  105257. }
  105258. return p;
  105259. }
  105260. /*
  105261. ** This routine is called on a collation sequence before it is used to
  105262. ** check that it is defined. An undefined collation sequence exists when
  105263. ** a database is loaded that contains references to collation sequences
  105264. ** that have not been defined by sqlite3_create_collation() etc.
  105265. **
  105266. ** If required, this routine calls the 'collation needed' callback to
  105267. ** request a definition of the collating sequence. If this doesn't work,
  105268. ** an equivalent collating sequence that uses a text encoding different
  105269. ** from the main database is substituted, if one is available.
  105270. */
  105271. SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
  105272. if( pColl && pColl->xCmp==0 ){
  105273. const char *zName = pColl->zName;
  105274. sqlite3 *db = pParse->db;
  105275. CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName);
  105276. if( !p ){
  105277. return SQLITE_ERROR;
  105278. }
  105279. assert( p==pColl );
  105280. }
  105281. return SQLITE_OK;
  105282. }
  105283. /*
  105284. ** Locate and return an entry from the db.aCollSeq hash table. If the entry
  105285. ** specified by zName and nName is not found and parameter 'create' is
  105286. ** true, then create a new entry. Otherwise return NULL.
  105287. **
  105288. ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
  105289. ** array of three CollSeq structures. The first is the collation sequence
  105290. ** preferred for UTF-8, the second UTF-16le, and the third UTF-16be.
  105291. **
  105292. ** Stored immediately after the three collation sequences is a copy of
  105293. ** the collation sequence name. A pointer to this string is stored in
  105294. ** each collation sequence structure.
  105295. */
  105296. static CollSeq *findCollSeqEntry(
  105297. sqlite3 *db, /* Database connection */
  105298. const char *zName, /* Name of the collating sequence */
  105299. int create /* Create a new entry if true */
  105300. ){
  105301. CollSeq *pColl;
  105302. pColl = sqlite3HashFind(&db->aCollSeq, zName);
  105303. if( 0==pColl && create ){
  105304. int nName = sqlite3Strlen30(zName) + 1;
  105305. pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName);
  105306. if( pColl ){
  105307. CollSeq *pDel = 0;
  105308. pColl[0].zName = (char*)&pColl[3];
  105309. pColl[0].enc = SQLITE_UTF8;
  105310. pColl[1].zName = (char*)&pColl[3];
  105311. pColl[1].enc = SQLITE_UTF16LE;
  105312. pColl[2].zName = (char*)&pColl[3];
  105313. pColl[2].enc = SQLITE_UTF16BE;
  105314. memcpy(pColl[0].zName, zName, nName);
  105315. pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, pColl);
  105316. /* If a malloc() failure occurred in sqlite3HashInsert(), it will
  105317. ** return the pColl pointer to be deleted (because it wasn't added
  105318. ** to the hash table).
  105319. */
  105320. assert( pDel==0 || pDel==pColl );
  105321. if( pDel!=0 ){
  105322. sqlite3OomFault(db);
  105323. sqlite3DbFree(db, pDel);
  105324. pColl = 0;
  105325. }
  105326. }
  105327. }
  105328. return pColl;
  105329. }
  105330. /*
  105331. ** Parameter zName points to a UTF-8 encoded string nName bytes long.
  105332. ** Return the CollSeq* pointer for the collation sequence named zName
  105333. ** for the encoding 'enc' from the database 'db'.
  105334. **
  105335. ** If the entry specified is not found and 'create' is true, then create a
  105336. ** new entry. Otherwise return NULL.
  105337. **
  105338. ** A separate function sqlite3LocateCollSeq() is a wrapper around
  105339. ** this routine. sqlite3LocateCollSeq() invokes the collation factory
  105340. ** if necessary and generates an error message if the collating sequence
  105341. ** cannot be found.
  105342. **
  105343. ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
  105344. */
  105345. SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
  105346. sqlite3 *db,
  105347. u8 enc,
  105348. const char *zName,
  105349. int create
  105350. ){
  105351. CollSeq *pColl;
  105352. if( zName ){
  105353. pColl = findCollSeqEntry(db, zName, create);
  105354. }else{
  105355. pColl = db->pDfltColl;
  105356. }
  105357. assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  105358. assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
  105359. if( pColl ) pColl += enc-1;
  105360. return pColl;
  105361. }
  105362. /* During the search for the best function definition, this procedure
  105363. ** is called to test how well the function passed as the first argument
  105364. ** matches the request for a function with nArg arguments in a system
  105365. ** that uses encoding enc. The value returned indicates how well the
  105366. ** request is matched. A higher value indicates a better match.
  105367. **
  105368. ** If nArg is -1 that means to only return a match (non-zero) if p->nArg
  105369. ** is also -1. In other words, we are searching for a function that
  105370. ** takes a variable number of arguments.
  105371. **
  105372. ** If nArg is -2 that means that we are searching for any function
  105373. ** regardless of the number of arguments it uses, so return a positive
  105374. ** match score for any
  105375. **
  105376. ** The returned value is always between 0 and 6, as follows:
  105377. **
  105378. ** 0: Not a match.
  105379. ** 1: UTF8/16 conversion required and function takes any number of arguments.
  105380. ** 2: UTF16 byte order change required and function takes any number of args.
  105381. ** 3: encoding matches and function takes any number of arguments
  105382. ** 4: UTF8/16 conversion required - argument count matches exactly
  105383. ** 5: UTF16 byte order conversion required - argument count matches exactly
  105384. ** 6: Perfect match: encoding and argument count match exactly.
  105385. **
  105386. ** If nArg==(-2) then any function with a non-null xSFunc is
  105387. ** a perfect match and any function with xSFunc NULL is
  105388. ** a non-match.
  105389. */
  105390. #define FUNC_PERFECT_MATCH 6 /* The score for a perfect match */
  105391. static int matchQuality(
  105392. FuncDef *p, /* The function we are evaluating for match quality */
  105393. int nArg, /* Desired number of arguments. (-1)==any */
  105394. u8 enc /* Desired text encoding */
  105395. ){
  105396. int match;
  105397. /* nArg of -2 is a special case */
  105398. if( nArg==(-2) ) return (p->xSFunc==0) ? 0 : FUNC_PERFECT_MATCH;
  105399. /* Wrong number of arguments means "no match" */
  105400. if( p->nArg!=nArg && p->nArg>=0 ) return 0;
  105401. /* Give a better score to a function with a specific number of arguments
  105402. ** than to function that accepts any number of arguments. */
  105403. if( p->nArg==nArg ){
  105404. match = 4;
  105405. }else{
  105406. match = 1;
  105407. }
  105408. /* Bonus points if the text encoding matches */
  105409. if( enc==(p->funcFlags & SQLITE_FUNC_ENCMASK) ){
  105410. match += 2; /* Exact encoding match */
  105411. }else if( (enc & p->funcFlags & 2)!=0 ){
  105412. match += 1; /* Both are UTF16, but with different byte orders */
  105413. }
  105414. return match;
  105415. }
  105416. /*
  105417. ** Search a FuncDefHash for a function with the given name. Return
  105418. ** a pointer to the matching FuncDef if found, or 0 if there is no match.
  105419. */
  105420. SQLITE_PRIVATE FuncDef *sqlite3FunctionSearch(
  105421. int h, /* Hash of the name */
  105422. const char *zFunc /* Name of function */
  105423. ){
  105424. FuncDef *p;
  105425. for(p=sqlite3BuiltinFunctions.a[h]; p; p=p->u.pHash){
  105426. if( sqlite3StrICmp(p->zName, zFunc)==0 ){
  105427. return p;
  105428. }
  105429. }
  105430. return 0;
  105431. }
  105432. /*
  105433. ** Insert a new FuncDef into a FuncDefHash hash table.
  105434. */
  105435. SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(
  105436. FuncDef *aDef, /* List of global functions to be inserted */
  105437. int nDef /* Length of the apDef[] list */
  105438. ){
  105439. int i;
  105440. for(i=0; i<nDef; i++){
  105441. FuncDef *pOther;
  105442. const char *zName = aDef[i].zName;
  105443. int nName = sqlite3Strlen30(zName);
  105444. int h = SQLITE_FUNC_HASH(zName[0], nName);
  105445. assert( zName[0]>='a' && zName[0]<='z' );
  105446. pOther = sqlite3FunctionSearch(h, zName);
  105447. if( pOther ){
  105448. assert( pOther!=&aDef[i] && pOther->pNext!=&aDef[i] );
  105449. aDef[i].pNext = pOther->pNext;
  105450. pOther->pNext = &aDef[i];
  105451. }else{
  105452. aDef[i].pNext = 0;
  105453. aDef[i].u.pHash = sqlite3BuiltinFunctions.a[h];
  105454. sqlite3BuiltinFunctions.a[h] = &aDef[i];
  105455. }
  105456. }
  105457. }
  105458. /*
  105459. ** Locate a user function given a name, a number of arguments and a flag
  105460. ** indicating whether the function prefers UTF-16 over UTF-8. Return a
  105461. ** pointer to the FuncDef structure that defines that function, or return
  105462. ** NULL if the function does not exist.
  105463. **
  105464. ** If the createFlag argument is true, then a new (blank) FuncDef
  105465. ** structure is created and liked into the "db" structure if a
  105466. ** no matching function previously existed.
  105467. **
  105468. ** If nArg is -2, then the first valid function found is returned. A
  105469. ** function is valid if xSFunc is non-zero. The nArg==(-2)
  105470. ** case is used to see if zName is a valid function name for some number
  105471. ** of arguments. If nArg is -2, then createFlag must be 0.
  105472. **
  105473. ** If createFlag is false, then a function with the required name and
  105474. ** number of arguments may be returned even if the eTextRep flag does not
  105475. ** match that requested.
  105476. */
  105477. SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
  105478. sqlite3 *db, /* An open database */
  105479. const char *zName, /* Name of the function. zero-terminated */
  105480. int nArg, /* Number of arguments. -1 means any number */
  105481. u8 enc, /* Preferred text encoding */
  105482. u8 createFlag /* Create new entry if true and does not otherwise exist */
  105483. ){
  105484. FuncDef *p; /* Iterator variable */
  105485. FuncDef *pBest = 0; /* Best match found so far */
  105486. int bestScore = 0; /* Score of best match */
  105487. int h; /* Hash value */
  105488. int nName; /* Length of the name */
  105489. assert( nArg>=(-2) );
  105490. assert( nArg>=(-1) || createFlag==0 );
  105491. nName = sqlite3Strlen30(zName);
  105492. /* First search for a match amongst the application-defined functions.
  105493. */
  105494. p = (FuncDef*)sqlite3HashFind(&db->aFunc, zName);
  105495. while( p ){
  105496. int score = matchQuality(p, nArg, enc);
  105497. if( score>bestScore ){
  105498. pBest = p;
  105499. bestScore = score;
  105500. }
  105501. p = p->pNext;
  105502. }
  105503. /* If no match is found, search the built-in functions.
  105504. **
  105505. ** If the DBFLAG_PreferBuiltin flag is set, then search the built-in
  105506. ** functions even if a prior app-defined function was found. And give
  105507. ** priority to built-in functions.
  105508. **
  105509. ** Except, if createFlag is true, that means that we are trying to
  105510. ** install a new function. Whatever FuncDef structure is returned it will
  105511. ** have fields overwritten with new information appropriate for the
  105512. ** new function. But the FuncDefs for built-in functions are read-only.
  105513. ** So we must not search for built-ins when creating a new function.
  105514. */
  105515. if( !createFlag && (pBest==0 || (db->mDbFlags & DBFLAG_PreferBuiltin)!=0) ){
  105516. bestScore = 0;
  105517. h = SQLITE_FUNC_HASH(sqlite3UpperToLower[(u8)zName[0]], nName);
  105518. p = sqlite3FunctionSearch(h, zName);
  105519. while( p ){
  105520. int score = matchQuality(p, nArg, enc);
  105521. if( score>bestScore ){
  105522. pBest = p;
  105523. bestScore = score;
  105524. }
  105525. p = p->pNext;
  105526. }
  105527. }
  105528. /* If the createFlag parameter is true and the search did not reveal an
  105529. ** exact match for the name, number of arguments and encoding, then add a
  105530. ** new entry to the hash table and return it.
  105531. */
  105532. if( createFlag && bestScore<FUNC_PERFECT_MATCH &&
  105533. (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
  105534. FuncDef *pOther;
  105535. u8 *z;
  105536. pBest->zName = (const char*)&pBest[1];
  105537. pBest->nArg = (u16)nArg;
  105538. pBest->funcFlags = enc;
  105539. memcpy((char*)&pBest[1], zName, nName+1);
  105540. for(z=(u8*)pBest->zName; *z; z++) *z = sqlite3UpperToLower[*z];
  105541. pOther = (FuncDef*)sqlite3HashInsert(&db->aFunc, pBest->zName, pBest);
  105542. if( pOther==pBest ){
  105543. sqlite3DbFree(db, pBest);
  105544. sqlite3OomFault(db);
  105545. return 0;
  105546. }else{
  105547. pBest->pNext = pOther;
  105548. }
  105549. }
  105550. if( pBest && (pBest->xSFunc || createFlag) ){
  105551. return pBest;
  105552. }
  105553. return 0;
  105554. }
  105555. /*
  105556. ** Free all resources held by the schema structure. The void* argument points
  105557. ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
  105558. ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
  105559. ** of the schema hash tables).
  105560. **
  105561. ** The Schema.cache_size variable is not cleared.
  105562. */
  105563. SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
  105564. Hash temp1;
  105565. Hash temp2;
  105566. HashElem *pElem;
  105567. Schema *pSchema = (Schema *)p;
  105568. temp1 = pSchema->tblHash;
  105569. temp2 = pSchema->trigHash;
  105570. sqlite3HashInit(&pSchema->trigHash);
  105571. sqlite3HashClear(&pSchema->idxHash);
  105572. for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
  105573. sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
  105574. }
  105575. sqlite3HashClear(&temp2);
  105576. sqlite3HashInit(&pSchema->tblHash);
  105577. for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
  105578. Table *pTab = sqliteHashData(pElem);
  105579. sqlite3DeleteTable(0, pTab);
  105580. }
  105581. sqlite3HashClear(&temp1);
  105582. sqlite3HashClear(&pSchema->fkeyHash);
  105583. pSchema->pSeqTab = 0;
  105584. if( pSchema->schemaFlags & DB_SchemaLoaded ){
  105585. pSchema->iGeneration++;
  105586. }
  105587. pSchema->schemaFlags &= ~(DB_SchemaLoaded|DB_ResetWanted);
  105588. }
  105589. /*
  105590. ** Find and return the schema associated with a BTree. Create
  105591. ** a new one if necessary.
  105592. */
  105593. SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
  105594. Schema * p;
  105595. if( pBt ){
  105596. p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
  105597. }else{
  105598. p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
  105599. }
  105600. if( !p ){
  105601. sqlite3OomFault(db);
  105602. }else if ( 0==p->file_format ){
  105603. sqlite3HashInit(&p->tblHash);
  105604. sqlite3HashInit(&p->idxHash);
  105605. sqlite3HashInit(&p->trigHash);
  105606. sqlite3HashInit(&p->fkeyHash);
  105607. p->enc = SQLITE_UTF8;
  105608. }
  105609. return p;
  105610. }
  105611. /************** End of callback.c ********************************************/
  105612. /************** Begin file delete.c ******************************************/
  105613. /*
  105614. ** 2001 September 15
  105615. **
  105616. ** The author disclaims copyright to this source code. In place of
  105617. ** a legal notice, here is a blessing:
  105618. **
  105619. ** May you do good and not evil.
  105620. ** May you find forgiveness for yourself and forgive others.
  105621. ** May you share freely, never taking more than you give.
  105622. **
  105623. *************************************************************************
  105624. ** This file contains C code routines that are called by the parser
  105625. ** in order to generate code for DELETE FROM statements.
  105626. */
  105627. /* #include "sqliteInt.h" */
  105628. /*
  105629. ** While a SrcList can in general represent multiple tables and subqueries
  105630. ** (as in the FROM clause of a SELECT statement) in this case it contains
  105631. ** the name of a single table, as one might find in an INSERT, DELETE,
  105632. ** or UPDATE statement. Look up that table in the symbol table and
  105633. ** return a pointer. Set an error message and return NULL if the table
  105634. ** name is not found or if any other error occurs.
  105635. **
  105636. ** The following fields are initialized appropriate in pSrc:
  105637. **
  105638. ** pSrc->a[0].pTab Pointer to the Table object
  105639. ** pSrc->a[0].pIndex Pointer to the INDEXED BY index, if there is one
  105640. **
  105641. */
  105642. SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
  105643. struct SrcList_item *pItem = pSrc->a;
  105644. Table *pTab;
  105645. assert( pItem && pSrc->nSrc==1 );
  105646. pTab = sqlite3LocateTableItem(pParse, 0, pItem);
  105647. sqlite3DeleteTable(pParse->db, pItem->pTab);
  105648. pItem->pTab = pTab;
  105649. if( pTab ){
  105650. pTab->nTabRef++;
  105651. }
  105652. if( sqlite3IndexedByLookup(pParse, pItem) ){
  105653. pTab = 0;
  105654. }
  105655. return pTab;
  105656. }
  105657. /* Return true if table pTab is read-only.
  105658. **
  105659. ** A table is read-only if any of the following are true:
  105660. **
  105661. ** 1) It is a virtual table and no implementation of the xUpdate method
  105662. ** has been provided
  105663. **
  105664. ** 2) It is a system table (i.e. sqlite_master), this call is not
  105665. ** part of a nested parse and writable_schema pragma has not
  105666. ** been specified
  105667. **
  105668. ** 3) The table is a shadow table, the database connection is in
  105669. ** defensive mode, and the current sqlite3_prepare()
  105670. ** is for a top-level SQL statement.
  105671. */
  105672. static int tabIsReadOnly(Parse *pParse, Table *pTab){
  105673. sqlite3 *db;
  105674. if( IsVirtual(pTab) ){
  105675. return sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0;
  105676. }
  105677. if( (pTab->tabFlags & (TF_Readonly|TF_Shadow))==0 ) return 0;
  105678. db = pParse->db;
  105679. if( (pTab->tabFlags & TF_Readonly)!=0 ){
  105680. return sqlite3WritableSchema(db)==0 && pParse->nested==0;
  105681. }
  105682. assert( pTab->tabFlags & TF_Shadow );
  105683. return (db->flags & SQLITE_Defensive)!=0
  105684. #ifndef SQLITE_OMIT_VIRTUALTABLE
  105685. && db->pVtabCtx==0
  105686. #endif
  105687. && db->nVdbeExec==0;
  105688. }
  105689. /*
  105690. ** Check to make sure the given table is writable. If it is not
  105691. ** writable, generate an error message and return 1. If it is
  105692. ** writable return 0;
  105693. */
  105694. SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
  105695. if( tabIsReadOnly(pParse, pTab) ){
  105696. sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
  105697. return 1;
  105698. }
  105699. #ifndef SQLITE_OMIT_VIEW
  105700. if( !viewOk && pTab->pSelect ){
  105701. sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
  105702. return 1;
  105703. }
  105704. #endif
  105705. return 0;
  105706. }
  105707. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  105708. /*
  105709. ** Evaluate a view and store its result in an ephemeral table. The
  105710. ** pWhere argument is an optional WHERE clause that restricts the
  105711. ** set of rows in the view that are to be added to the ephemeral table.
  105712. */
  105713. SQLITE_PRIVATE void sqlite3MaterializeView(
  105714. Parse *pParse, /* Parsing context */
  105715. Table *pView, /* View definition */
  105716. Expr *pWhere, /* Optional WHERE clause to be added */
  105717. ExprList *pOrderBy, /* Optional ORDER BY clause */
  105718. Expr *pLimit, /* Optional LIMIT clause */
  105719. int iCur /* Cursor number for ephemeral table */
  105720. ){
  105721. SelectDest dest;
  105722. Select *pSel;
  105723. SrcList *pFrom;
  105724. sqlite3 *db = pParse->db;
  105725. int iDb = sqlite3SchemaToIndex(db, pView->pSchema);
  105726. pWhere = sqlite3ExprDup(db, pWhere, 0);
  105727. pFrom = sqlite3SrcListAppend(pParse, 0, 0, 0);
  105728. if( pFrom ){
  105729. assert( pFrom->nSrc==1 );
  105730. pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName);
  105731. pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zDbSName);
  105732. assert( pFrom->a[0].pOn==0 );
  105733. assert( pFrom->a[0].pUsing==0 );
  105734. }
  105735. pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, pOrderBy,
  105736. SF_IncludeHidden, pLimit);
  105737. sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
  105738. sqlite3Select(pParse, pSel, &dest);
  105739. sqlite3SelectDelete(db, pSel);
  105740. }
  105741. #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
  105742. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  105743. /*
  105744. ** Generate an expression tree to implement the WHERE, ORDER BY,
  105745. ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
  105746. **
  105747. ** DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
  105748. ** \__________________________/
  105749. ** pLimitWhere (pInClause)
  105750. */
  105751. SQLITE_PRIVATE Expr *sqlite3LimitWhere(
  105752. Parse *pParse, /* The parser context */
  105753. SrcList *pSrc, /* the FROM clause -- which tables to scan */
  105754. Expr *pWhere, /* The WHERE clause. May be null */
  105755. ExprList *pOrderBy, /* The ORDER BY clause. May be null */
  105756. Expr *pLimit, /* The LIMIT clause. May be null */
  105757. char *zStmtType /* Either DELETE or UPDATE. For err msgs. */
  105758. ){
  105759. sqlite3 *db = pParse->db;
  105760. Expr *pLhs = NULL; /* LHS of IN(SELECT...) operator */
  105761. Expr *pInClause = NULL; /* WHERE rowid IN ( select ) */
  105762. ExprList *pEList = NULL; /* Expression list contaning only pSelectRowid */
  105763. SrcList *pSelectSrc = NULL; /* SELECT rowid FROM x ... (dup of pSrc) */
  105764. Select *pSelect = NULL; /* Complete SELECT tree */
  105765. Table *pTab;
  105766. /* Check that there isn't an ORDER BY without a LIMIT clause.
  105767. */
  105768. if( pOrderBy && pLimit==0 ) {
  105769. sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
  105770. sqlite3ExprDelete(pParse->db, pWhere);
  105771. sqlite3ExprListDelete(pParse->db, pOrderBy);
  105772. return 0;
  105773. }
  105774. /* We only need to generate a select expression if there
  105775. ** is a limit/offset term to enforce.
  105776. */
  105777. if( pLimit == 0 ) {
  105778. return pWhere;
  105779. }
  105780. /* Generate a select expression tree to enforce the limit/offset
  105781. ** term for the DELETE or UPDATE statement. For example:
  105782. ** DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
  105783. ** becomes:
  105784. ** DELETE FROM table_a WHERE rowid IN (
  105785. ** SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
  105786. ** );
  105787. */
  105788. pTab = pSrc->a[0].pTab;
  105789. if( HasRowid(pTab) ){
  105790. pLhs = sqlite3PExpr(pParse, TK_ROW, 0, 0);
  105791. pEList = sqlite3ExprListAppend(
  105792. pParse, 0, sqlite3PExpr(pParse, TK_ROW, 0, 0)
  105793. );
  105794. }else{
  105795. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  105796. if( pPk->nKeyCol==1 ){
  105797. const char *zName = pTab->aCol[pPk->aiColumn[0]].zName;
  105798. pLhs = sqlite3Expr(db, TK_ID, zName);
  105799. pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, zName));
  105800. }else{
  105801. int i;
  105802. for(i=0; i<pPk->nKeyCol; i++){
  105803. Expr *p = sqlite3Expr(db, TK_ID, pTab->aCol[pPk->aiColumn[i]].zName);
  105804. pEList = sqlite3ExprListAppend(pParse, pEList, p);
  105805. }
  105806. pLhs = sqlite3PExpr(pParse, TK_VECTOR, 0, 0);
  105807. if( pLhs ){
  105808. pLhs->x.pList = sqlite3ExprListDup(db, pEList, 0);
  105809. }
  105810. }
  105811. }
  105812. /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
  105813. ** and the SELECT subtree. */
  105814. pSrc->a[0].pTab = 0;
  105815. pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
  105816. pSrc->a[0].pTab = pTab;
  105817. pSrc->a[0].pIBIndex = 0;
  105818. /* generate the SELECT expression tree. */
  105819. pSelect = sqlite3SelectNew(pParse, pEList, pSelectSrc, pWhere, 0 ,0,
  105820. pOrderBy,0,pLimit
  105821. );
  105822. /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
  105823. pInClause = sqlite3PExpr(pParse, TK_IN, pLhs, 0);
  105824. sqlite3PExprAddSelect(pParse, pInClause, pSelect);
  105825. return pInClause;
  105826. }
  105827. #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) */
  105828. /* && !defined(SQLITE_OMIT_SUBQUERY) */
  105829. /*
  105830. ** Generate code for a DELETE FROM statement.
  105831. **
  105832. ** DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
  105833. ** \________/ \________________/
  105834. ** pTabList pWhere
  105835. */
  105836. SQLITE_PRIVATE void sqlite3DeleteFrom(
  105837. Parse *pParse, /* The parser context */
  105838. SrcList *pTabList, /* The table from which we should delete things */
  105839. Expr *pWhere, /* The WHERE clause. May be null */
  105840. ExprList *pOrderBy, /* ORDER BY clause. May be null */
  105841. Expr *pLimit /* LIMIT clause. May be null */
  105842. ){
  105843. Vdbe *v; /* The virtual database engine */
  105844. Table *pTab; /* The table from which records will be deleted */
  105845. int i; /* Loop counter */
  105846. WhereInfo *pWInfo; /* Information about the WHERE clause */
  105847. Index *pIdx; /* For looping over indices of the table */
  105848. int iTabCur; /* Cursor number for the table */
  105849. int iDataCur = 0; /* VDBE cursor for the canonical data source */
  105850. int iIdxCur = 0; /* Cursor number of the first index */
  105851. int nIdx; /* Number of indices */
  105852. sqlite3 *db; /* Main database structure */
  105853. AuthContext sContext; /* Authorization context */
  105854. NameContext sNC; /* Name context to resolve expressions in */
  105855. int iDb; /* Database number */
  105856. int memCnt = 0; /* Memory cell used for change counting */
  105857. int rcauth; /* Value returned by authorization callback */
  105858. int eOnePass; /* ONEPASS_OFF or _SINGLE or _MULTI */
  105859. int aiCurOnePass[2]; /* The write cursors opened by WHERE_ONEPASS */
  105860. u8 *aToOpen = 0; /* Open cursor iTabCur+j if aToOpen[j] is true */
  105861. Index *pPk; /* The PRIMARY KEY index on the table */
  105862. int iPk = 0; /* First of nPk registers holding PRIMARY KEY value */
  105863. i16 nPk = 1; /* Number of columns in the PRIMARY KEY */
  105864. int iKey; /* Memory cell holding key of row to be deleted */
  105865. i16 nKey; /* Number of memory cells in the row key */
  105866. int iEphCur = 0; /* Ephemeral table holding all primary key values */
  105867. int iRowSet = 0; /* Register for rowset of rows to delete */
  105868. int addrBypass = 0; /* Address of jump over the delete logic */
  105869. int addrLoop = 0; /* Top of the delete loop */
  105870. int addrEphOpen = 0; /* Instruction to open the Ephemeral table */
  105871. int bComplex; /* True if there are triggers or FKs or
  105872. ** subqueries in the WHERE clause */
  105873. #ifndef SQLITE_OMIT_TRIGGER
  105874. int isView; /* True if attempting to delete from a view */
  105875. Trigger *pTrigger; /* List of table triggers, if required */
  105876. #endif
  105877. memset(&sContext, 0, sizeof(sContext));
  105878. db = pParse->db;
  105879. if( pParse->nErr || db->mallocFailed ){
  105880. goto delete_from_cleanup;
  105881. }
  105882. assert( pTabList->nSrc==1 );
  105883. /* Locate the table which we want to delete. This table has to be
  105884. ** put in an SrcList structure because some of the subroutines we
  105885. ** will be calling are designed to work with multiple tables and expect
  105886. ** an SrcList* parameter instead of just a Table* parameter.
  105887. */
  105888. pTab = sqlite3SrcListLookup(pParse, pTabList);
  105889. if( pTab==0 ) goto delete_from_cleanup;
  105890. /* Figure out if we have any triggers and if the table being
  105891. ** deleted from is a view
  105892. */
  105893. #ifndef SQLITE_OMIT_TRIGGER
  105894. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  105895. isView = pTab->pSelect!=0;
  105896. #else
  105897. # define pTrigger 0
  105898. # define isView 0
  105899. #endif
  105900. bComplex = pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0);
  105901. #ifdef SQLITE_OMIT_VIEW
  105902. # undef isView
  105903. # define isView 0
  105904. #endif
  105905. #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
  105906. if( !isView ){
  105907. pWhere = sqlite3LimitWhere(
  105908. pParse, pTabList, pWhere, pOrderBy, pLimit, "DELETE"
  105909. );
  105910. pOrderBy = 0;
  105911. pLimit = 0;
  105912. }
  105913. #endif
  105914. /* If pTab is really a view, make sure it has been initialized.
  105915. */
  105916. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  105917. goto delete_from_cleanup;
  105918. }
  105919. if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
  105920. goto delete_from_cleanup;
  105921. }
  105922. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  105923. assert( iDb<db->nDb );
  105924. rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0,
  105925. db->aDb[iDb].zDbSName);
  105926. assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
  105927. if( rcauth==SQLITE_DENY ){
  105928. goto delete_from_cleanup;
  105929. }
  105930. assert(!isView || pTrigger);
  105931. /* Assign cursor numbers to the table and all its indices.
  105932. */
  105933. assert( pTabList->nSrc==1 );
  105934. iTabCur = pTabList->a[0].iCursor = pParse->nTab++;
  105935. for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
  105936. pParse->nTab++;
  105937. }
  105938. /* Start the view context
  105939. */
  105940. if( isView ){
  105941. sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
  105942. }
  105943. /* Begin generating code.
  105944. */
  105945. v = sqlite3GetVdbe(pParse);
  105946. if( v==0 ){
  105947. goto delete_from_cleanup;
  105948. }
  105949. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  105950. sqlite3BeginWriteOperation(pParse, bComplex, iDb);
  105951. /* If we are trying to delete from a view, realize that view into
  105952. ** an ephemeral table.
  105953. */
  105954. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  105955. if( isView ){
  105956. sqlite3MaterializeView(pParse, pTab,
  105957. pWhere, pOrderBy, pLimit, iTabCur
  105958. );
  105959. iDataCur = iIdxCur = iTabCur;
  105960. pOrderBy = 0;
  105961. pLimit = 0;
  105962. }
  105963. #endif
  105964. /* Resolve the column names in the WHERE clause.
  105965. */
  105966. memset(&sNC, 0, sizeof(sNC));
  105967. sNC.pParse = pParse;
  105968. sNC.pSrcList = pTabList;
  105969. if( sqlite3ResolveExprNames(&sNC, pWhere) ){
  105970. goto delete_from_cleanup;
  105971. }
  105972. /* Initialize the counter of the number of rows deleted, if
  105973. ** we are counting rows.
  105974. */
  105975. if( (db->flags & SQLITE_CountRows)!=0
  105976. && !pParse->nested
  105977. && !pParse->pTriggerTab
  105978. ){
  105979. memCnt = ++pParse->nMem;
  105980. sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
  105981. }
  105982. #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
  105983. /* Special case: A DELETE without a WHERE clause deletes everything.
  105984. ** It is easier just to erase the whole table. Prior to version 3.6.5,
  105985. ** this optimization caused the row change count (the value returned by
  105986. ** API function sqlite3_count_changes) to be set incorrectly.
  105987. **
  105988. ** The "rcauth==SQLITE_OK" terms is the
  105989. ** IMPLEMENTATION-OF: R-17228-37124 If the action code is SQLITE_DELETE and
  105990. ** the callback returns SQLITE_IGNORE then the DELETE operation proceeds but
  105991. ** the truncate optimization is disabled and all rows are deleted
  105992. ** individually.
  105993. */
  105994. if( rcauth==SQLITE_OK
  105995. && pWhere==0
  105996. && !bComplex
  105997. && !IsVirtual(pTab)
  105998. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  105999. && db->xPreUpdateCallback==0
  106000. #endif
  106001. ){
  106002. assert( !isView );
  106003. sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
  106004. if( HasRowid(pTab) ){
  106005. sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt ? memCnt : -1,
  106006. pTab->zName, P4_STATIC);
  106007. }
  106008. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  106009. assert( pIdx->pSchema==pTab->pSchema );
  106010. sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
  106011. }
  106012. }else
  106013. #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
  106014. {
  106015. u16 wcf = WHERE_ONEPASS_DESIRED|WHERE_DUPLICATES_OK|WHERE_SEEK_TABLE;
  106016. if( sNC.ncFlags & NC_VarSelect ) bComplex = 1;
  106017. wcf |= (bComplex ? 0 : WHERE_ONEPASS_MULTIROW);
  106018. if( HasRowid(pTab) ){
  106019. /* For a rowid table, initialize the RowSet to an empty set */
  106020. pPk = 0;
  106021. nPk = 1;
  106022. iRowSet = ++pParse->nMem;
  106023. sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
  106024. }else{
  106025. /* For a WITHOUT ROWID table, create an ephemeral table used to
  106026. ** hold all primary keys for rows to be deleted. */
  106027. pPk = sqlite3PrimaryKeyIndex(pTab);
  106028. assert( pPk!=0 );
  106029. nPk = pPk->nKeyCol;
  106030. iPk = pParse->nMem+1;
  106031. pParse->nMem += nPk;
  106032. iEphCur = pParse->nTab++;
  106033. addrEphOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEphCur, nPk);
  106034. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  106035. }
  106036. /* Construct a query to find the rowid or primary key for every row
  106037. ** to be deleted, based on the WHERE clause. Set variable eOnePass
  106038. ** to indicate the strategy used to implement this delete:
  106039. **
  106040. ** ONEPASS_OFF: Two-pass approach - use a FIFO for rowids/PK values.
  106041. ** ONEPASS_SINGLE: One-pass approach - at most one row deleted.
  106042. ** ONEPASS_MULTI: One-pass approach - any number of rows may be deleted.
  106043. */
  106044. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, wcf, iTabCur+1);
  106045. if( pWInfo==0 ) goto delete_from_cleanup;
  106046. eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
  106047. assert( IsVirtual(pTab)==0 || eOnePass!=ONEPASS_MULTI );
  106048. assert( IsVirtual(pTab) || bComplex || eOnePass!=ONEPASS_OFF );
  106049. if( eOnePass!=ONEPASS_SINGLE ) sqlite3MultiWrite(pParse);
  106050. /* Keep track of the number of rows to be deleted */
  106051. if( memCnt ){
  106052. sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
  106053. }
  106054. /* Extract the rowid or primary key for the current row */
  106055. if( pPk ){
  106056. for(i=0; i<nPk; i++){
  106057. assert( pPk->aiColumn[i]>=0 );
  106058. sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
  106059. pPk->aiColumn[i], iPk+i);
  106060. }
  106061. iKey = iPk;
  106062. }else{
  106063. iKey = ++pParse->nMem;
  106064. sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur, -1, iKey);
  106065. }
  106066. if( eOnePass!=ONEPASS_OFF ){
  106067. /* For ONEPASS, no need to store the rowid/primary-key. There is only
  106068. ** one, so just keep it in its register(s) and fall through to the
  106069. ** delete code. */
  106070. nKey = nPk; /* OP_Found will use an unpacked key */
  106071. aToOpen = sqlite3DbMallocRawNN(db, nIdx+2);
  106072. if( aToOpen==0 ){
  106073. sqlite3WhereEnd(pWInfo);
  106074. goto delete_from_cleanup;
  106075. }
  106076. memset(aToOpen, 1, nIdx+1);
  106077. aToOpen[nIdx+1] = 0;
  106078. if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iTabCur] = 0;
  106079. if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iTabCur] = 0;
  106080. if( addrEphOpen ) sqlite3VdbeChangeToNoop(v, addrEphOpen);
  106081. }else{
  106082. if( pPk ){
  106083. /* Add the PK key for this row to the temporary table */
  106084. iKey = ++pParse->nMem;
  106085. nKey = 0; /* Zero tells OP_Found to use a composite key */
  106086. sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, iKey,
  106087. sqlite3IndexAffinityStr(pParse->db, pPk), nPk);
  106088. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iEphCur, iKey, iPk, nPk);
  106089. }else{
  106090. /* Add the rowid of the row to be deleted to the RowSet */
  106091. nKey = 1; /* OP_DeferredSeek always uses a single rowid */
  106092. sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, iKey);
  106093. }
  106094. }
  106095. /* If this DELETE cannot use the ONEPASS strategy, this is the
  106096. ** end of the WHERE loop */
  106097. if( eOnePass!=ONEPASS_OFF ){
  106098. addrBypass = sqlite3VdbeMakeLabel(pParse);
  106099. }else{
  106100. sqlite3WhereEnd(pWInfo);
  106101. }
  106102. /* Unless this is a view, open cursors for the table we are
  106103. ** deleting from and all its indices. If this is a view, then the
  106104. ** only effect this statement has is to fire the INSTEAD OF
  106105. ** triggers.
  106106. */
  106107. if( !isView ){
  106108. int iAddrOnce = 0;
  106109. if( eOnePass==ONEPASS_MULTI ){
  106110. iAddrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  106111. }
  106112. testcase( IsVirtual(pTab) );
  106113. sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, OPFLAG_FORDELETE,
  106114. iTabCur, aToOpen, &iDataCur, &iIdxCur);
  106115. assert( pPk || IsVirtual(pTab) || iDataCur==iTabCur );
  106116. assert( pPk || IsVirtual(pTab) || iIdxCur==iDataCur+1 );
  106117. if( eOnePass==ONEPASS_MULTI ) sqlite3VdbeJumpHere(v, iAddrOnce);
  106118. }
  106119. /* Set up a loop over the rowids/primary-keys that were found in the
  106120. ** where-clause loop above.
  106121. */
  106122. if( eOnePass!=ONEPASS_OFF ){
  106123. assert( nKey==nPk ); /* OP_Found will use an unpacked key */
  106124. if( !IsVirtual(pTab) && aToOpen[iDataCur-iTabCur] ){
  106125. assert( pPk!=0 || pTab->pSelect!=0 );
  106126. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, addrBypass, iKey, nKey);
  106127. VdbeCoverage(v);
  106128. }
  106129. }else if( pPk ){
  106130. addrLoop = sqlite3VdbeAddOp1(v, OP_Rewind, iEphCur); VdbeCoverage(v);
  106131. if( IsVirtual(pTab) ){
  106132. sqlite3VdbeAddOp3(v, OP_Column, iEphCur, 0, iKey);
  106133. }else{
  106134. sqlite3VdbeAddOp2(v, OP_RowData, iEphCur, iKey);
  106135. }
  106136. assert( nKey==0 ); /* OP_Found will use a composite key */
  106137. }else{
  106138. addrLoop = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, 0, iKey);
  106139. VdbeCoverage(v);
  106140. assert( nKey==1 );
  106141. }
  106142. /* Delete the row */
  106143. #ifndef SQLITE_OMIT_VIRTUALTABLE
  106144. if( IsVirtual(pTab) ){
  106145. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  106146. sqlite3VtabMakeWritable(pParse, pTab);
  106147. assert( eOnePass==ONEPASS_OFF || eOnePass==ONEPASS_SINGLE );
  106148. sqlite3MayAbort(pParse);
  106149. if( eOnePass==ONEPASS_SINGLE ){
  106150. sqlite3VdbeAddOp1(v, OP_Close, iTabCur);
  106151. if( sqlite3IsToplevel(pParse) ){
  106152. pParse->isMultiWrite = 0;
  106153. }
  106154. }
  106155. sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iKey, pVTab, P4_VTAB);
  106156. sqlite3VdbeChangeP5(v, OE_Abort);
  106157. }else
  106158. #endif
  106159. {
  106160. int count = (pParse->nested==0); /* True to count changes */
  106161. sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
  106162. iKey, nKey, count, OE_Default, eOnePass, aiCurOnePass[1]);
  106163. }
  106164. /* End of the loop over all rowids/primary-keys. */
  106165. if( eOnePass!=ONEPASS_OFF ){
  106166. sqlite3VdbeResolveLabel(v, addrBypass);
  106167. sqlite3WhereEnd(pWInfo);
  106168. }else if( pPk ){
  106169. sqlite3VdbeAddOp2(v, OP_Next, iEphCur, addrLoop+1); VdbeCoverage(v);
  106170. sqlite3VdbeJumpHere(v, addrLoop);
  106171. }else{
  106172. sqlite3VdbeGoto(v, addrLoop);
  106173. sqlite3VdbeJumpHere(v, addrLoop);
  106174. }
  106175. } /* End non-truncate path */
  106176. /* Update the sqlite_sequence table by storing the content of the
  106177. ** maximum rowid counter values recorded while inserting into
  106178. ** autoincrement tables.
  106179. */
  106180. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  106181. sqlite3AutoincrementEnd(pParse);
  106182. }
  106183. /* Return the number of rows that were deleted. If this routine is
  106184. ** generating code because of a call to sqlite3NestedParse(), do not
  106185. ** invoke the callback function.
  106186. */
  106187. if( memCnt ){
  106188. sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
  106189. sqlite3VdbeSetNumCols(v, 1);
  106190. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
  106191. }
  106192. delete_from_cleanup:
  106193. sqlite3AuthContextPop(&sContext);
  106194. sqlite3SrcListDelete(db, pTabList);
  106195. sqlite3ExprDelete(db, pWhere);
  106196. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)
  106197. sqlite3ExprListDelete(db, pOrderBy);
  106198. sqlite3ExprDelete(db, pLimit);
  106199. #endif
  106200. sqlite3DbFree(db, aToOpen);
  106201. return;
  106202. }
  106203. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  106204. ** they may interfere with compilation of other functions in this file
  106205. ** (or in another file, if this file becomes part of the amalgamation). */
  106206. #ifdef isView
  106207. #undef isView
  106208. #endif
  106209. #ifdef pTrigger
  106210. #undef pTrigger
  106211. #endif
  106212. /*
  106213. ** This routine generates VDBE code that causes a single row of a
  106214. ** single table to be deleted. Both the original table entry and
  106215. ** all indices are removed.
  106216. **
  106217. ** Preconditions:
  106218. **
  106219. ** 1. iDataCur is an open cursor on the btree that is the canonical data
  106220. ** store for the table. (This will be either the table itself,
  106221. ** in the case of a rowid table, or the PRIMARY KEY index in the case
  106222. ** of a WITHOUT ROWID table.)
  106223. **
  106224. ** 2. Read/write cursors for all indices of pTab must be open as
  106225. ** cursor number iIdxCur+i for the i-th index.
  106226. **
  106227. ** 3. The primary key for the row to be deleted must be stored in a
  106228. ** sequence of nPk memory cells starting at iPk. If nPk==0 that means
  106229. ** that a search record formed from OP_MakeRecord is contained in the
  106230. ** single memory location iPk.
  106231. **
  106232. ** eMode:
  106233. ** Parameter eMode may be passed either ONEPASS_OFF (0), ONEPASS_SINGLE, or
  106234. ** ONEPASS_MULTI. If eMode is not ONEPASS_OFF, then the cursor
  106235. ** iDataCur already points to the row to delete. If eMode is ONEPASS_OFF
  106236. ** then this function must seek iDataCur to the entry identified by iPk
  106237. ** and nPk before reading from it.
  106238. **
  106239. ** If eMode is ONEPASS_MULTI, then this call is being made as part
  106240. ** of a ONEPASS delete that affects multiple rows. In this case, if
  106241. ** iIdxNoSeek is a valid cursor number (>=0) and is not the same as
  106242. ** iDataCur, then its position should be preserved following the delete
  106243. ** operation. Or, if iIdxNoSeek is not a valid cursor number, the
  106244. ** position of iDataCur should be preserved instead.
  106245. **
  106246. ** iIdxNoSeek:
  106247. ** If iIdxNoSeek is a valid cursor number (>=0) not equal to iDataCur,
  106248. ** then it identifies an index cursor (from within array of cursors
  106249. ** starting at iIdxCur) that already points to the index entry to be deleted.
  106250. ** Except, this optimization is disabled if there are BEFORE triggers since
  106251. ** the trigger body might have moved the cursor.
  106252. */
  106253. SQLITE_PRIVATE void sqlite3GenerateRowDelete(
  106254. Parse *pParse, /* Parsing context */
  106255. Table *pTab, /* Table containing the row to be deleted */
  106256. Trigger *pTrigger, /* List of triggers to (potentially) fire */
  106257. int iDataCur, /* Cursor from which column data is extracted */
  106258. int iIdxCur, /* First index cursor */
  106259. int iPk, /* First memory cell containing the PRIMARY KEY */
  106260. i16 nPk, /* Number of PRIMARY KEY memory cells */
  106261. u8 count, /* If non-zero, increment the row change counter */
  106262. u8 onconf, /* Default ON CONFLICT policy for triggers */
  106263. u8 eMode, /* ONEPASS_OFF, _SINGLE, or _MULTI. See above */
  106264. int iIdxNoSeek /* Cursor number of cursor that does not need seeking */
  106265. ){
  106266. Vdbe *v = pParse->pVdbe; /* Vdbe */
  106267. int iOld = 0; /* First register in OLD.* array */
  106268. int iLabel; /* Label resolved to end of generated code */
  106269. u8 opSeek; /* Seek opcode */
  106270. /* Vdbe is guaranteed to have been allocated by this stage. */
  106271. assert( v );
  106272. VdbeModuleComment((v, "BEGIN: GenRowDel(%d,%d,%d,%d)",
  106273. iDataCur, iIdxCur, iPk, (int)nPk));
  106274. /* Seek cursor iCur to the row to delete. If this row no longer exists
  106275. ** (this can happen if a trigger program has already deleted it), do
  106276. ** not attempt to delete it or fire any DELETE triggers. */
  106277. iLabel = sqlite3VdbeMakeLabel(pParse);
  106278. opSeek = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
  106279. if( eMode==ONEPASS_OFF ){
  106280. sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
  106281. VdbeCoverageIf(v, opSeek==OP_NotExists);
  106282. VdbeCoverageIf(v, opSeek==OP_NotFound);
  106283. }
  106284. /* If there are any triggers to fire, allocate a range of registers to
  106285. ** use for the old.* references in the triggers. */
  106286. if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
  106287. u32 mask; /* Mask of OLD.* columns in use */
  106288. int iCol; /* Iterator used while populating OLD.* */
  106289. int addrStart; /* Start of BEFORE trigger programs */
  106290. /* TODO: Could use temporary registers here. Also could attempt to
  106291. ** avoid copying the contents of the rowid register. */
  106292. mask = sqlite3TriggerColmask(
  106293. pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
  106294. );
  106295. mask |= sqlite3FkOldmask(pParse, pTab);
  106296. iOld = pParse->nMem+1;
  106297. pParse->nMem += (1 + pTab->nCol);
  106298. /* Populate the OLD.* pseudo-table register array. These values will be
  106299. ** used by any BEFORE and AFTER triggers that exist. */
  106300. sqlite3VdbeAddOp2(v, OP_Copy, iPk, iOld);
  106301. for(iCol=0; iCol<pTab->nCol; iCol++){
  106302. testcase( mask!=0xffffffff && iCol==31 );
  106303. testcase( mask!=0xffffffff && iCol==32 );
  106304. if( mask==0xffffffff || (iCol<=31 && (mask & MASKBIT32(iCol))!=0) ){
  106305. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, iCol, iOld+iCol+1);
  106306. }
  106307. }
  106308. /* Invoke BEFORE DELETE trigger programs. */
  106309. addrStart = sqlite3VdbeCurrentAddr(v);
  106310. sqlite3CodeRowTrigger(pParse, pTrigger,
  106311. TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
  106312. );
  106313. /* If any BEFORE triggers were coded, then seek the cursor to the
  106314. ** row to be deleted again. It may be that the BEFORE triggers moved
  106315. ** the cursor or already deleted the row that the cursor was
  106316. ** pointing to.
  106317. **
  106318. ** Also disable the iIdxNoSeek optimization since the BEFORE trigger
  106319. ** may have moved that cursor.
  106320. */
  106321. if( addrStart<sqlite3VdbeCurrentAddr(v) ){
  106322. sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
  106323. VdbeCoverageIf(v, opSeek==OP_NotExists);
  106324. VdbeCoverageIf(v, opSeek==OP_NotFound);
  106325. testcase( iIdxNoSeek>=0 );
  106326. iIdxNoSeek = -1;
  106327. }
  106328. /* Do FK processing. This call checks that any FK constraints that
  106329. ** refer to this table (i.e. constraints attached to other tables)
  106330. ** are not violated by deleting this row. */
  106331. sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0);
  106332. }
  106333. /* Delete the index and table entries. Skip this step if pTab is really
  106334. ** a view (in which case the only effect of the DELETE statement is to
  106335. ** fire the INSTEAD OF triggers).
  106336. **
  106337. ** If variable 'count' is non-zero, then this OP_Delete instruction should
  106338. ** invoke the update-hook. The pre-update-hook, on the other hand should
  106339. ** be invoked unless table pTab is a system table. The difference is that
  106340. ** the update-hook is not invoked for rows removed by REPLACE, but the
  106341. ** pre-update-hook is.
  106342. */
  106343. if( pTab->pSelect==0 ){
  106344. u8 p5 = 0;
  106345. sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,iIdxNoSeek);
  106346. sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, (count?OPFLAG_NCHANGE:0));
  106347. if( pParse->nested==0 || 0==sqlite3_stricmp(pTab->zName, "sqlite_stat1") ){
  106348. sqlite3VdbeAppendP4(v, (char*)pTab, P4_TABLE);
  106349. }
  106350. if( eMode!=ONEPASS_OFF ){
  106351. sqlite3VdbeChangeP5(v, OPFLAG_AUXDELETE);
  106352. }
  106353. if( iIdxNoSeek>=0 && iIdxNoSeek!=iDataCur ){
  106354. sqlite3VdbeAddOp1(v, OP_Delete, iIdxNoSeek);
  106355. }
  106356. if( eMode==ONEPASS_MULTI ) p5 |= OPFLAG_SAVEPOSITION;
  106357. sqlite3VdbeChangeP5(v, p5);
  106358. }
  106359. /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
  106360. ** handle rows (possibly in other tables) that refer via a foreign key
  106361. ** to the row just deleted. */
  106362. sqlite3FkActions(pParse, pTab, 0, iOld, 0, 0);
  106363. /* Invoke AFTER DELETE trigger programs. */
  106364. sqlite3CodeRowTrigger(pParse, pTrigger,
  106365. TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
  106366. );
  106367. /* Jump here if the row had already been deleted before any BEFORE
  106368. ** trigger programs were invoked. Or if a trigger program throws a
  106369. ** RAISE(IGNORE) exception. */
  106370. sqlite3VdbeResolveLabel(v, iLabel);
  106371. VdbeModuleComment((v, "END: GenRowDel()"));
  106372. }
  106373. /*
  106374. ** This routine generates VDBE code that causes the deletion of all
  106375. ** index entries associated with a single row of a single table, pTab
  106376. **
  106377. ** Preconditions:
  106378. **
  106379. ** 1. A read/write cursor "iDataCur" must be open on the canonical storage
  106380. ** btree for the table pTab. (This will be either the table itself
  106381. ** for rowid tables or to the primary key index for WITHOUT ROWID
  106382. ** tables.)
  106383. **
  106384. ** 2. Read/write cursors for all indices of pTab must be open as
  106385. ** cursor number iIdxCur+i for the i-th index. (The pTab->pIndex
  106386. ** index is the 0-th index.)
  106387. **
  106388. ** 3. The "iDataCur" cursor must be already be positioned on the row
  106389. ** that is to be deleted.
  106390. */
  106391. SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
  106392. Parse *pParse, /* Parsing and code generating context */
  106393. Table *pTab, /* Table containing the row to be deleted */
  106394. int iDataCur, /* Cursor of table holding data. */
  106395. int iIdxCur, /* First index cursor */
  106396. int *aRegIdx, /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
  106397. int iIdxNoSeek /* Do not delete from this cursor */
  106398. ){
  106399. int i; /* Index loop counter */
  106400. int r1 = -1; /* Register holding an index key */
  106401. int iPartIdxLabel; /* Jump destination for skipping partial index entries */
  106402. Index *pIdx; /* Current index */
  106403. Index *pPrior = 0; /* Prior index */
  106404. Vdbe *v; /* The prepared statement under construction */
  106405. Index *pPk; /* PRIMARY KEY index, or NULL for rowid tables */
  106406. v = pParse->pVdbe;
  106407. pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
  106408. for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
  106409. assert( iIdxCur+i!=iDataCur || pPk==pIdx );
  106410. if( aRegIdx!=0 && aRegIdx[i]==0 ) continue;
  106411. if( pIdx==pPk ) continue;
  106412. if( iIdxCur+i==iIdxNoSeek ) continue;
  106413. VdbeModuleComment((v, "GenRowIdxDel for %s", pIdx->zName));
  106414. r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 1,
  106415. &iPartIdxLabel, pPrior, r1);
  106416. sqlite3VdbeAddOp3(v, OP_IdxDelete, iIdxCur+i, r1,
  106417. pIdx->uniqNotNull ? pIdx->nKeyCol : pIdx->nColumn);
  106418. sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
  106419. pPrior = pIdx;
  106420. }
  106421. }
  106422. /*
  106423. ** Generate code that will assemble an index key and stores it in register
  106424. ** regOut. The key with be for index pIdx which is an index on pTab.
  106425. ** iCur is the index of a cursor open on the pTab table and pointing to
  106426. ** the entry that needs indexing. If pTab is a WITHOUT ROWID table, then
  106427. ** iCur must be the cursor of the PRIMARY KEY index.
  106428. **
  106429. ** Return a register number which is the first in a block of
  106430. ** registers that holds the elements of the index key. The
  106431. ** block of registers has already been deallocated by the time
  106432. ** this routine returns.
  106433. **
  106434. ** If *piPartIdxLabel is not NULL, fill it in with a label and jump
  106435. ** to that label if pIdx is a partial index that should be skipped.
  106436. ** The label should be resolved using sqlite3ResolvePartIdxLabel().
  106437. ** A partial index should be skipped if its WHERE clause evaluates
  106438. ** to false or null. If pIdx is not a partial index, *piPartIdxLabel
  106439. ** will be set to zero which is an empty label that is ignored by
  106440. ** sqlite3ResolvePartIdxLabel().
  106441. **
  106442. ** The pPrior and regPrior parameters are used to implement a cache to
  106443. ** avoid unnecessary register loads. If pPrior is not NULL, then it is
  106444. ** a pointer to a different index for which an index key has just been
  106445. ** computed into register regPrior. If the current pIdx index is generating
  106446. ** its key into the same sequence of registers and if pPrior and pIdx share
  106447. ** a column in common, then the register corresponding to that column already
  106448. ** holds the correct value and the loading of that register is skipped.
  106449. ** This optimization is helpful when doing a DELETE or an INTEGRITY_CHECK
  106450. ** on a table with multiple indices, and especially with the ROWID or
  106451. ** PRIMARY KEY columns of the index.
  106452. */
  106453. SQLITE_PRIVATE int sqlite3GenerateIndexKey(
  106454. Parse *pParse, /* Parsing context */
  106455. Index *pIdx, /* The index for which to generate a key */
  106456. int iDataCur, /* Cursor number from which to take column data */
  106457. int regOut, /* Put the new key into this register if not 0 */
  106458. int prefixOnly, /* Compute only a unique prefix of the key */
  106459. int *piPartIdxLabel, /* OUT: Jump to this label to skip partial index */
  106460. Index *pPrior, /* Previously generated index key */
  106461. int regPrior /* Register holding previous generated key */
  106462. ){
  106463. Vdbe *v = pParse->pVdbe;
  106464. int j;
  106465. int regBase;
  106466. int nCol;
  106467. if( piPartIdxLabel ){
  106468. if( pIdx->pPartIdxWhere ){
  106469. *piPartIdxLabel = sqlite3VdbeMakeLabel(pParse);
  106470. pParse->iSelfTab = iDataCur + 1;
  106471. sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel,
  106472. SQLITE_JUMPIFNULL);
  106473. pParse->iSelfTab = 0;
  106474. }else{
  106475. *piPartIdxLabel = 0;
  106476. }
  106477. }
  106478. nCol = (prefixOnly && pIdx->uniqNotNull) ? pIdx->nKeyCol : pIdx->nColumn;
  106479. regBase = sqlite3GetTempRange(pParse, nCol);
  106480. if( pPrior && (regBase!=regPrior || pPrior->pPartIdxWhere) ) pPrior = 0;
  106481. for(j=0; j<nCol; j++){
  106482. if( pPrior
  106483. && pPrior->aiColumn[j]==pIdx->aiColumn[j]
  106484. && pPrior->aiColumn[j]!=XN_EXPR
  106485. ){
  106486. /* This column was already computed by the previous index */
  106487. continue;
  106488. }
  106489. sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iDataCur, j, regBase+j);
  106490. /* If the column affinity is REAL but the number is an integer, then it
  106491. ** might be stored in the table as an integer (using a compact
  106492. ** representation) then converted to REAL by an OP_RealAffinity opcode.
  106493. ** But we are getting ready to store this value back into an index, where
  106494. ** it should be converted by to INTEGER again. So omit the OP_RealAffinity
  106495. ** opcode if it is present */
  106496. sqlite3VdbeDeletePriorOpcode(v, OP_RealAffinity);
  106497. }
  106498. if( regOut ){
  106499. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regOut);
  106500. if( pIdx->pTable->pSelect ){
  106501. const char *zAff = sqlite3IndexAffinityStr(pParse->db, pIdx);
  106502. sqlite3VdbeChangeP4(v, -1, zAff, P4_TRANSIENT);
  106503. }
  106504. }
  106505. sqlite3ReleaseTempRange(pParse, regBase, nCol);
  106506. return regBase;
  106507. }
  106508. /*
  106509. ** If a prior call to sqlite3GenerateIndexKey() generated a jump-over label
  106510. ** because it was a partial index, then this routine should be called to
  106511. ** resolve that label.
  106512. */
  106513. SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse *pParse, int iLabel){
  106514. if( iLabel ){
  106515. sqlite3VdbeResolveLabel(pParse->pVdbe, iLabel);
  106516. }
  106517. }
  106518. /************** End of delete.c **********************************************/
  106519. /************** Begin file func.c ********************************************/
  106520. /*
  106521. ** 2002 February 23
  106522. **
  106523. ** The author disclaims copyright to this source code. In place of
  106524. ** a legal notice, here is a blessing:
  106525. **
  106526. ** May you do good and not evil.
  106527. ** May you find forgiveness for yourself and forgive others.
  106528. ** May you share freely, never taking more than you give.
  106529. **
  106530. *************************************************************************
  106531. ** This file contains the C-language implementations for many of the SQL
  106532. ** functions of SQLite. (Some function, and in particular the date and
  106533. ** time functions, are implemented separately.)
  106534. */
  106535. /* #include "sqliteInt.h" */
  106536. /* #include <stdlib.h> */
  106537. /* #include <assert.h> */
  106538. /* #include <math.h> */
  106539. /* #include "vdbeInt.h" */
  106540. /*
  106541. ** Return the collating function associated with a function.
  106542. */
  106543. static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
  106544. VdbeOp *pOp;
  106545. assert( context->pVdbe!=0 );
  106546. pOp = &context->pVdbe->aOp[context->iOp-1];
  106547. assert( pOp->opcode==OP_CollSeq );
  106548. assert( pOp->p4type==P4_COLLSEQ );
  106549. return pOp->p4.pColl;
  106550. }
  106551. /*
  106552. ** Indicate that the accumulator load should be skipped on this
  106553. ** iteration of the aggregate loop.
  106554. */
  106555. static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
  106556. assert( context->isError<=0 );
  106557. context->isError = -1;
  106558. context->skipFlag = 1;
  106559. }
  106560. /*
  106561. ** Implementation of the non-aggregate min() and max() functions
  106562. */
  106563. static void minmaxFunc(
  106564. sqlite3_context *context,
  106565. int argc,
  106566. sqlite3_value **argv
  106567. ){
  106568. int i;
  106569. int mask; /* 0 for min() or 0xffffffff for max() */
  106570. int iBest;
  106571. CollSeq *pColl;
  106572. assert( argc>1 );
  106573. mask = sqlite3_user_data(context)==0 ? 0 : -1;
  106574. pColl = sqlite3GetFuncCollSeq(context);
  106575. assert( pColl );
  106576. assert( mask==-1 || mask==0 );
  106577. iBest = 0;
  106578. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  106579. for(i=1; i<argc; i++){
  106580. if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
  106581. if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
  106582. testcase( mask==0 );
  106583. iBest = i;
  106584. }
  106585. }
  106586. sqlite3_result_value(context, argv[iBest]);
  106587. }
  106588. /*
  106589. ** Return the type of the argument.
  106590. */
  106591. static void typeofFunc(
  106592. sqlite3_context *context,
  106593. int NotUsed,
  106594. sqlite3_value **argv
  106595. ){
  106596. static const char *azType[] = { "integer", "real", "text", "blob", "null" };
  106597. int i = sqlite3_value_type(argv[0]) - 1;
  106598. UNUSED_PARAMETER(NotUsed);
  106599. assert( i>=0 && i<ArraySize(azType) );
  106600. assert( SQLITE_INTEGER==1 );
  106601. assert( SQLITE_FLOAT==2 );
  106602. assert( SQLITE_TEXT==3 );
  106603. assert( SQLITE_BLOB==4 );
  106604. assert( SQLITE_NULL==5 );
  106605. /* EVIDENCE-OF: R-01470-60482 The sqlite3_value_type(V) interface returns
  106606. ** the datatype code for the initial datatype of the sqlite3_value object
  106607. ** V. The returned value is one of SQLITE_INTEGER, SQLITE_FLOAT,
  106608. ** SQLITE_TEXT, SQLITE_BLOB, or SQLITE_NULL. */
  106609. sqlite3_result_text(context, azType[i], -1, SQLITE_STATIC);
  106610. }
  106611. /*
  106612. ** Implementation of the length() function
  106613. */
  106614. static void lengthFunc(
  106615. sqlite3_context *context,
  106616. int argc,
  106617. sqlite3_value **argv
  106618. ){
  106619. assert( argc==1 );
  106620. UNUSED_PARAMETER(argc);
  106621. switch( sqlite3_value_type(argv[0]) ){
  106622. case SQLITE_BLOB:
  106623. case SQLITE_INTEGER:
  106624. case SQLITE_FLOAT: {
  106625. sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
  106626. break;
  106627. }
  106628. case SQLITE_TEXT: {
  106629. const unsigned char *z = sqlite3_value_text(argv[0]);
  106630. const unsigned char *z0;
  106631. unsigned char c;
  106632. if( z==0 ) return;
  106633. z0 = z;
  106634. while( (c = *z)!=0 ){
  106635. z++;
  106636. if( c>=0xc0 ){
  106637. while( (*z & 0xc0)==0x80 ){ z++; z0++; }
  106638. }
  106639. }
  106640. sqlite3_result_int(context, (int)(z-z0));
  106641. break;
  106642. }
  106643. default: {
  106644. sqlite3_result_null(context);
  106645. break;
  106646. }
  106647. }
  106648. }
  106649. /*
  106650. ** Implementation of the abs() function.
  106651. **
  106652. ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
  106653. ** the numeric argument X.
  106654. */
  106655. static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  106656. assert( argc==1 );
  106657. UNUSED_PARAMETER(argc);
  106658. switch( sqlite3_value_type(argv[0]) ){
  106659. case SQLITE_INTEGER: {
  106660. i64 iVal = sqlite3_value_int64(argv[0]);
  106661. if( iVal<0 ){
  106662. if( iVal==SMALLEST_INT64 ){
  106663. /* IMP: R-31676-45509 If X is the integer -9223372036854775808
  106664. ** then abs(X) throws an integer overflow error since there is no
  106665. ** equivalent positive 64-bit two complement value. */
  106666. sqlite3_result_error(context, "integer overflow", -1);
  106667. return;
  106668. }
  106669. iVal = -iVal;
  106670. }
  106671. sqlite3_result_int64(context, iVal);
  106672. break;
  106673. }
  106674. case SQLITE_NULL: {
  106675. /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
  106676. sqlite3_result_null(context);
  106677. break;
  106678. }
  106679. default: {
  106680. /* Because sqlite3_value_double() returns 0.0 if the argument is not
  106681. ** something that can be converted into a number, we have:
  106682. ** IMP: R-01992-00519 Abs(X) returns 0.0 if X is a string or blob
  106683. ** that cannot be converted to a numeric value.
  106684. */
  106685. double rVal = sqlite3_value_double(argv[0]);
  106686. if( rVal<0 ) rVal = -rVal;
  106687. sqlite3_result_double(context, rVal);
  106688. break;
  106689. }
  106690. }
  106691. }
  106692. /*
  106693. ** Implementation of the instr() function.
  106694. **
  106695. ** instr(haystack,needle) finds the first occurrence of needle
  106696. ** in haystack and returns the number of previous characters plus 1,
  106697. ** or 0 if needle does not occur within haystack.
  106698. **
  106699. ** If both haystack and needle are BLOBs, then the result is one more than
  106700. ** the number of bytes in haystack prior to the first occurrence of needle,
  106701. ** or 0 if needle never occurs in haystack.
  106702. */
  106703. static void instrFunc(
  106704. sqlite3_context *context,
  106705. int argc,
  106706. sqlite3_value **argv
  106707. ){
  106708. const unsigned char *zHaystack;
  106709. const unsigned char *zNeedle;
  106710. int nHaystack;
  106711. int nNeedle;
  106712. int typeHaystack, typeNeedle;
  106713. int N = 1;
  106714. int isText;
  106715. unsigned char firstChar;
  106716. UNUSED_PARAMETER(argc);
  106717. typeHaystack = sqlite3_value_type(argv[0]);
  106718. typeNeedle = sqlite3_value_type(argv[1]);
  106719. if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;
  106720. nHaystack = sqlite3_value_bytes(argv[0]);
  106721. nNeedle = sqlite3_value_bytes(argv[1]);
  106722. if( nNeedle>0 ){
  106723. if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){
  106724. zHaystack = sqlite3_value_blob(argv[0]);
  106725. zNeedle = sqlite3_value_blob(argv[1]);
  106726. isText = 0;
  106727. }else{
  106728. zHaystack = sqlite3_value_text(argv[0]);
  106729. zNeedle = sqlite3_value_text(argv[1]);
  106730. isText = 1;
  106731. }
  106732. if( zNeedle==0 || (nHaystack && zHaystack==0) ) return;
  106733. firstChar = zNeedle[0];
  106734. while( nNeedle<=nHaystack
  106735. && (zHaystack[0]!=firstChar || memcmp(zHaystack, zNeedle, nNeedle)!=0)
  106736. ){
  106737. N++;
  106738. do{
  106739. nHaystack--;
  106740. zHaystack++;
  106741. }while( isText && (zHaystack[0]&0xc0)==0x80 );
  106742. }
  106743. if( nNeedle>nHaystack ) N = 0;
  106744. }
  106745. sqlite3_result_int(context, N);
  106746. }
  106747. /*
  106748. ** Implementation of the printf() function.
  106749. */
  106750. static void printfFunc(
  106751. sqlite3_context *context,
  106752. int argc,
  106753. sqlite3_value **argv
  106754. ){
  106755. PrintfArguments x;
  106756. StrAccum str;
  106757. const char *zFormat;
  106758. int n;
  106759. sqlite3 *db = sqlite3_context_db_handle(context);
  106760. if( argc>=1 && (zFormat = (const char*)sqlite3_value_text(argv[0]))!=0 ){
  106761. x.nArg = argc-1;
  106762. x.nUsed = 0;
  106763. x.apArg = argv+1;
  106764. sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
  106765. str.printfFlags = SQLITE_PRINTF_SQLFUNC;
  106766. sqlite3_str_appendf(&str, zFormat, &x);
  106767. n = str.nChar;
  106768. sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n,
  106769. SQLITE_DYNAMIC);
  106770. }
  106771. }
  106772. /*
  106773. ** Implementation of the substr() function.
  106774. **
  106775. ** substr(x,p1,p2) returns p2 characters of x[] beginning with p1.
  106776. ** p1 is 1-indexed. So substr(x,1,1) returns the first character
  106777. ** of x. If x is text, then we actually count UTF-8 characters.
  106778. ** If x is a blob, then we count bytes.
  106779. **
  106780. ** If p1 is negative, then we begin abs(p1) from the end of x[].
  106781. **
  106782. ** If p2 is negative, return the p2 characters preceding p1.
  106783. */
  106784. static void substrFunc(
  106785. sqlite3_context *context,
  106786. int argc,
  106787. sqlite3_value **argv
  106788. ){
  106789. const unsigned char *z;
  106790. const unsigned char *z2;
  106791. int len;
  106792. int p0type;
  106793. i64 p1, p2;
  106794. int negP2 = 0;
  106795. assert( argc==3 || argc==2 );
  106796. if( sqlite3_value_type(argv[1])==SQLITE_NULL
  106797. || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
  106798. ){
  106799. return;
  106800. }
  106801. p0type = sqlite3_value_type(argv[0]);
  106802. p1 = sqlite3_value_int(argv[1]);
  106803. if( p0type==SQLITE_BLOB ){
  106804. len = sqlite3_value_bytes(argv[0]);
  106805. z = sqlite3_value_blob(argv[0]);
  106806. if( z==0 ) return;
  106807. assert( len==sqlite3_value_bytes(argv[0]) );
  106808. }else{
  106809. z = sqlite3_value_text(argv[0]);
  106810. if( z==0 ) return;
  106811. len = 0;
  106812. if( p1<0 ){
  106813. for(z2=z; *z2; len++){
  106814. SQLITE_SKIP_UTF8(z2);
  106815. }
  106816. }
  106817. }
  106818. #ifdef SQLITE_SUBSTR_COMPATIBILITY
  106819. /* If SUBSTR_COMPATIBILITY is defined then substr(X,0,N) work the same as
  106820. ** as substr(X,1,N) - it returns the first N characters of X. This
  106821. ** is essentially a back-out of the bug-fix in check-in [5fc125d362df4b8]
  106822. ** from 2009-02-02 for compatibility of applications that exploited the
  106823. ** old buggy behavior. */
  106824. if( p1==0 ) p1 = 1; /* <rdar://problem/6778339> */
  106825. #endif
  106826. if( argc==3 ){
  106827. p2 = sqlite3_value_int(argv[2]);
  106828. if( p2<0 ){
  106829. p2 = -p2;
  106830. negP2 = 1;
  106831. }
  106832. }else{
  106833. p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
  106834. }
  106835. if( p1<0 ){
  106836. p1 += len;
  106837. if( p1<0 ){
  106838. p2 += p1;
  106839. if( p2<0 ) p2 = 0;
  106840. p1 = 0;
  106841. }
  106842. }else if( p1>0 ){
  106843. p1--;
  106844. }else if( p2>0 ){
  106845. p2--;
  106846. }
  106847. if( negP2 ){
  106848. p1 -= p2;
  106849. if( p1<0 ){
  106850. p2 += p1;
  106851. p1 = 0;
  106852. }
  106853. }
  106854. assert( p1>=0 && p2>=0 );
  106855. if( p0type!=SQLITE_BLOB ){
  106856. while( *z && p1 ){
  106857. SQLITE_SKIP_UTF8(z);
  106858. p1--;
  106859. }
  106860. for(z2=z; *z2 && p2; p2--){
  106861. SQLITE_SKIP_UTF8(z2);
  106862. }
  106863. sqlite3_result_text64(context, (char*)z, z2-z, SQLITE_TRANSIENT,
  106864. SQLITE_UTF8);
  106865. }else{
  106866. if( p1+p2>len ){
  106867. p2 = len-p1;
  106868. if( p2<0 ) p2 = 0;
  106869. }
  106870. sqlite3_result_blob64(context, (char*)&z[p1], (u64)p2, SQLITE_TRANSIENT);
  106871. }
  106872. }
  106873. /*
  106874. ** Implementation of the round() function
  106875. */
  106876. #ifndef SQLITE_OMIT_FLOATING_POINT
  106877. static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  106878. int n = 0;
  106879. double r;
  106880. char *zBuf;
  106881. assert( argc==1 || argc==2 );
  106882. if( argc==2 ){
  106883. if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
  106884. n = sqlite3_value_int(argv[1]);
  106885. if( n>30 ) n = 30;
  106886. if( n<0 ) n = 0;
  106887. }
  106888. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  106889. r = sqlite3_value_double(argv[0]);
  106890. /* If Y==0 and X will fit in a 64-bit int,
  106891. ** handle the rounding directly,
  106892. ** otherwise use printf.
  106893. */
  106894. if( r<-4503599627370496.0 || r>+4503599627370496.0 ){
  106895. /* The value has no fractional part so there is nothing to round */
  106896. }else if( n==0 ){
  106897. r = (double)((sqlite_int64)(r+(r<0?-0.5:+0.5)));
  106898. }else{
  106899. zBuf = sqlite3_mprintf("%.*f",n,r);
  106900. if( zBuf==0 ){
  106901. sqlite3_result_error_nomem(context);
  106902. return;
  106903. }
  106904. sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
  106905. sqlite3_free(zBuf);
  106906. }
  106907. sqlite3_result_double(context, r);
  106908. }
  106909. #endif
  106910. /*
  106911. ** Allocate nByte bytes of space using sqlite3Malloc(). If the
  106912. ** allocation fails, call sqlite3_result_error_nomem() to notify
  106913. ** the database handle that malloc() has failed and return NULL.
  106914. ** If nByte is larger than the maximum string or blob length, then
  106915. ** raise an SQLITE_TOOBIG exception and return NULL.
  106916. */
  106917. static void *contextMalloc(sqlite3_context *context, i64 nByte){
  106918. char *z;
  106919. sqlite3 *db = sqlite3_context_db_handle(context);
  106920. assert( nByte>0 );
  106921. testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
  106922. testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  106923. if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  106924. sqlite3_result_error_toobig(context);
  106925. z = 0;
  106926. }else{
  106927. z = sqlite3Malloc(nByte);
  106928. if( !z ){
  106929. sqlite3_result_error_nomem(context);
  106930. }
  106931. }
  106932. return z;
  106933. }
  106934. /*
  106935. ** Implementation of the upper() and lower() SQL functions.
  106936. */
  106937. static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  106938. char *z1;
  106939. const char *z2;
  106940. int i, n;
  106941. UNUSED_PARAMETER(argc);
  106942. z2 = (char*)sqlite3_value_text(argv[0]);
  106943. n = sqlite3_value_bytes(argv[0]);
  106944. /* Verify that the call to _bytes() does not invalidate the _text() pointer */
  106945. assert( z2==(char*)sqlite3_value_text(argv[0]) );
  106946. if( z2 ){
  106947. z1 = contextMalloc(context, ((i64)n)+1);
  106948. if( z1 ){
  106949. for(i=0; i<n; i++){
  106950. z1[i] = (char)sqlite3Toupper(z2[i]);
  106951. }
  106952. sqlite3_result_text(context, z1, n, sqlite3_free);
  106953. }
  106954. }
  106955. }
  106956. static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  106957. char *z1;
  106958. const char *z2;
  106959. int i, n;
  106960. UNUSED_PARAMETER(argc);
  106961. z2 = (char*)sqlite3_value_text(argv[0]);
  106962. n = sqlite3_value_bytes(argv[0]);
  106963. /* Verify that the call to _bytes() does not invalidate the _text() pointer */
  106964. assert( z2==(char*)sqlite3_value_text(argv[0]) );
  106965. if( z2 ){
  106966. z1 = contextMalloc(context, ((i64)n)+1);
  106967. if( z1 ){
  106968. for(i=0; i<n; i++){
  106969. z1[i] = sqlite3Tolower(z2[i]);
  106970. }
  106971. sqlite3_result_text(context, z1, n, sqlite3_free);
  106972. }
  106973. }
  106974. }
  106975. /*
  106976. ** Some functions like COALESCE() and IFNULL() and UNLIKELY() are implemented
  106977. ** as VDBE code so that unused argument values do not have to be computed.
  106978. ** However, we still need some kind of function implementation for this
  106979. ** routines in the function table. The noopFunc macro provides this.
  106980. ** noopFunc will never be called so it doesn't matter what the implementation
  106981. ** is. We might as well use the "version()" function as a substitute.
  106982. */
  106983. #define noopFunc versionFunc /* Substitute function - never called */
  106984. /*
  106985. ** Implementation of random(). Return a random integer.
  106986. */
  106987. static void randomFunc(
  106988. sqlite3_context *context,
  106989. int NotUsed,
  106990. sqlite3_value **NotUsed2
  106991. ){
  106992. sqlite_int64 r;
  106993. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  106994. sqlite3_randomness(sizeof(r), &r);
  106995. if( r<0 ){
  106996. /* We need to prevent a random number of 0x8000000000000000
  106997. ** (or -9223372036854775808) since when you do abs() of that
  106998. ** number of you get the same value back again. To do this
  106999. ** in a way that is testable, mask the sign bit off of negative
  107000. ** values, resulting in a positive value. Then take the
  107001. ** 2s complement of that positive value. The end result can
  107002. ** therefore be no less than -9223372036854775807.
  107003. */
  107004. r = -(r & LARGEST_INT64);
  107005. }
  107006. sqlite3_result_int64(context, r);
  107007. }
  107008. /*
  107009. ** Implementation of randomblob(N). Return a random blob
  107010. ** that is N bytes long.
  107011. */
  107012. static void randomBlob(
  107013. sqlite3_context *context,
  107014. int argc,
  107015. sqlite3_value **argv
  107016. ){
  107017. sqlite3_int64 n;
  107018. unsigned char *p;
  107019. assert( argc==1 );
  107020. UNUSED_PARAMETER(argc);
  107021. n = sqlite3_value_int64(argv[0]);
  107022. if( n<1 ){
  107023. n = 1;
  107024. }
  107025. p = contextMalloc(context, n);
  107026. if( p ){
  107027. sqlite3_randomness(n, p);
  107028. sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
  107029. }
  107030. }
  107031. /*
  107032. ** Implementation of the last_insert_rowid() SQL function. The return
  107033. ** value is the same as the sqlite3_last_insert_rowid() API function.
  107034. */
  107035. static void last_insert_rowid(
  107036. sqlite3_context *context,
  107037. int NotUsed,
  107038. sqlite3_value **NotUsed2
  107039. ){
  107040. sqlite3 *db = sqlite3_context_db_handle(context);
  107041. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  107042. /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
  107043. ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
  107044. ** function. */
  107045. sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
  107046. }
  107047. /*
  107048. ** Implementation of the changes() SQL function.
  107049. **
  107050. ** IMP: R-62073-11209 The changes() SQL function is a wrapper
  107051. ** around the sqlite3_changes() C/C++ function and hence follows the same
  107052. ** rules for counting changes.
  107053. */
  107054. static void changes(
  107055. sqlite3_context *context,
  107056. int NotUsed,
  107057. sqlite3_value **NotUsed2
  107058. ){
  107059. sqlite3 *db = sqlite3_context_db_handle(context);
  107060. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  107061. sqlite3_result_int(context, sqlite3_changes(db));
  107062. }
  107063. /*
  107064. ** Implementation of the total_changes() SQL function. The return value is
  107065. ** the same as the sqlite3_total_changes() API function.
  107066. */
  107067. static void total_changes(
  107068. sqlite3_context *context,
  107069. int NotUsed,
  107070. sqlite3_value **NotUsed2
  107071. ){
  107072. sqlite3 *db = sqlite3_context_db_handle(context);
  107073. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  107074. /* IMP: R-52756-41993 This function is a wrapper around the
  107075. ** sqlite3_total_changes() C/C++ interface. */
  107076. sqlite3_result_int(context, sqlite3_total_changes(db));
  107077. }
  107078. /*
  107079. ** A structure defining how to do GLOB-style comparisons.
  107080. */
  107081. struct compareInfo {
  107082. u8 matchAll; /* "*" or "%" */
  107083. u8 matchOne; /* "?" or "_" */
  107084. u8 matchSet; /* "[" or 0 */
  107085. u8 noCase; /* true to ignore case differences */
  107086. };
  107087. /*
  107088. ** For LIKE and GLOB matching on EBCDIC machines, assume that every
  107089. ** character is exactly one byte in size. Also, provde the Utf8Read()
  107090. ** macro for fast reading of the next character in the common case where
  107091. ** the next character is ASCII.
  107092. */
  107093. #if defined(SQLITE_EBCDIC)
  107094. # define sqlite3Utf8Read(A) (*((*A)++))
  107095. # define Utf8Read(A) (*(A++))
  107096. #else
  107097. # define Utf8Read(A) (A[0]<0x80?*(A++):sqlite3Utf8Read(&A))
  107098. #endif
  107099. static const struct compareInfo globInfo = { '*', '?', '[', 0 };
  107100. /* The correct SQL-92 behavior is for the LIKE operator to ignore
  107101. ** case. Thus 'a' LIKE 'A' would be true. */
  107102. static const struct compareInfo likeInfoNorm = { '%', '_', 0, 1 };
  107103. /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
  107104. ** is case sensitive causing 'a' LIKE 'A' to be false */
  107105. static const struct compareInfo likeInfoAlt = { '%', '_', 0, 0 };
  107106. /*
  107107. ** Possible error returns from patternMatch()
  107108. */
  107109. #define SQLITE_MATCH 0
  107110. #define SQLITE_NOMATCH 1
  107111. #define SQLITE_NOWILDCARDMATCH 2
  107112. /*
  107113. ** Compare two UTF-8 strings for equality where the first string is
  107114. ** a GLOB or LIKE expression. Return values:
  107115. **
  107116. ** SQLITE_MATCH: Match
  107117. ** SQLITE_NOMATCH: No match
  107118. ** SQLITE_NOWILDCARDMATCH: No match in spite of having * or % wildcards.
  107119. **
  107120. ** Globbing rules:
  107121. **
  107122. ** '*' Matches any sequence of zero or more characters.
  107123. **
  107124. ** '?' Matches exactly one character.
  107125. **
  107126. ** [...] Matches one character from the enclosed list of
  107127. ** characters.
  107128. **
  107129. ** [^...] Matches one character not in the enclosed list.
  107130. **
  107131. ** With the [...] and [^...] matching, a ']' character can be included
  107132. ** in the list by making it the first character after '[' or '^'. A
  107133. ** range of characters can be specified using '-'. Example:
  107134. ** "[a-z]" matches any single lower-case letter. To match a '-', make
  107135. ** it the last character in the list.
  107136. **
  107137. ** Like matching rules:
  107138. **
  107139. ** '%' Matches any sequence of zero or more characters
  107140. **
  107141. *** '_' Matches any one character
  107142. **
  107143. ** Ec Where E is the "esc" character and c is any other
  107144. ** character, including '%', '_', and esc, match exactly c.
  107145. **
  107146. ** The comments within this routine usually assume glob matching.
  107147. **
  107148. ** This routine is usually quick, but can be N**2 in the worst case.
  107149. */
  107150. static int patternCompare(
  107151. const u8 *zPattern, /* The glob pattern */
  107152. const u8 *zString, /* The string to compare against the glob */
  107153. const struct compareInfo *pInfo, /* Information about how to do the compare */
  107154. u32 matchOther /* The escape char (LIKE) or '[' (GLOB) */
  107155. ){
  107156. u32 c, c2; /* Next pattern and input string chars */
  107157. u32 matchOne = pInfo->matchOne; /* "?" or "_" */
  107158. u32 matchAll = pInfo->matchAll; /* "*" or "%" */
  107159. u8 noCase = pInfo->noCase; /* True if uppercase==lowercase */
  107160. const u8 *zEscaped = 0; /* One past the last escaped input char */
  107161. while( (c = Utf8Read(zPattern))!=0 ){
  107162. if( c==matchAll ){ /* Match "*" */
  107163. /* Skip over multiple "*" characters in the pattern. If there
  107164. ** are also "?" characters, skip those as well, but consume a
  107165. ** single character of the input string for each "?" skipped */
  107166. while( (c=Utf8Read(zPattern)) == matchAll || c == matchOne ){
  107167. if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
  107168. return SQLITE_NOWILDCARDMATCH;
  107169. }
  107170. }
  107171. if( c==0 ){
  107172. return SQLITE_MATCH; /* "*" at the end of the pattern matches */
  107173. }else if( c==matchOther ){
  107174. if( pInfo->matchSet==0 ){
  107175. c = sqlite3Utf8Read(&zPattern);
  107176. if( c==0 ) return SQLITE_NOWILDCARDMATCH;
  107177. }else{
  107178. /* "[...]" immediately follows the "*". We have to do a slow
  107179. ** recursive search in this case, but it is an unusual case. */
  107180. assert( matchOther<0x80 ); /* '[' is a single-byte character */
  107181. while( *zString ){
  107182. int bMatch = patternCompare(&zPattern[-1],zString,pInfo,matchOther);
  107183. if( bMatch!=SQLITE_NOMATCH ) return bMatch;
  107184. SQLITE_SKIP_UTF8(zString);
  107185. }
  107186. return SQLITE_NOWILDCARDMATCH;
  107187. }
  107188. }
  107189. /* At this point variable c contains the first character of the
  107190. ** pattern string past the "*". Search in the input string for the
  107191. ** first matching character and recursively continue the match from
  107192. ** that point.
  107193. **
  107194. ** For a case-insensitive search, set variable cx to be the same as
  107195. ** c but in the other case and search the input string for either
  107196. ** c or cx.
  107197. */
  107198. if( c<=0x80 ){
  107199. char zStop[3];
  107200. int bMatch;
  107201. if( noCase ){
  107202. zStop[0] = sqlite3Toupper(c);
  107203. zStop[1] = sqlite3Tolower(c);
  107204. zStop[2] = 0;
  107205. }else{
  107206. zStop[0] = c;
  107207. zStop[1] = 0;
  107208. }
  107209. while(1){
  107210. zString += strcspn((const char*)zString, zStop);
  107211. if( zString[0]==0 ) break;
  107212. zString++;
  107213. bMatch = patternCompare(zPattern,zString,pInfo,matchOther);
  107214. if( bMatch!=SQLITE_NOMATCH ) return bMatch;
  107215. }
  107216. }else{
  107217. int bMatch;
  107218. while( (c2 = Utf8Read(zString))!=0 ){
  107219. if( c2!=c ) continue;
  107220. bMatch = patternCompare(zPattern,zString,pInfo,matchOther);
  107221. if( bMatch!=SQLITE_NOMATCH ) return bMatch;
  107222. }
  107223. }
  107224. return SQLITE_NOWILDCARDMATCH;
  107225. }
  107226. if( c==matchOther ){
  107227. if( pInfo->matchSet==0 ){
  107228. c = sqlite3Utf8Read(&zPattern);
  107229. if( c==0 ) return SQLITE_NOMATCH;
  107230. zEscaped = zPattern;
  107231. }else{
  107232. u32 prior_c = 0;
  107233. int seen = 0;
  107234. int invert = 0;
  107235. c = sqlite3Utf8Read(&zString);
  107236. if( c==0 ) return SQLITE_NOMATCH;
  107237. c2 = sqlite3Utf8Read(&zPattern);
  107238. if( c2=='^' ){
  107239. invert = 1;
  107240. c2 = sqlite3Utf8Read(&zPattern);
  107241. }
  107242. if( c2==']' ){
  107243. if( c==']' ) seen = 1;
  107244. c2 = sqlite3Utf8Read(&zPattern);
  107245. }
  107246. while( c2 && c2!=']' ){
  107247. if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
  107248. c2 = sqlite3Utf8Read(&zPattern);
  107249. if( c>=prior_c && c<=c2 ) seen = 1;
  107250. prior_c = 0;
  107251. }else{
  107252. if( c==c2 ){
  107253. seen = 1;
  107254. }
  107255. prior_c = c2;
  107256. }
  107257. c2 = sqlite3Utf8Read(&zPattern);
  107258. }
  107259. if( c2==0 || (seen ^ invert)==0 ){
  107260. return SQLITE_NOMATCH;
  107261. }
  107262. continue;
  107263. }
  107264. }
  107265. c2 = Utf8Read(zString);
  107266. if( c==c2 ) continue;
  107267. if( noCase && sqlite3Tolower(c)==sqlite3Tolower(c2) && c<0x80 && c2<0x80 ){
  107268. continue;
  107269. }
  107270. if( c==matchOne && zPattern!=zEscaped && c2!=0 ) continue;
  107271. return SQLITE_NOMATCH;
  107272. }
  107273. return *zString==0 ? SQLITE_MATCH : SQLITE_NOMATCH;
  107274. }
  107275. /*
  107276. ** The sqlite3_strglob() interface. Return 0 on a match (like strcmp()) and
  107277. ** non-zero if there is no match.
  107278. */
  107279. SQLITE_API int sqlite3_strglob(const char *zGlobPattern, const char *zString){
  107280. return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, '[');
  107281. }
  107282. /*
  107283. ** The sqlite3_strlike() interface. Return 0 on a match and non-zero for
  107284. ** a miss - like strcmp().
  107285. */
  107286. SQLITE_API int sqlite3_strlike(const char *zPattern, const char *zStr, unsigned int esc){
  107287. return patternCompare((u8*)zPattern, (u8*)zStr, &likeInfoNorm, esc);
  107288. }
  107289. /*
  107290. ** Count the number of times that the LIKE operator (or GLOB which is
  107291. ** just a variation of LIKE) gets called. This is used for testing
  107292. ** only.
  107293. */
  107294. #ifdef SQLITE_TEST
  107295. SQLITE_API int sqlite3_like_count = 0;
  107296. #endif
  107297. /*
  107298. ** Implementation of the like() SQL function. This function implements
  107299. ** the build-in LIKE operator. The first argument to the function is the
  107300. ** pattern and the second argument is the string. So, the SQL statements:
  107301. **
  107302. ** A LIKE B
  107303. **
  107304. ** is implemented as like(B,A).
  107305. **
  107306. ** This same function (with a different compareInfo structure) computes
  107307. ** the GLOB operator.
  107308. */
  107309. static void likeFunc(
  107310. sqlite3_context *context,
  107311. int argc,
  107312. sqlite3_value **argv
  107313. ){
  107314. const unsigned char *zA, *zB;
  107315. u32 escape;
  107316. int nPat;
  107317. sqlite3 *db = sqlite3_context_db_handle(context);
  107318. struct compareInfo *pInfo = sqlite3_user_data(context);
  107319. #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  107320. if( sqlite3_value_type(argv[0])==SQLITE_BLOB
  107321. || sqlite3_value_type(argv[1])==SQLITE_BLOB
  107322. ){
  107323. #ifdef SQLITE_TEST
  107324. sqlite3_like_count++;
  107325. #endif
  107326. sqlite3_result_int(context, 0);
  107327. return;
  107328. }
  107329. #endif
  107330. /* Limit the length of the LIKE or GLOB pattern to avoid problems
  107331. ** of deep recursion and N*N behavior in patternCompare().
  107332. */
  107333. nPat = sqlite3_value_bytes(argv[0]);
  107334. testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
  107335. testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
  107336. if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
  107337. sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
  107338. return;
  107339. }
  107340. if( argc==3 ){
  107341. /* The escape character string must consist of a single UTF-8 character.
  107342. ** Otherwise, return an error.
  107343. */
  107344. const unsigned char *zEsc = sqlite3_value_text(argv[2]);
  107345. if( zEsc==0 ) return;
  107346. if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
  107347. sqlite3_result_error(context,
  107348. "ESCAPE expression must be a single character", -1);
  107349. return;
  107350. }
  107351. escape = sqlite3Utf8Read(&zEsc);
  107352. }else{
  107353. escape = pInfo->matchSet;
  107354. }
  107355. zB = sqlite3_value_text(argv[0]);
  107356. zA = sqlite3_value_text(argv[1]);
  107357. if( zA && zB ){
  107358. #ifdef SQLITE_TEST
  107359. sqlite3_like_count++;
  107360. #endif
  107361. sqlite3_result_int(context,
  107362. patternCompare(zB, zA, pInfo, escape)==SQLITE_MATCH);
  107363. }
  107364. }
  107365. /*
  107366. ** Implementation of the NULLIF(x,y) function. The result is the first
  107367. ** argument if the arguments are different. The result is NULL if the
  107368. ** arguments are equal to each other.
  107369. */
  107370. static void nullifFunc(
  107371. sqlite3_context *context,
  107372. int NotUsed,
  107373. sqlite3_value **argv
  107374. ){
  107375. CollSeq *pColl = sqlite3GetFuncCollSeq(context);
  107376. UNUSED_PARAMETER(NotUsed);
  107377. if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
  107378. sqlite3_result_value(context, argv[0]);
  107379. }
  107380. }
  107381. /*
  107382. ** Implementation of the sqlite_version() function. The result is the version
  107383. ** of the SQLite library that is running.
  107384. */
  107385. static void versionFunc(
  107386. sqlite3_context *context,
  107387. int NotUsed,
  107388. sqlite3_value **NotUsed2
  107389. ){
  107390. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  107391. /* IMP: R-48699-48617 This function is an SQL wrapper around the
  107392. ** sqlite3_libversion() C-interface. */
  107393. sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
  107394. }
  107395. /*
  107396. ** Implementation of the sqlite_source_id() function. The result is a string
  107397. ** that identifies the particular version of the source code used to build
  107398. ** SQLite.
  107399. */
  107400. static void sourceidFunc(
  107401. sqlite3_context *context,
  107402. int NotUsed,
  107403. sqlite3_value **NotUsed2
  107404. ){
  107405. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  107406. /* IMP: R-24470-31136 This function is an SQL wrapper around the
  107407. ** sqlite3_sourceid() C interface. */
  107408. sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
  107409. }
  107410. /*
  107411. ** Implementation of the sqlite_log() function. This is a wrapper around
  107412. ** sqlite3_log(). The return value is NULL. The function exists purely for
  107413. ** its side-effects.
  107414. */
  107415. static void errlogFunc(
  107416. sqlite3_context *context,
  107417. int argc,
  107418. sqlite3_value **argv
  107419. ){
  107420. UNUSED_PARAMETER(argc);
  107421. UNUSED_PARAMETER(context);
  107422. sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
  107423. }
  107424. /*
  107425. ** Implementation of the sqlite_compileoption_used() function.
  107426. ** The result is an integer that identifies if the compiler option
  107427. ** was used to build SQLite.
  107428. */
  107429. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  107430. static void compileoptionusedFunc(
  107431. sqlite3_context *context,
  107432. int argc,
  107433. sqlite3_value **argv
  107434. ){
  107435. const char *zOptName;
  107436. assert( argc==1 );
  107437. UNUSED_PARAMETER(argc);
  107438. /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
  107439. ** function is a wrapper around the sqlite3_compileoption_used() C/C++
  107440. ** function.
  107441. */
  107442. if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
  107443. sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
  107444. }
  107445. }
  107446. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  107447. /*
  107448. ** Implementation of the sqlite_compileoption_get() function.
  107449. ** The result is a string that identifies the compiler options
  107450. ** used to build SQLite.
  107451. */
  107452. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  107453. static void compileoptiongetFunc(
  107454. sqlite3_context *context,
  107455. int argc,
  107456. sqlite3_value **argv
  107457. ){
  107458. int n;
  107459. assert( argc==1 );
  107460. UNUSED_PARAMETER(argc);
  107461. /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
  107462. ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
  107463. */
  107464. n = sqlite3_value_int(argv[0]);
  107465. sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
  107466. }
  107467. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  107468. /* Array for converting from half-bytes (nybbles) into ASCII hex
  107469. ** digits. */
  107470. static const char hexdigits[] = {
  107471. '0', '1', '2', '3', '4', '5', '6', '7',
  107472. '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
  107473. };
  107474. /*
  107475. ** Implementation of the QUOTE() function. This function takes a single
  107476. ** argument. If the argument is numeric, the return value is the same as
  107477. ** the argument. If the argument is NULL, the return value is the string
  107478. ** "NULL". Otherwise, the argument is enclosed in single quotes with
  107479. ** single-quote escapes.
  107480. */
  107481. static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  107482. assert( argc==1 );
  107483. UNUSED_PARAMETER(argc);
  107484. switch( sqlite3_value_type(argv[0]) ){
  107485. case SQLITE_FLOAT: {
  107486. double r1, r2;
  107487. char zBuf[50];
  107488. r1 = sqlite3_value_double(argv[0]);
  107489. sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
  107490. sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8);
  107491. if( r1!=r2 ){
  107492. sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1);
  107493. }
  107494. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  107495. break;
  107496. }
  107497. case SQLITE_INTEGER: {
  107498. sqlite3_result_value(context, argv[0]);
  107499. break;
  107500. }
  107501. case SQLITE_BLOB: {
  107502. char *zText = 0;
  107503. char const *zBlob = sqlite3_value_blob(argv[0]);
  107504. int nBlob = sqlite3_value_bytes(argv[0]);
  107505. assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
  107506. zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
  107507. if( zText ){
  107508. int i;
  107509. for(i=0; i<nBlob; i++){
  107510. zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
  107511. zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
  107512. }
  107513. zText[(nBlob*2)+2] = '\'';
  107514. zText[(nBlob*2)+3] = '\0';
  107515. zText[0] = 'X';
  107516. zText[1] = '\'';
  107517. sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
  107518. sqlite3_free(zText);
  107519. }
  107520. break;
  107521. }
  107522. case SQLITE_TEXT: {
  107523. int i,j;
  107524. u64 n;
  107525. const unsigned char *zArg = sqlite3_value_text(argv[0]);
  107526. char *z;
  107527. if( zArg==0 ) return;
  107528. for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
  107529. z = contextMalloc(context, ((i64)i)+((i64)n)+3);
  107530. if( z ){
  107531. z[0] = '\'';
  107532. for(i=0, j=1; zArg[i]; i++){
  107533. z[j++] = zArg[i];
  107534. if( zArg[i]=='\'' ){
  107535. z[j++] = '\'';
  107536. }
  107537. }
  107538. z[j++] = '\'';
  107539. z[j] = 0;
  107540. sqlite3_result_text(context, z, j, sqlite3_free);
  107541. }
  107542. break;
  107543. }
  107544. default: {
  107545. assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
  107546. sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
  107547. break;
  107548. }
  107549. }
  107550. }
  107551. /*
  107552. ** The unicode() function. Return the integer unicode code-point value
  107553. ** for the first character of the input string.
  107554. */
  107555. static void unicodeFunc(
  107556. sqlite3_context *context,
  107557. int argc,
  107558. sqlite3_value **argv
  107559. ){
  107560. const unsigned char *z = sqlite3_value_text(argv[0]);
  107561. (void)argc;
  107562. if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z));
  107563. }
  107564. /*
  107565. ** The char() function takes zero or more arguments, each of which is
  107566. ** an integer. It constructs a string where each character of the string
  107567. ** is the unicode character for the corresponding integer argument.
  107568. */
  107569. static void charFunc(
  107570. sqlite3_context *context,
  107571. int argc,
  107572. sqlite3_value **argv
  107573. ){
  107574. unsigned char *z, *zOut;
  107575. int i;
  107576. zOut = z = sqlite3_malloc64( argc*4+1 );
  107577. if( z==0 ){
  107578. sqlite3_result_error_nomem(context);
  107579. return;
  107580. }
  107581. for(i=0; i<argc; i++){
  107582. sqlite3_int64 x;
  107583. unsigned c;
  107584. x = sqlite3_value_int64(argv[i]);
  107585. if( x<0 || x>0x10ffff ) x = 0xfffd;
  107586. c = (unsigned)(x & 0x1fffff);
  107587. if( c<0x00080 ){
  107588. *zOut++ = (u8)(c&0xFF);
  107589. }else if( c<0x00800 ){
  107590. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);
  107591. *zOut++ = 0x80 + (u8)(c & 0x3F);
  107592. }else if( c<0x10000 ){
  107593. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);
  107594. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
  107595. *zOut++ = 0x80 + (u8)(c & 0x3F);
  107596. }else{
  107597. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);
  107598. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);
  107599. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
  107600. *zOut++ = 0x80 + (u8)(c & 0x3F);
  107601. } \
  107602. }
  107603. sqlite3_result_text64(context, (char*)z, zOut-z, sqlite3_free, SQLITE_UTF8);
  107604. }
  107605. /*
  107606. ** The hex() function. Interpret the argument as a blob. Return
  107607. ** a hexadecimal rendering as text.
  107608. */
  107609. static void hexFunc(
  107610. sqlite3_context *context,
  107611. int argc,
  107612. sqlite3_value **argv
  107613. ){
  107614. int i, n;
  107615. const unsigned char *pBlob;
  107616. char *zHex, *z;
  107617. assert( argc==1 );
  107618. UNUSED_PARAMETER(argc);
  107619. pBlob = sqlite3_value_blob(argv[0]);
  107620. n = sqlite3_value_bytes(argv[0]);
  107621. assert( pBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
  107622. z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
  107623. if( zHex ){
  107624. for(i=0; i<n; i++, pBlob++){
  107625. unsigned char c = *pBlob;
  107626. *(z++) = hexdigits[(c>>4)&0xf];
  107627. *(z++) = hexdigits[c&0xf];
  107628. }
  107629. *z = 0;
  107630. sqlite3_result_text(context, zHex, n*2, sqlite3_free);
  107631. }
  107632. }
  107633. /*
  107634. ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
  107635. */
  107636. static void zeroblobFunc(
  107637. sqlite3_context *context,
  107638. int argc,
  107639. sqlite3_value **argv
  107640. ){
  107641. i64 n;
  107642. int rc;
  107643. assert( argc==1 );
  107644. UNUSED_PARAMETER(argc);
  107645. n = sqlite3_value_int64(argv[0]);
  107646. if( n<0 ) n = 0;
  107647. rc = sqlite3_result_zeroblob64(context, n); /* IMP: R-00293-64994 */
  107648. if( rc ){
  107649. sqlite3_result_error_code(context, rc);
  107650. }
  107651. }
  107652. /*
  107653. ** The replace() function. Three arguments are all strings: call
  107654. ** them A, B, and C. The result is also a string which is derived
  107655. ** from A by replacing every occurrence of B with C. The match
  107656. ** must be exact. Collating sequences are not used.
  107657. */
  107658. static void replaceFunc(
  107659. sqlite3_context *context,
  107660. int argc,
  107661. sqlite3_value **argv
  107662. ){
  107663. const unsigned char *zStr; /* The input string A */
  107664. const unsigned char *zPattern; /* The pattern string B */
  107665. const unsigned char *zRep; /* The replacement string C */
  107666. unsigned char *zOut; /* The output */
  107667. int nStr; /* Size of zStr */
  107668. int nPattern; /* Size of zPattern */
  107669. int nRep; /* Size of zRep */
  107670. i64 nOut; /* Maximum size of zOut */
  107671. int loopLimit; /* Last zStr[] that might match zPattern[] */
  107672. int i, j; /* Loop counters */
  107673. unsigned cntExpand; /* Number zOut expansions */
  107674. sqlite3 *db = sqlite3_context_db_handle(context);
  107675. assert( argc==3 );
  107676. UNUSED_PARAMETER(argc);
  107677. zStr = sqlite3_value_text(argv[0]);
  107678. if( zStr==0 ) return;
  107679. nStr = sqlite3_value_bytes(argv[0]);
  107680. assert( zStr==sqlite3_value_text(argv[0]) ); /* No encoding change */
  107681. zPattern = sqlite3_value_text(argv[1]);
  107682. if( zPattern==0 ){
  107683. assert( sqlite3_value_type(argv[1])==SQLITE_NULL
  107684. || sqlite3_context_db_handle(context)->mallocFailed );
  107685. return;
  107686. }
  107687. if( zPattern[0]==0 ){
  107688. assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
  107689. sqlite3_result_value(context, argv[0]);
  107690. return;
  107691. }
  107692. nPattern = sqlite3_value_bytes(argv[1]);
  107693. assert( zPattern==sqlite3_value_text(argv[1]) ); /* No encoding change */
  107694. zRep = sqlite3_value_text(argv[2]);
  107695. if( zRep==0 ) return;
  107696. nRep = sqlite3_value_bytes(argv[2]);
  107697. assert( zRep==sqlite3_value_text(argv[2]) );
  107698. nOut = nStr + 1;
  107699. assert( nOut<SQLITE_MAX_LENGTH );
  107700. zOut = contextMalloc(context, (i64)nOut);
  107701. if( zOut==0 ){
  107702. return;
  107703. }
  107704. loopLimit = nStr - nPattern;
  107705. cntExpand = 0;
  107706. for(i=j=0; i<=loopLimit; i++){
  107707. if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
  107708. zOut[j++] = zStr[i];
  107709. }else{
  107710. if( nRep>nPattern ){
  107711. nOut += nRep - nPattern;
  107712. testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
  107713. testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
  107714. if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  107715. sqlite3_result_error_toobig(context);
  107716. sqlite3_free(zOut);
  107717. return;
  107718. }
  107719. cntExpand++;
  107720. if( (cntExpand&(cntExpand-1))==0 ){
  107721. /* Grow the size of the output buffer only on substitutions
  107722. ** whose index is a power of two: 1, 2, 4, 8, 16, 32, ... */
  107723. u8 *zOld;
  107724. zOld = zOut;
  107725. zOut = sqlite3_realloc64(zOut, (int)nOut + (nOut - nStr - 1));
  107726. if( zOut==0 ){
  107727. sqlite3_result_error_nomem(context);
  107728. sqlite3_free(zOld);
  107729. return;
  107730. }
  107731. }
  107732. }
  107733. memcpy(&zOut[j], zRep, nRep);
  107734. j += nRep;
  107735. i += nPattern-1;
  107736. }
  107737. }
  107738. assert( j+nStr-i+1<=nOut );
  107739. memcpy(&zOut[j], &zStr[i], nStr-i);
  107740. j += nStr - i;
  107741. assert( j<=nOut );
  107742. zOut[j] = 0;
  107743. sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
  107744. }
  107745. /*
  107746. ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
  107747. ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
  107748. */
  107749. static void trimFunc(
  107750. sqlite3_context *context,
  107751. int argc,
  107752. sqlite3_value **argv
  107753. ){
  107754. const unsigned char *zIn; /* Input string */
  107755. const unsigned char *zCharSet; /* Set of characters to trim */
  107756. int nIn; /* Number of bytes in input */
  107757. int flags; /* 1: trimleft 2: trimright 3: trim */
  107758. int i; /* Loop counter */
  107759. unsigned char *aLen = 0; /* Length of each character in zCharSet */
  107760. unsigned char **azChar = 0; /* Individual characters in zCharSet */
  107761. int nChar; /* Number of characters in zCharSet */
  107762. if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
  107763. return;
  107764. }
  107765. zIn = sqlite3_value_text(argv[0]);
  107766. if( zIn==0 ) return;
  107767. nIn = sqlite3_value_bytes(argv[0]);
  107768. assert( zIn==sqlite3_value_text(argv[0]) );
  107769. if( argc==1 ){
  107770. static const unsigned char lenOne[] = { 1 };
  107771. static unsigned char * const azOne[] = { (u8*)" " };
  107772. nChar = 1;
  107773. aLen = (u8*)lenOne;
  107774. azChar = (unsigned char **)azOne;
  107775. zCharSet = 0;
  107776. }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
  107777. return;
  107778. }else{
  107779. const unsigned char *z;
  107780. for(z=zCharSet, nChar=0; *z; nChar++){
  107781. SQLITE_SKIP_UTF8(z);
  107782. }
  107783. if( nChar>0 ){
  107784. azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
  107785. if( azChar==0 ){
  107786. return;
  107787. }
  107788. aLen = (unsigned char*)&azChar[nChar];
  107789. for(z=zCharSet, nChar=0; *z; nChar++){
  107790. azChar[nChar] = (unsigned char *)z;
  107791. SQLITE_SKIP_UTF8(z);
  107792. aLen[nChar] = (u8)(z - azChar[nChar]);
  107793. }
  107794. }
  107795. }
  107796. if( nChar>0 ){
  107797. flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
  107798. if( flags & 1 ){
  107799. while( nIn>0 ){
  107800. int len = 0;
  107801. for(i=0; i<nChar; i++){
  107802. len = aLen[i];
  107803. if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
  107804. }
  107805. if( i>=nChar ) break;
  107806. zIn += len;
  107807. nIn -= len;
  107808. }
  107809. }
  107810. if( flags & 2 ){
  107811. while( nIn>0 ){
  107812. int len = 0;
  107813. for(i=0; i<nChar; i++){
  107814. len = aLen[i];
  107815. if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
  107816. }
  107817. if( i>=nChar ) break;
  107818. nIn -= len;
  107819. }
  107820. }
  107821. if( zCharSet ){
  107822. sqlite3_free(azChar);
  107823. }
  107824. }
  107825. sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
  107826. }
  107827. #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
  107828. /*
  107829. ** The "unknown" function is automatically substituted in place of
  107830. ** any unrecognized function name when doing an EXPLAIN or EXPLAIN QUERY PLAN
  107831. ** when the SQLITE_ENABLE_UNKNOWN_FUNCTION compile-time option is used.
  107832. ** When the "sqlite3" command-line shell is built using this functionality,
  107833. ** that allows an EXPLAIN or EXPLAIN QUERY PLAN for complex queries
  107834. ** involving application-defined functions to be examined in a generic
  107835. ** sqlite3 shell.
  107836. */
  107837. static void unknownFunc(
  107838. sqlite3_context *context,
  107839. int argc,
  107840. sqlite3_value **argv
  107841. ){
  107842. /* no-op */
  107843. }
  107844. #endif /*SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION*/
  107845. /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
  107846. ** is only available if the SQLITE_SOUNDEX compile-time option is used
  107847. ** when SQLite is built.
  107848. */
  107849. #ifdef SQLITE_SOUNDEX
  107850. /*
  107851. ** Compute the soundex encoding of a word.
  107852. **
  107853. ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
  107854. ** soundex encoding of the string X.
  107855. */
  107856. static void soundexFunc(
  107857. sqlite3_context *context,
  107858. int argc,
  107859. sqlite3_value **argv
  107860. ){
  107861. char zResult[8];
  107862. const u8 *zIn;
  107863. int i, j;
  107864. static const unsigned char iCode[] = {
  107865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  107866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  107867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  107868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  107869. 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
  107870. 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
  107871. 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
  107872. 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
  107873. };
  107874. assert( argc==1 );
  107875. zIn = (u8*)sqlite3_value_text(argv[0]);
  107876. if( zIn==0 ) zIn = (u8*)"";
  107877. for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
  107878. if( zIn[i] ){
  107879. u8 prevcode = iCode[zIn[i]&0x7f];
  107880. zResult[0] = sqlite3Toupper(zIn[i]);
  107881. for(j=1; j<4 && zIn[i]; i++){
  107882. int code = iCode[zIn[i]&0x7f];
  107883. if( code>0 ){
  107884. if( code!=prevcode ){
  107885. prevcode = code;
  107886. zResult[j++] = code + '0';
  107887. }
  107888. }else{
  107889. prevcode = 0;
  107890. }
  107891. }
  107892. while( j<4 ){
  107893. zResult[j++] = '0';
  107894. }
  107895. zResult[j] = 0;
  107896. sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
  107897. }else{
  107898. /* IMP: R-64894-50321 The string "?000" is returned if the argument
  107899. ** is NULL or contains no ASCII alphabetic characters. */
  107900. sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
  107901. }
  107902. }
  107903. #endif /* SQLITE_SOUNDEX */
  107904. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  107905. /*
  107906. ** A function that loads a shared-library extension then returns NULL.
  107907. */
  107908. static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
  107909. const char *zFile = (const char *)sqlite3_value_text(argv[0]);
  107910. const char *zProc;
  107911. sqlite3 *db = sqlite3_context_db_handle(context);
  107912. char *zErrMsg = 0;
  107913. /* Disallow the load_extension() SQL function unless the SQLITE_LoadExtFunc
  107914. ** flag is set. See the sqlite3_enable_load_extension() API.
  107915. */
  107916. if( (db->flags & SQLITE_LoadExtFunc)==0 ){
  107917. sqlite3_result_error(context, "not authorized", -1);
  107918. return;
  107919. }
  107920. if( argc==2 ){
  107921. zProc = (const char *)sqlite3_value_text(argv[1]);
  107922. }else{
  107923. zProc = 0;
  107924. }
  107925. if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
  107926. sqlite3_result_error(context, zErrMsg, -1);
  107927. sqlite3_free(zErrMsg);
  107928. }
  107929. }
  107930. #endif
  107931. /*
  107932. ** An instance of the following structure holds the context of a
  107933. ** sum() or avg() aggregate computation.
  107934. */
  107935. typedef struct SumCtx SumCtx;
  107936. struct SumCtx {
  107937. double rSum; /* Floating point sum */
  107938. i64 iSum; /* Integer sum */
  107939. i64 cnt; /* Number of elements summed */
  107940. u8 overflow; /* True if integer overflow seen */
  107941. u8 approx; /* True if non-integer value was input to the sum */
  107942. };
  107943. /*
  107944. ** Routines used to compute the sum, average, and total.
  107945. **
  107946. ** The SUM() function follows the (broken) SQL standard which means
  107947. ** that it returns NULL if it sums over no inputs. TOTAL returns
  107948. ** 0.0 in that case. In addition, TOTAL always returns a float where
  107949. ** SUM might return an integer if it never encounters a floating point
  107950. ** value. TOTAL never fails, but SUM might through an exception if
  107951. ** it overflows an integer.
  107952. */
  107953. static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
  107954. SumCtx *p;
  107955. int type;
  107956. assert( argc==1 );
  107957. UNUSED_PARAMETER(argc);
  107958. p = sqlite3_aggregate_context(context, sizeof(*p));
  107959. type = sqlite3_value_numeric_type(argv[0]);
  107960. if( p && type!=SQLITE_NULL ){
  107961. p->cnt++;
  107962. if( type==SQLITE_INTEGER ){
  107963. i64 v = sqlite3_value_int64(argv[0]);
  107964. p->rSum += v;
  107965. if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
  107966. p->approx = p->overflow = 1;
  107967. }
  107968. }else{
  107969. p->rSum += sqlite3_value_double(argv[0]);
  107970. p->approx = 1;
  107971. }
  107972. }
  107973. }
  107974. #ifndef SQLITE_OMIT_WINDOWFUNC
  107975. static void sumInverse(sqlite3_context *context, int argc, sqlite3_value**argv){
  107976. SumCtx *p;
  107977. int type;
  107978. assert( argc==1 );
  107979. UNUSED_PARAMETER(argc);
  107980. p = sqlite3_aggregate_context(context, sizeof(*p));
  107981. type = sqlite3_value_numeric_type(argv[0]);
  107982. /* p is always non-NULL because sumStep() will have been called first
  107983. ** to initialize it */
  107984. if( ALWAYS(p) && type!=SQLITE_NULL ){
  107985. assert( p->cnt>0 );
  107986. p->cnt--;
  107987. assert( type==SQLITE_INTEGER || p->approx );
  107988. if( type==SQLITE_INTEGER && p->approx==0 ){
  107989. i64 v = sqlite3_value_int64(argv[0]);
  107990. p->rSum -= v;
  107991. p->iSum -= v;
  107992. }else{
  107993. p->rSum -= sqlite3_value_double(argv[0]);
  107994. }
  107995. }
  107996. }
  107997. #else
  107998. # define sumInverse 0
  107999. #endif /* SQLITE_OMIT_WINDOWFUNC */
  108000. static void sumFinalize(sqlite3_context *context){
  108001. SumCtx *p;
  108002. p = sqlite3_aggregate_context(context, 0);
  108003. if( p && p->cnt>0 ){
  108004. if( p->overflow ){
  108005. sqlite3_result_error(context,"integer overflow",-1);
  108006. }else if( p->approx ){
  108007. sqlite3_result_double(context, p->rSum);
  108008. }else{
  108009. sqlite3_result_int64(context, p->iSum);
  108010. }
  108011. }
  108012. }
  108013. static void avgFinalize(sqlite3_context *context){
  108014. SumCtx *p;
  108015. p = sqlite3_aggregate_context(context, 0);
  108016. if( p && p->cnt>0 ){
  108017. sqlite3_result_double(context, p->rSum/(double)p->cnt);
  108018. }
  108019. }
  108020. static void totalFinalize(sqlite3_context *context){
  108021. SumCtx *p;
  108022. p = sqlite3_aggregate_context(context, 0);
  108023. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  108024. sqlite3_result_double(context, p ? p->rSum : (double)0);
  108025. }
  108026. /*
  108027. ** The following structure keeps track of state information for the
  108028. ** count() aggregate function.
  108029. */
  108030. typedef struct CountCtx CountCtx;
  108031. struct CountCtx {
  108032. i64 n;
  108033. #ifdef SQLITE_DEBUG
  108034. int bInverse; /* True if xInverse() ever called */
  108035. #endif
  108036. };
  108037. /*
  108038. ** Routines to implement the count() aggregate function.
  108039. */
  108040. static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
  108041. CountCtx *p;
  108042. p = sqlite3_aggregate_context(context, sizeof(*p));
  108043. if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
  108044. p->n++;
  108045. }
  108046. #ifndef SQLITE_OMIT_DEPRECATED
  108047. /* The sqlite3_aggregate_count() function is deprecated. But just to make
  108048. ** sure it still operates correctly, verify that its count agrees with our
  108049. ** internal count when using count(*) and when the total count can be
  108050. ** expressed as a 32-bit integer. */
  108051. assert( argc==1 || p==0 || p->n>0x7fffffff || p->bInverse
  108052. || p->n==sqlite3_aggregate_count(context) );
  108053. #endif
  108054. }
  108055. static void countFinalize(sqlite3_context *context){
  108056. CountCtx *p;
  108057. p = sqlite3_aggregate_context(context, 0);
  108058. sqlite3_result_int64(context, p ? p->n : 0);
  108059. }
  108060. #ifndef SQLITE_OMIT_WINDOWFUNC
  108061. static void countInverse(sqlite3_context *ctx, int argc, sqlite3_value **argv){
  108062. CountCtx *p;
  108063. p = sqlite3_aggregate_context(ctx, sizeof(*p));
  108064. /* p is always non-NULL since countStep() will have been called first */
  108065. if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && ALWAYS(p) ){
  108066. p->n--;
  108067. #ifdef SQLITE_DEBUG
  108068. p->bInverse = 1;
  108069. #endif
  108070. }
  108071. }
  108072. #else
  108073. # define countInverse 0
  108074. #endif /* SQLITE_OMIT_WINDOWFUNC */
  108075. /*
  108076. ** Routines to implement min() and max() aggregate functions.
  108077. */
  108078. static void minmaxStep(
  108079. sqlite3_context *context,
  108080. int NotUsed,
  108081. sqlite3_value **argv
  108082. ){
  108083. Mem *pArg = (Mem *)argv[0];
  108084. Mem *pBest;
  108085. UNUSED_PARAMETER(NotUsed);
  108086. pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
  108087. if( !pBest ) return;
  108088. if( sqlite3_value_type(pArg)==SQLITE_NULL ){
  108089. if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
  108090. }else if( pBest->flags ){
  108091. int max;
  108092. int cmp;
  108093. CollSeq *pColl = sqlite3GetFuncCollSeq(context);
  108094. /* This step function is used for both the min() and max() aggregates,
  108095. ** the only difference between the two being that the sense of the
  108096. ** comparison is inverted. For the max() aggregate, the
  108097. ** sqlite3_user_data() function returns (void *)-1. For min() it
  108098. ** returns (void *)db, where db is the sqlite3* database pointer.
  108099. ** Therefore the next statement sets variable 'max' to 1 for the max()
  108100. ** aggregate, or 0 for min().
  108101. */
  108102. max = sqlite3_user_data(context)!=0;
  108103. cmp = sqlite3MemCompare(pBest, pArg, pColl);
  108104. if( (max && cmp<0) || (!max && cmp>0) ){
  108105. sqlite3VdbeMemCopy(pBest, pArg);
  108106. }else{
  108107. sqlite3SkipAccumulatorLoad(context);
  108108. }
  108109. }else{
  108110. pBest->db = sqlite3_context_db_handle(context);
  108111. sqlite3VdbeMemCopy(pBest, pArg);
  108112. }
  108113. }
  108114. static void minMaxValueFinalize(sqlite3_context *context, int bValue){
  108115. sqlite3_value *pRes;
  108116. pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
  108117. if( pRes ){
  108118. if( pRes->flags ){
  108119. sqlite3_result_value(context, pRes);
  108120. }
  108121. if( bValue==0 ) sqlite3VdbeMemRelease(pRes);
  108122. }
  108123. }
  108124. #ifndef SQLITE_OMIT_WINDOWFUNC
  108125. static void minMaxValue(sqlite3_context *context){
  108126. minMaxValueFinalize(context, 1);
  108127. }
  108128. #else
  108129. # define minMaxValue 0
  108130. #endif /* SQLITE_OMIT_WINDOWFUNC */
  108131. static void minMaxFinalize(sqlite3_context *context){
  108132. minMaxValueFinalize(context, 0);
  108133. }
  108134. /*
  108135. ** group_concat(EXPR, ?SEPARATOR?)
  108136. */
  108137. static void groupConcatStep(
  108138. sqlite3_context *context,
  108139. int argc,
  108140. sqlite3_value **argv
  108141. ){
  108142. const char *zVal;
  108143. StrAccum *pAccum;
  108144. const char *zSep;
  108145. int nVal, nSep;
  108146. assert( argc==1 || argc==2 );
  108147. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  108148. pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
  108149. if( pAccum ){
  108150. sqlite3 *db = sqlite3_context_db_handle(context);
  108151. int firstTerm = pAccum->mxAlloc==0;
  108152. pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
  108153. if( !firstTerm ){
  108154. if( argc==2 ){
  108155. zSep = (char*)sqlite3_value_text(argv[1]);
  108156. nSep = sqlite3_value_bytes(argv[1]);
  108157. }else{
  108158. zSep = ",";
  108159. nSep = 1;
  108160. }
  108161. if( zSep ) sqlite3_str_append(pAccum, zSep, nSep);
  108162. }
  108163. zVal = (char*)sqlite3_value_text(argv[0]);
  108164. nVal = sqlite3_value_bytes(argv[0]);
  108165. if( zVal ) sqlite3_str_append(pAccum, zVal, nVal);
  108166. }
  108167. }
  108168. #ifndef SQLITE_OMIT_WINDOWFUNC
  108169. static void groupConcatInverse(
  108170. sqlite3_context *context,
  108171. int argc,
  108172. sqlite3_value **argv
  108173. ){
  108174. int n;
  108175. StrAccum *pAccum;
  108176. assert( argc==1 || argc==2 );
  108177. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  108178. pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
  108179. /* pAccum is always non-NULL since groupConcatStep() will have always
  108180. ** run frist to initialize it */
  108181. if( ALWAYS(pAccum) ){
  108182. n = sqlite3_value_bytes(argv[0]);
  108183. if( argc==2 ){
  108184. n += sqlite3_value_bytes(argv[1]);
  108185. }else{
  108186. n++;
  108187. }
  108188. if( n>=(int)pAccum->nChar ){
  108189. pAccum->nChar = 0;
  108190. }else{
  108191. pAccum->nChar -= n;
  108192. memmove(pAccum->zText, &pAccum->zText[n], pAccum->nChar);
  108193. }
  108194. if( pAccum->nChar==0 ) pAccum->mxAlloc = 0;
  108195. }
  108196. }
  108197. #else
  108198. # define groupConcatInverse 0
  108199. #endif /* SQLITE_OMIT_WINDOWFUNC */
  108200. static void groupConcatFinalize(sqlite3_context *context){
  108201. StrAccum *pAccum;
  108202. pAccum = sqlite3_aggregate_context(context, 0);
  108203. if( pAccum ){
  108204. if( pAccum->accError==SQLITE_TOOBIG ){
  108205. sqlite3_result_error_toobig(context);
  108206. }else if( pAccum->accError==SQLITE_NOMEM ){
  108207. sqlite3_result_error_nomem(context);
  108208. }else{
  108209. sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
  108210. sqlite3_free);
  108211. }
  108212. }
  108213. }
  108214. #ifndef SQLITE_OMIT_WINDOWFUNC
  108215. static void groupConcatValue(sqlite3_context *context){
  108216. sqlite3_str *pAccum;
  108217. pAccum = (sqlite3_str*)sqlite3_aggregate_context(context, 0);
  108218. if( pAccum ){
  108219. if( pAccum->accError==SQLITE_TOOBIG ){
  108220. sqlite3_result_error_toobig(context);
  108221. }else if( pAccum->accError==SQLITE_NOMEM ){
  108222. sqlite3_result_error_nomem(context);
  108223. }else{
  108224. const char *zText = sqlite3_str_value(pAccum);
  108225. sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
  108226. }
  108227. }
  108228. }
  108229. #else
  108230. # define groupConcatValue 0
  108231. #endif /* SQLITE_OMIT_WINDOWFUNC */
  108232. /*
  108233. ** This routine does per-connection function registration. Most
  108234. ** of the built-in functions above are part of the global function set.
  108235. ** This routine only deals with those that are not global.
  108236. */
  108237. SQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3 *db){
  108238. int rc = sqlite3_overload_function(db, "MATCH", 2);
  108239. assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
  108240. if( rc==SQLITE_NOMEM ){
  108241. sqlite3OomFault(db);
  108242. }
  108243. }
  108244. /*
  108245. ** Re-register the built-in LIKE functions. The caseSensitive
  108246. ** parameter determines whether or not the LIKE operator is case
  108247. ** sensitive.
  108248. */
  108249. SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
  108250. struct compareInfo *pInfo;
  108251. int flags;
  108252. if( caseSensitive ){
  108253. pInfo = (struct compareInfo*)&likeInfoAlt;
  108254. flags = SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE;
  108255. }else{
  108256. pInfo = (struct compareInfo*)&likeInfoNorm;
  108257. flags = SQLITE_FUNC_LIKE;
  108258. }
  108259. sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0, 0, 0);
  108260. sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0, 0, 0);
  108261. sqlite3FindFunction(db, "like", 2, SQLITE_UTF8, 0)->funcFlags |= flags;
  108262. sqlite3FindFunction(db, "like", 3, SQLITE_UTF8, 0)->funcFlags |= flags;
  108263. }
  108264. /*
  108265. ** pExpr points to an expression which implements a function. If
  108266. ** it is appropriate to apply the LIKE optimization to that function
  108267. ** then set aWc[0] through aWc[2] to the wildcard characters and the
  108268. ** escape character and then return TRUE. If the function is not a
  108269. ** LIKE-style function then return FALSE.
  108270. **
  108271. ** The expression "a LIKE b ESCAPE c" is only considered a valid LIKE
  108272. ** operator if c is a string literal that is exactly one byte in length.
  108273. ** That one byte is stored in aWc[3]. aWc[3] is set to zero if there is
  108274. ** no ESCAPE clause.
  108275. **
  108276. ** *pIsNocase is set to true if uppercase and lowercase are equivalent for
  108277. ** the function (default for LIKE). If the function makes the distinction
  108278. ** between uppercase and lowercase (as does GLOB) then *pIsNocase is set to
  108279. ** false.
  108280. */
  108281. SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
  108282. FuncDef *pDef;
  108283. int nExpr;
  108284. if( pExpr->op!=TK_FUNCTION || !pExpr->x.pList ){
  108285. return 0;
  108286. }
  108287. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  108288. nExpr = pExpr->x.pList->nExpr;
  108289. pDef = sqlite3FindFunction(db, pExpr->u.zToken, nExpr, SQLITE_UTF8, 0);
  108290. if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){
  108291. return 0;
  108292. }
  108293. if( nExpr<3 ){
  108294. aWc[3] = 0;
  108295. }else{
  108296. Expr *pEscape = pExpr->x.pList->a[2].pExpr;
  108297. char *zEscape;
  108298. if( pEscape->op!=TK_STRING ) return 0;
  108299. zEscape = pEscape->u.zToken;
  108300. if( zEscape[0]==0 || zEscape[1]!=0 ) return 0;
  108301. aWc[3] = zEscape[0];
  108302. }
  108303. /* The memcpy() statement assumes that the wildcard characters are
  108304. ** the first three statements in the compareInfo structure. The
  108305. ** asserts() that follow verify that assumption
  108306. */
  108307. memcpy(aWc, pDef->pUserData, 3);
  108308. assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
  108309. assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
  108310. assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
  108311. *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0;
  108312. return 1;
  108313. }
  108314. /*
  108315. ** All of the FuncDef structures in the aBuiltinFunc[] array above
  108316. ** to the global function hash table. This occurs at start-time (as
  108317. ** a consequence of calling sqlite3_initialize()).
  108318. **
  108319. ** After this routine runs
  108320. */
  108321. SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){
  108322. /*
  108323. ** The following array holds FuncDef structures for all of the functions
  108324. ** defined in this file.
  108325. **
  108326. ** The array cannot be constant since changes are made to the
  108327. ** FuncDef.pHash elements at start-time. The elements of this array
  108328. ** are read-only after initialization is complete.
  108329. **
  108330. ** For peak efficiency, put the most frequently used function last.
  108331. */
  108332. static FuncDef aBuiltinFunc[] = {
  108333. #ifdef SQLITE_SOUNDEX
  108334. FUNCTION(soundex, 1, 0, 0, soundexFunc ),
  108335. #endif
  108336. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  108337. VFUNCTION(load_extension, 1, 0, 0, loadExt ),
  108338. VFUNCTION(load_extension, 2, 0, 0, loadExt ),
  108339. #endif
  108340. #if SQLITE_USER_AUTHENTICATION
  108341. FUNCTION(sqlite_crypt, 2, 0, 0, sqlite3CryptFunc ),
  108342. #endif
  108343. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  108344. DFUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc ),
  108345. DFUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc ),
  108346. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  108347. FUNCTION2(unlikely, 1, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
  108348. FUNCTION2(likelihood, 2, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
  108349. FUNCTION2(likely, 1, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
  108350. #ifdef SQLITE_DEBUG
  108351. FUNCTION2(affinity, 1, 0, 0, noopFunc, SQLITE_FUNC_AFFINITY),
  108352. #endif
  108353. #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
  108354. FUNCTION2(sqlite_offset, 1, 0, 0, noopFunc, SQLITE_FUNC_OFFSET|
  108355. SQLITE_FUNC_TYPEOF),
  108356. #endif
  108357. FUNCTION(ltrim, 1, 1, 0, trimFunc ),
  108358. FUNCTION(ltrim, 2, 1, 0, trimFunc ),
  108359. FUNCTION(rtrim, 1, 2, 0, trimFunc ),
  108360. FUNCTION(rtrim, 2, 2, 0, trimFunc ),
  108361. FUNCTION(trim, 1, 3, 0, trimFunc ),
  108362. FUNCTION(trim, 2, 3, 0, trimFunc ),
  108363. FUNCTION(min, -1, 0, 1, minmaxFunc ),
  108364. FUNCTION(min, 0, 0, 1, 0 ),
  108365. WAGGREGATE(min, 1, 0, 1, minmaxStep, minMaxFinalize, minMaxValue, 0,
  108366. SQLITE_FUNC_MINMAX ),
  108367. FUNCTION(max, -1, 1, 1, minmaxFunc ),
  108368. FUNCTION(max, 0, 1, 1, 0 ),
  108369. WAGGREGATE(max, 1, 1, 1, minmaxStep, minMaxFinalize, minMaxValue, 0,
  108370. SQLITE_FUNC_MINMAX ),
  108371. FUNCTION2(typeof, 1, 0, 0, typeofFunc, SQLITE_FUNC_TYPEOF),
  108372. FUNCTION2(length, 1, 0, 0, lengthFunc, SQLITE_FUNC_LENGTH),
  108373. FUNCTION(instr, 2, 0, 0, instrFunc ),
  108374. FUNCTION(printf, -1, 0, 0, printfFunc ),
  108375. FUNCTION(unicode, 1, 0, 0, unicodeFunc ),
  108376. FUNCTION(char, -1, 0, 0, charFunc ),
  108377. FUNCTION(abs, 1, 0, 0, absFunc ),
  108378. #ifndef SQLITE_OMIT_FLOATING_POINT
  108379. FUNCTION(round, 1, 0, 0, roundFunc ),
  108380. FUNCTION(round, 2, 0, 0, roundFunc ),
  108381. #endif
  108382. FUNCTION(upper, 1, 0, 0, upperFunc ),
  108383. FUNCTION(lower, 1, 0, 0, lowerFunc ),
  108384. FUNCTION(hex, 1, 0, 0, hexFunc ),
  108385. FUNCTION2(ifnull, 2, 0, 0, noopFunc, SQLITE_FUNC_COALESCE),
  108386. VFUNCTION(random, 0, 0, 0, randomFunc ),
  108387. VFUNCTION(randomblob, 1, 0, 0, randomBlob ),
  108388. FUNCTION(nullif, 2, 0, 1, nullifFunc ),
  108389. DFUNCTION(sqlite_version, 0, 0, 0, versionFunc ),
  108390. DFUNCTION(sqlite_source_id, 0, 0, 0, sourceidFunc ),
  108391. FUNCTION(sqlite_log, 2, 0, 0, errlogFunc ),
  108392. FUNCTION(quote, 1, 0, 0, quoteFunc ),
  108393. VFUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
  108394. VFUNCTION(changes, 0, 0, 0, changes ),
  108395. VFUNCTION(total_changes, 0, 0, 0, total_changes ),
  108396. FUNCTION(replace, 3, 0, 0, replaceFunc ),
  108397. FUNCTION(zeroblob, 1, 0, 0, zeroblobFunc ),
  108398. FUNCTION(substr, 2, 0, 0, substrFunc ),
  108399. FUNCTION(substr, 3, 0, 0, substrFunc ),
  108400. WAGGREGATE(sum, 1,0,0, sumStep, sumFinalize, sumFinalize, sumInverse, 0),
  108401. WAGGREGATE(total, 1,0,0, sumStep,totalFinalize,totalFinalize,sumInverse, 0),
  108402. WAGGREGATE(avg, 1,0,0, sumStep, avgFinalize, avgFinalize, sumInverse, 0),
  108403. WAGGREGATE(count, 0,0,0, countStep,
  108404. countFinalize, countFinalize, countInverse, SQLITE_FUNC_COUNT ),
  108405. WAGGREGATE(count, 1,0,0, countStep,
  108406. countFinalize, countFinalize, countInverse, 0 ),
  108407. WAGGREGATE(group_concat, 1, 0, 0, groupConcatStep,
  108408. groupConcatFinalize, groupConcatValue, groupConcatInverse, 0),
  108409. WAGGREGATE(group_concat, 2, 0, 0, groupConcatStep,
  108410. groupConcatFinalize, groupConcatValue, groupConcatInverse, 0),
  108411. LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  108412. #ifdef SQLITE_CASE_SENSITIVE_LIKE
  108413. LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  108414. LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  108415. #else
  108416. LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
  108417. LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
  108418. #endif
  108419. #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
  108420. FUNCTION(unknown, -1, 0, 0, unknownFunc ),
  108421. #endif
  108422. FUNCTION(coalesce, 1, 0, 0, 0 ),
  108423. FUNCTION(coalesce, 0, 0, 0, 0 ),
  108424. FUNCTION2(coalesce, -1, 0, 0, noopFunc, SQLITE_FUNC_COALESCE),
  108425. };
  108426. #ifndef SQLITE_OMIT_ALTERTABLE
  108427. sqlite3AlterFunctions();
  108428. #endif
  108429. sqlite3WindowFunctions();
  108430. #if defined(SQLITE_ENABLE_STAT3) || defined(SQLITE_ENABLE_STAT4)
  108431. sqlite3AnalyzeFunctions();
  108432. #endif
  108433. sqlite3RegisterDateTimeFunctions();
  108434. sqlite3InsertBuiltinFuncs(aBuiltinFunc, ArraySize(aBuiltinFunc));
  108435. #if 0 /* Enable to print out how the built-in functions are hashed */
  108436. {
  108437. int i;
  108438. FuncDef *p;
  108439. for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){
  108440. printf("FUNC-HASH %02d:", i);
  108441. for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash){
  108442. int n = sqlite3Strlen30(p->zName);
  108443. int h = p->zName[0] + n;
  108444. printf(" %s(%d)", p->zName, h);
  108445. }
  108446. printf("\n");
  108447. }
  108448. }
  108449. #endif
  108450. }
  108451. /************** End of func.c ************************************************/
  108452. /************** Begin file fkey.c ********************************************/
  108453. /*
  108454. **
  108455. ** The author disclaims copyright to this source code. In place of
  108456. ** a legal notice, here is a blessing:
  108457. **
  108458. ** May you do good and not evil.
  108459. ** May you find forgiveness for yourself and forgive others.
  108460. ** May you share freely, never taking more than you give.
  108461. **
  108462. *************************************************************************
  108463. ** This file contains code used by the compiler to add foreign key
  108464. ** support to compiled SQL statements.
  108465. */
  108466. /* #include "sqliteInt.h" */
  108467. #ifndef SQLITE_OMIT_FOREIGN_KEY
  108468. #ifndef SQLITE_OMIT_TRIGGER
  108469. /*
  108470. ** Deferred and Immediate FKs
  108471. ** --------------------------
  108472. **
  108473. ** Foreign keys in SQLite come in two flavours: deferred and immediate.
  108474. ** If an immediate foreign key constraint is violated,
  108475. ** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current
  108476. ** statement transaction rolled back. If a
  108477. ** deferred foreign key constraint is violated, no action is taken
  108478. ** immediately. However if the application attempts to commit the
  108479. ** transaction before fixing the constraint violation, the attempt fails.
  108480. **
  108481. ** Deferred constraints are implemented using a simple counter associated
  108482. ** with the database handle. The counter is set to zero each time a
  108483. ** database transaction is opened. Each time a statement is executed
  108484. ** that causes a foreign key violation, the counter is incremented. Each
  108485. ** time a statement is executed that removes an existing violation from
  108486. ** the database, the counter is decremented. When the transaction is
  108487. ** committed, the commit fails if the current value of the counter is
  108488. ** greater than zero. This scheme has two big drawbacks:
  108489. **
  108490. ** * When a commit fails due to a deferred foreign key constraint,
  108491. ** there is no way to tell which foreign constraint is not satisfied,
  108492. ** or which row it is not satisfied for.
  108493. **
  108494. ** * If the database contains foreign key violations when the
  108495. ** transaction is opened, this may cause the mechanism to malfunction.
  108496. **
  108497. ** Despite these problems, this approach is adopted as it seems simpler
  108498. ** than the alternatives.
  108499. **
  108500. ** INSERT operations:
  108501. **
  108502. ** I.1) For each FK for which the table is the child table, search
  108503. ** the parent table for a match. If none is found increment the
  108504. ** constraint counter.
  108505. **
  108506. ** I.2) For each FK for which the table is the parent table,
  108507. ** search the child table for rows that correspond to the new
  108508. ** row in the parent table. Decrement the counter for each row
  108509. ** found (as the constraint is now satisfied).
  108510. **
  108511. ** DELETE operations:
  108512. **
  108513. ** D.1) For each FK for which the table is the child table,
  108514. ** search the parent table for a row that corresponds to the
  108515. ** deleted row in the child table. If such a row is not found,
  108516. ** decrement the counter.
  108517. **
  108518. ** D.2) For each FK for which the table is the parent table, search
  108519. ** the child table for rows that correspond to the deleted row
  108520. ** in the parent table. For each found increment the counter.
  108521. **
  108522. ** UPDATE operations:
  108523. **
  108524. ** An UPDATE command requires that all 4 steps above are taken, but only
  108525. ** for FK constraints for which the affected columns are actually
  108526. ** modified (values must be compared at runtime).
  108527. **
  108528. ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
  108529. ** This simplifies the implementation a bit.
  108530. **
  108531. ** For the purposes of immediate FK constraints, the OR REPLACE conflict
  108532. ** resolution is considered to delete rows before the new row is inserted.
  108533. ** If a delete caused by OR REPLACE violates an FK constraint, an exception
  108534. ** is thrown, even if the FK constraint would be satisfied after the new
  108535. ** row is inserted.
  108536. **
  108537. ** Immediate constraints are usually handled similarly. The only difference
  108538. ** is that the counter used is stored as part of each individual statement
  108539. ** object (struct Vdbe). If, after the statement has run, its immediate
  108540. ** constraint counter is greater than zero,
  108541. ** it returns SQLITE_CONSTRAINT_FOREIGNKEY
  108542. ** and the statement transaction is rolled back. An exception is an INSERT
  108543. ** statement that inserts a single row only (no triggers). In this case,
  108544. ** instead of using a counter, an exception is thrown immediately if the
  108545. ** INSERT violates a foreign key constraint. This is necessary as such
  108546. ** an INSERT does not open a statement transaction.
  108547. **
  108548. ** TODO: How should dropping a table be handled? How should renaming a
  108549. ** table be handled?
  108550. **
  108551. **
  108552. ** Query API Notes
  108553. ** ---------------
  108554. **
  108555. ** Before coding an UPDATE or DELETE row operation, the code-generator
  108556. ** for those two operations needs to know whether or not the operation
  108557. ** requires any FK processing and, if so, which columns of the original
  108558. ** row are required by the FK processing VDBE code (i.e. if FKs were
  108559. ** implemented using triggers, which of the old.* columns would be
  108560. ** accessed). No information is required by the code-generator before
  108561. ** coding an INSERT operation. The functions used by the UPDATE/DELETE
  108562. ** generation code to query for this information are:
  108563. **
  108564. ** sqlite3FkRequired() - Test to see if FK processing is required.
  108565. ** sqlite3FkOldmask() - Query for the set of required old.* columns.
  108566. **
  108567. **
  108568. ** Externally accessible module functions
  108569. ** --------------------------------------
  108570. **
  108571. ** sqlite3FkCheck() - Check for foreign key violations.
  108572. ** sqlite3FkActions() - Code triggers for ON UPDATE/ON DELETE actions.
  108573. ** sqlite3FkDelete() - Delete an FKey structure.
  108574. */
  108575. /*
  108576. ** VDBE Calling Convention
  108577. ** -----------------------
  108578. **
  108579. ** Example:
  108580. **
  108581. ** For the following INSERT statement:
  108582. **
  108583. ** CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
  108584. ** INSERT INTO t1 VALUES(1, 2, 3.1);
  108585. **
  108586. ** Register (x): 2 (type integer)
  108587. ** Register (x+1): 1 (type integer)
  108588. ** Register (x+2): NULL (type NULL)
  108589. ** Register (x+3): 3.1 (type real)
  108590. */
  108591. /*
  108592. ** A foreign key constraint requires that the key columns in the parent
  108593. ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
  108594. ** Given that pParent is the parent table for foreign key constraint pFKey,
  108595. ** search the schema for a unique index on the parent key columns.
  108596. **
  108597. ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
  108598. ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
  108599. ** is set to point to the unique index.
  108600. **
  108601. ** If the parent key consists of a single column (the foreign key constraint
  108602. ** is not a composite foreign key), output variable *paiCol is set to NULL.
  108603. ** Otherwise, it is set to point to an allocated array of size N, where
  108604. ** N is the number of columns in the parent key. The first element of the
  108605. ** array is the index of the child table column that is mapped by the FK
  108606. ** constraint to the parent table column stored in the left-most column
  108607. ** of index *ppIdx. The second element of the array is the index of the
  108608. ** child table column that corresponds to the second left-most column of
  108609. ** *ppIdx, and so on.
  108610. **
  108611. ** If the required index cannot be found, either because:
  108612. **
  108613. ** 1) The named parent key columns do not exist, or
  108614. **
  108615. ** 2) The named parent key columns do exist, but are not subject to a
  108616. ** UNIQUE or PRIMARY KEY constraint, or
  108617. **
  108618. ** 3) No parent key columns were provided explicitly as part of the
  108619. ** foreign key definition, and the parent table does not have a
  108620. ** PRIMARY KEY, or
  108621. **
  108622. ** 4) No parent key columns were provided explicitly as part of the
  108623. ** foreign key definition, and the PRIMARY KEY of the parent table
  108624. ** consists of a different number of columns to the child key in
  108625. ** the child table.
  108626. **
  108627. ** then non-zero is returned, and a "foreign key mismatch" error loaded
  108628. ** into pParse. If an OOM error occurs, non-zero is returned and the
  108629. ** pParse->db->mallocFailed flag is set.
  108630. */
  108631. SQLITE_PRIVATE int sqlite3FkLocateIndex(
  108632. Parse *pParse, /* Parse context to store any error in */
  108633. Table *pParent, /* Parent table of FK constraint pFKey */
  108634. FKey *pFKey, /* Foreign key to find index for */
  108635. Index **ppIdx, /* OUT: Unique index on parent table */
  108636. int **paiCol /* OUT: Map of index columns in pFKey */
  108637. ){
  108638. Index *pIdx = 0; /* Value to return via *ppIdx */
  108639. int *aiCol = 0; /* Value to return via *paiCol */
  108640. int nCol = pFKey->nCol; /* Number of columns in parent key */
  108641. char *zKey = pFKey->aCol[0].zCol; /* Name of left-most parent key column */
  108642. /* The caller is responsible for zeroing output parameters. */
  108643. assert( ppIdx && *ppIdx==0 );
  108644. assert( !paiCol || *paiCol==0 );
  108645. assert( pParse );
  108646. /* If this is a non-composite (single column) foreign key, check if it
  108647. ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
  108648. ** and *paiCol set to zero and return early.
  108649. **
  108650. ** Otherwise, for a composite foreign key (more than one column), allocate
  108651. ** space for the aiCol array (returned via output parameter *paiCol).
  108652. ** Non-composite foreign keys do not require the aiCol array.
  108653. */
  108654. if( nCol==1 ){
  108655. /* The FK maps to the IPK if any of the following are true:
  108656. **
  108657. ** 1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
  108658. ** mapped to the primary key of table pParent, or
  108659. ** 2) The FK is explicitly mapped to a column declared as INTEGER
  108660. ** PRIMARY KEY.
  108661. */
  108662. if( pParent->iPKey>=0 ){
  108663. if( !zKey ) return 0;
  108664. if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
  108665. }
  108666. }else if( paiCol ){
  108667. assert( nCol>1 );
  108668. aiCol = (int *)sqlite3DbMallocRawNN(pParse->db, nCol*sizeof(int));
  108669. if( !aiCol ) return 1;
  108670. *paiCol = aiCol;
  108671. }
  108672. for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
  108673. if( pIdx->nKeyCol==nCol && IsUniqueIndex(pIdx) && pIdx->pPartIdxWhere==0 ){
  108674. /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
  108675. ** of columns. If each indexed column corresponds to a foreign key
  108676. ** column of pFKey, then this index is a winner. */
  108677. if( zKey==0 ){
  108678. /* If zKey is NULL, then this foreign key is implicitly mapped to
  108679. ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
  108680. ** identified by the test. */
  108681. if( IsPrimaryKeyIndex(pIdx) ){
  108682. if( aiCol ){
  108683. int i;
  108684. for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
  108685. }
  108686. break;
  108687. }
  108688. }else{
  108689. /* If zKey is non-NULL, then this foreign key was declared to
  108690. ** map to an explicit list of columns in table pParent. Check if this
  108691. ** index matches those columns. Also, check that the index uses
  108692. ** the default collation sequences for each column. */
  108693. int i, j;
  108694. for(i=0; i<nCol; i++){
  108695. i16 iCol = pIdx->aiColumn[i]; /* Index of column in parent tbl */
  108696. const char *zDfltColl; /* Def. collation for column */
  108697. char *zIdxCol; /* Name of indexed column */
  108698. if( iCol<0 ) break; /* No foreign keys against expression indexes */
  108699. /* If the index uses a collation sequence that is different from
  108700. ** the default collation sequence for the column, this index is
  108701. ** unusable. Bail out early in this case. */
  108702. zDfltColl = pParent->aCol[iCol].zColl;
  108703. if( !zDfltColl ) zDfltColl = sqlite3StrBINARY;
  108704. if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
  108705. zIdxCol = pParent->aCol[iCol].zName;
  108706. for(j=0; j<nCol; j++){
  108707. if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
  108708. if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
  108709. break;
  108710. }
  108711. }
  108712. if( j==nCol ) break;
  108713. }
  108714. if( i==nCol ) break; /* pIdx is usable */
  108715. }
  108716. }
  108717. }
  108718. if( !pIdx ){
  108719. if( !pParse->disableTriggers ){
  108720. sqlite3ErrorMsg(pParse,
  108721. "foreign key mismatch - \"%w\" referencing \"%w\"",
  108722. pFKey->pFrom->zName, pFKey->zTo);
  108723. }
  108724. sqlite3DbFree(pParse->db, aiCol);
  108725. return 1;
  108726. }
  108727. *ppIdx = pIdx;
  108728. return 0;
  108729. }
  108730. /*
  108731. ** This function is called when a row is inserted into or deleted from the
  108732. ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
  108733. ** on the child table of pFKey, this function is invoked twice for each row
  108734. ** affected - once to "delete" the old row, and then again to "insert" the
  108735. ** new row.
  108736. **
  108737. ** Each time it is called, this function generates VDBE code to locate the
  108738. ** row in the parent table that corresponds to the row being inserted into
  108739. ** or deleted from the child table. If the parent row can be found, no
  108740. ** special action is taken. Otherwise, if the parent row can *not* be
  108741. ** found in the parent table:
  108742. **
  108743. ** Operation | FK type | Action taken
  108744. ** --------------------------------------------------------------------------
  108745. ** INSERT immediate Increment the "immediate constraint counter".
  108746. **
  108747. ** DELETE immediate Decrement the "immediate constraint counter".
  108748. **
  108749. ** INSERT deferred Increment the "deferred constraint counter".
  108750. **
  108751. ** DELETE deferred Decrement the "deferred constraint counter".
  108752. **
  108753. ** These operations are identified in the comment at the top of this file
  108754. ** (fkey.c) as "I.1" and "D.1".
  108755. */
  108756. static void fkLookupParent(
  108757. Parse *pParse, /* Parse context */
  108758. int iDb, /* Index of database housing pTab */
  108759. Table *pTab, /* Parent table of FK pFKey */
  108760. Index *pIdx, /* Unique index on parent key columns in pTab */
  108761. FKey *pFKey, /* Foreign key constraint */
  108762. int *aiCol, /* Map from parent key columns to child table columns */
  108763. int regData, /* Address of array containing child table row */
  108764. int nIncr, /* Increment constraint counter by this */
  108765. int isIgnore /* If true, pretend pTab contains all NULL values */
  108766. ){
  108767. int i; /* Iterator variable */
  108768. Vdbe *v = sqlite3GetVdbe(pParse); /* Vdbe to add code to */
  108769. int iCur = pParse->nTab - 1; /* Cursor number to use */
  108770. int iOk = sqlite3VdbeMakeLabel(pParse); /* jump here if parent key found */
  108771. sqlite3VdbeVerifyAbortable(v,
  108772. (!pFKey->isDeferred
  108773. && !(pParse->db->flags & SQLITE_DeferFKs)
  108774. && !pParse->pToplevel
  108775. && !pParse->isMultiWrite) ? OE_Abort : OE_Ignore);
  108776. /* If nIncr is less than zero, then check at runtime if there are any
  108777. ** outstanding constraints to resolve. If there are not, there is no need
  108778. ** to check if deleting this row resolves any outstanding violations.
  108779. **
  108780. ** Check if any of the key columns in the child table row are NULL. If
  108781. ** any are, then the constraint is considered satisfied. No need to
  108782. ** search for a matching row in the parent table. */
  108783. if( nIncr<0 ){
  108784. sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
  108785. VdbeCoverage(v);
  108786. }
  108787. for(i=0; i<pFKey->nCol; i++){
  108788. int iReg = aiCol[i] + regData + 1;
  108789. sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk); VdbeCoverage(v);
  108790. }
  108791. if( isIgnore==0 ){
  108792. if( pIdx==0 ){
  108793. /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
  108794. ** column of the parent table (table pTab). */
  108795. int iMustBeInt; /* Address of MustBeInt instruction */
  108796. int regTemp = sqlite3GetTempReg(pParse);
  108797. /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
  108798. ** apply the affinity of the parent key). If this fails, then there
  108799. ** is no matching parent key. Before using MustBeInt, make a copy of
  108800. ** the value. Otherwise, the value inserted into the child key column
  108801. ** will have INTEGER affinity applied to it, which may not be correct. */
  108802. sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
  108803. iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
  108804. VdbeCoverage(v);
  108805. /* If the parent table is the same as the child table, and we are about
  108806. ** to increment the constraint-counter (i.e. this is an INSERT operation),
  108807. ** then check if the row being inserted matches itself. If so, do not
  108808. ** increment the constraint-counter. */
  108809. if( pTab==pFKey->pFrom && nIncr==1 ){
  108810. sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp); VdbeCoverage(v);
  108811. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  108812. }
  108813. sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
  108814. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp); VdbeCoverage(v);
  108815. sqlite3VdbeGoto(v, iOk);
  108816. sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
  108817. sqlite3VdbeJumpHere(v, iMustBeInt);
  108818. sqlite3ReleaseTempReg(pParse, regTemp);
  108819. }else{
  108820. int nCol = pFKey->nCol;
  108821. int regTemp = sqlite3GetTempRange(pParse, nCol);
  108822. int regRec = sqlite3GetTempReg(pParse);
  108823. sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
  108824. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  108825. for(i=0; i<nCol; i++){
  108826. sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
  108827. }
  108828. /* If the parent table is the same as the child table, and we are about
  108829. ** to increment the constraint-counter (i.e. this is an INSERT operation),
  108830. ** then check if the row being inserted matches itself. If so, do not
  108831. ** increment the constraint-counter.
  108832. **
  108833. ** If any of the parent-key values are NULL, then the row cannot match
  108834. ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
  108835. ** of the parent-key values are NULL (at this point it is known that
  108836. ** none of the child key values are).
  108837. */
  108838. if( pTab==pFKey->pFrom && nIncr==1 ){
  108839. int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
  108840. for(i=0; i<nCol; i++){
  108841. int iChild = aiCol[i]+1+regData;
  108842. int iParent = pIdx->aiColumn[i]+1+regData;
  108843. assert( pIdx->aiColumn[i]>=0 );
  108844. assert( aiCol[i]!=pTab->iPKey );
  108845. if( pIdx->aiColumn[i]==pTab->iPKey ){
  108846. /* The parent key is a composite key that includes the IPK column */
  108847. iParent = regData;
  108848. }
  108849. sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent); VdbeCoverage(v);
  108850. sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
  108851. }
  108852. sqlite3VdbeGoto(v, iOk);
  108853. }
  108854. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTemp, nCol, regRec,
  108855. sqlite3IndexAffinityStr(pParse->db,pIdx), nCol);
  108856. sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0); VdbeCoverage(v);
  108857. sqlite3ReleaseTempReg(pParse, regRec);
  108858. sqlite3ReleaseTempRange(pParse, regTemp, nCol);
  108859. }
  108860. }
  108861. if( !pFKey->isDeferred && !(pParse->db->flags & SQLITE_DeferFKs)
  108862. && !pParse->pToplevel
  108863. && !pParse->isMultiWrite
  108864. ){
  108865. /* Special case: If this is an INSERT statement that will insert exactly
  108866. ** one row into the table, raise a constraint immediately instead of
  108867. ** incrementing a counter. This is necessary as the VM code is being
  108868. ** generated for will not open a statement transaction. */
  108869. assert( nIncr==1 );
  108870. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
  108871. OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
  108872. }else{
  108873. if( nIncr>0 && pFKey->isDeferred==0 ){
  108874. sqlite3MayAbort(pParse);
  108875. }
  108876. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
  108877. }
  108878. sqlite3VdbeResolveLabel(v, iOk);
  108879. sqlite3VdbeAddOp1(v, OP_Close, iCur);
  108880. }
  108881. /*
  108882. ** Return an Expr object that refers to a memory register corresponding
  108883. ** to column iCol of table pTab.
  108884. **
  108885. ** regBase is the first of an array of register that contains the data
  108886. ** for pTab. regBase itself holds the rowid. regBase+1 holds the first
  108887. ** column. regBase+2 holds the second column, and so forth.
  108888. */
  108889. static Expr *exprTableRegister(
  108890. Parse *pParse, /* Parsing and code generating context */
  108891. Table *pTab, /* The table whose content is at r[regBase]... */
  108892. int regBase, /* Contents of table pTab */
  108893. i16 iCol /* Which column of pTab is desired */
  108894. ){
  108895. Expr *pExpr;
  108896. Column *pCol;
  108897. const char *zColl;
  108898. sqlite3 *db = pParse->db;
  108899. pExpr = sqlite3Expr(db, TK_REGISTER, 0);
  108900. if( pExpr ){
  108901. if( iCol>=0 && iCol!=pTab->iPKey ){
  108902. pCol = &pTab->aCol[iCol];
  108903. pExpr->iTable = regBase + iCol + 1;
  108904. pExpr->affinity = pCol->affinity;
  108905. zColl = pCol->zColl;
  108906. if( zColl==0 ) zColl = db->pDfltColl->zName;
  108907. pExpr = sqlite3ExprAddCollateString(pParse, pExpr, zColl);
  108908. }else{
  108909. pExpr->iTable = regBase;
  108910. pExpr->affinity = SQLITE_AFF_INTEGER;
  108911. }
  108912. }
  108913. return pExpr;
  108914. }
  108915. /*
  108916. ** Return an Expr object that refers to column iCol of table pTab which
  108917. ** has cursor iCur.
  108918. */
  108919. static Expr *exprTableColumn(
  108920. sqlite3 *db, /* The database connection */
  108921. Table *pTab, /* The table whose column is desired */
  108922. int iCursor, /* The open cursor on the table */
  108923. i16 iCol /* The column that is wanted */
  108924. ){
  108925. Expr *pExpr = sqlite3Expr(db, TK_COLUMN, 0);
  108926. if( pExpr ){
  108927. pExpr->y.pTab = pTab;
  108928. pExpr->iTable = iCursor;
  108929. pExpr->iColumn = iCol;
  108930. }
  108931. return pExpr;
  108932. }
  108933. /*
  108934. ** This function is called to generate code executed when a row is deleted
  108935. ** from the parent table of foreign key constraint pFKey and, if pFKey is
  108936. ** deferred, when a row is inserted into the same table. When generating
  108937. ** code for an SQL UPDATE operation, this function may be called twice -
  108938. ** once to "delete" the old row and once to "insert" the new row.
  108939. **
  108940. ** Parameter nIncr is passed -1 when inserting a row (as this may decrease
  108941. ** the number of FK violations in the db) or +1 when deleting one (as this
  108942. ** may increase the number of FK constraint problems).
  108943. **
  108944. ** The code generated by this function scans through the rows in the child
  108945. ** table that correspond to the parent table row being deleted or inserted.
  108946. ** For each child row found, one of the following actions is taken:
  108947. **
  108948. ** Operation | FK type | Action taken
  108949. ** --------------------------------------------------------------------------
  108950. ** DELETE immediate Increment the "immediate constraint counter".
  108951. ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
  108952. ** throw a "FOREIGN KEY constraint failed" exception.
  108953. **
  108954. ** INSERT immediate Decrement the "immediate constraint counter".
  108955. **
  108956. ** DELETE deferred Increment the "deferred constraint counter".
  108957. ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
  108958. ** throw a "FOREIGN KEY constraint failed" exception.
  108959. **
  108960. ** INSERT deferred Decrement the "deferred constraint counter".
  108961. **
  108962. ** These operations are identified in the comment at the top of this file
  108963. ** (fkey.c) as "I.2" and "D.2".
  108964. */
  108965. static void fkScanChildren(
  108966. Parse *pParse, /* Parse context */
  108967. SrcList *pSrc, /* The child table to be scanned */
  108968. Table *pTab, /* The parent table */
  108969. Index *pIdx, /* Index on parent covering the foreign key */
  108970. FKey *pFKey, /* The foreign key linking pSrc to pTab */
  108971. int *aiCol, /* Map from pIdx cols to child table cols */
  108972. int regData, /* Parent row data starts here */
  108973. int nIncr /* Amount to increment deferred counter by */
  108974. ){
  108975. sqlite3 *db = pParse->db; /* Database handle */
  108976. int i; /* Iterator variable */
  108977. Expr *pWhere = 0; /* WHERE clause to scan with */
  108978. NameContext sNameContext; /* Context used to resolve WHERE clause */
  108979. WhereInfo *pWInfo; /* Context used by sqlite3WhereXXX() */
  108980. int iFkIfZero = 0; /* Address of OP_FkIfZero */
  108981. Vdbe *v = sqlite3GetVdbe(pParse);
  108982. assert( pIdx==0 || pIdx->pTable==pTab );
  108983. assert( pIdx==0 || pIdx->nKeyCol==pFKey->nCol );
  108984. assert( pIdx!=0 || pFKey->nCol==1 );
  108985. assert( pIdx!=0 || HasRowid(pTab) );
  108986. if( nIncr<0 ){
  108987. iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
  108988. VdbeCoverage(v);
  108989. }
  108990. /* Create an Expr object representing an SQL expression like:
  108991. **
  108992. ** <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
  108993. **
  108994. ** The collation sequence used for the comparison should be that of
  108995. ** the parent key columns. The affinity of the parent key column should
  108996. ** be applied to each child key value before the comparison takes place.
  108997. */
  108998. for(i=0; i<pFKey->nCol; i++){
  108999. Expr *pLeft; /* Value from parent table row */
  109000. Expr *pRight; /* Column ref to child table */
  109001. Expr *pEq; /* Expression (pLeft = pRight) */
  109002. i16 iCol; /* Index of column in child table */
  109003. const char *zCol; /* Name of column in child table */
  109004. iCol = pIdx ? pIdx->aiColumn[i] : -1;
  109005. pLeft = exprTableRegister(pParse, pTab, regData, iCol);
  109006. iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
  109007. assert( iCol>=0 );
  109008. zCol = pFKey->pFrom->aCol[iCol].zName;
  109009. pRight = sqlite3Expr(db, TK_ID, zCol);
  109010. pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight);
  109011. pWhere = sqlite3ExprAnd(pParse, pWhere, pEq);
  109012. }
  109013. /* If the child table is the same as the parent table, then add terms
  109014. ** to the WHERE clause that prevent this entry from being scanned.
  109015. ** The added WHERE clause terms are like this:
  109016. **
  109017. ** $current_rowid!=rowid
  109018. ** NOT( $current_a==a AND $current_b==b AND ... )
  109019. **
  109020. ** The first form is used for rowid tables. The second form is used
  109021. ** for WITHOUT ROWID tables. In the second form, the *parent* key is
  109022. ** (a,b,...). Either the parent or primary key could be used to
  109023. ** uniquely identify the current row, but the parent key is more convenient
  109024. ** as the required values have already been loaded into registers
  109025. ** by the caller.
  109026. */
  109027. if( pTab==pFKey->pFrom && nIncr>0 ){
  109028. Expr *pNe; /* Expression (pLeft != pRight) */
  109029. Expr *pLeft; /* Value from parent table row */
  109030. Expr *pRight; /* Column ref to child table */
  109031. if( HasRowid(pTab) ){
  109032. pLeft = exprTableRegister(pParse, pTab, regData, -1);
  109033. pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, -1);
  109034. pNe = sqlite3PExpr(pParse, TK_NE, pLeft, pRight);
  109035. }else{
  109036. Expr *pEq, *pAll = 0;
  109037. assert( pIdx!=0 );
  109038. for(i=0; i<pIdx->nKeyCol; i++){
  109039. i16 iCol = pIdx->aiColumn[i];
  109040. assert( iCol>=0 );
  109041. pLeft = exprTableRegister(pParse, pTab, regData, iCol);
  109042. pRight = sqlite3Expr(db, TK_ID, pTab->aCol[iCol].zName);
  109043. pEq = sqlite3PExpr(pParse, TK_IS, pLeft, pRight);
  109044. pAll = sqlite3ExprAnd(pParse, pAll, pEq);
  109045. }
  109046. pNe = sqlite3PExpr(pParse, TK_NOT, pAll, 0);
  109047. }
  109048. pWhere = sqlite3ExprAnd(pParse, pWhere, pNe);
  109049. }
  109050. /* Resolve the references in the WHERE clause. */
  109051. memset(&sNameContext, 0, sizeof(NameContext));
  109052. sNameContext.pSrcList = pSrc;
  109053. sNameContext.pParse = pParse;
  109054. sqlite3ResolveExprNames(&sNameContext, pWhere);
  109055. /* Create VDBE to loop through the entries in pSrc that match the WHERE
  109056. ** clause. For each row found, increment either the deferred or immediate
  109057. ** foreign key constraint counter. */
  109058. if( pParse->nErr==0 ){
  109059. pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0);
  109060. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
  109061. if( pWInfo ){
  109062. sqlite3WhereEnd(pWInfo);
  109063. }
  109064. }
  109065. /* Clean up the WHERE clause constructed above. */
  109066. sqlite3ExprDelete(db, pWhere);
  109067. if( iFkIfZero ){
  109068. sqlite3VdbeJumpHere(v, iFkIfZero);
  109069. }
  109070. }
  109071. /*
  109072. ** This function returns a linked list of FKey objects (connected by
  109073. ** FKey.pNextTo) holding all children of table pTab. For example,
  109074. ** given the following schema:
  109075. **
  109076. ** CREATE TABLE t1(a PRIMARY KEY);
  109077. ** CREATE TABLE t2(b REFERENCES t1(a);
  109078. **
  109079. ** Calling this function with table "t1" as an argument returns a pointer
  109080. ** to the FKey structure representing the foreign key constraint on table
  109081. ** "t2". Calling this function with "t2" as the argument would return a
  109082. ** NULL pointer (as there are no FK constraints for which t2 is the parent
  109083. ** table).
  109084. */
  109085. SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
  109086. return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName);
  109087. }
  109088. /*
  109089. ** The second argument is a Trigger structure allocated by the
  109090. ** fkActionTrigger() routine. This function deletes the Trigger structure
  109091. ** and all of its sub-components.
  109092. **
  109093. ** The Trigger structure or any of its sub-components may be allocated from
  109094. ** the lookaside buffer belonging to database handle dbMem.
  109095. */
  109096. static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
  109097. if( p ){
  109098. TriggerStep *pStep = p->step_list;
  109099. sqlite3ExprDelete(dbMem, pStep->pWhere);
  109100. sqlite3ExprListDelete(dbMem, pStep->pExprList);
  109101. sqlite3SelectDelete(dbMem, pStep->pSelect);
  109102. sqlite3ExprDelete(dbMem, p->pWhen);
  109103. sqlite3DbFree(dbMem, p);
  109104. }
  109105. }
  109106. /*
  109107. ** This function is called to generate code that runs when table pTab is
  109108. ** being dropped from the database. The SrcList passed as the second argument
  109109. ** to this function contains a single entry guaranteed to resolve to
  109110. ** table pTab.
  109111. **
  109112. ** Normally, no code is required. However, if either
  109113. **
  109114. ** (a) The table is the parent table of a FK constraint, or
  109115. ** (b) The table is the child table of a deferred FK constraint and it is
  109116. ** determined at runtime that there are outstanding deferred FK
  109117. ** constraint violations in the database,
  109118. **
  109119. ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
  109120. ** the table from the database. Triggers are disabled while running this
  109121. ** DELETE, but foreign key actions are not.
  109122. */
  109123. SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
  109124. sqlite3 *db = pParse->db;
  109125. if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) ){
  109126. int iSkip = 0;
  109127. Vdbe *v = sqlite3GetVdbe(pParse);
  109128. assert( v ); /* VDBE has already been allocated */
  109129. assert( pTab->pSelect==0 ); /* Not a view */
  109130. if( sqlite3FkReferences(pTab)==0 ){
  109131. /* Search for a deferred foreign key constraint for which this table
  109132. ** is the child table. If one cannot be found, return without
  109133. ** generating any VDBE code. If one can be found, then jump over
  109134. ** the entire DELETE if there are no outstanding deferred constraints
  109135. ** when this statement is run. */
  109136. FKey *p;
  109137. for(p=pTab->pFKey; p; p=p->pNextFrom){
  109138. if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break;
  109139. }
  109140. if( !p ) return;
  109141. iSkip = sqlite3VdbeMakeLabel(pParse);
  109142. sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip); VdbeCoverage(v);
  109143. }
  109144. pParse->disableTriggers = 1;
  109145. sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0, 0, 0);
  109146. pParse->disableTriggers = 0;
  109147. /* If the DELETE has generated immediate foreign key constraint
  109148. ** violations, halt the VDBE and return an error at this point, before
  109149. ** any modifications to the schema are made. This is because statement
  109150. ** transactions are not able to rollback schema changes.
  109151. **
  109152. ** If the SQLITE_DeferFKs flag is set, then this is not required, as
  109153. ** the statement transaction will not be rolled back even if FK
  109154. ** constraints are violated.
  109155. */
  109156. if( (db->flags & SQLITE_DeferFKs)==0 ){
  109157. sqlite3VdbeVerifyAbortable(v, OE_Abort);
  109158. sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
  109159. VdbeCoverage(v);
  109160. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
  109161. OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
  109162. }
  109163. if( iSkip ){
  109164. sqlite3VdbeResolveLabel(v, iSkip);
  109165. }
  109166. }
  109167. }
  109168. /*
  109169. ** The second argument points to an FKey object representing a foreign key
  109170. ** for which pTab is the child table. An UPDATE statement against pTab
  109171. ** is currently being processed. For each column of the table that is
  109172. ** actually updated, the corresponding element in the aChange[] array
  109173. ** is zero or greater (if a column is unmodified the corresponding element
  109174. ** is set to -1). If the rowid column is modified by the UPDATE statement
  109175. ** the bChngRowid argument is non-zero.
  109176. **
  109177. ** This function returns true if any of the columns that are part of the
  109178. ** child key for FK constraint *p are modified.
  109179. */
  109180. static int fkChildIsModified(
  109181. Table *pTab, /* Table being updated */
  109182. FKey *p, /* Foreign key for which pTab is the child */
  109183. int *aChange, /* Array indicating modified columns */
  109184. int bChngRowid /* True if rowid is modified by this update */
  109185. ){
  109186. int i;
  109187. for(i=0; i<p->nCol; i++){
  109188. int iChildKey = p->aCol[i].iFrom;
  109189. if( aChange[iChildKey]>=0 ) return 1;
  109190. if( iChildKey==pTab->iPKey && bChngRowid ) return 1;
  109191. }
  109192. return 0;
  109193. }
  109194. /*
  109195. ** The second argument points to an FKey object representing a foreign key
  109196. ** for which pTab is the parent table. An UPDATE statement against pTab
  109197. ** is currently being processed. For each column of the table that is
  109198. ** actually updated, the corresponding element in the aChange[] array
  109199. ** is zero or greater (if a column is unmodified the corresponding element
  109200. ** is set to -1). If the rowid column is modified by the UPDATE statement
  109201. ** the bChngRowid argument is non-zero.
  109202. **
  109203. ** This function returns true if any of the columns that are part of the
  109204. ** parent key for FK constraint *p are modified.
  109205. */
  109206. static int fkParentIsModified(
  109207. Table *pTab,
  109208. FKey *p,
  109209. int *aChange,
  109210. int bChngRowid
  109211. ){
  109212. int i;
  109213. for(i=0; i<p->nCol; i++){
  109214. char *zKey = p->aCol[i].zCol;
  109215. int iKey;
  109216. for(iKey=0; iKey<pTab->nCol; iKey++){
  109217. if( aChange[iKey]>=0 || (iKey==pTab->iPKey && bChngRowid) ){
  109218. Column *pCol = &pTab->aCol[iKey];
  109219. if( zKey ){
  109220. if( 0==sqlite3StrICmp(pCol->zName, zKey) ) return 1;
  109221. }else if( pCol->colFlags & COLFLAG_PRIMKEY ){
  109222. return 1;
  109223. }
  109224. }
  109225. }
  109226. }
  109227. return 0;
  109228. }
  109229. /*
  109230. ** Return true if the parser passed as the first argument is being
  109231. ** used to code a trigger that is really a "SET NULL" action belonging
  109232. ** to trigger pFKey.
  109233. */
  109234. static int isSetNullAction(Parse *pParse, FKey *pFKey){
  109235. Parse *pTop = sqlite3ParseToplevel(pParse);
  109236. if( pTop->pTriggerPrg ){
  109237. Trigger *p = pTop->pTriggerPrg->pTrigger;
  109238. if( (p==pFKey->apTrigger[0] && pFKey->aAction[0]==OE_SetNull)
  109239. || (p==pFKey->apTrigger[1] && pFKey->aAction[1]==OE_SetNull)
  109240. ){
  109241. return 1;
  109242. }
  109243. }
  109244. return 0;
  109245. }
  109246. /*
  109247. ** This function is called when inserting, deleting or updating a row of
  109248. ** table pTab to generate VDBE code to perform foreign key constraint
  109249. ** processing for the operation.
  109250. **
  109251. ** For a DELETE operation, parameter regOld is passed the index of the
  109252. ** first register in an array of (pTab->nCol+1) registers containing the
  109253. ** rowid of the row being deleted, followed by each of the column values
  109254. ** of the row being deleted, from left to right. Parameter regNew is passed
  109255. ** zero in this case.
  109256. **
  109257. ** For an INSERT operation, regOld is passed zero and regNew is passed the
  109258. ** first register of an array of (pTab->nCol+1) registers containing the new
  109259. ** row data.
  109260. **
  109261. ** For an UPDATE operation, this function is called twice. Once before
  109262. ** the original record is deleted from the table using the calling convention
  109263. ** described for DELETE. Then again after the original record is deleted
  109264. ** but before the new record is inserted using the INSERT convention.
  109265. */
  109266. SQLITE_PRIVATE void sqlite3FkCheck(
  109267. Parse *pParse, /* Parse context */
  109268. Table *pTab, /* Row is being deleted from this table */
  109269. int regOld, /* Previous row data is stored here */
  109270. int regNew, /* New row data is stored here */
  109271. int *aChange, /* Array indicating UPDATEd columns (or 0) */
  109272. int bChngRowid /* True if rowid is UPDATEd */
  109273. ){
  109274. sqlite3 *db = pParse->db; /* Database handle */
  109275. FKey *pFKey; /* Used to iterate through FKs */
  109276. int iDb; /* Index of database containing pTab */
  109277. const char *zDb; /* Name of database containing pTab */
  109278. int isIgnoreErrors = pParse->disableTriggers;
  109279. /* Exactly one of regOld and regNew should be non-zero. */
  109280. assert( (regOld==0)!=(regNew==0) );
  109281. /* If foreign-keys are disabled, this function is a no-op. */
  109282. if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
  109283. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  109284. zDb = db->aDb[iDb].zDbSName;
  109285. /* Loop through all the foreign key constraints for which pTab is the
  109286. ** child table (the table that the foreign key definition is part of). */
  109287. for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
  109288. Table *pTo; /* Parent table of foreign key pFKey */
  109289. Index *pIdx = 0; /* Index on key columns in pTo */
  109290. int *aiFree = 0;
  109291. int *aiCol;
  109292. int iCol;
  109293. int i;
  109294. int bIgnore = 0;
  109295. if( aChange
  109296. && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0
  109297. && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0
  109298. ){
  109299. continue;
  109300. }
  109301. /* Find the parent table of this foreign key. Also find a unique index
  109302. ** on the parent key columns in the parent table. If either of these
  109303. ** schema items cannot be located, set an error in pParse and return
  109304. ** early. */
  109305. if( pParse->disableTriggers ){
  109306. pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
  109307. }else{
  109308. pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
  109309. }
  109310. if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
  109311. assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
  109312. if( !isIgnoreErrors || db->mallocFailed ) return;
  109313. if( pTo==0 ){
  109314. /* If isIgnoreErrors is true, then a table is being dropped. In this
  109315. ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
  109316. ** before actually dropping it in order to check FK constraints.
  109317. ** If the parent table of an FK constraint on the current table is
  109318. ** missing, behave as if it is empty. i.e. decrement the relevant
  109319. ** FK counter for each row of the current table with non-NULL keys.
  109320. */
  109321. Vdbe *v = sqlite3GetVdbe(pParse);
  109322. int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
  109323. for(i=0; i<pFKey->nCol; i++){
  109324. int iReg = pFKey->aCol[i].iFrom + regOld + 1;
  109325. sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump); VdbeCoverage(v);
  109326. }
  109327. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
  109328. }
  109329. continue;
  109330. }
  109331. assert( pFKey->nCol==1 || (aiFree && pIdx) );
  109332. if( aiFree ){
  109333. aiCol = aiFree;
  109334. }else{
  109335. iCol = pFKey->aCol[0].iFrom;
  109336. aiCol = &iCol;
  109337. }
  109338. for(i=0; i<pFKey->nCol; i++){
  109339. if( aiCol[i]==pTab->iPKey ){
  109340. aiCol[i] = -1;
  109341. }
  109342. assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
  109343. #ifndef SQLITE_OMIT_AUTHORIZATION
  109344. /* Request permission to read the parent key columns. If the
  109345. ** authorization callback returns SQLITE_IGNORE, behave as if any
  109346. ** values read from the parent table are NULL. */
  109347. if( db->xAuth ){
  109348. int rcauth;
  109349. char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
  109350. rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
  109351. bIgnore = (rcauth==SQLITE_IGNORE);
  109352. }
  109353. #endif
  109354. }
  109355. /* Take a shared-cache advisory read-lock on the parent table. Allocate
  109356. ** a cursor to use to search the unique index on the parent key columns
  109357. ** in the parent table. */
  109358. sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
  109359. pParse->nTab++;
  109360. if( regOld!=0 ){
  109361. /* A row is being removed from the child table. Search for the parent.
  109362. ** If the parent does not exist, removing the child row resolves an
  109363. ** outstanding foreign key constraint violation. */
  109364. fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1, bIgnore);
  109365. }
  109366. if( regNew!=0 && !isSetNullAction(pParse, pFKey) ){
  109367. /* A row is being added to the child table. If a parent row cannot
  109368. ** be found, adding the child row has violated the FK constraint.
  109369. **
  109370. ** If this operation is being performed as part of a trigger program
  109371. ** that is actually a "SET NULL" action belonging to this very
  109372. ** foreign key, then omit this scan altogether. As all child key
  109373. ** values are guaranteed to be NULL, it is not possible for adding
  109374. ** this row to cause an FK violation. */
  109375. fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1, bIgnore);
  109376. }
  109377. sqlite3DbFree(db, aiFree);
  109378. }
  109379. /* Loop through all the foreign key constraints that refer to this table.
  109380. ** (the "child" constraints) */
  109381. for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
  109382. Index *pIdx = 0; /* Foreign key index for pFKey */
  109383. SrcList *pSrc;
  109384. int *aiCol = 0;
  109385. if( aChange && fkParentIsModified(pTab, pFKey, aChange, bChngRowid)==0 ){
  109386. continue;
  109387. }
  109388. if( !pFKey->isDeferred && !(db->flags & SQLITE_DeferFKs)
  109389. && !pParse->pToplevel && !pParse->isMultiWrite
  109390. ){
  109391. assert( regOld==0 && regNew!=0 );
  109392. /* Inserting a single row into a parent table cannot cause (or fix)
  109393. ** an immediate foreign key violation. So do nothing in this case. */
  109394. continue;
  109395. }
  109396. if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
  109397. if( !isIgnoreErrors || db->mallocFailed ) return;
  109398. continue;
  109399. }
  109400. assert( aiCol || pFKey->nCol==1 );
  109401. /* Create a SrcList structure containing the child table. We need the
  109402. ** child table as a SrcList for sqlite3WhereBegin() */
  109403. pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0);
  109404. if( pSrc ){
  109405. struct SrcList_item *pItem = pSrc->a;
  109406. pItem->pTab = pFKey->pFrom;
  109407. pItem->zName = pFKey->pFrom->zName;
  109408. pItem->pTab->nTabRef++;
  109409. pItem->iCursor = pParse->nTab++;
  109410. if( regNew!=0 ){
  109411. fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
  109412. }
  109413. if( regOld!=0 ){
  109414. int eAction = pFKey->aAction[aChange!=0];
  109415. fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
  109416. /* If this is a deferred FK constraint, or a CASCADE or SET NULL
  109417. ** action applies, then any foreign key violations caused by
  109418. ** removing the parent key will be rectified by the action trigger.
  109419. ** So do not set the "may-abort" flag in this case.
  109420. **
  109421. ** Note 1: If the FK is declared "ON UPDATE CASCADE", then the
  109422. ** may-abort flag will eventually be set on this statement anyway
  109423. ** (when this function is called as part of processing the UPDATE
  109424. ** within the action trigger).
  109425. **
  109426. ** Note 2: At first glance it may seem like SQLite could simply omit
  109427. ** all OP_FkCounter related scans when either CASCADE or SET NULL
  109428. ** applies. The trouble starts if the CASCADE or SET NULL action
  109429. ** trigger causes other triggers or action rules attached to the
  109430. ** child table to fire. In these cases the fk constraint counters
  109431. ** might be set incorrectly if any OP_FkCounter related scans are
  109432. ** omitted. */
  109433. if( !pFKey->isDeferred && eAction!=OE_Cascade && eAction!=OE_SetNull ){
  109434. sqlite3MayAbort(pParse);
  109435. }
  109436. }
  109437. pItem->zName = 0;
  109438. sqlite3SrcListDelete(db, pSrc);
  109439. }
  109440. sqlite3DbFree(db, aiCol);
  109441. }
  109442. }
  109443. #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
  109444. /*
  109445. ** This function is called before generating code to update or delete a
  109446. ** row contained in table pTab.
  109447. */
  109448. SQLITE_PRIVATE u32 sqlite3FkOldmask(
  109449. Parse *pParse, /* Parse context */
  109450. Table *pTab /* Table being modified */
  109451. ){
  109452. u32 mask = 0;
  109453. if( pParse->db->flags&SQLITE_ForeignKeys ){
  109454. FKey *p;
  109455. int i;
  109456. for(p=pTab->pFKey; p; p=p->pNextFrom){
  109457. for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
  109458. }
  109459. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  109460. Index *pIdx = 0;
  109461. sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0);
  109462. if( pIdx ){
  109463. for(i=0; i<pIdx->nKeyCol; i++){
  109464. assert( pIdx->aiColumn[i]>=0 );
  109465. mask |= COLUMN_MASK(pIdx->aiColumn[i]);
  109466. }
  109467. }
  109468. }
  109469. }
  109470. return mask;
  109471. }
  109472. /*
  109473. ** This function is called before generating code to update or delete a
  109474. ** row contained in table pTab. If the operation is a DELETE, then
  109475. ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
  109476. ** to an array of size N, where N is the number of columns in table pTab.
  109477. ** If the i'th column is not modified by the UPDATE, then the corresponding
  109478. ** entry in the aChange[] array is set to -1. If the column is modified,
  109479. ** the value is 0 or greater. Parameter chngRowid is set to true if the
  109480. ** UPDATE statement modifies the rowid fields of the table.
  109481. **
  109482. ** If any foreign key processing will be required, this function returns
  109483. ** non-zero. If there is no foreign key related processing, this function
  109484. ** returns zero.
  109485. **
  109486. ** For an UPDATE, this function returns 2 if:
  109487. **
  109488. ** * There are any FKs for which pTab is the child and the parent table, or
  109489. ** * the UPDATE modifies one or more parent keys for which the action is
  109490. ** not "NO ACTION" (i.e. is CASCADE, SET DEFAULT or SET NULL).
  109491. **
  109492. ** Or, assuming some other foreign key processing is required, 1.
  109493. */
  109494. SQLITE_PRIVATE int sqlite3FkRequired(
  109495. Parse *pParse, /* Parse context */
  109496. Table *pTab, /* Table being modified */
  109497. int *aChange, /* Non-NULL for UPDATE operations */
  109498. int chngRowid /* True for UPDATE that affects rowid */
  109499. ){
  109500. int eRet = 0;
  109501. if( pParse->db->flags&SQLITE_ForeignKeys ){
  109502. if( !aChange ){
  109503. /* A DELETE operation. Foreign key processing is required if the
  109504. ** table in question is either the child or parent table for any
  109505. ** foreign key constraint. */
  109506. eRet = (sqlite3FkReferences(pTab) || pTab->pFKey);
  109507. }else{
  109508. /* This is an UPDATE. Foreign key processing is only required if the
  109509. ** operation modifies one or more child or parent key columns. */
  109510. FKey *p;
  109511. /* Check if any child key columns are being modified. */
  109512. for(p=pTab->pFKey; p; p=p->pNextFrom){
  109513. if( 0==sqlite3_stricmp(pTab->zName, p->zTo) ) return 2;
  109514. if( fkChildIsModified(pTab, p, aChange, chngRowid) ){
  109515. eRet = 1;
  109516. }
  109517. }
  109518. /* Check if any parent key columns are being modified. */
  109519. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  109520. if( fkParentIsModified(pTab, p, aChange, chngRowid) ){
  109521. if( p->aAction[1]!=OE_None ) return 2;
  109522. eRet = 1;
  109523. }
  109524. }
  109525. }
  109526. }
  109527. return eRet;
  109528. }
  109529. /*
  109530. ** This function is called when an UPDATE or DELETE operation is being
  109531. ** compiled on table pTab, which is the parent table of foreign-key pFKey.
  109532. ** If the current operation is an UPDATE, then the pChanges parameter is
  109533. ** passed a pointer to the list of columns being modified. If it is a
  109534. ** DELETE, pChanges is passed a NULL pointer.
  109535. **
  109536. ** It returns a pointer to a Trigger structure containing a trigger
  109537. ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
  109538. ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
  109539. ** returned (these actions require no special handling by the triggers
  109540. ** sub-system, code for them is created by fkScanChildren()).
  109541. **
  109542. ** For example, if pFKey is the foreign key and pTab is table "p" in
  109543. ** the following schema:
  109544. **
  109545. ** CREATE TABLE p(pk PRIMARY KEY);
  109546. ** CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
  109547. **
  109548. ** then the returned trigger structure is equivalent to:
  109549. **
  109550. ** CREATE TRIGGER ... DELETE ON p BEGIN
  109551. ** DELETE FROM c WHERE ck = old.pk;
  109552. ** END;
  109553. **
  109554. ** The returned pointer is cached as part of the foreign key object. It
  109555. ** is eventually freed along with the rest of the foreign key object by
  109556. ** sqlite3FkDelete().
  109557. */
  109558. static Trigger *fkActionTrigger(
  109559. Parse *pParse, /* Parse context */
  109560. Table *pTab, /* Table being updated or deleted from */
  109561. FKey *pFKey, /* Foreign key to get action for */
  109562. ExprList *pChanges /* Change-list for UPDATE, NULL for DELETE */
  109563. ){
  109564. sqlite3 *db = pParse->db; /* Database handle */
  109565. int action; /* One of OE_None, OE_Cascade etc. */
  109566. Trigger *pTrigger; /* Trigger definition to return */
  109567. int iAction = (pChanges!=0); /* 1 for UPDATE, 0 for DELETE */
  109568. action = pFKey->aAction[iAction];
  109569. if( action==OE_Restrict && (db->flags & SQLITE_DeferFKs) ){
  109570. return 0;
  109571. }
  109572. pTrigger = pFKey->apTrigger[iAction];
  109573. if( action!=OE_None && !pTrigger ){
  109574. char const *zFrom; /* Name of child table */
  109575. int nFrom; /* Length in bytes of zFrom */
  109576. Index *pIdx = 0; /* Parent key index for this FK */
  109577. int *aiCol = 0; /* child table cols -> parent key cols */
  109578. TriggerStep *pStep = 0; /* First (only) step of trigger program */
  109579. Expr *pWhere = 0; /* WHERE clause of trigger step */
  109580. ExprList *pList = 0; /* Changes list if ON UPDATE CASCADE */
  109581. Select *pSelect = 0; /* If RESTRICT, "SELECT RAISE(...)" */
  109582. int i; /* Iterator variable */
  109583. Expr *pWhen = 0; /* WHEN clause for the trigger */
  109584. if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
  109585. assert( aiCol || pFKey->nCol==1 );
  109586. for(i=0; i<pFKey->nCol; i++){
  109587. Token tOld = { "old", 3 }; /* Literal "old" token */
  109588. Token tNew = { "new", 3 }; /* Literal "new" token */
  109589. Token tFromCol; /* Name of column in child table */
  109590. Token tToCol; /* Name of column in parent table */
  109591. int iFromCol; /* Idx of column in child table */
  109592. Expr *pEq; /* tFromCol = OLD.tToCol */
  109593. iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
  109594. assert( iFromCol>=0 );
  109595. assert( pIdx!=0 || (pTab->iPKey>=0 && pTab->iPKey<pTab->nCol) );
  109596. assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
  109597. sqlite3TokenInit(&tToCol,
  109598. pTab->aCol[pIdx ? pIdx->aiColumn[i] : pTab->iPKey].zName);
  109599. sqlite3TokenInit(&tFromCol, pFKey->pFrom->aCol[iFromCol].zName);
  109600. /* Create the expression "OLD.zToCol = zFromCol". It is important
  109601. ** that the "OLD.zToCol" term is on the LHS of the = operator, so
  109602. ** that the affinity and collation sequence associated with the
  109603. ** parent table are used for the comparison. */
  109604. pEq = sqlite3PExpr(pParse, TK_EQ,
  109605. sqlite3PExpr(pParse, TK_DOT,
  109606. sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
  109607. sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)),
  109608. sqlite3ExprAlloc(db, TK_ID, &tFromCol, 0)
  109609. );
  109610. pWhere = sqlite3ExprAnd(pParse, pWhere, pEq);
  109611. /* For ON UPDATE, construct the next term of the WHEN clause.
  109612. ** The final WHEN clause will be like this:
  109613. **
  109614. ** WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
  109615. */
  109616. if( pChanges ){
  109617. pEq = sqlite3PExpr(pParse, TK_IS,
  109618. sqlite3PExpr(pParse, TK_DOT,
  109619. sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
  109620. sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)),
  109621. sqlite3PExpr(pParse, TK_DOT,
  109622. sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
  109623. sqlite3ExprAlloc(db, TK_ID, &tToCol, 0))
  109624. );
  109625. pWhen = sqlite3ExprAnd(pParse, pWhen, pEq);
  109626. }
  109627. if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
  109628. Expr *pNew;
  109629. if( action==OE_Cascade ){
  109630. pNew = sqlite3PExpr(pParse, TK_DOT,
  109631. sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
  109632. sqlite3ExprAlloc(db, TK_ID, &tToCol, 0));
  109633. }else if( action==OE_SetDflt ){
  109634. Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
  109635. if( pDflt ){
  109636. pNew = sqlite3ExprDup(db, pDflt, 0);
  109637. }else{
  109638. pNew = sqlite3ExprAlloc(db, TK_NULL, 0, 0);
  109639. }
  109640. }else{
  109641. pNew = sqlite3ExprAlloc(db, TK_NULL, 0, 0);
  109642. }
  109643. pList = sqlite3ExprListAppend(pParse, pList, pNew);
  109644. sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
  109645. }
  109646. }
  109647. sqlite3DbFree(db, aiCol);
  109648. zFrom = pFKey->pFrom->zName;
  109649. nFrom = sqlite3Strlen30(zFrom);
  109650. if( action==OE_Restrict ){
  109651. Token tFrom;
  109652. Expr *pRaise;
  109653. tFrom.z = zFrom;
  109654. tFrom.n = nFrom;
  109655. pRaise = sqlite3Expr(db, TK_RAISE, "FOREIGN KEY constraint failed");
  109656. if( pRaise ){
  109657. pRaise->affinity = OE_Abort;
  109658. }
  109659. pSelect = sqlite3SelectNew(pParse,
  109660. sqlite3ExprListAppend(pParse, 0, pRaise),
  109661. sqlite3SrcListAppend(pParse, 0, &tFrom, 0),
  109662. pWhere,
  109663. 0, 0, 0, 0, 0
  109664. );
  109665. pWhere = 0;
  109666. }
  109667. /* Disable lookaside memory allocation */
  109668. db->lookaside.bDisable++;
  109669. pTrigger = (Trigger *)sqlite3DbMallocZero(db,
  109670. sizeof(Trigger) + /* struct Trigger */
  109671. sizeof(TriggerStep) + /* Single step in trigger program */
  109672. nFrom + 1 /* Space for pStep->zTarget */
  109673. );
  109674. if( pTrigger ){
  109675. pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
  109676. pStep->zTarget = (char *)&pStep[1];
  109677. memcpy((char *)pStep->zTarget, zFrom, nFrom);
  109678. pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  109679. pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
  109680. pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  109681. if( pWhen ){
  109682. pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0);
  109683. pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
  109684. }
  109685. }
  109686. /* Re-enable the lookaside buffer, if it was disabled earlier. */
  109687. db->lookaside.bDisable--;
  109688. sqlite3ExprDelete(db, pWhere);
  109689. sqlite3ExprDelete(db, pWhen);
  109690. sqlite3ExprListDelete(db, pList);
  109691. sqlite3SelectDelete(db, pSelect);
  109692. if( db->mallocFailed==1 ){
  109693. fkTriggerDelete(db, pTrigger);
  109694. return 0;
  109695. }
  109696. assert( pStep!=0 );
  109697. switch( action ){
  109698. case OE_Restrict:
  109699. pStep->op = TK_SELECT;
  109700. break;
  109701. case OE_Cascade:
  109702. if( !pChanges ){
  109703. pStep->op = TK_DELETE;
  109704. break;
  109705. }
  109706. default:
  109707. pStep->op = TK_UPDATE;
  109708. }
  109709. pStep->pTrig = pTrigger;
  109710. pTrigger->pSchema = pTab->pSchema;
  109711. pTrigger->pTabSchema = pTab->pSchema;
  109712. pFKey->apTrigger[iAction] = pTrigger;
  109713. pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
  109714. }
  109715. return pTrigger;
  109716. }
  109717. /*
  109718. ** This function is called when deleting or updating a row to implement
  109719. ** any required CASCADE, SET NULL or SET DEFAULT actions.
  109720. */
  109721. SQLITE_PRIVATE void sqlite3FkActions(
  109722. Parse *pParse, /* Parse context */
  109723. Table *pTab, /* Table being updated or deleted from */
  109724. ExprList *pChanges, /* Change-list for UPDATE, NULL for DELETE */
  109725. int regOld, /* Address of array containing old row */
  109726. int *aChange, /* Array indicating UPDATEd columns (or 0) */
  109727. int bChngRowid /* True if rowid is UPDATEd */
  109728. ){
  109729. /* If foreign-key support is enabled, iterate through all FKs that
  109730. ** refer to table pTab. If there is an action associated with the FK
  109731. ** for this operation (either update or delete), invoke the associated
  109732. ** trigger sub-program. */
  109733. if( pParse->db->flags&SQLITE_ForeignKeys ){
  109734. FKey *pFKey; /* Iterator variable */
  109735. for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
  109736. if( aChange==0 || fkParentIsModified(pTab, pFKey, aChange, bChngRowid) ){
  109737. Trigger *pAct = fkActionTrigger(pParse, pTab, pFKey, pChanges);
  109738. if( pAct ){
  109739. sqlite3CodeRowTriggerDirect(pParse, pAct, pTab, regOld, OE_Abort, 0);
  109740. }
  109741. }
  109742. }
  109743. }
  109744. }
  109745. #endif /* ifndef SQLITE_OMIT_TRIGGER */
  109746. /*
  109747. ** Free all memory associated with foreign key definitions attached to
  109748. ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
  109749. ** hash table.
  109750. */
  109751. SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
  109752. FKey *pFKey; /* Iterator variable */
  109753. FKey *pNext; /* Copy of pFKey->pNextFrom */
  109754. assert( db==0 || IsVirtual(pTab)
  109755. || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
  109756. for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
  109757. /* Remove the FK from the fkeyHash hash table. */
  109758. if( !db || db->pnBytesFreed==0 ){
  109759. if( pFKey->pPrevTo ){
  109760. pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
  109761. }else{
  109762. void *p = (void *)pFKey->pNextTo;
  109763. const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
  109764. sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, p);
  109765. }
  109766. if( pFKey->pNextTo ){
  109767. pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
  109768. }
  109769. }
  109770. /* EV: R-30323-21917 Each foreign key constraint in SQLite is
  109771. ** classified as either immediate or deferred.
  109772. */
  109773. assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
  109774. /* Delete any triggers created to implement actions for this FK. */
  109775. #ifndef SQLITE_OMIT_TRIGGER
  109776. fkTriggerDelete(db, pFKey->apTrigger[0]);
  109777. fkTriggerDelete(db, pFKey->apTrigger[1]);
  109778. #endif
  109779. pNext = pFKey->pNextFrom;
  109780. sqlite3DbFree(db, pFKey);
  109781. }
  109782. }
  109783. #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
  109784. /************** End of fkey.c ************************************************/
  109785. /************** Begin file insert.c ******************************************/
  109786. /*
  109787. ** 2001 September 15
  109788. **
  109789. ** The author disclaims copyright to this source code. In place of
  109790. ** a legal notice, here is a blessing:
  109791. **
  109792. ** May you do good and not evil.
  109793. ** May you find forgiveness for yourself and forgive others.
  109794. ** May you share freely, never taking more than you give.
  109795. **
  109796. *************************************************************************
  109797. ** This file contains C code routines that are called by the parser
  109798. ** to handle INSERT statements in SQLite.
  109799. */
  109800. /* #include "sqliteInt.h" */
  109801. /*
  109802. ** Generate code that will
  109803. **
  109804. ** (1) acquire a lock for table pTab then
  109805. ** (2) open pTab as cursor iCur.
  109806. **
  109807. ** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index
  109808. ** for that table that is actually opened.
  109809. */
  109810. SQLITE_PRIVATE void sqlite3OpenTable(
  109811. Parse *pParse, /* Generate code into this VDBE */
  109812. int iCur, /* The cursor number of the table */
  109813. int iDb, /* The database index in sqlite3.aDb[] */
  109814. Table *pTab, /* The table to be opened */
  109815. int opcode /* OP_OpenRead or OP_OpenWrite */
  109816. ){
  109817. Vdbe *v;
  109818. assert( !IsVirtual(pTab) );
  109819. v = sqlite3GetVdbe(pParse);
  109820. assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
  109821. sqlite3TableLock(pParse, iDb, pTab->tnum,
  109822. (opcode==OP_OpenWrite)?1:0, pTab->zName);
  109823. if( HasRowid(pTab) ){
  109824. sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nCol);
  109825. VdbeComment((v, "%s", pTab->zName));
  109826. }else{
  109827. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  109828. assert( pPk!=0 );
  109829. assert( pPk->tnum==pTab->tnum );
  109830. sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
  109831. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  109832. VdbeComment((v, "%s", pTab->zName));
  109833. }
  109834. }
  109835. /*
  109836. ** Return a pointer to the column affinity string associated with index
  109837. ** pIdx. A column affinity string has one character for each column in
  109838. ** the table, according to the affinity of the column:
  109839. **
  109840. ** Character Column affinity
  109841. ** ------------------------------
  109842. ** 'A' BLOB
  109843. ** 'B' TEXT
  109844. ** 'C' NUMERIC
  109845. ** 'D' INTEGER
  109846. ** 'F' REAL
  109847. **
  109848. ** An extra 'D' is appended to the end of the string to cover the
  109849. ** rowid that appears as the last column in every index.
  109850. **
  109851. ** Memory for the buffer containing the column index affinity string
  109852. ** is managed along with the rest of the Index structure. It will be
  109853. ** released when sqlite3DeleteIndex() is called.
  109854. */
  109855. SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3 *db, Index *pIdx){
  109856. if( !pIdx->zColAff ){
  109857. /* The first time a column affinity string for a particular index is
  109858. ** required, it is allocated and populated here. It is then stored as
  109859. ** a member of the Index structure for subsequent use.
  109860. **
  109861. ** The column affinity string will eventually be deleted by
  109862. ** sqliteDeleteIndex() when the Index structure itself is cleaned
  109863. ** up.
  109864. */
  109865. int n;
  109866. Table *pTab = pIdx->pTable;
  109867. pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
  109868. if( !pIdx->zColAff ){
  109869. sqlite3OomFault(db);
  109870. return 0;
  109871. }
  109872. for(n=0; n<pIdx->nColumn; n++){
  109873. i16 x = pIdx->aiColumn[n];
  109874. if( x>=0 ){
  109875. pIdx->zColAff[n] = pTab->aCol[x].affinity;
  109876. }else if( x==XN_ROWID ){
  109877. pIdx->zColAff[n] = SQLITE_AFF_INTEGER;
  109878. }else{
  109879. char aff;
  109880. assert( x==XN_EXPR );
  109881. assert( pIdx->aColExpr!=0 );
  109882. aff = sqlite3ExprAffinity(pIdx->aColExpr->a[n].pExpr);
  109883. if( aff==0 ) aff = SQLITE_AFF_BLOB;
  109884. pIdx->zColAff[n] = aff;
  109885. }
  109886. }
  109887. pIdx->zColAff[n] = 0;
  109888. }
  109889. return pIdx->zColAff;
  109890. }
  109891. /*
  109892. ** Compute the affinity string for table pTab, if it has not already been
  109893. ** computed. As an optimization, omit trailing SQLITE_AFF_BLOB affinities.
  109894. **
  109895. ** If the affinity exists (if it is no entirely SQLITE_AFF_BLOB values) and
  109896. ** if iReg>0 then code an OP_Affinity opcode that will set the affinities
  109897. ** for register iReg and following. Or if affinities exists and iReg==0,
  109898. ** then just set the P4 operand of the previous opcode (which should be
  109899. ** an OP_MakeRecord) to the affinity string.
  109900. **
  109901. ** A column affinity string has one character per column:
  109902. **
  109903. ** Character Column affinity
  109904. ** ------------------------------
  109905. ** 'A' BLOB
  109906. ** 'B' TEXT
  109907. ** 'C' NUMERIC
  109908. ** 'D' INTEGER
  109909. ** 'E' REAL
  109910. */
  109911. SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
  109912. int i;
  109913. char *zColAff = pTab->zColAff;
  109914. if( zColAff==0 ){
  109915. sqlite3 *db = sqlite3VdbeDb(v);
  109916. zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
  109917. if( !zColAff ){
  109918. sqlite3OomFault(db);
  109919. return;
  109920. }
  109921. for(i=0; i<pTab->nCol; i++){
  109922. zColAff[i] = pTab->aCol[i].affinity;
  109923. }
  109924. do{
  109925. zColAff[i--] = 0;
  109926. }while( i>=0 && zColAff[i]==SQLITE_AFF_BLOB );
  109927. pTab->zColAff = zColAff;
  109928. }
  109929. assert( zColAff!=0 );
  109930. i = sqlite3Strlen30NN(zColAff);
  109931. if( i ){
  109932. if( iReg ){
  109933. sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
  109934. }else{
  109935. sqlite3VdbeChangeP4(v, -1, zColAff, i);
  109936. }
  109937. }
  109938. }
  109939. /*
  109940. ** Return non-zero if the table pTab in database iDb or any of its indices
  109941. ** have been opened at any point in the VDBE program. This is used to see if
  109942. ** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can
  109943. ** run without using a temporary table for the results of the SELECT.
  109944. */
  109945. static int readsTable(Parse *p, int iDb, Table *pTab){
  109946. Vdbe *v = sqlite3GetVdbe(p);
  109947. int i;
  109948. int iEnd = sqlite3VdbeCurrentAddr(v);
  109949. #ifndef SQLITE_OMIT_VIRTUALTABLE
  109950. VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
  109951. #endif
  109952. for(i=1; i<iEnd; i++){
  109953. VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
  109954. assert( pOp!=0 );
  109955. if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
  109956. Index *pIndex;
  109957. int tnum = pOp->p2;
  109958. if( tnum==pTab->tnum ){
  109959. return 1;
  109960. }
  109961. for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
  109962. if( tnum==pIndex->tnum ){
  109963. return 1;
  109964. }
  109965. }
  109966. }
  109967. #ifndef SQLITE_OMIT_VIRTUALTABLE
  109968. if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
  109969. assert( pOp->p4.pVtab!=0 );
  109970. assert( pOp->p4type==P4_VTAB );
  109971. return 1;
  109972. }
  109973. #endif
  109974. }
  109975. return 0;
  109976. }
  109977. #ifndef SQLITE_OMIT_AUTOINCREMENT
  109978. /*
  109979. ** Locate or create an AutoincInfo structure associated with table pTab
  109980. ** which is in database iDb. Return the register number for the register
  109981. ** that holds the maximum rowid. Return zero if pTab is not an AUTOINCREMENT
  109982. ** table. (Also return zero when doing a VACUUM since we do not want to
  109983. ** update the AUTOINCREMENT counters during a VACUUM.)
  109984. **
  109985. ** There is at most one AutoincInfo structure per table even if the
  109986. ** same table is autoincremented multiple times due to inserts within
  109987. ** triggers. A new AutoincInfo structure is created if this is the
  109988. ** first use of table pTab. On 2nd and subsequent uses, the original
  109989. ** AutoincInfo structure is used.
  109990. **
  109991. ** Four consecutive registers are allocated:
  109992. **
  109993. ** (1) The name of the pTab table.
  109994. ** (2) The maximum ROWID of pTab.
  109995. ** (3) The rowid in sqlite_sequence of pTab
  109996. ** (4) The original value of the max ROWID in pTab, or NULL if none
  109997. **
  109998. ** The 2nd register is the one that is returned. That is all the
  109999. ** insert routine needs to know about.
  110000. */
  110001. static int autoIncBegin(
  110002. Parse *pParse, /* Parsing context */
  110003. int iDb, /* Index of the database holding pTab */
  110004. Table *pTab /* The table we are writing to */
  110005. ){
  110006. int memId = 0; /* Register holding maximum rowid */
  110007. assert( pParse->db->aDb[iDb].pSchema!=0 );
  110008. if( (pTab->tabFlags & TF_Autoincrement)!=0
  110009. && (pParse->db->mDbFlags & DBFLAG_Vacuum)==0
  110010. ){
  110011. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  110012. AutoincInfo *pInfo;
  110013. Table *pSeqTab = pParse->db->aDb[iDb].pSchema->pSeqTab;
  110014. /* Verify that the sqlite_sequence table exists and is an ordinary
  110015. ** rowid table with exactly two columns.
  110016. ** Ticket d8dc2b3a58cd5dc2918a1d4acb 2018-05-23 */
  110017. if( pSeqTab==0
  110018. || !HasRowid(pSeqTab)
  110019. || IsVirtual(pSeqTab)
  110020. || pSeqTab->nCol!=2
  110021. ){
  110022. pParse->nErr++;
  110023. pParse->rc = SQLITE_CORRUPT_SEQUENCE;
  110024. return 0;
  110025. }
  110026. pInfo = pToplevel->pAinc;
  110027. while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
  110028. if( pInfo==0 ){
  110029. pInfo = sqlite3DbMallocRawNN(pParse->db, sizeof(*pInfo));
  110030. if( pInfo==0 ) return 0;
  110031. pInfo->pNext = pToplevel->pAinc;
  110032. pToplevel->pAinc = pInfo;
  110033. pInfo->pTab = pTab;
  110034. pInfo->iDb = iDb;
  110035. pToplevel->nMem++; /* Register to hold name of table */
  110036. pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */
  110037. pToplevel->nMem +=2; /* Rowid in sqlite_sequence + orig max val */
  110038. }
  110039. memId = pInfo->regCtr;
  110040. }
  110041. return memId;
  110042. }
  110043. /*
  110044. ** This routine generates code that will initialize all of the
  110045. ** register used by the autoincrement tracker.
  110046. */
  110047. SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
  110048. AutoincInfo *p; /* Information about an AUTOINCREMENT */
  110049. sqlite3 *db = pParse->db; /* The database connection */
  110050. Db *pDb; /* Database only autoinc table */
  110051. int memId; /* Register holding max rowid */
  110052. Vdbe *v = pParse->pVdbe; /* VDBE under construction */
  110053. /* This routine is never called during trigger-generation. It is
  110054. ** only called from the top-level */
  110055. assert( pParse->pTriggerTab==0 );
  110056. assert( sqlite3IsToplevel(pParse) );
  110057. assert( v ); /* We failed long ago if this is not so */
  110058. for(p = pParse->pAinc; p; p = p->pNext){
  110059. static const int iLn = VDBE_OFFSET_LINENO(2);
  110060. static const VdbeOpList autoInc[] = {
  110061. /* 0 */ {OP_Null, 0, 0, 0},
  110062. /* 1 */ {OP_Rewind, 0, 10, 0},
  110063. /* 2 */ {OP_Column, 0, 0, 0},
  110064. /* 3 */ {OP_Ne, 0, 9, 0},
  110065. /* 4 */ {OP_Rowid, 0, 0, 0},
  110066. /* 5 */ {OP_Column, 0, 1, 0},
  110067. /* 6 */ {OP_AddImm, 0, 0, 0},
  110068. /* 7 */ {OP_Copy, 0, 0, 0},
  110069. /* 8 */ {OP_Goto, 0, 11, 0},
  110070. /* 9 */ {OP_Next, 0, 2, 0},
  110071. /* 10 */ {OP_Integer, 0, 0, 0},
  110072. /* 11 */ {OP_Close, 0, 0, 0}
  110073. };
  110074. VdbeOp *aOp;
  110075. pDb = &db->aDb[p->iDb];
  110076. memId = p->regCtr;
  110077. assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
  110078. sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
  110079. sqlite3VdbeLoadString(v, memId-1, p->pTab->zName);
  110080. aOp = sqlite3VdbeAddOpList(v, ArraySize(autoInc), autoInc, iLn);
  110081. if( aOp==0 ) break;
  110082. aOp[0].p2 = memId;
  110083. aOp[0].p3 = memId+2;
  110084. aOp[2].p3 = memId;
  110085. aOp[3].p1 = memId-1;
  110086. aOp[3].p3 = memId;
  110087. aOp[3].p5 = SQLITE_JUMPIFNULL;
  110088. aOp[4].p2 = memId+1;
  110089. aOp[5].p3 = memId;
  110090. aOp[6].p1 = memId;
  110091. aOp[7].p2 = memId+2;
  110092. aOp[7].p1 = memId;
  110093. aOp[10].p2 = memId;
  110094. if( pParse->nTab==0 ) pParse->nTab = 1;
  110095. }
  110096. }
  110097. /*
  110098. ** Update the maximum rowid for an autoincrement calculation.
  110099. **
  110100. ** This routine should be called when the regRowid register holds a
  110101. ** new rowid that is about to be inserted. If that new rowid is
  110102. ** larger than the maximum rowid in the memId memory cell, then the
  110103. ** memory cell is updated.
  110104. */
  110105. static void autoIncStep(Parse *pParse, int memId, int regRowid){
  110106. if( memId>0 ){
  110107. sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
  110108. }
  110109. }
  110110. /*
  110111. ** This routine generates the code needed to write autoincrement
  110112. ** maximum rowid values back into the sqlite_sequence register.
  110113. ** Every statement that might do an INSERT into an autoincrement
  110114. ** table (either directly or through triggers) needs to call this
  110115. ** routine just before the "exit" code.
  110116. */
  110117. static SQLITE_NOINLINE void autoIncrementEnd(Parse *pParse){
  110118. AutoincInfo *p;
  110119. Vdbe *v = pParse->pVdbe;
  110120. sqlite3 *db = pParse->db;
  110121. assert( v );
  110122. for(p = pParse->pAinc; p; p = p->pNext){
  110123. static const int iLn = VDBE_OFFSET_LINENO(2);
  110124. static const VdbeOpList autoIncEnd[] = {
  110125. /* 0 */ {OP_NotNull, 0, 2, 0},
  110126. /* 1 */ {OP_NewRowid, 0, 0, 0},
  110127. /* 2 */ {OP_MakeRecord, 0, 2, 0},
  110128. /* 3 */ {OP_Insert, 0, 0, 0},
  110129. /* 4 */ {OP_Close, 0, 0, 0}
  110130. };
  110131. VdbeOp *aOp;
  110132. Db *pDb = &db->aDb[p->iDb];
  110133. int iRec;
  110134. int memId = p->regCtr;
  110135. iRec = sqlite3GetTempReg(pParse);
  110136. assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
  110137. sqlite3VdbeAddOp3(v, OP_Le, memId+2, sqlite3VdbeCurrentAddr(v)+7, memId);
  110138. VdbeCoverage(v);
  110139. sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
  110140. aOp = sqlite3VdbeAddOpList(v, ArraySize(autoIncEnd), autoIncEnd, iLn);
  110141. if( aOp==0 ) break;
  110142. aOp[0].p1 = memId+1;
  110143. aOp[1].p2 = memId+1;
  110144. aOp[2].p1 = memId-1;
  110145. aOp[2].p3 = iRec;
  110146. aOp[3].p2 = iRec;
  110147. aOp[3].p3 = memId+1;
  110148. aOp[3].p5 = OPFLAG_APPEND;
  110149. sqlite3ReleaseTempReg(pParse, iRec);
  110150. }
  110151. }
  110152. SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
  110153. if( pParse->pAinc ) autoIncrementEnd(pParse);
  110154. }
  110155. #else
  110156. /*
  110157. ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
  110158. ** above are all no-ops
  110159. */
  110160. # define autoIncBegin(A,B,C) (0)
  110161. # define autoIncStep(A,B,C)
  110162. #endif /* SQLITE_OMIT_AUTOINCREMENT */
  110163. /* Forward declaration */
  110164. static int xferOptimization(
  110165. Parse *pParse, /* Parser context */
  110166. Table *pDest, /* The table we are inserting into */
  110167. Select *pSelect, /* A SELECT statement to use as the data source */
  110168. int onError, /* How to handle constraint errors */
  110169. int iDbDest /* The database of pDest */
  110170. );
  110171. /*
  110172. ** This routine is called to handle SQL of the following forms:
  110173. **
  110174. ** insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),...
  110175. ** insert into TABLE (IDLIST) select
  110176. ** insert into TABLE (IDLIST) default values
  110177. **
  110178. ** The IDLIST following the table name is always optional. If omitted,
  110179. ** then a list of all (non-hidden) columns for the table is substituted.
  110180. ** The IDLIST appears in the pColumn parameter. pColumn is NULL if IDLIST
  110181. ** is omitted.
  110182. **
  110183. ** For the pSelect parameter holds the values to be inserted for the
  110184. ** first two forms shown above. A VALUES clause is really just short-hand
  110185. ** for a SELECT statement that omits the FROM clause and everything else
  110186. ** that follows. If the pSelect parameter is NULL, that means that the
  110187. ** DEFAULT VALUES form of the INSERT statement is intended.
  110188. **
  110189. ** The code generated follows one of four templates. For a simple
  110190. ** insert with data coming from a single-row VALUES clause, the code executes
  110191. ** once straight down through. Pseudo-code follows (we call this
  110192. ** the "1st template"):
  110193. **
  110194. ** open write cursor to <table> and its indices
  110195. ** put VALUES clause expressions into registers
  110196. ** write the resulting record into <table>
  110197. ** cleanup
  110198. **
  110199. ** The three remaining templates assume the statement is of the form
  110200. **
  110201. ** INSERT INTO <table> SELECT ...
  110202. **
  110203. ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
  110204. ** in other words if the SELECT pulls all columns from a single table
  110205. ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
  110206. ** if <table2> and <table1> are distinct tables but have identical
  110207. ** schemas, including all the same indices, then a special optimization
  110208. ** is invoked that copies raw records from <table2> over to <table1>.
  110209. ** See the xferOptimization() function for the implementation of this
  110210. ** template. This is the 2nd template.
  110211. **
  110212. ** open a write cursor to <table>
  110213. ** open read cursor on <table2>
  110214. ** transfer all records in <table2> over to <table>
  110215. ** close cursors
  110216. ** foreach index on <table>
  110217. ** open a write cursor on the <table> index
  110218. ** open a read cursor on the corresponding <table2> index
  110219. ** transfer all records from the read to the write cursors
  110220. ** close cursors
  110221. ** end foreach
  110222. **
  110223. ** The 3rd template is for when the second template does not apply
  110224. ** and the SELECT clause does not read from <table> at any time.
  110225. ** The generated code follows this template:
  110226. **
  110227. ** X <- A
  110228. ** goto B
  110229. ** A: setup for the SELECT
  110230. ** loop over the rows in the SELECT
  110231. ** load values into registers R..R+n
  110232. ** yield X
  110233. ** end loop
  110234. ** cleanup after the SELECT
  110235. ** end-coroutine X
  110236. ** B: open write cursor to <table> and its indices
  110237. ** C: yield X, at EOF goto D
  110238. ** insert the select result into <table> from R..R+n
  110239. ** goto C
  110240. ** D: cleanup
  110241. **
  110242. ** The 4th template is used if the insert statement takes its
  110243. ** values from a SELECT but the data is being inserted into a table
  110244. ** that is also read as part of the SELECT. In the third form,
  110245. ** we have to use an intermediate table to store the results of
  110246. ** the select. The template is like this:
  110247. **
  110248. ** X <- A
  110249. ** goto B
  110250. ** A: setup for the SELECT
  110251. ** loop over the tables in the SELECT
  110252. ** load value into register R..R+n
  110253. ** yield X
  110254. ** end loop
  110255. ** cleanup after the SELECT
  110256. ** end co-routine R
  110257. ** B: open temp table
  110258. ** L: yield X, at EOF goto M
  110259. ** insert row from R..R+n into temp table
  110260. ** goto L
  110261. ** M: open write cursor to <table> and its indices
  110262. ** rewind temp table
  110263. ** C: loop over rows of intermediate table
  110264. ** transfer values form intermediate table into <table>
  110265. ** end loop
  110266. ** D: cleanup
  110267. */
  110268. SQLITE_PRIVATE void sqlite3Insert(
  110269. Parse *pParse, /* Parser context */
  110270. SrcList *pTabList, /* Name of table into which we are inserting */
  110271. Select *pSelect, /* A SELECT statement to use as the data source */
  110272. IdList *pColumn, /* Column names corresponding to IDLIST. */
  110273. int onError, /* How to handle constraint errors */
  110274. Upsert *pUpsert /* ON CONFLICT clauses for upsert, or NULL */
  110275. ){
  110276. sqlite3 *db; /* The main database structure */
  110277. Table *pTab; /* The table to insert into. aka TABLE */
  110278. int i, j; /* Loop counters */
  110279. Vdbe *v; /* Generate code into this virtual machine */
  110280. Index *pIdx; /* For looping over indices of the table */
  110281. int nColumn; /* Number of columns in the data */
  110282. int nHidden = 0; /* Number of hidden columns if TABLE is virtual */
  110283. int iDataCur = 0; /* VDBE cursor that is the main data repository */
  110284. int iIdxCur = 0; /* First index cursor */
  110285. int ipkColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
  110286. int endOfLoop; /* Label for the end of the insertion loop */
  110287. int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
  110288. int addrInsTop = 0; /* Jump to label "D" */
  110289. int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */
  110290. SelectDest dest; /* Destination for SELECT on rhs of INSERT */
  110291. int iDb; /* Index of database holding TABLE */
  110292. u8 useTempTable = 0; /* Store SELECT results in intermediate table */
  110293. u8 appendFlag = 0; /* True if the insert is likely to be an append */
  110294. u8 withoutRowid; /* 0 for normal table. 1 for WITHOUT ROWID table */
  110295. u8 bIdListInOrder; /* True if IDLIST is in table order */
  110296. ExprList *pList = 0; /* List of VALUES() to be inserted */
  110297. /* Register allocations */
  110298. int regFromSelect = 0;/* Base register for data coming from SELECT */
  110299. int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */
  110300. int regRowCount = 0; /* Memory cell used for the row counter */
  110301. int regIns; /* Block of regs holding rowid+data being inserted */
  110302. int regRowid; /* registers holding insert rowid */
  110303. int regData; /* register holding first column to insert */
  110304. int *aRegIdx = 0; /* One register allocated to each index */
  110305. #ifndef SQLITE_OMIT_TRIGGER
  110306. int isView; /* True if attempting to insert into a view */
  110307. Trigger *pTrigger; /* List of triggers on pTab, if required */
  110308. int tmask; /* Mask of trigger times */
  110309. #endif
  110310. db = pParse->db;
  110311. if( pParse->nErr || db->mallocFailed ){
  110312. goto insert_cleanup;
  110313. }
  110314. dest.iSDParm = 0; /* Suppress a harmless compiler warning */
  110315. /* If the Select object is really just a simple VALUES() list with a
  110316. ** single row (the common case) then keep that one row of values
  110317. ** and discard the other (unused) parts of the pSelect object
  110318. */
  110319. if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
  110320. pList = pSelect->pEList;
  110321. pSelect->pEList = 0;
  110322. sqlite3SelectDelete(db, pSelect);
  110323. pSelect = 0;
  110324. }
  110325. /* Locate the table into which we will be inserting new information.
  110326. */
  110327. assert( pTabList->nSrc==1 );
  110328. pTab = sqlite3SrcListLookup(pParse, pTabList);
  110329. if( pTab==0 ){
  110330. goto insert_cleanup;
  110331. }
  110332. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  110333. assert( iDb<db->nDb );
  110334. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0,
  110335. db->aDb[iDb].zDbSName) ){
  110336. goto insert_cleanup;
  110337. }
  110338. withoutRowid = !HasRowid(pTab);
  110339. /* Figure out if we have any triggers and if the table being
  110340. ** inserted into is a view
  110341. */
  110342. #ifndef SQLITE_OMIT_TRIGGER
  110343. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
  110344. isView = pTab->pSelect!=0;
  110345. #else
  110346. # define pTrigger 0
  110347. # define tmask 0
  110348. # define isView 0
  110349. #endif
  110350. #ifdef SQLITE_OMIT_VIEW
  110351. # undef isView
  110352. # define isView 0
  110353. #endif
  110354. assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
  110355. /* If pTab is really a view, make sure it has been initialized.
  110356. ** ViewGetColumnNames() is a no-op if pTab is not a view.
  110357. */
  110358. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  110359. goto insert_cleanup;
  110360. }
  110361. /* Cannot insert into a read-only table.
  110362. */
  110363. if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
  110364. goto insert_cleanup;
  110365. }
  110366. /* Allocate a VDBE
  110367. */
  110368. v = sqlite3GetVdbe(pParse);
  110369. if( v==0 ) goto insert_cleanup;
  110370. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  110371. sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
  110372. #ifndef SQLITE_OMIT_XFER_OPT
  110373. /* If the statement is of the form
  110374. **
  110375. ** INSERT INTO <table1> SELECT * FROM <table2>;
  110376. **
  110377. ** Then special optimizations can be applied that make the transfer
  110378. ** very fast and which reduce fragmentation of indices.
  110379. **
  110380. ** This is the 2nd template.
  110381. */
  110382. if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
  110383. assert( !pTrigger );
  110384. assert( pList==0 );
  110385. goto insert_end;
  110386. }
  110387. #endif /* SQLITE_OMIT_XFER_OPT */
  110388. /* If this is an AUTOINCREMENT table, look up the sequence number in the
  110389. ** sqlite_sequence table and store it in memory cell regAutoinc.
  110390. */
  110391. regAutoinc = autoIncBegin(pParse, iDb, pTab);
  110392. /* Allocate registers for holding the rowid of the new row,
  110393. ** the content of the new row, and the assembled row record.
  110394. */
  110395. regRowid = regIns = pParse->nMem+1;
  110396. pParse->nMem += pTab->nCol + 1;
  110397. if( IsVirtual(pTab) ){
  110398. regRowid++;
  110399. pParse->nMem++;
  110400. }
  110401. regData = regRowid+1;
  110402. /* If the INSERT statement included an IDLIST term, then make sure
  110403. ** all elements of the IDLIST really are columns of the table and
  110404. ** remember the column indices.
  110405. **
  110406. ** If the table has an INTEGER PRIMARY KEY column and that column
  110407. ** is named in the IDLIST, then record in the ipkColumn variable
  110408. ** the index into IDLIST of the primary key column. ipkColumn is
  110409. ** the index of the primary key as it appears in IDLIST, not as
  110410. ** is appears in the original table. (The index of the INTEGER
  110411. ** PRIMARY KEY in the original table is pTab->iPKey.)
  110412. */
  110413. bIdListInOrder = (pTab->tabFlags & TF_OOOHidden)==0;
  110414. if( pColumn ){
  110415. for(i=0; i<pColumn->nId; i++){
  110416. pColumn->a[i].idx = -1;
  110417. }
  110418. for(i=0; i<pColumn->nId; i++){
  110419. for(j=0; j<pTab->nCol; j++){
  110420. if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
  110421. pColumn->a[i].idx = j;
  110422. if( i!=j ) bIdListInOrder = 0;
  110423. if( j==pTab->iPKey ){
  110424. ipkColumn = i; assert( !withoutRowid );
  110425. }
  110426. break;
  110427. }
  110428. }
  110429. if( j>=pTab->nCol ){
  110430. if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
  110431. ipkColumn = i;
  110432. bIdListInOrder = 0;
  110433. }else{
  110434. sqlite3ErrorMsg(pParse, "table %S has no column named %s",
  110435. pTabList, 0, pColumn->a[i].zName);
  110436. pParse->checkSchema = 1;
  110437. goto insert_cleanup;
  110438. }
  110439. }
  110440. }
  110441. }
  110442. /* Figure out how many columns of data are supplied. If the data
  110443. ** is coming from a SELECT statement, then generate a co-routine that
  110444. ** produces a single row of the SELECT on each invocation. The
  110445. ** co-routine is the common header to the 3rd and 4th templates.
  110446. */
  110447. if( pSelect ){
  110448. /* Data is coming from a SELECT or from a multi-row VALUES clause.
  110449. ** Generate a co-routine to run the SELECT. */
  110450. int regYield; /* Register holding co-routine entry-point */
  110451. int addrTop; /* Top of the co-routine */
  110452. int rc; /* Result code */
  110453. regYield = ++pParse->nMem;
  110454. addrTop = sqlite3VdbeCurrentAddr(v) + 1;
  110455. sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
  110456. sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
  110457. dest.iSdst = bIdListInOrder ? regData : 0;
  110458. dest.nSdst = pTab->nCol;
  110459. rc = sqlite3Select(pParse, pSelect, &dest);
  110460. regFromSelect = dest.iSdst;
  110461. if( rc || db->mallocFailed || pParse->nErr ) goto insert_cleanup;
  110462. sqlite3VdbeEndCoroutine(v, regYield);
  110463. sqlite3VdbeJumpHere(v, addrTop - 1); /* label B: */
  110464. assert( pSelect->pEList );
  110465. nColumn = pSelect->pEList->nExpr;
  110466. /* Set useTempTable to TRUE if the result of the SELECT statement
  110467. ** should be written into a temporary table (template 4). Set to
  110468. ** FALSE if each output row of the SELECT can be written directly into
  110469. ** the destination table (template 3).
  110470. **
  110471. ** A temp table must be used if the table being updated is also one
  110472. ** of the tables being read by the SELECT statement. Also use a
  110473. ** temp table in the case of row triggers.
  110474. */
  110475. if( pTrigger || readsTable(pParse, iDb, pTab) ){
  110476. useTempTable = 1;
  110477. }
  110478. if( useTempTable ){
  110479. /* Invoke the coroutine to extract information from the SELECT
  110480. ** and add it to a transient table srcTab. The code generated
  110481. ** here is from the 4th template:
  110482. **
  110483. ** B: open temp table
  110484. ** L: yield X, goto M at EOF
  110485. ** insert row from R..R+n into temp table
  110486. ** goto L
  110487. ** M: ...
  110488. */
  110489. int regRec; /* Register to hold packed record */
  110490. int regTempRowid; /* Register to hold temp table ROWID */
  110491. int addrL; /* Label "L" */
  110492. srcTab = pParse->nTab++;
  110493. regRec = sqlite3GetTempReg(pParse);
  110494. regTempRowid = sqlite3GetTempReg(pParse);
  110495. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
  110496. addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
  110497. sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
  110498. sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
  110499. sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
  110500. sqlite3VdbeGoto(v, addrL);
  110501. sqlite3VdbeJumpHere(v, addrL);
  110502. sqlite3ReleaseTempReg(pParse, regRec);
  110503. sqlite3ReleaseTempReg(pParse, regTempRowid);
  110504. }
  110505. }else{
  110506. /* This is the case if the data for the INSERT is coming from a
  110507. ** single-row VALUES clause
  110508. */
  110509. NameContext sNC;
  110510. memset(&sNC, 0, sizeof(sNC));
  110511. sNC.pParse = pParse;
  110512. srcTab = -1;
  110513. assert( useTempTable==0 );
  110514. if( pList ){
  110515. nColumn = pList->nExpr;
  110516. if( sqlite3ResolveExprListNames(&sNC, pList) ){
  110517. goto insert_cleanup;
  110518. }
  110519. }else{
  110520. nColumn = 0;
  110521. }
  110522. }
  110523. /* If there is no IDLIST term but the table has an integer primary
  110524. ** key, the set the ipkColumn variable to the integer primary key
  110525. ** column index in the original table definition.
  110526. */
  110527. if( pColumn==0 && nColumn>0 ){
  110528. ipkColumn = pTab->iPKey;
  110529. }
  110530. /* Make sure the number of columns in the source data matches the number
  110531. ** of columns to be inserted into the table.
  110532. */
  110533. for(i=0; i<pTab->nCol; i++){
  110534. nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
  110535. }
  110536. if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
  110537. sqlite3ErrorMsg(pParse,
  110538. "table %S has %d columns but %d values were supplied",
  110539. pTabList, 0, pTab->nCol-nHidden, nColumn);
  110540. goto insert_cleanup;
  110541. }
  110542. if( pColumn!=0 && nColumn!=pColumn->nId ){
  110543. sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
  110544. goto insert_cleanup;
  110545. }
  110546. /* Initialize the count of rows to be inserted
  110547. */
  110548. if( (db->flags & SQLITE_CountRows)!=0
  110549. && !pParse->nested
  110550. && !pParse->pTriggerTab
  110551. ){
  110552. regRowCount = ++pParse->nMem;
  110553. sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
  110554. }
  110555. /* If this is not a view, open the table and and all indices */
  110556. if( !isView ){
  110557. int nIdx;
  110558. nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, -1, 0,
  110559. &iDataCur, &iIdxCur);
  110560. aRegIdx = sqlite3DbMallocRawNN(db, sizeof(int)*(nIdx+2));
  110561. if( aRegIdx==0 ){
  110562. goto insert_cleanup;
  110563. }
  110564. for(i=0, pIdx=pTab->pIndex; i<nIdx; pIdx=pIdx->pNext, i++){
  110565. assert( pIdx );
  110566. aRegIdx[i] = ++pParse->nMem;
  110567. pParse->nMem += pIdx->nColumn;
  110568. }
  110569. aRegIdx[i] = ++pParse->nMem; /* Register to store the table record */
  110570. }
  110571. #ifndef SQLITE_OMIT_UPSERT
  110572. if( pUpsert ){
  110573. if( IsVirtual(pTab) ){
  110574. sqlite3ErrorMsg(pParse, "UPSERT not implemented for virtual table \"%s\"",
  110575. pTab->zName);
  110576. goto insert_cleanup;
  110577. }
  110578. pTabList->a[0].iCursor = iDataCur;
  110579. pUpsert->pUpsertSrc = pTabList;
  110580. pUpsert->regData = regData;
  110581. pUpsert->iDataCur = iDataCur;
  110582. pUpsert->iIdxCur = iIdxCur;
  110583. if( pUpsert->pUpsertTarget ){
  110584. sqlite3UpsertAnalyzeTarget(pParse, pTabList, pUpsert);
  110585. }
  110586. }
  110587. #endif
  110588. /* This is the top of the main insertion loop */
  110589. if( useTempTable ){
  110590. /* This block codes the top of loop only. The complete loop is the
  110591. ** following pseudocode (template 4):
  110592. **
  110593. ** rewind temp table, if empty goto D
  110594. ** C: loop over rows of intermediate table
  110595. ** transfer values form intermediate table into <table>
  110596. ** end loop
  110597. ** D: ...
  110598. */
  110599. addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
  110600. addrCont = sqlite3VdbeCurrentAddr(v);
  110601. }else if( pSelect ){
  110602. /* This block codes the top of loop only. The complete loop is the
  110603. ** following pseudocode (template 3):
  110604. **
  110605. ** C: yield X, at EOF goto D
  110606. ** insert the select result into <table> from R..R+n
  110607. ** goto C
  110608. ** D: ...
  110609. */
  110610. addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
  110611. VdbeCoverage(v);
  110612. }
  110613. /* Run the BEFORE and INSTEAD OF triggers, if there are any
  110614. */
  110615. endOfLoop = sqlite3VdbeMakeLabel(pParse);
  110616. if( tmask & TRIGGER_BEFORE ){
  110617. int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
  110618. /* build the NEW.* reference row. Note that if there is an INTEGER
  110619. ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
  110620. ** translated into a unique ID for the row. But on a BEFORE trigger,
  110621. ** we do not know what the unique ID will be (because the insert has
  110622. ** not happened yet) so we substitute a rowid of -1
  110623. */
  110624. if( ipkColumn<0 ){
  110625. sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
  110626. }else{
  110627. int addr1;
  110628. assert( !withoutRowid );
  110629. if( useTempTable ){
  110630. sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
  110631. }else{
  110632. assert( pSelect==0 ); /* Otherwise useTempTable is true */
  110633. sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
  110634. }
  110635. addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
  110636. sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
  110637. sqlite3VdbeJumpHere(v, addr1);
  110638. sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
  110639. }
  110640. /* Cannot have triggers on a virtual table. If it were possible,
  110641. ** this block would have to account for hidden column.
  110642. */
  110643. assert( !IsVirtual(pTab) );
  110644. /* Create the new column data
  110645. */
  110646. for(i=j=0; i<pTab->nCol; i++){
  110647. if( pColumn ){
  110648. for(j=0; j<pColumn->nId; j++){
  110649. if( pColumn->a[j].idx==i ) break;
  110650. }
  110651. }
  110652. if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId)
  110653. || (pColumn==0 && IsOrdinaryHiddenColumn(&pTab->aCol[i])) ){
  110654. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
  110655. }else if( useTempTable ){
  110656. sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
  110657. }else{
  110658. assert( pSelect==0 ); /* Otherwise useTempTable is true */
  110659. sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
  110660. }
  110661. if( pColumn==0 && !IsOrdinaryHiddenColumn(&pTab->aCol[i]) ) j++;
  110662. }
  110663. /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
  110664. ** do not attempt any conversions before assembling the record.
  110665. ** If this is a real table, attempt conversions as required by the
  110666. ** table column affinities.
  110667. */
  110668. if( !isView ){
  110669. sqlite3TableAffinity(v, pTab, regCols+1);
  110670. }
  110671. /* Fire BEFORE or INSTEAD OF triggers */
  110672. sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
  110673. pTab, regCols-pTab->nCol-1, onError, endOfLoop);
  110674. sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
  110675. }
  110676. /* Compute the content of the next row to insert into a range of
  110677. ** registers beginning at regIns.
  110678. */
  110679. if( !isView ){
  110680. if( IsVirtual(pTab) ){
  110681. /* The row that the VUpdate opcode will delete: none */
  110682. sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
  110683. }
  110684. if( ipkColumn>=0 ){
  110685. if( useTempTable ){
  110686. sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
  110687. }else if( pSelect ){
  110688. sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
  110689. }else{
  110690. Expr *pIpk = pList->a[ipkColumn].pExpr;
  110691. if( pIpk->op==TK_NULL && !IsVirtual(pTab) ){
  110692. sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
  110693. appendFlag = 1;
  110694. }else{
  110695. sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
  110696. }
  110697. }
  110698. /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
  110699. ** to generate a unique primary key value.
  110700. */
  110701. if( !appendFlag ){
  110702. int addr1;
  110703. if( !IsVirtual(pTab) ){
  110704. addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
  110705. sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
  110706. sqlite3VdbeJumpHere(v, addr1);
  110707. }else{
  110708. addr1 = sqlite3VdbeCurrentAddr(v);
  110709. sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, addr1+2); VdbeCoverage(v);
  110710. }
  110711. sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
  110712. }
  110713. }else if( IsVirtual(pTab) || withoutRowid ){
  110714. sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
  110715. }else{
  110716. sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
  110717. appendFlag = 1;
  110718. }
  110719. autoIncStep(pParse, regAutoinc, regRowid);
  110720. /* Compute data for all columns of the new entry, beginning
  110721. ** with the first column.
  110722. */
  110723. nHidden = 0;
  110724. for(i=0; i<pTab->nCol; i++){
  110725. int iRegStore = regRowid+1+i;
  110726. if( i==pTab->iPKey ){
  110727. /* The value of the INTEGER PRIMARY KEY column is always a NULL.
  110728. ** Whenever this column is read, the rowid will be substituted
  110729. ** in its place. Hence, fill this column with a NULL to avoid
  110730. ** taking up data space with information that will never be used.
  110731. ** As there may be shallow copies of this value, make it a soft-NULL */
  110732. sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
  110733. continue;
  110734. }
  110735. if( pColumn==0 ){
  110736. if( IsHiddenColumn(&pTab->aCol[i]) ){
  110737. j = -1;
  110738. nHidden++;
  110739. }else{
  110740. j = i - nHidden;
  110741. }
  110742. }else{
  110743. for(j=0; j<pColumn->nId; j++){
  110744. if( pColumn->a[j].idx==i ) break;
  110745. }
  110746. }
  110747. if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
  110748. sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
  110749. }else if( useTempTable ){
  110750. sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
  110751. }else if( pSelect ){
  110752. if( regFromSelect!=regData ){
  110753. sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
  110754. }
  110755. }else{
  110756. sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
  110757. }
  110758. }
  110759. /* Generate code to check constraints and generate index keys and
  110760. ** do the insertion.
  110761. */
  110762. #ifndef SQLITE_OMIT_VIRTUALTABLE
  110763. if( IsVirtual(pTab) ){
  110764. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  110765. sqlite3VtabMakeWritable(pParse, pTab);
  110766. sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
  110767. sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
  110768. sqlite3MayAbort(pParse);
  110769. }else
  110770. #endif
  110771. {
  110772. int isReplace; /* Set to true if constraints may cause a replace */
  110773. int bUseSeek; /* True to use OPFLAG_SEEKRESULT */
  110774. sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
  110775. regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace, 0, pUpsert
  110776. );
  110777. sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
  110778. /* Set the OPFLAG_USESEEKRESULT flag if either (a) there are no REPLACE
  110779. ** constraints or (b) there are no triggers and this table is not a
  110780. ** parent table in a foreign key constraint. It is safe to set the
  110781. ** flag in the second case as if any REPLACE constraint is hit, an
  110782. ** OP_Delete or OP_IdxDelete instruction will be executed on each
  110783. ** cursor that is disturbed. And these instructions both clear the
  110784. ** VdbeCursor.seekResult variable, disabling the OPFLAG_USESEEKRESULT
  110785. ** functionality. */
  110786. bUseSeek = (isReplace==0 || (pTrigger==0 &&
  110787. ((db->flags & SQLITE_ForeignKeys)==0 || sqlite3FkReferences(pTab)==0)
  110788. ));
  110789. sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
  110790. regIns, aRegIdx, 0, appendFlag, bUseSeek
  110791. );
  110792. }
  110793. }
  110794. /* Update the count of rows that are inserted
  110795. */
  110796. if( regRowCount ){
  110797. sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
  110798. }
  110799. if( pTrigger ){
  110800. /* Code AFTER triggers */
  110801. sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
  110802. pTab, regData-2-pTab->nCol, onError, endOfLoop);
  110803. }
  110804. /* The bottom of the main insertion loop, if the data source
  110805. ** is a SELECT statement.
  110806. */
  110807. sqlite3VdbeResolveLabel(v, endOfLoop);
  110808. if( useTempTable ){
  110809. sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
  110810. sqlite3VdbeJumpHere(v, addrInsTop);
  110811. sqlite3VdbeAddOp1(v, OP_Close, srcTab);
  110812. }else if( pSelect ){
  110813. sqlite3VdbeGoto(v, addrCont);
  110814. sqlite3VdbeJumpHere(v, addrInsTop);
  110815. }
  110816. insert_end:
  110817. /* Update the sqlite_sequence table by storing the content of the
  110818. ** maximum rowid counter values recorded while inserting into
  110819. ** autoincrement tables.
  110820. */
  110821. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  110822. sqlite3AutoincrementEnd(pParse);
  110823. }
  110824. /*
  110825. ** Return the number of rows inserted. If this routine is
  110826. ** generating code because of a call to sqlite3NestedParse(), do not
  110827. ** invoke the callback function.
  110828. */
  110829. if( regRowCount ){
  110830. sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
  110831. sqlite3VdbeSetNumCols(v, 1);
  110832. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
  110833. }
  110834. insert_cleanup:
  110835. sqlite3SrcListDelete(db, pTabList);
  110836. sqlite3ExprListDelete(db, pList);
  110837. sqlite3UpsertDelete(db, pUpsert);
  110838. sqlite3SelectDelete(db, pSelect);
  110839. sqlite3IdListDelete(db, pColumn);
  110840. sqlite3DbFree(db, aRegIdx);
  110841. }
  110842. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  110843. ** they may interfere with compilation of other functions in this file
  110844. ** (or in another file, if this file becomes part of the amalgamation). */
  110845. #ifdef isView
  110846. #undef isView
  110847. #endif
  110848. #ifdef pTrigger
  110849. #undef pTrigger
  110850. #endif
  110851. #ifdef tmask
  110852. #undef tmask
  110853. #endif
  110854. /*
  110855. ** Meanings of bits in of pWalker->eCode for
  110856. ** sqlite3ExprReferencesUpdatedColumn()
  110857. */
  110858. #define CKCNSTRNT_COLUMN 0x01 /* CHECK constraint uses a changing column */
  110859. #define CKCNSTRNT_ROWID 0x02 /* CHECK constraint references the ROWID */
  110860. /* This is the Walker callback from sqlite3ExprReferencesUpdatedColumn().
  110861. * Set bit 0x01 of pWalker->eCode if pWalker->eCode to 0 and if this
  110862. ** expression node references any of the
  110863. ** columns that are being modifed by an UPDATE statement.
  110864. */
  110865. static int checkConstraintExprNode(Walker *pWalker, Expr *pExpr){
  110866. if( pExpr->op==TK_COLUMN ){
  110867. assert( pExpr->iColumn>=0 || pExpr->iColumn==-1 );
  110868. if( pExpr->iColumn>=0 ){
  110869. if( pWalker->u.aiCol[pExpr->iColumn]>=0 ){
  110870. pWalker->eCode |= CKCNSTRNT_COLUMN;
  110871. }
  110872. }else{
  110873. pWalker->eCode |= CKCNSTRNT_ROWID;
  110874. }
  110875. }
  110876. return WRC_Continue;
  110877. }
  110878. /*
  110879. ** pExpr is a CHECK constraint on a row that is being UPDATE-ed. The
  110880. ** only columns that are modified by the UPDATE are those for which
  110881. ** aiChng[i]>=0, and also the ROWID is modified if chngRowid is true.
  110882. **
  110883. ** Return true if CHECK constraint pExpr uses any of the
  110884. ** changing columns (or the rowid if it is changing). In other words,
  110885. ** return true if this CHECK constraint must be validated for
  110886. ** the new row in the UPDATE statement.
  110887. **
  110888. ** 2018-09-15: pExpr might also be an expression for an index-on-expressions.
  110889. ** The operation of this routine is the same - return true if an only if
  110890. ** the expression uses one or more of columns identified by the second and
  110891. ** third arguments.
  110892. */
  110893. SQLITE_PRIVATE int sqlite3ExprReferencesUpdatedColumn(
  110894. Expr *pExpr, /* The expression to be checked */
  110895. int *aiChng, /* aiChng[x]>=0 if column x changed by the UPDATE */
  110896. int chngRowid /* True if UPDATE changes the rowid */
  110897. ){
  110898. Walker w;
  110899. memset(&w, 0, sizeof(w));
  110900. w.eCode = 0;
  110901. w.xExprCallback = checkConstraintExprNode;
  110902. w.u.aiCol = aiChng;
  110903. sqlite3WalkExpr(&w, pExpr);
  110904. if( !chngRowid ){
  110905. testcase( (w.eCode & CKCNSTRNT_ROWID)!=0 );
  110906. w.eCode &= ~CKCNSTRNT_ROWID;
  110907. }
  110908. testcase( w.eCode==0 );
  110909. testcase( w.eCode==CKCNSTRNT_COLUMN );
  110910. testcase( w.eCode==CKCNSTRNT_ROWID );
  110911. testcase( w.eCode==(CKCNSTRNT_ROWID|CKCNSTRNT_COLUMN) );
  110912. return w.eCode!=0;
  110913. }
  110914. /*
  110915. ** Generate code to do constraint checks prior to an INSERT or an UPDATE
  110916. ** on table pTab.
  110917. **
  110918. ** The regNewData parameter is the first register in a range that contains
  110919. ** the data to be inserted or the data after the update. There will be
  110920. ** pTab->nCol+1 registers in this range. The first register (the one
  110921. ** that regNewData points to) will contain the new rowid, or NULL in the
  110922. ** case of a WITHOUT ROWID table. The second register in the range will
  110923. ** contain the content of the first table column. The third register will
  110924. ** contain the content of the second table column. And so forth.
  110925. **
  110926. ** The regOldData parameter is similar to regNewData except that it contains
  110927. ** the data prior to an UPDATE rather than afterwards. regOldData is zero
  110928. ** for an INSERT. This routine can distinguish between UPDATE and INSERT by
  110929. ** checking regOldData for zero.
  110930. **
  110931. ** For an UPDATE, the pkChng boolean is true if the true primary key (the
  110932. ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
  110933. ** might be modified by the UPDATE. If pkChng is false, then the key of
  110934. ** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
  110935. **
  110936. ** For an INSERT, the pkChng boolean indicates whether or not the rowid
  110937. ** was explicitly specified as part of the INSERT statement. If pkChng
  110938. ** is zero, it means that the either rowid is computed automatically or
  110939. ** that the table is a WITHOUT ROWID table and has no rowid. On an INSERT,
  110940. ** pkChng will only be true if the INSERT statement provides an integer
  110941. ** value for either the rowid column or its INTEGER PRIMARY KEY alias.
  110942. **
  110943. ** The code generated by this routine will store new index entries into
  110944. ** registers identified by aRegIdx[]. No index entry is created for
  110945. ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is
  110946. ** the same as the order of indices on the linked list of indices
  110947. ** at pTab->pIndex.
  110948. **
  110949. ** (2019-05-07) The generated code also creates a new record for the
  110950. ** main table, if pTab is a rowid table, and stores that record in the
  110951. ** register identified by aRegIdx[nIdx] - in other words in the first
  110952. ** entry of aRegIdx[] past the last index. It is important that the
  110953. ** record be generated during constraint checks to avoid affinity changes
  110954. ** to the register content that occur after constraint checks but before
  110955. ** the new record is inserted.
  110956. **
  110957. ** The caller must have already opened writeable cursors on the main
  110958. ** table and all applicable indices (that is to say, all indices for which
  110959. ** aRegIdx[] is not zero). iDataCur is the cursor for the main table when
  110960. ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
  110961. ** index when operating on a WITHOUT ROWID table. iIdxCur is the cursor
  110962. ** for the first index in the pTab->pIndex list. Cursors for other indices
  110963. ** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
  110964. **
  110965. ** This routine also generates code to check constraints. NOT NULL,
  110966. ** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
  110967. ** then the appropriate action is performed. There are five possible
  110968. ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
  110969. **
  110970. ** Constraint type Action What Happens
  110971. ** --------------- ---------- ----------------------------------------
  110972. ** any ROLLBACK The current transaction is rolled back and
  110973. ** sqlite3_step() returns immediately with a
  110974. ** return code of SQLITE_CONSTRAINT.
  110975. **
  110976. ** any ABORT Back out changes from the current command
  110977. ** only (do not do a complete rollback) then
  110978. ** cause sqlite3_step() to return immediately
  110979. ** with SQLITE_CONSTRAINT.
  110980. **
  110981. ** any FAIL Sqlite3_step() returns immediately with a
  110982. ** return code of SQLITE_CONSTRAINT. The
  110983. ** transaction is not rolled back and any
  110984. ** changes to prior rows are retained.
  110985. **
  110986. ** any IGNORE The attempt in insert or update the current
  110987. ** row is skipped, without throwing an error.
  110988. ** Processing continues with the next row.
  110989. ** (There is an immediate jump to ignoreDest.)
  110990. **
  110991. ** NOT NULL REPLACE The NULL value is replace by the default
  110992. ** value for that column. If the default value
  110993. ** is NULL, the action is the same as ABORT.
  110994. **
  110995. ** UNIQUE REPLACE The other row that conflicts with the row
  110996. ** being inserted is removed.
  110997. **
  110998. ** CHECK REPLACE Illegal. The results in an exception.
  110999. **
  111000. ** Which action to take is determined by the overrideError parameter.
  111001. ** Or if overrideError==OE_Default, then the pParse->onError parameter
  111002. ** is used. Or if pParse->onError==OE_Default then the onError value
  111003. ** for the constraint is used.
  111004. */
  111005. SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
  111006. Parse *pParse, /* The parser context */
  111007. Table *pTab, /* The table being inserted or updated */
  111008. int *aRegIdx, /* Use register aRegIdx[i] for index i. 0 for unused */
  111009. int iDataCur, /* Canonical data cursor (main table or PK index) */
  111010. int iIdxCur, /* First index cursor */
  111011. int regNewData, /* First register in a range holding values to insert */
  111012. int regOldData, /* Previous content. 0 for INSERTs */
  111013. u8 pkChng, /* Non-zero if the rowid or PRIMARY KEY changed */
  111014. u8 overrideError, /* Override onError to this if not OE_Default */
  111015. int ignoreDest, /* Jump to this label on an OE_Ignore resolution */
  111016. int *pbMayReplace, /* OUT: Set to true if constraint may cause a replace */
  111017. int *aiChng, /* column i is unchanged if aiChng[i]<0 */
  111018. Upsert *pUpsert /* ON CONFLICT clauses, if any. NULL otherwise */
  111019. ){
  111020. Vdbe *v; /* VDBE under constrution */
  111021. Index *pIdx; /* Pointer to one of the indices */
  111022. Index *pPk = 0; /* The PRIMARY KEY index */
  111023. sqlite3 *db; /* Database connection */
  111024. int i; /* loop counter */
  111025. int ix; /* Index loop counter */
  111026. int nCol; /* Number of columns */
  111027. int onError; /* Conflict resolution strategy */
  111028. int addr1; /* Address of jump instruction */
  111029. int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
  111030. int nPkField; /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
  111031. Index *pUpIdx = 0; /* Index to which to apply the upsert */
  111032. u8 isUpdate; /* True if this is an UPDATE operation */
  111033. u8 bAffinityDone = 0; /* True if the OP_Affinity operation has been run */
  111034. int upsertBypass = 0; /* Address of Goto to bypass upsert subroutine */
  111035. int upsertJump = 0; /* Address of Goto that jumps into upsert subroutine */
  111036. int ipkTop = 0; /* Top of the IPK uniqueness check */
  111037. int ipkBottom = 0; /* OP_Goto at the end of the IPK uniqueness check */
  111038. isUpdate = regOldData!=0;
  111039. db = pParse->db;
  111040. v = sqlite3GetVdbe(pParse);
  111041. assert( v!=0 );
  111042. assert( pTab->pSelect==0 ); /* This table is not a VIEW */
  111043. nCol = pTab->nCol;
  111044. /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
  111045. ** normal rowid tables. nPkField is the number of key fields in the
  111046. ** pPk index or 1 for a rowid table. In other words, nPkField is the
  111047. ** number of fields in the true primary key of the table. */
  111048. if( HasRowid(pTab) ){
  111049. pPk = 0;
  111050. nPkField = 1;
  111051. }else{
  111052. pPk = sqlite3PrimaryKeyIndex(pTab);
  111053. nPkField = pPk->nKeyCol;
  111054. }
  111055. /* Record that this module has started */
  111056. VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
  111057. iDataCur, iIdxCur, regNewData, regOldData, pkChng));
  111058. /* Test all NOT NULL constraints.
  111059. */
  111060. for(i=0; i<nCol; i++){
  111061. if( i==pTab->iPKey ){
  111062. continue; /* ROWID is never NULL */
  111063. }
  111064. if( aiChng && aiChng[i]<0 ){
  111065. /* Don't bother checking for NOT NULL on columns that do not change */
  111066. continue;
  111067. }
  111068. onError = pTab->aCol[i].notNull;
  111069. if( onError==OE_None ) continue; /* This column is allowed to be NULL */
  111070. if( overrideError!=OE_Default ){
  111071. onError = overrideError;
  111072. }else if( onError==OE_Default ){
  111073. onError = OE_Abort;
  111074. }
  111075. if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
  111076. onError = OE_Abort;
  111077. }
  111078. assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
  111079. || onError==OE_Ignore || onError==OE_Replace );
  111080. addr1 = 0;
  111081. switch( onError ){
  111082. case OE_Replace: {
  111083. assert( onError==OE_Replace );
  111084. addr1 = sqlite3VdbeMakeLabel(pParse);
  111085. sqlite3VdbeAddOp2(v, OP_NotNull, regNewData+1+i, addr1);
  111086. VdbeCoverage(v);
  111087. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i);
  111088. sqlite3VdbeAddOp2(v, OP_NotNull, regNewData+1+i, addr1);
  111089. VdbeCoverage(v);
  111090. onError = OE_Abort;
  111091. /* Fall through into the OE_Abort case to generate code that runs
  111092. ** if both the input and the default value are NULL */
  111093. }
  111094. case OE_Abort:
  111095. sqlite3MayAbort(pParse);
  111096. /* Fall through */
  111097. case OE_Rollback:
  111098. case OE_Fail: {
  111099. char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
  111100. pTab->aCol[i].zName);
  111101. sqlite3VdbeAddOp3(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError,
  111102. regNewData+1+i);
  111103. sqlite3VdbeAppendP4(v, zMsg, P4_DYNAMIC);
  111104. sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
  111105. VdbeCoverage(v);
  111106. if( addr1 ) sqlite3VdbeResolveLabel(v, addr1);
  111107. break;
  111108. }
  111109. default: {
  111110. assert( onError==OE_Ignore );
  111111. sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest);
  111112. VdbeCoverage(v);
  111113. break;
  111114. }
  111115. }
  111116. }
  111117. /* Test all CHECK constraints
  111118. */
  111119. #ifndef SQLITE_OMIT_CHECK
  111120. if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
  111121. ExprList *pCheck = pTab->pCheck;
  111122. pParse->iSelfTab = -(regNewData+1);
  111123. onError = overrideError!=OE_Default ? overrideError : OE_Abort;
  111124. for(i=0; i<pCheck->nExpr; i++){
  111125. int allOk;
  111126. Expr *pExpr = pCheck->a[i].pExpr;
  111127. if( aiChng
  111128. && !sqlite3ExprReferencesUpdatedColumn(pExpr, aiChng, pkChng)
  111129. ){
  111130. /* The check constraints do not reference any of the columns being
  111131. ** updated so there is no point it verifying the check constraint */
  111132. continue;
  111133. }
  111134. allOk = sqlite3VdbeMakeLabel(pParse);
  111135. sqlite3VdbeVerifyAbortable(v, onError);
  111136. sqlite3ExprIfTrue(pParse, pExpr, allOk, SQLITE_JUMPIFNULL);
  111137. if( onError==OE_Ignore ){
  111138. sqlite3VdbeGoto(v, ignoreDest);
  111139. }else{
  111140. char *zName = pCheck->a[i].zName;
  111141. if( zName==0 ) zName = pTab->zName;
  111142. if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-26383-51744 */
  111143. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
  111144. onError, zName, P4_TRANSIENT,
  111145. P5_ConstraintCheck);
  111146. }
  111147. sqlite3VdbeResolveLabel(v, allOk);
  111148. }
  111149. pParse->iSelfTab = 0;
  111150. }
  111151. #endif /* !defined(SQLITE_OMIT_CHECK) */
  111152. /* UNIQUE and PRIMARY KEY constraints should be handled in the following
  111153. ** order:
  111154. **
  111155. ** (1) OE_Update
  111156. ** (2) OE_Abort, OE_Fail, OE_Rollback, OE_Ignore
  111157. ** (3) OE_Replace
  111158. **
  111159. ** OE_Fail and OE_Ignore must happen before any changes are made.
  111160. ** OE_Update guarantees that only a single row will change, so it
  111161. ** must happen before OE_Replace. Technically, OE_Abort and OE_Rollback
  111162. ** could happen in any order, but they are grouped up front for
  111163. ** convenience.
  111164. **
  111165. ** 2018-08-14: Ticket https://www.sqlite.org/src/info/908f001483982c43
  111166. ** The order of constraints used to have OE_Update as (2) and OE_Abort
  111167. ** and so forth as (1). But apparently PostgreSQL checks the OE_Update
  111168. ** constraint before any others, so it had to be moved.
  111169. **
  111170. ** Constraint checking code is generated in this order:
  111171. ** (A) The rowid constraint
  111172. ** (B) Unique index constraints that do not have OE_Replace as their
  111173. ** default conflict resolution strategy
  111174. ** (C) Unique index that do use OE_Replace by default.
  111175. **
  111176. ** The ordering of (2) and (3) is accomplished by making sure the linked
  111177. ** list of indexes attached to a table puts all OE_Replace indexes last
  111178. ** in the list. See sqlite3CreateIndex() for where that happens.
  111179. */
  111180. if( pUpsert ){
  111181. if( pUpsert->pUpsertTarget==0 ){
  111182. /* An ON CONFLICT DO NOTHING clause, without a constraint-target.
  111183. ** Make all unique constraint resolution be OE_Ignore */
  111184. assert( pUpsert->pUpsertSet==0 );
  111185. overrideError = OE_Ignore;
  111186. pUpsert = 0;
  111187. }else if( (pUpIdx = pUpsert->pUpsertIdx)!=0 ){
  111188. /* If the constraint-target uniqueness check must be run first.
  111189. ** Jump to that uniqueness check now */
  111190. upsertJump = sqlite3VdbeAddOp0(v, OP_Goto);
  111191. VdbeComment((v, "UPSERT constraint goes first"));
  111192. }
  111193. }
  111194. /* If rowid is changing, make sure the new rowid does not previously
  111195. ** exist in the table.
  111196. */
  111197. if( pkChng && pPk==0 ){
  111198. int addrRowidOk = sqlite3VdbeMakeLabel(pParse);
  111199. /* Figure out what action to take in case of a rowid collision */
  111200. onError = pTab->keyConf;
  111201. if( overrideError!=OE_Default ){
  111202. onError = overrideError;
  111203. }else if( onError==OE_Default ){
  111204. onError = OE_Abort;
  111205. }
  111206. /* figure out whether or not upsert applies in this case */
  111207. if( pUpsert && pUpsert->pUpsertIdx==0 ){
  111208. if( pUpsert->pUpsertSet==0 ){
  111209. onError = OE_Ignore; /* DO NOTHING is the same as INSERT OR IGNORE */
  111210. }else{
  111211. onError = OE_Update; /* DO UPDATE */
  111212. }
  111213. }
  111214. /* If the response to a rowid conflict is REPLACE but the response
  111215. ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
  111216. ** to defer the running of the rowid conflict checking until after
  111217. ** the UNIQUE constraints have run.
  111218. */
  111219. if( onError==OE_Replace /* IPK rule is REPLACE */
  111220. && onError!=overrideError /* Rules for other contraints are different */
  111221. && pTab->pIndex /* There exist other constraints */
  111222. ){
  111223. ipkTop = sqlite3VdbeAddOp0(v, OP_Goto)+1;
  111224. VdbeComment((v, "defer IPK REPLACE until last"));
  111225. }
  111226. if( isUpdate ){
  111227. /* pkChng!=0 does not mean that the rowid has changed, only that
  111228. ** it might have changed. Skip the conflict logic below if the rowid
  111229. ** is unchanged. */
  111230. sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
  111231. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  111232. VdbeCoverage(v);
  111233. }
  111234. /* Check to see if the new rowid already exists in the table. Skip
  111235. ** the following conflict logic if it does not. */
  111236. VdbeNoopComment((v, "uniqueness check for ROWID"));
  111237. sqlite3VdbeVerifyAbortable(v, onError);
  111238. sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
  111239. VdbeCoverage(v);
  111240. switch( onError ){
  111241. default: {
  111242. onError = OE_Abort;
  111243. /* Fall thru into the next case */
  111244. }
  111245. case OE_Rollback:
  111246. case OE_Abort:
  111247. case OE_Fail: {
  111248. testcase( onError==OE_Rollback );
  111249. testcase( onError==OE_Abort );
  111250. testcase( onError==OE_Fail );
  111251. sqlite3RowidConstraint(pParse, onError, pTab);
  111252. break;
  111253. }
  111254. case OE_Replace: {
  111255. /* If there are DELETE triggers on this table and the
  111256. ** recursive-triggers flag is set, call GenerateRowDelete() to
  111257. ** remove the conflicting row from the table. This will fire
  111258. ** the triggers and remove both the table and index b-tree entries.
  111259. **
  111260. ** Otherwise, if there are no triggers or the recursive-triggers
  111261. ** flag is not set, but the table has one or more indexes, call
  111262. ** GenerateRowIndexDelete(). This removes the index b-tree entries
  111263. ** only. The table b-tree entry will be replaced by the new entry
  111264. ** when it is inserted.
  111265. **
  111266. ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
  111267. ** also invoke MultiWrite() to indicate that this VDBE may require
  111268. ** statement rollback (if the statement is aborted after the delete
  111269. ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
  111270. ** but being more selective here allows statements like:
  111271. **
  111272. ** REPLACE INTO t(rowid) VALUES($newrowid)
  111273. **
  111274. ** to run without a statement journal if there are no indexes on the
  111275. ** table.
  111276. */
  111277. Trigger *pTrigger = 0;
  111278. if( db->flags&SQLITE_RecTriggers ){
  111279. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  111280. }
  111281. if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
  111282. sqlite3MultiWrite(pParse);
  111283. sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
  111284. regNewData, 1, 0, OE_Replace, 1, -1);
  111285. }else{
  111286. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  111287. assert( HasRowid(pTab) );
  111288. /* This OP_Delete opcode fires the pre-update-hook only. It does
  111289. ** not modify the b-tree. It is more efficient to let the coming
  111290. ** OP_Insert replace the existing entry than it is to delete the
  111291. ** existing entry and then insert a new one. */
  111292. sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, OPFLAG_ISNOOP);
  111293. sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
  111294. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  111295. if( pTab->pIndex ){
  111296. sqlite3MultiWrite(pParse);
  111297. sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1);
  111298. }
  111299. }
  111300. seenReplace = 1;
  111301. break;
  111302. }
  111303. #ifndef SQLITE_OMIT_UPSERT
  111304. case OE_Update: {
  111305. sqlite3UpsertDoUpdate(pParse, pUpsert, pTab, 0, iDataCur);
  111306. /* Fall through */
  111307. }
  111308. #endif
  111309. case OE_Ignore: {
  111310. testcase( onError==OE_Ignore );
  111311. sqlite3VdbeGoto(v, ignoreDest);
  111312. break;
  111313. }
  111314. }
  111315. sqlite3VdbeResolveLabel(v, addrRowidOk);
  111316. if( ipkTop ){
  111317. ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
  111318. sqlite3VdbeJumpHere(v, ipkTop-1);
  111319. }
  111320. }
  111321. /* Test all UNIQUE constraints by creating entries for each UNIQUE
  111322. ** index and making sure that duplicate entries do not already exist.
  111323. ** Compute the revised record entries for indices as we go.
  111324. **
  111325. ** This loop also handles the case of the PRIMARY KEY index for a
  111326. ** WITHOUT ROWID table.
  111327. */
  111328. for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){
  111329. int regIdx; /* Range of registers hold conent for pIdx */
  111330. int regR; /* Range of registers holding conflicting PK */
  111331. int iThisCur; /* Cursor for this UNIQUE index */
  111332. int addrUniqueOk; /* Jump here if the UNIQUE constraint is satisfied */
  111333. if( aRegIdx[ix]==0 ) continue; /* Skip indices that do not change */
  111334. if( pUpIdx==pIdx ){
  111335. addrUniqueOk = upsertJump+1;
  111336. upsertBypass = sqlite3VdbeGoto(v, 0);
  111337. VdbeComment((v, "Skip upsert subroutine"));
  111338. sqlite3VdbeJumpHere(v, upsertJump);
  111339. }else{
  111340. addrUniqueOk = sqlite3VdbeMakeLabel(pParse);
  111341. }
  111342. if( bAffinityDone==0 && (pUpIdx==0 || pUpIdx==pIdx) ){
  111343. sqlite3TableAffinity(v, pTab, regNewData+1);
  111344. bAffinityDone = 1;
  111345. }
  111346. VdbeNoopComment((v, "uniqueness check for %s", pIdx->zName));
  111347. iThisCur = iIdxCur+ix;
  111348. /* Skip partial indices for which the WHERE clause is not true */
  111349. if( pIdx->pPartIdxWhere ){
  111350. sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
  111351. pParse->iSelfTab = -(regNewData+1);
  111352. sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
  111353. SQLITE_JUMPIFNULL);
  111354. pParse->iSelfTab = 0;
  111355. }
  111356. /* Create a record for this index entry as it should appear after
  111357. ** the insert or update. Store that record in the aRegIdx[ix] register
  111358. */
  111359. regIdx = aRegIdx[ix]+1;
  111360. for(i=0; i<pIdx->nColumn; i++){
  111361. int iField = pIdx->aiColumn[i];
  111362. int x;
  111363. if( iField==XN_EXPR ){
  111364. pParse->iSelfTab = -(regNewData+1);
  111365. sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i);
  111366. pParse->iSelfTab = 0;
  111367. VdbeComment((v, "%s column %d", pIdx->zName, i));
  111368. }else{
  111369. if( iField==XN_ROWID || iField==pTab->iPKey ){
  111370. x = regNewData;
  111371. }else{
  111372. x = iField + regNewData + 1;
  111373. }
  111374. sqlite3VdbeAddOp2(v, iField<0 ? OP_IntCopy : OP_SCopy, x, regIdx+i);
  111375. VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName));
  111376. }
  111377. }
  111378. sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
  111379. VdbeComment((v, "for %s", pIdx->zName));
  111380. #ifdef SQLITE_ENABLE_NULL_TRIM
  111381. if( pIdx->idxType==SQLITE_IDXTYPE_PRIMARYKEY ){
  111382. sqlite3SetMakeRecordP5(v, pIdx->pTable);
  111383. }
  111384. #endif
  111385. /* In an UPDATE operation, if this index is the PRIMARY KEY index
  111386. ** of a WITHOUT ROWID table and there has been no change the
  111387. ** primary key, then no collision is possible. The collision detection
  111388. ** logic below can all be skipped. */
  111389. if( isUpdate && pPk==pIdx && pkChng==0 ){
  111390. sqlite3VdbeResolveLabel(v, addrUniqueOk);
  111391. continue;
  111392. }
  111393. /* Find out what action to take in case there is a uniqueness conflict */
  111394. onError = pIdx->onError;
  111395. if( onError==OE_None ){
  111396. sqlite3VdbeResolveLabel(v, addrUniqueOk);
  111397. continue; /* pIdx is not a UNIQUE index */
  111398. }
  111399. if( overrideError!=OE_Default ){
  111400. onError = overrideError;
  111401. }else if( onError==OE_Default ){
  111402. onError = OE_Abort;
  111403. }
  111404. /* Figure out if the upsert clause applies to this index */
  111405. if( pUpIdx==pIdx ){
  111406. if( pUpsert->pUpsertSet==0 ){
  111407. onError = OE_Ignore; /* DO NOTHING is the same as INSERT OR IGNORE */
  111408. }else{
  111409. onError = OE_Update; /* DO UPDATE */
  111410. }
  111411. }
  111412. /* Collision detection may be omitted if all of the following are true:
  111413. ** (1) The conflict resolution algorithm is REPLACE
  111414. ** (2) The table is a WITHOUT ROWID table
  111415. ** (3) There are no secondary indexes on the table
  111416. ** (4) No delete triggers need to be fired if there is a conflict
  111417. ** (5) No FK constraint counters need to be updated if a conflict occurs.
  111418. **
  111419. ** This is not possible for ENABLE_PREUPDATE_HOOK builds, as the row
  111420. ** must be explicitly deleted in order to ensure any pre-update hook
  111421. ** is invoked. */
  111422. #ifndef SQLITE_ENABLE_PREUPDATE_HOOK
  111423. if( (ix==0 && pIdx->pNext==0) /* Condition 3 */
  111424. && pPk==pIdx /* Condition 2 */
  111425. && onError==OE_Replace /* Condition 1 */
  111426. && ( 0==(db->flags&SQLITE_RecTriggers) || /* Condition 4 */
  111427. 0==sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0))
  111428. && ( 0==(db->flags&SQLITE_ForeignKeys) || /* Condition 5 */
  111429. (0==pTab->pFKey && 0==sqlite3FkReferences(pTab)))
  111430. ){
  111431. sqlite3VdbeResolveLabel(v, addrUniqueOk);
  111432. continue;
  111433. }
  111434. #endif /* ifndef SQLITE_ENABLE_PREUPDATE_HOOK */
  111435. /* Check to see if the new index entry will be unique */
  111436. sqlite3VdbeVerifyAbortable(v, onError);
  111437. sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
  111438. regIdx, pIdx->nKeyCol); VdbeCoverage(v);
  111439. /* Generate code to handle collisions */
  111440. regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField);
  111441. if( isUpdate || onError==OE_Replace ){
  111442. if( HasRowid(pTab) ){
  111443. sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
  111444. /* Conflict only if the rowid of the existing index entry
  111445. ** is different from old-rowid */
  111446. if( isUpdate ){
  111447. sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
  111448. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  111449. VdbeCoverage(v);
  111450. }
  111451. }else{
  111452. int x;
  111453. /* Extract the PRIMARY KEY from the end of the index entry and
  111454. ** store it in registers regR..regR+nPk-1 */
  111455. if( pIdx!=pPk ){
  111456. for(i=0; i<pPk->nKeyCol; i++){
  111457. assert( pPk->aiColumn[i]>=0 );
  111458. x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]);
  111459. sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
  111460. VdbeComment((v, "%s.%s", pTab->zName,
  111461. pTab->aCol[pPk->aiColumn[i]].zName));
  111462. }
  111463. }
  111464. if( isUpdate ){
  111465. /* If currently processing the PRIMARY KEY of a WITHOUT ROWID
  111466. ** table, only conflict if the new PRIMARY KEY values are actually
  111467. ** different from the old.
  111468. **
  111469. ** For a UNIQUE index, only conflict if the PRIMARY KEY values
  111470. ** of the matched index row are different from the original PRIMARY
  111471. ** KEY values of this row before the update. */
  111472. int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
  111473. int op = OP_Ne;
  111474. int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR);
  111475. for(i=0; i<pPk->nKeyCol; i++){
  111476. char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
  111477. x = pPk->aiColumn[i];
  111478. assert( x>=0 );
  111479. if( i==(pPk->nKeyCol-1) ){
  111480. addrJump = addrUniqueOk;
  111481. op = OP_Eq;
  111482. }
  111483. sqlite3VdbeAddOp4(v, op,
  111484. regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
  111485. );
  111486. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  111487. VdbeCoverageIf(v, op==OP_Eq);
  111488. VdbeCoverageIf(v, op==OP_Ne);
  111489. }
  111490. }
  111491. }
  111492. }
  111493. /* Generate code that executes if the new index entry is not unique */
  111494. assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
  111495. || onError==OE_Ignore || onError==OE_Replace || onError==OE_Update );
  111496. switch( onError ){
  111497. case OE_Rollback:
  111498. case OE_Abort:
  111499. case OE_Fail: {
  111500. testcase( onError==OE_Rollback );
  111501. testcase( onError==OE_Abort );
  111502. testcase( onError==OE_Fail );
  111503. sqlite3UniqueConstraint(pParse, onError, pIdx);
  111504. break;
  111505. }
  111506. #ifndef SQLITE_OMIT_UPSERT
  111507. case OE_Update: {
  111508. sqlite3UpsertDoUpdate(pParse, pUpsert, pTab, pIdx, iIdxCur+ix);
  111509. /* Fall through */
  111510. }
  111511. #endif
  111512. case OE_Ignore: {
  111513. testcase( onError==OE_Ignore );
  111514. sqlite3VdbeGoto(v, ignoreDest);
  111515. break;
  111516. }
  111517. default: {
  111518. Trigger *pTrigger = 0;
  111519. assert( onError==OE_Replace );
  111520. if( db->flags&SQLITE_RecTriggers ){
  111521. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  111522. }
  111523. if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
  111524. sqlite3MultiWrite(pParse);
  111525. }
  111526. sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
  111527. regR, nPkField, 0, OE_Replace,
  111528. (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), iThisCur);
  111529. seenReplace = 1;
  111530. break;
  111531. }
  111532. }
  111533. if( pUpIdx==pIdx ){
  111534. sqlite3VdbeGoto(v, upsertJump+1);
  111535. sqlite3VdbeJumpHere(v, upsertBypass);
  111536. }else{
  111537. sqlite3VdbeResolveLabel(v, addrUniqueOk);
  111538. }
  111539. if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
  111540. }
  111541. /* If the IPK constraint is a REPLACE, run it last */
  111542. if( ipkTop ){
  111543. sqlite3VdbeGoto(v, ipkTop);
  111544. VdbeComment((v, "Do IPK REPLACE"));
  111545. sqlite3VdbeJumpHere(v, ipkBottom);
  111546. }
  111547. /* Generate the table record */
  111548. if( HasRowid(pTab) ){
  111549. int regRec = aRegIdx[ix];
  111550. sqlite3VdbeAddOp3(v, OP_MakeRecord, regNewData+1, pTab->nCol, regRec);
  111551. sqlite3SetMakeRecordP5(v, pTab);
  111552. if( !bAffinityDone ){
  111553. sqlite3TableAffinity(v, pTab, 0);
  111554. }
  111555. }
  111556. *pbMayReplace = seenReplace;
  111557. VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
  111558. }
  111559. #ifdef SQLITE_ENABLE_NULL_TRIM
  111560. /*
  111561. ** Change the P5 operand on the last opcode (which should be an OP_MakeRecord)
  111562. ** to be the number of columns in table pTab that must not be NULL-trimmed.
  111563. **
  111564. ** Or if no columns of pTab may be NULL-trimmed, leave P5 at zero.
  111565. */
  111566. SQLITE_PRIVATE void sqlite3SetMakeRecordP5(Vdbe *v, Table *pTab){
  111567. u16 i;
  111568. /* Records with omitted columns are only allowed for schema format
  111569. ** version 2 and later (SQLite version 3.1.4, 2005-02-20). */
  111570. if( pTab->pSchema->file_format<2 ) return;
  111571. for(i=pTab->nCol-1; i>0; i--){
  111572. if( pTab->aCol[i].pDflt!=0 ) break;
  111573. if( pTab->aCol[i].colFlags & COLFLAG_PRIMKEY ) break;
  111574. }
  111575. sqlite3VdbeChangeP5(v, i+1);
  111576. }
  111577. #endif
  111578. /*
  111579. ** This routine generates code to finish the INSERT or UPDATE operation
  111580. ** that was started by a prior call to sqlite3GenerateConstraintChecks.
  111581. ** A consecutive range of registers starting at regNewData contains the
  111582. ** rowid and the content to be inserted.
  111583. **
  111584. ** The arguments to this routine should be the same as the first six
  111585. ** arguments to sqlite3GenerateConstraintChecks.
  111586. */
  111587. SQLITE_PRIVATE void sqlite3CompleteInsertion(
  111588. Parse *pParse, /* The parser context */
  111589. Table *pTab, /* the table into which we are inserting */
  111590. int iDataCur, /* Cursor of the canonical data source */
  111591. int iIdxCur, /* First index cursor */
  111592. int regNewData, /* Range of content */
  111593. int *aRegIdx, /* Register used by each index. 0 for unused indices */
  111594. int update_flags, /* True for UPDATE, False for INSERT */
  111595. int appendBias, /* True if this is likely to be an append */
  111596. int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
  111597. ){
  111598. Vdbe *v; /* Prepared statements under construction */
  111599. Index *pIdx; /* An index being inserted or updated */
  111600. u8 pik_flags; /* flag values passed to the btree insert */
  111601. int i; /* Loop counter */
  111602. assert( update_flags==0
  111603. || update_flags==OPFLAG_ISUPDATE
  111604. || update_flags==(OPFLAG_ISUPDATE|OPFLAG_SAVEPOSITION)
  111605. );
  111606. v = sqlite3GetVdbe(pParse);
  111607. assert( v!=0 );
  111608. assert( pTab->pSelect==0 ); /* This table is not a VIEW */
  111609. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  111610. if( aRegIdx[i]==0 ) continue;
  111611. if( pIdx->pPartIdxWhere ){
  111612. sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
  111613. VdbeCoverage(v);
  111614. }
  111615. pik_flags = (useSeekResult ? OPFLAG_USESEEKRESULT : 0);
  111616. if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
  111617. assert( pParse->nested==0 );
  111618. pik_flags |= OPFLAG_NCHANGE;
  111619. pik_flags |= (update_flags & OPFLAG_SAVEPOSITION);
  111620. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  111621. if( update_flags==0 ){
  111622. int r = sqlite3GetTempReg(pParse);
  111623. sqlite3VdbeAddOp2(v, OP_Integer, 0, r);
  111624. sqlite3VdbeAddOp4(v, OP_Insert,
  111625. iIdxCur+i, aRegIdx[i], r, (char*)pTab, P4_TABLE
  111626. );
  111627. sqlite3VdbeChangeP5(v, OPFLAG_ISNOOP);
  111628. sqlite3ReleaseTempReg(pParse, r);
  111629. }
  111630. #endif
  111631. }
  111632. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i],
  111633. aRegIdx[i]+1,
  111634. pIdx->uniqNotNull ? pIdx->nKeyCol: pIdx->nColumn);
  111635. sqlite3VdbeChangeP5(v, pik_flags);
  111636. }
  111637. if( !HasRowid(pTab) ) return;
  111638. if( pParse->nested ){
  111639. pik_flags = 0;
  111640. }else{
  111641. pik_flags = OPFLAG_NCHANGE;
  111642. pik_flags |= (update_flags?update_flags:OPFLAG_LASTROWID);
  111643. }
  111644. if( appendBias ){
  111645. pik_flags |= OPFLAG_APPEND;
  111646. }
  111647. if( useSeekResult ){
  111648. pik_flags |= OPFLAG_USESEEKRESULT;
  111649. }
  111650. sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, aRegIdx[i], regNewData);
  111651. if( !pParse->nested ){
  111652. sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
  111653. }
  111654. sqlite3VdbeChangeP5(v, pik_flags);
  111655. }
  111656. /*
  111657. ** Allocate cursors for the pTab table and all its indices and generate
  111658. ** code to open and initialized those cursors.
  111659. **
  111660. ** The cursor for the object that contains the complete data (normally
  111661. ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
  111662. ** ROWID table) is returned in *piDataCur. The first index cursor is
  111663. ** returned in *piIdxCur. The number of indices is returned.
  111664. **
  111665. ** Use iBase as the first cursor (either the *piDataCur for rowid tables
  111666. ** or the first index for WITHOUT ROWID tables) if it is non-negative.
  111667. ** If iBase is negative, then allocate the next available cursor.
  111668. **
  111669. ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
  111670. ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
  111671. ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
  111672. ** pTab->pIndex list.
  111673. **
  111674. ** If pTab is a virtual table, then this routine is a no-op and the
  111675. ** *piDataCur and *piIdxCur values are left uninitialized.
  111676. */
  111677. SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
  111678. Parse *pParse, /* Parsing context */
  111679. Table *pTab, /* Table to be opened */
  111680. int op, /* OP_OpenRead or OP_OpenWrite */
  111681. u8 p5, /* P5 value for OP_Open* opcodes (except on WITHOUT ROWID) */
  111682. int iBase, /* Use this for the table cursor, if there is one */
  111683. u8 *aToOpen, /* If not NULL: boolean for each table and index */
  111684. int *piDataCur, /* Write the database source cursor number here */
  111685. int *piIdxCur /* Write the first index cursor number here */
  111686. ){
  111687. int i;
  111688. int iDb;
  111689. int iDataCur;
  111690. Index *pIdx;
  111691. Vdbe *v;
  111692. assert( op==OP_OpenRead || op==OP_OpenWrite );
  111693. assert( op==OP_OpenWrite || p5==0 );
  111694. if( IsVirtual(pTab) ){
  111695. /* This routine is a no-op for virtual tables. Leave the output
  111696. ** variables *piDataCur and *piIdxCur uninitialized so that valgrind
  111697. ** can detect if they are used by mistake in the caller. */
  111698. return 0;
  111699. }
  111700. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  111701. v = sqlite3GetVdbe(pParse);
  111702. assert( v!=0 );
  111703. if( iBase<0 ) iBase = pParse->nTab;
  111704. iDataCur = iBase++;
  111705. if( piDataCur ) *piDataCur = iDataCur;
  111706. if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
  111707. sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
  111708. }else{
  111709. sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
  111710. }
  111711. if( piIdxCur ) *piIdxCur = iBase;
  111712. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  111713. int iIdxCur = iBase++;
  111714. assert( pIdx->pSchema==pTab->pSchema );
  111715. if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
  111716. if( piDataCur ) *piDataCur = iIdxCur;
  111717. p5 = 0;
  111718. }
  111719. if( aToOpen==0 || aToOpen[i+1] ){
  111720. sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
  111721. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  111722. sqlite3VdbeChangeP5(v, p5);
  111723. VdbeComment((v, "%s", pIdx->zName));
  111724. }
  111725. }
  111726. if( iBase>pParse->nTab ) pParse->nTab = iBase;
  111727. return i;
  111728. }
  111729. #ifdef SQLITE_TEST
  111730. /*
  111731. ** The following global variable is incremented whenever the
  111732. ** transfer optimization is used. This is used for testing
  111733. ** purposes only - to make sure the transfer optimization really
  111734. ** is happening when it is supposed to.
  111735. */
  111736. SQLITE_API int sqlite3_xferopt_count;
  111737. #endif /* SQLITE_TEST */
  111738. #ifndef SQLITE_OMIT_XFER_OPT
  111739. /*
  111740. ** Check to see if index pSrc is compatible as a source of data
  111741. ** for index pDest in an insert transfer optimization. The rules
  111742. ** for a compatible index:
  111743. **
  111744. ** * The index is over the same set of columns
  111745. ** * The same DESC and ASC markings occurs on all columns
  111746. ** * The same onError processing (OE_Abort, OE_Ignore, etc)
  111747. ** * The same collating sequence on each column
  111748. ** * The index has the exact same WHERE clause
  111749. */
  111750. static int xferCompatibleIndex(Index *pDest, Index *pSrc){
  111751. int i;
  111752. assert( pDest && pSrc );
  111753. assert( pDest->pTable!=pSrc->pTable );
  111754. if( pDest->nKeyCol!=pSrc->nKeyCol ){
  111755. return 0; /* Different number of columns */
  111756. }
  111757. if( pDest->onError!=pSrc->onError ){
  111758. return 0; /* Different conflict resolution strategies */
  111759. }
  111760. for(i=0; i<pSrc->nKeyCol; i++){
  111761. if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
  111762. return 0; /* Different columns indexed */
  111763. }
  111764. if( pSrc->aiColumn[i]==XN_EXPR ){
  111765. assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 );
  111766. if( sqlite3ExprCompare(0, pSrc->aColExpr->a[i].pExpr,
  111767. pDest->aColExpr->a[i].pExpr, -1)!=0 ){
  111768. return 0; /* Different expressions in the index */
  111769. }
  111770. }
  111771. if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
  111772. return 0; /* Different sort orders */
  111773. }
  111774. if( sqlite3_stricmp(pSrc->azColl[i],pDest->azColl[i])!=0 ){
  111775. return 0; /* Different collating sequences */
  111776. }
  111777. }
  111778. if( sqlite3ExprCompare(0, pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
  111779. return 0; /* Different WHERE clauses */
  111780. }
  111781. /* If no test above fails then the indices must be compatible */
  111782. return 1;
  111783. }
  111784. /*
  111785. ** Attempt the transfer optimization on INSERTs of the form
  111786. **
  111787. ** INSERT INTO tab1 SELECT * FROM tab2;
  111788. **
  111789. ** The xfer optimization transfers raw records from tab2 over to tab1.
  111790. ** Columns are not decoded and reassembled, which greatly improves
  111791. ** performance. Raw index records are transferred in the same way.
  111792. **
  111793. ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
  111794. ** There are lots of rules for determining compatibility - see comments
  111795. ** embedded in the code for details.
  111796. **
  111797. ** This routine returns TRUE if the optimization is guaranteed to be used.
  111798. ** Sometimes the xfer optimization will only work if the destination table
  111799. ** is empty - a factor that can only be determined at run-time. In that
  111800. ** case, this routine generates code for the xfer optimization but also
  111801. ** does a test to see if the destination table is empty and jumps over the
  111802. ** xfer optimization code if the test fails. In that case, this routine
  111803. ** returns FALSE so that the caller will know to go ahead and generate
  111804. ** an unoptimized transfer. This routine also returns FALSE if there
  111805. ** is no chance that the xfer optimization can be applied.
  111806. **
  111807. ** This optimization is particularly useful at making VACUUM run faster.
  111808. */
  111809. static int xferOptimization(
  111810. Parse *pParse, /* Parser context */
  111811. Table *pDest, /* The table we are inserting into */
  111812. Select *pSelect, /* A SELECT statement to use as the data source */
  111813. int onError, /* How to handle constraint errors */
  111814. int iDbDest /* The database of pDest */
  111815. ){
  111816. sqlite3 *db = pParse->db;
  111817. ExprList *pEList; /* The result set of the SELECT */
  111818. Table *pSrc; /* The table in the FROM clause of SELECT */
  111819. Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
  111820. struct SrcList_item *pItem; /* An element of pSelect->pSrc */
  111821. int i; /* Loop counter */
  111822. int iDbSrc; /* The database of pSrc */
  111823. int iSrc, iDest; /* Cursors from source and destination */
  111824. int addr1, addr2; /* Loop addresses */
  111825. int emptyDestTest = 0; /* Address of test for empty pDest */
  111826. int emptySrcTest = 0; /* Address of test for empty pSrc */
  111827. Vdbe *v; /* The VDBE we are building */
  111828. int regAutoinc; /* Memory register used by AUTOINC */
  111829. int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
  111830. int regData, regRowid; /* Registers holding data and rowid */
  111831. if( pSelect==0 ){
  111832. return 0; /* Must be of the form INSERT INTO ... SELECT ... */
  111833. }
  111834. if( pParse->pWith || pSelect->pWith ){
  111835. /* Do not attempt to process this query if there are an WITH clauses
  111836. ** attached to it. Proceeding may generate a false "no such table: xxx"
  111837. ** error if pSelect reads from a CTE named "xxx". */
  111838. return 0;
  111839. }
  111840. if( sqlite3TriggerList(pParse, pDest) ){
  111841. return 0; /* tab1 must not have triggers */
  111842. }
  111843. #ifndef SQLITE_OMIT_VIRTUALTABLE
  111844. if( IsVirtual(pDest) ){
  111845. return 0; /* tab1 must not be a virtual table */
  111846. }
  111847. #endif
  111848. if( onError==OE_Default ){
  111849. if( pDest->iPKey>=0 ) onError = pDest->keyConf;
  111850. if( onError==OE_Default ) onError = OE_Abort;
  111851. }
  111852. assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
  111853. if( pSelect->pSrc->nSrc!=1 ){
  111854. return 0; /* FROM clause must have exactly one term */
  111855. }
  111856. if( pSelect->pSrc->a[0].pSelect ){
  111857. return 0; /* FROM clause cannot contain a subquery */
  111858. }
  111859. if( pSelect->pWhere ){
  111860. return 0; /* SELECT may not have a WHERE clause */
  111861. }
  111862. if( pSelect->pOrderBy ){
  111863. return 0; /* SELECT may not have an ORDER BY clause */
  111864. }
  111865. /* Do not need to test for a HAVING clause. If HAVING is present but
  111866. ** there is no ORDER BY, we will get an error. */
  111867. if( pSelect->pGroupBy ){
  111868. return 0; /* SELECT may not have a GROUP BY clause */
  111869. }
  111870. if( pSelect->pLimit ){
  111871. return 0; /* SELECT may not have a LIMIT clause */
  111872. }
  111873. if( pSelect->pPrior ){
  111874. return 0; /* SELECT may not be a compound query */
  111875. }
  111876. if( pSelect->selFlags & SF_Distinct ){
  111877. return 0; /* SELECT may not be DISTINCT */
  111878. }
  111879. pEList = pSelect->pEList;
  111880. assert( pEList!=0 );
  111881. if( pEList->nExpr!=1 ){
  111882. return 0; /* The result set must have exactly one column */
  111883. }
  111884. assert( pEList->a[0].pExpr );
  111885. if( pEList->a[0].pExpr->op!=TK_ASTERISK ){
  111886. return 0; /* The result set must be the special operator "*" */
  111887. }
  111888. /* At this point we have established that the statement is of the
  111889. ** correct syntactic form to participate in this optimization. Now
  111890. ** we have to check the semantics.
  111891. */
  111892. pItem = pSelect->pSrc->a;
  111893. pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
  111894. if( pSrc==0 ){
  111895. return 0; /* FROM clause does not contain a real table */
  111896. }
  111897. if( pSrc->tnum==pDest->tnum && pSrc->pSchema==pDest->pSchema ){
  111898. testcase( pSrc!=pDest ); /* Possible due to bad sqlite_master.rootpage */
  111899. return 0; /* tab1 and tab2 may not be the same table */
  111900. }
  111901. if( HasRowid(pDest)!=HasRowid(pSrc) ){
  111902. return 0; /* source and destination must both be WITHOUT ROWID or not */
  111903. }
  111904. #ifndef SQLITE_OMIT_VIRTUALTABLE
  111905. if( IsVirtual(pSrc) ){
  111906. return 0; /* tab2 must not be a virtual table */
  111907. }
  111908. #endif
  111909. if( pSrc->pSelect ){
  111910. return 0; /* tab2 may not be a view */
  111911. }
  111912. if( pDest->nCol!=pSrc->nCol ){
  111913. return 0; /* Number of columns must be the same in tab1 and tab2 */
  111914. }
  111915. if( pDest->iPKey!=pSrc->iPKey ){
  111916. return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
  111917. }
  111918. for(i=0; i<pDest->nCol; i++){
  111919. Column *pDestCol = &pDest->aCol[i];
  111920. Column *pSrcCol = &pSrc->aCol[i];
  111921. #ifdef SQLITE_ENABLE_HIDDEN_COLUMNS
  111922. if( (db->mDbFlags & DBFLAG_Vacuum)==0
  111923. && (pDestCol->colFlags | pSrcCol->colFlags) & COLFLAG_HIDDEN
  111924. ){
  111925. return 0; /* Neither table may have __hidden__ columns */
  111926. }
  111927. #endif
  111928. if( pDestCol->affinity!=pSrcCol->affinity ){
  111929. return 0; /* Affinity must be the same on all columns */
  111930. }
  111931. if( sqlite3_stricmp(pDestCol->zColl, pSrcCol->zColl)!=0 ){
  111932. return 0; /* Collating sequence must be the same on all columns */
  111933. }
  111934. if( pDestCol->notNull && !pSrcCol->notNull ){
  111935. return 0; /* tab2 must be NOT NULL if tab1 is */
  111936. }
  111937. /* Default values for second and subsequent columns need to match. */
  111938. if( i>0 ){
  111939. assert( pDestCol->pDflt==0 || pDestCol->pDflt->op==TK_SPAN );
  111940. assert( pSrcCol->pDflt==0 || pSrcCol->pDflt->op==TK_SPAN );
  111941. if( (pDestCol->pDflt==0)!=(pSrcCol->pDflt==0)
  111942. || (pDestCol->pDflt && strcmp(pDestCol->pDflt->u.zToken,
  111943. pSrcCol->pDflt->u.zToken)!=0)
  111944. ){
  111945. return 0; /* Default values must be the same for all columns */
  111946. }
  111947. }
  111948. }
  111949. for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
  111950. if( IsUniqueIndex(pDestIdx) ){
  111951. destHasUniqueIdx = 1;
  111952. }
  111953. for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
  111954. if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
  111955. }
  111956. if( pSrcIdx==0 ){
  111957. return 0; /* pDestIdx has no corresponding index in pSrc */
  111958. }
  111959. if( pSrcIdx->tnum==pDestIdx->tnum && pSrc->pSchema==pDest->pSchema
  111960. && sqlite3FaultSim(411)==SQLITE_OK ){
  111961. /* The sqlite3FaultSim() call allows this corruption test to be
  111962. ** bypassed during testing, in order to exercise other corruption tests
  111963. ** further downstream. */
  111964. return 0; /* Corrupt schema - two indexes on the same btree */
  111965. }
  111966. }
  111967. #ifndef SQLITE_OMIT_CHECK
  111968. if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
  111969. return 0; /* Tables have different CHECK constraints. Ticket #2252 */
  111970. }
  111971. #endif
  111972. #ifndef SQLITE_OMIT_FOREIGN_KEY
  111973. /* Disallow the transfer optimization if the destination table constains
  111974. ** any foreign key constraints. This is more restrictive than necessary.
  111975. ** But the main beneficiary of the transfer optimization is the VACUUM
  111976. ** command, and the VACUUM command disables foreign key constraints. So
  111977. ** the extra complication to make this rule less restrictive is probably
  111978. ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
  111979. */
  111980. if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
  111981. return 0;
  111982. }
  111983. #endif
  111984. if( (db->flags & SQLITE_CountRows)!=0 ){
  111985. return 0; /* xfer opt does not play well with PRAGMA count_changes */
  111986. }
  111987. /* If we get this far, it means that the xfer optimization is at
  111988. ** least a possibility, though it might only work if the destination
  111989. ** table (tab1) is initially empty.
  111990. */
  111991. #ifdef SQLITE_TEST
  111992. sqlite3_xferopt_count++;
  111993. #endif
  111994. iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema);
  111995. v = sqlite3GetVdbe(pParse);
  111996. sqlite3CodeVerifySchema(pParse, iDbSrc);
  111997. iSrc = pParse->nTab++;
  111998. iDest = pParse->nTab++;
  111999. regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
  112000. regData = sqlite3GetTempReg(pParse);
  112001. regRowid = sqlite3GetTempReg(pParse);
  112002. sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
  112003. assert( HasRowid(pDest) || destHasUniqueIdx );
  112004. if( (db->mDbFlags & DBFLAG_Vacuum)==0 && (
  112005. (pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */
  112006. || destHasUniqueIdx /* (2) */
  112007. || (onError!=OE_Abort && onError!=OE_Rollback) /* (3) */
  112008. )){
  112009. /* In some circumstances, we are able to run the xfer optimization
  112010. ** only if the destination table is initially empty. Unless the
  112011. ** DBFLAG_Vacuum flag is set, this block generates code to make
  112012. ** that determination. If DBFLAG_Vacuum is set, then the destination
  112013. ** table is always empty.
  112014. **
  112015. ** Conditions under which the destination must be empty:
  112016. **
  112017. ** (1) There is no INTEGER PRIMARY KEY but there are indices.
  112018. ** (If the destination is not initially empty, the rowid fields
  112019. ** of index entries might need to change.)
  112020. **
  112021. ** (2) The destination has a unique index. (The xfer optimization
  112022. ** is unable to test uniqueness.)
  112023. **
  112024. ** (3) onError is something other than OE_Abort and OE_Rollback.
  112025. */
  112026. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);
  112027. emptyDestTest = sqlite3VdbeAddOp0(v, OP_Goto);
  112028. sqlite3VdbeJumpHere(v, addr1);
  112029. }
  112030. if( HasRowid(pSrc) ){
  112031. u8 insFlags;
  112032. sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
  112033. emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
  112034. if( pDest->iPKey>=0 ){
  112035. addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
  112036. sqlite3VdbeVerifyAbortable(v, onError);
  112037. addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
  112038. VdbeCoverage(v);
  112039. sqlite3RowidConstraint(pParse, onError, pDest);
  112040. sqlite3VdbeJumpHere(v, addr2);
  112041. autoIncStep(pParse, regAutoinc, regRowid);
  112042. }else if( pDest->pIndex==0 && !(db->mDbFlags & DBFLAG_VacuumInto) ){
  112043. addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
  112044. }else{
  112045. addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
  112046. assert( (pDest->tabFlags & TF_Autoincrement)==0 );
  112047. }
  112048. sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
  112049. if( db->mDbFlags & DBFLAG_Vacuum ){
  112050. sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest);
  112051. insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|
  112052. OPFLAG_APPEND|OPFLAG_USESEEKRESULT;
  112053. }else{
  112054. insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND;
  112055. }
  112056. sqlite3VdbeAddOp4(v, OP_Insert, iDest, regData, regRowid,
  112057. (char*)pDest, P4_TABLE);
  112058. sqlite3VdbeChangeP5(v, insFlags);
  112059. sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
  112060. sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
  112061. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  112062. }else{
  112063. sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
  112064. sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
  112065. }
  112066. for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
  112067. u8 idxInsFlags = 0;
  112068. for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
  112069. if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
  112070. }
  112071. assert( pSrcIdx );
  112072. sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
  112073. sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
  112074. VdbeComment((v, "%s", pSrcIdx->zName));
  112075. sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
  112076. sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
  112077. sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
  112078. VdbeComment((v, "%s", pDestIdx->zName));
  112079. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
  112080. sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
  112081. if( db->mDbFlags & DBFLAG_Vacuum ){
  112082. /* This INSERT command is part of a VACUUM operation, which guarantees
  112083. ** that the destination table is empty. If all indexed columns use
  112084. ** collation sequence BINARY, then it can also be assumed that the
  112085. ** index will be populated by inserting keys in strictly sorted
  112086. ** order. In this case, instead of seeking within the b-tree as part
  112087. ** of every OP_IdxInsert opcode, an OP_SeekEnd is added before the
  112088. ** OP_IdxInsert to seek to the point within the b-tree where each key
  112089. ** should be inserted. This is faster.
  112090. **
  112091. ** If any of the indexed columns use a collation sequence other than
  112092. ** BINARY, this optimization is disabled. This is because the user
  112093. ** might change the definition of a collation sequence and then run
  112094. ** a VACUUM command. In that case keys may not be written in strictly
  112095. ** sorted order. */
  112096. for(i=0; i<pSrcIdx->nColumn; i++){
  112097. const char *zColl = pSrcIdx->azColl[i];
  112098. if( sqlite3_stricmp(sqlite3StrBINARY, zColl) ) break;
  112099. }
  112100. if( i==pSrcIdx->nColumn ){
  112101. idxInsFlags = OPFLAG_USESEEKRESULT;
  112102. sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest);
  112103. }
  112104. }
  112105. if( !HasRowid(pSrc) && pDestIdx->idxType==SQLITE_IDXTYPE_PRIMARYKEY ){
  112106. idxInsFlags |= OPFLAG_NCHANGE;
  112107. }
  112108. sqlite3VdbeAddOp2(v, OP_IdxInsert, iDest, regData);
  112109. sqlite3VdbeChangeP5(v, idxInsFlags|OPFLAG_APPEND);
  112110. sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
  112111. sqlite3VdbeJumpHere(v, addr1);
  112112. sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
  112113. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  112114. }
  112115. if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);
  112116. sqlite3ReleaseTempReg(pParse, regRowid);
  112117. sqlite3ReleaseTempReg(pParse, regData);
  112118. if( emptyDestTest ){
  112119. sqlite3AutoincrementEnd(pParse);
  112120. sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
  112121. sqlite3VdbeJumpHere(v, emptyDestTest);
  112122. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  112123. return 0;
  112124. }else{
  112125. return 1;
  112126. }
  112127. }
  112128. #endif /* SQLITE_OMIT_XFER_OPT */
  112129. /************** End of insert.c **********************************************/
  112130. /************** Begin file legacy.c ******************************************/
  112131. /*
  112132. ** 2001 September 15
  112133. **
  112134. ** The author disclaims copyright to this source code. In place of
  112135. ** a legal notice, here is a blessing:
  112136. **
  112137. ** May you do good and not evil.
  112138. ** May you find forgiveness for yourself and forgive others.
  112139. ** May you share freely, never taking more than you give.
  112140. **
  112141. *************************************************************************
  112142. ** Main file for the SQLite library. The routines in this file
  112143. ** implement the programmer interface to the library. Routines in
  112144. ** other files are for internal use by SQLite and should not be
  112145. ** accessed by users of the library.
  112146. */
  112147. /* #include "sqliteInt.h" */
  112148. /*
  112149. ** Execute SQL code. Return one of the SQLITE_ success/failure
  112150. ** codes. Also write an error message into memory obtained from
  112151. ** malloc() and make *pzErrMsg point to that message.
  112152. **
  112153. ** If the SQL is a query, then for each row in the query result
  112154. ** the xCallback() function is called. pArg becomes the first
  112155. ** argument to xCallback(). If xCallback=NULL then no callback
  112156. ** is invoked, even for queries.
  112157. */
  112158. SQLITE_API int sqlite3_exec(
  112159. sqlite3 *db, /* The database on which the SQL executes */
  112160. const char *zSql, /* The SQL to be executed */
  112161. sqlite3_callback xCallback, /* Invoke this callback routine */
  112162. void *pArg, /* First argument to xCallback() */
  112163. char **pzErrMsg /* Write error messages here */
  112164. ){
  112165. int rc = SQLITE_OK; /* Return code */
  112166. const char *zLeftover; /* Tail of unprocessed SQL */
  112167. sqlite3_stmt *pStmt = 0; /* The current SQL statement */
  112168. char **azCols = 0; /* Names of result columns */
  112169. int callbackIsInit; /* True if callback data is initialized */
  112170. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  112171. if( zSql==0 ) zSql = "";
  112172. sqlite3_mutex_enter(db->mutex);
  112173. sqlite3Error(db, SQLITE_OK);
  112174. while( rc==SQLITE_OK && zSql[0] ){
  112175. int nCol = 0;
  112176. char **azVals = 0;
  112177. pStmt = 0;
  112178. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
  112179. assert( rc==SQLITE_OK || pStmt==0 );
  112180. if( rc!=SQLITE_OK ){
  112181. continue;
  112182. }
  112183. if( !pStmt ){
  112184. /* this happens for a comment or white-space */
  112185. zSql = zLeftover;
  112186. continue;
  112187. }
  112188. callbackIsInit = 0;
  112189. while( 1 ){
  112190. int i;
  112191. rc = sqlite3_step(pStmt);
  112192. /* Invoke the callback function if required */
  112193. if( xCallback && (SQLITE_ROW==rc ||
  112194. (SQLITE_DONE==rc && !callbackIsInit
  112195. && db->flags&SQLITE_NullCallback)) ){
  112196. if( !callbackIsInit ){
  112197. nCol = sqlite3_column_count(pStmt);
  112198. azCols = sqlite3DbMallocRaw(db, (2*nCol+1)*sizeof(const char*));
  112199. if( azCols==0 ){
  112200. goto exec_out;
  112201. }
  112202. for(i=0; i<nCol; i++){
  112203. azCols[i] = (char *)sqlite3_column_name(pStmt, i);
  112204. /* sqlite3VdbeSetColName() installs column names as UTF8
  112205. ** strings so there is no way for sqlite3_column_name() to fail. */
  112206. assert( azCols[i]!=0 );
  112207. }
  112208. callbackIsInit = 1;
  112209. }
  112210. if( rc==SQLITE_ROW ){
  112211. azVals = &azCols[nCol];
  112212. for(i=0; i<nCol; i++){
  112213. azVals[i] = (char *)sqlite3_column_text(pStmt, i);
  112214. if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
  112215. sqlite3OomFault(db);
  112216. goto exec_out;
  112217. }
  112218. }
  112219. azVals[i] = 0;
  112220. }
  112221. if( xCallback(pArg, nCol, azVals, azCols) ){
  112222. /* EVIDENCE-OF: R-38229-40159 If the callback function to
  112223. ** sqlite3_exec() returns non-zero, then sqlite3_exec() will
  112224. ** return SQLITE_ABORT. */
  112225. rc = SQLITE_ABORT;
  112226. sqlite3VdbeFinalize((Vdbe *)pStmt);
  112227. pStmt = 0;
  112228. sqlite3Error(db, SQLITE_ABORT);
  112229. goto exec_out;
  112230. }
  112231. }
  112232. if( rc!=SQLITE_ROW ){
  112233. rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
  112234. pStmt = 0;
  112235. zSql = zLeftover;
  112236. while( sqlite3Isspace(zSql[0]) ) zSql++;
  112237. break;
  112238. }
  112239. }
  112240. sqlite3DbFree(db, azCols);
  112241. azCols = 0;
  112242. }
  112243. exec_out:
  112244. if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
  112245. sqlite3DbFree(db, azCols);
  112246. rc = sqlite3ApiExit(db, rc);
  112247. if( rc!=SQLITE_OK && pzErrMsg ){
  112248. *pzErrMsg = sqlite3DbStrDup(0, sqlite3_errmsg(db));
  112249. if( *pzErrMsg==0 ){
  112250. rc = SQLITE_NOMEM_BKPT;
  112251. sqlite3Error(db, SQLITE_NOMEM);
  112252. }
  112253. }else if( pzErrMsg ){
  112254. *pzErrMsg = 0;
  112255. }
  112256. assert( (rc&db->errMask)==rc );
  112257. sqlite3_mutex_leave(db->mutex);
  112258. return rc;
  112259. }
  112260. /************** End of legacy.c **********************************************/
  112261. /************** Begin file loadext.c *****************************************/
  112262. /*
  112263. ** 2006 June 7
  112264. **
  112265. ** The author disclaims copyright to this source code. In place of
  112266. ** a legal notice, here is a blessing:
  112267. **
  112268. ** May you do good and not evil.
  112269. ** May you find forgiveness for yourself and forgive others.
  112270. ** May you share freely, never taking more than you give.
  112271. **
  112272. *************************************************************************
  112273. ** This file contains code used to dynamically load extensions into
  112274. ** the SQLite library.
  112275. */
  112276. #ifndef SQLITE_CORE
  112277. #define SQLITE_CORE 1 /* Disable the API redefinition in sqlite3ext.h */
  112278. #endif
  112279. /************** Include sqlite3ext.h in the middle of loadext.c **************/
  112280. /************** Begin file sqlite3ext.h **************************************/
  112281. /*
  112282. ** 2006 June 7
  112283. **
  112284. ** The author disclaims copyright to this source code. In place of
  112285. ** a legal notice, here is a blessing:
  112286. **
  112287. ** May you do good and not evil.
  112288. ** May you find forgiveness for yourself and forgive others.
  112289. ** May you share freely, never taking more than you give.
  112290. **
  112291. *************************************************************************
  112292. ** This header file defines the SQLite interface for use by
  112293. ** shared libraries that want to be imported as extensions into
  112294. ** an SQLite instance. Shared libraries that intend to be loaded
  112295. ** as extensions by SQLite should #include this file instead of
  112296. ** sqlite3.h.
  112297. */
  112298. #ifndef SQLITE3EXT_H
  112299. #define SQLITE3EXT_H
  112300. /* #include "sqlite3.h" */
  112301. /*
  112302. ** The following structure holds pointers to all of the SQLite API
  112303. ** routines.
  112304. **
  112305. ** WARNING: In order to maintain backwards compatibility, add new
  112306. ** interfaces to the end of this structure only. If you insert new
  112307. ** interfaces in the middle of this structure, then older different
  112308. ** versions of SQLite will not be able to load each other's shared
  112309. ** libraries!
  112310. */
  112311. struct sqlite3_api_routines {
  112312. void * (*aggregate_context)(sqlite3_context*,int nBytes);
  112313. int (*aggregate_count)(sqlite3_context*);
  112314. int (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
  112315. int (*bind_double)(sqlite3_stmt*,int,double);
  112316. int (*bind_int)(sqlite3_stmt*,int,int);
  112317. int (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
  112318. int (*bind_null)(sqlite3_stmt*,int);
  112319. int (*bind_parameter_count)(sqlite3_stmt*);
  112320. int (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
  112321. const char * (*bind_parameter_name)(sqlite3_stmt*,int);
  112322. int (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
  112323. int (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
  112324. int (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
  112325. int (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
  112326. int (*busy_timeout)(sqlite3*,int ms);
  112327. int (*changes)(sqlite3*);
  112328. int (*close)(sqlite3*);
  112329. int (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
  112330. int eTextRep,const char*));
  112331. int (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
  112332. int eTextRep,const void*));
  112333. const void * (*column_blob)(sqlite3_stmt*,int iCol);
  112334. int (*column_bytes)(sqlite3_stmt*,int iCol);
  112335. int (*column_bytes16)(sqlite3_stmt*,int iCol);
  112336. int (*column_count)(sqlite3_stmt*pStmt);
  112337. const char * (*column_database_name)(sqlite3_stmt*,int);
  112338. const void * (*column_database_name16)(sqlite3_stmt*,int);
  112339. const char * (*column_decltype)(sqlite3_stmt*,int i);
  112340. const void * (*column_decltype16)(sqlite3_stmt*,int);
  112341. double (*column_double)(sqlite3_stmt*,int iCol);
  112342. int (*column_int)(sqlite3_stmt*,int iCol);
  112343. sqlite_int64 (*column_int64)(sqlite3_stmt*,int iCol);
  112344. const char * (*column_name)(sqlite3_stmt*,int);
  112345. const void * (*column_name16)(sqlite3_stmt*,int);
  112346. const char * (*column_origin_name)(sqlite3_stmt*,int);
  112347. const void * (*column_origin_name16)(sqlite3_stmt*,int);
  112348. const char * (*column_table_name)(sqlite3_stmt*,int);
  112349. const void * (*column_table_name16)(sqlite3_stmt*,int);
  112350. const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
  112351. const void * (*column_text16)(sqlite3_stmt*,int iCol);
  112352. int (*column_type)(sqlite3_stmt*,int iCol);
  112353. sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
  112354. void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
  112355. int (*complete)(const char*sql);
  112356. int (*complete16)(const void*sql);
  112357. int (*create_collation)(sqlite3*,const char*,int,void*,
  112358. int(*)(void*,int,const void*,int,const void*));
  112359. int (*create_collation16)(sqlite3*,const void*,int,void*,
  112360. int(*)(void*,int,const void*,int,const void*));
  112361. int (*create_function)(sqlite3*,const char*,int,int,void*,
  112362. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  112363. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  112364. void (*xFinal)(sqlite3_context*));
  112365. int (*create_function16)(sqlite3*,const void*,int,int,void*,
  112366. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  112367. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  112368. void (*xFinal)(sqlite3_context*));
  112369. int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
  112370. int (*data_count)(sqlite3_stmt*pStmt);
  112371. sqlite3 * (*db_handle)(sqlite3_stmt*);
  112372. int (*declare_vtab)(sqlite3*,const char*);
  112373. int (*enable_shared_cache)(int);
  112374. int (*errcode)(sqlite3*db);
  112375. const char * (*errmsg)(sqlite3*);
  112376. const void * (*errmsg16)(sqlite3*);
  112377. int (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
  112378. int (*expired)(sqlite3_stmt*);
  112379. int (*finalize)(sqlite3_stmt*pStmt);
  112380. void (*free)(void*);
  112381. void (*free_table)(char**result);
  112382. int (*get_autocommit)(sqlite3*);
  112383. void * (*get_auxdata)(sqlite3_context*,int);
  112384. int (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
  112385. int (*global_recover)(void);
  112386. void (*interruptx)(sqlite3*);
  112387. sqlite_int64 (*last_insert_rowid)(sqlite3*);
  112388. const char * (*libversion)(void);
  112389. int (*libversion_number)(void);
  112390. void *(*malloc)(int);
  112391. char * (*mprintf)(const char*,...);
  112392. int (*open)(const char*,sqlite3**);
  112393. int (*open16)(const void*,sqlite3**);
  112394. int (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
  112395. int (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
  112396. void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
  112397. void (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
  112398. void *(*realloc)(void*,int);
  112399. int (*reset)(sqlite3_stmt*pStmt);
  112400. void (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
  112401. void (*result_double)(sqlite3_context*,double);
  112402. void (*result_error)(sqlite3_context*,const char*,int);
  112403. void (*result_error16)(sqlite3_context*,const void*,int);
  112404. void (*result_int)(sqlite3_context*,int);
  112405. void (*result_int64)(sqlite3_context*,sqlite_int64);
  112406. void (*result_null)(sqlite3_context*);
  112407. void (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
  112408. void (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
  112409. void (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
  112410. void (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
  112411. void (*result_value)(sqlite3_context*,sqlite3_value*);
  112412. void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
  112413. int (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
  112414. const char*,const char*),void*);
  112415. void (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
  112416. char * (*xsnprintf)(int,char*,const char*,...);
  112417. int (*step)(sqlite3_stmt*);
  112418. int (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
  112419. char const**,char const**,int*,int*,int*);
  112420. void (*thread_cleanup)(void);
  112421. int (*total_changes)(sqlite3*);
  112422. void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
  112423. int (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
  112424. void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
  112425. sqlite_int64),void*);
  112426. void * (*user_data)(sqlite3_context*);
  112427. const void * (*value_blob)(sqlite3_value*);
  112428. int (*value_bytes)(sqlite3_value*);
  112429. int (*value_bytes16)(sqlite3_value*);
  112430. double (*value_double)(sqlite3_value*);
  112431. int (*value_int)(sqlite3_value*);
  112432. sqlite_int64 (*value_int64)(sqlite3_value*);
  112433. int (*value_numeric_type)(sqlite3_value*);
  112434. const unsigned char * (*value_text)(sqlite3_value*);
  112435. const void * (*value_text16)(sqlite3_value*);
  112436. const void * (*value_text16be)(sqlite3_value*);
  112437. const void * (*value_text16le)(sqlite3_value*);
  112438. int (*value_type)(sqlite3_value*);
  112439. char *(*vmprintf)(const char*,va_list);
  112440. /* Added ??? */
  112441. int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
  112442. /* Added by 3.3.13 */
  112443. int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
  112444. int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
  112445. int (*clear_bindings)(sqlite3_stmt*);
  112446. /* Added by 3.4.1 */
  112447. int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
  112448. void (*xDestroy)(void *));
  112449. /* Added by 3.5.0 */
  112450. int (*bind_zeroblob)(sqlite3_stmt*,int,int);
  112451. int (*blob_bytes)(sqlite3_blob*);
  112452. int (*blob_close)(sqlite3_blob*);
  112453. int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
  112454. int,sqlite3_blob**);
  112455. int (*blob_read)(sqlite3_blob*,void*,int,int);
  112456. int (*blob_write)(sqlite3_blob*,const void*,int,int);
  112457. int (*create_collation_v2)(sqlite3*,const char*,int,void*,
  112458. int(*)(void*,int,const void*,int,const void*),
  112459. void(*)(void*));
  112460. int (*file_control)(sqlite3*,const char*,int,void*);
  112461. sqlite3_int64 (*memory_highwater)(int);
  112462. sqlite3_int64 (*memory_used)(void);
  112463. sqlite3_mutex *(*mutex_alloc)(int);
  112464. void (*mutex_enter)(sqlite3_mutex*);
  112465. void (*mutex_free)(sqlite3_mutex*);
  112466. void (*mutex_leave)(sqlite3_mutex*);
  112467. int (*mutex_try)(sqlite3_mutex*);
  112468. int (*open_v2)(const char*,sqlite3**,int,const char*);
  112469. int (*release_memory)(int);
  112470. void (*result_error_nomem)(sqlite3_context*);
  112471. void (*result_error_toobig)(sqlite3_context*);
  112472. int (*sleep)(int);
  112473. void (*soft_heap_limit)(int);
  112474. sqlite3_vfs *(*vfs_find)(const char*);
  112475. int (*vfs_register)(sqlite3_vfs*,int);
  112476. int (*vfs_unregister)(sqlite3_vfs*);
  112477. int (*xthreadsafe)(void);
  112478. void (*result_zeroblob)(sqlite3_context*,int);
  112479. void (*result_error_code)(sqlite3_context*,int);
  112480. int (*test_control)(int, ...);
  112481. void (*randomness)(int,void*);
  112482. sqlite3 *(*context_db_handle)(sqlite3_context*);
  112483. int (*extended_result_codes)(sqlite3*,int);
  112484. int (*limit)(sqlite3*,int,int);
  112485. sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
  112486. const char *(*sql)(sqlite3_stmt*);
  112487. int (*status)(int,int*,int*,int);
  112488. int (*backup_finish)(sqlite3_backup*);
  112489. sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
  112490. int (*backup_pagecount)(sqlite3_backup*);
  112491. int (*backup_remaining)(sqlite3_backup*);
  112492. int (*backup_step)(sqlite3_backup*,int);
  112493. const char *(*compileoption_get)(int);
  112494. int (*compileoption_used)(const char*);
  112495. int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
  112496. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  112497. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  112498. void (*xFinal)(sqlite3_context*),
  112499. void(*xDestroy)(void*));
  112500. int (*db_config)(sqlite3*,int,...);
  112501. sqlite3_mutex *(*db_mutex)(sqlite3*);
  112502. int (*db_status)(sqlite3*,int,int*,int*,int);
  112503. int (*extended_errcode)(sqlite3*);
  112504. void (*log)(int,const char*,...);
  112505. sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
  112506. const char *(*sourceid)(void);
  112507. int (*stmt_status)(sqlite3_stmt*,int,int);
  112508. int (*strnicmp)(const char*,const char*,int);
  112509. int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
  112510. int (*wal_autocheckpoint)(sqlite3*,int);
  112511. int (*wal_checkpoint)(sqlite3*,const char*);
  112512. void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
  112513. int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
  112514. int (*vtab_config)(sqlite3*,int op,...);
  112515. int (*vtab_on_conflict)(sqlite3*);
  112516. /* Version 3.7.16 and later */
  112517. int (*close_v2)(sqlite3*);
  112518. const char *(*db_filename)(sqlite3*,const char*);
  112519. int (*db_readonly)(sqlite3*,const char*);
  112520. int (*db_release_memory)(sqlite3*);
  112521. const char *(*errstr)(int);
  112522. int (*stmt_busy)(sqlite3_stmt*);
  112523. int (*stmt_readonly)(sqlite3_stmt*);
  112524. int (*stricmp)(const char*,const char*);
  112525. int (*uri_boolean)(const char*,const char*,int);
  112526. sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64);
  112527. const char *(*uri_parameter)(const char*,const char*);
  112528. char *(*xvsnprintf)(int,char*,const char*,va_list);
  112529. int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*);
  112530. /* Version 3.8.7 and later */
  112531. int (*auto_extension)(void(*)(void));
  112532. int (*bind_blob64)(sqlite3_stmt*,int,const void*,sqlite3_uint64,
  112533. void(*)(void*));
  112534. int (*bind_text64)(sqlite3_stmt*,int,const char*,sqlite3_uint64,
  112535. void(*)(void*),unsigned char);
  112536. int (*cancel_auto_extension)(void(*)(void));
  112537. int (*load_extension)(sqlite3*,const char*,const char*,char**);
  112538. void *(*malloc64)(sqlite3_uint64);
  112539. sqlite3_uint64 (*msize)(void*);
  112540. void *(*realloc64)(void*,sqlite3_uint64);
  112541. void (*reset_auto_extension)(void);
  112542. void (*result_blob64)(sqlite3_context*,const void*,sqlite3_uint64,
  112543. void(*)(void*));
  112544. void (*result_text64)(sqlite3_context*,const char*,sqlite3_uint64,
  112545. void(*)(void*), unsigned char);
  112546. int (*strglob)(const char*,const char*);
  112547. /* Version 3.8.11 and later */
  112548. sqlite3_value *(*value_dup)(const sqlite3_value*);
  112549. void (*value_free)(sqlite3_value*);
  112550. int (*result_zeroblob64)(sqlite3_context*,sqlite3_uint64);
  112551. int (*bind_zeroblob64)(sqlite3_stmt*, int, sqlite3_uint64);
  112552. /* Version 3.9.0 and later */
  112553. unsigned int (*value_subtype)(sqlite3_value*);
  112554. void (*result_subtype)(sqlite3_context*,unsigned int);
  112555. /* Version 3.10.0 and later */
  112556. int (*status64)(int,sqlite3_int64*,sqlite3_int64*,int);
  112557. int (*strlike)(const char*,const char*,unsigned int);
  112558. int (*db_cacheflush)(sqlite3*);
  112559. /* Version 3.12.0 and later */
  112560. int (*system_errno)(sqlite3*);
  112561. /* Version 3.14.0 and later */
  112562. int (*trace_v2)(sqlite3*,unsigned,int(*)(unsigned,void*,void*,void*),void*);
  112563. char *(*expanded_sql)(sqlite3_stmt*);
  112564. /* Version 3.18.0 and later */
  112565. void (*set_last_insert_rowid)(sqlite3*,sqlite3_int64);
  112566. /* Version 3.20.0 and later */
  112567. int (*prepare_v3)(sqlite3*,const char*,int,unsigned int,
  112568. sqlite3_stmt**,const char**);
  112569. int (*prepare16_v3)(sqlite3*,const void*,int,unsigned int,
  112570. sqlite3_stmt**,const void**);
  112571. int (*bind_pointer)(sqlite3_stmt*,int,void*,const char*,void(*)(void*));
  112572. void (*result_pointer)(sqlite3_context*,void*,const char*,void(*)(void*));
  112573. void *(*value_pointer)(sqlite3_value*,const char*);
  112574. int (*vtab_nochange)(sqlite3_context*);
  112575. int (*value_nochange)(sqlite3_value*);
  112576. const char *(*vtab_collation)(sqlite3_index_info*,int);
  112577. /* Version 3.24.0 and later */
  112578. int (*keyword_count)(void);
  112579. int (*keyword_name)(int,const char**,int*);
  112580. int (*keyword_check)(const char*,int);
  112581. sqlite3_str *(*str_new)(sqlite3*);
  112582. char *(*str_finish)(sqlite3_str*);
  112583. void (*str_appendf)(sqlite3_str*, const char *zFormat, ...);
  112584. void (*str_vappendf)(sqlite3_str*, const char *zFormat, va_list);
  112585. void (*str_append)(sqlite3_str*, const char *zIn, int N);
  112586. void (*str_appendall)(sqlite3_str*, const char *zIn);
  112587. void (*str_appendchar)(sqlite3_str*, int N, char C);
  112588. void (*str_reset)(sqlite3_str*);
  112589. int (*str_errcode)(sqlite3_str*);
  112590. int (*str_length)(sqlite3_str*);
  112591. char *(*str_value)(sqlite3_str*);
  112592. /* Version 3.25.0 and later */
  112593. int (*create_window_function)(sqlite3*,const char*,int,int,void*,
  112594. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  112595. void (*xFinal)(sqlite3_context*),
  112596. void (*xValue)(sqlite3_context*),
  112597. void (*xInv)(sqlite3_context*,int,sqlite3_value**),
  112598. void(*xDestroy)(void*));
  112599. /* Version 3.26.0 and later */
  112600. const char *(*normalized_sql)(sqlite3_stmt*);
  112601. /* Version 3.28.0 and later */
  112602. int (*stmt_isexplain)(sqlite3_stmt*);
  112603. int (*value_frombind)(sqlite3_value*);
  112604. };
  112605. /*
  112606. ** This is the function signature used for all extension entry points. It
  112607. ** is also defined in the file "loadext.c".
  112608. */
  112609. typedef int (*sqlite3_loadext_entry)(
  112610. sqlite3 *db, /* Handle to the database. */
  112611. char **pzErrMsg, /* Used to set error string on failure. */
  112612. const sqlite3_api_routines *pThunk /* Extension API function pointers. */
  112613. );
  112614. /*
  112615. ** The following macros redefine the API routines so that they are
  112616. ** redirected through the global sqlite3_api structure.
  112617. **
  112618. ** This header file is also used by the loadext.c source file
  112619. ** (part of the main SQLite library - not an extension) so that
  112620. ** it can get access to the sqlite3_api_routines structure
  112621. ** definition. But the main library does not want to redefine
  112622. ** the API. So the redefinition macros are only valid if the
  112623. ** SQLITE_CORE macros is undefined.
  112624. */
  112625. #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  112626. #define sqlite3_aggregate_context sqlite3_api->aggregate_context
  112627. #ifndef SQLITE_OMIT_DEPRECATED
  112628. #define sqlite3_aggregate_count sqlite3_api->aggregate_count
  112629. #endif
  112630. #define sqlite3_bind_blob sqlite3_api->bind_blob
  112631. #define sqlite3_bind_double sqlite3_api->bind_double
  112632. #define sqlite3_bind_int sqlite3_api->bind_int
  112633. #define sqlite3_bind_int64 sqlite3_api->bind_int64
  112634. #define sqlite3_bind_null sqlite3_api->bind_null
  112635. #define sqlite3_bind_parameter_count sqlite3_api->bind_parameter_count
  112636. #define sqlite3_bind_parameter_index sqlite3_api->bind_parameter_index
  112637. #define sqlite3_bind_parameter_name sqlite3_api->bind_parameter_name
  112638. #define sqlite3_bind_text sqlite3_api->bind_text
  112639. #define sqlite3_bind_text16 sqlite3_api->bind_text16
  112640. #define sqlite3_bind_value sqlite3_api->bind_value
  112641. #define sqlite3_busy_handler sqlite3_api->busy_handler
  112642. #define sqlite3_busy_timeout sqlite3_api->busy_timeout
  112643. #define sqlite3_changes sqlite3_api->changes
  112644. #define sqlite3_close sqlite3_api->close
  112645. #define sqlite3_collation_needed sqlite3_api->collation_needed
  112646. #define sqlite3_collation_needed16 sqlite3_api->collation_needed16
  112647. #define sqlite3_column_blob sqlite3_api->column_blob
  112648. #define sqlite3_column_bytes sqlite3_api->column_bytes
  112649. #define sqlite3_column_bytes16 sqlite3_api->column_bytes16
  112650. #define sqlite3_column_count sqlite3_api->column_count
  112651. #define sqlite3_column_database_name sqlite3_api->column_database_name
  112652. #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
  112653. #define sqlite3_column_decltype sqlite3_api->column_decltype
  112654. #define sqlite3_column_decltype16 sqlite3_api->column_decltype16
  112655. #define sqlite3_column_double sqlite3_api->column_double
  112656. #define sqlite3_column_int sqlite3_api->column_int
  112657. #define sqlite3_column_int64 sqlite3_api->column_int64
  112658. #define sqlite3_column_name sqlite3_api->column_name
  112659. #define sqlite3_column_name16 sqlite3_api->column_name16
  112660. #define sqlite3_column_origin_name sqlite3_api->column_origin_name
  112661. #define sqlite3_column_origin_name16 sqlite3_api->column_origin_name16
  112662. #define sqlite3_column_table_name sqlite3_api->column_table_name
  112663. #define sqlite3_column_table_name16 sqlite3_api->column_table_name16
  112664. #define sqlite3_column_text sqlite3_api->column_text
  112665. #define sqlite3_column_text16 sqlite3_api->column_text16
  112666. #define sqlite3_column_type sqlite3_api->column_type
  112667. #define sqlite3_column_value sqlite3_api->column_value
  112668. #define sqlite3_commit_hook sqlite3_api->commit_hook
  112669. #define sqlite3_complete sqlite3_api->complete
  112670. #define sqlite3_complete16 sqlite3_api->complete16
  112671. #define sqlite3_create_collation sqlite3_api->create_collation
  112672. #define sqlite3_create_collation16 sqlite3_api->create_collation16
  112673. #define sqlite3_create_function sqlite3_api->create_function
  112674. #define sqlite3_create_function16 sqlite3_api->create_function16
  112675. #define sqlite3_create_module sqlite3_api->create_module
  112676. #define sqlite3_create_module_v2 sqlite3_api->create_module_v2
  112677. #define sqlite3_data_count sqlite3_api->data_count
  112678. #define sqlite3_db_handle sqlite3_api->db_handle
  112679. #define sqlite3_declare_vtab sqlite3_api->declare_vtab
  112680. #define sqlite3_enable_shared_cache sqlite3_api->enable_shared_cache
  112681. #define sqlite3_errcode sqlite3_api->errcode
  112682. #define sqlite3_errmsg sqlite3_api->errmsg
  112683. #define sqlite3_errmsg16 sqlite3_api->errmsg16
  112684. #define sqlite3_exec sqlite3_api->exec
  112685. #ifndef SQLITE_OMIT_DEPRECATED
  112686. #define sqlite3_expired sqlite3_api->expired
  112687. #endif
  112688. #define sqlite3_finalize sqlite3_api->finalize
  112689. #define sqlite3_free sqlite3_api->free
  112690. #define sqlite3_free_table sqlite3_api->free_table
  112691. #define sqlite3_get_autocommit sqlite3_api->get_autocommit
  112692. #define sqlite3_get_auxdata sqlite3_api->get_auxdata
  112693. #define sqlite3_get_table sqlite3_api->get_table
  112694. #ifndef SQLITE_OMIT_DEPRECATED
  112695. #define sqlite3_global_recover sqlite3_api->global_recover
  112696. #endif
  112697. #define sqlite3_interrupt sqlite3_api->interruptx
  112698. #define sqlite3_last_insert_rowid sqlite3_api->last_insert_rowid
  112699. #define sqlite3_libversion sqlite3_api->libversion
  112700. #define sqlite3_libversion_number sqlite3_api->libversion_number
  112701. #define sqlite3_malloc sqlite3_api->malloc
  112702. #define sqlite3_mprintf sqlite3_api->mprintf
  112703. #define sqlite3_open sqlite3_api->open
  112704. #define sqlite3_open16 sqlite3_api->open16
  112705. #define sqlite3_prepare sqlite3_api->prepare
  112706. #define sqlite3_prepare16 sqlite3_api->prepare16
  112707. #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
  112708. #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
  112709. #define sqlite3_profile sqlite3_api->profile
  112710. #define sqlite3_progress_handler sqlite3_api->progress_handler
  112711. #define sqlite3_realloc sqlite3_api->realloc
  112712. #define sqlite3_reset sqlite3_api->reset
  112713. #define sqlite3_result_blob sqlite3_api->result_blob
  112714. #define sqlite3_result_double sqlite3_api->result_double
  112715. #define sqlite3_result_error sqlite3_api->result_error
  112716. #define sqlite3_result_error16 sqlite3_api->result_error16
  112717. #define sqlite3_result_int sqlite3_api->result_int
  112718. #define sqlite3_result_int64 sqlite3_api->result_int64
  112719. #define sqlite3_result_null sqlite3_api->result_null
  112720. #define sqlite3_result_text sqlite3_api->result_text
  112721. #define sqlite3_result_text16 sqlite3_api->result_text16
  112722. #define sqlite3_result_text16be sqlite3_api->result_text16be
  112723. #define sqlite3_result_text16le sqlite3_api->result_text16le
  112724. #define sqlite3_result_value sqlite3_api->result_value
  112725. #define sqlite3_rollback_hook sqlite3_api->rollback_hook
  112726. #define sqlite3_set_authorizer sqlite3_api->set_authorizer
  112727. #define sqlite3_set_auxdata sqlite3_api->set_auxdata
  112728. #define sqlite3_snprintf sqlite3_api->xsnprintf
  112729. #define sqlite3_step sqlite3_api->step
  112730. #define sqlite3_table_column_metadata sqlite3_api->table_column_metadata
  112731. #define sqlite3_thread_cleanup sqlite3_api->thread_cleanup
  112732. #define sqlite3_total_changes sqlite3_api->total_changes
  112733. #define sqlite3_trace sqlite3_api->trace
  112734. #ifndef SQLITE_OMIT_DEPRECATED
  112735. #define sqlite3_transfer_bindings sqlite3_api->transfer_bindings
  112736. #endif
  112737. #define sqlite3_update_hook sqlite3_api->update_hook
  112738. #define sqlite3_user_data sqlite3_api->user_data
  112739. #define sqlite3_value_blob sqlite3_api->value_blob
  112740. #define sqlite3_value_bytes sqlite3_api->value_bytes
  112741. #define sqlite3_value_bytes16 sqlite3_api->value_bytes16
  112742. #define sqlite3_value_double sqlite3_api->value_double
  112743. #define sqlite3_value_int sqlite3_api->value_int
  112744. #define sqlite3_value_int64 sqlite3_api->value_int64
  112745. #define sqlite3_value_numeric_type sqlite3_api->value_numeric_type
  112746. #define sqlite3_value_text sqlite3_api->value_text
  112747. #define sqlite3_value_text16 sqlite3_api->value_text16
  112748. #define sqlite3_value_text16be sqlite3_api->value_text16be
  112749. #define sqlite3_value_text16le sqlite3_api->value_text16le
  112750. #define sqlite3_value_type sqlite3_api->value_type
  112751. #define sqlite3_vmprintf sqlite3_api->vmprintf
  112752. #define sqlite3_vsnprintf sqlite3_api->xvsnprintf
  112753. #define sqlite3_overload_function sqlite3_api->overload_function
  112754. #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
  112755. #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
  112756. #define sqlite3_clear_bindings sqlite3_api->clear_bindings
  112757. #define sqlite3_bind_zeroblob sqlite3_api->bind_zeroblob
  112758. #define sqlite3_blob_bytes sqlite3_api->blob_bytes
  112759. #define sqlite3_blob_close sqlite3_api->blob_close
  112760. #define sqlite3_blob_open sqlite3_api->blob_open
  112761. #define sqlite3_blob_read sqlite3_api->blob_read
  112762. #define sqlite3_blob_write sqlite3_api->blob_write
  112763. #define sqlite3_create_collation_v2 sqlite3_api->create_collation_v2
  112764. #define sqlite3_file_control sqlite3_api->file_control
  112765. #define sqlite3_memory_highwater sqlite3_api->memory_highwater
  112766. #define sqlite3_memory_used sqlite3_api->memory_used
  112767. #define sqlite3_mutex_alloc sqlite3_api->mutex_alloc
  112768. #define sqlite3_mutex_enter sqlite3_api->mutex_enter
  112769. #define sqlite3_mutex_free sqlite3_api->mutex_free
  112770. #define sqlite3_mutex_leave sqlite3_api->mutex_leave
  112771. #define sqlite3_mutex_try sqlite3_api->mutex_try
  112772. #define sqlite3_open_v2 sqlite3_api->open_v2
  112773. #define sqlite3_release_memory sqlite3_api->release_memory
  112774. #define sqlite3_result_error_nomem sqlite3_api->result_error_nomem
  112775. #define sqlite3_result_error_toobig sqlite3_api->result_error_toobig
  112776. #define sqlite3_sleep sqlite3_api->sleep
  112777. #define sqlite3_soft_heap_limit sqlite3_api->soft_heap_limit
  112778. #define sqlite3_vfs_find sqlite3_api->vfs_find
  112779. #define sqlite3_vfs_register sqlite3_api->vfs_register
  112780. #define sqlite3_vfs_unregister sqlite3_api->vfs_unregister
  112781. #define sqlite3_threadsafe sqlite3_api->xthreadsafe
  112782. #define sqlite3_result_zeroblob sqlite3_api->result_zeroblob
  112783. #define sqlite3_result_error_code sqlite3_api->result_error_code
  112784. #define sqlite3_test_control sqlite3_api->test_control
  112785. #define sqlite3_randomness sqlite3_api->randomness
  112786. #define sqlite3_context_db_handle sqlite3_api->context_db_handle
  112787. #define sqlite3_extended_result_codes sqlite3_api->extended_result_codes
  112788. #define sqlite3_limit sqlite3_api->limit
  112789. #define sqlite3_next_stmt sqlite3_api->next_stmt
  112790. #define sqlite3_sql sqlite3_api->sql
  112791. #define sqlite3_status sqlite3_api->status
  112792. #define sqlite3_backup_finish sqlite3_api->backup_finish
  112793. #define sqlite3_backup_init sqlite3_api->backup_init
  112794. #define sqlite3_backup_pagecount sqlite3_api->backup_pagecount
  112795. #define sqlite3_backup_remaining sqlite3_api->backup_remaining
  112796. #define sqlite3_backup_step sqlite3_api->backup_step
  112797. #define sqlite3_compileoption_get sqlite3_api->compileoption_get
  112798. #define sqlite3_compileoption_used sqlite3_api->compileoption_used
  112799. #define sqlite3_create_function_v2 sqlite3_api->create_function_v2
  112800. #define sqlite3_db_config sqlite3_api->db_config
  112801. #define sqlite3_db_mutex sqlite3_api->db_mutex
  112802. #define sqlite3_db_status sqlite3_api->db_status
  112803. #define sqlite3_extended_errcode sqlite3_api->extended_errcode
  112804. #define sqlite3_log sqlite3_api->log
  112805. #define sqlite3_soft_heap_limit64 sqlite3_api->soft_heap_limit64
  112806. #define sqlite3_sourceid sqlite3_api->sourceid
  112807. #define sqlite3_stmt_status sqlite3_api->stmt_status
  112808. #define sqlite3_strnicmp sqlite3_api->strnicmp
  112809. #define sqlite3_unlock_notify sqlite3_api->unlock_notify
  112810. #define sqlite3_wal_autocheckpoint sqlite3_api->wal_autocheckpoint
  112811. #define sqlite3_wal_checkpoint sqlite3_api->wal_checkpoint
  112812. #define sqlite3_wal_hook sqlite3_api->wal_hook
  112813. #define sqlite3_blob_reopen sqlite3_api->blob_reopen
  112814. #define sqlite3_vtab_config sqlite3_api->vtab_config
  112815. #define sqlite3_vtab_on_conflict sqlite3_api->vtab_on_conflict
  112816. /* Version 3.7.16 and later */
  112817. #define sqlite3_close_v2 sqlite3_api->close_v2
  112818. #define sqlite3_db_filename sqlite3_api->db_filename
  112819. #define sqlite3_db_readonly sqlite3_api->db_readonly
  112820. #define sqlite3_db_release_memory sqlite3_api->db_release_memory
  112821. #define sqlite3_errstr sqlite3_api->errstr
  112822. #define sqlite3_stmt_busy sqlite3_api->stmt_busy
  112823. #define sqlite3_stmt_readonly sqlite3_api->stmt_readonly
  112824. #define sqlite3_stricmp sqlite3_api->stricmp
  112825. #define sqlite3_uri_boolean sqlite3_api->uri_boolean
  112826. #define sqlite3_uri_int64 sqlite3_api->uri_int64
  112827. #define sqlite3_uri_parameter sqlite3_api->uri_parameter
  112828. #define sqlite3_uri_vsnprintf sqlite3_api->xvsnprintf
  112829. #define sqlite3_wal_checkpoint_v2 sqlite3_api->wal_checkpoint_v2
  112830. /* Version 3.8.7 and later */
  112831. #define sqlite3_auto_extension sqlite3_api->auto_extension
  112832. #define sqlite3_bind_blob64 sqlite3_api->bind_blob64
  112833. #define sqlite3_bind_text64 sqlite3_api->bind_text64
  112834. #define sqlite3_cancel_auto_extension sqlite3_api->cancel_auto_extension
  112835. #define sqlite3_load_extension sqlite3_api->load_extension
  112836. #define sqlite3_malloc64 sqlite3_api->malloc64
  112837. #define sqlite3_msize sqlite3_api->msize
  112838. #define sqlite3_realloc64 sqlite3_api->realloc64
  112839. #define sqlite3_reset_auto_extension sqlite3_api->reset_auto_extension
  112840. #define sqlite3_result_blob64 sqlite3_api->result_blob64
  112841. #define sqlite3_result_text64 sqlite3_api->result_text64
  112842. #define sqlite3_strglob sqlite3_api->strglob
  112843. /* Version 3.8.11 and later */
  112844. #define sqlite3_value_dup sqlite3_api->value_dup
  112845. #define sqlite3_value_free sqlite3_api->value_free
  112846. #define sqlite3_result_zeroblob64 sqlite3_api->result_zeroblob64
  112847. #define sqlite3_bind_zeroblob64 sqlite3_api->bind_zeroblob64
  112848. /* Version 3.9.0 and later */
  112849. #define sqlite3_value_subtype sqlite3_api->value_subtype
  112850. #define sqlite3_result_subtype sqlite3_api->result_subtype
  112851. /* Version 3.10.0 and later */
  112852. #define sqlite3_status64 sqlite3_api->status64
  112853. #define sqlite3_strlike sqlite3_api->strlike
  112854. #define sqlite3_db_cacheflush sqlite3_api->db_cacheflush
  112855. /* Version 3.12.0 and later */
  112856. #define sqlite3_system_errno sqlite3_api->system_errno
  112857. /* Version 3.14.0 and later */
  112858. #define sqlite3_trace_v2 sqlite3_api->trace_v2
  112859. #define sqlite3_expanded_sql sqlite3_api->expanded_sql
  112860. /* Version 3.18.0 and later */
  112861. #define sqlite3_set_last_insert_rowid sqlite3_api->set_last_insert_rowid
  112862. /* Version 3.20.0 and later */
  112863. #define sqlite3_prepare_v3 sqlite3_api->prepare_v3
  112864. #define sqlite3_prepare16_v3 sqlite3_api->prepare16_v3
  112865. #define sqlite3_bind_pointer sqlite3_api->bind_pointer
  112866. #define sqlite3_result_pointer sqlite3_api->result_pointer
  112867. #define sqlite3_value_pointer sqlite3_api->value_pointer
  112868. /* Version 3.22.0 and later */
  112869. #define sqlite3_vtab_nochange sqlite3_api->vtab_nochange
  112870. #define sqlite3_value_nochange sqlite3_api->value_nochange
  112871. #define sqlite3_vtab_collation sqlite3_api->vtab_collation
  112872. /* Version 3.24.0 and later */
  112873. #define sqlite3_keyword_count sqlite3_api->keyword_count
  112874. #define sqlite3_keyword_name sqlite3_api->keyword_name
  112875. #define sqlite3_keyword_check sqlite3_api->keyword_check
  112876. #define sqlite3_str_new sqlite3_api->str_new
  112877. #define sqlite3_str_finish sqlite3_api->str_finish
  112878. #define sqlite3_str_appendf sqlite3_api->str_appendf
  112879. #define sqlite3_str_vappendf sqlite3_api->str_vappendf
  112880. #define sqlite3_str_append sqlite3_api->str_append
  112881. #define sqlite3_str_appendall sqlite3_api->str_appendall
  112882. #define sqlite3_str_appendchar sqlite3_api->str_appendchar
  112883. #define sqlite3_str_reset sqlite3_api->str_reset
  112884. #define sqlite3_str_errcode sqlite3_api->str_errcode
  112885. #define sqlite3_str_length sqlite3_api->str_length
  112886. #define sqlite3_str_value sqlite3_api->str_value
  112887. /* Version 3.25.0 and later */
  112888. #define sqlite3_create_window_function sqlite3_api->create_window_function
  112889. /* Version 3.26.0 and later */
  112890. #define sqlite3_normalized_sql sqlite3_api->normalized_sql
  112891. /* Version 3.28.0 and later */
  112892. #define sqlite3_stmt_isexplain sqlite3_api->isexplain
  112893. #define sqlite3_value_frombind sqlite3_api->frombind
  112894. #endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */
  112895. #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  112896. /* This case when the file really is being compiled as a loadable
  112897. ** extension */
  112898. # define SQLITE_EXTENSION_INIT1 const sqlite3_api_routines *sqlite3_api=0;
  112899. # define SQLITE_EXTENSION_INIT2(v) sqlite3_api=v;
  112900. # define SQLITE_EXTENSION_INIT3 \
  112901. extern const sqlite3_api_routines *sqlite3_api;
  112902. #else
  112903. /* This case when the file is being statically linked into the
  112904. ** application */
  112905. # define SQLITE_EXTENSION_INIT1 /*no-op*/
  112906. # define SQLITE_EXTENSION_INIT2(v) (void)v; /* unused parameter */
  112907. # define SQLITE_EXTENSION_INIT3 /*no-op*/
  112908. #endif
  112909. #endif /* SQLITE3EXT_H */
  112910. /************** End of sqlite3ext.h ******************************************/
  112911. /************** Continuing where we left off in loadext.c ********************/
  112912. /* #include "sqliteInt.h" */
  112913. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  112914. /*
  112915. ** Some API routines are omitted when various features are
  112916. ** excluded from a build of SQLite. Substitute a NULL pointer
  112917. ** for any missing APIs.
  112918. */
  112919. #ifndef SQLITE_ENABLE_COLUMN_METADATA
  112920. # define sqlite3_column_database_name 0
  112921. # define sqlite3_column_database_name16 0
  112922. # define sqlite3_column_table_name 0
  112923. # define sqlite3_column_table_name16 0
  112924. # define sqlite3_column_origin_name 0
  112925. # define sqlite3_column_origin_name16 0
  112926. #endif
  112927. #ifdef SQLITE_OMIT_AUTHORIZATION
  112928. # define sqlite3_set_authorizer 0
  112929. #endif
  112930. #ifdef SQLITE_OMIT_UTF16
  112931. # define sqlite3_bind_text16 0
  112932. # define sqlite3_collation_needed16 0
  112933. # define sqlite3_column_decltype16 0
  112934. # define sqlite3_column_name16 0
  112935. # define sqlite3_column_text16 0
  112936. # define sqlite3_complete16 0
  112937. # define sqlite3_create_collation16 0
  112938. # define sqlite3_create_function16 0
  112939. # define sqlite3_errmsg16 0
  112940. # define sqlite3_open16 0
  112941. # define sqlite3_prepare16 0
  112942. # define sqlite3_prepare16_v2 0
  112943. # define sqlite3_prepare16_v3 0
  112944. # define sqlite3_result_error16 0
  112945. # define sqlite3_result_text16 0
  112946. # define sqlite3_result_text16be 0
  112947. # define sqlite3_result_text16le 0
  112948. # define sqlite3_value_text16 0
  112949. # define sqlite3_value_text16be 0
  112950. # define sqlite3_value_text16le 0
  112951. # define sqlite3_column_database_name16 0
  112952. # define sqlite3_column_table_name16 0
  112953. # define sqlite3_column_origin_name16 0
  112954. #endif
  112955. #ifdef SQLITE_OMIT_COMPLETE
  112956. # define sqlite3_complete 0
  112957. # define sqlite3_complete16 0
  112958. #endif
  112959. #ifdef SQLITE_OMIT_DECLTYPE
  112960. # define sqlite3_column_decltype16 0
  112961. # define sqlite3_column_decltype 0
  112962. #endif
  112963. #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
  112964. # define sqlite3_progress_handler 0
  112965. #endif
  112966. #ifdef SQLITE_OMIT_VIRTUALTABLE
  112967. # define sqlite3_create_module 0
  112968. # define sqlite3_create_module_v2 0
  112969. # define sqlite3_declare_vtab 0
  112970. # define sqlite3_vtab_config 0
  112971. # define sqlite3_vtab_on_conflict 0
  112972. # define sqlite3_vtab_collation 0
  112973. #endif
  112974. #ifdef SQLITE_OMIT_SHARED_CACHE
  112975. # define sqlite3_enable_shared_cache 0
  112976. #endif
  112977. #if defined(SQLITE_OMIT_TRACE) || defined(SQLITE_OMIT_DEPRECATED)
  112978. # define sqlite3_profile 0
  112979. # define sqlite3_trace 0
  112980. #endif
  112981. #ifdef SQLITE_OMIT_GET_TABLE
  112982. # define sqlite3_free_table 0
  112983. # define sqlite3_get_table 0
  112984. #endif
  112985. #ifdef SQLITE_OMIT_INCRBLOB
  112986. #define sqlite3_bind_zeroblob 0
  112987. #define sqlite3_blob_bytes 0
  112988. #define sqlite3_blob_close 0
  112989. #define sqlite3_blob_open 0
  112990. #define sqlite3_blob_read 0
  112991. #define sqlite3_blob_write 0
  112992. #define sqlite3_blob_reopen 0
  112993. #endif
  112994. #if defined(SQLITE_OMIT_TRACE)
  112995. # define sqlite3_trace_v2 0
  112996. #endif
  112997. /*
  112998. ** The following structure contains pointers to all SQLite API routines.
  112999. ** A pointer to this structure is passed into extensions when they are
  113000. ** loaded so that the extension can make calls back into the SQLite
  113001. ** library.
  113002. **
  113003. ** When adding new APIs, add them to the bottom of this structure
  113004. ** in order to preserve backwards compatibility.
  113005. **
  113006. ** Extensions that use newer APIs should first call the
  113007. ** sqlite3_libversion_number() to make sure that the API they
  113008. ** intend to use is supported by the library. Extensions should
  113009. ** also check to make sure that the pointer to the function is
  113010. ** not NULL before calling it.
  113011. */
  113012. static const sqlite3_api_routines sqlite3Apis = {
  113013. sqlite3_aggregate_context,
  113014. #ifndef SQLITE_OMIT_DEPRECATED
  113015. sqlite3_aggregate_count,
  113016. #else
  113017. 0,
  113018. #endif
  113019. sqlite3_bind_blob,
  113020. sqlite3_bind_double,
  113021. sqlite3_bind_int,
  113022. sqlite3_bind_int64,
  113023. sqlite3_bind_null,
  113024. sqlite3_bind_parameter_count,
  113025. sqlite3_bind_parameter_index,
  113026. sqlite3_bind_parameter_name,
  113027. sqlite3_bind_text,
  113028. sqlite3_bind_text16,
  113029. sqlite3_bind_value,
  113030. sqlite3_busy_handler,
  113031. sqlite3_busy_timeout,
  113032. sqlite3_changes,
  113033. sqlite3_close,
  113034. sqlite3_collation_needed,
  113035. sqlite3_collation_needed16,
  113036. sqlite3_column_blob,
  113037. sqlite3_column_bytes,
  113038. sqlite3_column_bytes16,
  113039. sqlite3_column_count,
  113040. sqlite3_column_database_name,
  113041. sqlite3_column_database_name16,
  113042. sqlite3_column_decltype,
  113043. sqlite3_column_decltype16,
  113044. sqlite3_column_double,
  113045. sqlite3_column_int,
  113046. sqlite3_column_int64,
  113047. sqlite3_column_name,
  113048. sqlite3_column_name16,
  113049. sqlite3_column_origin_name,
  113050. sqlite3_column_origin_name16,
  113051. sqlite3_column_table_name,
  113052. sqlite3_column_table_name16,
  113053. sqlite3_column_text,
  113054. sqlite3_column_text16,
  113055. sqlite3_column_type,
  113056. sqlite3_column_value,
  113057. sqlite3_commit_hook,
  113058. sqlite3_complete,
  113059. sqlite3_complete16,
  113060. sqlite3_create_collation,
  113061. sqlite3_create_collation16,
  113062. sqlite3_create_function,
  113063. sqlite3_create_function16,
  113064. sqlite3_create_module,
  113065. sqlite3_data_count,
  113066. sqlite3_db_handle,
  113067. sqlite3_declare_vtab,
  113068. sqlite3_enable_shared_cache,
  113069. sqlite3_errcode,
  113070. sqlite3_errmsg,
  113071. sqlite3_errmsg16,
  113072. sqlite3_exec,
  113073. #ifndef SQLITE_OMIT_DEPRECATED
  113074. sqlite3_expired,
  113075. #else
  113076. 0,
  113077. #endif
  113078. sqlite3_finalize,
  113079. sqlite3_free,
  113080. sqlite3_free_table,
  113081. sqlite3_get_autocommit,
  113082. sqlite3_get_auxdata,
  113083. sqlite3_get_table,
  113084. 0, /* Was sqlite3_global_recover(), but that function is deprecated */
  113085. sqlite3_interrupt,
  113086. sqlite3_last_insert_rowid,
  113087. sqlite3_libversion,
  113088. sqlite3_libversion_number,
  113089. sqlite3_malloc,
  113090. sqlite3_mprintf,
  113091. sqlite3_open,
  113092. sqlite3_open16,
  113093. sqlite3_prepare,
  113094. sqlite3_prepare16,
  113095. sqlite3_profile,
  113096. sqlite3_progress_handler,
  113097. sqlite3_realloc,
  113098. sqlite3_reset,
  113099. sqlite3_result_blob,
  113100. sqlite3_result_double,
  113101. sqlite3_result_error,
  113102. sqlite3_result_error16,
  113103. sqlite3_result_int,
  113104. sqlite3_result_int64,
  113105. sqlite3_result_null,
  113106. sqlite3_result_text,
  113107. sqlite3_result_text16,
  113108. sqlite3_result_text16be,
  113109. sqlite3_result_text16le,
  113110. sqlite3_result_value,
  113111. sqlite3_rollback_hook,
  113112. sqlite3_set_authorizer,
  113113. sqlite3_set_auxdata,
  113114. sqlite3_snprintf,
  113115. sqlite3_step,
  113116. sqlite3_table_column_metadata,
  113117. #ifndef SQLITE_OMIT_DEPRECATED
  113118. sqlite3_thread_cleanup,
  113119. #else
  113120. 0,
  113121. #endif
  113122. sqlite3_total_changes,
  113123. sqlite3_trace,
  113124. #ifndef SQLITE_OMIT_DEPRECATED
  113125. sqlite3_transfer_bindings,
  113126. #else
  113127. 0,
  113128. #endif
  113129. sqlite3_update_hook,
  113130. sqlite3_user_data,
  113131. sqlite3_value_blob,
  113132. sqlite3_value_bytes,
  113133. sqlite3_value_bytes16,
  113134. sqlite3_value_double,
  113135. sqlite3_value_int,
  113136. sqlite3_value_int64,
  113137. sqlite3_value_numeric_type,
  113138. sqlite3_value_text,
  113139. sqlite3_value_text16,
  113140. sqlite3_value_text16be,
  113141. sqlite3_value_text16le,
  113142. sqlite3_value_type,
  113143. sqlite3_vmprintf,
  113144. /*
  113145. ** The original API set ends here. All extensions can call any
  113146. ** of the APIs above provided that the pointer is not NULL. But
  113147. ** before calling APIs that follow, extension should check the
  113148. ** sqlite3_libversion_number() to make sure they are dealing with
  113149. ** a library that is new enough to support that API.
  113150. *************************************************************************
  113151. */
  113152. sqlite3_overload_function,
  113153. /*
  113154. ** Added after 3.3.13
  113155. */
  113156. sqlite3_prepare_v2,
  113157. sqlite3_prepare16_v2,
  113158. sqlite3_clear_bindings,
  113159. /*
  113160. ** Added for 3.4.1
  113161. */
  113162. sqlite3_create_module_v2,
  113163. /*
  113164. ** Added for 3.5.0
  113165. */
  113166. sqlite3_bind_zeroblob,
  113167. sqlite3_blob_bytes,
  113168. sqlite3_blob_close,
  113169. sqlite3_blob_open,
  113170. sqlite3_blob_read,
  113171. sqlite3_blob_write,
  113172. sqlite3_create_collation_v2,
  113173. sqlite3_file_control,
  113174. sqlite3_memory_highwater,
  113175. sqlite3_memory_used,
  113176. #ifdef SQLITE_MUTEX_OMIT
  113177. 0,
  113178. 0,
  113179. 0,
  113180. 0,
  113181. 0,
  113182. #else
  113183. sqlite3_mutex_alloc,
  113184. sqlite3_mutex_enter,
  113185. sqlite3_mutex_free,
  113186. sqlite3_mutex_leave,
  113187. sqlite3_mutex_try,
  113188. #endif
  113189. sqlite3_open_v2,
  113190. sqlite3_release_memory,
  113191. sqlite3_result_error_nomem,
  113192. sqlite3_result_error_toobig,
  113193. sqlite3_sleep,
  113194. sqlite3_soft_heap_limit,
  113195. sqlite3_vfs_find,
  113196. sqlite3_vfs_register,
  113197. sqlite3_vfs_unregister,
  113198. /*
  113199. ** Added for 3.5.8
  113200. */
  113201. sqlite3_threadsafe,
  113202. sqlite3_result_zeroblob,
  113203. sqlite3_result_error_code,
  113204. sqlite3_test_control,
  113205. sqlite3_randomness,
  113206. sqlite3_context_db_handle,
  113207. /*
  113208. ** Added for 3.6.0
  113209. */
  113210. sqlite3_extended_result_codes,
  113211. sqlite3_limit,
  113212. sqlite3_next_stmt,
  113213. sqlite3_sql,
  113214. sqlite3_status,
  113215. /*
  113216. ** Added for 3.7.4
  113217. */
  113218. sqlite3_backup_finish,
  113219. sqlite3_backup_init,
  113220. sqlite3_backup_pagecount,
  113221. sqlite3_backup_remaining,
  113222. sqlite3_backup_step,
  113223. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  113224. sqlite3_compileoption_get,
  113225. sqlite3_compileoption_used,
  113226. #else
  113227. 0,
  113228. 0,
  113229. #endif
  113230. sqlite3_create_function_v2,
  113231. sqlite3_db_config,
  113232. sqlite3_db_mutex,
  113233. sqlite3_db_status,
  113234. sqlite3_extended_errcode,
  113235. sqlite3_log,
  113236. sqlite3_soft_heap_limit64,
  113237. sqlite3_sourceid,
  113238. sqlite3_stmt_status,
  113239. sqlite3_strnicmp,
  113240. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  113241. sqlite3_unlock_notify,
  113242. #else
  113243. 0,
  113244. #endif
  113245. #ifndef SQLITE_OMIT_WAL
  113246. sqlite3_wal_autocheckpoint,
  113247. sqlite3_wal_checkpoint,
  113248. sqlite3_wal_hook,
  113249. #else
  113250. 0,
  113251. 0,
  113252. 0,
  113253. #endif
  113254. sqlite3_blob_reopen,
  113255. sqlite3_vtab_config,
  113256. sqlite3_vtab_on_conflict,
  113257. sqlite3_close_v2,
  113258. sqlite3_db_filename,
  113259. sqlite3_db_readonly,
  113260. sqlite3_db_release_memory,
  113261. sqlite3_errstr,
  113262. sqlite3_stmt_busy,
  113263. sqlite3_stmt_readonly,
  113264. sqlite3_stricmp,
  113265. sqlite3_uri_boolean,
  113266. sqlite3_uri_int64,
  113267. sqlite3_uri_parameter,
  113268. sqlite3_vsnprintf,
  113269. sqlite3_wal_checkpoint_v2,
  113270. /* Version 3.8.7 and later */
  113271. sqlite3_auto_extension,
  113272. sqlite3_bind_blob64,
  113273. sqlite3_bind_text64,
  113274. sqlite3_cancel_auto_extension,
  113275. sqlite3_load_extension,
  113276. sqlite3_malloc64,
  113277. sqlite3_msize,
  113278. sqlite3_realloc64,
  113279. sqlite3_reset_auto_extension,
  113280. sqlite3_result_blob64,
  113281. sqlite3_result_text64,
  113282. sqlite3_strglob,
  113283. /* Version 3.8.11 and later */
  113284. (sqlite3_value*(*)(const sqlite3_value*))sqlite3_value_dup,
  113285. sqlite3_value_free,
  113286. sqlite3_result_zeroblob64,
  113287. sqlite3_bind_zeroblob64,
  113288. /* Version 3.9.0 and later */
  113289. sqlite3_value_subtype,
  113290. sqlite3_result_subtype,
  113291. /* Version 3.10.0 and later */
  113292. sqlite3_status64,
  113293. sqlite3_strlike,
  113294. sqlite3_db_cacheflush,
  113295. /* Version 3.12.0 and later */
  113296. sqlite3_system_errno,
  113297. /* Version 3.14.0 and later */
  113298. sqlite3_trace_v2,
  113299. sqlite3_expanded_sql,
  113300. /* Version 3.18.0 and later */
  113301. sqlite3_set_last_insert_rowid,
  113302. /* Version 3.20.0 and later */
  113303. sqlite3_prepare_v3,
  113304. sqlite3_prepare16_v3,
  113305. sqlite3_bind_pointer,
  113306. sqlite3_result_pointer,
  113307. sqlite3_value_pointer,
  113308. /* Version 3.22.0 and later */
  113309. sqlite3_vtab_nochange,
  113310. sqlite3_value_nochange,
  113311. sqlite3_vtab_collation,
  113312. /* Version 3.24.0 and later */
  113313. sqlite3_keyword_count,
  113314. sqlite3_keyword_name,
  113315. sqlite3_keyword_check,
  113316. sqlite3_str_new,
  113317. sqlite3_str_finish,
  113318. sqlite3_str_appendf,
  113319. sqlite3_str_vappendf,
  113320. sqlite3_str_append,
  113321. sqlite3_str_appendall,
  113322. sqlite3_str_appendchar,
  113323. sqlite3_str_reset,
  113324. sqlite3_str_errcode,
  113325. sqlite3_str_length,
  113326. sqlite3_str_value,
  113327. /* Version 3.25.0 and later */
  113328. sqlite3_create_window_function,
  113329. /* Version 3.26.0 and later */
  113330. #ifdef SQLITE_ENABLE_NORMALIZE
  113331. sqlite3_normalized_sql,
  113332. #else
  113333. 0,
  113334. #endif
  113335. /* Version 3.28.0 and later */
  113336. sqlite3_stmt_isexplain,
  113337. sqlite3_value_frombind
  113338. };
  113339. /*
  113340. ** Attempt to load an SQLite extension library contained in the file
  113341. ** zFile. The entry point is zProc. zProc may be 0 in which case a
  113342. ** default entry point name (sqlite3_extension_init) is used. Use
  113343. ** of the default name is recommended.
  113344. **
  113345. ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
  113346. **
  113347. ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
  113348. ** error message text. The calling function should free this memory
  113349. ** by calling sqlite3DbFree(db, ).
  113350. */
  113351. static int sqlite3LoadExtension(
  113352. sqlite3 *db, /* Load the extension into this database connection */
  113353. const char *zFile, /* Name of the shared library containing extension */
  113354. const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
  113355. char **pzErrMsg /* Put error message here if not 0 */
  113356. ){
  113357. sqlite3_vfs *pVfs = db->pVfs;
  113358. void *handle;
  113359. sqlite3_loadext_entry xInit;
  113360. char *zErrmsg = 0;
  113361. const char *zEntry;
  113362. char *zAltEntry = 0;
  113363. void **aHandle;
  113364. u64 nMsg = 300 + sqlite3Strlen30(zFile);
  113365. int ii;
  113366. int rc;
  113367. /* Shared library endings to try if zFile cannot be loaded as written */
  113368. static const char *azEndings[] = {
  113369. #if SQLITE_OS_WIN
  113370. "dll"
  113371. #elif defined(__APPLE__)
  113372. "dylib"
  113373. #else
  113374. "so"
  113375. #endif
  113376. };
  113377. if( pzErrMsg ) *pzErrMsg = 0;
  113378. /* Ticket #1863. To avoid a creating security problems for older
  113379. ** applications that relink against newer versions of SQLite, the
  113380. ** ability to run load_extension is turned off by default. One
  113381. ** must call either sqlite3_enable_load_extension(db) or
  113382. ** sqlite3_db_config(db, SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, 1, 0)
  113383. ** to turn on extension loading.
  113384. */
  113385. if( (db->flags & SQLITE_LoadExtension)==0 ){
  113386. if( pzErrMsg ){
  113387. *pzErrMsg = sqlite3_mprintf("not authorized");
  113388. }
  113389. return SQLITE_ERROR;
  113390. }
  113391. zEntry = zProc ? zProc : "sqlite3_extension_init";
  113392. handle = sqlite3OsDlOpen(pVfs, zFile);
  113393. #if SQLITE_OS_UNIX || SQLITE_OS_WIN
  113394. for(ii=0; ii<ArraySize(azEndings) && handle==0; ii++){
  113395. char *zAltFile = sqlite3_mprintf("%s.%s", zFile, azEndings[ii]);
  113396. if( zAltFile==0 ) return SQLITE_NOMEM_BKPT;
  113397. handle = sqlite3OsDlOpen(pVfs, zAltFile);
  113398. sqlite3_free(zAltFile);
  113399. }
  113400. #endif
  113401. if( handle==0 ){
  113402. if( pzErrMsg ){
  113403. *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
  113404. if( zErrmsg ){
  113405. sqlite3_snprintf(nMsg, zErrmsg,
  113406. "unable to open shared library [%s]", zFile);
  113407. sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
  113408. }
  113409. }
  113410. return SQLITE_ERROR;
  113411. }
  113412. xInit = (sqlite3_loadext_entry)sqlite3OsDlSym(pVfs, handle, zEntry);
  113413. /* If no entry point was specified and the default legacy
  113414. ** entry point name "sqlite3_extension_init" was not found, then
  113415. ** construct an entry point name "sqlite3_X_init" where the X is
  113416. ** replaced by the lowercase value of every ASCII alphabetic
  113417. ** character in the filename after the last "/" upto the first ".",
  113418. ** and eliding the first three characters if they are "lib".
  113419. ** Examples:
  113420. **
  113421. ** /usr/local/lib/libExample5.4.3.so ==> sqlite3_example_init
  113422. ** C:/lib/mathfuncs.dll ==> sqlite3_mathfuncs_init
  113423. */
  113424. if( xInit==0 && zProc==0 ){
  113425. int iFile, iEntry, c;
  113426. int ncFile = sqlite3Strlen30(zFile);
  113427. zAltEntry = sqlite3_malloc64(ncFile+30);
  113428. if( zAltEntry==0 ){
  113429. sqlite3OsDlClose(pVfs, handle);
  113430. return SQLITE_NOMEM_BKPT;
  113431. }
  113432. memcpy(zAltEntry, "sqlite3_", 8);
  113433. for(iFile=ncFile-1; iFile>=0 && zFile[iFile]!='/'; iFile--){}
  113434. iFile++;
  113435. if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3;
  113436. for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){
  113437. if( sqlite3Isalpha(c) ){
  113438. zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c];
  113439. }
  113440. }
  113441. memcpy(zAltEntry+iEntry, "_init", 6);
  113442. zEntry = zAltEntry;
  113443. xInit = (sqlite3_loadext_entry)sqlite3OsDlSym(pVfs, handle, zEntry);
  113444. }
  113445. if( xInit==0 ){
  113446. if( pzErrMsg ){
  113447. nMsg += sqlite3Strlen30(zEntry);
  113448. *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
  113449. if( zErrmsg ){
  113450. sqlite3_snprintf(nMsg, zErrmsg,
  113451. "no entry point [%s] in shared library [%s]", zEntry, zFile);
  113452. sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
  113453. }
  113454. }
  113455. sqlite3OsDlClose(pVfs, handle);
  113456. sqlite3_free(zAltEntry);
  113457. return SQLITE_ERROR;
  113458. }
  113459. sqlite3_free(zAltEntry);
  113460. rc = xInit(db, &zErrmsg, &sqlite3Apis);
  113461. if( rc ){
  113462. if( rc==SQLITE_OK_LOAD_PERMANENTLY ) return SQLITE_OK;
  113463. if( pzErrMsg ){
  113464. *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
  113465. }
  113466. sqlite3_free(zErrmsg);
  113467. sqlite3OsDlClose(pVfs, handle);
  113468. return SQLITE_ERROR;
  113469. }
  113470. /* Append the new shared library handle to the db->aExtension array. */
  113471. aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
  113472. if( aHandle==0 ){
  113473. return SQLITE_NOMEM_BKPT;
  113474. }
  113475. if( db->nExtension>0 ){
  113476. memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
  113477. }
  113478. sqlite3DbFree(db, db->aExtension);
  113479. db->aExtension = aHandle;
  113480. db->aExtension[db->nExtension++] = handle;
  113481. return SQLITE_OK;
  113482. }
  113483. SQLITE_API int sqlite3_load_extension(
  113484. sqlite3 *db, /* Load the extension into this database connection */
  113485. const char *zFile, /* Name of the shared library containing extension */
  113486. const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
  113487. char **pzErrMsg /* Put error message here if not 0 */
  113488. ){
  113489. int rc;
  113490. sqlite3_mutex_enter(db->mutex);
  113491. rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
  113492. rc = sqlite3ApiExit(db, rc);
  113493. sqlite3_mutex_leave(db->mutex);
  113494. return rc;
  113495. }
  113496. /*
  113497. ** Call this routine when the database connection is closing in order
  113498. ** to clean up loaded extensions
  113499. */
  113500. SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
  113501. int i;
  113502. assert( sqlite3_mutex_held(db->mutex) );
  113503. for(i=0; i<db->nExtension; i++){
  113504. sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
  113505. }
  113506. sqlite3DbFree(db, db->aExtension);
  113507. }
  113508. /*
  113509. ** Enable or disable extension loading. Extension loading is disabled by
  113510. ** default so as not to open security holes in older applications.
  113511. */
  113512. SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
  113513. sqlite3_mutex_enter(db->mutex);
  113514. if( onoff ){
  113515. db->flags |= SQLITE_LoadExtension|SQLITE_LoadExtFunc;
  113516. }else{
  113517. db->flags &= ~(u64)(SQLITE_LoadExtension|SQLITE_LoadExtFunc);
  113518. }
  113519. sqlite3_mutex_leave(db->mutex);
  113520. return SQLITE_OK;
  113521. }
  113522. #endif /* !defined(SQLITE_OMIT_LOAD_EXTENSION) */
  113523. /*
  113524. ** The following object holds the list of automatically loaded
  113525. ** extensions.
  113526. **
  113527. ** This list is shared across threads. The SQLITE_MUTEX_STATIC_MASTER
  113528. ** mutex must be held while accessing this list.
  113529. */
  113530. typedef struct sqlite3AutoExtList sqlite3AutoExtList;
  113531. static SQLITE_WSD struct sqlite3AutoExtList {
  113532. u32 nExt; /* Number of entries in aExt[] */
  113533. void (**aExt)(void); /* Pointers to the extension init functions */
  113534. } sqlite3Autoext = { 0, 0 };
  113535. /* The "wsdAutoext" macro will resolve to the autoextension
  113536. ** state vector. If writable static data is unsupported on the target,
  113537. ** we have to locate the state vector at run-time. In the more common
  113538. ** case where writable static data is supported, wsdStat can refer directly
  113539. ** to the "sqlite3Autoext" state vector declared above.
  113540. */
  113541. #ifdef SQLITE_OMIT_WSD
  113542. # define wsdAutoextInit \
  113543. sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
  113544. # define wsdAutoext x[0]
  113545. #else
  113546. # define wsdAutoextInit
  113547. # define wsdAutoext sqlite3Autoext
  113548. #endif
  113549. /*
  113550. ** Register a statically linked extension that is automatically
  113551. ** loaded by every new database connection.
  113552. */
  113553. SQLITE_API int sqlite3_auto_extension(
  113554. void (*xInit)(void)
  113555. ){
  113556. int rc = SQLITE_OK;
  113557. #ifndef SQLITE_OMIT_AUTOINIT
  113558. rc = sqlite3_initialize();
  113559. if( rc ){
  113560. return rc;
  113561. }else
  113562. #endif
  113563. {
  113564. u32 i;
  113565. #if SQLITE_THREADSAFE
  113566. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  113567. #endif
  113568. wsdAutoextInit;
  113569. sqlite3_mutex_enter(mutex);
  113570. for(i=0; i<wsdAutoext.nExt; i++){
  113571. if( wsdAutoext.aExt[i]==xInit ) break;
  113572. }
  113573. if( i==wsdAutoext.nExt ){
  113574. u64 nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
  113575. void (**aNew)(void);
  113576. aNew = sqlite3_realloc64(wsdAutoext.aExt, nByte);
  113577. if( aNew==0 ){
  113578. rc = SQLITE_NOMEM_BKPT;
  113579. }else{
  113580. wsdAutoext.aExt = aNew;
  113581. wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
  113582. wsdAutoext.nExt++;
  113583. }
  113584. }
  113585. sqlite3_mutex_leave(mutex);
  113586. assert( (rc&0xff)==rc );
  113587. return rc;
  113588. }
  113589. }
  113590. /*
  113591. ** Cancel a prior call to sqlite3_auto_extension. Remove xInit from the
  113592. ** set of routines that is invoked for each new database connection, if it
  113593. ** is currently on the list. If xInit is not on the list, then this
  113594. ** routine is a no-op.
  113595. **
  113596. ** Return 1 if xInit was found on the list and removed. Return 0 if xInit
  113597. ** was not on the list.
  113598. */
  113599. SQLITE_API int sqlite3_cancel_auto_extension(
  113600. void (*xInit)(void)
  113601. ){
  113602. #if SQLITE_THREADSAFE
  113603. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  113604. #endif
  113605. int i;
  113606. int n = 0;
  113607. wsdAutoextInit;
  113608. sqlite3_mutex_enter(mutex);
  113609. for(i=(int)wsdAutoext.nExt-1; i>=0; i--){
  113610. if( wsdAutoext.aExt[i]==xInit ){
  113611. wsdAutoext.nExt--;
  113612. wsdAutoext.aExt[i] = wsdAutoext.aExt[wsdAutoext.nExt];
  113613. n++;
  113614. break;
  113615. }
  113616. }
  113617. sqlite3_mutex_leave(mutex);
  113618. return n;
  113619. }
  113620. /*
  113621. ** Reset the automatic extension loading mechanism.
  113622. */
  113623. SQLITE_API void sqlite3_reset_auto_extension(void){
  113624. #ifndef SQLITE_OMIT_AUTOINIT
  113625. if( sqlite3_initialize()==SQLITE_OK )
  113626. #endif
  113627. {
  113628. #if SQLITE_THREADSAFE
  113629. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  113630. #endif
  113631. wsdAutoextInit;
  113632. sqlite3_mutex_enter(mutex);
  113633. sqlite3_free(wsdAutoext.aExt);
  113634. wsdAutoext.aExt = 0;
  113635. wsdAutoext.nExt = 0;
  113636. sqlite3_mutex_leave(mutex);
  113637. }
  113638. }
  113639. /*
  113640. ** Load all automatic extensions.
  113641. **
  113642. ** If anything goes wrong, set an error in the database connection.
  113643. */
  113644. SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
  113645. u32 i;
  113646. int go = 1;
  113647. int rc;
  113648. sqlite3_loadext_entry xInit;
  113649. wsdAutoextInit;
  113650. if( wsdAutoext.nExt==0 ){
  113651. /* Common case: early out without every having to acquire a mutex */
  113652. return;
  113653. }
  113654. for(i=0; go; i++){
  113655. char *zErrmsg;
  113656. #if SQLITE_THREADSAFE
  113657. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  113658. #endif
  113659. #ifdef SQLITE_OMIT_LOAD_EXTENSION
  113660. const sqlite3_api_routines *pThunk = 0;
  113661. #else
  113662. const sqlite3_api_routines *pThunk = &sqlite3Apis;
  113663. #endif
  113664. sqlite3_mutex_enter(mutex);
  113665. if( i>=wsdAutoext.nExt ){
  113666. xInit = 0;
  113667. go = 0;
  113668. }else{
  113669. xInit = (sqlite3_loadext_entry)wsdAutoext.aExt[i];
  113670. }
  113671. sqlite3_mutex_leave(mutex);
  113672. zErrmsg = 0;
  113673. if( xInit && (rc = xInit(db, &zErrmsg, pThunk))!=0 ){
  113674. sqlite3ErrorWithMsg(db, rc,
  113675. "automatic extension loading failed: %s", zErrmsg);
  113676. go = 0;
  113677. }
  113678. sqlite3_free(zErrmsg);
  113679. }
  113680. }
  113681. /************** End of loadext.c *********************************************/
  113682. /************** Begin file pragma.c ******************************************/
  113683. /*
  113684. ** 2003 April 6
  113685. **
  113686. ** The author disclaims copyright to this source code. In place of
  113687. ** a legal notice, here is a blessing:
  113688. **
  113689. ** May you do good and not evil.
  113690. ** May you find forgiveness for yourself and forgive others.
  113691. ** May you share freely, never taking more than you give.
  113692. **
  113693. *************************************************************************
  113694. ** This file contains code used to implement the PRAGMA command.
  113695. */
  113696. /* #include "sqliteInt.h" */
  113697. #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
  113698. # if defined(__APPLE__)
  113699. # define SQLITE_ENABLE_LOCKING_STYLE 1
  113700. # else
  113701. # define SQLITE_ENABLE_LOCKING_STYLE 0
  113702. # endif
  113703. #endif
  113704. /***************************************************************************
  113705. ** The "pragma.h" include file is an automatically generated file that
  113706. ** that includes the PragType_XXXX macro definitions and the aPragmaName[]
  113707. ** object. This ensures that the aPragmaName[] table is arranged in
  113708. ** lexicographical order to facility a binary search of the pragma name.
  113709. ** Do not edit pragma.h directly. Edit and rerun the script in at
  113710. ** ../tool/mkpragmatab.tcl. */
  113711. /************** Include pragma.h in the middle of pragma.c *******************/
  113712. /************** Begin file pragma.h ******************************************/
  113713. /* DO NOT EDIT!
  113714. ** This file is automatically generated by the script at
  113715. ** ../tool/mkpragmatab.tcl. To update the set of pragmas, edit
  113716. ** that script and rerun it.
  113717. */
  113718. /* The various pragma types */
  113719. #define PragTyp_HEADER_VALUE 0
  113720. #define PragTyp_AUTO_VACUUM 1
  113721. #define PragTyp_FLAG 2
  113722. #define PragTyp_BUSY_TIMEOUT 3
  113723. #define PragTyp_CACHE_SIZE 4
  113724. #define PragTyp_CACHE_SPILL 5
  113725. #define PragTyp_CASE_SENSITIVE_LIKE 6
  113726. #define PragTyp_COLLATION_LIST 7
  113727. #define PragTyp_COMPILE_OPTIONS 8
  113728. #define PragTyp_DATA_STORE_DIRECTORY 9
  113729. #define PragTyp_DATABASE_LIST 10
  113730. #define PragTyp_DEFAULT_CACHE_SIZE 11
  113731. #define PragTyp_ENCODING 12
  113732. #define PragTyp_FOREIGN_KEY_CHECK 13
  113733. #define PragTyp_FOREIGN_KEY_LIST 14
  113734. #define PragTyp_FUNCTION_LIST 15
  113735. #define PragTyp_INCREMENTAL_VACUUM 16
  113736. #define PragTyp_INDEX_INFO 17
  113737. #define PragTyp_INDEX_LIST 18
  113738. #define PragTyp_INTEGRITY_CHECK 19
  113739. #define PragTyp_JOURNAL_MODE 20
  113740. #define PragTyp_JOURNAL_SIZE_LIMIT 21
  113741. #define PragTyp_LOCK_PROXY_FILE 22
  113742. #define PragTyp_LOCKING_MODE 23
  113743. #define PragTyp_PAGE_COUNT 24
  113744. #define PragTyp_MMAP_SIZE 25
  113745. #define PragTyp_MODULE_LIST 26
  113746. #define PragTyp_OPTIMIZE 27
  113747. #define PragTyp_PAGE_SIZE 28
  113748. #define PragTyp_PRAGMA_LIST 29
  113749. #define PragTyp_SECURE_DELETE 30
  113750. #define PragTyp_SHRINK_MEMORY 31
  113751. #define PragTyp_SOFT_HEAP_LIMIT 32
  113752. #define PragTyp_SYNCHRONOUS 33
  113753. #define PragTyp_TABLE_INFO 34
  113754. #define PragTyp_TEMP_STORE 35
  113755. #define PragTyp_TEMP_STORE_DIRECTORY 36
  113756. #define PragTyp_THREADS 37
  113757. #define PragTyp_WAL_AUTOCHECKPOINT 38
  113758. #define PragTyp_WAL_CHECKPOINT 39
  113759. #define PragTyp_ACTIVATE_EXTENSIONS 40
  113760. #define PragTyp_KEY 41
  113761. #define PragTyp_LOCK_STATUS 42
  113762. #define PragTyp_STATS 43
  113763. /* Property flags associated with various pragma. */
  113764. #define PragFlg_NeedSchema 0x01 /* Force schema load before running */
  113765. #define PragFlg_NoColumns 0x02 /* OP_ResultRow called with zero columns */
  113766. #define PragFlg_NoColumns1 0x04 /* zero columns if RHS argument is present */
  113767. #define PragFlg_ReadOnly 0x08 /* Read-only HEADER_VALUE */
  113768. #define PragFlg_Result0 0x10 /* Acts as query when no argument */
  113769. #define PragFlg_Result1 0x20 /* Acts as query when has one argument */
  113770. #define PragFlg_SchemaOpt 0x40 /* Schema restricts name search if present */
  113771. #define PragFlg_SchemaReq 0x80 /* Schema required - "main" is default */
  113772. /* Names of columns for pragmas that return multi-column result
  113773. ** or that return single-column results where the name of the
  113774. ** result column is different from the name of the pragma
  113775. */
  113776. static const char *const pragCName[] = {
  113777. /* 0 */ "id", /* Used by: foreign_key_list */
  113778. /* 1 */ "seq",
  113779. /* 2 */ "table",
  113780. /* 3 */ "from",
  113781. /* 4 */ "to",
  113782. /* 5 */ "on_update",
  113783. /* 6 */ "on_delete",
  113784. /* 7 */ "match",
  113785. /* 8 */ "cid", /* Used by: table_xinfo */
  113786. /* 9 */ "name",
  113787. /* 10 */ "type",
  113788. /* 11 */ "notnull",
  113789. /* 12 */ "dflt_value",
  113790. /* 13 */ "pk",
  113791. /* 14 */ "hidden",
  113792. /* table_info reuses 8 */
  113793. /* 15 */ "seqno", /* Used by: index_xinfo */
  113794. /* 16 */ "cid",
  113795. /* 17 */ "name",
  113796. /* 18 */ "desc",
  113797. /* 19 */ "coll",
  113798. /* 20 */ "key",
  113799. /* 21 */ "tbl", /* Used by: stats */
  113800. /* 22 */ "idx",
  113801. /* 23 */ "wdth",
  113802. /* 24 */ "hght",
  113803. /* 25 */ "flgs",
  113804. /* 26 */ "seq", /* Used by: index_list */
  113805. /* 27 */ "name",
  113806. /* 28 */ "unique",
  113807. /* 29 */ "origin",
  113808. /* 30 */ "partial",
  113809. /* 31 */ "table", /* Used by: foreign_key_check */
  113810. /* 32 */ "rowid",
  113811. /* 33 */ "parent",
  113812. /* 34 */ "fkid",
  113813. /* index_info reuses 15 */
  113814. /* 35 */ "seq", /* Used by: database_list */
  113815. /* 36 */ "name",
  113816. /* 37 */ "file",
  113817. /* 38 */ "busy", /* Used by: wal_checkpoint */
  113818. /* 39 */ "log",
  113819. /* 40 */ "checkpointed",
  113820. /* 41 */ "name", /* Used by: function_list */
  113821. /* 42 */ "builtin",
  113822. /* collation_list reuses 26 */
  113823. /* 43 */ "database", /* Used by: lock_status */
  113824. /* 44 */ "status",
  113825. /* 45 */ "cache_size", /* Used by: default_cache_size */
  113826. /* module_list pragma_list reuses 9 */
  113827. /* 46 */ "timeout", /* Used by: busy_timeout */
  113828. };
  113829. /* Definitions of all built-in pragmas */
  113830. typedef struct PragmaName {
  113831. const char *const zName; /* Name of pragma */
  113832. u8 ePragTyp; /* PragTyp_XXX value */
  113833. u8 mPragFlg; /* Zero or more PragFlg_XXX values */
  113834. u8 iPragCName; /* Start of column names in pragCName[] */
  113835. u8 nPragCName; /* Num of col names. 0 means use pragma name */
  113836. u64 iArg; /* Extra argument */
  113837. } PragmaName;
  113838. static const PragmaName aPragmaName[] = {
  113839. #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
  113840. {/* zName: */ "activate_extensions",
  113841. /* ePragTyp: */ PragTyp_ACTIVATE_EXTENSIONS,
  113842. /* ePragFlg: */ 0,
  113843. /* ColNames: */ 0, 0,
  113844. /* iArg: */ 0 },
  113845. #endif
  113846. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  113847. {/* zName: */ "application_id",
  113848. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  113849. /* ePragFlg: */ PragFlg_NoColumns1|PragFlg_Result0,
  113850. /* ColNames: */ 0, 0,
  113851. /* iArg: */ BTREE_APPLICATION_ID },
  113852. #endif
  113853. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  113854. {/* zName: */ "auto_vacuum",
  113855. /* ePragTyp: */ PragTyp_AUTO_VACUUM,
  113856. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
  113857. /* ColNames: */ 0, 0,
  113858. /* iArg: */ 0 },
  113859. #endif
  113860. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  113861. #if !defined(SQLITE_OMIT_AUTOMATIC_INDEX)
  113862. {/* zName: */ "automatic_index",
  113863. /* ePragTyp: */ PragTyp_FLAG,
  113864. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  113865. /* ColNames: */ 0, 0,
  113866. /* iArg: */ SQLITE_AutoIndex },
  113867. #endif
  113868. #endif
  113869. {/* zName: */ "busy_timeout",
  113870. /* ePragTyp: */ PragTyp_BUSY_TIMEOUT,
  113871. /* ePragFlg: */ PragFlg_Result0,
  113872. /* ColNames: */ 46, 1,
  113873. /* iArg: */ 0 },
  113874. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  113875. {/* zName: */ "cache_size",
  113876. /* ePragTyp: */ PragTyp_CACHE_SIZE,
  113877. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
  113878. /* ColNames: */ 0, 0,
  113879. /* iArg: */ 0 },
  113880. #endif
  113881. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  113882. {/* zName: */ "cache_spill",
  113883. /* ePragTyp: */ PragTyp_CACHE_SPILL,
  113884. /* ePragFlg: */ PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
  113885. /* ColNames: */ 0, 0,
  113886. /* iArg: */ 0 },
  113887. #endif
  113888. #if !defined(SQLITE_OMIT_CASE_SENSITIVE_LIKE_PRAGMA)
  113889. {/* zName: */ "case_sensitive_like",
  113890. /* ePragTyp: */ PragTyp_CASE_SENSITIVE_LIKE,
  113891. /* ePragFlg: */ PragFlg_NoColumns,
  113892. /* ColNames: */ 0, 0,
  113893. /* iArg: */ 0 },
  113894. #endif
  113895. {/* zName: */ "cell_size_check",
  113896. /* ePragTyp: */ PragTyp_FLAG,
  113897. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  113898. /* ColNames: */ 0, 0,
  113899. /* iArg: */ SQLITE_CellSizeCk },
  113900. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  113901. {/* zName: */ "checkpoint_fullfsync",
  113902. /* ePragTyp: */ PragTyp_FLAG,
  113903. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  113904. /* ColNames: */ 0, 0,
  113905. /* iArg: */ SQLITE_CkptFullFSync },
  113906. #endif
  113907. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  113908. {/* zName: */ "collation_list",
  113909. /* ePragTyp: */ PragTyp_COLLATION_LIST,
  113910. /* ePragFlg: */ PragFlg_Result0,
  113911. /* ColNames: */ 26, 2,
  113912. /* iArg: */ 0 },
  113913. #endif
  113914. #if !defined(SQLITE_OMIT_COMPILEOPTION_DIAGS)
  113915. {/* zName: */ "compile_options",
  113916. /* ePragTyp: */ PragTyp_COMPILE_OPTIONS,
  113917. /* ePragFlg: */ PragFlg_Result0,
  113918. /* ColNames: */ 0, 0,
  113919. /* iArg: */ 0 },
  113920. #endif
  113921. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  113922. {/* zName: */ "count_changes",
  113923. /* ePragTyp: */ PragTyp_FLAG,
  113924. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  113925. /* ColNames: */ 0, 0,
  113926. /* iArg: */ SQLITE_CountRows },
  113927. #endif
  113928. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_OS_WIN
  113929. {/* zName: */ "data_store_directory",
  113930. /* ePragTyp: */ PragTyp_DATA_STORE_DIRECTORY,
  113931. /* ePragFlg: */ PragFlg_NoColumns1,
  113932. /* ColNames: */ 0, 0,
  113933. /* iArg: */ 0 },
  113934. #endif
  113935. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  113936. {/* zName: */ "data_version",
  113937. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  113938. /* ePragFlg: */ PragFlg_ReadOnly|PragFlg_Result0,
  113939. /* ColNames: */ 0, 0,
  113940. /* iArg: */ BTREE_DATA_VERSION },
  113941. #endif
  113942. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  113943. {/* zName: */ "database_list",
  113944. /* ePragTyp: */ PragTyp_DATABASE_LIST,
  113945. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0,
  113946. /* ColNames: */ 35, 3,
  113947. /* iArg: */ 0 },
  113948. #endif
  113949. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
  113950. {/* zName: */ "default_cache_size",
  113951. /* ePragTyp: */ PragTyp_DEFAULT_CACHE_SIZE,
  113952. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
  113953. /* ColNames: */ 45, 1,
  113954. /* iArg: */ 0 },
  113955. #endif
  113956. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  113957. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  113958. {/* zName: */ "defer_foreign_keys",
  113959. /* ePragTyp: */ PragTyp_FLAG,
  113960. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  113961. /* ColNames: */ 0, 0,
  113962. /* iArg: */ SQLITE_DeferFKs },
  113963. #endif
  113964. #endif
  113965. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  113966. {/* zName: */ "empty_result_callbacks",
  113967. /* ePragTyp: */ PragTyp_FLAG,
  113968. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  113969. /* ColNames: */ 0, 0,
  113970. /* iArg: */ SQLITE_NullCallback },
  113971. #endif
  113972. #if !defined(SQLITE_OMIT_UTF16)
  113973. {/* zName: */ "encoding",
  113974. /* ePragTyp: */ PragTyp_ENCODING,
  113975. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  113976. /* ColNames: */ 0, 0,
  113977. /* iArg: */ 0 },
  113978. #endif
  113979. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  113980. {/* zName: */ "foreign_key_check",
  113981. /* ePragTyp: */ PragTyp_FOREIGN_KEY_CHECK,
  113982. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0,
  113983. /* ColNames: */ 31, 4,
  113984. /* iArg: */ 0 },
  113985. #endif
  113986. #if !defined(SQLITE_OMIT_FOREIGN_KEY)
  113987. {/* zName: */ "foreign_key_list",
  113988. /* ePragTyp: */ PragTyp_FOREIGN_KEY_LIST,
  113989. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
  113990. /* ColNames: */ 0, 8,
  113991. /* iArg: */ 0 },
  113992. #endif
  113993. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  113994. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  113995. {/* zName: */ "foreign_keys",
  113996. /* ePragTyp: */ PragTyp_FLAG,
  113997. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  113998. /* ColNames: */ 0, 0,
  113999. /* iArg: */ SQLITE_ForeignKeys },
  114000. #endif
  114001. #endif
  114002. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  114003. {/* zName: */ "freelist_count",
  114004. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  114005. /* ePragFlg: */ PragFlg_ReadOnly|PragFlg_Result0,
  114006. /* ColNames: */ 0, 0,
  114007. /* iArg: */ BTREE_FREE_PAGE_COUNT },
  114008. #endif
  114009. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  114010. {/* zName: */ "full_column_names",
  114011. /* ePragTyp: */ PragTyp_FLAG,
  114012. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  114013. /* ColNames: */ 0, 0,
  114014. /* iArg: */ SQLITE_FullColNames },
  114015. {/* zName: */ "fullfsync",
  114016. /* ePragTyp: */ PragTyp_FLAG,
  114017. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  114018. /* ColNames: */ 0, 0,
  114019. /* iArg: */ SQLITE_FullFSync },
  114020. #endif
  114021. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  114022. #if defined(SQLITE_INTROSPECTION_PRAGMAS)
  114023. {/* zName: */ "function_list",
  114024. /* ePragTyp: */ PragTyp_FUNCTION_LIST,
  114025. /* ePragFlg: */ PragFlg_Result0,
  114026. /* ColNames: */ 41, 2,
  114027. /* iArg: */ 0 },
  114028. #endif
  114029. #endif
  114030. #if defined(SQLITE_HAS_CODEC)
  114031. {/* zName: */ "hexkey",
  114032. /* ePragTyp: */ PragTyp_KEY,
  114033. /* ePragFlg: */ 0,
  114034. /* ColNames: */ 0, 0,
  114035. /* iArg: */ 2 },
  114036. {/* zName: */ "hexrekey",
  114037. /* ePragTyp: */ PragTyp_KEY,
  114038. /* ePragFlg: */ 0,
  114039. /* ColNames: */ 0, 0,
  114040. /* iArg: */ 3 },
  114041. #endif
  114042. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  114043. #if !defined(SQLITE_OMIT_CHECK)
  114044. {/* zName: */ "ignore_check_constraints",
  114045. /* ePragTyp: */ PragTyp_FLAG,
  114046. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  114047. /* ColNames: */ 0, 0,
  114048. /* iArg: */ SQLITE_IgnoreChecks },
  114049. #endif
  114050. #endif
  114051. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  114052. {/* zName: */ "incremental_vacuum",
  114053. /* ePragTyp: */ PragTyp_INCREMENTAL_VACUUM,
  114054. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_NoColumns,
  114055. /* ColNames: */ 0, 0,
  114056. /* iArg: */ 0 },
  114057. #endif
  114058. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  114059. {/* zName: */ "index_info",
  114060. /* ePragTyp: */ PragTyp_INDEX_INFO,
  114061. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
  114062. /* ColNames: */ 15, 3,
  114063. /* iArg: */ 0 },
  114064. {/* zName: */ "index_list",
  114065. /* ePragTyp: */ PragTyp_INDEX_LIST,
  114066. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
  114067. /* ColNames: */ 26, 5,
  114068. /* iArg: */ 0 },
  114069. {/* zName: */ "index_xinfo",
  114070. /* ePragTyp: */ PragTyp_INDEX_INFO,
  114071. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
  114072. /* ColNames: */ 15, 6,
  114073. /* iArg: */ 1 },
  114074. #endif
  114075. #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
  114076. {/* zName: */ "integrity_check",
  114077. /* ePragTyp: */ PragTyp_INTEGRITY_CHECK,
  114078. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_Result1,
  114079. /* ColNames: */ 0, 0,
  114080. /* iArg: */ 0 },
  114081. #endif
  114082. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  114083. {/* zName: */ "journal_mode",
  114084. /* ePragTyp: */ PragTyp_JOURNAL_MODE,
  114085. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
  114086. /* ColNames: */ 0, 0,
  114087. /* iArg: */ 0 },
  114088. {/* zName: */ "journal_size_limit",
  114089. /* ePragTyp: */ PragTyp_JOURNAL_SIZE_LIMIT,
  114090. /* ePragFlg: */ PragFlg_Result0|PragFlg_SchemaReq,
  114091. /* ColNames: */ 0, 0,
  114092. /* iArg: */ 0 },
  114093. #endif
  114094. #if defined(SQLITE_HAS_CODEC)
  114095. {/* zName: */ "key",
  114096. /* ePragTyp: */ PragTyp_KEY,
  114097. /* ePragFlg: */ 0,
  114098. /* ColNames: */ 0, 0,
  114099. /* iArg: */ 0 },
  114100. #endif
  114101. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  114102. {/* zName: */ "legacy_alter_table",
  114103. /* ePragTyp: */ PragTyp_FLAG,
  114104. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  114105. /* ColNames: */ 0, 0,
  114106. /* iArg: */ SQLITE_LegacyAlter },
  114107. {/* zName: */ "legacy_file_format",
  114108. /* ePragTyp: */ PragTyp_FLAG,
  114109. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  114110. /* ColNames: */ 0, 0,
  114111. /* iArg: */ SQLITE_LegacyFileFmt },
  114112. #endif
  114113. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_ENABLE_LOCKING_STYLE
  114114. {/* zName: */ "lock_proxy_file",
  114115. /* ePragTyp: */ PragTyp_LOCK_PROXY_FILE,
  114116. /* ePragFlg: */ PragFlg_NoColumns1,
  114117. /* ColNames: */ 0, 0,
  114118. /* iArg: */ 0 },
  114119. #endif
  114120. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  114121. {/* zName: */ "lock_status",
  114122. /* ePragTyp: */ PragTyp_LOCK_STATUS,
  114123. /* ePragFlg: */ PragFlg_Result0,
  114124. /* ColNames: */ 43, 2,
  114125. /* iArg: */ 0 },
  114126. #endif
  114127. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  114128. {/* zName: */ "locking_mode",
  114129. /* ePragTyp: */ PragTyp_LOCKING_MODE,
  114130. /* ePragFlg: */ PragFlg_Result0|PragFlg_SchemaReq,
  114131. /* ColNames: */ 0, 0,
  114132. /* iArg: */ 0 },
  114133. {/* zName: */ "max_page_count",
  114134. /* ePragTyp: */ PragTyp_PAGE_COUNT,
  114135. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
  114136. /* ColNames: */ 0, 0,
  114137. /* iArg: */ 0 },
  114138. {/* zName: */ "mmap_size",
  114139. /* ePragTyp: */ PragTyp_MMAP_SIZE,
  114140. /* ePragFlg: */ 0,
  114141. /* ColNames: */ 0, 0,
  114142. /* iArg: */ 0 },
  114143. #endif
  114144. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  114145. #if !defined(SQLITE_OMIT_VIRTUALTABLE)
  114146. #if defined(SQLITE_INTROSPECTION_PRAGMAS)
  114147. {/* zName: */ "module_list",
  114148. /* ePragTyp: */ PragTyp_MODULE_LIST,
  114149. /* ePragFlg: */ PragFlg_Result0,
  114150. /* ColNames: */ 9, 1,
  114151. /* iArg: */ 0 },
  114152. #endif
  114153. #endif
  114154. #endif
  114155. {/* zName: */ "optimize",
  114156. /* ePragTyp: */ PragTyp_OPTIMIZE,
  114157. /* ePragFlg: */ PragFlg_Result1|PragFlg_NeedSchema,
  114158. /* ColNames: */ 0, 0,
  114159. /* iArg: */ 0 },
  114160. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  114161. {/* zName: */ "page_count",
  114162. /* ePragTyp: */ PragTyp_PAGE_COUNT,
  114163. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
  114164. /* ColNames: */ 0, 0,
  114165. /* iArg: */ 0 },
  114166. {/* zName: */ "page_size",
  114167. /* ePragTyp: */ PragTyp_PAGE_SIZE,
  114168. /* ePragFlg: */ PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
  114169. /* ColNames: */ 0, 0,
  114170. /* iArg: */ 0 },
  114171. #endif
  114172. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  114173. #if defined(SQLITE_DEBUG)
  114174. {/* zName: */ "parser_trace",
  114175. /* ePragTyp: */ PragTyp_FLAG,
  114176. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  114177. /* ColNames: */ 0, 0,
  114178. /* iArg: */ SQLITE_ParserTrace },
  114179. #endif
  114180. #endif
  114181. #if defined(SQLITE_INTROSPECTION_PRAGMAS)
  114182. {/* zName: */ "pragma_list",
  114183. /* ePragTyp: */ PragTyp_PRAGMA_LIST,
  114184. /* ePragFlg: */ PragFlg_Result0,
  114185. /* ColNames: */ 9, 1,
  114186. /* iArg: */ 0 },
  114187. #endif
  114188. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  114189. {/* zName: */ "query_only",
  114190. /* ePragTyp: */ PragTyp_FLAG,
  114191. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  114192. /* ColNames: */ 0, 0,
  114193. /* iArg: */ SQLITE_QueryOnly },
  114194. #endif
  114195. #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
  114196. {/* zName: */ "quick_check",
  114197. /* ePragTyp: */ PragTyp_INTEGRITY_CHECK,
  114198. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_Result1,
  114199. /* ColNames: */ 0, 0,
  114200. /* iArg: */ 0 },
  114201. #endif
  114202. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  114203. {/* zName: */ "read_uncommitted",
  114204. /* ePragTyp: */ PragTyp_FLAG,
  114205. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  114206. /* ColNames: */ 0, 0,
  114207. /* iArg: */ SQLITE_ReadUncommit },
  114208. {/* zName: */ "recursive_triggers",
  114209. /* ePragTyp: */ PragTyp_FLAG,
  114210. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  114211. /* ColNames: */ 0, 0,
  114212. /* iArg: */ SQLITE_RecTriggers },
  114213. #endif
  114214. #if defined(SQLITE_HAS_CODEC)
  114215. {/* zName: */ "rekey",
  114216. /* ePragTyp: */ PragTyp_KEY,
  114217. /* ePragFlg: */ 0,
  114218. /* ColNames: */ 0, 0,
  114219. /* iArg: */ 1 },
  114220. #endif
  114221. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  114222. {/* zName: */ "reverse_unordered_selects",
  114223. /* ePragTyp: */ PragTyp_FLAG,
  114224. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  114225. /* ColNames: */ 0, 0,
  114226. /* iArg: */ SQLITE_ReverseOrder },
  114227. #endif
  114228. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  114229. {/* zName: */ "schema_version",
  114230. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  114231. /* ePragFlg: */ PragFlg_NoColumns1|PragFlg_Result0,
  114232. /* ColNames: */ 0, 0,
  114233. /* iArg: */ BTREE_SCHEMA_VERSION },
  114234. #endif
  114235. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  114236. {/* zName: */ "secure_delete",
  114237. /* ePragTyp: */ PragTyp_SECURE_DELETE,
  114238. /* ePragFlg: */ PragFlg_Result0,
  114239. /* ColNames: */ 0, 0,
  114240. /* iArg: */ 0 },
  114241. #endif
  114242. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  114243. {/* zName: */ "short_column_names",
  114244. /* ePragTyp: */ PragTyp_FLAG,
  114245. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  114246. /* ColNames: */ 0, 0,
  114247. /* iArg: */ SQLITE_ShortColNames },
  114248. #endif
  114249. {/* zName: */ "shrink_memory",
  114250. /* ePragTyp: */ PragTyp_SHRINK_MEMORY,
  114251. /* ePragFlg: */ PragFlg_NoColumns,
  114252. /* ColNames: */ 0, 0,
  114253. /* iArg: */ 0 },
  114254. {/* zName: */ "soft_heap_limit",
  114255. /* ePragTyp: */ PragTyp_SOFT_HEAP_LIMIT,
  114256. /* ePragFlg: */ PragFlg_Result0,
  114257. /* ColNames: */ 0, 0,
  114258. /* iArg: */ 0 },
  114259. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  114260. #if defined(SQLITE_DEBUG)
  114261. {/* zName: */ "sql_trace",
  114262. /* ePragTyp: */ PragTyp_FLAG,
  114263. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  114264. /* ColNames: */ 0, 0,
  114265. /* iArg: */ SQLITE_SqlTrace },
  114266. #endif
  114267. #endif
  114268. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) && defined(SQLITE_DEBUG)
  114269. {/* zName: */ "stats",
  114270. /* ePragTyp: */ PragTyp_STATS,
  114271. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
  114272. /* ColNames: */ 21, 5,
  114273. /* iArg: */ 0 },
  114274. #endif
  114275. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  114276. {/* zName: */ "synchronous",
  114277. /* ePragTyp: */ PragTyp_SYNCHRONOUS,
  114278. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
  114279. /* ColNames: */ 0, 0,
  114280. /* iArg: */ 0 },
  114281. #endif
  114282. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  114283. {/* zName: */ "table_info",
  114284. /* ePragTyp: */ PragTyp_TABLE_INFO,
  114285. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
  114286. /* ColNames: */ 8, 6,
  114287. /* iArg: */ 0 },
  114288. {/* zName: */ "table_xinfo",
  114289. /* ePragTyp: */ PragTyp_TABLE_INFO,
  114290. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
  114291. /* ColNames: */ 8, 7,
  114292. /* iArg: */ 1 },
  114293. #endif
  114294. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  114295. {/* zName: */ "temp_store",
  114296. /* ePragTyp: */ PragTyp_TEMP_STORE,
  114297. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  114298. /* ColNames: */ 0, 0,
  114299. /* iArg: */ 0 },
  114300. {/* zName: */ "temp_store_directory",
  114301. /* ePragTyp: */ PragTyp_TEMP_STORE_DIRECTORY,
  114302. /* ePragFlg: */ PragFlg_NoColumns1,
  114303. /* ColNames: */ 0, 0,
  114304. /* iArg: */ 0 },
  114305. #endif
  114306. #if defined(SQLITE_HAS_CODEC)
  114307. {/* zName: */ "textkey",
  114308. /* ePragTyp: */ PragTyp_KEY,
  114309. /* ePragFlg: */ 0,
  114310. /* ColNames: */ 0, 0,
  114311. /* iArg: */ 4 },
  114312. {/* zName: */ "textrekey",
  114313. /* ePragTyp: */ PragTyp_KEY,
  114314. /* ePragFlg: */ 0,
  114315. /* ColNames: */ 0, 0,
  114316. /* iArg: */ 5 },
  114317. #endif
  114318. {/* zName: */ "threads",
  114319. /* ePragTyp: */ PragTyp_THREADS,
  114320. /* ePragFlg: */ PragFlg_Result0,
  114321. /* ColNames: */ 0, 0,
  114322. /* iArg: */ 0 },
  114323. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  114324. {/* zName: */ "user_version",
  114325. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  114326. /* ePragFlg: */ PragFlg_NoColumns1|PragFlg_Result0,
  114327. /* ColNames: */ 0, 0,
  114328. /* iArg: */ BTREE_USER_VERSION },
  114329. #endif
  114330. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  114331. #if defined(SQLITE_DEBUG)
  114332. {/* zName: */ "vdbe_addoptrace",
  114333. /* ePragTyp: */ PragTyp_FLAG,
  114334. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  114335. /* ColNames: */ 0, 0,
  114336. /* iArg: */ SQLITE_VdbeAddopTrace },
  114337. {/* zName: */ "vdbe_debug",
  114338. /* ePragTyp: */ PragTyp_FLAG,
  114339. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  114340. /* ColNames: */ 0, 0,
  114341. /* iArg: */ SQLITE_SqlTrace|SQLITE_VdbeListing|SQLITE_VdbeTrace },
  114342. {/* zName: */ "vdbe_eqp",
  114343. /* ePragTyp: */ PragTyp_FLAG,
  114344. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  114345. /* ColNames: */ 0, 0,
  114346. /* iArg: */ SQLITE_VdbeEQP },
  114347. {/* zName: */ "vdbe_listing",
  114348. /* ePragTyp: */ PragTyp_FLAG,
  114349. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  114350. /* ColNames: */ 0, 0,
  114351. /* iArg: */ SQLITE_VdbeListing },
  114352. {/* zName: */ "vdbe_trace",
  114353. /* ePragTyp: */ PragTyp_FLAG,
  114354. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  114355. /* ColNames: */ 0, 0,
  114356. /* iArg: */ SQLITE_VdbeTrace },
  114357. #endif
  114358. #endif
  114359. #if !defined(SQLITE_OMIT_WAL)
  114360. {/* zName: */ "wal_autocheckpoint",
  114361. /* ePragTyp: */ PragTyp_WAL_AUTOCHECKPOINT,
  114362. /* ePragFlg: */ 0,
  114363. /* ColNames: */ 0, 0,
  114364. /* iArg: */ 0 },
  114365. {/* zName: */ "wal_checkpoint",
  114366. /* ePragTyp: */ PragTyp_WAL_CHECKPOINT,
  114367. /* ePragFlg: */ PragFlg_NeedSchema,
  114368. /* ColNames: */ 38, 3,
  114369. /* iArg: */ 0 },
  114370. #endif
  114371. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  114372. {/* zName: */ "writable_schema",
  114373. /* ePragTyp: */ PragTyp_FLAG,
  114374. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  114375. /* ColNames: */ 0, 0,
  114376. /* iArg: */ SQLITE_WriteSchema|SQLITE_NoSchemaError },
  114377. #endif
  114378. };
  114379. /* Number of pragmas: 62 on by default, 81 total. */
  114380. /************** End of pragma.h **********************************************/
  114381. /************** Continuing where we left off in pragma.c *********************/
  114382. /*
  114383. ** Interpret the given string as a safety level. Return 0 for OFF,
  114384. ** 1 for ON or NORMAL, 2 for FULL, and 3 for EXTRA. Return 1 for an empty or
  114385. ** unrecognized string argument. The FULL and EXTRA option is disallowed
  114386. ** if the omitFull parameter it 1.
  114387. **
  114388. ** Note that the values returned are one less that the values that
  114389. ** should be passed into sqlite3BtreeSetSafetyLevel(). The is done
  114390. ** to support legacy SQL code. The safety level used to be boolean
  114391. ** and older scripts may have used numbers 0 for OFF and 1 for ON.
  114392. */
  114393. static u8 getSafetyLevel(const char *z, int omitFull, u8 dflt){
  114394. /* 123456789 123456789 123 */
  114395. static const char zText[] = "onoffalseyestruextrafull";
  114396. static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 15, 20};
  114397. static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 5, 4};
  114398. static const u8 iValue[] = {1, 0, 0, 0, 1, 1, 3, 2};
  114399. /* on no off false yes true extra full */
  114400. int i, n;
  114401. if( sqlite3Isdigit(*z) ){
  114402. return (u8)sqlite3Atoi(z);
  114403. }
  114404. n = sqlite3Strlen30(z);
  114405. for(i=0; i<ArraySize(iLength); i++){
  114406. if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0
  114407. && (!omitFull || iValue[i]<=1)
  114408. ){
  114409. return iValue[i];
  114410. }
  114411. }
  114412. return dflt;
  114413. }
  114414. /*
  114415. ** Interpret the given string as a boolean value.
  114416. */
  114417. SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, u8 dflt){
  114418. return getSafetyLevel(z,1,dflt)!=0;
  114419. }
  114420. /* The sqlite3GetBoolean() function is used by other modules but the
  114421. ** remainder of this file is specific to PRAGMA processing. So omit
  114422. ** the rest of the file if PRAGMAs are omitted from the build.
  114423. */
  114424. #if !defined(SQLITE_OMIT_PRAGMA)
  114425. /*
  114426. ** Interpret the given string as a locking mode value.
  114427. */
  114428. static int getLockingMode(const char *z){
  114429. if( z ){
  114430. if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
  114431. if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
  114432. }
  114433. return PAGER_LOCKINGMODE_QUERY;
  114434. }
  114435. #ifndef SQLITE_OMIT_AUTOVACUUM
  114436. /*
  114437. ** Interpret the given string as an auto-vacuum mode value.
  114438. **
  114439. ** The following strings, "none", "full" and "incremental" are
  114440. ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
  114441. */
  114442. static int getAutoVacuum(const char *z){
  114443. int i;
  114444. if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
  114445. if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
  114446. if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
  114447. i = sqlite3Atoi(z);
  114448. return (u8)((i>=0&&i<=2)?i:0);
  114449. }
  114450. #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
  114451. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  114452. /*
  114453. ** Interpret the given string as a temp db location. Return 1 for file
  114454. ** backed temporary databases, 2 for the Red-Black tree in memory database
  114455. ** and 0 to use the compile-time default.
  114456. */
  114457. static int getTempStore(const char *z){
  114458. if( z[0]>='0' && z[0]<='2' ){
  114459. return z[0] - '0';
  114460. }else if( sqlite3StrICmp(z, "file")==0 ){
  114461. return 1;
  114462. }else if( sqlite3StrICmp(z, "memory")==0 ){
  114463. return 2;
  114464. }else{
  114465. return 0;
  114466. }
  114467. }
  114468. #endif /* SQLITE_PAGER_PRAGMAS */
  114469. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  114470. /*
  114471. ** Invalidate temp storage, either when the temp storage is changed
  114472. ** from default, or when 'file' and the temp_store_directory has changed
  114473. */
  114474. static int invalidateTempStorage(Parse *pParse){
  114475. sqlite3 *db = pParse->db;
  114476. if( db->aDb[1].pBt!=0 ){
  114477. if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
  114478. sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
  114479. "from within a transaction");
  114480. return SQLITE_ERROR;
  114481. }
  114482. sqlite3BtreeClose(db->aDb[1].pBt);
  114483. db->aDb[1].pBt = 0;
  114484. sqlite3ResetAllSchemasOfConnection(db);
  114485. }
  114486. return SQLITE_OK;
  114487. }
  114488. #endif /* SQLITE_PAGER_PRAGMAS */
  114489. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  114490. /*
  114491. ** If the TEMP database is open, close it and mark the database schema
  114492. ** as needing reloading. This must be done when using the SQLITE_TEMP_STORE
  114493. ** or DEFAULT_TEMP_STORE pragmas.
  114494. */
  114495. static int changeTempStorage(Parse *pParse, const char *zStorageType){
  114496. int ts = getTempStore(zStorageType);
  114497. sqlite3 *db = pParse->db;
  114498. if( db->temp_store==ts ) return SQLITE_OK;
  114499. if( invalidateTempStorage( pParse ) != SQLITE_OK ){
  114500. return SQLITE_ERROR;
  114501. }
  114502. db->temp_store = (u8)ts;
  114503. return SQLITE_OK;
  114504. }
  114505. #endif /* SQLITE_PAGER_PRAGMAS */
  114506. /*
  114507. ** Set result column names for a pragma.
  114508. */
  114509. static void setPragmaResultColumnNames(
  114510. Vdbe *v, /* The query under construction */
  114511. const PragmaName *pPragma /* The pragma */
  114512. ){
  114513. u8 n = pPragma->nPragCName;
  114514. sqlite3VdbeSetNumCols(v, n==0 ? 1 : n);
  114515. if( n==0 ){
  114516. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, pPragma->zName, SQLITE_STATIC);
  114517. }else{
  114518. int i, j;
  114519. for(i=0, j=pPragma->iPragCName; i<n; i++, j++){
  114520. sqlite3VdbeSetColName(v, i, COLNAME_NAME, pragCName[j], SQLITE_STATIC);
  114521. }
  114522. }
  114523. }
  114524. /*
  114525. ** Generate code to return a single integer value.
  114526. */
  114527. static void returnSingleInt(Vdbe *v, i64 value){
  114528. sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, 1, 0, (const u8*)&value, P4_INT64);
  114529. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  114530. }
  114531. /*
  114532. ** Generate code to return a single text value.
  114533. */
  114534. static void returnSingleText(
  114535. Vdbe *v, /* Prepared statement under construction */
  114536. const char *zValue /* Value to be returned */
  114537. ){
  114538. if( zValue ){
  114539. sqlite3VdbeLoadString(v, 1, (const char*)zValue);
  114540. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  114541. }
  114542. }
  114543. /*
  114544. ** Set the safety_level and pager flags for pager iDb. Or if iDb<0
  114545. ** set these values for all pagers.
  114546. */
  114547. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  114548. static void setAllPagerFlags(sqlite3 *db){
  114549. if( db->autoCommit ){
  114550. Db *pDb = db->aDb;
  114551. int n = db->nDb;
  114552. assert( SQLITE_FullFSync==PAGER_FULLFSYNC );
  114553. assert( SQLITE_CkptFullFSync==PAGER_CKPT_FULLFSYNC );
  114554. assert( SQLITE_CacheSpill==PAGER_CACHESPILL );
  114555. assert( (PAGER_FULLFSYNC | PAGER_CKPT_FULLFSYNC | PAGER_CACHESPILL)
  114556. == PAGER_FLAGS_MASK );
  114557. assert( (pDb->safety_level & PAGER_SYNCHRONOUS_MASK)==pDb->safety_level );
  114558. while( (n--) > 0 ){
  114559. if( pDb->pBt ){
  114560. sqlite3BtreeSetPagerFlags(pDb->pBt,
  114561. pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) );
  114562. }
  114563. pDb++;
  114564. }
  114565. }
  114566. }
  114567. #else
  114568. # define setAllPagerFlags(X) /* no-op */
  114569. #endif
  114570. /*
  114571. ** Return a human-readable name for a constraint resolution action.
  114572. */
  114573. #ifndef SQLITE_OMIT_FOREIGN_KEY
  114574. static const char *actionName(u8 action){
  114575. const char *zName;
  114576. switch( action ){
  114577. case OE_SetNull: zName = "SET NULL"; break;
  114578. case OE_SetDflt: zName = "SET DEFAULT"; break;
  114579. case OE_Cascade: zName = "CASCADE"; break;
  114580. case OE_Restrict: zName = "RESTRICT"; break;
  114581. default: zName = "NO ACTION";
  114582. assert( action==OE_None ); break;
  114583. }
  114584. return zName;
  114585. }
  114586. #endif
  114587. /*
  114588. ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
  114589. ** defined in pager.h. This function returns the associated lowercase
  114590. ** journal-mode name.
  114591. */
  114592. SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
  114593. static char * const azModeName[] = {
  114594. "delete", "persist", "off", "truncate", "memory"
  114595. #ifndef SQLITE_OMIT_WAL
  114596. , "wal"
  114597. #endif
  114598. };
  114599. assert( PAGER_JOURNALMODE_DELETE==0 );
  114600. assert( PAGER_JOURNALMODE_PERSIST==1 );
  114601. assert( PAGER_JOURNALMODE_OFF==2 );
  114602. assert( PAGER_JOURNALMODE_TRUNCATE==3 );
  114603. assert( PAGER_JOURNALMODE_MEMORY==4 );
  114604. assert( PAGER_JOURNALMODE_WAL==5 );
  114605. assert( eMode>=0 && eMode<=ArraySize(azModeName) );
  114606. if( eMode==ArraySize(azModeName) ) return 0;
  114607. return azModeName[eMode];
  114608. }
  114609. /*
  114610. ** Locate a pragma in the aPragmaName[] array.
  114611. */
  114612. static const PragmaName *pragmaLocate(const char *zName){
  114613. int upr, lwr, mid = 0, rc;
  114614. lwr = 0;
  114615. upr = ArraySize(aPragmaName)-1;
  114616. while( lwr<=upr ){
  114617. mid = (lwr+upr)/2;
  114618. rc = sqlite3_stricmp(zName, aPragmaName[mid].zName);
  114619. if( rc==0 ) break;
  114620. if( rc<0 ){
  114621. upr = mid - 1;
  114622. }else{
  114623. lwr = mid + 1;
  114624. }
  114625. }
  114626. return lwr>upr ? 0 : &aPragmaName[mid];
  114627. }
  114628. /*
  114629. ** Helper subroutine for PRAGMA integrity_check:
  114630. **
  114631. ** Generate code to output a single-column result row with a value of the
  114632. ** string held in register 3. Decrement the result count in register 1
  114633. ** and halt if the maximum number of result rows have been issued.
  114634. */
  114635. static int integrityCheckResultRow(Vdbe *v){
  114636. int addr;
  114637. sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
  114638. addr = sqlite3VdbeAddOp3(v, OP_IfPos, 1, sqlite3VdbeCurrentAddr(v)+2, 1);
  114639. VdbeCoverage(v);
  114640. sqlite3VdbeAddOp0(v, OP_Halt);
  114641. return addr;
  114642. }
  114643. /*
  114644. ** Process a pragma statement.
  114645. **
  114646. ** Pragmas are of this form:
  114647. **
  114648. ** PRAGMA [schema.]id [= value]
  114649. **
  114650. ** The identifier might also be a string. The value is a string, and
  114651. ** identifier, or a number. If minusFlag is true, then the value is
  114652. ** a number that was preceded by a minus sign.
  114653. **
  114654. ** If the left side is "database.id" then pId1 is the database name
  114655. ** and pId2 is the id. If the left side is just "id" then pId1 is the
  114656. ** id and pId2 is any empty string.
  114657. */
  114658. SQLITE_PRIVATE void sqlite3Pragma(
  114659. Parse *pParse,
  114660. Token *pId1, /* First part of [schema.]id field */
  114661. Token *pId2, /* Second part of [schema.]id field, or NULL */
  114662. Token *pValue, /* Token for <value>, or NULL */
  114663. int minusFlag /* True if a '-' sign preceded <value> */
  114664. ){
  114665. char *zLeft = 0; /* Nul-terminated UTF-8 string <id> */
  114666. char *zRight = 0; /* Nul-terminated UTF-8 string <value>, or NULL */
  114667. const char *zDb = 0; /* The database name */
  114668. Token *pId; /* Pointer to <id> token */
  114669. char *aFcntl[4]; /* Argument to SQLITE_FCNTL_PRAGMA */
  114670. int iDb; /* Database index for <database> */
  114671. int rc; /* return value form SQLITE_FCNTL_PRAGMA */
  114672. sqlite3 *db = pParse->db; /* The database connection */
  114673. Db *pDb; /* The specific database being pragmaed */
  114674. Vdbe *v = sqlite3GetVdbe(pParse); /* Prepared statement */
  114675. const PragmaName *pPragma; /* The pragma */
  114676. if( v==0 ) return;
  114677. sqlite3VdbeRunOnlyOnce(v);
  114678. pParse->nMem = 2;
  114679. /* Interpret the [schema.] part of the pragma statement. iDb is the
  114680. ** index of the database this pragma is being applied to in db.aDb[]. */
  114681. iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
  114682. if( iDb<0 ) return;
  114683. pDb = &db->aDb[iDb];
  114684. /* If the temp database has been explicitly named as part of the
  114685. ** pragma, make sure it is open.
  114686. */
  114687. if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
  114688. return;
  114689. }
  114690. zLeft = sqlite3NameFromToken(db, pId);
  114691. if( !zLeft ) return;
  114692. if( minusFlag ){
  114693. zRight = sqlite3MPrintf(db, "-%T", pValue);
  114694. }else{
  114695. zRight = sqlite3NameFromToken(db, pValue);
  114696. }
  114697. assert( pId2 );
  114698. zDb = pId2->n>0 ? pDb->zDbSName : 0;
  114699. if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
  114700. goto pragma_out;
  114701. }
  114702. /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
  114703. ** connection. If it returns SQLITE_OK, then assume that the VFS
  114704. ** handled the pragma and generate a no-op prepared statement.
  114705. **
  114706. ** IMPLEMENTATION-OF: R-12238-55120 Whenever a PRAGMA statement is parsed,
  114707. ** an SQLITE_FCNTL_PRAGMA file control is sent to the open sqlite3_file
  114708. ** object corresponding to the database file to which the pragma
  114709. ** statement refers.
  114710. **
  114711. ** IMPLEMENTATION-OF: R-29875-31678 The argument to the SQLITE_FCNTL_PRAGMA
  114712. ** file control is an array of pointers to strings (char**) in which the
  114713. ** second element of the array is the name of the pragma and the third
  114714. ** element is the argument to the pragma or NULL if the pragma has no
  114715. ** argument.
  114716. */
  114717. aFcntl[0] = 0;
  114718. aFcntl[1] = zLeft;
  114719. aFcntl[2] = zRight;
  114720. aFcntl[3] = 0;
  114721. db->busyHandler.nBusy = 0;
  114722. rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
  114723. if( rc==SQLITE_OK ){
  114724. sqlite3VdbeSetNumCols(v, 1);
  114725. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, aFcntl[0], SQLITE_TRANSIENT);
  114726. returnSingleText(v, aFcntl[0]);
  114727. sqlite3_free(aFcntl[0]);
  114728. goto pragma_out;
  114729. }
  114730. if( rc!=SQLITE_NOTFOUND ){
  114731. if( aFcntl[0] ){
  114732. sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
  114733. sqlite3_free(aFcntl[0]);
  114734. }
  114735. pParse->nErr++;
  114736. pParse->rc = rc;
  114737. goto pragma_out;
  114738. }
  114739. /* Locate the pragma in the lookup table */
  114740. pPragma = pragmaLocate(zLeft);
  114741. if( pPragma==0 ) goto pragma_out;
  114742. /* Make sure the database schema is loaded if the pragma requires that */
  114743. if( (pPragma->mPragFlg & PragFlg_NeedSchema)!=0 ){
  114744. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  114745. }
  114746. /* Register the result column names for pragmas that return results */
  114747. if( (pPragma->mPragFlg & PragFlg_NoColumns)==0
  114748. && ((pPragma->mPragFlg & PragFlg_NoColumns1)==0 || zRight==0)
  114749. ){
  114750. setPragmaResultColumnNames(v, pPragma);
  114751. }
  114752. /* Jump to the appropriate pragma handler */
  114753. switch( pPragma->ePragTyp ){
  114754. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
  114755. /*
  114756. ** PRAGMA [schema.]default_cache_size
  114757. ** PRAGMA [schema.]default_cache_size=N
  114758. **
  114759. ** The first form reports the current persistent setting for the
  114760. ** page cache size. The value returned is the maximum number of
  114761. ** pages in the page cache. The second form sets both the current
  114762. ** page cache size value and the persistent page cache size value
  114763. ** stored in the database file.
  114764. **
  114765. ** Older versions of SQLite would set the default cache size to a
  114766. ** negative number to indicate synchronous=OFF. These days, synchronous
  114767. ** is always on by default regardless of the sign of the default cache
  114768. ** size. But continue to take the absolute value of the default cache
  114769. ** size of historical compatibility.
  114770. */
  114771. case PragTyp_DEFAULT_CACHE_SIZE: {
  114772. static const int iLn = VDBE_OFFSET_LINENO(2);
  114773. static const VdbeOpList getCacheSize[] = {
  114774. { OP_Transaction, 0, 0, 0}, /* 0 */
  114775. { OP_ReadCookie, 0, 1, BTREE_DEFAULT_CACHE_SIZE}, /* 1 */
  114776. { OP_IfPos, 1, 8, 0},
  114777. { OP_Integer, 0, 2, 0},
  114778. { OP_Subtract, 1, 2, 1},
  114779. { OP_IfPos, 1, 8, 0},
  114780. { OP_Integer, 0, 1, 0}, /* 6 */
  114781. { OP_Noop, 0, 0, 0},
  114782. { OP_ResultRow, 1, 1, 0},
  114783. };
  114784. VdbeOp *aOp;
  114785. sqlite3VdbeUsesBtree(v, iDb);
  114786. if( !zRight ){
  114787. pParse->nMem += 2;
  114788. sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(getCacheSize));
  114789. aOp = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize, iLn);
  114790. if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
  114791. aOp[0].p1 = iDb;
  114792. aOp[1].p1 = iDb;
  114793. aOp[6].p1 = SQLITE_DEFAULT_CACHE_SIZE;
  114794. }else{
  114795. int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
  114796. sqlite3BeginWriteOperation(pParse, 0, iDb);
  114797. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, size);
  114798. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  114799. pDb->pSchema->cache_size = size;
  114800. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  114801. }
  114802. break;
  114803. }
  114804. #endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
  114805. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  114806. /*
  114807. ** PRAGMA [schema.]page_size
  114808. ** PRAGMA [schema.]page_size=N
  114809. **
  114810. ** The first form reports the current setting for the
  114811. ** database page size in bytes. The second form sets the
  114812. ** database page size value. The value can only be set if
  114813. ** the database has not yet been created.
  114814. */
  114815. case PragTyp_PAGE_SIZE: {
  114816. Btree *pBt = pDb->pBt;
  114817. assert( pBt!=0 );
  114818. if( !zRight ){
  114819. int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
  114820. returnSingleInt(v, size);
  114821. }else{
  114822. /* Malloc may fail when setting the page-size, as there is an internal
  114823. ** buffer that the pager module resizes using sqlite3_realloc().
  114824. */
  114825. db->nextPagesize = sqlite3Atoi(zRight);
  114826. if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
  114827. sqlite3OomFault(db);
  114828. }
  114829. }
  114830. break;
  114831. }
  114832. /*
  114833. ** PRAGMA [schema.]secure_delete
  114834. ** PRAGMA [schema.]secure_delete=ON/OFF/FAST
  114835. **
  114836. ** The first form reports the current setting for the
  114837. ** secure_delete flag. The second form changes the secure_delete
  114838. ** flag setting and reports the new value.
  114839. */
  114840. case PragTyp_SECURE_DELETE: {
  114841. Btree *pBt = pDb->pBt;
  114842. int b = -1;
  114843. assert( pBt!=0 );
  114844. if( zRight ){
  114845. if( sqlite3_stricmp(zRight, "fast")==0 ){
  114846. b = 2;
  114847. }else{
  114848. b = sqlite3GetBoolean(zRight, 0);
  114849. }
  114850. }
  114851. if( pId2->n==0 && b>=0 ){
  114852. int ii;
  114853. for(ii=0; ii<db->nDb; ii++){
  114854. sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
  114855. }
  114856. }
  114857. b = sqlite3BtreeSecureDelete(pBt, b);
  114858. returnSingleInt(v, b);
  114859. break;
  114860. }
  114861. /*
  114862. ** PRAGMA [schema.]max_page_count
  114863. ** PRAGMA [schema.]max_page_count=N
  114864. **
  114865. ** The first form reports the current setting for the
  114866. ** maximum number of pages in the database file. The
  114867. ** second form attempts to change this setting. Both
  114868. ** forms return the current setting.
  114869. **
  114870. ** The absolute value of N is used. This is undocumented and might
  114871. ** change. The only purpose is to provide an easy way to test
  114872. ** the sqlite3AbsInt32() function.
  114873. **
  114874. ** PRAGMA [schema.]page_count
  114875. **
  114876. ** Return the number of pages in the specified database.
  114877. */
  114878. case PragTyp_PAGE_COUNT: {
  114879. int iReg;
  114880. sqlite3CodeVerifySchema(pParse, iDb);
  114881. iReg = ++pParse->nMem;
  114882. if( sqlite3Tolower(zLeft[0])=='p' ){
  114883. sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
  114884. }else{
  114885. sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg,
  114886. sqlite3AbsInt32(sqlite3Atoi(zRight)));
  114887. }
  114888. sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
  114889. break;
  114890. }
  114891. /*
  114892. ** PRAGMA [schema.]locking_mode
  114893. ** PRAGMA [schema.]locking_mode = (normal|exclusive)
  114894. */
  114895. case PragTyp_LOCKING_MODE: {
  114896. const char *zRet = "normal";
  114897. int eMode = getLockingMode(zRight);
  114898. if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
  114899. /* Simple "PRAGMA locking_mode;" statement. This is a query for
  114900. ** the current default locking mode (which may be different to
  114901. ** the locking-mode of the main database).
  114902. */
  114903. eMode = db->dfltLockMode;
  114904. }else{
  114905. Pager *pPager;
  114906. if( pId2->n==0 ){
  114907. /* This indicates that no database name was specified as part
  114908. ** of the PRAGMA command. In this case the locking-mode must be
  114909. ** set on all attached databases, as well as the main db file.
  114910. **
  114911. ** Also, the sqlite3.dfltLockMode variable is set so that
  114912. ** any subsequently attached databases also use the specified
  114913. ** locking mode.
  114914. */
  114915. int ii;
  114916. assert(pDb==&db->aDb[0]);
  114917. for(ii=2; ii<db->nDb; ii++){
  114918. pPager = sqlite3BtreePager(db->aDb[ii].pBt);
  114919. sqlite3PagerLockingMode(pPager, eMode);
  114920. }
  114921. db->dfltLockMode = (u8)eMode;
  114922. }
  114923. pPager = sqlite3BtreePager(pDb->pBt);
  114924. eMode = sqlite3PagerLockingMode(pPager, eMode);
  114925. }
  114926. assert( eMode==PAGER_LOCKINGMODE_NORMAL
  114927. || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
  114928. if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
  114929. zRet = "exclusive";
  114930. }
  114931. returnSingleText(v, zRet);
  114932. break;
  114933. }
  114934. /*
  114935. ** PRAGMA [schema.]journal_mode
  114936. ** PRAGMA [schema.]journal_mode =
  114937. ** (delete|persist|off|truncate|memory|wal|off)
  114938. */
  114939. case PragTyp_JOURNAL_MODE: {
  114940. int eMode; /* One of the PAGER_JOURNALMODE_XXX symbols */
  114941. int ii; /* Loop counter */
  114942. if( zRight==0 ){
  114943. /* If there is no "=MODE" part of the pragma, do a query for the
  114944. ** current mode */
  114945. eMode = PAGER_JOURNALMODE_QUERY;
  114946. }else{
  114947. const char *zMode;
  114948. int n = sqlite3Strlen30(zRight);
  114949. for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
  114950. if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
  114951. }
  114952. if( !zMode ){
  114953. /* If the "=MODE" part does not match any known journal mode,
  114954. ** then do a query */
  114955. eMode = PAGER_JOURNALMODE_QUERY;
  114956. }
  114957. if( eMode==PAGER_JOURNALMODE_OFF && (db->flags & SQLITE_Defensive)!=0 ){
  114958. /* Do not allow journal-mode "OFF" in defensive since the database
  114959. ** can become corrupted using ordinary SQL when the journal is off */
  114960. eMode = PAGER_JOURNALMODE_QUERY;
  114961. }
  114962. }
  114963. if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
  114964. /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
  114965. iDb = 0;
  114966. pId2->n = 1;
  114967. }
  114968. for(ii=db->nDb-1; ii>=0; ii--){
  114969. if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
  114970. sqlite3VdbeUsesBtree(v, ii);
  114971. sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
  114972. }
  114973. }
  114974. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  114975. break;
  114976. }
  114977. /*
  114978. ** PRAGMA [schema.]journal_size_limit
  114979. ** PRAGMA [schema.]journal_size_limit=N
  114980. **
  114981. ** Get or set the size limit on rollback journal files.
  114982. */
  114983. case PragTyp_JOURNAL_SIZE_LIMIT: {
  114984. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  114985. i64 iLimit = -2;
  114986. if( zRight ){
  114987. sqlite3DecOrHexToI64(zRight, &iLimit);
  114988. if( iLimit<-1 ) iLimit = -1;
  114989. }
  114990. iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
  114991. returnSingleInt(v, iLimit);
  114992. break;
  114993. }
  114994. #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
  114995. /*
  114996. ** PRAGMA [schema.]auto_vacuum
  114997. ** PRAGMA [schema.]auto_vacuum=N
  114998. **
  114999. ** Get or set the value of the database 'auto-vacuum' parameter.
  115000. ** The value is one of: 0 NONE 1 FULL 2 INCREMENTAL
  115001. */
  115002. #ifndef SQLITE_OMIT_AUTOVACUUM
  115003. case PragTyp_AUTO_VACUUM: {
  115004. Btree *pBt = pDb->pBt;
  115005. assert( pBt!=0 );
  115006. if( !zRight ){
  115007. returnSingleInt(v, sqlite3BtreeGetAutoVacuum(pBt));
  115008. }else{
  115009. int eAuto = getAutoVacuum(zRight);
  115010. assert( eAuto>=0 && eAuto<=2 );
  115011. db->nextAutovac = (u8)eAuto;
  115012. /* Call SetAutoVacuum() to set initialize the internal auto and
  115013. ** incr-vacuum flags. This is required in case this connection
  115014. ** creates the database file. It is important that it is created
  115015. ** as an auto-vacuum capable db.
  115016. */
  115017. rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
  115018. if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
  115019. /* When setting the auto_vacuum mode to either "full" or
  115020. ** "incremental", write the value of meta[6] in the database
  115021. ** file. Before writing to meta[6], check that meta[3] indicates
  115022. ** that this really is an auto-vacuum capable database.
  115023. */
  115024. static const int iLn = VDBE_OFFSET_LINENO(2);
  115025. static const VdbeOpList setMeta6[] = {
  115026. { OP_Transaction, 0, 1, 0}, /* 0 */
  115027. { OP_ReadCookie, 0, 1, BTREE_LARGEST_ROOT_PAGE},
  115028. { OP_If, 1, 0, 0}, /* 2 */
  115029. { OP_Halt, SQLITE_OK, OE_Abort, 0}, /* 3 */
  115030. { OP_SetCookie, 0, BTREE_INCR_VACUUM, 0}, /* 4 */
  115031. };
  115032. VdbeOp *aOp;
  115033. int iAddr = sqlite3VdbeCurrentAddr(v);
  115034. sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setMeta6));
  115035. aOp = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6, iLn);
  115036. if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
  115037. aOp[0].p1 = iDb;
  115038. aOp[1].p1 = iDb;
  115039. aOp[2].p2 = iAddr+4;
  115040. aOp[4].p1 = iDb;
  115041. aOp[4].p3 = eAuto - 1;
  115042. sqlite3VdbeUsesBtree(v, iDb);
  115043. }
  115044. }
  115045. break;
  115046. }
  115047. #endif
  115048. /*
  115049. ** PRAGMA [schema.]incremental_vacuum(N)
  115050. **
  115051. ** Do N steps of incremental vacuuming on a database.
  115052. */
  115053. #ifndef SQLITE_OMIT_AUTOVACUUM
  115054. case PragTyp_INCREMENTAL_VACUUM: {
  115055. int iLimit, addr;
  115056. if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
  115057. iLimit = 0x7fffffff;
  115058. }
  115059. sqlite3BeginWriteOperation(pParse, 0, iDb);
  115060. sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
  115061. addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); VdbeCoverage(v);
  115062. sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
  115063. sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
  115064. sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); VdbeCoverage(v);
  115065. sqlite3VdbeJumpHere(v, addr);
  115066. break;
  115067. }
  115068. #endif
  115069. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  115070. /*
  115071. ** PRAGMA [schema.]cache_size
  115072. ** PRAGMA [schema.]cache_size=N
  115073. **
  115074. ** The first form reports the current local setting for the
  115075. ** page cache size. The second form sets the local
  115076. ** page cache size value. If N is positive then that is the
  115077. ** number of pages in the cache. If N is negative, then the
  115078. ** number of pages is adjusted so that the cache uses -N kibibytes
  115079. ** of memory.
  115080. */
  115081. case PragTyp_CACHE_SIZE: {
  115082. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  115083. if( !zRight ){
  115084. returnSingleInt(v, pDb->pSchema->cache_size);
  115085. }else{
  115086. int size = sqlite3Atoi(zRight);
  115087. pDb->pSchema->cache_size = size;
  115088. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  115089. }
  115090. break;
  115091. }
  115092. /*
  115093. ** PRAGMA [schema.]cache_spill
  115094. ** PRAGMA cache_spill=BOOLEAN
  115095. ** PRAGMA [schema.]cache_spill=N
  115096. **
  115097. ** The first form reports the current local setting for the
  115098. ** page cache spill size. The second form turns cache spill on
  115099. ** or off. When turnning cache spill on, the size is set to the
  115100. ** current cache_size. The third form sets a spill size that
  115101. ** may be different form the cache size.
  115102. ** If N is positive then that is the
  115103. ** number of pages in the cache. If N is negative, then the
  115104. ** number of pages is adjusted so that the cache uses -N kibibytes
  115105. ** of memory.
  115106. **
  115107. ** If the number of cache_spill pages is less then the number of
  115108. ** cache_size pages, no spilling occurs until the page count exceeds
  115109. ** the number of cache_size pages.
  115110. **
  115111. ** The cache_spill=BOOLEAN setting applies to all attached schemas,
  115112. ** not just the schema specified.
  115113. */
  115114. case PragTyp_CACHE_SPILL: {
  115115. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  115116. if( !zRight ){
  115117. returnSingleInt(v,
  115118. (db->flags & SQLITE_CacheSpill)==0 ? 0 :
  115119. sqlite3BtreeSetSpillSize(pDb->pBt,0));
  115120. }else{
  115121. int size = 1;
  115122. if( sqlite3GetInt32(zRight, &size) ){
  115123. sqlite3BtreeSetSpillSize(pDb->pBt, size);
  115124. }
  115125. if( sqlite3GetBoolean(zRight, size!=0) ){
  115126. db->flags |= SQLITE_CacheSpill;
  115127. }else{
  115128. db->flags &= ~(u64)SQLITE_CacheSpill;
  115129. }
  115130. setAllPagerFlags(db);
  115131. }
  115132. break;
  115133. }
  115134. /*
  115135. ** PRAGMA [schema.]mmap_size(N)
  115136. **
  115137. ** Used to set mapping size limit. The mapping size limit is
  115138. ** used to limit the aggregate size of all memory mapped regions of the
  115139. ** database file. If this parameter is set to zero, then memory mapping
  115140. ** is not used at all. If N is negative, then the default memory map
  115141. ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
  115142. ** The parameter N is measured in bytes.
  115143. **
  115144. ** This value is advisory. The underlying VFS is free to memory map
  115145. ** as little or as much as it wants. Except, if N is set to 0 then the
  115146. ** upper layers will never invoke the xFetch interfaces to the VFS.
  115147. */
  115148. case PragTyp_MMAP_SIZE: {
  115149. sqlite3_int64 sz;
  115150. #if SQLITE_MAX_MMAP_SIZE>0
  115151. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  115152. if( zRight ){
  115153. int ii;
  115154. sqlite3DecOrHexToI64(zRight, &sz);
  115155. if( sz<0 ) sz = sqlite3GlobalConfig.szMmap;
  115156. if( pId2->n==0 ) db->szMmap = sz;
  115157. for(ii=db->nDb-1; ii>=0; ii--){
  115158. if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
  115159. sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
  115160. }
  115161. }
  115162. }
  115163. sz = -1;
  115164. rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz);
  115165. #else
  115166. sz = 0;
  115167. rc = SQLITE_OK;
  115168. #endif
  115169. if( rc==SQLITE_OK ){
  115170. returnSingleInt(v, sz);
  115171. }else if( rc!=SQLITE_NOTFOUND ){
  115172. pParse->nErr++;
  115173. pParse->rc = rc;
  115174. }
  115175. break;
  115176. }
  115177. /*
  115178. ** PRAGMA temp_store
  115179. ** PRAGMA temp_store = "default"|"memory"|"file"
  115180. **
  115181. ** Return or set the local value of the temp_store flag. Changing
  115182. ** the local value does not make changes to the disk file and the default
  115183. ** value will be restored the next time the database is opened.
  115184. **
  115185. ** Note that it is possible for the library compile-time options to
  115186. ** override this setting
  115187. */
  115188. case PragTyp_TEMP_STORE: {
  115189. if( !zRight ){
  115190. returnSingleInt(v, db->temp_store);
  115191. }else{
  115192. changeTempStorage(pParse, zRight);
  115193. }
  115194. break;
  115195. }
  115196. /*
  115197. ** PRAGMA temp_store_directory
  115198. ** PRAGMA temp_store_directory = ""|"directory_name"
  115199. **
  115200. ** Return or set the local value of the temp_store_directory flag. Changing
  115201. ** the value sets a specific directory to be used for temporary files.
  115202. ** Setting to a null string reverts to the default temporary directory search.
  115203. ** If temporary directory is changed, then invalidateTempStorage.
  115204. **
  115205. */
  115206. case PragTyp_TEMP_STORE_DIRECTORY: {
  115207. if( !zRight ){
  115208. returnSingleText(v, sqlite3_temp_directory);
  115209. }else{
  115210. #ifndef SQLITE_OMIT_WSD
  115211. if( zRight[0] ){
  115212. int res;
  115213. rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
  115214. if( rc!=SQLITE_OK || res==0 ){
  115215. sqlite3ErrorMsg(pParse, "not a writable directory");
  115216. goto pragma_out;
  115217. }
  115218. }
  115219. if( SQLITE_TEMP_STORE==0
  115220. || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
  115221. || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
  115222. ){
  115223. invalidateTempStorage(pParse);
  115224. }
  115225. sqlite3_free(sqlite3_temp_directory);
  115226. if( zRight[0] ){
  115227. sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
  115228. }else{
  115229. sqlite3_temp_directory = 0;
  115230. }
  115231. #endif /* SQLITE_OMIT_WSD */
  115232. }
  115233. break;
  115234. }
  115235. #if SQLITE_OS_WIN
  115236. /*
  115237. ** PRAGMA data_store_directory
  115238. ** PRAGMA data_store_directory = ""|"directory_name"
  115239. **
  115240. ** Return or set the local value of the data_store_directory flag. Changing
  115241. ** the value sets a specific directory to be used for database files that
  115242. ** were specified with a relative pathname. Setting to a null string reverts
  115243. ** to the default database directory, which for database files specified with
  115244. ** a relative path will probably be based on the current directory for the
  115245. ** process. Database file specified with an absolute path are not impacted
  115246. ** by this setting, regardless of its value.
  115247. **
  115248. */
  115249. case PragTyp_DATA_STORE_DIRECTORY: {
  115250. if( !zRight ){
  115251. returnSingleText(v, sqlite3_data_directory);
  115252. }else{
  115253. #ifndef SQLITE_OMIT_WSD
  115254. if( zRight[0] ){
  115255. int res;
  115256. rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
  115257. if( rc!=SQLITE_OK || res==0 ){
  115258. sqlite3ErrorMsg(pParse, "not a writable directory");
  115259. goto pragma_out;
  115260. }
  115261. }
  115262. sqlite3_free(sqlite3_data_directory);
  115263. if( zRight[0] ){
  115264. sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
  115265. }else{
  115266. sqlite3_data_directory = 0;
  115267. }
  115268. #endif /* SQLITE_OMIT_WSD */
  115269. }
  115270. break;
  115271. }
  115272. #endif
  115273. #if SQLITE_ENABLE_LOCKING_STYLE
  115274. /*
  115275. ** PRAGMA [schema.]lock_proxy_file
  115276. ** PRAGMA [schema.]lock_proxy_file = ":auto:"|"lock_file_path"
  115277. **
  115278. ** Return or set the value of the lock_proxy_file flag. Changing
  115279. ** the value sets a specific file to be used for database access locks.
  115280. **
  115281. */
  115282. case PragTyp_LOCK_PROXY_FILE: {
  115283. if( !zRight ){
  115284. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  115285. char *proxy_file_path = NULL;
  115286. sqlite3_file *pFile = sqlite3PagerFile(pPager);
  115287. sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE,
  115288. &proxy_file_path);
  115289. returnSingleText(v, proxy_file_path);
  115290. }else{
  115291. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  115292. sqlite3_file *pFile = sqlite3PagerFile(pPager);
  115293. int res;
  115294. if( zRight[0] ){
  115295. res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
  115296. zRight);
  115297. } else {
  115298. res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
  115299. NULL);
  115300. }
  115301. if( res!=SQLITE_OK ){
  115302. sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
  115303. goto pragma_out;
  115304. }
  115305. }
  115306. break;
  115307. }
  115308. #endif /* SQLITE_ENABLE_LOCKING_STYLE */
  115309. /*
  115310. ** PRAGMA [schema.]synchronous
  115311. ** PRAGMA [schema.]synchronous=OFF|ON|NORMAL|FULL|EXTRA
  115312. **
  115313. ** Return or set the local value of the synchronous flag. Changing
  115314. ** the local value does not make changes to the disk file and the
  115315. ** default value will be restored the next time the database is
  115316. ** opened.
  115317. */
  115318. case PragTyp_SYNCHRONOUS: {
  115319. if( !zRight ){
  115320. returnSingleInt(v, pDb->safety_level-1);
  115321. }else{
  115322. if( !db->autoCommit ){
  115323. sqlite3ErrorMsg(pParse,
  115324. "Safety level may not be changed inside a transaction");
  115325. }else if( iDb!=1 ){
  115326. int iLevel = (getSafetyLevel(zRight,0,1)+1) & PAGER_SYNCHRONOUS_MASK;
  115327. if( iLevel==0 ) iLevel = 1;
  115328. pDb->safety_level = iLevel;
  115329. pDb->bSyncSet = 1;
  115330. setAllPagerFlags(db);
  115331. }
  115332. }
  115333. break;
  115334. }
  115335. #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
  115336. #ifndef SQLITE_OMIT_FLAG_PRAGMAS
  115337. case PragTyp_FLAG: {
  115338. if( zRight==0 ){
  115339. setPragmaResultColumnNames(v, pPragma);
  115340. returnSingleInt(v, (db->flags & pPragma->iArg)!=0 );
  115341. }else{
  115342. u64 mask = pPragma->iArg; /* Mask of bits to set or clear. */
  115343. if( db->autoCommit==0 ){
  115344. /* Foreign key support may not be enabled or disabled while not
  115345. ** in auto-commit mode. */
  115346. mask &= ~(SQLITE_ForeignKeys);
  115347. }
  115348. #if SQLITE_USER_AUTHENTICATION
  115349. if( db->auth.authLevel==UAUTH_User ){
  115350. /* Do not allow non-admin users to modify the schema arbitrarily */
  115351. mask &= ~(SQLITE_WriteSchema);
  115352. }
  115353. #endif
  115354. if( sqlite3GetBoolean(zRight, 0) ){
  115355. db->flags |= mask;
  115356. }else{
  115357. db->flags &= ~mask;
  115358. if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
  115359. }
  115360. /* Many of the flag-pragmas modify the code generated by the SQL
  115361. ** compiler (eg. count_changes). So add an opcode to expire all
  115362. ** compiled SQL statements after modifying a pragma value.
  115363. */
  115364. sqlite3VdbeAddOp0(v, OP_Expire);
  115365. setAllPagerFlags(db);
  115366. }
  115367. break;
  115368. }
  115369. #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
  115370. #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
  115371. /*
  115372. ** PRAGMA table_info(<table>)
  115373. **
  115374. ** Return a single row for each column of the named table. The columns of
  115375. ** the returned data set are:
  115376. **
  115377. ** cid: Column id (numbered from left to right, starting at 0)
  115378. ** name: Column name
  115379. ** type: Column declaration type.
  115380. ** notnull: True if 'NOT NULL' is part of column declaration
  115381. ** dflt_value: The default value for the column, if any.
  115382. ** pk: Non-zero for PK fields.
  115383. */
  115384. case PragTyp_TABLE_INFO: if( zRight ){
  115385. Table *pTab;
  115386. pTab = sqlite3LocateTable(pParse, LOCATE_NOERR, zRight, zDb);
  115387. if( pTab ){
  115388. int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  115389. int i, k;
  115390. int nHidden = 0;
  115391. Column *pCol;
  115392. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  115393. pParse->nMem = 7;
  115394. sqlite3CodeVerifySchema(pParse, iTabDb);
  115395. sqlite3ViewGetColumnNames(pParse, pTab);
  115396. for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
  115397. int isHidden = IsHiddenColumn(pCol);
  115398. if( isHidden && pPragma->iArg==0 ){
  115399. nHidden++;
  115400. continue;
  115401. }
  115402. if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
  115403. k = 0;
  115404. }else if( pPk==0 ){
  115405. k = 1;
  115406. }else{
  115407. for(k=1; k<=pTab->nCol && pPk->aiColumn[k-1]!=i; k++){}
  115408. }
  115409. assert( pCol->pDflt==0 || pCol->pDflt->op==TK_SPAN );
  115410. sqlite3VdbeMultiLoad(v, 1, pPragma->iArg ? "issisii" : "issisi",
  115411. i-nHidden,
  115412. pCol->zName,
  115413. sqlite3ColumnType(pCol,""),
  115414. pCol->notNull ? 1 : 0,
  115415. pCol->pDflt ? pCol->pDflt->u.zToken : 0,
  115416. k,
  115417. isHidden);
  115418. }
  115419. }
  115420. }
  115421. break;
  115422. #ifdef SQLITE_DEBUG
  115423. case PragTyp_STATS: {
  115424. Index *pIdx;
  115425. HashElem *i;
  115426. pParse->nMem = 5;
  115427. sqlite3CodeVerifySchema(pParse, iDb);
  115428. for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){
  115429. Table *pTab = sqliteHashData(i);
  115430. sqlite3VdbeMultiLoad(v, 1, "ssiii",
  115431. pTab->zName,
  115432. 0,
  115433. pTab->szTabRow,
  115434. pTab->nRowLogEst,
  115435. pTab->tabFlags);
  115436. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  115437. sqlite3VdbeMultiLoad(v, 2, "siiiX",
  115438. pIdx->zName,
  115439. pIdx->szIdxRow,
  115440. pIdx->aiRowLogEst[0],
  115441. pIdx->hasStat1);
  115442. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5);
  115443. }
  115444. }
  115445. }
  115446. break;
  115447. #endif
  115448. case PragTyp_INDEX_INFO: if( zRight ){
  115449. Index *pIdx;
  115450. Table *pTab;
  115451. pIdx = sqlite3FindIndex(db, zRight, zDb);
  115452. if( pIdx ){
  115453. int iIdxDb = sqlite3SchemaToIndex(db, pIdx->pSchema);
  115454. int i;
  115455. int mx;
  115456. if( pPragma->iArg ){
  115457. /* PRAGMA index_xinfo (newer version with more rows and columns) */
  115458. mx = pIdx->nColumn;
  115459. pParse->nMem = 6;
  115460. }else{
  115461. /* PRAGMA index_info (legacy version) */
  115462. mx = pIdx->nKeyCol;
  115463. pParse->nMem = 3;
  115464. }
  115465. pTab = pIdx->pTable;
  115466. sqlite3CodeVerifySchema(pParse, iIdxDb);
  115467. assert( pParse->nMem<=pPragma->nPragCName );
  115468. for(i=0; i<mx; i++){
  115469. i16 cnum = pIdx->aiColumn[i];
  115470. sqlite3VdbeMultiLoad(v, 1, "iisX", i, cnum,
  115471. cnum<0 ? 0 : pTab->aCol[cnum].zName);
  115472. if( pPragma->iArg ){
  115473. sqlite3VdbeMultiLoad(v, 4, "isiX",
  115474. pIdx->aSortOrder[i],
  115475. pIdx->azColl[i],
  115476. i<pIdx->nKeyCol);
  115477. }
  115478. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, pParse->nMem);
  115479. }
  115480. }
  115481. }
  115482. break;
  115483. case PragTyp_INDEX_LIST: if( zRight ){
  115484. Index *pIdx;
  115485. Table *pTab;
  115486. int i;
  115487. pTab = sqlite3FindTable(db, zRight, zDb);
  115488. if( pTab ){
  115489. int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  115490. pParse->nMem = 5;
  115491. sqlite3CodeVerifySchema(pParse, iTabDb);
  115492. for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){
  115493. const char *azOrigin[] = { "c", "u", "pk" };
  115494. sqlite3VdbeMultiLoad(v, 1, "isisi",
  115495. i,
  115496. pIdx->zName,
  115497. IsUniqueIndex(pIdx),
  115498. azOrigin[pIdx->idxType],
  115499. pIdx->pPartIdxWhere!=0);
  115500. }
  115501. }
  115502. }
  115503. break;
  115504. case PragTyp_DATABASE_LIST: {
  115505. int i;
  115506. pParse->nMem = 3;
  115507. for(i=0; i<db->nDb; i++){
  115508. if( db->aDb[i].pBt==0 ) continue;
  115509. assert( db->aDb[i].zDbSName!=0 );
  115510. sqlite3VdbeMultiLoad(v, 1, "iss",
  115511. i,
  115512. db->aDb[i].zDbSName,
  115513. sqlite3BtreeGetFilename(db->aDb[i].pBt));
  115514. }
  115515. }
  115516. break;
  115517. case PragTyp_COLLATION_LIST: {
  115518. int i = 0;
  115519. HashElem *p;
  115520. pParse->nMem = 2;
  115521. for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
  115522. CollSeq *pColl = (CollSeq *)sqliteHashData(p);
  115523. sqlite3VdbeMultiLoad(v, 1, "is", i++, pColl->zName);
  115524. }
  115525. }
  115526. break;
  115527. #ifdef SQLITE_INTROSPECTION_PRAGMAS
  115528. case PragTyp_FUNCTION_LIST: {
  115529. int i;
  115530. HashElem *j;
  115531. FuncDef *p;
  115532. pParse->nMem = 2;
  115533. for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){
  115534. for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash ){
  115535. if( p->funcFlags & SQLITE_FUNC_INTERNAL ) continue;
  115536. sqlite3VdbeMultiLoad(v, 1, "si", p->zName, 1);
  115537. }
  115538. }
  115539. for(j=sqliteHashFirst(&db->aFunc); j; j=sqliteHashNext(j)){
  115540. p = (FuncDef*)sqliteHashData(j);
  115541. sqlite3VdbeMultiLoad(v, 1, "si", p->zName, 0);
  115542. }
  115543. }
  115544. break;
  115545. #ifndef SQLITE_OMIT_VIRTUALTABLE
  115546. case PragTyp_MODULE_LIST: {
  115547. HashElem *j;
  115548. pParse->nMem = 1;
  115549. for(j=sqliteHashFirst(&db->aModule); j; j=sqliteHashNext(j)){
  115550. Module *pMod = (Module*)sqliteHashData(j);
  115551. sqlite3VdbeMultiLoad(v, 1, "s", pMod->zName);
  115552. }
  115553. }
  115554. break;
  115555. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  115556. case PragTyp_PRAGMA_LIST: {
  115557. int i;
  115558. for(i=0; i<ArraySize(aPragmaName); i++){
  115559. sqlite3VdbeMultiLoad(v, 1, "s", aPragmaName[i].zName);
  115560. }
  115561. }
  115562. break;
  115563. #endif /* SQLITE_INTROSPECTION_PRAGMAS */
  115564. #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
  115565. #ifndef SQLITE_OMIT_FOREIGN_KEY
  115566. case PragTyp_FOREIGN_KEY_LIST: if( zRight ){
  115567. FKey *pFK;
  115568. Table *pTab;
  115569. pTab = sqlite3FindTable(db, zRight, zDb);
  115570. if( pTab ){
  115571. pFK = pTab->pFKey;
  115572. if( pFK ){
  115573. int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  115574. int i = 0;
  115575. pParse->nMem = 8;
  115576. sqlite3CodeVerifySchema(pParse, iTabDb);
  115577. while(pFK){
  115578. int j;
  115579. for(j=0; j<pFK->nCol; j++){
  115580. sqlite3VdbeMultiLoad(v, 1, "iissssss",
  115581. i,
  115582. j,
  115583. pFK->zTo,
  115584. pTab->aCol[pFK->aCol[j].iFrom].zName,
  115585. pFK->aCol[j].zCol,
  115586. actionName(pFK->aAction[1]), /* ON UPDATE */
  115587. actionName(pFK->aAction[0]), /* ON DELETE */
  115588. "NONE");
  115589. }
  115590. ++i;
  115591. pFK = pFK->pNextFrom;
  115592. }
  115593. }
  115594. }
  115595. }
  115596. break;
  115597. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  115598. #ifndef SQLITE_OMIT_FOREIGN_KEY
  115599. #ifndef SQLITE_OMIT_TRIGGER
  115600. case PragTyp_FOREIGN_KEY_CHECK: {
  115601. FKey *pFK; /* A foreign key constraint */
  115602. Table *pTab; /* Child table contain "REFERENCES" keyword */
  115603. Table *pParent; /* Parent table that child points to */
  115604. Index *pIdx; /* Index in the parent table */
  115605. int i; /* Loop counter: Foreign key number for pTab */
  115606. int j; /* Loop counter: Field of the foreign key */
  115607. HashElem *k; /* Loop counter: Next table in schema */
  115608. int x; /* result variable */
  115609. int regResult; /* 3 registers to hold a result row */
  115610. int regKey; /* Register to hold key for checking the FK */
  115611. int regRow; /* Registers to hold a row from pTab */
  115612. int addrTop; /* Top of a loop checking foreign keys */
  115613. int addrOk; /* Jump here if the key is OK */
  115614. int *aiCols; /* child to parent column mapping */
  115615. regResult = pParse->nMem+1;
  115616. pParse->nMem += 4;
  115617. regKey = ++pParse->nMem;
  115618. regRow = ++pParse->nMem;
  115619. k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
  115620. while( k ){
  115621. int iTabDb;
  115622. if( zRight ){
  115623. pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
  115624. k = 0;
  115625. }else{
  115626. pTab = (Table*)sqliteHashData(k);
  115627. k = sqliteHashNext(k);
  115628. }
  115629. if( pTab==0 || pTab->pFKey==0 ) continue;
  115630. iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  115631. sqlite3CodeVerifySchema(pParse, iTabDb);
  115632. sqlite3TableLock(pParse, iTabDb, pTab->tnum, 0, pTab->zName);
  115633. if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
  115634. sqlite3OpenTable(pParse, 0, iTabDb, pTab, OP_OpenRead);
  115635. sqlite3VdbeLoadString(v, regResult, pTab->zName);
  115636. for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
  115637. pParent = sqlite3FindTable(db, pFK->zTo, zDb);
  115638. if( pParent==0 ) continue;
  115639. pIdx = 0;
  115640. sqlite3TableLock(pParse, iTabDb, pParent->tnum, 0, pParent->zName);
  115641. x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
  115642. if( x==0 ){
  115643. if( pIdx==0 ){
  115644. sqlite3OpenTable(pParse, i, iTabDb, pParent, OP_OpenRead);
  115645. }else{
  115646. sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iTabDb);
  115647. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  115648. }
  115649. }else{
  115650. k = 0;
  115651. break;
  115652. }
  115653. }
  115654. assert( pParse->nErr>0 || pFK==0 );
  115655. if( pFK ) break;
  115656. if( pParse->nTab<i ) pParse->nTab = i;
  115657. addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v);
  115658. for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
  115659. pParent = sqlite3FindTable(db, pFK->zTo, zDb);
  115660. pIdx = 0;
  115661. aiCols = 0;
  115662. if( pParent ){
  115663. x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
  115664. assert( x==0 );
  115665. }
  115666. addrOk = sqlite3VdbeMakeLabel(pParse);
  115667. /* Generate code to read the child key values into registers
  115668. ** regRow..regRow+n. If any of the child key values are NULL, this
  115669. ** row cannot cause an FK violation. Jump directly to addrOk in
  115670. ** this case. */
  115671. for(j=0; j<pFK->nCol; j++){
  115672. int iCol = aiCols ? aiCols[j] : pFK->aCol[j].iFrom;
  115673. sqlite3ExprCodeGetColumnOfTable(v, pTab, 0, iCol, regRow+j);
  115674. sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v);
  115675. }
  115676. /* Generate code to query the parent index for a matching parent
  115677. ** key. If a match is found, jump to addrOk. */
  115678. if( pIdx ){
  115679. sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, pFK->nCol, regKey,
  115680. sqlite3IndexAffinityStr(db,pIdx), pFK->nCol);
  115681. sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0);
  115682. VdbeCoverage(v);
  115683. }else if( pParent ){
  115684. int jmp = sqlite3VdbeCurrentAddr(v)+2;
  115685. sqlite3VdbeAddOp3(v, OP_SeekRowid, i, jmp, regRow); VdbeCoverage(v);
  115686. sqlite3VdbeGoto(v, addrOk);
  115687. assert( pFK->nCol==1 );
  115688. }
  115689. /* Generate code to report an FK violation to the caller. */
  115690. if( HasRowid(pTab) ){
  115691. sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
  115692. }else{
  115693. sqlite3VdbeAddOp2(v, OP_Null, 0, regResult+1);
  115694. }
  115695. sqlite3VdbeMultiLoad(v, regResult+2, "siX", pFK->zTo, i-1);
  115696. sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
  115697. sqlite3VdbeResolveLabel(v, addrOk);
  115698. sqlite3DbFree(db, aiCols);
  115699. }
  115700. sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); VdbeCoverage(v);
  115701. sqlite3VdbeJumpHere(v, addrTop);
  115702. }
  115703. }
  115704. break;
  115705. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  115706. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  115707. #ifndef SQLITE_OMIT_CASE_SENSITIVE_LIKE_PRAGMA
  115708. /* Reinstall the LIKE and GLOB functions. The variant of LIKE
  115709. ** used will be case sensitive or not depending on the RHS.
  115710. */
  115711. case PragTyp_CASE_SENSITIVE_LIKE: {
  115712. if( zRight ){
  115713. sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
  115714. }
  115715. }
  115716. break;
  115717. #endif /* SQLITE_OMIT_CASE_SENSITIVE_LIKE_PRAGMA */
  115718. #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
  115719. # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
  115720. #endif
  115721. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  115722. /* PRAGMA integrity_check
  115723. ** PRAGMA integrity_check(N)
  115724. ** PRAGMA quick_check
  115725. ** PRAGMA quick_check(N)
  115726. **
  115727. ** Verify the integrity of the database.
  115728. **
  115729. ** The "quick_check" is reduced version of
  115730. ** integrity_check designed to detect most database corruption
  115731. ** without the overhead of cross-checking indexes. Quick_check
  115732. ** is linear time wherease integrity_check is O(NlogN).
  115733. */
  115734. case PragTyp_INTEGRITY_CHECK: {
  115735. int i, j, addr, mxErr;
  115736. int isQuick = (sqlite3Tolower(zLeft[0])=='q');
  115737. /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
  115738. ** then iDb is set to the index of the database identified by <db>.
  115739. ** In this case, the integrity of database iDb only is verified by
  115740. ** the VDBE created below.
  115741. **
  115742. ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
  115743. ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
  115744. ** to -1 here, to indicate that the VDBE should verify the integrity
  115745. ** of all attached databases. */
  115746. assert( iDb>=0 );
  115747. assert( iDb==0 || pId2->z );
  115748. if( pId2->z==0 ) iDb = -1;
  115749. /* Initialize the VDBE program */
  115750. pParse->nMem = 6;
  115751. /* Set the maximum error count */
  115752. mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
  115753. if( zRight ){
  115754. sqlite3GetInt32(zRight, &mxErr);
  115755. if( mxErr<=0 ){
  115756. mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
  115757. }
  115758. }
  115759. sqlite3VdbeAddOp2(v, OP_Integer, mxErr-1, 1); /* reg[1] holds errors left */
  115760. /* Do an integrity check on each database file */
  115761. for(i=0; i<db->nDb; i++){
  115762. HashElem *x; /* For looping over tables in the schema */
  115763. Hash *pTbls; /* Set of all tables in the schema */
  115764. int *aRoot; /* Array of root page numbers of all btrees */
  115765. int cnt = 0; /* Number of entries in aRoot[] */
  115766. int mxIdx = 0; /* Maximum number of indexes for any table */
  115767. if( OMIT_TEMPDB && i==1 ) continue;
  115768. if( iDb>=0 && i!=iDb ) continue;
  115769. sqlite3CodeVerifySchema(pParse, i);
  115770. /* Do an integrity check of the B-Tree
  115771. **
  115772. ** Begin by finding the root pages numbers
  115773. ** for all tables and indices in the database.
  115774. */
  115775. assert( sqlite3SchemaMutexHeld(db, i, 0) );
  115776. pTbls = &db->aDb[i].pSchema->tblHash;
  115777. for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
  115778. Table *pTab = sqliteHashData(x); /* Current table */
  115779. Index *pIdx; /* An index on pTab */
  115780. int nIdx; /* Number of indexes on pTab */
  115781. if( HasRowid(pTab) ) cnt++;
  115782. for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){ cnt++; }
  115783. if( nIdx>mxIdx ) mxIdx = nIdx;
  115784. }
  115785. aRoot = sqlite3DbMallocRawNN(db, sizeof(int)*(cnt+1));
  115786. if( aRoot==0 ) break;
  115787. for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
  115788. Table *pTab = sqliteHashData(x);
  115789. Index *pIdx;
  115790. if( HasRowid(pTab) ) aRoot[++cnt] = pTab->tnum;
  115791. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  115792. aRoot[++cnt] = pIdx->tnum;
  115793. }
  115794. }
  115795. aRoot[0] = cnt;
  115796. /* Make sure sufficient number of registers have been allocated */
  115797. pParse->nMem = MAX( pParse->nMem, 8+mxIdx );
  115798. sqlite3ClearTempRegCache(pParse);
  115799. /* Do the b-tree integrity checks */
  115800. sqlite3VdbeAddOp4(v, OP_IntegrityCk, 2, cnt, 1, (char*)aRoot,P4_INTARRAY);
  115801. sqlite3VdbeChangeP5(v, (u8)i);
  115802. addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v);
  115803. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
  115804. sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zDbSName),
  115805. P4_DYNAMIC);
  115806. sqlite3VdbeAddOp3(v, OP_Concat, 2, 3, 3);
  115807. integrityCheckResultRow(v);
  115808. sqlite3VdbeJumpHere(v, addr);
  115809. /* Make sure all the indices are constructed correctly.
  115810. */
  115811. for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
  115812. Table *pTab = sqliteHashData(x);
  115813. Index *pIdx, *pPk;
  115814. Index *pPrior = 0;
  115815. int loopTop;
  115816. int iDataCur, iIdxCur;
  115817. int r1 = -1;
  115818. if( pTab->tnum<1 ) continue; /* Skip VIEWs or VIRTUAL TABLEs */
  115819. pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
  115820. sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead, 0,
  115821. 1, 0, &iDataCur, &iIdxCur);
  115822. /* reg[7] counts the number of entries in the table.
  115823. ** reg[8+i] counts the number of entries in the i-th index
  115824. */
  115825. sqlite3VdbeAddOp2(v, OP_Integer, 0, 7);
  115826. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  115827. sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); /* index entries counter */
  115828. }
  115829. assert( pParse->nMem>=8+j );
  115830. assert( sqlite3NoTempsInRange(pParse,1,7+j) );
  115831. sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v);
  115832. loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1);
  115833. if( !isQuick ){
  115834. /* Sanity check on record header decoding */
  115835. sqlite3VdbeAddOp3(v, OP_Column, iDataCur, pTab->nCol-1, 3);
  115836. sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
  115837. }
  115838. /* Verify that all NOT NULL columns really are NOT NULL */
  115839. for(j=0; j<pTab->nCol; j++){
  115840. char *zErr;
  115841. int jmp2;
  115842. if( j==pTab->iPKey ) continue;
  115843. if( pTab->aCol[j].notNull==0 ) continue;
  115844. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3);
  115845. sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
  115846. jmp2 = sqlite3VdbeAddOp1(v, OP_NotNull, 3); VdbeCoverage(v);
  115847. zErr = sqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName,
  115848. pTab->aCol[j].zName);
  115849. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
  115850. integrityCheckResultRow(v);
  115851. sqlite3VdbeJumpHere(v, jmp2);
  115852. }
  115853. /* Verify CHECK constraints */
  115854. if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
  115855. ExprList *pCheck = sqlite3ExprListDup(db, pTab->pCheck, 0);
  115856. if( db->mallocFailed==0 ){
  115857. int addrCkFault = sqlite3VdbeMakeLabel(pParse);
  115858. int addrCkOk = sqlite3VdbeMakeLabel(pParse);
  115859. char *zErr;
  115860. int k;
  115861. pParse->iSelfTab = iDataCur + 1;
  115862. for(k=pCheck->nExpr-1; k>0; k--){
  115863. sqlite3ExprIfFalse(pParse, pCheck->a[k].pExpr, addrCkFault, 0);
  115864. }
  115865. sqlite3ExprIfTrue(pParse, pCheck->a[0].pExpr, addrCkOk,
  115866. SQLITE_JUMPIFNULL);
  115867. sqlite3VdbeResolveLabel(v, addrCkFault);
  115868. pParse->iSelfTab = 0;
  115869. zErr = sqlite3MPrintf(db, "CHECK constraint failed in %s",
  115870. pTab->zName);
  115871. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
  115872. integrityCheckResultRow(v);
  115873. sqlite3VdbeResolveLabel(v, addrCkOk);
  115874. }
  115875. sqlite3ExprListDelete(db, pCheck);
  115876. }
  115877. if( !isQuick ){ /* Omit the remaining tests for quick_check */
  115878. /* Validate index entries for the current row */
  115879. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  115880. int jmp2, jmp3, jmp4, jmp5;
  115881. int ckUniq = sqlite3VdbeMakeLabel(pParse);
  115882. if( pPk==pIdx ) continue;
  115883. r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3,
  115884. pPrior, r1);
  115885. pPrior = pIdx;
  115886. sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1);/* increment entry count */
  115887. /* Verify that an index entry exists for the current table row */
  115888. jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, ckUniq, r1,
  115889. pIdx->nColumn); VdbeCoverage(v);
  115890. sqlite3VdbeLoadString(v, 3, "row ");
  115891. sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
  115892. sqlite3VdbeLoadString(v, 4, " missing from index ");
  115893. sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
  115894. jmp5 = sqlite3VdbeLoadString(v, 4, pIdx->zName);
  115895. sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
  115896. jmp4 = integrityCheckResultRow(v);
  115897. sqlite3VdbeJumpHere(v, jmp2);
  115898. /* For UNIQUE indexes, verify that only one entry exists with the
  115899. ** current key. The entry is unique if (1) any column is NULL
  115900. ** or (2) the next entry has a different key */
  115901. if( IsUniqueIndex(pIdx) ){
  115902. int uniqOk = sqlite3VdbeMakeLabel(pParse);
  115903. int jmp6;
  115904. int kk;
  115905. for(kk=0; kk<pIdx->nKeyCol; kk++){
  115906. int iCol = pIdx->aiColumn[kk];
  115907. assert( iCol!=XN_ROWID && iCol<pTab->nCol );
  115908. if( iCol>=0 && pTab->aCol[iCol].notNull ) continue;
  115909. sqlite3VdbeAddOp2(v, OP_IsNull, r1+kk, uniqOk);
  115910. VdbeCoverage(v);
  115911. }
  115912. jmp6 = sqlite3VdbeAddOp1(v, OP_Next, iIdxCur+j); VdbeCoverage(v);
  115913. sqlite3VdbeGoto(v, uniqOk);
  115914. sqlite3VdbeJumpHere(v, jmp6);
  115915. sqlite3VdbeAddOp4Int(v, OP_IdxGT, iIdxCur+j, uniqOk, r1,
  115916. pIdx->nKeyCol); VdbeCoverage(v);
  115917. sqlite3VdbeLoadString(v, 3, "non-unique entry in index ");
  115918. sqlite3VdbeGoto(v, jmp5);
  115919. sqlite3VdbeResolveLabel(v, uniqOk);
  115920. }
  115921. sqlite3VdbeJumpHere(v, jmp4);
  115922. sqlite3ResolvePartIdxLabel(pParse, jmp3);
  115923. }
  115924. }
  115925. sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v);
  115926. sqlite3VdbeJumpHere(v, loopTop-1);
  115927. #ifndef SQLITE_OMIT_BTREECOUNT
  115928. if( !isQuick ){
  115929. sqlite3VdbeLoadString(v, 2, "wrong # of entries in index ");
  115930. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  115931. if( pPk==pIdx ) continue;
  115932. sqlite3VdbeAddOp2(v, OP_Count, iIdxCur+j, 3);
  115933. addr = sqlite3VdbeAddOp3(v, OP_Eq, 8+j, 0, 3); VdbeCoverage(v);
  115934. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  115935. sqlite3VdbeLoadString(v, 4, pIdx->zName);
  115936. sqlite3VdbeAddOp3(v, OP_Concat, 4, 2, 3);
  115937. integrityCheckResultRow(v);
  115938. sqlite3VdbeJumpHere(v, addr);
  115939. }
  115940. }
  115941. #endif /* SQLITE_OMIT_BTREECOUNT */
  115942. }
  115943. }
  115944. {
  115945. static const int iLn = VDBE_OFFSET_LINENO(2);
  115946. static const VdbeOpList endCode[] = {
  115947. { OP_AddImm, 1, 0, 0}, /* 0 */
  115948. { OP_IfNotZero, 1, 4, 0}, /* 1 */
  115949. { OP_String8, 0, 3, 0}, /* 2 */
  115950. { OP_ResultRow, 3, 1, 0}, /* 3 */
  115951. { OP_Halt, 0, 0, 0}, /* 4 */
  115952. { OP_String8, 0, 3, 0}, /* 5 */
  115953. { OP_Goto, 0, 3, 0}, /* 6 */
  115954. };
  115955. VdbeOp *aOp;
  115956. aOp = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn);
  115957. if( aOp ){
  115958. aOp[0].p2 = 1-mxErr;
  115959. aOp[2].p4type = P4_STATIC;
  115960. aOp[2].p4.z = "ok";
  115961. aOp[5].p4type = P4_STATIC;
  115962. aOp[5].p4.z = (char*)sqlite3ErrStr(SQLITE_CORRUPT);
  115963. }
  115964. sqlite3VdbeChangeP3(v, 0, sqlite3VdbeCurrentAddr(v)-2);
  115965. }
  115966. }
  115967. break;
  115968. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  115969. #ifndef SQLITE_OMIT_UTF16
  115970. /*
  115971. ** PRAGMA encoding
  115972. ** PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
  115973. **
  115974. ** In its first form, this pragma returns the encoding of the main
  115975. ** database. If the database is not initialized, it is initialized now.
  115976. **
  115977. ** The second form of this pragma is a no-op if the main database file
  115978. ** has not already been initialized. In this case it sets the default
  115979. ** encoding that will be used for the main database file if a new file
  115980. ** is created. If an existing main database file is opened, then the
  115981. ** default text encoding for the existing database is used.
  115982. **
  115983. ** In all cases new databases created using the ATTACH command are
  115984. ** created to use the same default text encoding as the main database. If
  115985. ** the main database has not been initialized and/or created when ATTACH
  115986. ** is executed, this is done before the ATTACH operation.
  115987. **
  115988. ** In the second form this pragma sets the text encoding to be used in
  115989. ** new database files created using this database handle. It is only
  115990. ** useful if invoked immediately after the main database i
  115991. */
  115992. case PragTyp_ENCODING: {
  115993. static const struct EncName {
  115994. char *zName;
  115995. u8 enc;
  115996. } encnames[] = {
  115997. { "UTF8", SQLITE_UTF8 },
  115998. { "UTF-8", SQLITE_UTF8 }, /* Must be element [1] */
  115999. { "UTF-16le", SQLITE_UTF16LE }, /* Must be element [2] */
  116000. { "UTF-16be", SQLITE_UTF16BE }, /* Must be element [3] */
  116001. { "UTF16le", SQLITE_UTF16LE },
  116002. { "UTF16be", SQLITE_UTF16BE },
  116003. { "UTF-16", 0 }, /* SQLITE_UTF16NATIVE */
  116004. { "UTF16", 0 }, /* SQLITE_UTF16NATIVE */
  116005. { 0, 0 }
  116006. };
  116007. const struct EncName *pEnc;
  116008. if( !zRight ){ /* "PRAGMA encoding" */
  116009. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  116010. assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
  116011. assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
  116012. assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
  116013. returnSingleText(v, encnames[ENC(pParse->db)].zName);
  116014. }else{ /* "PRAGMA encoding = XXX" */
  116015. /* Only change the value of sqlite.enc if the database handle is not
  116016. ** initialized. If the main database exists, the new sqlite.enc value
  116017. ** will be overwritten when the schema is next loaded. If it does not
  116018. ** already exists, it will be created to use the new encoding value.
  116019. */
  116020. if(
  116021. !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
  116022. DbHasProperty(db, 0, DB_Empty)
  116023. ){
  116024. for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
  116025. if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
  116026. SCHEMA_ENC(db) = ENC(db) =
  116027. pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
  116028. break;
  116029. }
  116030. }
  116031. if( !pEnc->zName ){
  116032. sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
  116033. }
  116034. }
  116035. }
  116036. }
  116037. break;
  116038. #endif /* SQLITE_OMIT_UTF16 */
  116039. #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
  116040. /*
  116041. ** PRAGMA [schema.]schema_version
  116042. ** PRAGMA [schema.]schema_version = <integer>
  116043. **
  116044. ** PRAGMA [schema.]user_version
  116045. ** PRAGMA [schema.]user_version = <integer>
  116046. **
  116047. ** PRAGMA [schema.]freelist_count
  116048. **
  116049. ** PRAGMA [schema.]data_version
  116050. **
  116051. ** PRAGMA [schema.]application_id
  116052. ** PRAGMA [schema.]application_id = <integer>
  116053. **
  116054. ** The pragma's schema_version and user_version are used to set or get
  116055. ** the value of the schema-version and user-version, respectively. Both
  116056. ** the schema-version and the user-version are 32-bit signed integers
  116057. ** stored in the database header.
  116058. **
  116059. ** The schema-cookie is usually only manipulated internally by SQLite. It
  116060. ** is incremented by SQLite whenever the database schema is modified (by
  116061. ** creating or dropping a table or index). The schema version is used by
  116062. ** SQLite each time a query is executed to ensure that the internal cache
  116063. ** of the schema used when compiling the SQL query matches the schema of
  116064. ** the database against which the compiled query is actually executed.
  116065. ** Subverting this mechanism by using "PRAGMA schema_version" to modify
  116066. ** the schema-version is potentially dangerous and may lead to program
  116067. ** crashes or database corruption. Use with caution!
  116068. **
  116069. ** The user-version is not used internally by SQLite. It may be used by
  116070. ** applications for any purpose.
  116071. */
  116072. case PragTyp_HEADER_VALUE: {
  116073. int iCookie = pPragma->iArg; /* Which cookie to read or write */
  116074. sqlite3VdbeUsesBtree(v, iDb);
  116075. if( zRight && (pPragma->mPragFlg & PragFlg_ReadOnly)==0 ){
  116076. /* Write the specified cookie value */
  116077. static const VdbeOpList setCookie[] = {
  116078. { OP_Transaction, 0, 1, 0}, /* 0 */
  116079. { OP_SetCookie, 0, 0, 0}, /* 1 */
  116080. };
  116081. VdbeOp *aOp;
  116082. sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setCookie));
  116083. aOp = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0);
  116084. if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
  116085. aOp[0].p1 = iDb;
  116086. aOp[1].p1 = iDb;
  116087. aOp[1].p2 = iCookie;
  116088. aOp[1].p3 = sqlite3Atoi(zRight);
  116089. }else{
  116090. /* Read the specified cookie value */
  116091. static const VdbeOpList readCookie[] = {
  116092. { OP_Transaction, 0, 0, 0}, /* 0 */
  116093. { OP_ReadCookie, 0, 1, 0}, /* 1 */
  116094. { OP_ResultRow, 1, 1, 0}
  116095. };
  116096. VdbeOp *aOp;
  116097. sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(readCookie));
  116098. aOp = sqlite3VdbeAddOpList(v, ArraySize(readCookie),readCookie,0);
  116099. if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
  116100. aOp[0].p1 = iDb;
  116101. aOp[1].p1 = iDb;
  116102. aOp[1].p3 = iCookie;
  116103. sqlite3VdbeReusable(v);
  116104. }
  116105. }
  116106. break;
  116107. #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
  116108. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  116109. /*
  116110. ** PRAGMA compile_options
  116111. **
  116112. ** Return the names of all compile-time options used in this build,
  116113. ** one option per row.
  116114. */
  116115. case PragTyp_COMPILE_OPTIONS: {
  116116. int i = 0;
  116117. const char *zOpt;
  116118. pParse->nMem = 1;
  116119. while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
  116120. sqlite3VdbeLoadString(v, 1, zOpt);
  116121. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  116122. }
  116123. sqlite3VdbeReusable(v);
  116124. }
  116125. break;
  116126. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  116127. #ifndef SQLITE_OMIT_WAL
  116128. /*
  116129. ** PRAGMA [schema.]wal_checkpoint = passive|full|restart|truncate
  116130. **
  116131. ** Checkpoint the database.
  116132. */
  116133. case PragTyp_WAL_CHECKPOINT: {
  116134. int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
  116135. int eMode = SQLITE_CHECKPOINT_PASSIVE;
  116136. if( zRight ){
  116137. if( sqlite3StrICmp(zRight, "full")==0 ){
  116138. eMode = SQLITE_CHECKPOINT_FULL;
  116139. }else if( sqlite3StrICmp(zRight, "restart")==0 ){
  116140. eMode = SQLITE_CHECKPOINT_RESTART;
  116141. }else if( sqlite3StrICmp(zRight, "truncate")==0 ){
  116142. eMode = SQLITE_CHECKPOINT_TRUNCATE;
  116143. }
  116144. }
  116145. pParse->nMem = 3;
  116146. sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
  116147. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  116148. }
  116149. break;
  116150. /*
  116151. ** PRAGMA wal_autocheckpoint
  116152. ** PRAGMA wal_autocheckpoint = N
  116153. **
  116154. ** Configure a database connection to automatically checkpoint a database
  116155. ** after accumulating N frames in the log. Or query for the current value
  116156. ** of N.
  116157. */
  116158. case PragTyp_WAL_AUTOCHECKPOINT: {
  116159. if( zRight ){
  116160. sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
  116161. }
  116162. returnSingleInt(v,
  116163. db->xWalCallback==sqlite3WalDefaultHook ?
  116164. SQLITE_PTR_TO_INT(db->pWalArg) : 0);
  116165. }
  116166. break;
  116167. #endif
  116168. /*
  116169. ** PRAGMA shrink_memory
  116170. **
  116171. ** IMPLEMENTATION-OF: R-23445-46109 This pragma causes the database
  116172. ** connection on which it is invoked to free up as much memory as it
  116173. ** can, by calling sqlite3_db_release_memory().
  116174. */
  116175. case PragTyp_SHRINK_MEMORY: {
  116176. sqlite3_db_release_memory(db);
  116177. break;
  116178. }
  116179. /*
  116180. ** PRAGMA optimize
  116181. ** PRAGMA optimize(MASK)
  116182. ** PRAGMA schema.optimize
  116183. ** PRAGMA schema.optimize(MASK)
  116184. **
  116185. ** Attempt to optimize the database. All schemas are optimized in the first
  116186. ** two forms, and only the specified schema is optimized in the latter two.
  116187. **
  116188. ** The details of optimizations performed by this pragma are expected
  116189. ** to change and improve over time. Applications should anticipate that
  116190. ** this pragma will perform new optimizations in future releases.
  116191. **
  116192. ** The optional argument is a bitmask of optimizations to perform:
  116193. **
  116194. ** 0x0001 Debugging mode. Do not actually perform any optimizations
  116195. ** but instead return one line of text for each optimization
  116196. ** that would have been done. Off by default.
  116197. **
  116198. ** 0x0002 Run ANALYZE on tables that might benefit. On by default.
  116199. ** See below for additional information.
  116200. **
  116201. ** 0x0004 (Not yet implemented) Record usage and performance
  116202. ** information from the current session in the
  116203. ** database file so that it will be available to "optimize"
  116204. ** pragmas run by future database connections.
  116205. **
  116206. ** 0x0008 (Not yet implemented) Create indexes that might have
  116207. ** been helpful to recent queries
  116208. **
  116209. ** The default MASK is and always shall be 0xfffe. 0xfffe means perform all
  116210. ** of the optimizations listed above except Debug Mode, including new
  116211. ** optimizations that have not yet been invented. If new optimizations are
  116212. ** ever added that should be off by default, those off-by-default
  116213. ** optimizations will have bitmasks of 0x10000 or larger.
  116214. **
  116215. ** DETERMINATION OF WHEN TO RUN ANALYZE
  116216. **
  116217. ** In the current implementation, a table is analyzed if only if all of
  116218. ** the following are true:
  116219. **
  116220. ** (1) MASK bit 0x02 is set.
  116221. **
  116222. ** (2) The query planner used sqlite_stat1-style statistics for one or
  116223. ** more indexes of the table at some point during the lifetime of
  116224. ** the current connection.
  116225. **
  116226. ** (3) One or more indexes of the table are currently unanalyzed OR
  116227. ** the number of rows in the table has increased by 25 times or more
  116228. ** since the last time ANALYZE was run.
  116229. **
  116230. ** The rules for when tables are analyzed are likely to change in
  116231. ** future releases.
  116232. */
  116233. case PragTyp_OPTIMIZE: {
  116234. int iDbLast; /* Loop termination point for the schema loop */
  116235. int iTabCur; /* Cursor for a table whose size needs checking */
  116236. HashElem *k; /* Loop over tables of a schema */
  116237. Schema *pSchema; /* The current schema */
  116238. Table *pTab; /* A table in the schema */
  116239. Index *pIdx; /* An index of the table */
  116240. LogEst szThreshold; /* Size threshold above which reanalysis is needd */
  116241. char *zSubSql; /* SQL statement for the OP_SqlExec opcode */
  116242. u32 opMask; /* Mask of operations to perform */
  116243. if( zRight ){
  116244. opMask = (u32)sqlite3Atoi(zRight);
  116245. if( (opMask & 0x02)==0 ) break;
  116246. }else{
  116247. opMask = 0xfffe;
  116248. }
  116249. iTabCur = pParse->nTab++;
  116250. for(iDbLast = zDb?iDb:db->nDb-1; iDb<=iDbLast; iDb++){
  116251. if( iDb==1 ) continue;
  116252. sqlite3CodeVerifySchema(pParse, iDb);
  116253. pSchema = db->aDb[iDb].pSchema;
  116254. for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
  116255. pTab = (Table*)sqliteHashData(k);
  116256. /* If table pTab has not been used in a way that would benefit from
  116257. ** having analysis statistics during the current session, then skip it.
  116258. ** This also has the effect of skipping virtual tables and views */
  116259. if( (pTab->tabFlags & TF_StatsUsed)==0 ) continue;
  116260. /* Reanalyze if the table is 25 times larger than the last analysis */
  116261. szThreshold = pTab->nRowLogEst + 46; assert( sqlite3LogEst(25)==46 );
  116262. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  116263. if( !pIdx->hasStat1 ){
  116264. szThreshold = 0; /* Always analyze if any index lacks statistics */
  116265. break;
  116266. }
  116267. }
  116268. if( szThreshold ){
  116269. sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
  116270. sqlite3VdbeAddOp3(v, OP_IfSmaller, iTabCur,
  116271. sqlite3VdbeCurrentAddr(v)+2+(opMask&1), szThreshold);
  116272. VdbeCoverage(v);
  116273. }
  116274. zSubSql = sqlite3MPrintf(db, "ANALYZE \"%w\".\"%w\"",
  116275. db->aDb[iDb].zDbSName, pTab->zName);
  116276. if( opMask & 0x01 ){
  116277. int r1 = sqlite3GetTempReg(pParse);
  116278. sqlite3VdbeAddOp4(v, OP_String8, 0, r1, 0, zSubSql, P4_DYNAMIC);
  116279. sqlite3VdbeAddOp2(v, OP_ResultRow, r1, 1);
  116280. }else{
  116281. sqlite3VdbeAddOp4(v, OP_SqlExec, 0, 0, 0, zSubSql, P4_DYNAMIC);
  116282. }
  116283. }
  116284. }
  116285. sqlite3VdbeAddOp0(v, OP_Expire);
  116286. break;
  116287. }
  116288. /*
  116289. ** PRAGMA busy_timeout
  116290. ** PRAGMA busy_timeout = N
  116291. **
  116292. ** Call sqlite3_busy_timeout(db, N). Return the current timeout value
  116293. ** if one is set. If no busy handler or a different busy handler is set
  116294. ** then 0 is returned. Setting the busy_timeout to 0 or negative
  116295. ** disables the timeout.
  116296. */
  116297. /*case PragTyp_BUSY_TIMEOUT*/ default: {
  116298. assert( pPragma->ePragTyp==PragTyp_BUSY_TIMEOUT );
  116299. if( zRight ){
  116300. sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
  116301. }
  116302. returnSingleInt(v, db->busyTimeout);
  116303. break;
  116304. }
  116305. /*
  116306. ** PRAGMA soft_heap_limit
  116307. ** PRAGMA soft_heap_limit = N
  116308. **
  116309. ** IMPLEMENTATION-OF: R-26343-45930 This pragma invokes the
  116310. ** sqlite3_soft_heap_limit64() interface with the argument N, if N is
  116311. ** specified and is a non-negative integer.
  116312. ** IMPLEMENTATION-OF: R-64451-07163 The soft_heap_limit pragma always
  116313. ** returns the same integer that would be returned by the
  116314. ** sqlite3_soft_heap_limit64(-1) C-language function.
  116315. */
  116316. case PragTyp_SOFT_HEAP_LIMIT: {
  116317. sqlite3_int64 N;
  116318. if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){
  116319. sqlite3_soft_heap_limit64(N);
  116320. }
  116321. returnSingleInt(v, sqlite3_soft_heap_limit64(-1));
  116322. break;
  116323. }
  116324. /*
  116325. ** PRAGMA threads
  116326. ** PRAGMA threads = N
  116327. **
  116328. ** Configure the maximum number of worker threads. Return the new
  116329. ** maximum, which might be less than requested.
  116330. */
  116331. case PragTyp_THREADS: {
  116332. sqlite3_int64 N;
  116333. if( zRight
  116334. && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK
  116335. && N>=0
  116336. ){
  116337. sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, (int)(N&0x7fffffff));
  116338. }
  116339. returnSingleInt(v, sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, -1));
  116340. break;
  116341. }
  116342. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  116343. /*
  116344. ** Report the current state of file logs for all databases
  116345. */
  116346. case PragTyp_LOCK_STATUS: {
  116347. static const char *const azLockName[] = {
  116348. "unlocked", "shared", "reserved", "pending", "exclusive"
  116349. };
  116350. int i;
  116351. pParse->nMem = 2;
  116352. for(i=0; i<db->nDb; i++){
  116353. Btree *pBt;
  116354. const char *zState = "unknown";
  116355. int j;
  116356. if( db->aDb[i].zDbSName==0 ) continue;
  116357. pBt = db->aDb[i].pBt;
  116358. if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
  116359. zState = "closed";
  116360. }else if( sqlite3_file_control(db, i ? db->aDb[i].zDbSName : 0,
  116361. SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
  116362. zState = azLockName[j];
  116363. }
  116364. sqlite3VdbeMultiLoad(v, 1, "ss", db->aDb[i].zDbSName, zState);
  116365. }
  116366. break;
  116367. }
  116368. #endif
  116369. #ifdef SQLITE_HAS_CODEC
  116370. /* Pragma iArg
  116371. ** ---------- ------
  116372. ** key 0
  116373. ** rekey 1
  116374. ** hexkey 2
  116375. ** hexrekey 3
  116376. ** textkey 4
  116377. ** textrekey 5
  116378. */
  116379. case PragTyp_KEY: {
  116380. if( zRight ){
  116381. char zBuf[40];
  116382. const char *zKey = zRight;
  116383. int n;
  116384. if( pPragma->iArg==2 || pPragma->iArg==3 ){
  116385. u8 iByte;
  116386. int i;
  116387. for(i=0, iByte=0; i<sizeof(zBuf)*2 && sqlite3Isxdigit(zRight[i]); i++){
  116388. iByte = (iByte<<4) + sqlite3HexToInt(zRight[i]);
  116389. if( (i&1)!=0 ) zBuf[i/2] = iByte;
  116390. }
  116391. zKey = zBuf;
  116392. n = i/2;
  116393. }else{
  116394. n = pPragma->iArg<4 ? sqlite3Strlen30(zRight) : -1;
  116395. }
  116396. if( (pPragma->iArg & 1)==0 ){
  116397. rc = sqlite3_key_v2(db, zDb, zKey, n);
  116398. }else{
  116399. rc = sqlite3_rekey_v2(db, zDb, zKey, n);
  116400. }
  116401. if( rc==SQLITE_OK && n!=0 ){
  116402. sqlite3VdbeSetNumCols(v, 1);
  116403. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "ok", SQLITE_STATIC);
  116404. returnSingleText(v, "ok");
  116405. }
  116406. }
  116407. break;
  116408. }
  116409. #endif
  116410. #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
  116411. case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){
  116412. #ifdef SQLITE_HAS_CODEC
  116413. if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
  116414. sqlite3_activate_see(&zRight[4]);
  116415. }
  116416. #endif
  116417. #ifdef SQLITE_ENABLE_CEROD
  116418. if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
  116419. sqlite3_activate_cerod(&zRight[6]);
  116420. }
  116421. #endif
  116422. }
  116423. break;
  116424. #endif
  116425. } /* End of the PRAGMA switch */
  116426. /* The following block is a no-op unless SQLITE_DEBUG is defined. Its only
  116427. ** purpose is to execute assert() statements to verify that if the
  116428. ** PragFlg_NoColumns1 flag is set and the caller specified an argument
  116429. ** to the PRAGMA, the implementation has not added any OP_ResultRow
  116430. ** instructions to the VM. */
  116431. if( (pPragma->mPragFlg & PragFlg_NoColumns1) && zRight ){
  116432. sqlite3VdbeVerifyNoResultRow(v);
  116433. }
  116434. pragma_out:
  116435. sqlite3DbFree(db, zLeft);
  116436. sqlite3DbFree(db, zRight);
  116437. }
  116438. #ifndef SQLITE_OMIT_VIRTUALTABLE
  116439. /*****************************************************************************
  116440. ** Implementation of an eponymous virtual table that runs a pragma.
  116441. **
  116442. */
  116443. typedef struct PragmaVtab PragmaVtab;
  116444. typedef struct PragmaVtabCursor PragmaVtabCursor;
  116445. struct PragmaVtab {
  116446. sqlite3_vtab base; /* Base class. Must be first */
  116447. sqlite3 *db; /* The database connection to which it belongs */
  116448. const PragmaName *pName; /* Name of the pragma */
  116449. u8 nHidden; /* Number of hidden columns */
  116450. u8 iHidden; /* Index of the first hidden column */
  116451. };
  116452. struct PragmaVtabCursor {
  116453. sqlite3_vtab_cursor base; /* Base class. Must be first */
  116454. sqlite3_stmt *pPragma; /* The pragma statement to run */
  116455. sqlite_int64 iRowid; /* Current rowid */
  116456. char *azArg[2]; /* Value of the argument and schema */
  116457. };
  116458. /*
  116459. ** Pragma virtual table module xConnect method.
  116460. */
  116461. static int pragmaVtabConnect(
  116462. sqlite3 *db,
  116463. void *pAux,
  116464. int argc, const char *const*argv,
  116465. sqlite3_vtab **ppVtab,
  116466. char **pzErr
  116467. ){
  116468. const PragmaName *pPragma = (const PragmaName*)pAux;
  116469. PragmaVtab *pTab = 0;
  116470. int rc;
  116471. int i, j;
  116472. char cSep = '(';
  116473. StrAccum acc;
  116474. char zBuf[200];
  116475. UNUSED_PARAMETER(argc);
  116476. UNUSED_PARAMETER(argv);
  116477. sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
  116478. sqlite3_str_appendall(&acc, "CREATE TABLE x");
  116479. for(i=0, j=pPragma->iPragCName; i<pPragma->nPragCName; i++, j++){
  116480. sqlite3_str_appendf(&acc, "%c\"%s\"", cSep, pragCName[j]);
  116481. cSep = ',';
  116482. }
  116483. if( i==0 ){
  116484. sqlite3_str_appendf(&acc, "(\"%s\"", pPragma->zName);
  116485. i++;
  116486. }
  116487. j = 0;
  116488. if( pPragma->mPragFlg & PragFlg_Result1 ){
  116489. sqlite3_str_appendall(&acc, ",arg HIDDEN");
  116490. j++;
  116491. }
  116492. if( pPragma->mPragFlg & (PragFlg_SchemaOpt|PragFlg_SchemaReq) ){
  116493. sqlite3_str_appendall(&acc, ",schema HIDDEN");
  116494. j++;
  116495. }
  116496. sqlite3_str_append(&acc, ")", 1);
  116497. sqlite3StrAccumFinish(&acc);
  116498. assert( strlen(zBuf) < sizeof(zBuf)-1 );
  116499. rc = sqlite3_declare_vtab(db, zBuf);
  116500. if( rc==SQLITE_OK ){
  116501. pTab = (PragmaVtab*)sqlite3_malloc(sizeof(PragmaVtab));
  116502. if( pTab==0 ){
  116503. rc = SQLITE_NOMEM;
  116504. }else{
  116505. memset(pTab, 0, sizeof(PragmaVtab));
  116506. pTab->pName = pPragma;
  116507. pTab->db = db;
  116508. pTab->iHidden = i;
  116509. pTab->nHidden = j;
  116510. }
  116511. }else{
  116512. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  116513. }
  116514. *ppVtab = (sqlite3_vtab*)pTab;
  116515. return rc;
  116516. }
  116517. /*
  116518. ** Pragma virtual table module xDisconnect method.
  116519. */
  116520. static int pragmaVtabDisconnect(sqlite3_vtab *pVtab){
  116521. PragmaVtab *pTab = (PragmaVtab*)pVtab;
  116522. sqlite3_free(pTab);
  116523. return SQLITE_OK;
  116524. }
  116525. /* Figure out the best index to use to search a pragma virtual table.
  116526. **
  116527. ** There are not really any index choices. But we want to encourage the
  116528. ** query planner to give == constraints on as many hidden parameters as
  116529. ** possible, and especially on the first hidden parameter. So return a
  116530. ** high cost if hidden parameters are unconstrained.
  116531. */
  116532. static int pragmaVtabBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  116533. PragmaVtab *pTab = (PragmaVtab*)tab;
  116534. const struct sqlite3_index_constraint *pConstraint;
  116535. int i, j;
  116536. int seen[2];
  116537. pIdxInfo->estimatedCost = (double)1;
  116538. if( pTab->nHidden==0 ){ return SQLITE_OK; }
  116539. pConstraint = pIdxInfo->aConstraint;
  116540. seen[0] = 0;
  116541. seen[1] = 0;
  116542. for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
  116543. if( pConstraint->usable==0 ) continue;
  116544. if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
  116545. if( pConstraint->iColumn < pTab->iHidden ) continue;
  116546. j = pConstraint->iColumn - pTab->iHidden;
  116547. assert( j < 2 );
  116548. seen[j] = i+1;
  116549. }
  116550. if( seen[0]==0 ){
  116551. pIdxInfo->estimatedCost = (double)2147483647;
  116552. pIdxInfo->estimatedRows = 2147483647;
  116553. return SQLITE_OK;
  116554. }
  116555. j = seen[0]-1;
  116556. pIdxInfo->aConstraintUsage[j].argvIndex = 1;
  116557. pIdxInfo->aConstraintUsage[j].omit = 1;
  116558. if( seen[1]==0 ) return SQLITE_OK;
  116559. pIdxInfo->estimatedCost = (double)20;
  116560. pIdxInfo->estimatedRows = 20;
  116561. j = seen[1]-1;
  116562. pIdxInfo->aConstraintUsage[j].argvIndex = 2;
  116563. pIdxInfo->aConstraintUsage[j].omit = 1;
  116564. return SQLITE_OK;
  116565. }
  116566. /* Create a new cursor for the pragma virtual table */
  116567. static int pragmaVtabOpen(sqlite3_vtab *pVtab, sqlite3_vtab_cursor **ppCursor){
  116568. PragmaVtabCursor *pCsr;
  116569. pCsr = (PragmaVtabCursor*)sqlite3_malloc(sizeof(*pCsr));
  116570. if( pCsr==0 ) return SQLITE_NOMEM;
  116571. memset(pCsr, 0, sizeof(PragmaVtabCursor));
  116572. pCsr->base.pVtab = pVtab;
  116573. *ppCursor = &pCsr->base;
  116574. return SQLITE_OK;
  116575. }
  116576. /* Clear all content from pragma virtual table cursor. */
  116577. static void pragmaVtabCursorClear(PragmaVtabCursor *pCsr){
  116578. int i;
  116579. sqlite3_finalize(pCsr->pPragma);
  116580. pCsr->pPragma = 0;
  116581. for(i=0; i<ArraySize(pCsr->azArg); i++){
  116582. sqlite3_free(pCsr->azArg[i]);
  116583. pCsr->azArg[i] = 0;
  116584. }
  116585. }
  116586. /* Close a pragma virtual table cursor */
  116587. static int pragmaVtabClose(sqlite3_vtab_cursor *cur){
  116588. PragmaVtabCursor *pCsr = (PragmaVtabCursor*)cur;
  116589. pragmaVtabCursorClear(pCsr);
  116590. sqlite3_free(pCsr);
  116591. return SQLITE_OK;
  116592. }
  116593. /* Advance the pragma virtual table cursor to the next row */
  116594. static int pragmaVtabNext(sqlite3_vtab_cursor *pVtabCursor){
  116595. PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
  116596. int rc = SQLITE_OK;
  116597. /* Increment the xRowid value */
  116598. pCsr->iRowid++;
  116599. assert( pCsr->pPragma );
  116600. if( SQLITE_ROW!=sqlite3_step(pCsr->pPragma) ){
  116601. rc = sqlite3_finalize(pCsr->pPragma);
  116602. pCsr->pPragma = 0;
  116603. pragmaVtabCursorClear(pCsr);
  116604. }
  116605. return rc;
  116606. }
  116607. /*
  116608. ** Pragma virtual table module xFilter method.
  116609. */
  116610. static int pragmaVtabFilter(
  116611. sqlite3_vtab_cursor *pVtabCursor,
  116612. int idxNum, const char *idxStr,
  116613. int argc, sqlite3_value **argv
  116614. ){
  116615. PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
  116616. PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);
  116617. int rc;
  116618. int i, j;
  116619. StrAccum acc;
  116620. char *zSql;
  116621. UNUSED_PARAMETER(idxNum);
  116622. UNUSED_PARAMETER(idxStr);
  116623. pragmaVtabCursorClear(pCsr);
  116624. j = (pTab->pName->mPragFlg & PragFlg_Result1)!=0 ? 0 : 1;
  116625. for(i=0; i<argc; i++, j++){
  116626. const char *zText = (const char*)sqlite3_value_text(argv[i]);
  116627. assert( j<ArraySize(pCsr->azArg) );
  116628. assert( pCsr->azArg[j]==0 );
  116629. if( zText ){
  116630. pCsr->azArg[j] = sqlite3_mprintf("%s", zText);
  116631. if( pCsr->azArg[j]==0 ){
  116632. return SQLITE_NOMEM;
  116633. }
  116634. }
  116635. }
  116636. sqlite3StrAccumInit(&acc, 0, 0, 0, pTab->db->aLimit[SQLITE_LIMIT_SQL_LENGTH]);
  116637. sqlite3_str_appendall(&acc, "PRAGMA ");
  116638. if( pCsr->azArg[1] ){
  116639. sqlite3_str_appendf(&acc, "%Q.", pCsr->azArg[1]);
  116640. }
  116641. sqlite3_str_appendall(&acc, pTab->pName->zName);
  116642. if( pCsr->azArg[0] ){
  116643. sqlite3_str_appendf(&acc, "=%Q", pCsr->azArg[0]);
  116644. }
  116645. zSql = sqlite3StrAccumFinish(&acc);
  116646. if( zSql==0 ) return SQLITE_NOMEM;
  116647. rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pPragma, 0);
  116648. sqlite3_free(zSql);
  116649. if( rc!=SQLITE_OK ){
  116650. pTab->base.zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pTab->db));
  116651. return rc;
  116652. }
  116653. return pragmaVtabNext(pVtabCursor);
  116654. }
  116655. /*
  116656. ** Pragma virtual table module xEof method.
  116657. */
  116658. static int pragmaVtabEof(sqlite3_vtab_cursor *pVtabCursor){
  116659. PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
  116660. return (pCsr->pPragma==0);
  116661. }
  116662. /* The xColumn method simply returns the corresponding column from
  116663. ** the PRAGMA.
  116664. */
  116665. static int pragmaVtabColumn(
  116666. sqlite3_vtab_cursor *pVtabCursor,
  116667. sqlite3_context *ctx,
  116668. int i
  116669. ){
  116670. PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
  116671. PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);
  116672. if( i<pTab->iHidden ){
  116673. sqlite3_result_value(ctx, sqlite3_column_value(pCsr->pPragma, i));
  116674. }else{
  116675. sqlite3_result_text(ctx, pCsr->azArg[i-pTab->iHidden],-1,SQLITE_TRANSIENT);
  116676. }
  116677. return SQLITE_OK;
  116678. }
  116679. /*
  116680. ** Pragma virtual table module xRowid method.
  116681. */
  116682. static int pragmaVtabRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *p){
  116683. PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
  116684. *p = pCsr->iRowid;
  116685. return SQLITE_OK;
  116686. }
  116687. /* The pragma virtual table object */
  116688. static const sqlite3_module pragmaVtabModule = {
  116689. 0, /* iVersion */
  116690. 0, /* xCreate - create a table */
  116691. pragmaVtabConnect, /* xConnect - connect to an existing table */
  116692. pragmaVtabBestIndex, /* xBestIndex - Determine search strategy */
  116693. pragmaVtabDisconnect, /* xDisconnect - Disconnect from a table */
  116694. 0, /* xDestroy - Drop a table */
  116695. pragmaVtabOpen, /* xOpen - open a cursor */
  116696. pragmaVtabClose, /* xClose - close a cursor */
  116697. pragmaVtabFilter, /* xFilter - configure scan constraints */
  116698. pragmaVtabNext, /* xNext - advance a cursor */
  116699. pragmaVtabEof, /* xEof */
  116700. pragmaVtabColumn, /* xColumn - read data */
  116701. pragmaVtabRowid, /* xRowid - read data */
  116702. 0, /* xUpdate - write data */
  116703. 0, /* xBegin - begin transaction */
  116704. 0, /* xSync - sync transaction */
  116705. 0, /* xCommit - commit transaction */
  116706. 0, /* xRollback - rollback transaction */
  116707. 0, /* xFindFunction - function overloading */
  116708. 0, /* xRename - rename the table */
  116709. 0, /* xSavepoint */
  116710. 0, /* xRelease */
  116711. 0, /* xRollbackTo */
  116712. 0 /* xShadowName */
  116713. };
  116714. /*
  116715. ** Check to see if zTabName is really the name of a pragma. If it is,
  116716. ** then register an eponymous virtual table for that pragma and return
  116717. ** a pointer to the Module object for the new virtual table.
  116718. */
  116719. SQLITE_PRIVATE Module *sqlite3PragmaVtabRegister(sqlite3 *db, const char *zName){
  116720. const PragmaName *pName;
  116721. assert( sqlite3_strnicmp(zName, "pragma_", 7)==0 );
  116722. pName = pragmaLocate(zName+7);
  116723. if( pName==0 ) return 0;
  116724. if( (pName->mPragFlg & (PragFlg_Result0|PragFlg_Result1))==0 ) return 0;
  116725. assert( sqlite3HashFind(&db->aModule, zName)==0 );
  116726. return sqlite3VtabCreateModule(db, zName, &pragmaVtabModule, (void*)pName, 0);
  116727. }
  116728. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  116729. #endif /* SQLITE_OMIT_PRAGMA */
  116730. /************** End of pragma.c **********************************************/
  116731. /************** Begin file prepare.c *****************************************/
  116732. /*
  116733. ** 2005 May 25
  116734. **
  116735. ** The author disclaims copyright to this source code. In place of
  116736. ** a legal notice, here is a blessing:
  116737. **
  116738. ** May you do good and not evil.
  116739. ** May you find forgiveness for yourself and forgive others.
  116740. ** May you share freely, never taking more than you give.
  116741. **
  116742. *************************************************************************
  116743. ** This file contains the implementation of the sqlite3_prepare()
  116744. ** interface, and routines that contribute to loading the database schema
  116745. ** from disk.
  116746. */
  116747. /* #include "sqliteInt.h" */
  116748. /*
  116749. ** Fill the InitData structure with an error message that indicates
  116750. ** that the database is corrupt.
  116751. */
  116752. static void corruptSchema(
  116753. InitData *pData, /* Initialization context */
  116754. const char *zObj, /* Object being parsed at the point of error */
  116755. const char *zExtra /* Error information */
  116756. ){
  116757. sqlite3 *db = pData->db;
  116758. if( db->mallocFailed ){
  116759. pData->rc = SQLITE_NOMEM_BKPT;
  116760. }else if( pData->pzErrMsg[0]!=0 ){
  116761. /* A error message has already been generated. Do not overwrite it */
  116762. }else if( pData->mInitFlags & INITFLAG_AlterTable ){
  116763. *pData->pzErrMsg = sqlite3DbStrDup(db, zExtra);
  116764. pData->rc = SQLITE_ERROR;
  116765. }else if( db->flags & SQLITE_WriteSchema ){
  116766. pData->rc = SQLITE_CORRUPT_BKPT;
  116767. }else{
  116768. char *z;
  116769. if( zObj==0 ) zObj = "?";
  116770. z = sqlite3MPrintf(db, "malformed database schema (%s)", zObj);
  116771. if( zExtra && zExtra[0] ) z = sqlite3MPrintf(db, "%z - %s", z, zExtra);
  116772. *pData->pzErrMsg = z;
  116773. pData->rc = SQLITE_CORRUPT_BKPT;
  116774. }
  116775. }
  116776. /*
  116777. ** Check to see if any sibling index (another index on the same table)
  116778. ** of pIndex has the same root page number, and if it does, return true.
  116779. ** This would indicate a corrupt schema.
  116780. */
  116781. SQLITE_PRIVATE int sqlite3IndexHasDuplicateRootPage(Index *pIndex){
  116782. Index *p;
  116783. for(p=pIndex->pTable->pIndex; p; p=p->pNext){
  116784. if( p->tnum==pIndex->tnum && p!=pIndex ) return 1;
  116785. }
  116786. return 0;
  116787. }
  116788. /*
  116789. ** This is the callback routine for the code that initializes the
  116790. ** database. See sqlite3Init() below for additional information.
  116791. ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
  116792. **
  116793. ** Each callback contains the following information:
  116794. **
  116795. ** argv[0] = name of thing being created
  116796. ** argv[1] = root page number for table or index. 0 for trigger or view.
  116797. ** argv[2] = SQL text for the CREATE statement.
  116798. **
  116799. */
  116800. SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
  116801. InitData *pData = (InitData*)pInit;
  116802. sqlite3 *db = pData->db;
  116803. int iDb = pData->iDb;
  116804. assert( argc==3 );
  116805. UNUSED_PARAMETER2(NotUsed, argc);
  116806. assert( sqlite3_mutex_held(db->mutex) );
  116807. DbClearProperty(db, iDb, DB_Empty);
  116808. pData->nInitRow++;
  116809. if( db->mallocFailed ){
  116810. corruptSchema(pData, argv[0], 0);
  116811. return 1;
  116812. }
  116813. assert( iDb>=0 && iDb<db->nDb );
  116814. if( argv==0 ) return 0; /* Might happen if EMPTY_RESULT_CALLBACKS are on */
  116815. if( argv[1]==0 ){
  116816. corruptSchema(pData, argv[0], 0);
  116817. }else if( sqlite3_strnicmp(argv[2],"create ",7)==0 ){
  116818. /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
  116819. ** But because db->init.busy is set to 1, no VDBE code is generated
  116820. ** or executed. All the parser does is build the internal data
  116821. ** structures that describe the table, index, or view.
  116822. */
  116823. int rc;
  116824. u8 saved_iDb = db->init.iDb;
  116825. sqlite3_stmt *pStmt;
  116826. TESTONLY(int rcp); /* Return code from sqlite3_prepare() */
  116827. assert( db->init.busy );
  116828. db->init.iDb = iDb;
  116829. db->init.newTnum = sqlite3Atoi(argv[1]);
  116830. db->init.orphanTrigger = 0;
  116831. TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
  116832. rc = db->errCode;
  116833. assert( (rc&0xFF)==(rcp&0xFF) );
  116834. db->init.iDb = saved_iDb;
  116835. /* assert( saved_iDb==0 || (db->mDbFlags & DBFLAG_Vacuum)!=0 ); */
  116836. if( SQLITE_OK!=rc ){
  116837. if( db->init.orphanTrigger ){
  116838. assert( iDb==1 );
  116839. }else{
  116840. pData->rc = rc;
  116841. if( rc==SQLITE_NOMEM ){
  116842. sqlite3OomFault(db);
  116843. }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
  116844. corruptSchema(pData, argv[0], sqlite3_errmsg(db));
  116845. }
  116846. }
  116847. }
  116848. sqlite3_finalize(pStmt);
  116849. }else if( argv[0]==0 || (argv[2]!=0 && argv[2][0]!=0) ){
  116850. corruptSchema(pData, argv[0], 0);
  116851. }else{
  116852. /* If the SQL column is blank it means this is an index that
  116853. ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
  116854. ** constraint for a CREATE TABLE. The index should have already
  116855. ** been created when we processed the CREATE TABLE. All we have
  116856. ** to do here is record the root page number for that index.
  116857. */
  116858. Index *pIndex;
  116859. pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zDbSName);
  116860. if( pIndex==0
  116861. || sqlite3GetInt32(argv[1],&pIndex->tnum)==0
  116862. || pIndex->tnum<2
  116863. || sqlite3IndexHasDuplicateRootPage(pIndex)
  116864. ){
  116865. corruptSchema(pData, argv[0], pIndex?"invalid rootpage":"orphan index");
  116866. }
  116867. }
  116868. return 0;
  116869. }
  116870. /*
  116871. ** Attempt to read the database schema and initialize internal
  116872. ** data structures for a single database file. The index of the
  116873. ** database file is given by iDb. iDb==0 is used for the main
  116874. ** database. iDb==1 should never be used. iDb>=2 is used for
  116875. ** auxiliary databases. Return one of the SQLITE_ error codes to
  116876. ** indicate success or failure.
  116877. */
  116878. SQLITE_PRIVATE int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg, u32 mFlags){
  116879. int rc;
  116880. int i;
  116881. #ifndef SQLITE_OMIT_DEPRECATED
  116882. int size;
  116883. #endif
  116884. Db *pDb;
  116885. char const *azArg[4];
  116886. int meta[5];
  116887. InitData initData;
  116888. const char *zMasterName;
  116889. int openedTransaction = 0;
  116890. assert( (db->mDbFlags & DBFLAG_SchemaKnownOk)==0 );
  116891. assert( iDb>=0 && iDb<db->nDb );
  116892. assert( db->aDb[iDb].pSchema );
  116893. assert( sqlite3_mutex_held(db->mutex) );
  116894. assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
  116895. db->init.busy = 1;
  116896. /* Construct the in-memory representation schema tables (sqlite_master or
  116897. ** sqlite_temp_master) by invoking the parser directly. The appropriate
  116898. ** table name will be inserted automatically by the parser so we can just
  116899. ** use the abbreviation "x" here. The parser will also automatically tag
  116900. ** the schema table as read-only. */
  116901. azArg[0] = zMasterName = SCHEMA_TABLE(iDb);
  116902. azArg[1] = "1";
  116903. azArg[2] = "CREATE TABLE x(type text,name text,tbl_name text,"
  116904. "rootpage int,sql text)";
  116905. azArg[3] = 0;
  116906. initData.db = db;
  116907. initData.iDb = iDb;
  116908. initData.rc = SQLITE_OK;
  116909. initData.pzErrMsg = pzErrMsg;
  116910. initData.mInitFlags = mFlags;
  116911. initData.nInitRow = 0;
  116912. sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
  116913. if( initData.rc ){
  116914. rc = initData.rc;
  116915. goto error_out;
  116916. }
  116917. /* Create a cursor to hold the database open
  116918. */
  116919. pDb = &db->aDb[iDb];
  116920. if( pDb->pBt==0 ){
  116921. assert( iDb==1 );
  116922. DbSetProperty(db, 1, DB_SchemaLoaded);
  116923. rc = SQLITE_OK;
  116924. goto error_out;
  116925. }
  116926. /* If there is not already a read-only (or read-write) transaction opened
  116927. ** on the b-tree database, open one now. If a transaction is opened, it
  116928. ** will be closed before this function returns. */
  116929. sqlite3BtreeEnter(pDb->pBt);
  116930. if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
  116931. rc = sqlite3BtreeBeginTrans(pDb->pBt, 0, 0);
  116932. if( rc!=SQLITE_OK ){
  116933. sqlite3SetString(pzErrMsg, db, sqlite3ErrStr(rc));
  116934. goto initone_error_out;
  116935. }
  116936. openedTransaction = 1;
  116937. }
  116938. /* Get the database meta information.
  116939. **
  116940. ** Meta values are as follows:
  116941. ** meta[0] Schema cookie. Changes with each schema change.
  116942. ** meta[1] File format of schema layer.
  116943. ** meta[2] Size of the page cache.
  116944. ** meta[3] Largest rootpage (auto/incr_vacuum mode)
  116945. ** meta[4] Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
  116946. ** meta[5] User version
  116947. ** meta[6] Incremental vacuum mode
  116948. ** meta[7] unused
  116949. ** meta[8] unused
  116950. ** meta[9] unused
  116951. **
  116952. ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
  116953. ** the possible values of meta[4].
  116954. */
  116955. for(i=0; i<ArraySize(meta); i++){
  116956. sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
  116957. }
  116958. if( (db->flags & SQLITE_ResetDatabase)!=0 ){
  116959. memset(meta, 0, sizeof(meta));
  116960. }
  116961. pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
  116962. /* If opening a non-empty database, check the text encoding. For the
  116963. ** main database, set sqlite3.enc to the encoding of the main database.
  116964. ** For an attached db, it is an error if the encoding is not the same
  116965. ** as sqlite3.enc.
  116966. */
  116967. if( meta[BTREE_TEXT_ENCODING-1] ){ /* text encoding */
  116968. if( iDb==0 ){
  116969. #ifndef SQLITE_OMIT_UTF16
  116970. u8 encoding;
  116971. /* If opening the main database, set ENC(db). */
  116972. encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
  116973. if( encoding==0 ) encoding = SQLITE_UTF8;
  116974. ENC(db) = encoding;
  116975. #else
  116976. ENC(db) = SQLITE_UTF8;
  116977. #endif
  116978. }else{
  116979. /* If opening an attached database, the encoding much match ENC(db) */
  116980. if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
  116981. sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
  116982. " text encoding as main database");
  116983. rc = SQLITE_ERROR;
  116984. goto initone_error_out;
  116985. }
  116986. }
  116987. }else{
  116988. DbSetProperty(db, iDb, DB_Empty);
  116989. }
  116990. pDb->pSchema->enc = ENC(db);
  116991. if( pDb->pSchema->cache_size==0 ){
  116992. #ifndef SQLITE_OMIT_DEPRECATED
  116993. size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
  116994. if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
  116995. pDb->pSchema->cache_size = size;
  116996. #else
  116997. pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
  116998. #endif
  116999. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  117000. }
  117001. /*
  117002. ** file_format==1 Version 3.0.0.
  117003. ** file_format==2 Version 3.1.3. // ALTER TABLE ADD COLUMN
  117004. ** file_format==3 Version 3.1.4. // ditto but with non-NULL defaults
  117005. ** file_format==4 Version 3.3.0. // DESC indices. Boolean constants
  117006. */
  117007. pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
  117008. if( pDb->pSchema->file_format==0 ){
  117009. pDb->pSchema->file_format = 1;
  117010. }
  117011. if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
  117012. sqlite3SetString(pzErrMsg, db, "unsupported file format");
  117013. rc = SQLITE_ERROR;
  117014. goto initone_error_out;
  117015. }
  117016. /* Ticket #2804: When we open a database in the newer file format,
  117017. ** clear the legacy_file_format pragma flag so that a VACUUM will
  117018. ** not downgrade the database and thus invalidate any descending
  117019. ** indices that the user might have created.
  117020. */
  117021. if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
  117022. db->flags &= ~(u64)SQLITE_LegacyFileFmt;
  117023. }
  117024. /* Read the schema information out of the schema tables
  117025. */
  117026. assert( db->init.busy );
  117027. {
  117028. char *zSql;
  117029. zSql = sqlite3MPrintf(db,
  117030. "SELECT name, rootpage, sql FROM \"%w\".%s ORDER BY rowid",
  117031. db->aDb[iDb].zDbSName, zMasterName);
  117032. #ifndef SQLITE_OMIT_AUTHORIZATION
  117033. {
  117034. sqlite3_xauth xAuth;
  117035. xAuth = db->xAuth;
  117036. db->xAuth = 0;
  117037. #endif
  117038. rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
  117039. #ifndef SQLITE_OMIT_AUTHORIZATION
  117040. db->xAuth = xAuth;
  117041. }
  117042. #endif
  117043. if( rc==SQLITE_OK ) rc = initData.rc;
  117044. sqlite3DbFree(db, zSql);
  117045. #ifndef SQLITE_OMIT_ANALYZE
  117046. if( rc==SQLITE_OK ){
  117047. sqlite3AnalysisLoad(db, iDb);
  117048. }
  117049. #endif
  117050. }
  117051. if( db->mallocFailed ){
  117052. rc = SQLITE_NOMEM_BKPT;
  117053. sqlite3ResetAllSchemasOfConnection(db);
  117054. }
  117055. if( rc==SQLITE_OK || (db->flags&SQLITE_NoSchemaError)){
  117056. /* Black magic: If the SQLITE_NoSchemaError flag is set, then consider
  117057. ** the schema loaded, even if errors occurred. In this situation the
  117058. ** current sqlite3_prepare() operation will fail, but the following one
  117059. ** will attempt to compile the supplied statement against whatever subset
  117060. ** of the schema was loaded before the error occurred. The primary
  117061. ** purpose of this is to allow access to the sqlite_master table
  117062. ** even when its contents have been corrupted.
  117063. */
  117064. DbSetProperty(db, iDb, DB_SchemaLoaded);
  117065. rc = SQLITE_OK;
  117066. }
  117067. /* Jump here for an error that occurs after successfully allocating
  117068. ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
  117069. ** before that point, jump to error_out.
  117070. */
  117071. initone_error_out:
  117072. if( openedTransaction ){
  117073. sqlite3BtreeCommit(pDb->pBt);
  117074. }
  117075. sqlite3BtreeLeave(pDb->pBt);
  117076. error_out:
  117077. if( rc ){
  117078. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  117079. sqlite3OomFault(db);
  117080. }
  117081. sqlite3ResetOneSchema(db, iDb);
  117082. }
  117083. db->init.busy = 0;
  117084. return rc;
  117085. }
  117086. /*
  117087. ** Initialize all database files - the main database file, the file
  117088. ** used to store temporary tables, and any additional database files
  117089. ** created using ATTACH statements. Return a success code. If an
  117090. ** error occurs, write an error message into *pzErrMsg.
  117091. **
  117092. ** After a database is initialized, the DB_SchemaLoaded bit is set
  117093. ** bit is set in the flags field of the Db structure. If the database
  117094. ** file was of zero-length, then the DB_Empty flag is also set.
  117095. */
  117096. SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
  117097. int i, rc;
  117098. int commit_internal = !(db->mDbFlags&DBFLAG_SchemaChange);
  117099. assert( sqlite3_mutex_held(db->mutex) );
  117100. assert( sqlite3BtreeHoldsMutex(db->aDb[0].pBt) );
  117101. assert( db->init.busy==0 );
  117102. ENC(db) = SCHEMA_ENC(db);
  117103. assert( db->nDb>0 );
  117104. /* Do the main schema first */
  117105. if( !DbHasProperty(db, 0, DB_SchemaLoaded) ){
  117106. rc = sqlite3InitOne(db, 0, pzErrMsg, 0);
  117107. if( rc ) return rc;
  117108. }
  117109. /* All other schemas after the main schema. The "temp" schema must be last */
  117110. for(i=db->nDb-1; i>0; i--){
  117111. assert( i==1 || sqlite3BtreeHoldsMutex(db->aDb[i].pBt) );
  117112. if( !DbHasProperty(db, i, DB_SchemaLoaded) ){
  117113. rc = sqlite3InitOne(db, i, pzErrMsg, 0);
  117114. if( rc ) return rc;
  117115. }
  117116. }
  117117. if( commit_internal ){
  117118. sqlite3CommitInternalChanges(db);
  117119. }
  117120. return SQLITE_OK;
  117121. }
  117122. /*
  117123. ** This routine is a no-op if the database schema is already initialized.
  117124. ** Otherwise, the schema is loaded. An error code is returned.
  117125. */
  117126. SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
  117127. int rc = SQLITE_OK;
  117128. sqlite3 *db = pParse->db;
  117129. assert( sqlite3_mutex_held(db->mutex) );
  117130. if( !db->init.busy ){
  117131. rc = sqlite3Init(db, &pParse->zErrMsg);
  117132. if( rc!=SQLITE_OK ){
  117133. pParse->rc = rc;
  117134. pParse->nErr++;
  117135. }else if( db->noSharedCache ){
  117136. db->mDbFlags |= DBFLAG_SchemaKnownOk;
  117137. }
  117138. }
  117139. return rc;
  117140. }
  117141. /*
  117142. ** Check schema cookies in all databases. If any cookie is out
  117143. ** of date set pParse->rc to SQLITE_SCHEMA. If all schema cookies
  117144. ** make no changes to pParse->rc.
  117145. */
  117146. static void schemaIsValid(Parse *pParse){
  117147. sqlite3 *db = pParse->db;
  117148. int iDb;
  117149. int rc;
  117150. int cookie;
  117151. assert( pParse->checkSchema );
  117152. assert( sqlite3_mutex_held(db->mutex) );
  117153. for(iDb=0; iDb<db->nDb; iDb++){
  117154. int openedTransaction = 0; /* True if a transaction is opened */
  117155. Btree *pBt = db->aDb[iDb].pBt; /* Btree database to read cookie from */
  117156. if( pBt==0 ) continue;
  117157. /* If there is not already a read-only (or read-write) transaction opened
  117158. ** on the b-tree database, open one now. If a transaction is opened, it
  117159. ** will be closed immediately after reading the meta-value. */
  117160. if( !sqlite3BtreeIsInReadTrans(pBt) ){
  117161. rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
  117162. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  117163. sqlite3OomFault(db);
  117164. }
  117165. if( rc!=SQLITE_OK ) return;
  117166. openedTransaction = 1;
  117167. }
  117168. /* Read the schema cookie from the database. If it does not match the
  117169. ** value stored as part of the in-memory schema representation,
  117170. ** set Parse.rc to SQLITE_SCHEMA. */
  117171. sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
  117172. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  117173. if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
  117174. sqlite3ResetOneSchema(db, iDb);
  117175. pParse->rc = SQLITE_SCHEMA;
  117176. }
  117177. /* Close the transaction, if one was opened. */
  117178. if( openedTransaction ){
  117179. sqlite3BtreeCommit(pBt);
  117180. }
  117181. }
  117182. }
  117183. /*
  117184. ** Convert a schema pointer into the iDb index that indicates
  117185. ** which database file in db->aDb[] the schema refers to.
  117186. **
  117187. ** If the same database is attached more than once, the first
  117188. ** attached database is returned.
  117189. */
  117190. SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
  117191. int i = -1000000;
  117192. /* If pSchema is NULL, then return -1000000. This happens when code in
  117193. ** expr.c is trying to resolve a reference to a transient table (i.e. one
  117194. ** created by a sub-select). In this case the return value of this
  117195. ** function should never be used.
  117196. **
  117197. ** We return -1000000 instead of the more usual -1 simply because using
  117198. ** -1000000 as the incorrect index into db->aDb[] is much
  117199. ** more likely to cause a segfault than -1 (of course there are assert()
  117200. ** statements too, but it never hurts to play the odds).
  117201. */
  117202. assert( sqlite3_mutex_held(db->mutex) );
  117203. if( pSchema ){
  117204. for(i=0; 1; i++){
  117205. assert( i<db->nDb );
  117206. if( db->aDb[i].pSchema==pSchema ){
  117207. break;
  117208. }
  117209. }
  117210. assert( i>=0 && i<db->nDb );
  117211. }
  117212. return i;
  117213. }
  117214. /*
  117215. ** Free all memory allocations in the pParse object
  117216. */
  117217. SQLITE_PRIVATE void sqlite3ParserReset(Parse *pParse){
  117218. sqlite3 *db = pParse->db;
  117219. sqlite3DbFree(db, pParse->aLabel);
  117220. sqlite3ExprListDelete(db, pParse->pConstExpr);
  117221. if( db ){
  117222. assert( db->lookaside.bDisable >= pParse->disableLookaside );
  117223. db->lookaside.bDisable -= pParse->disableLookaside;
  117224. }
  117225. pParse->disableLookaside = 0;
  117226. }
  117227. /*
  117228. ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
  117229. */
  117230. static int sqlite3Prepare(
  117231. sqlite3 *db, /* Database handle. */
  117232. const char *zSql, /* UTF-8 encoded SQL statement. */
  117233. int nBytes, /* Length of zSql in bytes. */
  117234. u32 prepFlags, /* Zero or more SQLITE_PREPARE_* flags */
  117235. Vdbe *pReprepare, /* VM being reprepared */
  117236. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  117237. const char **pzTail /* OUT: End of parsed string */
  117238. ){
  117239. char *zErrMsg = 0; /* Error message */
  117240. int rc = SQLITE_OK; /* Result code */
  117241. int i; /* Loop counter */
  117242. Parse sParse; /* Parsing context */
  117243. memset(&sParse, 0, PARSE_HDR_SZ);
  117244. memset(PARSE_TAIL(&sParse), 0, PARSE_TAIL_SZ);
  117245. sParse.pReprepare = pReprepare;
  117246. assert( ppStmt && *ppStmt==0 );
  117247. /* assert( !db->mallocFailed ); // not true with SQLITE_USE_ALLOCA */
  117248. assert( sqlite3_mutex_held(db->mutex) );
  117249. /* For a long-term use prepared statement avoid the use of
  117250. ** lookaside memory.
  117251. */
  117252. if( prepFlags & SQLITE_PREPARE_PERSISTENT ){
  117253. sParse.disableLookaside++;
  117254. db->lookaside.bDisable++;
  117255. }
  117256. sParse.disableVtab = (prepFlags & SQLITE_PREPARE_NO_VTAB)!=0;
  117257. /* Check to verify that it is possible to get a read lock on all
  117258. ** database schemas. The inability to get a read lock indicates that
  117259. ** some other database connection is holding a write-lock, which in
  117260. ** turn means that the other connection has made uncommitted changes
  117261. ** to the schema.
  117262. **
  117263. ** Were we to proceed and prepare the statement against the uncommitted
  117264. ** schema changes and if those schema changes are subsequently rolled
  117265. ** back and different changes are made in their place, then when this
  117266. ** prepared statement goes to run the schema cookie would fail to detect
  117267. ** the schema change. Disaster would follow.
  117268. **
  117269. ** This thread is currently holding mutexes on all Btrees (because
  117270. ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
  117271. ** is not possible for another thread to start a new schema change
  117272. ** while this routine is running. Hence, we do not need to hold
  117273. ** locks on the schema, we just need to make sure nobody else is
  117274. ** holding them.
  117275. **
  117276. ** Note that setting READ_UNCOMMITTED overrides most lock detection,
  117277. ** but it does *not* override schema lock detection, so this all still
  117278. ** works even if READ_UNCOMMITTED is set.
  117279. */
  117280. for(i=0; i<db->nDb; i++) {
  117281. Btree *pBt = db->aDb[i].pBt;
  117282. if( pBt ){
  117283. assert( sqlite3BtreeHoldsMutex(pBt) );
  117284. rc = sqlite3BtreeSchemaLocked(pBt);
  117285. if( rc ){
  117286. const char *zDb = db->aDb[i].zDbSName;
  117287. sqlite3ErrorWithMsg(db, rc, "database schema is locked: %s", zDb);
  117288. testcase( db->flags & SQLITE_ReadUncommit );
  117289. goto end_prepare;
  117290. }
  117291. }
  117292. }
  117293. sqlite3VtabUnlockList(db);
  117294. sParse.db = db;
  117295. if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
  117296. char *zSqlCopy;
  117297. int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
  117298. testcase( nBytes==mxLen );
  117299. testcase( nBytes==mxLen+1 );
  117300. if( nBytes>mxLen ){
  117301. sqlite3ErrorWithMsg(db, SQLITE_TOOBIG, "statement too long");
  117302. rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
  117303. goto end_prepare;
  117304. }
  117305. zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
  117306. if( zSqlCopy ){
  117307. sqlite3RunParser(&sParse, zSqlCopy, &zErrMsg);
  117308. sParse.zTail = &zSql[sParse.zTail-zSqlCopy];
  117309. sqlite3DbFree(db, zSqlCopy);
  117310. }else{
  117311. sParse.zTail = &zSql[nBytes];
  117312. }
  117313. }else{
  117314. sqlite3RunParser(&sParse, zSql, &zErrMsg);
  117315. }
  117316. assert( 0==sParse.nQueryLoop );
  117317. if( sParse.rc==SQLITE_DONE ) sParse.rc = SQLITE_OK;
  117318. if( sParse.checkSchema ){
  117319. schemaIsValid(&sParse);
  117320. }
  117321. if( db->mallocFailed ){
  117322. sParse.rc = SQLITE_NOMEM_BKPT;
  117323. }
  117324. if( pzTail ){
  117325. *pzTail = sParse.zTail;
  117326. }
  117327. rc = sParse.rc;
  117328. #ifndef SQLITE_OMIT_EXPLAIN
  117329. if( rc==SQLITE_OK && sParse.pVdbe && sParse.explain ){
  117330. static const char * const azColName[] = {
  117331. "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
  117332. "id", "parent", "notused", "detail"
  117333. };
  117334. int iFirst, mx;
  117335. if( sParse.explain==2 ){
  117336. sqlite3VdbeSetNumCols(sParse.pVdbe, 4);
  117337. iFirst = 8;
  117338. mx = 12;
  117339. }else{
  117340. sqlite3VdbeSetNumCols(sParse.pVdbe, 8);
  117341. iFirst = 0;
  117342. mx = 8;
  117343. }
  117344. for(i=iFirst; i<mx; i++){
  117345. sqlite3VdbeSetColName(sParse.pVdbe, i-iFirst, COLNAME_NAME,
  117346. azColName[i], SQLITE_STATIC);
  117347. }
  117348. }
  117349. #endif
  117350. if( db->init.busy==0 ){
  117351. sqlite3VdbeSetSql(sParse.pVdbe, zSql, (int)(sParse.zTail-zSql), prepFlags);
  117352. }
  117353. if( sParse.pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
  117354. sqlite3VdbeFinalize(sParse.pVdbe);
  117355. assert(!(*ppStmt));
  117356. }else{
  117357. *ppStmt = (sqlite3_stmt*)sParse.pVdbe;
  117358. }
  117359. if( zErrMsg ){
  117360. sqlite3ErrorWithMsg(db, rc, "%s", zErrMsg);
  117361. sqlite3DbFree(db, zErrMsg);
  117362. }else{
  117363. sqlite3Error(db, rc);
  117364. }
  117365. /* Delete any TriggerPrg structures allocated while parsing this statement. */
  117366. while( sParse.pTriggerPrg ){
  117367. TriggerPrg *pT = sParse.pTriggerPrg;
  117368. sParse.pTriggerPrg = pT->pNext;
  117369. sqlite3DbFree(db, pT);
  117370. }
  117371. end_prepare:
  117372. sqlite3ParserReset(&sParse);
  117373. return rc;
  117374. }
  117375. static int sqlite3LockAndPrepare(
  117376. sqlite3 *db, /* Database handle. */
  117377. const char *zSql, /* UTF-8 encoded SQL statement. */
  117378. int nBytes, /* Length of zSql in bytes. */
  117379. u32 prepFlags, /* Zero or more SQLITE_PREPARE_* flags */
  117380. Vdbe *pOld, /* VM being reprepared */
  117381. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  117382. const char **pzTail /* OUT: End of parsed string */
  117383. ){
  117384. int rc;
  117385. int cnt = 0;
  117386. #ifdef SQLITE_ENABLE_API_ARMOR
  117387. if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
  117388. #endif
  117389. *ppStmt = 0;
  117390. if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
  117391. return SQLITE_MISUSE_BKPT;
  117392. }
  117393. sqlite3_mutex_enter(db->mutex);
  117394. sqlite3BtreeEnterAll(db);
  117395. do{
  117396. /* Make multiple attempts to compile the SQL, until it either succeeds
  117397. ** or encounters a permanent error. A schema problem after one schema
  117398. ** reset is considered a permanent error. */
  117399. rc = sqlite3Prepare(db, zSql, nBytes, prepFlags, pOld, ppStmt, pzTail);
  117400. assert( rc==SQLITE_OK || *ppStmt==0 );
  117401. }while( rc==SQLITE_ERROR_RETRY
  117402. || (rc==SQLITE_SCHEMA && (sqlite3ResetOneSchema(db,-1), cnt++)==0) );
  117403. sqlite3BtreeLeaveAll(db);
  117404. rc = sqlite3ApiExit(db, rc);
  117405. assert( (rc&db->errMask)==rc );
  117406. sqlite3_mutex_leave(db->mutex);
  117407. return rc;
  117408. }
  117409. /*
  117410. ** Rerun the compilation of a statement after a schema change.
  117411. **
  117412. ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
  117413. ** if the statement cannot be recompiled because another connection has
  117414. ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
  117415. ** occurs, return SQLITE_SCHEMA.
  117416. */
  117417. SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
  117418. int rc;
  117419. sqlite3_stmt *pNew;
  117420. const char *zSql;
  117421. sqlite3 *db;
  117422. u8 prepFlags;
  117423. assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
  117424. zSql = sqlite3_sql((sqlite3_stmt *)p);
  117425. assert( zSql!=0 ); /* Reprepare only called for prepare_v2() statements */
  117426. db = sqlite3VdbeDb(p);
  117427. assert( sqlite3_mutex_held(db->mutex) );
  117428. prepFlags = sqlite3VdbePrepareFlags(p);
  117429. rc = sqlite3LockAndPrepare(db, zSql, -1, prepFlags, p, &pNew, 0);
  117430. if( rc ){
  117431. if( rc==SQLITE_NOMEM ){
  117432. sqlite3OomFault(db);
  117433. }
  117434. assert( pNew==0 );
  117435. return rc;
  117436. }else{
  117437. assert( pNew!=0 );
  117438. }
  117439. sqlite3VdbeSwap((Vdbe*)pNew, p);
  117440. sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
  117441. sqlite3VdbeResetStepResult((Vdbe*)pNew);
  117442. sqlite3VdbeFinalize((Vdbe*)pNew);
  117443. return SQLITE_OK;
  117444. }
  117445. /*
  117446. ** Two versions of the official API. Legacy and new use. In the legacy
  117447. ** version, the original SQL text is not saved in the prepared statement
  117448. ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
  117449. ** sqlite3_step(). In the new version, the original SQL text is retained
  117450. ** and the statement is automatically recompiled if an schema change
  117451. ** occurs.
  117452. */
  117453. SQLITE_API int sqlite3_prepare(
  117454. sqlite3 *db, /* Database handle. */
  117455. const char *zSql, /* UTF-8 encoded SQL statement. */
  117456. int nBytes, /* Length of zSql in bytes. */
  117457. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  117458. const char **pzTail /* OUT: End of parsed string */
  117459. ){
  117460. int rc;
  117461. rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
  117462. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  117463. return rc;
  117464. }
  117465. SQLITE_API int sqlite3_prepare_v2(
  117466. sqlite3 *db, /* Database handle. */
  117467. const char *zSql, /* UTF-8 encoded SQL statement. */
  117468. int nBytes, /* Length of zSql in bytes. */
  117469. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  117470. const char **pzTail /* OUT: End of parsed string */
  117471. ){
  117472. int rc;
  117473. /* EVIDENCE-OF: R-37923-12173 The sqlite3_prepare_v2() interface works
  117474. ** exactly the same as sqlite3_prepare_v3() with a zero prepFlags
  117475. ** parameter.
  117476. **
  117477. ** Proof in that the 5th parameter to sqlite3LockAndPrepare is 0 */
  117478. rc = sqlite3LockAndPrepare(db,zSql,nBytes,SQLITE_PREPARE_SAVESQL,0,
  117479. ppStmt,pzTail);
  117480. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );
  117481. return rc;
  117482. }
  117483. SQLITE_API int sqlite3_prepare_v3(
  117484. sqlite3 *db, /* Database handle. */
  117485. const char *zSql, /* UTF-8 encoded SQL statement. */
  117486. int nBytes, /* Length of zSql in bytes. */
  117487. unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_* flags */
  117488. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  117489. const char **pzTail /* OUT: End of parsed string */
  117490. ){
  117491. int rc;
  117492. /* EVIDENCE-OF: R-56861-42673 sqlite3_prepare_v3() differs from
  117493. ** sqlite3_prepare_v2() only in having the extra prepFlags parameter,
  117494. ** which is a bit array consisting of zero or more of the
  117495. ** SQLITE_PREPARE_* flags.
  117496. **
  117497. ** Proof by comparison to the implementation of sqlite3_prepare_v2()
  117498. ** directly above. */
  117499. rc = sqlite3LockAndPrepare(db,zSql,nBytes,
  117500. SQLITE_PREPARE_SAVESQL|(prepFlags&SQLITE_PREPARE_MASK),
  117501. 0,ppStmt,pzTail);
  117502. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );
  117503. return rc;
  117504. }
  117505. #ifndef SQLITE_OMIT_UTF16
  117506. /*
  117507. ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
  117508. */
  117509. static int sqlite3Prepare16(
  117510. sqlite3 *db, /* Database handle. */
  117511. const void *zSql, /* UTF-16 encoded SQL statement. */
  117512. int nBytes, /* Length of zSql in bytes. */
  117513. u32 prepFlags, /* Zero or more SQLITE_PREPARE_* flags */
  117514. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  117515. const void **pzTail /* OUT: End of parsed string */
  117516. ){
  117517. /* This function currently works by first transforming the UTF-16
  117518. ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
  117519. ** tricky bit is figuring out the pointer to return in *pzTail.
  117520. */
  117521. char *zSql8;
  117522. const char *zTail8 = 0;
  117523. int rc = SQLITE_OK;
  117524. #ifdef SQLITE_ENABLE_API_ARMOR
  117525. if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
  117526. #endif
  117527. *ppStmt = 0;
  117528. if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
  117529. return SQLITE_MISUSE_BKPT;
  117530. }
  117531. if( nBytes>=0 ){
  117532. int sz;
  117533. const char *z = (const char*)zSql;
  117534. for(sz=0; sz<nBytes && (z[sz]!=0 || z[sz+1]!=0); sz += 2){}
  117535. nBytes = sz;
  117536. }
  117537. sqlite3_mutex_enter(db->mutex);
  117538. zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
  117539. if( zSql8 ){
  117540. rc = sqlite3LockAndPrepare(db, zSql8, -1, prepFlags, 0, ppStmt, &zTail8);
  117541. }
  117542. if( zTail8 && pzTail ){
  117543. /* If sqlite3_prepare returns a tail pointer, we calculate the
  117544. ** equivalent pointer into the UTF-16 string by counting the unicode
  117545. ** characters between zSql8 and zTail8, and then returning a pointer
  117546. ** the same number of characters into the UTF-16 string.
  117547. */
  117548. int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
  117549. *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
  117550. }
  117551. sqlite3DbFree(db, zSql8);
  117552. rc = sqlite3ApiExit(db, rc);
  117553. sqlite3_mutex_leave(db->mutex);
  117554. return rc;
  117555. }
  117556. /*
  117557. ** Two versions of the official API. Legacy and new use. In the legacy
  117558. ** version, the original SQL text is not saved in the prepared statement
  117559. ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
  117560. ** sqlite3_step(). In the new version, the original SQL text is retained
  117561. ** and the statement is automatically recompiled if an schema change
  117562. ** occurs.
  117563. */
  117564. SQLITE_API int sqlite3_prepare16(
  117565. sqlite3 *db, /* Database handle. */
  117566. const void *zSql, /* UTF-16 encoded SQL statement. */
  117567. int nBytes, /* Length of zSql in bytes. */
  117568. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  117569. const void **pzTail /* OUT: End of parsed string */
  117570. ){
  117571. int rc;
  117572. rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
  117573. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  117574. return rc;
  117575. }
  117576. SQLITE_API int sqlite3_prepare16_v2(
  117577. sqlite3 *db, /* Database handle. */
  117578. const void *zSql, /* UTF-16 encoded SQL statement. */
  117579. int nBytes, /* Length of zSql in bytes. */
  117580. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  117581. const void **pzTail /* OUT: End of parsed string */
  117582. ){
  117583. int rc;
  117584. rc = sqlite3Prepare16(db,zSql,nBytes,SQLITE_PREPARE_SAVESQL,ppStmt,pzTail);
  117585. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  117586. return rc;
  117587. }
  117588. SQLITE_API int sqlite3_prepare16_v3(
  117589. sqlite3 *db, /* Database handle. */
  117590. const void *zSql, /* UTF-16 encoded SQL statement. */
  117591. int nBytes, /* Length of zSql in bytes. */
  117592. unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_* flags */
  117593. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  117594. const void **pzTail /* OUT: End of parsed string */
  117595. ){
  117596. int rc;
  117597. rc = sqlite3Prepare16(db,zSql,nBytes,
  117598. SQLITE_PREPARE_SAVESQL|(prepFlags&SQLITE_PREPARE_MASK),
  117599. ppStmt,pzTail);
  117600. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  117601. return rc;
  117602. }
  117603. #endif /* SQLITE_OMIT_UTF16 */
  117604. /************** End of prepare.c *********************************************/
  117605. /************** Begin file select.c ******************************************/
  117606. /*
  117607. ** 2001 September 15
  117608. **
  117609. ** The author disclaims copyright to this source code. In place of
  117610. ** a legal notice, here is a blessing:
  117611. **
  117612. ** May you do good and not evil.
  117613. ** May you find forgiveness for yourself and forgive others.
  117614. ** May you share freely, never taking more than you give.
  117615. **
  117616. *************************************************************************
  117617. ** This file contains C code routines that are called by the parser
  117618. ** to handle SELECT statements in SQLite.
  117619. */
  117620. /* #include "sqliteInt.h" */
  117621. /*
  117622. ** Trace output macros
  117623. */
  117624. #if SELECTTRACE_ENABLED
  117625. /***/ int sqlite3SelectTrace = 0;
  117626. # define SELECTTRACE(K,P,S,X) \
  117627. if(sqlite3SelectTrace&(K)) \
  117628. sqlite3DebugPrintf("%u/%d/%p: ",(S)->selId,(P)->addrExplain,(S)),\
  117629. sqlite3DebugPrintf X
  117630. #else
  117631. # define SELECTTRACE(K,P,S,X)
  117632. #endif
  117633. /*
  117634. ** An instance of the following object is used to record information about
  117635. ** how to process the DISTINCT keyword, to simplify passing that information
  117636. ** into the selectInnerLoop() routine.
  117637. */
  117638. typedef struct DistinctCtx DistinctCtx;
  117639. struct DistinctCtx {
  117640. u8 isTnct; /* True if the DISTINCT keyword is present */
  117641. u8 eTnctType; /* One of the WHERE_DISTINCT_* operators */
  117642. int tabTnct; /* Ephemeral table used for DISTINCT processing */
  117643. int addrTnct; /* Address of OP_OpenEphemeral opcode for tabTnct */
  117644. };
  117645. /*
  117646. ** An instance of the following object is used to record information about
  117647. ** the ORDER BY (or GROUP BY) clause of query is being coded.
  117648. **
  117649. ** The aDefer[] array is used by the sorter-references optimization. For
  117650. ** example, assuming there is no index that can be used for the ORDER BY,
  117651. ** for the query:
  117652. **
  117653. ** SELECT a, bigblob FROM t1 ORDER BY a LIMIT 10;
  117654. **
  117655. ** it may be more efficient to add just the "a" values to the sorter, and
  117656. ** retrieve the associated "bigblob" values directly from table t1 as the
  117657. ** 10 smallest "a" values are extracted from the sorter.
  117658. **
  117659. ** When the sorter-reference optimization is used, there is one entry in the
  117660. ** aDefer[] array for each database table that may be read as values are
  117661. ** extracted from the sorter.
  117662. */
  117663. typedef struct SortCtx SortCtx;
  117664. struct SortCtx {
  117665. ExprList *pOrderBy; /* The ORDER BY (or GROUP BY clause) */
  117666. int nOBSat; /* Number of ORDER BY terms satisfied by indices */
  117667. int iECursor; /* Cursor number for the sorter */
  117668. int regReturn; /* Register holding block-output return address */
  117669. int labelBkOut; /* Start label for the block-output subroutine */
  117670. int addrSortIndex; /* Address of the OP_SorterOpen or OP_OpenEphemeral */
  117671. int labelDone; /* Jump here when done, ex: LIMIT reached */
  117672. int labelOBLopt; /* Jump here when sorter is full */
  117673. u8 sortFlags; /* Zero or more SORTFLAG_* bits */
  117674. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  117675. u8 nDefer; /* Number of valid entries in aDefer[] */
  117676. struct DeferredCsr {
  117677. Table *pTab; /* Table definition */
  117678. int iCsr; /* Cursor number for table */
  117679. int nKey; /* Number of PK columns for table pTab (>=1) */
  117680. } aDefer[4];
  117681. #endif
  117682. struct RowLoadInfo *pDeferredRowLoad; /* Deferred row loading info or NULL */
  117683. };
  117684. #define SORTFLAG_UseSorter 0x01 /* Use SorterOpen instead of OpenEphemeral */
  117685. /*
  117686. ** Delete all the content of a Select structure. Deallocate the structure
  117687. ** itself only if bFree is true.
  117688. */
  117689. static void clearSelect(sqlite3 *db, Select *p, int bFree){
  117690. while( p ){
  117691. Select *pPrior = p->pPrior;
  117692. sqlite3ExprListDelete(db, p->pEList);
  117693. sqlite3SrcListDelete(db, p->pSrc);
  117694. sqlite3ExprDelete(db, p->pWhere);
  117695. sqlite3ExprListDelete(db, p->pGroupBy);
  117696. sqlite3ExprDelete(db, p->pHaving);
  117697. sqlite3ExprListDelete(db, p->pOrderBy);
  117698. sqlite3ExprDelete(db, p->pLimit);
  117699. #ifndef SQLITE_OMIT_WINDOWFUNC
  117700. if( OK_IF_ALWAYS_TRUE(p->pWinDefn) ){
  117701. sqlite3WindowListDelete(db, p->pWinDefn);
  117702. }
  117703. #endif
  117704. if( OK_IF_ALWAYS_TRUE(p->pWith) ) sqlite3WithDelete(db, p->pWith);
  117705. if( bFree ) sqlite3DbFreeNN(db, p);
  117706. p = pPrior;
  117707. bFree = 1;
  117708. }
  117709. }
  117710. /*
  117711. ** Initialize a SelectDest structure.
  117712. */
  117713. SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
  117714. pDest->eDest = (u8)eDest;
  117715. pDest->iSDParm = iParm;
  117716. pDest->zAffSdst = 0;
  117717. pDest->iSdst = 0;
  117718. pDest->nSdst = 0;
  117719. }
  117720. /*
  117721. ** Allocate a new Select structure and return a pointer to that
  117722. ** structure.
  117723. */
  117724. SQLITE_PRIVATE Select *sqlite3SelectNew(
  117725. Parse *pParse, /* Parsing context */
  117726. ExprList *pEList, /* which columns to include in the result */
  117727. SrcList *pSrc, /* the FROM clause -- which tables to scan */
  117728. Expr *pWhere, /* the WHERE clause */
  117729. ExprList *pGroupBy, /* the GROUP BY clause */
  117730. Expr *pHaving, /* the HAVING clause */
  117731. ExprList *pOrderBy, /* the ORDER BY clause */
  117732. u32 selFlags, /* Flag parameters, such as SF_Distinct */
  117733. Expr *pLimit /* LIMIT value. NULL means not used */
  117734. ){
  117735. Select *pNew;
  117736. Select standin;
  117737. pNew = sqlite3DbMallocRawNN(pParse->db, sizeof(*pNew) );
  117738. if( pNew==0 ){
  117739. assert( pParse->db->mallocFailed );
  117740. pNew = &standin;
  117741. }
  117742. if( pEList==0 ){
  117743. pEList = sqlite3ExprListAppend(pParse, 0,
  117744. sqlite3Expr(pParse->db,TK_ASTERISK,0));
  117745. }
  117746. pNew->pEList = pEList;
  117747. pNew->op = TK_SELECT;
  117748. pNew->selFlags = selFlags;
  117749. pNew->iLimit = 0;
  117750. pNew->iOffset = 0;
  117751. pNew->selId = ++pParse->nSelect;
  117752. pNew->addrOpenEphm[0] = -1;
  117753. pNew->addrOpenEphm[1] = -1;
  117754. pNew->nSelectRow = 0;
  117755. if( pSrc==0 ) pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*pSrc));
  117756. pNew->pSrc = pSrc;
  117757. pNew->pWhere = pWhere;
  117758. pNew->pGroupBy = pGroupBy;
  117759. pNew->pHaving = pHaving;
  117760. pNew->pOrderBy = pOrderBy;
  117761. pNew->pPrior = 0;
  117762. pNew->pNext = 0;
  117763. pNew->pLimit = pLimit;
  117764. pNew->pWith = 0;
  117765. #ifndef SQLITE_OMIT_WINDOWFUNC
  117766. pNew->pWin = 0;
  117767. pNew->pWinDefn = 0;
  117768. #endif
  117769. if( pParse->db->mallocFailed ) {
  117770. clearSelect(pParse->db, pNew, pNew!=&standin);
  117771. pNew = 0;
  117772. }else{
  117773. assert( pNew->pSrc!=0 || pParse->nErr>0 );
  117774. }
  117775. assert( pNew!=&standin );
  117776. return pNew;
  117777. }
  117778. /*
  117779. ** Delete the given Select structure and all of its substructures.
  117780. */
  117781. SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
  117782. if( OK_IF_ALWAYS_TRUE(p) ) clearSelect(db, p, 1);
  117783. }
  117784. /*
  117785. ** Return a pointer to the right-most SELECT statement in a compound.
  117786. */
  117787. static Select *findRightmost(Select *p){
  117788. while( p->pNext ) p = p->pNext;
  117789. return p;
  117790. }
  117791. /*
  117792. ** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
  117793. ** type of join. Return an integer constant that expresses that type
  117794. ** in terms of the following bit values:
  117795. **
  117796. ** JT_INNER
  117797. ** JT_CROSS
  117798. ** JT_OUTER
  117799. ** JT_NATURAL
  117800. ** JT_LEFT
  117801. ** JT_RIGHT
  117802. **
  117803. ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
  117804. **
  117805. ** If an illegal or unsupported join type is seen, then still return
  117806. ** a join type, but put an error in the pParse structure.
  117807. */
  117808. SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
  117809. int jointype = 0;
  117810. Token *apAll[3];
  117811. Token *p;
  117812. /* 0123456789 123456789 123456789 123 */
  117813. static const char zKeyText[] = "naturaleftouterightfullinnercross";
  117814. static const struct {
  117815. u8 i; /* Beginning of keyword text in zKeyText[] */
  117816. u8 nChar; /* Length of the keyword in characters */
  117817. u8 code; /* Join type mask */
  117818. } aKeyword[] = {
  117819. /* natural */ { 0, 7, JT_NATURAL },
  117820. /* left */ { 6, 4, JT_LEFT|JT_OUTER },
  117821. /* outer */ { 10, 5, JT_OUTER },
  117822. /* right */ { 14, 5, JT_RIGHT|JT_OUTER },
  117823. /* full */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
  117824. /* inner */ { 23, 5, JT_INNER },
  117825. /* cross */ { 28, 5, JT_INNER|JT_CROSS },
  117826. };
  117827. int i, j;
  117828. apAll[0] = pA;
  117829. apAll[1] = pB;
  117830. apAll[2] = pC;
  117831. for(i=0; i<3 && apAll[i]; i++){
  117832. p = apAll[i];
  117833. for(j=0; j<ArraySize(aKeyword); j++){
  117834. if( p->n==aKeyword[j].nChar
  117835. && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
  117836. jointype |= aKeyword[j].code;
  117837. break;
  117838. }
  117839. }
  117840. testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
  117841. if( j>=ArraySize(aKeyword) ){
  117842. jointype |= JT_ERROR;
  117843. break;
  117844. }
  117845. }
  117846. if(
  117847. (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
  117848. (jointype & JT_ERROR)!=0
  117849. ){
  117850. const char *zSp = " ";
  117851. assert( pB!=0 );
  117852. if( pC==0 ){ zSp++; }
  117853. sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
  117854. "%T %T%s%T", pA, pB, zSp, pC);
  117855. jointype = JT_INNER;
  117856. }else if( (jointype & JT_OUTER)!=0
  117857. && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
  117858. sqlite3ErrorMsg(pParse,
  117859. "RIGHT and FULL OUTER JOINs are not currently supported");
  117860. jointype = JT_INNER;
  117861. }
  117862. return jointype;
  117863. }
  117864. /*
  117865. ** Return the index of a column in a table. Return -1 if the column
  117866. ** is not contained in the table.
  117867. */
  117868. static int columnIndex(Table *pTab, const char *zCol){
  117869. int i;
  117870. for(i=0; i<pTab->nCol; i++){
  117871. if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
  117872. }
  117873. return -1;
  117874. }
  117875. /*
  117876. ** Search the first N tables in pSrc, from left to right, looking for a
  117877. ** table that has a column named zCol.
  117878. **
  117879. ** When found, set *piTab and *piCol to the table index and column index
  117880. ** of the matching column and return TRUE.
  117881. **
  117882. ** If not found, return FALSE.
  117883. */
  117884. static int tableAndColumnIndex(
  117885. SrcList *pSrc, /* Array of tables to search */
  117886. int N, /* Number of tables in pSrc->a[] to search */
  117887. const char *zCol, /* Name of the column we are looking for */
  117888. int *piTab, /* Write index of pSrc->a[] here */
  117889. int *piCol /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
  117890. ){
  117891. int i; /* For looping over tables in pSrc */
  117892. int iCol; /* Index of column matching zCol */
  117893. assert( (piTab==0)==(piCol==0) ); /* Both or neither are NULL */
  117894. for(i=0; i<N; i++){
  117895. iCol = columnIndex(pSrc->a[i].pTab, zCol);
  117896. if( iCol>=0 ){
  117897. if( piTab ){
  117898. *piTab = i;
  117899. *piCol = iCol;
  117900. }
  117901. return 1;
  117902. }
  117903. }
  117904. return 0;
  117905. }
  117906. /*
  117907. ** This function is used to add terms implied by JOIN syntax to the
  117908. ** WHERE clause expression of a SELECT statement. The new term, which
  117909. ** is ANDed with the existing WHERE clause, is of the form:
  117910. **
  117911. ** (tab1.col1 = tab2.col2)
  117912. **
  117913. ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
  117914. ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
  117915. ** column iColRight of tab2.
  117916. */
  117917. static void addWhereTerm(
  117918. Parse *pParse, /* Parsing context */
  117919. SrcList *pSrc, /* List of tables in FROM clause */
  117920. int iLeft, /* Index of first table to join in pSrc */
  117921. int iColLeft, /* Index of column in first table */
  117922. int iRight, /* Index of second table in pSrc */
  117923. int iColRight, /* Index of column in second table */
  117924. int isOuterJoin, /* True if this is an OUTER join */
  117925. Expr **ppWhere /* IN/OUT: The WHERE clause to add to */
  117926. ){
  117927. sqlite3 *db = pParse->db;
  117928. Expr *pE1;
  117929. Expr *pE2;
  117930. Expr *pEq;
  117931. assert( iLeft<iRight );
  117932. assert( pSrc->nSrc>iRight );
  117933. assert( pSrc->a[iLeft].pTab );
  117934. assert( pSrc->a[iRight].pTab );
  117935. pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
  117936. pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
  117937. pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2);
  117938. if( pEq && isOuterJoin ){
  117939. ExprSetProperty(pEq, EP_FromJoin);
  117940. assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
  117941. ExprSetVVAProperty(pEq, EP_NoReduce);
  117942. pEq->iRightJoinTable = (i16)pE2->iTable;
  117943. }
  117944. *ppWhere = sqlite3ExprAnd(pParse, *ppWhere, pEq);
  117945. }
  117946. /*
  117947. ** Set the EP_FromJoin property on all terms of the given expression.
  117948. ** And set the Expr.iRightJoinTable to iTable for every term in the
  117949. ** expression.
  117950. **
  117951. ** The EP_FromJoin property is used on terms of an expression to tell
  117952. ** the LEFT OUTER JOIN processing logic that this term is part of the
  117953. ** join restriction specified in the ON or USING clause and not a part
  117954. ** of the more general WHERE clause. These terms are moved over to the
  117955. ** WHERE clause during join processing but we need to remember that they
  117956. ** originated in the ON or USING clause.
  117957. **
  117958. ** The Expr.iRightJoinTable tells the WHERE clause processing that the
  117959. ** expression depends on table iRightJoinTable even if that table is not
  117960. ** explicitly mentioned in the expression. That information is needed
  117961. ** for cases like this:
  117962. **
  117963. ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
  117964. **
  117965. ** The where clause needs to defer the handling of the t1.x=5
  117966. ** term until after the t2 loop of the join. In that way, a
  117967. ** NULL t2 row will be inserted whenever t1.x!=5. If we do not
  117968. ** defer the handling of t1.x=5, it will be processed immediately
  117969. ** after the t1 loop and rows with t1.x!=5 will never appear in
  117970. ** the output, which is incorrect.
  117971. */
  117972. static void setJoinExpr(Expr *p, int iTable){
  117973. while( p ){
  117974. ExprSetProperty(p, EP_FromJoin);
  117975. assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
  117976. ExprSetVVAProperty(p, EP_NoReduce);
  117977. p->iRightJoinTable = (i16)iTable;
  117978. if( p->op==TK_FUNCTION && p->x.pList ){
  117979. int i;
  117980. for(i=0; i<p->x.pList->nExpr; i++){
  117981. setJoinExpr(p->x.pList->a[i].pExpr, iTable);
  117982. }
  117983. }
  117984. setJoinExpr(p->pLeft, iTable);
  117985. p = p->pRight;
  117986. }
  117987. }
  117988. /* Undo the work of setJoinExpr(). In the expression tree p, convert every
  117989. ** term that is marked with EP_FromJoin and iRightJoinTable==iTable into
  117990. ** an ordinary term that omits the EP_FromJoin mark.
  117991. **
  117992. ** This happens when a LEFT JOIN is simplified into an ordinary JOIN.
  117993. */
  117994. static void unsetJoinExpr(Expr *p, int iTable){
  117995. while( p ){
  117996. if( ExprHasProperty(p, EP_FromJoin)
  117997. && (iTable<0 || p->iRightJoinTable==iTable) ){
  117998. ExprClearProperty(p, EP_FromJoin);
  117999. }
  118000. if( p->op==TK_FUNCTION && p->x.pList ){
  118001. int i;
  118002. for(i=0; i<p->x.pList->nExpr; i++){
  118003. unsetJoinExpr(p->x.pList->a[i].pExpr, iTable);
  118004. }
  118005. }
  118006. unsetJoinExpr(p->pLeft, iTable);
  118007. p = p->pRight;
  118008. }
  118009. }
  118010. /*
  118011. ** This routine processes the join information for a SELECT statement.
  118012. ** ON and USING clauses are converted into extra terms of the WHERE clause.
  118013. ** NATURAL joins also create extra WHERE clause terms.
  118014. **
  118015. ** The terms of a FROM clause are contained in the Select.pSrc structure.
  118016. ** The left most table is the first entry in Select.pSrc. The right-most
  118017. ** table is the last entry. The join operator is held in the entry to
  118018. ** the left. Thus entry 0 contains the join operator for the join between
  118019. ** entries 0 and 1. Any ON or USING clauses associated with the join are
  118020. ** also attached to the left entry.
  118021. **
  118022. ** This routine returns the number of errors encountered.
  118023. */
  118024. static int sqliteProcessJoin(Parse *pParse, Select *p){
  118025. SrcList *pSrc; /* All tables in the FROM clause */
  118026. int i, j; /* Loop counters */
  118027. struct SrcList_item *pLeft; /* Left table being joined */
  118028. struct SrcList_item *pRight; /* Right table being joined */
  118029. pSrc = p->pSrc;
  118030. pLeft = &pSrc->a[0];
  118031. pRight = &pLeft[1];
  118032. for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
  118033. Table *pRightTab = pRight->pTab;
  118034. int isOuter;
  118035. if( NEVER(pLeft->pTab==0 || pRightTab==0) ) continue;
  118036. isOuter = (pRight->fg.jointype & JT_OUTER)!=0;
  118037. /* When the NATURAL keyword is present, add WHERE clause terms for
  118038. ** every column that the two tables have in common.
  118039. */
  118040. if( pRight->fg.jointype & JT_NATURAL ){
  118041. if( pRight->pOn || pRight->pUsing ){
  118042. sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
  118043. "an ON or USING clause", 0);
  118044. return 1;
  118045. }
  118046. for(j=0; j<pRightTab->nCol; j++){
  118047. char *zName; /* Name of column in the right table */
  118048. int iLeft; /* Matching left table */
  118049. int iLeftCol; /* Matching column in the left table */
  118050. zName = pRightTab->aCol[j].zName;
  118051. if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
  118052. addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
  118053. isOuter, &p->pWhere);
  118054. }
  118055. }
  118056. }
  118057. /* Disallow both ON and USING clauses in the same join
  118058. */
  118059. if( pRight->pOn && pRight->pUsing ){
  118060. sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
  118061. "clauses in the same join");
  118062. return 1;
  118063. }
  118064. /* Add the ON clause to the end of the WHERE clause, connected by
  118065. ** an AND operator.
  118066. */
  118067. if( pRight->pOn ){
  118068. if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
  118069. p->pWhere = sqlite3ExprAnd(pParse, p->pWhere, pRight->pOn);
  118070. pRight->pOn = 0;
  118071. }
  118072. /* Create extra terms on the WHERE clause for each column named
  118073. ** in the USING clause. Example: If the two tables to be joined are
  118074. ** A and B and the USING clause names X, Y, and Z, then add this
  118075. ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
  118076. ** Report an error if any column mentioned in the USING clause is
  118077. ** not contained in both tables to be joined.
  118078. */
  118079. if( pRight->pUsing ){
  118080. IdList *pList = pRight->pUsing;
  118081. for(j=0; j<pList->nId; j++){
  118082. char *zName; /* Name of the term in the USING clause */
  118083. int iLeft; /* Table on the left with matching column name */
  118084. int iLeftCol; /* Column number of matching column on the left */
  118085. int iRightCol; /* Column number of matching column on the right */
  118086. zName = pList->a[j].zName;
  118087. iRightCol = columnIndex(pRightTab, zName);
  118088. if( iRightCol<0
  118089. || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
  118090. ){
  118091. sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
  118092. "not present in both tables", zName);
  118093. return 1;
  118094. }
  118095. addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
  118096. isOuter, &p->pWhere);
  118097. }
  118098. }
  118099. }
  118100. return 0;
  118101. }
  118102. /*
  118103. ** An instance of this object holds information (beyond pParse and pSelect)
  118104. ** needed to load the next result row that is to be added to the sorter.
  118105. */
  118106. typedef struct RowLoadInfo RowLoadInfo;
  118107. struct RowLoadInfo {
  118108. int regResult; /* Store results in array of registers here */
  118109. u8 ecelFlags; /* Flag argument to ExprCodeExprList() */
  118110. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  118111. ExprList *pExtra; /* Extra columns needed by sorter refs */
  118112. int regExtraResult; /* Where to load the extra columns */
  118113. #endif
  118114. };
  118115. /*
  118116. ** This routine does the work of loading query data into an array of
  118117. ** registers so that it can be added to the sorter.
  118118. */
  118119. static void innerLoopLoadRow(
  118120. Parse *pParse, /* Statement under construction */
  118121. Select *pSelect, /* The query being coded */
  118122. RowLoadInfo *pInfo /* Info needed to complete the row load */
  118123. ){
  118124. sqlite3ExprCodeExprList(pParse, pSelect->pEList, pInfo->regResult,
  118125. 0, pInfo->ecelFlags);
  118126. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  118127. if( pInfo->pExtra ){
  118128. sqlite3ExprCodeExprList(pParse, pInfo->pExtra, pInfo->regExtraResult, 0, 0);
  118129. sqlite3ExprListDelete(pParse->db, pInfo->pExtra);
  118130. }
  118131. #endif
  118132. }
  118133. /*
  118134. ** Code the OP_MakeRecord instruction that generates the entry to be
  118135. ** added into the sorter.
  118136. **
  118137. ** Return the register in which the result is stored.
  118138. */
  118139. static int makeSorterRecord(
  118140. Parse *pParse,
  118141. SortCtx *pSort,
  118142. Select *pSelect,
  118143. int regBase,
  118144. int nBase
  118145. ){
  118146. int nOBSat = pSort->nOBSat;
  118147. Vdbe *v = pParse->pVdbe;
  118148. int regOut = ++pParse->nMem;
  118149. if( pSort->pDeferredRowLoad ){
  118150. innerLoopLoadRow(pParse, pSelect, pSort->pDeferredRowLoad);
  118151. }
  118152. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regOut);
  118153. return regOut;
  118154. }
  118155. /*
  118156. ** Generate code that will push the record in registers regData
  118157. ** through regData+nData-1 onto the sorter.
  118158. */
  118159. static void pushOntoSorter(
  118160. Parse *pParse, /* Parser context */
  118161. SortCtx *pSort, /* Information about the ORDER BY clause */
  118162. Select *pSelect, /* The whole SELECT statement */
  118163. int regData, /* First register holding data to be sorted */
  118164. int regOrigData, /* First register holding data before packing */
  118165. int nData, /* Number of elements in the regData data array */
  118166. int nPrefixReg /* No. of reg prior to regData available for use */
  118167. ){
  118168. Vdbe *v = pParse->pVdbe; /* Stmt under construction */
  118169. int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0);
  118170. int nExpr = pSort->pOrderBy->nExpr; /* No. of ORDER BY terms */
  118171. int nBase = nExpr + bSeq + nData; /* Fields in sorter record */
  118172. int regBase; /* Regs for sorter record */
  118173. int regRecord = 0; /* Assembled sorter record */
  118174. int nOBSat = pSort->nOBSat; /* ORDER BY terms to skip */
  118175. int op; /* Opcode to add sorter record to sorter */
  118176. int iLimit; /* LIMIT counter */
  118177. int iSkip = 0; /* End of the sorter insert loop */
  118178. assert( bSeq==0 || bSeq==1 );
  118179. /* Three cases:
  118180. ** (1) The data to be sorted has already been packed into a Record
  118181. ** by a prior OP_MakeRecord. In this case nData==1 and regData
  118182. ** will be completely unrelated to regOrigData.
  118183. ** (2) All output columns are included in the sort record. In that
  118184. ** case regData==regOrigData.
  118185. ** (3) Some output columns are omitted from the sort record due to
  118186. ** the SQLITE_ENABLE_SORTER_REFERENCE optimization, or due to the
  118187. ** SQLITE_ECEL_OMITREF optimization, or due to the
  118188. ** SortCtx.pDeferredRowLoad optimiation. In any of these cases
  118189. ** regOrigData is 0 to prevent this routine from trying to copy
  118190. ** values that might not yet exist.
  118191. */
  118192. assert( nData==1 || regData==regOrigData || regOrigData==0 );
  118193. if( nPrefixReg ){
  118194. assert( nPrefixReg==nExpr+bSeq );
  118195. regBase = regData - nPrefixReg;
  118196. }else{
  118197. regBase = pParse->nMem + 1;
  118198. pParse->nMem += nBase;
  118199. }
  118200. assert( pSelect->iOffset==0 || pSelect->iLimit!=0 );
  118201. iLimit = pSelect->iOffset ? pSelect->iOffset+1 : pSelect->iLimit;
  118202. pSort->labelDone = sqlite3VdbeMakeLabel(pParse);
  118203. sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, regOrigData,
  118204. SQLITE_ECEL_DUP | (regOrigData? SQLITE_ECEL_REF : 0));
  118205. if( bSeq ){
  118206. sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr);
  118207. }
  118208. if( nPrefixReg==0 && nData>0 ){
  118209. sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData);
  118210. }
  118211. if( nOBSat>0 ){
  118212. int regPrevKey; /* The first nOBSat columns of the previous row */
  118213. int addrFirst; /* Address of the OP_IfNot opcode */
  118214. int addrJmp; /* Address of the OP_Jump opcode */
  118215. VdbeOp *pOp; /* Opcode that opens the sorter */
  118216. int nKey; /* Number of sorting key columns, including OP_Sequence */
  118217. KeyInfo *pKI; /* Original KeyInfo on the sorter table */
  118218. regRecord = makeSorterRecord(pParse, pSort, pSelect, regBase, nBase);
  118219. regPrevKey = pParse->nMem+1;
  118220. pParse->nMem += pSort->nOBSat;
  118221. nKey = nExpr - pSort->nOBSat + bSeq;
  118222. if( bSeq ){
  118223. addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr);
  118224. }else{
  118225. addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor);
  118226. }
  118227. VdbeCoverage(v);
  118228. sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat);
  118229. pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
  118230. if( pParse->db->mallocFailed ) return;
  118231. pOp->p2 = nKey + nData;
  118232. pKI = pOp->p4.pKeyInfo;
  118233. memset(pKI->aSortOrder, 0, pKI->nKeyField); /* Makes OP_Jump testable */
  118234. sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO);
  118235. testcase( pKI->nAllField > pKI->nKeyField+2 );
  118236. pOp->p4.pKeyInfo = sqlite3KeyInfoFromExprList(pParse,pSort->pOrderBy,nOBSat,
  118237. pKI->nAllField-pKI->nKeyField-1);
  118238. addrJmp = sqlite3VdbeCurrentAddr(v);
  118239. sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v);
  118240. pSort->labelBkOut = sqlite3VdbeMakeLabel(pParse);
  118241. pSort->regReturn = ++pParse->nMem;
  118242. sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
  118243. sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor);
  118244. if( iLimit ){
  118245. sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, pSort->labelDone);
  118246. VdbeCoverage(v);
  118247. }
  118248. sqlite3VdbeJumpHere(v, addrFirst);
  118249. sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat);
  118250. sqlite3VdbeJumpHere(v, addrJmp);
  118251. }
  118252. if( iLimit ){
  118253. /* At this point the values for the new sorter entry are stored
  118254. ** in an array of registers. They need to be composed into a record
  118255. ** and inserted into the sorter if either (a) there are currently
  118256. ** less than LIMIT+OFFSET items or (b) the new record is smaller than
  118257. ** the largest record currently in the sorter. If (b) is true and there
  118258. ** are already LIMIT+OFFSET items in the sorter, delete the largest
  118259. ** entry before inserting the new one. This way there are never more
  118260. ** than LIMIT+OFFSET items in the sorter.
  118261. **
  118262. ** If the new record does not need to be inserted into the sorter,
  118263. ** jump to the next iteration of the loop. If the pSort->labelOBLopt
  118264. ** value is not zero, then it is a label of where to jump. Otherwise,
  118265. ** just bypass the row insert logic. See the header comment on the
  118266. ** sqlite3WhereOrderByLimitOptLabel() function for additional info.
  118267. */
  118268. int iCsr = pSort->iECursor;
  118269. sqlite3VdbeAddOp2(v, OP_IfNotZero, iLimit, sqlite3VdbeCurrentAddr(v)+4);
  118270. VdbeCoverage(v);
  118271. sqlite3VdbeAddOp2(v, OP_Last, iCsr, 0);
  118272. iSkip = sqlite3VdbeAddOp4Int(v, OP_IdxLE,
  118273. iCsr, 0, regBase+nOBSat, nExpr-nOBSat);
  118274. VdbeCoverage(v);
  118275. sqlite3VdbeAddOp1(v, OP_Delete, iCsr);
  118276. }
  118277. if( regRecord==0 ){
  118278. regRecord = makeSorterRecord(pParse, pSort, pSelect, regBase, nBase);
  118279. }
  118280. if( pSort->sortFlags & SORTFLAG_UseSorter ){
  118281. op = OP_SorterInsert;
  118282. }else{
  118283. op = OP_IdxInsert;
  118284. }
  118285. sqlite3VdbeAddOp4Int(v, op, pSort->iECursor, regRecord,
  118286. regBase+nOBSat, nBase-nOBSat);
  118287. if( iSkip ){
  118288. sqlite3VdbeChangeP2(v, iSkip,
  118289. pSort->labelOBLopt ? pSort->labelOBLopt : sqlite3VdbeCurrentAddr(v));
  118290. }
  118291. }
  118292. /*
  118293. ** Add code to implement the OFFSET
  118294. */
  118295. static void codeOffset(
  118296. Vdbe *v, /* Generate code into this VM */
  118297. int iOffset, /* Register holding the offset counter */
  118298. int iContinue /* Jump here to skip the current record */
  118299. ){
  118300. if( iOffset>0 ){
  118301. sqlite3VdbeAddOp3(v, OP_IfPos, iOffset, iContinue, 1); VdbeCoverage(v);
  118302. VdbeComment((v, "OFFSET"));
  118303. }
  118304. }
  118305. /*
  118306. ** Add code that will check to make sure the N registers starting at iMem
  118307. ** form a distinct entry. iTab is a sorting index that holds previously
  118308. ** seen combinations of the N values. A new entry is made in iTab
  118309. ** if the current N values are new.
  118310. **
  118311. ** A jump to addrRepeat is made and the N+1 values are popped from the
  118312. ** stack if the top N elements are not distinct.
  118313. */
  118314. static void codeDistinct(
  118315. Parse *pParse, /* Parsing and code generating context */
  118316. int iTab, /* A sorting index used to test for distinctness */
  118317. int addrRepeat, /* Jump to here if not distinct */
  118318. int N, /* Number of elements */
  118319. int iMem /* First element */
  118320. ){
  118321. Vdbe *v;
  118322. int r1;
  118323. v = pParse->pVdbe;
  118324. r1 = sqlite3GetTempReg(pParse);
  118325. sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v);
  118326. sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
  118327. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r1, iMem, N);
  118328. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  118329. sqlite3ReleaseTempReg(pParse, r1);
  118330. }
  118331. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  118332. /*
  118333. ** This function is called as part of inner-loop generation for a SELECT
  118334. ** statement with an ORDER BY that is not optimized by an index. It
  118335. ** determines the expressions, if any, that the sorter-reference
  118336. ** optimization should be used for. The sorter-reference optimization
  118337. ** is used for SELECT queries like:
  118338. **
  118339. ** SELECT a, bigblob FROM t1 ORDER BY a LIMIT 10
  118340. **
  118341. ** If the optimization is used for expression "bigblob", then instead of
  118342. ** storing values read from that column in the sorter records, the PK of
  118343. ** the row from table t1 is stored instead. Then, as records are extracted from
  118344. ** the sorter to return to the user, the required value of bigblob is
  118345. ** retrieved directly from table t1. If the values are very large, this
  118346. ** can be more efficient than storing them directly in the sorter records.
  118347. **
  118348. ** The ExprList_item.bSorterRef flag is set for each expression in pEList
  118349. ** for which the sorter-reference optimization should be enabled.
  118350. ** Additionally, the pSort->aDefer[] array is populated with entries
  118351. ** for all cursors required to evaluate all selected expressions. Finally.
  118352. ** output variable (*ppExtra) is set to an expression list containing
  118353. ** expressions for all extra PK values that should be stored in the
  118354. ** sorter records.
  118355. */
  118356. static void selectExprDefer(
  118357. Parse *pParse, /* Leave any error here */
  118358. SortCtx *pSort, /* Sorter context */
  118359. ExprList *pEList, /* Expressions destined for sorter */
  118360. ExprList **ppExtra /* Expressions to append to sorter record */
  118361. ){
  118362. int i;
  118363. int nDefer = 0;
  118364. ExprList *pExtra = 0;
  118365. for(i=0; i<pEList->nExpr; i++){
  118366. struct ExprList_item *pItem = &pEList->a[i];
  118367. if( pItem->u.x.iOrderByCol==0 ){
  118368. Expr *pExpr = pItem->pExpr;
  118369. Table *pTab = pExpr->y.pTab;
  118370. if( pExpr->op==TK_COLUMN && pExpr->iColumn>=0 && pTab && !IsVirtual(pTab)
  118371. && (pTab->aCol[pExpr->iColumn].colFlags & COLFLAG_SORTERREF)
  118372. ){
  118373. int j;
  118374. for(j=0; j<nDefer; j++){
  118375. if( pSort->aDefer[j].iCsr==pExpr->iTable ) break;
  118376. }
  118377. if( j==nDefer ){
  118378. if( nDefer==ArraySize(pSort->aDefer) ){
  118379. continue;
  118380. }else{
  118381. int nKey = 1;
  118382. int k;
  118383. Index *pPk = 0;
  118384. if( !HasRowid(pTab) ){
  118385. pPk = sqlite3PrimaryKeyIndex(pTab);
  118386. nKey = pPk->nKeyCol;
  118387. }
  118388. for(k=0; k<nKey; k++){
  118389. Expr *pNew = sqlite3PExpr(pParse, TK_COLUMN, 0, 0);
  118390. if( pNew ){
  118391. pNew->iTable = pExpr->iTable;
  118392. pNew->y.pTab = pExpr->y.pTab;
  118393. pNew->iColumn = pPk ? pPk->aiColumn[k] : -1;
  118394. pExtra = sqlite3ExprListAppend(pParse, pExtra, pNew);
  118395. }
  118396. }
  118397. pSort->aDefer[nDefer].pTab = pExpr->y.pTab;
  118398. pSort->aDefer[nDefer].iCsr = pExpr->iTable;
  118399. pSort->aDefer[nDefer].nKey = nKey;
  118400. nDefer++;
  118401. }
  118402. }
  118403. pItem->bSorterRef = 1;
  118404. }
  118405. }
  118406. }
  118407. pSort->nDefer = (u8)nDefer;
  118408. *ppExtra = pExtra;
  118409. }
  118410. #endif
  118411. /*
  118412. ** This routine generates the code for the inside of the inner loop
  118413. ** of a SELECT.
  118414. **
  118415. ** If srcTab is negative, then the p->pEList expressions
  118416. ** are evaluated in order to get the data for this row. If srcTab is
  118417. ** zero or more, then data is pulled from srcTab and p->pEList is used only
  118418. ** to get the number of columns and the collation sequence for each column.
  118419. */
  118420. static void selectInnerLoop(
  118421. Parse *pParse, /* The parser context */
  118422. Select *p, /* The complete select statement being coded */
  118423. int srcTab, /* Pull data from this table if non-negative */
  118424. SortCtx *pSort, /* If not NULL, info on how to process ORDER BY */
  118425. DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
  118426. SelectDest *pDest, /* How to dispose of the results */
  118427. int iContinue, /* Jump here to continue with next row */
  118428. int iBreak /* Jump here to break out of the inner loop */
  118429. ){
  118430. Vdbe *v = pParse->pVdbe;
  118431. int i;
  118432. int hasDistinct; /* True if the DISTINCT keyword is present */
  118433. int eDest = pDest->eDest; /* How to dispose of results */
  118434. int iParm = pDest->iSDParm; /* First argument to disposal method */
  118435. int nResultCol; /* Number of result columns */
  118436. int nPrefixReg = 0; /* Number of extra registers before regResult */
  118437. RowLoadInfo sRowLoadInfo; /* Info for deferred row loading */
  118438. /* Usually, regResult is the first cell in an array of memory cells
  118439. ** containing the current result row. In this case regOrig is set to the
  118440. ** same value. However, if the results are being sent to the sorter, the
  118441. ** values for any expressions that are also part of the sort-key are omitted
  118442. ** from this array. In this case regOrig is set to zero. */
  118443. int regResult; /* Start of memory holding current results */
  118444. int regOrig; /* Start of memory holding full result (or 0) */
  118445. assert( v );
  118446. assert( p->pEList!=0 );
  118447. hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
  118448. if( pSort && pSort->pOrderBy==0 ) pSort = 0;
  118449. if( pSort==0 && !hasDistinct ){
  118450. assert( iContinue!=0 );
  118451. codeOffset(v, p->iOffset, iContinue);
  118452. }
  118453. /* Pull the requested columns.
  118454. */
  118455. nResultCol = p->pEList->nExpr;
  118456. if( pDest->iSdst==0 ){
  118457. if( pSort ){
  118458. nPrefixReg = pSort->pOrderBy->nExpr;
  118459. if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++;
  118460. pParse->nMem += nPrefixReg;
  118461. }
  118462. pDest->iSdst = pParse->nMem+1;
  118463. pParse->nMem += nResultCol;
  118464. }else if( pDest->iSdst+nResultCol > pParse->nMem ){
  118465. /* This is an error condition that can result, for example, when a SELECT
  118466. ** on the right-hand side of an INSERT contains more result columns than
  118467. ** there are columns in the table on the left. The error will be caught
  118468. ** and reported later. But we need to make sure enough memory is allocated
  118469. ** to avoid other spurious errors in the meantime. */
  118470. pParse->nMem += nResultCol;
  118471. }
  118472. pDest->nSdst = nResultCol;
  118473. regOrig = regResult = pDest->iSdst;
  118474. if( srcTab>=0 ){
  118475. for(i=0; i<nResultCol; i++){
  118476. sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
  118477. VdbeComment((v, "%s", p->pEList->a[i].zName));
  118478. }
  118479. }else if( eDest!=SRT_Exists ){
  118480. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  118481. ExprList *pExtra = 0;
  118482. #endif
  118483. /* If the destination is an EXISTS(...) expression, the actual
  118484. ** values returned by the SELECT are not required.
  118485. */
  118486. u8 ecelFlags; /* "ecel" is an abbreviation of "ExprCodeExprList" */
  118487. ExprList *pEList;
  118488. if( eDest==SRT_Mem || eDest==SRT_Output || eDest==SRT_Coroutine ){
  118489. ecelFlags = SQLITE_ECEL_DUP;
  118490. }else{
  118491. ecelFlags = 0;
  118492. }
  118493. if( pSort && hasDistinct==0 && eDest!=SRT_EphemTab && eDest!=SRT_Table ){
  118494. /* For each expression in p->pEList that is a copy of an expression in
  118495. ** the ORDER BY clause (pSort->pOrderBy), set the associated
  118496. ** iOrderByCol value to one more than the index of the ORDER BY
  118497. ** expression within the sort-key that pushOntoSorter() will generate.
  118498. ** This allows the p->pEList field to be omitted from the sorted record,
  118499. ** saving space and CPU cycles. */
  118500. ecelFlags |= (SQLITE_ECEL_OMITREF|SQLITE_ECEL_REF);
  118501. for(i=pSort->nOBSat; i<pSort->pOrderBy->nExpr; i++){
  118502. int j;
  118503. if( (j = pSort->pOrderBy->a[i].u.x.iOrderByCol)>0 ){
  118504. p->pEList->a[j-1].u.x.iOrderByCol = i+1-pSort->nOBSat;
  118505. }
  118506. }
  118507. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  118508. selectExprDefer(pParse, pSort, p->pEList, &pExtra);
  118509. if( pExtra && pParse->db->mallocFailed==0 ){
  118510. /* If there are any extra PK columns to add to the sorter records,
  118511. ** allocate extra memory cells and adjust the OpenEphemeral
  118512. ** instruction to account for the larger records. This is only
  118513. ** required if there are one or more WITHOUT ROWID tables with
  118514. ** composite primary keys in the SortCtx.aDefer[] array. */
  118515. VdbeOp *pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
  118516. pOp->p2 += (pExtra->nExpr - pSort->nDefer);
  118517. pOp->p4.pKeyInfo->nAllField += (pExtra->nExpr - pSort->nDefer);
  118518. pParse->nMem += pExtra->nExpr;
  118519. }
  118520. #endif
  118521. /* Adjust nResultCol to account for columns that are omitted
  118522. ** from the sorter by the optimizations in this branch */
  118523. pEList = p->pEList;
  118524. for(i=0; i<pEList->nExpr; i++){
  118525. if( pEList->a[i].u.x.iOrderByCol>0
  118526. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  118527. || pEList->a[i].bSorterRef
  118528. #endif
  118529. ){
  118530. nResultCol--;
  118531. regOrig = 0;
  118532. }
  118533. }
  118534. testcase( regOrig );
  118535. testcase( eDest==SRT_Set );
  118536. testcase( eDest==SRT_Mem );
  118537. testcase( eDest==SRT_Coroutine );
  118538. testcase( eDest==SRT_Output );
  118539. assert( eDest==SRT_Set || eDest==SRT_Mem
  118540. || eDest==SRT_Coroutine || eDest==SRT_Output );
  118541. }
  118542. sRowLoadInfo.regResult = regResult;
  118543. sRowLoadInfo.ecelFlags = ecelFlags;
  118544. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  118545. sRowLoadInfo.pExtra = pExtra;
  118546. sRowLoadInfo.regExtraResult = regResult + nResultCol;
  118547. if( pExtra ) nResultCol += pExtra->nExpr;
  118548. #endif
  118549. if( p->iLimit
  118550. && (ecelFlags & SQLITE_ECEL_OMITREF)!=0
  118551. && nPrefixReg>0
  118552. ){
  118553. assert( pSort!=0 );
  118554. assert( hasDistinct==0 );
  118555. pSort->pDeferredRowLoad = &sRowLoadInfo;
  118556. regOrig = 0;
  118557. }else{
  118558. innerLoopLoadRow(pParse, p, &sRowLoadInfo);
  118559. }
  118560. }
  118561. /* If the DISTINCT keyword was present on the SELECT statement
  118562. ** and this row has been seen before, then do not make this row
  118563. ** part of the result.
  118564. */
  118565. if( hasDistinct ){
  118566. switch( pDistinct->eTnctType ){
  118567. case WHERE_DISTINCT_ORDERED: {
  118568. VdbeOp *pOp; /* No longer required OpenEphemeral instr. */
  118569. int iJump; /* Jump destination */
  118570. int regPrev; /* Previous row content */
  118571. /* Allocate space for the previous row */
  118572. regPrev = pParse->nMem+1;
  118573. pParse->nMem += nResultCol;
  118574. /* Change the OP_OpenEphemeral coded earlier to an OP_Null
  118575. ** sets the MEM_Cleared bit on the first register of the
  118576. ** previous value. This will cause the OP_Ne below to always
  118577. ** fail on the first iteration of the loop even if the first
  118578. ** row is all NULLs.
  118579. */
  118580. sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
  118581. pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
  118582. pOp->opcode = OP_Null;
  118583. pOp->p1 = 1;
  118584. pOp->p2 = regPrev;
  118585. iJump = sqlite3VdbeCurrentAddr(v) + nResultCol;
  118586. for(i=0; i<nResultCol; i++){
  118587. CollSeq *pColl = sqlite3ExprCollSeq(pParse, p->pEList->a[i].pExpr);
  118588. if( i<nResultCol-1 ){
  118589. sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
  118590. VdbeCoverage(v);
  118591. }else{
  118592. sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
  118593. VdbeCoverage(v);
  118594. }
  118595. sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
  118596. sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
  118597. }
  118598. assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed );
  118599. sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1);
  118600. break;
  118601. }
  118602. case WHERE_DISTINCT_UNIQUE: {
  118603. sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
  118604. break;
  118605. }
  118606. default: {
  118607. assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
  118608. codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol,
  118609. regResult);
  118610. break;
  118611. }
  118612. }
  118613. if( pSort==0 ){
  118614. codeOffset(v, p->iOffset, iContinue);
  118615. }
  118616. }
  118617. switch( eDest ){
  118618. /* In this mode, write each query result to the key of the temporary
  118619. ** table iParm.
  118620. */
  118621. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  118622. case SRT_Union: {
  118623. int r1;
  118624. r1 = sqlite3GetTempReg(pParse);
  118625. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
  118626. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol);
  118627. sqlite3ReleaseTempReg(pParse, r1);
  118628. break;
  118629. }
  118630. /* Construct a record from the query result, but instead of
  118631. ** saving that record, use it as a key to delete elements from
  118632. ** the temporary table iParm.
  118633. */
  118634. case SRT_Except: {
  118635. sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol);
  118636. break;
  118637. }
  118638. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  118639. /* Store the result as data using a unique key.
  118640. */
  118641. case SRT_Fifo:
  118642. case SRT_DistFifo:
  118643. case SRT_Table:
  118644. case SRT_EphemTab: {
  118645. int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1);
  118646. testcase( eDest==SRT_Table );
  118647. testcase( eDest==SRT_EphemTab );
  118648. testcase( eDest==SRT_Fifo );
  118649. testcase( eDest==SRT_DistFifo );
  118650. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg);
  118651. #ifndef SQLITE_OMIT_CTE
  118652. if( eDest==SRT_DistFifo ){
  118653. /* If the destination is DistFifo, then cursor (iParm+1) is open
  118654. ** on an ephemeral index. If the current row is already present
  118655. ** in the index, do not write it to the output. If not, add the
  118656. ** current row to the index and proceed with writing it to the
  118657. ** output table as well. */
  118658. int addr = sqlite3VdbeCurrentAddr(v) + 4;
  118659. sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0);
  118660. VdbeCoverage(v);
  118661. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm+1, r1,regResult,nResultCol);
  118662. assert( pSort==0 );
  118663. }
  118664. #endif
  118665. if( pSort ){
  118666. assert( regResult==regOrig );
  118667. pushOntoSorter(pParse, pSort, p, r1+nPrefixReg, regOrig, 1, nPrefixReg);
  118668. }else{
  118669. int r2 = sqlite3GetTempReg(pParse);
  118670. sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
  118671. sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
  118672. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  118673. sqlite3ReleaseTempReg(pParse, r2);
  118674. }
  118675. sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1);
  118676. break;
  118677. }
  118678. #ifndef SQLITE_OMIT_SUBQUERY
  118679. /* If we are creating a set for an "expr IN (SELECT ...)" construct,
  118680. ** then there should be a single item on the stack. Write this
  118681. ** item into the set table with bogus data.
  118682. */
  118683. case SRT_Set: {
  118684. if( pSort ){
  118685. /* At first glance you would think we could optimize out the
  118686. ** ORDER BY in this case since the order of entries in the set
  118687. ** does not matter. But there might be a LIMIT clause, in which
  118688. ** case the order does matter */
  118689. pushOntoSorter(
  118690. pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);
  118691. }else{
  118692. int r1 = sqlite3GetTempReg(pParse);
  118693. assert( sqlite3Strlen30(pDest->zAffSdst)==nResultCol );
  118694. sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, nResultCol,
  118695. r1, pDest->zAffSdst, nResultCol);
  118696. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol);
  118697. sqlite3ReleaseTempReg(pParse, r1);
  118698. }
  118699. break;
  118700. }
  118701. /* If any row exist in the result set, record that fact and abort.
  118702. */
  118703. case SRT_Exists: {
  118704. sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
  118705. /* The LIMIT clause will terminate the loop for us */
  118706. break;
  118707. }
  118708. /* If this is a scalar select that is part of an expression, then
  118709. ** store the results in the appropriate memory cell or array of
  118710. ** memory cells and break out of the scan loop.
  118711. */
  118712. case SRT_Mem: {
  118713. if( pSort ){
  118714. assert( nResultCol<=pDest->nSdst );
  118715. pushOntoSorter(
  118716. pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);
  118717. }else{
  118718. assert( nResultCol==pDest->nSdst );
  118719. assert( regResult==iParm );
  118720. /* The LIMIT clause will jump out of the loop for us */
  118721. }
  118722. break;
  118723. }
  118724. #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
  118725. case SRT_Coroutine: /* Send data to a co-routine */
  118726. case SRT_Output: { /* Return the results */
  118727. testcase( eDest==SRT_Coroutine );
  118728. testcase( eDest==SRT_Output );
  118729. if( pSort ){
  118730. pushOntoSorter(pParse, pSort, p, regResult, regOrig, nResultCol,
  118731. nPrefixReg);
  118732. }else if( eDest==SRT_Coroutine ){
  118733. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  118734. }else{
  118735. sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol);
  118736. }
  118737. break;
  118738. }
  118739. #ifndef SQLITE_OMIT_CTE
  118740. /* Write the results into a priority queue that is order according to
  118741. ** pDest->pOrderBy (in pSO). pDest->iSDParm (in iParm) is the cursor for an
  118742. ** index with pSO->nExpr+2 columns. Build a key using pSO for the first
  118743. ** pSO->nExpr columns, then make sure all keys are unique by adding a
  118744. ** final OP_Sequence column. The last column is the record as a blob.
  118745. */
  118746. case SRT_DistQueue:
  118747. case SRT_Queue: {
  118748. int nKey;
  118749. int r1, r2, r3;
  118750. int addrTest = 0;
  118751. ExprList *pSO;
  118752. pSO = pDest->pOrderBy;
  118753. assert( pSO );
  118754. nKey = pSO->nExpr;
  118755. r1 = sqlite3GetTempReg(pParse);
  118756. r2 = sqlite3GetTempRange(pParse, nKey+2);
  118757. r3 = r2+nKey+1;
  118758. if( eDest==SRT_DistQueue ){
  118759. /* If the destination is DistQueue, then cursor (iParm+1) is open
  118760. ** on a second ephemeral index that holds all values every previously
  118761. ** added to the queue. */
  118762. addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0,
  118763. regResult, nResultCol);
  118764. VdbeCoverage(v);
  118765. }
  118766. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3);
  118767. if( eDest==SRT_DistQueue ){
  118768. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3);
  118769. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  118770. }
  118771. for(i=0; i<nKey; i++){
  118772. sqlite3VdbeAddOp2(v, OP_SCopy,
  118773. regResult + pSO->a[i].u.x.iOrderByCol - 1,
  118774. r2+i);
  118775. }
  118776. sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey);
  118777. sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1);
  118778. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, r2, nKey+2);
  118779. if( addrTest ) sqlite3VdbeJumpHere(v, addrTest);
  118780. sqlite3ReleaseTempReg(pParse, r1);
  118781. sqlite3ReleaseTempRange(pParse, r2, nKey+2);
  118782. break;
  118783. }
  118784. #endif /* SQLITE_OMIT_CTE */
  118785. #if !defined(SQLITE_OMIT_TRIGGER)
  118786. /* Discard the results. This is used for SELECT statements inside
  118787. ** the body of a TRIGGER. The purpose of such selects is to call
  118788. ** user-defined functions that have side effects. We do not care
  118789. ** about the actual results of the select.
  118790. */
  118791. default: {
  118792. assert( eDest==SRT_Discard );
  118793. break;
  118794. }
  118795. #endif
  118796. }
  118797. /* Jump to the end of the loop if the LIMIT is reached. Except, if
  118798. ** there is a sorter, in which case the sorter has already limited
  118799. ** the output for us.
  118800. */
  118801. if( pSort==0 && p->iLimit ){
  118802. sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
  118803. }
  118804. }
  118805. /*
  118806. ** Allocate a KeyInfo object sufficient for an index of N key columns and
  118807. ** X extra columns.
  118808. */
  118809. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){
  118810. int nExtra = (N+X)*(sizeof(CollSeq*)+1) - sizeof(CollSeq*);
  118811. KeyInfo *p = sqlite3DbMallocRawNN(db, sizeof(KeyInfo) + nExtra);
  118812. if( p ){
  118813. p->aSortOrder = (u8*)&p->aColl[N+X];
  118814. p->nKeyField = (u16)N;
  118815. p->nAllField = (u16)(N+X);
  118816. p->enc = ENC(db);
  118817. p->db = db;
  118818. p->nRef = 1;
  118819. memset(&p[1], 0, nExtra);
  118820. }else{
  118821. sqlite3OomFault(db);
  118822. }
  118823. return p;
  118824. }
  118825. /*
  118826. ** Deallocate a KeyInfo object
  118827. */
  118828. SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo *p){
  118829. if( p ){
  118830. assert( p->nRef>0 );
  118831. p->nRef--;
  118832. if( p->nRef==0 ) sqlite3DbFreeNN(p->db, p);
  118833. }
  118834. }
  118835. /*
  118836. ** Make a new pointer to a KeyInfo object
  118837. */
  118838. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){
  118839. if( p ){
  118840. assert( p->nRef>0 );
  118841. p->nRef++;
  118842. }
  118843. return p;
  118844. }
  118845. #ifdef SQLITE_DEBUG
  118846. /*
  118847. ** Return TRUE if a KeyInfo object can be change. The KeyInfo object
  118848. ** can only be changed if this is just a single reference to the object.
  118849. **
  118850. ** This routine is used only inside of assert() statements.
  118851. */
  118852. SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; }
  118853. #endif /* SQLITE_DEBUG */
  118854. /*
  118855. ** Given an expression list, generate a KeyInfo structure that records
  118856. ** the collating sequence for each expression in that expression list.
  118857. **
  118858. ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
  118859. ** KeyInfo structure is appropriate for initializing a virtual index to
  118860. ** implement that clause. If the ExprList is the result set of a SELECT
  118861. ** then the KeyInfo structure is appropriate for initializing a virtual
  118862. ** index to implement a DISTINCT test.
  118863. **
  118864. ** Space to hold the KeyInfo structure is obtained from malloc. The calling
  118865. ** function is responsible for seeing that this structure is eventually
  118866. ** freed.
  118867. */
  118868. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoFromExprList(
  118869. Parse *pParse, /* Parsing context */
  118870. ExprList *pList, /* Form the KeyInfo object from this ExprList */
  118871. int iStart, /* Begin with this column of pList */
  118872. int nExtra /* Add this many extra columns to the end */
  118873. ){
  118874. int nExpr;
  118875. KeyInfo *pInfo;
  118876. struct ExprList_item *pItem;
  118877. sqlite3 *db = pParse->db;
  118878. int i;
  118879. nExpr = pList->nExpr;
  118880. pInfo = sqlite3KeyInfoAlloc(db, nExpr-iStart, nExtra+1);
  118881. if( pInfo ){
  118882. assert( sqlite3KeyInfoIsWriteable(pInfo) );
  118883. for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){
  118884. pInfo->aColl[i-iStart] = sqlite3ExprNNCollSeq(pParse, pItem->pExpr);
  118885. pInfo->aSortOrder[i-iStart] = pItem->sortOrder;
  118886. }
  118887. }
  118888. return pInfo;
  118889. }
  118890. /*
  118891. ** Name of the connection operator, used for error messages.
  118892. */
  118893. static const char *selectOpName(int id){
  118894. char *z;
  118895. switch( id ){
  118896. case TK_ALL: z = "UNION ALL"; break;
  118897. case TK_INTERSECT: z = "INTERSECT"; break;
  118898. case TK_EXCEPT: z = "EXCEPT"; break;
  118899. default: z = "UNION"; break;
  118900. }
  118901. return z;
  118902. }
  118903. #ifndef SQLITE_OMIT_EXPLAIN
  118904. /*
  118905. ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
  118906. ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
  118907. ** where the caption is of the form:
  118908. **
  118909. ** "USE TEMP B-TREE FOR xxx"
  118910. **
  118911. ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
  118912. ** is determined by the zUsage argument.
  118913. */
  118914. static void explainTempTable(Parse *pParse, const char *zUsage){
  118915. ExplainQueryPlan((pParse, 0, "USE TEMP B-TREE FOR %s", zUsage));
  118916. }
  118917. /*
  118918. ** Assign expression b to lvalue a. A second, no-op, version of this macro
  118919. ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
  118920. ** in sqlite3Select() to assign values to structure member variables that
  118921. ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
  118922. ** code with #ifndef directives.
  118923. */
  118924. # define explainSetInteger(a, b) a = b
  118925. #else
  118926. /* No-op versions of the explainXXX() functions and macros. */
  118927. # define explainTempTable(y,z)
  118928. # define explainSetInteger(y,z)
  118929. #endif
  118930. /*
  118931. ** If the inner loop was generated using a non-null pOrderBy argument,
  118932. ** then the results were placed in a sorter. After the loop is terminated
  118933. ** we need to run the sorter and output the results. The following
  118934. ** routine generates the code needed to do that.
  118935. */
  118936. static void generateSortTail(
  118937. Parse *pParse, /* Parsing context */
  118938. Select *p, /* The SELECT statement */
  118939. SortCtx *pSort, /* Information on the ORDER BY clause */
  118940. int nColumn, /* Number of columns of data */
  118941. SelectDest *pDest /* Write the sorted results here */
  118942. ){
  118943. Vdbe *v = pParse->pVdbe; /* The prepared statement */
  118944. int addrBreak = pSort->labelDone; /* Jump here to exit loop */
  118945. int addrContinue = sqlite3VdbeMakeLabel(pParse);/* Jump here for next cycle */
  118946. int addr; /* Top of output loop. Jump for Next. */
  118947. int addrOnce = 0;
  118948. int iTab;
  118949. ExprList *pOrderBy = pSort->pOrderBy;
  118950. int eDest = pDest->eDest;
  118951. int iParm = pDest->iSDParm;
  118952. int regRow;
  118953. int regRowid;
  118954. int iCol;
  118955. int nKey; /* Number of key columns in sorter record */
  118956. int iSortTab; /* Sorter cursor to read from */
  118957. int i;
  118958. int bSeq; /* True if sorter record includes seq. no. */
  118959. int nRefKey = 0;
  118960. struct ExprList_item *aOutEx = p->pEList->a;
  118961. assert( addrBreak<0 );
  118962. if( pSort->labelBkOut ){
  118963. sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
  118964. sqlite3VdbeGoto(v, addrBreak);
  118965. sqlite3VdbeResolveLabel(v, pSort->labelBkOut);
  118966. }
  118967. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  118968. /* Open any cursors needed for sorter-reference expressions */
  118969. for(i=0; i<pSort->nDefer; i++){
  118970. Table *pTab = pSort->aDefer[i].pTab;
  118971. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  118972. sqlite3OpenTable(pParse, pSort->aDefer[i].iCsr, iDb, pTab, OP_OpenRead);
  118973. nRefKey = MAX(nRefKey, pSort->aDefer[i].nKey);
  118974. }
  118975. #endif
  118976. iTab = pSort->iECursor;
  118977. if( eDest==SRT_Output || eDest==SRT_Coroutine || eDest==SRT_Mem ){
  118978. regRowid = 0;
  118979. regRow = pDest->iSdst;
  118980. }else{
  118981. regRowid = sqlite3GetTempReg(pParse);
  118982. if( eDest==SRT_EphemTab || eDest==SRT_Table ){
  118983. regRow = sqlite3GetTempReg(pParse);
  118984. nColumn = 0;
  118985. }else{
  118986. regRow = sqlite3GetTempRange(pParse, nColumn);
  118987. }
  118988. }
  118989. nKey = pOrderBy->nExpr - pSort->nOBSat;
  118990. if( pSort->sortFlags & SORTFLAG_UseSorter ){
  118991. int regSortOut = ++pParse->nMem;
  118992. iSortTab = pParse->nTab++;
  118993. if( pSort->labelBkOut ){
  118994. addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  118995. }
  118996. sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut,
  118997. nKey+1+nColumn+nRefKey);
  118998. if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
  118999. addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
  119000. VdbeCoverage(v);
  119001. codeOffset(v, p->iOffset, addrContinue);
  119002. sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab);
  119003. bSeq = 0;
  119004. }else{
  119005. addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v);
  119006. codeOffset(v, p->iOffset, addrContinue);
  119007. iSortTab = iTab;
  119008. bSeq = 1;
  119009. }
  119010. for(i=0, iCol=nKey+bSeq-1; i<nColumn; i++){
  119011. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  119012. if( aOutEx[i].bSorterRef ) continue;
  119013. #endif
  119014. if( aOutEx[i].u.x.iOrderByCol==0 ) iCol++;
  119015. }
  119016. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  119017. if( pSort->nDefer ){
  119018. int iKey = iCol+1;
  119019. int regKey = sqlite3GetTempRange(pParse, nRefKey);
  119020. for(i=0; i<pSort->nDefer; i++){
  119021. int iCsr = pSort->aDefer[i].iCsr;
  119022. Table *pTab = pSort->aDefer[i].pTab;
  119023. int nKey = pSort->aDefer[i].nKey;
  119024. sqlite3VdbeAddOp1(v, OP_NullRow, iCsr);
  119025. if( HasRowid(pTab) ){
  119026. sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iKey++, regKey);
  119027. sqlite3VdbeAddOp3(v, OP_SeekRowid, iCsr,
  119028. sqlite3VdbeCurrentAddr(v)+1, regKey);
  119029. }else{
  119030. int k;
  119031. int iJmp;
  119032. assert( sqlite3PrimaryKeyIndex(pTab)->nKeyCol==nKey );
  119033. for(k=0; k<nKey; k++){
  119034. sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iKey++, regKey+k);
  119035. }
  119036. iJmp = sqlite3VdbeCurrentAddr(v);
  119037. sqlite3VdbeAddOp4Int(v, OP_SeekGE, iCsr, iJmp+2, regKey, nKey);
  119038. sqlite3VdbeAddOp4Int(v, OP_IdxLE, iCsr, iJmp+3, regKey, nKey);
  119039. sqlite3VdbeAddOp1(v, OP_NullRow, iCsr);
  119040. }
  119041. }
  119042. sqlite3ReleaseTempRange(pParse, regKey, nRefKey);
  119043. }
  119044. #endif
  119045. for(i=nColumn-1; i>=0; i--){
  119046. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  119047. if( aOutEx[i].bSorterRef ){
  119048. sqlite3ExprCode(pParse, aOutEx[i].pExpr, regRow+i);
  119049. }else
  119050. #endif
  119051. {
  119052. int iRead;
  119053. if( aOutEx[i].u.x.iOrderByCol ){
  119054. iRead = aOutEx[i].u.x.iOrderByCol-1;
  119055. }else{
  119056. iRead = iCol--;
  119057. }
  119058. sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iRead, regRow+i);
  119059. VdbeComment((v, "%s", aOutEx[i].zName?aOutEx[i].zName : aOutEx[i].zSpan));
  119060. }
  119061. }
  119062. switch( eDest ){
  119063. case SRT_Table:
  119064. case SRT_EphemTab: {
  119065. sqlite3VdbeAddOp3(v, OP_Column, iSortTab, nKey+bSeq, regRow);
  119066. sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
  119067. sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
  119068. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  119069. break;
  119070. }
  119071. #ifndef SQLITE_OMIT_SUBQUERY
  119072. case SRT_Set: {
  119073. assert( nColumn==sqlite3Strlen30(pDest->zAffSdst) );
  119074. sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, nColumn, regRowid,
  119075. pDest->zAffSdst, nColumn);
  119076. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, regRowid, regRow, nColumn);
  119077. break;
  119078. }
  119079. case SRT_Mem: {
  119080. /* The LIMIT clause will terminate the loop for us */
  119081. break;
  119082. }
  119083. #endif
  119084. default: {
  119085. assert( eDest==SRT_Output || eDest==SRT_Coroutine );
  119086. testcase( eDest==SRT_Output );
  119087. testcase( eDest==SRT_Coroutine );
  119088. if( eDest==SRT_Output ){
  119089. sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
  119090. }else{
  119091. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  119092. }
  119093. break;
  119094. }
  119095. }
  119096. if( regRowid ){
  119097. if( eDest==SRT_Set ){
  119098. sqlite3ReleaseTempRange(pParse, regRow, nColumn);
  119099. }else{
  119100. sqlite3ReleaseTempReg(pParse, regRow);
  119101. }
  119102. sqlite3ReleaseTempReg(pParse, regRowid);
  119103. }
  119104. /* The bottom of the loop
  119105. */
  119106. sqlite3VdbeResolveLabel(v, addrContinue);
  119107. if( pSort->sortFlags & SORTFLAG_UseSorter ){
  119108. sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v);
  119109. }else{
  119110. sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v);
  119111. }
  119112. if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn);
  119113. sqlite3VdbeResolveLabel(v, addrBreak);
  119114. }
  119115. /*
  119116. ** Return a pointer to a string containing the 'declaration type' of the
  119117. ** expression pExpr. The string may be treated as static by the caller.
  119118. **
  119119. ** Also try to estimate the size of the returned value and return that
  119120. ** result in *pEstWidth.
  119121. **
  119122. ** The declaration type is the exact datatype definition extracted from the
  119123. ** original CREATE TABLE statement if the expression is a column. The
  119124. ** declaration type for a ROWID field is INTEGER. Exactly when an expression
  119125. ** is considered a column can be complex in the presence of subqueries. The
  119126. ** result-set expression in all of the following SELECT statements is
  119127. ** considered a column by this function.
  119128. **
  119129. ** SELECT col FROM tbl;
  119130. ** SELECT (SELECT col FROM tbl;
  119131. ** SELECT (SELECT col FROM tbl);
  119132. ** SELECT abc FROM (SELECT col AS abc FROM tbl);
  119133. **
  119134. ** The declaration type for any expression other than a column is NULL.
  119135. **
  119136. ** This routine has either 3 or 6 parameters depending on whether or not
  119137. ** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
  119138. */
  119139. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  119140. # define columnType(A,B,C,D,E) columnTypeImpl(A,B,C,D,E)
  119141. #else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
  119142. # define columnType(A,B,C,D,E) columnTypeImpl(A,B)
  119143. #endif
  119144. static const char *columnTypeImpl(
  119145. NameContext *pNC,
  119146. #ifndef SQLITE_ENABLE_COLUMN_METADATA
  119147. Expr *pExpr
  119148. #else
  119149. Expr *pExpr,
  119150. const char **pzOrigDb,
  119151. const char **pzOrigTab,
  119152. const char **pzOrigCol
  119153. #endif
  119154. ){
  119155. char const *zType = 0;
  119156. int j;
  119157. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  119158. char const *zOrigDb = 0;
  119159. char const *zOrigTab = 0;
  119160. char const *zOrigCol = 0;
  119161. #endif
  119162. assert( pExpr!=0 );
  119163. assert( pNC->pSrcList!=0 );
  119164. assert( pExpr->op!=TK_AGG_COLUMN ); /* This routine runes before aggregates
  119165. ** are processed */
  119166. switch( pExpr->op ){
  119167. case TK_COLUMN: {
  119168. /* The expression is a column. Locate the table the column is being
  119169. ** extracted from in NameContext.pSrcList. This table may be real
  119170. ** database table or a subquery.
  119171. */
  119172. Table *pTab = 0; /* Table structure column is extracted from */
  119173. Select *pS = 0; /* Select the column is extracted from */
  119174. int iCol = pExpr->iColumn; /* Index of column in pTab */
  119175. while( pNC && !pTab ){
  119176. SrcList *pTabList = pNC->pSrcList;
  119177. for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
  119178. if( j<pTabList->nSrc ){
  119179. pTab = pTabList->a[j].pTab;
  119180. pS = pTabList->a[j].pSelect;
  119181. }else{
  119182. pNC = pNC->pNext;
  119183. }
  119184. }
  119185. if( pTab==0 ){
  119186. /* At one time, code such as "SELECT new.x" within a trigger would
  119187. ** cause this condition to run. Since then, we have restructured how
  119188. ** trigger code is generated and so this condition is no longer
  119189. ** possible. However, it can still be true for statements like
  119190. ** the following:
  119191. **
  119192. ** CREATE TABLE t1(col INTEGER);
  119193. ** SELECT (SELECT t1.col) FROM FROM t1;
  119194. **
  119195. ** when columnType() is called on the expression "t1.col" in the
  119196. ** sub-select. In this case, set the column type to NULL, even
  119197. ** though it should really be "INTEGER".
  119198. **
  119199. ** This is not a problem, as the column type of "t1.col" is never
  119200. ** used. When columnType() is called on the expression
  119201. ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
  119202. ** branch below. */
  119203. break;
  119204. }
  119205. assert( pTab && pExpr->y.pTab==pTab );
  119206. if( pS ){
  119207. /* The "table" is actually a sub-select or a view in the FROM clause
  119208. ** of the SELECT statement. Return the declaration type and origin
  119209. ** data for the result-set column of the sub-select.
  119210. */
  119211. if( iCol>=0 && iCol<pS->pEList->nExpr ){
  119212. /* If iCol is less than zero, then the expression requests the
  119213. ** rowid of the sub-select or view. This expression is legal (see
  119214. ** test case misc2.2.2) - it always evaluates to NULL.
  119215. */
  119216. NameContext sNC;
  119217. Expr *p = pS->pEList->a[iCol].pExpr;
  119218. sNC.pSrcList = pS->pSrc;
  119219. sNC.pNext = pNC;
  119220. sNC.pParse = pNC->pParse;
  119221. zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol);
  119222. }
  119223. }else{
  119224. /* A real table or a CTE table */
  119225. assert( !pS );
  119226. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  119227. if( iCol<0 ) iCol = pTab->iPKey;
  119228. assert( iCol==XN_ROWID || (iCol>=0 && iCol<pTab->nCol) );
  119229. if( iCol<0 ){
  119230. zType = "INTEGER";
  119231. zOrigCol = "rowid";
  119232. }else{
  119233. zOrigCol = pTab->aCol[iCol].zName;
  119234. zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
  119235. }
  119236. zOrigTab = pTab->zName;
  119237. if( pNC->pParse && pTab->pSchema ){
  119238. int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
  119239. zOrigDb = pNC->pParse->db->aDb[iDb].zDbSName;
  119240. }
  119241. #else
  119242. assert( iCol==XN_ROWID || (iCol>=0 && iCol<pTab->nCol) );
  119243. if( iCol<0 ){
  119244. zType = "INTEGER";
  119245. }else{
  119246. zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
  119247. }
  119248. #endif
  119249. }
  119250. break;
  119251. }
  119252. #ifndef SQLITE_OMIT_SUBQUERY
  119253. case TK_SELECT: {
  119254. /* The expression is a sub-select. Return the declaration type and
  119255. ** origin info for the single column in the result set of the SELECT
  119256. ** statement.
  119257. */
  119258. NameContext sNC;
  119259. Select *pS = pExpr->x.pSelect;
  119260. Expr *p = pS->pEList->a[0].pExpr;
  119261. assert( ExprHasProperty(pExpr, EP_xIsSelect) );
  119262. sNC.pSrcList = pS->pSrc;
  119263. sNC.pNext = pNC;
  119264. sNC.pParse = pNC->pParse;
  119265. zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
  119266. break;
  119267. }
  119268. #endif
  119269. }
  119270. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  119271. if( pzOrigDb ){
  119272. assert( pzOrigTab && pzOrigCol );
  119273. *pzOrigDb = zOrigDb;
  119274. *pzOrigTab = zOrigTab;
  119275. *pzOrigCol = zOrigCol;
  119276. }
  119277. #endif
  119278. return zType;
  119279. }
  119280. /*
  119281. ** Generate code that will tell the VDBE the declaration types of columns
  119282. ** in the result set.
  119283. */
  119284. static void generateColumnTypes(
  119285. Parse *pParse, /* Parser context */
  119286. SrcList *pTabList, /* List of tables */
  119287. ExprList *pEList /* Expressions defining the result set */
  119288. ){
  119289. #ifndef SQLITE_OMIT_DECLTYPE
  119290. Vdbe *v = pParse->pVdbe;
  119291. int i;
  119292. NameContext sNC;
  119293. sNC.pSrcList = pTabList;
  119294. sNC.pParse = pParse;
  119295. sNC.pNext = 0;
  119296. for(i=0; i<pEList->nExpr; i++){
  119297. Expr *p = pEList->a[i].pExpr;
  119298. const char *zType;
  119299. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  119300. const char *zOrigDb = 0;
  119301. const char *zOrigTab = 0;
  119302. const char *zOrigCol = 0;
  119303. zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
  119304. /* The vdbe must make its own copy of the column-type and other
  119305. ** column specific strings, in case the schema is reset before this
  119306. ** virtual machine is deleted.
  119307. */
  119308. sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
  119309. sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
  119310. sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
  119311. #else
  119312. zType = columnType(&sNC, p, 0, 0, 0);
  119313. #endif
  119314. sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
  119315. }
  119316. #endif /* !defined(SQLITE_OMIT_DECLTYPE) */
  119317. }
  119318. /*
  119319. ** Compute the column names for a SELECT statement.
  119320. **
  119321. ** The only guarantee that SQLite makes about column names is that if the
  119322. ** column has an AS clause assigning it a name, that will be the name used.
  119323. ** That is the only documented guarantee. However, countless applications
  119324. ** developed over the years have made baseless assumptions about column names
  119325. ** and will break if those assumptions changes. Hence, use extreme caution
  119326. ** when modifying this routine to avoid breaking legacy.
  119327. **
  119328. ** See Also: sqlite3ColumnsFromExprList()
  119329. **
  119330. ** The PRAGMA short_column_names and PRAGMA full_column_names settings are
  119331. ** deprecated. The default setting is short=ON, full=OFF. 99.9% of all
  119332. ** applications should operate this way. Nevertheless, we need to support the
  119333. ** other modes for legacy:
  119334. **
  119335. ** short=OFF, full=OFF: Column name is the text of the expression has it
  119336. ** originally appears in the SELECT statement. In
  119337. ** other words, the zSpan of the result expression.
  119338. **
  119339. ** short=ON, full=OFF: (This is the default setting). If the result
  119340. ** refers directly to a table column, then the
  119341. ** result column name is just the table column
  119342. ** name: COLUMN. Otherwise use zSpan.
  119343. **
  119344. ** full=ON, short=ANY: If the result refers directly to a table column,
  119345. ** then the result column name with the table name
  119346. ** prefix, ex: TABLE.COLUMN. Otherwise use zSpan.
  119347. */
  119348. static void generateColumnNames(
  119349. Parse *pParse, /* Parser context */
  119350. Select *pSelect /* Generate column names for this SELECT statement */
  119351. ){
  119352. Vdbe *v = pParse->pVdbe;
  119353. int i;
  119354. Table *pTab;
  119355. SrcList *pTabList;
  119356. ExprList *pEList;
  119357. sqlite3 *db = pParse->db;
  119358. int fullName; /* TABLE.COLUMN if no AS clause and is a direct table ref */
  119359. int srcName; /* COLUMN or TABLE.COLUMN if no AS clause and is direct */
  119360. #ifndef SQLITE_OMIT_EXPLAIN
  119361. /* If this is an EXPLAIN, skip this step */
  119362. if( pParse->explain ){
  119363. return;
  119364. }
  119365. #endif
  119366. if( pParse->colNamesSet ) return;
  119367. /* Column names are determined by the left-most term of a compound select */
  119368. while( pSelect->pPrior ) pSelect = pSelect->pPrior;
  119369. SELECTTRACE(1,pParse,pSelect,("generating column names\n"));
  119370. pTabList = pSelect->pSrc;
  119371. pEList = pSelect->pEList;
  119372. assert( v!=0 );
  119373. assert( pTabList!=0 );
  119374. pParse->colNamesSet = 1;
  119375. fullName = (db->flags & SQLITE_FullColNames)!=0;
  119376. srcName = (db->flags & SQLITE_ShortColNames)!=0 || fullName;
  119377. sqlite3VdbeSetNumCols(v, pEList->nExpr);
  119378. for(i=0; i<pEList->nExpr; i++){
  119379. Expr *p = pEList->a[i].pExpr;
  119380. assert( p!=0 );
  119381. assert( p->op!=TK_AGG_COLUMN ); /* Agg processing has not run yet */
  119382. assert( p->op!=TK_COLUMN || p->y.pTab!=0 ); /* Covering idx not yet coded */
  119383. if( pEList->a[i].zName ){
  119384. /* An AS clause always takes first priority */
  119385. char *zName = pEList->a[i].zName;
  119386. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
  119387. }else if( srcName && p->op==TK_COLUMN ){
  119388. char *zCol;
  119389. int iCol = p->iColumn;
  119390. pTab = p->y.pTab;
  119391. assert( pTab!=0 );
  119392. if( iCol<0 ) iCol = pTab->iPKey;
  119393. assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
  119394. if( iCol<0 ){
  119395. zCol = "rowid";
  119396. }else{
  119397. zCol = pTab->aCol[iCol].zName;
  119398. }
  119399. if( fullName ){
  119400. char *zName = 0;
  119401. zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
  119402. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
  119403. }else{
  119404. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
  119405. }
  119406. }else{
  119407. const char *z = pEList->a[i].zSpan;
  119408. z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z);
  119409. sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC);
  119410. }
  119411. }
  119412. generateColumnTypes(pParse, pTabList, pEList);
  119413. }
  119414. /*
  119415. ** Given an expression list (which is really the list of expressions
  119416. ** that form the result set of a SELECT statement) compute appropriate
  119417. ** column names for a table that would hold the expression list.
  119418. **
  119419. ** All column names will be unique.
  119420. **
  119421. ** Only the column names are computed. Column.zType, Column.zColl,
  119422. ** and other fields of Column are zeroed.
  119423. **
  119424. ** Return SQLITE_OK on success. If a memory allocation error occurs,
  119425. ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
  119426. **
  119427. ** The only guarantee that SQLite makes about column names is that if the
  119428. ** column has an AS clause assigning it a name, that will be the name used.
  119429. ** That is the only documented guarantee. However, countless applications
  119430. ** developed over the years have made baseless assumptions about column names
  119431. ** and will break if those assumptions changes. Hence, use extreme caution
  119432. ** when modifying this routine to avoid breaking legacy.
  119433. **
  119434. ** See Also: generateColumnNames()
  119435. */
  119436. SQLITE_PRIVATE int sqlite3ColumnsFromExprList(
  119437. Parse *pParse, /* Parsing context */
  119438. ExprList *pEList, /* Expr list from which to derive column names */
  119439. i16 *pnCol, /* Write the number of columns here */
  119440. Column **paCol /* Write the new column list here */
  119441. ){
  119442. sqlite3 *db = pParse->db; /* Database connection */
  119443. int i, j; /* Loop counters */
  119444. u32 cnt; /* Index added to make the name unique */
  119445. Column *aCol, *pCol; /* For looping over result columns */
  119446. int nCol; /* Number of columns in the result set */
  119447. char *zName; /* Column name */
  119448. int nName; /* Size of name in zName[] */
  119449. Hash ht; /* Hash table of column names */
  119450. sqlite3HashInit(&ht);
  119451. if( pEList ){
  119452. nCol = pEList->nExpr;
  119453. aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
  119454. testcase( aCol==0 );
  119455. if( nCol>32767 ) nCol = 32767;
  119456. }else{
  119457. nCol = 0;
  119458. aCol = 0;
  119459. }
  119460. assert( nCol==(i16)nCol );
  119461. *pnCol = nCol;
  119462. *paCol = aCol;
  119463. for(i=0, pCol=aCol; i<nCol && !db->mallocFailed; i++, pCol++){
  119464. /* Get an appropriate name for the column
  119465. */
  119466. if( (zName = pEList->a[i].zName)!=0 ){
  119467. /* If the column contains an "AS <name>" phrase, use <name> as the name */
  119468. }else{
  119469. Expr *pColExpr = sqlite3ExprSkipCollate(pEList->a[i].pExpr);
  119470. while( pColExpr->op==TK_DOT ){
  119471. pColExpr = pColExpr->pRight;
  119472. assert( pColExpr!=0 );
  119473. }
  119474. assert( pColExpr->op!=TK_AGG_COLUMN );
  119475. if( pColExpr->op==TK_COLUMN ){
  119476. /* For columns use the column name name */
  119477. int iCol = pColExpr->iColumn;
  119478. Table *pTab = pColExpr->y.pTab;
  119479. assert( pTab!=0 );
  119480. if( iCol<0 ) iCol = pTab->iPKey;
  119481. zName = iCol>=0 ? pTab->aCol[iCol].zName : "rowid";
  119482. }else if( pColExpr->op==TK_ID ){
  119483. assert( !ExprHasProperty(pColExpr, EP_IntValue) );
  119484. zName = pColExpr->u.zToken;
  119485. }else{
  119486. /* Use the original text of the column expression as its name */
  119487. zName = pEList->a[i].zSpan;
  119488. }
  119489. }
  119490. if( zName ){
  119491. zName = sqlite3DbStrDup(db, zName);
  119492. }else{
  119493. zName = sqlite3MPrintf(db,"column%d",i+1);
  119494. }
  119495. /* Make sure the column name is unique. If the name is not unique,
  119496. ** append an integer to the name so that it becomes unique.
  119497. */
  119498. cnt = 0;
  119499. while( zName && sqlite3HashFind(&ht, zName)!=0 ){
  119500. nName = sqlite3Strlen30(zName);
  119501. if( nName>0 ){
  119502. for(j=nName-1; j>0 && sqlite3Isdigit(zName[j]); j--){}
  119503. if( zName[j]==':' ) nName = j;
  119504. }
  119505. zName = sqlite3MPrintf(db, "%.*z:%u", nName, zName, ++cnt);
  119506. if( cnt>3 ) sqlite3_randomness(sizeof(cnt), &cnt);
  119507. }
  119508. pCol->zName = zName;
  119509. sqlite3ColumnPropertiesFromName(0, pCol);
  119510. if( zName && sqlite3HashInsert(&ht, zName, pCol)==pCol ){
  119511. sqlite3OomFault(db);
  119512. }
  119513. }
  119514. sqlite3HashClear(&ht);
  119515. if( db->mallocFailed ){
  119516. for(j=0; j<i; j++){
  119517. sqlite3DbFree(db, aCol[j].zName);
  119518. }
  119519. sqlite3DbFree(db, aCol);
  119520. *paCol = 0;
  119521. *pnCol = 0;
  119522. return SQLITE_NOMEM_BKPT;
  119523. }
  119524. return SQLITE_OK;
  119525. }
  119526. /*
  119527. ** Add type and collation information to a column list based on
  119528. ** a SELECT statement.
  119529. **
  119530. ** The column list presumably came from selectColumnNamesFromExprList().
  119531. ** The column list has only names, not types or collations. This
  119532. ** routine goes through and adds the types and collations.
  119533. **
  119534. ** This routine requires that all identifiers in the SELECT
  119535. ** statement be resolved.
  119536. */
  119537. SQLITE_PRIVATE void sqlite3SelectAddColumnTypeAndCollation(
  119538. Parse *pParse, /* Parsing contexts */
  119539. Table *pTab, /* Add column type information to this table */
  119540. Select *pSelect /* SELECT used to determine types and collations */
  119541. ){
  119542. sqlite3 *db = pParse->db;
  119543. NameContext sNC;
  119544. Column *pCol;
  119545. CollSeq *pColl;
  119546. int i;
  119547. Expr *p;
  119548. struct ExprList_item *a;
  119549. assert( pSelect!=0 );
  119550. assert( (pSelect->selFlags & SF_Resolved)!=0 );
  119551. assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed );
  119552. if( db->mallocFailed ) return;
  119553. memset(&sNC, 0, sizeof(sNC));
  119554. sNC.pSrcList = pSelect->pSrc;
  119555. a = pSelect->pEList->a;
  119556. for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
  119557. const char *zType;
  119558. int n, m;
  119559. p = a[i].pExpr;
  119560. zType = columnType(&sNC, p, 0, 0, 0);
  119561. /* pCol->szEst = ... // Column size est for SELECT tables never used */
  119562. pCol->affinity = sqlite3ExprAffinity(p);
  119563. if( zType ){
  119564. m = sqlite3Strlen30(zType);
  119565. n = sqlite3Strlen30(pCol->zName);
  119566. pCol->zName = sqlite3DbReallocOrFree(db, pCol->zName, n+m+2);
  119567. if( pCol->zName ){
  119568. memcpy(&pCol->zName[n+1], zType, m+1);
  119569. pCol->colFlags |= COLFLAG_HASTYPE;
  119570. }
  119571. }
  119572. if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_BLOB;
  119573. pColl = sqlite3ExprCollSeq(pParse, p);
  119574. if( pColl && pCol->zColl==0 ){
  119575. pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
  119576. }
  119577. }
  119578. pTab->szTabRow = 1; /* Any non-zero value works */
  119579. }
  119580. /*
  119581. ** Given a SELECT statement, generate a Table structure that describes
  119582. ** the result set of that SELECT.
  119583. */
  119584. SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
  119585. Table *pTab;
  119586. sqlite3 *db = pParse->db;
  119587. u64 savedFlags;
  119588. savedFlags = db->flags;
  119589. db->flags &= ~(u64)SQLITE_FullColNames;
  119590. db->flags |= SQLITE_ShortColNames;
  119591. sqlite3SelectPrep(pParse, pSelect, 0);
  119592. db->flags = savedFlags;
  119593. if( pParse->nErr ) return 0;
  119594. while( pSelect->pPrior ) pSelect = pSelect->pPrior;
  119595. pTab = sqlite3DbMallocZero(db, sizeof(Table) );
  119596. if( pTab==0 ){
  119597. return 0;
  119598. }
  119599. pTab->nTabRef = 1;
  119600. pTab->zName = 0;
  119601. pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  119602. sqlite3ColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
  119603. sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSelect);
  119604. pTab->iPKey = -1;
  119605. if( db->mallocFailed ){
  119606. sqlite3DeleteTable(db, pTab);
  119607. return 0;
  119608. }
  119609. return pTab;
  119610. }
  119611. /*
  119612. ** Get a VDBE for the given parser context. Create a new one if necessary.
  119613. ** If an error occurs, return NULL and leave a message in pParse.
  119614. */
  119615. SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
  119616. if( pParse->pVdbe ){
  119617. return pParse->pVdbe;
  119618. }
  119619. if( pParse->pToplevel==0
  119620. && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst)
  119621. ){
  119622. pParse->okConstFactor = 1;
  119623. }
  119624. return sqlite3VdbeCreate(pParse);
  119625. }
  119626. /*
  119627. ** Compute the iLimit and iOffset fields of the SELECT based on the
  119628. ** pLimit expressions. pLimit->pLeft and pLimit->pRight hold the expressions
  119629. ** that appear in the original SQL statement after the LIMIT and OFFSET
  119630. ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset
  119631. ** are the integer memory register numbers for counters used to compute
  119632. ** the limit and offset. If there is no limit and/or offset, then
  119633. ** iLimit and iOffset are negative.
  119634. **
  119635. ** This routine changes the values of iLimit and iOffset only if
  119636. ** a limit or offset is defined by pLimit->pLeft and pLimit->pRight. iLimit
  119637. ** and iOffset should have been preset to appropriate default values (zero)
  119638. ** prior to calling this routine.
  119639. **
  119640. ** The iOffset register (if it exists) is initialized to the value
  119641. ** of the OFFSET. The iLimit register is initialized to LIMIT. Register
  119642. ** iOffset+1 is initialized to LIMIT+OFFSET.
  119643. **
  119644. ** Only if pLimit->pLeft!=0 do the limit registers get
  119645. ** redefined. The UNION ALL operator uses this property to force
  119646. ** the reuse of the same limit and offset registers across multiple
  119647. ** SELECT statements.
  119648. */
  119649. static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
  119650. Vdbe *v = 0;
  119651. int iLimit = 0;
  119652. int iOffset;
  119653. int n;
  119654. Expr *pLimit = p->pLimit;
  119655. if( p->iLimit ) return;
  119656. /*
  119657. ** "LIMIT -1" always shows all rows. There is some
  119658. ** controversy about what the correct behavior should be.
  119659. ** The current implementation interprets "LIMIT 0" to mean
  119660. ** no rows.
  119661. */
  119662. if( pLimit ){
  119663. assert( pLimit->op==TK_LIMIT );
  119664. assert( pLimit->pLeft!=0 );
  119665. p->iLimit = iLimit = ++pParse->nMem;
  119666. v = sqlite3GetVdbe(pParse);
  119667. assert( v!=0 );
  119668. if( sqlite3ExprIsInteger(pLimit->pLeft, &n) ){
  119669. sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
  119670. VdbeComment((v, "LIMIT counter"));
  119671. if( n==0 ){
  119672. sqlite3VdbeGoto(v, iBreak);
  119673. }else if( n>=0 && p->nSelectRow>sqlite3LogEst((u64)n) ){
  119674. p->nSelectRow = sqlite3LogEst((u64)n);
  119675. p->selFlags |= SF_FixedLimit;
  119676. }
  119677. }else{
  119678. sqlite3ExprCode(pParse, pLimit->pLeft, iLimit);
  119679. sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v);
  119680. VdbeComment((v, "LIMIT counter"));
  119681. sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, iBreak); VdbeCoverage(v);
  119682. }
  119683. if( pLimit->pRight ){
  119684. p->iOffset = iOffset = ++pParse->nMem;
  119685. pParse->nMem++; /* Allocate an extra register for limit+offset */
  119686. sqlite3ExprCode(pParse, pLimit->pRight, iOffset);
  119687. sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v);
  119688. VdbeComment((v, "OFFSET counter"));
  119689. sqlite3VdbeAddOp3(v, OP_OffsetLimit, iLimit, iOffset+1, iOffset);
  119690. VdbeComment((v, "LIMIT+OFFSET"));
  119691. }
  119692. }
  119693. }
  119694. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  119695. /*
  119696. ** Return the appropriate collating sequence for the iCol-th column of
  119697. ** the result set for the compound-select statement "p". Return NULL if
  119698. ** the column has no default collating sequence.
  119699. **
  119700. ** The collating sequence for the compound select is taken from the
  119701. ** left-most term of the select that has a collating sequence.
  119702. */
  119703. static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
  119704. CollSeq *pRet;
  119705. if( p->pPrior ){
  119706. pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
  119707. }else{
  119708. pRet = 0;
  119709. }
  119710. assert( iCol>=0 );
  119711. /* iCol must be less than p->pEList->nExpr. Otherwise an error would
  119712. ** have been thrown during name resolution and we would not have gotten
  119713. ** this far */
  119714. if( pRet==0 && ALWAYS(iCol<p->pEList->nExpr) ){
  119715. pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
  119716. }
  119717. return pRet;
  119718. }
  119719. /*
  119720. ** The select statement passed as the second parameter is a compound SELECT
  119721. ** with an ORDER BY clause. This function allocates and returns a KeyInfo
  119722. ** structure suitable for implementing the ORDER BY.
  119723. **
  119724. ** Space to hold the KeyInfo structure is obtained from malloc. The calling
  119725. ** function is responsible for ensuring that this structure is eventually
  119726. ** freed.
  119727. */
  119728. static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){
  119729. ExprList *pOrderBy = p->pOrderBy;
  119730. int nOrderBy = p->pOrderBy->nExpr;
  119731. sqlite3 *db = pParse->db;
  119732. KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1);
  119733. if( pRet ){
  119734. int i;
  119735. for(i=0; i<nOrderBy; i++){
  119736. struct ExprList_item *pItem = &pOrderBy->a[i];
  119737. Expr *pTerm = pItem->pExpr;
  119738. CollSeq *pColl;
  119739. if( pTerm->flags & EP_Collate ){
  119740. pColl = sqlite3ExprCollSeq(pParse, pTerm);
  119741. }else{
  119742. pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1);
  119743. if( pColl==0 ) pColl = db->pDfltColl;
  119744. pOrderBy->a[i].pExpr =
  119745. sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
  119746. }
  119747. assert( sqlite3KeyInfoIsWriteable(pRet) );
  119748. pRet->aColl[i] = pColl;
  119749. pRet->aSortOrder[i] = pOrderBy->a[i].sortOrder;
  119750. }
  119751. }
  119752. return pRet;
  119753. }
  119754. #ifndef SQLITE_OMIT_CTE
  119755. /*
  119756. ** This routine generates VDBE code to compute the content of a WITH RECURSIVE
  119757. ** query of the form:
  119758. **
  119759. ** <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>)
  119760. ** \___________/ \_______________/
  119761. ** p->pPrior p
  119762. **
  119763. **
  119764. ** There is exactly one reference to the recursive-table in the FROM clause
  119765. ** of recursive-query, marked with the SrcList->a[].fg.isRecursive flag.
  119766. **
  119767. ** The setup-query runs once to generate an initial set of rows that go
  119768. ** into a Queue table. Rows are extracted from the Queue table one by
  119769. ** one. Each row extracted from Queue is output to pDest. Then the single
  119770. ** extracted row (now in the iCurrent table) becomes the content of the
  119771. ** recursive-table for a recursive-query run. The output of the recursive-query
  119772. ** is added back into the Queue table. Then another row is extracted from Queue
  119773. ** and the iteration continues until the Queue table is empty.
  119774. **
  119775. ** If the compound query operator is UNION then no duplicate rows are ever
  119776. ** inserted into the Queue table. The iDistinct table keeps a copy of all rows
  119777. ** that have ever been inserted into Queue and causes duplicates to be
  119778. ** discarded. If the operator is UNION ALL, then duplicates are allowed.
  119779. **
  119780. ** If the query has an ORDER BY, then entries in the Queue table are kept in
  119781. ** ORDER BY order and the first entry is extracted for each cycle. Without
  119782. ** an ORDER BY, the Queue table is just a FIFO.
  119783. **
  119784. ** If a LIMIT clause is provided, then the iteration stops after LIMIT rows
  119785. ** have been output to pDest. A LIMIT of zero means to output no rows and a
  119786. ** negative LIMIT means to output all rows. If there is also an OFFSET clause
  119787. ** with a positive value, then the first OFFSET outputs are discarded rather
  119788. ** than being sent to pDest. The LIMIT count does not begin until after OFFSET
  119789. ** rows have been skipped.
  119790. */
  119791. static void generateWithRecursiveQuery(
  119792. Parse *pParse, /* Parsing context */
  119793. Select *p, /* The recursive SELECT to be coded */
  119794. SelectDest *pDest /* What to do with query results */
  119795. ){
  119796. SrcList *pSrc = p->pSrc; /* The FROM clause of the recursive query */
  119797. int nCol = p->pEList->nExpr; /* Number of columns in the recursive table */
  119798. Vdbe *v = pParse->pVdbe; /* The prepared statement under construction */
  119799. Select *pSetup = p->pPrior; /* The setup query */
  119800. int addrTop; /* Top of the loop */
  119801. int addrCont, addrBreak; /* CONTINUE and BREAK addresses */
  119802. int iCurrent = 0; /* The Current table */
  119803. int regCurrent; /* Register holding Current table */
  119804. int iQueue; /* The Queue table */
  119805. int iDistinct = 0; /* To ensure unique results if UNION */
  119806. int eDest = SRT_Fifo; /* How to write to Queue */
  119807. SelectDest destQueue; /* SelectDest targetting the Queue table */
  119808. int i; /* Loop counter */
  119809. int rc; /* Result code */
  119810. ExprList *pOrderBy; /* The ORDER BY clause */
  119811. Expr *pLimit; /* Saved LIMIT and OFFSET */
  119812. int regLimit, regOffset; /* Registers used by LIMIT and OFFSET */
  119813. #ifndef SQLITE_OMIT_WINDOWFUNC
  119814. if( p->pWin ){
  119815. sqlite3ErrorMsg(pParse, "cannot use window functions in recursive queries");
  119816. return;
  119817. }
  119818. #endif
  119819. /* Obtain authorization to do a recursive query */
  119820. if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return;
  119821. /* Process the LIMIT and OFFSET clauses, if they exist */
  119822. addrBreak = sqlite3VdbeMakeLabel(pParse);
  119823. p->nSelectRow = 320; /* 4 billion rows */
  119824. computeLimitRegisters(pParse, p, addrBreak);
  119825. pLimit = p->pLimit;
  119826. regLimit = p->iLimit;
  119827. regOffset = p->iOffset;
  119828. p->pLimit = 0;
  119829. p->iLimit = p->iOffset = 0;
  119830. pOrderBy = p->pOrderBy;
  119831. /* Locate the cursor number of the Current table */
  119832. for(i=0; ALWAYS(i<pSrc->nSrc); i++){
  119833. if( pSrc->a[i].fg.isRecursive ){
  119834. iCurrent = pSrc->a[i].iCursor;
  119835. break;
  119836. }
  119837. }
  119838. /* Allocate cursors numbers for Queue and Distinct. The cursor number for
  119839. ** the Distinct table must be exactly one greater than Queue in order
  119840. ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */
  119841. iQueue = pParse->nTab++;
  119842. if( p->op==TK_UNION ){
  119843. eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo;
  119844. iDistinct = pParse->nTab++;
  119845. }else{
  119846. eDest = pOrderBy ? SRT_Queue : SRT_Fifo;
  119847. }
  119848. sqlite3SelectDestInit(&destQueue, eDest, iQueue);
  119849. /* Allocate cursors for Current, Queue, and Distinct. */
  119850. regCurrent = ++pParse->nMem;
  119851. sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol);
  119852. if( pOrderBy ){
  119853. KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1);
  119854. sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0,
  119855. (char*)pKeyInfo, P4_KEYINFO);
  119856. destQueue.pOrderBy = pOrderBy;
  119857. }else{
  119858. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol);
  119859. }
  119860. VdbeComment((v, "Queue table"));
  119861. if( iDistinct ){
  119862. p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0);
  119863. p->selFlags |= SF_UsesEphemeral;
  119864. }
  119865. /* Detach the ORDER BY clause from the compound SELECT */
  119866. p->pOrderBy = 0;
  119867. /* Store the results of the setup-query in Queue. */
  119868. pSetup->pNext = 0;
  119869. ExplainQueryPlan((pParse, 1, "SETUP"));
  119870. rc = sqlite3Select(pParse, pSetup, &destQueue);
  119871. pSetup->pNext = p;
  119872. if( rc ) goto end_of_recursive_query;
  119873. /* Find the next row in the Queue and output that row */
  119874. addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v);
  119875. /* Transfer the next row in Queue over to Current */
  119876. sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */
  119877. if( pOrderBy ){
  119878. sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);
  119879. }else{
  119880. sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent);
  119881. }
  119882. sqlite3VdbeAddOp1(v, OP_Delete, iQueue);
  119883. /* Output the single row in Current */
  119884. addrCont = sqlite3VdbeMakeLabel(pParse);
  119885. codeOffset(v, regOffset, addrCont);
  119886. selectInnerLoop(pParse, p, iCurrent,
  119887. 0, 0, pDest, addrCont, addrBreak);
  119888. if( regLimit ){
  119889. sqlite3VdbeAddOp2(v, OP_DecrJumpZero, regLimit, addrBreak);
  119890. VdbeCoverage(v);
  119891. }
  119892. sqlite3VdbeResolveLabel(v, addrCont);
  119893. /* Execute the recursive SELECT taking the single row in Current as
  119894. ** the value for the recursive-table. Store the results in the Queue.
  119895. */
  119896. if( p->selFlags & SF_Aggregate ){
  119897. sqlite3ErrorMsg(pParse, "recursive aggregate queries not supported");
  119898. }else{
  119899. p->pPrior = 0;
  119900. ExplainQueryPlan((pParse, 1, "RECURSIVE STEP"));
  119901. sqlite3Select(pParse, p, &destQueue);
  119902. assert( p->pPrior==0 );
  119903. p->pPrior = pSetup;
  119904. }
  119905. /* Keep running the loop until the Queue is empty */
  119906. sqlite3VdbeGoto(v, addrTop);
  119907. sqlite3VdbeResolveLabel(v, addrBreak);
  119908. end_of_recursive_query:
  119909. sqlite3ExprListDelete(pParse->db, p->pOrderBy);
  119910. p->pOrderBy = pOrderBy;
  119911. p->pLimit = pLimit;
  119912. return;
  119913. }
  119914. #endif /* SQLITE_OMIT_CTE */
  119915. /* Forward references */
  119916. static int multiSelectOrderBy(
  119917. Parse *pParse, /* Parsing context */
  119918. Select *p, /* The right-most of SELECTs to be coded */
  119919. SelectDest *pDest /* What to do with query results */
  119920. );
  119921. /*
  119922. ** Handle the special case of a compound-select that originates from a
  119923. ** VALUES clause. By handling this as a special case, we avoid deep
  119924. ** recursion, and thus do not need to enforce the SQLITE_LIMIT_COMPOUND_SELECT
  119925. ** on a VALUES clause.
  119926. **
  119927. ** Because the Select object originates from a VALUES clause:
  119928. ** (1) There is no LIMIT or OFFSET or else there is a LIMIT of exactly 1
  119929. ** (2) All terms are UNION ALL
  119930. ** (3) There is no ORDER BY clause
  119931. **
  119932. ** The "LIMIT of exactly 1" case of condition (1) comes about when a VALUES
  119933. ** clause occurs within scalar expression (ex: "SELECT (VALUES(1),(2),(3))").
  119934. ** The sqlite3CodeSubselect will have added the LIMIT 1 clause in tht case.
  119935. ** Since the limit is exactly 1, we only need to evalutes the left-most VALUES.
  119936. */
  119937. static int multiSelectValues(
  119938. Parse *pParse, /* Parsing context */
  119939. Select *p, /* The right-most of SELECTs to be coded */
  119940. SelectDest *pDest /* What to do with query results */
  119941. ){
  119942. int nRow = 1;
  119943. int rc = 0;
  119944. int bShowAll = p->pLimit==0;
  119945. assert( p->selFlags & SF_MultiValue );
  119946. do{
  119947. assert( p->selFlags & SF_Values );
  119948. assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) );
  119949. assert( p->pNext==0 || p->pEList->nExpr==p->pNext->pEList->nExpr );
  119950. if( p->pPrior==0 ) break;
  119951. assert( p->pPrior->pNext==p );
  119952. p = p->pPrior;
  119953. nRow += bShowAll;
  119954. }while(1);
  119955. ExplainQueryPlan((pParse, 0, "SCAN %d CONSTANT ROW%s", nRow,
  119956. nRow==1 ? "" : "S"));
  119957. while( p ){
  119958. selectInnerLoop(pParse, p, -1, 0, 0, pDest, 1, 1);
  119959. if( !bShowAll ) break;
  119960. p->nSelectRow = nRow;
  119961. p = p->pNext;
  119962. }
  119963. return rc;
  119964. }
  119965. /*
  119966. ** This routine is called to process a compound query form from
  119967. ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
  119968. ** INTERSECT
  119969. **
  119970. ** "p" points to the right-most of the two queries. the query on the
  119971. ** left is p->pPrior. The left query could also be a compound query
  119972. ** in which case this routine will be called recursively.
  119973. **
  119974. ** The results of the total query are to be written into a destination
  119975. ** of type eDest with parameter iParm.
  119976. **
  119977. ** Example 1: Consider a three-way compound SQL statement.
  119978. **
  119979. ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
  119980. **
  119981. ** This statement is parsed up as follows:
  119982. **
  119983. ** SELECT c FROM t3
  119984. ** |
  119985. ** `-----> SELECT b FROM t2
  119986. ** |
  119987. ** `------> SELECT a FROM t1
  119988. **
  119989. ** The arrows in the diagram above represent the Select.pPrior pointer.
  119990. ** So if this routine is called with p equal to the t3 query, then
  119991. ** pPrior will be the t2 query. p->op will be TK_UNION in this case.
  119992. **
  119993. ** Notice that because of the way SQLite parses compound SELECTs, the
  119994. ** individual selects always group from left to right.
  119995. */
  119996. static int multiSelect(
  119997. Parse *pParse, /* Parsing context */
  119998. Select *p, /* The right-most of SELECTs to be coded */
  119999. SelectDest *pDest /* What to do with query results */
  120000. ){
  120001. int rc = SQLITE_OK; /* Success code from a subroutine */
  120002. Select *pPrior; /* Another SELECT immediately to our left */
  120003. Vdbe *v; /* Generate code to this VDBE */
  120004. SelectDest dest; /* Alternative data destination */
  120005. Select *pDelete = 0; /* Chain of simple selects to delete */
  120006. sqlite3 *db; /* Database connection */
  120007. /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
  120008. ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
  120009. */
  120010. assert( p && p->pPrior ); /* Calling function guarantees this much */
  120011. assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );
  120012. assert( p->selFlags & SF_Compound );
  120013. db = pParse->db;
  120014. pPrior = p->pPrior;
  120015. dest = *pDest;
  120016. if( pPrior->pOrderBy || pPrior->pLimit ){
  120017. sqlite3ErrorMsg(pParse,"%s clause should come after %s not before",
  120018. pPrior->pOrderBy!=0 ? "ORDER BY" : "LIMIT", selectOpName(p->op));
  120019. rc = 1;
  120020. goto multi_select_end;
  120021. }
  120022. v = sqlite3GetVdbe(pParse);
  120023. assert( v!=0 ); /* The VDBE already created by calling function */
  120024. /* Create the destination temporary table if necessary
  120025. */
  120026. if( dest.eDest==SRT_EphemTab ){
  120027. assert( p->pEList );
  120028. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
  120029. dest.eDest = SRT_Table;
  120030. }
  120031. /* Special handling for a compound-select that originates as a VALUES clause.
  120032. */
  120033. if( p->selFlags & SF_MultiValue ){
  120034. rc = multiSelectValues(pParse, p, &dest);
  120035. goto multi_select_end;
  120036. }
  120037. /* Make sure all SELECTs in the statement have the same number of elements
  120038. ** in their result sets.
  120039. */
  120040. assert( p->pEList && pPrior->pEList );
  120041. assert( p->pEList->nExpr==pPrior->pEList->nExpr );
  120042. #ifndef SQLITE_OMIT_CTE
  120043. if( p->selFlags & SF_Recursive ){
  120044. generateWithRecursiveQuery(pParse, p, &dest);
  120045. }else
  120046. #endif
  120047. /* Compound SELECTs that have an ORDER BY clause are handled separately.
  120048. */
  120049. if( p->pOrderBy ){
  120050. return multiSelectOrderBy(pParse, p, pDest);
  120051. }else{
  120052. #ifndef SQLITE_OMIT_EXPLAIN
  120053. if( pPrior->pPrior==0 ){
  120054. ExplainQueryPlan((pParse, 1, "COMPOUND QUERY"));
  120055. ExplainQueryPlan((pParse, 1, "LEFT-MOST SUBQUERY"));
  120056. }
  120057. #endif
  120058. /* Generate code for the left and right SELECT statements.
  120059. */
  120060. switch( p->op ){
  120061. case TK_ALL: {
  120062. int addr = 0;
  120063. int nLimit;
  120064. assert( !pPrior->pLimit );
  120065. pPrior->iLimit = p->iLimit;
  120066. pPrior->iOffset = p->iOffset;
  120067. pPrior->pLimit = p->pLimit;
  120068. rc = sqlite3Select(pParse, pPrior, &dest);
  120069. p->pLimit = 0;
  120070. if( rc ){
  120071. goto multi_select_end;
  120072. }
  120073. p->pPrior = 0;
  120074. p->iLimit = pPrior->iLimit;
  120075. p->iOffset = pPrior->iOffset;
  120076. if( p->iLimit ){
  120077. addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v);
  120078. VdbeComment((v, "Jump ahead if LIMIT reached"));
  120079. if( p->iOffset ){
  120080. sqlite3VdbeAddOp3(v, OP_OffsetLimit,
  120081. p->iLimit, p->iOffset+1, p->iOffset);
  120082. }
  120083. }
  120084. ExplainQueryPlan((pParse, 1, "UNION ALL"));
  120085. rc = sqlite3Select(pParse, p, &dest);
  120086. testcase( rc!=SQLITE_OK );
  120087. pDelete = p->pPrior;
  120088. p->pPrior = pPrior;
  120089. p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
  120090. if( pPrior->pLimit
  120091. && sqlite3ExprIsInteger(pPrior->pLimit->pLeft, &nLimit)
  120092. && nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit)
  120093. ){
  120094. p->nSelectRow = sqlite3LogEst((u64)nLimit);
  120095. }
  120096. if( addr ){
  120097. sqlite3VdbeJumpHere(v, addr);
  120098. }
  120099. break;
  120100. }
  120101. case TK_EXCEPT:
  120102. case TK_UNION: {
  120103. int unionTab; /* Cursor number of the temp table holding result */
  120104. u8 op = 0; /* One of the SRT_ operations to apply to self */
  120105. int priorOp; /* The SRT_ operation to apply to prior selects */
  120106. Expr *pLimit; /* Saved values of p->nLimit */
  120107. int addr;
  120108. SelectDest uniondest;
  120109. testcase( p->op==TK_EXCEPT );
  120110. testcase( p->op==TK_UNION );
  120111. priorOp = SRT_Union;
  120112. if( dest.eDest==priorOp ){
  120113. /* We can reuse a temporary table generated by a SELECT to our
  120114. ** right.
  120115. */
  120116. assert( p->pLimit==0 ); /* Not allowed on leftward elements */
  120117. unionTab = dest.iSDParm;
  120118. }else{
  120119. /* We will need to create our own temporary table to hold the
  120120. ** intermediate results.
  120121. */
  120122. unionTab = pParse->nTab++;
  120123. assert( p->pOrderBy==0 );
  120124. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
  120125. assert( p->addrOpenEphm[0] == -1 );
  120126. p->addrOpenEphm[0] = addr;
  120127. findRightmost(p)->selFlags |= SF_UsesEphemeral;
  120128. assert( p->pEList );
  120129. }
  120130. /* Code the SELECT statements to our left
  120131. */
  120132. assert( !pPrior->pOrderBy );
  120133. sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
  120134. rc = sqlite3Select(pParse, pPrior, &uniondest);
  120135. if( rc ){
  120136. goto multi_select_end;
  120137. }
  120138. /* Code the current SELECT statement
  120139. */
  120140. if( p->op==TK_EXCEPT ){
  120141. op = SRT_Except;
  120142. }else{
  120143. assert( p->op==TK_UNION );
  120144. op = SRT_Union;
  120145. }
  120146. p->pPrior = 0;
  120147. pLimit = p->pLimit;
  120148. p->pLimit = 0;
  120149. uniondest.eDest = op;
  120150. ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE",
  120151. selectOpName(p->op)));
  120152. rc = sqlite3Select(pParse, p, &uniondest);
  120153. testcase( rc!=SQLITE_OK );
  120154. /* Query flattening in sqlite3Select() might refill p->pOrderBy.
  120155. ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
  120156. sqlite3ExprListDelete(db, p->pOrderBy);
  120157. pDelete = p->pPrior;
  120158. p->pPrior = pPrior;
  120159. p->pOrderBy = 0;
  120160. if( p->op==TK_UNION ){
  120161. p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
  120162. }
  120163. sqlite3ExprDelete(db, p->pLimit);
  120164. p->pLimit = pLimit;
  120165. p->iLimit = 0;
  120166. p->iOffset = 0;
  120167. /* Convert the data in the temporary table into whatever form
  120168. ** it is that we currently need.
  120169. */
  120170. assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
  120171. if( dest.eDest!=priorOp ){
  120172. int iCont, iBreak, iStart;
  120173. assert( p->pEList );
  120174. iBreak = sqlite3VdbeMakeLabel(pParse);
  120175. iCont = sqlite3VdbeMakeLabel(pParse);
  120176. computeLimitRegisters(pParse, p, iBreak);
  120177. sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v);
  120178. iStart = sqlite3VdbeCurrentAddr(v);
  120179. selectInnerLoop(pParse, p, unionTab,
  120180. 0, 0, &dest, iCont, iBreak);
  120181. sqlite3VdbeResolveLabel(v, iCont);
  120182. sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v);
  120183. sqlite3VdbeResolveLabel(v, iBreak);
  120184. sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
  120185. }
  120186. break;
  120187. }
  120188. default: assert( p->op==TK_INTERSECT ); {
  120189. int tab1, tab2;
  120190. int iCont, iBreak, iStart;
  120191. Expr *pLimit;
  120192. int addr;
  120193. SelectDest intersectdest;
  120194. int r1;
  120195. /* INTERSECT is different from the others since it requires
  120196. ** two temporary tables. Hence it has its own case. Begin
  120197. ** by allocating the tables we will need.
  120198. */
  120199. tab1 = pParse->nTab++;
  120200. tab2 = pParse->nTab++;
  120201. assert( p->pOrderBy==0 );
  120202. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
  120203. assert( p->addrOpenEphm[0] == -1 );
  120204. p->addrOpenEphm[0] = addr;
  120205. findRightmost(p)->selFlags |= SF_UsesEphemeral;
  120206. assert( p->pEList );
  120207. /* Code the SELECTs to our left into temporary table "tab1".
  120208. */
  120209. sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
  120210. rc = sqlite3Select(pParse, pPrior, &intersectdest);
  120211. if( rc ){
  120212. goto multi_select_end;
  120213. }
  120214. /* Code the current SELECT into temporary table "tab2"
  120215. */
  120216. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
  120217. assert( p->addrOpenEphm[1] == -1 );
  120218. p->addrOpenEphm[1] = addr;
  120219. p->pPrior = 0;
  120220. pLimit = p->pLimit;
  120221. p->pLimit = 0;
  120222. intersectdest.iSDParm = tab2;
  120223. ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE",
  120224. selectOpName(p->op)));
  120225. rc = sqlite3Select(pParse, p, &intersectdest);
  120226. testcase( rc!=SQLITE_OK );
  120227. pDelete = p->pPrior;
  120228. p->pPrior = pPrior;
  120229. if( p->nSelectRow>pPrior->nSelectRow ){
  120230. p->nSelectRow = pPrior->nSelectRow;
  120231. }
  120232. sqlite3ExprDelete(db, p->pLimit);
  120233. p->pLimit = pLimit;
  120234. /* Generate code to take the intersection of the two temporary
  120235. ** tables.
  120236. */
  120237. assert( p->pEList );
  120238. iBreak = sqlite3VdbeMakeLabel(pParse);
  120239. iCont = sqlite3VdbeMakeLabel(pParse);
  120240. computeLimitRegisters(pParse, p, iBreak);
  120241. sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v);
  120242. r1 = sqlite3GetTempReg(pParse);
  120243. iStart = sqlite3VdbeAddOp2(v, OP_RowData, tab1, r1);
  120244. sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
  120245. VdbeCoverage(v);
  120246. sqlite3ReleaseTempReg(pParse, r1);
  120247. selectInnerLoop(pParse, p, tab1,
  120248. 0, 0, &dest, iCont, iBreak);
  120249. sqlite3VdbeResolveLabel(v, iCont);
  120250. sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v);
  120251. sqlite3VdbeResolveLabel(v, iBreak);
  120252. sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
  120253. sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
  120254. break;
  120255. }
  120256. }
  120257. #ifndef SQLITE_OMIT_EXPLAIN
  120258. if( p->pNext==0 ){
  120259. ExplainQueryPlanPop(pParse);
  120260. }
  120261. #endif
  120262. }
  120263. /* Compute collating sequences used by
  120264. ** temporary tables needed to implement the compound select.
  120265. ** Attach the KeyInfo structure to all temporary tables.
  120266. **
  120267. ** This section is run by the right-most SELECT statement only.
  120268. ** SELECT statements to the left always skip this part. The right-most
  120269. ** SELECT might also skip this part if it has no ORDER BY clause and
  120270. ** no temp tables are required.
  120271. */
  120272. if( p->selFlags & SF_UsesEphemeral ){
  120273. int i; /* Loop counter */
  120274. KeyInfo *pKeyInfo; /* Collating sequence for the result set */
  120275. Select *pLoop; /* For looping through SELECT statements */
  120276. CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */
  120277. int nCol; /* Number of columns in result set */
  120278. assert( p->pNext==0 );
  120279. nCol = p->pEList->nExpr;
  120280. pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);
  120281. if( !pKeyInfo ){
  120282. rc = SQLITE_NOMEM_BKPT;
  120283. goto multi_select_end;
  120284. }
  120285. for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
  120286. *apColl = multiSelectCollSeq(pParse, p, i);
  120287. if( 0==*apColl ){
  120288. *apColl = db->pDfltColl;
  120289. }
  120290. }
  120291. for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
  120292. for(i=0; i<2; i++){
  120293. int addr = pLoop->addrOpenEphm[i];
  120294. if( addr<0 ){
  120295. /* If [0] is unused then [1] is also unused. So we can
  120296. ** always safely abort as soon as the first unused slot is found */
  120297. assert( pLoop->addrOpenEphm[1]<0 );
  120298. break;
  120299. }
  120300. sqlite3VdbeChangeP2(v, addr, nCol);
  120301. sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo),
  120302. P4_KEYINFO);
  120303. pLoop->addrOpenEphm[i] = -1;
  120304. }
  120305. }
  120306. sqlite3KeyInfoUnref(pKeyInfo);
  120307. }
  120308. multi_select_end:
  120309. pDest->iSdst = dest.iSdst;
  120310. pDest->nSdst = dest.nSdst;
  120311. sqlite3SelectDelete(db, pDelete);
  120312. return rc;
  120313. }
  120314. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  120315. /*
  120316. ** Error message for when two or more terms of a compound select have different
  120317. ** size result sets.
  120318. */
  120319. SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p){
  120320. if( p->selFlags & SF_Values ){
  120321. sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
  120322. }else{
  120323. sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
  120324. " do not have the same number of result columns", selectOpName(p->op));
  120325. }
  120326. }
  120327. /*
  120328. ** Code an output subroutine for a coroutine implementation of a
  120329. ** SELECT statment.
  120330. **
  120331. ** The data to be output is contained in pIn->iSdst. There are
  120332. ** pIn->nSdst columns to be output. pDest is where the output should
  120333. ** be sent.
  120334. **
  120335. ** regReturn is the number of the register holding the subroutine
  120336. ** return address.
  120337. **
  120338. ** If regPrev>0 then it is the first register in a vector that
  120339. ** records the previous output. mem[regPrev] is a flag that is false
  120340. ** if there has been no previous output. If regPrev>0 then code is
  120341. ** generated to suppress duplicates. pKeyInfo is used for comparing
  120342. ** keys.
  120343. **
  120344. ** If the LIMIT found in p->iLimit is reached, jump immediately to
  120345. ** iBreak.
  120346. */
  120347. static int generateOutputSubroutine(
  120348. Parse *pParse, /* Parsing context */
  120349. Select *p, /* The SELECT statement */
  120350. SelectDest *pIn, /* Coroutine supplying data */
  120351. SelectDest *pDest, /* Where to send the data */
  120352. int regReturn, /* The return address register */
  120353. int regPrev, /* Previous result register. No uniqueness if 0 */
  120354. KeyInfo *pKeyInfo, /* For comparing with previous entry */
  120355. int iBreak /* Jump here if we hit the LIMIT */
  120356. ){
  120357. Vdbe *v = pParse->pVdbe;
  120358. int iContinue;
  120359. int addr;
  120360. addr = sqlite3VdbeCurrentAddr(v);
  120361. iContinue = sqlite3VdbeMakeLabel(pParse);
  120362. /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
  120363. */
  120364. if( regPrev ){
  120365. int addr1, addr2;
  120366. addr1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v);
  120367. addr2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
  120368. (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
  120369. sqlite3VdbeAddOp3(v, OP_Jump, addr2+2, iContinue, addr2+2); VdbeCoverage(v);
  120370. sqlite3VdbeJumpHere(v, addr1);
  120371. sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
  120372. sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
  120373. }
  120374. if( pParse->db->mallocFailed ) return 0;
  120375. /* Suppress the first OFFSET entries if there is an OFFSET clause
  120376. */
  120377. codeOffset(v, p->iOffset, iContinue);
  120378. assert( pDest->eDest!=SRT_Exists );
  120379. assert( pDest->eDest!=SRT_Table );
  120380. switch( pDest->eDest ){
  120381. /* Store the result as data using a unique key.
  120382. */
  120383. case SRT_EphemTab: {
  120384. int r1 = sqlite3GetTempReg(pParse);
  120385. int r2 = sqlite3GetTempReg(pParse);
  120386. sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
  120387. sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
  120388. sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
  120389. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  120390. sqlite3ReleaseTempReg(pParse, r2);
  120391. sqlite3ReleaseTempReg(pParse, r1);
  120392. break;
  120393. }
  120394. #ifndef SQLITE_OMIT_SUBQUERY
  120395. /* If we are creating a set for an "expr IN (SELECT ...)".
  120396. */
  120397. case SRT_Set: {
  120398. int r1;
  120399. testcase( pIn->nSdst>1 );
  120400. r1 = sqlite3GetTempReg(pParse);
  120401. sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst,
  120402. r1, pDest->zAffSdst, pIn->nSdst);
  120403. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pDest->iSDParm, r1,
  120404. pIn->iSdst, pIn->nSdst);
  120405. sqlite3ReleaseTempReg(pParse, r1);
  120406. break;
  120407. }
  120408. /* If this is a scalar select that is part of an expression, then
  120409. ** store the results in the appropriate memory cell and break out
  120410. ** of the scan loop.
  120411. */
  120412. case SRT_Mem: {
  120413. assert( pIn->nSdst==1 || pParse->nErr>0 ); testcase( pIn->nSdst!=1 );
  120414. sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
  120415. /* The LIMIT clause will jump out of the loop for us */
  120416. break;
  120417. }
  120418. #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
  120419. /* The results are stored in a sequence of registers
  120420. ** starting at pDest->iSdst. Then the co-routine yields.
  120421. */
  120422. case SRT_Coroutine: {
  120423. if( pDest->iSdst==0 ){
  120424. pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
  120425. pDest->nSdst = pIn->nSdst;
  120426. }
  120427. sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pIn->nSdst);
  120428. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  120429. break;
  120430. }
  120431. /* If none of the above, then the result destination must be
  120432. ** SRT_Output. This routine is never called with any other
  120433. ** destination other than the ones handled above or SRT_Output.
  120434. **
  120435. ** For SRT_Output, results are stored in a sequence of registers.
  120436. ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
  120437. ** return the next row of result.
  120438. */
  120439. default: {
  120440. assert( pDest->eDest==SRT_Output );
  120441. sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
  120442. break;
  120443. }
  120444. }
  120445. /* Jump to the end of the loop if the LIMIT is reached.
  120446. */
  120447. if( p->iLimit ){
  120448. sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
  120449. }
  120450. /* Generate the subroutine return
  120451. */
  120452. sqlite3VdbeResolveLabel(v, iContinue);
  120453. sqlite3VdbeAddOp1(v, OP_Return, regReturn);
  120454. return addr;
  120455. }
  120456. /*
  120457. ** Alternative compound select code generator for cases when there
  120458. ** is an ORDER BY clause.
  120459. **
  120460. ** We assume a query of the following form:
  120461. **
  120462. ** <selectA> <operator> <selectB> ORDER BY <orderbylist>
  120463. **
  120464. ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea
  120465. ** is to code both <selectA> and <selectB> with the ORDER BY clause as
  120466. ** co-routines. Then run the co-routines in parallel and merge the results
  120467. ** into the output. In addition to the two coroutines (called selectA and
  120468. ** selectB) there are 7 subroutines:
  120469. **
  120470. ** outA: Move the output of the selectA coroutine into the output
  120471. ** of the compound query.
  120472. **
  120473. ** outB: Move the output of the selectB coroutine into the output
  120474. ** of the compound query. (Only generated for UNION and
  120475. ** UNION ALL. EXCEPT and INSERTSECT never output a row that
  120476. ** appears only in B.)
  120477. **
  120478. ** AltB: Called when there is data from both coroutines and A<B.
  120479. **
  120480. ** AeqB: Called when there is data from both coroutines and A==B.
  120481. **
  120482. ** AgtB: Called when there is data from both coroutines and A>B.
  120483. **
  120484. ** EofA: Called when data is exhausted from selectA.
  120485. **
  120486. ** EofB: Called when data is exhausted from selectB.
  120487. **
  120488. ** The implementation of the latter five subroutines depend on which
  120489. ** <operator> is used:
  120490. **
  120491. **
  120492. ** UNION ALL UNION EXCEPT INTERSECT
  120493. ** ------------- ----------------- -------------- -----------------
  120494. ** AltB: outA, nextA outA, nextA outA, nextA nextA
  120495. **
  120496. ** AeqB: outA, nextA nextA nextA outA, nextA
  120497. **
  120498. ** AgtB: outB, nextB outB, nextB nextB nextB
  120499. **
  120500. ** EofA: outB, nextB outB, nextB halt halt
  120501. **
  120502. ** EofB: outA, nextA outA, nextA outA, nextA halt
  120503. **
  120504. ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
  120505. ** causes an immediate jump to EofA and an EOF on B following nextB causes
  120506. ** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or
  120507. ** following nextX causes a jump to the end of the select processing.
  120508. **
  120509. ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
  120510. ** within the output subroutine. The regPrev register set holds the previously
  120511. ** output value. A comparison is made against this value and the output
  120512. ** is skipped if the next results would be the same as the previous.
  120513. **
  120514. ** The implementation plan is to implement the two coroutines and seven
  120515. ** subroutines first, then put the control logic at the bottom. Like this:
  120516. **
  120517. ** goto Init
  120518. ** coA: coroutine for left query (A)
  120519. ** coB: coroutine for right query (B)
  120520. ** outA: output one row of A
  120521. ** outB: output one row of B (UNION and UNION ALL only)
  120522. ** EofA: ...
  120523. ** EofB: ...
  120524. ** AltB: ...
  120525. ** AeqB: ...
  120526. ** AgtB: ...
  120527. ** Init: initialize coroutine registers
  120528. ** yield coA
  120529. ** if eof(A) goto EofA
  120530. ** yield coB
  120531. ** if eof(B) goto EofB
  120532. ** Cmpr: Compare A, B
  120533. ** Jump AltB, AeqB, AgtB
  120534. ** End: ...
  120535. **
  120536. ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
  120537. ** actually called using Gosub and they do not Return. EofA and EofB loop
  120538. ** until all data is exhausted then jump to the "end" labe. AltB, AeqB,
  120539. ** and AgtB jump to either L2 or to one of EofA or EofB.
  120540. */
  120541. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  120542. static int multiSelectOrderBy(
  120543. Parse *pParse, /* Parsing context */
  120544. Select *p, /* The right-most of SELECTs to be coded */
  120545. SelectDest *pDest /* What to do with query results */
  120546. ){
  120547. int i, j; /* Loop counters */
  120548. Select *pPrior; /* Another SELECT immediately to our left */
  120549. Vdbe *v; /* Generate code to this VDBE */
  120550. SelectDest destA; /* Destination for coroutine A */
  120551. SelectDest destB; /* Destination for coroutine B */
  120552. int regAddrA; /* Address register for select-A coroutine */
  120553. int regAddrB; /* Address register for select-B coroutine */
  120554. int addrSelectA; /* Address of the select-A coroutine */
  120555. int addrSelectB; /* Address of the select-B coroutine */
  120556. int regOutA; /* Address register for the output-A subroutine */
  120557. int regOutB; /* Address register for the output-B subroutine */
  120558. int addrOutA; /* Address of the output-A subroutine */
  120559. int addrOutB = 0; /* Address of the output-B subroutine */
  120560. int addrEofA; /* Address of the select-A-exhausted subroutine */
  120561. int addrEofA_noB; /* Alternate addrEofA if B is uninitialized */
  120562. int addrEofB; /* Address of the select-B-exhausted subroutine */
  120563. int addrAltB; /* Address of the A<B subroutine */
  120564. int addrAeqB; /* Address of the A==B subroutine */
  120565. int addrAgtB; /* Address of the A>B subroutine */
  120566. int regLimitA; /* Limit register for select-A */
  120567. int regLimitB; /* Limit register for select-A */
  120568. int regPrev; /* A range of registers to hold previous output */
  120569. int savedLimit; /* Saved value of p->iLimit */
  120570. int savedOffset; /* Saved value of p->iOffset */
  120571. int labelCmpr; /* Label for the start of the merge algorithm */
  120572. int labelEnd; /* Label for the end of the overall SELECT stmt */
  120573. int addr1; /* Jump instructions that get retargetted */
  120574. int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
  120575. KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
  120576. KeyInfo *pKeyMerge; /* Comparison information for merging rows */
  120577. sqlite3 *db; /* Database connection */
  120578. ExprList *pOrderBy; /* The ORDER BY clause */
  120579. int nOrderBy; /* Number of terms in the ORDER BY clause */
  120580. int *aPermute; /* Mapping from ORDER BY terms to result set columns */
  120581. assert( p->pOrderBy!=0 );
  120582. assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */
  120583. db = pParse->db;
  120584. v = pParse->pVdbe;
  120585. assert( v!=0 ); /* Already thrown the error if VDBE alloc failed */
  120586. labelEnd = sqlite3VdbeMakeLabel(pParse);
  120587. labelCmpr = sqlite3VdbeMakeLabel(pParse);
  120588. /* Patch up the ORDER BY clause
  120589. */
  120590. op = p->op;
  120591. pPrior = p->pPrior;
  120592. assert( pPrior->pOrderBy==0 );
  120593. pOrderBy = p->pOrderBy;
  120594. assert( pOrderBy );
  120595. nOrderBy = pOrderBy->nExpr;
  120596. /* For operators other than UNION ALL we have to make sure that
  120597. ** the ORDER BY clause covers every term of the result set. Add
  120598. ** terms to the ORDER BY clause as necessary.
  120599. */
  120600. if( op!=TK_ALL ){
  120601. for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
  120602. struct ExprList_item *pItem;
  120603. for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
  120604. assert( pItem->u.x.iOrderByCol>0 );
  120605. if( pItem->u.x.iOrderByCol==i ) break;
  120606. }
  120607. if( j==nOrderBy ){
  120608. Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
  120609. if( pNew==0 ) return SQLITE_NOMEM_BKPT;
  120610. pNew->flags |= EP_IntValue;
  120611. pNew->u.iValue = i;
  120612. p->pOrderBy = pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
  120613. if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i;
  120614. }
  120615. }
  120616. }
  120617. /* Compute the comparison permutation and keyinfo that is used with
  120618. ** the permutation used to determine if the next
  120619. ** row of results comes from selectA or selectB. Also add explicit
  120620. ** collations to the ORDER BY clause terms so that when the subqueries
  120621. ** to the right and the left are evaluated, they use the correct
  120622. ** collation.
  120623. */
  120624. aPermute = sqlite3DbMallocRawNN(db, sizeof(int)*(nOrderBy + 1));
  120625. if( aPermute ){
  120626. struct ExprList_item *pItem;
  120627. aPermute[0] = nOrderBy;
  120628. for(i=1, pItem=pOrderBy->a; i<=nOrderBy; i++, pItem++){
  120629. assert( pItem->u.x.iOrderByCol>0 );
  120630. assert( pItem->u.x.iOrderByCol<=p->pEList->nExpr );
  120631. aPermute[i] = pItem->u.x.iOrderByCol - 1;
  120632. }
  120633. pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1);
  120634. }else{
  120635. pKeyMerge = 0;
  120636. }
  120637. /* Reattach the ORDER BY clause to the query.
  120638. */
  120639. p->pOrderBy = pOrderBy;
  120640. pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
  120641. /* Allocate a range of temporary registers and the KeyInfo needed
  120642. ** for the logic that removes duplicate result rows when the
  120643. ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
  120644. */
  120645. if( op==TK_ALL ){
  120646. regPrev = 0;
  120647. }else{
  120648. int nExpr = p->pEList->nExpr;
  120649. assert( nOrderBy>=nExpr || db->mallocFailed );
  120650. regPrev = pParse->nMem+1;
  120651. pParse->nMem += nExpr+1;
  120652. sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
  120653. pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1);
  120654. if( pKeyDup ){
  120655. assert( sqlite3KeyInfoIsWriteable(pKeyDup) );
  120656. for(i=0; i<nExpr; i++){
  120657. pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
  120658. pKeyDup->aSortOrder[i] = 0;
  120659. }
  120660. }
  120661. }
  120662. /* Separate the left and the right query from one another
  120663. */
  120664. p->pPrior = 0;
  120665. pPrior->pNext = 0;
  120666. sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
  120667. if( pPrior->pPrior==0 ){
  120668. sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
  120669. }
  120670. /* Compute the limit registers */
  120671. computeLimitRegisters(pParse, p, labelEnd);
  120672. if( p->iLimit && op==TK_ALL ){
  120673. regLimitA = ++pParse->nMem;
  120674. regLimitB = ++pParse->nMem;
  120675. sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
  120676. regLimitA);
  120677. sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
  120678. }else{
  120679. regLimitA = regLimitB = 0;
  120680. }
  120681. sqlite3ExprDelete(db, p->pLimit);
  120682. p->pLimit = 0;
  120683. regAddrA = ++pParse->nMem;
  120684. regAddrB = ++pParse->nMem;
  120685. regOutA = ++pParse->nMem;
  120686. regOutB = ++pParse->nMem;
  120687. sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
  120688. sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
  120689. ExplainQueryPlan((pParse, 1, "MERGE (%s)", selectOpName(p->op)));
  120690. /* Generate a coroutine to evaluate the SELECT statement to the
  120691. ** left of the compound operator - the "A" select.
  120692. */
  120693. addrSelectA = sqlite3VdbeCurrentAddr(v) + 1;
  120694. addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA);
  120695. VdbeComment((v, "left SELECT"));
  120696. pPrior->iLimit = regLimitA;
  120697. ExplainQueryPlan((pParse, 1, "LEFT"));
  120698. sqlite3Select(pParse, pPrior, &destA);
  120699. sqlite3VdbeEndCoroutine(v, regAddrA);
  120700. sqlite3VdbeJumpHere(v, addr1);
  120701. /* Generate a coroutine to evaluate the SELECT statement on
  120702. ** the right - the "B" select
  120703. */
  120704. addrSelectB = sqlite3VdbeCurrentAddr(v) + 1;
  120705. addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB);
  120706. VdbeComment((v, "right SELECT"));
  120707. savedLimit = p->iLimit;
  120708. savedOffset = p->iOffset;
  120709. p->iLimit = regLimitB;
  120710. p->iOffset = 0;
  120711. ExplainQueryPlan((pParse, 1, "RIGHT"));
  120712. sqlite3Select(pParse, p, &destB);
  120713. p->iLimit = savedLimit;
  120714. p->iOffset = savedOffset;
  120715. sqlite3VdbeEndCoroutine(v, regAddrB);
  120716. /* Generate a subroutine that outputs the current row of the A
  120717. ** select as the next output row of the compound select.
  120718. */
  120719. VdbeNoopComment((v, "Output routine for A"));
  120720. addrOutA = generateOutputSubroutine(pParse,
  120721. p, &destA, pDest, regOutA,
  120722. regPrev, pKeyDup, labelEnd);
  120723. /* Generate a subroutine that outputs the current row of the B
  120724. ** select as the next output row of the compound select.
  120725. */
  120726. if( op==TK_ALL || op==TK_UNION ){
  120727. VdbeNoopComment((v, "Output routine for B"));
  120728. addrOutB = generateOutputSubroutine(pParse,
  120729. p, &destB, pDest, regOutB,
  120730. regPrev, pKeyDup, labelEnd);
  120731. }
  120732. sqlite3KeyInfoUnref(pKeyDup);
  120733. /* Generate a subroutine to run when the results from select A
  120734. ** are exhausted and only data in select B remains.
  120735. */
  120736. if( op==TK_EXCEPT || op==TK_INTERSECT ){
  120737. addrEofA_noB = addrEofA = labelEnd;
  120738. }else{
  120739. VdbeNoopComment((v, "eof-A subroutine"));
  120740. addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
  120741. addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd);
  120742. VdbeCoverage(v);
  120743. sqlite3VdbeGoto(v, addrEofA);
  120744. p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
  120745. }
  120746. /* Generate a subroutine to run when the results from select B
  120747. ** are exhausted and only data in select A remains.
  120748. */
  120749. if( op==TK_INTERSECT ){
  120750. addrEofB = addrEofA;
  120751. if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
  120752. }else{
  120753. VdbeNoopComment((v, "eof-B subroutine"));
  120754. addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
  120755. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v);
  120756. sqlite3VdbeGoto(v, addrEofB);
  120757. }
  120758. /* Generate code to handle the case of A<B
  120759. */
  120760. VdbeNoopComment((v, "A-lt-B subroutine"));
  120761. addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
  120762. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
  120763. sqlite3VdbeGoto(v, labelCmpr);
  120764. /* Generate code to handle the case of A==B
  120765. */
  120766. if( op==TK_ALL ){
  120767. addrAeqB = addrAltB;
  120768. }else if( op==TK_INTERSECT ){
  120769. addrAeqB = addrAltB;
  120770. addrAltB++;
  120771. }else{
  120772. VdbeNoopComment((v, "A-eq-B subroutine"));
  120773. addrAeqB =
  120774. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
  120775. sqlite3VdbeGoto(v, labelCmpr);
  120776. }
  120777. /* Generate code to handle the case of A>B
  120778. */
  120779. VdbeNoopComment((v, "A-gt-B subroutine"));
  120780. addrAgtB = sqlite3VdbeCurrentAddr(v);
  120781. if( op==TK_ALL || op==TK_UNION ){
  120782. sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
  120783. }
  120784. sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
  120785. sqlite3VdbeGoto(v, labelCmpr);
  120786. /* This code runs once to initialize everything.
  120787. */
  120788. sqlite3VdbeJumpHere(v, addr1);
  120789. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v);
  120790. sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
  120791. /* Implement the main merge loop
  120792. */
  120793. sqlite3VdbeResolveLabel(v, labelCmpr);
  120794. sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
  120795. sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
  120796. (char*)pKeyMerge, P4_KEYINFO);
  120797. sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
  120798. sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v);
  120799. /* Jump to the this point in order to terminate the query.
  120800. */
  120801. sqlite3VdbeResolveLabel(v, labelEnd);
  120802. /* Reassembly the compound query so that it will be freed correctly
  120803. ** by the calling function */
  120804. if( p->pPrior ){
  120805. sqlite3SelectDelete(db, p->pPrior);
  120806. }
  120807. p->pPrior = pPrior;
  120808. pPrior->pNext = p;
  120809. /*** TBD: Insert subroutine calls to close cursors on incomplete
  120810. **** subqueries ****/
  120811. ExplainQueryPlanPop(pParse);
  120812. return pParse->nErr!=0;
  120813. }
  120814. #endif
  120815. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  120816. /* An instance of the SubstContext object describes an substitution edit
  120817. ** to be performed on a parse tree.
  120818. **
  120819. ** All references to columns in table iTable are to be replaced by corresponding
  120820. ** expressions in pEList.
  120821. */
  120822. typedef struct SubstContext {
  120823. Parse *pParse; /* The parsing context */
  120824. int iTable; /* Replace references to this table */
  120825. int iNewTable; /* New table number */
  120826. int isLeftJoin; /* Add TK_IF_NULL_ROW opcodes on each replacement */
  120827. ExprList *pEList; /* Replacement expressions */
  120828. } SubstContext;
  120829. /* Forward Declarations */
  120830. static void substExprList(SubstContext*, ExprList*);
  120831. static void substSelect(SubstContext*, Select*, int);
  120832. /*
  120833. ** Scan through the expression pExpr. Replace every reference to
  120834. ** a column in table number iTable with a copy of the iColumn-th
  120835. ** entry in pEList. (But leave references to the ROWID column
  120836. ** unchanged.)
  120837. **
  120838. ** This routine is part of the flattening procedure. A subquery
  120839. ** whose result set is defined by pEList appears as entry in the
  120840. ** FROM clause of a SELECT such that the VDBE cursor assigned to that
  120841. ** FORM clause entry is iTable. This routine makes the necessary
  120842. ** changes to pExpr so that it refers directly to the source table
  120843. ** of the subquery rather the result set of the subquery.
  120844. */
  120845. static Expr *substExpr(
  120846. SubstContext *pSubst, /* Description of the substitution */
  120847. Expr *pExpr /* Expr in which substitution occurs */
  120848. ){
  120849. if( pExpr==0 ) return 0;
  120850. if( ExprHasProperty(pExpr, EP_FromJoin)
  120851. && pExpr->iRightJoinTable==pSubst->iTable
  120852. ){
  120853. pExpr->iRightJoinTable = pSubst->iNewTable;
  120854. }
  120855. if( pExpr->op==TK_COLUMN && pExpr->iTable==pSubst->iTable ){
  120856. if( pExpr->iColumn<0 ){
  120857. pExpr->op = TK_NULL;
  120858. }else{
  120859. Expr *pNew;
  120860. Expr *pCopy = pSubst->pEList->a[pExpr->iColumn].pExpr;
  120861. Expr ifNullRow;
  120862. assert( pSubst->pEList!=0 && pExpr->iColumn<pSubst->pEList->nExpr );
  120863. assert( pExpr->pRight==0 );
  120864. if( sqlite3ExprIsVector(pCopy) ){
  120865. sqlite3VectorErrorMsg(pSubst->pParse, pCopy);
  120866. }else{
  120867. sqlite3 *db = pSubst->pParse->db;
  120868. if( pSubst->isLeftJoin && pCopy->op!=TK_COLUMN ){
  120869. memset(&ifNullRow, 0, sizeof(ifNullRow));
  120870. ifNullRow.op = TK_IF_NULL_ROW;
  120871. ifNullRow.pLeft = pCopy;
  120872. ifNullRow.iTable = pSubst->iNewTable;
  120873. pCopy = &ifNullRow;
  120874. }
  120875. testcase( ExprHasProperty(pCopy, EP_Subquery) );
  120876. pNew = sqlite3ExprDup(db, pCopy, 0);
  120877. if( pNew && pSubst->isLeftJoin ){
  120878. ExprSetProperty(pNew, EP_CanBeNull);
  120879. }
  120880. if( pNew && ExprHasProperty(pExpr,EP_FromJoin) ){
  120881. pNew->iRightJoinTable = pExpr->iRightJoinTable;
  120882. ExprSetProperty(pNew, EP_FromJoin);
  120883. }
  120884. sqlite3ExprDelete(db, pExpr);
  120885. pExpr = pNew;
  120886. }
  120887. }
  120888. }else{
  120889. if( pExpr->op==TK_IF_NULL_ROW && pExpr->iTable==pSubst->iTable ){
  120890. pExpr->iTable = pSubst->iNewTable;
  120891. }
  120892. pExpr->pLeft = substExpr(pSubst, pExpr->pLeft);
  120893. pExpr->pRight = substExpr(pSubst, pExpr->pRight);
  120894. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  120895. substSelect(pSubst, pExpr->x.pSelect, 1);
  120896. }else{
  120897. substExprList(pSubst, pExpr->x.pList);
  120898. }
  120899. }
  120900. return pExpr;
  120901. }
  120902. static void substExprList(
  120903. SubstContext *pSubst, /* Description of the substitution */
  120904. ExprList *pList /* List to scan and in which to make substitutes */
  120905. ){
  120906. int i;
  120907. if( pList==0 ) return;
  120908. for(i=0; i<pList->nExpr; i++){
  120909. pList->a[i].pExpr = substExpr(pSubst, pList->a[i].pExpr);
  120910. }
  120911. }
  120912. static void substSelect(
  120913. SubstContext *pSubst, /* Description of the substitution */
  120914. Select *p, /* SELECT statement in which to make substitutions */
  120915. int doPrior /* Do substitutes on p->pPrior too */
  120916. ){
  120917. SrcList *pSrc;
  120918. struct SrcList_item *pItem;
  120919. int i;
  120920. if( !p ) return;
  120921. do{
  120922. substExprList(pSubst, p->pEList);
  120923. substExprList(pSubst, p->pGroupBy);
  120924. substExprList(pSubst, p->pOrderBy);
  120925. p->pHaving = substExpr(pSubst, p->pHaving);
  120926. p->pWhere = substExpr(pSubst, p->pWhere);
  120927. pSrc = p->pSrc;
  120928. assert( pSrc!=0 );
  120929. for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
  120930. substSelect(pSubst, pItem->pSelect, 1);
  120931. if( pItem->fg.isTabFunc ){
  120932. substExprList(pSubst, pItem->u1.pFuncArg);
  120933. }
  120934. }
  120935. }while( doPrior && (p = p->pPrior)!=0 );
  120936. }
  120937. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  120938. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  120939. /*
  120940. ** This routine attempts to flatten subqueries as a performance optimization.
  120941. ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
  120942. **
  120943. ** To understand the concept of flattening, consider the following
  120944. ** query:
  120945. **
  120946. ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
  120947. **
  120948. ** The default way of implementing this query is to execute the
  120949. ** subquery first and store the results in a temporary table, then
  120950. ** run the outer query on that temporary table. This requires two
  120951. ** passes over the data. Furthermore, because the temporary table
  120952. ** has no indices, the WHERE clause on the outer query cannot be
  120953. ** optimized.
  120954. **
  120955. ** This routine attempts to rewrite queries such as the above into
  120956. ** a single flat select, like this:
  120957. **
  120958. ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
  120959. **
  120960. ** The code generated for this simplification gives the same result
  120961. ** but only has to scan the data once. And because indices might
  120962. ** exist on the table t1, a complete scan of the data might be
  120963. ** avoided.
  120964. **
  120965. ** Flattening is subject to the following constraints:
  120966. **
  120967. ** (**) We no longer attempt to flatten aggregate subqueries. Was:
  120968. ** The subquery and the outer query cannot both be aggregates.
  120969. **
  120970. ** (**) We no longer attempt to flatten aggregate subqueries. Was:
  120971. ** (2) If the subquery is an aggregate then
  120972. ** (2a) the outer query must not be a join and
  120973. ** (2b) the outer query must not use subqueries
  120974. ** other than the one FROM-clause subquery that is a candidate
  120975. ** for flattening. (This is due to ticket [2f7170d73bf9abf80]
  120976. ** from 2015-02-09.)
  120977. **
  120978. ** (3) If the subquery is the right operand of a LEFT JOIN then
  120979. ** (3a) the subquery may not be a join and
  120980. ** (3b) the FROM clause of the subquery may not contain a virtual
  120981. ** table and
  120982. ** (3c) the outer query may not be an aggregate.
  120983. **
  120984. ** (4) The subquery can not be DISTINCT.
  120985. **
  120986. ** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT
  120987. ** sub-queries that were excluded from this optimization. Restriction
  120988. ** (4) has since been expanded to exclude all DISTINCT subqueries.
  120989. **
  120990. ** (**) We no longer attempt to flatten aggregate subqueries. Was:
  120991. ** If the subquery is aggregate, the outer query may not be DISTINCT.
  120992. **
  120993. ** (7) The subquery must have a FROM clause. TODO: For subqueries without
  120994. ** A FROM clause, consider adding a FROM clause with the special
  120995. ** table sqlite_once that consists of a single row containing a
  120996. ** single NULL.
  120997. **
  120998. ** (8) If the subquery uses LIMIT then the outer query may not be a join.
  120999. **
  121000. ** (9) If the subquery uses LIMIT then the outer query may not be aggregate.
  121001. **
  121002. ** (**) Restriction (10) was removed from the code on 2005-02-05 but we
  121003. ** accidently carried the comment forward until 2014-09-15. Original
  121004. ** constraint: "If the subquery is aggregate then the outer query
  121005. ** may not use LIMIT."
  121006. **
  121007. ** (11) The subquery and the outer query may not both have ORDER BY clauses.
  121008. **
  121009. ** (**) Not implemented. Subsumed into restriction (3). Was previously
  121010. ** a separate restriction deriving from ticket #350.
  121011. **
  121012. ** (13) The subquery and outer query may not both use LIMIT.
  121013. **
  121014. ** (14) The subquery may not use OFFSET.
  121015. **
  121016. ** (15) If the outer query is part of a compound select, then the
  121017. ** subquery may not use LIMIT.
  121018. ** (See ticket #2339 and ticket [02a8e81d44]).
  121019. **
  121020. ** (16) If the outer query is aggregate, then the subquery may not
  121021. ** use ORDER BY. (Ticket #2942) This used to not matter
  121022. ** until we introduced the group_concat() function.
  121023. **
  121024. ** (17) If the subquery is a compound select, then
  121025. ** (17a) all compound operators must be a UNION ALL, and
  121026. ** (17b) no terms within the subquery compound may be aggregate
  121027. ** or DISTINCT, and
  121028. ** (17c) every term within the subquery compound must have a FROM clause
  121029. ** (17d) the outer query may not be
  121030. ** (17d1) aggregate, or
  121031. ** (17d2) DISTINCT, or
  121032. ** (17d3) a join.
  121033. **
  121034. ** The parent and sub-query may contain WHERE clauses. Subject to
  121035. ** rules (11), (13) and (14), they may also contain ORDER BY,
  121036. ** LIMIT and OFFSET clauses. The subquery cannot use any compound
  121037. ** operator other than UNION ALL because all the other compound
  121038. ** operators have an implied DISTINCT which is disallowed by
  121039. ** restriction (4).
  121040. **
  121041. ** Also, each component of the sub-query must return the same number
  121042. ** of result columns. This is actually a requirement for any compound
  121043. ** SELECT statement, but all the code here does is make sure that no
  121044. ** such (illegal) sub-query is flattened. The caller will detect the
  121045. ** syntax error and return a detailed message.
  121046. **
  121047. ** (18) If the sub-query is a compound select, then all terms of the
  121048. ** ORDER BY clause of the parent must be simple references to
  121049. ** columns of the sub-query.
  121050. **
  121051. ** (19) If the subquery uses LIMIT then the outer query may not
  121052. ** have a WHERE clause.
  121053. **
  121054. ** (20) If the sub-query is a compound select, then it must not use
  121055. ** an ORDER BY clause. Ticket #3773. We could relax this constraint
  121056. ** somewhat by saying that the terms of the ORDER BY clause must
  121057. ** appear as unmodified result columns in the outer query. But we
  121058. ** have other optimizations in mind to deal with that case.
  121059. **
  121060. ** (21) If the subquery uses LIMIT then the outer query may not be
  121061. ** DISTINCT. (See ticket [752e1646fc]).
  121062. **
  121063. ** (22) The subquery may not be a recursive CTE.
  121064. **
  121065. ** (**) Subsumed into restriction (17d3). Was: If the outer query is
  121066. ** a recursive CTE, then the sub-query may not be a compound query.
  121067. ** This restriction is because transforming the
  121068. ** parent to a compound query confuses the code that handles
  121069. ** recursive queries in multiSelect().
  121070. **
  121071. ** (**) We no longer attempt to flatten aggregate subqueries. Was:
  121072. ** The subquery may not be an aggregate that uses the built-in min() or
  121073. ** or max() functions. (Without this restriction, a query like:
  121074. ** "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily
  121075. ** return the value X for which Y was maximal.)
  121076. **
  121077. ** (25) If either the subquery or the parent query contains a window
  121078. ** function in the select list or ORDER BY clause, flattening
  121079. ** is not attempted.
  121080. **
  121081. **
  121082. ** In this routine, the "p" parameter is a pointer to the outer query.
  121083. ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
  121084. ** uses aggregates.
  121085. **
  121086. ** If flattening is not attempted, this routine is a no-op and returns 0.
  121087. ** If flattening is attempted this routine returns 1.
  121088. **
  121089. ** All of the expression analysis must occur on both the outer query and
  121090. ** the subquery before this routine runs.
  121091. */
  121092. static int flattenSubquery(
  121093. Parse *pParse, /* Parsing context */
  121094. Select *p, /* The parent or outer SELECT statement */
  121095. int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
  121096. int isAgg /* True if outer SELECT uses aggregate functions */
  121097. ){
  121098. const char *zSavedAuthContext = pParse->zAuthContext;
  121099. Select *pParent; /* Current UNION ALL term of the other query */
  121100. Select *pSub; /* The inner query or "subquery" */
  121101. Select *pSub1; /* Pointer to the rightmost select in sub-query */
  121102. SrcList *pSrc; /* The FROM clause of the outer query */
  121103. SrcList *pSubSrc; /* The FROM clause of the subquery */
  121104. int iParent; /* VDBE cursor number of the pSub result set temp table */
  121105. int iNewParent = -1;/* Replacement table for iParent */
  121106. int isLeftJoin = 0; /* True if pSub is the right side of a LEFT JOIN */
  121107. int i; /* Loop counter */
  121108. Expr *pWhere; /* The WHERE clause */
  121109. struct SrcList_item *pSubitem; /* The subquery */
  121110. sqlite3 *db = pParse->db;
  121111. /* Check to see if flattening is permitted. Return 0 if not.
  121112. */
  121113. assert( p!=0 );
  121114. assert( p->pPrior==0 );
  121115. if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
  121116. pSrc = p->pSrc;
  121117. assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
  121118. pSubitem = &pSrc->a[iFrom];
  121119. iParent = pSubitem->iCursor;
  121120. pSub = pSubitem->pSelect;
  121121. assert( pSub!=0 );
  121122. #ifndef SQLITE_OMIT_WINDOWFUNC
  121123. if( p->pWin || pSub->pWin ) return 0; /* Restriction (25) */
  121124. #endif
  121125. pSubSrc = pSub->pSrc;
  121126. assert( pSubSrc );
  121127. /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
  121128. ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET
  121129. ** because they could be computed at compile-time. But when LIMIT and OFFSET
  121130. ** became arbitrary expressions, we were forced to add restrictions (13)
  121131. ** and (14). */
  121132. if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */
  121133. if( pSub->pLimit && pSub->pLimit->pRight ) return 0; /* Restriction (14) */
  121134. if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){
  121135. return 0; /* Restriction (15) */
  121136. }
  121137. if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */
  121138. if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (4) */
  121139. if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
  121140. return 0; /* Restrictions (8)(9) */
  121141. }
  121142. if( p->pOrderBy && pSub->pOrderBy ){
  121143. return 0; /* Restriction (11) */
  121144. }
  121145. if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */
  121146. if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */
  121147. if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
  121148. return 0; /* Restriction (21) */
  121149. }
  121150. if( pSub->selFlags & (SF_Recursive) ){
  121151. return 0; /* Restrictions (22) */
  121152. }
  121153. /*
  121154. ** If the subquery is the right operand of a LEFT JOIN, then the
  121155. ** subquery may not be a join itself (3a). Example of why this is not
  121156. ** allowed:
  121157. **
  121158. ** t1 LEFT OUTER JOIN (t2 JOIN t3)
  121159. **
  121160. ** If we flatten the above, we would get
  121161. **
  121162. ** (t1 LEFT OUTER JOIN t2) JOIN t3
  121163. **
  121164. ** which is not at all the same thing.
  121165. **
  121166. ** If the subquery is the right operand of a LEFT JOIN, then the outer
  121167. ** query cannot be an aggregate. (3c) This is an artifact of the way
  121168. ** aggregates are processed - there is no mechanism to determine if
  121169. ** the LEFT JOIN table should be all-NULL.
  121170. **
  121171. ** See also tickets #306, #350, and #3300.
  121172. */
  121173. if( (pSubitem->fg.jointype & JT_OUTER)!=0 ){
  121174. isLeftJoin = 1;
  121175. if( pSubSrc->nSrc>1 || isAgg || IsVirtual(pSubSrc->a[0].pTab) ){
  121176. /* (3a) (3c) (3b) */
  121177. return 0;
  121178. }
  121179. }
  121180. #ifdef SQLITE_EXTRA_IFNULLROW
  121181. else if( iFrom>0 && !isAgg ){
  121182. /* Setting isLeftJoin to -1 causes OP_IfNullRow opcodes to be generated for
  121183. ** every reference to any result column from subquery in a join, even
  121184. ** though they are not necessary. This will stress-test the OP_IfNullRow
  121185. ** opcode. */
  121186. isLeftJoin = -1;
  121187. }
  121188. #endif
  121189. /* Restriction (17): If the sub-query is a compound SELECT, then it must
  121190. ** use only the UNION ALL operator. And none of the simple select queries
  121191. ** that make up the compound SELECT are allowed to be aggregate or distinct
  121192. ** queries.
  121193. */
  121194. if( pSub->pPrior ){
  121195. if( pSub->pOrderBy ){
  121196. return 0; /* Restriction (20) */
  121197. }
  121198. if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
  121199. return 0; /* (17d1), (17d2), or (17d3) */
  121200. }
  121201. for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
  121202. testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
  121203. testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
  121204. assert( pSub->pSrc!=0 );
  121205. assert( pSub->pEList->nExpr==pSub1->pEList->nExpr );
  121206. if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0 /* (17b) */
  121207. || (pSub1->pPrior && pSub1->op!=TK_ALL) /* (17a) */
  121208. || pSub1->pSrc->nSrc<1 /* (17c) */
  121209. ){
  121210. return 0;
  121211. }
  121212. testcase( pSub1->pSrc->nSrc>1 );
  121213. }
  121214. /* Restriction (18). */
  121215. if( p->pOrderBy ){
  121216. int ii;
  121217. for(ii=0; ii<p->pOrderBy->nExpr; ii++){
  121218. if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
  121219. }
  121220. }
  121221. }
  121222. /* Ex-restriction (23):
  121223. ** The only way that the recursive part of a CTE can contain a compound
  121224. ** subquery is for the subquery to be one term of a join. But if the
  121225. ** subquery is a join, then the flattening has already been stopped by
  121226. ** restriction (17d3)
  121227. */
  121228. assert( (p->selFlags & SF_Recursive)==0 || pSub->pPrior==0 );
  121229. /***** If we reach this point, flattening is permitted. *****/
  121230. SELECTTRACE(1,pParse,p,("flatten %u.%p from term %d\n",
  121231. pSub->selId, pSub, iFrom));
  121232. /* Authorize the subquery */
  121233. pParse->zAuthContext = pSubitem->zName;
  121234. TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
  121235. testcase( i==SQLITE_DENY );
  121236. pParse->zAuthContext = zSavedAuthContext;
  121237. /* If the sub-query is a compound SELECT statement, then (by restrictions
  121238. ** 17 and 18 above) it must be a UNION ALL and the parent query must
  121239. ** be of the form:
  121240. **
  121241. ** SELECT <expr-list> FROM (<sub-query>) <where-clause>
  121242. **
  121243. ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
  121244. ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
  121245. ** OFFSET clauses and joins them to the left-hand-side of the original
  121246. ** using UNION ALL operators. In this case N is the number of simple
  121247. ** select statements in the compound sub-query.
  121248. **
  121249. ** Example:
  121250. **
  121251. ** SELECT a+1 FROM (
  121252. ** SELECT x FROM tab
  121253. ** UNION ALL
  121254. ** SELECT y FROM tab
  121255. ** UNION ALL
  121256. ** SELECT abs(z*2) FROM tab2
  121257. ** ) WHERE a!=5 ORDER BY 1
  121258. **
  121259. ** Transformed into:
  121260. **
  121261. ** SELECT x+1 FROM tab WHERE x+1!=5
  121262. ** UNION ALL
  121263. ** SELECT y+1 FROM tab WHERE y+1!=5
  121264. ** UNION ALL
  121265. ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
  121266. ** ORDER BY 1
  121267. **
  121268. ** We call this the "compound-subquery flattening".
  121269. */
  121270. for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
  121271. Select *pNew;
  121272. ExprList *pOrderBy = p->pOrderBy;
  121273. Expr *pLimit = p->pLimit;
  121274. Select *pPrior = p->pPrior;
  121275. p->pOrderBy = 0;
  121276. p->pSrc = 0;
  121277. p->pPrior = 0;
  121278. p->pLimit = 0;
  121279. pNew = sqlite3SelectDup(db, p, 0);
  121280. p->pLimit = pLimit;
  121281. p->pOrderBy = pOrderBy;
  121282. p->pSrc = pSrc;
  121283. p->op = TK_ALL;
  121284. if( pNew==0 ){
  121285. p->pPrior = pPrior;
  121286. }else{
  121287. pNew->pPrior = pPrior;
  121288. if( pPrior ) pPrior->pNext = pNew;
  121289. pNew->pNext = p;
  121290. p->pPrior = pNew;
  121291. SELECTTRACE(2,pParse,p,("compound-subquery flattener"
  121292. " creates %u as peer\n",pNew->selId));
  121293. }
  121294. if( db->mallocFailed ) return 1;
  121295. }
  121296. /* Begin flattening the iFrom-th entry of the FROM clause
  121297. ** in the outer query.
  121298. */
  121299. pSub = pSub1 = pSubitem->pSelect;
  121300. /* Delete the transient table structure associated with the
  121301. ** subquery
  121302. */
  121303. sqlite3DbFree(db, pSubitem->zDatabase);
  121304. sqlite3DbFree(db, pSubitem->zName);
  121305. sqlite3DbFree(db, pSubitem->zAlias);
  121306. pSubitem->zDatabase = 0;
  121307. pSubitem->zName = 0;
  121308. pSubitem->zAlias = 0;
  121309. pSubitem->pSelect = 0;
  121310. /* Defer deleting the Table object associated with the
  121311. ** subquery until code generation is
  121312. ** complete, since there may still exist Expr.pTab entries that
  121313. ** refer to the subquery even after flattening. Ticket #3346.
  121314. **
  121315. ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
  121316. */
  121317. if( ALWAYS(pSubitem->pTab!=0) ){
  121318. Table *pTabToDel = pSubitem->pTab;
  121319. if( pTabToDel->nTabRef==1 ){
  121320. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  121321. pTabToDel->pNextZombie = pToplevel->pZombieTab;
  121322. pToplevel->pZombieTab = pTabToDel;
  121323. }else{
  121324. pTabToDel->nTabRef--;
  121325. }
  121326. pSubitem->pTab = 0;
  121327. }
  121328. /* The following loop runs once for each term in a compound-subquery
  121329. ** flattening (as described above). If we are doing a different kind
  121330. ** of flattening - a flattening other than a compound-subquery flattening -
  121331. ** then this loop only runs once.
  121332. **
  121333. ** This loop moves all of the FROM elements of the subquery into the
  121334. ** the FROM clause of the outer query. Before doing this, remember
  121335. ** the cursor number for the original outer query FROM element in
  121336. ** iParent. The iParent cursor will never be used. Subsequent code
  121337. ** will scan expressions looking for iParent references and replace
  121338. ** those references with expressions that resolve to the subquery FROM
  121339. ** elements we are now copying in.
  121340. */
  121341. for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
  121342. int nSubSrc;
  121343. u8 jointype = 0;
  121344. pSubSrc = pSub->pSrc; /* FROM clause of subquery */
  121345. nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */
  121346. pSrc = pParent->pSrc; /* FROM clause of the outer query */
  121347. if( pSrc ){
  121348. assert( pParent==p ); /* First time through the loop */
  121349. jointype = pSubitem->fg.jointype;
  121350. }else{
  121351. assert( pParent!=p ); /* 2nd and subsequent times through the loop */
  121352. pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0);
  121353. if( pSrc==0 ) break;
  121354. pParent->pSrc = pSrc;
  121355. }
  121356. /* The subquery uses a single slot of the FROM clause of the outer
  121357. ** query. If the subquery has more than one element in its FROM clause,
  121358. ** then expand the outer query to make space for it to hold all elements
  121359. ** of the subquery.
  121360. **
  121361. ** Example:
  121362. **
  121363. ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
  121364. **
  121365. ** The outer query has 3 slots in its FROM clause. One slot of the
  121366. ** outer query (the middle slot) is used by the subquery. The next
  121367. ** block of code will expand the outer query FROM clause to 4 slots.
  121368. ** The middle slot is expanded to two slots in order to make space
  121369. ** for the two elements in the FROM clause of the subquery.
  121370. */
  121371. if( nSubSrc>1 ){
  121372. pSrc = sqlite3SrcListEnlarge(pParse, pSrc, nSubSrc-1,iFrom+1);
  121373. if( pSrc==0 ) break;
  121374. pParent->pSrc = pSrc;
  121375. }
  121376. /* Transfer the FROM clause terms from the subquery into the
  121377. ** outer query.
  121378. */
  121379. for(i=0; i<nSubSrc; i++){
  121380. sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
  121381. assert( pSrc->a[i+iFrom].fg.isTabFunc==0 );
  121382. pSrc->a[i+iFrom] = pSubSrc->a[i];
  121383. iNewParent = pSubSrc->a[i].iCursor;
  121384. memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
  121385. }
  121386. pSrc->a[iFrom].fg.jointype = jointype;
  121387. /* Now begin substituting subquery result set expressions for
  121388. ** references to the iParent in the outer query.
  121389. **
  121390. ** Example:
  121391. **
  121392. ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
  121393. ** \ \_____________ subquery __________/ /
  121394. ** \_____________________ outer query ______________________________/
  121395. **
  121396. ** We look at every expression in the outer query and every place we see
  121397. ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
  121398. */
  121399. if( pSub->pOrderBy ){
  121400. /* At this point, any non-zero iOrderByCol values indicate that the
  121401. ** ORDER BY column expression is identical to the iOrderByCol'th
  121402. ** expression returned by SELECT statement pSub. Since these values
  121403. ** do not necessarily correspond to columns in SELECT statement pParent,
  121404. ** zero them before transfering the ORDER BY clause.
  121405. **
  121406. ** Not doing this may cause an error if a subsequent call to this
  121407. ** function attempts to flatten a compound sub-query into pParent
  121408. ** (the only way this can happen is if the compound sub-query is
  121409. ** currently part of pSub->pSrc). See ticket [d11a6e908f]. */
  121410. ExprList *pOrderBy = pSub->pOrderBy;
  121411. for(i=0; i<pOrderBy->nExpr; i++){
  121412. pOrderBy->a[i].u.x.iOrderByCol = 0;
  121413. }
  121414. assert( pParent->pOrderBy==0 );
  121415. pParent->pOrderBy = pOrderBy;
  121416. pSub->pOrderBy = 0;
  121417. }
  121418. pWhere = pSub->pWhere;
  121419. pSub->pWhere = 0;
  121420. if( isLeftJoin>0 ){
  121421. setJoinExpr(pWhere, iNewParent);
  121422. }
  121423. pParent->pWhere = sqlite3ExprAnd(pParse, pWhere, pParent->pWhere);
  121424. if( db->mallocFailed==0 ){
  121425. SubstContext x;
  121426. x.pParse = pParse;
  121427. x.iTable = iParent;
  121428. x.iNewTable = iNewParent;
  121429. x.isLeftJoin = isLeftJoin;
  121430. x.pEList = pSub->pEList;
  121431. substSelect(&x, pParent, 0);
  121432. }
  121433. /* The flattened query is a compound if either the inner or the
  121434. ** outer query is a compound. */
  121435. pParent->selFlags |= pSub->selFlags & SF_Compound;
  121436. assert( (pSub->selFlags & SF_Distinct)==0 ); /* restriction (17b) */
  121437. /*
  121438. ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
  121439. **
  121440. ** One is tempted to try to add a and b to combine the limits. But this
  121441. ** does not work if either limit is negative.
  121442. */
  121443. if( pSub->pLimit ){
  121444. pParent->pLimit = pSub->pLimit;
  121445. pSub->pLimit = 0;
  121446. }
  121447. }
  121448. /* Finially, delete what is left of the subquery and return
  121449. ** success.
  121450. */
  121451. sqlite3SelectDelete(db, pSub1);
  121452. #if SELECTTRACE_ENABLED
  121453. if( sqlite3SelectTrace & 0x100 ){
  121454. SELECTTRACE(0x100,pParse,p,("After flattening:\n"));
  121455. sqlite3TreeViewSelect(0, p, 0);
  121456. }
  121457. #endif
  121458. return 1;
  121459. }
  121460. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  121461. /*
  121462. ** A structure to keep track of all of the column values that are fixed to
  121463. ** a known value due to WHERE clause constraints of the form COLUMN=VALUE.
  121464. */
  121465. typedef struct WhereConst WhereConst;
  121466. struct WhereConst {
  121467. Parse *pParse; /* Parsing context */
  121468. int nConst; /* Number for COLUMN=CONSTANT terms */
  121469. int nChng; /* Number of times a constant is propagated */
  121470. Expr **apExpr; /* [i*2] is COLUMN and [i*2+1] is VALUE */
  121471. };
  121472. /*
  121473. ** Add a new entry to the pConst object. Except, do not add duplicate
  121474. ** pColumn entires.
  121475. */
  121476. static void constInsert(
  121477. WhereConst *pConst, /* The WhereConst into which we are inserting */
  121478. Expr *pColumn, /* The COLUMN part of the constraint */
  121479. Expr *pValue /* The VALUE part of the constraint */
  121480. ){
  121481. int i;
  121482. assert( pColumn->op==TK_COLUMN );
  121483. /* 2018-10-25 ticket [cf5ed20f]
  121484. ** Make sure the same pColumn is not inserted more than once */
  121485. for(i=0; i<pConst->nConst; i++){
  121486. const Expr *pExpr = pConst->apExpr[i*2];
  121487. assert( pExpr->op==TK_COLUMN );
  121488. if( pExpr->iTable==pColumn->iTable
  121489. && pExpr->iColumn==pColumn->iColumn
  121490. ){
  121491. return; /* Already present. Return without doing anything. */
  121492. }
  121493. }
  121494. pConst->nConst++;
  121495. pConst->apExpr = sqlite3DbReallocOrFree(pConst->pParse->db, pConst->apExpr,
  121496. pConst->nConst*2*sizeof(Expr*));
  121497. if( pConst->apExpr==0 ){
  121498. pConst->nConst = 0;
  121499. }else{
  121500. if( ExprHasProperty(pValue, EP_FixedCol) ) pValue = pValue->pLeft;
  121501. pConst->apExpr[pConst->nConst*2-2] = pColumn;
  121502. pConst->apExpr[pConst->nConst*2-1] = pValue;
  121503. }
  121504. }
  121505. /*
  121506. ** Find all terms of COLUMN=VALUE or VALUE=COLUMN in pExpr where VALUE
  121507. ** is a constant expression and where the term must be true because it
  121508. ** is part of the AND-connected terms of the expression. For each term
  121509. ** found, add it to the pConst structure.
  121510. */
  121511. static void findConstInWhere(WhereConst *pConst, Expr *pExpr){
  121512. Expr *pRight, *pLeft;
  121513. if( pExpr==0 ) return;
  121514. if( ExprHasProperty(pExpr, EP_FromJoin) ) return;
  121515. if( pExpr->op==TK_AND ){
  121516. findConstInWhere(pConst, pExpr->pRight);
  121517. findConstInWhere(pConst, pExpr->pLeft);
  121518. return;
  121519. }
  121520. if( pExpr->op!=TK_EQ ) return;
  121521. pRight = pExpr->pRight;
  121522. pLeft = pExpr->pLeft;
  121523. assert( pRight!=0 );
  121524. assert( pLeft!=0 );
  121525. if( pRight->op==TK_COLUMN
  121526. && !ExprHasProperty(pRight, EP_FixedCol)
  121527. && sqlite3ExprIsConstant(pLeft)
  121528. && sqlite3IsBinary(sqlite3BinaryCompareCollSeq(pConst->pParse,pLeft,pRight))
  121529. ){
  121530. constInsert(pConst, pRight, pLeft);
  121531. }else
  121532. if( pLeft->op==TK_COLUMN
  121533. && !ExprHasProperty(pLeft, EP_FixedCol)
  121534. && sqlite3ExprIsConstant(pRight)
  121535. && sqlite3IsBinary(sqlite3BinaryCompareCollSeq(pConst->pParse,pLeft,pRight))
  121536. ){
  121537. constInsert(pConst, pLeft, pRight);
  121538. }
  121539. }
  121540. /*
  121541. ** This is a Walker expression callback. pExpr is a candidate expression
  121542. ** to be replaced by a value. If pExpr is equivalent to one of the
  121543. ** columns named in pWalker->u.pConst, then overwrite it with its
  121544. ** corresponding value.
  121545. */
  121546. static int propagateConstantExprRewrite(Walker *pWalker, Expr *pExpr){
  121547. int i;
  121548. WhereConst *pConst;
  121549. if( pExpr->op!=TK_COLUMN ) return WRC_Continue;
  121550. if( ExprHasProperty(pExpr, EP_FixedCol) ) return WRC_Continue;
  121551. pConst = pWalker->u.pConst;
  121552. for(i=0; i<pConst->nConst; i++){
  121553. Expr *pColumn = pConst->apExpr[i*2];
  121554. if( pColumn==pExpr ) continue;
  121555. if( pColumn->iTable!=pExpr->iTable ) continue;
  121556. if( pColumn->iColumn!=pExpr->iColumn ) continue;
  121557. /* A match is found. Add the EP_FixedCol property */
  121558. pConst->nChng++;
  121559. ExprClearProperty(pExpr, EP_Leaf);
  121560. ExprSetProperty(pExpr, EP_FixedCol);
  121561. assert( pExpr->pLeft==0 );
  121562. pExpr->pLeft = sqlite3ExprDup(pConst->pParse->db, pConst->apExpr[i*2+1], 0);
  121563. break;
  121564. }
  121565. return WRC_Prune;
  121566. }
  121567. /*
  121568. ** The WHERE-clause constant propagation optimization.
  121569. **
  121570. ** If the WHERE clause contains terms of the form COLUMN=CONSTANT or
  121571. ** CONSTANT=COLUMN that must be tree (in other words, if the terms top-level
  121572. ** AND-connected terms that are not part of a ON clause from a LEFT JOIN)
  121573. ** then throughout the query replace all other occurrences of COLUMN
  121574. ** with CONSTANT within the WHERE clause.
  121575. **
  121576. ** For example, the query:
  121577. **
  121578. ** SELECT * FROM t1, t2, t3 WHERE t1.a=39 AND t2.b=t1.a AND t3.c=t2.b
  121579. **
  121580. ** Is transformed into
  121581. **
  121582. ** SELECT * FROM t1, t2, t3 WHERE t1.a=39 AND t2.b=39 AND t3.c=39
  121583. **
  121584. ** Return true if any transformations where made and false if not.
  121585. **
  121586. ** Implementation note: Constant propagation is tricky due to affinity
  121587. ** and collating sequence interactions. Consider this example:
  121588. **
  121589. ** CREATE TABLE t1(a INT,b TEXT);
  121590. ** INSERT INTO t1 VALUES(123,'0123');
  121591. ** SELECT * FROM t1 WHERE a=123 AND b=a;
  121592. ** SELECT * FROM t1 WHERE a=123 AND b=123;
  121593. **
  121594. ** The two SELECT statements above should return different answers. b=a
  121595. ** is alway true because the comparison uses numeric affinity, but b=123
  121596. ** is false because it uses text affinity and '0123' is not the same as '123'.
  121597. ** To work around this, the expression tree is not actually changed from
  121598. ** "b=a" to "b=123" but rather the "a" in "b=a" is tagged with EP_FixedCol
  121599. ** and the "123" value is hung off of the pLeft pointer. Code generator
  121600. ** routines know to generate the constant "123" instead of looking up the
  121601. ** column value. Also, to avoid collation problems, this optimization is
  121602. ** only attempted if the "a=123" term uses the default BINARY collation.
  121603. */
  121604. static int propagateConstants(
  121605. Parse *pParse, /* The parsing context */
  121606. Select *p /* The query in which to propagate constants */
  121607. ){
  121608. WhereConst x;
  121609. Walker w;
  121610. int nChng = 0;
  121611. x.pParse = pParse;
  121612. do{
  121613. x.nConst = 0;
  121614. x.nChng = 0;
  121615. x.apExpr = 0;
  121616. findConstInWhere(&x, p->pWhere);
  121617. if( x.nConst ){
  121618. memset(&w, 0, sizeof(w));
  121619. w.pParse = pParse;
  121620. w.xExprCallback = propagateConstantExprRewrite;
  121621. w.xSelectCallback = sqlite3SelectWalkNoop;
  121622. w.xSelectCallback2 = 0;
  121623. w.walkerDepth = 0;
  121624. w.u.pConst = &x;
  121625. sqlite3WalkExpr(&w, p->pWhere);
  121626. sqlite3DbFree(x.pParse->db, x.apExpr);
  121627. nChng += x.nChng;
  121628. }
  121629. }while( x.nChng );
  121630. return nChng;
  121631. }
  121632. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  121633. /*
  121634. ** Make copies of relevant WHERE clause terms of the outer query into
  121635. ** the WHERE clause of subquery. Example:
  121636. **
  121637. ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1) WHERE x=5 AND y=10;
  121638. **
  121639. ** Transformed into:
  121640. **
  121641. ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1 WHERE a=5 AND c-d=10)
  121642. ** WHERE x=5 AND y=10;
  121643. **
  121644. ** The hope is that the terms added to the inner query will make it more
  121645. ** efficient.
  121646. **
  121647. ** Do not attempt this optimization if:
  121648. **
  121649. ** (1) (** This restriction was removed on 2017-09-29. We used to
  121650. ** disallow this optimization for aggregate subqueries, but now
  121651. ** it is allowed by putting the extra terms on the HAVING clause.
  121652. ** The added HAVING clause is pointless if the subquery lacks
  121653. ** a GROUP BY clause. But such a HAVING clause is also harmless
  121654. ** so there does not appear to be any reason to add extra logic
  121655. ** to suppress it. **)
  121656. **
  121657. ** (2) The inner query is the recursive part of a common table expression.
  121658. **
  121659. ** (3) The inner query has a LIMIT clause (since the changes to the WHERE
  121660. ** clause would change the meaning of the LIMIT).
  121661. **
  121662. ** (4) The inner query is the right operand of a LEFT JOIN and the
  121663. ** expression to be pushed down does not come from the ON clause
  121664. ** on that LEFT JOIN.
  121665. **
  121666. ** (5) The WHERE clause expression originates in the ON or USING clause
  121667. ** of a LEFT JOIN where iCursor is not the right-hand table of that
  121668. ** left join. An example:
  121669. **
  121670. ** SELECT *
  121671. ** FROM (SELECT 1 AS a1 UNION ALL SELECT 2) AS aa
  121672. ** JOIN (SELECT 1 AS b2 UNION ALL SELECT 2) AS bb ON (a1=b2)
  121673. ** LEFT JOIN (SELECT 8 AS c3 UNION ALL SELECT 9) AS cc ON (b2=2);
  121674. **
  121675. ** The correct answer is three rows: (1,1,NULL),(2,2,8),(2,2,9).
  121676. ** But if the (b2=2) term were to be pushed down into the bb subquery,
  121677. ** then the (1,1,NULL) row would be suppressed.
  121678. **
  121679. ** (6) The inner query features one or more window-functions (since
  121680. ** changes to the WHERE clause of the inner query could change the
  121681. ** window over which window functions are calculated).
  121682. **
  121683. ** Return 0 if no changes are made and non-zero if one or more WHERE clause
  121684. ** terms are duplicated into the subquery.
  121685. */
  121686. static int pushDownWhereTerms(
  121687. Parse *pParse, /* Parse context (for malloc() and error reporting) */
  121688. Select *pSubq, /* The subquery whose WHERE clause is to be augmented */
  121689. Expr *pWhere, /* The WHERE clause of the outer query */
  121690. int iCursor, /* Cursor number of the subquery */
  121691. int isLeftJoin /* True if pSubq is the right term of a LEFT JOIN */
  121692. ){
  121693. Expr *pNew;
  121694. int nChng = 0;
  121695. if( pWhere==0 ) return 0;
  121696. if( pSubq->selFlags & SF_Recursive ) return 0; /* restriction (2) */
  121697. #ifndef SQLITE_OMIT_WINDOWFUNC
  121698. if( pSubq->pWin ) return 0; /* restriction (6) */
  121699. #endif
  121700. #ifdef SQLITE_DEBUG
  121701. /* Only the first term of a compound can have a WITH clause. But make
  121702. ** sure no other terms are marked SF_Recursive in case something changes
  121703. ** in the future.
  121704. */
  121705. {
  121706. Select *pX;
  121707. for(pX=pSubq; pX; pX=pX->pPrior){
  121708. assert( (pX->selFlags & (SF_Recursive))==0 );
  121709. }
  121710. }
  121711. #endif
  121712. if( pSubq->pLimit!=0 ){
  121713. return 0; /* restriction (3) */
  121714. }
  121715. while( pWhere->op==TK_AND ){
  121716. nChng += pushDownWhereTerms(pParse, pSubq, pWhere->pRight,
  121717. iCursor, isLeftJoin);
  121718. pWhere = pWhere->pLeft;
  121719. }
  121720. if( isLeftJoin
  121721. && (ExprHasProperty(pWhere,EP_FromJoin)==0
  121722. || pWhere->iRightJoinTable!=iCursor)
  121723. ){
  121724. return 0; /* restriction (4) */
  121725. }
  121726. if( ExprHasProperty(pWhere,EP_FromJoin) && pWhere->iRightJoinTable!=iCursor ){
  121727. return 0; /* restriction (5) */
  121728. }
  121729. if( sqlite3ExprIsTableConstant(pWhere, iCursor) ){
  121730. nChng++;
  121731. while( pSubq ){
  121732. SubstContext x;
  121733. pNew = sqlite3ExprDup(pParse->db, pWhere, 0);
  121734. unsetJoinExpr(pNew, -1);
  121735. x.pParse = pParse;
  121736. x.iTable = iCursor;
  121737. x.iNewTable = iCursor;
  121738. x.isLeftJoin = 0;
  121739. x.pEList = pSubq->pEList;
  121740. pNew = substExpr(&x, pNew);
  121741. if( pSubq->selFlags & SF_Aggregate ){
  121742. pSubq->pHaving = sqlite3ExprAnd(pParse, pSubq->pHaving, pNew);
  121743. }else{
  121744. pSubq->pWhere = sqlite3ExprAnd(pParse, pSubq->pWhere, pNew);
  121745. }
  121746. pSubq = pSubq->pPrior;
  121747. }
  121748. }
  121749. return nChng;
  121750. }
  121751. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  121752. /*
  121753. ** The pFunc is the only aggregate function in the query. Check to see
  121754. ** if the query is a candidate for the min/max optimization.
  121755. **
  121756. ** If the query is a candidate for the min/max optimization, then set
  121757. ** *ppMinMax to be an ORDER BY clause to be used for the optimization
  121758. ** and return either WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX depending on
  121759. ** whether pFunc is a min() or max() function.
  121760. **
  121761. ** If the query is not a candidate for the min/max optimization, return
  121762. ** WHERE_ORDERBY_NORMAL (which must be zero).
  121763. **
  121764. ** This routine must be called after aggregate functions have been
  121765. ** located but before their arguments have been subjected to aggregate
  121766. ** analysis.
  121767. */
  121768. static u8 minMaxQuery(sqlite3 *db, Expr *pFunc, ExprList **ppMinMax){
  121769. int eRet = WHERE_ORDERBY_NORMAL; /* Return value */
  121770. ExprList *pEList = pFunc->x.pList; /* Arguments to agg function */
  121771. const char *zFunc; /* Name of aggregate function pFunc */
  121772. ExprList *pOrderBy;
  121773. u8 sortOrder;
  121774. assert( *ppMinMax==0 );
  121775. assert( pFunc->op==TK_AGG_FUNCTION );
  121776. if( pEList==0 || pEList->nExpr!=1 ) return eRet;
  121777. zFunc = pFunc->u.zToken;
  121778. if( sqlite3StrICmp(zFunc, "min")==0 ){
  121779. eRet = WHERE_ORDERBY_MIN;
  121780. sortOrder = SQLITE_SO_ASC;
  121781. }else if( sqlite3StrICmp(zFunc, "max")==0 ){
  121782. eRet = WHERE_ORDERBY_MAX;
  121783. sortOrder = SQLITE_SO_DESC;
  121784. }else{
  121785. return eRet;
  121786. }
  121787. *ppMinMax = pOrderBy = sqlite3ExprListDup(db, pEList, 0);
  121788. assert( pOrderBy!=0 || db->mallocFailed );
  121789. if( pOrderBy ) pOrderBy->a[0].sortOrder = sortOrder;
  121790. return eRet;
  121791. }
  121792. /*
  121793. ** The select statement passed as the first argument is an aggregate query.
  121794. ** The second argument is the associated aggregate-info object. This
  121795. ** function tests if the SELECT is of the form:
  121796. **
  121797. ** SELECT count(*) FROM <tbl>
  121798. **
  121799. ** where table is a database table, not a sub-select or view. If the query
  121800. ** does match this pattern, then a pointer to the Table object representing
  121801. ** <tbl> is returned. Otherwise, 0 is returned.
  121802. */
  121803. static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
  121804. Table *pTab;
  121805. Expr *pExpr;
  121806. assert( !p->pGroupBy );
  121807. if( p->pWhere || p->pEList->nExpr!=1
  121808. || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
  121809. ){
  121810. return 0;
  121811. }
  121812. pTab = p->pSrc->a[0].pTab;
  121813. pExpr = p->pEList->a[0].pExpr;
  121814. assert( pTab && !pTab->pSelect && pExpr );
  121815. if( IsVirtual(pTab) ) return 0;
  121816. if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
  121817. if( NEVER(pAggInfo->nFunc==0) ) return 0;
  121818. if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
  121819. if( pExpr->flags&EP_Distinct ) return 0;
  121820. return pTab;
  121821. }
  121822. /*
  121823. ** If the source-list item passed as an argument was augmented with an
  121824. ** INDEXED BY clause, then try to locate the specified index. If there
  121825. ** was such a clause and the named index cannot be found, return
  121826. ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
  121827. ** pFrom->pIndex and return SQLITE_OK.
  121828. */
  121829. SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
  121830. if( pFrom->pTab && pFrom->fg.isIndexedBy ){
  121831. Table *pTab = pFrom->pTab;
  121832. char *zIndexedBy = pFrom->u1.zIndexedBy;
  121833. Index *pIdx;
  121834. for(pIdx=pTab->pIndex;
  121835. pIdx && sqlite3StrICmp(pIdx->zName, zIndexedBy);
  121836. pIdx=pIdx->pNext
  121837. );
  121838. if( !pIdx ){
  121839. sqlite3ErrorMsg(pParse, "no such index: %s", zIndexedBy, 0);
  121840. pParse->checkSchema = 1;
  121841. return SQLITE_ERROR;
  121842. }
  121843. pFrom->pIBIndex = pIdx;
  121844. }
  121845. return SQLITE_OK;
  121846. }
  121847. /*
  121848. ** Detect compound SELECT statements that use an ORDER BY clause with
  121849. ** an alternative collating sequence.
  121850. **
  121851. ** SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
  121852. **
  121853. ** These are rewritten as a subquery:
  121854. **
  121855. ** SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
  121856. ** ORDER BY ... COLLATE ...
  121857. **
  121858. ** This transformation is necessary because the multiSelectOrderBy() routine
  121859. ** above that generates the code for a compound SELECT with an ORDER BY clause
  121860. ** uses a merge algorithm that requires the same collating sequence on the
  121861. ** result columns as on the ORDER BY clause. See ticket
  121862. ** http://www.sqlite.org/src/info/6709574d2a
  121863. **
  121864. ** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
  121865. ** The UNION ALL operator works fine with multiSelectOrderBy() even when
  121866. ** there are COLLATE terms in the ORDER BY.
  121867. */
  121868. static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
  121869. int i;
  121870. Select *pNew;
  121871. Select *pX;
  121872. sqlite3 *db;
  121873. struct ExprList_item *a;
  121874. SrcList *pNewSrc;
  121875. Parse *pParse;
  121876. Token dummy;
  121877. if( p->pPrior==0 ) return WRC_Continue;
  121878. if( p->pOrderBy==0 ) return WRC_Continue;
  121879. for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
  121880. if( pX==0 ) return WRC_Continue;
  121881. a = p->pOrderBy->a;
  121882. for(i=p->pOrderBy->nExpr-1; i>=0; i--){
  121883. if( a[i].pExpr->flags & EP_Collate ) break;
  121884. }
  121885. if( i<0 ) return WRC_Continue;
  121886. /* If we reach this point, that means the transformation is required. */
  121887. pParse = pWalker->pParse;
  121888. db = pParse->db;
  121889. pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
  121890. if( pNew==0 ) return WRC_Abort;
  121891. memset(&dummy, 0, sizeof(dummy));
  121892. pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0);
  121893. if( pNewSrc==0 ) return WRC_Abort;
  121894. *pNew = *p;
  121895. p->pSrc = pNewSrc;
  121896. p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ASTERISK, 0));
  121897. p->op = TK_SELECT;
  121898. p->pWhere = 0;
  121899. pNew->pGroupBy = 0;
  121900. pNew->pHaving = 0;
  121901. pNew->pOrderBy = 0;
  121902. p->pPrior = 0;
  121903. p->pNext = 0;
  121904. p->pWith = 0;
  121905. p->selFlags &= ~SF_Compound;
  121906. assert( (p->selFlags & SF_Converted)==0 );
  121907. p->selFlags |= SF_Converted;
  121908. assert( pNew->pPrior!=0 );
  121909. pNew->pPrior->pNext = pNew;
  121910. pNew->pLimit = 0;
  121911. return WRC_Continue;
  121912. }
  121913. /*
  121914. ** Check to see if the FROM clause term pFrom has table-valued function
  121915. ** arguments. If it does, leave an error message in pParse and return
  121916. ** non-zero, since pFrom is not allowed to be a table-valued function.
  121917. */
  121918. static int cannotBeFunction(Parse *pParse, struct SrcList_item *pFrom){
  121919. if( pFrom->fg.isTabFunc ){
  121920. sqlite3ErrorMsg(pParse, "'%s' is not a function", pFrom->zName);
  121921. return 1;
  121922. }
  121923. return 0;
  121924. }
  121925. #ifndef SQLITE_OMIT_CTE
  121926. /*
  121927. ** Argument pWith (which may be NULL) points to a linked list of nested
  121928. ** WITH contexts, from inner to outermost. If the table identified by
  121929. ** FROM clause element pItem is really a common-table-expression (CTE)
  121930. ** then return a pointer to the CTE definition for that table. Otherwise
  121931. ** return NULL.
  121932. **
  121933. ** If a non-NULL value is returned, set *ppContext to point to the With
  121934. ** object that the returned CTE belongs to.
  121935. */
  121936. static struct Cte *searchWith(
  121937. With *pWith, /* Current innermost WITH clause */
  121938. struct SrcList_item *pItem, /* FROM clause element to resolve */
  121939. With **ppContext /* OUT: WITH clause return value belongs to */
  121940. ){
  121941. const char *zName;
  121942. if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){
  121943. With *p;
  121944. for(p=pWith; p; p=p->pOuter){
  121945. int i;
  121946. for(i=0; i<p->nCte; i++){
  121947. if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){
  121948. *ppContext = p;
  121949. return &p->a[i];
  121950. }
  121951. }
  121952. }
  121953. }
  121954. return 0;
  121955. }
  121956. /* The code generator maintains a stack of active WITH clauses
  121957. ** with the inner-most WITH clause being at the top of the stack.
  121958. **
  121959. ** This routine pushes the WITH clause passed as the second argument
  121960. ** onto the top of the stack. If argument bFree is true, then this
  121961. ** WITH clause will never be popped from the stack. In this case it
  121962. ** should be freed along with the Parse object. In other cases, when
  121963. ** bFree==0, the With object will be freed along with the SELECT
  121964. ** statement with which it is associated.
  121965. */
  121966. SQLITE_PRIVATE void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
  121967. assert( bFree==0 || (pParse->pWith==0 && pParse->pWithToFree==0) );
  121968. if( pWith ){
  121969. assert( pParse->pWith!=pWith );
  121970. pWith->pOuter = pParse->pWith;
  121971. pParse->pWith = pWith;
  121972. if( bFree ) pParse->pWithToFree = pWith;
  121973. }
  121974. }
  121975. /*
  121976. ** This function checks if argument pFrom refers to a CTE declared by
  121977. ** a WITH clause on the stack currently maintained by the parser. And,
  121978. ** if currently processing a CTE expression, if it is a recursive
  121979. ** reference to the current CTE.
  121980. **
  121981. ** If pFrom falls into either of the two categories above, pFrom->pTab
  121982. ** and other fields are populated accordingly. The caller should check
  121983. ** (pFrom->pTab!=0) to determine whether or not a successful match
  121984. ** was found.
  121985. **
  121986. ** Whether or not a match is found, SQLITE_OK is returned if no error
  121987. ** occurs. If an error does occur, an error message is stored in the
  121988. ** parser and some error code other than SQLITE_OK returned.
  121989. */
  121990. static int withExpand(
  121991. Walker *pWalker,
  121992. struct SrcList_item *pFrom
  121993. ){
  121994. Parse *pParse = pWalker->pParse;
  121995. sqlite3 *db = pParse->db;
  121996. struct Cte *pCte; /* Matched CTE (or NULL if no match) */
  121997. With *pWith; /* WITH clause that pCte belongs to */
  121998. assert( pFrom->pTab==0 );
  121999. pCte = searchWith(pParse->pWith, pFrom, &pWith);
  122000. if( pCte ){
  122001. Table *pTab;
  122002. ExprList *pEList;
  122003. Select *pSel;
  122004. Select *pLeft; /* Left-most SELECT statement */
  122005. int bMayRecursive; /* True if compound joined by UNION [ALL] */
  122006. With *pSavedWith; /* Initial value of pParse->pWith */
  122007. /* If pCte->zCteErr is non-NULL at this point, then this is an illegal
  122008. ** recursive reference to CTE pCte. Leave an error in pParse and return
  122009. ** early. If pCte->zCteErr is NULL, then this is not a recursive reference.
  122010. ** In this case, proceed. */
  122011. if( pCte->zCteErr ){
  122012. sqlite3ErrorMsg(pParse, pCte->zCteErr, pCte->zName);
  122013. return SQLITE_ERROR;
  122014. }
  122015. if( cannotBeFunction(pParse, pFrom) ) return SQLITE_ERROR;
  122016. assert( pFrom->pTab==0 );
  122017. pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
  122018. if( pTab==0 ) return WRC_Abort;
  122019. pTab->nTabRef = 1;
  122020. pTab->zName = sqlite3DbStrDup(db, pCte->zName);
  122021. pTab->iPKey = -1;
  122022. pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  122023. pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid;
  122024. pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0);
  122025. if( db->mallocFailed ) return SQLITE_NOMEM_BKPT;
  122026. assert( pFrom->pSelect );
  122027. /* Check if this is a recursive CTE. */
  122028. pSel = pFrom->pSelect;
  122029. bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );
  122030. if( bMayRecursive ){
  122031. int i;
  122032. SrcList *pSrc = pFrom->pSelect->pSrc;
  122033. for(i=0; i<pSrc->nSrc; i++){
  122034. struct SrcList_item *pItem = &pSrc->a[i];
  122035. if( pItem->zDatabase==0
  122036. && pItem->zName!=0
  122037. && 0==sqlite3StrICmp(pItem->zName, pCte->zName)
  122038. ){
  122039. pItem->pTab = pTab;
  122040. pItem->fg.isRecursive = 1;
  122041. pTab->nTabRef++;
  122042. pSel->selFlags |= SF_Recursive;
  122043. }
  122044. }
  122045. }
  122046. /* Only one recursive reference is permitted. */
  122047. if( pTab->nTabRef>2 ){
  122048. sqlite3ErrorMsg(
  122049. pParse, "multiple references to recursive table: %s", pCte->zName
  122050. );
  122051. return SQLITE_ERROR;
  122052. }
  122053. assert( pTab->nTabRef==1 ||
  122054. ((pSel->selFlags&SF_Recursive) && pTab->nTabRef==2 ));
  122055. pCte->zCteErr = "circular reference: %s";
  122056. pSavedWith = pParse->pWith;
  122057. pParse->pWith = pWith;
  122058. if( bMayRecursive ){
  122059. Select *pPrior = pSel->pPrior;
  122060. assert( pPrior->pWith==0 );
  122061. pPrior->pWith = pSel->pWith;
  122062. sqlite3WalkSelect(pWalker, pPrior);
  122063. pPrior->pWith = 0;
  122064. }else{
  122065. sqlite3WalkSelect(pWalker, pSel);
  122066. }
  122067. pParse->pWith = pWith;
  122068. for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior);
  122069. pEList = pLeft->pEList;
  122070. if( pCte->pCols ){
  122071. if( pEList && pEList->nExpr!=pCte->pCols->nExpr ){
  122072. sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns",
  122073. pCte->zName, pEList->nExpr, pCte->pCols->nExpr
  122074. );
  122075. pParse->pWith = pSavedWith;
  122076. return SQLITE_ERROR;
  122077. }
  122078. pEList = pCte->pCols;
  122079. }
  122080. sqlite3ColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol);
  122081. if( bMayRecursive ){
  122082. if( pSel->selFlags & SF_Recursive ){
  122083. pCte->zCteErr = "multiple recursive references: %s";
  122084. }else{
  122085. pCte->zCteErr = "recursive reference in a subquery: %s";
  122086. }
  122087. sqlite3WalkSelect(pWalker, pSel);
  122088. }
  122089. pCte->zCteErr = 0;
  122090. pParse->pWith = pSavedWith;
  122091. }
  122092. return SQLITE_OK;
  122093. }
  122094. #endif
  122095. #ifndef SQLITE_OMIT_CTE
  122096. /*
  122097. ** If the SELECT passed as the second argument has an associated WITH
  122098. ** clause, pop it from the stack stored as part of the Parse object.
  122099. **
  122100. ** This function is used as the xSelectCallback2() callback by
  122101. ** sqlite3SelectExpand() when walking a SELECT tree to resolve table
  122102. ** names and other FROM clause elements.
  122103. */
  122104. static void selectPopWith(Walker *pWalker, Select *p){
  122105. Parse *pParse = pWalker->pParse;
  122106. if( OK_IF_ALWAYS_TRUE(pParse->pWith) && p->pPrior==0 ){
  122107. With *pWith = findRightmost(p)->pWith;
  122108. if( pWith!=0 ){
  122109. assert( pParse->pWith==pWith );
  122110. pParse->pWith = pWith->pOuter;
  122111. }
  122112. }
  122113. }
  122114. #else
  122115. #define selectPopWith 0
  122116. #endif
  122117. /*
  122118. ** The SrcList_item structure passed as the second argument represents a
  122119. ** sub-query in the FROM clause of a SELECT statement. This function
  122120. ** allocates and populates the SrcList_item.pTab object. If successful,
  122121. ** SQLITE_OK is returned. Otherwise, if an OOM error is encountered,
  122122. ** SQLITE_NOMEM.
  122123. */
  122124. SQLITE_PRIVATE int sqlite3ExpandSubquery(Parse *pParse, struct SrcList_item *pFrom){
  122125. Select *pSel = pFrom->pSelect;
  122126. Table *pTab;
  122127. assert( pSel );
  122128. pFrom->pTab = pTab = sqlite3DbMallocZero(pParse->db, sizeof(Table));
  122129. if( pTab==0 ) return SQLITE_NOMEM;
  122130. pTab->nTabRef = 1;
  122131. if( pFrom->zAlias ){
  122132. pTab->zName = sqlite3DbStrDup(pParse->db, pFrom->zAlias);
  122133. }else{
  122134. pTab->zName = sqlite3MPrintf(pParse->db, "subquery_%u", pSel->selId);
  122135. }
  122136. while( pSel->pPrior ){ pSel = pSel->pPrior; }
  122137. sqlite3ColumnsFromExprList(pParse, pSel->pEList,&pTab->nCol,&pTab->aCol);
  122138. pTab->iPKey = -1;
  122139. pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  122140. pTab->tabFlags |= TF_Ephemeral;
  122141. return pParse->nErr ? SQLITE_ERROR : SQLITE_OK;
  122142. }
  122143. /*
  122144. ** This routine is a Walker callback for "expanding" a SELECT statement.
  122145. ** "Expanding" means to do the following:
  122146. **
  122147. ** (1) Make sure VDBE cursor numbers have been assigned to every
  122148. ** element of the FROM clause.
  122149. **
  122150. ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that
  122151. ** defines FROM clause. When views appear in the FROM clause,
  122152. ** fill pTabList->a[].pSelect with a copy of the SELECT statement
  122153. ** that implements the view. A copy is made of the view's SELECT
  122154. ** statement so that we can freely modify or delete that statement
  122155. ** without worrying about messing up the persistent representation
  122156. ** of the view.
  122157. **
  122158. ** (3) Add terms to the WHERE clause to accommodate the NATURAL keyword
  122159. ** on joins and the ON and USING clause of joins.
  122160. **
  122161. ** (4) Scan the list of columns in the result set (pEList) looking
  122162. ** for instances of the "*" operator or the TABLE.* operator.
  122163. ** If found, expand each "*" to be every column in every table
  122164. ** and TABLE.* to be every column in TABLE.
  122165. **
  122166. */
  122167. static int selectExpander(Walker *pWalker, Select *p){
  122168. Parse *pParse = pWalker->pParse;
  122169. int i, j, k;
  122170. SrcList *pTabList;
  122171. ExprList *pEList;
  122172. struct SrcList_item *pFrom;
  122173. sqlite3 *db = pParse->db;
  122174. Expr *pE, *pRight, *pExpr;
  122175. u16 selFlags = p->selFlags;
  122176. u32 elistFlags = 0;
  122177. p->selFlags |= SF_Expanded;
  122178. if( db->mallocFailed ){
  122179. return WRC_Abort;
  122180. }
  122181. assert( p->pSrc!=0 );
  122182. if( (selFlags & SF_Expanded)!=0 ){
  122183. return WRC_Prune;
  122184. }
  122185. if( pWalker->eCode ){
  122186. /* Renumber selId because it has been copied from a view */
  122187. p->selId = ++pParse->nSelect;
  122188. }
  122189. pTabList = p->pSrc;
  122190. pEList = p->pEList;
  122191. sqlite3WithPush(pParse, p->pWith, 0);
  122192. /* Make sure cursor numbers have been assigned to all entries in
  122193. ** the FROM clause of the SELECT statement.
  122194. */
  122195. sqlite3SrcListAssignCursors(pParse, pTabList);
  122196. /* Look up every table named in the FROM clause of the select. If
  122197. ** an entry of the FROM clause is a subquery instead of a table or view,
  122198. ** then create a transient table structure to describe the subquery.
  122199. */
  122200. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  122201. Table *pTab;
  122202. assert( pFrom->fg.isRecursive==0 || pFrom->pTab!=0 );
  122203. if( pFrom->fg.isRecursive ) continue;
  122204. assert( pFrom->pTab==0 );
  122205. #ifndef SQLITE_OMIT_CTE
  122206. if( withExpand(pWalker, pFrom) ) return WRC_Abort;
  122207. if( pFrom->pTab ) {} else
  122208. #endif
  122209. if( pFrom->zName==0 ){
  122210. #ifndef SQLITE_OMIT_SUBQUERY
  122211. Select *pSel = pFrom->pSelect;
  122212. /* A sub-query in the FROM clause of a SELECT */
  122213. assert( pSel!=0 );
  122214. assert( pFrom->pTab==0 );
  122215. if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort;
  122216. if( sqlite3ExpandSubquery(pParse, pFrom) ) return WRC_Abort;
  122217. #endif
  122218. }else{
  122219. /* An ordinary table or view name in the FROM clause */
  122220. assert( pFrom->pTab==0 );
  122221. pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
  122222. if( pTab==0 ) return WRC_Abort;
  122223. if( pTab->nTabRef>=0xffff ){
  122224. sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
  122225. pTab->zName);
  122226. pFrom->pTab = 0;
  122227. return WRC_Abort;
  122228. }
  122229. pTab->nTabRef++;
  122230. if( !IsVirtual(pTab) && cannotBeFunction(pParse, pFrom) ){
  122231. return WRC_Abort;
  122232. }
  122233. #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
  122234. if( IsVirtual(pTab) || pTab->pSelect ){
  122235. i16 nCol;
  122236. u8 eCodeOrig = pWalker->eCode;
  122237. if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
  122238. assert( pFrom->pSelect==0 );
  122239. pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
  122240. nCol = pTab->nCol;
  122241. pTab->nCol = -1;
  122242. pWalker->eCode = 1; /* Turn on Select.selId renumbering */
  122243. sqlite3WalkSelect(pWalker, pFrom->pSelect);
  122244. pWalker->eCode = eCodeOrig;
  122245. pTab->nCol = nCol;
  122246. }
  122247. #endif
  122248. }
  122249. /* Locate the index named by the INDEXED BY clause, if any. */
  122250. if( sqlite3IndexedByLookup(pParse, pFrom) ){
  122251. return WRC_Abort;
  122252. }
  122253. }
  122254. /* Process NATURAL keywords, and ON and USING clauses of joins.
  122255. */
  122256. if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
  122257. return WRC_Abort;
  122258. }
  122259. /* For every "*" that occurs in the column list, insert the names of
  122260. ** all columns in all tables. And for every TABLE.* insert the names
  122261. ** of all columns in TABLE. The parser inserted a special expression
  122262. ** with the TK_ASTERISK operator for each "*" that it found in the column
  122263. ** list. The following code just has to locate the TK_ASTERISK
  122264. ** expressions and expand each one to the list of all columns in
  122265. ** all tables.
  122266. **
  122267. ** The first loop just checks to see if there are any "*" operators
  122268. ** that need expanding.
  122269. */
  122270. for(k=0; k<pEList->nExpr; k++){
  122271. pE = pEList->a[k].pExpr;
  122272. if( pE->op==TK_ASTERISK ) break;
  122273. assert( pE->op!=TK_DOT || pE->pRight!=0 );
  122274. assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
  122275. if( pE->op==TK_DOT && pE->pRight->op==TK_ASTERISK ) break;
  122276. elistFlags |= pE->flags;
  122277. }
  122278. if( k<pEList->nExpr ){
  122279. /*
  122280. ** If we get here it means the result set contains one or more "*"
  122281. ** operators that need to be expanded. Loop through each expression
  122282. ** in the result set and expand them one by one.
  122283. */
  122284. struct ExprList_item *a = pEList->a;
  122285. ExprList *pNew = 0;
  122286. int flags = pParse->db->flags;
  122287. int longNames = (flags & SQLITE_FullColNames)!=0
  122288. && (flags & SQLITE_ShortColNames)==0;
  122289. for(k=0; k<pEList->nExpr; k++){
  122290. pE = a[k].pExpr;
  122291. elistFlags |= pE->flags;
  122292. pRight = pE->pRight;
  122293. assert( pE->op!=TK_DOT || pRight!=0 );
  122294. if( pE->op!=TK_ASTERISK
  122295. && (pE->op!=TK_DOT || pRight->op!=TK_ASTERISK)
  122296. ){
  122297. /* This particular expression does not need to be expanded.
  122298. */
  122299. pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
  122300. if( pNew ){
  122301. pNew->a[pNew->nExpr-1].zName = a[k].zName;
  122302. pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
  122303. a[k].zName = 0;
  122304. a[k].zSpan = 0;
  122305. }
  122306. a[k].pExpr = 0;
  122307. }else{
  122308. /* This expression is a "*" or a "TABLE.*" and needs to be
  122309. ** expanded. */
  122310. int tableSeen = 0; /* Set to 1 when TABLE matches */
  122311. char *zTName = 0; /* text of name of TABLE */
  122312. if( pE->op==TK_DOT ){
  122313. assert( pE->pLeft!=0 );
  122314. assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
  122315. zTName = pE->pLeft->u.zToken;
  122316. }
  122317. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  122318. Table *pTab = pFrom->pTab;
  122319. Select *pSub = pFrom->pSelect;
  122320. char *zTabName = pFrom->zAlias;
  122321. const char *zSchemaName = 0;
  122322. int iDb;
  122323. if( zTabName==0 ){
  122324. zTabName = pTab->zName;
  122325. }
  122326. if( db->mallocFailed ) break;
  122327. if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
  122328. pSub = 0;
  122329. if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
  122330. continue;
  122331. }
  122332. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  122333. zSchemaName = iDb>=0 ? db->aDb[iDb].zDbSName : "*";
  122334. }
  122335. for(j=0; j<pTab->nCol; j++){
  122336. char *zName = pTab->aCol[j].zName;
  122337. char *zColname; /* The computed column name */
  122338. char *zToFree; /* Malloced string that needs to be freed */
  122339. Token sColname; /* Computed column name as a token */
  122340. assert( zName );
  122341. if( zTName && pSub
  122342. && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0
  122343. ){
  122344. continue;
  122345. }
  122346. /* If a column is marked as 'hidden', omit it from the expanded
  122347. ** result-set list unless the SELECT has the SF_IncludeHidden
  122348. ** bit set.
  122349. */
  122350. if( (p->selFlags & SF_IncludeHidden)==0
  122351. && IsHiddenColumn(&pTab->aCol[j])
  122352. ){
  122353. continue;
  122354. }
  122355. tableSeen = 1;
  122356. if( i>0 && zTName==0 ){
  122357. if( (pFrom->fg.jointype & JT_NATURAL)!=0
  122358. && tableAndColumnIndex(pTabList, i, zName, 0, 0)
  122359. ){
  122360. /* In a NATURAL join, omit the join columns from the
  122361. ** table to the right of the join */
  122362. continue;
  122363. }
  122364. if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
  122365. /* In a join with a USING clause, omit columns in the
  122366. ** using clause from the table on the right. */
  122367. continue;
  122368. }
  122369. }
  122370. pRight = sqlite3Expr(db, TK_ID, zName);
  122371. zColname = zName;
  122372. zToFree = 0;
  122373. if( longNames || pTabList->nSrc>1 ){
  122374. Expr *pLeft;
  122375. pLeft = sqlite3Expr(db, TK_ID, zTabName);
  122376. pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight);
  122377. if( zSchemaName ){
  122378. pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
  122379. pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr);
  122380. }
  122381. if( longNames ){
  122382. zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
  122383. zToFree = zColname;
  122384. }
  122385. }else{
  122386. pExpr = pRight;
  122387. }
  122388. pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
  122389. sqlite3TokenInit(&sColname, zColname);
  122390. sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
  122391. if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){
  122392. struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
  122393. if( pSub ){
  122394. pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);
  122395. testcase( pX->zSpan==0 );
  122396. }else{
  122397. pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s",
  122398. zSchemaName, zTabName, zColname);
  122399. testcase( pX->zSpan==0 );
  122400. }
  122401. pX->bSpanIsTab = 1;
  122402. }
  122403. sqlite3DbFree(db, zToFree);
  122404. }
  122405. }
  122406. if( !tableSeen ){
  122407. if( zTName ){
  122408. sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
  122409. }else{
  122410. sqlite3ErrorMsg(pParse, "no tables specified");
  122411. }
  122412. }
  122413. }
  122414. }
  122415. sqlite3ExprListDelete(db, pEList);
  122416. p->pEList = pNew;
  122417. }
  122418. if( p->pEList ){
  122419. if( p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  122420. sqlite3ErrorMsg(pParse, "too many columns in result set");
  122421. return WRC_Abort;
  122422. }
  122423. if( (elistFlags & (EP_HasFunc|EP_Subquery))!=0 ){
  122424. p->selFlags |= SF_ComplexResult;
  122425. }
  122426. }
  122427. return WRC_Continue;
  122428. }
  122429. /*
  122430. ** No-op routine for the parse-tree walker.
  122431. **
  122432. ** When this routine is the Walker.xExprCallback then expression trees
  122433. ** are walked without any actions being taken at each node. Presumably,
  122434. ** when this routine is used for Walker.xExprCallback then
  122435. ** Walker.xSelectCallback is set to do something useful for every
  122436. ** subquery in the parser tree.
  122437. */
  122438. SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
  122439. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  122440. return WRC_Continue;
  122441. }
  122442. /*
  122443. ** No-op routine for the parse-tree walker for SELECT statements.
  122444. ** subquery in the parser tree.
  122445. */
  122446. SQLITE_PRIVATE int sqlite3SelectWalkNoop(Walker *NotUsed, Select *NotUsed2){
  122447. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  122448. return WRC_Continue;
  122449. }
  122450. #if SQLITE_DEBUG
  122451. /*
  122452. ** Always assert. This xSelectCallback2 implementation proves that the
  122453. ** xSelectCallback2 is never invoked.
  122454. */
  122455. SQLITE_PRIVATE void sqlite3SelectWalkAssert2(Walker *NotUsed, Select *NotUsed2){
  122456. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  122457. assert( 0 );
  122458. }
  122459. #endif
  122460. /*
  122461. ** This routine "expands" a SELECT statement and all of its subqueries.
  122462. ** For additional information on what it means to "expand" a SELECT
  122463. ** statement, see the comment on the selectExpand worker callback above.
  122464. **
  122465. ** Expanding a SELECT statement is the first step in processing a
  122466. ** SELECT statement. The SELECT statement must be expanded before
  122467. ** name resolution is performed.
  122468. **
  122469. ** If anything goes wrong, an error message is written into pParse.
  122470. ** The calling function can detect the problem by looking at pParse->nErr
  122471. ** and/or pParse->db->mallocFailed.
  122472. */
  122473. static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
  122474. Walker w;
  122475. w.xExprCallback = sqlite3ExprWalkNoop;
  122476. w.pParse = pParse;
  122477. if( OK_IF_ALWAYS_TRUE(pParse->hasCompound) ){
  122478. w.xSelectCallback = convertCompoundSelectToSubquery;
  122479. w.xSelectCallback2 = 0;
  122480. sqlite3WalkSelect(&w, pSelect);
  122481. }
  122482. w.xSelectCallback = selectExpander;
  122483. w.xSelectCallback2 = selectPopWith;
  122484. w.eCode = 0;
  122485. sqlite3WalkSelect(&w, pSelect);
  122486. }
  122487. #ifndef SQLITE_OMIT_SUBQUERY
  122488. /*
  122489. ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
  122490. ** interface.
  122491. **
  122492. ** For each FROM-clause subquery, add Column.zType and Column.zColl
  122493. ** information to the Table structure that represents the result set
  122494. ** of that subquery.
  122495. **
  122496. ** The Table structure that represents the result set was constructed
  122497. ** by selectExpander() but the type and collation information was omitted
  122498. ** at that point because identifiers had not yet been resolved. This
  122499. ** routine is called after identifier resolution.
  122500. */
  122501. static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
  122502. Parse *pParse;
  122503. int i;
  122504. SrcList *pTabList;
  122505. struct SrcList_item *pFrom;
  122506. assert( p->selFlags & SF_Resolved );
  122507. if( p->selFlags & SF_HasTypeInfo ) return;
  122508. p->selFlags |= SF_HasTypeInfo;
  122509. pParse = pWalker->pParse;
  122510. pTabList = p->pSrc;
  122511. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  122512. Table *pTab = pFrom->pTab;
  122513. assert( pTab!=0 );
  122514. if( (pTab->tabFlags & TF_Ephemeral)!=0 ){
  122515. /* A sub-query in the FROM clause of a SELECT */
  122516. Select *pSel = pFrom->pSelect;
  122517. if( pSel ){
  122518. while( pSel->pPrior ) pSel = pSel->pPrior;
  122519. sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSel);
  122520. }
  122521. }
  122522. }
  122523. }
  122524. #endif
  122525. /*
  122526. ** This routine adds datatype and collating sequence information to
  122527. ** the Table structures of all FROM-clause subqueries in a
  122528. ** SELECT statement.
  122529. **
  122530. ** Use this routine after name resolution.
  122531. */
  122532. static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
  122533. #ifndef SQLITE_OMIT_SUBQUERY
  122534. Walker w;
  122535. w.xSelectCallback = sqlite3SelectWalkNoop;
  122536. w.xSelectCallback2 = selectAddSubqueryTypeInfo;
  122537. w.xExprCallback = sqlite3ExprWalkNoop;
  122538. w.pParse = pParse;
  122539. sqlite3WalkSelect(&w, pSelect);
  122540. #endif
  122541. }
  122542. /*
  122543. ** This routine sets up a SELECT statement for processing. The
  122544. ** following is accomplished:
  122545. **
  122546. ** * VDBE Cursor numbers are assigned to all FROM-clause terms.
  122547. ** * Ephemeral Table objects are created for all FROM-clause subqueries.
  122548. ** * ON and USING clauses are shifted into WHERE statements
  122549. ** * Wildcards "*" and "TABLE.*" in result sets are expanded.
  122550. ** * Identifiers in expression are matched to tables.
  122551. **
  122552. ** This routine acts recursively on all subqueries within the SELECT.
  122553. */
  122554. SQLITE_PRIVATE void sqlite3SelectPrep(
  122555. Parse *pParse, /* The parser context */
  122556. Select *p, /* The SELECT statement being coded. */
  122557. NameContext *pOuterNC /* Name context for container */
  122558. ){
  122559. assert( p!=0 || pParse->db->mallocFailed );
  122560. if( pParse->db->mallocFailed ) return;
  122561. if( p->selFlags & SF_HasTypeInfo ) return;
  122562. sqlite3SelectExpand(pParse, p);
  122563. if( pParse->nErr || pParse->db->mallocFailed ) return;
  122564. sqlite3ResolveSelectNames(pParse, p, pOuterNC);
  122565. if( pParse->nErr || pParse->db->mallocFailed ) return;
  122566. sqlite3SelectAddTypeInfo(pParse, p);
  122567. }
  122568. /*
  122569. ** Reset the aggregate accumulator.
  122570. **
  122571. ** The aggregate accumulator is a set of memory cells that hold
  122572. ** intermediate results while calculating an aggregate. This
  122573. ** routine generates code that stores NULLs in all of those memory
  122574. ** cells.
  122575. */
  122576. static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
  122577. Vdbe *v = pParse->pVdbe;
  122578. int i;
  122579. struct AggInfo_func *pFunc;
  122580. int nReg = pAggInfo->nFunc + pAggInfo->nColumn;
  122581. if( nReg==0 ) return;
  122582. #ifdef SQLITE_DEBUG
  122583. /* Verify that all AggInfo registers are within the range specified by
  122584. ** AggInfo.mnReg..AggInfo.mxReg */
  122585. assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 );
  122586. for(i=0; i<pAggInfo->nColumn; i++){
  122587. assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg
  122588. && pAggInfo->aCol[i].iMem<=pAggInfo->mxReg );
  122589. }
  122590. for(i=0; i<pAggInfo->nFunc; i++){
  122591. assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg
  122592. && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg );
  122593. }
  122594. #endif
  122595. sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg);
  122596. for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
  122597. if( pFunc->iDistinct>=0 ){
  122598. Expr *pE = pFunc->pExpr;
  122599. assert( !ExprHasProperty(pE, EP_xIsSelect) );
  122600. if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
  122601. sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
  122602. "argument");
  122603. pFunc->iDistinct = -1;
  122604. }else{
  122605. KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pE->x.pList,0,0);
  122606. sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
  122607. (char*)pKeyInfo, P4_KEYINFO);
  122608. }
  122609. }
  122610. }
  122611. }
  122612. /*
  122613. ** Invoke the OP_AggFinalize opcode for every aggregate function
  122614. ** in the AggInfo structure.
  122615. */
  122616. static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
  122617. Vdbe *v = pParse->pVdbe;
  122618. int i;
  122619. struct AggInfo_func *pF;
  122620. for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
  122621. ExprList *pList = pF->pExpr->x.pList;
  122622. assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
  122623. sqlite3VdbeAddOp2(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0);
  122624. sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
  122625. }
  122626. }
  122627. /*
  122628. ** Update the accumulator memory cells for an aggregate based on
  122629. ** the current cursor position.
  122630. **
  122631. ** If regAcc is non-zero and there are no min() or max() aggregates
  122632. ** in pAggInfo, then only populate the pAggInfo->nAccumulator accumulator
  122633. ** registers if register regAcc contains 0. The caller will take care
  122634. ** of setting and clearing regAcc.
  122635. */
  122636. static void updateAccumulator(Parse *pParse, int regAcc, AggInfo *pAggInfo){
  122637. Vdbe *v = pParse->pVdbe;
  122638. int i;
  122639. int regHit = 0;
  122640. int addrHitTest = 0;
  122641. struct AggInfo_func *pF;
  122642. struct AggInfo_col *pC;
  122643. pAggInfo->directMode = 1;
  122644. for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
  122645. int nArg;
  122646. int addrNext = 0;
  122647. int regAgg;
  122648. ExprList *pList = pF->pExpr->x.pList;
  122649. assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
  122650. if( pList ){
  122651. nArg = pList->nExpr;
  122652. regAgg = sqlite3GetTempRange(pParse, nArg);
  122653. sqlite3ExprCodeExprList(pParse, pList, regAgg, 0, SQLITE_ECEL_DUP);
  122654. }else{
  122655. nArg = 0;
  122656. regAgg = 0;
  122657. }
  122658. if( pF->iDistinct>=0 ){
  122659. addrNext = sqlite3VdbeMakeLabel(pParse);
  122660. testcase( nArg==0 ); /* Error condition */
  122661. testcase( nArg>1 ); /* Also an error */
  122662. codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
  122663. }
  122664. if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
  122665. CollSeq *pColl = 0;
  122666. struct ExprList_item *pItem;
  122667. int j;
  122668. assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */
  122669. for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
  122670. pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
  122671. }
  122672. if( !pColl ){
  122673. pColl = pParse->db->pDfltColl;
  122674. }
  122675. if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
  122676. sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
  122677. }
  122678. sqlite3VdbeAddOp3(v, OP_AggStep, 0, regAgg, pF->iMem);
  122679. sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
  122680. sqlite3VdbeChangeP5(v, (u8)nArg);
  122681. sqlite3ReleaseTempRange(pParse, regAgg, nArg);
  122682. if( addrNext ){
  122683. sqlite3VdbeResolveLabel(v, addrNext);
  122684. }
  122685. }
  122686. if( regHit==0 && pAggInfo->nAccumulator ){
  122687. regHit = regAcc;
  122688. }
  122689. if( regHit ){
  122690. addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v);
  122691. }
  122692. for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
  122693. sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
  122694. }
  122695. pAggInfo->directMode = 0;
  122696. if( addrHitTest ){
  122697. sqlite3VdbeJumpHere(v, addrHitTest);
  122698. }
  122699. }
  122700. /*
  122701. ** Add a single OP_Explain instruction to the VDBE to explain a simple
  122702. ** count(*) query ("SELECT count(*) FROM pTab").
  122703. */
  122704. #ifndef SQLITE_OMIT_EXPLAIN
  122705. static void explainSimpleCount(
  122706. Parse *pParse, /* Parse context */
  122707. Table *pTab, /* Table being queried */
  122708. Index *pIdx /* Index used to optimize scan, or NULL */
  122709. ){
  122710. if( pParse->explain==2 ){
  122711. int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx)));
  122712. sqlite3VdbeExplain(pParse, 0, "SCAN TABLE %s%s%s",
  122713. pTab->zName,
  122714. bCover ? " USING COVERING INDEX " : "",
  122715. bCover ? pIdx->zName : ""
  122716. );
  122717. }
  122718. }
  122719. #else
  122720. # define explainSimpleCount(a,b,c)
  122721. #endif
  122722. /*
  122723. ** sqlite3WalkExpr() callback used by havingToWhere().
  122724. **
  122725. ** If the node passed to the callback is a TK_AND node, return
  122726. ** WRC_Continue to tell sqlite3WalkExpr() to iterate through child nodes.
  122727. **
  122728. ** Otherwise, return WRC_Prune. In this case, also check if the
  122729. ** sub-expression matches the criteria for being moved to the WHERE
  122730. ** clause. If so, add it to the WHERE clause and replace the sub-expression
  122731. ** within the HAVING expression with a constant "1".
  122732. */
  122733. static int havingToWhereExprCb(Walker *pWalker, Expr *pExpr){
  122734. if( pExpr->op!=TK_AND ){
  122735. Select *pS = pWalker->u.pSelect;
  122736. if( sqlite3ExprIsConstantOrGroupBy(pWalker->pParse, pExpr, pS->pGroupBy) ){
  122737. sqlite3 *db = pWalker->pParse->db;
  122738. Expr *pNew = sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[1], 0);
  122739. if( pNew ){
  122740. Expr *pWhere = pS->pWhere;
  122741. SWAP(Expr, *pNew, *pExpr);
  122742. pNew = sqlite3ExprAnd(pWalker->pParse, pWhere, pNew);
  122743. pS->pWhere = pNew;
  122744. pWalker->eCode = 1;
  122745. }
  122746. }
  122747. return WRC_Prune;
  122748. }
  122749. return WRC_Continue;
  122750. }
  122751. /*
  122752. ** Transfer eligible terms from the HAVING clause of a query, which is
  122753. ** processed after grouping, to the WHERE clause, which is processed before
  122754. ** grouping. For example, the query:
  122755. **
  122756. ** SELECT * FROM <tables> WHERE a=? GROUP BY b HAVING b=? AND c=?
  122757. **
  122758. ** can be rewritten as:
  122759. **
  122760. ** SELECT * FROM <tables> WHERE a=? AND b=? GROUP BY b HAVING c=?
  122761. **
  122762. ** A term of the HAVING expression is eligible for transfer if it consists
  122763. ** entirely of constants and expressions that are also GROUP BY terms that
  122764. ** use the "BINARY" collation sequence.
  122765. */
  122766. static void havingToWhere(Parse *pParse, Select *p){
  122767. Walker sWalker;
  122768. memset(&sWalker, 0, sizeof(sWalker));
  122769. sWalker.pParse = pParse;
  122770. sWalker.xExprCallback = havingToWhereExprCb;
  122771. sWalker.u.pSelect = p;
  122772. sqlite3WalkExpr(&sWalker, p->pHaving);
  122773. #if SELECTTRACE_ENABLED
  122774. if( sWalker.eCode && (sqlite3SelectTrace & 0x100)!=0 ){
  122775. SELECTTRACE(0x100,pParse,p,("Move HAVING terms into WHERE:\n"));
  122776. sqlite3TreeViewSelect(0, p, 0);
  122777. }
  122778. #endif
  122779. }
  122780. /*
  122781. ** Check to see if the pThis entry of pTabList is a self-join of a prior view.
  122782. ** If it is, then return the SrcList_item for the prior view. If it is not,
  122783. ** then return 0.
  122784. */
  122785. static struct SrcList_item *isSelfJoinView(
  122786. SrcList *pTabList, /* Search for self-joins in this FROM clause */
  122787. struct SrcList_item *pThis /* Search for prior reference to this subquery */
  122788. ){
  122789. struct SrcList_item *pItem;
  122790. for(pItem = pTabList->a; pItem<pThis; pItem++){
  122791. Select *pS1;
  122792. if( pItem->pSelect==0 ) continue;
  122793. if( pItem->fg.viaCoroutine ) continue;
  122794. if( pItem->zName==0 ) continue;
  122795. assert( pItem->pTab!=0 );
  122796. assert( pThis->pTab!=0 );
  122797. if( pItem->pTab->pSchema!=pThis->pTab->pSchema ) continue;
  122798. if( sqlite3_stricmp(pItem->zName, pThis->zName)!=0 ) continue;
  122799. pS1 = pItem->pSelect;
  122800. if( pItem->pTab->pSchema==0 && pThis->pSelect->selId!=pS1->selId ){
  122801. /* The query flattener left two different CTE tables with identical
  122802. ** names in the same FROM clause. */
  122803. continue;
  122804. }
  122805. if( sqlite3ExprCompare(0, pThis->pSelect->pWhere, pS1->pWhere, -1)
  122806. || sqlite3ExprCompare(0, pThis->pSelect->pHaving, pS1->pHaving, -1)
  122807. ){
  122808. /* The view was modified by some other optimization such as
  122809. ** pushDownWhereTerms() */
  122810. continue;
  122811. }
  122812. return pItem;
  122813. }
  122814. return 0;
  122815. }
  122816. #ifdef SQLITE_COUNTOFVIEW_OPTIMIZATION
  122817. /*
  122818. ** Attempt to transform a query of the form
  122819. **
  122820. ** SELECT count(*) FROM (SELECT x FROM t1 UNION ALL SELECT y FROM t2)
  122821. **
  122822. ** Into this:
  122823. **
  122824. ** SELECT (SELECT count(*) FROM t1)+(SELECT count(*) FROM t2)
  122825. **
  122826. ** The transformation only works if all of the following are true:
  122827. **
  122828. ** * The subquery is a UNION ALL of two or more terms
  122829. ** * The subquery does not have a LIMIT clause
  122830. ** * There is no WHERE or GROUP BY or HAVING clauses on the subqueries
  122831. ** * The outer query is a simple count(*) with no WHERE clause or other
  122832. ** extraneous syntax.
  122833. **
  122834. ** Return TRUE if the optimization is undertaken.
  122835. */
  122836. static int countOfViewOptimization(Parse *pParse, Select *p){
  122837. Select *pSub, *pPrior;
  122838. Expr *pExpr;
  122839. Expr *pCount;
  122840. sqlite3 *db;
  122841. if( (p->selFlags & SF_Aggregate)==0 ) return 0; /* This is an aggregate */
  122842. if( p->pEList->nExpr!=1 ) return 0; /* Single result column */
  122843. if( p->pWhere ) return 0;
  122844. if( p->pGroupBy ) return 0;
  122845. pExpr = p->pEList->a[0].pExpr;
  122846. if( pExpr->op!=TK_AGG_FUNCTION ) return 0; /* Result is an aggregate */
  122847. if( sqlite3_stricmp(pExpr->u.zToken,"count") ) return 0; /* Is count() */
  122848. if( pExpr->x.pList!=0 ) return 0; /* Must be count(*) */
  122849. if( p->pSrc->nSrc!=1 ) return 0; /* One table in FROM */
  122850. pSub = p->pSrc->a[0].pSelect;
  122851. if( pSub==0 ) return 0; /* The FROM is a subquery */
  122852. if( pSub->pPrior==0 ) return 0; /* Must be a compound ry */
  122853. do{
  122854. if( pSub->op!=TK_ALL && pSub->pPrior ) return 0; /* Must be UNION ALL */
  122855. if( pSub->pWhere ) return 0; /* No WHERE clause */
  122856. if( pSub->pLimit ) return 0; /* No LIMIT clause */
  122857. if( pSub->selFlags & SF_Aggregate ) return 0; /* Not an aggregate */
  122858. pSub = pSub->pPrior; /* Repeat over compound */
  122859. }while( pSub );
  122860. /* If we reach this point then it is OK to perform the transformation */
  122861. db = pParse->db;
  122862. pCount = pExpr;
  122863. pExpr = 0;
  122864. pSub = p->pSrc->a[0].pSelect;
  122865. p->pSrc->a[0].pSelect = 0;
  122866. sqlite3SrcListDelete(db, p->pSrc);
  122867. p->pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*p->pSrc));
  122868. while( pSub ){
  122869. Expr *pTerm;
  122870. pPrior = pSub->pPrior;
  122871. pSub->pPrior = 0;
  122872. pSub->pNext = 0;
  122873. pSub->selFlags |= SF_Aggregate;
  122874. pSub->selFlags &= ~SF_Compound;
  122875. pSub->nSelectRow = 0;
  122876. sqlite3ExprListDelete(db, pSub->pEList);
  122877. pTerm = pPrior ? sqlite3ExprDup(db, pCount, 0) : pCount;
  122878. pSub->pEList = sqlite3ExprListAppend(pParse, 0, pTerm);
  122879. pTerm = sqlite3PExpr(pParse, TK_SELECT, 0, 0);
  122880. sqlite3PExprAddSelect(pParse, pTerm, pSub);
  122881. if( pExpr==0 ){
  122882. pExpr = pTerm;
  122883. }else{
  122884. pExpr = sqlite3PExpr(pParse, TK_PLUS, pTerm, pExpr);
  122885. }
  122886. pSub = pPrior;
  122887. }
  122888. p->pEList->a[0].pExpr = pExpr;
  122889. p->selFlags &= ~SF_Aggregate;
  122890. #if SELECTTRACE_ENABLED
  122891. if( sqlite3SelectTrace & 0x400 ){
  122892. SELECTTRACE(0x400,pParse,p,("After count-of-view optimization:\n"));
  122893. sqlite3TreeViewSelect(0, p, 0);
  122894. }
  122895. #endif
  122896. return 1;
  122897. }
  122898. #endif /* SQLITE_COUNTOFVIEW_OPTIMIZATION */
  122899. /*
  122900. ** Generate code for the SELECT statement given in the p argument.
  122901. **
  122902. ** The results are returned according to the SelectDest structure.
  122903. ** See comments in sqliteInt.h for further information.
  122904. **
  122905. ** This routine returns the number of errors. If any errors are
  122906. ** encountered, then an appropriate error message is left in
  122907. ** pParse->zErrMsg.
  122908. **
  122909. ** This routine does NOT free the Select structure passed in. The
  122910. ** calling function needs to do that.
  122911. */
  122912. SQLITE_PRIVATE int sqlite3Select(
  122913. Parse *pParse, /* The parser context */
  122914. Select *p, /* The SELECT statement being coded. */
  122915. SelectDest *pDest /* What to do with the query results */
  122916. ){
  122917. int i, j; /* Loop counters */
  122918. WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */
  122919. Vdbe *v; /* The virtual machine under construction */
  122920. int isAgg; /* True for select lists like "count(*)" */
  122921. ExprList *pEList = 0; /* List of columns to extract. */
  122922. SrcList *pTabList; /* List of tables to select from */
  122923. Expr *pWhere; /* The WHERE clause. May be NULL */
  122924. ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
  122925. Expr *pHaving; /* The HAVING clause. May be NULL */
  122926. int rc = 1; /* Value to return from this function */
  122927. DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
  122928. SortCtx sSort; /* Info on how to code the ORDER BY clause */
  122929. AggInfo sAggInfo; /* Information used by aggregate queries */
  122930. int iEnd; /* Address of the end of the query */
  122931. sqlite3 *db; /* The database connection */
  122932. ExprList *pMinMaxOrderBy = 0; /* Added ORDER BY for min/max queries */
  122933. u8 minMaxFlag; /* Flag for min/max queries */
  122934. db = pParse->db;
  122935. v = sqlite3GetVdbe(pParse);
  122936. if( p==0 || db->mallocFailed || pParse->nErr ){
  122937. return 1;
  122938. }
  122939. if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
  122940. memset(&sAggInfo, 0, sizeof(sAggInfo));
  122941. #if SELECTTRACE_ENABLED
  122942. SELECTTRACE(1,pParse,p, ("begin processing:\n", pParse->addrExplain));
  122943. if( sqlite3SelectTrace & 0x100 ){
  122944. sqlite3TreeViewSelect(0, p, 0);
  122945. }
  122946. #endif
  122947. assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo );
  122948. assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo );
  122949. assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue );
  122950. assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue );
  122951. if( IgnorableOrderby(pDest) ){
  122952. assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
  122953. pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard ||
  122954. pDest->eDest==SRT_Queue || pDest->eDest==SRT_DistFifo ||
  122955. pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_Fifo);
  122956. /* If ORDER BY makes no difference in the output then neither does
  122957. ** DISTINCT so it can be removed too. */
  122958. sqlite3ExprListDelete(db, p->pOrderBy);
  122959. p->pOrderBy = 0;
  122960. p->selFlags &= ~SF_Distinct;
  122961. }
  122962. sqlite3SelectPrep(pParse, p, 0);
  122963. if( pParse->nErr || db->mallocFailed ){
  122964. goto select_end;
  122965. }
  122966. assert( p->pEList!=0 );
  122967. #if SELECTTRACE_ENABLED
  122968. if( sqlite3SelectTrace & 0x104 ){
  122969. SELECTTRACE(0x104,pParse,p, ("after name resolution:\n"));
  122970. sqlite3TreeViewSelect(0, p, 0);
  122971. }
  122972. #endif
  122973. if( pDest->eDest==SRT_Output ){
  122974. generateColumnNames(pParse, p);
  122975. }
  122976. #ifndef SQLITE_OMIT_WINDOWFUNC
  122977. if( sqlite3WindowRewrite(pParse, p) ){
  122978. goto select_end;
  122979. }
  122980. #if SELECTTRACE_ENABLED
  122981. if( sqlite3SelectTrace & 0x108 ){
  122982. SELECTTRACE(0x104,pParse,p, ("after window rewrite:\n"));
  122983. sqlite3TreeViewSelect(0, p, 0);
  122984. }
  122985. #endif
  122986. #endif /* SQLITE_OMIT_WINDOWFUNC */
  122987. pTabList = p->pSrc;
  122988. isAgg = (p->selFlags & SF_Aggregate)!=0;
  122989. memset(&sSort, 0, sizeof(sSort));
  122990. sSort.pOrderBy = p->pOrderBy;
  122991. /* Try to various optimizations (flattening subqueries, and strength
  122992. ** reduction of join operators) in the FROM clause up into the main query
  122993. */
  122994. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  122995. for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
  122996. struct SrcList_item *pItem = &pTabList->a[i];
  122997. Select *pSub = pItem->pSelect;
  122998. Table *pTab = pItem->pTab;
  122999. /* Convert LEFT JOIN into JOIN if there are terms of the right table
  123000. ** of the LEFT JOIN used in the WHERE clause.
  123001. */
  123002. if( (pItem->fg.jointype & JT_LEFT)!=0
  123003. && sqlite3ExprImpliesNonNullRow(p->pWhere, pItem->iCursor)
  123004. && OptimizationEnabled(db, SQLITE_SimplifyJoin)
  123005. ){
  123006. SELECTTRACE(0x100,pParse,p,
  123007. ("LEFT-JOIN simplifies to JOIN on term %d\n",i));
  123008. pItem->fg.jointype &= ~(JT_LEFT|JT_OUTER);
  123009. unsetJoinExpr(p->pWhere, pItem->iCursor);
  123010. }
  123011. /* No futher action if this term of the FROM clause is no a subquery */
  123012. if( pSub==0 ) continue;
  123013. /* Catch mismatch in the declared columns of a view and the number of
  123014. ** columns in the SELECT on the RHS */
  123015. if( pTab->nCol!=pSub->pEList->nExpr ){
  123016. sqlite3ErrorMsg(pParse, "expected %d columns for '%s' but got %d",
  123017. pTab->nCol, pTab->zName, pSub->pEList->nExpr);
  123018. goto select_end;
  123019. }
  123020. /* Do not try to flatten an aggregate subquery.
  123021. **
  123022. ** Flattening an aggregate subquery is only possible if the outer query
  123023. ** is not a join. But if the outer query is not a join, then the subquery
  123024. ** will be implemented as a co-routine and there is no advantage to
  123025. ** flattening in that case.
  123026. */
  123027. if( (pSub->selFlags & SF_Aggregate)!=0 ) continue;
  123028. assert( pSub->pGroupBy==0 );
  123029. /* If the outer query contains a "complex" result set (that is,
  123030. ** if the result set of the outer query uses functions or subqueries)
  123031. ** and if the subquery contains an ORDER BY clause and if
  123032. ** it will be implemented as a co-routine, then do not flatten. This
  123033. ** restriction allows SQL constructs like this:
  123034. **
  123035. ** SELECT expensive_function(x)
  123036. ** FROM (SELECT x FROM tab ORDER BY y LIMIT 10);
  123037. **
  123038. ** The expensive_function() is only computed on the 10 rows that
  123039. ** are output, rather than every row of the table.
  123040. **
  123041. ** The requirement that the outer query have a complex result set
  123042. ** means that flattening does occur on simpler SQL constraints without
  123043. ** the expensive_function() like:
  123044. **
  123045. ** SELECT x FROM (SELECT x FROM tab ORDER BY y LIMIT 10);
  123046. */
  123047. if( pSub->pOrderBy!=0
  123048. && i==0
  123049. && (p->selFlags & SF_ComplexResult)!=0
  123050. && (pTabList->nSrc==1
  123051. || (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0)
  123052. ){
  123053. continue;
  123054. }
  123055. if( flattenSubquery(pParse, p, i, isAgg) ){
  123056. if( pParse->nErr ) goto select_end;
  123057. /* This subquery can be absorbed into its parent. */
  123058. i = -1;
  123059. }
  123060. pTabList = p->pSrc;
  123061. if( db->mallocFailed ) goto select_end;
  123062. if( !IgnorableOrderby(pDest) ){
  123063. sSort.pOrderBy = p->pOrderBy;
  123064. }
  123065. }
  123066. #endif
  123067. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  123068. /* Handle compound SELECT statements using the separate multiSelect()
  123069. ** procedure.
  123070. */
  123071. if( p->pPrior ){
  123072. rc = multiSelect(pParse, p, pDest);
  123073. #if SELECTTRACE_ENABLED
  123074. SELECTTRACE(0x1,pParse,p,("end compound-select processing\n"));
  123075. if( (sqlite3SelectTrace & 0x2000)!=0 && ExplainQueryPlanParent(pParse)==0 ){
  123076. sqlite3TreeViewSelect(0, p, 0);
  123077. }
  123078. #endif
  123079. if( p->pNext==0 ) ExplainQueryPlanPop(pParse);
  123080. return rc;
  123081. }
  123082. #endif
  123083. /* Do the WHERE-clause constant propagation optimization if this is
  123084. ** a join. No need to speed time on this operation for non-join queries
  123085. ** as the equivalent optimization will be handled by query planner in
  123086. ** sqlite3WhereBegin().
  123087. */
  123088. if( pTabList->nSrc>1
  123089. && OptimizationEnabled(db, SQLITE_PropagateConst)
  123090. && propagateConstants(pParse, p)
  123091. ){
  123092. #if SELECTTRACE_ENABLED
  123093. if( sqlite3SelectTrace & 0x100 ){
  123094. SELECTTRACE(0x100,pParse,p,("After constant propagation:\n"));
  123095. sqlite3TreeViewSelect(0, p, 0);
  123096. }
  123097. #endif
  123098. }else{
  123099. SELECTTRACE(0x100,pParse,p,("Constant propagation not helpful\n"));
  123100. }
  123101. #ifdef SQLITE_COUNTOFVIEW_OPTIMIZATION
  123102. if( OptimizationEnabled(db, SQLITE_QueryFlattener|SQLITE_CountOfView)
  123103. && countOfViewOptimization(pParse, p)
  123104. ){
  123105. if( db->mallocFailed ) goto select_end;
  123106. pEList = p->pEList;
  123107. pTabList = p->pSrc;
  123108. }
  123109. #endif
  123110. /* For each term in the FROM clause, do two things:
  123111. ** (1) Authorized unreferenced tables
  123112. ** (2) Generate code for all sub-queries
  123113. */
  123114. for(i=0; i<pTabList->nSrc; i++){
  123115. struct SrcList_item *pItem = &pTabList->a[i];
  123116. SelectDest dest;
  123117. Select *pSub;
  123118. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  123119. const char *zSavedAuthContext;
  123120. #endif
  123121. /* Issue SQLITE_READ authorizations with a fake column name for any
  123122. ** tables that are referenced but from which no values are extracted.
  123123. ** Examples of where these kinds of null SQLITE_READ authorizations
  123124. ** would occur:
  123125. **
  123126. ** SELECT count(*) FROM t1; -- SQLITE_READ t1.""
  123127. ** SELECT t1.* FROM t1, t2; -- SQLITE_READ t2.""
  123128. **
  123129. ** The fake column name is an empty string. It is possible for a table to
  123130. ** have a column named by the empty string, in which case there is no way to
  123131. ** distinguish between an unreferenced table and an actual reference to the
  123132. ** "" column. The original design was for the fake column name to be a NULL,
  123133. ** which would be unambiguous. But legacy authorization callbacks might
  123134. ** assume the column name is non-NULL and segfault. The use of an empty
  123135. ** string for the fake column name seems safer.
  123136. */
  123137. if( pItem->colUsed==0 ){
  123138. sqlite3AuthCheck(pParse, SQLITE_READ, pItem->zName, "", pItem->zDatabase);
  123139. }
  123140. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  123141. /* Generate code for all sub-queries in the FROM clause
  123142. */
  123143. pSub = pItem->pSelect;
  123144. if( pSub==0 ) continue;
  123145. /* The code for a subquery should only be generated once, though it is
  123146. ** technically harmless for it to be generated multiple times. The
  123147. ** following assert() will detect if something changes to cause
  123148. ** the same subquery to be coded multiple times, as a signal to the
  123149. ** developers to try to optimize the situation. */
  123150. assert( pItem->addrFillSub==0 );
  123151. /* Increment Parse.nHeight by the height of the largest expression
  123152. ** tree referred to by this, the parent select. The child select
  123153. ** may contain expression trees of at most
  123154. ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
  123155. ** more conservative than necessary, but much easier than enforcing
  123156. ** an exact limit.
  123157. */
  123158. pParse->nHeight += sqlite3SelectExprHeight(p);
  123159. /* Make copies of constant WHERE-clause terms in the outer query down
  123160. ** inside the subquery. This can help the subquery to run more efficiently.
  123161. */
  123162. if( OptimizationEnabled(db, SQLITE_PushDown)
  123163. && pushDownWhereTerms(pParse, pSub, p->pWhere, pItem->iCursor,
  123164. (pItem->fg.jointype & JT_OUTER)!=0)
  123165. ){
  123166. #if SELECTTRACE_ENABLED
  123167. if( sqlite3SelectTrace & 0x100 ){
  123168. SELECTTRACE(0x100,pParse,p,
  123169. ("After WHERE-clause push-down into subquery %d:\n", pSub->selId));
  123170. sqlite3TreeViewSelect(0, p, 0);
  123171. }
  123172. #endif
  123173. }else{
  123174. SELECTTRACE(0x100,pParse,p,("Push-down not possible\n"));
  123175. }
  123176. zSavedAuthContext = pParse->zAuthContext;
  123177. pParse->zAuthContext = pItem->zName;
  123178. /* Generate code to implement the subquery
  123179. **
  123180. ** The subquery is implemented as a co-routine if the subquery is
  123181. ** guaranteed to be the outer loop (so that it does not need to be
  123182. ** computed more than once)
  123183. **
  123184. ** TODO: Are there other reasons beside (1) to use a co-routine
  123185. ** implementation?
  123186. */
  123187. if( i==0
  123188. && (pTabList->nSrc==1
  123189. || (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0) /* (1) */
  123190. ){
  123191. /* Implement a co-routine that will return a single row of the result
  123192. ** set on each invocation.
  123193. */
  123194. int addrTop = sqlite3VdbeCurrentAddr(v)+1;
  123195. pItem->regReturn = ++pParse->nMem;
  123196. sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop);
  123197. VdbeComment((v, "%s", pItem->pTab->zName));
  123198. pItem->addrFillSub = addrTop;
  123199. sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
  123200. ExplainQueryPlan((pParse, 1, "CO-ROUTINE %u", pSub->selId));
  123201. sqlite3Select(pParse, pSub, &dest);
  123202. pItem->pTab->nRowLogEst = pSub->nSelectRow;
  123203. pItem->fg.viaCoroutine = 1;
  123204. pItem->regResult = dest.iSdst;
  123205. sqlite3VdbeEndCoroutine(v, pItem->regReturn);
  123206. sqlite3VdbeJumpHere(v, addrTop-1);
  123207. sqlite3ClearTempRegCache(pParse);
  123208. }else{
  123209. /* Generate a subroutine that will fill an ephemeral table with
  123210. ** the content of this subquery. pItem->addrFillSub will point
  123211. ** to the address of the generated subroutine. pItem->regReturn
  123212. ** is a register allocated to hold the subroutine return address
  123213. */
  123214. int topAddr;
  123215. int onceAddr = 0;
  123216. int retAddr;
  123217. struct SrcList_item *pPrior;
  123218. assert( pItem->addrFillSub==0 );
  123219. pItem->regReturn = ++pParse->nMem;
  123220. topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
  123221. pItem->addrFillSub = topAddr+1;
  123222. if( pItem->fg.isCorrelated==0 ){
  123223. /* If the subquery is not correlated and if we are not inside of
  123224. ** a trigger, then we only need to compute the value of the subquery
  123225. ** once. */
  123226. onceAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  123227. VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName));
  123228. }else{
  123229. VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName));
  123230. }
  123231. pPrior = isSelfJoinView(pTabList, pItem);
  123232. if( pPrior ){
  123233. sqlite3VdbeAddOp2(v, OP_OpenDup, pItem->iCursor, pPrior->iCursor);
  123234. assert( pPrior->pSelect!=0 );
  123235. pSub->nSelectRow = pPrior->pSelect->nSelectRow;
  123236. }else{
  123237. sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
  123238. ExplainQueryPlan((pParse, 1, "MATERIALIZE %u", pSub->selId));
  123239. sqlite3Select(pParse, pSub, &dest);
  123240. }
  123241. pItem->pTab->nRowLogEst = pSub->nSelectRow;
  123242. if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
  123243. retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
  123244. VdbeComment((v, "end %s", pItem->pTab->zName));
  123245. sqlite3VdbeChangeP1(v, topAddr, retAddr);
  123246. sqlite3ClearTempRegCache(pParse);
  123247. }
  123248. if( db->mallocFailed ) goto select_end;
  123249. pParse->nHeight -= sqlite3SelectExprHeight(p);
  123250. pParse->zAuthContext = zSavedAuthContext;
  123251. #endif
  123252. }
  123253. /* Various elements of the SELECT copied into local variables for
  123254. ** convenience */
  123255. pEList = p->pEList;
  123256. pWhere = p->pWhere;
  123257. pGroupBy = p->pGroupBy;
  123258. pHaving = p->pHaving;
  123259. sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
  123260. #if SELECTTRACE_ENABLED
  123261. if( sqlite3SelectTrace & 0x400 ){
  123262. SELECTTRACE(0x400,pParse,p,("After all FROM-clause analysis:\n"));
  123263. sqlite3TreeViewSelect(0, p, 0);
  123264. }
  123265. #endif
  123266. /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
  123267. ** if the select-list is the same as the ORDER BY list, then this query
  123268. ** can be rewritten as a GROUP BY. In other words, this:
  123269. **
  123270. ** SELECT DISTINCT xyz FROM ... ORDER BY xyz
  123271. **
  123272. ** is transformed to:
  123273. **
  123274. ** SELECT xyz FROM ... GROUP BY xyz ORDER BY xyz
  123275. **
  123276. ** The second form is preferred as a single index (or temp-table) may be
  123277. ** used for both the ORDER BY and DISTINCT processing. As originally
  123278. ** written the query must use a temp-table for at least one of the ORDER
  123279. ** BY and DISTINCT, and an index or separate temp-table for the other.
  123280. */
  123281. if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
  123282. && sqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0
  123283. ){
  123284. p->selFlags &= ~SF_Distinct;
  123285. pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0);
  123286. /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
  123287. ** the sDistinct.isTnct is still set. Hence, isTnct represents the
  123288. ** original setting of the SF_Distinct flag, not the current setting */
  123289. assert( sDistinct.isTnct );
  123290. #if SELECTTRACE_ENABLED
  123291. if( sqlite3SelectTrace & 0x400 ){
  123292. SELECTTRACE(0x400,pParse,p,("Transform DISTINCT into GROUP BY:\n"));
  123293. sqlite3TreeViewSelect(0, p, 0);
  123294. }
  123295. #endif
  123296. }
  123297. /* If there is an ORDER BY clause, then create an ephemeral index to
  123298. ** do the sorting. But this sorting ephemeral index might end up
  123299. ** being unused if the data can be extracted in pre-sorted order.
  123300. ** If that is the case, then the OP_OpenEphemeral instruction will be
  123301. ** changed to an OP_Noop once we figure out that the sorting index is
  123302. ** not needed. The sSort.addrSortIndex variable is used to facilitate
  123303. ** that change.
  123304. */
  123305. if( sSort.pOrderBy ){
  123306. KeyInfo *pKeyInfo;
  123307. pKeyInfo = sqlite3KeyInfoFromExprList(
  123308. pParse, sSort.pOrderBy, 0, pEList->nExpr);
  123309. sSort.iECursor = pParse->nTab++;
  123310. sSort.addrSortIndex =
  123311. sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
  123312. sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0,
  123313. (char*)pKeyInfo, P4_KEYINFO
  123314. );
  123315. }else{
  123316. sSort.addrSortIndex = -1;
  123317. }
  123318. /* If the output is destined for a temporary table, open that table.
  123319. */
  123320. if( pDest->eDest==SRT_EphemTab ){
  123321. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
  123322. }
  123323. /* Set the limiter.
  123324. */
  123325. iEnd = sqlite3VdbeMakeLabel(pParse);
  123326. if( (p->selFlags & SF_FixedLimit)==0 ){
  123327. p->nSelectRow = 320; /* 4 billion rows */
  123328. }
  123329. computeLimitRegisters(pParse, p, iEnd);
  123330. if( p->iLimit==0 && sSort.addrSortIndex>=0 ){
  123331. sqlite3VdbeChangeOpcode(v, sSort.addrSortIndex, OP_SorterOpen);
  123332. sSort.sortFlags |= SORTFLAG_UseSorter;
  123333. }
  123334. /* Open an ephemeral index to use for the distinct set.
  123335. */
  123336. if( p->selFlags & SF_Distinct ){
  123337. sDistinct.tabTnct = pParse->nTab++;
  123338. sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
  123339. sDistinct.tabTnct, 0, 0,
  123340. (char*)sqlite3KeyInfoFromExprList(pParse, p->pEList,0,0),
  123341. P4_KEYINFO);
  123342. sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
  123343. sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
  123344. }else{
  123345. sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
  123346. }
  123347. if( !isAgg && pGroupBy==0 ){
  123348. /* No aggregate functions and no GROUP BY clause */
  123349. u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0)
  123350. | (p->selFlags & SF_FixedLimit);
  123351. #ifndef SQLITE_OMIT_WINDOWFUNC
  123352. Window *pWin = p->pWin; /* Master window object (or NULL) */
  123353. if( pWin ){
  123354. sqlite3WindowCodeInit(pParse, pWin);
  123355. }
  123356. #endif
  123357. assert( WHERE_USE_LIMIT==SF_FixedLimit );
  123358. /* Begin the database scan. */
  123359. SELECTTRACE(1,pParse,p,("WhereBegin\n"));
  123360. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy,
  123361. p->pEList, wctrlFlags, p->nSelectRow);
  123362. if( pWInfo==0 ) goto select_end;
  123363. if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
  123364. p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
  123365. }
  123366. if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
  123367. sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
  123368. }
  123369. if( sSort.pOrderBy ){
  123370. sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo);
  123371. sSort.labelOBLopt = sqlite3WhereOrderByLimitOptLabel(pWInfo);
  123372. if( sSort.nOBSat==sSort.pOrderBy->nExpr ){
  123373. sSort.pOrderBy = 0;
  123374. }
  123375. }
  123376. /* If sorting index that was created by a prior OP_OpenEphemeral
  123377. ** instruction ended up not being needed, then change the OP_OpenEphemeral
  123378. ** into an OP_Noop.
  123379. */
  123380. if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){
  123381. sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
  123382. }
  123383. assert( p->pEList==pEList );
  123384. #ifndef SQLITE_OMIT_WINDOWFUNC
  123385. if( pWin ){
  123386. int addrGosub = sqlite3VdbeMakeLabel(pParse);
  123387. int iCont = sqlite3VdbeMakeLabel(pParse);
  123388. int iBreak = sqlite3VdbeMakeLabel(pParse);
  123389. int regGosub = ++pParse->nMem;
  123390. sqlite3WindowCodeStep(pParse, p, pWInfo, regGosub, addrGosub);
  123391. sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
  123392. sqlite3VdbeResolveLabel(v, addrGosub);
  123393. VdbeNoopComment((v, "inner-loop subroutine"));
  123394. sSort.labelOBLopt = 0;
  123395. selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest, iCont, iBreak);
  123396. sqlite3VdbeResolveLabel(v, iCont);
  123397. sqlite3VdbeAddOp1(v, OP_Return, regGosub);
  123398. VdbeComment((v, "end inner-loop subroutine"));
  123399. sqlite3VdbeResolveLabel(v, iBreak);
  123400. }else
  123401. #endif /* SQLITE_OMIT_WINDOWFUNC */
  123402. {
  123403. /* Use the standard inner loop. */
  123404. selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest,
  123405. sqlite3WhereContinueLabel(pWInfo),
  123406. sqlite3WhereBreakLabel(pWInfo));
  123407. /* End the database scan loop.
  123408. */
  123409. sqlite3WhereEnd(pWInfo);
  123410. }
  123411. }else{
  123412. /* This case when there exist aggregate functions or a GROUP BY clause
  123413. ** or both */
  123414. NameContext sNC; /* Name context for processing aggregate information */
  123415. int iAMem; /* First Mem address for storing current GROUP BY */
  123416. int iBMem; /* First Mem address for previous GROUP BY */
  123417. int iUseFlag; /* Mem address holding flag indicating that at least
  123418. ** one row of the input to the aggregator has been
  123419. ** processed */
  123420. int iAbortFlag; /* Mem address which causes query abort if positive */
  123421. int groupBySort; /* Rows come from source in GROUP BY order */
  123422. int addrEnd; /* End of processing for this SELECT */
  123423. int sortPTab = 0; /* Pseudotable used to decode sorting results */
  123424. int sortOut = 0; /* Output register from the sorter */
  123425. int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */
  123426. /* Remove any and all aliases between the result set and the
  123427. ** GROUP BY clause.
  123428. */
  123429. if( pGroupBy ){
  123430. int k; /* Loop counter */
  123431. struct ExprList_item *pItem; /* For looping over expression in a list */
  123432. for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
  123433. pItem->u.x.iAlias = 0;
  123434. }
  123435. for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
  123436. pItem->u.x.iAlias = 0;
  123437. }
  123438. assert( 66==sqlite3LogEst(100) );
  123439. if( p->nSelectRow>66 ) p->nSelectRow = 66;
  123440. }else{
  123441. assert( 0==sqlite3LogEst(1) );
  123442. p->nSelectRow = 0;
  123443. }
  123444. /* If there is both a GROUP BY and an ORDER BY clause and they are
  123445. ** identical, then it may be possible to disable the ORDER BY clause
  123446. ** on the grounds that the GROUP BY will cause elements to come out
  123447. ** in the correct order. It also may not - the GROUP BY might use a
  123448. ** database index that causes rows to be grouped together as required
  123449. ** but not actually sorted. Either way, record the fact that the
  123450. ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp
  123451. ** variable. */
  123452. if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){
  123453. orderByGrp = 1;
  123454. }
  123455. /* Create a label to jump to when we want to abort the query */
  123456. addrEnd = sqlite3VdbeMakeLabel(pParse);
  123457. /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
  123458. ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
  123459. ** SELECT statement.
  123460. */
  123461. memset(&sNC, 0, sizeof(sNC));
  123462. sNC.pParse = pParse;
  123463. sNC.pSrcList = pTabList;
  123464. sNC.uNC.pAggInfo = &sAggInfo;
  123465. VVA_ONLY( sNC.ncFlags = NC_UAggInfo; )
  123466. sAggInfo.mnReg = pParse->nMem+1;
  123467. sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0;
  123468. sAggInfo.pGroupBy = pGroupBy;
  123469. sqlite3ExprAnalyzeAggList(&sNC, pEList);
  123470. sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy);
  123471. if( pHaving ){
  123472. if( pGroupBy ){
  123473. assert( pWhere==p->pWhere );
  123474. assert( pHaving==p->pHaving );
  123475. assert( pGroupBy==p->pGroupBy );
  123476. havingToWhere(pParse, p);
  123477. pWhere = p->pWhere;
  123478. }
  123479. sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
  123480. }
  123481. sAggInfo.nAccumulator = sAggInfo.nColumn;
  123482. if( p->pGroupBy==0 && p->pHaving==0 && sAggInfo.nFunc==1 ){
  123483. minMaxFlag = minMaxQuery(db, sAggInfo.aFunc[0].pExpr, &pMinMaxOrderBy);
  123484. }else{
  123485. minMaxFlag = WHERE_ORDERBY_NORMAL;
  123486. }
  123487. for(i=0; i<sAggInfo.nFunc; i++){
  123488. assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
  123489. sNC.ncFlags |= NC_InAggFunc;
  123490. sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
  123491. sNC.ncFlags &= ~NC_InAggFunc;
  123492. }
  123493. sAggInfo.mxReg = pParse->nMem;
  123494. if( db->mallocFailed ) goto select_end;
  123495. #if SELECTTRACE_ENABLED
  123496. if( sqlite3SelectTrace & 0x400 ){
  123497. int ii;
  123498. SELECTTRACE(0x400,pParse,p,("After aggregate analysis:\n"));
  123499. sqlite3TreeViewSelect(0, p, 0);
  123500. for(ii=0; ii<sAggInfo.nColumn; ii++){
  123501. sqlite3DebugPrintf("agg-column[%d] iMem=%d\n",
  123502. ii, sAggInfo.aCol[ii].iMem);
  123503. sqlite3TreeViewExpr(0, sAggInfo.aCol[ii].pExpr, 0);
  123504. }
  123505. for(ii=0; ii<sAggInfo.nFunc; ii++){
  123506. sqlite3DebugPrintf("agg-func[%d]: iMem=%d\n",
  123507. ii, sAggInfo.aFunc[ii].iMem);
  123508. sqlite3TreeViewExpr(0, sAggInfo.aFunc[ii].pExpr, 0);
  123509. }
  123510. }
  123511. #endif
  123512. /* Processing for aggregates with GROUP BY is very different and
  123513. ** much more complex than aggregates without a GROUP BY.
  123514. */
  123515. if( pGroupBy ){
  123516. KeyInfo *pKeyInfo; /* Keying information for the group by clause */
  123517. int addr1; /* A-vs-B comparision jump */
  123518. int addrOutputRow; /* Start of subroutine that outputs a result row */
  123519. int regOutputRow; /* Return address register for output subroutine */
  123520. int addrSetAbort; /* Set the abort flag and return */
  123521. int addrTopOfLoop; /* Top of the input loop */
  123522. int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
  123523. int addrReset; /* Subroutine for resetting the accumulator */
  123524. int regReset; /* Return address register for reset subroutine */
  123525. /* If there is a GROUP BY clause we might need a sorting index to
  123526. ** implement it. Allocate that sorting index now. If it turns out
  123527. ** that we do not need it after all, the OP_SorterOpen instruction
  123528. ** will be converted into a Noop.
  123529. */
  123530. sAggInfo.sortingIdx = pParse->nTab++;
  123531. pKeyInfo = sqlite3KeyInfoFromExprList(pParse,pGroupBy,0,sAggInfo.nColumn);
  123532. addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
  123533. sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
  123534. 0, (char*)pKeyInfo, P4_KEYINFO);
  123535. /* Initialize memory locations used by GROUP BY aggregate processing
  123536. */
  123537. iUseFlag = ++pParse->nMem;
  123538. iAbortFlag = ++pParse->nMem;
  123539. regOutputRow = ++pParse->nMem;
  123540. addrOutputRow = sqlite3VdbeMakeLabel(pParse);
  123541. regReset = ++pParse->nMem;
  123542. addrReset = sqlite3VdbeMakeLabel(pParse);
  123543. iAMem = pParse->nMem + 1;
  123544. pParse->nMem += pGroupBy->nExpr;
  123545. iBMem = pParse->nMem + 1;
  123546. pParse->nMem += pGroupBy->nExpr;
  123547. sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
  123548. VdbeComment((v, "clear abort flag"));
  123549. sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
  123550. /* Begin a loop that will extract all source rows in GROUP BY order.
  123551. ** This might involve two separate loops with an OP_Sort in between, or
  123552. ** it might be a single loop that uses an index to extract information
  123553. ** in the right order to begin with.
  123554. */
  123555. sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
  123556. SELECTTRACE(1,pParse,p,("WhereBegin\n"));
  123557. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0,
  123558. WHERE_GROUPBY | (orderByGrp ? WHERE_SORTBYGROUP : 0), 0
  123559. );
  123560. if( pWInfo==0 ) goto select_end;
  123561. if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){
  123562. /* The optimizer is able to deliver rows in group by order so
  123563. ** we do not have to sort. The OP_OpenEphemeral table will be
  123564. ** cancelled later because we still need to use the pKeyInfo
  123565. */
  123566. groupBySort = 0;
  123567. }else{
  123568. /* Rows are coming out in undetermined order. We have to push
  123569. ** each row into a sorting index, terminate the first loop,
  123570. ** then loop over the sorting index in order to get the output
  123571. ** in sorted order
  123572. */
  123573. int regBase;
  123574. int regRecord;
  123575. int nCol;
  123576. int nGroupBy;
  123577. explainTempTable(pParse,
  123578. (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
  123579. "DISTINCT" : "GROUP BY");
  123580. groupBySort = 1;
  123581. nGroupBy = pGroupBy->nExpr;
  123582. nCol = nGroupBy;
  123583. j = nGroupBy;
  123584. for(i=0; i<sAggInfo.nColumn; i++){
  123585. if( sAggInfo.aCol[i].iSorterColumn>=j ){
  123586. nCol++;
  123587. j++;
  123588. }
  123589. }
  123590. regBase = sqlite3GetTempRange(pParse, nCol);
  123591. sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0, 0);
  123592. j = nGroupBy;
  123593. for(i=0; i<sAggInfo.nColumn; i++){
  123594. struct AggInfo_col *pCol = &sAggInfo.aCol[i];
  123595. if( pCol->iSorterColumn>=j ){
  123596. int r1 = j + regBase;
  123597. sqlite3ExprCodeGetColumnOfTable(v,
  123598. pCol->pTab, pCol->iTable, pCol->iColumn, r1);
  123599. j++;
  123600. }
  123601. }
  123602. regRecord = sqlite3GetTempReg(pParse);
  123603. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
  123604. sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
  123605. sqlite3ReleaseTempReg(pParse, regRecord);
  123606. sqlite3ReleaseTempRange(pParse, regBase, nCol);
  123607. sqlite3WhereEnd(pWInfo);
  123608. sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
  123609. sortOut = sqlite3GetTempReg(pParse);
  123610. sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
  123611. sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
  123612. VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v);
  123613. sAggInfo.useSortingIdx = 1;
  123614. }
  123615. /* If the index or temporary table used by the GROUP BY sort
  123616. ** will naturally deliver rows in the order required by the ORDER BY
  123617. ** clause, cancel the ephemeral table open coded earlier.
  123618. **
  123619. ** This is an optimization - the correct answer should result regardless.
  123620. ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to
  123621. ** disable this optimization for testing purposes. */
  123622. if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder)
  123623. && (groupBySort || sqlite3WhereIsSorted(pWInfo))
  123624. ){
  123625. sSort.pOrderBy = 0;
  123626. sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
  123627. }
  123628. /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
  123629. ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
  123630. ** Then compare the current GROUP BY terms against the GROUP BY terms
  123631. ** from the previous row currently stored in a0, a1, a2...
  123632. */
  123633. addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
  123634. if( groupBySort ){
  123635. sqlite3VdbeAddOp3(v, OP_SorterData, sAggInfo.sortingIdx,
  123636. sortOut, sortPTab);
  123637. }
  123638. for(j=0; j<pGroupBy->nExpr; j++){
  123639. if( groupBySort ){
  123640. sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
  123641. }else{
  123642. sAggInfo.directMode = 1;
  123643. sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
  123644. }
  123645. }
  123646. sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
  123647. (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
  123648. addr1 = sqlite3VdbeCurrentAddr(v);
  123649. sqlite3VdbeAddOp3(v, OP_Jump, addr1+1, 0, addr1+1); VdbeCoverage(v);
  123650. /* Generate code that runs whenever the GROUP BY changes.
  123651. ** Changes in the GROUP BY are detected by the previous code
  123652. ** block. If there were no changes, this block is skipped.
  123653. **
  123654. ** This code copies current group by terms in b0,b1,b2,...
  123655. ** over to a0,a1,a2. It then calls the output subroutine
  123656. ** and resets the aggregate accumulator registers in preparation
  123657. ** for the next GROUP BY batch.
  123658. */
  123659. sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
  123660. sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
  123661. VdbeComment((v, "output one row"));
  123662. sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v);
  123663. VdbeComment((v, "check abort flag"));
  123664. sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
  123665. VdbeComment((v, "reset accumulator"));
  123666. /* Update the aggregate accumulators based on the content of
  123667. ** the current row
  123668. */
  123669. sqlite3VdbeJumpHere(v, addr1);
  123670. updateAccumulator(pParse, iUseFlag, &sAggInfo);
  123671. sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
  123672. VdbeComment((v, "indicate data in accumulator"));
  123673. /* End of the loop
  123674. */
  123675. if( groupBySort ){
  123676. sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
  123677. VdbeCoverage(v);
  123678. }else{
  123679. sqlite3WhereEnd(pWInfo);
  123680. sqlite3VdbeChangeToNoop(v, addrSortingIdx);
  123681. }
  123682. /* Output the final row of result
  123683. */
  123684. sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
  123685. VdbeComment((v, "output final row"));
  123686. /* Jump over the subroutines
  123687. */
  123688. sqlite3VdbeGoto(v, addrEnd);
  123689. /* Generate a subroutine that outputs a single row of the result
  123690. ** set. This subroutine first looks at the iUseFlag. If iUseFlag
  123691. ** is less than or equal to zero, the subroutine is a no-op. If
  123692. ** the processing calls for the query to abort, this subroutine
  123693. ** increments the iAbortFlag memory location before returning in
  123694. ** order to signal the caller to abort.
  123695. */
  123696. addrSetAbort = sqlite3VdbeCurrentAddr(v);
  123697. sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
  123698. VdbeComment((v, "set abort flag"));
  123699. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  123700. sqlite3VdbeResolveLabel(v, addrOutputRow);
  123701. addrOutputRow = sqlite3VdbeCurrentAddr(v);
  123702. sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
  123703. VdbeCoverage(v);
  123704. VdbeComment((v, "Groupby result generator entry point"));
  123705. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  123706. finalizeAggFunctions(pParse, &sAggInfo);
  123707. sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
  123708. selectInnerLoop(pParse, p, -1, &sSort,
  123709. &sDistinct, pDest,
  123710. addrOutputRow+1, addrSetAbort);
  123711. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  123712. VdbeComment((v, "end groupby result generator"));
  123713. /* Generate a subroutine that will reset the group-by accumulator
  123714. */
  123715. sqlite3VdbeResolveLabel(v, addrReset);
  123716. resetAccumulator(pParse, &sAggInfo);
  123717. sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
  123718. VdbeComment((v, "indicate accumulator empty"));
  123719. sqlite3VdbeAddOp1(v, OP_Return, regReset);
  123720. } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */
  123721. else {
  123722. #ifndef SQLITE_OMIT_BTREECOUNT
  123723. Table *pTab;
  123724. if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
  123725. /* If isSimpleCount() returns a pointer to a Table structure, then
  123726. ** the SQL statement is of the form:
  123727. **
  123728. ** SELECT count(*) FROM <tbl>
  123729. **
  123730. ** where the Table structure returned represents table <tbl>.
  123731. **
  123732. ** This statement is so common that it is optimized specially. The
  123733. ** OP_Count instruction is executed either on the intkey table that
  123734. ** contains the data for table <tbl> or on one of its indexes. It
  123735. ** is better to execute the op on an index, as indexes are almost
  123736. ** always spread across less pages than their corresponding tables.
  123737. */
  123738. const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  123739. const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */
  123740. Index *pIdx; /* Iterator variable */
  123741. KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */
  123742. Index *pBest = 0; /* Best index found so far */
  123743. int iRoot = pTab->tnum; /* Root page of scanned b-tree */
  123744. sqlite3CodeVerifySchema(pParse, iDb);
  123745. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  123746. /* Search for the index that has the lowest scan cost.
  123747. **
  123748. ** (2011-04-15) Do not do a full scan of an unordered index.
  123749. **
  123750. ** (2013-10-03) Do not count the entries in a partial index.
  123751. **
  123752. ** In practice the KeyInfo structure will not be used. It is only
  123753. ** passed to keep OP_OpenRead happy.
  123754. */
  123755. if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab);
  123756. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  123757. if( pIdx->bUnordered==0
  123758. && pIdx->szIdxRow<pTab->szTabRow
  123759. && pIdx->pPartIdxWhere==0
  123760. && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
  123761. ){
  123762. pBest = pIdx;
  123763. }
  123764. }
  123765. if( pBest ){
  123766. iRoot = pBest->tnum;
  123767. pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest);
  123768. }
  123769. /* Open a read-only cursor, execute the OP_Count, close the cursor. */
  123770. sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1);
  123771. if( pKeyInfo ){
  123772. sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO);
  123773. }
  123774. sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
  123775. sqlite3VdbeAddOp1(v, OP_Close, iCsr);
  123776. explainSimpleCount(pParse, pTab, pBest);
  123777. }else
  123778. #endif /* SQLITE_OMIT_BTREECOUNT */
  123779. {
  123780. int regAcc = 0; /* "populate accumulators" flag */
  123781. /* If there are accumulator registers but no min() or max() functions,
  123782. ** allocate register regAcc. Register regAcc will contain 0 the first
  123783. ** time the inner loop runs, and 1 thereafter. The code generated
  123784. ** by updateAccumulator() only updates the accumulator registers if
  123785. ** regAcc contains 0. */
  123786. if( sAggInfo.nAccumulator ){
  123787. for(i=0; i<sAggInfo.nFunc; i++){
  123788. if( sAggInfo.aFunc[i].pFunc->funcFlags&SQLITE_FUNC_NEEDCOLL ) break;
  123789. }
  123790. if( i==sAggInfo.nFunc ){
  123791. regAcc = ++pParse->nMem;
  123792. sqlite3VdbeAddOp2(v, OP_Integer, 0, regAcc);
  123793. }
  123794. }
  123795. /* This case runs if the aggregate has no GROUP BY clause. The
  123796. ** processing is much simpler since there is only a single row
  123797. ** of output.
  123798. */
  123799. assert( p->pGroupBy==0 );
  123800. resetAccumulator(pParse, &sAggInfo);
  123801. /* If this query is a candidate for the min/max optimization, then
  123802. ** minMaxFlag will have been previously set to either
  123803. ** WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX and pMinMaxOrderBy will
  123804. ** be an appropriate ORDER BY expression for the optimization.
  123805. */
  123806. assert( minMaxFlag==WHERE_ORDERBY_NORMAL || pMinMaxOrderBy!=0 );
  123807. assert( pMinMaxOrderBy==0 || pMinMaxOrderBy->nExpr==1 );
  123808. SELECTTRACE(1,pParse,p,("WhereBegin\n"));
  123809. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMaxOrderBy,
  123810. 0, minMaxFlag, 0);
  123811. if( pWInfo==0 ){
  123812. goto select_end;
  123813. }
  123814. updateAccumulator(pParse, regAcc, &sAggInfo);
  123815. if( regAcc ) sqlite3VdbeAddOp2(v, OP_Integer, 1, regAcc);
  123816. if( sqlite3WhereIsOrdered(pWInfo)>0 ){
  123817. sqlite3VdbeGoto(v, sqlite3WhereBreakLabel(pWInfo));
  123818. VdbeComment((v, "%s() by index",
  123819. (minMaxFlag==WHERE_ORDERBY_MIN?"min":"max")));
  123820. }
  123821. sqlite3WhereEnd(pWInfo);
  123822. finalizeAggFunctions(pParse, &sAggInfo);
  123823. }
  123824. sSort.pOrderBy = 0;
  123825. sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
  123826. selectInnerLoop(pParse, p, -1, 0, 0,
  123827. pDest, addrEnd, addrEnd);
  123828. }
  123829. sqlite3VdbeResolveLabel(v, addrEnd);
  123830. } /* endif aggregate query */
  123831. if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
  123832. explainTempTable(pParse, "DISTINCT");
  123833. }
  123834. /* If there is an ORDER BY clause, then we need to sort the results
  123835. ** and send them to the callback one by one.
  123836. */
  123837. if( sSort.pOrderBy ){
  123838. explainTempTable(pParse,
  123839. sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY");
  123840. assert( p->pEList==pEList );
  123841. generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest);
  123842. }
  123843. /* Jump here to skip this query
  123844. */
  123845. sqlite3VdbeResolveLabel(v, iEnd);
  123846. /* The SELECT has been coded. If there is an error in the Parse structure,
  123847. ** set the return code to 1. Otherwise 0. */
  123848. rc = (pParse->nErr>0);
  123849. /* Control jumps to here if an error is encountered above, or upon
  123850. ** successful coding of the SELECT.
  123851. */
  123852. select_end:
  123853. sqlite3ExprListDelete(db, pMinMaxOrderBy);
  123854. sqlite3DbFree(db, sAggInfo.aCol);
  123855. sqlite3DbFree(db, sAggInfo.aFunc);
  123856. #if SELECTTRACE_ENABLED
  123857. SELECTTRACE(0x1,pParse,p,("end processing\n"));
  123858. if( (sqlite3SelectTrace & 0x2000)!=0 && ExplainQueryPlanParent(pParse)==0 ){
  123859. sqlite3TreeViewSelect(0, p, 0);
  123860. }
  123861. #endif
  123862. ExplainQueryPlanPop(pParse);
  123863. return rc;
  123864. }
  123865. /************** End of select.c **********************************************/
  123866. /************** Begin file table.c *******************************************/
  123867. /*
  123868. ** 2001 September 15
  123869. **
  123870. ** The author disclaims copyright to this source code. In place of
  123871. ** a legal notice, here is a blessing:
  123872. **
  123873. ** May you do good and not evil.
  123874. ** May you find forgiveness for yourself and forgive others.
  123875. ** May you share freely, never taking more than you give.
  123876. **
  123877. *************************************************************************
  123878. ** This file contains the sqlite3_get_table() and sqlite3_free_table()
  123879. ** interface routines. These are just wrappers around the main
  123880. ** interface routine of sqlite3_exec().
  123881. **
  123882. ** These routines are in a separate files so that they will not be linked
  123883. ** if they are not used.
  123884. */
  123885. /* #include "sqliteInt.h" */
  123886. #ifndef SQLITE_OMIT_GET_TABLE
  123887. /*
  123888. ** This structure is used to pass data from sqlite3_get_table() through
  123889. ** to the callback function is uses to build the result.
  123890. */
  123891. typedef struct TabResult {
  123892. char **azResult; /* Accumulated output */
  123893. char *zErrMsg; /* Error message text, if an error occurs */
  123894. u32 nAlloc; /* Slots allocated for azResult[] */
  123895. u32 nRow; /* Number of rows in the result */
  123896. u32 nColumn; /* Number of columns in the result */
  123897. u32 nData; /* Slots used in azResult[]. (nRow+1)*nColumn */
  123898. int rc; /* Return code from sqlite3_exec() */
  123899. } TabResult;
  123900. /*
  123901. ** This routine is called once for each row in the result table. Its job
  123902. ** is to fill in the TabResult structure appropriately, allocating new
  123903. ** memory as necessary.
  123904. */
  123905. static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
  123906. TabResult *p = (TabResult*)pArg; /* Result accumulator */
  123907. int need; /* Slots needed in p->azResult[] */
  123908. int i; /* Loop counter */
  123909. char *z; /* A single column of result */
  123910. /* Make sure there is enough space in p->azResult to hold everything
  123911. ** we need to remember from this invocation of the callback.
  123912. */
  123913. if( p->nRow==0 && argv!=0 ){
  123914. need = nCol*2;
  123915. }else{
  123916. need = nCol;
  123917. }
  123918. if( p->nData + need > p->nAlloc ){
  123919. char **azNew;
  123920. p->nAlloc = p->nAlloc*2 + need;
  123921. azNew = sqlite3_realloc64( p->azResult, sizeof(char*)*p->nAlloc );
  123922. if( azNew==0 ) goto malloc_failed;
  123923. p->azResult = azNew;
  123924. }
  123925. /* If this is the first row, then generate an extra row containing
  123926. ** the names of all columns.
  123927. */
  123928. if( p->nRow==0 ){
  123929. p->nColumn = nCol;
  123930. for(i=0; i<nCol; i++){
  123931. z = sqlite3_mprintf("%s", colv[i]);
  123932. if( z==0 ) goto malloc_failed;
  123933. p->azResult[p->nData++] = z;
  123934. }
  123935. }else if( (int)p->nColumn!=nCol ){
  123936. sqlite3_free(p->zErrMsg);
  123937. p->zErrMsg = sqlite3_mprintf(
  123938. "sqlite3_get_table() called with two or more incompatible queries"
  123939. );
  123940. p->rc = SQLITE_ERROR;
  123941. return 1;
  123942. }
  123943. /* Copy over the row data
  123944. */
  123945. if( argv!=0 ){
  123946. for(i=0; i<nCol; i++){
  123947. if( argv[i]==0 ){
  123948. z = 0;
  123949. }else{
  123950. int n = sqlite3Strlen30(argv[i])+1;
  123951. z = sqlite3_malloc64( n );
  123952. if( z==0 ) goto malloc_failed;
  123953. memcpy(z, argv[i], n);
  123954. }
  123955. p->azResult[p->nData++] = z;
  123956. }
  123957. p->nRow++;
  123958. }
  123959. return 0;
  123960. malloc_failed:
  123961. p->rc = SQLITE_NOMEM_BKPT;
  123962. return 1;
  123963. }
  123964. /*
  123965. ** Query the database. But instead of invoking a callback for each row,
  123966. ** malloc() for space to hold the result and return the entire results
  123967. ** at the conclusion of the call.
  123968. **
  123969. ** The result that is written to ***pazResult is held in memory obtained
  123970. ** from malloc(). But the caller cannot free this memory directly.
  123971. ** Instead, the entire table should be passed to sqlite3_free_table() when
  123972. ** the calling procedure is finished using it.
  123973. */
  123974. SQLITE_API int sqlite3_get_table(
  123975. sqlite3 *db, /* The database on which the SQL executes */
  123976. const char *zSql, /* The SQL to be executed */
  123977. char ***pazResult, /* Write the result table here */
  123978. int *pnRow, /* Write the number of rows in the result here */
  123979. int *pnColumn, /* Write the number of columns of result here */
  123980. char **pzErrMsg /* Write error messages here */
  123981. ){
  123982. int rc;
  123983. TabResult res;
  123984. #ifdef SQLITE_ENABLE_API_ARMOR
  123985. if( !sqlite3SafetyCheckOk(db) || pazResult==0 ) return SQLITE_MISUSE_BKPT;
  123986. #endif
  123987. *pazResult = 0;
  123988. if( pnColumn ) *pnColumn = 0;
  123989. if( pnRow ) *pnRow = 0;
  123990. if( pzErrMsg ) *pzErrMsg = 0;
  123991. res.zErrMsg = 0;
  123992. res.nRow = 0;
  123993. res.nColumn = 0;
  123994. res.nData = 1;
  123995. res.nAlloc = 20;
  123996. res.rc = SQLITE_OK;
  123997. res.azResult = sqlite3_malloc64(sizeof(char*)*res.nAlloc );
  123998. if( res.azResult==0 ){
  123999. db->errCode = SQLITE_NOMEM;
  124000. return SQLITE_NOMEM_BKPT;
  124001. }
  124002. res.azResult[0] = 0;
  124003. rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
  124004. assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
  124005. res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
  124006. if( (rc&0xff)==SQLITE_ABORT ){
  124007. sqlite3_free_table(&res.azResult[1]);
  124008. if( res.zErrMsg ){
  124009. if( pzErrMsg ){
  124010. sqlite3_free(*pzErrMsg);
  124011. *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
  124012. }
  124013. sqlite3_free(res.zErrMsg);
  124014. }
  124015. db->errCode = res.rc; /* Assume 32-bit assignment is atomic */
  124016. return res.rc;
  124017. }
  124018. sqlite3_free(res.zErrMsg);
  124019. if( rc!=SQLITE_OK ){
  124020. sqlite3_free_table(&res.azResult[1]);
  124021. return rc;
  124022. }
  124023. if( res.nAlloc>res.nData ){
  124024. char **azNew;
  124025. azNew = sqlite3_realloc64( res.azResult, sizeof(char*)*res.nData );
  124026. if( azNew==0 ){
  124027. sqlite3_free_table(&res.azResult[1]);
  124028. db->errCode = SQLITE_NOMEM;
  124029. return SQLITE_NOMEM_BKPT;
  124030. }
  124031. res.azResult = azNew;
  124032. }
  124033. *pazResult = &res.azResult[1];
  124034. if( pnColumn ) *pnColumn = res.nColumn;
  124035. if( pnRow ) *pnRow = res.nRow;
  124036. return rc;
  124037. }
  124038. /*
  124039. ** This routine frees the space the sqlite3_get_table() malloced.
  124040. */
  124041. SQLITE_API void sqlite3_free_table(
  124042. char **azResult /* Result returned from sqlite3_get_table() */
  124043. ){
  124044. if( azResult ){
  124045. int i, n;
  124046. azResult--;
  124047. assert( azResult!=0 );
  124048. n = SQLITE_PTR_TO_INT(azResult[0]);
  124049. for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
  124050. sqlite3_free(azResult);
  124051. }
  124052. }
  124053. #endif /* SQLITE_OMIT_GET_TABLE */
  124054. /************** End of table.c ***********************************************/
  124055. /************** Begin file trigger.c *****************************************/
  124056. /*
  124057. **
  124058. ** The author disclaims copyright to this source code. In place of
  124059. ** a legal notice, here is a blessing:
  124060. **
  124061. ** May you do good and not evil.
  124062. ** May you find forgiveness for yourself and forgive others.
  124063. ** May you share freely, never taking more than you give.
  124064. **
  124065. *************************************************************************
  124066. ** This file contains the implementation for TRIGGERs
  124067. */
  124068. /* #include "sqliteInt.h" */
  124069. #ifndef SQLITE_OMIT_TRIGGER
  124070. /*
  124071. ** Delete a linked list of TriggerStep structures.
  124072. */
  124073. SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
  124074. while( pTriggerStep ){
  124075. TriggerStep * pTmp = pTriggerStep;
  124076. pTriggerStep = pTriggerStep->pNext;
  124077. sqlite3ExprDelete(db, pTmp->pWhere);
  124078. sqlite3ExprListDelete(db, pTmp->pExprList);
  124079. sqlite3SelectDelete(db, pTmp->pSelect);
  124080. sqlite3IdListDelete(db, pTmp->pIdList);
  124081. sqlite3UpsertDelete(db, pTmp->pUpsert);
  124082. sqlite3DbFree(db, pTmp->zSpan);
  124083. sqlite3DbFree(db, pTmp);
  124084. }
  124085. }
  124086. /*
  124087. ** Given table pTab, return a list of all the triggers attached to
  124088. ** the table. The list is connected by Trigger.pNext pointers.
  124089. **
  124090. ** All of the triggers on pTab that are in the same database as pTab
  124091. ** are already attached to pTab->pTrigger. But there might be additional
  124092. ** triggers on pTab in the TEMP schema. This routine prepends all
  124093. ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
  124094. ** and returns the combined list.
  124095. **
  124096. ** To state it another way: This routine returns a list of all triggers
  124097. ** that fire off of pTab. The list will include any TEMP triggers on
  124098. ** pTab as well as the triggers lised in pTab->pTrigger.
  124099. */
  124100. SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
  124101. Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
  124102. Trigger *pList = 0; /* List of triggers to return */
  124103. if( pParse->disableTriggers ){
  124104. return 0;
  124105. }
  124106. if( pTmpSchema!=pTab->pSchema ){
  124107. HashElem *p;
  124108. assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
  124109. for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
  124110. Trigger *pTrig = (Trigger *)sqliteHashData(p);
  124111. if( pTrig->pTabSchema==pTab->pSchema
  124112. && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
  124113. ){
  124114. pTrig->pNext = (pList ? pList : pTab->pTrigger);
  124115. pList = pTrig;
  124116. }
  124117. }
  124118. }
  124119. return (pList ? pList : pTab->pTrigger);
  124120. }
  124121. /*
  124122. ** This is called by the parser when it sees a CREATE TRIGGER statement
  124123. ** up to the point of the BEGIN before the trigger actions. A Trigger
  124124. ** structure is generated based on the information available and stored
  124125. ** in pParse->pNewTrigger. After the trigger actions have been parsed, the
  124126. ** sqlite3FinishTrigger() function is called to complete the trigger
  124127. ** construction process.
  124128. */
  124129. SQLITE_PRIVATE void sqlite3BeginTrigger(
  124130. Parse *pParse, /* The parse context of the CREATE TRIGGER statement */
  124131. Token *pName1, /* The name of the trigger */
  124132. Token *pName2, /* The name of the trigger */
  124133. int tr_tm, /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
  124134. int op, /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
  124135. IdList *pColumns, /* column list if this is an UPDATE OF trigger */
  124136. SrcList *pTableName,/* The name of the table/view the trigger applies to */
  124137. Expr *pWhen, /* WHEN clause */
  124138. int isTemp, /* True if the TEMPORARY keyword is present */
  124139. int noErr /* Suppress errors if the trigger already exists */
  124140. ){
  124141. Trigger *pTrigger = 0; /* The new trigger */
  124142. Table *pTab; /* Table that the trigger fires off of */
  124143. char *zName = 0; /* Name of the trigger */
  124144. sqlite3 *db = pParse->db; /* The database connection */
  124145. int iDb; /* The database to store the trigger in */
  124146. Token *pName; /* The unqualified db name */
  124147. DbFixer sFix; /* State vector for the DB fixer */
  124148. assert( pName1!=0 ); /* pName1->z might be NULL, but not pName1 itself */
  124149. assert( pName2!=0 );
  124150. assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
  124151. assert( op>0 && op<0xff );
  124152. if( isTemp ){
  124153. /* If TEMP was specified, then the trigger name may not be qualified. */
  124154. if( pName2->n>0 ){
  124155. sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
  124156. goto trigger_cleanup;
  124157. }
  124158. iDb = 1;
  124159. pName = pName1;
  124160. }else{
  124161. /* Figure out the db that the trigger will be created in */
  124162. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  124163. if( iDb<0 ){
  124164. goto trigger_cleanup;
  124165. }
  124166. }
  124167. if( !pTableName || db->mallocFailed ){
  124168. goto trigger_cleanup;
  124169. }
  124170. /* A long-standing parser bug is that this syntax was allowed:
  124171. **
  124172. ** CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
  124173. ** ^^^^^^^^
  124174. **
  124175. ** To maintain backwards compatibility, ignore the database
  124176. ** name on pTableName if we are reparsing out of SQLITE_MASTER.
  124177. */
  124178. if( db->init.busy && iDb!=1 ){
  124179. sqlite3DbFree(db, pTableName->a[0].zDatabase);
  124180. pTableName->a[0].zDatabase = 0;
  124181. }
  124182. /* If the trigger name was unqualified, and the table is a temp table,
  124183. ** then set iDb to 1 to create the trigger in the temporary database.
  124184. ** If sqlite3SrcListLookup() returns 0, indicating the table does not
  124185. ** exist, the error is caught by the block below.
  124186. */
  124187. pTab = sqlite3SrcListLookup(pParse, pTableName);
  124188. if( db->init.busy==0 && pName2->n==0 && pTab
  124189. && pTab->pSchema==db->aDb[1].pSchema ){
  124190. iDb = 1;
  124191. }
  124192. /* Ensure the table name matches database name and that the table exists */
  124193. if( db->mallocFailed ) goto trigger_cleanup;
  124194. assert( pTableName->nSrc==1 );
  124195. sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName);
  124196. if( sqlite3FixSrcList(&sFix, pTableName) ){
  124197. goto trigger_cleanup;
  124198. }
  124199. pTab = sqlite3SrcListLookup(pParse, pTableName);
  124200. if( !pTab ){
  124201. /* The table does not exist. */
  124202. if( db->init.iDb==1 ){
  124203. /* Ticket #3810.
  124204. ** Normally, whenever a table is dropped, all associated triggers are
  124205. ** dropped too. But if a TEMP trigger is created on a non-TEMP table
  124206. ** and the table is dropped by a different database connection, the
  124207. ** trigger is not visible to the database connection that does the
  124208. ** drop so the trigger cannot be dropped. This results in an
  124209. ** "orphaned trigger" - a trigger whose associated table is missing.
  124210. */
  124211. db->init.orphanTrigger = 1;
  124212. }
  124213. goto trigger_cleanup;
  124214. }
  124215. if( IsVirtual(pTab) ){
  124216. sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
  124217. goto trigger_cleanup;
  124218. }
  124219. /* Check that the trigger name is not reserved and that no trigger of the
  124220. ** specified name exists */
  124221. zName = sqlite3NameFromToken(db, pName);
  124222. if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  124223. goto trigger_cleanup;
  124224. }
  124225. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  124226. if( !IN_RENAME_OBJECT ){
  124227. if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),zName) ){
  124228. if( !noErr ){
  124229. sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
  124230. }else{
  124231. assert( !db->init.busy );
  124232. sqlite3CodeVerifySchema(pParse, iDb);
  124233. }
  124234. goto trigger_cleanup;
  124235. }
  124236. }
  124237. /* Do not create a trigger on a system table */
  124238. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
  124239. sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
  124240. goto trigger_cleanup;
  124241. }
  124242. /* INSTEAD of triggers are only for views and views only support INSTEAD
  124243. ** of triggers.
  124244. */
  124245. if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
  124246. sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
  124247. (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
  124248. goto trigger_cleanup;
  124249. }
  124250. if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
  124251. sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
  124252. " trigger on table: %S", pTableName, 0);
  124253. goto trigger_cleanup;
  124254. }
  124255. #ifndef SQLITE_OMIT_AUTHORIZATION
  124256. if( !IN_RENAME_OBJECT ){
  124257. int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  124258. int code = SQLITE_CREATE_TRIGGER;
  124259. const char *zDb = db->aDb[iTabDb].zDbSName;
  124260. const char *zDbTrig = isTemp ? db->aDb[1].zDbSName : zDb;
  124261. if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
  124262. if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
  124263. goto trigger_cleanup;
  124264. }
  124265. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
  124266. goto trigger_cleanup;
  124267. }
  124268. }
  124269. #endif
  124270. /* INSTEAD OF triggers can only appear on views and BEFORE triggers
  124271. ** cannot appear on views. So we might as well translate every
  124272. ** INSTEAD OF trigger into a BEFORE trigger. It simplifies code
  124273. ** elsewhere.
  124274. */
  124275. if (tr_tm == TK_INSTEAD){
  124276. tr_tm = TK_BEFORE;
  124277. }
  124278. /* Build the Trigger object */
  124279. pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
  124280. if( pTrigger==0 ) goto trigger_cleanup;
  124281. pTrigger->zName = zName;
  124282. zName = 0;
  124283. pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
  124284. pTrigger->pSchema = db->aDb[iDb].pSchema;
  124285. pTrigger->pTabSchema = pTab->pSchema;
  124286. pTrigger->op = (u8)op;
  124287. pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
  124288. if( IN_RENAME_OBJECT ){
  124289. sqlite3RenameTokenRemap(pParse, pTrigger->table, pTableName->a[0].zName);
  124290. pTrigger->pWhen = pWhen;
  124291. pWhen = 0;
  124292. }else{
  124293. pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
  124294. }
  124295. pTrigger->pColumns = pColumns;
  124296. pColumns = 0;
  124297. assert( pParse->pNewTrigger==0 );
  124298. pParse->pNewTrigger = pTrigger;
  124299. trigger_cleanup:
  124300. sqlite3DbFree(db, zName);
  124301. sqlite3SrcListDelete(db, pTableName);
  124302. sqlite3IdListDelete(db, pColumns);
  124303. sqlite3ExprDelete(db, pWhen);
  124304. if( !pParse->pNewTrigger ){
  124305. sqlite3DeleteTrigger(db, pTrigger);
  124306. }else{
  124307. assert( pParse->pNewTrigger==pTrigger );
  124308. }
  124309. }
  124310. /*
  124311. ** This routine is called after all of the trigger actions have been parsed
  124312. ** in order to complete the process of building the trigger.
  124313. */
  124314. SQLITE_PRIVATE void sqlite3FinishTrigger(
  124315. Parse *pParse, /* Parser context */
  124316. TriggerStep *pStepList, /* The triggered program */
  124317. Token *pAll /* Token that describes the complete CREATE TRIGGER */
  124318. ){
  124319. Trigger *pTrig = pParse->pNewTrigger; /* Trigger being finished */
  124320. char *zName; /* Name of trigger */
  124321. sqlite3 *db = pParse->db; /* The database */
  124322. DbFixer sFix; /* Fixer object */
  124323. int iDb; /* Database containing the trigger */
  124324. Token nameToken; /* Trigger name for error reporting */
  124325. pParse->pNewTrigger = 0;
  124326. if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
  124327. zName = pTrig->zName;
  124328. iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
  124329. pTrig->step_list = pStepList;
  124330. while( pStepList ){
  124331. pStepList->pTrig = pTrig;
  124332. pStepList = pStepList->pNext;
  124333. }
  124334. sqlite3TokenInit(&nameToken, pTrig->zName);
  124335. sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken);
  124336. if( sqlite3FixTriggerStep(&sFix, pTrig->step_list)
  124337. || sqlite3FixExpr(&sFix, pTrig->pWhen)
  124338. ){
  124339. goto triggerfinish_cleanup;
  124340. }
  124341. #ifndef SQLITE_OMIT_ALTERTABLE
  124342. if( IN_RENAME_OBJECT ){
  124343. assert( !db->init.busy );
  124344. pParse->pNewTrigger = pTrig;
  124345. pTrig = 0;
  124346. }else
  124347. #endif
  124348. /* if we are not initializing,
  124349. ** build the sqlite_master entry
  124350. */
  124351. if( !db->init.busy ){
  124352. Vdbe *v;
  124353. char *z;
  124354. /* Make an entry in the sqlite_master table */
  124355. v = sqlite3GetVdbe(pParse);
  124356. if( v==0 ) goto triggerfinish_cleanup;
  124357. sqlite3BeginWriteOperation(pParse, 0, iDb);
  124358. z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
  124359. testcase( z==0 );
  124360. sqlite3NestedParse(pParse,
  124361. "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
  124362. db->aDb[iDb].zDbSName, MASTER_NAME, zName,
  124363. pTrig->table, z);
  124364. sqlite3DbFree(db, z);
  124365. sqlite3ChangeCookie(pParse, iDb);
  124366. sqlite3VdbeAddParseSchemaOp(v, iDb,
  124367. sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
  124368. }
  124369. if( db->init.busy ){
  124370. Trigger *pLink = pTrig;
  124371. Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
  124372. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  124373. pTrig = sqlite3HashInsert(pHash, zName, pTrig);
  124374. if( pTrig ){
  124375. sqlite3OomFault(db);
  124376. }else if( pLink->pSchema==pLink->pTabSchema ){
  124377. Table *pTab;
  124378. pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table);
  124379. assert( pTab!=0 );
  124380. pLink->pNext = pTab->pTrigger;
  124381. pTab->pTrigger = pLink;
  124382. }
  124383. }
  124384. triggerfinish_cleanup:
  124385. sqlite3DeleteTrigger(db, pTrig);
  124386. assert( IN_RENAME_OBJECT || !pParse->pNewTrigger );
  124387. sqlite3DeleteTriggerStep(db, pStepList);
  124388. }
  124389. /*
  124390. ** Duplicate a range of text from an SQL statement, then convert all
  124391. ** whitespace characters into ordinary space characters.
  124392. */
  124393. static char *triggerSpanDup(sqlite3 *db, const char *zStart, const char *zEnd){
  124394. char *z = sqlite3DbSpanDup(db, zStart, zEnd);
  124395. int i;
  124396. if( z ) for(i=0; z[i]; i++) if( sqlite3Isspace(z[i]) ) z[i] = ' ';
  124397. return z;
  124398. }
  124399. /*
  124400. ** Turn a SELECT statement (that the pSelect parameter points to) into
  124401. ** a trigger step. Return a pointer to a TriggerStep structure.
  124402. **
  124403. ** The parser calls this routine when it finds a SELECT statement in
  124404. ** body of a TRIGGER.
  124405. */
  124406. SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(
  124407. sqlite3 *db, /* Database connection */
  124408. Select *pSelect, /* The SELECT statement */
  124409. const char *zStart, /* Start of SQL text */
  124410. const char *zEnd /* End of SQL text */
  124411. ){
  124412. TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
  124413. if( pTriggerStep==0 ) {
  124414. sqlite3SelectDelete(db, pSelect);
  124415. return 0;
  124416. }
  124417. pTriggerStep->op = TK_SELECT;
  124418. pTriggerStep->pSelect = pSelect;
  124419. pTriggerStep->orconf = OE_Default;
  124420. pTriggerStep->zSpan = triggerSpanDup(db, zStart, zEnd);
  124421. return pTriggerStep;
  124422. }
  124423. /*
  124424. ** Allocate space to hold a new trigger step. The allocated space
  124425. ** holds both the TriggerStep object and the TriggerStep.target.z string.
  124426. **
  124427. ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
  124428. */
  124429. static TriggerStep *triggerStepAllocate(
  124430. Parse *pParse, /* Parser context */
  124431. u8 op, /* Trigger opcode */
  124432. Token *pName, /* The target name */
  124433. const char *zStart, /* Start of SQL text */
  124434. const char *zEnd /* End of SQL text */
  124435. ){
  124436. sqlite3 *db = pParse->db;
  124437. TriggerStep *pTriggerStep;
  124438. pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n + 1);
  124439. if( pTriggerStep ){
  124440. char *z = (char*)&pTriggerStep[1];
  124441. memcpy(z, pName->z, pName->n);
  124442. sqlite3Dequote(z);
  124443. pTriggerStep->zTarget = z;
  124444. pTriggerStep->op = op;
  124445. pTriggerStep->zSpan = triggerSpanDup(db, zStart, zEnd);
  124446. if( IN_RENAME_OBJECT ){
  124447. sqlite3RenameTokenMap(pParse, pTriggerStep->zTarget, pName);
  124448. }
  124449. }
  124450. return pTriggerStep;
  124451. }
  124452. /*
  124453. ** Build a trigger step out of an INSERT statement. Return a pointer
  124454. ** to the new trigger step.
  124455. **
  124456. ** The parser calls this routine when it sees an INSERT inside the
  124457. ** body of a trigger.
  124458. */
  124459. SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
  124460. Parse *pParse, /* Parser */
  124461. Token *pTableName, /* Name of the table into which we insert */
  124462. IdList *pColumn, /* List of columns in pTableName to insert into */
  124463. Select *pSelect, /* A SELECT statement that supplies values */
  124464. u8 orconf, /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
  124465. Upsert *pUpsert, /* ON CONFLICT clauses for upsert */
  124466. const char *zStart, /* Start of SQL text */
  124467. const char *zEnd /* End of SQL text */
  124468. ){
  124469. sqlite3 *db = pParse->db;
  124470. TriggerStep *pTriggerStep;
  124471. assert(pSelect != 0 || db->mallocFailed);
  124472. pTriggerStep = triggerStepAllocate(pParse, TK_INSERT, pTableName,zStart,zEnd);
  124473. if( pTriggerStep ){
  124474. if( IN_RENAME_OBJECT ){
  124475. pTriggerStep->pSelect = pSelect;
  124476. pSelect = 0;
  124477. }else{
  124478. pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  124479. }
  124480. pTriggerStep->pIdList = pColumn;
  124481. pTriggerStep->pUpsert = pUpsert;
  124482. pTriggerStep->orconf = orconf;
  124483. }else{
  124484. testcase( pColumn );
  124485. sqlite3IdListDelete(db, pColumn);
  124486. testcase( pUpsert );
  124487. sqlite3UpsertDelete(db, pUpsert);
  124488. }
  124489. sqlite3SelectDelete(db, pSelect);
  124490. return pTriggerStep;
  124491. }
  124492. /*
  124493. ** Construct a trigger step that implements an UPDATE statement and return
  124494. ** a pointer to that trigger step. The parser calls this routine when it
  124495. ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
  124496. */
  124497. SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
  124498. Parse *pParse, /* Parser */
  124499. Token *pTableName, /* Name of the table to be updated */
  124500. ExprList *pEList, /* The SET clause: list of column and new values */
  124501. Expr *pWhere, /* The WHERE clause */
  124502. u8 orconf, /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
  124503. const char *zStart, /* Start of SQL text */
  124504. const char *zEnd /* End of SQL text */
  124505. ){
  124506. sqlite3 *db = pParse->db;
  124507. TriggerStep *pTriggerStep;
  124508. pTriggerStep = triggerStepAllocate(pParse, TK_UPDATE, pTableName,zStart,zEnd);
  124509. if( pTriggerStep ){
  124510. if( IN_RENAME_OBJECT ){
  124511. pTriggerStep->pExprList = pEList;
  124512. pTriggerStep->pWhere = pWhere;
  124513. pEList = 0;
  124514. pWhere = 0;
  124515. }else{
  124516. pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
  124517. pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  124518. }
  124519. pTriggerStep->orconf = orconf;
  124520. }
  124521. sqlite3ExprListDelete(db, pEList);
  124522. sqlite3ExprDelete(db, pWhere);
  124523. return pTriggerStep;
  124524. }
  124525. /*
  124526. ** Construct a trigger step that implements a DELETE statement and return
  124527. ** a pointer to that trigger step. The parser calls this routine when it
  124528. ** sees a DELETE statement inside the body of a CREATE TRIGGER.
  124529. */
  124530. SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
  124531. Parse *pParse, /* Parser */
  124532. Token *pTableName, /* The table from which rows are deleted */
  124533. Expr *pWhere, /* The WHERE clause */
  124534. const char *zStart, /* Start of SQL text */
  124535. const char *zEnd /* End of SQL text */
  124536. ){
  124537. sqlite3 *db = pParse->db;
  124538. TriggerStep *pTriggerStep;
  124539. pTriggerStep = triggerStepAllocate(pParse, TK_DELETE, pTableName,zStart,zEnd);
  124540. if( pTriggerStep ){
  124541. if( IN_RENAME_OBJECT ){
  124542. pTriggerStep->pWhere = pWhere;
  124543. pWhere = 0;
  124544. }else{
  124545. pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  124546. }
  124547. pTriggerStep->orconf = OE_Default;
  124548. }
  124549. sqlite3ExprDelete(db, pWhere);
  124550. return pTriggerStep;
  124551. }
  124552. /*
  124553. ** Recursively delete a Trigger structure
  124554. */
  124555. SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
  124556. if( pTrigger==0 ) return;
  124557. sqlite3DeleteTriggerStep(db, pTrigger->step_list);
  124558. sqlite3DbFree(db, pTrigger->zName);
  124559. sqlite3DbFree(db, pTrigger->table);
  124560. sqlite3ExprDelete(db, pTrigger->pWhen);
  124561. sqlite3IdListDelete(db, pTrigger->pColumns);
  124562. sqlite3DbFree(db, pTrigger);
  124563. }
  124564. /*
  124565. ** This function is called to drop a trigger from the database schema.
  124566. **
  124567. ** This may be called directly from the parser and therefore identifies
  124568. ** the trigger by name. The sqlite3DropTriggerPtr() routine does the
  124569. ** same job as this routine except it takes a pointer to the trigger
  124570. ** instead of the trigger name.
  124571. **/
  124572. SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
  124573. Trigger *pTrigger = 0;
  124574. int i;
  124575. const char *zDb;
  124576. const char *zName;
  124577. sqlite3 *db = pParse->db;
  124578. if( db->mallocFailed ) goto drop_trigger_cleanup;
  124579. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  124580. goto drop_trigger_cleanup;
  124581. }
  124582. assert( pName->nSrc==1 );
  124583. zDb = pName->a[0].zDatabase;
  124584. zName = pName->a[0].zName;
  124585. assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  124586. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  124587. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  124588. if( zDb && sqlite3StrICmp(db->aDb[j].zDbSName, zDb) ) continue;
  124589. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  124590. pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName);
  124591. if( pTrigger ) break;
  124592. }
  124593. if( !pTrigger ){
  124594. if( !noErr ){
  124595. sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
  124596. }else{
  124597. sqlite3CodeVerifyNamedSchema(pParse, zDb);
  124598. }
  124599. pParse->checkSchema = 1;
  124600. goto drop_trigger_cleanup;
  124601. }
  124602. sqlite3DropTriggerPtr(pParse, pTrigger);
  124603. drop_trigger_cleanup:
  124604. sqlite3SrcListDelete(db, pName);
  124605. }
  124606. /*
  124607. ** Return a pointer to the Table structure for the table that a trigger
  124608. ** is set on.
  124609. */
  124610. static Table *tableOfTrigger(Trigger *pTrigger){
  124611. return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table);
  124612. }
  124613. /*
  124614. ** Drop a trigger given a pointer to that trigger.
  124615. */
  124616. SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
  124617. Table *pTable;
  124618. Vdbe *v;
  124619. sqlite3 *db = pParse->db;
  124620. int iDb;
  124621. iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
  124622. assert( iDb>=0 && iDb<db->nDb );
  124623. pTable = tableOfTrigger(pTrigger);
  124624. assert( pTable );
  124625. assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
  124626. #ifndef SQLITE_OMIT_AUTHORIZATION
  124627. {
  124628. int code = SQLITE_DROP_TRIGGER;
  124629. const char *zDb = db->aDb[iDb].zDbSName;
  124630. const char *zTab = SCHEMA_TABLE(iDb);
  124631. if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
  124632. if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
  124633. sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
  124634. return;
  124635. }
  124636. }
  124637. #endif
  124638. /* Generate code to destroy the database record of the trigger.
  124639. */
  124640. assert( pTable!=0 );
  124641. if( (v = sqlite3GetVdbe(pParse))!=0 ){
  124642. sqlite3NestedParse(pParse,
  124643. "DELETE FROM %Q.%s WHERE name=%Q AND type='trigger'",
  124644. db->aDb[iDb].zDbSName, MASTER_NAME, pTrigger->zName
  124645. );
  124646. sqlite3ChangeCookie(pParse, iDb);
  124647. sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
  124648. }
  124649. }
  124650. /*
  124651. ** Remove a trigger from the hash tables of the sqlite* pointer.
  124652. */
  124653. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
  124654. Trigger *pTrigger;
  124655. Hash *pHash;
  124656. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  124657. pHash = &(db->aDb[iDb].pSchema->trigHash);
  124658. pTrigger = sqlite3HashInsert(pHash, zName, 0);
  124659. if( ALWAYS(pTrigger) ){
  124660. if( pTrigger->pSchema==pTrigger->pTabSchema ){
  124661. Table *pTab = tableOfTrigger(pTrigger);
  124662. Trigger **pp;
  124663. for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
  124664. *pp = (*pp)->pNext;
  124665. }
  124666. sqlite3DeleteTrigger(db, pTrigger);
  124667. db->mDbFlags |= DBFLAG_SchemaChange;
  124668. }
  124669. }
  124670. /*
  124671. ** pEList is the SET clause of an UPDATE statement. Each entry
  124672. ** in pEList is of the format <id>=<expr>. If any of the entries
  124673. ** in pEList have an <id> which matches an identifier in pIdList,
  124674. ** then return TRUE. If pIdList==NULL, then it is considered a
  124675. ** wildcard that matches anything. Likewise if pEList==NULL then
  124676. ** it matches anything so always return true. Return false only
  124677. ** if there is no match.
  124678. */
  124679. static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
  124680. int e;
  124681. if( pIdList==0 || NEVER(pEList==0) ) return 1;
  124682. for(e=0; e<pEList->nExpr; e++){
  124683. if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
  124684. }
  124685. return 0;
  124686. }
  124687. /*
  124688. ** Return a list of all triggers on table pTab if there exists at least
  124689. ** one trigger that must be fired when an operation of type 'op' is
  124690. ** performed on the table, and, if that operation is an UPDATE, if at
  124691. ** least one of the columns in pChanges is being modified.
  124692. */
  124693. SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
  124694. Parse *pParse, /* Parse context */
  124695. Table *pTab, /* The table the contains the triggers */
  124696. int op, /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
  124697. ExprList *pChanges, /* Columns that change in an UPDATE statement */
  124698. int *pMask /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  124699. ){
  124700. int mask = 0;
  124701. Trigger *pList = 0;
  124702. Trigger *p;
  124703. if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
  124704. pList = sqlite3TriggerList(pParse, pTab);
  124705. }
  124706. assert( pList==0 || IsVirtual(pTab)==0 );
  124707. for(p=pList; p; p=p->pNext){
  124708. if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
  124709. mask |= p->tr_tm;
  124710. }
  124711. }
  124712. if( pMask ){
  124713. *pMask = mask;
  124714. }
  124715. return (mask ? pList : 0);
  124716. }
  124717. /*
  124718. ** Convert the pStep->zTarget string into a SrcList and return a pointer
  124719. ** to that SrcList.
  124720. **
  124721. ** This routine adds a specific database name, if needed, to the target when
  124722. ** forming the SrcList. This prevents a trigger in one database from
  124723. ** referring to a target in another database. An exception is when the
  124724. ** trigger is in TEMP in which case it can refer to any other database it
  124725. ** wants.
  124726. */
  124727. static SrcList *targetSrcList(
  124728. Parse *pParse, /* The parsing context */
  124729. TriggerStep *pStep /* The trigger containing the target token */
  124730. ){
  124731. sqlite3 *db = pParse->db;
  124732. int iDb; /* Index of the database to use */
  124733. SrcList *pSrc; /* SrcList to be returned */
  124734. pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0);
  124735. if( pSrc ){
  124736. assert( pSrc->nSrc>0 );
  124737. pSrc->a[pSrc->nSrc-1].zName = sqlite3DbStrDup(db, pStep->zTarget);
  124738. iDb = sqlite3SchemaToIndex(db, pStep->pTrig->pSchema);
  124739. if( iDb==0 || iDb>=2 ){
  124740. const char *zDb;
  124741. assert( iDb<db->nDb );
  124742. zDb = db->aDb[iDb].zDbSName;
  124743. pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, zDb);
  124744. }
  124745. }
  124746. return pSrc;
  124747. }
  124748. /*
  124749. ** Generate VDBE code for the statements inside the body of a single
  124750. ** trigger.
  124751. */
  124752. static int codeTriggerProgram(
  124753. Parse *pParse, /* The parser context */
  124754. TriggerStep *pStepList, /* List of statements inside the trigger body */
  124755. int orconf /* Conflict algorithm. (OE_Abort, etc) */
  124756. ){
  124757. TriggerStep *pStep;
  124758. Vdbe *v = pParse->pVdbe;
  124759. sqlite3 *db = pParse->db;
  124760. assert( pParse->pTriggerTab && pParse->pToplevel );
  124761. assert( pStepList );
  124762. assert( v!=0 );
  124763. for(pStep=pStepList; pStep; pStep=pStep->pNext){
  124764. /* Figure out the ON CONFLICT policy that will be used for this step
  124765. ** of the trigger program. If the statement that caused this trigger
  124766. ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
  124767. ** the ON CONFLICT policy that was specified as part of the trigger
  124768. ** step statement. Example:
  124769. **
  124770. ** CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
  124771. ** INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
  124772. ** END;
  124773. **
  124774. ** INSERT INTO t1 ... ; -- insert into t2 uses REPLACE policy
  124775. ** INSERT OR IGNORE INTO t1 ... ; -- insert into t2 uses IGNORE policy
  124776. */
  124777. pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
  124778. assert( pParse->okConstFactor==0 );
  124779. #ifndef SQLITE_OMIT_TRACE
  124780. if( pStep->zSpan ){
  124781. sqlite3VdbeAddOp4(v, OP_Trace, 0x7fffffff, 1, 0,
  124782. sqlite3MPrintf(db, "-- %s", pStep->zSpan),
  124783. P4_DYNAMIC);
  124784. }
  124785. #endif
  124786. switch( pStep->op ){
  124787. case TK_UPDATE: {
  124788. sqlite3Update(pParse,
  124789. targetSrcList(pParse, pStep),
  124790. sqlite3ExprListDup(db, pStep->pExprList, 0),
  124791. sqlite3ExprDup(db, pStep->pWhere, 0),
  124792. pParse->eOrconf, 0, 0, 0
  124793. );
  124794. break;
  124795. }
  124796. case TK_INSERT: {
  124797. sqlite3Insert(pParse,
  124798. targetSrcList(pParse, pStep),
  124799. sqlite3SelectDup(db, pStep->pSelect, 0),
  124800. sqlite3IdListDup(db, pStep->pIdList),
  124801. pParse->eOrconf,
  124802. sqlite3UpsertDup(db, pStep->pUpsert)
  124803. );
  124804. break;
  124805. }
  124806. case TK_DELETE: {
  124807. sqlite3DeleteFrom(pParse,
  124808. targetSrcList(pParse, pStep),
  124809. sqlite3ExprDup(db, pStep->pWhere, 0), 0, 0
  124810. );
  124811. break;
  124812. }
  124813. default: assert( pStep->op==TK_SELECT ); {
  124814. SelectDest sDest;
  124815. Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
  124816. sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
  124817. sqlite3Select(pParse, pSelect, &sDest);
  124818. sqlite3SelectDelete(db, pSelect);
  124819. break;
  124820. }
  124821. }
  124822. if( pStep->op!=TK_SELECT ){
  124823. sqlite3VdbeAddOp0(v, OP_ResetCount);
  124824. }
  124825. }
  124826. return 0;
  124827. }
  124828. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  124829. /*
  124830. ** This function is used to add VdbeComment() annotations to a VDBE
  124831. ** program. It is not used in production code, only for debugging.
  124832. */
  124833. static const char *onErrorText(int onError){
  124834. switch( onError ){
  124835. case OE_Abort: return "abort";
  124836. case OE_Rollback: return "rollback";
  124837. case OE_Fail: return "fail";
  124838. case OE_Replace: return "replace";
  124839. case OE_Ignore: return "ignore";
  124840. case OE_Default: return "default";
  124841. }
  124842. return "n/a";
  124843. }
  124844. #endif
  124845. /*
  124846. ** Parse context structure pFrom has just been used to create a sub-vdbe
  124847. ** (trigger program). If an error has occurred, transfer error information
  124848. ** from pFrom to pTo.
  124849. */
  124850. static void transferParseError(Parse *pTo, Parse *pFrom){
  124851. assert( pFrom->zErrMsg==0 || pFrom->nErr );
  124852. assert( pTo->zErrMsg==0 || pTo->nErr );
  124853. if( pTo->nErr==0 ){
  124854. pTo->zErrMsg = pFrom->zErrMsg;
  124855. pTo->nErr = pFrom->nErr;
  124856. pTo->rc = pFrom->rc;
  124857. }else{
  124858. sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
  124859. }
  124860. }
  124861. /*
  124862. ** Create and populate a new TriggerPrg object with a sub-program
  124863. ** implementing trigger pTrigger with ON CONFLICT policy orconf.
  124864. */
  124865. static TriggerPrg *codeRowTrigger(
  124866. Parse *pParse, /* Current parse context */
  124867. Trigger *pTrigger, /* Trigger to code */
  124868. Table *pTab, /* The table pTrigger is attached to */
  124869. int orconf /* ON CONFLICT policy to code trigger program with */
  124870. ){
  124871. Parse *pTop = sqlite3ParseToplevel(pParse);
  124872. sqlite3 *db = pParse->db; /* Database handle */
  124873. TriggerPrg *pPrg; /* Value to return */
  124874. Expr *pWhen = 0; /* Duplicate of trigger WHEN expression */
  124875. Vdbe *v; /* Temporary VM */
  124876. NameContext sNC; /* Name context for sub-vdbe */
  124877. SubProgram *pProgram = 0; /* Sub-vdbe for trigger program */
  124878. Parse *pSubParse; /* Parse context for sub-vdbe */
  124879. int iEndTrigger = 0; /* Label to jump to if WHEN is false */
  124880. assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
  124881. assert( pTop->pVdbe );
  124882. /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
  124883. ** are freed if an error occurs, link them into the Parse.pTriggerPrg
  124884. ** list of the top-level Parse object sooner rather than later. */
  124885. pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
  124886. if( !pPrg ) return 0;
  124887. pPrg->pNext = pTop->pTriggerPrg;
  124888. pTop->pTriggerPrg = pPrg;
  124889. pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
  124890. if( !pProgram ) return 0;
  124891. sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
  124892. pPrg->pTrigger = pTrigger;
  124893. pPrg->orconf = orconf;
  124894. pPrg->aColmask[0] = 0xffffffff;
  124895. pPrg->aColmask[1] = 0xffffffff;
  124896. /* Allocate and populate a new Parse context to use for coding the
  124897. ** trigger sub-program. */
  124898. pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
  124899. if( !pSubParse ) return 0;
  124900. memset(&sNC, 0, sizeof(sNC));
  124901. sNC.pParse = pSubParse;
  124902. pSubParse->db = db;
  124903. pSubParse->pTriggerTab = pTab;
  124904. pSubParse->pToplevel = pTop;
  124905. pSubParse->zAuthContext = pTrigger->zName;
  124906. pSubParse->eTriggerOp = pTrigger->op;
  124907. pSubParse->nQueryLoop = pParse->nQueryLoop;
  124908. pSubParse->disableVtab = pParse->disableVtab;
  124909. v = sqlite3GetVdbe(pSubParse);
  124910. if( v ){
  124911. VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
  124912. pTrigger->zName, onErrorText(orconf),
  124913. (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
  124914. (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
  124915. (pTrigger->op==TK_INSERT ? "INSERT" : ""),
  124916. (pTrigger->op==TK_DELETE ? "DELETE" : ""),
  124917. pTab->zName
  124918. ));
  124919. #ifndef SQLITE_OMIT_TRACE
  124920. if( pTrigger->zName ){
  124921. sqlite3VdbeChangeP4(v, -1,
  124922. sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
  124923. );
  124924. }
  124925. #endif
  124926. /* If one was specified, code the WHEN clause. If it evaluates to false
  124927. ** (or NULL) the sub-vdbe is immediately halted by jumping to the
  124928. ** OP_Halt inserted at the end of the program. */
  124929. if( pTrigger->pWhen ){
  124930. pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
  124931. if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
  124932. && db->mallocFailed==0
  124933. ){
  124934. iEndTrigger = sqlite3VdbeMakeLabel(pSubParse);
  124935. sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
  124936. }
  124937. sqlite3ExprDelete(db, pWhen);
  124938. }
  124939. /* Code the trigger program into the sub-vdbe. */
  124940. codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
  124941. /* Insert an OP_Halt at the end of the sub-program. */
  124942. if( iEndTrigger ){
  124943. sqlite3VdbeResolveLabel(v, iEndTrigger);
  124944. }
  124945. sqlite3VdbeAddOp0(v, OP_Halt);
  124946. VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
  124947. transferParseError(pParse, pSubParse);
  124948. if( db->mallocFailed==0 && pParse->nErr==0 ){
  124949. pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
  124950. }
  124951. pProgram->nMem = pSubParse->nMem;
  124952. pProgram->nCsr = pSubParse->nTab;
  124953. pProgram->token = (void *)pTrigger;
  124954. pPrg->aColmask[0] = pSubParse->oldmask;
  124955. pPrg->aColmask[1] = pSubParse->newmask;
  124956. sqlite3VdbeDelete(v);
  124957. }
  124958. assert( !pSubParse->pAinc && !pSubParse->pZombieTab );
  124959. assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
  124960. sqlite3ParserReset(pSubParse);
  124961. sqlite3StackFree(db, pSubParse);
  124962. return pPrg;
  124963. }
  124964. /*
  124965. ** Return a pointer to a TriggerPrg object containing the sub-program for
  124966. ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
  124967. ** TriggerPrg object exists, a new object is allocated and populated before
  124968. ** being returned.
  124969. */
  124970. static TriggerPrg *getRowTrigger(
  124971. Parse *pParse, /* Current parse context */
  124972. Trigger *pTrigger, /* Trigger to code */
  124973. Table *pTab, /* The table trigger pTrigger is attached to */
  124974. int orconf /* ON CONFLICT algorithm. */
  124975. ){
  124976. Parse *pRoot = sqlite3ParseToplevel(pParse);
  124977. TriggerPrg *pPrg;
  124978. assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
  124979. /* It may be that this trigger has already been coded (or is in the
  124980. ** process of being coded). If this is the case, then an entry with
  124981. ** a matching TriggerPrg.pTrigger field will be present somewhere
  124982. ** in the Parse.pTriggerPrg list. Search for such an entry. */
  124983. for(pPrg=pRoot->pTriggerPrg;
  124984. pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
  124985. pPrg=pPrg->pNext
  124986. );
  124987. /* If an existing TriggerPrg could not be located, create a new one. */
  124988. if( !pPrg ){
  124989. pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
  124990. }
  124991. return pPrg;
  124992. }
  124993. /*
  124994. ** Generate code for the trigger program associated with trigger p on
  124995. ** table pTab. The reg, orconf and ignoreJump parameters passed to this
  124996. ** function are the same as those described in the header function for
  124997. ** sqlite3CodeRowTrigger()
  124998. */
  124999. SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
  125000. Parse *pParse, /* Parse context */
  125001. Trigger *p, /* Trigger to code */
  125002. Table *pTab, /* The table to code triggers from */
  125003. int reg, /* Reg array containing OLD.* and NEW.* values */
  125004. int orconf, /* ON CONFLICT policy */
  125005. int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
  125006. ){
  125007. Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
  125008. TriggerPrg *pPrg;
  125009. pPrg = getRowTrigger(pParse, p, pTab, orconf);
  125010. assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
  125011. /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
  125012. ** is a pointer to the sub-vdbe containing the trigger program. */
  125013. if( pPrg ){
  125014. int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
  125015. sqlite3VdbeAddOp4(v, OP_Program, reg, ignoreJump, ++pParse->nMem,
  125016. (const char *)pPrg->pProgram, P4_SUBPROGRAM);
  125017. VdbeComment(
  125018. (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
  125019. /* Set the P5 operand of the OP_Program instruction to non-zero if
  125020. ** recursive invocation of this trigger program is disallowed. Recursive
  125021. ** invocation is disallowed if (a) the sub-program is really a trigger,
  125022. ** not a foreign key action, and (b) the flag to enable recursive triggers
  125023. ** is clear. */
  125024. sqlite3VdbeChangeP5(v, (u8)bRecursive);
  125025. }
  125026. }
  125027. /*
  125028. ** This is called to code the required FOR EACH ROW triggers for an operation
  125029. ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
  125030. ** is given by the op parameter. The tr_tm parameter determines whether the
  125031. ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
  125032. ** parameter pChanges is passed the list of columns being modified.
  125033. **
  125034. ** If there are no triggers that fire at the specified time for the specified
  125035. ** operation on pTab, this function is a no-op.
  125036. **
  125037. ** The reg argument is the address of the first in an array of registers
  125038. ** that contain the values substituted for the new.* and old.* references
  125039. ** in the trigger program. If N is the number of columns in table pTab
  125040. ** (a copy of pTab->nCol), then registers are populated as follows:
  125041. **
  125042. ** Register Contains
  125043. ** ------------------------------------------------------
  125044. ** reg+0 OLD.rowid
  125045. ** reg+1 OLD.* value of left-most column of pTab
  125046. ** ... ...
  125047. ** reg+N OLD.* value of right-most column of pTab
  125048. ** reg+N+1 NEW.rowid
  125049. ** reg+N+2 OLD.* value of left-most column of pTab
  125050. ** ... ...
  125051. ** reg+N+N+1 NEW.* value of right-most column of pTab
  125052. **
  125053. ** For ON DELETE triggers, the registers containing the NEW.* values will
  125054. ** never be accessed by the trigger program, so they are not allocated or
  125055. ** populated by the caller (there is no data to populate them with anyway).
  125056. ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
  125057. ** are never accessed, and so are not allocated by the caller. So, for an
  125058. ** ON INSERT trigger, the value passed to this function as parameter reg
  125059. ** is not a readable register, although registers (reg+N) through
  125060. ** (reg+N+N+1) are.
  125061. **
  125062. ** Parameter orconf is the default conflict resolution algorithm for the
  125063. ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
  125064. ** is the instruction that control should jump to if a trigger program
  125065. ** raises an IGNORE exception.
  125066. */
  125067. SQLITE_PRIVATE void sqlite3CodeRowTrigger(
  125068. Parse *pParse, /* Parse context */
  125069. Trigger *pTrigger, /* List of triggers on table pTab */
  125070. int op, /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
  125071. ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
  125072. int tr_tm, /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
  125073. Table *pTab, /* The table to code triggers from */
  125074. int reg, /* The first in an array of registers (see above) */
  125075. int orconf, /* ON CONFLICT policy */
  125076. int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
  125077. ){
  125078. Trigger *p; /* Used to iterate through pTrigger list */
  125079. assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
  125080. assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
  125081. assert( (op==TK_UPDATE)==(pChanges!=0) );
  125082. for(p=pTrigger; p; p=p->pNext){
  125083. /* Sanity checking: The schema for the trigger and for the table are
  125084. ** always defined. The trigger must be in the same schema as the table
  125085. ** or else it must be a TEMP trigger. */
  125086. assert( p->pSchema!=0 );
  125087. assert( p->pTabSchema!=0 );
  125088. assert( p->pSchema==p->pTabSchema
  125089. || p->pSchema==pParse->db->aDb[1].pSchema );
  125090. /* Determine whether we should code this trigger */
  125091. if( p->op==op
  125092. && p->tr_tm==tr_tm
  125093. && checkColumnOverlap(p->pColumns, pChanges)
  125094. ){
  125095. sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
  125096. }
  125097. }
  125098. }
  125099. /*
  125100. ** Triggers may access values stored in the old.* or new.* pseudo-table.
  125101. ** This function returns a 32-bit bitmask indicating which columns of the
  125102. ** old.* or new.* tables actually are used by triggers. This information
  125103. ** may be used by the caller, for example, to avoid having to load the entire
  125104. ** old.* record into memory when executing an UPDATE or DELETE command.
  125105. **
  125106. ** Bit 0 of the returned mask is set if the left-most column of the
  125107. ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
  125108. ** the second leftmost column value is required, and so on. If there
  125109. ** are more than 32 columns in the table, and at least one of the columns
  125110. ** with an index greater than 32 may be accessed, 0xffffffff is returned.
  125111. **
  125112. ** It is not possible to determine if the old.rowid or new.rowid column is
  125113. ** accessed by triggers. The caller must always assume that it is.
  125114. **
  125115. ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
  125116. ** applies to the old.* table. If 1, the new.* table.
  125117. **
  125118. ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
  125119. ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
  125120. ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
  125121. ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
  125122. ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
  125123. */
  125124. SQLITE_PRIVATE u32 sqlite3TriggerColmask(
  125125. Parse *pParse, /* Parse context */
  125126. Trigger *pTrigger, /* List of triggers on table pTab */
  125127. ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
  125128. int isNew, /* 1 for new.* ref mask, 0 for old.* ref mask */
  125129. int tr_tm, /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  125130. Table *pTab, /* The table to code triggers from */
  125131. int orconf /* Default ON CONFLICT policy for trigger steps */
  125132. ){
  125133. const int op = pChanges ? TK_UPDATE : TK_DELETE;
  125134. u32 mask = 0;
  125135. Trigger *p;
  125136. assert( isNew==1 || isNew==0 );
  125137. for(p=pTrigger; p; p=p->pNext){
  125138. if( p->op==op && (tr_tm&p->tr_tm)
  125139. && checkColumnOverlap(p->pColumns,pChanges)
  125140. ){
  125141. TriggerPrg *pPrg;
  125142. pPrg = getRowTrigger(pParse, p, pTab, orconf);
  125143. if( pPrg ){
  125144. mask |= pPrg->aColmask[isNew];
  125145. }
  125146. }
  125147. }
  125148. return mask;
  125149. }
  125150. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  125151. /************** End of trigger.c *********************************************/
  125152. /************** Begin file update.c ******************************************/
  125153. /*
  125154. ** 2001 September 15
  125155. **
  125156. ** The author disclaims copyright to this source code. In place of
  125157. ** a legal notice, here is a blessing:
  125158. **
  125159. ** May you do good and not evil.
  125160. ** May you find forgiveness for yourself and forgive others.
  125161. ** May you share freely, never taking more than you give.
  125162. **
  125163. *************************************************************************
  125164. ** This file contains C code routines that are called by the parser
  125165. ** to handle UPDATE statements.
  125166. */
  125167. /* #include "sqliteInt.h" */
  125168. #ifndef SQLITE_OMIT_VIRTUALTABLE
  125169. /* Forward declaration */
  125170. static void updateVirtualTable(
  125171. Parse *pParse, /* The parsing context */
  125172. SrcList *pSrc, /* The virtual table to be modified */
  125173. Table *pTab, /* The virtual table */
  125174. ExprList *pChanges, /* The columns to change in the UPDATE statement */
  125175. Expr *pRowidExpr, /* Expression used to recompute the rowid */
  125176. int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
  125177. Expr *pWhere, /* WHERE clause of the UPDATE statement */
  125178. int onError /* ON CONFLICT strategy */
  125179. );
  125180. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  125181. /*
  125182. ** The most recently coded instruction was an OP_Column to retrieve the
  125183. ** i-th column of table pTab. This routine sets the P4 parameter of the
  125184. ** OP_Column to the default value, if any.
  125185. **
  125186. ** The default value of a column is specified by a DEFAULT clause in the
  125187. ** column definition. This was either supplied by the user when the table
  125188. ** was created, or added later to the table definition by an ALTER TABLE
  125189. ** command. If the latter, then the row-records in the table btree on disk
  125190. ** may not contain a value for the column and the default value, taken
  125191. ** from the P4 parameter of the OP_Column instruction, is returned instead.
  125192. ** If the former, then all row-records are guaranteed to include a value
  125193. ** for the column and the P4 value is not required.
  125194. **
  125195. ** Column definitions created by an ALTER TABLE command may only have
  125196. ** literal default values specified: a number, null or a string. (If a more
  125197. ** complicated default expression value was provided, it is evaluated
  125198. ** when the ALTER TABLE is executed and one of the literal values written
  125199. ** into the sqlite_master table.)
  125200. **
  125201. ** Therefore, the P4 parameter is only required if the default value for
  125202. ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
  125203. ** function is capable of transforming these types of expressions into
  125204. ** sqlite3_value objects.
  125205. **
  125206. ** If parameter iReg is not negative, code an OP_RealAffinity instruction
  125207. ** on register iReg. This is used when an equivalent integer value is
  125208. ** stored in place of an 8-byte floating point value in order to save
  125209. ** space.
  125210. */
  125211. SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
  125212. assert( pTab!=0 );
  125213. if( !pTab->pSelect ){
  125214. sqlite3_value *pValue = 0;
  125215. u8 enc = ENC(sqlite3VdbeDb(v));
  125216. Column *pCol = &pTab->aCol[i];
  125217. VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
  125218. assert( i<pTab->nCol );
  125219. sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
  125220. pCol->affinity, &pValue);
  125221. if( pValue ){
  125222. sqlite3VdbeAppendP4(v, pValue, P4_MEM);
  125223. }
  125224. }
  125225. #ifndef SQLITE_OMIT_FLOATING_POINT
  125226. if( pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
  125227. sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
  125228. }
  125229. #endif
  125230. }
  125231. /*
  125232. ** Check to see if column iCol of index pIdx references any of the
  125233. ** columns defined by aXRef and chngRowid. Return true if it does
  125234. ** and false if not. This is an optimization. False-positives are a
  125235. ** performance degradation, but false-negatives can result in a corrupt
  125236. ** index and incorrect answers.
  125237. **
  125238. ** aXRef[j] will be non-negative if column j of the original table is
  125239. ** being updated. chngRowid will be true if the rowid of the table is
  125240. ** being updated.
  125241. */
  125242. static int indexColumnIsBeingUpdated(
  125243. Index *pIdx, /* The index to check */
  125244. int iCol, /* Which column of the index to check */
  125245. int *aXRef, /* aXRef[j]>=0 if column j is being updated */
  125246. int chngRowid /* true if the rowid is being updated */
  125247. ){
  125248. i16 iIdxCol = pIdx->aiColumn[iCol];
  125249. assert( iIdxCol!=XN_ROWID ); /* Cannot index rowid */
  125250. if( iIdxCol>=0 ){
  125251. return aXRef[iIdxCol]>=0;
  125252. }
  125253. assert( iIdxCol==XN_EXPR );
  125254. assert( pIdx->aColExpr!=0 );
  125255. assert( pIdx->aColExpr->a[iCol].pExpr!=0 );
  125256. return sqlite3ExprReferencesUpdatedColumn(pIdx->aColExpr->a[iCol].pExpr,
  125257. aXRef,chngRowid);
  125258. }
  125259. /*
  125260. ** Check to see if index pIdx is a partial index whose conditional
  125261. ** expression might change values due to an UPDATE. Return true if
  125262. ** the index is subject to change and false if the index is guaranteed
  125263. ** to be unchanged. This is an optimization. False-positives are a
  125264. ** performance degradation, but false-negatives can result in a corrupt
  125265. ** index and incorrect answers.
  125266. **
  125267. ** aXRef[j] will be non-negative if column j of the original table is
  125268. ** being updated. chngRowid will be true if the rowid of the table is
  125269. ** being updated.
  125270. */
  125271. static int indexWhereClauseMightChange(
  125272. Index *pIdx, /* The index to check */
  125273. int *aXRef, /* aXRef[j]>=0 if column j is being updated */
  125274. int chngRowid /* true if the rowid is being updated */
  125275. ){
  125276. if( pIdx->pPartIdxWhere==0 ) return 0;
  125277. return sqlite3ExprReferencesUpdatedColumn(pIdx->pPartIdxWhere,
  125278. aXRef, chngRowid);
  125279. }
  125280. /*
  125281. ** Process an UPDATE statement.
  125282. **
  125283. ** UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
  125284. ** \_______/ \________/ \______/ \________________/
  125285. * onError pTabList pChanges pWhere
  125286. */
  125287. SQLITE_PRIVATE void sqlite3Update(
  125288. Parse *pParse, /* The parser context */
  125289. SrcList *pTabList, /* The table in which we should change things */
  125290. ExprList *pChanges, /* Things to be changed */
  125291. Expr *pWhere, /* The WHERE clause. May be null */
  125292. int onError, /* How to handle constraint errors */
  125293. ExprList *pOrderBy, /* ORDER BY clause. May be null */
  125294. Expr *pLimit, /* LIMIT clause. May be null */
  125295. Upsert *pUpsert /* ON CONFLICT clause, or null */
  125296. ){
  125297. int i, j; /* Loop counters */
  125298. Table *pTab; /* The table to be updated */
  125299. int addrTop = 0; /* VDBE instruction address of the start of the loop */
  125300. WhereInfo *pWInfo; /* Information about the WHERE clause */
  125301. Vdbe *v; /* The virtual database engine */
  125302. Index *pIdx; /* For looping over indices */
  125303. Index *pPk; /* The PRIMARY KEY index for WITHOUT ROWID tables */
  125304. int nIdx; /* Number of indices that need updating */
  125305. int nAllIdx; /* Total number of indexes */
  125306. int iBaseCur; /* Base cursor number */
  125307. int iDataCur; /* Cursor for the canonical data btree */
  125308. int iIdxCur; /* Cursor for the first index */
  125309. sqlite3 *db; /* The database structure */
  125310. int *aRegIdx = 0; /* Registers for to each index and the main table */
  125311. int *aXRef = 0; /* aXRef[i] is the index in pChanges->a[] of the
  125312. ** an expression for the i-th column of the table.
  125313. ** aXRef[i]==-1 if the i-th column is not changed. */
  125314. u8 *aToOpen; /* 1 for tables and indices to be opened */
  125315. u8 chngPk; /* PRIMARY KEY changed in a WITHOUT ROWID table */
  125316. u8 chngRowid; /* Rowid changed in a normal table */
  125317. u8 chngKey; /* Either chngPk or chngRowid */
  125318. Expr *pRowidExpr = 0; /* Expression defining the new record number */
  125319. AuthContext sContext; /* The authorization context */
  125320. NameContext sNC; /* The name-context to resolve expressions in */
  125321. int iDb; /* Database containing the table being updated */
  125322. int eOnePass; /* ONEPASS_XXX value from where.c */
  125323. int hasFK; /* True if foreign key processing is required */
  125324. int labelBreak; /* Jump here to break out of UPDATE loop */
  125325. int labelContinue; /* Jump here to continue next step of UPDATE loop */
  125326. int flags; /* Flags for sqlite3WhereBegin() */
  125327. #ifndef SQLITE_OMIT_TRIGGER
  125328. int isView; /* True when updating a view (INSTEAD OF trigger) */
  125329. Trigger *pTrigger; /* List of triggers on pTab, if required */
  125330. int tmask; /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  125331. #endif
  125332. int newmask; /* Mask of NEW.* columns accessed by BEFORE triggers */
  125333. int iEph = 0; /* Ephemeral table holding all primary key values */
  125334. int nKey = 0; /* Number of elements in regKey for WITHOUT ROWID */
  125335. int aiCurOnePass[2]; /* The write cursors opened by WHERE_ONEPASS */
  125336. int addrOpen = 0; /* Address of OP_OpenEphemeral */
  125337. int iPk = 0; /* First of nPk cells holding PRIMARY KEY value */
  125338. i16 nPk = 0; /* Number of components of the PRIMARY KEY */
  125339. int bReplace = 0; /* True if REPLACE conflict resolution might happen */
  125340. /* Register Allocations */
  125341. int regRowCount = 0; /* A count of rows changed */
  125342. int regOldRowid = 0; /* The old rowid */
  125343. int regNewRowid = 0; /* The new rowid */
  125344. int regNew = 0; /* Content of the NEW.* table in triggers */
  125345. int regOld = 0; /* Content of OLD.* table in triggers */
  125346. int regRowSet = 0; /* Rowset of rows to be updated */
  125347. int regKey = 0; /* composite PRIMARY KEY value */
  125348. memset(&sContext, 0, sizeof(sContext));
  125349. db = pParse->db;
  125350. if( pParse->nErr || db->mallocFailed ){
  125351. goto update_cleanup;
  125352. }
  125353. assert( pTabList->nSrc==1 );
  125354. /* Locate the table which we want to update.
  125355. */
  125356. pTab = sqlite3SrcListLookup(pParse, pTabList);
  125357. if( pTab==0 ) goto update_cleanup;
  125358. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  125359. /* Figure out if we have any triggers and if the table being
  125360. ** updated is a view.
  125361. */
  125362. #ifndef SQLITE_OMIT_TRIGGER
  125363. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
  125364. isView = pTab->pSelect!=0;
  125365. assert( pTrigger || tmask==0 );
  125366. #else
  125367. # define pTrigger 0
  125368. # define isView 0
  125369. # define tmask 0
  125370. #endif
  125371. #ifdef SQLITE_OMIT_VIEW
  125372. # undef isView
  125373. # define isView 0
  125374. #endif
  125375. #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
  125376. if( !isView ){
  125377. pWhere = sqlite3LimitWhere(
  125378. pParse, pTabList, pWhere, pOrderBy, pLimit, "UPDATE"
  125379. );
  125380. pOrderBy = 0;
  125381. pLimit = 0;
  125382. }
  125383. #endif
  125384. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  125385. goto update_cleanup;
  125386. }
  125387. if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
  125388. goto update_cleanup;
  125389. }
  125390. /* Allocate a cursors for the main database table and for all indices.
  125391. ** The index cursors might not be used, but if they are used they
  125392. ** need to occur right after the database cursor. So go ahead and
  125393. ** allocate enough space, just in case.
  125394. */
  125395. iBaseCur = iDataCur = pParse->nTab++;
  125396. iIdxCur = iDataCur+1;
  125397. pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
  125398. testcase( pPk!=0 && pPk!=pTab->pIndex );
  125399. for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
  125400. if( pPk==pIdx ){
  125401. iDataCur = pParse->nTab;
  125402. }
  125403. pParse->nTab++;
  125404. }
  125405. if( pUpsert ){
  125406. /* On an UPSERT, reuse the same cursors already opened by INSERT */
  125407. iDataCur = pUpsert->iDataCur;
  125408. iIdxCur = pUpsert->iIdxCur;
  125409. pParse->nTab = iBaseCur;
  125410. }
  125411. pTabList->a[0].iCursor = iDataCur;
  125412. /* Allocate space for aXRef[], aRegIdx[], and aToOpen[].
  125413. ** Initialize aXRef[] and aToOpen[] to their default values.
  125414. */
  125415. aXRef = sqlite3DbMallocRawNN(db, sizeof(int) * (pTab->nCol+nIdx+1) + nIdx+2 );
  125416. if( aXRef==0 ) goto update_cleanup;
  125417. aRegIdx = aXRef+pTab->nCol;
  125418. aToOpen = (u8*)(aRegIdx+nIdx+1);
  125419. memset(aToOpen, 1, nIdx+1);
  125420. aToOpen[nIdx+1] = 0;
  125421. for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
  125422. /* Initialize the name-context */
  125423. memset(&sNC, 0, sizeof(sNC));
  125424. sNC.pParse = pParse;
  125425. sNC.pSrcList = pTabList;
  125426. sNC.uNC.pUpsert = pUpsert;
  125427. sNC.ncFlags = NC_UUpsert;
  125428. /* Resolve the column names in all the expressions of the
  125429. ** of the UPDATE statement. Also find the column index
  125430. ** for each column to be updated in the pChanges array. For each
  125431. ** column to be updated, make sure we have authorization to change
  125432. ** that column.
  125433. */
  125434. chngRowid = chngPk = 0;
  125435. for(i=0; i<pChanges->nExpr; i++){
  125436. if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
  125437. goto update_cleanup;
  125438. }
  125439. for(j=0; j<pTab->nCol; j++){
  125440. if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
  125441. if( j==pTab->iPKey ){
  125442. chngRowid = 1;
  125443. pRowidExpr = pChanges->a[i].pExpr;
  125444. }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){
  125445. chngPk = 1;
  125446. }
  125447. aXRef[j] = i;
  125448. break;
  125449. }
  125450. }
  125451. if( j>=pTab->nCol ){
  125452. if( pPk==0 && sqlite3IsRowid(pChanges->a[i].zName) ){
  125453. j = -1;
  125454. chngRowid = 1;
  125455. pRowidExpr = pChanges->a[i].pExpr;
  125456. }else{
  125457. sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
  125458. pParse->checkSchema = 1;
  125459. goto update_cleanup;
  125460. }
  125461. }
  125462. #ifndef SQLITE_OMIT_AUTHORIZATION
  125463. {
  125464. int rc;
  125465. rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
  125466. j<0 ? "ROWID" : pTab->aCol[j].zName,
  125467. db->aDb[iDb].zDbSName);
  125468. if( rc==SQLITE_DENY ){
  125469. goto update_cleanup;
  125470. }else if( rc==SQLITE_IGNORE ){
  125471. aXRef[j] = -1;
  125472. }
  125473. }
  125474. #endif
  125475. }
  125476. assert( (chngRowid & chngPk)==0 );
  125477. assert( chngRowid==0 || chngRowid==1 );
  125478. assert( chngPk==0 || chngPk==1 );
  125479. chngKey = chngRowid + chngPk;
  125480. /* The SET expressions are not actually used inside the WHERE loop.
  125481. ** So reset the colUsed mask. Unless this is a virtual table. In that
  125482. ** case, set all bits of the colUsed mask (to ensure that the virtual
  125483. ** table implementation makes all columns available).
  125484. */
  125485. pTabList->a[0].colUsed = IsVirtual(pTab) ? ALLBITS : 0;
  125486. hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngKey);
  125487. /* There is one entry in the aRegIdx[] array for each index on the table
  125488. ** being updated. Fill in aRegIdx[] with a register number that will hold
  125489. ** the key for accessing each index.
  125490. */
  125491. if( onError==OE_Replace ) bReplace = 1;
  125492. for(nAllIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nAllIdx++){
  125493. int reg;
  125494. if( chngKey || hasFK>1 || pIdx==pPk
  125495. || indexWhereClauseMightChange(pIdx,aXRef,chngRowid)
  125496. ){
  125497. reg = ++pParse->nMem;
  125498. pParse->nMem += pIdx->nColumn;
  125499. }else{
  125500. reg = 0;
  125501. for(i=0; i<pIdx->nKeyCol; i++){
  125502. if( indexColumnIsBeingUpdated(pIdx, i, aXRef, chngRowid) ){
  125503. reg = ++pParse->nMem;
  125504. pParse->nMem += pIdx->nColumn;
  125505. if( onError==OE_Default && pIdx->onError==OE_Replace ){
  125506. bReplace = 1;
  125507. }
  125508. break;
  125509. }
  125510. }
  125511. }
  125512. if( reg==0 ) aToOpen[nAllIdx+1] = 0;
  125513. aRegIdx[nAllIdx] = reg;
  125514. }
  125515. aRegIdx[nAllIdx] = ++pParse->nMem; /* Register storing the table record */
  125516. if( bReplace ){
  125517. /* If REPLACE conflict resolution might be invoked, open cursors on all
  125518. ** indexes in case they are needed to delete records. */
  125519. memset(aToOpen, 1, nIdx+1);
  125520. }
  125521. /* Begin generating code. */
  125522. v = sqlite3GetVdbe(pParse);
  125523. if( v==0 ) goto update_cleanup;
  125524. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  125525. sqlite3BeginWriteOperation(pParse, pTrigger || hasFK, iDb);
  125526. /* Allocate required registers. */
  125527. if( !IsVirtual(pTab) ){
  125528. /* For now, regRowSet and aRegIdx[nAllIdx] share the same register.
  125529. ** If regRowSet turns out to be needed, then aRegIdx[nAllIdx] will be
  125530. ** reallocated. aRegIdx[nAllIdx] is the register in which the main
  125531. ** table record is written. regRowSet holds the RowSet for the
  125532. ** two-pass update algorithm. */
  125533. assert( aRegIdx[nAllIdx]==pParse->nMem );
  125534. regRowSet = aRegIdx[nAllIdx];
  125535. regOldRowid = regNewRowid = ++pParse->nMem;
  125536. if( chngPk || pTrigger || hasFK ){
  125537. regOld = pParse->nMem + 1;
  125538. pParse->nMem += pTab->nCol;
  125539. }
  125540. if( chngKey || pTrigger || hasFK ){
  125541. regNewRowid = ++pParse->nMem;
  125542. }
  125543. regNew = pParse->nMem + 1;
  125544. pParse->nMem += pTab->nCol;
  125545. }
  125546. /* Start the view context. */
  125547. if( isView ){
  125548. sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
  125549. }
  125550. /* If we are trying to update a view, realize that view into
  125551. ** an ephemeral table.
  125552. */
  125553. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  125554. if( isView ){
  125555. sqlite3MaterializeView(pParse, pTab,
  125556. pWhere, pOrderBy, pLimit, iDataCur
  125557. );
  125558. pOrderBy = 0;
  125559. pLimit = 0;
  125560. }
  125561. #endif
  125562. /* Resolve the column names in all the expressions in the
  125563. ** WHERE clause.
  125564. */
  125565. if( sqlite3ResolveExprNames(&sNC, pWhere) ){
  125566. goto update_cleanup;
  125567. }
  125568. #ifndef SQLITE_OMIT_VIRTUALTABLE
  125569. /* Virtual tables must be handled separately */
  125570. if( IsVirtual(pTab) ){
  125571. updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
  125572. pWhere, onError);
  125573. goto update_cleanup;
  125574. }
  125575. #endif
  125576. /* Jump to labelBreak to abandon further processing of this UPDATE */
  125577. labelContinue = labelBreak = sqlite3VdbeMakeLabel(pParse);
  125578. /* Not an UPSERT. Normal processing. Begin by
  125579. ** initialize the count of updated rows */
  125580. if( (db->flags&SQLITE_CountRows)!=0
  125581. && !pParse->pTriggerTab
  125582. && !pParse->nested
  125583. && pUpsert==0
  125584. ){
  125585. regRowCount = ++pParse->nMem;
  125586. sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
  125587. }
  125588. if( HasRowid(pTab) ){
  125589. sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
  125590. }else{
  125591. assert( pPk!=0 );
  125592. nPk = pPk->nKeyCol;
  125593. iPk = pParse->nMem+1;
  125594. pParse->nMem += nPk;
  125595. regKey = ++pParse->nMem;
  125596. if( pUpsert==0 ){
  125597. iEph = pParse->nTab++;
  125598. sqlite3VdbeAddOp3(v, OP_Null, 0, iPk, iPk+nPk-1);
  125599. addrOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEph, nPk);
  125600. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  125601. }
  125602. }
  125603. if( pUpsert ){
  125604. /* If this is an UPSERT, then all cursors have already been opened by
  125605. ** the outer INSERT and the data cursor should be pointing at the row
  125606. ** that is to be updated. So bypass the code that searches for the
  125607. ** row(s) to be updated.
  125608. */
  125609. pWInfo = 0;
  125610. eOnePass = ONEPASS_SINGLE;
  125611. sqlite3ExprIfFalse(pParse, pWhere, labelBreak, SQLITE_JUMPIFNULL);
  125612. }else{
  125613. /* Begin the database scan.
  125614. **
  125615. ** Do not consider a single-pass strategy for a multi-row update if
  125616. ** there are any triggers or foreign keys to process, or rows may
  125617. ** be deleted as a result of REPLACE conflict handling. Any of these
  125618. ** things might disturb a cursor being used to scan through the table
  125619. ** or index, causing a single-pass approach to malfunction. */
  125620. flags = WHERE_ONEPASS_DESIRED|WHERE_SEEK_UNIQ_TABLE;
  125621. if( !pParse->nested && !pTrigger && !hasFK && !chngKey && !bReplace ){
  125622. flags |= WHERE_ONEPASS_MULTIROW;
  125623. }
  125624. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, flags, iIdxCur);
  125625. if( pWInfo==0 ) goto update_cleanup;
  125626. /* A one-pass strategy that might update more than one row may not
  125627. ** be used if any column of the index used for the scan is being
  125628. ** updated. Otherwise, if there is an index on "b", statements like
  125629. ** the following could create an infinite loop:
  125630. **
  125631. ** UPDATE t1 SET b=b+1 WHERE b>?
  125632. **
  125633. ** Fall back to ONEPASS_OFF if where.c has selected a ONEPASS_MULTI
  125634. ** strategy that uses an index for which one or more columns are being
  125635. ** updated. */
  125636. eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
  125637. if( eOnePass!=ONEPASS_SINGLE ){
  125638. sqlite3MultiWrite(pParse);
  125639. if( eOnePass==ONEPASS_MULTI ){
  125640. int iCur = aiCurOnePass[1];
  125641. if( iCur>=0 && iCur!=iDataCur && aToOpen[iCur-iBaseCur] ){
  125642. eOnePass = ONEPASS_OFF;
  125643. }
  125644. assert( iCur!=iDataCur || !HasRowid(pTab) );
  125645. }
  125646. }
  125647. }
  125648. if( HasRowid(pTab) ){
  125649. /* Read the rowid of the current row of the WHERE scan. In ONEPASS_OFF
  125650. ** mode, write the rowid into the FIFO. In either of the one-pass modes,
  125651. ** leave it in register regOldRowid. */
  125652. sqlite3VdbeAddOp2(v, OP_Rowid, iDataCur, regOldRowid);
  125653. if( eOnePass==ONEPASS_OFF ){
  125654. /* We need to use regRowSet, so reallocate aRegIdx[nAllIdx] */
  125655. aRegIdx[nAllIdx] = ++pParse->nMem;
  125656. sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
  125657. }
  125658. }else{
  125659. /* Read the PK of the current row into an array of registers. In
  125660. ** ONEPASS_OFF mode, serialize the array into a record and store it in
  125661. ** the ephemeral table. Or, in ONEPASS_SINGLE or MULTI mode, change
  125662. ** the OP_OpenEphemeral instruction to a Noop (the ephemeral table
  125663. ** is not required) and leave the PK fields in the array of registers. */
  125664. for(i=0; i<nPk; i++){
  125665. assert( pPk->aiColumn[i]>=0 );
  125666. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur,pPk->aiColumn[i],iPk+i);
  125667. }
  125668. if( eOnePass ){
  125669. if( addrOpen ) sqlite3VdbeChangeToNoop(v, addrOpen);
  125670. nKey = nPk;
  125671. regKey = iPk;
  125672. }else{
  125673. sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, regKey,
  125674. sqlite3IndexAffinityStr(db, pPk), nPk);
  125675. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iEph, regKey, iPk, nPk);
  125676. }
  125677. }
  125678. if( pUpsert==0 ){
  125679. if( eOnePass!=ONEPASS_MULTI ){
  125680. sqlite3WhereEnd(pWInfo);
  125681. }
  125682. if( !isView ){
  125683. int addrOnce = 0;
  125684. /* Open every index that needs updating. */
  125685. if( eOnePass!=ONEPASS_OFF ){
  125686. if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iBaseCur] = 0;
  125687. if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iBaseCur] = 0;
  125688. }
  125689. if( eOnePass==ONEPASS_MULTI && (nIdx-(aiCurOnePass[1]>=0))>0 ){
  125690. addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  125691. }
  125692. sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, iBaseCur,
  125693. aToOpen, 0, 0);
  125694. if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
  125695. }
  125696. /* Top of the update loop */
  125697. if( eOnePass!=ONEPASS_OFF ){
  125698. if( !isView && aiCurOnePass[0]!=iDataCur && aiCurOnePass[1]!=iDataCur ){
  125699. assert( pPk );
  125700. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelBreak, regKey,nKey);
  125701. VdbeCoverage(v);
  125702. }
  125703. if( eOnePass!=ONEPASS_SINGLE ){
  125704. labelContinue = sqlite3VdbeMakeLabel(pParse);
  125705. }
  125706. sqlite3VdbeAddOp2(v, OP_IsNull, pPk ? regKey : regOldRowid, labelBreak);
  125707. VdbeCoverageIf(v, pPk==0);
  125708. VdbeCoverageIf(v, pPk!=0);
  125709. }else if( pPk ){
  125710. labelContinue = sqlite3VdbeMakeLabel(pParse);
  125711. sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak); VdbeCoverage(v);
  125712. addrTop = sqlite3VdbeAddOp2(v, OP_RowData, iEph, regKey);
  125713. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue, regKey, 0);
  125714. VdbeCoverage(v);
  125715. }else{
  125716. labelContinue = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet,labelBreak,
  125717. regOldRowid);
  125718. VdbeCoverage(v);
  125719. sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
  125720. VdbeCoverage(v);
  125721. }
  125722. }
  125723. /* If the rowid value will change, set register regNewRowid to
  125724. ** contain the new value. If the rowid is not being modified,
  125725. ** then regNewRowid is the same register as regOldRowid, which is
  125726. ** already populated. */
  125727. assert( chngKey || pTrigger || hasFK || regOldRowid==regNewRowid );
  125728. if( chngRowid ){
  125729. sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
  125730. sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid); VdbeCoverage(v);
  125731. }
  125732. /* Compute the old pre-UPDATE content of the row being changed, if that
  125733. ** information is needed */
  125734. if( chngPk || hasFK || pTrigger ){
  125735. u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
  125736. oldmask |= sqlite3TriggerColmask(pParse,
  125737. pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
  125738. );
  125739. for(i=0; i<pTab->nCol; i++){
  125740. if( oldmask==0xffffffff
  125741. || (i<32 && (oldmask & MASKBIT32(i))!=0)
  125742. || (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0
  125743. ){
  125744. testcase( oldmask!=0xffffffff && i==31 );
  125745. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regOld+i);
  125746. }else{
  125747. sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
  125748. }
  125749. }
  125750. if( chngRowid==0 && pPk==0 ){
  125751. sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
  125752. }
  125753. }
  125754. /* Populate the array of registers beginning at regNew with the new
  125755. ** row data. This array is used to check constants, create the new
  125756. ** table and index records, and as the values for any new.* references
  125757. ** made by triggers.
  125758. **
  125759. ** If there are one or more BEFORE triggers, then do not populate the
  125760. ** registers associated with columns that are (a) not modified by
  125761. ** this UPDATE statement and (b) not accessed by new.* references. The
  125762. ** values for registers not modified by the UPDATE must be reloaded from
  125763. ** the database after the BEFORE triggers are fired anyway (as the trigger
  125764. ** may have modified them). So not loading those that are not going to
  125765. ** be used eliminates some redundant opcodes.
  125766. */
  125767. newmask = sqlite3TriggerColmask(
  125768. pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
  125769. );
  125770. for(i=0; i<pTab->nCol; i++){
  125771. if( i==pTab->iPKey ){
  125772. sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
  125773. }else{
  125774. j = aXRef[i];
  125775. if( j>=0 ){
  125776. sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
  125777. }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask & MASKBIT32(i)) ){
  125778. /* This branch loads the value of a column that will not be changed
  125779. ** into a register. This is done if there are no BEFORE triggers, or
  125780. ** if there are one or more BEFORE triggers that use this value via
  125781. ** a new.* reference in a trigger program.
  125782. */
  125783. testcase( i==31 );
  125784. testcase( i==32 );
  125785. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
  125786. }else{
  125787. sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
  125788. }
  125789. }
  125790. }
  125791. /* Fire any BEFORE UPDATE triggers. This happens before constraints are
  125792. ** verified. One could argue that this is wrong.
  125793. */
  125794. if( tmask&TRIGGER_BEFORE ){
  125795. sqlite3TableAffinity(v, pTab, regNew);
  125796. sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
  125797. TRIGGER_BEFORE, pTab, regOldRowid, onError, labelContinue);
  125798. /* The row-trigger may have deleted the row being updated. In this
  125799. ** case, jump to the next row. No updates or AFTER triggers are
  125800. ** required. This behavior - what happens when the row being updated
  125801. ** is deleted or renamed by a BEFORE trigger - is left undefined in the
  125802. ** documentation.
  125803. */
  125804. if( pPk ){
  125805. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue,regKey,nKey);
  125806. VdbeCoverage(v);
  125807. }else{
  125808. sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
  125809. VdbeCoverage(v);
  125810. }
  125811. /* After-BEFORE-trigger-reload-loop:
  125812. ** If it did not delete it, the BEFORE trigger may still have modified
  125813. ** some of the columns of the row being updated. Load the values for
  125814. ** all columns not modified by the update statement into their registers
  125815. ** in case this has happened. Only unmodified columns are reloaded.
  125816. ** The values computed for modified columns use the values before the
  125817. ** BEFORE trigger runs. See test case trigger1-18.0 (added 2018-04-26)
  125818. ** for an example.
  125819. */
  125820. for(i=0; i<pTab->nCol; i++){
  125821. if( aXRef[i]<0 && i!=pTab->iPKey ){
  125822. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
  125823. }
  125824. }
  125825. }
  125826. if( !isView ){
  125827. int addr1 = 0; /* Address of jump instruction */
  125828. /* Do constraint checks. */
  125829. assert( regOldRowid>0 );
  125830. sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
  125831. regNewRowid, regOldRowid, chngKey, onError, labelContinue, &bReplace,
  125832. aXRef, 0);
  125833. /* Do FK constraint checks. */
  125834. if( hasFK ){
  125835. sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngKey);
  125836. }
  125837. /* Delete the index entries associated with the current record. */
  125838. if( bReplace || chngKey ){
  125839. if( pPk ){
  125840. addr1 = sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, 0, regKey, nKey);
  125841. }else{
  125842. addr1 = sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, 0, regOldRowid);
  125843. }
  125844. VdbeCoverageNeverTaken(v);
  125845. }
  125846. sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx, -1);
  125847. /* If changing the rowid value, or if there are foreign key constraints
  125848. ** to process, delete the old record. Otherwise, add a noop OP_Delete
  125849. ** to invoke the pre-update hook.
  125850. **
  125851. ** That (regNew==regnewRowid+1) is true is also important for the
  125852. ** pre-update hook. If the caller invokes preupdate_new(), the returned
  125853. ** value is copied from memory cell (regNewRowid+1+iCol), where iCol
  125854. ** is the column index supplied by the user.
  125855. */
  125856. assert( regNew==regNewRowid+1 );
  125857. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  125858. sqlite3VdbeAddOp3(v, OP_Delete, iDataCur,
  125859. OPFLAG_ISUPDATE | ((hasFK>1 || chngKey) ? 0 : OPFLAG_ISNOOP),
  125860. regNewRowid
  125861. );
  125862. if( eOnePass==ONEPASS_MULTI ){
  125863. assert( hasFK==0 && chngKey==0 );
  125864. sqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION);
  125865. }
  125866. if( !pParse->nested ){
  125867. sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
  125868. }
  125869. #else
  125870. if( hasFK>1 || chngKey ){
  125871. sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, 0);
  125872. }
  125873. #endif
  125874. if( bReplace || chngKey ){
  125875. sqlite3VdbeJumpHere(v, addr1);
  125876. }
  125877. if( hasFK ){
  125878. sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngKey);
  125879. }
  125880. /* Insert the new index entries and the new record. */
  125881. sqlite3CompleteInsertion(
  125882. pParse, pTab, iDataCur, iIdxCur, regNewRowid, aRegIdx,
  125883. OPFLAG_ISUPDATE | (eOnePass==ONEPASS_MULTI ? OPFLAG_SAVEPOSITION : 0),
  125884. 0, 0
  125885. );
  125886. /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
  125887. ** handle rows (possibly in other tables) that refer via a foreign key
  125888. ** to the row just updated. */
  125889. if( hasFK ){
  125890. sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngKey);
  125891. }
  125892. }
  125893. /* Increment the row counter
  125894. */
  125895. if( regRowCount ){
  125896. sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
  125897. }
  125898. sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
  125899. TRIGGER_AFTER, pTab, regOldRowid, onError, labelContinue);
  125900. /* Repeat the above with the next record to be updated, until
  125901. ** all record selected by the WHERE clause have been updated.
  125902. */
  125903. if( eOnePass==ONEPASS_SINGLE ){
  125904. /* Nothing to do at end-of-loop for a single-pass */
  125905. }else if( eOnePass==ONEPASS_MULTI ){
  125906. sqlite3VdbeResolveLabel(v, labelContinue);
  125907. sqlite3WhereEnd(pWInfo);
  125908. }else if( pPk ){
  125909. sqlite3VdbeResolveLabel(v, labelContinue);
  125910. sqlite3VdbeAddOp2(v, OP_Next, iEph, addrTop); VdbeCoverage(v);
  125911. }else{
  125912. sqlite3VdbeGoto(v, labelContinue);
  125913. }
  125914. sqlite3VdbeResolveLabel(v, labelBreak);
  125915. /* Update the sqlite_sequence table by storing the content of the
  125916. ** maximum rowid counter values recorded while inserting into
  125917. ** autoincrement tables.
  125918. */
  125919. if( pParse->nested==0 && pParse->pTriggerTab==0 && pUpsert==0 ){
  125920. sqlite3AutoincrementEnd(pParse);
  125921. }
  125922. /*
  125923. ** Return the number of rows that were changed, if we are tracking
  125924. ** that information.
  125925. */
  125926. if( regRowCount ){
  125927. sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
  125928. sqlite3VdbeSetNumCols(v, 1);
  125929. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
  125930. }
  125931. update_cleanup:
  125932. sqlite3AuthContextPop(&sContext);
  125933. sqlite3DbFree(db, aXRef); /* Also frees aRegIdx[] and aToOpen[] */
  125934. sqlite3SrcListDelete(db, pTabList);
  125935. sqlite3ExprListDelete(db, pChanges);
  125936. sqlite3ExprDelete(db, pWhere);
  125937. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)
  125938. sqlite3ExprListDelete(db, pOrderBy);
  125939. sqlite3ExprDelete(db, pLimit);
  125940. #endif
  125941. return;
  125942. }
  125943. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  125944. ** they may interfere with compilation of other functions in this file
  125945. ** (or in another file, if this file becomes part of the amalgamation). */
  125946. #ifdef isView
  125947. #undef isView
  125948. #endif
  125949. #ifdef pTrigger
  125950. #undef pTrigger
  125951. #endif
  125952. #ifndef SQLITE_OMIT_VIRTUALTABLE
  125953. /*
  125954. ** Generate code for an UPDATE of a virtual table.
  125955. **
  125956. ** There are two possible strategies - the default and the special
  125957. ** "onepass" strategy. Onepass is only used if the virtual table
  125958. ** implementation indicates that pWhere may match at most one row.
  125959. **
  125960. ** The default strategy is to create an ephemeral table that contains
  125961. ** for each row to be changed:
  125962. **
  125963. ** (A) The original rowid of that row.
  125964. ** (B) The revised rowid for the row.
  125965. ** (C) The content of every column in the row.
  125966. **
  125967. ** Then loop through the contents of this ephemeral table executing a
  125968. ** VUpdate for each row. When finished, drop the ephemeral table.
  125969. **
  125970. ** The "onepass" strategy does not use an ephemeral table. Instead, it
  125971. ** stores the same values (A, B and C above) in a register array and
  125972. ** makes a single invocation of VUpdate.
  125973. */
  125974. static void updateVirtualTable(
  125975. Parse *pParse, /* The parsing context */
  125976. SrcList *pSrc, /* The virtual table to be modified */
  125977. Table *pTab, /* The virtual table */
  125978. ExprList *pChanges, /* The columns to change in the UPDATE statement */
  125979. Expr *pRowid, /* Expression used to recompute the rowid */
  125980. int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
  125981. Expr *pWhere, /* WHERE clause of the UPDATE statement */
  125982. int onError /* ON CONFLICT strategy */
  125983. ){
  125984. Vdbe *v = pParse->pVdbe; /* Virtual machine under construction */
  125985. int ephemTab; /* Table holding the result of the SELECT */
  125986. int i; /* Loop counter */
  125987. sqlite3 *db = pParse->db; /* Database connection */
  125988. const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
  125989. WhereInfo *pWInfo;
  125990. int nArg = 2 + pTab->nCol; /* Number of arguments to VUpdate */
  125991. int regArg; /* First register in VUpdate arg array */
  125992. int regRec; /* Register in which to assemble record */
  125993. int regRowid; /* Register for ephem table rowid */
  125994. int iCsr = pSrc->a[0].iCursor; /* Cursor used for virtual table scan */
  125995. int aDummy[2]; /* Unused arg for sqlite3WhereOkOnePass() */
  125996. int eOnePass; /* True to use onepass strategy */
  125997. int addr; /* Address of OP_OpenEphemeral */
  125998. /* Allocate nArg registers in which to gather the arguments for VUpdate. Then
  125999. ** create and open the ephemeral table in which the records created from
  126000. ** these arguments will be temporarily stored. */
  126001. assert( v );
  126002. ephemTab = pParse->nTab++;
  126003. addr= sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, nArg);
  126004. regArg = pParse->nMem + 1;
  126005. pParse->nMem += nArg;
  126006. regRec = ++pParse->nMem;
  126007. regRowid = ++pParse->nMem;
  126008. /* Start scanning the virtual table */
  126009. pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0,0,WHERE_ONEPASS_DESIRED,0);
  126010. if( pWInfo==0 ) return;
  126011. /* Populate the argument registers. */
  126012. for(i=0; i<pTab->nCol; i++){
  126013. if( aXRef[i]>=0 ){
  126014. sqlite3ExprCode(pParse, pChanges->a[aXRef[i]].pExpr, regArg+2+i);
  126015. }else{
  126016. sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, i, regArg+2+i);
  126017. sqlite3VdbeChangeP5(v, OPFLAG_NOCHNG);/* Enable sqlite3_vtab_nochange() */
  126018. }
  126019. }
  126020. if( HasRowid(pTab) ){
  126021. sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg);
  126022. if( pRowid ){
  126023. sqlite3ExprCode(pParse, pRowid, regArg+1);
  126024. }else{
  126025. sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg+1);
  126026. }
  126027. }else{
  126028. Index *pPk; /* PRIMARY KEY index */
  126029. i16 iPk; /* PRIMARY KEY column */
  126030. pPk = sqlite3PrimaryKeyIndex(pTab);
  126031. assert( pPk!=0 );
  126032. assert( pPk->nKeyCol==1 );
  126033. iPk = pPk->aiColumn[0];
  126034. sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, iPk, regArg);
  126035. sqlite3VdbeAddOp2(v, OP_SCopy, regArg+2+iPk, regArg+1);
  126036. }
  126037. eOnePass = sqlite3WhereOkOnePass(pWInfo, aDummy);
  126038. /* There is no ONEPASS_MULTI on virtual tables */
  126039. assert( eOnePass==ONEPASS_OFF || eOnePass==ONEPASS_SINGLE );
  126040. if( eOnePass ){
  126041. /* If using the onepass strategy, no-op out the OP_OpenEphemeral coded
  126042. ** above. */
  126043. sqlite3VdbeChangeToNoop(v, addr);
  126044. sqlite3VdbeAddOp1(v, OP_Close, iCsr);
  126045. }else{
  126046. /* Create a record from the argument register contents and insert it into
  126047. ** the ephemeral table. */
  126048. sqlite3MultiWrite(pParse);
  126049. sqlite3VdbeAddOp3(v, OP_MakeRecord, regArg, nArg, regRec);
  126050. #ifdef SQLITE_DEBUG
  126051. /* Signal an assert() within OP_MakeRecord that it is allowed to
  126052. ** accept no-change records with serial_type 10 */
  126053. sqlite3VdbeChangeP5(v, OPFLAG_NOCHNG_MAGIC);
  126054. #endif
  126055. sqlite3VdbeAddOp2(v, OP_NewRowid, ephemTab, regRowid);
  126056. sqlite3VdbeAddOp3(v, OP_Insert, ephemTab, regRec, regRowid);
  126057. }
  126058. if( eOnePass==ONEPASS_OFF ){
  126059. /* End the virtual table scan */
  126060. sqlite3WhereEnd(pWInfo);
  126061. /* Begin scannning through the ephemeral table. */
  126062. addr = sqlite3VdbeAddOp1(v, OP_Rewind, ephemTab); VdbeCoverage(v);
  126063. /* Extract arguments from the current row of the ephemeral table and
  126064. ** invoke the VUpdate method. */
  126065. for(i=0; i<nArg; i++){
  126066. sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i, regArg+i);
  126067. }
  126068. }
  126069. sqlite3VtabMakeWritable(pParse, pTab);
  126070. sqlite3VdbeAddOp4(v, OP_VUpdate, 0, nArg, regArg, pVTab, P4_VTAB);
  126071. sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
  126072. sqlite3MayAbort(pParse);
  126073. /* End of the ephemeral table scan. Or, if using the onepass strategy,
  126074. ** jump to here if the scan visited zero rows. */
  126075. if( eOnePass==ONEPASS_OFF ){
  126076. sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1); VdbeCoverage(v);
  126077. sqlite3VdbeJumpHere(v, addr);
  126078. sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
  126079. }else{
  126080. sqlite3WhereEnd(pWInfo);
  126081. }
  126082. }
  126083. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  126084. /************** End of update.c **********************************************/
  126085. /************** Begin file upsert.c ******************************************/
  126086. /*
  126087. ** 2018-04-12
  126088. **
  126089. ** The author disclaims copyright to this source code. In place of
  126090. ** a legal notice, here is a blessing:
  126091. **
  126092. ** May you do good and not evil.
  126093. ** May you find forgiveness for yourself and forgive others.
  126094. ** May you share freely, never taking more than you give.
  126095. **
  126096. *************************************************************************
  126097. ** This file contains code to implement various aspects of UPSERT
  126098. ** processing and handling of the Upsert object.
  126099. */
  126100. /* #include "sqliteInt.h" */
  126101. #ifndef SQLITE_OMIT_UPSERT
  126102. /*
  126103. ** Free a list of Upsert objects
  126104. */
  126105. SQLITE_PRIVATE void sqlite3UpsertDelete(sqlite3 *db, Upsert *p){
  126106. if( p ){
  126107. sqlite3ExprListDelete(db, p->pUpsertTarget);
  126108. sqlite3ExprDelete(db, p->pUpsertTargetWhere);
  126109. sqlite3ExprListDelete(db, p->pUpsertSet);
  126110. sqlite3ExprDelete(db, p->pUpsertWhere);
  126111. sqlite3DbFree(db, p);
  126112. }
  126113. }
  126114. /*
  126115. ** Duplicate an Upsert object.
  126116. */
  126117. SQLITE_PRIVATE Upsert *sqlite3UpsertDup(sqlite3 *db, Upsert *p){
  126118. if( p==0 ) return 0;
  126119. return sqlite3UpsertNew(db,
  126120. sqlite3ExprListDup(db, p->pUpsertTarget, 0),
  126121. sqlite3ExprDup(db, p->pUpsertTargetWhere, 0),
  126122. sqlite3ExprListDup(db, p->pUpsertSet, 0),
  126123. sqlite3ExprDup(db, p->pUpsertWhere, 0)
  126124. );
  126125. }
  126126. /*
  126127. ** Create a new Upsert object.
  126128. */
  126129. SQLITE_PRIVATE Upsert *sqlite3UpsertNew(
  126130. sqlite3 *db, /* Determines which memory allocator to use */
  126131. ExprList *pTarget, /* Target argument to ON CONFLICT, or NULL */
  126132. Expr *pTargetWhere, /* Optional WHERE clause on the target */
  126133. ExprList *pSet, /* UPDATE columns, or NULL for a DO NOTHING */
  126134. Expr *pWhere /* WHERE clause for the ON CONFLICT UPDATE */
  126135. ){
  126136. Upsert *pNew;
  126137. pNew = sqlite3DbMallocRaw(db, sizeof(Upsert));
  126138. if( pNew==0 ){
  126139. sqlite3ExprListDelete(db, pTarget);
  126140. sqlite3ExprDelete(db, pTargetWhere);
  126141. sqlite3ExprListDelete(db, pSet);
  126142. sqlite3ExprDelete(db, pWhere);
  126143. return 0;
  126144. }else{
  126145. pNew->pUpsertTarget = pTarget;
  126146. pNew->pUpsertTargetWhere = pTargetWhere;
  126147. pNew->pUpsertSet = pSet;
  126148. pNew->pUpsertWhere = pWhere;
  126149. pNew->pUpsertIdx = 0;
  126150. }
  126151. return pNew;
  126152. }
  126153. /*
  126154. ** Analyze the ON CONFLICT clause described by pUpsert. Resolve all
  126155. ** symbols in the conflict-target.
  126156. **
  126157. ** Return SQLITE_OK if everything works, or an error code is something
  126158. ** is wrong.
  126159. */
  126160. SQLITE_PRIVATE int sqlite3UpsertAnalyzeTarget(
  126161. Parse *pParse, /* The parsing context */
  126162. SrcList *pTabList, /* Table into which we are inserting */
  126163. Upsert *pUpsert /* The ON CONFLICT clauses */
  126164. ){
  126165. Table *pTab; /* That table into which we are inserting */
  126166. int rc; /* Result code */
  126167. int iCursor; /* Cursor used by pTab */
  126168. Index *pIdx; /* One of the indexes of pTab */
  126169. ExprList *pTarget; /* The conflict-target clause */
  126170. Expr *pTerm; /* One term of the conflict-target clause */
  126171. NameContext sNC; /* Context for resolving symbolic names */
  126172. Expr sCol[2]; /* Index column converted into an Expr */
  126173. assert( pTabList->nSrc==1 );
  126174. assert( pTabList->a[0].pTab!=0 );
  126175. assert( pUpsert!=0 );
  126176. assert( pUpsert->pUpsertTarget!=0 );
  126177. /* Resolve all symbolic names in the conflict-target clause, which
  126178. ** includes both the list of columns and the optional partial-index
  126179. ** WHERE clause.
  126180. */
  126181. memset(&sNC, 0, sizeof(sNC));
  126182. sNC.pParse = pParse;
  126183. sNC.pSrcList = pTabList;
  126184. rc = sqlite3ResolveExprListNames(&sNC, pUpsert->pUpsertTarget);
  126185. if( rc ) return rc;
  126186. rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertTargetWhere);
  126187. if( rc ) return rc;
  126188. /* Check to see if the conflict target matches the rowid. */
  126189. pTab = pTabList->a[0].pTab;
  126190. pTarget = pUpsert->pUpsertTarget;
  126191. iCursor = pTabList->a[0].iCursor;
  126192. if( HasRowid(pTab)
  126193. && pTarget->nExpr==1
  126194. && (pTerm = pTarget->a[0].pExpr)->op==TK_COLUMN
  126195. && pTerm->iColumn==XN_ROWID
  126196. ){
  126197. /* The conflict-target is the rowid of the primary table */
  126198. assert( pUpsert->pUpsertIdx==0 );
  126199. return SQLITE_OK;
  126200. }
  126201. /* Initialize sCol[0..1] to be an expression parse tree for a
  126202. ** single column of an index. The sCol[0] node will be the TK_COLLATE
  126203. ** operator and sCol[1] will be the TK_COLUMN operator. Code below
  126204. ** will populate the specific collation and column number values
  126205. ** prior to comparing against the conflict-target expression.
  126206. */
  126207. memset(sCol, 0, sizeof(sCol));
  126208. sCol[0].op = TK_COLLATE;
  126209. sCol[0].pLeft = &sCol[1];
  126210. sCol[1].op = TK_COLUMN;
  126211. sCol[1].iTable = pTabList->a[0].iCursor;
  126212. /* Check for matches against other indexes */
  126213. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  126214. int ii, jj, nn;
  126215. if( !IsUniqueIndex(pIdx) ) continue;
  126216. if( pTarget->nExpr!=pIdx->nKeyCol ) continue;
  126217. if( pIdx->pPartIdxWhere ){
  126218. if( pUpsert->pUpsertTargetWhere==0 ) continue;
  126219. if( sqlite3ExprCompare(pParse, pUpsert->pUpsertTargetWhere,
  126220. pIdx->pPartIdxWhere, iCursor)!=0 ){
  126221. continue;
  126222. }
  126223. }
  126224. nn = pIdx->nKeyCol;
  126225. for(ii=0; ii<nn; ii++){
  126226. Expr *pExpr;
  126227. sCol[0].u.zToken = (char*)pIdx->azColl[ii];
  126228. if( pIdx->aiColumn[ii]==XN_EXPR ){
  126229. assert( pIdx->aColExpr!=0 );
  126230. assert( pIdx->aColExpr->nExpr>ii );
  126231. pExpr = pIdx->aColExpr->a[ii].pExpr;
  126232. if( pExpr->op!=TK_COLLATE ){
  126233. sCol[0].pLeft = pExpr;
  126234. pExpr = &sCol[0];
  126235. }
  126236. }else{
  126237. sCol[0].pLeft = &sCol[1];
  126238. sCol[1].iColumn = pIdx->aiColumn[ii];
  126239. pExpr = &sCol[0];
  126240. }
  126241. for(jj=0; jj<nn; jj++){
  126242. if( sqlite3ExprCompare(pParse, pTarget->a[jj].pExpr, pExpr,iCursor)<2 ){
  126243. break; /* Column ii of the index matches column jj of target */
  126244. }
  126245. }
  126246. if( jj>=nn ){
  126247. /* The target contains no match for column jj of the index */
  126248. break;
  126249. }
  126250. }
  126251. if( ii<nn ){
  126252. /* Column ii of the index did not match any term of the conflict target.
  126253. ** Continue the search with the next index. */
  126254. continue;
  126255. }
  126256. pUpsert->pUpsertIdx = pIdx;
  126257. return SQLITE_OK;
  126258. }
  126259. sqlite3ErrorMsg(pParse, "ON CONFLICT clause does not match any "
  126260. "PRIMARY KEY or UNIQUE constraint");
  126261. return SQLITE_ERROR;
  126262. }
  126263. /*
  126264. ** Generate bytecode that does an UPDATE as part of an upsert.
  126265. **
  126266. ** If pIdx is NULL, then the UNIQUE constraint that failed was the IPK.
  126267. ** In this case parameter iCur is a cursor open on the table b-tree that
  126268. ** currently points to the conflicting table row. Otherwise, if pIdx
  126269. ** is not NULL, then pIdx is the constraint that failed and iCur is a
  126270. ** cursor points to the conflicting row.
  126271. */
  126272. SQLITE_PRIVATE void sqlite3UpsertDoUpdate(
  126273. Parse *pParse, /* The parsing and code-generating context */
  126274. Upsert *pUpsert, /* The ON CONFLICT clause for the upsert */
  126275. Table *pTab, /* The table being updated */
  126276. Index *pIdx, /* The UNIQUE constraint that failed */
  126277. int iCur /* Cursor for pIdx (or pTab if pIdx==NULL) */
  126278. ){
  126279. Vdbe *v = pParse->pVdbe;
  126280. sqlite3 *db = pParse->db;
  126281. SrcList *pSrc; /* FROM clause for the UPDATE */
  126282. int iDataCur;
  126283. assert( v!=0 );
  126284. assert( pUpsert!=0 );
  126285. VdbeNoopComment((v, "Begin DO UPDATE of UPSERT"));
  126286. iDataCur = pUpsert->iDataCur;
  126287. if( pIdx && iCur!=iDataCur ){
  126288. if( HasRowid(pTab) ){
  126289. int regRowid = sqlite3GetTempReg(pParse);
  126290. sqlite3VdbeAddOp2(v, OP_IdxRowid, iCur, regRowid);
  126291. sqlite3VdbeAddOp3(v, OP_SeekRowid, iDataCur, 0, regRowid);
  126292. VdbeCoverage(v);
  126293. sqlite3ReleaseTempReg(pParse, regRowid);
  126294. }else{
  126295. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  126296. int nPk = pPk->nKeyCol;
  126297. int iPk = pParse->nMem+1;
  126298. int i;
  126299. pParse->nMem += nPk;
  126300. for(i=0; i<nPk; i++){
  126301. int k;
  126302. assert( pPk->aiColumn[i]>=0 );
  126303. k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]);
  126304. sqlite3VdbeAddOp3(v, OP_Column, iCur, k, iPk+i);
  126305. VdbeComment((v, "%s.%s", pIdx->zName,
  126306. pTab->aCol[pPk->aiColumn[i]].zName));
  126307. }
  126308. sqlite3VdbeVerifyAbortable(v, OE_Abort);
  126309. i = sqlite3VdbeAddOp4Int(v, OP_Found, iDataCur, 0, iPk, nPk);
  126310. VdbeCoverage(v);
  126311. sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CORRUPT, OE_Abort, 0,
  126312. "corrupt database", P4_STATIC);
  126313. sqlite3VdbeJumpHere(v, i);
  126314. }
  126315. }
  126316. /* pUpsert does not own pUpsertSrc - the outer INSERT statement does. So
  126317. ** we have to make a copy before passing it down into sqlite3Update() */
  126318. pSrc = sqlite3SrcListDup(db, pUpsert->pUpsertSrc, 0);
  126319. sqlite3Update(pParse, pSrc, pUpsert->pUpsertSet,
  126320. pUpsert->pUpsertWhere, OE_Abort, 0, 0, pUpsert);
  126321. pUpsert->pUpsertSet = 0; /* Will have been deleted by sqlite3Update() */
  126322. pUpsert->pUpsertWhere = 0; /* Will have been deleted by sqlite3Update() */
  126323. VdbeNoopComment((v, "End DO UPDATE of UPSERT"));
  126324. }
  126325. #endif /* SQLITE_OMIT_UPSERT */
  126326. /************** End of upsert.c **********************************************/
  126327. /************** Begin file vacuum.c ******************************************/
  126328. /*
  126329. ** 2003 April 6
  126330. **
  126331. ** The author disclaims copyright to this source code. In place of
  126332. ** a legal notice, here is a blessing:
  126333. **
  126334. ** May you do good and not evil.
  126335. ** May you find forgiveness for yourself and forgive others.
  126336. ** May you share freely, never taking more than you give.
  126337. **
  126338. *************************************************************************
  126339. ** This file contains code used to implement the VACUUM command.
  126340. **
  126341. ** Most of the code in this file may be omitted by defining the
  126342. ** SQLITE_OMIT_VACUUM macro.
  126343. */
  126344. /* #include "sqliteInt.h" */
  126345. /* #include "vdbeInt.h" */
  126346. #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
  126347. /*
  126348. ** Execute zSql on database db.
  126349. **
  126350. ** If zSql returns rows, then each row will have exactly one
  126351. ** column. (This will only happen if zSql begins with "SELECT".)
  126352. ** Take each row of result and call execSql() again recursively.
  126353. **
  126354. ** The execSqlF() routine does the same thing, except it accepts
  126355. ** a format string as its third argument
  126356. */
  126357. static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
  126358. sqlite3_stmt *pStmt;
  126359. int rc;
  126360. /* printf("SQL: [%s]\n", zSql); fflush(stdout); */
  126361. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  126362. if( rc!=SQLITE_OK ) return rc;
  126363. while( SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
  126364. const char *zSubSql = (const char*)sqlite3_column_text(pStmt,0);
  126365. assert( sqlite3_strnicmp(zSql,"SELECT",6)==0 );
  126366. /* The secondary SQL must be one of CREATE TABLE, CREATE INDEX,
  126367. ** or INSERT. Historically there have been attacks that first
  126368. ** corrupt the sqlite_master.sql field with other kinds of statements
  126369. ** then run VACUUM to get those statements to execute at inappropriate
  126370. ** times. */
  126371. if( zSubSql
  126372. && (strncmp(zSubSql,"CRE",3)==0 || strncmp(zSubSql,"INS",3)==0)
  126373. ){
  126374. rc = execSql(db, pzErrMsg, zSubSql);
  126375. if( rc!=SQLITE_OK ) break;
  126376. }
  126377. }
  126378. assert( rc!=SQLITE_ROW );
  126379. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  126380. if( rc ){
  126381. sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
  126382. }
  126383. (void)sqlite3_finalize(pStmt);
  126384. return rc;
  126385. }
  126386. static int execSqlF(sqlite3 *db, char **pzErrMsg, const char *zSql, ...){
  126387. char *z;
  126388. va_list ap;
  126389. int rc;
  126390. va_start(ap, zSql);
  126391. z = sqlite3VMPrintf(db, zSql, ap);
  126392. va_end(ap);
  126393. if( z==0 ) return SQLITE_NOMEM;
  126394. rc = execSql(db, pzErrMsg, z);
  126395. sqlite3DbFree(db, z);
  126396. return rc;
  126397. }
  126398. /*
  126399. ** The VACUUM command is used to clean up the database,
  126400. ** collapse free space, etc. It is modelled after the VACUUM command
  126401. ** in PostgreSQL. The VACUUM command works as follows:
  126402. **
  126403. ** (1) Create a new transient database file
  126404. ** (2) Copy all content from the database being vacuumed into
  126405. ** the new transient database file
  126406. ** (3) Copy content from the transient database back into the
  126407. ** original database.
  126408. **
  126409. ** The transient database requires temporary disk space approximately
  126410. ** equal to the size of the original database. The copy operation of
  126411. ** step (3) requires additional temporary disk space approximately equal
  126412. ** to the size of the original database for the rollback journal.
  126413. ** Hence, temporary disk space that is approximately 2x the size of the
  126414. ** original database is required. Every page of the database is written
  126415. ** approximately 3 times: Once for step (2) and twice for step (3).
  126416. ** Two writes per page are required in step (3) because the original
  126417. ** database content must be written into the rollback journal prior to
  126418. ** overwriting the database with the vacuumed content.
  126419. **
  126420. ** Only 1x temporary space and only 1x writes would be required if
  126421. ** the copy of step (3) were replaced by deleting the original database
  126422. ** and renaming the transient database as the original. But that will
  126423. ** not work if other processes are attached to the original database.
  126424. ** And a power loss in between deleting the original and renaming the
  126425. ** transient would cause the database file to appear to be deleted
  126426. ** following reboot.
  126427. */
  126428. SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse, Token *pNm, Expr *pInto){
  126429. Vdbe *v = sqlite3GetVdbe(pParse);
  126430. int iDb = 0;
  126431. if( v==0 ) goto build_vacuum_end;
  126432. if( pParse->nErr ) goto build_vacuum_end;
  126433. if( pNm ){
  126434. #ifndef SQLITE_BUG_COMPATIBLE_20160819
  126435. /* Default behavior: Report an error if the argument to VACUUM is
  126436. ** not recognized */
  126437. iDb = sqlite3TwoPartName(pParse, pNm, pNm, &pNm);
  126438. if( iDb<0 ) goto build_vacuum_end;
  126439. #else
  126440. /* When SQLITE_BUG_COMPATIBLE_20160819 is defined, unrecognized arguments
  126441. ** to VACUUM are silently ignored. This is a back-out of a bug fix that
  126442. ** occurred on 2016-08-19 (https://www.sqlite.org/src/info/083f9e6270).
  126443. ** The buggy behavior is required for binary compatibility with some
  126444. ** legacy applications. */
  126445. iDb = sqlite3FindDb(pParse->db, pNm);
  126446. if( iDb<0 ) iDb = 0;
  126447. #endif
  126448. }
  126449. if( iDb!=1 ){
  126450. int iIntoReg = 0;
  126451. if( pInto && sqlite3ResolveSelfReference(pParse,0,0,pInto,0)==0 ){
  126452. iIntoReg = ++pParse->nMem;
  126453. sqlite3ExprCode(pParse, pInto, iIntoReg);
  126454. }
  126455. sqlite3VdbeAddOp2(v, OP_Vacuum, iDb, iIntoReg);
  126456. sqlite3VdbeUsesBtree(v, iDb);
  126457. }
  126458. build_vacuum_end:
  126459. sqlite3ExprDelete(pParse->db, pInto);
  126460. return;
  126461. }
  126462. /*
  126463. ** This routine implements the OP_Vacuum opcode of the VDBE.
  126464. */
  126465. SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3RunVacuum(
  126466. char **pzErrMsg, /* Write error message here */
  126467. sqlite3 *db, /* Database connection */
  126468. int iDb, /* Which attached DB to vacuum */
  126469. sqlite3_value *pOut /* Write results here, if not NULL. VACUUM INTO */
  126470. ){
  126471. int rc = SQLITE_OK; /* Return code from service routines */
  126472. Btree *pMain; /* The database being vacuumed */
  126473. Btree *pTemp; /* The temporary database we vacuum into */
  126474. u32 saved_mDbFlags; /* Saved value of db->mDbFlags */
  126475. u64 saved_flags; /* Saved value of db->flags */
  126476. int saved_nChange; /* Saved value of db->nChange */
  126477. int saved_nTotalChange; /* Saved value of db->nTotalChange */
  126478. u32 saved_openFlags; /* Saved value of db->openFlags */
  126479. u8 saved_mTrace; /* Saved trace settings */
  126480. Db *pDb = 0; /* Database to detach at end of vacuum */
  126481. int isMemDb; /* True if vacuuming a :memory: database */
  126482. int nRes; /* Bytes of reserved space at the end of each page */
  126483. int nDb; /* Number of attached databases */
  126484. const char *zDbMain; /* Schema name of database to vacuum */
  126485. const char *zOut; /* Name of output file */
  126486. if( !db->autoCommit ){
  126487. sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
  126488. return SQLITE_ERROR; /* IMP: R-12218-18073 */
  126489. }
  126490. if( db->nVdbeActive>1 ){
  126491. sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
  126492. return SQLITE_ERROR; /* IMP: R-15610-35227 */
  126493. }
  126494. saved_openFlags = db->openFlags;
  126495. if( pOut ){
  126496. if( sqlite3_value_type(pOut)!=SQLITE_TEXT ){
  126497. sqlite3SetString(pzErrMsg, db, "non-text filename");
  126498. return SQLITE_ERROR;
  126499. }
  126500. zOut = (const char*)sqlite3_value_text(pOut);
  126501. db->openFlags &= ~SQLITE_OPEN_READONLY;
  126502. db->openFlags |= SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE;
  126503. }else{
  126504. zOut = "";
  126505. }
  126506. /* Save the current value of the database flags so that it can be
  126507. ** restored before returning. Then set the writable-schema flag, and
  126508. ** disable CHECK and foreign key constraints. */
  126509. saved_flags = db->flags;
  126510. saved_mDbFlags = db->mDbFlags;
  126511. saved_nChange = db->nChange;
  126512. saved_nTotalChange = db->nTotalChange;
  126513. saved_mTrace = db->mTrace;
  126514. db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks;
  126515. db->mDbFlags |= DBFLAG_PreferBuiltin | DBFLAG_Vacuum;
  126516. db->flags &= ~(u64)(SQLITE_ForeignKeys | SQLITE_ReverseOrder
  126517. | SQLITE_Defensive | SQLITE_CountRows);
  126518. db->mTrace = 0;
  126519. zDbMain = db->aDb[iDb].zDbSName;
  126520. pMain = db->aDb[iDb].pBt;
  126521. isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
  126522. /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
  126523. ** can be set to 'off' for this file, as it is not recovered if a crash
  126524. ** occurs anyway. The integrity of the database is maintained by a
  126525. ** (possibly synchronous) transaction opened on the main database before
  126526. ** sqlite3BtreeCopyFile() is called.
  126527. **
  126528. ** An optimisation would be to use a non-journaled pager.
  126529. ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
  126530. ** that actually made the VACUUM run slower. Very little journalling
  126531. ** actually occurs when doing a vacuum since the vacuum_db is initially
  126532. ** empty. Only the journal header is written. Apparently it takes more
  126533. ** time to parse and run the PRAGMA to turn journalling off than it does
  126534. ** to write the journal header file.
  126535. */
  126536. nDb = db->nDb;
  126537. rc = execSqlF(db, pzErrMsg, "ATTACH %Q AS vacuum_db", zOut);
  126538. db->openFlags = saved_openFlags;
  126539. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  126540. assert( (db->nDb-1)==nDb );
  126541. pDb = &db->aDb[nDb];
  126542. assert( strcmp(pDb->zDbSName,"vacuum_db")==0 );
  126543. pTemp = pDb->pBt;
  126544. if( pOut ){
  126545. sqlite3_file *id = sqlite3PagerFile(sqlite3BtreePager(pTemp));
  126546. i64 sz = 0;
  126547. if( id->pMethods!=0 && (sqlite3OsFileSize(id, &sz)!=SQLITE_OK || sz>0) ){
  126548. rc = SQLITE_ERROR;
  126549. sqlite3SetString(pzErrMsg, db, "output file already exists");
  126550. goto end_of_vacuum;
  126551. }
  126552. db->mDbFlags |= DBFLAG_VacuumInto;
  126553. }
  126554. nRes = sqlite3BtreeGetOptimalReserve(pMain);
  126555. /* A VACUUM cannot change the pagesize of an encrypted database. */
  126556. #ifdef SQLITE_HAS_CODEC
  126557. if( db->nextPagesize ){
  126558. extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
  126559. int nKey;
  126560. char *zKey;
  126561. sqlite3CodecGetKey(db, iDb, (void**)&zKey, &nKey);
  126562. if( nKey ) db->nextPagesize = 0;
  126563. }
  126564. #endif
  126565. sqlite3BtreeSetCacheSize(pTemp, db->aDb[iDb].pSchema->cache_size);
  126566. sqlite3BtreeSetSpillSize(pTemp, sqlite3BtreeSetSpillSize(pMain,0));
  126567. sqlite3BtreeSetPagerFlags(pTemp, PAGER_SYNCHRONOUS_OFF|PAGER_CACHESPILL);
  126568. /* Begin a transaction and take an exclusive lock on the main database
  126569. ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
  126570. ** to ensure that we do not try to change the page-size on a WAL database.
  126571. */
  126572. rc = execSql(db, pzErrMsg, "BEGIN");
  126573. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  126574. rc = sqlite3BtreeBeginTrans(pMain, pOut==0 ? 2 : 0, 0);
  126575. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  126576. /* Do not attempt to change the page size for a WAL database */
  126577. if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
  126578. ==PAGER_JOURNALMODE_WAL ){
  126579. db->nextPagesize = 0;
  126580. }
  126581. if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
  126582. || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
  126583. || NEVER(db->mallocFailed)
  126584. ){
  126585. rc = SQLITE_NOMEM_BKPT;
  126586. goto end_of_vacuum;
  126587. }
  126588. #ifndef SQLITE_OMIT_AUTOVACUUM
  126589. sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
  126590. sqlite3BtreeGetAutoVacuum(pMain));
  126591. #endif
  126592. /* Query the schema of the main database. Create a mirror schema
  126593. ** in the temporary database.
  126594. */
  126595. db->init.iDb = nDb; /* force new CREATE statements into vacuum_db */
  126596. rc = execSqlF(db, pzErrMsg,
  126597. "SELECT sql FROM \"%w\".sqlite_master"
  126598. " WHERE type='table'AND name<>'sqlite_sequence'"
  126599. " AND coalesce(rootpage,1)>0",
  126600. zDbMain
  126601. );
  126602. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  126603. rc = execSqlF(db, pzErrMsg,
  126604. "SELECT sql FROM \"%w\".sqlite_master"
  126605. " WHERE type='index'",
  126606. zDbMain
  126607. );
  126608. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  126609. db->init.iDb = 0;
  126610. /* Loop through the tables in the main database. For each, do
  126611. ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
  126612. ** the contents to the temporary database.
  126613. */
  126614. rc = execSqlF(db, pzErrMsg,
  126615. "SELECT'INSERT INTO vacuum_db.'||quote(name)"
  126616. "||' SELECT*FROM\"%w\".'||quote(name)"
  126617. "FROM vacuum_db.sqlite_master "
  126618. "WHERE type='table'AND coalesce(rootpage,1)>0",
  126619. zDbMain
  126620. );
  126621. assert( (db->mDbFlags & DBFLAG_Vacuum)!=0 );
  126622. db->mDbFlags &= ~DBFLAG_Vacuum;
  126623. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  126624. /* Copy the triggers, views, and virtual tables from the main database
  126625. ** over to the temporary database. None of these objects has any
  126626. ** associated storage, so all we have to do is copy their entries
  126627. ** from the SQLITE_MASTER table.
  126628. */
  126629. rc = execSqlF(db, pzErrMsg,
  126630. "INSERT INTO vacuum_db.sqlite_master"
  126631. " SELECT*FROM \"%w\".sqlite_master"
  126632. " WHERE type IN('view','trigger')"
  126633. " OR(type='table'AND rootpage=0)",
  126634. zDbMain
  126635. );
  126636. if( rc ) goto end_of_vacuum;
  126637. /* At this point, there is a write transaction open on both the
  126638. ** vacuum database and the main database. Assuming no error occurs,
  126639. ** both transactions are closed by this block - the main database
  126640. ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
  126641. ** call to sqlite3BtreeCommit().
  126642. */
  126643. {
  126644. u32 meta;
  126645. int i;
  126646. /* This array determines which meta meta values are preserved in the
  126647. ** vacuum. Even entries are the meta value number and odd entries
  126648. ** are an increment to apply to the meta value after the vacuum.
  126649. ** The increment is used to increase the schema cookie so that other
  126650. ** connections to the same database will know to reread the schema.
  126651. */
  126652. static const unsigned char aCopy[] = {
  126653. BTREE_SCHEMA_VERSION, 1, /* Add one to the old schema cookie */
  126654. BTREE_DEFAULT_CACHE_SIZE, 0, /* Preserve the default page cache size */
  126655. BTREE_TEXT_ENCODING, 0, /* Preserve the text encoding */
  126656. BTREE_USER_VERSION, 0, /* Preserve the user version */
  126657. BTREE_APPLICATION_ID, 0, /* Preserve the application id */
  126658. };
  126659. assert( 1==sqlite3BtreeIsInTrans(pTemp) );
  126660. assert( pOut!=0 || 1==sqlite3BtreeIsInTrans(pMain) );
  126661. /* Copy Btree meta values */
  126662. for(i=0; i<ArraySize(aCopy); i+=2){
  126663. /* GetMeta() and UpdateMeta() cannot fail in this context because
  126664. ** we already have page 1 loaded into cache and marked dirty. */
  126665. sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
  126666. rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
  126667. if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
  126668. }
  126669. if( pOut==0 ){
  126670. rc = sqlite3BtreeCopyFile(pMain, pTemp);
  126671. }
  126672. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  126673. rc = sqlite3BtreeCommit(pTemp);
  126674. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  126675. #ifndef SQLITE_OMIT_AUTOVACUUM
  126676. if( pOut==0 ){
  126677. sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
  126678. }
  126679. #endif
  126680. }
  126681. assert( rc==SQLITE_OK );
  126682. if( pOut==0 ){
  126683. rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
  126684. }
  126685. end_of_vacuum:
  126686. /* Restore the original value of db->flags */
  126687. db->init.iDb = 0;
  126688. db->mDbFlags = saved_mDbFlags;
  126689. db->flags = saved_flags;
  126690. db->nChange = saved_nChange;
  126691. db->nTotalChange = saved_nTotalChange;
  126692. db->mTrace = saved_mTrace;
  126693. sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
  126694. /* Currently there is an SQL level transaction open on the vacuum
  126695. ** database. No locks are held on any other files (since the main file
  126696. ** was committed at the btree level). So it safe to end the transaction
  126697. ** by manually setting the autoCommit flag to true and detaching the
  126698. ** vacuum database. The vacuum_db journal file is deleted when the pager
  126699. ** is closed by the DETACH.
  126700. */
  126701. db->autoCommit = 1;
  126702. if( pDb ){
  126703. sqlite3BtreeClose(pDb->pBt);
  126704. pDb->pBt = 0;
  126705. pDb->pSchema = 0;
  126706. }
  126707. /* This both clears the schemas and reduces the size of the db->aDb[]
  126708. ** array. */
  126709. sqlite3ResetAllSchemasOfConnection(db);
  126710. return rc;
  126711. }
  126712. #endif /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
  126713. /************** End of vacuum.c **********************************************/
  126714. /************** Begin file vtab.c ********************************************/
  126715. /*
  126716. ** 2006 June 10
  126717. **
  126718. ** The author disclaims copyright to this source code. In place of
  126719. ** a legal notice, here is a blessing:
  126720. **
  126721. ** May you do good and not evil.
  126722. ** May you find forgiveness for yourself and forgive others.
  126723. ** May you share freely, never taking more than you give.
  126724. **
  126725. *************************************************************************
  126726. ** This file contains code used to help implement virtual tables.
  126727. */
  126728. #ifndef SQLITE_OMIT_VIRTUALTABLE
  126729. /* #include "sqliteInt.h" */
  126730. /*
  126731. ** Before a virtual table xCreate() or xConnect() method is invoked, the
  126732. ** sqlite3.pVtabCtx member variable is set to point to an instance of
  126733. ** this struct allocated on the stack. It is used by the implementation of
  126734. ** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
  126735. ** are invoked only from within xCreate and xConnect methods.
  126736. */
  126737. struct VtabCtx {
  126738. VTable *pVTable; /* The virtual table being constructed */
  126739. Table *pTab; /* The Table object to which the virtual table belongs */
  126740. VtabCtx *pPrior; /* Parent context (if any) */
  126741. int bDeclared; /* True after sqlite3_declare_vtab() is called */
  126742. };
  126743. /*
  126744. ** Construct and install a Module object for a virtual table. When this
  126745. ** routine is called, it is guaranteed that all appropriate locks are held
  126746. ** and the module is not already part of the connection.
  126747. */
  126748. SQLITE_PRIVATE Module *sqlite3VtabCreateModule(
  126749. sqlite3 *db, /* Database in which module is registered */
  126750. const char *zName, /* Name assigned to this module */
  126751. const sqlite3_module *pModule, /* The definition of the module */
  126752. void *pAux, /* Context pointer for xCreate/xConnect */
  126753. void (*xDestroy)(void *) /* Module destructor function */
  126754. ){
  126755. Module *pMod;
  126756. int nName = sqlite3Strlen30(zName);
  126757. pMod = (Module *)sqlite3Malloc(sizeof(Module) + nName + 1);
  126758. if( pMod==0 ){
  126759. sqlite3OomFault(db);
  126760. }else{
  126761. Module *pDel;
  126762. char *zCopy = (char *)(&pMod[1]);
  126763. memcpy(zCopy, zName, nName+1);
  126764. pMod->zName = zCopy;
  126765. pMod->pModule = pModule;
  126766. pMod->pAux = pAux;
  126767. pMod->xDestroy = xDestroy;
  126768. pMod->pEpoTab = 0;
  126769. pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,(void*)pMod);
  126770. assert( pDel==0 || pDel==pMod );
  126771. if( pDel ){
  126772. sqlite3OomFault(db);
  126773. sqlite3DbFree(db, pDel);
  126774. pMod = 0;
  126775. }
  126776. }
  126777. return pMod;
  126778. }
  126779. /*
  126780. ** The actual function that does the work of creating a new module.
  126781. ** This function implements the sqlite3_create_module() and
  126782. ** sqlite3_create_module_v2() interfaces.
  126783. */
  126784. static int createModule(
  126785. sqlite3 *db, /* Database in which module is registered */
  126786. const char *zName, /* Name assigned to this module */
  126787. const sqlite3_module *pModule, /* The definition of the module */
  126788. void *pAux, /* Context pointer for xCreate/xConnect */
  126789. void (*xDestroy)(void *) /* Module destructor function */
  126790. ){
  126791. int rc = SQLITE_OK;
  126792. sqlite3_mutex_enter(db->mutex);
  126793. if( sqlite3HashFind(&db->aModule, zName) ){
  126794. rc = SQLITE_MISUSE_BKPT;
  126795. }else{
  126796. (void)sqlite3VtabCreateModule(db, zName, pModule, pAux, xDestroy);
  126797. }
  126798. rc = sqlite3ApiExit(db, rc);
  126799. if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux);
  126800. sqlite3_mutex_leave(db->mutex);
  126801. return rc;
  126802. }
  126803. /*
  126804. ** External API function used to create a new virtual-table module.
  126805. */
  126806. SQLITE_API int sqlite3_create_module(
  126807. sqlite3 *db, /* Database in which module is registered */
  126808. const char *zName, /* Name assigned to this module */
  126809. const sqlite3_module *pModule, /* The definition of the module */
  126810. void *pAux /* Context pointer for xCreate/xConnect */
  126811. ){
  126812. #ifdef SQLITE_ENABLE_API_ARMOR
  126813. if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
  126814. #endif
  126815. return createModule(db, zName, pModule, pAux, 0);
  126816. }
  126817. /*
  126818. ** External API function used to create a new virtual-table module.
  126819. */
  126820. SQLITE_API int sqlite3_create_module_v2(
  126821. sqlite3 *db, /* Database in which module is registered */
  126822. const char *zName, /* Name assigned to this module */
  126823. const sqlite3_module *pModule, /* The definition of the module */
  126824. void *pAux, /* Context pointer for xCreate/xConnect */
  126825. void (*xDestroy)(void *) /* Module destructor function */
  126826. ){
  126827. #ifdef SQLITE_ENABLE_API_ARMOR
  126828. if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
  126829. #endif
  126830. return createModule(db, zName, pModule, pAux, xDestroy);
  126831. }
  126832. /*
  126833. ** Lock the virtual table so that it cannot be disconnected.
  126834. ** Locks nest. Every lock should have a corresponding unlock.
  126835. ** If an unlock is omitted, resources leaks will occur.
  126836. **
  126837. ** If a disconnect is attempted while a virtual table is locked,
  126838. ** the disconnect is deferred until all locks have been removed.
  126839. */
  126840. SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
  126841. pVTab->nRef++;
  126842. }
  126843. /*
  126844. ** pTab is a pointer to a Table structure representing a virtual-table.
  126845. ** Return a pointer to the VTable object used by connection db to access
  126846. ** this virtual-table, if one has been created, or NULL otherwise.
  126847. */
  126848. SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
  126849. VTable *pVtab;
  126850. assert( IsVirtual(pTab) );
  126851. for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
  126852. return pVtab;
  126853. }
  126854. /*
  126855. ** Decrement the ref-count on a virtual table object. When the ref-count
  126856. ** reaches zero, call the xDisconnect() method to delete the object.
  126857. */
  126858. SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
  126859. sqlite3 *db = pVTab->db;
  126860. assert( db );
  126861. assert( pVTab->nRef>0 );
  126862. assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE );
  126863. pVTab->nRef--;
  126864. if( pVTab->nRef==0 ){
  126865. sqlite3_vtab *p = pVTab->pVtab;
  126866. if( p ){
  126867. p->pModule->xDisconnect(p);
  126868. }
  126869. sqlite3DbFree(db, pVTab);
  126870. }
  126871. }
  126872. /*
  126873. ** Table p is a virtual table. This function moves all elements in the
  126874. ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
  126875. ** database connections to be disconnected at the next opportunity.
  126876. ** Except, if argument db is not NULL, then the entry associated with
  126877. ** connection db is left in the p->pVTable list.
  126878. */
  126879. static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
  126880. VTable *pRet = 0;
  126881. VTable *pVTable = p->pVTable;
  126882. p->pVTable = 0;
  126883. /* Assert that the mutex (if any) associated with the BtShared database
  126884. ** that contains table p is held by the caller. See header comments
  126885. ** above function sqlite3VtabUnlockList() for an explanation of why
  126886. ** this makes it safe to access the sqlite3.pDisconnect list of any
  126887. ** database connection that may have an entry in the p->pVTable list.
  126888. */
  126889. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
  126890. while( pVTable ){
  126891. sqlite3 *db2 = pVTable->db;
  126892. VTable *pNext = pVTable->pNext;
  126893. assert( db2 );
  126894. if( db2==db ){
  126895. pRet = pVTable;
  126896. p->pVTable = pRet;
  126897. pRet->pNext = 0;
  126898. }else{
  126899. pVTable->pNext = db2->pDisconnect;
  126900. db2->pDisconnect = pVTable;
  126901. }
  126902. pVTable = pNext;
  126903. }
  126904. assert( !db || pRet );
  126905. return pRet;
  126906. }
  126907. /*
  126908. ** Table *p is a virtual table. This function removes the VTable object
  126909. ** for table *p associated with database connection db from the linked
  126910. ** list in p->pVTab. It also decrements the VTable ref count. This is
  126911. ** used when closing database connection db to free all of its VTable
  126912. ** objects without disturbing the rest of the Schema object (which may
  126913. ** be being used by other shared-cache connections).
  126914. */
  126915. SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){
  126916. VTable **ppVTab;
  126917. assert( IsVirtual(p) );
  126918. assert( sqlite3BtreeHoldsAllMutexes(db) );
  126919. assert( sqlite3_mutex_held(db->mutex) );
  126920. for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){
  126921. if( (*ppVTab)->db==db ){
  126922. VTable *pVTab = *ppVTab;
  126923. *ppVTab = pVTab->pNext;
  126924. sqlite3VtabUnlock(pVTab);
  126925. break;
  126926. }
  126927. }
  126928. }
  126929. /*
  126930. ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
  126931. **
  126932. ** This function may only be called when the mutexes associated with all
  126933. ** shared b-tree databases opened using connection db are held by the
  126934. ** caller. This is done to protect the sqlite3.pDisconnect list. The
  126935. ** sqlite3.pDisconnect list is accessed only as follows:
  126936. **
  126937. ** 1) By this function. In this case, all BtShared mutexes and the mutex
  126938. ** associated with the database handle itself must be held.
  126939. **
  126940. ** 2) By function vtabDisconnectAll(), when it adds a VTable entry to
  126941. ** the sqlite3.pDisconnect list. In this case either the BtShared mutex
  126942. ** associated with the database the virtual table is stored in is held
  126943. ** or, if the virtual table is stored in a non-sharable database, then
  126944. ** the database handle mutex is held.
  126945. **
  126946. ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
  126947. ** by multiple threads. It is thread-safe.
  126948. */
  126949. SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
  126950. VTable *p = db->pDisconnect;
  126951. db->pDisconnect = 0;
  126952. assert( sqlite3BtreeHoldsAllMutexes(db) );
  126953. assert( sqlite3_mutex_held(db->mutex) );
  126954. if( p ){
  126955. sqlite3ExpirePreparedStatements(db, 0);
  126956. do {
  126957. VTable *pNext = p->pNext;
  126958. sqlite3VtabUnlock(p);
  126959. p = pNext;
  126960. }while( p );
  126961. }
  126962. }
  126963. /*
  126964. ** Clear any and all virtual-table information from the Table record.
  126965. ** This routine is called, for example, just before deleting the Table
  126966. ** record.
  126967. **
  126968. ** Since it is a virtual-table, the Table structure contains a pointer
  126969. ** to the head of a linked list of VTable structures. Each VTable
  126970. ** structure is associated with a single sqlite3* user of the schema.
  126971. ** The reference count of the VTable structure associated with database
  126972. ** connection db is decremented immediately (which may lead to the
  126973. ** structure being xDisconnected and free). Any other VTable structures
  126974. ** in the list are moved to the sqlite3.pDisconnect list of the associated
  126975. ** database connection.
  126976. */
  126977. SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
  126978. if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
  126979. if( p->azModuleArg ){
  126980. int i;
  126981. for(i=0; i<p->nModuleArg; i++){
  126982. if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]);
  126983. }
  126984. sqlite3DbFree(db, p->azModuleArg);
  126985. }
  126986. }
  126987. /*
  126988. ** Add a new module argument to pTable->azModuleArg[].
  126989. ** The string is not copied - the pointer is stored. The
  126990. ** string will be freed automatically when the table is
  126991. ** deleted.
  126992. */
  126993. static void addModuleArgument(Parse *pParse, Table *pTable, char *zArg){
  126994. sqlite3_int64 nBytes = sizeof(char *)*(2+pTable->nModuleArg);
  126995. char **azModuleArg;
  126996. sqlite3 *db = pParse->db;
  126997. if( pTable->nModuleArg+3>=db->aLimit[SQLITE_LIMIT_COLUMN] ){
  126998. sqlite3ErrorMsg(pParse, "too many columns on %s", pTable->zName);
  126999. }
  127000. azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
  127001. if( azModuleArg==0 ){
  127002. sqlite3DbFree(db, zArg);
  127003. }else{
  127004. int i = pTable->nModuleArg++;
  127005. azModuleArg[i] = zArg;
  127006. azModuleArg[i+1] = 0;
  127007. pTable->azModuleArg = azModuleArg;
  127008. }
  127009. }
  127010. /*
  127011. ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
  127012. ** statement. The module name has been parsed, but the optional list
  127013. ** of parameters that follow the module name are still pending.
  127014. */
  127015. SQLITE_PRIVATE void sqlite3VtabBeginParse(
  127016. Parse *pParse, /* Parsing context */
  127017. Token *pName1, /* Name of new table, or database name */
  127018. Token *pName2, /* Name of new table or NULL */
  127019. Token *pModuleName, /* Name of the module for the virtual table */
  127020. int ifNotExists /* No error if the table already exists */
  127021. ){
  127022. Table *pTable; /* The new virtual table */
  127023. sqlite3 *db; /* Database connection */
  127024. sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
  127025. pTable = pParse->pNewTable;
  127026. if( pTable==0 ) return;
  127027. assert( 0==pTable->pIndex );
  127028. db = pParse->db;
  127029. assert( pTable->nModuleArg==0 );
  127030. addModuleArgument(pParse, pTable, sqlite3NameFromToken(db, pModuleName));
  127031. addModuleArgument(pParse, pTable, 0);
  127032. addModuleArgument(pParse, pTable, sqlite3DbStrDup(db, pTable->zName));
  127033. assert( (pParse->sNameToken.z==pName2->z && pName2->z!=0)
  127034. || (pParse->sNameToken.z==pName1->z && pName2->z==0)
  127035. );
  127036. pParse->sNameToken.n = (int)(
  127037. &pModuleName->z[pModuleName->n] - pParse->sNameToken.z
  127038. );
  127039. #ifndef SQLITE_OMIT_AUTHORIZATION
  127040. /* Creating a virtual table invokes the authorization callback twice.
  127041. ** The first invocation, to obtain permission to INSERT a row into the
  127042. ** sqlite_master table, has already been made by sqlite3StartTable().
  127043. ** The second call, to obtain permission to create the table, is made now.
  127044. */
  127045. if( pTable->azModuleArg ){
  127046. int iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
  127047. assert( iDb>=0 ); /* The database the table is being created in */
  127048. sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
  127049. pTable->azModuleArg[0], pParse->db->aDb[iDb].zDbSName);
  127050. }
  127051. #endif
  127052. }
  127053. /*
  127054. ** This routine takes the module argument that has been accumulating
  127055. ** in pParse->zArg[] and appends it to the list of arguments on the
  127056. ** virtual table currently under construction in pParse->pTable.
  127057. */
  127058. static void addArgumentToVtab(Parse *pParse){
  127059. if( pParse->sArg.z && pParse->pNewTable ){
  127060. const char *z = (const char*)pParse->sArg.z;
  127061. int n = pParse->sArg.n;
  127062. sqlite3 *db = pParse->db;
  127063. addModuleArgument(pParse, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
  127064. }
  127065. }
  127066. /*
  127067. ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
  127068. ** has been completely parsed.
  127069. */
  127070. SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
  127071. Table *pTab = pParse->pNewTable; /* The table being constructed */
  127072. sqlite3 *db = pParse->db; /* The database connection */
  127073. if( pTab==0 ) return;
  127074. addArgumentToVtab(pParse);
  127075. pParse->sArg.z = 0;
  127076. if( pTab->nModuleArg<1 ) return;
  127077. /* If the CREATE VIRTUAL TABLE statement is being entered for the
  127078. ** first time (in other words if the virtual table is actually being
  127079. ** created now instead of just being read out of sqlite_master) then
  127080. ** do additional initialization work and store the statement text
  127081. ** in the sqlite_master table.
  127082. */
  127083. if( !db->init.busy ){
  127084. char *zStmt;
  127085. char *zWhere;
  127086. int iDb;
  127087. int iReg;
  127088. Vdbe *v;
  127089. /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
  127090. if( pEnd ){
  127091. pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
  127092. }
  127093. zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
  127094. /* A slot for the record has already been allocated in the
  127095. ** SQLITE_MASTER table. We just need to update that slot with all
  127096. ** the information we've collected.
  127097. **
  127098. ** The VM register number pParse->regRowid holds the rowid of an
  127099. ** entry in the sqlite_master table tht was created for this vtab
  127100. ** by sqlite3StartTable().
  127101. */
  127102. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  127103. sqlite3NestedParse(pParse,
  127104. "UPDATE %Q.%s "
  127105. "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
  127106. "WHERE rowid=#%d",
  127107. db->aDb[iDb].zDbSName, MASTER_NAME,
  127108. pTab->zName,
  127109. pTab->zName,
  127110. zStmt,
  127111. pParse->regRowid
  127112. );
  127113. sqlite3DbFree(db, zStmt);
  127114. v = sqlite3GetVdbe(pParse);
  127115. sqlite3ChangeCookie(pParse, iDb);
  127116. sqlite3VdbeAddOp0(v, OP_Expire);
  127117. zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
  127118. sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
  127119. iReg = ++pParse->nMem;
  127120. sqlite3VdbeLoadString(v, iReg, pTab->zName);
  127121. sqlite3VdbeAddOp2(v, OP_VCreate, iDb, iReg);
  127122. }
  127123. /* If we are rereading the sqlite_master table create the in-memory
  127124. ** record of the table. The xConnect() method is not called until
  127125. ** the first time the virtual table is used in an SQL statement. This
  127126. ** allows a schema that contains virtual tables to be loaded before
  127127. ** the required virtual table implementations are registered. */
  127128. else {
  127129. Table *pOld;
  127130. Schema *pSchema = pTab->pSchema;
  127131. const char *zName = pTab->zName;
  127132. assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
  127133. pOld = sqlite3HashInsert(&pSchema->tblHash, zName, pTab);
  127134. if( pOld ){
  127135. sqlite3OomFault(db);
  127136. assert( pTab==pOld ); /* Malloc must have failed inside HashInsert() */
  127137. return;
  127138. }
  127139. pParse->pNewTable = 0;
  127140. }
  127141. }
  127142. /*
  127143. ** The parser calls this routine when it sees the first token
  127144. ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
  127145. */
  127146. SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
  127147. addArgumentToVtab(pParse);
  127148. pParse->sArg.z = 0;
  127149. pParse->sArg.n = 0;
  127150. }
  127151. /*
  127152. ** The parser calls this routine for each token after the first token
  127153. ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
  127154. */
  127155. SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
  127156. Token *pArg = &pParse->sArg;
  127157. if( pArg->z==0 ){
  127158. pArg->z = p->z;
  127159. pArg->n = p->n;
  127160. }else{
  127161. assert(pArg->z <= p->z);
  127162. pArg->n = (int)(&p->z[p->n] - pArg->z);
  127163. }
  127164. }
  127165. /*
  127166. ** Invoke a virtual table constructor (either xCreate or xConnect). The
  127167. ** pointer to the function to invoke is passed as the fourth parameter
  127168. ** to this procedure.
  127169. */
  127170. static int vtabCallConstructor(
  127171. sqlite3 *db,
  127172. Table *pTab,
  127173. Module *pMod,
  127174. int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
  127175. char **pzErr
  127176. ){
  127177. VtabCtx sCtx;
  127178. VTable *pVTable;
  127179. int rc;
  127180. const char *const*azArg = (const char *const*)pTab->azModuleArg;
  127181. int nArg = pTab->nModuleArg;
  127182. char *zErr = 0;
  127183. char *zModuleName;
  127184. int iDb;
  127185. VtabCtx *pCtx;
  127186. /* Check that the virtual-table is not already being initialized */
  127187. for(pCtx=db->pVtabCtx; pCtx; pCtx=pCtx->pPrior){
  127188. if( pCtx->pTab==pTab ){
  127189. *pzErr = sqlite3MPrintf(db,
  127190. "vtable constructor called recursively: %s", pTab->zName
  127191. );
  127192. return SQLITE_LOCKED;
  127193. }
  127194. }
  127195. zModuleName = sqlite3DbStrDup(db, pTab->zName);
  127196. if( !zModuleName ){
  127197. return SQLITE_NOMEM_BKPT;
  127198. }
  127199. pVTable = sqlite3MallocZero(sizeof(VTable));
  127200. if( !pVTable ){
  127201. sqlite3OomFault(db);
  127202. sqlite3DbFree(db, zModuleName);
  127203. return SQLITE_NOMEM_BKPT;
  127204. }
  127205. pVTable->db = db;
  127206. pVTable->pMod = pMod;
  127207. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  127208. pTab->azModuleArg[1] = db->aDb[iDb].zDbSName;
  127209. /* Invoke the virtual table constructor */
  127210. assert( &db->pVtabCtx );
  127211. assert( xConstruct );
  127212. sCtx.pTab = pTab;
  127213. sCtx.pVTable = pVTable;
  127214. sCtx.pPrior = db->pVtabCtx;
  127215. sCtx.bDeclared = 0;
  127216. db->pVtabCtx = &sCtx;
  127217. rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
  127218. db->pVtabCtx = sCtx.pPrior;
  127219. if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
  127220. assert( sCtx.pTab==pTab );
  127221. if( SQLITE_OK!=rc ){
  127222. if( zErr==0 ){
  127223. *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
  127224. }else {
  127225. *pzErr = sqlite3MPrintf(db, "%s", zErr);
  127226. sqlite3_free(zErr);
  127227. }
  127228. sqlite3DbFree(db, pVTable);
  127229. }else if( ALWAYS(pVTable->pVtab) ){
  127230. /* Justification of ALWAYS(): A correct vtab constructor must allocate
  127231. ** the sqlite3_vtab object if successful. */
  127232. memset(pVTable->pVtab, 0, sizeof(pVTable->pVtab[0]));
  127233. pVTable->pVtab->pModule = pMod->pModule;
  127234. pVTable->nRef = 1;
  127235. if( sCtx.bDeclared==0 ){
  127236. const char *zFormat = "vtable constructor did not declare schema: %s";
  127237. *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
  127238. sqlite3VtabUnlock(pVTable);
  127239. rc = SQLITE_ERROR;
  127240. }else{
  127241. int iCol;
  127242. u8 oooHidden = 0;
  127243. /* If everything went according to plan, link the new VTable structure
  127244. ** into the linked list headed by pTab->pVTable. Then loop through the
  127245. ** columns of the table to see if any of them contain the token "hidden".
  127246. ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from
  127247. ** the type string. */
  127248. pVTable->pNext = pTab->pVTable;
  127249. pTab->pVTable = pVTable;
  127250. for(iCol=0; iCol<pTab->nCol; iCol++){
  127251. char *zType = sqlite3ColumnType(&pTab->aCol[iCol], "");
  127252. int nType;
  127253. int i = 0;
  127254. nType = sqlite3Strlen30(zType);
  127255. for(i=0; i<nType; i++){
  127256. if( 0==sqlite3StrNICmp("hidden", &zType[i], 6)
  127257. && (i==0 || zType[i-1]==' ')
  127258. && (zType[i+6]=='\0' || zType[i+6]==' ')
  127259. ){
  127260. break;
  127261. }
  127262. }
  127263. if( i<nType ){
  127264. int j;
  127265. int nDel = 6 + (zType[i+6] ? 1 : 0);
  127266. for(j=i; (j+nDel)<=nType; j++){
  127267. zType[j] = zType[j+nDel];
  127268. }
  127269. if( zType[i]=='\0' && i>0 ){
  127270. assert(zType[i-1]==' ');
  127271. zType[i-1] = '\0';
  127272. }
  127273. pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN;
  127274. oooHidden = TF_OOOHidden;
  127275. }else{
  127276. pTab->tabFlags |= oooHidden;
  127277. }
  127278. }
  127279. }
  127280. }
  127281. sqlite3DbFree(db, zModuleName);
  127282. return rc;
  127283. }
  127284. /*
  127285. ** This function is invoked by the parser to call the xConnect() method
  127286. ** of the virtual table pTab. If an error occurs, an error code is returned
  127287. ** and an error left in pParse.
  127288. **
  127289. ** This call is a no-op if table pTab is not a virtual table.
  127290. */
  127291. SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
  127292. sqlite3 *db = pParse->db;
  127293. const char *zMod;
  127294. Module *pMod;
  127295. int rc;
  127296. assert( pTab );
  127297. if( !IsVirtual(pTab) || sqlite3GetVTable(db, pTab) ){
  127298. return SQLITE_OK;
  127299. }
  127300. /* Locate the required virtual table module */
  127301. zMod = pTab->azModuleArg[0];
  127302. pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
  127303. if( !pMod ){
  127304. const char *zModule = pTab->azModuleArg[0];
  127305. sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
  127306. rc = SQLITE_ERROR;
  127307. }else{
  127308. char *zErr = 0;
  127309. rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
  127310. if( rc!=SQLITE_OK ){
  127311. sqlite3ErrorMsg(pParse, "%s", zErr);
  127312. pParse->rc = rc;
  127313. }
  127314. sqlite3DbFree(db, zErr);
  127315. }
  127316. return rc;
  127317. }
  127318. /*
  127319. ** Grow the db->aVTrans[] array so that there is room for at least one
  127320. ** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
  127321. */
  127322. static int growVTrans(sqlite3 *db){
  127323. const int ARRAY_INCR = 5;
  127324. /* Grow the sqlite3.aVTrans array if required */
  127325. if( (db->nVTrans%ARRAY_INCR)==0 ){
  127326. VTable **aVTrans;
  127327. sqlite3_int64 nBytes = sizeof(sqlite3_vtab*)*
  127328. ((sqlite3_int64)db->nVTrans + ARRAY_INCR);
  127329. aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
  127330. if( !aVTrans ){
  127331. return SQLITE_NOMEM_BKPT;
  127332. }
  127333. memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
  127334. db->aVTrans = aVTrans;
  127335. }
  127336. return SQLITE_OK;
  127337. }
  127338. /*
  127339. ** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
  127340. ** have already been reserved using growVTrans().
  127341. */
  127342. static void addToVTrans(sqlite3 *db, VTable *pVTab){
  127343. /* Add pVtab to the end of sqlite3.aVTrans */
  127344. db->aVTrans[db->nVTrans++] = pVTab;
  127345. sqlite3VtabLock(pVTab);
  127346. }
  127347. /*
  127348. ** This function is invoked by the vdbe to call the xCreate method
  127349. ** of the virtual table named zTab in database iDb.
  127350. **
  127351. ** If an error occurs, *pzErr is set to point to an English language
  127352. ** description of the error and an SQLITE_XXX error code is returned.
  127353. ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
  127354. */
  127355. SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
  127356. int rc = SQLITE_OK;
  127357. Table *pTab;
  127358. Module *pMod;
  127359. const char *zMod;
  127360. pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zDbSName);
  127361. assert( pTab && IsVirtual(pTab) && !pTab->pVTable );
  127362. /* Locate the required virtual table module */
  127363. zMod = pTab->azModuleArg[0];
  127364. pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
  127365. /* If the module has been registered and includes a Create method,
  127366. ** invoke it now. If the module has not been registered, return an
  127367. ** error. Otherwise, do nothing.
  127368. */
  127369. if( pMod==0 || pMod->pModule->xCreate==0 || pMod->pModule->xDestroy==0 ){
  127370. *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
  127371. rc = SQLITE_ERROR;
  127372. }else{
  127373. rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
  127374. }
  127375. /* Justification of ALWAYS(): The xConstructor method is required to
  127376. ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
  127377. if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
  127378. rc = growVTrans(db);
  127379. if( rc==SQLITE_OK ){
  127380. addToVTrans(db, sqlite3GetVTable(db, pTab));
  127381. }
  127382. }
  127383. return rc;
  127384. }
  127385. /*
  127386. ** This function is used to set the schema of a virtual table. It is only
  127387. ** valid to call this function from within the xCreate() or xConnect() of a
  127388. ** virtual table module.
  127389. */
  127390. SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
  127391. VtabCtx *pCtx;
  127392. int rc = SQLITE_OK;
  127393. Table *pTab;
  127394. char *zErr = 0;
  127395. Parse sParse;
  127396. #ifdef SQLITE_ENABLE_API_ARMOR
  127397. if( !sqlite3SafetyCheckOk(db) || zCreateTable==0 ){
  127398. return SQLITE_MISUSE_BKPT;
  127399. }
  127400. #endif
  127401. sqlite3_mutex_enter(db->mutex);
  127402. pCtx = db->pVtabCtx;
  127403. if( !pCtx || pCtx->bDeclared ){
  127404. sqlite3Error(db, SQLITE_MISUSE);
  127405. sqlite3_mutex_leave(db->mutex);
  127406. return SQLITE_MISUSE_BKPT;
  127407. }
  127408. pTab = pCtx->pTab;
  127409. assert( IsVirtual(pTab) );
  127410. memset(&sParse, 0, sizeof(sParse));
  127411. sParse.eParseMode = PARSE_MODE_DECLARE_VTAB;
  127412. sParse.db = db;
  127413. sParse.nQueryLoop = 1;
  127414. if( SQLITE_OK==sqlite3RunParser(&sParse, zCreateTable, &zErr)
  127415. && sParse.pNewTable
  127416. && !db->mallocFailed
  127417. && !sParse.pNewTable->pSelect
  127418. && !IsVirtual(sParse.pNewTable)
  127419. ){
  127420. if( !pTab->aCol ){
  127421. Table *pNew = sParse.pNewTable;
  127422. Index *pIdx;
  127423. pTab->aCol = pNew->aCol;
  127424. pTab->nCol = pNew->nCol;
  127425. pTab->tabFlags |= pNew->tabFlags & (TF_WithoutRowid|TF_NoVisibleRowid);
  127426. pNew->nCol = 0;
  127427. pNew->aCol = 0;
  127428. assert( pTab->pIndex==0 );
  127429. assert( HasRowid(pNew) || sqlite3PrimaryKeyIndex(pNew)!=0 );
  127430. if( !HasRowid(pNew)
  127431. && pCtx->pVTable->pMod->pModule->xUpdate!=0
  127432. && sqlite3PrimaryKeyIndex(pNew)->nKeyCol!=1
  127433. ){
  127434. /* WITHOUT ROWID virtual tables must either be read-only (xUpdate==0)
  127435. ** or else must have a single-column PRIMARY KEY */
  127436. rc = SQLITE_ERROR;
  127437. }
  127438. pIdx = pNew->pIndex;
  127439. if( pIdx ){
  127440. assert( pIdx->pNext==0 );
  127441. pTab->pIndex = pIdx;
  127442. pNew->pIndex = 0;
  127443. pIdx->pTable = pTab;
  127444. }
  127445. }
  127446. pCtx->bDeclared = 1;
  127447. }else{
  127448. sqlite3ErrorWithMsg(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
  127449. sqlite3DbFree(db, zErr);
  127450. rc = SQLITE_ERROR;
  127451. }
  127452. sParse.eParseMode = PARSE_MODE_NORMAL;
  127453. if( sParse.pVdbe ){
  127454. sqlite3VdbeFinalize(sParse.pVdbe);
  127455. }
  127456. sqlite3DeleteTable(db, sParse.pNewTable);
  127457. sqlite3ParserReset(&sParse);
  127458. assert( (rc&0xff)==rc );
  127459. rc = sqlite3ApiExit(db, rc);
  127460. sqlite3_mutex_leave(db->mutex);
  127461. return rc;
  127462. }
  127463. /*
  127464. ** This function is invoked by the vdbe to call the xDestroy method
  127465. ** of the virtual table named zTab in database iDb. This occurs
  127466. ** when a DROP TABLE is mentioned.
  127467. **
  127468. ** This call is a no-op if zTab is not a virtual table.
  127469. */
  127470. SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
  127471. int rc = SQLITE_OK;
  127472. Table *pTab;
  127473. pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zDbSName);
  127474. if( pTab!=0 && ALWAYS(pTab->pVTable!=0) ){
  127475. VTable *p;
  127476. int (*xDestroy)(sqlite3_vtab *);
  127477. for(p=pTab->pVTable; p; p=p->pNext){
  127478. assert( p->pVtab );
  127479. if( p->pVtab->nRef>0 ){
  127480. return SQLITE_LOCKED;
  127481. }
  127482. }
  127483. p = vtabDisconnectAll(db, pTab);
  127484. xDestroy = p->pMod->pModule->xDestroy;
  127485. assert( xDestroy!=0 ); /* Checked before the virtual table is created */
  127486. pTab->nTabRef++;
  127487. rc = xDestroy(p->pVtab);
  127488. /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
  127489. if( rc==SQLITE_OK ){
  127490. assert( pTab->pVTable==p && p->pNext==0 );
  127491. p->pVtab = 0;
  127492. pTab->pVTable = 0;
  127493. sqlite3VtabUnlock(p);
  127494. }
  127495. sqlite3DeleteTable(db, pTab);
  127496. }
  127497. return rc;
  127498. }
  127499. /*
  127500. ** This function invokes either the xRollback or xCommit method
  127501. ** of each of the virtual tables in the sqlite3.aVTrans array. The method
  127502. ** called is identified by the second argument, "offset", which is
  127503. ** the offset of the method to call in the sqlite3_module structure.
  127504. **
  127505. ** The array is cleared after invoking the callbacks.
  127506. */
  127507. static void callFinaliser(sqlite3 *db, int offset){
  127508. int i;
  127509. if( db->aVTrans ){
  127510. VTable **aVTrans = db->aVTrans;
  127511. db->aVTrans = 0;
  127512. for(i=0; i<db->nVTrans; i++){
  127513. VTable *pVTab = aVTrans[i];
  127514. sqlite3_vtab *p = pVTab->pVtab;
  127515. if( p ){
  127516. int (*x)(sqlite3_vtab *);
  127517. x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
  127518. if( x ) x(p);
  127519. }
  127520. pVTab->iSavepoint = 0;
  127521. sqlite3VtabUnlock(pVTab);
  127522. }
  127523. sqlite3DbFree(db, aVTrans);
  127524. db->nVTrans = 0;
  127525. }
  127526. }
  127527. /*
  127528. ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
  127529. ** array. Return the error code for the first error that occurs, or
  127530. ** SQLITE_OK if all xSync operations are successful.
  127531. **
  127532. ** If an error message is available, leave it in p->zErrMsg.
  127533. */
  127534. SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe *p){
  127535. int i;
  127536. int rc = SQLITE_OK;
  127537. VTable **aVTrans = db->aVTrans;
  127538. db->aVTrans = 0;
  127539. for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
  127540. int (*x)(sqlite3_vtab *);
  127541. sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
  127542. if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
  127543. rc = x(pVtab);
  127544. sqlite3VtabImportErrmsg(p, pVtab);
  127545. }
  127546. }
  127547. db->aVTrans = aVTrans;
  127548. return rc;
  127549. }
  127550. /*
  127551. ** Invoke the xRollback method of all virtual tables in the
  127552. ** sqlite3.aVTrans array. Then clear the array itself.
  127553. */
  127554. SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
  127555. callFinaliser(db, offsetof(sqlite3_module,xRollback));
  127556. return SQLITE_OK;
  127557. }
  127558. /*
  127559. ** Invoke the xCommit method of all virtual tables in the
  127560. ** sqlite3.aVTrans array. Then clear the array itself.
  127561. */
  127562. SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
  127563. callFinaliser(db, offsetof(sqlite3_module,xCommit));
  127564. return SQLITE_OK;
  127565. }
  127566. /*
  127567. ** If the virtual table pVtab supports the transaction interface
  127568. ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
  127569. ** not currently open, invoke the xBegin method now.
  127570. **
  127571. ** If the xBegin call is successful, place the sqlite3_vtab pointer
  127572. ** in the sqlite3.aVTrans array.
  127573. */
  127574. SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
  127575. int rc = SQLITE_OK;
  127576. const sqlite3_module *pModule;
  127577. /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
  127578. ** than zero, then this function is being called from within a
  127579. ** virtual module xSync() callback. It is illegal to write to
  127580. ** virtual module tables in this case, so return SQLITE_LOCKED.
  127581. */
  127582. if( sqlite3VtabInSync(db) ){
  127583. return SQLITE_LOCKED;
  127584. }
  127585. if( !pVTab ){
  127586. return SQLITE_OK;
  127587. }
  127588. pModule = pVTab->pVtab->pModule;
  127589. if( pModule->xBegin ){
  127590. int i;
  127591. /* If pVtab is already in the aVTrans array, return early */
  127592. for(i=0; i<db->nVTrans; i++){
  127593. if( db->aVTrans[i]==pVTab ){
  127594. return SQLITE_OK;
  127595. }
  127596. }
  127597. /* Invoke the xBegin method. If successful, add the vtab to the
  127598. ** sqlite3.aVTrans[] array. */
  127599. rc = growVTrans(db);
  127600. if( rc==SQLITE_OK ){
  127601. rc = pModule->xBegin(pVTab->pVtab);
  127602. if( rc==SQLITE_OK ){
  127603. int iSvpt = db->nStatement + db->nSavepoint;
  127604. addToVTrans(db, pVTab);
  127605. if( iSvpt && pModule->xSavepoint ){
  127606. pVTab->iSavepoint = iSvpt;
  127607. rc = pModule->xSavepoint(pVTab->pVtab, iSvpt-1);
  127608. }
  127609. }
  127610. }
  127611. }
  127612. return rc;
  127613. }
  127614. /*
  127615. ** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
  127616. ** virtual tables that currently have an open transaction. Pass iSavepoint
  127617. ** as the second argument to the virtual table method invoked.
  127618. **
  127619. ** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
  127620. ** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is
  127621. ** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
  127622. ** an open transaction is invoked.
  127623. **
  127624. ** If any virtual table method returns an error code other than SQLITE_OK,
  127625. ** processing is abandoned and the error returned to the caller of this
  127626. ** function immediately. If all calls to virtual table methods are successful,
  127627. ** SQLITE_OK is returned.
  127628. */
  127629. SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
  127630. int rc = SQLITE_OK;
  127631. assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
  127632. assert( iSavepoint>=-1 );
  127633. if( db->aVTrans ){
  127634. int i;
  127635. for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
  127636. VTable *pVTab = db->aVTrans[i];
  127637. const sqlite3_module *pMod = pVTab->pMod->pModule;
  127638. if( pVTab->pVtab && pMod->iVersion>=2 ){
  127639. int (*xMethod)(sqlite3_vtab *, int);
  127640. sqlite3VtabLock(pVTab);
  127641. switch( op ){
  127642. case SAVEPOINT_BEGIN:
  127643. xMethod = pMod->xSavepoint;
  127644. pVTab->iSavepoint = iSavepoint+1;
  127645. break;
  127646. case SAVEPOINT_ROLLBACK:
  127647. xMethod = pMod->xRollbackTo;
  127648. break;
  127649. default:
  127650. xMethod = pMod->xRelease;
  127651. break;
  127652. }
  127653. if( xMethod && pVTab->iSavepoint>iSavepoint ){
  127654. rc = xMethod(pVTab->pVtab, iSavepoint);
  127655. }
  127656. sqlite3VtabUnlock(pVTab);
  127657. }
  127658. }
  127659. }
  127660. return rc;
  127661. }
  127662. /*
  127663. ** The first parameter (pDef) is a function implementation. The
  127664. ** second parameter (pExpr) is the first argument to this function.
  127665. ** If pExpr is a column in a virtual table, then let the virtual
  127666. ** table implementation have an opportunity to overload the function.
  127667. **
  127668. ** This routine is used to allow virtual table implementations to
  127669. ** overload MATCH, LIKE, GLOB, and REGEXP operators.
  127670. **
  127671. ** Return either the pDef argument (indicating no change) or a
  127672. ** new FuncDef structure that is marked as ephemeral using the
  127673. ** SQLITE_FUNC_EPHEM flag.
  127674. */
  127675. SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
  127676. sqlite3 *db, /* Database connection for reporting malloc problems */
  127677. FuncDef *pDef, /* Function to possibly overload */
  127678. int nArg, /* Number of arguments to the function */
  127679. Expr *pExpr /* First argument to the function */
  127680. ){
  127681. Table *pTab;
  127682. sqlite3_vtab *pVtab;
  127683. sqlite3_module *pMod;
  127684. void (*xSFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
  127685. void *pArg = 0;
  127686. FuncDef *pNew;
  127687. int rc = 0;
  127688. /* Check to see the left operand is a column in a virtual table */
  127689. if( NEVER(pExpr==0) ) return pDef;
  127690. if( pExpr->op!=TK_COLUMN ) return pDef;
  127691. pTab = pExpr->y.pTab;
  127692. if( pTab==0 ) return pDef;
  127693. if( !IsVirtual(pTab) ) return pDef;
  127694. pVtab = sqlite3GetVTable(db, pTab)->pVtab;
  127695. assert( pVtab!=0 );
  127696. assert( pVtab->pModule!=0 );
  127697. pMod = (sqlite3_module *)pVtab->pModule;
  127698. if( pMod->xFindFunction==0 ) return pDef;
  127699. /* Call the xFindFunction method on the virtual table implementation
  127700. ** to see if the implementation wants to overload this function.
  127701. **
  127702. ** Though undocumented, we have historically always invoked xFindFunction
  127703. ** with an all lower-case function name. Continue in this tradition to
  127704. ** avoid any chance of an incompatibility.
  127705. */
  127706. #ifdef SQLITE_DEBUG
  127707. {
  127708. int i;
  127709. for(i=0; pDef->zName[i]; i++){
  127710. unsigned char x = (unsigned char)pDef->zName[i];
  127711. assert( x==sqlite3UpperToLower[x] );
  127712. }
  127713. }
  127714. #endif
  127715. rc = pMod->xFindFunction(pVtab, nArg, pDef->zName, &xSFunc, &pArg);
  127716. if( rc==0 ){
  127717. return pDef;
  127718. }
  127719. /* Create a new ephemeral function definition for the overloaded
  127720. ** function */
  127721. pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
  127722. + sqlite3Strlen30(pDef->zName) + 1);
  127723. if( pNew==0 ){
  127724. return pDef;
  127725. }
  127726. *pNew = *pDef;
  127727. pNew->zName = (const char*)&pNew[1];
  127728. memcpy((char*)&pNew[1], pDef->zName, sqlite3Strlen30(pDef->zName)+1);
  127729. pNew->xSFunc = xSFunc;
  127730. pNew->pUserData = pArg;
  127731. pNew->funcFlags |= SQLITE_FUNC_EPHEM;
  127732. return pNew;
  127733. }
  127734. /*
  127735. ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
  127736. ** array so that an OP_VBegin will get generated for it. Add pTab to the
  127737. ** array if it is missing. If pTab is already in the array, this routine
  127738. ** is a no-op.
  127739. */
  127740. SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
  127741. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  127742. int i, n;
  127743. Table **apVtabLock;
  127744. assert( IsVirtual(pTab) );
  127745. for(i=0; i<pToplevel->nVtabLock; i++){
  127746. if( pTab==pToplevel->apVtabLock[i] ) return;
  127747. }
  127748. n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
  127749. apVtabLock = sqlite3_realloc64(pToplevel->apVtabLock, n);
  127750. if( apVtabLock ){
  127751. pToplevel->apVtabLock = apVtabLock;
  127752. pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
  127753. }else{
  127754. sqlite3OomFault(pToplevel->db);
  127755. }
  127756. }
  127757. /*
  127758. ** Check to see if virtual table module pMod can be have an eponymous
  127759. ** virtual table instance. If it can, create one if one does not already
  127760. ** exist. Return non-zero if the eponymous virtual table instance exists
  127761. ** when this routine returns, and return zero if it does not exist.
  127762. **
  127763. ** An eponymous virtual table instance is one that is named after its
  127764. ** module, and more importantly, does not require a CREATE VIRTUAL TABLE
  127765. ** statement in order to come into existance. Eponymous virtual table
  127766. ** instances always exist. They cannot be DROP-ed.
  127767. **
  127768. ** Any virtual table module for which xConnect and xCreate are the same
  127769. ** method can have an eponymous virtual table instance.
  127770. */
  127771. SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse *pParse, Module *pMod){
  127772. const sqlite3_module *pModule = pMod->pModule;
  127773. Table *pTab;
  127774. char *zErr = 0;
  127775. int rc;
  127776. sqlite3 *db = pParse->db;
  127777. if( pMod->pEpoTab ) return 1;
  127778. if( pModule->xCreate!=0 && pModule->xCreate!=pModule->xConnect ) return 0;
  127779. pTab = sqlite3DbMallocZero(db, sizeof(Table));
  127780. if( pTab==0 ) return 0;
  127781. pTab->zName = sqlite3DbStrDup(db, pMod->zName);
  127782. if( pTab->zName==0 ){
  127783. sqlite3DbFree(db, pTab);
  127784. return 0;
  127785. }
  127786. pMod->pEpoTab = pTab;
  127787. pTab->nTabRef = 1;
  127788. pTab->pSchema = db->aDb[0].pSchema;
  127789. assert( pTab->nModuleArg==0 );
  127790. pTab->iPKey = -1;
  127791. addModuleArgument(pParse, pTab, sqlite3DbStrDup(db, pTab->zName));
  127792. addModuleArgument(pParse, pTab, 0);
  127793. addModuleArgument(pParse, pTab, sqlite3DbStrDup(db, pTab->zName));
  127794. rc = vtabCallConstructor(db, pTab, pMod, pModule->xConnect, &zErr);
  127795. if( rc ){
  127796. sqlite3ErrorMsg(pParse, "%s", zErr);
  127797. sqlite3DbFree(db, zErr);
  127798. sqlite3VtabEponymousTableClear(db, pMod);
  127799. return 0;
  127800. }
  127801. return 1;
  127802. }
  127803. /*
  127804. ** Erase the eponymous virtual table instance associated with
  127805. ** virtual table module pMod, if it exists.
  127806. */
  127807. SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3 *db, Module *pMod){
  127808. Table *pTab = pMod->pEpoTab;
  127809. if( pTab!=0 ){
  127810. /* Mark the table as Ephemeral prior to deleting it, so that the
  127811. ** sqlite3DeleteTable() routine will know that it is not stored in
  127812. ** the schema. */
  127813. pTab->tabFlags |= TF_Ephemeral;
  127814. sqlite3DeleteTable(db, pTab);
  127815. pMod->pEpoTab = 0;
  127816. }
  127817. }
  127818. /*
  127819. ** Return the ON CONFLICT resolution mode in effect for the virtual
  127820. ** table update operation currently in progress.
  127821. **
  127822. ** The results of this routine are undefined unless it is called from
  127823. ** within an xUpdate method.
  127824. */
  127825. SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *db){
  127826. static const unsigned char aMap[] = {
  127827. SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE
  127828. };
  127829. #ifdef SQLITE_ENABLE_API_ARMOR
  127830. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  127831. #endif
  127832. assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
  127833. assert( OE_Ignore==4 && OE_Replace==5 );
  127834. assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
  127835. return (int)aMap[db->vtabOnConflict-1];
  127836. }
  127837. /*
  127838. ** Call from within the xCreate() or xConnect() methods to provide
  127839. ** the SQLite core with additional information about the behavior
  127840. ** of the virtual table being implemented.
  127841. */
  127842. SQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){
  127843. va_list ap;
  127844. int rc = SQLITE_OK;
  127845. #ifdef SQLITE_ENABLE_API_ARMOR
  127846. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  127847. #endif
  127848. sqlite3_mutex_enter(db->mutex);
  127849. va_start(ap, op);
  127850. switch( op ){
  127851. case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
  127852. VtabCtx *p = db->pVtabCtx;
  127853. if( !p ){
  127854. rc = SQLITE_MISUSE_BKPT;
  127855. }else{
  127856. assert( p->pTab==0 || IsVirtual(p->pTab) );
  127857. p->pVTable->bConstraint = (u8)va_arg(ap, int);
  127858. }
  127859. break;
  127860. }
  127861. default:
  127862. rc = SQLITE_MISUSE_BKPT;
  127863. break;
  127864. }
  127865. va_end(ap);
  127866. if( rc!=SQLITE_OK ) sqlite3Error(db, rc);
  127867. sqlite3_mutex_leave(db->mutex);
  127868. return rc;
  127869. }
  127870. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  127871. /************** End of vtab.c ************************************************/
  127872. /************** Begin file wherecode.c ***************************************/
  127873. /*
  127874. ** 2015-06-06
  127875. **
  127876. ** The author disclaims copyright to this source code. In place of
  127877. ** a legal notice, here is a blessing:
  127878. **
  127879. ** May you do good and not evil.
  127880. ** May you find forgiveness for yourself and forgive others.
  127881. ** May you share freely, never taking more than you give.
  127882. **
  127883. *************************************************************************
  127884. ** This module contains C code that generates VDBE code used to process
  127885. ** the WHERE clause of SQL statements.
  127886. **
  127887. ** This file was split off from where.c on 2015-06-06 in order to reduce the
  127888. ** size of where.c and make it easier to edit. This file contains the routines
  127889. ** that actually generate the bulk of the WHERE loop code. The original where.c
  127890. ** file retains the code that does query planning and analysis.
  127891. */
  127892. /* #include "sqliteInt.h" */
  127893. /************** Include whereInt.h in the middle of wherecode.c **************/
  127894. /************** Begin file whereInt.h ****************************************/
  127895. /*
  127896. ** 2013-11-12
  127897. **
  127898. ** The author disclaims copyright to this source code. In place of
  127899. ** a legal notice, here is a blessing:
  127900. **
  127901. ** May you do good and not evil.
  127902. ** May you find forgiveness for yourself and forgive others.
  127903. ** May you share freely, never taking more than you give.
  127904. **
  127905. *************************************************************************
  127906. **
  127907. ** This file contains structure and macro definitions for the query
  127908. ** planner logic in "where.c". These definitions are broken out into
  127909. ** a separate source file for easier editing.
  127910. */
  127911. #ifndef SQLITE_WHEREINT_H
  127912. #define SQLITE_WHEREINT_H
  127913. /*
  127914. ** Trace output macros
  127915. */
  127916. #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
  127917. /***/ extern int sqlite3WhereTrace;
  127918. #endif
  127919. #if defined(SQLITE_DEBUG) \
  127920. && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
  127921. # define WHERETRACE(K,X) if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
  127922. # define WHERETRACE_ENABLED 1
  127923. #else
  127924. # define WHERETRACE(K,X)
  127925. #endif
  127926. /* Forward references
  127927. */
  127928. typedef struct WhereClause WhereClause;
  127929. typedef struct WhereMaskSet WhereMaskSet;
  127930. typedef struct WhereOrInfo WhereOrInfo;
  127931. typedef struct WhereAndInfo WhereAndInfo;
  127932. typedef struct WhereLevel WhereLevel;
  127933. typedef struct WhereLoop WhereLoop;
  127934. typedef struct WherePath WherePath;
  127935. typedef struct WhereTerm WhereTerm;
  127936. typedef struct WhereLoopBuilder WhereLoopBuilder;
  127937. typedef struct WhereScan WhereScan;
  127938. typedef struct WhereOrCost WhereOrCost;
  127939. typedef struct WhereOrSet WhereOrSet;
  127940. /*
  127941. ** This object contains information needed to implement a single nested
  127942. ** loop in WHERE clause.
  127943. **
  127944. ** Contrast this object with WhereLoop. This object describes the
  127945. ** implementation of the loop. WhereLoop describes the algorithm.
  127946. ** This object contains a pointer to the WhereLoop algorithm as one of
  127947. ** its elements.
  127948. **
  127949. ** The WhereInfo object contains a single instance of this object for
  127950. ** each term in the FROM clause (which is to say, for each of the
  127951. ** nested loops as implemented). The order of WhereLevel objects determines
  127952. ** the loop nested order, with WhereInfo.a[0] being the outer loop and
  127953. ** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop.
  127954. */
  127955. struct WhereLevel {
  127956. int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */
  127957. int iTabCur; /* The VDBE cursor used to access the table */
  127958. int iIdxCur; /* The VDBE cursor used to access pIdx */
  127959. int addrBrk; /* Jump here to break out of the loop */
  127960. int addrNxt; /* Jump here to start the next IN combination */
  127961. int addrSkip; /* Jump here for next iteration of skip-scan */
  127962. int addrCont; /* Jump here to continue with the next loop cycle */
  127963. int addrFirst; /* First instruction of interior of the loop */
  127964. int addrBody; /* Beginning of the body of this loop */
  127965. #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  127966. u32 iLikeRepCntr; /* LIKE range processing counter register (times 2) */
  127967. int addrLikeRep; /* LIKE range processing address */
  127968. #endif
  127969. u8 iFrom; /* Which entry in the FROM clause */
  127970. u8 op, p3, p5; /* Opcode, P3 & P5 of the opcode that ends the loop */
  127971. int p1, p2; /* Operands of the opcode used to ends the loop */
  127972. union { /* Information that depends on pWLoop->wsFlags */
  127973. struct {
  127974. int nIn; /* Number of entries in aInLoop[] */
  127975. struct InLoop {
  127976. int iCur; /* The VDBE cursor used by this IN operator */
  127977. int addrInTop; /* Top of the IN loop */
  127978. int iBase; /* Base register of multi-key index record */
  127979. int nPrefix; /* Number of prior entires in the key */
  127980. u8 eEndLoopOp; /* IN Loop terminator. OP_Next or OP_Prev */
  127981. } *aInLoop; /* Information about each nested IN operator */
  127982. } in; /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
  127983. Index *pCovidx; /* Possible covering index for WHERE_MULTI_OR */
  127984. } u;
  127985. struct WhereLoop *pWLoop; /* The selected WhereLoop object */
  127986. Bitmask notReady; /* FROM entries not usable at this level */
  127987. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  127988. int addrVisit; /* Address at which row is visited */
  127989. #endif
  127990. };
  127991. /*
  127992. ** Each instance of this object represents an algorithm for evaluating one
  127993. ** term of a join. Every term of the FROM clause will have at least
  127994. ** one corresponding WhereLoop object (unless INDEXED BY constraints
  127995. ** prevent a query solution - which is an error) and many terms of the
  127996. ** FROM clause will have multiple WhereLoop objects, each describing a
  127997. ** potential way of implementing that FROM-clause term, together with
  127998. ** dependencies and cost estimates for using the chosen algorithm.
  127999. **
  128000. ** Query planning consists of building up a collection of these WhereLoop
  128001. ** objects, then computing a particular sequence of WhereLoop objects, with
  128002. ** one WhereLoop object per FROM clause term, that satisfy all dependencies
  128003. ** and that minimize the overall cost.
  128004. */
  128005. struct WhereLoop {
  128006. Bitmask prereq; /* Bitmask of other loops that must run first */
  128007. Bitmask maskSelf; /* Bitmask identifying table iTab */
  128008. #ifdef SQLITE_DEBUG
  128009. char cId; /* Symbolic ID of this loop for debugging use */
  128010. #endif
  128011. u8 iTab; /* Position in FROM clause of table for this loop */
  128012. u8 iSortIdx; /* Sorting index number. 0==None */
  128013. LogEst rSetup; /* One-time setup cost (ex: create transient index) */
  128014. LogEst rRun; /* Cost of running each loop */
  128015. LogEst nOut; /* Estimated number of output rows */
  128016. union {
  128017. struct { /* Information for internal btree tables */
  128018. u16 nEq; /* Number of equality constraints */
  128019. u16 nBtm; /* Size of BTM vector */
  128020. u16 nTop; /* Size of TOP vector */
  128021. u16 nIdxCol; /* Index column used for ORDER BY */
  128022. Index *pIndex; /* Index used, or NULL */
  128023. } btree;
  128024. struct { /* Information for virtual tables */
  128025. int idxNum; /* Index number */
  128026. u8 needFree; /* True if sqlite3_free(idxStr) is needed */
  128027. i8 isOrdered; /* True if satisfies ORDER BY */
  128028. u16 omitMask; /* Terms that may be omitted */
  128029. char *idxStr; /* Index identifier string */
  128030. } vtab;
  128031. } u;
  128032. u32 wsFlags; /* WHERE_* flags describing the plan */
  128033. u16 nLTerm; /* Number of entries in aLTerm[] */
  128034. u16 nSkip; /* Number of NULL aLTerm[] entries */
  128035. /**** whereLoopXfer() copies fields above ***********************/
  128036. # define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot)
  128037. u16 nLSlot; /* Number of slots allocated for aLTerm[] */
  128038. WhereTerm **aLTerm; /* WhereTerms used */
  128039. WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */
  128040. WhereTerm *aLTermSpace[3]; /* Initial aLTerm[] space */
  128041. };
  128042. /* This object holds the prerequisites and the cost of running a
  128043. ** subquery on one operand of an OR operator in the WHERE clause.
  128044. ** See WhereOrSet for additional information
  128045. */
  128046. struct WhereOrCost {
  128047. Bitmask prereq; /* Prerequisites */
  128048. LogEst rRun; /* Cost of running this subquery */
  128049. LogEst nOut; /* Number of outputs for this subquery */
  128050. };
  128051. /* The WhereOrSet object holds a set of possible WhereOrCosts that
  128052. ** correspond to the subquery(s) of OR-clause processing. Only the
  128053. ** best N_OR_COST elements are retained.
  128054. */
  128055. #define N_OR_COST 3
  128056. struct WhereOrSet {
  128057. u16 n; /* Number of valid a[] entries */
  128058. WhereOrCost a[N_OR_COST]; /* Set of best costs */
  128059. };
  128060. /*
  128061. ** Each instance of this object holds a sequence of WhereLoop objects
  128062. ** that implement some or all of a query plan.
  128063. **
  128064. ** Think of each WhereLoop object as a node in a graph with arcs
  128065. ** showing dependencies and costs for travelling between nodes. (That is
  128066. ** not a completely accurate description because WhereLoop costs are a
  128067. ** vector, not a scalar, and because dependencies are many-to-one, not
  128068. ** one-to-one as are graph nodes. But it is a useful visualization aid.)
  128069. ** Then a WherePath object is a path through the graph that visits some
  128070. ** or all of the WhereLoop objects once.
  128071. **
  128072. ** The "solver" works by creating the N best WherePath objects of length
  128073. ** 1. Then using those as a basis to compute the N best WherePath objects
  128074. ** of length 2. And so forth until the length of WherePaths equals the
  128075. ** number of nodes in the FROM clause. The best (lowest cost) WherePath
  128076. ** at the end is the chosen query plan.
  128077. */
  128078. struct WherePath {
  128079. Bitmask maskLoop; /* Bitmask of all WhereLoop objects in this path */
  128080. Bitmask revLoop; /* aLoop[]s that should be reversed for ORDER BY */
  128081. LogEst nRow; /* Estimated number of rows generated by this path */
  128082. LogEst rCost; /* Total cost of this path */
  128083. LogEst rUnsorted; /* Total cost of this path ignoring sorting costs */
  128084. i8 isOrdered; /* No. of ORDER BY terms satisfied. -1 for unknown */
  128085. WhereLoop **aLoop; /* Array of WhereLoop objects implementing this path */
  128086. };
  128087. /*
  128088. ** The query generator uses an array of instances of this structure to
  128089. ** help it analyze the subexpressions of the WHERE clause. Each WHERE
  128090. ** clause subexpression is separated from the others by AND operators,
  128091. ** usually, or sometimes subexpressions separated by OR.
  128092. **
  128093. ** All WhereTerms are collected into a single WhereClause structure.
  128094. ** The following identity holds:
  128095. **
  128096. ** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
  128097. **
  128098. ** When a term is of the form:
  128099. **
  128100. ** X <op> <expr>
  128101. **
  128102. ** where X is a column name and <op> is one of certain operators,
  128103. ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
  128104. ** cursor number and column number for X. WhereTerm.eOperator records
  128105. ** the <op> using a bitmask encoding defined by WO_xxx below. The
  128106. ** use of a bitmask encoding for the operator allows us to search
  128107. ** quickly for terms that match any of several different operators.
  128108. **
  128109. ** A WhereTerm might also be two or more subterms connected by OR:
  128110. **
  128111. ** (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
  128112. **
  128113. ** In this second case, wtFlag has the TERM_ORINFO bit set and eOperator==WO_OR
  128114. ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
  128115. ** is collected about the OR clause.
  128116. **
  128117. ** If a term in the WHERE clause does not match either of the two previous
  128118. ** categories, then eOperator==0. The WhereTerm.pExpr field is still set
  128119. ** to the original subexpression content and wtFlags is set up appropriately
  128120. ** but no other fields in the WhereTerm object are meaningful.
  128121. **
  128122. ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
  128123. ** but they do so indirectly. A single WhereMaskSet structure translates
  128124. ** cursor number into bits and the translated bit is stored in the prereq
  128125. ** fields. The translation is used in order to maximize the number of
  128126. ** bits that will fit in a Bitmask. The VDBE cursor numbers might be
  128127. ** spread out over the non-negative integers. For example, the cursor
  128128. ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The WhereMaskSet
  128129. ** translates these sparse cursor numbers into consecutive integers
  128130. ** beginning with 0 in order to make the best possible use of the available
  128131. ** bits in the Bitmask. So, in the example above, the cursor numbers
  128132. ** would be mapped into integers 0 through 7.
  128133. **
  128134. ** The number of terms in a join is limited by the number of bits
  128135. ** in prereqRight and prereqAll. The default is 64 bits, hence SQLite
  128136. ** is only able to process joins with 64 or fewer tables.
  128137. */
  128138. struct WhereTerm {
  128139. Expr *pExpr; /* Pointer to the subexpression that is this term */
  128140. WhereClause *pWC; /* The clause this term is part of */
  128141. LogEst truthProb; /* Probability of truth for this expression */
  128142. u16 wtFlags; /* TERM_xxx bit flags. See below */
  128143. u16 eOperator; /* A WO_xx value describing <op> */
  128144. u8 nChild; /* Number of children that must disable us */
  128145. u8 eMatchOp; /* Op for vtab MATCH/LIKE/GLOB/REGEXP terms */
  128146. int iParent; /* Disable pWC->a[iParent] when this term disabled */
  128147. int leftCursor; /* Cursor number of X in "X <op> <expr>" */
  128148. int iField; /* Field in (?,?,?) IN (SELECT...) vector */
  128149. union {
  128150. int leftColumn; /* Column number of X in "X <op> <expr>" */
  128151. WhereOrInfo *pOrInfo; /* Extra information if (eOperator & WO_OR)!=0 */
  128152. WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
  128153. } u;
  128154. Bitmask prereqRight; /* Bitmask of tables used by pExpr->pRight */
  128155. Bitmask prereqAll; /* Bitmask of tables referenced by pExpr */
  128156. };
  128157. /*
  128158. ** Allowed values of WhereTerm.wtFlags
  128159. */
  128160. #define TERM_DYNAMIC 0x01 /* Need to call sqlite3ExprDelete(db, pExpr) */
  128161. #define TERM_VIRTUAL 0x02 /* Added by the optimizer. Do not code */
  128162. #define TERM_CODED 0x04 /* This term is already coded */
  128163. #define TERM_COPIED 0x08 /* Has a child */
  128164. #define TERM_ORINFO 0x10 /* Need to free the WhereTerm.u.pOrInfo object */
  128165. #define TERM_ANDINFO 0x20 /* Need to free the WhereTerm.u.pAndInfo obj */
  128166. #define TERM_OR_OK 0x40 /* Used during OR-clause processing */
  128167. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  128168. # define TERM_VNULL 0x80 /* Manufactured x>NULL or x<=NULL term */
  128169. #else
  128170. # define TERM_VNULL 0x00 /* Disabled if not using stat3 */
  128171. #endif
  128172. #define TERM_LIKEOPT 0x100 /* Virtual terms from the LIKE optimization */
  128173. #define TERM_LIKECOND 0x200 /* Conditionally this LIKE operator term */
  128174. #define TERM_LIKE 0x400 /* The original LIKE operator */
  128175. #define TERM_IS 0x800 /* Term.pExpr is an IS operator */
  128176. #define TERM_VARSELECT 0x1000 /* Term.pExpr contains a correlated sub-query */
  128177. /*
  128178. ** An instance of the WhereScan object is used as an iterator for locating
  128179. ** terms in the WHERE clause that are useful to the query planner.
  128180. */
  128181. struct WhereScan {
  128182. WhereClause *pOrigWC; /* Original, innermost WhereClause */
  128183. WhereClause *pWC; /* WhereClause currently being scanned */
  128184. const char *zCollName; /* Required collating sequence, if not NULL */
  128185. Expr *pIdxExpr; /* Search for this index expression */
  128186. char idxaff; /* Must match this affinity, if zCollName!=NULL */
  128187. unsigned char nEquiv; /* Number of entries in aEquiv[] */
  128188. unsigned char iEquiv; /* Next unused slot in aEquiv[] */
  128189. u32 opMask; /* Acceptable operators */
  128190. int k; /* Resume scanning at this->pWC->a[this->k] */
  128191. int aiCur[11]; /* Cursors in the equivalence class */
  128192. i16 aiColumn[11]; /* Corresponding column number in the eq-class */
  128193. };
  128194. /*
  128195. ** An instance of the following structure holds all information about a
  128196. ** WHERE clause. Mostly this is a container for one or more WhereTerms.
  128197. **
  128198. ** Explanation of pOuter: For a WHERE clause of the form
  128199. **
  128200. ** a AND ((b AND c) OR (d AND e)) AND f
  128201. **
  128202. ** There are separate WhereClause objects for the whole clause and for
  128203. ** the subclauses "(b AND c)" and "(d AND e)". The pOuter field of the
  128204. ** subclauses points to the WhereClause object for the whole clause.
  128205. */
  128206. struct WhereClause {
  128207. WhereInfo *pWInfo; /* WHERE clause processing context */
  128208. WhereClause *pOuter; /* Outer conjunction */
  128209. u8 op; /* Split operator. TK_AND or TK_OR */
  128210. u8 hasOr; /* True if any a[].eOperator is WO_OR */
  128211. int nTerm; /* Number of terms */
  128212. int nSlot; /* Number of entries in a[] */
  128213. WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */
  128214. #if defined(SQLITE_SMALL_STACK)
  128215. WhereTerm aStatic[1]; /* Initial static space for a[] */
  128216. #else
  128217. WhereTerm aStatic[8]; /* Initial static space for a[] */
  128218. #endif
  128219. };
  128220. /*
  128221. ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
  128222. ** a dynamically allocated instance of the following structure.
  128223. */
  128224. struct WhereOrInfo {
  128225. WhereClause wc; /* Decomposition into subterms */
  128226. Bitmask indexable; /* Bitmask of all indexable tables in the clause */
  128227. };
  128228. /*
  128229. ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
  128230. ** a dynamically allocated instance of the following structure.
  128231. */
  128232. struct WhereAndInfo {
  128233. WhereClause wc; /* The subexpression broken out */
  128234. };
  128235. /*
  128236. ** An instance of the following structure keeps track of a mapping
  128237. ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
  128238. **
  128239. ** The VDBE cursor numbers are small integers contained in
  128240. ** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE
  128241. ** clause, the cursor numbers might not begin with 0 and they might
  128242. ** contain gaps in the numbering sequence. But we want to make maximum
  128243. ** use of the bits in our bitmasks. This structure provides a mapping
  128244. ** from the sparse cursor numbers into consecutive integers beginning
  128245. ** with 0.
  128246. **
  128247. ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
  128248. ** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
  128249. **
  128250. ** For example, if the WHERE clause expression used these VDBE
  128251. ** cursors: 4, 5, 8, 29, 57, 73. Then the WhereMaskSet structure
  128252. ** would map those cursor numbers into bits 0 through 5.
  128253. **
  128254. ** Note that the mapping is not necessarily ordered. In the example
  128255. ** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0,
  128256. ** 57->5, 73->4. Or one of 719 other combinations might be used. It
  128257. ** does not really matter. What is important is that sparse cursor
  128258. ** numbers all get mapped into bit numbers that begin with 0 and contain
  128259. ** no gaps.
  128260. */
  128261. struct WhereMaskSet {
  128262. int bVarSelect; /* Used by sqlite3WhereExprUsage() */
  128263. int n; /* Number of assigned cursor values */
  128264. int ix[BMS]; /* Cursor assigned to each bit */
  128265. };
  128266. /*
  128267. ** Initialize a WhereMaskSet object
  128268. */
  128269. #define initMaskSet(P) (P)->n=0
  128270. /*
  128271. ** This object is a convenience wrapper holding all information needed
  128272. ** to construct WhereLoop objects for a particular query.
  128273. */
  128274. struct WhereLoopBuilder {
  128275. WhereInfo *pWInfo; /* Information about this WHERE */
  128276. WhereClause *pWC; /* WHERE clause terms */
  128277. ExprList *pOrderBy; /* ORDER BY clause */
  128278. WhereLoop *pNew; /* Template WhereLoop */
  128279. WhereOrSet *pOrSet; /* Record best loops here, if not NULL */
  128280. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  128281. UnpackedRecord *pRec; /* Probe for stat4 (if required) */
  128282. int nRecValid; /* Number of valid fields currently in pRec */
  128283. #endif
  128284. unsigned int bldFlags; /* SQLITE_BLDF_* flags */
  128285. unsigned int iPlanLimit; /* Search limiter */
  128286. };
  128287. /* Allowed values for WhereLoopBuider.bldFlags */
  128288. #define SQLITE_BLDF_INDEXED 0x0001 /* An index is used */
  128289. #define SQLITE_BLDF_UNIQUE 0x0002 /* All keys of a UNIQUE index used */
  128290. /* The WhereLoopBuilder.iPlanLimit is used to limit the number of
  128291. ** index+constraint combinations the query planner will consider for a
  128292. ** particular query. If this parameter is unlimited, then certain
  128293. ** pathological queries can spend excess time in the sqlite3WhereBegin()
  128294. ** routine. The limit is high enough that is should not impact real-world
  128295. ** queries.
  128296. **
  128297. ** SQLITE_QUERY_PLANNER_LIMIT is the baseline limit. The limit is
  128298. ** increased by SQLITE_QUERY_PLANNER_LIMIT_INCR before each term of the FROM
  128299. ** clause is processed, so that every table in a join is guaranteed to be
  128300. ** able to propose a some index+constraint combinations even if the initial
  128301. ** baseline limit was exhausted by prior tables of the join.
  128302. */
  128303. #ifndef SQLITE_QUERY_PLANNER_LIMIT
  128304. # define SQLITE_QUERY_PLANNER_LIMIT 20000
  128305. #endif
  128306. #ifndef SQLITE_QUERY_PLANNER_LIMIT_INCR
  128307. # define SQLITE_QUERY_PLANNER_LIMIT_INCR 1000
  128308. #endif
  128309. /*
  128310. ** The WHERE clause processing routine has two halves. The
  128311. ** first part does the start of the WHERE loop and the second
  128312. ** half does the tail of the WHERE loop. An instance of
  128313. ** this structure is returned by the first half and passed
  128314. ** into the second half to give some continuity.
  128315. **
  128316. ** An instance of this object holds the complete state of the query
  128317. ** planner.
  128318. */
  128319. struct WhereInfo {
  128320. Parse *pParse; /* Parsing and code generating context */
  128321. SrcList *pTabList; /* List of tables in the join */
  128322. ExprList *pOrderBy; /* The ORDER BY clause or NULL */
  128323. ExprList *pResultSet; /* Result set of the query */
  128324. Expr *pWhere; /* The complete WHERE clause */
  128325. LogEst iLimit; /* LIMIT if wctrlFlags has WHERE_USE_LIMIT */
  128326. int aiCurOnePass[2]; /* OP_OpenWrite cursors for the ONEPASS opt */
  128327. int iContinue; /* Jump here to continue with next record */
  128328. int iBreak; /* Jump here to break out of the loop */
  128329. int savedNQueryLoop; /* pParse->nQueryLoop outside the WHERE loop */
  128330. u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */
  128331. u8 nLevel; /* Number of nested loop */
  128332. i8 nOBSat; /* Number of ORDER BY terms satisfied by indices */
  128333. u8 sorted; /* True if really sorted (not just grouped) */
  128334. u8 eOnePass; /* ONEPASS_OFF, or _SINGLE, or _MULTI */
  128335. u8 untestedTerms; /* Not all WHERE terms resolved by outer loop */
  128336. u8 eDistinct; /* One of the WHERE_DISTINCT_* values */
  128337. u8 bOrderedInnerLoop; /* True if only the inner-most loop is ordered */
  128338. int iTop; /* The very beginning of the WHERE loop */
  128339. WhereLoop *pLoops; /* List of all WhereLoop objects */
  128340. Bitmask revMask; /* Mask of ORDER BY terms that need reversing */
  128341. LogEst nRowOut; /* Estimated number of output rows */
  128342. WhereClause sWC; /* Decomposition of the WHERE clause */
  128343. WhereMaskSet sMaskSet; /* Map cursor numbers to bitmasks */
  128344. WhereLevel a[1]; /* Information about each nest loop in WHERE */
  128345. };
  128346. /*
  128347. ** Private interfaces - callable only by other where.c routines.
  128348. **
  128349. ** where.c:
  128350. */
  128351. SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet*,int);
  128352. #ifdef WHERETRACE_ENABLED
  128353. SQLITE_PRIVATE void sqlite3WhereClausePrint(WhereClause *pWC);
  128354. #endif
  128355. SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm(
  128356. WhereClause *pWC, /* The WHERE clause to be searched */
  128357. int iCur, /* Cursor number of LHS */
  128358. int iColumn, /* Column number of LHS */
  128359. Bitmask notReady, /* RHS must not overlap with this mask */
  128360. u32 op, /* Mask of WO_xx values describing operator */
  128361. Index *pIdx /* Must be compatible with this index, if not NULL */
  128362. );
  128363. /* wherecode.c: */
  128364. #ifndef SQLITE_OMIT_EXPLAIN
  128365. SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
  128366. Parse *pParse, /* Parse context */
  128367. SrcList *pTabList, /* Table list this loop refers to */
  128368. WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
  128369. u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
  128370. );
  128371. #else
  128372. # define sqlite3WhereExplainOneScan(u,v,w,x) 0
  128373. #endif /* SQLITE_OMIT_EXPLAIN */
  128374. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  128375. SQLITE_PRIVATE void sqlite3WhereAddScanStatus(
  128376. Vdbe *v, /* Vdbe to add scanstatus entry to */
  128377. SrcList *pSrclist, /* FROM clause pLvl reads data from */
  128378. WhereLevel *pLvl, /* Level to add scanstatus() entry for */
  128379. int addrExplain /* Address of OP_Explain (or 0) */
  128380. );
  128381. #else
  128382. # define sqlite3WhereAddScanStatus(a, b, c, d) ((void)d)
  128383. #endif
  128384. SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
  128385. Parse *pParse, /* Parsing context */
  128386. Vdbe *v, /* Prepared statement under construction */
  128387. WhereInfo *pWInfo, /* Complete information about the WHERE clause */
  128388. int iLevel, /* Which level of pWInfo->a[] should be coded */
  128389. WhereLevel *pLevel, /* The current level pointer */
  128390. Bitmask notReady /* Which tables are currently available */
  128391. );
  128392. /* whereexpr.c: */
  128393. SQLITE_PRIVATE void sqlite3WhereClauseInit(WhereClause*,WhereInfo*);
  128394. SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause*);
  128395. SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause*,Expr*,u8);
  128396. SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet*, Expr*);
  128397. SQLITE_PRIVATE Bitmask sqlite3WhereExprUsageNN(WhereMaskSet*, Expr*);
  128398. SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet*, ExprList*);
  128399. SQLITE_PRIVATE void sqlite3WhereExprAnalyze(SrcList*, WhereClause*);
  128400. SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(Parse*, struct SrcList_item*, WhereClause*);
  128401. /*
  128402. ** Bitmasks for the operators on WhereTerm objects. These are all
  128403. ** operators that are of interest to the query planner. An
  128404. ** OR-ed combination of these values can be used when searching for
  128405. ** particular WhereTerms within a WhereClause.
  128406. **
  128407. ** Value constraints:
  128408. ** WO_EQ == SQLITE_INDEX_CONSTRAINT_EQ
  128409. ** WO_LT == SQLITE_INDEX_CONSTRAINT_LT
  128410. ** WO_LE == SQLITE_INDEX_CONSTRAINT_LE
  128411. ** WO_GT == SQLITE_INDEX_CONSTRAINT_GT
  128412. ** WO_GE == SQLITE_INDEX_CONSTRAINT_GE
  128413. */
  128414. #define WO_IN 0x0001
  128415. #define WO_EQ 0x0002
  128416. #define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
  128417. #define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
  128418. #define WO_GT (WO_EQ<<(TK_GT-TK_EQ))
  128419. #define WO_GE (WO_EQ<<(TK_GE-TK_EQ))
  128420. #define WO_AUX 0x0040 /* Op useful to virtual tables only */
  128421. #define WO_IS 0x0080
  128422. #define WO_ISNULL 0x0100
  128423. #define WO_OR 0x0200 /* Two or more OR-connected terms */
  128424. #define WO_AND 0x0400 /* Two or more AND-connected terms */
  128425. #define WO_EQUIV 0x0800 /* Of the form A==B, both columns */
  128426. #define WO_NOOP 0x1000 /* This term does not restrict search space */
  128427. #define WO_ALL 0x1fff /* Mask of all possible WO_* values */
  128428. #define WO_SINGLE 0x01ff /* Mask of all non-compound WO_* values */
  128429. /*
  128430. ** These are definitions of bits in the WhereLoop.wsFlags field.
  128431. ** The particular combination of bits in each WhereLoop help to
  128432. ** determine the algorithm that WhereLoop represents.
  128433. */
  128434. #define WHERE_COLUMN_EQ 0x00000001 /* x=EXPR */
  128435. #define WHERE_COLUMN_RANGE 0x00000002 /* x<EXPR and/or x>EXPR */
  128436. #define WHERE_COLUMN_IN 0x00000004 /* x IN (...) */
  128437. #define WHERE_COLUMN_NULL 0x00000008 /* x IS NULL */
  128438. #define WHERE_CONSTRAINT 0x0000000f /* Any of the WHERE_COLUMN_xxx values */
  128439. #define WHERE_TOP_LIMIT 0x00000010 /* x<EXPR or x<=EXPR constraint */
  128440. #define WHERE_BTM_LIMIT 0x00000020 /* x>EXPR or x>=EXPR constraint */
  128441. #define WHERE_BOTH_LIMIT 0x00000030 /* Both x>EXPR and x<EXPR */
  128442. #define WHERE_IDX_ONLY 0x00000040 /* Use index only - omit table */
  128443. #define WHERE_IPK 0x00000100 /* x is the INTEGER PRIMARY KEY */
  128444. #define WHERE_INDEXED 0x00000200 /* WhereLoop.u.btree.pIndex is valid */
  128445. #define WHERE_VIRTUALTABLE 0x00000400 /* WhereLoop.u.vtab is valid */
  128446. #define WHERE_IN_ABLE 0x00000800 /* Able to support an IN operator */
  128447. #define WHERE_ONEROW 0x00001000 /* Selects no more than one row */
  128448. #define WHERE_MULTI_OR 0x00002000 /* OR using multiple indices */
  128449. #define WHERE_AUTO_INDEX 0x00004000 /* Uses an ephemeral index */
  128450. #define WHERE_SKIPSCAN 0x00008000 /* Uses the skip-scan algorithm */
  128451. #define WHERE_UNQ_WANTED 0x00010000 /* WHERE_ONEROW would have been helpful*/
  128452. #define WHERE_PARTIALIDX 0x00020000 /* The automatic index is partial */
  128453. #define WHERE_IN_EARLYOUT 0x00040000 /* Perhaps quit IN loops early */
  128454. #endif /* !defined(SQLITE_WHEREINT_H) */
  128455. /************** End of whereInt.h ********************************************/
  128456. /************** Continuing where we left off in wherecode.c ******************/
  128457. #ifndef SQLITE_OMIT_EXPLAIN
  128458. /*
  128459. ** Return the name of the i-th column of the pIdx index.
  128460. */
  128461. static const char *explainIndexColumnName(Index *pIdx, int i){
  128462. i = pIdx->aiColumn[i];
  128463. if( i==XN_EXPR ) return "<expr>";
  128464. if( i==XN_ROWID ) return "rowid";
  128465. return pIdx->pTable->aCol[i].zName;
  128466. }
  128467. /*
  128468. ** This routine is a helper for explainIndexRange() below
  128469. **
  128470. ** pStr holds the text of an expression that we are building up one term
  128471. ** at a time. This routine adds a new term to the end of the expression.
  128472. ** Terms are separated by AND so add the "AND" text for second and subsequent
  128473. ** terms only.
  128474. */
  128475. static void explainAppendTerm(
  128476. StrAccum *pStr, /* The text expression being built */
  128477. Index *pIdx, /* Index to read column names from */
  128478. int nTerm, /* Number of terms */
  128479. int iTerm, /* Zero-based index of first term. */
  128480. int bAnd, /* Non-zero to append " AND " */
  128481. const char *zOp /* Name of the operator */
  128482. ){
  128483. int i;
  128484. assert( nTerm>=1 );
  128485. if( bAnd ) sqlite3_str_append(pStr, " AND ", 5);
  128486. if( nTerm>1 ) sqlite3_str_append(pStr, "(", 1);
  128487. for(i=0; i<nTerm; i++){
  128488. if( i ) sqlite3_str_append(pStr, ",", 1);
  128489. sqlite3_str_appendall(pStr, explainIndexColumnName(pIdx, iTerm+i));
  128490. }
  128491. if( nTerm>1 ) sqlite3_str_append(pStr, ")", 1);
  128492. sqlite3_str_append(pStr, zOp, 1);
  128493. if( nTerm>1 ) sqlite3_str_append(pStr, "(", 1);
  128494. for(i=0; i<nTerm; i++){
  128495. if( i ) sqlite3_str_append(pStr, ",", 1);
  128496. sqlite3_str_append(pStr, "?", 1);
  128497. }
  128498. if( nTerm>1 ) sqlite3_str_append(pStr, ")", 1);
  128499. }
  128500. /*
  128501. ** Argument pLevel describes a strategy for scanning table pTab. This
  128502. ** function appends text to pStr that describes the subset of table
  128503. ** rows scanned by the strategy in the form of an SQL expression.
  128504. **
  128505. ** For example, if the query:
  128506. **
  128507. ** SELECT * FROM t1 WHERE a=1 AND b>2;
  128508. **
  128509. ** is run and there is an index on (a, b), then this function returns a
  128510. ** string similar to:
  128511. **
  128512. ** "a=? AND b>?"
  128513. */
  128514. static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop){
  128515. Index *pIndex = pLoop->u.btree.pIndex;
  128516. u16 nEq = pLoop->u.btree.nEq;
  128517. u16 nSkip = pLoop->nSkip;
  128518. int i, j;
  128519. if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return;
  128520. sqlite3_str_append(pStr, " (", 2);
  128521. for(i=0; i<nEq; i++){
  128522. const char *z = explainIndexColumnName(pIndex, i);
  128523. if( i ) sqlite3_str_append(pStr, " AND ", 5);
  128524. sqlite3_str_appendf(pStr, i>=nSkip ? "%s=?" : "ANY(%s)", z);
  128525. }
  128526. j = i;
  128527. if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
  128528. explainAppendTerm(pStr, pIndex, pLoop->u.btree.nBtm, j, i, ">");
  128529. i = 1;
  128530. }
  128531. if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
  128532. explainAppendTerm(pStr, pIndex, pLoop->u.btree.nTop, j, i, "<");
  128533. }
  128534. sqlite3_str_append(pStr, ")", 1);
  128535. }
  128536. /*
  128537. ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
  128538. ** command, or if either SQLITE_DEBUG or SQLITE_ENABLE_STMT_SCANSTATUS was
  128539. ** defined at compile-time. If it is not a no-op, a single OP_Explain opcode
  128540. ** is added to the output to describe the table scan strategy in pLevel.
  128541. **
  128542. ** If an OP_Explain opcode is added to the VM, its address is returned.
  128543. ** Otherwise, if no OP_Explain is coded, zero is returned.
  128544. */
  128545. SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
  128546. Parse *pParse, /* Parse context */
  128547. SrcList *pTabList, /* Table list this loop refers to */
  128548. WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
  128549. u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
  128550. ){
  128551. int ret = 0;
  128552. #if !defined(SQLITE_DEBUG) && !defined(SQLITE_ENABLE_STMT_SCANSTATUS)
  128553. if( sqlite3ParseToplevel(pParse)->explain==2 )
  128554. #endif
  128555. {
  128556. struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
  128557. Vdbe *v = pParse->pVdbe; /* VM being constructed */
  128558. sqlite3 *db = pParse->db; /* Database handle */
  128559. int isSearch; /* True for a SEARCH. False for SCAN. */
  128560. WhereLoop *pLoop; /* The controlling WhereLoop object */
  128561. u32 flags; /* Flags that describe this loop */
  128562. char *zMsg; /* Text to add to EQP output */
  128563. StrAccum str; /* EQP output string */
  128564. char zBuf[100]; /* Initial space for EQP output string */
  128565. pLoop = pLevel->pWLoop;
  128566. flags = pLoop->wsFlags;
  128567. if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_OR_SUBCLAUSE) ) return 0;
  128568. isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
  128569. || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
  128570. || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
  128571. sqlite3StrAccumInit(&str, db, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH);
  128572. sqlite3_str_appendall(&str, isSearch ? "SEARCH" : "SCAN");
  128573. if( pItem->pSelect ){
  128574. sqlite3_str_appendf(&str, " SUBQUERY %u", pItem->pSelect->selId);
  128575. }else{
  128576. sqlite3_str_appendf(&str, " TABLE %s", pItem->zName);
  128577. }
  128578. if( pItem->zAlias ){
  128579. sqlite3_str_appendf(&str, " AS %s", pItem->zAlias);
  128580. }
  128581. if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){
  128582. const char *zFmt = 0;
  128583. Index *pIdx;
  128584. assert( pLoop->u.btree.pIndex!=0 );
  128585. pIdx = pLoop->u.btree.pIndex;
  128586. assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) );
  128587. if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){
  128588. if( isSearch ){
  128589. zFmt = "PRIMARY KEY";
  128590. }
  128591. }else if( flags & WHERE_PARTIALIDX ){
  128592. zFmt = "AUTOMATIC PARTIAL COVERING INDEX";
  128593. }else if( flags & WHERE_AUTO_INDEX ){
  128594. zFmt = "AUTOMATIC COVERING INDEX";
  128595. }else if( flags & WHERE_IDX_ONLY ){
  128596. zFmt = "COVERING INDEX %s";
  128597. }else{
  128598. zFmt = "INDEX %s";
  128599. }
  128600. if( zFmt ){
  128601. sqlite3_str_append(&str, " USING ", 7);
  128602. sqlite3_str_appendf(&str, zFmt, pIdx->zName);
  128603. explainIndexRange(&str, pLoop);
  128604. }
  128605. }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
  128606. const char *zRangeOp;
  128607. if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
  128608. zRangeOp = "=";
  128609. }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
  128610. zRangeOp = ">? AND rowid<";
  128611. }else if( flags&WHERE_BTM_LIMIT ){
  128612. zRangeOp = ">";
  128613. }else{
  128614. assert( flags&WHERE_TOP_LIMIT);
  128615. zRangeOp = "<";
  128616. }
  128617. sqlite3_str_appendf(&str,
  128618. " USING INTEGER PRIMARY KEY (rowid%s?)",zRangeOp);
  128619. }
  128620. #ifndef SQLITE_OMIT_VIRTUALTABLE
  128621. else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
  128622. sqlite3_str_appendf(&str, " VIRTUAL TABLE INDEX %d:%s",
  128623. pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
  128624. }
  128625. #endif
  128626. #ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS
  128627. if( pLoop->nOut>=10 ){
  128628. sqlite3_str_appendf(&str, " (~%llu rows)",
  128629. sqlite3LogEstToInt(pLoop->nOut));
  128630. }else{
  128631. sqlite3_str_append(&str, " (~1 row)", 9);
  128632. }
  128633. #endif
  128634. zMsg = sqlite3StrAccumFinish(&str);
  128635. sqlite3ExplainBreakpoint("",zMsg);
  128636. ret = sqlite3VdbeAddOp4(v, OP_Explain, sqlite3VdbeCurrentAddr(v),
  128637. pParse->addrExplain, 0, zMsg,P4_DYNAMIC);
  128638. }
  128639. return ret;
  128640. }
  128641. #endif /* SQLITE_OMIT_EXPLAIN */
  128642. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  128643. /*
  128644. ** Configure the VM passed as the first argument with an
  128645. ** sqlite3_stmt_scanstatus() entry corresponding to the scan used to
  128646. ** implement level pLvl. Argument pSrclist is a pointer to the FROM
  128647. ** clause that the scan reads data from.
  128648. **
  128649. ** If argument addrExplain is not 0, it must be the address of an
  128650. ** OP_Explain instruction that describes the same loop.
  128651. */
  128652. SQLITE_PRIVATE void sqlite3WhereAddScanStatus(
  128653. Vdbe *v, /* Vdbe to add scanstatus entry to */
  128654. SrcList *pSrclist, /* FROM clause pLvl reads data from */
  128655. WhereLevel *pLvl, /* Level to add scanstatus() entry for */
  128656. int addrExplain /* Address of OP_Explain (or 0) */
  128657. ){
  128658. const char *zObj = 0;
  128659. WhereLoop *pLoop = pLvl->pWLoop;
  128660. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 && pLoop->u.btree.pIndex!=0 ){
  128661. zObj = pLoop->u.btree.pIndex->zName;
  128662. }else{
  128663. zObj = pSrclist->a[pLvl->iFrom].zName;
  128664. }
  128665. sqlite3VdbeScanStatus(
  128666. v, addrExplain, pLvl->addrBody, pLvl->addrVisit, pLoop->nOut, zObj
  128667. );
  128668. }
  128669. #endif
  128670. /*
  128671. ** Disable a term in the WHERE clause. Except, do not disable the term
  128672. ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
  128673. ** or USING clause of that join.
  128674. **
  128675. ** Consider the term t2.z='ok' in the following queries:
  128676. **
  128677. ** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
  128678. ** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
  128679. ** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
  128680. **
  128681. ** The t2.z='ok' is disabled in the in (2) because it originates
  128682. ** in the ON clause. The term is disabled in (3) because it is not part
  128683. ** of a LEFT OUTER JOIN. In (1), the term is not disabled.
  128684. **
  128685. ** Disabling a term causes that term to not be tested in the inner loop
  128686. ** of the join. Disabling is an optimization. When terms are satisfied
  128687. ** by indices, we disable them to prevent redundant tests in the inner
  128688. ** loop. We would get the correct results if nothing were ever disabled,
  128689. ** but joins might run a little slower. The trick is to disable as much
  128690. ** as we can without disabling too much. If we disabled in (1), we'd get
  128691. ** the wrong answer. See ticket #813.
  128692. **
  128693. ** If all the children of a term are disabled, then that term is also
  128694. ** automatically disabled. In this way, terms get disabled if derived
  128695. ** virtual terms are tested first. For example:
  128696. **
  128697. ** x GLOB 'abc*' AND x>='abc' AND x<'acd'
  128698. ** \___________/ \______/ \_____/
  128699. ** parent child1 child2
  128700. **
  128701. ** Only the parent term was in the original WHERE clause. The child1
  128702. ** and child2 terms were added by the LIKE optimization. If both of
  128703. ** the virtual child terms are valid, then testing of the parent can be
  128704. ** skipped.
  128705. **
  128706. ** Usually the parent term is marked as TERM_CODED. But if the parent
  128707. ** term was originally TERM_LIKE, then the parent gets TERM_LIKECOND instead.
  128708. ** The TERM_LIKECOND marking indicates that the term should be coded inside
  128709. ** a conditional such that is only evaluated on the second pass of a
  128710. ** LIKE-optimization loop, when scanning BLOBs instead of strings.
  128711. */
  128712. static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
  128713. int nLoop = 0;
  128714. assert( pTerm!=0 );
  128715. while( (pTerm->wtFlags & TERM_CODED)==0
  128716. && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
  128717. && (pLevel->notReady & pTerm->prereqAll)==0
  128718. ){
  128719. if( nLoop && (pTerm->wtFlags & TERM_LIKE)!=0 ){
  128720. pTerm->wtFlags |= TERM_LIKECOND;
  128721. }else{
  128722. pTerm->wtFlags |= TERM_CODED;
  128723. }
  128724. if( pTerm->iParent<0 ) break;
  128725. pTerm = &pTerm->pWC->a[pTerm->iParent];
  128726. assert( pTerm!=0 );
  128727. pTerm->nChild--;
  128728. if( pTerm->nChild!=0 ) break;
  128729. nLoop++;
  128730. }
  128731. }
  128732. /*
  128733. ** Code an OP_Affinity opcode to apply the column affinity string zAff
  128734. ** to the n registers starting at base.
  128735. **
  128736. ** As an optimization, SQLITE_AFF_BLOB entries (which are no-ops) at the
  128737. ** beginning and end of zAff are ignored. If all entries in zAff are
  128738. ** SQLITE_AFF_BLOB, then no code gets generated.
  128739. **
  128740. ** This routine makes its own copy of zAff so that the caller is free
  128741. ** to modify zAff after this routine returns.
  128742. */
  128743. static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
  128744. Vdbe *v = pParse->pVdbe;
  128745. if( zAff==0 ){
  128746. assert( pParse->db->mallocFailed );
  128747. return;
  128748. }
  128749. assert( v!=0 );
  128750. /* Adjust base and n to skip over SQLITE_AFF_BLOB entries at the beginning
  128751. ** and end of the affinity string.
  128752. */
  128753. while( n>0 && zAff[0]==SQLITE_AFF_BLOB ){
  128754. n--;
  128755. base++;
  128756. zAff++;
  128757. }
  128758. while( n>1 && zAff[n-1]==SQLITE_AFF_BLOB ){
  128759. n--;
  128760. }
  128761. /* Code the OP_Affinity opcode if there is anything left to do. */
  128762. if( n>0 ){
  128763. sqlite3VdbeAddOp4(v, OP_Affinity, base, n, 0, zAff, n);
  128764. }
  128765. }
  128766. /*
  128767. ** Expression pRight, which is the RHS of a comparison operation, is
  128768. ** either a vector of n elements or, if n==1, a scalar expression.
  128769. ** Before the comparison operation, affinity zAff is to be applied
  128770. ** to the pRight values. This function modifies characters within the
  128771. ** affinity string to SQLITE_AFF_BLOB if either:
  128772. **
  128773. ** * the comparison will be performed with no affinity, or
  128774. ** * the affinity change in zAff is guaranteed not to change the value.
  128775. */
  128776. static void updateRangeAffinityStr(
  128777. Expr *pRight, /* RHS of comparison */
  128778. int n, /* Number of vector elements in comparison */
  128779. char *zAff /* Affinity string to modify */
  128780. ){
  128781. int i;
  128782. for(i=0; i<n; i++){
  128783. Expr *p = sqlite3VectorFieldSubexpr(pRight, i);
  128784. if( sqlite3CompareAffinity(p, zAff[i])==SQLITE_AFF_BLOB
  128785. || sqlite3ExprNeedsNoAffinityChange(p, zAff[i])
  128786. ){
  128787. zAff[i] = SQLITE_AFF_BLOB;
  128788. }
  128789. }
  128790. }
  128791. /*
  128792. ** pX is an expression of the form: (vector) IN (SELECT ...)
  128793. ** In other words, it is a vector IN operator with a SELECT clause on the
  128794. ** LHS. But not all terms in the vector are indexable and the terms might
  128795. ** not be in the correct order for indexing.
  128796. **
  128797. ** This routine makes a copy of the input pX expression and then adjusts
  128798. ** the vector on the LHS with corresponding changes to the SELECT so that
  128799. ** the vector contains only index terms and those terms are in the correct
  128800. ** order. The modified IN expression is returned. The caller is responsible
  128801. ** for deleting the returned expression.
  128802. **
  128803. ** Example:
  128804. **
  128805. ** CREATE TABLE t1(a,b,c,d,e,f);
  128806. ** CREATE INDEX t1x1 ON t1(e,c);
  128807. ** SELECT * FROM t1 WHERE (a,b,c,d,e) IN (SELECT v,w,x,y,z FROM t2)
  128808. ** \_______________________________________/
  128809. ** The pX expression
  128810. **
  128811. ** Since only columns e and c can be used with the index, in that order,
  128812. ** the modified IN expression that is returned will be:
  128813. **
  128814. ** (e,c) IN (SELECT z,x FROM t2)
  128815. **
  128816. ** The reduced pX is different from the original (obviously) and thus is
  128817. ** only used for indexing, to improve performance. The original unaltered
  128818. ** IN expression must also be run on each output row for correctness.
  128819. */
  128820. static Expr *removeUnindexableInClauseTerms(
  128821. Parse *pParse, /* The parsing context */
  128822. int iEq, /* Look at loop terms starting here */
  128823. WhereLoop *pLoop, /* The current loop */
  128824. Expr *pX /* The IN expression to be reduced */
  128825. ){
  128826. sqlite3 *db = pParse->db;
  128827. Expr *pNew = sqlite3ExprDup(db, pX, 0);
  128828. if( db->mallocFailed==0 ){
  128829. ExprList *pOrigRhs = pNew->x.pSelect->pEList; /* Original unmodified RHS */
  128830. ExprList *pOrigLhs = pNew->pLeft->x.pList; /* Original unmodified LHS */
  128831. ExprList *pRhs = 0; /* New RHS after modifications */
  128832. ExprList *pLhs = 0; /* New LHS after mods */
  128833. int i; /* Loop counter */
  128834. Select *pSelect; /* Pointer to the SELECT on the RHS */
  128835. for(i=iEq; i<pLoop->nLTerm; i++){
  128836. if( pLoop->aLTerm[i]->pExpr==pX ){
  128837. int iField = pLoop->aLTerm[i]->iField - 1;
  128838. if( pOrigRhs->a[iField].pExpr==0 ) continue; /* Duplicate PK column */
  128839. pRhs = sqlite3ExprListAppend(pParse, pRhs, pOrigRhs->a[iField].pExpr);
  128840. pOrigRhs->a[iField].pExpr = 0;
  128841. assert( pOrigLhs->a[iField].pExpr!=0 );
  128842. pLhs = sqlite3ExprListAppend(pParse, pLhs, pOrigLhs->a[iField].pExpr);
  128843. pOrigLhs->a[iField].pExpr = 0;
  128844. }
  128845. }
  128846. sqlite3ExprListDelete(db, pOrigRhs);
  128847. sqlite3ExprListDelete(db, pOrigLhs);
  128848. pNew->pLeft->x.pList = pLhs;
  128849. pNew->x.pSelect->pEList = pRhs;
  128850. if( pLhs && pLhs->nExpr==1 ){
  128851. /* Take care here not to generate a TK_VECTOR containing only a
  128852. ** single value. Since the parser never creates such a vector, some
  128853. ** of the subroutines do not handle this case. */
  128854. Expr *p = pLhs->a[0].pExpr;
  128855. pLhs->a[0].pExpr = 0;
  128856. sqlite3ExprDelete(db, pNew->pLeft);
  128857. pNew->pLeft = p;
  128858. }
  128859. pSelect = pNew->x.pSelect;
  128860. if( pSelect->pOrderBy ){
  128861. /* If the SELECT statement has an ORDER BY clause, zero the
  128862. ** iOrderByCol variables. These are set to non-zero when an
  128863. ** ORDER BY term exactly matches one of the terms of the
  128864. ** result-set. Since the result-set of the SELECT statement may
  128865. ** have been modified or reordered, these variables are no longer
  128866. ** set correctly. Since setting them is just an optimization,
  128867. ** it's easiest just to zero them here. */
  128868. ExprList *pOrderBy = pSelect->pOrderBy;
  128869. for(i=0; i<pOrderBy->nExpr; i++){
  128870. pOrderBy->a[i].u.x.iOrderByCol = 0;
  128871. }
  128872. }
  128873. #if 0
  128874. printf("For indexing, change the IN expr:\n");
  128875. sqlite3TreeViewExpr(0, pX, 0);
  128876. printf("Into:\n");
  128877. sqlite3TreeViewExpr(0, pNew, 0);
  128878. #endif
  128879. }
  128880. return pNew;
  128881. }
  128882. /*
  128883. ** Generate code for a single equality term of the WHERE clause. An equality
  128884. ** term can be either X=expr or X IN (...). pTerm is the term to be
  128885. ** coded.
  128886. **
  128887. ** The current value for the constraint is left in a register, the index
  128888. ** of which is returned. An attempt is made store the result in iTarget but
  128889. ** this is only guaranteed for TK_ISNULL and TK_IN constraints. If the
  128890. ** constraint is a TK_EQ or TK_IS, then the current value might be left in
  128891. ** some other register and it is the caller's responsibility to compensate.
  128892. **
  128893. ** For a constraint of the form X=expr, the expression is evaluated in
  128894. ** straight-line code. For constraints of the form X IN (...)
  128895. ** this routine sets up a loop that will iterate over all values of X.
  128896. */
  128897. static int codeEqualityTerm(
  128898. Parse *pParse, /* The parsing context */
  128899. WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
  128900. WhereLevel *pLevel, /* The level of the FROM clause we are working on */
  128901. int iEq, /* Index of the equality term within this level */
  128902. int bRev, /* True for reverse-order IN operations */
  128903. int iTarget /* Attempt to leave results in this register */
  128904. ){
  128905. Expr *pX = pTerm->pExpr;
  128906. Vdbe *v = pParse->pVdbe;
  128907. int iReg; /* Register holding results */
  128908. assert( pLevel->pWLoop->aLTerm[iEq]==pTerm );
  128909. assert( iTarget>0 );
  128910. if( pX->op==TK_EQ || pX->op==TK_IS ){
  128911. iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
  128912. }else if( pX->op==TK_ISNULL ){
  128913. iReg = iTarget;
  128914. sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
  128915. #ifndef SQLITE_OMIT_SUBQUERY
  128916. }else{
  128917. int eType = IN_INDEX_NOOP;
  128918. int iTab;
  128919. struct InLoop *pIn;
  128920. WhereLoop *pLoop = pLevel->pWLoop;
  128921. int i;
  128922. int nEq = 0;
  128923. int *aiMap = 0;
  128924. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
  128925. && pLoop->u.btree.pIndex!=0
  128926. && pLoop->u.btree.pIndex->aSortOrder[iEq]
  128927. ){
  128928. testcase( iEq==0 );
  128929. testcase( bRev );
  128930. bRev = !bRev;
  128931. }
  128932. assert( pX->op==TK_IN );
  128933. iReg = iTarget;
  128934. for(i=0; i<iEq; i++){
  128935. if( pLoop->aLTerm[i] && pLoop->aLTerm[i]->pExpr==pX ){
  128936. disableTerm(pLevel, pTerm);
  128937. return iTarget;
  128938. }
  128939. }
  128940. for(i=iEq;i<pLoop->nLTerm; i++){
  128941. assert( pLoop->aLTerm[i]!=0 );
  128942. if( pLoop->aLTerm[i]->pExpr==pX ) nEq++;
  128943. }
  128944. iTab = 0;
  128945. if( (pX->flags & EP_xIsSelect)==0 || pX->x.pSelect->pEList->nExpr==1 ){
  128946. eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, 0, &iTab);
  128947. }else{
  128948. sqlite3 *db = pParse->db;
  128949. pX = removeUnindexableInClauseTerms(pParse, iEq, pLoop, pX);
  128950. if( !db->mallocFailed ){
  128951. aiMap = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int)*nEq);
  128952. eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, aiMap, &iTab);
  128953. pTerm->pExpr->iTable = iTab;
  128954. }
  128955. sqlite3ExprDelete(db, pX);
  128956. pX = pTerm->pExpr;
  128957. }
  128958. if( eType==IN_INDEX_INDEX_DESC ){
  128959. testcase( bRev );
  128960. bRev = !bRev;
  128961. }
  128962. sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
  128963. VdbeCoverageIf(v, bRev);
  128964. VdbeCoverageIf(v, !bRev);
  128965. assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
  128966. pLoop->wsFlags |= WHERE_IN_ABLE;
  128967. if( pLevel->u.in.nIn==0 ){
  128968. pLevel->addrNxt = sqlite3VdbeMakeLabel(pParse);
  128969. }
  128970. i = pLevel->u.in.nIn;
  128971. pLevel->u.in.nIn += nEq;
  128972. pLevel->u.in.aInLoop =
  128973. sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
  128974. sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
  128975. pIn = pLevel->u.in.aInLoop;
  128976. if( pIn ){
  128977. int iMap = 0; /* Index in aiMap[] */
  128978. pIn += i;
  128979. for(i=iEq;i<pLoop->nLTerm; i++){
  128980. if( pLoop->aLTerm[i]->pExpr==pX ){
  128981. int iOut = iReg + i - iEq;
  128982. if( eType==IN_INDEX_ROWID ){
  128983. pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iOut);
  128984. }else{
  128985. int iCol = aiMap ? aiMap[iMap++] : 0;
  128986. pIn->addrInTop = sqlite3VdbeAddOp3(v,OP_Column,iTab, iCol, iOut);
  128987. }
  128988. sqlite3VdbeAddOp1(v, OP_IsNull, iOut); VdbeCoverage(v);
  128989. if( i==iEq ){
  128990. pIn->iCur = iTab;
  128991. pIn->eEndLoopOp = bRev ? OP_Prev : OP_Next;
  128992. if( iEq>0 && (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 ){
  128993. pIn->iBase = iReg - i;
  128994. pIn->nPrefix = i;
  128995. pLoop->wsFlags |= WHERE_IN_EARLYOUT;
  128996. }else{
  128997. pIn->nPrefix = 0;
  128998. }
  128999. }else{
  129000. pIn->eEndLoopOp = OP_Noop;
  129001. }
  129002. pIn++;
  129003. }
  129004. }
  129005. }else{
  129006. pLevel->u.in.nIn = 0;
  129007. }
  129008. sqlite3DbFree(pParse->db, aiMap);
  129009. #endif
  129010. }
  129011. disableTerm(pLevel, pTerm);
  129012. return iReg;
  129013. }
  129014. /*
  129015. ** Generate code that will evaluate all == and IN constraints for an
  129016. ** index scan.
  129017. **
  129018. ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
  129019. ** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
  129020. ** The index has as many as three equality constraints, but in this
  129021. ** example, the third "c" value is an inequality. So only two
  129022. ** constraints are coded. This routine will generate code to evaluate
  129023. ** a==5 and b IN (1,2,3). The current values for a and b will be stored
  129024. ** in consecutive registers and the index of the first register is returned.
  129025. **
  129026. ** In the example above nEq==2. But this subroutine works for any value
  129027. ** of nEq including 0. If nEq==0, this routine is nearly a no-op.
  129028. ** The only thing it does is allocate the pLevel->iMem memory cell and
  129029. ** compute the affinity string.
  129030. **
  129031. ** The nExtraReg parameter is 0 or 1. It is 0 if all WHERE clause constraints
  129032. ** are == or IN and are covered by the nEq. nExtraReg is 1 if there is
  129033. ** an inequality constraint (such as the "c>=5 AND c<10" in the example) that
  129034. ** occurs after the nEq quality constraints.
  129035. **
  129036. ** This routine allocates a range of nEq+nExtraReg memory cells and returns
  129037. ** the index of the first memory cell in that range. The code that
  129038. ** calls this routine will use that memory range to store keys for
  129039. ** start and termination conditions of the loop.
  129040. ** key value of the loop. If one or more IN operators appear, then
  129041. ** this routine allocates an additional nEq memory cells for internal
  129042. ** use.
  129043. **
  129044. ** Before returning, *pzAff is set to point to a buffer containing a
  129045. ** copy of the column affinity string of the index allocated using
  129046. ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
  129047. ** with equality constraints that use BLOB or NONE affinity are set to
  129048. ** SQLITE_AFF_BLOB. This is to deal with SQL such as the following:
  129049. **
  129050. ** CREATE TABLE t1(a TEXT PRIMARY KEY, b);
  129051. ** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
  129052. **
  129053. ** In the example above, the index on t1(a) has TEXT affinity. But since
  129054. ** the right hand side of the equality constraint (t2.b) has BLOB/NONE affinity,
  129055. ** no conversion should be attempted before using a t2.b value as part of
  129056. ** a key to search the index. Hence the first byte in the returned affinity
  129057. ** string in this example would be set to SQLITE_AFF_BLOB.
  129058. */
  129059. static int codeAllEqualityTerms(
  129060. Parse *pParse, /* Parsing context */
  129061. WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
  129062. int bRev, /* Reverse the order of IN operators */
  129063. int nExtraReg, /* Number of extra registers to allocate */
  129064. char **pzAff /* OUT: Set to point to affinity string */
  129065. ){
  129066. u16 nEq; /* The number of == or IN constraints to code */
  129067. u16 nSkip; /* Number of left-most columns to skip */
  129068. Vdbe *v = pParse->pVdbe; /* The vm under construction */
  129069. Index *pIdx; /* The index being used for this loop */
  129070. WhereTerm *pTerm; /* A single constraint term */
  129071. WhereLoop *pLoop; /* The WhereLoop object */
  129072. int j; /* Loop counter */
  129073. int regBase; /* Base register */
  129074. int nReg; /* Number of registers to allocate */
  129075. char *zAff; /* Affinity string to return */
  129076. /* This module is only called on query plans that use an index. */
  129077. pLoop = pLevel->pWLoop;
  129078. assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
  129079. nEq = pLoop->u.btree.nEq;
  129080. nSkip = pLoop->nSkip;
  129081. pIdx = pLoop->u.btree.pIndex;
  129082. assert( pIdx!=0 );
  129083. /* Figure out how many memory cells we will need then allocate them.
  129084. */
  129085. regBase = pParse->nMem + 1;
  129086. nReg = pLoop->u.btree.nEq + nExtraReg;
  129087. pParse->nMem += nReg;
  129088. zAff = sqlite3DbStrDup(pParse->db,sqlite3IndexAffinityStr(pParse->db,pIdx));
  129089. assert( zAff!=0 || pParse->db->mallocFailed );
  129090. if( nSkip ){
  129091. int iIdxCur = pLevel->iIdxCur;
  129092. sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur);
  129093. VdbeCoverageIf(v, bRev==0);
  129094. VdbeCoverageIf(v, bRev!=0);
  129095. VdbeComment((v, "begin skip-scan on %s", pIdx->zName));
  129096. j = sqlite3VdbeAddOp0(v, OP_Goto);
  129097. pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT),
  129098. iIdxCur, 0, regBase, nSkip);
  129099. VdbeCoverageIf(v, bRev==0);
  129100. VdbeCoverageIf(v, bRev!=0);
  129101. sqlite3VdbeJumpHere(v, j);
  129102. for(j=0; j<nSkip; j++){
  129103. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j);
  129104. testcase( pIdx->aiColumn[j]==XN_EXPR );
  129105. VdbeComment((v, "%s", explainIndexColumnName(pIdx, j)));
  129106. }
  129107. }
  129108. /* Evaluate the equality constraints
  129109. */
  129110. assert( zAff==0 || (int)strlen(zAff)>=nEq );
  129111. for(j=nSkip; j<nEq; j++){
  129112. int r1;
  129113. pTerm = pLoop->aLTerm[j];
  129114. assert( pTerm!=0 );
  129115. /* The following testcase is true for indices with redundant columns.
  129116. ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
  129117. testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
  129118. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  129119. r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
  129120. if( r1!=regBase+j ){
  129121. if( nReg==1 ){
  129122. sqlite3ReleaseTempReg(pParse, regBase);
  129123. regBase = r1;
  129124. }else{
  129125. sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
  129126. }
  129127. }
  129128. if( pTerm->eOperator & WO_IN ){
  129129. if( pTerm->pExpr->flags & EP_xIsSelect ){
  129130. /* No affinity ever needs to be (or should be) applied to a value
  129131. ** from the RHS of an "? IN (SELECT ...)" expression. The
  129132. ** sqlite3FindInIndex() routine has already ensured that the
  129133. ** affinity of the comparison has been applied to the value. */
  129134. if( zAff ) zAff[j] = SQLITE_AFF_BLOB;
  129135. }
  129136. }else if( (pTerm->eOperator & WO_ISNULL)==0 ){
  129137. Expr *pRight = pTerm->pExpr->pRight;
  129138. if( (pTerm->wtFlags & TERM_IS)==0 && sqlite3ExprCanBeNull(pRight) ){
  129139. sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
  129140. VdbeCoverage(v);
  129141. }
  129142. if( zAff ){
  129143. if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_BLOB ){
  129144. zAff[j] = SQLITE_AFF_BLOB;
  129145. }
  129146. if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
  129147. zAff[j] = SQLITE_AFF_BLOB;
  129148. }
  129149. }
  129150. }
  129151. }
  129152. *pzAff = zAff;
  129153. return regBase;
  129154. }
  129155. #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  129156. /*
  129157. ** If the most recently coded instruction is a constant range constraint
  129158. ** (a string literal) that originated from the LIKE optimization, then
  129159. ** set P3 and P5 on the OP_String opcode so that the string will be cast
  129160. ** to a BLOB at appropriate times.
  129161. **
  129162. ** The LIKE optimization trys to evaluate "x LIKE 'abc%'" as a range
  129163. ** expression: "x>='ABC' AND x<'abd'". But this requires that the range
  129164. ** scan loop run twice, once for strings and a second time for BLOBs.
  129165. ** The OP_String opcodes on the second pass convert the upper and lower
  129166. ** bound string constants to blobs. This routine makes the necessary changes
  129167. ** to the OP_String opcodes for that to happen.
  129168. **
  129169. ** Except, of course, if SQLITE_LIKE_DOESNT_MATCH_BLOBS is defined, then
  129170. ** only the one pass through the string space is required, so this routine
  129171. ** becomes a no-op.
  129172. */
  129173. static void whereLikeOptimizationStringFixup(
  129174. Vdbe *v, /* prepared statement under construction */
  129175. WhereLevel *pLevel, /* The loop that contains the LIKE operator */
  129176. WhereTerm *pTerm /* The upper or lower bound just coded */
  129177. ){
  129178. if( pTerm->wtFlags & TERM_LIKEOPT ){
  129179. VdbeOp *pOp;
  129180. assert( pLevel->iLikeRepCntr>0 );
  129181. pOp = sqlite3VdbeGetOp(v, -1);
  129182. assert( pOp!=0 );
  129183. assert( pOp->opcode==OP_String8
  129184. || pTerm->pWC->pWInfo->pParse->db->mallocFailed );
  129185. pOp->p3 = (int)(pLevel->iLikeRepCntr>>1); /* Register holding counter */
  129186. pOp->p5 = (u8)(pLevel->iLikeRepCntr&1); /* ASC or DESC */
  129187. }
  129188. }
  129189. #else
  129190. # define whereLikeOptimizationStringFixup(A,B,C)
  129191. #endif
  129192. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  129193. /*
  129194. ** Information is passed from codeCursorHint() down to individual nodes of
  129195. ** the expression tree (by sqlite3WalkExpr()) using an instance of this
  129196. ** structure.
  129197. */
  129198. struct CCurHint {
  129199. int iTabCur; /* Cursor for the main table */
  129200. int iIdxCur; /* Cursor for the index, if pIdx!=0. Unused otherwise */
  129201. Index *pIdx; /* The index used to access the table */
  129202. };
  129203. /*
  129204. ** This function is called for every node of an expression that is a candidate
  129205. ** for a cursor hint on an index cursor. For TK_COLUMN nodes that reference
  129206. ** the table CCurHint.iTabCur, verify that the same column can be
  129207. ** accessed through the index. If it cannot, then set pWalker->eCode to 1.
  129208. */
  129209. static int codeCursorHintCheckExpr(Walker *pWalker, Expr *pExpr){
  129210. struct CCurHint *pHint = pWalker->u.pCCurHint;
  129211. assert( pHint->pIdx!=0 );
  129212. if( pExpr->op==TK_COLUMN
  129213. && pExpr->iTable==pHint->iTabCur
  129214. && sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn)<0
  129215. ){
  129216. pWalker->eCode = 1;
  129217. }
  129218. return WRC_Continue;
  129219. }
  129220. /*
  129221. ** Test whether or not expression pExpr, which was part of a WHERE clause,
  129222. ** should be included in the cursor-hint for a table that is on the rhs
  129223. ** of a LEFT JOIN. Set Walker.eCode to non-zero before returning if the
  129224. ** expression is not suitable.
  129225. **
  129226. ** An expression is unsuitable if it might evaluate to non NULL even if
  129227. ** a TK_COLUMN node that does affect the value of the expression is set
  129228. ** to NULL. For example:
  129229. **
  129230. ** col IS NULL
  129231. ** col IS NOT NULL
  129232. ** coalesce(col, 1)
  129233. ** CASE WHEN col THEN 0 ELSE 1 END
  129234. */
  129235. static int codeCursorHintIsOrFunction(Walker *pWalker, Expr *pExpr){
  129236. if( pExpr->op==TK_IS
  129237. || pExpr->op==TK_ISNULL || pExpr->op==TK_ISNOT
  129238. || pExpr->op==TK_NOTNULL || pExpr->op==TK_CASE
  129239. ){
  129240. pWalker->eCode = 1;
  129241. }else if( pExpr->op==TK_FUNCTION ){
  129242. int d1;
  129243. char d2[4];
  129244. if( 0==sqlite3IsLikeFunction(pWalker->pParse->db, pExpr, &d1, d2) ){
  129245. pWalker->eCode = 1;
  129246. }
  129247. }
  129248. return WRC_Continue;
  129249. }
  129250. /*
  129251. ** This function is called on every node of an expression tree used as an
  129252. ** argument to the OP_CursorHint instruction. If the node is a TK_COLUMN
  129253. ** that accesses any table other than the one identified by
  129254. ** CCurHint.iTabCur, then do the following:
  129255. **
  129256. ** 1) allocate a register and code an OP_Column instruction to read
  129257. ** the specified column into the new register, and
  129258. **
  129259. ** 2) transform the expression node to a TK_REGISTER node that reads
  129260. ** from the newly populated register.
  129261. **
  129262. ** Also, if the node is a TK_COLUMN that does access the table idenified
  129263. ** by pCCurHint.iTabCur, and an index is being used (which we will
  129264. ** know because CCurHint.pIdx!=0) then transform the TK_COLUMN into
  129265. ** an access of the index rather than the original table.
  129266. */
  129267. static int codeCursorHintFixExpr(Walker *pWalker, Expr *pExpr){
  129268. int rc = WRC_Continue;
  129269. struct CCurHint *pHint = pWalker->u.pCCurHint;
  129270. if( pExpr->op==TK_COLUMN ){
  129271. if( pExpr->iTable!=pHint->iTabCur ){
  129272. int reg = ++pWalker->pParse->nMem; /* Register for column value */
  129273. sqlite3ExprCode(pWalker->pParse, pExpr, reg);
  129274. pExpr->op = TK_REGISTER;
  129275. pExpr->iTable = reg;
  129276. }else if( pHint->pIdx!=0 ){
  129277. pExpr->iTable = pHint->iIdxCur;
  129278. pExpr->iColumn = sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn);
  129279. assert( pExpr->iColumn>=0 );
  129280. }
  129281. }else if( pExpr->op==TK_AGG_FUNCTION ){
  129282. /* An aggregate function in the WHERE clause of a query means this must
  129283. ** be a correlated sub-query, and expression pExpr is an aggregate from
  129284. ** the parent context. Do not walk the function arguments in this case.
  129285. **
  129286. ** todo: It should be possible to replace this node with a TK_REGISTER
  129287. ** expression, as the result of the expression must be stored in a
  129288. ** register at this point. The same holds for TK_AGG_COLUMN nodes. */
  129289. rc = WRC_Prune;
  129290. }
  129291. return rc;
  129292. }
  129293. /*
  129294. ** Insert an OP_CursorHint instruction if it is appropriate to do so.
  129295. */
  129296. static void codeCursorHint(
  129297. struct SrcList_item *pTabItem, /* FROM clause item */
  129298. WhereInfo *pWInfo, /* The where clause */
  129299. WhereLevel *pLevel, /* Which loop to provide hints for */
  129300. WhereTerm *pEndRange /* Hint this end-of-scan boundary term if not NULL */
  129301. ){
  129302. Parse *pParse = pWInfo->pParse;
  129303. sqlite3 *db = pParse->db;
  129304. Vdbe *v = pParse->pVdbe;
  129305. Expr *pExpr = 0;
  129306. WhereLoop *pLoop = pLevel->pWLoop;
  129307. int iCur;
  129308. WhereClause *pWC;
  129309. WhereTerm *pTerm;
  129310. int i, j;
  129311. struct CCurHint sHint;
  129312. Walker sWalker;
  129313. if( OptimizationDisabled(db, SQLITE_CursorHints) ) return;
  129314. iCur = pLevel->iTabCur;
  129315. assert( iCur==pWInfo->pTabList->a[pLevel->iFrom].iCursor );
  129316. sHint.iTabCur = iCur;
  129317. sHint.iIdxCur = pLevel->iIdxCur;
  129318. sHint.pIdx = pLoop->u.btree.pIndex;
  129319. memset(&sWalker, 0, sizeof(sWalker));
  129320. sWalker.pParse = pParse;
  129321. sWalker.u.pCCurHint = &sHint;
  129322. pWC = &pWInfo->sWC;
  129323. for(i=0; i<pWC->nTerm; i++){
  129324. pTerm = &pWC->a[i];
  129325. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  129326. if( pTerm->prereqAll & pLevel->notReady ) continue;
  129327. /* Any terms specified as part of the ON(...) clause for any LEFT
  129328. ** JOIN for which the current table is not the rhs are omitted
  129329. ** from the cursor-hint.
  129330. **
  129331. ** If this table is the rhs of a LEFT JOIN, "IS" or "IS NULL" terms
  129332. ** that were specified as part of the WHERE clause must be excluded.
  129333. ** This is to address the following:
  129334. **
  129335. ** SELECT ... t1 LEFT JOIN t2 ON (t1.a=t2.b) WHERE t2.c IS NULL;
  129336. **
  129337. ** Say there is a single row in t2 that matches (t1.a=t2.b), but its
  129338. ** t2.c values is not NULL. If the (t2.c IS NULL) constraint is
  129339. ** pushed down to the cursor, this row is filtered out, causing
  129340. ** SQLite to synthesize a row of NULL values. Which does match the
  129341. ** WHERE clause, and so the query returns a row. Which is incorrect.
  129342. **
  129343. ** For the same reason, WHERE terms such as:
  129344. **
  129345. ** WHERE 1 = (t2.c IS NULL)
  129346. **
  129347. ** are also excluded. See codeCursorHintIsOrFunction() for details.
  129348. */
  129349. if( pTabItem->fg.jointype & JT_LEFT ){
  129350. Expr *pExpr = pTerm->pExpr;
  129351. if( !ExprHasProperty(pExpr, EP_FromJoin)
  129352. || pExpr->iRightJoinTable!=pTabItem->iCursor
  129353. ){
  129354. sWalker.eCode = 0;
  129355. sWalker.xExprCallback = codeCursorHintIsOrFunction;
  129356. sqlite3WalkExpr(&sWalker, pTerm->pExpr);
  129357. if( sWalker.eCode ) continue;
  129358. }
  129359. }else{
  129360. if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) continue;
  129361. }
  129362. /* All terms in pWLoop->aLTerm[] except pEndRange are used to initialize
  129363. ** the cursor. These terms are not needed as hints for a pure range
  129364. ** scan (that has no == terms) so omit them. */
  129365. if( pLoop->u.btree.nEq==0 && pTerm!=pEndRange ){
  129366. for(j=0; j<pLoop->nLTerm && pLoop->aLTerm[j]!=pTerm; j++){}
  129367. if( j<pLoop->nLTerm ) continue;
  129368. }
  129369. /* No subqueries or non-deterministic functions allowed */
  129370. if( sqlite3ExprContainsSubquery(pTerm->pExpr) ) continue;
  129371. /* For an index scan, make sure referenced columns are actually in
  129372. ** the index. */
  129373. if( sHint.pIdx!=0 ){
  129374. sWalker.eCode = 0;
  129375. sWalker.xExprCallback = codeCursorHintCheckExpr;
  129376. sqlite3WalkExpr(&sWalker, pTerm->pExpr);
  129377. if( sWalker.eCode ) continue;
  129378. }
  129379. /* If we survive all prior tests, that means this term is worth hinting */
  129380. pExpr = sqlite3ExprAnd(pParse, pExpr, sqlite3ExprDup(db, pTerm->pExpr, 0));
  129381. }
  129382. if( pExpr!=0 ){
  129383. sWalker.xExprCallback = codeCursorHintFixExpr;
  129384. sqlite3WalkExpr(&sWalker, pExpr);
  129385. sqlite3VdbeAddOp4(v, OP_CursorHint,
  129386. (sHint.pIdx ? sHint.iIdxCur : sHint.iTabCur), 0, 0,
  129387. (const char*)pExpr, P4_EXPR);
  129388. }
  129389. }
  129390. #else
  129391. # define codeCursorHint(A,B,C,D) /* No-op */
  129392. #endif /* SQLITE_ENABLE_CURSOR_HINTS */
  129393. /*
  129394. ** Cursor iCur is open on an intkey b-tree (a table). Register iRowid contains
  129395. ** a rowid value just read from cursor iIdxCur, open on index pIdx. This
  129396. ** function generates code to do a deferred seek of cursor iCur to the
  129397. ** rowid stored in register iRowid.
  129398. **
  129399. ** Normally, this is just:
  129400. **
  129401. ** OP_DeferredSeek $iCur $iRowid
  129402. **
  129403. ** However, if the scan currently being coded is a branch of an OR-loop and
  129404. ** the statement currently being coded is a SELECT, then P3 of OP_DeferredSeek
  129405. ** is set to iIdxCur and P4 is set to point to an array of integers
  129406. ** containing one entry for each column of the table cursor iCur is open
  129407. ** on. For each table column, if the column is the i'th column of the
  129408. ** index, then the corresponding array entry is set to (i+1). If the column
  129409. ** does not appear in the index at all, the array entry is set to 0.
  129410. */
  129411. static void codeDeferredSeek(
  129412. WhereInfo *pWInfo, /* Where clause context */
  129413. Index *pIdx, /* Index scan is using */
  129414. int iCur, /* Cursor for IPK b-tree */
  129415. int iIdxCur /* Index cursor */
  129416. ){
  129417. Parse *pParse = pWInfo->pParse; /* Parse context */
  129418. Vdbe *v = pParse->pVdbe; /* Vdbe to generate code within */
  129419. assert( iIdxCur>0 );
  129420. assert( pIdx->aiColumn[pIdx->nColumn-1]==-1 );
  129421. sqlite3VdbeAddOp3(v, OP_DeferredSeek, iIdxCur, 0, iCur);
  129422. if( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)
  129423. && DbMaskAllZero(sqlite3ParseToplevel(pParse)->writeMask)
  129424. ){
  129425. int i;
  129426. Table *pTab = pIdx->pTable;
  129427. int *ai = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int)*(pTab->nCol+1));
  129428. if( ai ){
  129429. ai[0] = pTab->nCol;
  129430. for(i=0; i<pIdx->nColumn-1; i++){
  129431. assert( pIdx->aiColumn[i]<pTab->nCol );
  129432. if( pIdx->aiColumn[i]>=0 ) ai[pIdx->aiColumn[i]+1] = i+1;
  129433. }
  129434. sqlite3VdbeChangeP4(v, -1, (char*)ai, P4_INTARRAY);
  129435. }
  129436. }
  129437. }
  129438. /*
  129439. ** If the expression passed as the second argument is a vector, generate
  129440. ** code to write the first nReg elements of the vector into an array
  129441. ** of registers starting with iReg.
  129442. **
  129443. ** If the expression is not a vector, then nReg must be passed 1. In
  129444. ** this case, generate code to evaluate the expression and leave the
  129445. ** result in register iReg.
  129446. */
  129447. static void codeExprOrVector(Parse *pParse, Expr *p, int iReg, int nReg){
  129448. assert( nReg>0 );
  129449. if( p && sqlite3ExprIsVector(p) ){
  129450. #ifndef SQLITE_OMIT_SUBQUERY
  129451. if( (p->flags & EP_xIsSelect) ){
  129452. Vdbe *v = pParse->pVdbe;
  129453. int iSelect;
  129454. assert( p->op==TK_SELECT );
  129455. iSelect = sqlite3CodeSubselect(pParse, p);
  129456. sqlite3VdbeAddOp3(v, OP_Copy, iSelect, iReg, nReg-1);
  129457. }else
  129458. #endif
  129459. {
  129460. int i;
  129461. ExprList *pList = p->x.pList;
  129462. assert( nReg<=pList->nExpr );
  129463. for(i=0; i<nReg; i++){
  129464. sqlite3ExprCode(pParse, pList->a[i].pExpr, iReg+i);
  129465. }
  129466. }
  129467. }else{
  129468. assert( nReg==1 );
  129469. sqlite3ExprCode(pParse, p, iReg);
  129470. }
  129471. }
  129472. /* An instance of the IdxExprTrans object carries information about a
  129473. ** mapping from an expression on table columns into a column in an index
  129474. ** down through the Walker.
  129475. */
  129476. typedef struct IdxExprTrans {
  129477. Expr *pIdxExpr; /* The index expression */
  129478. int iTabCur; /* The cursor of the corresponding table */
  129479. int iIdxCur; /* The cursor for the index */
  129480. int iIdxCol; /* The column for the index */
  129481. } IdxExprTrans;
  129482. /* The walker node callback used to transform matching expressions into
  129483. ** a reference to an index column for an index on an expression.
  129484. **
  129485. ** If pExpr matches, then transform it into a reference to the index column
  129486. ** that contains the value of pExpr.
  129487. */
  129488. static int whereIndexExprTransNode(Walker *p, Expr *pExpr){
  129489. IdxExprTrans *pX = p->u.pIdxTrans;
  129490. if( sqlite3ExprCompare(0, pExpr, pX->pIdxExpr, pX->iTabCur)==0 ){
  129491. pExpr->op = TK_COLUMN;
  129492. pExpr->iTable = pX->iIdxCur;
  129493. pExpr->iColumn = pX->iIdxCol;
  129494. pExpr->y.pTab = 0;
  129495. return WRC_Prune;
  129496. }else{
  129497. return WRC_Continue;
  129498. }
  129499. }
  129500. /*
  129501. ** For an indexes on expression X, locate every instance of expression X
  129502. ** in pExpr and change that subexpression into a reference to the appropriate
  129503. ** column of the index.
  129504. */
  129505. static void whereIndexExprTrans(
  129506. Index *pIdx, /* The Index */
  129507. int iTabCur, /* Cursor of the table that is being indexed */
  129508. int iIdxCur, /* Cursor of the index itself */
  129509. WhereInfo *pWInfo /* Transform expressions in this WHERE clause */
  129510. ){
  129511. int iIdxCol; /* Column number of the index */
  129512. ExprList *aColExpr; /* Expressions that are indexed */
  129513. Walker w;
  129514. IdxExprTrans x;
  129515. aColExpr = pIdx->aColExpr;
  129516. if( aColExpr==0 ) return; /* Not an index on expressions */
  129517. memset(&w, 0, sizeof(w));
  129518. w.xExprCallback = whereIndexExprTransNode;
  129519. w.u.pIdxTrans = &x;
  129520. x.iTabCur = iTabCur;
  129521. x.iIdxCur = iIdxCur;
  129522. for(iIdxCol=0; iIdxCol<aColExpr->nExpr; iIdxCol++){
  129523. if( pIdx->aiColumn[iIdxCol]!=XN_EXPR ) continue;
  129524. assert( aColExpr->a[iIdxCol].pExpr!=0 );
  129525. x.iIdxCol = iIdxCol;
  129526. x.pIdxExpr = aColExpr->a[iIdxCol].pExpr;
  129527. sqlite3WalkExpr(&w, pWInfo->pWhere);
  129528. sqlite3WalkExprList(&w, pWInfo->pOrderBy);
  129529. sqlite3WalkExprList(&w, pWInfo->pResultSet);
  129530. }
  129531. }
  129532. /*
  129533. ** The pTruth expression is always true because it is the WHERE clause
  129534. ** a partial index that is driving a query loop. Look through all of the
  129535. ** WHERE clause terms on the query, and if any of those terms must be
  129536. ** true because pTruth is true, then mark those WHERE clause terms as
  129537. ** coded.
  129538. */
  129539. static void whereApplyPartialIndexConstraints(
  129540. Expr *pTruth,
  129541. int iTabCur,
  129542. WhereClause *pWC
  129543. ){
  129544. int i;
  129545. WhereTerm *pTerm;
  129546. while( pTruth->op==TK_AND ){
  129547. whereApplyPartialIndexConstraints(pTruth->pLeft, iTabCur, pWC);
  129548. pTruth = pTruth->pRight;
  129549. }
  129550. for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  129551. Expr *pExpr;
  129552. if( pTerm->wtFlags & TERM_CODED ) continue;
  129553. pExpr = pTerm->pExpr;
  129554. if( sqlite3ExprCompare(0, pExpr, pTruth, iTabCur)==0 ){
  129555. pTerm->wtFlags |= TERM_CODED;
  129556. }
  129557. }
  129558. }
  129559. /*
  129560. ** Generate code for the start of the iLevel-th loop in the WHERE clause
  129561. ** implementation described by pWInfo.
  129562. */
  129563. SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
  129564. Parse *pParse, /* Parsing context */
  129565. Vdbe *v, /* Prepared statement under construction */
  129566. WhereInfo *pWInfo, /* Complete information about the WHERE clause */
  129567. int iLevel, /* Which level of pWInfo->a[] should be coded */
  129568. WhereLevel *pLevel, /* The current level pointer */
  129569. Bitmask notReady /* Which tables are currently available */
  129570. ){
  129571. int j, k; /* Loop counters */
  129572. int iCur; /* The VDBE cursor for the table */
  129573. int addrNxt; /* Where to jump to continue with the next IN case */
  129574. int bRev; /* True if we need to scan in reverse order */
  129575. WhereLoop *pLoop; /* The WhereLoop object being coded */
  129576. WhereClause *pWC; /* Decomposition of the entire WHERE clause */
  129577. WhereTerm *pTerm; /* A WHERE clause term */
  129578. sqlite3 *db; /* Database connection */
  129579. struct SrcList_item *pTabItem; /* FROM clause term being coded */
  129580. int addrBrk; /* Jump here to break out of the loop */
  129581. int addrHalt; /* addrBrk for the outermost loop */
  129582. int addrCont; /* Jump here to continue with next cycle */
  129583. int iRowidReg = 0; /* Rowid is stored in this register, if not zero */
  129584. int iReleaseReg = 0; /* Temp register to free before returning */
  129585. Index *pIdx = 0; /* Index used by loop (if any) */
  129586. int iLoop; /* Iteration of constraint generator loop */
  129587. pWC = &pWInfo->sWC;
  129588. db = pParse->db;
  129589. pLoop = pLevel->pWLoop;
  129590. pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
  129591. iCur = pTabItem->iCursor;
  129592. pLevel->notReady = notReady & ~sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur);
  129593. bRev = (pWInfo->revMask>>iLevel)&1;
  129594. VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName));
  129595. /* Create labels for the "break" and "continue" instructions
  129596. ** for the current loop. Jump to addrBrk to break out of a loop.
  129597. ** Jump to cont to go immediately to the next iteration of the
  129598. ** loop.
  129599. **
  129600. ** When there is an IN operator, we also have a "addrNxt" label that
  129601. ** means to continue with the next IN value combination. When
  129602. ** there are no IN operators in the constraints, the "addrNxt" label
  129603. ** is the same as "addrBrk".
  129604. */
  129605. addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(pParse);
  129606. addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(pParse);
  129607. /* If this is the right table of a LEFT OUTER JOIN, allocate and
  129608. ** initialize a memory cell that records if this table matches any
  129609. ** row of the left table of the join.
  129610. */
  129611. assert( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)
  129612. || pLevel->iFrom>0 || (pTabItem[0].fg.jointype & JT_LEFT)==0
  129613. );
  129614. if( pLevel->iFrom>0 && (pTabItem[0].fg.jointype & JT_LEFT)!=0 ){
  129615. pLevel->iLeftJoin = ++pParse->nMem;
  129616. sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
  129617. VdbeComment((v, "init LEFT JOIN no-match flag"));
  129618. }
  129619. /* Compute a safe address to jump to if we discover that the table for
  129620. ** this loop is empty and can never contribute content. */
  129621. for(j=iLevel; j>0 && pWInfo->a[j].iLeftJoin==0; j--){}
  129622. addrHalt = pWInfo->a[j].addrBrk;
  129623. /* Special case of a FROM clause subquery implemented as a co-routine */
  129624. if( pTabItem->fg.viaCoroutine ){
  129625. int regYield = pTabItem->regReturn;
  129626. sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
  129627. pLevel->p2 = sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk);
  129628. VdbeCoverage(v);
  129629. VdbeComment((v, "next row of %s", pTabItem->pTab->zName));
  129630. pLevel->op = OP_Goto;
  129631. }else
  129632. #ifndef SQLITE_OMIT_VIRTUALTABLE
  129633. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
  129634. /* Case 1: The table is a virtual-table. Use the VFilter and VNext
  129635. ** to access the data.
  129636. */
  129637. int iReg; /* P3 Value for OP_VFilter */
  129638. int addrNotFound;
  129639. int nConstraint = pLoop->nLTerm;
  129640. int iIn; /* Counter for IN constraints */
  129641. iReg = sqlite3GetTempRange(pParse, nConstraint+2);
  129642. addrNotFound = pLevel->addrBrk;
  129643. for(j=0; j<nConstraint; j++){
  129644. int iTarget = iReg+j+2;
  129645. pTerm = pLoop->aLTerm[j];
  129646. if( NEVER(pTerm==0) ) continue;
  129647. if( pTerm->eOperator & WO_IN ){
  129648. codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
  129649. addrNotFound = pLevel->addrNxt;
  129650. }else{
  129651. Expr *pRight = pTerm->pExpr->pRight;
  129652. codeExprOrVector(pParse, pRight, iTarget, 1);
  129653. }
  129654. }
  129655. sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
  129656. sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
  129657. sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
  129658. pLoop->u.vtab.idxStr,
  129659. pLoop->u.vtab.needFree ? P4_DYNAMIC : P4_STATIC);
  129660. VdbeCoverage(v);
  129661. pLoop->u.vtab.needFree = 0;
  129662. pLevel->p1 = iCur;
  129663. pLevel->op = pWInfo->eOnePass ? OP_Noop : OP_VNext;
  129664. pLevel->p2 = sqlite3VdbeCurrentAddr(v);
  129665. iIn = pLevel->u.in.nIn;
  129666. for(j=nConstraint-1; j>=0; j--){
  129667. pTerm = pLoop->aLTerm[j];
  129668. if( j<16 && (pLoop->u.vtab.omitMask>>j)&1 ){
  129669. disableTerm(pLevel, pTerm);
  129670. }else if( (pTerm->eOperator & WO_IN)!=0 ){
  129671. Expr *pCompare; /* The comparison operator */
  129672. Expr *pRight; /* RHS of the comparison */
  129673. VdbeOp *pOp; /* Opcode to access the value of the IN constraint */
  129674. /* Reload the constraint value into reg[iReg+j+2]. The same value
  129675. ** was loaded into the same register prior to the OP_VFilter, but
  129676. ** the xFilter implementation might have changed the datatype or
  129677. ** encoding of the value in the register, so it *must* be reloaded. */
  129678. assert( pLevel->u.in.aInLoop!=0 || db->mallocFailed );
  129679. if( !db->mallocFailed ){
  129680. assert( iIn>0 );
  129681. pOp = sqlite3VdbeGetOp(v, pLevel->u.in.aInLoop[--iIn].addrInTop);
  129682. assert( pOp->opcode==OP_Column || pOp->opcode==OP_Rowid );
  129683. assert( pOp->opcode!=OP_Column || pOp->p3==iReg+j+2 );
  129684. assert( pOp->opcode!=OP_Rowid || pOp->p2==iReg+j+2 );
  129685. testcase( pOp->opcode==OP_Rowid );
  129686. sqlite3VdbeAddOp3(v, pOp->opcode, pOp->p1, pOp->p2, pOp->p3);
  129687. }
  129688. /* Generate code that will continue to the next row if
  129689. ** the IN constraint is not satisfied */
  129690. pCompare = sqlite3PExpr(pParse, TK_EQ, 0, 0);
  129691. assert( pCompare!=0 || db->mallocFailed );
  129692. if( pCompare ){
  129693. pCompare->pLeft = pTerm->pExpr->pLeft;
  129694. pCompare->pRight = pRight = sqlite3Expr(db, TK_REGISTER, 0);
  129695. if( pRight ){
  129696. pRight->iTable = iReg+j+2;
  129697. sqlite3ExprIfFalse(pParse, pCompare, pLevel->addrCont, 0);
  129698. }
  129699. pCompare->pLeft = 0;
  129700. sqlite3ExprDelete(db, pCompare);
  129701. }
  129702. }
  129703. }
  129704. /* These registers need to be preserved in case there is an IN operator
  129705. ** loop. So we could deallocate the registers here (and potentially
  129706. ** reuse them later) if (pLoop->wsFlags & WHERE_IN_ABLE)==0. But it seems
  129707. ** simpler and safer to simply not reuse the registers.
  129708. **
  129709. ** sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
  129710. */
  129711. }else
  129712. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  129713. if( (pLoop->wsFlags & WHERE_IPK)!=0
  129714. && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
  129715. ){
  129716. /* Case 2: We can directly reference a single row using an
  129717. ** equality comparison against the ROWID field. Or
  129718. ** we reference multiple rows using a "rowid IN (...)"
  129719. ** construct.
  129720. */
  129721. assert( pLoop->u.btree.nEq==1 );
  129722. pTerm = pLoop->aLTerm[0];
  129723. assert( pTerm!=0 );
  129724. assert( pTerm->pExpr!=0 );
  129725. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  129726. iReleaseReg = ++pParse->nMem;
  129727. iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
  129728. if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg);
  129729. addrNxt = pLevel->addrNxt;
  129730. sqlite3VdbeAddOp3(v, OP_SeekRowid, iCur, addrNxt, iRowidReg);
  129731. VdbeCoverage(v);
  129732. pLevel->op = OP_Noop;
  129733. if( (pTerm->prereqAll & pLevel->notReady)==0 ){
  129734. pTerm->wtFlags |= TERM_CODED;
  129735. }
  129736. }else if( (pLoop->wsFlags & WHERE_IPK)!=0
  129737. && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
  129738. ){
  129739. /* Case 3: We have an inequality comparison against the ROWID field.
  129740. */
  129741. int testOp = OP_Noop;
  129742. int start;
  129743. int memEndValue = 0;
  129744. WhereTerm *pStart, *pEnd;
  129745. j = 0;
  129746. pStart = pEnd = 0;
  129747. if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
  129748. if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
  129749. assert( pStart!=0 || pEnd!=0 );
  129750. if( bRev ){
  129751. pTerm = pStart;
  129752. pStart = pEnd;
  129753. pEnd = pTerm;
  129754. }
  129755. codeCursorHint(pTabItem, pWInfo, pLevel, pEnd);
  129756. if( pStart ){
  129757. Expr *pX; /* The expression that defines the start bound */
  129758. int r1, rTemp; /* Registers for holding the start boundary */
  129759. int op; /* Cursor seek operation */
  129760. /* The following constant maps TK_xx codes into corresponding
  129761. ** seek opcodes. It depends on a particular ordering of TK_xx
  129762. */
  129763. const u8 aMoveOp[] = {
  129764. /* TK_GT */ OP_SeekGT,
  129765. /* TK_LE */ OP_SeekLE,
  129766. /* TK_LT */ OP_SeekLT,
  129767. /* TK_GE */ OP_SeekGE
  129768. };
  129769. assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */
  129770. assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */
  129771. assert( TK_GE==TK_GT+3 ); /* ... is correcct. */
  129772. assert( (pStart->wtFlags & TERM_VNULL)==0 );
  129773. testcase( pStart->wtFlags & TERM_VIRTUAL );
  129774. pX = pStart->pExpr;
  129775. assert( pX!=0 );
  129776. testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
  129777. if( sqlite3ExprIsVector(pX->pRight) ){
  129778. r1 = rTemp = sqlite3GetTempReg(pParse);
  129779. codeExprOrVector(pParse, pX->pRight, r1, 1);
  129780. testcase( pX->op==TK_GT );
  129781. testcase( pX->op==TK_GE );
  129782. testcase( pX->op==TK_LT );
  129783. testcase( pX->op==TK_LE );
  129784. op = aMoveOp[((pX->op - TK_GT - 1) & 0x3) | 0x1];
  129785. assert( pX->op!=TK_GT || op==OP_SeekGE );
  129786. assert( pX->op!=TK_GE || op==OP_SeekGE );
  129787. assert( pX->op!=TK_LT || op==OP_SeekLE );
  129788. assert( pX->op!=TK_LE || op==OP_SeekLE );
  129789. }else{
  129790. r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
  129791. disableTerm(pLevel, pStart);
  129792. op = aMoveOp[(pX->op - TK_GT)];
  129793. }
  129794. sqlite3VdbeAddOp3(v, op, iCur, addrBrk, r1);
  129795. VdbeComment((v, "pk"));
  129796. VdbeCoverageIf(v, pX->op==TK_GT);
  129797. VdbeCoverageIf(v, pX->op==TK_LE);
  129798. VdbeCoverageIf(v, pX->op==TK_LT);
  129799. VdbeCoverageIf(v, pX->op==TK_GE);
  129800. sqlite3ReleaseTempReg(pParse, rTemp);
  129801. }else{
  129802. sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrHalt);
  129803. VdbeCoverageIf(v, bRev==0);
  129804. VdbeCoverageIf(v, bRev!=0);
  129805. }
  129806. if( pEnd ){
  129807. Expr *pX;
  129808. pX = pEnd->pExpr;
  129809. assert( pX!=0 );
  129810. assert( (pEnd->wtFlags & TERM_VNULL)==0 );
  129811. testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
  129812. testcase( pEnd->wtFlags & TERM_VIRTUAL );
  129813. memEndValue = ++pParse->nMem;
  129814. codeExprOrVector(pParse, pX->pRight, memEndValue, 1);
  129815. if( 0==sqlite3ExprIsVector(pX->pRight)
  129816. && (pX->op==TK_LT || pX->op==TK_GT)
  129817. ){
  129818. testOp = bRev ? OP_Le : OP_Ge;
  129819. }else{
  129820. testOp = bRev ? OP_Lt : OP_Gt;
  129821. }
  129822. if( 0==sqlite3ExprIsVector(pX->pRight) ){
  129823. disableTerm(pLevel, pEnd);
  129824. }
  129825. }
  129826. start = sqlite3VdbeCurrentAddr(v);
  129827. pLevel->op = bRev ? OP_Prev : OP_Next;
  129828. pLevel->p1 = iCur;
  129829. pLevel->p2 = start;
  129830. assert( pLevel->p5==0 );
  129831. if( testOp!=OP_Noop ){
  129832. iRowidReg = ++pParse->nMem;
  129833. sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
  129834. sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
  129835. VdbeCoverageIf(v, testOp==OP_Le);
  129836. VdbeCoverageIf(v, testOp==OP_Lt);
  129837. VdbeCoverageIf(v, testOp==OP_Ge);
  129838. VdbeCoverageIf(v, testOp==OP_Gt);
  129839. sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
  129840. }
  129841. }else if( pLoop->wsFlags & WHERE_INDEXED ){
  129842. /* Case 4: A scan using an index.
  129843. **
  129844. ** The WHERE clause may contain zero or more equality
  129845. ** terms ("==" or "IN" operators) that refer to the N
  129846. ** left-most columns of the index. It may also contain
  129847. ** inequality constraints (>, <, >= or <=) on the indexed
  129848. ** column that immediately follows the N equalities. Only
  129849. ** the right-most column can be an inequality - the rest must
  129850. ** use the "==" and "IN" operators. For example, if the
  129851. ** index is on (x,y,z), then the following clauses are all
  129852. ** optimized:
  129853. **
  129854. ** x=5
  129855. ** x=5 AND y=10
  129856. ** x=5 AND y<10
  129857. ** x=5 AND y>5 AND y<10
  129858. ** x=5 AND y=5 AND z<=10
  129859. **
  129860. ** The z<10 term of the following cannot be used, only
  129861. ** the x=5 term:
  129862. **
  129863. ** x=5 AND z<10
  129864. **
  129865. ** N may be zero if there are inequality constraints.
  129866. ** If there are no inequality constraints, then N is at
  129867. ** least one.
  129868. **
  129869. ** This case is also used when there are no WHERE clause
  129870. ** constraints but an index is selected anyway, in order
  129871. ** to force the output order to conform to an ORDER BY.
  129872. */
  129873. static const u8 aStartOp[] = {
  129874. 0,
  129875. 0,
  129876. OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */
  129877. OP_Last, /* 3: (!start_constraints && startEq && bRev) */
  129878. OP_SeekGT, /* 4: (start_constraints && !startEq && !bRev) */
  129879. OP_SeekLT, /* 5: (start_constraints && !startEq && bRev) */
  129880. OP_SeekGE, /* 6: (start_constraints && startEq && !bRev) */
  129881. OP_SeekLE /* 7: (start_constraints && startEq && bRev) */
  129882. };
  129883. static const u8 aEndOp[] = {
  129884. OP_IdxGE, /* 0: (end_constraints && !bRev && !endEq) */
  129885. OP_IdxGT, /* 1: (end_constraints && !bRev && endEq) */
  129886. OP_IdxLE, /* 2: (end_constraints && bRev && !endEq) */
  129887. OP_IdxLT, /* 3: (end_constraints && bRev && endEq) */
  129888. };
  129889. u16 nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */
  129890. u16 nBtm = pLoop->u.btree.nBtm; /* Length of BTM vector */
  129891. u16 nTop = pLoop->u.btree.nTop; /* Length of TOP vector */
  129892. int regBase; /* Base register holding constraint values */
  129893. WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
  129894. WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
  129895. int startEq; /* True if range start uses ==, >= or <= */
  129896. int endEq; /* True if range end uses ==, >= or <= */
  129897. int start_constraints; /* Start of range is constrained */
  129898. int nConstraint; /* Number of constraint terms */
  129899. int iIdxCur; /* The VDBE cursor for the index */
  129900. int nExtraReg = 0; /* Number of extra registers needed */
  129901. int op; /* Instruction opcode */
  129902. char *zStartAff; /* Affinity for start of range constraint */
  129903. char *zEndAff = 0; /* Affinity for end of range constraint */
  129904. u8 bSeekPastNull = 0; /* True to seek past initial nulls */
  129905. u8 bStopAtNull = 0; /* Add condition to terminate at NULLs */
  129906. int omitTable; /* True if we use the index only */
  129907. pIdx = pLoop->u.btree.pIndex;
  129908. iIdxCur = pLevel->iIdxCur;
  129909. assert( nEq>=pLoop->nSkip );
  129910. /* If this loop satisfies a sort order (pOrderBy) request that
  129911. ** was passed to this function to implement a "SELECT min(x) ..."
  129912. ** query, then the caller will only allow the loop to run for
  129913. ** a single iteration. This means that the first row returned
  129914. ** should not have a NULL value stored in 'x'. If column 'x' is
  129915. ** the first one after the nEq equality constraints in the index,
  129916. ** this requires some special handling.
  129917. */
  129918. assert( pWInfo->pOrderBy==0
  129919. || pWInfo->pOrderBy->nExpr==1
  129920. || (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 );
  129921. if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
  129922. && pWInfo->nOBSat>0
  129923. && (pIdx->nKeyCol>nEq)
  129924. ){
  129925. assert( pLoop->nSkip==0 );
  129926. bSeekPastNull = 1;
  129927. nExtraReg = 1;
  129928. }
  129929. /* Find any inequality constraint terms for the start and end
  129930. ** of the range.
  129931. */
  129932. j = nEq;
  129933. if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
  129934. pRangeStart = pLoop->aLTerm[j++];
  129935. nExtraReg = MAX(nExtraReg, pLoop->u.btree.nBtm);
  129936. /* Like optimization range constraints always occur in pairs */
  129937. assert( (pRangeStart->wtFlags & TERM_LIKEOPT)==0 ||
  129938. (pLoop->wsFlags & WHERE_TOP_LIMIT)!=0 );
  129939. }
  129940. if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
  129941. pRangeEnd = pLoop->aLTerm[j++];
  129942. nExtraReg = MAX(nExtraReg, pLoop->u.btree.nTop);
  129943. #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  129944. if( (pRangeEnd->wtFlags & TERM_LIKEOPT)!=0 ){
  129945. assert( pRangeStart!=0 ); /* LIKE opt constraints */
  129946. assert( pRangeStart->wtFlags & TERM_LIKEOPT ); /* occur in pairs */
  129947. pLevel->iLikeRepCntr = (u32)++pParse->nMem;
  129948. sqlite3VdbeAddOp2(v, OP_Integer, 1, (int)pLevel->iLikeRepCntr);
  129949. VdbeComment((v, "LIKE loop counter"));
  129950. pLevel->addrLikeRep = sqlite3VdbeCurrentAddr(v);
  129951. /* iLikeRepCntr actually stores 2x the counter register number. The
  129952. ** bottom bit indicates whether the search order is ASC or DESC. */
  129953. testcase( bRev );
  129954. testcase( pIdx->aSortOrder[nEq]==SQLITE_SO_DESC );
  129955. assert( (bRev & ~1)==0 );
  129956. pLevel->iLikeRepCntr <<=1;
  129957. pLevel->iLikeRepCntr |= bRev ^ (pIdx->aSortOrder[nEq]==SQLITE_SO_DESC);
  129958. }
  129959. #endif
  129960. if( pRangeStart==0 ){
  129961. j = pIdx->aiColumn[nEq];
  129962. if( (j>=0 && pIdx->pTable->aCol[j].notNull==0) || j==XN_EXPR ){
  129963. bSeekPastNull = 1;
  129964. }
  129965. }
  129966. }
  129967. assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 );
  129968. /* If we are doing a reverse order scan on an ascending index, or
  129969. ** a forward order scan on a descending index, interchange the
  129970. ** start and end terms (pRangeStart and pRangeEnd).
  129971. */
  129972. if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
  129973. || (bRev && pIdx->nKeyCol==nEq)
  129974. ){
  129975. SWAP(WhereTerm *, pRangeEnd, pRangeStart);
  129976. SWAP(u8, bSeekPastNull, bStopAtNull);
  129977. SWAP(u8, nBtm, nTop);
  129978. }
  129979. /* Generate code to evaluate all constraint terms using == or IN
  129980. ** and store the values of those terms in an array of registers
  129981. ** starting at regBase.
  129982. */
  129983. codeCursorHint(pTabItem, pWInfo, pLevel, pRangeEnd);
  129984. regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
  129985. assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq );
  129986. if( zStartAff && nTop ){
  129987. zEndAff = sqlite3DbStrDup(db, &zStartAff[nEq]);
  129988. }
  129989. addrNxt = pLevel->addrNxt;
  129990. testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
  129991. testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
  129992. testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
  129993. testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
  129994. startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
  129995. endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
  129996. start_constraints = pRangeStart || nEq>0;
  129997. /* Seek the index cursor to the start of the range. */
  129998. nConstraint = nEq;
  129999. if( pRangeStart ){
  130000. Expr *pRight = pRangeStart->pExpr->pRight;
  130001. codeExprOrVector(pParse, pRight, regBase+nEq, nBtm);
  130002. whereLikeOptimizationStringFixup(v, pLevel, pRangeStart);
  130003. if( (pRangeStart->wtFlags & TERM_VNULL)==0
  130004. && sqlite3ExprCanBeNull(pRight)
  130005. ){
  130006. sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
  130007. VdbeCoverage(v);
  130008. }
  130009. if( zStartAff ){
  130010. updateRangeAffinityStr(pRight, nBtm, &zStartAff[nEq]);
  130011. }
  130012. nConstraint += nBtm;
  130013. testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
  130014. if( sqlite3ExprIsVector(pRight)==0 ){
  130015. disableTerm(pLevel, pRangeStart);
  130016. }else{
  130017. startEq = 1;
  130018. }
  130019. bSeekPastNull = 0;
  130020. }else if( bSeekPastNull ){
  130021. sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
  130022. nConstraint++;
  130023. startEq = 0;
  130024. start_constraints = 1;
  130025. }
  130026. codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff);
  130027. if( pLoop->nSkip>0 && nConstraint==pLoop->nSkip ){
  130028. /* The skip-scan logic inside the call to codeAllEqualityConstraints()
  130029. ** above has already left the cursor sitting on the correct row,
  130030. ** so no further seeking is needed */
  130031. }else{
  130032. if( pLoop->wsFlags & WHERE_IN_EARLYOUT ){
  130033. sqlite3VdbeAddOp1(v, OP_SeekHit, iIdxCur);
  130034. }
  130035. op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
  130036. assert( op!=0 );
  130037. sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
  130038. VdbeCoverage(v);
  130039. VdbeCoverageIf(v, op==OP_Rewind); testcase( op==OP_Rewind );
  130040. VdbeCoverageIf(v, op==OP_Last); testcase( op==OP_Last );
  130041. VdbeCoverageIf(v, op==OP_SeekGT); testcase( op==OP_SeekGT );
  130042. VdbeCoverageIf(v, op==OP_SeekGE); testcase( op==OP_SeekGE );
  130043. VdbeCoverageIf(v, op==OP_SeekLE); testcase( op==OP_SeekLE );
  130044. VdbeCoverageIf(v, op==OP_SeekLT); testcase( op==OP_SeekLT );
  130045. }
  130046. /* Load the value for the inequality constraint at the end of the
  130047. ** range (if any).
  130048. */
  130049. nConstraint = nEq;
  130050. if( pRangeEnd ){
  130051. Expr *pRight = pRangeEnd->pExpr->pRight;
  130052. codeExprOrVector(pParse, pRight, regBase+nEq, nTop);
  130053. whereLikeOptimizationStringFixup(v, pLevel, pRangeEnd);
  130054. if( (pRangeEnd->wtFlags & TERM_VNULL)==0
  130055. && sqlite3ExprCanBeNull(pRight)
  130056. ){
  130057. sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
  130058. VdbeCoverage(v);
  130059. }
  130060. if( zEndAff ){
  130061. updateRangeAffinityStr(pRight, nTop, zEndAff);
  130062. codeApplyAffinity(pParse, regBase+nEq, nTop, zEndAff);
  130063. }else{
  130064. assert( pParse->db->mallocFailed );
  130065. }
  130066. nConstraint += nTop;
  130067. testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
  130068. if( sqlite3ExprIsVector(pRight)==0 ){
  130069. disableTerm(pLevel, pRangeEnd);
  130070. }else{
  130071. endEq = 1;
  130072. }
  130073. }else if( bStopAtNull ){
  130074. sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
  130075. endEq = 0;
  130076. nConstraint++;
  130077. }
  130078. sqlite3DbFree(db, zStartAff);
  130079. sqlite3DbFree(db, zEndAff);
  130080. /* Top of the loop body */
  130081. pLevel->p2 = sqlite3VdbeCurrentAddr(v);
  130082. /* Check if the index cursor is past the end of the range. */
  130083. if( nConstraint ){
  130084. op = aEndOp[bRev*2 + endEq];
  130085. sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
  130086. testcase( op==OP_IdxGT ); VdbeCoverageIf(v, op==OP_IdxGT );
  130087. testcase( op==OP_IdxGE ); VdbeCoverageIf(v, op==OP_IdxGE );
  130088. testcase( op==OP_IdxLT ); VdbeCoverageIf(v, op==OP_IdxLT );
  130089. testcase( op==OP_IdxLE ); VdbeCoverageIf(v, op==OP_IdxLE );
  130090. }
  130091. if( pLoop->wsFlags & WHERE_IN_EARLYOUT ){
  130092. sqlite3VdbeAddOp2(v, OP_SeekHit, iIdxCur, 1);
  130093. }
  130094. /* Seek the table cursor, if required */
  130095. omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
  130096. && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0;
  130097. if( omitTable ){
  130098. /* pIdx is a covering index. No need to access the main table. */
  130099. }else if( HasRowid(pIdx->pTable) ){
  130100. if( (pWInfo->wctrlFlags & WHERE_SEEK_TABLE) || (
  130101. (pWInfo->wctrlFlags & WHERE_SEEK_UNIQ_TABLE)
  130102. && (pWInfo->eOnePass==ONEPASS_SINGLE)
  130103. )){
  130104. iRowidReg = ++pParse->nMem;
  130105. sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
  130106. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, iRowidReg);
  130107. VdbeCoverage(v);
  130108. }else{
  130109. codeDeferredSeek(pWInfo, pIdx, iCur, iIdxCur);
  130110. }
  130111. }else if( iCur!=iIdxCur ){
  130112. Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
  130113. iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
  130114. for(j=0; j<pPk->nKeyCol; j++){
  130115. k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
  130116. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j);
  130117. }
  130118. sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont,
  130119. iRowidReg, pPk->nKeyCol); VdbeCoverage(v);
  130120. }
  130121. /* If pIdx is an index on one or more expressions, then look through
  130122. ** all the expressions in pWInfo and try to transform matching expressions
  130123. ** into reference to index columns.
  130124. **
  130125. ** Do not do this for the RHS of a LEFT JOIN. This is because the
  130126. ** expression may be evaluated after OP_NullRow has been executed on
  130127. ** the cursor. In this case it is important to do the full evaluation,
  130128. ** as the result of the expression may not be NULL, even if all table
  130129. ** column values are. https://www.sqlite.org/src/info/7fa8049685b50b5a
  130130. **
  130131. ** Also, do not do this when processing one index an a multi-index
  130132. ** OR clause, since the transformation will become invalid once we
  130133. ** move forward to the next index.
  130134. ** https://sqlite.org/src/info/4e8e4857d32d401f
  130135. */
  130136. if( pLevel->iLeftJoin==0 && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0 ){
  130137. whereIndexExprTrans(pIdx, iCur, iIdxCur, pWInfo);
  130138. }
  130139. /* If a partial index is driving the loop, try to eliminate WHERE clause
  130140. ** terms from the query that must be true due to the WHERE clause of
  130141. ** the partial index
  130142. */
  130143. if( pIdx->pPartIdxWhere ){
  130144. whereApplyPartialIndexConstraints(pIdx->pPartIdxWhere, iCur, pWC);
  130145. }
  130146. /* Record the instruction used to terminate the loop. */
  130147. if( pLoop->wsFlags & WHERE_ONEROW ){
  130148. pLevel->op = OP_Noop;
  130149. }else if( bRev ){
  130150. pLevel->op = OP_Prev;
  130151. }else{
  130152. pLevel->op = OP_Next;
  130153. }
  130154. pLevel->p1 = iIdxCur;
  130155. pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0;
  130156. if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
  130157. pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
  130158. }else{
  130159. assert( pLevel->p5==0 );
  130160. }
  130161. if( omitTable ) pIdx = 0;
  130162. }else
  130163. #ifndef SQLITE_OMIT_OR_OPTIMIZATION
  130164. if( pLoop->wsFlags & WHERE_MULTI_OR ){
  130165. /* Case 5: Two or more separately indexed terms connected by OR
  130166. **
  130167. ** Example:
  130168. **
  130169. ** CREATE TABLE t1(a,b,c,d);
  130170. ** CREATE INDEX i1 ON t1(a);
  130171. ** CREATE INDEX i2 ON t1(b);
  130172. ** CREATE INDEX i3 ON t1(c);
  130173. **
  130174. ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
  130175. **
  130176. ** In the example, there are three indexed terms connected by OR.
  130177. ** The top of the loop looks like this:
  130178. **
  130179. ** Null 1 # Zero the rowset in reg 1
  130180. **
  130181. ** Then, for each indexed term, the following. The arguments to
  130182. ** RowSetTest are such that the rowid of the current row is inserted
  130183. ** into the RowSet. If it is already present, control skips the
  130184. ** Gosub opcode and jumps straight to the code generated by WhereEnd().
  130185. **
  130186. ** sqlite3WhereBegin(<term>)
  130187. ** RowSetTest # Insert rowid into rowset
  130188. ** Gosub 2 A
  130189. ** sqlite3WhereEnd()
  130190. **
  130191. ** Following the above, code to terminate the loop. Label A, the target
  130192. ** of the Gosub above, jumps to the instruction right after the Goto.
  130193. **
  130194. ** Null 1 # Zero the rowset in reg 1
  130195. ** Goto B # The loop is finished.
  130196. **
  130197. ** A: <loop body> # Return data, whatever.
  130198. **
  130199. ** Return 2 # Jump back to the Gosub
  130200. **
  130201. ** B: <after the loop>
  130202. **
  130203. ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then
  130204. ** use an ephemeral index instead of a RowSet to record the primary
  130205. ** keys of the rows we have already seen.
  130206. **
  130207. */
  130208. WhereClause *pOrWc; /* The OR-clause broken out into subterms */
  130209. SrcList *pOrTab; /* Shortened table list or OR-clause generation */
  130210. Index *pCov = 0; /* Potential covering index (or NULL) */
  130211. int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */
  130212. int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */
  130213. int regRowset = 0; /* Register for RowSet object */
  130214. int regRowid = 0; /* Register holding rowid */
  130215. int iLoopBody = sqlite3VdbeMakeLabel(pParse);/* Start of loop body */
  130216. int iRetInit; /* Address of regReturn init */
  130217. int untestedTerms = 0; /* Some terms not completely tested */
  130218. int ii; /* Loop counter */
  130219. u16 wctrlFlags; /* Flags for sub-WHERE clause */
  130220. Expr *pAndExpr = 0; /* An ".. AND (...)" expression */
  130221. Table *pTab = pTabItem->pTab;
  130222. pTerm = pLoop->aLTerm[0];
  130223. assert( pTerm!=0 );
  130224. assert( pTerm->eOperator & WO_OR );
  130225. assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
  130226. pOrWc = &pTerm->u.pOrInfo->wc;
  130227. pLevel->op = OP_Return;
  130228. pLevel->p1 = regReturn;
  130229. /* Set up a new SrcList in pOrTab containing the table being scanned
  130230. ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
  130231. ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
  130232. */
  130233. if( pWInfo->nLevel>1 ){
  130234. int nNotReady; /* The number of notReady tables */
  130235. struct SrcList_item *origSrc; /* Original list of tables */
  130236. nNotReady = pWInfo->nLevel - iLevel - 1;
  130237. pOrTab = sqlite3StackAllocRaw(db,
  130238. sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
  130239. if( pOrTab==0 ) return notReady;
  130240. pOrTab->nAlloc = (u8)(nNotReady + 1);
  130241. pOrTab->nSrc = pOrTab->nAlloc;
  130242. memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
  130243. origSrc = pWInfo->pTabList->a;
  130244. for(k=1; k<=nNotReady; k++){
  130245. memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
  130246. }
  130247. }else{
  130248. pOrTab = pWInfo->pTabList;
  130249. }
  130250. /* Initialize the rowset register to contain NULL. An SQL NULL is
  130251. ** equivalent to an empty rowset. Or, create an ephemeral index
  130252. ** capable of holding primary keys in the case of a WITHOUT ROWID.
  130253. **
  130254. ** Also initialize regReturn to contain the address of the instruction
  130255. ** immediately following the OP_Return at the bottom of the loop. This
  130256. ** is required in a few obscure LEFT JOIN cases where control jumps
  130257. ** over the top of the loop into the body of it. In this case the
  130258. ** correct response for the end-of-loop code (the OP_Return) is to
  130259. ** fall through to the next instruction, just as an OP_Next does if
  130260. ** called on an uninitialized cursor.
  130261. */
  130262. if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
  130263. if( HasRowid(pTab) ){
  130264. regRowset = ++pParse->nMem;
  130265. sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
  130266. }else{
  130267. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  130268. regRowset = pParse->nTab++;
  130269. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol);
  130270. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  130271. }
  130272. regRowid = ++pParse->nMem;
  130273. }
  130274. iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
  130275. /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y
  130276. ** Then for every term xN, evaluate as the subexpression: xN AND z
  130277. ** That way, terms in y that are factored into the disjunction will
  130278. ** be picked up by the recursive calls to sqlite3WhereBegin() below.
  130279. **
  130280. ** Actually, each subexpression is converted to "xN AND w" where w is
  130281. ** the "interesting" terms of z - terms that did not originate in the
  130282. ** ON or USING clause of a LEFT JOIN, and terms that are usable as
  130283. ** indices.
  130284. **
  130285. ** This optimization also only applies if the (x1 OR x2 OR ...) term
  130286. ** is not contained in the ON clause of a LEFT JOIN.
  130287. ** See ticket http://www.sqlite.org/src/info/f2369304e4
  130288. */
  130289. if( pWC->nTerm>1 ){
  130290. int iTerm;
  130291. for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
  130292. Expr *pExpr = pWC->a[iTerm].pExpr;
  130293. if( &pWC->a[iTerm] == pTerm ) continue;
  130294. testcase( pWC->a[iTerm].wtFlags & TERM_VIRTUAL );
  130295. testcase( pWC->a[iTerm].wtFlags & TERM_CODED );
  130296. if( (pWC->a[iTerm].wtFlags & (TERM_VIRTUAL|TERM_CODED))!=0 ) continue;
  130297. if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
  130298. testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO );
  130299. pExpr = sqlite3ExprDup(db, pExpr, 0);
  130300. pAndExpr = sqlite3ExprAnd(pParse, pAndExpr, pExpr);
  130301. }
  130302. if( pAndExpr ){
  130303. /* The extra 0x10000 bit on the opcode is masked off and does not
  130304. ** become part of the new Expr.op. However, it does make the
  130305. ** op==TK_AND comparison inside of sqlite3PExpr() false, and this
  130306. ** prevents sqlite3PExpr() from implementing AND short-circuit
  130307. ** optimization, which we do not want here. */
  130308. pAndExpr = sqlite3PExpr(pParse, TK_AND|0x10000, 0, pAndExpr);
  130309. }
  130310. }
  130311. /* Run a separate WHERE clause for each term of the OR clause. After
  130312. ** eliminating duplicates from other WHERE clauses, the action for each
  130313. ** sub-WHERE clause is to to invoke the main loop body as a subroutine.
  130314. */
  130315. wctrlFlags = WHERE_OR_SUBCLAUSE | (pWInfo->wctrlFlags & WHERE_SEEK_TABLE);
  130316. ExplainQueryPlan((pParse, 1, "MULTI-INDEX OR"));
  130317. for(ii=0; ii<pOrWc->nTerm; ii++){
  130318. WhereTerm *pOrTerm = &pOrWc->a[ii];
  130319. if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
  130320. WhereInfo *pSubWInfo; /* Info for single OR-term scan */
  130321. Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */
  130322. int jmp1 = 0; /* Address of jump operation */
  130323. assert( (pTabItem[0].fg.jointype & JT_LEFT)==0
  130324. || ExprHasProperty(pOrExpr, EP_FromJoin)
  130325. );
  130326. if( pAndExpr ){
  130327. pAndExpr->pLeft = pOrExpr;
  130328. pOrExpr = pAndExpr;
  130329. }
  130330. /* Loop through table entries that match term pOrTerm. */
  130331. ExplainQueryPlan((pParse, 1, "INDEX %d", ii+1));
  130332. WHERETRACE(0xffff, ("Subplan for OR-clause:\n"));
  130333. pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
  130334. wctrlFlags, iCovCur);
  130335. assert( pSubWInfo || pParse->nErr || db->mallocFailed );
  130336. if( pSubWInfo ){
  130337. WhereLoop *pSubLoop;
  130338. int addrExplain = sqlite3WhereExplainOneScan(
  130339. pParse, pOrTab, &pSubWInfo->a[0], 0
  130340. );
  130341. sqlite3WhereAddScanStatus(v, pOrTab, &pSubWInfo->a[0], addrExplain);
  130342. /* This is the sub-WHERE clause body. First skip over
  130343. ** duplicate rows from prior sub-WHERE clauses, and record the
  130344. ** rowid (or PRIMARY KEY) for the current row so that the same
  130345. ** row will be skipped in subsequent sub-WHERE clauses.
  130346. */
  130347. if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
  130348. int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
  130349. if( HasRowid(pTab) ){
  130350. sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, -1, regRowid);
  130351. jmp1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0,
  130352. regRowid, iSet);
  130353. VdbeCoverage(v);
  130354. }else{
  130355. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  130356. int nPk = pPk->nKeyCol;
  130357. int iPk;
  130358. int r;
  130359. /* Read the PK into an array of temp registers. */
  130360. r = sqlite3GetTempRange(pParse, nPk);
  130361. for(iPk=0; iPk<nPk; iPk++){
  130362. int iCol = pPk->aiColumn[iPk];
  130363. sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol, r+iPk);
  130364. }
  130365. /* Check if the temp table already contains this key. If so,
  130366. ** the row has already been included in the result set and
  130367. ** can be ignored (by jumping past the Gosub below). Otherwise,
  130368. ** insert the key into the temp table and proceed with processing
  130369. ** the row.
  130370. **
  130371. ** Use some of the same optimizations as OP_RowSetTest: If iSet
  130372. ** is zero, assume that the key cannot already be present in
  130373. ** the temp table. And if iSet is -1, assume that there is no
  130374. ** need to insert the key into the temp table, as it will never
  130375. ** be tested for. */
  130376. if( iSet ){
  130377. jmp1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk);
  130378. VdbeCoverage(v);
  130379. }
  130380. if( iSet>=0 ){
  130381. sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid);
  130382. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, regRowset, regRowid,
  130383. r, nPk);
  130384. if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  130385. }
  130386. /* Release the array of temp registers */
  130387. sqlite3ReleaseTempRange(pParse, r, nPk);
  130388. }
  130389. }
  130390. /* Invoke the main loop body as a subroutine */
  130391. sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
  130392. /* Jump here (skipping the main loop body subroutine) if the
  130393. ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */
  130394. if( jmp1 ) sqlite3VdbeJumpHere(v, jmp1);
  130395. /* The pSubWInfo->untestedTerms flag means that this OR term
  130396. ** contained one or more AND term from a notReady table. The
  130397. ** terms from the notReady table could not be tested and will
  130398. ** need to be tested later.
  130399. */
  130400. if( pSubWInfo->untestedTerms ) untestedTerms = 1;
  130401. /* If all of the OR-connected terms are optimized using the same
  130402. ** index, and the index is opened using the same cursor number
  130403. ** by each call to sqlite3WhereBegin() made by this loop, it may
  130404. ** be possible to use that index as a covering index.
  130405. **
  130406. ** If the call to sqlite3WhereBegin() above resulted in a scan that
  130407. ** uses an index, and this is either the first OR-connected term
  130408. ** processed or the index is the same as that used by all previous
  130409. ** terms, set pCov to the candidate covering index. Otherwise, set
  130410. ** pCov to NULL to indicate that no candidate covering index will
  130411. ** be available.
  130412. */
  130413. pSubLoop = pSubWInfo->a[0].pWLoop;
  130414. assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
  130415. if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
  130416. && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
  130417. && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex))
  130418. ){
  130419. assert( pSubWInfo->a[0].iIdxCur==iCovCur );
  130420. pCov = pSubLoop->u.btree.pIndex;
  130421. }else{
  130422. pCov = 0;
  130423. }
  130424. /* Finish the loop through table entries that match term pOrTerm. */
  130425. sqlite3WhereEnd(pSubWInfo);
  130426. ExplainQueryPlanPop(pParse);
  130427. }
  130428. }
  130429. }
  130430. ExplainQueryPlanPop(pParse);
  130431. pLevel->u.pCovidx = pCov;
  130432. if( pCov ) pLevel->iIdxCur = iCovCur;
  130433. if( pAndExpr ){
  130434. pAndExpr->pLeft = 0;
  130435. sqlite3ExprDelete(db, pAndExpr);
  130436. }
  130437. sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
  130438. sqlite3VdbeGoto(v, pLevel->addrBrk);
  130439. sqlite3VdbeResolveLabel(v, iLoopBody);
  130440. if( pWInfo->nLevel>1 ){ sqlite3StackFree(db, pOrTab); }
  130441. if( !untestedTerms ) disableTerm(pLevel, pTerm);
  130442. }else
  130443. #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
  130444. {
  130445. /* Case 6: There is no usable index. We must do a complete
  130446. ** scan of the entire table.
  130447. */
  130448. static const u8 aStep[] = { OP_Next, OP_Prev };
  130449. static const u8 aStart[] = { OP_Rewind, OP_Last };
  130450. assert( bRev==0 || bRev==1 );
  130451. if( pTabItem->fg.isRecursive ){
  130452. /* Tables marked isRecursive have only a single row that is stored in
  130453. ** a pseudo-cursor. No need to Rewind or Next such cursors. */
  130454. pLevel->op = OP_Noop;
  130455. }else{
  130456. codeCursorHint(pTabItem, pWInfo, pLevel, 0);
  130457. pLevel->op = aStep[bRev];
  130458. pLevel->p1 = iCur;
  130459. pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrHalt);
  130460. VdbeCoverageIf(v, bRev==0);
  130461. VdbeCoverageIf(v, bRev!=0);
  130462. pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
  130463. }
  130464. }
  130465. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  130466. pLevel->addrVisit = sqlite3VdbeCurrentAddr(v);
  130467. #endif
  130468. /* Insert code to test every subexpression that can be completely
  130469. ** computed using the current set of tables.
  130470. **
  130471. ** This loop may run between one and three times, depending on the
  130472. ** constraints to be generated. The value of stack variable iLoop
  130473. ** determines the constraints coded by each iteration, as follows:
  130474. **
  130475. ** iLoop==1: Code only expressions that are entirely covered by pIdx.
  130476. ** iLoop==2: Code remaining expressions that do not contain correlated
  130477. ** sub-queries.
  130478. ** iLoop==3: Code all remaining expressions.
  130479. **
  130480. ** An effort is made to skip unnecessary iterations of the loop.
  130481. */
  130482. iLoop = (pIdx ? 1 : 2);
  130483. do{
  130484. int iNext = 0; /* Next value for iLoop */
  130485. for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
  130486. Expr *pE;
  130487. int skipLikeAddr = 0;
  130488. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  130489. testcase( pTerm->wtFlags & TERM_CODED );
  130490. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  130491. if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
  130492. testcase( pWInfo->untestedTerms==0
  130493. && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 );
  130494. pWInfo->untestedTerms = 1;
  130495. continue;
  130496. }
  130497. pE = pTerm->pExpr;
  130498. assert( pE!=0 );
  130499. if( (pTabItem->fg.jointype&JT_LEFT) && !ExprHasProperty(pE,EP_FromJoin) ){
  130500. continue;
  130501. }
  130502. if( iLoop==1 && !sqlite3ExprCoveredByIndex(pE, pLevel->iTabCur, pIdx) ){
  130503. iNext = 2;
  130504. continue;
  130505. }
  130506. if( iLoop<3 && (pTerm->wtFlags & TERM_VARSELECT) ){
  130507. if( iNext==0 ) iNext = 3;
  130508. continue;
  130509. }
  130510. if( (pTerm->wtFlags & TERM_LIKECOND)!=0 ){
  130511. /* If the TERM_LIKECOND flag is set, that means that the range search
  130512. ** is sufficient to guarantee that the LIKE operator is true, so we
  130513. ** can skip the call to the like(A,B) function. But this only works
  130514. ** for strings. So do not skip the call to the function on the pass
  130515. ** that compares BLOBs. */
  130516. #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  130517. continue;
  130518. #else
  130519. u32 x = pLevel->iLikeRepCntr;
  130520. if( x>0 ){
  130521. skipLikeAddr = sqlite3VdbeAddOp1(v, (x&1)?OP_IfNot:OP_If,(int)(x>>1));
  130522. VdbeCoverageIf(v, (x&1)==1);
  130523. VdbeCoverageIf(v, (x&1)==0);
  130524. }
  130525. #endif
  130526. }
  130527. #ifdef WHERETRACE_ENABLED /* 0xffff */
  130528. if( sqlite3WhereTrace ){
  130529. VdbeNoopComment((v, "WhereTerm[%d] (%p) priority=%d",
  130530. pWC->nTerm-j, pTerm, iLoop));
  130531. }
  130532. #endif
  130533. sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
  130534. if( skipLikeAddr ) sqlite3VdbeJumpHere(v, skipLikeAddr);
  130535. pTerm->wtFlags |= TERM_CODED;
  130536. }
  130537. iLoop = iNext;
  130538. }while( iLoop>0 );
  130539. /* Insert code to test for implied constraints based on transitivity
  130540. ** of the "==" operator.
  130541. **
  130542. ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
  130543. ** and we are coding the t1 loop and the t2 loop has not yet coded,
  130544. ** then we cannot use the "t1.a=t2.b" constraint, but we can code
  130545. ** the implied "t1.a=123" constraint.
  130546. */
  130547. for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
  130548. Expr *pE, sEAlt;
  130549. WhereTerm *pAlt;
  130550. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  130551. if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) continue;
  130552. if( (pTerm->eOperator & WO_EQUIV)==0 ) continue;
  130553. if( pTerm->leftCursor!=iCur ) continue;
  130554. if( pLevel->iLeftJoin ) continue;
  130555. pE = pTerm->pExpr;
  130556. assert( !ExprHasProperty(pE, EP_FromJoin) );
  130557. assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
  130558. pAlt = sqlite3WhereFindTerm(pWC, iCur, pTerm->u.leftColumn, notReady,
  130559. WO_EQ|WO_IN|WO_IS, 0);
  130560. if( pAlt==0 ) continue;
  130561. if( pAlt->wtFlags & (TERM_CODED) ) continue;
  130562. if( (pAlt->eOperator & WO_IN)
  130563. && (pAlt->pExpr->flags & EP_xIsSelect)
  130564. && (pAlt->pExpr->x.pSelect->pEList->nExpr>1)
  130565. ){
  130566. continue;
  130567. }
  130568. testcase( pAlt->eOperator & WO_EQ );
  130569. testcase( pAlt->eOperator & WO_IS );
  130570. testcase( pAlt->eOperator & WO_IN );
  130571. VdbeModuleComment((v, "begin transitive constraint"));
  130572. sEAlt = *pAlt->pExpr;
  130573. sEAlt.pLeft = pE->pLeft;
  130574. sqlite3ExprIfFalse(pParse, &sEAlt, addrCont, SQLITE_JUMPIFNULL);
  130575. }
  130576. /* For a LEFT OUTER JOIN, generate code that will record the fact that
  130577. ** at least one row of the right table has matched the left table.
  130578. */
  130579. if( pLevel->iLeftJoin ){
  130580. pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
  130581. sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
  130582. VdbeComment((v, "record LEFT JOIN hit"));
  130583. for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
  130584. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  130585. testcase( pTerm->wtFlags & TERM_CODED );
  130586. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  130587. if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
  130588. assert( pWInfo->untestedTerms );
  130589. continue;
  130590. }
  130591. assert( pTerm->pExpr );
  130592. sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
  130593. pTerm->wtFlags |= TERM_CODED;
  130594. }
  130595. }
  130596. return pLevel->notReady;
  130597. }
  130598. /************** End of wherecode.c *******************************************/
  130599. /************** Begin file whereexpr.c ***************************************/
  130600. /*
  130601. ** 2015-06-08
  130602. **
  130603. ** The author disclaims copyright to this source code. In place of
  130604. ** a legal notice, here is a blessing:
  130605. **
  130606. ** May you do good and not evil.
  130607. ** May you find forgiveness for yourself and forgive others.
  130608. ** May you share freely, never taking more than you give.
  130609. **
  130610. *************************************************************************
  130611. ** This module contains C code that generates VDBE code used to process
  130612. ** the WHERE clause of SQL statements.
  130613. **
  130614. ** This file was originally part of where.c but was split out to improve
  130615. ** readability and editabiliity. This file contains utility routines for
  130616. ** analyzing Expr objects in the WHERE clause.
  130617. */
  130618. /* #include "sqliteInt.h" */
  130619. /* #include "whereInt.h" */
  130620. /* Forward declarations */
  130621. static void exprAnalyze(SrcList*, WhereClause*, int);
  130622. /*
  130623. ** Deallocate all memory associated with a WhereOrInfo object.
  130624. */
  130625. static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
  130626. sqlite3WhereClauseClear(&p->wc);
  130627. sqlite3DbFree(db, p);
  130628. }
  130629. /*
  130630. ** Deallocate all memory associated with a WhereAndInfo object.
  130631. */
  130632. static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
  130633. sqlite3WhereClauseClear(&p->wc);
  130634. sqlite3DbFree(db, p);
  130635. }
  130636. /*
  130637. ** Add a single new WhereTerm entry to the WhereClause object pWC.
  130638. ** The new WhereTerm object is constructed from Expr p and with wtFlags.
  130639. ** The index in pWC->a[] of the new WhereTerm is returned on success.
  130640. ** 0 is returned if the new WhereTerm could not be added due to a memory
  130641. ** allocation error. The memory allocation failure will be recorded in
  130642. ** the db->mallocFailed flag so that higher-level functions can detect it.
  130643. **
  130644. ** This routine will increase the size of the pWC->a[] array as necessary.
  130645. **
  130646. ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
  130647. ** for freeing the expression p is assumed by the WhereClause object pWC.
  130648. ** This is true even if this routine fails to allocate a new WhereTerm.
  130649. **
  130650. ** WARNING: This routine might reallocate the space used to store
  130651. ** WhereTerms. All pointers to WhereTerms should be invalidated after
  130652. ** calling this routine. Such pointers may be reinitialized by referencing
  130653. ** the pWC->a[] array.
  130654. */
  130655. static int whereClauseInsert(WhereClause *pWC, Expr *p, u16 wtFlags){
  130656. WhereTerm *pTerm;
  130657. int idx;
  130658. testcase( wtFlags & TERM_VIRTUAL );
  130659. if( pWC->nTerm>=pWC->nSlot ){
  130660. WhereTerm *pOld = pWC->a;
  130661. sqlite3 *db = pWC->pWInfo->pParse->db;
  130662. pWC->a = sqlite3DbMallocRawNN(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
  130663. if( pWC->a==0 ){
  130664. if( wtFlags & TERM_DYNAMIC ){
  130665. sqlite3ExprDelete(db, p);
  130666. }
  130667. pWC->a = pOld;
  130668. return 0;
  130669. }
  130670. memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
  130671. if( pOld!=pWC->aStatic ){
  130672. sqlite3DbFree(db, pOld);
  130673. }
  130674. pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
  130675. }
  130676. pTerm = &pWC->a[idx = pWC->nTerm++];
  130677. if( p && ExprHasProperty(p, EP_Unlikely) ){
  130678. pTerm->truthProb = sqlite3LogEst(p->iTable) - 270;
  130679. }else{
  130680. pTerm->truthProb = 1;
  130681. }
  130682. pTerm->pExpr = sqlite3ExprSkipCollate(p);
  130683. pTerm->wtFlags = wtFlags;
  130684. pTerm->pWC = pWC;
  130685. pTerm->iParent = -1;
  130686. memset(&pTerm->eOperator, 0,
  130687. sizeof(WhereTerm) - offsetof(WhereTerm,eOperator));
  130688. return idx;
  130689. }
  130690. /*
  130691. ** Return TRUE if the given operator is one of the operators that is
  130692. ** allowed for an indexable WHERE clause term. The allowed operators are
  130693. ** "=", "<", ">", "<=", ">=", "IN", "IS", and "IS NULL"
  130694. */
  130695. static int allowedOp(int op){
  130696. assert( TK_GT>TK_EQ && TK_GT<TK_GE );
  130697. assert( TK_LT>TK_EQ && TK_LT<TK_GE );
  130698. assert( TK_LE>TK_EQ && TK_LE<TK_GE );
  130699. assert( TK_GE==TK_EQ+4 );
  130700. return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL || op==TK_IS;
  130701. }
  130702. /*
  130703. ** Commute a comparison operator. Expressions of the form "X op Y"
  130704. ** are converted into "Y op X".
  130705. **
  130706. ** If left/right precedence rules come into play when determining the
  130707. ** collating sequence, then COLLATE operators are adjusted to ensure
  130708. ** that the collating sequence does not change. For example:
  130709. ** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
  130710. ** the left hand side of a comparison overrides any collation sequence
  130711. ** attached to the right. For the same reason the EP_Collate flag
  130712. ** is not commuted.
  130713. */
  130714. static void exprCommute(Parse *pParse, Expr *pExpr){
  130715. u16 expRight = (pExpr->pRight->flags & EP_Collate);
  130716. u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
  130717. assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
  130718. if( expRight==expLeft ){
  130719. /* Either X and Y both have COLLATE operator or neither do */
  130720. if( expRight ){
  130721. /* Both X and Y have COLLATE operators. Make sure X is always
  130722. ** used by clearing the EP_Collate flag from Y. */
  130723. pExpr->pRight->flags &= ~EP_Collate;
  130724. }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
  130725. /* Neither X nor Y have COLLATE operators, but X has a non-default
  130726. ** collating sequence. So add the EP_Collate marker on X to cause
  130727. ** it to be searched first. */
  130728. pExpr->pLeft->flags |= EP_Collate;
  130729. }
  130730. }
  130731. SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
  130732. if( pExpr->op>=TK_GT ){
  130733. assert( TK_LT==TK_GT+2 );
  130734. assert( TK_GE==TK_LE+2 );
  130735. assert( TK_GT>TK_EQ );
  130736. assert( TK_GT<TK_LE );
  130737. assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
  130738. pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
  130739. }
  130740. }
  130741. /*
  130742. ** Translate from TK_xx operator to WO_xx bitmask.
  130743. */
  130744. static u16 operatorMask(int op){
  130745. u16 c;
  130746. assert( allowedOp(op) );
  130747. if( op==TK_IN ){
  130748. c = WO_IN;
  130749. }else if( op==TK_ISNULL ){
  130750. c = WO_ISNULL;
  130751. }else if( op==TK_IS ){
  130752. c = WO_IS;
  130753. }else{
  130754. assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
  130755. c = (u16)(WO_EQ<<(op-TK_EQ));
  130756. }
  130757. assert( op!=TK_ISNULL || c==WO_ISNULL );
  130758. assert( op!=TK_IN || c==WO_IN );
  130759. assert( op!=TK_EQ || c==WO_EQ );
  130760. assert( op!=TK_LT || c==WO_LT );
  130761. assert( op!=TK_LE || c==WO_LE );
  130762. assert( op!=TK_GT || c==WO_GT );
  130763. assert( op!=TK_GE || c==WO_GE );
  130764. assert( op!=TK_IS || c==WO_IS );
  130765. return c;
  130766. }
  130767. #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
  130768. /*
  130769. ** Check to see if the given expression is a LIKE or GLOB operator that
  130770. ** can be optimized using inequality constraints. Return TRUE if it is
  130771. ** so and false if not.
  130772. **
  130773. ** In order for the operator to be optimizible, the RHS must be a string
  130774. ** literal that does not begin with a wildcard. The LHS must be a column
  130775. ** that may only be NULL, a string, or a BLOB, never a number. (This means
  130776. ** that virtual tables cannot participate in the LIKE optimization.) The
  130777. ** collating sequence for the column on the LHS must be appropriate for
  130778. ** the operator.
  130779. */
  130780. static int isLikeOrGlob(
  130781. Parse *pParse, /* Parsing and code generating context */
  130782. Expr *pExpr, /* Test this expression */
  130783. Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */
  130784. int *pisComplete, /* True if the only wildcard is % in the last character */
  130785. int *pnoCase /* True if uppercase is equivalent to lowercase */
  130786. ){
  130787. const u8 *z = 0; /* String on RHS of LIKE operator */
  130788. Expr *pRight, *pLeft; /* Right and left size of LIKE operator */
  130789. ExprList *pList; /* List of operands to the LIKE operator */
  130790. u8 c; /* One character in z[] */
  130791. int cnt; /* Number of non-wildcard prefix characters */
  130792. u8 wc[4]; /* Wildcard characters */
  130793. sqlite3 *db = pParse->db; /* Database connection */
  130794. sqlite3_value *pVal = 0;
  130795. int op; /* Opcode of pRight */
  130796. int rc; /* Result code to return */
  130797. if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, (char*)wc) ){
  130798. return 0;
  130799. }
  130800. #ifdef SQLITE_EBCDIC
  130801. if( *pnoCase ) return 0;
  130802. #endif
  130803. pList = pExpr->x.pList;
  130804. pLeft = pList->a[1].pExpr;
  130805. pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr);
  130806. op = pRight->op;
  130807. if( op==TK_VARIABLE && (db->flags & SQLITE_EnableQPSG)==0 ){
  130808. Vdbe *pReprepare = pParse->pReprepare;
  130809. int iCol = pRight->iColumn;
  130810. pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_BLOB);
  130811. if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
  130812. z = sqlite3_value_text(pVal);
  130813. }
  130814. sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
  130815. assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
  130816. }else if( op==TK_STRING ){
  130817. z = (u8*)pRight->u.zToken;
  130818. }
  130819. if( z ){
  130820. /* Count the number of prefix characters prior to the first wildcard */
  130821. cnt = 0;
  130822. while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
  130823. cnt++;
  130824. if( c==wc[3] && z[cnt]!=0 ) cnt++;
  130825. }
  130826. /* The optimization is possible only if (1) the pattern does not begin
  130827. ** with a wildcard and if (2) the non-wildcard prefix does not end with
  130828. ** an (illegal 0xff) character, or (3) the pattern does not consist of
  130829. ** a single escape character. The second condition is necessary so
  130830. ** that we can increment the prefix key to find an upper bound for the
  130831. ** range search. The third is because the caller assumes that the pattern
  130832. ** consists of at least one character after all escapes have been
  130833. ** removed. */
  130834. if( cnt!=0 && 255!=(u8)z[cnt-1] && (cnt>1 || z[0]!=wc[3]) ){
  130835. Expr *pPrefix;
  130836. /* A "complete" match if the pattern ends with "*" or "%" */
  130837. *pisComplete = c==wc[0] && z[cnt+1]==0;
  130838. /* Get the pattern prefix. Remove all escapes from the prefix. */
  130839. pPrefix = sqlite3Expr(db, TK_STRING, (char*)z);
  130840. if( pPrefix ){
  130841. int iFrom, iTo;
  130842. char *zNew = pPrefix->u.zToken;
  130843. zNew[cnt] = 0;
  130844. for(iFrom=iTo=0; iFrom<cnt; iFrom++){
  130845. if( zNew[iFrom]==wc[3] ) iFrom++;
  130846. zNew[iTo++] = zNew[iFrom];
  130847. }
  130848. zNew[iTo] = 0;
  130849. assert( iTo>0 );
  130850. /* If the LHS is not an ordinary column with TEXT affinity, then the
  130851. ** pattern prefix boundaries (both the start and end boundaries) must
  130852. ** not look like a number. Otherwise the pattern might be treated as
  130853. ** a number, which will invalidate the LIKE optimization.
  130854. **
  130855. ** Getting this right has been a persistent source of bugs in the
  130856. ** LIKE optimization. See, for example:
  130857. ** 2018-09-10 https://sqlite.org/src/info/c94369cae9b561b1
  130858. ** 2019-05-02 https://sqlite.org/src/info/b043a54c3de54b28
  130859. ** 2019-06-10 https://sqlite.org/src/info/fd76310a5e843e07
  130860. ** 2019-06-14 https://sqlite.org/src/info/ce8717f0885af975
  130861. */
  130862. if( pLeft->op!=TK_COLUMN
  130863. || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
  130864. || IsVirtual(pLeft->y.pTab) /* Value might be numeric */
  130865. ){
  130866. int isNum;
  130867. double rDummy;
  130868. isNum = sqlite3AtoF(zNew, &rDummy, iTo, SQLITE_UTF8);
  130869. if( isNum<=0 ){
  130870. zNew[iTo-1]++;
  130871. isNum = sqlite3AtoF(zNew, &rDummy, iTo, SQLITE_UTF8);
  130872. zNew[iTo-1]--;
  130873. }
  130874. if( isNum>0 ){
  130875. sqlite3ExprDelete(db, pPrefix);
  130876. sqlite3ValueFree(pVal);
  130877. return 0;
  130878. }
  130879. }
  130880. }
  130881. *ppPrefix = pPrefix;
  130882. /* If the RHS pattern is a bound parameter, make arrangements to
  130883. ** reprepare the statement when that parameter is rebound */
  130884. if( op==TK_VARIABLE ){
  130885. Vdbe *v = pParse->pVdbe;
  130886. sqlite3VdbeSetVarmask(v, pRight->iColumn);
  130887. if( *pisComplete && pRight->u.zToken[1] ){
  130888. /* If the rhs of the LIKE expression is a variable, and the current
  130889. ** value of the variable means there is no need to invoke the LIKE
  130890. ** function, then no OP_Variable will be added to the program.
  130891. ** This causes problems for the sqlite3_bind_parameter_name()
  130892. ** API. To work around them, add a dummy OP_Variable here.
  130893. */
  130894. int r1 = sqlite3GetTempReg(pParse);
  130895. sqlite3ExprCodeTarget(pParse, pRight, r1);
  130896. sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
  130897. sqlite3ReleaseTempReg(pParse, r1);
  130898. }
  130899. }
  130900. }else{
  130901. z = 0;
  130902. }
  130903. }
  130904. rc = (z!=0);
  130905. sqlite3ValueFree(pVal);
  130906. return rc;
  130907. }
  130908. #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
  130909. #ifndef SQLITE_OMIT_VIRTUALTABLE
  130910. /*
  130911. ** Check to see if the pExpr expression is a form that needs to be passed
  130912. ** to the xBestIndex method of virtual tables. Forms of interest include:
  130913. **
  130914. ** Expression Virtual Table Operator
  130915. ** ----------------------- ---------------------------------
  130916. ** 1. column MATCH expr SQLITE_INDEX_CONSTRAINT_MATCH
  130917. ** 2. column GLOB expr SQLITE_INDEX_CONSTRAINT_GLOB
  130918. ** 3. column LIKE expr SQLITE_INDEX_CONSTRAINT_LIKE
  130919. ** 4. column REGEXP expr SQLITE_INDEX_CONSTRAINT_REGEXP
  130920. ** 5. column != expr SQLITE_INDEX_CONSTRAINT_NE
  130921. ** 6. expr != column SQLITE_INDEX_CONSTRAINT_NE
  130922. ** 7. column IS NOT expr SQLITE_INDEX_CONSTRAINT_ISNOT
  130923. ** 8. expr IS NOT column SQLITE_INDEX_CONSTRAINT_ISNOT
  130924. ** 9. column IS NOT NULL SQLITE_INDEX_CONSTRAINT_ISNOTNULL
  130925. **
  130926. ** In every case, "column" must be a column of a virtual table. If there
  130927. ** is a match, set *ppLeft to the "column" expression, set *ppRight to the
  130928. ** "expr" expression (even though in forms (6) and (8) the column is on the
  130929. ** right and the expression is on the left). Also set *peOp2 to the
  130930. ** appropriate virtual table operator. The return value is 1 or 2 if there
  130931. ** is a match. The usual return is 1, but if the RHS is also a column
  130932. ** of virtual table in forms (5) or (7) then return 2.
  130933. **
  130934. ** If the expression matches none of the patterns above, return 0.
  130935. */
  130936. static int isAuxiliaryVtabOperator(
  130937. sqlite3 *db, /* Parsing context */
  130938. Expr *pExpr, /* Test this expression */
  130939. unsigned char *peOp2, /* OUT: 0 for MATCH, or else an op2 value */
  130940. Expr **ppLeft, /* Column expression to left of MATCH/op2 */
  130941. Expr **ppRight /* Expression to left of MATCH/op2 */
  130942. ){
  130943. if( pExpr->op==TK_FUNCTION ){
  130944. static const struct Op2 {
  130945. const char *zOp;
  130946. unsigned char eOp2;
  130947. } aOp[] = {
  130948. { "match", SQLITE_INDEX_CONSTRAINT_MATCH },
  130949. { "glob", SQLITE_INDEX_CONSTRAINT_GLOB },
  130950. { "like", SQLITE_INDEX_CONSTRAINT_LIKE },
  130951. { "regexp", SQLITE_INDEX_CONSTRAINT_REGEXP }
  130952. };
  130953. ExprList *pList;
  130954. Expr *pCol; /* Column reference */
  130955. int i;
  130956. pList = pExpr->x.pList;
  130957. if( pList==0 || pList->nExpr!=2 ){
  130958. return 0;
  130959. }
  130960. /* Built-in operators MATCH, GLOB, LIKE, and REGEXP attach to a
  130961. ** virtual table on their second argument, which is the same as
  130962. ** the left-hand side operand in their in-fix form.
  130963. **
  130964. ** vtab_column MATCH expression
  130965. ** MATCH(expression,vtab_column)
  130966. */
  130967. pCol = pList->a[1].pExpr;
  130968. if( pCol->op==TK_COLUMN && IsVirtual(pCol->y.pTab) ){
  130969. for(i=0; i<ArraySize(aOp); i++){
  130970. if( sqlite3StrICmp(pExpr->u.zToken, aOp[i].zOp)==0 ){
  130971. *peOp2 = aOp[i].eOp2;
  130972. *ppRight = pList->a[0].pExpr;
  130973. *ppLeft = pCol;
  130974. return 1;
  130975. }
  130976. }
  130977. }
  130978. /* We can also match against the first column of overloaded
  130979. ** functions where xFindFunction returns a value of at least
  130980. ** SQLITE_INDEX_CONSTRAINT_FUNCTION.
  130981. **
  130982. ** OVERLOADED(vtab_column,expression)
  130983. **
  130984. ** Historically, xFindFunction expected to see lower-case function
  130985. ** names. But for this use case, xFindFunction is expected to deal
  130986. ** with function names in an arbitrary case.
  130987. */
  130988. pCol = pList->a[0].pExpr;
  130989. if( pCol->op==TK_COLUMN && IsVirtual(pCol->y.pTab) ){
  130990. sqlite3_vtab *pVtab;
  130991. sqlite3_module *pMod;
  130992. void (*xNotUsed)(sqlite3_context*,int,sqlite3_value**);
  130993. void *pNotUsed;
  130994. pVtab = sqlite3GetVTable(db, pCol->y.pTab)->pVtab;
  130995. assert( pVtab!=0 );
  130996. assert( pVtab->pModule!=0 );
  130997. pMod = (sqlite3_module *)pVtab->pModule;
  130998. if( pMod->xFindFunction!=0 ){
  130999. i = pMod->xFindFunction(pVtab,2, pExpr->u.zToken, &xNotUsed, &pNotUsed);
  131000. if( i>=SQLITE_INDEX_CONSTRAINT_FUNCTION ){
  131001. *peOp2 = i;
  131002. *ppRight = pList->a[1].pExpr;
  131003. *ppLeft = pCol;
  131004. return 1;
  131005. }
  131006. }
  131007. }
  131008. }else if( pExpr->op==TK_NE || pExpr->op==TK_ISNOT || pExpr->op==TK_NOTNULL ){
  131009. int res = 0;
  131010. Expr *pLeft = pExpr->pLeft;
  131011. Expr *pRight = pExpr->pRight;
  131012. if( pLeft->op==TK_COLUMN && IsVirtual(pLeft->y.pTab) ){
  131013. res++;
  131014. }
  131015. if( pRight && pRight->op==TK_COLUMN && IsVirtual(pRight->y.pTab) ){
  131016. res++;
  131017. SWAP(Expr*, pLeft, pRight);
  131018. }
  131019. *ppLeft = pLeft;
  131020. *ppRight = pRight;
  131021. if( pExpr->op==TK_NE ) *peOp2 = SQLITE_INDEX_CONSTRAINT_NE;
  131022. if( pExpr->op==TK_ISNOT ) *peOp2 = SQLITE_INDEX_CONSTRAINT_ISNOT;
  131023. if( pExpr->op==TK_NOTNULL ) *peOp2 = SQLITE_INDEX_CONSTRAINT_ISNOTNULL;
  131024. return res;
  131025. }
  131026. return 0;
  131027. }
  131028. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  131029. /*
  131030. ** If the pBase expression originated in the ON or USING clause of
  131031. ** a join, then transfer the appropriate markings over to derived.
  131032. */
  131033. static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
  131034. if( pDerived ){
  131035. pDerived->flags |= pBase->flags & EP_FromJoin;
  131036. pDerived->iRightJoinTable = pBase->iRightJoinTable;
  131037. }
  131038. }
  131039. /*
  131040. ** Mark term iChild as being a child of term iParent
  131041. */
  131042. static void markTermAsChild(WhereClause *pWC, int iChild, int iParent){
  131043. pWC->a[iChild].iParent = iParent;
  131044. pWC->a[iChild].truthProb = pWC->a[iParent].truthProb;
  131045. pWC->a[iParent].nChild++;
  131046. }
  131047. /*
  131048. ** Return the N-th AND-connected subterm of pTerm. Or if pTerm is not
  131049. ** a conjunction, then return just pTerm when N==0. If N is exceeds
  131050. ** the number of available subterms, return NULL.
  131051. */
  131052. static WhereTerm *whereNthSubterm(WhereTerm *pTerm, int N){
  131053. if( pTerm->eOperator!=WO_AND ){
  131054. return N==0 ? pTerm : 0;
  131055. }
  131056. if( N<pTerm->u.pAndInfo->wc.nTerm ){
  131057. return &pTerm->u.pAndInfo->wc.a[N];
  131058. }
  131059. return 0;
  131060. }
  131061. /*
  131062. ** Subterms pOne and pTwo are contained within WHERE clause pWC. The
  131063. ** two subterms are in disjunction - they are OR-ed together.
  131064. **
  131065. ** If these two terms are both of the form: "A op B" with the same
  131066. ** A and B values but different operators and if the operators are
  131067. ** compatible (if one is = and the other is <, for example) then
  131068. ** add a new virtual AND term to pWC that is the combination of the
  131069. ** two.
  131070. **
  131071. ** Some examples:
  131072. **
  131073. ** x<y OR x=y --> x<=y
  131074. ** x=y OR x=y --> x=y
  131075. ** x<=y OR x<y --> x<=y
  131076. **
  131077. ** The following is NOT generated:
  131078. **
  131079. ** x<y OR x>y --> x!=y
  131080. */
  131081. static void whereCombineDisjuncts(
  131082. SrcList *pSrc, /* the FROM clause */
  131083. WhereClause *pWC, /* The complete WHERE clause */
  131084. WhereTerm *pOne, /* First disjunct */
  131085. WhereTerm *pTwo /* Second disjunct */
  131086. ){
  131087. u16 eOp = pOne->eOperator | pTwo->eOperator;
  131088. sqlite3 *db; /* Database connection (for malloc) */
  131089. Expr *pNew; /* New virtual expression */
  131090. int op; /* Operator for the combined expression */
  131091. int idxNew; /* Index in pWC of the next virtual term */
  131092. if( (pOne->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
  131093. if( (pTwo->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
  131094. if( (eOp & (WO_EQ|WO_LT|WO_LE))!=eOp
  131095. && (eOp & (WO_EQ|WO_GT|WO_GE))!=eOp ) return;
  131096. assert( pOne->pExpr->pLeft!=0 && pOne->pExpr->pRight!=0 );
  131097. assert( pTwo->pExpr->pLeft!=0 && pTwo->pExpr->pRight!=0 );
  131098. if( sqlite3ExprCompare(0,pOne->pExpr->pLeft, pTwo->pExpr->pLeft, -1) ) return;
  131099. if( sqlite3ExprCompare(0,pOne->pExpr->pRight, pTwo->pExpr->pRight,-1) )return;
  131100. /* If we reach this point, it means the two subterms can be combined */
  131101. if( (eOp & (eOp-1))!=0 ){
  131102. if( eOp & (WO_LT|WO_LE) ){
  131103. eOp = WO_LE;
  131104. }else{
  131105. assert( eOp & (WO_GT|WO_GE) );
  131106. eOp = WO_GE;
  131107. }
  131108. }
  131109. db = pWC->pWInfo->pParse->db;
  131110. pNew = sqlite3ExprDup(db, pOne->pExpr, 0);
  131111. if( pNew==0 ) return;
  131112. for(op=TK_EQ; eOp!=(WO_EQ<<(op-TK_EQ)); op++){ assert( op<TK_GE ); }
  131113. pNew->op = op;
  131114. idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
  131115. exprAnalyze(pSrc, pWC, idxNew);
  131116. }
  131117. #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
  131118. /*
  131119. ** Analyze a term that consists of two or more OR-connected
  131120. ** subterms. So in:
  131121. **
  131122. ** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
  131123. ** ^^^^^^^^^^^^^^^^^^^^
  131124. **
  131125. ** This routine analyzes terms such as the middle term in the above example.
  131126. ** A WhereOrTerm object is computed and attached to the term under
  131127. ** analysis, regardless of the outcome of the analysis. Hence:
  131128. **
  131129. ** WhereTerm.wtFlags |= TERM_ORINFO
  131130. ** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
  131131. **
  131132. ** The term being analyzed must have two or more of OR-connected subterms.
  131133. ** A single subterm might be a set of AND-connected sub-subterms.
  131134. ** Examples of terms under analysis:
  131135. **
  131136. ** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
  131137. ** (B) x=expr1 OR expr2=x OR x=expr3
  131138. ** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
  131139. ** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
  131140. ** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
  131141. ** (F) x>A OR (x=A AND y>=B)
  131142. **
  131143. ** CASE 1:
  131144. **
  131145. ** If all subterms are of the form T.C=expr for some single column of C and
  131146. ** a single table T (as shown in example B above) then create a new virtual
  131147. ** term that is an equivalent IN expression. In other words, if the term
  131148. ** being analyzed is:
  131149. **
  131150. ** x = expr1 OR expr2 = x OR x = expr3
  131151. **
  131152. ** then create a new virtual term like this:
  131153. **
  131154. ** x IN (expr1,expr2,expr3)
  131155. **
  131156. ** CASE 2:
  131157. **
  131158. ** If there are exactly two disjuncts and one side has x>A and the other side
  131159. ** has x=A (for the same x and A) then add a new virtual conjunct term to the
  131160. ** WHERE clause of the form "x>=A". Example:
  131161. **
  131162. ** x>A OR (x=A AND y>B) adds: x>=A
  131163. **
  131164. ** The added conjunct can sometimes be helpful in query planning.
  131165. **
  131166. ** CASE 3:
  131167. **
  131168. ** If all subterms are indexable by a single table T, then set
  131169. **
  131170. ** WhereTerm.eOperator = WO_OR
  131171. ** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T
  131172. **
  131173. ** A subterm is "indexable" if it is of the form
  131174. ** "T.C <op> <expr>" where C is any column of table T and
  131175. ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
  131176. ** A subterm is also indexable if it is an AND of two or more
  131177. ** subsubterms at least one of which is indexable. Indexable AND
  131178. ** subterms have their eOperator set to WO_AND and they have
  131179. ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
  131180. **
  131181. ** From another point of view, "indexable" means that the subterm could
  131182. ** potentially be used with an index if an appropriate index exists.
  131183. ** This analysis does not consider whether or not the index exists; that
  131184. ** is decided elsewhere. This analysis only looks at whether subterms
  131185. ** appropriate for indexing exist.
  131186. **
  131187. ** All examples A through E above satisfy case 3. But if a term
  131188. ** also satisfies case 1 (such as B) we know that the optimizer will
  131189. ** always prefer case 1, so in that case we pretend that case 3 is not
  131190. ** satisfied.
  131191. **
  131192. ** It might be the case that multiple tables are indexable. For example,
  131193. ** (E) above is indexable on tables P, Q, and R.
  131194. **
  131195. ** Terms that satisfy case 3 are candidates for lookup by using
  131196. ** separate indices to find rowids for each subterm and composing
  131197. ** the union of all rowids using a RowSet object. This is similar
  131198. ** to "bitmap indices" in other database engines.
  131199. **
  131200. ** OTHERWISE:
  131201. **
  131202. ** If none of cases 1, 2, or 3 apply, then leave the eOperator set to
  131203. ** zero. This term is not useful for search.
  131204. */
  131205. static void exprAnalyzeOrTerm(
  131206. SrcList *pSrc, /* the FROM clause */
  131207. WhereClause *pWC, /* the complete WHERE clause */
  131208. int idxTerm /* Index of the OR-term to be analyzed */
  131209. ){
  131210. WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
  131211. Parse *pParse = pWInfo->pParse; /* Parser context */
  131212. sqlite3 *db = pParse->db; /* Database connection */
  131213. WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
  131214. Expr *pExpr = pTerm->pExpr; /* The expression of the term */
  131215. int i; /* Loop counters */
  131216. WhereClause *pOrWc; /* Breakup of pTerm into subterms */
  131217. WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
  131218. WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
  131219. Bitmask chngToIN; /* Tables that might satisfy case 1 */
  131220. Bitmask indexable; /* Tables that are indexable, satisfying case 2 */
  131221. /*
  131222. ** Break the OR clause into its separate subterms. The subterms are
  131223. ** stored in a WhereClause structure containing within the WhereOrInfo
  131224. ** object that is attached to the original OR clause term.
  131225. */
  131226. assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
  131227. assert( pExpr->op==TK_OR );
  131228. pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
  131229. if( pOrInfo==0 ) return;
  131230. pTerm->wtFlags |= TERM_ORINFO;
  131231. pOrWc = &pOrInfo->wc;
  131232. memset(pOrWc->aStatic, 0, sizeof(pOrWc->aStatic));
  131233. sqlite3WhereClauseInit(pOrWc, pWInfo);
  131234. sqlite3WhereSplit(pOrWc, pExpr, TK_OR);
  131235. sqlite3WhereExprAnalyze(pSrc, pOrWc);
  131236. if( db->mallocFailed ) return;
  131237. assert( pOrWc->nTerm>=2 );
  131238. /*
  131239. ** Compute the set of tables that might satisfy cases 1 or 3.
  131240. */
  131241. indexable = ~(Bitmask)0;
  131242. chngToIN = ~(Bitmask)0;
  131243. for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
  131244. if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
  131245. WhereAndInfo *pAndInfo;
  131246. assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
  131247. chngToIN = 0;
  131248. pAndInfo = sqlite3DbMallocRawNN(db, sizeof(*pAndInfo));
  131249. if( pAndInfo ){
  131250. WhereClause *pAndWC;
  131251. WhereTerm *pAndTerm;
  131252. int j;
  131253. Bitmask b = 0;
  131254. pOrTerm->u.pAndInfo = pAndInfo;
  131255. pOrTerm->wtFlags |= TERM_ANDINFO;
  131256. pOrTerm->eOperator = WO_AND;
  131257. pAndWC = &pAndInfo->wc;
  131258. memset(pAndWC->aStatic, 0, sizeof(pAndWC->aStatic));
  131259. sqlite3WhereClauseInit(pAndWC, pWC->pWInfo);
  131260. sqlite3WhereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
  131261. sqlite3WhereExprAnalyze(pSrc, pAndWC);
  131262. pAndWC->pOuter = pWC;
  131263. if( !db->mallocFailed ){
  131264. for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
  131265. assert( pAndTerm->pExpr );
  131266. if( allowedOp(pAndTerm->pExpr->op)
  131267. || pAndTerm->eOperator==WO_AUX
  131268. ){
  131269. b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
  131270. }
  131271. }
  131272. }
  131273. indexable &= b;
  131274. }
  131275. }else if( pOrTerm->wtFlags & TERM_COPIED ){
  131276. /* Skip this term for now. We revisit it when we process the
  131277. ** corresponding TERM_VIRTUAL term */
  131278. }else{
  131279. Bitmask b;
  131280. b = sqlite3WhereGetMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
  131281. if( pOrTerm->wtFlags & TERM_VIRTUAL ){
  131282. WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
  131283. b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pOther->leftCursor);
  131284. }
  131285. indexable &= b;
  131286. if( (pOrTerm->eOperator & WO_EQ)==0 ){
  131287. chngToIN = 0;
  131288. }else{
  131289. chngToIN &= b;
  131290. }
  131291. }
  131292. }
  131293. /*
  131294. ** Record the set of tables that satisfy case 3. The set might be
  131295. ** empty.
  131296. */
  131297. pOrInfo->indexable = indexable;
  131298. if( indexable ){
  131299. pTerm->eOperator = WO_OR;
  131300. pWC->hasOr = 1;
  131301. }else{
  131302. pTerm->eOperator = WO_OR;
  131303. }
  131304. /* For a two-way OR, attempt to implementation case 2.
  131305. */
  131306. if( indexable && pOrWc->nTerm==2 ){
  131307. int iOne = 0;
  131308. WhereTerm *pOne;
  131309. while( (pOne = whereNthSubterm(&pOrWc->a[0],iOne++))!=0 ){
  131310. int iTwo = 0;
  131311. WhereTerm *pTwo;
  131312. while( (pTwo = whereNthSubterm(&pOrWc->a[1],iTwo++))!=0 ){
  131313. whereCombineDisjuncts(pSrc, pWC, pOne, pTwo);
  131314. }
  131315. }
  131316. }
  131317. /*
  131318. ** chngToIN holds a set of tables that *might* satisfy case 1. But
  131319. ** we have to do some additional checking to see if case 1 really
  131320. ** is satisfied.
  131321. **
  131322. ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means
  131323. ** that there is no possibility of transforming the OR clause into an
  131324. ** IN operator because one or more terms in the OR clause contain
  131325. ** something other than == on a column in the single table. The 1-bit
  131326. ** case means that every term of the OR clause is of the form
  131327. ** "table.column=expr" for some single table. The one bit that is set
  131328. ** will correspond to the common table. We still need to check to make
  131329. ** sure the same column is used on all terms. The 2-bit case is when
  131330. ** the all terms are of the form "table1.column=table2.column". It
  131331. ** might be possible to form an IN operator with either table1.column
  131332. ** or table2.column as the LHS if either is common to every term of
  131333. ** the OR clause.
  131334. **
  131335. ** Note that terms of the form "table.column1=table.column2" (the
  131336. ** same table on both sizes of the ==) cannot be optimized.
  131337. */
  131338. if( chngToIN ){
  131339. int okToChngToIN = 0; /* True if the conversion to IN is valid */
  131340. int iColumn = -1; /* Column index on lhs of IN operator */
  131341. int iCursor = -1; /* Table cursor common to all terms */
  131342. int j = 0; /* Loop counter */
  131343. /* Search for a table and column that appears on one side or the
  131344. ** other of the == operator in every subterm. That table and column
  131345. ** will be recorded in iCursor and iColumn. There might not be any
  131346. ** such table and column. Set okToChngToIN if an appropriate table
  131347. ** and column is found but leave okToChngToIN false if not found.
  131348. */
  131349. for(j=0; j<2 && !okToChngToIN; j++){
  131350. Expr *pLeft = 0;
  131351. pOrTerm = pOrWc->a;
  131352. for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
  131353. assert( pOrTerm->eOperator & WO_EQ );
  131354. pOrTerm->wtFlags &= ~TERM_OR_OK;
  131355. if( pOrTerm->leftCursor==iCursor ){
  131356. /* This is the 2-bit case and we are on the second iteration and
  131357. ** current term is from the first iteration. So skip this term. */
  131358. assert( j==1 );
  131359. continue;
  131360. }
  131361. if( (chngToIN & sqlite3WhereGetMask(&pWInfo->sMaskSet,
  131362. pOrTerm->leftCursor))==0 ){
  131363. /* This term must be of the form t1.a==t2.b where t2 is in the
  131364. ** chngToIN set but t1 is not. This term will be either preceded
  131365. ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
  131366. ** and use its inversion. */
  131367. testcase( pOrTerm->wtFlags & TERM_COPIED );
  131368. testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
  131369. assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
  131370. continue;
  131371. }
  131372. iColumn = pOrTerm->u.leftColumn;
  131373. iCursor = pOrTerm->leftCursor;
  131374. pLeft = pOrTerm->pExpr->pLeft;
  131375. break;
  131376. }
  131377. if( i<0 ){
  131378. /* No candidate table+column was found. This can only occur
  131379. ** on the second iteration */
  131380. assert( j==1 );
  131381. assert( IsPowerOfTwo(chngToIN) );
  131382. assert( chngToIN==sqlite3WhereGetMask(&pWInfo->sMaskSet, iCursor) );
  131383. break;
  131384. }
  131385. testcase( j==1 );
  131386. /* We have found a candidate table and column. Check to see if that
  131387. ** table and column is common to every term in the OR clause */
  131388. okToChngToIN = 1;
  131389. for(; i>=0 && okToChngToIN; i--, pOrTerm++){
  131390. assert( pOrTerm->eOperator & WO_EQ );
  131391. if( pOrTerm->leftCursor!=iCursor ){
  131392. pOrTerm->wtFlags &= ~TERM_OR_OK;
  131393. }else if( pOrTerm->u.leftColumn!=iColumn || (iColumn==XN_EXPR
  131394. && sqlite3ExprCompare(pParse, pOrTerm->pExpr->pLeft, pLeft, -1)
  131395. )){
  131396. okToChngToIN = 0;
  131397. }else{
  131398. int affLeft, affRight;
  131399. /* If the right-hand side is also a column, then the affinities
  131400. ** of both right and left sides must be such that no type
  131401. ** conversions are required on the right. (Ticket #2249)
  131402. */
  131403. affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
  131404. affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
  131405. if( affRight!=0 && affRight!=affLeft ){
  131406. okToChngToIN = 0;
  131407. }else{
  131408. pOrTerm->wtFlags |= TERM_OR_OK;
  131409. }
  131410. }
  131411. }
  131412. }
  131413. /* At this point, okToChngToIN is true if original pTerm satisfies
  131414. ** case 1. In that case, construct a new virtual term that is
  131415. ** pTerm converted into an IN operator.
  131416. */
  131417. if( okToChngToIN ){
  131418. Expr *pDup; /* A transient duplicate expression */
  131419. ExprList *pList = 0; /* The RHS of the IN operator */
  131420. Expr *pLeft = 0; /* The LHS of the IN operator */
  131421. Expr *pNew; /* The complete IN operator */
  131422. for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
  131423. if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
  131424. assert( pOrTerm->eOperator & WO_EQ );
  131425. assert( pOrTerm->leftCursor==iCursor );
  131426. assert( pOrTerm->u.leftColumn==iColumn );
  131427. pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
  131428. pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
  131429. pLeft = pOrTerm->pExpr->pLeft;
  131430. }
  131431. assert( pLeft!=0 );
  131432. pDup = sqlite3ExprDup(db, pLeft, 0);
  131433. pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0);
  131434. if( pNew ){
  131435. int idxNew;
  131436. transferJoinMarkings(pNew, pExpr);
  131437. assert( !ExprHasProperty(pNew, EP_xIsSelect) );
  131438. pNew->x.pList = pList;
  131439. idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
  131440. testcase( idxNew==0 );
  131441. exprAnalyze(pSrc, pWC, idxNew);
  131442. /* pTerm = &pWC->a[idxTerm]; // would be needed if pTerm where used again */
  131443. markTermAsChild(pWC, idxNew, idxTerm);
  131444. }else{
  131445. sqlite3ExprListDelete(db, pList);
  131446. }
  131447. }
  131448. }
  131449. }
  131450. #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
  131451. /*
  131452. ** We already know that pExpr is a binary operator where both operands are
  131453. ** column references. This routine checks to see if pExpr is an equivalence
  131454. ** relation:
  131455. ** 1. The SQLITE_Transitive optimization must be enabled
  131456. ** 2. Must be either an == or an IS operator
  131457. ** 3. Not originating in the ON clause of an OUTER JOIN
  131458. ** 4. The affinities of A and B must be compatible
  131459. ** 5a. Both operands use the same collating sequence OR
  131460. ** 5b. The overall collating sequence is BINARY
  131461. ** If this routine returns TRUE, that means that the RHS can be substituted
  131462. ** for the LHS anyplace else in the WHERE clause where the LHS column occurs.
  131463. ** This is an optimization. No harm comes from returning 0. But if 1 is
  131464. ** returned when it should not be, then incorrect answers might result.
  131465. */
  131466. static int termIsEquivalence(Parse *pParse, Expr *pExpr){
  131467. char aff1, aff2;
  131468. CollSeq *pColl;
  131469. if( !OptimizationEnabled(pParse->db, SQLITE_Transitive) ) return 0;
  131470. if( pExpr->op!=TK_EQ && pExpr->op!=TK_IS ) return 0;
  131471. if( ExprHasProperty(pExpr, EP_FromJoin) ) return 0;
  131472. aff1 = sqlite3ExprAffinity(pExpr->pLeft);
  131473. aff2 = sqlite3ExprAffinity(pExpr->pRight);
  131474. if( aff1!=aff2
  131475. && (!sqlite3IsNumericAffinity(aff1) || !sqlite3IsNumericAffinity(aff2))
  131476. ){
  131477. return 0;
  131478. }
  131479. pColl = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft, pExpr->pRight);
  131480. if( sqlite3IsBinary(pColl) ) return 1;
  131481. return sqlite3ExprCollSeqMatch(pParse, pExpr->pLeft, pExpr->pRight);
  131482. }
  131483. /*
  131484. ** Recursively walk the expressions of a SELECT statement and generate
  131485. ** a bitmask indicating which tables are used in that expression
  131486. ** tree.
  131487. */
  131488. static Bitmask exprSelectUsage(WhereMaskSet *pMaskSet, Select *pS){
  131489. Bitmask mask = 0;
  131490. while( pS ){
  131491. SrcList *pSrc = pS->pSrc;
  131492. mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pEList);
  131493. mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pGroupBy);
  131494. mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pOrderBy);
  131495. mask |= sqlite3WhereExprUsage(pMaskSet, pS->pWhere);
  131496. mask |= sqlite3WhereExprUsage(pMaskSet, pS->pHaving);
  131497. if( ALWAYS(pSrc!=0) ){
  131498. int i;
  131499. for(i=0; i<pSrc->nSrc; i++){
  131500. mask |= exprSelectUsage(pMaskSet, pSrc->a[i].pSelect);
  131501. mask |= sqlite3WhereExprUsage(pMaskSet, pSrc->a[i].pOn);
  131502. if( pSrc->a[i].fg.isTabFunc ){
  131503. mask |= sqlite3WhereExprListUsage(pMaskSet, pSrc->a[i].u1.pFuncArg);
  131504. }
  131505. }
  131506. }
  131507. pS = pS->pPrior;
  131508. }
  131509. return mask;
  131510. }
  131511. /*
  131512. ** Expression pExpr is one operand of a comparison operator that might
  131513. ** be useful for indexing. This routine checks to see if pExpr appears
  131514. ** in any index. Return TRUE (1) if pExpr is an indexed term and return
  131515. ** FALSE (0) if not. If TRUE is returned, also set aiCurCol[0] to the cursor
  131516. ** number of the table that is indexed and aiCurCol[1] to the column number
  131517. ** of the column that is indexed, or XN_EXPR (-2) if an expression is being
  131518. ** indexed.
  131519. **
  131520. ** If pExpr is a TK_COLUMN column reference, then this routine always returns
  131521. ** true even if that particular column is not indexed, because the column
  131522. ** might be added to an automatic index later.
  131523. */
  131524. static SQLITE_NOINLINE int exprMightBeIndexed2(
  131525. SrcList *pFrom, /* The FROM clause */
  131526. Bitmask mPrereq, /* Bitmask of FROM clause terms referenced by pExpr */
  131527. int *aiCurCol, /* Write the referenced table cursor and column here */
  131528. Expr *pExpr /* An operand of a comparison operator */
  131529. ){
  131530. Index *pIdx;
  131531. int i;
  131532. int iCur;
  131533. for(i=0; mPrereq>1; i++, mPrereq>>=1){}
  131534. iCur = pFrom->a[i].iCursor;
  131535. for(pIdx=pFrom->a[i].pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  131536. if( pIdx->aColExpr==0 ) continue;
  131537. for(i=0; i<pIdx->nKeyCol; i++){
  131538. if( pIdx->aiColumn[i]!=XN_EXPR ) continue;
  131539. if( sqlite3ExprCompareSkip(pExpr, pIdx->aColExpr->a[i].pExpr, iCur)==0 ){
  131540. aiCurCol[0] = iCur;
  131541. aiCurCol[1] = XN_EXPR;
  131542. return 1;
  131543. }
  131544. }
  131545. }
  131546. return 0;
  131547. }
  131548. static int exprMightBeIndexed(
  131549. SrcList *pFrom, /* The FROM clause */
  131550. Bitmask mPrereq, /* Bitmask of FROM clause terms referenced by pExpr */
  131551. int *aiCurCol, /* Write the referenced table cursor & column here */
  131552. Expr *pExpr, /* An operand of a comparison operator */
  131553. int op /* The specific comparison operator */
  131554. ){
  131555. /* If this expression is a vector to the left or right of a
  131556. ** inequality constraint (>, <, >= or <=), perform the processing
  131557. ** on the first element of the vector. */
  131558. assert( TK_GT+1==TK_LE && TK_GT+2==TK_LT && TK_GT+3==TK_GE );
  131559. assert( TK_IS<TK_GE && TK_ISNULL<TK_GE && TK_IN<TK_GE );
  131560. assert( op<=TK_GE );
  131561. if( pExpr->op==TK_VECTOR && (op>=TK_GT && ALWAYS(op<=TK_GE)) ){
  131562. pExpr = pExpr->x.pList->a[0].pExpr;
  131563. }
  131564. if( pExpr->op==TK_COLUMN ){
  131565. aiCurCol[0] = pExpr->iTable;
  131566. aiCurCol[1] = pExpr->iColumn;
  131567. return 1;
  131568. }
  131569. if( mPrereq==0 ) return 0; /* No table references */
  131570. if( (mPrereq&(mPrereq-1))!=0 ) return 0; /* Refs more than one table */
  131571. return exprMightBeIndexed2(pFrom,mPrereq,aiCurCol,pExpr);
  131572. }
  131573. /*
  131574. ** The input to this routine is an WhereTerm structure with only the
  131575. ** "pExpr" field filled in. The job of this routine is to analyze the
  131576. ** subexpression and populate all the other fields of the WhereTerm
  131577. ** structure.
  131578. **
  131579. ** If the expression is of the form "<expr> <op> X" it gets commuted
  131580. ** to the standard form of "X <op> <expr>".
  131581. **
  131582. ** If the expression is of the form "X <op> Y" where both X and Y are
  131583. ** columns, then the original expression is unchanged and a new virtual
  131584. ** term of the form "Y <op> X" is added to the WHERE clause and
  131585. ** analyzed separately. The original term is marked with TERM_COPIED
  131586. ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
  131587. ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
  131588. ** is a commuted copy of a prior term.) The original term has nChild=1
  131589. ** and the copy has idxParent set to the index of the original term.
  131590. */
  131591. static void exprAnalyze(
  131592. SrcList *pSrc, /* the FROM clause */
  131593. WhereClause *pWC, /* the WHERE clause */
  131594. int idxTerm /* Index of the term to be analyzed */
  131595. ){
  131596. WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
  131597. WhereTerm *pTerm; /* The term to be analyzed */
  131598. WhereMaskSet *pMaskSet; /* Set of table index masks */
  131599. Expr *pExpr; /* The expression to be analyzed */
  131600. Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
  131601. Bitmask prereqAll; /* Prerequesites of pExpr */
  131602. Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
  131603. Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
  131604. int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
  131605. int noCase = 0; /* uppercase equivalent to lowercase */
  131606. int op; /* Top-level operator. pExpr->op */
  131607. Parse *pParse = pWInfo->pParse; /* Parsing context */
  131608. sqlite3 *db = pParse->db; /* Database connection */
  131609. unsigned char eOp2 = 0; /* op2 value for LIKE/REGEXP/GLOB */
  131610. int nLeft; /* Number of elements on left side vector */
  131611. if( db->mallocFailed ){
  131612. return;
  131613. }
  131614. pTerm = &pWC->a[idxTerm];
  131615. pMaskSet = &pWInfo->sMaskSet;
  131616. pExpr = pTerm->pExpr;
  131617. assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
  131618. prereqLeft = sqlite3WhereExprUsage(pMaskSet, pExpr->pLeft);
  131619. op = pExpr->op;
  131620. if( op==TK_IN ){
  131621. assert( pExpr->pRight==0 );
  131622. if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
  131623. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  131624. pTerm->prereqRight = exprSelectUsage(pMaskSet, pExpr->x.pSelect);
  131625. }else{
  131626. pTerm->prereqRight = sqlite3WhereExprListUsage(pMaskSet, pExpr->x.pList);
  131627. }
  131628. }else if( op==TK_ISNULL ){
  131629. pTerm->prereqRight = 0;
  131630. }else{
  131631. pTerm->prereqRight = sqlite3WhereExprUsage(pMaskSet, pExpr->pRight);
  131632. }
  131633. pMaskSet->bVarSelect = 0;
  131634. prereqAll = sqlite3WhereExprUsageNN(pMaskSet, pExpr);
  131635. if( pMaskSet->bVarSelect ) pTerm->wtFlags |= TERM_VARSELECT;
  131636. if( ExprHasProperty(pExpr, EP_FromJoin) ){
  131637. Bitmask x = sqlite3WhereGetMask(pMaskSet, pExpr->iRightJoinTable);
  131638. prereqAll |= x;
  131639. extraRight = x-1; /* ON clause terms may not be used with an index
  131640. ** on left table of a LEFT JOIN. Ticket #3015 */
  131641. if( (prereqAll>>1)>=x ){
  131642. sqlite3ErrorMsg(pParse, "ON clause references tables to its right");
  131643. return;
  131644. }
  131645. }
  131646. pTerm->prereqAll = prereqAll;
  131647. pTerm->leftCursor = -1;
  131648. pTerm->iParent = -1;
  131649. pTerm->eOperator = 0;
  131650. if( allowedOp(op) ){
  131651. int aiCurCol[2];
  131652. Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
  131653. Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
  131654. u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
  131655. if( pTerm->iField>0 ){
  131656. assert( op==TK_IN );
  131657. assert( pLeft->op==TK_VECTOR );
  131658. pLeft = pLeft->x.pList->a[pTerm->iField-1].pExpr;
  131659. }
  131660. if( exprMightBeIndexed(pSrc, prereqLeft, aiCurCol, pLeft, op) ){
  131661. pTerm->leftCursor = aiCurCol[0];
  131662. pTerm->u.leftColumn = aiCurCol[1];
  131663. pTerm->eOperator = operatorMask(op) & opMask;
  131664. }
  131665. if( op==TK_IS ) pTerm->wtFlags |= TERM_IS;
  131666. if( pRight
  131667. && exprMightBeIndexed(pSrc, pTerm->prereqRight, aiCurCol, pRight, op)
  131668. ){
  131669. WhereTerm *pNew;
  131670. Expr *pDup;
  131671. u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */
  131672. assert( pTerm->iField==0 );
  131673. if( pTerm->leftCursor>=0 ){
  131674. int idxNew;
  131675. pDup = sqlite3ExprDup(db, pExpr, 0);
  131676. if( db->mallocFailed ){
  131677. sqlite3ExprDelete(db, pDup);
  131678. return;
  131679. }
  131680. idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
  131681. if( idxNew==0 ) return;
  131682. pNew = &pWC->a[idxNew];
  131683. markTermAsChild(pWC, idxNew, idxTerm);
  131684. if( op==TK_IS ) pNew->wtFlags |= TERM_IS;
  131685. pTerm = &pWC->a[idxTerm];
  131686. pTerm->wtFlags |= TERM_COPIED;
  131687. if( termIsEquivalence(pParse, pDup) ){
  131688. pTerm->eOperator |= WO_EQUIV;
  131689. eExtraOp = WO_EQUIV;
  131690. }
  131691. }else{
  131692. pDup = pExpr;
  131693. pNew = pTerm;
  131694. }
  131695. exprCommute(pParse, pDup);
  131696. pNew->leftCursor = aiCurCol[0];
  131697. pNew->u.leftColumn = aiCurCol[1];
  131698. testcase( (prereqLeft | extraRight) != prereqLeft );
  131699. pNew->prereqRight = prereqLeft | extraRight;
  131700. pNew->prereqAll = prereqAll;
  131701. pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
  131702. }
  131703. }
  131704. #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
  131705. /* If a term is the BETWEEN operator, create two new virtual terms
  131706. ** that define the range that the BETWEEN implements. For example:
  131707. **
  131708. ** a BETWEEN b AND c
  131709. **
  131710. ** is converted into:
  131711. **
  131712. ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
  131713. **
  131714. ** The two new terms are added onto the end of the WhereClause object.
  131715. ** The new terms are "dynamic" and are children of the original BETWEEN
  131716. ** term. That means that if the BETWEEN term is coded, the children are
  131717. ** skipped. Or, if the children are satisfied by an index, the original
  131718. ** BETWEEN term is skipped.
  131719. */
  131720. else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
  131721. ExprList *pList = pExpr->x.pList;
  131722. int i;
  131723. static const u8 ops[] = {TK_GE, TK_LE};
  131724. assert( pList!=0 );
  131725. assert( pList->nExpr==2 );
  131726. for(i=0; i<2; i++){
  131727. Expr *pNewExpr;
  131728. int idxNew;
  131729. pNewExpr = sqlite3PExpr(pParse, ops[i],
  131730. sqlite3ExprDup(db, pExpr->pLeft, 0),
  131731. sqlite3ExprDup(db, pList->a[i].pExpr, 0));
  131732. transferJoinMarkings(pNewExpr, pExpr);
  131733. idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
  131734. testcase( idxNew==0 );
  131735. exprAnalyze(pSrc, pWC, idxNew);
  131736. pTerm = &pWC->a[idxTerm];
  131737. markTermAsChild(pWC, idxNew, idxTerm);
  131738. }
  131739. }
  131740. #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
  131741. #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
  131742. /* Analyze a term that is composed of two or more subterms connected by
  131743. ** an OR operator.
  131744. */
  131745. else if( pExpr->op==TK_OR ){
  131746. assert( pWC->op==TK_AND );
  131747. exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
  131748. pTerm = &pWC->a[idxTerm];
  131749. }
  131750. #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
  131751. #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
  131752. /* Add constraints to reduce the search space on a LIKE or GLOB
  131753. ** operator.
  131754. **
  131755. ** A like pattern of the form "x LIKE 'aBc%'" is changed into constraints
  131756. **
  131757. ** x>='ABC' AND x<'abd' AND x LIKE 'aBc%'
  131758. **
  131759. ** The last character of the prefix "abc" is incremented to form the
  131760. ** termination condition "abd". If case is not significant (the default
  131761. ** for LIKE) then the lower-bound is made all uppercase and the upper-
  131762. ** bound is made all lowercase so that the bounds also work when comparing
  131763. ** BLOBs.
  131764. */
  131765. if( pWC->op==TK_AND
  131766. && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
  131767. ){
  131768. Expr *pLeft; /* LHS of LIKE/GLOB operator */
  131769. Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
  131770. Expr *pNewExpr1;
  131771. Expr *pNewExpr2;
  131772. int idxNew1;
  131773. int idxNew2;
  131774. const char *zCollSeqName; /* Name of collating sequence */
  131775. const u16 wtFlags = TERM_LIKEOPT | TERM_VIRTUAL | TERM_DYNAMIC;
  131776. pLeft = pExpr->x.pList->a[1].pExpr;
  131777. pStr2 = sqlite3ExprDup(db, pStr1, 0);
  131778. /* Convert the lower bound to upper-case and the upper bound to
  131779. ** lower-case (upper-case is less than lower-case in ASCII) so that
  131780. ** the range constraints also work for BLOBs
  131781. */
  131782. if( noCase && !pParse->db->mallocFailed ){
  131783. int i;
  131784. char c;
  131785. pTerm->wtFlags |= TERM_LIKE;
  131786. for(i=0; (c = pStr1->u.zToken[i])!=0; i++){
  131787. pStr1->u.zToken[i] = sqlite3Toupper(c);
  131788. pStr2->u.zToken[i] = sqlite3Tolower(c);
  131789. }
  131790. }
  131791. if( !db->mallocFailed ){
  131792. u8 c, *pC; /* Last character before the first wildcard */
  131793. pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
  131794. c = *pC;
  131795. if( noCase ){
  131796. /* The point is to increment the last character before the first
  131797. ** wildcard. But if we increment '@', that will push it into the
  131798. ** alphabetic range where case conversions will mess up the
  131799. ** inequality. To avoid this, make sure to also run the full
  131800. ** LIKE on all candidate expressions by clearing the isComplete flag
  131801. */
  131802. if( c=='A'-1 ) isComplete = 0;
  131803. c = sqlite3UpperToLower[c];
  131804. }
  131805. *pC = c + 1;
  131806. }
  131807. zCollSeqName = noCase ? "NOCASE" : sqlite3StrBINARY;
  131808. pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
  131809. pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
  131810. sqlite3ExprAddCollateString(pParse,pNewExpr1,zCollSeqName),
  131811. pStr1);
  131812. transferJoinMarkings(pNewExpr1, pExpr);
  131813. idxNew1 = whereClauseInsert(pWC, pNewExpr1, wtFlags);
  131814. testcase( idxNew1==0 );
  131815. exprAnalyze(pSrc, pWC, idxNew1);
  131816. pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
  131817. pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
  131818. sqlite3ExprAddCollateString(pParse,pNewExpr2,zCollSeqName),
  131819. pStr2);
  131820. transferJoinMarkings(pNewExpr2, pExpr);
  131821. idxNew2 = whereClauseInsert(pWC, pNewExpr2, wtFlags);
  131822. testcase( idxNew2==0 );
  131823. exprAnalyze(pSrc, pWC, idxNew2);
  131824. pTerm = &pWC->a[idxTerm];
  131825. if( isComplete ){
  131826. markTermAsChild(pWC, idxNew1, idxTerm);
  131827. markTermAsChild(pWC, idxNew2, idxTerm);
  131828. }
  131829. }
  131830. #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
  131831. #ifndef SQLITE_OMIT_VIRTUALTABLE
  131832. /* Add a WO_AUX auxiliary term to the constraint set if the
  131833. ** current expression is of the form "column OP expr" where OP
  131834. ** is an operator that gets passed into virtual tables but which is
  131835. ** not normally optimized for ordinary tables. In other words, OP
  131836. ** is one of MATCH, LIKE, GLOB, REGEXP, !=, IS, IS NOT, or NOT NULL.
  131837. ** This information is used by the xBestIndex methods of
  131838. ** virtual tables. The native query optimizer does not attempt
  131839. ** to do anything with MATCH functions.
  131840. */
  131841. if( pWC->op==TK_AND ){
  131842. Expr *pRight = 0, *pLeft = 0;
  131843. int res = isAuxiliaryVtabOperator(db, pExpr, &eOp2, &pLeft, &pRight);
  131844. while( res-- > 0 ){
  131845. int idxNew;
  131846. WhereTerm *pNewTerm;
  131847. Bitmask prereqColumn, prereqExpr;
  131848. prereqExpr = sqlite3WhereExprUsage(pMaskSet, pRight);
  131849. prereqColumn = sqlite3WhereExprUsage(pMaskSet, pLeft);
  131850. if( (prereqExpr & prereqColumn)==0 ){
  131851. Expr *pNewExpr;
  131852. pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
  131853. 0, sqlite3ExprDup(db, pRight, 0));
  131854. if( ExprHasProperty(pExpr, EP_FromJoin) && pNewExpr ){
  131855. ExprSetProperty(pNewExpr, EP_FromJoin);
  131856. }
  131857. idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
  131858. testcase( idxNew==0 );
  131859. pNewTerm = &pWC->a[idxNew];
  131860. pNewTerm->prereqRight = prereqExpr;
  131861. pNewTerm->leftCursor = pLeft->iTable;
  131862. pNewTerm->u.leftColumn = pLeft->iColumn;
  131863. pNewTerm->eOperator = WO_AUX;
  131864. pNewTerm->eMatchOp = eOp2;
  131865. markTermAsChild(pWC, idxNew, idxTerm);
  131866. pTerm = &pWC->a[idxTerm];
  131867. pTerm->wtFlags |= TERM_COPIED;
  131868. pNewTerm->prereqAll = pTerm->prereqAll;
  131869. }
  131870. SWAP(Expr*, pLeft, pRight);
  131871. }
  131872. }
  131873. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  131874. /* If there is a vector == or IS term - e.g. "(a, b) == (?, ?)" - create
  131875. ** new terms for each component comparison - "a = ?" and "b = ?". The
  131876. ** new terms completely replace the original vector comparison, which is
  131877. ** no longer used.
  131878. **
  131879. ** This is only required if at least one side of the comparison operation
  131880. ** is not a sub-select. */
  131881. if( pWC->op==TK_AND
  131882. && (pExpr->op==TK_EQ || pExpr->op==TK_IS)
  131883. && (nLeft = sqlite3ExprVectorSize(pExpr->pLeft))>1
  131884. && sqlite3ExprVectorSize(pExpr->pRight)==nLeft
  131885. && ( (pExpr->pLeft->flags & EP_xIsSelect)==0
  131886. || (pExpr->pRight->flags & EP_xIsSelect)==0)
  131887. ){
  131888. int i;
  131889. for(i=0; i<nLeft; i++){
  131890. int idxNew;
  131891. Expr *pNew;
  131892. Expr *pLeft = sqlite3ExprForVectorField(pParse, pExpr->pLeft, i);
  131893. Expr *pRight = sqlite3ExprForVectorField(pParse, pExpr->pRight, i);
  131894. pNew = sqlite3PExpr(pParse, pExpr->op, pLeft, pRight);
  131895. transferJoinMarkings(pNew, pExpr);
  131896. idxNew = whereClauseInsert(pWC, pNew, TERM_DYNAMIC);
  131897. exprAnalyze(pSrc, pWC, idxNew);
  131898. }
  131899. pTerm = &pWC->a[idxTerm];
  131900. pTerm->wtFlags |= TERM_CODED|TERM_VIRTUAL; /* Disable the original */
  131901. pTerm->eOperator = 0;
  131902. }
  131903. /* If there is a vector IN term - e.g. "(a, b) IN (SELECT ...)" - create
  131904. ** a virtual term for each vector component. The expression object
  131905. ** used by each such virtual term is pExpr (the full vector IN(...)
  131906. ** expression). The WhereTerm.iField variable identifies the index within
  131907. ** the vector on the LHS that the virtual term represents.
  131908. **
  131909. ** This only works if the RHS is a simple SELECT, not a compound
  131910. */
  131911. if( pWC->op==TK_AND && pExpr->op==TK_IN && pTerm->iField==0
  131912. && pExpr->pLeft->op==TK_VECTOR
  131913. && pExpr->x.pSelect->pPrior==0
  131914. ){
  131915. int i;
  131916. for(i=0; i<sqlite3ExprVectorSize(pExpr->pLeft); i++){
  131917. int idxNew;
  131918. idxNew = whereClauseInsert(pWC, pExpr, TERM_VIRTUAL);
  131919. pWC->a[idxNew].iField = i+1;
  131920. exprAnalyze(pSrc, pWC, idxNew);
  131921. markTermAsChild(pWC, idxNew, idxTerm);
  131922. }
  131923. }
  131924. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  131925. /* When sqlite_stat3 histogram data is available an operator of the
  131926. ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
  131927. ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a
  131928. ** virtual term of that form.
  131929. **
  131930. ** Note that the virtual term must be tagged with TERM_VNULL.
  131931. */
  131932. if( pExpr->op==TK_NOTNULL
  131933. && pExpr->pLeft->op==TK_COLUMN
  131934. && pExpr->pLeft->iColumn>=0
  131935. && !ExprHasProperty(pExpr, EP_FromJoin)
  131936. && OptimizationEnabled(db, SQLITE_Stat34)
  131937. ){
  131938. Expr *pNewExpr;
  131939. Expr *pLeft = pExpr->pLeft;
  131940. int idxNew;
  131941. WhereTerm *pNewTerm;
  131942. pNewExpr = sqlite3PExpr(pParse, TK_GT,
  131943. sqlite3ExprDup(db, pLeft, 0),
  131944. sqlite3ExprAlloc(db, TK_NULL, 0, 0));
  131945. idxNew = whereClauseInsert(pWC, pNewExpr,
  131946. TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
  131947. if( idxNew ){
  131948. pNewTerm = &pWC->a[idxNew];
  131949. pNewTerm->prereqRight = 0;
  131950. pNewTerm->leftCursor = pLeft->iTable;
  131951. pNewTerm->u.leftColumn = pLeft->iColumn;
  131952. pNewTerm->eOperator = WO_GT;
  131953. markTermAsChild(pWC, idxNew, idxTerm);
  131954. pTerm = &pWC->a[idxTerm];
  131955. pTerm->wtFlags |= TERM_COPIED;
  131956. pNewTerm->prereqAll = pTerm->prereqAll;
  131957. }
  131958. }
  131959. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  131960. /* Prevent ON clause terms of a LEFT JOIN from being used to drive
  131961. ** an index for tables to the left of the join.
  131962. */
  131963. testcase( pTerm!=&pWC->a[idxTerm] );
  131964. pTerm = &pWC->a[idxTerm];
  131965. pTerm->prereqRight |= extraRight;
  131966. }
  131967. /***************************************************************************
  131968. ** Routines with file scope above. Interface to the rest of the where.c
  131969. ** subsystem follows.
  131970. ***************************************************************************/
  131971. /*
  131972. ** This routine identifies subexpressions in the WHERE clause where
  131973. ** each subexpression is separated by the AND operator or some other
  131974. ** operator specified in the op parameter. The WhereClause structure
  131975. ** is filled with pointers to subexpressions. For example:
  131976. **
  131977. ** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
  131978. ** \________/ \_______________/ \________________/
  131979. ** slot[0] slot[1] slot[2]
  131980. **
  131981. ** The original WHERE clause in pExpr is unaltered. All this routine
  131982. ** does is make slot[] entries point to substructure within pExpr.
  131983. **
  131984. ** In the previous sentence and in the diagram, "slot[]" refers to
  131985. ** the WhereClause.a[] array. The slot[] array grows as needed to contain
  131986. ** all terms of the WHERE clause.
  131987. */
  131988. SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
  131989. Expr *pE2 = sqlite3ExprSkipCollate(pExpr);
  131990. pWC->op = op;
  131991. if( pE2==0 ) return;
  131992. if( pE2->op!=op ){
  131993. whereClauseInsert(pWC, pExpr, 0);
  131994. }else{
  131995. sqlite3WhereSplit(pWC, pE2->pLeft, op);
  131996. sqlite3WhereSplit(pWC, pE2->pRight, op);
  131997. }
  131998. }
  131999. /*
  132000. ** Initialize a preallocated WhereClause structure.
  132001. */
  132002. SQLITE_PRIVATE void sqlite3WhereClauseInit(
  132003. WhereClause *pWC, /* The WhereClause to be initialized */
  132004. WhereInfo *pWInfo /* The WHERE processing context */
  132005. ){
  132006. pWC->pWInfo = pWInfo;
  132007. pWC->hasOr = 0;
  132008. pWC->pOuter = 0;
  132009. pWC->nTerm = 0;
  132010. pWC->nSlot = ArraySize(pWC->aStatic);
  132011. pWC->a = pWC->aStatic;
  132012. }
  132013. /*
  132014. ** Deallocate a WhereClause structure. The WhereClause structure
  132015. ** itself is not freed. This routine is the inverse of
  132016. ** sqlite3WhereClauseInit().
  132017. */
  132018. SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause *pWC){
  132019. int i;
  132020. WhereTerm *a;
  132021. sqlite3 *db = pWC->pWInfo->pParse->db;
  132022. for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
  132023. if( a->wtFlags & TERM_DYNAMIC ){
  132024. sqlite3ExprDelete(db, a->pExpr);
  132025. }
  132026. if( a->wtFlags & TERM_ORINFO ){
  132027. whereOrInfoDelete(db, a->u.pOrInfo);
  132028. }else if( a->wtFlags & TERM_ANDINFO ){
  132029. whereAndInfoDelete(db, a->u.pAndInfo);
  132030. }
  132031. }
  132032. if( pWC->a!=pWC->aStatic ){
  132033. sqlite3DbFree(db, pWC->a);
  132034. }
  132035. }
  132036. /*
  132037. ** These routines walk (recursively) an expression tree and generate
  132038. ** a bitmask indicating which tables are used in that expression
  132039. ** tree.
  132040. */
  132041. SQLITE_PRIVATE Bitmask sqlite3WhereExprUsageNN(WhereMaskSet *pMaskSet, Expr *p){
  132042. Bitmask mask;
  132043. if( p->op==TK_COLUMN && !ExprHasProperty(p, EP_FixedCol) ){
  132044. return sqlite3WhereGetMask(pMaskSet, p->iTable);
  132045. }else if( ExprHasProperty(p, EP_TokenOnly|EP_Leaf) ){
  132046. assert( p->op!=TK_IF_NULL_ROW );
  132047. return 0;
  132048. }
  132049. mask = (p->op==TK_IF_NULL_ROW) ? sqlite3WhereGetMask(pMaskSet, p->iTable) : 0;
  132050. if( p->pLeft ) mask |= sqlite3WhereExprUsageNN(pMaskSet, p->pLeft);
  132051. if( p->pRight ){
  132052. mask |= sqlite3WhereExprUsageNN(pMaskSet, p->pRight);
  132053. assert( p->x.pList==0 );
  132054. }else if( ExprHasProperty(p, EP_xIsSelect) ){
  132055. if( ExprHasProperty(p, EP_VarSelect) ) pMaskSet->bVarSelect = 1;
  132056. mask |= exprSelectUsage(pMaskSet, p->x.pSelect);
  132057. }else if( p->x.pList ){
  132058. mask |= sqlite3WhereExprListUsage(pMaskSet, p->x.pList);
  132059. }
  132060. #ifndef SQLITE_OMIT_WINDOWFUNC
  132061. if( p->op==TK_FUNCTION && p->y.pWin ){
  132062. mask |= sqlite3WhereExprListUsage(pMaskSet, p->y.pWin->pPartition);
  132063. mask |= sqlite3WhereExprListUsage(pMaskSet, p->y.pWin->pOrderBy);
  132064. }
  132065. #endif
  132066. return mask;
  132067. }
  132068. SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet *pMaskSet, Expr *p){
  132069. return p ? sqlite3WhereExprUsageNN(pMaskSet,p) : 0;
  132070. }
  132071. SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet *pMaskSet, ExprList *pList){
  132072. int i;
  132073. Bitmask mask = 0;
  132074. if( pList ){
  132075. for(i=0; i<pList->nExpr; i++){
  132076. mask |= sqlite3WhereExprUsage(pMaskSet, pList->a[i].pExpr);
  132077. }
  132078. }
  132079. return mask;
  132080. }
  132081. /*
  132082. ** Call exprAnalyze on all terms in a WHERE clause.
  132083. **
  132084. ** Note that exprAnalyze() might add new virtual terms onto the
  132085. ** end of the WHERE clause. We do not want to analyze these new
  132086. ** virtual terms, so start analyzing at the end and work forward
  132087. ** so that the added virtual terms are never processed.
  132088. */
  132089. SQLITE_PRIVATE void sqlite3WhereExprAnalyze(
  132090. SrcList *pTabList, /* the FROM clause */
  132091. WhereClause *pWC /* the WHERE clause to be analyzed */
  132092. ){
  132093. int i;
  132094. for(i=pWC->nTerm-1; i>=0; i--){
  132095. exprAnalyze(pTabList, pWC, i);
  132096. }
  132097. }
  132098. /*
  132099. ** For table-valued-functions, transform the function arguments into
  132100. ** new WHERE clause terms.
  132101. **
  132102. ** Each function argument translates into an equality constraint against
  132103. ** a HIDDEN column in the table.
  132104. */
  132105. SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(
  132106. Parse *pParse, /* Parsing context */
  132107. struct SrcList_item *pItem, /* The FROM clause term to process */
  132108. WhereClause *pWC /* Xfer function arguments to here */
  132109. ){
  132110. Table *pTab;
  132111. int j, k;
  132112. ExprList *pArgs;
  132113. Expr *pColRef;
  132114. Expr *pTerm;
  132115. if( pItem->fg.isTabFunc==0 ) return;
  132116. pTab = pItem->pTab;
  132117. assert( pTab!=0 );
  132118. pArgs = pItem->u1.pFuncArg;
  132119. if( pArgs==0 ) return;
  132120. for(j=k=0; j<pArgs->nExpr; j++){
  132121. Expr *pRhs;
  132122. while( k<pTab->nCol && (pTab->aCol[k].colFlags & COLFLAG_HIDDEN)==0 ){k++;}
  132123. if( k>=pTab->nCol ){
  132124. sqlite3ErrorMsg(pParse, "too many arguments on %s() - max %d",
  132125. pTab->zName, j);
  132126. return;
  132127. }
  132128. pColRef = sqlite3ExprAlloc(pParse->db, TK_COLUMN, 0, 0);
  132129. if( pColRef==0 ) return;
  132130. pColRef->iTable = pItem->iCursor;
  132131. pColRef->iColumn = k++;
  132132. pColRef->y.pTab = pTab;
  132133. pRhs = sqlite3PExpr(pParse, TK_UPLUS,
  132134. sqlite3ExprDup(pParse->db, pArgs->a[j].pExpr, 0), 0);
  132135. pTerm = sqlite3PExpr(pParse, TK_EQ, pColRef, pRhs);
  132136. whereClauseInsert(pWC, pTerm, TERM_DYNAMIC);
  132137. }
  132138. }
  132139. /************** End of whereexpr.c *******************************************/
  132140. /************** Begin file where.c *******************************************/
  132141. /*
  132142. ** 2001 September 15
  132143. **
  132144. ** The author disclaims copyright to this source code. In place of
  132145. ** a legal notice, here is a blessing:
  132146. **
  132147. ** May you do good and not evil.
  132148. ** May you find forgiveness for yourself and forgive others.
  132149. ** May you share freely, never taking more than you give.
  132150. **
  132151. *************************************************************************
  132152. ** This module contains C code that generates VDBE code used to process
  132153. ** the WHERE clause of SQL statements. This module is responsible for
  132154. ** generating the code that loops through a table looking for applicable
  132155. ** rows. Indices are selected and used to speed the search when doing
  132156. ** so is applicable. Because this module is responsible for selecting
  132157. ** indices, you might also think of this module as the "query optimizer".
  132158. */
  132159. /* #include "sqliteInt.h" */
  132160. /* #include "whereInt.h" */
  132161. /*
  132162. ** Extra information appended to the end of sqlite3_index_info but not
  132163. ** visible to the xBestIndex function, at least not directly. The
  132164. ** sqlite3_vtab_collation() interface knows how to reach it, however.
  132165. **
  132166. ** This object is not an API and can be changed from one release to the
  132167. ** next. As long as allocateIndexInfo() and sqlite3_vtab_collation()
  132168. ** agree on the structure, all will be well.
  132169. */
  132170. typedef struct HiddenIndexInfo HiddenIndexInfo;
  132171. struct HiddenIndexInfo {
  132172. WhereClause *pWC; /* The Where clause being analyzed */
  132173. Parse *pParse; /* The parsing context */
  132174. };
  132175. /* Forward declaration of methods */
  132176. static int whereLoopResize(sqlite3*, WhereLoop*, int);
  132177. /* Test variable that can be set to enable WHERE tracing */
  132178. #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
  132179. /***/ int sqlite3WhereTrace = 0;
  132180. #endif
  132181. /*
  132182. ** Return the estimated number of output rows from a WHERE clause
  132183. */
  132184. SQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
  132185. return pWInfo->nRowOut;
  132186. }
  132187. /*
  132188. ** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
  132189. ** WHERE clause returns outputs for DISTINCT processing.
  132190. */
  132191. SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
  132192. return pWInfo->eDistinct;
  132193. }
  132194. /*
  132195. ** Return TRUE if the WHERE clause returns rows in ORDER BY order.
  132196. ** Return FALSE if the output needs to be sorted.
  132197. */
  132198. SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
  132199. return pWInfo->nOBSat;
  132200. }
  132201. /*
  132202. ** In the ORDER BY LIMIT optimization, if the inner-most loop is known
  132203. ** to emit rows in increasing order, and if the last row emitted by the
  132204. ** inner-most loop did not fit within the sorter, then we can skip all
  132205. ** subsequent rows for the current iteration of the inner loop (because they
  132206. ** will not fit in the sorter either) and continue with the second inner
  132207. ** loop - the loop immediately outside the inner-most.
  132208. **
  132209. ** When a row does not fit in the sorter (because the sorter already
  132210. ** holds LIMIT+OFFSET rows that are smaller), then a jump is made to the
  132211. ** label returned by this function.
  132212. **
  132213. ** If the ORDER BY LIMIT optimization applies, the jump destination should
  132214. ** be the continuation for the second-inner-most loop. If the ORDER BY
  132215. ** LIMIT optimization does not apply, then the jump destination should
  132216. ** be the continuation for the inner-most loop.
  132217. **
  132218. ** It is always safe for this routine to return the continuation of the
  132219. ** inner-most loop, in the sense that a correct answer will result.
  132220. ** Returning the continuation the second inner loop is an optimization
  132221. ** that might make the code run a little faster, but should not change
  132222. ** the final answer.
  132223. */
  132224. SQLITE_PRIVATE int sqlite3WhereOrderByLimitOptLabel(WhereInfo *pWInfo){
  132225. WhereLevel *pInner;
  132226. if( !pWInfo->bOrderedInnerLoop ){
  132227. /* The ORDER BY LIMIT optimization does not apply. Jump to the
  132228. ** continuation of the inner-most loop. */
  132229. return pWInfo->iContinue;
  132230. }
  132231. pInner = &pWInfo->a[pWInfo->nLevel-1];
  132232. assert( pInner->addrNxt!=0 );
  132233. return pInner->addrNxt;
  132234. }
  132235. /*
  132236. ** Return the VDBE address or label to jump to in order to continue
  132237. ** immediately with the next row of a WHERE clause.
  132238. */
  132239. SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
  132240. assert( pWInfo->iContinue!=0 );
  132241. return pWInfo->iContinue;
  132242. }
  132243. /*
  132244. ** Return the VDBE address or label to jump to in order to break
  132245. ** out of a WHERE loop.
  132246. */
  132247. SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
  132248. return pWInfo->iBreak;
  132249. }
  132250. /*
  132251. ** Return ONEPASS_OFF (0) if an UPDATE or DELETE statement is unable to
  132252. ** operate directly on the rowis returned by a WHERE clause. Return
  132253. ** ONEPASS_SINGLE (1) if the statement can operation directly because only
  132254. ** a single row is to be changed. Return ONEPASS_MULTI (2) if the one-pass
  132255. ** optimization can be used on multiple
  132256. **
  132257. ** If the ONEPASS optimization is used (if this routine returns true)
  132258. ** then also write the indices of open cursors used by ONEPASS
  132259. ** into aiCur[0] and aiCur[1]. iaCur[0] gets the cursor of the data
  132260. ** table and iaCur[1] gets the cursor used by an auxiliary index.
  132261. ** Either value may be -1, indicating that cursor is not used.
  132262. ** Any cursors returned will have been opened for writing.
  132263. **
  132264. ** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is
  132265. ** unable to use the ONEPASS optimization.
  132266. */
  132267. SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){
  132268. memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2);
  132269. #ifdef WHERETRACE_ENABLED
  132270. if( sqlite3WhereTrace && pWInfo->eOnePass!=ONEPASS_OFF ){
  132271. sqlite3DebugPrintf("%s cursors: %d %d\n",
  132272. pWInfo->eOnePass==ONEPASS_SINGLE ? "ONEPASS_SINGLE" : "ONEPASS_MULTI",
  132273. aiCur[0], aiCur[1]);
  132274. }
  132275. #endif
  132276. return pWInfo->eOnePass;
  132277. }
  132278. /*
  132279. ** Move the content of pSrc into pDest
  132280. */
  132281. static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){
  132282. pDest->n = pSrc->n;
  132283. memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));
  132284. }
  132285. /*
  132286. ** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
  132287. **
  132288. ** The new entry might overwrite an existing entry, or it might be
  132289. ** appended, or it might be discarded. Do whatever is the right thing
  132290. ** so that pSet keeps the N_OR_COST best entries seen so far.
  132291. */
  132292. static int whereOrInsert(
  132293. WhereOrSet *pSet, /* The WhereOrSet to be updated */
  132294. Bitmask prereq, /* Prerequisites of the new entry */
  132295. LogEst rRun, /* Run-cost of the new entry */
  132296. LogEst nOut /* Number of outputs for the new entry */
  132297. ){
  132298. u16 i;
  132299. WhereOrCost *p;
  132300. for(i=pSet->n, p=pSet->a; i>0; i--, p++){
  132301. if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
  132302. goto whereOrInsert_done;
  132303. }
  132304. if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
  132305. return 0;
  132306. }
  132307. }
  132308. if( pSet->n<N_OR_COST ){
  132309. p = &pSet->a[pSet->n++];
  132310. p->nOut = nOut;
  132311. }else{
  132312. p = pSet->a;
  132313. for(i=1; i<pSet->n; i++){
  132314. if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
  132315. }
  132316. if( p->rRun<=rRun ) return 0;
  132317. }
  132318. whereOrInsert_done:
  132319. p->prereq = prereq;
  132320. p->rRun = rRun;
  132321. if( p->nOut>nOut ) p->nOut = nOut;
  132322. return 1;
  132323. }
  132324. /*
  132325. ** Return the bitmask for the given cursor number. Return 0 if
  132326. ** iCursor is not in the set.
  132327. */
  132328. SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet *pMaskSet, int iCursor){
  132329. int i;
  132330. assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
  132331. for(i=0; i<pMaskSet->n; i++){
  132332. if( pMaskSet->ix[i]==iCursor ){
  132333. return MASKBIT(i);
  132334. }
  132335. }
  132336. return 0;
  132337. }
  132338. /*
  132339. ** Create a new mask for cursor iCursor.
  132340. **
  132341. ** There is one cursor per table in the FROM clause. The number of
  132342. ** tables in the FROM clause is limited by a test early in the
  132343. ** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[]
  132344. ** array will never overflow.
  132345. */
  132346. static void createMask(WhereMaskSet *pMaskSet, int iCursor){
  132347. assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
  132348. pMaskSet->ix[pMaskSet->n++] = iCursor;
  132349. }
  132350. /*
  132351. ** Advance to the next WhereTerm that matches according to the criteria
  132352. ** established when the pScan object was initialized by whereScanInit().
  132353. ** Return NULL if there are no more matching WhereTerms.
  132354. */
  132355. static WhereTerm *whereScanNext(WhereScan *pScan){
  132356. int iCur; /* The cursor on the LHS of the term */
  132357. i16 iColumn; /* The column on the LHS of the term. -1 for IPK */
  132358. Expr *pX; /* An expression being tested */
  132359. WhereClause *pWC; /* Shorthand for pScan->pWC */
  132360. WhereTerm *pTerm; /* The term being tested */
  132361. int k = pScan->k; /* Where to start scanning */
  132362. assert( pScan->iEquiv<=pScan->nEquiv );
  132363. pWC = pScan->pWC;
  132364. while(1){
  132365. iColumn = pScan->aiColumn[pScan->iEquiv-1];
  132366. iCur = pScan->aiCur[pScan->iEquiv-1];
  132367. assert( pWC!=0 );
  132368. do{
  132369. for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
  132370. if( pTerm->leftCursor==iCur
  132371. && pTerm->u.leftColumn==iColumn
  132372. && (iColumn!=XN_EXPR
  132373. || sqlite3ExprCompareSkip(pTerm->pExpr->pLeft,
  132374. pScan->pIdxExpr,iCur)==0)
  132375. && (pScan->iEquiv<=1 || !ExprHasProperty(pTerm->pExpr, EP_FromJoin))
  132376. ){
  132377. if( (pTerm->eOperator & WO_EQUIV)!=0
  132378. && pScan->nEquiv<ArraySize(pScan->aiCur)
  132379. && (pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight))->op==TK_COLUMN
  132380. ){
  132381. int j;
  132382. for(j=0; j<pScan->nEquiv; j++){
  132383. if( pScan->aiCur[j]==pX->iTable
  132384. && pScan->aiColumn[j]==pX->iColumn ){
  132385. break;
  132386. }
  132387. }
  132388. if( j==pScan->nEquiv ){
  132389. pScan->aiCur[j] = pX->iTable;
  132390. pScan->aiColumn[j] = pX->iColumn;
  132391. pScan->nEquiv++;
  132392. }
  132393. }
  132394. if( (pTerm->eOperator & pScan->opMask)!=0 ){
  132395. /* Verify the affinity and collating sequence match */
  132396. if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
  132397. CollSeq *pColl;
  132398. Parse *pParse = pWC->pWInfo->pParse;
  132399. pX = pTerm->pExpr;
  132400. if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
  132401. continue;
  132402. }
  132403. assert(pX->pLeft);
  132404. pColl = sqlite3BinaryCompareCollSeq(pParse,
  132405. pX->pLeft, pX->pRight);
  132406. if( pColl==0 ) pColl = pParse->db->pDfltColl;
  132407. if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
  132408. continue;
  132409. }
  132410. }
  132411. if( (pTerm->eOperator & (WO_EQ|WO_IS))!=0
  132412. && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
  132413. && pX->iTable==pScan->aiCur[0]
  132414. && pX->iColumn==pScan->aiColumn[0]
  132415. ){
  132416. testcase( pTerm->eOperator & WO_IS );
  132417. continue;
  132418. }
  132419. pScan->pWC = pWC;
  132420. pScan->k = k+1;
  132421. return pTerm;
  132422. }
  132423. }
  132424. }
  132425. pWC = pWC->pOuter;
  132426. k = 0;
  132427. }while( pWC!=0 );
  132428. if( pScan->iEquiv>=pScan->nEquiv ) break;
  132429. pWC = pScan->pOrigWC;
  132430. k = 0;
  132431. pScan->iEquiv++;
  132432. }
  132433. return 0;
  132434. }
  132435. /*
  132436. ** This is whereScanInit() for the case of an index on an expression.
  132437. ** It is factored out into a separate tail-recursion subroutine so that
  132438. ** the normal whereScanInit() routine, which is a high-runner, does not
  132439. ** need to push registers onto the stack as part of its prologue.
  132440. */
  132441. static SQLITE_NOINLINE WhereTerm *whereScanInitIndexExpr(WhereScan *pScan){
  132442. pScan->idxaff = sqlite3ExprAffinity(pScan->pIdxExpr);
  132443. return whereScanNext(pScan);
  132444. }
  132445. /*
  132446. ** Initialize a WHERE clause scanner object. Return a pointer to the
  132447. ** first match. Return NULL if there are no matches.
  132448. **
  132449. ** The scanner will be searching the WHERE clause pWC. It will look
  132450. ** for terms of the form "X <op> <expr>" where X is column iColumn of table
  132451. ** iCur. Or if pIdx!=0 then X is column iColumn of index pIdx. pIdx
  132452. ** must be one of the indexes of table iCur.
  132453. **
  132454. ** The <op> must be one of the operators described by opMask.
  132455. **
  132456. ** If the search is for X and the WHERE clause contains terms of the
  132457. ** form X=Y then this routine might also return terms of the form
  132458. ** "Y <op> <expr>". The number of levels of transitivity is limited,
  132459. ** but is enough to handle most commonly occurring SQL statements.
  132460. **
  132461. ** If X is not the INTEGER PRIMARY KEY then X must be compatible with
  132462. ** index pIdx.
  132463. */
  132464. static WhereTerm *whereScanInit(
  132465. WhereScan *pScan, /* The WhereScan object being initialized */
  132466. WhereClause *pWC, /* The WHERE clause to be scanned */
  132467. int iCur, /* Cursor to scan for */
  132468. int iColumn, /* Column to scan for */
  132469. u32 opMask, /* Operator(s) to scan for */
  132470. Index *pIdx /* Must be compatible with this index */
  132471. ){
  132472. pScan->pOrigWC = pWC;
  132473. pScan->pWC = pWC;
  132474. pScan->pIdxExpr = 0;
  132475. pScan->idxaff = 0;
  132476. pScan->zCollName = 0;
  132477. pScan->opMask = opMask;
  132478. pScan->k = 0;
  132479. pScan->aiCur[0] = iCur;
  132480. pScan->nEquiv = 1;
  132481. pScan->iEquiv = 1;
  132482. if( pIdx ){
  132483. int j = iColumn;
  132484. iColumn = pIdx->aiColumn[j];
  132485. if( iColumn==XN_EXPR ){
  132486. pScan->pIdxExpr = pIdx->aColExpr->a[j].pExpr;
  132487. pScan->zCollName = pIdx->azColl[j];
  132488. pScan->aiColumn[0] = XN_EXPR;
  132489. return whereScanInitIndexExpr(pScan);
  132490. }else if( iColumn==pIdx->pTable->iPKey ){
  132491. iColumn = XN_ROWID;
  132492. }else if( iColumn>=0 ){
  132493. pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
  132494. pScan->zCollName = pIdx->azColl[j];
  132495. }
  132496. }else if( iColumn==XN_EXPR ){
  132497. return 0;
  132498. }
  132499. pScan->aiColumn[0] = iColumn;
  132500. return whereScanNext(pScan);
  132501. }
  132502. /*
  132503. ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
  132504. ** where X is a reference to the iColumn of table iCur or of index pIdx
  132505. ** if pIdx!=0 and <op> is one of the WO_xx operator codes specified by
  132506. ** the op parameter. Return a pointer to the term. Return 0 if not found.
  132507. **
  132508. ** If pIdx!=0 then it must be one of the indexes of table iCur.
  132509. ** Search for terms matching the iColumn-th column of pIdx
  132510. ** rather than the iColumn-th column of table iCur.
  132511. **
  132512. ** The term returned might by Y=<expr> if there is another constraint in
  132513. ** the WHERE clause that specifies that X=Y. Any such constraints will be
  132514. ** identified by the WO_EQUIV bit in the pTerm->eOperator field. The
  132515. ** aiCur[]/iaColumn[] arrays hold X and all its equivalents. There are 11
  132516. ** slots in aiCur[]/aiColumn[] so that means we can look for X plus up to 10
  132517. ** other equivalent values. Hence a search for X will return <expr> if X=A1
  132518. ** and A1=A2 and A2=A3 and ... and A9=A10 and A10=<expr>.
  132519. **
  132520. ** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
  132521. ** then try for the one with no dependencies on <expr> - in other words where
  132522. ** <expr> is a constant expression of some kind. Only return entries of
  132523. ** the form "X <op> Y" where Y is a column in another table if no terms of
  132524. ** the form "X <op> <const-expr>" exist. If no terms with a constant RHS
  132525. ** exist, try to return a term that does not use WO_EQUIV.
  132526. */
  132527. SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm(
  132528. WhereClause *pWC, /* The WHERE clause to be searched */
  132529. int iCur, /* Cursor number of LHS */
  132530. int iColumn, /* Column number of LHS */
  132531. Bitmask notReady, /* RHS must not overlap with this mask */
  132532. u32 op, /* Mask of WO_xx values describing operator */
  132533. Index *pIdx /* Must be compatible with this index, if not NULL */
  132534. ){
  132535. WhereTerm *pResult = 0;
  132536. WhereTerm *p;
  132537. WhereScan scan;
  132538. p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
  132539. op &= WO_EQ|WO_IS;
  132540. while( p ){
  132541. if( (p->prereqRight & notReady)==0 ){
  132542. if( p->prereqRight==0 && (p->eOperator&op)!=0 ){
  132543. testcase( p->eOperator & WO_IS );
  132544. return p;
  132545. }
  132546. if( pResult==0 ) pResult = p;
  132547. }
  132548. p = whereScanNext(&scan);
  132549. }
  132550. return pResult;
  132551. }
  132552. /*
  132553. ** This function searches pList for an entry that matches the iCol-th column
  132554. ** of index pIdx.
  132555. **
  132556. ** If such an expression is found, its index in pList->a[] is returned. If
  132557. ** no expression is found, -1 is returned.
  132558. */
  132559. static int findIndexCol(
  132560. Parse *pParse, /* Parse context */
  132561. ExprList *pList, /* Expression list to search */
  132562. int iBase, /* Cursor for table associated with pIdx */
  132563. Index *pIdx, /* Index to match column of */
  132564. int iCol /* Column of index to match */
  132565. ){
  132566. int i;
  132567. const char *zColl = pIdx->azColl[iCol];
  132568. for(i=0; i<pList->nExpr; i++){
  132569. Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
  132570. if( p->op==TK_COLUMN
  132571. && p->iColumn==pIdx->aiColumn[iCol]
  132572. && p->iTable==iBase
  132573. ){
  132574. CollSeq *pColl = sqlite3ExprNNCollSeq(pParse, pList->a[i].pExpr);
  132575. if( 0==sqlite3StrICmp(pColl->zName, zColl) ){
  132576. return i;
  132577. }
  132578. }
  132579. }
  132580. return -1;
  132581. }
  132582. /*
  132583. ** Return TRUE if the iCol-th column of index pIdx is NOT NULL
  132584. */
  132585. static int indexColumnNotNull(Index *pIdx, int iCol){
  132586. int j;
  132587. assert( pIdx!=0 );
  132588. assert( iCol>=0 && iCol<pIdx->nColumn );
  132589. j = pIdx->aiColumn[iCol];
  132590. if( j>=0 ){
  132591. return pIdx->pTable->aCol[j].notNull;
  132592. }else if( j==(-1) ){
  132593. return 1;
  132594. }else{
  132595. assert( j==(-2) );
  132596. return 0; /* Assume an indexed expression can always yield a NULL */
  132597. }
  132598. }
  132599. /*
  132600. ** Return true if the DISTINCT expression-list passed as the third argument
  132601. ** is redundant.
  132602. **
  132603. ** A DISTINCT list is redundant if any subset of the columns in the
  132604. ** DISTINCT list are collectively unique and individually non-null.
  132605. */
  132606. static int isDistinctRedundant(
  132607. Parse *pParse, /* Parsing context */
  132608. SrcList *pTabList, /* The FROM clause */
  132609. WhereClause *pWC, /* The WHERE clause */
  132610. ExprList *pDistinct /* The result set that needs to be DISTINCT */
  132611. ){
  132612. Table *pTab;
  132613. Index *pIdx;
  132614. int i;
  132615. int iBase;
  132616. /* If there is more than one table or sub-select in the FROM clause of
  132617. ** this query, then it will not be possible to show that the DISTINCT
  132618. ** clause is redundant. */
  132619. if( pTabList->nSrc!=1 ) return 0;
  132620. iBase = pTabList->a[0].iCursor;
  132621. pTab = pTabList->a[0].pTab;
  132622. /* If any of the expressions is an IPK column on table iBase, then return
  132623. ** true. Note: The (p->iTable==iBase) part of this test may be false if the
  132624. ** current SELECT is a correlated sub-query.
  132625. */
  132626. for(i=0; i<pDistinct->nExpr; i++){
  132627. Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
  132628. if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
  132629. }
  132630. /* Loop through all indices on the table, checking each to see if it makes
  132631. ** the DISTINCT qualifier redundant. It does so if:
  132632. **
  132633. ** 1. The index is itself UNIQUE, and
  132634. **
  132635. ** 2. All of the columns in the index are either part of the pDistinct
  132636. ** list, or else the WHERE clause contains a term of the form "col=X",
  132637. ** where X is a constant value. The collation sequences of the
  132638. ** comparison and select-list expressions must match those of the index.
  132639. **
  132640. ** 3. All of those index columns for which the WHERE clause does not
  132641. ** contain a "col=X" term are subject to a NOT NULL constraint.
  132642. */
  132643. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  132644. if( !IsUniqueIndex(pIdx) ) continue;
  132645. for(i=0; i<pIdx->nKeyCol; i++){
  132646. if( 0==sqlite3WhereFindTerm(pWC, iBase, i, ~(Bitmask)0, WO_EQ, pIdx) ){
  132647. if( findIndexCol(pParse, pDistinct, iBase, pIdx, i)<0 ) break;
  132648. if( indexColumnNotNull(pIdx, i)==0 ) break;
  132649. }
  132650. }
  132651. if( i==pIdx->nKeyCol ){
  132652. /* This index implies that the DISTINCT qualifier is redundant. */
  132653. return 1;
  132654. }
  132655. }
  132656. return 0;
  132657. }
  132658. /*
  132659. ** Estimate the logarithm of the input value to base 2.
  132660. */
  132661. static LogEst estLog(LogEst N){
  132662. return N<=10 ? 0 : sqlite3LogEst(N) - 33;
  132663. }
  132664. /*
  132665. ** Convert OP_Column opcodes to OP_Copy in previously generated code.
  132666. **
  132667. ** This routine runs over generated VDBE code and translates OP_Column
  132668. ** opcodes into OP_Copy when the table is being accessed via co-routine
  132669. ** instead of via table lookup.
  132670. **
  132671. ** If the iAutoidxCur is not zero, then any OP_Rowid instructions on
  132672. ** cursor iTabCur are transformed into OP_Sequence opcode for the
  132673. ** iAutoidxCur cursor, in order to generate unique rowids for the
  132674. ** automatic index being generated.
  132675. */
  132676. static void translateColumnToCopy(
  132677. Parse *pParse, /* Parsing context */
  132678. int iStart, /* Translate from this opcode to the end */
  132679. int iTabCur, /* OP_Column/OP_Rowid references to this table */
  132680. int iRegister, /* The first column is in this register */
  132681. int iAutoidxCur /* If non-zero, cursor of autoindex being generated */
  132682. ){
  132683. Vdbe *v = pParse->pVdbe;
  132684. VdbeOp *pOp = sqlite3VdbeGetOp(v, iStart);
  132685. int iEnd = sqlite3VdbeCurrentAddr(v);
  132686. if( pParse->db->mallocFailed ) return;
  132687. for(; iStart<iEnd; iStart++, pOp++){
  132688. if( pOp->p1!=iTabCur ) continue;
  132689. if( pOp->opcode==OP_Column ){
  132690. pOp->opcode = OP_Copy;
  132691. pOp->p1 = pOp->p2 + iRegister;
  132692. pOp->p2 = pOp->p3;
  132693. pOp->p3 = 0;
  132694. }else if( pOp->opcode==OP_Rowid ){
  132695. if( iAutoidxCur ){
  132696. pOp->opcode = OP_Sequence;
  132697. pOp->p1 = iAutoidxCur;
  132698. }else{
  132699. pOp->opcode = OP_Null;
  132700. pOp->p1 = 0;
  132701. pOp->p3 = 0;
  132702. }
  132703. }
  132704. }
  132705. }
  132706. /*
  132707. ** Two routines for printing the content of an sqlite3_index_info
  132708. ** structure. Used for testing and debugging only. If neither
  132709. ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
  132710. ** are no-ops.
  132711. */
  132712. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
  132713. static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
  132714. int i;
  132715. if( !sqlite3WhereTrace ) return;
  132716. for(i=0; i<p->nConstraint; i++){
  132717. sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
  132718. i,
  132719. p->aConstraint[i].iColumn,
  132720. p->aConstraint[i].iTermOffset,
  132721. p->aConstraint[i].op,
  132722. p->aConstraint[i].usable);
  132723. }
  132724. for(i=0; i<p->nOrderBy; i++){
  132725. sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
  132726. i,
  132727. p->aOrderBy[i].iColumn,
  132728. p->aOrderBy[i].desc);
  132729. }
  132730. }
  132731. static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
  132732. int i;
  132733. if( !sqlite3WhereTrace ) return;
  132734. for(i=0; i<p->nConstraint; i++){
  132735. sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
  132736. i,
  132737. p->aConstraintUsage[i].argvIndex,
  132738. p->aConstraintUsage[i].omit);
  132739. }
  132740. sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
  132741. sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
  132742. sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
  132743. sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
  132744. sqlite3DebugPrintf(" estimatedRows=%lld\n", p->estimatedRows);
  132745. }
  132746. #else
  132747. #define TRACE_IDX_INPUTS(A)
  132748. #define TRACE_IDX_OUTPUTS(A)
  132749. #endif
  132750. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  132751. /*
  132752. ** Return TRUE if the WHERE clause term pTerm is of a form where it
  132753. ** could be used with an index to access pSrc, assuming an appropriate
  132754. ** index existed.
  132755. */
  132756. static int termCanDriveIndex(
  132757. WhereTerm *pTerm, /* WHERE clause term to check */
  132758. struct SrcList_item *pSrc, /* Table we are trying to access */
  132759. Bitmask notReady /* Tables in outer loops of the join */
  132760. ){
  132761. char aff;
  132762. if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
  132763. if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) return 0;
  132764. if( (pSrc->fg.jointype & JT_LEFT)
  132765. && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
  132766. && (pTerm->eOperator & WO_IS)
  132767. ){
  132768. /* Cannot use an IS term from the WHERE clause as an index driver for
  132769. ** the RHS of a LEFT JOIN. Such a term can only be used if it is from
  132770. ** the ON clause. */
  132771. return 0;
  132772. }
  132773. if( (pTerm->prereqRight & notReady)!=0 ) return 0;
  132774. if( pTerm->u.leftColumn<0 ) return 0;
  132775. aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
  132776. if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
  132777. testcase( pTerm->pExpr->op==TK_IS );
  132778. return 1;
  132779. }
  132780. #endif
  132781. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  132782. /*
  132783. ** Generate code to construct the Index object for an automatic index
  132784. ** and to set up the WhereLevel object pLevel so that the code generator
  132785. ** makes use of the automatic index.
  132786. */
  132787. static void constructAutomaticIndex(
  132788. Parse *pParse, /* The parsing context */
  132789. WhereClause *pWC, /* The WHERE clause */
  132790. struct SrcList_item *pSrc, /* The FROM clause term to get the next index */
  132791. Bitmask notReady, /* Mask of cursors that are not available */
  132792. WhereLevel *pLevel /* Write new index here */
  132793. ){
  132794. int nKeyCol; /* Number of columns in the constructed index */
  132795. WhereTerm *pTerm; /* A single term of the WHERE clause */
  132796. WhereTerm *pWCEnd; /* End of pWC->a[] */
  132797. Index *pIdx; /* Object describing the transient index */
  132798. Vdbe *v; /* Prepared statement under construction */
  132799. int addrInit; /* Address of the initialization bypass jump */
  132800. Table *pTable; /* The table being indexed */
  132801. int addrTop; /* Top of the index fill loop */
  132802. int regRecord; /* Register holding an index record */
  132803. int n; /* Column counter */
  132804. int i; /* Loop counter */
  132805. int mxBitCol; /* Maximum column in pSrc->colUsed */
  132806. CollSeq *pColl; /* Collating sequence to on a column */
  132807. WhereLoop *pLoop; /* The Loop object */
  132808. char *zNotUsed; /* Extra space on the end of pIdx */
  132809. Bitmask idxCols; /* Bitmap of columns used for indexing */
  132810. Bitmask extraCols; /* Bitmap of additional columns */
  132811. u8 sentWarning = 0; /* True if a warnning has been issued */
  132812. Expr *pPartial = 0; /* Partial Index Expression */
  132813. int iContinue = 0; /* Jump here to skip excluded rows */
  132814. struct SrcList_item *pTabItem; /* FROM clause term being indexed */
  132815. int addrCounter = 0; /* Address where integer counter is initialized */
  132816. int regBase; /* Array of registers where record is assembled */
  132817. /* Generate code to skip over the creation and initialization of the
  132818. ** transient index on 2nd and subsequent iterations of the loop. */
  132819. v = pParse->pVdbe;
  132820. assert( v!=0 );
  132821. addrInit = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  132822. /* Count the number of columns that will be added to the index
  132823. ** and used to match WHERE clause constraints */
  132824. nKeyCol = 0;
  132825. pTable = pSrc->pTab;
  132826. pWCEnd = &pWC->a[pWC->nTerm];
  132827. pLoop = pLevel->pWLoop;
  132828. idxCols = 0;
  132829. for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
  132830. Expr *pExpr = pTerm->pExpr;
  132831. assert( !ExprHasProperty(pExpr, EP_FromJoin) /* prereq always non-zero */
  132832. || pExpr->iRightJoinTable!=pSrc->iCursor /* for the right-hand */
  132833. || pLoop->prereq!=0 ); /* table of a LEFT JOIN */
  132834. if( pLoop->prereq==0
  132835. && (pTerm->wtFlags & TERM_VIRTUAL)==0
  132836. && !ExprHasProperty(pExpr, EP_FromJoin)
  132837. && sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor) ){
  132838. pPartial = sqlite3ExprAnd(pParse, pPartial,
  132839. sqlite3ExprDup(pParse->db, pExpr, 0));
  132840. }
  132841. if( termCanDriveIndex(pTerm, pSrc, notReady) ){
  132842. int iCol = pTerm->u.leftColumn;
  132843. Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
  132844. testcase( iCol==BMS );
  132845. testcase( iCol==BMS-1 );
  132846. if( !sentWarning ){
  132847. sqlite3_log(SQLITE_WARNING_AUTOINDEX,
  132848. "automatic index on %s(%s)", pTable->zName,
  132849. pTable->aCol[iCol].zName);
  132850. sentWarning = 1;
  132851. }
  132852. if( (idxCols & cMask)==0 ){
  132853. if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ){
  132854. goto end_auto_index_create;
  132855. }
  132856. pLoop->aLTerm[nKeyCol++] = pTerm;
  132857. idxCols |= cMask;
  132858. }
  132859. }
  132860. }
  132861. assert( nKeyCol>0 );
  132862. pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;
  132863. pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
  132864. | WHERE_AUTO_INDEX;
  132865. /* Count the number of additional columns needed to create a
  132866. ** covering index. A "covering index" is an index that contains all
  132867. ** columns that are needed by the query. With a covering index, the
  132868. ** original table never needs to be accessed. Automatic indices must
  132869. ** be a covering index because the index will not be updated if the
  132870. ** original table changes and the index and table cannot both be used
  132871. ** if they go out of sync.
  132872. */
  132873. extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
  132874. mxBitCol = MIN(BMS-1,pTable->nCol);
  132875. testcase( pTable->nCol==BMS-1 );
  132876. testcase( pTable->nCol==BMS-2 );
  132877. for(i=0; i<mxBitCol; i++){
  132878. if( extraCols & MASKBIT(i) ) nKeyCol++;
  132879. }
  132880. if( pSrc->colUsed & MASKBIT(BMS-1) ){
  132881. nKeyCol += pTable->nCol - BMS + 1;
  132882. }
  132883. /* Construct the Index object to describe this index */
  132884. pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed);
  132885. if( pIdx==0 ) goto end_auto_index_create;
  132886. pLoop->u.btree.pIndex = pIdx;
  132887. pIdx->zName = "auto-index";
  132888. pIdx->pTable = pTable;
  132889. n = 0;
  132890. idxCols = 0;
  132891. for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
  132892. if( termCanDriveIndex(pTerm, pSrc, notReady) ){
  132893. int iCol = pTerm->u.leftColumn;
  132894. Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
  132895. testcase( iCol==BMS-1 );
  132896. testcase( iCol==BMS );
  132897. if( (idxCols & cMask)==0 ){
  132898. Expr *pX = pTerm->pExpr;
  132899. idxCols |= cMask;
  132900. pIdx->aiColumn[n] = pTerm->u.leftColumn;
  132901. pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
  132902. pIdx->azColl[n] = pColl ? pColl->zName : sqlite3StrBINARY;
  132903. n++;
  132904. }
  132905. }
  132906. }
  132907. assert( (u32)n==pLoop->u.btree.nEq );
  132908. /* Add additional columns needed to make the automatic index into
  132909. ** a covering index */
  132910. for(i=0; i<mxBitCol; i++){
  132911. if( extraCols & MASKBIT(i) ){
  132912. pIdx->aiColumn[n] = i;
  132913. pIdx->azColl[n] = sqlite3StrBINARY;
  132914. n++;
  132915. }
  132916. }
  132917. if( pSrc->colUsed & MASKBIT(BMS-1) ){
  132918. for(i=BMS-1; i<pTable->nCol; i++){
  132919. pIdx->aiColumn[n] = i;
  132920. pIdx->azColl[n] = sqlite3StrBINARY;
  132921. n++;
  132922. }
  132923. }
  132924. assert( n==nKeyCol );
  132925. pIdx->aiColumn[n] = XN_ROWID;
  132926. pIdx->azColl[n] = sqlite3StrBINARY;
  132927. /* Create the automatic index */
  132928. assert( pLevel->iIdxCur>=0 );
  132929. pLevel->iIdxCur = pParse->nTab++;
  132930. sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);
  132931. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  132932. VdbeComment((v, "for %s", pTable->zName));
  132933. /* Fill the automatic index with content */
  132934. pTabItem = &pWC->pWInfo->pTabList->a[pLevel->iFrom];
  132935. if( pTabItem->fg.viaCoroutine ){
  132936. int regYield = pTabItem->regReturn;
  132937. addrCounter = sqlite3VdbeAddOp2(v, OP_Integer, 0, 0);
  132938. sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
  132939. addrTop = sqlite3VdbeAddOp1(v, OP_Yield, regYield);
  132940. VdbeCoverage(v);
  132941. VdbeComment((v, "next row of %s", pTabItem->pTab->zName));
  132942. }else{
  132943. addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);
  132944. }
  132945. if( pPartial ){
  132946. iContinue = sqlite3VdbeMakeLabel(pParse);
  132947. sqlite3ExprIfFalse(pParse, pPartial, iContinue, SQLITE_JUMPIFNULL);
  132948. pLoop->wsFlags |= WHERE_PARTIALIDX;
  132949. }
  132950. regRecord = sqlite3GetTempReg(pParse);
  132951. regBase = sqlite3GenerateIndexKey(
  132952. pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0
  132953. );
  132954. sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
  132955. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  132956. if( pPartial ) sqlite3VdbeResolveLabel(v, iContinue);
  132957. if( pTabItem->fg.viaCoroutine ){
  132958. sqlite3VdbeChangeP2(v, addrCounter, regBase+n);
  132959. testcase( pParse->db->mallocFailed );
  132960. assert( pLevel->iIdxCur>0 );
  132961. translateColumnToCopy(pParse, addrTop, pLevel->iTabCur,
  132962. pTabItem->regResult, pLevel->iIdxCur);
  132963. sqlite3VdbeGoto(v, addrTop);
  132964. pTabItem->fg.viaCoroutine = 0;
  132965. }else{
  132966. sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);
  132967. }
  132968. sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
  132969. sqlite3VdbeJumpHere(v, addrTop);
  132970. sqlite3ReleaseTempReg(pParse, regRecord);
  132971. /* Jump here when skipping the initialization */
  132972. sqlite3VdbeJumpHere(v, addrInit);
  132973. end_auto_index_create:
  132974. sqlite3ExprDelete(pParse->db, pPartial);
  132975. }
  132976. #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
  132977. #ifndef SQLITE_OMIT_VIRTUALTABLE
  132978. /*
  132979. ** Allocate and populate an sqlite3_index_info structure. It is the
  132980. ** responsibility of the caller to eventually release the structure
  132981. ** by passing the pointer returned by this function to sqlite3_free().
  132982. */
  132983. static sqlite3_index_info *allocateIndexInfo(
  132984. Parse *pParse, /* The parsing context */
  132985. WhereClause *pWC, /* The WHERE clause being analyzed */
  132986. Bitmask mUnusable, /* Ignore terms with these prereqs */
  132987. struct SrcList_item *pSrc, /* The FROM clause term that is the vtab */
  132988. ExprList *pOrderBy, /* The ORDER BY clause */
  132989. u16 *pmNoOmit /* Mask of terms not to omit */
  132990. ){
  132991. int i, j;
  132992. int nTerm;
  132993. struct sqlite3_index_constraint *pIdxCons;
  132994. struct sqlite3_index_orderby *pIdxOrderBy;
  132995. struct sqlite3_index_constraint_usage *pUsage;
  132996. struct HiddenIndexInfo *pHidden;
  132997. WhereTerm *pTerm;
  132998. int nOrderBy;
  132999. sqlite3_index_info *pIdxInfo;
  133000. u16 mNoOmit = 0;
  133001. /* Count the number of possible WHERE clause constraints referring
  133002. ** to this virtual table */
  133003. for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  133004. if( pTerm->leftCursor != pSrc->iCursor ) continue;
  133005. if( pTerm->prereqRight & mUnusable ) continue;
  133006. assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
  133007. testcase( pTerm->eOperator & WO_IN );
  133008. testcase( pTerm->eOperator & WO_ISNULL );
  133009. testcase( pTerm->eOperator & WO_IS );
  133010. testcase( pTerm->eOperator & WO_ALL );
  133011. if( (pTerm->eOperator & ~(WO_EQUIV))==0 ) continue;
  133012. if( pTerm->wtFlags & TERM_VNULL ) continue;
  133013. assert( pTerm->u.leftColumn>=(-1) );
  133014. nTerm++;
  133015. }
  133016. /* If the ORDER BY clause contains only columns in the current
  133017. ** virtual table then allocate space for the aOrderBy part of
  133018. ** the sqlite3_index_info structure.
  133019. */
  133020. nOrderBy = 0;
  133021. if( pOrderBy ){
  133022. int n = pOrderBy->nExpr;
  133023. for(i=0; i<n; i++){
  133024. Expr *pExpr = pOrderBy->a[i].pExpr;
  133025. if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
  133026. }
  133027. if( i==n){
  133028. nOrderBy = n;
  133029. }
  133030. }
  133031. /* Allocate the sqlite3_index_info structure
  133032. */
  133033. pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
  133034. + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
  133035. + sizeof(*pIdxOrderBy)*nOrderBy + sizeof(*pHidden) );
  133036. if( pIdxInfo==0 ){
  133037. sqlite3ErrorMsg(pParse, "out of memory");
  133038. return 0;
  133039. }
  133040. /* Initialize the structure. The sqlite3_index_info structure contains
  133041. ** many fields that are declared "const" to prevent xBestIndex from
  133042. ** changing them. We have to do some funky casting in order to
  133043. ** initialize those fields.
  133044. */
  133045. pHidden = (struct HiddenIndexInfo*)&pIdxInfo[1];
  133046. pIdxCons = (struct sqlite3_index_constraint*)&pHidden[1];
  133047. pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
  133048. pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
  133049. *(int*)&pIdxInfo->nConstraint = nTerm;
  133050. *(int*)&pIdxInfo->nOrderBy = nOrderBy;
  133051. *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
  133052. *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
  133053. *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
  133054. pUsage;
  133055. pHidden->pWC = pWC;
  133056. pHidden->pParse = pParse;
  133057. for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  133058. u16 op;
  133059. if( pTerm->leftCursor != pSrc->iCursor ) continue;
  133060. if( pTerm->prereqRight & mUnusable ) continue;
  133061. assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
  133062. testcase( pTerm->eOperator & WO_IN );
  133063. testcase( pTerm->eOperator & WO_IS );
  133064. testcase( pTerm->eOperator & WO_ISNULL );
  133065. testcase( pTerm->eOperator & WO_ALL );
  133066. if( (pTerm->eOperator & ~(WO_EQUIV))==0 ) continue;
  133067. if( pTerm->wtFlags & TERM_VNULL ) continue;
  133068. if( (pSrc->fg.jointype & JT_LEFT)!=0
  133069. && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
  133070. && (pTerm->eOperator & (WO_IS|WO_ISNULL))
  133071. ){
  133072. /* An "IS" term in the WHERE clause where the virtual table is the rhs
  133073. ** of a LEFT JOIN. Do not pass this term to the virtual table
  133074. ** implementation, as this can lead to incorrect results from SQL such
  133075. ** as:
  133076. **
  133077. ** "LEFT JOIN vtab WHERE vtab.col IS NULL" */
  133078. testcase( pTerm->eOperator & WO_ISNULL );
  133079. testcase( pTerm->eOperator & WO_IS );
  133080. continue;
  133081. }
  133082. assert( pTerm->u.leftColumn>=(-1) );
  133083. pIdxCons[j].iColumn = pTerm->u.leftColumn;
  133084. pIdxCons[j].iTermOffset = i;
  133085. op = pTerm->eOperator & WO_ALL;
  133086. if( op==WO_IN ) op = WO_EQ;
  133087. if( op==WO_AUX ){
  133088. pIdxCons[j].op = pTerm->eMatchOp;
  133089. }else if( op & (WO_ISNULL|WO_IS) ){
  133090. if( op==WO_ISNULL ){
  133091. pIdxCons[j].op = SQLITE_INDEX_CONSTRAINT_ISNULL;
  133092. }else{
  133093. pIdxCons[j].op = SQLITE_INDEX_CONSTRAINT_IS;
  133094. }
  133095. }else{
  133096. pIdxCons[j].op = (u8)op;
  133097. /* The direct assignment in the previous line is possible only because
  133098. ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
  133099. ** following asserts verify this fact. */
  133100. assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
  133101. assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
  133102. assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
  133103. assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
  133104. assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
  133105. assert( pTerm->eOperator&(WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_AUX) );
  133106. if( op & (WO_LT|WO_LE|WO_GT|WO_GE)
  133107. && sqlite3ExprIsVector(pTerm->pExpr->pRight)
  133108. ){
  133109. if( i<16 ) mNoOmit |= (1 << i);
  133110. if( op==WO_LT ) pIdxCons[j].op = WO_LE;
  133111. if( op==WO_GT ) pIdxCons[j].op = WO_GE;
  133112. }
  133113. }
  133114. j++;
  133115. }
  133116. for(i=0; i<nOrderBy; i++){
  133117. Expr *pExpr = pOrderBy->a[i].pExpr;
  133118. pIdxOrderBy[i].iColumn = pExpr->iColumn;
  133119. pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
  133120. }
  133121. *pmNoOmit = mNoOmit;
  133122. return pIdxInfo;
  133123. }
  133124. /*
  133125. ** The table object reference passed as the second argument to this function
  133126. ** must represent a virtual table. This function invokes the xBestIndex()
  133127. ** method of the virtual table with the sqlite3_index_info object that
  133128. ** comes in as the 3rd argument to this function.
  133129. **
  133130. ** If an error occurs, pParse is populated with an error message and an
  133131. ** appropriate error code is returned. A return of SQLITE_CONSTRAINT from
  133132. ** xBestIndex is not considered an error. SQLITE_CONSTRAINT indicates that
  133133. ** the current configuration of "unusable" flags in sqlite3_index_info can
  133134. ** not result in a valid plan.
  133135. **
  133136. ** Whether or not an error is returned, it is the responsibility of the
  133137. ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
  133138. ** that this is required.
  133139. */
  133140. static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
  133141. sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
  133142. int rc;
  133143. TRACE_IDX_INPUTS(p);
  133144. rc = pVtab->pModule->xBestIndex(pVtab, p);
  133145. TRACE_IDX_OUTPUTS(p);
  133146. if( rc!=SQLITE_OK && rc!=SQLITE_CONSTRAINT ){
  133147. if( rc==SQLITE_NOMEM ){
  133148. sqlite3OomFault(pParse->db);
  133149. }else if( !pVtab->zErrMsg ){
  133150. sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
  133151. }else{
  133152. sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
  133153. }
  133154. }
  133155. sqlite3_free(pVtab->zErrMsg);
  133156. pVtab->zErrMsg = 0;
  133157. return rc;
  133158. }
  133159. #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
  133160. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  133161. /*
  133162. ** Estimate the location of a particular key among all keys in an
  133163. ** index. Store the results in aStat as follows:
  133164. **
  133165. ** aStat[0] Est. number of rows less than pRec
  133166. ** aStat[1] Est. number of rows equal to pRec
  133167. **
  133168. ** Return the index of the sample that is the smallest sample that
  133169. ** is greater than or equal to pRec. Note that this index is not an index
  133170. ** into the aSample[] array - it is an index into a virtual set of samples
  133171. ** based on the contents of aSample[] and the number of fields in record
  133172. ** pRec.
  133173. */
  133174. static int whereKeyStats(
  133175. Parse *pParse, /* Database connection */
  133176. Index *pIdx, /* Index to consider domain of */
  133177. UnpackedRecord *pRec, /* Vector of values to consider */
  133178. int roundUp, /* Round up if true. Round down if false */
  133179. tRowcnt *aStat /* OUT: stats written here */
  133180. ){
  133181. IndexSample *aSample = pIdx->aSample;
  133182. int iCol; /* Index of required stats in anEq[] etc. */
  133183. int i; /* Index of first sample >= pRec */
  133184. int iSample; /* Smallest sample larger than or equal to pRec */
  133185. int iMin = 0; /* Smallest sample not yet tested */
  133186. int iTest; /* Next sample to test */
  133187. int res; /* Result of comparison operation */
  133188. int nField; /* Number of fields in pRec */
  133189. tRowcnt iLower = 0; /* anLt[] + anEq[] of largest sample pRec is > */
  133190. #ifndef SQLITE_DEBUG
  133191. UNUSED_PARAMETER( pParse );
  133192. #endif
  133193. assert( pRec!=0 );
  133194. assert( pIdx->nSample>0 );
  133195. assert( pRec->nField>0 && pRec->nField<=pIdx->nSampleCol );
  133196. /* Do a binary search to find the first sample greater than or equal
  133197. ** to pRec. If pRec contains a single field, the set of samples to search
  133198. ** is simply the aSample[] array. If the samples in aSample[] contain more
  133199. ** than one fields, all fields following the first are ignored.
  133200. **
  133201. ** If pRec contains N fields, where N is more than one, then as well as the
  133202. ** samples in aSample[] (truncated to N fields), the search also has to
  133203. ** consider prefixes of those samples. For example, if the set of samples
  133204. ** in aSample is:
  133205. **
  133206. ** aSample[0] = (a, 5)
  133207. ** aSample[1] = (a, 10)
  133208. ** aSample[2] = (b, 5)
  133209. ** aSample[3] = (c, 100)
  133210. ** aSample[4] = (c, 105)
  133211. **
  133212. ** Then the search space should ideally be the samples above and the
  133213. ** unique prefixes [a], [b] and [c]. But since that is hard to organize,
  133214. ** the code actually searches this set:
  133215. **
  133216. ** 0: (a)
  133217. ** 1: (a, 5)
  133218. ** 2: (a, 10)
  133219. ** 3: (a, 10)
  133220. ** 4: (b)
  133221. ** 5: (b, 5)
  133222. ** 6: (c)
  133223. ** 7: (c, 100)
  133224. ** 8: (c, 105)
  133225. ** 9: (c, 105)
  133226. **
  133227. ** For each sample in the aSample[] array, N samples are present in the
  133228. ** effective sample array. In the above, samples 0 and 1 are based on
  133229. ** sample aSample[0]. Samples 2 and 3 on aSample[1] etc.
  133230. **
  133231. ** Often, sample i of each block of N effective samples has (i+1) fields.
  133232. ** Except, each sample may be extended to ensure that it is greater than or
  133233. ** equal to the previous sample in the array. For example, in the above,
  133234. ** sample 2 is the first sample of a block of N samples, so at first it
  133235. ** appears that it should be 1 field in size. However, that would make it
  133236. ** smaller than sample 1, so the binary search would not work. As a result,
  133237. ** it is extended to two fields. The duplicates that this creates do not
  133238. ** cause any problems.
  133239. */
  133240. nField = pRec->nField;
  133241. iCol = 0;
  133242. iSample = pIdx->nSample * nField;
  133243. do{
  133244. int iSamp; /* Index in aSample[] of test sample */
  133245. int n; /* Number of fields in test sample */
  133246. iTest = (iMin+iSample)/2;
  133247. iSamp = iTest / nField;
  133248. if( iSamp>0 ){
  133249. /* The proposed effective sample is a prefix of sample aSample[iSamp].
  133250. ** Specifically, the shortest prefix of at least (1 + iTest%nField)
  133251. ** fields that is greater than the previous effective sample. */
  133252. for(n=(iTest % nField) + 1; n<nField; n++){
  133253. if( aSample[iSamp-1].anLt[n-1]!=aSample[iSamp].anLt[n-1] ) break;
  133254. }
  133255. }else{
  133256. n = iTest + 1;
  133257. }
  133258. pRec->nField = n;
  133259. res = sqlite3VdbeRecordCompare(aSample[iSamp].n, aSample[iSamp].p, pRec);
  133260. if( res<0 ){
  133261. iLower = aSample[iSamp].anLt[n-1] + aSample[iSamp].anEq[n-1];
  133262. iMin = iTest+1;
  133263. }else if( res==0 && n<nField ){
  133264. iLower = aSample[iSamp].anLt[n-1];
  133265. iMin = iTest+1;
  133266. res = -1;
  133267. }else{
  133268. iSample = iTest;
  133269. iCol = n-1;
  133270. }
  133271. }while( res && iMin<iSample );
  133272. i = iSample / nField;
  133273. #ifdef SQLITE_DEBUG
  133274. /* The following assert statements check that the binary search code
  133275. ** above found the right answer. This block serves no purpose other
  133276. ** than to invoke the asserts. */
  133277. if( pParse->db->mallocFailed==0 ){
  133278. if( res==0 ){
  133279. /* If (res==0) is true, then pRec must be equal to sample i. */
  133280. assert( i<pIdx->nSample );
  133281. assert( iCol==nField-1 );
  133282. pRec->nField = nField;
  133283. assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)
  133284. || pParse->db->mallocFailed
  133285. );
  133286. }else{
  133287. /* Unless i==pIdx->nSample, indicating that pRec is larger than
  133288. ** all samples in the aSample[] array, pRec must be smaller than the
  133289. ** (iCol+1) field prefix of sample i. */
  133290. assert( i<=pIdx->nSample && i>=0 );
  133291. pRec->nField = iCol+1;
  133292. assert( i==pIdx->nSample
  133293. || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
  133294. || pParse->db->mallocFailed );
  133295. /* if i==0 and iCol==0, then record pRec is smaller than all samples
  133296. ** in the aSample[] array. Otherwise, if (iCol>0) then pRec must
  133297. ** be greater than or equal to the (iCol) field prefix of sample i.
  133298. ** If (i>0), then pRec must also be greater than sample (i-1). */
  133299. if( iCol>0 ){
  133300. pRec->nField = iCol;
  133301. assert( sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)<=0
  133302. || pParse->db->mallocFailed );
  133303. }
  133304. if( i>0 ){
  133305. pRec->nField = nField;
  133306. assert( sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
  133307. || pParse->db->mallocFailed );
  133308. }
  133309. }
  133310. }
  133311. #endif /* ifdef SQLITE_DEBUG */
  133312. if( res==0 ){
  133313. /* Record pRec is equal to sample i */
  133314. assert( iCol==nField-1 );
  133315. aStat[0] = aSample[i].anLt[iCol];
  133316. aStat[1] = aSample[i].anEq[iCol];
  133317. }else{
  133318. /* At this point, the (iCol+1) field prefix of aSample[i] is the first
  133319. ** sample that is greater than pRec. Or, if i==pIdx->nSample then pRec
  133320. ** is larger than all samples in the array. */
  133321. tRowcnt iUpper, iGap;
  133322. if( i>=pIdx->nSample ){
  133323. iUpper = sqlite3LogEstToInt(pIdx->aiRowLogEst[0]);
  133324. }else{
  133325. iUpper = aSample[i].anLt[iCol];
  133326. }
  133327. if( iLower>=iUpper ){
  133328. iGap = 0;
  133329. }else{
  133330. iGap = iUpper - iLower;
  133331. }
  133332. if( roundUp ){
  133333. iGap = (iGap*2)/3;
  133334. }else{
  133335. iGap = iGap/3;
  133336. }
  133337. aStat[0] = iLower + iGap;
  133338. aStat[1] = pIdx->aAvgEq[nField-1];
  133339. }
  133340. /* Restore the pRec->nField value before returning. */
  133341. pRec->nField = nField;
  133342. return i;
  133343. }
  133344. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  133345. /*
  133346. ** If it is not NULL, pTerm is a term that provides an upper or lower
  133347. ** bound on a range scan. Without considering pTerm, it is estimated
  133348. ** that the scan will visit nNew rows. This function returns the number
  133349. ** estimated to be visited after taking pTerm into account.
  133350. **
  133351. ** If the user explicitly specified a likelihood() value for this term,
  133352. ** then the return value is the likelihood multiplied by the number of
  133353. ** input rows. Otherwise, this function assumes that an "IS NOT NULL" term
  133354. ** has a likelihood of 0.50, and any other term a likelihood of 0.25.
  133355. */
  133356. static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){
  133357. LogEst nRet = nNew;
  133358. if( pTerm ){
  133359. if( pTerm->truthProb<=0 ){
  133360. nRet += pTerm->truthProb;
  133361. }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){
  133362. nRet -= 20; assert( 20==sqlite3LogEst(4) );
  133363. }
  133364. }
  133365. return nRet;
  133366. }
  133367. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  133368. /*
  133369. ** Return the affinity for a single column of an index.
  133370. */
  133371. SQLITE_PRIVATE char sqlite3IndexColumnAffinity(sqlite3 *db, Index *pIdx, int iCol){
  133372. assert( iCol>=0 && iCol<pIdx->nColumn );
  133373. if( !pIdx->zColAff ){
  133374. if( sqlite3IndexAffinityStr(db, pIdx)==0 ) return SQLITE_AFF_BLOB;
  133375. }
  133376. return pIdx->zColAff[iCol];
  133377. }
  133378. #endif
  133379. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  133380. /*
  133381. ** This function is called to estimate the number of rows visited by a
  133382. ** range-scan on a skip-scan index. For example:
  133383. **
  133384. ** CREATE INDEX i1 ON t1(a, b, c);
  133385. ** SELECT * FROM t1 WHERE a=? AND c BETWEEN ? AND ?;
  133386. **
  133387. ** Value pLoop->nOut is currently set to the estimated number of rows
  133388. ** visited for scanning (a=? AND b=?). This function reduces that estimate
  133389. ** by some factor to account for the (c BETWEEN ? AND ?) expression based
  133390. ** on the stat4 data for the index. this scan will be peformed multiple
  133391. ** times (once for each (a,b) combination that matches a=?) is dealt with
  133392. ** by the caller.
  133393. **
  133394. ** It does this by scanning through all stat4 samples, comparing values
  133395. ** extracted from pLower and pUpper with the corresponding column in each
  133396. ** sample. If L and U are the number of samples found to be less than or
  133397. ** equal to the values extracted from pLower and pUpper respectively, and
  133398. ** N is the total number of samples, the pLoop->nOut value is adjusted
  133399. ** as follows:
  133400. **
  133401. ** nOut = nOut * ( min(U - L, 1) / N )
  133402. **
  133403. ** If pLower is NULL, or a value cannot be extracted from the term, L is
  133404. ** set to zero. If pUpper is NULL, or a value cannot be extracted from it,
  133405. ** U is set to N.
  133406. **
  133407. ** Normally, this function sets *pbDone to 1 before returning. However,
  133408. ** if no value can be extracted from either pLower or pUpper (and so the
  133409. ** estimate of the number of rows delivered remains unchanged), *pbDone
  133410. ** is left as is.
  133411. **
  133412. ** If an error occurs, an SQLite error code is returned. Otherwise,
  133413. ** SQLITE_OK.
  133414. */
  133415. static int whereRangeSkipScanEst(
  133416. Parse *pParse, /* Parsing & code generating context */
  133417. WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
  133418. WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
  133419. WhereLoop *pLoop, /* Update the .nOut value of this loop */
  133420. int *pbDone /* Set to true if at least one expr. value extracted */
  133421. ){
  133422. Index *p = pLoop->u.btree.pIndex;
  133423. int nEq = pLoop->u.btree.nEq;
  133424. sqlite3 *db = pParse->db;
  133425. int nLower = -1;
  133426. int nUpper = p->nSample+1;
  133427. int rc = SQLITE_OK;
  133428. u8 aff = sqlite3IndexColumnAffinity(db, p, nEq);
  133429. CollSeq *pColl;
  133430. sqlite3_value *p1 = 0; /* Value extracted from pLower */
  133431. sqlite3_value *p2 = 0; /* Value extracted from pUpper */
  133432. sqlite3_value *pVal = 0; /* Value extracted from record */
  133433. pColl = sqlite3LocateCollSeq(pParse, p->azColl[nEq]);
  133434. if( pLower ){
  133435. rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1);
  133436. nLower = 0;
  133437. }
  133438. if( pUpper && rc==SQLITE_OK ){
  133439. rc = sqlite3Stat4ValueFromExpr(pParse, pUpper->pExpr->pRight, aff, &p2);
  133440. nUpper = p2 ? 0 : p->nSample;
  133441. }
  133442. if( p1 || p2 ){
  133443. int i;
  133444. int nDiff;
  133445. for(i=0; rc==SQLITE_OK && i<p->nSample; i++){
  133446. rc = sqlite3Stat4Column(db, p->aSample[i].p, p->aSample[i].n, nEq, &pVal);
  133447. if( rc==SQLITE_OK && p1 ){
  133448. int res = sqlite3MemCompare(p1, pVal, pColl);
  133449. if( res>=0 ) nLower++;
  133450. }
  133451. if( rc==SQLITE_OK && p2 ){
  133452. int res = sqlite3MemCompare(p2, pVal, pColl);
  133453. if( res>=0 ) nUpper++;
  133454. }
  133455. }
  133456. nDiff = (nUpper - nLower);
  133457. if( nDiff<=0 ) nDiff = 1;
  133458. /* If there is both an upper and lower bound specified, and the
  133459. ** comparisons indicate that they are close together, use the fallback
  133460. ** method (assume that the scan visits 1/64 of the rows) for estimating
  133461. ** the number of rows visited. Otherwise, estimate the number of rows
  133462. ** using the method described in the header comment for this function. */
  133463. if( nDiff!=1 || pUpper==0 || pLower==0 ){
  133464. int nAdjust = (sqlite3LogEst(p->nSample) - sqlite3LogEst(nDiff));
  133465. pLoop->nOut -= nAdjust;
  133466. *pbDone = 1;
  133467. WHERETRACE(0x10, ("range skip-scan regions: %u..%u adjust=%d est=%d\n",
  133468. nLower, nUpper, nAdjust*-1, pLoop->nOut));
  133469. }
  133470. }else{
  133471. assert( *pbDone==0 );
  133472. }
  133473. sqlite3ValueFree(p1);
  133474. sqlite3ValueFree(p2);
  133475. sqlite3ValueFree(pVal);
  133476. return rc;
  133477. }
  133478. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  133479. /*
  133480. ** This function is used to estimate the number of rows that will be visited
  133481. ** by scanning an index for a range of values. The range may have an upper
  133482. ** bound, a lower bound, or both. The WHERE clause terms that set the upper
  133483. ** and lower bounds are represented by pLower and pUpper respectively. For
  133484. ** example, assuming that index p is on t1(a):
  133485. **
  133486. ** ... FROM t1 WHERE a > ? AND a < ? ...
  133487. ** |_____| |_____|
  133488. ** | |
  133489. ** pLower pUpper
  133490. **
  133491. ** If either of the upper or lower bound is not present, then NULL is passed in
  133492. ** place of the corresponding WhereTerm.
  133493. **
  133494. ** The value in (pBuilder->pNew->u.btree.nEq) is the number of the index
  133495. ** column subject to the range constraint. Or, equivalently, the number of
  133496. ** equality constraints optimized by the proposed index scan. For example,
  133497. ** assuming index p is on t1(a, b), and the SQL query is:
  133498. **
  133499. ** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
  133500. **
  133501. ** then nEq is set to 1 (as the range restricted column, b, is the second
  133502. ** left-most column of the index). Or, if the query is:
  133503. **
  133504. ** ... FROM t1 WHERE a > ? AND a < ? ...
  133505. **
  133506. ** then nEq is set to 0.
  133507. **
  133508. ** When this function is called, *pnOut is set to the sqlite3LogEst() of the
  133509. ** number of rows that the index scan is expected to visit without
  133510. ** considering the range constraints. If nEq is 0, then *pnOut is the number of
  133511. ** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
  133512. ** to account for the range constraints pLower and pUpper.
  133513. **
  133514. ** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
  133515. ** used, a single range inequality reduces the search space by a factor of 4.
  133516. ** and a pair of constraints (x>? AND x<?) reduces the expected number of
  133517. ** rows visited by a factor of 64.
  133518. */
  133519. static int whereRangeScanEst(
  133520. Parse *pParse, /* Parsing & code generating context */
  133521. WhereLoopBuilder *pBuilder,
  133522. WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
  133523. WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
  133524. WhereLoop *pLoop /* Modify the .nOut and maybe .rRun fields */
  133525. ){
  133526. int rc = SQLITE_OK;
  133527. int nOut = pLoop->nOut;
  133528. LogEst nNew;
  133529. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  133530. Index *p = pLoop->u.btree.pIndex;
  133531. int nEq = pLoop->u.btree.nEq;
  133532. if( p->nSample>0 && nEq<p->nSampleCol
  133533. && OptimizationEnabled(pParse->db, SQLITE_Stat34)
  133534. ){
  133535. if( nEq==pBuilder->nRecValid ){
  133536. UnpackedRecord *pRec = pBuilder->pRec;
  133537. tRowcnt a[2];
  133538. int nBtm = pLoop->u.btree.nBtm;
  133539. int nTop = pLoop->u.btree.nTop;
  133540. /* Variable iLower will be set to the estimate of the number of rows in
  133541. ** the index that are less than the lower bound of the range query. The
  133542. ** lower bound being the concatenation of $P and $L, where $P is the
  133543. ** key-prefix formed by the nEq values matched against the nEq left-most
  133544. ** columns of the index, and $L is the value in pLower.
  133545. **
  133546. ** Or, if pLower is NULL or $L cannot be extracted from it (because it
  133547. ** is not a simple variable or literal value), the lower bound of the
  133548. ** range is $P. Due to a quirk in the way whereKeyStats() works, even
  133549. ** if $L is available, whereKeyStats() is called for both ($P) and
  133550. ** ($P:$L) and the larger of the two returned values is used.
  133551. **
  133552. ** Similarly, iUpper is to be set to the estimate of the number of rows
  133553. ** less than the upper bound of the range query. Where the upper bound
  133554. ** is either ($P) or ($P:$U). Again, even if $U is available, both values
  133555. ** of iUpper are requested of whereKeyStats() and the smaller used.
  133556. **
  133557. ** The number of rows between the two bounds is then just iUpper-iLower.
  133558. */
  133559. tRowcnt iLower; /* Rows less than the lower bound */
  133560. tRowcnt iUpper; /* Rows less than the upper bound */
  133561. int iLwrIdx = -2; /* aSample[] for the lower bound */
  133562. int iUprIdx = -1; /* aSample[] for the upper bound */
  133563. if( pRec ){
  133564. testcase( pRec->nField!=pBuilder->nRecValid );
  133565. pRec->nField = pBuilder->nRecValid;
  133566. }
  133567. /* Determine iLower and iUpper using ($P) only. */
  133568. if( nEq==0 ){
  133569. iLower = 0;
  133570. iUpper = p->nRowEst0;
  133571. }else{
  133572. /* Note: this call could be optimized away - since the same values must
  133573. ** have been requested when testing key $P in whereEqualScanEst(). */
  133574. whereKeyStats(pParse, p, pRec, 0, a);
  133575. iLower = a[0];
  133576. iUpper = a[0] + a[1];
  133577. }
  133578. assert( pLower==0 || (pLower->eOperator & (WO_GT|WO_GE))!=0 );
  133579. assert( pUpper==0 || (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
  133580. assert( p->aSortOrder!=0 );
  133581. if( p->aSortOrder[nEq] ){
  133582. /* The roles of pLower and pUpper are swapped for a DESC index */
  133583. SWAP(WhereTerm*, pLower, pUpper);
  133584. SWAP(int, nBtm, nTop);
  133585. }
  133586. /* If possible, improve on the iLower estimate using ($P:$L). */
  133587. if( pLower ){
  133588. int n; /* Values extracted from pExpr */
  133589. Expr *pExpr = pLower->pExpr->pRight;
  133590. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nBtm, nEq, &n);
  133591. if( rc==SQLITE_OK && n ){
  133592. tRowcnt iNew;
  133593. u16 mask = WO_GT|WO_LE;
  133594. if( sqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT);
  133595. iLwrIdx = whereKeyStats(pParse, p, pRec, 0, a);
  133596. iNew = a[0] + ((pLower->eOperator & mask) ? a[1] : 0);
  133597. if( iNew>iLower ) iLower = iNew;
  133598. nOut--;
  133599. pLower = 0;
  133600. }
  133601. }
  133602. /* If possible, improve on the iUpper estimate using ($P:$U). */
  133603. if( pUpper ){
  133604. int n; /* Values extracted from pExpr */
  133605. Expr *pExpr = pUpper->pExpr->pRight;
  133606. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nTop, nEq, &n);
  133607. if( rc==SQLITE_OK && n ){
  133608. tRowcnt iNew;
  133609. u16 mask = WO_GT|WO_LE;
  133610. if( sqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT);
  133611. iUprIdx = whereKeyStats(pParse, p, pRec, 1, a);
  133612. iNew = a[0] + ((pUpper->eOperator & mask) ? a[1] : 0);
  133613. if( iNew<iUpper ) iUpper = iNew;
  133614. nOut--;
  133615. pUpper = 0;
  133616. }
  133617. }
  133618. pBuilder->pRec = pRec;
  133619. if( rc==SQLITE_OK ){
  133620. if( iUpper>iLower ){
  133621. nNew = sqlite3LogEst(iUpper - iLower);
  133622. /* TUNING: If both iUpper and iLower are derived from the same
  133623. ** sample, then assume they are 4x more selective. This brings
  133624. ** the estimated selectivity more in line with what it would be
  133625. ** if estimated without the use of STAT3/4 tables. */
  133626. if( iLwrIdx==iUprIdx ) nNew -= 20; assert( 20==sqlite3LogEst(4) );
  133627. }else{
  133628. nNew = 10; assert( 10==sqlite3LogEst(2) );
  133629. }
  133630. if( nNew<nOut ){
  133631. nOut = nNew;
  133632. }
  133633. WHERETRACE(0x10, ("STAT4 range scan: %u..%u est=%d\n",
  133634. (u32)iLower, (u32)iUpper, nOut));
  133635. }
  133636. }else{
  133637. int bDone = 0;
  133638. rc = whereRangeSkipScanEst(pParse, pLower, pUpper, pLoop, &bDone);
  133639. if( bDone ) return rc;
  133640. }
  133641. }
  133642. #else
  133643. UNUSED_PARAMETER(pParse);
  133644. UNUSED_PARAMETER(pBuilder);
  133645. assert( pLower || pUpper );
  133646. #endif
  133647. assert( pUpper==0 || (pUpper->wtFlags & TERM_VNULL)==0 );
  133648. nNew = whereRangeAdjust(pLower, nOut);
  133649. nNew = whereRangeAdjust(pUpper, nNew);
  133650. /* TUNING: If there is both an upper and lower limit and neither limit
  133651. ** has an application-defined likelihood(), assume the range is
  133652. ** reduced by an additional 75%. This means that, by default, an open-ended
  133653. ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the
  133654. ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to
  133655. ** match 1/64 of the index. */
  133656. if( pLower && pLower->truthProb>0 && pUpper && pUpper->truthProb>0 ){
  133657. nNew -= 20;
  133658. }
  133659. nOut -= (pLower!=0) + (pUpper!=0);
  133660. if( nNew<10 ) nNew = 10;
  133661. if( nNew<nOut ) nOut = nNew;
  133662. #if defined(WHERETRACE_ENABLED)
  133663. if( pLoop->nOut>nOut ){
  133664. WHERETRACE(0x10,("Range scan lowers nOut from %d to %d\n",
  133665. pLoop->nOut, nOut));
  133666. }
  133667. #endif
  133668. pLoop->nOut = (LogEst)nOut;
  133669. return rc;
  133670. }
  133671. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  133672. /*
  133673. ** Estimate the number of rows that will be returned based on
  133674. ** an equality constraint x=VALUE and where that VALUE occurs in
  133675. ** the histogram data. This only works when x is the left-most
  133676. ** column of an index and sqlite_stat3 histogram data is available
  133677. ** for that index. When pExpr==NULL that means the constraint is
  133678. ** "x IS NULL" instead of "x=VALUE".
  133679. **
  133680. ** Write the estimated row count into *pnRow and return SQLITE_OK.
  133681. ** If unable to make an estimate, leave *pnRow unchanged and return
  133682. ** non-zero.
  133683. **
  133684. ** This routine can fail if it is unable to load a collating sequence
  133685. ** required for string comparison, or if unable to allocate memory
  133686. ** for a UTF conversion required for comparison. The error is stored
  133687. ** in the pParse structure.
  133688. */
  133689. static int whereEqualScanEst(
  133690. Parse *pParse, /* Parsing & code generating context */
  133691. WhereLoopBuilder *pBuilder,
  133692. Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */
  133693. tRowcnt *pnRow /* Write the revised row estimate here */
  133694. ){
  133695. Index *p = pBuilder->pNew->u.btree.pIndex;
  133696. int nEq = pBuilder->pNew->u.btree.nEq;
  133697. UnpackedRecord *pRec = pBuilder->pRec;
  133698. int rc; /* Subfunction return code */
  133699. tRowcnt a[2]; /* Statistics */
  133700. int bOk;
  133701. assert( nEq>=1 );
  133702. assert( nEq<=p->nColumn );
  133703. assert( p->aSample!=0 );
  133704. assert( p->nSample>0 );
  133705. assert( pBuilder->nRecValid<nEq );
  133706. /* If values are not available for all fields of the index to the left
  133707. ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
  133708. if( pBuilder->nRecValid<(nEq-1) ){
  133709. return SQLITE_NOTFOUND;
  133710. }
  133711. /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
  133712. ** below would return the same value. */
  133713. if( nEq>=p->nColumn ){
  133714. *pnRow = 1;
  133715. return SQLITE_OK;
  133716. }
  133717. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, 1, nEq-1, &bOk);
  133718. pBuilder->pRec = pRec;
  133719. if( rc!=SQLITE_OK ) return rc;
  133720. if( bOk==0 ) return SQLITE_NOTFOUND;
  133721. pBuilder->nRecValid = nEq;
  133722. whereKeyStats(pParse, p, pRec, 0, a);
  133723. WHERETRACE(0x10,("equality scan regions %s(%d): %d\n",
  133724. p->zName, nEq-1, (int)a[1]));
  133725. *pnRow = a[1];
  133726. return rc;
  133727. }
  133728. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  133729. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  133730. /*
  133731. ** Estimate the number of rows that will be returned based on
  133732. ** an IN constraint where the right-hand side of the IN operator
  133733. ** is a list of values. Example:
  133734. **
  133735. ** WHERE x IN (1,2,3,4)
  133736. **
  133737. ** Write the estimated row count into *pnRow and return SQLITE_OK.
  133738. ** If unable to make an estimate, leave *pnRow unchanged and return
  133739. ** non-zero.
  133740. **
  133741. ** This routine can fail if it is unable to load a collating sequence
  133742. ** required for string comparison, or if unable to allocate memory
  133743. ** for a UTF conversion required for comparison. The error is stored
  133744. ** in the pParse structure.
  133745. */
  133746. static int whereInScanEst(
  133747. Parse *pParse, /* Parsing & code generating context */
  133748. WhereLoopBuilder *pBuilder,
  133749. ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
  133750. tRowcnt *pnRow /* Write the revised row estimate here */
  133751. ){
  133752. Index *p = pBuilder->pNew->u.btree.pIndex;
  133753. i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]);
  133754. int nRecValid = pBuilder->nRecValid;
  133755. int rc = SQLITE_OK; /* Subfunction return code */
  133756. tRowcnt nEst; /* Number of rows for a single term */
  133757. tRowcnt nRowEst = 0; /* New estimate of the number of rows */
  133758. int i; /* Loop counter */
  133759. assert( p->aSample!=0 );
  133760. for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
  133761. nEst = nRow0;
  133762. rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
  133763. nRowEst += nEst;
  133764. pBuilder->nRecValid = nRecValid;
  133765. }
  133766. if( rc==SQLITE_OK ){
  133767. if( nRowEst > nRow0 ) nRowEst = nRow0;
  133768. *pnRow = nRowEst;
  133769. WHERETRACE(0x10,("IN row estimate: est=%d\n", nRowEst));
  133770. }
  133771. assert( pBuilder->nRecValid==nRecValid );
  133772. return rc;
  133773. }
  133774. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  133775. #ifdef WHERETRACE_ENABLED
  133776. /*
  133777. ** Print the content of a WhereTerm object
  133778. */
  133779. static void whereTermPrint(WhereTerm *pTerm, int iTerm){
  133780. if( pTerm==0 ){
  133781. sqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm);
  133782. }else{
  133783. char zType[4];
  133784. char zLeft[50];
  133785. memcpy(zType, "...", 4);
  133786. if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V';
  133787. if( pTerm->eOperator & WO_EQUIV ) zType[1] = 'E';
  133788. if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L';
  133789. if( pTerm->eOperator & WO_SINGLE ){
  133790. sqlite3_snprintf(sizeof(zLeft),zLeft,"left={%d:%d}",
  133791. pTerm->leftCursor, pTerm->u.leftColumn);
  133792. }else if( (pTerm->eOperator & WO_OR)!=0 && pTerm->u.pOrInfo!=0 ){
  133793. sqlite3_snprintf(sizeof(zLeft),zLeft,"indexable=0x%lld",
  133794. pTerm->u.pOrInfo->indexable);
  133795. }else{
  133796. sqlite3_snprintf(sizeof(zLeft),zLeft,"left=%d", pTerm->leftCursor);
  133797. }
  133798. sqlite3DebugPrintf(
  133799. "TERM-%-3d %p %s %-12s prob=%-3d op=0x%03x wtFlags=0x%04x",
  133800. iTerm, pTerm, zType, zLeft, pTerm->truthProb,
  133801. pTerm->eOperator, pTerm->wtFlags);
  133802. if( pTerm->iField ){
  133803. sqlite3DebugPrintf(" iField=%d\n", pTerm->iField);
  133804. }else{
  133805. sqlite3DebugPrintf("\n");
  133806. }
  133807. sqlite3TreeViewExpr(0, pTerm->pExpr, 0);
  133808. }
  133809. }
  133810. #endif
  133811. #ifdef WHERETRACE_ENABLED
  133812. /*
  133813. ** Show the complete content of a WhereClause
  133814. */
  133815. SQLITE_PRIVATE void sqlite3WhereClausePrint(WhereClause *pWC){
  133816. int i;
  133817. for(i=0; i<pWC->nTerm; i++){
  133818. whereTermPrint(&pWC->a[i], i);
  133819. }
  133820. }
  133821. #endif
  133822. #ifdef WHERETRACE_ENABLED
  133823. /*
  133824. ** Print a WhereLoop object for debugging purposes
  133825. */
  133826. static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){
  133827. WhereInfo *pWInfo = pWC->pWInfo;
  133828. int nb = 1+(pWInfo->pTabList->nSrc+3)/4;
  133829. struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab;
  133830. Table *pTab = pItem->pTab;
  133831. Bitmask mAll = (((Bitmask)1)<<(nb*4)) - 1;
  133832. sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
  133833. p->iTab, nb, p->maskSelf, nb, p->prereq & mAll);
  133834. sqlite3DebugPrintf(" %12s",
  133835. pItem->zAlias ? pItem->zAlias : pTab->zName);
  133836. if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
  133837. const char *zName;
  133838. if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){
  133839. if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
  133840. int i = sqlite3Strlen30(zName) - 1;
  133841. while( zName[i]!='_' ) i--;
  133842. zName += i;
  133843. }
  133844. sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
  133845. }else{
  133846. sqlite3DebugPrintf("%20s","");
  133847. }
  133848. }else{
  133849. char *z;
  133850. if( p->u.vtab.idxStr ){
  133851. z = sqlite3_mprintf("(%d,\"%s\",%x)",
  133852. p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
  133853. }else{
  133854. z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
  133855. }
  133856. sqlite3DebugPrintf(" %-19s", z);
  133857. sqlite3_free(z);
  133858. }
  133859. if( p->wsFlags & WHERE_SKIPSCAN ){
  133860. sqlite3DebugPrintf(" f %05x %d-%d", p->wsFlags, p->nLTerm,p->nSkip);
  133861. }else{
  133862. sqlite3DebugPrintf(" f %05x N %d", p->wsFlags, p->nLTerm);
  133863. }
  133864. sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
  133865. if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){
  133866. int i;
  133867. for(i=0; i<p->nLTerm; i++){
  133868. whereTermPrint(p->aLTerm[i], i);
  133869. }
  133870. }
  133871. }
  133872. #endif
  133873. /*
  133874. ** Convert bulk memory into a valid WhereLoop that can be passed
  133875. ** to whereLoopClear harmlessly.
  133876. */
  133877. static void whereLoopInit(WhereLoop *p){
  133878. p->aLTerm = p->aLTermSpace;
  133879. p->nLTerm = 0;
  133880. p->nLSlot = ArraySize(p->aLTermSpace);
  133881. p->wsFlags = 0;
  133882. }
  133883. /*
  133884. ** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact.
  133885. */
  133886. static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
  133887. if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
  133888. if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
  133889. sqlite3_free(p->u.vtab.idxStr);
  133890. p->u.vtab.needFree = 0;
  133891. p->u.vtab.idxStr = 0;
  133892. }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
  133893. sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
  133894. sqlite3DbFreeNN(db, p->u.btree.pIndex);
  133895. p->u.btree.pIndex = 0;
  133896. }
  133897. }
  133898. }
  133899. /*
  133900. ** Deallocate internal memory used by a WhereLoop object
  133901. */
  133902. static void whereLoopClear(sqlite3 *db, WhereLoop *p){
  133903. if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFreeNN(db, p->aLTerm);
  133904. whereLoopClearUnion(db, p);
  133905. whereLoopInit(p);
  133906. }
  133907. /*
  133908. ** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
  133909. */
  133910. static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
  133911. WhereTerm **paNew;
  133912. if( p->nLSlot>=n ) return SQLITE_OK;
  133913. n = (n+7)&~7;
  133914. paNew = sqlite3DbMallocRawNN(db, sizeof(p->aLTerm[0])*n);
  133915. if( paNew==0 ) return SQLITE_NOMEM_BKPT;
  133916. memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
  133917. if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFreeNN(db, p->aLTerm);
  133918. p->aLTerm = paNew;
  133919. p->nLSlot = n;
  133920. return SQLITE_OK;
  133921. }
  133922. /*
  133923. ** Transfer content from the second pLoop into the first.
  133924. */
  133925. static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
  133926. whereLoopClearUnion(db, pTo);
  133927. if( whereLoopResize(db, pTo, pFrom->nLTerm) ){
  133928. memset(&pTo->u, 0, sizeof(pTo->u));
  133929. return SQLITE_NOMEM_BKPT;
  133930. }
  133931. memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
  133932. memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
  133933. if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
  133934. pFrom->u.vtab.needFree = 0;
  133935. }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
  133936. pFrom->u.btree.pIndex = 0;
  133937. }
  133938. return SQLITE_OK;
  133939. }
  133940. /*
  133941. ** Delete a WhereLoop object
  133942. */
  133943. static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
  133944. whereLoopClear(db, p);
  133945. sqlite3DbFreeNN(db, p);
  133946. }
  133947. /*
  133948. ** Free a WhereInfo structure
  133949. */
  133950. static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
  133951. int i;
  133952. assert( pWInfo!=0 );
  133953. for(i=0; i<pWInfo->nLevel; i++){
  133954. WhereLevel *pLevel = &pWInfo->a[i];
  133955. if( pLevel->pWLoop && (pLevel->pWLoop->wsFlags & WHERE_IN_ABLE) ){
  133956. sqlite3DbFree(db, pLevel->u.in.aInLoop);
  133957. }
  133958. }
  133959. sqlite3WhereClauseClear(&pWInfo->sWC);
  133960. while( pWInfo->pLoops ){
  133961. WhereLoop *p = pWInfo->pLoops;
  133962. pWInfo->pLoops = p->pNextLoop;
  133963. whereLoopDelete(db, p);
  133964. }
  133965. sqlite3DbFreeNN(db, pWInfo);
  133966. }
  133967. /*
  133968. ** Return TRUE if all of the following are true:
  133969. **
  133970. ** (1) X has the same or lower cost that Y
  133971. ** (2) X uses fewer WHERE clause terms than Y
  133972. ** (3) Every WHERE clause term used by X is also used by Y
  133973. ** (4) X skips at least as many columns as Y
  133974. ** (5) If X is a covering index, than Y is too
  133975. **
  133976. ** Conditions (2) and (3) mean that X is a "proper subset" of Y.
  133977. ** If X is a proper subset of Y then Y is a better choice and ought
  133978. ** to have a lower cost. This routine returns TRUE when that cost
  133979. ** relationship is inverted and needs to be adjusted. Constraint (4)
  133980. ** was added because if X uses skip-scan less than Y it still might
  133981. ** deserve a lower cost even if it is a proper subset of Y. Constraint (5)
  133982. ** was added because a covering index probably deserves to have a lower cost
  133983. ** than a non-covering index even if it is a proper subset.
  133984. */
  133985. static int whereLoopCheaperProperSubset(
  133986. const WhereLoop *pX, /* First WhereLoop to compare */
  133987. const WhereLoop *pY /* Compare against this WhereLoop */
  133988. ){
  133989. int i, j;
  133990. if( pX->nLTerm-pX->nSkip >= pY->nLTerm-pY->nSkip ){
  133991. return 0; /* X is not a subset of Y */
  133992. }
  133993. if( pY->nSkip > pX->nSkip ) return 0;
  133994. if( pX->rRun >= pY->rRun ){
  133995. if( pX->rRun > pY->rRun ) return 0; /* X costs more than Y */
  133996. if( pX->nOut > pY->nOut ) return 0; /* X costs more than Y */
  133997. }
  133998. for(i=pX->nLTerm-1; i>=0; i--){
  133999. if( pX->aLTerm[i]==0 ) continue;
  134000. for(j=pY->nLTerm-1; j>=0; j--){
  134001. if( pY->aLTerm[j]==pX->aLTerm[i] ) break;
  134002. }
  134003. if( j<0 ) return 0; /* X not a subset of Y since term X[i] not used by Y */
  134004. }
  134005. if( (pX->wsFlags&WHERE_IDX_ONLY)!=0
  134006. && (pY->wsFlags&WHERE_IDX_ONLY)==0 ){
  134007. return 0; /* Constraint (5) */
  134008. }
  134009. return 1; /* All conditions meet */
  134010. }
  134011. /*
  134012. ** Try to adjust the cost of WhereLoop pTemplate upwards or downwards so
  134013. ** that:
  134014. **
  134015. ** (1) pTemplate costs less than any other WhereLoops that are a proper
  134016. ** subset of pTemplate
  134017. **
  134018. ** (2) pTemplate costs more than any other WhereLoops for which pTemplate
  134019. ** is a proper subset.
  134020. **
  134021. ** To say "WhereLoop X is a proper subset of Y" means that X uses fewer
  134022. ** WHERE clause terms than Y and that every WHERE clause term used by X is
  134023. ** also used by Y.
  134024. */
  134025. static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){
  134026. if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return;
  134027. for(; p; p=p->pNextLoop){
  134028. if( p->iTab!=pTemplate->iTab ) continue;
  134029. if( (p->wsFlags & WHERE_INDEXED)==0 ) continue;
  134030. if( whereLoopCheaperProperSubset(p, pTemplate) ){
  134031. /* Adjust pTemplate cost downward so that it is cheaper than its
  134032. ** subset p. */
  134033. WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
  134034. pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut-1));
  134035. pTemplate->rRun = p->rRun;
  134036. pTemplate->nOut = p->nOut - 1;
  134037. }else if( whereLoopCheaperProperSubset(pTemplate, p) ){
  134038. /* Adjust pTemplate cost upward so that it is costlier than p since
  134039. ** pTemplate is a proper subset of p */
  134040. WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
  134041. pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut+1));
  134042. pTemplate->rRun = p->rRun;
  134043. pTemplate->nOut = p->nOut + 1;
  134044. }
  134045. }
  134046. }
  134047. /*
  134048. ** Search the list of WhereLoops in *ppPrev looking for one that can be
  134049. ** replaced by pTemplate.
  134050. **
  134051. ** Return NULL if pTemplate does not belong on the WhereLoop list.
  134052. ** In other words if pTemplate ought to be dropped from further consideration.
  134053. **
  134054. ** If pX is a WhereLoop that pTemplate can replace, then return the
  134055. ** link that points to pX.
  134056. **
  134057. ** If pTemplate cannot replace any existing element of the list but needs
  134058. ** to be added to the list as a new entry, then return a pointer to the
  134059. ** tail of the list.
  134060. */
  134061. static WhereLoop **whereLoopFindLesser(
  134062. WhereLoop **ppPrev,
  134063. const WhereLoop *pTemplate
  134064. ){
  134065. WhereLoop *p;
  134066. for(p=(*ppPrev); p; ppPrev=&p->pNextLoop, p=*ppPrev){
  134067. if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
  134068. /* If either the iTab or iSortIdx values for two WhereLoop are different
  134069. ** then those WhereLoops need to be considered separately. Neither is
  134070. ** a candidate to replace the other. */
  134071. continue;
  134072. }
  134073. /* In the current implementation, the rSetup value is either zero
  134074. ** or the cost of building an automatic index (NlogN) and the NlogN
  134075. ** is the same for compatible WhereLoops. */
  134076. assert( p->rSetup==0 || pTemplate->rSetup==0
  134077. || p->rSetup==pTemplate->rSetup );
  134078. /* whereLoopAddBtree() always generates and inserts the automatic index
  134079. ** case first. Hence compatible candidate WhereLoops never have a larger
  134080. ** rSetup. Call this SETUP-INVARIANT */
  134081. assert( p->rSetup>=pTemplate->rSetup );
  134082. /* Any loop using an appliation-defined index (or PRIMARY KEY or
  134083. ** UNIQUE constraint) with one or more == constraints is better
  134084. ** than an automatic index. Unless it is a skip-scan. */
  134085. if( (p->wsFlags & WHERE_AUTO_INDEX)!=0
  134086. && (pTemplate->nSkip)==0
  134087. && (pTemplate->wsFlags & WHERE_INDEXED)!=0
  134088. && (pTemplate->wsFlags & WHERE_COLUMN_EQ)!=0
  134089. && (p->prereq & pTemplate->prereq)==pTemplate->prereq
  134090. ){
  134091. break;
  134092. }
  134093. /* If existing WhereLoop p is better than pTemplate, pTemplate can be
  134094. ** discarded. WhereLoop p is better if:
  134095. ** (1) p has no more dependencies than pTemplate, and
  134096. ** (2) p has an equal or lower cost than pTemplate
  134097. */
  134098. if( (p->prereq & pTemplate->prereq)==p->prereq /* (1) */
  134099. && p->rSetup<=pTemplate->rSetup /* (2a) */
  134100. && p->rRun<=pTemplate->rRun /* (2b) */
  134101. && p->nOut<=pTemplate->nOut /* (2c) */
  134102. ){
  134103. return 0; /* Discard pTemplate */
  134104. }
  134105. /* If pTemplate is always better than p, then cause p to be overwritten
  134106. ** with pTemplate. pTemplate is better than p if:
  134107. ** (1) pTemplate has no more dependences than p, and
  134108. ** (2) pTemplate has an equal or lower cost than p.
  134109. */
  134110. if( (p->prereq & pTemplate->prereq)==pTemplate->prereq /* (1) */
  134111. && p->rRun>=pTemplate->rRun /* (2a) */
  134112. && p->nOut>=pTemplate->nOut /* (2b) */
  134113. ){
  134114. assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
  134115. break; /* Cause p to be overwritten by pTemplate */
  134116. }
  134117. }
  134118. return ppPrev;
  134119. }
  134120. /*
  134121. ** Insert or replace a WhereLoop entry using the template supplied.
  134122. **
  134123. ** An existing WhereLoop entry might be overwritten if the new template
  134124. ** is better and has fewer dependencies. Or the template will be ignored
  134125. ** and no insert will occur if an existing WhereLoop is faster and has
  134126. ** fewer dependencies than the template. Otherwise a new WhereLoop is
  134127. ** added based on the template.
  134128. **
  134129. ** If pBuilder->pOrSet is not NULL then we care about only the
  134130. ** prerequisites and rRun and nOut costs of the N best loops. That
  134131. ** information is gathered in the pBuilder->pOrSet object. This special
  134132. ** processing mode is used only for OR clause processing.
  134133. **
  134134. ** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
  134135. ** still might overwrite similar loops with the new template if the
  134136. ** new template is better. Loops may be overwritten if the following
  134137. ** conditions are met:
  134138. **
  134139. ** (1) They have the same iTab.
  134140. ** (2) They have the same iSortIdx.
  134141. ** (3) The template has same or fewer dependencies than the current loop
  134142. ** (4) The template has the same or lower cost than the current loop
  134143. */
  134144. static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
  134145. WhereLoop **ppPrev, *p;
  134146. WhereInfo *pWInfo = pBuilder->pWInfo;
  134147. sqlite3 *db = pWInfo->pParse->db;
  134148. int rc;
  134149. /* Stop the search once we hit the query planner search limit */
  134150. if( pBuilder->iPlanLimit==0 ){
  134151. WHERETRACE(0xffffffff,("=== query planner search limit reached ===\n"));
  134152. if( pBuilder->pOrSet ) pBuilder->pOrSet->n = 0;
  134153. return SQLITE_DONE;
  134154. }
  134155. pBuilder->iPlanLimit--;
  134156. /* If pBuilder->pOrSet is defined, then only keep track of the costs
  134157. ** and prereqs.
  134158. */
  134159. if( pBuilder->pOrSet!=0 ){
  134160. if( pTemplate->nLTerm ){
  134161. #if WHERETRACE_ENABLED
  134162. u16 n = pBuilder->pOrSet->n;
  134163. int x =
  134164. #endif
  134165. whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
  134166. pTemplate->nOut);
  134167. #if WHERETRACE_ENABLED /* 0x8 */
  134168. if( sqlite3WhereTrace & 0x8 ){
  134169. sqlite3DebugPrintf(x?" or-%d: ":" or-X: ", n);
  134170. whereLoopPrint(pTemplate, pBuilder->pWC);
  134171. }
  134172. #endif
  134173. }
  134174. return SQLITE_OK;
  134175. }
  134176. /* Look for an existing WhereLoop to replace with pTemplate
  134177. */
  134178. whereLoopAdjustCost(pWInfo->pLoops, pTemplate);
  134179. ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate);
  134180. if( ppPrev==0 ){
  134181. /* There already exists a WhereLoop on the list that is better
  134182. ** than pTemplate, so just ignore pTemplate */
  134183. #if WHERETRACE_ENABLED /* 0x8 */
  134184. if( sqlite3WhereTrace & 0x8 ){
  134185. sqlite3DebugPrintf(" skip: ");
  134186. whereLoopPrint(pTemplate, pBuilder->pWC);
  134187. }
  134188. #endif
  134189. return SQLITE_OK;
  134190. }else{
  134191. p = *ppPrev;
  134192. }
  134193. /* If we reach this point it means that either p[] should be overwritten
  134194. ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
  134195. ** WhereLoop and insert it.
  134196. */
  134197. #if WHERETRACE_ENABLED /* 0x8 */
  134198. if( sqlite3WhereTrace & 0x8 ){
  134199. if( p!=0 ){
  134200. sqlite3DebugPrintf("replace: ");
  134201. whereLoopPrint(p, pBuilder->pWC);
  134202. sqlite3DebugPrintf(" with: ");
  134203. }else{
  134204. sqlite3DebugPrintf(" add: ");
  134205. }
  134206. whereLoopPrint(pTemplate, pBuilder->pWC);
  134207. }
  134208. #endif
  134209. if( p==0 ){
  134210. /* Allocate a new WhereLoop to add to the end of the list */
  134211. *ppPrev = p = sqlite3DbMallocRawNN(db, sizeof(WhereLoop));
  134212. if( p==0 ) return SQLITE_NOMEM_BKPT;
  134213. whereLoopInit(p);
  134214. p->pNextLoop = 0;
  134215. }else{
  134216. /* We will be overwriting WhereLoop p[]. But before we do, first
  134217. ** go through the rest of the list and delete any other entries besides
  134218. ** p[] that are also supplated by pTemplate */
  134219. WhereLoop **ppTail = &p->pNextLoop;
  134220. WhereLoop *pToDel;
  134221. while( *ppTail ){
  134222. ppTail = whereLoopFindLesser(ppTail, pTemplate);
  134223. if( ppTail==0 ) break;
  134224. pToDel = *ppTail;
  134225. if( pToDel==0 ) break;
  134226. *ppTail = pToDel->pNextLoop;
  134227. #if WHERETRACE_ENABLED /* 0x8 */
  134228. if( sqlite3WhereTrace & 0x8 ){
  134229. sqlite3DebugPrintf(" delete: ");
  134230. whereLoopPrint(pToDel, pBuilder->pWC);
  134231. }
  134232. #endif
  134233. whereLoopDelete(db, pToDel);
  134234. }
  134235. }
  134236. rc = whereLoopXfer(db, p, pTemplate);
  134237. if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
  134238. Index *pIndex = p->u.btree.pIndex;
  134239. if( pIndex && pIndex->idxType==SQLITE_IDXTYPE_IPK ){
  134240. p->u.btree.pIndex = 0;
  134241. }
  134242. }
  134243. return rc;
  134244. }
  134245. /*
  134246. ** Adjust the WhereLoop.nOut value downward to account for terms of the
  134247. ** WHERE clause that reference the loop but which are not used by an
  134248. ** index.
  134249. *
  134250. ** For every WHERE clause term that is not used by the index
  134251. ** and which has a truth probability assigned by one of the likelihood(),
  134252. ** likely(), or unlikely() SQL functions, reduce the estimated number
  134253. ** of output rows by the probability specified.
  134254. **
  134255. ** TUNING: For every WHERE clause term that is not used by the index
  134256. ** and which does not have an assigned truth probability, heuristics
  134257. ** described below are used to try to estimate the truth probability.
  134258. ** TODO --> Perhaps this is something that could be improved by better
  134259. ** table statistics.
  134260. **
  134261. ** Heuristic 1: Estimate the truth probability as 93.75%. The 93.75%
  134262. ** value corresponds to -1 in LogEst notation, so this means decrement
  134263. ** the WhereLoop.nOut field for every such WHERE clause term.
  134264. **
  134265. ** Heuristic 2: If there exists one or more WHERE clause terms of the
  134266. ** form "x==EXPR" and EXPR is not a constant 0 or 1, then make sure the
  134267. ** final output row estimate is no greater than 1/4 of the total number
  134268. ** of rows in the table. In other words, assume that x==EXPR will filter
  134269. ** out at least 3 out of 4 rows. If EXPR is -1 or 0 or 1, then maybe the
  134270. ** "x" column is boolean or else -1 or 0 or 1 is a common default value
  134271. ** on the "x" column and so in that case only cap the output row estimate
  134272. ** at 1/2 instead of 1/4.
  134273. */
  134274. static void whereLoopOutputAdjust(
  134275. WhereClause *pWC, /* The WHERE clause */
  134276. WhereLoop *pLoop, /* The loop to adjust downward */
  134277. LogEst nRow /* Number of rows in the entire table */
  134278. ){
  134279. WhereTerm *pTerm, *pX;
  134280. Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
  134281. int i, j, k;
  134282. LogEst iReduce = 0; /* pLoop->nOut should not exceed nRow-iReduce */
  134283. assert( (pLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
  134284. for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){
  134285. if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;
  134286. if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
  134287. if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
  134288. for(j=pLoop->nLTerm-1; j>=0; j--){
  134289. pX = pLoop->aLTerm[j];
  134290. if( pX==0 ) continue;
  134291. if( pX==pTerm ) break;
  134292. if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
  134293. }
  134294. if( j<0 ){
  134295. if( pTerm->truthProb<=0 ){
  134296. /* If a truth probability is specified using the likelihood() hints,
  134297. ** then use the probability provided by the application. */
  134298. pLoop->nOut += pTerm->truthProb;
  134299. }else{
  134300. /* In the absence of explicit truth probabilities, use heuristics to
  134301. ** guess a reasonable truth probability. */
  134302. pLoop->nOut--;
  134303. if( pTerm->eOperator&(WO_EQ|WO_IS) ){
  134304. Expr *pRight = pTerm->pExpr->pRight;
  134305. testcase( pTerm->pExpr->op==TK_IS );
  134306. if( sqlite3ExprIsInteger(pRight, &k) && k>=(-1) && k<=1 ){
  134307. k = 10;
  134308. }else{
  134309. k = 20;
  134310. }
  134311. if( iReduce<k ) iReduce = k;
  134312. }
  134313. }
  134314. }
  134315. }
  134316. if( pLoop->nOut > nRow-iReduce ) pLoop->nOut = nRow - iReduce;
  134317. }
  134318. /*
  134319. ** Term pTerm is a vector range comparison operation. The first comparison
  134320. ** in the vector can be optimized using column nEq of the index. This
  134321. ** function returns the total number of vector elements that can be used
  134322. ** as part of the range comparison.
  134323. **
  134324. ** For example, if the query is:
  134325. **
  134326. ** WHERE a = ? AND (b, c, d) > (?, ?, ?)
  134327. **
  134328. ** and the index:
  134329. **
  134330. ** CREATE INDEX ... ON (a, b, c, d, e)
  134331. **
  134332. ** then this function would be invoked with nEq=1. The value returned in
  134333. ** this case is 3.
  134334. */
  134335. static int whereRangeVectorLen(
  134336. Parse *pParse, /* Parsing context */
  134337. int iCur, /* Cursor open on pIdx */
  134338. Index *pIdx, /* The index to be used for a inequality constraint */
  134339. int nEq, /* Number of prior equality constraints on same index */
  134340. WhereTerm *pTerm /* The vector inequality constraint */
  134341. ){
  134342. int nCmp = sqlite3ExprVectorSize(pTerm->pExpr->pLeft);
  134343. int i;
  134344. nCmp = MIN(nCmp, (pIdx->nColumn - nEq));
  134345. for(i=1; i<nCmp; i++){
  134346. /* Test if comparison i of pTerm is compatible with column (i+nEq)
  134347. ** of the index. If not, exit the loop. */
  134348. char aff; /* Comparison affinity */
  134349. char idxaff = 0; /* Indexed columns affinity */
  134350. CollSeq *pColl; /* Comparison collation sequence */
  134351. Expr *pLhs = pTerm->pExpr->pLeft->x.pList->a[i].pExpr;
  134352. Expr *pRhs = pTerm->pExpr->pRight;
  134353. if( pRhs->flags & EP_xIsSelect ){
  134354. pRhs = pRhs->x.pSelect->pEList->a[i].pExpr;
  134355. }else{
  134356. pRhs = pRhs->x.pList->a[i].pExpr;
  134357. }
  134358. /* Check that the LHS of the comparison is a column reference to
  134359. ** the right column of the right source table. And that the sort
  134360. ** order of the index column is the same as the sort order of the
  134361. ** leftmost index column. */
  134362. if( pLhs->op!=TK_COLUMN
  134363. || pLhs->iTable!=iCur
  134364. || pLhs->iColumn!=pIdx->aiColumn[i+nEq]
  134365. || pIdx->aSortOrder[i+nEq]!=pIdx->aSortOrder[nEq]
  134366. ){
  134367. break;
  134368. }
  134369. testcase( pLhs->iColumn==XN_ROWID );
  134370. aff = sqlite3CompareAffinity(pRhs, sqlite3ExprAffinity(pLhs));
  134371. idxaff = sqlite3TableColumnAffinity(pIdx->pTable, pLhs->iColumn);
  134372. if( aff!=idxaff ) break;
  134373. pColl = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
  134374. if( pColl==0 ) break;
  134375. if( sqlite3StrICmp(pColl->zName, pIdx->azColl[i+nEq]) ) break;
  134376. }
  134377. return i;
  134378. }
  134379. /*
  134380. ** Adjust the cost C by the costMult facter T. This only occurs if
  134381. ** compiled with -DSQLITE_ENABLE_COSTMULT
  134382. */
  134383. #ifdef SQLITE_ENABLE_COSTMULT
  134384. # define ApplyCostMultiplier(C,T) C += T
  134385. #else
  134386. # define ApplyCostMultiplier(C,T)
  134387. #endif
  134388. /*
  134389. ** We have so far matched pBuilder->pNew->u.btree.nEq terms of the
  134390. ** index pIndex. Try to match one more.
  134391. **
  134392. ** When this function is called, pBuilder->pNew->nOut contains the
  134393. ** number of rows expected to be visited by filtering using the nEq
  134394. ** terms only. If it is modified, this value is restored before this
  134395. ** function returns.
  134396. **
  134397. ** If pProbe->idxType==SQLITE_IDXTYPE_IPK, that means pIndex is
  134398. ** a fake index used for the INTEGER PRIMARY KEY.
  134399. */
  134400. static int whereLoopAddBtreeIndex(
  134401. WhereLoopBuilder *pBuilder, /* The WhereLoop factory */
  134402. struct SrcList_item *pSrc, /* FROM clause term being analyzed */
  134403. Index *pProbe, /* An index on pSrc */
  134404. LogEst nInMul /* log(Number of iterations due to IN) */
  134405. ){
  134406. WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyse context */
  134407. Parse *pParse = pWInfo->pParse; /* Parsing context */
  134408. sqlite3 *db = pParse->db; /* Database connection malloc context */
  134409. WhereLoop *pNew; /* Template WhereLoop under construction */
  134410. WhereTerm *pTerm; /* A WhereTerm under consideration */
  134411. int opMask; /* Valid operators for constraints */
  134412. WhereScan scan; /* Iterator for WHERE terms */
  134413. Bitmask saved_prereq; /* Original value of pNew->prereq */
  134414. u16 saved_nLTerm; /* Original value of pNew->nLTerm */
  134415. u16 saved_nEq; /* Original value of pNew->u.btree.nEq */
  134416. u16 saved_nBtm; /* Original value of pNew->u.btree.nBtm */
  134417. u16 saved_nTop; /* Original value of pNew->u.btree.nTop */
  134418. u16 saved_nSkip; /* Original value of pNew->nSkip */
  134419. u32 saved_wsFlags; /* Original value of pNew->wsFlags */
  134420. LogEst saved_nOut; /* Original value of pNew->nOut */
  134421. int rc = SQLITE_OK; /* Return code */
  134422. LogEst rSize; /* Number of rows in the table */
  134423. LogEst rLogSize; /* Logarithm of table size */
  134424. WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
  134425. pNew = pBuilder->pNew;
  134426. if( db->mallocFailed ) return SQLITE_NOMEM_BKPT;
  134427. WHERETRACE(0x800, ("BEGIN %s.addBtreeIdx(%s), nEq=%d\n",
  134428. pProbe->pTable->zName,pProbe->zName, pNew->u.btree.nEq));
  134429. assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
  134430. assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
  134431. if( pNew->wsFlags & WHERE_BTM_LIMIT ){
  134432. opMask = WO_LT|WO_LE;
  134433. }else{
  134434. assert( pNew->u.btree.nBtm==0 );
  134435. opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE|WO_ISNULL|WO_IS;
  134436. }
  134437. if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
  134438. assert( pNew->u.btree.nEq<pProbe->nColumn );
  134439. saved_nEq = pNew->u.btree.nEq;
  134440. saved_nBtm = pNew->u.btree.nBtm;
  134441. saved_nTop = pNew->u.btree.nTop;
  134442. saved_nSkip = pNew->nSkip;
  134443. saved_nLTerm = pNew->nLTerm;
  134444. saved_wsFlags = pNew->wsFlags;
  134445. saved_prereq = pNew->prereq;
  134446. saved_nOut = pNew->nOut;
  134447. pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, saved_nEq,
  134448. opMask, pProbe);
  134449. pNew->rSetup = 0;
  134450. rSize = pProbe->aiRowLogEst[0];
  134451. rLogSize = estLog(rSize);
  134452. for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
  134453. u16 eOp = pTerm->eOperator; /* Shorthand for pTerm->eOperator */
  134454. LogEst rCostIdx;
  134455. LogEst nOutUnadjusted; /* nOut before IN() and WHERE adjustments */
  134456. int nIn = 0;
  134457. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  134458. int nRecValid = pBuilder->nRecValid;
  134459. #endif
  134460. if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
  134461. && indexColumnNotNull(pProbe, saved_nEq)
  134462. ){
  134463. continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
  134464. }
  134465. if( pTerm->prereqRight & pNew->maskSelf ) continue;
  134466. /* Do not allow the upper bound of a LIKE optimization range constraint
  134467. ** to mix with a lower range bound from some other source */
  134468. if( pTerm->wtFlags & TERM_LIKEOPT && pTerm->eOperator==WO_LT ) continue;
  134469. /* Do not allow constraints from the WHERE clause to be used by the
  134470. ** right table of a LEFT JOIN. Only constraints in the ON clause are
  134471. ** allowed */
  134472. if( (pSrc->fg.jointype & JT_LEFT)!=0
  134473. && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
  134474. ){
  134475. continue;
  134476. }
  134477. if( IsUniqueIndex(pProbe) && saved_nEq==pProbe->nKeyCol-1 ){
  134478. pBuilder->bldFlags |= SQLITE_BLDF_UNIQUE;
  134479. }else{
  134480. pBuilder->bldFlags |= SQLITE_BLDF_INDEXED;
  134481. }
  134482. pNew->wsFlags = saved_wsFlags;
  134483. pNew->u.btree.nEq = saved_nEq;
  134484. pNew->u.btree.nBtm = saved_nBtm;
  134485. pNew->u.btree.nTop = saved_nTop;
  134486. pNew->nLTerm = saved_nLTerm;
  134487. if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
  134488. pNew->aLTerm[pNew->nLTerm++] = pTerm;
  134489. pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
  134490. assert( nInMul==0
  134491. || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0
  134492. || (pNew->wsFlags & WHERE_COLUMN_IN)!=0
  134493. || (pNew->wsFlags & WHERE_SKIPSCAN)!=0
  134494. );
  134495. if( eOp & WO_IN ){
  134496. Expr *pExpr = pTerm->pExpr;
  134497. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  134498. /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */
  134499. int i;
  134500. nIn = 46; assert( 46==sqlite3LogEst(25) );
  134501. /* The expression may actually be of the form (x, y) IN (SELECT...).
  134502. ** In this case there is a separate term for each of (x) and (y).
  134503. ** However, the nIn multiplier should only be applied once, not once
  134504. ** for each such term. The following loop checks that pTerm is the
  134505. ** first such term in use, and sets nIn back to 0 if it is not. */
  134506. for(i=0; i<pNew->nLTerm-1; i++){
  134507. if( pNew->aLTerm[i] && pNew->aLTerm[i]->pExpr==pExpr ) nIn = 0;
  134508. }
  134509. }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
  134510. /* "x IN (value, value, ...)" */
  134511. nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
  134512. assert( nIn>0 ); /* RHS always has 2 or more terms... The parser
  134513. ** changes "x IN (?)" into "x=?". */
  134514. }
  134515. if( pProbe->hasStat1 ){
  134516. LogEst M, logK, safetyMargin;
  134517. /* Let:
  134518. ** N = the total number of rows in the table
  134519. ** K = the number of entries on the RHS of the IN operator
  134520. ** M = the number of rows in the table that match terms to the
  134521. ** to the left in the same index. If the IN operator is on
  134522. ** the left-most index column, M==N.
  134523. **
  134524. ** Given the definitions above, it is better to omit the IN operator
  134525. ** from the index lookup and instead do a scan of the M elements,
  134526. ** testing each scanned row against the IN operator separately, if:
  134527. **
  134528. ** M*log(K) < K*log(N)
  134529. **
  134530. ** Our estimates for M, K, and N might be inaccurate, so we build in
  134531. ** a safety margin of 2 (LogEst: 10) that favors using the IN operator
  134532. ** with the index, as using an index has better worst-case behavior.
  134533. ** If we do not have real sqlite_stat1 data, always prefer to use
  134534. ** the index.
  134535. */
  134536. M = pProbe->aiRowLogEst[saved_nEq];
  134537. logK = estLog(nIn);
  134538. safetyMargin = 10; /* TUNING: extra weight for indexed IN */
  134539. if( M + logK + safetyMargin < nIn + rLogSize ){
  134540. WHERETRACE(0x40,
  134541. ("Scan preferred over IN operator on column %d of \"%s\" (%d<%d)\n",
  134542. saved_nEq, pProbe->zName, M+logK+10, nIn+rLogSize));
  134543. continue;
  134544. }else{
  134545. WHERETRACE(0x40,
  134546. ("IN operator preferred on column %d of \"%s\" (%d>=%d)\n",
  134547. saved_nEq, pProbe->zName, M+logK+10, nIn+rLogSize));
  134548. }
  134549. }
  134550. pNew->wsFlags |= WHERE_COLUMN_IN;
  134551. }else if( eOp & (WO_EQ|WO_IS) ){
  134552. int iCol = pProbe->aiColumn[saved_nEq];
  134553. pNew->wsFlags |= WHERE_COLUMN_EQ;
  134554. assert( saved_nEq==pNew->u.btree.nEq );
  134555. if( iCol==XN_ROWID
  134556. || (iCol>=0 && nInMul==0 && saved_nEq==pProbe->nKeyCol-1)
  134557. ){
  134558. if( iCol==XN_ROWID || pProbe->uniqNotNull
  134559. || (pProbe->nKeyCol==1 && pProbe->onError && eOp==WO_EQ)
  134560. ){
  134561. pNew->wsFlags |= WHERE_ONEROW;
  134562. }else{
  134563. pNew->wsFlags |= WHERE_UNQ_WANTED;
  134564. }
  134565. }
  134566. }else if( eOp & WO_ISNULL ){
  134567. pNew->wsFlags |= WHERE_COLUMN_NULL;
  134568. }else if( eOp & (WO_GT|WO_GE) ){
  134569. testcase( eOp & WO_GT );
  134570. testcase( eOp & WO_GE );
  134571. pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
  134572. pNew->u.btree.nBtm = whereRangeVectorLen(
  134573. pParse, pSrc->iCursor, pProbe, saved_nEq, pTerm
  134574. );
  134575. pBtm = pTerm;
  134576. pTop = 0;
  134577. if( pTerm->wtFlags & TERM_LIKEOPT ){
  134578. /* Range contraints that come from the LIKE optimization are
  134579. ** always used in pairs. */
  134580. pTop = &pTerm[1];
  134581. assert( (pTop-(pTerm->pWC->a))<pTerm->pWC->nTerm );
  134582. assert( pTop->wtFlags & TERM_LIKEOPT );
  134583. assert( pTop->eOperator==WO_LT );
  134584. if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
  134585. pNew->aLTerm[pNew->nLTerm++] = pTop;
  134586. pNew->wsFlags |= WHERE_TOP_LIMIT;
  134587. pNew->u.btree.nTop = 1;
  134588. }
  134589. }else{
  134590. assert( eOp & (WO_LT|WO_LE) );
  134591. testcase( eOp & WO_LT );
  134592. testcase( eOp & WO_LE );
  134593. pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
  134594. pNew->u.btree.nTop = whereRangeVectorLen(
  134595. pParse, pSrc->iCursor, pProbe, saved_nEq, pTerm
  134596. );
  134597. pTop = pTerm;
  134598. pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
  134599. pNew->aLTerm[pNew->nLTerm-2] : 0;
  134600. }
  134601. /* At this point pNew->nOut is set to the number of rows expected to
  134602. ** be visited by the index scan before considering term pTerm, or the
  134603. ** values of nIn and nInMul. In other words, assuming that all
  134604. ** "x IN(...)" terms are replaced with "x = ?". This block updates
  134605. ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul). */
  134606. assert( pNew->nOut==saved_nOut );
  134607. if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
  134608. /* Adjust nOut using stat3/stat4 data. Or, if there is no stat3/stat4
  134609. ** data, using some other estimate. */
  134610. whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
  134611. }else{
  134612. int nEq = ++pNew->u.btree.nEq;
  134613. assert( eOp & (WO_ISNULL|WO_EQ|WO_IN|WO_IS) );
  134614. assert( pNew->nOut==saved_nOut );
  134615. if( pTerm->truthProb<=0 && pProbe->aiColumn[saved_nEq]>=0 ){
  134616. assert( (eOp & WO_IN) || nIn==0 );
  134617. testcase( eOp & WO_IN );
  134618. pNew->nOut += pTerm->truthProb;
  134619. pNew->nOut -= nIn;
  134620. }else{
  134621. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  134622. tRowcnt nOut = 0;
  134623. if( nInMul==0
  134624. && pProbe->nSample
  134625. && pNew->u.btree.nEq<=pProbe->nSampleCol
  134626. && ((eOp & WO_IN)==0 || !ExprHasProperty(pTerm->pExpr, EP_xIsSelect))
  134627. && OptimizationEnabled(db, SQLITE_Stat34)
  134628. ){
  134629. Expr *pExpr = pTerm->pExpr;
  134630. if( (eOp & (WO_EQ|WO_ISNULL|WO_IS))!=0 ){
  134631. testcase( eOp & WO_EQ );
  134632. testcase( eOp & WO_IS );
  134633. testcase( eOp & WO_ISNULL );
  134634. rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
  134635. }else{
  134636. rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
  134637. }
  134638. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  134639. if( rc!=SQLITE_OK ) break; /* Jump out of the pTerm loop */
  134640. if( nOut ){
  134641. pNew->nOut = sqlite3LogEst(nOut);
  134642. if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
  134643. pNew->nOut -= nIn;
  134644. }
  134645. }
  134646. if( nOut==0 )
  134647. #endif
  134648. {
  134649. pNew->nOut += (pProbe->aiRowLogEst[nEq] - pProbe->aiRowLogEst[nEq-1]);
  134650. if( eOp & WO_ISNULL ){
  134651. /* TUNING: If there is no likelihood() value, assume that a
  134652. ** "col IS NULL" expression matches twice as many rows
  134653. ** as (col=?). */
  134654. pNew->nOut += 10;
  134655. }
  134656. }
  134657. }
  134658. }
  134659. /* Set rCostIdx to the cost of visiting selected rows in index. Add
  134660. ** it to pNew->rRun, which is currently set to the cost of the index
  134661. ** seek only. Then, if this is a non-covering index, add the cost of
  134662. ** visiting the rows in the main table. */
  134663. rCostIdx = pNew->nOut + 1 + (15*pProbe->szIdxRow)/pSrc->pTab->szTabRow;
  134664. pNew->rRun = sqlite3LogEstAdd(rLogSize, rCostIdx);
  134665. if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
  134666. pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16);
  134667. }
  134668. ApplyCostMultiplier(pNew->rRun, pProbe->pTable->costMult);
  134669. nOutUnadjusted = pNew->nOut;
  134670. pNew->rRun += nInMul + nIn;
  134671. pNew->nOut += nInMul + nIn;
  134672. whereLoopOutputAdjust(pBuilder->pWC, pNew, rSize);
  134673. rc = whereLoopInsert(pBuilder, pNew);
  134674. if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
  134675. pNew->nOut = saved_nOut;
  134676. }else{
  134677. pNew->nOut = nOutUnadjusted;
  134678. }
  134679. if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
  134680. && pNew->u.btree.nEq<pProbe->nColumn
  134681. ){
  134682. whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
  134683. }
  134684. pNew->nOut = saved_nOut;
  134685. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  134686. pBuilder->nRecValid = nRecValid;
  134687. #endif
  134688. }
  134689. pNew->prereq = saved_prereq;
  134690. pNew->u.btree.nEq = saved_nEq;
  134691. pNew->u.btree.nBtm = saved_nBtm;
  134692. pNew->u.btree.nTop = saved_nTop;
  134693. pNew->nSkip = saved_nSkip;
  134694. pNew->wsFlags = saved_wsFlags;
  134695. pNew->nOut = saved_nOut;
  134696. pNew->nLTerm = saved_nLTerm;
  134697. /* Consider using a skip-scan if there are no WHERE clause constraints
  134698. ** available for the left-most terms of the index, and if the average
  134699. ** number of repeats in the left-most terms is at least 18.
  134700. **
  134701. ** The magic number 18 is selected on the basis that scanning 17 rows
  134702. ** is almost always quicker than an index seek (even though if the index
  134703. ** contains fewer than 2^17 rows we assume otherwise in other parts of
  134704. ** the code). And, even if it is not, it should not be too much slower.
  134705. ** On the other hand, the extra seeks could end up being significantly
  134706. ** more expensive. */
  134707. assert( 42==sqlite3LogEst(18) );
  134708. if( saved_nEq==saved_nSkip
  134709. && saved_nEq+1<pProbe->nKeyCol
  134710. && pProbe->noSkipScan==0
  134711. && OptimizationEnabled(db, SQLITE_SkipScan)
  134712. && pProbe->aiRowLogEst[saved_nEq+1]>=42 /* TUNING: Minimum for skip-scan */
  134713. && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK
  134714. ){
  134715. LogEst nIter;
  134716. pNew->u.btree.nEq++;
  134717. pNew->nSkip++;
  134718. pNew->aLTerm[pNew->nLTerm++] = 0;
  134719. pNew->wsFlags |= WHERE_SKIPSCAN;
  134720. nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1];
  134721. pNew->nOut -= nIter;
  134722. /* TUNING: Because uncertainties in the estimates for skip-scan queries,
  134723. ** add a 1.375 fudge factor to make skip-scan slightly less likely. */
  134724. nIter += 5;
  134725. whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul);
  134726. pNew->nOut = saved_nOut;
  134727. pNew->u.btree.nEq = saved_nEq;
  134728. pNew->nSkip = saved_nSkip;
  134729. pNew->wsFlags = saved_wsFlags;
  134730. }
  134731. WHERETRACE(0x800, ("END %s.addBtreeIdx(%s), nEq=%d, rc=%d\n",
  134732. pProbe->pTable->zName, pProbe->zName, saved_nEq, rc));
  134733. return rc;
  134734. }
  134735. /*
  134736. ** Return True if it is possible that pIndex might be useful in
  134737. ** implementing the ORDER BY clause in pBuilder.
  134738. **
  134739. ** Return False if pBuilder does not contain an ORDER BY clause or
  134740. ** if there is no way for pIndex to be useful in implementing that
  134741. ** ORDER BY clause.
  134742. */
  134743. static int indexMightHelpWithOrderBy(
  134744. WhereLoopBuilder *pBuilder,
  134745. Index *pIndex,
  134746. int iCursor
  134747. ){
  134748. ExprList *pOB;
  134749. ExprList *aColExpr;
  134750. int ii, jj;
  134751. if( pIndex->bUnordered ) return 0;
  134752. if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
  134753. for(ii=0; ii<pOB->nExpr; ii++){
  134754. Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
  134755. if( pExpr->op==TK_COLUMN && pExpr->iTable==iCursor ){
  134756. if( pExpr->iColumn<0 ) return 1;
  134757. for(jj=0; jj<pIndex->nKeyCol; jj++){
  134758. if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
  134759. }
  134760. }else if( (aColExpr = pIndex->aColExpr)!=0 ){
  134761. for(jj=0; jj<pIndex->nKeyCol; jj++){
  134762. if( pIndex->aiColumn[jj]!=XN_EXPR ) continue;
  134763. if( sqlite3ExprCompareSkip(pExpr,aColExpr->a[jj].pExpr,iCursor)==0 ){
  134764. return 1;
  134765. }
  134766. }
  134767. }
  134768. }
  134769. return 0;
  134770. }
  134771. /* Check to see if a partial index with pPartIndexWhere can be used
  134772. ** in the current query. Return true if it can be and false if not.
  134773. */
  134774. static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
  134775. int i;
  134776. WhereTerm *pTerm;
  134777. Parse *pParse = pWC->pWInfo->pParse;
  134778. while( pWhere->op==TK_AND ){
  134779. if( !whereUsablePartialIndex(iTab,pWC,pWhere->pLeft) ) return 0;
  134780. pWhere = pWhere->pRight;
  134781. }
  134782. if( pParse->db->flags & SQLITE_EnableQPSG ) pParse = 0;
  134783. for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  134784. Expr *pExpr = pTerm->pExpr;
  134785. if( (!ExprHasProperty(pExpr, EP_FromJoin) || pExpr->iRightJoinTable==iTab)
  134786. && sqlite3ExprImpliesExpr(pParse, pExpr, pWhere, iTab)
  134787. ){
  134788. return 1;
  134789. }
  134790. }
  134791. return 0;
  134792. }
  134793. /*
  134794. ** Add all WhereLoop objects for a single table of the join where the table
  134795. ** is identified by pBuilder->pNew->iTab. That table is guaranteed to be
  134796. ** a b-tree table, not a virtual table.
  134797. **
  134798. ** The costs (WhereLoop.rRun) of the b-tree loops added by this function
  134799. ** are calculated as follows:
  134800. **
  134801. ** For a full scan, assuming the table (or index) contains nRow rows:
  134802. **
  134803. ** cost = nRow * 3.0 // full-table scan
  134804. ** cost = nRow * K // scan of covering index
  134805. ** cost = nRow * (K+3.0) // scan of non-covering index
  134806. **
  134807. ** where K is a value between 1.1 and 3.0 set based on the relative
  134808. ** estimated average size of the index and table records.
  134809. **
  134810. ** For an index scan, where nVisit is the number of index rows visited
  134811. ** by the scan, and nSeek is the number of seek operations required on
  134812. ** the index b-tree:
  134813. **
  134814. ** cost = nSeek * (log(nRow) + K * nVisit) // covering index
  134815. ** cost = nSeek * (log(nRow) + (K+3.0) * nVisit) // non-covering index
  134816. **
  134817. ** Normally, nSeek is 1. nSeek values greater than 1 come about if the
  134818. ** WHERE clause includes "x IN (....)" terms used in place of "x=?". Or when
  134819. ** implicit "x IN (SELECT x FROM tbl)" terms are added for skip-scans.
  134820. **
  134821. ** The estimated values (nRow, nVisit, nSeek) often contain a large amount
  134822. ** of uncertainty. For this reason, scoring is designed to pick plans that
  134823. ** "do the least harm" if the estimates are inaccurate. For example, a
  134824. ** log(nRow) factor is omitted from a non-covering index scan in order to
  134825. ** bias the scoring in favor of using an index, since the worst-case
  134826. ** performance of using an index is far better than the worst-case performance
  134827. ** of a full table scan.
  134828. */
  134829. static int whereLoopAddBtree(
  134830. WhereLoopBuilder *pBuilder, /* WHERE clause information */
  134831. Bitmask mPrereq /* Extra prerequesites for using this table */
  134832. ){
  134833. WhereInfo *pWInfo; /* WHERE analysis context */
  134834. Index *pProbe; /* An index we are evaluating */
  134835. Index sPk; /* A fake index object for the primary key */
  134836. LogEst aiRowEstPk[2]; /* The aiRowLogEst[] value for the sPk index */
  134837. i16 aiColumnPk = -1; /* The aColumn[] value for the sPk index */
  134838. SrcList *pTabList; /* The FROM clause */
  134839. struct SrcList_item *pSrc; /* The FROM clause btree term to add */
  134840. WhereLoop *pNew; /* Template WhereLoop object */
  134841. int rc = SQLITE_OK; /* Return code */
  134842. int iSortIdx = 1; /* Index number */
  134843. int b; /* A boolean value */
  134844. LogEst rSize; /* number of rows in the table */
  134845. LogEst rLogSize; /* Logarithm of the number of rows in the table */
  134846. WhereClause *pWC; /* The parsed WHERE clause */
  134847. Table *pTab; /* Table being queried */
  134848. pNew = pBuilder->pNew;
  134849. pWInfo = pBuilder->pWInfo;
  134850. pTabList = pWInfo->pTabList;
  134851. pSrc = pTabList->a + pNew->iTab;
  134852. pTab = pSrc->pTab;
  134853. pWC = pBuilder->pWC;
  134854. assert( !IsVirtual(pSrc->pTab) );
  134855. if( pSrc->pIBIndex ){
  134856. /* An INDEXED BY clause specifies a particular index to use */
  134857. pProbe = pSrc->pIBIndex;
  134858. }else if( !HasRowid(pTab) ){
  134859. pProbe = pTab->pIndex;
  134860. }else{
  134861. /* There is no INDEXED BY clause. Create a fake Index object in local
  134862. ** variable sPk to represent the rowid primary key index. Make this
  134863. ** fake index the first in a chain of Index objects with all of the real
  134864. ** indices to follow */
  134865. Index *pFirst; /* First of real indices on the table */
  134866. memset(&sPk, 0, sizeof(Index));
  134867. sPk.nKeyCol = 1;
  134868. sPk.nColumn = 1;
  134869. sPk.aiColumn = &aiColumnPk;
  134870. sPk.aiRowLogEst = aiRowEstPk;
  134871. sPk.onError = OE_Replace;
  134872. sPk.pTable = pTab;
  134873. sPk.szIdxRow = pTab->szTabRow;
  134874. sPk.idxType = SQLITE_IDXTYPE_IPK;
  134875. aiRowEstPk[0] = pTab->nRowLogEst;
  134876. aiRowEstPk[1] = 0;
  134877. pFirst = pSrc->pTab->pIndex;
  134878. if( pSrc->fg.notIndexed==0 ){
  134879. /* The real indices of the table are only considered if the
  134880. ** NOT INDEXED qualifier is omitted from the FROM clause */
  134881. sPk.pNext = pFirst;
  134882. }
  134883. pProbe = &sPk;
  134884. }
  134885. rSize = pTab->nRowLogEst;
  134886. rLogSize = estLog(rSize);
  134887. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  134888. /* Automatic indexes */
  134889. if( !pBuilder->pOrSet /* Not part of an OR optimization */
  134890. && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0
  134891. && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
  134892. && pSrc->pIBIndex==0 /* Has no INDEXED BY clause */
  134893. && !pSrc->fg.notIndexed /* Has no NOT INDEXED clause */
  134894. && HasRowid(pTab) /* Not WITHOUT ROWID table. (FIXME: Why not?) */
  134895. && !pSrc->fg.isCorrelated /* Not a correlated subquery */
  134896. && !pSrc->fg.isRecursive /* Not a recursive common table expression. */
  134897. ){
  134898. /* Generate auto-index WhereLoops */
  134899. WhereTerm *pTerm;
  134900. WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
  134901. for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
  134902. if( pTerm->prereqRight & pNew->maskSelf ) continue;
  134903. if( termCanDriveIndex(pTerm, pSrc, 0) ){
  134904. pNew->u.btree.nEq = 1;
  134905. pNew->nSkip = 0;
  134906. pNew->u.btree.pIndex = 0;
  134907. pNew->nLTerm = 1;
  134908. pNew->aLTerm[0] = pTerm;
  134909. /* TUNING: One-time cost for computing the automatic index is
  134910. ** estimated to be X*N*log2(N) where N is the number of rows in
  134911. ** the table being indexed and where X is 7 (LogEst=28) for normal
  134912. ** tables or 0.5 (LogEst=-10) for views and subqueries. The value
  134913. ** of X is smaller for views and subqueries so that the query planner
  134914. ** will be more aggressive about generating automatic indexes for
  134915. ** those objects, since there is no opportunity to add schema
  134916. ** indexes on subqueries and views. */
  134917. pNew->rSetup = rLogSize + rSize;
  134918. if( pTab->pSelect==0 && (pTab->tabFlags & TF_Ephemeral)==0 ){
  134919. pNew->rSetup += 28;
  134920. }else{
  134921. pNew->rSetup -= 10;
  134922. }
  134923. ApplyCostMultiplier(pNew->rSetup, pTab->costMult);
  134924. if( pNew->rSetup<0 ) pNew->rSetup = 0;
  134925. /* TUNING: Each index lookup yields 20 rows in the table. This
  134926. ** is more than the usual guess of 10 rows, since we have no way
  134927. ** of knowing how selective the index will ultimately be. It would
  134928. ** not be unreasonable to make this value much larger. */
  134929. pNew->nOut = 43; assert( 43==sqlite3LogEst(20) );
  134930. pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
  134931. pNew->wsFlags = WHERE_AUTO_INDEX;
  134932. pNew->prereq = mPrereq | pTerm->prereqRight;
  134933. rc = whereLoopInsert(pBuilder, pNew);
  134934. }
  134935. }
  134936. }
  134937. #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
  134938. /* Loop over all indices. If there was an INDEXED BY clause, then only
  134939. ** consider index pProbe. */
  134940. for(; rc==SQLITE_OK && pProbe;
  134941. pProbe=(pSrc->pIBIndex ? 0 : pProbe->pNext), iSortIdx++
  134942. ){
  134943. if( pProbe->pPartIdxWhere!=0
  134944. && !whereUsablePartialIndex(pSrc->iCursor, pWC, pProbe->pPartIdxWhere) ){
  134945. testcase( pNew->iTab!=pSrc->iCursor ); /* See ticket [98d973b8f5] */
  134946. continue; /* Partial index inappropriate for this query */
  134947. }
  134948. if( pProbe->bNoQuery ) continue;
  134949. rSize = pProbe->aiRowLogEst[0];
  134950. pNew->u.btree.nEq = 0;
  134951. pNew->u.btree.nBtm = 0;
  134952. pNew->u.btree.nTop = 0;
  134953. pNew->nSkip = 0;
  134954. pNew->nLTerm = 0;
  134955. pNew->iSortIdx = 0;
  134956. pNew->rSetup = 0;
  134957. pNew->prereq = mPrereq;
  134958. pNew->nOut = rSize;
  134959. pNew->u.btree.pIndex = pProbe;
  134960. b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
  134961. /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
  134962. assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
  134963. if( pProbe->idxType==SQLITE_IDXTYPE_IPK ){
  134964. /* Integer primary key index */
  134965. pNew->wsFlags = WHERE_IPK;
  134966. /* Full table scan */
  134967. pNew->iSortIdx = b ? iSortIdx : 0;
  134968. /* TUNING: Cost of full table scan is (N*3.0). */
  134969. pNew->rRun = rSize + 16;
  134970. ApplyCostMultiplier(pNew->rRun, pTab->costMult);
  134971. whereLoopOutputAdjust(pWC, pNew, rSize);
  134972. rc = whereLoopInsert(pBuilder, pNew);
  134973. pNew->nOut = rSize;
  134974. if( rc ) break;
  134975. }else{
  134976. Bitmask m;
  134977. if( pProbe->isCovering ){
  134978. pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
  134979. m = 0;
  134980. }else{
  134981. m = pSrc->colUsed & pProbe->colNotIdxed;
  134982. pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
  134983. }
  134984. /* Full scan via index */
  134985. if( b
  134986. || !HasRowid(pTab)
  134987. || pProbe->pPartIdxWhere!=0
  134988. || ( m==0
  134989. && pProbe->bUnordered==0
  134990. && (pProbe->szIdxRow<pTab->szTabRow)
  134991. && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
  134992. && sqlite3GlobalConfig.bUseCis
  134993. && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
  134994. )
  134995. ){
  134996. pNew->iSortIdx = b ? iSortIdx : 0;
  134997. /* The cost of visiting the index rows is N*K, where K is
  134998. ** between 1.1 and 3.0, depending on the relative sizes of the
  134999. ** index and table rows. */
  135000. pNew->rRun = rSize + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow;
  135001. if( m!=0 ){
  135002. /* If this is a non-covering index scan, add in the cost of
  135003. ** doing table lookups. The cost will be 3x the number of
  135004. ** lookups. Take into account WHERE clause terms that can be
  135005. ** satisfied using just the index, and that do not require a
  135006. ** table lookup. */
  135007. LogEst nLookup = rSize + 16; /* Base cost: N*3 */
  135008. int ii;
  135009. int iCur = pSrc->iCursor;
  135010. WhereClause *pWC2 = &pWInfo->sWC;
  135011. for(ii=0; ii<pWC2->nTerm; ii++){
  135012. WhereTerm *pTerm = &pWC2->a[ii];
  135013. if( !sqlite3ExprCoveredByIndex(pTerm->pExpr, iCur, pProbe) ){
  135014. break;
  135015. }
  135016. /* pTerm can be evaluated using just the index. So reduce
  135017. ** the expected number of table lookups accordingly */
  135018. if( pTerm->truthProb<=0 ){
  135019. nLookup += pTerm->truthProb;
  135020. }else{
  135021. nLookup--;
  135022. if( pTerm->eOperator & (WO_EQ|WO_IS) ) nLookup -= 19;
  135023. }
  135024. }
  135025. pNew->rRun = sqlite3LogEstAdd(pNew->rRun, nLookup);
  135026. }
  135027. ApplyCostMultiplier(pNew->rRun, pTab->costMult);
  135028. whereLoopOutputAdjust(pWC, pNew, rSize);
  135029. rc = whereLoopInsert(pBuilder, pNew);
  135030. pNew->nOut = rSize;
  135031. if( rc ) break;
  135032. }
  135033. }
  135034. pBuilder->bldFlags = 0;
  135035. rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
  135036. if( pBuilder->bldFlags==SQLITE_BLDF_INDEXED ){
  135037. /* If a non-unique index is used, or if a prefix of the key for
  135038. ** unique index is used (making the index functionally non-unique)
  135039. ** then the sqlite_stat1 data becomes important for scoring the
  135040. ** plan */
  135041. pTab->tabFlags |= TF_StatsUsed;
  135042. }
  135043. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  135044. sqlite3Stat4ProbeFree(pBuilder->pRec);
  135045. pBuilder->nRecValid = 0;
  135046. pBuilder->pRec = 0;
  135047. #endif
  135048. }
  135049. return rc;
  135050. }
  135051. #ifndef SQLITE_OMIT_VIRTUALTABLE
  135052. /*
  135053. ** Argument pIdxInfo is already populated with all constraints that may
  135054. ** be used by the virtual table identified by pBuilder->pNew->iTab. This
  135055. ** function marks a subset of those constraints usable, invokes the
  135056. ** xBestIndex method and adds the returned plan to pBuilder.
  135057. **
  135058. ** A constraint is marked usable if:
  135059. **
  135060. ** * Argument mUsable indicates that its prerequisites are available, and
  135061. **
  135062. ** * It is not one of the operators specified in the mExclude mask passed
  135063. ** as the fourth argument (which in practice is either WO_IN or 0).
  135064. **
  135065. ** Argument mPrereq is a mask of tables that must be scanned before the
  135066. ** virtual table in question. These are added to the plans prerequisites
  135067. ** before it is added to pBuilder.
  135068. **
  135069. ** Output parameter *pbIn is set to true if the plan added to pBuilder
  135070. ** uses one or more WO_IN terms, or false otherwise.
  135071. */
  135072. static int whereLoopAddVirtualOne(
  135073. WhereLoopBuilder *pBuilder,
  135074. Bitmask mPrereq, /* Mask of tables that must be used. */
  135075. Bitmask mUsable, /* Mask of usable tables */
  135076. u16 mExclude, /* Exclude terms using these operators */
  135077. sqlite3_index_info *pIdxInfo, /* Populated object for xBestIndex */
  135078. u16 mNoOmit, /* Do not omit these constraints */
  135079. int *pbIn /* OUT: True if plan uses an IN(...) op */
  135080. ){
  135081. WhereClause *pWC = pBuilder->pWC;
  135082. struct sqlite3_index_constraint *pIdxCons;
  135083. struct sqlite3_index_constraint_usage *pUsage = pIdxInfo->aConstraintUsage;
  135084. int i;
  135085. int mxTerm;
  135086. int rc = SQLITE_OK;
  135087. WhereLoop *pNew = pBuilder->pNew;
  135088. Parse *pParse = pBuilder->pWInfo->pParse;
  135089. struct SrcList_item *pSrc = &pBuilder->pWInfo->pTabList->a[pNew->iTab];
  135090. int nConstraint = pIdxInfo->nConstraint;
  135091. assert( (mUsable & mPrereq)==mPrereq );
  135092. *pbIn = 0;
  135093. pNew->prereq = mPrereq;
  135094. /* Set the usable flag on the subset of constraints identified by
  135095. ** arguments mUsable and mExclude. */
  135096. pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
  135097. for(i=0; i<nConstraint; i++, pIdxCons++){
  135098. WhereTerm *pTerm = &pWC->a[pIdxCons->iTermOffset];
  135099. pIdxCons->usable = 0;
  135100. if( (pTerm->prereqRight & mUsable)==pTerm->prereqRight
  135101. && (pTerm->eOperator & mExclude)==0
  135102. ){
  135103. pIdxCons->usable = 1;
  135104. }
  135105. }
  135106. /* Initialize the output fields of the sqlite3_index_info structure */
  135107. memset(pUsage, 0, sizeof(pUsage[0])*nConstraint);
  135108. assert( pIdxInfo->needToFreeIdxStr==0 );
  135109. pIdxInfo->idxStr = 0;
  135110. pIdxInfo->idxNum = 0;
  135111. pIdxInfo->orderByConsumed = 0;
  135112. pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
  135113. pIdxInfo->estimatedRows = 25;
  135114. pIdxInfo->idxFlags = 0;
  135115. pIdxInfo->colUsed = (sqlite3_int64)pSrc->colUsed;
  135116. /* Invoke the virtual table xBestIndex() method */
  135117. rc = vtabBestIndex(pParse, pSrc->pTab, pIdxInfo);
  135118. if( rc ){
  135119. if( rc==SQLITE_CONSTRAINT ){
  135120. /* If the xBestIndex method returns SQLITE_CONSTRAINT, that means
  135121. ** that the particular combination of parameters provided is unusable.
  135122. ** Make no entries in the loop table.
  135123. */
  135124. WHERETRACE(0xffff, (" ^^^^--- non-viable plan rejected!\n"));
  135125. return SQLITE_OK;
  135126. }
  135127. return rc;
  135128. }
  135129. mxTerm = -1;
  135130. assert( pNew->nLSlot>=nConstraint );
  135131. for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
  135132. pNew->u.vtab.omitMask = 0;
  135133. pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
  135134. for(i=0; i<nConstraint; i++, pIdxCons++){
  135135. int iTerm;
  135136. if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
  135137. WhereTerm *pTerm;
  135138. int j = pIdxCons->iTermOffset;
  135139. if( iTerm>=nConstraint
  135140. || j<0
  135141. || j>=pWC->nTerm
  135142. || pNew->aLTerm[iTerm]!=0
  135143. || pIdxCons->usable==0
  135144. ){
  135145. sqlite3ErrorMsg(pParse,"%s.xBestIndex malfunction",pSrc->pTab->zName);
  135146. testcase( pIdxInfo->needToFreeIdxStr );
  135147. return SQLITE_ERROR;
  135148. }
  135149. testcase( iTerm==nConstraint-1 );
  135150. testcase( j==0 );
  135151. testcase( j==pWC->nTerm-1 );
  135152. pTerm = &pWC->a[j];
  135153. pNew->prereq |= pTerm->prereqRight;
  135154. assert( iTerm<pNew->nLSlot );
  135155. pNew->aLTerm[iTerm] = pTerm;
  135156. if( iTerm>mxTerm ) mxTerm = iTerm;
  135157. testcase( iTerm==15 );
  135158. testcase( iTerm==16 );
  135159. if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
  135160. if( (pTerm->eOperator & WO_IN)!=0 ){
  135161. /* A virtual table that is constrained by an IN clause may not
  135162. ** consume the ORDER BY clause because (1) the order of IN terms
  135163. ** is not necessarily related to the order of output terms and
  135164. ** (2) Multiple outputs from a single IN value will not merge
  135165. ** together. */
  135166. pIdxInfo->orderByConsumed = 0;
  135167. pIdxInfo->idxFlags &= ~SQLITE_INDEX_SCAN_UNIQUE;
  135168. *pbIn = 1; assert( (mExclude & WO_IN)==0 );
  135169. }
  135170. }
  135171. }
  135172. pNew->u.vtab.omitMask &= ~mNoOmit;
  135173. pNew->nLTerm = mxTerm+1;
  135174. for(i=0; i<=mxTerm; i++){
  135175. if( pNew->aLTerm[i]==0 ){
  135176. /* The non-zero argvIdx values must be contiguous. Raise an
  135177. ** error if they are not */
  135178. sqlite3ErrorMsg(pParse,"%s.xBestIndex malfunction",pSrc->pTab->zName);
  135179. testcase( pIdxInfo->needToFreeIdxStr );
  135180. return SQLITE_ERROR;
  135181. }
  135182. }
  135183. assert( pNew->nLTerm<=pNew->nLSlot );
  135184. pNew->u.vtab.idxNum = pIdxInfo->idxNum;
  135185. pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
  135186. pIdxInfo->needToFreeIdxStr = 0;
  135187. pNew->u.vtab.idxStr = pIdxInfo->idxStr;
  135188. pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ?
  135189. pIdxInfo->nOrderBy : 0);
  135190. pNew->rSetup = 0;
  135191. pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
  135192. pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows);
  135193. /* Set the WHERE_ONEROW flag if the xBestIndex() method indicated
  135194. ** that the scan will visit at most one row. Clear it otherwise. */
  135195. if( pIdxInfo->idxFlags & SQLITE_INDEX_SCAN_UNIQUE ){
  135196. pNew->wsFlags |= WHERE_ONEROW;
  135197. }else{
  135198. pNew->wsFlags &= ~WHERE_ONEROW;
  135199. }
  135200. rc = whereLoopInsert(pBuilder, pNew);
  135201. if( pNew->u.vtab.needFree ){
  135202. sqlite3_free(pNew->u.vtab.idxStr);
  135203. pNew->u.vtab.needFree = 0;
  135204. }
  135205. WHERETRACE(0xffff, (" bIn=%d prereqIn=%04llx prereqOut=%04llx\n",
  135206. *pbIn, (sqlite3_uint64)mPrereq,
  135207. (sqlite3_uint64)(pNew->prereq & ~mPrereq)));
  135208. return rc;
  135209. }
  135210. /*
  135211. ** If this function is invoked from within an xBestIndex() callback, it
  135212. ** returns a pointer to a buffer containing the name of the collation
  135213. ** sequence associated with element iCons of the sqlite3_index_info.aConstraint
  135214. ** array. Or, if iCons is out of range or there is no active xBestIndex
  135215. ** call, return NULL.
  135216. */
  135217. SQLITE_API const char *sqlite3_vtab_collation(sqlite3_index_info *pIdxInfo, int iCons){
  135218. HiddenIndexInfo *pHidden = (HiddenIndexInfo*)&pIdxInfo[1];
  135219. const char *zRet = 0;
  135220. if( iCons>=0 && iCons<pIdxInfo->nConstraint ){
  135221. CollSeq *pC = 0;
  135222. int iTerm = pIdxInfo->aConstraint[iCons].iTermOffset;
  135223. Expr *pX = pHidden->pWC->a[iTerm].pExpr;
  135224. if( pX->pLeft ){
  135225. pC = sqlite3BinaryCompareCollSeq(pHidden->pParse, pX->pLeft, pX->pRight);
  135226. }
  135227. zRet = (pC ? pC->zName : sqlite3StrBINARY);
  135228. }
  135229. return zRet;
  135230. }
  135231. /*
  135232. ** Add all WhereLoop objects for a table of the join identified by
  135233. ** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table.
  135234. **
  135235. ** If there are no LEFT or CROSS JOIN joins in the query, both mPrereq and
  135236. ** mUnusable are set to 0. Otherwise, mPrereq is a mask of all FROM clause
  135237. ** entries that occur before the virtual table in the FROM clause and are
  135238. ** separated from it by at least one LEFT or CROSS JOIN. Similarly, the
  135239. ** mUnusable mask contains all FROM clause entries that occur after the
  135240. ** virtual table and are separated from it by at least one LEFT or
  135241. ** CROSS JOIN.
  135242. **
  135243. ** For example, if the query were:
  135244. **
  135245. ** ... FROM t1, t2 LEFT JOIN t3, t4, vt CROSS JOIN t5, t6;
  135246. **
  135247. ** then mPrereq corresponds to (t1, t2) and mUnusable to (t5, t6).
  135248. **
  135249. ** All the tables in mPrereq must be scanned before the current virtual
  135250. ** table. So any terms for which all prerequisites are satisfied by
  135251. ** mPrereq may be specified as "usable" in all calls to xBestIndex.
  135252. ** Conversely, all tables in mUnusable must be scanned after the current
  135253. ** virtual table, so any terms for which the prerequisites overlap with
  135254. ** mUnusable should always be configured as "not-usable" for xBestIndex.
  135255. */
  135256. static int whereLoopAddVirtual(
  135257. WhereLoopBuilder *pBuilder, /* WHERE clause information */
  135258. Bitmask mPrereq, /* Tables that must be scanned before this one */
  135259. Bitmask mUnusable /* Tables that must be scanned after this one */
  135260. ){
  135261. int rc = SQLITE_OK; /* Return code */
  135262. WhereInfo *pWInfo; /* WHERE analysis context */
  135263. Parse *pParse; /* The parsing context */
  135264. WhereClause *pWC; /* The WHERE clause */
  135265. struct SrcList_item *pSrc; /* The FROM clause term to search */
  135266. sqlite3_index_info *p; /* Object to pass to xBestIndex() */
  135267. int nConstraint; /* Number of constraints in p */
  135268. int bIn; /* True if plan uses IN(...) operator */
  135269. WhereLoop *pNew;
  135270. Bitmask mBest; /* Tables used by best possible plan */
  135271. u16 mNoOmit;
  135272. assert( (mPrereq & mUnusable)==0 );
  135273. pWInfo = pBuilder->pWInfo;
  135274. pParse = pWInfo->pParse;
  135275. pWC = pBuilder->pWC;
  135276. pNew = pBuilder->pNew;
  135277. pSrc = &pWInfo->pTabList->a[pNew->iTab];
  135278. assert( IsVirtual(pSrc->pTab) );
  135279. p = allocateIndexInfo(pParse, pWC, mUnusable, pSrc, pBuilder->pOrderBy,
  135280. &mNoOmit);
  135281. if( p==0 ) return SQLITE_NOMEM_BKPT;
  135282. pNew->rSetup = 0;
  135283. pNew->wsFlags = WHERE_VIRTUALTABLE;
  135284. pNew->nLTerm = 0;
  135285. pNew->u.vtab.needFree = 0;
  135286. nConstraint = p->nConstraint;
  135287. if( whereLoopResize(pParse->db, pNew, nConstraint) ){
  135288. sqlite3DbFree(pParse->db, p);
  135289. return SQLITE_NOMEM_BKPT;
  135290. }
  135291. /* First call xBestIndex() with all constraints usable. */
  135292. WHERETRACE(0x800, ("BEGIN %s.addVirtual()\n", pSrc->pTab->zName));
  135293. WHERETRACE(0x40, (" VirtualOne: all usable\n"));
  135294. rc = whereLoopAddVirtualOne(pBuilder, mPrereq, ALLBITS, 0, p, mNoOmit, &bIn);
  135295. /* If the call to xBestIndex() with all terms enabled produced a plan
  135296. ** that does not require any source tables (IOW: a plan with mBest==0)
  135297. ** and does not use an IN(...) operator, then there is no point in making
  135298. ** any further calls to xBestIndex() since they will all return the same
  135299. ** result (if the xBestIndex() implementation is sane). */
  135300. if( rc==SQLITE_OK && ((mBest = (pNew->prereq & ~mPrereq))!=0 || bIn) ){
  135301. int seenZero = 0; /* True if a plan with no prereqs seen */
  135302. int seenZeroNoIN = 0; /* Plan with no prereqs and no IN(...) seen */
  135303. Bitmask mPrev = 0;
  135304. Bitmask mBestNoIn = 0;
  135305. /* If the plan produced by the earlier call uses an IN(...) term, call
  135306. ** xBestIndex again, this time with IN(...) terms disabled. */
  135307. if( bIn ){
  135308. WHERETRACE(0x40, (" VirtualOne: all usable w/o IN\n"));
  135309. rc = whereLoopAddVirtualOne(
  135310. pBuilder, mPrereq, ALLBITS, WO_IN, p, mNoOmit, &bIn);
  135311. assert( bIn==0 );
  135312. mBestNoIn = pNew->prereq & ~mPrereq;
  135313. if( mBestNoIn==0 ){
  135314. seenZero = 1;
  135315. seenZeroNoIN = 1;
  135316. }
  135317. }
  135318. /* Call xBestIndex once for each distinct value of (prereqRight & ~mPrereq)
  135319. ** in the set of terms that apply to the current virtual table. */
  135320. while( rc==SQLITE_OK ){
  135321. int i;
  135322. Bitmask mNext = ALLBITS;
  135323. assert( mNext>0 );
  135324. for(i=0; i<nConstraint; i++){
  135325. Bitmask mThis = (
  135326. pWC->a[p->aConstraint[i].iTermOffset].prereqRight & ~mPrereq
  135327. );
  135328. if( mThis>mPrev && mThis<mNext ) mNext = mThis;
  135329. }
  135330. mPrev = mNext;
  135331. if( mNext==ALLBITS ) break;
  135332. if( mNext==mBest || mNext==mBestNoIn ) continue;
  135333. WHERETRACE(0x40, (" VirtualOne: mPrev=%04llx mNext=%04llx\n",
  135334. (sqlite3_uint64)mPrev, (sqlite3_uint64)mNext));
  135335. rc = whereLoopAddVirtualOne(
  135336. pBuilder, mPrereq, mNext|mPrereq, 0, p, mNoOmit, &bIn);
  135337. if( pNew->prereq==mPrereq ){
  135338. seenZero = 1;
  135339. if( bIn==0 ) seenZeroNoIN = 1;
  135340. }
  135341. }
  135342. /* If the calls to xBestIndex() in the above loop did not find a plan
  135343. ** that requires no source tables at all (i.e. one guaranteed to be
  135344. ** usable), make a call here with all source tables disabled */
  135345. if( rc==SQLITE_OK && seenZero==0 ){
  135346. WHERETRACE(0x40, (" VirtualOne: all disabled\n"));
  135347. rc = whereLoopAddVirtualOne(
  135348. pBuilder, mPrereq, mPrereq, 0, p, mNoOmit, &bIn);
  135349. if( bIn==0 ) seenZeroNoIN = 1;
  135350. }
  135351. /* If the calls to xBestIndex() have so far failed to find a plan
  135352. ** that requires no source tables at all and does not use an IN(...)
  135353. ** operator, make a final call to obtain one here. */
  135354. if( rc==SQLITE_OK && seenZeroNoIN==0 ){
  135355. WHERETRACE(0x40, (" VirtualOne: all disabled and w/o IN\n"));
  135356. rc = whereLoopAddVirtualOne(
  135357. pBuilder, mPrereq, mPrereq, WO_IN, p, mNoOmit, &bIn);
  135358. }
  135359. }
  135360. if( p->needToFreeIdxStr ) sqlite3_free(p->idxStr);
  135361. sqlite3DbFreeNN(pParse->db, p);
  135362. WHERETRACE(0x800, ("END %s.addVirtual(), rc=%d\n", pSrc->pTab->zName, rc));
  135363. return rc;
  135364. }
  135365. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  135366. /*
  135367. ** Add WhereLoop entries to handle OR terms. This works for either
  135368. ** btrees or virtual tables.
  135369. */
  135370. static int whereLoopAddOr(
  135371. WhereLoopBuilder *pBuilder,
  135372. Bitmask mPrereq,
  135373. Bitmask mUnusable
  135374. ){
  135375. WhereInfo *pWInfo = pBuilder->pWInfo;
  135376. WhereClause *pWC;
  135377. WhereLoop *pNew;
  135378. WhereTerm *pTerm, *pWCEnd;
  135379. int rc = SQLITE_OK;
  135380. int iCur;
  135381. WhereClause tempWC;
  135382. WhereLoopBuilder sSubBuild;
  135383. WhereOrSet sSum, sCur;
  135384. struct SrcList_item *pItem;
  135385. pWC = pBuilder->pWC;
  135386. pWCEnd = pWC->a + pWC->nTerm;
  135387. pNew = pBuilder->pNew;
  135388. memset(&sSum, 0, sizeof(sSum));
  135389. pItem = pWInfo->pTabList->a + pNew->iTab;
  135390. iCur = pItem->iCursor;
  135391. for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
  135392. if( (pTerm->eOperator & WO_OR)!=0
  135393. && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
  135394. ){
  135395. WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
  135396. WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
  135397. WhereTerm *pOrTerm;
  135398. int once = 1;
  135399. int i, j;
  135400. sSubBuild = *pBuilder;
  135401. sSubBuild.pOrderBy = 0;
  135402. sSubBuild.pOrSet = &sCur;
  135403. WHERETRACE(0x200, ("Begin processing OR-clause %p\n", pTerm));
  135404. for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
  135405. if( (pOrTerm->eOperator & WO_AND)!=0 ){
  135406. sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
  135407. }else if( pOrTerm->leftCursor==iCur ){
  135408. tempWC.pWInfo = pWC->pWInfo;
  135409. tempWC.pOuter = pWC;
  135410. tempWC.op = TK_AND;
  135411. tempWC.nTerm = 1;
  135412. tempWC.a = pOrTerm;
  135413. sSubBuild.pWC = &tempWC;
  135414. }else{
  135415. continue;
  135416. }
  135417. sCur.n = 0;
  135418. #ifdef WHERETRACE_ENABLED
  135419. WHERETRACE(0x200, ("OR-term %d of %p has %d subterms:\n",
  135420. (int)(pOrTerm-pOrWC->a), pTerm, sSubBuild.pWC->nTerm));
  135421. if( sqlite3WhereTrace & 0x400 ){
  135422. sqlite3WhereClausePrint(sSubBuild.pWC);
  135423. }
  135424. #endif
  135425. #ifndef SQLITE_OMIT_VIRTUALTABLE
  135426. if( IsVirtual(pItem->pTab) ){
  135427. rc = whereLoopAddVirtual(&sSubBuild, mPrereq, mUnusable);
  135428. }else
  135429. #endif
  135430. {
  135431. rc = whereLoopAddBtree(&sSubBuild, mPrereq);
  135432. }
  135433. if( rc==SQLITE_OK ){
  135434. rc = whereLoopAddOr(&sSubBuild, mPrereq, mUnusable);
  135435. }
  135436. assert( rc==SQLITE_OK || sCur.n==0 );
  135437. if( sCur.n==0 ){
  135438. sSum.n = 0;
  135439. break;
  135440. }else if( once ){
  135441. whereOrMove(&sSum, &sCur);
  135442. once = 0;
  135443. }else{
  135444. WhereOrSet sPrev;
  135445. whereOrMove(&sPrev, &sSum);
  135446. sSum.n = 0;
  135447. for(i=0; i<sPrev.n; i++){
  135448. for(j=0; j<sCur.n; j++){
  135449. whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
  135450. sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
  135451. sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
  135452. }
  135453. }
  135454. }
  135455. }
  135456. pNew->nLTerm = 1;
  135457. pNew->aLTerm[0] = pTerm;
  135458. pNew->wsFlags = WHERE_MULTI_OR;
  135459. pNew->rSetup = 0;
  135460. pNew->iSortIdx = 0;
  135461. memset(&pNew->u, 0, sizeof(pNew->u));
  135462. for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
  135463. /* TUNING: Currently sSum.a[i].rRun is set to the sum of the costs
  135464. ** of all sub-scans required by the OR-scan. However, due to rounding
  135465. ** errors, it may be that the cost of the OR-scan is equal to its
  135466. ** most expensive sub-scan. Add the smallest possible penalty
  135467. ** (equivalent to multiplying the cost by 1.07) to ensure that
  135468. ** this does not happen. Otherwise, for WHERE clauses such as the
  135469. ** following where there is an index on "y":
  135470. **
  135471. ** WHERE likelihood(x=?, 0.99) OR y=?
  135472. **
  135473. ** the planner may elect to "OR" together a full-table scan and an
  135474. ** index lookup. And other similarly odd results. */
  135475. pNew->rRun = sSum.a[i].rRun + 1;
  135476. pNew->nOut = sSum.a[i].nOut;
  135477. pNew->prereq = sSum.a[i].prereq;
  135478. rc = whereLoopInsert(pBuilder, pNew);
  135479. }
  135480. WHERETRACE(0x200, ("End processing OR-clause %p\n", pTerm));
  135481. }
  135482. }
  135483. return rc;
  135484. }
  135485. /*
  135486. ** Add all WhereLoop objects for all tables
  135487. */
  135488. static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
  135489. WhereInfo *pWInfo = pBuilder->pWInfo;
  135490. Bitmask mPrereq = 0;
  135491. Bitmask mPrior = 0;
  135492. int iTab;
  135493. SrcList *pTabList = pWInfo->pTabList;
  135494. struct SrcList_item *pItem;
  135495. struct SrcList_item *pEnd = &pTabList->a[pWInfo->nLevel];
  135496. sqlite3 *db = pWInfo->pParse->db;
  135497. int rc = SQLITE_OK;
  135498. WhereLoop *pNew;
  135499. u8 priorJointype = 0;
  135500. /* Loop over the tables in the join, from left to right */
  135501. pNew = pBuilder->pNew;
  135502. whereLoopInit(pNew);
  135503. pBuilder->iPlanLimit = SQLITE_QUERY_PLANNER_LIMIT;
  135504. for(iTab=0, pItem=pTabList->a; pItem<pEnd; iTab++, pItem++){
  135505. Bitmask mUnusable = 0;
  135506. pNew->iTab = iTab;
  135507. pBuilder->iPlanLimit += SQLITE_QUERY_PLANNER_LIMIT_INCR;
  135508. pNew->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, pItem->iCursor);
  135509. if( ((pItem->fg.jointype|priorJointype) & (JT_LEFT|JT_CROSS))!=0 ){
  135510. /* This condition is true when pItem is the FROM clause term on the
  135511. ** right-hand-side of a LEFT or CROSS JOIN. */
  135512. mPrereq = mPrior;
  135513. }
  135514. priorJointype = pItem->fg.jointype;
  135515. #ifndef SQLITE_OMIT_VIRTUALTABLE
  135516. if( IsVirtual(pItem->pTab) ){
  135517. struct SrcList_item *p;
  135518. for(p=&pItem[1]; p<pEnd; p++){
  135519. if( mUnusable || (p->fg.jointype & (JT_LEFT|JT_CROSS)) ){
  135520. mUnusable |= sqlite3WhereGetMask(&pWInfo->sMaskSet, p->iCursor);
  135521. }
  135522. }
  135523. rc = whereLoopAddVirtual(pBuilder, mPrereq, mUnusable);
  135524. }else
  135525. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  135526. {
  135527. rc = whereLoopAddBtree(pBuilder, mPrereq);
  135528. }
  135529. if( rc==SQLITE_OK && pBuilder->pWC->hasOr ){
  135530. rc = whereLoopAddOr(pBuilder, mPrereq, mUnusable);
  135531. }
  135532. mPrior |= pNew->maskSelf;
  135533. if( rc || db->mallocFailed ){
  135534. if( rc==SQLITE_DONE ){
  135535. /* We hit the query planner search limit set by iPlanLimit */
  135536. sqlite3_log(SQLITE_WARNING, "abbreviated query algorithm search");
  135537. rc = SQLITE_OK;
  135538. }else{
  135539. break;
  135540. }
  135541. }
  135542. }
  135543. whereLoopClear(db, pNew);
  135544. return rc;
  135545. }
  135546. /*
  135547. ** Examine a WherePath (with the addition of the extra WhereLoop of the 6th
  135548. ** parameters) to see if it outputs rows in the requested ORDER BY
  135549. ** (or GROUP BY) without requiring a separate sort operation. Return N:
  135550. **
  135551. ** N>0: N terms of the ORDER BY clause are satisfied
  135552. ** N==0: No terms of the ORDER BY clause are satisfied
  135553. ** N<0: Unknown yet how many terms of ORDER BY might be satisfied.
  135554. **
  135555. ** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
  135556. ** strict. With GROUP BY and DISTINCT the only requirement is that
  135557. ** equivalent rows appear immediately adjacent to one another. GROUP BY
  135558. ** and DISTINCT do not require rows to appear in any particular order as long
  135559. ** as equivalent rows are grouped together. Thus for GROUP BY and DISTINCT
  135560. ** the pOrderBy terms can be matched in any order. With ORDER BY, the
  135561. ** pOrderBy terms must be matched in strict left-to-right order.
  135562. */
  135563. static i8 wherePathSatisfiesOrderBy(
  135564. WhereInfo *pWInfo, /* The WHERE clause */
  135565. ExprList *pOrderBy, /* ORDER BY or GROUP BY or DISTINCT clause to check */
  135566. WherePath *pPath, /* The WherePath to check */
  135567. u16 wctrlFlags, /* WHERE_GROUPBY or _DISTINCTBY or _ORDERBY_LIMIT */
  135568. u16 nLoop, /* Number of entries in pPath->aLoop[] */
  135569. WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */
  135570. Bitmask *pRevMask /* OUT: Mask of WhereLoops to run in reverse order */
  135571. ){
  135572. u8 revSet; /* True if rev is known */
  135573. u8 rev; /* Composite sort order */
  135574. u8 revIdx; /* Index sort order */
  135575. u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */
  135576. u8 distinctColumns; /* True if the loop has UNIQUE NOT NULL columns */
  135577. u8 isMatch; /* iColumn matches a term of the ORDER BY clause */
  135578. u16 eqOpMask; /* Allowed equality operators */
  135579. u16 nKeyCol; /* Number of key columns in pIndex */
  135580. u16 nColumn; /* Total number of ordered columns in the index */
  135581. u16 nOrderBy; /* Number terms in the ORDER BY clause */
  135582. int iLoop; /* Index of WhereLoop in pPath being processed */
  135583. int i, j; /* Loop counters */
  135584. int iCur; /* Cursor number for current WhereLoop */
  135585. int iColumn; /* A column number within table iCur */
  135586. WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
  135587. WhereTerm *pTerm; /* A single term of the WHERE clause */
  135588. Expr *pOBExpr; /* An expression from the ORDER BY clause */
  135589. CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */
  135590. Index *pIndex; /* The index associated with pLoop */
  135591. sqlite3 *db = pWInfo->pParse->db; /* Database connection */
  135592. Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */
  135593. Bitmask obDone; /* Mask of all ORDER BY terms */
  135594. Bitmask orderDistinctMask; /* Mask of all well-ordered loops */
  135595. Bitmask ready; /* Mask of inner loops */
  135596. /*
  135597. ** We say the WhereLoop is "one-row" if it generates no more than one
  135598. ** row of output. A WhereLoop is one-row if all of the following are true:
  135599. ** (a) All index columns match with WHERE_COLUMN_EQ.
  135600. ** (b) The index is unique
  135601. ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
  135602. ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
  135603. **
  135604. ** We say the WhereLoop is "order-distinct" if the set of columns from
  135605. ** that WhereLoop that are in the ORDER BY clause are different for every
  135606. ** row of the WhereLoop. Every one-row WhereLoop is automatically
  135607. ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause
  135608. ** is not order-distinct. To be order-distinct is not quite the same as being
  135609. ** UNIQUE since a UNIQUE column or index can have multiple rows that
  135610. ** are NULL and NULL values are equivalent for the purpose of order-distinct.
  135611. ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
  135612. **
  135613. ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
  135614. ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
  135615. ** automatically order-distinct.
  135616. */
  135617. assert( pOrderBy!=0 );
  135618. if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
  135619. nOrderBy = pOrderBy->nExpr;
  135620. testcase( nOrderBy==BMS-1 );
  135621. if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */
  135622. isOrderDistinct = 1;
  135623. obDone = MASKBIT(nOrderBy)-1;
  135624. orderDistinctMask = 0;
  135625. ready = 0;
  135626. eqOpMask = WO_EQ | WO_IS | WO_ISNULL;
  135627. if( wctrlFlags & WHERE_ORDERBY_LIMIT ) eqOpMask |= WO_IN;
  135628. for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
  135629. if( iLoop>0 ) ready |= pLoop->maskSelf;
  135630. if( iLoop<nLoop ){
  135631. pLoop = pPath->aLoop[iLoop];
  135632. if( wctrlFlags & WHERE_ORDERBY_LIMIT ) continue;
  135633. }else{
  135634. pLoop = pLast;
  135635. }
  135636. if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){
  135637. if( pLoop->u.vtab.isOrdered ) obSat = obDone;
  135638. break;
  135639. }else{
  135640. pLoop->u.btree.nIdxCol = 0;
  135641. }
  135642. iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
  135643. /* Mark off any ORDER BY term X that is a column in the table of
  135644. ** the current loop for which there is term in the WHERE
  135645. ** clause of the form X IS NULL or X=? that reference only outer
  135646. ** loops.
  135647. */
  135648. for(i=0; i<nOrderBy; i++){
  135649. if( MASKBIT(i) & obSat ) continue;
  135650. pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
  135651. if( pOBExpr->op!=TK_COLUMN ) continue;
  135652. if( pOBExpr->iTable!=iCur ) continue;
  135653. pTerm = sqlite3WhereFindTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
  135654. ~ready, eqOpMask, 0);
  135655. if( pTerm==0 ) continue;
  135656. if( pTerm->eOperator==WO_IN ){
  135657. /* IN terms are only valid for sorting in the ORDER BY LIMIT
  135658. ** optimization, and then only if they are actually used
  135659. ** by the query plan */
  135660. assert( wctrlFlags & WHERE_ORDERBY_LIMIT );
  135661. for(j=0; j<pLoop->nLTerm && pTerm!=pLoop->aLTerm[j]; j++){}
  135662. if( j>=pLoop->nLTerm ) continue;
  135663. }
  135664. if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0 && pOBExpr->iColumn>=0 ){
  135665. if( sqlite3ExprCollSeqMatch(pWInfo->pParse,
  135666. pOrderBy->a[i].pExpr, pTerm->pExpr)==0 ){
  135667. continue;
  135668. }
  135669. testcase( pTerm->pExpr->op==TK_IS );
  135670. }
  135671. obSat |= MASKBIT(i);
  135672. }
  135673. if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
  135674. if( pLoop->wsFlags & WHERE_IPK ){
  135675. pIndex = 0;
  135676. nKeyCol = 0;
  135677. nColumn = 1;
  135678. }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
  135679. return 0;
  135680. }else{
  135681. nKeyCol = pIndex->nKeyCol;
  135682. nColumn = pIndex->nColumn;
  135683. assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) );
  135684. assert( pIndex->aiColumn[nColumn-1]==XN_ROWID
  135685. || !HasRowid(pIndex->pTable));
  135686. isOrderDistinct = IsUniqueIndex(pIndex);
  135687. }
  135688. /* Loop through all columns of the index and deal with the ones
  135689. ** that are not constrained by == or IN.
  135690. */
  135691. rev = revSet = 0;
  135692. distinctColumns = 0;
  135693. for(j=0; j<nColumn; j++){
  135694. u8 bOnce = 1; /* True to run the ORDER BY search loop */
  135695. assert( j>=pLoop->u.btree.nEq
  135696. || (pLoop->aLTerm[j]==0)==(j<pLoop->nSkip)
  135697. );
  135698. if( j<pLoop->u.btree.nEq && j>=pLoop->nSkip ){
  135699. u16 eOp = pLoop->aLTerm[j]->eOperator;
  135700. /* Skip over == and IS and ISNULL terms. (Also skip IN terms when
  135701. ** doing WHERE_ORDERBY_LIMIT processing).
  135702. **
  135703. ** If the current term is a column of an ((?,?) IN (SELECT...))
  135704. ** expression for which the SELECT returns more than one column,
  135705. ** check that it is the only column used by this loop. Otherwise,
  135706. ** if it is one of two or more, none of the columns can be
  135707. ** considered to match an ORDER BY term. */
  135708. if( (eOp & eqOpMask)!=0 ){
  135709. if( eOp & WO_ISNULL ){
  135710. testcase( isOrderDistinct );
  135711. isOrderDistinct = 0;
  135712. }
  135713. continue;
  135714. }else if( ALWAYS(eOp & WO_IN) ){
  135715. /* ALWAYS() justification: eOp is an equality operator due to the
  135716. ** j<pLoop->u.btree.nEq constraint above. Any equality other
  135717. ** than WO_IN is captured by the previous "if". So this one
  135718. ** always has to be WO_IN. */
  135719. Expr *pX = pLoop->aLTerm[j]->pExpr;
  135720. for(i=j+1; i<pLoop->u.btree.nEq; i++){
  135721. if( pLoop->aLTerm[i]->pExpr==pX ){
  135722. assert( (pLoop->aLTerm[i]->eOperator & WO_IN) );
  135723. bOnce = 0;
  135724. break;
  135725. }
  135726. }
  135727. }
  135728. }
  135729. /* Get the column number in the table (iColumn) and sort order
  135730. ** (revIdx) for the j-th column of the index.
  135731. */
  135732. if( pIndex ){
  135733. iColumn = pIndex->aiColumn[j];
  135734. revIdx = pIndex->aSortOrder[j];
  135735. if( iColumn==pIndex->pTable->iPKey ) iColumn = XN_ROWID;
  135736. }else{
  135737. iColumn = XN_ROWID;
  135738. revIdx = 0;
  135739. }
  135740. /* An unconstrained column that might be NULL means that this
  135741. ** WhereLoop is not well-ordered
  135742. */
  135743. if( isOrderDistinct
  135744. && iColumn>=0
  135745. && j>=pLoop->u.btree.nEq
  135746. && pIndex->pTable->aCol[iColumn].notNull==0
  135747. ){
  135748. isOrderDistinct = 0;
  135749. }
  135750. /* Find the ORDER BY term that corresponds to the j-th column
  135751. ** of the index and mark that ORDER BY term off
  135752. */
  135753. isMatch = 0;
  135754. for(i=0; bOnce && i<nOrderBy; i++){
  135755. if( MASKBIT(i) & obSat ) continue;
  135756. pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
  135757. testcase( wctrlFlags & WHERE_GROUPBY );
  135758. testcase( wctrlFlags & WHERE_DISTINCTBY );
  135759. if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
  135760. if( iColumn>=XN_ROWID ){
  135761. if( pOBExpr->op!=TK_COLUMN ) continue;
  135762. if( pOBExpr->iTable!=iCur ) continue;
  135763. if( pOBExpr->iColumn!=iColumn ) continue;
  135764. }else{
  135765. Expr *pIdxExpr = pIndex->aColExpr->a[j].pExpr;
  135766. if( sqlite3ExprCompareSkip(pOBExpr, pIdxExpr, iCur) ){
  135767. continue;
  135768. }
  135769. }
  135770. if( iColumn!=XN_ROWID ){
  135771. pColl = sqlite3ExprNNCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
  135772. if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
  135773. }
  135774. pLoop->u.btree.nIdxCol = j+1;
  135775. isMatch = 1;
  135776. break;
  135777. }
  135778. if( isMatch && (wctrlFlags & WHERE_GROUPBY)==0 ){
  135779. /* Make sure the sort order is compatible in an ORDER BY clause.
  135780. ** Sort order is irrelevant for a GROUP BY clause. */
  135781. if( revSet ){
  135782. if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) isMatch = 0;
  135783. }else{
  135784. rev = revIdx ^ pOrderBy->a[i].sortOrder;
  135785. if( rev ) *pRevMask |= MASKBIT(iLoop);
  135786. revSet = 1;
  135787. }
  135788. }
  135789. if( isMatch ){
  135790. if( iColumn==XN_ROWID ){
  135791. testcase( distinctColumns==0 );
  135792. distinctColumns = 1;
  135793. }
  135794. obSat |= MASKBIT(i);
  135795. }else{
  135796. /* No match found */
  135797. if( j==0 || j<nKeyCol ){
  135798. testcase( isOrderDistinct!=0 );
  135799. isOrderDistinct = 0;
  135800. }
  135801. break;
  135802. }
  135803. } /* end Loop over all index columns */
  135804. if( distinctColumns ){
  135805. testcase( isOrderDistinct==0 );
  135806. isOrderDistinct = 1;
  135807. }
  135808. } /* end-if not one-row */
  135809. /* Mark off any other ORDER BY terms that reference pLoop */
  135810. if( isOrderDistinct ){
  135811. orderDistinctMask |= pLoop->maskSelf;
  135812. for(i=0; i<nOrderBy; i++){
  135813. Expr *p;
  135814. Bitmask mTerm;
  135815. if( MASKBIT(i) & obSat ) continue;
  135816. p = pOrderBy->a[i].pExpr;
  135817. mTerm = sqlite3WhereExprUsage(&pWInfo->sMaskSet,p);
  135818. if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue;
  135819. if( (mTerm&~orderDistinctMask)==0 ){
  135820. obSat |= MASKBIT(i);
  135821. }
  135822. }
  135823. }
  135824. } /* End the loop over all WhereLoops from outer-most down to inner-most */
  135825. if( obSat==obDone ) return (i8)nOrderBy;
  135826. if( !isOrderDistinct ){
  135827. for(i=nOrderBy-1; i>0; i--){
  135828. Bitmask m = MASKBIT(i) - 1;
  135829. if( (obSat&m)==m ) return i;
  135830. }
  135831. return 0;
  135832. }
  135833. return -1;
  135834. }
  135835. /*
  135836. ** If the WHERE_GROUPBY flag is set in the mask passed to sqlite3WhereBegin(),
  135837. ** the planner assumes that the specified pOrderBy list is actually a GROUP
  135838. ** BY clause - and so any order that groups rows as required satisfies the
  135839. ** request.
  135840. **
  135841. ** Normally, in this case it is not possible for the caller to determine
  135842. ** whether or not the rows are really being delivered in sorted order, or
  135843. ** just in some other order that provides the required grouping. However,
  135844. ** if the WHERE_SORTBYGROUP flag is also passed to sqlite3WhereBegin(), then
  135845. ** this function may be called on the returned WhereInfo object. It returns
  135846. ** true if the rows really will be sorted in the specified order, or false
  135847. ** otherwise.
  135848. **
  135849. ** For example, assuming:
  135850. **
  135851. ** CREATE INDEX i1 ON t1(x, Y);
  135852. **
  135853. ** then
  135854. **
  135855. ** SELECT * FROM t1 GROUP BY x,y ORDER BY x,y; -- IsSorted()==1
  135856. ** SELECT * FROM t1 GROUP BY y,x ORDER BY y,x; -- IsSorted()==0
  135857. */
  135858. SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo *pWInfo){
  135859. assert( pWInfo->wctrlFlags & WHERE_GROUPBY );
  135860. assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP );
  135861. return pWInfo->sorted;
  135862. }
  135863. #ifdef WHERETRACE_ENABLED
  135864. /* For debugging use only: */
  135865. static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
  135866. static char zName[65];
  135867. int i;
  135868. for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
  135869. if( pLast ) zName[i++] = pLast->cId;
  135870. zName[i] = 0;
  135871. return zName;
  135872. }
  135873. #endif
  135874. /*
  135875. ** Return the cost of sorting nRow rows, assuming that the keys have
  135876. ** nOrderby columns and that the first nSorted columns are already in
  135877. ** order.
  135878. */
  135879. static LogEst whereSortingCost(
  135880. WhereInfo *pWInfo,
  135881. LogEst nRow,
  135882. int nOrderBy,
  135883. int nSorted
  135884. ){
  135885. /* TUNING: Estimated cost of a full external sort, where N is
  135886. ** the number of rows to sort is:
  135887. **
  135888. ** cost = (3.0 * N * log(N)).
  135889. **
  135890. ** Or, if the order-by clause has X terms but only the last Y
  135891. ** terms are out of order, then block-sorting will reduce the
  135892. ** sorting cost to:
  135893. **
  135894. ** cost = (3.0 * N * log(N)) * (Y/X)
  135895. **
  135896. ** The (Y/X) term is implemented using stack variable rScale
  135897. ** below. */
  135898. LogEst rScale, rSortCost;
  135899. assert( nOrderBy>0 && 66==sqlite3LogEst(100) );
  135900. rScale = sqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66;
  135901. rSortCost = nRow + rScale + 16;
  135902. /* Multiple by log(M) where M is the number of output rows.
  135903. ** Use the LIMIT for M if it is smaller */
  135904. if( (pWInfo->wctrlFlags & WHERE_USE_LIMIT)!=0 && pWInfo->iLimit<nRow ){
  135905. nRow = pWInfo->iLimit;
  135906. }
  135907. rSortCost += estLog(nRow);
  135908. return rSortCost;
  135909. }
  135910. /*
  135911. ** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
  135912. ** attempts to find the lowest cost path that visits each WhereLoop
  135913. ** once. This path is then loaded into the pWInfo->a[].pWLoop fields.
  135914. **
  135915. ** Assume that the total number of output rows that will need to be sorted
  135916. ** will be nRowEst (in the 10*log2 representation). Or, ignore sorting
  135917. ** costs if nRowEst==0.
  135918. **
  135919. ** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
  135920. ** error occurs.
  135921. */
  135922. static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
  135923. int mxChoice; /* Maximum number of simultaneous paths tracked */
  135924. int nLoop; /* Number of terms in the join */
  135925. Parse *pParse; /* Parsing context */
  135926. sqlite3 *db; /* The database connection */
  135927. int iLoop; /* Loop counter over the terms of the join */
  135928. int ii, jj; /* Loop counters */
  135929. int mxI = 0; /* Index of next entry to replace */
  135930. int nOrderBy; /* Number of ORDER BY clause terms */
  135931. LogEst mxCost = 0; /* Maximum cost of a set of paths */
  135932. LogEst mxUnsorted = 0; /* Maximum unsorted cost of a set of path */
  135933. int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */
  135934. WherePath *aFrom; /* All nFrom paths at the previous level */
  135935. WherePath *aTo; /* The nTo best paths at the current level */
  135936. WherePath *pFrom; /* An element of aFrom[] that we are working on */
  135937. WherePath *pTo; /* An element of aTo[] that we are working on */
  135938. WhereLoop *pWLoop; /* One of the WhereLoop objects */
  135939. WhereLoop **pX; /* Used to divy up the pSpace memory */
  135940. LogEst *aSortCost = 0; /* Sorting and partial sorting costs */
  135941. char *pSpace; /* Temporary memory used by this routine */
  135942. int nSpace; /* Bytes of space allocated at pSpace */
  135943. pParse = pWInfo->pParse;
  135944. db = pParse->db;
  135945. nLoop = pWInfo->nLevel;
  135946. /* TUNING: For simple queries, only the best path is tracked.
  135947. ** For 2-way joins, the 5 best paths are followed.
  135948. ** For joins of 3 or more tables, track the 10 best paths */
  135949. mxChoice = (nLoop<=1) ? 1 : (nLoop==2 ? 5 : 10);
  135950. assert( nLoop<=pWInfo->pTabList->nSrc );
  135951. WHERETRACE(0x002, ("---- begin solver. (nRowEst=%d)\n", nRowEst));
  135952. /* If nRowEst is zero and there is an ORDER BY clause, ignore it. In this
  135953. ** case the purpose of this call is to estimate the number of rows returned
  135954. ** by the overall query. Once this estimate has been obtained, the caller
  135955. ** will invoke this function a second time, passing the estimate as the
  135956. ** nRowEst parameter. */
  135957. if( pWInfo->pOrderBy==0 || nRowEst==0 ){
  135958. nOrderBy = 0;
  135959. }else{
  135960. nOrderBy = pWInfo->pOrderBy->nExpr;
  135961. }
  135962. /* Allocate and initialize space for aTo, aFrom and aSortCost[] */
  135963. nSpace = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
  135964. nSpace += sizeof(LogEst) * nOrderBy;
  135965. pSpace = sqlite3DbMallocRawNN(db, nSpace);
  135966. if( pSpace==0 ) return SQLITE_NOMEM_BKPT;
  135967. aTo = (WherePath*)pSpace;
  135968. aFrom = aTo+mxChoice;
  135969. memset(aFrom, 0, sizeof(aFrom[0]));
  135970. pX = (WhereLoop**)(aFrom+mxChoice);
  135971. for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
  135972. pFrom->aLoop = pX;
  135973. }
  135974. if( nOrderBy ){
  135975. /* If there is an ORDER BY clause and it is not being ignored, set up
  135976. ** space for the aSortCost[] array. Each element of the aSortCost array
  135977. ** is either zero - meaning it has not yet been initialized - or the
  135978. ** cost of sorting nRowEst rows of data where the first X terms of
  135979. ** the ORDER BY clause are already in order, where X is the array
  135980. ** index. */
  135981. aSortCost = (LogEst*)pX;
  135982. memset(aSortCost, 0, sizeof(LogEst) * nOrderBy);
  135983. }
  135984. assert( aSortCost==0 || &pSpace[nSpace]==(char*)&aSortCost[nOrderBy] );
  135985. assert( aSortCost!=0 || &pSpace[nSpace]==(char*)pX );
  135986. /* Seed the search with a single WherePath containing zero WhereLoops.
  135987. **
  135988. ** TUNING: Do not let the number of iterations go above 28. If the cost
  135989. ** of computing an automatic index is not paid back within the first 28
  135990. ** rows, then do not use the automatic index. */
  135991. aFrom[0].nRow = MIN(pParse->nQueryLoop, 48); assert( 48==sqlite3LogEst(28) );
  135992. nFrom = 1;
  135993. assert( aFrom[0].isOrdered==0 );
  135994. if( nOrderBy ){
  135995. /* If nLoop is zero, then there are no FROM terms in the query. Since
  135996. ** in this case the query may return a maximum of one row, the results
  135997. ** are already in the requested order. Set isOrdered to nOrderBy to
  135998. ** indicate this. Or, if nLoop is greater than zero, set isOrdered to
  135999. ** -1, indicating that the result set may or may not be ordered,
  136000. ** depending on the loops added to the current plan. */
  136001. aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy;
  136002. }
  136003. /* Compute successively longer WherePaths using the previous generation
  136004. ** of WherePaths as the basis for the next. Keep track of the mxChoice
  136005. ** best paths at each generation */
  136006. for(iLoop=0; iLoop<nLoop; iLoop++){
  136007. nTo = 0;
  136008. for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
  136009. for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
  136010. LogEst nOut; /* Rows visited by (pFrom+pWLoop) */
  136011. LogEst rCost; /* Cost of path (pFrom+pWLoop) */
  136012. LogEst rUnsorted; /* Unsorted cost of (pFrom+pWLoop) */
  136013. i8 isOrdered = pFrom->isOrdered; /* isOrdered for (pFrom+pWLoop) */
  136014. Bitmask maskNew; /* Mask of src visited by (..) */
  136015. Bitmask revMask = 0; /* Mask of rev-order loops for (..) */
  136016. if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
  136017. if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
  136018. if( (pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 && pFrom->nRow<3 ){
  136019. /* Do not use an automatic index if the this loop is expected
  136020. ** to run less than 1.25 times. It is tempting to also exclude
  136021. ** automatic index usage on an outer loop, but sometimes an automatic
  136022. ** index is useful in the outer loop of a correlated subquery. */
  136023. assert( 10==sqlite3LogEst(2) );
  136024. continue;
  136025. }
  136026. /* At this point, pWLoop is a candidate to be the next loop.
  136027. ** Compute its cost */
  136028. rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
  136029. rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted);
  136030. nOut = pFrom->nRow + pWLoop->nOut;
  136031. maskNew = pFrom->maskLoop | pWLoop->maskSelf;
  136032. if( isOrdered<0 ){
  136033. isOrdered = wherePathSatisfiesOrderBy(pWInfo,
  136034. pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
  136035. iLoop, pWLoop, &revMask);
  136036. }else{
  136037. revMask = pFrom->revLoop;
  136038. }
  136039. if( isOrdered>=0 && isOrdered<nOrderBy ){
  136040. if( aSortCost[isOrdered]==0 ){
  136041. aSortCost[isOrdered] = whereSortingCost(
  136042. pWInfo, nRowEst, nOrderBy, isOrdered
  136043. );
  136044. }
  136045. /* TUNING: Add a small extra penalty (5) to sorting as an
  136046. ** extra encouragment to the query planner to select a plan
  136047. ** where the rows emerge in the correct order without any sorting
  136048. ** required. */
  136049. rCost = sqlite3LogEstAdd(rUnsorted, aSortCost[isOrdered]) + 5;
  136050. WHERETRACE(0x002,
  136051. ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n",
  136052. aSortCost[isOrdered], (nOrderBy-isOrdered), nOrderBy,
  136053. rUnsorted, rCost));
  136054. }else{
  136055. rCost = rUnsorted;
  136056. rUnsorted -= 2; /* TUNING: Slight bias in favor of no-sort plans */
  136057. }
  136058. /* Check to see if pWLoop should be added to the set of
  136059. ** mxChoice best-so-far paths.
  136060. **
  136061. ** First look for an existing path among best-so-far paths
  136062. ** that covers the same set of loops and has the same isOrdered
  136063. ** setting as the current path candidate.
  136064. **
  136065. ** The term "((pTo->isOrdered^isOrdered)&0x80)==0" is equivalent
  136066. ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range
  136067. ** of legal values for isOrdered, -1..64.
  136068. */
  136069. for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
  136070. if( pTo->maskLoop==maskNew
  136071. && ((pTo->isOrdered^isOrdered)&0x80)==0
  136072. ){
  136073. testcase( jj==nTo-1 );
  136074. break;
  136075. }
  136076. }
  136077. if( jj>=nTo ){
  136078. /* None of the existing best-so-far paths match the candidate. */
  136079. if( nTo>=mxChoice
  136080. && (rCost>mxCost || (rCost==mxCost && rUnsorted>=mxUnsorted))
  136081. ){
  136082. /* The current candidate is no better than any of the mxChoice
  136083. ** paths currently in the best-so-far buffer. So discard
  136084. ** this candidate as not viable. */
  136085. #ifdef WHERETRACE_ENABLED /* 0x4 */
  136086. if( sqlite3WhereTrace&0x4 ){
  136087. sqlite3DebugPrintf("Skip %s cost=%-3d,%3d,%3d order=%c\n",
  136088. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
  136089. isOrdered>=0 ? isOrdered+'0' : '?');
  136090. }
  136091. #endif
  136092. continue;
  136093. }
  136094. /* If we reach this points it means that the new candidate path
  136095. ** needs to be added to the set of best-so-far paths. */
  136096. if( nTo<mxChoice ){
  136097. /* Increase the size of the aTo set by one */
  136098. jj = nTo++;
  136099. }else{
  136100. /* New path replaces the prior worst to keep count below mxChoice */
  136101. jj = mxI;
  136102. }
  136103. pTo = &aTo[jj];
  136104. #ifdef WHERETRACE_ENABLED /* 0x4 */
  136105. if( sqlite3WhereTrace&0x4 ){
  136106. sqlite3DebugPrintf("New %s cost=%-3d,%3d,%3d order=%c\n",
  136107. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
  136108. isOrdered>=0 ? isOrdered+'0' : '?');
  136109. }
  136110. #endif
  136111. }else{
  136112. /* Control reaches here if best-so-far path pTo=aTo[jj] covers the
  136113. ** same set of loops and has the same isOrdered setting as the
  136114. ** candidate path. Check to see if the candidate should replace
  136115. ** pTo or if the candidate should be skipped.
  136116. **
  136117. ** The conditional is an expanded vector comparison equivalent to:
  136118. ** (pTo->rCost,pTo->nRow,pTo->rUnsorted) <= (rCost,nOut,rUnsorted)
  136119. */
  136120. if( pTo->rCost<rCost
  136121. || (pTo->rCost==rCost
  136122. && (pTo->nRow<nOut
  136123. || (pTo->nRow==nOut && pTo->rUnsorted<=rUnsorted)
  136124. )
  136125. )
  136126. ){
  136127. #ifdef WHERETRACE_ENABLED /* 0x4 */
  136128. if( sqlite3WhereTrace&0x4 ){
  136129. sqlite3DebugPrintf(
  136130. "Skip %s cost=%-3d,%3d,%3d order=%c",
  136131. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
  136132. isOrdered>=0 ? isOrdered+'0' : '?');
  136133. sqlite3DebugPrintf(" vs %s cost=%-3d,%3d,%3d order=%c\n",
  136134. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  136135. pTo->rUnsorted, pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
  136136. }
  136137. #endif
  136138. /* Discard the candidate path from further consideration */
  136139. testcase( pTo->rCost==rCost );
  136140. continue;
  136141. }
  136142. testcase( pTo->rCost==rCost+1 );
  136143. /* Control reaches here if the candidate path is better than the
  136144. ** pTo path. Replace pTo with the candidate. */
  136145. #ifdef WHERETRACE_ENABLED /* 0x4 */
  136146. if( sqlite3WhereTrace&0x4 ){
  136147. sqlite3DebugPrintf(
  136148. "Update %s cost=%-3d,%3d,%3d order=%c",
  136149. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
  136150. isOrdered>=0 ? isOrdered+'0' : '?');
  136151. sqlite3DebugPrintf(" was %s cost=%-3d,%3d,%3d order=%c\n",
  136152. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  136153. pTo->rUnsorted, pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
  136154. }
  136155. #endif
  136156. }
  136157. /* pWLoop is a winner. Add it to the set of best so far */
  136158. pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
  136159. pTo->revLoop = revMask;
  136160. pTo->nRow = nOut;
  136161. pTo->rCost = rCost;
  136162. pTo->rUnsorted = rUnsorted;
  136163. pTo->isOrdered = isOrdered;
  136164. memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
  136165. pTo->aLoop[iLoop] = pWLoop;
  136166. if( nTo>=mxChoice ){
  136167. mxI = 0;
  136168. mxCost = aTo[0].rCost;
  136169. mxUnsorted = aTo[0].nRow;
  136170. for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
  136171. if( pTo->rCost>mxCost
  136172. || (pTo->rCost==mxCost && pTo->rUnsorted>mxUnsorted)
  136173. ){
  136174. mxCost = pTo->rCost;
  136175. mxUnsorted = pTo->rUnsorted;
  136176. mxI = jj;
  136177. }
  136178. }
  136179. }
  136180. }
  136181. }
  136182. #ifdef WHERETRACE_ENABLED /* >=2 */
  136183. if( sqlite3WhereTrace & 0x02 ){
  136184. sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
  136185. for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
  136186. sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
  136187. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  136188. pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?');
  136189. if( pTo->isOrdered>0 ){
  136190. sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
  136191. }else{
  136192. sqlite3DebugPrintf("\n");
  136193. }
  136194. }
  136195. }
  136196. #endif
  136197. /* Swap the roles of aFrom and aTo for the next generation */
  136198. pFrom = aTo;
  136199. aTo = aFrom;
  136200. aFrom = pFrom;
  136201. nFrom = nTo;
  136202. }
  136203. if( nFrom==0 ){
  136204. sqlite3ErrorMsg(pParse, "no query solution");
  136205. sqlite3DbFreeNN(db, pSpace);
  136206. return SQLITE_ERROR;
  136207. }
  136208. /* Find the lowest cost path. pFrom will be left pointing to that path */
  136209. pFrom = aFrom;
  136210. for(ii=1; ii<nFrom; ii++){
  136211. if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
  136212. }
  136213. assert( pWInfo->nLevel==nLoop );
  136214. /* Load the lowest cost path into pWInfo */
  136215. for(iLoop=0; iLoop<nLoop; iLoop++){
  136216. WhereLevel *pLevel = pWInfo->a + iLoop;
  136217. pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
  136218. pLevel->iFrom = pWLoop->iTab;
  136219. pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
  136220. }
  136221. if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
  136222. && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
  136223. && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
  136224. && nRowEst
  136225. ){
  136226. Bitmask notUsed;
  136227. int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
  136228. WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
  136229. if( rc==pWInfo->pResultSet->nExpr ){
  136230. pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
  136231. }
  136232. }
  136233. pWInfo->bOrderedInnerLoop = 0;
  136234. if( pWInfo->pOrderBy ){
  136235. if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
  136236. if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){
  136237. pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
  136238. }
  136239. }else{
  136240. pWInfo->nOBSat = pFrom->isOrdered;
  136241. pWInfo->revMask = pFrom->revLoop;
  136242. if( pWInfo->nOBSat<=0 ){
  136243. pWInfo->nOBSat = 0;
  136244. if( nLoop>0 ){
  136245. u32 wsFlags = pFrom->aLoop[nLoop-1]->wsFlags;
  136246. if( (wsFlags & WHERE_ONEROW)==0
  136247. && (wsFlags&(WHERE_IPK|WHERE_COLUMN_IN))!=(WHERE_IPK|WHERE_COLUMN_IN)
  136248. ){
  136249. Bitmask m = 0;
  136250. int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy, pFrom,
  136251. WHERE_ORDERBY_LIMIT, nLoop-1, pFrom->aLoop[nLoop-1], &m);
  136252. testcase( wsFlags & WHERE_IPK );
  136253. testcase( wsFlags & WHERE_COLUMN_IN );
  136254. if( rc==pWInfo->pOrderBy->nExpr ){
  136255. pWInfo->bOrderedInnerLoop = 1;
  136256. pWInfo->revMask = m;
  136257. }
  136258. }
  136259. }
  136260. }
  136261. }
  136262. if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP)
  136263. && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr && nLoop>0
  136264. ){
  136265. Bitmask revMask = 0;
  136266. int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy,
  136267. pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &revMask
  136268. );
  136269. assert( pWInfo->sorted==0 );
  136270. if( nOrder==pWInfo->pOrderBy->nExpr ){
  136271. pWInfo->sorted = 1;
  136272. pWInfo->revMask = revMask;
  136273. }
  136274. }
  136275. }
  136276. pWInfo->nRowOut = pFrom->nRow;
  136277. /* Free temporary memory and return success */
  136278. sqlite3DbFreeNN(db, pSpace);
  136279. return SQLITE_OK;
  136280. }
  136281. /*
  136282. ** Most queries use only a single table (they are not joins) and have
  136283. ** simple == constraints against indexed fields. This routine attempts
  136284. ** to plan those simple cases using much less ceremony than the
  136285. ** general-purpose query planner, and thereby yield faster sqlite3_prepare()
  136286. ** times for the common case.
  136287. **
  136288. ** Return non-zero on success, if this query can be handled by this
  136289. ** no-frills query planner. Return zero if this query needs the
  136290. ** general-purpose query planner.
  136291. */
  136292. static int whereShortCut(WhereLoopBuilder *pBuilder){
  136293. WhereInfo *pWInfo;
  136294. struct SrcList_item *pItem;
  136295. WhereClause *pWC;
  136296. WhereTerm *pTerm;
  136297. WhereLoop *pLoop;
  136298. int iCur;
  136299. int j;
  136300. Table *pTab;
  136301. Index *pIdx;
  136302. pWInfo = pBuilder->pWInfo;
  136303. if( pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE ) return 0;
  136304. assert( pWInfo->pTabList->nSrc>=1 );
  136305. pItem = pWInfo->pTabList->a;
  136306. pTab = pItem->pTab;
  136307. if( IsVirtual(pTab) ) return 0;
  136308. if( pItem->fg.isIndexedBy ) return 0;
  136309. iCur = pItem->iCursor;
  136310. pWC = &pWInfo->sWC;
  136311. pLoop = pBuilder->pNew;
  136312. pLoop->wsFlags = 0;
  136313. pLoop->nSkip = 0;
  136314. pTerm = sqlite3WhereFindTerm(pWC, iCur, -1, 0, WO_EQ|WO_IS, 0);
  136315. if( pTerm ){
  136316. testcase( pTerm->eOperator & WO_IS );
  136317. pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
  136318. pLoop->aLTerm[0] = pTerm;
  136319. pLoop->nLTerm = 1;
  136320. pLoop->u.btree.nEq = 1;
  136321. /* TUNING: Cost of a rowid lookup is 10 */
  136322. pLoop->rRun = 33; /* 33==sqlite3LogEst(10) */
  136323. }else{
  136324. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  136325. int opMask;
  136326. assert( pLoop->aLTermSpace==pLoop->aLTerm );
  136327. if( !IsUniqueIndex(pIdx)
  136328. || pIdx->pPartIdxWhere!=0
  136329. || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace)
  136330. ) continue;
  136331. opMask = pIdx->uniqNotNull ? (WO_EQ|WO_IS) : WO_EQ;
  136332. for(j=0; j<pIdx->nKeyCol; j++){
  136333. pTerm = sqlite3WhereFindTerm(pWC, iCur, j, 0, opMask, pIdx);
  136334. if( pTerm==0 ) break;
  136335. testcase( pTerm->eOperator & WO_IS );
  136336. pLoop->aLTerm[j] = pTerm;
  136337. }
  136338. if( j!=pIdx->nKeyCol ) continue;
  136339. pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
  136340. if( pIdx->isCovering || (pItem->colUsed & pIdx->colNotIdxed)==0 ){
  136341. pLoop->wsFlags |= WHERE_IDX_ONLY;
  136342. }
  136343. pLoop->nLTerm = j;
  136344. pLoop->u.btree.nEq = j;
  136345. pLoop->u.btree.pIndex = pIdx;
  136346. /* TUNING: Cost of a unique index lookup is 15 */
  136347. pLoop->rRun = 39; /* 39==sqlite3LogEst(15) */
  136348. break;
  136349. }
  136350. }
  136351. if( pLoop->wsFlags ){
  136352. pLoop->nOut = (LogEst)1;
  136353. pWInfo->a[0].pWLoop = pLoop;
  136354. assert( pWInfo->sMaskSet.n==1 && iCur==pWInfo->sMaskSet.ix[0] );
  136355. pLoop->maskSelf = 1; /* sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur); */
  136356. pWInfo->a[0].iTabCur = iCur;
  136357. pWInfo->nRowOut = 1;
  136358. if( pWInfo->pOrderBy ) pWInfo->nOBSat = pWInfo->pOrderBy->nExpr;
  136359. if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
  136360. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  136361. }
  136362. #ifdef SQLITE_DEBUG
  136363. pLoop->cId = '0';
  136364. #endif
  136365. return 1;
  136366. }
  136367. return 0;
  136368. }
  136369. /*
  136370. ** Helper function for exprIsDeterministic().
  136371. */
  136372. static int exprNodeIsDeterministic(Walker *pWalker, Expr *pExpr){
  136373. if( pExpr->op==TK_FUNCTION && ExprHasProperty(pExpr, EP_ConstFunc)==0 ){
  136374. pWalker->eCode = 0;
  136375. return WRC_Abort;
  136376. }
  136377. return WRC_Continue;
  136378. }
  136379. /*
  136380. ** Return true if the expression contains no non-deterministic SQL
  136381. ** functions. Do not consider non-deterministic SQL functions that are
  136382. ** part of sub-select statements.
  136383. */
  136384. static int exprIsDeterministic(Expr *p){
  136385. Walker w;
  136386. memset(&w, 0, sizeof(w));
  136387. w.eCode = 1;
  136388. w.xExprCallback = exprNodeIsDeterministic;
  136389. w.xSelectCallback = sqlite3SelectWalkFail;
  136390. sqlite3WalkExpr(&w, p);
  136391. return w.eCode;
  136392. }
  136393. /*
  136394. ** Generate the beginning of the loop used for WHERE clause processing.
  136395. ** The return value is a pointer to an opaque structure that contains
  136396. ** information needed to terminate the loop. Later, the calling routine
  136397. ** should invoke sqlite3WhereEnd() with the return value of this function
  136398. ** in order to complete the WHERE clause processing.
  136399. **
  136400. ** If an error occurs, this routine returns NULL.
  136401. **
  136402. ** The basic idea is to do a nested loop, one loop for each table in
  136403. ** the FROM clause of a select. (INSERT and UPDATE statements are the
  136404. ** same as a SELECT with only a single table in the FROM clause.) For
  136405. ** example, if the SQL is this:
  136406. **
  136407. ** SELECT * FROM t1, t2, t3 WHERE ...;
  136408. **
  136409. ** Then the code generated is conceptually like the following:
  136410. **
  136411. ** foreach row1 in t1 do \ Code generated
  136412. ** foreach row2 in t2 do |-- by sqlite3WhereBegin()
  136413. ** foreach row3 in t3 do /
  136414. ** ...
  136415. ** end \ Code generated
  136416. ** end |-- by sqlite3WhereEnd()
  136417. ** end /
  136418. **
  136419. ** Note that the loops might not be nested in the order in which they
  136420. ** appear in the FROM clause if a different order is better able to make
  136421. ** use of indices. Note also that when the IN operator appears in
  136422. ** the WHERE clause, it might result in additional nested loops for
  136423. ** scanning through all values on the right-hand side of the IN.
  136424. **
  136425. ** There are Btree cursors associated with each table. t1 uses cursor
  136426. ** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
  136427. ** And so forth. This routine generates code to open those VDBE cursors
  136428. ** and sqlite3WhereEnd() generates the code to close them.
  136429. **
  136430. ** The code that sqlite3WhereBegin() generates leaves the cursors named
  136431. ** in pTabList pointing at their appropriate entries. The [...] code
  136432. ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
  136433. ** data from the various tables of the loop.
  136434. **
  136435. ** If the WHERE clause is empty, the foreach loops must each scan their
  136436. ** entire tables. Thus a three-way join is an O(N^3) operation. But if
  136437. ** the tables have indices and there are terms in the WHERE clause that
  136438. ** refer to those indices, a complete table scan can be avoided and the
  136439. ** code will run much faster. Most of the work of this routine is checking
  136440. ** to see if there are indices that can be used to speed up the loop.
  136441. **
  136442. ** Terms of the WHERE clause are also used to limit which rows actually
  136443. ** make it to the "..." in the middle of the loop. After each "foreach",
  136444. ** terms of the WHERE clause that use only terms in that loop and outer
  136445. ** loops are evaluated and if false a jump is made around all subsequent
  136446. ** inner loops (or around the "..." if the test occurs within the inner-
  136447. ** most loop)
  136448. **
  136449. ** OUTER JOINS
  136450. **
  136451. ** An outer join of tables t1 and t2 is conceptally coded as follows:
  136452. **
  136453. ** foreach row1 in t1 do
  136454. ** flag = 0
  136455. ** foreach row2 in t2 do
  136456. ** start:
  136457. ** ...
  136458. ** flag = 1
  136459. ** end
  136460. ** if flag==0 then
  136461. ** move the row2 cursor to a null row
  136462. ** goto start
  136463. ** fi
  136464. ** end
  136465. **
  136466. ** ORDER BY CLAUSE PROCESSING
  136467. **
  136468. ** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
  136469. ** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
  136470. ** if there is one. If there is no ORDER BY clause or if this routine
  136471. ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
  136472. **
  136473. ** The iIdxCur parameter is the cursor number of an index. If
  136474. ** WHERE_OR_SUBCLAUSE is set, iIdxCur is the cursor number of an index
  136475. ** to use for OR clause processing. The WHERE clause should use this
  136476. ** specific cursor. If WHERE_ONEPASS_DESIRED is set, then iIdxCur is
  136477. ** the first cursor in an array of cursors for all indices. iIdxCur should
  136478. ** be used to compute the appropriate cursor depending on which index is
  136479. ** used.
  136480. */
  136481. SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
  136482. Parse *pParse, /* The parser context */
  136483. SrcList *pTabList, /* FROM clause: A list of all tables to be scanned */
  136484. Expr *pWhere, /* The WHERE clause */
  136485. ExprList *pOrderBy, /* An ORDER BY (or GROUP BY) clause, or NULL */
  136486. ExprList *pResultSet, /* Query result set. Req'd for DISTINCT */
  136487. u16 wctrlFlags, /* The WHERE_* flags defined in sqliteInt.h */
  136488. int iAuxArg /* If WHERE_OR_SUBCLAUSE is set, index cursor number
  136489. ** If WHERE_USE_LIMIT, then the limit amount */
  136490. ){
  136491. int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
  136492. int nTabList; /* Number of elements in pTabList */
  136493. WhereInfo *pWInfo; /* Will become the return value of this function */
  136494. Vdbe *v = pParse->pVdbe; /* The virtual database engine */
  136495. Bitmask notReady; /* Cursors that are not yet positioned */
  136496. WhereLoopBuilder sWLB; /* The WhereLoop builder */
  136497. WhereMaskSet *pMaskSet; /* The expression mask set */
  136498. WhereLevel *pLevel; /* A single level in pWInfo->a[] */
  136499. WhereLoop *pLoop; /* Pointer to a single WhereLoop object */
  136500. int ii; /* Loop counter */
  136501. sqlite3 *db; /* Database connection */
  136502. int rc; /* Return code */
  136503. u8 bFordelete = 0; /* OPFLAG_FORDELETE or zero, as appropriate */
  136504. assert( (wctrlFlags & WHERE_ONEPASS_MULTIROW)==0 || (
  136505. (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
  136506. && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0
  136507. ));
  136508. /* Only one of WHERE_OR_SUBCLAUSE or WHERE_USE_LIMIT */
  136509. assert( (wctrlFlags & WHERE_OR_SUBCLAUSE)==0
  136510. || (wctrlFlags & WHERE_USE_LIMIT)==0 );
  136511. /* Variable initialization */
  136512. db = pParse->db;
  136513. memset(&sWLB, 0, sizeof(sWLB));
  136514. /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */
  136515. testcase( pOrderBy && pOrderBy->nExpr==BMS-1 );
  136516. if( pOrderBy && pOrderBy->nExpr>=BMS ) pOrderBy = 0;
  136517. sWLB.pOrderBy = pOrderBy;
  136518. /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
  136519. ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
  136520. if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
  136521. wctrlFlags &= ~WHERE_WANT_DISTINCT;
  136522. }
  136523. /* The number of tables in the FROM clause is limited by the number of
  136524. ** bits in a Bitmask
  136525. */
  136526. testcase( pTabList->nSrc==BMS );
  136527. if( pTabList->nSrc>BMS ){
  136528. sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
  136529. return 0;
  136530. }
  136531. /* This function normally generates a nested loop for all tables in
  136532. ** pTabList. But if the WHERE_OR_SUBCLAUSE flag is set, then we should
  136533. ** only generate code for the first table in pTabList and assume that
  136534. ** any cursors associated with subsequent tables are uninitialized.
  136535. */
  136536. nTabList = (wctrlFlags & WHERE_OR_SUBCLAUSE) ? 1 : pTabList->nSrc;
  136537. /* Allocate and initialize the WhereInfo structure that will become the
  136538. ** return value. A single allocation is used to store the WhereInfo
  136539. ** struct, the contents of WhereInfo.a[], the WhereClause structure
  136540. ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
  136541. ** field (type Bitmask) it must be aligned on an 8-byte boundary on
  136542. ** some architectures. Hence the ROUND8() below.
  136543. */
  136544. nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
  136545. pWInfo = sqlite3DbMallocRawNN(db, nByteWInfo + sizeof(WhereLoop));
  136546. if( db->mallocFailed ){
  136547. sqlite3DbFree(db, pWInfo);
  136548. pWInfo = 0;
  136549. goto whereBeginError;
  136550. }
  136551. pWInfo->pParse = pParse;
  136552. pWInfo->pTabList = pTabList;
  136553. pWInfo->pOrderBy = pOrderBy;
  136554. pWInfo->pWhere = pWhere;
  136555. pWInfo->pResultSet = pResultSet;
  136556. pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;
  136557. pWInfo->nLevel = nTabList;
  136558. pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(pParse);
  136559. pWInfo->wctrlFlags = wctrlFlags;
  136560. pWInfo->iLimit = iAuxArg;
  136561. pWInfo->savedNQueryLoop = pParse->nQueryLoop;
  136562. memset(&pWInfo->nOBSat, 0,
  136563. offsetof(WhereInfo,sWC) - offsetof(WhereInfo,nOBSat));
  136564. memset(&pWInfo->a[0], 0, sizeof(WhereLoop)+nTabList*sizeof(WhereLevel));
  136565. assert( pWInfo->eOnePass==ONEPASS_OFF ); /* ONEPASS defaults to OFF */
  136566. pMaskSet = &pWInfo->sMaskSet;
  136567. sWLB.pWInfo = pWInfo;
  136568. sWLB.pWC = &pWInfo->sWC;
  136569. sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
  136570. assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
  136571. whereLoopInit(sWLB.pNew);
  136572. #ifdef SQLITE_DEBUG
  136573. sWLB.pNew->cId = '*';
  136574. #endif
  136575. /* Split the WHERE clause into separate subexpressions where each
  136576. ** subexpression is separated by an AND operator.
  136577. */
  136578. initMaskSet(pMaskSet);
  136579. sqlite3WhereClauseInit(&pWInfo->sWC, pWInfo);
  136580. sqlite3WhereSplit(&pWInfo->sWC, pWhere, TK_AND);
  136581. /* Special case: No FROM clause
  136582. */
  136583. if( nTabList==0 ){
  136584. if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr;
  136585. if( wctrlFlags & WHERE_WANT_DISTINCT ){
  136586. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  136587. }
  136588. ExplainQueryPlan((pParse, 0, "SCAN CONSTANT ROW"));
  136589. }else{
  136590. /* Assign a bit from the bitmask to every term in the FROM clause.
  136591. **
  136592. ** The N-th term of the FROM clause is assigned a bitmask of 1<<N.
  136593. **
  136594. ** The rule of the previous sentence ensures thta if X is the bitmask for
  136595. ** a table T, then X-1 is the bitmask for all other tables to the left of T.
  136596. ** Knowing the bitmask for all tables to the left of a left join is
  136597. ** important. Ticket #3015.
  136598. **
  136599. ** Note that bitmasks are created for all pTabList->nSrc tables in
  136600. ** pTabList, not just the first nTabList tables. nTabList is normally
  136601. ** equal to pTabList->nSrc but might be shortened to 1 if the
  136602. ** WHERE_OR_SUBCLAUSE flag is set.
  136603. */
  136604. ii = 0;
  136605. do{
  136606. createMask(pMaskSet, pTabList->a[ii].iCursor);
  136607. sqlite3WhereTabFuncArgs(pParse, &pTabList->a[ii], &pWInfo->sWC);
  136608. }while( (++ii)<pTabList->nSrc );
  136609. #ifdef SQLITE_DEBUG
  136610. {
  136611. Bitmask mx = 0;
  136612. for(ii=0; ii<pTabList->nSrc; ii++){
  136613. Bitmask m = sqlite3WhereGetMask(pMaskSet, pTabList->a[ii].iCursor);
  136614. assert( m>=mx );
  136615. mx = m;
  136616. }
  136617. }
  136618. #endif
  136619. }
  136620. /* Analyze all of the subexpressions. */
  136621. sqlite3WhereExprAnalyze(pTabList, &pWInfo->sWC);
  136622. if( db->mallocFailed ) goto whereBeginError;
  136623. /* Special case: WHERE terms that do not refer to any tables in the join
  136624. ** (constant expressions). Evaluate each such term, and jump over all the
  136625. ** generated code if the result is not true.
  136626. **
  136627. ** Do not do this if the expression contains non-deterministic functions
  136628. ** that are not within a sub-select. This is not strictly required, but
  136629. ** preserves SQLite's legacy behaviour in the following two cases:
  136630. **
  136631. ** FROM ... WHERE random()>0; -- eval random() once per row
  136632. ** FROM ... WHERE (SELECT random())>0; -- eval random() once overall
  136633. */
  136634. for(ii=0; ii<sWLB.pWC->nTerm; ii++){
  136635. WhereTerm *pT = &sWLB.pWC->a[ii];
  136636. if( pT->wtFlags & TERM_VIRTUAL ) continue;
  136637. if( pT->prereqAll==0 && (nTabList==0 || exprIsDeterministic(pT->pExpr)) ){
  136638. sqlite3ExprIfFalse(pParse, pT->pExpr, pWInfo->iBreak, SQLITE_JUMPIFNULL);
  136639. pT->wtFlags |= TERM_CODED;
  136640. }
  136641. }
  136642. if( wctrlFlags & WHERE_WANT_DISTINCT ){
  136643. if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
  136644. /* The DISTINCT marking is pointless. Ignore it. */
  136645. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  136646. }else if( pOrderBy==0 ){
  136647. /* Try to ORDER BY the result set to make distinct processing easier */
  136648. pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
  136649. pWInfo->pOrderBy = pResultSet;
  136650. }
  136651. }
  136652. /* Construct the WhereLoop objects */
  136653. #if defined(WHERETRACE_ENABLED)
  136654. if( sqlite3WhereTrace & 0xffff ){
  136655. sqlite3DebugPrintf("*** Optimizer Start *** (wctrlFlags: 0x%x",wctrlFlags);
  136656. if( wctrlFlags & WHERE_USE_LIMIT ){
  136657. sqlite3DebugPrintf(", limit: %d", iAuxArg);
  136658. }
  136659. sqlite3DebugPrintf(")\n");
  136660. }
  136661. if( sqlite3WhereTrace & 0x100 ){ /* Display all terms of the WHERE clause */
  136662. sqlite3WhereClausePrint(sWLB.pWC);
  136663. }
  136664. #endif
  136665. if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
  136666. rc = whereLoopAddAll(&sWLB);
  136667. if( rc ) goto whereBeginError;
  136668. #ifdef WHERETRACE_ENABLED
  136669. if( sqlite3WhereTrace ){ /* Display all of the WhereLoop objects */
  136670. WhereLoop *p;
  136671. int i;
  136672. static const char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
  136673. "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
  136674. for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
  136675. p->cId = zLabel[i%(sizeof(zLabel)-1)];
  136676. whereLoopPrint(p, sWLB.pWC);
  136677. }
  136678. }
  136679. #endif
  136680. wherePathSolver(pWInfo, 0);
  136681. if( db->mallocFailed ) goto whereBeginError;
  136682. if( pWInfo->pOrderBy ){
  136683. wherePathSolver(pWInfo, pWInfo->nRowOut+1);
  136684. if( db->mallocFailed ) goto whereBeginError;
  136685. }
  136686. }
  136687. if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
  136688. pWInfo->revMask = ALLBITS;
  136689. }
  136690. if( pParse->nErr || NEVER(db->mallocFailed) ){
  136691. goto whereBeginError;
  136692. }
  136693. #ifdef WHERETRACE_ENABLED
  136694. if( sqlite3WhereTrace ){
  136695. sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
  136696. if( pWInfo->nOBSat>0 ){
  136697. sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask);
  136698. }
  136699. switch( pWInfo->eDistinct ){
  136700. case WHERE_DISTINCT_UNIQUE: {
  136701. sqlite3DebugPrintf(" DISTINCT=unique");
  136702. break;
  136703. }
  136704. case WHERE_DISTINCT_ORDERED: {
  136705. sqlite3DebugPrintf(" DISTINCT=ordered");
  136706. break;
  136707. }
  136708. case WHERE_DISTINCT_UNORDERED: {
  136709. sqlite3DebugPrintf(" DISTINCT=unordered");
  136710. break;
  136711. }
  136712. }
  136713. sqlite3DebugPrintf("\n");
  136714. for(ii=0; ii<pWInfo->nLevel; ii++){
  136715. whereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC);
  136716. }
  136717. }
  136718. #endif
  136719. /* Attempt to omit tables from the join that do not affect the result.
  136720. ** For a table to not affect the result, the following must be true:
  136721. **
  136722. ** 1) The query must not be an aggregate.
  136723. ** 2) The table must be the RHS of a LEFT JOIN.
  136724. ** 3) Either the query must be DISTINCT, or else the ON or USING clause
  136725. ** must contain a constraint that limits the scan of the table to
  136726. ** at most a single row.
  136727. ** 4) The table must not be referenced by any part of the query apart
  136728. ** from its own USING or ON clause.
  136729. **
  136730. ** For example, given:
  136731. **
  136732. ** CREATE TABLE t1(ipk INTEGER PRIMARY KEY, v1);
  136733. ** CREATE TABLE t2(ipk INTEGER PRIMARY KEY, v2);
  136734. ** CREATE TABLE t3(ipk INTEGER PRIMARY KEY, v3);
  136735. **
  136736. ** then table t2 can be omitted from the following:
  136737. **
  136738. ** SELECT v1, v3 FROM t1
  136739. ** LEFT JOIN t2 USING (t1.ipk=t2.ipk)
  136740. ** LEFT JOIN t3 USING (t1.ipk=t3.ipk)
  136741. **
  136742. ** or from:
  136743. **
  136744. ** SELECT DISTINCT v1, v3 FROM t1
  136745. ** LEFT JOIN t2
  136746. ** LEFT JOIN t3 USING (t1.ipk=t3.ipk)
  136747. */
  136748. notReady = ~(Bitmask)0;
  136749. if( pWInfo->nLevel>=2
  136750. && pResultSet!=0 /* guarantees condition (1) above */
  136751. && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
  136752. ){
  136753. int i;
  136754. Bitmask tabUsed = sqlite3WhereExprListUsage(pMaskSet, pResultSet);
  136755. if( sWLB.pOrderBy ){
  136756. tabUsed |= sqlite3WhereExprListUsage(pMaskSet, sWLB.pOrderBy);
  136757. }
  136758. for(i=pWInfo->nLevel-1; i>=1; i--){
  136759. WhereTerm *pTerm, *pEnd;
  136760. struct SrcList_item *pItem;
  136761. pLoop = pWInfo->a[i].pWLoop;
  136762. pItem = &pWInfo->pTabList->a[pLoop->iTab];
  136763. if( (pItem->fg.jointype & JT_LEFT)==0 ) continue;
  136764. if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
  136765. && (pLoop->wsFlags & WHERE_ONEROW)==0
  136766. ){
  136767. continue;
  136768. }
  136769. if( (tabUsed & pLoop->maskSelf)!=0 ) continue;
  136770. pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
  136771. for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
  136772. if( (pTerm->prereqAll & pLoop->maskSelf)!=0 ){
  136773. if( !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
  136774. || pTerm->pExpr->iRightJoinTable!=pItem->iCursor
  136775. ){
  136776. break;
  136777. }
  136778. }
  136779. }
  136780. if( pTerm<pEnd ) continue;
  136781. WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
  136782. notReady &= ~pLoop->maskSelf;
  136783. for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
  136784. if( (pTerm->prereqAll & pLoop->maskSelf)!=0 ){
  136785. pTerm->wtFlags |= TERM_CODED;
  136786. }
  136787. }
  136788. if( i!=pWInfo->nLevel-1 ){
  136789. int nByte = (pWInfo->nLevel-1-i) * sizeof(WhereLevel);
  136790. memmove(&pWInfo->a[i], &pWInfo->a[i+1], nByte);
  136791. }
  136792. pWInfo->nLevel--;
  136793. nTabList--;
  136794. }
  136795. }
  136796. WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
  136797. pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
  136798. /* If the caller is an UPDATE or DELETE statement that is requesting
  136799. ** to use a one-pass algorithm, determine if this is appropriate.
  136800. **
  136801. ** A one-pass approach can be used if the caller has requested one
  136802. ** and either (a) the scan visits at most one row or (b) each
  136803. ** of the following are true:
  136804. **
  136805. ** * the caller has indicated that a one-pass approach can be used
  136806. ** with multiple rows (by setting WHERE_ONEPASS_MULTIROW), and
  136807. ** * the table is not a virtual table, and
  136808. ** * either the scan does not use the OR optimization or the caller
  136809. ** is a DELETE operation (WHERE_DUPLICATES_OK is only specified
  136810. ** for DELETE).
  136811. **
  136812. ** The last qualification is because an UPDATE statement uses
  136813. ** WhereInfo.aiCurOnePass[1] to determine whether or not it really can
  136814. ** use a one-pass approach, and this is not set accurately for scans
  136815. ** that use the OR optimization.
  136816. */
  136817. assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
  136818. if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 ){
  136819. int wsFlags = pWInfo->a[0].pWLoop->wsFlags;
  136820. int bOnerow = (wsFlags & WHERE_ONEROW)!=0;
  136821. assert( !(wsFlags & WHERE_VIRTUALTABLE) || IsVirtual(pTabList->a[0].pTab) );
  136822. if( bOnerow || (
  136823. 0!=(wctrlFlags & WHERE_ONEPASS_MULTIROW)
  136824. && !IsVirtual(pTabList->a[0].pTab)
  136825. && (0==(wsFlags & WHERE_MULTI_OR) || (wctrlFlags & WHERE_DUPLICATES_OK))
  136826. )){
  136827. pWInfo->eOnePass = bOnerow ? ONEPASS_SINGLE : ONEPASS_MULTI;
  136828. if( HasRowid(pTabList->a[0].pTab) && (wsFlags & WHERE_IDX_ONLY) ){
  136829. if( wctrlFlags & WHERE_ONEPASS_MULTIROW ){
  136830. bFordelete = OPFLAG_FORDELETE;
  136831. }
  136832. pWInfo->a[0].pWLoop->wsFlags = (wsFlags & ~WHERE_IDX_ONLY);
  136833. }
  136834. }
  136835. }
  136836. /* Open all tables in the pTabList and any indices selected for
  136837. ** searching those tables.
  136838. */
  136839. for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
  136840. Table *pTab; /* Table to open */
  136841. int iDb; /* Index of database containing table/index */
  136842. struct SrcList_item *pTabItem;
  136843. pTabItem = &pTabList->a[pLevel->iFrom];
  136844. pTab = pTabItem->pTab;
  136845. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  136846. pLoop = pLevel->pWLoop;
  136847. if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
  136848. /* Do nothing */
  136849. }else
  136850. #ifndef SQLITE_OMIT_VIRTUALTABLE
  136851. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
  136852. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  136853. int iCur = pTabItem->iCursor;
  136854. sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
  136855. }else if( IsVirtual(pTab) ){
  136856. /* noop */
  136857. }else
  136858. #endif
  136859. if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
  136860. && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0 ){
  136861. int op = OP_OpenRead;
  136862. if( pWInfo->eOnePass!=ONEPASS_OFF ){
  136863. op = OP_OpenWrite;
  136864. pWInfo->aiCurOnePass[0] = pTabItem->iCursor;
  136865. };
  136866. sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
  136867. assert( pTabItem->iCursor==pLevel->iTabCur );
  136868. testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS-1 );
  136869. testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS );
  136870. if( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol<BMS && HasRowid(pTab) ){
  136871. Bitmask b = pTabItem->colUsed;
  136872. int n = 0;
  136873. for(; b; b=b>>1, n++){}
  136874. sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(n), P4_INT32);
  136875. assert( n<=pTab->nCol );
  136876. }
  136877. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  136878. if( pLoop->u.btree.pIndex!=0 ){
  136879. sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ|bFordelete);
  136880. }else
  136881. #endif
  136882. {
  136883. sqlite3VdbeChangeP5(v, bFordelete);
  136884. }
  136885. #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
  136886. sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, pTabItem->iCursor, 0, 0,
  136887. (const u8*)&pTabItem->colUsed, P4_INT64);
  136888. #endif
  136889. }else{
  136890. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  136891. }
  136892. if( pLoop->wsFlags & WHERE_INDEXED ){
  136893. Index *pIx = pLoop->u.btree.pIndex;
  136894. int iIndexCur;
  136895. int op = OP_OpenRead;
  136896. /* iAuxArg is always set to a positive value if ONEPASS is possible */
  136897. assert( iAuxArg!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 );
  136898. if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx)
  136899. && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0
  136900. ){
  136901. /* This is one term of an OR-optimization using the PRIMARY KEY of a
  136902. ** WITHOUT ROWID table. No need for a separate index */
  136903. iIndexCur = pLevel->iTabCur;
  136904. op = 0;
  136905. }else if( pWInfo->eOnePass!=ONEPASS_OFF ){
  136906. Index *pJ = pTabItem->pTab->pIndex;
  136907. iIndexCur = iAuxArg;
  136908. assert( wctrlFlags & WHERE_ONEPASS_DESIRED );
  136909. while( ALWAYS(pJ) && pJ!=pIx ){
  136910. iIndexCur++;
  136911. pJ = pJ->pNext;
  136912. }
  136913. op = OP_OpenWrite;
  136914. pWInfo->aiCurOnePass[1] = iIndexCur;
  136915. }else if( iAuxArg && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 ){
  136916. iIndexCur = iAuxArg;
  136917. op = OP_ReopenIdx;
  136918. }else{
  136919. iIndexCur = pParse->nTab++;
  136920. }
  136921. pLevel->iIdxCur = iIndexCur;
  136922. assert( pIx->pSchema==pTab->pSchema );
  136923. assert( iIndexCur>=0 );
  136924. if( op ){
  136925. sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb);
  136926. sqlite3VdbeSetP4KeyInfo(pParse, pIx);
  136927. if( (pLoop->wsFlags & WHERE_CONSTRAINT)!=0
  136928. && (pLoop->wsFlags & (WHERE_COLUMN_RANGE|WHERE_SKIPSCAN))==0
  136929. && (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0
  136930. && pWInfo->eDistinct!=WHERE_DISTINCT_ORDERED
  136931. ){
  136932. sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ); /* Hint to COMDB2 */
  136933. }
  136934. VdbeComment((v, "%s", pIx->zName));
  136935. #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
  136936. {
  136937. u64 colUsed = 0;
  136938. int ii, jj;
  136939. for(ii=0; ii<pIx->nColumn; ii++){
  136940. jj = pIx->aiColumn[ii];
  136941. if( jj<0 ) continue;
  136942. if( jj>63 ) jj = 63;
  136943. if( (pTabItem->colUsed & MASKBIT(jj))==0 ) continue;
  136944. colUsed |= ((u64)1)<<(ii<63 ? ii : 63);
  136945. }
  136946. sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, iIndexCur, 0, 0,
  136947. (u8*)&colUsed, P4_INT64);
  136948. }
  136949. #endif /* SQLITE_ENABLE_COLUMN_USED_MASK */
  136950. }
  136951. }
  136952. if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb);
  136953. }
  136954. pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
  136955. if( db->mallocFailed ) goto whereBeginError;
  136956. /* Generate the code to do the search. Each iteration of the for
  136957. ** loop below generates code for a single nested loop of the VM
  136958. ** program.
  136959. */
  136960. for(ii=0; ii<nTabList; ii++){
  136961. int addrExplain;
  136962. int wsFlags;
  136963. pLevel = &pWInfo->a[ii];
  136964. wsFlags = pLevel->pWLoop->wsFlags;
  136965. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  136966. if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
  136967. constructAutomaticIndex(pParse, &pWInfo->sWC,
  136968. &pTabList->a[pLevel->iFrom], notReady, pLevel);
  136969. if( db->mallocFailed ) goto whereBeginError;
  136970. }
  136971. #endif
  136972. addrExplain = sqlite3WhereExplainOneScan(
  136973. pParse, pTabList, pLevel, wctrlFlags
  136974. );
  136975. pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
  136976. notReady = sqlite3WhereCodeOneLoopStart(pParse,v,pWInfo,ii,pLevel,notReady);
  136977. pWInfo->iContinue = pLevel->addrCont;
  136978. if( (wsFlags&WHERE_MULTI_OR)==0 && (wctrlFlags&WHERE_OR_SUBCLAUSE)==0 ){
  136979. sqlite3WhereAddScanStatus(v, pTabList, pLevel, addrExplain);
  136980. }
  136981. }
  136982. /* Done. */
  136983. VdbeModuleComment((v, "Begin WHERE-core"));
  136984. return pWInfo;
  136985. /* Jump here if malloc fails */
  136986. whereBeginError:
  136987. if( pWInfo ){
  136988. pParse->nQueryLoop = pWInfo->savedNQueryLoop;
  136989. whereInfoFree(db, pWInfo);
  136990. }
  136991. return 0;
  136992. }
  136993. /*
  136994. ** Part of sqlite3WhereEnd() will rewrite opcodes to reference the
  136995. ** index rather than the main table. In SQLITE_DEBUG mode, we want
  136996. ** to trace those changes if PRAGMA vdbe_addoptrace=on. This routine
  136997. ** does that.
  136998. */
  136999. #ifndef SQLITE_DEBUG
  137000. # define OpcodeRewriteTrace(D,K,P) /* no-op */
  137001. #else
  137002. # define OpcodeRewriteTrace(D,K,P) sqlite3WhereOpcodeRewriteTrace(D,K,P)
  137003. static void sqlite3WhereOpcodeRewriteTrace(
  137004. sqlite3 *db,
  137005. int pc,
  137006. VdbeOp *pOp
  137007. ){
  137008. if( (db->flags & SQLITE_VdbeAddopTrace)==0 ) return;
  137009. sqlite3VdbePrintOp(0, pc, pOp);
  137010. }
  137011. #endif
  137012. /*
  137013. ** Generate the end of the WHERE loop. See comments on
  137014. ** sqlite3WhereBegin() for additional information.
  137015. */
  137016. SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
  137017. Parse *pParse = pWInfo->pParse;
  137018. Vdbe *v = pParse->pVdbe;
  137019. int i;
  137020. WhereLevel *pLevel;
  137021. WhereLoop *pLoop;
  137022. SrcList *pTabList = pWInfo->pTabList;
  137023. sqlite3 *db = pParse->db;
  137024. /* Generate loop termination code.
  137025. */
  137026. VdbeModuleComment((v, "End WHERE-core"));
  137027. for(i=pWInfo->nLevel-1; i>=0; i--){
  137028. int addr;
  137029. pLevel = &pWInfo->a[i];
  137030. pLoop = pLevel->pWLoop;
  137031. if( pLevel->op!=OP_Noop ){
  137032. #ifndef SQLITE_DISABLE_SKIPAHEAD_DISTINCT
  137033. int addrSeek = 0;
  137034. Index *pIdx;
  137035. int n;
  137036. if( pWInfo->eDistinct==WHERE_DISTINCT_ORDERED
  137037. && i==pWInfo->nLevel-1 /* Ticket [ef9318757b152e3] 2017-10-21 */
  137038. && (pLoop->wsFlags & WHERE_INDEXED)!=0
  137039. && (pIdx = pLoop->u.btree.pIndex)->hasStat1
  137040. && (n = pLoop->u.btree.nIdxCol)>0
  137041. && pIdx->aiRowLogEst[n]>=36
  137042. ){
  137043. int r1 = pParse->nMem+1;
  137044. int j, op;
  137045. for(j=0; j<n; j++){
  137046. sqlite3VdbeAddOp3(v, OP_Column, pLevel->iIdxCur, j, r1+j);
  137047. }
  137048. pParse->nMem += n+1;
  137049. op = pLevel->op==OP_Prev ? OP_SeekLT : OP_SeekGT;
  137050. addrSeek = sqlite3VdbeAddOp4Int(v, op, pLevel->iIdxCur, 0, r1, n);
  137051. VdbeCoverageIf(v, op==OP_SeekLT);
  137052. VdbeCoverageIf(v, op==OP_SeekGT);
  137053. sqlite3VdbeAddOp2(v, OP_Goto, 1, pLevel->p2);
  137054. }
  137055. #endif /* SQLITE_DISABLE_SKIPAHEAD_DISTINCT */
  137056. /* The common case: Advance to the next row */
  137057. sqlite3VdbeResolveLabel(v, pLevel->addrCont);
  137058. sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3);
  137059. sqlite3VdbeChangeP5(v, pLevel->p5);
  137060. VdbeCoverage(v);
  137061. VdbeCoverageIf(v, pLevel->op==OP_Next);
  137062. VdbeCoverageIf(v, pLevel->op==OP_Prev);
  137063. VdbeCoverageIf(v, pLevel->op==OP_VNext);
  137064. #ifndef SQLITE_DISABLE_SKIPAHEAD_DISTINCT
  137065. if( addrSeek ) sqlite3VdbeJumpHere(v, addrSeek);
  137066. #endif
  137067. }else{
  137068. sqlite3VdbeResolveLabel(v, pLevel->addrCont);
  137069. }
  137070. if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
  137071. struct InLoop *pIn;
  137072. int j;
  137073. sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
  137074. for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
  137075. sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
  137076. if( pIn->eEndLoopOp!=OP_Noop ){
  137077. if( pIn->nPrefix ){
  137078. assert( pLoop->wsFlags & WHERE_IN_EARLYOUT );
  137079. sqlite3VdbeAddOp4Int(v, OP_IfNoHope, pLevel->iIdxCur,
  137080. sqlite3VdbeCurrentAddr(v)+2,
  137081. pIn->iBase, pIn->nPrefix);
  137082. VdbeCoverage(v);
  137083. }
  137084. sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
  137085. VdbeCoverage(v);
  137086. VdbeCoverageIf(v, pIn->eEndLoopOp==OP_Prev);
  137087. VdbeCoverageIf(v, pIn->eEndLoopOp==OP_Next);
  137088. }
  137089. sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
  137090. }
  137091. }
  137092. sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
  137093. if( pLevel->addrSkip ){
  137094. sqlite3VdbeGoto(v, pLevel->addrSkip);
  137095. VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName));
  137096. sqlite3VdbeJumpHere(v, pLevel->addrSkip);
  137097. sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
  137098. }
  137099. #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  137100. if( pLevel->addrLikeRep ){
  137101. sqlite3VdbeAddOp2(v, OP_DecrJumpZero, (int)(pLevel->iLikeRepCntr>>1),
  137102. pLevel->addrLikeRep);
  137103. VdbeCoverage(v);
  137104. }
  137105. #endif
  137106. if( pLevel->iLeftJoin ){
  137107. int ws = pLoop->wsFlags;
  137108. addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v);
  137109. assert( (ws & WHERE_IDX_ONLY)==0 || (ws & WHERE_INDEXED)!=0 );
  137110. if( (ws & WHERE_IDX_ONLY)==0 ){
  137111. assert( pLevel->iTabCur==pTabList->a[pLevel->iFrom].iCursor );
  137112. sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iTabCur);
  137113. }
  137114. if( (ws & WHERE_INDEXED)
  137115. || ((ws & WHERE_MULTI_OR) && pLevel->u.pCovidx)
  137116. ){
  137117. sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
  137118. }
  137119. if( pLevel->op==OP_Return ){
  137120. sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
  137121. }else{
  137122. sqlite3VdbeGoto(v, pLevel->addrFirst);
  137123. }
  137124. sqlite3VdbeJumpHere(v, addr);
  137125. }
  137126. VdbeModuleComment((v, "End WHERE-loop%d: %s", i,
  137127. pWInfo->pTabList->a[pLevel->iFrom].pTab->zName));
  137128. }
  137129. /* The "break" point is here, just past the end of the outer loop.
  137130. ** Set it.
  137131. */
  137132. sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
  137133. assert( pWInfo->nLevel<=pTabList->nSrc );
  137134. for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
  137135. int k, last;
  137136. VdbeOp *pOp;
  137137. Index *pIdx = 0;
  137138. struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
  137139. Table *pTab = pTabItem->pTab;
  137140. assert( pTab!=0 );
  137141. pLoop = pLevel->pWLoop;
  137142. /* For a co-routine, change all OP_Column references to the table of
  137143. ** the co-routine into OP_Copy of result contained in a register.
  137144. ** OP_Rowid becomes OP_Null.
  137145. */
  137146. if( pTabItem->fg.viaCoroutine ){
  137147. testcase( pParse->db->mallocFailed );
  137148. translateColumnToCopy(pParse, pLevel->addrBody, pLevel->iTabCur,
  137149. pTabItem->regResult, 0);
  137150. continue;
  137151. }
  137152. #ifdef SQLITE_ENABLE_EARLY_CURSOR_CLOSE
  137153. /* Close all of the cursors that were opened by sqlite3WhereBegin.
  137154. ** Except, do not close cursors that will be reused by the OR optimization
  137155. ** (WHERE_OR_SUBCLAUSE). And do not close the OP_OpenWrite cursors
  137156. ** created for the ONEPASS optimization.
  137157. */
  137158. if( (pTab->tabFlags & TF_Ephemeral)==0
  137159. && pTab->pSelect==0
  137160. && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0
  137161. ){
  137162. int ws = pLoop->wsFlags;
  137163. if( pWInfo->eOnePass==ONEPASS_OFF && (ws & WHERE_IDX_ONLY)==0 ){
  137164. sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
  137165. }
  137166. if( (ws & WHERE_INDEXED)!=0
  137167. && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0
  137168. && pLevel->iIdxCur!=pWInfo->aiCurOnePass[1]
  137169. ){
  137170. sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
  137171. }
  137172. }
  137173. #endif
  137174. /* If this scan uses an index, make VDBE code substitutions to read data
  137175. ** from the index instead of from the table where possible. In some cases
  137176. ** this optimization prevents the table from ever being read, which can
  137177. ** yield a significant performance boost.
  137178. **
  137179. ** Calls to the code generator in between sqlite3WhereBegin and
  137180. ** sqlite3WhereEnd will have created code that references the table
  137181. ** directly. This loop scans all that code looking for opcodes
  137182. ** that reference the table and converts them into opcodes that
  137183. ** reference the index.
  137184. */
  137185. if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
  137186. pIdx = pLoop->u.btree.pIndex;
  137187. }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
  137188. pIdx = pLevel->u.pCovidx;
  137189. }
  137190. if( pIdx
  137191. && (pWInfo->eOnePass==ONEPASS_OFF || !HasRowid(pIdx->pTable))
  137192. && !db->mallocFailed
  137193. ){
  137194. last = sqlite3VdbeCurrentAddr(v);
  137195. k = pLevel->addrBody;
  137196. #ifdef SQLITE_DEBUG
  137197. if( db->flags & SQLITE_VdbeAddopTrace ){
  137198. printf("TRANSLATE opcodes in range %d..%d\n", k, last-1);
  137199. }
  137200. #endif
  137201. pOp = sqlite3VdbeGetOp(v, k);
  137202. for(; k<last; k++, pOp++){
  137203. if( pOp->p1!=pLevel->iTabCur ) continue;
  137204. if( pOp->opcode==OP_Column
  137205. #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
  137206. || pOp->opcode==OP_Offset
  137207. #endif
  137208. ){
  137209. int x = pOp->p2;
  137210. assert( pIdx->pTable==pTab );
  137211. if( !HasRowid(pTab) ){
  137212. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  137213. x = pPk->aiColumn[x];
  137214. assert( x>=0 );
  137215. }
  137216. x = sqlite3ColumnOfIndex(pIdx, x);
  137217. if( x>=0 ){
  137218. pOp->p2 = x;
  137219. pOp->p1 = pLevel->iIdxCur;
  137220. OpcodeRewriteTrace(db, k, pOp);
  137221. }
  137222. assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0
  137223. || pWInfo->eOnePass );
  137224. }else if( pOp->opcode==OP_Rowid ){
  137225. pOp->p1 = pLevel->iIdxCur;
  137226. pOp->opcode = OP_IdxRowid;
  137227. OpcodeRewriteTrace(db, k, pOp);
  137228. }else if( pOp->opcode==OP_IfNullRow ){
  137229. pOp->p1 = pLevel->iIdxCur;
  137230. OpcodeRewriteTrace(db, k, pOp);
  137231. }
  137232. }
  137233. #ifdef SQLITE_DEBUG
  137234. if( db->flags & SQLITE_VdbeAddopTrace ) printf("TRANSLATE complete\n");
  137235. #endif
  137236. }
  137237. }
  137238. /* Final cleanup
  137239. */
  137240. pParse->nQueryLoop = pWInfo->savedNQueryLoop;
  137241. whereInfoFree(db, pWInfo);
  137242. return;
  137243. }
  137244. /************** End of where.c ***********************************************/
  137245. /************** Begin file window.c ******************************************/
  137246. /*
  137247. ** 2018 May 08
  137248. **
  137249. ** The author disclaims copyright to this source code. In place of
  137250. ** a legal notice, here is a blessing:
  137251. **
  137252. ** May you do good and not evil.
  137253. ** May you find forgiveness for yourself and forgive others.
  137254. ** May you share freely, never taking more than you give.
  137255. **
  137256. *************************************************************************
  137257. */
  137258. /* #include "sqliteInt.h" */
  137259. #ifndef SQLITE_OMIT_WINDOWFUNC
  137260. /*
  137261. ** SELECT REWRITING
  137262. **
  137263. ** Any SELECT statement that contains one or more window functions in
  137264. ** either the select list or ORDER BY clause (the only two places window
  137265. ** functions may be used) is transformed by function sqlite3WindowRewrite()
  137266. ** in order to support window function processing. For example, with the
  137267. ** schema:
  137268. **
  137269. ** CREATE TABLE t1(a, b, c, d, e, f, g);
  137270. **
  137271. ** the statement:
  137272. **
  137273. ** SELECT a+1, max(b) OVER (PARTITION BY c ORDER BY d) FROM t1 ORDER BY e;
  137274. **
  137275. ** is transformed to:
  137276. **
  137277. ** SELECT a+1, max(b) OVER (PARTITION BY c ORDER BY d) FROM (
  137278. ** SELECT a, e, c, d, b FROM t1 ORDER BY c, d
  137279. ** ) ORDER BY e;
  137280. **
  137281. ** The flattening optimization is disabled when processing this transformed
  137282. ** SELECT statement. This allows the implementation of the window function
  137283. ** (in this case max()) to process rows sorted in order of (c, d), which
  137284. ** makes things easier for obvious reasons. More generally:
  137285. **
  137286. ** * FROM, WHERE, GROUP BY and HAVING clauses are all moved to
  137287. ** the sub-query.
  137288. **
  137289. ** * ORDER BY, LIMIT and OFFSET remain part of the parent query.
  137290. **
  137291. ** * Terminals from each of the expression trees that make up the
  137292. ** select-list and ORDER BY expressions in the parent query are
  137293. ** selected by the sub-query. For the purposes of the transformation,
  137294. ** terminals are column references and aggregate functions.
  137295. **
  137296. ** If there is more than one window function in the SELECT that uses
  137297. ** the same window declaration (the OVER bit), then a single scan may
  137298. ** be used to process more than one window function. For example:
  137299. **
  137300. ** SELECT max(b) OVER (PARTITION BY c ORDER BY d),
  137301. ** min(e) OVER (PARTITION BY c ORDER BY d)
  137302. ** FROM t1;
  137303. **
  137304. ** is transformed in the same way as the example above. However:
  137305. **
  137306. ** SELECT max(b) OVER (PARTITION BY c ORDER BY d),
  137307. ** min(e) OVER (PARTITION BY a ORDER BY b)
  137308. ** FROM t1;
  137309. **
  137310. ** Must be transformed to:
  137311. **
  137312. ** SELECT max(b) OVER (PARTITION BY c ORDER BY d) FROM (
  137313. ** SELECT e, min(e) OVER (PARTITION BY a ORDER BY b), c, d, b FROM
  137314. ** SELECT a, e, c, d, b FROM t1 ORDER BY a, b
  137315. ** ) ORDER BY c, d
  137316. ** ) ORDER BY e;
  137317. **
  137318. ** so that both min() and max() may process rows in the order defined by
  137319. ** their respective window declarations.
  137320. **
  137321. ** INTERFACE WITH SELECT.C
  137322. **
  137323. ** When processing the rewritten SELECT statement, code in select.c calls
  137324. ** sqlite3WhereBegin() to begin iterating through the results of the
  137325. ** sub-query, which is always implemented as a co-routine. It then calls
  137326. ** sqlite3WindowCodeStep() to process rows and finish the scan by calling
  137327. ** sqlite3WhereEnd().
  137328. **
  137329. ** sqlite3WindowCodeStep() generates VM code so that, for each row returned
  137330. ** by the sub-query a sub-routine (OP_Gosub) coded by select.c is invoked.
  137331. ** When the sub-routine is invoked:
  137332. **
  137333. ** * The results of all window-functions for the row are stored
  137334. ** in the associated Window.regResult registers.
  137335. **
  137336. ** * The required terminal values are stored in the current row of
  137337. ** temp table Window.iEphCsr.
  137338. **
  137339. ** In some cases, depending on the window frame and the specific window
  137340. ** functions invoked, sqlite3WindowCodeStep() caches each entire partition
  137341. ** in a temp table before returning any rows. In other cases it does not.
  137342. ** This detail is encapsulated within this file, the code generated by
  137343. ** select.c is the same in either case.
  137344. **
  137345. ** BUILT-IN WINDOW FUNCTIONS
  137346. **
  137347. ** This implementation features the following built-in window functions:
  137348. **
  137349. ** row_number()
  137350. ** rank()
  137351. ** dense_rank()
  137352. ** percent_rank()
  137353. ** cume_dist()
  137354. ** ntile(N)
  137355. ** lead(expr [, offset [, default]])
  137356. ** lag(expr [, offset [, default]])
  137357. ** first_value(expr)
  137358. ** last_value(expr)
  137359. ** nth_value(expr, N)
  137360. **
  137361. ** These are the same built-in window functions supported by Postgres.
  137362. ** Although the behaviour of aggregate window functions (functions that
  137363. ** can be used as either aggregates or window funtions) allows them to
  137364. ** be implemented using an API, built-in window functions are much more
  137365. ** esoteric. Additionally, some window functions (e.g. nth_value())
  137366. ** may only be implemented by caching the entire partition in memory.
  137367. ** As such, some built-in window functions use the same API as aggregate
  137368. ** window functions and some are implemented directly using VDBE
  137369. ** instructions. Additionally, for those functions that use the API, the
  137370. ** window frame is sometimes modified before the SELECT statement is
  137371. ** rewritten. For example, regardless of the specified window frame, the
  137372. ** row_number() function always uses:
  137373. **
  137374. ** ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
  137375. **
  137376. ** See sqlite3WindowUpdate() for details.
  137377. **
  137378. ** As well as some of the built-in window functions, aggregate window
  137379. ** functions min() and max() are implemented using VDBE instructions if
  137380. ** the start of the window frame is declared as anything other than
  137381. ** UNBOUNDED PRECEDING.
  137382. */
  137383. /*
  137384. ** Implementation of built-in window function row_number(). Assumes that the
  137385. ** window frame has been coerced to:
  137386. **
  137387. ** ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
  137388. */
  137389. static void row_numberStepFunc(
  137390. sqlite3_context *pCtx,
  137391. int nArg,
  137392. sqlite3_value **apArg
  137393. ){
  137394. i64 *p = (i64*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  137395. if( p ) (*p)++;
  137396. UNUSED_PARAMETER(nArg);
  137397. UNUSED_PARAMETER(apArg);
  137398. }
  137399. static void row_numberValueFunc(sqlite3_context *pCtx){
  137400. i64 *p = (i64*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  137401. sqlite3_result_int64(pCtx, (p ? *p : 0));
  137402. }
  137403. /*
  137404. ** Context object type used by rank(), dense_rank(), percent_rank() and
  137405. ** cume_dist().
  137406. */
  137407. struct CallCount {
  137408. i64 nValue;
  137409. i64 nStep;
  137410. i64 nTotal;
  137411. };
  137412. /*
  137413. ** Implementation of built-in window function dense_rank(). Assumes that
  137414. ** the window frame has been set to:
  137415. **
  137416. ** RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
  137417. */
  137418. static void dense_rankStepFunc(
  137419. sqlite3_context *pCtx,
  137420. int nArg,
  137421. sqlite3_value **apArg
  137422. ){
  137423. struct CallCount *p;
  137424. p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  137425. if( p ) p->nStep = 1;
  137426. UNUSED_PARAMETER(nArg);
  137427. UNUSED_PARAMETER(apArg);
  137428. }
  137429. static void dense_rankValueFunc(sqlite3_context *pCtx){
  137430. struct CallCount *p;
  137431. p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  137432. if( p ){
  137433. if( p->nStep ){
  137434. p->nValue++;
  137435. p->nStep = 0;
  137436. }
  137437. sqlite3_result_int64(pCtx, p->nValue);
  137438. }
  137439. }
  137440. /*
  137441. ** Implementation of built-in window function nth_value(). This
  137442. ** implementation is used in "slow mode" only - when the EXCLUDE clause
  137443. ** is not set to the default value "NO OTHERS".
  137444. */
  137445. struct NthValueCtx {
  137446. i64 nStep;
  137447. sqlite3_value *pValue;
  137448. };
  137449. static void nth_valueStepFunc(
  137450. sqlite3_context *pCtx,
  137451. int nArg,
  137452. sqlite3_value **apArg
  137453. ){
  137454. struct NthValueCtx *p;
  137455. p = (struct NthValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  137456. if( p ){
  137457. i64 iVal;
  137458. switch( sqlite3_value_numeric_type(apArg[1]) ){
  137459. case SQLITE_INTEGER:
  137460. iVal = sqlite3_value_int64(apArg[1]);
  137461. break;
  137462. case SQLITE_FLOAT: {
  137463. double fVal = sqlite3_value_double(apArg[1]);
  137464. if( ((i64)fVal)!=fVal ) goto error_out;
  137465. iVal = (i64)fVal;
  137466. break;
  137467. }
  137468. default:
  137469. goto error_out;
  137470. }
  137471. if( iVal<=0 ) goto error_out;
  137472. p->nStep++;
  137473. if( iVal==p->nStep ){
  137474. p->pValue = sqlite3_value_dup(apArg[0]);
  137475. if( !p->pValue ){
  137476. sqlite3_result_error_nomem(pCtx);
  137477. }
  137478. }
  137479. }
  137480. UNUSED_PARAMETER(nArg);
  137481. UNUSED_PARAMETER(apArg);
  137482. return;
  137483. error_out:
  137484. sqlite3_result_error(
  137485. pCtx, "second argument to nth_value must be a positive integer", -1
  137486. );
  137487. }
  137488. static void nth_valueFinalizeFunc(sqlite3_context *pCtx){
  137489. struct NthValueCtx *p;
  137490. p = (struct NthValueCtx*)sqlite3_aggregate_context(pCtx, 0);
  137491. if( p && p->pValue ){
  137492. sqlite3_result_value(pCtx, p->pValue);
  137493. sqlite3_value_free(p->pValue);
  137494. p->pValue = 0;
  137495. }
  137496. }
  137497. #define nth_valueInvFunc noopStepFunc
  137498. #define nth_valueValueFunc noopValueFunc
  137499. static void first_valueStepFunc(
  137500. sqlite3_context *pCtx,
  137501. int nArg,
  137502. sqlite3_value **apArg
  137503. ){
  137504. struct NthValueCtx *p;
  137505. p = (struct NthValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  137506. if( p && p->pValue==0 ){
  137507. p->pValue = sqlite3_value_dup(apArg[0]);
  137508. if( !p->pValue ){
  137509. sqlite3_result_error_nomem(pCtx);
  137510. }
  137511. }
  137512. UNUSED_PARAMETER(nArg);
  137513. UNUSED_PARAMETER(apArg);
  137514. }
  137515. static void first_valueFinalizeFunc(sqlite3_context *pCtx){
  137516. struct NthValueCtx *p;
  137517. p = (struct NthValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  137518. if( p && p->pValue ){
  137519. sqlite3_result_value(pCtx, p->pValue);
  137520. sqlite3_value_free(p->pValue);
  137521. p->pValue = 0;
  137522. }
  137523. }
  137524. #define first_valueInvFunc noopStepFunc
  137525. #define first_valueValueFunc noopValueFunc
  137526. /*
  137527. ** Implementation of built-in window function rank(). Assumes that
  137528. ** the window frame has been set to:
  137529. **
  137530. ** RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
  137531. */
  137532. static void rankStepFunc(
  137533. sqlite3_context *pCtx,
  137534. int nArg,
  137535. sqlite3_value **apArg
  137536. ){
  137537. struct CallCount *p;
  137538. p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  137539. if( p ){
  137540. p->nStep++;
  137541. if( p->nValue==0 ){
  137542. p->nValue = p->nStep;
  137543. }
  137544. }
  137545. UNUSED_PARAMETER(nArg);
  137546. UNUSED_PARAMETER(apArg);
  137547. }
  137548. static void rankValueFunc(sqlite3_context *pCtx){
  137549. struct CallCount *p;
  137550. p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  137551. if( p ){
  137552. sqlite3_result_int64(pCtx, p->nValue);
  137553. p->nValue = 0;
  137554. }
  137555. }
  137556. /*
  137557. ** Implementation of built-in window function percent_rank(). Assumes that
  137558. ** the window frame has been set to:
  137559. **
  137560. ** GROUPS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
  137561. */
  137562. static void percent_rankStepFunc(
  137563. sqlite3_context *pCtx,
  137564. int nArg,
  137565. sqlite3_value **apArg
  137566. ){
  137567. struct CallCount *p;
  137568. UNUSED_PARAMETER(nArg); assert( nArg==0 );
  137569. UNUSED_PARAMETER(apArg);
  137570. p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  137571. if( p ){
  137572. p->nTotal++;
  137573. }
  137574. }
  137575. static void percent_rankInvFunc(
  137576. sqlite3_context *pCtx,
  137577. int nArg,
  137578. sqlite3_value **apArg
  137579. ){
  137580. struct CallCount *p;
  137581. UNUSED_PARAMETER(nArg); assert( nArg==0 );
  137582. UNUSED_PARAMETER(apArg);
  137583. p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  137584. p->nStep++;
  137585. }
  137586. static void percent_rankValueFunc(sqlite3_context *pCtx){
  137587. struct CallCount *p;
  137588. p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  137589. if( p ){
  137590. p->nValue = p->nStep;
  137591. if( p->nTotal>1 ){
  137592. double r = (double)p->nValue / (double)(p->nTotal-1);
  137593. sqlite3_result_double(pCtx, r);
  137594. }else{
  137595. sqlite3_result_double(pCtx, 0.0);
  137596. }
  137597. }
  137598. }
  137599. #define percent_rankFinalizeFunc percent_rankValueFunc
  137600. /*
  137601. ** Implementation of built-in window function cume_dist(). Assumes that
  137602. ** the window frame has been set to:
  137603. **
  137604. ** GROUPS BETWEEN 1 FOLLOWING AND UNBOUNDED FOLLOWING
  137605. */
  137606. static void cume_distStepFunc(
  137607. sqlite3_context *pCtx,
  137608. int nArg,
  137609. sqlite3_value **apArg
  137610. ){
  137611. struct CallCount *p;
  137612. UNUSED_PARAMETER(nArg); assert( nArg==0 );
  137613. UNUSED_PARAMETER(apArg);
  137614. p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  137615. if( p ){
  137616. p->nTotal++;
  137617. }
  137618. }
  137619. static void cume_distInvFunc(
  137620. sqlite3_context *pCtx,
  137621. int nArg,
  137622. sqlite3_value **apArg
  137623. ){
  137624. struct CallCount *p;
  137625. UNUSED_PARAMETER(nArg); assert( nArg==0 );
  137626. UNUSED_PARAMETER(apArg);
  137627. p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  137628. p->nStep++;
  137629. }
  137630. static void cume_distValueFunc(sqlite3_context *pCtx){
  137631. struct CallCount *p;
  137632. p = (struct CallCount*)sqlite3_aggregate_context(pCtx, 0);
  137633. if( p ){
  137634. double r = (double)(p->nStep) / (double)(p->nTotal);
  137635. sqlite3_result_double(pCtx, r);
  137636. }
  137637. }
  137638. #define cume_distFinalizeFunc cume_distValueFunc
  137639. /*
  137640. ** Context object for ntile() window function.
  137641. */
  137642. struct NtileCtx {
  137643. i64 nTotal; /* Total rows in partition */
  137644. i64 nParam; /* Parameter passed to ntile(N) */
  137645. i64 iRow; /* Current row */
  137646. };
  137647. /*
  137648. ** Implementation of ntile(). This assumes that the window frame has
  137649. ** been coerced to:
  137650. **
  137651. ** ROWS CURRENT ROW AND UNBOUNDED FOLLOWING
  137652. */
  137653. static void ntileStepFunc(
  137654. sqlite3_context *pCtx,
  137655. int nArg,
  137656. sqlite3_value **apArg
  137657. ){
  137658. struct NtileCtx *p;
  137659. assert( nArg==1 ); UNUSED_PARAMETER(nArg);
  137660. p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  137661. if( p ){
  137662. if( p->nTotal==0 ){
  137663. p->nParam = sqlite3_value_int64(apArg[0]);
  137664. if( p->nParam<=0 ){
  137665. sqlite3_result_error(
  137666. pCtx, "argument of ntile must be a positive integer", -1
  137667. );
  137668. }
  137669. }
  137670. p->nTotal++;
  137671. }
  137672. }
  137673. static void ntileInvFunc(
  137674. sqlite3_context *pCtx,
  137675. int nArg,
  137676. sqlite3_value **apArg
  137677. ){
  137678. struct NtileCtx *p;
  137679. assert( nArg==1 ); UNUSED_PARAMETER(nArg);
  137680. UNUSED_PARAMETER(apArg);
  137681. p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  137682. p->iRow++;
  137683. }
  137684. static void ntileValueFunc(sqlite3_context *pCtx){
  137685. struct NtileCtx *p;
  137686. p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  137687. if( p && p->nParam>0 ){
  137688. int nSize = (p->nTotal / p->nParam);
  137689. if( nSize==0 ){
  137690. sqlite3_result_int64(pCtx, p->iRow+1);
  137691. }else{
  137692. i64 nLarge = p->nTotal - p->nParam*nSize;
  137693. i64 iSmall = nLarge*(nSize+1);
  137694. i64 iRow = p->iRow;
  137695. assert( (nLarge*(nSize+1) + (p->nParam-nLarge)*nSize)==p->nTotal );
  137696. if( iRow<iSmall ){
  137697. sqlite3_result_int64(pCtx, 1 + iRow/(nSize+1));
  137698. }else{
  137699. sqlite3_result_int64(pCtx, 1 + nLarge + (iRow-iSmall)/nSize);
  137700. }
  137701. }
  137702. }
  137703. }
  137704. #define ntileFinalizeFunc ntileValueFunc
  137705. /*
  137706. ** Context object for last_value() window function.
  137707. */
  137708. struct LastValueCtx {
  137709. sqlite3_value *pVal;
  137710. int nVal;
  137711. };
  137712. /*
  137713. ** Implementation of last_value().
  137714. */
  137715. static void last_valueStepFunc(
  137716. sqlite3_context *pCtx,
  137717. int nArg,
  137718. sqlite3_value **apArg
  137719. ){
  137720. struct LastValueCtx *p;
  137721. UNUSED_PARAMETER(nArg);
  137722. p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  137723. if( p ){
  137724. sqlite3_value_free(p->pVal);
  137725. p->pVal = sqlite3_value_dup(apArg[0]);
  137726. if( p->pVal==0 ){
  137727. sqlite3_result_error_nomem(pCtx);
  137728. }else{
  137729. p->nVal++;
  137730. }
  137731. }
  137732. }
  137733. static void last_valueInvFunc(
  137734. sqlite3_context *pCtx,
  137735. int nArg,
  137736. sqlite3_value **apArg
  137737. ){
  137738. struct LastValueCtx *p;
  137739. UNUSED_PARAMETER(nArg);
  137740. UNUSED_PARAMETER(apArg);
  137741. p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  137742. if( ALWAYS(p) ){
  137743. p->nVal--;
  137744. if( p->nVal==0 ){
  137745. sqlite3_value_free(p->pVal);
  137746. p->pVal = 0;
  137747. }
  137748. }
  137749. }
  137750. static void last_valueValueFunc(sqlite3_context *pCtx){
  137751. struct LastValueCtx *p;
  137752. p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, 0);
  137753. if( p && p->pVal ){
  137754. sqlite3_result_value(pCtx, p->pVal);
  137755. }
  137756. }
  137757. static void last_valueFinalizeFunc(sqlite3_context *pCtx){
  137758. struct LastValueCtx *p;
  137759. p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  137760. if( p && p->pVal ){
  137761. sqlite3_result_value(pCtx, p->pVal);
  137762. sqlite3_value_free(p->pVal);
  137763. p->pVal = 0;
  137764. }
  137765. }
  137766. /*
  137767. ** Static names for the built-in window function names. These static
  137768. ** names are used, rather than string literals, so that FuncDef objects
  137769. ** can be associated with a particular window function by direct
  137770. ** comparison of the zName pointer. Example:
  137771. **
  137772. ** if( pFuncDef->zName==row_valueName ){ ... }
  137773. */
  137774. static const char row_numberName[] = "row_number";
  137775. static const char dense_rankName[] = "dense_rank";
  137776. static const char rankName[] = "rank";
  137777. static const char percent_rankName[] = "percent_rank";
  137778. static const char cume_distName[] = "cume_dist";
  137779. static const char ntileName[] = "ntile";
  137780. static const char last_valueName[] = "last_value";
  137781. static const char nth_valueName[] = "nth_value";
  137782. static const char first_valueName[] = "first_value";
  137783. static const char leadName[] = "lead";
  137784. static const char lagName[] = "lag";
  137785. /*
  137786. ** No-op implementations of xStep() and xFinalize(). Used as place-holders
  137787. ** for built-in window functions that never call those interfaces.
  137788. **
  137789. ** The noopValueFunc() is called but is expected to do nothing. The
  137790. ** noopStepFunc() is never called, and so it is marked with NO_TEST to
  137791. ** let the test coverage routine know not to expect this function to be
  137792. ** invoked.
  137793. */
  137794. static void noopStepFunc( /*NO_TEST*/
  137795. sqlite3_context *p, /*NO_TEST*/
  137796. int n, /*NO_TEST*/
  137797. sqlite3_value **a /*NO_TEST*/
  137798. ){ /*NO_TEST*/
  137799. UNUSED_PARAMETER(p); /*NO_TEST*/
  137800. UNUSED_PARAMETER(n); /*NO_TEST*/
  137801. UNUSED_PARAMETER(a); /*NO_TEST*/
  137802. assert(0); /*NO_TEST*/
  137803. } /*NO_TEST*/
  137804. static void noopValueFunc(sqlite3_context *p){ UNUSED_PARAMETER(p); /*no-op*/ }
  137805. /* Window functions that use all window interfaces: xStep, xFinal,
  137806. ** xValue, and xInverse */
  137807. #define WINDOWFUNCALL(name,nArg,extra) { \
  137808. nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \
  137809. name ## StepFunc, name ## FinalizeFunc, name ## ValueFunc, \
  137810. name ## InvFunc, name ## Name, {0} \
  137811. }
  137812. /* Window functions that are implemented using bytecode and thus have
  137813. ** no-op routines for their methods */
  137814. #define WINDOWFUNCNOOP(name,nArg,extra) { \
  137815. nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \
  137816. noopStepFunc, noopValueFunc, noopValueFunc, \
  137817. noopStepFunc, name ## Name, {0} \
  137818. }
  137819. /* Window functions that use all window interfaces: xStep, the
  137820. ** same routine for xFinalize and xValue and which never call
  137821. ** xInverse. */
  137822. #define WINDOWFUNCX(name,nArg,extra) { \
  137823. nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \
  137824. name ## StepFunc, name ## ValueFunc, name ## ValueFunc, \
  137825. noopStepFunc, name ## Name, {0} \
  137826. }
  137827. /*
  137828. ** Register those built-in window functions that are not also aggregates.
  137829. */
  137830. SQLITE_PRIVATE void sqlite3WindowFunctions(void){
  137831. static FuncDef aWindowFuncs[] = {
  137832. WINDOWFUNCX(row_number, 0, 0),
  137833. WINDOWFUNCX(dense_rank, 0, 0),
  137834. WINDOWFUNCX(rank, 0, 0),
  137835. WINDOWFUNCALL(percent_rank, 0, 0),
  137836. WINDOWFUNCALL(cume_dist, 0, 0),
  137837. WINDOWFUNCALL(ntile, 1, 0),
  137838. WINDOWFUNCALL(last_value, 1, 0),
  137839. WINDOWFUNCALL(nth_value, 2, 0),
  137840. WINDOWFUNCALL(first_value, 1, 0),
  137841. WINDOWFUNCNOOP(lead, 1, 0),
  137842. WINDOWFUNCNOOP(lead, 2, 0),
  137843. WINDOWFUNCNOOP(lead, 3, 0),
  137844. WINDOWFUNCNOOP(lag, 1, 0),
  137845. WINDOWFUNCNOOP(lag, 2, 0),
  137846. WINDOWFUNCNOOP(lag, 3, 0),
  137847. };
  137848. sqlite3InsertBuiltinFuncs(aWindowFuncs, ArraySize(aWindowFuncs));
  137849. }
  137850. static Window *windowFind(Parse *pParse, Window *pList, const char *zName){
  137851. Window *p;
  137852. for(p=pList; p; p=p->pNextWin){
  137853. if( sqlite3StrICmp(p->zName, zName)==0 ) break;
  137854. }
  137855. if( p==0 ){
  137856. sqlite3ErrorMsg(pParse, "no such window: %s", zName);
  137857. }
  137858. return p;
  137859. }
  137860. /*
  137861. ** This function is called immediately after resolving the function name
  137862. ** for a window function within a SELECT statement. Argument pList is a
  137863. ** linked list of WINDOW definitions for the current SELECT statement.
  137864. ** Argument pFunc is the function definition just resolved and pWin
  137865. ** is the Window object representing the associated OVER clause. This
  137866. ** function updates the contents of pWin as follows:
  137867. **
  137868. ** * If the OVER clause refered to a named window (as in "max(x) OVER win"),
  137869. ** search list pList for a matching WINDOW definition, and update pWin
  137870. ** accordingly. If no such WINDOW clause can be found, leave an error
  137871. ** in pParse.
  137872. **
  137873. ** * If the function is a built-in window function that requires the
  137874. ** window to be coerced (see "BUILT-IN WINDOW FUNCTIONS" at the top
  137875. ** of this file), pWin is updated here.
  137876. */
  137877. SQLITE_PRIVATE void sqlite3WindowUpdate(
  137878. Parse *pParse,
  137879. Window *pList, /* List of named windows for this SELECT */
  137880. Window *pWin, /* Window frame to update */
  137881. FuncDef *pFunc /* Window function definition */
  137882. ){
  137883. if( pWin->zName && pWin->eFrmType==0 ){
  137884. Window *p = windowFind(pParse, pList, pWin->zName);
  137885. if( p==0 ) return;
  137886. pWin->pPartition = sqlite3ExprListDup(pParse->db, p->pPartition, 0);
  137887. pWin->pOrderBy = sqlite3ExprListDup(pParse->db, p->pOrderBy, 0);
  137888. pWin->pStart = sqlite3ExprDup(pParse->db, p->pStart, 0);
  137889. pWin->pEnd = sqlite3ExprDup(pParse->db, p->pEnd, 0);
  137890. pWin->eStart = p->eStart;
  137891. pWin->eEnd = p->eEnd;
  137892. pWin->eFrmType = p->eFrmType;
  137893. pWin->eExclude = p->eExclude;
  137894. }else{
  137895. sqlite3WindowChain(pParse, pWin, pList);
  137896. }
  137897. if( (pWin->eFrmType==TK_RANGE)
  137898. && (pWin->pStart || pWin->pEnd)
  137899. && (pWin->pOrderBy==0 || pWin->pOrderBy->nExpr!=1)
  137900. ){
  137901. sqlite3ErrorMsg(pParse,
  137902. "RANGE with offset PRECEDING/FOLLOWING requires one ORDER BY expression"
  137903. );
  137904. }else
  137905. if( pFunc->funcFlags & SQLITE_FUNC_WINDOW ){
  137906. sqlite3 *db = pParse->db;
  137907. if( pWin->pFilter ){
  137908. sqlite3ErrorMsg(pParse,
  137909. "FILTER clause may only be used with aggregate window functions"
  137910. );
  137911. }else{
  137912. struct WindowUpdate {
  137913. const char *zFunc;
  137914. int eFrmType;
  137915. int eStart;
  137916. int eEnd;
  137917. } aUp[] = {
  137918. { row_numberName, TK_ROWS, TK_UNBOUNDED, TK_CURRENT },
  137919. { dense_rankName, TK_RANGE, TK_UNBOUNDED, TK_CURRENT },
  137920. { rankName, TK_RANGE, TK_UNBOUNDED, TK_CURRENT },
  137921. { percent_rankName, TK_GROUPS, TK_CURRENT, TK_UNBOUNDED },
  137922. { cume_distName, TK_GROUPS, TK_FOLLOWING, TK_UNBOUNDED },
  137923. { ntileName, TK_ROWS, TK_CURRENT, TK_UNBOUNDED },
  137924. { leadName, TK_ROWS, TK_UNBOUNDED, TK_UNBOUNDED },
  137925. { lagName, TK_ROWS, TK_UNBOUNDED, TK_CURRENT },
  137926. };
  137927. int i;
  137928. for(i=0; i<ArraySize(aUp); i++){
  137929. if( pFunc->zName==aUp[i].zFunc ){
  137930. sqlite3ExprDelete(db, pWin->pStart);
  137931. sqlite3ExprDelete(db, pWin->pEnd);
  137932. pWin->pEnd = pWin->pStart = 0;
  137933. pWin->eFrmType = aUp[i].eFrmType;
  137934. pWin->eStart = aUp[i].eStart;
  137935. pWin->eEnd = aUp[i].eEnd;
  137936. pWin->eExclude = 0;
  137937. if( pWin->eStart==TK_FOLLOWING ){
  137938. pWin->pStart = sqlite3Expr(db, TK_INTEGER, "1");
  137939. }
  137940. break;
  137941. }
  137942. }
  137943. }
  137944. }
  137945. pWin->pFunc = pFunc;
  137946. }
  137947. /*
  137948. ** Context object passed through sqlite3WalkExprList() to
  137949. ** selectWindowRewriteExprCb() by selectWindowRewriteEList().
  137950. */
  137951. typedef struct WindowRewrite WindowRewrite;
  137952. struct WindowRewrite {
  137953. Window *pWin;
  137954. SrcList *pSrc;
  137955. ExprList *pSub;
  137956. Table *pTab;
  137957. Select *pSubSelect; /* Current sub-select, if any */
  137958. };
  137959. /*
  137960. ** Callback function used by selectWindowRewriteEList(). If necessary,
  137961. ** this function appends to the output expression-list and updates
  137962. ** expression (*ppExpr) in place.
  137963. */
  137964. static int selectWindowRewriteExprCb(Walker *pWalker, Expr *pExpr){
  137965. struct WindowRewrite *p = pWalker->u.pRewrite;
  137966. Parse *pParse = pWalker->pParse;
  137967. /* If this function is being called from within a scalar sub-select
  137968. ** that used by the SELECT statement being processed, only process
  137969. ** TK_COLUMN expressions that refer to it (the outer SELECT). Do
  137970. ** not process aggregates or window functions at all, as they belong
  137971. ** to the scalar sub-select. */
  137972. if( p->pSubSelect ){
  137973. if( pExpr->op!=TK_COLUMN ){
  137974. return WRC_Continue;
  137975. }else{
  137976. int nSrc = p->pSrc->nSrc;
  137977. int i;
  137978. for(i=0; i<nSrc; i++){
  137979. if( pExpr->iTable==p->pSrc->a[i].iCursor ) break;
  137980. }
  137981. if( i==nSrc ) return WRC_Continue;
  137982. }
  137983. }
  137984. switch( pExpr->op ){
  137985. case TK_FUNCTION:
  137986. if( !ExprHasProperty(pExpr, EP_WinFunc) ){
  137987. break;
  137988. }else{
  137989. Window *pWin;
  137990. for(pWin=p->pWin; pWin; pWin=pWin->pNextWin){
  137991. if( pExpr->y.pWin==pWin ){
  137992. assert( pWin->pOwner==pExpr );
  137993. return WRC_Prune;
  137994. }
  137995. }
  137996. }
  137997. /* Fall through. */
  137998. case TK_AGG_FUNCTION:
  137999. case TK_COLUMN: {
  138000. Expr *pDup = sqlite3ExprDup(pParse->db, pExpr, 0);
  138001. p->pSub = sqlite3ExprListAppend(pParse, p->pSub, pDup);
  138002. if( p->pSub ){
  138003. assert( ExprHasProperty(pExpr, EP_Static)==0 );
  138004. ExprSetProperty(pExpr, EP_Static);
  138005. sqlite3ExprDelete(pParse->db, pExpr);
  138006. ExprClearProperty(pExpr, EP_Static);
  138007. memset(pExpr, 0, sizeof(Expr));
  138008. pExpr->op = TK_COLUMN;
  138009. pExpr->iColumn = p->pSub->nExpr-1;
  138010. pExpr->iTable = p->pWin->iEphCsr;
  138011. pExpr->y.pTab = p->pTab;
  138012. }
  138013. break;
  138014. }
  138015. default: /* no-op */
  138016. break;
  138017. }
  138018. return WRC_Continue;
  138019. }
  138020. static int selectWindowRewriteSelectCb(Walker *pWalker, Select *pSelect){
  138021. struct WindowRewrite *p = pWalker->u.pRewrite;
  138022. Select *pSave = p->pSubSelect;
  138023. if( pSave==pSelect ){
  138024. return WRC_Continue;
  138025. }else{
  138026. p->pSubSelect = pSelect;
  138027. sqlite3WalkSelect(pWalker, pSelect);
  138028. p->pSubSelect = pSave;
  138029. }
  138030. return WRC_Prune;
  138031. }
  138032. /*
  138033. ** Iterate through each expression in expression-list pEList. For each:
  138034. **
  138035. ** * TK_COLUMN,
  138036. ** * aggregate function, or
  138037. ** * window function with a Window object that is not a member of the
  138038. ** Window list passed as the second argument (pWin).
  138039. **
  138040. ** Append the node to output expression-list (*ppSub). And replace it
  138041. ** with a TK_COLUMN that reads the (N-1)th element of table
  138042. ** pWin->iEphCsr, where N is the number of elements in (*ppSub) after
  138043. ** appending the new one.
  138044. */
  138045. static void selectWindowRewriteEList(
  138046. Parse *pParse,
  138047. Window *pWin,
  138048. SrcList *pSrc,
  138049. ExprList *pEList, /* Rewrite expressions in this list */
  138050. Table *pTab,
  138051. ExprList **ppSub /* IN/OUT: Sub-select expression-list */
  138052. ){
  138053. Walker sWalker;
  138054. WindowRewrite sRewrite;
  138055. memset(&sWalker, 0, sizeof(Walker));
  138056. memset(&sRewrite, 0, sizeof(WindowRewrite));
  138057. sRewrite.pSub = *ppSub;
  138058. sRewrite.pWin = pWin;
  138059. sRewrite.pSrc = pSrc;
  138060. sRewrite.pTab = pTab;
  138061. sWalker.pParse = pParse;
  138062. sWalker.xExprCallback = selectWindowRewriteExprCb;
  138063. sWalker.xSelectCallback = selectWindowRewriteSelectCb;
  138064. sWalker.u.pRewrite = &sRewrite;
  138065. (void)sqlite3WalkExprList(&sWalker, pEList);
  138066. *ppSub = sRewrite.pSub;
  138067. }
  138068. /*
  138069. ** Append a copy of each expression in expression-list pAppend to
  138070. ** expression list pList. Return a pointer to the result list.
  138071. */
  138072. static ExprList *exprListAppendList(
  138073. Parse *pParse, /* Parsing context */
  138074. ExprList *pList, /* List to which to append. Might be NULL */
  138075. ExprList *pAppend, /* List of values to append. Might be NULL */
  138076. int bIntToNull
  138077. ){
  138078. if( pAppend ){
  138079. int i;
  138080. int nInit = pList ? pList->nExpr : 0;
  138081. for(i=0; i<pAppend->nExpr; i++){
  138082. Expr *pDup = sqlite3ExprDup(pParse->db, pAppend->a[i].pExpr, 0);
  138083. if( bIntToNull && pDup && pDup->op==TK_INTEGER ){
  138084. pDup->op = TK_NULL;
  138085. pDup->flags &= ~(EP_IntValue|EP_IsTrue|EP_IsFalse);
  138086. }
  138087. pList = sqlite3ExprListAppend(pParse, pList, pDup);
  138088. if( pList ) pList->a[nInit+i].sortOrder = pAppend->a[i].sortOrder;
  138089. }
  138090. }
  138091. return pList;
  138092. }
  138093. /*
  138094. ** If the SELECT statement passed as the second argument does not invoke
  138095. ** any SQL window functions, this function is a no-op. Otherwise, it
  138096. ** rewrites the SELECT statement so that window function xStep functions
  138097. ** are invoked in the correct order as described under "SELECT REWRITING"
  138098. ** at the top of this file.
  138099. */
  138100. SQLITE_PRIVATE int sqlite3WindowRewrite(Parse *pParse, Select *p){
  138101. int rc = SQLITE_OK;
  138102. if( p->pWin && p->pPrior==0 ){
  138103. Vdbe *v = sqlite3GetVdbe(pParse);
  138104. sqlite3 *db = pParse->db;
  138105. Select *pSub = 0; /* The subquery */
  138106. SrcList *pSrc = p->pSrc;
  138107. Expr *pWhere = p->pWhere;
  138108. ExprList *pGroupBy = p->pGroupBy;
  138109. Expr *pHaving = p->pHaving;
  138110. ExprList *pSort = 0;
  138111. ExprList *pSublist = 0; /* Expression list for sub-query */
  138112. Window *pMWin = p->pWin; /* Master window object */
  138113. Window *pWin; /* Window object iterator */
  138114. Table *pTab;
  138115. pTab = sqlite3DbMallocZero(db, sizeof(Table));
  138116. if( pTab==0 ){
  138117. return SQLITE_NOMEM;
  138118. }
  138119. p->pSrc = 0;
  138120. p->pWhere = 0;
  138121. p->pGroupBy = 0;
  138122. p->pHaving = 0;
  138123. p->selFlags &= ~SF_Aggregate;
  138124. /* Create the ORDER BY clause for the sub-select. This is the concatenation
  138125. ** of the window PARTITION and ORDER BY clauses. Then, if this makes it
  138126. ** redundant, remove the ORDER BY from the parent SELECT. */
  138127. pSort = sqlite3ExprListDup(db, pMWin->pPartition, 0);
  138128. pSort = exprListAppendList(pParse, pSort, pMWin->pOrderBy, 1);
  138129. if( pSort && p->pOrderBy ){
  138130. if( sqlite3ExprListCompare(pSort, p->pOrderBy, -1)==0 ){
  138131. sqlite3ExprListDelete(db, p->pOrderBy);
  138132. p->pOrderBy = 0;
  138133. }
  138134. }
  138135. /* Assign a cursor number for the ephemeral table used to buffer rows.
  138136. ** The OpenEphemeral instruction is coded later, after it is known how
  138137. ** many columns the table will have. */
  138138. pMWin->iEphCsr = pParse->nTab++;
  138139. pParse->nTab += 3;
  138140. selectWindowRewriteEList(pParse, pMWin, pSrc, p->pEList, pTab, &pSublist);
  138141. selectWindowRewriteEList(pParse, pMWin, pSrc, p->pOrderBy, pTab, &pSublist);
  138142. pMWin->nBufferCol = (pSublist ? pSublist->nExpr : 0);
  138143. /* Append the PARTITION BY and ORDER BY expressions to the to the
  138144. ** sub-select expression list. They are required to figure out where
  138145. ** boundaries for partitions and sets of peer rows lie. */
  138146. pSublist = exprListAppendList(pParse, pSublist, pMWin->pPartition, 0);
  138147. pSublist = exprListAppendList(pParse, pSublist, pMWin->pOrderBy, 0);
  138148. /* Append the arguments passed to each window function to the
  138149. ** sub-select expression list. Also allocate two registers for each
  138150. ** window function - one for the accumulator, another for interim
  138151. ** results. */
  138152. for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
  138153. pWin->iArgCol = (pSublist ? pSublist->nExpr : 0);
  138154. pSublist = exprListAppendList(pParse, pSublist, pWin->pOwner->x.pList, 0);
  138155. if( pWin->pFilter ){
  138156. Expr *pFilter = sqlite3ExprDup(db, pWin->pFilter, 0);
  138157. pSublist = sqlite3ExprListAppend(pParse, pSublist, pFilter);
  138158. }
  138159. pWin->regAccum = ++pParse->nMem;
  138160. pWin->regResult = ++pParse->nMem;
  138161. sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
  138162. }
  138163. /* If there is no ORDER BY or PARTITION BY clause, and the window
  138164. ** function accepts zero arguments, and there are no other columns
  138165. ** selected (e.g. "SELECT row_number() OVER () FROM t1"), it is possible
  138166. ** that pSublist is still NULL here. Add a constant expression here to
  138167. ** keep everything legal in this case.
  138168. */
  138169. if( pSublist==0 ){
  138170. pSublist = sqlite3ExprListAppend(pParse, 0,
  138171. sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0)
  138172. );
  138173. }
  138174. pSub = sqlite3SelectNew(
  138175. pParse, pSublist, pSrc, pWhere, pGroupBy, pHaving, pSort, 0, 0
  138176. );
  138177. p->pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0);
  138178. if( p->pSrc ){
  138179. Table *pTab2;
  138180. p->pSrc->a[0].pSelect = pSub;
  138181. sqlite3SrcListAssignCursors(pParse, p->pSrc);
  138182. pSub->selFlags |= SF_Expanded;
  138183. pTab2 = sqlite3ResultSetOfSelect(pParse, pSub);
  138184. if( pTab2==0 ){
  138185. rc = SQLITE_NOMEM;
  138186. }else{
  138187. memcpy(pTab, pTab2, sizeof(Table));
  138188. pTab->tabFlags |= TF_Ephemeral;
  138189. p->pSrc->a[0].pTab = pTab;
  138190. pTab = pTab2;
  138191. }
  138192. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pMWin->iEphCsr, pSublist->nExpr);
  138193. sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+1, pMWin->iEphCsr);
  138194. sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+2, pMWin->iEphCsr);
  138195. sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+3, pMWin->iEphCsr);
  138196. }else{
  138197. sqlite3SelectDelete(db, pSub);
  138198. }
  138199. if( db->mallocFailed ) rc = SQLITE_NOMEM;
  138200. sqlite3DbFree(db, pTab);
  138201. }
  138202. return rc;
  138203. }
  138204. /*
  138205. ** Free the Window object passed as the second argument.
  138206. */
  138207. SQLITE_PRIVATE void sqlite3WindowDelete(sqlite3 *db, Window *p){
  138208. if( p ){
  138209. sqlite3ExprDelete(db, p->pFilter);
  138210. sqlite3ExprListDelete(db, p->pPartition);
  138211. sqlite3ExprListDelete(db, p->pOrderBy);
  138212. sqlite3ExprDelete(db, p->pEnd);
  138213. sqlite3ExprDelete(db, p->pStart);
  138214. sqlite3DbFree(db, p->zName);
  138215. sqlite3DbFree(db, p->zBase);
  138216. sqlite3DbFree(db, p);
  138217. }
  138218. }
  138219. /*
  138220. ** Free the linked list of Window objects starting at the second argument.
  138221. */
  138222. SQLITE_PRIVATE void sqlite3WindowListDelete(sqlite3 *db, Window *p){
  138223. while( p ){
  138224. Window *pNext = p->pNextWin;
  138225. sqlite3WindowDelete(db, p);
  138226. p = pNext;
  138227. }
  138228. }
  138229. /*
  138230. ** The argument expression is an PRECEDING or FOLLOWING offset. The
  138231. ** value should be a non-negative integer. If the value is not a
  138232. ** constant, change it to NULL. The fact that it is then a non-negative
  138233. ** integer will be caught later. But it is important not to leave
  138234. ** variable values in the expression tree.
  138235. */
  138236. static Expr *sqlite3WindowOffsetExpr(Parse *pParse, Expr *pExpr){
  138237. if( 0==sqlite3ExprIsConstant(pExpr) ){
  138238. if( IN_RENAME_OBJECT ) sqlite3RenameExprUnmap(pParse, pExpr);
  138239. sqlite3ExprDelete(pParse->db, pExpr);
  138240. pExpr = sqlite3ExprAlloc(pParse->db, TK_NULL, 0, 0);
  138241. }
  138242. return pExpr;
  138243. }
  138244. /*
  138245. ** Allocate and return a new Window object describing a Window Definition.
  138246. */
  138247. SQLITE_PRIVATE Window *sqlite3WindowAlloc(
  138248. Parse *pParse, /* Parsing context */
  138249. int eType, /* Frame type. TK_RANGE, TK_ROWS, TK_GROUPS, or 0 */
  138250. int eStart, /* Start type: CURRENT, PRECEDING, FOLLOWING, UNBOUNDED */
  138251. Expr *pStart, /* Start window size if TK_PRECEDING or FOLLOWING */
  138252. int eEnd, /* End type: CURRENT, FOLLOWING, TK_UNBOUNDED, PRECEDING */
  138253. Expr *pEnd, /* End window size if TK_FOLLOWING or PRECEDING */
  138254. u8 eExclude /* EXCLUDE clause */
  138255. ){
  138256. Window *pWin = 0;
  138257. int bImplicitFrame = 0;
  138258. /* Parser assures the following: */
  138259. assert( eType==0 || eType==TK_RANGE || eType==TK_ROWS || eType==TK_GROUPS );
  138260. assert( eStart==TK_CURRENT || eStart==TK_PRECEDING
  138261. || eStart==TK_UNBOUNDED || eStart==TK_FOLLOWING );
  138262. assert( eEnd==TK_CURRENT || eEnd==TK_FOLLOWING
  138263. || eEnd==TK_UNBOUNDED || eEnd==TK_PRECEDING );
  138264. assert( (eStart==TK_PRECEDING || eStart==TK_FOLLOWING)==(pStart!=0) );
  138265. assert( (eEnd==TK_FOLLOWING || eEnd==TK_PRECEDING)==(pEnd!=0) );
  138266. if( eType==0 ){
  138267. bImplicitFrame = 1;
  138268. eType = TK_RANGE;
  138269. }
  138270. /* Additionally, the
  138271. ** starting boundary type may not occur earlier in the following list than
  138272. ** the ending boundary type:
  138273. **
  138274. ** UNBOUNDED PRECEDING
  138275. ** <expr> PRECEDING
  138276. ** CURRENT ROW
  138277. ** <expr> FOLLOWING
  138278. ** UNBOUNDED FOLLOWING
  138279. **
  138280. ** The parser ensures that "UNBOUNDED PRECEDING" cannot be used as an ending
  138281. ** boundary, and than "UNBOUNDED FOLLOWING" cannot be used as a starting
  138282. ** frame boundary.
  138283. */
  138284. if( (eStart==TK_CURRENT && eEnd==TK_PRECEDING)
  138285. || (eStart==TK_FOLLOWING && (eEnd==TK_PRECEDING || eEnd==TK_CURRENT))
  138286. ){
  138287. sqlite3ErrorMsg(pParse, "unsupported frame specification");
  138288. goto windowAllocErr;
  138289. }
  138290. pWin = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window));
  138291. if( pWin==0 ) goto windowAllocErr;
  138292. pWin->eFrmType = eType;
  138293. pWin->eStart = eStart;
  138294. pWin->eEnd = eEnd;
  138295. if( eExclude==0 && OptimizationDisabled(pParse->db, SQLITE_WindowFunc) ){
  138296. eExclude = TK_NO;
  138297. }
  138298. pWin->eExclude = eExclude;
  138299. pWin->bImplicitFrame = bImplicitFrame;
  138300. pWin->pEnd = sqlite3WindowOffsetExpr(pParse, pEnd);
  138301. pWin->pStart = sqlite3WindowOffsetExpr(pParse, pStart);
  138302. return pWin;
  138303. windowAllocErr:
  138304. sqlite3ExprDelete(pParse->db, pEnd);
  138305. sqlite3ExprDelete(pParse->db, pStart);
  138306. return 0;
  138307. }
  138308. /*
  138309. ** Attach PARTITION and ORDER BY clauses pPartition and pOrderBy to window
  138310. ** pWin. Also, if parameter pBase is not NULL, set pWin->zBase to the
  138311. ** equivalent nul-terminated string.
  138312. */
  138313. SQLITE_PRIVATE Window *sqlite3WindowAssemble(
  138314. Parse *pParse,
  138315. Window *pWin,
  138316. ExprList *pPartition,
  138317. ExprList *pOrderBy,
  138318. Token *pBase
  138319. ){
  138320. if( pWin ){
  138321. pWin->pPartition = pPartition;
  138322. pWin->pOrderBy = pOrderBy;
  138323. if( pBase ){
  138324. pWin->zBase = sqlite3DbStrNDup(pParse->db, pBase->z, pBase->n);
  138325. }
  138326. }else{
  138327. sqlite3ExprListDelete(pParse->db, pPartition);
  138328. sqlite3ExprListDelete(pParse->db, pOrderBy);
  138329. }
  138330. return pWin;
  138331. }
  138332. /*
  138333. ** Window *pWin has just been created from a WINDOW clause. Tokne pBase
  138334. ** is the base window. Earlier windows from the same WINDOW clause are
  138335. ** stored in the linked list starting at pWin->pNextWin. This function
  138336. ** either updates *pWin according to the base specification, or else
  138337. ** leaves an error in pParse.
  138338. */
  138339. SQLITE_PRIVATE void sqlite3WindowChain(Parse *pParse, Window *pWin, Window *pList){
  138340. if( pWin->zBase ){
  138341. sqlite3 *db = pParse->db;
  138342. Window *pExist = windowFind(pParse, pList, pWin->zBase);
  138343. if( pExist ){
  138344. const char *zErr = 0;
  138345. /* Check for errors */
  138346. if( pWin->pPartition ){
  138347. zErr = "PARTITION clause";
  138348. }else if( pExist->pOrderBy && pWin->pOrderBy ){
  138349. zErr = "ORDER BY clause";
  138350. }else if( pExist->bImplicitFrame==0 ){
  138351. zErr = "frame specification";
  138352. }
  138353. if( zErr ){
  138354. sqlite3ErrorMsg(pParse,
  138355. "cannot override %s of window: %s", zErr, pWin->zBase
  138356. );
  138357. }else{
  138358. pWin->pPartition = sqlite3ExprListDup(db, pExist->pPartition, 0);
  138359. if( pExist->pOrderBy ){
  138360. assert( pWin->pOrderBy==0 );
  138361. pWin->pOrderBy = sqlite3ExprListDup(db, pExist->pOrderBy, 0);
  138362. }
  138363. sqlite3DbFree(db, pWin->zBase);
  138364. pWin->zBase = 0;
  138365. }
  138366. }
  138367. }
  138368. }
  138369. /*
  138370. ** Attach window object pWin to expression p.
  138371. */
  138372. SQLITE_PRIVATE void sqlite3WindowAttach(Parse *pParse, Expr *p, Window *pWin){
  138373. if( p ){
  138374. assert( p->op==TK_FUNCTION );
  138375. /* This routine is only called for the parser. If pWin was not
  138376. ** allocated due to an OOM, then the parser would fail before ever
  138377. ** invoking this routine */
  138378. if( ALWAYS(pWin) ){
  138379. p->y.pWin = pWin;
  138380. ExprSetProperty(p, EP_WinFunc);
  138381. pWin->pOwner = p;
  138382. if( p->flags & EP_Distinct ){
  138383. sqlite3ErrorMsg(pParse,
  138384. "DISTINCT is not supported for window functions");
  138385. }
  138386. }
  138387. }else{
  138388. sqlite3WindowDelete(pParse->db, pWin);
  138389. }
  138390. }
  138391. /*
  138392. ** Return 0 if the two window objects are identical, or non-zero otherwise.
  138393. ** Identical window objects can be processed in a single scan.
  138394. */
  138395. SQLITE_PRIVATE int sqlite3WindowCompare(Parse *pParse, Window *p1, Window *p2){
  138396. if( p1->eFrmType!=p2->eFrmType ) return 1;
  138397. if( p1->eStart!=p2->eStart ) return 1;
  138398. if( p1->eEnd!=p2->eEnd ) return 1;
  138399. if( p1->eExclude!=p2->eExclude ) return 1;
  138400. if( sqlite3ExprCompare(pParse, p1->pStart, p2->pStart, -1) ) return 1;
  138401. if( sqlite3ExprCompare(pParse, p1->pEnd, p2->pEnd, -1) ) return 1;
  138402. if( sqlite3ExprListCompare(p1->pPartition, p2->pPartition, -1) ) return 1;
  138403. if( sqlite3ExprListCompare(p1->pOrderBy, p2->pOrderBy, -1) ) return 1;
  138404. return 0;
  138405. }
  138406. /*
  138407. ** This is called by code in select.c before it calls sqlite3WhereBegin()
  138408. ** to begin iterating through the sub-query results. It is used to allocate
  138409. ** and initialize registers and cursors used by sqlite3WindowCodeStep().
  138410. */
  138411. SQLITE_PRIVATE void sqlite3WindowCodeInit(Parse *pParse, Window *pMWin){
  138412. Window *pWin;
  138413. Vdbe *v = sqlite3GetVdbe(pParse);
  138414. /* Allocate registers to use for PARTITION BY values, if any. Initialize
  138415. ** said registers to NULL. */
  138416. if( pMWin->pPartition ){
  138417. int nExpr = pMWin->pPartition->nExpr;
  138418. pMWin->regPart = pParse->nMem+1;
  138419. pParse->nMem += nExpr;
  138420. sqlite3VdbeAddOp3(v, OP_Null, 0, pMWin->regPart, pMWin->regPart+nExpr-1);
  138421. }
  138422. pMWin->regOne = ++pParse->nMem;
  138423. sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regOne);
  138424. if( pMWin->eExclude ){
  138425. pMWin->regStartRowid = ++pParse->nMem;
  138426. pMWin->regEndRowid = ++pParse->nMem;
  138427. pMWin->csrApp = pParse->nTab++;
  138428. sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regStartRowid);
  138429. sqlite3VdbeAddOp2(v, OP_Integer, 0, pMWin->regEndRowid);
  138430. sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->csrApp, pMWin->iEphCsr);
  138431. return;
  138432. }
  138433. for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
  138434. FuncDef *p = pWin->pFunc;
  138435. if( (p->funcFlags & SQLITE_FUNC_MINMAX) && pWin->eStart!=TK_UNBOUNDED ){
  138436. /* The inline versions of min() and max() require a single ephemeral
  138437. ** table and 3 registers. The registers are used as follows:
  138438. **
  138439. ** regApp+0: slot to copy min()/max() argument to for MakeRecord
  138440. ** regApp+1: integer value used to ensure keys are unique
  138441. ** regApp+2: output of MakeRecord
  138442. */
  138443. ExprList *pList = pWin->pOwner->x.pList;
  138444. KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pList, 0, 0);
  138445. pWin->csrApp = pParse->nTab++;
  138446. pWin->regApp = pParse->nMem+1;
  138447. pParse->nMem += 3;
  138448. if( pKeyInfo && pWin->pFunc->zName[1]=='i' ){
  138449. assert( pKeyInfo->aSortOrder[0]==0 );
  138450. pKeyInfo->aSortOrder[0] = 1;
  138451. }
  138452. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pWin->csrApp, 2);
  138453. sqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO);
  138454. sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
  138455. }
  138456. else if( p->zName==nth_valueName || p->zName==first_valueName ){
  138457. /* Allocate two registers at pWin->regApp. These will be used to
  138458. ** store the start and end index of the current frame. */
  138459. pWin->regApp = pParse->nMem+1;
  138460. pWin->csrApp = pParse->nTab++;
  138461. pParse->nMem += 2;
  138462. sqlite3VdbeAddOp2(v, OP_OpenDup, pWin->csrApp, pMWin->iEphCsr);
  138463. }
  138464. else if( p->zName==leadName || p->zName==lagName ){
  138465. pWin->csrApp = pParse->nTab++;
  138466. sqlite3VdbeAddOp2(v, OP_OpenDup, pWin->csrApp, pMWin->iEphCsr);
  138467. }
  138468. }
  138469. }
  138470. #define WINDOW_STARTING_INT 0
  138471. #define WINDOW_ENDING_INT 1
  138472. #define WINDOW_NTH_VALUE_INT 2
  138473. #define WINDOW_STARTING_NUM 3
  138474. #define WINDOW_ENDING_NUM 4
  138475. /*
  138476. ** A "PRECEDING <expr>" (eCond==0) or "FOLLOWING <expr>" (eCond==1) or the
  138477. ** value of the second argument to nth_value() (eCond==2) has just been
  138478. ** evaluated and the result left in register reg. This function generates VM
  138479. ** code to check that the value is a non-negative integer and throws an
  138480. ** exception if it is not.
  138481. */
  138482. static void windowCheckValue(Parse *pParse, int reg, int eCond){
  138483. static const char *azErr[] = {
  138484. "frame starting offset must be a non-negative integer",
  138485. "frame ending offset must be a non-negative integer",
  138486. "second argument to nth_value must be a positive integer",
  138487. "frame starting offset must be a non-negative number",
  138488. "frame ending offset must be a non-negative number",
  138489. };
  138490. static int aOp[] = { OP_Ge, OP_Ge, OP_Gt, OP_Ge, OP_Ge };
  138491. Vdbe *v = sqlite3GetVdbe(pParse);
  138492. int regZero = sqlite3GetTempReg(pParse);
  138493. assert( eCond>=0 && eCond<ArraySize(azErr) );
  138494. sqlite3VdbeAddOp2(v, OP_Integer, 0, regZero);
  138495. if( eCond>=WINDOW_STARTING_NUM ){
  138496. int regString = sqlite3GetTempReg(pParse);
  138497. sqlite3VdbeAddOp4(v, OP_String8, 0, regString, 0, "", P4_STATIC);
  138498. sqlite3VdbeAddOp3(v, OP_Ge, regString, sqlite3VdbeCurrentAddr(v)+2, reg);
  138499. sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC|SQLITE_JUMPIFNULL);
  138500. VdbeCoverage(v);
  138501. assert( eCond==3 || eCond==4 );
  138502. VdbeCoverageIf(v, eCond==3);
  138503. VdbeCoverageIf(v, eCond==4);
  138504. }else{
  138505. sqlite3VdbeAddOp2(v, OP_MustBeInt, reg, sqlite3VdbeCurrentAddr(v)+2);
  138506. VdbeCoverage(v);
  138507. assert( eCond==0 || eCond==1 || eCond==2 );
  138508. VdbeCoverageIf(v, eCond==0);
  138509. VdbeCoverageIf(v, eCond==1);
  138510. VdbeCoverageIf(v, eCond==2);
  138511. }
  138512. sqlite3VdbeAddOp3(v, aOp[eCond], regZero, sqlite3VdbeCurrentAddr(v)+2, reg);
  138513. VdbeCoverageNeverNullIf(v, eCond==0); /* NULL case captured by */
  138514. VdbeCoverageNeverNullIf(v, eCond==1); /* the OP_MustBeInt */
  138515. VdbeCoverageNeverNullIf(v, eCond==2);
  138516. VdbeCoverageNeverNullIf(v, eCond==3); /* NULL case caught by */
  138517. VdbeCoverageNeverNullIf(v, eCond==4); /* the OP_Ge */
  138518. sqlite3MayAbort(pParse);
  138519. sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_ERROR, OE_Abort);
  138520. sqlite3VdbeAppendP4(v, (void*)azErr[eCond], P4_STATIC);
  138521. sqlite3ReleaseTempReg(pParse, regZero);
  138522. }
  138523. /*
  138524. ** Return the number of arguments passed to the window-function associated
  138525. ** with the object passed as the only argument to this function.
  138526. */
  138527. static int windowArgCount(Window *pWin){
  138528. ExprList *pList = pWin->pOwner->x.pList;
  138529. return (pList ? pList->nExpr : 0);
  138530. }
  138531. /*
  138532. ** Generate VM code to invoke either xStep() (if bInverse is 0) or
  138533. ** xInverse (if bInverse is non-zero) for each window function in the
  138534. ** linked list starting at pMWin. Or, for built-in window functions
  138535. ** that do not use the standard function API, generate the required
  138536. ** inline VM code.
  138537. **
  138538. ** If argument csr is greater than or equal to 0, then argument reg is
  138539. ** the first register in an array of registers guaranteed to be large
  138540. ** enough to hold the array of arguments for each function. In this case
  138541. ** the arguments are extracted from the current row of csr into the
  138542. ** array of registers before invoking OP_AggStep or OP_AggInverse
  138543. **
  138544. ** Or, if csr is less than zero, then the array of registers at reg is
  138545. ** already populated with all columns from the current row of the sub-query.
  138546. **
  138547. ** If argument regPartSize is non-zero, then it is a register containing the
  138548. ** number of rows in the current partition.
  138549. */
  138550. static void windowAggStep(
  138551. Parse *pParse,
  138552. Window *pMWin, /* Linked list of window functions */
  138553. int csr, /* Read arguments from this cursor */
  138554. int bInverse, /* True to invoke xInverse instead of xStep */
  138555. int reg /* Array of registers */
  138556. ){
  138557. Vdbe *v = sqlite3GetVdbe(pParse);
  138558. Window *pWin;
  138559. for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
  138560. FuncDef *pFunc = pWin->pFunc;
  138561. int regArg;
  138562. int nArg = windowArgCount(pWin);
  138563. int i;
  138564. for(i=0; i<nArg; i++){
  138565. if( i!=1 || pFunc->zName!=nth_valueName ){
  138566. sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol+i, reg+i);
  138567. }else{
  138568. sqlite3VdbeAddOp3(v, OP_Column, pMWin->iEphCsr, pWin->iArgCol+i, reg+i);
  138569. }
  138570. }
  138571. regArg = reg;
  138572. if( pMWin->regStartRowid==0
  138573. && (pFunc->funcFlags & SQLITE_FUNC_MINMAX)
  138574. && (pWin->eStart!=TK_UNBOUNDED)
  138575. ){
  138576. int addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regArg);
  138577. VdbeCoverage(v);
  138578. if( bInverse==0 ){
  138579. sqlite3VdbeAddOp2(v, OP_AddImm, pWin->regApp+1, 1);
  138580. sqlite3VdbeAddOp2(v, OP_SCopy, regArg, pWin->regApp);
  138581. sqlite3VdbeAddOp3(v, OP_MakeRecord, pWin->regApp, 2, pWin->regApp+2);
  138582. sqlite3VdbeAddOp2(v, OP_IdxInsert, pWin->csrApp, pWin->regApp+2);
  138583. }else{
  138584. sqlite3VdbeAddOp4Int(v, OP_SeekGE, pWin->csrApp, 0, regArg, 1);
  138585. VdbeCoverageNeverTaken(v);
  138586. sqlite3VdbeAddOp1(v, OP_Delete, pWin->csrApp);
  138587. sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
  138588. }
  138589. sqlite3VdbeJumpHere(v, addrIsNull);
  138590. }else if( pWin->regApp ){
  138591. assert( pFunc->zName==nth_valueName
  138592. || pFunc->zName==first_valueName
  138593. );
  138594. assert( bInverse==0 || bInverse==1 );
  138595. sqlite3VdbeAddOp2(v, OP_AddImm, pWin->regApp+1-bInverse, 1);
  138596. }else if( pFunc->xSFunc!=noopStepFunc ){
  138597. int addrIf = 0;
  138598. if( pWin->pFilter ){
  138599. int regTmp;
  138600. assert( nArg==0 || nArg==pWin->pOwner->x.pList->nExpr );
  138601. assert( nArg || pWin->pOwner->x.pList==0 );
  138602. regTmp = sqlite3GetTempReg(pParse);
  138603. sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol+nArg,regTmp);
  138604. addrIf = sqlite3VdbeAddOp3(v, OP_IfNot, regTmp, 0, 1);
  138605. VdbeCoverage(v);
  138606. sqlite3ReleaseTempReg(pParse, regTmp);
  138607. }
  138608. if( pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
  138609. CollSeq *pColl;
  138610. assert( nArg>0 );
  138611. pColl = sqlite3ExprNNCollSeq(pParse, pWin->pOwner->x.pList->a[0].pExpr);
  138612. sqlite3VdbeAddOp4(v, OP_CollSeq, 0,0,0, (const char*)pColl, P4_COLLSEQ);
  138613. }
  138614. sqlite3VdbeAddOp3(v, bInverse? OP_AggInverse : OP_AggStep,
  138615. bInverse, regArg, pWin->regAccum);
  138616. sqlite3VdbeAppendP4(v, pFunc, P4_FUNCDEF);
  138617. sqlite3VdbeChangeP5(v, (u8)nArg);
  138618. if( addrIf ) sqlite3VdbeJumpHere(v, addrIf);
  138619. }
  138620. }
  138621. }
  138622. typedef struct WindowCodeArg WindowCodeArg;
  138623. typedef struct WindowCsrAndReg WindowCsrAndReg;
  138624. struct WindowCsrAndReg {
  138625. int csr;
  138626. int reg;
  138627. };
  138628. struct WindowCodeArg {
  138629. Parse *pParse;
  138630. Window *pMWin;
  138631. Vdbe *pVdbe;
  138632. int regGosub;
  138633. int addrGosub;
  138634. int regArg;
  138635. int eDelete;
  138636. WindowCsrAndReg start;
  138637. WindowCsrAndReg current;
  138638. WindowCsrAndReg end;
  138639. };
  138640. /*
  138641. ** Values that may be passed as the second argument to windowCodeOp().
  138642. */
  138643. #define WINDOW_RETURN_ROW 1
  138644. #define WINDOW_AGGINVERSE 2
  138645. #define WINDOW_AGGSTEP 3
  138646. /*
  138647. ** Generate VM code to read the window frames peer values from cursor csr into
  138648. ** an array of registers starting at reg.
  138649. */
  138650. static void windowReadPeerValues(
  138651. WindowCodeArg *p,
  138652. int csr,
  138653. int reg
  138654. ){
  138655. Window *pMWin = p->pMWin;
  138656. ExprList *pOrderBy = pMWin->pOrderBy;
  138657. if( pOrderBy ){
  138658. Vdbe *v = sqlite3GetVdbe(p->pParse);
  138659. ExprList *pPart = pMWin->pPartition;
  138660. int iColOff = pMWin->nBufferCol + (pPart ? pPart->nExpr : 0);
  138661. int i;
  138662. for(i=0; i<pOrderBy->nExpr; i++){
  138663. sqlite3VdbeAddOp3(v, OP_Column, csr, iColOff+i, reg+i);
  138664. }
  138665. }
  138666. }
  138667. /*
  138668. ** Generate VM code to invoke either xValue() (bFin==0) or xFinalize()
  138669. ** (bFin==1) for each window function in the linked list starting at
  138670. ** pMWin. Or, for built-in window-functions that do not use the standard
  138671. ** API, generate the equivalent VM code.
  138672. */
  138673. static void windowAggFinal(WindowCodeArg *p, int bFin){
  138674. Parse *pParse = p->pParse;
  138675. Window *pMWin = p->pMWin;
  138676. Vdbe *v = sqlite3GetVdbe(pParse);
  138677. Window *pWin;
  138678. for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
  138679. if( pMWin->regStartRowid==0
  138680. && (pWin->pFunc->funcFlags & SQLITE_FUNC_MINMAX)
  138681. && (pWin->eStart!=TK_UNBOUNDED)
  138682. ){
  138683. sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
  138684. sqlite3VdbeAddOp1(v, OP_Last, pWin->csrApp);
  138685. VdbeCoverage(v);
  138686. sqlite3VdbeAddOp3(v, OP_Column, pWin->csrApp, 0, pWin->regResult);
  138687. sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
  138688. }else if( pWin->regApp ){
  138689. assert( pMWin->regStartRowid==0 );
  138690. }else{
  138691. int nArg = windowArgCount(pWin);
  138692. if( bFin ){
  138693. sqlite3VdbeAddOp2(v, OP_AggFinal, pWin->regAccum, nArg);
  138694. sqlite3VdbeAppendP4(v, pWin->pFunc, P4_FUNCDEF);
  138695. sqlite3VdbeAddOp2(v, OP_Copy, pWin->regAccum, pWin->regResult);
  138696. sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
  138697. }else{
  138698. sqlite3VdbeAddOp3(v, OP_AggValue,pWin->regAccum,nArg,pWin->regResult);
  138699. sqlite3VdbeAppendP4(v, pWin->pFunc, P4_FUNCDEF);
  138700. }
  138701. }
  138702. }
  138703. }
  138704. /*
  138705. ** Generate code to calculate the current values of all window functions in the
  138706. ** p->pMWin list by doing a full scan of the current window frame. Store the
  138707. ** results in the Window.regResult registers, ready to return the upper
  138708. ** layer.
  138709. */
  138710. static void windowFullScan(WindowCodeArg *p){
  138711. Window *pWin;
  138712. Parse *pParse = p->pParse;
  138713. Window *pMWin = p->pMWin;
  138714. Vdbe *v = p->pVdbe;
  138715. int regCRowid = 0; /* Current rowid value */
  138716. int regCPeer = 0; /* Current peer values */
  138717. int regRowid = 0; /* AggStep rowid value */
  138718. int regPeer = 0; /* AggStep peer values */
  138719. int nPeer;
  138720. int lblNext;
  138721. int lblBrk;
  138722. int addrNext;
  138723. int csr = pMWin->csrApp;
  138724. nPeer = (pMWin->pOrderBy ? pMWin->pOrderBy->nExpr : 0);
  138725. lblNext = sqlite3VdbeMakeLabel(pParse);
  138726. lblBrk = sqlite3VdbeMakeLabel(pParse);
  138727. regCRowid = sqlite3GetTempReg(pParse);
  138728. regRowid = sqlite3GetTempReg(pParse);
  138729. if( nPeer ){
  138730. regCPeer = sqlite3GetTempRange(pParse, nPeer);
  138731. regPeer = sqlite3GetTempRange(pParse, nPeer);
  138732. }
  138733. sqlite3VdbeAddOp2(v, OP_Rowid, pMWin->iEphCsr, regCRowid);
  138734. windowReadPeerValues(p, pMWin->iEphCsr, regCPeer);
  138735. for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
  138736. sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
  138737. }
  138738. sqlite3VdbeAddOp3(v, OP_SeekGE, csr, lblBrk, pMWin->regStartRowid);
  138739. VdbeCoverage(v);
  138740. addrNext = sqlite3VdbeCurrentAddr(v);
  138741. sqlite3VdbeAddOp2(v, OP_Rowid, csr, regRowid);
  138742. sqlite3VdbeAddOp3(v, OP_Gt, pMWin->regEndRowid, lblBrk, regRowid);
  138743. VdbeCoverageNeverNull(v);
  138744. if( pMWin->eExclude==TK_CURRENT ){
  138745. sqlite3VdbeAddOp3(v, OP_Eq, regCRowid, lblNext, regRowid);
  138746. VdbeCoverageNeverNull(v);
  138747. }else if( pMWin->eExclude!=TK_NO ){
  138748. int addr;
  138749. int addrEq = 0;
  138750. KeyInfo *pKeyInfo = 0;
  138751. if( pMWin->pOrderBy ){
  138752. pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pMWin->pOrderBy, 0, 0);
  138753. }
  138754. if( pMWin->eExclude==TK_TIES ){
  138755. addrEq = sqlite3VdbeAddOp3(v, OP_Eq, regCRowid, 0, regRowid);
  138756. VdbeCoverageNeverNull(v);
  138757. }
  138758. if( pKeyInfo ){
  138759. windowReadPeerValues(p, csr, regPeer);
  138760. sqlite3VdbeAddOp3(v, OP_Compare, regPeer, regCPeer, nPeer);
  138761. sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
  138762. addr = sqlite3VdbeCurrentAddr(v)+1;
  138763. sqlite3VdbeAddOp3(v, OP_Jump, addr, lblNext, addr);
  138764. VdbeCoverageEqNe(v);
  138765. }else{
  138766. sqlite3VdbeAddOp2(v, OP_Goto, 0, lblNext);
  138767. }
  138768. if( addrEq ) sqlite3VdbeJumpHere(v, addrEq);
  138769. }
  138770. windowAggStep(pParse, pMWin, csr, 0, p->regArg);
  138771. sqlite3VdbeResolveLabel(v, lblNext);
  138772. sqlite3VdbeAddOp2(v, OP_Next, csr, addrNext);
  138773. VdbeCoverage(v);
  138774. sqlite3VdbeJumpHere(v, addrNext-1);
  138775. sqlite3VdbeJumpHere(v, addrNext+1);
  138776. sqlite3ReleaseTempReg(pParse, regRowid);
  138777. sqlite3ReleaseTempReg(pParse, regCRowid);
  138778. if( nPeer ){
  138779. sqlite3ReleaseTempRange(pParse, regPeer, nPeer);
  138780. sqlite3ReleaseTempRange(pParse, regCPeer, nPeer);
  138781. }
  138782. windowAggFinal(p, 1);
  138783. }
  138784. /*
  138785. ** Invoke the sub-routine at regGosub (generated by code in select.c) to
  138786. ** return the current row of Window.iEphCsr. If all window functions are
  138787. ** aggregate window functions that use the standard API, a single
  138788. ** OP_Gosub instruction is all that this routine generates. Extra VM code
  138789. ** for per-row processing is only generated for the following built-in window
  138790. ** functions:
  138791. **
  138792. ** nth_value()
  138793. ** first_value()
  138794. ** lag()
  138795. ** lead()
  138796. */
  138797. static void windowReturnOneRow(WindowCodeArg *p){
  138798. Window *pMWin = p->pMWin;
  138799. Vdbe *v = p->pVdbe;
  138800. if( pMWin->regStartRowid ){
  138801. windowFullScan(p);
  138802. }else{
  138803. Parse *pParse = p->pParse;
  138804. Window *pWin;
  138805. for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
  138806. FuncDef *pFunc = pWin->pFunc;
  138807. if( pFunc->zName==nth_valueName
  138808. || pFunc->zName==first_valueName
  138809. ){
  138810. int csr = pWin->csrApp;
  138811. int lbl = sqlite3VdbeMakeLabel(pParse);
  138812. int tmpReg = sqlite3GetTempReg(pParse);
  138813. sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
  138814. if( pFunc->zName==nth_valueName ){
  138815. sqlite3VdbeAddOp3(v, OP_Column,pMWin->iEphCsr,pWin->iArgCol+1,tmpReg);
  138816. windowCheckValue(pParse, tmpReg, 2);
  138817. }else{
  138818. sqlite3VdbeAddOp2(v, OP_Integer, 1, tmpReg);
  138819. }
  138820. sqlite3VdbeAddOp3(v, OP_Add, tmpReg, pWin->regApp, tmpReg);
  138821. sqlite3VdbeAddOp3(v, OP_Gt, pWin->regApp+1, lbl, tmpReg);
  138822. VdbeCoverageNeverNull(v);
  138823. sqlite3VdbeAddOp3(v, OP_SeekRowid, csr, 0, tmpReg);
  138824. VdbeCoverageNeverTaken(v);
  138825. sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol, pWin->regResult);
  138826. sqlite3VdbeResolveLabel(v, lbl);
  138827. sqlite3ReleaseTempReg(pParse, tmpReg);
  138828. }
  138829. else if( pFunc->zName==leadName || pFunc->zName==lagName ){
  138830. int nArg = pWin->pOwner->x.pList->nExpr;
  138831. int csr = pWin->csrApp;
  138832. int lbl = sqlite3VdbeMakeLabel(pParse);
  138833. int tmpReg = sqlite3GetTempReg(pParse);
  138834. int iEph = pMWin->iEphCsr;
  138835. if( nArg<3 ){
  138836. sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
  138837. }else{
  138838. sqlite3VdbeAddOp3(v, OP_Column, iEph,pWin->iArgCol+2,pWin->regResult);
  138839. }
  138840. sqlite3VdbeAddOp2(v, OP_Rowid, iEph, tmpReg);
  138841. if( nArg<2 ){
  138842. int val = (pFunc->zName==leadName ? 1 : -1);
  138843. sqlite3VdbeAddOp2(v, OP_AddImm, tmpReg, val);
  138844. }else{
  138845. int op = (pFunc->zName==leadName ? OP_Add : OP_Subtract);
  138846. int tmpReg2 = sqlite3GetTempReg(pParse);
  138847. sqlite3VdbeAddOp3(v, OP_Column, iEph, pWin->iArgCol+1, tmpReg2);
  138848. sqlite3VdbeAddOp3(v, op, tmpReg2, tmpReg, tmpReg);
  138849. sqlite3ReleaseTempReg(pParse, tmpReg2);
  138850. }
  138851. sqlite3VdbeAddOp3(v, OP_SeekRowid, csr, lbl, tmpReg);
  138852. VdbeCoverage(v);
  138853. sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol, pWin->regResult);
  138854. sqlite3VdbeResolveLabel(v, lbl);
  138855. sqlite3ReleaseTempReg(pParse, tmpReg);
  138856. }
  138857. }
  138858. }
  138859. sqlite3VdbeAddOp2(v, OP_Gosub, p->regGosub, p->addrGosub);
  138860. }
  138861. /*
  138862. ** Generate code to set the accumulator register for each window function
  138863. ** in the linked list passed as the second argument to NULL. And perform
  138864. ** any equivalent initialization required by any built-in window functions
  138865. ** in the list.
  138866. */
  138867. static int windowInitAccum(Parse *pParse, Window *pMWin){
  138868. Vdbe *v = sqlite3GetVdbe(pParse);
  138869. int regArg;
  138870. int nArg = 0;
  138871. Window *pWin;
  138872. for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
  138873. FuncDef *pFunc = pWin->pFunc;
  138874. sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
  138875. nArg = MAX(nArg, windowArgCount(pWin));
  138876. if( pMWin->regStartRowid==0 ){
  138877. if( pFunc->zName==nth_valueName || pFunc->zName==first_valueName ){
  138878. sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp);
  138879. sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
  138880. }
  138881. if( (pFunc->funcFlags & SQLITE_FUNC_MINMAX) && pWin->csrApp ){
  138882. assert( pWin->eStart!=TK_UNBOUNDED );
  138883. sqlite3VdbeAddOp1(v, OP_ResetSorter, pWin->csrApp);
  138884. sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
  138885. }
  138886. }
  138887. }
  138888. regArg = pParse->nMem+1;
  138889. pParse->nMem += nArg;
  138890. return regArg;
  138891. }
  138892. /*
  138893. ** Return true if the current frame should be cached in the ephemeral table,
  138894. ** even if there are no xInverse() calls required.
  138895. */
  138896. static int windowCacheFrame(Window *pMWin){
  138897. Window *pWin;
  138898. if( pMWin->regStartRowid ) return 1;
  138899. for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
  138900. FuncDef *pFunc = pWin->pFunc;
  138901. if( (pFunc->zName==nth_valueName)
  138902. || (pFunc->zName==first_valueName)
  138903. || (pFunc->zName==leadName)
  138904. || (pFunc->zName==lagName)
  138905. ){
  138906. return 1;
  138907. }
  138908. }
  138909. return 0;
  138910. }
  138911. /*
  138912. ** regOld and regNew are each the first register in an array of size
  138913. ** pOrderBy->nExpr. This function generates code to compare the two
  138914. ** arrays of registers using the collation sequences and other comparison
  138915. ** parameters specified by pOrderBy.
  138916. **
  138917. ** If the two arrays are not equal, the contents of regNew is copied to
  138918. ** regOld and control falls through. Otherwise, if the contents of the arrays
  138919. ** are equal, an OP_Goto is executed. The address of the OP_Goto is returned.
  138920. */
  138921. static void windowIfNewPeer(
  138922. Parse *pParse,
  138923. ExprList *pOrderBy,
  138924. int regNew, /* First in array of new values */
  138925. int regOld, /* First in array of old values */
  138926. int addr /* Jump here */
  138927. ){
  138928. Vdbe *v = sqlite3GetVdbe(pParse);
  138929. if( pOrderBy ){
  138930. int nVal = pOrderBy->nExpr;
  138931. KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pOrderBy, 0, 0);
  138932. sqlite3VdbeAddOp3(v, OP_Compare, regOld, regNew, nVal);
  138933. sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
  138934. sqlite3VdbeAddOp3(v, OP_Jump,
  138935. sqlite3VdbeCurrentAddr(v)+1, addr, sqlite3VdbeCurrentAddr(v)+1
  138936. );
  138937. VdbeCoverageEqNe(v);
  138938. sqlite3VdbeAddOp3(v, OP_Copy, regNew, regOld, nVal-1);
  138939. }else{
  138940. sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
  138941. }
  138942. }
  138943. /*
  138944. ** This function is called as part of generating VM programs for RANGE
  138945. ** offset PRECEDING/FOLLOWING frame boundaries. Assuming "ASC" order for
  138946. ** the ORDER BY term in the window, it generates code equivalent to:
  138947. **
  138948. ** if( csr1.peerVal + regVal >= csr2.peerVal ) goto lbl;
  138949. **
  138950. ** A special type of arithmetic is used such that if csr.peerVal is not
  138951. ** a numeric type (real or integer), then the result of the addition is
  138952. ** a copy of csr1.peerVal.
  138953. */
  138954. static void windowCodeRangeTest(
  138955. WindowCodeArg *p,
  138956. int op, /* OP_Ge or OP_Gt */
  138957. int csr1,
  138958. int regVal,
  138959. int csr2,
  138960. int lbl
  138961. ){
  138962. Parse *pParse = p->pParse;
  138963. Vdbe *v = sqlite3GetVdbe(pParse);
  138964. int reg1 = sqlite3GetTempReg(pParse);
  138965. int reg2 = sqlite3GetTempReg(pParse);
  138966. int arith = OP_Add;
  138967. int addrGe;
  138968. int regString = ++pParse->nMem;
  138969. assert( op==OP_Ge || op==OP_Gt || op==OP_Le );
  138970. assert( p->pMWin->pOrderBy && p->pMWin->pOrderBy->nExpr==1 );
  138971. if( p->pMWin->pOrderBy->a[0].sortOrder ){
  138972. switch( op ){
  138973. case OP_Ge: op = OP_Le; break;
  138974. case OP_Gt: op = OP_Lt; break;
  138975. default: assert( op==OP_Le ); op = OP_Ge; break;
  138976. }
  138977. arith = OP_Subtract;
  138978. }
  138979. windowReadPeerValues(p, csr1, reg1);
  138980. windowReadPeerValues(p, csr2, reg2);
  138981. /* Check if the peer value for csr1 value is a text or blob by comparing
  138982. ** it to the smallest possible string - ''. If it is, jump over the
  138983. ** OP_Add or OP_Subtract operation and proceed directly to the comparison. */
  138984. sqlite3VdbeAddOp4(v, OP_String8, 0, regString, 0, "", P4_STATIC);
  138985. addrGe = sqlite3VdbeAddOp3(v, OP_Ge, regString, 0, reg1);
  138986. VdbeCoverage(v);
  138987. sqlite3VdbeAddOp3(v, arith, regVal, reg1, reg1);
  138988. sqlite3VdbeJumpHere(v, addrGe);
  138989. sqlite3VdbeAddOp3(v, op, reg2, lbl, reg1); VdbeCoverage(v);
  138990. sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
  138991. assert( op==OP_Ge || op==OP_Gt || op==OP_Lt || op==OP_Le );
  138992. testcase(op==OP_Ge); VdbeCoverageIf(v, op==OP_Ge);
  138993. testcase(op==OP_Lt); VdbeCoverageIf(v, op==OP_Lt);
  138994. testcase(op==OP_Le); VdbeCoverageIf(v, op==OP_Le);
  138995. testcase(op==OP_Gt); VdbeCoverageIf(v, op==OP_Gt);
  138996. sqlite3ReleaseTempReg(pParse, reg1);
  138997. sqlite3ReleaseTempReg(pParse, reg2);
  138998. }
  138999. /*
  139000. ** Helper function for sqlite3WindowCodeStep(). Each call to this function
  139001. ** generates VM code for a single RETURN_ROW, AGGSTEP or AGGINVERSE
  139002. ** operation. Refer to the header comment for sqlite3WindowCodeStep() for
  139003. ** details.
  139004. */
  139005. static int windowCodeOp(
  139006. WindowCodeArg *p, /* Context object */
  139007. int op, /* WINDOW_RETURN_ROW, AGGSTEP or AGGINVERSE */
  139008. int regCountdown, /* Register for OP_IfPos countdown */
  139009. int jumpOnEof /* Jump here if stepped cursor reaches EOF */
  139010. ){
  139011. int csr, reg;
  139012. Parse *pParse = p->pParse;
  139013. Window *pMWin = p->pMWin;
  139014. int ret = 0;
  139015. Vdbe *v = p->pVdbe;
  139016. int addrIf = 0;
  139017. int addrContinue = 0;
  139018. int addrGoto = 0;
  139019. int bPeer = (pMWin->eFrmType!=TK_ROWS);
  139020. int lblDone = sqlite3VdbeMakeLabel(pParse);
  139021. int addrNextRange = 0;
  139022. /* Special case - WINDOW_AGGINVERSE is always a no-op if the frame
  139023. ** starts with UNBOUNDED PRECEDING. */
  139024. if( op==WINDOW_AGGINVERSE && pMWin->eStart==TK_UNBOUNDED ){
  139025. assert( regCountdown==0 && jumpOnEof==0 );
  139026. return 0;
  139027. }
  139028. if( regCountdown>0 ){
  139029. if( pMWin->eFrmType==TK_RANGE ){
  139030. addrNextRange = sqlite3VdbeCurrentAddr(v);
  139031. assert( op==WINDOW_AGGINVERSE || op==WINDOW_AGGSTEP );
  139032. if( op==WINDOW_AGGINVERSE ){
  139033. if( pMWin->eStart==TK_FOLLOWING ){
  139034. windowCodeRangeTest(
  139035. p, OP_Le, p->current.csr, regCountdown, p->start.csr, lblDone
  139036. );
  139037. }else{
  139038. windowCodeRangeTest(
  139039. p, OP_Ge, p->start.csr, regCountdown, p->current.csr, lblDone
  139040. );
  139041. }
  139042. }else{
  139043. windowCodeRangeTest(
  139044. p, OP_Gt, p->end.csr, regCountdown, p->current.csr, lblDone
  139045. );
  139046. }
  139047. }else{
  139048. addrIf = sqlite3VdbeAddOp3(v, OP_IfPos, regCountdown, 0, 1);
  139049. VdbeCoverage(v);
  139050. }
  139051. }
  139052. if( op==WINDOW_RETURN_ROW && pMWin->regStartRowid==0 ){
  139053. windowAggFinal(p, 0);
  139054. }
  139055. addrContinue = sqlite3VdbeCurrentAddr(v);
  139056. switch( op ){
  139057. case WINDOW_RETURN_ROW:
  139058. csr = p->current.csr;
  139059. reg = p->current.reg;
  139060. windowReturnOneRow(p);
  139061. break;
  139062. case WINDOW_AGGINVERSE:
  139063. csr = p->start.csr;
  139064. reg = p->start.reg;
  139065. if( pMWin->regStartRowid ){
  139066. assert( pMWin->regEndRowid );
  139067. sqlite3VdbeAddOp2(v, OP_AddImm, pMWin->regStartRowid, 1);
  139068. }else{
  139069. windowAggStep(pParse, pMWin, csr, 1, p->regArg);
  139070. }
  139071. break;
  139072. default:
  139073. assert( op==WINDOW_AGGSTEP );
  139074. csr = p->end.csr;
  139075. reg = p->end.reg;
  139076. if( pMWin->regStartRowid ){
  139077. assert( pMWin->regEndRowid );
  139078. sqlite3VdbeAddOp2(v, OP_AddImm, pMWin->regEndRowid, 1);
  139079. }else{
  139080. windowAggStep(pParse, pMWin, csr, 0, p->regArg);
  139081. }
  139082. break;
  139083. }
  139084. if( op==p->eDelete ){
  139085. sqlite3VdbeAddOp1(v, OP_Delete, csr);
  139086. sqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION);
  139087. }
  139088. if( jumpOnEof ){
  139089. sqlite3VdbeAddOp2(v, OP_Next, csr, sqlite3VdbeCurrentAddr(v)+2);
  139090. VdbeCoverage(v);
  139091. ret = sqlite3VdbeAddOp0(v, OP_Goto);
  139092. }else{
  139093. sqlite3VdbeAddOp2(v, OP_Next, csr, sqlite3VdbeCurrentAddr(v)+1+bPeer);
  139094. VdbeCoverage(v);
  139095. if( bPeer ){
  139096. addrGoto = sqlite3VdbeAddOp0(v, OP_Goto);
  139097. }
  139098. }
  139099. if( bPeer ){
  139100. int nReg = (pMWin->pOrderBy ? pMWin->pOrderBy->nExpr : 0);
  139101. int regTmp = (nReg ? sqlite3GetTempRange(pParse, nReg) : 0);
  139102. windowReadPeerValues(p, csr, regTmp);
  139103. windowIfNewPeer(pParse, pMWin->pOrderBy, regTmp, reg, addrContinue);
  139104. sqlite3ReleaseTempRange(pParse, regTmp, nReg);
  139105. }
  139106. if( addrNextRange ){
  139107. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrNextRange);
  139108. }
  139109. sqlite3VdbeResolveLabel(v, lblDone);
  139110. if( addrGoto ) sqlite3VdbeJumpHere(v, addrGoto);
  139111. if( addrIf ) sqlite3VdbeJumpHere(v, addrIf);
  139112. return ret;
  139113. }
  139114. /*
  139115. ** Allocate and return a duplicate of the Window object indicated by the
  139116. ** third argument. Set the Window.pOwner field of the new object to
  139117. ** pOwner.
  139118. */
  139119. SQLITE_PRIVATE Window *sqlite3WindowDup(sqlite3 *db, Expr *pOwner, Window *p){
  139120. Window *pNew = 0;
  139121. if( ALWAYS(p) ){
  139122. pNew = sqlite3DbMallocZero(db, sizeof(Window));
  139123. if( pNew ){
  139124. pNew->zName = sqlite3DbStrDup(db, p->zName);
  139125. pNew->pFilter = sqlite3ExprDup(db, p->pFilter, 0);
  139126. pNew->pFunc = p->pFunc;
  139127. pNew->pPartition = sqlite3ExprListDup(db, p->pPartition, 0);
  139128. pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, 0);
  139129. pNew->eFrmType = p->eFrmType;
  139130. pNew->eEnd = p->eEnd;
  139131. pNew->eStart = p->eStart;
  139132. pNew->eExclude = p->eExclude;
  139133. pNew->pStart = sqlite3ExprDup(db, p->pStart, 0);
  139134. pNew->pEnd = sqlite3ExprDup(db, p->pEnd, 0);
  139135. pNew->pOwner = pOwner;
  139136. }
  139137. }
  139138. return pNew;
  139139. }
  139140. /*
  139141. ** Return a copy of the linked list of Window objects passed as the
  139142. ** second argument.
  139143. */
  139144. SQLITE_PRIVATE Window *sqlite3WindowListDup(sqlite3 *db, Window *p){
  139145. Window *pWin;
  139146. Window *pRet = 0;
  139147. Window **pp = &pRet;
  139148. for(pWin=p; pWin; pWin=pWin->pNextWin){
  139149. *pp = sqlite3WindowDup(db, 0, pWin);
  139150. if( *pp==0 ) break;
  139151. pp = &((*pp)->pNextWin);
  139152. }
  139153. return pRet;
  139154. }
  139155. /*
  139156. ** Return true if it can be determined at compile time that expression
  139157. ** pExpr evaluates to a value that, when cast to an integer, is greater
  139158. ** than zero. False otherwise.
  139159. **
  139160. ** If an OOM error occurs, this function sets the Parse.db.mallocFailed
  139161. ** flag and returns zero.
  139162. */
  139163. static int windowExprGtZero(Parse *pParse, Expr *pExpr){
  139164. int ret = 0;
  139165. sqlite3 *db = pParse->db;
  139166. sqlite3_value *pVal = 0;
  139167. sqlite3ValueFromExpr(db, pExpr, db->enc, SQLITE_AFF_NUMERIC, &pVal);
  139168. if( pVal && sqlite3_value_int(pVal)>0 ){
  139169. ret = 1;
  139170. }
  139171. sqlite3ValueFree(pVal);
  139172. return ret;
  139173. }
  139174. /*
  139175. ** sqlite3WhereBegin() has already been called for the SELECT statement
  139176. ** passed as the second argument when this function is invoked. It generates
  139177. ** code to populate the Window.regResult register for each window function
  139178. ** and invoke the sub-routine at instruction addrGosub once for each row.
  139179. ** sqlite3WhereEnd() is always called before returning.
  139180. **
  139181. ** This function handles several different types of window frames, which
  139182. ** require slightly different processing. The following pseudo code is
  139183. ** used to implement window frames of the form:
  139184. **
  139185. ** ROWS BETWEEN <expr1> PRECEDING AND <expr2> FOLLOWING
  139186. **
  139187. ** Other window frame types use variants of the following:
  139188. **
  139189. ** ... loop started by sqlite3WhereBegin() ...
  139190. ** if( new partition ){
  139191. ** Gosub flush
  139192. ** }
  139193. ** Insert new row into eph table.
  139194. **
  139195. ** if( first row of partition ){
  139196. ** // Rewind three cursors, all open on the eph table.
  139197. ** Rewind(csrEnd);
  139198. ** Rewind(csrStart);
  139199. ** Rewind(csrCurrent);
  139200. **
  139201. ** regEnd = <expr2> // FOLLOWING expression
  139202. ** regStart = <expr1> // PRECEDING expression
  139203. ** }else{
  139204. ** // First time this branch is taken, the eph table contains two
  139205. ** // rows. The first row in the partition, which all three cursors
  139206. ** // currently point to, and the following row.
  139207. ** AGGSTEP
  139208. ** if( (regEnd--)<=0 ){
  139209. ** RETURN_ROW
  139210. ** if( (regStart--)<=0 ){
  139211. ** AGGINVERSE
  139212. ** }
  139213. ** }
  139214. ** }
  139215. ** }
  139216. ** flush:
  139217. ** AGGSTEP
  139218. ** while( 1 ){
  139219. ** RETURN ROW
  139220. ** if( csrCurrent is EOF ) break;
  139221. ** if( (regStart--)<=0 ){
  139222. ** AggInverse(csrStart)
  139223. ** Next(csrStart)
  139224. ** }
  139225. ** }
  139226. **
  139227. ** The pseudo-code above uses the following shorthand:
  139228. **
  139229. ** AGGSTEP: invoke the aggregate xStep() function for each window function
  139230. ** with arguments read from the current row of cursor csrEnd, then
  139231. ** step cursor csrEnd forward one row (i.e. sqlite3BtreeNext()).
  139232. **
  139233. ** RETURN_ROW: return a row to the caller based on the contents of the
  139234. ** current row of csrCurrent and the current state of all
  139235. ** aggregates. Then step cursor csrCurrent forward one row.
  139236. **
  139237. ** AGGINVERSE: invoke the aggregate xInverse() function for each window
  139238. ** functions with arguments read from the current row of cursor
  139239. ** csrStart. Then step csrStart forward one row.
  139240. **
  139241. ** There are two other ROWS window frames that are handled significantly
  139242. ** differently from the above - "BETWEEN <expr> PRECEDING AND <expr> PRECEDING"
  139243. ** and "BETWEEN <expr> FOLLOWING AND <expr> FOLLOWING". These are special
  139244. ** cases because they change the order in which the three cursors (csrStart,
  139245. ** csrCurrent and csrEnd) iterate through the ephemeral table. Cases that
  139246. ** use UNBOUNDED or CURRENT ROW are much simpler variations on one of these
  139247. ** three.
  139248. **
  139249. ** ROWS BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING
  139250. **
  139251. ** ... loop started by sqlite3WhereBegin() ...
  139252. ** if( new partition ){
  139253. ** Gosub flush
  139254. ** }
  139255. ** Insert new row into eph table.
  139256. ** if( first row of partition ){
  139257. ** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
  139258. ** regEnd = <expr2>
  139259. ** regStart = <expr1>
  139260. ** }else{
  139261. ** if( (regEnd--)<=0 ){
  139262. ** AGGSTEP
  139263. ** }
  139264. ** RETURN_ROW
  139265. ** if( (regStart--)<=0 ){
  139266. ** AGGINVERSE
  139267. ** }
  139268. ** }
  139269. ** }
  139270. ** flush:
  139271. ** if( (regEnd--)<=0 ){
  139272. ** AGGSTEP
  139273. ** }
  139274. ** RETURN_ROW
  139275. **
  139276. **
  139277. ** ROWS BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING
  139278. **
  139279. ** ... loop started by sqlite3WhereBegin() ...
  139280. ** if( new partition ){
  139281. ** Gosub flush
  139282. ** }
  139283. ** Insert new row into eph table.
  139284. ** if( first row of partition ){
  139285. ** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
  139286. ** regEnd = <expr2>
  139287. ** regStart = regEnd - <expr1>
  139288. ** }else{
  139289. ** AGGSTEP
  139290. ** if( (regEnd--)<=0 ){
  139291. ** RETURN_ROW
  139292. ** }
  139293. ** if( (regStart--)<=0 ){
  139294. ** AGGINVERSE
  139295. ** }
  139296. ** }
  139297. ** }
  139298. ** flush:
  139299. ** AGGSTEP
  139300. ** while( 1 ){
  139301. ** if( (regEnd--)<=0 ){
  139302. ** RETURN_ROW
  139303. ** if( eof ) break;
  139304. ** }
  139305. ** if( (regStart--)<=0 ){
  139306. ** AGGINVERSE
  139307. ** if( eof ) break
  139308. ** }
  139309. ** }
  139310. ** while( !eof csrCurrent ){
  139311. ** RETURN_ROW
  139312. ** }
  139313. **
  139314. ** For the most part, the patterns above are adapted to support UNBOUNDED by
  139315. ** assuming that it is equivalent to "infinity PRECEDING/FOLLOWING" and
  139316. ** CURRENT ROW by assuming that it is equivilent to "0 PRECEDING/FOLLOWING".
  139317. ** This is optimized of course - branches that will never be taken and
  139318. ** conditions that are always true are omitted from the VM code. The only
  139319. ** exceptional case is:
  139320. **
  139321. ** ROWS BETWEEN <expr1> FOLLOWING AND UNBOUNDED FOLLOWING
  139322. **
  139323. ** ... loop started by sqlite3WhereBegin() ...
  139324. ** if( new partition ){
  139325. ** Gosub flush
  139326. ** }
  139327. ** Insert new row into eph table.
  139328. ** if( first row of partition ){
  139329. ** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
  139330. ** regStart = <expr1>
  139331. ** }else{
  139332. ** AGGSTEP
  139333. ** }
  139334. ** }
  139335. ** flush:
  139336. ** AGGSTEP
  139337. ** while( 1 ){
  139338. ** if( (regStart--)<=0 ){
  139339. ** AGGINVERSE
  139340. ** if( eof ) break
  139341. ** }
  139342. ** RETURN_ROW
  139343. ** }
  139344. ** while( !eof csrCurrent ){
  139345. ** RETURN_ROW
  139346. ** }
  139347. **
  139348. ** Also requiring special handling are the cases:
  139349. **
  139350. ** ROWS BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING
  139351. ** ROWS BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING
  139352. **
  139353. ** when (expr1 < expr2). This is detected at runtime, not by this function.
  139354. ** To handle this case, the pseudo-code programs depicted above are modified
  139355. ** slightly to be:
  139356. **
  139357. ** ... loop started by sqlite3WhereBegin() ...
  139358. ** if( new partition ){
  139359. ** Gosub flush
  139360. ** }
  139361. ** Insert new row into eph table.
  139362. ** if( first row of partition ){
  139363. ** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
  139364. ** regEnd = <expr2>
  139365. ** regStart = <expr1>
  139366. ** if( regEnd < regStart ){
  139367. ** RETURN_ROW
  139368. ** delete eph table contents
  139369. ** continue
  139370. ** }
  139371. ** ...
  139372. **
  139373. ** The new "continue" statement in the above jumps to the next iteration
  139374. ** of the outer loop - the one started by sqlite3WhereBegin().
  139375. **
  139376. ** The various GROUPS cases are implemented using the same patterns as
  139377. ** ROWS. The VM code is modified slightly so that:
  139378. **
  139379. ** 1. The else branch in the main loop is only taken if the row just
  139380. ** added to the ephemeral table is the start of a new group. In
  139381. ** other words, it becomes:
  139382. **
  139383. ** ... loop started by sqlite3WhereBegin() ...
  139384. ** if( new partition ){
  139385. ** Gosub flush
  139386. ** }
  139387. ** Insert new row into eph table.
  139388. ** if( first row of partition ){
  139389. ** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
  139390. ** regEnd = <expr2>
  139391. ** regStart = <expr1>
  139392. ** }else if( new group ){
  139393. ** ...
  139394. ** }
  139395. ** }
  139396. **
  139397. ** 2. Instead of processing a single row, each RETURN_ROW, AGGSTEP or
  139398. ** AGGINVERSE step processes the current row of the relevant cursor and
  139399. ** all subsequent rows belonging to the same group.
  139400. **
  139401. ** RANGE window frames are a little different again. As for GROUPS, the
  139402. ** main loop runs once per group only. And RETURN_ROW, AGGSTEP and AGGINVERSE
  139403. ** deal in groups instead of rows. As for ROWS and GROUPS, there are three
  139404. ** basic cases:
  139405. **
  139406. ** RANGE BETWEEN <expr1> PRECEDING AND <expr2> FOLLOWING
  139407. **
  139408. ** ... loop started by sqlite3WhereBegin() ...
  139409. ** if( new partition ){
  139410. ** Gosub flush
  139411. ** }
  139412. ** Insert new row into eph table.
  139413. ** if( first row of partition ){
  139414. ** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
  139415. ** regEnd = <expr2>
  139416. ** regStart = <expr1>
  139417. ** }else{
  139418. ** AGGSTEP
  139419. ** while( (csrCurrent.key + regEnd) < csrEnd.key ){
  139420. ** RETURN_ROW
  139421. ** while( csrStart.key + regStart) < csrCurrent.key ){
  139422. ** AGGINVERSE
  139423. ** }
  139424. ** }
  139425. ** }
  139426. ** }
  139427. ** flush:
  139428. ** AGGSTEP
  139429. ** while( 1 ){
  139430. ** RETURN ROW
  139431. ** if( csrCurrent is EOF ) break;
  139432. ** while( csrStart.key + regStart) < csrCurrent.key ){
  139433. ** AGGINVERSE
  139434. ** }
  139435. ** }
  139436. ** }
  139437. **
  139438. ** In the above notation, "csr.key" means the current value of the ORDER BY
  139439. ** expression (there is only ever 1 for a RANGE that uses an <expr> FOLLOWING
  139440. ** or <expr PRECEDING) read from cursor csr.
  139441. **
  139442. ** RANGE BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING
  139443. **
  139444. ** ... loop started by sqlite3WhereBegin() ...
  139445. ** if( new partition ){
  139446. ** Gosub flush
  139447. ** }
  139448. ** Insert new row into eph table.
  139449. ** if( first row of partition ){
  139450. ** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
  139451. ** regEnd = <expr2>
  139452. ** regStart = <expr1>
  139453. ** }else{
  139454. ** if( (csrEnd.key + regEnd) <= csrCurrent.key ){
  139455. ** AGGSTEP
  139456. ** }
  139457. ** while( (csrStart.key + regStart) < csrCurrent.key ){
  139458. ** AGGINVERSE
  139459. ** }
  139460. ** RETURN_ROW
  139461. ** }
  139462. ** }
  139463. ** flush:
  139464. ** while( (csrEnd.key + regEnd) <= csrCurrent.key ){
  139465. ** AGGSTEP
  139466. ** }
  139467. ** while( (csrStart.key + regStart) < csrCurrent.key ){
  139468. ** AGGINVERSE
  139469. ** }
  139470. ** RETURN_ROW
  139471. **
  139472. ** RANGE BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING
  139473. **
  139474. ** ... loop started by sqlite3WhereBegin() ...
  139475. ** if( new partition ){
  139476. ** Gosub flush
  139477. ** }
  139478. ** Insert new row into eph table.
  139479. ** if( first row of partition ){
  139480. ** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
  139481. ** regEnd = <expr2>
  139482. ** regStart = <expr1>
  139483. ** }else{
  139484. ** AGGSTEP
  139485. ** while( (csrCurrent.key + regEnd) < csrEnd.key ){
  139486. ** while( (csrCurrent.key + regStart) > csrStart.key ){
  139487. ** AGGINVERSE
  139488. ** }
  139489. ** RETURN_ROW
  139490. ** }
  139491. ** }
  139492. ** }
  139493. ** flush:
  139494. ** AGGSTEP
  139495. ** while( 1 ){
  139496. ** while( (csrCurrent.key + regStart) > csrStart.key ){
  139497. ** AGGINVERSE
  139498. ** if( eof ) break "while( 1 )" loop.
  139499. ** }
  139500. ** RETURN_ROW
  139501. ** }
  139502. ** while( !eof csrCurrent ){
  139503. ** RETURN_ROW
  139504. ** }
  139505. **
  139506. ** The text above leaves out many details. Refer to the code and comments
  139507. ** below for a more complete picture.
  139508. */
  139509. SQLITE_PRIVATE void sqlite3WindowCodeStep(
  139510. Parse *pParse, /* Parse context */
  139511. Select *p, /* Rewritten SELECT statement */
  139512. WhereInfo *pWInfo, /* Context returned by sqlite3WhereBegin() */
  139513. int regGosub, /* Register for OP_Gosub */
  139514. int addrGosub /* OP_Gosub here to return each row */
  139515. ){
  139516. Window *pMWin = p->pWin;
  139517. ExprList *pOrderBy = pMWin->pOrderBy;
  139518. Vdbe *v = sqlite3GetVdbe(pParse);
  139519. int csrWrite; /* Cursor used to write to eph. table */
  139520. int csrInput = p->pSrc->a[0].iCursor; /* Cursor of sub-select */
  139521. int nInput = p->pSrc->a[0].pTab->nCol; /* Number of cols returned by sub */
  139522. int iInput; /* To iterate through sub cols */
  139523. int addrNe; /* Address of OP_Ne */
  139524. int addrGosubFlush = 0; /* Address of OP_Gosub to flush: */
  139525. int addrInteger = 0; /* Address of OP_Integer */
  139526. int addrEmpty; /* Address of OP_Rewind in flush: */
  139527. int regStart = 0; /* Value of <expr> PRECEDING */
  139528. int regEnd = 0; /* Value of <expr> FOLLOWING */
  139529. int regNew; /* Array of registers holding new input row */
  139530. int regRecord; /* regNew array in record form */
  139531. int regRowid; /* Rowid for regRecord in eph table */
  139532. int regNewPeer = 0; /* Peer values for new row (part of regNew) */
  139533. int regPeer = 0; /* Peer values for current row */
  139534. int regFlushPart = 0; /* Register for "Gosub flush_partition" */
  139535. WindowCodeArg s; /* Context object for sub-routines */
  139536. int lblWhereEnd; /* Label just before sqlite3WhereEnd() code */
  139537. assert( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_CURRENT
  139538. || pMWin->eStart==TK_FOLLOWING || pMWin->eStart==TK_UNBOUNDED
  139539. );
  139540. assert( pMWin->eEnd==TK_FOLLOWING || pMWin->eEnd==TK_CURRENT
  139541. || pMWin->eEnd==TK_UNBOUNDED || pMWin->eEnd==TK_PRECEDING
  139542. );
  139543. assert( pMWin->eExclude==0 || pMWin->eExclude==TK_CURRENT
  139544. || pMWin->eExclude==TK_GROUP || pMWin->eExclude==TK_TIES
  139545. || pMWin->eExclude==TK_NO
  139546. );
  139547. lblWhereEnd = sqlite3VdbeMakeLabel(pParse);
  139548. /* Fill in the context object */
  139549. memset(&s, 0, sizeof(WindowCodeArg));
  139550. s.pParse = pParse;
  139551. s.pMWin = pMWin;
  139552. s.pVdbe = v;
  139553. s.regGosub = regGosub;
  139554. s.addrGosub = addrGosub;
  139555. s.current.csr = pMWin->iEphCsr;
  139556. csrWrite = s.current.csr+1;
  139557. s.start.csr = s.current.csr+2;
  139558. s.end.csr = s.current.csr+3;
  139559. /* Figure out when rows may be deleted from the ephemeral table. There
  139560. ** are four options - they may never be deleted (eDelete==0), they may
  139561. ** be deleted as soon as they are no longer part of the window frame
  139562. ** (eDelete==WINDOW_AGGINVERSE), they may be deleted as after the row
  139563. ** has been returned to the caller (WINDOW_RETURN_ROW), or they may
  139564. ** be deleted after they enter the frame (WINDOW_AGGSTEP). */
  139565. switch( pMWin->eStart ){
  139566. case TK_FOLLOWING:
  139567. if( pMWin->eFrmType!=TK_RANGE
  139568. && windowExprGtZero(pParse, pMWin->pStart)
  139569. ){
  139570. s.eDelete = WINDOW_RETURN_ROW;
  139571. }
  139572. break;
  139573. case TK_UNBOUNDED:
  139574. if( windowCacheFrame(pMWin)==0 ){
  139575. if( pMWin->eEnd==TK_PRECEDING ){
  139576. if( pMWin->eFrmType!=TK_RANGE
  139577. && windowExprGtZero(pParse, pMWin->pEnd)
  139578. ){
  139579. s.eDelete = WINDOW_AGGSTEP;
  139580. }
  139581. }else{
  139582. s.eDelete = WINDOW_RETURN_ROW;
  139583. }
  139584. }
  139585. break;
  139586. default:
  139587. s.eDelete = WINDOW_AGGINVERSE;
  139588. break;
  139589. }
  139590. /* Allocate registers for the array of values from the sub-query, the
  139591. ** samve values in record form, and the rowid used to insert said record
  139592. ** into the ephemeral table. */
  139593. regNew = pParse->nMem+1;
  139594. pParse->nMem += nInput;
  139595. regRecord = ++pParse->nMem;
  139596. regRowid = ++pParse->nMem;
  139597. /* If the window frame contains an "<expr> PRECEDING" or "<expr> FOLLOWING"
  139598. ** clause, allocate registers to store the results of evaluating each
  139599. ** <expr>. */
  139600. if( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_FOLLOWING ){
  139601. regStart = ++pParse->nMem;
  139602. }
  139603. if( pMWin->eEnd==TK_PRECEDING || pMWin->eEnd==TK_FOLLOWING ){
  139604. regEnd = ++pParse->nMem;
  139605. }
  139606. /* If this is not a "ROWS BETWEEN ..." frame, then allocate arrays of
  139607. ** registers to store copies of the ORDER BY expressions (peer values)
  139608. ** for the main loop, and for each cursor (start, current and end). */
  139609. if( pMWin->eFrmType!=TK_ROWS ){
  139610. int nPeer = (pOrderBy ? pOrderBy->nExpr : 0);
  139611. regNewPeer = regNew + pMWin->nBufferCol;
  139612. if( pMWin->pPartition ) regNewPeer += pMWin->pPartition->nExpr;
  139613. regPeer = pParse->nMem+1; pParse->nMem += nPeer;
  139614. s.start.reg = pParse->nMem+1; pParse->nMem += nPeer;
  139615. s.current.reg = pParse->nMem+1; pParse->nMem += nPeer;
  139616. s.end.reg = pParse->nMem+1; pParse->nMem += nPeer;
  139617. }
  139618. /* Load the column values for the row returned by the sub-select
  139619. ** into an array of registers starting at regNew. Assemble them into
  139620. ** a record in register regRecord. */
  139621. for(iInput=0; iInput<nInput; iInput++){
  139622. sqlite3VdbeAddOp3(v, OP_Column, csrInput, iInput, regNew+iInput);
  139623. }
  139624. sqlite3VdbeAddOp3(v, OP_MakeRecord, regNew, nInput, regRecord);
  139625. /* An input row has just been read into an array of registers starting
  139626. ** at regNew. If the window has a PARTITION clause, this block generates
  139627. ** VM code to check if the input row is the start of a new partition.
  139628. ** If so, it does an OP_Gosub to an address to be filled in later. The
  139629. ** address of the OP_Gosub is stored in local variable addrGosubFlush. */
  139630. if( pMWin->pPartition ){
  139631. int addr;
  139632. ExprList *pPart = pMWin->pPartition;
  139633. int nPart = pPart->nExpr;
  139634. int regNewPart = regNew + pMWin->nBufferCol;
  139635. KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pPart, 0, 0);
  139636. regFlushPart = ++pParse->nMem;
  139637. addr = sqlite3VdbeAddOp3(v, OP_Compare, regNewPart, pMWin->regPart, nPart);
  139638. sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
  139639. sqlite3VdbeAddOp3(v, OP_Jump, addr+2, addr+4, addr+2);
  139640. VdbeCoverageEqNe(v);
  139641. addrGosubFlush = sqlite3VdbeAddOp1(v, OP_Gosub, regFlushPart);
  139642. VdbeComment((v, "call flush_partition"));
  139643. sqlite3VdbeAddOp3(v, OP_Copy, regNewPart, pMWin->regPart, nPart-1);
  139644. }
  139645. /* Insert the new row into the ephemeral table */
  139646. sqlite3VdbeAddOp2(v, OP_NewRowid, csrWrite, regRowid);
  139647. sqlite3VdbeAddOp3(v, OP_Insert, csrWrite, regRecord, regRowid);
  139648. addrNe = sqlite3VdbeAddOp3(v, OP_Ne, pMWin->regOne, 0, regRowid);
  139649. VdbeCoverageNeverNull(v);
  139650. /* This block is run for the first row of each partition */
  139651. s.regArg = windowInitAccum(pParse, pMWin);
  139652. if( regStart ){
  139653. sqlite3ExprCode(pParse, pMWin->pStart, regStart);
  139654. windowCheckValue(pParse, regStart, 0 + (pMWin->eFrmType==TK_RANGE ? 3 : 0));
  139655. }
  139656. if( regEnd ){
  139657. sqlite3ExprCode(pParse, pMWin->pEnd, regEnd);
  139658. windowCheckValue(pParse, regEnd, 1 + (pMWin->eFrmType==TK_RANGE ? 3 : 0));
  139659. }
  139660. if( pMWin->eStart==pMWin->eEnd && regStart ){
  139661. int op = ((pMWin->eStart==TK_FOLLOWING) ? OP_Ge : OP_Le);
  139662. int addrGe = sqlite3VdbeAddOp3(v, op, regStart, 0, regEnd);
  139663. VdbeCoverageNeverNullIf(v, op==OP_Ge); /* NeverNull because bound <expr> */
  139664. VdbeCoverageNeverNullIf(v, op==OP_Le); /* values previously checked */
  139665. windowAggFinal(&s, 0);
  139666. sqlite3VdbeAddOp2(v, OP_Rewind, s.current.csr, 1);
  139667. VdbeCoverageNeverTaken(v);
  139668. windowReturnOneRow(&s);
  139669. sqlite3VdbeAddOp1(v, OP_ResetSorter, s.current.csr);
  139670. sqlite3VdbeAddOp2(v, OP_Goto, 0, lblWhereEnd);
  139671. sqlite3VdbeJumpHere(v, addrGe);
  139672. }
  139673. if( pMWin->eStart==TK_FOLLOWING && pMWin->eFrmType!=TK_RANGE && regEnd ){
  139674. assert( pMWin->eEnd==TK_FOLLOWING );
  139675. sqlite3VdbeAddOp3(v, OP_Subtract, regStart, regEnd, regStart);
  139676. }
  139677. if( pMWin->eStart!=TK_UNBOUNDED ){
  139678. sqlite3VdbeAddOp2(v, OP_Rewind, s.start.csr, 1);
  139679. VdbeCoverageNeverTaken(v);
  139680. }
  139681. sqlite3VdbeAddOp2(v, OP_Rewind, s.current.csr, 1);
  139682. VdbeCoverageNeverTaken(v);
  139683. sqlite3VdbeAddOp2(v, OP_Rewind, s.end.csr, 1);
  139684. VdbeCoverageNeverTaken(v);
  139685. if( regPeer && pOrderBy ){
  139686. sqlite3VdbeAddOp3(v, OP_Copy, regNewPeer, regPeer, pOrderBy->nExpr-1);
  139687. sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.start.reg, pOrderBy->nExpr-1);
  139688. sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.current.reg, pOrderBy->nExpr-1);
  139689. sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.end.reg, pOrderBy->nExpr-1);
  139690. }
  139691. sqlite3VdbeAddOp2(v, OP_Goto, 0, lblWhereEnd);
  139692. sqlite3VdbeJumpHere(v, addrNe);
  139693. /* Beginning of the block executed for the second and subsequent rows. */
  139694. if( regPeer ){
  139695. windowIfNewPeer(pParse, pOrderBy, regNewPeer, regPeer, lblWhereEnd);
  139696. }
  139697. if( pMWin->eStart==TK_FOLLOWING ){
  139698. windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
  139699. if( pMWin->eEnd!=TK_UNBOUNDED ){
  139700. if( pMWin->eFrmType==TK_RANGE ){
  139701. int lbl = sqlite3VdbeMakeLabel(pParse);
  139702. int addrNext = sqlite3VdbeCurrentAddr(v);
  139703. windowCodeRangeTest(&s, OP_Ge, s.current.csr, regEnd, s.end.csr, lbl);
  139704. windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
  139705. windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
  139706. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrNext);
  139707. sqlite3VdbeResolveLabel(v, lbl);
  139708. }else{
  139709. windowCodeOp(&s, WINDOW_RETURN_ROW, regEnd, 0);
  139710. windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
  139711. }
  139712. }
  139713. }else
  139714. if( pMWin->eEnd==TK_PRECEDING ){
  139715. int bRPS = (pMWin->eStart==TK_PRECEDING && pMWin->eFrmType==TK_RANGE);
  139716. windowCodeOp(&s, WINDOW_AGGSTEP, regEnd, 0);
  139717. if( bRPS ) windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
  139718. windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
  139719. if( !bRPS ) windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
  139720. }else{
  139721. int addr = 0;
  139722. windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
  139723. if( pMWin->eEnd!=TK_UNBOUNDED ){
  139724. if( pMWin->eFrmType==TK_RANGE ){
  139725. int lbl = 0;
  139726. addr = sqlite3VdbeCurrentAddr(v);
  139727. if( regEnd ){
  139728. lbl = sqlite3VdbeMakeLabel(pParse);
  139729. windowCodeRangeTest(&s, OP_Ge, s.current.csr, regEnd, s.end.csr, lbl);
  139730. }
  139731. windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
  139732. windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
  139733. if( regEnd ){
  139734. sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
  139735. sqlite3VdbeResolveLabel(v, lbl);
  139736. }
  139737. }else{
  139738. if( regEnd ){
  139739. addr = sqlite3VdbeAddOp3(v, OP_IfPos, regEnd, 0, 1);
  139740. VdbeCoverage(v);
  139741. }
  139742. windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
  139743. windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
  139744. if( regEnd ) sqlite3VdbeJumpHere(v, addr);
  139745. }
  139746. }
  139747. }
  139748. /* End of the main input loop */
  139749. sqlite3VdbeResolveLabel(v, lblWhereEnd);
  139750. sqlite3WhereEnd(pWInfo);
  139751. /* Fall through */
  139752. if( pMWin->pPartition ){
  139753. addrInteger = sqlite3VdbeAddOp2(v, OP_Integer, 0, regFlushPart);
  139754. sqlite3VdbeJumpHere(v, addrGosubFlush);
  139755. }
  139756. addrEmpty = sqlite3VdbeAddOp1(v, OP_Rewind, csrWrite);
  139757. VdbeCoverage(v);
  139758. if( pMWin->eEnd==TK_PRECEDING ){
  139759. int bRPS = (pMWin->eStart==TK_PRECEDING && pMWin->eFrmType==TK_RANGE);
  139760. windowCodeOp(&s, WINDOW_AGGSTEP, regEnd, 0);
  139761. if( bRPS ) windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
  139762. windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
  139763. }else if( pMWin->eStart==TK_FOLLOWING ){
  139764. int addrStart;
  139765. int addrBreak1;
  139766. int addrBreak2;
  139767. int addrBreak3;
  139768. windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
  139769. if( pMWin->eFrmType==TK_RANGE ){
  139770. addrStart = sqlite3VdbeCurrentAddr(v);
  139771. addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 1);
  139772. addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1);
  139773. }else
  139774. if( pMWin->eEnd==TK_UNBOUNDED ){
  139775. addrStart = sqlite3VdbeCurrentAddr(v);
  139776. addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, regStart, 1);
  139777. addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, 0, 1);
  139778. }else{
  139779. assert( pMWin->eEnd==TK_FOLLOWING );
  139780. addrStart = sqlite3VdbeCurrentAddr(v);
  139781. addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, regEnd, 1);
  139782. addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 1);
  139783. }
  139784. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart);
  139785. sqlite3VdbeJumpHere(v, addrBreak2);
  139786. addrStart = sqlite3VdbeCurrentAddr(v);
  139787. addrBreak3 = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1);
  139788. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart);
  139789. sqlite3VdbeJumpHere(v, addrBreak1);
  139790. sqlite3VdbeJumpHere(v, addrBreak3);
  139791. }else{
  139792. int addrBreak;
  139793. int addrStart;
  139794. windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
  139795. addrStart = sqlite3VdbeCurrentAddr(v);
  139796. addrBreak = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1);
  139797. windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
  139798. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart);
  139799. sqlite3VdbeJumpHere(v, addrBreak);
  139800. }
  139801. sqlite3VdbeJumpHere(v, addrEmpty);
  139802. sqlite3VdbeAddOp1(v, OP_ResetSorter, s.current.csr);
  139803. if( pMWin->pPartition ){
  139804. if( pMWin->regStartRowid ){
  139805. sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regStartRowid);
  139806. sqlite3VdbeAddOp2(v, OP_Integer, 0, pMWin->regEndRowid);
  139807. }
  139808. sqlite3VdbeChangeP1(v, addrInteger, sqlite3VdbeCurrentAddr(v));
  139809. sqlite3VdbeAddOp1(v, OP_Return, regFlushPart);
  139810. }
  139811. }
  139812. #endif /* SQLITE_OMIT_WINDOWFUNC */
  139813. /************** End of window.c **********************************************/
  139814. /************** Begin file parse.c *******************************************/
  139815. /*
  139816. ** 2000-05-29
  139817. **
  139818. ** The author disclaims copyright to this source code. In place of
  139819. ** a legal notice, here is a blessing:
  139820. **
  139821. ** May you do good and not evil.
  139822. ** May you find forgiveness for yourself and forgive others.
  139823. ** May you share freely, never taking more than you give.
  139824. **
  139825. *************************************************************************
  139826. ** Driver template for the LEMON parser generator.
  139827. **
  139828. ** The "lemon" program processes an LALR(1) input grammar file, then uses
  139829. ** this template to construct a parser. The "lemon" program inserts text
  139830. ** at each "%%" line. Also, any "P-a-r-s-e" identifer prefix (without the
  139831. ** interstitial "-" characters) contained in this template is changed into
  139832. ** the value of the %name directive from the grammar. Otherwise, the content
  139833. ** of this template is copied straight through into the generate parser
  139834. ** source file.
  139835. **
  139836. ** The following is the concatenation of all %include directives from the
  139837. ** input grammar file:
  139838. */
  139839. /* #include <stdio.h> */
  139840. /* #include <assert.h> */
  139841. /************ Begin %include sections from the grammar ************************/
  139842. /* #include "sqliteInt.h" */
  139843. /*
  139844. ** Disable all error recovery processing in the parser push-down
  139845. ** automaton.
  139846. */
  139847. #define YYNOERRORRECOVERY 1
  139848. /*
  139849. ** Make yytestcase() the same as testcase()
  139850. */
  139851. #define yytestcase(X) testcase(X)
  139852. /*
  139853. ** Indicate that sqlite3ParserFree() will never be called with a null
  139854. ** pointer.
  139855. */
  139856. #define YYPARSEFREENEVERNULL 1
  139857. /*
  139858. ** In the amalgamation, the parse.c file generated by lemon and the
  139859. ** tokenize.c file are concatenated. In that case, sqlite3RunParser()
  139860. ** has access to the the size of the yyParser object and so the parser
  139861. ** engine can be allocated from stack. In that case, only the
  139862. ** sqlite3ParserInit() and sqlite3ParserFinalize() routines are invoked
  139863. ** and the sqlite3ParserAlloc() and sqlite3ParserFree() routines can be
  139864. ** omitted.
  139865. */
  139866. #ifdef SQLITE_AMALGAMATION
  139867. # define sqlite3Parser_ENGINEALWAYSONSTACK 1
  139868. #endif
  139869. /*
  139870. ** Alternative datatype for the argument to the malloc() routine passed
  139871. ** into sqlite3ParserAlloc(). The default is size_t.
  139872. */
  139873. #define YYMALLOCARGTYPE u64
  139874. /*
  139875. ** An instance of the following structure describes the event of a
  139876. ** TRIGGER. "a" is the event type, one of TK_UPDATE, TK_INSERT,
  139877. ** TK_DELETE, or TK_INSTEAD. If the event is of the form
  139878. **
  139879. ** UPDATE ON (a,b,c)
  139880. **
  139881. ** Then the "b" IdList records the list "a,b,c".
  139882. */
  139883. struct TrigEvent { int a; IdList * b; };
  139884. struct FrameBound { int eType; Expr *pExpr; };
  139885. /*
  139886. ** Disable lookaside memory allocation for objects that might be
  139887. ** shared across database connections.
  139888. */
  139889. static void disableLookaside(Parse *pParse){
  139890. pParse->disableLookaside++;
  139891. pParse->db->lookaside.bDisable++;
  139892. }
  139893. /*
  139894. ** For a compound SELECT statement, make sure p->pPrior->pNext==p for
  139895. ** all elements in the list. And make sure list length does not exceed
  139896. ** SQLITE_LIMIT_COMPOUND_SELECT.
  139897. */
  139898. static void parserDoubleLinkSelect(Parse *pParse, Select *p){
  139899. if( p->pPrior ){
  139900. Select *pNext = 0, *pLoop;
  139901. int mxSelect, cnt = 0;
  139902. for(pLoop=p; pLoop; pNext=pLoop, pLoop=pLoop->pPrior, cnt++){
  139903. pLoop->pNext = pNext;
  139904. pLoop->selFlags |= SF_Compound;
  139905. }
  139906. if( (p->selFlags & SF_MultiValue)==0 &&
  139907. (mxSelect = pParse->db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT])>0 &&
  139908. cnt>mxSelect
  139909. ){
  139910. sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
  139911. }
  139912. }
  139913. }
  139914. /* Construct a new Expr object from a single identifier. Use the
  139915. ** new Expr to populate pOut. Set the span of pOut to be the identifier
  139916. ** that created the expression.
  139917. */
  139918. static Expr *tokenExpr(Parse *pParse, int op, Token t){
  139919. Expr *p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr)+t.n+1);
  139920. if( p ){
  139921. /* memset(p, 0, sizeof(Expr)); */
  139922. p->op = (u8)op;
  139923. p->affinity = 0;
  139924. p->flags = EP_Leaf;
  139925. p->iAgg = -1;
  139926. p->pLeft = p->pRight = 0;
  139927. p->x.pList = 0;
  139928. p->pAggInfo = 0;
  139929. p->y.pTab = 0;
  139930. p->op2 = 0;
  139931. p->iTable = 0;
  139932. p->iColumn = 0;
  139933. p->u.zToken = (char*)&p[1];
  139934. memcpy(p->u.zToken, t.z, t.n);
  139935. p->u.zToken[t.n] = 0;
  139936. if( sqlite3Isquote(p->u.zToken[0]) ){
  139937. sqlite3DequoteExpr(p);
  139938. }
  139939. #if SQLITE_MAX_EXPR_DEPTH>0
  139940. p->nHeight = 1;
  139941. #endif
  139942. if( IN_RENAME_OBJECT ){
  139943. return (Expr*)sqlite3RenameTokenMap(pParse, (void*)p, &t);
  139944. }
  139945. }
  139946. return p;
  139947. }
  139948. /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
  139949. ** unary TK_ISNULL or TK_NOTNULL expression. */
  139950. static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
  139951. sqlite3 *db = pParse->db;
  139952. if( pA && pY && pY->op==TK_NULL && !IN_RENAME_OBJECT ){
  139953. pA->op = (u8)op;
  139954. sqlite3ExprDelete(db, pA->pRight);
  139955. pA->pRight = 0;
  139956. }
  139957. }
  139958. /* Add a single new term to an ExprList that is used to store a
  139959. ** list of identifiers. Report an error if the ID list contains
  139960. ** a COLLATE clause or an ASC or DESC keyword, except ignore the
  139961. ** error while parsing a legacy schema.
  139962. */
  139963. static ExprList *parserAddExprIdListTerm(
  139964. Parse *pParse,
  139965. ExprList *pPrior,
  139966. Token *pIdToken,
  139967. int hasCollate,
  139968. int sortOrder
  139969. ){
  139970. ExprList *p = sqlite3ExprListAppend(pParse, pPrior, 0);
  139971. if( (hasCollate || sortOrder!=SQLITE_SO_UNDEFINED)
  139972. && pParse->db->init.busy==0
  139973. ){
  139974. sqlite3ErrorMsg(pParse, "syntax error after column name \"%.*s\"",
  139975. pIdToken->n, pIdToken->z);
  139976. }
  139977. sqlite3ExprListSetName(pParse, p, pIdToken, 1);
  139978. return p;
  139979. }
  139980. #if TK_SPAN>255
  139981. # error too many tokens in the grammar
  139982. #endif
  139983. /**************** End of %include directives **********************************/
  139984. /* These constants specify the various numeric values for terminal symbols
  139985. ** in a format understandable to "makeheaders". This section is blank unless
  139986. ** "lemon" is run with the "-m" command-line option.
  139987. ***************** Begin makeheaders token definitions *************************/
  139988. /**************** End makeheaders token definitions ***************************/
  139989. /* The next sections is a series of control #defines.
  139990. ** various aspects of the generated parser.
  139991. ** YYCODETYPE is the data type used to store the integer codes
  139992. ** that represent terminal and non-terminal symbols.
  139993. ** "unsigned char" is used if there are fewer than
  139994. ** 256 symbols. Larger types otherwise.
  139995. ** YYNOCODE is a number of type YYCODETYPE that is not used for
  139996. ** any terminal or nonterminal symbol.
  139997. ** YYFALLBACK If defined, this indicates that one or more tokens
  139998. ** (also known as: "terminal symbols") have fall-back
  139999. ** values which should be used if the original symbol
  140000. ** would not parse. This permits keywords to sometimes
  140001. ** be used as identifiers, for example.
  140002. ** YYACTIONTYPE is the data type used for "action codes" - numbers
  140003. ** that indicate what to do in response to the next
  140004. ** token.
  140005. ** sqlite3ParserTOKENTYPE is the data type used for minor type for terminal
  140006. ** symbols. Background: A "minor type" is a semantic
  140007. ** value associated with a terminal or non-terminal
  140008. ** symbols. For example, for an "ID" terminal symbol,
  140009. ** the minor type might be the name of the identifier.
  140010. ** Each non-terminal can have a different minor type.
  140011. ** Terminal symbols all have the same minor type, though.
  140012. ** This macros defines the minor type for terminal
  140013. ** symbols.
  140014. ** YYMINORTYPE is the data type used for all minor types.
  140015. ** This is typically a union of many types, one of
  140016. ** which is sqlite3ParserTOKENTYPE. The entry in the union
  140017. ** for terminal symbols is called "yy0".
  140018. ** YYSTACKDEPTH is the maximum depth of the parser's stack. If
  140019. ** zero the stack is dynamically sized using realloc()
  140020. ** sqlite3ParserARG_SDECL A static variable declaration for the %extra_argument
  140021. ** sqlite3ParserARG_PDECL A parameter declaration for the %extra_argument
  140022. ** sqlite3ParserARG_PARAM Code to pass %extra_argument as a subroutine parameter
  140023. ** sqlite3ParserARG_STORE Code to store %extra_argument into yypParser
  140024. ** sqlite3ParserARG_FETCH Code to extract %extra_argument from yypParser
  140025. ** sqlite3ParserCTX_* As sqlite3ParserARG_ except for %extra_context
  140026. ** YYERRORSYMBOL is the code number of the error symbol. If not
  140027. ** defined, then do no error processing.
  140028. ** YYNSTATE the combined number of states.
  140029. ** YYNRULE the number of rules in the grammar
  140030. ** YYNTOKEN Number of terminal symbols
  140031. ** YY_MAX_SHIFT Maximum value for shift actions
  140032. ** YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions
  140033. ** YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions
  140034. ** YY_ERROR_ACTION The yy_action[] code for syntax error
  140035. ** YY_ACCEPT_ACTION The yy_action[] code for accept
  140036. ** YY_NO_ACTION The yy_action[] code for no-op
  140037. ** YY_MIN_REDUCE Minimum value for reduce actions
  140038. ** YY_MAX_REDUCE Maximum value for reduce actions
  140039. */
  140040. #ifndef INTERFACE
  140041. # define INTERFACE 1
  140042. #endif
  140043. /************* Begin control #defines *****************************************/
  140044. #define YYCODETYPE unsigned short int
  140045. #define YYNOCODE 302
  140046. #define YYACTIONTYPE unsigned short int
  140047. #define YYWILDCARD 95
  140048. #define sqlite3ParserTOKENTYPE Token
  140049. typedef union {
  140050. int yyinit;
  140051. sqlite3ParserTOKENTYPE yy0;
  140052. TriggerStep* yy11;
  140053. IdList* yy76;
  140054. ExprList* yy94;
  140055. Upsert* yy95;
  140056. int yy100;
  140057. Expr* yy102;
  140058. struct {int value; int mask;} yy199;
  140059. u8 yy218;
  140060. With* yy243;
  140061. struct TrigEvent yy298;
  140062. Window* yy379;
  140063. struct FrameBound yy389;
  140064. Select* yy391;
  140065. SrcList* yy407;
  140066. const char* yy528;
  140067. } YYMINORTYPE;
  140068. #ifndef YYSTACKDEPTH
  140069. #define YYSTACKDEPTH 100
  140070. #endif
  140071. #define sqlite3ParserARG_SDECL
  140072. #define sqlite3ParserARG_PDECL
  140073. #define sqlite3ParserARG_PARAM
  140074. #define sqlite3ParserARG_FETCH
  140075. #define sqlite3ParserARG_STORE
  140076. #define sqlite3ParserCTX_SDECL Parse *pParse;
  140077. #define sqlite3ParserCTX_PDECL ,Parse *pParse
  140078. #define sqlite3ParserCTX_PARAM ,pParse
  140079. #define sqlite3ParserCTX_FETCH Parse *pParse=yypParser->pParse;
  140080. #define sqlite3ParserCTX_STORE yypParser->pParse=pParse;
  140081. #define YYFALLBACK 1
  140082. #define YYNSTATE 540
  140083. #define YYNRULE 376
  140084. #define YYNTOKEN 176
  140085. #define YY_MAX_SHIFT 539
  140086. #define YY_MIN_SHIFTREDUCE 783
  140087. #define YY_MAX_SHIFTREDUCE 1158
  140088. #define YY_ERROR_ACTION 1159
  140089. #define YY_ACCEPT_ACTION 1160
  140090. #define YY_NO_ACTION 1161
  140091. #define YY_MIN_REDUCE 1162
  140092. #define YY_MAX_REDUCE 1537
  140093. /************* End control #defines *******************************************/
  140094. #define YY_NLOOKAHEAD ((int)(sizeof(yy_lookahead)/sizeof(yy_lookahead[0])))
  140095. /* Define the yytestcase() macro to be a no-op if is not already defined
  140096. ** otherwise.
  140097. **
  140098. ** Applications can choose to define yytestcase() in the %include section
  140099. ** to a macro that can assist in verifying code coverage. For production
  140100. ** code the yytestcase() macro should be turned off. But it is useful
  140101. ** for testing.
  140102. */
  140103. #ifndef yytestcase
  140104. # define yytestcase(X)
  140105. #endif
  140106. /* Next are the tables used to determine what action to take based on the
  140107. ** current state and lookahead token. These tables are used to implement
  140108. ** functions that take a state number and lookahead value and return an
  140109. ** action integer.
  140110. **
  140111. ** Suppose the action integer is N. Then the action is determined as
  140112. ** follows
  140113. **
  140114. ** 0 <= N <= YY_MAX_SHIFT Shift N. That is, push the lookahead
  140115. ** token onto the stack and goto state N.
  140116. **
  140117. ** N between YY_MIN_SHIFTREDUCE Shift to an arbitrary state then
  140118. ** and YY_MAX_SHIFTREDUCE reduce by rule N-YY_MIN_SHIFTREDUCE.
  140119. **
  140120. ** N == YY_ERROR_ACTION A syntax error has occurred.
  140121. **
  140122. ** N == YY_ACCEPT_ACTION The parser accepts its input.
  140123. **
  140124. ** N == YY_NO_ACTION No such action. Denotes unused
  140125. ** slots in the yy_action[] table.
  140126. **
  140127. ** N between YY_MIN_REDUCE Reduce by rule N-YY_MIN_REDUCE
  140128. ** and YY_MAX_REDUCE
  140129. **
  140130. ** The action table is constructed as a single large table named yy_action[].
  140131. ** Given state S and lookahead X, the action is computed as either:
  140132. **
  140133. ** (A) N = yy_action[ yy_shift_ofst[S] + X ]
  140134. ** (B) N = yy_default[S]
  140135. **
  140136. ** The (A) formula is preferred. The B formula is used instead if
  140137. ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X.
  140138. **
  140139. ** The formulas above are for computing the action when the lookahead is
  140140. ** a terminal symbol. If the lookahead is a non-terminal (as occurs after
  140141. ** a reduce action) then the yy_reduce_ofst[] array is used in place of
  140142. ** the yy_shift_ofst[] array.
  140143. **
  140144. ** The following are the tables generated in this section:
  140145. **
  140146. ** yy_action[] A single table containing all actions.
  140147. ** yy_lookahead[] A table containing the lookahead for each entry in
  140148. ** yy_action. Used to detect hash collisions.
  140149. ** yy_shift_ofst[] For each state, the offset into yy_action for
  140150. ** shifting terminals.
  140151. ** yy_reduce_ofst[] For each state, the offset into yy_action for
  140152. ** shifting non-terminals after a reduce.
  140153. ** yy_default[] Default action for each state.
  140154. **
  140155. *********** Begin parsing tables **********************************************/
  140156. #define YY_ACTTAB_COUNT (2142)
  140157. static const YYACTIONTYPE yy_action[] = {
  140158. /* 0 */ 112, 109, 209, 112, 109, 209, 1160, 1, 1, 539,
  140159. /* 10 */ 2, 1164, 490, 1193, 1293, 534, 289, 1196, 134, 383,
  140160. /* 20 */ 1485, 1428, 1164, 1229, 1208, 1242, 1195, 289, 491, 134,
  140161. /* 30 */ 373, 915, 1229, 443, 16, 16, 1242, 70, 70, 916,
  140162. /* 40 */ 242, 1292, 296, 119, 120, 110, 1136, 1136, 981, 984,
  140163. /* 50 */ 974, 974, 117, 117, 118, 118, 118, 118, 264, 264,
  140164. /* 60 */ 190, 264, 264, 264, 264, 112, 109, 209, 362, 264,
  140165. /* 70 */ 264, 531, 376, 497, 531, 1134, 531, 1501, 239, 206,
  140166. /* 80 */ 338, 9, 531, 242, 219, 1203, 118, 118, 118, 118,
  140167. /* 90 */ 111, 439, 112, 109, 209, 219, 116, 116, 116, 116,
  140168. /* 100 */ 115, 115, 114, 114, 114, 113, 414, 115, 115, 114,
  140169. /* 110 */ 114, 114, 113, 414, 418, 12, 383, 400, 1134, 114,
  140170. /* 120 */ 114, 114, 113, 414, 1115, 418, 1134, 1392, 116, 116,
  140171. /* 130 */ 116, 116, 115, 115, 114, 114, 114, 113, 414, 961,
  140172. /* 140 */ 119, 120, 110, 1136, 1136, 981, 984, 974, 974, 117,
  140173. /* 150 */ 117, 118, 118, 118, 118, 952, 534, 414, 941, 951,
  140174. /* 160 */ 1481, 539, 2, 1164, 1505, 534, 160, 175, 289, 1134,
  140175. /* 170 */ 134, 434, 312, 297, 1115, 1116, 1117, 1242, 70, 70,
  140176. /* 180 */ 1089, 338, 1089, 118, 118, 118, 118, 42, 42, 448,
  140177. /* 190 */ 951, 951, 953, 116, 116, 116, 116, 115, 115, 114,
  140178. /* 200 */ 114, 114, 113, 414, 1115, 311, 264, 264, 82, 441,
  140179. /* 210 */ 264, 264, 190, 383, 284, 12, 288, 525, 407, 531,
  140180. /* 220 */ 96, 159, 458, 531, 371, 116, 116, 116, 116, 115,
  140181. /* 230 */ 115, 114, 114, 114, 113, 414, 219, 119, 120, 110,
  140182. /* 240 */ 1136, 1136, 981, 984, 974, 974, 117, 117, 118, 118,
  140183. /* 250 */ 118, 118, 511, 1477, 1115, 1116, 1117, 113, 414, 534,
  140184. /* 260 */ 528, 528, 528, 121, 534, 1427, 418, 116, 116, 116,
  140185. /* 270 */ 116, 115, 115, 114, 114, 114, 113, 414, 1464, 351,
  140186. /* 280 */ 270, 42, 42, 383, 187, 1115, 70, 70, 533, 433,
  140187. /* 290 */ 116, 116, 116, 116, 115, 115, 114, 114, 114, 113,
  140188. /* 300 */ 414, 534, 1339, 405, 159, 411, 410, 119, 120, 110,
  140189. /* 310 */ 1136, 1136, 981, 984, 974, 974, 117, 117, 118, 118,
  140190. /* 320 */ 118, 118, 285, 42, 42, 349, 411, 410, 514, 479,
  140191. /* 330 */ 1458, 79, 1084, 6, 1140, 1115, 1116, 1117, 480, 1142,
  140192. /* 340 */ 501, 1115, 1084, 123, 238, 1084, 136, 1141, 1234, 1234,
  140193. /* 350 */ 1143, 383, 1143, 1115, 167, 426, 80, 447, 512, 1451,
  140194. /* 360 */ 116, 116, 116, 116, 115, 115, 114, 114, 114, 113,
  140195. /* 370 */ 414, 1143, 1466, 1143, 350, 119, 120, 110, 1136, 1136,
  140196. /* 380 */ 981, 984, 974, 974, 117, 117, 118, 118, 118, 118,
  140197. /* 390 */ 402, 1115, 1116, 1117, 500, 534, 250, 267, 336, 474,
  140198. /* 400 */ 331, 473, 236, 1115, 1116, 1117, 231, 1115, 329, 471,
  140199. /* 410 */ 468, 467, 509, 1458, 1464, 505, 6, 70, 70, 466,
  140200. /* 420 */ 181, 380, 379, 534, 971, 971, 982, 985, 116, 116,
  140201. /* 430 */ 116, 116, 115, 115, 114, 114, 114, 113, 414, 1115,
  140202. /* 440 */ 412, 412, 412, 496, 1115, 69, 69, 235, 383, 288,
  140203. /* 450 */ 525, 273, 326, 516, 337, 458, 1084, 1115, 1116, 1117,
  140204. /* 460 */ 1232, 1232, 492, 160, 508, 441, 1084, 1067, 1531, 1084,
  140205. /* 470 */ 207, 1531, 119, 120, 110, 1136, 1136, 981, 984, 974,
  140206. /* 480 */ 974, 117, 117, 118, 118, 118, 118, 881, 534, 1115,
  140207. /* 490 */ 1116, 1117, 975, 534, 1115, 1116, 1117, 534, 421, 534,
  140208. /* 500 */ 141, 534, 176, 356, 517, 1119, 32, 511, 482, 388,
  140209. /* 510 */ 70, 70, 818, 288, 525, 70, 70, 441, 499, 50,
  140210. /* 520 */ 50, 70, 70, 70, 70, 116, 116, 116, 116, 115,
  140211. /* 530 */ 115, 114, 114, 114, 113, 414, 274, 264, 264, 1115,
  140212. /* 540 */ 1065, 264, 264, 1115, 355, 383, 409, 961, 1439, 822,
  140213. /* 550 */ 531, 516, 190, 419, 531, 483, 1119, 516, 337, 516,
  140214. /* 560 */ 518, 1115, 818, 952, 382, 458, 515, 951, 481, 119,
  140215. /* 570 */ 120, 110, 1136, 1136, 981, 984, 974, 974, 117, 117,
  140216. /* 580 */ 118, 118, 118, 118, 1338, 278, 1045, 278, 275, 1115,
  140217. /* 590 */ 1116, 1117, 259, 1115, 1116, 1117, 534, 5, 951, 951,
  140218. /* 600 */ 953, 1046, 231, 3, 143, 471, 468, 467, 1391, 463,
  140219. /* 610 */ 1115, 1115, 1116, 1117, 1452, 466, 1047, 836, 70, 70,
  140220. /* 620 */ 480, 534, 116, 116, 116, 116, 115, 115, 114, 114,
  140221. /* 630 */ 114, 113, 414, 95, 1115, 287, 235, 856, 902, 420,
  140222. /* 640 */ 1115, 534, 383, 13, 13, 381, 815, 857, 472, 112,
  140223. /* 650 */ 109, 209, 1115, 337, 413, 309, 837, 394, 1436, 534,
  140224. /* 660 */ 1115, 1116, 1117, 54, 54, 291, 119, 120, 110, 1136,
  140225. /* 670 */ 1136, 981, 984, 974, 974, 117, 117, 118, 118, 118,
  140226. /* 680 */ 118, 13, 13, 1084, 1115, 1116, 1117, 901, 264, 264,
  140227. /* 690 */ 1115, 1116, 1117, 1084, 292, 399, 1084, 800, 388, 140,
  140228. /* 700 */ 295, 531, 1115, 1116, 1117, 403, 447, 532, 534, 870,
  140229. /* 710 */ 870, 534, 1240, 534, 329, 534, 1185, 389, 534, 116,
  140230. /* 720 */ 116, 116, 116, 115, 115, 114, 114, 114, 113, 414,
  140231. /* 730 */ 13, 13, 1024, 13, 13, 13, 13, 13, 13, 383,
  140232. /* 740 */ 13, 13, 424, 1100, 401, 264, 264, 277, 160, 184,
  140233. /* 750 */ 1182, 185, 1533, 369, 513, 484, 432, 487, 531, 424,
  140234. /* 760 */ 423, 1397, 941, 119, 120, 110, 1136, 1136, 981, 984,
  140235. /* 770 */ 974, 974, 117, 117, 118, 118, 118, 118, 1397, 1399,
  140236. /* 780 */ 425, 519, 392, 264, 264, 1029, 1029, 455, 264, 264,
  140237. /* 790 */ 264, 264, 1004, 304, 261, 1278, 531, 900, 288, 525,
  140238. /* 800 */ 310, 531, 493, 531, 1067, 1532, 458, 387, 1532, 311,
  140239. /* 810 */ 429, 299, 534, 107, 264, 264, 116, 116, 116, 116,
  140240. /* 820 */ 115, 115, 114, 114, 114, 113, 414, 531, 424, 1384,
  140241. /* 830 */ 507, 258, 258, 1246, 55, 55, 383, 1277, 265, 265,
  140242. /* 840 */ 962, 324, 434, 312, 531, 531, 506, 1397, 1026, 1241,
  140243. /* 850 */ 298, 531, 1026, 445, 301, 1095, 303, 534, 368, 1156,
  140244. /* 860 */ 119, 120, 110, 1136, 1136, 981, 984, 974, 974, 117,
  140245. /* 870 */ 117, 118, 118, 118, 118, 1045, 534, 1065, 534, 15,
  140246. /* 880 */ 15, 1084, 208, 1324, 453, 452, 534, 1324, 534, 449,
  140247. /* 890 */ 1046, 1084, 494, 458, 1084, 234, 233, 232, 44, 44,
  140248. /* 900 */ 56, 56, 319, 1095, 322, 1047, 534, 900, 57, 57,
  140249. /* 910 */ 58, 58, 534, 116, 116, 116, 116, 115, 115, 114,
  140250. /* 920 */ 114, 114, 113, 414, 534, 514, 522, 534, 59, 59,
  140251. /* 930 */ 302, 1157, 534, 383, 60, 60, 1237, 946, 788, 789,
  140252. /* 940 */ 790, 1459, 1456, 446, 6, 6, 61, 61, 1212, 45,
  140253. /* 950 */ 45, 534, 396, 383, 46, 46, 397, 119, 120, 110,
  140254. /* 960 */ 1136, 1136, 981, 984, 974, 974, 117, 117, 118, 118,
  140255. /* 970 */ 118, 118, 428, 48, 48, 534, 392, 119, 120, 110,
  140256. /* 980 */ 1136, 1136, 981, 984, 974, 974, 117, 117, 118, 118,
  140257. /* 990 */ 118, 118, 1324, 368, 1066, 447, 825, 49, 49, 534,
  140258. /* 1000 */ 458, 357, 534, 353, 534, 138, 534, 337, 1478, 478,
  140259. /* 1010 */ 116, 116, 116, 116, 115, 115, 114, 114, 114, 113,
  140260. /* 1020 */ 414, 62, 62, 392, 63, 63, 64, 64, 14, 14,
  140261. /* 1030 */ 116, 116, 116, 116, 115, 115, 114, 114, 114, 113,
  140262. /* 1040 */ 414, 534, 810, 317, 271, 534, 1457, 825, 534, 6,
  140263. /* 1050 */ 534, 1324, 534, 142, 534, 1442, 534, 212, 534, 1324,
  140264. /* 1060 */ 534, 398, 305, 65, 65, 534, 1157, 125, 125, 476,
  140265. /* 1070 */ 66, 66, 51, 51, 67, 67, 68, 68, 52, 52,
  140266. /* 1080 */ 147, 147, 148, 148, 534, 98, 534, 75, 75, 276,
  140267. /* 1090 */ 534, 272, 534, 810, 534, 876, 534, 527, 389, 534,
  140268. /* 1100 */ 875, 534, 1151, 202, 534, 383, 53, 53, 71, 71,
  140269. /* 1110 */ 288, 525, 126, 126, 72, 72, 127, 127, 128, 128,
  140270. /* 1120 */ 454, 124, 124, 146, 146, 383, 145, 145, 408, 119,
  140271. /* 1130 */ 120, 110, 1136, 1136, 981, 984, 974, 974, 117, 117,
  140272. /* 1140 */ 118, 118, 118, 118, 534, 900, 534, 95, 534, 119,
  140273. /* 1150 */ 120, 110, 1136, 1136, 981, 984, 974, 974, 117, 117,
  140274. /* 1160 */ 118, 118, 118, 118, 390, 161, 132, 132, 131, 131,
  140275. /* 1170 */ 129, 129, 534, 915, 534, 1455, 534, 1454, 6, 1416,
  140276. /* 1180 */ 6, 916, 116, 116, 116, 116, 115, 115, 114, 114,
  140277. /* 1190 */ 114, 113, 414, 1415, 130, 130, 74, 74, 76, 76,
  140278. /* 1200 */ 534, 30, 116, 116, 116, 116, 115, 115, 114, 114,
  140279. /* 1210 */ 114, 113, 414, 534, 263, 206, 534, 1133, 1504, 93,
  140280. /* 1220 */ 876, 845, 73, 73, 102, 875, 100, 139, 17, 38,
  140281. /* 1230 */ 208, 1062, 31, 450, 370, 43, 43, 101, 47, 47,
  140282. /* 1240 */ 827, 216, 436, 308, 943, 440, 95, 241, 241, 442,
  140283. /* 1250 */ 313, 464, 241, 95, 237, 900, 327, 383, 266, 95,
  140284. /* 1260 */ 835, 834, 193, 335, 938, 314, 1011, 435, 842, 843,
  140285. /* 1270 */ 955, 1007, 909, 334, 237, 241, 873, 383, 1023, 107,
  140286. /* 1280 */ 1023, 119, 120, 110, 1136, 1136, 981, 984, 974, 974,
  140287. /* 1290 */ 117, 117, 118, 118, 118, 118, 1022, 808, 1022, 1274,
  140288. /* 1300 */ 137, 119, 108, 110, 1136, 1136, 981, 984, 974, 974,
  140289. /* 1310 */ 117, 117, 118, 118, 118, 118, 874, 1011, 318, 107,
  140290. /* 1320 */ 321, 955, 323, 325, 1225, 1211, 197, 1210, 1209, 330,
  140291. /* 1330 */ 339, 1265, 340, 283, 116, 116, 116, 116, 115, 115,
  140292. /* 1340 */ 114, 114, 114, 113, 414, 1286, 1323, 1261, 1471, 1272,
  140293. /* 1350 */ 520, 218, 521, 1329, 116, 116, 116, 116, 115, 115,
  140294. /* 1360 */ 114, 114, 114, 113, 414, 1192, 1184, 1173, 1172, 1174,
  140295. /* 1370 */ 1494, 1488, 459, 256, 383, 1258, 342, 199, 367, 344,
  140296. /* 1380 */ 211, 195, 307, 444, 11, 346, 469, 333, 1308, 1316,
  140297. /* 1390 */ 375, 427, 203, 360, 383, 1388, 188, 1387, 189, 120,
  140298. /* 1400 */ 110, 1136, 1136, 981, 984, 974, 974, 117, 117, 118,
  140299. /* 1410 */ 118, 118, 118, 1208, 1151, 300, 348, 1491, 245, 1148,
  140300. /* 1420 */ 110, 1136, 1136, 981, 984, 974, 974, 117, 117, 118,
  140301. /* 1430 */ 118, 118, 118, 198, 1435, 1433, 524, 78, 391, 163,
  140302. /* 1440 */ 82, 1393, 438, 173, 81, 105, 526, 1313, 4, 35,
  140303. /* 1450 */ 157, 116, 116, 116, 116, 115, 115, 114, 114, 114,
  140304. /* 1460 */ 113, 414, 529, 165, 93, 430, 1305, 168, 169, 431,
  140305. /* 1470 */ 462, 116, 116, 116, 116, 115, 115, 114, 114, 114,
  140306. /* 1480 */ 113, 414, 170, 171, 221, 415, 372, 437, 1319, 177,
  140307. /* 1490 */ 374, 36, 451, 225, 1382, 87, 457, 523, 257, 1404,
  140308. /* 1500 */ 316, 105, 526, 227, 4, 182, 460, 160, 320, 228,
  140309. /* 1510 */ 377, 1175, 475, 229, 1228, 404, 1227, 1226, 529, 827,
  140310. /* 1520 */ 961, 1219, 378, 1200, 1199, 406, 103, 103, 1218, 332,
  140311. /* 1530 */ 8, 281, 1198, 104, 1503, 415, 536, 535, 486, 282,
  140312. /* 1540 */ 951, 415, 489, 495, 92, 244, 1269, 341, 243, 122,
  140313. /* 1550 */ 1270, 343, 514, 523, 1268, 1462, 10, 288, 525, 345,
  140314. /* 1560 */ 1461, 354, 99, 352, 503, 94, 1267, 347, 1251, 502,
  140315. /* 1570 */ 498, 951, 951, 953, 954, 27, 961, 1250, 194, 358,
  140316. /* 1580 */ 251, 359, 103, 103, 1181, 34, 537, 1110, 252, 104,
  140317. /* 1590 */ 254, 415, 536, 535, 255, 1368, 951, 1420, 286, 538,
  140318. /* 1600 */ 1170, 1165, 1421, 135, 1419, 1418, 149, 150, 279, 784,
  140319. /* 1610 */ 416, 196, 151, 290, 210, 200, 77, 385, 269, 386,
  140320. /* 1620 */ 133, 162, 935, 1021, 201, 1019, 153, 951, 951, 953,
  140321. /* 1630 */ 954, 27, 1480, 1104, 417, 164, 217, 268, 859, 166,
  140322. /* 1640 */ 306, 1035, 366, 366, 365, 253, 363, 220, 172, 797,
  140323. /* 1650 */ 939, 155, 105, 526, 393, 4, 395, 174, 156, 83,
  140324. /* 1660 */ 1038, 84, 213, 85, 294, 222, 86, 223, 1034, 529,
  140325. /* 1670 */ 144, 18, 293, 224, 315, 456, 241, 1027, 1145, 178,
  140326. /* 1680 */ 226, 179, 37, 799, 334, 461, 230, 465, 470, 838,
  140327. /* 1690 */ 180, 88, 415, 19, 280, 328, 20, 89, 90, 158,
  140328. /* 1700 */ 191, 477, 215, 1097, 523, 204, 192, 987, 91, 1070,
  140329. /* 1710 */ 152, 39, 485, 154, 1071, 503, 40, 488, 205, 260,
  140330. /* 1720 */ 504, 262, 105, 526, 214, 4, 908, 961, 183, 240,
  140331. /* 1730 */ 903, 107, 1086, 103, 103, 21, 22, 1088, 23, 529,
  140332. /* 1740 */ 104, 24, 415, 536, 535, 1090, 1093, 951, 1094, 25,
  140333. /* 1750 */ 1074, 33, 7, 26, 510, 1002, 247, 186, 384, 95,
  140334. /* 1760 */ 988, 986, 415, 288, 525, 990, 1044, 246, 1043, 991,
  140335. /* 1770 */ 28, 41, 530, 956, 523, 809, 106, 29, 951, 951,
  140336. /* 1780 */ 953, 954, 27, 869, 361, 503, 422, 248, 364, 1105,
  140337. /* 1790 */ 502, 249, 1161, 1496, 1495, 1161, 1161, 961, 1161, 1161,
  140338. /* 1800 */ 1161, 1161, 1161, 103, 103, 1161, 1161, 1161, 1161, 1161,
  140339. /* 1810 */ 104, 1161, 415, 536, 535, 1104, 417, 951, 1161, 268,
  140340. /* 1820 */ 1161, 1161, 1161, 1161, 366, 366, 365, 253, 363, 1161,
  140341. /* 1830 */ 1161, 797, 1161, 1161, 1161, 1161, 105, 526, 1161, 4,
  140342. /* 1840 */ 1161, 1161, 1161, 1161, 213, 1161, 294, 1161, 951, 951,
  140343. /* 1850 */ 953, 954, 27, 529, 293, 1161, 1161, 1161, 1161, 1161,
  140344. /* 1860 */ 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161,
  140345. /* 1870 */ 1161, 1161, 1161, 1161, 1161, 1161, 415, 1161, 1161, 1161,
  140346. /* 1880 */ 1161, 1161, 1161, 1161, 215, 1161, 1161, 1161, 523, 1161,
  140347. /* 1890 */ 1161, 1161, 152, 1161, 1161, 154, 105, 526, 1161, 4,
  140348. /* 1900 */ 1161, 1161, 1161, 1161, 1161, 1161, 214, 1161, 1161, 1161,
  140349. /* 1910 */ 1161, 961, 1161, 529, 1161, 1161, 1161, 103, 103, 880,
  140350. /* 1920 */ 1161, 1161, 1161, 1161, 104, 1161, 415, 536, 535, 1161,
  140351. /* 1930 */ 1161, 951, 1161, 1161, 1161, 1161, 415, 1161, 1161, 1161,
  140352. /* 1940 */ 384, 1161, 1161, 1161, 1161, 288, 525, 1161, 523, 1161,
  140353. /* 1950 */ 1161, 1161, 1161, 1161, 1161, 1161, 97, 526, 1161, 4,
  140354. /* 1960 */ 1161, 1161, 951, 951, 953, 954, 27, 1161, 422, 1161,
  140355. /* 1970 */ 1161, 961, 1161, 529, 1161, 1161, 1161, 103, 103, 1161,
  140356. /* 1980 */ 1161, 1161, 1161, 1161, 104, 1161, 415, 536, 535, 1161,
  140357. /* 1990 */ 1161, 951, 268, 1161, 1161, 1161, 415, 366, 366, 365,
  140358. /* 2000 */ 253, 363, 1161, 1161, 797, 1161, 1161, 1161, 523, 1161,
  140359. /* 2010 */ 1161, 1161, 1161, 1161, 1161, 1161, 1161, 213, 1161, 294,
  140360. /* 2020 */ 1161, 1161, 951, 951, 953, 954, 27, 293, 1161, 1161,
  140361. /* 2030 */ 1161, 961, 1161, 1161, 1161, 1161, 1161, 103, 103, 1161,
  140362. /* 2040 */ 1161, 1161, 1161, 1161, 104, 1161, 415, 536, 535, 1161,
  140363. /* 2050 */ 1161, 951, 1161, 1161, 1161, 1161, 1161, 215, 1161, 1161,
  140364. /* 2060 */ 1161, 1161, 1161, 1161, 1161, 152, 1161, 1161, 154, 1161,
  140365. /* 2070 */ 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 214,
  140366. /* 2080 */ 1161, 1161, 951, 951, 953, 954, 27, 1161, 1161, 1161,
  140367. /* 2090 */ 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161,
  140368. /* 2100 */ 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161,
  140369. /* 2110 */ 1161, 1161, 1161, 384, 1161, 1161, 1161, 1161, 288, 525,
  140370. /* 2120 */ 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161,
  140371. /* 2130 */ 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161,
  140372. /* 2140 */ 1161, 422,
  140373. };
  140374. static const YYCODETYPE yy_lookahead[] = {
  140375. /* 0 */ 260, 261, 262, 260, 261, 262, 176, 177, 178, 179,
  140376. /* 10 */ 180, 181, 184, 206, 209, 184, 186, 206, 188, 19,
  140377. /* 20 */ 179, 281, 181, 213, 214, 195, 206, 186, 195, 188,
  140378. /* 30 */ 195, 31, 222, 184, 206, 207, 195, 206, 207, 39,
  140379. /* 40 */ 24, 209, 184, 43, 44, 45, 46, 47, 48, 49,
  140380. /* 50 */ 50, 51, 52, 53, 54, 55, 56, 57, 228, 229,
  140381. /* 60 */ 184, 228, 229, 228, 229, 260, 261, 262, 192, 228,
  140382. /* 70 */ 229, 241, 196, 242, 241, 59, 241, 205, 245, 246,
  140383. /* 80 */ 184, 22, 241, 24, 254, 213, 54, 55, 56, 57,
  140384. /* 90 */ 58, 256, 260, 261, 262, 254, 96, 97, 98, 99,
  140385. /* 100 */ 100, 101, 102, 103, 104, 105, 106, 100, 101, 102,
  140386. /* 110 */ 103, 104, 105, 106, 284, 203, 19, 221, 59, 102,
  140387. /* 120 */ 103, 104, 105, 106, 59, 284, 110, 269, 96, 97,
  140388. /* 130 */ 98, 99, 100, 101, 102, 103, 104, 105, 106, 94,
  140389. /* 140 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
  140390. /* 150 */ 53, 54, 55, 56, 57, 110, 184, 106, 73, 114,
  140391. /* 160 */ 178, 179, 180, 181, 219, 184, 81, 22, 186, 110,
  140392. /* 170 */ 188, 121, 122, 195, 109, 110, 111, 195, 206, 207,
  140393. /* 180 */ 83, 184, 85, 54, 55, 56, 57, 206, 207, 277,
  140394. /* 190 */ 145, 146, 147, 96, 97, 98, 99, 100, 101, 102,
  140395. /* 200 */ 103, 104, 105, 106, 59, 120, 228, 229, 143, 184,
  140396. /* 210 */ 228, 229, 184, 19, 242, 203, 131, 132, 221, 241,
  140397. /* 220 */ 26, 184, 184, 241, 196, 96, 97, 98, 99, 100,
  140398. /* 230 */ 101, 102, 103, 104, 105, 106, 254, 43, 44, 45,
  140399. /* 240 */ 46, 47, 48, 49, 50, 51, 52, 53, 54, 55,
  140400. /* 250 */ 56, 57, 184, 184, 109, 110, 111, 105, 106, 184,
  140401. /* 260 */ 200, 201, 202, 69, 184, 227, 284, 96, 97, 98,
  140402. /* 270 */ 99, 100, 101, 102, 103, 104, 105, 106, 297, 298,
  140403. /* 280 */ 255, 206, 207, 19, 272, 59, 206, 207, 184, 277,
  140404. /* 290 */ 96, 97, 98, 99, 100, 101, 102, 103, 104, 105,
  140405. /* 300 */ 106, 184, 259, 19, 184, 100, 101, 43, 44, 45,
  140406. /* 310 */ 46, 47, 48, 49, 50, 51, 52, 53, 54, 55,
  140407. /* 320 */ 56, 57, 242, 206, 207, 184, 100, 101, 138, 292,
  140408. /* 330 */ 293, 67, 76, 296, 108, 109, 110, 111, 295, 113,
  140409. /* 340 */ 84, 59, 86, 22, 26, 89, 156, 121, 224, 225,
  140410. /* 350 */ 145, 19, 147, 59, 72, 256, 24, 184, 290, 291,
  140411. /* 360 */ 96, 97, 98, 99, 100, 101, 102, 103, 104, 105,
  140412. /* 370 */ 106, 145, 297, 147, 299, 43, 44, 45, 46, 47,
  140413. /* 380 */ 48, 49, 50, 51, 52, 53, 54, 55, 56, 57,
  140414. /* 390 */ 106, 109, 110, 111, 138, 184, 112, 113, 114, 115,
  140415. /* 400 */ 116, 117, 118, 109, 110, 111, 112, 59, 124, 115,
  140416. /* 410 */ 116, 117, 292, 293, 297, 298, 296, 206, 207, 125,
  140417. /* 420 */ 72, 100, 101, 184, 46, 47, 48, 49, 96, 97,
  140418. /* 430 */ 98, 99, 100, 101, 102, 103, 104, 105, 106, 59,
  140419. /* 440 */ 200, 201, 202, 184, 59, 206, 207, 46, 19, 131,
  140420. /* 450 */ 132, 278, 23, 242, 184, 184, 76, 109, 110, 111,
  140421. /* 460 */ 224, 225, 251, 81, 84, 184, 86, 22, 23, 89,
  140422. /* 470 */ 184, 26, 43, 44, 45, 46, 47, 48, 49, 50,
  140423. /* 480 */ 51, 52, 53, 54, 55, 56, 57, 102, 184, 109,
  140424. /* 490 */ 110, 111, 114, 184, 109, 110, 111, 184, 227, 184,
  140425. /* 500 */ 230, 184, 22, 264, 195, 59, 22, 184, 195, 108,
  140426. /* 510 */ 206, 207, 59, 131, 132, 206, 207, 184, 138, 206,
  140427. /* 520 */ 207, 206, 207, 206, 207, 96, 97, 98, 99, 100,
  140428. /* 530 */ 101, 102, 103, 104, 105, 106, 255, 228, 229, 59,
  140429. /* 540 */ 95, 228, 229, 59, 184, 19, 242, 94, 184, 23,
  140430. /* 550 */ 241, 242, 184, 282, 241, 242, 110, 242, 184, 242,
  140431. /* 560 */ 251, 59, 109, 110, 196, 184, 251, 114, 251, 43,
  140432. /* 570 */ 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
  140433. /* 580 */ 54, 55, 56, 57, 259, 217, 12, 219, 255, 109,
  140434. /* 590 */ 110, 111, 203, 109, 110, 111, 184, 22, 145, 146,
  140435. /* 600 */ 147, 27, 112, 22, 230, 115, 116, 117, 227, 19,
  140436. /* 610 */ 59, 109, 110, 111, 291, 125, 42, 35, 206, 207,
  140437. /* 620 */ 295, 184, 96, 97, 98, 99, 100, 101, 102, 103,
  140438. /* 630 */ 104, 105, 106, 26, 59, 233, 46, 63, 136, 184,
  140439. /* 640 */ 59, 184, 19, 206, 207, 243, 23, 73, 66, 260,
  140440. /* 650 */ 261, 262, 59, 184, 242, 195, 74, 220, 184, 184,
  140441. /* 660 */ 109, 110, 111, 206, 207, 184, 43, 44, 45, 46,
  140442. /* 670 */ 47, 48, 49, 50, 51, 52, 53, 54, 55, 56,
  140443. /* 680 */ 57, 206, 207, 76, 109, 110, 111, 136, 228, 229,
  140444. /* 690 */ 109, 110, 111, 86, 184, 220, 89, 21, 108, 230,
  140445. /* 700 */ 184, 241, 109, 110, 111, 123, 184, 127, 184, 129,
  140446. /* 710 */ 130, 184, 195, 184, 124, 184, 198, 199, 184, 96,
  140447. /* 720 */ 97, 98, 99, 100, 101, 102, 103, 104, 105, 106,
  140448. /* 730 */ 206, 207, 11, 206, 207, 206, 207, 206, 207, 19,
  140449. /* 740 */ 206, 207, 184, 23, 220, 228, 229, 220, 81, 220,
  140450. /* 750 */ 195, 220, 287, 288, 220, 195, 80, 195, 241, 201,
  140451. /* 760 */ 202, 184, 73, 43, 44, 45, 46, 47, 48, 49,
  140452. /* 770 */ 50, 51, 52, 53, 54, 55, 56, 57, 201, 202,
  140453. /* 780 */ 113, 195, 184, 228, 229, 120, 121, 122, 228, 229,
  140454. /* 790 */ 228, 229, 116, 16, 23, 184, 241, 26, 131, 132,
  140455. /* 800 */ 278, 241, 19, 241, 22, 23, 184, 189, 26, 120,
  140456. /* 810 */ 121, 122, 184, 26, 228, 229, 96, 97, 98, 99,
  140457. /* 820 */ 100, 101, 102, 103, 104, 105, 106, 241, 270, 153,
  140458. /* 830 */ 66, 228, 229, 229, 206, 207, 19, 184, 228, 229,
  140459. /* 840 */ 23, 16, 121, 122, 241, 241, 82, 270, 29, 227,
  140460. /* 850 */ 252, 241, 33, 19, 77, 91, 79, 184, 22, 23,
  140461. /* 860 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
  140462. /* 870 */ 53, 54, 55, 56, 57, 12, 184, 95, 184, 206,
  140463. /* 880 */ 207, 76, 111, 184, 65, 267, 184, 184, 184, 271,
  140464. /* 890 */ 27, 86, 109, 184, 89, 120, 121, 122, 206, 207,
  140465. /* 900 */ 206, 207, 77, 139, 79, 42, 184, 136, 206, 207,
  140466. /* 910 */ 206, 207, 184, 96, 97, 98, 99, 100, 101, 102,
  140467. /* 920 */ 103, 104, 105, 106, 184, 138, 63, 184, 206, 207,
  140468. /* 930 */ 153, 95, 184, 19, 206, 207, 227, 23, 7, 8,
  140469. /* 940 */ 9, 293, 293, 109, 296, 296, 206, 207, 215, 206,
  140470. /* 950 */ 207, 184, 253, 19, 206, 207, 253, 43, 44, 45,
  140471. /* 960 */ 46, 47, 48, 49, 50, 51, 52, 53, 54, 55,
  140472. /* 970 */ 56, 57, 184, 206, 207, 184, 184, 43, 44, 45,
  140473. /* 980 */ 46, 47, 48, 49, 50, 51, 52, 53, 54, 55,
  140474. /* 990 */ 56, 57, 184, 22, 23, 184, 59, 206, 207, 184,
  140475. /* 1000 */ 184, 238, 184, 240, 184, 22, 184, 184, 157, 158,
  140476. /* 1010 */ 96, 97, 98, 99, 100, 101, 102, 103, 104, 105,
  140477. /* 1020 */ 106, 206, 207, 184, 206, 207, 206, 207, 206, 207,
  140478. /* 1030 */ 96, 97, 98, 99, 100, 101, 102, 103, 104, 105,
  140479. /* 1040 */ 106, 184, 59, 227, 252, 184, 293, 110, 184, 296,
  140480. /* 1050 */ 184, 184, 184, 230, 184, 184, 184, 15, 184, 184,
  140481. /* 1060 */ 184, 253, 184, 206, 207, 184, 95, 206, 207, 102,
  140482. /* 1070 */ 206, 207, 206, 207, 206, 207, 206, 207, 206, 207,
  140483. /* 1080 */ 206, 207, 206, 207, 184, 151, 184, 206, 207, 278,
  140484. /* 1090 */ 184, 252, 184, 110, 184, 128, 184, 198, 199, 184,
  140485. /* 1100 */ 133, 184, 60, 26, 184, 19, 206, 207, 206, 207,
  140486. /* 1110 */ 131, 132, 206, 207, 206, 207, 206, 207, 206, 207,
  140487. /* 1120 */ 253, 206, 207, 206, 207, 19, 206, 207, 253, 43,
  140488. /* 1130 */ 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
  140489. /* 1140 */ 54, 55, 56, 57, 184, 26, 184, 26, 184, 43,
  140490. /* 1150 */ 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
  140491. /* 1160 */ 54, 55, 56, 57, 285, 286, 206, 207, 206, 207,
  140492. /* 1170 */ 206, 207, 184, 31, 184, 293, 184, 293, 296, 184,
  140493. /* 1180 */ 296, 39, 96, 97, 98, 99, 100, 101, 102, 103,
  140494. /* 1190 */ 104, 105, 106, 184, 206, 207, 206, 207, 206, 207,
  140495. /* 1200 */ 184, 22, 96, 97, 98, 99, 100, 101, 102, 103,
  140496. /* 1210 */ 104, 105, 106, 184, 245, 246, 184, 26, 23, 142,
  140497. /* 1220 */ 128, 26, 206, 207, 150, 133, 152, 22, 22, 24,
  140498. /* 1230 */ 111, 23, 53, 184, 26, 206, 207, 151, 206, 207,
  140499. /* 1240 */ 119, 24, 122, 23, 23, 23, 26, 26, 26, 23,
  140500. /* 1250 */ 23, 23, 26, 26, 26, 136, 23, 19, 22, 26,
  140501. /* 1260 */ 113, 114, 24, 114, 144, 184, 59, 61, 7, 8,
  140502. /* 1270 */ 59, 23, 23, 124, 26, 26, 23, 19, 145, 26,
  140503. /* 1280 */ 147, 43, 44, 45, 46, 47, 48, 49, 50, 51,
  140504. /* 1290 */ 52, 53, 54, 55, 56, 57, 145, 23, 147, 184,
  140505. /* 1300 */ 26, 43, 44, 45, 46, 47, 48, 49, 50, 51,
  140506. /* 1310 */ 52, 53, 54, 55, 56, 57, 23, 110, 184, 26,
  140507. /* 1320 */ 184, 110, 184, 184, 184, 215, 135, 215, 184, 184,
  140508. /* 1330 */ 184, 247, 184, 244, 96, 97, 98, 99, 100, 101,
  140509. /* 1340 */ 102, 103, 104, 105, 106, 184, 184, 184, 301, 184,
  140510. /* 1350 */ 184, 134, 225, 184, 96, 97, 98, 99, 100, 101,
  140511. /* 1360 */ 102, 103, 104, 105, 106, 184, 184, 184, 184, 184,
  140512. /* 1370 */ 134, 184, 274, 273, 19, 244, 244, 204, 182, 244,
  140513. /* 1380 */ 283, 231, 279, 279, 232, 244, 210, 209, 235, 235,
  140514. /* 1390 */ 235, 248, 218, 234, 19, 209, 238, 209, 238, 44,
  140515. /* 1400 */ 45, 46, 47, 48, 49, 50, 51, 52, 53, 54,
  140516. /* 1410 */ 55, 56, 57, 214, 60, 248, 248, 187, 134, 38,
  140517. /* 1420 */ 45, 46, 47, 48, 49, 50, 51, 52, 53, 54,
  140518. /* 1430 */ 55, 56, 57, 232, 191, 191, 266, 280, 191, 283,
  140519. /* 1440 */ 143, 269, 108, 22, 280, 19, 20, 258, 22, 257,
  140520. /* 1450 */ 43, 96, 97, 98, 99, 100, 101, 102, 103, 104,
  140521. /* 1460 */ 105, 106, 36, 223, 142, 18, 235, 226, 226, 191,
  140522. /* 1470 */ 18, 96, 97, 98, 99, 100, 101, 102, 103, 104,
  140523. /* 1480 */ 105, 106, 226, 226, 190, 59, 235, 235, 223, 223,
  140524. /* 1490 */ 258, 257, 191, 190, 235, 150, 62, 71, 191, 276,
  140525. /* 1500 */ 275, 19, 20, 190, 22, 22, 211, 81, 191, 190,
  140526. /* 1510 */ 211, 191, 108, 190, 208, 64, 208, 208, 36, 119,
  140527. /* 1520 */ 94, 216, 211, 208, 210, 106, 100, 101, 216, 208,
  140528. /* 1530 */ 48, 268, 208, 107, 208, 109, 110, 111, 211, 268,
  140529. /* 1540 */ 114, 59, 211, 137, 108, 88, 250, 249, 191, 141,
  140530. /* 1550 */ 250, 249, 138, 71, 250, 300, 22, 131, 132, 249,
  140531. /* 1560 */ 300, 191, 150, 238, 82, 140, 250, 249, 239, 87,
  140532. /* 1570 */ 139, 145, 146, 147, 148, 149, 94, 239, 237, 236,
  140533. /* 1580 */ 25, 235, 100, 101, 194, 26, 193, 13, 185, 107,
  140534. /* 1590 */ 185, 109, 110, 111, 6, 263, 114, 203, 265, 183,
  140535. /* 1600 */ 183, 183, 203, 212, 203, 203, 197, 197, 212, 4,
  140536. /* 1610 */ 3, 22, 197, 155, 15, 204, 203, 289, 93, 289,
  140537. /* 1620 */ 16, 286, 132, 23, 204, 23, 123, 145, 146, 147,
  140538. /* 1630 */ 148, 149, 0, 1, 2, 143, 24, 5, 20, 135,
  140539. /* 1640 */ 16, 1, 10, 11, 12, 13, 14, 137, 135, 17,
  140540. /* 1650 */ 144, 123, 19, 20, 61, 22, 37, 143, 123, 53,
  140541. /* 1660 */ 109, 53, 30, 53, 32, 34, 53, 134, 1, 36,
  140542. /* 1670 */ 5, 22, 40, 108, 153, 41, 26, 68, 75, 68,
  140543. /* 1680 */ 134, 108, 24, 20, 124, 19, 118, 67, 67, 28,
  140544. /* 1690 */ 22, 22, 59, 22, 67, 23, 22, 22, 142, 37,
  140545. /* 1700 */ 23, 22, 70, 23, 71, 157, 23, 23, 26, 23,
  140546. /* 1710 */ 78, 22, 24, 81, 23, 82, 22, 24, 134, 23,
  140547. /* 1720 */ 87, 23, 19, 20, 92, 22, 109, 94, 22, 34,
  140548. /* 1730 */ 136, 26, 85, 100, 101, 34, 34, 83, 34, 36,
  140549. /* 1740 */ 107, 34, 109, 110, 111, 75, 90, 114, 75, 34,
  140550. /* 1750 */ 23, 22, 44, 34, 24, 23, 22, 26, 126, 26,
  140551. /* 1760 */ 23, 23, 59, 131, 132, 23, 23, 26, 23, 11,
  140552. /* 1770 */ 22, 22, 26, 23, 71, 23, 22, 22, 145, 146,
  140553. /* 1780 */ 147, 148, 149, 128, 23, 82, 154, 134, 15, 1,
  140554. /* 1790 */ 87, 134, 302, 134, 134, 302, 302, 94, 302, 302,
  140555. /* 1800 */ 302, 302, 302, 100, 101, 302, 302, 302, 302, 302,
  140556. /* 1810 */ 107, 302, 109, 110, 111, 1, 2, 114, 302, 5,
  140557. /* 1820 */ 302, 302, 302, 302, 10, 11, 12, 13, 14, 302,
  140558. /* 1830 */ 302, 17, 302, 302, 302, 302, 19, 20, 302, 22,
  140559. /* 1840 */ 302, 302, 302, 302, 30, 302, 32, 302, 145, 146,
  140560. /* 1850 */ 147, 148, 149, 36, 40, 302, 302, 302, 302, 302,
  140561. /* 1860 */ 302, 302, 302, 302, 302, 302, 302, 302, 302, 302,
  140562. /* 1870 */ 302, 302, 302, 302, 302, 302, 59, 302, 302, 302,
  140563. /* 1880 */ 302, 302, 302, 302, 70, 302, 302, 302, 71, 302,
  140564. /* 1890 */ 302, 302, 78, 302, 302, 81, 19, 20, 302, 22,
  140565. /* 1900 */ 302, 302, 302, 302, 302, 302, 92, 302, 302, 302,
  140566. /* 1910 */ 302, 94, 302, 36, 302, 302, 302, 100, 101, 102,
  140567. /* 1920 */ 302, 302, 302, 302, 107, 302, 109, 110, 111, 302,
  140568. /* 1930 */ 302, 114, 302, 302, 302, 302, 59, 302, 302, 302,
  140569. /* 1940 */ 126, 302, 302, 302, 302, 131, 132, 302, 71, 302,
  140570. /* 1950 */ 302, 302, 302, 302, 302, 302, 19, 20, 302, 22,
  140571. /* 1960 */ 302, 302, 145, 146, 147, 148, 149, 302, 154, 302,
  140572. /* 1970 */ 302, 94, 302, 36, 302, 302, 302, 100, 101, 302,
  140573. /* 1980 */ 302, 302, 302, 302, 107, 302, 109, 110, 111, 302,
  140574. /* 1990 */ 302, 114, 5, 302, 302, 302, 59, 10, 11, 12,
  140575. /* 2000 */ 13, 14, 302, 302, 17, 302, 302, 302, 71, 302,
  140576. /* 2010 */ 302, 302, 302, 302, 302, 302, 302, 30, 302, 32,
  140577. /* 2020 */ 302, 302, 145, 146, 147, 148, 149, 40, 302, 302,
  140578. /* 2030 */ 302, 94, 302, 302, 302, 302, 302, 100, 101, 302,
  140579. /* 2040 */ 302, 302, 302, 302, 107, 302, 109, 110, 111, 302,
  140580. /* 2050 */ 302, 114, 302, 302, 302, 302, 302, 70, 302, 302,
  140581. /* 2060 */ 302, 302, 302, 302, 302, 78, 302, 302, 81, 302,
  140582. /* 2070 */ 302, 302, 302, 302, 302, 302, 302, 302, 302, 92,
  140583. /* 2080 */ 302, 302, 145, 146, 147, 148, 149, 302, 302, 302,
  140584. /* 2090 */ 302, 302, 302, 302, 302, 302, 302, 302, 302, 302,
  140585. /* 2100 */ 302, 302, 302, 302, 302, 302, 302, 302, 302, 302,
  140586. /* 2110 */ 302, 302, 302, 126, 302, 302, 302, 302, 131, 132,
  140587. /* 2120 */ 302, 302, 302, 302, 302, 302, 302, 302, 302, 302,
  140588. /* 2130 */ 302, 302, 302, 302, 302, 302, 302, 302, 302, 302,
  140589. /* 2140 */ 302, 154, 302, 302, 302, 302, 302, 302, 302, 302,
  140590. /* 2150 */ 302, 302, 302, 302, 302, 302, 302, 302, 302, 302,
  140591. /* 2160 */ 302, 302, 302, 302, 302, 302, 302, 302, 302,
  140592. };
  140593. #define YY_SHIFT_COUNT (539)
  140594. #define YY_SHIFT_MIN (0)
  140595. #define YY_SHIFT_MAX (1987)
  140596. static const unsigned short int yy_shift_ofst[] = {
  140597. /* 0 */ 1814, 1632, 1987, 1426, 1426, 382, 1482, 1633, 1703, 1877,
  140598. /* 10 */ 1877, 1877, 85, 0, 0, 264, 1106, 1877, 1877, 1877,
  140599. /* 20 */ 1877, 1877, 1877, 1877, 1877, 1877, 1877, 1877, 1877, 1877,
  140600. /* 30 */ 226, 226, 380, 380, 294, 667, 382, 382, 382, 382,
  140601. /* 40 */ 382, 382, 97, 194, 332, 429, 526, 623, 720, 817,
  140602. /* 50 */ 914, 934, 1086, 1238, 1106, 1106, 1106, 1106, 1106, 1106,
  140603. /* 60 */ 1106, 1106, 1106, 1106, 1106, 1106, 1106, 1106, 1106, 1106,
  140604. /* 70 */ 1106, 1106, 1258, 1106, 1355, 1375, 1375, 1817, 1877, 1877,
  140605. /* 80 */ 1877, 1877, 1877, 1877, 1877, 1877, 1877, 1877, 1877, 1877,
  140606. /* 90 */ 1877, 1877, 1877, 1877, 1877, 1877, 1877, 1877, 1877, 1877,
  140607. /* 100 */ 1877, 1877, 1877, 1877, 1877, 1877, 1877, 1877, 1877, 1877,
  140608. /* 110 */ 1937, 1877, 1877, 1877, 1877, 1877, 1877, 1877, 1877, 1877,
  140609. /* 120 */ 1877, 1877, 1877, 1877, 32, 129, 129, 129, 129, 129,
  140610. /* 130 */ 171, 7, 17, 593, 676, 590, 593, 205, 205, 593,
  140611. /* 140 */ 318, 318, 318, 318, 50, 152, 51, 2142, 2142, 284,
  140612. /* 150 */ 284, 284, 65, 145, 282, 145, 145, 574, 574, 256,
  140613. /* 160 */ 348, 445, 782, 593, 593, 593, 593, 593, 593, 593,
  140614. /* 170 */ 593, 593, 593, 593, 593, 593, 593, 593, 593, 593,
  140615. /* 180 */ 593, 593, 593, 593, 607, 607, 593, 721, 805, 805,
  140616. /* 190 */ 446, 851, 851, 446, 190, 979, 2142, 2142, 2142, 453,
  140617. /* 200 */ 45, 45, 480, 490, 484, 385, 575, 502, 551, 581,
  140618. /* 210 */ 593, 593, 593, 593, 593, 593, 593, 593, 593, 689,
  140619. /* 220 */ 593, 593, 593, 593, 593, 593, 593, 593, 593, 593,
  140620. /* 230 */ 593, 593, 582, 582, 582, 593, 593, 593, 593, 771,
  140621. /* 240 */ 593, 593, 593, 59, 764, 593, 593, 863, 593, 593,
  140622. /* 250 */ 593, 593, 593, 593, 593, 593, 665, 819, 580, 16,
  140623. /* 260 */ 16, 16, 16, 1119, 580, 580, 967, 321, 931, 1042,
  140624. /* 270 */ 1077, 783, 783, 834, 1077, 1077, 834, 1121, 1195, 401,
  140625. /* 280 */ 1142, 1142, 1142, 783, 787, 787, 1074, 1191, 1092, 1205,
  140626. /* 290 */ 1354, 1284, 1284, 1381, 1381, 1284, 1297, 1334, 1421, 1407,
  140627. /* 300 */ 1322, 1447, 1447, 1447, 1447, 1284, 1452, 1322, 1322, 1334,
  140628. /* 310 */ 1421, 1407, 1407, 1322, 1284, 1452, 1345, 1434, 1284, 1452,
  140629. /* 320 */ 1483, 1284, 1452, 1284, 1452, 1483, 1404, 1404, 1404, 1451,
  140630. /* 330 */ 1483, 1404, 1400, 1404, 1451, 1404, 1404, 1483, 1419, 1419,
  140631. /* 340 */ 1483, 1406, 1436, 1406, 1436, 1406, 1436, 1406, 1436, 1284,
  140632. /* 350 */ 1457, 1457, 1408, 1414, 1534, 1284, 1412, 1408, 1425, 1431,
  140633. /* 360 */ 1322, 1555, 1559, 1574, 1574, 1588, 1588, 1588, 2142, 2142,
  140634. /* 370 */ 2142, 2142, 2142, 2142, 2142, 2142, 2142, 2142, 2142, 2142,
  140635. /* 380 */ 2142, 2142, 2142, 378, 777, 836, 971, 825, 775, 983,
  140636. /* 390 */ 1208, 1179, 1217, 1120, 1220, 1206, 1221, 1222, 1226, 1227,
  140637. /* 400 */ 1228, 1233, 937, 1147, 1261, 1149, 1207, 1248, 1249, 1253,
  140638. /* 410 */ 1133, 1151, 1274, 1293, 1211, 1236, 1605, 1607, 1589, 1458,
  140639. /* 420 */ 1599, 1525, 1604, 1600, 1602, 1490, 1492, 1503, 1612, 1504,
  140640. /* 430 */ 1618, 1510, 1624, 1640, 1513, 1506, 1528, 1593, 1619, 1514,
  140641. /* 440 */ 1606, 1608, 1610, 1613, 1535, 1551, 1631, 1533, 1667, 1665,
  140642. /* 450 */ 1649, 1565, 1521, 1609, 1650, 1611, 1603, 1634, 1546, 1573,
  140643. /* 460 */ 1658, 1663, 1666, 1560, 1568, 1668, 1620, 1669, 1671, 1672,
  140644. /* 470 */ 1674, 1621, 1661, 1675, 1627, 1662, 1677, 1556, 1679, 1680,
  140645. /* 480 */ 1548, 1683, 1684, 1682, 1686, 1689, 1688, 1691, 1694, 1693,
  140646. /* 490 */ 1584, 1696, 1698, 1617, 1695, 1706, 1594, 1705, 1701, 1702,
  140647. /* 500 */ 1704, 1707, 1647, 1670, 1654, 1708, 1673, 1656, 1715, 1727,
  140648. /* 510 */ 1729, 1730, 1731, 1733, 1719, 1732, 1705, 1737, 1738, 1742,
  140649. /* 520 */ 1743, 1741, 1745, 1734, 1758, 1748, 1749, 1750, 1752, 1754,
  140650. /* 530 */ 1755, 1746, 1655, 1653, 1657, 1659, 1660, 1761, 1773, 1788,
  140651. };
  140652. #define YY_REDUCE_COUNT (382)
  140653. #define YY_REDUCE_MIN (-260)
  140654. #define YY_REDUCE_MAX (1420)
  140655. static const short yy_reduce_ofst[] = {
  140656. /* 0 */ -170, -18, -159, 309, 313, -167, -19, 75, 117, 211,
  140657. /* 10 */ 315, 317, -165, -195, -168, -260, 389, 437, 475, 524,
  140658. /* 20 */ 527, -169, 529, 531, -28, 80, 534, 239, 304, 412,
  140659. /* 30 */ 558, 577, 37, 120, 368, -22, 460, 517, 555, 560,
  140660. /* 40 */ 562, 586, -257, -257, -257, -257, -257, -257, -257, -257,
  140661. /* 50 */ -257, -257, -257, -257, -257, -257, -257, -257, -257, -257,
  140662. /* 60 */ -257, -257, -257, -257, -257, -257, -257, -257, -257, -257,
  140663. /* 70 */ -257, -257, -257, -257, -257, -257, -257, -172, 457, 628,
  140664. /* 80 */ 673, 692, 694, 702, 704, 722, 728, 740, 743, 748,
  140665. /* 90 */ 767, 791, 815, 818, 820, 822, 857, 861, 864, 866,
  140666. /* 100 */ 868, 870, 872, 874, 876, 881, 900, 902, 906, 908,
  140667. /* 110 */ 910, 912, 915, 917, 920, 960, 962, 964, 988, 990,
  140668. /* 120 */ 992, 1016, 1029, 1032, -257, -257, -257, -257, -257, -257,
  140669. /* 130 */ -257, -257, -257, 271, 618, -190, 68, 60, 240, -124,
  140670. /* 140 */ 603, 610, 603, 610, 12, -257, -257, -257, -257, -128,
  140671. /* 150 */ -128, -128, -142, 25, 270, 281, 333, 124, 236, 648,
  140672. /* 160 */ 374, 465, 465, 28, 598, 792, 839, 469, 38, 381,
  140673. /* 170 */ 622, 709, 173, 699, 522, 703, 808, 811, 867, 816,
  140674. /* 180 */ -104, 823, -3, 875, 649, 753, 323, -88, 882, 884,
  140675. /* 190 */ 518, 43, 325, 899, 763, 604, 879, 969, 402, -193,
  140676. /* 200 */ -189, -180, -151, -55, 69, 104, 141, 259, 286, 360,
  140677. /* 210 */ 364, 455, 474, 481, 510, 516, 611, 653, 788, 99,
  140678. /* 220 */ 871, 878, 995, 1009, 1049, 1081, 1115, 1134, 1136, 1138,
  140679. /* 230 */ 1139, 1140, 733, 1110, 1112, 1144, 1145, 1146, 1148, 1084,
  140680. /* 240 */ 1161, 1162, 1163, 1089, 1047, 1165, 1166, 1127, 1169, 104,
  140681. /* 250 */ 1181, 1182, 1183, 1184, 1185, 1187, 1098, 1100, 1150, 1131,
  140682. /* 260 */ 1132, 1135, 1141, 1084, 1150, 1150, 1152, 1173, 1196, 1097,
  140683. /* 270 */ 1153, 1143, 1167, 1103, 1154, 1155, 1104, 1176, 1174, 1199,
  140684. /* 280 */ 1178, 1186, 1188, 1168, 1158, 1160, 1170, 1159, 1201, 1230,
  140685. /* 290 */ 1156, 1243, 1244, 1157, 1164, 1247, 1172, 1189, 1192, 1240,
  140686. /* 300 */ 1231, 1241, 1242, 1256, 1257, 1278, 1294, 1251, 1252, 1232,
  140687. /* 310 */ 1234, 1265, 1266, 1259, 1301, 1303, 1223, 1225, 1307, 1313,
  140688. /* 320 */ 1295, 1317, 1319, 1320, 1323, 1299, 1306, 1308, 1309, 1305,
  140689. /* 330 */ 1311, 1315, 1314, 1321, 1312, 1324, 1326, 1327, 1263, 1271,
  140690. /* 340 */ 1331, 1296, 1298, 1300, 1302, 1304, 1310, 1316, 1318, 1357,
  140691. /* 350 */ 1255, 1260, 1329, 1325, 1332, 1370, 1333, 1338, 1341, 1343,
  140692. /* 360 */ 1346, 1390, 1393, 1403, 1405, 1416, 1417, 1418, 1328, 1330,
  140693. /* 370 */ 1335, 1409, 1394, 1399, 1401, 1402, 1410, 1391, 1396, 1411,
  140694. /* 380 */ 1420, 1413, 1415,
  140695. };
  140696. static const YYACTIONTYPE yy_default[] = {
  140697. /* 0 */ 1537, 1537, 1537, 1377, 1159, 1266, 1159, 1159, 1159, 1377,
  140698. /* 10 */ 1377, 1377, 1159, 1296, 1296, 1430, 1190, 1159, 1159, 1159,
  140699. /* 20 */ 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1376, 1159, 1159,
  140700. /* 30 */ 1159, 1159, 1460, 1460, 1159, 1159, 1159, 1159, 1159, 1159,
  140701. /* 40 */ 1159, 1159, 1159, 1302, 1159, 1159, 1159, 1159, 1159, 1378,
  140702. /* 50 */ 1379, 1159, 1159, 1159, 1429, 1431, 1394, 1312, 1311, 1310,
  140703. /* 60 */ 1309, 1412, 1283, 1307, 1300, 1304, 1372, 1373, 1371, 1375,
  140704. /* 70 */ 1379, 1378, 1159, 1303, 1343, 1357, 1342, 1159, 1159, 1159,
  140705. /* 80 */ 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159,
  140706. /* 90 */ 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159,
  140707. /* 100 */ 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159,
  140708. /* 110 */ 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159,
  140709. /* 120 */ 1159, 1159, 1159, 1159, 1351, 1356, 1362, 1355, 1352, 1345,
  140710. /* 130 */ 1344, 1346, 1347, 1159, 1180, 1230, 1159, 1159, 1159, 1159,
  140711. /* 140 */ 1448, 1447, 1159, 1159, 1190, 1348, 1349, 1359, 1358, 1437,
  140712. /* 150 */ 1493, 1492, 1395, 1159, 1159, 1159, 1159, 1159, 1159, 1460,
  140713. /* 160 */ 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159,
  140714. /* 170 */ 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159,
  140715. /* 180 */ 1159, 1159, 1159, 1159, 1460, 1460, 1159, 1190, 1460, 1460,
  140716. /* 190 */ 1186, 1337, 1336, 1186, 1290, 1159, 1443, 1266, 1257, 1159,
  140717. /* 200 */ 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159,
  140718. /* 210 */ 1159, 1159, 1159, 1434, 1432, 1159, 1159, 1159, 1159, 1159,
  140719. /* 220 */ 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159,
  140720. /* 230 */ 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159,
  140721. /* 240 */ 1159, 1159, 1159, 1262, 1159, 1159, 1159, 1159, 1159, 1159,
  140722. /* 250 */ 1159, 1159, 1159, 1159, 1159, 1487, 1159, 1407, 1244, 1262,
  140723. /* 260 */ 1262, 1262, 1262, 1264, 1245, 1243, 1256, 1191, 1166, 1529,
  140724. /* 270 */ 1306, 1285, 1285, 1526, 1306, 1306, 1526, 1205, 1507, 1202,
  140725. /* 280 */ 1296, 1296, 1296, 1285, 1290, 1290, 1374, 1263, 1256, 1159,
  140726. /* 290 */ 1529, 1271, 1271, 1528, 1528, 1271, 1395, 1315, 1321, 1233,
  140727. /* 300 */ 1306, 1239, 1239, 1239, 1239, 1271, 1177, 1306, 1306, 1315,
  140728. /* 310 */ 1321, 1233, 1233, 1306, 1271, 1177, 1411, 1523, 1271, 1177,
  140729. /* 320 */ 1385, 1271, 1177, 1271, 1177, 1385, 1231, 1231, 1231, 1220,
  140730. /* 330 */ 1385, 1231, 1205, 1231, 1220, 1231, 1231, 1385, 1389, 1389,
  140731. /* 340 */ 1385, 1289, 1284, 1289, 1284, 1289, 1284, 1289, 1284, 1271,
  140732. /* 350 */ 1470, 1470, 1301, 1290, 1380, 1271, 1159, 1301, 1299, 1297,
  140733. /* 360 */ 1306, 1183, 1223, 1490, 1490, 1486, 1486, 1486, 1534, 1534,
  140734. /* 370 */ 1443, 1502, 1190, 1190, 1190, 1190, 1502, 1207, 1207, 1191,
  140735. /* 380 */ 1191, 1190, 1502, 1159, 1159, 1159, 1159, 1159, 1159, 1497,
  140736. /* 390 */ 1159, 1396, 1275, 1159, 1159, 1159, 1159, 1159, 1159, 1159,
  140737. /* 400 */ 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159,
  140738. /* 410 */ 1159, 1159, 1159, 1159, 1159, 1326, 1159, 1162, 1440, 1159,
  140739. /* 420 */ 1159, 1438, 1159, 1159, 1159, 1159, 1159, 1159, 1276, 1159,
  140740. /* 430 */ 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159,
  140741. /* 440 */ 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1525, 1159, 1159,
  140742. /* 450 */ 1159, 1159, 1159, 1159, 1410, 1409, 1159, 1159, 1273, 1159,
  140743. /* 460 */ 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159,
  140744. /* 470 */ 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159,
  140745. /* 480 */ 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159,
  140746. /* 490 */ 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1298, 1159, 1159,
  140747. /* 500 */ 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159,
  140748. /* 510 */ 1159, 1159, 1475, 1291, 1159, 1159, 1516, 1159, 1159, 1159,
  140749. /* 520 */ 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159,
  140750. /* 530 */ 1159, 1511, 1247, 1328, 1159, 1327, 1331, 1159, 1171, 1159,
  140751. };
  140752. /********** End of lemon-generated parsing tables *****************************/
  140753. /* The next table maps tokens (terminal symbols) into fallback tokens.
  140754. ** If a construct like the following:
  140755. **
  140756. ** %fallback ID X Y Z.
  140757. **
  140758. ** appears in the grammar, then ID becomes a fallback token for X, Y,
  140759. ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser
  140760. ** but it does not parse, the type of the token is changed to ID and
  140761. ** the parse is retried before an error is thrown.
  140762. **
  140763. ** This feature can be used, for example, to cause some keywords in a language
  140764. ** to revert to identifiers if they keyword does not apply in the context where
  140765. ** it appears.
  140766. */
  140767. #ifdef YYFALLBACK
  140768. static const YYCODETYPE yyFallback[] = {
  140769. 0, /* $ => nothing */
  140770. 0, /* SEMI => nothing */
  140771. 59, /* EXPLAIN => ID */
  140772. 59, /* QUERY => ID */
  140773. 59, /* PLAN => ID */
  140774. 59, /* BEGIN => ID */
  140775. 0, /* TRANSACTION => nothing */
  140776. 59, /* DEFERRED => ID */
  140777. 59, /* IMMEDIATE => ID */
  140778. 59, /* EXCLUSIVE => ID */
  140779. 0, /* COMMIT => nothing */
  140780. 59, /* END => ID */
  140781. 59, /* ROLLBACK => ID */
  140782. 59, /* SAVEPOINT => ID */
  140783. 59, /* RELEASE => ID */
  140784. 0, /* TO => nothing */
  140785. 0, /* TABLE => nothing */
  140786. 0, /* CREATE => nothing */
  140787. 59, /* IF => ID */
  140788. 0, /* NOT => nothing */
  140789. 0, /* EXISTS => nothing */
  140790. 59, /* TEMP => ID */
  140791. 0, /* LP => nothing */
  140792. 0, /* RP => nothing */
  140793. 0, /* AS => nothing */
  140794. 59, /* WITHOUT => ID */
  140795. 0, /* COMMA => nothing */
  140796. 59, /* ABORT => ID */
  140797. 59, /* ACTION => ID */
  140798. 59, /* AFTER => ID */
  140799. 59, /* ANALYZE => ID */
  140800. 59, /* ASC => ID */
  140801. 59, /* ATTACH => ID */
  140802. 59, /* BEFORE => ID */
  140803. 59, /* BY => ID */
  140804. 59, /* CASCADE => ID */
  140805. 59, /* CAST => ID */
  140806. 59, /* CONFLICT => ID */
  140807. 59, /* DATABASE => ID */
  140808. 59, /* DESC => ID */
  140809. 59, /* DETACH => ID */
  140810. 59, /* EACH => ID */
  140811. 59, /* FAIL => ID */
  140812. 0, /* OR => nothing */
  140813. 0, /* AND => nothing */
  140814. 0, /* IS => nothing */
  140815. 59, /* MATCH => ID */
  140816. 59, /* LIKE_KW => ID */
  140817. 0, /* BETWEEN => nothing */
  140818. 0, /* IN => nothing */
  140819. 0, /* ISNULL => nothing */
  140820. 0, /* NOTNULL => nothing */
  140821. 0, /* NE => nothing */
  140822. 0, /* EQ => nothing */
  140823. 0, /* GT => nothing */
  140824. 0, /* LE => nothing */
  140825. 0, /* LT => nothing */
  140826. 0, /* GE => nothing */
  140827. 0, /* ESCAPE => nothing */
  140828. 0, /* ID => nothing */
  140829. 59, /* COLUMNKW => ID */
  140830. 59, /* DO => ID */
  140831. 59, /* FOR => ID */
  140832. 59, /* IGNORE => ID */
  140833. 59, /* INITIALLY => ID */
  140834. 59, /* INSTEAD => ID */
  140835. 59, /* NO => ID */
  140836. 59, /* KEY => ID */
  140837. 59, /* OF => ID */
  140838. 59, /* OFFSET => ID */
  140839. 59, /* PRAGMA => ID */
  140840. 59, /* RAISE => ID */
  140841. 59, /* RECURSIVE => ID */
  140842. 59, /* REPLACE => ID */
  140843. 59, /* RESTRICT => ID */
  140844. 59, /* ROW => ID */
  140845. 59, /* ROWS => ID */
  140846. 59, /* TRIGGER => ID */
  140847. 59, /* VACUUM => ID */
  140848. 59, /* VIEW => ID */
  140849. 59, /* VIRTUAL => ID */
  140850. 59, /* WITH => ID */
  140851. 59, /* CURRENT => ID */
  140852. 59, /* FOLLOWING => ID */
  140853. 59, /* PARTITION => ID */
  140854. 59, /* PRECEDING => ID */
  140855. 59, /* RANGE => ID */
  140856. 59, /* UNBOUNDED => ID */
  140857. 59, /* EXCLUDE => ID */
  140858. 59, /* GROUPS => ID */
  140859. 59, /* OTHERS => ID */
  140860. 59, /* TIES => ID */
  140861. 59, /* REINDEX => ID */
  140862. 59, /* RENAME => ID */
  140863. 59, /* CTIME_KW => ID */
  140864. };
  140865. #endif /* YYFALLBACK */
  140866. /* The following structure represents a single element of the
  140867. ** parser's stack. Information stored includes:
  140868. **
  140869. ** + The state number for the parser at this level of the stack.
  140870. **
  140871. ** + The value of the token stored at this level of the stack.
  140872. ** (In other words, the "major" token.)
  140873. **
  140874. ** + The semantic value stored at this level of the stack. This is
  140875. ** the information used by the action routines in the grammar.
  140876. ** It is sometimes called the "minor" token.
  140877. **
  140878. ** After the "shift" half of a SHIFTREDUCE action, the stateno field
  140879. ** actually contains the reduce action for the second half of the
  140880. ** SHIFTREDUCE.
  140881. */
  140882. struct yyStackEntry {
  140883. YYACTIONTYPE stateno; /* The state-number, or reduce action in SHIFTREDUCE */
  140884. YYCODETYPE major; /* The major token value. This is the code
  140885. ** number for the token at this stack level */
  140886. YYMINORTYPE minor; /* The user-supplied minor token value. This
  140887. ** is the value of the token */
  140888. };
  140889. typedef struct yyStackEntry yyStackEntry;
  140890. /* The state of the parser is completely contained in an instance of
  140891. ** the following structure */
  140892. struct yyParser {
  140893. yyStackEntry *yytos; /* Pointer to top element of the stack */
  140894. #ifdef YYTRACKMAXSTACKDEPTH
  140895. int yyhwm; /* High-water mark of the stack */
  140896. #endif
  140897. #ifndef YYNOERRORRECOVERY
  140898. int yyerrcnt; /* Shifts left before out of the error */
  140899. #endif
  140900. sqlite3ParserARG_SDECL /* A place to hold %extra_argument */
  140901. sqlite3ParserCTX_SDECL /* A place to hold %extra_context */
  140902. #if YYSTACKDEPTH<=0
  140903. int yystksz; /* Current side of the stack */
  140904. yyStackEntry *yystack; /* The parser's stack */
  140905. yyStackEntry yystk0; /* First stack entry */
  140906. #else
  140907. yyStackEntry yystack[YYSTACKDEPTH]; /* The parser's stack */
  140908. yyStackEntry *yystackEnd; /* Last entry in the stack */
  140909. #endif
  140910. };
  140911. typedef struct yyParser yyParser;
  140912. #ifndef NDEBUG
  140913. /* #include <stdio.h> */
  140914. static FILE *yyTraceFILE = 0;
  140915. static char *yyTracePrompt = 0;
  140916. #endif /* NDEBUG */
  140917. #ifndef NDEBUG
  140918. /*
  140919. ** Turn parser tracing on by giving a stream to which to write the trace
  140920. ** and a prompt to preface each trace message. Tracing is turned off
  140921. ** by making either argument NULL
  140922. **
  140923. ** Inputs:
  140924. ** <ul>
  140925. ** <li> A FILE* to which trace output should be written.
  140926. ** If NULL, then tracing is turned off.
  140927. ** <li> A prefix string written at the beginning of every
  140928. ** line of trace output. If NULL, then tracing is
  140929. ** turned off.
  140930. ** </ul>
  140931. **
  140932. ** Outputs:
  140933. ** None.
  140934. */
  140935. SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
  140936. yyTraceFILE = TraceFILE;
  140937. yyTracePrompt = zTracePrompt;
  140938. if( yyTraceFILE==0 ) yyTracePrompt = 0;
  140939. else if( yyTracePrompt==0 ) yyTraceFILE = 0;
  140940. }
  140941. #endif /* NDEBUG */
  140942. #if defined(YYCOVERAGE) || !defined(NDEBUG)
  140943. /* For tracing shifts, the names of all terminals and nonterminals
  140944. ** are required. The following table supplies these names */
  140945. static const char *const yyTokenName[] = {
  140946. /* 0 */ "$",
  140947. /* 1 */ "SEMI",
  140948. /* 2 */ "EXPLAIN",
  140949. /* 3 */ "QUERY",
  140950. /* 4 */ "PLAN",
  140951. /* 5 */ "BEGIN",
  140952. /* 6 */ "TRANSACTION",
  140953. /* 7 */ "DEFERRED",
  140954. /* 8 */ "IMMEDIATE",
  140955. /* 9 */ "EXCLUSIVE",
  140956. /* 10 */ "COMMIT",
  140957. /* 11 */ "END",
  140958. /* 12 */ "ROLLBACK",
  140959. /* 13 */ "SAVEPOINT",
  140960. /* 14 */ "RELEASE",
  140961. /* 15 */ "TO",
  140962. /* 16 */ "TABLE",
  140963. /* 17 */ "CREATE",
  140964. /* 18 */ "IF",
  140965. /* 19 */ "NOT",
  140966. /* 20 */ "EXISTS",
  140967. /* 21 */ "TEMP",
  140968. /* 22 */ "LP",
  140969. /* 23 */ "RP",
  140970. /* 24 */ "AS",
  140971. /* 25 */ "WITHOUT",
  140972. /* 26 */ "COMMA",
  140973. /* 27 */ "ABORT",
  140974. /* 28 */ "ACTION",
  140975. /* 29 */ "AFTER",
  140976. /* 30 */ "ANALYZE",
  140977. /* 31 */ "ASC",
  140978. /* 32 */ "ATTACH",
  140979. /* 33 */ "BEFORE",
  140980. /* 34 */ "BY",
  140981. /* 35 */ "CASCADE",
  140982. /* 36 */ "CAST",
  140983. /* 37 */ "CONFLICT",
  140984. /* 38 */ "DATABASE",
  140985. /* 39 */ "DESC",
  140986. /* 40 */ "DETACH",
  140987. /* 41 */ "EACH",
  140988. /* 42 */ "FAIL",
  140989. /* 43 */ "OR",
  140990. /* 44 */ "AND",
  140991. /* 45 */ "IS",
  140992. /* 46 */ "MATCH",
  140993. /* 47 */ "LIKE_KW",
  140994. /* 48 */ "BETWEEN",
  140995. /* 49 */ "IN",
  140996. /* 50 */ "ISNULL",
  140997. /* 51 */ "NOTNULL",
  140998. /* 52 */ "NE",
  140999. /* 53 */ "EQ",
  141000. /* 54 */ "GT",
  141001. /* 55 */ "LE",
  141002. /* 56 */ "LT",
  141003. /* 57 */ "GE",
  141004. /* 58 */ "ESCAPE",
  141005. /* 59 */ "ID",
  141006. /* 60 */ "COLUMNKW",
  141007. /* 61 */ "DO",
  141008. /* 62 */ "FOR",
  141009. /* 63 */ "IGNORE",
  141010. /* 64 */ "INITIALLY",
  141011. /* 65 */ "INSTEAD",
  141012. /* 66 */ "NO",
  141013. /* 67 */ "KEY",
  141014. /* 68 */ "OF",
  141015. /* 69 */ "OFFSET",
  141016. /* 70 */ "PRAGMA",
  141017. /* 71 */ "RAISE",
  141018. /* 72 */ "RECURSIVE",
  141019. /* 73 */ "REPLACE",
  141020. /* 74 */ "RESTRICT",
  141021. /* 75 */ "ROW",
  141022. /* 76 */ "ROWS",
  141023. /* 77 */ "TRIGGER",
  141024. /* 78 */ "VACUUM",
  141025. /* 79 */ "VIEW",
  141026. /* 80 */ "VIRTUAL",
  141027. /* 81 */ "WITH",
  141028. /* 82 */ "CURRENT",
  141029. /* 83 */ "FOLLOWING",
  141030. /* 84 */ "PARTITION",
  141031. /* 85 */ "PRECEDING",
  141032. /* 86 */ "RANGE",
  141033. /* 87 */ "UNBOUNDED",
  141034. /* 88 */ "EXCLUDE",
  141035. /* 89 */ "GROUPS",
  141036. /* 90 */ "OTHERS",
  141037. /* 91 */ "TIES",
  141038. /* 92 */ "REINDEX",
  141039. /* 93 */ "RENAME",
  141040. /* 94 */ "CTIME_KW",
  141041. /* 95 */ "ANY",
  141042. /* 96 */ "BITAND",
  141043. /* 97 */ "BITOR",
  141044. /* 98 */ "LSHIFT",
  141045. /* 99 */ "RSHIFT",
  141046. /* 100 */ "PLUS",
  141047. /* 101 */ "MINUS",
  141048. /* 102 */ "STAR",
  141049. /* 103 */ "SLASH",
  141050. /* 104 */ "REM",
  141051. /* 105 */ "CONCAT",
  141052. /* 106 */ "COLLATE",
  141053. /* 107 */ "BITNOT",
  141054. /* 108 */ "ON",
  141055. /* 109 */ "INDEXED",
  141056. /* 110 */ "STRING",
  141057. /* 111 */ "JOIN_KW",
  141058. /* 112 */ "CONSTRAINT",
  141059. /* 113 */ "DEFAULT",
  141060. /* 114 */ "NULL",
  141061. /* 115 */ "PRIMARY",
  141062. /* 116 */ "UNIQUE",
  141063. /* 117 */ "CHECK",
  141064. /* 118 */ "REFERENCES",
  141065. /* 119 */ "AUTOINCR",
  141066. /* 120 */ "INSERT",
  141067. /* 121 */ "DELETE",
  141068. /* 122 */ "UPDATE",
  141069. /* 123 */ "SET",
  141070. /* 124 */ "DEFERRABLE",
  141071. /* 125 */ "FOREIGN",
  141072. /* 126 */ "DROP",
  141073. /* 127 */ "UNION",
  141074. /* 128 */ "ALL",
  141075. /* 129 */ "EXCEPT",
  141076. /* 130 */ "INTERSECT",
  141077. /* 131 */ "SELECT",
  141078. /* 132 */ "VALUES",
  141079. /* 133 */ "DISTINCT",
  141080. /* 134 */ "DOT",
  141081. /* 135 */ "FROM",
  141082. /* 136 */ "JOIN",
  141083. /* 137 */ "USING",
  141084. /* 138 */ "ORDER",
  141085. /* 139 */ "GROUP",
  141086. /* 140 */ "HAVING",
  141087. /* 141 */ "LIMIT",
  141088. /* 142 */ "WHERE",
  141089. /* 143 */ "INTO",
  141090. /* 144 */ "NOTHING",
  141091. /* 145 */ "FLOAT",
  141092. /* 146 */ "BLOB",
  141093. /* 147 */ "INTEGER",
  141094. /* 148 */ "VARIABLE",
  141095. /* 149 */ "CASE",
  141096. /* 150 */ "WHEN",
  141097. /* 151 */ "THEN",
  141098. /* 152 */ "ELSE",
  141099. /* 153 */ "INDEX",
  141100. /* 154 */ "ALTER",
  141101. /* 155 */ "ADD",
  141102. /* 156 */ "WINDOW",
  141103. /* 157 */ "OVER",
  141104. /* 158 */ "FILTER",
  141105. /* 159 */ "TRUEFALSE",
  141106. /* 160 */ "ISNOT",
  141107. /* 161 */ "FUNCTION",
  141108. /* 162 */ "COLUMN",
  141109. /* 163 */ "AGG_FUNCTION",
  141110. /* 164 */ "AGG_COLUMN",
  141111. /* 165 */ "UMINUS",
  141112. /* 166 */ "UPLUS",
  141113. /* 167 */ "TRUTH",
  141114. /* 168 */ "REGISTER",
  141115. /* 169 */ "VECTOR",
  141116. /* 170 */ "SELECT_COLUMN",
  141117. /* 171 */ "IF_NULL_ROW",
  141118. /* 172 */ "ASTERISK",
  141119. /* 173 */ "SPAN",
  141120. /* 174 */ "SPACE",
  141121. /* 175 */ "ILLEGAL",
  141122. /* 176 */ "input",
  141123. /* 177 */ "cmdlist",
  141124. /* 178 */ "ecmd",
  141125. /* 179 */ "cmdx",
  141126. /* 180 */ "explain",
  141127. /* 181 */ "cmd",
  141128. /* 182 */ "transtype",
  141129. /* 183 */ "trans_opt",
  141130. /* 184 */ "nm",
  141131. /* 185 */ "savepoint_opt",
  141132. /* 186 */ "create_table",
  141133. /* 187 */ "create_table_args",
  141134. /* 188 */ "createkw",
  141135. /* 189 */ "temp",
  141136. /* 190 */ "ifnotexists",
  141137. /* 191 */ "dbnm",
  141138. /* 192 */ "columnlist",
  141139. /* 193 */ "conslist_opt",
  141140. /* 194 */ "table_options",
  141141. /* 195 */ "select",
  141142. /* 196 */ "columnname",
  141143. /* 197 */ "carglist",
  141144. /* 198 */ "typetoken",
  141145. /* 199 */ "typename",
  141146. /* 200 */ "signed",
  141147. /* 201 */ "plus_num",
  141148. /* 202 */ "minus_num",
  141149. /* 203 */ "scanpt",
  141150. /* 204 */ "scantok",
  141151. /* 205 */ "ccons",
  141152. /* 206 */ "term",
  141153. /* 207 */ "expr",
  141154. /* 208 */ "onconf",
  141155. /* 209 */ "sortorder",
  141156. /* 210 */ "autoinc",
  141157. /* 211 */ "eidlist_opt",
  141158. /* 212 */ "refargs",
  141159. /* 213 */ "defer_subclause",
  141160. /* 214 */ "refarg",
  141161. /* 215 */ "refact",
  141162. /* 216 */ "init_deferred_pred_opt",
  141163. /* 217 */ "conslist",
  141164. /* 218 */ "tconscomma",
  141165. /* 219 */ "tcons",
  141166. /* 220 */ "sortlist",
  141167. /* 221 */ "eidlist",
  141168. /* 222 */ "defer_subclause_opt",
  141169. /* 223 */ "orconf",
  141170. /* 224 */ "resolvetype",
  141171. /* 225 */ "raisetype",
  141172. /* 226 */ "ifexists",
  141173. /* 227 */ "fullname",
  141174. /* 228 */ "selectnowith",
  141175. /* 229 */ "oneselect",
  141176. /* 230 */ "wqlist",
  141177. /* 231 */ "multiselect_op",
  141178. /* 232 */ "distinct",
  141179. /* 233 */ "selcollist",
  141180. /* 234 */ "from",
  141181. /* 235 */ "where_opt",
  141182. /* 236 */ "groupby_opt",
  141183. /* 237 */ "having_opt",
  141184. /* 238 */ "orderby_opt",
  141185. /* 239 */ "limit_opt",
  141186. /* 240 */ "window_clause",
  141187. /* 241 */ "values",
  141188. /* 242 */ "nexprlist",
  141189. /* 243 */ "sclp",
  141190. /* 244 */ "as",
  141191. /* 245 */ "seltablist",
  141192. /* 246 */ "stl_prefix",
  141193. /* 247 */ "joinop",
  141194. /* 248 */ "indexed_opt",
  141195. /* 249 */ "on_opt",
  141196. /* 250 */ "using_opt",
  141197. /* 251 */ "exprlist",
  141198. /* 252 */ "xfullname",
  141199. /* 253 */ "idlist",
  141200. /* 254 */ "with",
  141201. /* 255 */ "setlist",
  141202. /* 256 */ "insert_cmd",
  141203. /* 257 */ "idlist_opt",
  141204. /* 258 */ "upsert",
  141205. /* 259 */ "over_clause",
  141206. /* 260 */ "likeop",
  141207. /* 261 */ "between_op",
  141208. /* 262 */ "in_op",
  141209. /* 263 */ "paren_exprlist",
  141210. /* 264 */ "case_operand",
  141211. /* 265 */ "case_exprlist",
  141212. /* 266 */ "case_else",
  141213. /* 267 */ "uniqueflag",
  141214. /* 268 */ "collate",
  141215. /* 269 */ "vinto",
  141216. /* 270 */ "nmnum",
  141217. /* 271 */ "trigger_decl",
  141218. /* 272 */ "trigger_cmd_list",
  141219. /* 273 */ "trigger_time",
  141220. /* 274 */ "trigger_event",
  141221. /* 275 */ "foreach_clause",
  141222. /* 276 */ "when_clause",
  141223. /* 277 */ "trigger_cmd",
  141224. /* 278 */ "trnm",
  141225. /* 279 */ "tridxby",
  141226. /* 280 */ "database_kw_opt",
  141227. /* 281 */ "key_opt",
  141228. /* 282 */ "add_column_fullname",
  141229. /* 283 */ "kwcolumn_opt",
  141230. /* 284 */ "create_vtab",
  141231. /* 285 */ "vtabarglist",
  141232. /* 286 */ "vtabarg",
  141233. /* 287 */ "vtabargtoken",
  141234. /* 288 */ "lp",
  141235. /* 289 */ "anylist",
  141236. /* 290 */ "windowdefn_list",
  141237. /* 291 */ "windowdefn",
  141238. /* 292 */ "window",
  141239. /* 293 */ "frame_opt",
  141240. /* 294 */ "part_opt",
  141241. /* 295 */ "filter_opt",
  141242. /* 296 */ "range_or_rows",
  141243. /* 297 */ "frame_bound",
  141244. /* 298 */ "frame_bound_s",
  141245. /* 299 */ "frame_bound_e",
  141246. /* 300 */ "frame_exclude_opt",
  141247. /* 301 */ "frame_exclude",
  141248. };
  141249. #endif /* defined(YYCOVERAGE) || !defined(NDEBUG) */
  141250. #ifndef NDEBUG
  141251. /* For tracing reduce actions, the names of all rules are required.
  141252. */
  141253. static const char *const yyRuleName[] = {
  141254. /* 0 */ "explain ::= EXPLAIN",
  141255. /* 1 */ "explain ::= EXPLAIN QUERY PLAN",
  141256. /* 2 */ "cmdx ::= cmd",
  141257. /* 3 */ "cmd ::= BEGIN transtype trans_opt",
  141258. /* 4 */ "transtype ::=",
  141259. /* 5 */ "transtype ::= DEFERRED",
  141260. /* 6 */ "transtype ::= IMMEDIATE",
  141261. /* 7 */ "transtype ::= EXCLUSIVE",
  141262. /* 8 */ "cmd ::= COMMIT|END trans_opt",
  141263. /* 9 */ "cmd ::= ROLLBACK trans_opt",
  141264. /* 10 */ "cmd ::= SAVEPOINT nm",
  141265. /* 11 */ "cmd ::= RELEASE savepoint_opt nm",
  141266. /* 12 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
  141267. /* 13 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
  141268. /* 14 */ "createkw ::= CREATE",
  141269. /* 15 */ "ifnotexists ::=",
  141270. /* 16 */ "ifnotexists ::= IF NOT EXISTS",
  141271. /* 17 */ "temp ::= TEMP",
  141272. /* 18 */ "temp ::=",
  141273. /* 19 */ "create_table_args ::= LP columnlist conslist_opt RP table_options",
  141274. /* 20 */ "create_table_args ::= AS select",
  141275. /* 21 */ "table_options ::=",
  141276. /* 22 */ "table_options ::= WITHOUT nm",
  141277. /* 23 */ "columnname ::= nm typetoken",
  141278. /* 24 */ "typetoken ::=",
  141279. /* 25 */ "typetoken ::= typename LP signed RP",
  141280. /* 26 */ "typetoken ::= typename LP signed COMMA signed RP",
  141281. /* 27 */ "typename ::= typename ID|STRING",
  141282. /* 28 */ "scanpt ::=",
  141283. /* 29 */ "scantok ::=",
  141284. /* 30 */ "ccons ::= CONSTRAINT nm",
  141285. /* 31 */ "ccons ::= DEFAULT scantok term",
  141286. /* 32 */ "ccons ::= DEFAULT LP expr RP",
  141287. /* 33 */ "ccons ::= DEFAULT PLUS scantok term",
  141288. /* 34 */ "ccons ::= DEFAULT MINUS scantok term",
  141289. /* 35 */ "ccons ::= DEFAULT scantok ID|INDEXED",
  141290. /* 36 */ "ccons ::= NOT NULL onconf",
  141291. /* 37 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
  141292. /* 38 */ "ccons ::= UNIQUE onconf",
  141293. /* 39 */ "ccons ::= CHECK LP expr RP",
  141294. /* 40 */ "ccons ::= REFERENCES nm eidlist_opt refargs",
  141295. /* 41 */ "ccons ::= defer_subclause",
  141296. /* 42 */ "ccons ::= COLLATE ID|STRING",
  141297. /* 43 */ "autoinc ::=",
  141298. /* 44 */ "autoinc ::= AUTOINCR",
  141299. /* 45 */ "refargs ::=",
  141300. /* 46 */ "refargs ::= refargs refarg",
  141301. /* 47 */ "refarg ::= MATCH nm",
  141302. /* 48 */ "refarg ::= ON INSERT refact",
  141303. /* 49 */ "refarg ::= ON DELETE refact",
  141304. /* 50 */ "refarg ::= ON UPDATE refact",
  141305. /* 51 */ "refact ::= SET NULL",
  141306. /* 52 */ "refact ::= SET DEFAULT",
  141307. /* 53 */ "refact ::= CASCADE",
  141308. /* 54 */ "refact ::= RESTRICT",
  141309. /* 55 */ "refact ::= NO ACTION",
  141310. /* 56 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
  141311. /* 57 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
  141312. /* 58 */ "init_deferred_pred_opt ::=",
  141313. /* 59 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
  141314. /* 60 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
  141315. /* 61 */ "conslist_opt ::=",
  141316. /* 62 */ "tconscomma ::= COMMA",
  141317. /* 63 */ "tcons ::= CONSTRAINT nm",
  141318. /* 64 */ "tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf",
  141319. /* 65 */ "tcons ::= UNIQUE LP sortlist RP onconf",
  141320. /* 66 */ "tcons ::= CHECK LP expr RP onconf",
  141321. /* 67 */ "tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt",
  141322. /* 68 */ "defer_subclause_opt ::=",
  141323. /* 69 */ "onconf ::=",
  141324. /* 70 */ "onconf ::= ON CONFLICT resolvetype",
  141325. /* 71 */ "orconf ::=",
  141326. /* 72 */ "orconf ::= OR resolvetype",
  141327. /* 73 */ "resolvetype ::= IGNORE",
  141328. /* 74 */ "resolvetype ::= REPLACE",
  141329. /* 75 */ "cmd ::= DROP TABLE ifexists fullname",
  141330. /* 76 */ "ifexists ::= IF EXISTS",
  141331. /* 77 */ "ifexists ::=",
  141332. /* 78 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select",
  141333. /* 79 */ "cmd ::= DROP VIEW ifexists fullname",
  141334. /* 80 */ "cmd ::= select",
  141335. /* 81 */ "select ::= WITH wqlist selectnowith",
  141336. /* 82 */ "select ::= WITH RECURSIVE wqlist selectnowith",
  141337. /* 83 */ "select ::= selectnowith",
  141338. /* 84 */ "selectnowith ::= selectnowith multiselect_op oneselect",
  141339. /* 85 */ "multiselect_op ::= UNION",
  141340. /* 86 */ "multiselect_op ::= UNION ALL",
  141341. /* 87 */ "multiselect_op ::= EXCEPT|INTERSECT",
  141342. /* 88 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
  141343. /* 89 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt window_clause orderby_opt limit_opt",
  141344. /* 90 */ "values ::= VALUES LP nexprlist RP",
  141345. /* 91 */ "values ::= values COMMA LP nexprlist RP",
  141346. /* 92 */ "distinct ::= DISTINCT",
  141347. /* 93 */ "distinct ::= ALL",
  141348. /* 94 */ "distinct ::=",
  141349. /* 95 */ "sclp ::=",
  141350. /* 96 */ "selcollist ::= sclp scanpt expr scanpt as",
  141351. /* 97 */ "selcollist ::= sclp scanpt STAR",
  141352. /* 98 */ "selcollist ::= sclp scanpt nm DOT STAR",
  141353. /* 99 */ "as ::= AS nm",
  141354. /* 100 */ "as ::=",
  141355. /* 101 */ "from ::=",
  141356. /* 102 */ "from ::= FROM seltablist",
  141357. /* 103 */ "stl_prefix ::= seltablist joinop",
  141358. /* 104 */ "stl_prefix ::=",
  141359. /* 105 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
  141360. /* 106 */ "seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt",
  141361. /* 107 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
  141362. /* 108 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
  141363. /* 109 */ "dbnm ::=",
  141364. /* 110 */ "dbnm ::= DOT nm",
  141365. /* 111 */ "fullname ::= nm",
  141366. /* 112 */ "fullname ::= nm DOT nm",
  141367. /* 113 */ "xfullname ::= nm",
  141368. /* 114 */ "xfullname ::= nm DOT nm",
  141369. /* 115 */ "xfullname ::= nm DOT nm AS nm",
  141370. /* 116 */ "xfullname ::= nm AS nm",
  141371. /* 117 */ "joinop ::= COMMA|JOIN",
  141372. /* 118 */ "joinop ::= JOIN_KW JOIN",
  141373. /* 119 */ "joinop ::= JOIN_KW nm JOIN",
  141374. /* 120 */ "joinop ::= JOIN_KW nm nm JOIN",
  141375. /* 121 */ "on_opt ::= ON expr",
  141376. /* 122 */ "on_opt ::=",
  141377. /* 123 */ "indexed_opt ::=",
  141378. /* 124 */ "indexed_opt ::= INDEXED BY nm",
  141379. /* 125 */ "indexed_opt ::= NOT INDEXED",
  141380. /* 126 */ "using_opt ::= USING LP idlist RP",
  141381. /* 127 */ "using_opt ::=",
  141382. /* 128 */ "orderby_opt ::=",
  141383. /* 129 */ "orderby_opt ::= ORDER BY sortlist",
  141384. /* 130 */ "sortlist ::= sortlist COMMA expr sortorder",
  141385. /* 131 */ "sortlist ::= expr sortorder",
  141386. /* 132 */ "sortorder ::= ASC",
  141387. /* 133 */ "sortorder ::= DESC",
  141388. /* 134 */ "sortorder ::=",
  141389. /* 135 */ "groupby_opt ::=",
  141390. /* 136 */ "groupby_opt ::= GROUP BY nexprlist",
  141391. /* 137 */ "having_opt ::=",
  141392. /* 138 */ "having_opt ::= HAVING expr",
  141393. /* 139 */ "limit_opt ::=",
  141394. /* 140 */ "limit_opt ::= LIMIT expr",
  141395. /* 141 */ "limit_opt ::= LIMIT expr OFFSET expr",
  141396. /* 142 */ "limit_opt ::= LIMIT expr COMMA expr",
  141397. /* 143 */ "cmd ::= with DELETE FROM xfullname indexed_opt where_opt",
  141398. /* 144 */ "where_opt ::=",
  141399. /* 145 */ "where_opt ::= WHERE expr",
  141400. /* 146 */ "cmd ::= with UPDATE orconf xfullname indexed_opt SET setlist where_opt",
  141401. /* 147 */ "setlist ::= setlist COMMA nm EQ expr",
  141402. /* 148 */ "setlist ::= setlist COMMA LP idlist RP EQ expr",
  141403. /* 149 */ "setlist ::= nm EQ expr",
  141404. /* 150 */ "setlist ::= LP idlist RP EQ expr",
  141405. /* 151 */ "cmd ::= with insert_cmd INTO xfullname idlist_opt select upsert",
  141406. /* 152 */ "cmd ::= with insert_cmd INTO xfullname idlist_opt DEFAULT VALUES",
  141407. /* 153 */ "upsert ::=",
  141408. /* 154 */ "upsert ::= ON CONFLICT LP sortlist RP where_opt DO UPDATE SET setlist where_opt",
  141409. /* 155 */ "upsert ::= ON CONFLICT LP sortlist RP where_opt DO NOTHING",
  141410. /* 156 */ "upsert ::= ON CONFLICT DO NOTHING",
  141411. /* 157 */ "insert_cmd ::= INSERT orconf",
  141412. /* 158 */ "insert_cmd ::= REPLACE",
  141413. /* 159 */ "idlist_opt ::=",
  141414. /* 160 */ "idlist_opt ::= LP idlist RP",
  141415. /* 161 */ "idlist ::= idlist COMMA nm",
  141416. /* 162 */ "idlist ::= nm",
  141417. /* 163 */ "expr ::= LP expr RP",
  141418. /* 164 */ "expr ::= ID|INDEXED",
  141419. /* 165 */ "expr ::= JOIN_KW",
  141420. /* 166 */ "expr ::= nm DOT nm",
  141421. /* 167 */ "expr ::= nm DOT nm DOT nm",
  141422. /* 168 */ "term ::= NULL|FLOAT|BLOB",
  141423. /* 169 */ "term ::= STRING",
  141424. /* 170 */ "term ::= INTEGER",
  141425. /* 171 */ "expr ::= VARIABLE",
  141426. /* 172 */ "expr ::= expr COLLATE ID|STRING",
  141427. /* 173 */ "expr ::= CAST LP expr AS typetoken RP",
  141428. /* 174 */ "expr ::= ID|INDEXED LP distinct exprlist RP",
  141429. /* 175 */ "expr ::= ID|INDEXED LP STAR RP",
  141430. /* 176 */ "expr ::= ID|INDEXED LP distinct exprlist RP over_clause",
  141431. /* 177 */ "expr ::= ID|INDEXED LP STAR RP over_clause",
  141432. /* 178 */ "term ::= CTIME_KW",
  141433. /* 179 */ "expr ::= LP nexprlist COMMA expr RP",
  141434. /* 180 */ "expr ::= expr AND expr",
  141435. /* 181 */ "expr ::= expr OR expr",
  141436. /* 182 */ "expr ::= expr LT|GT|GE|LE expr",
  141437. /* 183 */ "expr ::= expr EQ|NE expr",
  141438. /* 184 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
  141439. /* 185 */ "expr ::= expr PLUS|MINUS expr",
  141440. /* 186 */ "expr ::= expr STAR|SLASH|REM expr",
  141441. /* 187 */ "expr ::= expr CONCAT expr",
  141442. /* 188 */ "likeop ::= NOT LIKE_KW|MATCH",
  141443. /* 189 */ "expr ::= expr likeop expr",
  141444. /* 190 */ "expr ::= expr likeop expr ESCAPE expr",
  141445. /* 191 */ "expr ::= expr ISNULL|NOTNULL",
  141446. /* 192 */ "expr ::= expr NOT NULL",
  141447. /* 193 */ "expr ::= expr IS expr",
  141448. /* 194 */ "expr ::= expr IS NOT expr",
  141449. /* 195 */ "expr ::= NOT expr",
  141450. /* 196 */ "expr ::= BITNOT expr",
  141451. /* 197 */ "expr ::= PLUS|MINUS expr",
  141452. /* 198 */ "between_op ::= BETWEEN",
  141453. /* 199 */ "between_op ::= NOT BETWEEN",
  141454. /* 200 */ "expr ::= expr between_op expr AND expr",
  141455. /* 201 */ "in_op ::= IN",
  141456. /* 202 */ "in_op ::= NOT IN",
  141457. /* 203 */ "expr ::= expr in_op LP exprlist RP",
  141458. /* 204 */ "expr ::= LP select RP",
  141459. /* 205 */ "expr ::= expr in_op LP select RP",
  141460. /* 206 */ "expr ::= expr in_op nm dbnm paren_exprlist",
  141461. /* 207 */ "expr ::= EXISTS LP select RP",
  141462. /* 208 */ "expr ::= CASE case_operand case_exprlist case_else END",
  141463. /* 209 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
  141464. /* 210 */ "case_exprlist ::= WHEN expr THEN expr",
  141465. /* 211 */ "case_else ::= ELSE expr",
  141466. /* 212 */ "case_else ::=",
  141467. /* 213 */ "case_operand ::= expr",
  141468. /* 214 */ "case_operand ::=",
  141469. /* 215 */ "exprlist ::=",
  141470. /* 216 */ "nexprlist ::= nexprlist COMMA expr",
  141471. /* 217 */ "nexprlist ::= expr",
  141472. /* 218 */ "paren_exprlist ::=",
  141473. /* 219 */ "paren_exprlist ::= LP exprlist RP",
  141474. /* 220 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt",
  141475. /* 221 */ "uniqueflag ::= UNIQUE",
  141476. /* 222 */ "uniqueflag ::=",
  141477. /* 223 */ "eidlist_opt ::=",
  141478. /* 224 */ "eidlist_opt ::= LP eidlist RP",
  141479. /* 225 */ "eidlist ::= eidlist COMMA nm collate sortorder",
  141480. /* 226 */ "eidlist ::= nm collate sortorder",
  141481. /* 227 */ "collate ::=",
  141482. /* 228 */ "collate ::= COLLATE ID|STRING",
  141483. /* 229 */ "cmd ::= DROP INDEX ifexists fullname",
  141484. /* 230 */ "cmd ::= VACUUM vinto",
  141485. /* 231 */ "cmd ::= VACUUM nm vinto",
  141486. /* 232 */ "vinto ::= INTO expr",
  141487. /* 233 */ "vinto ::=",
  141488. /* 234 */ "cmd ::= PRAGMA nm dbnm",
  141489. /* 235 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
  141490. /* 236 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
  141491. /* 237 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
  141492. /* 238 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
  141493. /* 239 */ "plus_num ::= PLUS INTEGER|FLOAT",
  141494. /* 240 */ "minus_num ::= MINUS INTEGER|FLOAT",
  141495. /* 241 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
  141496. /* 242 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
  141497. /* 243 */ "trigger_time ::= BEFORE|AFTER",
  141498. /* 244 */ "trigger_time ::= INSTEAD OF",
  141499. /* 245 */ "trigger_time ::=",
  141500. /* 246 */ "trigger_event ::= DELETE|INSERT",
  141501. /* 247 */ "trigger_event ::= UPDATE",
  141502. /* 248 */ "trigger_event ::= UPDATE OF idlist",
  141503. /* 249 */ "when_clause ::=",
  141504. /* 250 */ "when_clause ::= WHEN expr",
  141505. /* 251 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
  141506. /* 252 */ "trigger_cmd_list ::= trigger_cmd SEMI",
  141507. /* 253 */ "trnm ::= nm DOT nm",
  141508. /* 254 */ "tridxby ::= INDEXED BY nm",
  141509. /* 255 */ "tridxby ::= NOT INDEXED",
  141510. /* 256 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt scanpt",
  141511. /* 257 */ "trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt",
  141512. /* 258 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt",
  141513. /* 259 */ "trigger_cmd ::= scanpt select scanpt",
  141514. /* 260 */ "expr ::= RAISE LP IGNORE RP",
  141515. /* 261 */ "expr ::= RAISE LP raisetype COMMA nm RP",
  141516. /* 262 */ "raisetype ::= ROLLBACK",
  141517. /* 263 */ "raisetype ::= ABORT",
  141518. /* 264 */ "raisetype ::= FAIL",
  141519. /* 265 */ "cmd ::= DROP TRIGGER ifexists fullname",
  141520. /* 266 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
  141521. /* 267 */ "cmd ::= DETACH database_kw_opt expr",
  141522. /* 268 */ "key_opt ::=",
  141523. /* 269 */ "key_opt ::= KEY expr",
  141524. /* 270 */ "cmd ::= REINDEX",
  141525. /* 271 */ "cmd ::= REINDEX nm dbnm",
  141526. /* 272 */ "cmd ::= ANALYZE",
  141527. /* 273 */ "cmd ::= ANALYZE nm dbnm",
  141528. /* 274 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
  141529. /* 275 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist",
  141530. /* 276 */ "add_column_fullname ::= fullname",
  141531. /* 277 */ "cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm",
  141532. /* 278 */ "cmd ::= create_vtab",
  141533. /* 279 */ "cmd ::= create_vtab LP vtabarglist RP",
  141534. /* 280 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
  141535. /* 281 */ "vtabarg ::=",
  141536. /* 282 */ "vtabargtoken ::= ANY",
  141537. /* 283 */ "vtabargtoken ::= lp anylist RP",
  141538. /* 284 */ "lp ::= LP",
  141539. /* 285 */ "with ::= WITH wqlist",
  141540. /* 286 */ "with ::= WITH RECURSIVE wqlist",
  141541. /* 287 */ "wqlist ::= nm eidlist_opt AS LP select RP",
  141542. /* 288 */ "wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP",
  141543. /* 289 */ "windowdefn_list ::= windowdefn",
  141544. /* 290 */ "windowdefn_list ::= windowdefn_list COMMA windowdefn",
  141545. /* 291 */ "windowdefn ::= nm AS LP window RP",
  141546. /* 292 */ "window ::= PARTITION BY nexprlist orderby_opt frame_opt",
  141547. /* 293 */ "window ::= nm PARTITION BY nexprlist orderby_opt frame_opt",
  141548. /* 294 */ "window ::= ORDER BY sortlist frame_opt",
  141549. /* 295 */ "window ::= nm ORDER BY sortlist frame_opt",
  141550. /* 296 */ "window ::= frame_opt",
  141551. /* 297 */ "window ::= nm frame_opt",
  141552. /* 298 */ "frame_opt ::=",
  141553. /* 299 */ "frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt",
  141554. /* 300 */ "frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt",
  141555. /* 301 */ "range_or_rows ::= RANGE|ROWS|GROUPS",
  141556. /* 302 */ "frame_bound_s ::= frame_bound",
  141557. /* 303 */ "frame_bound_s ::= UNBOUNDED PRECEDING",
  141558. /* 304 */ "frame_bound_e ::= frame_bound",
  141559. /* 305 */ "frame_bound_e ::= UNBOUNDED FOLLOWING",
  141560. /* 306 */ "frame_bound ::= expr PRECEDING|FOLLOWING",
  141561. /* 307 */ "frame_bound ::= CURRENT ROW",
  141562. /* 308 */ "frame_exclude_opt ::=",
  141563. /* 309 */ "frame_exclude_opt ::= EXCLUDE frame_exclude",
  141564. /* 310 */ "frame_exclude ::= NO OTHERS",
  141565. /* 311 */ "frame_exclude ::= CURRENT ROW",
  141566. /* 312 */ "frame_exclude ::= GROUP|TIES",
  141567. /* 313 */ "window_clause ::= WINDOW windowdefn_list",
  141568. /* 314 */ "over_clause ::= filter_opt OVER LP window RP",
  141569. /* 315 */ "over_clause ::= filter_opt OVER nm",
  141570. /* 316 */ "filter_opt ::=",
  141571. /* 317 */ "filter_opt ::= FILTER LP WHERE expr RP",
  141572. /* 318 */ "input ::= cmdlist",
  141573. /* 319 */ "cmdlist ::= cmdlist ecmd",
  141574. /* 320 */ "cmdlist ::= ecmd",
  141575. /* 321 */ "ecmd ::= SEMI",
  141576. /* 322 */ "ecmd ::= cmdx SEMI",
  141577. /* 323 */ "ecmd ::= explain cmdx",
  141578. /* 324 */ "trans_opt ::=",
  141579. /* 325 */ "trans_opt ::= TRANSACTION",
  141580. /* 326 */ "trans_opt ::= TRANSACTION nm",
  141581. /* 327 */ "savepoint_opt ::= SAVEPOINT",
  141582. /* 328 */ "savepoint_opt ::=",
  141583. /* 329 */ "cmd ::= create_table create_table_args",
  141584. /* 330 */ "columnlist ::= columnlist COMMA columnname carglist",
  141585. /* 331 */ "columnlist ::= columnname carglist",
  141586. /* 332 */ "nm ::= ID|INDEXED",
  141587. /* 333 */ "nm ::= STRING",
  141588. /* 334 */ "nm ::= JOIN_KW",
  141589. /* 335 */ "typetoken ::= typename",
  141590. /* 336 */ "typename ::= ID|STRING",
  141591. /* 337 */ "signed ::= plus_num",
  141592. /* 338 */ "signed ::= minus_num",
  141593. /* 339 */ "carglist ::= carglist ccons",
  141594. /* 340 */ "carglist ::=",
  141595. /* 341 */ "ccons ::= NULL onconf",
  141596. /* 342 */ "conslist_opt ::= COMMA conslist",
  141597. /* 343 */ "conslist ::= conslist tconscomma tcons",
  141598. /* 344 */ "conslist ::= tcons",
  141599. /* 345 */ "tconscomma ::=",
  141600. /* 346 */ "defer_subclause_opt ::= defer_subclause",
  141601. /* 347 */ "resolvetype ::= raisetype",
  141602. /* 348 */ "selectnowith ::= oneselect",
  141603. /* 349 */ "oneselect ::= values",
  141604. /* 350 */ "sclp ::= selcollist COMMA",
  141605. /* 351 */ "as ::= ID|STRING",
  141606. /* 352 */ "expr ::= term",
  141607. /* 353 */ "likeop ::= LIKE_KW|MATCH",
  141608. /* 354 */ "exprlist ::= nexprlist",
  141609. /* 355 */ "nmnum ::= plus_num",
  141610. /* 356 */ "nmnum ::= nm",
  141611. /* 357 */ "nmnum ::= ON",
  141612. /* 358 */ "nmnum ::= DELETE",
  141613. /* 359 */ "nmnum ::= DEFAULT",
  141614. /* 360 */ "plus_num ::= INTEGER|FLOAT",
  141615. /* 361 */ "foreach_clause ::=",
  141616. /* 362 */ "foreach_clause ::= FOR EACH ROW",
  141617. /* 363 */ "trnm ::= nm",
  141618. /* 364 */ "tridxby ::=",
  141619. /* 365 */ "database_kw_opt ::= DATABASE",
  141620. /* 366 */ "database_kw_opt ::=",
  141621. /* 367 */ "kwcolumn_opt ::=",
  141622. /* 368 */ "kwcolumn_opt ::= COLUMNKW",
  141623. /* 369 */ "vtabarglist ::= vtabarg",
  141624. /* 370 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
  141625. /* 371 */ "vtabarg ::= vtabarg vtabargtoken",
  141626. /* 372 */ "anylist ::=",
  141627. /* 373 */ "anylist ::= anylist LP anylist RP",
  141628. /* 374 */ "anylist ::= anylist ANY",
  141629. /* 375 */ "with ::=",
  141630. };
  141631. #endif /* NDEBUG */
  141632. #if YYSTACKDEPTH<=0
  141633. /*
  141634. ** Try to increase the size of the parser stack. Return the number
  141635. ** of errors. Return 0 on success.
  141636. */
  141637. static int yyGrowStack(yyParser *p){
  141638. int newSize;
  141639. int idx;
  141640. yyStackEntry *pNew;
  141641. newSize = p->yystksz*2 + 100;
  141642. idx = p->yytos ? (int)(p->yytos - p->yystack) : 0;
  141643. if( p->yystack==&p->yystk0 ){
  141644. pNew = malloc(newSize*sizeof(pNew[0]));
  141645. if( pNew ) pNew[0] = p->yystk0;
  141646. }else{
  141647. pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
  141648. }
  141649. if( pNew ){
  141650. p->yystack = pNew;
  141651. p->yytos = &p->yystack[idx];
  141652. #ifndef NDEBUG
  141653. if( yyTraceFILE ){
  141654. fprintf(yyTraceFILE,"%sStack grows from %d to %d entries.\n",
  141655. yyTracePrompt, p->yystksz, newSize);
  141656. }
  141657. #endif
  141658. p->yystksz = newSize;
  141659. }
  141660. return pNew==0;
  141661. }
  141662. #endif
  141663. /* Datatype of the argument to the memory allocated passed as the
  141664. ** second argument to sqlite3ParserAlloc() below. This can be changed by
  141665. ** putting an appropriate #define in the %include section of the input
  141666. ** grammar.
  141667. */
  141668. #ifndef YYMALLOCARGTYPE
  141669. # define YYMALLOCARGTYPE size_t
  141670. #endif
  141671. /* Initialize a new parser that has already been allocated.
  141672. */
  141673. SQLITE_PRIVATE void sqlite3ParserInit(void *yypRawParser sqlite3ParserCTX_PDECL){
  141674. yyParser *yypParser = (yyParser*)yypRawParser;
  141675. sqlite3ParserCTX_STORE
  141676. #ifdef YYTRACKMAXSTACKDEPTH
  141677. yypParser->yyhwm = 0;
  141678. #endif
  141679. #if YYSTACKDEPTH<=0
  141680. yypParser->yytos = NULL;
  141681. yypParser->yystack = NULL;
  141682. yypParser->yystksz = 0;
  141683. if( yyGrowStack(yypParser) ){
  141684. yypParser->yystack = &yypParser->yystk0;
  141685. yypParser->yystksz = 1;
  141686. }
  141687. #endif
  141688. #ifndef YYNOERRORRECOVERY
  141689. yypParser->yyerrcnt = -1;
  141690. #endif
  141691. yypParser->yytos = yypParser->yystack;
  141692. yypParser->yystack[0].stateno = 0;
  141693. yypParser->yystack[0].major = 0;
  141694. #if YYSTACKDEPTH>0
  141695. yypParser->yystackEnd = &yypParser->yystack[YYSTACKDEPTH-1];
  141696. #endif
  141697. }
  141698. #ifndef sqlite3Parser_ENGINEALWAYSONSTACK
  141699. /*
  141700. ** This function allocates a new parser.
  141701. ** The only argument is a pointer to a function which works like
  141702. ** malloc.
  141703. **
  141704. ** Inputs:
  141705. ** A pointer to the function used to allocate memory.
  141706. **
  141707. ** Outputs:
  141708. ** A pointer to a parser. This pointer is used in subsequent calls
  141709. ** to sqlite3Parser and sqlite3ParserFree.
  141710. */
  141711. SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(YYMALLOCARGTYPE) sqlite3ParserCTX_PDECL){
  141712. yyParser *yypParser;
  141713. yypParser = (yyParser*)(*mallocProc)( (YYMALLOCARGTYPE)sizeof(yyParser) );
  141714. if( yypParser ){
  141715. sqlite3ParserCTX_STORE
  141716. sqlite3ParserInit(yypParser sqlite3ParserCTX_PARAM);
  141717. }
  141718. return (void*)yypParser;
  141719. }
  141720. #endif /* sqlite3Parser_ENGINEALWAYSONSTACK */
  141721. /* The following function deletes the "minor type" or semantic value
  141722. ** associated with a symbol. The symbol can be either a terminal
  141723. ** or nonterminal. "yymajor" is the symbol code, and "yypminor" is
  141724. ** a pointer to the value to be deleted. The code used to do the
  141725. ** deletions is derived from the %destructor and/or %token_destructor
  141726. ** directives of the input grammar.
  141727. */
  141728. static void yy_destructor(
  141729. yyParser *yypParser, /* The parser */
  141730. YYCODETYPE yymajor, /* Type code for object to destroy */
  141731. YYMINORTYPE *yypminor /* The object to be destroyed */
  141732. ){
  141733. sqlite3ParserARG_FETCH
  141734. sqlite3ParserCTX_FETCH
  141735. switch( yymajor ){
  141736. /* Here is inserted the actions which take place when a
  141737. ** terminal or non-terminal is destroyed. This can happen
  141738. ** when the symbol is popped from the stack during a
  141739. ** reduce or during error processing or when a parser is
  141740. ** being destroyed before it is finished parsing.
  141741. **
  141742. ** Note: during a reduce, the only symbols destroyed are those
  141743. ** which appear on the RHS of the rule, but which are *not* used
  141744. ** inside the C code.
  141745. */
  141746. /********* Begin destructor definitions ***************************************/
  141747. case 195: /* select */
  141748. case 228: /* selectnowith */
  141749. case 229: /* oneselect */
  141750. case 241: /* values */
  141751. {
  141752. sqlite3SelectDelete(pParse->db, (yypminor->yy391));
  141753. }
  141754. break;
  141755. case 206: /* term */
  141756. case 207: /* expr */
  141757. case 235: /* where_opt */
  141758. case 237: /* having_opt */
  141759. case 249: /* on_opt */
  141760. case 264: /* case_operand */
  141761. case 266: /* case_else */
  141762. case 269: /* vinto */
  141763. case 276: /* when_clause */
  141764. case 281: /* key_opt */
  141765. case 295: /* filter_opt */
  141766. {
  141767. sqlite3ExprDelete(pParse->db, (yypminor->yy102));
  141768. }
  141769. break;
  141770. case 211: /* eidlist_opt */
  141771. case 220: /* sortlist */
  141772. case 221: /* eidlist */
  141773. case 233: /* selcollist */
  141774. case 236: /* groupby_opt */
  141775. case 238: /* orderby_opt */
  141776. case 242: /* nexprlist */
  141777. case 243: /* sclp */
  141778. case 251: /* exprlist */
  141779. case 255: /* setlist */
  141780. case 263: /* paren_exprlist */
  141781. case 265: /* case_exprlist */
  141782. case 294: /* part_opt */
  141783. {
  141784. sqlite3ExprListDelete(pParse->db, (yypminor->yy94));
  141785. }
  141786. break;
  141787. case 227: /* fullname */
  141788. case 234: /* from */
  141789. case 245: /* seltablist */
  141790. case 246: /* stl_prefix */
  141791. case 252: /* xfullname */
  141792. {
  141793. sqlite3SrcListDelete(pParse->db, (yypminor->yy407));
  141794. }
  141795. break;
  141796. case 230: /* wqlist */
  141797. {
  141798. sqlite3WithDelete(pParse->db, (yypminor->yy243));
  141799. }
  141800. break;
  141801. case 240: /* window_clause */
  141802. case 290: /* windowdefn_list */
  141803. {
  141804. sqlite3WindowListDelete(pParse->db, (yypminor->yy379));
  141805. }
  141806. break;
  141807. case 250: /* using_opt */
  141808. case 253: /* idlist */
  141809. case 257: /* idlist_opt */
  141810. {
  141811. sqlite3IdListDelete(pParse->db, (yypminor->yy76));
  141812. }
  141813. break;
  141814. case 259: /* over_clause */
  141815. case 291: /* windowdefn */
  141816. case 292: /* window */
  141817. case 293: /* frame_opt */
  141818. {
  141819. sqlite3WindowDelete(pParse->db, (yypminor->yy379));
  141820. }
  141821. break;
  141822. case 272: /* trigger_cmd_list */
  141823. case 277: /* trigger_cmd */
  141824. {
  141825. sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy11));
  141826. }
  141827. break;
  141828. case 274: /* trigger_event */
  141829. {
  141830. sqlite3IdListDelete(pParse->db, (yypminor->yy298).b);
  141831. }
  141832. break;
  141833. case 297: /* frame_bound */
  141834. case 298: /* frame_bound_s */
  141835. case 299: /* frame_bound_e */
  141836. {
  141837. sqlite3ExprDelete(pParse->db, (yypminor->yy389).pExpr);
  141838. }
  141839. break;
  141840. /********* End destructor definitions *****************************************/
  141841. default: break; /* If no destructor action specified: do nothing */
  141842. }
  141843. }
  141844. /*
  141845. ** Pop the parser's stack once.
  141846. **
  141847. ** If there is a destructor routine associated with the token which
  141848. ** is popped from the stack, then call it.
  141849. */
  141850. static void yy_pop_parser_stack(yyParser *pParser){
  141851. yyStackEntry *yytos;
  141852. assert( pParser->yytos!=0 );
  141853. assert( pParser->yytos > pParser->yystack );
  141854. yytos = pParser->yytos--;
  141855. #ifndef NDEBUG
  141856. if( yyTraceFILE ){
  141857. fprintf(yyTraceFILE,"%sPopping %s\n",
  141858. yyTracePrompt,
  141859. yyTokenName[yytos->major]);
  141860. }
  141861. #endif
  141862. yy_destructor(pParser, yytos->major, &yytos->minor);
  141863. }
  141864. /*
  141865. ** Clear all secondary memory allocations from the parser
  141866. */
  141867. SQLITE_PRIVATE void sqlite3ParserFinalize(void *p){
  141868. yyParser *pParser = (yyParser*)p;
  141869. while( pParser->yytos>pParser->yystack ) yy_pop_parser_stack(pParser);
  141870. #if YYSTACKDEPTH<=0
  141871. if( pParser->yystack!=&pParser->yystk0 ) free(pParser->yystack);
  141872. #endif
  141873. }
  141874. #ifndef sqlite3Parser_ENGINEALWAYSONSTACK
  141875. /*
  141876. ** Deallocate and destroy a parser. Destructors are called for
  141877. ** all stack elements before shutting the parser down.
  141878. **
  141879. ** If the YYPARSEFREENEVERNULL macro exists (for example because it
  141880. ** is defined in a %include section of the input grammar) then it is
  141881. ** assumed that the input pointer is never NULL.
  141882. */
  141883. SQLITE_PRIVATE void sqlite3ParserFree(
  141884. void *p, /* The parser to be deleted */
  141885. void (*freeProc)(void*) /* Function used to reclaim memory */
  141886. ){
  141887. #ifndef YYPARSEFREENEVERNULL
  141888. if( p==0 ) return;
  141889. #endif
  141890. sqlite3ParserFinalize(p);
  141891. (*freeProc)(p);
  141892. }
  141893. #endif /* sqlite3Parser_ENGINEALWAYSONSTACK */
  141894. /*
  141895. ** Return the peak depth of the stack for a parser.
  141896. */
  141897. #ifdef YYTRACKMAXSTACKDEPTH
  141898. SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
  141899. yyParser *pParser = (yyParser*)p;
  141900. return pParser->yyhwm;
  141901. }
  141902. #endif
  141903. /* This array of booleans keeps track of the parser statement
  141904. ** coverage. The element yycoverage[X][Y] is set when the parser
  141905. ** is in state X and has a lookahead token Y. In a well-tested
  141906. ** systems, every element of this matrix should end up being set.
  141907. */
  141908. #if defined(YYCOVERAGE)
  141909. static unsigned char yycoverage[YYNSTATE][YYNTOKEN];
  141910. #endif
  141911. /*
  141912. ** Write into out a description of every state/lookahead combination that
  141913. **
  141914. ** (1) has not been used by the parser, and
  141915. ** (2) is not a syntax error.
  141916. **
  141917. ** Return the number of missed state/lookahead combinations.
  141918. */
  141919. #if defined(YYCOVERAGE)
  141920. SQLITE_PRIVATE int sqlite3ParserCoverage(FILE *out){
  141921. int stateno, iLookAhead, i;
  141922. int nMissed = 0;
  141923. for(stateno=0; stateno<YYNSTATE; stateno++){
  141924. i = yy_shift_ofst[stateno];
  141925. for(iLookAhead=0; iLookAhead<YYNTOKEN; iLookAhead++){
  141926. if( yy_lookahead[i+iLookAhead]!=iLookAhead ) continue;
  141927. if( yycoverage[stateno][iLookAhead]==0 ) nMissed++;
  141928. if( out ){
  141929. fprintf(out,"State %d lookahead %s %s\n", stateno,
  141930. yyTokenName[iLookAhead],
  141931. yycoverage[stateno][iLookAhead] ? "ok" : "missed");
  141932. }
  141933. }
  141934. }
  141935. return nMissed;
  141936. }
  141937. #endif
  141938. /*
  141939. ** Find the appropriate action for a parser given the terminal
  141940. ** look-ahead token iLookAhead.
  141941. */
  141942. static YYACTIONTYPE yy_find_shift_action(
  141943. YYCODETYPE iLookAhead, /* The look-ahead token */
  141944. YYACTIONTYPE stateno /* Current state number */
  141945. ){
  141946. int i;
  141947. if( stateno>YY_MAX_SHIFT ) return stateno;
  141948. assert( stateno <= YY_SHIFT_COUNT );
  141949. #if defined(YYCOVERAGE)
  141950. yycoverage[stateno][iLookAhead] = 1;
  141951. #endif
  141952. do{
  141953. i = yy_shift_ofst[stateno];
  141954. assert( i>=0 );
  141955. /* assert( i+YYNTOKEN<=(int)YY_NLOOKAHEAD ); */
  141956. assert( iLookAhead!=YYNOCODE );
  141957. assert( iLookAhead < YYNTOKEN );
  141958. i += iLookAhead;
  141959. if( i>=YY_NLOOKAHEAD || yy_lookahead[i]!=iLookAhead ){
  141960. #ifdef YYFALLBACK
  141961. YYCODETYPE iFallback; /* Fallback token */
  141962. if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
  141963. && (iFallback = yyFallback[iLookAhead])!=0 ){
  141964. #ifndef NDEBUG
  141965. if( yyTraceFILE ){
  141966. fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
  141967. yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
  141968. }
  141969. #endif
  141970. assert( yyFallback[iFallback]==0 ); /* Fallback loop must terminate */
  141971. iLookAhead = iFallback;
  141972. continue;
  141973. }
  141974. #endif
  141975. #ifdef YYWILDCARD
  141976. {
  141977. int j = i - iLookAhead + YYWILDCARD;
  141978. if(
  141979. #if YY_SHIFT_MIN+YYWILDCARD<0
  141980. j>=0 &&
  141981. #endif
  141982. #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
  141983. j<YY_ACTTAB_COUNT &&
  141984. #endif
  141985. j<(int)(sizeof(yy_lookahead)/sizeof(yy_lookahead[0])) &&
  141986. yy_lookahead[j]==YYWILDCARD && iLookAhead>0
  141987. ){
  141988. #ifndef NDEBUG
  141989. if( yyTraceFILE ){
  141990. fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
  141991. yyTracePrompt, yyTokenName[iLookAhead],
  141992. yyTokenName[YYWILDCARD]);
  141993. }
  141994. #endif /* NDEBUG */
  141995. return yy_action[j];
  141996. }
  141997. }
  141998. #endif /* YYWILDCARD */
  141999. return yy_default[stateno];
  142000. }else{
  142001. return yy_action[i];
  142002. }
  142003. }while(1);
  142004. }
  142005. /*
  142006. ** Find the appropriate action for a parser given the non-terminal
  142007. ** look-ahead token iLookAhead.
  142008. */
  142009. static YYACTIONTYPE yy_find_reduce_action(
  142010. YYACTIONTYPE stateno, /* Current state number */
  142011. YYCODETYPE iLookAhead /* The look-ahead token */
  142012. ){
  142013. int i;
  142014. #ifdef YYERRORSYMBOL
  142015. if( stateno>YY_REDUCE_COUNT ){
  142016. return yy_default[stateno];
  142017. }
  142018. #else
  142019. assert( stateno<=YY_REDUCE_COUNT );
  142020. #endif
  142021. i = yy_reduce_ofst[stateno];
  142022. assert( iLookAhead!=YYNOCODE );
  142023. i += iLookAhead;
  142024. #ifdef YYERRORSYMBOL
  142025. if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
  142026. return yy_default[stateno];
  142027. }
  142028. #else
  142029. assert( i>=0 && i<YY_ACTTAB_COUNT );
  142030. assert( yy_lookahead[i]==iLookAhead );
  142031. #endif
  142032. return yy_action[i];
  142033. }
  142034. /*
  142035. ** The following routine is called if the stack overflows.
  142036. */
  142037. static void yyStackOverflow(yyParser *yypParser){
  142038. sqlite3ParserARG_FETCH
  142039. sqlite3ParserCTX_FETCH
  142040. #ifndef NDEBUG
  142041. if( yyTraceFILE ){
  142042. fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
  142043. }
  142044. #endif
  142045. while( yypParser->yytos>yypParser->yystack ) yy_pop_parser_stack(yypParser);
  142046. /* Here code is inserted which will execute if the parser
  142047. ** stack every overflows */
  142048. /******** Begin %stack_overflow code ******************************************/
  142049. sqlite3ErrorMsg(pParse, "parser stack overflow");
  142050. /******** End %stack_overflow code ********************************************/
  142051. sqlite3ParserARG_STORE /* Suppress warning about unused %extra_argument var */
  142052. sqlite3ParserCTX_STORE
  142053. }
  142054. /*
  142055. ** Print tracing information for a SHIFT action
  142056. */
  142057. #ifndef NDEBUG
  142058. static void yyTraceShift(yyParser *yypParser, int yyNewState, const char *zTag){
  142059. if( yyTraceFILE ){
  142060. if( yyNewState<YYNSTATE ){
  142061. fprintf(yyTraceFILE,"%s%s '%s', go to state %d\n",
  142062. yyTracePrompt, zTag, yyTokenName[yypParser->yytos->major],
  142063. yyNewState);
  142064. }else{
  142065. fprintf(yyTraceFILE,"%s%s '%s', pending reduce %d\n",
  142066. yyTracePrompt, zTag, yyTokenName[yypParser->yytos->major],
  142067. yyNewState - YY_MIN_REDUCE);
  142068. }
  142069. }
  142070. }
  142071. #else
  142072. # define yyTraceShift(X,Y,Z)
  142073. #endif
  142074. /*
  142075. ** Perform a shift action.
  142076. */
  142077. static void yy_shift(
  142078. yyParser *yypParser, /* The parser to be shifted */
  142079. YYACTIONTYPE yyNewState, /* The new state to shift in */
  142080. YYCODETYPE yyMajor, /* The major token to shift in */
  142081. sqlite3ParserTOKENTYPE yyMinor /* The minor token to shift in */
  142082. ){
  142083. yyStackEntry *yytos;
  142084. yypParser->yytos++;
  142085. #ifdef YYTRACKMAXSTACKDEPTH
  142086. if( (int)(yypParser->yytos - yypParser->yystack)>yypParser->yyhwm ){
  142087. yypParser->yyhwm++;
  142088. assert( yypParser->yyhwm == (int)(yypParser->yytos - yypParser->yystack) );
  142089. }
  142090. #endif
  142091. #if YYSTACKDEPTH>0
  142092. if( yypParser->yytos>yypParser->yystackEnd ){
  142093. yypParser->yytos--;
  142094. yyStackOverflow(yypParser);
  142095. return;
  142096. }
  142097. #else
  142098. if( yypParser->yytos>=&yypParser->yystack[yypParser->yystksz] ){
  142099. if( yyGrowStack(yypParser) ){
  142100. yypParser->yytos--;
  142101. yyStackOverflow(yypParser);
  142102. return;
  142103. }
  142104. }
  142105. #endif
  142106. if( yyNewState > YY_MAX_SHIFT ){
  142107. yyNewState += YY_MIN_REDUCE - YY_MIN_SHIFTREDUCE;
  142108. }
  142109. yytos = yypParser->yytos;
  142110. yytos->stateno = yyNewState;
  142111. yytos->major = yyMajor;
  142112. yytos->minor.yy0 = yyMinor;
  142113. yyTraceShift(yypParser, yyNewState, "Shift");
  142114. }
  142115. /* For rule J, yyRuleInfoLhs[J] contains the symbol on the left-hand side
  142116. ** of that rule */
  142117. static const YYCODETYPE yyRuleInfoLhs[] = {
  142118. 180, /* (0) explain ::= EXPLAIN */
  142119. 180, /* (1) explain ::= EXPLAIN QUERY PLAN */
  142120. 179, /* (2) cmdx ::= cmd */
  142121. 181, /* (3) cmd ::= BEGIN transtype trans_opt */
  142122. 182, /* (4) transtype ::= */
  142123. 182, /* (5) transtype ::= DEFERRED */
  142124. 182, /* (6) transtype ::= IMMEDIATE */
  142125. 182, /* (7) transtype ::= EXCLUSIVE */
  142126. 181, /* (8) cmd ::= COMMIT|END trans_opt */
  142127. 181, /* (9) cmd ::= ROLLBACK trans_opt */
  142128. 181, /* (10) cmd ::= SAVEPOINT nm */
  142129. 181, /* (11) cmd ::= RELEASE savepoint_opt nm */
  142130. 181, /* (12) cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
  142131. 186, /* (13) create_table ::= createkw temp TABLE ifnotexists nm dbnm */
  142132. 188, /* (14) createkw ::= CREATE */
  142133. 190, /* (15) ifnotexists ::= */
  142134. 190, /* (16) ifnotexists ::= IF NOT EXISTS */
  142135. 189, /* (17) temp ::= TEMP */
  142136. 189, /* (18) temp ::= */
  142137. 187, /* (19) create_table_args ::= LP columnlist conslist_opt RP table_options */
  142138. 187, /* (20) create_table_args ::= AS select */
  142139. 194, /* (21) table_options ::= */
  142140. 194, /* (22) table_options ::= WITHOUT nm */
  142141. 196, /* (23) columnname ::= nm typetoken */
  142142. 198, /* (24) typetoken ::= */
  142143. 198, /* (25) typetoken ::= typename LP signed RP */
  142144. 198, /* (26) typetoken ::= typename LP signed COMMA signed RP */
  142145. 199, /* (27) typename ::= typename ID|STRING */
  142146. 203, /* (28) scanpt ::= */
  142147. 204, /* (29) scantok ::= */
  142148. 205, /* (30) ccons ::= CONSTRAINT nm */
  142149. 205, /* (31) ccons ::= DEFAULT scantok term */
  142150. 205, /* (32) ccons ::= DEFAULT LP expr RP */
  142151. 205, /* (33) ccons ::= DEFAULT PLUS scantok term */
  142152. 205, /* (34) ccons ::= DEFAULT MINUS scantok term */
  142153. 205, /* (35) ccons ::= DEFAULT scantok ID|INDEXED */
  142154. 205, /* (36) ccons ::= NOT NULL onconf */
  142155. 205, /* (37) ccons ::= PRIMARY KEY sortorder onconf autoinc */
  142156. 205, /* (38) ccons ::= UNIQUE onconf */
  142157. 205, /* (39) ccons ::= CHECK LP expr RP */
  142158. 205, /* (40) ccons ::= REFERENCES nm eidlist_opt refargs */
  142159. 205, /* (41) ccons ::= defer_subclause */
  142160. 205, /* (42) ccons ::= COLLATE ID|STRING */
  142161. 210, /* (43) autoinc ::= */
  142162. 210, /* (44) autoinc ::= AUTOINCR */
  142163. 212, /* (45) refargs ::= */
  142164. 212, /* (46) refargs ::= refargs refarg */
  142165. 214, /* (47) refarg ::= MATCH nm */
  142166. 214, /* (48) refarg ::= ON INSERT refact */
  142167. 214, /* (49) refarg ::= ON DELETE refact */
  142168. 214, /* (50) refarg ::= ON UPDATE refact */
  142169. 215, /* (51) refact ::= SET NULL */
  142170. 215, /* (52) refact ::= SET DEFAULT */
  142171. 215, /* (53) refact ::= CASCADE */
  142172. 215, /* (54) refact ::= RESTRICT */
  142173. 215, /* (55) refact ::= NO ACTION */
  142174. 213, /* (56) defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
  142175. 213, /* (57) defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
  142176. 216, /* (58) init_deferred_pred_opt ::= */
  142177. 216, /* (59) init_deferred_pred_opt ::= INITIALLY DEFERRED */
  142178. 216, /* (60) init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
  142179. 193, /* (61) conslist_opt ::= */
  142180. 218, /* (62) tconscomma ::= COMMA */
  142181. 219, /* (63) tcons ::= CONSTRAINT nm */
  142182. 219, /* (64) tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */
  142183. 219, /* (65) tcons ::= UNIQUE LP sortlist RP onconf */
  142184. 219, /* (66) tcons ::= CHECK LP expr RP onconf */
  142185. 219, /* (67) tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */
  142186. 222, /* (68) defer_subclause_opt ::= */
  142187. 208, /* (69) onconf ::= */
  142188. 208, /* (70) onconf ::= ON CONFLICT resolvetype */
  142189. 223, /* (71) orconf ::= */
  142190. 223, /* (72) orconf ::= OR resolvetype */
  142191. 224, /* (73) resolvetype ::= IGNORE */
  142192. 224, /* (74) resolvetype ::= REPLACE */
  142193. 181, /* (75) cmd ::= DROP TABLE ifexists fullname */
  142194. 226, /* (76) ifexists ::= IF EXISTS */
  142195. 226, /* (77) ifexists ::= */
  142196. 181, /* (78) cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */
  142197. 181, /* (79) cmd ::= DROP VIEW ifexists fullname */
  142198. 181, /* (80) cmd ::= select */
  142199. 195, /* (81) select ::= WITH wqlist selectnowith */
  142200. 195, /* (82) select ::= WITH RECURSIVE wqlist selectnowith */
  142201. 195, /* (83) select ::= selectnowith */
  142202. 228, /* (84) selectnowith ::= selectnowith multiselect_op oneselect */
  142203. 231, /* (85) multiselect_op ::= UNION */
  142204. 231, /* (86) multiselect_op ::= UNION ALL */
  142205. 231, /* (87) multiselect_op ::= EXCEPT|INTERSECT */
  142206. 229, /* (88) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
  142207. 229, /* (89) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt window_clause orderby_opt limit_opt */
  142208. 241, /* (90) values ::= VALUES LP nexprlist RP */
  142209. 241, /* (91) values ::= values COMMA LP nexprlist RP */
  142210. 232, /* (92) distinct ::= DISTINCT */
  142211. 232, /* (93) distinct ::= ALL */
  142212. 232, /* (94) distinct ::= */
  142213. 243, /* (95) sclp ::= */
  142214. 233, /* (96) selcollist ::= sclp scanpt expr scanpt as */
  142215. 233, /* (97) selcollist ::= sclp scanpt STAR */
  142216. 233, /* (98) selcollist ::= sclp scanpt nm DOT STAR */
  142217. 244, /* (99) as ::= AS nm */
  142218. 244, /* (100) as ::= */
  142219. 234, /* (101) from ::= */
  142220. 234, /* (102) from ::= FROM seltablist */
  142221. 246, /* (103) stl_prefix ::= seltablist joinop */
  142222. 246, /* (104) stl_prefix ::= */
  142223. 245, /* (105) seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
  142224. 245, /* (106) seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */
  142225. 245, /* (107) seltablist ::= stl_prefix LP select RP as on_opt using_opt */
  142226. 245, /* (108) seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
  142227. 191, /* (109) dbnm ::= */
  142228. 191, /* (110) dbnm ::= DOT nm */
  142229. 227, /* (111) fullname ::= nm */
  142230. 227, /* (112) fullname ::= nm DOT nm */
  142231. 252, /* (113) xfullname ::= nm */
  142232. 252, /* (114) xfullname ::= nm DOT nm */
  142233. 252, /* (115) xfullname ::= nm DOT nm AS nm */
  142234. 252, /* (116) xfullname ::= nm AS nm */
  142235. 247, /* (117) joinop ::= COMMA|JOIN */
  142236. 247, /* (118) joinop ::= JOIN_KW JOIN */
  142237. 247, /* (119) joinop ::= JOIN_KW nm JOIN */
  142238. 247, /* (120) joinop ::= JOIN_KW nm nm JOIN */
  142239. 249, /* (121) on_opt ::= ON expr */
  142240. 249, /* (122) on_opt ::= */
  142241. 248, /* (123) indexed_opt ::= */
  142242. 248, /* (124) indexed_opt ::= INDEXED BY nm */
  142243. 248, /* (125) indexed_opt ::= NOT INDEXED */
  142244. 250, /* (126) using_opt ::= USING LP idlist RP */
  142245. 250, /* (127) using_opt ::= */
  142246. 238, /* (128) orderby_opt ::= */
  142247. 238, /* (129) orderby_opt ::= ORDER BY sortlist */
  142248. 220, /* (130) sortlist ::= sortlist COMMA expr sortorder */
  142249. 220, /* (131) sortlist ::= expr sortorder */
  142250. 209, /* (132) sortorder ::= ASC */
  142251. 209, /* (133) sortorder ::= DESC */
  142252. 209, /* (134) sortorder ::= */
  142253. 236, /* (135) groupby_opt ::= */
  142254. 236, /* (136) groupby_opt ::= GROUP BY nexprlist */
  142255. 237, /* (137) having_opt ::= */
  142256. 237, /* (138) having_opt ::= HAVING expr */
  142257. 239, /* (139) limit_opt ::= */
  142258. 239, /* (140) limit_opt ::= LIMIT expr */
  142259. 239, /* (141) limit_opt ::= LIMIT expr OFFSET expr */
  142260. 239, /* (142) limit_opt ::= LIMIT expr COMMA expr */
  142261. 181, /* (143) cmd ::= with DELETE FROM xfullname indexed_opt where_opt */
  142262. 235, /* (144) where_opt ::= */
  142263. 235, /* (145) where_opt ::= WHERE expr */
  142264. 181, /* (146) cmd ::= with UPDATE orconf xfullname indexed_opt SET setlist where_opt */
  142265. 255, /* (147) setlist ::= setlist COMMA nm EQ expr */
  142266. 255, /* (148) setlist ::= setlist COMMA LP idlist RP EQ expr */
  142267. 255, /* (149) setlist ::= nm EQ expr */
  142268. 255, /* (150) setlist ::= LP idlist RP EQ expr */
  142269. 181, /* (151) cmd ::= with insert_cmd INTO xfullname idlist_opt select upsert */
  142270. 181, /* (152) cmd ::= with insert_cmd INTO xfullname idlist_opt DEFAULT VALUES */
  142271. 258, /* (153) upsert ::= */
  142272. 258, /* (154) upsert ::= ON CONFLICT LP sortlist RP where_opt DO UPDATE SET setlist where_opt */
  142273. 258, /* (155) upsert ::= ON CONFLICT LP sortlist RP where_opt DO NOTHING */
  142274. 258, /* (156) upsert ::= ON CONFLICT DO NOTHING */
  142275. 256, /* (157) insert_cmd ::= INSERT orconf */
  142276. 256, /* (158) insert_cmd ::= REPLACE */
  142277. 257, /* (159) idlist_opt ::= */
  142278. 257, /* (160) idlist_opt ::= LP idlist RP */
  142279. 253, /* (161) idlist ::= idlist COMMA nm */
  142280. 253, /* (162) idlist ::= nm */
  142281. 207, /* (163) expr ::= LP expr RP */
  142282. 207, /* (164) expr ::= ID|INDEXED */
  142283. 207, /* (165) expr ::= JOIN_KW */
  142284. 207, /* (166) expr ::= nm DOT nm */
  142285. 207, /* (167) expr ::= nm DOT nm DOT nm */
  142286. 206, /* (168) term ::= NULL|FLOAT|BLOB */
  142287. 206, /* (169) term ::= STRING */
  142288. 206, /* (170) term ::= INTEGER */
  142289. 207, /* (171) expr ::= VARIABLE */
  142290. 207, /* (172) expr ::= expr COLLATE ID|STRING */
  142291. 207, /* (173) expr ::= CAST LP expr AS typetoken RP */
  142292. 207, /* (174) expr ::= ID|INDEXED LP distinct exprlist RP */
  142293. 207, /* (175) expr ::= ID|INDEXED LP STAR RP */
  142294. 207, /* (176) expr ::= ID|INDEXED LP distinct exprlist RP over_clause */
  142295. 207, /* (177) expr ::= ID|INDEXED LP STAR RP over_clause */
  142296. 206, /* (178) term ::= CTIME_KW */
  142297. 207, /* (179) expr ::= LP nexprlist COMMA expr RP */
  142298. 207, /* (180) expr ::= expr AND expr */
  142299. 207, /* (181) expr ::= expr OR expr */
  142300. 207, /* (182) expr ::= expr LT|GT|GE|LE expr */
  142301. 207, /* (183) expr ::= expr EQ|NE expr */
  142302. 207, /* (184) expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */
  142303. 207, /* (185) expr ::= expr PLUS|MINUS expr */
  142304. 207, /* (186) expr ::= expr STAR|SLASH|REM expr */
  142305. 207, /* (187) expr ::= expr CONCAT expr */
  142306. 260, /* (188) likeop ::= NOT LIKE_KW|MATCH */
  142307. 207, /* (189) expr ::= expr likeop expr */
  142308. 207, /* (190) expr ::= expr likeop expr ESCAPE expr */
  142309. 207, /* (191) expr ::= expr ISNULL|NOTNULL */
  142310. 207, /* (192) expr ::= expr NOT NULL */
  142311. 207, /* (193) expr ::= expr IS expr */
  142312. 207, /* (194) expr ::= expr IS NOT expr */
  142313. 207, /* (195) expr ::= NOT expr */
  142314. 207, /* (196) expr ::= BITNOT expr */
  142315. 207, /* (197) expr ::= PLUS|MINUS expr */
  142316. 261, /* (198) between_op ::= BETWEEN */
  142317. 261, /* (199) between_op ::= NOT BETWEEN */
  142318. 207, /* (200) expr ::= expr between_op expr AND expr */
  142319. 262, /* (201) in_op ::= IN */
  142320. 262, /* (202) in_op ::= NOT IN */
  142321. 207, /* (203) expr ::= expr in_op LP exprlist RP */
  142322. 207, /* (204) expr ::= LP select RP */
  142323. 207, /* (205) expr ::= expr in_op LP select RP */
  142324. 207, /* (206) expr ::= expr in_op nm dbnm paren_exprlist */
  142325. 207, /* (207) expr ::= EXISTS LP select RP */
  142326. 207, /* (208) expr ::= CASE case_operand case_exprlist case_else END */
  142327. 265, /* (209) case_exprlist ::= case_exprlist WHEN expr THEN expr */
  142328. 265, /* (210) case_exprlist ::= WHEN expr THEN expr */
  142329. 266, /* (211) case_else ::= ELSE expr */
  142330. 266, /* (212) case_else ::= */
  142331. 264, /* (213) case_operand ::= expr */
  142332. 264, /* (214) case_operand ::= */
  142333. 251, /* (215) exprlist ::= */
  142334. 242, /* (216) nexprlist ::= nexprlist COMMA expr */
  142335. 242, /* (217) nexprlist ::= expr */
  142336. 263, /* (218) paren_exprlist ::= */
  142337. 263, /* (219) paren_exprlist ::= LP exprlist RP */
  142338. 181, /* (220) cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
  142339. 267, /* (221) uniqueflag ::= UNIQUE */
  142340. 267, /* (222) uniqueflag ::= */
  142341. 211, /* (223) eidlist_opt ::= */
  142342. 211, /* (224) eidlist_opt ::= LP eidlist RP */
  142343. 221, /* (225) eidlist ::= eidlist COMMA nm collate sortorder */
  142344. 221, /* (226) eidlist ::= nm collate sortorder */
  142345. 268, /* (227) collate ::= */
  142346. 268, /* (228) collate ::= COLLATE ID|STRING */
  142347. 181, /* (229) cmd ::= DROP INDEX ifexists fullname */
  142348. 181, /* (230) cmd ::= VACUUM vinto */
  142349. 181, /* (231) cmd ::= VACUUM nm vinto */
  142350. 269, /* (232) vinto ::= INTO expr */
  142351. 269, /* (233) vinto ::= */
  142352. 181, /* (234) cmd ::= PRAGMA nm dbnm */
  142353. 181, /* (235) cmd ::= PRAGMA nm dbnm EQ nmnum */
  142354. 181, /* (236) cmd ::= PRAGMA nm dbnm LP nmnum RP */
  142355. 181, /* (237) cmd ::= PRAGMA nm dbnm EQ minus_num */
  142356. 181, /* (238) cmd ::= PRAGMA nm dbnm LP minus_num RP */
  142357. 201, /* (239) plus_num ::= PLUS INTEGER|FLOAT */
  142358. 202, /* (240) minus_num ::= MINUS INTEGER|FLOAT */
  142359. 181, /* (241) cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
  142360. 271, /* (242) trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
  142361. 273, /* (243) trigger_time ::= BEFORE|AFTER */
  142362. 273, /* (244) trigger_time ::= INSTEAD OF */
  142363. 273, /* (245) trigger_time ::= */
  142364. 274, /* (246) trigger_event ::= DELETE|INSERT */
  142365. 274, /* (247) trigger_event ::= UPDATE */
  142366. 274, /* (248) trigger_event ::= UPDATE OF idlist */
  142367. 276, /* (249) when_clause ::= */
  142368. 276, /* (250) when_clause ::= WHEN expr */
  142369. 272, /* (251) trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
  142370. 272, /* (252) trigger_cmd_list ::= trigger_cmd SEMI */
  142371. 278, /* (253) trnm ::= nm DOT nm */
  142372. 279, /* (254) tridxby ::= INDEXED BY nm */
  142373. 279, /* (255) tridxby ::= NOT INDEXED */
  142374. 277, /* (256) trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt scanpt */
  142375. 277, /* (257) trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt */
  142376. 277, /* (258) trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */
  142377. 277, /* (259) trigger_cmd ::= scanpt select scanpt */
  142378. 207, /* (260) expr ::= RAISE LP IGNORE RP */
  142379. 207, /* (261) expr ::= RAISE LP raisetype COMMA nm RP */
  142380. 225, /* (262) raisetype ::= ROLLBACK */
  142381. 225, /* (263) raisetype ::= ABORT */
  142382. 225, /* (264) raisetype ::= FAIL */
  142383. 181, /* (265) cmd ::= DROP TRIGGER ifexists fullname */
  142384. 181, /* (266) cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
  142385. 181, /* (267) cmd ::= DETACH database_kw_opt expr */
  142386. 281, /* (268) key_opt ::= */
  142387. 281, /* (269) key_opt ::= KEY expr */
  142388. 181, /* (270) cmd ::= REINDEX */
  142389. 181, /* (271) cmd ::= REINDEX nm dbnm */
  142390. 181, /* (272) cmd ::= ANALYZE */
  142391. 181, /* (273) cmd ::= ANALYZE nm dbnm */
  142392. 181, /* (274) cmd ::= ALTER TABLE fullname RENAME TO nm */
  142393. 181, /* (275) cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
  142394. 282, /* (276) add_column_fullname ::= fullname */
  142395. 181, /* (277) cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm */
  142396. 181, /* (278) cmd ::= create_vtab */
  142397. 181, /* (279) cmd ::= create_vtab LP vtabarglist RP */
  142398. 284, /* (280) create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
  142399. 286, /* (281) vtabarg ::= */
  142400. 287, /* (282) vtabargtoken ::= ANY */
  142401. 287, /* (283) vtabargtoken ::= lp anylist RP */
  142402. 288, /* (284) lp ::= LP */
  142403. 254, /* (285) with ::= WITH wqlist */
  142404. 254, /* (286) with ::= WITH RECURSIVE wqlist */
  142405. 230, /* (287) wqlist ::= nm eidlist_opt AS LP select RP */
  142406. 230, /* (288) wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP */
  142407. 290, /* (289) windowdefn_list ::= windowdefn */
  142408. 290, /* (290) windowdefn_list ::= windowdefn_list COMMA windowdefn */
  142409. 291, /* (291) windowdefn ::= nm AS LP window RP */
  142410. 292, /* (292) window ::= PARTITION BY nexprlist orderby_opt frame_opt */
  142411. 292, /* (293) window ::= nm PARTITION BY nexprlist orderby_opt frame_opt */
  142412. 292, /* (294) window ::= ORDER BY sortlist frame_opt */
  142413. 292, /* (295) window ::= nm ORDER BY sortlist frame_opt */
  142414. 292, /* (296) window ::= frame_opt */
  142415. 292, /* (297) window ::= nm frame_opt */
  142416. 293, /* (298) frame_opt ::= */
  142417. 293, /* (299) frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt */
  142418. 293, /* (300) frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt */
  142419. 296, /* (301) range_or_rows ::= RANGE|ROWS|GROUPS */
  142420. 298, /* (302) frame_bound_s ::= frame_bound */
  142421. 298, /* (303) frame_bound_s ::= UNBOUNDED PRECEDING */
  142422. 299, /* (304) frame_bound_e ::= frame_bound */
  142423. 299, /* (305) frame_bound_e ::= UNBOUNDED FOLLOWING */
  142424. 297, /* (306) frame_bound ::= expr PRECEDING|FOLLOWING */
  142425. 297, /* (307) frame_bound ::= CURRENT ROW */
  142426. 300, /* (308) frame_exclude_opt ::= */
  142427. 300, /* (309) frame_exclude_opt ::= EXCLUDE frame_exclude */
  142428. 301, /* (310) frame_exclude ::= NO OTHERS */
  142429. 301, /* (311) frame_exclude ::= CURRENT ROW */
  142430. 301, /* (312) frame_exclude ::= GROUP|TIES */
  142431. 240, /* (313) window_clause ::= WINDOW windowdefn_list */
  142432. 259, /* (314) over_clause ::= filter_opt OVER LP window RP */
  142433. 259, /* (315) over_clause ::= filter_opt OVER nm */
  142434. 295, /* (316) filter_opt ::= */
  142435. 295, /* (317) filter_opt ::= FILTER LP WHERE expr RP */
  142436. 176, /* (318) input ::= cmdlist */
  142437. 177, /* (319) cmdlist ::= cmdlist ecmd */
  142438. 177, /* (320) cmdlist ::= ecmd */
  142439. 178, /* (321) ecmd ::= SEMI */
  142440. 178, /* (322) ecmd ::= cmdx SEMI */
  142441. 178, /* (323) ecmd ::= explain cmdx */
  142442. 183, /* (324) trans_opt ::= */
  142443. 183, /* (325) trans_opt ::= TRANSACTION */
  142444. 183, /* (326) trans_opt ::= TRANSACTION nm */
  142445. 185, /* (327) savepoint_opt ::= SAVEPOINT */
  142446. 185, /* (328) savepoint_opt ::= */
  142447. 181, /* (329) cmd ::= create_table create_table_args */
  142448. 192, /* (330) columnlist ::= columnlist COMMA columnname carglist */
  142449. 192, /* (331) columnlist ::= columnname carglist */
  142450. 184, /* (332) nm ::= ID|INDEXED */
  142451. 184, /* (333) nm ::= STRING */
  142452. 184, /* (334) nm ::= JOIN_KW */
  142453. 198, /* (335) typetoken ::= typename */
  142454. 199, /* (336) typename ::= ID|STRING */
  142455. 200, /* (337) signed ::= plus_num */
  142456. 200, /* (338) signed ::= minus_num */
  142457. 197, /* (339) carglist ::= carglist ccons */
  142458. 197, /* (340) carglist ::= */
  142459. 205, /* (341) ccons ::= NULL onconf */
  142460. 193, /* (342) conslist_opt ::= COMMA conslist */
  142461. 217, /* (343) conslist ::= conslist tconscomma tcons */
  142462. 217, /* (344) conslist ::= tcons */
  142463. 218, /* (345) tconscomma ::= */
  142464. 222, /* (346) defer_subclause_opt ::= defer_subclause */
  142465. 224, /* (347) resolvetype ::= raisetype */
  142466. 228, /* (348) selectnowith ::= oneselect */
  142467. 229, /* (349) oneselect ::= values */
  142468. 243, /* (350) sclp ::= selcollist COMMA */
  142469. 244, /* (351) as ::= ID|STRING */
  142470. 207, /* (352) expr ::= term */
  142471. 260, /* (353) likeop ::= LIKE_KW|MATCH */
  142472. 251, /* (354) exprlist ::= nexprlist */
  142473. 270, /* (355) nmnum ::= plus_num */
  142474. 270, /* (356) nmnum ::= nm */
  142475. 270, /* (357) nmnum ::= ON */
  142476. 270, /* (358) nmnum ::= DELETE */
  142477. 270, /* (359) nmnum ::= DEFAULT */
  142478. 201, /* (360) plus_num ::= INTEGER|FLOAT */
  142479. 275, /* (361) foreach_clause ::= */
  142480. 275, /* (362) foreach_clause ::= FOR EACH ROW */
  142481. 278, /* (363) trnm ::= nm */
  142482. 279, /* (364) tridxby ::= */
  142483. 280, /* (365) database_kw_opt ::= DATABASE */
  142484. 280, /* (366) database_kw_opt ::= */
  142485. 283, /* (367) kwcolumn_opt ::= */
  142486. 283, /* (368) kwcolumn_opt ::= COLUMNKW */
  142487. 285, /* (369) vtabarglist ::= vtabarg */
  142488. 285, /* (370) vtabarglist ::= vtabarglist COMMA vtabarg */
  142489. 286, /* (371) vtabarg ::= vtabarg vtabargtoken */
  142490. 289, /* (372) anylist ::= */
  142491. 289, /* (373) anylist ::= anylist LP anylist RP */
  142492. 289, /* (374) anylist ::= anylist ANY */
  142493. 254, /* (375) with ::= */
  142494. };
  142495. /* For rule J, yyRuleInfoNRhs[J] contains the negative of the number
  142496. ** of symbols on the right-hand side of that rule. */
  142497. static const signed char yyRuleInfoNRhs[] = {
  142498. -1, /* (0) explain ::= EXPLAIN */
  142499. -3, /* (1) explain ::= EXPLAIN QUERY PLAN */
  142500. -1, /* (2) cmdx ::= cmd */
  142501. -3, /* (3) cmd ::= BEGIN transtype trans_opt */
  142502. 0, /* (4) transtype ::= */
  142503. -1, /* (5) transtype ::= DEFERRED */
  142504. -1, /* (6) transtype ::= IMMEDIATE */
  142505. -1, /* (7) transtype ::= EXCLUSIVE */
  142506. -2, /* (8) cmd ::= COMMIT|END trans_opt */
  142507. -2, /* (9) cmd ::= ROLLBACK trans_opt */
  142508. -2, /* (10) cmd ::= SAVEPOINT nm */
  142509. -3, /* (11) cmd ::= RELEASE savepoint_opt nm */
  142510. -5, /* (12) cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
  142511. -6, /* (13) create_table ::= createkw temp TABLE ifnotexists nm dbnm */
  142512. -1, /* (14) createkw ::= CREATE */
  142513. 0, /* (15) ifnotexists ::= */
  142514. -3, /* (16) ifnotexists ::= IF NOT EXISTS */
  142515. -1, /* (17) temp ::= TEMP */
  142516. 0, /* (18) temp ::= */
  142517. -5, /* (19) create_table_args ::= LP columnlist conslist_opt RP table_options */
  142518. -2, /* (20) create_table_args ::= AS select */
  142519. 0, /* (21) table_options ::= */
  142520. -2, /* (22) table_options ::= WITHOUT nm */
  142521. -2, /* (23) columnname ::= nm typetoken */
  142522. 0, /* (24) typetoken ::= */
  142523. -4, /* (25) typetoken ::= typename LP signed RP */
  142524. -6, /* (26) typetoken ::= typename LP signed COMMA signed RP */
  142525. -2, /* (27) typename ::= typename ID|STRING */
  142526. 0, /* (28) scanpt ::= */
  142527. 0, /* (29) scantok ::= */
  142528. -2, /* (30) ccons ::= CONSTRAINT nm */
  142529. -3, /* (31) ccons ::= DEFAULT scantok term */
  142530. -4, /* (32) ccons ::= DEFAULT LP expr RP */
  142531. -4, /* (33) ccons ::= DEFAULT PLUS scantok term */
  142532. -4, /* (34) ccons ::= DEFAULT MINUS scantok term */
  142533. -3, /* (35) ccons ::= DEFAULT scantok ID|INDEXED */
  142534. -3, /* (36) ccons ::= NOT NULL onconf */
  142535. -5, /* (37) ccons ::= PRIMARY KEY sortorder onconf autoinc */
  142536. -2, /* (38) ccons ::= UNIQUE onconf */
  142537. -4, /* (39) ccons ::= CHECK LP expr RP */
  142538. -4, /* (40) ccons ::= REFERENCES nm eidlist_opt refargs */
  142539. -1, /* (41) ccons ::= defer_subclause */
  142540. -2, /* (42) ccons ::= COLLATE ID|STRING */
  142541. 0, /* (43) autoinc ::= */
  142542. -1, /* (44) autoinc ::= AUTOINCR */
  142543. 0, /* (45) refargs ::= */
  142544. -2, /* (46) refargs ::= refargs refarg */
  142545. -2, /* (47) refarg ::= MATCH nm */
  142546. -3, /* (48) refarg ::= ON INSERT refact */
  142547. -3, /* (49) refarg ::= ON DELETE refact */
  142548. -3, /* (50) refarg ::= ON UPDATE refact */
  142549. -2, /* (51) refact ::= SET NULL */
  142550. -2, /* (52) refact ::= SET DEFAULT */
  142551. -1, /* (53) refact ::= CASCADE */
  142552. -1, /* (54) refact ::= RESTRICT */
  142553. -2, /* (55) refact ::= NO ACTION */
  142554. -3, /* (56) defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
  142555. -2, /* (57) defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
  142556. 0, /* (58) init_deferred_pred_opt ::= */
  142557. -2, /* (59) init_deferred_pred_opt ::= INITIALLY DEFERRED */
  142558. -2, /* (60) init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
  142559. 0, /* (61) conslist_opt ::= */
  142560. -1, /* (62) tconscomma ::= COMMA */
  142561. -2, /* (63) tcons ::= CONSTRAINT nm */
  142562. -7, /* (64) tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */
  142563. -5, /* (65) tcons ::= UNIQUE LP sortlist RP onconf */
  142564. -5, /* (66) tcons ::= CHECK LP expr RP onconf */
  142565. -10, /* (67) tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */
  142566. 0, /* (68) defer_subclause_opt ::= */
  142567. 0, /* (69) onconf ::= */
  142568. -3, /* (70) onconf ::= ON CONFLICT resolvetype */
  142569. 0, /* (71) orconf ::= */
  142570. -2, /* (72) orconf ::= OR resolvetype */
  142571. -1, /* (73) resolvetype ::= IGNORE */
  142572. -1, /* (74) resolvetype ::= REPLACE */
  142573. -4, /* (75) cmd ::= DROP TABLE ifexists fullname */
  142574. -2, /* (76) ifexists ::= IF EXISTS */
  142575. 0, /* (77) ifexists ::= */
  142576. -9, /* (78) cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */
  142577. -4, /* (79) cmd ::= DROP VIEW ifexists fullname */
  142578. -1, /* (80) cmd ::= select */
  142579. -3, /* (81) select ::= WITH wqlist selectnowith */
  142580. -4, /* (82) select ::= WITH RECURSIVE wqlist selectnowith */
  142581. -1, /* (83) select ::= selectnowith */
  142582. -3, /* (84) selectnowith ::= selectnowith multiselect_op oneselect */
  142583. -1, /* (85) multiselect_op ::= UNION */
  142584. -2, /* (86) multiselect_op ::= UNION ALL */
  142585. -1, /* (87) multiselect_op ::= EXCEPT|INTERSECT */
  142586. -9, /* (88) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
  142587. -10, /* (89) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt window_clause orderby_opt limit_opt */
  142588. -4, /* (90) values ::= VALUES LP nexprlist RP */
  142589. -5, /* (91) values ::= values COMMA LP nexprlist RP */
  142590. -1, /* (92) distinct ::= DISTINCT */
  142591. -1, /* (93) distinct ::= ALL */
  142592. 0, /* (94) distinct ::= */
  142593. 0, /* (95) sclp ::= */
  142594. -5, /* (96) selcollist ::= sclp scanpt expr scanpt as */
  142595. -3, /* (97) selcollist ::= sclp scanpt STAR */
  142596. -5, /* (98) selcollist ::= sclp scanpt nm DOT STAR */
  142597. -2, /* (99) as ::= AS nm */
  142598. 0, /* (100) as ::= */
  142599. 0, /* (101) from ::= */
  142600. -2, /* (102) from ::= FROM seltablist */
  142601. -2, /* (103) stl_prefix ::= seltablist joinop */
  142602. 0, /* (104) stl_prefix ::= */
  142603. -7, /* (105) seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
  142604. -9, /* (106) seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */
  142605. -7, /* (107) seltablist ::= stl_prefix LP select RP as on_opt using_opt */
  142606. -7, /* (108) seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
  142607. 0, /* (109) dbnm ::= */
  142608. -2, /* (110) dbnm ::= DOT nm */
  142609. -1, /* (111) fullname ::= nm */
  142610. -3, /* (112) fullname ::= nm DOT nm */
  142611. -1, /* (113) xfullname ::= nm */
  142612. -3, /* (114) xfullname ::= nm DOT nm */
  142613. -5, /* (115) xfullname ::= nm DOT nm AS nm */
  142614. -3, /* (116) xfullname ::= nm AS nm */
  142615. -1, /* (117) joinop ::= COMMA|JOIN */
  142616. -2, /* (118) joinop ::= JOIN_KW JOIN */
  142617. -3, /* (119) joinop ::= JOIN_KW nm JOIN */
  142618. -4, /* (120) joinop ::= JOIN_KW nm nm JOIN */
  142619. -2, /* (121) on_opt ::= ON expr */
  142620. 0, /* (122) on_opt ::= */
  142621. 0, /* (123) indexed_opt ::= */
  142622. -3, /* (124) indexed_opt ::= INDEXED BY nm */
  142623. -2, /* (125) indexed_opt ::= NOT INDEXED */
  142624. -4, /* (126) using_opt ::= USING LP idlist RP */
  142625. 0, /* (127) using_opt ::= */
  142626. 0, /* (128) orderby_opt ::= */
  142627. -3, /* (129) orderby_opt ::= ORDER BY sortlist */
  142628. -4, /* (130) sortlist ::= sortlist COMMA expr sortorder */
  142629. -2, /* (131) sortlist ::= expr sortorder */
  142630. -1, /* (132) sortorder ::= ASC */
  142631. -1, /* (133) sortorder ::= DESC */
  142632. 0, /* (134) sortorder ::= */
  142633. 0, /* (135) groupby_opt ::= */
  142634. -3, /* (136) groupby_opt ::= GROUP BY nexprlist */
  142635. 0, /* (137) having_opt ::= */
  142636. -2, /* (138) having_opt ::= HAVING expr */
  142637. 0, /* (139) limit_opt ::= */
  142638. -2, /* (140) limit_opt ::= LIMIT expr */
  142639. -4, /* (141) limit_opt ::= LIMIT expr OFFSET expr */
  142640. -4, /* (142) limit_opt ::= LIMIT expr COMMA expr */
  142641. -6, /* (143) cmd ::= with DELETE FROM xfullname indexed_opt where_opt */
  142642. 0, /* (144) where_opt ::= */
  142643. -2, /* (145) where_opt ::= WHERE expr */
  142644. -8, /* (146) cmd ::= with UPDATE orconf xfullname indexed_opt SET setlist where_opt */
  142645. -5, /* (147) setlist ::= setlist COMMA nm EQ expr */
  142646. -7, /* (148) setlist ::= setlist COMMA LP idlist RP EQ expr */
  142647. -3, /* (149) setlist ::= nm EQ expr */
  142648. -5, /* (150) setlist ::= LP idlist RP EQ expr */
  142649. -7, /* (151) cmd ::= with insert_cmd INTO xfullname idlist_opt select upsert */
  142650. -7, /* (152) cmd ::= with insert_cmd INTO xfullname idlist_opt DEFAULT VALUES */
  142651. 0, /* (153) upsert ::= */
  142652. -11, /* (154) upsert ::= ON CONFLICT LP sortlist RP where_opt DO UPDATE SET setlist where_opt */
  142653. -8, /* (155) upsert ::= ON CONFLICT LP sortlist RP where_opt DO NOTHING */
  142654. -4, /* (156) upsert ::= ON CONFLICT DO NOTHING */
  142655. -2, /* (157) insert_cmd ::= INSERT orconf */
  142656. -1, /* (158) insert_cmd ::= REPLACE */
  142657. 0, /* (159) idlist_opt ::= */
  142658. -3, /* (160) idlist_opt ::= LP idlist RP */
  142659. -3, /* (161) idlist ::= idlist COMMA nm */
  142660. -1, /* (162) idlist ::= nm */
  142661. -3, /* (163) expr ::= LP expr RP */
  142662. -1, /* (164) expr ::= ID|INDEXED */
  142663. -1, /* (165) expr ::= JOIN_KW */
  142664. -3, /* (166) expr ::= nm DOT nm */
  142665. -5, /* (167) expr ::= nm DOT nm DOT nm */
  142666. -1, /* (168) term ::= NULL|FLOAT|BLOB */
  142667. -1, /* (169) term ::= STRING */
  142668. -1, /* (170) term ::= INTEGER */
  142669. -1, /* (171) expr ::= VARIABLE */
  142670. -3, /* (172) expr ::= expr COLLATE ID|STRING */
  142671. -6, /* (173) expr ::= CAST LP expr AS typetoken RP */
  142672. -5, /* (174) expr ::= ID|INDEXED LP distinct exprlist RP */
  142673. -4, /* (175) expr ::= ID|INDEXED LP STAR RP */
  142674. -6, /* (176) expr ::= ID|INDEXED LP distinct exprlist RP over_clause */
  142675. -5, /* (177) expr ::= ID|INDEXED LP STAR RP over_clause */
  142676. -1, /* (178) term ::= CTIME_KW */
  142677. -5, /* (179) expr ::= LP nexprlist COMMA expr RP */
  142678. -3, /* (180) expr ::= expr AND expr */
  142679. -3, /* (181) expr ::= expr OR expr */
  142680. -3, /* (182) expr ::= expr LT|GT|GE|LE expr */
  142681. -3, /* (183) expr ::= expr EQ|NE expr */
  142682. -3, /* (184) expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */
  142683. -3, /* (185) expr ::= expr PLUS|MINUS expr */
  142684. -3, /* (186) expr ::= expr STAR|SLASH|REM expr */
  142685. -3, /* (187) expr ::= expr CONCAT expr */
  142686. -2, /* (188) likeop ::= NOT LIKE_KW|MATCH */
  142687. -3, /* (189) expr ::= expr likeop expr */
  142688. -5, /* (190) expr ::= expr likeop expr ESCAPE expr */
  142689. -2, /* (191) expr ::= expr ISNULL|NOTNULL */
  142690. -3, /* (192) expr ::= expr NOT NULL */
  142691. -3, /* (193) expr ::= expr IS expr */
  142692. -4, /* (194) expr ::= expr IS NOT expr */
  142693. -2, /* (195) expr ::= NOT expr */
  142694. -2, /* (196) expr ::= BITNOT expr */
  142695. -2, /* (197) expr ::= PLUS|MINUS expr */
  142696. -1, /* (198) between_op ::= BETWEEN */
  142697. -2, /* (199) between_op ::= NOT BETWEEN */
  142698. -5, /* (200) expr ::= expr between_op expr AND expr */
  142699. -1, /* (201) in_op ::= IN */
  142700. -2, /* (202) in_op ::= NOT IN */
  142701. -5, /* (203) expr ::= expr in_op LP exprlist RP */
  142702. -3, /* (204) expr ::= LP select RP */
  142703. -5, /* (205) expr ::= expr in_op LP select RP */
  142704. -5, /* (206) expr ::= expr in_op nm dbnm paren_exprlist */
  142705. -4, /* (207) expr ::= EXISTS LP select RP */
  142706. -5, /* (208) expr ::= CASE case_operand case_exprlist case_else END */
  142707. -5, /* (209) case_exprlist ::= case_exprlist WHEN expr THEN expr */
  142708. -4, /* (210) case_exprlist ::= WHEN expr THEN expr */
  142709. -2, /* (211) case_else ::= ELSE expr */
  142710. 0, /* (212) case_else ::= */
  142711. -1, /* (213) case_operand ::= expr */
  142712. 0, /* (214) case_operand ::= */
  142713. 0, /* (215) exprlist ::= */
  142714. -3, /* (216) nexprlist ::= nexprlist COMMA expr */
  142715. -1, /* (217) nexprlist ::= expr */
  142716. 0, /* (218) paren_exprlist ::= */
  142717. -3, /* (219) paren_exprlist ::= LP exprlist RP */
  142718. -12, /* (220) cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
  142719. -1, /* (221) uniqueflag ::= UNIQUE */
  142720. 0, /* (222) uniqueflag ::= */
  142721. 0, /* (223) eidlist_opt ::= */
  142722. -3, /* (224) eidlist_opt ::= LP eidlist RP */
  142723. -5, /* (225) eidlist ::= eidlist COMMA nm collate sortorder */
  142724. -3, /* (226) eidlist ::= nm collate sortorder */
  142725. 0, /* (227) collate ::= */
  142726. -2, /* (228) collate ::= COLLATE ID|STRING */
  142727. -4, /* (229) cmd ::= DROP INDEX ifexists fullname */
  142728. -2, /* (230) cmd ::= VACUUM vinto */
  142729. -3, /* (231) cmd ::= VACUUM nm vinto */
  142730. -2, /* (232) vinto ::= INTO expr */
  142731. 0, /* (233) vinto ::= */
  142732. -3, /* (234) cmd ::= PRAGMA nm dbnm */
  142733. -5, /* (235) cmd ::= PRAGMA nm dbnm EQ nmnum */
  142734. -6, /* (236) cmd ::= PRAGMA nm dbnm LP nmnum RP */
  142735. -5, /* (237) cmd ::= PRAGMA nm dbnm EQ minus_num */
  142736. -6, /* (238) cmd ::= PRAGMA nm dbnm LP minus_num RP */
  142737. -2, /* (239) plus_num ::= PLUS INTEGER|FLOAT */
  142738. -2, /* (240) minus_num ::= MINUS INTEGER|FLOAT */
  142739. -5, /* (241) cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
  142740. -11, /* (242) trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
  142741. -1, /* (243) trigger_time ::= BEFORE|AFTER */
  142742. -2, /* (244) trigger_time ::= INSTEAD OF */
  142743. 0, /* (245) trigger_time ::= */
  142744. -1, /* (246) trigger_event ::= DELETE|INSERT */
  142745. -1, /* (247) trigger_event ::= UPDATE */
  142746. -3, /* (248) trigger_event ::= UPDATE OF idlist */
  142747. 0, /* (249) when_clause ::= */
  142748. -2, /* (250) when_clause ::= WHEN expr */
  142749. -3, /* (251) trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
  142750. -2, /* (252) trigger_cmd_list ::= trigger_cmd SEMI */
  142751. -3, /* (253) trnm ::= nm DOT nm */
  142752. -3, /* (254) tridxby ::= INDEXED BY nm */
  142753. -2, /* (255) tridxby ::= NOT INDEXED */
  142754. -8, /* (256) trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt scanpt */
  142755. -8, /* (257) trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt */
  142756. -6, /* (258) trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */
  142757. -3, /* (259) trigger_cmd ::= scanpt select scanpt */
  142758. -4, /* (260) expr ::= RAISE LP IGNORE RP */
  142759. -6, /* (261) expr ::= RAISE LP raisetype COMMA nm RP */
  142760. -1, /* (262) raisetype ::= ROLLBACK */
  142761. -1, /* (263) raisetype ::= ABORT */
  142762. -1, /* (264) raisetype ::= FAIL */
  142763. -4, /* (265) cmd ::= DROP TRIGGER ifexists fullname */
  142764. -6, /* (266) cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
  142765. -3, /* (267) cmd ::= DETACH database_kw_opt expr */
  142766. 0, /* (268) key_opt ::= */
  142767. -2, /* (269) key_opt ::= KEY expr */
  142768. -1, /* (270) cmd ::= REINDEX */
  142769. -3, /* (271) cmd ::= REINDEX nm dbnm */
  142770. -1, /* (272) cmd ::= ANALYZE */
  142771. -3, /* (273) cmd ::= ANALYZE nm dbnm */
  142772. -6, /* (274) cmd ::= ALTER TABLE fullname RENAME TO nm */
  142773. -7, /* (275) cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
  142774. -1, /* (276) add_column_fullname ::= fullname */
  142775. -8, /* (277) cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm */
  142776. -1, /* (278) cmd ::= create_vtab */
  142777. -4, /* (279) cmd ::= create_vtab LP vtabarglist RP */
  142778. -8, /* (280) create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
  142779. 0, /* (281) vtabarg ::= */
  142780. -1, /* (282) vtabargtoken ::= ANY */
  142781. -3, /* (283) vtabargtoken ::= lp anylist RP */
  142782. -1, /* (284) lp ::= LP */
  142783. -2, /* (285) with ::= WITH wqlist */
  142784. -3, /* (286) with ::= WITH RECURSIVE wqlist */
  142785. -6, /* (287) wqlist ::= nm eidlist_opt AS LP select RP */
  142786. -8, /* (288) wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP */
  142787. -1, /* (289) windowdefn_list ::= windowdefn */
  142788. -3, /* (290) windowdefn_list ::= windowdefn_list COMMA windowdefn */
  142789. -5, /* (291) windowdefn ::= nm AS LP window RP */
  142790. -5, /* (292) window ::= PARTITION BY nexprlist orderby_opt frame_opt */
  142791. -6, /* (293) window ::= nm PARTITION BY nexprlist orderby_opt frame_opt */
  142792. -4, /* (294) window ::= ORDER BY sortlist frame_opt */
  142793. -5, /* (295) window ::= nm ORDER BY sortlist frame_opt */
  142794. -1, /* (296) window ::= frame_opt */
  142795. -2, /* (297) window ::= nm frame_opt */
  142796. 0, /* (298) frame_opt ::= */
  142797. -3, /* (299) frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt */
  142798. -6, /* (300) frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt */
  142799. -1, /* (301) range_or_rows ::= RANGE|ROWS|GROUPS */
  142800. -1, /* (302) frame_bound_s ::= frame_bound */
  142801. -2, /* (303) frame_bound_s ::= UNBOUNDED PRECEDING */
  142802. -1, /* (304) frame_bound_e ::= frame_bound */
  142803. -2, /* (305) frame_bound_e ::= UNBOUNDED FOLLOWING */
  142804. -2, /* (306) frame_bound ::= expr PRECEDING|FOLLOWING */
  142805. -2, /* (307) frame_bound ::= CURRENT ROW */
  142806. 0, /* (308) frame_exclude_opt ::= */
  142807. -2, /* (309) frame_exclude_opt ::= EXCLUDE frame_exclude */
  142808. -2, /* (310) frame_exclude ::= NO OTHERS */
  142809. -2, /* (311) frame_exclude ::= CURRENT ROW */
  142810. -1, /* (312) frame_exclude ::= GROUP|TIES */
  142811. -2, /* (313) window_clause ::= WINDOW windowdefn_list */
  142812. -5, /* (314) over_clause ::= filter_opt OVER LP window RP */
  142813. -3, /* (315) over_clause ::= filter_opt OVER nm */
  142814. 0, /* (316) filter_opt ::= */
  142815. -5, /* (317) filter_opt ::= FILTER LP WHERE expr RP */
  142816. -1, /* (318) input ::= cmdlist */
  142817. -2, /* (319) cmdlist ::= cmdlist ecmd */
  142818. -1, /* (320) cmdlist ::= ecmd */
  142819. -1, /* (321) ecmd ::= SEMI */
  142820. -2, /* (322) ecmd ::= cmdx SEMI */
  142821. -2, /* (323) ecmd ::= explain cmdx */
  142822. 0, /* (324) trans_opt ::= */
  142823. -1, /* (325) trans_opt ::= TRANSACTION */
  142824. -2, /* (326) trans_opt ::= TRANSACTION nm */
  142825. -1, /* (327) savepoint_opt ::= SAVEPOINT */
  142826. 0, /* (328) savepoint_opt ::= */
  142827. -2, /* (329) cmd ::= create_table create_table_args */
  142828. -4, /* (330) columnlist ::= columnlist COMMA columnname carglist */
  142829. -2, /* (331) columnlist ::= columnname carglist */
  142830. -1, /* (332) nm ::= ID|INDEXED */
  142831. -1, /* (333) nm ::= STRING */
  142832. -1, /* (334) nm ::= JOIN_KW */
  142833. -1, /* (335) typetoken ::= typename */
  142834. -1, /* (336) typename ::= ID|STRING */
  142835. -1, /* (337) signed ::= plus_num */
  142836. -1, /* (338) signed ::= minus_num */
  142837. -2, /* (339) carglist ::= carglist ccons */
  142838. 0, /* (340) carglist ::= */
  142839. -2, /* (341) ccons ::= NULL onconf */
  142840. -2, /* (342) conslist_opt ::= COMMA conslist */
  142841. -3, /* (343) conslist ::= conslist tconscomma tcons */
  142842. -1, /* (344) conslist ::= tcons */
  142843. 0, /* (345) tconscomma ::= */
  142844. -1, /* (346) defer_subclause_opt ::= defer_subclause */
  142845. -1, /* (347) resolvetype ::= raisetype */
  142846. -1, /* (348) selectnowith ::= oneselect */
  142847. -1, /* (349) oneselect ::= values */
  142848. -2, /* (350) sclp ::= selcollist COMMA */
  142849. -1, /* (351) as ::= ID|STRING */
  142850. -1, /* (352) expr ::= term */
  142851. -1, /* (353) likeop ::= LIKE_KW|MATCH */
  142852. -1, /* (354) exprlist ::= nexprlist */
  142853. -1, /* (355) nmnum ::= plus_num */
  142854. -1, /* (356) nmnum ::= nm */
  142855. -1, /* (357) nmnum ::= ON */
  142856. -1, /* (358) nmnum ::= DELETE */
  142857. -1, /* (359) nmnum ::= DEFAULT */
  142858. -1, /* (360) plus_num ::= INTEGER|FLOAT */
  142859. 0, /* (361) foreach_clause ::= */
  142860. -3, /* (362) foreach_clause ::= FOR EACH ROW */
  142861. -1, /* (363) trnm ::= nm */
  142862. 0, /* (364) tridxby ::= */
  142863. -1, /* (365) database_kw_opt ::= DATABASE */
  142864. 0, /* (366) database_kw_opt ::= */
  142865. 0, /* (367) kwcolumn_opt ::= */
  142866. -1, /* (368) kwcolumn_opt ::= COLUMNKW */
  142867. -1, /* (369) vtabarglist ::= vtabarg */
  142868. -3, /* (370) vtabarglist ::= vtabarglist COMMA vtabarg */
  142869. -2, /* (371) vtabarg ::= vtabarg vtabargtoken */
  142870. 0, /* (372) anylist ::= */
  142871. -4, /* (373) anylist ::= anylist LP anylist RP */
  142872. -2, /* (374) anylist ::= anylist ANY */
  142873. 0, /* (375) with ::= */
  142874. };
  142875. static void yy_accept(yyParser*); /* Forward Declaration */
  142876. /*
  142877. ** Perform a reduce action and the shift that must immediately
  142878. ** follow the reduce.
  142879. **
  142880. ** The yyLookahead and yyLookaheadToken parameters provide reduce actions
  142881. ** access to the lookahead token (if any). The yyLookahead will be YYNOCODE
  142882. ** if the lookahead token has already been consumed. As this procedure is
  142883. ** only called from one place, optimizing compilers will in-line it, which
  142884. ** means that the extra parameters have no performance impact.
  142885. */
  142886. static YYACTIONTYPE yy_reduce(
  142887. yyParser *yypParser, /* The parser */
  142888. unsigned int yyruleno, /* Number of the rule by which to reduce */
  142889. int yyLookahead, /* Lookahead token, or YYNOCODE if none */
  142890. sqlite3ParserTOKENTYPE yyLookaheadToken /* Value of the lookahead token */
  142891. sqlite3ParserCTX_PDECL /* %extra_context */
  142892. ){
  142893. int yygoto; /* The next state */
  142894. YYACTIONTYPE yyact; /* The next action */
  142895. yyStackEntry *yymsp; /* The top of the parser's stack */
  142896. int yysize; /* Amount to pop the stack */
  142897. sqlite3ParserARG_FETCH
  142898. (void)yyLookahead;
  142899. (void)yyLookaheadToken;
  142900. yymsp = yypParser->yytos;
  142901. #ifndef NDEBUG
  142902. if( yyTraceFILE && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
  142903. yysize = yyRuleInfoNRhs[yyruleno];
  142904. if( yysize ){
  142905. fprintf(yyTraceFILE, "%sReduce %d [%s], go to state %d.\n",
  142906. yyTracePrompt,
  142907. yyruleno, yyRuleName[yyruleno], yymsp[yysize].stateno);
  142908. }else{
  142909. fprintf(yyTraceFILE, "%sReduce %d [%s].\n",
  142910. yyTracePrompt, yyruleno, yyRuleName[yyruleno]);
  142911. }
  142912. }
  142913. #endif /* NDEBUG */
  142914. /* Check that the stack is large enough to grow by a single entry
  142915. ** if the RHS of the rule is empty. This ensures that there is room
  142916. ** enough on the stack to push the LHS value */
  142917. if( yyRuleInfoNRhs[yyruleno]==0 ){
  142918. #ifdef YYTRACKMAXSTACKDEPTH
  142919. if( (int)(yypParser->yytos - yypParser->yystack)>yypParser->yyhwm ){
  142920. yypParser->yyhwm++;
  142921. assert( yypParser->yyhwm == (int)(yypParser->yytos - yypParser->yystack));
  142922. }
  142923. #endif
  142924. #if YYSTACKDEPTH>0
  142925. if( yypParser->yytos>=yypParser->yystackEnd ){
  142926. yyStackOverflow(yypParser);
  142927. /* The call to yyStackOverflow() above pops the stack until it is
  142928. ** empty, causing the main parser loop to exit. So the return value
  142929. ** is never used and does not matter. */
  142930. return 0;
  142931. }
  142932. #else
  142933. if( yypParser->yytos>=&yypParser->yystack[yypParser->yystksz-1] ){
  142934. if( yyGrowStack(yypParser) ){
  142935. yyStackOverflow(yypParser);
  142936. /* The call to yyStackOverflow() above pops the stack until it is
  142937. ** empty, causing the main parser loop to exit. So the return value
  142938. ** is never used and does not matter. */
  142939. return 0;
  142940. }
  142941. yymsp = yypParser->yytos;
  142942. }
  142943. #endif
  142944. }
  142945. switch( yyruleno ){
  142946. /* Beginning here are the reduction cases. A typical example
  142947. ** follows:
  142948. ** case 0:
  142949. ** #line <lineno> <grammarfile>
  142950. ** { ... } // User supplied code
  142951. ** #line <lineno> <thisfile>
  142952. ** break;
  142953. */
  142954. /********** Begin reduce actions **********************************************/
  142955. YYMINORTYPE yylhsminor;
  142956. case 0: /* explain ::= EXPLAIN */
  142957. { pParse->explain = 1; }
  142958. break;
  142959. case 1: /* explain ::= EXPLAIN QUERY PLAN */
  142960. { pParse->explain = 2; }
  142961. break;
  142962. case 2: /* cmdx ::= cmd */
  142963. { sqlite3FinishCoding(pParse); }
  142964. break;
  142965. case 3: /* cmd ::= BEGIN transtype trans_opt */
  142966. {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy100);}
  142967. break;
  142968. case 4: /* transtype ::= */
  142969. {yymsp[1].minor.yy100 = TK_DEFERRED;}
  142970. break;
  142971. case 5: /* transtype ::= DEFERRED */
  142972. case 6: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==6);
  142973. case 7: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==7);
  142974. case 301: /* range_or_rows ::= RANGE|ROWS|GROUPS */ yytestcase(yyruleno==301);
  142975. {yymsp[0].minor.yy100 = yymsp[0].major; /*A-overwrites-X*/}
  142976. break;
  142977. case 8: /* cmd ::= COMMIT|END trans_opt */
  142978. case 9: /* cmd ::= ROLLBACK trans_opt */ yytestcase(yyruleno==9);
  142979. {sqlite3EndTransaction(pParse,yymsp[-1].major);}
  142980. break;
  142981. case 10: /* cmd ::= SAVEPOINT nm */
  142982. {
  142983. sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
  142984. }
  142985. break;
  142986. case 11: /* cmd ::= RELEASE savepoint_opt nm */
  142987. {
  142988. sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
  142989. }
  142990. break;
  142991. case 12: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
  142992. {
  142993. sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
  142994. }
  142995. break;
  142996. case 13: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
  142997. {
  142998. sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy100,0,0,yymsp[-2].minor.yy100);
  142999. }
  143000. break;
  143001. case 14: /* createkw ::= CREATE */
  143002. {disableLookaside(pParse);}
  143003. break;
  143004. case 15: /* ifnotexists ::= */
  143005. case 18: /* temp ::= */ yytestcase(yyruleno==18);
  143006. case 21: /* table_options ::= */ yytestcase(yyruleno==21);
  143007. case 43: /* autoinc ::= */ yytestcase(yyruleno==43);
  143008. case 58: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==58);
  143009. case 68: /* defer_subclause_opt ::= */ yytestcase(yyruleno==68);
  143010. case 77: /* ifexists ::= */ yytestcase(yyruleno==77);
  143011. case 94: /* distinct ::= */ yytestcase(yyruleno==94);
  143012. case 227: /* collate ::= */ yytestcase(yyruleno==227);
  143013. {yymsp[1].minor.yy100 = 0;}
  143014. break;
  143015. case 16: /* ifnotexists ::= IF NOT EXISTS */
  143016. {yymsp[-2].minor.yy100 = 1;}
  143017. break;
  143018. case 17: /* temp ::= TEMP */
  143019. case 44: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==44);
  143020. {yymsp[0].minor.yy100 = 1;}
  143021. break;
  143022. case 19: /* create_table_args ::= LP columnlist conslist_opt RP table_options */
  143023. {
  143024. sqlite3EndTable(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,yymsp[0].minor.yy100,0);
  143025. }
  143026. break;
  143027. case 20: /* create_table_args ::= AS select */
  143028. {
  143029. sqlite3EndTable(pParse,0,0,0,yymsp[0].minor.yy391);
  143030. sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy391);
  143031. }
  143032. break;
  143033. case 22: /* table_options ::= WITHOUT nm */
  143034. {
  143035. if( yymsp[0].minor.yy0.n==5 && sqlite3_strnicmp(yymsp[0].minor.yy0.z,"rowid",5)==0 ){
  143036. yymsp[-1].minor.yy100 = TF_WithoutRowid | TF_NoVisibleRowid;
  143037. }else{
  143038. yymsp[-1].minor.yy100 = 0;
  143039. sqlite3ErrorMsg(pParse, "unknown table option: %.*s", yymsp[0].minor.yy0.n, yymsp[0].minor.yy0.z);
  143040. }
  143041. }
  143042. break;
  143043. case 23: /* columnname ::= nm typetoken */
  143044. {sqlite3AddColumn(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
  143045. break;
  143046. case 24: /* typetoken ::= */
  143047. case 61: /* conslist_opt ::= */ yytestcase(yyruleno==61);
  143048. case 100: /* as ::= */ yytestcase(yyruleno==100);
  143049. {yymsp[1].minor.yy0.n = 0; yymsp[1].minor.yy0.z = 0;}
  143050. break;
  143051. case 25: /* typetoken ::= typename LP signed RP */
  143052. {
  143053. yymsp[-3].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
  143054. }
  143055. break;
  143056. case 26: /* typetoken ::= typename LP signed COMMA signed RP */
  143057. {
  143058. yymsp[-5].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
  143059. }
  143060. break;
  143061. case 27: /* typename ::= typename ID|STRING */
  143062. {yymsp[-1].minor.yy0.n=yymsp[0].minor.yy0.n+(int)(yymsp[0].minor.yy0.z-yymsp[-1].minor.yy0.z);}
  143063. break;
  143064. case 28: /* scanpt ::= */
  143065. {
  143066. assert( yyLookahead!=YYNOCODE );
  143067. yymsp[1].minor.yy528 = yyLookaheadToken.z;
  143068. }
  143069. break;
  143070. case 29: /* scantok ::= */
  143071. {
  143072. assert( yyLookahead!=YYNOCODE );
  143073. yymsp[1].minor.yy0 = yyLookaheadToken;
  143074. }
  143075. break;
  143076. case 30: /* ccons ::= CONSTRAINT nm */
  143077. case 63: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==63);
  143078. {pParse->constraintName = yymsp[0].minor.yy0;}
  143079. break;
  143080. case 31: /* ccons ::= DEFAULT scantok term */
  143081. {sqlite3AddDefaultValue(pParse,yymsp[0].minor.yy102,yymsp[-1].minor.yy0.z,&yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n]);}
  143082. break;
  143083. case 32: /* ccons ::= DEFAULT LP expr RP */
  143084. {sqlite3AddDefaultValue(pParse,yymsp[-1].minor.yy102,yymsp[-2].minor.yy0.z+1,yymsp[0].minor.yy0.z);}
  143085. break;
  143086. case 33: /* ccons ::= DEFAULT PLUS scantok term */
  143087. {sqlite3AddDefaultValue(pParse,yymsp[0].minor.yy102,yymsp[-2].minor.yy0.z,&yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n]);}
  143088. break;
  143089. case 34: /* ccons ::= DEFAULT MINUS scantok term */
  143090. {
  143091. Expr *p = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy102, 0);
  143092. sqlite3AddDefaultValue(pParse,p,yymsp[-2].minor.yy0.z,&yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n]);
  143093. }
  143094. break;
  143095. case 35: /* ccons ::= DEFAULT scantok ID|INDEXED */
  143096. {
  143097. Expr *p = tokenExpr(pParse, TK_STRING, yymsp[0].minor.yy0);
  143098. if( p ){
  143099. sqlite3ExprIdToTrueFalse(p);
  143100. testcase( p->op==TK_TRUEFALSE && sqlite3ExprTruthValue(p) );
  143101. }
  143102. sqlite3AddDefaultValue(pParse,p,yymsp[0].minor.yy0.z,yymsp[0].minor.yy0.z+yymsp[0].minor.yy0.n);
  143103. }
  143104. break;
  143105. case 36: /* ccons ::= NOT NULL onconf */
  143106. {sqlite3AddNotNull(pParse, yymsp[0].minor.yy100);}
  143107. break;
  143108. case 37: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
  143109. {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy100,yymsp[0].minor.yy100,yymsp[-2].minor.yy100);}
  143110. break;
  143111. case 38: /* ccons ::= UNIQUE onconf */
  143112. {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy100,0,0,0,0,
  143113. SQLITE_IDXTYPE_UNIQUE);}
  143114. break;
  143115. case 39: /* ccons ::= CHECK LP expr RP */
  143116. {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy102);}
  143117. break;
  143118. case 40: /* ccons ::= REFERENCES nm eidlist_opt refargs */
  143119. {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy94,yymsp[0].minor.yy100);}
  143120. break;
  143121. case 41: /* ccons ::= defer_subclause */
  143122. {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy100);}
  143123. break;
  143124. case 42: /* ccons ::= COLLATE ID|STRING */
  143125. {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
  143126. break;
  143127. case 45: /* refargs ::= */
  143128. { yymsp[1].minor.yy100 = OE_None*0x0101; /* EV: R-19803-45884 */}
  143129. break;
  143130. case 46: /* refargs ::= refargs refarg */
  143131. { yymsp[-1].minor.yy100 = (yymsp[-1].minor.yy100 & ~yymsp[0].minor.yy199.mask) | yymsp[0].minor.yy199.value; }
  143132. break;
  143133. case 47: /* refarg ::= MATCH nm */
  143134. { yymsp[-1].minor.yy199.value = 0; yymsp[-1].minor.yy199.mask = 0x000000; }
  143135. break;
  143136. case 48: /* refarg ::= ON INSERT refact */
  143137. { yymsp[-2].minor.yy199.value = 0; yymsp[-2].minor.yy199.mask = 0x000000; }
  143138. break;
  143139. case 49: /* refarg ::= ON DELETE refact */
  143140. { yymsp[-2].minor.yy199.value = yymsp[0].minor.yy100; yymsp[-2].minor.yy199.mask = 0x0000ff; }
  143141. break;
  143142. case 50: /* refarg ::= ON UPDATE refact */
  143143. { yymsp[-2].minor.yy199.value = yymsp[0].minor.yy100<<8; yymsp[-2].minor.yy199.mask = 0x00ff00; }
  143144. break;
  143145. case 51: /* refact ::= SET NULL */
  143146. { yymsp[-1].minor.yy100 = OE_SetNull; /* EV: R-33326-45252 */}
  143147. break;
  143148. case 52: /* refact ::= SET DEFAULT */
  143149. { yymsp[-1].minor.yy100 = OE_SetDflt; /* EV: R-33326-45252 */}
  143150. break;
  143151. case 53: /* refact ::= CASCADE */
  143152. { yymsp[0].minor.yy100 = OE_Cascade; /* EV: R-33326-45252 */}
  143153. break;
  143154. case 54: /* refact ::= RESTRICT */
  143155. { yymsp[0].minor.yy100 = OE_Restrict; /* EV: R-33326-45252 */}
  143156. break;
  143157. case 55: /* refact ::= NO ACTION */
  143158. { yymsp[-1].minor.yy100 = OE_None; /* EV: R-33326-45252 */}
  143159. break;
  143160. case 56: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
  143161. {yymsp[-2].minor.yy100 = 0;}
  143162. break;
  143163. case 57: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
  143164. case 72: /* orconf ::= OR resolvetype */ yytestcase(yyruleno==72);
  143165. case 157: /* insert_cmd ::= INSERT orconf */ yytestcase(yyruleno==157);
  143166. {yymsp[-1].minor.yy100 = yymsp[0].minor.yy100;}
  143167. break;
  143168. case 59: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */
  143169. case 76: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==76);
  143170. case 199: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==199);
  143171. case 202: /* in_op ::= NOT IN */ yytestcase(yyruleno==202);
  143172. case 228: /* collate ::= COLLATE ID|STRING */ yytestcase(yyruleno==228);
  143173. {yymsp[-1].minor.yy100 = 1;}
  143174. break;
  143175. case 60: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
  143176. {yymsp[-1].minor.yy100 = 0;}
  143177. break;
  143178. case 62: /* tconscomma ::= COMMA */
  143179. {pParse->constraintName.n = 0;}
  143180. break;
  143181. case 64: /* tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */
  143182. {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy94,yymsp[0].minor.yy100,yymsp[-2].minor.yy100,0);}
  143183. break;
  143184. case 65: /* tcons ::= UNIQUE LP sortlist RP onconf */
  143185. {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy94,yymsp[0].minor.yy100,0,0,0,0,
  143186. SQLITE_IDXTYPE_UNIQUE);}
  143187. break;
  143188. case 66: /* tcons ::= CHECK LP expr RP onconf */
  143189. {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy102);}
  143190. break;
  143191. case 67: /* tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */
  143192. {
  143193. sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy94, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy94, yymsp[-1].minor.yy100);
  143194. sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy100);
  143195. }
  143196. break;
  143197. case 69: /* onconf ::= */
  143198. case 71: /* orconf ::= */ yytestcase(yyruleno==71);
  143199. {yymsp[1].minor.yy100 = OE_Default;}
  143200. break;
  143201. case 70: /* onconf ::= ON CONFLICT resolvetype */
  143202. {yymsp[-2].minor.yy100 = yymsp[0].minor.yy100;}
  143203. break;
  143204. case 73: /* resolvetype ::= IGNORE */
  143205. {yymsp[0].minor.yy100 = OE_Ignore;}
  143206. break;
  143207. case 74: /* resolvetype ::= REPLACE */
  143208. case 158: /* insert_cmd ::= REPLACE */ yytestcase(yyruleno==158);
  143209. {yymsp[0].minor.yy100 = OE_Replace;}
  143210. break;
  143211. case 75: /* cmd ::= DROP TABLE ifexists fullname */
  143212. {
  143213. sqlite3DropTable(pParse, yymsp[0].minor.yy407, 0, yymsp[-1].minor.yy100);
  143214. }
  143215. break;
  143216. case 78: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */
  143217. {
  143218. sqlite3CreateView(pParse, &yymsp[-8].minor.yy0, &yymsp[-4].minor.yy0, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy94, yymsp[0].minor.yy391, yymsp[-7].minor.yy100, yymsp[-5].minor.yy100);
  143219. }
  143220. break;
  143221. case 79: /* cmd ::= DROP VIEW ifexists fullname */
  143222. {
  143223. sqlite3DropTable(pParse, yymsp[0].minor.yy407, 1, yymsp[-1].minor.yy100);
  143224. }
  143225. break;
  143226. case 80: /* cmd ::= select */
  143227. {
  143228. SelectDest dest = {SRT_Output, 0, 0, 0, 0, 0};
  143229. sqlite3Select(pParse, yymsp[0].minor.yy391, &dest);
  143230. sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy391);
  143231. }
  143232. break;
  143233. case 81: /* select ::= WITH wqlist selectnowith */
  143234. {
  143235. Select *p = yymsp[0].minor.yy391;
  143236. if( p ){
  143237. p->pWith = yymsp[-1].minor.yy243;
  143238. parserDoubleLinkSelect(pParse, p);
  143239. }else{
  143240. sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy243);
  143241. }
  143242. yymsp[-2].minor.yy391 = p;
  143243. }
  143244. break;
  143245. case 82: /* select ::= WITH RECURSIVE wqlist selectnowith */
  143246. {
  143247. Select *p = yymsp[0].minor.yy391;
  143248. if( p ){
  143249. p->pWith = yymsp[-1].minor.yy243;
  143250. parserDoubleLinkSelect(pParse, p);
  143251. }else{
  143252. sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy243);
  143253. }
  143254. yymsp[-3].minor.yy391 = p;
  143255. }
  143256. break;
  143257. case 83: /* select ::= selectnowith */
  143258. {
  143259. Select *p = yymsp[0].minor.yy391;
  143260. if( p ){
  143261. parserDoubleLinkSelect(pParse, p);
  143262. }
  143263. yymsp[0].minor.yy391 = p; /*A-overwrites-X*/
  143264. }
  143265. break;
  143266. case 84: /* selectnowith ::= selectnowith multiselect_op oneselect */
  143267. {
  143268. Select *pRhs = yymsp[0].minor.yy391;
  143269. Select *pLhs = yymsp[-2].minor.yy391;
  143270. if( pRhs && pRhs->pPrior ){
  143271. SrcList *pFrom;
  143272. Token x;
  143273. x.n = 0;
  143274. parserDoubleLinkSelect(pParse, pRhs);
  143275. pFrom = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&x,pRhs,0,0);
  143276. pRhs = sqlite3SelectNew(pParse,0,pFrom,0,0,0,0,0,0);
  143277. }
  143278. if( pRhs ){
  143279. pRhs->op = (u8)yymsp[-1].minor.yy100;
  143280. pRhs->pPrior = pLhs;
  143281. if( ALWAYS(pLhs) ) pLhs->selFlags &= ~SF_MultiValue;
  143282. pRhs->selFlags &= ~SF_MultiValue;
  143283. if( yymsp[-1].minor.yy100!=TK_ALL ) pParse->hasCompound = 1;
  143284. }else{
  143285. sqlite3SelectDelete(pParse->db, pLhs);
  143286. }
  143287. yymsp[-2].minor.yy391 = pRhs;
  143288. }
  143289. break;
  143290. case 85: /* multiselect_op ::= UNION */
  143291. case 87: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==87);
  143292. {yymsp[0].minor.yy100 = yymsp[0].major; /*A-overwrites-OP*/}
  143293. break;
  143294. case 86: /* multiselect_op ::= UNION ALL */
  143295. {yymsp[-1].minor.yy100 = TK_ALL;}
  143296. break;
  143297. case 88: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
  143298. {
  143299. yymsp[-8].minor.yy391 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy94,yymsp[-5].minor.yy407,yymsp[-4].minor.yy102,yymsp[-3].minor.yy94,yymsp[-2].minor.yy102,yymsp[-1].minor.yy94,yymsp[-7].minor.yy100,yymsp[0].minor.yy102);
  143300. }
  143301. break;
  143302. case 89: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt window_clause orderby_opt limit_opt */
  143303. {
  143304. yymsp[-9].minor.yy391 = sqlite3SelectNew(pParse,yymsp[-7].minor.yy94,yymsp[-6].minor.yy407,yymsp[-5].minor.yy102,yymsp[-4].minor.yy94,yymsp[-3].minor.yy102,yymsp[-1].minor.yy94,yymsp[-8].minor.yy100,yymsp[0].minor.yy102);
  143305. if( yymsp[-9].minor.yy391 ){
  143306. yymsp[-9].minor.yy391->pWinDefn = yymsp[-2].minor.yy379;
  143307. }else{
  143308. sqlite3WindowListDelete(pParse->db, yymsp[-2].minor.yy379);
  143309. }
  143310. }
  143311. break;
  143312. case 90: /* values ::= VALUES LP nexprlist RP */
  143313. {
  143314. yymsp[-3].minor.yy391 = sqlite3SelectNew(pParse,yymsp[-1].minor.yy94,0,0,0,0,0,SF_Values,0);
  143315. }
  143316. break;
  143317. case 91: /* values ::= values COMMA LP nexprlist RP */
  143318. {
  143319. Select *pRight, *pLeft = yymsp[-4].minor.yy391;
  143320. pRight = sqlite3SelectNew(pParse,yymsp[-1].minor.yy94,0,0,0,0,0,SF_Values|SF_MultiValue,0);
  143321. if( ALWAYS(pLeft) ) pLeft->selFlags &= ~SF_MultiValue;
  143322. if( pRight ){
  143323. pRight->op = TK_ALL;
  143324. pRight->pPrior = pLeft;
  143325. yymsp[-4].minor.yy391 = pRight;
  143326. }else{
  143327. yymsp[-4].minor.yy391 = pLeft;
  143328. }
  143329. }
  143330. break;
  143331. case 92: /* distinct ::= DISTINCT */
  143332. {yymsp[0].minor.yy100 = SF_Distinct;}
  143333. break;
  143334. case 93: /* distinct ::= ALL */
  143335. {yymsp[0].minor.yy100 = SF_All;}
  143336. break;
  143337. case 95: /* sclp ::= */
  143338. case 128: /* orderby_opt ::= */ yytestcase(yyruleno==128);
  143339. case 135: /* groupby_opt ::= */ yytestcase(yyruleno==135);
  143340. case 215: /* exprlist ::= */ yytestcase(yyruleno==215);
  143341. case 218: /* paren_exprlist ::= */ yytestcase(yyruleno==218);
  143342. case 223: /* eidlist_opt ::= */ yytestcase(yyruleno==223);
  143343. {yymsp[1].minor.yy94 = 0;}
  143344. break;
  143345. case 96: /* selcollist ::= sclp scanpt expr scanpt as */
  143346. {
  143347. yymsp[-4].minor.yy94 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy94, yymsp[-2].minor.yy102);
  143348. if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yymsp[-4].minor.yy94, &yymsp[0].minor.yy0, 1);
  143349. sqlite3ExprListSetSpan(pParse,yymsp[-4].minor.yy94,yymsp[-3].minor.yy528,yymsp[-1].minor.yy528);
  143350. }
  143351. break;
  143352. case 97: /* selcollist ::= sclp scanpt STAR */
  143353. {
  143354. Expr *p = sqlite3Expr(pParse->db, TK_ASTERISK, 0);
  143355. yymsp[-2].minor.yy94 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy94, p);
  143356. }
  143357. break;
  143358. case 98: /* selcollist ::= sclp scanpt nm DOT STAR */
  143359. {
  143360. Expr *pRight = sqlite3PExpr(pParse, TK_ASTERISK, 0, 0);
  143361. Expr *pLeft = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1);
  143362. Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight);
  143363. yymsp[-4].minor.yy94 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy94, pDot);
  143364. }
  143365. break;
  143366. case 99: /* as ::= AS nm */
  143367. case 110: /* dbnm ::= DOT nm */ yytestcase(yyruleno==110);
  143368. case 239: /* plus_num ::= PLUS INTEGER|FLOAT */ yytestcase(yyruleno==239);
  143369. case 240: /* minus_num ::= MINUS INTEGER|FLOAT */ yytestcase(yyruleno==240);
  143370. {yymsp[-1].minor.yy0 = yymsp[0].minor.yy0;}
  143371. break;
  143372. case 101: /* from ::= */
  143373. {yymsp[1].minor.yy407 = sqlite3DbMallocZero(pParse->db, sizeof(*yymsp[1].minor.yy407));}
  143374. break;
  143375. case 102: /* from ::= FROM seltablist */
  143376. {
  143377. yymsp[-1].minor.yy407 = yymsp[0].minor.yy407;
  143378. sqlite3SrcListShiftJoinType(yymsp[-1].minor.yy407);
  143379. }
  143380. break;
  143381. case 103: /* stl_prefix ::= seltablist joinop */
  143382. {
  143383. if( ALWAYS(yymsp[-1].minor.yy407 && yymsp[-1].minor.yy407->nSrc>0) ) yymsp[-1].minor.yy407->a[yymsp[-1].minor.yy407->nSrc-1].fg.jointype = (u8)yymsp[0].minor.yy100;
  143384. }
  143385. break;
  143386. case 104: /* stl_prefix ::= */
  143387. {yymsp[1].minor.yy407 = 0;}
  143388. break;
  143389. case 105: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
  143390. {
  143391. yymsp[-6].minor.yy407 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy407,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy102,yymsp[0].minor.yy76);
  143392. sqlite3SrcListIndexedBy(pParse, yymsp[-6].minor.yy407, &yymsp[-2].minor.yy0);
  143393. }
  143394. break;
  143395. case 106: /* seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */
  143396. {
  143397. yymsp[-8].minor.yy407 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-8].minor.yy407,&yymsp[-7].minor.yy0,&yymsp[-6].minor.yy0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy102,yymsp[0].minor.yy76);
  143398. sqlite3SrcListFuncArgs(pParse, yymsp[-8].minor.yy407, yymsp[-4].minor.yy94);
  143399. }
  143400. break;
  143401. case 107: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
  143402. {
  143403. yymsp[-6].minor.yy407 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy407,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy391,yymsp[-1].minor.yy102,yymsp[0].minor.yy76);
  143404. }
  143405. break;
  143406. case 108: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
  143407. {
  143408. if( yymsp[-6].minor.yy407==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy102==0 && yymsp[0].minor.yy76==0 ){
  143409. yymsp[-6].minor.yy407 = yymsp[-4].minor.yy407;
  143410. }else if( yymsp[-4].minor.yy407->nSrc==1 ){
  143411. yymsp[-6].minor.yy407 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy407,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy102,yymsp[0].minor.yy76);
  143412. if( yymsp[-6].minor.yy407 ){
  143413. struct SrcList_item *pNew = &yymsp[-6].minor.yy407->a[yymsp[-6].minor.yy407->nSrc-1];
  143414. struct SrcList_item *pOld = yymsp[-4].minor.yy407->a;
  143415. pNew->zName = pOld->zName;
  143416. pNew->zDatabase = pOld->zDatabase;
  143417. pNew->pSelect = pOld->pSelect;
  143418. if( pOld->fg.isTabFunc ){
  143419. pNew->u1.pFuncArg = pOld->u1.pFuncArg;
  143420. pOld->u1.pFuncArg = 0;
  143421. pOld->fg.isTabFunc = 0;
  143422. pNew->fg.isTabFunc = 1;
  143423. }
  143424. pOld->zName = pOld->zDatabase = 0;
  143425. pOld->pSelect = 0;
  143426. }
  143427. sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy407);
  143428. }else{
  143429. Select *pSubquery;
  143430. sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy407);
  143431. pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy407,0,0,0,0,SF_NestedFrom,0);
  143432. yymsp[-6].minor.yy407 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy407,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy102,yymsp[0].minor.yy76);
  143433. }
  143434. }
  143435. break;
  143436. case 109: /* dbnm ::= */
  143437. case 123: /* indexed_opt ::= */ yytestcase(yyruleno==123);
  143438. {yymsp[1].minor.yy0.z=0; yymsp[1].minor.yy0.n=0;}
  143439. break;
  143440. case 111: /* fullname ::= nm */
  143441. {
  143442. yylhsminor.yy407 = sqlite3SrcListAppend(pParse,0,&yymsp[0].minor.yy0,0);
  143443. if( IN_RENAME_OBJECT && yylhsminor.yy407 ) sqlite3RenameTokenMap(pParse, yylhsminor.yy407->a[0].zName, &yymsp[0].minor.yy0);
  143444. }
  143445. yymsp[0].minor.yy407 = yylhsminor.yy407;
  143446. break;
  143447. case 112: /* fullname ::= nm DOT nm */
  143448. {
  143449. yylhsminor.yy407 = sqlite3SrcListAppend(pParse,0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
  143450. if( IN_RENAME_OBJECT && yylhsminor.yy407 ) sqlite3RenameTokenMap(pParse, yylhsminor.yy407->a[0].zName, &yymsp[0].minor.yy0);
  143451. }
  143452. yymsp[-2].minor.yy407 = yylhsminor.yy407;
  143453. break;
  143454. case 113: /* xfullname ::= nm */
  143455. {yymsp[0].minor.yy407 = sqlite3SrcListAppend(pParse,0,&yymsp[0].minor.yy0,0); /*A-overwrites-X*/}
  143456. break;
  143457. case 114: /* xfullname ::= nm DOT nm */
  143458. {yymsp[-2].minor.yy407 = sqlite3SrcListAppend(pParse,0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/}
  143459. break;
  143460. case 115: /* xfullname ::= nm DOT nm AS nm */
  143461. {
  143462. yymsp[-4].minor.yy407 = sqlite3SrcListAppend(pParse,0,&yymsp[-4].minor.yy0,&yymsp[-2].minor.yy0); /*A-overwrites-X*/
  143463. if( yymsp[-4].minor.yy407 ) yymsp[-4].minor.yy407->a[0].zAlias = sqlite3NameFromToken(pParse->db, &yymsp[0].minor.yy0);
  143464. }
  143465. break;
  143466. case 116: /* xfullname ::= nm AS nm */
  143467. {
  143468. yymsp[-2].minor.yy407 = sqlite3SrcListAppend(pParse,0,&yymsp[-2].minor.yy0,0); /*A-overwrites-X*/
  143469. if( yymsp[-2].minor.yy407 ) yymsp[-2].minor.yy407->a[0].zAlias = sqlite3NameFromToken(pParse->db, &yymsp[0].minor.yy0);
  143470. }
  143471. break;
  143472. case 117: /* joinop ::= COMMA|JOIN */
  143473. { yymsp[0].minor.yy100 = JT_INNER; }
  143474. break;
  143475. case 118: /* joinop ::= JOIN_KW JOIN */
  143476. {yymsp[-1].minor.yy100 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); /*X-overwrites-A*/}
  143477. break;
  143478. case 119: /* joinop ::= JOIN_KW nm JOIN */
  143479. {yymsp[-2].minor.yy100 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); /*X-overwrites-A*/}
  143480. break;
  143481. case 120: /* joinop ::= JOIN_KW nm nm JOIN */
  143482. {yymsp[-3].minor.yy100 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);/*X-overwrites-A*/}
  143483. break;
  143484. case 121: /* on_opt ::= ON expr */
  143485. case 138: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==138);
  143486. case 145: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==145);
  143487. case 211: /* case_else ::= ELSE expr */ yytestcase(yyruleno==211);
  143488. case 232: /* vinto ::= INTO expr */ yytestcase(yyruleno==232);
  143489. {yymsp[-1].minor.yy102 = yymsp[0].minor.yy102;}
  143490. break;
  143491. case 122: /* on_opt ::= */
  143492. case 137: /* having_opt ::= */ yytestcase(yyruleno==137);
  143493. case 139: /* limit_opt ::= */ yytestcase(yyruleno==139);
  143494. case 144: /* where_opt ::= */ yytestcase(yyruleno==144);
  143495. case 212: /* case_else ::= */ yytestcase(yyruleno==212);
  143496. case 214: /* case_operand ::= */ yytestcase(yyruleno==214);
  143497. case 233: /* vinto ::= */ yytestcase(yyruleno==233);
  143498. {yymsp[1].minor.yy102 = 0;}
  143499. break;
  143500. case 124: /* indexed_opt ::= INDEXED BY nm */
  143501. {yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;}
  143502. break;
  143503. case 125: /* indexed_opt ::= NOT INDEXED */
  143504. {yymsp[-1].minor.yy0.z=0; yymsp[-1].minor.yy0.n=1;}
  143505. break;
  143506. case 126: /* using_opt ::= USING LP idlist RP */
  143507. {yymsp[-3].minor.yy76 = yymsp[-1].minor.yy76;}
  143508. break;
  143509. case 127: /* using_opt ::= */
  143510. case 159: /* idlist_opt ::= */ yytestcase(yyruleno==159);
  143511. {yymsp[1].minor.yy76 = 0;}
  143512. break;
  143513. case 129: /* orderby_opt ::= ORDER BY sortlist */
  143514. case 136: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==136);
  143515. {yymsp[-2].minor.yy94 = yymsp[0].minor.yy94;}
  143516. break;
  143517. case 130: /* sortlist ::= sortlist COMMA expr sortorder */
  143518. {
  143519. yymsp[-3].minor.yy94 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy94,yymsp[-1].minor.yy102);
  143520. sqlite3ExprListSetSortOrder(yymsp[-3].minor.yy94,yymsp[0].minor.yy100);
  143521. }
  143522. break;
  143523. case 131: /* sortlist ::= expr sortorder */
  143524. {
  143525. yymsp[-1].minor.yy94 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy102); /*A-overwrites-Y*/
  143526. sqlite3ExprListSetSortOrder(yymsp[-1].minor.yy94,yymsp[0].minor.yy100);
  143527. }
  143528. break;
  143529. case 132: /* sortorder ::= ASC */
  143530. {yymsp[0].minor.yy100 = SQLITE_SO_ASC;}
  143531. break;
  143532. case 133: /* sortorder ::= DESC */
  143533. {yymsp[0].minor.yy100 = SQLITE_SO_DESC;}
  143534. break;
  143535. case 134: /* sortorder ::= */
  143536. {yymsp[1].minor.yy100 = SQLITE_SO_UNDEFINED;}
  143537. break;
  143538. case 140: /* limit_opt ::= LIMIT expr */
  143539. {yymsp[-1].minor.yy102 = sqlite3PExpr(pParse,TK_LIMIT,yymsp[0].minor.yy102,0);}
  143540. break;
  143541. case 141: /* limit_opt ::= LIMIT expr OFFSET expr */
  143542. {yymsp[-3].minor.yy102 = sqlite3PExpr(pParse,TK_LIMIT,yymsp[-2].minor.yy102,yymsp[0].minor.yy102);}
  143543. break;
  143544. case 142: /* limit_opt ::= LIMIT expr COMMA expr */
  143545. {yymsp[-3].minor.yy102 = sqlite3PExpr(pParse,TK_LIMIT,yymsp[0].minor.yy102,yymsp[-2].minor.yy102);}
  143546. break;
  143547. case 143: /* cmd ::= with DELETE FROM xfullname indexed_opt where_opt */
  143548. {
  143549. sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy407, &yymsp[-1].minor.yy0);
  143550. sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy407,yymsp[0].minor.yy102,0,0);
  143551. }
  143552. break;
  143553. case 146: /* cmd ::= with UPDATE orconf xfullname indexed_opt SET setlist where_opt */
  143554. {
  143555. sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy407, &yymsp[-3].minor.yy0);
  143556. sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy94,"set list");
  143557. sqlite3Update(pParse,yymsp[-4].minor.yy407,yymsp[-1].minor.yy94,yymsp[0].minor.yy102,yymsp[-5].minor.yy100,0,0,0);
  143558. }
  143559. break;
  143560. case 147: /* setlist ::= setlist COMMA nm EQ expr */
  143561. {
  143562. yymsp[-4].minor.yy94 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy94, yymsp[0].minor.yy102);
  143563. sqlite3ExprListSetName(pParse, yymsp[-4].minor.yy94, &yymsp[-2].minor.yy0, 1);
  143564. }
  143565. break;
  143566. case 148: /* setlist ::= setlist COMMA LP idlist RP EQ expr */
  143567. {
  143568. yymsp[-6].minor.yy94 = sqlite3ExprListAppendVector(pParse, yymsp[-6].minor.yy94, yymsp[-3].minor.yy76, yymsp[0].minor.yy102);
  143569. }
  143570. break;
  143571. case 149: /* setlist ::= nm EQ expr */
  143572. {
  143573. yylhsminor.yy94 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy102);
  143574. sqlite3ExprListSetName(pParse, yylhsminor.yy94, &yymsp[-2].minor.yy0, 1);
  143575. }
  143576. yymsp[-2].minor.yy94 = yylhsminor.yy94;
  143577. break;
  143578. case 150: /* setlist ::= LP idlist RP EQ expr */
  143579. {
  143580. yymsp[-4].minor.yy94 = sqlite3ExprListAppendVector(pParse, 0, yymsp[-3].minor.yy76, yymsp[0].minor.yy102);
  143581. }
  143582. break;
  143583. case 151: /* cmd ::= with insert_cmd INTO xfullname idlist_opt select upsert */
  143584. {
  143585. sqlite3Insert(pParse, yymsp[-3].minor.yy407, yymsp[-1].minor.yy391, yymsp[-2].minor.yy76, yymsp[-5].minor.yy100, yymsp[0].minor.yy95);
  143586. }
  143587. break;
  143588. case 152: /* cmd ::= with insert_cmd INTO xfullname idlist_opt DEFAULT VALUES */
  143589. {
  143590. sqlite3Insert(pParse, yymsp[-3].minor.yy407, 0, yymsp[-2].minor.yy76, yymsp[-5].minor.yy100, 0);
  143591. }
  143592. break;
  143593. case 153: /* upsert ::= */
  143594. { yymsp[1].minor.yy95 = 0; }
  143595. break;
  143596. case 154: /* upsert ::= ON CONFLICT LP sortlist RP where_opt DO UPDATE SET setlist where_opt */
  143597. { yymsp[-10].minor.yy95 = sqlite3UpsertNew(pParse->db,yymsp[-7].minor.yy94,yymsp[-5].minor.yy102,yymsp[-1].minor.yy94,yymsp[0].minor.yy102);}
  143598. break;
  143599. case 155: /* upsert ::= ON CONFLICT LP sortlist RP where_opt DO NOTHING */
  143600. { yymsp[-7].minor.yy95 = sqlite3UpsertNew(pParse->db,yymsp[-4].minor.yy94,yymsp[-2].minor.yy102,0,0); }
  143601. break;
  143602. case 156: /* upsert ::= ON CONFLICT DO NOTHING */
  143603. { yymsp[-3].minor.yy95 = sqlite3UpsertNew(pParse->db,0,0,0,0); }
  143604. break;
  143605. case 160: /* idlist_opt ::= LP idlist RP */
  143606. {yymsp[-2].minor.yy76 = yymsp[-1].minor.yy76;}
  143607. break;
  143608. case 161: /* idlist ::= idlist COMMA nm */
  143609. {yymsp[-2].minor.yy76 = sqlite3IdListAppend(pParse,yymsp[-2].minor.yy76,&yymsp[0].minor.yy0);}
  143610. break;
  143611. case 162: /* idlist ::= nm */
  143612. {yymsp[0].minor.yy76 = sqlite3IdListAppend(pParse,0,&yymsp[0].minor.yy0); /*A-overwrites-Y*/}
  143613. break;
  143614. case 163: /* expr ::= LP expr RP */
  143615. {yymsp[-2].minor.yy102 = yymsp[-1].minor.yy102;}
  143616. break;
  143617. case 164: /* expr ::= ID|INDEXED */
  143618. case 165: /* expr ::= JOIN_KW */ yytestcase(yyruleno==165);
  143619. {yymsp[0].minor.yy102=tokenExpr(pParse,TK_ID,yymsp[0].minor.yy0); /*A-overwrites-X*/}
  143620. break;
  143621. case 166: /* expr ::= nm DOT nm */
  143622. {
  143623. Expr *temp1 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1);
  143624. Expr *temp2 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[0].minor.yy0, 1);
  143625. if( IN_RENAME_OBJECT ){
  143626. sqlite3RenameTokenMap(pParse, (void*)temp2, &yymsp[0].minor.yy0);
  143627. sqlite3RenameTokenMap(pParse, (void*)temp1, &yymsp[-2].minor.yy0);
  143628. }
  143629. yylhsminor.yy102 = sqlite3PExpr(pParse, TK_DOT, temp1, temp2);
  143630. }
  143631. yymsp[-2].minor.yy102 = yylhsminor.yy102;
  143632. break;
  143633. case 167: /* expr ::= nm DOT nm DOT nm */
  143634. {
  143635. Expr *temp1 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-4].minor.yy0, 1);
  143636. Expr *temp2 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1);
  143637. Expr *temp3 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[0].minor.yy0, 1);
  143638. Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3);
  143639. if( IN_RENAME_OBJECT ){
  143640. sqlite3RenameTokenMap(pParse, (void*)temp3, &yymsp[0].minor.yy0);
  143641. sqlite3RenameTokenMap(pParse, (void*)temp2, &yymsp[-2].minor.yy0);
  143642. }
  143643. yylhsminor.yy102 = sqlite3PExpr(pParse, TK_DOT, temp1, temp4);
  143644. }
  143645. yymsp[-4].minor.yy102 = yylhsminor.yy102;
  143646. break;
  143647. case 168: /* term ::= NULL|FLOAT|BLOB */
  143648. case 169: /* term ::= STRING */ yytestcase(yyruleno==169);
  143649. {yymsp[0].minor.yy102=tokenExpr(pParse,yymsp[0].major,yymsp[0].minor.yy0); /*A-overwrites-X*/}
  143650. break;
  143651. case 170: /* term ::= INTEGER */
  143652. {
  143653. yylhsminor.yy102 = sqlite3ExprAlloc(pParse->db, TK_INTEGER, &yymsp[0].minor.yy0, 1);
  143654. }
  143655. yymsp[0].minor.yy102 = yylhsminor.yy102;
  143656. break;
  143657. case 171: /* expr ::= VARIABLE */
  143658. {
  143659. if( !(yymsp[0].minor.yy0.z[0]=='#' && sqlite3Isdigit(yymsp[0].minor.yy0.z[1])) ){
  143660. u32 n = yymsp[0].minor.yy0.n;
  143661. yymsp[0].minor.yy102 = tokenExpr(pParse, TK_VARIABLE, yymsp[0].minor.yy0);
  143662. sqlite3ExprAssignVarNumber(pParse, yymsp[0].minor.yy102, n);
  143663. }else{
  143664. /* When doing a nested parse, one can include terms in an expression
  143665. ** that look like this: #1 #2 ... These terms refer to registers
  143666. ** in the virtual machine. #N is the N-th register. */
  143667. Token t = yymsp[0].minor.yy0; /*A-overwrites-X*/
  143668. assert( t.n>=2 );
  143669. if( pParse->nested==0 ){
  143670. sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &t);
  143671. yymsp[0].minor.yy102 = 0;
  143672. }else{
  143673. yymsp[0].minor.yy102 = sqlite3PExpr(pParse, TK_REGISTER, 0, 0);
  143674. if( yymsp[0].minor.yy102 ) sqlite3GetInt32(&t.z[1], &yymsp[0].minor.yy102->iTable);
  143675. }
  143676. }
  143677. }
  143678. break;
  143679. case 172: /* expr ::= expr COLLATE ID|STRING */
  143680. {
  143681. yymsp[-2].minor.yy102 = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy102, &yymsp[0].minor.yy0, 1);
  143682. }
  143683. break;
  143684. case 173: /* expr ::= CAST LP expr AS typetoken RP */
  143685. {
  143686. yymsp[-5].minor.yy102 = sqlite3ExprAlloc(pParse->db, TK_CAST, &yymsp[-1].minor.yy0, 1);
  143687. sqlite3ExprAttachSubtrees(pParse->db, yymsp[-5].minor.yy102, yymsp[-3].minor.yy102, 0);
  143688. }
  143689. break;
  143690. case 174: /* expr ::= ID|INDEXED LP distinct exprlist RP */
  143691. {
  143692. yylhsminor.yy102 = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy94, &yymsp[-4].minor.yy0, yymsp[-2].minor.yy100);
  143693. }
  143694. yymsp[-4].minor.yy102 = yylhsminor.yy102;
  143695. break;
  143696. case 175: /* expr ::= ID|INDEXED LP STAR RP */
  143697. {
  143698. yylhsminor.yy102 = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0, 0);
  143699. }
  143700. yymsp[-3].minor.yy102 = yylhsminor.yy102;
  143701. break;
  143702. case 176: /* expr ::= ID|INDEXED LP distinct exprlist RP over_clause */
  143703. {
  143704. yylhsminor.yy102 = sqlite3ExprFunction(pParse, yymsp[-2].minor.yy94, &yymsp[-5].minor.yy0, yymsp[-3].minor.yy100);
  143705. sqlite3WindowAttach(pParse, yylhsminor.yy102, yymsp[0].minor.yy379);
  143706. }
  143707. yymsp[-5].minor.yy102 = yylhsminor.yy102;
  143708. break;
  143709. case 177: /* expr ::= ID|INDEXED LP STAR RP over_clause */
  143710. {
  143711. yylhsminor.yy102 = sqlite3ExprFunction(pParse, 0, &yymsp[-4].minor.yy0, 0);
  143712. sqlite3WindowAttach(pParse, yylhsminor.yy102, yymsp[0].minor.yy379);
  143713. }
  143714. yymsp[-4].minor.yy102 = yylhsminor.yy102;
  143715. break;
  143716. case 178: /* term ::= CTIME_KW */
  143717. {
  143718. yylhsminor.yy102 = sqlite3ExprFunction(pParse, 0, &yymsp[0].minor.yy0, 0);
  143719. }
  143720. yymsp[0].minor.yy102 = yylhsminor.yy102;
  143721. break;
  143722. case 179: /* expr ::= LP nexprlist COMMA expr RP */
  143723. {
  143724. ExprList *pList = sqlite3ExprListAppend(pParse, yymsp[-3].minor.yy94, yymsp[-1].minor.yy102);
  143725. yymsp[-4].minor.yy102 = sqlite3PExpr(pParse, TK_VECTOR, 0, 0);
  143726. if( yymsp[-4].minor.yy102 ){
  143727. yymsp[-4].minor.yy102->x.pList = pList;
  143728. }else{
  143729. sqlite3ExprListDelete(pParse->db, pList);
  143730. }
  143731. }
  143732. break;
  143733. case 180: /* expr ::= expr AND expr */
  143734. {yymsp[-2].minor.yy102=sqlite3ExprAnd(pParse,yymsp[-2].minor.yy102,yymsp[0].minor.yy102);}
  143735. break;
  143736. case 181: /* expr ::= expr OR expr */
  143737. case 182: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==182);
  143738. case 183: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==183);
  143739. case 184: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==184);
  143740. case 185: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==185);
  143741. case 186: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==186);
  143742. case 187: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==187);
  143743. {yymsp[-2].minor.yy102=sqlite3PExpr(pParse,yymsp[-1].major,yymsp[-2].minor.yy102,yymsp[0].minor.yy102);}
  143744. break;
  143745. case 188: /* likeop ::= NOT LIKE_KW|MATCH */
  143746. {yymsp[-1].minor.yy0=yymsp[0].minor.yy0; yymsp[-1].minor.yy0.n|=0x80000000; /*yymsp[-1].minor.yy0-overwrite-yymsp[0].minor.yy0*/}
  143747. break;
  143748. case 189: /* expr ::= expr likeop expr */
  143749. {
  143750. ExprList *pList;
  143751. int bNot = yymsp[-1].minor.yy0.n & 0x80000000;
  143752. yymsp[-1].minor.yy0.n &= 0x7fffffff;
  143753. pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy102);
  143754. pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy102);
  143755. yymsp[-2].minor.yy102 = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy0, 0);
  143756. if( bNot ) yymsp[-2].minor.yy102 = sqlite3PExpr(pParse, TK_NOT, yymsp[-2].minor.yy102, 0);
  143757. if( yymsp[-2].minor.yy102 ) yymsp[-2].minor.yy102->flags |= EP_InfixFunc;
  143758. }
  143759. break;
  143760. case 190: /* expr ::= expr likeop expr ESCAPE expr */
  143761. {
  143762. ExprList *pList;
  143763. int bNot = yymsp[-3].minor.yy0.n & 0x80000000;
  143764. yymsp[-3].minor.yy0.n &= 0x7fffffff;
  143765. pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy102);
  143766. pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy102);
  143767. pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy102);
  143768. yymsp[-4].minor.yy102 = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy0, 0);
  143769. if( bNot ) yymsp[-4].minor.yy102 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy102, 0);
  143770. if( yymsp[-4].minor.yy102 ) yymsp[-4].minor.yy102->flags |= EP_InfixFunc;
  143771. }
  143772. break;
  143773. case 191: /* expr ::= expr ISNULL|NOTNULL */
  143774. {yymsp[-1].minor.yy102 = sqlite3PExpr(pParse,yymsp[0].major,yymsp[-1].minor.yy102,0);}
  143775. break;
  143776. case 192: /* expr ::= expr NOT NULL */
  143777. {yymsp[-2].minor.yy102 = sqlite3PExpr(pParse,TK_NOTNULL,yymsp[-2].minor.yy102,0);}
  143778. break;
  143779. case 193: /* expr ::= expr IS expr */
  143780. {
  143781. yymsp[-2].minor.yy102 = sqlite3PExpr(pParse,TK_IS,yymsp[-2].minor.yy102,yymsp[0].minor.yy102);
  143782. binaryToUnaryIfNull(pParse, yymsp[0].minor.yy102, yymsp[-2].minor.yy102, TK_ISNULL);
  143783. }
  143784. break;
  143785. case 194: /* expr ::= expr IS NOT expr */
  143786. {
  143787. yymsp[-3].minor.yy102 = sqlite3PExpr(pParse,TK_ISNOT,yymsp[-3].minor.yy102,yymsp[0].minor.yy102);
  143788. binaryToUnaryIfNull(pParse, yymsp[0].minor.yy102, yymsp[-3].minor.yy102, TK_NOTNULL);
  143789. }
  143790. break;
  143791. case 195: /* expr ::= NOT expr */
  143792. case 196: /* expr ::= BITNOT expr */ yytestcase(yyruleno==196);
  143793. {yymsp[-1].minor.yy102 = sqlite3PExpr(pParse, yymsp[-1].major, yymsp[0].minor.yy102, 0);/*A-overwrites-B*/}
  143794. break;
  143795. case 197: /* expr ::= PLUS|MINUS expr */
  143796. {
  143797. yymsp[-1].minor.yy102 = sqlite3PExpr(pParse, yymsp[-1].major==TK_PLUS ? TK_UPLUS : TK_UMINUS, yymsp[0].minor.yy102, 0);
  143798. /*A-overwrites-B*/
  143799. }
  143800. break;
  143801. case 198: /* between_op ::= BETWEEN */
  143802. case 201: /* in_op ::= IN */ yytestcase(yyruleno==201);
  143803. {yymsp[0].minor.yy100 = 0;}
  143804. break;
  143805. case 200: /* expr ::= expr between_op expr AND expr */
  143806. {
  143807. ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy102);
  143808. pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy102);
  143809. yymsp[-4].minor.yy102 = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy102, 0);
  143810. if( yymsp[-4].minor.yy102 ){
  143811. yymsp[-4].minor.yy102->x.pList = pList;
  143812. }else{
  143813. sqlite3ExprListDelete(pParse->db, pList);
  143814. }
  143815. if( yymsp[-3].minor.yy100 ) yymsp[-4].minor.yy102 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy102, 0);
  143816. }
  143817. break;
  143818. case 203: /* expr ::= expr in_op LP exprlist RP */
  143819. {
  143820. if( yymsp[-1].minor.yy94==0 ){
  143821. /* Expressions of the form
  143822. **
  143823. ** expr1 IN ()
  143824. ** expr1 NOT IN ()
  143825. **
  143826. ** simplify to constants 0 (false) and 1 (true), respectively,
  143827. ** regardless of the value of expr1.
  143828. */
  143829. sqlite3ExprUnmapAndDelete(pParse, yymsp[-4].minor.yy102);
  143830. yymsp[-4].minor.yy102 = sqlite3ExprAlloc(pParse->db, TK_INTEGER,&sqlite3IntTokens[yymsp[-3].minor.yy100],1);
  143831. }else if( yymsp[-1].minor.yy94->nExpr==1 ){
  143832. /* Expressions of the form:
  143833. **
  143834. ** expr1 IN (?1)
  143835. ** expr1 NOT IN (?2)
  143836. **
  143837. ** with exactly one value on the RHS can be simplified to something
  143838. ** like this:
  143839. **
  143840. ** expr1 == ?1
  143841. ** expr1 <> ?2
  143842. **
  143843. ** But, the RHS of the == or <> is marked with the EP_Generic flag
  143844. ** so that it may not contribute to the computation of comparison
  143845. ** affinity or the collating sequence to use for comparison. Otherwise,
  143846. ** the semantics would be subtly different from IN or NOT IN.
  143847. */
  143848. Expr *pRHS = yymsp[-1].minor.yy94->a[0].pExpr;
  143849. yymsp[-1].minor.yy94->a[0].pExpr = 0;
  143850. sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy94);
  143851. /* pRHS cannot be NULL because a malloc error would have been detected
  143852. ** before now and control would have never reached this point */
  143853. if( ALWAYS(pRHS) ){
  143854. pRHS->flags &= ~EP_Collate;
  143855. pRHS->flags |= EP_Generic;
  143856. }
  143857. yymsp[-4].minor.yy102 = sqlite3PExpr(pParse, yymsp[-3].minor.yy100 ? TK_NE : TK_EQ, yymsp[-4].minor.yy102, pRHS);
  143858. }else{
  143859. yymsp[-4].minor.yy102 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy102, 0);
  143860. if( yymsp[-4].minor.yy102 ){
  143861. yymsp[-4].minor.yy102->x.pList = yymsp[-1].minor.yy94;
  143862. sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy102);
  143863. }else{
  143864. sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy94);
  143865. }
  143866. if( yymsp[-3].minor.yy100 ) yymsp[-4].minor.yy102 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy102, 0);
  143867. }
  143868. }
  143869. break;
  143870. case 204: /* expr ::= LP select RP */
  143871. {
  143872. yymsp[-2].minor.yy102 = sqlite3PExpr(pParse, TK_SELECT, 0, 0);
  143873. sqlite3PExprAddSelect(pParse, yymsp[-2].minor.yy102, yymsp[-1].minor.yy391);
  143874. }
  143875. break;
  143876. case 205: /* expr ::= expr in_op LP select RP */
  143877. {
  143878. yymsp[-4].minor.yy102 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy102, 0);
  143879. sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy102, yymsp[-1].minor.yy391);
  143880. if( yymsp[-3].minor.yy100 ) yymsp[-4].minor.yy102 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy102, 0);
  143881. }
  143882. break;
  143883. case 206: /* expr ::= expr in_op nm dbnm paren_exprlist */
  143884. {
  143885. SrcList *pSrc = sqlite3SrcListAppend(pParse, 0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);
  143886. Select *pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0);
  143887. if( yymsp[0].minor.yy94 ) sqlite3SrcListFuncArgs(pParse, pSelect ? pSrc : 0, yymsp[0].minor.yy94);
  143888. yymsp[-4].minor.yy102 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy102, 0);
  143889. sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy102, pSelect);
  143890. if( yymsp[-3].minor.yy100 ) yymsp[-4].minor.yy102 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy102, 0);
  143891. }
  143892. break;
  143893. case 207: /* expr ::= EXISTS LP select RP */
  143894. {
  143895. Expr *p;
  143896. p = yymsp[-3].minor.yy102 = sqlite3PExpr(pParse, TK_EXISTS, 0, 0);
  143897. sqlite3PExprAddSelect(pParse, p, yymsp[-1].minor.yy391);
  143898. }
  143899. break;
  143900. case 208: /* expr ::= CASE case_operand case_exprlist case_else END */
  143901. {
  143902. yymsp[-4].minor.yy102 = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy102, 0);
  143903. if( yymsp[-4].minor.yy102 ){
  143904. yymsp[-4].minor.yy102->x.pList = yymsp[-1].minor.yy102 ? sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy94,yymsp[-1].minor.yy102) : yymsp[-2].minor.yy94;
  143905. sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy102);
  143906. }else{
  143907. sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy94);
  143908. sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy102);
  143909. }
  143910. }
  143911. break;
  143912. case 209: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
  143913. {
  143914. yymsp[-4].minor.yy94 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy94, yymsp[-2].minor.yy102);
  143915. yymsp[-4].minor.yy94 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy94, yymsp[0].minor.yy102);
  143916. }
  143917. break;
  143918. case 210: /* case_exprlist ::= WHEN expr THEN expr */
  143919. {
  143920. yymsp[-3].minor.yy94 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy102);
  143921. yymsp[-3].minor.yy94 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy94, yymsp[0].minor.yy102);
  143922. }
  143923. break;
  143924. case 213: /* case_operand ::= expr */
  143925. {yymsp[0].minor.yy102 = yymsp[0].minor.yy102; /*A-overwrites-X*/}
  143926. break;
  143927. case 216: /* nexprlist ::= nexprlist COMMA expr */
  143928. {yymsp[-2].minor.yy94 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy94,yymsp[0].minor.yy102);}
  143929. break;
  143930. case 217: /* nexprlist ::= expr */
  143931. {yymsp[0].minor.yy94 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy102); /*A-overwrites-Y*/}
  143932. break;
  143933. case 219: /* paren_exprlist ::= LP exprlist RP */
  143934. case 224: /* eidlist_opt ::= LP eidlist RP */ yytestcase(yyruleno==224);
  143935. {yymsp[-2].minor.yy94 = yymsp[-1].minor.yy94;}
  143936. break;
  143937. case 220: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
  143938. {
  143939. sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0,
  143940. sqlite3SrcListAppend(pParse,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy94, yymsp[-10].minor.yy100,
  143941. &yymsp[-11].minor.yy0, yymsp[0].minor.yy102, SQLITE_SO_ASC, yymsp[-8].minor.yy100, SQLITE_IDXTYPE_APPDEF);
  143942. if( IN_RENAME_OBJECT && pParse->pNewIndex ){
  143943. sqlite3RenameTokenMap(pParse, pParse->pNewIndex->zName, &yymsp[-4].minor.yy0);
  143944. }
  143945. }
  143946. break;
  143947. case 221: /* uniqueflag ::= UNIQUE */
  143948. case 263: /* raisetype ::= ABORT */ yytestcase(yyruleno==263);
  143949. {yymsp[0].minor.yy100 = OE_Abort;}
  143950. break;
  143951. case 222: /* uniqueflag ::= */
  143952. {yymsp[1].minor.yy100 = OE_None;}
  143953. break;
  143954. case 225: /* eidlist ::= eidlist COMMA nm collate sortorder */
  143955. {
  143956. yymsp[-4].minor.yy94 = parserAddExprIdListTerm(pParse, yymsp[-4].minor.yy94, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy100, yymsp[0].minor.yy100);
  143957. }
  143958. break;
  143959. case 226: /* eidlist ::= nm collate sortorder */
  143960. {
  143961. yymsp[-2].minor.yy94 = parserAddExprIdListTerm(pParse, 0, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy100, yymsp[0].minor.yy100); /*A-overwrites-Y*/
  143962. }
  143963. break;
  143964. case 229: /* cmd ::= DROP INDEX ifexists fullname */
  143965. {sqlite3DropIndex(pParse, yymsp[0].minor.yy407, yymsp[-1].minor.yy100);}
  143966. break;
  143967. case 230: /* cmd ::= VACUUM vinto */
  143968. {sqlite3Vacuum(pParse,0,yymsp[0].minor.yy102);}
  143969. break;
  143970. case 231: /* cmd ::= VACUUM nm vinto */
  143971. {sqlite3Vacuum(pParse,&yymsp[-1].minor.yy0,yymsp[0].minor.yy102);}
  143972. break;
  143973. case 234: /* cmd ::= PRAGMA nm dbnm */
  143974. {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
  143975. break;
  143976. case 235: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
  143977. {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
  143978. break;
  143979. case 236: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
  143980. {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
  143981. break;
  143982. case 237: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
  143983. {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
  143984. break;
  143985. case 238: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
  143986. {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
  143987. break;
  143988. case 241: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
  143989. {
  143990. Token all;
  143991. all.z = yymsp[-3].minor.yy0.z;
  143992. all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
  143993. sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy11, &all);
  143994. }
  143995. break;
  143996. case 242: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
  143997. {
  143998. sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy100, yymsp[-4].minor.yy298.a, yymsp[-4].minor.yy298.b, yymsp[-2].minor.yy407, yymsp[0].minor.yy102, yymsp[-10].minor.yy100, yymsp[-8].minor.yy100);
  143999. yymsp[-10].minor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0); /*A-overwrites-T*/
  144000. }
  144001. break;
  144002. case 243: /* trigger_time ::= BEFORE|AFTER */
  144003. { yymsp[0].minor.yy100 = yymsp[0].major; /*A-overwrites-X*/ }
  144004. break;
  144005. case 244: /* trigger_time ::= INSTEAD OF */
  144006. { yymsp[-1].minor.yy100 = TK_INSTEAD;}
  144007. break;
  144008. case 245: /* trigger_time ::= */
  144009. { yymsp[1].minor.yy100 = TK_BEFORE; }
  144010. break;
  144011. case 246: /* trigger_event ::= DELETE|INSERT */
  144012. case 247: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==247);
  144013. {yymsp[0].minor.yy298.a = yymsp[0].major; /*A-overwrites-X*/ yymsp[0].minor.yy298.b = 0;}
  144014. break;
  144015. case 248: /* trigger_event ::= UPDATE OF idlist */
  144016. {yymsp[-2].minor.yy298.a = TK_UPDATE; yymsp[-2].minor.yy298.b = yymsp[0].minor.yy76;}
  144017. break;
  144018. case 249: /* when_clause ::= */
  144019. case 268: /* key_opt ::= */ yytestcase(yyruleno==268);
  144020. case 316: /* filter_opt ::= */ yytestcase(yyruleno==316);
  144021. { yymsp[1].minor.yy102 = 0; }
  144022. break;
  144023. case 250: /* when_clause ::= WHEN expr */
  144024. case 269: /* key_opt ::= KEY expr */ yytestcase(yyruleno==269);
  144025. { yymsp[-1].minor.yy102 = yymsp[0].minor.yy102; }
  144026. break;
  144027. case 251: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
  144028. {
  144029. assert( yymsp[-2].minor.yy11!=0 );
  144030. yymsp[-2].minor.yy11->pLast->pNext = yymsp[-1].minor.yy11;
  144031. yymsp[-2].minor.yy11->pLast = yymsp[-1].minor.yy11;
  144032. }
  144033. break;
  144034. case 252: /* trigger_cmd_list ::= trigger_cmd SEMI */
  144035. {
  144036. assert( yymsp[-1].minor.yy11!=0 );
  144037. yymsp[-1].minor.yy11->pLast = yymsp[-1].minor.yy11;
  144038. }
  144039. break;
  144040. case 253: /* trnm ::= nm DOT nm */
  144041. {
  144042. yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;
  144043. sqlite3ErrorMsg(pParse,
  144044. "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
  144045. "statements within triggers");
  144046. }
  144047. break;
  144048. case 254: /* tridxby ::= INDEXED BY nm */
  144049. {
  144050. sqlite3ErrorMsg(pParse,
  144051. "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
  144052. "within triggers");
  144053. }
  144054. break;
  144055. case 255: /* tridxby ::= NOT INDEXED */
  144056. {
  144057. sqlite3ErrorMsg(pParse,
  144058. "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
  144059. "within triggers");
  144060. }
  144061. break;
  144062. case 256: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt scanpt */
  144063. {yylhsminor.yy11 = sqlite3TriggerUpdateStep(pParse, &yymsp[-5].minor.yy0, yymsp[-2].minor.yy94, yymsp[-1].minor.yy102, yymsp[-6].minor.yy100, yymsp[-7].minor.yy0.z, yymsp[0].minor.yy528);}
  144064. yymsp[-7].minor.yy11 = yylhsminor.yy11;
  144065. break;
  144066. case 257: /* trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt */
  144067. {
  144068. yylhsminor.yy11 = sqlite3TriggerInsertStep(pParse,&yymsp[-4].minor.yy0,yymsp[-3].minor.yy76,yymsp[-2].minor.yy391,yymsp[-6].minor.yy100,yymsp[-1].minor.yy95,yymsp[-7].minor.yy528,yymsp[0].minor.yy528);/*yylhsminor.yy11-overwrites-yymsp[-6].minor.yy100*/
  144069. }
  144070. yymsp[-7].minor.yy11 = yylhsminor.yy11;
  144071. break;
  144072. case 258: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */
  144073. {yylhsminor.yy11 = sqlite3TriggerDeleteStep(pParse, &yymsp[-3].minor.yy0, yymsp[-1].minor.yy102, yymsp[-5].minor.yy0.z, yymsp[0].minor.yy528);}
  144074. yymsp[-5].minor.yy11 = yylhsminor.yy11;
  144075. break;
  144076. case 259: /* trigger_cmd ::= scanpt select scanpt */
  144077. {yylhsminor.yy11 = sqlite3TriggerSelectStep(pParse->db, yymsp[-1].minor.yy391, yymsp[-2].minor.yy528, yymsp[0].minor.yy528); /*yylhsminor.yy11-overwrites-yymsp[-1].minor.yy391*/}
  144078. yymsp[-2].minor.yy11 = yylhsminor.yy11;
  144079. break;
  144080. case 260: /* expr ::= RAISE LP IGNORE RP */
  144081. {
  144082. yymsp[-3].minor.yy102 = sqlite3PExpr(pParse, TK_RAISE, 0, 0);
  144083. if( yymsp[-3].minor.yy102 ){
  144084. yymsp[-3].minor.yy102->affinity = OE_Ignore;
  144085. }
  144086. }
  144087. break;
  144088. case 261: /* expr ::= RAISE LP raisetype COMMA nm RP */
  144089. {
  144090. yymsp[-5].minor.yy102 = sqlite3ExprAlloc(pParse->db, TK_RAISE, &yymsp[-1].minor.yy0, 1);
  144091. if( yymsp[-5].minor.yy102 ) {
  144092. yymsp[-5].minor.yy102->affinity = (char)yymsp[-3].minor.yy100;
  144093. }
  144094. }
  144095. break;
  144096. case 262: /* raisetype ::= ROLLBACK */
  144097. {yymsp[0].minor.yy100 = OE_Rollback;}
  144098. break;
  144099. case 264: /* raisetype ::= FAIL */
  144100. {yymsp[0].minor.yy100 = OE_Fail;}
  144101. break;
  144102. case 265: /* cmd ::= DROP TRIGGER ifexists fullname */
  144103. {
  144104. sqlite3DropTrigger(pParse,yymsp[0].minor.yy407,yymsp[-1].minor.yy100);
  144105. }
  144106. break;
  144107. case 266: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
  144108. {
  144109. sqlite3Attach(pParse, yymsp[-3].minor.yy102, yymsp[-1].minor.yy102, yymsp[0].minor.yy102);
  144110. }
  144111. break;
  144112. case 267: /* cmd ::= DETACH database_kw_opt expr */
  144113. {
  144114. sqlite3Detach(pParse, yymsp[0].minor.yy102);
  144115. }
  144116. break;
  144117. case 270: /* cmd ::= REINDEX */
  144118. {sqlite3Reindex(pParse, 0, 0);}
  144119. break;
  144120. case 271: /* cmd ::= REINDEX nm dbnm */
  144121. {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
  144122. break;
  144123. case 272: /* cmd ::= ANALYZE */
  144124. {sqlite3Analyze(pParse, 0, 0);}
  144125. break;
  144126. case 273: /* cmd ::= ANALYZE nm dbnm */
  144127. {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
  144128. break;
  144129. case 274: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
  144130. {
  144131. sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy407,&yymsp[0].minor.yy0);
  144132. }
  144133. break;
  144134. case 275: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
  144135. {
  144136. yymsp[-1].minor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-1].minor.yy0.z) + pParse->sLastToken.n;
  144137. sqlite3AlterFinishAddColumn(pParse, &yymsp[-1].minor.yy0);
  144138. }
  144139. break;
  144140. case 276: /* add_column_fullname ::= fullname */
  144141. {
  144142. disableLookaside(pParse);
  144143. sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy407);
  144144. }
  144145. break;
  144146. case 277: /* cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm */
  144147. {
  144148. sqlite3AlterRenameColumn(pParse, yymsp[-5].minor.yy407, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0);
  144149. }
  144150. break;
  144151. case 278: /* cmd ::= create_vtab */
  144152. {sqlite3VtabFinishParse(pParse,0);}
  144153. break;
  144154. case 279: /* cmd ::= create_vtab LP vtabarglist RP */
  144155. {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
  144156. break;
  144157. case 280: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
  144158. {
  144159. sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy100);
  144160. }
  144161. break;
  144162. case 281: /* vtabarg ::= */
  144163. {sqlite3VtabArgInit(pParse);}
  144164. break;
  144165. case 282: /* vtabargtoken ::= ANY */
  144166. case 283: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==283);
  144167. case 284: /* lp ::= LP */ yytestcase(yyruleno==284);
  144168. {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
  144169. break;
  144170. case 285: /* with ::= WITH wqlist */
  144171. case 286: /* with ::= WITH RECURSIVE wqlist */ yytestcase(yyruleno==286);
  144172. { sqlite3WithPush(pParse, yymsp[0].minor.yy243, 1); }
  144173. break;
  144174. case 287: /* wqlist ::= nm eidlist_opt AS LP select RP */
  144175. {
  144176. yymsp[-5].minor.yy243 = sqlite3WithAdd(pParse, 0, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy94, yymsp[-1].minor.yy391); /*A-overwrites-X*/
  144177. }
  144178. break;
  144179. case 288: /* wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP */
  144180. {
  144181. yymsp[-7].minor.yy243 = sqlite3WithAdd(pParse, yymsp[-7].minor.yy243, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy94, yymsp[-1].minor.yy391);
  144182. }
  144183. break;
  144184. case 289: /* windowdefn_list ::= windowdefn */
  144185. { yylhsminor.yy379 = yymsp[0].minor.yy379; }
  144186. yymsp[0].minor.yy379 = yylhsminor.yy379;
  144187. break;
  144188. case 290: /* windowdefn_list ::= windowdefn_list COMMA windowdefn */
  144189. {
  144190. assert( yymsp[0].minor.yy379!=0 );
  144191. sqlite3WindowChain(pParse, yymsp[0].minor.yy379, yymsp[-2].minor.yy379);
  144192. yymsp[0].minor.yy379->pNextWin = yymsp[-2].minor.yy379;
  144193. yylhsminor.yy379 = yymsp[0].minor.yy379;
  144194. }
  144195. yymsp[-2].minor.yy379 = yylhsminor.yy379;
  144196. break;
  144197. case 291: /* windowdefn ::= nm AS LP window RP */
  144198. {
  144199. if( ALWAYS(yymsp[-1].minor.yy379) ){
  144200. yymsp[-1].minor.yy379->zName = sqlite3DbStrNDup(pParse->db, yymsp[-4].minor.yy0.z, yymsp[-4].minor.yy0.n);
  144201. }
  144202. yylhsminor.yy379 = yymsp[-1].minor.yy379;
  144203. }
  144204. yymsp[-4].minor.yy379 = yylhsminor.yy379;
  144205. break;
  144206. case 292: /* window ::= PARTITION BY nexprlist orderby_opt frame_opt */
  144207. {
  144208. yymsp[-4].minor.yy379 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy379, yymsp[-2].minor.yy94, yymsp[-1].minor.yy94, 0);
  144209. }
  144210. break;
  144211. case 293: /* window ::= nm PARTITION BY nexprlist orderby_opt frame_opt */
  144212. {
  144213. yylhsminor.yy379 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy379, yymsp[-2].minor.yy94, yymsp[-1].minor.yy94, &yymsp[-5].minor.yy0);
  144214. }
  144215. yymsp[-5].minor.yy379 = yylhsminor.yy379;
  144216. break;
  144217. case 294: /* window ::= ORDER BY sortlist frame_opt */
  144218. {
  144219. yymsp[-3].minor.yy379 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy379, 0, yymsp[-1].minor.yy94, 0);
  144220. }
  144221. break;
  144222. case 295: /* window ::= nm ORDER BY sortlist frame_opt */
  144223. {
  144224. yylhsminor.yy379 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy379, 0, yymsp[-1].minor.yy94, &yymsp[-4].minor.yy0);
  144225. }
  144226. yymsp[-4].minor.yy379 = yylhsminor.yy379;
  144227. break;
  144228. case 296: /* window ::= frame_opt */
  144229. {
  144230. yylhsminor.yy379 = yymsp[0].minor.yy379;
  144231. }
  144232. yymsp[0].minor.yy379 = yylhsminor.yy379;
  144233. break;
  144234. case 297: /* window ::= nm frame_opt */
  144235. {
  144236. yylhsminor.yy379 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy379, 0, 0, &yymsp[-1].minor.yy0);
  144237. }
  144238. yymsp[-1].minor.yy379 = yylhsminor.yy379;
  144239. break;
  144240. case 298: /* frame_opt ::= */
  144241. {
  144242. yymsp[1].minor.yy379 = sqlite3WindowAlloc(pParse, 0, TK_UNBOUNDED, 0, TK_CURRENT, 0, 0);
  144243. }
  144244. break;
  144245. case 299: /* frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt */
  144246. {
  144247. yylhsminor.yy379 = sqlite3WindowAlloc(pParse, yymsp[-2].minor.yy100, yymsp[-1].minor.yy389.eType, yymsp[-1].minor.yy389.pExpr, TK_CURRENT, 0, yymsp[0].minor.yy218);
  144248. }
  144249. yymsp[-2].minor.yy379 = yylhsminor.yy379;
  144250. break;
  144251. case 300: /* frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt */
  144252. {
  144253. yylhsminor.yy379 = sqlite3WindowAlloc(pParse, yymsp[-5].minor.yy100, yymsp[-3].minor.yy389.eType, yymsp[-3].minor.yy389.pExpr, yymsp[-1].minor.yy389.eType, yymsp[-1].minor.yy389.pExpr, yymsp[0].minor.yy218);
  144254. }
  144255. yymsp[-5].minor.yy379 = yylhsminor.yy379;
  144256. break;
  144257. case 302: /* frame_bound_s ::= frame_bound */
  144258. case 304: /* frame_bound_e ::= frame_bound */ yytestcase(yyruleno==304);
  144259. {yylhsminor.yy389 = yymsp[0].minor.yy389;}
  144260. yymsp[0].minor.yy389 = yylhsminor.yy389;
  144261. break;
  144262. case 303: /* frame_bound_s ::= UNBOUNDED PRECEDING */
  144263. case 305: /* frame_bound_e ::= UNBOUNDED FOLLOWING */ yytestcase(yyruleno==305);
  144264. case 307: /* frame_bound ::= CURRENT ROW */ yytestcase(yyruleno==307);
  144265. {yylhsminor.yy389.eType = yymsp[-1].major; yylhsminor.yy389.pExpr = 0;}
  144266. yymsp[-1].minor.yy389 = yylhsminor.yy389;
  144267. break;
  144268. case 306: /* frame_bound ::= expr PRECEDING|FOLLOWING */
  144269. {yylhsminor.yy389.eType = yymsp[0].major; yylhsminor.yy389.pExpr = yymsp[-1].minor.yy102;}
  144270. yymsp[-1].minor.yy389 = yylhsminor.yy389;
  144271. break;
  144272. case 308: /* frame_exclude_opt ::= */
  144273. {yymsp[1].minor.yy218 = 0;}
  144274. break;
  144275. case 309: /* frame_exclude_opt ::= EXCLUDE frame_exclude */
  144276. {yymsp[-1].minor.yy218 = yymsp[0].minor.yy218;}
  144277. break;
  144278. case 310: /* frame_exclude ::= NO OTHERS */
  144279. case 311: /* frame_exclude ::= CURRENT ROW */ yytestcase(yyruleno==311);
  144280. {yymsp[-1].minor.yy218 = yymsp[-1].major; /*A-overwrites-X*/}
  144281. break;
  144282. case 312: /* frame_exclude ::= GROUP|TIES */
  144283. {yymsp[0].minor.yy218 = yymsp[0].major; /*A-overwrites-X*/}
  144284. break;
  144285. case 313: /* window_clause ::= WINDOW windowdefn_list */
  144286. { yymsp[-1].minor.yy379 = yymsp[0].minor.yy379; }
  144287. break;
  144288. case 314: /* over_clause ::= filter_opt OVER LP window RP */
  144289. {
  144290. yylhsminor.yy379 = yymsp[-1].minor.yy379;
  144291. assert( yylhsminor.yy379!=0 );
  144292. yylhsminor.yy379->pFilter = yymsp[-4].minor.yy102;
  144293. }
  144294. yymsp[-4].minor.yy379 = yylhsminor.yy379;
  144295. break;
  144296. case 315: /* over_clause ::= filter_opt OVER nm */
  144297. {
  144298. yylhsminor.yy379 = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window));
  144299. if( yylhsminor.yy379 ){
  144300. yylhsminor.yy379->zName = sqlite3DbStrNDup(pParse->db, yymsp[0].minor.yy0.z, yymsp[0].minor.yy0.n);
  144301. yylhsminor.yy379->pFilter = yymsp[-2].minor.yy102;
  144302. }else{
  144303. sqlite3ExprDelete(pParse->db, yymsp[-2].minor.yy102);
  144304. }
  144305. }
  144306. yymsp[-2].minor.yy379 = yylhsminor.yy379;
  144307. break;
  144308. case 317: /* filter_opt ::= FILTER LP WHERE expr RP */
  144309. { yymsp[-4].minor.yy102 = yymsp[-1].minor.yy102; }
  144310. break;
  144311. default:
  144312. /* (318) input ::= cmdlist */ yytestcase(yyruleno==318);
  144313. /* (319) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==319);
  144314. /* (320) cmdlist ::= ecmd (OPTIMIZED OUT) */ assert(yyruleno!=320);
  144315. /* (321) ecmd ::= SEMI */ yytestcase(yyruleno==321);
  144316. /* (322) ecmd ::= cmdx SEMI */ yytestcase(yyruleno==322);
  144317. /* (323) ecmd ::= explain cmdx */ yytestcase(yyruleno==323);
  144318. /* (324) trans_opt ::= */ yytestcase(yyruleno==324);
  144319. /* (325) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==325);
  144320. /* (326) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==326);
  144321. /* (327) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==327);
  144322. /* (328) savepoint_opt ::= */ yytestcase(yyruleno==328);
  144323. /* (329) cmd ::= create_table create_table_args */ yytestcase(yyruleno==329);
  144324. /* (330) columnlist ::= columnlist COMMA columnname carglist */ yytestcase(yyruleno==330);
  144325. /* (331) columnlist ::= columnname carglist */ yytestcase(yyruleno==331);
  144326. /* (332) nm ::= ID|INDEXED */ yytestcase(yyruleno==332);
  144327. /* (333) nm ::= STRING */ yytestcase(yyruleno==333);
  144328. /* (334) nm ::= JOIN_KW */ yytestcase(yyruleno==334);
  144329. /* (335) typetoken ::= typename */ yytestcase(yyruleno==335);
  144330. /* (336) typename ::= ID|STRING */ yytestcase(yyruleno==336);
  144331. /* (337) signed ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=337);
  144332. /* (338) signed ::= minus_num (OPTIMIZED OUT) */ assert(yyruleno!=338);
  144333. /* (339) carglist ::= carglist ccons */ yytestcase(yyruleno==339);
  144334. /* (340) carglist ::= */ yytestcase(yyruleno==340);
  144335. /* (341) ccons ::= NULL onconf */ yytestcase(yyruleno==341);
  144336. /* (342) conslist_opt ::= COMMA conslist */ yytestcase(yyruleno==342);
  144337. /* (343) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==343);
  144338. /* (344) conslist ::= tcons (OPTIMIZED OUT) */ assert(yyruleno!=344);
  144339. /* (345) tconscomma ::= */ yytestcase(yyruleno==345);
  144340. /* (346) defer_subclause_opt ::= defer_subclause (OPTIMIZED OUT) */ assert(yyruleno!=346);
  144341. /* (347) resolvetype ::= raisetype (OPTIMIZED OUT) */ assert(yyruleno!=347);
  144342. /* (348) selectnowith ::= oneselect (OPTIMIZED OUT) */ assert(yyruleno!=348);
  144343. /* (349) oneselect ::= values */ yytestcase(yyruleno==349);
  144344. /* (350) sclp ::= selcollist COMMA */ yytestcase(yyruleno==350);
  144345. /* (351) as ::= ID|STRING */ yytestcase(yyruleno==351);
  144346. /* (352) expr ::= term (OPTIMIZED OUT) */ assert(yyruleno!=352);
  144347. /* (353) likeop ::= LIKE_KW|MATCH */ yytestcase(yyruleno==353);
  144348. /* (354) exprlist ::= nexprlist */ yytestcase(yyruleno==354);
  144349. /* (355) nmnum ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=355);
  144350. /* (356) nmnum ::= nm (OPTIMIZED OUT) */ assert(yyruleno!=356);
  144351. /* (357) nmnum ::= ON */ yytestcase(yyruleno==357);
  144352. /* (358) nmnum ::= DELETE */ yytestcase(yyruleno==358);
  144353. /* (359) nmnum ::= DEFAULT */ yytestcase(yyruleno==359);
  144354. /* (360) plus_num ::= INTEGER|FLOAT */ yytestcase(yyruleno==360);
  144355. /* (361) foreach_clause ::= */ yytestcase(yyruleno==361);
  144356. /* (362) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==362);
  144357. /* (363) trnm ::= nm */ yytestcase(yyruleno==363);
  144358. /* (364) tridxby ::= */ yytestcase(yyruleno==364);
  144359. /* (365) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==365);
  144360. /* (366) database_kw_opt ::= */ yytestcase(yyruleno==366);
  144361. /* (367) kwcolumn_opt ::= */ yytestcase(yyruleno==367);
  144362. /* (368) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==368);
  144363. /* (369) vtabarglist ::= vtabarg */ yytestcase(yyruleno==369);
  144364. /* (370) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==370);
  144365. /* (371) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==371);
  144366. /* (372) anylist ::= */ yytestcase(yyruleno==372);
  144367. /* (373) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==373);
  144368. /* (374) anylist ::= anylist ANY */ yytestcase(yyruleno==374);
  144369. /* (375) with ::= */ yytestcase(yyruleno==375);
  144370. break;
  144371. /********** End reduce actions ************************************************/
  144372. };
  144373. assert( yyruleno<sizeof(yyRuleInfoLhs)/sizeof(yyRuleInfoLhs[0]) );
  144374. yygoto = yyRuleInfoLhs[yyruleno];
  144375. yysize = yyRuleInfoNRhs[yyruleno];
  144376. yyact = yy_find_reduce_action(yymsp[yysize].stateno,(YYCODETYPE)yygoto);
  144377. /* There are no SHIFTREDUCE actions on nonterminals because the table
  144378. ** generator has simplified them to pure REDUCE actions. */
  144379. assert( !(yyact>YY_MAX_SHIFT && yyact<=YY_MAX_SHIFTREDUCE) );
  144380. /* It is not possible for a REDUCE to be followed by an error */
  144381. assert( yyact!=YY_ERROR_ACTION );
  144382. yymsp += yysize+1;
  144383. yypParser->yytos = yymsp;
  144384. yymsp->stateno = (YYACTIONTYPE)yyact;
  144385. yymsp->major = (YYCODETYPE)yygoto;
  144386. yyTraceShift(yypParser, yyact, "... then shift");
  144387. return yyact;
  144388. }
  144389. /*
  144390. ** The following code executes when the parse fails
  144391. */
  144392. #ifndef YYNOERRORRECOVERY
  144393. static void yy_parse_failed(
  144394. yyParser *yypParser /* The parser */
  144395. ){
  144396. sqlite3ParserARG_FETCH
  144397. sqlite3ParserCTX_FETCH
  144398. #ifndef NDEBUG
  144399. if( yyTraceFILE ){
  144400. fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
  144401. }
  144402. #endif
  144403. while( yypParser->yytos>yypParser->yystack ) yy_pop_parser_stack(yypParser);
  144404. /* Here code is inserted which will be executed whenever the
  144405. ** parser fails */
  144406. /************ Begin %parse_failure code ***************************************/
  144407. /************ End %parse_failure code *****************************************/
  144408. sqlite3ParserARG_STORE /* Suppress warning about unused %extra_argument variable */
  144409. sqlite3ParserCTX_STORE
  144410. }
  144411. #endif /* YYNOERRORRECOVERY */
  144412. /*
  144413. ** The following code executes when a syntax error first occurs.
  144414. */
  144415. static void yy_syntax_error(
  144416. yyParser *yypParser, /* The parser */
  144417. int yymajor, /* The major type of the error token */
  144418. sqlite3ParserTOKENTYPE yyminor /* The minor type of the error token */
  144419. ){
  144420. sqlite3ParserARG_FETCH
  144421. sqlite3ParserCTX_FETCH
  144422. #define TOKEN yyminor
  144423. /************ Begin %syntax_error code ****************************************/
  144424. UNUSED_PARAMETER(yymajor); /* Silence some compiler warnings */
  144425. if( TOKEN.z[0] ){
  144426. sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
  144427. }else{
  144428. sqlite3ErrorMsg(pParse, "incomplete input");
  144429. }
  144430. /************ End %syntax_error code ******************************************/
  144431. sqlite3ParserARG_STORE /* Suppress warning about unused %extra_argument variable */
  144432. sqlite3ParserCTX_STORE
  144433. }
  144434. /*
  144435. ** The following is executed when the parser accepts
  144436. */
  144437. static void yy_accept(
  144438. yyParser *yypParser /* The parser */
  144439. ){
  144440. sqlite3ParserARG_FETCH
  144441. sqlite3ParserCTX_FETCH
  144442. #ifndef NDEBUG
  144443. if( yyTraceFILE ){
  144444. fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
  144445. }
  144446. #endif
  144447. #ifndef YYNOERRORRECOVERY
  144448. yypParser->yyerrcnt = -1;
  144449. #endif
  144450. assert( yypParser->yytos==yypParser->yystack );
  144451. /* Here code is inserted which will be executed whenever the
  144452. ** parser accepts */
  144453. /*********** Begin %parse_accept code *****************************************/
  144454. /*********** End %parse_accept code *******************************************/
  144455. sqlite3ParserARG_STORE /* Suppress warning about unused %extra_argument variable */
  144456. sqlite3ParserCTX_STORE
  144457. }
  144458. /* The main parser program.
  144459. ** The first argument is a pointer to a structure obtained from
  144460. ** "sqlite3ParserAlloc" which describes the current state of the parser.
  144461. ** The second argument is the major token number. The third is
  144462. ** the minor token. The fourth optional argument is whatever the
  144463. ** user wants (and specified in the grammar) and is available for
  144464. ** use by the action routines.
  144465. **
  144466. ** Inputs:
  144467. ** <ul>
  144468. ** <li> A pointer to the parser (an opaque structure.)
  144469. ** <li> The major token number.
  144470. ** <li> The minor token number.
  144471. ** <li> An option argument of a grammar-specified type.
  144472. ** </ul>
  144473. **
  144474. ** Outputs:
  144475. ** None.
  144476. */
  144477. SQLITE_PRIVATE void sqlite3Parser(
  144478. void *yyp, /* The parser */
  144479. int yymajor, /* The major token code number */
  144480. sqlite3ParserTOKENTYPE yyminor /* The value for the token */
  144481. sqlite3ParserARG_PDECL /* Optional %extra_argument parameter */
  144482. ){
  144483. YYMINORTYPE yyminorunion;
  144484. YYACTIONTYPE yyact; /* The parser action. */
  144485. #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
  144486. int yyendofinput; /* True if we are at the end of input */
  144487. #endif
  144488. #ifdef YYERRORSYMBOL
  144489. int yyerrorhit = 0; /* True if yymajor has invoked an error */
  144490. #endif
  144491. yyParser *yypParser = (yyParser*)yyp; /* The parser */
  144492. sqlite3ParserCTX_FETCH
  144493. sqlite3ParserARG_STORE
  144494. assert( yypParser->yytos!=0 );
  144495. #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
  144496. yyendofinput = (yymajor==0);
  144497. #endif
  144498. yyact = yypParser->yytos->stateno;
  144499. #ifndef NDEBUG
  144500. if( yyTraceFILE ){
  144501. if( yyact < YY_MIN_REDUCE ){
  144502. fprintf(yyTraceFILE,"%sInput '%s' in state %d\n",
  144503. yyTracePrompt,yyTokenName[yymajor],yyact);
  144504. }else{
  144505. fprintf(yyTraceFILE,"%sInput '%s' with pending reduce %d\n",
  144506. yyTracePrompt,yyTokenName[yymajor],yyact-YY_MIN_REDUCE);
  144507. }
  144508. }
  144509. #endif
  144510. do{
  144511. assert( yyact==yypParser->yytos->stateno );
  144512. yyact = yy_find_shift_action((YYCODETYPE)yymajor,yyact);
  144513. if( yyact >= YY_MIN_REDUCE ){
  144514. yyact = yy_reduce(yypParser,yyact-YY_MIN_REDUCE,yymajor,
  144515. yyminor sqlite3ParserCTX_PARAM);
  144516. }else if( yyact <= YY_MAX_SHIFTREDUCE ){
  144517. yy_shift(yypParser,yyact,(YYCODETYPE)yymajor,yyminor);
  144518. #ifndef YYNOERRORRECOVERY
  144519. yypParser->yyerrcnt--;
  144520. #endif
  144521. break;
  144522. }else if( yyact==YY_ACCEPT_ACTION ){
  144523. yypParser->yytos--;
  144524. yy_accept(yypParser);
  144525. return;
  144526. }else{
  144527. assert( yyact == YY_ERROR_ACTION );
  144528. yyminorunion.yy0 = yyminor;
  144529. #ifdef YYERRORSYMBOL
  144530. int yymx;
  144531. #endif
  144532. #ifndef NDEBUG
  144533. if( yyTraceFILE ){
  144534. fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
  144535. }
  144536. #endif
  144537. #ifdef YYERRORSYMBOL
  144538. /* A syntax error has occurred.
  144539. ** The response to an error depends upon whether or not the
  144540. ** grammar defines an error token "ERROR".
  144541. **
  144542. ** This is what we do if the grammar does define ERROR:
  144543. **
  144544. ** * Call the %syntax_error function.
  144545. **
  144546. ** * Begin popping the stack until we enter a state where
  144547. ** it is legal to shift the error symbol, then shift
  144548. ** the error symbol.
  144549. **
  144550. ** * Set the error count to three.
  144551. **
  144552. ** * Begin accepting and shifting new tokens. No new error
  144553. ** processing will occur until three tokens have been
  144554. ** shifted successfully.
  144555. **
  144556. */
  144557. if( yypParser->yyerrcnt<0 ){
  144558. yy_syntax_error(yypParser,yymajor,yyminor);
  144559. }
  144560. yymx = yypParser->yytos->major;
  144561. if( yymx==YYERRORSYMBOL || yyerrorhit ){
  144562. #ifndef NDEBUG
  144563. if( yyTraceFILE ){
  144564. fprintf(yyTraceFILE,"%sDiscard input token %s\n",
  144565. yyTracePrompt,yyTokenName[yymajor]);
  144566. }
  144567. #endif
  144568. yy_destructor(yypParser, (YYCODETYPE)yymajor, &yyminorunion);
  144569. yymajor = YYNOCODE;
  144570. }else{
  144571. while( yypParser->yytos >= yypParser->yystack
  144572. && (yyact = yy_find_reduce_action(
  144573. yypParser->yytos->stateno,
  144574. YYERRORSYMBOL)) > YY_MAX_SHIFTREDUCE
  144575. ){
  144576. yy_pop_parser_stack(yypParser);
  144577. }
  144578. if( yypParser->yytos < yypParser->yystack || yymajor==0 ){
  144579. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  144580. yy_parse_failed(yypParser);
  144581. #ifndef YYNOERRORRECOVERY
  144582. yypParser->yyerrcnt = -1;
  144583. #endif
  144584. yymajor = YYNOCODE;
  144585. }else if( yymx!=YYERRORSYMBOL ){
  144586. yy_shift(yypParser,yyact,YYERRORSYMBOL,yyminor);
  144587. }
  144588. }
  144589. yypParser->yyerrcnt = 3;
  144590. yyerrorhit = 1;
  144591. if( yymajor==YYNOCODE ) break;
  144592. yyact = yypParser->yytos->stateno;
  144593. #elif defined(YYNOERRORRECOVERY)
  144594. /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
  144595. ** do any kind of error recovery. Instead, simply invoke the syntax
  144596. ** error routine and continue going as if nothing had happened.
  144597. **
  144598. ** Applications can set this macro (for example inside %include) if
  144599. ** they intend to abandon the parse upon the first syntax error seen.
  144600. */
  144601. yy_syntax_error(yypParser,yymajor, yyminor);
  144602. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  144603. break;
  144604. #else /* YYERRORSYMBOL is not defined */
  144605. /* This is what we do if the grammar does not define ERROR:
  144606. **
  144607. ** * Report an error message, and throw away the input token.
  144608. **
  144609. ** * If the input token is $, then fail the parse.
  144610. **
  144611. ** As before, subsequent error messages are suppressed until
  144612. ** three input tokens have been successfully shifted.
  144613. */
  144614. if( yypParser->yyerrcnt<=0 ){
  144615. yy_syntax_error(yypParser,yymajor, yyminor);
  144616. }
  144617. yypParser->yyerrcnt = 3;
  144618. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  144619. if( yyendofinput ){
  144620. yy_parse_failed(yypParser);
  144621. #ifndef YYNOERRORRECOVERY
  144622. yypParser->yyerrcnt = -1;
  144623. #endif
  144624. }
  144625. break;
  144626. #endif
  144627. }
  144628. }while( yypParser->yytos>yypParser->yystack );
  144629. #ifndef NDEBUG
  144630. if( yyTraceFILE ){
  144631. yyStackEntry *i;
  144632. char cDiv = '[';
  144633. fprintf(yyTraceFILE,"%sReturn. Stack=",yyTracePrompt);
  144634. for(i=&yypParser->yystack[1]; i<=yypParser->yytos; i++){
  144635. fprintf(yyTraceFILE,"%c%s", cDiv, yyTokenName[i->major]);
  144636. cDiv = ' ';
  144637. }
  144638. fprintf(yyTraceFILE,"]\n");
  144639. }
  144640. #endif
  144641. return;
  144642. }
  144643. /*
  144644. ** Return the fallback token corresponding to canonical token iToken, or
  144645. ** 0 if iToken has no fallback.
  144646. */
  144647. SQLITE_PRIVATE int sqlite3ParserFallback(int iToken){
  144648. #ifdef YYFALLBACK
  144649. if( iToken<(int)(sizeof(yyFallback)/sizeof(yyFallback[0])) ){
  144650. return yyFallback[iToken];
  144651. }
  144652. #else
  144653. (void)iToken;
  144654. #endif
  144655. return 0;
  144656. }
  144657. /************** End of parse.c ***********************************************/
  144658. /************** Begin file tokenize.c ****************************************/
  144659. /*
  144660. ** 2001 September 15
  144661. **
  144662. ** The author disclaims copyright to this source code. In place of
  144663. ** a legal notice, here is a blessing:
  144664. **
  144665. ** May you do good and not evil.
  144666. ** May you find forgiveness for yourself and forgive others.
  144667. ** May you share freely, never taking more than you give.
  144668. **
  144669. *************************************************************************
  144670. ** An tokenizer for SQL
  144671. **
  144672. ** This file contains C code that splits an SQL input string up into
  144673. ** individual tokens and sends those tokens one-by-one over to the
  144674. ** parser for analysis.
  144675. */
  144676. /* #include "sqliteInt.h" */
  144677. /* #include <stdlib.h> */
  144678. /* Character classes for tokenizing
  144679. **
  144680. ** In the sqlite3GetToken() function, a switch() on aiClass[c] is implemented
  144681. ** using a lookup table, whereas a switch() directly on c uses a binary search.
  144682. ** The lookup table is much faster. To maximize speed, and to ensure that
  144683. ** a lookup table is used, all of the classes need to be small integers and
  144684. ** all of them need to be used within the switch.
  144685. */
  144686. #define CC_X 0 /* The letter 'x', or start of BLOB literal */
  144687. #define CC_KYWD 1 /* Alphabetics or '_'. Usable in a keyword */
  144688. #define CC_ID 2 /* unicode characters usable in IDs */
  144689. #define CC_DIGIT 3 /* Digits */
  144690. #define CC_DOLLAR 4 /* '$' */
  144691. #define CC_VARALPHA 5 /* '@', '#', ':'. Alphabetic SQL variables */
  144692. #define CC_VARNUM 6 /* '?'. Numeric SQL variables */
  144693. #define CC_SPACE 7 /* Space characters */
  144694. #define CC_QUOTE 8 /* '"', '\'', or '`'. String literals, quoted ids */
  144695. #define CC_QUOTE2 9 /* '['. [...] style quoted ids */
  144696. #define CC_PIPE 10 /* '|'. Bitwise OR or concatenate */
  144697. #define CC_MINUS 11 /* '-'. Minus or SQL-style comment */
  144698. #define CC_LT 12 /* '<'. Part of < or <= or <> */
  144699. #define CC_GT 13 /* '>'. Part of > or >= */
  144700. #define CC_EQ 14 /* '='. Part of = or == */
  144701. #define CC_BANG 15 /* '!'. Part of != */
  144702. #define CC_SLASH 16 /* '/'. / or c-style comment */
  144703. #define CC_LP 17 /* '(' */
  144704. #define CC_RP 18 /* ')' */
  144705. #define CC_SEMI 19 /* ';' */
  144706. #define CC_PLUS 20 /* '+' */
  144707. #define CC_STAR 21 /* '*' */
  144708. #define CC_PERCENT 22 /* '%' */
  144709. #define CC_COMMA 23 /* ',' */
  144710. #define CC_AND 24 /* '&' */
  144711. #define CC_TILDA 25 /* '~' */
  144712. #define CC_DOT 26 /* '.' */
  144713. #define CC_ILLEGAL 27 /* Illegal character */
  144714. #define CC_NUL 28 /* 0x00 */
  144715. static const unsigned char aiClass[] = {
  144716. #ifdef SQLITE_ASCII
  144717. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xa xb xc xd xe xf */
  144718. /* 0x */ 28, 27, 27, 27, 27, 27, 27, 27, 27, 7, 7, 27, 7, 7, 27, 27,
  144719. /* 1x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  144720. /* 2x */ 7, 15, 8, 5, 4, 22, 24, 8, 17, 18, 21, 20, 23, 11, 26, 16,
  144721. /* 3x */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 5, 19, 12, 14, 13, 6,
  144722. /* 4x */ 5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  144723. /* 5x */ 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 9, 27, 27, 27, 1,
  144724. /* 6x */ 8, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  144725. /* 7x */ 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 27, 10, 27, 25, 27,
  144726. /* 8x */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  144727. /* 9x */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  144728. /* Ax */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  144729. /* Bx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  144730. /* Cx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  144731. /* Dx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  144732. /* Ex */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  144733. /* Fx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2
  144734. #endif
  144735. #ifdef SQLITE_EBCDIC
  144736. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xa xb xc xd xe xf */
  144737. /* 0x */ 27, 27, 27, 27, 27, 7, 27, 27, 27, 27, 27, 27, 7, 7, 27, 27,
  144738. /* 1x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  144739. /* 2x */ 27, 27, 27, 27, 27, 7, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  144740. /* 3x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  144741. /* 4x */ 7, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 26, 12, 17, 20, 10,
  144742. /* 5x */ 24, 27, 27, 27, 27, 27, 27, 27, 27, 27, 15, 4, 21, 18, 19, 27,
  144743. /* 6x */ 11, 16, 27, 27, 27, 27, 27, 27, 27, 27, 27, 23, 22, 1, 13, 6,
  144744. /* 7x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 8, 5, 5, 5, 8, 14, 8,
  144745. /* 8x */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27,
  144746. /* 9x */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27,
  144747. /* Ax */ 27, 25, 1, 1, 1, 1, 1, 0, 1, 1, 27, 27, 27, 27, 27, 27,
  144748. /* Bx */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 9, 27, 27, 27, 27, 27,
  144749. /* Cx */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27,
  144750. /* Dx */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27,
  144751. /* Ex */ 27, 27, 1, 1, 1, 1, 1, 0, 1, 1, 27, 27, 27, 27, 27, 27,
  144752. /* Fx */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 27, 27, 27, 27, 27, 27,
  144753. #endif
  144754. };
  144755. /*
  144756. ** The charMap() macro maps alphabetic characters (only) into their
  144757. ** lower-case ASCII equivalent. On ASCII machines, this is just
  144758. ** an upper-to-lower case map. On EBCDIC machines we also need
  144759. ** to adjust the encoding. The mapping is only valid for alphabetics
  144760. ** which are the only characters for which this feature is used.
  144761. **
  144762. ** Used by keywordhash.h
  144763. */
  144764. #ifdef SQLITE_ASCII
  144765. # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
  144766. #endif
  144767. #ifdef SQLITE_EBCDIC
  144768. # define charMap(X) ebcdicToAscii[(unsigned char)X]
  144769. const unsigned char ebcdicToAscii[] = {
  144770. /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
  144771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
  144772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
  144773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
  144774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 3x */
  144775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 4x */
  144776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 5x */
  144777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 95, 0, 0, /* 6x */
  144778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 7x */
  144779. 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* 8x */
  144780. 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* 9x */
  144781. 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ax */
  144782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
  144783. 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* Cx */
  144784. 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* Dx */
  144785. 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ex */
  144786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Fx */
  144787. };
  144788. #endif
  144789. /*
  144790. ** The sqlite3KeywordCode function looks up an identifier to determine if
  144791. ** it is a keyword. If it is a keyword, the token code of that keyword is
  144792. ** returned. If the input is not a keyword, TK_ID is returned.
  144793. **
  144794. ** The implementation of this routine was generated by a program,
  144795. ** mkkeywordhash.c, located in the tool subdirectory of the distribution.
  144796. ** The output of the mkkeywordhash.c program is written into a file
  144797. ** named keywordhash.h and then included into this source file by
  144798. ** the #include below.
  144799. */
  144800. /************** Include keywordhash.h in the middle of tokenize.c ************/
  144801. /************** Begin file keywordhash.h *************************************/
  144802. /***** This file contains automatically generated code ******
  144803. **
  144804. ** The code in this file has been automatically generated by
  144805. **
  144806. ** sqlite/tool/mkkeywordhash.c
  144807. **
  144808. ** The code in this file implements a function that determines whether
  144809. ** or not a given identifier is really an SQL keyword. The same thing
  144810. ** might be implemented more directly using a hand-written hash table.
  144811. ** But by using this automatically generated code, the size of the code
  144812. ** is substantially reduced. This is important for embedded applications
  144813. ** on platforms with limited memory.
  144814. */
  144815. /* Hash score: 214 */
  144816. /* zKWText[] encodes 950 bytes of keyword text in 629 bytes */
  144817. /* REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT */
  144818. /* ABLEFTHENDEFERRABLELSEXCLUDELETEMPORARYCONSTRAINTERSECTIES */
  144819. /* AVEPOINTOFFSETRANSACTIONATURALTERAISEXCEPTRIGGEREFERENCES */
  144820. /* UNIQUERYWITHOUTERELEASEXCLUSIVEXISTSATTACHAVINGLOBEGINNERANGE */
  144821. /* BETWEENOTHINGROUPSCASCADETACHCASECOLLATECREATECURRENT_DATE */
  144822. /* IMMEDIATEJOINSERTLIKEMATCHPLANALYZEPRAGMABORTUPDATEVALUES */
  144823. /* VIRTUALIMITWHENOTNULLWHERECURSIVEAFTERENAMEANDEFAULT */
  144824. /* AUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSSCURRENT_TIMESTAMP */
  144825. /* ARTITIONDEFERREDISTINCTDROPRECEDINGFAILFILTEREPLACEFOLLOWING */
  144826. /* FROMFULLIFISNULLORDERESTRICTOTHERSOVERIGHTROLLBACKROWS */
  144827. /* UNBOUNDEDUNIONUSINGVACUUMVIEWINDOWBYINITIALLYPRIMARY */
  144828. static const char zKWText[628] = {
  144829. 'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
  144830. 'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
  144831. 'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
  144832. 'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
  144833. 'E','R','R','A','B','L','E','L','S','E','X','C','L','U','D','E','L','E',
  144834. 'T','E','M','P','O','R','A','R','Y','C','O','N','S','T','R','A','I','N',
  144835. 'T','E','R','S','E','C','T','I','E','S','A','V','E','P','O','I','N','T',
  144836. 'O','F','F','S','E','T','R','A','N','S','A','C','T','I','O','N','A','T',
  144837. 'U','R','A','L','T','E','R','A','I','S','E','X','C','E','P','T','R','I',
  144838. 'G','G','E','R','E','F','E','R','E','N','C','E','S','U','N','I','Q','U',
  144839. 'E','R','Y','W','I','T','H','O','U','T','E','R','E','L','E','A','S','E',
  144840. 'X','C','L','U','S','I','V','E','X','I','S','T','S','A','T','T','A','C',
  144841. 'H','A','V','I','N','G','L','O','B','E','G','I','N','N','E','R','A','N',
  144842. 'G','E','B','E','T','W','E','E','N','O','T','H','I','N','G','R','O','U',
  144843. 'P','S','C','A','S','C','A','D','E','T','A','C','H','C','A','S','E','C',
  144844. 'O','L','L','A','T','E','C','R','E','A','T','E','C','U','R','R','E','N',
  144845. 'T','_','D','A','T','E','I','M','M','E','D','I','A','T','E','J','O','I',
  144846. 'N','S','E','R','T','L','I','K','E','M','A','T','C','H','P','L','A','N',
  144847. 'A','L','Y','Z','E','P','R','A','G','M','A','B','O','R','T','U','P','D',
  144848. 'A','T','E','V','A','L','U','E','S','V','I','R','T','U','A','L','I','M',
  144849. 'I','T','W','H','E','N','O','T','N','U','L','L','W','H','E','R','E','C',
  144850. 'U','R','S','I','V','E','A','F','T','E','R','E','N','A','M','E','A','N',
  144851. 'D','E','F','A','U','L','T','A','U','T','O','I','N','C','R','E','M','E',
  144852. 'N','T','C','A','S','T','C','O','L','U','M','N','C','O','M','M','I','T',
  144853. 'C','O','N','F','L','I','C','T','C','R','O','S','S','C','U','R','R','E',
  144854. 'N','T','_','T','I','M','E','S','T','A','M','P','A','R','T','I','T','I',
  144855. 'O','N','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T','D',
  144856. 'R','O','P','R','E','C','E','D','I','N','G','F','A','I','L','F','I','L',
  144857. 'T','E','R','E','P','L','A','C','E','F','O','L','L','O','W','I','N','G',
  144858. 'F','R','O','M','F','U','L','L','I','F','I','S','N','U','L','L','O','R',
  144859. 'D','E','R','E','S','T','R','I','C','T','O','T','H','E','R','S','O','V',
  144860. 'E','R','I','G','H','T','R','O','L','L','B','A','C','K','R','O','W','S',
  144861. 'U','N','B','O','U','N','D','E','D','U','N','I','O','N','U','S','I','N',
  144862. 'G','V','A','C','U','U','M','V','I','E','W','I','N','D','O','W','B','Y',
  144863. 'I','N','I','T','I','A','L','L','Y','P','R','I','M','A','R','Y',
  144864. };
  144865. /* aKWHash[i] is the hash value for the i-th keyword */
  144866. static const unsigned char aKWHash[127] = {
  144867. 75, 111, 127, 73, 108, 29, 0, 0, 83, 0, 77, 63, 0,
  144868. 37, 33, 78, 15, 0, 126, 86, 57, 120, 128, 19, 0, 0,
  144869. 133, 0, 131, 123, 0, 22, 98, 0, 9, 0, 0, 117, 71,
  144870. 0, 69, 6, 0, 49, 95, 140, 0, 129, 106, 0, 0, 54,
  144871. 0, 109, 24, 0, 17, 0, 134, 56, 23, 26, 5, 58, 135,
  144872. 101, 0, 0, 139, 112, 62, 138, 59, 115, 65, 0, 96, 0,
  144873. 105, 45, 0, 104, 0, 0, 0, 100, 97, 102, 107, 119, 14,
  144874. 31, 118, 0, 81, 0, 136, 116, 137, 61, 124, 132, 80, 121,
  144875. 88, 30, 85, 0, 0, 99, 35, 125, 122, 0, 130, 0, 0,
  144876. 41, 0, 91, 89, 90, 0, 20, 87, 113, 82,
  144877. };
  144878. /* aKWNext[] forms the hash collision chain. If aKWHash[i]==0
  144879. ** then the i-th keyword has no more hash collisions. Otherwise,
  144880. ** the next keyword with the same hash is aKWHash[i]-1. */
  144881. static const unsigned char aKWNext[140] = {
  144882. 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0,
  144883. 0, 2, 0, 0, 0, 0, 0, 0, 13, 0, 0, 0, 0,
  144884. 0, 0, 0, 21, 0, 0, 12, 0, 0, 0, 0, 0, 0,
  144885. 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  144886. 51, 28, 0, 0, 38, 0, 0, 0, 44, 0, 0, 0, 3,
  144887. 0, 0, 67, 1, 66, 0, 0, 0, 36, 0, 47, 0, 0,
  144888. 0, 0, 0, 48, 50, 76, 0, 0, 42, 0, 60, 0, 0,
  144889. 0, 43, 0, 16, 55, 10, 0, 0, 0, 0, 0, 0, 0,
  144890. 11, 72, 93, 0, 0, 8, 0, 110, 0, 103, 40, 53, 70,
  144891. 0, 114, 0, 74, 52, 0, 0, 92, 39, 46, 0, 68, 32,
  144892. 84, 0, 34, 27, 25, 18, 94, 0, 64, 79,
  144893. };
  144894. /* aKWLen[i] is the length (in bytes) of the i-th keyword */
  144895. static const unsigned char aKWLen[140] = {
  144896. 7, 7, 5, 4, 6, 4, 5, 3, 6, 7, 3, 6, 6,
  144897. 7, 7, 3, 8, 2, 6, 5, 4, 4, 3, 10, 4, 7,
  144898. 6, 9, 4, 2, 10, 9, 4, 9, 4, 6, 2, 3, 11,
  144899. 6, 2, 7, 5, 5, 6, 7, 10, 6, 5, 7, 4, 5,
  144900. 7, 9, 6, 6, 6, 4, 5, 5, 5, 7, 7, 6, 5,
  144901. 7, 3, 6, 4, 7, 6, 12, 9, 4, 6, 4, 5, 4,
  144902. 7, 6, 5, 6, 6, 7, 5, 4, 7, 3, 2, 4, 5,
  144903. 9, 5, 6, 3, 7, 13, 2, 2, 4, 6, 6, 8, 5,
  144904. 17, 12, 7, 9, 8, 8, 2, 4, 9, 4, 6, 7, 9,
  144905. 4, 4, 2, 6, 5, 8, 6, 4, 5, 8, 4, 3, 9,
  144906. 5, 5, 6, 4, 6, 2, 2, 9, 3, 7,
  144907. };
  144908. /* aKWOffset[i] is the index into zKWText[] of the start of
  144909. ** the text for the i-th keyword. */
  144910. static const unsigned short int aKWOffset[140] = {
  144911. 0, 2, 2, 8, 9, 14, 16, 20, 23, 25, 25, 29, 33,
  144912. 36, 41, 46, 48, 53, 54, 59, 62, 65, 67, 69, 78, 81,
  144913. 86, 90, 90, 94, 99, 106, 114, 117, 123, 126, 126, 129, 131,
  144914. 136, 140, 141, 146, 150, 154, 159, 165, 175, 178, 183, 183, 187,
  144915. 191, 197, 205, 211, 216, 221, 224, 227, 231, 236, 242, 248, 248,
  144916. 254, 255, 259, 265, 269, 276, 282, 294, 303, 305, 311, 315, 320,
  144917. 322, 329, 334, 339, 345, 351, 357, 362, 365, 365, 365, 368, 372,
  144918. 375, 384, 388, 394, 396, 403, 405, 407, 416, 420, 426, 432, 440,
  144919. 445, 445, 445, 461, 470, 477, 478, 485, 488, 497, 501, 506, 513,
  144920. 522, 526, 530, 532, 538, 542, 550, 556, 559, 564, 572, 572, 576,
  144921. 585, 590, 595, 601, 604, 607, 610, 612, 617, 621,
  144922. };
  144923. /* aKWCode[i] is the parser symbol code for the i-th keyword */
  144924. static const unsigned char aKWCode[140] = {
  144925. TK_REINDEX, TK_INDEXED, TK_INDEX, TK_DESC, TK_ESCAPE,
  144926. TK_EACH, TK_CHECK, TK_KEY, TK_BEFORE, TK_FOREIGN,
  144927. TK_FOR, TK_IGNORE, TK_LIKE_KW, TK_EXPLAIN, TK_INSTEAD,
  144928. TK_ADD, TK_DATABASE, TK_AS, TK_SELECT, TK_TABLE,
  144929. TK_JOIN_KW, TK_THEN, TK_END, TK_DEFERRABLE, TK_ELSE,
  144930. TK_EXCLUDE, TK_DELETE, TK_TEMP, TK_TEMP, TK_OR,
  144931. TK_CONSTRAINT, TK_INTERSECT, TK_TIES, TK_SAVEPOINT, TK_INTO,
  144932. TK_OFFSET, TK_OF, TK_SET, TK_TRANSACTION,TK_ACTION,
  144933. TK_ON, TK_JOIN_KW, TK_ALTER, TK_RAISE, TK_EXCEPT,
  144934. TK_TRIGGER, TK_REFERENCES, TK_UNIQUE, TK_QUERY, TK_WITHOUT,
  144935. TK_WITH, TK_JOIN_KW, TK_RELEASE, TK_EXCLUSIVE, TK_EXISTS,
  144936. TK_ATTACH, TK_HAVING, TK_LIKE_KW, TK_BEGIN, TK_JOIN_KW,
  144937. TK_RANGE, TK_BETWEEN, TK_NOTHING, TK_GROUPS, TK_GROUP,
  144938. TK_CASCADE, TK_ASC, TK_DETACH, TK_CASE, TK_COLLATE,
  144939. TK_CREATE, TK_CTIME_KW, TK_IMMEDIATE, TK_JOIN, TK_INSERT,
  144940. TK_LIKE_KW, TK_MATCH, TK_PLAN, TK_ANALYZE, TK_PRAGMA,
  144941. TK_ABORT, TK_UPDATE, TK_VALUES, TK_VIRTUAL, TK_LIMIT,
  144942. TK_WHEN, TK_NOTNULL, TK_NOT, TK_NO, TK_NULL,
  144943. TK_WHERE, TK_RECURSIVE, TK_AFTER, TK_RENAME, TK_AND,
  144944. TK_DEFAULT, TK_AUTOINCR, TK_TO, TK_IN, TK_CAST,
  144945. TK_COLUMNKW, TK_COMMIT, TK_CONFLICT, TK_JOIN_KW, TK_CTIME_KW,
  144946. TK_CTIME_KW, TK_CURRENT, TK_PARTITION, TK_DEFERRED, TK_DISTINCT,
  144947. TK_IS, TK_DROP, TK_PRECEDING, TK_FAIL, TK_FILTER,
  144948. TK_REPLACE, TK_FOLLOWING, TK_FROM, TK_JOIN_KW, TK_IF,
  144949. TK_ISNULL, TK_ORDER, TK_RESTRICT, TK_OTHERS, TK_OVER,
  144950. TK_JOIN_KW, TK_ROLLBACK, TK_ROWS, TK_ROW, TK_UNBOUNDED,
  144951. TK_UNION, TK_USING, TK_VACUUM, TK_VIEW, TK_WINDOW,
  144952. TK_DO, TK_BY, TK_INITIALLY, TK_ALL, TK_PRIMARY,
  144953. };
  144954. /* Check to see if z[0..n-1] is a keyword. If it is, write the
  144955. ** parser symbol code for that keyword into *pType. Always
  144956. ** return the integer n (the length of the token). */
  144957. static int keywordCode(const char *z, int n, int *pType){
  144958. int i, j;
  144959. const char *zKW;
  144960. if( n>=2 ){
  144961. i = ((charMap(z[0])*4) ^ (charMap(z[n-1])*3) ^ n) % 127;
  144962. for(i=((int)aKWHash[i])-1; i>=0; i=((int)aKWNext[i])-1){
  144963. if( aKWLen[i]!=n ) continue;
  144964. j = 0;
  144965. zKW = &zKWText[aKWOffset[i]];
  144966. #ifdef SQLITE_ASCII
  144967. while( j<n && (z[j]&~0x20)==zKW[j] ){ j++; }
  144968. #endif
  144969. #ifdef SQLITE_EBCDIC
  144970. while( j<n && toupper(z[j])==zKW[j] ){ j++; }
  144971. #endif
  144972. if( j<n ) continue;
  144973. testcase( i==0 ); /* REINDEX */
  144974. testcase( i==1 ); /* INDEXED */
  144975. testcase( i==2 ); /* INDEX */
  144976. testcase( i==3 ); /* DESC */
  144977. testcase( i==4 ); /* ESCAPE */
  144978. testcase( i==5 ); /* EACH */
  144979. testcase( i==6 ); /* CHECK */
  144980. testcase( i==7 ); /* KEY */
  144981. testcase( i==8 ); /* BEFORE */
  144982. testcase( i==9 ); /* FOREIGN */
  144983. testcase( i==10 ); /* FOR */
  144984. testcase( i==11 ); /* IGNORE */
  144985. testcase( i==12 ); /* REGEXP */
  144986. testcase( i==13 ); /* EXPLAIN */
  144987. testcase( i==14 ); /* INSTEAD */
  144988. testcase( i==15 ); /* ADD */
  144989. testcase( i==16 ); /* DATABASE */
  144990. testcase( i==17 ); /* AS */
  144991. testcase( i==18 ); /* SELECT */
  144992. testcase( i==19 ); /* TABLE */
  144993. testcase( i==20 ); /* LEFT */
  144994. testcase( i==21 ); /* THEN */
  144995. testcase( i==22 ); /* END */
  144996. testcase( i==23 ); /* DEFERRABLE */
  144997. testcase( i==24 ); /* ELSE */
  144998. testcase( i==25 ); /* EXCLUDE */
  144999. testcase( i==26 ); /* DELETE */
  145000. testcase( i==27 ); /* TEMPORARY */
  145001. testcase( i==28 ); /* TEMP */
  145002. testcase( i==29 ); /* OR */
  145003. testcase( i==30 ); /* CONSTRAINT */
  145004. testcase( i==31 ); /* INTERSECT */
  145005. testcase( i==32 ); /* TIES */
  145006. testcase( i==33 ); /* SAVEPOINT */
  145007. testcase( i==34 ); /* INTO */
  145008. testcase( i==35 ); /* OFFSET */
  145009. testcase( i==36 ); /* OF */
  145010. testcase( i==37 ); /* SET */
  145011. testcase( i==38 ); /* TRANSACTION */
  145012. testcase( i==39 ); /* ACTION */
  145013. testcase( i==40 ); /* ON */
  145014. testcase( i==41 ); /* NATURAL */
  145015. testcase( i==42 ); /* ALTER */
  145016. testcase( i==43 ); /* RAISE */
  145017. testcase( i==44 ); /* EXCEPT */
  145018. testcase( i==45 ); /* TRIGGER */
  145019. testcase( i==46 ); /* REFERENCES */
  145020. testcase( i==47 ); /* UNIQUE */
  145021. testcase( i==48 ); /* QUERY */
  145022. testcase( i==49 ); /* WITHOUT */
  145023. testcase( i==50 ); /* WITH */
  145024. testcase( i==51 ); /* OUTER */
  145025. testcase( i==52 ); /* RELEASE */
  145026. testcase( i==53 ); /* EXCLUSIVE */
  145027. testcase( i==54 ); /* EXISTS */
  145028. testcase( i==55 ); /* ATTACH */
  145029. testcase( i==56 ); /* HAVING */
  145030. testcase( i==57 ); /* GLOB */
  145031. testcase( i==58 ); /* BEGIN */
  145032. testcase( i==59 ); /* INNER */
  145033. testcase( i==60 ); /* RANGE */
  145034. testcase( i==61 ); /* BETWEEN */
  145035. testcase( i==62 ); /* NOTHING */
  145036. testcase( i==63 ); /* GROUPS */
  145037. testcase( i==64 ); /* GROUP */
  145038. testcase( i==65 ); /* CASCADE */
  145039. testcase( i==66 ); /* ASC */
  145040. testcase( i==67 ); /* DETACH */
  145041. testcase( i==68 ); /* CASE */
  145042. testcase( i==69 ); /* COLLATE */
  145043. testcase( i==70 ); /* CREATE */
  145044. testcase( i==71 ); /* CURRENT_DATE */
  145045. testcase( i==72 ); /* IMMEDIATE */
  145046. testcase( i==73 ); /* JOIN */
  145047. testcase( i==74 ); /* INSERT */
  145048. testcase( i==75 ); /* LIKE */
  145049. testcase( i==76 ); /* MATCH */
  145050. testcase( i==77 ); /* PLAN */
  145051. testcase( i==78 ); /* ANALYZE */
  145052. testcase( i==79 ); /* PRAGMA */
  145053. testcase( i==80 ); /* ABORT */
  145054. testcase( i==81 ); /* UPDATE */
  145055. testcase( i==82 ); /* VALUES */
  145056. testcase( i==83 ); /* VIRTUAL */
  145057. testcase( i==84 ); /* LIMIT */
  145058. testcase( i==85 ); /* WHEN */
  145059. testcase( i==86 ); /* NOTNULL */
  145060. testcase( i==87 ); /* NOT */
  145061. testcase( i==88 ); /* NO */
  145062. testcase( i==89 ); /* NULL */
  145063. testcase( i==90 ); /* WHERE */
  145064. testcase( i==91 ); /* RECURSIVE */
  145065. testcase( i==92 ); /* AFTER */
  145066. testcase( i==93 ); /* RENAME */
  145067. testcase( i==94 ); /* AND */
  145068. testcase( i==95 ); /* DEFAULT */
  145069. testcase( i==96 ); /* AUTOINCREMENT */
  145070. testcase( i==97 ); /* TO */
  145071. testcase( i==98 ); /* IN */
  145072. testcase( i==99 ); /* CAST */
  145073. testcase( i==100 ); /* COLUMN */
  145074. testcase( i==101 ); /* COMMIT */
  145075. testcase( i==102 ); /* CONFLICT */
  145076. testcase( i==103 ); /* CROSS */
  145077. testcase( i==104 ); /* CURRENT_TIMESTAMP */
  145078. testcase( i==105 ); /* CURRENT_TIME */
  145079. testcase( i==106 ); /* CURRENT */
  145080. testcase( i==107 ); /* PARTITION */
  145081. testcase( i==108 ); /* DEFERRED */
  145082. testcase( i==109 ); /* DISTINCT */
  145083. testcase( i==110 ); /* IS */
  145084. testcase( i==111 ); /* DROP */
  145085. testcase( i==112 ); /* PRECEDING */
  145086. testcase( i==113 ); /* FAIL */
  145087. testcase( i==114 ); /* FILTER */
  145088. testcase( i==115 ); /* REPLACE */
  145089. testcase( i==116 ); /* FOLLOWING */
  145090. testcase( i==117 ); /* FROM */
  145091. testcase( i==118 ); /* FULL */
  145092. testcase( i==119 ); /* IF */
  145093. testcase( i==120 ); /* ISNULL */
  145094. testcase( i==121 ); /* ORDER */
  145095. testcase( i==122 ); /* RESTRICT */
  145096. testcase( i==123 ); /* OTHERS */
  145097. testcase( i==124 ); /* OVER */
  145098. testcase( i==125 ); /* RIGHT */
  145099. testcase( i==126 ); /* ROLLBACK */
  145100. testcase( i==127 ); /* ROWS */
  145101. testcase( i==128 ); /* ROW */
  145102. testcase( i==129 ); /* UNBOUNDED */
  145103. testcase( i==130 ); /* UNION */
  145104. testcase( i==131 ); /* USING */
  145105. testcase( i==132 ); /* VACUUM */
  145106. testcase( i==133 ); /* VIEW */
  145107. testcase( i==134 ); /* WINDOW */
  145108. testcase( i==135 ); /* DO */
  145109. testcase( i==136 ); /* BY */
  145110. testcase( i==137 ); /* INITIALLY */
  145111. testcase( i==138 ); /* ALL */
  145112. testcase( i==139 ); /* PRIMARY */
  145113. *pType = aKWCode[i];
  145114. break;
  145115. }
  145116. }
  145117. return n;
  145118. }
  145119. SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
  145120. int id = TK_ID;
  145121. keywordCode((char*)z, n, &id);
  145122. return id;
  145123. }
  145124. #define SQLITE_N_KEYWORD 140
  145125. SQLITE_API int sqlite3_keyword_name(int i,const char **pzName,int *pnName){
  145126. if( i<0 || i>=SQLITE_N_KEYWORD ) return SQLITE_ERROR;
  145127. *pzName = zKWText + aKWOffset[i];
  145128. *pnName = aKWLen[i];
  145129. return SQLITE_OK;
  145130. }
  145131. SQLITE_API int sqlite3_keyword_count(void){ return SQLITE_N_KEYWORD; }
  145132. SQLITE_API int sqlite3_keyword_check(const char *zName, int nName){
  145133. return TK_ID!=sqlite3KeywordCode((const u8*)zName, nName);
  145134. }
  145135. /************** End of keywordhash.h *****************************************/
  145136. /************** Continuing where we left off in tokenize.c *******************/
  145137. /*
  145138. ** If X is a character that can be used in an identifier then
  145139. ** IdChar(X) will be true. Otherwise it is false.
  145140. **
  145141. ** For ASCII, any character with the high-order bit set is
  145142. ** allowed in an identifier. For 7-bit characters,
  145143. ** sqlite3IsIdChar[X] must be 1.
  145144. **
  145145. ** For EBCDIC, the rules are more complex but have the same
  145146. ** end result.
  145147. **
  145148. ** Ticket #1066. the SQL standard does not allow '$' in the
  145149. ** middle of identifiers. But many SQL implementations do.
  145150. ** SQLite will allow '$' in identifiers for compatibility.
  145151. ** But the feature is undocumented.
  145152. */
  145153. #ifdef SQLITE_ASCII
  145154. #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
  145155. #endif
  145156. #ifdef SQLITE_EBCDIC
  145157. SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
  145158. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
  145159. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 4x */
  145160. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, /* 5x */
  145161. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, /* 6x */
  145162. 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* 7x */
  145163. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, /* 8x */
  145164. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, /* 9x */
  145165. 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, /* Ax */
  145166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
  145167. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Cx */
  145168. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Dx */
  145169. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Ex */
  145170. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, /* Fx */
  145171. };
  145172. #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
  145173. #endif
  145174. /* Make the IdChar function accessible from ctime.c and alter.c */
  145175. SQLITE_PRIVATE int sqlite3IsIdChar(u8 c){ return IdChar(c); }
  145176. #ifndef SQLITE_OMIT_WINDOWFUNC
  145177. /*
  145178. ** Return the id of the next token in string (*pz). Before returning, set
  145179. ** (*pz) to point to the byte following the parsed token.
  145180. */
  145181. static int getToken(const unsigned char **pz){
  145182. const unsigned char *z = *pz;
  145183. int t; /* Token type to return */
  145184. do {
  145185. z += sqlite3GetToken(z, &t);
  145186. }while( t==TK_SPACE );
  145187. if( t==TK_ID
  145188. || t==TK_STRING
  145189. || t==TK_JOIN_KW
  145190. || t==TK_WINDOW
  145191. || t==TK_OVER
  145192. || sqlite3ParserFallback(t)==TK_ID
  145193. ){
  145194. t = TK_ID;
  145195. }
  145196. *pz = z;
  145197. return t;
  145198. }
  145199. /*
  145200. ** The following three functions are called immediately after the tokenizer
  145201. ** reads the keywords WINDOW, OVER and FILTER, respectively, to determine
  145202. ** whether the token should be treated as a keyword or an SQL identifier.
  145203. ** This cannot be handled by the usual lemon %fallback method, due to
  145204. ** the ambiguity in some constructions. e.g.
  145205. **
  145206. ** SELECT sum(x) OVER ...
  145207. **
  145208. ** In the above, "OVER" might be a keyword, or it might be an alias for the
  145209. ** sum(x) expression. If a "%fallback ID OVER" directive were added to
  145210. ** grammar, then SQLite would always treat "OVER" as an alias, making it
  145211. ** impossible to call a window-function without a FILTER clause.
  145212. **
  145213. ** WINDOW is treated as a keyword if:
  145214. **
  145215. ** * the following token is an identifier, or a keyword that can fallback
  145216. ** to being an identifier, and
  145217. ** * the token after than one is TK_AS.
  145218. **
  145219. ** OVER is a keyword if:
  145220. **
  145221. ** * the previous token was TK_RP, and
  145222. ** * the next token is either TK_LP or an identifier.
  145223. **
  145224. ** FILTER is a keyword if:
  145225. **
  145226. ** * the previous token was TK_RP, and
  145227. ** * the next token is TK_LP.
  145228. */
  145229. static int analyzeWindowKeyword(const unsigned char *z){
  145230. int t;
  145231. t = getToken(&z);
  145232. if( t!=TK_ID ) return TK_ID;
  145233. t = getToken(&z);
  145234. if( t!=TK_AS ) return TK_ID;
  145235. return TK_WINDOW;
  145236. }
  145237. static int analyzeOverKeyword(const unsigned char *z, int lastToken){
  145238. if( lastToken==TK_RP ){
  145239. int t = getToken(&z);
  145240. if( t==TK_LP || t==TK_ID ) return TK_OVER;
  145241. }
  145242. return TK_ID;
  145243. }
  145244. static int analyzeFilterKeyword(const unsigned char *z, int lastToken){
  145245. if( lastToken==TK_RP && getToken(&z)==TK_LP ){
  145246. return TK_FILTER;
  145247. }
  145248. return TK_ID;
  145249. }
  145250. #endif /* SQLITE_OMIT_WINDOWFUNC */
  145251. /*
  145252. ** Return the length (in bytes) of the token that begins at z[0].
  145253. ** Store the token type in *tokenType before returning.
  145254. */
  145255. SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
  145256. int i, c;
  145257. switch( aiClass[*z] ){ /* Switch on the character-class of the first byte
  145258. ** of the token. See the comment on the CC_ defines
  145259. ** above. */
  145260. case CC_SPACE: {
  145261. testcase( z[0]==' ' );
  145262. testcase( z[0]=='\t' );
  145263. testcase( z[0]=='\n' );
  145264. testcase( z[0]=='\f' );
  145265. testcase( z[0]=='\r' );
  145266. for(i=1; sqlite3Isspace(z[i]); i++){}
  145267. *tokenType = TK_SPACE;
  145268. return i;
  145269. }
  145270. case CC_MINUS: {
  145271. if( z[1]=='-' ){
  145272. for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
  145273. *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
  145274. return i;
  145275. }
  145276. *tokenType = TK_MINUS;
  145277. return 1;
  145278. }
  145279. case CC_LP: {
  145280. *tokenType = TK_LP;
  145281. return 1;
  145282. }
  145283. case CC_RP: {
  145284. *tokenType = TK_RP;
  145285. return 1;
  145286. }
  145287. case CC_SEMI: {
  145288. *tokenType = TK_SEMI;
  145289. return 1;
  145290. }
  145291. case CC_PLUS: {
  145292. *tokenType = TK_PLUS;
  145293. return 1;
  145294. }
  145295. case CC_STAR: {
  145296. *tokenType = TK_STAR;
  145297. return 1;
  145298. }
  145299. case CC_SLASH: {
  145300. if( z[1]!='*' || z[2]==0 ){
  145301. *tokenType = TK_SLASH;
  145302. return 1;
  145303. }
  145304. for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
  145305. if( c ) i++;
  145306. *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
  145307. return i;
  145308. }
  145309. case CC_PERCENT: {
  145310. *tokenType = TK_REM;
  145311. return 1;
  145312. }
  145313. case CC_EQ: {
  145314. *tokenType = TK_EQ;
  145315. return 1 + (z[1]=='=');
  145316. }
  145317. case CC_LT: {
  145318. if( (c=z[1])=='=' ){
  145319. *tokenType = TK_LE;
  145320. return 2;
  145321. }else if( c=='>' ){
  145322. *tokenType = TK_NE;
  145323. return 2;
  145324. }else if( c=='<' ){
  145325. *tokenType = TK_LSHIFT;
  145326. return 2;
  145327. }else{
  145328. *tokenType = TK_LT;
  145329. return 1;
  145330. }
  145331. }
  145332. case CC_GT: {
  145333. if( (c=z[1])=='=' ){
  145334. *tokenType = TK_GE;
  145335. return 2;
  145336. }else if( c=='>' ){
  145337. *tokenType = TK_RSHIFT;
  145338. return 2;
  145339. }else{
  145340. *tokenType = TK_GT;
  145341. return 1;
  145342. }
  145343. }
  145344. case CC_BANG: {
  145345. if( z[1]!='=' ){
  145346. *tokenType = TK_ILLEGAL;
  145347. return 1;
  145348. }else{
  145349. *tokenType = TK_NE;
  145350. return 2;
  145351. }
  145352. }
  145353. case CC_PIPE: {
  145354. if( z[1]!='|' ){
  145355. *tokenType = TK_BITOR;
  145356. return 1;
  145357. }else{
  145358. *tokenType = TK_CONCAT;
  145359. return 2;
  145360. }
  145361. }
  145362. case CC_COMMA: {
  145363. *tokenType = TK_COMMA;
  145364. return 1;
  145365. }
  145366. case CC_AND: {
  145367. *tokenType = TK_BITAND;
  145368. return 1;
  145369. }
  145370. case CC_TILDA: {
  145371. *tokenType = TK_BITNOT;
  145372. return 1;
  145373. }
  145374. case CC_QUOTE: {
  145375. int delim = z[0];
  145376. testcase( delim=='`' );
  145377. testcase( delim=='\'' );
  145378. testcase( delim=='"' );
  145379. for(i=1; (c=z[i])!=0; i++){
  145380. if( c==delim ){
  145381. if( z[i+1]==delim ){
  145382. i++;
  145383. }else{
  145384. break;
  145385. }
  145386. }
  145387. }
  145388. if( c=='\'' ){
  145389. *tokenType = TK_STRING;
  145390. return i+1;
  145391. }else if( c!=0 ){
  145392. *tokenType = TK_ID;
  145393. return i+1;
  145394. }else{
  145395. *tokenType = TK_ILLEGAL;
  145396. return i;
  145397. }
  145398. }
  145399. case CC_DOT: {
  145400. #ifndef SQLITE_OMIT_FLOATING_POINT
  145401. if( !sqlite3Isdigit(z[1]) )
  145402. #endif
  145403. {
  145404. *tokenType = TK_DOT;
  145405. return 1;
  145406. }
  145407. /* If the next character is a digit, this is a floating point
  145408. ** number that begins with ".". Fall thru into the next case */
  145409. }
  145410. case CC_DIGIT: {
  145411. testcase( z[0]=='0' ); testcase( z[0]=='1' ); testcase( z[0]=='2' );
  145412. testcase( z[0]=='3' ); testcase( z[0]=='4' ); testcase( z[0]=='5' );
  145413. testcase( z[0]=='6' ); testcase( z[0]=='7' ); testcase( z[0]=='8' );
  145414. testcase( z[0]=='9' );
  145415. *tokenType = TK_INTEGER;
  145416. #ifndef SQLITE_OMIT_HEX_INTEGER
  145417. if( z[0]=='0' && (z[1]=='x' || z[1]=='X') && sqlite3Isxdigit(z[2]) ){
  145418. for(i=3; sqlite3Isxdigit(z[i]); i++){}
  145419. return i;
  145420. }
  145421. #endif
  145422. for(i=0; sqlite3Isdigit(z[i]); i++){}
  145423. #ifndef SQLITE_OMIT_FLOATING_POINT
  145424. if( z[i]=='.' ){
  145425. i++;
  145426. while( sqlite3Isdigit(z[i]) ){ i++; }
  145427. *tokenType = TK_FLOAT;
  145428. }
  145429. if( (z[i]=='e' || z[i]=='E') &&
  145430. ( sqlite3Isdigit(z[i+1])
  145431. || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
  145432. )
  145433. ){
  145434. i += 2;
  145435. while( sqlite3Isdigit(z[i]) ){ i++; }
  145436. *tokenType = TK_FLOAT;
  145437. }
  145438. #endif
  145439. while( IdChar(z[i]) ){
  145440. *tokenType = TK_ILLEGAL;
  145441. i++;
  145442. }
  145443. return i;
  145444. }
  145445. case CC_QUOTE2: {
  145446. for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
  145447. *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
  145448. return i;
  145449. }
  145450. case CC_VARNUM: {
  145451. *tokenType = TK_VARIABLE;
  145452. for(i=1; sqlite3Isdigit(z[i]); i++){}
  145453. return i;
  145454. }
  145455. case CC_DOLLAR:
  145456. case CC_VARALPHA: {
  145457. int n = 0;
  145458. testcase( z[0]=='$' ); testcase( z[0]=='@' );
  145459. testcase( z[0]==':' ); testcase( z[0]=='#' );
  145460. *tokenType = TK_VARIABLE;
  145461. for(i=1; (c=z[i])!=0; i++){
  145462. if( IdChar(c) ){
  145463. n++;
  145464. #ifndef SQLITE_OMIT_TCL_VARIABLE
  145465. }else if( c=='(' && n>0 ){
  145466. do{
  145467. i++;
  145468. }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
  145469. if( c==')' ){
  145470. i++;
  145471. }else{
  145472. *tokenType = TK_ILLEGAL;
  145473. }
  145474. break;
  145475. }else if( c==':' && z[i+1]==':' ){
  145476. i++;
  145477. #endif
  145478. }else{
  145479. break;
  145480. }
  145481. }
  145482. if( n==0 ) *tokenType = TK_ILLEGAL;
  145483. return i;
  145484. }
  145485. case CC_KYWD: {
  145486. for(i=1; aiClass[z[i]]<=CC_KYWD; i++){}
  145487. if( IdChar(z[i]) ){
  145488. /* This token started out using characters that can appear in keywords,
  145489. ** but z[i] is a character not allowed within keywords, so this must
  145490. ** be an identifier instead */
  145491. i++;
  145492. break;
  145493. }
  145494. *tokenType = TK_ID;
  145495. return keywordCode((char*)z, i, tokenType);
  145496. }
  145497. case CC_X: {
  145498. #ifndef SQLITE_OMIT_BLOB_LITERAL
  145499. testcase( z[0]=='x' ); testcase( z[0]=='X' );
  145500. if( z[1]=='\'' ){
  145501. *tokenType = TK_BLOB;
  145502. for(i=2; sqlite3Isxdigit(z[i]); i++){}
  145503. if( z[i]!='\'' || i%2 ){
  145504. *tokenType = TK_ILLEGAL;
  145505. while( z[i] && z[i]!='\'' ){ i++; }
  145506. }
  145507. if( z[i] ) i++;
  145508. return i;
  145509. }
  145510. #endif
  145511. /* If it is not a BLOB literal, then it must be an ID, since no
  145512. ** SQL keywords start with the letter 'x'. Fall through */
  145513. }
  145514. case CC_ID: {
  145515. i = 1;
  145516. break;
  145517. }
  145518. case CC_NUL: {
  145519. *tokenType = TK_ILLEGAL;
  145520. return 0;
  145521. }
  145522. default: {
  145523. *tokenType = TK_ILLEGAL;
  145524. return 1;
  145525. }
  145526. }
  145527. while( IdChar(z[i]) ){ i++; }
  145528. *tokenType = TK_ID;
  145529. return i;
  145530. }
  145531. /*
  145532. ** Run the parser on the given SQL string. The parser structure is
  145533. ** passed in. An SQLITE_ status code is returned. If an error occurs
  145534. ** then an and attempt is made to write an error message into
  145535. ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
  145536. ** error message.
  145537. */
  145538. SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
  145539. int nErr = 0; /* Number of errors encountered */
  145540. void *pEngine; /* The LEMON-generated LALR(1) parser */
  145541. int n = 0; /* Length of the next token token */
  145542. int tokenType; /* type of the next token */
  145543. int lastTokenParsed = -1; /* type of the previous token */
  145544. sqlite3 *db = pParse->db; /* The database connection */
  145545. int mxSqlLen; /* Max length of an SQL string */
  145546. #ifdef sqlite3Parser_ENGINEALWAYSONSTACK
  145547. yyParser sEngine; /* Space to hold the Lemon-generated Parser object */
  145548. #endif
  145549. VVA_ONLY( u8 startedWithOom = db->mallocFailed );
  145550. assert( zSql!=0 );
  145551. mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
  145552. if( db->nVdbeActive==0 ){
  145553. db->u1.isInterrupted = 0;
  145554. }
  145555. pParse->rc = SQLITE_OK;
  145556. pParse->zTail = zSql;
  145557. assert( pzErrMsg!=0 );
  145558. #ifdef SQLITE_DEBUG
  145559. if( db->flags & SQLITE_ParserTrace ){
  145560. printf("parser: [[[%s]]]\n", zSql);
  145561. sqlite3ParserTrace(stdout, "parser: ");
  145562. }else{
  145563. sqlite3ParserTrace(0, 0);
  145564. }
  145565. #endif
  145566. #ifdef sqlite3Parser_ENGINEALWAYSONSTACK
  145567. pEngine = &sEngine;
  145568. sqlite3ParserInit(pEngine, pParse);
  145569. #else
  145570. pEngine = sqlite3ParserAlloc(sqlite3Malloc, pParse);
  145571. if( pEngine==0 ){
  145572. sqlite3OomFault(db);
  145573. return SQLITE_NOMEM_BKPT;
  145574. }
  145575. #endif
  145576. assert( pParse->pNewTable==0 );
  145577. assert( pParse->pNewTrigger==0 );
  145578. assert( pParse->nVar==0 );
  145579. assert( pParse->pVList==0 );
  145580. pParse->pParentParse = db->pParse;
  145581. db->pParse = pParse;
  145582. while( 1 ){
  145583. n = sqlite3GetToken((u8*)zSql, &tokenType);
  145584. mxSqlLen -= n;
  145585. if( mxSqlLen<0 ){
  145586. pParse->rc = SQLITE_TOOBIG;
  145587. break;
  145588. }
  145589. #ifndef SQLITE_OMIT_WINDOWFUNC
  145590. if( tokenType>=TK_WINDOW ){
  145591. assert( tokenType==TK_SPACE || tokenType==TK_OVER || tokenType==TK_FILTER
  145592. || tokenType==TK_ILLEGAL || tokenType==TK_WINDOW
  145593. );
  145594. #else
  145595. if( tokenType>=TK_SPACE ){
  145596. assert( tokenType==TK_SPACE || tokenType==TK_ILLEGAL );
  145597. #endif /* SQLITE_OMIT_WINDOWFUNC */
  145598. if( db->u1.isInterrupted ){
  145599. pParse->rc = SQLITE_INTERRUPT;
  145600. break;
  145601. }
  145602. if( tokenType==TK_SPACE ){
  145603. zSql += n;
  145604. continue;
  145605. }
  145606. if( zSql[0]==0 ){
  145607. /* Upon reaching the end of input, call the parser two more times
  145608. ** with tokens TK_SEMI and 0, in that order. */
  145609. if( lastTokenParsed==TK_SEMI ){
  145610. tokenType = 0;
  145611. }else if( lastTokenParsed==0 ){
  145612. break;
  145613. }else{
  145614. tokenType = TK_SEMI;
  145615. }
  145616. n = 0;
  145617. #ifndef SQLITE_OMIT_WINDOWFUNC
  145618. }else if( tokenType==TK_WINDOW ){
  145619. assert( n==6 );
  145620. tokenType = analyzeWindowKeyword((const u8*)&zSql[6]);
  145621. }else if( tokenType==TK_OVER ){
  145622. assert( n==4 );
  145623. tokenType = analyzeOverKeyword((const u8*)&zSql[4], lastTokenParsed);
  145624. }else if( tokenType==TK_FILTER ){
  145625. assert( n==6 );
  145626. tokenType = analyzeFilterKeyword((const u8*)&zSql[6], lastTokenParsed);
  145627. #endif /* SQLITE_OMIT_WINDOWFUNC */
  145628. }else{
  145629. sqlite3ErrorMsg(pParse, "unrecognized token: \"%.*s\"", n, zSql);
  145630. break;
  145631. }
  145632. }
  145633. pParse->sLastToken.z = zSql;
  145634. pParse->sLastToken.n = n;
  145635. sqlite3Parser(pEngine, tokenType, pParse->sLastToken);
  145636. lastTokenParsed = tokenType;
  145637. zSql += n;
  145638. assert( db->mallocFailed==0 || pParse->rc!=SQLITE_OK || startedWithOom );
  145639. if( pParse->rc!=SQLITE_OK ) break;
  145640. }
  145641. assert( nErr==0 );
  145642. #ifdef YYTRACKMAXSTACKDEPTH
  145643. sqlite3_mutex_enter(sqlite3MallocMutex());
  145644. sqlite3StatusHighwater(SQLITE_STATUS_PARSER_STACK,
  145645. sqlite3ParserStackPeak(pEngine)
  145646. );
  145647. sqlite3_mutex_leave(sqlite3MallocMutex());
  145648. #endif /* YYDEBUG */
  145649. #ifdef sqlite3Parser_ENGINEALWAYSONSTACK
  145650. sqlite3ParserFinalize(pEngine);
  145651. #else
  145652. sqlite3ParserFree(pEngine, sqlite3_free);
  145653. #endif
  145654. if( db->mallocFailed ){
  145655. pParse->rc = SQLITE_NOMEM_BKPT;
  145656. }
  145657. if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
  145658. pParse->zErrMsg = sqlite3MPrintf(db, "%s", sqlite3ErrStr(pParse->rc));
  145659. }
  145660. assert( pzErrMsg!=0 );
  145661. if( pParse->zErrMsg ){
  145662. *pzErrMsg = pParse->zErrMsg;
  145663. sqlite3_log(pParse->rc, "%s in \"%s\"",
  145664. *pzErrMsg, pParse->zTail);
  145665. pParse->zErrMsg = 0;
  145666. nErr++;
  145667. }
  145668. pParse->zTail = zSql;
  145669. if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
  145670. sqlite3VdbeDelete(pParse->pVdbe);
  145671. pParse->pVdbe = 0;
  145672. }
  145673. #ifndef SQLITE_OMIT_SHARED_CACHE
  145674. if( pParse->nested==0 ){
  145675. sqlite3DbFree(db, pParse->aTableLock);
  145676. pParse->aTableLock = 0;
  145677. pParse->nTableLock = 0;
  145678. }
  145679. #endif
  145680. #ifndef SQLITE_OMIT_VIRTUALTABLE
  145681. sqlite3_free(pParse->apVtabLock);
  145682. #endif
  145683. if( !IN_SPECIAL_PARSE ){
  145684. /* If the pParse->declareVtab flag is set, do not delete any table
  145685. ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
  145686. ** will take responsibility for freeing the Table structure.
  145687. */
  145688. sqlite3DeleteTable(db, pParse->pNewTable);
  145689. }
  145690. if( !IN_RENAME_OBJECT ){
  145691. sqlite3DeleteTrigger(db, pParse->pNewTrigger);
  145692. }
  145693. if( pParse->pWithToFree ) sqlite3WithDelete(db, pParse->pWithToFree);
  145694. sqlite3DbFree(db, pParse->pVList);
  145695. while( pParse->pAinc ){
  145696. AutoincInfo *p = pParse->pAinc;
  145697. pParse->pAinc = p->pNext;
  145698. sqlite3DbFreeNN(db, p);
  145699. }
  145700. while( pParse->pZombieTab ){
  145701. Table *p = pParse->pZombieTab;
  145702. pParse->pZombieTab = p->pNextZombie;
  145703. sqlite3DeleteTable(db, p);
  145704. }
  145705. db->pParse = pParse->pParentParse;
  145706. pParse->pParentParse = 0;
  145707. assert( nErr==0 || pParse->rc!=SQLITE_OK );
  145708. return nErr;
  145709. }
  145710. #ifdef SQLITE_ENABLE_NORMALIZE
  145711. /*
  145712. ** Insert a single space character into pStr if the current string
  145713. ** ends with an identifier
  145714. */
  145715. static void addSpaceSeparator(sqlite3_str *pStr){
  145716. if( pStr->nChar && sqlite3IsIdChar(pStr->zText[pStr->nChar-1]) ){
  145717. sqlite3_str_append(pStr, " ", 1);
  145718. }
  145719. }
  145720. /*
  145721. ** Compute a normalization of the SQL given by zSql[0..nSql-1]. Return
  145722. ** the normalization in space obtained from sqlite3DbMalloc(). Or return
  145723. ** NULL if anything goes wrong or if zSql is NULL.
  145724. */
  145725. SQLITE_PRIVATE char *sqlite3Normalize(
  145726. Vdbe *pVdbe, /* VM being reprepared */
  145727. const char *zSql /* The original SQL string */
  145728. ){
  145729. sqlite3 *db; /* The database connection */
  145730. int i; /* Next unread byte of zSql[] */
  145731. int n; /* length of current token */
  145732. int tokenType; /* type of current token */
  145733. int prevType = 0; /* Previous non-whitespace token */
  145734. int nParen; /* Number of nested levels of parentheses */
  145735. int iStartIN; /* Start of RHS of IN operator in z[] */
  145736. int nParenAtIN; /* Value of nParent at start of RHS of IN operator */
  145737. int j; /* Bytes of normalized SQL generated so far */
  145738. sqlite3_str *pStr; /* The normalized SQL string under construction */
  145739. db = sqlite3VdbeDb(pVdbe);
  145740. tokenType = -1;
  145741. nParen = iStartIN = nParenAtIN = 0;
  145742. pStr = sqlite3_str_new(db);
  145743. assert( pStr!=0 ); /* sqlite3_str_new() never returns NULL */
  145744. for(i=0; zSql[i] && pStr->accError==0; i+=n){
  145745. if( tokenType!=TK_SPACE ){
  145746. prevType = tokenType;
  145747. }
  145748. n = sqlite3GetToken((unsigned char*)zSql+i, &tokenType);
  145749. if( NEVER(n<=0) ) break;
  145750. switch( tokenType ){
  145751. case TK_SPACE: {
  145752. break;
  145753. }
  145754. case TK_NULL: {
  145755. if( prevType==TK_IS || prevType==TK_NOT ){
  145756. sqlite3_str_append(pStr, " NULL", 5);
  145757. break;
  145758. }
  145759. /* Fall through */
  145760. }
  145761. case TK_STRING:
  145762. case TK_INTEGER:
  145763. case TK_FLOAT:
  145764. case TK_VARIABLE:
  145765. case TK_BLOB: {
  145766. sqlite3_str_append(pStr, "?", 1);
  145767. break;
  145768. }
  145769. case TK_LP: {
  145770. nParen++;
  145771. if( prevType==TK_IN ){
  145772. iStartIN = pStr->nChar;
  145773. nParenAtIN = nParen;
  145774. }
  145775. sqlite3_str_append(pStr, "(", 1);
  145776. break;
  145777. }
  145778. case TK_RP: {
  145779. if( iStartIN>0 && nParen==nParenAtIN ){
  145780. assert( pStr->nChar>=iStartIN );
  145781. pStr->nChar = iStartIN+1;
  145782. sqlite3_str_append(pStr, "?,?,?", 5);
  145783. iStartIN = 0;
  145784. }
  145785. nParen--;
  145786. sqlite3_str_append(pStr, ")", 1);
  145787. break;
  145788. }
  145789. case TK_ID: {
  145790. iStartIN = 0;
  145791. j = pStr->nChar;
  145792. if( sqlite3Isquote(zSql[i]) ){
  145793. char *zId = sqlite3DbStrNDup(db, zSql+i, n);
  145794. int nId;
  145795. int eType = 0;
  145796. if( zId==0 ) break;
  145797. sqlite3Dequote(zId);
  145798. if( zSql[i]=='"' && sqlite3VdbeUsesDoubleQuotedString(pVdbe, zId) ){
  145799. sqlite3_str_append(pStr, "?", 1);
  145800. sqlite3DbFree(db, zId);
  145801. break;
  145802. }
  145803. nId = sqlite3Strlen30(zId);
  145804. if( sqlite3GetToken((u8*)zId, &eType)==nId && eType==TK_ID ){
  145805. addSpaceSeparator(pStr);
  145806. sqlite3_str_append(pStr, zId, nId);
  145807. }else{
  145808. sqlite3_str_appendf(pStr, "\"%w\"", zId);
  145809. }
  145810. sqlite3DbFree(db, zId);
  145811. }else{
  145812. addSpaceSeparator(pStr);
  145813. sqlite3_str_append(pStr, zSql+i, n);
  145814. }
  145815. while( j<pStr->nChar ){
  145816. pStr->zText[j] = sqlite3Tolower(pStr->zText[j]);
  145817. j++;
  145818. }
  145819. break;
  145820. }
  145821. case TK_SELECT: {
  145822. iStartIN = 0;
  145823. /* fall through */
  145824. }
  145825. default: {
  145826. if( sqlite3IsIdChar(zSql[i]) ) addSpaceSeparator(pStr);
  145827. j = pStr->nChar;
  145828. sqlite3_str_append(pStr, zSql+i, n);
  145829. while( j<pStr->nChar ){
  145830. pStr->zText[j] = sqlite3Toupper(pStr->zText[j]);
  145831. j++;
  145832. }
  145833. break;
  145834. }
  145835. }
  145836. }
  145837. if( tokenType!=TK_SEMI ) sqlite3_str_append(pStr, ";", 1);
  145838. return sqlite3_str_finish(pStr);
  145839. }
  145840. #endif /* SQLITE_ENABLE_NORMALIZE */
  145841. /************** End of tokenize.c ********************************************/
  145842. /************** Begin file complete.c ****************************************/
  145843. /*
  145844. ** 2001 September 15
  145845. **
  145846. ** The author disclaims copyright to this source code. In place of
  145847. ** a legal notice, here is a blessing:
  145848. **
  145849. ** May you do good and not evil.
  145850. ** May you find forgiveness for yourself and forgive others.
  145851. ** May you share freely, never taking more than you give.
  145852. **
  145853. *************************************************************************
  145854. ** An tokenizer for SQL
  145855. **
  145856. ** This file contains C code that implements the sqlite3_complete() API.
  145857. ** This code used to be part of the tokenizer.c source file. But by
  145858. ** separating it out, the code will be automatically omitted from
  145859. ** static links that do not use it.
  145860. */
  145861. /* #include "sqliteInt.h" */
  145862. #ifndef SQLITE_OMIT_COMPLETE
  145863. /*
  145864. ** This is defined in tokenize.c. We just have to import the definition.
  145865. */
  145866. #ifndef SQLITE_AMALGAMATION
  145867. #ifdef SQLITE_ASCII
  145868. #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
  145869. #endif
  145870. #ifdef SQLITE_EBCDIC
  145871. SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
  145872. #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
  145873. #endif
  145874. #endif /* SQLITE_AMALGAMATION */
  145875. /*
  145876. ** Token types used by the sqlite3_complete() routine. See the header
  145877. ** comments on that procedure for additional information.
  145878. */
  145879. #define tkSEMI 0
  145880. #define tkWS 1
  145881. #define tkOTHER 2
  145882. #ifndef SQLITE_OMIT_TRIGGER
  145883. #define tkEXPLAIN 3
  145884. #define tkCREATE 4
  145885. #define tkTEMP 5
  145886. #define tkTRIGGER 6
  145887. #define tkEND 7
  145888. #endif
  145889. /*
  145890. ** Return TRUE if the given SQL string ends in a semicolon.
  145891. **
  145892. ** Special handling is require for CREATE TRIGGER statements.
  145893. ** Whenever the CREATE TRIGGER keywords are seen, the statement
  145894. ** must end with ";END;".
  145895. **
  145896. ** This implementation uses a state machine with 8 states:
  145897. **
  145898. ** (0) INVALID We have not yet seen a non-whitespace character.
  145899. **
  145900. ** (1) START At the beginning or end of an SQL statement. This routine
  145901. ** returns 1 if it ends in the START state and 0 if it ends
  145902. ** in any other state.
  145903. **
  145904. ** (2) NORMAL We are in the middle of statement which ends with a single
  145905. ** semicolon.
  145906. **
  145907. ** (3) EXPLAIN The keyword EXPLAIN has been seen at the beginning of
  145908. ** a statement.
  145909. **
  145910. ** (4) CREATE The keyword CREATE has been seen at the beginning of a
  145911. ** statement, possibly preceded by EXPLAIN and/or followed by
  145912. ** TEMP or TEMPORARY
  145913. **
  145914. ** (5) TRIGGER We are in the middle of a trigger definition that must be
  145915. ** ended by a semicolon, the keyword END, and another semicolon.
  145916. **
  145917. ** (6) SEMI We've seen the first semicolon in the ";END;" that occurs at
  145918. ** the end of a trigger definition.
  145919. **
  145920. ** (7) END We've seen the ";END" of the ";END;" that occurs at the end
  145921. ** of a trigger definition.
  145922. **
  145923. ** Transitions between states above are determined by tokens extracted
  145924. ** from the input. The following tokens are significant:
  145925. **
  145926. ** (0) tkSEMI A semicolon.
  145927. ** (1) tkWS Whitespace.
  145928. ** (2) tkOTHER Any other SQL token.
  145929. ** (3) tkEXPLAIN The "explain" keyword.
  145930. ** (4) tkCREATE The "create" keyword.
  145931. ** (5) tkTEMP The "temp" or "temporary" keyword.
  145932. ** (6) tkTRIGGER The "trigger" keyword.
  145933. ** (7) tkEND The "end" keyword.
  145934. **
  145935. ** Whitespace never causes a state transition and is always ignored.
  145936. ** This means that a SQL string of all whitespace is invalid.
  145937. **
  145938. ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
  145939. ** to recognize the end of a trigger can be omitted. All we have to do
  145940. ** is look for a semicolon that is not part of an string or comment.
  145941. */
  145942. SQLITE_API int sqlite3_complete(const char *zSql){
  145943. u8 state = 0; /* Current state, using numbers defined in header comment */
  145944. u8 token; /* Value of the next token */
  145945. #ifndef SQLITE_OMIT_TRIGGER
  145946. /* A complex statement machine used to detect the end of a CREATE TRIGGER
  145947. ** statement. This is the normal case.
  145948. */
  145949. static const u8 trans[8][8] = {
  145950. /* Token: */
  145951. /* State: ** SEMI WS OTHER EXPLAIN CREATE TEMP TRIGGER END */
  145952. /* 0 INVALID: */ { 1, 0, 2, 3, 4, 2, 2, 2, },
  145953. /* 1 START: */ { 1, 1, 2, 3, 4, 2, 2, 2, },
  145954. /* 2 NORMAL: */ { 1, 2, 2, 2, 2, 2, 2, 2, },
  145955. /* 3 EXPLAIN: */ { 1, 3, 3, 2, 4, 2, 2, 2, },
  145956. /* 4 CREATE: */ { 1, 4, 2, 2, 2, 4, 5, 2, },
  145957. /* 5 TRIGGER: */ { 6, 5, 5, 5, 5, 5, 5, 5, },
  145958. /* 6 SEMI: */ { 6, 6, 5, 5, 5, 5, 5, 7, },
  145959. /* 7 END: */ { 1, 7, 5, 5, 5, 5, 5, 5, },
  145960. };
  145961. #else
  145962. /* If triggers are not supported by this compile then the statement machine
  145963. ** used to detect the end of a statement is much simpler
  145964. */
  145965. static const u8 trans[3][3] = {
  145966. /* Token: */
  145967. /* State: ** SEMI WS OTHER */
  145968. /* 0 INVALID: */ { 1, 0, 2, },
  145969. /* 1 START: */ { 1, 1, 2, },
  145970. /* 2 NORMAL: */ { 1, 2, 2, },
  145971. };
  145972. #endif /* SQLITE_OMIT_TRIGGER */
  145973. #ifdef SQLITE_ENABLE_API_ARMOR
  145974. if( zSql==0 ){
  145975. (void)SQLITE_MISUSE_BKPT;
  145976. return 0;
  145977. }
  145978. #endif
  145979. while( *zSql ){
  145980. switch( *zSql ){
  145981. case ';': { /* A semicolon */
  145982. token = tkSEMI;
  145983. break;
  145984. }
  145985. case ' ':
  145986. case '\r':
  145987. case '\t':
  145988. case '\n':
  145989. case '\f': { /* White space is ignored */
  145990. token = tkWS;
  145991. break;
  145992. }
  145993. case '/': { /* C-style comments */
  145994. if( zSql[1]!='*' ){
  145995. token = tkOTHER;
  145996. break;
  145997. }
  145998. zSql += 2;
  145999. while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
  146000. if( zSql[0]==0 ) return 0;
  146001. zSql++;
  146002. token = tkWS;
  146003. break;
  146004. }
  146005. case '-': { /* SQL-style comments from "--" to end of line */
  146006. if( zSql[1]!='-' ){
  146007. token = tkOTHER;
  146008. break;
  146009. }
  146010. while( *zSql && *zSql!='\n' ){ zSql++; }
  146011. if( *zSql==0 ) return state==1;
  146012. token = tkWS;
  146013. break;
  146014. }
  146015. case '[': { /* Microsoft-style identifiers in [...] */
  146016. zSql++;
  146017. while( *zSql && *zSql!=']' ){ zSql++; }
  146018. if( *zSql==0 ) return 0;
  146019. token = tkOTHER;
  146020. break;
  146021. }
  146022. case '`': /* Grave-accent quoted symbols used by MySQL */
  146023. case '"': /* single- and double-quoted strings */
  146024. case '\'': {
  146025. int c = *zSql;
  146026. zSql++;
  146027. while( *zSql && *zSql!=c ){ zSql++; }
  146028. if( *zSql==0 ) return 0;
  146029. token = tkOTHER;
  146030. break;
  146031. }
  146032. default: {
  146033. #ifdef SQLITE_EBCDIC
  146034. unsigned char c;
  146035. #endif
  146036. if( IdChar((u8)*zSql) ){
  146037. /* Keywords and unquoted identifiers */
  146038. int nId;
  146039. for(nId=1; IdChar(zSql[nId]); nId++){}
  146040. #ifdef SQLITE_OMIT_TRIGGER
  146041. token = tkOTHER;
  146042. #else
  146043. switch( *zSql ){
  146044. case 'c': case 'C': {
  146045. if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
  146046. token = tkCREATE;
  146047. }else{
  146048. token = tkOTHER;
  146049. }
  146050. break;
  146051. }
  146052. case 't': case 'T': {
  146053. if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
  146054. token = tkTRIGGER;
  146055. }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
  146056. token = tkTEMP;
  146057. }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
  146058. token = tkTEMP;
  146059. }else{
  146060. token = tkOTHER;
  146061. }
  146062. break;
  146063. }
  146064. case 'e': case 'E': {
  146065. if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
  146066. token = tkEND;
  146067. }else
  146068. #ifndef SQLITE_OMIT_EXPLAIN
  146069. if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
  146070. token = tkEXPLAIN;
  146071. }else
  146072. #endif
  146073. {
  146074. token = tkOTHER;
  146075. }
  146076. break;
  146077. }
  146078. default: {
  146079. token = tkOTHER;
  146080. break;
  146081. }
  146082. }
  146083. #endif /* SQLITE_OMIT_TRIGGER */
  146084. zSql += nId-1;
  146085. }else{
  146086. /* Operators and special symbols */
  146087. token = tkOTHER;
  146088. }
  146089. break;
  146090. }
  146091. }
  146092. state = trans[state][token];
  146093. zSql++;
  146094. }
  146095. return state==1;
  146096. }
  146097. #ifndef SQLITE_OMIT_UTF16
  146098. /*
  146099. ** This routine is the same as the sqlite3_complete() routine described
  146100. ** above, except that the parameter is required to be UTF-16 encoded, not
  146101. ** UTF-8.
  146102. */
  146103. SQLITE_API int sqlite3_complete16(const void *zSql){
  146104. sqlite3_value *pVal;
  146105. char const *zSql8;
  146106. int rc;
  146107. #ifndef SQLITE_OMIT_AUTOINIT
  146108. rc = sqlite3_initialize();
  146109. if( rc ) return rc;
  146110. #endif
  146111. pVal = sqlite3ValueNew(0);
  146112. sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  146113. zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
  146114. if( zSql8 ){
  146115. rc = sqlite3_complete(zSql8);
  146116. }else{
  146117. rc = SQLITE_NOMEM_BKPT;
  146118. }
  146119. sqlite3ValueFree(pVal);
  146120. return rc & 0xff;
  146121. }
  146122. #endif /* SQLITE_OMIT_UTF16 */
  146123. #endif /* SQLITE_OMIT_COMPLETE */
  146124. /************** End of complete.c ********************************************/
  146125. /************** Begin file main.c ********************************************/
  146126. /*
  146127. ** 2001 September 15
  146128. **
  146129. ** The author disclaims copyright to this source code. In place of
  146130. ** a legal notice, here is a blessing:
  146131. **
  146132. ** May you do good and not evil.
  146133. ** May you find forgiveness for yourself and forgive others.
  146134. ** May you share freely, never taking more than you give.
  146135. **
  146136. *************************************************************************
  146137. ** Main file for the SQLite library. The routines in this file
  146138. ** implement the programmer interface to the library. Routines in
  146139. ** other files are for internal use by SQLite and should not be
  146140. ** accessed by users of the library.
  146141. */
  146142. /* #include "sqliteInt.h" */
  146143. #ifdef SQLITE_ENABLE_FTS3
  146144. /************** Include fts3.h in the middle of main.c ***********************/
  146145. /************** Begin file fts3.h ********************************************/
  146146. /*
  146147. ** 2006 Oct 10
  146148. **
  146149. ** The author disclaims copyright to this source code. In place of
  146150. ** a legal notice, here is a blessing:
  146151. **
  146152. ** May you do good and not evil.
  146153. ** May you find forgiveness for yourself and forgive others.
  146154. ** May you share freely, never taking more than you give.
  146155. **
  146156. ******************************************************************************
  146157. **
  146158. ** This header file is used by programs that want to link against the
  146159. ** FTS3 library. All it does is declare the sqlite3Fts3Init() interface.
  146160. */
  146161. /* #include "sqlite3.h" */
  146162. #if 0
  146163. extern "C" {
  146164. #endif /* __cplusplus */
  146165. SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
  146166. #if 0
  146167. } /* extern "C" */
  146168. #endif /* __cplusplus */
  146169. /************** End of fts3.h ************************************************/
  146170. /************** Continuing where we left off in main.c ***********************/
  146171. #endif
  146172. #ifdef SQLITE_ENABLE_RTREE
  146173. /************** Include rtree.h in the middle of main.c **********************/
  146174. /************** Begin file rtree.h *******************************************/
  146175. /*
  146176. ** 2008 May 26
  146177. **
  146178. ** The author disclaims copyright to this source code. In place of
  146179. ** a legal notice, here is a blessing:
  146180. **
  146181. ** May you do good and not evil.
  146182. ** May you find forgiveness for yourself and forgive others.
  146183. ** May you share freely, never taking more than you give.
  146184. **
  146185. ******************************************************************************
  146186. **
  146187. ** This header file is used by programs that want to link against the
  146188. ** RTREE library. All it does is declare the sqlite3RtreeInit() interface.
  146189. */
  146190. /* #include "sqlite3.h" */
  146191. #ifdef SQLITE_OMIT_VIRTUALTABLE
  146192. # undef SQLITE_ENABLE_RTREE
  146193. #endif
  146194. #if 0
  146195. extern "C" {
  146196. #endif /* __cplusplus */
  146197. SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
  146198. #if 0
  146199. } /* extern "C" */
  146200. #endif /* __cplusplus */
  146201. /************** End of rtree.h ***********************************************/
  146202. /************** Continuing where we left off in main.c ***********************/
  146203. #endif
  146204. #if defined(SQLITE_ENABLE_ICU) || defined(SQLITE_ENABLE_ICU_COLLATIONS)
  146205. /************** Include sqliteicu.h in the middle of main.c ******************/
  146206. /************** Begin file sqliteicu.h ***************************************/
  146207. /*
  146208. ** 2008 May 26
  146209. **
  146210. ** The author disclaims copyright to this source code. In place of
  146211. ** a legal notice, here is a blessing:
  146212. **
  146213. ** May you do good and not evil.
  146214. ** May you find forgiveness for yourself and forgive others.
  146215. ** May you share freely, never taking more than you give.
  146216. **
  146217. ******************************************************************************
  146218. **
  146219. ** This header file is used by programs that want to link against the
  146220. ** ICU extension. All it does is declare the sqlite3IcuInit() interface.
  146221. */
  146222. /* #include "sqlite3.h" */
  146223. #if 0
  146224. extern "C" {
  146225. #endif /* __cplusplus */
  146226. SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
  146227. #if 0
  146228. } /* extern "C" */
  146229. #endif /* __cplusplus */
  146230. /************** End of sqliteicu.h *******************************************/
  146231. /************** Continuing where we left off in main.c ***********************/
  146232. #endif
  146233. #ifdef SQLITE_ENABLE_JSON1
  146234. SQLITE_PRIVATE int sqlite3Json1Init(sqlite3*);
  146235. #endif
  146236. #ifdef SQLITE_ENABLE_STMTVTAB
  146237. SQLITE_PRIVATE int sqlite3StmtVtabInit(sqlite3*);
  146238. #endif
  146239. #ifdef SQLITE_ENABLE_FTS5
  146240. SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3*);
  146241. #endif
  146242. #ifndef SQLITE_AMALGAMATION
  146243. /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
  146244. ** contains the text of SQLITE_VERSION macro.
  146245. */
  146246. SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
  146247. #endif
  146248. /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
  146249. ** a pointer to the to the sqlite3_version[] string constant.
  146250. */
  146251. SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
  146252. /* IMPLEMENTATION-OF: R-25063-23286 The sqlite3_sourceid() function returns a
  146253. ** pointer to a string constant whose value is the same as the
  146254. ** SQLITE_SOURCE_ID C preprocessor macro. Except if SQLite is built using
  146255. ** an edited copy of the amalgamation, then the last four characters of
  146256. ** the hash might be different from SQLITE_SOURCE_ID.
  146257. */
  146258. /* SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; } */
  146259. /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
  146260. ** returns an integer equal to SQLITE_VERSION_NUMBER.
  146261. */
  146262. SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
  146263. /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
  146264. ** zero if and only if SQLite was compiled with mutexing code omitted due to
  146265. ** the SQLITE_THREADSAFE compile-time option being set to 0.
  146266. */
  146267. SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
  146268. /*
  146269. ** When compiling the test fixture or with debugging enabled (on Win32),
  146270. ** this variable being set to non-zero will cause OSTRACE macros to emit
  146271. ** extra diagnostic information.
  146272. */
  146273. #ifdef SQLITE_HAVE_OS_TRACE
  146274. # ifndef SQLITE_DEBUG_OS_TRACE
  146275. # define SQLITE_DEBUG_OS_TRACE 0
  146276. # endif
  146277. int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
  146278. #endif
  146279. #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
  146280. /*
  146281. ** If the following function pointer is not NULL and if
  146282. ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
  146283. ** I/O active are written using this function. These messages
  146284. ** are intended for debugging activity only.
  146285. */
  146286. SQLITE_API void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...) = 0;
  146287. #endif
  146288. /*
  146289. ** If the following global variable points to a string which is the
  146290. ** name of a directory, then that directory will be used to store
  146291. ** temporary files.
  146292. **
  146293. ** See also the "PRAGMA temp_store_directory" SQL command.
  146294. */
  146295. SQLITE_API char *sqlite3_temp_directory = 0;
  146296. /*
  146297. ** If the following global variable points to a string which is the
  146298. ** name of a directory, then that directory will be used to store
  146299. ** all database files specified with a relative pathname.
  146300. **
  146301. ** See also the "PRAGMA data_store_directory" SQL command.
  146302. */
  146303. SQLITE_API char *sqlite3_data_directory = 0;
  146304. /*
  146305. ** Initialize SQLite.
  146306. **
  146307. ** This routine must be called to initialize the memory allocation,
  146308. ** VFS, and mutex subsystems prior to doing any serious work with
  146309. ** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT
  146310. ** this routine will be called automatically by key routines such as
  146311. ** sqlite3_open().
  146312. **
  146313. ** This routine is a no-op except on its very first call for the process,
  146314. ** or for the first call after a call to sqlite3_shutdown.
  146315. **
  146316. ** The first thread to call this routine runs the initialization to
  146317. ** completion. If subsequent threads call this routine before the first
  146318. ** thread has finished the initialization process, then the subsequent
  146319. ** threads must block until the first thread finishes with the initialization.
  146320. **
  146321. ** The first thread might call this routine recursively. Recursive
  146322. ** calls to this routine should not block, of course. Otherwise the
  146323. ** initialization process would never complete.
  146324. **
  146325. ** Let X be the first thread to enter this routine. Let Y be some other
  146326. ** thread. Then while the initial invocation of this routine by X is
  146327. ** incomplete, it is required that:
  146328. **
  146329. ** * Calls to this routine from Y must block until the outer-most
  146330. ** call by X completes.
  146331. **
  146332. ** * Recursive calls to this routine from thread X return immediately
  146333. ** without blocking.
  146334. */
  146335. SQLITE_API int sqlite3_initialize(void){
  146336. MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
  146337. int rc; /* Result code */
  146338. #ifdef SQLITE_EXTRA_INIT
  146339. int bRunExtraInit = 0; /* Extra initialization needed */
  146340. #endif
  146341. #ifdef SQLITE_OMIT_WSD
  146342. rc = sqlite3_wsd_init(4096, 24);
  146343. if( rc!=SQLITE_OK ){
  146344. return rc;
  146345. }
  146346. #endif
  146347. /* If the following assert() fails on some obscure processor/compiler
  146348. ** combination, the work-around is to set the correct pointer
  146349. ** size at compile-time using -DSQLITE_PTRSIZE=n compile-time option */
  146350. assert( SQLITE_PTRSIZE==sizeof(char*) );
  146351. /* If SQLite is already completely initialized, then this call
  146352. ** to sqlite3_initialize() should be a no-op. But the initialization
  146353. ** must be complete. So isInit must not be set until the very end
  146354. ** of this routine.
  146355. */
  146356. if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
  146357. /* Make sure the mutex subsystem is initialized. If unable to
  146358. ** initialize the mutex subsystem, return early with the error.
  146359. ** If the system is so sick that we are unable to allocate a mutex,
  146360. ** there is not much SQLite is going to be able to do.
  146361. **
  146362. ** The mutex subsystem must take care of serializing its own
  146363. ** initialization.
  146364. */
  146365. rc = sqlite3MutexInit();
  146366. if( rc ) return rc;
  146367. /* Initialize the malloc() system and the recursive pInitMutex mutex.
  146368. ** This operation is protected by the STATIC_MASTER mutex. Note that
  146369. ** MutexAlloc() is called for a static mutex prior to initializing the
  146370. ** malloc subsystem - this implies that the allocation of a static
  146371. ** mutex must not require support from the malloc subsystem.
  146372. */
  146373. MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  146374. sqlite3_mutex_enter(pMaster);
  146375. sqlite3GlobalConfig.isMutexInit = 1;
  146376. if( !sqlite3GlobalConfig.isMallocInit ){
  146377. rc = sqlite3MallocInit();
  146378. }
  146379. if( rc==SQLITE_OK ){
  146380. sqlite3GlobalConfig.isMallocInit = 1;
  146381. if( !sqlite3GlobalConfig.pInitMutex ){
  146382. sqlite3GlobalConfig.pInitMutex =
  146383. sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
  146384. if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
  146385. rc = SQLITE_NOMEM_BKPT;
  146386. }
  146387. }
  146388. }
  146389. if( rc==SQLITE_OK ){
  146390. sqlite3GlobalConfig.nRefInitMutex++;
  146391. }
  146392. sqlite3_mutex_leave(pMaster);
  146393. /* If rc is not SQLITE_OK at this point, then either the malloc
  146394. ** subsystem could not be initialized or the system failed to allocate
  146395. ** the pInitMutex mutex. Return an error in either case. */
  146396. if( rc!=SQLITE_OK ){
  146397. return rc;
  146398. }
  146399. /* Do the rest of the initialization under the recursive mutex so
  146400. ** that we will be able to handle recursive calls into
  146401. ** sqlite3_initialize(). The recursive calls normally come through
  146402. ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
  146403. ** recursive calls might also be possible.
  146404. **
  146405. ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
  146406. ** to the xInit method, so the xInit method need not be threadsafe.
  146407. **
  146408. ** The following mutex is what serializes access to the appdef pcache xInit
  146409. ** methods. The sqlite3_pcache_methods.xInit() all is embedded in the
  146410. ** call to sqlite3PcacheInitialize().
  146411. */
  146412. sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
  146413. if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
  146414. sqlite3GlobalConfig.inProgress = 1;
  146415. #ifdef SQLITE_ENABLE_SQLLOG
  146416. {
  146417. extern void sqlite3_init_sqllog(void);
  146418. sqlite3_init_sqllog();
  146419. }
  146420. #endif
  146421. memset(&sqlite3BuiltinFunctions, 0, sizeof(sqlite3BuiltinFunctions));
  146422. sqlite3RegisterBuiltinFunctions();
  146423. if( sqlite3GlobalConfig.isPCacheInit==0 ){
  146424. rc = sqlite3PcacheInitialize();
  146425. }
  146426. if( rc==SQLITE_OK ){
  146427. sqlite3GlobalConfig.isPCacheInit = 1;
  146428. rc = sqlite3OsInit();
  146429. }
  146430. #ifdef SQLITE_ENABLE_DESERIALIZE
  146431. if( rc==SQLITE_OK ){
  146432. rc = sqlite3MemdbInit();
  146433. }
  146434. #endif
  146435. if( rc==SQLITE_OK ){
  146436. sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
  146437. sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
  146438. sqlite3GlobalConfig.isInit = 1;
  146439. #ifdef SQLITE_EXTRA_INIT
  146440. bRunExtraInit = 1;
  146441. #endif
  146442. }
  146443. sqlite3GlobalConfig.inProgress = 0;
  146444. }
  146445. sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
  146446. /* Go back under the static mutex and clean up the recursive
  146447. ** mutex to prevent a resource leak.
  146448. */
  146449. sqlite3_mutex_enter(pMaster);
  146450. sqlite3GlobalConfig.nRefInitMutex--;
  146451. if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
  146452. assert( sqlite3GlobalConfig.nRefInitMutex==0 );
  146453. sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
  146454. sqlite3GlobalConfig.pInitMutex = 0;
  146455. }
  146456. sqlite3_mutex_leave(pMaster);
  146457. /* The following is just a sanity check to make sure SQLite has
  146458. ** been compiled correctly. It is important to run this code, but
  146459. ** we don't want to run it too often and soak up CPU cycles for no
  146460. ** reason. So we run it once during initialization.
  146461. */
  146462. #ifndef NDEBUG
  146463. #ifndef SQLITE_OMIT_FLOATING_POINT
  146464. /* This section of code's only "output" is via assert() statements. */
  146465. if( rc==SQLITE_OK ){
  146466. u64 x = (((u64)1)<<63)-1;
  146467. double y;
  146468. assert(sizeof(x)==8);
  146469. assert(sizeof(x)==sizeof(y));
  146470. memcpy(&y, &x, 8);
  146471. assert( sqlite3IsNaN(y) );
  146472. }
  146473. #endif
  146474. #endif
  146475. /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
  146476. ** compile-time option.
  146477. */
  146478. #ifdef SQLITE_EXTRA_INIT
  146479. if( bRunExtraInit ){
  146480. int SQLITE_EXTRA_INIT(const char*);
  146481. rc = SQLITE_EXTRA_INIT(0);
  146482. }
  146483. #endif
  146484. return rc;
  146485. }
  146486. /*
  146487. ** Undo the effects of sqlite3_initialize(). Must not be called while
  146488. ** there are outstanding database connections or memory allocations or
  146489. ** while any part of SQLite is otherwise in use in any thread. This
  146490. ** routine is not threadsafe. But it is safe to invoke this routine
  146491. ** on when SQLite is already shut down. If SQLite is already shut down
  146492. ** when this routine is invoked, then this routine is a harmless no-op.
  146493. */
  146494. SQLITE_API int sqlite3_shutdown(void){
  146495. #ifdef SQLITE_OMIT_WSD
  146496. int rc = sqlite3_wsd_init(4096, 24);
  146497. if( rc!=SQLITE_OK ){
  146498. return rc;
  146499. }
  146500. #endif
  146501. if( sqlite3GlobalConfig.isInit ){
  146502. #ifdef SQLITE_EXTRA_SHUTDOWN
  146503. void SQLITE_EXTRA_SHUTDOWN(void);
  146504. SQLITE_EXTRA_SHUTDOWN();
  146505. #endif
  146506. sqlite3_os_end();
  146507. sqlite3_reset_auto_extension();
  146508. sqlite3GlobalConfig.isInit = 0;
  146509. }
  146510. if( sqlite3GlobalConfig.isPCacheInit ){
  146511. sqlite3PcacheShutdown();
  146512. sqlite3GlobalConfig.isPCacheInit = 0;
  146513. }
  146514. if( sqlite3GlobalConfig.isMallocInit ){
  146515. sqlite3MallocEnd();
  146516. sqlite3GlobalConfig.isMallocInit = 0;
  146517. #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
  146518. /* The heap subsystem has now been shutdown and these values are supposed
  146519. ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
  146520. ** which would rely on that heap subsystem; therefore, make sure these
  146521. ** values cannot refer to heap memory that was just invalidated when the
  146522. ** heap subsystem was shutdown. This is only done if the current call to
  146523. ** this function resulted in the heap subsystem actually being shutdown.
  146524. */
  146525. sqlite3_data_directory = 0;
  146526. sqlite3_temp_directory = 0;
  146527. #endif
  146528. }
  146529. if( sqlite3GlobalConfig.isMutexInit ){
  146530. sqlite3MutexEnd();
  146531. sqlite3GlobalConfig.isMutexInit = 0;
  146532. }
  146533. return SQLITE_OK;
  146534. }
  146535. /*
  146536. ** This API allows applications to modify the global configuration of
  146537. ** the SQLite library at run-time.
  146538. **
  146539. ** This routine should only be called when there are no outstanding
  146540. ** database connections or memory allocations. This routine is not
  146541. ** threadsafe. Failure to heed these warnings can lead to unpredictable
  146542. ** behavior.
  146543. */
  146544. SQLITE_API int sqlite3_config(int op, ...){
  146545. va_list ap;
  146546. int rc = SQLITE_OK;
  146547. /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
  146548. ** the SQLite library is in use. */
  146549. if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
  146550. va_start(ap, op);
  146551. switch( op ){
  146552. /* Mutex configuration options are only available in a threadsafe
  146553. ** compile.
  146554. */
  146555. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-54466-46756 */
  146556. case SQLITE_CONFIG_SINGLETHREAD: {
  146557. /* EVIDENCE-OF: R-02748-19096 This option sets the threading mode to
  146558. ** Single-thread. */
  146559. sqlite3GlobalConfig.bCoreMutex = 0; /* Disable mutex on core */
  146560. sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */
  146561. break;
  146562. }
  146563. #endif
  146564. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-20520-54086 */
  146565. case SQLITE_CONFIG_MULTITHREAD: {
  146566. /* EVIDENCE-OF: R-14374-42468 This option sets the threading mode to
  146567. ** Multi-thread. */
  146568. sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */
  146569. sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */
  146570. break;
  146571. }
  146572. #endif
  146573. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-59593-21810 */
  146574. case SQLITE_CONFIG_SERIALIZED: {
  146575. /* EVIDENCE-OF: R-41220-51800 This option sets the threading mode to
  146576. ** Serialized. */
  146577. sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */
  146578. sqlite3GlobalConfig.bFullMutex = 1; /* Enable mutex on connections */
  146579. break;
  146580. }
  146581. #endif
  146582. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-63666-48755 */
  146583. case SQLITE_CONFIG_MUTEX: {
  146584. /* Specify an alternative mutex implementation */
  146585. sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
  146586. break;
  146587. }
  146588. #endif
  146589. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-14450-37597 */
  146590. case SQLITE_CONFIG_GETMUTEX: {
  146591. /* Retrieve the current mutex implementation */
  146592. *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
  146593. break;
  146594. }
  146595. #endif
  146596. case SQLITE_CONFIG_MALLOC: {
  146597. /* EVIDENCE-OF: R-55594-21030 The SQLITE_CONFIG_MALLOC option takes a
  146598. ** single argument which is a pointer to an instance of the
  146599. ** sqlite3_mem_methods structure. The argument specifies alternative
  146600. ** low-level memory allocation routines to be used in place of the memory
  146601. ** allocation routines built into SQLite. */
  146602. sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
  146603. break;
  146604. }
  146605. case SQLITE_CONFIG_GETMALLOC: {
  146606. /* EVIDENCE-OF: R-51213-46414 The SQLITE_CONFIG_GETMALLOC option takes a
  146607. ** single argument which is a pointer to an instance of the
  146608. ** sqlite3_mem_methods structure. The sqlite3_mem_methods structure is
  146609. ** filled with the currently defined memory allocation routines. */
  146610. if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
  146611. *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
  146612. break;
  146613. }
  146614. case SQLITE_CONFIG_MEMSTATUS: {
  146615. /* EVIDENCE-OF: R-61275-35157 The SQLITE_CONFIG_MEMSTATUS option takes
  146616. ** single argument of type int, interpreted as a boolean, which enables
  146617. ** or disables the collection of memory allocation statistics. */
  146618. sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
  146619. break;
  146620. }
  146621. case SQLITE_CONFIG_SMALL_MALLOC: {
  146622. sqlite3GlobalConfig.bSmallMalloc = va_arg(ap, int);
  146623. break;
  146624. }
  146625. case SQLITE_CONFIG_PAGECACHE: {
  146626. /* EVIDENCE-OF: R-18761-36601 There are three arguments to
  146627. ** SQLITE_CONFIG_PAGECACHE: A pointer to 8-byte aligned memory (pMem),
  146628. ** the size of each page cache line (sz), and the number of cache lines
  146629. ** (N). */
  146630. sqlite3GlobalConfig.pPage = va_arg(ap, void*);
  146631. sqlite3GlobalConfig.szPage = va_arg(ap, int);
  146632. sqlite3GlobalConfig.nPage = va_arg(ap, int);
  146633. break;
  146634. }
  146635. case SQLITE_CONFIG_PCACHE_HDRSZ: {
  146636. /* EVIDENCE-OF: R-39100-27317 The SQLITE_CONFIG_PCACHE_HDRSZ option takes
  146637. ** a single parameter which is a pointer to an integer and writes into
  146638. ** that integer the number of extra bytes per page required for each page
  146639. ** in SQLITE_CONFIG_PAGECACHE. */
  146640. *va_arg(ap, int*) =
  146641. sqlite3HeaderSizeBtree() +
  146642. sqlite3HeaderSizePcache() +
  146643. sqlite3HeaderSizePcache1();
  146644. break;
  146645. }
  146646. case SQLITE_CONFIG_PCACHE: {
  146647. /* no-op */
  146648. break;
  146649. }
  146650. case SQLITE_CONFIG_GETPCACHE: {
  146651. /* now an error */
  146652. rc = SQLITE_ERROR;
  146653. break;
  146654. }
  146655. case SQLITE_CONFIG_PCACHE2: {
  146656. /* EVIDENCE-OF: R-63325-48378 The SQLITE_CONFIG_PCACHE2 option takes a
  146657. ** single argument which is a pointer to an sqlite3_pcache_methods2
  146658. ** object. This object specifies the interface to a custom page cache
  146659. ** implementation. */
  146660. sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
  146661. break;
  146662. }
  146663. case SQLITE_CONFIG_GETPCACHE2: {
  146664. /* EVIDENCE-OF: R-22035-46182 The SQLITE_CONFIG_GETPCACHE2 option takes a
  146665. ** single argument which is a pointer to an sqlite3_pcache_methods2
  146666. ** object. SQLite copies of the current page cache implementation into
  146667. ** that object. */
  146668. if( sqlite3GlobalConfig.pcache2.xInit==0 ){
  146669. sqlite3PCacheSetDefault();
  146670. }
  146671. *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
  146672. break;
  146673. }
  146674. /* EVIDENCE-OF: R-06626-12911 The SQLITE_CONFIG_HEAP option is only
  146675. ** available if SQLite is compiled with either SQLITE_ENABLE_MEMSYS3 or
  146676. ** SQLITE_ENABLE_MEMSYS5 and returns SQLITE_ERROR if invoked otherwise. */
  146677. #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
  146678. case SQLITE_CONFIG_HEAP: {
  146679. /* EVIDENCE-OF: R-19854-42126 There are three arguments to
  146680. ** SQLITE_CONFIG_HEAP: An 8-byte aligned pointer to the memory, the
  146681. ** number of bytes in the memory buffer, and the minimum allocation size.
  146682. */
  146683. sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
  146684. sqlite3GlobalConfig.nHeap = va_arg(ap, int);
  146685. sqlite3GlobalConfig.mnReq = va_arg(ap, int);
  146686. if( sqlite3GlobalConfig.mnReq<1 ){
  146687. sqlite3GlobalConfig.mnReq = 1;
  146688. }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
  146689. /* cap min request size at 2^12 */
  146690. sqlite3GlobalConfig.mnReq = (1<<12);
  146691. }
  146692. if( sqlite3GlobalConfig.pHeap==0 ){
  146693. /* EVIDENCE-OF: R-49920-60189 If the first pointer (the memory pointer)
  146694. ** is NULL, then SQLite reverts to using its default memory allocator
  146695. ** (the system malloc() implementation), undoing any prior invocation of
  146696. ** SQLITE_CONFIG_MALLOC.
  146697. **
  146698. ** Setting sqlite3GlobalConfig.m to all zeros will cause malloc to
  146699. ** revert to its default implementation when sqlite3_initialize() is run
  146700. */
  146701. memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
  146702. }else{
  146703. /* EVIDENCE-OF: R-61006-08918 If the memory pointer is not NULL then the
  146704. ** alternative memory allocator is engaged to handle all of SQLites
  146705. ** memory allocation needs. */
  146706. #ifdef SQLITE_ENABLE_MEMSYS3
  146707. sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
  146708. #endif
  146709. #ifdef SQLITE_ENABLE_MEMSYS5
  146710. sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
  146711. #endif
  146712. }
  146713. break;
  146714. }
  146715. #endif
  146716. case SQLITE_CONFIG_LOOKASIDE: {
  146717. sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
  146718. sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
  146719. break;
  146720. }
  146721. /* Record a pointer to the logger function and its first argument.
  146722. ** The default is NULL. Logging is disabled if the function pointer is
  146723. ** NULL.
  146724. */
  146725. case SQLITE_CONFIG_LOG: {
  146726. /* MSVC is picky about pulling func ptrs from va lists.
  146727. ** http://support.microsoft.com/kb/47961
  146728. ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
  146729. */
  146730. typedef void(*LOGFUNC_t)(void*,int,const char*);
  146731. sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
  146732. sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
  146733. break;
  146734. }
  146735. /* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames
  146736. ** can be changed at start-time using the
  146737. ** sqlite3_config(SQLITE_CONFIG_URI,1) or
  146738. ** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls.
  146739. */
  146740. case SQLITE_CONFIG_URI: {
  146741. /* EVIDENCE-OF: R-25451-61125 The SQLITE_CONFIG_URI option takes a single
  146742. ** argument of type int. If non-zero, then URI handling is globally
  146743. ** enabled. If the parameter is zero, then URI handling is globally
  146744. ** disabled. */
  146745. sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
  146746. break;
  146747. }
  146748. case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
  146749. /* EVIDENCE-OF: R-36592-02772 The SQLITE_CONFIG_COVERING_INDEX_SCAN
  146750. ** option takes a single integer argument which is interpreted as a
  146751. ** boolean in order to enable or disable the use of covering indices for
  146752. ** full table scans in the query optimizer. */
  146753. sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
  146754. break;
  146755. }
  146756. #ifdef SQLITE_ENABLE_SQLLOG
  146757. case SQLITE_CONFIG_SQLLOG: {
  146758. typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
  146759. sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
  146760. sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
  146761. break;
  146762. }
  146763. #endif
  146764. case SQLITE_CONFIG_MMAP_SIZE: {
  146765. /* EVIDENCE-OF: R-58063-38258 SQLITE_CONFIG_MMAP_SIZE takes two 64-bit
  146766. ** integer (sqlite3_int64) values that are the default mmap size limit
  146767. ** (the default setting for PRAGMA mmap_size) and the maximum allowed
  146768. ** mmap size limit. */
  146769. sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
  146770. sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
  146771. /* EVIDENCE-OF: R-53367-43190 If either argument to this option is
  146772. ** negative, then that argument is changed to its compile-time default.
  146773. **
  146774. ** EVIDENCE-OF: R-34993-45031 The maximum allowed mmap size will be
  146775. ** silently truncated if necessary so that it does not exceed the
  146776. ** compile-time maximum mmap size set by the SQLITE_MAX_MMAP_SIZE
  146777. ** compile-time option.
  146778. */
  146779. if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){
  146780. mxMmap = SQLITE_MAX_MMAP_SIZE;
  146781. }
  146782. if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
  146783. if( szMmap>mxMmap) szMmap = mxMmap;
  146784. sqlite3GlobalConfig.mxMmap = mxMmap;
  146785. sqlite3GlobalConfig.szMmap = szMmap;
  146786. break;
  146787. }
  146788. #if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC) /* IMP: R-04780-55815 */
  146789. case SQLITE_CONFIG_WIN32_HEAPSIZE: {
  146790. /* EVIDENCE-OF: R-34926-03360 SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit
  146791. ** unsigned integer value that specifies the maximum size of the created
  146792. ** heap. */
  146793. sqlite3GlobalConfig.nHeap = va_arg(ap, int);
  146794. break;
  146795. }
  146796. #endif
  146797. case SQLITE_CONFIG_PMASZ: {
  146798. sqlite3GlobalConfig.szPma = va_arg(ap, unsigned int);
  146799. break;
  146800. }
  146801. case SQLITE_CONFIG_STMTJRNL_SPILL: {
  146802. sqlite3GlobalConfig.nStmtSpill = va_arg(ap, int);
  146803. break;
  146804. }
  146805. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  146806. case SQLITE_CONFIG_SORTERREF_SIZE: {
  146807. int iVal = va_arg(ap, int);
  146808. if( iVal<0 ){
  146809. iVal = SQLITE_DEFAULT_SORTERREF_SIZE;
  146810. }
  146811. sqlite3GlobalConfig.szSorterRef = (u32)iVal;
  146812. break;
  146813. }
  146814. #endif /* SQLITE_ENABLE_SORTER_REFERENCES */
  146815. #ifdef SQLITE_ENABLE_DESERIALIZE
  146816. case SQLITE_CONFIG_MEMDB_MAXSIZE: {
  146817. sqlite3GlobalConfig.mxMemdbSize = va_arg(ap, sqlite3_int64);
  146818. break;
  146819. }
  146820. #endif /* SQLITE_ENABLE_DESERIALIZE */
  146821. default: {
  146822. rc = SQLITE_ERROR;
  146823. break;
  146824. }
  146825. }
  146826. va_end(ap);
  146827. return rc;
  146828. }
  146829. /*
  146830. ** Set up the lookaside buffers for a database connection.
  146831. ** Return SQLITE_OK on success.
  146832. ** If lookaside is already active, return SQLITE_BUSY.
  146833. **
  146834. ** The sz parameter is the number of bytes in each lookaside slot.
  146835. ** The cnt parameter is the number of slots. If pStart is NULL the
  146836. ** space for the lookaside memory is obtained from sqlite3_malloc().
  146837. ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
  146838. ** the lookaside memory.
  146839. */
  146840. static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
  146841. #ifndef SQLITE_OMIT_LOOKASIDE
  146842. void *pStart;
  146843. if( sqlite3LookasideUsed(db,0)>0 ){
  146844. return SQLITE_BUSY;
  146845. }
  146846. /* Free any existing lookaside buffer for this handle before
  146847. ** allocating a new one so we don't have to have space for
  146848. ** both at the same time.
  146849. */
  146850. if( db->lookaside.bMalloced ){
  146851. sqlite3_free(db->lookaside.pStart);
  146852. }
  146853. /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
  146854. ** than a pointer to be useful.
  146855. */
  146856. sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
  146857. if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
  146858. if( cnt<0 ) cnt = 0;
  146859. if( sz==0 || cnt==0 ){
  146860. sz = 0;
  146861. pStart = 0;
  146862. }else if( pBuf==0 ){
  146863. sqlite3BeginBenignMalloc();
  146864. pStart = sqlite3Malloc( sz*(sqlite3_int64)cnt ); /* IMP: R-61949-35727 */
  146865. sqlite3EndBenignMalloc();
  146866. if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
  146867. }else{
  146868. pStart = pBuf;
  146869. }
  146870. db->lookaside.pStart = pStart;
  146871. db->lookaside.pInit = 0;
  146872. db->lookaside.pFree = 0;
  146873. db->lookaside.sz = (u16)sz;
  146874. if( pStart ){
  146875. int i;
  146876. LookasideSlot *p;
  146877. assert( sz > (int)sizeof(LookasideSlot*) );
  146878. db->lookaside.nSlot = cnt;
  146879. p = (LookasideSlot*)pStart;
  146880. for(i=cnt-1; i>=0; i--){
  146881. p->pNext = db->lookaside.pInit;
  146882. db->lookaside.pInit = p;
  146883. p = (LookasideSlot*)&((u8*)p)[sz];
  146884. }
  146885. db->lookaside.pEnd = p;
  146886. db->lookaside.bDisable = 0;
  146887. db->lookaside.bMalloced = pBuf==0 ?1:0;
  146888. }else{
  146889. db->lookaside.pStart = db;
  146890. db->lookaside.pEnd = db;
  146891. db->lookaside.bDisable = 1;
  146892. db->lookaside.bMalloced = 0;
  146893. db->lookaside.nSlot = 0;
  146894. }
  146895. #endif /* SQLITE_OMIT_LOOKASIDE */
  146896. return SQLITE_OK;
  146897. }
  146898. /*
  146899. ** Return the mutex associated with a database connection.
  146900. */
  146901. SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
  146902. #ifdef SQLITE_ENABLE_API_ARMOR
  146903. if( !sqlite3SafetyCheckOk(db) ){
  146904. (void)SQLITE_MISUSE_BKPT;
  146905. return 0;
  146906. }
  146907. #endif
  146908. return db->mutex;
  146909. }
  146910. /*
  146911. ** Free up as much memory as we can from the given database
  146912. ** connection.
  146913. */
  146914. SQLITE_API int sqlite3_db_release_memory(sqlite3 *db){
  146915. int i;
  146916. #ifdef SQLITE_ENABLE_API_ARMOR
  146917. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  146918. #endif
  146919. sqlite3_mutex_enter(db->mutex);
  146920. sqlite3BtreeEnterAll(db);
  146921. for(i=0; i<db->nDb; i++){
  146922. Btree *pBt = db->aDb[i].pBt;
  146923. if( pBt ){
  146924. Pager *pPager = sqlite3BtreePager(pBt);
  146925. sqlite3PagerShrink(pPager);
  146926. }
  146927. }
  146928. sqlite3BtreeLeaveAll(db);
  146929. sqlite3_mutex_leave(db->mutex);
  146930. return SQLITE_OK;
  146931. }
  146932. /*
  146933. ** Flush any dirty pages in the pager-cache for any attached database
  146934. ** to disk.
  146935. */
  146936. SQLITE_API int sqlite3_db_cacheflush(sqlite3 *db){
  146937. int i;
  146938. int rc = SQLITE_OK;
  146939. int bSeenBusy = 0;
  146940. #ifdef SQLITE_ENABLE_API_ARMOR
  146941. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  146942. #endif
  146943. sqlite3_mutex_enter(db->mutex);
  146944. sqlite3BtreeEnterAll(db);
  146945. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  146946. Btree *pBt = db->aDb[i].pBt;
  146947. if( pBt && sqlite3BtreeIsInTrans(pBt) ){
  146948. Pager *pPager = sqlite3BtreePager(pBt);
  146949. rc = sqlite3PagerFlush(pPager);
  146950. if( rc==SQLITE_BUSY ){
  146951. bSeenBusy = 1;
  146952. rc = SQLITE_OK;
  146953. }
  146954. }
  146955. }
  146956. sqlite3BtreeLeaveAll(db);
  146957. sqlite3_mutex_leave(db->mutex);
  146958. return ((rc==SQLITE_OK && bSeenBusy) ? SQLITE_BUSY : rc);
  146959. }
  146960. /*
  146961. ** Configuration settings for an individual database connection
  146962. */
  146963. SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
  146964. va_list ap;
  146965. int rc;
  146966. va_start(ap, op);
  146967. switch( op ){
  146968. case SQLITE_DBCONFIG_MAINDBNAME: {
  146969. /* IMP: R-06824-28531 */
  146970. /* IMP: R-36257-52125 */
  146971. db->aDb[0].zDbSName = va_arg(ap,char*);
  146972. rc = SQLITE_OK;
  146973. break;
  146974. }
  146975. case SQLITE_DBCONFIG_LOOKASIDE: {
  146976. void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
  146977. int sz = va_arg(ap, int); /* IMP: R-47871-25994 */
  146978. int cnt = va_arg(ap, int); /* IMP: R-04460-53386 */
  146979. rc = setupLookaside(db, pBuf, sz, cnt);
  146980. break;
  146981. }
  146982. default: {
  146983. static const struct {
  146984. int op; /* The opcode */
  146985. u32 mask; /* Mask of the bit in sqlite3.flags to set/clear */
  146986. } aFlagOp[] = {
  146987. { SQLITE_DBCONFIG_ENABLE_FKEY, SQLITE_ForeignKeys },
  146988. { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger },
  146989. { SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, SQLITE_Fts3Tokenizer },
  146990. { SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, SQLITE_LoadExtension },
  146991. { SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE, SQLITE_NoCkptOnClose },
  146992. { SQLITE_DBCONFIG_ENABLE_QPSG, SQLITE_EnableQPSG },
  146993. { SQLITE_DBCONFIG_TRIGGER_EQP, SQLITE_TriggerEQP },
  146994. { SQLITE_DBCONFIG_RESET_DATABASE, SQLITE_ResetDatabase },
  146995. { SQLITE_DBCONFIG_DEFENSIVE, SQLITE_Defensive },
  146996. { SQLITE_DBCONFIG_WRITABLE_SCHEMA, SQLITE_WriteSchema|
  146997. SQLITE_NoSchemaError },
  146998. { SQLITE_DBCONFIG_LEGACY_ALTER_TABLE, SQLITE_LegacyAlter },
  146999. { SQLITE_DBCONFIG_DQS_DDL, SQLITE_DqsDDL },
  147000. { SQLITE_DBCONFIG_DQS_DML, SQLITE_DqsDML },
  147001. };
  147002. unsigned int i;
  147003. rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
  147004. for(i=0; i<ArraySize(aFlagOp); i++){
  147005. if( aFlagOp[i].op==op ){
  147006. int onoff = va_arg(ap, int);
  147007. int *pRes = va_arg(ap, int*);
  147008. u64 oldFlags = db->flags;
  147009. if( onoff>0 ){
  147010. db->flags |= aFlagOp[i].mask;
  147011. }else if( onoff==0 ){
  147012. db->flags &= ~(u64)aFlagOp[i].mask;
  147013. }
  147014. if( oldFlags!=db->flags ){
  147015. sqlite3ExpirePreparedStatements(db, 0);
  147016. }
  147017. if( pRes ){
  147018. *pRes = (db->flags & aFlagOp[i].mask)!=0;
  147019. }
  147020. rc = SQLITE_OK;
  147021. break;
  147022. }
  147023. }
  147024. break;
  147025. }
  147026. }
  147027. va_end(ap);
  147028. return rc;
  147029. }
  147030. /*
  147031. ** This is the default collating function named "BINARY" which is always
  147032. ** available.
  147033. */
  147034. static int binCollFunc(
  147035. void *NotUsed,
  147036. int nKey1, const void *pKey1,
  147037. int nKey2, const void *pKey2
  147038. ){
  147039. int rc, n;
  147040. UNUSED_PARAMETER(NotUsed);
  147041. n = nKey1<nKey2 ? nKey1 : nKey2;
  147042. /* EVIDENCE-OF: R-65033-28449 The built-in BINARY collation compares
  147043. ** strings byte by byte using the memcmp() function from the standard C
  147044. ** library. */
  147045. assert( pKey1 && pKey2 );
  147046. rc = memcmp(pKey1, pKey2, n);
  147047. if( rc==0 ){
  147048. rc = nKey1 - nKey2;
  147049. }
  147050. return rc;
  147051. }
  147052. /*
  147053. ** This is the collating function named "RTRIM" which is always
  147054. ** available. Ignore trailing spaces.
  147055. */
  147056. static int rtrimCollFunc(
  147057. void *pUser,
  147058. int nKey1, const void *pKey1,
  147059. int nKey2, const void *pKey2
  147060. ){
  147061. const u8 *pK1 = (const u8*)pKey1;
  147062. const u8 *pK2 = (const u8*)pKey2;
  147063. while( nKey1 && pK1[nKey1-1]==' ' ) nKey1--;
  147064. while( nKey2 && pK2[nKey2-1]==' ' ) nKey2--;
  147065. return binCollFunc(pUser, nKey1, pKey1, nKey2, pKey2);
  147066. }
  147067. /*
  147068. ** Return true if CollSeq is the default built-in BINARY.
  147069. */
  147070. SQLITE_PRIVATE int sqlite3IsBinary(const CollSeq *p){
  147071. assert( p==0 || p->xCmp!=binCollFunc || strcmp(p->zName,"BINARY")==0 );
  147072. return p==0 || p->xCmp==binCollFunc;
  147073. }
  147074. /*
  147075. ** Another built-in collating sequence: NOCASE.
  147076. **
  147077. ** This collating sequence is intended to be used for "case independent
  147078. ** comparison". SQLite's knowledge of upper and lower case equivalents
  147079. ** extends only to the 26 characters used in the English language.
  147080. **
  147081. ** At the moment there is only a UTF-8 implementation.
  147082. */
  147083. static int nocaseCollatingFunc(
  147084. void *NotUsed,
  147085. int nKey1, const void *pKey1,
  147086. int nKey2, const void *pKey2
  147087. ){
  147088. int r = sqlite3StrNICmp(
  147089. (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
  147090. UNUSED_PARAMETER(NotUsed);
  147091. if( 0==r ){
  147092. r = nKey1-nKey2;
  147093. }
  147094. return r;
  147095. }
  147096. /*
  147097. ** Return the ROWID of the most recent insert
  147098. */
  147099. SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
  147100. #ifdef SQLITE_ENABLE_API_ARMOR
  147101. if( !sqlite3SafetyCheckOk(db) ){
  147102. (void)SQLITE_MISUSE_BKPT;
  147103. return 0;
  147104. }
  147105. #endif
  147106. return db->lastRowid;
  147107. }
  147108. /*
  147109. ** Set the value returned by the sqlite3_last_insert_rowid() API function.
  147110. */
  147111. SQLITE_API void sqlite3_set_last_insert_rowid(sqlite3 *db, sqlite3_int64 iRowid){
  147112. #ifdef SQLITE_ENABLE_API_ARMOR
  147113. if( !sqlite3SafetyCheckOk(db) ){
  147114. (void)SQLITE_MISUSE_BKPT;
  147115. return;
  147116. }
  147117. #endif
  147118. sqlite3_mutex_enter(db->mutex);
  147119. db->lastRowid = iRowid;
  147120. sqlite3_mutex_leave(db->mutex);
  147121. }
  147122. /*
  147123. ** Return the number of changes in the most recent call to sqlite3_exec().
  147124. */
  147125. SQLITE_API int sqlite3_changes(sqlite3 *db){
  147126. #ifdef SQLITE_ENABLE_API_ARMOR
  147127. if( !sqlite3SafetyCheckOk(db) ){
  147128. (void)SQLITE_MISUSE_BKPT;
  147129. return 0;
  147130. }
  147131. #endif
  147132. return db->nChange;
  147133. }
  147134. /*
  147135. ** Return the number of changes since the database handle was opened.
  147136. */
  147137. SQLITE_API int sqlite3_total_changes(sqlite3 *db){
  147138. #ifdef SQLITE_ENABLE_API_ARMOR
  147139. if( !sqlite3SafetyCheckOk(db) ){
  147140. (void)SQLITE_MISUSE_BKPT;
  147141. return 0;
  147142. }
  147143. #endif
  147144. return db->nTotalChange;
  147145. }
  147146. /*
  147147. ** Close all open savepoints. This function only manipulates fields of the
  147148. ** database handle object, it does not close any savepoints that may be open
  147149. ** at the b-tree/pager level.
  147150. */
  147151. SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
  147152. while( db->pSavepoint ){
  147153. Savepoint *pTmp = db->pSavepoint;
  147154. db->pSavepoint = pTmp->pNext;
  147155. sqlite3DbFree(db, pTmp);
  147156. }
  147157. db->nSavepoint = 0;
  147158. db->nStatement = 0;
  147159. db->isTransactionSavepoint = 0;
  147160. }
  147161. /*
  147162. ** Invoke the destructor function associated with FuncDef p, if any. Except,
  147163. ** if this is not the last copy of the function, do not invoke it. Multiple
  147164. ** copies of a single function are created when create_function() is called
  147165. ** with SQLITE_ANY as the encoding.
  147166. */
  147167. static void functionDestroy(sqlite3 *db, FuncDef *p){
  147168. FuncDestructor *pDestructor = p->u.pDestructor;
  147169. if( pDestructor ){
  147170. pDestructor->nRef--;
  147171. if( pDestructor->nRef==0 ){
  147172. pDestructor->xDestroy(pDestructor->pUserData);
  147173. sqlite3DbFree(db, pDestructor);
  147174. }
  147175. }
  147176. }
  147177. /*
  147178. ** Disconnect all sqlite3_vtab objects that belong to database connection
  147179. ** db. This is called when db is being closed.
  147180. */
  147181. static void disconnectAllVtab(sqlite3 *db){
  147182. #ifndef SQLITE_OMIT_VIRTUALTABLE
  147183. int i;
  147184. HashElem *p;
  147185. sqlite3BtreeEnterAll(db);
  147186. for(i=0; i<db->nDb; i++){
  147187. Schema *pSchema = db->aDb[i].pSchema;
  147188. if( pSchema ){
  147189. for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
  147190. Table *pTab = (Table *)sqliteHashData(p);
  147191. if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
  147192. }
  147193. }
  147194. }
  147195. for(p=sqliteHashFirst(&db->aModule); p; p=sqliteHashNext(p)){
  147196. Module *pMod = (Module *)sqliteHashData(p);
  147197. if( pMod->pEpoTab ){
  147198. sqlite3VtabDisconnect(db, pMod->pEpoTab);
  147199. }
  147200. }
  147201. sqlite3VtabUnlockList(db);
  147202. sqlite3BtreeLeaveAll(db);
  147203. #else
  147204. UNUSED_PARAMETER(db);
  147205. #endif
  147206. }
  147207. /*
  147208. ** Return TRUE if database connection db has unfinalized prepared
  147209. ** statements or unfinished sqlite3_backup objects.
  147210. */
  147211. static int connectionIsBusy(sqlite3 *db){
  147212. int j;
  147213. assert( sqlite3_mutex_held(db->mutex) );
  147214. if( db->pVdbe ) return 1;
  147215. for(j=0; j<db->nDb; j++){
  147216. Btree *pBt = db->aDb[j].pBt;
  147217. if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
  147218. }
  147219. return 0;
  147220. }
  147221. /*
  147222. ** Close an existing SQLite database
  147223. */
  147224. static int sqlite3Close(sqlite3 *db, int forceZombie){
  147225. if( !db ){
  147226. /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or
  147227. ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */
  147228. return SQLITE_OK;
  147229. }
  147230. if( !sqlite3SafetyCheckSickOrOk(db) ){
  147231. return SQLITE_MISUSE_BKPT;
  147232. }
  147233. sqlite3_mutex_enter(db->mutex);
  147234. if( db->mTrace & SQLITE_TRACE_CLOSE ){
  147235. db->xTrace(SQLITE_TRACE_CLOSE, db->pTraceArg, db, 0);
  147236. }
  147237. /* Force xDisconnect calls on all virtual tables */
  147238. disconnectAllVtab(db);
  147239. /* If a transaction is open, the disconnectAllVtab() call above
  147240. ** will not have called the xDisconnect() method on any virtual
  147241. ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
  147242. ** call will do so. We need to do this before the check for active
  147243. ** SQL statements below, as the v-table implementation may be storing
  147244. ** some prepared statements internally.
  147245. */
  147246. sqlite3VtabRollback(db);
  147247. /* Legacy behavior (sqlite3_close() behavior) is to return
  147248. ** SQLITE_BUSY if the connection can not be closed immediately.
  147249. */
  147250. if( !forceZombie && connectionIsBusy(db) ){
  147251. sqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to close due to unfinalized "
  147252. "statements or unfinished backups");
  147253. sqlite3_mutex_leave(db->mutex);
  147254. return SQLITE_BUSY;
  147255. }
  147256. #ifdef SQLITE_ENABLE_SQLLOG
  147257. if( sqlite3GlobalConfig.xSqllog ){
  147258. /* Closing the handle. Fourth parameter is passed the value 2. */
  147259. sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
  147260. }
  147261. #endif
  147262. /* Convert the connection into a zombie and then close it.
  147263. */
  147264. db->magic = SQLITE_MAGIC_ZOMBIE;
  147265. sqlite3LeaveMutexAndCloseZombie(db);
  147266. return SQLITE_OK;
  147267. }
  147268. /*
  147269. ** Two variations on the public interface for closing a database
  147270. ** connection. The sqlite3_close() version returns SQLITE_BUSY and
  147271. ** leaves the connection option if there are unfinalized prepared
  147272. ** statements or unfinished sqlite3_backups. The sqlite3_close_v2()
  147273. ** version forces the connection to become a zombie if there are
  147274. ** unclosed resources, and arranges for deallocation when the last
  147275. ** prepare statement or sqlite3_backup closes.
  147276. */
  147277. SQLITE_API int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
  147278. SQLITE_API int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
  147279. /*
  147280. ** Close the mutex on database connection db.
  147281. **
  147282. ** Furthermore, if database connection db is a zombie (meaning that there
  147283. ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
  147284. ** every sqlite3_stmt has now been finalized and every sqlite3_backup has
  147285. ** finished, then free all resources.
  147286. */
  147287. SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
  147288. HashElem *i; /* Hash table iterator */
  147289. int j;
  147290. /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
  147291. ** or if the connection has not yet been closed by sqlite3_close_v2(),
  147292. ** then just leave the mutex and return.
  147293. */
  147294. if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
  147295. sqlite3_mutex_leave(db->mutex);
  147296. return;
  147297. }
  147298. /* If we reach this point, it means that the database connection has
  147299. ** closed all sqlite3_stmt and sqlite3_backup objects and has been
  147300. ** passed to sqlite3_close (meaning that it is a zombie). Therefore,
  147301. ** go ahead and free all resources.
  147302. */
  147303. /* If a transaction is open, roll it back. This also ensures that if
  147304. ** any database schemas have been modified by an uncommitted transaction
  147305. ** they are reset. And that the required b-tree mutex is held to make
  147306. ** the pager rollback and schema reset an atomic operation. */
  147307. sqlite3RollbackAll(db, SQLITE_OK);
  147308. /* Free any outstanding Savepoint structures. */
  147309. sqlite3CloseSavepoints(db);
  147310. /* Close all database connections */
  147311. for(j=0; j<db->nDb; j++){
  147312. struct Db *pDb = &db->aDb[j];
  147313. if( pDb->pBt ){
  147314. sqlite3BtreeClose(pDb->pBt);
  147315. pDb->pBt = 0;
  147316. if( j!=1 ){
  147317. pDb->pSchema = 0;
  147318. }
  147319. }
  147320. }
  147321. /* Clear the TEMP schema separately and last */
  147322. if( db->aDb[1].pSchema ){
  147323. sqlite3SchemaClear(db->aDb[1].pSchema);
  147324. }
  147325. sqlite3VtabUnlockList(db);
  147326. /* Free up the array of auxiliary databases */
  147327. sqlite3CollapseDatabaseArray(db);
  147328. assert( db->nDb<=2 );
  147329. assert( db->aDb==db->aDbStatic );
  147330. /* Tell the code in notify.c that the connection no longer holds any
  147331. ** locks and does not require any further unlock-notify callbacks.
  147332. */
  147333. sqlite3ConnectionClosed(db);
  147334. for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){
  147335. FuncDef *pNext, *p;
  147336. p = sqliteHashData(i);
  147337. do{
  147338. functionDestroy(db, p);
  147339. pNext = p->pNext;
  147340. sqlite3DbFree(db, p);
  147341. p = pNext;
  147342. }while( p );
  147343. }
  147344. sqlite3HashClear(&db->aFunc);
  147345. for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
  147346. CollSeq *pColl = (CollSeq *)sqliteHashData(i);
  147347. /* Invoke any destructors registered for collation sequence user data. */
  147348. for(j=0; j<3; j++){
  147349. if( pColl[j].xDel ){
  147350. pColl[j].xDel(pColl[j].pUser);
  147351. }
  147352. }
  147353. sqlite3DbFree(db, pColl);
  147354. }
  147355. sqlite3HashClear(&db->aCollSeq);
  147356. #ifndef SQLITE_OMIT_VIRTUALTABLE
  147357. for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
  147358. Module *pMod = (Module *)sqliteHashData(i);
  147359. if( pMod->xDestroy ){
  147360. pMod->xDestroy(pMod->pAux);
  147361. }
  147362. sqlite3VtabEponymousTableClear(db, pMod);
  147363. sqlite3DbFree(db, pMod);
  147364. }
  147365. sqlite3HashClear(&db->aModule);
  147366. #endif
  147367. sqlite3Error(db, SQLITE_OK); /* Deallocates any cached error strings. */
  147368. sqlite3ValueFree(db->pErr);
  147369. sqlite3CloseExtensions(db);
  147370. #if SQLITE_USER_AUTHENTICATION
  147371. sqlite3_free(db->auth.zAuthUser);
  147372. sqlite3_free(db->auth.zAuthPW);
  147373. #endif
  147374. db->magic = SQLITE_MAGIC_ERROR;
  147375. /* The temp-database schema is allocated differently from the other schema
  147376. ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
  147377. ** So it needs to be freed here. Todo: Why not roll the temp schema into
  147378. ** the same sqliteMalloc() as the one that allocates the database
  147379. ** structure?
  147380. */
  147381. sqlite3DbFree(db, db->aDb[1].pSchema);
  147382. sqlite3_mutex_leave(db->mutex);
  147383. db->magic = SQLITE_MAGIC_CLOSED;
  147384. sqlite3_mutex_free(db->mutex);
  147385. assert( sqlite3LookasideUsed(db,0)==0 );
  147386. if( db->lookaside.bMalloced ){
  147387. sqlite3_free(db->lookaside.pStart);
  147388. }
  147389. sqlite3_free(db);
  147390. }
  147391. /*
  147392. ** Rollback all database files. If tripCode is not SQLITE_OK, then
  147393. ** any write cursors are invalidated ("tripped" - as in "tripping a circuit
  147394. ** breaker") and made to return tripCode if there are any further
  147395. ** attempts to use that cursor. Read cursors remain open and valid
  147396. ** but are "saved" in case the table pages are moved around.
  147397. */
  147398. SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
  147399. int i;
  147400. int inTrans = 0;
  147401. int schemaChange;
  147402. assert( sqlite3_mutex_held(db->mutex) );
  147403. sqlite3BeginBenignMalloc();
  147404. /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
  147405. ** This is important in case the transaction being rolled back has
  147406. ** modified the database schema. If the b-tree mutexes are not taken
  147407. ** here, then another shared-cache connection might sneak in between
  147408. ** the database rollback and schema reset, which can cause false
  147409. ** corruption reports in some cases. */
  147410. sqlite3BtreeEnterAll(db);
  147411. schemaChange = (db->mDbFlags & DBFLAG_SchemaChange)!=0 && db->init.busy==0;
  147412. for(i=0; i<db->nDb; i++){
  147413. Btree *p = db->aDb[i].pBt;
  147414. if( p ){
  147415. if( sqlite3BtreeIsInTrans(p) ){
  147416. inTrans = 1;
  147417. }
  147418. sqlite3BtreeRollback(p, tripCode, !schemaChange);
  147419. }
  147420. }
  147421. sqlite3VtabRollback(db);
  147422. sqlite3EndBenignMalloc();
  147423. if( schemaChange ){
  147424. sqlite3ExpirePreparedStatements(db, 0);
  147425. sqlite3ResetAllSchemasOfConnection(db);
  147426. }
  147427. sqlite3BtreeLeaveAll(db);
  147428. /* Any deferred constraint violations have now been resolved. */
  147429. db->nDeferredCons = 0;
  147430. db->nDeferredImmCons = 0;
  147431. db->flags &= ~(u64)SQLITE_DeferFKs;
  147432. /* If one has been configured, invoke the rollback-hook callback */
  147433. if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
  147434. db->xRollbackCallback(db->pRollbackArg);
  147435. }
  147436. }
  147437. /*
  147438. ** Return a static string containing the name corresponding to the error code
  147439. ** specified in the argument.
  147440. */
  147441. #if defined(SQLITE_NEED_ERR_NAME)
  147442. SQLITE_PRIVATE const char *sqlite3ErrName(int rc){
  147443. const char *zName = 0;
  147444. int i, origRc = rc;
  147445. for(i=0; i<2 && zName==0; i++, rc &= 0xff){
  147446. switch( rc ){
  147447. case SQLITE_OK: zName = "SQLITE_OK"; break;
  147448. case SQLITE_ERROR: zName = "SQLITE_ERROR"; break;
  147449. case SQLITE_ERROR_SNAPSHOT: zName = "SQLITE_ERROR_SNAPSHOT"; break;
  147450. case SQLITE_INTERNAL: zName = "SQLITE_INTERNAL"; break;
  147451. case SQLITE_PERM: zName = "SQLITE_PERM"; break;
  147452. case SQLITE_ABORT: zName = "SQLITE_ABORT"; break;
  147453. case SQLITE_ABORT_ROLLBACK: zName = "SQLITE_ABORT_ROLLBACK"; break;
  147454. case SQLITE_BUSY: zName = "SQLITE_BUSY"; break;
  147455. case SQLITE_BUSY_RECOVERY: zName = "SQLITE_BUSY_RECOVERY"; break;
  147456. case SQLITE_BUSY_SNAPSHOT: zName = "SQLITE_BUSY_SNAPSHOT"; break;
  147457. case SQLITE_LOCKED: zName = "SQLITE_LOCKED"; break;
  147458. case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
  147459. case SQLITE_NOMEM: zName = "SQLITE_NOMEM"; break;
  147460. case SQLITE_READONLY: zName = "SQLITE_READONLY"; break;
  147461. case SQLITE_READONLY_RECOVERY: zName = "SQLITE_READONLY_RECOVERY"; break;
  147462. case SQLITE_READONLY_CANTINIT: zName = "SQLITE_READONLY_CANTINIT"; break;
  147463. case SQLITE_READONLY_ROLLBACK: zName = "SQLITE_READONLY_ROLLBACK"; break;
  147464. case SQLITE_READONLY_DBMOVED: zName = "SQLITE_READONLY_DBMOVED"; break;
  147465. case SQLITE_READONLY_DIRECTORY: zName = "SQLITE_READONLY_DIRECTORY";break;
  147466. case SQLITE_INTERRUPT: zName = "SQLITE_INTERRUPT"; break;
  147467. case SQLITE_IOERR: zName = "SQLITE_IOERR"; break;
  147468. case SQLITE_IOERR_READ: zName = "SQLITE_IOERR_READ"; break;
  147469. case SQLITE_IOERR_SHORT_READ: zName = "SQLITE_IOERR_SHORT_READ"; break;
  147470. case SQLITE_IOERR_WRITE: zName = "SQLITE_IOERR_WRITE"; break;
  147471. case SQLITE_IOERR_FSYNC: zName = "SQLITE_IOERR_FSYNC"; break;
  147472. case SQLITE_IOERR_DIR_FSYNC: zName = "SQLITE_IOERR_DIR_FSYNC"; break;
  147473. case SQLITE_IOERR_TRUNCATE: zName = "SQLITE_IOERR_TRUNCATE"; break;
  147474. case SQLITE_IOERR_FSTAT: zName = "SQLITE_IOERR_FSTAT"; break;
  147475. case SQLITE_IOERR_UNLOCK: zName = "SQLITE_IOERR_UNLOCK"; break;
  147476. case SQLITE_IOERR_RDLOCK: zName = "SQLITE_IOERR_RDLOCK"; break;
  147477. case SQLITE_IOERR_DELETE: zName = "SQLITE_IOERR_DELETE"; break;
  147478. case SQLITE_IOERR_NOMEM: zName = "SQLITE_IOERR_NOMEM"; break;
  147479. case SQLITE_IOERR_ACCESS: zName = "SQLITE_IOERR_ACCESS"; break;
  147480. case SQLITE_IOERR_CHECKRESERVEDLOCK:
  147481. zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
  147482. case SQLITE_IOERR_LOCK: zName = "SQLITE_IOERR_LOCK"; break;
  147483. case SQLITE_IOERR_CLOSE: zName = "SQLITE_IOERR_CLOSE"; break;
  147484. case SQLITE_IOERR_DIR_CLOSE: zName = "SQLITE_IOERR_DIR_CLOSE"; break;
  147485. case SQLITE_IOERR_SHMOPEN: zName = "SQLITE_IOERR_SHMOPEN"; break;
  147486. case SQLITE_IOERR_SHMSIZE: zName = "SQLITE_IOERR_SHMSIZE"; break;
  147487. case SQLITE_IOERR_SHMLOCK: zName = "SQLITE_IOERR_SHMLOCK"; break;
  147488. case SQLITE_IOERR_SHMMAP: zName = "SQLITE_IOERR_SHMMAP"; break;
  147489. case SQLITE_IOERR_SEEK: zName = "SQLITE_IOERR_SEEK"; break;
  147490. case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
  147491. case SQLITE_IOERR_MMAP: zName = "SQLITE_IOERR_MMAP"; break;
  147492. case SQLITE_IOERR_GETTEMPPATH: zName = "SQLITE_IOERR_GETTEMPPATH"; break;
  147493. case SQLITE_IOERR_CONVPATH: zName = "SQLITE_IOERR_CONVPATH"; break;
  147494. case SQLITE_CORRUPT: zName = "SQLITE_CORRUPT"; break;
  147495. case SQLITE_CORRUPT_VTAB: zName = "SQLITE_CORRUPT_VTAB"; break;
  147496. case SQLITE_NOTFOUND: zName = "SQLITE_NOTFOUND"; break;
  147497. case SQLITE_FULL: zName = "SQLITE_FULL"; break;
  147498. case SQLITE_CANTOPEN: zName = "SQLITE_CANTOPEN"; break;
  147499. case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
  147500. case SQLITE_CANTOPEN_ISDIR: zName = "SQLITE_CANTOPEN_ISDIR"; break;
  147501. case SQLITE_CANTOPEN_FULLPATH: zName = "SQLITE_CANTOPEN_FULLPATH"; break;
  147502. case SQLITE_CANTOPEN_CONVPATH: zName = "SQLITE_CANTOPEN_CONVPATH"; break;
  147503. case SQLITE_PROTOCOL: zName = "SQLITE_PROTOCOL"; break;
  147504. case SQLITE_EMPTY: zName = "SQLITE_EMPTY"; break;
  147505. case SQLITE_SCHEMA: zName = "SQLITE_SCHEMA"; break;
  147506. case SQLITE_TOOBIG: zName = "SQLITE_TOOBIG"; break;
  147507. case SQLITE_CONSTRAINT: zName = "SQLITE_CONSTRAINT"; break;
  147508. case SQLITE_CONSTRAINT_UNIQUE: zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
  147509. case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
  147510. case SQLITE_CONSTRAINT_FOREIGNKEY:
  147511. zName = "SQLITE_CONSTRAINT_FOREIGNKEY"; break;
  147512. case SQLITE_CONSTRAINT_CHECK: zName = "SQLITE_CONSTRAINT_CHECK"; break;
  147513. case SQLITE_CONSTRAINT_PRIMARYKEY:
  147514. zName = "SQLITE_CONSTRAINT_PRIMARYKEY"; break;
  147515. case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
  147516. case SQLITE_CONSTRAINT_COMMITHOOK:
  147517. zName = "SQLITE_CONSTRAINT_COMMITHOOK"; break;
  147518. case SQLITE_CONSTRAINT_VTAB: zName = "SQLITE_CONSTRAINT_VTAB"; break;
  147519. case SQLITE_CONSTRAINT_FUNCTION:
  147520. zName = "SQLITE_CONSTRAINT_FUNCTION"; break;
  147521. case SQLITE_CONSTRAINT_ROWID: zName = "SQLITE_CONSTRAINT_ROWID"; break;
  147522. case SQLITE_MISMATCH: zName = "SQLITE_MISMATCH"; break;
  147523. case SQLITE_MISUSE: zName = "SQLITE_MISUSE"; break;
  147524. case SQLITE_NOLFS: zName = "SQLITE_NOLFS"; break;
  147525. case SQLITE_AUTH: zName = "SQLITE_AUTH"; break;
  147526. case SQLITE_FORMAT: zName = "SQLITE_FORMAT"; break;
  147527. case SQLITE_RANGE: zName = "SQLITE_RANGE"; break;
  147528. case SQLITE_NOTADB: zName = "SQLITE_NOTADB"; break;
  147529. case SQLITE_ROW: zName = "SQLITE_ROW"; break;
  147530. case SQLITE_NOTICE: zName = "SQLITE_NOTICE"; break;
  147531. case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
  147532. case SQLITE_NOTICE_RECOVER_ROLLBACK:
  147533. zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
  147534. case SQLITE_WARNING: zName = "SQLITE_WARNING"; break;
  147535. case SQLITE_WARNING_AUTOINDEX: zName = "SQLITE_WARNING_AUTOINDEX"; break;
  147536. case SQLITE_DONE: zName = "SQLITE_DONE"; break;
  147537. }
  147538. }
  147539. if( zName==0 ){
  147540. static char zBuf[50];
  147541. sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
  147542. zName = zBuf;
  147543. }
  147544. return zName;
  147545. }
  147546. #endif
  147547. /*
  147548. ** Return a static string that describes the kind of error specified in the
  147549. ** argument.
  147550. */
  147551. SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
  147552. static const char* const aMsg[] = {
  147553. /* SQLITE_OK */ "not an error",
  147554. /* SQLITE_ERROR */ "SQL logic error",
  147555. /* SQLITE_INTERNAL */ 0,
  147556. /* SQLITE_PERM */ "access permission denied",
  147557. /* SQLITE_ABORT */ "query aborted",
  147558. /* SQLITE_BUSY */ "database is locked",
  147559. /* SQLITE_LOCKED */ "database table is locked",
  147560. /* SQLITE_NOMEM */ "out of memory",
  147561. /* SQLITE_READONLY */ "attempt to write a readonly database",
  147562. /* SQLITE_INTERRUPT */ "interrupted",
  147563. /* SQLITE_IOERR */ "disk I/O error",
  147564. /* SQLITE_CORRUPT */ "database disk image is malformed",
  147565. /* SQLITE_NOTFOUND */ "unknown operation",
  147566. /* SQLITE_FULL */ "database or disk is full",
  147567. /* SQLITE_CANTOPEN */ "unable to open database file",
  147568. /* SQLITE_PROTOCOL */ "locking protocol",
  147569. /* SQLITE_EMPTY */ 0,
  147570. /* SQLITE_SCHEMA */ "database schema has changed",
  147571. /* SQLITE_TOOBIG */ "string or blob too big",
  147572. /* SQLITE_CONSTRAINT */ "constraint failed",
  147573. /* SQLITE_MISMATCH */ "datatype mismatch",
  147574. /* SQLITE_MISUSE */ "bad parameter or other API misuse",
  147575. #ifdef SQLITE_DISABLE_LFS
  147576. /* SQLITE_NOLFS */ "large file support is disabled",
  147577. #else
  147578. /* SQLITE_NOLFS */ 0,
  147579. #endif
  147580. /* SQLITE_AUTH */ "authorization denied",
  147581. /* SQLITE_FORMAT */ 0,
  147582. /* SQLITE_RANGE */ "column index out of range",
  147583. /* SQLITE_NOTADB */ "file is not a database",
  147584. /* SQLITE_NOTICE */ "notification message",
  147585. /* SQLITE_WARNING */ "warning message",
  147586. };
  147587. const char *zErr = "unknown error";
  147588. switch( rc ){
  147589. case SQLITE_ABORT_ROLLBACK: {
  147590. zErr = "abort due to ROLLBACK";
  147591. break;
  147592. }
  147593. case SQLITE_ROW: {
  147594. zErr = "another row available";
  147595. break;
  147596. }
  147597. case SQLITE_DONE: {
  147598. zErr = "no more rows available";
  147599. break;
  147600. }
  147601. default: {
  147602. rc &= 0xff;
  147603. if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
  147604. zErr = aMsg[rc];
  147605. }
  147606. break;
  147607. }
  147608. }
  147609. return zErr;
  147610. }
  147611. /*
  147612. ** This routine implements a busy callback that sleeps and tries
  147613. ** again until a timeout value is reached. The timeout value is
  147614. ** an integer number of milliseconds passed in as the first
  147615. ** argument.
  147616. **
  147617. ** Return non-zero to retry the lock. Return zero to stop trying
  147618. ** and cause SQLite to return SQLITE_BUSY.
  147619. */
  147620. static int sqliteDefaultBusyCallback(
  147621. void *ptr, /* Database connection */
  147622. int count, /* Number of times table has been busy */
  147623. sqlite3_file *pFile /* The file on which the lock occurred */
  147624. ){
  147625. #if SQLITE_OS_WIN || HAVE_USLEEP
  147626. /* This case is for systems that have support for sleeping for fractions of
  147627. ** a second. Examples: All windows systems, unix systems with usleep() */
  147628. static const u8 delays[] =
  147629. { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 };
  147630. static const u8 totals[] =
  147631. { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 };
  147632. # define NDELAY ArraySize(delays)
  147633. sqlite3 *db = (sqlite3 *)ptr;
  147634. int tmout = db->busyTimeout;
  147635. int delay, prior;
  147636. #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
  147637. if( sqlite3OsFileControl(pFile,SQLITE_FCNTL_LOCK_TIMEOUT,&tmout)==SQLITE_OK ){
  147638. if( count ){
  147639. tmout = 0;
  147640. sqlite3OsFileControl(pFile, SQLITE_FCNTL_LOCK_TIMEOUT, &tmout);
  147641. return 0;
  147642. }else{
  147643. return 1;
  147644. }
  147645. }
  147646. #else
  147647. UNUSED_PARAMETER(pFile);
  147648. #endif
  147649. assert( count>=0 );
  147650. if( count < NDELAY ){
  147651. delay = delays[count];
  147652. prior = totals[count];
  147653. }else{
  147654. delay = delays[NDELAY-1];
  147655. prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
  147656. }
  147657. if( prior + delay > tmout ){
  147658. delay = tmout - prior;
  147659. if( delay<=0 ) return 0;
  147660. }
  147661. sqlite3OsSleep(db->pVfs, delay*1000);
  147662. return 1;
  147663. #else
  147664. /* This case for unix systems that lack usleep() support. Sleeping
  147665. ** must be done in increments of whole seconds */
  147666. sqlite3 *db = (sqlite3 *)ptr;
  147667. int tmout = ((sqlite3 *)ptr)->busyTimeout;
  147668. UNUSED_PARAMETER(pFile);
  147669. if( (count+1)*1000 > tmout ){
  147670. return 0;
  147671. }
  147672. sqlite3OsSleep(db->pVfs, 1000000);
  147673. return 1;
  147674. #endif
  147675. }
  147676. /*
  147677. ** Invoke the given busy handler.
  147678. **
  147679. ** This routine is called when an operation failed to acquire a
  147680. ** lock on VFS file pFile.
  147681. **
  147682. ** If this routine returns non-zero, the lock is retried. If it
  147683. ** returns 0, the operation aborts with an SQLITE_BUSY error.
  147684. */
  147685. SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p, sqlite3_file *pFile){
  147686. int rc;
  147687. if( p->xBusyHandler==0 || p->nBusy<0 ) return 0;
  147688. if( p->bExtraFileArg ){
  147689. /* Add an extra parameter with the pFile pointer to the end of the
  147690. ** callback argument list */
  147691. int (*xTra)(void*,int,sqlite3_file*);
  147692. xTra = (int(*)(void*,int,sqlite3_file*))p->xBusyHandler;
  147693. rc = xTra(p->pBusyArg, p->nBusy, pFile);
  147694. }else{
  147695. /* Legacy style busy handler callback */
  147696. rc = p->xBusyHandler(p->pBusyArg, p->nBusy);
  147697. }
  147698. if( rc==0 ){
  147699. p->nBusy = -1;
  147700. }else{
  147701. p->nBusy++;
  147702. }
  147703. return rc;
  147704. }
  147705. /*
  147706. ** This routine sets the busy callback for an Sqlite database to the
  147707. ** given callback function with the given argument.
  147708. */
  147709. SQLITE_API int sqlite3_busy_handler(
  147710. sqlite3 *db,
  147711. int (*xBusy)(void*,int),
  147712. void *pArg
  147713. ){
  147714. #ifdef SQLITE_ENABLE_API_ARMOR
  147715. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  147716. #endif
  147717. sqlite3_mutex_enter(db->mutex);
  147718. db->busyHandler.xBusyHandler = xBusy;
  147719. db->busyHandler.pBusyArg = pArg;
  147720. db->busyHandler.nBusy = 0;
  147721. db->busyHandler.bExtraFileArg = 0;
  147722. db->busyTimeout = 0;
  147723. sqlite3_mutex_leave(db->mutex);
  147724. return SQLITE_OK;
  147725. }
  147726. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  147727. /*
  147728. ** This routine sets the progress callback for an Sqlite database to the
  147729. ** given callback function with the given argument. The progress callback will
  147730. ** be invoked every nOps opcodes.
  147731. */
  147732. SQLITE_API void sqlite3_progress_handler(
  147733. sqlite3 *db,
  147734. int nOps,
  147735. int (*xProgress)(void*),
  147736. void *pArg
  147737. ){
  147738. #ifdef SQLITE_ENABLE_API_ARMOR
  147739. if( !sqlite3SafetyCheckOk(db) ){
  147740. (void)SQLITE_MISUSE_BKPT;
  147741. return;
  147742. }
  147743. #endif
  147744. sqlite3_mutex_enter(db->mutex);
  147745. if( nOps>0 ){
  147746. db->xProgress = xProgress;
  147747. db->nProgressOps = (unsigned)nOps;
  147748. db->pProgressArg = pArg;
  147749. }else{
  147750. db->xProgress = 0;
  147751. db->nProgressOps = 0;
  147752. db->pProgressArg = 0;
  147753. }
  147754. sqlite3_mutex_leave(db->mutex);
  147755. }
  147756. #endif
  147757. /*
  147758. ** This routine installs a default busy handler that waits for the
  147759. ** specified number of milliseconds before returning 0.
  147760. */
  147761. SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
  147762. #ifdef SQLITE_ENABLE_API_ARMOR
  147763. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  147764. #endif
  147765. if( ms>0 ){
  147766. sqlite3_busy_handler(db, (int(*)(void*,int))sqliteDefaultBusyCallback,
  147767. (void*)db);
  147768. db->busyTimeout = ms;
  147769. db->busyHandler.bExtraFileArg = 1;
  147770. }else{
  147771. sqlite3_busy_handler(db, 0, 0);
  147772. }
  147773. return SQLITE_OK;
  147774. }
  147775. /*
  147776. ** Cause any pending operation to stop at its earliest opportunity.
  147777. */
  147778. SQLITE_API void sqlite3_interrupt(sqlite3 *db){
  147779. #ifdef SQLITE_ENABLE_API_ARMOR
  147780. if( !sqlite3SafetyCheckOk(db) && (db==0 || db->magic!=SQLITE_MAGIC_ZOMBIE) ){
  147781. (void)SQLITE_MISUSE_BKPT;
  147782. return;
  147783. }
  147784. #endif
  147785. db->u1.isInterrupted = 1;
  147786. }
  147787. /*
  147788. ** This function is exactly the same as sqlite3_create_function(), except
  147789. ** that it is designed to be called by internal code. The difference is
  147790. ** that if a malloc() fails in sqlite3_create_function(), an error code
  147791. ** is returned and the mallocFailed flag cleared.
  147792. */
  147793. SQLITE_PRIVATE int sqlite3CreateFunc(
  147794. sqlite3 *db,
  147795. const char *zFunctionName,
  147796. int nArg,
  147797. int enc,
  147798. void *pUserData,
  147799. void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
  147800. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  147801. void (*xFinal)(sqlite3_context*),
  147802. void (*xValue)(sqlite3_context*),
  147803. void (*xInverse)(sqlite3_context*,int,sqlite3_value **),
  147804. FuncDestructor *pDestructor
  147805. ){
  147806. FuncDef *p;
  147807. int nName;
  147808. int extraFlags;
  147809. assert( sqlite3_mutex_held(db->mutex) );
  147810. assert( xValue==0 || xSFunc==0 );
  147811. if( zFunctionName==0 /* Must have a valid name */
  147812. || (xSFunc!=0 && xFinal!=0) /* Not both xSFunc and xFinal */
  147813. || ((xFinal==0)!=(xStep==0)) /* Both or neither of xFinal and xStep */
  147814. || ((xValue==0)!=(xInverse==0)) /* Both or neither of xValue, xInverse */
  147815. || (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG)
  147816. || (255<(nName = sqlite3Strlen30( zFunctionName)))
  147817. ){
  147818. return SQLITE_MISUSE_BKPT;
  147819. }
  147820. assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC );
  147821. extraFlags = enc & SQLITE_DETERMINISTIC;
  147822. enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY);
  147823. #ifndef SQLITE_OMIT_UTF16
  147824. /* If SQLITE_UTF16 is specified as the encoding type, transform this
  147825. ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
  147826. ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
  147827. **
  147828. ** If SQLITE_ANY is specified, add three versions of the function
  147829. ** to the hash table.
  147830. */
  147831. if( enc==SQLITE_UTF16 ){
  147832. enc = SQLITE_UTF16NATIVE;
  147833. }else if( enc==SQLITE_ANY ){
  147834. int rc;
  147835. rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8|extraFlags,
  147836. pUserData, xSFunc, xStep, xFinal, xValue, xInverse, pDestructor);
  147837. if( rc==SQLITE_OK ){
  147838. rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE|extraFlags,
  147839. pUserData, xSFunc, xStep, xFinal, xValue, xInverse, pDestructor);
  147840. }
  147841. if( rc!=SQLITE_OK ){
  147842. return rc;
  147843. }
  147844. enc = SQLITE_UTF16BE;
  147845. }
  147846. #else
  147847. enc = SQLITE_UTF8;
  147848. #endif
  147849. /* Check if an existing function is being overridden or deleted. If so,
  147850. ** and there are active VMs, then return SQLITE_BUSY. If a function
  147851. ** is being overridden/deleted but there are no active VMs, allow the
  147852. ** operation to continue but invalidate all precompiled statements.
  147853. */
  147854. p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 0);
  147855. if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==(u32)enc && p->nArg==nArg ){
  147856. if( db->nVdbeActive ){
  147857. sqlite3ErrorWithMsg(db, SQLITE_BUSY,
  147858. "unable to delete/modify user-function due to active statements");
  147859. assert( !db->mallocFailed );
  147860. return SQLITE_BUSY;
  147861. }else{
  147862. sqlite3ExpirePreparedStatements(db, 0);
  147863. }
  147864. }
  147865. p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 1);
  147866. assert(p || db->mallocFailed);
  147867. if( !p ){
  147868. return SQLITE_NOMEM_BKPT;
  147869. }
  147870. /* If an older version of the function with a configured destructor is
  147871. ** being replaced invoke the destructor function here. */
  147872. functionDestroy(db, p);
  147873. if( pDestructor ){
  147874. pDestructor->nRef++;
  147875. }
  147876. p->u.pDestructor = pDestructor;
  147877. p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags;
  147878. testcase( p->funcFlags & SQLITE_DETERMINISTIC );
  147879. p->xSFunc = xSFunc ? xSFunc : xStep;
  147880. p->xFinalize = xFinal;
  147881. p->xValue = xValue;
  147882. p->xInverse = xInverse;
  147883. p->pUserData = pUserData;
  147884. p->nArg = (u16)nArg;
  147885. return SQLITE_OK;
  147886. }
  147887. /*
  147888. ** Worker function used by utf-8 APIs that create new functions:
  147889. **
  147890. ** sqlite3_create_function()
  147891. ** sqlite3_create_function_v2()
  147892. ** sqlite3_create_window_function()
  147893. */
  147894. static int createFunctionApi(
  147895. sqlite3 *db,
  147896. const char *zFunc,
  147897. int nArg,
  147898. int enc,
  147899. void *p,
  147900. void (*xSFunc)(sqlite3_context*,int,sqlite3_value**),
  147901. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  147902. void (*xFinal)(sqlite3_context*),
  147903. void (*xValue)(sqlite3_context*),
  147904. void (*xInverse)(sqlite3_context*,int,sqlite3_value**),
  147905. void(*xDestroy)(void*)
  147906. ){
  147907. int rc = SQLITE_ERROR;
  147908. FuncDestructor *pArg = 0;
  147909. #ifdef SQLITE_ENABLE_API_ARMOR
  147910. if( !sqlite3SafetyCheckOk(db) ){
  147911. return SQLITE_MISUSE_BKPT;
  147912. }
  147913. #endif
  147914. sqlite3_mutex_enter(db->mutex);
  147915. if( xDestroy ){
  147916. pArg = (FuncDestructor *)sqlite3Malloc(sizeof(FuncDestructor));
  147917. if( !pArg ){
  147918. sqlite3OomFault(db);
  147919. xDestroy(p);
  147920. goto out;
  147921. }
  147922. pArg->nRef = 0;
  147923. pArg->xDestroy = xDestroy;
  147924. pArg->pUserData = p;
  147925. }
  147926. rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p,
  147927. xSFunc, xStep, xFinal, xValue, xInverse, pArg
  147928. );
  147929. if( pArg && pArg->nRef==0 ){
  147930. assert( rc!=SQLITE_OK );
  147931. xDestroy(p);
  147932. sqlite3_free(pArg);
  147933. }
  147934. out:
  147935. rc = sqlite3ApiExit(db, rc);
  147936. sqlite3_mutex_leave(db->mutex);
  147937. return rc;
  147938. }
  147939. /*
  147940. ** Create new user functions.
  147941. */
  147942. SQLITE_API int sqlite3_create_function(
  147943. sqlite3 *db,
  147944. const char *zFunc,
  147945. int nArg,
  147946. int enc,
  147947. void *p,
  147948. void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
  147949. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  147950. void (*xFinal)(sqlite3_context*)
  147951. ){
  147952. return createFunctionApi(db, zFunc, nArg, enc, p, xSFunc, xStep,
  147953. xFinal, 0, 0, 0);
  147954. }
  147955. SQLITE_API int sqlite3_create_function_v2(
  147956. sqlite3 *db,
  147957. const char *zFunc,
  147958. int nArg,
  147959. int enc,
  147960. void *p,
  147961. void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
  147962. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  147963. void (*xFinal)(sqlite3_context*),
  147964. void (*xDestroy)(void *)
  147965. ){
  147966. return createFunctionApi(db, zFunc, nArg, enc, p, xSFunc, xStep,
  147967. xFinal, 0, 0, xDestroy);
  147968. }
  147969. SQLITE_API int sqlite3_create_window_function(
  147970. sqlite3 *db,
  147971. const char *zFunc,
  147972. int nArg,
  147973. int enc,
  147974. void *p,
  147975. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  147976. void (*xFinal)(sqlite3_context*),
  147977. void (*xValue)(sqlite3_context*),
  147978. void (*xInverse)(sqlite3_context*,int,sqlite3_value **),
  147979. void (*xDestroy)(void *)
  147980. ){
  147981. return createFunctionApi(db, zFunc, nArg, enc, p, 0, xStep,
  147982. xFinal, xValue, xInverse, xDestroy);
  147983. }
  147984. #ifndef SQLITE_OMIT_UTF16
  147985. SQLITE_API int sqlite3_create_function16(
  147986. sqlite3 *db,
  147987. const void *zFunctionName,
  147988. int nArg,
  147989. int eTextRep,
  147990. void *p,
  147991. void (*xSFunc)(sqlite3_context*,int,sqlite3_value**),
  147992. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  147993. void (*xFinal)(sqlite3_context*)
  147994. ){
  147995. int rc;
  147996. char *zFunc8;
  147997. #ifdef SQLITE_ENABLE_API_ARMOR
  147998. if( !sqlite3SafetyCheckOk(db) || zFunctionName==0 ) return SQLITE_MISUSE_BKPT;
  147999. #endif
  148000. sqlite3_mutex_enter(db->mutex);
  148001. assert( !db->mallocFailed );
  148002. zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
  148003. rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xSFunc,xStep,xFinal,0,0,0);
  148004. sqlite3DbFree(db, zFunc8);
  148005. rc = sqlite3ApiExit(db, rc);
  148006. sqlite3_mutex_leave(db->mutex);
  148007. return rc;
  148008. }
  148009. #endif
  148010. /*
  148011. ** The following is the implementation of an SQL function that always
  148012. ** fails with an error message stating that the function is used in the
  148013. ** wrong context. The sqlite3_overload_function() API might construct
  148014. ** SQL function that use this routine so that the functions will exist
  148015. ** for name resolution but are actually overloaded by the xFindFunction
  148016. ** method of virtual tables.
  148017. */
  148018. static void sqlite3InvalidFunction(
  148019. sqlite3_context *context, /* The function calling context */
  148020. int NotUsed, /* Number of arguments to the function */
  148021. sqlite3_value **NotUsed2 /* Value of each argument */
  148022. ){
  148023. const char *zName = (const char*)sqlite3_user_data(context);
  148024. char *zErr;
  148025. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  148026. zErr = sqlite3_mprintf(
  148027. "unable to use function %s in the requested context", zName);
  148028. sqlite3_result_error(context, zErr, -1);
  148029. sqlite3_free(zErr);
  148030. }
  148031. /*
  148032. ** Declare that a function has been overloaded by a virtual table.
  148033. **
  148034. ** If the function already exists as a regular global function, then
  148035. ** this routine is a no-op. If the function does not exist, then create
  148036. ** a new one that always throws a run-time error.
  148037. **
  148038. ** When virtual tables intend to provide an overloaded function, they
  148039. ** should call this routine to make sure the global function exists.
  148040. ** A global function must exist in order for name resolution to work
  148041. ** properly.
  148042. */
  148043. SQLITE_API int sqlite3_overload_function(
  148044. sqlite3 *db,
  148045. const char *zName,
  148046. int nArg
  148047. ){
  148048. int rc;
  148049. char *zCopy;
  148050. #ifdef SQLITE_ENABLE_API_ARMOR
  148051. if( !sqlite3SafetyCheckOk(db) || zName==0 || nArg<-2 ){
  148052. return SQLITE_MISUSE_BKPT;
  148053. }
  148054. #endif
  148055. sqlite3_mutex_enter(db->mutex);
  148056. rc = sqlite3FindFunction(db, zName, nArg, SQLITE_UTF8, 0)!=0;
  148057. sqlite3_mutex_leave(db->mutex);
  148058. if( rc ) return SQLITE_OK;
  148059. zCopy = sqlite3_mprintf(zName);
  148060. if( zCopy==0 ) return SQLITE_NOMEM;
  148061. return sqlite3_create_function_v2(db, zName, nArg, SQLITE_UTF8,
  148062. zCopy, sqlite3InvalidFunction, 0, 0, sqlite3_free);
  148063. }
  148064. #ifndef SQLITE_OMIT_TRACE
  148065. /*
  148066. ** Register a trace function. The pArg from the previously registered trace
  148067. ** is returned.
  148068. **
  148069. ** A NULL trace function means that no tracing is executes. A non-NULL
  148070. ** trace is a pointer to a function that is invoked at the start of each
  148071. ** SQL statement.
  148072. */
  148073. #ifndef SQLITE_OMIT_DEPRECATED
  148074. SQLITE_API void *sqlite3_trace(sqlite3 *db, void(*xTrace)(void*,const char*), void *pArg){
  148075. void *pOld;
  148076. #ifdef SQLITE_ENABLE_API_ARMOR
  148077. if( !sqlite3SafetyCheckOk(db) ){
  148078. (void)SQLITE_MISUSE_BKPT;
  148079. return 0;
  148080. }
  148081. #endif
  148082. sqlite3_mutex_enter(db->mutex);
  148083. pOld = db->pTraceArg;
  148084. db->mTrace = xTrace ? SQLITE_TRACE_LEGACY : 0;
  148085. db->xTrace = (int(*)(u32,void*,void*,void*))xTrace;
  148086. db->pTraceArg = pArg;
  148087. sqlite3_mutex_leave(db->mutex);
  148088. return pOld;
  148089. }
  148090. #endif /* SQLITE_OMIT_DEPRECATED */
  148091. /* Register a trace callback using the version-2 interface.
  148092. */
  148093. SQLITE_API int sqlite3_trace_v2(
  148094. sqlite3 *db, /* Trace this connection */
  148095. unsigned mTrace, /* Mask of events to be traced */
  148096. int(*xTrace)(unsigned,void*,void*,void*), /* Callback to invoke */
  148097. void *pArg /* Context */
  148098. ){
  148099. #ifdef SQLITE_ENABLE_API_ARMOR
  148100. if( !sqlite3SafetyCheckOk(db) ){
  148101. return SQLITE_MISUSE_BKPT;
  148102. }
  148103. #endif
  148104. sqlite3_mutex_enter(db->mutex);
  148105. if( mTrace==0 ) xTrace = 0;
  148106. if( xTrace==0 ) mTrace = 0;
  148107. db->mTrace = mTrace;
  148108. db->xTrace = xTrace;
  148109. db->pTraceArg = pArg;
  148110. sqlite3_mutex_leave(db->mutex);
  148111. return SQLITE_OK;
  148112. }
  148113. #ifndef SQLITE_OMIT_DEPRECATED
  148114. /*
  148115. ** Register a profile function. The pArg from the previously registered
  148116. ** profile function is returned.
  148117. **
  148118. ** A NULL profile function means that no profiling is executes. A non-NULL
  148119. ** profile is a pointer to a function that is invoked at the conclusion of
  148120. ** each SQL statement that is run.
  148121. */
  148122. SQLITE_API void *sqlite3_profile(
  148123. sqlite3 *db,
  148124. void (*xProfile)(void*,const char*,sqlite_uint64),
  148125. void *pArg
  148126. ){
  148127. void *pOld;
  148128. #ifdef SQLITE_ENABLE_API_ARMOR
  148129. if( !sqlite3SafetyCheckOk(db) ){
  148130. (void)SQLITE_MISUSE_BKPT;
  148131. return 0;
  148132. }
  148133. #endif
  148134. sqlite3_mutex_enter(db->mutex);
  148135. pOld = db->pProfileArg;
  148136. db->xProfile = xProfile;
  148137. db->pProfileArg = pArg;
  148138. db->mTrace &= SQLITE_TRACE_NONLEGACY_MASK;
  148139. if( db->xProfile ) db->mTrace |= SQLITE_TRACE_XPROFILE;
  148140. sqlite3_mutex_leave(db->mutex);
  148141. return pOld;
  148142. }
  148143. #endif /* SQLITE_OMIT_DEPRECATED */
  148144. #endif /* SQLITE_OMIT_TRACE */
  148145. /*
  148146. ** Register a function to be invoked when a transaction commits.
  148147. ** If the invoked function returns non-zero, then the commit becomes a
  148148. ** rollback.
  148149. */
  148150. SQLITE_API void *sqlite3_commit_hook(
  148151. sqlite3 *db, /* Attach the hook to this database */
  148152. int (*xCallback)(void*), /* Function to invoke on each commit */
  148153. void *pArg /* Argument to the function */
  148154. ){
  148155. void *pOld;
  148156. #ifdef SQLITE_ENABLE_API_ARMOR
  148157. if( !sqlite3SafetyCheckOk(db) ){
  148158. (void)SQLITE_MISUSE_BKPT;
  148159. return 0;
  148160. }
  148161. #endif
  148162. sqlite3_mutex_enter(db->mutex);
  148163. pOld = db->pCommitArg;
  148164. db->xCommitCallback = xCallback;
  148165. db->pCommitArg = pArg;
  148166. sqlite3_mutex_leave(db->mutex);
  148167. return pOld;
  148168. }
  148169. /*
  148170. ** Register a callback to be invoked each time a row is updated,
  148171. ** inserted or deleted using this database connection.
  148172. */
  148173. SQLITE_API void *sqlite3_update_hook(
  148174. sqlite3 *db, /* Attach the hook to this database */
  148175. void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
  148176. void *pArg /* Argument to the function */
  148177. ){
  148178. void *pRet;
  148179. #ifdef SQLITE_ENABLE_API_ARMOR
  148180. if( !sqlite3SafetyCheckOk(db) ){
  148181. (void)SQLITE_MISUSE_BKPT;
  148182. return 0;
  148183. }
  148184. #endif
  148185. sqlite3_mutex_enter(db->mutex);
  148186. pRet = db->pUpdateArg;
  148187. db->xUpdateCallback = xCallback;
  148188. db->pUpdateArg = pArg;
  148189. sqlite3_mutex_leave(db->mutex);
  148190. return pRet;
  148191. }
  148192. /*
  148193. ** Register a callback to be invoked each time a transaction is rolled
  148194. ** back by this database connection.
  148195. */
  148196. SQLITE_API void *sqlite3_rollback_hook(
  148197. sqlite3 *db, /* Attach the hook to this database */
  148198. void (*xCallback)(void*), /* Callback function */
  148199. void *pArg /* Argument to the function */
  148200. ){
  148201. void *pRet;
  148202. #ifdef SQLITE_ENABLE_API_ARMOR
  148203. if( !sqlite3SafetyCheckOk(db) ){
  148204. (void)SQLITE_MISUSE_BKPT;
  148205. return 0;
  148206. }
  148207. #endif
  148208. sqlite3_mutex_enter(db->mutex);
  148209. pRet = db->pRollbackArg;
  148210. db->xRollbackCallback = xCallback;
  148211. db->pRollbackArg = pArg;
  148212. sqlite3_mutex_leave(db->mutex);
  148213. return pRet;
  148214. }
  148215. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  148216. /*
  148217. ** Register a callback to be invoked each time a row is updated,
  148218. ** inserted or deleted using this database connection.
  148219. */
  148220. SQLITE_API void *sqlite3_preupdate_hook(
  148221. sqlite3 *db, /* Attach the hook to this database */
  148222. void(*xCallback)( /* Callback function */
  148223. void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64),
  148224. void *pArg /* First callback argument */
  148225. ){
  148226. void *pRet;
  148227. sqlite3_mutex_enter(db->mutex);
  148228. pRet = db->pPreUpdateArg;
  148229. db->xPreUpdateCallback = xCallback;
  148230. db->pPreUpdateArg = pArg;
  148231. sqlite3_mutex_leave(db->mutex);
  148232. return pRet;
  148233. }
  148234. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  148235. #ifndef SQLITE_OMIT_WAL
  148236. /*
  148237. ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
  148238. ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
  148239. ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
  148240. ** wal_autocheckpoint()).
  148241. */
  148242. SQLITE_PRIVATE int sqlite3WalDefaultHook(
  148243. void *pClientData, /* Argument */
  148244. sqlite3 *db, /* Connection */
  148245. const char *zDb, /* Database */
  148246. int nFrame /* Size of WAL */
  148247. ){
  148248. if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
  148249. sqlite3BeginBenignMalloc();
  148250. sqlite3_wal_checkpoint(db, zDb);
  148251. sqlite3EndBenignMalloc();
  148252. }
  148253. return SQLITE_OK;
  148254. }
  148255. #endif /* SQLITE_OMIT_WAL */
  148256. /*
  148257. ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
  148258. ** a database after committing a transaction if there are nFrame or
  148259. ** more frames in the log file. Passing zero or a negative value as the
  148260. ** nFrame parameter disables automatic checkpoints entirely.
  148261. **
  148262. ** The callback registered by this function replaces any existing callback
  148263. ** registered using sqlite3_wal_hook(). Likewise, registering a callback
  148264. ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
  148265. ** configured by this function.
  148266. */
  148267. SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
  148268. #ifdef SQLITE_OMIT_WAL
  148269. UNUSED_PARAMETER(db);
  148270. UNUSED_PARAMETER(nFrame);
  148271. #else
  148272. #ifdef SQLITE_ENABLE_API_ARMOR
  148273. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  148274. #endif
  148275. if( nFrame>0 ){
  148276. sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
  148277. }else{
  148278. sqlite3_wal_hook(db, 0, 0);
  148279. }
  148280. #endif
  148281. return SQLITE_OK;
  148282. }
  148283. /*
  148284. ** Register a callback to be invoked each time a transaction is written
  148285. ** into the write-ahead-log by this database connection.
  148286. */
  148287. SQLITE_API void *sqlite3_wal_hook(
  148288. sqlite3 *db, /* Attach the hook to this db handle */
  148289. int(*xCallback)(void *, sqlite3*, const char*, int),
  148290. void *pArg /* First argument passed to xCallback() */
  148291. ){
  148292. #ifndef SQLITE_OMIT_WAL
  148293. void *pRet;
  148294. #ifdef SQLITE_ENABLE_API_ARMOR
  148295. if( !sqlite3SafetyCheckOk(db) ){
  148296. (void)SQLITE_MISUSE_BKPT;
  148297. return 0;
  148298. }
  148299. #endif
  148300. sqlite3_mutex_enter(db->mutex);
  148301. pRet = db->pWalArg;
  148302. db->xWalCallback = xCallback;
  148303. db->pWalArg = pArg;
  148304. sqlite3_mutex_leave(db->mutex);
  148305. return pRet;
  148306. #else
  148307. return 0;
  148308. #endif
  148309. }
  148310. /*
  148311. ** Checkpoint database zDb.
  148312. */
  148313. SQLITE_API int sqlite3_wal_checkpoint_v2(
  148314. sqlite3 *db, /* Database handle */
  148315. const char *zDb, /* Name of attached database (or NULL) */
  148316. int eMode, /* SQLITE_CHECKPOINT_* value */
  148317. int *pnLog, /* OUT: Size of WAL log in frames */
  148318. int *pnCkpt /* OUT: Total number of frames checkpointed */
  148319. ){
  148320. #ifdef SQLITE_OMIT_WAL
  148321. return SQLITE_OK;
  148322. #else
  148323. int rc; /* Return code */
  148324. int iDb = SQLITE_MAX_ATTACHED; /* sqlite3.aDb[] index of db to checkpoint */
  148325. #ifdef SQLITE_ENABLE_API_ARMOR
  148326. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  148327. #endif
  148328. /* Initialize the output variables to -1 in case an error occurs. */
  148329. if( pnLog ) *pnLog = -1;
  148330. if( pnCkpt ) *pnCkpt = -1;
  148331. assert( SQLITE_CHECKPOINT_PASSIVE==0 );
  148332. assert( SQLITE_CHECKPOINT_FULL==1 );
  148333. assert( SQLITE_CHECKPOINT_RESTART==2 );
  148334. assert( SQLITE_CHECKPOINT_TRUNCATE==3 );
  148335. if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_TRUNCATE ){
  148336. /* EVIDENCE-OF: R-03996-12088 The M parameter must be a valid checkpoint
  148337. ** mode: */
  148338. return SQLITE_MISUSE;
  148339. }
  148340. sqlite3_mutex_enter(db->mutex);
  148341. if( zDb && zDb[0] ){
  148342. iDb = sqlite3FindDbName(db, zDb);
  148343. }
  148344. if( iDb<0 ){
  148345. rc = SQLITE_ERROR;
  148346. sqlite3ErrorWithMsg(db, SQLITE_ERROR, "unknown database: %s", zDb);
  148347. }else{
  148348. db->busyHandler.nBusy = 0;
  148349. rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
  148350. sqlite3Error(db, rc);
  148351. }
  148352. rc = sqlite3ApiExit(db, rc);
  148353. /* If there are no active statements, clear the interrupt flag at this
  148354. ** point. */
  148355. if( db->nVdbeActive==0 ){
  148356. db->u1.isInterrupted = 0;
  148357. }
  148358. sqlite3_mutex_leave(db->mutex);
  148359. return rc;
  148360. #endif
  148361. }
  148362. /*
  148363. ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
  148364. ** to contains a zero-length string, all attached databases are
  148365. ** checkpointed.
  148366. */
  148367. SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
  148368. /* EVIDENCE-OF: R-41613-20553 The sqlite3_wal_checkpoint(D,X) is equivalent to
  148369. ** sqlite3_wal_checkpoint_v2(D,X,SQLITE_CHECKPOINT_PASSIVE,0,0). */
  148370. return sqlite3_wal_checkpoint_v2(db,zDb,SQLITE_CHECKPOINT_PASSIVE,0,0);
  148371. }
  148372. #ifndef SQLITE_OMIT_WAL
  148373. /*
  148374. ** Run a checkpoint on database iDb. This is a no-op if database iDb is
  148375. ** not currently open in WAL mode.
  148376. **
  148377. ** If a transaction is open on the database being checkpointed, this
  148378. ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
  148379. ** an error occurs while running the checkpoint, an SQLite error code is
  148380. ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
  148381. **
  148382. ** The mutex on database handle db should be held by the caller. The mutex
  148383. ** associated with the specific b-tree being checkpointed is taken by
  148384. ** this function while the checkpoint is running.
  148385. **
  148386. ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
  148387. ** checkpointed. If an error is encountered it is returned immediately -
  148388. ** no attempt is made to checkpoint any remaining databases.
  148389. **
  148390. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL, RESTART
  148391. ** or TRUNCATE.
  148392. */
  148393. SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
  148394. int rc = SQLITE_OK; /* Return code */
  148395. int i; /* Used to iterate through attached dbs */
  148396. int bBusy = 0; /* True if SQLITE_BUSY has been encountered */
  148397. assert( sqlite3_mutex_held(db->mutex) );
  148398. assert( !pnLog || *pnLog==-1 );
  148399. assert( !pnCkpt || *pnCkpt==-1 );
  148400. for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
  148401. if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
  148402. rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
  148403. pnLog = 0;
  148404. pnCkpt = 0;
  148405. if( rc==SQLITE_BUSY ){
  148406. bBusy = 1;
  148407. rc = SQLITE_OK;
  148408. }
  148409. }
  148410. }
  148411. return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
  148412. }
  148413. #endif /* SQLITE_OMIT_WAL */
  148414. /*
  148415. ** This function returns true if main-memory should be used instead of
  148416. ** a temporary file for transient pager files and statement journals.
  148417. ** The value returned depends on the value of db->temp_store (runtime
  148418. ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
  148419. ** following table describes the relationship between these two values
  148420. ** and this functions return value.
  148421. **
  148422. ** SQLITE_TEMP_STORE db->temp_store Location of temporary database
  148423. ** ----------------- -------------- ------------------------------
  148424. ** 0 any file (return 0)
  148425. ** 1 1 file (return 0)
  148426. ** 1 2 memory (return 1)
  148427. ** 1 0 file (return 0)
  148428. ** 2 1 file (return 0)
  148429. ** 2 2 memory (return 1)
  148430. ** 2 0 memory (return 1)
  148431. ** 3 any memory (return 1)
  148432. */
  148433. SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
  148434. #if SQLITE_TEMP_STORE==1
  148435. return ( db->temp_store==2 );
  148436. #endif
  148437. #if SQLITE_TEMP_STORE==2
  148438. return ( db->temp_store!=1 );
  148439. #endif
  148440. #if SQLITE_TEMP_STORE==3
  148441. UNUSED_PARAMETER(db);
  148442. return 1;
  148443. #endif
  148444. #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
  148445. UNUSED_PARAMETER(db);
  148446. return 0;
  148447. #endif
  148448. }
  148449. /*
  148450. ** Return UTF-8 encoded English language explanation of the most recent
  148451. ** error.
  148452. */
  148453. SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
  148454. const char *z;
  148455. if( !db ){
  148456. return sqlite3ErrStr(SQLITE_NOMEM_BKPT);
  148457. }
  148458. if( !sqlite3SafetyCheckSickOrOk(db) ){
  148459. return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
  148460. }
  148461. sqlite3_mutex_enter(db->mutex);
  148462. if( db->mallocFailed ){
  148463. z = sqlite3ErrStr(SQLITE_NOMEM_BKPT);
  148464. }else{
  148465. testcase( db->pErr==0 );
  148466. z = db->errCode ? (char*)sqlite3_value_text(db->pErr) : 0;
  148467. assert( !db->mallocFailed );
  148468. if( z==0 ){
  148469. z = sqlite3ErrStr(db->errCode);
  148470. }
  148471. }
  148472. sqlite3_mutex_leave(db->mutex);
  148473. return z;
  148474. }
  148475. #ifndef SQLITE_OMIT_UTF16
  148476. /*
  148477. ** Return UTF-16 encoded English language explanation of the most recent
  148478. ** error.
  148479. */
  148480. SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
  148481. static const u16 outOfMem[] = {
  148482. 'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
  148483. };
  148484. static const u16 misuse[] = {
  148485. 'b', 'a', 'd', ' ', 'p', 'a', 'r', 'a', 'm', 'e', 't', 'e', 'r', ' ',
  148486. 'o', 'r', ' ', 'o', 't', 'h', 'e', 'r', ' ', 'A', 'P', 'I', ' ',
  148487. 'm', 'i', 's', 'u', 's', 'e', 0
  148488. };
  148489. const void *z;
  148490. if( !db ){
  148491. return (void *)outOfMem;
  148492. }
  148493. if( !sqlite3SafetyCheckSickOrOk(db) ){
  148494. return (void *)misuse;
  148495. }
  148496. sqlite3_mutex_enter(db->mutex);
  148497. if( db->mallocFailed ){
  148498. z = (void *)outOfMem;
  148499. }else{
  148500. z = sqlite3_value_text16(db->pErr);
  148501. if( z==0 ){
  148502. sqlite3ErrorWithMsg(db, db->errCode, sqlite3ErrStr(db->errCode));
  148503. z = sqlite3_value_text16(db->pErr);
  148504. }
  148505. /* A malloc() may have failed within the call to sqlite3_value_text16()
  148506. ** above. If this is the case, then the db->mallocFailed flag needs to
  148507. ** be cleared before returning. Do this directly, instead of via
  148508. ** sqlite3ApiExit(), to avoid setting the database handle error message.
  148509. */
  148510. sqlite3OomClear(db);
  148511. }
  148512. sqlite3_mutex_leave(db->mutex);
  148513. return z;
  148514. }
  148515. #endif /* SQLITE_OMIT_UTF16 */
  148516. /*
  148517. ** Return the most recent error code generated by an SQLite routine. If NULL is
  148518. ** passed to this function, we assume a malloc() failed during sqlite3_open().
  148519. */
  148520. SQLITE_API int sqlite3_errcode(sqlite3 *db){
  148521. if( db && !sqlite3SafetyCheckSickOrOk(db) ){
  148522. return SQLITE_MISUSE_BKPT;
  148523. }
  148524. if( !db || db->mallocFailed ){
  148525. return SQLITE_NOMEM_BKPT;
  148526. }
  148527. return db->errCode & db->errMask;
  148528. }
  148529. SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
  148530. if( db && !sqlite3SafetyCheckSickOrOk(db) ){
  148531. return SQLITE_MISUSE_BKPT;
  148532. }
  148533. if( !db || db->mallocFailed ){
  148534. return SQLITE_NOMEM_BKPT;
  148535. }
  148536. return db->errCode;
  148537. }
  148538. SQLITE_API int sqlite3_system_errno(sqlite3 *db){
  148539. return db ? db->iSysErrno : 0;
  148540. }
  148541. /*
  148542. ** Return a string that describes the kind of error specified in the
  148543. ** argument. For now, this simply calls the internal sqlite3ErrStr()
  148544. ** function.
  148545. */
  148546. SQLITE_API const char *sqlite3_errstr(int rc){
  148547. return sqlite3ErrStr(rc);
  148548. }
  148549. /*
  148550. ** Create a new collating function for database "db". The name is zName
  148551. ** and the encoding is enc.
  148552. */
  148553. static int createCollation(
  148554. sqlite3* db,
  148555. const char *zName,
  148556. u8 enc,
  148557. void* pCtx,
  148558. int(*xCompare)(void*,int,const void*,int,const void*),
  148559. void(*xDel)(void*)
  148560. ){
  148561. CollSeq *pColl;
  148562. int enc2;
  148563. assert( sqlite3_mutex_held(db->mutex) );
  148564. /* If SQLITE_UTF16 is specified as the encoding type, transform this
  148565. ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
  148566. ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
  148567. */
  148568. enc2 = enc;
  148569. testcase( enc2==SQLITE_UTF16 );
  148570. testcase( enc2==SQLITE_UTF16_ALIGNED );
  148571. if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
  148572. enc2 = SQLITE_UTF16NATIVE;
  148573. }
  148574. if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
  148575. return SQLITE_MISUSE_BKPT;
  148576. }
  148577. /* Check if this call is removing or replacing an existing collation
  148578. ** sequence. If so, and there are active VMs, return busy. If there
  148579. ** are no active VMs, invalidate any pre-compiled statements.
  148580. */
  148581. pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
  148582. if( pColl && pColl->xCmp ){
  148583. if( db->nVdbeActive ){
  148584. sqlite3ErrorWithMsg(db, SQLITE_BUSY,
  148585. "unable to delete/modify collation sequence due to active statements");
  148586. return SQLITE_BUSY;
  148587. }
  148588. sqlite3ExpirePreparedStatements(db, 0);
  148589. /* If collation sequence pColl was created directly by a call to
  148590. ** sqlite3_create_collation, and not generated by synthCollSeq(),
  148591. ** then any copies made by synthCollSeq() need to be invalidated.
  148592. ** Also, collation destructor - CollSeq.xDel() - function may need
  148593. ** to be called.
  148594. */
  148595. if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
  148596. CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName);
  148597. int j;
  148598. for(j=0; j<3; j++){
  148599. CollSeq *p = &aColl[j];
  148600. if( p->enc==pColl->enc ){
  148601. if( p->xDel ){
  148602. p->xDel(p->pUser);
  148603. }
  148604. p->xCmp = 0;
  148605. }
  148606. }
  148607. }
  148608. }
  148609. pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
  148610. if( pColl==0 ) return SQLITE_NOMEM_BKPT;
  148611. pColl->xCmp = xCompare;
  148612. pColl->pUser = pCtx;
  148613. pColl->xDel = xDel;
  148614. pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
  148615. sqlite3Error(db, SQLITE_OK);
  148616. return SQLITE_OK;
  148617. }
  148618. /*
  148619. ** This array defines hard upper bounds on limit values. The
  148620. ** initializer must be kept in sync with the SQLITE_LIMIT_*
  148621. ** #defines in sqlite3.h.
  148622. */
  148623. static const int aHardLimit[] = {
  148624. SQLITE_MAX_LENGTH,
  148625. SQLITE_MAX_SQL_LENGTH,
  148626. SQLITE_MAX_COLUMN,
  148627. SQLITE_MAX_EXPR_DEPTH,
  148628. SQLITE_MAX_COMPOUND_SELECT,
  148629. SQLITE_MAX_VDBE_OP,
  148630. SQLITE_MAX_FUNCTION_ARG,
  148631. SQLITE_MAX_ATTACHED,
  148632. SQLITE_MAX_LIKE_PATTERN_LENGTH,
  148633. SQLITE_MAX_VARIABLE_NUMBER, /* IMP: R-38091-32352 */
  148634. SQLITE_MAX_TRIGGER_DEPTH,
  148635. SQLITE_MAX_WORKER_THREADS,
  148636. };
  148637. /*
  148638. ** Make sure the hard limits are set to reasonable values
  148639. */
  148640. #if SQLITE_MAX_LENGTH<100
  148641. # error SQLITE_MAX_LENGTH must be at least 100
  148642. #endif
  148643. #if SQLITE_MAX_SQL_LENGTH<100
  148644. # error SQLITE_MAX_SQL_LENGTH must be at least 100
  148645. #endif
  148646. #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
  148647. # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
  148648. #endif
  148649. #if SQLITE_MAX_COMPOUND_SELECT<2
  148650. # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
  148651. #endif
  148652. #if SQLITE_MAX_VDBE_OP<40
  148653. # error SQLITE_MAX_VDBE_OP must be at least 40
  148654. #endif
  148655. #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>127
  148656. # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 127
  148657. #endif
  148658. #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125
  148659. # error SQLITE_MAX_ATTACHED must be between 0 and 125
  148660. #endif
  148661. #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
  148662. # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
  148663. #endif
  148664. #if SQLITE_MAX_COLUMN>32767
  148665. # error SQLITE_MAX_COLUMN must not exceed 32767
  148666. #endif
  148667. #if SQLITE_MAX_TRIGGER_DEPTH<1
  148668. # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
  148669. #endif
  148670. #if SQLITE_MAX_WORKER_THREADS<0 || SQLITE_MAX_WORKER_THREADS>50
  148671. # error SQLITE_MAX_WORKER_THREADS must be between 0 and 50
  148672. #endif
  148673. /*
  148674. ** Change the value of a limit. Report the old value.
  148675. ** If an invalid limit index is supplied, report -1.
  148676. ** Make no changes but still report the old value if the
  148677. ** new limit is negative.
  148678. **
  148679. ** A new lower limit does not shrink existing constructs.
  148680. ** It merely prevents new constructs that exceed the limit
  148681. ** from forming.
  148682. */
  148683. SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
  148684. int oldLimit;
  148685. #ifdef SQLITE_ENABLE_API_ARMOR
  148686. if( !sqlite3SafetyCheckOk(db) ){
  148687. (void)SQLITE_MISUSE_BKPT;
  148688. return -1;
  148689. }
  148690. #endif
  148691. /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
  148692. ** there is a hard upper bound set at compile-time by a C preprocessor
  148693. ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
  148694. ** "_MAX_".)
  148695. */
  148696. assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
  148697. assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
  148698. assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
  148699. assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
  148700. assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
  148701. assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
  148702. assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
  148703. assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
  148704. assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
  148705. SQLITE_MAX_LIKE_PATTERN_LENGTH );
  148706. assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
  148707. assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
  148708. assert( aHardLimit[SQLITE_LIMIT_WORKER_THREADS]==SQLITE_MAX_WORKER_THREADS );
  148709. assert( SQLITE_LIMIT_WORKER_THREADS==(SQLITE_N_LIMIT-1) );
  148710. if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
  148711. return -1;
  148712. }
  148713. oldLimit = db->aLimit[limitId];
  148714. if( newLimit>=0 ){ /* IMP: R-52476-28732 */
  148715. if( newLimit>aHardLimit[limitId] ){
  148716. newLimit = aHardLimit[limitId]; /* IMP: R-51463-25634 */
  148717. }
  148718. db->aLimit[limitId] = newLimit;
  148719. }
  148720. return oldLimit; /* IMP: R-53341-35419 */
  148721. }
  148722. /*
  148723. ** This function is used to parse both URIs and non-URI filenames passed by the
  148724. ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
  148725. ** URIs specified as part of ATTACH statements.
  148726. **
  148727. ** The first argument to this function is the name of the VFS to use (or
  148728. ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
  148729. ** query parameter. The second argument contains the URI (or non-URI filename)
  148730. ** itself. When this function is called the *pFlags variable should contain
  148731. ** the default flags to open the database handle with. The value stored in
  148732. ** *pFlags may be updated before returning if the URI filename contains
  148733. ** "cache=xxx" or "mode=xxx" query parameters.
  148734. **
  148735. ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
  148736. ** the VFS that should be used to open the database file. *pzFile is set to
  148737. ** point to a buffer containing the name of the file to open. It is the
  148738. ** responsibility of the caller to eventually call sqlite3_free() to release
  148739. ** this buffer.
  148740. **
  148741. ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
  148742. ** may be set to point to a buffer containing an English language error
  148743. ** message. It is the responsibility of the caller to eventually release
  148744. ** this buffer by calling sqlite3_free().
  148745. */
  148746. SQLITE_PRIVATE int sqlite3ParseUri(
  148747. const char *zDefaultVfs, /* VFS to use if no "vfs=xxx" query option */
  148748. const char *zUri, /* Nul-terminated URI to parse */
  148749. unsigned int *pFlags, /* IN/OUT: SQLITE_OPEN_XXX flags */
  148750. sqlite3_vfs **ppVfs, /* OUT: VFS to use */
  148751. char **pzFile, /* OUT: Filename component of URI */
  148752. char **pzErrMsg /* OUT: Error message (if rc!=SQLITE_OK) */
  148753. ){
  148754. int rc = SQLITE_OK;
  148755. unsigned int flags = *pFlags;
  148756. const char *zVfs = zDefaultVfs;
  148757. char *zFile;
  148758. char c;
  148759. int nUri = sqlite3Strlen30(zUri);
  148760. assert( *pzErrMsg==0 );
  148761. if( ((flags & SQLITE_OPEN_URI) /* IMP: R-48725-32206 */
  148762. || sqlite3GlobalConfig.bOpenUri) /* IMP: R-51689-46548 */
  148763. && nUri>=5 && memcmp(zUri, "file:", 5)==0 /* IMP: R-57884-37496 */
  148764. ){
  148765. char *zOpt;
  148766. int eState; /* Parser state when parsing URI */
  148767. int iIn; /* Input character index */
  148768. int iOut = 0; /* Output character index */
  148769. u64 nByte = nUri+2; /* Bytes of space to allocate */
  148770. /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
  148771. ** method that there may be extra parameters following the file-name. */
  148772. flags |= SQLITE_OPEN_URI;
  148773. for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
  148774. zFile = sqlite3_malloc64(nByte);
  148775. if( !zFile ) return SQLITE_NOMEM_BKPT;
  148776. iIn = 5;
  148777. #ifdef SQLITE_ALLOW_URI_AUTHORITY
  148778. if( strncmp(zUri+5, "///", 3)==0 ){
  148779. iIn = 7;
  148780. /* The following condition causes URIs with five leading / characters
  148781. ** like file://///host/path to be converted into UNCs like //host/path.
  148782. ** The correct URI for that UNC has only two or four leading / characters
  148783. ** file://host/path or file:////host/path. But 5 leading slashes is a
  148784. ** common error, we are told, so we handle it as a special case. */
  148785. if( strncmp(zUri+7, "///", 3)==0 ){ iIn++; }
  148786. }else if( strncmp(zUri+5, "//localhost/", 12)==0 ){
  148787. iIn = 16;
  148788. }
  148789. #else
  148790. /* Discard the scheme and authority segments of the URI. */
  148791. if( zUri[5]=='/' && zUri[6]=='/' ){
  148792. iIn = 7;
  148793. while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
  148794. if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
  148795. *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
  148796. iIn-7, &zUri[7]);
  148797. rc = SQLITE_ERROR;
  148798. goto parse_uri_out;
  148799. }
  148800. }
  148801. #endif
  148802. /* Copy the filename and any query parameters into the zFile buffer.
  148803. ** Decode %HH escape codes along the way.
  148804. **
  148805. ** Within this loop, variable eState may be set to 0, 1 or 2, depending
  148806. ** on the parsing context. As follows:
  148807. **
  148808. ** 0: Parsing file-name.
  148809. ** 1: Parsing name section of a name=value query parameter.
  148810. ** 2: Parsing value section of a name=value query parameter.
  148811. */
  148812. eState = 0;
  148813. while( (c = zUri[iIn])!=0 && c!='#' ){
  148814. iIn++;
  148815. if( c=='%'
  148816. && sqlite3Isxdigit(zUri[iIn])
  148817. && sqlite3Isxdigit(zUri[iIn+1])
  148818. ){
  148819. int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
  148820. octet += sqlite3HexToInt(zUri[iIn++]);
  148821. assert( octet>=0 && octet<256 );
  148822. if( octet==0 ){
  148823. #ifndef SQLITE_ENABLE_URI_00_ERROR
  148824. /* This branch is taken when "%00" appears within the URI. In this
  148825. ** case we ignore all text in the remainder of the path, name or
  148826. ** value currently being parsed. So ignore the current character
  148827. ** and skip to the next "?", "=" or "&", as appropriate. */
  148828. while( (c = zUri[iIn])!=0 && c!='#'
  148829. && (eState!=0 || c!='?')
  148830. && (eState!=1 || (c!='=' && c!='&'))
  148831. && (eState!=2 || c!='&')
  148832. ){
  148833. iIn++;
  148834. }
  148835. continue;
  148836. #else
  148837. /* If ENABLE_URI_00_ERROR is defined, "%00" in a URI is an error. */
  148838. *pzErrMsg = sqlite3_mprintf("unexpected %%00 in uri");
  148839. rc = SQLITE_ERROR;
  148840. goto parse_uri_out;
  148841. #endif
  148842. }
  148843. c = octet;
  148844. }else if( eState==1 && (c=='&' || c=='=') ){
  148845. if( zFile[iOut-1]==0 ){
  148846. /* An empty option name. Ignore this option altogether. */
  148847. while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
  148848. continue;
  148849. }
  148850. if( c=='&' ){
  148851. zFile[iOut++] = '\0';
  148852. }else{
  148853. eState = 2;
  148854. }
  148855. c = 0;
  148856. }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
  148857. c = 0;
  148858. eState = 1;
  148859. }
  148860. zFile[iOut++] = c;
  148861. }
  148862. if( eState==1 ) zFile[iOut++] = '\0';
  148863. zFile[iOut++] = '\0';
  148864. zFile[iOut++] = '\0';
  148865. /* Check if there were any options specified that should be interpreted
  148866. ** here. Options that are interpreted here include "vfs" and those that
  148867. ** correspond to flags that may be passed to the sqlite3_open_v2()
  148868. ** method. */
  148869. zOpt = &zFile[sqlite3Strlen30(zFile)+1];
  148870. while( zOpt[0] ){
  148871. int nOpt = sqlite3Strlen30(zOpt);
  148872. char *zVal = &zOpt[nOpt+1];
  148873. int nVal = sqlite3Strlen30(zVal);
  148874. if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
  148875. zVfs = zVal;
  148876. }else{
  148877. struct OpenMode {
  148878. const char *z;
  148879. int mode;
  148880. } *aMode = 0;
  148881. char *zModeType = 0;
  148882. int mask = 0;
  148883. int limit = 0;
  148884. if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
  148885. static struct OpenMode aCacheMode[] = {
  148886. { "shared", SQLITE_OPEN_SHAREDCACHE },
  148887. { "private", SQLITE_OPEN_PRIVATECACHE },
  148888. { 0, 0 }
  148889. };
  148890. mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
  148891. aMode = aCacheMode;
  148892. limit = mask;
  148893. zModeType = "cache";
  148894. }
  148895. if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
  148896. static struct OpenMode aOpenMode[] = {
  148897. { "ro", SQLITE_OPEN_READONLY },
  148898. { "rw", SQLITE_OPEN_READWRITE },
  148899. { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
  148900. { "memory", SQLITE_OPEN_MEMORY },
  148901. { 0, 0 }
  148902. };
  148903. mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
  148904. | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
  148905. aMode = aOpenMode;
  148906. limit = mask & flags;
  148907. zModeType = "access";
  148908. }
  148909. if( aMode ){
  148910. int i;
  148911. int mode = 0;
  148912. for(i=0; aMode[i].z; i++){
  148913. const char *z = aMode[i].z;
  148914. if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
  148915. mode = aMode[i].mode;
  148916. break;
  148917. }
  148918. }
  148919. if( mode==0 ){
  148920. *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
  148921. rc = SQLITE_ERROR;
  148922. goto parse_uri_out;
  148923. }
  148924. if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
  148925. *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
  148926. zModeType, zVal);
  148927. rc = SQLITE_PERM;
  148928. goto parse_uri_out;
  148929. }
  148930. flags = (flags & ~mask) | mode;
  148931. }
  148932. }
  148933. zOpt = &zVal[nVal+1];
  148934. }
  148935. }else{
  148936. zFile = sqlite3_malloc64(nUri+2);
  148937. if( !zFile ) return SQLITE_NOMEM_BKPT;
  148938. if( nUri ){
  148939. memcpy(zFile, zUri, nUri);
  148940. }
  148941. zFile[nUri] = '\0';
  148942. zFile[nUri+1] = '\0';
  148943. flags &= ~SQLITE_OPEN_URI;
  148944. }
  148945. *ppVfs = sqlite3_vfs_find(zVfs);
  148946. if( *ppVfs==0 ){
  148947. *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
  148948. rc = SQLITE_ERROR;
  148949. }
  148950. parse_uri_out:
  148951. if( rc!=SQLITE_OK ){
  148952. sqlite3_free(zFile);
  148953. zFile = 0;
  148954. }
  148955. *pFlags = flags;
  148956. *pzFile = zFile;
  148957. return rc;
  148958. }
  148959. #if defined(SQLITE_HAS_CODEC)
  148960. /*
  148961. ** Process URI filename query parameters relevant to the SQLite Encryption
  148962. ** Extension. Return true if any of the relevant query parameters are
  148963. ** seen and return false if not.
  148964. */
  148965. SQLITE_PRIVATE int sqlite3CodecQueryParameters(
  148966. sqlite3 *db, /* Database connection */
  148967. const char *zDb, /* Which schema is being created/attached */
  148968. const char *zUri /* URI filename */
  148969. ){
  148970. const char *zKey;
  148971. if( (zKey = sqlite3_uri_parameter(zUri, "hexkey"))!=0 && zKey[0] ){
  148972. u8 iByte;
  148973. int i;
  148974. char zDecoded[40];
  148975. for(i=0, iByte=0; i<sizeof(zDecoded)*2 && sqlite3Isxdigit(zKey[i]); i++){
  148976. iByte = (iByte<<4) + sqlite3HexToInt(zKey[i]);
  148977. if( (i&1)!=0 ) zDecoded[i/2] = iByte;
  148978. }
  148979. sqlite3_key_v2(db, zDb, zDecoded, i/2);
  148980. return 1;
  148981. }else if( (zKey = sqlite3_uri_parameter(zUri, "key"))!=0 ){
  148982. sqlite3_key_v2(db, zDb, zKey, sqlite3Strlen30(zKey));
  148983. return 1;
  148984. }else if( (zKey = sqlite3_uri_parameter(zUri, "textkey"))!=0 ){
  148985. sqlite3_key_v2(db, zDb, zKey, -1);
  148986. return 1;
  148987. }else{
  148988. return 0;
  148989. }
  148990. }
  148991. #endif
  148992. /*
  148993. ** This routine does the work of opening a database on behalf of
  148994. ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
  148995. ** is UTF-8 encoded.
  148996. */
  148997. static int openDatabase(
  148998. const char *zFilename, /* Database filename UTF-8 encoded */
  148999. sqlite3 **ppDb, /* OUT: Returned database handle */
  149000. unsigned int flags, /* Operational flags */
  149001. const char *zVfs /* Name of the VFS to use */
  149002. ){
  149003. sqlite3 *db; /* Store allocated handle here */
  149004. int rc; /* Return code */
  149005. int isThreadsafe; /* True for threadsafe connections */
  149006. char *zOpen = 0; /* Filename argument to pass to BtreeOpen() */
  149007. char *zErrMsg = 0; /* Error message from sqlite3ParseUri() */
  149008. #ifdef SQLITE_ENABLE_API_ARMOR
  149009. if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
  149010. #endif
  149011. *ppDb = 0;
  149012. #ifndef SQLITE_OMIT_AUTOINIT
  149013. rc = sqlite3_initialize();
  149014. if( rc ) return rc;
  149015. #endif
  149016. if( sqlite3GlobalConfig.bCoreMutex==0 ){
  149017. isThreadsafe = 0;
  149018. }else if( flags & SQLITE_OPEN_NOMUTEX ){
  149019. isThreadsafe = 0;
  149020. }else if( flags & SQLITE_OPEN_FULLMUTEX ){
  149021. isThreadsafe = 1;
  149022. }else{
  149023. isThreadsafe = sqlite3GlobalConfig.bFullMutex;
  149024. }
  149025. if( flags & SQLITE_OPEN_PRIVATECACHE ){
  149026. flags &= ~SQLITE_OPEN_SHAREDCACHE;
  149027. }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
  149028. flags |= SQLITE_OPEN_SHAREDCACHE;
  149029. }
  149030. /* Remove harmful bits from the flags parameter
  149031. **
  149032. ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
  149033. ** dealt with in the previous code block. Besides these, the only
  149034. ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
  149035. ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
  149036. ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits. Silently mask
  149037. ** off all other flags.
  149038. */
  149039. flags &= ~( SQLITE_OPEN_DELETEONCLOSE |
  149040. SQLITE_OPEN_EXCLUSIVE |
  149041. SQLITE_OPEN_MAIN_DB |
  149042. SQLITE_OPEN_TEMP_DB |
  149043. SQLITE_OPEN_TRANSIENT_DB |
  149044. SQLITE_OPEN_MAIN_JOURNAL |
  149045. SQLITE_OPEN_TEMP_JOURNAL |
  149046. SQLITE_OPEN_SUBJOURNAL |
  149047. SQLITE_OPEN_MASTER_JOURNAL |
  149048. SQLITE_OPEN_NOMUTEX |
  149049. SQLITE_OPEN_FULLMUTEX |
  149050. SQLITE_OPEN_WAL
  149051. );
  149052. /* Allocate the sqlite data structure */
  149053. db = sqlite3MallocZero( sizeof(sqlite3) );
  149054. if( db==0 ) goto opendb_out;
  149055. if( isThreadsafe
  149056. #ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS
  149057. || sqlite3GlobalConfig.bCoreMutex
  149058. #endif
  149059. ){
  149060. db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
  149061. if( db->mutex==0 ){
  149062. sqlite3_free(db);
  149063. db = 0;
  149064. goto opendb_out;
  149065. }
  149066. if( isThreadsafe==0 ){
  149067. sqlite3MutexWarnOnContention(db->mutex);
  149068. }
  149069. }
  149070. sqlite3_mutex_enter(db->mutex);
  149071. db->errMask = 0xff;
  149072. db->nDb = 2;
  149073. db->magic = SQLITE_MAGIC_BUSY;
  149074. db->aDb = db->aDbStatic;
  149075. db->lookaside.bDisable = 1;
  149076. assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
  149077. memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
  149078. db->aLimit[SQLITE_LIMIT_WORKER_THREADS] = SQLITE_DEFAULT_WORKER_THREADS;
  149079. db->autoCommit = 1;
  149080. db->nextAutovac = -1;
  149081. db->szMmap = sqlite3GlobalConfig.szMmap;
  149082. db->nextPagesize = 0;
  149083. db->nMaxSorterMmap = 0x7FFFFFFF;
  149084. db->flags |= SQLITE_ShortColNames
  149085. | SQLITE_EnableTrigger
  149086. | SQLITE_CacheSpill
  149087. /* The SQLITE_DQS compile-time option determines the default settings
  149088. ** for SQLITE_DBCONFIG_DQS_DDL and SQLITE_DBCONFIG_DQS_DML.
  149089. **
  149090. ** SQLITE_DQS SQLITE_DBCONFIG_DQS_DDL SQLITE_DBCONFIG_DQS_DML
  149091. ** ---------- ----------------------- -----------------------
  149092. ** undefined on on
  149093. ** 3 on on
  149094. ** 2 on off
  149095. ** 1 off on
  149096. ** 0 off off
  149097. **
  149098. ** Legacy behavior is 3 (double-quoted string literals are allowed anywhere)
  149099. ** and so that is the default. But developers are encouranged to use
  149100. ** -DSQLITE_DQS=0 (best) or -DSQLITE_DQS=1 (second choice) if possible.
  149101. */
  149102. #if !defined(SQLITE_DQS)
  149103. # define SQLITE_DQS 3
  149104. #endif
  149105. #if (SQLITE_DQS&1)==1
  149106. | SQLITE_DqsDML
  149107. #endif
  149108. #if (SQLITE_DQS&2)==2
  149109. | SQLITE_DqsDDL
  149110. #endif
  149111. #if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
  149112. | SQLITE_AutoIndex
  149113. #endif
  149114. #if SQLITE_DEFAULT_CKPTFULLFSYNC
  149115. | SQLITE_CkptFullFSync
  149116. #endif
  149117. #if SQLITE_DEFAULT_FILE_FORMAT<4
  149118. | SQLITE_LegacyFileFmt
  149119. #endif
  149120. #ifdef SQLITE_ENABLE_LOAD_EXTENSION
  149121. | SQLITE_LoadExtension
  149122. #endif
  149123. #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
  149124. | SQLITE_RecTriggers
  149125. #endif
  149126. #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
  149127. | SQLITE_ForeignKeys
  149128. #endif
  149129. #if defined(SQLITE_REVERSE_UNORDERED_SELECTS)
  149130. | SQLITE_ReverseOrder
  149131. #endif
  149132. #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
  149133. | SQLITE_CellSizeCk
  149134. #endif
  149135. #if defined(SQLITE_ENABLE_FTS3_TOKENIZER)
  149136. | SQLITE_Fts3Tokenizer
  149137. #endif
  149138. #if defined(SQLITE_ENABLE_QPSG)
  149139. | SQLITE_EnableQPSG
  149140. #endif
  149141. #if defined(SQLITE_DEFAULT_DEFENSIVE)
  149142. | SQLITE_Defensive
  149143. #endif
  149144. ;
  149145. sqlite3HashInit(&db->aCollSeq);
  149146. #ifndef SQLITE_OMIT_VIRTUALTABLE
  149147. sqlite3HashInit(&db->aModule);
  149148. #endif
  149149. /* Add the default collation sequence BINARY. BINARY works for both UTF-8
  149150. ** and UTF-16, so add a version for each to avoid any unnecessary
  149151. ** conversions. The only error that can occur here is a malloc() failure.
  149152. **
  149153. ** EVIDENCE-OF: R-52786-44878 SQLite defines three built-in collating
  149154. ** functions:
  149155. */
  149156. createCollation(db, sqlite3StrBINARY, SQLITE_UTF8, 0, binCollFunc, 0);
  149157. createCollation(db, sqlite3StrBINARY, SQLITE_UTF16BE, 0, binCollFunc, 0);
  149158. createCollation(db, sqlite3StrBINARY, SQLITE_UTF16LE, 0, binCollFunc, 0);
  149159. createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
  149160. createCollation(db, "RTRIM", SQLITE_UTF8, 0, rtrimCollFunc, 0);
  149161. if( db->mallocFailed ){
  149162. goto opendb_out;
  149163. }
  149164. /* EVIDENCE-OF: R-08308-17224 The default collating function for all
  149165. ** strings is BINARY.
  149166. */
  149167. db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, sqlite3StrBINARY, 0);
  149168. assert( db->pDfltColl!=0 );
  149169. /* Parse the filename/URI argument
  149170. **
  149171. ** Only allow sensible combinations of bits in the flags argument.
  149172. ** Throw an error if any non-sense combination is used. If we
  149173. ** do not block illegal combinations here, it could trigger
  149174. ** assert() statements in deeper layers. Sensible combinations
  149175. ** are:
  149176. **
  149177. ** 1: SQLITE_OPEN_READONLY
  149178. ** 2: SQLITE_OPEN_READWRITE
  149179. ** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
  149180. */
  149181. db->openFlags = flags;
  149182. assert( SQLITE_OPEN_READONLY == 0x01 );
  149183. assert( SQLITE_OPEN_READWRITE == 0x02 );
  149184. assert( SQLITE_OPEN_CREATE == 0x04 );
  149185. testcase( (1<<(flags&7))==0x02 ); /* READONLY */
  149186. testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
  149187. testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
  149188. if( ((1<<(flags&7)) & 0x46)==0 ){
  149189. rc = SQLITE_MISUSE_BKPT; /* IMP: R-65497-44594 */
  149190. }else{
  149191. rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
  149192. }
  149193. if( rc!=SQLITE_OK ){
  149194. if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
  149195. sqlite3ErrorWithMsg(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
  149196. sqlite3_free(zErrMsg);
  149197. goto opendb_out;
  149198. }
  149199. /* Open the backend database driver */
  149200. rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
  149201. flags | SQLITE_OPEN_MAIN_DB);
  149202. if( rc!=SQLITE_OK ){
  149203. if( rc==SQLITE_IOERR_NOMEM ){
  149204. rc = SQLITE_NOMEM_BKPT;
  149205. }
  149206. sqlite3Error(db, rc);
  149207. goto opendb_out;
  149208. }
  149209. sqlite3BtreeEnter(db->aDb[0].pBt);
  149210. db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
  149211. if( !db->mallocFailed ) ENC(db) = SCHEMA_ENC(db);
  149212. sqlite3BtreeLeave(db->aDb[0].pBt);
  149213. db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
  149214. /* The default safety_level for the main database is FULL; for the temp
  149215. ** database it is OFF. This matches the pager layer defaults.
  149216. */
  149217. db->aDb[0].zDbSName = "main";
  149218. db->aDb[0].safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
  149219. db->aDb[1].zDbSName = "temp";
  149220. db->aDb[1].safety_level = PAGER_SYNCHRONOUS_OFF;
  149221. db->magic = SQLITE_MAGIC_OPEN;
  149222. if( db->mallocFailed ){
  149223. goto opendb_out;
  149224. }
  149225. /* Register all built-in functions, but do not attempt to read the
  149226. ** database schema yet. This is delayed until the first time the database
  149227. ** is accessed.
  149228. */
  149229. sqlite3Error(db, SQLITE_OK);
  149230. sqlite3RegisterPerConnectionBuiltinFunctions(db);
  149231. rc = sqlite3_errcode(db);
  149232. #ifdef SQLITE_ENABLE_FTS5
  149233. /* Register any built-in FTS5 module before loading the automatic
  149234. ** extensions. This allows automatic extensions to register FTS5
  149235. ** tokenizers and auxiliary functions. */
  149236. if( !db->mallocFailed && rc==SQLITE_OK ){
  149237. rc = sqlite3Fts5Init(db);
  149238. }
  149239. #endif
  149240. /* Load automatic extensions - extensions that have been registered
  149241. ** using the sqlite3_automatic_extension() API.
  149242. */
  149243. if( rc==SQLITE_OK ){
  149244. sqlite3AutoLoadExtensions(db);
  149245. rc = sqlite3_errcode(db);
  149246. if( rc!=SQLITE_OK ){
  149247. goto opendb_out;
  149248. }
  149249. }
  149250. #ifdef SQLITE_ENABLE_FTS1
  149251. if( !db->mallocFailed ){
  149252. extern int sqlite3Fts1Init(sqlite3*);
  149253. rc = sqlite3Fts1Init(db);
  149254. }
  149255. #endif
  149256. #ifdef SQLITE_ENABLE_FTS2
  149257. if( !db->mallocFailed && rc==SQLITE_OK ){
  149258. extern int sqlite3Fts2Init(sqlite3*);
  149259. rc = sqlite3Fts2Init(db);
  149260. }
  149261. #endif
  149262. #ifdef SQLITE_ENABLE_FTS3 /* automatically defined by SQLITE_ENABLE_FTS4 */
  149263. if( !db->mallocFailed && rc==SQLITE_OK ){
  149264. rc = sqlite3Fts3Init(db);
  149265. }
  149266. #endif
  149267. #if defined(SQLITE_ENABLE_ICU) || defined(SQLITE_ENABLE_ICU_COLLATIONS)
  149268. if( !db->mallocFailed && rc==SQLITE_OK ){
  149269. rc = sqlite3IcuInit(db);
  149270. }
  149271. #endif
  149272. #ifdef SQLITE_ENABLE_RTREE
  149273. if( !db->mallocFailed && rc==SQLITE_OK){
  149274. rc = sqlite3RtreeInit(db);
  149275. }
  149276. #endif
  149277. #ifdef SQLITE_ENABLE_DBPAGE_VTAB
  149278. if( !db->mallocFailed && rc==SQLITE_OK){
  149279. rc = sqlite3DbpageRegister(db);
  149280. }
  149281. #endif
  149282. #ifdef SQLITE_ENABLE_DBSTAT_VTAB
  149283. if( !db->mallocFailed && rc==SQLITE_OK){
  149284. rc = sqlite3DbstatRegister(db);
  149285. }
  149286. #endif
  149287. #ifdef SQLITE_ENABLE_JSON1
  149288. if( !db->mallocFailed && rc==SQLITE_OK){
  149289. rc = sqlite3Json1Init(db);
  149290. }
  149291. #endif
  149292. #ifdef SQLITE_ENABLE_STMTVTAB
  149293. if( !db->mallocFailed && rc==SQLITE_OK){
  149294. rc = sqlite3StmtVtabInit(db);
  149295. }
  149296. #endif
  149297. /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
  149298. ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
  149299. ** mode. Doing nothing at all also makes NORMAL the default.
  149300. */
  149301. #ifdef SQLITE_DEFAULT_LOCKING_MODE
  149302. db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
  149303. sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
  149304. SQLITE_DEFAULT_LOCKING_MODE);
  149305. #endif
  149306. if( rc ) sqlite3Error(db, rc);
  149307. /* Enable the lookaside-malloc subsystem */
  149308. setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
  149309. sqlite3GlobalConfig.nLookaside);
  149310. sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
  149311. opendb_out:
  149312. if( db ){
  149313. assert( db->mutex!=0 || isThreadsafe==0
  149314. || sqlite3GlobalConfig.bFullMutex==0 );
  149315. sqlite3_mutex_leave(db->mutex);
  149316. }
  149317. rc = sqlite3_errcode(db);
  149318. assert( db!=0 || rc==SQLITE_NOMEM );
  149319. if( rc==SQLITE_NOMEM ){
  149320. sqlite3_close(db);
  149321. db = 0;
  149322. }else if( rc!=SQLITE_OK ){
  149323. db->magic = SQLITE_MAGIC_SICK;
  149324. }
  149325. *ppDb = db;
  149326. #ifdef SQLITE_ENABLE_SQLLOG
  149327. if( sqlite3GlobalConfig.xSqllog ){
  149328. /* Opening a db handle. Fourth parameter is passed 0. */
  149329. void *pArg = sqlite3GlobalConfig.pSqllogArg;
  149330. sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
  149331. }
  149332. #endif
  149333. #if defined(SQLITE_HAS_CODEC)
  149334. if( rc==SQLITE_OK ) sqlite3CodecQueryParameters(db, 0, zOpen);
  149335. #endif
  149336. sqlite3_free(zOpen);
  149337. return rc & 0xff;
  149338. }
  149339. /*
  149340. ** Open a new database handle.
  149341. */
  149342. SQLITE_API int sqlite3_open(
  149343. const char *zFilename,
  149344. sqlite3 **ppDb
  149345. ){
  149346. return openDatabase(zFilename, ppDb,
  149347. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
  149348. }
  149349. SQLITE_API int sqlite3_open_v2(
  149350. const char *filename, /* Database filename (UTF-8) */
  149351. sqlite3 **ppDb, /* OUT: SQLite db handle */
  149352. int flags, /* Flags */
  149353. const char *zVfs /* Name of VFS module to use */
  149354. ){
  149355. return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
  149356. }
  149357. #ifndef SQLITE_OMIT_UTF16
  149358. /*
  149359. ** Open a new database handle.
  149360. */
  149361. SQLITE_API int sqlite3_open16(
  149362. const void *zFilename,
  149363. sqlite3 **ppDb
  149364. ){
  149365. char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */
  149366. sqlite3_value *pVal;
  149367. int rc;
  149368. #ifdef SQLITE_ENABLE_API_ARMOR
  149369. if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
  149370. #endif
  149371. *ppDb = 0;
  149372. #ifndef SQLITE_OMIT_AUTOINIT
  149373. rc = sqlite3_initialize();
  149374. if( rc ) return rc;
  149375. #endif
  149376. if( zFilename==0 ) zFilename = "\000\000";
  149377. pVal = sqlite3ValueNew(0);
  149378. sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  149379. zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
  149380. if( zFilename8 ){
  149381. rc = openDatabase(zFilename8, ppDb,
  149382. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
  149383. assert( *ppDb || rc==SQLITE_NOMEM );
  149384. if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
  149385. SCHEMA_ENC(*ppDb) = ENC(*ppDb) = SQLITE_UTF16NATIVE;
  149386. }
  149387. }else{
  149388. rc = SQLITE_NOMEM_BKPT;
  149389. }
  149390. sqlite3ValueFree(pVal);
  149391. return rc & 0xff;
  149392. }
  149393. #endif /* SQLITE_OMIT_UTF16 */
  149394. /*
  149395. ** Register a new collation sequence with the database handle db.
  149396. */
  149397. SQLITE_API int sqlite3_create_collation(
  149398. sqlite3* db,
  149399. const char *zName,
  149400. int enc,
  149401. void* pCtx,
  149402. int(*xCompare)(void*,int,const void*,int,const void*)
  149403. ){
  149404. return sqlite3_create_collation_v2(db, zName, enc, pCtx, xCompare, 0);
  149405. }
  149406. /*
  149407. ** Register a new collation sequence with the database handle db.
  149408. */
  149409. SQLITE_API int sqlite3_create_collation_v2(
  149410. sqlite3* db,
  149411. const char *zName,
  149412. int enc,
  149413. void* pCtx,
  149414. int(*xCompare)(void*,int,const void*,int,const void*),
  149415. void(*xDel)(void*)
  149416. ){
  149417. int rc;
  149418. #ifdef SQLITE_ENABLE_API_ARMOR
  149419. if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
  149420. #endif
  149421. sqlite3_mutex_enter(db->mutex);
  149422. assert( !db->mallocFailed );
  149423. rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
  149424. rc = sqlite3ApiExit(db, rc);
  149425. sqlite3_mutex_leave(db->mutex);
  149426. return rc;
  149427. }
  149428. #ifndef SQLITE_OMIT_UTF16
  149429. /*
  149430. ** Register a new collation sequence with the database handle db.
  149431. */
  149432. SQLITE_API int sqlite3_create_collation16(
  149433. sqlite3* db,
  149434. const void *zName,
  149435. int enc,
  149436. void* pCtx,
  149437. int(*xCompare)(void*,int,const void*,int,const void*)
  149438. ){
  149439. int rc = SQLITE_OK;
  149440. char *zName8;
  149441. #ifdef SQLITE_ENABLE_API_ARMOR
  149442. if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
  149443. #endif
  149444. sqlite3_mutex_enter(db->mutex);
  149445. assert( !db->mallocFailed );
  149446. zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
  149447. if( zName8 ){
  149448. rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
  149449. sqlite3DbFree(db, zName8);
  149450. }
  149451. rc = sqlite3ApiExit(db, rc);
  149452. sqlite3_mutex_leave(db->mutex);
  149453. return rc;
  149454. }
  149455. #endif /* SQLITE_OMIT_UTF16 */
  149456. /*
  149457. ** Register a collation sequence factory callback with the database handle
  149458. ** db. Replace any previously installed collation sequence factory.
  149459. */
  149460. SQLITE_API int sqlite3_collation_needed(
  149461. sqlite3 *db,
  149462. void *pCollNeededArg,
  149463. void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
  149464. ){
  149465. #ifdef SQLITE_ENABLE_API_ARMOR
  149466. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  149467. #endif
  149468. sqlite3_mutex_enter(db->mutex);
  149469. db->xCollNeeded = xCollNeeded;
  149470. db->xCollNeeded16 = 0;
  149471. db->pCollNeededArg = pCollNeededArg;
  149472. sqlite3_mutex_leave(db->mutex);
  149473. return SQLITE_OK;
  149474. }
  149475. #ifndef SQLITE_OMIT_UTF16
  149476. /*
  149477. ** Register a collation sequence factory callback with the database handle
  149478. ** db. Replace any previously installed collation sequence factory.
  149479. */
  149480. SQLITE_API int sqlite3_collation_needed16(
  149481. sqlite3 *db,
  149482. void *pCollNeededArg,
  149483. void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
  149484. ){
  149485. #ifdef SQLITE_ENABLE_API_ARMOR
  149486. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  149487. #endif
  149488. sqlite3_mutex_enter(db->mutex);
  149489. db->xCollNeeded = 0;
  149490. db->xCollNeeded16 = xCollNeeded16;
  149491. db->pCollNeededArg = pCollNeededArg;
  149492. sqlite3_mutex_leave(db->mutex);
  149493. return SQLITE_OK;
  149494. }
  149495. #endif /* SQLITE_OMIT_UTF16 */
  149496. #ifndef SQLITE_OMIT_DEPRECATED
  149497. /*
  149498. ** This function is now an anachronism. It used to be used to recover from a
  149499. ** malloc() failure, but SQLite now does this automatically.
  149500. */
  149501. SQLITE_API int sqlite3_global_recover(void){
  149502. return SQLITE_OK;
  149503. }
  149504. #endif
  149505. /*
  149506. ** Test to see whether or not the database connection is in autocommit
  149507. ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
  149508. ** by default. Autocommit is disabled by a BEGIN statement and reenabled
  149509. ** by the next COMMIT or ROLLBACK.
  149510. */
  149511. SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
  149512. #ifdef SQLITE_ENABLE_API_ARMOR
  149513. if( !sqlite3SafetyCheckOk(db) ){
  149514. (void)SQLITE_MISUSE_BKPT;
  149515. return 0;
  149516. }
  149517. #endif
  149518. return db->autoCommit;
  149519. }
  149520. /*
  149521. ** The following routines are substitutes for constants SQLITE_CORRUPT,
  149522. ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_NOMEM and possibly other error
  149523. ** constants. They serve two purposes:
  149524. **
  149525. ** 1. Serve as a convenient place to set a breakpoint in a debugger
  149526. ** to detect when version error conditions occurs.
  149527. **
  149528. ** 2. Invoke sqlite3_log() to provide the source code location where
  149529. ** a low-level error is first detected.
  149530. */
  149531. SQLITE_PRIVATE int sqlite3ReportError(int iErr, int lineno, const char *zType){
  149532. sqlite3_log(iErr, "%s at line %d of [%.10s]",
  149533. zType, lineno, 20+sqlite3_sourceid());
  149534. return iErr;
  149535. }
  149536. SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
  149537. testcase( sqlite3GlobalConfig.xLog!=0 );
  149538. return sqlite3ReportError(SQLITE_CORRUPT, lineno, "database corruption");
  149539. }
  149540. SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
  149541. testcase( sqlite3GlobalConfig.xLog!=0 );
  149542. return sqlite3ReportError(SQLITE_MISUSE, lineno, "misuse");
  149543. }
  149544. SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
  149545. testcase( sqlite3GlobalConfig.xLog!=0 );
  149546. return sqlite3ReportError(SQLITE_CANTOPEN, lineno, "cannot open file");
  149547. }
  149548. #ifdef SQLITE_DEBUG
  149549. SQLITE_PRIVATE int sqlite3CorruptPgnoError(int lineno, Pgno pgno){
  149550. char zMsg[100];
  149551. sqlite3_snprintf(sizeof(zMsg), zMsg, "database corruption page %d", pgno);
  149552. testcase( sqlite3GlobalConfig.xLog!=0 );
  149553. return sqlite3ReportError(SQLITE_CORRUPT, lineno, zMsg);
  149554. }
  149555. SQLITE_PRIVATE int sqlite3NomemError(int lineno){
  149556. testcase( sqlite3GlobalConfig.xLog!=0 );
  149557. return sqlite3ReportError(SQLITE_NOMEM, lineno, "OOM");
  149558. }
  149559. SQLITE_PRIVATE int sqlite3IoerrnomemError(int lineno){
  149560. testcase( sqlite3GlobalConfig.xLog!=0 );
  149561. return sqlite3ReportError(SQLITE_IOERR_NOMEM, lineno, "I/O OOM error");
  149562. }
  149563. #endif
  149564. #ifndef SQLITE_OMIT_DEPRECATED
  149565. /*
  149566. ** This is a convenience routine that makes sure that all thread-specific
  149567. ** data for this thread has been deallocated.
  149568. **
  149569. ** SQLite no longer uses thread-specific data so this routine is now a
  149570. ** no-op. It is retained for historical compatibility.
  149571. */
  149572. SQLITE_API void sqlite3_thread_cleanup(void){
  149573. }
  149574. #endif
  149575. /*
  149576. ** Return meta information about a specific column of a database table.
  149577. ** See comment in sqlite3.h (sqlite.h.in) for details.
  149578. */
  149579. SQLITE_API int sqlite3_table_column_metadata(
  149580. sqlite3 *db, /* Connection handle */
  149581. const char *zDbName, /* Database name or NULL */
  149582. const char *zTableName, /* Table name */
  149583. const char *zColumnName, /* Column name */
  149584. char const **pzDataType, /* OUTPUT: Declared data type */
  149585. char const **pzCollSeq, /* OUTPUT: Collation sequence name */
  149586. int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
  149587. int *pPrimaryKey, /* OUTPUT: True if column part of PK */
  149588. int *pAutoinc /* OUTPUT: True if column is auto-increment */
  149589. ){
  149590. int rc;
  149591. char *zErrMsg = 0;
  149592. Table *pTab = 0;
  149593. Column *pCol = 0;
  149594. int iCol = 0;
  149595. char const *zDataType = 0;
  149596. char const *zCollSeq = 0;
  149597. int notnull = 0;
  149598. int primarykey = 0;
  149599. int autoinc = 0;
  149600. #ifdef SQLITE_ENABLE_API_ARMOR
  149601. if( !sqlite3SafetyCheckOk(db) || zTableName==0 ){
  149602. return SQLITE_MISUSE_BKPT;
  149603. }
  149604. #endif
  149605. /* Ensure the database schema has been loaded */
  149606. sqlite3_mutex_enter(db->mutex);
  149607. sqlite3BtreeEnterAll(db);
  149608. rc = sqlite3Init(db, &zErrMsg);
  149609. if( SQLITE_OK!=rc ){
  149610. goto error_out;
  149611. }
  149612. /* Locate the table in question */
  149613. pTab = sqlite3FindTable(db, zTableName, zDbName);
  149614. if( !pTab || pTab->pSelect ){
  149615. pTab = 0;
  149616. goto error_out;
  149617. }
  149618. /* Find the column for which info is requested */
  149619. if( zColumnName==0 ){
  149620. /* Query for existance of table only */
  149621. }else{
  149622. for(iCol=0; iCol<pTab->nCol; iCol++){
  149623. pCol = &pTab->aCol[iCol];
  149624. if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
  149625. break;
  149626. }
  149627. }
  149628. if( iCol==pTab->nCol ){
  149629. if( HasRowid(pTab) && sqlite3IsRowid(zColumnName) ){
  149630. iCol = pTab->iPKey;
  149631. pCol = iCol>=0 ? &pTab->aCol[iCol] : 0;
  149632. }else{
  149633. pTab = 0;
  149634. goto error_out;
  149635. }
  149636. }
  149637. }
  149638. /* The following block stores the meta information that will be returned
  149639. ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
  149640. ** and autoinc. At this point there are two possibilities:
  149641. **
  149642. ** 1. The specified column name was rowid", "oid" or "_rowid_"
  149643. ** and there is no explicitly declared IPK column.
  149644. **
  149645. ** 2. The table is not a view and the column name identified an
  149646. ** explicitly declared column. Copy meta information from *pCol.
  149647. */
  149648. if( pCol ){
  149649. zDataType = sqlite3ColumnType(pCol,0);
  149650. zCollSeq = pCol->zColl;
  149651. notnull = pCol->notNull!=0;
  149652. primarykey = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
  149653. autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
  149654. }else{
  149655. zDataType = "INTEGER";
  149656. primarykey = 1;
  149657. }
  149658. if( !zCollSeq ){
  149659. zCollSeq = sqlite3StrBINARY;
  149660. }
  149661. error_out:
  149662. sqlite3BtreeLeaveAll(db);
  149663. /* Whether the function call succeeded or failed, set the output parameters
  149664. ** to whatever their local counterparts contain. If an error did occur,
  149665. ** this has the effect of zeroing all output parameters.
  149666. */
  149667. if( pzDataType ) *pzDataType = zDataType;
  149668. if( pzCollSeq ) *pzCollSeq = zCollSeq;
  149669. if( pNotNull ) *pNotNull = notnull;
  149670. if( pPrimaryKey ) *pPrimaryKey = primarykey;
  149671. if( pAutoinc ) *pAutoinc = autoinc;
  149672. if( SQLITE_OK==rc && !pTab ){
  149673. sqlite3DbFree(db, zErrMsg);
  149674. zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
  149675. zColumnName);
  149676. rc = SQLITE_ERROR;
  149677. }
  149678. sqlite3ErrorWithMsg(db, rc, (zErrMsg?"%s":0), zErrMsg);
  149679. sqlite3DbFree(db, zErrMsg);
  149680. rc = sqlite3ApiExit(db, rc);
  149681. sqlite3_mutex_leave(db->mutex);
  149682. return rc;
  149683. }
  149684. /*
  149685. ** Sleep for a little while. Return the amount of time slept.
  149686. */
  149687. SQLITE_API int sqlite3_sleep(int ms){
  149688. sqlite3_vfs *pVfs;
  149689. int rc;
  149690. pVfs = sqlite3_vfs_find(0);
  149691. if( pVfs==0 ) return 0;
  149692. /* This function works in milliseconds, but the underlying OsSleep()
  149693. ** API uses microseconds. Hence the 1000's.
  149694. */
  149695. rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
  149696. return rc;
  149697. }
  149698. /*
  149699. ** Enable or disable the extended result codes.
  149700. */
  149701. SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
  149702. #ifdef SQLITE_ENABLE_API_ARMOR
  149703. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  149704. #endif
  149705. sqlite3_mutex_enter(db->mutex);
  149706. db->errMask = onoff ? 0xffffffff : 0xff;
  149707. sqlite3_mutex_leave(db->mutex);
  149708. return SQLITE_OK;
  149709. }
  149710. /*
  149711. ** Invoke the xFileControl method on a particular database.
  149712. */
  149713. SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
  149714. int rc = SQLITE_ERROR;
  149715. Btree *pBtree;
  149716. #ifdef SQLITE_ENABLE_API_ARMOR
  149717. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  149718. #endif
  149719. sqlite3_mutex_enter(db->mutex);
  149720. pBtree = sqlite3DbNameToBtree(db, zDbName);
  149721. if( pBtree ){
  149722. Pager *pPager;
  149723. sqlite3_file *fd;
  149724. sqlite3BtreeEnter(pBtree);
  149725. pPager = sqlite3BtreePager(pBtree);
  149726. assert( pPager!=0 );
  149727. fd = sqlite3PagerFile(pPager);
  149728. assert( fd!=0 );
  149729. if( op==SQLITE_FCNTL_FILE_POINTER ){
  149730. *(sqlite3_file**)pArg = fd;
  149731. rc = SQLITE_OK;
  149732. }else if( op==SQLITE_FCNTL_VFS_POINTER ){
  149733. *(sqlite3_vfs**)pArg = sqlite3PagerVfs(pPager);
  149734. rc = SQLITE_OK;
  149735. }else if( op==SQLITE_FCNTL_JOURNAL_POINTER ){
  149736. *(sqlite3_file**)pArg = sqlite3PagerJrnlFile(pPager);
  149737. rc = SQLITE_OK;
  149738. }else if( op==SQLITE_FCNTL_DATA_VERSION ){
  149739. *(unsigned int*)pArg = sqlite3PagerDataVersion(pPager);
  149740. rc = SQLITE_OK;
  149741. }else{
  149742. rc = sqlite3OsFileControl(fd, op, pArg);
  149743. }
  149744. sqlite3BtreeLeave(pBtree);
  149745. }
  149746. sqlite3_mutex_leave(db->mutex);
  149747. return rc;
  149748. }
  149749. /*
  149750. ** Interface to the testing logic.
  149751. */
  149752. SQLITE_API int sqlite3_test_control(int op, ...){
  149753. int rc = 0;
  149754. #ifdef SQLITE_UNTESTABLE
  149755. UNUSED_PARAMETER(op);
  149756. #else
  149757. va_list ap;
  149758. va_start(ap, op);
  149759. switch( op ){
  149760. /*
  149761. ** Save the current state of the PRNG.
  149762. */
  149763. case SQLITE_TESTCTRL_PRNG_SAVE: {
  149764. sqlite3PrngSaveState();
  149765. break;
  149766. }
  149767. /*
  149768. ** Restore the state of the PRNG to the last state saved using
  149769. ** PRNG_SAVE. If PRNG_SAVE has never before been called, then
  149770. ** this verb acts like PRNG_RESET.
  149771. */
  149772. case SQLITE_TESTCTRL_PRNG_RESTORE: {
  149773. sqlite3PrngRestoreState();
  149774. break;
  149775. }
  149776. /*
  149777. ** Reset the PRNG back to its uninitialized state. The next call
  149778. ** to sqlite3_randomness() will reseed the PRNG using a single call
  149779. ** to the xRandomness method of the default VFS.
  149780. */
  149781. case SQLITE_TESTCTRL_PRNG_RESET: {
  149782. sqlite3_randomness(0,0);
  149783. break;
  149784. }
  149785. /*
  149786. ** sqlite3_test_control(BITVEC_TEST, size, program)
  149787. **
  149788. ** Run a test against a Bitvec object of size. The program argument
  149789. ** is an array of integers that defines the test. Return -1 on a
  149790. ** memory allocation error, 0 on success, or non-zero for an error.
  149791. ** See the sqlite3BitvecBuiltinTest() for additional information.
  149792. */
  149793. case SQLITE_TESTCTRL_BITVEC_TEST: {
  149794. int sz = va_arg(ap, int);
  149795. int *aProg = va_arg(ap, int*);
  149796. rc = sqlite3BitvecBuiltinTest(sz, aProg);
  149797. break;
  149798. }
  149799. /*
  149800. ** sqlite3_test_control(FAULT_INSTALL, xCallback)
  149801. **
  149802. ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called,
  149803. ** if xCallback is not NULL.
  149804. **
  149805. ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0)
  149806. ** is called immediately after installing the new callback and the return
  149807. ** value from sqlite3FaultSim(0) becomes the return from
  149808. ** sqlite3_test_control().
  149809. */
  149810. case SQLITE_TESTCTRL_FAULT_INSTALL: {
  149811. /* MSVC is picky about pulling func ptrs from va lists.
  149812. ** http://support.microsoft.com/kb/47961
  149813. ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int));
  149814. */
  149815. typedef int(*TESTCALLBACKFUNC_t)(int);
  149816. sqlite3GlobalConfig.xTestCallback = va_arg(ap, TESTCALLBACKFUNC_t);
  149817. rc = sqlite3FaultSim(0);
  149818. break;
  149819. }
  149820. /*
  149821. ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
  149822. **
  149823. ** Register hooks to call to indicate which malloc() failures
  149824. ** are benign.
  149825. */
  149826. case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
  149827. typedef void (*void_function)(void);
  149828. void_function xBenignBegin;
  149829. void_function xBenignEnd;
  149830. xBenignBegin = va_arg(ap, void_function);
  149831. xBenignEnd = va_arg(ap, void_function);
  149832. sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
  149833. break;
  149834. }
  149835. /*
  149836. ** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
  149837. **
  149838. ** Set the PENDING byte to the value in the argument, if X>0.
  149839. ** Make no changes if X==0. Return the value of the pending byte
  149840. ** as it existing before this routine was called.
  149841. **
  149842. ** IMPORTANT: Changing the PENDING byte from 0x40000000 results in
  149843. ** an incompatible database file format. Changing the PENDING byte
  149844. ** while any database connection is open results in undefined and
  149845. ** deleterious behavior.
  149846. */
  149847. case SQLITE_TESTCTRL_PENDING_BYTE: {
  149848. rc = PENDING_BYTE;
  149849. #ifndef SQLITE_OMIT_WSD
  149850. {
  149851. unsigned int newVal = va_arg(ap, unsigned int);
  149852. if( newVal ) sqlite3PendingByte = newVal;
  149853. }
  149854. #endif
  149855. break;
  149856. }
  149857. /*
  149858. ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
  149859. **
  149860. ** This action provides a run-time test to see whether or not
  149861. ** assert() was enabled at compile-time. If X is true and assert()
  149862. ** is enabled, then the return value is true. If X is true and
  149863. ** assert() is disabled, then the return value is zero. If X is
  149864. ** false and assert() is enabled, then the assertion fires and the
  149865. ** process aborts. If X is false and assert() is disabled, then the
  149866. ** return value is zero.
  149867. */
  149868. case SQLITE_TESTCTRL_ASSERT: {
  149869. volatile int x = 0;
  149870. assert( /*side-effects-ok*/ (x = va_arg(ap,int))!=0 );
  149871. rc = x;
  149872. break;
  149873. }
  149874. /*
  149875. ** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
  149876. **
  149877. ** This action provides a run-time test to see how the ALWAYS and
  149878. ** NEVER macros were defined at compile-time.
  149879. **
  149880. ** The return value is ALWAYS(X) if X is true, or 0 if X is false.
  149881. **
  149882. ** The recommended test is X==2. If the return value is 2, that means
  149883. ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
  149884. ** default setting. If the return value is 1, then ALWAYS() is either
  149885. ** hard-coded to true or else it asserts if its argument is false.
  149886. ** The first behavior (hard-coded to true) is the case if
  149887. ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
  149888. ** behavior (assert if the argument to ALWAYS() is false) is the case if
  149889. ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
  149890. **
  149891. ** The run-time test procedure might look something like this:
  149892. **
  149893. ** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
  149894. ** // ALWAYS() and NEVER() are no-op pass-through macros
  149895. ** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
  149896. ** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
  149897. ** }else{
  149898. ** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0.
  149899. ** }
  149900. */
  149901. case SQLITE_TESTCTRL_ALWAYS: {
  149902. int x = va_arg(ap,int);
  149903. rc = x ? ALWAYS(x) : 0;
  149904. break;
  149905. }
  149906. /*
  149907. ** sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER);
  149908. **
  149909. ** The integer returned reveals the byte-order of the computer on which
  149910. ** SQLite is running:
  149911. **
  149912. ** 1 big-endian, determined at run-time
  149913. ** 10 little-endian, determined at run-time
  149914. ** 432101 big-endian, determined at compile-time
  149915. ** 123410 little-endian, determined at compile-time
  149916. */
  149917. case SQLITE_TESTCTRL_BYTEORDER: {
  149918. rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN;
  149919. break;
  149920. }
  149921. /* sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
  149922. **
  149923. ** Set the nReserve size to N for the main database on the database
  149924. ** connection db.
  149925. */
  149926. case SQLITE_TESTCTRL_RESERVE: {
  149927. sqlite3 *db = va_arg(ap, sqlite3*);
  149928. int x = va_arg(ap,int);
  149929. sqlite3_mutex_enter(db->mutex);
  149930. sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
  149931. sqlite3_mutex_leave(db->mutex);
  149932. break;
  149933. }
  149934. /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
  149935. **
  149936. ** Enable or disable various optimizations for testing purposes. The
  149937. ** argument N is a bitmask of optimizations to be disabled. For normal
  149938. ** operation N should be 0. The idea is that a test program (like the
  149939. ** SQL Logic Test or SLT test module) can run the same SQL multiple times
  149940. ** with various optimizations disabled to verify that the same answer
  149941. ** is obtained in every case.
  149942. */
  149943. case SQLITE_TESTCTRL_OPTIMIZATIONS: {
  149944. sqlite3 *db = va_arg(ap, sqlite3*);
  149945. db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
  149946. break;
  149947. }
  149948. /* sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
  149949. **
  149950. ** If parameter onoff is non-zero, subsequent calls to localtime()
  149951. ** and its variants fail. If onoff is zero, undo this setting.
  149952. */
  149953. case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
  149954. sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
  149955. break;
  149956. }
  149957. /* sqlite3_test_control(SQLITE_TESTCTRL_INTERNAL_FUNCS, int onoff);
  149958. **
  149959. ** If parameter onoff is non-zero, internal-use-only SQL functions
  149960. ** are visible to ordinary SQL. This is useful for testing but is
  149961. ** unsafe because invalid parameters to those internal-use-only functions
  149962. ** can result in crashes or segfaults.
  149963. */
  149964. case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS: {
  149965. sqlite3GlobalConfig.bInternalFunctions = va_arg(ap, int);
  149966. break;
  149967. }
  149968. /* sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int);
  149969. **
  149970. ** Set or clear a flag that indicates that the database file is always well-
  149971. ** formed and never corrupt. This flag is clear by default, indicating that
  149972. ** database files might have arbitrary corruption. Setting the flag during
  149973. ** testing causes certain assert() statements in the code to be activated
  149974. ** that demonstrat invariants on well-formed database files.
  149975. */
  149976. case SQLITE_TESTCTRL_NEVER_CORRUPT: {
  149977. sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int);
  149978. break;
  149979. }
  149980. /* Set the threshold at which OP_Once counters reset back to zero.
  149981. ** By default this is 0x7ffffffe (over 2 billion), but that value is
  149982. ** too big to test in a reasonable amount of time, so this control is
  149983. ** provided to set a small and easily reachable reset value.
  149984. */
  149985. case SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD: {
  149986. sqlite3GlobalConfig.iOnceResetThreshold = va_arg(ap, int);
  149987. break;
  149988. }
  149989. /* sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr);
  149990. **
  149991. ** Set the VDBE coverage callback function to xCallback with context
  149992. ** pointer ptr.
  149993. */
  149994. case SQLITE_TESTCTRL_VDBE_COVERAGE: {
  149995. #ifdef SQLITE_VDBE_COVERAGE
  149996. typedef void (*branch_callback)(void*,unsigned int,
  149997. unsigned char,unsigned char);
  149998. sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback);
  149999. sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*);
  150000. #endif
  150001. break;
  150002. }
  150003. /* sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */
  150004. case SQLITE_TESTCTRL_SORTER_MMAP: {
  150005. sqlite3 *db = va_arg(ap, sqlite3*);
  150006. db->nMaxSorterMmap = va_arg(ap, int);
  150007. break;
  150008. }
  150009. /* sqlite3_test_control(SQLITE_TESTCTRL_ISINIT);
  150010. **
  150011. ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if
  150012. ** not.
  150013. */
  150014. case SQLITE_TESTCTRL_ISINIT: {
  150015. if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR;
  150016. break;
  150017. }
  150018. /* sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, db, dbName, onOff, tnum);
  150019. **
  150020. ** This test control is used to create imposter tables. "db" is a pointer
  150021. ** to the database connection. dbName is the database name (ex: "main" or
  150022. ** "temp") which will receive the imposter. "onOff" turns imposter mode on
  150023. ** or off. "tnum" is the root page of the b-tree to which the imposter
  150024. ** table should connect.
  150025. **
  150026. ** Enable imposter mode only when the schema has already been parsed. Then
  150027. ** run a single CREATE TABLE statement to construct the imposter table in
  150028. ** the parsed schema. Then turn imposter mode back off again.
  150029. **
  150030. ** If onOff==0 and tnum>0 then reset the schema for all databases, causing
  150031. ** the schema to be reparsed the next time it is needed. This has the
  150032. ** effect of erasing all imposter tables.
  150033. */
  150034. case SQLITE_TESTCTRL_IMPOSTER: {
  150035. sqlite3 *db = va_arg(ap, sqlite3*);
  150036. sqlite3_mutex_enter(db->mutex);
  150037. db->init.iDb = sqlite3FindDbName(db, va_arg(ap,const char*));
  150038. db->init.busy = db->init.imposterTable = va_arg(ap,int);
  150039. db->init.newTnum = va_arg(ap,int);
  150040. if( db->init.busy==0 && db->init.newTnum>0 ){
  150041. sqlite3ResetAllSchemasOfConnection(db);
  150042. }
  150043. sqlite3_mutex_leave(db->mutex);
  150044. break;
  150045. }
  150046. #if defined(YYCOVERAGE)
  150047. /* sqlite3_test_control(SQLITE_TESTCTRL_PARSER_COVERAGE, FILE *out)
  150048. **
  150049. ** This test control (only available when SQLite is compiled with
  150050. ** -DYYCOVERAGE) writes a report onto "out" that shows all
  150051. ** state/lookahead combinations in the parser state machine
  150052. ** which are never exercised. If any state is missed, make the
  150053. ** return code SQLITE_ERROR.
  150054. */
  150055. case SQLITE_TESTCTRL_PARSER_COVERAGE: {
  150056. FILE *out = va_arg(ap, FILE*);
  150057. if( sqlite3ParserCoverage(out) ) rc = SQLITE_ERROR;
  150058. break;
  150059. }
  150060. #endif /* defined(YYCOVERAGE) */
  150061. /* sqlite3_test_control(SQLITE_TESTCTRL_RESULT_INTREAL, sqlite3_context*);
  150062. **
  150063. ** This test-control causes the most recent sqlite3_result_int64() value
  150064. ** to be interpreted as a MEM_IntReal instead of as an MEM_Int. Normally,
  150065. ** MEM_IntReal values only arise during an INSERT operation of integer
  150066. ** values into a REAL column, so they can be challenging to test. This
  150067. ** test-control enables us to write an intreal() SQL function that can
  150068. ** inject an intreal() value at arbitrary places in an SQL statement,
  150069. ** for testing purposes.
  150070. */
  150071. case SQLITE_TESTCTRL_RESULT_INTREAL: {
  150072. sqlite3_context *pCtx = va_arg(ap, sqlite3_context*);
  150073. sqlite3ResultIntReal(pCtx);
  150074. break;
  150075. }
  150076. }
  150077. va_end(ap);
  150078. #endif /* SQLITE_UNTESTABLE */
  150079. return rc;
  150080. }
  150081. /*
  150082. ** This is a utility routine, useful to VFS implementations, that checks
  150083. ** to see if a database file was a URI that contained a specific query
  150084. ** parameter, and if so obtains the value of the query parameter.
  150085. **
  150086. ** The zFilename argument is the filename pointer passed into the xOpen()
  150087. ** method of a VFS implementation. The zParam argument is the name of the
  150088. ** query parameter we seek. This routine returns the value of the zParam
  150089. ** parameter if it exists. If the parameter does not exist, this routine
  150090. ** returns a NULL pointer.
  150091. */
  150092. SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
  150093. if( zFilename==0 || zParam==0 ) return 0;
  150094. zFilename += sqlite3Strlen30(zFilename) + 1;
  150095. while( zFilename[0] ){
  150096. int x = strcmp(zFilename, zParam);
  150097. zFilename += sqlite3Strlen30(zFilename) + 1;
  150098. if( x==0 ) return zFilename;
  150099. zFilename += sqlite3Strlen30(zFilename) + 1;
  150100. }
  150101. return 0;
  150102. }
  150103. /*
  150104. ** Return a boolean value for a query parameter.
  150105. */
  150106. SQLITE_API int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
  150107. const char *z = sqlite3_uri_parameter(zFilename, zParam);
  150108. bDflt = bDflt!=0;
  150109. return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
  150110. }
  150111. /*
  150112. ** Return a 64-bit integer value for a query parameter.
  150113. */
  150114. SQLITE_API sqlite3_int64 sqlite3_uri_int64(
  150115. const char *zFilename, /* Filename as passed to xOpen */
  150116. const char *zParam, /* URI parameter sought */
  150117. sqlite3_int64 bDflt /* return if parameter is missing */
  150118. ){
  150119. const char *z = sqlite3_uri_parameter(zFilename, zParam);
  150120. sqlite3_int64 v;
  150121. if( z && sqlite3DecOrHexToI64(z, &v)==0 ){
  150122. bDflt = v;
  150123. }
  150124. return bDflt;
  150125. }
  150126. /*
  150127. ** Return the Btree pointer identified by zDbName. Return NULL if not found.
  150128. */
  150129. SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
  150130. int iDb = zDbName ? sqlite3FindDbName(db, zDbName) : 0;
  150131. return iDb<0 ? 0 : db->aDb[iDb].pBt;
  150132. }
  150133. /*
  150134. ** Return the filename of the database associated with a database
  150135. ** connection.
  150136. */
  150137. SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
  150138. Btree *pBt;
  150139. #ifdef SQLITE_ENABLE_API_ARMOR
  150140. if( !sqlite3SafetyCheckOk(db) ){
  150141. (void)SQLITE_MISUSE_BKPT;
  150142. return 0;
  150143. }
  150144. #endif
  150145. pBt = sqlite3DbNameToBtree(db, zDbName);
  150146. return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
  150147. }
  150148. /*
  150149. ** Return 1 if database is read-only or 0 if read/write. Return -1 if
  150150. ** no such database exists.
  150151. */
  150152. SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
  150153. Btree *pBt;
  150154. #ifdef SQLITE_ENABLE_API_ARMOR
  150155. if( !sqlite3SafetyCheckOk(db) ){
  150156. (void)SQLITE_MISUSE_BKPT;
  150157. return -1;
  150158. }
  150159. #endif
  150160. pBt = sqlite3DbNameToBtree(db, zDbName);
  150161. return pBt ? sqlite3BtreeIsReadonly(pBt) : -1;
  150162. }
  150163. #ifdef SQLITE_ENABLE_SNAPSHOT
  150164. /*
  150165. ** Obtain a snapshot handle for the snapshot of database zDb currently
  150166. ** being read by handle db.
  150167. */
  150168. SQLITE_API int sqlite3_snapshot_get(
  150169. sqlite3 *db,
  150170. const char *zDb,
  150171. sqlite3_snapshot **ppSnapshot
  150172. ){
  150173. int rc = SQLITE_ERROR;
  150174. #ifndef SQLITE_OMIT_WAL
  150175. #ifdef SQLITE_ENABLE_API_ARMOR
  150176. if( !sqlite3SafetyCheckOk(db) ){
  150177. return SQLITE_MISUSE_BKPT;
  150178. }
  150179. #endif
  150180. sqlite3_mutex_enter(db->mutex);
  150181. if( db->autoCommit==0 ){
  150182. int iDb = sqlite3FindDbName(db, zDb);
  150183. if( iDb==0 || iDb>1 ){
  150184. Btree *pBt = db->aDb[iDb].pBt;
  150185. if( 0==sqlite3BtreeIsInTrans(pBt) ){
  150186. rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
  150187. if( rc==SQLITE_OK ){
  150188. rc = sqlite3PagerSnapshotGet(sqlite3BtreePager(pBt), ppSnapshot);
  150189. }
  150190. }
  150191. }
  150192. }
  150193. sqlite3_mutex_leave(db->mutex);
  150194. #endif /* SQLITE_OMIT_WAL */
  150195. return rc;
  150196. }
  150197. /*
  150198. ** Open a read-transaction on the snapshot idendified by pSnapshot.
  150199. */
  150200. SQLITE_API int sqlite3_snapshot_open(
  150201. sqlite3 *db,
  150202. const char *zDb,
  150203. sqlite3_snapshot *pSnapshot
  150204. ){
  150205. int rc = SQLITE_ERROR;
  150206. #ifndef SQLITE_OMIT_WAL
  150207. #ifdef SQLITE_ENABLE_API_ARMOR
  150208. if( !sqlite3SafetyCheckOk(db) ){
  150209. return SQLITE_MISUSE_BKPT;
  150210. }
  150211. #endif
  150212. sqlite3_mutex_enter(db->mutex);
  150213. if( db->autoCommit==0 ){
  150214. int iDb;
  150215. iDb = sqlite3FindDbName(db, zDb);
  150216. if( iDb==0 || iDb>1 ){
  150217. Btree *pBt = db->aDb[iDb].pBt;
  150218. if( sqlite3BtreeIsInTrans(pBt)==0 ){
  150219. Pager *pPager = sqlite3BtreePager(pBt);
  150220. int bUnlock = 0;
  150221. if( sqlite3BtreeIsInReadTrans(pBt) ){
  150222. if( db->nVdbeActive==0 ){
  150223. rc = sqlite3PagerSnapshotCheck(pPager, pSnapshot);
  150224. if( rc==SQLITE_OK ){
  150225. bUnlock = 1;
  150226. rc = sqlite3BtreeCommit(pBt);
  150227. }
  150228. }
  150229. }else{
  150230. rc = SQLITE_OK;
  150231. }
  150232. if( rc==SQLITE_OK ){
  150233. rc = sqlite3PagerSnapshotOpen(pPager, pSnapshot);
  150234. }
  150235. if( rc==SQLITE_OK ){
  150236. rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
  150237. sqlite3PagerSnapshotOpen(pPager, 0);
  150238. }
  150239. if( bUnlock ){
  150240. sqlite3PagerSnapshotUnlock(pPager);
  150241. }
  150242. }
  150243. }
  150244. }
  150245. sqlite3_mutex_leave(db->mutex);
  150246. #endif /* SQLITE_OMIT_WAL */
  150247. return rc;
  150248. }
  150249. /*
  150250. ** Recover as many snapshots as possible from the wal file associated with
  150251. ** schema zDb of database db.
  150252. */
  150253. SQLITE_API int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb){
  150254. int rc = SQLITE_ERROR;
  150255. int iDb;
  150256. #ifndef SQLITE_OMIT_WAL
  150257. #ifdef SQLITE_ENABLE_API_ARMOR
  150258. if( !sqlite3SafetyCheckOk(db) ){
  150259. return SQLITE_MISUSE_BKPT;
  150260. }
  150261. #endif
  150262. sqlite3_mutex_enter(db->mutex);
  150263. iDb = sqlite3FindDbName(db, zDb);
  150264. if( iDb==0 || iDb>1 ){
  150265. Btree *pBt = db->aDb[iDb].pBt;
  150266. if( 0==sqlite3BtreeIsInReadTrans(pBt) ){
  150267. rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
  150268. if( rc==SQLITE_OK ){
  150269. rc = sqlite3PagerSnapshotRecover(sqlite3BtreePager(pBt));
  150270. sqlite3BtreeCommit(pBt);
  150271. }
  150272. }
  150273. }
  150274. sqlite3_mutex_leave(db->mutex);
  150275. #endif /* SQLITE_OMIT_WAL */
  150276. return rc;
  150277. }
  150278. /*
  150279. ** Free a snapshot handle obtained from sqlite3_snapshot_get().
  150280. */
  150281. SQLITE_API void sqlite3_snapshot_free(sqlite3_snapshot *pSnapshot){
  150282. sqlite3_free(pSnapshot);
  150283. }
  150284. #endif /* SQLITE_ENABLE_SNAPSHOT */
  150285. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  150286. /*
  150287. ** Given the name of a compile-time option, return true if that option
  150288. ** was used and false if not.
  150289. **
  150290. ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
  150291. ** is not required for a match.
  150292. */
  150293. SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
  150294. int i, n;
  150295. int nOpt;
  150296. const char **azCompileOpt;
  150297. #if SQLITE_ENABLE_API_ARMOR
  150298. if( zOptName==0 ){
  150299. (void)SQLITE_MISUSE_BKPT;
  150300. return 0;
  150301. }
  150302. #endif
  150303. azCompileOpt = sqlite3CompileOptions(&nOpt);
  150304. if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
  150305. n = sqlite3Strlen30(zOptName);
  150306. /* Since nOpt is normally in single digits, a linear search is
  150307. ** adequate. No need for a binary search. */
  150308. for(i=0; i<nOpt; i++){
  150309. if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
  150310. && sqlite3IsIdChar((unsigned char)azCompileOpt[i][n])==0
  150311. ){
  150312. return 1;
  150313. }
  150314. }
  150315. return 0;
  150316. }
  150317. /*
  150318. ** Return the N-th compile-time option string. If N is out of range,
  150319. ** return a NULL pointer.
  150320. */
  150321. SQLITE_API const char *sqlite3_compileoption_get(int N){
  150322. int nOpt;
  150323. const char **azCompileOpt;
  150324. azCompileOpt = sqlite3CompileOptions(&nOpt);
  150325. if( N>=0 && N<nOpt ){
  150326. return azCompileOpt[N];
  150327. }
  150328. return 0;
  150329. }
  150330. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  150331. /************** End of main.c ************************************************/
  150332. /************** Begin file notify.c ******************************************/
  150333. /*
  150334. ** 2009 March 3
  150335. **
  150336. ** The author disclaims copyright to this source code. In place of
  150337. ** a legal notice, here is a blessing:
  150338. **
  150339. ** May you do good and not evil.
  150340. ** May you find forgiveness for yourself and forgive others.
  150341. ** May you share freely, never taking more than you give.
  150342. **
  150343. *************************************************************************
  150344. **
  150345. ** This file contains the implementation of the sqlite3_unlock_notify()
  150346. ** API method and its associated functionality.
  150347. */
  150348. /* #include "sqliteInt.h" */
  150349. /* #include "btreeInt.h" */
  150350. /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
  150351. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  150352. /*
  150353. ** Public interfaces:
  150354. **
  150355. ** sqlite3ConnectionBlocked()
  150356. ** sqlite3ConnectionUnlocked()
  150357. ** sqlite3ConnectionClosed()
  150358. ** sqlite3_unlock_notify()
  150359. */
  150360. #define assertMutexHeld() \
  150361. assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
  150362. /*
  150363. ** Head of a linked list of all sqlite3 objects created by this process
  150364. ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
  150365. ** is not NULL. This variable may only accessed while the STATIC_MASTER
  150366. ** mutex is held.
  150367. */
  150368. static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
  150369. #ifndef NDEBUG
  150370. /*
  150371. ** This function is a complex assert() that verifies the following
  150372. ** properties of the blocked connections list:
  150373. **
  150374. ** 1) Each entry in the list has a non-NULL value for either
  150375. ** pUnlockConnection or pBlockingConnection, or both.
  150376. **
  150377. ** 2) All entries in the list that share a common value for
  150378. ** xUnlockNotify are grouped together.
  150379. **
  150380. ** 3) If the argument db is not NULL, then none of the entries in the
  150381. ** blocked connections list have pUnlockConnection or pBlockingConnection
  150382. ** set to db. This is used when closing connection db.
  150383. */
  150384. static void checkListProperties(sqlite3 *db){
  150385. sqlite3 *p;
  150386. for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
  150387. int seen = 0;
  150388. sqlite3 *p2;
  150389. /* Verify property (1) */
  150390. assert( p->pUnlockConnection || p->pBlockingConnection );
  150391. /* Verify property (2) */
  150392. for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
  150393. if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
  150394. assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
  150395. assert( db==0 || p->pUnlockConnection!=db );
  150396. assert( db==0 || p->pBlockingConnection!=db );
  150397. }
  150398. }
  150399. }
  150400. #else
  150401. # define checkListProperties(x)
  150402. #endif
  150403. /*
  150404. ** Remove connection db from the blocked connections list. If connection
  150405. ** db is not currently a part of the list, this function is a no-op.
  150406. */
  150407. static void removeFromBlockedList(sqlite3 *db){
  150408. sqlite3 **pp;
  150409. assertMutexHeld();
  150410. for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
  150411. if( *pp==db ){
  150412. *pp = (*pp)->pNextBlocked;
  150413. break;
  150414. }
  150415. }
  150416. }
  150417. /*
  150418. ** Add connection db to the blocked connections list. It is assumed
  150419. ** that it is not already a part of the list.
  150420. */
  150421. static void addToBlockedList(sqlite3 *db){
  150422. sqlite3 **pp;
  150423. assertMutexHeld();
  150424. for(
  150425. pp=&sqlite3BlockedList;
  150426. *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
  150427. pp=&(*pp)->pNextBlocked
  150428. );
  150429. db->pNextBlocked = *pp;
  150430. *pp = db;
  150431. }
  150432. /*
  150433. ** Obtain the STATIC_MASTER mutex.
  150434. */
  150435. static void enterMutex(void){
  150436. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  150437. checkListProperties(0);
  150438. }
  150439. /*
  150440. ** Release the STATIC_MASTER mutex.
  150441. */
  150442. static void leaveMutex(void){
  150443. assertMutexHeld();
  150444. checkListProperties(0);
  150445. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  150446. }
  150447. /*
  150448. ** Register an unlock-notify callback.
  150449. **
  150450. ** This is called after connection "db" has attempted some operation
  150451. ** but has received an SQLITE_LOCKED error because another connection
  150452. ** (call it pOther) in the same process was busy using the same shared
  150453. ** cache. pOther is found by looking at db->pBlockingConnection.
  150454. **
  150455. ** If there is no blocking connection, the callback is invoked immediately,
  150456. ** before this routine returns.
  150457. **
  150458. ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
  150459. ** a deadlock.
  150460. **
  150461. ** Otherwise, make arrangements to invoke xNotify when pOther drops
  150462. ** its locks.
  150463. **
  150464. ** Each call to this routine overrides any prior callbacks registered
  150465. ** on the same "db". If xNotify==0 then any prior callbacks are immediately
  150466. ** cancelled.
  150467. */
  150468. SQLITE_API int sqlite3_unlock_notify(
  150469. sqlite3 *db,
  150470. void (*xNotify)(void **, int),
  150471. void *pArg
  150472. ){
  150473. int rc = SQLITE_OK;
  150474. sqlite3_mutex_enter(db->mutex);
  150475. enterMutex();
  150476. if( xNotify==0 ){
  150477. removeFromBlockedList(db);
  150478. db->pBlockingConnection = 0;
  150479. db->pUnlockConnection = 0;
  150480. db->xUnlockNotify = 0;
  150481. db->pUnlockArg = 0;
  150482. }else if( 0==db->pBlockingConnection ){
  150483. /* The blocking transaction has been concluded. Or there never was a
  150484. ** blocking transaction. In either case, invoke the notify callback
  150485. ** immediately.
  150486. */
  150487. xNotify(&pArg, 1);
  150488. }else{
  150489. sqlite3 *p;
  150490. for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
  150491. if( p ){
  150492. rc = SQLITE_LOCKED; /* Deadlock detected. */
  150493. }else{
  150494. db->pUnlockConnection = db->pBlockingConnection;
  150495. db->xUnlockNotify = xNotify;
  150496. db->pUnlockArg = pArg;
  150497. removeFromBlockedList(db);
  150498. addToBlockedList(db);
  150499. }
  150500. }
  150501. leaveMutex();
  150502. assert( !db->mallocFailed );
  150503. sqlite3ErrorWithMsg(db, rc, (rc?"database is deadlocked":0));
  150504. sqlite3_mutex_leave(db->mutex);
  150505. return rc;
  150506. }
  150507. /*
  150508. ** This function is called while stepping or preparing a statement
  150509. ** associated with connection db. The operation will return SQLITE_LOCKED
  150510. ** to the user because it requires a lock that will not be available
  150511. ** until connection pBlocker concludes its current transaction.
  150512. */
  150513. SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
  150514. enterMutex();
  150515. if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
  150516. addToBlockedList(db);
  150517. }
  150518. db->pBlockingConnection = pBlocker;
  150519. leaveMutex();
  150520. }
  150521. /*
  150522. ** This function is called when
  150523. ** the transaction opened by database db has just finished. Locks held
  150524. ** by database connection db have been released.
  150525. **
  150526. ** This function loops through each entry in the blocked connections
  150527. ** list and does the following:
  150528. **
  150529. ** 1) If the sqlite3.pBlockingConnection member of a list entry is
  150530. ** set to db, then set pBlockingConnection=0.
  150531. **
  150532. ** 2) If the sqlite3.pUnlockConnection member of a list entry is
  150533. ** set to db, then invoke the configured unlock-notify callback and
  150534. ** set pUnlockConnection=0.
  150535. **
  150536. ** 3) If the two steps above mean that pBlockingConnection==0 and
  150537. ** pUnlockConnection==0, remove the entry from the blocked connections
  150538. ** list.
  150539. */
  150540. SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
  150541. void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
  150542. int nArg = 0; /* Number of entries in aArg[] */
  150543. sqlite3 **pp; /* Iterator variable */
  150544. void **aArg; /* Arguments to the unlock callback */
  150545. void **aDyn = 0; /* Dynamically allocated space for aArg[] */
  150546. void *aStatic[16]; /* Starter space for aArg[]. No malloc required */
  150547. aArg = aStatic;
  150548. enterMutex(); /* Enter STATIC_MASTER mutex */
  150549. /* This loop runs once for each entry in the blocked-connections list. */
  150550. for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
  150551. sqlite3 *p = *pp;
  150552. /* Step 1. */
  150553. if( p->pBlockingConnection==db ){
  150554. p->pBlockingConnection = 0;
  150555. }
  150556. /* Step 2. */
  150557. if( p->pUnlockConnection==db ){
  150558. assert( p->xUnlockNotify );
  150559. if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
  150560. xUnlockNotify(aArg, nArg);
  150561. nArg = 0;
  150562. }
  150563. sqlite3BeginBenignMalloc();
  150564. assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
  150565. assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
  150566. if( (!aDyn && nArg==(int)ArraySize(aStatic))
  150567. || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
  150568. ){
  150569. /* The aArg[] array needs to grow. */
  150570. void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
  150571. if( pNew ){
  150572. memcpy(pNew, aArg, nArg*sizeof(void *));
  150573. sqlite3_free(aDyn);
  150574. aDyn = aArg = pNew;
  150575. }else{
  150576. /* This occurs when the array of context pointers that need to
  150577. ** be passed to the unlock-notify callback is larger than the
  150578. ** aStatic[] array allocated on the stack and the attempt to
  150579. ** allocate a larger array from the heap has failed.
  150580. **
  150581. ** This is a difficult situation to handle. Returning an error
  150582. ** code to the caller is insufficient, as even if an error code
  150583. ** is returned the transaction on connection db will still be
  150584. ** closed and the unlock-notify callbacks on blocked connections
  150585. ** will go unissued. This might cause the application to wait
  150586. ** indefinitely for an unlock-notify callback that will never
  150587. ** arrive.
  150588. **
  150589. ** Instead, invoke the unlock-notify callback with the context
  150590. ** array already accumulated. We can then clear the array and
  150591. ** begin accumulating any further context pointers without
  150592. ** requiring any dynamic allocation. This is sub-optimal because
  150593. ** it means that instead of one callback with a large array of
  150594. ** context pointers the application will receive two or more
  150595. ** callbacks with smaller arrays of context pointers, which will
  150596. ** reduce the applications ability to prioritize multiple
  150597. ** connections. But it is the best that can be done under the
  150598. ** circumstances.
  150599. */
  150600. xUnlockNotify(aArg, nArg);
  150601. nArg = 0;
  150602. }
  150603. }
  150604. sqlite3EndBenignMalloc();
  150605. aArg[nArg++] = p->pUnlockArg;
  150606. xUnlockNotify = p->xUnlockNotify;
  150607. p->pUnlockConnection = 0;
  150608. p->xUnlockNotify = 0;
  150609. p->pUnlockArg = 0;
  150610. }
  150611. /* Step 3. */
  150612. if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
  150613. /* Remove connection p from the blocked connections list. */
  150614. *pp = p->pNextBlocked;
  150615. p->pNextBlocked = 0;
  150616. }else{
  150617. pp = &p->pNextBlocked;
  150618. }
  150619. }
  150620. if( nArg!=0 ){
  150621. xUnlockNotify(aArg, nArg);
  150622. }
  150623. sqlite3_free(aDyn);
  150624. leaveMutex(); /* Leave STATIC_MASTER mutex */
  150625. }
  150626. /*
  150627. ** This is called when the database connection passed as an argument is
  150628. ** being closed. The connection is removed from the blocked list.
  150629. */
  150630. SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
  150631. sqlite3ConnectionUnlocked(db);
  150632. enterMutex();
  150633. removeFromBlockedList(db);
  150634. checkListProperties(db);
  150635. leaveMutex();
  150636. }
  150637. #endif
  150638. /************** End of notify.c **********************************************/
  150639. /************** Begin file fts3.c ********************************************/
  150640. /*
  150641. ** 2006 Oct 10
  150642. **
  150643. ** The author disclaims copyright to this source code. In place of
  150644. ** a legal notice, here is a blessing:
  150645. **
  150646. ** May you do good and not evil.
  150647. ** May you find forgiveness for yourself and forgive others.
  150648. ** May you share freely, never taking more than you give.
  150649. **
  150650. ******************************************************************************
  150651. **
  150652. ** This is an SQLite module implementing full-text search.
  150653. */
  150654. /*
  150655. ** The code in this file is only compiled if:
  150656. **
  150657. ** * The FTS3 module is being built as an extension
  150658. ** (in which case SQLITE_CORE is not defined), or
  150659. **
  150660. ** * The FTS3 module is being built into the core of
  150661. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  150662. */
  150663. /* The full-text index is stored in a series of b+tree (-like)
  150664. ** structures called segments which map terms to doclists. The
  150665. ** structures are like b+trees in layout, but are constructed from the
  150666. ** bottom up in optimal fashion and are not updatable. Since trees
  150667. ** are built from the bottom up, things will be described from the
  150668. ** bottom up.
  150669. **
  150670. **
  150671. **** Varints ****
  150672. ** The basic unit of encoding is a variable-length integer called a
  150673. ** varint. We encode variable-length integers in little-endian order
  150674. ** using seven bits * per byte as follows:
  150675. **
  150676. ** KEY:
  150677. ** A = 0xxxxxxx 7 bits of data and one flag bit
  150678. ** B = 1xxxxxxx 7 bits of data and one flag bit
  150679. **
  150680. ** 7 bits - A
  150681. ** 14 bits - BA
  150682. ** 21 bits - BBA
  150683. ** and so on.
  150684. **
  150685. ** This is similar in concept to how sqlite encodes "varints" but
  150686. ** the encoding is not the same. SQLite varints are big-endian
  150687. ** are are limited to 9 bytes in length whereas FTS3 varints are
  150688. ** little-endian and can be up to 10 bytes in length (in theory).
  150689. **
  150690. ** Example encodings:
  150691. **
  150692. ** 1: 0x01
  150693. ** 127: 0x7f
  150694. ** 128: 0x81 0x00
  150695. **
  150696. **
  150697. **** Document lists ****
  150698. ** A doclist (document list) holds a docid-sorted list of hits for a
  150699. ** given term. Doclists hold docids and associated token positions.
  150700. ** A docid is the unique integer identifier for a single document.
  150701. ** A position is the index of a word within the document. The first
  150702. ** word of the document has a position of 0.
  150703. **
  150704. ** FTS3 used to optionally store character offsets using a compile-time
  150705. ** option. But that functionality is no longer supported.
  150706. **
  150707. ** A doclist is stored like this:
  150708. **
  150709. ** array {
  150710. ** varint docid; (delta from previous doclist)
  150711. ** array { (position list for column 0)
  150712. ** varint position; (2 more than the delta from previous position)
  150713. ** }
  150714. ** array {
  150715. ** varint POS_COLUMN; (marks start of position list for new column)
  150716. ** varint column; (index of new column)
  150717. ** array {
  150718. ** varint position; (2 more than the delta from previous position)
  150719. ** }
  150720. ** }
  150721. ** varint POS_END; (marks end of positions for this document.
  150722. ** }
  150723. **
  150724. ** Here, array { X } means zero or more occurrences of X, adjacent in
  150725. ** memory. A "position" is an index of a token in the token stream
  150726. ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
  150727. ** in the same logical place as the position element, and act as sentinals
  150728. ** ending a position list array. POS_END is 0. POS_COLUMN is 1.
  150729. ** The positions numbers are not stored literally but rather as two more
  150730. ** than the difference from the prior position, or the just the position plus
  150731. ** 2 for the first position. Example:
  150732. **
  150733. ** label: A B C D E F G H I J K
  150734. ** value: 123 5 9 1 1 14 35 0 234 72 0
  150735. **
  150736. ** The 123 value is the first docid. For column zero in this document
  150737. ** there are two matches at positions 3 and 10 (5-2 and 9-2+3). The 1
  150738. ** at D signals the start of a new column; the 1 at E indicates that the
  150739. ** new column is column number 1. There are two positions at 12 and 45
  150740. ** (14-2 and 35-2+12). The 0 at H indicate the end-of-document. The
  150741. ** 234 at I is the delta to next docid (357). It has one position 70
  150742. ** (72-2) and then terminates with the 0 at K.
  150743. **
  150744. ** A "position-list" is the list of positions for multiple columns for
  150745. ** a single docid. A "column-list" is the set of positions for a single
  150746. ** column. Hence, a position-list consists of one or more column-lists,
  150747. ** a document record consists of a docid followed by a position-list and
  150748. ** a doclist consists of one or more document records.
  150749. **
  150750. ** A bare doclist omits the position information, becoming an
  150751. ** array of varint-encoded docids.
  150752. **
  150753. **** Segment leaf nodes ****
  150754. ** Segment leaf nodes store terms and doclists, ordered by term. Leaf
  150755. ** nodes are written using LeafWriter, and read using LeafReader (to
  150756. ** iterate through a single leaf node's data) and LeavesReader (to
  150757. ** iterate through a segment's entire leaf layer). Leaf nodes have
  150758. ** the format:
  150759. **
  150760. ** varint iHeight; (height from leaf level, always 0)
  150761. ** varint nTerm; (length of first term)
  150762. ** char pTerm[nTerm]; (content of first term)
  150763. ** varint nDoclist; (length of term's associated doclist)
  150764. ** char pDoclist[nDoclist]; (content of doclist)
  150765. ** array {
  150766. ** (further terms are delta-encoded)
  150767. ** varint nPrefix; (length of prefix shared with previous term)
  150768. ** varint nSuffix; (length of unshared suffix)
  150769. ** char pTermSuffix[nSuffix];(unshared suffix of next term)
  150770. ** varint nDoclist; (length of term's associated doclist)
  150771. ** char pDoclist[nDoclist]; (content of doclist)
  150772. ** }
  150773. **
  150774. ** Here, array { X } means zero or more occurrences of X, adjacent in
  150775. ** memory.
  150776. **
  150777. ** Leaf nodes are broken into blocks which are stored contiguously in
  150778. ** the %_segments table in sorted order. This means that when the end
  150779. ** of a node is reached, the next term is in the node with the next
  150780. ** greater node id.
  150781. **
  150782. ** New data is spilled to a new leaf node when the current node
  150783. ** exceeds LEAF_MAX bytes (default 2048). New data which itself is
  150784. ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
  150785. ** node (a leaf node with a single term and doclist). The goal of
  150786. ** these settings is to pack together groups of small doclists while
  150787. ** making it efficient to directly access large doclists. The
  150788. ** assumption is that large doclists represent terms which are more
  150789. ** likely to be query targets.
  150790. **
  150791. ** TODO(shess) It may be useful for blocking decisions to be more
  150792. ** dynamic. For instance, it may make more sense to have a 2.5k leaf
  150793. ** node rather than splitting into 2k and .5k nodes. My intuition is
  150794. ** that this might extend through 2x or 4x the pagesize.
  150795. **
  150796. **
  150797. **** Segment interior nodes ****
  150798. ** Segment interior nodes store blockids for subtree nodes and terms
  150799. ** to describe what data is stored by the each subtree. Interior
  150800. ** nodes are written using InteriorWriter, and read using
  150801. ** InteriorReader. InteriorWriters are created as needed when
  150802. ** SegmentWriter creates new leaf nodes, or when an interior node
  150803. ** itself grows too big and must be split. The format of interior
  150804. ** nodes:
  150805. **
  150806. ** varint iHeight; (height from leaf level, always >0)
  150807. ** varint iBlockid; (block id of node's leftmost subtree)
  150808. ** optional {
  150809. ** varint nTerm; (length of first term)
  150810. ** char pTerm[nTerm]; (content of first term)
  150811. ** array {
  150812. ** (further terms are delta-encoded)
  150813. ** varint nPrefix; (length of shared prefix with previous term)
  150814. ** varint nSuffix; (length of unshared suffix)
  150815. ** char pTermSuffix[nSuffix]; (unshared suffix of next term)
  150816. ** }
  150817. ** }
  150818. **
  150819. ** Here, optional { X } means an optional element, while array { X }
  150820. ** means zero or more occurrences of X, adjacent in memory.
  150821. **
  150822. ** An interior node encodes n terms separating n+1 subtrees. The
  150823. ** subtree blocks are contiguous, so only the first subtree's blockid
  150824. ** is encoded. The subtree at iBlockid will contain all terms less
  150825. ** than the first term encoded (or all terms if no term is encoded).
  150826. ** Otherwise, for terms greater than or equal to pTerm[i] but less
  150827. ** than pTerm[i+1], the subtree for that term will be rooted at
  150828. ** iBlockid+i. Interior nodes only store enough term data to
  150829. ** distinguish adjacent children (if the rightmost term of the left
  150830. ** child is "something", and the leftmost term of the right child is
  150831. ** "wicked", only "w" is stored).
  150832. **
  150833. ** New data is spilled to a new interior node at the same height when
  150834. ** the current node exceeds INTERIOR_MAX bytes (default 2048).
  150835. ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
  150836. ** interior nodes and making the tree too skinny. The interior nodes
  150837. ** at a given height are naturally tracked by interior nodes at
  150838. ** height+1, and so on.
  150839. **
  150840. **
  150841. **** Segment directory ****
  150842. ** The segment directory in table %_segdir stores meta-information for
  150843. ** merging and deleting segments, and also the root node of the
  150844. ** segment's tree.
  150845. **
  150846. ** The root node is the top node of the segment's tree after encoding
  150847. ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
  150848. ** This could be either a leaf node or an interior node. If the top
  150849. ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
  150850. ** and a new root interior node is generated (which should always fit
  150851. ** within ROOT_MAX because it only needs space for 2 varints, the
  150852. ** height and the blockid of the previous root).
  150853. **
  150854. ** The meta-information in the segment directory is:
  150855. ** level - segment level (see below)
  150856. ** idx - index within level
  150857. ** - (level,idx uniquely identify a segment)
  150858. ** start_block - first leaf node
  150859. ** leaves_end_block - last leaf node
  150860. ** end_block - last block (including interior nodes)
  150861. ** root - contents of root node
  150862. **
  150863. ** If the root node is a leaf node, then start_block,
  150864. ** leaves_end_block, and end_block are all 0.
  150865. **
  150866. **
  150867. **** Segment merging ****
  150868. ** To amortize update costs, segments are grouped into levels and
  150869. ** merged in batches. Each increase in level represents exponentially
  150870. ** more documents.
  150871. **
  150872. ** New documents (actually, document updates) are tokenized and
  150873. ** written individually (using LeafWriter) to a level 0 segment, with
  150874. ** incrementing idx. When idx reaches MERGE_COUNT (default 16), all
  150875. ** level 0 segments are merged into a single level 1 segment. Level 1
  150876. ** is populated like level 0, and eventually MERGE_COUNT level 1
  150877. ** segments are merged to a single level 2 segment (representing
  150878. ** MERGE_COUNT^2 updates), and so on.
  150879. **
  150880. ** A segment merge traverses all segments at a given level in
  150881. ** parallel, performing a straightforward sorted merge. Since segment
  150882. ** leaf nodes are written in to the %_segments table in order, this
  150883. ** merge traverses the underlying sqlite disk structures efficiently.
  150884. ** After the merge, all segment blocks from the merged level are
  150885. ** deleted.
  150886. **
  150887. ** MERGE_COUNT controls how often we merge segments. 16 seems to be
  150888. ** somewhat of a sweet spot for insertion performance. 32 and 64 show
  150889. ** very similar performance numbers to 16 on insertion, though they're
  150890. ** a tiny bit slower (perhaps due to more overhead in merge-time
  150891. ** sorting). 8 is about 20% slower than 16, 4 about 50% slower than
  150892. ** 16, 2 about 66% slower than 16.
  150893. **
  150894. ** At query time, high MERGE_COUNT increases the number of segments
  150895. ** which need to be scanned and merged. For instance, with 100k docs
  150896. ** inserted:
  150897. **
  150898. ** MERGE_COUNT segments
  150899. ** 16 25
  150900. ** 8 12
  150901. ** 4 10
  150902. ** 2 6
  150903. **
  150904. ** This appears to have only a moderate impact on queries for very
  150905. ** frequent terms (which are somewhat dominated by segment merge
  150906. ** costs), and infrequent and non-existent terms still seem to be fast
  150907. ** even with many segments.
  150908. **
  150909. ** TODO(shess) That said, it would be nice to have a better query-side
  150910. ** argument for MERGE_COUNT of 16. Also, it is possible/likely that
  150911. ** optimizations to things like doclist merging will swing the sweet
  150912. ** spot around.
  150913. **
  150914. **
  150915. **
  150916. **** Handling of deletions and updates ****
  150917. ** Since we're using a segmented structure, with no docid-oriented
  150918. ** index into the term index, we clearly cannot simply update the term
  150919. ** index when a document is deleted or updated. For deletions, we
  150920. ** write an empty doclist (varint(docid) varint(POS_END)), for updates
  150921. ** we simply write the new doclist. Segment merges overwrite older
  150922. ** data for a particular docid with newer data, so deletes or updates
  150923. ** will eventually overtake the earlier data and knock it out. The
  150924. ** query logic likewise merges doclists so that newer data knocks out
  150925. ** older data.
  150926. */
  150927. /************** Include fts3Int.h in the middle of fts3.c ********************/
  150928. /************** Begin file fts3Int.h *****************************************/
  150929. /*
  150930. ** 2009 Nov 12
  150931. **
  150932. ** The author disclaims copyright to this source code. In place of
  150933. ** a legal notice, here is a blessing:
  150934. **
  150935. ** May you do good and not evil.
  150936. ** May you find forgiveness for yourself and forgive others.
  150937. ** May you share freely, never taking more than you give.
  150938. **
  150939. ******************************************************************************
  150940. **
  150941. */
  150942. #ifndef _FTSINT_H
  150943. #define _FTSINT_H
  150944. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  150945. # define NDEBUG 1
  150946. #endif
  150947. /* FTS3/FTS4 require virtual tables */
  150948. #ifdef SQLITE_OMIT_VIRTUALTABLE
  150949. # undef SQLITE_ENABLE_FTS3
  150950. # undef SQLITE_ENABLE_FTS4
  150951. #endif
  150952. /*
  150953. ** FTS4 is really an extension for FTS3. It is enabled using the
  150954. ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also all
  150955. ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
  150956. */
  150957. #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
  150958. # define SQLITE_ENABLE_FTS3
  150959. #endif
  150960. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  150961. /* If not building as part of the core, include sqlite3ext.h. */
  150962. #ifndef SQLITE_CORE
  150963. /* # include "sqlite3ext.h" */
  150964. SQLITE_EXTENSION_INIT3
  150965. #endif
  150966. /* #include "sqlite3.h" */
  150967. /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
  150968. /************** Begin file fts3_tokenizer.h **********************************/
  150969. /*
  150970. ** 2006 July 10
  150971. **
  150972. ** The author disclaims copyright to this source code.
  150973. **
  150974. *************************************************************************
  150975. ** Defines the interface to tokenizers used by fulltext-search. There
  150976. ** are three basic components:
  150977. **
  150978. ** sqlite3_tokenizer_module is a singleton defining the tokenizer
  150979. ** interface functions. This is essentially the class structure for
  150980. ** tokenizers.
  150981. **
  150982. ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
  150983. ** including customization information defined at creation time.
  150984. **
  150985. ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
  150986. ** tokens from a particular input.
  150987. */
  150988. #ifndef _FTS3_TOKENIZER_H_
  150989. #define _FTS3_TOKENIZER_H_
  150990. /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
  150991. ** If tokenizers are to be allowed to call sqlite3_*() functions, then
  150992. ** we will need a way to register the API consistently.
  150993. */
  150994. /* #include "sqlite3.h" */
  150995. /*
  150996. ** Structures used by the tokenizer interface. When a new tokenizer
  150997. ** implementation is registered, the caller provides a pointer to
  150998. ** an sqlite3_tokenizer_module containing pointers to the callback
  150999. ** functions that make up an implementation.
  151000. **
  151001. ** When an fts3 table is created, it passes any arguments passed to
  151002. ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
  151003. ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
  151004. ** implementation. The xCreate() function in turn returns an
  151005. ** sqlite3_tokenizer structure representing the specific tokenizer to
  151006. ** be used for the fts3 table (customized by the tokenizer clause arguments).
  151007. **
  151008. ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
  151009. ** method is called. It returns an sqlite3_tokenizer_cursor object
  151010. ** that may be used to tokenize a specific input buffer based on
  151011. ** the tokenization rules supplied by a specific sqlite3_tokenizer
  151012. ** object.
  151013. */
  151014. typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
  151015. typedef struct sqlite3_tokenizer sqlite3_tokenizer;
  151016. typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
  151017. struct sqlite3_tokenizer_module {
  151018. /*
  151019. ** Structure version. Should always be set to 0 or 1.
  151020. */
  151021. int iVersion;
  151022. /*
  151023. ** Create a new tokenizer. The values in the argv[] array are the
  151024. ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
  151025. ** TABLE statement that created the fts3 table. For example, if
  151026. ** the following SQL is executed:
  151027. **
  151028. ** CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
  151029. **
  151030. ** then argc is set to 2, and the argv[] array contains pointers
  151031. ** to the strings "arg1" and "arg2".
  151032. **
  151033. ** This method should return either SQLITE_OK (0), or an SQLite error
  151034. ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
  151035. ** to point at the newly created tokenizer structure. The generic
  151036. ** sqlite3_tokenizer.pModule variable should not be initialized by
  151037. ** this callback. The caller will do so.
  151038. */
  151039. int (*xCreate)(
  151040. int argc, /* Size of argv array */
  151041. const char *const*argv, /* Tokenizer argument strings */
  151042. sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
  151043. );
  151044. /*
  151045. ** Destroy an existing tokenizer. The fts3 module calls this method
  151046. ** exactly once for each successful call to xCreate().
  151047. */
  151048. int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
  151049. /*
  151050. ** Create a tokenizer cursor to tokenize an input buffer. The caller
  151051. ** is responsible for ensuring that the input buffer remains valid
  151052. ** until the cursor is closed (using the xClose() method).
  151053. */
  151054. int (*xOpen)(
  151055. sqlite3_tokenizer *pTokenizer, /* Tokenizer object */
  151056. const char *pInput, int nBytes, /* Input buffer */
  151057. sqlite3_tokenizer_cursor **ppCursor /* OUT: Created tokenizer cursor */
  151058. );
  151059. /*
  151060. ** Destroy an existing tokenizer cursor. The fts3 module calls this
  151061. ** method exactly once for each successful call to xOpen().
  151062. */
  151063. int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
  151064. /*
  151065. ** Retrieve the next token from the tokenizer cursor pCursor. This
  151066. ** method should either return SQLITE_OK and set the values of the
  151067. ** "OUT" variables identified below, or SQLITE_DONE to indicate that
  151068. ** the end of the buffer has been reached, or an SQLite error code.
  151069. **
  151070. ** *ppToken should be set to point at a buffer containing the
  151071. ** normalized version of the token (i.e. after any case-folding and/or
  151072. ** stemming has been performed). *pnBytes should be set to the length
  151073. ** of this buffer in bytes. The input text that generated the token is
  151074. ** identified by the byte offsets returned in *piStartOffset and
  151075. ** *piEndOffset. *piStartOffset should be set to the index of the first
  151076. ** byte of the token in the input buffer. *piEndOffset should be set
  151077. ** to the index of the first byte just past the end of the token in
  151078. ** the input buffer.
  151079. **
  151080. ** The buffer *ppToken is set to point at is managed by the tokenizer
  151081. ** implementation. It is only required to be valid until the next call
  151082. ** to xNext() or xClose().
  151083. */
  151084. /* TODO(shess) current implementation requires pInput to be
  151085. ** nul-terminated. This should either be fixed, or pInput/nBytes
  151086. ** should be converted to zInput.
  151087. */
  151088. int (*xNext)(
  151089. sqlite3_tokenizer_cursor *pCursor, /* Tokenizer cursor */
  151090. const char **ppToken, int *pnBytes, /* OUT: Normalized text for token */
  151091. int *piStartOffset, /* OUT: Byte offset of token in input buffer */
  151092. int *piEndOffset, /* OUT: Byte offset of end of token in input buffer */
  151093. int *piPosition /* OUT: Number of tokens returned before this one */
  151094. );
  151095. /***********************************************************************
  151096. ** Methods below this point are only available if iVersion>=1.
  151097. */
  151098. /*
  151099. ** Configure the language id of a tokenizer cursor.
  151100. */
  151101. int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
  151102. };
  151103. struct sqlite3_tokenizer {
  151104. const sqlite3_tokenizer_module *pModule; /* The module for this tokenizer */
  151105. /* Tokenizer implementations will typically add additional fields */
  151106. };
  151107. struct sqlite3_tokenizer_cursor {
  151108. sqlite3_tokenizer *pTokenizer; /* Tokenizer for this cursor. */
  151109. /* Tokenizer implementations will typically add additional fields */
  151110. };
  151111. int fts3_global_term_cnt(int iTerm, int iCol);
  151112. int fts3_term_cnt(int iTerm, int iCol);
  151113. #endif /* _FTS3_TOKENIZER_H_ */
  151114. /************** End of fts3_tokenizer.h **************************************/
  151115. /************** Continuing where we left off in fts3Int.h ********************/
  151116. /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
  151117. /************** Begin file fts3_hash.h ***************************************/
  151118. /*
  151119. ** 2001 September 22
  151120. **
  151121. ** The author disclaims copyright to this source code. In place of
  151122. ** a legal notice, here is a blessing:
  151123. **
  151124. ** May you do good and not evil.
  151125. ** May you find forgiveness for yourself and forgive others.
  151126. ** May you share freely, never taking more than you give.
  151127. **
  151128. *************************************************************************
  151129. ** This is the header file for the generic hash-table implementation
  151130. ** used in SQLite. We've modified it slightly to serve as a standalone
  151131. ** hash table implementation for the full-text indexing module.
  151132. **
  151133. */
  151134. #ifndef _FTS3_HASH_H_
  151135. #define _FTS3_HASH_H_
  151136. /* Forward declarations of structures. */
  151137. typedef struct Fts3Hash Fts3Hash;
  151138. typedef struct Fts3HashElem Fts3HashElem;
  151139. /* A complete hash table is an instance of the following structure.
  151140. ** The internals of this structure are intended to be opaque -- client
  151141. ** code should not attempt to access or modify the fields of this structure
  151142. ** directly. Change this structure only by using the routines below.
  151143. ** However, many of the "procedures" and "functions" for modifying and
  151144. ** accessing this structure are really macros, so we can't really make
  151145. ** this structure opaque.
  151146. */
  151147. struct Fts3Hash {
  151148. char keyClass; /* HASH_INT, _POINTER, _STRING, _BINARY */
  151149. char copyKey; /* True if copy of key made on insert */
  151150. int count; /* Number of entries in this table */
  151151. Fts3HashElem *first; /* The first element of the array */
  151152. int htsize; /* Number of buckets in the hash table */
  151153. struct _fts3ht { /* the hash table */
  151154. int count; /* Number of entries with this hash */
  151155. Fts3HashElem *chain; /* Pointer to first entry with this hash */
  151156. } *ht;
  151157. };
  151158. /* Each element in the hash table is an instance of the following
  151159. ** structure. All elements are stored on a single doubly-linked list.
  151160. **
  151161. ** Again, this structure is intended to be opaque, but it can't really
  151162. ** be opaque because it is used by macros.
  151163. */
  151164. struct Fts3HashElem {
  151165. Fts3HashElem *next, *prev; /* Next and previous elements in the table */
  151166. void *data; /* Data associated with this element */
  151167. void *pKey; int nKey; /* Key associated with this element */
  151168. };
  151169. /*
  151170. ** There are 2 different modes of operation for a hash table:
  151171. **
  151172. ** FTS3_HASH_STRING pKey points to a string that is nKey bytes long
  151173. ** (including the null-terminator, if any). Case
  151174. ** is respected in comparisons.
  151175. **
  151176. ** FTS3_HASH_BINARY pKey points to binary data nKey bytes long.
  151177. ** memcmp() is used to compare keys.
  151178. **
  151179. ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
  151180. */
  151181. #define FTS3_HASH_STRING 1
  151182. #define FTS3_HASH_BINARY 2
  151183. /*
  151184. ** Access routines. To delete, insert a NULL pointer.
  151185. */
  151186. SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
  151187. SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
  151188. SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
  151189. SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
  151190. SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
  151191. /*
  151192. ** Shorthand for the functions above
  151193. */
  151194. #define fts3HashInit sqlite3Fts3HashInit
  151195. #define fts3HashInsert sqlite3Fts3HashInsert
  151196. #define fts3HashFind sqlite3Fts3HashFind
  151197. #define fts3HashClear sqlite3Fts3HashClear
  151198. #define fts3HashFindElem sqlite3Fts3HashFindElem
  151199. /*
  151200. ** Macros for looping over all elements of a hash table. The idiom is
  151201. ** like this:
  151202. **
  151203. ** Fts3Hash h;
  151204. ** Fts3HashElem *p;
  151205. ** ...
  151206. ** for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
  151207. ** SomeStructure *pData = fts3HashData(p);
  151208. ** // do something with pData
  151209. ** }
  151210. */
  151211. #define fts3HashFirst(H) ((H)->first)
  151212. #define fts3HashNext(E) ((E)->next)
  151213. #define fts3HashData(E) ((E)->data)
  151214. #define fts3HashKey(E) ((E)->pKey)
  151215. #define fts3HashKeysize(E) ((E)->nKey)
  151216. /*
  151217. ** Number of entries in a hash table
  151218. */
  151219. #define fts3HashCount(H) ((H)->count)
  151220. #endif /* _FTS3_HASH_H_ */
  151221. /************** End of fts3_hash.h *******************************************/
  151222. /************** Continuing where we left off in fts3Int.h ********************/
  151223. /*
  151224. ** This constant determines the maximum depth of an FTS expression tree
  151225. ** that the library will create and use. FTS uses recursion to perform
  151226. ** various operations on the query tree, so the disadvantage of a large
  151227. ** limit is that it may allow very large queries to use large amounts
  151228. ** of stack space (perhaps causing a stack overflow).
  151229. */
  151230. #ifndef SQLITE_FTS3_MAX_EXPR_DEPTH
  151231. # define SQLITE_FTS3_MAX_EXPR_DEPTH 12
  151232. #endif
  151233. /*
  151234. ** This constant controls how often segments are merged. Once there are
  151235. ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
  151236. ** segment of level N+1.
  151237. */
  151238. #define FTS3_MERGE_COUNT 16
  151239. /*
  151240. ** This is the maximum amount of data (in bytes) to store in the
  151241. ** Fts3Table.pendingTerms hash table. Normally, the hash table is
  151242. ** populated as documents are inserted/updated/deleted in a transaction
  151243. ** and used to create a new segment when the transaction is committed.
  151244. ** However if this limit is reached midway through a transaction, a new
  151245. ** segment is created and the hash table cleared immediately.
  151246. */
  151247. #define FTS3_MAX_PENDING_DATA (1*1024*1024)
  151248. /*
  151249. ** Macro to return the number of elements in an array. SQLite has a
  151250. ** similar macro called ArraySize(). Use a different name to avoid
  151251. ** a collision when building an amalgamation with built-in FTS3.
  151252. */
  151253. #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
  151254. #ifndef MIN
  151255. # define MIN(x,y) ((x)<(y)?(x):(y))
  151256. #endif
  151257. #ifndef MAX
  151258. # define MAX(x,y) ((x)>(y)?(x):(y))
  151259. #endif
  151260. /*
  151261. ** Maximum length of a varint encoded integer. The varint format is different
  151262. ** from that used by SQLite, so the maximum length is 10, not 9.
  151263. */
  151264. #define FTS3_VARINT_MAX 10
  151265. #define FTS3_BUFFER_PADDING 8
  151266. /*
  151267. ** FTS4 virtual tables may maintain multiple indexes - one index of all terms
  151268. ** in the document set and zero or more prefix indexes. All indexes are stored
  151269. ** as one or more b+-trees in the %_segments and %_segdir tables.
  151270. **
  151271. ** It is possible to determine which index a b+-tree belongs to based on the
  151272. ** value stored in the "%_segdir.level" column. Given this value L, the index
  151273. ** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
  151274. ** level values between 0 and 1023 (inclusive) belong to index 0, all levels
  151275. ** between 1024 and 2047 to index 1, and so on.
  151276. **
  151277. ** It is considered impossible for an index to use more than 1024 levels. In
  151278. ** theory though this may happen, but only after at least
  151279. ** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
  151280. */
  151281. #define FTS3_SEGDIR_MAXLEVEL 1024
  151282. #define FTS3_SEGDIR_MAXLEVEL_STR "1024"
  151283. /*
  151284. ** The testcase() macro is only used by the amalgamation. If undefined,
  151285. ** make it a no-op.
  151286. */
  151287. #ifndef testcase
  151288. # define testcase(X)
  151289. #endif
  151290. /*
  151291. ** Terminator values for position-lists and column-lists.
  151292. */
  151293. #define POS_COLUMN (1) /* Column-list terminator */
  151294. #define POS_END (0) /* Position-list terminator */
  151295. /*
  151296. ** The assert_fts3_nc() macro is similar to the assert() macro, except that it
  151297. ** is used for assert() conditions that are true only if it can be
  151298. ** guranteed that the database is not corrupt.
  151299. */
  151300. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  151301. SQLITE_API extern int sqlite3_fts3_may_be_corrupt;
  151302. # define assert_fts3_nc(x) assert(sqlite3_fts3_may_be_corrupt || (x))
  151303. #else
  151304. # define assert_fts3_nc(x) assert(x)
  151305. #endif
  151306. /*
  151307. ** This section provides definitions to allow the
  151308. ** FTS3 extension to be compiled outside of the
  151309. ** amalgamation.
  151310. */
  151311. #ifndef SQLITE_AMALGAMATION
  151312. /*
  151313. ** Macros indicating that conditional expressions are always true or
  151314. ** false.
  151315. */
  151316. #ifdef SQLITE_COVERAGE_TEST
  151317. # define ALWAYS(x) (1)
  151318. # define NEVER(X) (0)
  151319. #elif defined(SQLITE_DEBUG)
  151320. # define ALWAYS(x) sqlite3Fts3Always((x)!=0)
  151321. # define NEVER(x) sqlite3Fts3Never((x)!=0)
  151322. SQLITE_PRIVATE int sqlite3Fts3Always(int b);
  151323. SQLITE_PRIVATE int sqlite3Fts3Never(int b);
  151324. #else
  151325. # define ALWAYS(x) (x)
  151326. # define NEVER(x) (x)
  151327. #endif
  151328. /*
  151329. ** Internal types used by SQLite.
  151330. */
  151331. typedef unsigned char u8; /* 1-byte (or larger) unsigned integer */
  151332. typedef short int i16; /* 2-byte (or larger) signed integer */
  151333. typedef unsigned int u32; /* 4-byte unsigned integer */
  151334. typedef sqlite3_uint64 u64; /* 8-byte unsigned integer */
  151335. typedef sqlite3_int64 i64; /* 8-byte signed integer */
  151336. /*
  151337. ** Macro used to suppress compiler warnings for unused parameters.
  151338. */
  151339. #define UNUSED_PARAMETER(x) (void)(x)
  151340. /*
  151341. ** Activate assert() only if SQLITE_TEST is enabled.
  151342. */
  151343. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  151344. # define NDEBUG 1
  151345. #endif
  151346. /*
  151347. ** The TESTONLY macro is used to enclose variable declarations or
  151348. ** other bits of code that are needed to support the arguments
  151349. ** within testcase() and assert() macros.
  151350. */
  151351. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  151352. # define TESTONLY(X) X
  151353. #else
  151354. # define TESTONLY(X)
  151355. #endif
  151356. #endif /* SQLITE_AMALGAMATION */
  151357. #ifdef SQLITE_DEBUG
  151358. SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
  151359. # define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
  151360. #else
  151361. # define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
  151362. #endif
  151363. typedef struct Fts3Table Fts3Table;
  151364. typedef struct Fts3Cursor Fts3Cursor;
  151365. typedef struct Fts3Expr Fts3Expr;
  151366. typedef struct Fts3Phrase Fts3Phrase;
  151367. typedef struct Fts3PhraseToken Fts3PhraseToken;
  151368. typedef struct Fts3Doclist Fts3Doclist;
  151369. typedef struct Fts3SegFilter Fts3SegFilter;
  151370. typedef struct Fts3DeferredToken Fts3DeferredToken;
  151371. typedef struct Fts3SegReader Fts3SegReader;
  151372. typedef struct Fts3MultiSegReader Fts3MultiSegReader;
  151373. typedef struct MatchinfoBuffer MatchinfoBuffer;
  151374. /*
  151375. ** A connection to a fulltext index is an instance of the following
  151376. ** structure. The xCreate and xConnect methods create an instance
  151377. ** of this structure and xDestroy and xDisconnect free that instance.
  151378. ** All other methods receive a pointer to the structure as one of their
  151379. ** arguments.
  151380. */
  151381. struct Fts3Table {
  151382. sqlite3_vtab base; /* Base class used by SQLite core */
  151383. sqlite3 *db; /* The database connection */
  151384. const char *zDb; /* logical database name */
  151385. const char *zName; /* virtual table name */
  151386. int nColumn; /* number of named columns in virtual table */
  151387. char **azColumn; /* column names. malloced */
  151388. u8 *abNotindexed; /* True for 'notindexed' columns */
  151389. sqlite3_tokenizer *pTokenizer; /* tokenizer for inserts and queries */
  151390. char *zContentTbl; /* content=xxx option, or NULL */
  151391. char *zLanguageid; /* languageid=xxx option, or NULL */
  151392. int nAutoincrmerge; /* Value configured by 'automerge' */
  151393. u32 nLeafAdd; /* Number of leaf blocks added this trans */
  151394. /* Precompiled statements used by the implementation. Each of these
  151395. ** statements is run and reset within a single virtual table API call.
  151396. */
  151397. sqlite3_stmt *aStmt[40];
  151398. sqlite3_stmt *pSeekStmt; /* Cache for fts3CursorSeekStmt() */
  151399. char *zReadExprlist;
  151400. char *zWriteExprlist;
  151401. int nNodeSize; /* Soft limit for node size */
  151402. u8 bFts4; /* True for FTS4, false for FTS3 */
  151403. u8 bHasStat; /* True if %_stat table exists (2==unknown) */
  151404. u8 bHasDocsize; /* True if %_docsize table exists */
  151405. u8 bDescIdx; /* True if doclists are in reverse order */
  151406. u8 bIgnoreSavepoint; /* True to ignore xSavepoint invocations */
  151407. int nPgsz; /* Page size for host database */
  151408. char *zSegmentsTbl; /* Name of %_segments table */
  151409. sqlite3_blob *pSegments; /* Blob handle open on %_segments table */
  151410. /*
  151411. ** The following array of hash tables is used to buffer pending index
  151412. ** updates during transactions. All pending updates buffered at any one
  151413. ** time must share a common language-id (see the FTS4 langid= feature).
  151414. ** The current language id is stored in variable iPrevLangid.
  151415. **
  151416. ** A single FTS4 table may have multiple full-text indexes. For each index
  151417. ** there is an entry in the aIndex[] array. Index 0 is an index of all the
  151418. ** terms that appear in the document set. Each subsequent index in aIndex[]
  151419. ** is an index of prefixes of a specific length.
  151420. **
  151421. ** Variable nPendingData contains an estimate the memory consumed by the
  151422. ** pending data structures, including hash table overhead, but not including
  151423. ** malloc overhead. When nPendingData exceeds nMaxPendingData, all hash
  151424. ** tables are flushed to disk. Variable iPrevDocid is the docid of the most
  151425. ** recently inserted record.
  151426. */
  151427. int nIndex; /* Size of aIndex[] */
  151428. struct Fts3Index {
  151429. int nPrefix; /* Prefix length (0 for main terms index) */
  151430. Fts3Hash hPending; /* Pending terms table for this index */
  151431. } *aIndex;
  151432. int nMaxPendingData; /* Max pending data before flush to disk */
  151433. int nPendingData; /* Current bytes of pending data */
  151434. sqlite_int64 iPrevDocid; /* Docid of most recently inserted document */
  151435. int iPrevLangid; /* Langid of recently inserted document */
  151436. int bPrevDelete; /* True if last operation was a delete */
  151437. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  151438. /* State variables used for validating that the transaction control
  151439. ** methods of the virtual table are called at appropriate times. These
  151440. ** values do not contribute to FTS functionality; they are used for
  151441. ** verifying the operation of the SQLite core.
  151442. */
  151443. int inTransaction; /* True after xBegin but before xCommit/xRollback */
  151444. int mxSavepoint; /* Largest valid xSavepoint integer */
  151445. #endif
  151446. #ifdef SQLITE_TEST
  151447. /* True to disable the incremental doclist optimization. This is controled
  151448. ** by special insert command 'test-no-incr-doclist'. */
  151449. int bNoIncrDoclist;
  151450. #endif
  151451. };
  151452. /*
  151453. ** When the core wants to read from the virtual table, it creates a
  151454. ** virtual table cursor (an instance of the following structure) using
  151455. ** the xOpen method. Cursors are destroyed using the xClose method.
  151456. */
  151457. struct Fts3Cursor {
  151458. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  151459. i16 eSearch; /* Search strategy (see below) */
  151460. u8 isEof; /* True if at End Of Results */
  151461. u8 isRequireSeek; /* True if must seek pStmt to %_content row */
  151462. u8 bSeekStmt; /* True if pStmt is a seek */
  151463. sqlite3_stmt *pStmt; /* Prepared statement in use by the cursor */
  151464. Fts3Expr *pExpr; /* Parsed MATCH query string */
  151465. int iLangid; /* Language being queried for */
  151466. int nPhrase; /* Number of matchable phrases in query */
  151467. Fts3DeferredToken *pDeferred; /* Deferred search tokens, if any */
  151468. sqlite3_int64 iPrevId; /* Previous id read from aDoclist */
  151469. char *pNextId; /* Pointer into the body of aDoclist */
  151470. char *aDoclist; /* List of docids for full-text queries */
  151471. int nDoclist; /* Size of buffer at aDoclist */
  151472. u8 bDesc; /* True to sort in descending order */
  151473. int eEvalmode; /* An FTS3_EVAL_XX constant */
  151474. int nRowAvg; /* Average size of database rows, in pages */
  151475. sqlite3_int64 nDoc; /* Documents in table */
  151476. i64 iMinDocid; /* Minimum docid to return */
  151477. i64 iMaxDocid; /* Maximum docid to return */
  151478. int isMatchinfoNeeded; /* True when aMatchinfo[] needs filling in */
  151479. MatchinfoBuffer *pMIBuffer; /* Buffer for matchinfo data */
  151480. };
  151481. #define FTS3_EVAL_FILTER 0
  151482. #define FTS3_EVAL_NEXT 1
  151483. #define FTS3_EVAL_MATCHINFO 2
  151484. /*
  151485. ** The Fts3Cursor.eSearch member is always set to one of the following.
  151486. ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
  151487. ** FTS3_FULLTEXT_SEARCH. If so, then Fts3Cursor.eSearch - 2 is the index
  151488. ** of the column to be searched. For example, in
  151489. **
  151490. ** CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
  151491. ** SELECT docid FROM ex1 WHERE b MATCH 'one two three';
  151492. **
  151493. ** Because the LHS of the MATCH operator is 2nd column "b",
  151494. ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1. (+0 for a,
  151495. ** +1 for b, +2 for c, +3 for d.) If the LHS of MATCH were "ex1"
  151496. ** indicating that all columns should be searched,
  151497. ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
  151498. */
  151499. #define FTS3_FULLSCAN_SEARCH 0 /* Linear scan of %_content table */
  151500. #define FTS3_DOCID_SEARCH 1 /* Lookup by rowid on %_content table */
  151501. #define FTS3_FULLTEXT_SEARCH 2 /* Full-text index search */
  151502. /*
  151503. ** The lower 16-bits of the sqlite3_index_info.idxNum value set by
  151504. ** the xBestIndex() method contains the Fts3Cursor.eSearch value described
  151505. ** above. The upper 16-bits contain a combination of the following
  151506. ** bits, used to describe extra constraints on full-text searches.
  151507. */
  151508. #define FTS3_HAVE_LANGID 0x00010000 /* languageid=? */
  151509. #define FTS3_HAVE_DOCID_GE 0x00020000 /* docid>=? */
  151510. #define FTS3_HAVE_DOCID_LE 0x00040000 /* docid<=? */
  151511. struct Fts3Doclist {
  151512. char *aAll; /* Array containing doclist (or NULL) */
  151513. int nAll; /* Size of a[] in bytes */
  151514. char *pNextDocid; /* Pointer to next docid */
  151515. sqlite3_int64 iDocid; /* Current docid (if pList!=0) */
  151516. int bFreeList; /* True if pList should be sqlite3_free()d */
  151517. char *pList; /* Pointer to position list following iDocid */
  151518. int nList; /* Length of position list */
  151519. };
  151520. /*
  151521. ** A "phrase" is a sequence of one or more tokens that must match in
  151522. ** sequence. A single token is the base case and the most common case.
  151523. ** For a sequence of tokens contained in double-quotes (i.e. "one two three")
  151524. ** nToken will be the number of tokens in the string.
  151525. */
  151526. struct Fts3PhraseToken {
  151527. char *z; /* Text of the token */
  151528. int n; /* Number of bytes in buffer z */
  151529. int isPrefix; /* True if token ends with a "*" character */
  151530. int bFirst; /* True if token must appear at position 0 */
  151531. /* Variables above this point are populated when the expression is
  151532. ** parsed (by code in fts3_expr.c). Below this point the variables are
  151533. ** used when evaluating the expression. */
  151534. Fts3DeferredToken *pDeferred; /* Deferred token object for this token */
  151535. Fts3MultiSegReader *pSegcsr; /* Segment-reader for this token */
  151536. };
  151537. struct Fts3Phrase {
  151538. /* Cache of doclist for this phrase. */
  151539. Fts3Doclist doclist;
  151540. int bIncr; /* True if doclist is loaded incrementally */
  151541. int iDoclistToken;
  151542. /* Used by sqlite3Fts3EvalPhrasePoslist() if this is a descendent of an
  151543. ** OR condition. */
  151544. char *pOrPoslist;
  151545. i64 iOrDocid;
  151546. /* Variables below this point are populated by fts3_expr.c when parsing
  151547. ** a MATCH expression. Everything above is part of the evaluation phase.
  151548. */
  151549. int nToken; /* Number of tokens in the phrase */
  151550. int iColumn; /* Index of column this phrase must match */
  151551. Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
  151552. };
  151553. /*
  151554. ** A tree of these objects forms the RHS of a MATCH operator.
  151555. **
  151556. ** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist
  151557. ** points to a malloced buffer, size nDoclist bytes, containing the results
  151558. ** of this phrase query in FTS3 doclist format. As usual, the initial
  151559. ** "Length" field found in doclists stored on disk is omitted from this
  151560. ** buffer.
  151561. **
  151562. ** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
  151563. ** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
  151564. ** where nCol is the number of columns in the queried FTS table. The array
  151565. ** is populated as follows:
  151566. **
  151567. ** aMI[iCol*3 + 0] = Undefined
  151568. ** aMI[iCol*3 + 1] = Number of occurrences
  151569. ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
  151570. **
  151571. ** The aMI array is allocated using sqlite3_malloc(). It should be freed
  151572. ** when the expression node is.
  151573. */
  151574. struct Fts3Expr {
  151575. int eType; /* One of the FTSQUERY_XXX values defined below */
  151576. int nNear; /* Valid if eType==FTSQUERY_NEAR */
  151577. Fts3Expr *pParent; /* pParent->pLeft==this or pParent->pRight==this */
  151578. Fts3Expr *pLeft; /* Left operand */
  151579. Fts3Expr *pRight; /* Right operand */
  151580. Fts3Phrase *pPhrase; /* Valid if eType==FTSQUERY_PHRASE */
  151581. /* The following are used by the fts3_eval.c module. */
  151582. sqlite3_int64 iDocid; /* Current docid */
  151583. u8 bEof; /* True this expression is at EOF already */
  151584. u8 bStart; /* True if iDocid is valid */
  151585. u8 bDeferred; /* True if this expression is entirely deferred */
  151586. /* The following are used by the fts3_snippet.c module. */
  151587. int iPhrase; /* Index of this phrase in matchinfo() results */
  151588. u32 *aMI; /* See above */
  151589. };
  151590. /*
  151591. ** Candidate values for Fts3Query.eType. Note that the order of the first
  151592. ** four values is in order of precedence when parsing expressions. For
  151593. ** example, the following:
  151594. **
  151595. ** "a OR b AND c NOT d NEAR e"
  151596. **
  151597. ** is equivalent to:
  151598. **
  151599. ** "a OR (b AND (c NOT (d NEAR e)))"
  151600. */
  151601. #define FTSQUERY_NEAR 1
  151602. #define FTSQUERY_NOT 2
  151603. #define FTSQUERY_AND 3
  151604. #define FTSQUERY_OR 4
  151605. #define FTSQUERY_PHRASE 5
  151606. /* fts3_write.c */
  151607. SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
  151608. SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
  151609. SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
  151610. SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
  151611. SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,
  151612. sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
  151613. SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
  151614. Fts3Table*,int,const char*,int,int,Fts3SegReader**);
  151615. SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
  151616. SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);
  151617. SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
  151618. SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
  151619. SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
  151620. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  151621. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
  151622. SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
  151623. SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
  151624. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
  151625. SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
  151626. #else
  151627. # define sqlite3Fts3FreeDeferredTokens(x)
  151628. # define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK
  151629. # define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK
  151630. # define sqlite3Fts3FreeDeferredDoclists(x)
  151631. # define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK
  151632. #endif
  151633. SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
  151634. SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *);
  151635. /* Special values interpreted by sqlite3SegReaderCursor() */
  151636. #define FTS3_SEGCURSOR_PENDING -1
  151637. #define FTS3_SEGCURSOR_ALL -2
  151638. SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
  151639. SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
  151640. SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
  151641. SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *,
  151642. int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
  151643. /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
  151644. #define FTS3_SEGMENT_REQUIRE_POS 0x00000001
  151645. #define FTS3_SEGMENT_IGNORE_EMPTY 0x00000002
  151646. #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
  151647. #define FTS3_SEGMENT_PREFIX 0x00000008
  151648. #define FTS3_SEGMENT_SCAN 0x00000010
  151649. #define FTS3_SEGMENT_FIRST 0x00000020
  151650. /* Type passed as 4th argument to SegmentReaderIterate() */
  151651. struct Fts3SegFilter {
  151652. const char *zTerm;
  151653. int nTerm;
  151654. int iCol;
  151655. int flags;
  151656. };
  151657. struct Fts3MultiSegReader {
  151658. /* Used internally by sqlite3Fts3SegReaderXXX() calls */
  151659. Fts3SegReader **apSegment; /* Array of Fts3SegReader objects */
  151660. int nSegment; /* Size of apSegment array */
  151661. int nAdvance; /* How many seg-readers to advance */
  151662. Fts3SegFilter *pFilter; /* Pointer to filter object */
  151663. char *aBuffer; /* Buffer to merge doclists in */
  151664. int nBuffer; /* Allocated size of aBuffer[] in bytes */
  151665. int iColFilter; /* If >=0, filter for this column */
  151666. int bRestart;
  151667. /* Used by fts3.c only. */
  151668. int nCost; /* Cost of running iterator */
  151669. int bLookup; /* True if a lookup of a single entry. */
  151670. /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
  151671. char *zTerm; /* Pointer to term buffer */
  151672. int nTerm; /* Size of zTerm in bytes */
  151673. char *aDoclist; /* Pointer to doclist buffer */
  151674. int nDoclist; /* Size of aDoclist[] in bytes */
  151675. };
  151676. SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int);
  151677. #define fts3GetVarint32(p, piVal) ( \
  151678. (*(u8*)(p)&0x80) ? sqlite3Fts3GetVarint32(p, piVal) : (*piVal=*(u8*)(p), 1) \
  151679. )
  151680. /* fts3.c */
  151681. SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char**,const char*,...);
  151682. SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
  151683. SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
  151684. SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
  151685. SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
  151686. SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
  151687. SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
  151688. SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
  151689. SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
  151690. SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);
  151691. SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc);
  151692. /* fts3_tokenizer.c */
  151693. SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
  151694. SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
  151695. SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
  151696. sqlite3_tokenizer **, char **
  151697. );
  151698. SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
  151699. /* fts3_snippet.c */
  151700. SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
  151701. SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
  151702. const char *, const char *, int, int
  151703. );
  151704. SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
  151705. SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p);
  151706. /* fts3_expr.c */
  151707. SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
  151708. char **, int, int, int, const char *, int, Fts3Expr **, char **
  151709. );
  151710. SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
  151711. #ifdef SQLITE_TEST
  151712. SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db, Fts3Hash*);
  151713. SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
  151714. #endif
  151715. SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
  151716. sqlite3_tokenizer_cursor **
  151717. );
  151718. /* fts3_aux.c */
  151719. SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
  151720. SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
  151721. SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
  151722. Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
  151723. SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
  151724. Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
  151725. SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **);
  151726. SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
  151727. SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
  151728. /* fts3_tokenize_vtab.c */
  151729. SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3*, Fts3Hash *);
  151730. /* fts3_unicode2.c (functions generated by parsing unicode text files) */
  151731. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  151732. SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int);
  151733. SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int);
  151734. SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);
  151735. #endif
  151736. #endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
  151737. #endif /* _FTSINT_H */
  151738. /************** End of fts3Int.h *********************************************/
  151739. /************** Continuing where we left off in fts3.c ***********************/
  151740. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  151741. #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
  151742. # define SQLITE_CORE 1
  151743. #endif
  151744. /* #include <assert.h> */
  151745. /* #include <stdlib.h> */
  151746. /* #include <stddef.h> */
  151747. /* #include <stdio.h> */
  151748. /* #include <string.h> */
  151749. /* #include <stdarg.h> */
  151750. /* #include "fts3.h" */
  151751. #ifndef SQLITE_CORE
  151752. /* # include "sqlite3ext.h" */
  151753. SQLITE_EXTENSION_INIT1
  151754. #endif
  151755. static int fts3EvalNext(Fts3Cursor *pCsr);
  151756. static int fts3EvalStart(Fts3Cursor *pCsr);
  151757. static int fts3TermSegReaderCursor(
  151758. Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
  151759. #ifndef SQLITE_AMALGAMATION
  151760. # if defined(SQLITE_DEBUG)
  151761. SQLITE_PRIVATE int sqlite3Fts3Always(int b) { assert( b ); return b; }
  151762. SQLITE_PRIVATE int sqlite3Fts3Never(int b) { assert( !b ); return b; }
  151763. # endif
  151764. #endif
  151765. /*
  151766. ** This variable is set to false when running tests for which the on disk
  151767. ** structures should not be corrupt. Otherwise, true. If it is false, extra
  151768. ** assert() conditions in the fts3 code are activated - conditions that are
  151769. ** only true if it is guaranteed that the fts3 database is not corrupt.
  151770. */
  151771. SQLITE_API int sqlite3_fts3_may_be_corrupt = 1;
  151772. /*
  151773. ** Write a 64-bit variable-length integer to memory starting at p[0].
  151774. ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
  151775. ** The number of bytes written is returned.
  151776. */
  151777. SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
  151778. unsigned char *q = (unsigned char *) p;
  151779. sqlite_uint64 vu = v;
  151780. do{
  151781. *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
  151782. vu >>= 7;
  151783. }while( vu!=0 );
  151784. q[-1] &= 0x7f; /* turn off high bit in final byte */
  151785. assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
  151786. return (int) (q - (unsigned char *)p);
  151787. }
  151788. #define GETVARINT_STEP(v, ptr, shift, mask1, mask2, var, ret) \
  151789. v = (v & mask1) | ( (*(const unsigned char*)(ptr++)) << shift ); \
  151790. if( (v & mask2)==0 ){ var = v; return ret; }
  151791. #define GETVARINT_INIT(v, ptr, shift, mask1, mask2, var, ret) \
  151792. v = (*ptr++); \
  151793. if( (v & mask2)==0 ){ var = v; return ret; }
  151794. /*
  151795. ** Read a 64-bit variable-length integer from memory starting at p[0].
  151796. ** Return the number of bytes read, or 0 on error.
  151797. ** The value is stored in *v.
  151798. */
  151799. SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *pBuf, sqlite_int64 *v){
  151800. const unsigned char *p = (const unsigned char*)pBuf;
  151801. const unsigned char *pStart = p;
  151802. u32 a;
  151803. u64 b;
  151804. int shift;
  151805. GETVARINT_INIT(a, p, 0, 0x00, 0x80, *v, 1);
  151806. GETVARINT_STEP(a, p, 7, 0x7F, 0x4000, *v, 2);
  151807. GETVARINT_STEP(a, p, 14, 0x3FFF, 0x200000, *v, 3);
  151808. GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *v, 4);
  151809. b = (a & 0x0FFFFFFF );
  151810. for(shift=28; shift<=63; shift+=7){
  151811. u64 c = *p++;
  151812. b += (c&0x7F) << shift;
  151813. if( (c & 0x80)==0 ) break;
  151814. }
  151815. *v = b;
  151816. return (int)(p - pStart);
  151817. }
  151818. /*
  151819. ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to
  151820. ** a non-negative 32-bit integer before it is returned.
  151821. */
  151822. SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
  151823. const unsigned char *ptr = (const unsigned char*)p;
  151824. u32 a;
  151825. #ifndef fts3GetVarint32
  151826. GETVARINT_INIT(a, ptr, 0, 0x00, 0x80, *pi, 1);
  151827. #else
  151828. a = (*ptr++);
  151829. assert( a & 0x80 );
  151830. #endif
  151831. GETVARINT_STEP(a, ptr, 7, 0x7F, 0x4000, *pi, 2);
  151832. GETVARINT_STEP(a, ptr, 14, 0x3FFF, 0x200000, *pi, 3);
  151833. GETVARINT_STEP(a, ptr, 21, 0x1FFFFF, 0x10000000, *pi, 4);
  151834. a = (a & 0x0FFFFFFF );
  151835. *pi = (int)(a | ((u32)(*ptr & 0x07) << 28));
  151836. assert( 0==(a & 0x80000000) );
  151837. assert( *pi>=0 );
  151838. return 5;
  151839. }
  151840. /*
  151841. ** Return the number of bytes required to encode v as a varint
  151842. */
  151843. SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
  151844. int i = 0;
  151845. do{
  151846. i++;
  151847. v >>= 7;
  151848. }while( v!=0 );
  151849. return i;
  151850. }
  151851. /*
  151852. ** Convert an SQL-style quoted string into a normal string by removing
  151853. ** the quote characters. The conversion is done in-place. If the
  151854. ** input does not begin with a quote character, then this routine
  151855. ** is a no-op.
  151856. **
  151857. ** Examples:
  151858. **
  151859. ** "abc" becomes abc
  151860. ** 'xyz' becomes xyz
  151861. ** [pqr] becomes pqr
  151862. ** `mno` becomes mno
  151863. **
  151864. */
  151865. SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
  151866. char quote; /* Quote character (if any ) */
  151867. quote = z[0];
  151868. if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
  151869. int iIn = 1; /* Index of next byte to read from input */
  151870. int iOut = 0; /* Index of next byte to write to output */
  151871. /* If the first byte was a '[', then the close-quote character is a ']' */
  151872. if( quote=='[' ) quote = ']';
  151873. while( z[iIn] ){
  151874. if( z[iIn]==quote ){
  151875. if( z[iIn+1]!=quote ) break;
  151876. z[iOut++] = quote;
  151877. iIn += 2;
  151878. }else{
  151879. z[iOut++] = z[iIn++];
  151880. }
  151881. }
  151882. z[iOut] = '\0';
  151883. }
  151884. }
  151885. /*
  151886. ** Read a single varint from the doclist at *pp and advance *pp to point
  151887. ** to the first byte past the end of the varint. Add the value of the varint
  151888. ** to *pVal.
  151889. */
  151890. static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
  151891. sqlite3_int64 iVal;
  151892. *pp += sqlite3Fts3GetVarint(*pp, &iVal);
  151893. *pVal += iVal;
  151894. }
  151895. /*
  151896. ** When this function is called, *pp points to the first byte following a
  151897. ** varint that is part of a doclist (or position-list, or any other list
  151898. ** of varints). This function moves *pp to point to the start of that varint,
  151899. ** and sets *pVal by the varint value.
  151900. **
  151901. ** Argument pStart points to the first byte of the doclist that the
  151902. ** varint is part of.
  151903. */
  151904. static void fts3GetReverseVarint(
  151905. char **pp,
  151906. char *pStart,
  151907. sqlite3_int64 *pVal
  151908. ){
  151909. sqlite3_int64 iVal;
  151910. char *p;
  151911. /* Pointer p now points at the first byte past the varint we are
  151912. ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
  151913. ** clear on character p[-1]. */
  151914. for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
  151915. p++;
  151916. *pp = p;
  151917. sqlite3Fts3GetVarint(p, &iVal);
  151918. *pVal = iVal;
  151919. }
  151920. /*
  151921. ** The xDisconnect() virtual table method.
  151922. */
  151923. static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
  151924. Fts3Table *p = (Fts3Table *)pVtab;
  151925. int i;
  151926. assert( p->nPendingData==0 );
  151927. assert( p->pSegments==0 );
  151928. /* Free any prepared statements held */
  151929. sqlite3_finalize(p->pSeekStmt);
  151930. for(i=0; i<SizeofArray(p->aStmt); i++){
  151931. sqlite3_finalize(p->aStmt[i]);
  151932. }
  151933. sqlite3_free(p->zSegmentsTbl);
  151934. sqlite3_free(p->zReadExprlist);
  151935. sqlite3_free(p->zWriteExprlist);
  151936. sqlite3_free(p->zContentTbl);
  151937. sqlite3_free(p->zLanguageid);
  151938. /* Invoke the tokenizer destructor to free the tokenizer. */
  151939. p->pTokenizer->pModule->xDestroy(p->pTokenizer);
  151940. sqlite3_free(p);
  151941. return SQLITE_OK;
  151942. }
  151943. /*
  151944. ** Write an error message into *pzErr
  151945. */
  151946. SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char **pzErr, const char *zFormat, ...){
  151947. va_list ap;
  151948. sqlite3_free(*pzErr);
  151949. va_start(ap, zFormat);
  151950. *pzErr = sqlite3_vmprintf(zFormat, ap);
  151951. va_end(ap);
  151952. }
  151953. /*
  151954. ** Construct one or more SQL statements from the format string given
  151955. ** and then evaluate those statements. The success code is written
  151956. ** into *pRc.
  151957. **
  151958. ** If *pRc is initially non-zero then this routine is a no-op.
  151959. */
  151960. static void fts3DbExec(
  151961. int *pRc, /* Success code */
  151962. sqlite3 *db, /* Database in which to run SQL */
  151963. const char *zFormat, /* Format string for SQL */
  151964. ... /* Arguments to the format string */
  151965. ){
  151966. va_list ap;
  151967. char *zSql;
  151968. if( *pRc ) return;
  151969. va_start(ap, zFormat);
  151970. zSql = sqlite3_vmprintf(zFormat, ap);
  151971. va_end(ap);
  151972. if( zSql==0 ){
  151973. *pRc = SQLITE_NOMEM;
  151974. }else{
  151975. *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
  151976. sqlite3_free(zSql);
  151977. }
  151978. }
  151979. /*
  151980. ** The xDestroy() virtual table method.
  151981. */
  151982. static int fts3DestroyMethod(sqlite3_vtab *pVtab){
  151983. Fts3Table *p = (Fts3Table *)pVtab;
  151984. int rc = SQLITE_OK; /* Return code */
  151985. const char *zDb = p->zDb; /* Name of database (e.g. "main", "temp") */
  151986. sqlite3 *db = p->db; /* Database handle */
  151987. /* Drop the shadow tables */
  151988. fts3DbExec(&rc, db,
  151989. "DROP TABLE IF EXISTS %Q.'%q_segments';"
  151990. "DROP TABLE IF EXISTS %Q.'%q_segdir';"
  151991. "DROP TABLE IF EXISTS %Q.'%q_docsize';"
  151992. "DROP TABLE IF EXISTS %Q.'%q_stat';"
  151993. "%s DROP TABLE IF EXISTS %Q.'%q_content';",
  151994. zDb, p->zName,
  151995. zDb, p->zName,
  151996. zDb, p->zName,
  151997. zDb, p->zName,
  151998. (p->zContentTbl ? "--" : ""), zDb,p->zName
  151999. );
  152000. /* If everything has worked, invoke fts3DisconnectMethod() to free the
  152001. ** memory associated with the Fts3Table structure and return SQLITE_OK.
  152002. ** Otherwise, return an SQLite error code.
  152003. */
  152004. return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
  152005. }
  152006. /*
  152007. ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
  152008. ** passed as the first argument. This is done as part of the xConnect()
  152009. ** and xCreate() methods.
  152010. **
  152011. ** If *pRc is non-zero when this function is called, it is a no-op.
  152012. ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
  152013. ** before returning.
  152014. */
  152015. static void fts3DeclareVtab(int *pRc, Fts3Table *p){
  152016. if( *pRc==SQLITE_OK ){
  152017. int i; /* Iterator variable */
  152018. int rc; /* Return code */
  152019. char *zSql; /* SQL statement passed to declare_vtab() */
  152020. char *zCols; /* List of user defined columns */
  152021. const char *zLanguageid;
  152022. zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
  152023. sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
  152024. /* Create a list of user columns for the virtual table */
  152025. zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
  152026. for(i=1; zCols && i<p->nColumn; i++){
  152027. zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
  152028. }
  152029. /* Create the whole "CREATE TABLE" statement to pass to SQLite */
  152030. zSql = sqlite3_mprintf(
  152031. "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)",
  152032. zCols, p->zName, zLanguageid
  152033. );
  152034. if( !zCols || !zSql ){
  152035. rc = SQLITE_NOMEM;
  152036. }else{
  152037. rc = sqlite3_declare_vtab(p->db, zSql);
  152038. }
  152039. sqlite3_free(zSql);
  152040. sqlite3_free(zCols);
  152041. *pRc = rc;
  152042. }
  152043. }
  152044. /*
  152045. ** Create the %_stat table if it does not already exist.
  152046. */
  152047. SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){
  152048. fts3DbExec(pRc, p->db,
  152049. "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
  152050. "(id INTEGER PRIMARY KEY, value BLOB);",
  152051. p->zDb, p->zName
  152052. );
  152053. if( (*pRc)==SQLITE_OK ) p->bHasStat = 1;
  152054. }
  152055. /*
  152056. ** Create the backing store tables (%_content, %_segments and %_segdir)
  152057. ** required by the FTS3 table passed as the only argument. This is done
  152058. ** as part of the vtab xCreate() method.
  152059. **
  152060. ** If the p->bHasDocsize boolean is true (indicating that this is an
  152061. ** FTS4 table, not an FTS3 table) then also create the %_docsize and
  152062. ** %_stat tables required by FTS4.
  152063. */
  152064. static int fts3CreateTables(Fts3Table *p){
  152065. int rc = SQLITE_OK; /* Return code */
  152066. int i; /* Iterator variable */
  152067. sqlite3 *db = p->db; /* The database connection */
  152068. if( p->zContentTbl==0 ){
  152069. const char *zLanguageid = p->zLanguageid;
  152070. char *zContentCols; /* Columns of %_content table */
  152071. /* Create a list of user columns for the content table */
  152072. zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
  152073. for(i=0; zContentCols && i<p->nColumn; i++){
  152074. char *z = p->azColumn[i];
  152075. zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
  152076. }
  152077. if( zLanguageid && zContentCols ){
  152078. zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
  152079. }
  152080. if( zContentCols==0 ) rc = SQLITE_NOMEM;
  152081. /* Create the content table */
  152082. fts3DbExec(&rc, db,
  152083. "CREATE TABLE %Q.'%q_content'(%s)",
  152084. p->zDb, p->zName, zContentCols
  152085. );
  152086. sqlite3_free(zContentCols);
  152087. }
  152088. /* Create other tables */
  152089. fts3DbExec(&rc, db,
  152090. "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
  152091. p->zDb, p->zName
  152092. );
  152093. fts3DbExec(&rc, db,
  152094. "CREATE TABLE %Q.'%q_segdir'("
  152095. "level INTEGER,"
  152096. "idx INTEGER,"
  152097. "start_block INTEGER,"
  152098. "leaves_end_block INTEGER,"
  152099. "end_block INTEGER,"
  152100. "root BLOB,"
  152101. "PRIMARY KEY(level, idx)"
  152102. ");",
  152103. p->zDb, p->zName
  152104. );
  152105. if( p->bHasDocsize ){
  152106. fts3DbExec(&rc, db,
  152107. "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
  152108. p->zDb, p->zName
  152109. );
  152110. }
  152111. assert( p->bHasStat==p->bFts4 );
  152112. if( p->bHasStat ){
  152113. sqlite3Fts3CreateStatTable(&rc, p);
  152114. }
  152115. return rc;
  152116. }
  152117. /*
  152118. ** Store the current database page-size in bytes in p->nPgsz.
  152119. **
  152120. ** If *pRc is non-zero when this function is called, it is a no-op.
  152121. ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
  152122. ** before returning.
  152123. */
  152124. static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
  152125. if( *pRc==SQLITE_OK ){
  152126. int rc; /* Return code */
  152127. char *zSql; /* SQL text "PRAGMA %Q.page_size" */
  152128. sqlite3_stmt *pStmt; /* Compiled "PRAGMA %Q.page_size" statement */
  152129. zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
  152130. if( !zSql ){
  152131. rc = SQLITE_NOMEM;
  152132. }else{
  152133. rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
  152134. if( rc==SQLITE_OK ){
  152135. sqlite3_step(pStmt);
  152136. p->nPgsz = sqlite3_column_int(pStmt, 0);
  152137. rc = sqlite3_finalize(pStmt);
  152138. }else if( rc==SQLITE_AUTH ){
  152139. p->nPgsz = 1024;
  152140. rc = SQLITE_OK;
  152141. }
  152142. }
  152143. assert( p->nPgsz>0 || rc!=SQLITE_OK );
  152144. sqlite3_free(zSql);
  152145. *pRc = rc;
  152146. }
  152147. }
  152148. /*
  152149. ** "Special" FTS4 arguments are column specifications of the following form:
  152150. **
  152151. ** <key> = <value>
  152152. **
  152153. ** There may not be whitespace surrounding the "=" character. The <value>
  152154. ** term may be quoted, but the <key> may not.
  152155. */
  152156. static int fts3IsSpecialColumn(
  152157. const char *z,
  152158. int *pnKey,
  152159. char **pzValue
  152160. ){
  152161. char *zValue;
  152162. const char *zCsr = z;
  152163. while( *zCsr!='=' ){
  152164. if( *zCsr=='\0' ) return 0;
  152165. zCsr++;
  152166. }
  152167. *pnKey = (int)(zCsr-z);
  152168. zValue = sqlite3_mprintf("%s", &zCsr[1]);
  152169. if( zValue ){
  152170. sqlite3Fts3Dequote(zValue);
  152171. }
  152172. *pzValue = zValue;
  152173. return 1;
  152174. }
  152175. /*
  152176. ** Append the output of a printf() style formatting to an existing string.
  152177. */
  152178. static void fts3Appendf(
  152179. int *pRc, /* IN/OUT: Error code */
  152180. char **pz, /* IN/OUT: Pointer to string buffer */
  152181. const char *zFormat, /* Printf format string to append */
  152182. ... /* Arguments for printf format string */
  152183. ){
  152184. if( *pRc==SQLITE_OK ){
  152185. va_list ap;
  152186. char *z;
  152187. va_start(ap, zFormat);
  152188. z = sqlite3_vmprintf(zFormat, ap);
  152189. va_end(ap);
  152190. if( z && *pz ){
  152191. char *z2 = sqlite3_mprintf("%s%s", *pz, z);
  152192. sqlite3_free(z);
  152193. z = z2;
  152194. }
  152195. if( z==0 ) *pRc = SQLITE_NOMEM;
  152196. sqlite3_free(*pz);
  152197. *pz = z;
  152198. }
  152199. }
  152200. /*
  152201. ** Return a copy of input string zInput enclosed in double-quotes (") and
  152202. ** with all double quote characters escaped. For example:
  152203. **
  152204. ** fts3QuoteId("un \"zip\"") -> "un \"\"zip\"\""
  152205. **
  152206. ** The pointer returned points to memory obtained from sqlite3_malloc(). It
  152207. ** is the callers responsibility to call sqlite3_free() to release this
  152208. ** memory.
  152209. */
  152210. static char *fts3QuoteId(char const *zInput){
  152211. sqlite3_int64 nRet;
  152212. char *zRet;
  152213. nRet = 2 + (int)strlen(zInput)*2 + 1;
  152214. zRet = sqlite3_malloc64(nRet);
  152215. if( zRet ){
  152216. int i;
  152217. char *z = zRet;
  152218. *(z++) = '"';
  152219. for(i=0; zInput[i]; i++){
  152220. if( zInput[i]=='"' ) *(z++) = '"';
  152221. *(z++) = zInput[i];
  152222. }
  152223. *(z++) = '"';
  152224. *(z++) = '\0';
  152225. }
  152226. return zRet;
  152227. }
  152228. /*
  152229. ** Return a list of comma separated SQL expressions and a FROM clause that
  152230. ** could be used in a SELECT statement such as the following:
  152231. **
  152232. ** SELECT <list of expressions> FROM %_content AS x ...
  152233. **
  152234. ** to return the docid, followed by each column of text data in order
  152235. ** from left to write. If parameter zFunc is not NULL, then instead of
  152236. ** being returned directly each column of text data is passed to an SQL
  152237. ** function named zFunc first. For example, if zFunc is "unzip" and the
  152238. ** table has the three user-defined columns "a", "b", and "c", the following
  152239. ** string is returned:
  152240. **
  152241. ** "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
  152242. **
  152243. ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
  152244. ** is the responsibility of the caller to eventually free it.
  152245. **
  152246. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
  152247. ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
  152248. ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
  152249. ** no error occurs, *pRc is left unmodified.
  152250. */
  152251. static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
  152252. char *zRet = 0;
  152253. char *zFree = 0;
  152254. char *zFunction;
  152255. int i;
  152256. if( p->zContentTbl==0 ){
  152257. if( !zFunc ){
  152258. zFunction = "";
  152259. }else{
  152260. zFree = zFunction = fts3QuoteId(zFunc);
  152261. }
  152262. fts3Appendf(pRc, &zRet, "docid");
  152263. for(i=0; i<p->nColumn; i++){
  152264. fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
  152265. }
  152266. if( p->zLanguageid ){
  152267. fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
  152268. }
  152269. sqlite3_free(zFree);
  152270. }else{
  152271. fts3Appendf(pRc, &zRet, "rowid");
  152272. for(i=0; i<p->nColumn; i++){
  152273. fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
  152274. }
  152275. if( p->zLanguageid ){
  152276. fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
  152277. }
  152278. }
  152279. fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x",
  152280. p->zDb,
  152281. (p->zContentTbl ? p->zContentTbl : p->zName),
  152282. (p->zContentTbl ? "" : "_content")
  152283. );
  152284. return zRet;
  152285. }
  152286. /*
  152287. ** Return a list of N comma separated question marks, where N is the number
  152288. ** of columns in the %_content table (one for the docid plus one for each
  152289. ** user-defined text column).
  152290. **
  152291. ** If argument zFunc is not NULL, then all but the first question mark
  152292. ** is preceded by zFunc and an open bracket, and followed by a closed
  152293. ** bracket. For example, if zFunc is "zip" and the FTS3 table has three
  152294. ** user-defined text columns, the following string is returned:
  152295. **
  152296. ** "?, zip(?), zip(?), zip(?)"
  152297. **
  152298. ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
  152299. ** is the responsibility of the caller to eventually free it.
  152300. **
  152301. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
  152302. ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
  152303. ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
  152304. ** no error occurs, *pRc is left unmodified.
  152305. */
  152306. static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
  152307. char *zRet = 0;
  152308. char *zFree = 0;
  152309. char *zFunction;
  152310. int i;
  152311. if( !zFunc ){
  152312. zFunction = "";
  152313. }else{
  152314. zFree = zFunction = fts3QuoteId(zFunc);
  152315. }
  152316. fts3Appendf(pRc, &zRet, "?");
  152317. for(i=0; i<p->nColumn; i++){
  152318. fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
  152319. }
  152320. if( p->zLanguageid ){
  152321. fts3Appendf(pRc, &zRet, ", ?");
  152322. }
  152323. sqlite3_free(zFree);
  152324. return zRet;
  152325. }
  152326. /*
  152327. ** This function interprets the string at (*pp) as a non-negative integer
  152328. ** value. It reads the integer and sets *pnOut to the value read, then
  152329. ** sets *pp to point to the byte immediately following the last byte of
  152330. ** the integer value.
  152331. **
  152332. ** Only decimal digits ('0'..'9') may be part of an integer value.
  152333. **
  152334. ** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
  152335. ** the output value undefined. Otherwise SQLITE_OK is returned.
  152336. **
  152337. ** This function is used when parsing the "prefix=" FTS4 parameter.
  152338. */
  152339. static int fts3GobbleInt(const char **pp, int *pnOut){
  152340. const int MAX_NPREFIX = 10000000;
  152341. const char *p; /* Iterator pointer */
  152342. int nInt = 0; /* Output value */
  152343. for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
  152344. nInt = nInt * 10 + (p[0] - '0');
  152345. if( nInt>MAX_NPREFIX ){
  152346. nInt = 0;
  152347. break;
  152348. }
  152349. }
  152350. if( p==*pp ) return SQLITE_ERROR;
  152351. *pnOut = nInt;
  152352. *pp = p;
  152353. return SQLITE_OK;
  152354. }
  152355. /*
  152356. ** This function is called to allocate an array of Fts3Index structures
  152357. ** representing the indexes maintained by the current FTS table. FTS tables
  152358. ** always maintain the main "terms" index, but may also maintain one or
  152359. ** more "prefix" indexes, depending on the value of the "prefix=" parameter
  152360. ** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
  152361. **
  152362. ** Argument zParam is passed the value of the "prefix=" option if one was
  152363. ** specified, or NULL otherwise.
  152364. **
  152365. ** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
  152366. ** the allocated array. *pnIndex is set to the number of elements in the
  152367. ** array. If an error does occur, an SQLite error code is returned.
  152368. **
  152369. ** Regardless of whether or not an error is returned, it is the responsibility
  152370. ** of the caller to call sqlite3_free() on the output array to free it.
  152371. */
  152372. static int fts3PrefixParameter(
  152373. const char *zParam, /* ABC in prefix=ABC parameter to parse */
  152374. int *pnIndex, /* OUT: size of *apIndex[] array */
  152375. struct Fts3Index **apIndex /* OUT: Array of indexes for this table */
  152376. ){
  152377. struct Fts3Index *aIndex; /* Allocated array */
  152378. int nIndex = 1; /* Number of entries in array */
  152379. if( zParam && zParam[0] ){
  152380. const char *p;
  152381. nIndex++;
  152382. for(p=zParam; *p; p++){
  152383. if( *p==',' ) nIndex++;
  152384. }
  152385. }
  152386. aIndex = sqlite3_malloc64(sizeof(struct Fts3Index) * nIndex);
  152387. *apIndex = aIndex;
  152388. if( !aIndex ){
  152389. return SQLITE_NOMEM;
  152390. }
  152391. memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
  152392. if( zParam ){
  152393. const char *p = zParam;
  152394. int i;
  152395. for(i=1; i<nIndex; i++){
  152396. int nPrefix = 0;
  152397. if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
  152398. assert( nPrefix>=0 );
  152399. if( nPrefix==0 ){
  152400. nIndex--;
  152401. i--;
  152402. }else{
  152403. aIndex[i].nPrefix = nPrefix;
  152404. }
  152405. p++;
  152406. }
  152407. }
  152408. *pnIndex = nIndex;
  152409. return SQLITE_OK;
  152410. }
  152411. /*
  152412. ** This function is called when initializing an FTS4 table that uses the
  152413. ** content=xxx option. It determines the number of and names of the columns
  152414. ** of the new FTS4 table.
  152415. **
  152416. ** The third argument passed to this function is the value passed to the
  152417. ** config=xxx option (i.e. "xxx"). This function queries the database for
  152418. ** a table of that name. If found, the output variables are populated
  152419. ** as follows:
  152420. **
  152421. ** *pnCol: Set to the number of columns table xxx has,
  152422. **
  152423. ** *pnStr: Set to the total amount of space required to store a copy
  152424. ** of each columns name, including the nul-terminator.
  152425. **
  152426. ** *pazCol: Set to point to an array of *pnCol strings. Each string is
  152427. ** the name of the corresponding column in table xxx. The array
  152428. ** and its contents are allocated using a single allocation. It
  152429. ** is the responsibility of the caller to free this allocation
  152430. ** by eventually passing the *pazCol value to sqlite3_free().
  152431. **
  152432. ** If the table cannot be found, an error code is returned and the output
  152433. ** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
  152434. ** returned (and the output variables are undefined).
  152435. */
  152436. static int fts3ContentColumns(
  152437. sqlite3 *db, /* Database handle */
  152438. const char *zDb, /* Name of db (i.e. "main", "temp" etc.) */
  152439. const char *zTbl, /* Name of content table */
  152440. const char ***pazCol, /* OUT: Malloc'd array of column names */
  152441. int *pnCol, /* OUT: Size of array *pazCol */
  152442. int *pnStr, /* OUT: Bytes of string content */
  152443. char **pzErr /* OUT: error message */
  152444. ){
  152445. int rc = SQLITE_OK; /* Return code */
  152446. char *zSql; /* "SELECT *" statement on zTbl */
  152447. sqlite3_stmt *pStmt = 0; /* Compiled version of zSql */
  152448. zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
  152449. if( !zSql ){
  152450. rc = SQLITE_NOMEM;
  152451. }else{
  152452. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  152453. if( rc!=SQLITE_OK ){
  152454. sqlite3Fts3ErrMsg(pzErr, "%s", sqlite3_errmsg(db));
  152455. }
  152456. }
  152457. sqlite3_free(zSql);
  152458. if( rc==SQLITE_OK ){
  152459. const char **azCol; /* Output array */
  152460. sqlite3_int64 nStr = 0; /* Size of all column names (incl. 0x00) */
  152461. int nCol; /* Number of table columns */
  152462. int i; /* Used to iterate through columns */
  152463. /* Loop through the returned columns. Set nStr to the number of bytes of
  152464. ** space required to store a copy of each column name, including the
  152465. ** nul-terminator byte. */
  152466. nCol = sqlite3_column_count(pStmt);
  152467. for(i=0; i<nCol; i++){
  152468. const char *zCol = sqlite3_column_name(pStmt, i);
  152469. nStr += strlen(zCol) + 1;
  152470. }
  152471. /* Allocate and populate the array to return. */
  152472. azCol = (const char **)sqlite3_malloc64(sizeof(char *) * nCol + nStr);
  152473. if( azCol==0 ){
  152474. rc = SQLITE_NOMEM;
  152475. }else{
  152476. char *p = (char *)&azCol[nCol];
  152477. for(i=0; i<nCol; i++){
  152478. const char *zCol = sqlite3_column_name(pStmt, i);
  152479. int n = (int)strlen(zCol)+1;
  152480. memcpy(p, zCol, n);
  152481. azCol[i] = p;
  152482. p += n;
  152483. }
  152484. }
  152485. sqlite3_finalize(pStmt);
  152486. /* Set the output variables. */
  152487. *pnCol = nCol;
  152488. *pnStr = nStr;
  152489. *pazCol = azCol;
  152490. }
  152491. return rc;
  152492. }
  152493. /*
  152494. ** This function is the implementation of both the xConnect and xCreate
  152495. ** methods of the FTS3 virtual table.
  152496. **
  152497. ** The argv[] array contains the following:
  152498. **
  152499. ** argv[0] -> module name ("fts3" or "fts4")
  152500. ** argv[1] -> database name
  152501. ** argv[2] -> table name
  152502. ** argv[...] -> "column name" and other module argument fields.
  152503. */
  152504. static int fts3InitVtab(
  152505. int isCreate, /* True for xCreate, false for xConnect */
  152506. sqlite3 *db, /* The SQLite database connection */
  152507. void *pAux, /* Hash table containing tokenizers */
  152508. int argc, /* Number of elements in argv array */
  152509. const char * const *argv, /* xCreate/xConnect argument array */
  152510. sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
  152511. char **pzErr /* Write any error message here */
  152512. ){
  152513. Fts3Hash *pHash = (Fts3Hash *)pAux;
  152514. Fts3Table *p = 0; /* Pointer to allocated vtab */
  152515. int rc = SQLITE_OK; /* Return code */
  152516. int i; /* Iterator variable */
  152517. sqlite3_int64 nByte; /* Size of allocation used for *p */
  152518. int iCol; /* Column index */
  152519. int nString = 0; /* Bytes required to hold all column names */
  152520. int nCol = 0; /* Number of columns in the FTS table */
  152521. char *zCsr; /* Space for holding column names */
  152522. int nDb; /* Bytes required to hold database name */
  152523. int nName; /* Bytes required to hold table name */
  152524. int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
  152525. const char **aCol; /* Array of column names */
  152526. sqlite3_tokenizer *pTokenizer = 0; /* Tokenizer for this table */
  152527. int nIndex = 0; /* Size of aIndex[] array */
  152528. struct Fts3Index *aIndex = 0; /* Array of indexes for this table */
  152529. /* The results of parsing supported FTS4 key=value options: */
  152530. int bNoDocsize = 0; /* True to omit %_docsize table */
  152531. int bDescIdx = 0; /* True to store descending indexes */
  152532. char *zPrefix = 0; /* Prefix parameter value (or NULL) */
  152533. char *zCompress = 0; /* compress=? parameter (or NULL) */
  152534. char *zUncompress = 0; /* uncompress=? parameter (or NULL) */
  152535. char *zContent = 0; /* content=? parameter (or NULL) */
  152536. char *zLanguageid = 0; /* languageid=? parameter (or NULL) */
  152537. char **azNotindexed = 0; /* The set of notindexed= columns */
  152538. int nNotindexed = 0; /* Size of azNotindexed[] array */
  152539. assert( strlen(argv[0])==4 );
  152540. assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
  152541. || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
  152542. );
  152543. nDb = (int)strlen(argv[1]) + 1;
  152544. nName = (int)strlen(argv[2]) + 1;
  152545. nByte = sizeof(const char *) * (argc-2);
  152546. aCol = (const char **)sqlite3_malloc64(nByte);
  152547. if( aCol ){
  152548. memset((void*)aCol, 0, nByte);
  152549. azNotindexed = (char **)sqlite3_malloc64(nByte);
  152550. }
  152551. if( azNotindexed ){
  152552. memset(azNotindexed, 0, nByte);
  152553. }
  152554. if( !aCol || !azNotindexed ){
  152555. rc = SQLITE_NOMEM;
  152556. goto fts3_init_out;
  152557. }
  152558. /* Loop through all of the arguments passed by the user to the FTS3/4
  152559. ** module (i.e. all the column names and special arguments). This loop
  152560. ** does the following:
  152561. **
  152562. ** + Figures out the number of columns the FTSX table will have, and
  152563. ** the number of bytes of space that must be allocated to store copies
  152564. ** of the column names.
  152565. **
  152566. ** + If there is a tokenizer specification included in the arguments,
  152567. ** initializes the tokenizer pTokenizer.
  152568. */
  152569. for(i=3; rc==SQLITE_OK && i<argc; i++){
  152570. char const *z = argv[i];
  152571. int nKey;
  152572. char *zVal;
  152573. /* Check if this is a tokenizer specification */
  152574. if( !pTokenizer
  152575. && strlen(z)>8
  152576. && 0==sqlite3_strnicmp(z, "tokenize", 8)
  152577. && 0==sqlite3Fts3IsIdChar(z[8])
  152578. ){
  152579. rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
  152580. }
  152581. /* Check if it is an FTS4 special argument. */
  152582. else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
  152583. struct Fts4Option {
  152584. const char *zOpt;
  152585. int nOpt;
  152586. } aFts4Opt[] = {
  152587. { "matchinfo", 9 }, /* 0 -> MATCHINFO */
  152588. { "prefix", 6 }, /* 1 -> PREFIX */
  152589. { "compress", 8 }, /* 2 -> COMPRESS */
  152590. { "uncompress", 10 }, /* 3 -> UNCOMPRESS */
  152591. { "order", 5 }, /* 4 -> ORDER */
  152592. { "content", 7 }, /* 5 -> CONTENT */
  152593. { "languageid", 10 }, /* 6 -> LANGUAGEID */
  152594. { "notindexed", 10 } /* 7 -> NOTINDEXED */
  152595. };
  152596. int iOpt;
  152597. if( !zVal ){
  152598. rc = SQLITE_NOMEM;
  152599. }else{
  152600. for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
  152601. struct Fts4Option *pOp = &aFts4Opt[iOpt];
  152602. if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
  152603. break;
  152604. }
  152605. }
  152606. switch( iOpt ){
  152607. case 0: /* MATCHINFO */
  152608. if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
  152609. sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo: %s", zVal);
  152610. rc = SQLITE_ERROR;
  152611. }
  152612. bNoDocsize = 1;
  152613. break;
  152614. case 1: /* PREFIX */
  152615. sqlite3_free(zPrefix);
  152616. zPrefix = zVal;
  152617. zVal = 0;
  152618. break;
  152619. case 2: /* COMPRESS */
  152620. sqlite3_free(zCompress);
  152621. zCompress = zVal;
  152622. zVal = 0;
  152623. break;
  152624. case 3: /* UNCOMPRESS */
  152625. sqlite3_free(zUncompress);
  152626. zUncompress = zVal;
  152627. zVal = 0;
  152628. break;
  152629. case 4: /* ORDER */
  152630. if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3))
  152631. && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4))
  152632. ){
  152633. sqlite3Fts3ErrMsg(pzErr, "unrecognized order: %s", zVal);
  152634. rc = SQLITE_ERROR;
  152635. }
  152636. bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
  152637. break;
  152638. case 5: /* CONTENT */
  152639. sqlite3_free(zContent);
  152640. zContent = zVal;
  152641. zVal = 0;
  152642. break;
  152643. case 6: /* LANGUAGEID */
  152644. assert( iOpt==6 );
  152645. sqlite3_free(zLanguageid);
  152646. zLanguageid = zVal;
  152647. zVal = 0;
  152648. break;
  152649. case 7: /* NOTINDEXED */
  152650. azNotindexed[nNotindexed++] = zVal;
  152651. zVal = 0;
  152652. break;
  152653. default:
  152654. assert( iOpt==SizeofArray(aFts4Opt) );
  152655. sqlite3Fts3ErrMsg(pzErr, "unrecognized parameter: %s", z);
  152656. rc = SQLITE_ERROR;
  152657. break;
  152658. }
  152659. sqlite3_free(zVal);
  152660. }
  152661. }
  152662. /* Otherwise, the argument is a column name. */
  152663. else {
  152664. nString += (int)(strlen(z) + 1);
  152665. aCol[nCol++] = z;
  152666. }
  152667. }
  152668. /* If a content=xxx option was specified, the following:
  152669. **
  152670. ** 1. Ignore any compress= and uncompress= options.
  152671. **
  152672. ** 2. If no column names were specified as part of the CREATE VIRTUAL
  152673. ** TABLE statement, use all columns from the content table.
  152674. */
  152675. if( rc==SQLITE_OK && zContent ){
  152676. sqlite3_free(zCompress);
  152677. sqlite3_free(zUncompress);
  152678. zCompress = 0;
  152679. zUncompress = 0;
  152680. if( nCol==0 ){
  152681. sqlite3_free((void*)aCol);
  152682. aCol = 0;
  152683. rc = fts3ContentColumns(db, argv[1], zContent,&aCol,&nCol,&nString,pzErr);
  152684. /* If a languageid= option was specified, remove the language id
  152685. ** column from the aCol[] array. */
  152686. if( rc==SQLITE_OK && zLanguageid ){
  152687. int j;
  152688. for(j=0; j<nCol; j++){
  152689. if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
  152690. int k;
  152691. for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
  152692. nCol--;
  152693. break;
  152694. }
  152695. }
  152696. }
  152697. }
  152698. }
  152699. if( rc!=SQLITE_OK ) goto fts3_init_out;
  152700. if( nCol==0 ){
  152701. assert( nString==0 );
  152702. aCol[0] = "content";
  152703. nString = 8;
  152704. nCol = 1;
  152705. }
  152706. if( pTokenizer==0 ){
  152707. rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
  152708. if( rc!=SQLITE_OK ) goto fts3_init_out;
  152709. }
  152710. assert( pTokenizer );
  152711. rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
  152712. if( rc==SQLITE_ERROR ){
  152713. assert( zPrefix );
  152714. sqlite3Fts3ErrMsg(pzErr, "error parsing prefix parameter: %s", zPrefix);
  152715. }
  152716. if( rc!=SQLITE_OK ) goto fts3_init_out;
  152717. /* Allocate and populate the Fts3Table structure. */
  152718. nByte = sizeof(Fts3Table) + /* Fts3Table */
  152719. nCol * sizeof(char *) + /* azColumn */
  152720. nIndex * sizeof(struct Fts3Index) + /* aIndex */
  152721. nCol * sizeof(u8) + /* abNotindexed */
  152722. nName + /* zName */
  152723. nDb + /* zDb */
  152724. nString; /* Space for azColumn strings */
  152725. p = (Fts3Table*)sqlite3_malloc64(nByte);
  152726. if( p==0 ){
  152727. rc = SQLITE_NOMEM;
  152728. goto fts3_init_out;
  152729. }
  152730. memset(p, 0, nByte);
  152731. p->db = db;
  152732. p->nColumn = nCol;
  152733. p->nPendingData = 0;
  152734. p->azColumn = (char **)&p[1];
  152735. p->pTokenizer = pTokenizer;
  152736. p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
  152737. p->bHasDocsize = (isFts4 && bNoDocsize==0);
  152738. p->bHasStat = (u8)isFts4;
  152739. p->bFts4 = (u8)isFts4;
  152740. p->bDescIdx = (u8)bDescIdx;
  152741. p->nAutoincrmerge = 0xff; /* 0xff means setting unknown */
  152742. p->zContentTbl = zContent;
  152743. p->zLanguageid = zLanguageid;
  152744. zContent = 0;
  152745. zLanguageid = 0;
  152746. TESTONLY( p->inTransaction = -1 );
  152747. TESTONLY( p->mxSavepoint = -1 );
  152748. p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
  152749. memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
  152750. p->nIndex = nIndex;
  152751. for(i=0; i<nIndex; i++){
  152752. fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
  152753. }
  152754. p->abNotindexed = (u8 *)&p->aIndex[nIndex];
  152755. /* Fill in the zName and zDb fields of the vtab structure. */
  152756. zCsr = (char *)&p->abNotindexed[nCol];
  152757. p->zName = zCsr;
  152758. memcpy(zCsr, argv[2], nName);
  152759. zCsr += nName;
  152760. p->zDb = zCsr;
  152761. memcpy(zCsr, argv[1], nDb);
  152762. zCsr += nDb;
  152763. /* Fill in the azColumn array */
  152764. for(iCol=0; iCol<nCol; iCol++){
  152765. char *z;
  152766. int n = 0;
  152767. z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
  152768. if( n>0 ){
  152769. memcpy(zCsr, z, n);
  152770. }
  152771. zCsr[n] = '\0';
  152772. sqlite3Fts3Dequote(zCsr);
  152773. p->azColumn[iCol] = zCsr;
  152774. zCsr += n+1;
  152775. assert( zCsr <= &((char *)p)[nByte] );
  152776. }
  152777. /* Fill in the abNotindexed array */
  152778. for(iCol=0; iCol<nCol; iCol++){
  152779. int n = (int)strlen(p->azColumn[iCol]);
  152780. for(i=0; i<nNotindexed; i++){
  152781. char *zNot = azNotindexed[i];
  152782. if( zNot && n==(int)strlen(zNot)
  152783. && 0==sqlite3_strnicmp(p->azColumn[iCol], zNot, n)
  152784. ){
  152785. p->abNotindexed[iCol] = 1;
  152786. sqlite3_free(zNot);
  152787. azNotindexed[i] = 0;
  152788. }
  152789. }
  152790. }
  152791. for(i=0; i<nNotindexed; i++){
  152792. if( azNotindexed[i] ){
  152793. sqlite3Fts3ErrMsg(pzErr, "no such column: %s", azNotindexed[i]);
  152794. rc = SQLITE_ERROR;
  152795. }
  152796. }
  152797. if( rc==SQLITE_OK && (zCompress==0)!=(zUncompress==0) ){
  152798. char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
  152799. rc = SQLITE_ERROR;
  152800. sqlite3Fts3ErrMsg(pzErr, "missing %s parameter in fts4 constructor", zMiss);
  152801. }
  152802. p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
  152803. p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
  152804. if( rc!=SQLITE_OK ) goto fts3_init_out;
  152805. /* If this is an xCreate call, create the underlying tables in the
  152806. ** database. TODO: For xConnect(), it could verify that said tables exist.
  152807. */
  152808. if( isCreate ){
  152809. rc = fts3CreateTables(p);
  152810. }
  152811. /* Check to see if a legacy fts3 table has been "upgraded" by the
  152812. ** addition of a %_stat table so that it can use incremental merge.
  152813. */
  152814. if( !isFts4 && !isCreate ){
  152815. p->bHasStat = 2;
  152816. }
  152817. /* Figure out the page-size for the database. This is required in order to
  152818. ** estimate the cost of loading large doclists from the database. */
  152819. fts3DatabasePageSize(&rc, p);
  152820. p->nNodeSize = p->nPgsz-35;
  152821. /* Declare the table schema to SQLite. */
  152822. fts3DeclareVtab(&rc, p);
  152823. fts3_init_out:
  152824. sqlite3_free(zPrefix);
  152825. sqlite3_free(aIndex);
  152826. sqlite3_free(zCompress);
  152827. sqlite3_free(zUncompress);
  152828. sqlite3_free(zContent);
  152829. sqlite3_free(zLanguageid);
  152830. for(i=0; i<nNotindexed; i++) sqlite3_free(azNotindexed[i]);
  152831. sqlite3_free((void *)aCol);
  152832. sqlite3_free((void *)azNotindexed);
  152833. if( rc!=SQLITE_OK ){
  152834. if( p ){
  152835. fts3DisconnectMethod((sqlite3_vtab *)p);
  152836. }else if( pTokenizer ){
  152837. pTokenizer->pModule->xDestroy(pTokenizer);
  152838. }
  152839. }else{
  152840. assert( p->pSegments==0 );
  152841. *ppVTab = &p->base;
  152842. }
  152843. return rc;
  152844. }
  152845. /*
  152846. ** The xConnect() and xCreate() methods for the virtual table. All the
  152847. ** work is done in function fts3InitVtab().
  152848. */
  152849. static int fts3ConnectMethod(
  152850. sqlite3 *db, /* Database connection */
  152851. void *pAux, /* Pointer to tokenizer hash table */
  152852. int argc, /* Number of elements in argv array */
  152853. const char * const *argv, /* xCreate/xConnect argument array */
  152854. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  152855. char **pzErr /* OUT: sqlite3_malloc'd error message */
  152856. ){
  152857. return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
  152858. }
  152859. static int fts3CreateMethod(
  152860. sqlite3 *db, /* Database connection */
  152861. void *pAux, /* Pointer to tokenizer hash table */
  152862. int argc, /* Number of elements in argv array */
  152863. const char * const *argv, /* xCreate/xConnect argument array */
  152864. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  152865. char **pzErr /* OUT: sqlite3_malloc'd error message */
  152866. ){
  152867. return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
  152868. }
  152869. /*
  152870. ** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
  152871. ** extension is currently being used by a version of SQLite too old to
  152872. ** support estimatedRows. In that case this function is a no-op.
  152873. */
  152874. static void fts3SetEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
  152875. #if SQLITE_VERSION_NUMBER>=3008002
  152876. if( sqlite3_libversion_number()>=3008002 ){
  152877. pIdxInfo->estimatedRows = nRow;
  152878. }
  152879. #endif
  152880. }
  152881. /*
  152882. ** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this
  152883. ** extension is currently being used by a version of SQLite too old to
  152884. ** support index-info flags. In that case this function is a no-op.
  152885. */
  152886. static void fts3SetUniqueFlag(sqlite3_index_info *pIdxInfo){
  152887. #if SQLITE_VERSION_NUMBER>=3008012
  152888. if( sqlite3_libversion_number()>=3008012 ){
  152889. pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE;
  152890. }
  152891. #endif
  152892. }
  152893. /*
  152894. ** Implementation of the xBestIndex method for FTS3 tables. There
  152895. ** are three possible strategies, in order of preference:
  152896. **
  152897. ** 1. Direct lookup by rowid or docid.
  152898. ** 2. Full-text search using a MATCH operator on a non-docid column.
  152899. ** 3. Linear scan of %_content table.
  152900. */
  152901. static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
  152902. Fts3Table *p = (Fts3Table *)pVTab;
  152903. int i; /* Iterator variable */
  152904. int iCons = -1; /* Index of constraint to use */
  152905. int iLangidCons = -1; /* Index of langid=x constraint, if present */
  152906. int iDocidGe = -1; /* Index of docid>=x constraint, if present */
  152907. int iDocidLe = -1; /* Index of docid<=x constraint, if present */
  152908. int iIdx;
  152909. /* By default use a full table scan. This is an expensive option,
  152910. ** so search through the constraints to see if a more efficient
  152911. ** strategy is possible.
  152912. */
  152913. pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
  152914. pInfo->estimatedCost = 5000000;
  152915. for(i=0; i<pInfo->nConstraint; i++){
  152916. int bDocid; /* True if this constraint is on docid */
  152917. struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
  152918. if( pCons->usable==0 ){
  152919. if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
  152920. /* There exists an unusable MATCH constraint. This means that if
  152921. ** the planner does elect to use the results of this call as part
  152922. ** of the overall query plan the user will see an "unable to use
  152923. ** function MATCH in the requested context" error. To discourage
  152924. ** this, return a very high cost here. */
  152925. pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
  152926. pInfo->estimatedCost = 1e50;
  152927. fts3SetEstimatedRows(pInfo, ((sqlite3_int64)1) << 50);
  152928. return SQLITE_OK;
  152929. }
  152930. continue;
  152931. }
  152932. bDocid = (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1);
  152933. /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
  152934. if( iCons<0 && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ && bDocid ){
  152935. pInfo->idxNum = FTS3_DOCID_SEARCH;
  152936. pInfo->estimatedCost = 1.0;
  152937. iCons = i;
  152938. }
  152939. /* A MATCH constraint. Use a full-text search.
  152940. **
  152941. ** If there is more than one MATCH constraint available, use the first
  152942. ** one encountered. If there is both a MATCH constraint and a direct
  152943. ** rowid/docid lookup, prefer the MATCH strategy. This is done even
  152944. ** though the rowid/docid lookup is faster than a MATCH query, selecting
  152945. ** it would lead to an "unable to use function MATCH in the requested
  152946. ** context" error.
  152947. */
  152948. if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
  152949. && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
  152950. ){
  152951. pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
  152952. pInfo->estimatedCost = 2.0;
  152953. iCons = i;
  152954. }
  152955. /* Equality constraint on the langid column */
  152956. if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
  152957. && pCons->iColumn==p->nColumn + 2
  152958. ){
  152959. iLangidCons = i;
  152960. }
  152961. if( bDocid ){
  152962. switch( pCons->op ){
  152963. case SQLITE_INDEX_CONSTRAINT_GE:
  152964. case SQLITE_INDEX_CONSTRAINT_GT:
  152965. iDocidGe = i;
  152966. break;
  152967. case SQLITE_INDEX_CONSTRAINT_LE:
  152968. case SQLITE_INDEX_CONSTRAINT_LT:
  152969. iDocidLe = i;
  152970. break;
  152971. }
  152972. }
  152973. }
  152974. /* If using a docid=? or rowid=? strategy, set the UNIQUE flag. */
  152975. if( pInfo->idxNum==FTS3_DOCID_SEARCH ) fts3SetUniqueFlag(pInfo);
  152976. iIdx = 1;
  152977. if( iCons>=0 ){
  152978. pInfo->aConstraintUsage[iCons].argvIndex = iIdx++;
  152979. pInfo->aConstraintUsage[iCons].omit = 1;
  152980. }
  152981. if( iLangidCons>=0 ){
  152982. pInfo->idxNum |= FTS3_HAVE_LANGID;
  152983. pInfo->aConstraintUsage[iLangidCons].argvIndex = iIdx++;
  152984. }
  152985. if( iDocidGe>=0 ){
  152986. pInfo->idxNum |= FTS3_HAVE_DOCID_GE;
  152987. pInfo->aConstraintUsage[iDocidGe].argvIndex = iIdx++;
  152988. }
  152989. if( iDocidLe>=0 ){
  152990. pInfo->idxNum |= FTS3_HAVE_DOCID_LE;
  152991. pInfo->aConstraintUsage[iDocidLe].argvIndex = iIdx++;
  152992. }
  152993. /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
  152994. ** docid) order. Both ascending and descending are possible.
  152995. */
  152996. if( pInfo->nOrderBy==1 ){
  152997. struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
  152998. if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
  152999. if( pOrder->desc ){
  153000. pInfo->idxStr = "DESC";
  153001. }else{
  153002. pInfo->idxStr = "ASC";
  153003. }
  153004. pInfo->orderByConsumed = 1;
  153005. }
  153006. }
  153007. assert( p->pSegments==0 );
  153008. return SQLITE_OK;
  153009. }
  153010. /*
  153011. ** Implementation of xOpen method.
  153012. */
  153013. static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  153014. sqlite3_vtab_cursor *pCsr; /* Allocated cursor */
  153015. UNUSED_PARAMETER(pVTab);
  153016. /* Allocate a buffer large enough for an Fts3Cursor structure. If the
  153017. ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
  153018. ** if the allocation fails, return SQLITE_NOMEM.
  153019. */
  153020. *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
  153021. if( !pCsr ){
  153022. return SQLITE_NOMEM;
  153023. }
  153024. memset(pCsr, 0, sizeof(Fts3Cursor));
  153025. return SQLITE_OK;
  153026. }
  153027. /*
  153028. ** Finalize the statement handle at pCsr->pStmt.
  153029. **
  153030. ** Or, if that statement handle is one created by fts3CursorSeekStmt(),
  153031. ** and the Fts3Table.pSeekStmt slot is currently NULL, save the statement
  153032. ** pointer there instead of finalizing it.
  153033. */
  153034. static void fts3CursorFinalizeStmt(Fts3Cursor *pCsr){
  153035. if( pCsr->bSeekStmt ){
  153036. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  153037. if( p->pSeekStmt==0 ){
  153038. p->pSeekStmt = pCsr->pStmt;
  153039. sqlite3_reset(pCsr->pStmt);
  153040. pCsr->pStmt = 0;
  153041. }
  153042. pCsr->bSeekStmt = 0;
  153043. }
  153044. sqlite3_finalize(pCsr->pStmt);
  153045. }
  153046. /*
  153047. ** Free all resources currently held by the cursor passed as the only
  153048. ** argument.
  153049. */
  153050. static void fts3ClearCursor(Fts3Cursor *pCsr){
  153051. fts3CursorFinalizeStmt(pCsr);
  153052. sqlite3Fts3FreeDeferredTokens(pCsr);
  153053. sqlite3_free(pCsr->aDoclist);
  153054. sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
  153055. sqlite3Fts3ExprFree(pCsr->pExpr);
  153056. memset(&(&pCsr->base)[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
  153057. }
  153058. /*
  153059. ** Close the cursor. For additional information see the documentation
  153060. ** on the xClose method of the virtual table interface.
  153061. */
  153062. static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
  153063. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  153064. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  153065. fts3ClearCursor(pCsr);
  153066. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  153067. sqlite3_free(pCsr);
  153068. return SQLITE_OK;
  153069. }
  153070. /*
  153071. ** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
  153072. ** compose and prepare an SQL statement of the form:
  153073. **
  153074. ** "SELECT <columns> FROM %_content WHERE rowid = ?"
  153075. **
  153076. ** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
  153077. ** it. If an error occurs, return an SQLite error code.
  153078. */
  153079. static int fts3CursorSeekStmt(Fts3Cursor *pCsr){
  153080. int rc = SQLITE_OK;
  153081. if( pCsr->pStmt==0 ){
  153082. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  153083. char *zSql;
  153084. if( p->pSeekStmt ){
  153085. pCsr->pStmt = p->pSeekStmt;
  153086. p->pSeekStmt = 0;
  153087. }else{
  153088. zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
  153089. if( !zSql ) return SQLITE_NOMEM;
  153090. rc = sqlite3_prepare_v3(p->db, zSql,-1,SQLITE_PREPARE_PERSISTENT,&pCsr->pStmt,0);
  153091. sqlite3_free(zSql);
  153092. }
  153093. if( rc==SQLITE_OK ) pCsr->bSeekStmt = 1;
  153094. }
  153095. return rc;
  153096. }
  153097. /*
  153098. ** Position the pCsr->pStmt statement so that it is on the row
  153099. ** of the %_content table that contains the last match. Return
  153100. ** SQLITE_OK on success.
  153101. */
  153102. static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
  153103. int rc = SQLITE_OK;
  153104. if( pCsr->isRequireSeek ){
  153105. rc = fts3CursorSeekStmt(pCsr);
  153106. if( rc==SQLITE_OK ){
  153107. sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
  153108. pCsr->isRequireSeek = 0;
  153109. if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
  153110. return SQLITE_OK;
  153111. }else{
  153112. rc = sqlite3_reset(pCsr->pStmt);
  153113. if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
  153114. /* If no row was found and no error has occurred, then the %_content
  153115. ** table is missing a row that is present in the full-text index.
  153116. ** The data structures are corrupt. */
  153117. rc = FTS_CORRUPT_VTAB;
  153118. pCsr->isEof = 1;
  153119. }
  153120. }
  153121. }
  153122. }
  153123. if( rc!=SQLITE_OK && pContext ){
  153124. sqlite3_result_error_code(pContext, rc);
  153125. }
  153126. return rc;
  153127. }
  153128. /*
  153129. ** This function is used to process a single interior node when searching
  153130. ** a b-tree for a term or term prefix. The node data is passed to this
  153131. ** function via the zNode/nNode parameters. The term to search for is
  153132. ** passed in zTerm/nTerm.
  153133. **
  153134. ** If piFirst is not NULL, then this function sets *piFirst to the blockid
  153135. ** of the child node that heads the sub-tree that may contain the term.
  153136. **
  153137. ** If piLast is not NULL, then *piLast is set to the right-most child node
  153138. ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
  153139. ** a prefix.
  153140. **
  153141. ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
  153142. */
  153143. static int fts3ScanInteriorNode(
  153144. const char *zTerm, /* Term to select leaves for */
  153145. int nTerm, /* Size of term zTerm in bytes */
  153146. const char *zNode, /* Buffer containing segment interior node */
  153147. int nNode, /* Size of buffer at zNode */
  153148. sqlite3_int64 *piFirst, /* OUT: Selected child node */
  153149. sqlite3_int64 *piLast /* OUT: Selected child node */
  153150. ){
  153151. int rc = SQLITE_OK; /* Return code */
  153152. const char *zCsr = zNode; /* Cursor to iterate through node */
  153153. const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
  153154. char *zBuffer = 0; /* Buffer to load terms into */
  153155. i64 nAlloc = 0; /* Size of allocated buffer */
  153156. int isFirstTerm = 1; /* True when processing first term on page */
  153157. sqlite3_int64 iChild; /* Block id of child node to descend to */
  153158. /* Skip over the 'height' varint that occurs at the start of every
  153159. ** interior node. Then load the blockid of the left-child of the b-tree
  153160. ** node into variable iChild.
  153161. **
  153162. ** Even if the data structure on disk is corrupted, this (reading two
  153163. ** varints from the buffer) does not risk an overread. If zNode is a
  153164. ** root node, then the buffer comes from a SELECT statement. SQLite does
  153165. ** not make this guarantee explicitly, but in practice there are always
  153166. ** either more than 20 bytes of allocated space following the nNode bytes of
  153167. ** contents, or two zero bytes. Or, if the node is read from the %_segments
  153168. ** table, then there are always 20 bytes of zeroed padding following the
  153169. ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
  153170. */
  153171. zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
  153172. zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
  153173. if( zCsr>zEnd ){
  153174. return FTS_CORRUPT_VTAB;
  153175. }
  153176. while( zCsr<zEnd && (piFirst || piLast) ){
  153177. int cmp; /* memcmp() result */
  153178. int nSuffix; /* Size of term suffix */
  153179. int nPrefix = 0; /* Size of term prefix */
  153180. int nBuffer; /* Total term size */
  153181. /* Load the next term on the node into zBuffer. Use realloc() to expand
  153182. ** the size of zBuffer if required. */
  153183. if( !isFirstTerm ){
  153184. zCsr += fts3GetVarint32(zCsr, &nPrefix);
  153185. }
  153186. isFirstTerm = 0;
  153187. zCsr += fts3GetVarint32(zCsr, &nSuffix);
  153188. assert( nPrefix>=0 && nSuffix>=0 );
  153189. if( nPrefix>zCsr-zNode || nSuffix>zEnd-zCsr || nSuffix==0 ){
  153190. rc = FTS_CORRUPT_VTAB;
  153191. goto finish_scan;
  153192. }
  153193. if( (i64)nPrefix+nSuffix>nAlloc ){
  153194. char *zNew;
  153195. nAlloc = ((i64)nPrefix+nSuffix) * 2;
  153196. zNew = (char *)sqlite3_realloc64(zBuffer, nAlloc);
  153197. if( !zNew ){
  153198. rc = SQLITE_NOMEM;
  153199. goto finish_scan;
  153200. }
  153201. zBuffer = zNew;
  153202. }
  153203. assert( zBuffer );
  153204. memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
  153205. nBuffer = nPrefix + nSuffix;
  153206. zCsr += nSuffix;
  153207. /* Compare the term we are searching for with the term just loaded from
  153208. ** the interior node. If the specified term is greater than or equal
  153209. ** to the term from the interior node, then all terms on the sub-tree
  153210. ** headed by node iChild are smaller than zTerm. No need to search
  153211. ** iChild.
  153212. **
  153213. ** If the interior node term is larger than the specified term, then
  153214. ** the tree headed by iChild may contain the specified term.
  153215. */
  153216. cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
  153217. if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
  153218. *piFirst = iChild;
  153219. piFirst = 0;
  153220. }
  153221. if( piLast && cmp<0 ){
  153222. *piLast = iChild;
  153223. piLast = 0;
  153224. }
  153225. iChild++;
  153226. };
  153227. if( piFirst ) *piFirst = iChild;
  153228. if( piLast ) *piLast = iChild;
  153229. finish_scan:
  153230. sqlite3_free(zBuffer);
  153231. return rc;
  153232. }
  153233. /*
  153234. ** The buffer pointed to by argument zNode (size nNode bytes) contains an
  153235. ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
  153236. ** contains a term. This function searches the sub-tree headed by the zNode
  153237. ** node for the range of leaf nodes that may contain the specified term
  153238. ** or terms for which the specified term is a prefix.
  153239. **
  153240. ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
  153241. ** left-most leaf node in the tree that may contain the specified term.
  153242. ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
  153243. ** right-most leaf node that may contain a term for which the specified
  153244. ** term is a prefix.
  153245. **
  153246. ** It is possible that the range of returned leaf nodes does not contain
  153247. ** the specified term or any terms for which it is a prefix. However, if the
  153248. ** segment does contain any such terms, they are stored within the identified
  153249. ** range. Because this function only inspects interior segment nodes (and
  153250. ** never loads leaf nodes into memory), it is not possible to be sure.
  153251. **
  153252. ** If an error occurs, an error code other than SQLITE_OK is returned.
  153253. */
  153254. static int fts3SelectLeaf(
  153255. Fts3Table *p, /* Virtual table handle */
  153256. const char *zTerm, /* Term to select leaves for */
  153257. int nTerm, /* Size of term zTerm in bytes */
  153258. const char *zNode, /* Buffer containing segment interior node */
  153259. int nNode, /* Size of buffer at zNode */
  153260. sqlite3_int64 *piLeaf, /* Selected leaf node */
  153261. sqlite3_int64 *piLeaf2 /* Selected leaf node */
  153262. ){
  153263. int rc = SQLITE_OK; /* Return code */
  153264. int iHeight; /* Height of this node in tree */
  153265. assert( piLeaf || piLeaf2 );
  153266. fts3GetVarint32(zNode, &iHeight);
  153267. rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
  153268. assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
  153269. if( rc==SQLITE_OK && iHeight>1 ){
  153270. char *zBlob = 0; /* Blob read from %_segments table */
  153271. int nBlob = 0; /* Size of zBlob in bytes */
  153272. if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
  153273. rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
  153274. if( rc==SQLITE_OK ){
  153275. rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
  153276. }
  153277. sqlite3_free(zBlob);
  153278. piLeaf = 0;
  153279. zBlob = 0;
  153280. }
  153281. if( rc==SQLITE_OK ){
  153282. rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
  153283. }
  153284. if( rc==SQLITE_OK ){
  153285. rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
  153286. }
  153287. sqlite3_free(zBlob);
  153288. }
  153289. return rc;
  153290. }
  153291. /*
  153292. ** This function is used to create delta-encoded serialized lists of FTS3
  153293. ** varints. Each call to this function appends a single varint to a list.
  153294. */
  153295. static void fts3PutDeltaVarint(
  153296. char **pp, /* IN/OUT: Output pointer */
  153297. sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
  153298. sqlite3_int64 iVal /* Write this value to the list */
  153299. ){
  153300. assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
  153301. *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
  153302. *piPrev = iVal;
  153303. }
  153304. /*
  153305. ** When this function is called, *ppPoslist is assumed to point to the
  153306. ** start of a position-list. After it returns, *ppPoslist points to the
  153307. ** first byte after the position-list.
  153308. **
  153309. ** A position list is list of positions (delta encoded) and columns for
  153310. ** a single document record of a doclist. So, in other words, this
  153311. ** routine advances *ppPoslist so that it points to the next docid in
  153312. ** the doclist, or to the first byte past the end of the doclist.
  153313. **
  153314. ** If pp is not NULL, then the contents of the position list are copied
  153315. ** to *pp. *pp is set to point to the first byte past the last byte copied
  153316. ** before this function returns.
  153317. */
  153318. static void fts3PoslistCopy(char **pp, char **ppPoslist){
  153319. char *pEnd = *ppPoslist;
  153320. char c = 0;
  153321. /* The end of a position list is marked by a zero encoded as an FTS3
  153322. ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
  153323. ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
  153324. ** of some other, multi-byte, value.
  153325. **
  153326. ** The following while-loop moves pEnd to point to the first byte that is not
  153327. ** immediately preceded by a byte with the 0x80 bit set. Then increments
  153328. ** pEnd once more so that it points to the byte immediately following the
  153329. ** last byte in the position-list.
  153330. */
  153331. while( *pEnd | c ){
  153332. c = *pEnd++ & 0x80;
  153333. testcase( c!=0 && (*pEnd)==0 );
  153334. }
  153335. pEnd++; /* Advance past the POS_END terminator byte */
  153336. if( pp ){
  153337. int n = (int)(pEnd - *ppPoslist);
  153338. char *p = *pp;
  153339. memcpy(p, *ppPoslist, n);
  153340. p += n;
  153341. *pp = p;
  153342. }
  153343. *ppPoslist = pEnd;
  153344. }
  153345. /*
  153346. ** When this function is called, *ppPoslist is assumed to point to the
  153347. ** start of a column-list. After it returns, *ppPoslist points to the
  153348. ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
  153349. **
  153350. ** A column-list is list of delta-encoded positions for a single column
  153351. ** within a single document within a doclist.
  153352. **
  153353. ** The column-list is terminated either by a POS_COLUMN varint (1) or
  153354. ** a POS_END varint (0). This routine leaves *ppPoslist pointing to
  153355. ** the POS_COLUMN or POS_END that terminates the column-list.
  153356. **
  153357. ** If pp is not NULL, then the contents of the column-list are copied
  153358. ** to *pp. *pp is set to point to the first byte past the last byte copied
  153359. ** before this function returns. The POS_COLUMN or POS_END terminator
  153360. ** is not copied into *pp.
  153361. */
  153362. static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
  153363. char *pEnd = *ppPoslist;
  153364. char c = 0;
  153365. /* A column-list is terminated by either a 0x01 or 0x00 byte that is
  153366. ** not part of a multi-byte varint.
  153367. */
  153368. while( 0xFE & (*pEnd | c) ){
  153369. c = *pEnd++ & 0x80;
  153370. testcase( c!=0 && ((*pEnd)&0xfe)==0 );
  153371. }
  153372. if( pp ){
  153373. int n = (int)(pEnd - *ppPoslist);
  153374. char *p = *pp;
  153375. memcpy(p, *ppPoslist, n);
  153376. p += n;
  153377. *pp = p;
  153378. }
  153379. *ppPoslist = pEnd;
  153380. }
  153381. /*
  153382. ** Value used to signify the end of an position-list. This is safe because
  153383. ** it is not possible to have a document with 2^31 terms.
  153384. */
  153385. #define POSITION_LIST_END 0x7fffffff
  153386. /*
  153387. ** This function is used to help parse position-lists. When this function is
  153388. ** called, *pp may point to the start of the next varint in the position-list
  153389. ** being parsed, or it may point to 1 byte past the end of the position-list
  153390. ** (in which case **pp will be a terminator bytes POS_END (0) or
  153391. ** (1)).
  153392. **
  153393. ** If *pp points past the end of the current position-list, set *pi to
  153394. ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
  153395. ** increment the current value of *pi by the value read, and set *pp to
  153396. ** point to the next value before returning.
  153397. **
  153398. ** Before calling this routine *pi must be initialized to the value of
  153399. ** the previous position, or zero if we are reading the first position
  153400. ** in the position-list. Because positions are delta-encoded, the value
  153401. ** of the previous position is needed in order to compute the value of
  153402. ** the next position.
  153403. */
  153404. static void fts3ReadNextPos(
  153405. char **pp, /* IN/OUT: Pointer into position-list buffer */
  153406. sqlite3_int64 *pi /* IN/OUT: Value read from position-list */
  153407. ){
  153408. if( (**pp)&0xFE ){
  153409. fts3GetDeltaVarint(pp, pi);
  153410. *pi -= 2;
  153411. }else{
  153412. *pi = POSITION_LIST_END;
  153413. }
  153414. }
  153415. /*
  153416. ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
  153417. ** the value of iCol encoded as a varint to *pp. This will start a new
  153418. ** column list.
  153419. **
  153420. ** Set *pp to point to the byte just after the last byte written before
  153421. ** returning (do not modify it if iCol==0). Return the total number of bytes
  153422. ** written (0 if iCol==0).
  153423. */
  153424. static int fts3PutColNumber(char **pp, int iCol){
  153425. int n = 0; /* Number of bytes written */
  153426. if( iCol ){
  153427. char *p = *pp; /* Output pointer */
  153428. n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
  153429. *p = 0x01;
  153430. *pp = &p[n];
  153431. }
  153432. return n;
  153433. }
  153434. /*
  153435. ** Compute the union of two position lists. The output written
  153436. ** into *pp contains all positions of both *pp1 and *pp2 in sorted
  153437. ** order and with any duplicates removed. All pointers are
  153438. ** updated appropriately. The caller is responsible for insuring
  153439. ** that there is enough space in *pp to hold the complete output.
  153440. */
  153441. static int fts3PoslistMerge(
  153442. char **pp, /* Output buffer */
  153443. char **pp1, /* Left input list */
  153444. char **pp2 /* Right input list */
  153445. ){
  153446. char *p = *pp;
  153447. char *p1 = *pp1;
  153448. char *p2 = *pp2;
  153449. while( *p1 || *p2 ){
  153450. int iCol1; /* The current column index in pp1 */
  153451. int iCol2; /* The current column index in pp2 */
  153452. if( *p1==POS_COLUMN ){
  153453. fts3GetVarint32(&p1[1], &iCol1);
  153454. if( iCol1==0 ) return FTS_CORRUPT_VTAB;
  153455. }
  153456. else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
  153457. else iCol1 = 0;
  153458. if( *p2==POS_COLUMN ){
  153459. fts3GetVarint32(&p2[1], &iCol2);
  153460. if( iCol2==0 ) return FTS_CORRUPT_VTAB;
  153461. }
  153462. else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
  153463. else iCol2 = 0;
  153464. if( iCol1==iCol2 ){
  153465. sqlite3_int64 i1 = 0; /* Last position from pp1 */
  153466. sqlite3_int64 i2 = 0; /* Last position from pp2 */
  153467. sqlite3_int64 iPrev = 0;
  153468. int n = fts3PutColNumber(&p, iCol1);
  153469. p1 += n;
  153470. p2 += n;
  153471. /* At this point, both p1 and p2 point to the start of column-lists
  153472. ** for the same column (the column with index iCol1 and iCol2).
  153473. ** A column-list is a list of non-negative delta-encoded varints, each
  153474. ** incremented by 2 before being stored. Each list is terminated by a
  153475. ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
  153476. ** and writes the results to buffer p. p is left pointing to the byte
  153477. ** after the list written. No terminator (POS_END or POS_COLUMN) is
  153478. ** written to the output.
  153479. */
  153480. fts3GetDeltaVarint(&p1, &i1);
  153481. fts3GetDeltaVarint(&p2, &i2);
  153482. do {
  153483. fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
  153484. iPrev -= 2;
  153485. if( i1==i2 ){
  153486. fts3ReadNextPos(&p1, &i1);
  153487. fts3ReadNextPos(&p2, &i2);
  153488. }else if( i1<i2 ){
  153489. fts3ReadNextPos(&p1, &i1);
  153490. }else{
  153491. fts3ReadNextPos(&p2, &i2);
  153492. }
  153493. }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
  153494. }else if( iCol1<iCol2 ){
  153495. p1 += fts3PutColNumber(&p, iCol1);
  153496. fts3ColumnlistCopy(&p, &p1);
  153497. }else{
  153498. p2 += fts3PutColNumber(&p, iCol2);
  153499. fts3ColumnlistCopy(&p, &p2);
  153500. }
  153501. }
  153502. *p++ = POS_END;
  153503. *pp = p;
  153504. *pp1 = p1 + 1;
  153505. *pp2 = p2 + 1;
  153506. return SQLITE_OK;
  153507. }
  153508. /*
  153509. ** This function is used to merge two position lists into one. When it is
  153510. ** called, *pp1 and *pp2 must both point to position lists. A position-list is
  153511. ** the part of a doclist that follows each document id. For example, if a row
  153512. ** contains:
  153513. **
  153514. ** 'a b c'|'x y z'|'a b b a'
  153515. **
  153516. ** Then the position list for this row for token 'b' would consist of:
  153517. **
  153518. ** 0x02 0x01 0x02 0x03 0x03 0x00
  153519. **
  153520. ** When this function returns, both *pp1 and *pp2 are left pointing to the
  153521. ** byte following the 0x00 terminator of their respective position lists.
  153522. **
  153523. ** If isSaveLeft is 0, an entry is added to the output position list for
  153524. ** each position in *pp2 for which there exists one or more positions in
  153525. ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
  153526. ** when the *pp1 token appears before the *pp2 token, but not more than nToken
  153527. ** slots before it.
  153528. **
  153529. ** e.g. nToken==1 searches for adjacent positions.
  153530. */
  153531. static int fts3PoslistPhraseMerge(
  153532. char **pp, /* IN/OUT: Preallocated output buffer */
  153533. int nToken, /* Maximum difference in token positions */
  153534. int isSaveLeft, /* Save the left position */
  153535. int isExact, /* If *pp1 is exactly nTokens before *pp2 */
  153536. char **pp1, /* IN/OUT: Left input list */
  153537. char **pp2 /* IN/OUT: Right input list */
  153538. ){
  153539. char *p = *pp;
  153540. char *p1 = *pp1;
  153541. char *p2 = *pp2;
  153542. int iCol1 = 0;
  153543. int iCol2 = 0;
  153544. /* Never set both isSaveLeft and isExact for the same invocation. */
  153545. assert( isSaveLeft==0 || isExact==0 );
  153546. assert( p!=0 && *p1!=0 && *p2!=0 );
  153547. if( *p1==POS_COLUMN ){
  153548. p1++;
  153549. p1 += fts3GetVarint32(p1, &iCol1);
  153550. }
  153551. if( *p2==POS_COLUMN ){
  153552. p2++;
  153553. p2 += fts3GetVarint32(p2, &iCol2);
  153554. }
  153555. while( 1 ){
  153556. if( iCol1==iCol2 ){
  153557. char *pSave = p;
  153558. sqlite3_int64 iPrev = 0;
  153559. sqlite3_int64 iPos1 = 0;
  153560. sqlite3_int64 iPos2 = 0;
  153561. if( iCol1 ){
  153562. *p++ = POS_COLUMN;
  153563. p += sqlite3Fts3PutVarint(p, iCol1);
  153564. }
  153565. fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
  153566. fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
  153567. if( iPos1<0 || iPos2<0 ) break;
  153568. while( 1 ){
  153569. if( iPos2==iPos1+nToken
  153570. || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken)
  153571. ){
  153572. sqlite3_int64 iSave;
  153573. iSave = isSaveLeft ? iPos1 : iPos2;
  153574. fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
  153575. pSave = 0;
  153576. assert( p );
  153577. }
  153578. if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
  153579. if( (*p2&0xFE)==0 ) break;
  153580. fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
  153581. }else{
  153582. if( (*p1&0xFE)==0 ) break;
  153583. fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
  153584. }
  153585. }
  153586. if( pSave ){
  153587. assert( pp && p );
  153588. p = pSave;
  153589. }
  153590. fts3ColumnlistCopy(0, &p1);
  153591. fts3ColumnlistCopy(0, &p2);
  153592. assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
  153593. if( 0==*p1 || 0==*p2 ) break;
  153594. p1++;
  153595. p1 += fts3GetVarint32(p1, &iCol1);
  153596. p2++;
  153597. p2 += fts3GetVarint32(p2, &iCol2);
  153598. }
  153599. /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
  153600. ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
  153601. ** end of the position list, or the 0x01 that precedes the next
  153602. ** column-number in the position list.
  153603. */
  153604. else if( iCol1<iCol2 ){
  153605. fts3ColumnlistCopy(0, &p1);
  153606. if( 0==*p1 ) break;
  153607. p1++;
  153608. p1 += fts3GetVarint32(p1, &iCol1);
  153609. }else{
  153610. fts3ColumnlistCopy(0, &p2);
  153611. if( 0==*p2 ) break;
  153612. p2++;
  153613. p2 += fts3GetVarint32(p2, &iCol2);
  153614. }
  153615. }
  153616. fts3PoslistCopy(0, &p2);
  153617. fts3PoslistCopy(0, &p1);
  153618. *pp1 = p1;
  153619. *pp2 = p2;
  153620. if( *pp==p ){
  153621. return 0;
  153622. }
  153623. *p++ = 0x00;
  153624. *pp = p;
  153625. return 1;
  153626. }
  153627. /*
  153628. ** Merge two position-lists as required by the NEAR operator. The argument
  153629. ** position lists correspond to the left and right phrases of an expression
  153630. ** like:
  153631. **
  153632. ** "phrase 1" NEAR "phrase number 2"
  153633. **
  153634. ** Position list *pp1 corresponds to the left-hand side of the NEAR
  153635. ** expression and *pp2 to the right. As usual, the indexes in the position
  153636. ** lists are the offsets of the last token in each phrase (tokens "1" and "2"
  153637. ** in the example above).
  153638. **
  153639. ** The output position list - written to *pp - is a copy of *pp2 with those
  153640. ** entries that are not sufficiently NEAR entries in *pp1 removed.
  153641. */
  153642. static int fts3PoslistNearMerge(
  153643. char **pp, /* Output buffer */
  153644. char *aTmp, /* Temporary buffer space */
  153645. int nRight, /* Maximum difference in token positions */
  153646. int nLeft, /* Maximum difference in token positions */
  153647. char **pp1, /* IN/OUT: Left input list */
  153648. char **pp2 /* IN/OUT: Right input list */
  153649. ){
  153650. char *p1 = *pp1;
  153651. char *p2 = *pp2;
  153652. char *pTmp1 = aTmp;
  153653. char *pTmp2;
  153654. char *aTmp2;
  153655. int res = 1;
  153656. fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
  153657. aTmp2 = pTmp2 = pTmp1;
  153658. *pp1 = p1;
  153659. *pp2 = p2;
  153660. fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
  153661. if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
  153662. fts3PoslistMerge(pp, &aTmp, &aTmp2);
  153663. }else if( pTmp1!=aTmp ){
  153664. fts3PoslistCopy(pp, &aTmp);
  153665. }else if( pTmp2!=aTmp2 ){
  153666. fts3PoslistCopy(pp, &aTmp2);
  153667. }else{
  153668. res = 0;
  153669. }
  153670. return res;
  153671. }
  153672. /*
  153673. ** An instance of this function is used to merge together the (potentially
  153674. ** large number of) doclists for each term that matches a prefix query.
  153675. ** See function fts3TermSelectMerge() for details.
  153676. */
  153677. typedef struct TermSelect TermSelect;
  153678. struct TermSelect {
  153679. char *aaOutput[16]; /* Malloc'd output buffers */
  153680. int anOutput[16]; /* Size each output buffer in bytes */
  153681. };
  153682. /*
  153683. ** This function is used to read a single varint from a buffer. Parameter
  153684. ** pEnd points 1 byte past the end of the buffer. When this function is
  153685. ** called, if *pp points to pEnd or greater, then the end of the buffer
  153686. ** has been reached. In this case *pp is set to 0 and the function returns.
  153687. **
  153688. ** If *pp does not point to or past pEnd, then a single varint is read
  153689. ** from *pp. *pp is then set to point 1 byte past the end of the read varint.
  153690. **
  153691. ** If bDescIdx is false, the value read is added to *pVal before returning.
  153692. ** If it is true, the value read is subtracted from *pVal before this
  153693. ** function returns.
  153694. */
  153695. static void fts3GetDeltaVarint3(
  153696. char **pp, /* IN/OUT: Point to read varint from */
  153697. char *pEnd, /* End of buffer */
  153698. int bDescIdx, /* True if docids are descending */
  153699. sqlite3_int64 *pVal /* IN/OUT: Integer value */
  153700. ){
  153701. if( *pp>=pEnd ){
  153702. *pp = 0;
  153703. }else{
  153704. sqlite3_int64 iVal;
  153705. *pp += sqlite3Fts3GetVarint(*pp, &iVal);
  153706. if( bDescIdx ){
  153707. *pVal -= iVal;
  153708. }else{
  153709. *pVal += iVal;
  153710. }
  153711. }
  153712. }
  153713. /*
  153714. ** This function is used to write a single varint to a buffer. The varint
  153715. ** is written to *pp. Before returning, *pp is set to point 1 byte past the
  153716. ** end of the value written.
  153717. **
  153718. ** If *pbFirst is zero when this function is called, the value written to
  153719. ** the buffer is that of parameter iVal.
  153720. **
  153721. ** If *pbFirst is non-zero when this function is called, then the value
  153722. ** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
  153723. ** (if bDescIdx is non-zero).
  153724. **
  153725. ** Before returning, this function always sets *pbFirst to 1 and *piPrev
  153726. ** to the value of parameter iVal.
  153727. */
  153728. static void fts3PutDeltaVarint3(
  153729. char **pp, /* IN/OUT: Output pointer */
  153730. int bDescIdx, /* True for descending docids */
  153731. sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
  153732. int *pbFirst, /* IN/OUT: True after first int written */
  153733. sqlite3_int64 iVal /* Write this value to the list */
  153734. ){
  153735. sqlite3_int64 iWrite;
  153736. if( bDescIdx==0 || *pbFirst==0 ){
  153737. iWrite = iVal - *piPrev;
  153738. }else{
  153739. iWrite = *piPrev - iVal;
  153740. }
  153741. assert( *pbFirst || *piPrev==0 );
  153742. assert( *pbFirst==0 || iWrite>0 );
  153743. *pp += sqlite3Fts3PutVarint(*pp, iWrite);
  153744. *piPrev = iVal;
  153745. *pbFirst = 1;
  153746. }
  153747. /*
  153748. ** This macro is used by various functions that merge doclists. The two
  153749. ** arguments are 64-bit docid values. If the value of the stack variable
  153750. ** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2).
  153751. ** Otherwise, (i2-i1).
  153752. **
  153753. ** Using this makes it easier to write code that can merge doclists that are
  153754. ** sorted in either ascending or descending order.
  153755. */
  153756. #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
  153757. /*
  153758. ** This function does an "OR" merge of two doclists (output contains all
  153759. ** positions contained in either argument doclist). If the docids in the
  153760. ** input doclists are sorted in ascending order, parameter bDescDoclist
  153761. ** should be false. If they are sorted in ascending order, it should be
  153762. ** passed a non-zero value.
  153763. **
  153764. ** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
  153765. ** containing the output doclist and SQLITE_OK is returned. In this case
  153766. ** *pnOut is set to the number of bytes in the output doclist.
  153767. **
  153768. ** If an error occurs, an SQLite error code is returned. The output values
  153769. ** are undefined in this case.
  153770. */
  153771. static int fts3DoclistOrMerge(
  153772. int bDescDoclist, /* True if arguments are desc */
  153773. char *a1, int n1, /* First doclist */
  153774. char *a2, int n2, /* Second doclist */
  153775. char **paOut, int *pnOut /* OUT: Malloc'd doclist */
  153776. ){
  153777. int rc = SQLITE_OK;
  153778. sqlite3_int64 i1 = 0;
  153779. sqlite3_int64 i2 = 0;
  153780. sqlite3_int64 iPrev = 0;
  153781. char *pEnd1 = &a1[n1];
  153782. char *pEnd2 = &a2[n2];
  153783. char *p1 = a1;
  153784. char *p2 = a2;
  153785. char *p;
  153786. char *aOut;
  153787. int bFirstOut = 0;
  153788. *paOut = 0;
  153789. *pnOut = 0;
  153790. /* Allocate space for the output. Both the input and output doclists
  153791. ** are delta encoded. If they are in ascending order (bDescDoclist==0),
  153792. ** then the first docid in each list is simply encoded as a varint. For
  153793. ** each subsequent docid, the varint stored is the difference between the
  153794. ** current and previous docid (a positive number - since the list is in
  153795. ** ascending order).
  153796. **
  153797. ** The first docid written to the output is therefore encoded using the
  153798. ** same number of bytes as it is in whichever of the input lists it is
  153799. ** read from. And each subsequent docid read from the same input list
  153800. ** consumes either the same or less bytes as it did in the input (since
  153801. ** the difference between it and the previous value in the output must
  153802. ** be a positive value less than or equal to the delta value read from
  153803. ** the input list). The same argument applies to all but the first docid
  153804. ** read from the 'other' list. And to the contents of all position lists
  153805. ** that will be copied and merged from the input to the output.
  153806. **
  153807. ** However, if the first docid copied to the output is a negative number,
  153808. ** then the encoding of the first docid from the 'other' input list may
  153809. ** be larger in the output than it was in the input (since the delta value
  153810. ** may be a larger positive integer than the actual docid).
  153811. **
  153812. ** The space required to store the output is therefore the sum of the
  153813. ** sizes of the two inputs, plus enough space for exactly one of the input
  153814. ** docids to grow.
  153815. **
  153816. ** A symetric argument may be made if the doclists are in descending
  153817. ** order.
  153818. */
  153819. aOut = sqlite3_malloc64((i64)n1+n2+FTS3_VARINT_MAX-1+FTS3_BUFFER_PADDING);
  153820. if( !aOut ) return SQLITE_NOMEM;
  153821. p = aOut;
  153822. fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
  153823. fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
  153824. while( p1 || p2 ){
  153825. sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
  153826. if( p2 && p1 && iDiff==0 ){
  153827. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  153828. rc = fts3PoslistMerge(&p, &p1, &p2);
  153829. if( rc ) break;
  153830. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  153831. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  153832. }else if( !p2 || (p1 && iDiff<0) ){
  153833. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  153834. fts3PoslistCopy(&p, &p1);
  153835. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  153836. }else{
  153837. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
  153838. fts3PoslistCopy(&p, &p2);
  153839. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  153840. }
  153841. }
  153842. if( rc!=SQLITE_OK ){
  153843. sqlite3_free(aOut);
  153844. p = aOut = 0;
  153845. }else{
  153846. assert( (p-aOut)<=n1+n2+FTS3_VARINT_MAX-1 );
  153847. memset(&aOut[(p-aOut)], 0, FTS3_BUFFER_PADDING);
  153848. }
  153849. *paOut = aOut;
  153850. *pnOut = (int)(p-aOut);
  153851. return rc;
  153852. }
  153853. /*
  153854. ** This function does a "phrase" merge of two doclists. In a phrase merge,
  153855. ** the output contains a copy of each position from the right-hand input
  153856. ** doclist for which there is a position in the left-hand input doclist
  153857. ** exactly nDist tokens before it.
  153858. **
  153859. ** If the docids in the input doclists are sorted in ascending order,
  153860. ** parameter bDescDoclist should be false. If they are sorted in ascending
  153861. ** order, it should be passed a non-zero value.
  153862. **
  153863. ** The right-hand input doclist is overwritten by this function.
  153864. */
  153865. static int fts3DoclistPhraseMerge(
  153866. int bDescDoclist, /* True if arguments are desc */
  153867. int nDist, /* Distance from left to right (1=adjacent) */
  153868. char *aLeft, int nLeft, /* Left doclist */
  153869. char **paRight, int *pnRight /* IN/OUT: Right/output doclist */
  153870. ){
  153871. sqlite3_int64 i1 = 0;
  153872. sqlite3_int64 i2 = 0;
  153873. sqlite3_int64 iPrev = 0;
  153874. char *aRight = *paRight;
  153875. char *pEnd1 = &aLeft[nLeft];
  153876. char *pEnd2 = &aRight[*pnRight];
  153877. char *p1 = aLeft;
  153878. char *p2 = aRight;
  153879. char *p;
  153880. int bFirstOut = 0;
  153881. char *aOut;
  153882. assert( nDist>0 );
  153883. if( bDescDoclist ){
  153884. aOut = sqlite3_malloc64((sqlite3_int64)*pnRight + FTS3_VARINT_MAX);
  153885. if( aOut==0 ) return SQLITE_NOMEM;
  153886. }else{
  153887. aOut = aRight;
  153888. }
  153889. p = aOut;
  153890. fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
  153891. fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
  153892. while( p1 && p2 ){
  153893. sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
  153894. if( iDiff==0 ){
  153895. char *pSave = p;
  153896. sqlite3_int64 iPrevSave = iPrev;
  153897. int bFirstOutSave = bFirstOut;
  153898. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  153899. if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
  153900. p = pSave;
  153901. iPrev = iPrevSave;
  153902. bFirstOut = bFirstOutSave;
  153903. }
  153904. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  153905. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  153906. }else if( iDiff<0 ){
  153907. fts3PoslistCopy(0, &p1);
  153908. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  153909. }else{
  153910. fts3PoslistCopy(0, &p2);
  153911. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  153912. }
  153913. }
  153914. *pnRight = (int)(p - aOut);
  153915. if( bDescDoclist ){
  153916. sqlite3_free(aRight);
  153917. *paRight = aOut;
  153918. }
  153919. return SQLITE_OK;
  153920. }
  153921. /*
  153922. ** Argument pList points to a position list nList bytes in size. This
  153923. ** function checks to see if the position list contains any entries for
  153924. ** a token in position 0 (of any column). If so, it writes argument iDelta
  153925. ** to the output buffer pOut, followed by a position list consisting only
  153926. ** of the entries from pList at position 0, and terminated by an 0x00 byte.
  153927. ** The value returned is the number of bytes written to pOut (if any).
  153928. */
  153929. SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
  153930. sqlite3_int64 iDelta, /* Varint that may be written to pOut */
  153931. char *pList, /* Position list (no 0x00 term) */
  153932. int nList, /* Size of pList in bytes */
  153933. char *pOut /* Write output here */
  153934. ){
  153935. int nOut = 0;
  153936. int bWritten = 0; /* True once iDelta has been written */
  153937. char *p = pList;
  153938. char *pEnd = &pList[nList];
  153939. if( *p!=0x01 ){
  153940. if( *p==0x02 ){
  153941. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
  153942. pOut[nOut++] = 0x02;
  153943. bWritten = 1;
  153944. }
  153945. fts3ColumnlistCopy(0, &p);
  153946. }
  153947. while( p<pEnd ){
  153948. sqlite3_int64 iCol;
  153949. p++;
  153950. p += sqlite3Fts3GetVarint(p, &iCol);
  153951. if( *p==0x02 ){
  153952. if( bWritten==0 ){
  153953. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
  153954. bWritten = 1;
  153955. }
  153956. pOut[nOut++] = 0x01;
  153957. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
  153958. pOut[nOut++] = 0x02;
  153959. }
  153960. fts3ColumnlistCopy(0, &p);
  153961. }
  153962. if( bWritten ){
  153963. pOut[nOut++] = 0x00;
  153964. }
  153965. return nOut;
  153966. }
  153967. /*
  153968. ** Merge all doclists in the TermSelect.aaOutput[] array into a single
  153969. ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
  153970. ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
  153971. **
  153972. ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
  153973. ** the responsibility of the caller to free any doclists left in the
  153974. ** TermSelect.aaOutput[] array.
  153975. */
  153976. static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
  153977. char *aOut = 0;
  153978. int nOut = 0;
  153979. int i;
  153980. /* Loop through the doclists in the aaOutput[] array. Merge them all
  153981. ** into a single doclist.
  153982. */
  153983. for(i=0; i<SizeofArray(pTS->aaOutput); i++){
  153984. if( pTS->aaOutput[i] ){
  153985. if( !aOut ){
  153986. aOut = pTS->aaOutput[i];
  153987. nOut = pTS->anOutput[i];
  153988. pTS->aaOutput[i] = 0;
  153989. }else{
  153990. int nNew;
  153991. char *aNew;
  153992. int rc = fts3DoclistOrMerge(p->bDescIdx,
  153993. pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
  153994. );
  153995. if( rc!=SQLITE_OK ){
  153996. sqlite3_free(aOut);
  153997. return rc;
  153998. }
  153999. sqlite3_free(pTS->aaOutput[i]);
  154000. sqlite3_free(aOut);
  154001. pTS->aaOutput[i] = 0;
  154002. aOut = aNew;
  154003. nOut = nNew;
  154004. }
  154005. }
  154006. }
  154007. pTS->aaOutput[0] = aOut;
  154008. pTS->anOutput[0] = nOut;
  154009. return SQLITE_OK;
  154010. }
  154011. /*
  154012. ** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
  154013. ** as the first argument. The merge is an "OR" merge (see function
  154014. ** fts3DoclistOrMerge() for details).
  154015. **
  154016. ** This function is called with the doclist for each term that matches
  154017. ** a queried prefix. It merges all these doclists into one, the doclist
  154018. ** for the specified prefix. Since there can be a very large number of
  154019. ** doclists to merge, the merging is done pair-wise using the TermSelect
  154020. ** object.
  154021. **
  154022. ** This function returns SQLITE_OK if the merge is successful, or an
  154023. ** SQLite error code (SQLITE_NOMEM) if an error occurs.
  154024. */
  154025. static int fts3TermSelectMerge(
  154026. Fts3Table *p, /* FTS table handle */
  154027. TermSelect *pTS, /* TermSelect object to merge into */
  154028. char *aDoclist, /* Pointer to doclist */
  154029. int nDoclist /* Size of aDoclist in bytes */
  154030. ){
  154031. if( pTS->aaOutput[0]==0 ){
  154032. /* If this is the first term selected, copy the doclist to the output
  154033. ** buffer using memcpy().
  154034. **
  154035. ** Add FTS3_VARINT_MAX bytes of unused space to the end of the
  154036. ** allocation. This is so as to ensure that the buffer is big enough
  154037. ** to hold the current doclist AND'd with any other doclist. If the
  154038. ** doclists are stored in order=ASC order, this padding would not be
  154039. ** required (since the size of [doclistA AND doclistB] is always less
  154040. ** than or equal to the size of [doclistA] in that case). But this is
  154041. ** not true for order=DESC. For example, a doclist containing (1, -1)
  154042. ** may be smaller than (-1), as in the first example the -1 may be stored
  154043. ** as a single-byte delta, whereas in the second it must be stored as a
  154044. ** FTS3_VARINT_MAX byte varint.
  154045. **
  154046. ** Similar padding is added in the fts3DoclistOrMerge() function.
  154047. */
  154048. pTS->aaOutput[0] = sqlite3_malloc(nDoclist + FTS3_VARINT_MAX + 1);
  154049. pTS->anOutput[0] = nDoclist;
  154050. if( pTS->aaOutput[0] ){
  154051. memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
  154052. memset(&pTS->aaOutput[0][nDoclist], 0, FTS3_VARINT_MAX);
  154053. }else{
  154054. return SQLITE_NOMEM;
  154055. }
  154056. }else{
  154057. char *aMerge = aDoclist;
  154058. int nMerge = nDoclist;
  154059. int iOut;
  154060. for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
  154061. if( pTS->aaOutput[iOut]==0 ){
  154062. assert( iOut>0 );
  154063. pTS->aaOutput[iOut] = aMerge;
  154064. pTS->anOutput[iOut] = nMerge;
  154065. break;
  154066. }else{
  154067. char *aNew;
  154068. int nNew;
  154069. int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge,
  154070. pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
  154071. );
  154072. if( rc!=SQLITE_OK ){
  154073. if( aMerge!=aDoclist ) sqlite3_free(aMerge);
  154074. return rc;
  154075. }
  154076. if( aMerge!=aDoclist ) sqlite3_free(aMerge);
  154077. sqlite3_free(pTS->aaOutput[iOut]);
  154078. pTS->aaOutput[iOut] = 0;
  154079. aMerge = aNew;
  154080. nMerge = nNew;
  154081. if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
  154082. pTS->aaOutput[iOut] = aMerge;
  154083. pTS->anOutput[iOut] = nMerge;
  154084. }
  154085. }
  154086. }
  154087. }
  154088. return SQLITE_OK;
  154089. }
  154090. /*
  154091. ** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
  154092. */
  154093. static int fts3SegReaderCursorAppend(
  154094. Fts3MultiSegReader *pCsr,
  154095. Fts3SegReader *pNew
  154096. ){
  154097. if( (pCsr->nSegment%16)==0 ){
  154098. Fts3SegReader **apNew;
  154099. sqlite3_int64 nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
  154100. apNew = (Fts3SegReader **)sqlite3_realloc64(pCsr->apSegment, nByte);
  154101. if( !apNew ){
  154102. sqlite3Fts3SegReaderFree(pNew);
  154103. return SQLITE_NOMEM;
  154104. }
  154105. pCsr->apSegment = apNew;
  154106. }
  154107. pCsr->apSegment[pCsr->nSegment++] = pNew;
  154108. return SQLITE_OK;
  154109. }
  154110. /*
  154111. ** Add seg-reader objects to the Fts3MultiSegReader object passed as the
  154112. ** 8th argument.
  154113. **
  154114. ** This function returns SQLITE_OK if successful, or an SQLite error code
  154115. ** otherwise.
  154116. */
  154117. static int fts3SegReaderCursor(
  154118. Fts3Table *p, /* FTS3 table handle */
  154119. int iLangid, /* Language id */
  154120. int iIndex, /* Index to search (from 0 to p->nIndex-1) */
  154121. int iLevel, /* Level of segments to scan */
  154122. const char *zTerm, /* Term to query for */
  154123. int nTerm, /* Size of zTerm in bytes */
  154124. int isPrefix, /* True for a prefix search */
  154125. int isScan, /* True to scan from zTerm to EOF */
  154126. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  154127. ){
  154128. int rc = SQLITE_OK; /* Error code */
  154129. sqlite3_stmt *pStmt = 0; /* Statement to iterate through segments */
  154130. int rc2; /* Result of sqlite3_reset() */
  154131. /* If iLevel is less than 0 and this is not a scan, include a seg-reader
  154132. ** for the pending-terms. If this is a scan, then this call must be being
  154133. ** made by an fts4aux module, not an FTS table. In this case calling
  154134. ** Fts3SegReaderPending might segfault, as the data structures used by
  154135. ** fts4aux are not completely populated. So it's easiest to filter these
  154136. ** calls out here. */
  154137. if( iLevel<0 && p->aIndex ){
  154138. Fts3SegReader *pSeg = 0;
  154139. rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix||isScan, &pSeg);
  154140. if( rc==SQLITE_OK && pSeg ){
  154141. rc = fts3SegReaderCursorAppend(pCsr, pSeg);
  154142. }
  154143. }
  154144. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  154145. if( rc==SQLITE_OK ){
  154146. rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
  154147. }
  154148. while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
  154149. Fts3SegReader *pSeg = 0;
  154150. /* Read the values returned by the SELECT into local variables. */
  154151. sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
  154152. sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
  154153. sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
  154154. int nRoot = sqlite3_column_bytes(pStmt, 4);
  154155. char const *zRoot = sqlite3_column_blob(pStmt, 4);
  154156. /* If zTerm is not NULL, and this segment is not stored entirely on its
  154157. ** root node, the range of leaves scanned can be reduced. Do this. */
  154158. if( iStartBlock && zTerm && zRoot ){
  154159. sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
  154160. rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
  154161. if( rc!=SQLITE_OK ) goto finished;
  154162. if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
  154163. }
  154164. rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1,
  154165. (isPrefix==0 && isScan==0),
  154166. iStartBlock, iLeavesEndBlock,
  154167. iEndBlock, zRoot, nRoot, &pSeg
  154168. );
  154169. if( rc!=SQLITE_OK ) goto finished;
  154170. rc = fts3SegReaderCursorAppend(pCsr, pSeg);
  154171. }
  154172. }
  154173. finished:
  154174. rc2 = sqlite3_reset(pStmt);
  154175. if( rc==SQLITE_DONE ) rc = rc2;
  154176. return rc;
  154177. }
  154178. /*
  154179. ** Set up a cursor object for iterating through a full-text index or a
  154180. ** single level therein.
  154181. */
  154182. SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
  154183. Fts3Table *p, /* FTS3 table handle */
  154184. int iLangid, /* Language-id to search */
  154185. int iIndex, /* Index to search (from 0 to p->nIndex-1) */
  154186. int iLevel, /* Level of segments to scan */
  154187. const char *zTerm, /* Term to query for */
  154188. int nTerm, /* Size of zTerm in bytes */
  154189. int isPrefix, /* True for a prefix search */
  154190. int isScan, /* True to scan from zTerm to EOF */
  154191. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  154192. ){
  154193. assert( iIndex>=0 && iIndex<p->nIndex );
  154194. assert( iLevel==FTS3_SEGCURSOR_ALL
  154195. || iLevel==FTS3_SEGCURSOR_PENDING
  154196. || iLevel>=0
  154197. );
  154198. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  154199. assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
  154200. assert( isPrefix==0 || isScan==0 );
  154201. memset(pCsr, 0, sizeof(Fts3MultiSegReader));
  154202. return fts3SegReaderCursor(
  154203. p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
  154204. );
  154205. }
  154206. /*
  154207. ** In addition to its current configuration, have the Fts3MultiSegReader
  154208. ** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
  154209. **
  154210. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  154211. */
  154212. static int fts3SegReaderCursorAddZero(
  154213. Fts3Table *p, /* FTS virtual table handle */
  154214. int iLangid,
  154215. const char *zTerm, /* Term to scan doclist of */
  154216. int nTerm, /* Number of bytes in zTerm */
  154217. Fts3MultiSegReader *pCsr /* Fts3MultiSegReader to modify */
  154218. ){
  154219. return fts3SegReaderCursor(p,
  154220. iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
  154221. );
  154222. }
  154223. /*
  154224. ** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
  154225. ** if isPrefix is true, to scan the doclist for all terms for which
  154226. ** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
  154227. ** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
  154228. ** an SQLite error code.
  154229. **
  154230. ** It is the responsibility of the caller to free this object by eventually
  154231. ** passing it to fts3SegReaderCursorFree()
  154232. **
  154233. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  154234. ** Output parameter *ppSegcsr is set to 0 if an error occurs.
  154235. */
  154236. static int fts3TermSegReaderCursor(
  154237. Fts3Cursor *pCsr, /* Virtual table cursor handle */
  154238. const char *zTerm, /* Term to query for */
  154239. int nTerm, /* Size of zTerm in bytes */
  154240. int isPrefix, /* True for a prefix search */
  154241. Fts3MultiSegReader **ppSegcsr /* OUT: Allocated seg-reader cursor */
  154242. ){
  154243. Fts3MultiSegReader *pSegcsr; /* Object to allocate and return */
  154244. int rc = SQLITE_NOMEM; /* Return code */
  154245. pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
  154246. if( pSegcsr ){
  154247. int i;
  154248. int bFound = 0; /* True once an index has been found */
  154249. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  154250. if( isPrefix ){
  154251. for(i=1; bFound==0 && i<p->nIndex; i++){
  154252. if( p->aIndex[i].nPrefix==nTerm ){
  154253. bFound = 1;
  154254. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  154255. i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
  154256. );
  154257. pSegcsr->bLookup = 1;
  154258. }
  154259. }
  154260. for(i=1; bFound==0 && i<p->nIndex; i++){
  154261. if( p->aIndex[i].nPrefix==nTerm+1 ){
  154262. bFound = 1;
  154263. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  154264. i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
  154265. );
  154266. if( rc==SQLITE_OK ){
  154267. rc = fts3SegReaderCursorAddZero(
  154268. p, pCsr->iLangid, zTerm, nTerm, pSegcsr
  154269. );
  154270. }
  154271. }
  154272. }
  154273. }
  154274. if( bFound==0 ){
  154275. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  154276. 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
  154277. );
  154278. pSegcsr->bLookup = !isPrefix;
  154279. }
  154280. }
  154281. *ppSegcsr = pSegcsr;
  154282. return rc;
  154283. }
  154284. /*
  154285. ** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
  154286. */
  154287. static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
  154288. sqlite3Fts3SegReaderFinish(pSegcsr);
  154289. sqlite3_free(pSegcsr);
  154290. }
  154291. /*
  154292. ** This function retrieves the doclist for the specified term (or term
  154293. ** prefix) from the database.
  154294. */
  154295. static int fts3TermSelect(
  154296. Fts3Table *p, /* Virtual table handle */
  154297. Fts3PhraseToken *pTok, /* Token to query for */
  154298. int iColumn, /* Column to query (or -ve for all columns) */
  154299. int *pnOut, /* OUT: Size of buffer at *ppOut */
  154300. char **ppOut /* OUT: Malloced result buffer */
  154301. ){
  154302. int rc; /* Return code */
  154303. Fts3MultiSegReader *pSegcsr; /* Seg-reader cursor for this term */
  154304. TermSelect tsc; /* Object for pair-wise doclist merging */
  154305. Fts3SegFilter filter; /* Segment term filter configuration */
  154306. pSegcsr = pTok->pSegcsr;
  154307. memset(&tsc, 0, sizeof(TermSelect));
  154308. filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
  154309. | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
  154310. | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
  154311. | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
  154312. filter.iCol = iColumn;
  154313. filter.zTerm = pTok->z;
  154314. filter.nTerm = pTok->n;
  154315. rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
  154316. while( SQLITE_OK==rc
  154317. && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr))
  154318. ){
  154319. rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
  154320. }
  154321. if( rc==SQLITE_OK ){
  154322. rc = fts3TermSelectFinishMerge(p, &tsc);
  154323. }
  154324. if( rc==SQLITE_OK ){
  154325. *ppOut = tsc.aaOutput[0];
  154326. *pnOut = tsc.anOutput[0];
  154327. }else{
  154328. int i;
  154329. for(i=0; i<SizeofArray(tsc.aaOutput); i++){
  154330. sqlite3_free(tsc.aaOutput[i]);
  154331. }
  154332. }
  154333. fts3SegReaderCursorFree(pSegcsr);
  154334. pTok->pSegcsr = 0;
  154335. return rc;
  154336. }
  154337. /*
  154338. ** This function counts the total number of docids in the doclist stored
  154339. ** in buffer aList[], size nList bytes.
  154340. **
  154341. ** If the isPoslist argument is true, then it is assumed that the doclist
  154342. ** contains a position-list following each docid. Otherwise, it is assumed
  154343. ** that the doclist is simply a list of docids stored as delta encoded
  154344. ** varints.
  154345. */
  154346. static int fts3DoclistCountDocids(char *aList, int nList){
  154347. int nDoc = 0; /* Return value */
  154348. if( aList ){
  154349. char *aEnd = &aList[nList]; /* Pointer to one byte after EOF */
  154350. char *p = aList; /* Cursor */
  154351. while( p<aEnd ){
  154352. nDoc++;
  154353. while( (*p++)&0x80 ); /* Skip docid varint */
  154354. fts3PoslistCopy(0, &p); /* Skip over position list */
  154355. }
  154356. }
  154357. return nDoc;
  154358. }
  154359. /*
  154360. ** Advance the cursor to the next row in the %_content table that
  154361. ** matches the search criteria. For a MATCH search, this will be
  154362. ** the next row that matches. For a full-table scan, this will be
  154363. ** simply the next row in the %_content table. For a docid lookup,
  154364. ** this routine simply sets the EOF flag.
  154365. **
  154366. ** Return SQLITE_OK if nothing goes wrong. SQLITE_OK is returned
  154367. ** even if we reach end-of-file. The fts3EofMethod() will be called
  154368. ** subsequently to determine whether or not an EOF was hit.
  154369. */
  154370. static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
  154371. int rc;
  154372. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  154373. if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
  154374. if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
  154375. pCsr->isEof = 1;
  154376. rc = sqlite3_reset(pCsr->pStmt);
  154377. }else{
  154378. pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
  154379. rc = SQLITE_OK;
  154380. }
  154381. }else{
  154382. rc = fts3EvalNext((Fts3Cursor *)pCursor);
  154383. }
  154384. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  154385. return rc;
  154386. }
  154387. /*
  154388. ** The following are copied from sqliteInt.h.
  154389. **
  154390. ** Constants for the largest and smallest possible 64-bit signed integers.
  154391. ** These macros are designed to work correctly on both 32-bit and 64-bit
  154392. ** compilers.
  154393. */
  154394. #ifndef SQLITE_AMALGAMATION
  154395. # define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
  154396. # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
  154397. #endif
  154398. /*
  154399. ** If the numeric type of argument pVal is "integer", then return it
  154400. ** converted to a 64-bit signed integer. Otherwise, return a copy of
  154401. ** the second parameter, iDefault.
  154402. */
  154403. static sqlite3_int64 fts3DocidRange(sqlite3_value *pVal, i64 iDefault){
  154404. if( pVal ){
  154405. int eType = sqlite3_value_numeric_type(pVal);
  154406. if( eType==SQLITE_INTEGER ){
  154407. return sqlite3_value_int64(pVal);
  154408. }
  154409. }
  154410. return iDefault;
  154411. }
  154412. /*
  154413. ** This is the xFilter interface for the virtual table. See
  154414. ** the virtual table xFilter method documentation for additional
  154415. ** information.
  154416. **
  154417. ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
  154418. ** the %_content table.
  154419. **
  154420. ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
  154421. ** in the %_content table.
  154422. **
  154423. ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index. The
  154424. ** column on the left-hand side of the MATCH operator is column
  154425. ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed. argv[0] is the right-hand
  154426. ** side of the MATCH operator.
  154427. */
  154428. static int fts3FilterMethod(
  154429. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  154430. int idxNum, /* Strategy index */
  154431. const char *idxStr, /* Unused */
  154432. int nVal, /* Number of elements in apVal */
  154433. sqlite3_value **apVal /* Arguments for the indexing scheme */
  154434. ){
  154435. int rc = SQLITE_OK;
  154436. char *zSql; /* SQL statement used to access %_content */
  154437. int eSearch;
  154438. Fts3Table *p = (Fts3Table *)pCursor->pVtab;
  154439. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  154440. sqlite3_value *pCons = 0; /* The MATCH or rowid constraint, if any */
  154441. sqlite3_value *pLangid = 0; /* The "langid = ?" constraint, if any */
  154442. sqlite3_value *pDocidGe = 0; /* The "docid >= ?" constraint, if any */
  154443. sqlite3_value *pDocidLe = 0; /* The "docid <= ?" constraint, if any */
  154444. int iIdx;
  154445. UNUSED_PARAMETER(idxStr);
  154446. UNUSED_PARAMETER(nVal);
  154447. eSearch = (idxNum & 0x0000FFFF);
  154448. assert( eSearch>=0 && eSearch<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
  154449. assert( p->pSegments==0 );
  154450. /* Collect arguments into local variables */
  154451. iIdx = 0;
  154452. if( eSearch!=FTS3_FULLSCAN_SEARCH ) pCons = apVal[iIdx++];
  154453. if( idxNum & FTS3_HAVE_LANGID ) pLangid = apVal[iIdx++];
  154454. if( idxNum & FTS3_HAVE_DOCID_GE ) pDocidGe = apVal[iIdx++];
  154455. if( idxNum & FTS3_HAVE_DOCID_LE ) pDocidLe = apVal[iIdx++];
  154456. assert( iIdx==nVal );
  154457. /* In case the cursor has been used before, clear it now. */
  154458. fts3ClearCursor(pCsr);
  154459. /* Set the lower and upper bounds on docids to return */
  154460. pCsr->iMinDocid = fts3DocidRange(pDocidGe, SMALLEST_INT64);
  154461. pCsr->iMaxDocid = fts3DocidRange(pDocidLe, LARGEST_INT64);
  154462. if( idxStr ){
  154463. pCsr->bDesc = (idxStr[0]=='D');
  154464. }else{
  154465. pCsr->bDesc = p->bDescIdx;
  154466. }
  154467. pCsr->eSearch = (i16)eSearch;
  154468. if( eSearch!=FTS3_DOCID_SEARCH && eSearch!=FTS3_FULLSCAN_SEARCH ){
  154469. int iCol = eSearch-FTS3_FULLTEXT_SEARCH;
  154470. const char *zQuery = (const char *)sqlite3_value_text(pCons);
  154471. if( zQuery==0 && sqlite3_value_type(pCons)!=SQLITE_NULL ){
  154472. return SQLITE_NOMEM;
  154473. }
  154474. pCsr->iLangid = 0;
  154475. if( pLangid ) pCsr->iLangid = sqlite3_value_int(pLangid);
  154476. assert( p->base.zErrMsg==0 );
  154477. rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
  154478. p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr,
  154479. &p->base.zErrMsg
  154480. );
  154481. if( rc!=SQLITE_OK ){
  154482. return rc;
  154483. }
  154484. rc = fts3EvalStart(pCsr);
  154485. sqlite3Fts3SegmentsClose(p);
  154486. if( rc!=SQLITE_OK ) return rc;
  154487. pCsr->pNextId = pCsr->aDoclist;
  154488. pCsr->iPrevId = 0;
  154489. }
  154490. /* Compile a SELECT statement for this cursor. For a full-table-scan, the
  154491. ** statement loops through all rows of the %_content table. For a
  154492. ** full-text query or docid lookup, the statement retrieves a single
  154493. ** row by docid.
  154494. */
  154495. if( eSearch==FTS3_FULLSCAN_SEARCH ){
  154496. if( pDocidGe || pDocidLe ){
  154497. zSql = sqlite3_mprintf(
  154498. "SELECT %s WHERE rowid BETWEEN %lld AND %lld ORDER BY rowid %s",
  154499. p->zReadExprlist, pCsr->iMinDocid, pCsr->iMaxDocid,
  154500. (pCsr->bDesc ? "DESC" : "ASC")
  154501. );
  154502. }else{
  154503. zSql = sqlite3_mprintf("SELECT %s ORDER BY rowid %s",
  154504. p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
  154505. );
  154506. }
  154507. if( zSql ){
  154508. rc = sqlite3_prepare_v3(p->db,zSql,-1,SQLITE_PREPARE_PERSISTENT,&pCsr->pStmt,0);
  154509. sqlite3_free(zSql);
  154510. }else{
  154511. rc = SQLITE_NOMEM;
  154512. }
  154513. }else if( eSearch==FTS3_DOCID_SEARCH ){
  154514. rc = fts3CursorSeekStmt(pCsr);
  154515. if( rc==SQLITE_OK ){
  154516. rc = sqlite3_bind_value(pCsr->pStmt, 1, pCons);
  154517. }
  154518. }
  154519. if( rc!=SQLITE_OK ) return rc;
  154520. return fts3NextMethod(pCursor);
  154521. }
  154522. /*
  154523. ** This is the xEof method of the virtual table. SQLite calls this
  154524. ** routine to find out if it has reached the end of a result set.
  154525. */
  154526. static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
  154527. Fts3Cursor *pCsr = (Fts3Cursor*)pCursor;
  154528. if( pCsr->isEof ){
  154529. fts3ClearCursor(pCsr);
  154530. pCsr->isEof = 1;
  154531. }
  154532. return pCsr->isEof;
  154533. }
  154534. /*
  154535. ** This is the xRowid method. The SQLite core calls this routine to
  154536. ** retrieve the rowid for the current row of the result set. fts3
  154537. ** exposes %_content.docid as the rowid for the virtual table. The
  154538. ** rowid should be written to *pRowid.
  154539. */
  154540. static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  154541. Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
  154542. *pRowid = pCsr->iPrevId;
  154543. return SQLITE_OK;
  154544. }
  154545. /*
  154546. ** This is the xColumn method, called by SQLite to request a value from
  154547. ** the row that the supplied cursor currently points to.
  154548. **
  154549. ** If:
  154550. **
  154551. ** (iCol < p->nColumn) -> The value of the iCol'th user column.
  154552. ** (iCol == p->nColumn) -> Magic column with the same name as the table.
  154553. ** (iCol == p->nColumn+1) -> Docid column
  154554. ** (iCol == p->nColumn+2) -> Langid column
  154555. */
  154556. static int fts3ColumnMethod(
  154557. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  154558. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  154559. int iCol /* Index of column to read value from */
  154560. ){
  154561. int rc = SQLITE_OK; /* Return Code */
  154562. Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
  154563. Fts3Table *p = (Fts3Table *)pCursor->pVtab;
  154564. /* The column value supplied by SQLite must be in range. */
  154565. assert( iCol>=0 && iCol<=p->nColumn+2 );
  154566. switch( iCol-p->nColumn ){
  154567. case 0:
  154568. /* The special 'table-name' column */
  154569. sqlite3_result_pointer(pCtx, pCsr, "fts3cursor", 0);
  154570. break;
  154571. case 1:
  154572. /* The docid column */
  154573. sqlite3_result_int64(pCtx, pCsr->iPrevId);
  154574. break;
  154575. case 2:
  154576. if( pCsr->pExpr ){
  154577. sqlite3_result_int64(pCtx, pCsr->iLangid);
  154578. break;
  154579. }else if( p->zLanguageid==0 ){
  154580. sqlite3_result_int(pCtx, 0);
  154581. break;
  154582. }else{
  154583. iCol = p->nColumn;
  154584. /* fall-through */
  154585. }
  154586. default:
  154587. /* A user column. Or, if this is a full-table scan, possibly the
  154588. ** language-id column. Seek the cursor. */
  154589. rc = fts3CursorSeek(0, pCsr);
  154590. if( rc==SQLITE_OK && sqlite3_data_count(pCsr->pStmt)-1>iCol ){
  154591. sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
  154592. }
  154593. break;
  154594. }
  154595. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  154596. return rc;
  154597. }
  154598. /*
  154599. ** This function is the implementation of the xUpdate callback used by
  154600. ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
  154601. ** inserted, updated or deleted.
  154602. */
  154603. static int fts3UpdateMethod(
  154604. sqlite3_vtab *pVtab, /* Virtual table handle */
  154605. int nArg, /* Size of argument array */
  154606. sqlite3_value **apVal, /* Array of arguments */
  154607. sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
  154608. ){
  154609. return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
  154610. }
  154611. /*
  154612. ** Implementation of xSync() method. Flush the contents of the pending-terms
  154613. ** hash-table to the database.
  154614. */
  154615. static int fts3SyncMethod(sqlite3_vtab *pVtab){
  154616. /* Following an incremental-merge operation, assuming that the input
  154617. ** segments are not completely consumed (the usual case), they are updated
  154618. ** in place to remove the entries that have already been merged. This
  154619. ** involves updating the leaf block that contains the smallest unmerged
  154620. ** entry and each block (if any) between the leaf and the root node. So
  154621. ** if the height of the input segment b-trees is N, and input segments
  154622. ** are merged eight at a time, updating the input segments at the end
  154623. ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
  154624. ** small - often between 0 and 2. So the overhead of the incremental
  154625. ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
  154626. ** dwarfing the actual productive work accomplished, the incremental merge
  154627. ** is only attempted if it will write at least 64 leaf blocks. Hence
  154628. ** nMinMerge.
  154629. **
  154630. ** Of course, updating the input segments also involves deleting a bunch
  154631. ** of blocks from the segments table. But this is not considered overhead
  154632. ** as it would also be required by a crisis-merge that used the same input
  154633. ** segments.
  154634. */
  154635. const u32 nMinMerge = 64; /* Minimum amount of incr-merge work to do */
  154636. Fts3Table *p = (Fts3Table*)pVtab;
  154637. int rc;
  154638. i64 iLastRowid = sqlite3_last_insert_rowid(p->db);
  154639. rc = sqlite3Fts3PendingTermsFlush(p);
  154640. if( rc==SQLITE_OK
  154641. && p->nLeafAdd>(nMinMerge/16)
  154642. && p->nAutoincrmerge && p->nAutoincrmerge!=0xff
  154643. ){
  154644. int mxLevel = 0; /* Maximum relative level value in db */
  154645. int A; /* Incr-merge parameter A */
  154646. rc = sqlite3Fts3MaxLevel(p, &mxLevel);
  154647. assert( rc==SQLITE_OK || mxLevel==0 );
  154648. A = p->nLeafAdd * mxLevel;
  154649. A += (A/2);
  154650. if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, p->nAutoincrmerge);
  154651. }
  154652. sqlite3Fts3SegmentsClose(p);
  154653. sqlite3_set_last_insert_rowid(p->db, iLastRowid);
  154654. return rc;
  154655. }
  154656. /*
  154657. ** If it is currently unknown whether or not the FTS table has an %_stat
  154658. ** table (if p->bHasStat==2), attempt to determine this (set p->bHasStat
  154659. ** to 0 or 1). Return SQLITE_OK if successful, or an SQLite error code
  154660. ** if an error occurs.
  154661. */
  154662. static int fts3SetHasStat(Fts3Table *p){
  154663. int rc = SQLITE_OK;
  154664. if( p->bHasStat==2 ){
  154665. char *zTbl = sqlite3_mprintf("%s_stat", p->zName);
  154666. if( zTbl ){
  154667. int res = sqlite3_table_column_metadata(p->db, p->zDb, zTbl, 0,0,0,0,0,0);
  154668. sqlite3_free(zTbl);
  154669. p->bHasStat = (res==SQLITE_OK);
  154670. }else{
  154671. rc = SQLITE_NOMEM;
  154672. }
  154673. }
  154674. return rc;
  154675. }
  154676. /*
  154677. ** Implementation of xBegin() method.
  154678. */
  154679. static int fts3BeginMethod(sqlite3_vtab *pVtab){
  154680. Fts3Table *p = (Fts3Table*)pVtab;
  154681. UNUSED_PARAMETER(pVtab);
  154682. assert( p->pSegments==0 );
  154683. assert( p->nPendingData==0 );
  154684. assert( p->inTransaction!=1 );
  154685. TESTONLY( p->inTransaction = 1 );
  154686. TESTONLY( p->mxSavepoint = -1; );
  154687. p->nLeafAdd = 0;
  154688. return fts3SetHasStat(p);
  154689. }
  154690. /*
  154691. ** Implementation of xCommit() method. This is a no-op. The contents of
  154692. ** the pending-terms hash-table have already been flushed into the database
  154693. ** by fts3SyncMethod().
  154694. */
  154695. static int fts3CommitMethod(sqlite3_vtab *pVtab){
  154696. TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
  154697. UNUSED_PARAMETER(pVtab);
  154698. assert( p->nPendingData==0 );
  154699. assert( p->inTransaction!=0 );
  154700. assert( p->pSegments==0 );
  154701. TESTONLY( p->inTransaction = 0 );
  154702. TESTONLY( p->mxSavepoint = -1; );
  154703. return SQLITE_OK;
  154704. }
  154705. /*
  154706. ** Implementation of xRollback(). Discard the contents of the pending-terms
  154707. ** hash-table. Any changes made to the database are reverted by SQLite.
  154708. */
  154709. static int fts3RollbackMethod(sqlite3_vtab *pVtab){
  154710. Fts3Table *p = (Fts3Table*)pVtab;
  154711. sqlite3Fts3PendingTermsClear(p);
  154712. assert( p->inTransaction!=0 );
  154713. TESTONLY( p->inTransaction = 0 );
  154714. TESTONLY( p->mxSavepoint = -1; );
  154715. return SQLITE_OK;
  154716. }
  154717. /*
  154718. ** When called, *ppPoslist must point to the byte immediately following the
  154719. ** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
  154720. ** moves *ppPoslist so that it instead points to the first byte of the
  154721. ** same position list.
  154722. */
  154723. static void fts3ReversePoslist(char *pStart, char **ppPoslist){
  154724. char *p = &(*ppPoslist)[-2];
  154725. char c = 0;
  154726. /* Skip backwards passed any trailing 0x00 bytes added by NearTrim() */
  154727. while( p>pStart && (c=*p--)==0 );
  154728. /* Search backwards for a varint with value zero (the end of the previous
  154729. ** poslist). This is an 0x00 byte preceded by some byte that does not
  154730. ** have the 0x80 bit set. */
  154731. while( p>pStart && (*p & 0x80) | c ){
  154732. c = *p--;
  154733. }
  154734. assert( p==pStart || c==0 );
  154735. /* At this point p points to that preceding byte without the 0x80 bit
  154736. ** set. So to find the start of the poslist, skip forward 2 bytes then
  154737. ** over a varint.
  154738. **
  154739. ** Normally. The other case is that p==pStart and the poslist to return
  154740. ** is the first in the doclist. In this case do not skip forward 2 bytes.
  154741. ** The second part of the if condition (c==0 && *ppPoslist>&p[2])
  154742. ** is required for cases where the first byte of a doclist and the
  154743. ** doclist is empty. For example, if the first docid is 10, a doclist
  154744. ** that begins with:
  154745. **
  154746. ** 0x0A 0x00 <next docid delta varint>
  154747. */
  154748. if( p>pStart || (c==0 && *ppPoslist>&p[2]) ){ p = &p[2]; }
  154749. while( *p++&0x80 );
  154750. *ppPoslist = p;
  154751. }
  154752. /*
  154753. ** Helper function used by the implementation of the overloaded snippet(),
  154754. ** offsets() and optimize() SQL functions.
  154755. **
  154756. ** If the value passed as the third argument is a blob of size
  154757. ** sizeof(Fts3Cursor*), then the blob contents are copied to the
  154758. ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
  154759. ** message is written to context pContext and SQLITE_ERROR returned. The
  154760. ** string passed via zFunc is used as part of the error message.
  154761. */
  154762. static int fts3FunctionArg(
  154763. sqlite3_context *pContext, /* SQL function call context */
  154764. const char *zFunc, /* Function name */
  154765. sqlite3_value *pVal, /* argv[0] passed to function */
  154766. Fts3Cursor **ppCsr /* OUT: Store cursor handle here */
  154767. ){
  154768. int rc;
  154769. *ppCsr = (Fts3Cursor*)sqlite3_value_pointer(pVal, "fts3cursor");
  154770. if( (*ppCsr)!=0 ){
  154771. rc = SQLITE_OK;
  154772. }else{
  154773. char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
  154774. sqlite3_result_error(pContext, zErr, -1);
  154775. sqlite3_free(zErr);
  154776. rc = SQLITE_ERROR;
  154777. }
  154778. return rc;
  154779. }
  154780. /*
  154781. ** Implementation of the snippet() function for FTS3
  154782. */
  154783. static void fts3SnippetFunc(
  154784. sqlite3_context *pContext, /* SQLite function call context */
  154785. int nVal, /* Size of apVal[] array */
  154786. sqlite3_value **apVal /* Array of arguments */
  154787. ){
  154788. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  154789. const char *zStart = "<b>";
  154790. const char *zEnd = "</b>";
  154791. const char *zEllipsis = "<b>...</b>";
  154792. int iCol = -1;
  154793. int nToken = 15; /* Default number of tokens in snippet */
  154794. /* There must be at least one argument passed to this function (otherwise
  154795. ** the non-overloaded version would have been called instead of this one).
  154796. */
  154797. assert( nVal>=1 );
  154798. if( nVal>6 ){
  154799. sqlite3_result_error(pContext,
  154800. "wrong number of arguments to function snippet()", -1);
  154801. return;
  154802. }
  154803. if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
  154804. switch( nVal ){
  154805. case 6: nToken = sqlite3_value_int(apVal[5]);
  154806. case 5: iCol = sqlite3_value_int(apVal[4]);
  154807. case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
  154808. case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
  154809. case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
  154810. }
  154811. if( !zEllipsis || !zEnd || !zStart ){
  154812. sqlite3_result_error_nomem(pContext);
  154813. }else if( nToken==0 ){
  154814. sqlite3_result_text(pContext, "", -1, SQLITE_STATIC);
  154815. }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
  154816. sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
  154817. }
  154818. }
  154819. /*
  154820. ** Implementation of the offsets() function for FTS3
  154821. */
  154822. static void fts3OffsetsFunc(
  154823. sqlite3_context *pContext, /* SQLite function call context */
  154824. int nVal, /* Size of argument array */
  154825. sqlite3_value **apVal /* Array of arguments */
  154826. ){
  154827. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  154828. UNUSED_PARAMETER(nVal);
  154829. assert( nVal==1 );
  154830. if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
  154831. assert( pCsr );
  154832. if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
  154833. sqlite3Fts3Offsets(pContext, pCsr);
  154834. }
  154835. }
  154836. /*
  154837. ** Implementation of the special optimize() function for FTS3. This
  154838. ** function merges all segments in the database to a single segment.
  154839. ** Example usage is:
  154840. **
  154841. ** SELECT optimize(t) FROM t LIMIT 1;
  154842. **
  154843. ** where 't' is the name of an FTS3 table.
  154844. */
  154845. static void fts3OptimizeFunc(
  154846. sqlite3_context *pContext, /* SQLite function call context */
  154847. int nVal, /* Size of argument array */
  154848. sqlite3_value **apVal /* Array of arguments */
  154849. ){
  154850. int rc; /* Return code */
  154851. Fts3Table *p; /* Virtual table handle */
  154852. Fts3Cursor *pCursor; /* Cursor handle passed through apVal[0] */
  154853. UNUSED_PARAMETER(nVal);
  154854. assert( nVal==1 );
  154855. if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
  154856. p = (Fts3Table *)pCursor->base.pVtab;
  154857. assert( p );
  154858. rc = sqlite3Fts3Optimize(p);
  154859. switch( rc ){
  154860. case SQLITE_OK:
  154861. sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
  154862. break;
  154863. case SQLITE_DONE:
  154864. sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
  154865. break;
  154866. default:
  154867. sqlite3_result_error_code(pContext, rc);
  154868. break;
  154869. }
  154870. }
  154871. /*
  154872. ** Implementation of the matchinfo() function for FTS3
  154873. */
  154874. static void fts3MatchinfoFunc(
  154875. sqlite3_context *pContext, /* SQLite function call context */
  154876. int nVal, /* Size of argument array */
  154877. sqlite3_value **apVal /* Array of arguments */
  154878. ){
  154879. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  154880. assert( nVal==1 || nVal==2 );
  154881. if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
  154882. const char *zArg = 0;
  154883. if( nVal>1 ){
  154884. zArg = (const char *)sqlite3_value_text(apVal[1]);
  154885. }
  154886. sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
  154887. }
  154888. }
  154889. /*
  154890. ** This routine implements the xFindFunction method for the FTS3
  154891. ** virtual table.
  154892. */
  154893. static int fts3FindFunctionMethod(
  154894. sqlite3_vtab *pVtab, /* Virtual table handle */
  154895. int nArg, /* Number of SQL function arguments */
  154896. const char *zName, /* Name of SQL function */
  154897. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
  154898. void **ppArg /* Unused */
  154899. ){
  154900. struct Overloaded {
  154901. const char *zName;
  154902. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  154903. } aOverload[] = {
  154904. { "snippet", fts3SnippetFunc },
  154905. { "offsets", fts3OffsetsFunc },
  154906. { "optimize", fts3OptimizeFunc },
  154907. { "matchinfo", fts3MatchinfoFunc },
  154908. };
  154909. int i; /* Iterator variable */
  154910. UNUSED_PARAMETER(pVtab);
  154911. UNUSED_PARAMETER(nArg);
  154912. UNUSED_PARAMETER(ppArg);
  154913. for(i=0; i<SizeofArray(aOverload); i++){
  154914. if( strcmp(zName, aOverload[i].zName)==0 ){
  154915. *pxFunc = aOverload[i].xFunc;
  154916. return 1;
  154917. }
  154918. }
  154919. /* No function of the specified name was found. Return 0. */
  154920. return 0;
  154921. }
  154922. /*
  154923. ** Implementation of FTS3 xRename method. Rename an fts3 table.
  154924. */
  154925. static int fts3RenameMethod(
  154926. sqlite3_vtab *pVtab, /* Virtual table handle */
  154927. const char *zName /* New name of table */
  154928. ){
  154929. Fts3Table *p = (Fts3Table *)pVtab;
  154930. sqlite3 *db = p->db; /* Database connection */
  154931. int rc; /* Return Code */
  154932. /* At this point it must be known if the %_stat table exists or not.
  154933. ** So bHasStat may not be 2. */
  154934. rc = fts3SetHasStat(p);
  154935. /* As it happens, the pending terms table is always empty here. This is
  154936. ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction
  154937. ** always opens a savepoint transaction. And the xSavepoint() method
  154938. ** flushes the pending terms table. But leave the (no-op) call to
  154939. ** PendingTermsFlush() in in case that changes.
  154940. */
  154941. assert( p->nPendingData==0 );
  154942. if( rc==SQLITE_OK ){
  154943. rc = sqlite3Fts3PendingTermsFlush(p);
  154944. }
  154945. if( p->zContentTbl==0 ){
  154946. fts3DbExec(&rc, db,
  154947. "ALTER TABLE %Q.'%q_content' RENAME TO '%q_content';",
  154948. p->zDb, p->zName, zName
  154949. );
  154950. }
  154951. if( p->bHasDocsize ){
  154952. fts3DbExec(&rc, db,
  154953. "ALTER TABLE %Q.'%q_docsize' RENAME TO '%q_docsize';",
  154954. p->zDb, p->zName, zName
  154955. );
  154956. }
  154957. if( p->bHasStat ){
  154958. fts3DbExec(&rc, db,
  154959. "ALTER TABLE %Q.'%q_stat' RENAME TO '%q_stat';",
  154960. p->zDb, p->zName, zName
  154961. );
  154962. }
  154963. fts3DbExec(&rc, db,
  154964. "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
  154965. p->zDb, p->zName, zName
  154966. );
  154967. fts3DbExec(&rc, db,
  154968. "ALTER TABLE %Q.'%q_segdir' RENAME TO '%q_segdir';",
  154969. p->zDb, p->zName, zName
  154970. );
  154971. return rc;
  154972. }
  154973. /*
  154974. ** The xSavepoint() method.
  154975. **
  154976. ** Flush the contents of the pending-terms table to disk.
  154977. */
  154978. static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
  154979. int rc = SQLITE_OK;
  154980. UNUSED_PARAMETER(iSavepoint);
  154981. assert( ((Fts3Table *)pVtab)->inTransaction );
  154982. assert( ((Fts3Table *)pVtab)->mxSavepoint <= iSavepoint );
  154983. TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
  154984. if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){
  154985. rc = fts3SyncMethod(pVtab);
  154986. }
  154987. return rc;
  154988. }
  154989. /*
  154990. ** The xRelease() method.
  154991. **
  154992. ** This is a no-op.
  154993. */
  154994. static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
  154995. TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
  154996. UNUSED_PARAMETER(iSavepoint);
  154997. UNUSED_PARAMETER(pVtab);
  154998. assert( p->inTransaction );
  154999. assert( p->mxSavepoint >= iSavepoint );
  155000. TESTONLY( p->mxSavepoint = iSavepoint-1 );
  155001. return SQLITE_OK;
  155002. }
  155003. /*
  155004. ** The xRollbackTo() method.
  155005. **
  155006. ** Discard the contents of the pending terms table.
  155007. */
  155008. static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
  155009. Fts3Table *p = (Fts3Table*)pVtab;
  155010. UNUSED_PARAMETER(iSavepoint);
  155011. assert( p->inTransaction );
  155012. TESTONLY( p->mxSavepoint = iSavepoint );
  155013. sqlite3Fts3PendingTermsClear(p);
  155014. return SQLITE_OK;
  155015. }
  155016. /*
  155017. ** Return true if zName is the extension on one of the shadow tables used
  155018. ** by this module.
  155019. */
  155020. static int fts3ShadowName(const char *zName){
  155021. static const char *azName[] = {
  155022. "content", "docsize", "segdir", "segments", "stat",
  155023. };
  155024. unsigned int i;
  155025. for(i=0; i<sizeof(azName)/sizeof(azName[0]); i++){
  155026. if( sqlite3_stricmp(zName, azName[i])==0 ) return 1;
  155027. }
  155028. return 0;
  155029. }
  155030. static const sqlite3_module fts3Module = {
  155031. /* iVersion */ 3,
  155032. /* xCreate */ fts3CreateMethod,
  155033. /* xConnect */ fts3ConnectMethod,
  155034. /* xBestIndex */ fts3BestIndexMethod,
  155035. /* xDisconnect */ fts3DisconnectMethod,
  155036. /* xDestroy */ fts3DestroyMethod,
  155037. /* xOpen */ fts3OpenMethod,
  155038. /* xClose */ fts3CloseMethod,
  155039. /* xFilter */ fts3FilterMethod,
  155040. /* xNext */ fts3NextMethod,
  155041. /* xEof */ fts3EofMethod,
  155042. /* xColumn */ fts3ColumnMethod,
  155043. /* xRowid */ fts3RowidMethod,
  155044. /* xUpdate */ fts3UpdateMethod,
  155045. /* xBegin */ fts3BeginMethod,
  155046. /* xSync */ fts3SyncMethod,
  155047. /* xCommit */ fts3CommitMethod,
  155048. /* xRollback */ fts3RollbackMethod,
  155049. /* xFindFunction */ fts3FindFunctionMethod,
  155050. /* xRename */ fts3RenameMethod,
  155051. /* xSavepoint */ fts3SavepointMethod,
  155052. /* xRelease */ fts3ReleaseMethod,
  155053. /* xRollbackTo */ fts3RollbackToMethod,
  155054. /* xShadowName */ fts3ShadowName,
  155055. };
  155056. /*
  155057. ** This function is registered as the module destructor (called when an
  155058. ** FTS3 enabled database connection is closed). It frees the memory
  155059. ** allocated for the tokenizer hash table.
  155060. */
  155061. static void hashDestroy(void *p){
  155062. Fts3Hash *pHash = (Fts3Hash *)p;
  155063. sqlite3Fts3HashClear(pHash);
  155064. sqlite3_free(pHash);
  155065. }
  155066. /*
  155067. ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
  155068. ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
  155069. ** respectively. The following three forward declarations are for functions
  155070. ** declared in these files used to retrieve the respective implementations.
  155071. **
  155072. ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
  155073. ** to by the argument to point to the "simple" tokenizer implementation.
  155074. ** And so on.
  155075. */
  155076. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  155077. SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  155078. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  155079. SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule);
  155080. #endif
  155081. #ifdef SQLITE_ENABLE_ICU
  155082. SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  155083. #endif
  155084. /*
  155085. ** Initialize the fts3 extension. If this extension is built as part
  155086. ** of the sqlite library, then this function is called directly by
  155087. ** SQLite. If fts3 is built as a dynamically loadable extension, this
  155088. ** function is called by the sqlite3_extension_init() entry point.
  155089. */
  155090. SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
  155091. int rc = SQLITE_OK;
  155092. Fts3Hash *pHash = 0;
  155093. const sqlite3_tokenizer_module *pSimple = 0;
  155094. const sqlite3_tokenizer_module *pPorter = 0;
  155095. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  155096. const sqlite3_tokenizer_module *pUnicode = 0;
  155097. #endif
  155098. #ifdef SQLITE_ENABLE_ICU
  155099. const sqlite3_tokenizer_module *pIcu = 0;
  155100. sqlite3Fts3IcuTokenizerModule(&pIcu);
  155101. #endif
  155102. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  155103. sqlite3Fts3UnicodeTokenizer(&pUnicode);
  155104. #endif
  155105. #ifdef SQLITE_TEST
  155106. rc = sqlite3Fts3InitTerm(db);
  155107. if( rc!=SQLITE_OK ) return rc;
  155108. #endif
  155109. rc = sqlite3Fts3InitAux(db);
  155110. if( rc!=SQLITE_OK ) return rc;
  155111. sqlite3Fts3SimpleTokenizerModule(&pSimple);
  155112. sqlite3Fts3PorterTokenizerModule(&pPorter);
  155113. /* Allocate and initialize the hash-table used to store tokenizers. */
  155114. pHash = sqlite3_malloc(sizeof(Fts3Hash));
  155115. if( !pHash ){
  155116. rc = SQLITE_NOMEM;
  155117. }else{
  155118. sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
  155119. }
  155120. /* Load the built-in tokenizers into the hash table */
  155121. if( rc==SQLITE_OK ){
  155122. if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
  155123. || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
  155124. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  155125. || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode)
  155126. #endif
  155127. #ifdef SQLITE_ENABLE_ICU
  155128. || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
  155129. #endif
  155130. ){
  155131. rc = SQLITE_NOMEM;
  155132. }
  155133. }
  155134. #ifdef SQLITE_TEST
  155135. if( rc==SQLITE_OK ){
  155136. rc = sqlite3Fts3ExprInitTestInterface(db, pHash);
  155137. }
  155138. #endif
  155139. /* Create the virtual table wrapper around the hash-table and overload
  155140. ** the four scalar functions. If this is successful, register the
  155141. ** module with sqlite.
  155142. */
  155143. if( SQLITE_OK==rc
  155144. && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
  155145. && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
  155146. && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
  155147. && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
  155148. && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
  155149. && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
  155150. ){
  155151. rc = sqlite3_create_module_v2(
  155152. db, "fts3", &fts3Module, (void *)pHash, hashDestroy
  155153. );
  155154. if( rc==SQLITE_OK ){
  155155. rc = sqlite3_create_module_v2(
  155156. db, "fts4", &fts3Module, (void *)pHash, 0
  155157. );
  155158. }
  155159. if( rc==SQLITE_OK ){
  155160. rc = sqlite3Fts3InitTok(db, (void *)pHash);
  155161. }
  155162. return rc;
  155163. }
  155164. /* An error has occurred. Delete the hash table and return the error code. */
  155165. assert( rc!=SQLITE_OK );
  155166. if( pHash ){
  155167. sqlite3Fts3HashClear(pHash);
  155168. sqlite3_free(pHash);
  155169. }
  155170. return rc;
  155171. }
  155172. /*
  155173. ** Allocate an Fts3MultiSegReader for each token in the expression headed
  155174. ** by pExpr.
  155175. **
  155176. ** An Fts3SegReader object is a cursor that can seek or scan a range of
  155177. ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
  155178. ** Fts3SegReader objects internally to provide an interface to seek or scan
  155179. ** within the union of all segments of a b-tree. Hence the name.
  155180. **
  155181. ** If the allocated Fts3MultiSegReader just seeks to a single entry in a
  155182. ** segment b-tree (if the term is not a prefix or it is a prefix for which
  155183. ** there exists prefix b-tree of the right length) then it may be traversed
  155184. ** and merged incrementally. Otherwise, it has to be merged into an in-memory
  155185. ** doclist and then traversed.
  155186. */
  155187. static void fts3EvalAllocateReaders(
  155188. Fts3Cursor *pCsr, /* FTS cursor handle */
  155189. Fts3Expr *pExpr, /* Allocate readers for this expression */
  155190. int *pnToken, /* OUT: Total number of tokens in phrase. */
  155191. int *pnOr, /* OUT: Total number of OR nodes in expr. */
  155192. int *pRc /* IN/OUT: Error code */
  155193. ){
  155194. if( pExpr && SQLITE_OK==*pRc ){
  155195. if( pExpr->eType==FTSQUERY_PHRASE ){
  155196. int i;
  155197. int nToken = pExpr->pPhrase->nToken;
  155198. *pnToken += nToken;
  155199. for(i=0; i<nToken; i++){
  155200. Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
  155201. int rc = fts3TermSegReaderCursor(pCsr,
  155202. pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
  155203. );
  155204. if( rc!=SQLITE_OK ){
  155205. *pRc = rc;
  155206. return;
  155207. }
  155208. }
  155209. assert( pExpr->pPhrase->iDoclistToken==0 );
  155210. pExpr->pPhrase->iDoclistToken = -1;
  155211. }else{
  155212. *pnOr += (pExpr->eType==FTSQUERY_OR);
  155213. fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
  155214. fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
  155215. }
  155216. }
  155217. }
  155218. /*
  155219. ** Arguments pList/nList contain the doclist for token iToken of phrase p.
  155220. ** It is merged into the main doclist stored in p->doclist.aAll/nAll.
  155221. **
  155222. ** This function assumes that pList points to a buffer allocated using
  155223. ** sqlite3_malloc(). This function takes responsibility for eventually
  155224. ** freeing the buffer.
  155225. **
  155226. ** SQLITE_OK is returned if successful, or SQLITE_NOMEM if an error occurs.
  155227. */
  155228. static int fts3EvalPhraseMergeToken(
  155229. Fts3Table *pTab, /* FTS Table pointer */
  155230. Fts3Phrase *p, /* Phrase to merge pList/nList into */
  155231. int iToken, /* Token pList/nList corresponds to */
  155232. char *pList, /* Pointer to doclist */
  155233. int nList /* Number of bytes in pList */
  155234. ){
  155235. int rc = SQLITE_OK;
  155236. assert( iToken!=p->iDoclistToken );
  155237. if( pList==0 ){
  155238. sqlite3_free(p->doclist.aAll);
  155239. p->doclist.aAll = 0;
  155240. p->doclist.nAll = 0;
  155241. }
  155242. else if( p->iDoclistToken<0 ){
  155243. p->doclist.aAll = pList;
  155244. p->doclist.nAll = nList;
  155245. }
  155246. else if( p->doclist.aAll==0 ){
  155247. sqlite3_free(pList);
  155248. }
  155249. else {
  155250. char *pLeft;
  155251. char *pRight;
  155252. int nLeft;
  155253. int nRight;
  155254. int nDiff;
  155255. if( p->iDoclistToken<iToken ){
  155256. pLeft = p->doclist.aAll;
  155257. nLeft = p->doclist.nAll;
  155258. pRight = pList;
  155259. nRight = nList;
  155260. nDiff = iToken - p->iDoclistToken;
  155261. }else{
  155262. pRight = p->doclist.aAll;
  155263. nRight = p->doclist.nAll;
  155264. pLeft = pList;
  155265. nLeft = nList;
  155266. nDiff = p->iDoclistToken - iToken;
  155267. }
  155268. rc = fts3DoclistPhraseMerge(
  155269. pTab->bDescIdx, nDiff, pLeft, nLeft, &pRight, &nRight
  155270. );
  155271. sqlite3_free(pLeft);
  155272. p->doclist.aAll = pRight;
  155273. p->doclist.nAll = nRight;
  155274. }
  155275. if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
  155276. return rc;
  155277. }
  155278. /*
  155279. ** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
  155280. ** does not take deferred tokens into account.
  155281. **
  155282. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  155283. */
  155284. static int fts3EvalPhraseLoad(
  155285. Fts3Cursor *pCsr, /* FTS Cursor handle */
  155286. Fts3Phrase *p /* Phrase object */
  155287. ){
  155288. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  155289. int iToken;
  155290. int rc = SQLITE_OK;
  155291. for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
  155292. Fts3PhraseToken *pToken = &p->aToken[iToken];
  155293. assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
  155294. if( pToken->pSegcsr ){
  155295. int nThis = 0;
  155296. char *pThis = 0;
  155297. rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
  155298. if( rc==SQLITE_OK ){
  155299. rc = fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
  155300. }
  155301. }
  155302. assert( pToken->pSegcsr==0 );
  155303. }
  155304. return rc;
  155305. }
  155306. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  155307. /*
  155308. ** This function is called on each phrase after the position lists for
  155309. ** any deferred tokens have been loaded into memory. It updates the phrases
  155310. ** current position list to include only those positions that are really
  155311. ** instances of the phrase (after considering deferred tokens). If this
  155312. ** means that the phrase does not appear in the current row, doclist.pList
  155313. ** and doclist.nList are both zeroed.
  155314. **
  155315. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  155316. */
  155317. static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
  155318. int iToken; /* Used to iterate through phrase tokens */
  155319. char *aPoslist = 0; /* Position list for deferred tokens */
  155320. int nPoslist = 0; /* Number of bytes in aPoslist */
  155321. int iPrev = -1; /* Token number of previous deferred token */
  155322. assert( pPhrase->doclist.bFreeList==0 );
  155323. for(iToken=0; iToken<pPhrase->nToken; iToken++){
  155324. Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
  155325. Fts3DeferredToken *pDeferred = pToken->pDeferred;
  155326. if( pDeferred ){
  155327. char *pList;
  155328. int nList;
  155329. int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
  155330. if( rc!=SQLITE_OK ) return rc;
  155331. if( pList==0 ){
  155332. sqlite3_free(aPoslist);
  155333. pPhrase->doclist.pList = 0;
  155334. pPhrase->doclist.nList = 0;
  155335. return SQLITE_OK;
  155336. }else if( aPoslist==0 ){
  155337. aPoslist = pList;
  155338. nPoslist = nList;
  155339. }else{
  155340. char *aOut = pList;
  155341. char *p1 = aPoslist;
  155342. char *p2 = aOut;
  155343. assert( iPrev>=0 );
  155344. fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
  155345. sqlite3_free(aPoslist);
  155346. aPoslist = pList;
  155347. nPoslist = (int)(aOut - aPoslist);
  155348. if( nPoslist==0 ){
  155349. sqlite3_free(aPoslist);
  155350. pPhrase->doclist.pList = 0;
  155351. pPhrase->doclist.nList = 0;
  155352. return SQLITE_OK;
  155353. }
  155354. }
  155355. iPrev = iToken;
  155356. }
  155357. }
  155358. if( iPrev>=0 ){
  155359. int nMaxUndeferred = pPhrase->iDoclistToken;
  155360. if( nMaxUndeferred<0 ){
  155361. pPhrase->doclist.pList = aPoslist;
  155362. pPhrase->doclist.nList = nPoslist;
  155363. pPhrase->doclist.iDocid = pCsr->iPrevId;
  155364. pPhrase->doclist.bFreeList = 1;
  155365. }else{
  155366. int nDistance;
  155367. char *p1;
  155368. char *p2;
  155369. char *aOut;
  155370. if( nMaxUndeferred>iPrev ){
  155371. p1 = aPoslist;
  155372. p2 = pPhrase->doclist.pList;
  155373. nDistance = nMaxUndeferred - iPrev;
  155374. }else{
  155375. p1 = pPhrase->doclist.pList;
  155376. p2 = aPoslist;
  155377. nDistance = iPrev - nMaxUndeferred;
  155378. }
  155379. aOut = (char *)sqlite3_malloc(nPoslist+8);
  155380. if( !aOut ){
  155381. sqlite3_free(aPoslist);
  155382. return SQLITE_NOMEM;
  155383. }
  155384. pPhrase->doclist.pList = aOut;
  155385. if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
  155386. pPhrase->doclist.bFreeList = 1;
  155387. pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
  155388. }else{
  155389. sqlite3_free(aOut);
  155390. pPhrase->doclist.pList = 0;
  155391. pPhrase->doclist.nList = 0;
  155392. }
  155393. sqlite3_free(aPoslist);
  155394. }
  155395. }
  155396. return SQLITE_OK;
  155397. }
  155398. #endif /* SQLITE_DISABLE_FTS4_DEFERRED */
  155399. /*
  155400. ** Maximum number of tokens a phrase may have to be considered for the
  155401. ** incremental doclists strategy.
  155402. */
  155403. #define MAX_INCR_PHRASE_TOKENS 4
  155404. /*
  155405. ** This function is called for each Fts3Phrase in a full-text query
  155406. ** expression to initialize the mechanism for returning rows. Once this
  155407. ** function has been called successfully on an Fts3Phrase, it may be
  155408. ** used with fts3EvalPhraseNext() to iterate through the matching docids.
  155409. **
  155410. ** If parameter bOptOk is true, then the phrase may (or may not) use the
  155411. ** incremental loading strategy. Otherwise, the entire doclist is loaded into
  155412. ** memory within this call.
  155413. **
  155414. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  155415. */
  155416. static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
  155417. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  155418. int rc = SQLITE_OK; /* Error code */
  155419. int i;
  155420. /* Determine if doclists may be loaded from disk incrementally. This is
  155421. ** possible if the bOptOk argument is true, the FTS doclists will be
  155422. ** scanned in forward order, and the phrase consists of
  155423. ** MAX_INCR_PHRASE_TOKENS or fewer tokens, none of which are are "^first"
  155424. ** tokens or prefix tokens that cannot use a prefix-index. */
  155425. int bHaveIncr = 0;
  155426. int bIncrOk = (bOptOk
  155427. && pCsr->bDesc==pTab->bDescIdx
  155428. && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
  155429. #ifdef SQLITE_TEST
  155430. && pTab->bNoIncrDoclist==0
  155431. #endif
  155432. );
  155433. for(i=0; bIncrOk==1 && i<p->nToken; i++){
  155434. Fts3PhraseToken *pToken = &p->aToken[i];
  155435. if( pToken->bFirst || (pToken->pSegcsr!=0 && !pToken->pSegcsr->bLookup) ){
  155436. bIncrOk = 0;
  155437. }
  155438. if( pToken->pSegcsr ) bHaveIncr = 1;
  155439. }
  155440. if( bIncrOk && bHaveIncr ){
  155441. /* Use the incremental approach. */
  155442. int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
  155443. for(i=0; rc==SQLITE_OK && i<p->nToken; i++){
  155444. Fts3PhraseToken *pToken = &p->aToken[i];
  155445. Fts3MultiSegReader *pSegcsr = pToken->pSegcsr;
  155446. if( pSegcsr ){
  155447. rc = sqlite3Fts3MsrIncrStart(pTab, pSegcsr, iCol, pToken->z, pToken->n);
  155448. }
  155449. }
  155450. p->bIncr = 1;
  155451. }else{
  155452. /* Load the full doclist for the phrase into memory. */
  155453. rc = fts3EvalPhraseLoad(pCsr, p);
  155454. p->bIncr = 0;
  155455. }
  155456. assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
  155457. return rc;
  155458. }
  155459. /*
  155460. ** This function is used to iterate backwards (from the end to start)
  155461. ** through doclists. It is used by this module to iterate through phrase
  155462. ** doclists in reverse and by the fts3_write.c module to iterate through
  155463. ** pending-terms lists when writing to databases with "order=desc".
  155464. **
  155465. ** The doclist may be sorted in ascending (parameter bDescIdx==0) or
  155466. ** descending (parameter bDescIdx==1) order of docid. Regardless, this
  155467. ** function iterates from the end of the doclist to the beginning.
  155468. */
  155469. SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
  155470. int bDescIdx, /* True if the doclist is desc */
  155471. char *aDoclist, /* Pointer to entire doclist */
  155472. int nDoclist, /* Length of aDoclist in bytes */
  155473. char **ppIter, /* IN/OUT: Iterator pointer */
  155474. sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
  155475. int *pnList, /* OUT: List length pointer */
  155476. u8 *pbEof /* OUT: End-of-file flag */
  155477. ){
  155478. char *p = *ppIter;
  155479. assert( nDoclist>0 );
  155480. assert( *pbEof==0 );
  155481. assert( p || *piDocid==0 );
  155482. assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
  155483. if( p==0 ){
  155484. sqlite3_int64 iDocid = 0;
  155485. char *pNext = 0;
  155486. char *pDocid = aDoclist;
  155487. char *pEnd = &aDoclist[nDoclist];
  155488. int iMul = 1;
  155489. while( pDocid<pEnd ){
  155490. sqlite3_int64 iDelta;
  155491. pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
  155492. iDocid += (iMul * iDelta);
  155493. pNext = pDocid;
  155494. fts3PoslistCopy(0, &pDocid);
  155495. while( pDocid<pEnd && *pDocid==0 ) pDocid++;
  155496. iMul = (bDescIdx ? -1 : 1);
  155497. }
  155498. *pnList = (int)(pEnd - pNext);
  155499. *ppIter = pNext;
  155500. *piDocid = iDocid;
  155501. }else{
  155502. int iMul = (bDescIdx ? -1 : 1);
  155503. sqlite3_int64 iDelta;
  155504. fts3GetReverseVarint(&p, aDoclist, &iDelta);
  155505. *piDocid -= (iMul * iDelta);
  155506. if( p==aDoclist ){
  155507. *pbEof = 1;
  155508. }else{
  155509. char *pSave = p;
  155510. fts3ReversePoslist(aDoclist, &p);
  155511. *pnList = (int)(pSave - p);
  155512. }
  155513. *ppIter = p;
  155514. }
  155515. }
  155516. /*
  155517. ** Iterate forwards through a doclist.
  155518. */
  155519. SQLITE_PRIVATE void sqlite3Fts3DoclistNext(
  155520. int bDescIdx, /* True if the doclist is desc */
  155521. char *aDoclist, /* Pointer to entire doclist */
  155522. int nDoclist, /* Length of aDoclist in bytes */
  155523. char **ppIter, /* IN/OUT: Iterator pointer */
  155524. sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
  155525. u8 *pbEof /* OUT: End-of-file flag */
  155526. ){
  155527. char *p = *ppIter;
  155528. assert( nDoclist>0 );
  155529. assert( *pbEof==0 );
  155530. assert( p || *piDocid==0 );
  155531. assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );
  155532. if( p==0 ){
  155533. p = aDoclist;
  155534. p += sqlite3Fts3GetVarint(p, piDocid);
  155535. }else{
  155536. fts3PoslistCopy(0, &p);
  155537. while( p<&aDoclist[nDoclist] && *p==0 ) p++;
  155538. if( p>=&aDoclist[nDoclist] ){
  155539. *pbEof = 1;
  155540. }else{
  155541. sqlite3_int64 iVar;
  155542. p += sqlite3Fts3GetVarint(p, &iVar);
  155543. *piDocid += ((bDescIdx ? -1 : 1) * iVar);
  155544. }
  155545. }
  155546. *ppIter = p;
  155547. }
  155548. /*
  155549. ** Advance the iterator pDL to the next entry in pDL->aAll/nAll. Set *pbEof
  155550. ** to true if EOF is reached.
  155551. */
  155552. static void fts3EvalDlPhraseNext(
  155553. Fts3Table *pTab,
  155554. Fts3Doclist *pDL,
  155555. u8 *pbEof
  155556. ){
  155557. char *pIter; /* Used to iterate through aAll */
  155558. char *pEnd = &pDL->aAll[pDL->nAll]; /* 1 byte past end of aAll */
  155559. if( pDL->pNextDocid ){
  155560. pIter = pDL->pNextDocid;
  155561. }else{
  155562. pIter = pDL->aAll;
  155563. }
  155564. if( pIter>=pEnd ){
  155565. /* We have already reached the end of this doclist. EOF. */
  155566. *pbEof = 1;
  155567. }else{
  155568. sqlite3_int64 iDelta;
  155569. pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
  155570. if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
  155571. pDL->iDocid += iDelta;
  155572. }else{
  155573. pDL->iDocid -= iDelta;
  155574. }
  155575. pDL->pList = pIter;
  155576. fts3PoslistCopy(0, &pIter);
  155577. pDL->nList = (int)(pIter - pDL->pList);
  155578. /* pIter now points just past the 0x00 that terminates the position-
  155579. ** list for document pDL->iDocid. However, if this position-list was
  155580. ** edited in place by fts3EvalNearTrim(), then pIter may not actually
  155581. ** point to the start of the next docid value. The following line deals
  155582. ** with this case by advancing pIter past the zero-padding added by
  155583. ** fts3EvalNearTrim(). */
  155584. while( pIter<pEnd && *pIter==0 ) pIter++;
  155585. pDL->pNextDocid = pIter;
  155586. assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
  155587. *pbEof = 0;
  155588. }
  155589. }
  155590. /*
  155591. ** Helper type used by fts3EvalIncrPhraseNext() and incrPhraseTokenNext().
  155592. */
  155593. typedef struct TokenDoclist TokenDoclist;
  155594. struct TokenDoclist {
  155595. int bIgnore;
  155596. sqlite3_int64 iDocid;
  155597. char *pList;
  155598. int nList;
  155599. };
  155600. /*
  155601. ** Token pToken is an incrementally loaded token that is part of a
  155602. ** multi-token phrase. Advance it to the next matching document in the
  155603. ** database and populate output variable *p with the details of the new
  155604. ** entry. Or, if the iterator has reached EOF, set *pbEof to true.
  155605. **
  155606. ** If an error occurs, return an SQLite error code. Otherwise, return
  155607. ** SQLITE_OK.
  155608. */
  155609. static int incrPhraseTokenNext(
  155610. Fts3Table *pTab, /* Virtual table handle */
  155611. Fts3Phrase *pPhrase, /* Phrase to advance token of */
  155612. int iToken, /* Specific token to advance */
  155613. TokenDoclist *p, /* OUT: Docid and doclist for new entry */
  155614. u8 *pbEof /* OUT: True if iterator is at EOF */
  155615. ){
  155616. int rc = SQLITE_OK;
  155617. if( pPhrase->iDoclistToken==iToken ){
  155618. assert( p->bIgnore==0 );
  155619. assert( pPhrase->aToken[iToken].pSegcsr==0 );
  155620. fts3EvalDlPhraseNext(pTab, &pPhrase->doclist, pbEof);
  155621. p->pList = pPhrase->doclist.pList;
  155622. p->nList = pPhrase->doclist.nList;
  155623. p->iDocid = pPhrase->doclist.iDocid;
  155624. }else{
  155625. Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
  155626. assert( pToken->pDeferred==0 );
  155627. assert( pToken->pSegcsr || pPhrase->iDoclistToken>=0 );
  155628. if( pToken->pSegcsr ){
  155629. assert( p->bIgnore==0 );
  155630. rc = sqlite3Fts3MsrIncrNext(
  155631. pTab, pToken->pSegcsr, &p->iDocid, &p->pList, &p->nList
  155632. );
  155633. if( p->pList==0 ) *pbEof = 1;
  155634. }else{
  155635. p->bIgnore = 1;
  155636. }
  155637. }
  155638. return rc;
  155639. }
  155640. /*
  155641. ** The phrase iterator passed as the second argument:
  155642. **
  155643. ** * features at least one token that uses an incremental doclist, and
  155644. **
  155645. ** * does not contain any deferred tokens.
  155646. **
  155647. ** Advance it to the next matching documnent in the database and populate
  155648. ** the Fts3Doclist.pList and nList fields.
  155649. **
  155650. ** If there is no "next" entry and no error occurs, then *pbEof is set to
  155651. ** 1 before returning. Otherwise, if no error occurs and the iterator is
  155652. ** successfully advanced, *pbEof is set to 0.
  155653. **
  155654. ** If an error occurs, return an SQLite error code. Otherwise, return
  155655. ** SQLITE_OK.
  155656. */
  155657. static int fts3EvalIncrPhraseNext(
  155658. Fts3Cursor *pCsr, /* FTS Cursor handle */
  155659. Fts3Phrase *p, /* Phrase object to advance to next docid */
  155660. u8 *pbEof /* OUT: Set to 1 if EOF */
  155661. ){
  155662. int rc = SQLITE_OK;
  155663. Fts3Doclist *pDL = &p->doclist;
  155664. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  155665. u8 bEof = 0;
  155666. /* This is only called if it is guaranteed that the phrase has at least
  155667. ** one incremental token. In which case the bIncr flag is set. */
  155668. assert( p->bIncr==1 );
  155669. if( p->nToken==1 ){
  155670. rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr,
  155671. &pDL->iDocid, &pDL->pList, &pDL->nList
  155672. );
  155673. if( pDL->pList==0 ) bEof = 1;
  155674. }else{
  155675. int bDescDoclist = pCsr->bDesc;
  155676. struct TokenDoclist a[MAX_INCR_PHRASE_TOKENS];
  155677. memset(a, 0, sizeof(a));
  155678. assert( p->nToken<=MAX_INCR_PHRASE_TOKENS );
  155679. assert( p->iDoclistToken<MAX_INCR_PHRASE_TOKENS );
  155680. while( bEof==0 ){
  155681. int bMaxSet = 0;
  155682. sqlite3_int64 iMax = 0; /* Largest docid for all iterators */
  155683. int i; /* Used to iterate through tokens */
  155684. /* Advance the iterator for each token in the phrase once. */
  155685. for(i=0; rc==SQLITE_OK && i<p->nToken && bEof==0; i++){
  155686. rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
  155687. if( a[i].bIgnore==0 && (bMaxSet==0 || DOCID_CMP(iMax, a[i].iDocid)<0) ){
  155688. iMax = a[i].iDocid;
  155689. bMaxSet = 1;
  155690. }
  155691. }
  155692. assert( rc!=SQLITE_OK || (p->nToken>=1 && a[p->nToken-1].bIgnore==0) );
  155693. assert( rc!=SQLITE_OK || bMaxSet );
  155694. /* Keep advancing iterators until they all point to the same document */
  155695. for(i=0; i<p->nToken; i++){
  155696. while( rc==SQLITE_OK && bEof==0
  155697. && a[i].bIgnore==0 && DOCID_CMP(a[i].iDocid, iMax)<0
  155698. ){
  155699. rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
  155700. if( DOCID_CMP(a[i].iDocid, iMax)>0 ){
  155701. iMax = a[i].iDocid;
  155702. i = 0;
  155703. }
  155704. }
  155705. }
  155706. /* Check if the current entries really are a phrase match */
  155707. if( bEof==0 ){
  155708. int nList = 0;
  155709. int nByte = a[p->nToken-1].nList;
  155710. char *aDoclist = sqlite3_malloc(nByte+FTS3_BUFFER_PADDING);
  155711. if( !aDoclist ) return SQLITE_NOMEM;
  155712. memcpy(aDoclist, a[p->nToken-1].pList, nByte+1);
  155713. memset(&aDoclist[nByte], 0, FTS3_BUFFER_PADDING);
  155714. for(i=0; i<(p->nToken-1); i++){
  155715. if( a[i].bIgnore==0 ){
  155716. char *pL = a[i].pList;
  155717. char *pR = aDoclist;
  155718. char *pOut = aDoclist;
  155719. int nDist = p->nToken-1-i;
  155720. int res = fts3PoslistPhraseMerge(&pOut, nDist, 0, 1, &pL, &pR);
  155721. if( res==0 ) break;
  155722. nList = (int)(pOut - aDoclist);
  155723. }
  155724. }
  155725. if( i==(p->nToken-1) ){
  155726. pDL->iDocid = iMax;
  155727. pDL->pList = aDoclist;
  155728. pDL->nList = nList;
  155729. pDL->bFreeList = 1;
  155730. break;
  155731. }
  155732. sqlite3_free(aDoclist);
  155733. }
  155734. }
  155735. }
  155736. *pbEof = bEof;
  155737. return rc;
  155738. }
  155739. /*
  155740. ** Attempt to move the phrase iterator to point to the next matching docid.
  155741. ** If an error occurs, return an SQLite error code. Otherwise, return
  155742. ** SQLITE_OK.
  155743. **
  155744. ** If there is no "next" entry and no error occurs, then *pbEof is set to
  155745. ** 1 before returning. Otherwise, if no error occurs and the iterator is
  155746. ** successfully advanced, *pbEof is set to 0.
  155747. */
  155748. static int fts3EvalPhraseNext(
  155749. Fts3Cursor *pCsr, /* FTS Cursor handle */
  155750. Fts3Phrase *p, /* Phrase object to advance to next docid */
  155751. u8 *pbEof /* OUT: Set to 1 if EOF */
  155752. ){
  155753. int rc = SQLITE_OK;
  155754. Fts3Doclist *pDL = &p->doclist;
  155755. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  155756. if( p->bIncr ){
  155757. rc = fts3EvalIncrPhraseNext(pCsr, p, pbEof);
  155758. }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
  155759. sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll,
  155760. &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
  155761. );
  155762. pDL->pList = pDL->pNextDocid;
  155763. }else{
  155764. fts3EvalDlPhraseNext(pTab, pDL, pbEof);
  155765. }
  155766. return rc;
  155767. }
  155768. /*
  155769. **
  155770. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  155771. ** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
  155772. ** expression. Also the Fts3Expr.bDeferred variable is set to true for any
  155773. ** expressions for which all descendent tokens are deferred.
  155774. **
  155775. ** If parameter bOptOk is zero, then it is guaranteed that the
  155776. ** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
  155777. ** each phrase in the expression (subject to deferred token processing).
  155778. ** Or, if bOptOk is non-zero, then one or more tokens within the expression
  155779. ** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
  155780. **
  155781. ** If an error occurs within this function, *pRc is set to an SQLite error
  155782. ** code before returning.
  155783. */
  155784. static void fts3EvalStartReaders(
  155785. Fts3Cursor *pCsr, /* FTS Cursor handle */
  155786. Fts3Expr *pExpr, /* Expression to initialize phrases in */
  155787. int *pRc /* IN/OUT: Error code */
  155788. ){
  155789. if( pExpr && SQLITE_OK==*pRc ){
  155790. if( pExpr->eType==FTSQUERY_PHRASE ){
  155791. int nToken = pExpr->pPhrase->nToken;
  155792. if( nToken ){
  155793. int i;
  155794. for(i=0; i<nToken; i++){
  155795. if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
  155796. }
  155797. pExpr->bDeferred = (i==nToken);
  155798. }
  155799. *pRc = fts3EvalPhraseStart(pCsr, 1, pExpr->pPhrase);
  155800. }else{
  155801. fts3EvalStartReaders(pCsr, pExpr->pLeft, pRc);
  155802. fts3EvalStartReaders(pCsr, pExpr->pRight, pRc);
  155803. pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
  155804. }
  155805. }
  155806. }
  155807. /*
  155808. ** An array of the following structures is assembled as part of the process
  155809. ** of selecting tokens to defer before the query starts executing (as part
  155810. ** of the xFilter() method). There is one element in the array for each
  155811. ** token in the FTS expression.
  155812. **
  155813. ** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
  155814. ** to phrases that are connected only by AND and NEAR operators (not OR or
  155815. ** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
  155816. ** separately. The root of a tokens AND/NEAR cluster is stored in
  155817. ** Fts3TokenAndCost.pRoot.
  155818. */
  155819. typedef struct Fts3TokenAndCost Fts3TokenAndCost;
  155820. struct Fts3TokenAndCost {
  155821. Fts3Phrase *pPhrase; /* The phrase the token belongs to */
  155822. int iToken; /* Position of token in phrase */
  155823. Fts3PhraseToken *pToken; /* The token itself */
  155824. Fts3Expr *pRoot; /* Root of NEAR/AND cluster */
  155825. int nOvfl; /* Number of overflow pages to load doclist */
  155826. int iCol; /* The column the token must match */
  155827. };
  155828. /*
  155829. ** This function is used to populate an allocated Fts3TokenAndCost array.
  155830. **
  155831. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  155832. ** Otherwise, if an error occurs during execution, *pRc is set to an
  155833. ** SQLite error code.
  155834. */
  155835. static void fts3EvalTokenCosts(
  155836. Fts3Cursor *pCsr, /* FTS Cursor handle */
  155837. Fts3Expr *pRoot, /* Root of current AND/NEAR cluster */
  155838. Fts3Expr *pExpr, /* Expression to consider */
  155839. Fts3TokenAndCost **ppTC, /* Write new entries to *(*ppTC)++ */
  155840. Fts3Expr ***ppOr, /* Write new OR root to *(*ppOr)++ */
  155841. int *pRc /* IN/OUT: Error code */
  155842. ){
  155843. if( *pRc==SQLITE_OK ){
  155844. if( pExpr->eType==FTSQUERY_PHRASE ){
  155845. Fts3Phrase *pPhrase = pExpr->pPhrase;
  155846. int i;
  155847. for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
  155848. Fts3TokenAndCost *pTC = (*ppTC)++;
  155849. pTC->pPhrase = pPhrase;
  155850. pTC->iToken = i;
  155851. pTC->pRoot = pRoot;
  155852. pTC->pToken = &pPhrase->aToken[i];
  155853. pTC->iCol = pPhrase->iColumn;
  155854. *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
  155855. }
  155856. }else if( pExpr->eType!=FTSQUERY_NOT ){
  155857. assert( pExpr->eType==FTSQUERY_OR
  155858. || pExpr->eType==FTSQUERY_AND
  155859. || pExpr->eType==FTSQUERY_NEAR
  155860. );
  155861. assert( pExpr->pLeft && pExpr->pRight );
  155862. if( pExpr->eType==FTSQUERY_OR ){
  155863. pRoot = pExpr->pLeft;
  155864. **ppOr = pRoot;
  155865. (*ppOr)++;
  155866. }
  155867. fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
  155868. if( pExpr->eType==FTSQUERY_OR ){
  155869. pRoot = pExpr->pRight;
  155870. **ppOr = pRoot;
  155871. (*ppOr)++;
  155872. }
  155873. fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
  155874. }
  155875. }
  155876. }
  155877. /*
  155878. ** Determine the average document (row) size in pages. If successful,
  155879. ** write this value to *pnPage and return SQLITE_OK. Otherwise, return
  155880. ** an SQLite error code.
  155881. **
  155882. ** The average document size in pages is calculated by first calculating
  155883. ** determining the average size in bytes, B. If B is less than the amount
  155884. ** of data that will fit on a single leaf page of an intkey table in
  155885. ** this database, then the average docsize is 1. Otherwise, it is 1 plus
  155886. ** the number of overflow pages consumed by a record B bytes in size.
  155887. */
  155888. static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
  155889. int rc = SQLITE_OK;
  155890. if( pCsr->nRowAvg==0 ){
  155891. /* The average document size, which is required to calculate the cost
  155892. ** of each doclist, has not yet been determined. Read the required
  155893. ** data from the %_stat table to calculate it.
  155894. **
  155895. ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
  155896. ** varints, where nCol is the number of columns in the FTS3 table.
  155897. ** The first varint is the number of documents currently stored in
  155898. ** the table. The following nCol varints contain the total amount of
  155899. ** data stored in all rows of each column of the table, from left
  155900. ** to right.
  155901. */
  155902. Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
  155903. sqlite3_stmt *pStmt;
  155904. sqlite3_int64 nDoc = 0;
  155905. sqlite3_int64 nByte = 0;
  155906. const char *pEnd;
  155907. const char *a;
  155908. rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
  155909. if( rc!=SQLITE_OK ) return rc;
  155910. a = sqlite3_column_blob(pStmt, 0);
  155911. assert( a );
  155912. pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
  155913. a += sqlite3Fts3GetVarint(a, &nDoc);
  155914. while( a<pEnd ){
  155915. a += sqlite3Fts3GetVarint(a, &nByte);
  155916. }
  155917. if( nDoc==0 || nByte==0 ){
  155918. sqlite3_reset(pStmt);
  155919. return FTS_CORRUPT_VTAB;
  155920. }
  155921. pCsr->nDoc = nDoc;
  155922. pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
  155923. assert( pCsr->nRowAvg>0 );
  155924. rc = sqlite3_reset(pStmt);
  155925. }
  155926. *pnPage = pCsr->nRowAvg;
  155927. return rc;
  155928. }
  155929. /*
  155930. ** This function is called to select the tokens (if any) that will be
  155931. ** deferred. The array aTC[] has already been populated when this is
  155932. ** called.
  155933. **
  155934. ** This function is called once for each AND/NEAR cluster in the
  155935. ** expression. Each invocation determines which tokens to defer within
  155936. ** the cluster with root node pRoot. See comments above the definition
  155937. ** of struct Fts3TokenAndCost for more details.
  155938. **
  155939. ** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
  155940. ** called on each token to defer. Otherwise, an SQLite error code is
  155941. ** returned.
  155942. */
  155943. static int fts3EvalSelectDeferred(
  155944. Fts3Cursor *pCsr, /* FTS Cursor handle */
  155945. Fts3Expr *pRoot, /* Consider tokens with this root node */
  155946. Fts3TokenAndCost *aTC, /* Array of expression tokens and costs */
  155947. int nTC /* Number of entries in aTC[] */
  155948. ){
  155949. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  155950. int nDocSize = 0; /* Number of pages per doc loaded */
  155951. int rc = SQLITE_OK; /* Return code */
  155952. int ii; /* Iterator variable for various purposes */
  155953. int nOvfl = 0; /* Total overflow pages used by doclists */
  155954. int nToken = 0; /* Total number of tokens in cluster */
  155955. int nMinEst = 0; /* The minimum count for any phrase so far. */
  155956. int nLoad4 = 1; /* (Phrases that will be loaded)^4. */
  155957. /* Tokens are never deferred for FTS tables created using the content=xxx
  155958. ** option. The reason being that it is not guaranteed that the content
  155959. ** table actually contains the same data as the index. To prevent this from
  155960. ** causing any problems, the deferred token optimization is completely
  155961. ** disabled for content=xxx tables. */
  155962. if( pTab->zContentTbl ){
  155963. return SQLITE_OK;
  155964. }
  155965. /* Count the tokens in this AND/NEAR cluster. If none of the doclists
  155966. ** associated with the tokens spill onto overflow pages, or if there is
  155967. ** only 1 token, exit early. No tokens to defer in this case. */
  155968. for(ii=0; ii<nTC; ii++){
  155969. if( aTC[ii].pRoot==pRoot ){
  155970. nOvfl += aTC[ii].nOvfl;
  155971. nToken++;
  155972. }
  155973. }
  155974. if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
  155975. /* Obtain the average docsize (in pages). */
  155976. rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
  155977. assert( rc!=SQLITE_OK || nDocSize>0 );
  155978. /* Iterate through all tokens in this AND/NEAR cluster, in ascending order
  155979. ** of the number of overflow pages that will be loaded by the pager layer
  155980. ** to retrieve the entire doclist for the token from the full-text index.
  155981. ** Load the doclists for tokens that are either:
  155982. **
  155983. ** a. The cheapest token in the entire query (i.e. the one visited by the
  155984. ** first iteration of this loop), or
  155985. **
  155986. ** b. Part of a multi-token phrase.
  155987. **
  155988. ** After each token doclist is loaded, merge it with the others from the
  155989. ** same phrase and count the number of documents that the merged doclist
  155990. ** contains. Set variable "nMinEst" to the smallest number of documents in
  155991. ** any phrase doclist for which 1 or more token doclists have been loaded.
  155992. ** Let nOther be the number of other phrases for which it is certain that
  155993. ** one or more tokens will not be deferred.
  155994. **
  155995. ** Then, for each token, defer it if loading the doclist would result in
  155996. ** loading N or more overflow pages into memory, where N is computed as:
  155997. **
  155998. ** (nMinEst + 4^nOther - 1) / (4^nOther)
  155999. */
  156000. for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
  156001. int iTC; /* Used to iterate through aTC[] array. */
  156002. Fts3TokenAndCost *pTC = 0; /* Set to cheapest remaining token. */
  156003. /* Set pTC to point to the cheapest remaining token. */
  156004. for(iTC=0; iTC<nTC; iTC++){
  156005. if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot
  156006. && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl)
  156007. ){
  156008. pTC = &aTC[iTC];
  156009. }
  156010. }
  156011. assert( pTC );
  156012. if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
  156013. /* The number of overflow pages to load for this (and therefore all
  156014. ** subsequent) tokens is greater than the estimated number of pages
  156015. ** that will be loaded if all subsequent tokens are deferred.
  156016. */
  156017. Fts3PhraseToken *pToken = pTC->pToken;
  156018. rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
  156019. fts3SegReaderCursorFree(pToken->pSegcsr);
  156020. pToken->pSegcsr = 0;
  156021. }else{
  156022. /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
  156023. ** for-loop. Except, limit the value to 2^24 to prevent it from
  156024. ** overflowing the 32-bit integer it is stored in. */
  156025. if( ii<12 ) nLoad4 = nLoad4*4;
  156026. if( ii==0 || (pTC->pPhrase->nToken>1 && ii!=nToken-1) ){
  156027. /* Either this is the cheapest token in the entire query, or it is
  156028. ** part of a multi-token phrase. Either way, the entire doclist will
  156029. ** (eventually) be loaded into memory. It may as well be now. */
  156030. Fts3PhraseToken *pToken = pTC->pToken;
  156031. int nList = 0;
  156032. char *pList = 0;
  156033. rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
  156034. assert( rc==SQLITE_OK || pList==0 );
  156035. if( rc==SQLITE_OK ){
  156036. rc = fts3EvalPhraseMergeToken(
  156037. pTab, pTC->pPhrase, pTC->iToken,pList,nList
  156038. );
  156039. }
  156040. if( rc==SQLITE_OK ){
  156041. int nCount;
  156042. nCount = fts3DoclistCountDocids(
  156043. pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
  156044. );
  156045. if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
  156046. }
  156047. }
  156048. }
  156049. pTC->pToken = 0;
  156050. }
  156051. return rc;
  156052. }
  156053. /*
  156054. ** This function is called from within the xFilter method. It initializes
  156055. ** the full-text query currently stored in pCsr->pExpr. To iterate through
  156056. ** the results of a query, the caller does:
  156057. **
  156058. ** fts3EvalStart(pCsr);
  156059. ** while( 1 ){
  156060. ** fts3EvalNext(pCsr);
  156061. ** if( pCsr->bEof ) break;
  156062. ** ... return row pCsr->iPrevId to the caller ...
  156063. ** }
  156064. */
  156065. static int fts3EvalStart(Fts3Cursor *pCsr){
  156066. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  156067. int rc = SQLITE_OK;
  156068. int nToken = 0;
  156069. int nOr = 0;
  156070. /* Allocate a MultiSegReader for each token in the expression. */
  156071. fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
  156072. /* Determine which, if any, tokens in the expression should be deferred. */
  156073. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  156074. if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){
  156075. Fts3TokenAndCost *aTC;
  156076. Fts3Expr **apOr;
  156077. aTC = (Fts3TokenAndCost *)sqlite3_malloc64(
  156078. sizeof(Fts3TokenAndCost) * nToken
  156079. + sizeof(Fts3Expr *) * nOr * 2
  156080. );
  156081. apOr = (Fts3Expr **)&aTC[nToken];
  156082. if( !aTC ){
  156083. rc = SQLITE_NOMEM;
  156084. }else{
  156085. int ii;
  156086. Fts3TokenAndCost *pTC = aTC;
  156087. Fts3Expr **ppOr = apOr;
  156088. fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
  156089. nToken = (int)(pTC-aTC);
  156090. nOr = (int)(ppOr-apOr);
  156091. if( rc==SQLITE_OK ){
  156092. rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
  156093. for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
  156094. rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
  156095. }
  156096. }
  156097. sqlite3_free(aTC);
  156098. }
  156099. }
  156100. #endif
  156101. fts3EvalStartReaders(pCsr, pCsr->pExpr, &rc);
  156102. return rc;
  156103. }
  156104. /*
  156105. ** Invalidate the current position list for phrase pPhrase.
  156106. */
  156107. static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
  156108. if( pPhrase->doclist.bFreeList ){
  156109. sqlite3_free(pPhrase->doclist.pList);
  156110. }
  156111. pPhrase->doclist.pList = 0;
  156112. pPhrase->doclist.nList = 0;
  156113. pPhrase->doclist.bFreeList = 0;
  156114. }
  156115. /*
  156116. ** This function is called to edit the position list associated with
  156117. ** the phrase object passed as the fifth argument according to a NEAR
  156118. ** condition. For example:
  156119. **
  156120. ** abc NEAR/5 "def ghi"
  156121. **
  156122. ** Parameter nNear is passed the NEAR distance of the expression (5 in
  156123. ** the example above). When this function is called, *paPoslist points to
  156124. ** the position list, and *pnToken is the number of phrase tokens in, the
  156125. ** phrase on the other side of the NEAR operator to pPhrase. For example,
  156126. ** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
  156127. ** the position list associated with phrase "abc".
  156128. **
  156129. ** All positions in the pPhrase position list that are not sufficiently
  156130. ** close to a position in the *paPoslist position list are removed. If this
  156131. ** leaves 0 positions, zero is returned. Otherwise, non-zero.
  156132. **
  156133. ** Before returning, *paPoslist is set to point to the position lsit
  156134. ** associated with pPhrase. And *pnToken is set to the number of tokens in
  156135. ** pPhrase.
  156136. */
  156137. static int fts3EvalNearTrim(
  156138. int nNear, /* NEAR distance. As in "NEAR/nNear". */
  156139. char *aTmp, /* Temporary space to use */
  156140. char **paPoslist, /* IN/OUT: Position list */
  156141. int *pnToken, /* IN/OUT: Tokens in phrase of *paPoslist */
  156142. Fts3Phrase *pPhrase /* The phrase object to trim the doclist of */
  156143. ){
  156144. int nParam1 = nNear + pPhrase->nToken;
  156145. int nParam2 = nNear + *pnToken;
  156146. int nNew;
  156147. char *p2;
  156148. char *pOut;
  156149. int res;
  156150. assert( pPhrase->doclist.pList );
  156151. p2 = pOut = pPhrase->doclist.pList;
  156152. res = fts3PoslistNearMerge(
  156153. &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
  156154. );
  156155. if( res ){
  156156. nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
  156157. assert( pPhrase->doclist.pList[nNew]=='\0' );
  156158. assert( nNew<=pPhrase->doclist.nList && nNew>0 );
  156159. memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
  156160. pPhrase->doclist.nList = nNew;
  156161. *paPoslist = pPhrase->doclist.pList;
  156162. *pnToken = pPhrase->nToken;
  156163. }
  156164. return res;
  156165. }
  156166. /*
  156167. ** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
  156168. ** Otherwise, it advances the expression passed as the second argument to
  156169. ** point to the next matching row in the database. Expressions iterate through
  156170. ** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
  156171. ** or descending if it is non-zero.
  156172. **
  156173. ** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
  156174. ** successful, the following variables in pExpr are set:
  156175. **
  156176. ** Fts3Expr.bEof (non-zero if EOF - there is no next row)
  156177. ** Fts3Expr.iDocid (valid if bEof==0. The docid of the next row)
  156178. **
  156179. ** If the expression is of type FTSQUERY_PHRASE, and the expression is not
  156180. ** at EOF, then the following variables are populated with the position list
  156181. ** for the phrase for the visited row:
  156182. **
  156183. ** FTs3Expr.pPhrase->doclist.nList (length of pList in bytes)
  156184. ** FTs3Expr.pPhrase->doclist.pList (pointer to position list)
  156185. **
  156186. ** It says above that this function advances the expression to the next
  156187. ** matching row. This is usually true, but there are the following exceptions:
  156188. **
  156189. ** 1. Deferred tokens are not taken into account. If a phrase consists
  156190. ** entirely of deferred tokens, it is assumed to match every row in
  156191. ** the db. In this case the position-list is not populated at all.
  156192. **
  156193. ** Or, if a phrase contains one or more deferred tokens and one or
  156194. ** more non-deferred tokens, then the expression is advanced to the
  156195. ** next possible match, considering only non-deferred tokens. In other
  156196. ** words, if the phrase is "A B C", and "B" is deferred, the expression
  156197. ** is advanced to the next row that contains an instance of "A * C",
  156198. ** where "*" may match any single token. The position list in this case
  156199. ** is populated as for "A * C" before returning.
  156200. **
  156201. ** 2. NEAR is treated as AND. If the expression is "x NEAR y", it is
  156202. ** advanced to point to the next row that matches "x AND y".
  156203. **
  156204. ** See sqlite3Fts3EvalTestDeferred() for details on testing if a row is
  156205. ** really a match, taking into account deferred tokens and NEAR operators.
  156206. */
  156207. static void fts3EvalNextRow(
  156208. Fts3Cursor *pCsr, /* FTS Cursor handle */
  156209. Fts3Expr *pExpr, /* Expr. to advance to next matching row */
  156210. int *pRc /* IN/OUT: Error code */
  156211. ){
  156212. if( *pRc==SQLITE_OK ){
  156213. int bDescDoclist = pCsr->bDesc; /* Used by DOCID_CMP() macro */
  156214. assert( pExpr->bEof==0 );
  156215. pExpr->bStart = 1;
  156216. switch( pExpr->eType ){
  156217. case FTSQUERY_NEAR:
  156218. case FTSQUERY_AND: {
  156219. Fts3Expr *pLeft = pExpr->pLeft;
  156220. Fts3Expr *pRight = pExpr->pRight;
  156221. assert( !pLeft->bDeferred || !pRight->bDeferred );
  156222. if( pLeft->bDeferred ){
  156223. /* LHS is entirely deferred. So we assume it matches every row.
  156224. ** Advance the RHS iterator to find the next row visited. */
  156225. fts3EvalNextRow(pCsr, pRight, pRc);
  156226. pExpr->iDocid = pRight->iDocid;
  156227. pExpr->bEof = pRight->bEof;
  156228. }else if( pRight->bDeferred ){
  156229. /* RHS is entirely deferred. So we assume it matches every row.
  156230. ** Advance the LHS iterator to find the next row visited. */
  156231. fts3EvalNextRow(pCsr, pLeft, pRc);
  156232. pExpr->iDocid = pLeft->iDocid;
  156233. pExpr->bEof = pLeft->bEof;
  156234. }else{
  156235. /* Neither the RHS or LHS are deferred. */
  156236. fts3EvalNextRow(pCsr, pLeft, pRc);
  156237. fts3EvalNextRow(pCsr, pRight, pRc);
  156238. while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
  156239. sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  156240. if( iDiff==0 ) break;
  156241. if( iDiff<0 ){
  156242. fts3EvalNextRow(pCsr, pLeft, pRc);
  156243. }else{
  156244. fts3EvalNextRow(pCsr, pRight, pRc);
  156245. }
  156246. }
  156247. pExpr->iDocid = pLeft->iDocid;
  156248. pExpr->bEof = (pLeft->bEof || pRight->bEof);
  156249. if( pExpr->eType==FTSQUERY_NEAR && pExpr->bEof ){
  156250. assert( pRight->eType==FTSQUERY_PHRASE );
  156251. if( pRight->pPhrase->doclist.aAll ){
  156252. Fts3Doclist *pDl = &pRight->pPhrase->doclist;
  156253. while( *pRc==SQLITE_OK && pRight->bEof==0 ){
  156254. memset(pDl->pList, 0, pDl->nList);
  156255. fts3EvalNextRow(pCsr, pRight, pRc);
  156256. }
  156257. }
  156258. if( pLeft->pPhrase && pLeft->pPhrase->doclist.aAll ){
  156259. Fts3Doclist *pDl = &pLeft->pPhrase->doclist;
  156260. while( *pRc==SQLITE_OK && pLeft->bEof==0 ){
  156261. memset(pDl->pList, 0, pDl->nList);
  156262. fts3EvalNextRow(pCsr, pLeft, pRc);
  156263. }
  156264. }
  156265. }
  156266. }
  156267. break;
  156268. }
  156269. case FTSQUERY_OR: {
  156270. Fts3Expr *pLeft = pExpr->pLeft;
  156271. Fts3Expr *pRight = pExpr->pRight;
  156272. sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  156273. assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
  156274. assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
  156275. if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
  156276. fts3EvalNextRow(pCsr, pLeft, pRc);
  156277. }else if( pLeft->bEof || iCmp>0 ){
  156278. fts3EvalNextRow(pCsr, pRight, pRc);
  156279. }else{
  156280. fts3EvalNextRow(pCsr, pLeft, pRc);
  156281. fts3EvalNextRow(pCsr, pRight, pRc);
  156282. }
  156283. pExpr->bEof = (pLeft->bEof && pRight->bEof);
  156284. iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  156285. if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
  156286. pExpr->iDocid = pLeft->iDocid;
  156287. }else{
  156288. pExpr->iDocid = pRight->iDocid;
  156289. }
  156290. break;
  156291. }
  156292. case FTSQUERY_NOT: {
  156293. Fts3Expr *pLeft = pExpr->pLeft;
  156294. Fts3Expr *pRight = pExpr->pRight;
  156295. if( pRight->bStart==0 ){
  156296. fts3EvalNextRow(pCsr, pRight, pRc);
  156297. assert( *pRc!=SQLITE_OK || pRight->bStart );
  156298. }
  156299. fts3EvalNextRow(pCsr, pLeft, pRc);
  156300. if( pLeft->bEof==0 ){
  156301. while( !*pRc
  156302. && !pRight->bEof
  156303. && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0
  156304. ){
  156305. fts3EvalNextRow(pCsr, pRight, pRc);
  156306. }
  156307. }
  156308. pExpr->iDocid = pLeft->iDocid;
  156309. pExpr->bEof = pLeft->bEof;
  156310. break;
  156311. }
  156312. default: {
  156313. Fts3Phrase *pPhrase = pExpr->pPhrase;
  156314. fts3EvalInvalidatePoslist(pPhrase);
  156315. *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
  156316. pExpr->iDocid = pPhrase->doclist.iDocid;
  156317. break;
  156318. }
  156319. }
  156320. }
  156321. }
  156322. /*
  156323. ** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
  156324. ** cluster, then this function returns 1 immediately.
  156325. **
  156326. ** Otherwise, it checks if the current row really does match the NEAR
  156327. ** expression, using the data currently stored in the position lists
  156328. ** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression.
  156329. **
  156330. ** If the current row is a match, the position list associated with each
  156331. ** phrase in the NEAR expression is edited in place to contain only those
  156332. ** phrase instances sufficiently close to their peers to satisfy all NEAR
  156333. ** constraints. In this case it returns 1. If the NEAR expression does not
  156334. ** match the current row, 0 is returned. The position lists may or may not
  156335. ** be edited if 0 is returned.
  156336. */
  156337. static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
  156338. int res = 1;
  156339. /* The following block runs if pExpr is the root of a NEAR query.
  156340. ** For example, the query:
  156341. **
  156342. ** "w" NEAR "x" NEAR "y" NEAR "z"
  156343. **
  156344. ** which is represented in tree form as:
  156345. **
  156346. ** |
  156347. ** +--NEAR--+ <-- root of NEAR query
  156348. ** | |
  156349. ** +--NEAR--+ "z"
  156350. ** | |
  156351. ** +--NEAR--+ "y"
  156352. ** | |
  156353. ** "w" "x"
  156354. **
  156355. ** The right-hand child of a NEAR node is always a phrase. The
  156356. ** left-hand child may be either a phrase or a NEAR node. There are
  156357. ** no exceptions to this - it's the way the parser in fts3_expr.c works.
  156358. */
  156359. if( *pRc==SQLITE_OK
  156360. && pExpr->eType==FTSQUERY_NEAR
  156361. && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
  156362. ){
  156363. Fts3Expr *p;
  156364. sqlite3_int64 nTmp = 0; /* Bytes of temp space */
  156365. char *aTmp; /* Temp space for PoslistNearMerge() */
  156366. /* Allocate temporary working space. */
  156367. for(p=pExpr; p->pLeft; p=p->pLeft){
  156368. assert( p->pRight->pPhrase->doclist.nList>0 );
  156369. nTmp += p->pRight->pPhrase->doclist.nList;
  156370. }
  156371. nTmp += p->pPhrase->doclist.nList;
  156372. aTmp = sqlite3_malloc64(nTmp*2);
  156373. if( !aTmp ){
  156374. *pRc = SQLITE_NOMEM;
  156375. res = 0;
  156376. }else{
  156377. char *aPoslist = p->pPhrase->doclist.pList;
  156378. int nToken = p->pPhrase->nToken;
  156379. for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
  156380. Fts3Phrase *pPhrase = p->pRight->pPhrase;
  156381. int nNear = p->nNear;
  156382. res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
  156383. }
  156384. aPoslist = pExpr->pRight->pPhrase->doclist.pList;
  156385. nToken = pExpr->pRight->pPhrase->nToken;
  156386. for(p=pExpr->pLeft; p && res; p=p->pLeft){
  156387. int nNear;
  156388. Fts3Phrase *pPhrase;
  156389. assert( p->pParent && p->pParent->pLeft==p );
  156390. nNear = p->pParent->nNear;
  156391. pPhrase = (
  156392. p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
  156393. );
  156394. res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
  156395. }
  156396. }
  156397. sqlite3_free(aTmp);
  156398. }
  156399. return res;
  156400. }
  156401. /*
  156402. ** This function is a helper function for sqlite3Fts3EvalTestDeferred().
  156403. ** Assuming no error occurs or has occurred, It returns non-zero if the
  156404. ** expression passed as the second argument matches the row that pCsr
  156405. ** currently points to, or zero if it does not.
  156406. **
  156407. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  156408. ** If an error occurs during execution of this function, *pRc is set to
  156409. ** the appropriate SQLite error code. In this case the returned value is
  156410. ** undefined.
  156411. */
  156412. static int fts3EvalTestExpr(
  156413. Fts3Cursor *pCsr, /* FTS cursor handle */
  156414. Fts3Expr *pExpr, /* Expr to test. May or may not be root. */
  156415. int *pRc /* IN/OUT: Error code */
  156416. ){
  156417. int bHit = 1; /* Return value */
  156418. if( *pRc==SQLITE_OK ){
  156419. switch( pExpr->eType ){
  156420. case FTSQUERY_NEAR:
  156421. case FTSQUERY_AND:
  156422. bHit = (
  156423. fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
  156424. && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
  156425. && fts3EvalNearTest(pExpr, pRc)
  156426. );
  156427. /* If the NEAR expression does not match any rows, zero the doclist for
  156428. ** all phrases involved in the NEAR. This is because the snippet(),
  156429. ** offsets() and matchinfo() functions are not supposed to recognize
  156430. ** any instances of phrases that are part of unmatched NEAR queries.
  156431. ** For example if this expression:
  156432. **
  156433. ** ... MATCH 'a OR (b NEAR c)'
  156434. **
  156435. ** is matched against a row containing:
  156436. **
  156437. ** 'a b d e'
  156438. **
  156439. ** then any snippet() should ony highlight the "a" term, not the "b"
  156440. ** (as "b" is part of a non-matching NEAR clause).
  156441. */
  156442. if( bHit==0
  156443. && pExpr->eType==FTSQUERY_NEAR
  156444. && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
  156445. ){
  156446. Fts3Expr *p;
  156447. for(p=pExpr; p->pPhrase==0; p=p->pLeft){
  156448. if( p->pRight->iDocid==pCsr->iPrevId ){
  156449. fts3EvalInvalidatePoslist(p->pRight->pPhrase);
  156450. }
  156451. }
  156452. if( p->iDocid==pCsr->iPrevId ){
  156453. fts3EvalInvalidatePoslist(p->pPhrase);
  156454. }
  156455. }
  156456. break;
  156457. case FTSQUERY_OR: {
  156458. int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
  156459. int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
  156460. bHit = bHit1 || bHit2;
  156461. break;
  156462. }
  156463. case FTSQUERY_NOT:
  156464. bHit = (
  156465. fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
  156466. && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
  156467. );
  156468. break;
  156469. default: {
  156470. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  156471. if( pCsr->pDeferred
  156472. && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
  156473. ){
  156474. Fts3Phrase *pPhrase = pExpr->pPhrase;
  156475. assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
  156476. if( pExpr->bDeferred ){
  156477. fts3EvalInvalidatePoslist(pPhrase);
  156478. }
  156479. *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
  156480. bHit = (pPhrase->doclist.pList!=0);
  156481. pExpr->iDocid = pCsr->iPrevId;
  156482. }else
  156483. #endif
  156484. {
  156485. bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
  156486. }
  156487. break;
  156488. }
  156489. }
  156490. }
  156491. return bHit;
  156492. }
  156493. /*
  156494. ** This function is called as the second part of each xNext operation when
  156495. ** iterating through the results of a full-text query. At this point the
  156496. ** cursor points to a row that matches the query expression, with the
  156497. ** following caveats:
  156498. **
  156499. ** * Up until this point, "NEAR" operators in the expression have been
  156500. ** treated as "AND".
  156501. **
  156502. ** * Deferred tokens have not yet been considered.
  156503. **
  156504. ** If *pRc is not SQLITE_OK when this function is called, it immediately
  156505. ** returns 0. Otherwise, it tests whether or not after considering NEAR
  156506. ** operators and deferred tokens the current row is still a match for the
  156507. ** expression. It returns 1 if both of the following are true:
  156508. **
  156509. ** 1. *pRc is SQLITE_OK when this function returns, and
  156510. **
  156511. ** 2. After scanning the current FTS table row for the deferred tokens,
  156512. ** it is determined that the row does *not* match the query.
  156513. **
  156514. ** Or, if no error occurs and it seems the current row does match the FTS
  156515. ** query, return 0.
  156516. */
  156517. SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc){
  156518. int rc = *pRc;
  156519. int bMiss = 0;
  156520. if( rc==SQLITE_OK ){
  156521. /* If there are one or more deferred tokens, load the current row into
  156522. ** memory and scan it to determine the position list for each deferred
  156523. ** token. Then, see if this row is really a match, considering deferred
  156524. ** tokens and NEAR operators (neither of which were taken into account
  156525. ** earlier, by fts3EvalNextRow()).
  156526. */
  156527. if( pCsr->pDeferred ){
  156528. rc = fts3CursorSeek(0, pCsr);
  156529. if( rc==SQLITE_OK ){
  156530. rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
  156531. }
  156532. }
  156533. bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
  156534. /* Free the position-lists accumulated for each deferred token above. */
  156535. sqlite3Fts3FreeDeferredDoclists(pCsr);
  156536. *pRc = rc;
  156537. }
  156538. return (rc==SQLITE_OK && bMiss);
  156539. }
  156540. /*
  156541. ** Advance to the next document that matches the FTS expression in
  156542. ** Fts3Cursor.pExpr.
  156543. */
  156544. static int fts3EvalNext(Fts3Cursor *pCsr){
  156545. int rc = SQLITE_OK; /* Return Code */
  156546. Fts3Expr *pExpr = pCsr->pExpr;
  156547. assert( pCsr->isEof==0 );
  156548. if( pExpr==0 ){
  156549. pCsr->isEof = 1;
  156550. }else{
  156551. do {
  156552. if( pCsr->isRequireSeek==0 ){
  156553. sqlite3_reset(pCsr->pStmt);
  156554. }
  156555. assert( sqlite3_data_count(pCsr->pStmt)==0 );
  156556. fts3EvalNextRow(pCsr, pExpr, &rc);
  156557. pCsr->isEof = pExpr->bEof;
  156558. pCsr->isRequireSeek = 1;
  156559. pCsr->isMatchinfoNeeded = 1;
  156560. pCsr->iPrevId = pExpr->iDocid;
  156561. }while( pCsr->isEof==0 && sqlite3Fts3EvalTestDeferred(pCsr, &rc) );
  156562. }
  156563. /* Check if the cursor is past the end of the docid range specified
  156564. ** by Fts3Cursor.iMinDocid/iMaxDocid. If so, set the EOF flag. */
  156565. if( rc==SQLITE_OK && (
  156566. (pCsr->bDesc==0 && pCsr->iPrevId>pCsr->iMaxDocid)
  156567. || (pCsr->bDesc!=0 && pCsr->iPrevId<pCsr->iMinDocid)
  156568. )){
  156569. pCsr->isEof = 1;
  156570. }
  156571. return rc;
  156572. }
  156573. /*
  156574. ** Restart interation for expression pExpr so that the next call to
  156575. ** fts3EvalNext() visits the first row. Do not allow incremental
  156576. ** loading or merging of phrase doclists for this iteration.
  156577. **
  156578. ** If *pRc is other than SQLITE_OK when this function is called, it is
  156579. ** a no-op. If an error occurs within this function, *pRc is set to an
  156580. ** SQLite error code before returning.
  156581. */
  156582. static void fts3EvalRestart(
  156583. Fts3Cursor *pCsr,
  156584. Fts3Expr *pExpr,
  156585. int *pRc
  156586. ){
  156587. if( pExpr && *pRc==SQLITE_OK ){
  156588. Fts3Phrase *pPhrase = pExpr->pPhrase;
  156589. if( pPhrase ){
  156590. fts3EvalInvalidatePoslist(pPhrase);
  156591. if( pPhrase->bIncr ){
  156592. int i;
  156593. for(i=0; i<pPhrase->nToken; i++){
  156594. Fts3PhraseToken *pToken = &pPhrase->aToken[i];
  156595. assert( pToken->pDeferred==0 );
  156596. if( pToken->pSegcsr ){
  156597. sqlite3Fts3MsrIncrRestart(pToken->pSegcsr);
  156598. }
  156599. }
  156600. *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
  156601. }
  156602. pPhrase->doclist.pNextDocid = 0;
  156603. pPhrase->doclist.iDocid = 0;
  156604. pPhrase->pOrPoslist = 0;
  156605. }
  156606. pExpr->iDocid = 0;
  156607. pExpr->bEof = 0;
  156608. pExpr->bStart = 0;
  156609. fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
  156610. fts3EvalRestart(pCsr, pExpr->pRight, pRc);
  156611. }
  156612. }
  156613. /*
  156614. ** After allocating the Fts3Expr.aMI[] array for each phrase in the
  156615. ** expression rooted at pExpr, the cursor iterates through all rows matched
  156616. ** by pExpr, calling this function for each row. This function increments
  156617. ** the values in Fts3Expr.aMI[] according to the position-list currently
  156618. ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase
  156619. ** expression nodes.
  156620. */
  156621. static void fts3EvalUpdateCounts(Fts3Expr *pExpr, int nCol){
  156622. if( pExpr ){
  156623. Fts3Phrase *pPhrase = pExpr->pPhrase;
  156624. if( pPhrase && pPhrase->doclist.pList ){
  156625. int iCol = 0;
  156626. char *p = pPhrase->doclist.pList;
  156627. do{
  156628. u8 c = 0;
  156629. int iCnt = 0;
  156630. while( 0xFE & (*p | c) ){
  156631. if( (c&0x80)==0 ) iCnt++;
  156632. c = *p++ & 0x80;
  156633. }
  156634. /* aMI[iCol*3 + 1] = Number of occurrences
  156635. ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
  156636. */
  156637. pExpr->aMI[iCol*3 + 1] += iCnt;
  156638. pExpr->aMI[iCol*3 + 2] += (iCnt>0);
  156639. if( *p==0x00 ) break;
  156640. p++;
  156641. p += fts3GetVarint32(p, &iCol);
  156642. }while( iCol<nCol );
  156643. }
  156644. fts3EvalUpdateCounts(pExpr->pLeft, nCol);
  156645. fts3EvalUpdateCounts(pExpr->pRight, nCol);
  156646. }
  156647. }
  156648. /*
  156649. ** Expression pExpr must be of type FTSQUERY_PHRASE.
  156650. **
  156651. ** If it is not already allocated and populated, this function allocates and
  156652. ** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
  156653. ** of a NEAR expression, then it also allocates and populates the same array
  156654. ** for all other phrases that are part of the NEAR expression.
  156655. **
  156656. ** SQLITE_OK is returned if the aMI[] array is successfully allocated and
  156657. ** populated. Otherwise, if an error occurs, an SQLite error code is returned.
  156658. */
  156659. static int fts3EvalGatherStats(
  156660. Fts3Cursor *pCsr, /* Cursor object */
  156661. Fts3Expr *pExpr /* FTSQUERY_PHRASE expression */
  156662. ){
  156663. int rc = SQLITE_OK; /* Return code */
  156664. assert( pExpr->eType==FTSQUERY_PHRASE );
  156665. if( pExpr->aMI==0 ){
  156666. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  156667. Fts3Expr *pRoot; /* Root of NEAR expression */
  156668. Fts3Expr *p; /* Iterator used for several purposes */
  156669. sqlite3_int64 iPrevId = pCsr->iPrevId;
  156670. sqlite3_int64 iDocid;
  156671. u8 bEof;
  156672. /* Find the root of the NEAR expression */
  156673. pRoot = pExpr;
  156674. while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
  156675. pRoot = pRoot->pParent;
  156676. }
  156677. iDocid = pRoot->iDocid;
  156678. bEof = pRoot->bEof;
  156679. assert( pRoot->bStart );
  156680. /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
  156681. for(p=pRoot; p; p=p->pLeft){
  156682. Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
  156683. assert( pE->aMI==0 );
  156684. pE->aMI = (u32 *)sqlite3_malloc64(pTab->nColumn * 3 * sizeof(u32));
  156685. if( !pE->aMI ) return SQLITE_NOMEM;
  156686. memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
  156687. }
  156688. fts3EvalRestart(pCsr, pRoot, &rc);
  156689. while( pCsr->isEof==0 && rc==SQLITE_OK ){
  156690. do {
  156691. /* Ensure the %_content statement is reset. */
  156692. if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
  156693. assert( sqlite3_data_count(pCsr->pStmt)==0 );
  156694. /* Advance to the next document */
  156695. fts3EvalNextRow(pCsr, pRoot, &rc);
  156696. pCsr->isEof = pRoot->bEof;
  156697. pCsr->isRequireSeek = 1;
  156698. pCsr->isMatchinfoNeeded = 1;
  156699. pCsr->iPrevId = pRoot->iDocid;
  156700. }while( pCsr->isEof==0
  156701. && pRoot->eType==FTSQUERY_NEAR
  156702. && sqlite3Fts3EvalTestDeferred(pCsr, &rc)
  156703. );
  156704. if( rc==SQLITE_OK && pCsr->isEof==0 ){
  156705. fts3EvalUpdateCounts(pRoot, pTab->nColumn);
  156706. }
  156707. }
  156708. pCsr->isEof = 0;
  156709. pCsr->iPrevId = iPrevId;
  156710. if( bEof ){
  156711. pRoot->bEof = bEof;
  156712. }else{
  156713. /* Caution: pRoot may iterate through docids in ascending or descending
  156714. ** order. For this reason, even though it seems more defensive, the
  156715. ** do loop can not be written:
  156716. **
  156717. ** do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
  156718. */
  156719. fts3EvalRestart(pCsr, pRoot, &rc);
  156720. do {
  156721. fts3EvalNextRow(pCsr, pRoot, &rc);
  156722. assert( pRoot->bEof==0 );
  156723. }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
  156724. }
  156725. }
  156726. return rc;
  156727. }
  156728. /*
  156729. ** This function is used by the matchinfo() module to query a phrase
  156730. ** expression node for the following information:
  156731. **
  156732. ** 1. The total number of occurrences of the phrase in each column of
  156733. ** the FTS table (considering all rows), and
  156734. **
  156735. ** 2. For each column, the number of rows in the table for which the
  156736. ** column contains at least one instance of the phrase.
  156737. **
  156738. ** If no error occurs, SQLITE_OK is returned and the values for each column
  156739. ** written into the array aiOut as follows:
  156740. **
  156741. ** aiOut[iCol*3 + 1] = Number of occurrences
  156742. ** aiOut[iCol*3 + 2] = Number of rows containing at least one instance
  156743. **
  156744. ** Caveats:
  156745. **
  156746. ** * If a phrase consists entirely of deferred tokens, then all output
  156747. ** values are set to the number of documents in the table. In other
  156748. ** words we assume that very common tokens occur exactly once in each
  156749. ** column of each row of the table.
  156750. **
  156751. ** * If a phrase contains some deferred tokens (and some non-deferred
  156752. ** tokens), count the potential occurrence identified by considering
  156753. ** the non-deferred tokens instead of actual phrase occurrences.
  156754. **
  156755. ** * If the phrase is part of a NEAR expression, then only phrase instances
  156756. ** that meet the NEAR constraint are included in the counts.
  156757. */
  156758. SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
  156759. Fts3Cursor *pCsr, /* FTS cursor handle */
  156760. Fts3Expr *pExpr, /* Phrase expression */
  156761. u32 *aiOut /* Array to write results into (see above) */
  156762. ){
  156763. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  156764. int rc = SQLITE_OK;
  156765. int iCol;
  156766. if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
  156767. assert( pCsr->nDoc>0 );
  156768. for(iCol=0; iCol<pTab->nColumn; iCol++){
  156769. aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
  156770. aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
  156771. }
  156772. }else{
  156773. rc = fts3EvalGatherStats(pCsr, pExpr);
  156774. if( rc==SQLITE_OK ){
  156775. assert( pExpr->aMI );
  156776. for(iCol=0; iCol<pTab->nColumn; iCol++){
  156777. aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
  156778. aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
  156779. }
  156780. }
  156781. }
  156782. return rc;
  156783. }
  156784. /*
  156785. ** The expression pExpr passed as the second argument to this function
  156786. ** must be of type FTSQUERY_PHRASE.
  156787. **
  156788. ** The returned value is either NULL or a pointer to a buffer containing
  156789. ** a position-list indicating the occurrences of the phrase in column iCol
  156790. ** of the current row.
  156791. **
  156792. ** More specifically, the returned buffer contains 1 varint for each
  156793. ** occurrence of the phrase in the column, stored using the normal (delta+2)
  156794. ** compression and is terminated by either an 0x01 or 0x00 byte. For example,
  156795. ** if the requested column contains "a b X c d X X" and the position-list
  156796. ** for 'X' is requested, the buffer returned may contain:
  156797. **
  156798. ** 0x04 0x05 0x03 0x01 or 0x04 0x05 0x03 0x00
  156799. **
  156800. ** This function works regardless of whether or not the phrase is deferred,
  156801. ** incremental, or neither.
  156802. */
  156803. SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
  156804. Fts3Cursor *pCsr, /* FTS3 cursor object */
  156805. Fts3Expr *pExpr, /* Phrase to return doclist for */
  156806. int iCol, /* Column to return position list for */
  156807. char **ppOut /* OUT: Pointer to position list */
  156808. ){
  156809. Fts3Phrase *pPhrase = pExpr->pPhrase;
  156810. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  156811. char *pIter;
  156812. int iThis;
  156813. sqlite3_int64 iDocid;
  156814. /* If this phrase is applies specifically to some column other than
  156815. ** column iCol, return a NULL pointer. */
  156816. *ppOut = 0;
  156817. assert( iCol>=0 && iCol<pTab->nColumn );
  156818. if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){
  156819. return SQLITE_OK;
  156820. }
  156821. iDocid = pExpr->iDocid;
  156822. pIter = pPhrase->doclist.pList;
  156823. if( iDocid!=pCsr->iPrevId || pExpr->bEof ){
  156824. int rc = SQLITE_OK;
  156825. int bDescDoclist = pTab->bDescIdx; /* For DOCID_CMP macro */
  156826. int bOr = 0;
  156827. u8 bTreeEof = 0;
  156828. Fts3Expr *p; /* Used to iterate from pExpr to root */
  156829. Fts3Expr *pNear; /* Most senior NEAR ancestor (or pExpr) */
  156830. int bMatch;
  156831. /* Check if this phrase descends from an OR expression node. If not,
  156832. ** return NULL. Otherwise, the entry that corresponds to docid
  156833. ** pCsr->iPrevId may lie earlier in the doclist buffer. Or, if the
  156834. ** tree that the node is part of has been marked as EOF, but the node
  156835. ** itself is not EOF, then it may point to an earlier entry. */
  156836. pNear = pExpr;
  156837. for(p=pExpr->pParent; p; p=p->pParent){
  156838. if( p->eType==FTSQUERY_OR ) bOr = 1;
  156839. if( p->eType==FTSQUERY_NEAR ) pNear = p;
  156840. if( p->bEof ) bTreeEof = 1;
  156841. }
  156842. if( bOr==0 ) return SQLITE_OK;
  156843. /* This is the descendent of an OR node. In this case we cannot use
  156844. ** an incremental phrase. Load the entire doclist for the phrase
  156845. ** into memory in this case. */
  156846. if( pPhrase->bIncr ){
  156847. int bEofSave = pNear->bEof;
  156848. fts3EvalRestart(pCsr, pNear, &rc);
  156849. while( rc==SQLITE_OK && !pNear->bEof ){
  156850. fts3EvalNextRow(pCsr, pNear, &rc);
  156851. if( bEofSave==0 && pNear->iDocid==iDocid ) break;
  156852. }
  156853. assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );
  156854. }
  156855. if( bTreeEof ){
  156856. while( rc==SQLITE_OK && !pNear->bEof ){
  156857. fts3EvalNextRow(pCsr, pNear, &rc);
  156858. }
  156859. }
  156860. if( rc!=SQLITE_OK ) return rc;
  156861. bMatch = 1;
  156862. for(p=pNear; p; p=p->pLeft){
  156863. u8 bEof = 0;
  156864. Fts3Expr *pTest = p;
  156865. Fts3Phrase *pPh;
  156866. assert( pTest->eType==FTSQUERY_NEAR || pTest->eType==FTSQUERY_PHRASE );
  156867. if( pTest->eType==FTSQUERY_NEAR ) pTest = pTest->pRight;
  156868. assert( pTest->eType==FTSQUERY_PHRASE );
  156869. pPh = pTest->pPhrase;
  156870. pIter = pPh->pOrPoslist;
  156871. iDocid = pPh->iOrDocid;
  156872. if( pCsr->bDesc==bDescDoclist ){
  156873. bEof = !pPh->doclist.nAll ||
  156874. (pIter >= (pPh->doclist.aAll + pPh->doclist.nAll));
  156875. while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
  156876. sqlite3Fts3DoclistNext(
  156877. bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll,
  156878. &pIter, &iDocid, &bEof
  156879. );
  156880. }
  156881. }else{
  156882. bEof = !pPh->doclist.nAll || (pIter && pIter<=pPh->doclist.aAll);
  156883. while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
  156884. int dummy;
  156885. sqlite3Fts3DoclistPrev(
  156886. bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll,
  156887. &pIter, &iDocid, &dummy, &bEof
  156888. );
  156889. }
  156890. }
  156891. pPh->pOrPoslist = pIter;
  156892. pPh->iOrDocid = iDocid;
  156893. if( bEof || iDocid!=pCsr->iPrevId ) bMatch = 0;
  156894. }
  156895. if( bMatch ){
  156896. pIter = pPhrase->pOrPoslist;
  156897. }else{
  156898. pIter = 0;
  156899. }
  156900. }
  156901. if( pIter==0 ) return SQLITE_OK;
  156902. if( *pIter==0x01 ){
  156903. pIter++;
  156904. pIter += fts3GetVarint32(pIter, &iThis);
  156905. }else{
  156906. iThis = 0;
  156907. }
  156908. while( iThis<iCol ){
  156909. fts3ColumnlistCopy(0, &pIter);
  156910. if( *pIter==0x00 ) return SQLITE_OK;
  156911. pIter++;
  156912. pIter += fts3GetVarint32(pIter, &iThis);
  156913. }
  156914. if( *pIter==0x00 ){
  156915. pIter = 0;
  156916. }
  156917. *ppOut = ((iCol==iThis)?pIter:0);
  156918. return SQLITE_OK;
  156919. }
  156920. /*
  156921. ** Free all components of the Fts3Phrase structure that were allocated by
  156922. ** the eval module. Specifically, this means to free:
  156923. **
  156924. ** * the contents of pPhrase->doclist, and
  156925. ** * any Fts3MultiSegReader objects held by phrase tokens.
  156926. */
  156927. SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
  156928. if( pPhrase ){
  156929. int i;
  156930. sqlite3_free(pPhrase->doclist.aAll);
  156931. fts3EvalInvalidatePoslist(pPhrase);
  156932. memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
  156933. for(i=0; i<pPhrase->nToken; i++){
  156934. fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
  156935. pPhrase->aToken[i].pSegcsr = 0;
  156936. }
  156937. }
  156938. }
  156939. /*
  156940. ** Return SQLITE_CORRUPT_VTAB.
  156941. */
  156942. #ifdef SQLITE_DEBUG
  156943. SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
  156944. return SQLITE_CORRUPT_VTAB;
  156945. }
  156946. #endif
  156947. #if !SQLITE_CORE
  156948. /*
  156949. ** Initialize API pointer table, if required.
  156950. */
  156951. #ifdef _WIN32
  156952. __declspec(dllexport)
  156953. #endif
  156954. SQLITE_API int sqlite3_fts3_init(
  156955. sqlite3 *db,
  156956. char **pzErrMsg,
  156957. const sqlite3_api_routines *pApi
  156958. ){
  156959. SQLITE_EXTENSION_INIT2(pApi)
  156960. return sqlite3Fts3Init(db);
  156961. }
  156962. #endif
  156963. #endif
  156964. /************** End of fts3.c ************************************************/
  156965. /************** Begin file fts3_aux.c ****************************************/
  156966. /*
  156967. ** 2011 Jan 27
  156968. **
  156969. ** The author disclaims copyright to this source code. In place of
  156970. ** a legal notice, here is a blessing:
  156971. **
  156972. ** May you do good and not evil.
  156973. ** May you find forgiveness for yourself and forgive others.
  156974. ** May you share freely, never taking more than you give.
  156975. **
  156976. ******************************************************************************
  156977. **
  156978. */
  156979. /* #include "fts3Int.h" */
  156980. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  156981. /* #include <string.h> */
  156982. /* #include <assert.h> */
  156983. typedef struct Fts3auxTable Fts3auxTable;
  156984. typedef struct Fts3auxCursor Fts3auxCursor;
  156985. struct Fts3auxTable {
  156986. sqlite3_vtab base; /* Base class used by SQLite core */
  156987. Fts3Table *pFts3Tab;
  156988. };
  156989. struct Fts3auxCursor {
  156990. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  156991. Fts3MultiSegReader csr; /* Must be right after "base" */
  156992. Fts3SegFilter filter;
  156993. char *zStop;
  156994. int nStop; /* Byte-length of string zStop */
  156995. int iLangid; /* Language id to query */
  156996. int isEof; /* True if cursor is at EOF */
  156997. sqlite3_int64 iRowid; /* Current rowid */
  156998. int iCol; /* Current value of 'col' column */
  156999. int nStat; /* Size of aStat[] array */
  157000. struct Fts3auxColstats {
  157001. sqlite3_int64 nDoc; /* 'documents' values for current csr row */
  157002. sqlite3_int64 nOcc; /* 'occurrences' values for current csr row */
  157003. } *aStat;
  157004. };
  157005. /*
  157006. ** Schema of the terms table.
  157007. */
  157008. #define FTS3_AUX_SCHEMA \
  157009. "CREATE TABLE x(term, col, documents, occurrences, languageid HIDDEN)"
  157010. /*
  157011. ** This function does all the work for both the xConnect and xCreate methods.
  157012. ** These tables have no persistent representation of their own, so xConnect
  157013. ** and xCreate are identical operations.
  157014. */
  157015. static int fts3auxConnectMethod(
  157016. sqlite3 *db, /* Database connection */
  157017. void *pUnused, /* Unused */
  157018. int argc, /* Number of elements in argv array */
  157019. const char * const *argv, /* xCreate/xConnect argument array */
  157020. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  157021. char **pzErr /* OUT: sqlite3_malloc'd error message */
  157022. ){
  157023. char const *zDb; /* Name of database (e.g. "main") */
  157024. char const *zFts3; /* Name of fts3 table */
  157025. int nDb; /* Result of strlen(zDb) */
  157026. int nFts3; /* Result of strlen(zFts3) */
  157027. sqlite3_int64 nByte; /* Bytes of space to allocate here */
  157028. int rc; /* value returned by declare_vtab() */
  157029. Fts3auxTable *p; /* Virtual table object to return */
  157030. UNUSED_PARAMETER(pUnused);
  157031. /* The user should invoke this in one of two forms:
  157032. **
  157033. ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table);
  157034. ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table-db, fts4-table);
  157035. */
  157036. if( argc!=4 && argc!=5 ) goto bad_args;
  157037. zDb = argv[1];
  157038. nDb = (int)strlen(zDb);
  157039. if( argc==5 ){
  157040. if( nDb==4 && 0==sqlite3_strnicmp("temp", zDb, 4) ){
  157041. zDb = argv[3];
  157042. nDb = (int)strlen(zDb);
  157043. zFts3 = argv[4];
  157044. }else{
  157045. goto bad_args;
  157046. }
  157047. }else{
  157048. zFts3 = argv[3];
  157049. }
  157050. nFts3 = (int)strlen(zFts3);
  157051. rc = sqlite3_declare_vtab(db, FTS3_AUX_SCHEMA);
  157052. if( rc!=SQLITE_OK ) return rc;
  157053. nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
  157054. p = (Fts3auxTable *)sqlite3_malloc64(nByte);
  157055. if( !p ) return SQLITE_NOMEM;
  157056. memset(p, 0, nByte);
  157057. p->pFts3Tab = (Fts3Table *)&p[1];
  157058. p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
  157059. p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
  157060. p->pFts3Tab->db = db;
  157061. p->pFts3Tab->nIndex = 1;
  157062. memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
  157063. memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
  157064. sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
  157065. *ppVtab = (sqlite3_vtab *)p;
  157066. return SQLITE_OK;
  157067. bad_args:
  157068. sqlite3Fts3ErrMsg(pzErr, "invalid arguments to fts4aux constructor");
  157069. return SQLITE_ERROR;
  157070. }
  157071. /*
  157072. ** This function does the work for both the xDisconnect and xDestroy methods.
  157073. ** These tables have no persistent representation of their own, so xDisconnect
  157074. ** and xDestroy are identical operations.
  157075. */
  157076. static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
  157077. Fts3auxTable *p = (Fts3auxTable *)pVtab;
  157078. Fts3Table *pFts3 = p->pFts3Tab;
  157079. int i;
  157080. /* Free any prepared statements held */
  157081. for(i=0; i<SizeofArray(pFts3->aStmt); i++){
  157082. sqlite3_finalize(pFts3->aStmt[i]);
  157083. }
  157084. sqlite3_free(pFts3->zSegmentsTbl);
  157085. sqlite3_free(p);
  157086. return SQLITE_OK;
  157087. }
  157088. #define FTS4AUX_EQ_CONSTRAINT 1
  157089. #define FTS4AUX_GE_CONSTRAINT 2
  157090. #define FTS4AUX_LE_CONSTRAINT 4
  157091. /*
  157092. ** xBestIndex - Analyze a WHERE and ORDER BY clause.
  157093. */
  157094. static int fts3auxBestIndexMethod(
  157095. sqlite3_vtab *pVTab,
  157096. sqlite3_index_info *pInfo
  157097. ){
  157098. int i;
  157099. int iEq = -1;
  157100. int iGe = -1;
  157101. int iLe = -1;
  157102. int iLangid = -1;
  157103. int iNext = 1; /* Next free argvIndex value */
  157104. UNUSED_PARAMETER(pVTab);
  157105. /* This vtab delivers always results in "ORDER BY term ASC" order. */
  157106. if( pInfo->nOrderBy==1
  157107. && pInfo->aOrderBy[0].iColumn==0
  157108. && pInfo->aOrderBy[0].desc==0
  157109. ){
  157110. pInfo->orderByConsumed = 1;
  157111. }
  157112. /* Search for equality and range constraints on the "term" column.
  157113. ** And equality constraints on the hidden "languageid" column. */
  157114. for(i=0; i<pInfo->nConstraint; i++){
  157115. if( pInfo->aConstraint[i].usable ){
  157116. int op = pInfo->aConstraint[i].op;
  157117. int iCol = pInfo->aConstraint[i].iColumn;
  157118. if( iCol==0 ){
  157119. if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
  157120. if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
  157121. if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
  157122. if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
  157123. if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
  157124. }
  157125. if( iCol==4 ){
  157126. if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iLangid = i;
  157127. }
  157128. }
  157129. }
  157130. if( iEq>=0 ){
  157131. pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
  157132. pInfo->aConstraintUsage[iEq].argvIndex = iNext++;
  157133. pInfo->estimatedCost = 5;
  157134. }else{
  157135. pInfo->idxNum = 0;
  157136. pInfo->estimatedCost = 20000;
  157137. if( iGe>=0 ){
  157138. pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
  157139. pInfo->aConstraintUsage[iGe].argvIndex = iNext++;
  157140. pInfo->estimatedCost /= 2;
  157141. }
  157142. if( iLe>=0 ){
  157143. pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
  157144. pInfo->aConstraintUsage[iLe].argvIndex = iNext++;
  157145. pInfo->estimatedCost /= 2;
  157146. }
  157147. }
  157148. if( iLangid>=0 ){
  157149. pInfo->aConstraintUsage[iLangid].argvIndex = iNext++;
  157150. pInfo->estimatedCost--;
  157151. }
  157152. return SQLITE_OK;
  157153. }
  157154. /*
  157155. ** xOpen - Open a cursor.
  157156. */
  157157. static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  157158. Fts3auxCursor *pCsr; /* Pointer to cursor object to return */
  157159. UNUSED_PARAMETER(pVTab);
  157160. pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
  157161. if( !pCsr ) return SQLITE_NOMEM;
  157162. memset(pCsr, 0, sizeof(Fts3auxCursor));
  157163. *ppCsr = (sqlite3_vtab_cursor *)pCsr;
  157164. return SQLITE_OK;
  157165. }
  157166. /*
  157167. ** xClose - Close a cursor.
  157168. */
  157169. static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
  157170. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  157171. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  157172. sqlite3Fts3SegmentsClose(pFts3);
  157173. sqlite3Fts3SegReaderFinish(&pCsr->csr);
  157174. sqlite3_free((void *)pCsr->filter.zTerm);
  157175. sqlite3_free(pCsr->zStop);
  157176. sqlite3_free(pCsr->aStat);
  157177. sqlite3_free(pCsr);
  157178. return SQLITE_OK;
  157179. }
  157180. static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
  157181. if( nSize>pCsr->nStat ){
  157182. struct Fts3auxColstats *aNew;
  157183. aNew = (struct Fts3auxColstats *)sqlite3_realloc64(pCsr->aStat,
  157184. sizeof(struct Fts3auxColstats) * nSize
  157185. );
  157186. if( aNew==0 ) return SQLITE_NOMEM;
  157187. memset(&aNew[pCsr->nStat], 0,
  157188. sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
  157189. );
  157190. pCsr->aStat = aNew;
  157191. pCsr->nStat = nSize;
  157192. }
  157193. return SQLITE_OK;
  157194. }
  157195. /*
  157196. ** xNext - Advance the cursor to the next row, if any.
  157197. */
  157198. static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
  157199. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  157200. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  157201. int rc;
  157202. /* Increment our pretend rowid value. */
  157203. pCsr->iRowid++;
  157204. for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
  157205. if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
  157206. }
  157207. rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
  157208. if( rc==SQLITE_ROW ){
  157209. int i = 0;
  157210. int nDoclist = pCsr->csr.nDoclist;
  157211. char *aDoclist = pCsr->csr.aDoclist;
  157212. int iCol;
  157213. int eState = 0;
  157214. if( pCsr->zStop ){
  157215. int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
  157216. int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
  157217. if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
  157218. pCsr->isEof = 1;
  157219. return SQLITE_OK;
  157220. }
  157221. }
  157222. if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
  157223. memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
  157224. iCol = 0;
  157225. while( i<nDoclist ){
  157226. sqlite3_int64 v = 0;
  157227. i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
  157228. switch( eState ){
  157229. /* State 0. In this state the integer just read was a docid. */
  157230. case 0:
  157231. pCsr->aStat[0].nDoc++;
  157232. eState = 1;
  157233. iCol = 0;
  157234. break;
  157235. /* State 1. In this state we are expecting either a 1, indicating
  157236. ** that the following integer will be a column number, or the
  157237. ** start of a position list for column 0.
  157238. **
  157239. ** The only difference between state 1 and state 2 is that if the
  157240. ** integer encountered in state 1 is not 0 or 1, then we need to
  157241. ** increment the column 0 "nDoc" count for this term.
  157242. */
  157243. case 1:
  157244. assert( iCol==0 );
  157245. if( v>1 ){
  157246. pCsr->aStat[1].nDoc++;
  157247. }
  157248. eState = 2;
  157249. /* fall through */
  157250. case 2:
  157251. if( v==0 ){ /* 0x00. Next integer will be a docid. */
  157252. eState = 0;
  157253. }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
  157254. eState = 3;
  157255. }else{ /* 2 or greater. A position. */
  157256. pCsr->aStat[iCol+1].nOcc++;
  157257. pCsr->aStat[0].nOcc++;
  157258. }
  157259. break;
  157260. /* State 3. The integer just read is a column number. */
  157261. default: assert( eState==3 );
  157262. iCol = (int)v;
  157263. if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
  157264. pCsr->aStat[iCol+1].nDoc++;
  157265. eState = 2;
  157266. break;
  157267. }
  157268. }
  157269. pCsr->iCol = 0;
  157270. rc = SQLITE_OK;
  157271. }else{
  157272. pCsr->isEof = 1;
  157273. }
  157274. return rc;
  157275. }
  157276. /*
  157277. ** xFilter - Initialize a cursor to point at the start of its data.
  157278. */
  157279. static int fts3auxFilterMethod(
  157280. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  157281. int idxNum, /* Strategy index */
  157282. const char *idxStr, /* Unused */
  157283. int nVal, /* Number of elements in apVal */
  157284. sqlite3_value **apVal /* Arguments for the indexing scheme */
  157285. ){
  157286. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  157287. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  157288. int rc;
  157289. int isScan = 0;
  157290. int iLangVal = 0; /* Language id to query */
  157291. int iEq = -1; /* Index of term=? value in apVal */
  157292. int iGe = -1; /* Index of term>=? value in apVal */
  157293. int iLe = -1; /* Index of term<=? value in apVal */
  157294. int iLangid = -1; /* Index of languageid=? value in apVal */
  157295. int iNext = 0;
  157296. UNUSED_PARAMETER(nVal);
  157297. UNUSED_PARAMETER(idxStr);
  157298. assert( idxStr==0 );
  157299. assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
  157300. || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
  157301. || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
  157302. );
  157303. if( idxNum==FTS4AUX_EQ_CONSTRAINT ){
  157304. iEq = iNext++;
  157305. }else{
  157306. isScan = 1;
  157307. if( idxNum & FTS4AUX_GE_CONSTRAINT ){
  157308. iGe = iNext++;
  157309. }
  157310. if( idxNum & FTS4AUX_LE_CONSTRAINT ){
  157311. iLe = iNext++;
  157312. }
  157313. }
  157314. if( iNext<nVal ){
  157315. iLangid = iNext++;
  157316. }
  157317. /* In case this cursor is being reused, close and zero it. */
  157318. testcase(pCsr->filter.zTerm);
  157319. sqlite3Fts3SegReaderFinish(&pCsr->csr);
  157320. sqlite3_free((void *)pCsr->filter.zTerm);
  157321. sqlite3_free(pCsr->aStat);
  157322. memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
  157323. pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
  157324. if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
  157325. if( iEq>=0 || iGe>=0 ){
  157326. const unsigned char *zStr = sqlite3_value_text(apVal[0]);
  157327. assert( (iEq==0 && iGe==-1) || (iEq==-1 && iGe==0) );
  157328. if( zStr ){
  157329. pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
  157330. if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
  157331. pCsr->filter.nTerm = (int)strlen(pCsr->filter.zTerm);
  157332. }
  157333. }
  157334. if( iLe>=0 ){
  157335. pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iLe]));
  157336. if( pCsr->zStop==0 ) return SQLITE_NOMEM;
  157337. pCsr->nStop = (int)strlen(pCsr->zStop);
  157338. }
  157339. if( iLangid>=0 ){
  157340. iLangVal = sqlite3_value_int(apVal[iLangid]);
  157341. /* If the user specified a negative value for the languageid, use zero
  157342. ** instead. This works, as the "languageid=?" constraint will also
  157343. ** be tested by the VDBE layer. The test will always be false (since
  157344. ** this module will not return a row with a negative languageid), and
  157345. ** so the overall query will return zero rows. */
  157346. if( iLangVal<0 ) iLangVal = 0;
  157347. }
  157348. pCsr->iLangid = iLangVal;
  157349. rc = sqlite3Fts3SegReaderCursor(pFts3, iLangVal, 0, FTS3_SEGCURSOR_ALL,
  157350. pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
  157351. );
  157352. if( rc==SQLITE_OK ){
  157353. rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
  157354. }
  157355. if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
  157356. return rc;
  157357. }
  157358. /*
  157359. ** xEof - Return true if the cursor is at EOF, or false otherwise.
  157360. */
  157361. static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
  157362. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  157363. return pCsr->isEof;
  157364. }
  157365. /*
  157366. ** xColumn - Return a column value.
  157367. */
  157368. static int fts3auxColumnMethod(
  157369. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  157370. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  157371. int iCol /* Index of column to read value from */
  157372. ){
  157373. Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
  157374. assert( p->isEof==0 );
  157375. switch( iCol ){
  157376. case 0: /* term */
  157377. sqlite3_result_text(pCtx, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
  157378. break;
  157379. case 1: /* col */
  157380. if( p->iCol ){
  157381. sqlite3_result_int(pCtx, p->iCol-1);
  157382. }else{
  157383. sqlite3_result_text(pCtx, "*", -1, SQLITE_STATIC);
  157384. }
  157385. break;
  157386. case 2: /* documents */
  157387. sqlite3_result_int64(pCtx, p->aStat[p->iCol].nDoc);
  157388. break;
  157389. case 3: /* occurrences */
  157390. sqlite3_result_int64(pCtx, p->aStat[p->iCol].nOcc);
  157391. break;
  157392. default: /* languageid */
  157393. assert( iCol==4 );
  157394. sqlite3_result_int(pCtx, p->iLangid);
  157395. break;
  157396. }
  157397. return SQLITE_OK;
  157398. }
  157399. /*
  157400. ** xRowid - Return the current rowid for the cursor.
  157401. */
  157402. static int fts3auxRowidMethod(
  157403. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  157404. sqlite_int64 *pRowid /* OUT: Rowid value */
  157405. ){
  157406. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  157407. *pRowid = pCsr->iRowid;
  157408. return SQLITE_OK;
  157409. }
  157410. /*
  157411. ** Register the fts3aux module with database connection db. Return SQLITE_OK
  157412. ** if successful or an error code if sqlite3_create_module() fails.
  157413. */
  157414. SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
  157415. static const sqlite3_module fts3aux_module = {
  157416. 0, /* iVersion */
  157417. fts3auxConnectMethod, /* xCreate */
  157418. fts3auxConnectMethod, /* xConnect */
  157419. fts3auxBestIndexMethod, /* xBestIndex */
  157420. fts3auxDisconnectMethod, /* xDisconnect */
  157421. fts3auxDisconnectMethod, /* xDestroy */
  157422. fts3auxOpenMethod, /* xOpen */
  157423. fts3auxCloseMethod, /* xClose */
  157424. fts3auxFilterMethod, /* xFilter */
  157425. fts3auxNextMethod, /* xNext */
  157426. fts3auxEofMethod, /* xEof */
  157427. fts3auxColumnMethod, /* xColumn */
  157428. fts3auxRowidMethod, /* xRowid */
  157429. 0, /* xUpdate */
  157430. 0, /* xBegin */
  157431. 0, /* xSync */
  157432. 0, /* xCommit */
  157433. 0, /* xRollback */
  157434. 0, /* xFindFunction */
  157435. 0, /* xRename */
  157436. 0, /* xSavepoint */
  157437. 0, /* xRelease */
  157438. 0, /* xRollbackTo */
  157439. 0 /* xShadowName */
  157440. };
  157441. int rc; /* Return code */
  157442. rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
  157443. return rc;
  157444. }
  157445. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  157446. /************** End of fts3_aux.c ********************************************/
  157447. /************** Begin file fts3_expr.c ***************************************/
  157448. /*
  157449. ** 2008 Nov 28
  157450. **
  157451. ** The author disclaims copyright to this source code. In place of
  157452. ** a legal notice, here is a blessing:
  157453. **
  157454. ** May you do good and not evil.
  157455. ** May you find forgiveness for yourself and forgive others.
  157456. ** May you share freely, never taking more than you give.
  157457. **
  157458. ******************************************************************************
  157459. **
  157460. ** This module contains code that implements a parser for fts3 query strings
  157461. ** (the right-hand argument to the MATCH operator). Because the supported
  157462. ** syntax is relatively simple, the whole tokenizer/parser system is
  157463. ** hand-coded.
  157464. */
  157465. /* #include "fts3Int.h" */
  157466. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  157467. /*
  157468. ** By default, this module parses the legacy syntax that has been
  157469. ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
  157470. ** is defined, then it uses the new syntax. The differences between
  157471. ** the new and the old syntaxes are:
  157472. **
  157473. ** a) The new syntax supports parenthesis. The old does not.
  157474. **
  157475. ** b) The new syntax supports the AND and NOT operators. The old does not.
  157476. **
  157477. ** c) The old syntax supports the "-" token qualifier. This is not
  157478. ** supported by the new syntax (it is replaced by the NOT operator).
  157479. **
  157480. ** d) When using the old syntax, the OR operator has a greater precedence
  157481. ** than an implicit AND. When using the new, both implicity and explicit
  157482. ** AND operators have a higher precedence than OR.
  157483. **
  157484. ** If compiled with SQLITE_TEST defined, then this module exports the
  157485. ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
  157486. ** to zero causes the module to use the old syntax. If it is set to
  157487. ** non-zero the new syntax is activated. This is so both syntaxes can
  157488. ** be tested using a single build of testfixture.
  157489. **
  157490. ** The following describes the syntax supported by the fts3 MATCH
  157491. ** operator in a similar format to that used by the lemon parser
  157492. ** generator. This module does not use actually lemon, it uses a
  157493. ** custom parser.
  157494. **
  157495. ** query ::= andexpr (OR andexpr)*.
  157496. **
  157497. ** andexpr ::= notexpr (AND? notexpr)*.
  157498. **
  157499. ** notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
  157500. ** notexpr ::= LP query RP.
  157501. **
  157502. ** nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
  157503. **
  157504. ** distance_opt ::= .
  157505. ** distance_opt ::= / INTEGER.
  157506. **
  157507. ** phrase ::= TOKEN.
  157508. ** phrase ::= COLUMN:TOKEN.
  157509. ** phrase ::= "TOKEN TOKEN TOKEN...".
  157510. */
  157511. #ifdef SQLITE_TEST
  157512. SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
  157513. #else
  157514. # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
  157515. # define sqlite3_fts3_enable_parentheses 1
  157516. # else
  157517. # define sqlite3_fts3_enable_parentheses 0
  157518. # endif
  157519. #endif
  157520. /*
  157521. ** Default span for NEAR operators.
  157522. */
  157523. #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
  157524. /* #include <string.h> */
  157525. /* #include <assert.h> */
  157526. /*
  157527. ** isNot:
  157528. ** This variable is used by function getNextNode(). When getNextNode() is
  157529. ** called, it sets ParseContext.isNot to true if the 'next node' is a
  157530. ** FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
  157531. ** FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
  157532. ** zero.
  157533. */
  157534. typedef struct ParseContext ParseContext;
  157535. struct ParseContext {
  157536. sqlite3_tokenizer *pTokenizer; /* Tokenizer module */
  157537. int iLangid; /* Language id used with tokenizer */
  157538. const char **azCol; /* Array of column names for fts3 table */
  157539. int bFts4; /* True to allow FTS4-only syntax */
  157540. int nCol; /* Number of entries in azCol[] */
  157541. int iDefaultCol; /* Default column to query */
  157542. int isNot; /* True if getNextNode() sees a unary - */
  157543. sqlite3_context *pCtx; /* Write error message here */
  157544. int nNest; /* Number of nested brackets */
  157545. };
  157546. /*
  157547. ** This function is equivalent to the standard isspace() function.
  157548. **
  157549. ** The standard isspace() can be awkward to use safely, because although it
  157550. ** is defined to accept an argument of type int, its behavior when passed
  157551. ** an integer that falls outside of the range of the unsigned char type
  157552. ** is undefined (and sometimes, "undefined" means segfault). This wrapper
  157553. ** is defined to accept an argument of type char, and always returns 0 for
  157554. ** any values that fall outside of the range of the unsigned char type (i.e.
  157555. ** negative values).
  157556. */
  157557. static int fts3isspace(char c){
  157558. return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
  157559. }
  157560. /*
  157561. ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
  157562. ** zero the memory before returning a pointer to it. If unsuccessful,
  157563. ** return NULL.
  157564. */
  157565. static void *fts3MallocZero(sqlite3_int64 nByte){
  157566. void *pRet = sqlite3_malloc64(nByte);
  157567. if( pRet ) memset(pRet, 0, nByte);
  157568. return pRet;
  157569. }
  157570. SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(
  157571. sqlite3_tokenizer *pTokenizer,
  157572. int iLangid,
  157573. const char *z,
  157574. int n,
  157575. sqlite3_tokenizer_cursor **ppCsr
  157576. ){
  157577. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  157578. sqlite3_tokenizer_cursor *pCsr = 0;
  157579. int rc;
  157580. rc = pModule->xOpen(pTokenizer, z, n, &pCsr);
  157581. assert( rc==SQLITE_OK || pCsr==0 );
  157582. if( rc==SQLITE_OK ){
  157583. pCsr->pTokenizer = pTokenizer;
  157584. if( pModule->iVersion>=1 ){
  157585. rc = pModule->xLanguageid(pCsr, iLangid);
  157586. if( rc!=SQLITE_OK ){
  157587. pModule->xClose(pCsr);
  157588. pCsr = 0;
  157589. }
  157590. }
  157591. }
  157592. *ppCsr = pCsr;
  157593. return rc;
  157594. }
  157595. /*
  157596. ** Function getNextNode(), which is called by fts3ExprParse(), may itself
  157597. ** call fts3ExprParse(). So this forward declaration is required.
  157598. */
  157599. static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
  157600. /*
  157601. ** Extract the next token from buffer z (length n) using the tokenizer
  157602. ** and other information (column names etc.) in pParse. Create an Fts3Expr
  157603. ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
  157604. ** single token and set *ppExpr to point to it. If the end of the buffer is
  157605. ** reached before a token is found, set *ppExpr to zero. It is the
  157606. ** responsibility of the caller to eventually deallocate the allocated
  157607. ** Fts3Expr structure (if any) by passing it to sqlite3_free().
  157608. **
  157609. ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
  157610. ** fails.
  157611. */
  157612. static int getNextToken(
  157613. ParseContext *pParse, /* fts3 query parse context */
  157614. int iCol, /* Value for Fts3Phrase.iColumn */
  157615. const char *z, int n, /* Input string */
  157616. Fts3Expr **ppExpr, /* OUT: expression */
  157617. int *pnConsumed /* OUT: Number of bytes consumed */
  157618. ){
  157619. sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
  157620. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  157621. int rc;
  157622. sqlite3_tokenizer_cursor *pCursor;
  157623. Fts3Expr *pRet = 0;
  157624. int i = 0;
  157625. /* Set variable i to the maximum number of bytes of input to tokenize. */
  157626. for(i=0; i<n; i++){
  157627. if( sqlite3_fts3_enable_parentheses && (z[i]=='(' || z[i]==')') ) break;
  157628. if( z[i]=='"' ) break;
  157629. }
  157630. *pnConsumed = i;
  157631. rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, i, &pCursor);
  157632. if( rc==SQLITE_OK ){
  157633. const char *zToken;
  157634. int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0;
  157635. sqlite3_int64 nByte; /* total space to allocate */
  157636. rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
  157637. if( rc==SQLITE_OK ){
  157638. nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
  157639. pRet = (Fts3Expr *)fts3MallocZero(nByte);
  157640. if( !pRet ){
  157641. rc = SQLITE_NOMEM;
  157642. }else{
  157643. pRet->eType = FTSQUERY_PHRASE;
  157644. pRet->pPhrase = (Fts3Phrase *)&pRet[1];
  157645. pRet->pPhrase->nToken = 1;
  157646. pRet->pPhrase->iColumn = iCol;
  157647. pRet->pPhrase->aToken[0].n = nToken;
  157648. pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
  157649. memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
  157650. if( iEnd<n && z[iEnd]=='*' ){
  157651. pRet->pPhrase->aToken[0].isPrefix = 1;
  157652. iEnd++;
  157653. }
  157654. while( 1 ){
  157655. if( !sqlite3_fts3_enable_parentheses
  157656. && iStart>0 && z[iStart-1]=='-'
  157657. ){
  157658. pParse->isNot = 1;
  157659. iStart--;
  157660. }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
  157661. pRet->pPhrase->aToken[0].bFirst = 1;
  157662. iStart--;
  157663. }else{
  157664. break;
  157665. }
  157666. }
  157667. }
  157668. *pnConsumed = iEnd;
  157669. }else if( i && rc==SQLITE_DONE ){
  157670. rc = SQLITE_OK;
  157671. }
  157672. pModule->xClose(pCursor);
  157673. }
  157674. *ppExpr = pRet;
  157675. return rc;
  157676. }
  157677. /*
  157678. ** Enlarge a memory allocation. If an out-of-memory allocation occurs,
  157679. ** then free the old allocation.
  157680. */
  157681. static void *fts3ReallocOrFree(void *pOrig, sqlite3_int64 nNew){
  157682. void *pRet = sqlite3_realloc64(pOrig, nNew);
  157683. if( !pRet ){
  157684. sqlite3_free(pOrig);
  157685. }
  157686. return pRet;
  157687. }
  157688. /*
  157689. ** Buffer zInput, length nInput, contains the contents of a quoted string
  157690. ** that appeared as part of an fts3 query expression. Neither quote character
  157691. ** is included in the buffer. This function attempts to tokenize the entire
  157692. ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
  157693. ** containing the results.
  157694. **
  157695. ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
  157696. ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
  157697. ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
  157698. ** to 0.
  157699. */
  157700. static int getNextString(
  157701. ParseContext *pParse, /* fts3 query parse context */
  157702. const char *zInput, int nInput, /* Input string */
  157703. Fts3Expr **ppExpr /* OUT: expression */
  157704. ){
  157705. sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
  157706. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  157707. int rc;
  157708. Fts3Expr *p = 0;
  157709. sqlite3_tokenizer_cursor *pCursor = 0;
  157710. char *zTemp = 0;
  157711. int nTemp = 0;
  157712. const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
  157713. int nToken = 0;
  157714. /* The final Fts3Expr data structure, including the Fts3Phrase,
  157715. ** Fts3PhraseToken structures token buffers are all stored as a single
  157716. ** allocation so that the expression can be freed with a single call to
  157717. ** sqlite3_free(). Setting this up requires a two pass approach.
  157718. **
  157719. ** The first pass, in the block below, uses a tokenizer cursor to iterate
  157720. ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
  157721. ** to assemble data in two dynamic buffers:
  157722. **
  157723. ** Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
  157724. ** structure, followed by the array of Fts3PhraseToken
  157725. ** structures. This pass only populates the Fts3PhraseToken array.
  157726. **
  157727. ** Buffer zTemp: Contains copies of all tokens.
  157728. **
  157729. ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
  157730. ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
  157731. ** structures.
  157732. */
  157733. rc = sqlite3Fts3OpenTokenizer(
  157734. pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);
  157735. if( rc==SQLITE_OK ){
  157736. int ii;
  157737. for(ii=0; rc==SQLITE_OK; ii++){
  157738. const char *zByte;
  157739. int nByte = 0, iBegin = 0, iEnd = 0, iPos = 0;
  157740. rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
  157741. if( rc==SQLITE_OK ){
  157742. Fts3PhraseToken *pToken;
  157743. p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
  157744. if( !p ) goto no_mem;
  157745. zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
  157746. if( !zTemp ) goto no_mem;
  157747. assert( nToken==ii );
  157748. pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
  157749. memset(pToken, 0, sizeof(Fts3PhraseToken));
  157750. memcpy(&zTemp[nTemp], zByte, nByte);
  157751. nTemp += nByte;
  157752. pToken->n = nByte;
  157753. pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
  157754. pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
  157755. nToken = ii+1;
  157756. }
  157757. }
  157758. pModule->xClose(pCursor);
  157759. pCursor = 0;
  157760. }
  157761. if( rc==SQLITE_DONE ){
  157762. int jj;
  157763. char *zBuf = 0;
  157764. p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
  157765. if( !p ) goto no_mem;
  157766. memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
  157767. p->eType = FTSQUERY_PHRASE;
  157768. p->pPhrase = (Fts3Phrase *)&p[1];
  157769. p->pPhrase->iColumn = pParse->iDefaultCol;
  157770. p->pPhrase->nToken = nToken;
  157771. zBuf = (char *)&p->pPhrase->aToken[nToken];
  157772. if( zTemp ){
  157773. memcpy(zBuf, zTemp, nTemp);
  157774. sqlite3_free(zTemp);
  157775. }else{
  157776. assert( nTemp==0 );
  157777. }
  157778. for(jj=0; jj<p->pPhrase->nToken; jj++){
  157779. p->pPhrase->aToken[jj].z = zBuf;
  157780. zBuf += p->pPhrase->aToken[jj].n;
  157781. }
  157782. rc = SQLITE_OK;
  157783. }
  157784. *ppExpr = p;
  157785. return rc;
  157786. no_mem:
  157787. if( pCursor ){
  157788. pModule->xClose(pCursor);
  157789. }
  157790. sqlite3_free(zTemp);
  157791. sqlite3_free(p);
  157792. *ppExpr = 0;
  157793. return SQLITE_NOMEM;
  157794. }
  157795. /*
  157796. ** The output variable *ppExpr is populated with an allocated Fts3Expr
  157797. ** structure, or set to 0 if the end of the input buffer is reached.
  157798. **
  157799. ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
  157800. ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
  157801. ** If SQLITE_ERROR is returned, pContext is populated with an error message.
  157802. */
  157803. static int getNextNode(
  157804. ParseContext *pParse, /* fts3 query parse context */
  157805. const char *z, int n, /* Input string */
  157806. Fts3Expr **ppExpr, /* OUT: expression */
  157807. int *pnConsumed /* OUT: Number of bytes consumed */
  157808. ){
  157809. static const struct Fts3Keyword {
  157810. char *z; /* Keyword text */
  157811. unsigned char n; /* Length of the keyword */
  157812. unsigned char parenOnly; /* Only valid in paren mode */
  157813. unsigned char eType; /* Keyword code */
  157814. } aKeyword[] = {
  157815. { "OR" , 2, 0, FTSQUERY_OR },
  157816. { "AND", 3, 1, FTSQUERY_AND },
  157817. { "NOT", 3, 1, FTSQUERY_NOT },
  157818. { "NEAR", 4, 0, FTSQUERY_NEAR }
  157819. };
  157820. int ii;
  157821. int iCol;
  157822. int iColLen;
  157823. int rc;
  157824. Fts3Expr *pRet = 0;
  157825. const char *zInput = z;
  157826. int nInput = n;
  157827. pParse->isNot = 0;
  157828. /* Skip over any whitespace before checking for a keyword, an open or
  157829. ** close bracket, or a quoted string.
  157830. */
  157831. while( nInput>0 && fts3isspace(*zInput) ){
  157832. nInput--;
  157833. zInput++;
  157834. }
  157835. if( nInput==0 ){
  157836. return SQLITE_DONE;
  157837. }
  157838. /* See if we are dealing with a keyword. */
  157839. for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
  157840. const struct Fts3Keyword *pKey = &aKeyword[ii];
  157841. if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
  157842. continue;
  157843. }
  157844. if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
  157845. int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
  157846. int nKey = pKey->n;
  157847. char cNext;
  157848. /* If this is a "NEAR" keyword, check for an explicit nearness. */
  157849. if( pKey->eType==FTSQUERY_NEAR ){
  157850. assert( nKey==4 );
  157851. if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
  157852. nNear = 0;
  157853. for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
  157854. nNear = nNear * 10 + (zInput[nKey] - '0');
  157855. }
  157856. }
  157857. }
  157858. /* At this point this is probably a keyword. But for that to be true,
  157859. ** the next byte must contain either whitespace, an open or close
  157860. ** parenthesis, a quote character, or EOF.
  157861. */
  157862. cNext = zInput[nKey];
  157863. if( fts3isspace(cNext)
  157864. || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
  157865. ){
  157866. pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
  157867. if( !pRet ){
  157868. return SQLITE_NOMEM;
  157869. }
  157870. pRet->eType = pKey->eType;
  157871. pRet->nNear = nNear;
  157872. *ppExpr = pRet;
  157873. *pnConsumed = (int)((zInput - z) + nKey);
  157874. return SQLITE_OK;
  157875. }
  157876. /* Turns out that wasn't a keyword after all. This happens if the
  157877. ** user has supplied a token such as "ORacle". Continue.
  157878. */
  157879. }
  157880. }
  157881. /* See if we are dealing with a quoted phrase. If this is the case, then
  157882. ** search for the closing quote and pass the whole string to getNextString()
  157883. ** for processing. This is easy to do, as fts3 has no syntax for escaping
  157884. ** a quote character embedded in a string.
  157885. */
  157886. if( *zInput=='"' ){
  157887. for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
  157888. *pnConsumed = (int)((zInput - z) + ii + 1);
  157889. if( ii==nInput ){
  157890. return SQLITE_ERROR;
  157891. }
  157892. return getNextString(pParse, &zInput[1], ii-1, ppExpr);
  157893. }
  157894. if( sqlite3_fts3_enable_parentheses ){
  157895. if( *zInput=='(' ){
  157896. int nConsumed = 0;
  157897. pParse->nNest++;
  157898. rc = fts3ExprParse(pParse, zInput+1, nInput-1, ppExpr, &nConsumed);
  157899. *pnConsumed = (int)(zInput - z) + 1 + nConsumed;
  157900. return rc;
  157901. }else if( *zInput==')' ){
  157902. pParse->nNest--;
  157903. *pnConsumed = (int)((zInput - z) + 1);
  157904. *ppExpr = 0;
  157905. return SQLITE_DONE;
  157906. }
  157907. }
  157908. /* If control flows to this point, this must be a regular token, or
  157909. ** the end of the input. Read a regular token using the sqlite3_tokenizer
  157910. ** interface. Before doing so, figure out if there is an explicit
  157911. ** column specifier for the token.
  157912. **
  157913. ** TODO: Strangely, it is not possible to associate a column specifier
  157914. ** with a quoted phrase, only with a single token. Not sure if this was
  157915. ** an implementation artifact or an intentional decision when fts3 was
  157916. ** first implemented. Whichever it was, this module duplicates the
  157917. ** limitation.
  157918. */
  157919. iCol = pParse->iDefaultCol;
  157920. iColLen = 0;
  157921. for(ii=0; ii<pParse->nCol; ii++){
  157922. const char *zStr = pParse->azCol[ii];
  157923. int nStr = (int)strlen(zStr);
  157924. if( nInput>nStr && zInput[nStr]==':'
  157925. && sqlite3_strnicmp(zStr, zInput, nStr)==0
  157926. ){
  157927. iCol = ii;
  157928. iColLen = (int)((zInput - z) + nStr + 1);
  157929. break;
  157930. }
  157931. }
  157932. rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
  157933. *pnConsumed += iColLen;
  157934. return rc;
  157935. }
  157936. /*
  157937. ** The argument is an Fts3Expr structure for a binary operator (any type
  157938. ** except an FTSQUERY_PHRASE). Return an integer value representing the
  157939. ** precedence of the operator. Lower values have a higher precedence (i.e.
  157940. ** group more tightly). For example, in the C language, the == operator
  157941. ** groups more tightly than ||, and would therefore have a higher precedence.
  157942. **
  157943. ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
  157944. ** is defined), the order of the operators in precedence from highest to
  157945. ** lowest is:
  157946. **
  157947. ** NEAR
  157948. ** NOT
  157949. ** AND (including implicit ANDs)
  157950. ** OR
  157951. **
  157952. ** Note that when using the old query syntax, the OR operator has a higher
  157953. ** precedence than the AND operator.
  157954. */
  157955. static int opPrecedence(Fts3Expr *p){
  157956. assert( p->eType!=FTSQUERY_PHRASE );
  157957. if( sqlite3_fts3_enable_parentheses ){
  157958. return p->eType;
  157959. }else if( p->eType==FTSQUERY_NEAR ){
  157960. return 1;
  157961. }else if( p->eType==FTSQUERY_OR ){
  157962. return 2;
  157963. }
  157964. assert( p->eType==FTSQUERY_AND );
  157965. return 3;
  157966. }
  157967. /*
  157968. ** Argument ppHead contains a pointer to the current head of a query
  157969. ** expression tree being parsed. pPrev is the expression node most recently
  157970. ** inserted into the tree. This function adds pNew, which is always a binary
  157971. ** operator node, into the expression tree based on the relative precedence
  157972. ** of pNew and the existing nodes of the tree. This may result in the head
  157973. ** of the tree changing, in which case *ppHead is set to the new root node.
  157974. */
  157975. static void insertBinaryOperator(
  157976. Fts3Expr **ppHead, /* Pointer to the root node of a tree */
  157977. Fts3Expr *pPrev, /* Node most recently inserted into the tree */
  157978. Fts3Expr *pNew /* New binary node to insert into expression tree */
  157979. ){
  157980. Fts3Expr *pSplit = pPrev;
  157981. while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
  157982. pSplit = pSplit->pParent;
  157983. }
  157984. if( pSplit->pParent ){
  157985. assert( pSplit->pParent->pRight==pSplit );
  157986. pSplit->pParent->pRight = pNew;
  157987. pNew->pParent = pSplit->pParent;
  157988. }else{
  157989. *ppHead = pNew;
  157990. }
  157991. pNew->pLeft = pSplit;
  157992. pSplit->pParent = pNew;
  157993. }
  157994. /*
  157995. ** Parse the fts3 query expression found in buffer z, length n. This function
  157996. ** returns either when the end of the buffer is reached or an unmatched
  157997. ** closing bracket - ')' - is encountered.
  157998. **
  157999. ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
  158000. ** parsed form of the expression and *pnConsumed is set to the number of
  158001. ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
  158002. ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
  158003. */
  158004. static int fts3ExprParse(
  158005. ParseContext *pParse, /* fts3 query parse context */
  158006. const char *z, int n, /* Text of MATCH query */
  158007. Fts3Expr **ppExpr, /* OUT: Parsed query structure */
  158008. int *pnConsumed /* OUT: Number of bytes consumed */
  158009. ){
  158010. Fts3Expr *pRet = 0;
  158011. Fts3Expr *pPrev = 0;
  158012. Fts3Expr *pNotBranch = 0; /* Only used in legacy parse mode */
  158013. int nIn = n;
  158014. const char *zIn = z;
  158015. int rc = SQLITE_OK;
  158016. int isRequirePhrase = 1;
  158017. while( rc==SQLITE_OK ){
  158018. Fts3Expr *p = 0;
  158019. int nByte = 0;
  158020. rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
  158021. assert( nByte>0 || (rc!=SQLITE_OK && p==0) );
  158022. if( rc==SQLITE_OK ){
  158023. if( p ){
  158024. int isPhrase;
  158025. if( !sqlite3_fts3_enable_parentheses
  158026. && p->eType==FTSQUERY_PHRASE && pParse->isNot
  158027. ){
  158028. /* Create an implicit NOT operator. */
  158029. Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
  158030. if( !pNot ){
  158031. sqlite3Fts3ExprFree(p);
  158032. rc = SQLITE_NOMEM;
  158033. goto exprparse_out;
  158034. }
  158035. pNot->eType = FTSQUERY_NOT;
  158036. pNot->pRight = p;
  158037. p->pParent = pNot;
  158038. if( pNotBranch ){
  158039. pNot->pLeft = pNotBranch;
  158040. pNotBranch->pParent = pNot;
  158041. }
  158042. pNotBranch = pNot;
  158043. p = pPrev;
  158044. }else{
  158045. int eType = p->eType;
  158046. isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
  158047. /* The isRequirePhrase variable is set to true if a phrase or
  158048. ** an expression contained in parenthesis is required. If a
  158049. ** binary operator (AND, OR, NOT or NEAR) is encounted when
  158050. ** isRequirePhrase is set, this is a syntax error.
  158051. */
  158052. if( !isPhrase && isRequirePhrase ){
  158053. sqlite3Fts3ExprFree(p);
  158054. rc = SQLITE_ERROR;
  158055. goto exprparse_out;
  158056. }
  158057. if( isPhrase && !isRequirePhrase ){
  158058. /* Insert an implicit AND operator. */
  158059. Fts3Expr *pAnd;
  158060. assert( pRet && pPrev );
  158061. pAnd = fts3MallocZero(sizeof(Fts3Expr));
  158062. if( !pAnd ){
  158063. sqlite3Fts3ExprFree(p);
  158064. rc = SQLITE_NOMEM;
  158065. goto exprparse_out;
  158066. }
  158067. pAnd->eType = FTSQUERY_AND;
  158068. insertBinaryOperator(&pRet, pPrev, pAnd);
  158069. pPrev = pAnd;
  158070. }
  158071. /* This test catches attempts to make either operand of a NEAR
  158072. ** operator something other than a phrase. For example, either of
  158073. ** the following:
  158074. **
  158075. ** (bracketed expression) NEAR phrase
  158076. ** phrase NEAR (bracketed expression)
  158077. **
  158078. ** Return an error in either case.
  158079. */
  158080. if( pPrev && (
  158081. (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
  158082. || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
  158083. )){
  158084. sqlite3Fts3ExprFree(p);
  158085. rc = SQLITE_ERROR;
  158086. goto exprparse_out;
  158087. }
  158088. if( isPhrase ){
  158089. if( pRet ){
  158090. assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
  158091. pPrev->pRight = p;
  158092. p->pParent = pPrev;
  158093. }else{
  158094. pRet = p;
  158095. }
  158096. }else{
  158097. insertBinaryOperator(&pRet, pPrev, p);
  158098. }
  158099. isRequirePhrase = !isPhrase;
  158100. }
  158101. pPrev = p;
  158102. }
  158103. assert( nByte>0 );
  158104. }
  158105. assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
  158106. nIn -= nByte;
  158107. zIn += nByte;
  158108. }
  158109. if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
  158110. rc = SQLITE_ERROR;
  158111. }
  158112. if( rc==SQLITE_DONE ){
  158113. rc = SQLITE_OK;
  158114. if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
  158115. if( !pRet ){
  158116. rc = SQLITE_ERROR;
  158117. }else{
  158118. Fts3Expr *pIter = pNotBranch;
  158119. while( pIter->pLeft ){
  158120. pIter = pIter->pLeft;
  158121. }
  158122. pIter->pLeft = pRet;
  158123. pRet->pParent = pIter;
  158124. pRet = pNotBranch;
  158125. }
  158126. }
  158127. }
  158128. *pnConsumed = n - nIn;
  158129. exprparse_out:
  158130. if( rc!=SQLITE_OK ){
  158131. sqlite3Fts3ExprFree(pRet);
  158132. sqlite3Fts3ExprFree(pNotBranch);
  158133. pRet = 0;
  158134. }
  158135. *ppExpr = pRet;
  158136. return rc;
  158137. }
  158138. /*
  158139. ** Return SQLITE_ERROR if the maximum depth of the expression tree passed
  158140. ** as the only argument is more than nMaxDepth.
  158141. */
  158142. static int fts3ExprCheckDepth(Fts3Expr *p, int nMaxDepth){
  158143. int rc = SQLITE_OK;
  158144. if( p ){
  158145. if( nMaxDepth<0 ){
  158146. rc = SQLITE_TOOBIG;
  158147. }else{
  158148. rc = fts3ExprCheckDepth(p->pLeft, nMaxDepth-1);
  158149. if( rc==SQLITE_OK ){
  158150. rc = fts3ExprCheckDepth(p->pRight, nMaxDepth-1);
  158151. }
  158152. }
  158153. }
  158154. return rc;
  158155. }
  158156. /*
  158157. ** This function attempts to transform the expression tree at (*pp) to
  158158. ** an equivalent but more balanced form. The tree is modified in place.
  158159. ** If successful, SQLITE_OK is returned and (*pp) set to point to the
  158160. ** new root expression node.
  158161. **
  158162. ** nMaxDepth is the maximum allowable depth of the balanced sub-tree.
  158163. **
  158164. ** Otherwise, if an error occurs, an SQLite error code is returned and
  158165. ** expression (*pp) freed.
  158166. */
  158167. static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){
  158168. int rc = SQLITE_OK; /* Return code */
  158169. Fts3Expr *pRoot = *pp; /* Initial root node */
  158170. Fts3Expr *pFree = 0; /* List of free nodes. Linked by pParent. */
  158171. int eType = pRoot->eType; /* Type of node in this tree */
  158172. if( nMaxDepth==0 ){
  158173. rc = SQLITE_ERROR;
  158174. }
  158175. if( rc==SQLITE_OK ){
  158176. if( (eType==FTSQUERY_AND || eType==FTSQUERY_OR) ){
  158177. Fts3Expr **apLeaf;
  158178. apLeaf = (Fts3Expr **)sqlite3_malloc64(sizeof(Fts3Expr *) * nMaxDepth);
  158179. if( 0==apLeaf ){
  158180. rc = SQLITE_NOMEM;
  158181. }else{
  158182. memset(apLeaf, 0, sizeof(Fts3Expr *) * nMaxDepth);
  158183. }
  158184. if( rc==SQLITE_OK ){
  158185. int i;
  158186. Fts3Expr *p;
  158187. /* Set $p to point to the left-most leaf in the tree of eType nodes. */
  158188. for(p=pRoot; p->eType==eType; p=p->pLeft){
  158189. assert( p->pParent==0 || p->pParent->pLeft==p );
  158190. assert( p->pLeft && p->pRight );
  158191. }
  158192. /* This loop runs once for each leaf in the tree of eType nodes. */
  158193. while( 1 ){
  158194. int iLvl;
  158195. Fts3Expr *pParent = p->pParent; /* Current parent of p */
  158196. assert( pParent==0 || pParent->pLeft==p );
  158197. p->pParent = 0;
  158198. if( pParent ){
  158199. pParent->pLeft = 0;
  158200. }else{
  158201. pRoot = 0;
  158202. }
  158203. rc = fts3ExprBalance(&p, nMaxDepth-1);
  158204. if( rc!=SQLITE_OK ) break;
  158205. for(iLvl=0; p && iLvl<nMaxDepth; iLvl++){
  158206. if( apLeaf[iLvl]==0 ){
  158207. apLeaf[iLvl] = p;
  158208. p = 0;
  158209. }else{
  158210. assert( pFree );
  158211. pFree->pLeft = apLeaf[iLvl];
  158212. pFree->pRight = p;
  158213. pFree->pLeft->pParent = pFree;
  158214. pFree->pRight->pParent = pFree;
  158215. p = pFree;
  158216. pFree = pFree->pParent;
  158217. p->pParent = 0;
  158218. apLeaf[iLvl] = 0;
  158219. }
  158220. }
  158221. if( p ){
  158222. sqlite3Fts3ExprFree(p);
  158223. rc = SQLITE_TOOBIG;
  158224. break;
  158225. }
  158226. /* If that was the last leaf node, break out of the loop */
  158227. if( pParent==0 ) break;
  158228. /* Set $p to point to the next leaf in the tree of eType nodes */
  158229. for(p=pParent->pRight; p->eType==eType; p=p->pLeft);
  158230. /* Remove pParent from the original tree. */
  158231. assert( pParent->pParent==0 || pParent->pParent->pLeft==pParent );
  158232. pParent->pRight->pParent = pParent->pParent;
  158233. if( pParent->pParent ){
  158234. pParent->pParent->pLeft = pParent->pRight;
  158235. }else{
  158236. assert( pParent==pRoot );
  158237. pRoot = pParent->pRight;
  158238. }
  158239. /* Link pParent into the free node list. It will be used as an
  158240. ** internal node of the new tree. */
  158241. pParent->pParent = pFree;
  158242. pFree = pParent;
  158243. }
  158244. if( rc==SQLITE_OK ){
  158245. p = 0;
  158246. for(i=0; i<nMaxDepth; i++){
  158247. if( apLeaf[i] ){
  158248. if( p==0 ){
  158249. p = apLeaf[i];
  158250. p->pParent = 0;
  158251. }else{
  158252. assert( pFree!=0 );
  158253. pFree->pRight = p;
  158254. pFree->pLeft = apLeaf[i];
  158255. pFree->pLeft->pParent = pFree;
  158256. pFree->pRight->pParent = pFree;
  158257. p = pFree;
  158258. pFree = pFree->pParent;
  158259. p->pParent = 0;
  158260. }
  158261. }
  158262. }
  158263. pRoot = p;
  158264. }else{
  158265. /* An error occurred. Delete the contents of the apLeaf[] array
  158266. ** and pFree list. Everything else is cleaned up by the call to
  158267. ** sqlite3Fts3ExprFree(pRoot) below. */
  158268. Fts3Expr *pDel;
  158269. for(i=0; i<nMaxDepth; i++){
  158270. sqlite3Fts3ExprFree(apLeaf[i]);
  158271. }
  158272. while( (pDel=pFree)!=0 ){
  158273. pFree = pDel->pParent;
  158274. sqlite3_free(pDel);
  158275. }
  158276. }
  158277. assert( pFree==0 );
  158278. sqlite3_free( apLeaf );
  158279. }
  158280. }else if( eType==FTSQUERY_NOT ){
  158281. Fts3Expr *pLeft = pRoot->pLeft;
  158282. Fts3Expr *pRight = pRoot->pRight;
  158283. pRoot->pLeft = 0;
  158284. pRoot->pRight = 0;
  158285. pLeft->pParent = 0;
  158286. pRight->pParent = 0;
  158287. rc = fts3ExprBalance(&pLeft, nMaxDepth-1);
  158288. if( rc==SQLITE_OK ){
  158289. rc = fts3ExprBalance(&pRight, nMaxDepth-1);
  158290. }
  158291. if( rc!=SQLITE_OK ){
  158292. sqlite3Fts3ExprFree(pRight);
  158293. sqlite3Fts3ExprFree(pLeft);
  158294. }else{
  158295. assert( pLeft && pRight );
  158296. pRoot->pLeft = pLeft;
  158297. pLeft->pParent = pRoot;
  158298. pRoot->pRight = pRight;
  158299. pRight->pParent = pRoot;
  158300. }
  158301. }
  158302. }
  158303. if( rc!=SQLITE_OK ){
  158304. sqlite3Fts3ExprFree(pRoot);
  158305. pRoot = 0;
  158306. }
  158307. *pp = pRoot;
  158308. return rc;
  158309. }
  158310. /*
  158311. ** This function is similar to sqlite3Fts3ExprParse(), with the following
  158312. ** differences:
  158313. **
  158314. ** 1. It does not do expression rebalancing.
  158315. ** 2. It does not check that the expression does not exceed the
  158316. ** maximum allowable depth.
  158317. ** 3. Even if it fails, *ppExpr may still be set to point to an
  158318. ** expression tree. It should be deleted using sqlite3Fts3ExprFree()
  158319. ** in this case.
  158320. */
  158321. static int fts3ExprParseUnbalanced(
  158322. sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
  158323. int iLangid, /* Language id for tokenizer */
  158324. char **azCol, /* Array of column names for fts3 table */
  158325. int bFts4, /* True to allow FTS4-only syntax */
  158326. int nCol, /* Number of entries in azCol[] */
  158327. int iDefaultCol, /* Default column to query */
  158328. const char *z, int n, /* Text of MATCH query */
  158329. Fts3Expr **ppExpr /* OUT: Parsed query structure */
  158330. ){
  158331. int nParsed;
  158332. int rc;
  158333. ParseContext sParse;
  158334. memset(&sParse, 0, sizeof(ParseContext));
  158335. sParse.pTokenizer = pTokenizer;
  158336. sParse.iLangid = iLangid;
  158337. sParse.azCol = (const char **)azCol;
  158338. sParse.nCol = nCol;
  158339. sParse.iDefaultCol = iDefaultCol;
  158340. sParse.bFts4 = bFts4;
  158341. if( z==0 ){
  158342. *ppExpr = 0;
  158343. return SQLITE_OK;
  158344. }
  158345. if( n<0 ){
  158346. n = (int)strlen(z);
  158347. }
  158348. rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
  158349. assert( rc==SQLITE_OK || *ppExpr==0 );
  158350. /* Check for mismatched parenthesis */
  158351. if( rc==SQLITE_OK && sParse.nNest ){
  158352. rc = SQLITE_ERROR;
  158353. }
  158354. return rc;
  158355. }
  158356. /*
  158357. ** Parameters z and n contain a pointer to and length of a buffer containing
  158358. ** an fts3 query expression, respectively. This function attempts to parse the
  158359. ** query expression and create a tree of Fts3Expr structures representing the
  158360. ** parsed expression. If successful, *ppExpr is set to point to the head
  158361. ** of the parsed expression tree and SQLITE_OK is returned. If an error
  158362. ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
  158363. ** error) is returned and *ppExpr is set to 0.
  158364. **
  158365. ** If parameter n is a negative number, then z is assumed to point to a
  158366. ** nul-terminated string and the length is determined using strlen().
  158367. **
  158368. ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
  158369. ** use to normalize query tokens while parsing the expression. The azCol[]
  158370. ** array, which is assumed to contain nCol entries, should contain the names
  158371. ** of each column in the target fts3 table, in order from left to right.
  158372. ** Column names must be nul-terminated strings.
  158373. **
  158374. ** The iDefaultCol parameter should be passed the index of the table column
  158375. ** that appears on the left-hand-side of the MATCH operator (the default
  158376. ** column to match against for tokens for which a column name is not explicitly
  158377. ** specified as part of the query string), or -1 if tokens may by default
  158378. ** match any table column.
  158379. */
  158380. SQLITE_PRIVATE int sqlite3Fts3ExprParse(
  158381. sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
  158382. int iLangid, /* Language id for tokenizer */
  158383. char **azCol, /* Array of column names for fts3 table */
  158384. int bFts4, /* True to allow FTS4-only syntax */
  158385. int nCol, /* Number of entries in azCol[] */
  158386. int iDefaultCol, /* Default column to query */
  158387. const char *z, int n, /* Text of MATCH query */
  158388. Fts3Expr **ppExpr, /* OUT: Parsed query structure */
  158389. char **pzErr /* OUT: Error message (sqlite3_malloc) */
  158390. ){
  158391. int rc = fts3ExprParseUnbalanced(
  158392. pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr
  158393. );
  158394. /* Rebalance the expression. And check that its depth does not exceed
  158395. ** SQLITE_FTS3_MAX_EXPR_DEPTH. */
  158396. if( rc==SQLITE_OK && *ppExpr ){
  158397. rc = fts3ExprBalance(ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
  158398. if( rc==SQLITE_OK ){
  158399. rc = fts3ExprCheckDepth(*ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
  158400. }
  158401. }
  158402. if( rc!=SQLITE_OK ){
  158403. sqlite3Fts3ExprFree(*ppExpr);
  158404. *ppExpr = 0;
  158405. if( rc==SQLITE_TOOBIG ){
  158406. sqlite3Fts3ErrMsg(pzErr,
  158407. "FTS expression tree is too large (maximum depth %d)",
  158408. SQLITE_FTS3_MAX_EXPR_DEPTH
  158409. );
  158410. rc = SQLITE_ERROR;
  158411. }else if( rc==SQLITE_ERROR ){
  158412. sqlite3Fts3ErrMsg(pzErr, "malformed MATCH expression: [%s]", z);
  158413. }
  158414. }
  158415. return rc;
  158416. }
  158417. /*
  158418. ** Free a single node of an expression tree.
  158419. */
  158420. static void fts3FreeExprNode(Fts3Expr *p){
  158421. assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
  158422. sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
  158423. sqlite3_free(p->aMI);
  158424. sqlite3_free(p);
  158425. }
  158426. /*
  158427. ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
  158428. **
  158429. ** This function would be simpler if it recursively called itself. But
  158430. ** that would mean passing a sufficiently large expression to ExprParse()
  158431. ** could cause a stack overflow.
  158432. */
  158433. SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *pDel){
  158434. Fts3Expr *p;
  158435. assert( pDel==0 || pDel->pParent==0 );
  158436. for(p=pDel; p && (p->pLeft||p->pRight); p=(p->pLeft ? p->pLeft : p->pRight)){
  158437. assert( p->pParent==0 || p==p->pParent->pRight || p==p->pParent->pLeft );
  158438. }
  158439. while( p ){
  158440. Fts3Expr *pParent = p->pParent;
  158441. fts3FreeExprNode(p);
  158442. if( pParent && p==pParent->pLeft && pParent->pRight ){
  158443. p = pParent->pRight;
  158444. while( p && (p->pLeft || p->pRight) ){
  158445. assert( p==p->pParent->pRight || p==p->pParent->pLeft );
  158446. p = (p->pLeft ? p->pLeft : p->pRight);
  158447. }
  158448. }else{
  158449. p = pParent;
  158450. }
  158451. }
  158452. }
  158453. /****************************************************************************
  158454. *****************************************************************************
  158455. ** Everything after this point is just test code.
  158456. */
  158457. #ifdef SQLITE_TEST
  158458. /* #include <stdio.h> */
  158459. /*
  158460. ** Return a pointer to a buffer containing a text representation of the
  158461. ** expression passed as the first argument. The buffer is obtained from
  158462. ** sqlite3_malloc(). It is the responsibility of the caller to use
  158463. ** sqlite3_free() to release the memory. If an OOM condition is encountered,
  158464. ** NULL is returned.
  158465. **
  158466. ** If the second argument is not NULL, then its contents are prepended to
  158467. ** the returned expression text and then freed using sqlite3_free().
  158468. */
  158469. static char *exprToString(Fts3Expr *pExpr, char *zBuf){
  158470. if( pExpr==0 ){
  158471. return sqlite3_mprintf("");
  158472. }
  158473. switch( pExpr->eType ){
  158474. case FTSQUERY_PHRASE: {
  158475. Fts3Phrase *pPhrase = pExpr->pPhrase;
  158476. int i;
  158477. zBuf = sqlite3_mprintf(
  158478. "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
  158479. for(i=0; zBuf && i<pPhrase->nToken; i++){
  158480. zBuf = sqlite3_mprintf("%z %.*s%s", zBuf,
  158481. pPhrase->aToken[i].n, pPhrase->aToken[i].z,
  158482. (pPhrase->aToken[i].isPrefix?"+":"")
  158483. );
  158484. }
  158485. return zBuf;
  158486. }
  158487. case FTSQUERY_NEAR:
  158488. zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
  158489. break;
  158490. case FTSQUERY_NOT:
  158491. zBuf = sqlite3_mprintf("%zNOT ", zBuf);
  158492. break;
  158493. case FTSQUERY_AND:
  158494. zBuf = sqlite3_mprintf("%zAND ", zBuf);
  158495. break;
  158496. case FTSQUERY_OR:
  158497. zBuf = sqlite3_mprintf("%zOR ", zBuf);
  158498. break;
  158499. }
  158500. if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
  158501. if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
  158502. if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
  158503. if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
  158504. if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
  158505. return zBuf;
  158506. }
  158507. /*
  158508. ** This is the implementation of a scalar SQL function used to test the
  158509. ** expression parser. It should be called as follows:
  158510. **
  158511. ** fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
  158512. **
  158513. ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
  158514. ** to parse the query expression (see README.tokenizers). The second argument
  158515. ** is the query expression to parse. Each subsequent argument is the name
  158516. ** of a column of the fts3 table that the query expression may refer to.
  158517. ** For example:
  158518. **
  158519. ** SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
  158520. */
  158521. static void fts3ExprTestCommon(
  158522. int bRebalance,
  158523. sqlite3_context *context,
  158524. int argc,
  158525. sqlite3_value **argv
  158526. ){
  158527. sqlite3_tokenizer *pTokenizer = 0;
  158528. int rc;
  158529. char **azCol = 0;
  158530. const char *zExpr;
  158531. int nExpr;
  158532. int nCol;
  158533. int ii;
  158534. Fts3Expr *pExpr;
  158535. char *zBuf = 0;
  158536. Fts3Hash *pHash = (Fts3Hash*)sqlite3_user_data(context);
  158537. const char *zTokenizer = 0;
  158538. char *zErr = 0;
  158539. if( argc<3 ){
  158540. sqlite3_result_error(context,
  158541. "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
  158542. );
  158543. return;
  158544. }
  158545. zTokenizer = (const char*)sqlite3_value_text(argv[0]);
  158546. rc = sqlite3Fts3InitTokenizer(pHash, zTokenizer, &pTokenizer, &zErr);
  158547. if( rc!=SQLITE_OK ){
  158548. if( rc==SQLITE_NOMEM ){
  158549. sqlite3_result_error_nomem(context);
  158550. }else{
  158551. sqlite3_result_error(context, zErr, -1);
  158552. }
  158553. sqlite3_free(zErr);
  158554. return;
  158555. }
  158556. zExpr = (const char *)sqlite3_value_text(argv[1]);
  158557. nExpr = sqlite3_value_bytes(argv[1]);
  158558. nCol = argc-2;
  158559. azCol = (char **)sqlite3_malloc64(nCol*sizeof(char *));
  158560. if( !azCol ){
  158561. sqlite3_result_error_nomem(context);
  158562. goto exprtest_out;
  158563. }
  158564. for(ii=0; ii<nCol; ii++){
  158565. azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
  158566. }
  158567. if( bRebalance ){
  158568. char *zDummy = 0;
  158569. rc = sqlite3Fts3ExprParse(
  158570. pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr, &zDummy
  158571. );
  158572. assert( rc==SQLITE_OK || pExpr==0 );
  158573. sqlite3_free(zDummy);
  158574. }else{
  158575. rc = fts3ExprParseUnbalanced(
  158576. pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
  158577. );
  158578. }
  158579. if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
  158580. sqlite3Fts3ExprFree(pExpr);
  158581. sqlite3_result_error(context, "Error parsing expression", -1);
  158582. }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
  158583. sqlite3_result_error_nomem(context);
  158584. }else{
  158585. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  158586. sqlite3_free(zBuf);
  158587. }
  158588. sqlite3Fts3ExprFree(pExpr);
  158589. exprtest_out:
  158590. if( pTokenizer ){
  158591. rc = pTokenizer->pModule->xDestroy(pTokenizer);
  158592. }
  158593. sqlite3_free(azCol);
  158594. }
  158595. static void fts3ExprTest(
  158596. sqlite3_context *context,
  158597. int argc,
  158598. sqlite3_value **argv
  158599. ){
  158600. fts3ExprTestCommon(0, context, argc, argv);
  158601. }
  158602. static void fts3ExprTestRebalance(
  158603. sqlite3_context *context,
  158604. int argc,
  158605. sqlite3_value **argv
  158606. ){
  158607. fts3ExprTestCommon(1, context, argc, argv);
  158608. }
  158609. /*
  158610. ** Register the query expression parser test function fts3_exprtest()
  158611. ** with database connection db.
  158612. */
  158613. SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db, Fts3Hash *pHash){
  158614. int rc = sqlite3_create_function(
  158615. db, "fts3_exprtest", -1, SQLITE_UTF8, (void*)pHash, fts3ExprTest, 0, 0
  158616. );
  158617. if( rc==SQLITE_OK ){
  158618. rc = sqlite3_create_function(db, "fts3_exprtest_rebalance",
  158619. -1, SQLITE_UTF8, (void*)pHash, fts3ExprTestRebalance, 0, 0
  158620. );
  158621. }
  158622. return rc;
  158623. }
  158624. #endif
  158625. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  158626. /************** End of fts3_expr.c *******************************************/
  158627. /************** Begin file fts3_hash.c ***************************************/
  158628. /*
  158629. ** 2001 September 22
  158630. **
  158631. ** The author disclaims copyright to this source code. In place of
  158632. ** a legal notice, here is a blessing:
  158633. **
  158634. ** May you do good and not evil.
  158635. ** May you find forgiveness for yourself and forgive others.
  158636. ** May you share freely, never taking more than you give.
  158637. **
  158638. *************************************************************************
  158639. ** This is the implementation of generic hash-tables used in SQLite.
  158640. ** We've modified it slightly to serve as a standalone hash table
  158641. ** implementation for the full-text indexing module.
  158642. */
  158643. /*
  158644. ** The code in this file is only compiled if:
  158645. **
  158646. ** * The FTS3 module is being built as an extension
  158647. ** (in which case SQLITE_CORE is not defined), or
  158648. **
  158649. ** * The FTS3 module is being built into the core of
  158650. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  158651. */
  158652. /* #include "fts3Int.h" */
  158653. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  158654. /* #include <assert.h> */
  158655. /* #include <stdlib.h> */
  158656. /* #include <string.h> */
  158657. /* #include "fts3_hash.h" */
  158658. /*
  158659. ** Malloc and Free functions
  158660. */
  158661. static void *fts3HashMalloc(sqlite3_int64 n){
  158662. void *p = sqlite3_malloc64(n);
  158663. if( p ){
  158664. memset(p, 0, n);
  158665. }
  158666. return p;
  158667. }
  158668. static void fts3HashFree(void *p){
  158669. sqlite3_free(p);
  158670. }
  158671. /* Turn bulk memory into a hash table object by initializing the
  158672. ** fields of the Hash structure.
  158673. **
  158674. ** "pNew" is a pointer to the hash table that is to be initialized.
  158675. ** keyClass is one of the constants
  158676. ** FTS3_HASH_BINARY or FTS3_HASH_STRING. The value of keyClass
  158677. ** determines what kind of key the hash table will use. "copyKey" is
  158678. ** true if the hash table should make its own private copy of keys and
  158679. ** false if it should just use the supplied pointer.
  158680. */
  158681. SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
  158682. assert( pNew!=0 );
  158683. assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
  158684. pNew->keyClass = keyClass;
  158685. pNew->copyKey = copyKey;
  158686. pNew->first = 0;
  158687. pNew->count = 0;
  158688. pNew->htsize = 0;
  158689. pNew->ht = 0;
  158690. }
  158691. /* Remove all entries from a hash table. Reclaim all memory.
  158692. ** Call this routine to delete a hash table or to reset a hash table
  158693. ** to the empty state.
  158694. */
  158695. SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
  158696. Fts3HashElem *elem; /* For looping over all elements of the table */
  158697. assert( pH!=0 );
  158698. elem = pH->first;
  158699. pH->first = 0;
  158700. fts3HashFree(pH->ht);
  158701. pH->ht = 0;
  158702. pH->htsize = 0;
  158703. while( elem ){
  158704. Fts3HashElem *next_elem = elem->next;
  158705. if( pH->copyKey && elem->pKey ){
  158706. fts3HashFree(elem->pKey);
  158707. }
  158708. fts3HashFree(elem);
  158709. elem = next_elem;
  158710. }
  158711. pH->count = 0;
  158712. }
  158713. /*
  158714. ** Hash and comparison functions when the mode is FTS3_HASH_STRING
  158715. */
  158716. static int fts3StrHash(const void *pKey, int nKey){
  158717. const char *z = (const char *)pKey;
  158718. unsigned h = 0;
  158719. if( nKey<=0 ) nKey = (int) strlen(z);
  158720. while( nKey > 0 ){
  158721. h = (h<<3) ^ h ^ *z++;
  158722. nKey--;
  158723. }
  158724. return (int)(h & 0x7fffffff);
  158725. }
  158726. static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  158727. if( n1!=n2 ) return 1;
  158728. return strncmp((const char*)pKey1,(const char*)pKey2,n1);
  158729. }
  158730. /*
  158731. ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
  158732. */
  158733. static int fts3BinHash(const void *pKey, int nKey){
  158734. int h = 0;
  158735. const char *z = (const char *)pKey;
  158736. while( nKey-- > 0 ){
  158737. h = (h<<3) ^ h ^ *(z++);
  158738. }
  158739. return h & 0x7fffffff;
  158740. }
  158741. static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  158742. if( n1!=n2 ) return 1;
  158743. return memcmp(pKey1,pKey2,n1);
  158744. }
  158745. /*
  158746. ** Return a pointer to the appropriate hash function given the key class.
  158747. **
  158748. ** The C syntax in this function definition may be unfamilar to some
  158749. ** programmers, so we provide the following additional explanation:
  158750. **
  158751. ** The name of the function is "ftsHashFunction". The function takes a
  158752. ** single parameter "keyClass". The return value of ftsHashFunction()
  158753. ** is a pointer to another function. Specifically, the return value
  158754. ** of ftsHashFunction() is a pointer to a function that takes two parameters
  158755. ** with types "const void*" and "int" and returns an "int".
  158756. */
  158757. static int (*ftsHashFunction(int keyClass))(const void*,int){
  158758. if( keyClass==FTS3_HASH_STRING ){
  158759. return &fts3StrHash;
  158760. }else{
  158761. assert( keyClass==FTS3_HASH_BINARY );
  158762. return &fts3BinHash;
  158763. }
  158764. }
  158765. /*
  158766. ** Return a pointer to the appropriate hash function given the key class.
  158767. **
  158768. ** For help in interpreted the obscure C code in the function definition,
  158769. ** see the header comment on the previous function.
  158770. */
  158771. static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
  158772. if( keyClass==FTS3_HASH_STRING ){
  158773. return &fts3StrCompare;
  158774. }else{
  158775. assert( keyClass==FTS3_HASH_BINARY );
  158776. return &fts3BinCompare;
  158777. }
  158778. }
  158779. /* Link an element into the hash table
  158780. */
  158781. static void fts3HashInsertElement(
  158782. Fts3Hash *pH, /* The complete hash table */
  158783. struct _fts3ht *pEntry, /* The entry into which pNew is inserted */
  158784. Fts3HashElem *pNew /* The element to be inserted */
  158785. ){
  158786. Fts3HashElem *pHead; /* First element already in pEntry */
  158787. pHead = pEntry->chain;
  158788. if( pHead ){
  158789. pNew->next = pHead;
  158790. pNew->prev = pHead->prev;
  158791. if( pHead->prev ){ pHead->prev->next = pNew; }
  158792. else { pH->first = pNew; }
  158793. pHead->prev = pNew;
  158794. }else{
  158795. pNew->next = pH->first;
  158796. if( pH->first ){ pH->first->prev = pNew; }
  158797. pNew->prev = 0;
  158798. pH->first = pNew;
  158799. }
  158800. pEntry->count++;
  158801. pEntry->chain = pNew;
  158802. }
  158803. /* Resize the hash table so that it cantains "new_size" buckets.
  158804. ** "new_size" must be a power of 2. The hash table might fail
  158805. ** to resize if sqliteMalloc() fails.
  158806. **
  158807. ** Return non-zero if a memory allocation error occurs.
  158808. */
  158809. static int fts3Rehash(Fts3Hash *pH, int new_size){
  158810. struct _fts3ht *new_ht; /* The new hash table */
  158811. Fts3HashElem *elem, *next_elem; /* For looping over existing elements */
  158812. int (*xHash)(const void*,int); /* The hash function */
  158813. assert( (new_size & (new_size-1))==0 );
  158814. new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
  158815. if( new_ht==0 ) return 1;
  158816. fts3HashFree(pH->ht);
  158817. pH->ht = new_ht;
  158818. pH->htsize = new_size;
  158819. xHash = ftsHashFunction(pH->keyClass);
  158820. for(elem=pH->first, pH->first=0; elem; elem = next_elem){
  158821. int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
  158822. next_elem = elem->next;
  158823. fts3HashInsertElement(pH, &new_ht[h], elem);
  158824. }
  158825. return 0;
  158826. }
  158827. /* This function (for internal use only) locates an element in an
  158828. ** hash table that matches the given key. The hash for this key has
  158829. ** already been computed and is passed as the 4th parameter.
  158830. */
  158831. static Fts3HashElem *fts3FindElementByHash(
  158832. const Fts3Hash *pH, /* The pH to be searched */
  158833. const void *pKey, /* The key we are searching for */
  158834. int nKey,
  158835. int h /* The hash for this key. */
  158836. ){
  158837. Fts3HashElem *elem; /* Used to loop thru the element list */
  158838. int count; /* Number of elements left to test */
  158839. int (*xCompare)(const void*,int,const void*,int); /* comparison function */
  158840. if( pH->ht ){
  158841. struct _fts3ht *pEntry = &pH->ht[h];
  158842. elem = pEntry->chain;
  158843. count = pEntry->count;
  158844. xCompare = ftsCompareFunction(pH->keyClass);
  158845. while( count-- && elem ){
  158846. if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
  158847. return elem;
  158848. }
  158849. elem = elem->next;
  158850. }
  158851. }
  158852. return 0;
  158853. }
  158854. /* Remove a single entry from the hash table given a pointer to that
  158855. ** element and a hash on the element's key.
  158856. */
  158857. static void fts3RemoveElementByHash(
  158858. Fts3Hash *pH, /* The pH containing "elem" */
  158859. Fts3HashElem* elem, /* The element to be removed from the pH */
  158860. int h /* Hash value for the element */
  158861. ){
  158862. struct _fts3ht *pEntry;
  158863. if( elem->prev ){
  158864. elem->prev->next = elem->next;
  158865. }else{
  158866. pH->first = elem->next;
  158867. }
  158868. if( elem->next ){
  158869. elem->next->prev = elem->prev;
  158870. }
  158871. pEntry = &pH->ht[h];
  158872. if( pEntry->chain==elem ){
  158873. pEntry->chain = elem->next;
  158874. }
  158875. pEntry->count--;
  158876. if( pEntry->count<=0 ){
  158877. pEntry->chain = 0;
  158878. }
  158879. if( pH->copyKey && elem->pKey ){
  158880. fts3HashFree(elem->pKey);
  158881. }
  158882. fts3HashFree( elem );
  158883. pH->count--;
  158884. if( pH->count<=0 ){
  158885. assert( pH->first==0 );
  158886. assert( pH->count==0 );
  158887. fts3HashClear(pH);
  158888. }
  158889. }
  158890. SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
  158891. const Fts3Hash *pH,
  158892. const void *pKey,
  158893. int nKey
  158894. ){
  158895. int h; /* A hash on key */
  158896. int (*xHash)(const void*,int); /* The hash function */
  158897. if( pH==0 || pH->ht==0 ) return 0;
  158898. xHash = ftsHashFunction(pH->keyClass);
  158899. assert( xHash!=0 );
  158900. h = (*xHash)(pKey,nKey);
  158901. assert( (pH->htsize & (pH->htsize-1))==0 );
  158902. return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
  158903. }
  158904. /*
  158905. ** Attempt to locate an element of the hash table pH with a key
  158906. ** that matches pKey,nKey. Return the data for this element if it is
  158907. ** found, or NULL if there is no match.
  158908. */
  158909. SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
  158910. Fts3HashElem *pElem; /* The element that matches key (if any) */
  158911. pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
  158912. return pElem ? pElem->data : 0;
  158913. }
  158914. /* Insert an element into the hash table pH. The key is pKey,nKey
  158915. ** and the data is "data".
  158916. **
  158917. ** If no element exists with a matching key, then a new
  158918. ** element is created. A copy of the key is made if the copyKey
  158919. ** flag is set. NULL is returned.
  158920. **
  158921. ** If another element already exists with the same key, then the
  158922. ** new data replaces the old data and the old data is returned.
  158923. ** The key is not copied in this instance. If a malloc fails, then
  158924. ** the new data is returned and the hash table is unchanged.
  158925. **
  158926. ** If the "data" parameter to this function is NULL, then the
  158927. ** element corresponding to "key" is removed from the hash table.
  158928. */
  158929. SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
  158930. Fts3Hash *pH, /* The hash table to insert into */
  158931. const void *pKey, /* The key */
  158932. int nKey, /* Number of bytes in the key */
  158933. void *data /* The data */
  158934. ){
  158935. int hraw; /* Raw hash value of the key */
  158936. int h; /* the hash of the key modulo hash table size */
  158937. Fts3HashElem *elem; /* Used to loop thru the element list */
  158938. Fts3HashElem *new_elem; /* New element added to the pH */
  158939. int (*xHash)(const void*,int); /* The hash function */
  158940. assert( pH!=0 );
  158941. xHash = ftsHashFunction(pH->keyClass);
  158942. assert( xHash!=0 );
  158943. hraw = (*xHash)(pKey, nKey);
  158944. assert( (pH->htsize & (pH->htsize-1))==0 );
  158945. h = hraw & (pH->htsize-1);
  158946. elem = fts3FindElementByHash(pH,pKey,nKey,h);
  158947. if( elem ){
  158948. void *old_data = elem->data;
  158949. if( data==0 ){
  158950. fts3RemoveElementByHash(pH,elem,h);
  158951. }else{
  158952. elem->data = data;
  158953. }
  158954. return old_data;
  158955. }
  158956. if( data==0 ) return 0;
  158957. if( (pH->htsize==0 && fts3Rehash(pH,8))
  158958. || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
  158959. ){
  158960. pH->count = 0;
  158961. return data;
  158962. }
  158963. assert( pH->htsize>0 );
  158964. new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
  158965. if( new_elem==0 ) return data;
  158966. if( pH->copyKey && pKey!=0 ){
  158967. new_elem->pKey = fts3HashMalloc( nKey );
  158968. if( new_elem->pKey==0 ){
  158969. fts3HashFree(new_elem);
  158970. return data;
  158971. }
  158972. memcpy((void*)new_elem->pKey, pKey, nKey);
  158973. }else{
  158974. new_elem->pKey = (void*)pKey;
  158975. }
  158976. new_elem->nKey = nKey;
  158977. pH->count++;
  158978. assert( pH->htsize>0 );
  158979. assert( (pH->htsize & (pH->htsize-1))==0 );
  158980. h = hraw & (pH->htsize-1);
  158981. fts3HashInsertElement(pH, &pH->ht[h], new_elem);
  158982. new_elem->data = data;
  158983. return 0;
  158984. }
  158985. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  158986. /************** End of fts3_hash.c *******************************************/
  158987. /************** Begin file fts3_porter.c *************************************/
  158988. /*
  158989. ** 2006 September 30
  158990. **
  158991. ** The author disclaims copyright to this source code. In place of
  158992. ** a legal notice, here is a blessing:
  158993. **
  158994. ** May you do good and not evil.
  158995. ** May you find forgiveness for yourself and forgive others.
  158996. ** May you share freely, never taking more than you give.
  158997. **
  158998. *************************************************************************
  158999. ** Implementation of the full-text-search tokenizer that implements
  159000. ** a Porter stemmer.
  159001. */
  159002. /*
  159003. ** The code in this file is only compiled if:
  159004. **
  159005. ** * The FTS3 module is being built as an extension
  159006. ** (in which case SQLITE_CORE is not defined), or
  159007. **
  159008. ** * The FTS3 module is being built into the core of
  159009. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  159010. */
  159011. /* #include "fts3Int.h" */
  159012. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  159013. /* #include <assert.h> */
  159014. /* #include <stdlib.h> */
  159015. /* #include <stdio.h> */
  159016. /* #include <string.h> */
  159017. /* #include "fts3_tokenizer.h" */
  159018. /*
  159019. ** Class derived from sqlite3_tokenizer
  159020. */
  159021. typedef struct porter_tokenizer {
  159022. sqlite3_tokenizer base; /* Base class */
  159023. } porter_tokenizer;
  159024. /*
  159025. ** Class derived from sqlite3_tokenizer_cursor
  159026. */
  159027. typedef struct porter_tokenizer_cursor {
  159028. sqlite3_tokenizer_cursor base;
  159029. const char *zInput; /* input we are tokenizing */
  159030. int nInput; /* size of the input */
  159031. int iOffset; /* current position in zInput */
  159032. int iToken; /* index of next token to be returned */
  159033. char *zToken; /* storage for current token */
  159034. int nAllocated; /* space allocated to zToken buffer */
  159035. } porter_tokenizer_cursor;
  159036. /*
  159037. ** Create a new tokenizer instance.
  159038. */
  159039. static int porterCreate(
  159040. int argc, const char * const *argv,
  159041. sqlite3_tokenizer **ppTokenizer
  159042. ){
  159043. porter_tokenizer *t;
  159044. UNUSED_PARAMETER(argc);
  159045. UNUSED_PARAMETER(argv);
  159046. t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
  159047. if( t==NULL ) return SQLITE_NOMEM;
  159048. memset(t, 0, sizeof(*t));
  159049. *ppTokenizer = &t->base;
  159050. return SQLITE_OK;
  159051. }
  159052. /*
  159053. ** Destroy a tokenizer
  159054. */
  159055. static int porterDestroy(sqlite3_tokenizer *pTokenizer){
  159056. sqlite3_free(pTokenizer);
  159057. return SQLITE_OK;
  159058. }
  159059. /*
  159060. ** Prepare to begin tokenizing a particular string. The input
  159061. ** string to be tokenized is zInput[0..nInput-1]. A cursor
  159062. ** used to incrementally tokenize this string is returned in
  159063. ** *ppCursor.
  159064. */
  159065. static int porterOpen(
  159066. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  159067. const char *zInput, int nInput, /* String to be tokenized */
  159068. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  159069. ){
  159070. porter_tokenizer_cursor *c;
  159071. UNUSED_PARAMETER(pTokenizer);
  159072. c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
  159073. if( c==NULL ) return SQLITE_NOMEM;
  159074. c->zInput = zInput;
  159075. if( zInput==0 ){
  159076. c->nInput = 0;
  159077. }else if( nInput<0 ){
  159078. c->nInput = (int)strlen(zInput);
  159079. }else{
  159080. c->nInput = nInput;
  159081. }
  159082. c->iOffset = 0; /* start tokenizing at the beginning */
  159083. c->iToken = 0;
  159084. c->zToken = NULL; /* no space allocated, yet. */
  159085. c->nAllocated = 0;
  159086. *ppCursor = &c->base;
  159087. return SQLITE_OK;
  159088. }
  159089. /*
  159090. ** Close a tokenization cursor previously opened by a call to
  159091. ** porterOpen() above.
  159092. */
  159093. static int porterClose(sqlite3_tokenizer_cursor *pCursor){
  159094. porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
  159095. sqlite3_free(c->zToken);
  159096. sqlite3_free(c);
  159097. return SQLITE_OK;
  159098. }
  159099. /*
  159100. ** Vowel or consonant
  159101. */
  159102. static const char cType[] = {
  159103. 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
  159104. 1, 1, 1, 2, 1
  159105. };
  159106. /*
  159107. ** isConsonant() and isVowel() determine if their first character in
  159108. ** the string they point to is a consonant or a vowel, according
  159109. ** to Porter ruls.
  159110. **
  159111. ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
  159112. ** 'Y' is a consonant unless it follows another consonant,
  159113. ** in which case it is a vowel.
  159114. **
  159115. ** In these routine, the letters are in reverse order. So the 'y' rule
  159116. ** is that 'y' is a consonant unless it is followed by another
  159117. ** consonent.
  159118. */
  159119. static int isVowel(const char*);
  159120. static int isConsonant(const char *z){
  159121. int j;
  159122. char x = *z;
  159123. if( x==0 ) return 0;
  159124. assert( x>='a' && x<='z' );
  159125. j = cType[x-'a'];
  159126. if( j<2 ) return j;
  159127. return z[1]==0 || isVowel(z + 1);
  159128. }
  159129. static int isVowel(const char *z){
  159130. int j;
  159131. char x = *z;
  159132. if( x==0 ) return 0;
  159133. assert( x>='a' && x<='z' );
  159134. j = cType[x-'a'];
  159135. if( j<2 ) return 1-j;
  159136. return isConsonant(z + 1);
  159137. }
  159138. /*
  159139. ** Let any sequence of one or more vowels be represented by V and let
  159140. ** C be sequence of one or more consonants. Then every word can be
  159141. ** represented as:
  159142. **
  159143. ** [C] (VC){m} [V]
  159144. **
  159145. ** In prose: A word is an optional consonant followed by zero or
  159146. ** vowel-consonant pairs followed by an optional vowel. "m" is the
  159147. ** number of vowel consonant pairs. This routine computes the value
  159148. ** of m for the first i bytes of a word.
  159149. **
  159150. ** Return true if the m-value for z is 1 or more. In other words,
  159151. ** return true if z contains at least one vowel that is followed
  159152. ** by a consonant.
  159153. **
  159154. ** In this routine z[] is in reverse order. So we are really looking
  159155. ** for an instance of a consonant followed by a vowel.
  159156. */
  159157. static int m_gt_0(const char *z){
  159158. while( isVowel(z) ){ z++; }
  159159. if( *z==0 ) return 0;
  159160. while( isConsonant(z) ){ z++; }
  159161. return *z!=0;
  159162. }
  159163. /* Like mgt0 above except we are looking for a value of m which is
  159164. ** exactly 1
  159165. */
  159166. static int m_eq_1(const char *z){
  159167. while( isVowel(z) ){ z++; }
  159168. if( *z==0 ) return 0;
  159169. while( isConsonant(z) ){ z++; }
  159170. if( *z==0 ) return 0;
  159171. while( isVowel(z) ){ z++; }
  159172. if( *z==0 ) return 1;
  159173. while( isConsonant(z) ){ z++; }
  159174. return *z==0;
  159175. }
  159176. /* Like mgt0 above except we are looking for a value of m>1 instead
  159177. ** or m>0
  159178. */
  159179. static int m_gt_1(const char *z){
  159180. while( isVowel(z) ){ z++; }
  159181. if( *z==0 ) return 0;
  159182. while( isConsonant(z) ){ z++; }
  159183. if( *z==0 ) return 0;
  159184. while( isVowel(z) ){ z++; }
  159185. if( *z==0 ) return 0;
  159186. while( isConsonant(z) ){ z++; }
  159187. return *z!=0;
  159188. }
  159189. /*
  159190. ** Return TRUE if there is a vowel anywhere within z[0..n-1]
  159191. */
  159192. static int hasVowel(const char *z){
  159193. while( isConsonant(z) ){ z++; }
  159194. return *z!=0;
  159195. }
  159196. /*
  159197. ** Return TRUE if the word ends in a double consonant.
  159198. **
  159199. ** The text is reversed here. So we are really looking at
  159200. ** the first two characters of z[].
  159201. */
  159202. static int doubleConsonant(const char *z){
  159203. return isConsonant(z) && z[0]==z[1];
  159204. }
  159205. /*
  159206. ** Return TRUE if the word ends with three letters which
  159207. ** are consonant-vowel-consonent and where the final consonant
  159208. ** is not 'w', 'x', or 'y'.
  159209. **
  159210. ** The word is reversed here. So we are really checking the
  159211. ** first three letters and the first one cannot be in [wxy].
  159212. */
  159213. static int star_oh(const char *z){
  159214. return
  159215. isConsonant(z) &&
  159216. z[0]!='w' && z[0]!='x' && z[0]!='y' &&
  159217. isVowel(z+1) &&
  159218. isConsonant(z+2);
  159219. }
  159220. /*
  159221. ** If the word ends with zFrom and xCond() is true for the stem
  159222. ** of the word that preceeds the zFrom ending, then change the
  159223. ** ending to zTo.
  159224. **
  159225. ** The input word *pz and zFrom are both in reverse order. zTo
  159226. ** is in normal order.
  159227. **
  159228. ** Return TRUE if zFrom matches. Return FALSE if zFrom does not
  159229. ** match. Not that TRUE is returned even if xCond() fails and
  159230. ** no substitution occurs.
  159231. */
  159232. static int stem(
  159233. char **pz, /* The word being stemmed (Reversed) */
  159234. const char *zFrom, /* If the ending matches this... (Reversed) */
  159235. const char *zTo, /* ... change the ending to this (not reversed) */
  159236. int (*xCond)(const char*) /* Condition that must be true */
  159237. ){
  159238. char *z = *pz;
  159239. while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
  159240. if( *zFrom!=0 ) return 0;
  159241. if( xCond && !xCond(z) ) return 1;
  159242. while( *zTo ){
  159243. *(--z) = *(zTo++);
  159244. }
  159245. *pz = z;
  159246. return 1;
  159247. }
  159248. /*
  159249. ** This is the fallback stemmer used when the porter stemmer is
  159250. ** inappropriate. The input word is copied into the output with
  159251. ** US-ASCII case folding. If the input word is too long (more
  159252. ** than 20 bytes if it contains no digits or more than 6 bytes if
  159253. ** it contains digits) then word is truncated to 20 or 6 bytes
  159254. ** by taking 10 or 3 bytes from the beginning and end.
  159255. */
  159256. static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
  159257. int i, mx, j;
  159258. int hasDigit = 0;
  159259. for(i=0; i<nIn; i++){
  159260. char c = zIn[i];
  159261. if( c>='A' && c<='Z' ){
  159262. zOut[i] = c - 'A' + 'a';
  159263. }else{
  159264. if( c>='0' && c<='9' ) hasDigit = 1;
  159265. zOut[i] = c;
  159266. }
  159267. }
  159268. mx = hasDigit ? 3 : 10;
  159269. if( nIn>mx*2 ){
  159270. for(j=mx, i=nIn-mx; i<nIn; i++, j++){
  159271. zOut[j] = zOut[i];
  159272. }
  159273. i = j;
  159274. }
  159275. zOut[i] = 0;
  159276. *pnOut = i;
  159277. }
  159278. /*
  159279. ** Stem the input word zIn[0..nIn-1]. Store the output in zOut.
  159280. ** zOut is at least big enough to hold nIn bytes. Write the actual
  159281. ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
  159282. **
  159283. ** Any upper-case characters in the US-ASCII character set ([A-Z])
  159284. ** are converted to lower case. Upper-case UTF characters are
  159285. ** unchanged.
  159286. **
  159287. ** Words that are longer than about 20 bytes are stemmed by retaining
  159288. ** a few bytes from the beginning and the end of the word. If the
  159289. ** word contains digits, 3 bytes are taken from the beginning and
  159290. ** 3 bytes from the end. For long words without digits, 10 bytes
  159291. ** are taken from each end. US-ASCII case folding still applies.
  159292. **
  159293. ** If the input word contains not digits but does characters not
  159294. ** in [a-zA-Z] then no stemming is attempted and this routine just
  159295. ** copies the input into the input into the output with US-ASCII
  159296. ** case folding.
  159297. **
  159298. ** Stemming never increases the length of the word. So there is
  159299. ** no chance of overflowing the zOut buffer.
  159300. */
  159301. static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
  159302. int i, j;
  159303. char zReverse[28];
  159304. char *z, *z2;
  159305. if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
  159306. /* The word is too big or too small for the porter stemmer.
  159307. ** Fallback to the copy stemmer */
  159308. copy_stemmer(zIn, nIn, zOut, pnOut);
  159309. return;
  159310. }
  159311. for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
  159312. char c = zIn[i];
  159313. if( c>='A' && c<='Z' ){
  159314. zReverse[j] = c + 'a' - 'A';
  159315. }else if( c>='a' && c<='z' ){
  159316. zReverse[j] = c;
  159317. }else{
  159318. /* The use of a character not in [a-zA-Z] means that we fallback
  159319. ** to the copy stemmer */
  159320. copy_stemmer(zIn, nIn, zOut, pnOut);
  159321. return;
  159322. }
  159323. }
  159324. memset(&zReverse[sizeof(zReverse)-5], 0, 5);
  159325. z = &zReverse[j+1];
  159326. /* Step 1a */
  159327. if( z[0]=='s' ){
  159328. if(
  159329. !stem(&z, "sess", "ss", 0) &&
  159330. !stem(&z, "sei", "i", 0) &&
  159331. !stem(&z, "ss", "ss", 0)
  159332. ){
  159333. z++;
  159334. }
  159335. }
  159336. /* Step 1b */
  159337. z2 = z;
  159338. if( stem(&z, "dee", "ee", m_gt_0) ){
  159339. /* Do nothing. The work was all in the test */
  159340. }else if(
  159341. (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
  159342. && z!=z2
  159343. ){
  159344. if( stem(&z, "ta", "ate", 0) ||
  159345. stem(&z, "lb", "ble", 0) ||
  159346. stem(&z, "zi", "ize", 0) ){
  159347. /* Do nothing. The work was all in the test */
  159348. }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
  159349. z++;
  159350. }else if( m_eq_1(z) && star_oh(z) ){
  159351. *(--z) = 'e';
  159352. }
  159353. }
  159354. /* Step 1c */
  159355. if( z[0]=='y' && hasVowel(z+1) ){
  159356. z[0] = 'i';
  159357. }
  159358. /* Step 2 */
  159359. switch( z[1] ){
  159360. case 'a':
  159361. if( !stem(&z, "lanoita", "ate", m_gt_0) ){
  159362. stem(&z, "lanoit", "tion", m_gt_0);
  159363. }
  159364. break;
  159365. case 'c':
  159366. if( !stem(&z, "icne", "ence", m_gt_0) ){
  159367. stem(&z, "icna", "ance", m_gt_0);
  159368. }
  159369. break;
  159370. case 'e':
  159371. stem(&z, "rezi", "ize", m_gt_0);
  159372. break;
  159373. case 'g':
  159374. stem(&z, "igol", "log", m_gt_0);
  159375. break;
  159376. case 'l':
  159377. if( !stem(&z, "ilb", "ble", m_gt_0)
  159378. && !stem(&z, "illa", "al", m_gt_0)
  159379. && !stem(&z, "iltne", "ent", m_gt_0)
  159380. && !stem(&z, "ile", "e", m_gt_0)
  159381. ){
  159382. stem(&z, "ilsuo", "ous", m_gt_0);
  159383. }
  159384. break;
  159385. case 'o':
  159386. if( !stem(&z, "noitazi", "ize", m_gt_0)
  159387. && !stem(&z, "noita", "ate", m_gt_0)
  159388. ){
  159389. stem(&z, "rota", "ate", m_gt_0);
  159390. }
  159391. break;
  159392. case 's':
  159393. if( !stem(&z, "msila", "al", m_gt_0)
  159394. && !stem(&z, "ssenevi", "ive", m_gt_0)
  159395. && !stem(&z, "ssenluf", "ful", m_gt_0)
  159396. ){
  159397. stem(&z, "ssensuo", "ous", m_gt_0);
  159398. }
  159399. break;
  159400. case 't':
  159401. if( !stem(&z, "itila", "al", m_gt_0)
  159402. && !stem(&z, "itivi", "ive", m_gt_0)
  159403. ){
  159404. stem(&z, "itilib", "ble", m_gt_0);
  159405. }
  159406. break;
  159407. }
  159408. /* Step 3 */
  159409. switch( z[0] ){
  159410. case 'e':
  159411. if( !stem(&z, "etaci", "ic", m_gt_0)
  159412. && !stem(&z, "evita", "", m_gt_0)
  159413. ){
  159414. stem(&z, "ezila", "al", m_gt_0);
  159415. }
  159416. break;
  159417. case 'i':
  159418. stem(&z, "itici", "ic", m_gt_0);
  159419. break;
  159420. case 'l':
  159421. if( !stem(&z, "laci", "ic", m_gt_0) ){
  159422. stem(&z, "luf", "", m_gt_0);
  159423. }
  159424. break;
  159425. case 's':
  159426. stem(&z, "ssen", "", m_gt_0);
  159427. break;
  159428. }
  159429. /* Step 4 */
  159430. switch( z[1] ){
  159431. case 'a':
  159432. if( z[0]=='l' && m_gt_1(z+2) ){
  159433. z += 2;
  159434. }
  159435. break;
  159436. case 'c':
  159437. if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e') && m_gt_1(z+4) ){
  159438. z += 4;
  159439. }
  159440. break;
  159441. case 'e':
  159442. if( z[0]=='r' && m_gt_1(z+2) ){
  159443. z += 2;
  159444. }
  159445. break;
  159446. case 'i':
  159447. if( z[0]=='c' && m_gt_1(z+2) ){
  159448. z += 2;
  159449. }
  159450. break;
  159451. case 'l':
  159452. if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
  159453. z += 4;
  159454. }
  159455. break;
  159456. case 'n':
  159457. if( z[0]=='t' ){
  159458. if( z[2]=='a' ){
  159459. if( m_gt_1(z+3) ){
  159460. z += 3;
  159461. }
  159462. }else if( z[2]=='e' ){
  159463. if( !stem(&z, "tneme", "", m_gt_1)
  159464. && !stem(&z, "tnem", "", m_gt_1)
  159465. ){
  159466. stem(&z, "tne", "", m_gt_1);
  159467. }
  159468. }
  159469. }
  159470. break;
  159471. case 'o':
  159472. if( z[0]=='u' ){
  159473. if( m_gt_1(z+2) ){
  159474. z += 2;
  159475. }
  159476. }else if( z[3]=='s' || z[3]=='t' ){
  159477. stem(&z, "noi", "", m_gt_1);
  159478. }
  159479. break;
  159480. case 's':
  159481. if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
  159482. z += 3;
  159483. }
  159484. break;
  159485. case 't':
  159486. if( !stem(&z, "eta", "", m_gt_1) ){
  159487. stem(&z, "iti", "", m_gt_1);
  159488. }
  159489. break;
  159490. case 'u':
  159491. if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
  159492. z += 3;
  159493. }
  159494. break;
  159495. case 'v':
  159496. case 'z':
  159497. if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
  159498. z += 3;
  159499. }
  159500. break;
  159501. }
  159502. /* Step 5a */
  159503. if( z[0]=='e' ){
  159504. if( m_gt_1(z+1) ){
  159505. z++;
  159506. }else if( m_eq_1(z+1) && !star_oh(z+1) ){
  159507. z++;
  159508. }
  159509. }
  159510. /* Step 5b */
  159511. if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
  159512. z++;
  159513. }
  159514. /* z[] is now the stemmed word in reverse order. Flip it back
  159515. ** around into forward order and return.
  159516. */
  159517. *pnOut = i = (int)strlen(z);
  159518. zOut[i] = 0;
  159519. while( *z ){
  159520. zOut[--i] = *(z++);
  159521. }
  159522. }
  159523. /*
  159524. ** Characters that can be part of a token. We assume any character
  159525. ** whose value is greater than 0x80 (any UTF character) can be
  159526. ** part of a token. In other words, delimiters all must have
  159527. ** values of 0x7f or lower.
  159528. */
  159529. static const char porterIdChar[] = {
  159530. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
  159531. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
  159532. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
  159533. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
  159534. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
  159535. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
  159536. };
  159537. #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
  159538. /*
  159539. ** Extract the next token from a tokenization cursor. The cursor must
  159540. ** have been opened by a prior call to porterOpen().
  159541. */
  159542. static int porterNext(
  159543. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by porterOpen */
  159544. const char **pzToken, /* OUT: *pzToken is the token text */
  159545. int *pnBytes, /* OUT: Number of bytes in token */
  159546. int *piStartOffset, /* OUT: Starting offset of token */
  159547. int *piEndOffset, /* OUT: Ending offset of token */
  159548. int *piPosition /* OUT: Position integer of token */
  159549. ){
  159550. porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
  159551. const char *z = c->zInput;
  159552. while( c->iOffset<c->nInput ){
  159553. int iStartOffset, ch;
  159554. /* Scan past delimiter characters */
  159555. while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
  159556. c->iOffset++;
  159557. }
  159558. /* Count non-delimiter characters. */
  159559. iStartOffset = c->iOffset;
  159560. while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
  159561. c->iOffset++;
  159562. }
  159563. if( c->iOffset>iStartOffset ){
  159564. int n = c->iOffset-iStartOffset;
  159565. if( n>c->nAllocated ){
  159566. char *pNew;
  159567. c->nAllocated = n+20;
  159568. pNew = sqlite3_realloc(c->zToken, c->nAllocated);
  159569. if( !pNew ) return SQLITE_NOMEM;
  159570. c->zToken = pNew;
  159571. }
  159572. porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
  159573. *pzToken = c->zToken;
  159574. *piStartOffset = iStartOffset;
  159575. *piEndOffset = c->iOffset;
  159576. *piPosition = c->iToken++;
  159577. return SQLITE_OK;
  159578. }
  159579. }
  159580. return SQLITE_DONE;
  159581. }
  159582. /*
  159583. ** The set of routines that implement the porter-stemmer tokenizer
  159584. */
  159585. static const sqlite3_tokenizer_module porterTokenizerModule = {
  159586. 0,
  159587. porterCreate,
  159588. porterDestroy,
  159589. porterOpen,
  159590. porterClose,
  159591. porterNext,
  159592. 0
  159593. };
  159594. /*
  159595. ** Allocate a new porter tokenizer. Return a pointer to the new
  159596. ** tokenizer in *ppModule
  159597. */
  159598. SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
  159599. sqlite3_tokenizer_module const**ppModule
  159600. ){
  159601. *ppModule = &porterTokenizerModule;
  159602. }
  159603. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  159604. /************** End of fts3_porter.c *****************************************/
  159605. /************** Begin file fts3_tokenizer.c **********************************/
  159606. /*
  159607. ** 2007 June 22
  159608. **
  159609. ** The author disclaims copyright to this source code. In place of
  159610. ** a legal notice, here is a blessing:
  159611. **
  159612. ** May you do good and not evil.
  159613. ** May you find forgiveness for yourself and forgive others.
  159614. ** May you share freely, never taking more than you give.
  159615. **
  159616. ******************************************************************************
  159617. **
  159618. ** This is part of an SQLite module implementing full-text search.
  159619. ** This particular file implements the generic tokenizer interface.
  159620. */
  159621. /*
  159622. ** The code in this file is only compiled if:
  159623. **
  159624. ** * The FTS3 module is being built as an extension
  159625. ** (in which case SQLITE_CORE is not defined), or
  159626. **
  159627. ** * The FTS3 module is being built into the core of
  159628. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  159629. */
  159630. /* #include "fts3Int.h" */
  159631. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  159632. /* #include <assert.h> */
  159633. /* #include <string.h> */
  159634. /*
  159635. ** Return true if the two-argument version of fts3_tokenizer()
  159636. ** has been activated via a prior call to sqlite3_db_config(db,
  159637. ** SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, 1, 0);
  159638. */
  159639. static int fts3TokenizerEnabled(sqlite3_context *context){
  159640. sqlite3 *db = sqlite3_context_db_handle(context);
  159641. int isEnabled = 0;
  159642. sqlite3_db_config(db,SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER,-1,&isEnabled);
  159643. return isEnabled;
  159644. }
  159645. /*
  159646. ** Implementation of the SQL scalar function for accessing the underlying
  159647. ** hash table. This function may be called as follows:
  159648. **
  159649. ** SELECT <function-name>(<key-name>);
  159650. ** SELECT <function-name>(<key-name>, <pointer>);
  159651. **
  159652. ** where <function-name> is the name passed as the second argument
  159653. ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
  159654. **
  159655. ** If the <pointer> argument is specified, it must be a blob value
  159656. ** containing a pointer to be stored as the hash data corresponding
  159657. ** to the string <key-name>. If <pointer> is not specified, then
  159658. ** the string <key-name> must already exist in the has table. Otherwise,
  159659. ** an error is returned.
  159660. **
  159661. ** Whether or not the <pointer> argument is specified, the value returned
  159662. ** is a blob containing the pointer stored as the hash data corresponding
  159663. ** to string <key-name> (after the hash-table is updated, if applicable).
  159664. */
  159665. static void fts3TokenizerFunc(
  159666. sqlite3_context *context,
  159667. int argc,
  159668. sqlite3_value **argv
  159669. ){
  159670. Fts3Hash *pHash;
  159671. void *pPtr = 0;
  159672. const unsigned char *zName;
  159673. int nName;
  159674. assert( argc==1 || argc==2 );
  159675. pHash = (Fts3Hash *)sqlite3_user_data(context);
  159676. zName = sqlite3_value_text(argv[0]);
  159677. nName = sqlite3_value_bytes(argv[0])+1;
  159678. if( argc==2 ){
  159679. if( fts3TokenizerEnabled(context) || sqlite3_value_frombind(argv[1]) ){
  159680. void *pOld;
  159681. int n = sqlite3_value_bytes(argv[1]);
  159682. if( zName==0 || n!=sizeof(pPtr) ){
  159683. sqlite3_result_error(context, "argument type mismatch", -1);
  159684. return;
  159685. }
  159686. pPtr = *(void **)sqlite3_value_blob(argv[1]);
  159687. pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
  159688. if( pOld==pPtr ){
  159689. sqlite3_result_error(context, "out of memory", -1);
  159690. }
  159691. }else{
  159692. sqlite3_result_error(context, "fts3tokenize disabled", -1);
  159693. return;
  159694. }
  159695. }else{
  159696. if( zName ){
  159697. pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
  159698. }
  159699. if( !pPtr ){
  159700. char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
  159701. sqlite3_result_error(context, zErr, -1);
  159702. sqlite3_free(zErr);
  159703. return;
  159704. }
  159705. }
  159706. if( fts3TokenizerEnabled(context) || sqlite3_value_frombind(argv[0]) ){
  159707. sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
  159708. }
  159709. }
  159710. SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
  159711. static const char isFtsIdChar[] = {
  159712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
  159713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
  159714. 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
  159715. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
  159716. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
  159717. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
  159718. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
  159719. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
  159720. };
  159721. return (c&0x80 || isFtsIdChar[(int)(c)]);
  159722. }
  159723. SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
  159724. const char *z1;
  159725. const char *z2 = 0;
  159726. /* Find the start of the next token. */
  159727. z1 = zStr;
  159728. while( z2==0 ){
  159729. char c = *z1;
  159730. switch( c ){
  159731. case '\0': return 0; /* No more tokens here */
  159732. case '\'':
  159733. case '"':
  159734. case '`': {
  159735. z2 = z1;
  159736. while( *++z2 && (*z2!=c || *++z2==c) );
  159737. break;
  159738. }
  159739. case '[':
  159740. z2 = &z1[1];
  159741. while( *z2 && z2[0]!=']' ) z2++;
  159742. if( *z2 ) z2++;
  159743. break;
  159744. default:
  159745. if( sqlite3Fts3IsIdChar(*z1) ){
  159746. z2 = &z1[1];
  159747. while( sqlite3Fts3IsIdChar(*z2) ) z2++;
  159748. }else{
  159749. z1++;
  159750. }
  159751. }
  159752. }
  159753. *pn = (int)(z2-z1);
  159754. return z1;
  159755. }
  159756. SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
  159757. Fts3Hash *pHash, /* Tokenizer hash table */
  159758. const char *zArg, /* Tokenizer name */
  159759. sqlite3_tokenizer **ppTok, /* OUT: Tokenizer (if applicable) */
  159760. char **pzErr /* OUT: Set to malloced error message */
  159761. ){
  159762. int rc;
  159763. char *z = (char *)zArg;
  159764. int n = 0;
  159765. char *zCopy;
  159766. char *zEnd; /* Pointer to nul-term of zCopy */
  159767. sqlite3_tokenizer_module *m;
  159768. zCopy = sqlite3_mprintf("%s", zArg);
  159769. if( !zCopy ) return SQLITE_NOMEM;
  159770. zEnd = &zCopy[strlen(zCopy)];
  159771. z = (char *)sqlite3Fts3NextToken(zCopy, &n);
  159772. if( z==0 ){
  159773. assert( n==0 );
  159774. z = zCopy;
  159775. }
  159776. z[n] = '\0';
  159777. sqlite3Fts3Dequote(z);
  159778. m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
  159779. if( !m ){
  159780. sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", z);
  159781. rc = SQLITE_ERROR;
  159782. }else{
  159783. char const **aArg = 0;
  159784. int iArg = 0;
  159785. z = &z[n+1];
  159786. while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
  159787. sqlite3_int64 nNew = sizeof(char *)*(iArg+1);
  159788. char const **aNew = (const char **)sqlite3_realloc64((void *)aArg, nNew);
  159789. if( !aNew ){
  159790. sqlite3_free(zCopy);
  159791. sqlite3_free((void *)aArg);
  159792. return SQLITE_NOMEM;
  159793. }
  159794. aArg = aNew;
  159795. aArg[iArg++] = z;
  159796. z[n] = '\0';
  159797. sqlite3Fts3Dequote(z);
  159798. z = &z[n+1];
  159799. }
  159800. rc = m->xCreate(iArg, aArg, ppTok);
  159801. assert( rc!=SQLITE_OK || *ppTok );
  159802. if( rc!=SQLITE_OK ){
  159803. sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer");
  159804. }else{
  159805. (*ppTok)->pModule = m;
  159806. }
  159807. sqlite3_free((void *)aArg);
  159808. }
  159809. sqlite3_free(zCopy);
  159810. return rc;
  159811. }
  159812. #ifdef SQLITE_TEST
  159813. #if defined(INCLUDE_SQLITE_TCL_H)
  159814. # include "sqlite_tcl.h"
  159815. #else
  159816. # include "tcl.h"
  159817. #endif
  159818. /* #include <string.h> */
  159819. /*
  159820. ** Implementation of a special SQL scalar function for testing tokenizers
  159821. ** designed to be used in concert with the Tcl testing framework. This
  159822. ** function must be called with two or more arguments:
  159823. **
  159824. ** SELECT <function-name>(<key-name>, ..., <input-string>);
  159825. **
  159826. ** where <function-name> is the name passed as the second argument
  159827. ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
  159828. ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
  159829. **
  159830. ** The return value is a string that may be interpreted as a Tcl
  159831. ** list. For each token in the <input-string>, three elements are
  159832. ** added to the returned list. The first is the token position, the
  159833. ** second is the token text (folded, stemmed, etc.) and the third is the
  159834. ** substring of <input-string> associated with the token. For example,
  159835. ** using the built-in "simple" tokenizer:
  159836. **
  159837. ** SELECT fts_tokenizer_test('simple', 'I don't see how');
  159838. **
  159839. ** will return the string:
  159840. **
  159841. ** "{0 i I 1 dont don't 2 see see 3 how how}"
  159842. **
  159843. */
  159844. static void testFunc(
  159845. sqlite3_context *context,
  159846. int argc,
  159847. sqlite3_value **argv
  159848. ){
  159849. Fts3Hash *pHash;
  159850. sqlite3_tokenizer_module *p;
  159851. sqlite3_tokenizer *pTokenizer = 0;
  159852. sqlite3_tokenizer_cursor *pCsr = 0;
  159853. const char *zErr = 0;
  159854. const char *zName;
  159855. int nName;
  159856. const char *zInput;
  159857. int nInput;
  159858. const char *azArg[64];
  159859. const char *zToken;
  159860. int nToken = 0;
  159861. int iStart = 0;
  159862. int iEnd = 0;
  159863. int iPos = 0;
  159864. int i;
  159865. Tcl_Obj *pRet;
  159866. if( argc<2 ){
  159867. sqlite3_result_error(context, "insufficient arguments", -1);
  159868. return;
  159869. }
  159870. nName = sqlite3_value_bytes(argv[0]);
  159871. zName = (const char *)sqlite3_value_text(argv[0]);
  159872. nInput = sqlite3_value_bytes(argv[argc-1]);
  159873. zInput = (const char *)sqlite3_value_text(argv[argc-1]);
  159874. pHash = (Fts3Hash *)sqlite3_user_data(context);
  159875. p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
  159876. if( !p ){
  159877. char *zErr2 = sqlite3_mprintf("unknown tokenizer: %s", zName);
  159878. sqlite3_result_error(context, zErr2, -1);
  159879. sqlite3_free(zErr2);
  159880. return;
  159881. }
  159882. pRet = Tcl_NewObj();
  159883. Tcl_IncrRefCount(pRet);
  159884. for(i=1; i<argc-1; i++){
  159885. azArg[i-1] = (const char *)sqlite3_value_text(argv[i]);
  159886. }
  159887. if( SQLITE_OK!=p->xCreate(argc-2, azArg, &pTokenizer) ){
  159888. zErr = "error in xCreate()";
  159889. goto finish;
  159890. }
  159891. pTokenizer->pModule = p;
  159892. if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){
  159893. zErr = "error in xOpen()";
  159894. goto finish;
  159895. }
  159896. while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
  159897. Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
  159898. Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
  159899. zToken = &zInput[iStart];
  159900. nToken = iEnd-iStart;
  159901. Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
  159902. }
  159903. if( SQLITE_OK!=p->xClose(pCsr) ){
  159904. zErr = "error in xClose()";
  159905. goto finish;
  159906. }
  159907. if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
  159908. zErr = "error in xDestroy()";
  159909. goto finish;
  159910. }
  159911. finish:
  159912. if( zErr ){
  159913. sqlite3_result_error(context, zErr, -1);
  159914. }else{
  159915. sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
  159916. }
  159917. Tcl_DecrRefCount(pRet);
  159918. }
  159919. static
  159920. int registerTokenizer(
  159921. sqlite3 *db,
  159922. char *zName,
  159923. const sqlite3_tokenizer_module *p
  159924. ){
  159925. int rc;
  159926. sqlite3_stmt *pStmt;
  159927. const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
  159928. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  159929. if( rc!=SQLITE_OK ){
  159930. return rc;
  159931. }
  159932. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  159933. sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
  159934. sqlite3_step(pStmt);
  159935. return sqlite3_finalize(pStmt);
  159936. }
  159937. static
  159938. int queryTokenizer(
  159939. sqlite3 *db,
  159940. char *zName,
  159941. const sqlite3_tokenizer_module **pp
  159942. ){
  159943. int rc;
  159944. sqlite3_stmt *pStmt;
  159945. const char zSql[] = "SELECT fts3_tokenizer(?)";
  159946. *pp = 0;
  159947. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  159948. if( rc!=SQLITE_OK ){
  159949. return rc;
  159950. }
  159951. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  159952. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  159953. if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
  159954. memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
  159955. }
  159956. }
  159957. return sqlite3_finalize(pStmt);
  159958. }
  159959. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  159960. /*
  159961. ** Implementation of the scalar function fts3_tokenizer_internal_test().
  159962. ** This function is used for testing only, it is not included in the
  159963. ** build unless SQLITE_TEST is defined.
  159964. **
  159965. ** The purpose of this is to test that the fts3_tokenizer() function
  159966. ** can be used as designed by the C-code in the queryTokenizer and
  159967. ** registerTokenizer() functions above. These two functions are repeated
  159968. ** in the README.tokenizer file as an example, so it is important to
  159969. ** test them.
  159970. **
  159971. ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
  159972. ** function with no arguments. An assert() will fail if a problem is
  159973. ** detected. i.e.:
  159974. **
  159975. ** SELECT fts3_tokenizer_internal_test();
  159976. **
  159977. */
  159978. static void intTestFunc(
  159979. sqlite3_context *context,
  159980. int argc,
  159981. sqlite3_value **argv
  159982. ){
  159983. int rc;
  159984. const sqlite3_tokenizer_module *p1;
  159985. const sqlite3_tokenizer_module *p2;
  159986. sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
  159987. UNUSED_PARAMETER(argc);
  159988. UNUSED_PARAMETER(argv);
  159989. /* Test the query function */
  159990. sqlite3Fts3SimpleTokenizerModule(&p1);
  159991. rc = queryTokenizer(db, "simple", &p2);
  159992. assert( rc==SQLITE_OK );
  159993. assert( p1==p2 );
  159994. rc = queryTokenizer(db, "nosuchtokenizer", &p2);
  159995. assert( rc==SQLITE_ERROR );
  159996. assert( p2==0 );
  159997. assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
  159998. /* Test the storage function */
  159999. if( fts3TokenizerEnabled(context) ){
  160000. rc = registerTokenizer(db, "nosuchtokenizer", p1);
  160001. assert( rc==SQLITE_OK );
  160002. rc = queryTokenizer(db, "nosuchtokenizer", &p2);
  160003. assert( rc==SQLITE_OK );
  160004. assert( p2==p1 );
  160005. }
  160006. sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
  160007. }
  160008. #endif
  160009. /*
  160010. ** Set up SQL objects in database db used to access the contents of
  160011. ** the hash table pointed to by argument pHash. The hash table must
  160012. ** been initialized to use string keys, and to take a private copy
  160013. ** of the key when a value is inserted. i.e. by a call similar to:
  160014. **
  160015. ** sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
  160016. **
  160017. ** This function adds a scalar function (see header comment above
  160018. ** fts3TokenizerFunc() in this file for details) and, if ENABLE_TABLE is
  160019. ** defined at compilation time, a temporary virtual table (see header
  160020. ** comment above struct HashTableVtab) to the database schema. Both
  160021. ** provide read/write access to the contents of *pHash.
  160022. **
  160023. ** The third argument to this function, zName, is used as the name
  160024. ** of both the scalar and, if created, the virtual table.
  160025. */
  160026. SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
  160027. sqlite3 *db,
  160028. Fts3Hash *pHash,
  160029. const char *zName
  160030. ){
  160031. int rc = SQLITE_OK;
  160032. void *p = (void *)pHash;
  160033. const int any = SQLITE_ANY;
  160034. #ifdef SQLITE_TEST
  160035. char *zTest = 0;
  160036. char *zTest2 = 0;
  160037. void *pdb = (void *)db;
  160038. zTest = sqlite3_mprintf("%s_test", zName);
  160039. zTest2 = sqlite3_mprintf("%s_internal_test", zName);
  160040. if( !zTest || !zTest2 ){
  160041. rc = SQLITE_NOMEM;
  160042. }
  160043. #endif
  160044. if( SQLITE_OK==rc ){
  160045. rc = sqlite3_create_function(db, zName, 1, any, p, fts3TokenizerFunc, 0, 0);
  160046. }
  160047. if( SQLITE_OK==rc ){
  160048. rc = sqlite3_create_function(db, zName, 2, any, p, fts3TokenizerFunc, 0, 0);
  160049. }
  160050. #ifdef SQLITE_TEST
  160051. if( SQLITE_OK==rc ){
  160052. rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0);
  160053. }
  160054. if( SQLITE_OK==rc ){
  160055. rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
  160056. }
  160057. #endif
  160058. #ifdef SQLITE_TEST
  160059. sqlite3_free(zTest);
  160060. sqlite3_free(zTest2);
  160061. #endif
  160062. return rc;
  160063. }
  160064. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  160065. /************** End of fts3_tokenizer.c **************************************/
  160066. /************** Begin file fts3_tokenizer1.c *********************************/
  160067. /*
  160068. ** 2006 Oct 10
  160069. **
  160070. ** The author disclaims copyright to this source code. In place of
  160071. ** a legal notice, here is a blessing:
  160072. **
  160073. ** May you do good and not evil.
  160074. ** May you find forgiveness for yourself and forgive others.
  160075. ** May you share freely, never taking more than you give.
  160076. **
  160077. ******************************************************************************
  160078. **
  160079. ** Implementation of the "simple" full-text-search tokenizer.
  160080. */
  160081. /*
  160082. ** The code in this file is only compiled if:
  160083. **
  160084. ** * The FTS3 module is being built as an extension
  160085. ** (in which case SQLITE_CORE is not defined), or
  160086. **
  160087. ** * The FTS3 module is being built into the core of
  160088. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  160089. */
  160090. /* #include "fts3Int.h" */
  160091. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  160092. /* #include <assert.h> */
  160093. /* #include <stdlib.h> */
  160094. /* #include <stdio.h> */
  160095. /* #include <string.h> */
  160096. /* #include "fts3_tokenizer.h" */
  160097. typedef struct simple_tokenizer {
  160098. sqlite3_tokenizer base;
  160099. char delim[128]; /* flag ASCII delimiters */
  160100. } simple_tokenizer;
  160101. typedef struct simple_tokenizer_cursor {
  160102. sqlite3_tokenizer_cursor base;
  160103. const char *pInput; /* input we are tokenizing */
  160104. int nBytes; /* size of the input */
  160105. int iOffset; /* current position in pInput */
  160106. int iToken; /* index of next token to be returned */
  160107. char *pToken; /* storage for current token */
  160108. int nTokenAllocated; /* space allocated to zToken buffer */
  160109. } simple_tokenizer_cursor;
  160110. static int simpleDelim(simple_tokenizer *t, unsigned char c){
  160111. return c<0x80 && t->delim[c];
  160112. }
  160113. static int fts3_isalnum(int x){
  160114. return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
  160115. }
  160116. /*
  160117. ** Create a new tokenizer instance.
  160118. */
  160119. static int simpleCreate(
  160120. int argc, const char * const *argv,
  160121. sqlite3_tokenizer **ppTokenizer
  160122. ){
  160123. simple_tokenizer *t;
  160124. t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
  160125. if( t==NULL ) return SQLITE_NOMEM;
  160126. memset(t, 0, sizeof(*t));
  160127. /* TODO(shess) Delimiters need to remain the same from run to run,
  160128. ** else we need to reindex. One solution would be a meta-table to
  160129. ** track such information in the database, then we'd only want this
  160130. ** information on the initial create.
  160131. */
  160132. if( argc>1 ){
  160133. int i, n = (int)strlen(argv[1]);
  160134. for(i=0; i<n; i++){
  160135. unsigned char ch = argv[1][i];
  160136. /* We explicitly don't support UTF-8 delimiters for now. */
  160137. if( ch>=0x80 ){
  160138. sqlite3_free(t);
  160139. return SQLITE_ERROR;
  160140. }
  160141. t->delim[ch] = 1;
  160142. }
  160143. } else {
  160144. /* Mark non-alphanumeric ASCII characters as delimiters */
  160145. int i;
  160146. for(i=1; i<0x80; i++){
  160147. t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
  160148. }
  160149. }
  160150. *ppTokenizer = &t->base;
  160151. return SQLITE_OK;
  160152. }
  160153. /*
  160154. ** Destroy a tokenizer
  160155. */
  160156. static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
  160157. sqlite3_free(pTokenizer);
  160158. return SQLITE_OK;
  160159. }
  160160. /*
  160161. ** Prepare to begin tokenizing a particular string. The input
  160162. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  160163. ** used to incrementally tokenize this string is returned in
  160164. ** *ppCursor.
  160165. */
  160166. static int simpleOpen(
  160167. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  160168. const char *pInput, int nBytes, /* String to be tokenized */
  160169. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  160170. ){
  160171. simple_tokenizer_cursor *c;
  160172. UNUSED_PARAMETER(pTokenizer);
  160173. c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
  160174. if( c==NULL ) return SQLITE_NOMEM;
  160175. c->pInput = pInput;
  160176. if( pInput==0 ){
  160177. c->nBytes = 0;
  160178. }else if( nBytes<0 ){
  160179. c->nBytes = (int)strlen(pInput);
  160180. }else{
  160181. c->nBytes = nBytes;
  160182. }
  160183. c->iOffset = 0; /* start tokenizing at the beginning */
  160184. c->iToken = 0;
  160185. c->pToken = NULL; /* no space allocated, yet. */
  160186. c->nTokenAllocated = 0;
  160187. *ppCursor = &c->base;
  160188. return SQLITE_OK;
  160189. }
  160190. /*
  160191. ** Close a tokenization cursor previously opened by a call to
  160192. ** simpleOpen() above.
  160193. */
  160194. static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
  160195. simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
  160196. sqlite3_free(c->pToken);
  160197. sqlite3_free(c);
  160198. return SQLITE_OK;
  160199. }
  160200. /*
  160201. ** Extract the next token from a tokenization cursor. The cursor must
  160202. ** have been opened by a prior call to simpleOpen().
  160203. */
  160204. static int simpleNext(
  160205. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
  160206. const char **ppToken, /* OUT: *ppToken is the token text */
  160207. int *pnBytes, /* OUT: Number of bytes in token */
  160208. int *piStartOffset, /* OUT: Starting offset of token */
  160209. int *piEndOffset, /* OUT: Ending offset of token */
  160210. int *piPosition /* OUT: Position integer of token */
  160211. ){
  160212. simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
  160213. simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
  160214. unsigned char *p = (unsigned char *)c->pInput;
  160215. while( c->iOffset<c->nBytes ){
  160216. int iStartOffset;
  160217. /* Scan past delimiter characters */
  160218. while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
  160219. c->iOffset++;
  160220. }
  160221. /* Count non-delimiter characters. */
  160222. iStartOffset = c->iOffset;
  160223. while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
  160224. c->iOffset++;
  160225. }
  160226. if( c->iOffset>iStartOffset ){
  160227. int i, n = c->iOffset-iStartOffset;
  160228. if( n>c->nTokenAllocated ){
  160229. char *pNew;
  160230. c->nTokenAllocated = n+20;
  160231. pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
  160232. if( !pNew ) return SQLITE_NOMEM;
  160233. c->pToken = pNew;
  160234. }
  160235. for(i=0; i<n; i++){
  160236. /* TODO(shess) This needs expansion to handle UTF-8
  160237. ** case-insensitivity.
  160238. */
  160239. unsigned char ch = p[iStartOffset+i];
  160240. c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
  160241. }
  160242. *ppToken = c->pToken;
  160243. *pnBytes = n;
  160244. *piStartOffset = iStartOffset;
  160245. *piEndOffset = c->iOffset;
  160246. *piPosition = c->iToken++;
  160247. return SQLITE_OK;
  160248. }
  160249. }
  160250. return SQLITE_DONE;
  160251. }
  160252. /*
  160253. ** The set of routines that implement the simple tokenizer
  160254. */
  160255. static const sqlite3_tokenizer_module simpleTokenizerModule = {
  160256. 0,
  160257. simpleCreate,
  160258. simpleDestroy,
  160259. simpleOpen,
  160260. simpleClose,
  160261. simpleNext,
  160262. 0,
  160263. };
  160264. /*
  160265. ** Allocate a new simple tokenizer. Return a pointer to the new
  160266. ** tokenizer in *ppModule
  160267. */
  160268. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
  160269. sqlite3_tokenizer_module const**ppModule
  160270. ){
  160271. *ppModule = &simpleTokenizerModule;
  160272. }
  160273. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  160274. /************** End of fts3_tokenizer1.c *************************************/
  160275. /************** Begin file fts3_tokenize_vtab.c ******************************/
  160276. /*
  160277. ** 2013 Apr 22
  160278. **
  160279. ** The author disclaims copyright to this source code. In place of
  160280. ** a legal notice, here is a blessing:
  160281. **
  160282. ** May you do good and not evil.
  160283. ** May you find forgiveness for yourself and forgive others.
  160284. ** May you share freely, never taking more than you give.
  160285. **
  160286. ******************************************************************************
  160287. **
  160288. ** This file contains code for the "fts3tokenize" virtual table module.
  160289. ** An fts3tokenize virtual table is created as follows:
  160290. **
  160291. ** CREATE VIRTUAL TABLE <tbl> USING fts3tokenize(
  160292. ** <tokenizer-name>, <arg-1>, ...
  160293. ** );
  160294. **
  160295. ** The table created has the following schema:
  160296. **
  160297. ** CREATE TABLE <tbl>(input, token, start, end, position)
  160298. **
  160299. ** When queried, the query must include a WHERE clause of type:
  160300. **
  160301. ** input = <string>
  160302. **
  160303. ** The virtual table module tokenizes this <string>, using the FTS3
  160304. ** tokenizer specified by the arguments to the CREATE VIRTUAL TABLE
  160305. ** statement and returns one row for each token in the result. With
  160306. ** fields set as follows:
  160307. **
  160308. ** input: Always set to a copy of <string>
  160309. ** token: A token from the input.
  160310. ** start: Byte offset of the token within the input <string>.
  160311. ** end: Byte offset of the byte immediately following the end of the
  160312. ** token within the input string.
  160313. ** pos: Token offset of token within input.
  160314. **
  160315. */
  160316. /* #include "fts3Int.h" */
  160317. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  160318. /* #include <string.h> */
  160319. /* #include <assert.h> */
  160320. typedef struct Fts3tokTable Fts3tokTable;
  160321. typedef struct Fts3tokCursor Fts3tokCursor;
  160322. /*
  160323. ** Virtual table structure.
  160324. */
  160325. struct Fts3tokTable {
  160326. sqlite3_vtab base; /* Base class used by SQLite core */
  160327. const sqlite3_tokenizer_module *pMod;
  160328. sqlite3_tokenizer *pTok;
  160329. };
  160330. /*
  160331. ** Virtual table cursor structure.
  160332. */
  160333. struct Fts3tokCursor {
  160334. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  160335. char *zInput; /* Input string */
  160336. sqlite3_tokenizer_cursor *pCsr; /* Cursor to iterate through zInput */
  160337. int iRowid; /* Current 'rowid' value */
  160338. const char *zToken; /* Current 'token' value */
  160339. int nToken; /* Size of zToken in bytes */
  160340. int iStart; /* Current 'start' value */
  160341. int iEnd; /* Current 'end' value */
  160342. int iPos; /* Current 'pos' value */
  160343. };
  160344. /*
  160345. ** Query FTS for the tokenizer implementation named zName.
  160346. */
  160347. static int fts3tokQueryTokenizer(
  160348. Fts3Hash *pHash,
  160349. const char *zName,
  160350. const sqlite3_tokenizer_module **pp,
  160351. char **pzErr
  160352. ){
  160353. sqlite3_tokenizer_module *p;
  160354. int nName = (int)strlen(zName);
  160355. p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
  160356. if( !p ){
  160357. sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", zName);
  160358. return SQLITE_ERROR;
  160359. }
  160360. *pp = p;
  160361. return SQLITE_OK;
  160362. }
  160363. /*
  160364. ** The second argument, argv[], is an array of pointers to nul-terminated
  160365. ** strings. This function makes a copy of the array and strings into a
  160366. ** single block of memory. It then dequotes any of the strings that appear
  160367. ** to be quoted.
  160368. **
  160369. ** If successful, output parameter *pazDequote is set to point at the
  160370. ** array of dequoted strings and SQLITE_OK is returned. The caller is
  160371. ** responsible for eventually calling sqlite3_free() to free the array
  160372. ** in this case. Or, if an error occurs, an SQLite error code is returned.
  160373. ** The final value of *pazDequote is undefined in this case.
  160374. */
  160375. static int fts3tokDequoteArray(
  160376. int argc, /* Number of elements in argv[] */
  160377. const char * const *argv, /* Input array */
  160378. char ***pazDequote /* Output array */
  160379. ){
  160380. int rc = SQLITE_OK; /* Return code */
  160381. if( argc==0 ){
  160382. *pazDequote = 0;
  160383. }else{
  160384. int i;
  160385. int nByte = 0;
  160386. char **azDequote;
  160387. for(i=0; i<argc; i++){
  160388. nByte += (int)(strlen(argv[i]) + 1);
  160389. }
  160390. *pazDequote = azDequote = sqlite3_malloc64(sizeof(char *)*argc + nByte);
  160391. if( azDequote==0 ){
  160392. rc = SQLITE_NOMEM;
  160393. }else{
  160394. char *pSpace = (char *)&azDequote[argc];
  160395. for(i=0; i<argc; i++){
  160396. int n = (int)strlen(argv[i]);
  160397. azDequote[i] = pSpace;
  160398. memcpy(pSpace, argv[i], n+1);
  160399. sqlite3Fts3Dequote(pSpace);
  160400. pSpace += (n+1);
  160401. }
  160402. }
  160403. }
  160404. return rc;
  160405. }
  160406. /*
  160407. ** Schema of the tokenizer table.
  160408. */
  160409. #define FTS3_TOK_SCHEMA "CREATE TABLE x(input, token, start, end, position)"
  160410. /*
  160411. ** This function does all the work for both the xConnect and xCreate methods.
  160412. ** These tables have no persistent representation of their own, so xConnect
  160413. ** and xCreate are identical operations.
  160414. **
  160415. ** argv[0]: module name
  160416. ** argv[1]: database name
  160417. ** argv[2]: table name
  160418. ** argv[3]: first argument (tokenizer name)
  160419. */
  160420. static int fts3tokConnectMethod(
  160421. sqlite3 *db, /* Database connection */
  160422. void *pHash, /* Hash table of tokenizers */
  160423. int argc, /* Number of elements in argv array */
  160424. const char * const *argv, /* xCreate/xConnect argument array */
  160425. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  160426. char **pzErr /* OUT: sqlite3_malloc'd error message */
  160427. ){
  160428. Fts3tokTable *pTab = 0;
  160429. const sqlite3_tokenizer_module *pMod = 0;
  160430. sqlite3_tokenizer *pTok = 0;
  160431. int rc;
  160432. char **azDequote = 0;
  160433. int nDequote;
  160434. rc = sqlite3_declare_vtab(db, FTS3_TOK_SCHEMA);
  160435. if( rc!=SQLITE_OK ) return rc;
  160436. nDequote = argc-3;
  160437. rc = fts3tokDequoteArray(nDequote, &argv[3], &azDequote);
  160438. if( rc==SQLITE_OK ){
  160439. const char *zModule;
  160440. if( nDequote<1 ){
  160441. zModule = "simple";
  160442. }else{
  160443. zModule = azDequote[0];
  160444. }
  160445. rc = fts3tokQueryTokenizer((Fts3Hash*)pHash, zModule, &pMod, pzErr);
  160446. }
  160447. assert( (rc==SQLITE_OK)==(pMod!=0) );
  160448. if( rc==SQLITE_OK ){
  160449. const char * const *azArg = (const char * const *)&azDequote[1];
  160450. rc = pMod->xCreate((nDequote>1 ? nDequote-1 : 0), azArg, &pTok);
  160451. }
  160452. if( rc==SQLITE_OK ){
  160453. pTab = (Fts3tokTable *)sqlite3_malloc(sizeof(Fts3tokTable));
  160454. if( pTab==0 ){
  160455. rc = SQLITE_NOMEM;
  160456. }
  160457. }
  160458. if( rc==SQLITE_OK ){
  160459. memset(pTab, 0, sizeof(Fts3tokTable));
  160460. pTab->pMod = pMod;
  160461. pTab->pTok = pTok;
  160462. *ppVtab = &pTab->base;
  160463. }else{
  160464. if( pTok ){
  160465. pMod->xDestroy(pTok);
  160466. }
  160467. }
  160468. sqlite3_free(azDequote);
  160469. return rc;
  160470. }
  160471. /*
  160472. ** This function does the work for both the xDisconnect and xDestroy methods.
  160473. ** These tables have no persistent representation of their own, so xDisconnect
  160474. ** and xDestroy are identical operations.
  160475. */
  160476. static int fts3tokDisconnectMethod(sqlite3_vtab *pVtab){
  160477. Fts3tokTable *pTab = (Fts3tokTable *)pVtab;
  160478. pTab->pMod->xDestroy(pTab->pTok);
  160479. sqlite3_free(pTab);
  160480. return SQLITE_OK;
  160481. }
  160482. /*
  160483. ** xBestIndex - Analyze a WHERE and ORDER BY clause.
  160484. */
  160485. static int fts3tokBestIndexMethod(
  160486. sqlite3_vtab *pVTab,
  160487. sqlite3_index_info *pInfo
  160488. ){
  160489. int i;
  160490. UNUSED_PARAMETER(pVTab);
  160491. for(i=0; i<pInfo->nConstraint; i++){
  160492. if( pInfo->aConstraint[i].usable
  160493. && pInfo->aConstraint[i].iColumn==0
  160494. && pInfo->aConstraint[i].op==SQLITE_INDEX_CONSTRAINT_EQ
  160495. ){
  160496. pInfo->idxNum = 1;
  160497. pInfo->aConstraintUsage[i].argvIndex = 1;
  160498. pInfo->aConstraintUsage[i].omit = 1;
  160499. pInfo->estimatedCost = 1;
  160500. return SQLITE_OK;
  160501. }
  160502. }
  160503. pInfo->idxNum = 0;
  160504. assert( pInfo->estimatedCost>1000000.0 );
  160505. return SQLITE_OK;
  160506. }
  160507. /*
  160508. ** xOpen - Open a cursor.
  160509. */
  160510. static int fts3tokOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  160511. Fts3tokCursor *pCsr;
  160512. UNUSED_PARAMETER(pVTab);
  160513. pCsr = (Fts3tokCursor *)sqlite3_malloc(sizeof(Fts3tokCursor));
  160514. if( pCsr==0 ){
  160515. return SQLITE_NOMEM;
  160516. }
  160517. memset(pCsr, 0, sizeof(Fts3tokCursor));
  160518. *ppCsr = (sqlite3_vtab_cursor *)pCsr;
  160519. return SQLITE_OK;
  160520. }
  160521. /*
  160522. ** Reset the tokenizer cursor passed as the only argument. As if it had
  160523. ** just been returned by fts3tokOpenMethod().
  160524. */
  160525. static void fts3tokResetCursor(Fts3tokCursor *pCsr){
  160526. if( pCsr->pCsr ){
  160527. Fts3tokTable *pTab = (Fts3tokTable *)(pCsr->base.pVtab);
  160528. pTab->pMod->xClose(pCsr->pCsr);
  160529. pCsr->pCsr = 0;
  160530. }
  160531. sqlite3_free(pCsr->zInput);
  160532. pCsr->zInput = 0;
  160533. pCsr->zToken = 0;
  160534. pCsr->nToken = 0;
  160535. pCsr->iStart = 0;
  160536. pCsr->iEnd = 0;
  160537. pCsr->iPos = 0;
  160538. pCsr->iRowid = 0;
  160539. }
  160540. /*
  160541. ** xClose - Close a cursor.
  160542. */
  160543. static int fts3tokCloseMethod(sqlite3_vtab_cursor *pCursor){
  160544. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  160545. fts3tokResetCursor(pCsr);
  160546. sqlite3_free(pCsr);
  160547. return SQLITE_OK;
  160548. }
  160549. /*
  160550. ** xNext - Advance the cursor to the next row, if any.
  160551. */
  160552. static int fts3tokNextMethod(sqlite3_vtab_cursor *pCursor){
  160553. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  160554. Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
  160555. int rc; /* Return code */
  160556. pCsr->iRowid++;
  160557. rc = pTab->pMod->xNext(pCsr->pCsr,
  160558. &pCsr->zToken, &pCsr->nToken,
  160559. &pCsr->iStart, &pCsr->iEnd, &pCsr->iPos
  160560. );
  160561. if( rc!=SQLITE_OK ){
  160562. fts3tokResetCursor(pCsr);
  160563. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  160564. }
  160565. return rc;
  160566. }
  160567. /*
  160568. ** xFilter - Initialize a cursor to point at the start of its data.
  160569. */
  160570. static int fts3tokFilterMethod(
  160571. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  160572. int idxNum, /* Strategy index */
  160573. const char *idxStr, /* Unused */
  160574. int nVal, /* Number of elements in apVal */
  160575. sqlite3_value **apVal /* Arguments for the indexing scheme */
  160576. ){
  160577. int rc = SQLITE_ERROR;
  160578. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  160579. Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
  160580. UNUSED_PARAMETER(idxStr);
  160581. UNUSED_PARAMETER(nVal);
  160582. fts3tokResetCursor(pCsr);
  160583. if( idxNum==1 ){
  160584. const char *zByte = (const char *)sqlite3_value_text(apVal[0]);
  160585. int nByte = sqlite3_value_bytes(apVal[0]);
  160586. pCsr->zInput = sqlite3_malloc64(nByte+1);
  160587. if( pCsr->zInput==0 ){
  160588. rc = SQLITE_NOMEM;
  160589. }else{
  160590. memcpy(pCsr->zInput, zByte, nByte);
  160591. pCsr->zInput[nByte] = 0;
  160592. rc = pTab->pMod->xOpen(pTab->pTok, pCsr->zInput, nByte, &pCsr->pCsr);
  160593. if( rc==SQLITE_OK ){
  160594. pCsr->pCsr->pTokenizer = pTab->pTok;
  160595. }
  160596. }
  160597. }
  160598. if( rc!=SQLITE_OK ) return rc;
  160599. return fts3tokNextMethod(pCursor);
  160600. }
  160601. /*
  160602. ** xEof - Return true if the cursor is at EOF, or false otherwise.
  160603. */
  160604. static int fts3tokEofMethod(sqlite3_vtab_cursor *pCursor){
  160605. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  160606. return (pCsr->zToken==0);
  160607. }
  160608. /*
  160609. ** xColumn - Return a column value.
  160610. */
  160611. static int fts3tokColumnMethod(
  160612. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  160613. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  160614. int iCol /* Index of column to read value from */
  160615. ){
  160616. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  160617. /* CREATE TABLE x(input, token, start, end, position) */
  160618. switch( iCol ){
  160619. case 0:
  160620. sqlite3_result_text(pCtx, pCsr->zInput, -1, SQLITE_TRANSIENT);
  160621. break;
  160622. case 1:
  160623. sqlite3_result_text(pCtx, pCsr->zToken, pCsr->nToken, SQLITE_TRANSIENT);
  160624. break;
  160625. case 2:
  160626. sqlite3_result_int(pCtx, pCsr->iStart);
  160627. break;
  160628. case 3:
  160629. sqlite3_result_int(pCtx, pCsr->iEnd);
  160630. break;
  160631. default:
  160632. assert( iCol==4 );
  160633. sqlite3_result_int(pCtx, pCsr->iPos);
  160634. break;
  160635. }
  160636. return SQLITE_OK;
  160637. }
  160638. /*
  160639. ** xRowid - Return the current rowid for the cursor.
  160640. */
  160641. static int fts3tokRowidMethod(
  160642. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  160643. sqlite_int64 *pRowid /* OUT: Rowid value */
  160644. ){
  160645. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  160646. *pRowid = (sqlite3_int64)pCsr->iRowid;
  160647. return SQLITE_OK;
  160648. }
  160649. /*
  160650. ** Register the fts3tok module with database connection db. Return SQLITE_OK
  160651. ** if successful or an error code if sqlite3_create_module() fails.
  160652. */
  160653. SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){
  160654. static const sqlite3_module fts3tok_module = {
  160655. 0, /* iVersion */
  160656. fts3tokConnectMethod, /* xCreate */
  160657. fts3tokConnectMethod, /* xConnect */
  160658. fts3tokBestIndexMethod, /* xBestIndex */
  160659. fts3tokDisconnectMethod, /* xDisconnect */
  160660. fts3tokDisconnectMethod, /* xDestroy */
  160661. fts3tokOpenMethod, /* xOpen */
  160662. fts3tokCloseMethod, /* xClose */
  160663. fts3tokFilterMethod, /* xFilter */
  160664. fts3tokNextMethod, /* xNext */
  160665. fts3tokEofMethod, /* xEof */
  160666. fts3tokColumnMethod, /* xColumn */
  160667. fts3tokRowidMethod, /* xRowid */
  160668. 0, /* xUpdate */
  160669. 0, /* xBegin */
  160670. 0, /* xSync */
  160671. 0, /* xCommit */
  160672. 0, /* xRollback */
  160673. 0, /* xFindFunction */
  160674. 0, /* xRename */
  160675. 0, /* xSavepoint */
  160676. 0, /* xRelease */
  160677. 0, /* xRollbackTo */
  160678. 0 /* xShadowName */
  160679. };
  160680. int rc; /* Return code */
  160681. rc = sqlite3_create_module(db, "fts3tokenize", &fts3tok_module, (void*)pHash);
  160682. return rc;
  160683. }
  160684. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  160685. /************** End of fts3_tokenize_vtab.c **********************************/
  160686. /************** Begin file fts3_write.c **************************************/
  160687. /*
  160688. ** 2009 Oct 23
  160689. **
  160690. ** The author disclaims copyright to this source code. In place of
  160691. ** a legal notice, here is a blessing:
  160692. **
  160693. ** May you do good and not evil.
  160694. ** May you find forgiveness for yourself and forgive others.
  160695. ** May you share freely, never taking more than you give.
  160696. **
  160697. ******************************************************************************
  160698. **
  160699. ** This file is part of the SQLite FTS3 extension module. Specifically,
  160700. ** this file contains code to insert, update and delete rows from FTS3
  160701. ** tables. It also contains code to merge FTS3 b-tree segments. Some
  160702. ** of the sub-routines used to merge segments are also used by the query
  160703. ** code in fts3.c.
  160704. */
  160705. /* #include "fts3Int.h" */
  160706. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  160707. /* #include <string.h> */
  160708. /* #include <assert.h> */
  160709. /* #include <stdlib.h> */
  160710. #define FTS_MAX_APPENDABLE_HEIGHT 16
  160711. /*
  160712. ** When full-text index nodes are loaded from disk, the buffer that they
  160713. ** are loaded into has the following number of bytes of padding at the end
  160714. ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
  160715. ** of 920 bytes is allocated for it.
  160716. **
  160717. ** This means that if we have a pointer into a buffer containing node data,
  160718. ** it is always safe to read up to two varints from it without risking an
  160719. ** overread, even if the node data is corrupted.
  160720. */
  160721. #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
  160722. /*
  160723. ** Under certain circumstances, b-tree nodes (doclists) can be loaded into
  160724. ** memory incrementally instead of all at once. This can be a big performance
  160725. ** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
  160726. ** method before retrieving all query results (as may happen, for example,
  160727. ** if a query has a LIMIT clause).
  160728. **
  160729. ** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD
  160730. ** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
  160731. ** The code is written so that the hard lower-limit for each of these values
  160732. ** is 1. Clearly such small values would be inefficient, but can be useful
  160733. ** for testing purposes.
  160734. **
  160735. ** If this module is built with SQLITE_TEST defined, these constants may
  160736. ** be overridden at runtime for testing purposes. File fts3_test.c contains
  160737. ** a Tcl interface to read and write the values.
  160738. */
  160739. #ifdef SQLITE_TEST
  160740. int test_fts3_node_chunksize = (4*1024);
  160741. int test_fts3_node_chunk_threshold = (4*1024)*4;
  160742. # define FTS3_NODE_CHUNKSIZE test_fts3_node_chunksize
  160743. # define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
  160744. #else
  160745. # define FTS3_NODE_CHUNKSIZE (4*1024)
  160746. # define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
  160747. #endif
  160748. /*
  160749. ** The two values that may be meaningfully bound to the :1 parameter in
  160750. ** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.
  160751. */
  160752. #define FTS_STAT_DOCTOTAL 0
  160753. #define FTS_STAT_INCRMERGEHINT 1
  160754. #define FTS_STAT_AUTOINCRMERGE 2
  160755. /*
  160756. ** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic
  160757. ** and incremental merge operation that takes place. This is used for
  160758. ** debugging FTS only, it should not usually be turned on in production
  160759. ** systems.
  160760. */
  160761. #ifdef FTS3_LOG_MERGES
  160762. static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){
  160763. sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel);
  160764. }
  160765. #else
  160766. #define fts3LogMerge(x, y)
  160767. #endif
  160768. typedef struct PendingList PendingList;
  160769. typedef struct SegmentNode SegmentNode;
  160770. typedef struct SegmentWriter SegmentWriter;
  160771. /*
  160772. ** An instance of the following data structure is used to build doclists
  160773. ** incrementally. See function fts3PendingListAppend() for details.
  160774. */
  160775. struct PendingList {
  160776. int nData;
  160777. char *aData;
  160778. int nSpace;
  160779. sqlite3_int64 iLastDocid;
  160780. sqlite3_int64 iLastCol;
  160781. sqlite3_int64 iLastPos;
  160782. };
  160783. /*
  160784. ** Each cursor has a (possibly empty) linked list of the following objects.
  160785. */
  160786. struct Fts3DeferredToken {
  160787. Fts3PhraseToken *pToken; /* Pointer to corresponding expr token */
  160788. int iCol; /* Column token must occur in */
  160789. Fts3DeferredToken *pNext; /* Next in list of deferred tokens */
  160790. PendingList *pList; /* Doclist is assembled here */
  160791. };
  160792. /*
  160793. ** An instance of this structure is used to iterate through the terms on
  160794. ** a contiguous set of segment b-tree leaf nodes. Although the details of
  160795. ** this structure are only manipulated by code in this file, opaque handles
  160796. ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
  160797. ** terms when querying the full-text index. See functions:
  160798. **
  160799. ** sqlite3Fts3SegReaderNew()
  160800. ** sqlite3Fts3SegReaderFree()
  160801. ** sqlite3Fts3SegReaderIterate()
  160802. **
  160803. ** Methods used to manipulate Fts3SegReader structures:
  160804. **
  160805. ** fts3SegReaderNext()
  160806. ** fts3SegReaderFirstDocid()
  160807. ** fts3SegReaderNextDocid()
  160808. */
  160809. struct Fts3SegReader {
  160810. int iIdx; /* Index within level, or 0x7FFFFFFF for PT */
  160811. u8 bLookup; /* True for a lookup only */
  160812. u8 rootOnly; /* True for a root-only reader */
  160813. sqlite3_int64 iStartBlock; /* Rowid of first leaf block to traverse */
  160814. sqlite3_int64 iLeafEndBlock; /* Rowid of final leaf block to traverse */
  160815. sqlite3_int64 iEndBlock; /* Rowid of final block in segment (or 0) */
  160816. sqlite3_int64 iCurrentBlock; /* Current leaf block (or 0) */
  160817. char *aNode; /* Pointer to node data (or NULL) */
  160818. int nNode; /* Size of buffer at aNode (or 0) */
  160819. int nPopulate; /* If >0, bytes of buffer aNode[] loaded */
  160820. sqlite3_blob *pBlob; /* If not NULL, blob handle to read node */
  160821. Fts3HashElem **ppNextElem;
  160822. /* Variables set by fts3SegReaderNext(). These may be read directly
  160823. ** by the caller. They are valid from the time SegmentReaderNew() returns
  160824. ** until SegmentReaderNext() returns something other than SQLITE_OK
  160825. ** (i.e. SQLITE_DONE).
  160826. */
  160827. int nTerm; /* Number of bytes in current term */
  160828. char *zTerm; /* Pointer to current term */
  160829. int nTermAlloc; /* Allocated size of zTerm buffer */
  160830. char *aDoclist; /* Pointer to doclist of current entry */
  160831. int nDoclist; /* Size of doclist in current entry */
  160832. /* The following variables are used by fts3SegReaderNextDocid() to iterate
  160833. ** through the current doclist (aDoclist/nDoclist).
  160834. */
  160835. char *pOffsetList;
  160836. int nOffsetList; /* For descending pending seg-readers only */
  160837. sqlite3_int64 iDocid;
  160838. };
  160839. #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
  160840. #define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)
  160841. /*
  160842. ** An instance of this structure is used to create a segment b-tree in the
  160843. ** database. The internal details of this type are only accessed by the
  160844. ** following functions:
  160845. **
  160846. ** fts3SegWriterAdd()
  160847. ** fts3SegWriterFlush()
  160848. ** fts3SegWriterFree()
  160849. */
  160850. struct SegmentWriter {
  160851. SegmentNode *pTree; /* Pointer to interior tree structure */
  160852. sqlite3_int64 iFirst; /* First slot in %_segments written */
  160853. sqlite3_int64 iFree; /* Next free slot in %_segments */
  160854. char *zTerm; /* Pointer to previous term buffer */
  160855. int nTerm; /* Number of bytes in zTerm */
  160856. int nMalloc; /* Size of malloc'd buffer at zMalloc */
  160857. char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
  160858. int nSize; /* Size of allocation at aData */
  160859. int nData; /* Bytes of data in aData */
  160860. char *aData; /* Pointer to block from malloc() */
  160861. i64 nLeafData; /* Number of bytes of leaf data written */
  160862. };
  160863. /*
  160864. ** Type SegmentNode is used by the following three functions to create
  160865. ** the interior part of the segment b+-tree structures (everything except
  160866. ** the leaf nodes). These functions and type are only ever used by code
  160867. ** within the fts3SegWriterXXX() family of functions described above.
  160868. **
  160869. ** fts3NodeAddTerm()
  160870. ** fts3NodeWrite()
  160871. ** fts3NodeFree()
  160872. **
  160873. ** When a b+tree is written to the database (either as a result of a merge
  160874. ** or the pending-terms table being flushed), leaves are written into the
  160875. ** database file as soon as they are completely populated. The interior of
  160876. ** the tree is assembled in memory and written out only once all leaves have
  160877. ** been populated and stored. This is Ok, as the b+-tree fanout is usually
  160878. ** very large, meaning that the interior of the tree consumes relatively
  160879. ** little memory.
  160880. */
  160881. struct SegmentNode {
  160882. SegmentNode *pParent; /* Parent node (or NULL for root node) */
  160883. SegmentNode *pRight; /* Pointer to right-sibling */
  160884. SegmentNode *pLeftmost; /* Pointer to left-most node of this depth */
  160885. int nEntry; /* Number of terms written to node so far */
  160886. char *zTerm; /* Pointer to previous term buffer */
  160887. int nTerm; /* Number of bytes in zTerm */
  160888. int nMalloc; /* Size of malloc'd buffer at zMalloc */
  160889. char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
  160890. int nData; /* Bytes of valid data so far */
  160891. char *aData; /* Node data */
  160892. };
  160893. /*
  160894. ** Valid values for the second argument to fts3SqlStmt().
  160895. */
  160896. #define SQL_DELETE_CONTENT 0
  160897. #define SQL_IS_EMPTY 1
  160898. #define SQL_DELETE_ALL_CONTENT 2
  160899. #define SQL_DELETE_ALL_SEGMENTS 3
  160900. #define SQL_DELETE_ALL_SEGDIR 4
  160901. #define SQL_DELETE_ALL_DOCSIZE 5
  160902. #define SQL_DELETE_ALL_STAT 6
  160903. #define SQL_SELECT_CONTENT_BY_ROWID 7
  160904. #define SQL_NEXT_SEGMENT_INDEX 8
  160905. #define SQL_INSERT_SEGMENTS 9
  160906. #define SQL_NEXT_SEGMENTS_ID 10
  160907. #define SQL_INSERT_SEGDIR 11
  160908. #define SQL_SELECT_LEVEL 12
  160909. #define SQL_SELECT_LEVEL_RANGE 13
  160910. #define SQL_SELECT_LEVEL_COUNT 14
  160911. #define SQL_SELECT_SEGDIR_MAX_LEVEL 15
  160912. #define SQL_DELETE_SEGDIR_LEVEL 16
  160913. #define SQL_DELETE_SEGMENTS_RANGE 17
  160914. #define SQL_CONTENT_INSERT 18
  160915. #define SQL_DELETE_DOCSIZE 19
  160916. #define SQL_REPLACE_DOCSIZE 20
  160917. #define SQL_SELECT_DOCSIZE 21
  160918. #define SQL_SELECT_STAT 22
  160919. #define SQL_REPLACE_STAT 23
  160920. #define SQL_SELECT_ALL_PREFIX_LEVEL 24
  160921. #define SQL_DELETE_ALL_TERMS_SEGDIR 25
  160922. #define SQL_DELETE_SEGDIR_RANGE 26
  160923. #define SQL_SELECT_ALL_LANGID 27
  160924. #define SQL_FIND_MERGE_LEVEL 28
  160925. #define SQL_MAX_LEAF_NODE_ESTIMATE 29
  160926. #define SQL_DELETE_SEGDIR_ENTRY 30
  160927. #define SQL_SHIFT_SEGDIR_ENTRY 31
  160928. #define SQL_SELECT_SEGDIR 32
  160929. #define SQL_CHOMP_SEGDIR 33
  160930. #define SQL_SEGMENT_IS_APPENDABLE 34
  160931. #define SQL_SELECT_INDEXES 35
  160932. #define SQL_SELECT_MXLEVEL 36
  160933. #define SQL_SELECT_LEVEL_RANGE2 37
  160934. #define SQL_UPDATE_LEVEL_IDX 38
  160935. #define SQL_UPDATE_LEVEL 39
  160936. /*
  160937. ** This function is used to obtain an SQLite prepared statement handle
  160938. ** for the statement identified by the second argument. If successful,
  160939. ** *pp is set to the requested statement handle and SQLITE_OK returned.
  160940. ** Otherwise, an SQLite error code is returned and *pp is set to 0.
  160941. **
  160942. ** If argument apVal is not NULL, then it must point to an array with
  160943. ** at least as many entries as the requested statement has bound
  160944. ** parameters. The values are bound to the statements parameters before
  160945. ** returning.
  160946. */
  160947. static int fts3SqlStmt(
  160948. Fts3Table *p, /* Virtual table handle */
  160949. int eStmt, /* One of the SQL_XXX constants above */
  160950. sqlite3_stmt **pp, /* OUT: Statement handle */
  160951. sqlite3_value **apVal /* Values to bind to statement */
  160952. ){
  160953. const char *azSql[] = {
  160954. /* 0 */ "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
  160955. /* 1 */ "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
  160956. /* 2 */ "DELETE FROM %Q.'%q_content'",
  160957. /* 3 */ "DELETE FROM %Q.'%q_segments'",
  160958. /* 4 */ "DELETE FROM %Q.'%q_segdir'",
  160959. /* 5 */ "DELETE FROM %Q.'%q_docsize'",
  160960. /* 6 */ "DELETE FROM %Q.'%q_stat'",
  160961. /* 7 */ "SELECT %s WHERE rowid=?",
  160962. /* 8 */ "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
  160963. /* 9 */ "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
  160964. /* 10 */ "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
  160965. /* 11 */ "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
  160966. /* Return segments in order from oldest to newest.*/
  160967. /* 12 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  160968. "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
  160969. /* 13 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  160970. "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
  160971. "ORDER BY level DESC, idx ASC",
  160972. /* 14 */ "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
  160973. /* 15 */ "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
  160974. /* 16 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
  160975. /* 17 */ "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
  160976. /* 18 */ "INSERT INTO %Q.'%q_content' VALUES(%s)",
  160977. /* 19 */ "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
  160978. /* 20 */ "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
  160979. /* 21 */ "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
  160980. /* 22 */ "SELECT value FROM %Q.'%q_stat' WHERE id=?",
  160981. /* 23 */ "REPLACE INTO %Q.'%q_stat' VALUES(?,?)",
  160982. /* 24 */ "",
  160983. /* 25 */ "",
  160984. /* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
  160985. /* 27 */ "SELECT ? UNION SELECT level / (1024 * ?) FROM %Q.'%q_segdir'",
  160986. /* This statement is used to determine which level to read the input from
  160987. ** when performing an incremental merge. It returns the absolute level number
  160988. ** of the oldest level in the db that contains at least ? segments. Or,
  160989. ** if no level in the FTS index contains more than ? segments, the statement
  160990. ** returns zero rows. */
  160991. /* 28 */ "SELECT level, count(*) AS cnt FROM %Q.'%q_segdir' "
  160992. " GROUP BY level HAVING cnt>=?"
  160993. " ORDER BY (level %% 1024) ASC LIMIT 1",
  160994. /* Estimate the upper limit on the number of leaf nodes in a new segment
  160995. ** created by merging the oldest :2 segments from absolute level :1. See
  160996. ** function sqlite3Fts3Incrmerge() for details. */
  160997. /* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) "
  160998. " FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?",
  160999. /* SQL_DELETE_SEGDIR_ENTRY
  161000. ** Delete the %_segdir entry on absolute level :1 with index :2. */
  161001. /* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
  161002. /* SQL_SHIFT_SEGDIR_ENTRY
  161003. ** Modify the idx value for the segment with idx=:3 on absolute level :2
  161004. ** to :1. */
  161005. /* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?",
  161006. /* SQL_SELECT_SEGDIR
  161007. ** Read a single entry from the %_segdir table. The entry from absolute
  161008. ** level :1 with index value :2. */
  161009. /* 32 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  161010. "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
  161011. /* SQL_CHOMP_SEGDIR
  161012. ** Update the start_block (:1) and root (:2) fields of the %_segdir
  161013. ** entry located on absolute level :3 with index :4. */
  161014. /* 33 */ "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?"
  161015. "WHERE level = ? AND idx = ?",
  161016. /* SQL_SEGMENT_IS_APPENDABLE
  161017. ** Return a single row if the segment with end_block=? is appendable. Or
  161018. ** no rows otherwise. */
  161019. /* 34 */ "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL",
  161020. /* SQL_SELECT_INDEXES
  161021. ** Return the list of valid segment indexes for absolute level ? */
  161022. /* 35 */ "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC",
  161023. /* SQL_SELECT_MXLEVEL
  161024. ** Return the largest relative level in the FTS index or indexes. */
  161025. /* 36 */ "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'",
  161026. /* Return segments in order from oldest to newest.*/
  161027. /* 37 */ "SELECT level, idx, end_block "
  161028. "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ? "
  161029. "ORDER BY level DESC, idx ASC",
  161030. /* Update statements used while promoting segments */
  161031. /* 38 */ "UPDATE OR FAIL %Q.'%q_segdir' SET level=-1,idx=? "
  161032. "WHERE level=? AND idx=?",
  161033. /* 39 */ "UPDATE OR FAIL %Q.'%q_segdir' SET level=? WHERE level=-1"
  161034. };
  161035. int rc = SQLITE_OK;
  161036. sqlite3_stmt *pStmt;
  161037. assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
  161038. assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
  161039. pStmt = p->aStmt[eStmt];
  161040. if( !pStmt ){
  161041. int f = SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_NO_VTAB;
  161042. char *zSql;
  161043. if( eStmt==SQL_CONTENT_INSERT ){
  161044. zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
  161045. }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
  161046. f &= ~SQLITE_PREPARE_NO_VTAB;
  161047. zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
  161048. }else{
  161049. zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
  161050. }
  161051. if( !zSql ){
  161052. rc = SQLITE_NOMEM;
  161053. }else{
  161054. rc = sqlite3_prepare_v3(p->db, zSql, -1, f, &pStmt, NULL);
  161055. sqlite3_free(zSql);
  161056. assert( rc==SQLITE_OK || pStmt==0 );
  161057. p->aStmt[eStmt] = pStmt;
  161058. }
  161059. }
  161060. if( apVal ){
  161061. int i;
  161062. int nParam = sqlite3_bind_parameter_count(pStmt);
  161063. for(i=0; rc==SQLITE_OK && i<nParam; i++){
  161064. rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
  161065. }
  161066. }
  161067. *pp = pStmt;
  161068. return rc;
  161069. }
  161070. static int fts3SelectDocsize(
  161071. Fts3Table *pTab, /* FTS3 table handle */
  161072. sqlite3_int64 iDocid, /* Docid to bind for SQL_SELECT_DOCSIZE */
  161073. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  161074. ){
  161075. sqlite3_stmt *pStmt = 0; /* Statement requested from fts3SqlStmt() */
  161076. int rc; /* Return code */
  161077. rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);
  161078. if( rc==SQLITE_OK ){
  161079. sqlite3_bind_int64(pStmt, 1, iDocid);
  161080. rc = sqlite3_step(pStmt);
  161081. if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
  161082. rc = sqlite3_reset(pStmt);
  161083. if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
  161084. pStmt = 0;
  161085. }else{
  161086. rc = SQLITE_OK;
  161087. }
  161088. }
  161089. *ppStmt = pStmt;
  161090. return rc;
  161091. }
  161092. SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
  161093. Fts3Table *pTab, /* Fts3 table handle */
  161094. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  161095. ){
  161096. sqlite3_stmt *pStmt = 0;
  161097. int rc;
  161098. rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);
  161099. if( rc==SQLITE_OK ){
  161100. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  161101. if( sqlite3_step(pStmt)!=SQLITE_ROW
  161102. || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB
  161103. ){
  161104. rc = sqlite3_reset(pStmt);
  161105. if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
  161106. pStmt = 0;
  161107. }
  161108. }
  161109. *ppStmt = pStmt;
  161110. return rc;
  161111. }
  161112. SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
  161113. Fts3Table *pTab, /* Fts3 table handle */
  161114. sqlite3_int64 iDocid, /* Docid to read size data for */
  161115. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  161116. ){
  161117. return fts3SelectDocsize(pTab, iDocid, ppStmt);
  161118. }
  161119. /*
  161120. ** Similar to fts3SqlStmt(). Except, after binding the parameters in
  161121. ** array apVal[] to the SQL statement identified by eStmt, the statement
  161122. ** is executed.
  161123. **
  161124. ** Returns SQLITE_OK if the statement is successfully executed, or an
  161125. ** SQLite error code otherwise.
  161126. */
  161127. static void fts3SqlExec(
  161128. int *pRC, /* Result code */
  161129. Fts3Table *p, /* The FTS3 table */
  161130. int eStmt, /* Index of statement to evaluate */
  161131. sqlite3_value **apVal /* Parameters to bind */
  161132. ){
  161133. sqlite3_stmt *pStmt;
  161134. int rc;
  161135. if( *pRC ) return;
  161136. rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
  161137. if( rc==SQLITE_OK ){
  161138. sqlite3_step(pStmt);
  161139. rc = sqlite3_reset(pStmt);
  161140. }
  161141. *pRC = rc;
  161142. }
  161143. /*
  161144. ** This function ensures that the caller has obtained an exclusive
  161145. ** shared-cache table-lock on the %_segdir table. This is required before
  161146. ** writing data to the fts3 table. If this lock is not acquired first, then
  161147. ** the caller may end up attempting to take this lock as part of committing
  161148. ** a transaction, causing SQLite to return SQLITE_LOCKED or
  161149. ** LOCKED_SHAREDCACHEto a COMMIT command.
  161150. **
  161151. ** It is best to avoid this because if FTS3 returns any error when
  161152. ** committing a transaction, the whole transaction will be rolled back.
  161153. ** And this is not what users expect when they get SQLITE_LOCKED_SHAREDCACHE.
  161154. ** It can still happen if the user locks the underlying tables directly
  161155. ** instead of accessing them via FTS.
  161156. */
  161157. static int fts3Writelock(Fts3Table *p){
  161158. int rc = SQLITE_OK;
  161159. if( p->nPendingData==0 ){
  161160. sqlite3_stmt *pStmt;
  161161. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0);
  161162. if( rc==SQLITE_OK ){
  161163. sqlite3_bind_null(pStmt, 1);
  161164. sqlite3_step(pStmt);
  161165. rc = sqlite3_reset(pStmt);
  161166. }
  161167. }
  161168. return rc;
  161169. }
  161170. /*
  161171. ** FTS maintains a separate indexes for each language-id (a 32-bit integer).
  161172. ** Within each language id, a separate index is maintained to store the
  161173. ** document terms, and each configured prefix size (configured the FTS
  161174. ** "prefix=" option). And each index consists of multiple levels ("relative
  161175. ** levels").
  161176. **
  161177. ** All three of these values (the language id, the specific index and the
  161178. ** level within the index) are encoded in 64-bit integer values stored
  161179. ** in the %_segdir table on disk. This function is used to convert three
  161180. ** separate component values into the single 64-bit integer value that
  161181. ** can be used to query the %_segdir table.
  161182. **
  161183. ** Specifically, each language-id/index combination is allocated 1024
  161184. ** 64-bit integer level values ("absolute levels"). The main terms index
  161185. ** for language-id 0 is allocate values 0-1023. The first prefix index
  161186. ** (if any) for language-id 0 is allocated values 1024-2047. And so on.
  161187. ** Language 1 indexes are allocated immediately following language 0.
  161188. **
  161189. ** So, for a system with nPrefix prefix indexes configured, the block of
  161190. ** absolute levels that corresponds to language-id iLangid and index
  161191. ** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
  161192. */
  161193. static sqlite3_int64 getAbsoluteLevel(
  161194. Fts3Table *p, /* FTS3 table handle */
  161195. int iLangid, /* Language id */
  161196. int iIndex, /* Index in p->aIndex[] */
  161197. int iLevel /* Level of segments */
  161198. ){
  161199. sqlite3_int64 iBase; /* First absolute level for iLangid/iIndex */
  161200. assert_fts3_nc( iLangid>=0 );
  161201. assert( p->nIndex>0 );
  161202. assert( iIndex>=0 && iIndex<p->nIndex );
  161203. iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
  161204. return iBase + iLevel;
  161205. }
  161206. /*
  161207. ** Set *ppStmt to a statement handle that may be used to iterate through
  161208. ** all rows in the %_segdir table, from oldest to newest. If successful,
  161209. ** return SQLITE_OK. If an error occurs while preparing the statement,
  161210. ** return an SQLite error code.
  161211. **
  161212. ** There is only ever one instance of this SQL statement compiled for
  161213. ** each FTS3 table.
  161214. **
  161215. ** The statement returns the following columns from the %_segdir table:
  161216. **
  161217. ** 0: idx
  161218. ** 1: start_block
  161219. ** 2: leaves_end_block
  161220. ** 3: end_block
  161221. ** 4: root
  161222. */
  161223. SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
  161224. Fts3Table *p, /* FTS3 table */
  161225. int iLangid, /* Language being queried */
  161226. int iIndex, /* Index for p->aIndex[] */
  161227. int iLevel, /* Level to select (relative level) */
  161228. sqlite3_stmt **ppStmt /* OUT: Compiled statement */
  161229. ){
  161230. int rc;
  161231. sqlite3_stmt *pStmt = 0;
  161232. assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
  161233. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  161234. assert( iIndex>=0 && iIndex<p->nIndex );
  161235. if( iLevel<0 ){
  161236. /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
  161237. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
  161238. if( rc==SQLITE_OK ){
  161239. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  161240. sqlite3_bind_int64(pStmt, 2,
  161241. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  161242. );
  161243. }
  161244. }else{
  161245. /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
  161246. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
  161247. if( rc==SQLITE_OK ){
  161248. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
  161249. }
  161250. }
  161251. *ppStmt = pStmt;
  161252. return rc;
  161253. }
  161254. /*
  161255. ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
  161256. ** if successful, or an SQLite error code otherwise.
  161257. **
  161258. ** This function also serves to allocate the PendingList structure itself.
  161259. ** For example, to create a new PendingList structure containing two
  161260. ** varints:
  161261. **
  161262. ** PendingList *p = 0;
  161263. ** fts3PendingListAppendVarint(&p, 1);
  161264. ** fts3PendingListAppendVarint(&p, 2);
  161265. */
  161266. static int fts3PendingListAppendVarint(
  161267. PendingList **pp, /* IN/OUT: Pointer to PendingList struct */
  161268. sqlite3_int64 i /* Value to append to data */
  161269. ){
  161270. PendingList *p = *pp;
  161271. /* Allocate or grow the PendingList as required. */
  161272. if( !p ){
  161273. p = sqlite3_malloc(sizeof(*p) + 100);
  161274. if( !p ){
  161275. return SQLITE_NOMEM;
  161276. }
  161277. p->nSpace = 100;
  161278. p->aData = (char *)&p[1];
  161279. p->nData = 0;
  161280. }
  161281. else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
  161282. int nNew = p->nSpace * 2;
  161283. p = sqlite3_realloc(p, sizeof(*p) + nNew);
  161284. if( !p ){
  161285. sqlite3_free(*pp);
  161286. *pp = 0;
  161287. return SQLITE_NOMEM;
  161288. }
  161289. p->nSpace = nNew;
  161290. p->aData = (char *)&p[1];
  161291. }
  161292. /* Append the new serialized varint to the end of the list. */
  161293. p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
  161294. p->aData[p->nData] = '\0';
  161295. *pp = p;
  161296. return SQLITE_OK;
  161297. }
  161298. /*
  161299. ** Add a docid/column/position entry to a PendingList structure. Non-zero
  161300. ** is returned if the structure is sqlite3_realloced as part of adding
  161301. ** the entry. Otherwise, zero.
  161302. **
  161303. ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
  161304. ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
  161305. ** it is set to SQLITE_OK.
  161306. */
  161307. static int fts3PendingListAppend(
  161308. PendingList **pp, /* IN/OUT: PendingList structure */
  161309. sqlite3_int64 iDocid, /* Docid for entry to add */
  161310. sqlite3_int64 iCol, /* Column for entry to add */
  161311. sqlite3_int64 iPos, /* Position of term for entry to add */
  161312. int *pRc /* OUT: Return code */
  161313. ){
  161314. PendingList *p = *pp;
  161315. int rc = SQLITE_OK;
  161316. assert( !p || p->iLastDocid<=iDocid );
  161317. if( !p || p->iLastDocid!=iDocid ){
  161318. sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
  161319. if( p ){
  161320. assert( p->nData<p->nSpace );
  161321. assert( p->aData[p->nData]==0 );
  161322. p->nData++;
  161323. }
  161324. if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
  161325. goto pendinglistappend_out;
  161326. }
  161327. p->iLastCol = -1;
  161328. p->iLastPos = 0;
  161329. p->iLastDocid = iDocid;
  161330. }
  161331. if( iCol>0 && p->iLastCol!=iCol ){
  161332. if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
  161333. || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
  161334. ){
  161335. goto pendinglistappend_out;
  161336. }
  161337. p->iLastCol = iCol;
  161338. p->iLastPos = 0;
  161339. }
  161340. if( iCol>=0 ){
  161341. assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
  161342. rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
  161343. if( rc==SQLITE_OK ){
  161344. p->iLastPos = iPos;
  161345. }
  161346. }
  161347. pendinglistappend_out:
  161348. *pRc = rc;
  161349. if( p!=*pp ){
  161350. *pp = p;
  161351. return 1;
  161352. }
  161353. return 0;
  161354. }
  161355. /*
  161356. ** Free a PendingList object allocated by fts3PendingListAppend().
  161357. */
  161358. static void fts3PendingListDelete(PendingList *pList){
  161359. sqlite3_free(pList);
  161360. }
  161361. /*
  161362. ** Add an entry to one of the pending-terms hash tables.
  161363. */
  161364. static int fts3PendingTermsAddOne(
  161365. Fts3Table *p,
  161366. int iCol,
  161367. int iPos,
  161368. Fts3Hash *pHash, /* Pending terms hash table to add entry to */
  161369. const char *zToken,
  161370. int nToken
  161371. ){
  161372. PendingList *pList;
  161373. int rc = SQLITE_OK;
  161374. pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
  161375. if( pList ){
  161376. p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
  161377. }
  161378. if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
  161379. if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
  161380. /* Malloc failed while inserting the new entry. This can only
  161381. ** happen if there was no previous entry for this token.
  161382. */
  161383. assert( 0==fts3HashFind(pHash, zToken, nToken) );
  161384. sqlite3_free(pList);
  161385. rc = SQLITE_NOMEM;
  161386. }
  161387. }
  161388. if( rc==SQLITE_OK ){
  161389. p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
  161390. }
  161391. return rc;
  161392. }
  161393. /*
  161394. ** Tokenize the nul-terminated string zText and add all tokens to the
  161395. ** pending-terms hash-table. The docid used is that currently stored in
  161396. ** p->iPrevDocid, and the column is specified by argument iCol.
  161397. **
  161398. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
  161399. */
  161400. static int fts3PendingTermsAdd(
  161401. Fts3Table *p, /* Table into which text will be inserted */
  161402. int iLangid, /* Language id to use */
  161403. const char *zText, /* Text of document to be inserted */
  161404. int iCol, /* Column into which text is being inserted */
  161405. u32 *pnWord /* IN/OUT: Incr. by number tokens inserted */
  161406. ){
  161407. int rc;
  161408. int iStart = 0;
  161409. int iEnd = 0;
  161410. int iPos = 0;
  161411. int nWord = 0;
  161412. char const *zToken;
  161413. int nToken = 0;
  161414. sqlite3_tokenizer *pTokenizer = p->pTokenizer;
  161415. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  161416. sqlite3_tokenizer_cursor *pCsr;
  161417. int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
  161418. const char**,int*,int*,int*,int*);
  161419. assert( pTokenizer && pModule );
  161420. /* If the user has inserted a NULL value, this function may be called with
  161421. ** zText==0. In this case, add zero token entries to the hash table and
  161422. ** return early. */
  161423. if( zText==0 ){
  161424. *pnWord = 0;
  161425. return SQLITE_OK;
  161426. }
  161427. rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
  161428. if( rc!=SQLITE_OK ){
  161429. return rc;
  161430. }
  161431. xNext = pModule->xNext;
  161432. while( SQLITE_OK==rc
  161433. && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
  161434. ){
  161435. int i;
  161436. if( iPos>=nWord ) nWord = iPos+1;
  161437. /* Positions cannot be negative; we use -1 as a terminator internally.
  161438. ** Tokens must have a non-zero length.
  161439. */
  161440. if( iPos<0 || !zToken || nToken<=0 ){
  161441. rc = SQLITE_ERROR;
  161442. break;
  161443. }
  161444. /* Add the term to the terms index */
  161445. rc = fts3PendingTermsAddOne(
  161446. p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
  161447. );
  161448. /* Add the term to each of the prefix indexes that it is not too
  161449. ** short for. */
  161450. for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
  161451. struct Fts3Index *pIndex = &p->aIndex[i];
  161452. if( nToken<pIndex->nPrefix ) continue;
  161453. rc = fts3PendingTermsAddOne(
  161454. p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
  161455. );
  161456. }
  161457. }
  161458. pModule->xClose(pCsr);
  161459. *pnWord += nWord;
  161460. return (rc==SQLITE_DONE ? SQLITE_OK : rc);
  161461. }
  161462. /*
  161463. ** Calling this function indicates that subsequent calls to
  161464. ** fts3PendingTermsAdd() are to add term/position-list pairs for the
  161465. ** contents of the document with docid iDocid.
  161466. */
  161467. static int fts3PendingTermsDocid(
  161468. Fts3Table *p, /* Full-text table handle */
  161469. int bDelete, /* True if this op is a delete */
  161470. int iLangid, /* Language id of row being written */
  161471. sqlite_int64 iDocid /* Docid of row being written */
  161472. ){
  161473. assert( iLangid>=0 );
  161474. assert( bDelete==1 || bDelete==0 );
  161475. /* TODO(shess) Explore whether partially flushing the buffer on
  161476. ** forced-flush would provide better performance. I suspect that if
  161477. ** we ordered the doclists by size and flushed the largest until the
  161478. ** buffer was half empty, that would let the less frequent terms
  161479. ** generate longer doclists.
  161480. */
  161481. if( iDocid<p->iPrevDocid
  161482. || (iDocid==p->iPrevDocid && p->bPrevDelete==0)
  161483. || p->iPrevLangid!=iLangid
  161484. || p->nPendingData>p->nMaxPendingData
  161485. ){
  161486. int rc = sqlite3Fts3PendingTermsFlush(p);
  161487. if( rc!=SQLITE_OK ) return rc;
  161488. }
  161489. p->iPrevDocid = iDocid;
  161490. p->iPrevLangid = iLangid;
  161491. p->bPrevDelete = bDelete;
  161492. return SQLITE_OK;
  161493. }
  161494. /*
  161495. ** Discard the contents of the pending-terms hash tables.
  161496. */
  161497. SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
  161498. int i;
  161499. for(i=0; i<p->nIndex; i++){
  161500. Fts3HashElem *pElem;
  161501. Fts3Hash *pHash = &p->aIndex[i].hPending;
  161502. for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
  161503. PendingList *pList = (PendingList *)fts3HashData(pElem);
  161504. fts3PendingListDelete(pList);
  161505. }
  161506. fts3HashClear(pHash);
  161507. }
  161508. p->nPendingData = 0;
  161509. }
  161510. /*
  161511. ** This function is called by the xUpdate() method as part of an INSERT
  161512. ** operation. It adds entries for each term in the new record to the
  161513. ** pendingTerms hash table.
  161514. **
  161515. ** Argument apVal is the same as the similarly named argument passed to
  161516. ** fts3InsertData(). Parameter iDocid is the docid of the new row.
  161517. */
  161518. static int fts3InsertTerms(
  161519. Fts3Table *p,
  161520. int iLangid,
  161521. sqlite3_value **apVal,
  161522. u32 *aSz
  161523. ){
  161524. int i; /* Iterator variable */
  161525. for(i=2; i<p->nColumn+2; i++){
  161526. int iCol = i-2;
  161527. if( p->abNotindexed[iCol]==0 ){
  161528. const char *zText = (const char *)sqlite3_value_text(apVal[i]);
  161529. int rc = fts3PendingTermsAdd(p, iLangid, zText, iCol, &aSz[iCol]);
  161530. if( rc!=SQLITE_OK ){
  161531. return rc;
  161532. }
  161533. aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
  161534. }
  161535. }
  161536. return SQLITE_OK;
  161537. }
  161538. /*
  161539. ** This function is called by the xUpdate() method for an INSERT operation.
  161540. ** The apVal parameter is passed a copy of the apVal argument passed by
  161541. ** SQLite to the xUpdate() method. i.e:
  161542. **
  161543. ** apVal[0] Not used for INSERT.
  161544. ** apVal[1] rowid
  161545. ** apVal[2] Left-most user-defined column
  161546. ** ...
  161547. ** apVal[p->nColumn+1] Right-most user-defined column
  161548. ** apVal[p->nColumn+2] Hidden column with same name as table
  161549. ** apVal[p->nColumn+3] Hidden "docid" column (alias for rowid)
  161550. ** apVal[p->nColumn+4] Hidden languageid column
  161551. */
  161552. static int fts3InsertData(
  161553. Fts3Table *p, /* Full-text table */
  161554. sqlite3_value **apVal, /* Array of values to insert */
  161555. sqlite3_int64 *piDocid /* OUT: Docid for row just inserted */
  161556. ){
  161557. int rc; /* Return code */
  161558. sqlite3_stmt *pContentInsert; /* INSERT INTO %_content VALUES(...) */
  161559. if( p->zContentTbl ){
  161560. sqlite3_value *pRowid = apVal[p->nColumn+3];
  161561. if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
  161562. pRowid = apVal[1];
  161563. }
  161564. if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
  161565. return SQLITE_CONSTRAINT;
  161566. }
  161567. *piDocid = sqlite3_value_int64(pRowid);
  161568. return SQLITE_OK;
  161569. }
  161570. /* Locate the statement handle used to insert data into the %_content
  161571. ** table. The SQL for this statement is:
  161572. **
  161573. ** INSERT INTO %_content VALUES(?, ?, ?, ...)
  161574. **
  161575. ** The statement features N '?' variables, where N is the number of user
  161576. ** defined columns in the FTS3 table, plus one for the docid field.
  161577. */
  161578. rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
  161579. if( rc==SQLITE_OK && p->zLanguageid ){
  161580. rc = sqlite3_bind_int(
  161581. pContentInsert, p->nColumn+2,
  161582. sqlite3_value_int(apVal[p->nColumn+4])
  161583. );
  161584. }
  161585. if( rc!=SQLITE_OK ) return rc;
  161586. /* There is a quirk here. The users INSERT statement may have specified
  161587. ** a value for the "rowid" field, for the "docid" field, or for both.
  161588. ** Which is a problem, since "rowid" and "docid" are aliases for the
  161589. ** same value. For example:
  161590. **
  161591. ** INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
  161592. **
  161593. ** In FTS3, this is an error. It is an error to specify non-NULL values
  161594. ** for both docid and some other rowid alias.
  161595. */
  161596. if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
  161597. if( SQLITE_NULL==sqlite3_value_type(apVal[0])
  161598. && SQLITE_NULL!=sqlite3_value_type(apVal[1])
  161599. ){
  161600. /* A rowid/docid conflict. */
  161601. return SQLITE_ERROR;
  161602. }
  161603. rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
  161604. if( rc!=SQLITE_OK ) return rc;
  161605. }
  161606. /* Execute the statement to insert the record. Set *piDocid to the
  161607. ** new docid value.
  161608. */
  161609. sqlite3_step(pContentInsert);
  161610. rc = sqlite3_reset(pContentInsert);
  161611. *piDocid = sqlite3_last_insert_rowid(p->db);
  161612. return rc;
  161613. }
  161614. /*
  161615. ** Remove all data from the FTS3 table. Clear the hash table containing
  161616. ** pending terms.
  161617. */
  161618. static int fts3DeleteAll(Fts3Table *p, int bContent){
  161619. int rc = SQLITE_OK; /* Return code */
  161620. /* Discard the contents of the pending-terms hash table. */
  161621. sqlite3Fts3PendingTermsClear(p);
  161622. /* Delete everything from the shadow tables. Except, leave %_content as
  161623. ** is if bContent is false. */
  161624. assert( p->zContentTbl==0 || bContent==0 );
  161625. if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
  161626. fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
  161627. fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
  161628. if( p->bHasDocsize ){
  161629. fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
  161630. }
  161631. if( p->bHasStat ){
  161632. fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
  161633. }
  161634. return rc;
  161635. }
  161636. /*
  161637. **
  161638. */
  161639. static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
  161640. int iLangid = 0;
  161641. if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
  161642. return iLangid;
  161643. }
  161644. /*
  161645. ** The first element in the apVal[] array is assumed to contain the docid
  161646. ** (an integer) of a row about to be deleted. Remove all terms from the
  161647. ** full-text index.
  161648. */
  161649. static void fts3DeleteTerms(
  161650. int *pRC, /* Result code */
  161651. Fts3Table *p, /* The FTS table to delete from */
  161652. sqlite3_value *pRowid, /* The docid to be deleted */
  161653. u32 *aSz, /* Sizes of deleted document written here */
  161654. int *pbFound /* OUT: Set to true if row really does exist */
  161655. ){
  161656. int rc;
  161657. sqlite3_stmt *pSelect;
  161658. assert( *pbFound==0 );
  161659. if( *pRC ) return;
  161660. rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
  161661. if( rc==SQLITE_OK ){
  161662. if( SQLITE_ROW==sqlite3_step(pSelect) ){
  161663. int i;
  161664. int iLangid = langidFromSelect(p, pSelect);
  161665. i64 iDocid = sqlite3_column_int64(pSelect, 0);
  161666. rc = fts3PendingTermsDocid(p, 1, iLangid, iDocid);
  161667. for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
  161668. int iCol = i-1;
  161669. if( p->abNotindexed[iCol]==0 ){
  161670. const char *zText = (const char *)sqlite3_column_text(pSelect, i);
  161671. rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[iCol]);
  161672. aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
  161673. }
  161674. }
  161675. if( rc!=SQLITE_OK ){
  161676. sqlite3_reset(pSelect);
  161677. *pRC = rc;
  161678. return;
  161679. }
  161680. *pbFound = 1;
  161681. }
  161682. rc = sqlite3_reset(pSelect);
  161683. }else{
  161684. sqlite3_reset(pSelect);
  161685. }
  161686. *pRC = rc;
  161687. }
  161688. /*
  161689. ** Forward declaration to account for the circular dependency between
  161690. ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
  161691. */
  161692. static int fts3SegmentMerge(Fts3Table *, int, int, int);
  161693. /*
  161694. ** This function allocates a new level iLevel index in the segdir table.
  161695. ** Usually, indexes are allocated within a level sequentially starting
  161696. ** with 0, so the allocated index is one greater than the value returned
  161697. ** by:
  161698. **
  161699. ** SELECT max(idx) FROM %_segdir WHERE level = :iLevel
  161700. **
  161701. ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
  161702. ** level, they are merged into a single level (iLevel+1) segment and the
  161703. ** allocated index is 0.
  161704. **
  161705. ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
  161706. ** returned. Otherwise, an SQLite error code is returned.
  161707. */
  161708. static int fts3AllocateSegdirIdx(
  161709. Fts3Table *p,
  161710. int iLangid, /* Language id */
  161711. int iIndex, /* Index for p->aIndex */
  161712. int iLevel,
  161713. int *piIdx
  161714. ){
  161715. int rc; /* Return Code */
  161716. sqlite3_stmt *pNextIdx; /* Query for next idx at level iLevel */
  161717. int iNext = 0; /* Result of query pNextIdx */
  161718. assert( iLangid>=0 );
  161719. assert( p->nIndex>=1 );
  161720. /* Set variable iNext to the next available segdir index at level iLevel. */
  161721. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
  161722. if( rc==SQLITE_OK ){
  161723. sqlite3_bind_int64(
  161724. pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
  161725. );
  161726. if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
  161727. iNext = sqlite3_column_int(pNextIdx, 0);
  161728. }
  161729. rc = sqlite3_reset(pNextIdx);
  161730. }
  161731. if( rc==SQLITE_OK ){
  161732. /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
  161733. ** full, merge all segments in level iLevel into a single iLevel+1
  161734. ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
  161735. ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
  161736. */
  161737. if( iNext>=FTS3_MERGE_COUNT ){
  161738. fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));
  161739. rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
  161740. *piIdx = 0;
  161741. }else{
  161742. *piIdx = iNext;
  161743. }
  161744. }
  161745. return rc;
  161746. }
  161747. /*
  161748. ** The %_segments table is declared as follows:
  161749. **
  161750. ** CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
  161751. **
  161752. ** This function reads data from a single row of the %_segments table. The
  161753. ** specific row is identified by the iBlockid parameter. If paBlob is not
  161754. ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
  161755. ** with the contents of the blob stored in the "block" column of the
  161756. ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
  161757. ** to the size of the blob in bytes before returning.
  161758. **
  161759. ** If an error occurs, or the table does not contain the specified row,
  161760. ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
  161761. ** paBlob is non-NULL, then it is the responsibility of the caller to
  161762. ** eventually free the returned buffer.
  161763. **
  161764. ** This function may leave an open sqlite3_blob* handle in the
  161765. ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
  161766. ** to this function. The handle may be closed by calling the
  161767. ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
  161768. ** performance improvement, but the blob handle should always be closed
  161769. ** before control is returned to the user (to prevent a lock being held
  161770. ** on the database file for longer than necessary). Thus, any virtual table
  161771. ** method (xFilter etc.) that may directly or indirectly call this function
  161772. ** must call sqlite3Fts3SegmentsClose() before returning.
  161773. */
  161774. SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
  161775. Fts3Table *p, /* FTS3 table handle */
  161776. sqlite3_int64 iBlockid, /* Access the row with blockid=$iBlockid */
  161777. char **paBlob, /* OUT: Blob data in malloc'd buffer */
  161778. int *pnBlob, /* OUT: Size of blob data */
  161779. int *pnLoad /* OUT: Bytes actually loaded */
  161780. ){
  161781. int rc; /* Return code */
  161782. /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
  161783. assert( pnBlob );
  161784. if( p->pSegments ){
  161785. rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
  161786. }else{
  161787. if( 0==p->zSegmentsTbl ){
  161788. p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
  161789. if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
  161790. }
  161791. rc = sqlite3_blob_open(
  161792. p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
  161793. );
  161794. }
  161795. if( rc==SQLITE_OK ){
  161796. int nByte = sqlite3_blob_bytes(p->pSegments);
  161797. *pnBlob = nByte;
  161798. if( paBlob ){
  161799. char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
  161800. if( !aByte ){
  161801. rc = SQLITE_NOMEM;
  161802. }else{
  161803. if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
  161804. nByte = FTS3_NODE_CHUNKSIZE;
  161805. *pnLoad = nByte;
  161806. }
  161807. rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
  161808. memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
  161809. if( rc!=SQLITE_OK ){
  161810. sqlite3_free(aByte);
  161811. aByte = 0;
  161812. }
  161813. }
  161814. *paBlob = aByte;
  161815. }
  161816. }
  161817. return rc;
  161818. }
  161819. /*
  161820. ** Close the blob handle at p->pSegments, if it is open. See comments above
  161821. ** the sqlite3Fts3ReadBlock() function for details.
  161822. */
  161823. SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
  161824. sqlite3_blob_close(p->pSegments);
  161825. p->pSegments = 0;
  161826. }
  161827. static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
  161828. int nRead; /* Number of bytes to read */
  161829. int rc; /* Return code */
  161830. nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
  161831. rc = sqlite3_blob_read(
  161832. pReader->pBlob,
  161833. &pReader->aNode[pReader->nPopulate],
  161834. nRead,
  161835. pReader->nPopulate
  161836. );
  161837. if( rc==SQLITE_OK ){
  161838. pReader->nPopulate += nRead;
  161839. memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
  161840. if( pReader->nPopulate==pReader->nNode ){
  161841. sqlite3_blob_close(pReader->pBlob);
  161842. pReader->pBlob = 0;
  161843. pReader->nPopulate = 0;
  161844. }
  161845. }
  161846. return rc;
  161847. }
  161848. static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
  161849. int rc = SQLITE_OK;
  161850. assert( !pReader->pBlob
  161851. || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
  161852. );
  161853. while( pReader->pBlob && rc==SQLITE_OK
  161854. && (pFrom - pReader->aNode + nByte)>pReader->nPopulate
  161855. ){
  161856. rc = fts3SegReaderIncrRead(pReader);
  161857. }
  161858. return rc;
  161859. }
  161860. /*
  161861. ** Set an Fts3SegReader cursor to point at EOF.
  161862. */
  161863. static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
  161864. if( !fts3SegReaderIsRootOnly(pSeg) ){
  161865. sqlite3_free(pSeg->aNode);
  161866. sqlite3_blob_close(pSeg->pBlob);
  161867. pSeg->pBlob = 0;
  161868. }
  161869. pSeg->aNode = 0;
  161870. }
  161871. /*
  161872. ** Move the iterator passed as the first argument to the next term in the
  161873. ** segment. If successful, SQLITE_OK is returned. If there is no next term,
  161874. ** SQLITE_DONE. Otherwise, an SQLite error code.
  161875. */
  161876. static int fts3SegReaderNext(
  161877. Fts3Table *p,
  161878. Fts3SegReader *pReader,
  161879. int bIncr
  161880. ){
  161881. int rc; /* Return code of various sub-routines */
  161882. char *pNext; /* Cursor variable */
  161883. int nPrefix; /* Number of bytes in term prefix */
  161884. int nSuffix; /* Number of bytes in term suffix */
  161885. if( !pReader->aDoclist ){
  161886. pNext = pReader->aNode;
  161887. }else{
  161888. pNext = &pReader->aDoclist[pReader->nDoclist];
  161889. }
  161890. if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
  161891. if( fts3SegReaderIsPending(pReader) ){
  161892. Fts3HashElem *pElem = *(pReader->ppNextElem);
  161893. sqlite3_free(pReader->aNode);
  161894. pReader->aNode = 0;
  161895. if( pElem ){
  161896. char *aCopy;
  161897. PendingList *pList = (PendingList *)fts3HashData(pElem);
  161898. int nCopy = pList->nData+1;
  161899. pReader->zTerm = (char *)fts3HashKey(pElem);
  161900. pReader->nTerm = fts3HashKeysize(pElem);
  161901. aCopy = (char*)sqlite3_malloc(nCopy);
  161902. if( !aCopy ) return SQLITE_NOMEM;
  161903. memcpy(aCopy, pList->aData, nCopy);
  161904. pReader->nNode = pReader->nDoclist = nCopy;
  161905. pReader->aNode = pReader->aDoclist = aCopy;
  161906. pReader->ppNextElem++;
  161907. assert( pReader->aNode );
  161908. }
  161909. return SQLITE_OK;
  161910. }
  161911. fts3SegReaderSetEof(pReader);
  161912. /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
  161913. ** blocks have already been traversed. */
  161914. #ifdef CORRUPT_DB
  161915. assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock || CORRUPT_DB );
  161916. #endif
  161917. if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
  161918. return SQLITE_OK;
  161919. }
  161920. rc = sqlite3Fts3ReadBlock(
  161921. p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode,
  161922. (bIncr ? &pReader->nPopulate : 0)
  161923. );
  161924. if( rc!=SQLITE_OK ) return rc;
  161925. assert( pReader->pBlob==0 );
  161926. if( bIncr && pReader->nPopulate<pReader->nNode ){
  161927. pReader->pBlob = p->pSegments;
  161928. p->pSegments = 0;
  161929. }
  161930. pNext = pReader->aNode;
  161931. }
  161932. assert( !fts3SegReaderIsPending(pReader) );
  161933. rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
  161934. if( rc!=SQLITE_OK ) return rc;
  161935. /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
  161936. ** safe (no risk of overread) even if the node data is corrupted. */
  161937. pNext += fts3GetVarint32(pNext, &nPrefix);
  161938. pNext += fts3GetVarint32(pNext, &nSuffix);
  161939. if( nSuffix<=0
  161940. || (&pReader->aNode[pReader->nNode] - pNext)<nSuffix
  161941. || nPrefix>pReader->nTermAlloc
  161942. ){
  161943. return FTS_CORRUPT_VTAB;
  161944. }
  161945. /* Both nPrefix and nSuffix were read by fts3GetVarint32() and so are
  161946. ** between 0 and 0x7FFFFFFF. But the sum of the two may cause integer
  161947. ** overflow - hence the (i64) casts. */
  161948. if( (i64)nPrefix+nSuffix>(i64)pReader->nTermAlloc ){
  161949. i64 nNew = ((i64)nPrefix+nSuffix)*2;
  161950. char *zNew = sqlite3_realloc64(pReader->zTerm, nNew);
  161951. if( !zNew ){
  161952. return SQLITE_NOMEM;
  161953. }
  161954. pReader->zTerm = zNew;
  161955. pReader->nTermAlloc = nNew;
  161956. }
  161957. rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
  161958. if( rc!=SQLITE_OK ) return rc;
  161959. memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
  161960. pReader->nTerm = nPrefix+nSuffix;
  161961. pNext += nSuffix;
  161962. pNext += fts3GetVarint32(pNext, &pReader->nDoclist);
  161963. pReader->aDoclist = pNext;
  161964. pReader->pOffsetList = 0;
  161965. /* Check that the doclist does not appear to extend past the end of the
  161966. ** b-tree node. And that the final byte of the doclist is 0x00. If either
  161967. ** of these statements is untrue, then the data structure is corrupt.
  161968. */
  161969. if( pReader->nDoclist > pReader->nNode-(pReader->aDoclist-pReader->aNode)
  161970. || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
  161971. ){
  161972. return FTS_CORRUPT_VTAB;
  161973. }
  161974. return SQLITE_OK;
  161975. }
  161976. /*
  161977. ** Set the SegReader to point to the first docid in the doclist associated
  161978. ** with the current term.
  161979. */
  161980. static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
  161981. int rc = SQLITE_OK;
  161982. assert( pReader->aDoclist );
  161983. assert( !pReader->pOffsetList );
  161984. if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
  161985. u8 bEof = 0;
  161986. pReader->iDocid = 0;
  161987. pReader->nOffsetList = 0;
  161988. sqlite3Fts3DoclistPrev(0,
  161989. pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList,
  161990. &pReader->iDocid, &pReader->nOffsetList, &bEof
  161991. );
  161992. }else{
  161993. rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
  161994. if( rc==SQLITE_OK ){
  161995. int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
  161996. pReader->pOffsetList = &pReader->aDoclist[n];
  161997. }
  161998. }
  161999. return rc;
  162000. }
  162001. /*
  162002. ** Advance the SegReader to point to the next docid in the doclist
  162003. ** associated with the current term.
  162004. **
  162005. ** If arguments ppOffsetList and pnOffsetList are not NULL, then
  162006. ** *ppOffsetList is set to point to the first column-offset list
  162007. ** in the doclist entry (i.e. immediately past the docid varint).
  162008. ** *pnOffsetList is set to the length of the set of column-offset
  162009. ** lists, not including the nul-terminator byte. For example:
  162010. */
  162011. static int fts3SegReaderNextDocid(
  162012. Fts3Table *pTab,
  162013. Fts3SegReader *pReader, /* Reader to advance to next docid */
  162014. char **ppOffsetList, /* OUT: Pointer to current position-list */
  162015. int *pnOffsetList /* OUT: Length of *ppOffsetList in bytes */
  162016. ){
  162017. int rc = SQLITE_OK;
  162018. char *p = pReader->pOffsetList;
  162019. char c = 0;
  162020. assert( p );
  162021. if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
  162022. /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
  162023. ** Pending-terms doclists are always built up in ascending order, so
  162024. ** we have to iterate through them backwards here. */
  162025. u8 bEof = 0;
  162026. if( ppOffsetList ){
  162027. *ppOffsetList = pReader->pOffsetList;
  162028. *pnOffsetList = pReader->nOffsetList - 1;
  162029. }
  162030. sqlite3Fts3DoclistPrev(0,
  162031. pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
  162032. &pReader->nOffsetList, &bEof
  162033. );
  162034. if( bEof ){
  162035. pReader->pOffsetList = 0;
  162036. }else{
  162037. pReader->pOffsetList = p;
  162038. }
  162039. }else{
  162040. char *pEnd = &pReader->aDoclist[pReader->nDoclist];
  162041. /* Pointer p currently points at the first byte of an offset list. The
  162042. ** following block advances it to point one byte past the end of
  162043. ** the same offset list. */
  162044. while( 1 ){
  162045. /* The following line of code (and the "p++" below the while() loop) is
  162046. ** normally all that is required to move pointer p to the desired
  162047. ** position. The exception is if this node is being loaded from disk
  162048. ** incrementally and pointer "p" now points to the first byte past
  162049. ** the populated part of pReader->aNode[].
  162050. */
  162051. while( *p | c ) c = *p++ & 0x80;
  162052. assert( *p==0 );
  162053. if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
  162054. rc = fts3SegReaderIncrRead(pReader);
  162055. if( rc!=SQLITE_OK ) return rc;
  162056. }
  162057. p++;
  162058. /* If required, populate the output variables with a pointer to and the
  162059. ** size of the previous offset-list.
  162060. */
  162061. if( ppOffsetList ){
  162062. *ppOffsetList = pReader->pOffsetList;
  162063. *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
  162064. }
  162065. /* List may have been edited in place by fts3EvalNearTrim() */
  162066. while( p<pEnd && *p==0 ) p++;
  162067. /* If there are no more entries in the doclist, set pOffsetList to
  162068. ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
  162069. ** Fts3SegReader.pOffsetList to point to the next offset list before
  162070. ** returning.
  162071. */
  162072. if( p>=pEnd ){
  162073. pReader->pOffsetList = 0;
  162074. }else{
  162075. rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
  162076. if( rc==SQLITE_OK ){
  162077. sqlite3_int64 iDelta;
  162078. pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
  162079. if( pTab->bDescIdx ){
  162080. pReader->iDocid -= iDelta;
  162081. }else{
  162082. pReader->iDocid += iDelta;
  162083. }
  162084. }
  162085. }
  162086. }
  162087. return SQLITE_OK;
  162088. }
  162089. SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
  162090. Fts3Cursor *pCsr,
  162091. Fts3MultiSegReader *pMsr,
  162092. int *pnOvfl
  162093. ){
  162094. Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
  162095. int nOvfl = 0;
  162096. int ii;
  162097. int rc = SQLITE_OK;
  162098. int pgsz = p->nPgsz;
  162099. assert( p->bFts4 );
  162100. assert( pgsz>0 );
  162101. for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
  162102. Fts3SegReader *pReader = pMsr->apSegment[ii];
  162103. if( !fts3SegReaderIsPending(pReader)
  162104. && !fts3SegReaderIsRootOnly(pReader)
  162105. ){
  162106. sqlite3_int64 jj;
  162107. for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
  162108. int nBlob;
  162109. rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
  162110. if( rc!=SQLITE_OK ) break;
  162111. if( (nBlob+35)>pgsz ){
  162112. nOvfl += (nBlob + 34)/pgsz;
  162113. }
  162114. }
  162115. }
  162116. }
  162117. *pnOvfl = nOvfl;
  162118. return rc;
  162119. }
  162120. /*
  162121. ** Free all allocations associated with the iterator passed as the
  162122. ** second argument.
  162123. */
  162124. SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
  162125. if( pReader ){
  162126. if( !fts3SegReaderIsPending(pReader) ){
  162127. sqlite3_free(pReader->zTerm);
  162128. }
  162129. if( !fts3SegReaderIsRootOnly(pReader) ){
  162130. sqlite3_free(pReader->aNode);
  162131. }
  162132. sqlite3_blob_close(pReader->pBlob);
  162133. }
  162134. sqlite3_free(pReader);
  162135. }
  162136. /*
  162137. ** Allocate a new SegReader object.
  162138. */
  162139. SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
  162140. int iAge, /* Segment "age". */
  162141. int bLookup, /* True for a lookup only */
  162142. sqlite3_int64 iStartLeaf, /* First leaf to traverse */
  162143. sqlite3_int64 iEndLeaf, /* Final leaf to traverse */
  162144. sqlite3_int64 iEndBlock, /* Final block of segment */
  162145. const char *zRoot, /* Buffer containing root node */
  162146. int nRoot, /* Size of buffer containing root node */
  162147. Fts3SegReader **ppReader /* OUT: Allocated Fts3SegReader */
  162148. ){
  162149. Fts3SegReader *pReader; /* Newly allocated SegReader object */
  162150. int nExtra = 0; /* Bytes to allocate segment root node */
  162151. assert( zRoot!=0 || nRoot==0 );
  162152. #ifdef CORRUPT_DB
  162153. assert( zRoot!=0 || CORRUPT_DB );
  162154. #endif
  162155. if( iStartLeaf==0 ){
  162156. if( iEndLeaf!=0 ) return FTS_CORRUPT_VTAB;
  162157. nExtra = nRoot + FTS3_NODE_PADDING;
  162158. }
  162159. pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
  162160. if( !pReader ){
  162161. return SQLITE_NOMEM;
  162162. }
  162163. memset(pReader, 0, sizeof(Fts3SegReader));
  162164. pReader->iIdx = iAge;
  162165. pReader->bLookup = bLookup!=0;
  162166. pReader->iStartBlock = iStartLeaf;
  162167. pReader->iLeafEndBlock = iEndLeaf;
  162168. pReader->iEndBlock = iEndBlock;
  162169. if( nExtra ){
  162170. /* The entire segment is stored in the root node. */
  162171. pReader->aNode = (char *)&pReader[1];
  162172. pReader->rootOnly = 1;
  162173. pReader->nNode = nRoot;
  162174. if( nRoot ) memcpy(pReader->aNode, zRoot, nRoot);
  162175. memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
  162176. }else{
  162177. pReader->iCurrentBlock = iStartLeaf-1;
  162178. }
  162179. *ppReader = pReader;
  162180. return SQLITE_OK;
  162181. }
  162182. /*
  162183. ** This is a comparison function used as a qsort() callback when sorting
  162184. ** an array of pending terms by term. This occurs as part of flushing
  162185. ** the contents of the pending-terms hash table to the database.
  162186. */
  162187. static int SQLITE_CDECL fts3CompareElemByTerm(
  162188. const void *lhs,
  162189. const void *rhs
  162190. ){
  162191. char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
  162192. char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
  162193. int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
  162194. int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
  162195. int n = (n1<n2 ? n1 : n2);
  162196. int c = memcmp(z1, z2, n);
  162197. if( c==0 ){
  162198. c = n1 - n2;
  162199. }
  162200. return c;
  162201. }
  162202. /*
  162203. ** This function is used to allocate an Fts3SegReader that iterates through
  162204. ** a subset of the terms stored in the Fts3Table.pendingTerms array.
  162205. **
  162206. ** If the isPrefixIter parameter is zero, then the returned SegReader iterates
  162207. ** through each term in the pending-terms table. Or, if isPrefixIter is
  162208. ** non-zero, it iterates through each term and its prefixes. For example, if
  162209. ** the pending terms hash table contains the terms "sqlite", "mysql" and
  162210. ** "firebird", then the iterator visits the following 'terms' (in the order
  162211. ** shown):
  162212. **
  162213. ** f fi fir fire fireb firebi firebir firebird
  162214. ** m my mys mysq mysql
  162215. ** s sq sql sqli sqlit sqlite
  162216. **
  162217. ** Whereas if isPrefixIter is zero, the terms visited are:
  162218. **
  162219. ** firebird mysql sqlite
  162220. */
  162221. SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
  162222. Fts3Table *p, /* Virtual table handle */
  162223. int iIndex, /* Index for p->aIndex */
  162224. const char *zTerm, /* Term to search for */
  162225. int nTerm, /* Size of buffer zTerm */
  162226. int bPrefix, /* True for a prefix iterator */
  162227. Fts3SegReader **ppReader /* OUT: SegReader for pending-terms */
  162228. ){
  162229. Fts3SegReader *pReader = 0; /* Fts3SegReader object to return */
  162230. Fts3HashElem *pE; /* Iterator variable */
  162231. Fts3HashElem **aElem = 0; /* Array of term hash entries to scan */
  162232. int nElem = 0; /* Size of array at aElem */
  162233. int rc = SQLITE_OK; /* Return Code */
  162234. Fts3Hash *pHash;
  162235. pHash = &p->aIndex[iIndex].hPending;
  162236. if( bPrefix ){
  162237. int nAlloc = 0; /* Size of allocated array at aElem */
  162238. for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
  162239. char *zKey = (char *)fts3HashKey(pE);
  162240. int nKey = fts3HashKeysize(pE);
  162241. if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
  162242. if( nElem==nAlloc ){
  162243. Fts3HashElem **aElem2;
  162244. nAlloc += 16;
  162245. aElem2 = (Fts3HashElem **)sqlite3_realloc(
  162246. aElem, nAlloc*sizeof(Fts3HashElem *)
  162247. );
  162248. if( !aElem2 ){
  162249. rc = SQLITE_NOMEM;
  162250. nElem = 0;
  162251. break;
  162252. }
  162253. aElem = aElem2;
  162254. }
  162255. aElem[nElem++] = pE;
  162256. }
  162257. }
  162258. /* If more than one term matches the prefix, sort the Fts3HashElem
  162259. ** objects in term order using qsort(). This uses the same comparison
  162260. ** callback as is used when flushing terms to disk.
  162261. */
  162262. if( nElem>1 ){
  162263. qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
  162264. }
  162265. }else{
  162266. /* The query is a simple term lookup that matches at most one term in
  162267. ** the index. All that is required is a straight hash-lookup.
  162268. **
  162269. ** Because the stack address of pE may be accessed via the aElem pointer
  162270. ** below, the "Fts3HashElem *pE" must be declared so that it is valid
  162271. ** within this entire function, not just this "else{...}" block.
  162272. */
  162273. pE = fts3HashFindElem(pHash, zTerm, nTerm);
  162274. if( pE ){
  162275. aElem = &pE;
  162276. nElem = 1;
  162277. }
  162278. }
  162279. if( nElem>0 ){
  162280. sqlite3_int64 nByte;
  162281. nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
  162282. pReader = (Fts3SegReader *)sqlite3_malloc64(nByte);
  162283. if( !pReader ){
  162284. rc = SQLITE_NOMEM;
  162285. }else{
  162286. memset(pReader, 0, nByte);
  162287. pReader->iIdx = 0x7FFFFFFF;
  162288. pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
  162289. memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
  162290. }
  162291. }
  162292. if( bPrefix ){
  162293. sqlite3_free(aElem);
  162294. }
  162295. *ppReader = pReader;
  162296. return rc;
  162297. }
  162298. /*
  162299. ** Compare the entries pointed to by two Fts3SegReader structures.
  162300. ** Comparison is as follows:
  162301. **
  162302. ** 1) EOF is greater than not EOF.
  162303. **
  162304. ** 2) The current terms (if any) are compared using memcmp(). If one
  162305. ** term is a prefix of another, the longer term is considered the
  162306. ** larger.
  162307. **
  162308. ** 3) By segment age. An older segment is considered larger.
  162309. */
  162310. static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  162311. int rc;
  162312. if( pLhs->aNode && pRhs->aNode ){
  162313. int rc2 = pLhs->nTerm - pRhs->nTerm;
  162314. if( rc2<0 ){
  162315. rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
  162316. }else{
  162317. rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
  162318. }
  162319. if( rc==0 ){
  162320. rc = rc2;
  162321. }
  162322. }else{
  162323. rc = (pLhs->aNode==0) - (pRhs->aNode==0);
  162324. }
  162325. if( rc==0 ){
  162326. rc = pRhs->iIdx - pLhs->iIdx;
  162327. }
  162328. assert( rc!=0 );
  162329. return rc;
  162330. }
  162331. /*
  162332. ** A different comparison function for SegReader structures. In this
  162333. ** version, it is assumed that each SegReader points to an entry in
  162334. ** a doclist for identical terms. Comparison is made as follows:
  162335. **
  162336. ** 1) EOF (end of doclist in this case) is greater than not EOF.
  162337. **
  162338. ** 2) By current docid.
  162339. **
  162340. ** 3) By segment age. An older segment is considered larger.
  162341. */
  162342. static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  162343. int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
  162344. if( rc==0 ){
  162345. if( pLhs->iDocid==pRhs->iDocid ){
  162346. rc = pRhs->iIdx - pLhs->iIdx;
  162347. }else{
  162348. rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
  162349. }
  162350. }
  162351. assert( pLhs->aNode && pRhs->aNode );
  162352. return rc;
  162353. }
  162354. static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  162355. int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
  162356. if( rc==0 ){
  162357. if( pLhs->iDocid==pRhs->iDocid ){
  162358. rc = pRhs->iIdx - pLhs->iIdx;
  162359. }else{
  162360. rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
  162361. }
  162362. }
  162363. assert( pLhs->aNode && pRhs->aNode );
  162364. return rc;
  162365. }
  162366. /*
  162367. ** Compare the term that the Fts3SegReader object passed as the first argument
  162368. ** points to with the term specified by arguments zTerm and nTerm.
  162369. **
  162370. ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
  162371. ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
  162372. ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
  162373. */
  162374. static int fts3SegReaderTermCmp(
  162375. Fts3SegReader *pSeg, /* Segment reader object */
  162376. const char *zTerm, /* Term to compare to */
  162377. int nTerm /* Size of term zTerm in bytes */
  162378. ){
  162379. int res = 0;
  162380. if( pSeg->aNode ){
  162381. if( pSeg->nTerm>nTerm ){
  162382. res = memcmp(pSeg->zTerm, zTerm, nTerm);
  162383. }else{
  162384. res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
  162385. }
  162386. if( res==0 ){
  162387. res = pSeg->nTerm-nTerm;
  162388. }
  162389. }
  162390. return res;
  162391. }
  162392. /*
  162393. ** Argument apSegment is an array of nSegment elements. It is known that
  162394. ** the final (nSegment-nSuspect) members are already in sorted order
  162395. ** (according to the comparison function provided). This function shuffles
  162396. ** the array around until all entries are in sorted order.
  162397. */
  162398. static void fts3SegReaderSort(
  162399. Fts3SegReader **apSegment, /* Array to sort entries of */
  162400. int nSegment, /* Size of apSegment array */
  162401. int nSuspect, /* Unsorted entry count */
  162402. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) /* Comparison function */
  162403. ){
  162404. int i; /* Iterator variable */
  162405. assert( nSuspect<=nSegment );
  162406. if( nSuspect==nSegment ) nSuspect--;
  162407. for(i=nSuspect-1; i>=0; i--){
  162408. int j;
  162409. for(j=i; j<(nSegment-1); j++){
  162410. Fts3SegReader *pTmp;
  162411. if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
  162412. pTmp = apSegment[j+1];
  162413. apSegment[j+1] = apSegment[j];
  162414. apSegment[j] = pTmp;
  162415. }
  162416. }
  162417. #ifndef NDEBUG
  162418. /* Check that the list really is sorted now. */
  162419. for(i=0; i<(nSuspect-1); i++){
  162420. assert( xCmp(apSegment[i], apSegment[i+1])<0 );
  162421. }
  162422. #endif
  162423. }
  162424. /*
  162425. ** Insert a record into the %_segments table.
  162426. */
  162427. static int fts3WriteSegment(
  162428. Fts3Table *p, /* Virtual table handle */
  162429. sqlite3_int64 iBlock, /* Block id for new block */
  162430. char *z, /* Pointer to buffer containing block data */
  162431. int n /* Size of buffer z in bytes */
  162432. ){
  162433. sqlite3_stmt *pStmt;
  162434. int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
  162435. if( rc==SQLITE_OK ){
  162436. sqlite3_bind_int64(pStmt, 1, iBlock);
  162437. sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
  162438. sqlite3_step(pStmt);
  162439. rc = sqlite3_reset(pStmt);
  162440. sqlite3_bind_null(pStmt, 2);
  162441. }
  162442. return rc;
  162443. }
  162444. /*
  162445. ** Find the largest relative level number in the table. If successful, set
  162446. ** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,
  162447. ** set *pnMax to zero and return an SQLite error code.
  162448. */
  162449. SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){
  162450. int rc;
  162451. int mxLevel = 0;
  162452. sqlite3_stmt *pStmt = 0;
  162453. rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);
  162454. if( rc==SQLITE_OK ){
  162455. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  162456. mxLevel = sqlite3_column_int(pStmt, 0);
  162457. }
  162458. rc = sqlite3_reset(pStmt);
  162459. }
  162460. *pnMax = mxLevel;
  162461. return rc;
  162462. }
  162463. /*
  162464. ** Insert a record into the %_segdir table.
  162465. */
  162466. static int fts3WriteSegdir(
  162467. Fts3Table *p, /* Virtual table handle */
  162468. sqlite3_int64 iLevel, /* Value for "level" field (absolute level) */
  162469. int iIdx, /* Value for "idx" field */
  162470. sqlite3_int64 iStartBlock, /* Value for "start_block" field */
  162471. sqlite3_int64 iLeafEndBlock, /* Value for "leaves_end_block" field */
  162472. sqlite3_int64 iEndBlock, /* Value for "end_block" field */
  162473. sqlite3_int64 nLeafData, /* Bytes of leaf data in segment */
  162474. char *zRoot, /* Blob value for "root" field */
  162475. int nRoot /* Number of bytes in buffer zRoot */
  162476. ){
  162477. sqlite3_stmt *pStmt;
  162478. int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
  162479. if( rc==SQLITE_OK ){
  162480. sqlite3_bind_int64(pStmt, 1, iLevel);
  162481. sqlite3_bind_int(pStmt, 2, iIdx);
  162482. sqlite3_bind_int64(pStmt, 3, iStartBlock);
  162483. sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
  162484. if( nLeafData==0 ){
  162485. sqlite3_bind_int64(pStmt, 5, iEndBlock);
  162486. }else{
  162487. char *zEnd = sqlite3_mprintf("%lld %lld", iEndBlock, nLeafData);
  162488. if( !zEnd ) return SQLITE_NOMEM;
  162489. sqlite3_bind_text(pStmt, 5, zEnd, -1, sqlite3_free);
  162490. }
  162491. sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
  162492. sqlite3_step(pStmt);
  162493. rc = sqlite3_reset(pStmt);
  162494. sqlite3_bind_null(pStmt, 6);
  162495. }
  162496. return rc;
  162497. }
  162498. /*
  162499. ** Return the size of the common prefix (if any) shared by zPrev and
  162500. ** zNext, in bytes. For example,
  162501. **
  162502. ** fts3PrefixCompress("abc", 3, "abcdef", 6) // returns 3
  162503. ** fts3PrefixCompress("abX", 3, "abcdef", 6) // returns 2
  162504. ** fts3PrefixCompress("abX", 3, "Xbcdef", 6) // returns 0
  162505. */
  162506. static int fts3PrefixCompress(
  162507. const char *zPrev, /* Buffer containing previous term */
  162508. int nPrev, /* Size of buffer zPrev in bytes */
  162509. const char *zNext, /* Buffer containing next term */
  162510. int nNext /* Size of buffer zNext in bytes */
  162511. ){
  162512. int n;
  162513. UNUSED_PARAMETER(nNext);
  162514. for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
  162515. return n;
  162516. }
  162517. /*
  162518. ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
  162519. ** (according to memcmp) than the previous term.
  162520. */
  162521. static int fts3NodeAddTerm(
  162522. Fts3Table *p, /* Virtual table handle */
  162523. SegmentNode **ppTree, /* IN/OUT: SegmentNode handle */
  162524. int isCopyTerm, /* True if zTerm/nTerm is transient */
  162525. const char *zTerm, /* Pointer to buffer containing term */
  162526. int nTerm /* Size of term in bytes */
  162527. ){
  162528. SegmentNode *pTree = *ppTree;
  162529. int rc;
  162530. SegmentNode *pNew;
  162531. /* First try to append the term to the current node. Return early if
  162532. ** this is possible.
  162533. */
  162534. if( pTree ){
  162535. int nData = pTree->nData; /* Current size of node in bytes */
  162536. int nReq = nData; /* Required space after adding zTerm */
  162537. int nPrefix; /* Number of bytes of prefix compression */
  162538. int nSuffix; /* Suffix length */
  162539. nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
  162540. nSuffix = nTerm-nPrefix;
  162541. nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
  162542. if( nReq<=p->nNodeSize || !pTree->zTerm ){
  162543. if( nReq>p->nNodeSize ){
  162544. /* An unusual case: this is the first term to be added to the node
  162545. ** and the static node buffer (p->nNodeSize bytes) is not large
  162546. ** enough. Use a separately malloced buffer instead This wastes
  162547. ** p->nNodeSize bytes, but since this scenario only comes about when
  162548. ** the database contain two terms that share a prefix of almost 2KB,
  162549. ** this is not expected to be a serious problem.
  162550. */
  162551. assert( pTree->aData==(char *)&pTree[1] );
  162552. pTree->aData = (char *)sqlite3_malloc(nReq);
  162553. if( !pTree->aData ){
  162554. return SQLITE_NOMEM;
  162555. }
  162556. }
  162557. if( pTree->zTerm ){
  162558. /* There is no prefix-length field for first term in a node */
  162559. nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
  162560. }
  162561. nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
  162562. memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
  162563. pTree->nData = nData + nSuffix;
  162564. pTree->nEntry++;
  162565. if( isCopyTerm ){
  162566. if( pTree->nMalloc<nTerm ){
  162567. char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
  162568. if( !zNew ){
  162569. return SQLITE_NOMEM;
  162570. }
  162571. pTree->nMalloc = nTerm*2;
  162572. pTree->zMalloc = zNew;
  162573. }
  162574. pTree->zTerm = pTree->zMalloc;
  162575. memcpy(pTree->zTerm, zTerm, nTerm);
  162576. pTree->nTerm = nTerm;
  162577. }else{
  162578. pTree->zTerm = (char *)zTerm;
  162579. pTree->nTerm = nTerm;
  162580. }
  162581. return SQLITE_OK;
  162582. }
  162583. }
  162584. /* If control flows to here, it was not possible to append zTerm to the
  162585. ** current node. Create a new node (a right-sibling of the current node).
  162586. ** If this is the first node in the tree, the term is added to it.
  162587. **
  162588. ** Otherwise, the term is not added to the new node, it is left empty for
  162589. ** now. Instead, the term is inserted into the parent of pTree. If pTree
  162590. ** has no parent, one is created here.
  162591. */
  162592. pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
  162593. if( !pNew ){
  162594. return SQLITE_NOMEM;
  162595. }
  162596. memset(pNew, 0, sizeof(SegmentNode));
  162597. pNew->nData = 1 + FTS3_VARINT_MAX;
  162598. pNew->aData = (char *)&pNew[1];
  162599. if( pTree ){
  162600. SegmentNode *pParent = pTree->pParent;
  162601. rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
  162602. if( pTree->pParent==0 ){
  162603. pTree->pParent = pParent;
  162604. }
  162605. pTree->pRight = pNew;
  162606. pNew->pLeftmost = pTree->pLeftmost;
  162607. pNew->pParent = pParent;
  162608. pNew->zMalloc = pTree->zMalloc;
  162609. pNew->nMalloc = pTree->nMalloc;
  162610. pTree->zMalloc = 0;
  162611. }else{
  162612. pNew->pLeftmost = pNew;
  162613. rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
  162614. }
  162615. *ppTree = pNew;
  162616. return rc;
  162617. }
  162618. /*
  162619. ** Helper function for fts3NodeWrite().
  162620. */
  162621. static int fts3TreeFinishNode(
  162622. SegmentNode *pTree,
  162623. int iHeight,
  162624. sqlite3_int64 iLeftChild
  162625. ){
  162626. int nStart;
  162627. assert( iHeight>=1 && iHeight<128 );
  162628. nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
  162629. pTree->aData[nStart] = (char)iHeight;
  162630. sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
  162631. return nStart;
  162632. }
  162633. /*
  162634. ** Write the buffer for the segment node pTree and all of its peers to the
  162635. ** database. Then call this function recursively to write the parent of
  162636. ** pTree and its peers to the database.
  162637. **
  162638. ** Except, if pTree is a root node, do not write it to the database. Instead,
  162639. ** set output variables *paRoot and *pnRoot to contain the root node.
  162640. **
  162641. ** If successful, SQLITE_OK is returned and output variable *piLast is
  162642. ** set to the largest blockid written to the database (or zero if no
  162643. ** blocks were written to the db). Otherwise, an SQLite error code is
  162644. ** returned.
  162645. */
  162646. static int fts3NodeWrite(
  162647. Fts3Table *p, /* Virtual table handle */
  162648. SegmentNode *pTree, /* SegmentNode handle */
  162649. int iHeight, /* Height of this node in tree */
  162650. sqlite3_int64 iLeaf, /* Block id of first leaf node */
  162651. sqlite3_int64 iFree, /* Block id of next free slot in %_segments */
  162652. sqlite3_int64 *piLast, /* OUT: Block id of last entry written */
  162653. char **paRoot, /* OUT: Data for root node */
  162654. int *pnRoot /* OUT: Size of root node in bytes */
  162655. ){
  162656. int rc = SQLITE_OK;
  162657. if( !pTree->pParent ){
  162658. /* Root node of the tree. */
  162659. int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
  162660. *piLast = iFree-1;
  162661. *pnRoot = pTree->nData - nStart;
  162662. *paRoot = &pTree->aData[nStart];
  162663. }else{
  162664. SegmentNode *pIter;
  162665. sqlite3_int64 iNextFree = iFree;
  162666. sqlite3_int64 iNextLeaf = iLeaf;
  162667. for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
  162668. int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
  162669. int nWrite = pIter->nData - nStart;
  162670. rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
  162671. iNextFree++;
  162672. iNextLeaf += (pIter->nEntry+1);
  162673. }
  162674. if( rc==SQLITE_OK ){
  162675. assert( iNextLeaf==iFree );
  162676. rc = fts3NodeWrite(
  162677. p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
  162678. );
  162679. }
  162680. }
  162681. return rc;
  162682. }
  162683. /*
  162684. ** Free all memory allocations associated with the tree pTree.
  162685. */
  162686. static void fts3NodeFree(SegmentNode *pTree){
  162687. if( pTree ){
  162688. SegmentNode *p = pTree->pLeftmost;
  162689. fts3NodeFree(p->pParent);
  162690. while( p ){
  162691. SegmentNode *pRight = p->pRight;
  162692. if( p->aData!=(char *)&p[1] ){
  162693. sqlite3_free(p->aData);
  162694. }
  162695. assert( pRight==0 || p->zMalloc==0 );
  162696. sqlite3_free(p->zMalloc);
  162697. sqlite3_free(p);
  162698. p = pRight;
  162699. }
  162700. }
  162701. }
  162702. /*
  162703. ** Add a term to the segment being constructed by the SegmentWriter object
  162704. ** *ppWriter. When adding the first term to a segment, *ppWriter should
  162705. ** be passed NULL. This function will allocate a new SegmentWriter object
  162706. ** and return it via the input/output variable *ppWriter in this case.
  162707. **
  162708. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
  162709. */
  162710. static int fts3SegWriterAdd(
  162711. Fts3Table *p, /* Virtual table handle */
  162712. SegmentWriter **ppWriter, /* IN/OUT: SegmentWriter handle */
  162713. int isCopyTerm, /* True if buffer zTerm must be copied */
  162714. const char *zTerm, /* Pointer to buffer containing term */
  162715. int nTerm, /* Size of term in bytes */
  162716. const char *aDoclist, /* Pointer to buffer containing doclist */
  162717. int nDoclist /* Size of doclist in bytes */
  162718. ){
  162719. int nPrefix; /* Size of term prefix in bytes */
  162720. int nSuffix; /* Size of term suffix in bytes */
  162721. int nReq; /* Number of bytes required on leaf page */
  162722. int nData;
  162723. SegmentWriter *pWriter = *ppWriter;
  162724. if( !pWriter ){
  162725. int rc;
  162726. sqlite3_stmt *pStmt;
  162727. /* Allocate the SegmentWriter structure */
  162728. pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
  162729. if( !pWriter ) return SQLITE_NOMEM;
  162730. memset(pWriter, 0, sizeof(SegmentWriter));
  162731. *ppWriter = pWriter;
  162732. /* Allocate a buffer in which to accumulate data */
  162733. pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
  162734. if( !pWriter->aData ) return SQLITE_NOMEM;
  162735. pWriter->nSize = p->nNodeSize;
  162736. /* Find the next free blockid in the %_segments table */
  162737. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
  162738. if( rc!=SQLITE_OK ) return rc;
  162739. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  162740. pWriter->iFree = sqlite3_column_int64(pStmt, 0);
  162741. pWriter->iFirst = pWriter->iFree;
  162742. }
  162743. rc = sqlite3_reset(pStmt);
  162744. if( rc!=SQLITE_OK ) return rc;
  162745. }
  162746. nData = pWriter->nData;
  162747. nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
  162748. nSuffix = nTerm-nPrefix;
  162749. /* If nSuffix is zero or less, then zTerm/nTerm must be a prefix of
  162750. ** pWriter->zTerm/pWriter->nTerm. i.e. must be equal to or less than when
  162751. ** compared with BINARY collation. This indicates corruption. */
  162752. if( nSuffix<=0 ) return FTS_CORRUPT_VTAB;
  162753. /* Figure out how many bytes are required by this new entry */
  162754. nReq = sqlite3Fts3VarintLen(nPrefix) + /* varint containing prefix size */
  162755. sqlite3Fts3VarintLen(nSuffix) + /* varint containing suffix size */
  162756. nSuffix + /* Term suffix */
  162757. sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
  162758. nDoclist; /* Doclist data */
  162759. if( nData>0 && nData+nReq>p->nNodeSize ){
  162760. int rc;
  162761. /* The current leaf node is full. Write it out to the database. */
  162762. rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
  162763. if( rc!=SQLITE_OK ) return rc;
  162764. p->nLeafAdd++;
  162765. /* Add the current term to the interior node tree. The term added to
  162766. ** the interior tree must:
  162767. **
  162768. ** a) be greater than the largest term on the leaf node just written
  162769. ** to the database (still available in pWriter->zTerm), and
  162770. **
  162771. ** b) be less than or equal to the term about to be added to the new
  162772. ** leaf node (zTerm/nTerm).
  162773. **
  162774. ** In other words, it must be the prefix of zTerm 1 byte longer than
  162775. ** the common prefix (if any) of zTerm and pWriter->zTerm.
  162776. */
  162777. assert( nPrefix<nTerm );
  162778. rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
  162779. if( rc!=SQLITE_OK ) return rc;
  162780. nData = 0;
  162781. pWriter->nTerm = 0;
  162782. nPrefix = 0;
  162783. nSuffix = nTerm;
  162784. nReq = 1 + /* varint containing prefix size */
  162785. sqlite3Fts3VarintLen(nTerm) + /* varint containing suffix size */
  162786. nTerm + /* Term suffix */
  162787. sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
  162788. nDoclist; /* Doclist data */
  162789. }
  162790. /* Increase the total number of bytes written to account for the new entry. */
  162791. pWriter->nLeafData += nReq;
  162792. /* If the buffer currently allocated is too small for this entry, realloc
  162793. ** the buffer to make it large enough.
  162794. */
  162795. if( nReq>pWriter->nSize ){
  162796. char *aNew = sqlite3_realloc(pWriter->aData, nReq);
  162797. if( !aNew ) return SQLITE_NOMEM;
  162798. pWriter->aData = aNew;
  162799. pWriter->nSize = nReq;
  162800. }
  162801. assert( nData+nReq<=pWriter->nSize );
  162802. /* Append the prefix-compressed term and doclist to the buffer. */
  162803. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
  162804. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
  162805. memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
  162806. nData += nSuffix;
  162807. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
  162808. memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
  162809. pWriter->nData = nData + nDoclist;
  162810. /* Save the current term so that it can be used to prefix-compress the next.
  162811. ** If the isCopyTerm parameter is true, then the buffer pointed to by
  162812. ** zTerm is transient, so take a copy of the term data. Otherwise, just
  162813. ** store a copy of the pointer.
  162814. */
  162815. if( isCopyTerm ){
  162816. if( nTerm>pWriter->nMalloc ){
  162817. char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
  162818. if( !zNew ){
  162819. return SQLITE_NOMEM;
  162820. }
  162821. pWriter->nMalloc = nTerm*2;
  162822. pWriter->zMalloc = zNew;
  162823. pWriter->zTerm = zNew;
  162824. }
  162825. assert( pWriter->zTerm==pWriter->zMalloc );
  162826. memcpy(pWriter->zTerm, zTerm, nTerm);
  162827. }else{
  162828. pWriter->zTerm = (char *)zTerm;
  162829. }
  162830. pWriter->nTerm = nTerm;
  162831. return SQLITE_OK;
  162832. }
  162833. /*
  162834. ** Flush all data associated with the SegmentWriter object pWriter to the
  162835. ** database. This function must be called after all terms have been added
  162836. ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
  162837. ** returned. Otherwise, an SQLite error code.
  162838. */
  162839. static int fts3SegWriterFlush(
  162840. Fts3Table *p, /* Virtual table handle */
  162841. SegmentWriter *pWriter, /* SegmentWriter to flush to the db */
  162842. sqlite3_int64 iLevel, /* Value for 'level' column of %_segdir */
  162843. int iIdx /* Value for 'idx' column of %_segdir */
  162844. ){
  162845. int rc; /* Return code */
  162846. if( pWriter->pTree ){
  162847. sqlite3_int64 iLast = 0; /* Largest block id written to database */
  162848. sqlite3_int64 iLastLeaf; /* Largest leaf block id written to db */
  162849. char *zRoot = NULL; /* Pointer to buffer containing root node */
  162850. int nRoot = 0; /* Size of buffer zRoot */
  162851. iLastLeaf = pWriter->iFree;
  162852. rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
  162853. if( rc==SQLITE_OK ){
  162854. rc = fts3NodeWrite(p, pWriter->pTree, 1,
  162855. pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
  162856. }
  162857. if( rc==SQLITE_OK ){
  162858. rc = fts3WriteSegdir(p, iLevel, iIdx,
  162859. pWriter->iFirst, iLastLeaf, iLast, pWriter->nLeafData, zRoot, nRoot);
  162860. }
  162861. }else{
  162862. /* The entire tree fits on the root node. Write it to the segdir table. */
  162863. rc = fts3WriteSegdir(p, iLevel, iIdx,
  162864. 0, 0, 0, pWriter->nLeafData, pWriter->aData, pWriter->nData);
  162865. }
  162866. p->nLeafAdd++;
  162867. return rc;
  162868. }
  162869. /*
  162870. ** Release all memory held by the SegmentWriter object passed as the
  162871. ** first argument.
  162872. */
  162873. static void fts3SegWriterFree(SegmentWriter *pWriter){
  162874. if( pWriter ){
  162875. sqlite3_free(pWriter->aData);
  162876. sqlite3_free(pWriter->zMalloc);
  162877. fts3NodeFree(pWriter->pTree);
  162878. sqlite3_free(pWriter);
  162879. }
  162880. }
  162881. /*
  162882. ** The first value in the apVal[] array is assumed to contain an integer.
  162883. ** This function tests if there exist any documents with docid values that
  162884. ** are different from that integer. i.e. if deleting the document with docid
  162885. ** pRowid would mean the FTS3 table were empty.
  162886. **
  162887. ** If successful, *pisEmpty is set to true if the table is empty except for
  162888. ** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
  162889. ** error occurs, an SQLite error code is returned.
  162890. */
  162891. static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
  162892. sqlite3_stmt *pStmt;
  162893. int rc;
  162894. if( p->zContentTbl ){
  162895. /* If using the content=xxx option, assume the table is never empty */
  162896. *pisEmpty = 0;
  162897. rc = SQLITE_OK;
  162898. }else{
  162899. rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
  162900. if( rc==SQLITE_OK ){
  162901. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  162902. *pisEmpty = sqlite3_column_int(pStmt, 0);
  162903. }
  162904. rc = sqlite3_reset(pStmt);
  162905. }
  162906. }
  162907. return rc;
  162908. }
  162909. /*
  162910. ** Set *pnMax to the largest segment level in the database for the index
  162911. ** iIndex.
  162912. **
  162913. ** Segment levels are stored in the 'level' column of the %_segdir table.
  162914. **
  162915. ** Return SQLITE_OK if successful, or an SQLite error code if not.
  162916. */
  162917. static int fts3SegmentMaxLevel(
  162918. Fts3Table *p,
  162919. int iLangid,
  162920. int iIndex,
  162921. sqlite3_int64 *pnMax
  162922. ){
  162923. sqlite3_stmt *pStmt;
  162924. int rc;
  162925. assert( iIndex>=0 && iIndex<p->nIndex );
  162926. /* Set pStmt to the compiled version of:
  162927. **
  162928. ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
  162929. **
  162930. ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
  162931. */
  162932. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
  162933. if( rc!=SQLITE_OK ) return rc;
  162934. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  162935. sqlite3_bind_int64(pStmt, 2,
  162936. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  162937. );
  162938. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  162939. *pnMax = sqlite3_column_int64(pStmt, 0);
  162940. }
  162941. return sqlite3_reset(pStmt);
  162942. }
  162943. /*
  162944. ** iAbsLevel is an absolute level that may be assumed to exist within
  162945. ** the database. This function checks if it is the largest level number
  162946. ** within its index. Assuming no error occurs, *pbMax is set to 1 if
  162947. ** iAbsLevel is indeed the largest level, or 0 otherwise, and SQLITE_OK
  162948. ** is returned. If an error occurs, an error code is returned and the
  162949. ** final value of *pbMax is undefined.
  162950. */
  162951. static int fts3SegmentIsMaxLevel(Fts3Table *p, i64 iAbsLevel, int *pbMax){
  162952. /* Set pStmt to the compiled version of:
  162953. **
  162954. ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
  162955. **
  162956. ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
  162957. */
  162958. sqlite3_stmt *pStmt;
  162959. int rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
  162960. if( rc!=SQLITE_OK ) return rc;
  162961. sqlite3_bind_int64(pStmt, 1, iAbsLevel+1);
  162962. sqlite3_bind_int64(pStmt, 2,
  162963. ((iAbsLevel/FTS3_SEGDIR_MAXLEVEL)+1) * FTS3_SEGDIR_MAXLEVEL
  162964. );
  162965. *pbMax = 0;
  162966. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  162967. *pbMax = sqlite3_column_type(pStmt, 0)==SQLITE_NULL;
  162968. }
  162969. return sqlite3_reset(pStmt);
  162970. }
  162971. /*
  162972. ** Delete all entries in the %_segments table associated with the segment
  162973. ** opened with seg-reader pSeg. This function does not affect the contents
  162974. ** of the %_segdir table.
  162975. */
  162976. static int fts3DeleteSegment(
  162977. Fts3Table *p, /* FTS table handle */
  162978. Fts3SegReader *pSeg /* Segment to delete */
  162979. ){
  162980. int rc = SQLITE_OK; /* Return code */
  162981. if( pSeg->iStartBlock ){
  162982. sqlite3_stmt *pDelete; /* SQL statement to delete rows */
  162983. rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
  162984. if( rc==SQLITE_OK ){
  162985. sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);
  162986. sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);
  162987. sqlite3_step(pDelete);
  162988. rc = sqlite3_reset(pDelete);
  162989. }
  162990. }
  162991. return rc;
  162992. }
  162993. /*
  162994. ** This function is used after merging multiple segments into a single large
  162995. ** segment to delete the old, now redundant, segment b-trees. Specifically,
  162996. ** it:
  162997. **
  162998. ** 1) Deletes all %_segments entries for the segments associated with
  162999. ** each of the SegReader objects in the array passed as the third
  163000. ** argument, and
  163001. **
  163002. ** 2) deletes all %_segdir entries with level iLevel, or all %_segdir
  163003. ** entries regardless of level if (iLevel<0).
  163004. **
  163005. ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
  163006. */
  163007. static int fts3DeleteSegdir(
  163008. Fts3Table *p, /* Virtual table handle */
  163009. int iLangid, /* Language id */
  163010. int iIndex, /* Index for p->aIndex */
  163011. int iLevel, /* Level of %_segdir entries to delete */
  163012. Fts3SegReader **apSegment, /* Array of SegReader objects */
  163013. int nReader /* Size of array apSegment */
  163014. ){
  163015. int rc = SQLITE_OK; /* Return Code */
  163016. int i; /* Iterator variable */
  163017. sqlite3_stmt *pDelete = 0; /* SQL statement to delete rows */
  163018. for(i=0; rc==SQLITE_OK && i<nReader; i++){
  163019. rc = fts3DeleteSegment(p, apSegment[i]);
  163020. }
  163021. if( rc!=SQLITE_OK ){
  163022. return rc;
  163023. }
  163024. assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
  163025. if( iLevel==FTS3_SEGCURSOR_ALL ){
  163026. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
  163027. if( rc==SQLITE_OK ){
  163028. sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  163029. sqlite3_bind_int64(pDelete, 2,
  163030. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  163031. );
  163032. }
  163033. }else{
  163034. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
  163035. if( rc==SQLITE_OK ){
  163036. sqlite3_bind_int64(
  163037. pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
  163038. );
  163039. }
  163040. }
  163041. if( rc==SQLITE_OK ){
  163042. sqlite3_step(pDelete);
  163043. rc = sqlite3_reset(pDelete);
  163044. }
  163045. return rc;
  163046. }
  163047. /*
  163048. ** When this function is called, buffer *ppList (size *pnList bytes) contains
  163049. ** a position list that may (or may not) feature multiple columns. This
  163050. ** function adjusts the pointer *ppList and the length *pnList so that they
  163051. ** identify the subset of the position list that corresponds to column iCol.
  163052. **
  163053. ** If there are no entries in the input position list for column iCol, then
  163054. ** *pnList is set to zero before returning.
  163055. **
  163056. ** If parameter bZero is non-zero, then any part of the input list following
  163057. ** the end of the output list is zeroed before returning.
  163058. */
  163059. static void fts3ColumnFilter(
  163060. int iCol, /* Column to filter on */
  163061. int bZero, /* Zero out anything following *ppList */
  163062. char **ppList, /* IN/OUT: Pointer to position list */
  163063. int *pnList /* IN/OUT: Size of buffer *ppList in bytes */
  163064. ){
  163065. char *pList = *ppList;
  163066. int nList = *pnList;
  163067. char *pEnd = &pList[nList];
  163068. int iCurrent = 0;
  163069. char *p = pList;
  163070. assert( iCol>=0 );
  163071. while( 1 ){
  163072. char c = 0;
  163073. while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
  163074. if( iCol==iCurrent ){
  163075. nList = (int)(p - pList);
  163076. break;
  163077. }
  163078. nList -= (int)(p - pList);
  163079. pList = p;
  163080. if( nList<=0 ){
  163081. break;
  163082. }
  163083. p = &pList[1];
  163084. p += fts3GetVarint32(p, &iCurrent);
  163085. }
  163086. if( bZero && (pEnd - &pList[nList])>0){
  163087. memset(&pList[nList], 0, pEnd - &pList[nList]);
  163088. }
  163089. *ppList = pList;
  163090. *pnList = nList;
  163091. }
  163092. /*
  163093. ** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
  163094. ** existing data). Grow the buffer if required.
  163095. **
  163096. ** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
  163097. ** trying to resize the buffer, return SQLITE_NOMEM.
  163098. */
  163099. static int fts3MsrBufferData(
  163100. Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
  163101. char *pList,
  163102. int nList
  163103. ){
  163104. if( nList>pMsr->nBuffer ){
  163105. char *pNew;
  163106. pMsr->nBuffer = nList*2;
  163107. pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
  163108. if( !pNew ) return SQLITE_NOMEM;
  163109. pMsr->aBuffer = pNew;
  163110. }
  163111. memcpy(pMsr->aBuffer, pList, nList);
  163112. return SQLITE_OK;
  163113. }
  163114. SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
  163115. Fts3Table *p, /* Virtual table handle */
  163116. Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
  163117. sqlite3_int64 *piDocid, /* OUT: Docid value */
  163118. char **paPoslist, /* OUT: Pointer to position list */
  163119. int *pnPoslist /* OUT: Size of position list in bytes */
  163120. ){
  163121. int nMerge = pMsr->nAdvance;
  163122. Fts3SegReader **apSegment = pMsr->apSegment;
  163123. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  163124. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  163125. );
  163126. if( nMerge==0 ){
  163127. *paPoslist = 0;
  163128. return SQLITE_OK;
  163129. }
  163130. while( 1 ){
  163131. Fts3SegReader *pSeg;
  163132. pSeg = pMsr->apSegment[0];
  163133. if( pSeg->pOffsetList==0 ){
  163134. *paPoslist = 0;
  163135. break;
  163136. }else{
  163137. int rc;
  163138. char *pList;
  163139. int nList;
  163140. int j;
  163141. sqlite3_int64 iDocid = apSegment[0]->iDocid;
  163142. rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
  163143. j = 1;
  163144. while( rc==SQLITE_OK
  163145. && j<nMerge
  163146. && apSegment[j]->pOffsetList
  163147. && apSegment[j]->iDocid==iDocid
  163148. ){
  163149. rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
  163150. j++;
  163151. }
  163152. if( rc!=SQLITE_OK ) return rc;
  163153. fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
  163154. if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){
  163155. rc = fts3MsrBufferData(pMsr, pList, nList+1);
  163156. if( rc!=SQLITE_OK ) return rc;
  163157. assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
  163158. pList = pMsr->aBuffer;
  163159. }
  163160. if( pMsr->iColFilter>=0 ){
  163161. fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList);
  163162. }
  163163. if( nList>0 ){
  163164. *paPoslist = pList;
  163165. *piDocid = iDocid;
  163166. *pnPoslist = nList;
  163167. break;
  163168. }
  163169. }
  163170. }
  163171. return SQLITE_OK;
  163172. }
  163173. static int fts3SegReaderStart(
  163174. Fts3Table *p, /* Virtual table handle */
  163175. Fts3MultiSegReader *pCsr, /* Cursor object */
  163176. const char *zTerm, /* Term searched for (or NULL) */
  163177. int nTerm /* Length of zTerm in bytes */
  163178. ){
  163179. int i;
  163180. int nSeg = pCsr->nSegment;
  163181. /* If the Fts3SegFilter defines a specific term (or term prefix) to search
  163182. ** for, then advance each segment iterator until it points to a term of
  163183. ** equal or greater value than the specified term. This prevents many
  163184. ** unnecessary merge/sort operations for the case where single segment
  163185. ** b-tree leaf nodes contain more than one term.
  163186. */
  163187. for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
  163188. int res = 0;
  163189. Fts3SegReader *pSeg = pCsr->apSegment[i];
  163190. do {
  163191. int rc = fts3SegReaderNext(p, pSeg, 0);
  163192. if( rc!=SQLITE_OK ) return rc;
  163193. }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
  163194. if( pSeg->bLookup && res!=0 ){
  163195. fts3SegReaderSetEof(pSeg);
  163196. }
  163197. }
  163198. fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
  163199. return SQLITE_OK;
  163200. }
  163201. SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
  163202. Fts3Table *p, /* Virtual table handle */
  163203. Fts3MultiSegReader *pCsr, /* Cursor object */
  163204. Fts3SegFilter *pFilter /* Restrictions on range of iteration */
  163205. ){
  163206. pCsr->pFilter = pFilter;
  163207. return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
  163208. }
  163209. SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
  163210. Fts3Table *p, /* Virtual table handle */
  163211. Fts3MultiSegReader *pCsr, /* Cursor object */
  163212. int iCol, /* Column to match on. */
  163213. const char *zTerm, /* Term to iterate through a doclist for */
  163214. int nTerm /* Number of bytes in zTerm */
  163215. ){
  163216. int i;
  163217. int rc;
  163218. int nSegment = pCsr->nSegment;
  163219. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  163220. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  163221. );
  163222. assert( pCsr->pFilter==0 );
  163223. assert( zTerm && nTerm>0 );
  163224. /* Advance each segment iterator until it points to the term zTerm/nTerm. */
  163225. rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
  163226. if( rc!=SQLITE_OK ) return rc;
  163227. /* Determine how many of the segments actually point to zTerm/nTerm. */
  163228. for(i=0; i<nSegment; i++){
  163229. Fts3SegReader *pSeg = pCsr->apSegment[i];
  163230. if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
  163231. break;
  163232. }
  163233. }
  163234. pCsr->nAdvance = i;
  163235. /* Advance each of the segments to point to the first docid. */
  163236. for(i=0; i<pCsr->nAdvance; i++){
  163237. rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
  163238. if( rc!=SQLITE_OK ) return rc;
  163239. }
  163240. fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
  163241. assert( iCol<0 || iCol<p->nColumn );
  163242. pCsr->iColFilter = iCol;
  163243. return SQLITE_OK;
  163244. }
  163245. /*
  163246. ** This function is called on a MultiSegReader that has been started using
  163247. ** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
  163248. ** have been made. Calling this function puts the MultiSegReader in such
  163249. ** a state that if the next two calls are:
  163250. **
  163251. ** sqlite3Fts3SegReaderStart()
  163252. ** sqlite3Fts3SegReaderStep()
  163253. **
  163254. ** then the entire doclist for the term is available in
  163255. ** MultiSegReader.aDoclist/nDoclist.
  163256. */
  163257. SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
  163258. int i; /* Used to iterate through segment-readers */
  163259. assert( pCsr->zTerm==0 );
  163260. assert( pCsr->nTerm==0 );
  163261. assert( pCsr->aDoclist==0 );
  163262. assert( pCsr->nDoclist==0 );
  163263. pCsr->nAdvance = 0;
  163264. pCsr->bRestart = 1;
  163265. for(i=0; i<pCsr->nSegment; i++){
  163266. pCsr->apSegment[i]->pOffsetList = 0;
  163267. pCsr->apSegment[i]->nOffsetList = 0;
  163268. pCsr->apSegment[i]->iDocid = 0;
  163269. }
  163270. return SQLITE_OK;
  163271. }
  163272. SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
  163273. Fts3Table *p, /* Virtual table handle */
  163274. Fts3MultiSegReader *pCsr /* Cursor object */
  163275. ){
  163276. int rc = SQLITE_OK;
  163277. int isIgnoreEmpty = (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
  163278. int isRequirePos = (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
  163279. int isColFilter = (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
  163280. int isPrefix = (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
  163281. int isScan = (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
  163282. int isFirst = (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
  163283. Fts3SegReader **apSegment = pCsr->apSegment;
  163284. int nSegment = pCsr->nSegment;
  163285. Fts3SegFilter *pFilter = pCsr->pFilter;
  163286. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  163287. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  163288. );
  163289. if( pCsr->nSegment==0 ) return SQLITE_OK;
  163290. do {
  163291. int nMerge;
  163292. int i;
  163293. /* Advance the first pCsr->nAdvance entries in the apSegment[] array
  163294. ** forward. Then sort the list in order of current term again.
  163295. */
  163296. for(i=0; i<pCsr->nAdvance; i++){
  163297. Fts3SegReader *pSeg = apSegment[i];
  163298. if( pSeg->bLookup ){
  163299. fts3SegReaderSetEof(pSeg);
  163300. }else{
  163301. rc = fts3SegReaderNext(p, pSeg, 0);
  163302. }
  163303. if( rc!=SQLITE_OK ) return rc;
  163304. }
  163305. fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
  163306. pCsr->nAdvance = 0;
  163307. /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
  163308. assert( rc==SQLITE_OK );
  163309. if( apSegment[0]->aNode==0 ) break;
  163310. pCsr->nTerm = apSegment[0]->nTerm;
  163311. pCsr->zTerm = apSegment[0]->zTerm;
  163312. /* If this is a prefix-search, and if the term that apSegment[0] points
  163313. ** to does not share a suffix with pFilter->zTerm/nTerm, then all
  163314. ** required callbacks have been made. In this case exit early.
  163315. **
  163316. ** Similarly, if this is a search for an exact match, and the first term
  163317. ** of segment apSegment[0] is not a match, exit early.
  163318. */
  163319. if( pFilter->zTerm && !isScan ){
  163320. if( pCsr->nTerm<pFilter->nTerm
  163321. || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
  163322. || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
  163323. ){
  163324. break;
  163325. }
  163326. }
  163327. nMerge = 1;
  163328. while( nMerge<nSegment
  163329. && apSegment[nMerge]->aNode
  163330. && apSegment[nMerge]->nTerm==pCsr->nTerm
  163331. && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
  163332. ){
  163333. nMerge++;
  163334. }
  163335. assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
  163336. if( nMerge==1
  163337. && !isIgnoreEmpty
  163338. && !isFirst
  163339. && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
  163340. ){
  163341. pCsr->nDoclist = apSegment[0]->nDoclist;
  163342. if( fts3SegReaderIsPending(apSegment[0]) ){
  163343. rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
  163344. pCsr->aDoclist = pCsr->aBuffer;
  163345. }else{
  163346. pCsr->aDoclist = apSegment[0]->aDoclist;
  163347. }
  163348. if( rc==SQLITE_OK ) rc = SQLITE_ROW;
  163349. }else{
  163350. int nDoclist = 0; /* Size of doclist */
  163351. sqlite3_int64 iPrev = 0; /* Previous docid stored in doclist */
  163352. /* The current term of the first nMerge entries in the array
  163353. ** of Fts3SegReader objects is the same. The doclists must be merged
  163354. ** and a single term returned with the merged doclist.
  163355. */
  163356. for(i=0; i<nMerge; i++){
  163357. fts3SegReaderFirstDocid(p, apSegment[i]);
  163358. }
  163359. fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
  163360. while( apSegment[0]->pOffsetList ){
  163361. int j; /* Number of segments that share a docid */
  163362. char *pList = 0;
  163363. int nList = 0;
  163364. int nByte;
  163365. sqlite3_int64 iDocid = apSegment[0]->iDocid;
  163366. fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
  163367. j = 1;
  163368. while( j<nMerge
  163369. && apSegment[j]->pOffsetList
  163370. && apSegment[j]->iDocid==iDocid
  163371. ){
  163372. fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
  163373. j++;
  163374. }
  163375. if( isColFilter ){
  163376. fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList);
  163377. }
  163378. if( !isIgnoreEmpty || nList>0 ){
  163379. /* Calculate the 'docid' delta value to write into the merged
  163380. ** doclist. */
  163381. sqlite3_int64 iDelta;
  163382. if( p->bDescIdx && nDoclist>0 ){
  163383. iDelta = iPrev - iDocid;
  163384. }else{
  163385. iDelta = iDocid - iPrev;
  163386. }
  163387. if( iDelta<=0 && (nDoclist>0 || iDelta!=iDocid) ){
  163388. return FTS_CORRUPT_VTAB;
  163389. }
  163390. assert( nDoclist>0 || iDelta==iDocid );
  163391. nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
  163392. if( nDoclist+nByte>pCsr->nBuffer ){
  163393. char *aNew;
  163394. pCsr->nBuffer = (nDoclist+nByte)*2;
  163395. aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
  163396. if( !aNew ){
  163397. return SQLITE_NOMEM;
  163398. }
  163399. pCsr->aBuffer = aNew;
  163400. }
  163401. if( isFirst ){
  163402. char *a = &pCsr->aBuffer[nDoclist];
  163403. int nWrite;
  163404. nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
  163405. if( nWrite ){
  163406. iPrev = iDocid;
  163407. nDoclist += nWrite;
  163408. }
  163409. }else{
  163410. nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
  163411. iPrev = iDocid;
  163412. if( isRequirePos ){
  163413. memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
  163414. nDoclist += nList;
  163415. pCsr->aBuffer[nDoclist++] = '\0';
  163416. }
  163417. }
  163418. }
  163419. fts3SegReaderSort(apSegment, nMerge, j, xCmp);
  163420. }
  163421. if( nDoclist>0 ){
  163422. pCsr->aDoclist = pCsr->aBuffer;
  163423. pCsr->nDoclist = nDoclist;
  163424. rc = SQLITE_ROW;
  163425. }
  163426. }
  163427. pCsr->nAdvance = nMerge;
  163428. }while( rc==SQLITE_OK );
  163429. return rc;
  163430. }
  163431. SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
  163432. Fts3MultiSegReader *pCsr /* Cursor object */
  163433. ){
  163434. if( pCsr ){
  163435. int i;
  163436. for(i=0; i<pCsr->nSegment; i++){
  163437. sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
  163438. }
  163439. sqlite3_free(pCsr->apSegment);
  163440. sqlite3_free(pCsr->aBuffer);
  163441. pCsr->nSegment = 0;
  163442. pCsr->apSegment = 0;
  163443. pCsr->aBuffer = 0;
  163444. }
  163445. }
  163446. /*
  163447. ** Decode the "end_block" field, selected by column iCol of the SELECT
  163448. ** statement passed as the first argument.
  163449. **
  163450. ** The "end_block" field may contain either an integer, or a text field
  163451. ** containing the text representation of two non-negative integers separated
  163452. ** by one or more space (0x20) characters. In the first case, set *piEndBlock
  163453. ** to the integer value and *pnByte to zero before returning. In the second,
  163454. ** set *piEndBlock to the first value and *pnByte to the second.
  163455. */
  163456. static void fts3ReadEndBlockField(
  163457. sqlite3_stmt *pStmt,
  163458. int iCol,
  163459. i64 *piEndBlock,
  163460. i64 *pnByte
  163461. ){
  163462. const unsigned char *zText = sqlite3_column_text(pStmt, iCol);
  163463. if( zText ){
  163464. int i;
  163465. int iMul = 1;
  163466. i64 iVal = 0;
  163467. for(i=0; zText[i]>='0' && zText[i]<='9'; i++){
  163468. iVal = iVal*10 + (zText[i] - '0');
  163469. }
  163470. *piEndBlock = iVal;
  163471. while( zText[i]==' ' ) i++;
  163472. iVal = 0;
  163473. if( zText[i]=='-' ){
  163474. i++;
  163475. iMul = -1;
  163476. }
  163477. for(/* no-op */; zText[i]>='0' && zText[i]<='9'; i++){
  163478. iVal = iVal*10 + (zText[i] - '0');
  163479. }
  163480. *pnByte = (iVal * (i64)iMul);
  163481. }
  163482. }
  163483. /*
  163484. ** A segment of size nByte bytes has just been written to absolute level
  163485. ** iAbsLevel. Promote any segments that should be promoted as a result.
  163486. */
  163487. static int fts3PromoteSegments(
  163488. Fts3Table *p, /* FTS table handle */
  163489. sqlite3_int64 iAbsLevel, /* Absolute level just updated */
  163490. sqlite3_int64 nByte /* Size of new segment at iAbsLevel */
  163491. ){
  163492. int rc = SQLITE_OK;
  163493. sqlite3_stmt *pRange;
  163494. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE2, &pRange, 0);
  163495. if( rc==SQLITE_OK ){
  163496. int bOk = 0;
  163497. i64 iLast = (iAbsLevel/FTS3_SEGDIR_MAXLEVEL + 1) * FTS3_SEGDIR_MAXLEVEL - 1;
  163498. i64 nLimit = (nByte*3)/2;
  163499. /* Loop through all entries in the %_segdir table corresponding to
  163500. ** segments in this index on levels greater than iAbsLevel. If there is
  163501. ** at least one such segment, and it is possible to determine that all
  163502. ** such segments are smaller than nLimit bytes in size, they will be
  163503. ** promoted to level iAbsLevel. */
  163504. sqlite3_bind_int64(pRange, 1, iAbsLevel+1);
  163505. sqlite3_bind_int64(pRange, 2, iLast);
  163506. while( SQLITE_ROW==sqlite3_step(pRange) ){
  163507. i64 nSize = 0, dummy;
  163508. fts3ReadEndBlockField(pRange, 2, &dummy, &nSize);
  163509. if( nSize<=0 || nSize>nLimit ){
  163510. /* If nSize==0, then the %_segdir.end_block field does not not
  163511. ** contain a size value. This happens if it was written by an
  163512. ** old version of FTS. In this case it is not possible to determine
  163513. ** the size of the segment, and so segment promotion does not
  163514. ** take place. */
  163515. bOk = 0;
  163516. break;
  163517. }
  163518. bOk = 1;
  163519. }
  163520. rc = sqlite3_reset(pRange);
  163521. if( bOk ){
  163522. int iIdx = 0;
  163523. sqlite3_stmt *pUpdate1 = 0;
  163524. sqlite3_stmt *pUpdate2 = 0;
  163525. if( rc==SQLITE_OK ){
  163526. rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL_IDX, &pUpdate1, 0);
  163527. }
  163528. if( rc==SQLITE_OK ){
  163529. rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL, &pUpdate2, 0);
  163530. }
  163531. if( rc==SQLITE_OK ){
  163532. /* Loop through all %_segdir entries for segments in this index with
  163533. ** levels equal to or greater than iAbsLevel. As each entry is visited,
  163534. ** updated it to set (level = -1) and (idx = N), where N is 0 for the
  163535. ** oldest segment in the range, 1 for the next oldest, and so on.
  163536. **
  163537. ** In other words, move all segments being promoted to level -1,
  163538. ** setting the "idx" fields as appropriate to keep them in the same
  163539. ** order. The contents of level -1 (which is never used, except
  163540. ** transiently here), will be moved back to level iAbsLevel below. */
  163541. sqlite3_bind_int64(pRange, 1, iAbsLevel);
  163542. while( SQLITE_ROW==sqlite3_step(pRange) ){
  163543. sqlite3_bind_int(pUpdate1, 1, iIdx++);
  163544. sqlite3_bind_int(pUpdate1, 2, sqlite3_column_int(pRange, 0));
  163545. sqlite3_bind_int(pUpdate1, 3, sqlite3_column_int(pRange, 1));
  163546. sqlite3_step(pUpdate1);
  163547. rc = sqlite3_reset(pUpdate1);
  163548. if( rc!=SQLITE_OK ){
  163549. sqlite3_reset(pRange);
  163550. break;
  163551. }
  163552. }
  163553. }
  163554. if( rc==SQLITE_OK ){
  163555. rc = sqlite3_reset(pRange);
  163556. }
  163557. /* Move level -1 to level iAbsLevel */
  163558. if( rc==SQLITE_OK ){
  163559. sqlite3_bind_int64(pUpdate2, 1, iAbsLevel);
  163560. sqlite3_step(pUpdate2);
  163561. rc = sqlite3_reset(pUpdate2);
  163562. }
  163563. }
  163564. }
  163565. return rc;
  163566. }
  163567. /*
  163568. ** Merge all level iLevel segments in the database into a single
  163569. ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
  163570. ** single segment with a level equal to the numerically largest level
  163571. ** currently present in the database.
  163572. **
  163573. ** If this function is called with iLevel<0, but there is only one
  163574. ** segment in the database, SQLITE_DONE is returned immediately.
  163575. ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
  163576. ** an SQLite error code is returned.
  163577. */
  163578. static int fts3SegmentMerge(
  163579. Fts3Table *p,
  163580. int iLangid, /* Language id to merge */
  163581. int iIndex, /* Index in p->aIndex[] to merge */
  163582. int iLevel /* Level to merge */
  163583. ){
  163584. int rc; /* Return code */
  163585. int iIdx = 0; /* Index of new segment */
  163586. sqlite3_int64 iNewLevel = 0; /* Level/index to create new segment at */
  163587. SegmentWriter *pWriter = 0; /* Used to write the new, merged, segment */
  163588. Fts3SegFilter filter; /* Segment term filter condition */
  163589. Fts3MultiSegReader csr; /* Cursor to iterate through level(s) */
  163590. int bIgnoreEmpty = 0; /* True to ignore empty segments */
  163591. i64 iMaxLevel = 0; /* Max level number for this index/langid */
  163592. assert( iLevel==FTS3_SEGCURSOR_ALL
  163593. || iLevel==FTS3_SEGCURSOR_PENDING
  163594. || iLevel>=0
  163595. );
  163596. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  163597. assert( iIndex>=0 && iIndex<p->nIndex );
  163598. rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
  163599. if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
  163600. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  163601. rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iMaxLevel);
  163602. if( rc!=SQLITE_OK ) goto finished;
  163603. }
  163604. if( iLevel==FTS3_SEGCURSOR_ALL ){
  163605. /* This call is to merge all segments in the database to a single
  163606. ** segment. The level of the new segment is equal to the numerically
  163607. ** greatest segment level currently present in the database for this
  163608. ** index. The idx of the new segment is always 0. */
  163609. if( csr.nSegment==1 && 0==fts3SegReaderIsPending(csr.apSegment[0]) ){
  163610. rc = SQLITE_DONE;
  163611. goto finished;
  163612. }
  163613. iNewLevel = iMaxLevel;
  163614. bIgnoreEmpty = 1;
  163615. }else{
  163616. /* This call is to merge all segments at level iLevel. find the next
  163617. ** available segment index at level iLevel+1. The call to
  163618. ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
  163619. ** a single iLevel+2 segment if necessary. */
  163620. assert( FTS3_SEGCURSOR_PENDING==-1 );
  163621. iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
  163622. rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
  163623. bIgnoreEmpty = (iLevel!=FTS3_SEGCURSOR_PENDING) && (iNewLevel>iMaxLevel);
  163624. }
  163625. if( rc!=SQLITE_OK ) goto finished;
  163626. assert( csr.nSegment>0 );
  163627. assert_fts3_nc( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
  163628. assert_fts3_nc(
  163629. iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL)
  163630. );
  163631. memset(&filter, 0, sizeof(Fts3SegFilter));
  163632. filter.flags = FTS3_SEGMENT_REQUIRE_POS;
  163633. filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
  163634. rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
  163635. while( SQLITE_OK==rc ){
  163636. rc = sqlite3Fts3SegReaderStep(p, &csr);
  163637. if( rc!=SQLITE_ROW ) break;
  163638. rc = fts3SegWriterAdd(p, &pWriter, 1,
  163639. csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
  163640. }
  163641. if( rc!=SQLITE_OK ) goto finished;
  163642. assert( pWriter || bIgnoreEmpty );
  163643. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  163644. rc = fts3DeleteSegdir(
  163645. p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
  163646. );
  163647. if( rc!=SQLITE_OK ) goto finished;
  163648. }
  163649. if( pWriter ){
  163650. rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
  163651. if( rc==SQLITE_OK ){
  163652. if( iLevel==FTS3_SEGCURSOR_PENDING || iNewLevel<iMaxLevel ){
  163653. rc = fts3PromoteSegments(p, iNewLevel, pWriter->nLeafData);
  163654. }
  163655. }
  163656. }
  163657. finished:
  163658. fts3SegWriterFree(pWriter);
  163659. sqlite3Fts3SegReaderFinish(&csr);
  163660. return rc;
  163661. }
  163662. /*
  163663. ** Flush the contents of pendingTerms to level 0 segments.
  163664. */
  163665. SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
  163666. int rc = SQLITE_OK;
  163667. int i;
  163668. for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
  163669. rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
  163670. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  163671. }
  163672. sqlite3Fts3PendingTermsClear(p);
  163673. /* Determine the auto-incr-merge setting if unknown. If enabled,
  163674. ** estimate the number of leaf blocks of content to be written
  163675. */
  163676. if( rc==SQLITE_OK && p->bHasStat
  163677. && p->nAutoincrmerge==0xff && p->nLeafAdd>0
  163678. ){
  163679. sqlite3_stmt *pStmt = 0;
  163680. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
  163681. if( rc==SQLITE_OK ){
  163682. sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
  163683. rc = sqlite3_step(pStmt);
  163684. if( rc==SQLITE_ROW ){
  163685. p->nAutoincrmerge = sqlite3_column_int(pStmt, 0);
  163686. if( p->nAutoincrmerge==1 ) p->nAutoincrmerge = 8;
  163687. }else if( rc==SQLITE_DONE ){
  163688. p->nAutoincrmerge = 0;
  163689. }
  163690. rc = sqlite3_reset(pStmt);
  163691. }
  163692. }
  163693. return rc;
  163694. }
  163695. /*
  163696. ** Encode N integers as varints into a blob.
  163697. */
  163698. static void fts3EncodeIntArray(
  163699. int N, /* The number of integers to encode */
  163700. u32 *a, /* The integer values */
  163701. char *zBuf, /* Write the BLOB here */
  163702. int *pNBuf /* Write number of bytes if zBuf[] used here */
  163703. ){
  163704. int i, j;
  163705. for(i=j=0; i<N; i++){
  163706. j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
  163707. }
  163708. *pNBuf = j;
  163709. }
  163710. /*
  163711. ** Decode a blob of varints into N integers
  163712. */
  163713. static void fts3DecodeIntArray(
  163714. int N, /* The number of integers to decode */
  163715. u32 *a, /* Write the integer values */
  163716. const char *zBuf, /* The BLOB containing the varints */
  163717. int nBuf /* size of the BLOB */
  163718. ){
  163719. int i = 0;
  163720. if( nBuf && (zBuf[nBuf-1]&0x80)==0 ){
  163721. int j;
  163722. for(i=j=0; i<N && j<nBuf; i++){
  163723. sqlite3_int64 x;
  163724. j += sqlite3Fts3GetVarint(&zBuf[j], &x);
  163725. a[i] = (u32)(x & 0xffffffff);
  163726. }
  163727. }
  163728. while( i<N ) a[i++] = 0;
  163729. }
  163730. /*
  163731. ** Insert the sizes (in tokens) for each column of the document
  163732. ** with docid equal to p->iPrevDocid. The sizes are encoded as
  163733. ** a blob of varints.
  163734. */
  163735. static void fts3InsertDocsize(
  163736. int *pRC, /* Result code */
  163737. Fts3Table *p, /* Table into which to insert */
  163738. u32 *aSz /* Sizes of each column, in tokens */
  163739. ){
  163740. char *pBlob; /* The BLOB encoding of the document size */
  163741. int nBlob; /* Number of bytes in the BLOB */
  163742. sqlite3_stmt *pStmt; /* Statement used to insert the encoding */
  163743. int rc; /* Result code from subfunctions */
  163744. if( *pRC ) return;
  163745. pBlob = sqlite3_malloc64( 10*(sqlite3_int64)p->nColumn );
  163746. if( pBlob==0 ){
  163747. *pRC = SQLITE_NOMEM;
  163748. return;
  163749. }
  163750. fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
  163751. rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
  163752. if( rc ){
  163753. sqlite3_free(pBlob);
  163754. *pRC = rc;
  163755. return;
  163756. }
  163757. sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
  163758. sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
  163759. sqlite3_step(pStmt);
  163760. *pRC = sqlite3_reset(pStmt);
  163761. }
  163762. /*
  163763. ** Record 0 of the %_stat table contains a blob consisting of N varints,
  163764. ** where N is the number of user defined columns in the fts3 table plus
  163765. ** two. If nCol is the number of user defined columns, then values of the
  163766. ** varints are set as follows:
  163767. **
  163768. ** Varint 0: Total number of rows in the table.
  163769. **
  163770. ** Varint 1..nCol: For each column, the total number of tokens stored in
  163771. ** the column for all rows of the table.
  163772. **
  163773. ** Varint 1+nCol: The total size, in bytes, of all text values in all
  163774. ** columns of all rows of the table.
  163775. **
  163776. */
  163777. static void fts3UpdateDocTotals(
  163778. int *pRC, /* The result code */
  163779. Fts3Table *p, /* Table being updated */
  163780. u32 *aSzIns, /* Size increases */
  163781. u32 *aSzDel, /* Size decreases */
  163782. int nChng /* Change in the number of documents */
  163783. ){
  163784. char *pBlob; /* Storage for BLOB written into %_stat */
  163785. int nBlob; /* Size of BLOB written into %_stat */
  163786. u32 *a; /* Array of integers that becomes the BLOB */
  163787. sqlite3_stmt *pStmt; /* Statement for reading and writing */
  163788. int i; /* Loop counter */
  163789. int rc; /* Result code from subfunctions */
  163790. const int nStat = p->nColumn+2;
  163791. if( *pRC ) return;
  163792. a = sqlite3_malloc64( (sizeof(u32)+10)*(sqlite3_int64)nStat );
  163793. if( a==0 ){
  163794. *pRC = SQLITE_NOMEM;
  163795. return;
  163796. }
  163797. pBlob = (char*)&a[nStat];
  163798. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
  163799. if( rc ){
  163800. sqlite3_free(a);
  163801. *pRC = rc;
  163802. return;
  163803. }
  163804. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  163805. if( sqlite3_step(pStmt)==SQLITE_ROW ){
  163806. fts3DecodeIntArray(nStat, a,
  163807. sqlite3_column_blob(pStmt, 0),
  163808. sqlite3_column_bytes(pStmt, 0));
  163809. }else{
  163810. memset(a, 0, sizeof(u32)*(nStat) );
  163811. }
  163812. rc = sqlite3_reset(pStmt);
  163813. if( rc!=SQLITE_OK ){
  163814. sqlite3_free(a);
  163815. *pRC = rc;
  163816. return;
  163817. }
  163818. if( nChng<0 && a[0]<(u32)(-nChng) ){
  163819. a[0] = 0;
  163820. }else{
  163821. a[0] += nChng;
  163822. }
  163823. for(i=0; i<p->nColumn+1; i++){
  163824. u32 x = a[i+1];
  163825. if( x+aSzIns[i] < aSzDel[i] ){
  163826. x = 0;
  163827. }else{
  163828. x = x + aSzIns[i] - aSzDel[i];
  163829. }
  163830. a[i+1] = x;
  163831. }
  163832. fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
  163833. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
  163834. if( rc ){
  163835. sqlite3_free(a);
  163836. *pRC = rc;
  163837. return;
  163838. }
  163839. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  163840. sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);
  163841. sqlite3_step(pStmt);
  163842. *pRC = sqlite3_reset(pStmt);
  163843. sqlite3_bind_null(pStmt, 2);
  163844. sqlite3_free(a);
  163845. }
  163846. /*
  163847. ** Merge the entire database so that there is one segment for each
  163848. ** iIndex/iLangid combination.
  163849. */
  163850. static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
  163851. int bSeenDone = 0;
  163852. int rc;
  163853. sqlite3_stmt *pAllLangid = 0;
  163854. rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
  163855. if( rc==SQLITE_OK ){
  163856. int rc2;
  163857. sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
  163858. sqlite3_bind_int(pAllLangid, 2, p->nIndex);
  163859. while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
  163860. int i;
  163861. int iLangid = sqlite3_column_int(pAllLangid, 0);
  163862. for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
  163863. rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
  163864. if( rc==SQLITE_DONE ){
  163865. bSeenDone = 1;
  163866. rc = SQLITE_OK;
  163867. }
  163868. }
  163869. }
  163870. rc2 = sqlite3_reset(pAllLangid);
  163871. if( rc==SQLITE_OK ) rc = rc2;
  163872. }
  163873. sqlite3Fts3SegmentsClose(p);
  163874. sqlite3Fts3PendingTermsClear(p);
  163875. return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
  163876. }
  163877. /*
  163878. ** This function is called when the user executes the following statement:
  163879. **
  163880. ** INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
  163881. **
  163882. ** The entire FTS index is discarded and rebuilt. If the table is one
  163883. ** created using the content=xxx option, then the new index is based on
  163884. ** the current contents of the xxx table. Otherwise, it is rebuilt based
  163885. ** on the contents of the %_content table.
  163886. */
  163887. static int fts3DoRebuild(Fts3Table *p){
  163888. int rc; /* Return Code */
  163889. rc = fts3DeleteAll(p, 0);
  163890. if( rc==SQLITE_OK ){
  163891. u32 *aSz = 0;
  163892. u32 *aSzIns = 0;
  163893. u32 *aSzDel = 0;
  163894. sqlite3_stmt *pStmt = 0;
  163895. int nEntry = 0;
  163896. /* Compose and prepare an SQL statement to loop through the content table */
  163897. char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
  163898. if( !zSql ){
  163899. rc = SQLITE_NOMEM;
  163900. }else{
  163901. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  163902. sqlite3_free(zSql);
  163903. }
  163904. if( rc==SQLITE_OK ){
  163905. sqlite3_int64 nByte = sizeof(u32) * ((sqlite3_int64)p->nColumn+1)*3;
  163906. aSz = (u32 *)sqlite3_malloc64(nByte);
  163907. if( aSz==0 ){
  163908. rc = SQLITE_NOMEM;
  163909. }else{
  163910. memset(aSz, 0, nByte);
  163911. aSzIns = &aSz[p->nColumn+1];
  163912. aSzDel = &aSzIns[p->nColumn+1];
  163913. }
  163914. }
  163915. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  163916. int iCol;
  163917. int iLangid = langidFromSelect(p, pStmt);
  163918. rc = fts3PendingTermsDocid(p, 0, iLangid, sqlite3_column_int64(pStmt, 0));
  163919. memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1));
  163920. for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
  163921. if( p->abNotindexed[iCol]==0 ){
  163922. const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
  163923. rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
  163924. aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
  163925. }
  163926. }
  163927. if( p->bHasDocsize ){
  163928. fts3InsertDocsize(&rc, p, aSz);
  163929. }
  163930. if( rc!=SQLITE_OK ){
  163931. sqlite3_finalize(pStmt);
  163932. pStmt = 0;
  163933. }else{
  163934. nEntry++;
  163935. for(iCol=0; iCol<=p->nColumn; iCol++){
  163936. aSzIns[iCol] += aSz[iCol];
  163937. }
  163938. }
  163939. }
  163940. if( p->bFts4 ){
  163941. fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
  163942. }
  163943. sqlite3_free(aSz);
  163944. if( pStmt ){
  163945. int rc2 = sqlite3_finalize(pStmt);
  163946. if( rc==SQLITE_OK ){
  163947. rc = rc2;
  163948. }
  163949. }
  163950. }
  163951. return rc;
  163952. }
  163953. /*
  163954. ** This function opens a cursor used to read the input data for an
  163955. ** incremental merge operation. Specifically, it opens a cursor to scan
  163956. ** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute
  163957. ** level iAbsLevel.
  163958. */
  163959. static int fts3IncrmergeCsr(
  163960. Fts3Table *p, /* FTS3 table handle */
  163961. sqlite3_int64 iAbsLevel, /* Absolute level to open */
  163962. int nSeg, /* Number of segments to merge */
  163963. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  163964. ){
  163965. int rc; /* Return Code */
  163966. sqlite3_stmt *pStmt = 0; /* Statement used to read %_segdir entry */
  163967. sqlite3_int64 nByte; /* Bytes allocated at pCsr->apSegment[] */
  163968. /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
  163969. memset(pCsr, 0, sizeof(*pCsr));
  163970. nByte = sizeof(Fts3SegReader *) * nSeg;
  163971. pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc64(nByte);
  163972. if( pCsr->apSegment==0 ){
  163973. rc = SQLITE_NOMEM;
  163974. }else{
  163975. memset(pCsr->apSegment, 0, nByte);
  163976. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
  163977. }
  163978. if( rc==SQLITE_OK ){
  163979. int i;
  163980. int rc2;
  163981. sqlite3_bind_int64(pStmt, 1, iAbsLevel);
  163982. assert( pCsr->nSegment==0 );
  163983. for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){
  163984. rc = sqlite3Fts3SegReaderNew(i, 0,
  163985. sqlite3_column_int64(pStmt, 1), /* segdir.start_block */
  163986. sqlite3_column_int64(pStmt, 2), /* segdir.leaves_end_block */
  163987. sqlite3_column_int64(pStmt, 3), /* segdir.end_block */
  163988. sqlite3_column_blob(pStmt, 4), /* segdir.root */
  163989. sqlite3_column_bytes(pStmt, 4), /* segdir.root */
  163990. &pCsr->apSegment[i]
  163991. );
  163992. pCsr->nSegment++;
  163993. }
  163994. rc2 = sqlite3_reset(pStmt);
  163995. if( rc==SQLITE_OK ) rc = rc2;
  163996. }
  163997. return rc;
  163998. }
  163999. typedef struct IncrmergeWriter IncrmergeWriter;
  164000. typedef struct NodeWriter NodeWriter;
  164001. typedef struct Blob Blob;
  164002. typedef struct NodeReader NodeReader;
  164003. /*
  164004. ** An instance of the following structure is used as a dynamic buffer
  164005. ** to build up nodes or other blobs of data in.
  164006. **
  164007. ** The function blobGrowBuffer() is used to extend the allocation.
  164008. */
  164009. struct Blob {
  164010. char *a; /* Pointer to allocation */
  164011. int n; /* Number of valid bytes of data in a[] */
  164012. int nAlloc; /* Allocated size of a[] (nAlloc>=n) */
  164013. };
  164014. /*
  164015. ** This structure is used to build up buffers containing segment b-tree
  164016. ** nodes (blocks).
  164017. */
  164018. struct NodeWriter {
  164019. sqlite3_int64 iBlock; /* Current block id */
  164020. Blob key; /* Last key written to the current block */
  164021. Blob block; /* Current block image */
  164022. };
  164023. /*
  164024. ** An object of this type contains the state required to create or append
  164025. ** to an appendable b-tree segment.
  164026. */
  164027. struct IncrmergeWriter {
  164028. int nLeafEst; /* Space allocated for leaf blocks */
  164029. int nWork; /* Number of leaf pages flushed */
  164030. sqlite3_int64 iAbsLevel; /* Absolute level of input segments */
  164031. int iIdx; /* Index of *output* segment in iAbsLevel+1 */
  164032. sqlite3_int64 iStart; /* Block number of first allocated block */
  164033. sqlite3_int64 iEnd; /* Block number of last allocated block */
  164034. sqlite3_int64 nLeafData; /* Bytes of leaf page data so far */
  164035. u8 bNoLeafData; /* If true, store 0 for segment size */
  164036. NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];
  164037. };
  164038. /*
  164039. ** An object of the following type is used to read data from a single
  164040. ** FTS segment node. See the following functions:
  164041. **
  164042. ** nodeReaderInit()
  164043. ** nodeReaderNext()
  164044. ** nodeReaderRelease()
  164045. */
  164046. struct NodeReader {
  164047. const char *aNode;
  164048. int nNode;
  164049. int iOff; /* Current offset within aNode[] */
  164050. /* Output variables. Containing the current node entry. */
  164051. sqlite3_int64 iChild; /* Pointer to child node */
  164052. Blob term; /* Current term */
  164053. const char *aDoclist; /* Pointer to doclist */
  164054. int nDoclist; /* Size of doclist in bytes */
  164055. };
  164056. /*
  164057. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  164058. ** Otherwise, if the allocation at pBlob->a is not already at least nMin
  164059. ** bytes in size, extend (realloc) it to be so.
  164060. **
  164061. ** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
  164062. ** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
  164063. ** to reflect the new size of the pBlob->a[] buffer.
  164064. */
  164065. static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
  164066. if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
  164067. int nAlloc = nMin;
  164068. char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);
  164069. if( a ){
  164070. pBlob->nAlloc = nAlloc;
  164071. pBlob->a = a;
  164072. }else{
  164073. *pRc = SQLITE_NOMEM;
  164074. }
  164075. }
  164076. }
  164077. /*
  164078. ** Attempt to advance the node-reader object passed as the first argument to
  164079. ** the next entry on the node.
  164080. **
  164081. ** Return an error code if an error occurs (SQLITE_NOMEM is possible).
  164082. ** Otherwise return SQLITE_OK. If there is no next entry on the node
  164083. ** (e.g. because the current entry is the last) set NodeReader->aNode to
  164084. ** NULL to indicate EOF. Otherwise, populate the NodeReader structure output
  164085. ** variables for the new entry.
  164086. */
  164087. static int nodeReaderNext(NodeReader *p){
  164088. int bFirst = (p->term.n==0); /* True for first term on the node */
  164089. int nPrefix = 0; /* Bytes to copy from previous term */
  164090. int nSuffix = 0; /* Bytes to append to the prefix */
  164091. int rc = SQLITE_OK; /* Return code */
  164092. assert( p->aNode );
  164093. if( p->iChild && bFirst==0 ) p->iChild++;
  164094. if( p->iOff>=p->nNode ){
  164095. /* EOF */
  164096. p->aNode = 0;
  164097. }else{
  164098. if( bFirst==0 ){
  164099. p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
  164100. }
  164101. p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
  164102. if( nPrefix>p->term.n || nSuffix>p->nNode-p->iOff || nSuffix==0 ){
  164103. return FTS_CORRUPT_VTAB;
  164104. }
  164105. blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
  164106. if( rc==SQLITE_OK ){
  164107. memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
  164108. p->term.n = nPrefix+nSuffix;
  164109. p->iOff += nSuffix;
  164110. if( p->iChild==0 ){
  164111. p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
  164112. if( (p->nNode-p->iOff)<p->nDoclist ){
  164113. return FTS_CORRUPT_VTAB;
  164114. }
  164115. p->aDoclist = &p->aNode[p->iOff];
  164116. p->iOff += p->nDoclist;
  164117. }
  164118. }
  164119. }
  164120. assert_fts3_nc( p->iOff<=p->nNode );
  164121. return rc;
  164122. }
  164123. /*
  164124. ** Release all dynamic resources held by node-reader object *p.
  164125. */
  164126. static void nodeReaderRelease(NodeReader *p){
  164127. sqlite3_free(p->term.a);
  164128. }
  164129. /*
  164130. ** Initialize a node-reader object to read the node in buffer aNode/nNode.
  164131. **
  164132. ** If successful, SQLITE_OK is returned and the NodeReader object set to
  164133. ** point to the first entry on the node (if any). Otherwise, an SQLite
  164134. ** error code is returned.
  164135. */
  164136. static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){
  164137. memset(p, 0, sizeof(NodeReader));
  164138. p->aNode = aNode;
  164139. p->nNode = nNode;
  164140. /* Figure out if this is a leaf or an internal node. */
  164141. if( p->aNode[0] ){
  164142. /* An internal node. */
  164143. p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);
  164144. }else{
  164145. p->iOff = 1;
  164146. }
  164147. return nodeReaderNext(p);
  164148. }
  164149. /*
  164150. ** This function is called while writing an FTS segment each time a leaf o
  164151. ** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed
  164152. ** to be greater than the largest key on the node just written, but smaller
  164153. ** than or equal to the first key that will be written to the next leaf
  164154. ** node.
  164155. **
  164156. ** The block id of the leaf node just written to disk may be found in
  164157. ** (pWriter->aNodeWriter[0].iBlock) when this function is called.
  164158. */
  164159. static int fts3IncrmergePush(
  164160. Fts3Table *p, /* Fts3 table handle */
  164161. IncrmergeWriter *pWriter, /* Writer object */
  164162. const char *zTerm, /* Term to write to internal node */
  164163. int nTerm /* Bytes at zTerm */
  164164. ){
  164165. sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;
  164166. int iLayer;
  164167. assert( nTerm>0 );
  164168. for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){
  164169. sqlite3_int64 iNextPtr = 0;
  164170. NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];
  164171. int rc = SQLITE_OK;
  164172. int nPrefix;
  164173. int nSuffix;
  164174. int nSpace;
  164175. /* Figure out how much space the key will consume if it is written to
  164176. ** the current node of layer iLayer. Due to the prefix compression,
  164177. ** the space required changes depending on which node the key is to
  164178. ** be added to. */
  164179. nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
  164180. nSuffix = nTerm - nPrefix;
  164181. nSpace = sqlite3Fts3VarintLen(nPrefix);
  164182. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  164183. if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){
  164184. /* If the current node of layer iLayer contains zero keys, or if adding
  164185. ** the key to it will not cause it to grow to larger than nNodeSize
  164186. ** bytes in size, write the key here. */
  164187. Blob *pBlk = &pNode->block;
  164188. if( pBlk->n==0 ){
  164189. blobGrowBuffer(pBlk, p->nNodeSize, &rc);
  164190. if( rc==SQLITE_OK ){
  164191. pBlk->a[0] = (char)iLayer;
  164192. pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);
  164193. }
  164194. }
  164195. blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);
  164196. blobGrowBuffer(&pNode->key, nTerm, &rc);
  164197. if( rc==SQLITE_OK ){
  164198. if( pNode->key.n ){
  164199. pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
  164200. }
  164201. pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
  164202. memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
  164203. pBlk->n += nSuffix;
  164204. memcpy(pNode->key.a, zTerm, nTerm);
  164205. pNode->key.n = nTerm;
  164206. }
  164207. }else{
  164208. /* Otherwise, flush the current node of layer iLayer to disk.
  164209. ** Then allocate a new, empty sibling node. The key will be written
  164210. ** into the parent of this node. */
  164211. rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
  164212. assert( pNode->block.nAlloc>=p->nNodeSize );
  164213. pNode->block.a[0] = (char)iLayer;
  164214. pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);
  164215. iNextPtr = pNode->iBlock;
  164216. pNode->iBlock++;
  164217. pNode->key.n = 0;
  164218. }
  164219. if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;
  164220. iPtr = iNextPtr;
  164221. }
  164222. assert( 0 );
  164223. return 0;
  164224. }
  164225. /*
  164226. ** Append a term and (optionally) doclist to the FTS segment node currently
  164227. ** stored in blob *pNode. The node need not contain any terms, but the
  164228. ** header must be written before this function is called.
  164229. **
  164230. ** A node header is a single 0x00 byte for a leaf node, or a height varint
  164231. ** followed by the left-hand-child varint for an internal node.
  164232. **
  164233. ** The term to be appended is passed via arguments zTerm/nTerm. For a
  164234. ** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
  164235. ** node, both aDoclist and nDoclist must be passed 0.
  164236. **
  164237. ** If the size of the value in blob pPrev is zero, then this is the first
  164238. ** term written to the node. Otherwise, pPrev contains a copy of the
  164239. ** previous term. Before this function returns, it is updated to contain a
  164240. ** copy of zTerm/nTerm.
  164241. **
  164242. ** It is assumed that the buffer associated with pNode is already large
  164243. ** enough to accommodate the new entry. The buffer associated with pPrev
  164244. ** is extended by this function if requrired.
  164245. **
  164246. ** If an error (i.e. OOM condition) occurs, an SQLite error code is
  164247. ** returned. Otherwise, SQLITE_OK.
  164248. */
  164249. static int fts3AppendToNode(
  164250. Blob *pNode, /* Current node image to append to */
  164251. Blob *pPrev, /* Buffer containing previous term written */
  164252. const char *zTerm, /* New term to write */
  164253. int nTerm, /* Size of zTerm in bytes */
  164254. const char *aDoclist, /* Doclist (or NULL) to write */
  164255. int nDoclist /* Size of aDoclist in bytes */
  164256. ){
  164257. int rc = SQLITE_OK; /* Return code */
  164258. int bFirst = (pPrev->n==0); /* True if this is the first term written */
  164259. int nPrefix; /* Size of term prefix in bytes */
  164260. int nSuffix; /* Size of term suffix in bytes */
  164261. /* Node must have already been started. There must be a doclist for a
  164262. ** leaf node, and there must not be a doclist for an internal node. */
  164263. assert( pNode->n>0 );
  164264. assert_fts3_nc( (pNode->a[0]=='\0')==(aDoclist!=0) );
  164265. blobGrowBuffer(pPrev, nTerm, &rc);
  164266. if( rc!=SQLITE_OK ) return rc;
  164267. nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
  164268. nSuffix = nTerm - nPrefix;
  164269. memcpy(pPrev->a, zTerm, nTerm);
  164270. pPrev->n = nTerm;
  164271. if( bFirst==0 ){
  164272. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);
  164273. }
  164274. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);
  164275. memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);
  164276. pNode->n += nSuffix;
  164277. if( aDoclist ){
  164278. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);
  164279. memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);
  164280. pNode->n += nDoclist;
  164281. }
  164282. assert( pNode->n<=pNode->nAlloc );
  164283. return SQLITE_OK;
  164284. }
  164285. /*
  164286. ** Append the current term and doclist pointed to by cursor pCsr to the
  164287. ** appendable b-tree segment opened for writing by pWriter.
  164288. **
  164289. ** Return SQLITE_OK if successful, or an SQLite error code otherwise.
  164290. */
  164291. static int fts3IncrmergeAppend(
  164292. Fts3Table *p, /* Fts3 table handle */
  164293. IncrmergeWriter *pWriter, /* Writer object */
  164294. Fts3MultiSegReader *pCsr /* Cursor containing term and doclist */
  164295. ){
  164296. const char *zTerm = pCsr->zTerm;
  164297. int nTerm = pCsr->nTerm;
  164298. const char *aDoclist = pCsr->aDoclist;
  164299. int nDoclist = pCsr->nDoclist;
  164300. int rc = SQLITE_OK; /* Return code */
  164301. int nSpace; /* Total space in bytes required on leaf */
  164302. int nPrefix; /* Size of prefix shared with previous term */
  164303. int nSuffix; /* Size of suffix (nTerm - nPrefix) */
  164304. NodeWriter *pLeaf; /* Object used to write leaf nodes */
  164305. pLeaf = &pWriter->aNodeWriter[0];
  164306. nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
  164307. nSuffix = nTerm - nPrefix;
  164308. nSpace = sqlite3Fts3VarintLen(nPrefix);
  164309. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  164310. nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
  164311. /* If the current block is not empty, and if adding this term/doclist
  164312. ** to the current block would make it larger than Fts3Table.nNodeSize
  164313. ** bytes, write this block out to the database. */
  164314. if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){
  164315. rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
  164316. pWriter->nWork++;
  164317. /* Add the current term to the parent node. The term added to the
  164318. ** parent must:
  164319. **
  164320. ** a) be greater than the largest term on the leaf node just written
  164321. ** to the database (still available in pLeaf->key), and
  164322. **
  164323. ** b) be less than or equal to the term about to be added to the new
  164324. ** leaf node (zTerm/nTerm).
  164325. **
  164326. ** In other words, it must be the prefix of zTerm 1 byte longer than
  164327. ** the common prefix (if any) of zTerm and pWriter->zTerm.
  164328. */
  164329. if( rc==SQLITE_OK ){
  164330. rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);
  164331. }
  164332. /* Advance to the next output block */
  164333. pLeaf->iBlock++;
  164334. pLeaf->key.n = 0;
  164335. pLeaf->block.n = 0;
  164336. nSuffix = nTerm;
  164337. nSpace = 1;
  164338. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  164339. nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
  164340. }
  164341. pWriter->nLeafData += nSpace;
  164342. blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);
  164343. if( rc==SQLITE_OK ){
  164344. if( pLeaf->block.n==0 ){
  164345. pLeaf->block.n = 1;
  164346. pLeaf->block.a[0] = '\0';
  164347. }
  164348. rc = fts3AppendToNode(
  164349. &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist
  164350. );
  164351. }
  164352. return rc;
  164353. }
  164354. /*
  164355. ** This function is called to release all dynamic resources held by the
  164356. ** merge-writer object pWriter, and if no error has occurred, to flush
  164357. ** all outstanding node buffers held by pWriter to disk.
  164358. **
  164359. ** If *pRc is not SQLITE_OK when this function is called, then no attempt
  164360. ** is made to write any data to disk. Instead, this function serves only
  164361. ** to release outstanding resources.
  164362. **
  164363. ** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while
  164364. ** flushing buffers to disk, *pRc is set to an SQLite error code before
  164365. ** returning.
  164366. */
  164367. static void fts3IncrmergeRelease(
  164368. Fts3Table *p, /* FTS3 table handle */
  164369. IncrmergeWriter *pWriter, /* Merge-writer object */
  164370. int *pRc /* IN/OUT: Error code */
  164371. ){
  164372. int i; /* Used to iterate through non-root layers */
  164373. int iRoot; /* Index of root in pWriter->aNodeWriter */
  164374. NodeWriter *pRoot; /* NodeWriter for root node */
  164375. int rc = *pRc; /* Error code */
  164376. /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment
  164377. ** root node. If the segment fits entirely on a single leaf node, iRoot
  164378. ** will be set to 0. If the root node is the parent of the leaves, iRoot
  164379. ** will be 1. And so on. */
  164380. for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){
  164381. NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];
  164382. if( pNode->block.n>0 ) break;
  164383. assert( *pRc || pNode->block.nAlloc==0 );
  164384. assert( *pRc || pNode->key.nAlloc==0 );
  164385. sqlite3_free(pNode->block.a);
  164386. sqlite3_free(pNode->key.a);
  164387. }
  164388. /* Empty output segment. This is a no-op. */
  164389. if( iRoot<0 ) return;
  164390. /* The entire output segment fits on a single node. Normally, this means
  164391. ** the node would be stored as a blob in the "root" column of the %_segdir
  164392. ** table. However, this is not permitted in this case. The problem is that
  164393. ** space has already been reserved in the %_segments table, and so the
  164394. ** start_block and end_block fields of the %_segdir table must be populated.
  164395. ** And, by design or by accident, released versions of FTS cannot handle
  164396. ** segments that fit entirely on the root node with start_block!=0.
  164397. **
  164398. ** Instead, create a synthetic root node that contains nothing but a
  164399. ** pointer to the single content node. So that the segment consists of a
  164400. ** single leaf and a single interior (root) node.
  164401. **
  164402. ** Todo: Better might be to defer allocating space in the %_segments
  164403. ** table until we are sure it is needed.
  164404. */
  164405. if( iRoot==0 ){
  164406. Blob *pBlock = &pWriter->aNodeWriter[1].block;
  164407. blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);
  164408. if( rc==SQLITE_OK ){
  164409. pBlock->a[0] = 0x01;
  164410. pBlock->n = 1 + sqlite3Fts3PutVarint(
  164411. &pBlock->a[1], pWriter->aNodeWriter[0].iBlock
  164412. );
  164413. }
  164414. iRoot = 1;
  164415. }
  164416. pRoot = &pWriter->aNodeWriter[iRoot];
  164417. /* Flush all currently outstanding nodes to disk. */
  164418. for(i=0; i<iRoot; i++){
  164419. NodeWriter *pNode = &pWriter->aNodeWriter[i];
  164420. if( pNode->block.n>0 && rc==SQLITE_OK ){
  164421. rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
  164422. }
  164423. sqlite3_free(pNode->block.a);
  164424. sqlite3_free(pNode->key.a);
  164425. }
  164426. /* Write the %_segdir record. */
  164427. if( rc==SQLITE_OK ){
  164428. rc = fts3WriteSegdir(p,
  164429. pWriter->iAbsLevel+1, /* level */
  164430. pWriter->iIdx, /* idx */
  164431. pWriter->iStart, /* start_block */
  164432. pWriter->aNodeWriter[0].iBlock, /* leaves_end_block */
  164433. pWriter->iEnd, /* end_block */
  164434. (pWriter->bNoLeafData==0 ? pWriter->nLeafData : 0), /* end_block */
  164435. pRoot->block.a, pRoot->block.n /* root */
  164436. );
  164437. }
  164438. sqlite3_free(pRoot->block.a);
  164439. sqlite3_free(pRoot->key.a);
  164440. *pRc = rc;
  164441. }
  164442. /*
  164443. ** Compare the term in buffer zLhs (size in bytes nLhs) with that in
  164444. ** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of
  164445. ** the other, it is considered to be smaller than the other.
  164446. **
  164447. ** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve
  164448. ** if it is greater.
  164449. */
  164450. static int fts3TermCmp(
  164451. const char *zLhs, int nLhs, /* LHS of comparison */
  164452. const char *zRhs, int nRhs /* RHS of comparison */
  164453. ){
  164454. int nCmp = MIN(nLhs, nRhs);
  164455. int res;
  164456. res = (nCmp ? memcmp(zLhs, zRhs, nCmp) : 0);
  164457. if( res==0 ) res = nLhs - nRhs;
  164458. return res;
  164459. }
  164460. /*
  164461. ** Query to see if the entry in the %_segments table with blockid iEnd is
  164462. ** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
  164463. ** returning. Otherwise, set *pbRes to 0.
  164464. **
  164465. ** Or, if an error occurs while querying the database, return an SQLite
  164466. ** error code. The final value of *pbRes is undefined in this case.
  164467. **
  164468. ** This is used to test if a segment is an "appendable" segment. If it
  164469. ** is, then a NULL entry has been inserted into the %_segments table
  164470. ** with blockid %_segdir.end_block.
  164471. */
  164472. static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
  164473. int bRes = 0; /* Result to set *pbRes to */
  164474. sqlite3_stmt *pCheck = 0; /* Statement to query database with */
  164475. int rc; /* Return code */
  164476. rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);
  164477. if( rc==SQLITE_OK ){
  164478. sqlite3_bind_int64(pCheck, 1, iEnd);
  164479. if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
  164480. rc = sqlite3_reset(pCheck);
  164481. }
  164482. *pbRes = bRes;
  164483. return rc;
  164484. }
  164485. /*
  164486. ** This function is called when initializing an incremental-merge operation.
  164487. ** It checks if the existing segment with index value iIdx at absolute level
  164488. ** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
  164489. ** merge-writer object *pWriter is initialized to write to it.
  164490. **
  164491. ** An existing segment can be appended to by an incremental merge if:
  164492. **
  164493. ** * It was initially created as an appendable segment (with all required
  164494. ** space pre-allocated), and
  164495. **
  164496. ** * The first key read from the input (arguments zKey and nKey) is
  164497. ** greater than the largest key currently stored in the potential
  164498. ** output segment.
  164499. */
  164500. static int fts3IncrmergeLoad(
  164501. Fts3Table *p, /* Fts3 table handle */
  164502. sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
  164503. int iIdx, /* Index of candidate output segment */
  164504. const char *zKey, /* First key to write */
  164505. int nKey, /* Number of bytes in nKey */
  164506. IncrmergeWriter *pWriter /* Populate this object */
  164507. ){
  164508. int rc; /* Return code */
  164509. sqlite3_stmt *pSelect = 0; /* SELECT to read %_segdir entry */
  164510. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);
  164511. if( rc==SQLITE_OK ){
  164512. sqlite3_int64 iStart = 0; /* Value of %_segdir.start_block */
  164513. sqlite3_int64 iLeafEnd = 0; /* Value of %_segdir.leaves_end_block */
  164514. sqlite3_int64 iEnd = 0; /* Value of %_segdir.end_block */
  164515. const char *aRoot = 0; /* Pointer to %_segdir.root buffer */
  164516. int nRoot = 0; /* Size of aRoot[] in bytes */
  164517. int rc2; /* Return code from sqlite3_reset() */
  164518. int bAppendable = 0; /* Set to true if segment is appendable */
  164519. /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */
  164520. sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);
  164521. sqlite3_bind_int(pSelect, 2, iIdx);
  164522. if( sqlite3_step(pSelect)==SQLITE_ROW ){
  164523. iStart = sqlite3_column_int64(pSelect, 1);
  164524. iLeafEnd = sqlite3_column_int64(pSelect, 2);
  164525. fts3ReadEndBlockField(pSelect, 3, &iEnd, &pWriter->nLeafData);
  164526. if( pWriter->nLeafData<0 ){
  164527. pWriter->nLeafData = pWriter->nLeafData * -1;
  164528. }
  164529. pWriter->bNoLeafData = (pWriter->nLeafData==0);
  164530. nRoot = sqlite3_column_bytes(pSelect, 4);
  164531. aRoot = sqlite3_column_blob(pSelect, 4);
  164532. }else{
  164533. return sqlite3_reset(pSelect);
  164534. }
  164535. /* Check for the zero-length marker in the %_segments table */
  164536. rc = fts3IsAppendable(p, iEnd, &bAppendable);
  164537. /* Check that zKey/nKey is larger than the largest key the candidate */
  164538. if( rc==SQLITE_OK && bAppendable ){
  164539. char *aLeaf = 0;
  164540. int nLeaf = 0;
  164541. rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);
  164542. if( rc==SQLITE_OK ){
  164543. NodeReader reader;
  164544. for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);
  164545. rc==SQLITE_OK && reader.aNode;
  164546. rc = nodeReaderNext(&reader)
  164547. ){
  164548. assert( reader.aNode );
  164549. }
  164550. if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){
  164551. bAppendable = 0;
  164552. }
  164553. nodeReaderRelease(&reader);
  164554. }
  164555. sqlite3_free(aLeaf);
  164556. }
  164557. if( rc==SQLITE_OK && bAppendable ){
  164558. /* It is possible to append to this segment. Set up the IncrmergeWriter
  164559. ** object to do so. */
  164560. int i;
  164561. int nHeight = (int)aRoot[0];
  164562. NodeWriter *pNode;
  164563. pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
  164564. pWriter->iStart = iStart;
  164565. pWriter->iEnd = iEnd;
  164566. pWriter->iAbsLevel = iAbsLevel;
  164567. pWriter->iIdx = iIdx;
  164568. for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
  164569. pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
  164570. }
  164571. pNode = &pWriter->aNodeWriter[nHeight];
  164572. pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
  164573. blobGrowBuffer(&pNode->block,
  164574. MAX(nRoot, p->nNodeSize)+FTS3_NODE_PADDING, &rc
  164575. );
  164576. if( rc==SQLITE_OK ){
  164577. memcpy(pNode->block.a, aRoot, nRoot);
  164578. pNode->block.n = nRoot;
  164579. memset(&pNode->block.a[nRoot], 0, FTS3_NODE_PADDING);
  164580. }
  164581. for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){
  164582. NodeReader reader;
  164583. pNode = &pWriter->aNodeWriter[i];
  164584. rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);
  164585. if( reader.aNode ){
  164586. while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);
  164587. blobGrowBuffer(&pNode->key, reader.term.n, &rc);
  164588. if( rc==SQLITE_OK ){
  164589. memcpy(pNode->key.a, reader.term.a, reader.term.n);
  164590. pNode->key.n = reader.term.n;
  164591. if( i>0 ){
  164592. char *aBlock = 0;
  164593. int nBlock = 0;
  164594. pNode = &pWriter->aNodeWriter[i-1];
  164595. pNode->iBlock = reader.iChild;
  164596. rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);
  164597. blobGrowBuffer(&pNode->block,
  164598. MAX(nBlock, p->nNodeSize)+FTS3_NODE_PADDING, &rc
  164599. );
  164600. if( rc==SQLITE_OK ){
  164601. memcpy(pNode->block.a, aBlock, nBlock);
  164602. pNode->block.n = nBlock;
  164603. memset(&pNode->block.a[nBlock], 0, FTS3_NODE_PADDING);
  164604. }
  164605. sqlite3_free(aBlock);
  164606. }
  164607. }
  164608. }
  164609. nodeReaderRelease(&reader);
  164610. }
  164611. }
  164612. rc2 = sqlite3_reset(pSelect);
  164613. if( rc==SQLITE_OK ) rc = rc2;
  164614. }
  164615. return rc;
  164616. }
  164617. /*
  164618. ** Determine the largest segment index value that exists within absolute
  164619. ** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
  164620. ** one before returning SQLITE_OK. Or, if there are no segments at all
  164621. ** within level iAbsLevel, set *piIdx to zero.
  164622. **
  164623. ** If an error occurs, return an SQLite error code. The final value of
  164624. ** *piIdx is undefined in this case.
  164625. */
  164626. static int fts3IncrmergeOutputIdx(
  164627. Fts3Table *p, /* FTS Table handle */
  164628. sqlite3_int64 iAbsLevel, /* Absolute index of input segments */
  164629. int *piIdx /* OUT: Next free index at iAbsLevel+1 */
  164630. ){
  164631. int rc;
  164632. sqlite3_stmt *pOutputIdx = 0; /* SQL used to find output index */
  164633. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);
  164634. if( rc==SQLITE_OK ){
  164635. sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);
  164636. sqlite3_step(pOutputIdx);
  164637. *piIdx = sqlite3_column_int(pOutputIdx, 0);
  164638. rc = sqlite3_reset(pOutputIdx);
  164639. }
  164640. return rc;
  164641. }
  164642. /*
  164643. ** Allocate an appendable output segment on absolute level iAbsLevel+1
  164644. ** with idx value iIdx.
  164645. **
  164646. ** In the %_segdir table, a segment is defined by the values in three
  164647. ** columns:
  164648. **
  164649. ** start_block
  164650. ** leaves_end_block
  164651. ** end_block
  164652. **
  164653. ** When an appendable segment is allocated, it is estimated that the
  164654. ** maximum number of leaf blocks that may be required is the sum of the
  164655. ** number of leaf blocks consumed by the input segments, plus the number
  164656. ** of input segments, multiplied by two. This value is stored in stack
  164657. ** variable nLeafEst.
  164658. **
  164659. ** A total of 16*nLeafEst blocks are allocated when an appendable segment
  164660. ** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous
  164661. ** array of leaf nodes starts at the first block allocated. The array
  164662. ** of interior nodes that are parents of the leaf nodes start at block
  164663. ** (start_block + (1 + end_block - start_block) / 16). And so on.
  164664. **
  164665. ** In the actual code below, the value "16" is replaced with the
  164666. ** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
  164667. */
  164668. static int fts3IncrmergeWriter(
  164669. Fts3Table *p, /* Fts3 table handle */
  164670. sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
  164671. int iIdx, /* Index of new output segment */
  164672. Fts3MultiSegReader *pCsr, /* Cursor that data will be read from */
  164673. IncrmergeWriter *pWriter /* Populate this object */
  164674. ){
  164675. int rc; /* Return Code */
  164676. int i; /* Iterator variable */
  164677. int nLeafEst = 0; /* Blocks allocated for leaf nodes */
  164678. sqlite3_stmt *pLeafEst = 0; /* SQL used to determine nLeafEst */
  164679. sqlite3_stmt *pFirstBlock = 0; /* SQL used to determine first block */
  164680. /* Calculate nLeafEst. */
  164681. rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);
  164682. if( rc==SQLITE_OK ){
  164683. sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);
  164684. sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);
  164685. if( SQLITE_ROW==sqlite3_step(pLeafEst) ){
  164686. nLeafEst = sqlite3_column_int(pLeafEst, 0);
  164687. }
  164688. rc = sqlite3_reset(pLeafEst);
  164689. }
  164690. if( rc!=SQLITE_OK ) return rc;
  164691. /* Calculate the first block to use in the output segment */
  164692. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);
  164693. if( rc==SQLITE_OK ){
  164694. if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){
  164695. pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);
  164696. pWriter->iEnd = pWriter->iStart - 1;
  164697. pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;
  164698. }
  164699. rc = sqlite3_reset(pFirstBlock);
  164700. }
  164701. if( rc!=SQLITE_OK ) return rc;
  164702. /* Insert the marker in the %_segments table to make sure nobody tries
  164703. ** to steal the space just allocated. This is also used to identify
  164704. ** appendable segments. */
  164705. rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
  164706. if( rc!=SQLITE_OK ) return rc;
  164707. pWriter->iAbsLevel = iAbsLevel;
  164708. pWriter->nLeafEst = nLeafEst;
  164709. pWriter->iIdx = iIdx;
  164710. /* Set up the array of NodeWriter objects */
  164711. for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
  164712. pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
  164713. }
  164714. return SQLITE_OK;
  164715. }
  164716. /*
  164717. ** Remove an entry from the %_segdir table. This involves running the
  164718. ** following two statements:
  164719. **
  164720. ** DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
  164721. ** UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
  164722. **
  164723. ** The DELETE statement removes the specific %_segdir level. The UPDATE
  164724. ** statement ensures that the remaining segments have contiguously allocated
  164725. ** idx values.
  164726. */
  164727. static int fts3RemoveSegdirEntry(
  164728. Fts3Table *p, /* FTS3 table handle */
  164729. sqlite3_int64 iAbsLevel, /* Absolute level to delete from */
  164730. int iIdx /* Index of %_segdir entry to delete */
  164731. ){
  164732. int rc; /* Return code */
  164733. sqlite3_stmt *pDelete = 0; /* DELETE statement */
  164734. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);
  164735. if( rc==SQLITE_OK ){
  164736. sqlite3_bind_int64(pDelete, 1, iAbsLevel);
  164737. sqlite3_bind_int(pDelete, 2, iIdx);
  164738. sqlite3_step(pDelete);
  164739. rc = sqlite3_reset(pDelete);
  164740. }
  164741. return rc;
  164742. }
  164743. /*
  164744. ** One or more segments have just been removed from absolute level iAbsLevel.
  164745. ** Update the 'idx' values of the remaining segments in the level so that
  164746. ** the idx values are a contiguous sequence starting from 0.
  164747. */
  164748. static int fts3RepackSegdirLevel(
  164749. Fts3Table *p, /* FTS3 table handle */
  164750. sqlite3_int64 iAbsLevel /* Absolute level to repack */
  164751. ){
  164752. int rc; /* Return code */
  164753. int *aIdx = 0; /* Array of remaining idx values */
  164754. int nIdx = 0; /* Valid entries in aIdx[] */
  164755. int nAlloc = 0; /* Allocated size of aIdx[] */
  164756. int i; /* Iterator variable */
  164757. sqlite3_stmt *pSelect = 0; /* Select statement to read idx values */
  164758. sqlite3_stmt *pUpdate = 0; /* Update statement to modify idx values */
  164759. rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);
  164760. if( rc==SQLITE_OK ){
  164761. int rc2;
  164762. sqlite3_bind_int64(pSelect, 1, iAbsLevel);
  164763. while( SQLITE_ROW==sqlite3_step(pSelect) ){
  164764. if( nIdx>=nAlloc ){
  164765. int *aNew;
  164766. nAlloc += 16;
  164767. aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));
  164768. if( !aNew ){
  164769. rc = SQLITE_NOMEM;
  164770. break;
  164771. }
  164772. aIdx = aNew;
  164773. }
  164774. aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);
  164775. }
  164776. rc2 = sqlite3_reset(pSelect);
  164777. if( rc==SQLITE_OK ) rc = rc2;
  164778. }
  164779. if( rc==SQLITE_OK ){
  164780. rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);
  164781. }
  164782. if( rc==SQLITE_OK ){
  164783. sqlite3_bind_int64(pUpdate, 2, iAbsLevel);
  164784. }
  164785. assert( p->bIgnoreSavepoint==0 );
  164786. p->bIgnoreSavepoint = 1;
  164787. for(i=0; rc==SQLITE_OK && i<nIdx; i++){
  164788. if( aIdx[i]!=i ){
  164789. sqlite3_bind_int(pUpdate, 3, aIdx[i]);
  164790. sqlite3_bind_int(pUpdate, 1, i);
  164791. sqlite3_step(pUpdate);
  164792. rc = sqlite3_reset(pUpdate);
  164793. }
  164794. }
  164795. p->bIgnoreSavepoint = 0;
  164796. sqlite3_free(aIdx);
  164797. return rc;
  164798. }
  164799. static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){
  164800. pNode->a[0] = (char)iHeight;
  164801. if( iChild ){
  164802. assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );
  164803. pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);
  164804. }else{
  164805. assert( pNode->nAlloc>=1 );
  164806. pNode->n = 1;
  164807. }
  164808. }
  164809. /*
  164810. ** The first two arguments are a pointer to and the size of a segment b-tree
  164811. ** node. The node may be a leaf or an internal node.
  164812. **
  164813. ** This function creates a new node image in blob object *pNew by copying
  164814. ** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)
  164815. ** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.
  164816. */
  164817. static int fts3TruncateNode(
  164818. const char *aNode, /* Current node image */
  164819. int nNode, /* Size of aNode in bytes */
  164820. Blob *pNew, /* OUT: Write new node image here */
  164821. const char *zTerm, /* Omit all terms smaller than this */
  164822. int nTerm, /* Size of zTerm in bytes */
  164823. sqlite3_int64 *piBlock /* OUT: Block number in next layer down */
  164824. ){
  164825. NodeReader reader; /* Reader object */
  164826. Blob prev = {0, 0, 0}; /* Previous term written to new node */
  164827. int rc = SQLITE_OK; /* Return code */
  164828. int bLeaf; /* True for a leaf node */
  164829. if( nNode<1 ) return FTS_CORRUPT_VTAB;
  164830. bLeaf = aNode[0]=='\0';
  164831. /* Allocate required output space */
  164832. blobGrowBuffer(pNew, nNode, &rc);
  164833. if( rc!=SQLITE_OK ) return rc;
  164834. pNew->n = 0;
  164835. /* Populate new node buffer */
  164836. for(rc = nodeReaderInit(&reader, aNode, nNode);
  164837. rc==SQLITE_OK && reader.aNode;
  164838. rc = nodeReaderNext(&reader)
  164839. ){
  164840. if( pNew->n==0 ){
  164841. int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);
  164842. if( res<0 || (bLeaf==0 && res==0) ) continue;
  164843. fts3StartNode(pNew, (int)aNode[0], reader.iChild);
  164844. *piBlock = reader.iChild;
  164845. }
  164846. rc = fts3AppendToNode(
  164847. pNew, &prev, reader.term.a, reader.term.n,
  164848. reader.aDoclist, reader.nDoclist
  164849. );
  164850. if( rc!=SQLITE_OK ) break;
  164851. }
  164852. if( pNew->n==0 ){
  164853. fts3StartNode(pNew, (int)aNode[0], reader.iChild);
  164854. *piBlock = reader.iChild;
  164855. }
  164856. assert( pNew->n<=pNew->nAlloc );
  164857. nodeReaderRelease(&reader);
  164858. sqlite3_free(prev.a);
  164859. return rc;
  164860. }
  164861. /*
  164862. ** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute
  164863. ** level iAbsLevel. This may involve deleting entries from the %_segments
  164864. ** table, and modifying existing entries in both the %_segments and %_segdir
  164865. ** tables.
  164866. **
  164867. ** SQLITE_OK is returned if the segment is updated successfully. Or an
  164868. ** SQLite error code otherwise.
  164869. */
  164870. static int fts3TruncateSegment(
  164871. Fts3Table *p, /* FTS3 table handle */
  164872. sqlite3_int64 iAbsLevel, /* Absolute level of segment to modify */
  164873. int iIdx, /* Index within level of segment to modify */
  164874. const char *zTerm, /* Remove terms smaller than this */
  164875. int nTerm /* Number of bytes in buffer zTerm */
  164876. ){
  164877. int rc = SQLITE_OK; /* Return code */
  164878. Blob root = {0,0,0}; /* New root page image */
  164879. Blob block = {0,0,0}; /* Buffer used for any other block */
  164880. sqlite3_int64 iBlock = 0; /* Block id */
  164881. sqlite3_int64 iNewStart = 0; /* New value for iStartBlock */
  164882. sqlite3_int64 iOldStart = 0; /* Old value for iStartBlock */
  164883. sqlite3_stmt *pFetch = 0; /* Statement used to fetch segdir */
  164884. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);
  164885. if( rc==SQLITE_OK ){
  164886. int rc2; /* sqlite3_reset() return code */
  164887. sqlite3_bind_int64(pFetch, 1, iAbsLevel);
  164888. sqlite3_bind_int(pFetch, 2, iIdx);
  164889. if( SQLITE_ROW==sqlite3_step(pFetch) ){
  164890. const char *aRoot = sqlite3_column_blob(pFetch, 4);
  164891. int nRoot = sqlite3_column_bytes(pFetch, 4);
  164892. iOldStart = sqlite3_column_int64(pFetch, 1);
  164893. rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);
  164894. }
  164895. rc2 = sqlite3_reset(pFetch);
  164896. if( rc==SQLITE_OK ) rc = rc2;
  164897. }
  164898. while( rc==SQLITE_OK && iBlock ){
  164899. char *aBlock = 0;
  164900. int nBlock = 0;
  164901. iNewStart = iBlock;
  164902. rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);
  164903. if( rc==SQLITE_OK ){
  164904. rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);
  164905. }
  164906. if( rc==SQLITE_OK ){
  164907. rc = fts3WriteSegment(p, iNewStart, block.a, block.n);
  164908. }
  164909. sqlite3_free(aBlock);
  164910. }
  164911. /* Variable iNewStart now contains the first valid leaf node. */
  164912. if( rc==SQLITE_OK && iNewStart ){
  164913. sqlite3_stmt *pDel = 0;
  164914. rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);
  164915. if( rc==SQLITE_OK ){
  164916. sqlite3_bind_int64(pDel, 1, iOldStart);
  164917. sqlite3_bind_int64(pDel, 2, iNewStart-1);
  164918. sqlite3_step(pDel);
  164919. rc = sqlite3_reset(pDel);
  164920. }
  164921. }
  164922. if( rc==SQLITE_OK ){
  164923. sqlite3_stmt *pChomp = 0;
  164924. rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);
  164925. if( rc==SQLITE_OK ){
  164926. sqlite3_bind_int64(pChomp, 1, iNewStart);
  164927. sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);
  164928. sqlite3_bind_int64(pChomp, 3, iAbsLevel);
  164929. sqlite3_bind_int(pChomp, 4, iIdx);
  164930. sqlite3_step(pChomp);
  164931. rc = sqlite3_reset(pChomp);
  164932. sqlite3_bind_null(pChomp, 2);
  164933. }
  164934. }
  164935. sqlite3_free(root.a);
  164936. sqlite3_free(block.a);
  164937. return rc;
  164938. }
  164939. /*
  164940. ** This function is called after an incrmental-merge operation has run to
  164941. ** merge (or partially merge) two or more segments from absolute level
  164942. ** iAbsLevel.
  164943. **
  164944. ** Each input segment is either removed from the db completely (if all of
  164945. ** its data was copied to the output segment by the incrmerge operation)
  164946. ** or modified in place so that it no longer contains those entries that
  164947. ** have been duplicated in the output segment.
  164948. */
  164949. static int fts3IncrmergeChomp(
  164950. Fts3Table *p, /* FTS table handle */
  164951. sqlite3_int64 iAbsLevel, /* Absolute level containing segments */
  164952. Fts3MultiSegReader *pCsr, /* Chomp all segments opened by this cursor */
  164953. int *pnRem /* Number of segments not deleted */
  164954. ){
  164955. int i;
  164956. int nRem = 0;
  164957. int rc = SQLITE_OK;
  164958. for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
  164959. Fts3SegReader *pSeg = 0;
  164960. int j;
  164961. /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
  164962. ** somewhere in the pCsr->apSegment[] array. */
  164963. for(j=0; ALWAYS(j<pCsr->nSegment); j++){
  164964. pSeg = pCsr->apSegment[j];
  164965. if( pSeg->iIdx==i ) break;
  164966. }
  164967. assert( j<pCsr->nSegment && pSeg->iIdx==i );
  164968. if( pSeg->aNode==0 ){
  164969. /* Seg-reader is at EOF. Remove the entire input segment. */
  164970. rc = fts3DeleteSegment(p, pSeg);
  164971. if( rc==SQLITE_OK ){
  164972. rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
  164973. }
  164974. *pnRem = 0;
  164975. }else{
  164976. /* The incremental merge did not copy all the data from this
  164977. ** segment to the upper level. The segment is modified in place
  164978. ** so that it contains no keys smaller than zTerm/nTerm. */
  164979. const char *zTerm = pSeg->zTerm;
  164980. int nTerm = pSeg->nTerm;
  164981. rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
  164982. nRem++;
  164983. }
  164984. }
  164985. if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
  164986. rc = fts3RepackSegdirLevel(p, iAbsLevel);
  164987. }
  164988. *pnRem = nRem;
  164989. return rc;
  164990. }
  164991. /*
  164992. ** Store an incr-merge hint in the database.
  164993. */
  164994. static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
  164995. sqlite3_stmt *pReplace = 0;
  164996. int rc; /* Return code */
  164997. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);
  164998. if( rc==SQLITE_OK ){
  164999. sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);
  165000. sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);
  165001. sqlite3_step(pReplace);
  165002. rc = sqlite3_reset(pReplace);
  165003. sqlite3_bind_null(pReplace, 2);
  165004. }
  165005. return rc;
  165006. }
  165007. /*
  165008. ** Load an incr-merge hint from the database. The incr-merge hint, if one
  165009. ** exists, is stored in the rowid==1 row of the %_stat table.
  165010. **
  165011. ** If successful, populate blob *pHint with the value read from the %_stat
  165012. ** table and return SQLITE_OK. Otherwise, if an error occurs, return an
  165013. ** SQLite error code.
  165014. */
  165015. static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
  165016. sqlite3_stmt *pSelect = 0;
  165017. int rc;
  165018. pHint->n = 0;
  165019. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);
  165020. if( rc==SQLITE_OK ){
  165021. int rc2;
  165022. sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);
  165023. if( SQLITE_ROW==sqlite3_step(pSelect) ){
  165024. const char *aHint = sqlite3_column_blob(pSelect, 0);
  165025. int nHint = sqlite3_column_bytes(pSelect, 0);
  165026. if( aHint ){
  165027. blobGrowBuffer(pHint, nHint, &rc);
  165028. if( rc==SQLITE_OK ){
  165029. memcpy(pHint->a, aHint, nHint);
  165030. pHint->n = nHint;
  165031. }
  165032. }
  165033. }
  165034. rc2 = sqlite3_reset(pSelect);
  165035. if( rc==SQLITE_OK ) rc = rc2;
  165036. }
  165037. return rc;
  165038. }
  165039. /*
  165040. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  165041. ** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
  165042. ** consists of two varints, the absolute level number of the input segments
  165043. ** and the number of input segments.
  165044. **
  165045. ** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
  165046. ** set *pRc to an SQLite error code before returning.
  165047. */
  165048. static void fts3IncrmergeHintPush(
  165049. Blob *pHint, /* Hint blob to append to */
  165050. i64 iAbsLevel, /* First varint to store in hint */
  165051. int nInput, /* Second varint to store in hint */
  165052. int *pRc /* IN/OUT: Error code */
  165053. ){
  165054. blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);
  165055. if( *pRc==SQLITE_OK ){
  165056. pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);
  165057. pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);
  165058. }
  165059. }
  165060. /*
  165061. ** Read the last entry (most recently pushed) from the hint blob *pHint
  165062. ** and then remove the entry. Write the two values read to *piAbsLevel and
  165063. ** *pnInput before returning.
  165064. **
  165065. ** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
  165066. ** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.
  165067. */
  165068. static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
  165069. const int nHint = pHint->n;
  165070. int i;
  165071. i = pHint->n-2;
  165072. while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
  165073. while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
  165074. pHint->n = i;
  165075. i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
  165076. i += fts3GetVarint32(&pHint->a[i], pnInput);
  165077. if( i!=nHint ) return FTS_CORRUPT_VTAB;
  165078. return SQLITE_OK;
  165079. }
  165080. /*
  165081. ** Attempt an incremental merge that writes nMerge leaf blocks.
  165082. **
  165083. ** Incremental merges happen nMin segments at a time. The segments
  165084. ** to be merged are the nMin oldest segments (the ones with the smallest
  165085. ** values for the _segdir.idx field) in the highest level that contains
  165086. ** at least nMin segments. Multiple merges might occur in an attempt to
  165087. ** write the quota of nMerge leaf blocks.
  165088. */
  165089. SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
  165090. int rc; /* Return code */
  165091. int nRem = nMerge; /* Number of leaf pages yet to be written */
  165092. Fts3MultiSegReader *pCsr; /* Cursor used to read input data */
  165093. Fts3SegFilter *pFilter; /* Filter used with cursor pCsr */
  165094. IncrmergeWriter *pWriter; /* Writer object */
  165095. int nSeg = 0; /* Number of input segments */
  165096. sqlite3_int64 iAbsLevel = 0; /* Absolute level number to work on */
  165097. Blob hint = {0, 0, 0}; /* Hint read from %_stat table */
  165098. int bDirtyHint = 0; /* True if blob 'hint' has been modified */
  165099. /* Allocate space for the cursor, filter and writer objects */
  165100. const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
  165101. pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);
  165102. if( !pWriter ) return SQLITE_NOMEM;
  165103. pFilter = (Fts3SegFilter *)&pWriter[1];
  165104. pCsr = (Fts3MultiSegReader *)&pFilter[1];
  165105. rc = fts3IncrmergeHintLoad(p, &hint);
  165106. while( rc==SQLITE_OK && nRem>0 ){
  165107. const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;
  165108. sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */
  165109. int bUseHint = 0; /* True if attempting to append */
  165110. int iIdx = 0; /* Largest idx in level (iAbsLevel+1) */
  165111. /* Search the %_segdir table for the absolute level with the smallest
  165112. ** relative level number that contains at least nMin segments, if any.
  165113. ** If one is found, set iAbsLevel to the absolute level number and
  165114. ** nSeg to nMin. If no level with at least nMin segments can be found,
  165115. ** set nSeg to -1.
  165116. */
  165117. rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
  165118. sqlite3_bind_int(pFindLevel, 1, MAX(2, nMin));
  165119. if( sqlite3_step(pFindLevel)==SQLITE_ROW ){
  165120. iAbsLevel = sqlite3_column_int64(pFindLevel, 0);
  165121. nSeg = sqlite3_column_int(pFindLevel, 1);
  165122. assert( nSeg>=2 );
  165123. }else{
  165124. nSeg = -1;
  165125. }
  165126. rc = sqlite3_reset(pFindLevel);
  165127. /* If the hint read from the %_stat table is not empty, check if the
  165128. ** last entry in it specifies a relative level smaller than or equal
  165129. ** to the level identified by the block above (if any). If so, this
  165130. ** iteration of the loop will work on merging at the hinted level.
  165131. */
  165132. if( rc==SQLITE_OK && hint.n ){
  165133. int nHint = hint.n;
  165134. sqlite3_int64 iHintAbsLevel = 0; /* Hint level */
  165135. int nHintSeg = 0; /* Hint number of segments */
  165136. rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
  165137. if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
  165138. iAbsLevel = iHintAbsLevel;
  165139. nSeg = nHintSeg;
  165140. bUseHint = 1;
  165141. bDirtyHint = 1;
  165142. }else{
  165143. /* This undoes the effect of the HintPop() above - so that no entry
  165144. ** is removed from the hint blob. */
  165145. hint.n = nHint;
  165146. }
  165147. }
  165148. /* If nSeg is less that zero, then there is no level with at least
  165149. ** nMin segments and no hint in the %_stat table. No work to do.
  165150. ** Exit early in this case. */
  165151. if( nSeg<0 ) break;
  165152. /* Open a cursor to iterate through the contents of the oldest nSeg
  165153. ** indexes of absolute level iAbsLevel. If this cursor is opened using
  165154. ** the 'hint' parameters, it is possible that there are less than nSeg
  165155. ** segments available in level iAbsLevel. In this case, no work is
  165156. ** done on iAbsLevel - fall through to the next iteration of the loop
  165157. ** to start work on some other level. */
  165158. memset(pWriter, 0, nAlloc);
  165159. pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
  165160. if( rc==SQLITE_OK ){
  165161. rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
  165162. assert( bUseHint==1 || bUseHint==0 );
  165163. if( iIdx==0 || (bUseHint && iIdx==1) ){
  165164. int bIgnore = 0;
  165165. rc = fts3SegmentIsMaxLevel(p, iAbsLevel+1, &bIgnore);
  165166. if( bIgnore ){
  165167. pFilter->flags |= FTS3_SEGMENT_IGNORE_EMPTY;
  165168. }
  165169. }
  165170. }
  165171. if( rc==SQLITE_OK ){
  165172. rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);
  165173. }
  165174. if( SQLITE_OK==rc && pCsr->nSegment==nSeg
  165175. && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
  165176. && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr))
  165177. ){
  165178. if( bUseHint && iIdx>0 ){
  165179. const char *zKey = pCsr->zTerm;
  165180. int nKey = pCsr->nTerm;
  165181. rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);
  165182. }else{
  165183. rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);
  165184. }
  165185. if( rc==SQLITE_OK && pWriter->nLeafEst ){
  165186. fts3LogMerge(nSeg, iAbsLevel);
  165187. do {
  165188. rc = fts3IncrmergeAppend(p, pWriter, pCsr);
  165189. if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
  165190. if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
  165191. }while( rc==SQLITE_ROW );
  165192. /* Update or delete the input segments */
  165193. if( rc==SQLITE_OK ){
  165194. nRem -= (1 + pWriter->nWork);
  165195. rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);
  165196. if( nSeg!=0 ){
  165197. bDirtyHint = 1;
  165198. fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);
  165199. }
  165200. }
  165201. }
  165202. if( nSeg!=0 ){
  165203. pWriter->nLeafData = pWriter->nLeafData * -1;
  165204. }
  165205. fts3IncrmergeRelease(p, pWriter, &rc);
  165206. if( nSeg==0 && pWriter->bNoLeafData==0 ){
  165207. fts3PromoteSegments(p, iAbsLevel+1, pWriter->nLeafData);
  165208. }
  165209. }
  165210. sqlite3Fts3SegReaderFinish(pCsr);
  165211. }
  165212. /* Write the hint values into the %_stat table for the next incr-merger */
  165213. if( bDirtyHint && rc==SQLITE_OK ){
  165214. rc = fts3IncrmergeHintStore(p, &hint);
  165215. }
  165216. sqlite3_free(pWriter);
  165217. sqlite3_free(hint.a);
  165218. return rc;
  165219. }
  165220. /*
  165221. ** Convert the text beginning at *pz into an integer and return
  165222. ** its value. Advance *pz to point to the first character past
  165223. ** the integer.
  165224. **
  165225. ** This function used for parameters to merge= and incrmerge=
  165226. ** commands.
  165227. */
  165228. static int fts3Getint(const char **pz){
  165229. const char *z = *pz;
  165230. int i = 0;
  165231. while( (*z)>='0' && (*z)<='9' && i<214748363 ) i = 10*i + *(z++) - '0';
  165232. *pz = z;
  165233. return i;
  165234. }
  165235. /*
  165236. ** Process statements of the form:
  165237. **
  165238. ** INSERT INTO table(table) VALUES('merge=A,B');
  165239. **
  165240. ** A and B are integers that decode to be the number of leaf pages
  165241. ** written for the merge, and the minimum number of segments on a level
  165242. ** before it will be selected for a merge, respectively.
  165243. */
  165244. static int fts3DoIncrmerge(
  165245. Fts3Table *p, /* FTS3 table handle */
  165246. const char *zParam /* Nul-terminated string containing "A,B" */
  165247. ){
  165248. int rc;
  165249. int nMin = (FTS3_MERGE_COUNT / 2);
  165250. int nMerge = 0;
  165251. const char *z = zParam;
  165252. /* Read the first integer value */
  165253. nMerge = fts3Getint(&z);
  165254. /* If the first integer value is followed by a ',', read the second
  165255. ** integer value. */
  165256. if( z[0]==',' && z[1]!='\0' ){
  165257. z++;
  165258. nMin = fts3Getint(&z);
  165259. }
  165260. if( z[0]!='\0' || nMin<2 ){
  165261. rc = SQLITE_ERROR;
  165262. }else{
  165263. rc = SQLITE_OK;
  165264. if( !p->bHasStat ){
  165265. assert( p->bFts4==0 );
  165266. sqlite3Fts3CreateStatTable(&rc, p);
  165267. }
  165268. if( rc==SQLITE_OK ){
  165269. rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);
  165270. }
  165271. sqlite3Fts3SegmentsClose(p);
  165272. }
  165273. return rc;
  165274. }
  165275. /*
  165276. ** Process statements of the form:
  165277. **
  165278. ** INSERT INTO table(table) VALUES('automerge=X');
  165279. **
  165280. ** where X is an integer. X==0 means to turn automerge off. X!=0 means
  165281. ** turn it on. The setting is persistent.
  165282. */
  165283. static int fts3DoAutoincrmerge(
  165284. Fts3Table *p, /* FTS3 table handle */
  165285. const char *zParam /* Nul-terminated string containing boolean */
  165286. ){
  165287. int rc = SQLITE_OK;
  165288. sqlite3_stmt *pStmt = 0;
  165289. p->nAutoincrmerge = fts3Getint(&zParam);
  165290. if( p->nAutoincrmerge==1 || p->nAutoincrmerge>FTS3_MERGE_COUNT ){
  165291. p->nAutoincrmerge = 8;
  165292. }
  165293. if( !p->bHasStat ){
  165294. assert( p->bFts4==0 );
  165295. sqlite3Fts3CreateStatTable(&rc, p);
  165296. if( rc ) return rc;
  165297. }
  165298. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
  165299. if( rc ) return rc;
  165300. sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
  165301. sqlite3_bind_int(pStmt, 2, p->nAutoincrmerge);
  165302. sqlite3_step(pStmt);
  165303. rc = sqlite3_reset(pStmt);
  165304. return rc;
  165305. }
  165306. /*
  165307. ** Return a 64-bit checksum for the FTS index entry specified by the
  165308. ** arguments to this function.
  165309. */
  165310. static u64 fts3ChecksumEntry(
  165311. const char *zTerm, /* Pointer to buffer containing term */
  165312. int nTerm, /* Size of zTerm in bytes */
  165313. int iLangid, /* Language id for current row */
  165314. int iIndex, /* Index (0..Fts3Table.nIndex-1) */
  165315. i64 iDocid, /* Docid for current row. */
  165316. int iCol, /* Column number */
  165317. int iPos /* Position */
  165318. ){
  165319. int i;
  165320. u64 ret = (u64)iDocid;
  165321. ret += (ret<<3) + iLangid;
  165322. ret += (ret<<3) + iIndex;
  165323. ret += (ret<<3) + iCol;
  165324. ret += (ret<<3) + iPos;
  165325. for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];
  165326. return ret;
  165327. }
  165328. /*
  165329. ** Return a checksum of all entries in the FTS index that correspond to
  165330. ** language id iLangid. The checksum is calculated by XORing the checksums
  165331. ** of each individual entry (see fts3ChecksumEntry()) together.
  165332. **
  165333. ** If successful, the checksum value is returned and *pRc set to SQLITE_OK.
  165334. ** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The
  165335. ** return value is undefined in this case.
  165336. */
  165337. static u64 fts3ChecksumIndex(
  165338. Fts3Table *p, /* FTS3 table handle */
  165339. int iLangid, /* Language id to return cksum for */
  165340. int iIndex, /* Index to cksum (0..p->nIndex-1) */
  165341. int *pRc /* OUT: Return code */
  165342. ){
  165343. Fts3SegFilter filter;
  165344. Fts3MultiSegReader csr;
  165345. int rc;
  165346. u64 cksum = 0;
  165347. assert( *pRc==SQLITE_OK );
  165348. memset(&filter, 0, sizeof(filter));
  165349. memset(&csr, 0, sizeof(csr));
  165350. filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
  165351. filter.flags |= FTS3_SEGMENT_SCAN;
  165352. rc = sqlite3Fts3SegReaderCursor(
  165353. p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr
  165354. );
  165355. if( rc==SQLITE_OK ){
  165356. rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
  165357. }
  165358. if( rc==SQLITE_OK ){
  165359. while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){
  165360. char *pCsr = csr.aDoclist;
  165361. char *pEnd = &pCsr[csr.nDoclist];
  165362. i64 iDocid = 0;
  165363. i64 iCol = 0;
  165364. i64 iPos = 0;
  165365. pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
  165366. while( pCsr<pEnd ){
  165367. i64 iVal = 0;
  165368. pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
  165369. if( pCsr<pEnd ){
  165370. if( iVal==0 || iVal==1 ){
  165371. iCol = 0;
  165372. iPos = 0;
  165373. if( iVal ){
  165374. pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
  165375. }else{
  165376. pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
  165377. iDocid += iVal;
  165378. }
  165379. }else{
  165380. iPos += (iVal - 2);
  165381. cksum = cksum ^ fts3ChecksumEntry(
  165382. csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,
  165383. (int)iCol, (int)iPos
  165384. );
  165385. }
  165386. }
  165387. }
  165388. }
  165389. }
  165390. sqlite3Fts3SegReaderFinish(&csr);
  165391. *pRc = rc;
  165392. return cksum;
  165393. }
  165394. /*
  165395. ** Check if the contents of the FTS index match the current contents of the
  165396. ** content table. If no error occurs and the contents do match, set *pbOk
  165397. ** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
  165398. ** to false before returning.
  165399. **
  165400. ** If an error occurs (e.g. an OOM or IO error), return an SQLite error
  165401. ** code. The final value of *pbOk is undefined in this case.
  165402. */
  165403. static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
  165404. int rc = SQLITE_OK; /* Return code */
  165405. u64 cksum1 = 0; /* Checksum based on FTS index contents */
  165406. u64 cksum2 = 0; /* Checksum based on %_content contents */
  165407. sqlite3_stmt *pAllLangid = 0; /* Statement to return all language-ids */
  165408. /* This block calculates the checksum according to the FTS index. */
  165409. rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
  165410. if( rc==SQLITE_OK ){
  165411. int rc2;
  165412. sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
  165413. sqlite3_bind_int(pAllLangid, 2, p->nIndex);
  165414. while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){
  165415. int iLangid = sqlite3_column_int(pAllLangid, 0);
  165416. int i;
  165417. for(i=0; i<p->nIndex; i++){
  165418. cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);
  165419. }
  165420. }
  165421. rc2 = sqlite3_reset(pAllLangid);
  165422. if( rc==SQLITE_OK ) rc = rc2;
  165423. }
  165424. /* This block calculates the checksum according to the %_content table */
  165425. if( rc==SQLITE_OK ){
  165426. sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
  165427. sqlite3_stmt *pStmt = 0;
  165428. char *zSql;
  165429. zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
  165430. if( !zSql ){
  165431. rc = SQLITE_NOMEM;
  165432. }else{
  165433. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  165434. sqlite3_free(zSql);
  165435. }
  165436. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  165437. i64 iDocid = sqlite3_column_int64(pStmt, 0);
  165438. int iLang = langidFromSelect(p, pStmt);
  165439. int iCol;
  165440. for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
  165441. if( p->abNotindexed[iCol]==0 ){
  165442. const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
  165443. int nText = sqlite3_column_bytes(pStmt, iCol+1);
  165444. sqlite3_tokenizer_cursor *pT = 0;
  165445. rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText,&pT);
  165446. while( rc==SQLITE_OK ){
  165447. char const *zToken; /* Buffer containing token */
  165448. int nToken = 0; /* Number of bytes in token */
  165449. int iDum1 = 0, iDum2 = 0; /* Dummy variables */
  165450. int iPos = 0; /* Position of token in zText */
  165451. rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);
  165452. if( rc==SQLITE_OK ){
  165453. int i;
  165454. cksum2 = cksum2 ^ fts3ChecksumEntry(
  165455. zToken, nToken, iLang, 0, iDocid, iCol, iPos
  165456. );
  165457. for(i=1; i<p->nIndex; i++){
  165458. if( p->aIndex[i].nPrefix<=nToken ){
  165459. cksum2 = cksum2 ^ fts3ChecksumEntry(
  165460. zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos
  165461. );
  165462. }
  165463. }
  165464. }
  165465. }
  165466. if( pT ) pModule->xClose(pT);
  165467. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  165468. }
  165469. }
  165470. }
  165471. sqlite3_finalize(pStmt);
  165472. }
  165473. *pbOk = (cksum1==cksum2);
  165474. return rc;
  165475. }
  165476. /*
  165477. ** Run the integrity-check. If no error occurs and the current contents of
  165478. ** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
  165479. ** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
  165480. **
  165481. ** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite
  165482. ** error code.
  165483. **
  165484. ** The integrity-check works as follows. For each token and indexed token
  165485. ** prefix in the document set, a 64-bit checksum is calculated (by code
  165486. ** in fts3ChecksumEntry()) based on the following:
  165487. **
  165488. ** + The index number (0 for the main index, 1 for the first prefix
  165489. ** index etc.),
  165490. ** + The token (or token prefix) text itself,
  165491. ** + The language-id of the row it appears in,
  165492. ** + The docid of the row it appears in,
  165493. ** + The column it appears in, and
  165494. ** + The tokens position within that column.
  165495. **
  165496. ** The checksums for all entries in the index are XORed together to create
  165497. ** a single checksum for the entire index.
  165498. **
  165499. ** The integrity-check code calculates the same checksum in two ways:
  165500. **
  165501. ** 1. By scanning the contents of the FTS index, and
  165502. ** 2. By scanning and tokenizing the content table.
  165503. **
  165504. ** If the two checksums are identical, the integrity-check is deemed to have
  165505. ** passed.
  165506. */
  165507. static int fts3DoIntegrityCheck(
  165508. Fts3Table *p /* FTS3 table handle */
  165509. ){
  165510. int rc;
  165511. int bOk = 0;
  165512. rc = fts3IntegrityCheck(p, &bOk);
  165513. if( rc==SQLITE_OK && bOk==0 ) rc = FTS_CORRUPT_VTAB;
  165514. return rc;
  165515. }
  165516. /*
  165517. ** Handle a 'special' INSERT of the form:
  165518. **
  165519. ** "INSERT INTO tbl(tbl) VALUES(<expr>)"
  165520. **
  165521. ** Argument pVal contains the result of <expr>. Currently the only
  165522. ** meaningful value to insert is the text 'optimize'.
  165523. */
  165524. static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
  165525. int rc; /* Return Code */
  165526. const char *zVal = (const char *)sqlite3_value_text(pVal);
  165527. int nVal = sqlite3_value_bytes(pVal);
  165528. if( !zVal ){
  165529. return SQLITE_NOMEM;
  165530. }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
  165531. rc = fts3DoOptimize(p, 0);
  165532. }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
  165533. rc = fts3DoRebuild(p);
  165534. }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){
  165535. rc = fts3DoIntegrityCheck(p);
  165536. }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){
  165537. rc = fts3DoIncrmerge(p, &zVal[6]);
  165538. }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
  165539. rc = fts3DoAutoincrmerge(p, &zVal[10]);
  165540. #ifdef SQLITE_TEST
  165541. }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
  165542. p->nNodeSize = atoi(&zVal[9]);
  165543. rc = SQLITE_OK;
  165544. }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
  165545. p->nMaxPendingData = atoi(&zVal[11]);
  165546. rc = SQLITE_OK;
  165547. }else if( nVal>21 && 0==sqlite3_strnicmp(zVal, "test-no-incr-doclist=", 21) ){
  165548. p->bNoIncrDoclist = atoi(&zVal[21]);
  165549. rc = SQLITE_OK;
  165550. #endif
  165551. }else{
  165552. rc = SQLITE_ERROR;
  165553. }
  165554. return rc;
  165555. }
  165556. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  165557. /*
  165558. ** Delete all cached deferred doclists. Deferred doclists are cached
  165559. ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
  165560. */
  165561. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
  165562. Fts3DeferredToken *pDef;
  165563. for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
  165564. fts3PendingListDelete(pDef->pList);
  165565. pDef->pList = 0;
  165566. }
  165567. }
  165568. /*
  165569. ** Free all entries in the pCsr->pDeffered list. Entries are added to
  165570. ** this list using sqlite3Fts3DeferToken().
  165571. */
  165572. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
  165573. Fts3DeferredToken *pDef;
  165574. Fts3DeferredToken *pNext;
  165575. for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
  165576. pNext = pDef->pNext;
  165577. fts3PendingListDelete(pDef->pList);
  165578. sqlite3_free(pDef);
  165579. }
  165580. pCsr->pDeferred = 0;
  165581. }
  165582. /*
  165583. ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
  165584. ** based on the row that pCsr currently points to.
  165585. **
  165586. ** A deferred-doclist is like any other doclist with position information
  165587. ** included, except that it only contains entries for a single row of the
  165588. ** table, not for all rows.
  165589. */
  165590. SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
  165591. int rc = SQLITE_OK; /* Return code */
  165592. if( pCsr->pDeferred ){
  165593. int i; /* Used to iterate through table columns */
  165594. sqlite3_int64 iDocid; /* Docid of the row pCsr points to */
  165595. Fts3DeferredToken *pDef; /* Used to iterate through deferred tokens */
  165596. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  165597. sqlite3_tokenizer *pT = p->pTokenizer;
  165598. sqlite3_tokenizer_module const *pModule = pT->pModule;
  165599. assert( pCsr->isRequireSeek==0 );
  165600. iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
  165601. for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
  165602. if( p->abNotindexed[i]==0 ){
  165603. const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
  165604. sqlite3_tokenizer_cursor *pTC = 0;
  165605. rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
  165606. while( rc==SQLITE_OK ){
  165607. char const *zToken; /* Buffer containing token */
  165608. int nToken = 0; /* Number of bytes in token */
  165609. int iDum1 = 0, iDum2 = 0; /* Dummy variables */
  165610. int iPos = 0; /* Position of token in zText */
  165611. rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
  165612. for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
  165613. Fts3PhraseToken *pPT = pDef->pToken;
  165614. if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
  165615. && (pPT->bFirst==0 || iPos==0)
  165616. && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
  165617. && (0==memcmp(zToken, pPT->z, pPT->n))
  165618. ){
  165619. fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
  165620. }
  165621. }
  165622. }
  165623. if( pTC ) pModule->xClose(pTC);
  165624. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  165625. }
  165626. }
  165627. for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
  165628. if( pDef->pList ){
  165629. rc = fts3PendingListAppendVarint(&pDef->pList, 0);
  165630. }
  165631. }
  165632. }
  165633. return rc;
  165634. }
  165635. SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
  165636. Fts3DeferredToken *p,
  165637. char **ppData,
  165638. int *pnData
  165639. ){
  165640. char *pRet;
  165641. int nSkip;
  165642. sqlite3_int64 dummy;
  165643. *ppData = 0;
  165644. *pnData = 0;
  165645. if( p->pList==0 ){
  165646. return SQLITE_OK;
  165647. }
  165648. pRet = (char *)sqlite3_malloc(p->pList->nData);
  165649. if( !pRet ) return SQLITE_NOMEM;
  165650. nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
  165651. *pnData = p->pList->nData - nSkip;
  165652. *ppData = pRet;
  165653. memcpy(pRet, &p->pList->aData[nSkip], *pnData);
  165654. return SQLITE_OK;
  165655. }
  165656. /*
  165657. ** Add an entry for token pToken to the pCsr->pDeferred list.
  165658. */
  165659. SQLITE_PRIVATE int sqlite3Fts3DeferToken(
  165660. Fts3Cursor *pCsr, /* Fts3 table cursor */
  165661. Fts3PhraseToken *pToken, /* Token to defer */
  165662. int iCol /* Column that token must appear in (or -1) */
  165663. ){
  165664. Fts3DeferredToken *pDeferred;
  165665. pDeferred = sqlite3_malloc(sizeof(*pDeferred));
  165666. if( !pDeferred ){
  165667. return SQLITE_NOMEM;
  165668. }
  165669. memset(pDeferred, 0, sizeof(*pDeferred));
  165670. pDeferred->pToken = pToken;
  165671. pDeferred->pNext = pCsr->pDeferred;
  165672. pDeferred->iCol = iCol;
  165673. pCsr->pDeferred = pDeferred;
  165674. assert( pToken->pDeferred==0 );
  165675. pToken->pDeferred = pDeferred;
  165676. return SQLITE_OK;
  165677. }
  165678. #endif
  165679. /*
  165680. ** SQLite value pRowid contains the rowid of a row that may or may not be
  165681. ** present in the FTS3 table. If it is, delete it and adjust the contents
  165682. ** of subsiduary data structures accordingly.
  165683. */
  165684. static int fts3DeleteByRowid(
  165685. Fts3Table *p,
  165686. sqlite3_value *pRowid,
  165687. int *pnChng, /* IN/OUT: Decrement if row is deleted */
  165688. u32 *aSzDel
  165689. ){
  165690. int rc = SQLITE_OK; /* Return code */
  165691. int bFound = 0; /* True if *pRowid really is in the table */
  165692. fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound);
  165693. if( bFound && rc==SQLITE_OK ){
  165694. int isEmpty = 0; /* Deleting *pRowid leaves the table empty */
  165695. rc = fts3IsEmpty(p, pRowid, &isEmpty);
  165696. if( rc==SQLITE_OK ){
  165697. if( isEmpty ){
  165698. /* Deleting this row means the whole table is empty. In this case
  165699. ** delete the contents of all three tables and throw away any
  165700. ** data in the pendingTerms hash table. */
  165701. rc = fts3DeleteAll(p, 1);
  165702. *pnChng = 0;
  165703. memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2);
  165704. }else{
  165705. *pnChng = *pnChng - 1;
  165706. if( p->zContentTbl==0 ){
  165707. fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
  165708. }
  165709. if( p->bHasDocsize ){
  165710. fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
  165711. }
  165712. }
  165713. }
  165714. }
  165715. return rc;
  165716. }
  165717. /*
  165718. ** This function does the work for the xUpdate method of FTS3 virtual
  165719. ** tables. The schema of the virtual table being:
  165720. **
  165721. ** CREATE TABLE <table name>(
  165722. ** <user columns>,
  165723. ** <table name> HIDDEN,
  165724. ** docid HIDDEN,
  165725. ** <langid> HIDDEN
  165726. ** );
  165727. **
  165728. **
  165729. */
  165730. SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
  165731. sqlite3_vtab *pVtab, /* FTS3 vtab object */
  165732. int nArg, /* Size of argument array */
  165733. sqlite3_value **apVal, /* Array of arguments */
  165734. sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
  165735. ){
  165736. Fts3Table *p = (Fts3Table *)pVtab;
  165737. int rc = SQLITE_OK; /* Return Code */
  165738. u32 *aSzIns = 0; /* Sizes of inserted documents */
  165739. u32 *aSzDel = 0; /* Sizes of deleted documents */
  165740. int nChng = 0; /* Net change in number of documents */
  165741. int bInsertDone = 0;
  165742. /* At this point it must be known if the %_stat table exists or not.
  165743. ** So bHasStat may not be 2. */
  165744. assert( p->bHasStat==0 || p->bHasStat==1 );
  165745. assert( p->pSegments==0 );
  165746. assert(
  165747. nArg==1 /* DELETE operations */
  165748. || nArg==(2 + p->nColumn + 3) /* INSERT or UPDATE operations */
  165749. );
  165750. /* Check for a "special" INSERT operation. One of the form:
  165751. **
  165752. ** INSERT INTO xyz(xyz) VALUES('command');
  165753. */
  165754. if( nArg>1
  165755. && sqlite3_value_type(apVal[0])==SQLITE_NULL
  165756. && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL
  165757. ){
  165758. rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
  165759. goto update_out;
  165760. }
  165761. if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
  165762. rc = SQLITE_CONSTRAINT;
  165763. goto update_out;
  165764. }
  165765. /* Allocate space to hold the change in document sizes */
  165766. aSzDel = sqlite3_malloc64(sizeof(aSzDel[0])*((sqlite3_int64)p->nColumn+1)*2);
  165767. if( aSzDel==0 ){
  165768. rc = SQLITE_NOMEM;
  165769. goto update_out;
  165770. }
  165771. aSzIns = &aSzDel[p->nColumn+1];
  165772. memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
  165773. rc = fts3Writelock(p);
  165774. if( rc!=SQLITE_OK ) goto update_out;
  165775. /* If this is an INSERT operation, or an UPDATE that modifies the rowid
  165776. ** value, then this operation requires constraint handling.
  165777. **
  165778. ** If the on-conflict mode is REPLACE, this means that the existing row
  165779. ** should be deleted from the database before inserting the new row. Or,
  165780. ** if the on-conflict mode is other than REPLACE, then this method must
  165781. ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
  165782. ** modify the database file.
  165783. */
  165784. if( nArg>1 && p->zContentTbl==0 ){
  165785. /* Find the value object that holds the new rowid value. */
  165786. sqlite3_value *pNewRowid = apVal[3+p->nColumn];
  165787. if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
  165788. pNewRowid = apVal[1];
  165789. }
  165790. if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && (
  165791. sqlite3_value_type(apVal[0])==SQLITE_NULL
  165792. || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
  165793. )){
  165794. /* The new rowid is not NULL (in this case the rowid will be
  165795. ** automatically assigned and there is no chance of a conflict), and
  165796. ** the statement is either an INSERT or an UPDATE that modifies the
  165797. ** rowid column. So if the conflict mode is REPLACE, then delete any
  165798. ** existing row with rowid=pNewRowid.
  165799. **
  165800. ** Or, if the conflict mode is not REPLACE, insert the new record into
  165801. ** the %_content table. If we hit the duplicate rowid constraint (or any
  165802. ** other error) while doing so, return immediately.
  165803. **
  165804. ** This branch may also run if pNewRowid contains a value that cannot
  165805. ** be losslessly converted to an integer. In this case, the eventual
  165806. ** call to fts3InsertData() (either just below or further on in this
  165807. ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is
  165808. ** invoked, it will delete zero rows (since no row will have
  165809. ** docid=$pNewRowid if $pNewRowid is not an integer value).
  165810. */
  165811. if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
  165812. rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
  165813. }else{
  165814. rc = fts3InsertData(p, apVal, pRowid);
  165815. bInsertDone = 1;
  165816. }
  165817. }
  165818. }
  165819. if( rc!=SQLITE_OK ){
  165820. goto update_out;
  165821. }
  165822. /* If this is a DELETE or UPDATE operation, remove the old record. */
  165823. if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
  165824. assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
  165825. rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
  165826. }
  165827. /* If this is an INSERT or UPDATE operation, insert the new record. */
  165828. if( nArg>1 && rc==SQLITE_OK ){
  165829. int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
  165830. if( bInsertDone==0 ){
  165831. rc = fts3InsertData(p, apVal, pRowid);
  165832. if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
  165833. rc = FTS_CORRUPT_VTAB;
  165834. }
  165835. }
  165836. if( rc==SQLITE_OK ){
  165837. rc = fts3PendingTermsDocid(p, 0, iLangid, *pRowid);
  165838. }
  165839. if( rc==SQLITE_OK ){
  165840. assert( p->iPrevDocid==*pRowid );
  165841. rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
  165842. }
  165843. if( p->bHasDocsize ){
  165844. fts3InsertDocsize(&rc, p, aSzIns);
  165845. }
  165846. nChng++;
  165847. }
  165848. if( p->bFts4 ){
  165849. fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
  165850. }
  165851. update_out:
  165852. sqlite3_free(aSzDel);
  165853. sqlite3Fts3SegmentsClose(p);
  165854. return rc;
  165855. }
  165856. /*
  165857. ** Flush any data in the pending-terms hash table to disk. If successful,
  165858. ** merge all segments in the database (including the new segment, if
  165859. ** there was any data to flush) into a single segment.
  165860. */
  165861. SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
  165862. int rc;
  165863. rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
  165864. if( rc==SQLITE_OK ){
  165865. rc = fts3DoOptimize(p, 1);
  165866. if( rc==SQLITE_OK || rc==SQLITE_DONE ){
  165867. int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
  165868. if( rc2!=SQLITE_OK ) rc = rc2;
  165869. }else{
  165870. sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
  165871. sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
  165872. }
  165873. }
  165874. sqlite3Fts3SegmentsClose(p);
  165875. return rc;
  165876. }
  165877. #endif
  165878. /************** End of fts3_write.c ******************************************/
  165879. /************** Begin file fts3_snippet.c ************************************/
  165880. /*
  165881. ** 2009 Oct 23
  165882. **
  165883. ** The author disclaims copyright to this source code. In place of
  165884. ** a legal notice, here is a blessing:
  165885. **
  165886. ** May you do good and not evil.
  165887. ** May you find forgiveness for yourself and forgive others.
  165888. ** May you share freely, never taking more than you give.
  165889. **
  165890. ******************************************************************************
  165891. */
  165892. /* #include "fts3Int.h" */
  165893. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  165894. /* #include <string.h> */
  165895. /* #include <assert.h> */
  165896. /*
  165897. ** Characters that may appear in the second argument to matchinfo().
  165898. */
  165899. #define FTS3_MATCHINFO_NPHRASE 'p' /* 1 value */
  165900. #define FTS3_MATCHINFO_NCOL 'c' /* 1 value */
  165901. #define FTS3_MATCHINFO_NDOC 'n' /* 1 value */
  165902. #define FTS3_MATCHINFO_AVGLENGTH 'a' /* nCol values */
  165903. #define FTS3_MATCHINFO_LENGTH 'l' /* nCol values */
  165904. #define FTS3_MATCHINFO_LCS 's' /* nCol values */
  165905. #define FTS3_MATCHINFO_HITS 'x' /* 3*nCol*nPhrase values */
  165906. #define FTS3_MATCHINFO_LHITS 'y' /* nCol*nPhrase values */
  165907. #define FTS3_MATCHINFO_LHITS_BM 'b' /* nCol*nPhrase values */
  165908. /*
  165909. ** The default value for the second argument to matchinfo().
  165910. */
  165911. #define FTS3_MATCHINFO_DEFAULT "pcx"
  165912. /*
  165913. ** Used as an fts3ExprIterate() context when loading phrase doclists to
  165914. ** Fts3Expr.aDoclist[]/nDoclist.
  165915. */
  165916. typedef struct LoadDoclistCtx LoadDoclistCtx;
  165917. struct LoadDoclistCtx {
  165918. Fts3Cursor *pCsr; /* FTS3 Cursor */
  165919. int nPhrase; /* Number of phrases seen so far */
  165920. int nToken; /* Number of tokens seen so far */
  165921. };
  165922. /*
  165923. ** The following types are used as part of the implementation of the
  165924. ** fts3BestSnippet() routine.
  165925. */
  165926. typedef struct SnippetIter SnippetIter;
  165927. typedef struct SnippetPhrase SnippetPhrase;
  165928. typedef struct SnippetFragment SnippetFragment;
  165929. struct SnippetIter {
  165930. Fts3Cursor *pCsr; /* Cursor snippet is being generated from */
  165931. int iCol; /* Extract snippet from this column */
  165932. int nSnippet; /* Requested snippet length (in tokens) */
  165933. int nPhrase; /* Number of phrases in query */
  165934. SnippetPhrase *aPhrase; /* Array of size nPhrase */
  165935. int iCurrent; /* First token of current snippet */
  165936. };
  165937. struct SnippetPhrase {
  165938. int nToken; /* Number of tokens in phrase */
  165939. char *pList; /* Pointer to start of phrase position list */
  165940. int iHead; /* Next value in position list */
  165941. char *pHead; /* Position list data following iHead */
  165942. int iTail; /* Next value in trailing position list */
  165943. char *pTail; /* Position list data following iTail */
  165944. };
  165945. struct SnippetFragment {
  165946. int iCol; /* Column snippet is extracted from */
  165947. int iPos; /* Index of first token in snippet */
  165948. u64 covered; /* Mask of query phrases covered */
  165949. u64 hlmask; /* Mask of snippet terms to highlight */
  165950. };
  165951. /*
  165952. ** This type is used as an fts3ExprIterate() context object while
  165953. ** accumulating the data returned by the matchinfo() function.
  165954. */
  165955. typedef struct MatchInfo MatchInfo;
  165956. struct MatchInfo {
  165957. Fts3Cursor *pCursor; /* FTS3 Cursor */
  165958. int nCol; /* Number of columns in table */
  165959. int nPhrase; /* Number of matchable phrases in query */
  165960. sqlite3_int64 nDoc; /* Number of docs in database */
  165961. char flag;
  165962. u32 *aMatchinfo; /* Pre-allocated buffer */
  165963. };
  165964. /*
  165965. ** An instance of this structure is used to manage a pair of buffers, each
  165966. ** (nElem * sizeof(u32)) bytes in size. See the MatchinfoBuffer code below
  165967. ** for details.
  165968. */
  165969. struct MatchinfoBuffer {
  165970. u8 aRef[3];
  165971. int nElem;
  165972. int bGlobal; /* Set if global data is loaded */
  165973. char *zMatchinfo;
  165974. u32 aMatchinfo[1];
  165975. };
  165976. /*
  165977. ** The snippet() and offsets() functions both return text values. An instance
  165978. ** of the following structure is used to accumulate those values while the
  165979. ** functions are running. See fts3StringAppend() for details.
  165980. */
  165981. typedef struct StrBuffer StrBuffer;
  165982. struct StrBuffer {
  165983. char *z; /* Pointer to buffer containing string */
  165984. int n; /* Length of z in bytes (excl. nul-term) */
  165985. int nAlloc; /* Allocated size of buffer z in bytes */
  165986. };
  165987. /*************************************************************************
  165988. ** Start of MatchinfoBuffer code.
  165989. */
  165990. /*
  165991. ** Allocate a two-slot MatchinfoBuffer object.
  165992. */
  165993. static MatchinfoBuffer *fts3MIBufferNew(size_t nElem, const char *zMatchinfo){
  165994. MatchinfoBuffer *pRet;
  165995. sqlite3_int64 nByte = sizeof(u32) * (2*(sqlite3_int64)nElem + 1)
  165996. + sizeof(MatchinfoBuffer);
  165997. sqlite3_int64 nStr = strlen(zMatchinfo);
  165998. pRet = sqlite3_malloc64(nByte + nStr+1);
  165999. if( pRet ){
  166000. memset(pRet, 0, nByte);
  166001. pRet->aMatchinfo[0] = (u8*)(&pRet->aMatchinfo[1]) - (u8*)pRet;
  166002. pRet->aMatchinfo[1+nElem] = pRet->aMatchinfo[0]
  166003. + sizeof(u32)*((int)nElem+1);
  166004. pRet->nElem = (int)nElem;
  166005. pRet->zMatchinfo = ((char*)pRet) + nByte;
  166006. memcpy(pRet->zMatchinfo, zMatchinfo, nStr+1);
  166007. pRet->aRef[0] = 1;
  166008. }
  166009. return pRet;
  166010. }
  166011. static void fts3MIBufferFree(void *p){
  166012. MatchinfoBuffer *pBuf = (MatchinfoBuffer*)((u8*)p - ((u32*)p)[-1]);
  166013. assert( (u32*)p==&pBuf->aMatchinfo[1]
  166014. || (u32*)p==&pBuf->aMatchinfo[pBuf->nElem+2]
  166015. );
  166016. if( (u32*)p==&pBuf->aMatchinfo[1] ){
  166017. pBuf->aRef[1] = 0;
  166018. }else{
  166019. pBuf->aRef[2] = 0;
  166020. }
  166021. if( pBuf->aRef[0]==0 && pBuf->aRef[1]==0 && pBuf->aRef[2]==0 ){
  166022. sqlite3_free(pBuf);
  166023. }
  166024. }
  166025. static void (*fts3MIBufferAlloc(MatchinfoBuffer *p, u32 **paOut))(void*){
  166026. void (*xRet)(void*) = 0;
  166027. u32 *aOut = 0;
  166028. if( p->aRef[1]==0 ){
  166029. p->aRef[1] = 1;
  166030. aOut = &p->aMatchinfo[1];
  166031. xRet = fts3MIBufferFree;
  166032. }
  166033. else if( p->aRef[2]==0 ){
  166034. p->aRef[2] = 1;
  166035. aOut = &p->aMatchinfo[p->nElem+2];
  166036. xRet = fts3MIBufferFree;
  166037. }else{
  166038. aOut = (u32*)sqlite3_malloc64(p->nElem * sizeof(u32));
  166039. if( aOut ){
  166040. xRet = sqlite3_free;
  166041. if( p->bGlobal ) memcpy(aOut, &p->aMatchinfo[1], p->nElem*sizeof(u32));
  166042. }
  166043. }
  166044. *paOut = aOut;
  166045. return xRet;
  166046. }
  166047. static void fts3MIBufferSetGlobal(MatchinfoBuffer *p){
  166048. p->bGlobal = 1;
  166049. memcpy(&p->aMatchinfo[2+p->nElem], &p->aMatchinfo[1], p->nElem*sizeof(u32));
  166050. }
  166051. /*
  166052. ** Free a MatchinfoBuffer object allocated using fts3MIBufferNew()
  166053. */
  166054. SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p){
  166055. if( p ){
  166056. assert( p->aRef[0]==1 );
  166057. p->aRef[0] = 0;
  166058. if( p->aRef[0]==0 && p->aRef[1]==0 && p->aRef[2]==0 ){
  166059. sqlite3_free(p);
  166060. }
  166061. }
  166062. }
  166063. /*
  166064. ** End of MatchinfoBuffer code.
  166065. *************************************************************************/
  166066. /*
  166067. ** This function is used to help iterate through a position-list. A position
  166068. ** list is a list of unique integers, sorted from smallest to largest. Each
  166069. ** element of the list is represented by an FTS3 varint that takes the value
  166070. ** of the difference between the current element and the previous one plus
  166071. ** two. For example, to store the position-list:
  166072. **
  166073. ** 4 9 113
  166074. **
  166075. ** the three varints:
  166076. **
  166077. ** 6 7 106
  166078. **
  166079. ** are encoded.
  166080. **
  166081. ** When this function is called, *pp points to the start of an element of
  166082. ** the list. *piPos contains the value of the previous entry in the list.
  166083. ** After it returns, *piPos contains the value of the next element of the
  166084. ** list and *pp is advanced to the following varint.
  166085. */
  166086. static void fts3GetDeltaPosition(char **pp, int *piPos){
  166087. int iVal;
  166088. *pp += fts3GetVarint32(*pp, &iVal);
  166089. *piPos += (iVal-2);
  166090. }
  166091. /*
  166092. ** Helper function for fts3ExprIterate() (see below).
  166093. */
  166094. static int fts3ExprIterate2(
  166095. Fts3Expr *pExpr, /* Expression to iterate phrases of */
  166096. int *piPhrase, /* Pointer to phrase counter */
  166097. int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
  166098. void *pCtx /* Second argument to pass to callback */
  166099. ){
  166100. int rc; /* Return code */
  166101. int eType = pExpr->eType; /* Type of expression node pExpr */
  166102. if( eType!=FTSQUERY_PHRASE ){
  166103. assert( pExpr->pLeft && pExpr->pRight );
  166104. rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
  166105. if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
  166106. rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
  166107. }
  166108. }else{
  166109. rc = x(pExpr, *piPhrase, pCtx);
  166110. (*piPhrase)++;
  166111. }
  166112. return rc;
  166113. }
  166114. /*
  166115. ** Iterate through all phrase nodes in an FTS3 query, except those that
  166116. ** are part of a sub-tree that is the right-hand-side of a NOT operator.
  166117. ** For each phrase node found, the supplied callback function is invoked.
  166118. **
  166119. ** If the callback function returns anything other than SQLITE_OK,
  166120. ** the iteration is abandoned and the error code returned immediately.
  166121. ** Otherwise, SQLITE_OK is returned after a callback has been made for
  166122. ** all eligible phrase nodes.
  166123. */
  166124. static int fts3ExprIterate(
  166125. Fts3Expr *pExpr, /* Expression to iterate phrases of */
  166126. int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
  166127. void *pCtx /* Second argument to pass to callback */
  166128. ){
  166129. int iPhrase = 0; /* Variable used as the phrase counter */
  166130. return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
  166131. }
  166132. /*
  166133. ** This is an fts3ExprIterate() callback used while loading the doclists
  166134. ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
  166135. ** fts3ExprLoadDoclists().
  166136. */
  166137. static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
  166138. int rc = SQLITE_OK;
  166139. Fts3Phrase *pPhrase = pExpr->pPhrase;
  166140. LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
  166141. UNUSED_PARAMETER(iPhrase);
  166142. p->nPhrase++;
  166143. p->nToken += pPhrase->nToken;
  166144. return rc;
  166145. }
  166146. /*
  166147. ** Load the doclists for each phrase in the query associated with FTS3 cursor
  166148. ** pCsr.
  166149. **
  166150. ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
  166151. ** phrases in the expression (all phrases except those directly or
  166152. ** indirectly descended from the right-hand-side of a NOT operator). If
  166153. ** pnToken is not NULL, then it is set to the number of tokens in all
  166154. ** matchable phrases of the expression.
  166155. */
  166156. static int fts3ExprLoadDoclists(
  166157. Fts3Cursor *pCsr, /* Fts3 cursor for current query */
  166158. int *pnPhrase, /* OUT: Number of phrases in query */
  166159. int *pnToken /* OUT: Number of tokens in query */
  166160. ){
  166161. int rc; /* Return Code */
  166162. LoadDoclistCtx sCtx = {0,0,0}; /* Context for fts3ExprIterate() */
  166163. sCtx.pCsr = pCsr;
  166164. rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
  166165. if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
  166166. if( pnToken ) *pnToken = sCtx.nToken;
  166167. return rc;
  166168. }
  166169. static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
  166170. (*(int *)ctx)++;
  166171. pExpr->iPhrase = iPhrase;
  166172. return SQLITE_OK;
  166173. }
  166174. static int fts3ExprPhraseCount(Fts3Expr *pExpr){
  166175. int nPhrase = 0;
  166176. (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
  166177. return nPhrase;
  166178. }
  166179. /*
  166180. ** Advance the position list iterator specified by the first two
  166181. ** arguments so that it points to the first element with a value greater
  166182. ** than or equal to parameter iNext.
  166183. */
  166184. static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
  166185. char *pIter = *ppIter;
  166186. if( pIter ){
  166187. int iIter = *piIter;
  166188. while( iIter<iNext ){
  166189. if( 0==(*pIter & 0xFE) ){
  166190. iIter = -1;
  166191. pIter = 0;
  166192. break;
  166193. }
  166194. fts3GetDeltaPosition(&pIter, &iIter);
  166195. }
  166196. *piIter = iIter;
  166197. *ppIter = pIter;
  166198. }
  166199. }
  166200. /*
  166201. ** Advance the snippet iterator to the next candidate snippet.
  166202. */
  166203. static int fts3SnippetNextCandidate(SnippetIter *pIter){
  166204. int i; /* Loop counter */
  166205. if( pIter->iCurrent<0 ){
  166206. /* The SnippetIter object has just been initialized. The first snippet
  166207. ** candidate always starts at offset 0 (even if this candidate has a
  166208. ** score of 0.0).
  166209. */
  166210. pIter->iCurrent = 0;
  166211. /* Advance the 'head' iterator of each phrase to the first offset that
  166212. ** is greater than or equal to (iNext+nSnippet).
  166213. */
  166214. for(i=0; i<pIter->nPhrase; i++){
  166215. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  166216. fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
  166217. }
  166218. }else{
  166219. int iStart;
  166220. int iEnd = 0x7FFFFFFF;
  166221. for(i=0; i<pIter->nPhrase; i++){
  166222. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  166223. if( pPhrase->pHead && pPhrase->iHead<iEnd ){
  166224. iEnd = pPhrase->iHead;
  166225. }
  166226. }
  166227. if( iEnd==0x7FFFFFFF ){
  166228. return 1;
  166229. }
  166230. pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
  166231. for(i=0; i<pIter->nPhrase; i++){
  166232. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  166233. fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
  166234. fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
  166235. }
  166236. }
  166237. return 0;
  166238. }
  166239. /*
  166240. ** Retrieve information about the current candidate snippet of snippet
  166241. ** iterator pIter.
  166242. */
  166243. static void fts3SnippetDetails(
  166244. SnippetIter *pIter, /* Snippet iterator */
  166245. u64 mCovered, /* Bitmask of phrases already covered */
  166246. int *piToken, /* OUT: First token of proposed snippet */
  166247. int *piScore, /* OUT: "Score" for this snippet */
  166248. u64 *pmCover, /* OUT: Bitmask of phrases covered */
  166249. u64 *pmHighlight /* OUT: Bitmask of terms to highlight */
  166250. ){
  166251. int iStart = pIter->iCurrent; /* First token of snippet */
  166252. int iScore = 0; /* Score of this snippet */
  166253. int i; /* Loop counter */
  166254. u64 mCover = 0; /* Mask of phrases covered by this snippet */
  166255. u64 mHighlight = 0; /* Mask of tokens to highlight in snippet */
  166256. for(i=0; i<pIter->nPhrase; i++){
  166257. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  166258. if( pPhrase->pTail ){
  166259. char *pCsr = pPhrase->pTail;
  166260. int iCsr = pPhrase->iTail;
  166261. while( iCsr<(iStart+pIter->nSnippet) && iCsr>=iStart ){
  166262. int j;
  166263. u64 mPhrase = (u64)1 << i;
  166264. u64 mPos = (u64)1 << (iCsr - iStart);
  166265. assert( iCsr>=iStart && (iCsr - iStart)<=64 );
  166266. assert( i>=0 && i<=64 );
  166267. if( (mCover|mCovered)&mPhrase ){
  166268. iScore++;
  166269. }else{
  166270. iScore += 1000;
  166271. }
  166272. mCover |= mPhrase;
  166273. for(j=0; j<pPhrase->nToken; j++){
  166274. mHighlight |= (mPos>>j);
  166275. }
  166276. if( 0==(*pCsr & 0x0FE) ) break;
  166277. fts3GetDeltaPosition(&pCsr, &iCsr);
  166278. }
  166279. }
  166280. }
  166281. /* Set the output variables before returning. */
  166282. *piToken = iStart;
  166283. *piScore = iScore;
  166284. *pmCover = mCover;
  166285. *pmHighlight = mHighlight;
  166286. }
  166287. /*
  166288. ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
  166289. ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
  166290. */
  166291. static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
  166292. SnippetIter *p = (SnippetIter *)ctx;
  166293. SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
  166294. char *pCsr;
  166295. int rc;
  166296. pPhrase->nToken = pExpr->pPhrase->nToken;
  166297. rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr);
  166298. assert( rc==SQLITE_OK || pCsr==0 );
  166299. if( pCsr ){
  166300. int iFirst = 0;
  166301. pPhrase->pList = pCsr;
  166302. fts3GetDeltaPosition(&pCsr, &iFirst);
  166303. if( iFirst<0 ){
  166304. rc = FTS_CORRUPT_VTAB;
  166305. }else{
  166306. pPhrase->pHead = pCsr;
  166307. pPhrase->pTail = pCsr;
  166308. pPhrase->iHead = iFirst;
  166309. pPhrase->iTail = iFirst;
  166310. }
  166311. }else{
  166312. assert( rc!=SQLITE_OK || (
  166313. pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0
  166314. ));
  166315. }
  166316. return rc;
  166317. }
  166318. /*
  166319. ** Select the fragment of text consisting of nFragment contiguous tokens
  166320. ** from column iCol that represent the "best" snippet. The best snippet
  166321. ** is the snippet with the highest score, where scores are calculated
  166322. ** by adding:
  166323. **
  166324. ** (a) +1 point for each occurrence of a matchable phrase in the snippet.
  166325. **
  166326. ** (b) +1000 points for the first occurrence of each matchable phrase in
  166327. ** the snippet for which the corresponding mCovered bit is not set.
  166328. **
  166329. ** The selected snippet parameters are stored in structure *pFragment before
  166330. ** returning. The score of the selected snippet is stored in *piScore
  166331. ** before returning.
  166332. */
  166333. static int fts3BestSnippet(
  166334. int nSnippet, /* Desired snippet length */
  166335. Fts3Cursor *pCsr, /* Cursor to create snippet for */
  166336. int iCol, /* Index of column to create snippet from */
  166337. u64 mCovered, /* Mask of phrases already covered */
  166338. u64 *pmSeen, /* IN/OUT: Mask of phrases seen */
  166339. SnippetFragment *pFragment, /* OUT: Best snippet found */
  166340. int *piScore /* OUT: Score of snippet pFragment */
  166341. ){
  166342. int rc; /* Return Code */
  166343. int nList; /* Number of phrases in expression */
  166344. SnippetIter sIter; /* Iterates through snippet candidates */
  166345. sqlite3_int64 nByte; /* Number of bytes of space to allocate */
  166346. int iBestScore = -1; /* Best snippet score found so far */
  166347. int i; /* Loop counter */
  166348. memset(&sIter, 0, sizeof(sIter));
  166349. /* Iterate through the phrases in the expression to count them. The same
  166350. ** callback makes sure the doclists are loaded for each phrase.
  166351. */
  166352. rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
  166353. if( rc!=SQLITE_OK ){
  166354. return rc;
  166355. }
  166356. /* Now that it is known how many phrases there are, allocate and zero
  166357. ** the required space using malloc().
  166358. */
  166359. nByte = sizeof(SnippetPhrase) * nList;
  166360. sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc64(nByte);
  166361. if( !sIter.aPhrase ){
  166362. return SQLITE_NOMEM;
  166363. }
  166364. memset(sIter.aPhrase, 0, nByte);
  166365. /* Initialize the contents of the SnippetIter object. Then iterate through
  166366. ** the set of phrases in the expression to populate the aPhrase[] array.
  166367. */
  166368. sIter.pCsr = pCsr;
  166369. sIter.iCol = iCol;
  166370. sIter.nSnippet = nSnippet;
  166371. sIter.nPhrase = nList;
  166372. sIter.iCurrent = -1;
  166373. rc = fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void*)&sIter);
  166374. if( rc==SQLITE_OK ){
  166375. /* Set the *pmSeen output variable. */
  166376. for(i=0; i<nList; i++){
  166377. if( sIter.aPhrase[i].pHead ){
  166378. *pmSeen |= (u64)1 << i;
  166379. }
  166380. }
  166381. /* Loop through all candidate snippets. Store the best snippet in
  166382. ** *pFragment. Store its associated 'score' in iBestScore.
  166383. */
  166384. pFragment->iCol = iCol;
  166385. while( !fts3SnippetNextCandidate(&sIter) ){
  166386. int iPos;
  166387. int iScore;
  166388. u64 mCover;
  166389. u64 mHighlite;
  166390. fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover,&mHighlite);
  166391. assert( iScore>=0 );
  166392. if( iScore>iBestScore ){
  166393. pFragment->iPos = iPos;
  166394. pFragment->hlmask = mHighlite;
  166395. pFragment->covered = mCover;
  166396. iBestScore = iScore;
  166397. }
  166398. }
  166399. *piScore = iBestScore;
  166400. }
  166401. sqlite3_free(sIter.aPhrase);
  166402. return rc;
  166403. }
  166404. /*
  166405. ** Append a string to the string-buffer passed as the first argument.
  166406. **
  166407. ** If nAppend is negative, then the length of the string zAppend is
  166408. ** determined using strlen().
  166409. */
  166410. static int fts3StringAppend(
  166411. StrBuffer *pStr, /* Buffer to append to */
  166412. const char *zAppend, /* Pointer to data to append to buffer */
  166413. int nAppend /* Size of zAppend in bytes (or -1) */
  166414. ){
  166415. if( nAppend<0 ){
  166416. nAppend = (int)strlen(zAppend);
  166417. }
  166418. /* If there is insufficient space allocated at StrBuffer.z, use realloc()
  166419. ** to grow the buffer until so that it is big enough to accomadate the
  166420. ** appended data.
  166421. */
  166422. if( pStr->n+nAppend+1>=pStr->nAlloc ){
  166423. sqlite3_int64 nAlloc = pStr->nAlloc+(sqlite3_int64)nAppend+100;
  166424. char *zNew = sqlite3_realloc64(pStr->z, nAlloc);
  166425. if( !zNew ){
  166426. return SQLITE_NOMEM;
  166427. }
  166428. pStr->z = zNew;
  166429. pStr->nAlloc = nAlloc;
  166430. }
  166431. assert( pStr->z!=0 && (pStr->nAlloc >= pStr->n+nAppend+1) );
  166432. /* Append the data to the string buffer. */
  166433. memcpy(&pStr->z[pStr->n], zAppend, nAppend);
  166434. pStr->n += nAppend;
  166435. pStr->z[pStr->n] = '\0';
  166436. return SQLITE_OK;
  166437. }
  166438. /*
  166439. ** The fts3BestSnippet() function often selects snippets that end with a
  166440. ** query term. That is, the final term of the snippet is always a term
  166441. ** that requires highlighting. For example, if 'X' is a highlighted term
  166442. ** and '.' is a non-highlighted term, BestSnippet() may select:
  166443. **
  166444. ** ........X.....X
  166445. **
  166446. ** This function "shifts" the beginning of the snippet forward in the
  166447. ** document so that there are approximately the same number of
  166448. ** non-highlighted terms to the right of the final highlighted term as there
  166449. ** are to the left of the first highlighted term. For example, to this:
  166450. **
  166451. ** ....X.....X....
  166452. **
  166453. ** This is done as part of extracting the snippet text, not when selecting
  166454. ** the snippet. Snippet selection is done based on doclists only, so there
  166455. ** is no way for fts3BestSnippet() to know whether or not the document
  166456. ** actually contains terms that follow the final highlighted term.
  166457. */
  166458. static int fts3SnippetShift(
  166459. Fts3Table *pTab, /* FTS3 table snippet comes from */
  166460. int iLangid, /* Language id to use in tokenizing */
  166461. int nSnippet, /* Number of tokens desired for snippet */
  166462. const char *zDoc, /* Document text to extract snippet from */
  166463. int nDoc, /* Size of buffer zDoc in bytes */
  166464. int *piPos, /* IN/OUT: First token of snippet */
  166465. u64 *pHlmask /* IN/OUT: Mask of tokens to highlight */
  166466. ){
  166467. u64 hlmask = *pHlmask; /* Local copy of initial highlight-mask */
  166468. if( hlmask ){
  166469. int nLeft; /* Tokens to the left of first highlight */
  166470. int nRight; /* Tokens to the right of last highlight */
  166471. int nDesired; /* Ideal number of tokens to shift forward */
  166472. for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
  166473. for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
  166474. assert( (nSnippet-1-nRight)<=63 && (nSnippet-1-nRight)>=0 );
  166475. nDesired = (nLeft-nRight)/2;
  166476. /* Ideally, the start of the snippet should be pushed forward in the
  166477. ** document nDesired tokens. This block checks if there are actually
  166478. ** nDesired tokens to the right of the snippet. If so, *piPos and
  166479. ** *pHlMask are updated to shift the snippet nDesired tokens to the
  166480. ** right. Otherwise, the snippet is shifted by the number of tokens
  166481. ** available.
  166482. */
  166483. if( nDesired>0 ){
  166484. int nShift; /* Number of tokens to shift snippet by */
  166485. int iCurrent = 0; /* Token counter */
  166486. int rc; /* Return Code */
  166487. sqlite3_tokenizer_module *pMod;
  166488. sqlite3_tokenizer_cursor *pC;
  166489. pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
  166490. /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
  166491. ** or more tokens in zDoc/nDoc.
  166492. */
  166493. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
  166494. if( rc!=SQLITE_OK ){
  166495. return rc;
  166496. }
  166497. while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
  166498. const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0;
  166499. rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
  166500. }
  166501. pMod->xClose(pC);
  166502. if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
  166503. nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
  166504. assert( nShift<=nDesired );
  166505. if( nShift>0 ){
  166506. *piPos += nShift;
  166507. *pHlmask = hlmask >> nShift;
  166508. }
  166509. }
  166510. }
  166511. return SQLITE_OK;
  166512. }
  166513. /*
  166514. ** Extract the snippet text for fragment pFragment from cursor pCsr and
  166515. ** append it to string buffer pOut.
  166516. */
  166517. static int fts3SnippetText(
  166518. Fts3Cursor *pCsr, /* FTS3 Cursor */
  166519. SnippetFragment *pFragment, /* Snippet to extract */
  166520. int iFragment, /* Fragment number */
  166521. int isLast, /* True for final fragment in snippet */
  166522. int nSnippet, /* Number of tokens in extracted snippet */
  166523. const char *zOpen, /* String inserted before highlighted term */
  166524. const char *zClose, /* String inserted after highlighted term */
  166525. const char *zEllipsis, /* String inserted between snippets */
  166526. StrBuffer *pOut /* Write output here */
  166527. ){
  166528. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  166529. int rc; /* Return code */
  166530. const char *zDoc; /* Document text to extract snippet from */
  166531. int nDoc; /* Size of zDoc in bytes */
  166532. int iCurrent = 0; /* Current token number of document */
  166533. int iEnd = 0; /* Byte offset of end of current token */
  166534. int isShiftDone = 0; /* True after snippet is shifted */
  166535. int iPos = pFragment->iPos; /* First token of snippet */
  166536. u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
  166537. int iCol = pFragment->iCol+1; /* Query column to extract text from */
  166538. sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
  166539. sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor open on zDoc/nDoc */
  166540. zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
  166541. if( zDoc==0 ){
  166542. if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
  166543. return SQLITE_NOMEM;
  166544. }
  166545. return SQLITE_OK;
  166546. }
  166547. nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
  166548. /* Open a token cursor on the document. */
  166549. pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
  166550. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
  166551. if( rc!=SQLITE_OK ){
  166552. return rc;
  166553. }
  166554. while( rc==SQLITE_OK ){
  166555. const char *ZDUMMY; /* Dummy argument used with tokenizer */
  166556. int DUMMY1 = -1; /* Dummy argument used with tokenizer */
  166557. int iBegin = 0; /* Offset in zDoc of start of token */
  166558. int iFin = 0; /* Offset in zDoc of end of token */
  166559. int isHighlight = 0; /* True for highlighted terms */
  166560. /* Variable DUMMY1 is initialized to a negative value above. Elsewhere
  166561. ** in the FTS code the variable that the third argument to xNext points to
  166562. ** is initialized to zero before the first (*but not necessarily
  166563. ** subsequent*) call to xNext(). This is done for a particular application
  166564. ** that needs to know whether or not the tokenizer is being used for
  166565. ** snippet generation or for some other purpose.
  166566. **
  166567. ** Extreme care is required when writing code to depend on this
  166568. ** initialization. It is not a documented part of the tokenizer interface.
  166569. ** If a tokenizer is used directly by any code outside of FTS, this
  166570. ** convention might not be respected. */
  166571. rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
  166572. if( rc!=SQLITE_OK ){
  166573. if( rc==SQLITE_DONE ){
  166574. /* Special case - the last token of the snippet is also the last token
  166575. ** of the column. Append any punctuation that occurred between the end
  166576. ** of the previous token and the end of the document to the output.
  166577. ** Then break out of the loop. */
  166578. rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
  166579. }
  166580. break;
  166581. }
  166582. if( iCurrent<iPos ){ continue; }
  166583. if( !isShiftDone ){
  166584. int n = nDoc - iBegin;
  166585. rc = fts3SnippetShift(
  166586. pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
  166587. );
  166588. isShiftDone = 1;
  166589. /* Now that the shift has been done, check if the initial "..." are
  166590. ** required. They are required if (a) this is not the first fragment,
  166591. ** or (b) this fragment does not begin at position 0 of its column.
  166592. */
  166593. if( rc==SQLITE_OK ){
  166594. if( iPos>0 || iFragment>0 ){
  166595. rc = fts3StringAppend(pOut, zEllipsis, -1);
  166596. }else if( iBegin ){
  166597. rc = fts3StringAppend(pOut, zDoc, iBegin);
  166598. }
  166599. }
  166600. if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
  166601. }
  166602. if( iCurrent>=(iPos+nSnippet) ){
  166603. if( isLast ){
  166604. rc = fts3StringAppend(pOut, zEllipsis, -1);
  166605. }
  166606. break;
  166607. }
  166608. /* Set isHighlight to true if this term should be highlighted. */
  166609. isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
  166610. if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
  166611. if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
  166612. if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
  166613. if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
  166614. iEnd = iFin;
  166615. }
  166616. pMod->xClose(pC);
  166617. return rc;
  166618. }
  166619. /*
  166620. ** This function is used to count the entries in a column-list (a
  166621. ** delta-encoded list of term offsets within a single column of a single
  166622. ** row). When this function is called, *ppCollist should point to the
  166623. ** beginning of the first varint in the column-list (the varint that
  166624. ** contains the position of the first matching term in the column data).
  166625. ** Before returning, *ppCollist is set to point to the first byte after
  166626. ** the last varint in the column-list (either the 0x00 signifying the end
  166627. ** of the position-list, or the 0x01 that precedes the column number of
  166628. ** the next column in the position-list).
  166629. **
  166630. ** The number of elements in the column-list is returned.
  166631. */
  166632. static int fts3ColumnlistCount(char **ppCollist){
  166633. char *pEnd = *ppCollist;
  166634. char c = 0;
  166635. int nEntry = 0;
  166636. /* A column-list is terminated by either a 0x01 or 0x00. */
  166637. while( 0xFE & (*pEnd | c) ){
  166638. c = *pEnd++ & 0x80;
  166639. if( !c ) nEntry++;
  166640. }
  166641. *ppCollist = pEnd;
  166642. return nEntry;
  166643. }
  166644. /*
  166645. ** This function gathers 'y' or 'b' data for a single phrase.
  166646. */
  166647. static int fts3ExprLHits(
  166648. Fts3Expr *pExpr, /* Phrase expression node */
  166649. MatchInfo *p /* Matchinfo context */
  166650. ){
  166651. Fts3Table *pTab = (Fts3Table *)p->pCursor->base.pVtab;
  166652. int iStart;
  166653. Fts3Phrase *pPhrase = pExpr->pPhrase;
  166654. char *pIter = pPhrase->doclist.pList;
  166655. int iCol = 0;
  166656. assert( p->flag==FTS3_MATCHINFO_LHITS_BM || p->flag==FTS3_MATCHINFO_LHITS );
  166657. if( p->flag==FTS3_MATCHINFO_LHITS ){
  166658. iStart = pExpr->iPhrase * p->nCol;
  166659. }else{
  166660. iStart = pExpr->iPhrase * ((p->nCol + 31) / 32);
  166661. }
  166662. while( 1 ){
  166663. int nHit = fts3ColumnlistCount(&pIter);
  166664. if( (pPhrase->iColumn>=pTab->nColumn || pPhrase->iColumn==iCol) ){
  166665. if( p->flag==FTS3_MATCHINFO_LHITS ){
  166666. p->aMatchinfo[iStart + iCol] = (u32)nHit;
  166667. }else if( nHit ){
  166668. p->aMatchinfo[iStart + (iCol+1)/32] |= (1 << (iCol&0x1F));
  166669. }
  166670. }
  166671. assert( *pIter==0x00 || *pIter==0x01 );
  166672. if( *pIter!=0x01 ) break;
  166673. pIter++;
  166674. pIter += fts3GetVarint32(pIter, &iCol);
  166675. if( iCol>=p->nCol ) return FTS_CORRUPT_VTAB;
  166676. }
  166677. return SQLITE_OK;
  166678. }
  166679. /*
  166680. ** Gather the results for matchinfo directives 'y' and 'b'.
  166681. */
  166682. static int fts3ExprLHitGather(
  166683. Fts3Expr *pExpr,
  166684. MatchInfo *p
  166685. ){
  166686. int rc = SQLITE_OK;
  166687. assert( (pExpr->pLeft==0)==(pExpr->pRight==0) );
  166688. if( pExpr->bEof==0 && pExpr->iDocid==p->pCursor->iPrevId ){
  166689. if( pExpr->pLeft ){
  166690. rc = fts3ExprLHitGather(pExpr->pLeft, p);
  166691. if( rc==SQLITE_OK ) rc = fts3ExprLHitGather(pExpr->pRight, p);
  166692. }else{
  166693. rc = fts3ExprLHits(pExpr, p);
  166694. }
  166695. }
  166696. return rc;
  166697. }
  166698. /*
  166699. ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
  166700. ** for a single query.
  166701. **
  166702. ** fts3ExprIterate() callback to load the 'global' elements of a
  166703. ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements
  166704. ** of the matchinfo array that are constant for all rows returned by the
  166705. ** current query.
  166706. **
  166707. ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
  166708. ** function populates Matchinfo.aMatchinfo[] as follows:
  166709. **
  166710. ** for(iCol=0; iCol<nCol; iCol++){
  166711. ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
  166712. ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
  166713. ** }
  166714. **
  166715. ** where X is the number of matches for phrase iPhrase is column iCol of all
  166716. ** rows of the table. Y is the number of rows for which column iCol contains
  166717. ** at least one instance of phrase iPhrase.
  166718. **
  166719. ** If the phrase pExpr consists entirely of deferred tokens, then all X and
  166720. ** Y values are set to nDoc, where nDoc is the number of documents in the
  166721. ** file system. This is done because the full-text index doclist is required
  166722. ** to calculate these values properly, and the full-text index doclist is
  166723. ** not available for deferred tokens.
  166724. */
  166725. static int fts3ExprGlobalHitsCb(
  166726. Fts3Expr *pExpr, /* Phrase expression node */
  166727. int iPhrase, /* Phrase number (numbered from zero) */
  166728. void *pCtx /* Pointer to MatchInfo structure */
  166729. ){
  166730. MatchInfo *p = (MatchInfo *)pCtx;
  166731. return sqlite3Fts3EvalPhraseStats(
  166732. p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
  166733. );
  166734. }
  166735. /*
  166736. ** fts3ExprIterate() callback used to collect the "local" part of the
  166737. ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the
  166738. ** array that are different for each row returned by the query.
  166739. */
  166740. static int fts3ExprLocalHitsCb(
  166741. Fts3Expr *pExpr, /* Phrase expression node */
  166742. int iPhrase, /* Phrase number */
  166743. void *pCtx /* Pointer to MatchInfo structure */
  166744. ){
  166745. int rc = SQLITE_OK;
  166746. MatchInfo *p = (MatchInfo *)pCtx;
  166747. int iStart = iPhrase * p->nCol * 3;
  166748. int i;
  166749. for(i=0; i<p->nCol && rc==SQLITE_OK; i++){
  166750. char *pCsr;
  166751. rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr);
  166752. if( pCsr ){
  166753. p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
  166754. }else{
  166755. p->aMatchinfo[iStart+i*3] = 0;
  166756. }
  166757. }
  166758. return rc;
  166759. }
  166760. static int fts3MatchinfoCheck(
  166761. Fts3Table *pTab,
  166762. char cArg,
  166763. char **pzErr
  166764. ){
  166765. if( (cArg==FTS3_MATCHINFO_NPHRASE)
  166766. || (cArg==FTS3_MATCHINFO_NCOL)
  166767. || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4)
  166768. || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4)
  166769. || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
  166770. || (cArg==FTS3_MATCHINFO_LCS)
  166771. || (cArg==FTS3_MATCHINFO_HITS)
  166772. || (cArg==FTS3_MATCHINFO_LHITS)
  166773. || (cArg==FTS3_MATCHINFO_LHITS_BM)
  166774. ){
  166775. return SQLITE_OK;
  166776. }
  166777. sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo request: %c", cArg);
  166778. return SQLITE_ERROR;
  166779. }
  166780. static size_t fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
  166781. size_t nVal; /* Number of integers output by cArg */
  166782. switch( cArg ){
  166783. case FTS3_MATCHINFO_NDOC:
  166784. case FTS3_MATCHINFO_NPHRASE:
  166785. case FTS3_MATCHINFO_NCOL:
  166786. nVal = 1;
  166787. break;
  166788. case FTS3_MATCHINFO_AVGLENGTH:
  166789. case FTS3_MATCHINFO_LENGTH:
  166790. case FTS3_MATCHINFO_LCS:
  166791. nVal = pInfo->nCol;
  166792. break;
  166793. case FTS3_MATCHINFO_LHITS:
  166794. nVal = pInfo->nCol * pInfo->nPhrase;
  166795. break;
  166796. case FTS3_MATCHINFO_LHITS_BM:
  166797. nVal = pInfo->nPhrase * ((pInfo->nCol + 31) / 32);
  166798. break;
  166799. default:
  166800. assert( cArg==FTS3_MATCHINFO_HITS );
  166801. nVal = pInfo->nCol * pInfo->nPhrase * 3;
  166802. break;
  166803. }
  166804. return nVal;
  166805. }
  166806. static int fts3MatchinfoSelectDoctotal(
  166807. Fts3Table *pTab,
  166808. sqlite3_stmt **ppStmt,
  166809. sqlite3_int64 *pnDoc,
  166810. const char **paLen
  166811. ){
  166812. sqlite3_stmt *pStmt;
  166813. const char *a;
  166814. sqlite3_int64 nDoc;
  166815. if( !*ppStmt ){
  166816. int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
  166817. if( rc!=SQLITE_OK ) return rc;
  166818. }
  166819. pStmt = *ppStmt;
  166820. assert( sqlite3_data_count(pStmt)==1 );
  166821. a = sqlite3_column_blob(pStmt, 0);
  166822. a += sqlite3Fts3GetVarint(a, &nDoc);
  166823. if( nDoc==0 ) return FTS_CORRUPT_VTAB;
  166824. *pnDoc = (u32)nDoc;
  166825. if( paLen ) *paLen = a;
  166826. return SQLITE_OK;
  166827. }
  166828. /*
  166829. ** An instance of the following structure is used to store state while
  166830. ** iterating through a multi-column position-list corresponding to the
  166831. ** hits for a single phrase on a single row in order to calculate the
  166832. ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
  166833. */
  166834. typedef struct LcsIterator LcsIterator;
  166835. struct LcsIterator {
  166836. Fts3Expr *pExpr; /* Pointer to phrase expression */
  166837. int iPosOffset; /* Tokens count up to end of this phrase */
  166838. char *pRead; /* Cursor used to iterate through aDoclist */
  166839. int iPos; /* Current position */
  166840. };
  166841. /*
  166842. ** If LcsIterator.iCol is set to the following value, the iterator has
  166843. ** finished iterating through all offsets for all columns.
  166844. */
  166845. #define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
  166846. static int fts3MatchinfoLcsCb(
  166847. Fts3Expr *pExpr, /* Phrase expression node */
  166848. int iPhrase, /* Phrase number (numbered from zero) */
  166849. void *pCtx /* Pointer to MatchInfo structure */
  166850. ){
  166851. LcsIterator *aIter = (LcsIterator *)pCtx;
  166852. aIter[iPhrase].pExpr = pExpr;
  166853. return SQLITE_OK;
  166854. }
  166855. /*
  166856. ** Advance the iterator passed as an argument to the next position. Return
  166857. ** 1 if the iterator is at EOF or if it now points to the start of the
  166858. ** position list for the next column.
  166859. */
  166860. static int fts3LcsIteratorAdvance(LcsIterator *pIter){
  166861. char *pRead = pIter->pRead;
  166862. sqlite3_int64 iRead;
  166863. int rc = 0;
  166864. pRead += sqlite3Fts3GetVarint(pRead, &iRead);
  166865. if( iRead==0 || iRead==1 ){
  166866. pRead = 0;
  166867. rc = 1;
  166868. }else{
  166869. pIter->iPos += (int)(iRead-2);
  166870. }
  166871. pIter->pRead = pRead;
  166872. return rc;
  166873. }
  166874. /*
  166875. ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag.
  166876. **
  166877. ** If the call is successful, the longest-common-substring lengths for each
  166878. ** column are written into the first nCol elements of the pInfo->aMatchinfo[]
  166879. ** array before returning. SQLITE_OK is returned in this case.
  166880. **
  166881. ** Otherwise, if an error occurs, an SQLite error code is returned and the
  166882. ** data written to the first nCol elements of pInfo->aMatchinfo[] is
  166883. ** undefined.
  166884. */
  166885. static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
  166886. LcsIterator *aIter;
  166887. int i;
  166888. int iCol;
  166889. int nToken = 0;
  166890. int rc = SQLITE_OK;
  166891. /* Allocate and populate the array of LcsIterator objects. The array
  166892. ** contains one element for each matchable phrase in the query.
  166893. **/
  166894. aIter = sqlite3_malloc64(sizeof(LcsIterator) * pCsr->nPhrase);
  166895. if( !aIter ) return SQLITE_NOMEM;
  166896. memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
  166897. (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
  166898. for(i=0; i<pInfo->nPhrase; i++){
  166899. LcsIterator *pIter = &aIter[i];
  166900. nToken -= pIter->pExpr->pPhrase->nToken;
  166901. pIter->iPosOffset = nToken;
  166902. }
  166903. for(iCol=0; iCol<pInfo->nCol; iCol++){
  166904. int nLcs = 0; /* LCS value for this column */
  166905. int nLive = 0; /* Number of iterators in aIter not at EOF */
  166906. for(i=0; i<pInfo->nPhrase; i++){
  166907. LcsIterator *pIt = &aIter[i];
  166908. rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead);
  166909. if( rc!=SQLITE_OK ) goto matchinfo_lcs_out;
  166910. if( pIt->pRead ){
  166911. pIt->iPos = pIt->iPosOffset;
  166912. fts3LcsIteratorAdvance(pIt);
  166913. if( pIt->pRead==0 ){
  166914. rc = FTS_CORRUPT_VTAB;
  166915. goto matchinfo_lcs_out;
  166916. }
  166917. nLive++;
  166918. }
  166919. }
  166920. while( nLive>0 ){
  166921. LcsIterator *pAdv = 0; /* The iterator to advance by one position */
  166922. int nThisLcs = 0; /* LCS for the current iterator positions */
  166923. for(i=0; i<pInfo->nPhrase; i++){
  166924. LcsIterator *pIter = &aIter[i];
  166925. if( pIter->pRead==0 ){
  166926. /* This iterator is already at EOF for this column. */
  166927. nThisLcs = 0;
  166928. }else{
  166929. if( pAdv==0 || pIter->iPos<pAdv->iPos ){
  166930. pAdv = pIter;
  166931. }
  166932. if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
  166933. nThisLcs++;
  166934. }else{
  166935. nThisLcs = 1;
  166936. }
  166937. if( nThisLcs>nLcs ) nLcs = nThisLcs;
  166938. }
  166939. }
  166940. if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
  166941. }
  166942. pInfo->aMatchinfo[iCol] = nLcs;
  166943. }
  166944. matchinfo_lcs_out:
  166945. sqlite3_free(aIter);
  166946. return rc;
  166947. }
  166948. /*
  166949. ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
  166950. ** be returned by the matchinfo() function. Argument zArg contains the
  166951. ** format string passed as the second argument to matchinfo (or the
  166952. ** default value "pcx" if no second argument was specified). The format
  166953. ** string has already been validated and the pInfo->aMatchinfo[] array
  166954. ** is guaranteed to be large enough for the output.
  166955. **
  166956. ** If bGlobal is true, then populate all fields of the matchinfo() output.
  166957. ** If it is false, then assume that those fields that do not change between
  166958. ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
  166959. ** have already been populated.
  166960. **
  166961. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  166962. ** occurs. If a value other than SQLITE_OK is returned, the state the
  166963. ** pInfo->aMatchinfo[] buffer is left in is undefined.
  166964. */
  166965. static int fts3MatchinfoValues(
  166966. Fts3Cursor *pCsr, /* FTS3 cursor object */
  166967. int bGlobal, /* True to grab the global stats */
  166968. MatchInfo *pInfo, /* Matchinfo context object */
  166969. const char *zArg /* Matchinfo format string */
  166970. ){
  166971. int rc = SQLITE_OK;
  166972. int i;
  166973. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  166974. sqlite3_stmt *pSelect = 0;
  166975. for(i=0; rc==SQLITE_OK && zArg[i]; i++){
  166976. pInfo->flag = zArg[i];
  166977. switch( zArg[i] ){
  166978. case FTS3_MATCHINFO_NPHRASE:
  166979. if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
  166980. break;
  166981. case FTS3_MATCHINFO_NCOL:
  166982. if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
  166983. break;
  166984. case FTS3_MATCHINFO_NDOC:
  166985. if( bGlobal ){
  166986. sqlite3_int64 nDoc = 0;
  166987. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
  166988. pInfo->aMatchinfo[0] = (u32)nDoc;
  166989. }
  166990. break;
  166991. case FTS3_MATCHINFO_AVGLENGTH:
  166992. if( bGlobal ){
  166993. sqlite3_int64 nDoc; /* Number of rows in table */
  166994. const char *a; /* Aggregate column length array */
  166995. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
  166996. if( rc==SQLITE_OK ){
  166997. int iCol;
  166998. for(iCol=0; iCol<pInfo->nCol; iCol++){
  166999. u32 iVal;
  167000. sqlite3_int64 nToken;
  167001. a += sqlite3Fts3GetVarint(a, &nToken);
  167002. iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
  167003. pInfo->aMatchinfo[iCol] = iVal;
  167004. }
  167005. }
  167006. }
  167007. break;
  167008. case FTS3_MATCHINFO_LENGTH: {
  167009. sqlite3_stmt *pSelectDocsize = 0;
  167010. rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
  167011. if( rc==SQLITE_OK ){
  167012. int iCol;
  167013. const char *a = sqlite3_column_blob(pSelectDocsize, 0);
  167014. for(iCol=0; iCol<pInfo->nCol; iCol++){
  167015. sqlite3_int64 nToken;
  167016. a += sqlite3Fts3GetVarint(a, &nToken);
  167017. pInfo->aMatchinfo[iCol] = (u32)nToken;
  167018. }
  167019. }
  167020. sqlite3_reset(pSelectDocsize);
  167021. break;
  167022. }
  167023. case FTS3_MATCHINFO_LCS:
  167024. rc = fts3ExprLoadDoclists(pCsr, 0, 0);
  167025. if( rc==SQLITE_OK ){
  167026. rc = fts3MatchinfoLcs(pCsr, pInfo);
  167027. }
  167028. break;
  167029. case FTS3_MATCHINFO_LHITS_BM:
  167030. case FTS3_MATCHINFO_LHITS: {
  167031. size_t nZero = fts3MatchinfoSize(pInfo, zArg[i]) * sizeof(u32);
  167032. memset(pInfo->aMatchinfo, 0, nZero);
  167033. rc = fts3ExprLHitGather(pCsr->pExpr, pInfo);
  167034. break;
  167035. }
  167036. default: {
  167037. Fts3Expr *pExpr;
  167038. assert( zArg[i]==FTS3_MATCHINFO_HITS );
  167039. pExpr = pCsr->pExpr;
  167040. rc = fts3ExprLoadDoclists(pCsr, 0, 0);
  167041. if( rc!=SQLITE_OK ) break;
  167042. if( bGlobal ){
  167043. if( pCsr->pDeferred ){
  167044. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
  167045. if( rc!=SQLITE_OK ) break;
  167046. }
  167047. rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
  167048. sqlite3Fts3EvalTestDeferred(pCsr, &rc);
  167049. if( rc!=SQLITE_OK ) break;
  167050. }
  167051. (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
  167052. break;
  167053. }
  167054. }
  167055. pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
  167056. }
  167057. sqlite3_reset(pSelect);
  167058. return rc;
  167059. }
  167060. /*
  167061. ** Populate pCsr->aMatchinfo[] with data for the current row. The
  167062. ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
  167063. */
  167064. static void fts3GetMatchinfo(
  167065. sqlite3_context *pCtx, /* Return results here */
  167066. Fts3Cursor *pCsr, /* FTS3 Cursor object */
  167067. const char *zArg /* Second argument to matchinfo() function */
  167068. ){
  167069. MatchInfo sInfo;
  167070. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  167071. int rc = SQLITE_OK;
  167072. int bGlobal = 0; /* Collect 'global' stats as well as local */
  167073. u32 *aOut = 0;
  167074. void (*xDestroyOut)(void*) = 0;
  167075. memset(&sInfo, 0, sizeof(MatchInfo));
  167076. sInfo.pCursor = pCsr;
  167077. sInfo.nCol = pTab->nColumn;
  167078. /* If there is cached matchinfo() data, but the format string for the
  167079. ** cache does not match the format string for this request, discard
  167080. ** the cached data. */
  167081. if( pCsr->pMIBuffer && strcmp(pCsr->pMIBuffer->zMatchinfo, zArg) ){
  167082. sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
  167083. pCsr->pMIBuffer = 0;
  167084. }
  167085. /* If Fts3Cursor.pMIBuffer is NULL, then this is the first time the
  167086. ** matchinfo function has been called for this query. In this case
  167087. ** allocate the array used to accumulate the matchinfo data and
  167088. ** initialize those elements that are constant for every row.
  167089. */
  167090. if( pCsr->pMIBuffer==0 ){
  167091. size_t nMatchinfo = 0; /* Number of u32 elements in match-info */
  167092. int i; /* Used to iterate through zArg */
  167093. /* Determine the number of phrases in the query */
  167094. pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
  167095. sInfo.nPhrase = pCsr->nPhrase;
  167096. /* Determine the number of integers in the buffer returned by this call. */
  167097. for(i=0; zArg[i]; i++){
  167098. char *zErr = 0;
  167099. if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
  167100. sqlite3_result_error(pCtx, zErr, -1);
  167101. sqlite3_free(zErr);
  167102. return;
  167103. }
  167104. nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
  167105. }
  167106. /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
  167107. pCsr->pMIBuffer = fts3MIBufferNew(nMatchinfo, zArg);
  167108. if( !pCsr->pMIBuffer ) rc = SQLITE_NOMEM;
  167109. pCsr->isMatchinfoNeeded = 1;
  167110. bGlobal = 1;
  167111. }
  167112. if( rc==SQLITE_OK ){
  167113. xDestroyOut = fts3MIBufferAlloc(pCsr->pMIBuffer, &aOut);
  167114. if( xDestroyOut==0 ){
  167115. rc = SQLITE_NOMEM;
  167116. }
  167117. }
  167118. if( rc==SQLITE_OK ){
  167119. sInfo.aMatchinfo = aOut;
  167120. sInfo.nPhrase = pCsr->nPhrase;
  167121. rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
  167122. if( bGlobal ){
  167123. fts3MIBufferSetGlobal(pCsr->pMIBuffer);
  167124. }
  167125. }
  167126. if( rc!=SQLITE_OK ){
  167127. sqlite3_result_error_code(pCtx, rc);
  167128. if( xDestroyOut ) xDestroyOut(aOut);
  167129. }else{
  167130. int n = pCsr->pMIBuffer->nElem * sizeof(u32);
  167131. sqlite3_result_blob(pCtx, aOut, n, xDestroyOut);
  167132. }
  167133. }
  167134. /*
  167135. ** Implementation of snippet() function.
  167136. */
  167137. SQLITE_PRIVATE void sqlite3Fts3Snippet(
  167138. sqlite3_context *pCtx, /* SQLite function call context */
  167139. Fts3Cursor *pCsr, /* Cursor object */
  167140. const char *zStart, /* Snippet start text - "<b>" */
  167141. const char *zEnd, /* Snippet end text - "</b>" */
  167142. const char *zEllipsis, /* Snippet ellipsis text - "<b>...</b>" */
  167143. int iCol, /* Extract snippet from this column */
  167144. int nToken /* Approximate number of tokens in snippet */
  167145. ){
  167146. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  167147. int rc = SQLITE_OK;
  167148. int i;
  167149. StrBuffer res = {0, 0, 0};
  167150. /* The returned text includes up to four fragments of text extracted from
  167151. ** the data in the current row. The first iteration of the for(...) loop
  167152. ** below attempts to locate a single fragment of text nToken tokens in
  167153. ** size that contains at least one instance of all phrases in the query
  167154. ** expression that appear in the current row. If such a fragment of text
  167155. ** cannot be found, the second iteration of the loop attempts to locate
  167156. ** a pair of fragments, and so on.
  167157. */
  167158. int nSnippet = 0; /* Number of fragments in this snippet */
  167159. SnippetFragment aSnippet[4]; /* Maximum of 4 fragments per snippet */
  167160. int nFToken = -1; /* Number of tokens in each fragment */
  167161. if( !pCsr->pExpr ){
  167162. sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
  167163. return;
  167164. }
  167165. /* Limit the snippet length to 64 tokens. */
  167166. if( nToken<-64 ) nToken = -64;
  167167. if( nToken>+64 ) nToken = +64;
  167168. for(nSnippet=1; 1; nSnippet++){
  167169. int iSnip; /* Loop counter 0..nSnippet-1 */
  167170. u64 mCovered = 0; /* Bitmask of phrases covered by snippet */
  167171. u64 mSeen = 0; /* Bitmask of phrases seen by BestSnippet() */
  167172. if( nToken>=0 ){
  167173. nFToken = (nToken+nSnippet-1) / nSnippet;
  167174. }else{
  167175. nFToken = -1 * nToken;
  167176. }
  167177. for(iSnip=0; iSnip<nSnippet; iSnip++){
  167178. int iBestScore = -1; /* Best score of columns checked so far */
  167179. int iRead; /* Used to iterate through columns */
  167180. SnippetFragment *pFragment = &aSnippet[iSnip];
  167181. memset(pFragment, 0, sizeof(*pFragment));
  167182. /* Loop through all columns of the table being considered for snippets.
  167183. ** If the iCol argument to this function was negative, this means all
  167184. ** columns of the FTS3 table. Otherwise, only column iCol is considered.
  167185. */
  167186. for(iRead=0; iRead<pTab->nColumn; iRead++){
  167187. SnippetFragment sF = {0, 0, 0, 0};
  167188. int iS = 0;
  167189. if( iCol>=0 && iRead!=iCol ) continue;
  167190. /* Find the best snippet of nFToken tokens in column iRead. */
  167191. rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
  167192. if( rc!=SQLITE_OK ){
  167193. goto snippet_out;
  167194. }
  167195. if( iS>iBestScore ){
  167196. *pFragment = sF;
  167197. iBestScore = iS;
  167198. }
  167199. }
  167200. mCovered |= pFragment->covered;
  167201. }
  167202. /* If all query phrases seen by fts3BestSnippet() are present in at least
  167203. ** one of the nSnippet snippet fragments, break out of the loop.
  167204. */
  167205. assert( (mCovered&mSeen)==mCovered );
  167206. if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
  167207. }
  167208. assert( nFToken>0 );
  167209. for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
  167210. rc = fts3SnippetText(pCsr, &aSnippet[i],
  167211. i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
  167212. );
  167213. }
  167214. snippet_out:
  167215. sqlite3Fts3SegmentsClose(pTab);
  167216. if( rc!=SQLITE_OK ){
  167217. sqlite3_result_error_code(pCtx, rc);
  167218. sqlite3_free(res.z);
  167219. }else{
  167220. sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
  167221. }
  167222. }
  167223. typedef struct TermOffset TermOffset;
  167224. typedef struct TermOffsetCtx TermOffsetCtx;
  167225. struct TermOffset {
  167226. char *pList; /* Position-list */
  167227. int iPos; /* Position just read from pList */
  167228. int iOff; /* Offset of this term from read positions */
  167229. };
  167230. struct TermOffsetCtx {
  167231. Fts3Cursor *pCsr;
  167232. int iCol; /* Column of table to populate aTerm for */
  167233. int iTerm;
  167234. sqlite3_int64 iDocid;
  167235. TermOffset *aTerm;
  167236. };
  167237. /*
  167238. ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
  167239. */
  167240. static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
  167241. TermOffsetCtx *p = (TermOffsetCtx *)ctx;
  167242. int nTerm; /* Number of tokens in phrase */
  167243. int iTerm; /* For looping through nTerm phrase terms */
  167244. char *pList; /* Pointer to position list for phrase */
  167245. int iPos = 0; /* First position in position-list */
  167246. int rc;
  167247. UNUSED_PARAMETER(iPhrase);
  167248. rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList);
  167249. nTerm = pExpr->pPhrase->nToken;
  167250. if( pList ){
  167251. fts3GetDeltaPosition(&pList, &iPos);
  167252. assert_fts3_nc( iPos>=0 );
  167253. }
  167254. for(iTerm=0; iTerm<nTerm; iTerm++){
  167255. TermOffset *pT = &p->aTerm[p->iTerm++];
  167256. pT->iOff = nTerm-iTerm-1;
  167257. pT->pList = pList;
  167258. pT->iPos = iPos;
  167259. }
  167260. return rc;
  167261. }
  167262. /*
  167263. ** Implementation of offsets() function.
  167264. */
  167265. SQLITE_PRIVATE void sqlite3Fts3Offsets(
  167266. sqlite3_context *pCtx, /* SQLite function call context */
  167267. Fts3Cursor *pCsr /* Cursor object */
  167268. ){
  167269. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  167270. sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
  167271. int rc; /* Return Code */
  167272. int nToken; /* Number of tokens in query */
  167273. int iCol; /* Column currently being processed */
  167274. StrBuffer res = {0, 0, 0}; /* Result string */
  167275. TermOffsetCtx sCtx; /* Context for fts3ExprTermOffsetInit() */
  167276. if( !pCsr->pExpr ){
  167277. sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
  167278. return;
  167279. }
  167280. memset(&sCtx, 0, sizeof(sCtx));
  167281. assert( pCsr->isRequireSeek==0 );
  167282. /* Count the number of terms in the query */
  167283. rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
  167284. if( rc!=SQLITE_OK ) goto offsets_out;
  167285. /* Allocate the array of TermOffset iterators. */
  167286. sCtx.aTerm = (TermOffset *)sqlite3_malloc64(sizeof(TermOffset)*nToken);
  167287. if( 0==sCtx.aTerm ){
  167288. rc = SQLITE_NOMEM;
  167289. goto offsets_out;
  167290. }
  167291. sCtx.iDocid = pCsr->iPrevId;
  167292. sCtx.pCsr = pCsr;
  167293. /* Loop through the table columns, appending offset information to
  167294. ** string-buffer res for each column.
  167295. */
  167296. for(iCol=0; iCol<pTab->nColumn; iCol++){
  167297. sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
  167298. const char *ZDUMMY; /* Dummy argument used with xNext() */
  167299. int NDUMMY = 0; /* Dummy argument used with xNext() */
  167300. int iStart = 0;
  167301. int iEnd = 0;
  167302. int iCurrent = 0;
  167303. const char *zDoc;
  167304. int nDoc;
  167305. /* Initialize the contents of sCtx.aTerm[] for column iCol. There is
  167306. ** no way that this operation can fail, so the return code from
  167307. ** fts3ExprIterate() can be discarded.
  167308. */
  167309. sCtx.iCol = iCol;
  167310. sCtx.iTerm = 0;
  167311. (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void*)&sCtx);
  167312. /* Retreive the text stored in column iCol. If an SQL NULL is stored
  167313. ** in column iCol, jump immediately to the next iteration of the loop.
  167314. ** If an OOM occurs while retrieving the data (this can happen if SQLite
  167315. ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
  167316. ** to the caller.
  167317. */
  167318. zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
  167319. nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
  167320. if( zDoc==0 ){
  167321. if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
  167322. continue;
  167323. }
  167324. rc = SQLITE_NOMEM;
  167325. goto offsets_out;
  167326. }
  167327. /* Initialize a tokenizer iterator to iterate through column iCol. */
  167328. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
  167329. zDoc, nDoc, &pC
  167330. );
  167331. if( rc!=SQLITE_OK ) goto offsets_out;
  167332. rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
  167333. while( rc==SQLITE_OK ){
  167334. int i; /* Used to loop through terms */
  167335. int iMinPos = 0x7FFFFFFF; /* Position of next token */
  167336. TermOffset *pTerm = 0; /* TermOffset associated with next token */
  167337. for(i=0; i<nToken; i++){
  167338. TermOffset *pT = &sCtx.aTerm[i];
  167339. if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
  167340. iMinPos = pT->iPos-pT->iOff;
  167341. pTerm = pT;
  167342. }
  167343. }
  167344. if( !pTerm ){
  167345. /* All offsets for this column have been gathered. */
  167346. rc = SQLITE_DONE;
  167347. }else{
  167348. assert_fts3_nc( iCurrent<=iMinPos );
  167349. if( 0==(0xFE&*pTerm->pList) ){
  167350. pTerm->pList = 0;
  167351. }else{
  167352. fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
  167353. }
  167354. while( rc==SQLITE_OK && iCurrent<iMinPos ){
  167355. rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
  167356. }
  167357. if( rc==SQLITE_OK ){
  167358. char aBuffer[64];
  167359. sqlite3_snprintf(sizeof(aBuffer), aBuffer,
  167360. "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
  167361. );
  167362. rc = fts3StringAppend(&res, aBuffer, -1);
  167363. }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
  167364. rc = FTS_CORRUPT_VTAB;
  167365. }
  167366. }
  167367. }
  167368. if( rc==SQLITE_DONE ){
  167369. rc = SQLITE_OK;
  167370. }
  167371. pMod->xClose(pC);
  167372. if( rc!=SQLITE_OK ) goto offsets_out;
  167373. }
  167374. offsets_out:
  167375. sqlite3_free(sCtx.aTerm);
  167376. assert( rc!=SQLITE_DONE );
  167377. sqlite3Fts3SegmentsClose(pTab);
  167378. if( rc!=SQLITE_OK ){
  167379. sqlite3_result_error_code(pCtx, rc);
  167380. sqlite3_free(res.z);
  167381. }else{
  167382. sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
  167383. }
  167384. return;
  167385. }
  167386. /*
  167387. ** Implementation of matchinfo() function.
  167388. */
  167389. SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
  167390. sqlite3_context *pContext, /* Function call context */
  167391. Fts3Cursor *pCsr, /* FTS3 table cursor */
  167392. const char *zArg /* Second arg to matchinfo() function */
  167393. ){
  167394. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  167395. const char *zFormat;
  167396. if( zArg ){
  167397. zFormat = zArg;
  167398. }else{
  167399. zFormat = FTS3_MATCHINFO_DEFAULT;
  167400. }
  167401. if( !pCsr->pExpr ){
  167402. sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
  167403. return;
  167404. }else{
  167405. /* Retrieve matchinfo() data. */
  167406. fts3GetMatchinfo(pContext, pCsr, zFormat);
  167407. sqlite3Fts3SegmentsClose(pTab);
  167408. }
  167409. }
  167410. #endif
  167411. /************** End of fts3_snippet.c ****************************************/
  167412. /************** Begin file fts3_unicode.c ************************************/
  167413. /*
  167414. ** 2012 May 24
  167415. **
  167416. ** The author disclaims copyright to this source code. In place of
  167417. ** a legal notice, here is a blessing:
  167418. **
  167419. ** May you do good and not evil.
  167420. ** May you find forgiveness for yourself and forgive others.
  167421. ** May you share freely, never taking more than you give.
  167422. **
  167423. ******************************************************************************
  167424. **
  167425. ** Implementation of the "unicode" full-text-search tokenizer.
  167426. */
  167427. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  167428. /* #include "fts3Int.h" */
  167429. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  167430. /* #include <assert.h> */
  167431. /* #include <stdlib.h> */
  167432. /* #include <stdio.h> */
  167433. /* #include <string.h> */
  167434. /* #include "fts3_tokenizer.h" */
  167435. /*
  167436. ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
  167437. ** from the sqlite3 source file utf.c. If this file is compiled as part
  167438. ** of the amalgamation, they are not required.
  167439. */
  167440. #ifndef SQLITE_AMALGAMATION
  167441. static const unsigned char sqlite3Utf8Trans1[] = {
  167442. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  167443. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  167444. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  167445. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  167446. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  167447. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  167448. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  167449. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  167450. };
  167451. #define READ_UTF8(zIn, zTerm, c) \
  167452. c = *(zIn++); \
  167453. if( c>=0xc0 ){ \
  167454. c = sqlite3Utf8Trans1[c-0xc0]; \
  167455. while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
  167456. c = (c<<6) + (0x3f & *(zIn++)); \
  167457. } \
  167458. if( c<0x80 \
  167459. || (c&0xFFFFF800)==0xD800 \
  167460. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
  167461. }
  167462. #define WRITE_UTF8(zOut, c) { \
  167463. if( c<0x00080 ){ \
  167464. *zOut++ = (u8)(c&0xFF); \
  167465. } \
  167466. else if( c<0x00800 ){ \
  167467. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
  167468. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  167469. } \
  167470. else if( c<0x10000 ){ \
  167471. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
  167472. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  167473. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  167474. }else{ \
  167475. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
  167476. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
  167477. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  167478. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  167479. } \
  167480. }
  167481. #endif /* ifndef SQLITE_AMALGAMATION */
  167482. typedef struct unicode_tokenizer unicode_tokenizer;
  167483. typedef struct unicode_cursor unicode_cursor;
  167484. struct unicode_tokenizer {
  167485. sqlite3_tokenizer base;
  167486. int eRemoveDiacritic;
  167487. int nException;
  167488. int *aiException;
  167489. };
  167490. struct unicode_cursor {
  167491. sqlite3_tokenizer_cursor base;
  167492. const unsigned char *aInput; /* Input text being tokenized */
  167493. int nInput; /* Size of aInput[] in bytes */
  167494. int iOff; /* Current offset within aInput[] */
  167495. int iToken; /* Index of next token to be returned */
  167496. char *zToken; /* storage for current token */
  167497. int nAlloc; /* space allocated at zToken */
  167498. };
  167499. /*
  167500. ** Destroy a tokenizer allocated by unicodeCreate().
  167501. */
  167502. static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){
  167503. if( pTokenizer ){
  167504. unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer;
  167505. sqlite3_free(p->aiException);
  167506. sqlite3_free(p);
  167507. }
  167508. return SQLITE_OK;
  167509. }
  167510. /*
  167511. ** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE
  167512. ** statement has specified that the tokenizer for this table shall consider
  167513. ** all characters in string zIn/nIn to be separators (if bAlnum==0) or
  167514. ** token characters (if bAlnum==1).
  167515. **
  167516. ** For each codepoint in the zIn/nIn string, this function checks if the
  167517. ** sqlite3FtsUnicodeIsalnum() function already returns the desired result.
  167518. ** If so, no action is taken. Otherwise, the codepoint is added to the
  167519. ** unicode_tokenizer.aiException[] array. For the purposes of tokenization,
  167520. ** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all
  167521. ** codepoints in the aiException[] array.
  167522. **
  167523. ** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic()
  167524. ** identifies as a diacritic) occurs in the zIn/nIn string it is ignored.
  167525. ** It is not possible to change the behavior of the tokenizer with respect
  167526. ** to these codepoints.
  167527. */
  167528. static int unicodeAddExceptions(
  167529. unicode_tokenizer *p, /* Tokenizer to add exceptions to */
  167530. int bAlnum, /* Replace Isalnum() return value with this */
  167531. const char *zIn, /* Array of characters to make exceptions */
  167532. int nIn /* Length of z in bytes */
  167533. ){
  167534. const unsigned char *z = (const unsigned char *)zIn;
  167535. const unsigned char *zTerm = &z[nIn];
  167536. unsigned int iCode;
  167537. int nEntry = 0;
  167538. assert( bAlnum==0 || bAlnum==1 );
  167539. while( z<zTerm ){
  167540. READ_UTF8(z, zTerm, iCode);
  167541. assert( (sqlite3FtsUnicodeIsalnum((int)iCode) & 0xFFFFFFFE)==0 );
  167542. if( sqlite3FtsUnicodeIsalnum((int)iCode)!=bAlnum
  167543. && sqlite3FtsUnicodeIsdiacritic((int)iCode)==0
  167544. ){
  167545. nEntry++;
  167546. }
  167547. }
  167548. if( nEntry ){
  167549. int *aNew; /* New aiException[] array */
  167550. int nNew; /* Number of valid entries in array aNew[] */
  167551. aNew = sqlite3_realloc64(p->aiException,(p->nException+nEntry)*sizeof(int));
  167552. if( aNew==0 ) return SQLITE_NOMEM;
  167553. nNew = p->nException;
  167554. z = (const unsigned char *)zIn;
  167555. while( z<zTerm ){
  167556. READ_UTF8(z, zTerm, iCode);
  167557. if( sqlite3FtsUnicodeIsalnum((int)iCode)!=bAlnum
  167558. && sqlite3FtsUnicodeIsdiacritic((int)iCode)==0
  167559. ){
  167560. int i, j;
  167561. for(i=0; i<nNew && aNew[i]<(int)iCode; i++);
  167562. for(j=nNew; j>i; j--) aNew[j] = aNew[j-1];
  167563. aNew[i] = (int)iCode;
  167564. nNew++;
  167565. }
  167566. }
  167567. p->aiException = aNew;
  167568. p->nException = nNew;
  167569. }
  167570. return SQLITE_OK;
  167571. }
  167572. /*
  167573. ** Return true if the p->aiException[] array contains the value iCode.
  167574. */
  167575. static int unicodeIsException(unicode_tokenizer *p, int iCode){
  167576. if( p->nException>0 ){
  167577. int *a = p->aiException;
  167578. int iLo = 0;
  167579. int iHi = p->nException-1;
  167580. while( iHi>=iLo ){
  167581. int iTest = (iHi + iLo) / 2;
  167582. if( iCode==a[iTest] ){
  167583. return 1;
  167584. }else if( iCode>a[iTest] ){
  167585. iLo = iTest+1;
  167586. }else{
  167587. iHi = iTest-1;
  167588. }
  167589. }
  167590. }
  167591. return 0;
  167592. }
  167593. /*
  167594. ** Return true if, for the purposes of tokenization, codepoint iCode is
  167595. ** considered a token character (not a separator).
  167596. */
  167597. static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){
  167598. assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
  167599. return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode);
  167600. }
  167601. /*
  167602. ** Create a new tokenizer instance.
  167603. */
  167604. static int unicodeCreate(
  167605. int nArg, /* Size of array argv[] */
  167606. const char * const *azArg, /* Tokenizer creation arguments */
  167607. sqlite3_tokenizer **pp /* OUT: New tokenizer handle */
  167608. ){
  167609. unicode_tokenizer *pNew; /* New tokenizer object */
  167610. int i;
  167611. int rc = SQLITE_OK;
  167612. pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer));
  167613. if( pNew==NULL ) return SQLITE_NOMEM;
  167614. memset(pNew, 0, sizeof(unicode_tokenizer));
  167615. pNew->eRemoveDiacritic = 1;
  167616. for(i=0; rc==SQLITE_OK && i<nArg; i++){
  167617. const char *z = azArg[i];
  167618. int n = (int)strlen(z);
  167619. if( n==19 && memcmp("remove_diacritics=1", z, 19)==0 ){
  167620. pNew->eRemoveDiacritic = 1;
  167621. }
  167622. else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){
  167623. pNew->eRemoveDiacritic = 0;
  167624. }
  167625. else if( n==19 && memcmp("remove_diacritics=2", z, 19)==0 ){
  167626. pNew->eRemoveDiacritic = 2;
  167627. }
  167628. else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){
  167629. rc = unicodeAddExceptions(pNew, 1, &z[11], n-11);
  167630. }
  167631. else if( n>=11 && memcmp("separators=", z, 11)==0 ){
  167632. rc = unicodeAddExceptions(pNew, 0, &z[11], n-11);
  167633. }
  167634. else{
  167635. /* Unrecognized argument */
  167636. rc = SQLITE_ERROR;
  167637. }
  167638. }
  167639. if( rc!=SQLITE_OK ){
  167640. unicodeDestroy((sqlite3_tokenizer *)pNew);
  167641. pNew = 0;
  167642. }
  167643. *pp = (sqlite3_tokenizer *)pNew;
  167644. return rc;
  167645. }
  167646. /*
  167647. ** Prepare to begin tokenizing a particular string. The input
  167648. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  167649. ** used to incrementally tokenize this string is returned in
  167650. ** *ppCursor.
  167651. */
  167652. static int unicodeOpen(
  167653. sqlite3_tokenizer *p, /* The tokenizer */
  167654. const char *aInput, /* Input string */
  167655. int nInput, /* Size of string aInput in bytes */
  167656. sqlite3_tokenizer_cursor **pp /* OUT: New cursor object */
  167657. ){
  167658. unicode_cursor *pCsr;
  167659. pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor));
  167660. if( pCsr==0 ){
  167661. return SQLITE_NOMEM;
  167662. }
  167663. memset(pCsr, 0, sizeof(unicode_cursor));
  167664. pCsr->aInput = (const unsigned char *)aInput;
  167665. if( aInput==0 ){
  167666. pCsr->nInput = 0;
  167667. }else if( nInput<0 ){
  167668. pCsr->nInput = (int)strlen(aInput);
  167669. }else{
  167670. pCsr->nInput = nInput;
  167671. }
  167672. *pp = &pCsr->base;
  167673. UNUSED_PARAMETER(p);
  167674. return SQLITE_OK;
  167675. }
  167676. /*
  167677. ** Close a tokenization cursor previously opened by a call to
  167678. ** simpleOpen() above.
  167679. */
  167680. static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){
  167681. unicode_cursor *pCsr = (unicode_cursor *) pCursor;
  167682. sqlite3_free(pCsr->zToken);
  167683. sqlite3_free(pCsr);
  167684. return SQLITE_OK;
  167685. }
  167686. /*
  167687. ** Extract the next token from a tokenization cursor. The cursor must
  167688. ** have been opened by a prior call to simpleOpen().
  167689. */
  167690. static int unicodeNext(
  167691. sqlite3_tokenizer_cursor *pC, /* Cursor returned by simpleOpen */
  167692. const char **paToken, /* OUT: Token text */
  167693. int *pnToken, /* OUT: Number of bytes at *paToken */
  167694. int *piStart, /* OUT: Starting offset of token */
  167695. int *piEnd, /* OUT: Ending offset of token */
  167696. int *piPos /* OUT: Position integer of token */
  167697. ){
  167698. unicode_cursor *pCsr = (unicode_cursor *)pC;
  167699. unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer);
  167700. unsigned int iCode = 0;
  167701. char *zOut;
  167702. const unsigned char *z = &pCsr->aInput[pCsr->iOff];
  167703. const unsigned char *zStart = z;
  167704. const unsigned char *zEnd;
  167705. const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput];
  167706. /* Scan past any delimiter characters before the start of the next token.
  167707. ** Return SQLITE_DONE early if this takes us all the way to the end of
  167708. ** the input. */
  167709. while( z<zTerm ){
  167710. READ_UTF8(z, zTerm, iCode);
  167711. if( unicodeIsAlnum(p, (int)iCode) ) break;
  167712. zStart = z;
  167713. }
  167714. if( zStart>=zTerm ) return SQLITE_DONE;
  167715. zOut = pCsr->zToken;
  167716. do {
  167717. int iOut;
  167718. /* Grow the output buffer if required. */
  167719. if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){
  167720. char *zNew = sqlite3_realloc64(pCsr->zToken, pCsr->nAlloc+64);
  167721. if( !zNew ) return SQLITE_NOMEM;
  167722. zOut = &zNew[zOut - pCsr->zToken];
  167723. pCsr->zToken = zNew;
  167724. pCsr->nAlloc += 64;
  167725. }
  167726. /* Write the folded case of the last character read to the output */
  167727. zEnd = z;
  167728. iOut = sqlite3FtsUnicodeFold((int)iCode, p->eRemoveDiacritic);
  167729. if( iOut ){
  167730. WRITE_UTF8(zOut, iOut);
  167731. }
  167732. /* If the cursor is not at EOF, read the next character */
  167733. if( z>=zTerm ) break;
  167734. READ_UTF8(z, zTerm, iCode);
  167735. }while( unicodeIsAlnum(p, (int)iCode)
  167736. || sqlite3FtsUnicodeIsdiacritic((int)iCode)
  167737. );
  167738. /* Set the output variables and return. */
  167739. pCsr->iOff = (int)(z - pCsr->aInput);
  167740. *paToken = pCsr->zToken;
  167741. *pnToken = (int)(zOut - pCsr->zToken);
  167742. *piStart = (int)(zStart - pCsr->aInput);
  167743. *piEnd = (int)(zEnd - pCsr->aInput);
  167744. *piPos = pCsr->iToken++;
  167745. return SQLITE_OK;
  167746. }
  167747. /*
  167748. ** Set *ppModule to a pointer to the sqlite3_tokenizer_module
  167749. ** structure for the unicode tokenizer.
  167750. */
  167751. SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){
  167752. static const sqlite3_tokenizer_module module = {
  167753. 0,
  167754. unicodeCreate,
  167755. unicodeDestroy,
  167756. unicodeOpen,
  167757. unicodeClose,
  167758. unicodeNext,
  167759. 0,
  167760. };
  167761. *ppModule = &module;
  167762. }
  167763. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  167764. #endif /* ifndef SQLITE_DISABLE_FTS3_UNICODE */
  167765. /************** End of fts3_unicode.c ****************************************/
  167766. /************** Begin file fts3_unicode2.c ***********************************/
  167767. /*
  167768. ** 2012-05-25
  167769. **
  167770. ** The author disclaims copyright to this source code. In place of
  167771. ** a legal notice, here is a blessing:
  167772. **
  167773. ** May you do good and not evil.
  167774. ** May you find forgiveness for yourself and forgive others.
  167775. ** May you share freely, never taking more than you give.
  167776. **
  167777. ******************************************************************************
  167778. */
  167779. /*
  167780. ** DO NOT EDIT THIS MACHINE GENERATED FILE.
  167781. */
  167782. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  167783. #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
  167784. /* #include <assert.h> */
  167785. /*
  167786. ** Return true if the argument corresponds to a unicode codepoint
  167787. ** classified as either a letter or a number. Otherwise false.
  167788. **
  167789. ** The results are undefined if the value passed to this function
  167790. ** is less than zero.
  167791. */
  167792. SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
  167793. /* Each unsigned integer in the following array corresponds to a contiguous
  167794. ** range of unicode codepoints that are not either letters or numbers (i.e.
  167795. ** codepoints for which this function should return 0).
  167796. **
  167797. ** The most significant 22 bits in each 32-bit value contain the first
  167798. ** codepoint in the range. The least significant 10 bits are used to store
  167799. ** the size of the range (always at least 1). In other words, the value
  167800. ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
  167801. ** C. It is not possible to represent a range larger than 1023 codepoints
  167802. ** using this format.
  167803. */
  167804. static const unsigned int aEntry[] = {
  167805. 0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
  167806. 0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
  167807. 0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
  167808. 0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
  167809. 0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
  167810. 0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
  167811. 0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
  167812. 0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
  167813. 0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
  167814. 0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
  167815. 0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
  167816. 0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
  167817. 0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
  167818. 0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
  167819. 0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
  167820. 0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
  167821. 0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
  167822. 0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
  167823. 0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
  167824. 0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
  167825. 0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
  167826. 0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
  167827. 0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
  167828. 0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
  167829. 0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
  167830. 0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
  167831. 0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
  167832. 0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
  167833. 0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
  167834. 0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
  167835. 0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
  167836. 0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
  167837. 0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
  167838. 0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
  167839. 0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
  167840. 0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
  167841. 0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
  167842. 0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
  167843. 0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
  167844. 0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
  167845. 0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
  167846. 0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
  167847. 0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
  167848. 0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
  167849. 0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
  167850. 0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
  167851. 0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
  167852. 0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
  167853. 0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
  167854. 0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
  167855. 0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
  167856. 0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
  167857. 0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
  167858. 0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
  167859. 0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
  167860. 0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
  167861. 0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
  167862. 0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
  167863. 0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
  167864. 0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
  167865. 0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
  167866. 0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
  167867. 0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
  167868. 0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
  167869. 0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
  167870. 0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
  167871. 0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
  167872. 0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
  167873. 0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
  167874. 0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
  167875. 0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
  167876. 0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
  167877. 0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
  167878. 0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
  167879. 0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
  167880. 0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
  167881. 0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
  167882. 0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
  167883. 0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
  167884. 0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
  167885. 0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
  167886. 0x380400F0,
  167887. };
  167888. static const unsigned int aAscii[4] = {
  167889. 0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
  167890. };
  167891. if( (unsigned int)c<128 ){
  167892. return ( (aAscii[c >> 5] & ((unsigned int)1 << (c & 0x001F)))==0 );
  167893. }else if( (unsigned int)c<(1<<22) ){
  167894. unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
  167895. int iRes = 0;
  167896. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  167897. int iLo = 0;
  167898. while( iHi>=iLo ){
  167899. int iTest = (iHi + iLo) / 2;
  167900. if( key >= aEntry[iTest] ){
  167901. iRes = iTest;
  167902. iLo = iTest+1;
  167903. }else{
  167904. iHi = iTest-1;
  167905. }
  167906. }
  167907. assert( aEntry[0]<key );
  167908. assert( key>=aEntry[iRes] );
  167909. return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
  167910. }
  167911. return 1;
  167912. }
  167913. /*
  167914. ** If the argument is a codepoint corresponding to a lowercase letter
  167915. ** in the ASCII range with a diacritic added, return the codepoint
  167916. ** of the ASCII letter only. For example, if passed 235 - "LATIN
  167917. ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
  167918. ** E"). The resuls of passing a codepoint that corresponds to an
  167919. ** uppercase letter are undefined.
  167920. */
  167921. static int remove_diacritic(int c, int bComplex){
  167922. unsigned short aDia[] = {
  167923. 0, 1797, 1848, 1859, 1891, 1928, 1940, 1995,
  167924. 2024, 2040, 2060, 2110, 2168, 2206, 2264, 2286,
  167925. 2344, 2383, 2472, 2488, 2516, 2596, 2668, 2732,
  167926. 2782, 2842, 2894, 2954, 2984, 3000, 3028, 3336,
  167927. 3456, 3696, 3712, 3728, 3744, 3766, 3832, 3896,
  167928. 3912, 3928, 3944, 3968, 4008, 4040, 4056, 4106,
  167929. 4138, 4170, 4202, 4234, 4266, 4296, 4312, 4344,
  167930. 4408, 4424, 4442, 4472, 4488, 4504, 6148, 6198,
  167931. 6264, 6280, 6360, 6429, 6505, 6529, 61448, 61468,
  167932. 61512, 61534, 61592, 61610, 61642, 61672, 61688, 61704,
  167933. 61726, 61784, 61800, 61816, 61836, 61880, 61896, 61914,
  167934. 61948, 61998, 62062, 62122, 62154, 62184, 62200, 62218,
  167935. 62252, 62302, 62364, 62410, 62442, 62478, 62536, 62554,
  167936. 62584, 62604, 62640, 62648, 62656, 62664, 62730, 62766,
  167937. 62830, 62890, 62924, 62974, 63032, 63050, 63082, 63118,
  167938. 63182, 63242, 63274, 63310, 63368, 63390,
  167939. };
  167940. #define HIBIT ((unsigned char)0x80)
  167941. unsigned char aChar[] = {
  167942. '\0', 'a', 'c', 'e', 'i', 'n',
  167943. 'o', 'u', 'y', 'y', 'a', 'c',
  167944. 'd', 'e', 'e', 'g', 'h', 'i',
  167945. 'j', 'k', 'l', 'n', 'o', 'r',
  167946. 's', 't', 'u', 'u', 'w', 'y',
  167947. 'z', 'o', 'u', 'a', 'i', 'o',
  167948. 'u', 'u'|HIBIT, 'a'|HIBIT, 'g', 'k', 'o',
  167949. 'o'|HIBIT, 'j', 'g', 'n', 'a'|HIBIT, 'a',
  167950. 'e', 'i', 'o', 'r', 'u', 's',
  167951. 't', 'h', 'a', 'e', 'o'|HIBIT, 'o',
  167952. 'o'|HIBIT, 'y', '\0', '\0', '\0', '\0',
  167953. '\0', '\0', '\0', '\0', 'a', 'b',
  167954. 'c'|HIBIT, 'd', 'd', 'e'|HIBIT, 'e', 'e'|HIBIT,
  167955. 'f', 'g', 'h', 'h', 'i', 'i'|HIBIT,
  167956. 'k', 'l', 'l'|HIBIT, 'l', 'm', 'n',
  167957. 'o'|HIBIT, 'p', 'r', 'r'|HIBIT, 'r', 's',
  167958. 's'|HIBIT, 't', 'u', 'u'|HIBIT, 'v', 'w',
  167959. 'w', 'x', 'y', 'z', 'h', 't',
  167960. 'w', 'y', 'a', 'a'|HIBIT, 'a'|HIBIT, 'a'|HIBIT,
  167961. 'e', 'e'|HIBIT, 'e'|HIBIT, 'i', 'o', 'o'|HIBIT,
  167962. 'o'|HIBIT, 'o'|HIBIT, 'u', 'u'|HIBIT, 'u'|HIBIT, 'y',
  167963. };
  167964. unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
  167965. int iRes = 0;
  167966. int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
  167967. int iLo = 0;
  167968. while( iHi>=iLo ){
  167969. int iTest = (iHi + iLo) / 2;
  167970. if( key >= aDia[iTest] ){
  167971. iRes = iTest;
  167972. iLo = iTest+1;
  167973. }else{
  167974. iHi = iTest-1;
  167975. }
  167976. }
  167977. assert( key>=aDia[iRes] );
  167978. if( bComplex==0 && (aChar[iRes] & 0x80) ) return c;
  167979. return (c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : ((int)aChar[iRes] & 0x7F);
  167980. }
  167981. /*
  167982. ** Return true if the argument interpreted as a unicode codepoint
  167983. ** is a diacritical modifier character.
  167984. */
  167985. SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){
  167986. unsigned int mask0 = 0x08029FDF;
  167987. unsigned int mask1 = 0x000361F8;
  167988. if( c<768 || c>817 ) return 0;
  167989. return (c < 768+32) ?
  167990. (mask0 & ((unsigned int)1 << (c-768))) :
  167991. (mask1 & ((unsigned int)1 << (c-768-32)));
  167992. }
  167993. /*
  167994. ** Interpret the argument as a unicode codepoint. If the codepoint
  167995. ** is an upper case character that has a lower case equivalent,
  167996. ** return the codepoint corresponding to the lower case version.
  167997. ** Otherwise, return a copy of the argument.
  167998. **
  167999. ** The results are undefined if the value passed to this function
  168000. ** is less than zero.
  168001. */
  168002. SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int eRemoveDiacritic){
  168003. /* Each entry in the following array defines a rule for folding a range
  168004. ** of codepoints to lower case. The rule applies to a range of nRange
  168005. ** codepoints starting at codepoint iCode.
  168006. **
  168007. ** If the least significant bit in flags is clear, then the rule applies
  168008. ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
  168009. ** need to be folded). Or, if it is set, then the rule only applies to
  168010. ** every second codepoint in the range, starting with codepoint C.
  168011. **
  168012. ** The 7 most significant bits in flags are an index into the aiOff[]
  168013. ** array. If a specific codepoint C does require folding, then its lower
  168014. ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
  168015. **
  168016. ** The contents of this array are generated by parsing the CaseFolding.txt
  168017. ** file distributed as part of the "Unicode Character Database". See
  168018. ** http://www.unicode.org for details.
  168019. */
  168020. static const struct TableEntry {
  168021. unsigned short iCode;
  168022. unsigned char flags;
  168023. unsigned char nRange;
  168024. } aEntry[] = {
  168025. {65, 14, 26}, {181, 64, 1}, {192, 14, 23},
  168026. {216, 14, 7}, {256, 1, 48}, {306, 1, 6},
  168027. {313, 1, 16}, {330, 1, 46}, {376, 116, 1},
  168028. {377, 1, 6}, {383, 104, 1}, {385, 50, 1},
  168029. {386, 1, 4}, {390, 44, 1}, {391, 0, 1},
  168030. {393, 42, 2}, {395, 0, 1}, {398, 32, 1},
  168031. {399, 38, 1}, {400, 40, 1}, {401, 0, 1},
  168032. {403, 42, 1}, {404, 46, 1}, {406, 52, 1},
  168033. {407, 48, 1}, {408, 0, 1}, {412, 52, 1},
  168034. {413, 54, 1}, {415, 56, 1}, {416, 1, 6},
  168035. {422, 60, 1}, {423, 0, 1}, {425, 60, 1},
  168036. {428, 0, 1}, {430, 60, 1}, {431, 0, 1},
  168037. {433, 58, 2}, {435, 1, 4}, {439, 62, 1},
  168038. {440, 0, 1}, {444, 0, 1}, {452, 2, 1},
  168039. {453, 0, 1}, {455, 2, 1}, {456, 0, 1},
  168040. {458, 2, 1}, {459, 1, 18}, {478, 1, 18},
  168041. {497, 2, 1}, {498, 1, 4}, {502, 122, 1},
  168042. {503, 134, 1}, {504, 1, 40}, {544, 110, 1},
  168043. {546, 1, 18}, {570, 70, 1}, {571, 0, 1},
  168044. {573, 108, 1}, {574, 68, 1}, {577, 0, 1},
  168045. {579, 106, 1}, {580, 28, 1}, {581, 30, 1},
  168046. {582, 1, 10}, {837, 36, 1}, {880, 1, 4},
  168047. {886, 0, 1}, {902, 18, 1}, {904, 16, 3},
  168048. {908, 26, 1}, {910, 24, 2}, {913, 14, 17},
  168049. {931, 14, 9}, {962, 0, 1}, {975, 4, 1},
  168050. {976, 140, 1}, {977, 142, 1}, {981, 146, 1},
  168051. {982, 144, 1}, {984, 1, 24}, {1008, 136, 1},
  168052. {1009, 138, 1}, {1012, 130, 1}, {1013, 128, 1},
  168053. {1015, 0, 1}, {1017, 152, 1}, {1018, 0, 1},
  168054. {1021, 110, 3}, {1024, 34, 16}, {1040, 14, 32},
  168055. {1120, 1, 34}, {1162, 1, 54}, {1216, 6, 1},
  168056. {1217, 1, 14}, {1232, 1, 88}, {1329, 22, 38},
  168057. {4256, 66, 38}, {4295, 66, 1}, {4301, 66, 1},
  168058. {7680, 1, 150}, {7835, 132, 1}, {7838, 96, 1},
  168059. {7840, 1, 96}, {7944, 150, 8}, {7960, 150, 6},
  168060. {7976, 150, 8}, {7992, 150, 8}, {8008, 150, 6},
  168061. {8025, 151, 8}, {8040, 150, 8}, {8072, 150, 8},
  168062. {8088, 150, 8}, {8104, 150, 8}, {8120, 150, 2},
  168063. {8122, 126, 2}, {8124, 148, 1}, {8126, 100, 1},
  168064. {8136, 124, 4}, {8140, 148, 1}, {8152, 150, 2},
  168065. {8154, 120, 2}, {8168, 150, 2}, {8170, 118, 2},
  168066. {8172, 152, 1}, {8184, 112, 2}, {8186, 114, 2},
  168067. {8188, 148, 1}, {8486, 98, 1}, {8490, 92, 1},
  168068. {8491, 94, 1}, {8498, 12, 1}, {8544, 8, 16},
  168069. {8579, 0, 1}, {9398, 10, 26}, {11264, 22, 47},
  168070. {11360, 0, 1}, {11362, 88, 1}, {11363, 102, 1},
  168071. {11364, 90, 1}, {11367, 1, 6}, {11373, 84, 1},
  168072. {11374, 86, 1}, {11375, 80, 1}, {11376, 82, 1},
  168073. {11378, 0, 1}, {11381, 0, 1}, {11390, 78, 2},
  168074. {11392, 1, 100}, {11499, 1, 4}, {11506, 0, 1},
  168075. {42560, 1, 46}, {42624, 1, 24}, {42786, 1, 14},
  168076. {42802, 1, 62}, {42873, 1, 4}, {42877, 76, 1},
  168077. {42878, 1, 10}, {42891, 0, 1}, {42893, 74, 1},
  168078. {42896, 1, 4}, {42912, 1, 10}, {42922, 72, 1},
  168079. {65313, 14, 26},
  168080. };
  168081. static const unsigned short aiOff[] = {
  168082. 1, 2, 8, 15, 16, 26, 28, 32,
  168083. 37, 38, 40, 48, 63, 64, 69, 71,
  168084. 79, 80, 116, 202, 203, 205, 206, 207,
  168085. 209, 210, 211, 213, 214, 217, 218, 219,
  168086. 775, 7264, 10792, 10795, 23228, 23256, 30204, 54721,
  168087. 54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
  168088. 57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
  168089. 65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
  168090. 65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
  168091. 65514, 65521, 65527, 65528, 65529,
  168092. };
  168093. int ret = c;
  168094. assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
  168095. if( c<128 ){
  168096. if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
  168097. }else if( c<65536 ){
  168098. const struct TableEntry *p;
  168099. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  168100. int iLo = 0;
  168101. int iRes = -1;
  168102. assert( c>aEntry[0].iCode );
  168103. while( iHi>=iLo ){
  168104. int iTest = (iHi + iLo) / 2;
  168105. int cmp = (c - aEntry[iTest].iCode);
  168106. if( cmp>=0 ){
  168107. iRes = iTest;
  168108. iLo = iTest+1;
  168109. }else{
  168110. iHi = iTest-1;
  168111. }
  168112. }
  168113. assert( iRes>=0 && c>=aEntry[iRes].iCode );
  168114. p = &aEntry[iRes];
  168115. if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
  168116. ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
  168117. assert( ret>0 );
  168118. }
  168119. if( eRemoveDiacritic ){
  168120. ret = remove_diacritic(ret, eRemoveDiacritic==2);
  168121. }
  168122. }
  168123. else if( c>=66560 && c<66600 ){
  168124. ret = c + 40;
  168125. }
  168126. return ret;
  168127. }
  168128. #endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */
  168129. #endif /* !defined(SQLITE_DISABLE_FTS3_UNICODE) */
  168130. /************** End of fts3_unicode2.c ***************************************/
  168131. /************** Begin file json1.c *******************************************/
  168132. /*
  168133. ** 2015-08-12
  168134. **
  168135. ** The author disclaims copyright to this source code. In place of
  168136. ** a legal notice, here is a blessing:
  168137. **
  168138. ** May you do good and not evil.
  168139. ** May you find forgiveness for yourself and forgive others.
  168140. ** May you share freely, never taking more than you give.
  168141. **
  168142. ******************************************************************************
  168143. **
  168144. ** This SQLite extension implements JSON functions. The interface is
  168145. ** modeled after MySQL JSON functions:
  168146. **
  168147. ** https://dev.mysql.com/doc/refman/5.7/en/json.html
  168148. **
  168149. ** For the time being, all JSON is stored as pure text. (We might add
  168150. ** a JSONB type in the future which stores a binary encoding of JSON in
  168151. ** a BLOB, but there is no support for JSONB in the current implementation.
  168152. ** This implementation parses JSON text at 250 MB/s, so it is hard to see
  168153. ** how JSONB might improve on that.)
  168154. */
  168155. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1)
  168156. #if !defined(SQLITEINT_H)
  168157. /* #include "sqlite3ext.h" */
  168158. #endif
  168159. SQLITE_EXTENSION_INIT1
  168160. /* #include <assert.h> */
  168161. /* #include <string.h> */
  168162. /* #include <stdlib.h> */
  168163. /* #include <stdarg.h> */
  168164. /* Mark a function parameter as unused, to suppress nuisance compiler
  168165. ** warnings. */
  168166. #ifndef UNUSED_PARAM
  168167. # define UNUSED_PARAM(X) (void)(X)
  168168. #endif
  168169. #ifndef LARGEST_INT64
  168170. # define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
  168171. # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
  168172. #endif
  168173. /*
  168174. ** Versions of isspace(), isalnum() and isdigit() to which it is safe
  168175. ** to pass signed char values.
  168176. */
  168177. #ifdef sqlite3Isdigit
  168178. /* Use the SQLite core versions if this routine is part of the
  168179. ** SQLite amalgamation */
  168180. # define safe_isdigit(x) sqlite3Isdigit(x)
  168181. # define safe_isalnum(x) sqlite3Isalnum(x)
  168182. # define safe_isxdigit(x) sqlite3Isxdigit(x)
  168183. #else
  168184. /* Use the standard library for separate compilation */
  168185. #include <ctype.h> /* amalgamator: keep */
  168186. # define safe_isdigit(x) isdigit((unsigned char)(x))
  168187. # define safe_isalnum(x) isalnum((unsigned char)(x))
  168188. # define safe_isxdigit(x) isxdigit((unsigned char)(x))
  168189. #endif
  168190. /*
  168191. ** Growing our own isspace() routine this way is twice as fast as
  168192. ** the library isspace() function, resulting in a 7% overall performance
  168193. ** increase for the parser. (Ubuntu14.10 gcc 4.8.4 x64 with -Os).
  168194. */
  168195. static const char jsonIsSpace[] = {
  168196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0,
  168197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  168198. 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  168199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  168200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  168201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  168202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  168203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  168204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  168205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  168206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  168207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  168208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  168209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  168210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  168211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  168212. };
  168213. #define safe_isspace(x) (jsonIsSpace[(unsigned char)x])
  168214. #ifndef SQLITE_AMALGAMATION
  168215. /* Unsigned integer types. These are already defined in the sqliteInt.h,
  168216. ** but the definitions need to be repeated for separate compilation. */
  168217. typedef sqlite3_uint64 u64;
  168218. typedef unsigned int u32;
  168219. typedef unsigned short int u16;
  168220. typedef unsigned char u8;
  168221. #endif
  168222. /* Objects */
  168223. typedef struct JsonString JsonString;
  168224. typedef struct JsonNode JsonNode;
  168225. typedef struct JsonParse JsonParse;
  168226. /* An instance of this object represents a JSON string
  168227. ** under construction. Really, this is a generic string accumulator
  168228. ** that can be and is used to create strings other than JSON.
  168229. */
  168230. struct JsonString {
  168231. sqlite3_context *pCtx; /* Function context - put error messages here */
  168232. char *zBuf; /* Append JSON content here */
  168233. u64 nAlloc; /* Bytes of storage available in zBuf[] */
  168234. u64 nUsed; /* Bytes of zBuf[] currently used */
  168235. u8 bStatic; /* True if zBuf is static space */
  168236. u8 bErr; /* True if an error has been encountered */
  168237. char zSpace[100]; /* Initial static space */
  168238. };
  168239. /* JSON type values
  168240. */
  168241. #define JSON_NULL 0
  168242. #define JSON_TRUE 1
  168243. #define JSON_FALSE 2
  168244. #define JSON_INT 3
  168245. #define JSON_REAL 4
  168246. #define JSON_STRING 5
  168247. #define JSON_ARRAY 6
  168248. #define JSON_OBJECT 7
  168249. /* The "subtype" set for JSON values */
  168250. #define JSON_SUBTYPE 74 /* Ascii for "J" */
  168251. /*
  168252. ** Names of the various JSON types:
  168253. */
  168254. static const char * const jsonType[] = {
  168255. "null", "true", "false", "integer", "real", "text", "array", "object"
  168256. };
  168257. /* Bit values for the JsonNode.jnFlag field
  168258. */
  168259. #define JNODE_RAW 0x01 /* Content is raw, not JSON encoded */
  168260. #define JNODE_ESCAPE 0x02 /* Content is text with \ escapes */
  168261. #define JNODE_REMOVE 0x04 /* Do not output */
  168262. #define JNODE_REPLACE 0x08 /* Replace with JsonNode.u.iReplace */
  168263. #define JNODE_PATCH 0x10 /* Patch with JsonNode.u.pPatch */
  168264. #define JNODE_APPEND 0x20 /* More ARRAY/OBJECT entries at u.iAppend */
  168265. #define JNODE_LABEL 0x40 /* Is a label of an object */
  168266. /* A single node of parsed JSON
  168267. */
  168268. struct JsonNode {
  168269. u8 eType; /* One of the JSON_ type values */
  168270. u8 jnFlags; /* JNODE flags */
  168271. u32 n; /* Bytes of content, or number of sub-nodes */
  168272. union {
  168273. const char *zJContent; /* Content for INT, REAL, and STRING */
  168274. u32 iAppend; /* More terms for ARRAY and OBJECT */
  168275. u32 iKey; /* Key for ARRAY objects in json_tree() */
  168276. u32 iReplace; /* Replacement content for JNODE_REPLACE */
  168277. JsonNode *pPatch; /* Node chain of patch for JNODE_PATCH */
  168278. } u;
  168279. };
  168280. /* A completely parsed JSON string
  168281. */
  168282. struct JsonParse {
  168283. u32 nNode; /* Number of slots of aNode[] used */
  168284. u32 nAlloc; /* Number of slots of aNode[] allocated */
  168285. JsonNode *aNode; /* Array of nodes containing the parse */
  168286. const char *zJson; /* Original JSON string */
  168287. u32 *aUp; /* Index of parent of each node */
  168288. u8 oom; /* Set to true if out of memory */
  168289. u8 nErr; /* Number of errors seen */
  168290. u16 iDepth; /* Nesting depth */
  168291. int nJson; /* Length of the zJson string in bytes */
  168292. u32 iHold; /* Replace cache line with the lowest iHold value */
  168293. };
  168294. /*
  168295. ** Maximum nesting depth of JSON for this implementation.
  168296. **
  168297. ** This limit is needed to avoid a stack overflow in the recursive
  168298. ** descent parser. A depth of 2000 is far deeper than any sane JSON
  168299. ** should go.
  168300. */
  168301. #define JSON_MAX_DEPTH 2000
  168302. /**************************************************************************
  168303. ** Utility routines for dealing with JsonString objects
  168304. **************************************************************************/
  168305. /* Set the JsonString object to an empty string
  168306. */
  168307. static void jsonZero(JsonString *p){
  168308. p->zBuf = p->zSpace;
  168309. p->nAlloc = sizeof(p->zSpace);
  168310. p->nUsed = 0;
  168311. p->bStatic = 1;
  168312. }
  168313. /* Initialize the JsonString object
  168314. */
  168315. static void jsonInit(JsonString *p, sqlite3_context *pCtx){
  168316. p->pCtx = pCtx;
  168317. p->bErr = 0;
  168318. jsonZero(p);
  168319. }
  168320. /* Free all allocated memory and reset the JsonString object back to its
  168321. ** initial state.
  168322. */
  168323. static void jsonReset(JsonString *p){
  168324. if( !p->bStatic ) sqlite3_free(p->zBuf);
  168325. jsonZero(p);
  168326. }
  168327. /* Report an out-of-memory (OOM) condition
  168328. */
  168329. static void jsonOom(JsonString *p){
  168330. p->bErr = 1;
  168331. sqlite3_result_error_nomem(p->pCtx);
  168332. jsonReset(p);
  168333. }
  168334. /* Enlarge pJson->zBuf so that it can hold at least N more bytes.
  168335. ** Return zero on success. Return non-zero on an OOM error
  168336. */
  168337. static int jsonGrow(JsonString *p, u32 N){
  168338. u64 nTotal = N<p->nAlloc ? p->nAlloc*2 : p->nAlloc+N+10;
  168339. char *zNew;
  168340. if( p->bStatic ){
  168341. if( p->bErr ) return 1;
  168342. zNew = sqlite3_malloc64(nTotal);
  168343. if( zNew==0 ){
  168344. jsonOom(p);
  168345. return SQLITE_NOMEM;
  168346. }
  168347. memcpy(zNew, p->zBuf, (size_t)p->nUsed);
  168348. p->zBuf = zNew;
  168349. p->bStatic = 0;
  168350. }else{
  168351. zNew = sqlite3_realloc64(p->zBuf, nTotal);
  168352. if( zNew==0 ){
  168353. jsonOom(p);
  168354. return SQLITE_NOMEM;
  168355. }
  168356. p->zBuf = zNew;
  168357. }
  168358. p->nAlloc = nTotal;
  168359. return SQLITE_OK;
  168360. }
  168361. /* Append N bytes from zIn onto the end of the JsonString string.
  168362. */
  168363. static void jsonAppendRaw(JsonString *p, const char *zIn, u32 N){
  168364. if( (N+p->nUsed >= p->nAlloc) && jsonGrow(p,N)!=0 ) return;
  168365. memcpy(p->zBuf+p->nUsed, zIn, N);
  168366. p->nUsed += N;
  168367. }
  168368. /* Append formatted text (not to exceed N bytes) to the JsonString.
  168369. */
  168370. static void jsonPrintf(int N, JsonString *p, const char *zFormat, ...){
  168371. va_list ap;
  168372. if( (p->nUsed + N >= p->nAlloc) && jsonGrow(p, N) ) return;
  168373. va_start(ap, zFormat);
  168374. sqlite3_vsnprintf(N, p->zBuf+p->nUsed, zFormat, ap);
  168375. va_end(ap);
  168376. p->nUsed += (int)strlen(p->zBuf+p->nUsed);
  168377. }
  168378. /* Append a single character
  168379. */
  168380. static void jsonAppendChar(JsonString *p, char c){
  168381. if( p->nUsed>=p->nAlloc && jsonGrow(p,1)!=0 ) return;
  168382. p->zBuf[p->nUsed++] = c;
  168383. }
  168384. /* Append a comma separator to the output buffer, if the previous
  168385. ** character is not '[' or '{'.
  168386. */
  168387. static void jsonAppendSeparator(JsonString *p){
  168388. char c;
  168389. if( p->nUsed==0 ) return;
  168390. c = p->zBuf[p->nUsed-1];
  168391. if( c!='[' && c!='{' ) jsonAppendChar(p, ',');
  168392. }
  168393. /* Append the N-byte string in zIn to the end of the JsonString string
  168394. ** under construction. Enclose the string in "..." and escape
  168395. ** any double-quotes or backslash characters contained within the
  168396. ** string.
  168397. */
  168398. static void jsonAppendString(JsonString *p, const char *zIn, u32 N){
  168399. u32 i;
  168400. if( (N+p->nUsed+2 >= p->nAlloc) && jsonGrow(p,N+2)!=0 ) return;
  168401. p->zBuf[p->nUsed++] = '"';
  168402. for(i=0; i<N; i++){
  168403. unsigned char c = ((unsigned const char*)zIn)[i];
  168404. if( c=='"' || c=='\\' ){
  168405. json_simple_escape:
  168406. if( (p->nUsed+N+3-i > p->nAlloc) && jsonGrow(p,N+3-i)!=0 ) return;
  168407. p->zBuf[p->nUsed++] = '\\';
  168408. }else if( c<=0x1f ){
  168409. static const char aSpecial[] = {
  168410. 0, 0, 0, 0, 0, 0, 0, 0, 'b', 't', 'n', 0, 'f', 'r', 0, 0,
  168411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  168412. };
  168413. assert( sizeof(aSpecial)==32 );
  168414. assert( aSpecial['\b']=='b' );
  168415. assert( aSpecial['\f']=='f' );
  168416. assert( aSpecial['\n']=='n' );
  168417. assert( aSpecial['\r']=='r' );
  168418. assert( aSpecial['\t']=='t' );
  168419. if( aSpecial[c] ){
  168420. c = aSpecial[c];
  168421. goto json_simple_escape;
  168422. }
  168423. if( (p->nUsed+N+7+i > p->nAlloc) && jsonGrow(p,N+7-i)!=0 ) return;
  168424. p->zBuf[p->nUsed++] = '\\';
  168425. p->zBuf[p->nUsed++] = 'u';
  168426. p->zBuf[p->nUsed++] = '0';
  168427. p->zBuf[p->nUsed++] = '0';
  168428. p->zBuf[p->nUsed++] = '0' + (c>>4);
  168429. c = "0123456789abcdef"[c&0xf];
  168430. }
  168431. p->zBuf[p->nUsed++] = c;
  168432. }
  168433. p->zBuf[p->nUsed++] = '"';
  168434. assert( p->nUsed<p->nAlloc );
  168435. }
  168436. /*
  168437. ** Append a function parameter value to the JSON string under
  168438. ** construction.
  168439. */
  168440. static void jsonAppendValue(
  168441. JsonString *p, /* Append to this JSON string */
  168442. sqlite3_value *pValue /* Value to append */
  168443. ){
  168444. switch( sqlite3_value_type(pValue) ){
  168445. case SQLITE_NULL: {
  168446. jsonAppendRaw(p, "null", 4);
  168447. break;
  168448. }
  168449. case SQLITE_INTEGER:
  168450. case SQLITE_FLOAT: {
  168451. const char *z = (const char*)sqlite3_value_text(pValue);
  168452. u32 n = (u32)sqlite3_value_bytes(pValue);
  168453. jsonAppendRaw(p, z, n);
  168454. break;
  168455. }
  168456. case SQLITE_TEXT: {
  168457. const char *z = (const char*)sqlite3_value_text(pValue);
  168458. u32 n = (u32)sqlite3_value_bytes(pValue);
  168459. if( sqlite3_value_subtype(pValue)==JSON_SUBTYPE ){
  168460. jsonAppendRaw(p, z, n);
  168461. }else{
  168462. jsonAppendString(p, z, n);
  168463. }
  168464. break;
  168465. }
  168466. default: {
  168467. if( p->bErr==0 ){
  168468. sqlite3_result_error(p->pCtx, "JSON cannot hold BLOB values", -1);
  168469. p->bErr = 2;
  168470. jsonReset(p);
  168471. }
  168472. break;
  168473. }
  168474. }
  168475. }
  168476. /* Make the JSON in p the result of the SQL function.
  168477. */
  168478. static void jsonResult(JsonString *p){
  168479. if( p->bErr==0 ){
  168480. sqlite3_result_text64(p->pCtx, p->zBuf, p->nUsed,
  168481. p->bStatic ? SQLITE_TRANSIENT : sqlite3_free,
  168482. SQLITE_UTF8);
  168483. jsonZero(p);
  168484. }
  168485. assert( p->bStatic );
  168486. }
  168487. /**************************************************************************
  168488. ** Utility routines for dealing with JsonNode and JsonParse objects
  168489. **************************************************************************/
  168490. /*
  168491. ** Return the number of consecutive JsonNode slots need to represent
  168492. ** the parsed JSON at pNode. The minimum answer is 1. For ARRAY and
  168493. ** OBJECT types, the number might be larger.
  168494. **
  168495. ** Appended elements are not counted. The value returned is the number
  168496. ** by which the JsonNode counter should increment in order to go to the
  168497. ** next peer value.
  168498. */
  168499. static u32 jsonNodeSize(JsonNode *pNode){
  168500. return pNode->eType>=JSON_ARRAY ? pNode->n+1 : 1;
  168501. }
  168502. /*
  168503. ** Reclaim all memory allocated by a JsonParse object. But do not
  168504. ** delete the JsonParse object itself.
  168505. */
  168506. static void jsonParseReset(JsonParse *pParse){
  168507. sqlite3_free(pParse->aNode);
  168508. pParse->aNode = 0;
  168509. pParse->nNode = 0;
  168510. pParse->nAlloc = 0;
  168511. sqlite3_free(pParse->aUp);
  168512. pParse->aUp = 0;
  168513. }
  168514. /*
  168515. ** Free a JsonParse object that was obtained from sqlite3_malloc().
  168516. */
  168517. static void jsonParseFree(JsonParse *pParse){
  168518. jsonParseReset(pParse);
  168519. sqlite3_free(pParse);
  168520. }
  168521. /*
  168522. ** Convert the JsonNode pNode into a pure JSON string and
  168523. ** append to pOut. Subsubstructure is also included. Return
  168524. ** the number of JsonNode objects that are encoded.
  168525. */
  168526. static void jsonRenderNode(
  168527. JsonNode *pNode, /* The node to render */
  168528. JsonString *pOut, /* Write JSON here */
  168529. sqlite3_value **aReplace /* Replacement values */
  168530. ){
  168531. if( pNode->jnFlags & (JNODE_REPLACE|JNODE_PATCH) ){
  168532. if( pNode->jnFlags & JNODE_REPLACE ){
  168533. jsonAppendValue(pOut, aReplace[pNode->u.iReplace]);
  168534. return;
  168535. }
  168536. pNode = pNode->u.pPatch;
  168537. }
  168538. switch( pNode->eType ){
  168539. default: {
  168540. assert( pNode->eType==JSON_NULL );
  168541. jsonAppendRaw(pOut, "null", 4);
  168542. break;
  168543. }
  168544. case JSON_TRUE: {
  168545. jsonAppendRaw(pOut, "true", 4);
  168546. break;
  168547. }
  168548. case JSON_FALSE: {
  168549. jsonAppendRaw(pOut, "false", 5);
  168550. break;
  168551. }
  168552. case JSON_STRING: {
  168553. if( pNode->jnFlags & JNODE_RAW ){
  168554. jsonAppendString(pOut, pNode->u.zJContent, pNode->n);
  168555. break;
  168556. }
  168557. /* Fall through into the next case */
  168558. }
  168559. case JSON_REAL:
  168560. case JSON_INT: {
  168561. jsonAppendRaw(pOut, pNode->u.zJContent, pNode->n);
  168562. break;
  168563. }
  168564. case JSON_ARRAY: {
  168565. u32 j = 1;
  168566. jsonAppendChar(pOut, '[');
  168567. for(;;){
  168568. while( j<=pNode->n ){
  168569. if( (pNode[j].jnFlags & JNODE_REMOVE)==0 ){
  168570. jsonAppendSeparator(pOut);
  168571. jsonRenderNode(&pNode[j], pOut, aReplace);
  168572. }
  168573. j += jsonNodeSize(&pNode[j]);
  168574. }
  168575. if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
  168576. pNode = &pNode[pNode->u.iAppend];
  168577. j = 1;
  168578. }
  168579. jsonAppendChar(pOut, ']');
  168580. break;
  168581. }
  168582. case JSON_OBJECT: {
  168583. u32 j = 1;
  168584. jsonAppendChar(pOut, '{');
  168585. for(;;){
  168586. while( j<=pNode->n ){
  168587. if( (pNode[j+1].jnFlags & JNODE_REMOVE)==0 ){
  168588. jsonAppendSeparator(pOut);
  168589. jsonRenderNode(&pNode[j], pOut, aReplace);
  168590. jsonAppendChar(pOut, ':');
  168591. jsonRenderNode(&pNode[j+1], pOut, aReplace);
  168592. }
  168593. j += 1 + jsonNodeSize(&pNode[j+1]);
  168594. }
  168595. if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
  168596. pNode = &pNode[pNode->u.iAppend];
  168597. j = 1;
  168598. }
  168599. jsonAppendChar(pOut, '}');
  168600. break;
  168601. }
  168602. }
  168603. }
  168604. /*
  168605. ** Return a JsonNode and all its descendents as a JSON string.
  168606. */
  168607. static void jsonReturnJson(
  168608. JsonNode *pNode, /* Node to return */
  168609. sqlite3_context *pCtx, /* Return value for this function */
  168610. sqlite3_value **aReplace /* Array of replacement values */
  168611. ){
  168612. JsonString s;
  168613. jsonInit(&s, pCtx);
  168614. jsonRenderNode(pNode, &s, aReplace);
  168615. jsonResult(&s);
  168616. sqlite3_result_subtype(pCtx, JSON_SUBTYPE);
  168617. }
  168618. /*
  168619. ** Make the JsonNode the return value of the function.
  168620. */
  168621. static void jsonReturn(
  168622. JsonNode *pNode, /* Node to return */
  168623. sqlite3_context *pCtx, /* Return value for this function */
  168624. sqlite3_value **aReplace /* Array of replacement values */
  168625. ){
  168626. switch( pNode->eType ){
  168627. default: {
  168628. assert( pNode->eType==JSON_NULL );
  168629. sqlite3_result_null(pCtx);
  168630. break;
  168631. }
  168632. case JSON_TRUE: {
  168633. sqlite3_result_int(pCtx, 1);
  168634. break;
  168635. }
  168636. case JSON_FALSE: {
  168637. sqlite3_result_int(pCtx, 0);
  168638. break;
  168639. }
  168640. case JSON_INT: {
  168641. sqlite3_int64 i = 0;
  168642. const char *z = pNode->u.zJContent;
  168643. if( z[0]=='-' ){ z++; }
  168644. while( z[0]>='0' && z[0]<='9' ){
  168645. unsigned v = *(z++) - '0';
  168646. if( i>=LARGEST_INT64/10 ){
  168647. if( i>LARGEST_INT64/10 ) goto int_as_real;
  168648. if( z[0]>='0' && z[0]<='9' ) goto int_as_real;
  168649. if( v==9 ) goto int_as_real;
  168650. if( v==8 ){
  168651. if( pNode->u.zJContent[0]=='-' ){
  168652. sqlite3_result_int64(pCtx, SMALLEST_INT64);
  168653. goto int_done;
  168654. }else{
  168655. goto int_as_real;
  168656. }
  168657. }
  168658. }
  168659. i = i*10 + v;
  168660. }
  168661. if( pNode->u.zJContent[0]=='-' ){ i = -i; }
  168662. sqlite3_result_int64(pCtx, i);
  168663. int_done:
  168664. break;
  168665. int_as_real: /* fall through to real */;
  168666. }
  168667. case JSON_REAL: {
  168668. double r;
  168669. #ifdef SQLITE_AMALGAMATION
  168670. const char *z = pNode->u.zJContent;
  168671. sqlite3AtoF(z, &r, sqlite3Strlen30(z), SQLITE_UTF8);
  168672. #else
  168673. r = strtod(pNode->u.zJContent, 0);
  168674. #endif
  168675. sqlite3_result_double(pCtx, r);
  168676. break;
  168677. }
  168678. case JSON_STRING: {
  168679. #if 0 /* Never happens because JNODE_RAW is only set by json_set(),
  168680. ** json_insert() and json_replace() and those routines do not
  168681. ** call jsonReturn() */
  168682. if( pNode->jnFlags & JNODE_RAW ){
  168683. sqlite3_result_text(pCtx, pNode->u.zJContent, pNode->n,
  168684. SQLITE_TRANSIENT);
  168685. }else
  168686. #endif
  168687. assert( (pNode->jnFlags & JNODE_RAW)==0 );
  168688. if( (pNode->jnFlags & JNODE_ESCAPE)==0 ){
  168689. /* JSON formatted without any backslash-escapes */
  168690. sqlite3_result_text(pCtx, pNode->u.zJContent+1, pNode->n-2,
  168691. SQLITE_TRANSIENT);
  168692. }else{
  168693. /* Translate JSON formatted string into raw text */
  168694. u32 i;
  168695. u32 n = pNode->n;
  168696. const char *z = pNode->u.zJContent;
  168697. char *zOut;
  168698. u32 j;
  168699. zOut = sqlite3_malloc( n+1 );
  168700. if( zOut==0 ){
  168701. sqlite3_result_error_nomem(pCtx);
  168702. break;
  168703. }
  168704. for(i=1, j=0; i<n-1; i++){
  168705. char c = z[i];
  168706. if( c!='\\' ){
  168707. zOut[j++] = c;
  168708. }else{
  168709. c = z[++i];
  168710. if( c=='u' ){
  168711. u32 v = 0, k;
  168712. for(k=0; k<4; i++, k++){
  168713. assert( i<n-2 );
  168714. c = z[i+1];
  168715. assert( safe_isxdigit(c) );
  168716. if( c<='9' ) v = v*16 + c - '0';
  168717. else if( c<='F' ) v = v*16 + c - 'A' + 10;
  168718. else v = v*16 + c - 'a' + 10;
  168719. }
  168720. if( v==0 ) break;
  168721. if( v<=0x7f ){
  168722. zOut[j++] = (char)v;
  168723. }else if( v<=0x7ff ){
  168724. zOut[j++] = (char)(0xc0 | (v>>6));
  168725. zOut[j++] = 0x80 | (v&0x3f);
  168726. }else{
  168727. zOut[j++] = (char)(0xe0 | (v>>12));
  168728. zOut[j++] = 0x80 | ((v>>6)&0x3f);
  168729. zOut[j++] = 0x80 | (v&0x3f);
  168730. }
  168731. }else{
  168732. if( c=='b' ){
  168733. c = '\b';
  168734. }else if( c=='f' ){
  168735. c = '\f';
  168736. }else if( c=='n' ){
  168737. c = '\n';
  168738. }else if( c=='r' ){
  168739. c = '\r';
  168740. }else if( c=='t' ){
  168741. c = '\t';
  168742. }
  168743. zOut[j++] = c;
  168744. }
  168745. }
  168746. }
  168747. zOut[j] = 0;
  168748. sqlite3_result_text(pCtx, zOut, j, sqlite3_free);
  168749. }
  168750. break;
  168751. }
  168752. case JSON_ARRAY:
  168753. case JSON_OBJECT: {
  168754. jsonReturnJson(pNode, pCtx, aReplace);
  168755. break;
  168756. }
  168757. }
  168758. }
  168759. /* Forward reference */
  168760. static int jsonParseAddNode(JsonParse*,u32,u32,const char*);
  168761. /*
  168762. ** A macro to hint to the compiler that a function should not be
  168763. ** inlined.
  168764. */
  168765. #if defined(__GNUC__)
  168766. # define JSON_NOINLINE __attribute__((noinline))
  168767. #elif defined(_MSC_VER) && _MSC_VER>=1310
  168768. # define JSON_NOINLINE __declspec(noinline)
  168769. #else
  168770. # define JSON_NOINLINE
  168771. #endif
  168772. static JSON_NOINLINE int jsonParseAddNodeExpand(
  168773. JsonParse *pParse, /* Append the node to this object */
  168774. u32 eType, /* Node type */
  168775. u32 n, /* Content size or sub-node count */
  168776. const char *zContent /* Content */
  168777. ){
  168778. u32 nNew;
  168779. JsonNode *pNew;
  168780. assert( pParse->nNode>=pParse->nAlloc );
  168781. if( pParse->oom ) return -1;
  168782. nNew = pParse->nAlloc*2 + 10;
  168783. pNew = sqlite3_realloc64(pParse->aNode, sizeof(JsonNode)*nNew);
  168784. if( pNew==0 ){
  168785. pParse->oom = 1;
  168786. return -1;
  168787. }
  168788. pParse->nAlloc = nNew;
  168789. pParse->aNode = pNew;
  168790. assert( pParse->nNode<pParse->nAlloc );
  168791. return jsonParseAddNode(pParse, eType, n, zContent);
  168792. }
  168793. /*
  168794. ** Create a new JsonNode instance based on the arguments and append that
  168795. ** instance to the JsonParse. Return the index in pParse->aNode[] of the
  168796. ** new node, or -1 if a memory allocation fails.
  168797. */
  168798. static int jsonParseAddNode(
  168799. JsonParse *pParse, /* Append the node to this object */
  168800. u32 eType, /* Node type */
  168801. u32 n, /* Content size or sub-node count */
  168802. const char *zContent /* Content */
  168803. ){
  168804. JsonNode *p;
  168805. if( pParse->nNode>=pParse->nAlloc ){
  168806. return jsonParseAddNodeExpand(pParse, eType, n, zContent);
  168807. }
  168808. p = &pParse->aNode[pParse->nNode];
  168809. p->eType = (u8)eType;
  168810. p->jnFlags = 0;
  168811. p->n = n;
  168812. p->u.zJContent = zContent;
  168813. return pParse->nNode++;
  168814. }
  168815. /*
  168816. ** Return true if z[] begins with 4 (or more) hexadecimal digits
  168817. */
  168818. static int jsonIs4Hex(const char *z){
  168819. int i;
  168820. for(i=0; i<4; i++) if( !safe_isxdigit(z[i]) ) return 0;
  168821. return 1;
  168822. }
  168823. /*
  168824. ** Parse a single JSON value which begins at pParse->zJson[i]. Return the
  168825. ** index of the first character past the end of the value parsed.
  168826. **
  168827. ** Return negative for a syntax error. Special cases: return -2 if the
  168828. ** first non-whitespace character is '}' and return -3 if the first
  168829. ** non-whitespace character is ']'.
  168830. */
  168831. static int jsonParseValue(JsonParse *pParse, u32 i){
  168832. char c;
  168833. u32 j;
  168834. int iThis;
  168835. int x;
  168836. JsonNode *pNode;
  168837. const char *z = pParse->zJson;
  168838. while( safe_isspace(z[i]) ){ i++; }
  168839. if( (c = z[i])=='{' ){
  168840. /* Parse object */
  168841. iThis = jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
  168842. if( iThis<0 ) return -1;
  168843. for(j=i+1;;j++){
  168844. while( safe_isspace(z[j]) ){ j++; }
  168845. if( ++pParse->iDepth > JSON_MAX_DEPTH ) return -1;
  168846. x = jsonParseValue(pParse, j);
  168847. if( x<0 ){
  168848. pParse->iDepth--;
  168849. if( x==(-2) && pParse->nNode==(u32)iThis+1 ) return j+1;
  168850. return -1;
  168851. }
  168852. if( pParse->oom ) return -1;
  168853. pNode = &pParse->aNode[pParse->nNode-1];
  168854. if( pNode->eType!=JSON_STRING ) return -1;
  168855. pNode->jnFlags |= JNODE_LABEL;
  168856. j = x;
  168857. while( safe_isspace(z[j]) ){ j++; }
  168858. if( z[j]!=':' ) return -1;
  168859. j++;
  168860. x = jsonParseValue(pParse, j);
  168861. pParse->iDepth--;
  168862. if( x<0 ) return -1;
  168863. j = x;
  168864. while( safe_isspace(z[j]) ){ j++; }
  168865. c = z[j];
  168866. if( c==',' ) continue;
  168867. if( c!='}' ) return -1;
  168868. break;
  168869. }
  168870. pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
  168871. return j+1;
  168872. }else if( c=='[' ){
  168873. /* Parse array */
  168874. iThis = jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
  168875. if( iThis<0 ) return -1;
  168876. for(j=i+1;;j++){
  168877. while( safe_isspace(z[j]) ){ j++; }
  168878. if( ++pParse->iDepth > JSON_MAX_DEPTH ) return -1;
  168879. x = jsonParseValue(pParse, j);
  168880. pParse->iDepth--;
  168881. if( x<0 ){
  168882. if( x==(-3) && pParse->nNode==(u32)iThis+1 ) return j+1;
  168883. return -1;
  168884. }
  168885. j = x;
  168886. while( safe_isspace(z[j]) ){ j++; }
  168887. c = z[j];
  168888. if( c==',' ) continue;
  168889. if( c!=']' ) return -1;
  168890. break;
  168891. }
  168892. pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
  168893. return j+1;
  168894. }else if( c=='"' ){
  168895. /* Parse string */
  168896. u8 jnFlags = 0;
  168897. j = i+1;
  168898. for(;;){
  168899. c = z[j];
  168900. if( (c & ~0x1f)==0 ){
  168901. /* Control characters are not allowed in strings */
  168902. return -1;
  168903. }
  168904. if( c=='\\' ){
  168905. c = z[++j];
  168906. if( c=='"' || c=='\\' || c=='/' || c=='b' || c=='f'
  168907. || c=='n' || c=='r' || c=='t'
  168908. || (c=='u' && jsonIs4Hex(z+j+1)) ){
  168909. jnFlags = JNODE_ESCAPE;
  168910. }else{
  168911. return -1;
  168912. }
  168913. }else if( c=='"' ){
  168914. break;
  168915. }
  168916. j++;
  168917. }
  168918. jsonParseAddNode(pParse, JSON_STRING, j+1-i, &z[i]);
  168919. if( !pParse->oom ) pParse->aNode[pParse->nNode-1].jnFlags = jnFlags;
  168920. return j+1;
  168921. }else if( c=='n'
  168922. && strncmp(z+i,"null",4)==0
  168923. && !safe_isalnum(z[i+4]) ){
  168924. jsonParseAddNode(pParse, JSON_NULL, 0, 0);
  168925. return i+4;
  168926. }else if( c=='t'
  168927. && strncmp(z+i,"true",4)==0
  168928. && !safe_isalnum(z[i+4]) ){
  168929. jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
  168930. return i+4;
  168931. }else if( c=='f'
  168932. && strncmp(z+i,"false",5)==0
  168933. && !safe_isalnum(z[i+5]) ){
  168934. jsonParseAddNode(pParse, JSON_FALSE, 0, 0);
  168935. return i+5;
  168936. }else if( c=='-' || (c>='0' && c<='9') ){
  168937. /* Parse number */
  168938. u8 seenDP = 0;
  168939. u8 seenE = 0;
  168940. assert( '-' < '0' );
  168941. if( c<='0' ){
  168942. j = c=='-' ? i+1 : i;
  168943. if( z[j]=='0' && z[j+1]>='0' && z[j+1]<='9' ) return -1;
  168944. }
  168945. j = i+1;
  168946. for(;; j++){
  168947. c = z[j];
  168948. if( c>='0' && c<='9' ) continue;
  168949. if( c=='.' ){
  168950. if( z[j-1]=='-' ) return -1;
  168951. if( seenDP ) return -1;
  168952. seenDP = 1;
  168953. continue;
  168954. }
  168955. if( c=='e' || c=='E' ){
  168956. if( z[j-1]<'0' ) return -1;
  168957. if( seenE ) return -1;
  168958. seenDP = seenE = 1;
  168959. c = z[j+1];
  168960. if( c=='+' || c=='-' ){
  168961. j++;
  168962. c = z[j+1];
  168963. }
  168964. if( c<'0' || c>'9' ) return -1;
  168965. continue;
  168966. }
  168967. break;
  168968. }
  168969. if( z[j-1]<'0' ) return -1;
  168970. jsonParseAddNode(pParse, seenDP ? JSON_REAL : JSON_INT,
  168971. j - i, &z[i]);
  168972. return j;
  168973. }else if( c=='}' ){
  168974. return -2; /* End of {...} */
  168975. }else if( c==']' ){
  168976. return -3; /* End of [...] */
  168977. }else if( c==0 ){
  168978. return 0; /* End of file */
  168979. }else{
  168980. return -1; /* Syntax error */
  168981. }
  168982. }
  168983. /*
  168984. ** Parse a complete JSON string. Return 0 on success or non-zero if there
  168985. ** are any errors. If an error occurs, free all memory associated with
  168986. ** pParse.
  168987. **
  168988. ** pParse is uninitialized when this routine is called.
  168989. */
  168990. static int jsonParse(
  168991. JsonParse *pParse, /* Initialize and fill this JsonParse object */
  168992. sqlite3_context *pCtx, /* Report errors here */
  168993. const char *zJson /* Input JSON text to be parsed */
  168994. ){
  168995. int i;
  168996. memset(pParse, 0, sizeof(*pParse));
  168997. if( zJson==0 ) return 1;
  168998. pParse->zJson = zJson;
  168999. i = jsonParseValue(pParse, 0);
  169000. if( pParse->oom ) i = -1;
  169001. if( i>0 ){
  169002. assert( pParse->iDepth==0 );
  169003. while( safe_isspace(zJson[i]) ) i++;
  169004. if( zJson[i] ) i = -1;
  169005. }
  169006. if( i<=0 ){
  169007. if( pCtx!=0 ){
  169008. if( pParse->oom ){
  169009. sqlite3_result_error_nomem(pCtx);
  169010. }else{
  169011. sqlite3_result_error(pCtx, "malformed JSON", -1);
  169012. }
  169013. }
  169014. jsonParseReset(pParse);
  169015. return 1;
  169016. }
  169017. return 0;
  169018. }
  169019. /* Mark node i of pParse as being a child of iParent. Call recursively
  169020. ** to fill in all the descendants of node i.
  169021. */
  169022. static void jsonParseFillInParentage(JsonParse *pParse, u32 i, u32 iParent){
  169023. JsonNode *pNode = &pParse->aNode[i];
  169024. u32 j;
  169025. pParse->aUp[i] = iParent;
  169026. switch( pNode->eType ){
  169027. case JSON_ARRAY: {
  169028. for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j)){
  169029. jsonParseFillInParentage(pParse, i+j, i);
  169030. }
  169031. break;
  169032. }
  169033. case JSON_OBJECT: {
  169034. for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j+1)+1){
  169035. pParse->aUp[i+j] = i;
  169036. jsonParseFillInParentage(pParse, i+j+1, i);
  169037. }
  169038. break;
  169039. }
  169040. default: {
  169041. break;
  169042. }
  169043. }
  169044. }
  169045. /*
  169046. ** Compute the parentage of all nodes in a completed parse.
  169047. */
  169048. static int jsonParseFindParents(JsonParse *pParse){
  169049. u32 *aUp;
  169050. assert( pParse->aUp==0 );
  169051. aUp = pParse->aUp = sqlite3_malloc64( sizeof(u32)*pParse->nNode );
  169052. if( aUp==0 ){
  169053. pParse->oom = 1;
  169054. return SQLITE_NOMEM;
  169055. }
  169056. jsonParseFillInParentage(pParse, 0, 0);
  169057. return SQLITE_OK;
  169058. }
  169059. /*
  169060. ** Magic number used for the JSON parse cache in sqlite3_get_auxdata()
  169061. */
  169062. #define JSON_CACHE_ID (-429938) /* First cache entry */
  169063. #define JSON_CACHE_SZ 4 /* Max number of cache entries */
  169064. /*
  169065. ** Obtain a complete parse of the JSON found in the first argument
  169066. ** of the argv array. Use the sqlite3_get_auxdata() cache for this
  169067. ** parse if it is available. If the cache is not available or if it
  169068. ** is no longer valid, parse the JSON again and return the new parse,
  169069. ** and also register the new parse so that it will be available for
  169070. ** future sqlite3_get_auxdata() calls.
  169071. */
  169072. static JsonParse *jsonParseCached(
  169073. sqlite3_context *pCtx,
  169074. sqlite3_value **argv,
  169075. sqlite3_context *pErrCtx
  169076. ){
  169077. const char *zJson = (const char*)sqlite3_value_text(argv[0]);
  169078. int nJson = sqlite3_value_bytes(argv[0]);
  169079. JsonParse *p;
  169080. JsonParse *pMatch = 0;
  169081. int iKey;
  169082. int iMinKey = 0;
  169083. u32 iMinHold = 0xffffffff;
  169084. u32 iMaxHold = 0;
  169085. if( zJson==0 ) return 0;
  169086. for(iKey=0; iKey<JSON_CACHE_SZ; iKey++){
  169087. p = (JsonParse*)sqlite3_get_auxdata(pCtx, JSON_CACHE_ID+iKey);
  169088. if( p==0 ){
  169089. iMinKey = iKey;
  169090. break;
  169091. }
  169092. if( pMatch==0
  169093. && p->nJson==nJson
  169094. && memcmp(p->zJson,zJson,nJson)==0
  169095. ){
  169096. p->nErr = 0;
  169097. pMatch = p;
  169098. }else if( p->iHold<iMinHold ){
  169099. iMinHold = p->iHold;
  169100. iMinKey = iKey;
  169101. }
  169102. if( p->iHold>iMaxHold ){
  169103. iMaxHold = p->iHold;
  169104. }
  169105. }
  169106. if( pMatch ){
  169107. pMatch->nErr = 0;
  169108. pMatch->iHold = iMaxHold+1;
  169109. return pMatch;
  169110. }
  169111. p = sqlite3_malloc64( sizeof(*p) + nJson + 1 );
  169112. if( p==0 ){
  169113. sqlite3_result_error_nomem(pCtx);
  169114. return 0;
  169115. }
  169116. memset(p, 0, sizeof(*p));
  169117. p->zJson = (char*)&p[1];
  169118. memcpy((char*)p->zJson, zJson, nJson+1);
  169119. if( jsonParse(p, pErrCtx, p->zJson) ){
  169120. sqlite3_free(p);
  169121. return 0;
  169122. }
  169123. p->nJson = nJson;
  169124. p->iHold = iMaxHold+1;
  169125. sqlite3_set_auxdata(pCtx, JSON_CACHE_ID+iMinKey, p,
  169126. (void(*)(void*))jsonParseFree);
  169127. return (JsonParse*)sqlite3_get_auxdata(pCtx, JSON_CACHE_ID+iMinKey);
  169128. }
  169129. /*
  169130. ** Compare the OBJECT label at pNode against zKey,nKey. Return true on
  169131. ** a match.
  169132. */
  169133. static int jsonLabelCompare(JsonNode *pNode, const char *zKey, u32 nKey){
  169134. if( pNode->jnFlags & JNODE_RAW ){
  169135. if( pNode->n!=nKey ) return 0;
  169136. return strncmp(pNode->u.zJContent, zKey, nKey)==0;
  169137. }else{
  169138. if( pNode->n!=nKey+2 ) return 0;
  169139. return strncmp(pNode->u.zJContent+1, zKey, nKey)==0;
  169140. }
  169141. }
  169142. /* forward declaration */
  169143. static JsonNode *jsonLookupAppend(JsonParse*,const char*,int*,const char**);
  169144. /*
  169145. ** Search along zPath to find the node specified. Return a pointer
  169146. ** to that node, or NULL if zPath is malformed or if there is no such
  169147. ** node.
  169148. **
  169149. ** If pApnd!=0, then try to append new nodes to complete zPath if it is
  169150. ** possible to do so and if no existing node corresponds to zPath. If
  169151. ** new nodes are appended *pApnd is set to 1.
  169152. */
  169153. static JsonNode *jsonLookupStep(
  169154. JsonParse *pParse, /* The JSON to search */
  169155. u32 iRoot, /* Begin the search at this node */
  169156. const char *zPath, /* The path to search */
  169157. int *pApnd, /* Append nodes to complete path if not NULL */
  169158. const char **pzErr /* Make *pzErr point to any syntax error in zPath */
  169159. ){
  169160. u32 i, j, nKey;
  169161. const char *zKey;
  169162. JsonNode *pRoot = &pParse->aNode[iRoot];
  169163. if( zPath[0]==0 ) return pRoot;
  169164. if( zPath[0]=='.' ){
  169165. if( pRoot->eType!=JSON_OBJECT ) return 0;
  169166. zPath++;
  169167. if( zPath[0]=='"' ){
  169168. zKey = zPath + 1;
  169169. for(i=1; zPath[i] && zPath[i]!='"'; i++){}
  169170. nKey = i-1;
  169171. if( zPath[i] ){
  169172. i++;
  169173. }else{
  169174. *pzErr = zPath;
  169175. return 0;
  169176. }
  169177. }else{
  169178. zKey = zPath;
  169179. for(i=0; zPath[i] && zPath[i]!='.' && zPath[i]!='['; i++){}
  169180. nKey = i;
  169181. }
  169182. if( nKey==0 ){
  169183. *pzErr = zPath;
  169184. return 0;
  169185. }
  169186. j = 1;
  169187. for(;;){
  169188. while( j<=pRoot->n ){
  169189. if( jsonLabelCompare(pRoot+j, zKey, nKey) ){
  169190. return jsonLookupStep(pParse, iRoot+j+1, &zPath[i], pApnd, pzErr);
  169191. }
  169192. j++;
  169193. j += jsonNodeSize(&pRoot[j]);
  169194. }
  169195. if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
  169196. iRoot += pRoot->u.iAppend;
  169197. pRoot = &pParse->aNode[iRoot];
  169198. j = 1;
  169199. }
  169200. if( pApnd ){
  169201. u32 iStart, iLabel;
  169202. JsonNode *pNode;
  169203. iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
  169204. iLabel = jsonParseAddNode(pParse, JSON_STRING, nKey, zKey);
  169205. zPath += i;
  169206. pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
  169207. if( pParse->oom ) return 0;
  169208. if( pNode ){
  169209. pRoot = &pParse->aNode[iRoot];
  169210. pRoot->u.iAppend = iStart - iRoot;
  169211. pRoot->jnFlags |= JNODE_APPEND;
  169212. pParse->aNode[iLabel].jnFlags |= JNODE_RAW;
  169213. }
  169214. return pNode;
  169215. }
  169216. }else if( zPath[0]=='[' && safe_isdigit(zPath[1]) ){
  169217. if( pRoot->eType!=JSON_ARRAY ) return 0;
  169218. i = 0;
  169219. j = 1;
  169220. while( safe_isdigit(zPath[j]) ){
  169221. i = i*10 + zPath[j] - '0';
  169222. j++;
  169223. }
  169224. if( zPath[j]!=']' ){
  169225. *pzErr = zPath;
  169226. return 0;
  169227. }
  169228. zPath += j + 1;
  169229. j = 1;
  169230. for(;;){
  169231. while( j<=pRoot->n && (i>0 || (pRoot[j].jnFlags & JNODE_REMOVE)!=0) ){
  169232. if( (pRoot[j].jnFlags & JNODE_REMOVE)==0 ) i--;
  169233. j += jsonNodeSize(&pRoot[j]);
  169234. }
  169235. if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
  169236. iRoot += pRoot->u.iAppend;
  169237. pRoot = &pParse->aNode[iRoot];
  169238. j = 1;
  169239. }
  169240. if( j<=pRoot->n ){
  169241. return jsonLookupStep(pParse, iRoot+j, zPath, pApnd, pzErr);
  169242. }
  169243. if( i==0 && pApnd ){
  169244. u32 iStart;
  169245. JsonNode *pNode;
  169246. iStart = jsonParseAddNode(pParse, JSON_ARRAY, 1, 0);
  169247. pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
  169248. if( pParse->oom ) return 0;
  169249. if( pNode ){
  169250. pRoot = &pParse->aNode[iRoot];
  169251. pRoot->u.iAppend = iStart - iRoot;
  169252. pRoot->jnFlags |= JNODE_APPEND;
  169253. }
  169254. return pNode;
  169255. }
  169256. }else{
  169257. *pzErr = zPath;
  169258. }
  169259. return 0;
  169260. }
  169261. /*
  169262. ** Append content to pParse that will complete zPath. Return a pointer
  169263. ** to the inserted node, or return NULL if the append fails.
  169264. */
  169265. static JsonNode *jsonLookupAppend(
  169266. JsonParse *pParse, /* Append content to the JSON parse */
  169267. const char *zPath, /* Description of content to append */
  169268. int *pApnd, /* Set this flag to 1 */
  169269. const char **pzErr /* Make this point to any syntax error */
  169270. ){
  169271. *pApnd = 1;
  169272. if( zPath[0]==0 ){
  169273. jsonParseAddNode(pParse, JSON_NULL, 0, 0);
  169274. return pParse->oom ? 0 : &pParse->aNode[pParse->nNode-1];
  169275. }
  169276. if( zPath[0]=='.' ){
  169277. jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
  169278. }else if( strncmp(zPath,"[0]",3)==0 ){
  169279. jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
  169280. }else{
  169281. return 0;
  169282. }
  169283. if( pParse->oom ) return 0;
  169284. return jsonLookupStep(pParse, pParse->nNode-1, zPath, pApnd, pzErr);
  169285. }
  169286. /*
  169287. ** Return the text of a syntax error message on a JSON path. Space is
  169288. ** obtained from sqlite3_malloc().
  169289. */
  169290. static char *jsonPathSyntaxError(const char *zErr){
  169291. return sqlite3_mprintf("JSON path error near '%q'", zErr);
  169292. }
  169293. /*
  169294. ** Do a node lookup using zPath. Return a pointer to the node on success.
  169295. ** Return NULL if not found or if there is an error.
  169296. **
  169297. ** On an error, write an error message into pCtx and increment the
  169298. ** pParse->nErr counter.
  169299. **
  169300. ** If pApnd!=NULL then try to append missing nodes and set *pApnd = 1 if
  169301. ** nodes are appended.
  169302. */
  169303. static JsonNode *jsonLookup(
  169304. JsonParse *pParse, /* The JSON to search */
  169305. const char *zPath, /* The path to search */
  169306. int *pApnd, /* Append nodes to complete path if not NULL */
  169307. sqlite3_context *pCtx /* Report errors here, if not NULL */
  169308. ){
  169309. const char *zErr = 0;
  169310. JsonNode *pNode = 0;
  169311. char *zMsg;
  169312. if( zPath==0 ) return 0;
  169313. if( zPath[0]!='$' ){
  169314. zErr = zPath;
  169315. goto lookup_err;
  169316. }
  169317. zPath++;
  169318. pNode = jsonLookupStep(pParse, 0, zPath, pApnd, &zErr);
  169319. if( zErr==0 ) return pNode;
  169320. lookup_err:
  169321. pParse->nErr++;
  169322. assert( zErr!=0 && pCtx!=0 );
  169323. zMsg = jsonPathSyntaxError(zErr);
  169324. if( zMsg ){
  169325. sqlite3_result_error(pCtx, zMsg, -1);
  169326. sqlite3_free(zMsg);
  169327. }else{
  169328. sqlite3_result_error_nomem(pCtx);
  169329. }
  169330. return 0;
  169331. }
  169332. /*
  169333. ** Report the wrong number of arguments for json_insert(), json_replace()
  169334. ** or json_set().
  169335. */
  169336. static void jsonWrongNumArgs(
  169337. sqlite3_context *pCtx,
  169338. const char *zFuncName
  169339. ){
  169340. char *zMsg = sqlite3_mprintf("json_%s() needs an odd number of arguments",
  169341. zFuncName);
  169342. sqlite3_result_error(pCtx, zMsg, -1);
  169343. sqlite3_free(zMsg);
  169344. }
  169345. /*
  169346. ** Mark all NULL entries in the Object passed in as JNODE_REMOVE.
  169347. */
  169348. static void jsonRemoveAllNulls(JsonNode *pNode){
  169349. int i, n;
  169350. assert( pNode->eType==JSON_OBJECT );
  169351. n = pNode->n;
  169352. for(i=2; i<=n; i += jsonNodeSize(&pNode[i])+1){
  169353. switch( pNode[i].eType ){
  169354. case JSON_NULL:
  169355. pNode[i].jnFlags |= JNODE_REMOVE;
  169356. break;
  169357. case JSON_OBJECT:
  169358. jsonRemoveAllNulls(&pNode[i]);
  169359. break;
  169360. }
  169361. }
  169362. }
  169363. /****************************************************************************
  169364. ** SQL functions used for testing and debugging
  169365. ****************************************************************************/
  169366. #ifdef SQLITE_DEBUG
  169367. /*
  169368. ** The json_parse(JSON) function returns a string which describes
  169369. ** a parse of the JSON provided. Or it returns NULL if JSON is not
  169370. ** well-formed.
  169371. */
  169372. static void jsonParseFunc(
  169373. sqlite3_context *ctx,
  169374. int argc,
  169375. sqlite3_value **argv
  169376. ){
  169377. JsonString s; /* Output string - not real JSON */
  169378. JsonParse x; /* The parse */
  169379. u32 i;
  169380. assert( argc==1 );
  169381. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  169382. jsonParseFindParents(&x);
  169383. jsonInit(&s, ctx);
  169384. for(i=0; i<x.nNode; i++){
  169385. const char *zType;
  169386. if( x.aNode[i].jnFlags & JNODE_LABEL ){
  169387. assert( x.aNode[i].eType==JSON_STRING );
  169388. zType = "label";
  169389. }else{
  169390. zType = jsonType[x.aNode[i].eType];
  169391. }
  169392. jsonPrintf(100, &s,"node %3u: %7s n=%-4d up=%-4d",
  169393. i, zType, x.aNode[i].n, x.aUp[i]);
  169394. if( x.aNode[i].u.zJContent!=0 ){
  169395. jsonAppendRaw(&s, " ", 1);
  169396. jsonAppendRaw(&s, x.aNode[i].u.zJContent, x.aNode[i].n);
  169397. }
  169398. jsonAppendRaw(&s, "\n", 1);
  169399. }
  169400. jsonParseReset(&x);
  169401. jsonResult(&s);
  169402. }
  169403. /*
  169404. ** The json_test1(JSON) function return true (1) if the input is JSON
  169405. ** text generated by another json function. It returns (0) if the input
  169406. ** is not known to be JSON.
  169407. */
  169408. static void jsonTest1Func(
  169409. sqlite3_context *ctx,
  169410. int argc,
  169411. sqlite3_value **argv
  169412. ){
  169413. UNUSED_PARAM(argc);
  169414. sqlite3_result_int(ctx, sqlite3_value_subtype(argv[0])==JSON_SUBTYPE);
  169415. }
  169416. #endif /* SQLITE_DEBUG */
  169417. /****************************************************************************
  169418. ** Scalar SQL function implementations
  169419. ****************************************************************************/
  169420. /*
  169421. ** Implementation of the json_QUOTE(VALUE) function. Return a JSON value
  169422. ** corresponding to the SQL value input. Mostly this means putting
  169423. ** double-quotes around strings and returning the unquoted string "null"
  169424. ** when given a NULL input.
  169425. */
  169426. static void jsonQuoteFunc(
  169427. sqlite3_context *ctx,
  169428. int argc,
  169429. sqlite3_value **argv
  169430. ){
  169431. JsonString jx;
  169432. UNUSED_PARAM(argc);
  169433. jsonInit(&jx, ctx);
  169434. jsonAppendValue(&jx, argv[0]);
  169435. jsonResult(&jx);
  169436. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  169437. }
  169438. /*
  169439. ** Implementation of the json_array(VALUE,...) function. Return a JSON
  169440. ** array that contains all values given in arguments. Or if any argument
  169441. ** is a BLOB, throw an error.
  169442. */
  169443. static void jsonArrayFunc(
  169444. sqlite3_context *ctx,
  169445. int argc,
  169446. sqlite3_value **argv
  169447. ){
  169448. int i;
  169449. JsonString jx;
  169450. jsonInit(&jx, ctx);
  169451. jsonAppendChar(&jx, '[');
  169452. for(i=0; i<argc; i++){
  169453. jsonAppendSeparator(&jx);
  169454. jsonAppendValue(&jx, argv[i]);
  169455. }
  169456. jsonAppendChar(&jx, ']');
  169457. jsonResult(&jx);
  169458. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  169459. }
  169460. /*
  169461. ** json_array_length(JSON)
  169462. ** json_array_length(JSON, PATH)
  169463. **
  169464. ** Return the number of elements in the top-level JSON array.
  169465. ** Return 0 if the input is not a well-formed JSON array.
  169466. */
  169467. static void jsonArrayLengthFunc(
  169468. sqlite3_context *ctx,
  169469. int argc,
  169470. sqlite3_value **argv
  169471. ){
  169472. JsonParse *p; /* The parse */
  169473. sqlite3_int64 n = 0;
  169474. u32 i;
  169475. JsonNode *pNode;
  169476. p = jsonParseCached(ctx, argv, ctx);
  169477. if( p==0 ) return;
  169478. assert( p->nNode );
  169479. if( argc==2 ){
  169480. const char *zPath = (const char*)sqlite3_value_text(argv[1]);
  169481. pNode = jsonLookup(p, zPath, 0, ctx);
  169482. }else{
  169483. pNode = p->aNode;
  169484. }
  169485. if( pNode==0 ){
  169486. return;
  169487. }
  169488. if( pNode->eType==JSON_ARRAY ){
  169489. assert( (pNode->jnFlags & JNODE_APPEND)==0 );
  169490. for(i=1; i<=pNode->n; n++){
  169491. i += jsonNodeSize(&pNode[i]);
  169492. }
  169493. }
  169494. sqlite3_result_int64(ctx, n);
  169495. }
  169496. /*
  169497. ** json_extract(JSON, PATH, ...)
  169498. **
  169499. ** Return the element described by PATH. Return NULL if there is no
  169500. ** PATH element. If there are multiple PATHs, then return a JSON array
  169501. ** with the result from each path. Throw an error if the JSON or any PATH
  169502. ** is malformed.
  169503. */
  169504. static void jsonExtractFunc(
  169505. sqlite3_context *ctx,
  169506. int argc,
  169507. sqlite3_value **argv
  169508. ){
  169509. JsonParse *p; /* The parse */
  169510. JsonNode *pNode;
  169511. const char *zPath;
  169512. JsonString jx;
  169513. int i;
  169514. if( argc<2 ) return;
  169515. p = jsonParseCached(ctx, argv, ctx);
  169516. if( p==0 ) return;
  169517. jsonInit(&jx, ctx);
  169518. jsonAppendChar(&jx, '[');
  169519. for(i=1; i<argc; i++){
  169520. zPath = (const char*)sqlite3_value_text(argv[i]);
  169521. pNode = jsonLookup(p, zPath, 0, ctx);
  169522. if( p->nErr ) break;
  169523. if( argc>2 ){
  169524. jsonAppendSeparator(&jx);
  169525. if( pNode ){
  169526. jsonRenderNode(pNode, &jx, 0);
  169527. }else{
  169528. jsonAppendRaw(&jx, "null", 4);
  169529. }
  169530. }else if( pNode ){
  169531. jsonReturn(pNode, ctx, 0);
  169532. }
  169533. }
  169534. if( argc>2 && i==argc ){
  169535. jsonAppendChar(&jx, ']');
  169536. jsonResult(&jx);
  169537. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  169538. }
  169539. jsonReset(&jx);
  169540. }
  169541. /* This is the RFC 7396 MergePatch algorithm.
  169542. */
  169543. static JsonNode *jsonMergePatch(
  169544. JsonParse *pParse, /* The JSON parser that contains the TARGET */
  169545. u32 iTarget, /* Node of the TARGET in pParse */
  169546. JsonNode *pPatch /* The PATCH */
  169547. ){
  169548. u32 i, j;
  169549. u32 iRoot;
  169550. JsonNode *pTarget;
  169551. if( pPatch->eType!=JSON_OBJECT ){
  169552. return pPatch;
  169553. }
  169554. assert( iTarget>=0 && iTarget<pParse->nNode );
  169555. pTarget = &pParse->aNode[iTarget];
  169556. assert( (pPatch->jnFlags & JNODE_APPEND)==0 );
  169557. if( pTarget->eType!=JSON_OBJECT ){
  169558. jsonRemoveAllNulls(pPatch);
  169559. return pPatch;
  169560. }
  169561. iRoot = iTarget;
  169562. for(i=1; i<pPatch->n; i += jsonNodeSize(&pPatch[i+1])+1){
  169563. u32 nKey;
  169564. const char *zKey;
  169565. assert( pPatch[i].eType==JSON_STRING );
  169566. assert( pPatch[i].jnFlags & JNODE_LABEL );
  169567. nKey = pPatch[i].n;
  169568. zKey = pPatch[i].u.zJContent;
  169569. assert( (pPatch[i].jnFlags & JNODE_RAW)==0 );
  169570. for(j=1; j<pTarget->n; j += jsonNodeSize(&pTarget[j+1])+1 ){
  169571. assert( pTarget[j].eType==JSON_STRING );
  169572. assert( pTarget[j].jnFlags & JNODE_LABEL );
  169573. assert( (pPatch[i].jnFlags & JNODE_RAW)==0 );
  169574. if( pTarget[j].n==nKey && strncmp(pTarget[j].u.zJContent,zKey,nKey)==0 ){
  169575. if( pTarget[j+1].jnFlags & (JNODE_REMOVE|JNODE_PATCH) ) break;
  169576. if( pPatch[i+1].eType==JSON_NULL ){
  169577. pTarget[j+1].jnFlags |= JNODE_REMOVE;
  169578. }else{
  169579. JsonNode *pNew = jsonMergePatch(pParse, iTarget+j+1, &pPatch[i+1]);
  169580. if( pNew==0 ) return 0;
  169581. pTarget = &pParse->aNode[iTarget];
  169582. if( pNew!=&pTarget[j+1] ){
  169583. pTarget[j+1].u.pPatch = pNew;
  169584. pTarget[j+1].jnFlags |= JNODE_PATCH;
  169585. }
  169586. }
  169587. break;
  169588. }
  169589. }
  169590. if( j>=pTarget->n && pPatch[i+1].eType!=JSON_NULL ){
  169591. int iStart, iPatch;
  169592. iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
  169593. jsonParseAddNode(pParse, JSON_STRING, nKey, zKey);
  169594. iPatch = jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
  169595. if( pParse->oom ) return 0;
  169596. jsonRemoveAllNulls(pPatch);
  169597. pTarget = &pParse->aNode[iTarget];
  169598. pParse->aNode[iRoot].jnFlags |= JNODE_APPEND;
  169599. pParse->aNode[iRoot].u.iAppend = iStart - iRoot;
  169600. iRoot = iStart;
  169601. pParse->aNode[iPatch].jnFlags |= JNODE_PATCH;
  169602. pParse->aNode[iPatch].u.pPatch = &pPatch[i+1];
  169603. }
  169604. }
  169605. return pTarget;
  169606. }
  169607. /*
  169608. ** Implementation of the json_mergepatch(JSON1,JSON2) function. Return a JSON
  169609. ** object that is the result of running the RFC 7396 MergePatch() algorithm
  169610. ** on the two arguments.
  169611. */
  169612. static void jsonPatchFunc(
  169613. sqlite3_context *ctx,
  169614. int argc,
  169615. sqlite3_value **argv
  169616. ){
  169617. JsonParse x; /* The JSON that is being patched */
  169618. JsonParse y; /* The patch */
  169619. JsonNode *pResult; /* The result of the merge */
  169620. UNUSED_PARAM(argc);
  169621. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  169622. if( jsonParse(&y, ctx, (const char*)sqlite3_value_text(argv[1])) ){
  169623. jsonParseReset(&x);
  169624. return;
  169625. }
  169626. pResult = jsonMergePatch(&x, 0, y.aNode);
  169627. assert( pResult!=0 || x.oom );
  169628. if( pResult ){
  169629. jsonReturnJson(pResult, ctx, 0);
  169630. }else{
  169631. sqlite3_result_error_nomem(ctx);
  169632. }
  169633. jsonParseReset(&x);
  169634. jsonParseReset(&y);
  169635. }
  169636. /*
  169637. ** Implementation of the json_object(NAME,VALUE,...) function. Return a JSON
  169638. ** object that contains all name/value given in arguments. Or if any name
  169639. ** is not a string or if any value is a BLOB, throw an error.
  169640. */
  169641. static void jsonObjectFunc(
  169642. sqlite3_context *ctx,
  169643. int argc,
  169644. sqlite3_value **argv
  169645. ){
  169646. int i;
  169647. JsonString jx;
  169648. const char *z;
  169649. u32 n;
  169650. if( argc&1 ){
  169651. sqlite3_result_error(ctx, "json_object() requires an even number "
  169652. "of arguments", -1);
  169653. return;
  169654. }
  169655. jsonInit(&jx, ctx);
  169656. jsonAppendChar(&jx, '{');
  169657. for(i=0; i<argc; i+=2){
  169658. if( sqlite3_value_type(argv[i])!=SQLITE_TEXT ){
  169659. sqlite3_result_error(ctx, "json_object() labels must be TEXT", -1);
  169660. jsonReset(&jx);
  169661. return;
  169662. }
  169663. jsonAppendSeparator(&jx);
  169664. z = (const char*)sqlite3_value_text(argv[i]);
  169665. n = (u32)sqlite3_value_bytes(argv[i]);
  169666. jsonAppendString(&jx, z, n);
  169667. jsonAppendChar(&jx, ':');
  169668. jsonAppendValue(&jx, argv[i+1]);
  169669. }
  169670. jsonAppendChar(&jx, '}');
  169671. jsonResult(&jx);
  169672. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  169673. }
  169674. /*
  169675. ** json_remove(JSON, PATH, ...)
  169676. **
  169677. ** Remove the named elements from JSON and return the result. malformed
  169678. ** JSON or PATH arguments result in an error.
  169679. */
  169680. static void jsonRemoveFunc(
  169681. sqlite3_context *ctx,
  169682. int argc,
  169683. sqlite3_value **argv
  169684. ){
  169685. JsonParse x; /* The parse */
  169686. JsonNode *pNode;
  169687. const char *zPath;
  169688. u32 i;
  169689. if( argc<1 ) return;
  169690. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  169691. assert( x.nNode );
  169692. for(i=1; i<(u32)argc; i++){
  169693. zPath = (const char*)sqlite3_value_text(argv[i]);
  169694. if( zPath==0 ) goto remove_done;
  169695. pNode = jsonLookup(&x, zPath, 0, ctx);
  169696. if( x.nErr ) goto remove_done;
  169697. if( pNode ) pNode->jnFlags |= JNODE_REMOVE;
  169698. }
  169699. if( (x.aNode[0].jnFlags & JNODE_REMOVE)==0 ){
  169700. jsonReturnJson(x.aNode, ctx, 0);
  169701. }
  169702. remove_done:
  169703. jsonParseReset(&x);
  169704. }
  169705. /*
  169706. ** json_replace(JSON, PATH, VALUE, ...)
  169707. **
  169708. ** Replace the value at PATH with VALUE. If PATH does not already exist,
  169709. ** this routine is a no-op. If JSON or PATH is malformed, throw an error.
  169710. */
  169711. static void jsonReplaceFunc(
  169712. sqlite3_context *ctx,
  169713. int argc,
  169714. sqlite3_value **argv
  169715. ){
  169716. JsonParse x; /* The parse */
  169717. JsonNode *pNode;
  169718. const char *zPath;
  169719. u32 i;
  169720. if( argc<1 ) return;
  169721. if( (argc&1)==0 ) {
  169722. jsonWrongNumArgs(ctx, "replace");
  169723. return;
  169724. }
  169725. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  169726. assert( x.nNode );
  169727. for(i=1; i<(u32)argc; i+=2){
  169728. zPath = (const char*)sqlite3_value_text(argv[i]);
  169729. pNode = jsonLookup(&x, zPath, 0, ctx);
  169730. if( x.nErr ) goto replace_err;
  169731. if( pNode ){
  169732. pNode->jnFlags |= (u8)JNODE_REPLACE;
  169733. pNode->u.iReplace = i + 1;
  169734. }
  169735. }
  169736. if( x.aNode[0].jnFlags & JNODE_REPLACE ){
  169737. sqlite3_result_value(ctx, argv[x.aNode[0].u.iReplace]);
  169738. }else{
  169739. jsonReturnJson(x.aNode, ctx, argv);
  169740. }
  169741. replace_err:
  169742. jsonParseReset(&x);
  169743. }
  169744. /*
  169745. ** json_set(JSON, PATH, VALUE, ...)
  169746. **
  169747. ** Set the value at PATH to VALUE. Create the PATH if it does not already
  169748. ** exist. Overwrite existing values that do exist.
  169749. ** If JSON or PATH is malformed, throw an error.
  169750. **
  169751. ** json_insert(JSON, PATH, VALUE, ...)
  169752. **
  169753. ** Create PATH and initialize it to VALUE. If PATH already exists, this
  169754. ** routine is a no-op. If JSON or PATH is malformed, throw an error.
  169755. */
  169756. static void jsonSetFunc(
  169757. sqlite3_context *ctx,
  169758. int argc,
  169759. sqlite3_value **argv
  169760. ){
  169761. JsonParse x; /* The parse */
  169762. JsonNode *pNode;
  169763. const char *zPath;
  169764. u32 i;
  169765. int bApnd;
  169766. int bIsSet = *(int*)sqlite3_user_data(ctx);
  169767. if( argc<1 ) return;
  169768. if( (argc&1)==0 ) {
  169769. jsonWrongNumArgs(ctx, bIsSet ? "set" : "insert");
  169770. return;
  169771. }
  169772. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  169773. assert( x.nNode );
  169774. for(i=1; i<(u32)argc; i+=2){
  169775. zPath = (const char*)sqlite3_value_text(argv[i]);
  169776. bApnd = 0;
  169777. pNode = jsonLookup(&x, zPath, &bApnd, ctx);
  169778. if( x.oom ){
  169779. sqlite3_result_error_nomem(ctx);
  169780. goto jsonSetDone;
  169781. }else if( x.nErr ){
  169782. goto jsonSetDone;
  169783. }else if( pNode && (bApnd || bIsSet) ){
  169784. pNode->jnFlags |= (u8)JNODE_REPLACE;
  169785. pNode->u.iReplace = i + 1;
  169786. }
  169787. }
  169788. if( x.aNode[0].jnFlags & JNODE_REPLACE ){
  169789. sqlite3_result_value(ctx, argv[x.aNode[0].u.iReplace]);
  169790. }else{
  169791. jsonReturnJson(x.aNode, ctx, argv);
  169792. }
  169793. jsonSetDone:
  169794. jsonParseReset(&x);
  169795. }
  169796. /*
  169797. ** json_type(JSON)
  169798. ** json_type(JSON, PATH)
  169799. **
  169800. ** Return the top-level "type" of a JSON string. Throw an error if
  169801. ** either the JSON or PATH inputs are not well-formed.
  169802. */
  169803. static void jsonTypeFunc(
  169804. sqlite3_context *ctx,
  169805. int argc,
  169806. sqlite3_value **argv
  169807. ){
  169808. JsonParse *p; /* The parse */
  169809. const char *zPath;
  169810. JsonNode *pNode;
  169811. p = jsonParseCached(ctx, argv, ctx);
  169812. if( p==0 ) return;
  169813. if( argc==2 ){
  169814. zPath = (const char*)sqlite3_value_text(argv[1]);
  169815. pNode = jsonLookup(p, zPath, 0, ctx);
  169816. }else{
  169817. pNode = p->aNode;
  169818. }
  169819. if( pNode ){
  169820. sqlite3_result_text(ctx, jsonType[pNode->eType], -1, SQLITE_STATIC);
  169821. }
  169822. }
  169823. /*
  169824. ** json_valid(JSON)
  169825. **
  169826. ** Return 1 if JSON is a well-formed JSON string according to RFC-7159.
  169827. ** Return 0 otherwise.
  169828. */
  169829. static void jsonValidFunc(
  169830. sqlite3_context *ctx,
  169831. int argc,
  169832. sqlite3_value **argv
  169833. ){
  169834. JsonParse *p; /* The parse */
  169835. UNUSED_PARAM(argc);
  169836. p = jsonParseCached(ctx, argv, 0);
  169837. sqlite3_result_int(ctx, p!=0);
  169838. }
  169839. /****************************************************************************
  169840. ** Aggregate SQL function implementations
  169841. ****************************************************************************/
  169842. /*
  169843. ** json_group_array(VALUE)
  169844. **
  169845. ** Return a JSON array composed of all values in the aggregate.
  169846. */
  169847. static void jsonArrayStep(
  169848. sqlite3_context *ctx,
  169849. int argc,
  169850. sqlite3_value **argv
  169851. ){
  169852. JsonString *pStr;
  169853. UNUSED_PARAM(argc);
  169854. pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
  169855. if( pStr ){
  169856. if( pStr->zBuf==0 ){
  169857. jsonInit(pStr, ctx);
  169858. jsonAppendChar(pStr, '[');
  169859. }else{
  169860. jsonAppendChar(pStr, ',');
  169861. pStr->pCtx = ctx;
  169862. }
  169863. jsonAppendValue(pStr, argv[0]);
  169864. }
  169865. }
  169866. static void jsonArrayCompute(sqlite3_context *ctx, int isFinal){
  169867. JsonString *pStr;
  169868. pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
  169869. if( pStr ){
  169870. pStr->pCtx = ctx;
  169871. jsonAppendChar(pStr, ']');
  169872. if( pStr->bErr ){
  169873. if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx);
  169874. assert( pStr->bStatic );
  169875. }else if( isFinal ){
  169876. sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed,
  169877. pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
  169878. pStr->bStatic = 1;
  169879. }else{
  169880. sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed, SQLITE_TRANSIENT);
  169881. pStr->nUsed--;
  169882. }
  169883. }else{
  169884. sqlite3_result_text(ctx, "[]", 2, SQLITE_STATIC);
  169885. }
  169886. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  169887. }
  169888. static void jsonArrayValue(sqlite3_context *ctx){
  169889. jsonArrayCompute(ctx, 0);
  169890. }
  169891. static void jsonArrayFinal(sqlite3_context *ctx){
  169892. jsonArrayCompute(ctx, 1);
  169893. }
  169894. #ifndef SQLITE_OMIT_WINDOWFUNC
  169895. /*
  169896. ** This method works for both json_group_array() and json_group_object().
  169897. ** It works by removing the first element of the group by searching forward
  169898. ** to the first comma (",") that is not within a string and deleting all
  169899. ** text through that comma.
  169900. */
  169901. static void jsonGroupInverse(
  169902. sqlite3_context *ctx,
  169903. int argc,
  169904. sqlite3_value **argv
  169905. ){
  169906. int i;
  169907. int inStr = 0;
  169908. char *z;
  169909. JsonString *pStr;
  169910. UNUSED_PARAM(argc);
  169911. UNUSED_PARAM(argv);
  169912. pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
  169913. #ifdef NEVER
  169914. /* pStr is always non-NULL since jsonArrayStep() or jsonObjectStep() will
  169915. ** always have been called to initalize it */
  169916. if( NEVER(!pStr) ) return;
  169917. #endif
  169918. z = pStr->zBuf;
  169919. for(i=1; z[i]!=',' || inStr; i++){
  169920. assert( i<pStr->nUsed );
  169921. if( z[i]=='"' ){
  169922. inStr = !inStr;
  169923. }else if( z[i]=='\\' ){
  169924. i++;
  169925. }
  169926. }
  169927. pStr->nUsed -= i;
  169928. memmove(&z[1], &z[i+1], (size_t)pStr->nUsed-1);
  169929. }
  169930. #else
  169931. # define jsonGroupInverse 0
  169932. #endif
  169933. /*
  169934. ** json_group_obj(NAME,VALUE)
  169935. **
  169936. ** Return a JSON object composed of all names and values in the aggregate.
  169937. */
  169938. static void jsonObjectStep(
  169939. sqlite3_context *ctx,
  169940. int argc,
  169941. sqlite3_value **argv
  169942. ){
  169943. JsonString *pStr;
  169944. const char *z;
  169945. u32 n;
  169946. UNUSED_PARAM(argc);
  169947. pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
  169948. if( pStr ){
  169949. if( pStr->zBuf==0 ){
  169950. jsonInit(pStr, ctx);
  169951. jsonAppendChar(pStr, '{');
  169952. }else{
  169953. jsonAppendChar(pStr, ',');
  169954. pStr->pCtx = ctx;
  169955. }
  169956. z = (const char*)sqlite3_value_text(argv[0]);
  169957. n = (u32)sqlite3_value_bytes(argv[0]);
  169958. jsonAppendString(pStr, z, n);
  169959. jsonAppendChar(pStr, ':');
  169960. jsonAppendValue(pStr, argv[1]);
  169961. }
  169962. }
  169963. static void jsonObjectCompute(sqlite3_context *ctx, int isFinal){
  169964. JsonString *pStr;
  169965. pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
  169966. if( pStr ){
  169967. jsonAppendChar(pStr, '}');
  169968. if( pStr->bErr ){
  169969. if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx);
  169970. assert( pStr->bStatic );
  169971. }else if( isFinal ){
  169972. sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed,
  169973. pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
  169974. pStr->bStatic = 1;
  169975. }else{
  169976. sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed, SQLITE_TRANSIENT);
  169977. pStr->nUsed--;
  169978. }
  169979. }else{
  169980. sqlite3_result_text(ctx, "{}", 2, SQLITE_STATIC);
  169981. }
  169982. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  169983. }
  169984. static void jsonObjectValue(sqlite3_context *ctx){
  169985. jsonObjectCompute(ctx, 0);
  169986. }
  169987. static void jsonObjectFinal(sqlite3_context *ctx){
  169988. jsonObjectCompute(ctx, 1);
  169989. }
  169990. #ifndef SQLITE_OMIT_VIRTUALTABLE
  169991. /****************************************************************************
  169992. ** The json_each virtual table
  169993. ****************************************************************************/
  169994. typedef struct JsonEachCursor JsonEachCursor;
  169995. struct JsonEachCursor {
  169996. sqlite3_vtab_cursor base; /* Base class - must be first */
  169997. u32 iRowid; /* The rowid */
  169998. u32 iBegin; /* The first node of the scan */
  169999. u32 i; /* Index in sParse.aNode[] of current row */
  170000. u32 iEnd; /* EOF when i equals or exceeds this value */
  170001. u8 eType; /* Type of top-level element */
  170002. u8 bRecursive; /* True for json_tree(). False for json_each() */
  170003. char *zJson; /* Input JSON */
  170004. char *zRoot; /* Path by which to filter zJson */
  170005. JsonParse sParse; /* Parse of the input JSON */
  170006. };
  170007. /* Constructor for the json_each virtual table */
  170008. static int jsonEachConnect(
  170009. sqlite3 *db,
  170010. void *pAux,
  170011. int argc, const char *const*argv,
  170012. sqlite3_vtab **ppVtab,
  170013. char **pzErr
  170014. ){
  170015. sqlite3_vtab *pNew;
  170016. int rc;
  170017. /* Column numbers */
  170018. #define JEACH_KEY 0
  170019. #define JEACH_VALUE 1
  170020. #define JEACH_TYPE 2
  170021. #define JEACH_ATOM 3
  170022. #define JEACH_ID 4
  170023. #define JEACH_PARENT 5
  170024. #define JEACH_FULLKEY 6
  170025. #define JEACH_PATH 7
  170026. /* The xBestIndex method assumes that the JSON and ROOT columns are
  170027. ** the last two columns in the table. Should this ever changes, be
  170028. ** sure to update the xBestIndex method. */
  170029. #define JEACH_JSON 8
  170030. #define JEACH_ROOT 9
  170031. UNUSED_PARAM(pzErr);
  170032. UNUSED_PARAM(argv);
  170033. UNUSED_PARAM(argc);
  170034. UNUSED_PARAM(pAux);
  170035. rc = sqlite3_declare_vtab(db,
  170036. "CREATE TABLE x(key,value,type,atom,id,parent,fullkey,path,"
  170037. "json HIDDEN,root HIDDEN)");
  170038. if( rc==SQLITE_OK ){
  170039. pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
  170040. if( pNew==0 ) return SQLITE_NOMEM;
  170041. memset(pNew, 0, sizeof(*pNew));
  170042. }
  170043. return rc;
  170044. }
  170045. /* destructor for json_each virtual table */
  170046. static int jsonEachDisconnect(sqlite3_vtab *pVtab){
  170047. sqlite3_free(pVtab);
  170048. return SQLITE_OK;
  170049. }
  170050. /* constructor for a JsonEachCursor object for json_each(). */
  170051. static int jsonEachOpenEach(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
  170052. JsonEachCursor *pCur;
  170053. UNUSED_PARAM(p);
  170054. pCur = sqlite3_malloc( sizeof(*pCur) );
  170055. if( pCur==0 ) return SQLITE_NOMEM;
  170056. memset(pCur, 0, sizeof(*pCur));
  170057. *ppCursor = &pCur->base;
  170058. return SQLITE_OK;
  170059. }
  170060. /* constructor for a JsonEachCursor object for json_tree(). */
  170061. static int jsonEachOpenTree(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
  170062. int rc = jsonEachOpenEach(p, ppCursor);
  170063. if( rc==SQLITE_OK ){
  170064. JsonEachCursor *pCur = (JsonEachCursor*)*ppCursor;
  170065. pCur->bRecursive = 1;
  170066. }
  170067. return rc;
  170068. }
  170069. /* Reset a JsonEachCursor back to its original state. Free any memory
  170070. ** held. */
  170071. static void jsonEachCursorReset(JsonEachCursor *p){
  170072. sqlite3_free(p->zJson);
  170073. sqlite3_free(p->zRoot);
  170074. jsonParseReset(&p->sParse);
  170075. p->iRowid = 0;
  170076. p->i = 0;
  170077. p->iEnd = 0;
  170078. p->eType = 0;
  170079. p->zJson = 0;
  170080. p->zRoot = 0;
  170081. }
  170082. /* Destructor for a jsonEachCursor object */
  170083. static int jsonEachClose(sqlite3_vtab_cursor *cur){
  170084. JsonEachCursor *p = (JsonEachCursor*)cur;
  170085. jsonEachCursorReset(p);
  170086. sqlite3_free(cur);
  170087. return SQLITE_OK;
  170088. }
  170089. /* Return TRUE if the jsonEachCursor object has been advanced off the end
  170090. ** of the JSON object */
  170091. static int jsonEachEof(sqlite3_vtab_cursor *cur){
  170092. JsonEachCursor *p = (JsonEachCursor*)cur;
  170093. return p->i >= p->iEnd;
  170094. }
  170095. /* Advance the cursor to the next element for json_tree() */
  170096. static int jsonEachNext(sqlite3_vtab_cursor *cur){
  170097. JsonEachCursor *p = (JsonEachCursor*)cur;
  170098. if( p->bRecursive ){
  170099. if( p->sParse.aNode[p->i].jnFlags & JNODE_LABEL ) p->i++;
  170100. p->i++;
  170101. p->iRowid++;
  170102. if( p->i<p->iEnd ){
  170103. u32 iUp = p->sParse.aUp[p->i];
  170104. JsonNode *pUp = &p->sParse.aNode[iUp];
  170105. p->eType = pUp->eType;
  170106. if( pUp->eType==JSON_ARRAY ){
  170107. if( iUp==p->i-1 ){
  170108. pUp->u.iKey = 0;
  170109. }else{
  170110. pUp->u.iKey++;
  170111. }
  170112. }
  170113. }
  170114. }else{
  170115. switch( p->eType ){
  170116. case JSON_ARRAY: {
  170117. p->i += jsonNodeSize(&p->sParse.aNode[p->i]);
  170118. p->iRowid++;
  170119. break;
  170120. }
  170121. case JSON_OBJECT: {
  170122. p->i += 1 + jsonNodeSize(&p->sParse.aNode[p->i+1]);
  170123. p->iRowid++;
  170124. break;
  170125. }
  170126. default: {
  170127. p->i = p->iEnd;
  170128. break;
  170129. }
  170130. }
  170131. }
  170132. return SQLITE_OK;
  170133. }
  170134. /* Append the name of the path for element i to pStr
  170135. */
  170136. static void jsonEachComputePath(
  170137. JsonEachCursor *p, /* The cursor */
  170138. JsonString *pStr, /* Write the path here */
  170139. u32 i /* Path to this element */
  170140. ){
  170141. JsonNode *pNode, *pUp;
  170142. u32 iUp;
  170143. if( i==0 ){
  170144. jsonAppendChar(pStr, '$');
  170145. return;
  170146. }
  170147. iUp = p->sParse.aUp[i];
  170148. jsonEachComputePath(p, pStr, iUp);
  170149. pNode = &p->sParse.aNode[i];
  170150. pUp = &p->sParse.aNode[iUp];
  170151. if( pUp->eType==JSON_ARRAY ){
  170152. jsonPrintf(30, pStr, "[%d]", pUp->u.iKey);
  170153. }else{
  170154. assert( pUp->eType==JSON_OBJECT );
  170155. if( (pNode->jnFlags & JNODE_LABEL)==0 ) pNode--;
  170156. assert( pNode->eType==JSON_STRING );
  170157. assert( pNode->jnFlags & JNODE_LABEL );
  170158. jsonPrintf(pNode->n+1, pStr, ".%.*s", pNode->n-2, pNode->u.zJContent+1);
  170159. }
  170160. }
  170161. /* Return the value of a column */
  170162. static int jsonEachColumn(
  170163. sqlite3_vtab_cursor *cur, /* The cursor */
  170164. sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
  170165. int i /* Which column to return */
  170166. ){
  170167. JsonEachCursor *p = (JsonEachCursor*)cur;
  170168. JsonNode *pThis = &p->sParse.aNode[p->i];
  170169. switch( i ){
  170170. case JEACH_KEY: {
  170171. if( p->i==0 ) break;
  170172. if( p->eType==JSON_OBJECT ){
  170173. jsonReturn(pThis, ctx, 0);
  170174. }else if( p->eType==JSON_ARRAY ){
  170175. u32 iKey;
  170176. if( p->bRecursive ){
  170177. if( p->iRowid==0 ) break;
  170178. iKey = p->sParse.aNode[p->sParse.aUp[p->i]].u.iKey;
  170179. }else{
  170180. iKey = p->iRowid;
  170181. }
  170182. sqlite3_result_int64(ctx, (sqlite3_int64)iKey);
  170183. }
  170184. break;
  170185. }
  170186. case JEACH_VALUE: {
  170187. if( pThis->jnFlags & JNODE_LABEL ) pThis++;
  170188. jsonReturn(pThis, ctx, 0);
  170189. break;
  170190. }
  170191. case JEACH_TYPE: {
  170192. if( pThis->jnFlags & JNODE_LABEL ) pThis++;
  170193. sqlite3_result_text(ctx, jsonType[pThis->eType], -1, SQLITE_STATIC);
  170194. break;
  170195. }
  170196. case JEACH_ATOM: {
  170197. if( pThis->jnFlags & JNODE_LABEL ) pThis++;
  170198. if( pThis->eType>=JSON_ARRAY ) break;
  170199. jsonReturn(pThis, ctx, 0);
  170200. break;
  170201. }
  170202. case JEACH_ID: {
  170203. sqlite3_result_int64(ctx,
  170204. (sqlite3_int64)p->i + ((pThis->jnFlags & JNODE_LABEL)!=0));
  170205. break;
  170206. }
  170207. case JEACH_PARENT: {
  170208. if( p->i>p->iBegin && p->bRecursive ){
  170209. sqlite3_result_int64(ctx, (sqlite3_int64)p->sParse.aUp[p->i]);
  170210. }
  170211. break;
  170212. }
  170213. case JEACH_FULLKEY: {
  170214. JsonString x;
  170215. jsonInit(&x, ctx);
  170216. if( p->bRecursive ){
  170217. jsonEachComputePath(p, &x, p->i);
  170218. }else{
  170219. if( p->zRoot ){
  170220. jsonAppendRaw(&x, p->zRoot, (int)strlen(p->zRoot));
  170221. }else{
  170222. jsonAppendChar(&x, '$');
  170223. }
  170224. if( p->eType==JSON_ARRAY ){
  170225. jsonPrintf(30, &x, "[%d]", p->iRowid);
  170226. }else if( p->eType==JSON_OBJECT ){
  170227. jsonPrintf(pThis->n, &x, ".%.*s", pThis->n-2, pThis->u.zJContent+1);
  170228. }
  170229. }
  170230. jsonResult(&x);
  170231. break;
  170232. }
  170233. case JEACH_PATH: {
  170234. if( p->bRecursive ){
  170235. JsonString x;
  170236. jsonInit(&x, ctx);
  170237. jsonEachComputePath(p, &x, p->sParse.aUp[p->i]);
  170238. jsonResult(&x);
  170239. break;
  170240. }
  170241. /* For json_each() path and root are the same so fall through
  170242. ** into the root case */
  170243. }
  170244. default: {
  170245. const char *zRoot = p->zRoot;
  170246. if( zRoot==0 ) zRoot = "$";
  170247. sqlite3_result_text(ctx, zRoot, -1, SQLITE_STATIC);
  170248. break;
  170249. }
  170250. case JEACH_JSON: {
  170251. assert( i==JEACH_JSON );
  170252. sqlite3_result_text(ctx, p->sParse.zJson, -1, SQLITE_STATIC);
  170253. break;
  170254. }
  170255. }
  170256. return SQLITE_OK;
  170257. }
  170258. /* Return the current rowid value */
  170259. static int jsonEachRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
  170260. JsonEachCursor *p = (JsonEachCursor*)cur;
  170261. *pRowid = p->iRowid;
  170262. return SQLITE_OK;
  170263. }
  170264. /* The query strategy is to look for an equality constraint on the json
  170265. ** column. Without such a constraint, the table cannot operate. idxNum is
  170266. ** 1 if the constraint is found, 3 if the constraint and zRoot are found,
  170267. ** and 0 otherwise.
  170268. */
  170269. static int jsonEachBestIndex(
  170270. sqlite3_vtab *tab,
  170271. sqlite3_index_info *pIdxInfo
  170272. ){
  170273. int i; /* Loop counter or computed array index */
  170274. int aIdx[2]; /* Index of constraints for JSON and ROOT */
  170275. int unusableMask = 0; /* Mask of unusable JSON and ROOT constraints */
  170276. int idxMask = 0; /* Mask of usable == constraints JSON and ROOT */
  170277. const struct sqlite3_index_constraint *pConstraint;
  170278. /* This implementation assumes that JSON and ROOT are the last two
  170279. ** columns in the table */
  170280. assert( JEACH_ROOT == JEACH_JSON+1 );
  170281. UNUSED_PARAM(tab);
  170282. aIdx[0] = aIdx[1] = -1;
  170283. pConstraint = pIdxInfo->aConstraint;
  170284. for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
  170285. int iCol;
  170286. int iMask;
  170287. if( pConstraint->iColumn < JEACH_JSON ) continue;
  170288. iCol = pConstraint->iColumn - JEACH_JSON;
  170289. assert( iCol==0 || iCol==1 );
  170290. iMask = 1 << iCol;
  170291. if( pConstraint->usable==0 ){
  170292. unusableMask |= iMask;
  170293. }else if( pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ ){
  170294. aIdx[iCol] = i;
  170295. idxMask |= iMask;
  170296. }
  170297. }
  170298. if( (unusableMask & ~idxMask)!=0 ){
  170299. /* If there are any unusable constraints on JSON or ROOT, then reject
  170300. ** this entire plan */
  170301. return SQLITE_CONSTRAINT;
  170302. }
  170303. if( aIdx[0]<0 ){
  170304. /* No JSON input. Leave estimatedCost at the huge value that it was
  170305. ** initialized to to discourage the query planner from selecting this
  170306. ** plan. */
  170307. pIdxInfo->idxNum = 0;
  170308. }else{
  170309. pIdxInfo->estimatedCost = 1.0;
  170310. i = aIdx[0];
  170311. pIdxInfo->aConstraintUsage[i].argvIndex = 1;
  170312. pIdxInfo->aConstraintUsage[i].omit = 1;
  170313. if( aIdx[1]<0 ){
  170314. pIdxInfo->idxNum = 1; /* Only JSON supplied. Plan 1 */
  170315. }else{
  170316. i = aIdx[1];
  170317. pIdxInfo->aConstraintUsage[i].argvIndex = 2;
  170318. pIdxInfo->aConstraintUsage[i].omit = 1;
  170319. pIdxInfo->idxNum = 3; /* Both JSON and ROOT are supplied. Plan 3 */
  170320. }
  170321. }
  170322. return SQLITE_OK;
  170323. }
  170324. /* Start a search on a new JSON string */
  170325. static int jsonEachFilter(
  170326. sqlite3_vtab_cursor *cur,
  170327. int idxNum, const char *idxStr,
  170328. int argc, sqlite3_value **argv
  170329. ){
  170330. JsonEachCursor *p = (JsonEachCursor*)cur;
  170331. const char *z;
  170332. const char *zRoot = 0;
  170333. sqlite3_int64 n;
  170334. UNUSED_PARAM(idxStr);
  170335. UNUSED_PARAM(argc);
  170336. jsonEachCursorReset(p);
  170337. if( idxNum==0 ) return SQLITE_OK;
  170338. z = (const char*)sqlite3_value_text(argv[0]);
  170339. if( z==0 ) return SQLITE_OK;
  170340. n = sqlite3_value_bytes(argv[0]);
  170341. p->zJson = sqlite3_malloc64( n+1 );
  170342. if( p->zJson==0 ) return SQLITE_NOMEM;
  170343. memcpy(p->zJson, z, (size_t)n+1);
  170344. if( jsonParse(&p->sParse, 0, p->zJson) ){
  170345. int rc = SQLITE_NOMEM;
  170346. if( p->sParse.oom==0 ){
  170347. sqlite3_free(cur->pVtab->zErrMsg);
  170348. cur->pVtab->zErrMsg = sqlite3_mprintf("malformed JSON");
  170349. if( cur->pVtab->zErrMsg ) rc = SQLITE_ERROR;
  170350. }
  170351. jsonEachCursorReset(p);
  170352. return rc;
  170353. }else if( p->bRecursive && jsonParseFindParents(&p->sParse) ){
  170354. jsonEachCursorReset(p);
  170355. return SQLITE_NOMEM;
  170356. }else{
  170357. JsonNode *pNode = 0;
  170358. if( idxNum==3 ){
  170359. const char *zErr = 0;
  170360. zRoot = (const char*)sqlite3_value_text(argv[1]);
  170361. if( zRoot==0 ) return SQLITE_OK;
  170362. n = sqlite3_value_bytes(argv[1]);
  170363. p->zRoot = sqlite3_malloc64( n+1 );
  170364. if( p->zRoot==0 ) return SQLITE_NOMEM;
  170365. memcpy(p->zRoot, zRoot, (size_t)n+1);
  170366. if( zRoot[0]!='$' ){
  170367. zErr = zRoot;
  170368. }else{
  170369. pNode = jsonLookupStep(&p->sParse, 0, p->zRoot+1, 0, &zErr);
  170370. }
  170371. if( zErr ){
  170372. sqlite3_free(cur->pVtab->zErrMsg);
  170373. cur->pVtab->zErrMsg = jsonPathSyntaxError(zErr);
  170374. jsonEachCursorReset(p);
  170375. return cur->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM;
  170376. }else if( pNode==0 ){
  170377. return SQLITE_OK;
  170378. }
  170379. }else{
  170380. pNode = p->sParse.aNode;
  170381. }
  170382. p->iBegin = p->i = (int)(pNode - p->sParse.aNode);
  170383. p->eType = pNode->eType;
  170384. if( p->eType>=JSON_ARRAY ){
  170385. pNode->u.iKey = 0;
  170386. p->iEnd = p->i + pNode->n + 1;
  170387. if( p->bRecursive ){
  170388. p->eType = p->sParse.aNode[p->sParse.aUp[p->i]].eType;
  170389. if( p->i>0 && (p->sParse.aNode[p->i-1].jnFlags & JNODE_LABEL)!=0 ){
  170390. p->i--;
  170391. }
  170392. }else{
  170393. p->i++;
  170394. }
  170395. }else{
  170396. p->iEnd = p->i+1;
  170397. }
  170398. }
  170399. return SQLITE_OK;
  170400. }
  170401. /* The methods of the json_each virtual table */
  170402. static sqlite3_module jsonEachModule = {
  170403. 0, /* iVersion */
  170404. 0, /* xCreate */
  170405. jsonEachConnect, /* xConnect */
  170406. jsonEachBestIndex, /* xBestIndex */
  170407. jsonEachDisconnect, /* xDisconnect */
  170408. 0, /* xDestroy */
  170409. jsonEachOpenEach, /* xOpen - open a cursor */
  170410. jsonEachClose, /* xClose - close a cursor */
  170411. jsonEachFilter, /* xFilter - configure scan constraints */
  170412. jsonEachNext, /* xNext - advance a cursor */
  170413. jsonEachEof, /* xEof - check for end of scan */
  170414. jsonEachColumn, /* xColumn - read data */
  170415. jsonEachRowid, /* xRowid - read data */
  170416. 0, /* xUpdate */
  170417. 0, /* xBegin */
  170418. 0, /* xSync */
  170419. 0, /* xCommit */
  170420. 0, /* xRollback */
  170421. 0, /* xFindMethod */
  170422. 0, /* xRename */
  170423. 0, /* xSavepoint */
  170424. 0, /* xRelease */
  170425. 0, /* xRollbackTo */
  170426. 0 /* xShadowName */
  170427. };
  170428. /* The methods of the json_tree virtual table. */
  170429. static sqlite3_module jsonTreeModule = {
  170430. 0, /* iVersion */
  170431. 0, /* xCreate */
  170432. jsonEachConnect, /* xConnect */
  170433. jsonEachBestIndex, /* xBestIndex */
  170434. jsonEachDisconnect, /* xDisconnect */
  170435. 0, /* xDestroy */
  170436. jsonEachOpenTree, /* xOpen - open a cursor */
  170437. jsonEachClose, /* xClose - close a cursor */
  170438. jsonEachFilter, /* xFilter - configure scan constraints */
  170439. jsonEachNext, /* xNext - advance a cursor */
  170440. jsonEachEof, /* xEof - check for end of scan */
  170441. jsonEachColumn, /* xColumn - read data */
  170442. jsonEachRowid, /* xRowid - read data */
  170443. 0, /* xUpdate */
  170444. 0, /* xBegin */
  170445. 0, /* xSync */
  170446. 0, /* xCommit */
  170447. 0, /* xRollback */
  170448. 0, /* xFindMethod */
  170449. 0, /* xRename */
  170450. 0, /* xSavepoint */
  170451. 0, /* xRelease */
  170452. 0, /* xRollbackTo */
  170453. 0 /* xShadowName */
  170454. };
  170455. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  170456. /****************************************************************************
  170457. ** The following routines are the only publically visible identifiers in this
  170458. ** file. Call the following routines in order to register the various SQL
  170459. ** functions and the virtual table implemented by this file.
  170460. ****************************************************************************/
  170461. SQLITE_PRIVATE int sqlite3Json1Init(sqlite3 *db){
  170462. int rc = SQLITE_OK;
  170463. unsigned int i;
  170464. static const struct {
  170465. const char *zName;
  170466. int nArg;
  170467. int flag;
  170468. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  170469. } aFunc[] = {
  170470. { "json", 1, 0, jsonRemoveFunc },
  170471. { "json_array", -1, 0, jsonArrayFunc },
  170472. { "json_array_length", 1, 0, jsonArrayLengthFunc },
  170473. { "json_array_length", 2, 0, jsonArrayLengthFunc },
  170474. { "json_extract", -1, 0, jsonExtractFunc },
  170475. { "json_insert", -1, 0, jsonSetFunc },
  170476. { "json_object", -1, 0, jsonObjectFunc },
  170477. { "json_patch", 2, 0, jsonPatchFunc },
  170478. { "json_quote", 1, 0, jsonQuoteFunc },
  170479. { "json_remove", -1, 0, jsonRemoveFunc },
  170480. { "json_replace", -1, 0, jsonReplaceFunc },
  170481. { "json_set", -1, 1, jsonSetFunc },
  170482. { "json_type", 1, 0, jsonTypeFunc },
  170483. { "json_type", 2, 0, jsonTypeFunc },
  170484. { "json_valid", 1, 0, jsonValidFunc },
  170485. #if SQLITE_DEBUG
  170486. /* DEBUG and TESTING functions */
  170487. { "json_parse", 1, 0, jsonParseFunc },
  170488. { "json_test1", 1, 0, jsonTest1Func },
  170489. #endif
  170490. };
  170491. static const struct {
  170492. const char *zName;
  170493. int nArg;
  170494. void (*xStep)(sqlite3_context*,int,sqlite3_value**);
  170495. void (*xFinal)(sqlite3_context*);
  170496. void (*xValue)(sqlite3_context*);
  170497. } aAgg[] = {
  170498. { "json_group_array", 1,
  170499. jsonArrayStep, jsonArrayFinal, jsonArrayValue },
  170500. { "json_group_object", 2,
  170501. jsonObjectStep, jsonObjectFinal, jsonObjectValue },
  170502. };
  170503. #ifndef SQLITE_OMIT_VIRTUALTABLE
  170504. static const struct {
  170505. const char *zName;
  170506. sqlite3_module *pModule;
  170507. } aMod[] = {
  170508. { "json_each", &jsonEachModule },
  170509. { "json_tree", &jsonTreeModule },
  170510. };
  170511. #endif
  170512. for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
  170513. rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg,
  170514. SQLITE_UTF8 | SQLITE_DETERMINISTIC,
  170515. (void*)&aFunc[i].flag,
  170516. aFunc[i].xFunc, 0, 0);
  170517. }
  170518. #ifndef SQLITE_OMIT_WINDOWFUNC
  170519. for(i=0; i<sizeof(aAgg)/sizeof(aAgg[0]) && rc==SQLITE_OK; i++){
  170520. rc = sqlite3_create_window_function(db, aAgg[i].zName, aAgg[i].nArg,
  170521. SQLITE_UTF8 | SQLITE_DETERMINISTIC, 0,
  170522. aAgg[i].xStep, aAgg[i].xFinal,
  170523. aAgg[i].xValue, jsonGroupInverse, 0);
  170524. }
  170525. #endif
  170526. #ifndef SQLITE_OMIT_VIRTUALTABLE
  170527. for(i=0; i<sizeof(aMod)/sizeof(aMod[0]) && rc==SQLITE_OK; i++){
  170528. rc = sqlite3_create_module(db, aMod[i].zName, aMod[i].pModule, 0);
  170529. }
  170530. #endif
  170531. return rc;
  170532. }
  170533. #ifndef SQLITE_CORE
  170534. #ifdef _WIN32
  170535. __declspec(dllexport)
  170536. #endif
  170537. SQLITE_API int sqlite3_json_init(
  170538. sqlite3 *db,
  170539. char **pzErrMsg,
  170540. const sqlite3_api_routines *pApi
  170541. ){
  170542. SQLITE_EXTENSION_INIT2(pApi);
  170543. (void)pzErrMsg; /* Unused parameter */
  170544. return sqlite3Json1Init(db);
  170545. }
  170546. #endif
  170547. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1) */
  170548. /************** End of json1.c ***********************************************/
  170549. /************** Begin file rtree.c *******************************************/
  170550. /*
  170551. ** 2001 September 15
  170552. **
  170553. ** The author disclaims copyright to this source code. In place of
  170554. ** a legal notice, here is a blessing:
  170555. **
  170556. ** May you do good and not evil.
  170557. ** May you find forgiveness for yourself and forgive others.
  170558. ** May you share freely, never taking more than you give.
  170559. **
  170560. *************************************************************************
  170561. ** This file contains code for implementations of the r-tree and r*-tree
  170562. ** algorithms packaged as an SQLite virtual table module.
  170563. */
  170564. /*
  170565. ** Database Format of R-Tree Tables
  170566. ** --------------------------------
  170567. **
  170568. ** The data structure for a single virtual r-tree table is stored in three
  170569. ** native SQLite tables declared as follows. In each case, the '%' character
  170570. ** in the table name is replaced with the user-supplied name of the r-tree
  170571. ** table.
  170572. **
  170573. ** CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
  170574. ** CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
  170575. ** CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER, ...)
  170576. **
  170577. ** The data for each node of the r-tree structure is stored in the %_node
  170578. ** table. For each node that is not the root node of the r-tree, there is
  170579. ** an entry in the %_parent table associating the node with its parent.
  170580. ** And for each row of data in the table, there is an entry in the %_rowid
  170581. ** table that maps from the entries rowid to the id of the node that it
  170582. ** is stored on. If the r-tree contains auxiliary columns, those are stored
  170583. ** on the end of the %_rowid table.
  170584. **
  170585. ** The root node of an r-tree always exists, even if the r-tree table is
  170586. ** empty. The nodeno of the root node is always 1. All other nodes in the
  170587. ** table must be the same size as the root node. The content of each node
  170588. ** is formatted as follows:
  170589. **
  170590. ** 1. If the node is the root node (node 1), then the first 2 bytes
  170591. ** of the node contain the tree depth as a big-endian integer.
  170592. ** For non-root nodes, the first 2 bytes are left unused.
  170593. **
  170594. ** 2. The next 2 bytes contain the number of entries currently
  170595. ** stored in the node.
  170596. **
  170597. ** 3. The remainder of the node contains the node entries. Each entry
  170598. ** consists of a single 8-byte integer followed by an even number
  170599. ** of 4-byte coordinates. For leaf nodes the integer is the rowid
  170600. ** of a record. For internal nodes it is the node number of a
  170601. ** child page.
  170602. */
  170603. #if !defined(SQLITE_CORE) \
  170604. || (defined(SQLITE_ENABLE_RTREE) && !defined(SQLITE_OMIT_VIRTUALTABLE))
  170605. #ifndef SQLITE_CORE
  170606. /* #include "sqlite3ext.h" */
  170607. SQLITE_EXTENSION_INIT1
  170608. #else
  170609. /* #include "sqlite3.h" */
  170610. #endif
  170611. #ifndef SQLITE_AMALGAMATION
  170612. #include "sqlite3rtree.h"
  170613. typedef sqlite3_int64 i64;
  170614. typedef sqlite3_uint64 u64;
  170615. typedef unsigned char u8;
  170616. typedef unsigned short u16;
  170617. typedef unsigned int u32;
  170618. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  170619. # define NDEBUG 1
  170620. #endif
  170621. #if defined(NDEBUG) && defined(SQLITE_DEBUG)
  170622. # undef NDEBUG
  170623. #endif
  170624. #endif
  170625. /* #include <string.h> */
  170626. /* #include <stdio.h> */
  170627. /* #include <assert.h> */
  170628. /* The following macro is used to suppress compiler warnings.
  170629. */
  170630. #ifndef UNUSED_PARAMETER
  170631. # define UNUSED_PARAMETER(x) (void)(x)
  170632. #endif
  170633. typedef struct Rtree Rtree;
  170634. typedef struct RtreeCursor RtreeCursor;
  170635. typedef struct RtreeNode RtreeNode;
  170636. typedef struct RtreeCell RtreeCell;
  170637. typedef struct RtreeConstraint RtreeConstraint;
  170638. typedef struct RtreeMatchArg RtreeMatchArg;
  170639. typedef struct RtreeGeomCallback RtreeGeomCallback;
  170640. typedef union RtreeCoord RtreeCoord;
  170641. typedef struct RtreeSearchPoint RtreeSearchPoint;
  170642. /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
  170643. #define RTREE_MAX_DIMENSIONS 5
  170644. /* Maximum number of auxiliary columns */
  170645. #define RTREE_MAX_AUX_COLUMN 100
  170646. /* Size of hash table Rtree.aHash. This hash table is not expected to
  170647. ** ever contain very many entries, so a fixed number of buckets is
  170648. ** used.
  170649. */
  170650. #define HASHSIZE 97
  170651. /* The xBestIndex method of this virtual table requires an estimate of
  170652. ** the number of rows in the virtual table to calculate the costs of
  170653. ** various strategies. If possible, this estimate is loaded from the
  170654. ** sqlite_stat1 table (with RTREE_MIN_ROWEST as a hard-coded minimum).
  170655. ** Otherwise, if no sqlite_stat1 entry is available, use
  170656. ** RTREE_DEFAULT_ROWEST.
  170657. */
  170658. #define RTREE_DEFAULT_ROWEST 1048576
  170659. #define RTREE_MIN_ROWEST 100
  170660. /*
  170661. ** An rtree virtual-table object.
  170662. */
  170663. struct Rtree {
  170664. sqlite3_vtab base; /* Base class. Must be first */
  170665. sqlite3 *db; /* Host database connection */
  170666. int iNodeSize; /* Size in bytes of each node in the node table */
  170667. u8 nDim; /* Number of dimensions */
  170668. u8 nDim2; /* Twice the number of dimensions */
  170669. u8 eCoordType; /* RTREE_COORD_REAL32 or RTREE_COORD_INT32 */
  170670. u8 nBytesPerCell; /* Bytes consumed per cell */
  170671. u8 inWrTrans; /* True if inside write transaction */
  170672. u8 nAux; /* # of auxiliary columns in %_rowid */
  170673. u8 nAuxNotNull; /* Number of initial not-null aux columns */
  170674. #ifdef SQLITE_DEBUG
  170675. u8 bCorrupt; /* Shadow table corruption detected */
  170676. #endif
  170677. int iDepth; /* Current depth of the r-tree structure */
  170678. char *zDb; /* Name of database containing r-tree table */
  170679. char *zName; /* Name of r-tree table */
  170680. u32 nBusy; /* Current number of users of this structure */
  170681. i64 nRowEst; /* Estimated number of rows in this table */
  170682. u32 nCursor; /* Number of open cursors */
  170683. u32 nNodeRef; /* Number RtreeNodes with positive nRef */
  170684. char *zReadAuxSql; /* SQL for statement to read aux data */
  170685. /* List of nodes removed during a CondenseTree operation. List is
  170686. ** linked together via the pointer normally used for hash chains -
  170687. ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
  170688. ** headed by the node (leaf nodes have RtreeNode.iNode==0).
  170689. */
  170690. RtreeNode *pDeleted;
  170691. int iReinsertHeight; /* Height of sub-trees Reinsert() has run on */
  170692. /* Blob I/O on xxx_node */
  170693. sqlite3_blob *pNodeBlob;
  170694. /* Statements to read/write/delete a record from xxx_node */
  170695. sqlite3_stmt *pWriteNode;
  170696. sqlite3_stmt *pDeleteNode;
  170697. /* Statements to read/write/delete a record from xxx_rowid */
  170698. sqlite3_stmt *pReadRowid;
  170699. sqlite3_stmt *pWriteRowid;
  170700. sqlite3_stmt *pDeleteRowid;
  170701. /* Statements to read/write/delete a record from xxx_parent */
  170702. sqlite3_stmt *pReadParent;
  170703. sqlite3_stmt *pWriteParent;
  170704. sqlite3_stmt *pDeleteParent;
  170705. /* Statement for writing to the "aux:" fields, if there are any */
  170706. sqlite3_stmt *pWriteAux;
  170707. RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
  170708. };
  170709. /* Possible values for Rtree.eCoordType: */
  170710. #define RTREE_COORD_REAL32 0
  170711. #define RTREE_COORD_INT32 1
  170712. /*
  170713. ** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
  170714. ** only deal with integer coordinates. No floating point operations
  170715. ** will be done.
  170716. */
  170717. #ifdef SQLITE_RTREE_INT_ONLY
  170718. typedef sqlite3_int64 RtreeDValue; /* High accuracy coordinate */
  170719. typedef int RtreeValue; /* Low accuracy coordinate */
  170720. # define RTREE_ZERO 0
  170721. #else
  170722. typedef double RtreeDValue; /* High accuracy coordinate */
  170723. typedef float RtreeValue; /* Low accuracy coordinate */
  170724. # define RTREE_ZERO 0.0
  170725. #endif
  170726. /*
  170727. ** Set the Rtree.bCorrupt flag
  170728. */
  170729. #ifdef SQLITE_DEBUG
  170730. # define RTREE_IS_CORRUPT(X) ((X)->bCorrupt = 1)
  170731. #else
  170732. # define RTREE_IS_CORRUPT(X)
  170733. #endif
  170734. /*
  170735. ** When doing a search of an r-tree, instances of the following structure
  170736. ** record intermediate results from the tree walk.
  170737. **
  170738. ** The id is always a node-id. For iLevel>=1 the id is the node-id of
  170739. ** the node that the RtreeSearchPoint represents. When iLevel==0, however,
  170740. ** the id is of the parent node and the cell that RtreeSearchPoint
  170741. ** represents is the iCell-th entry in the parent node.
  170742. */
  170743. struct RtreeSearchPoint {
  170744. RtreeDValue rScore; /* The score for this node. Smallest goes first. */
  170745. sqlite3_int64 id; /* Node ID */
  170746. u8 iLevel; /* 0=entries. 1=leaf node. 2+ for higher */
  170747. u8 eWithin; /* PARTLY_WITHIN or FULLY_WITHIN */
  170748. u8 iCell; /* Cell index within the node */
  170749. };
  170750. /*
  170751. ** The minimum number of cells allowed for a node is a third of the
  170752. ** maximum. In Gutman's notation:
  170753. **
  170754. ** m = M/3
  170755. **
  170756. ** If an R*-tree "Reinsert" operation is required, the same number of
  170757. ** cells are removed from the overfull node and reinserted into the tree.
  170758. */
  170759. #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
  170760. #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
  170761. #define RTREE_MAXCELLS 51
  170762. /*
  170763. ** The smallest possible node-size is (512-64)==448 bytes. And the largest
  170764. ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
  170765. ** Therefore all non-root nodes must contain at least 3 entries. Since
  170766. ** 3^40 is greater than 2^64, an r-tree structure always has a depth of
  170767. ** 40 or less.
  170768. */
  170769. #define RTREE_MAX_DEPTH 40
  170770. /*
  170771. ** Number of entries in the cursor RtreeNode cache. The first entry is
  170772. ** used to cache the RtreeNode for RtreeCursor.sPoint. The remaining
  170773. ** entries cache the RtreeNode for the first elements of the priority queue.
  170774. */
  170775. #define RTREE_CACHE_SZ 5
  170776. /*
  170777. ** An rtree cursor object.
  170778. */
  170779. struct RtreeCursor {
  170780. sqlite3_vtab_cursor base; /* Base class. Must be first */
  170781. u8 atEOF; /* True if at end of search */
  170782. u8 bPoint; /* True if sPoint is valid */
  170783. u8 bAuxValid; /* True if pReadAux is valid */
  170784. int iStrategy; /* Copy of idxNum search parameter */
  170785. int nConstraint; /* Number of entries in aConstraint */
  170786. RtreeConstraint *aConstraint; /* Search constraints. */
  170787. int nPointAlloc; /* Number of slots allocated for aPoint[] */
  170788. int nPoint; /* Number of slots used in aPoint[] */
  170789. int mxLevel; /* iLevel value for root of the tree */
  170790. RtreeSearchPoint *aPoint; /* Priority queue for search points */
  170791. sqlite3_stmt *pReadAux; /* Statement to read aux-data */
  170792. RtreeSearchPoint sPoint; /* Cached next search point */
  170793. RtreeNode *aNode[RTREE_CACHE_SZ]; /* Rtree node cache */
  170794. u32 anQueue[RTREE_MAX_DEPTH+1]; /* Number of queued entries by iLevel */
  170795. };
  170796. /* Return the Rtree of a RtreeCursor */
  170797. #define RTREE_OF_CURSOR(X) ((Rtree*)((X)->base.pVtab))
  170798. /*
  170799. ** A coordinate can be either a floating point number or a integer. All
  170800. ** coordinates within a single R-Tree are always of the same time.
  170801. */
  170802. union RtreeCoord {
  170803. RtreeValue f; /* Floating point value */
  170804. int i; /* Integer value */
  170805. u32 u; /* Unsigned for byte-order conversions */
  170806. };
  170807. /*
  170808. ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
  170809. ** formatted as a RtreeDValue (double or int64). This macro assumes that local
  170810. ** variable pRtree points to the Rtree structure associated with the
  170811. ** RtreeCoord.
  170812. */
  170813. #ifdef SQLITE_RTREE_INT_ONLY
  170814. # define DCOORD(coord) ((RtreeDValue)coord.i)
  170815. #else
  170816. # define DCOORD(coord) ( \
  170817. (pRtree->eCoordType==RTREE_COORD_REAL32) ? \
  170818. ((double)coord.f) : \
  170819. ((double)coord.i) \
  170820. )
  170821. #endif
  170822. /*
  170823. ** A search constraint.
  170824. */
  170825. struct RtreeConstraint {
  170826. int iCoord; /* Index of constrained coordinate */
  170827. int op; /* Constraining operation */
  170828. union {
  170829. RtreeDValue rValue; /* Constraint value. */
  170830. int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*);
  170831. int (*xQueryFunc)(sqlite3_rtree_query_info*);
  170832. } u;
  170833. sqlite3_rtree_query_info *pInfo; /* xGeom and xQueryFunc argument */
  170834. };
  170835. /* Possible values for RtreeConstraint.op */
  170836. #define RTREE_EQ 0x41 /* A */
  170837. #define RTREE_LE 0x42 /* B */
  170838. #define RTREE_LT 0x43 /* C */
  170839. #define RTREE_GE 0x44 /* D */
  170840. #define RTREE_GT 0x45 /* E */
  170841. #define RTREE_MATCH 0x46 /* F: Old-style sqlite3_rtree_geometry_callback() */
  170842. #define RTREE_QUERY 0x47 /* G: New-style sqlite3_rtree_query_callback() */
  170843. /*
  170844. ** An rtree structure node.
  170845. */
  170846. struct RtreeNode {
  170847. RtreeNode *pParent; /* Parent node */
  170848. i64 iNode; /* The node number */
  170849. int nRef; /* Number of references to this node */
  170850. int isDirty; /* True if the node needs to be written to disk */
  170851. u8 *zData; /* Content of the node, as should be on disk */
  170852. RtreeNode *pNext; /* Next node in this hash collision chain */
  170853. };
  170854. /* Return the number of cells in a node */
  170855. #define NCELL(pNode) readInt16(&(pNode)->zData[2])
  170856. /*
  170857. ** A single cell from a node, deserialized
  170858. */
  170859. struct RtreeCell {
  170860. i64 iRowid; /* Node or entry ID */
  170861. RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2]; /* Bounding box coordinates */
  170862. };
  170863. /*
  170864. ** This object becomes the sqlite3_user_data() for the SQL functions
  170865. ** that are created by sqlite3_rtree_geometry_callback() and
  170866. ** sqlite3_rtree_query_callback() and which appear on the right of MATCH
  170867. ** operators in order to constrain a search.
  170868. **
  170869. ** xGeom and xQueryFunc are the callback functions. Exactly one of
  170870. ** xGeom and xQueryFunc fields is non-NULL, depending on whether the
  170871. ** SQL function was created using sqlite3_rtree_geometry_callback() or
  170872. ** sqlite3_rtree_query_callback().
  170873. **
  170874. ** This object is deleted automatically by the destructor mechanism in
  170875. ** sqlite3_create_function_v2().
  170876. */
  170877. struct RtreeGeomCallback {
  170878. int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
  170879. int (*xQueryFunc)(sqlite3_rtree_query_info*);
  170880. void (*xDestructor)(void*);
  170881. void *pContext;
  170882. };
  170883. /*
  170884. ** An instance of this structure (in the form of a BLOB) is returned by
  170885. ** the SQL functions that sqlite3_rtree_geometry_callback() and
  170886. ** sqlite3_rtree_query_callback() create, and is read as the right-hand
  170887. ** operand to the MATCH operator of an R-Tree.
  170888. */
  170889. struct RtreeMatchArg {
  170890. u32 iSize; /* Size of this object */
  170891. RtreeGeomCallback cb; /* Info about the callback functions */
  170892. int nParam; /* Number of parameters to the SQL function */
  170893. sqlite3_value **apSqlParam; /* Original SQL parameter values */
  170894. RtreeDValue aParam[1]; /* Values for parameters to the SQL function */
  170895. };
  170896. #ifndef MAX
  170897. # define MAX(x,y) ((x) < (y) ? (y) : (x))
  170898. #endif
  170899. #ifndef MIN
  170900. # define MIN(x,y) ((x) > (y) ? (y) : (x))
  170901. #endif
  170902. /* What version of GCC is being used. 0 means GCC is not being used .
  170903. ** Note that the GCC_VERSION macro will also be set correctly when using
  170904. ** clang, since clang works hard to be gcc compatible. So the gcc
  170905. ** optimizations will also work when compiling with clang.
  170906. */
  170907. #ifndef GCC_VERSION
  170908. #if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC)
  170909. # define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)
  170910. #else
  170911. # define GCC_VERSION 0
  170912. #endif
  170913. #endif
  170914. /* The testcase() macro should already be defined in the amalgamation. If
  170915. ** it is not, make it a no-op.
  170916. */
  170917. #ifndef SQLITE_AMALGAMATION
  170918. # define testcase(X)
  170919. #endif
  170920. /*
  170921. ** Macros to determine whether the machine is big or little endian,
  170922. ** and whether or not that determination is run-time or compile-time.
  170923. **
  170924. ** For best performance, an attempt is made to guess at the byte-order
  170925. ** using C-preprocessor macros. If that is unsuccessful, or if
  170926. ** -DSQLITE_RUNTIME_BYTEORDER=1 is set, then byte-order is determined
  170927. ** at run-time.
  170928. */
  170929. #ifndef SQLITE_BYTEORDER
  170930. #if defined(i386) || defined(__i386__) || defined(_M_IX86) || \
  170931. defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \
  170932. defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \
  170933. defined(__arm__)
  170934. # define SQLITE_BYTEORDER 1234
  170935. #elif defined(sparc) || defined(__ppc__)
  170936. # define SQLITE_BYTEORDER 4321
  170937. #else
  170938. # define SQLITE_BYTEORDER 0 /* 0 means "unknown at compile-time" */
  170939. #endif
  170940. #endif
  170941. /* What version of MSVC is being used. 0 means MSVC is not being used */
  170942. #ifndef MSVC_VERSION
  170943. #if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC)
  170944. # define MSVC_VERSION _MSC_VER
  170945. #else
  170946. # define MSVC_VERSION 0
  170947. #endif
  170948. #endif
  170949. /*
  170950. ** Functions to deserialize a 16 bit integer, 32 bit real number and
  170951. ** 64 bit integer. The deserialized value is returned.
  170952. */
  170953. static int readInt16(u8 *p){
  170954. return (p[0]<<8) + p[1];
  170955. }
  170956. static void readCoord(u8 *p, RtreeCoord *pCoord){
  170957. assert( ((((char*)p) - (char*)0)&3)==0 ); /* p is always 4-byte aligned */
  170958. #if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  170959. pCoord->u = _byteswap_ulong(*(u32*)p);
  170960. #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  170961. pCoord->u = __builtin_bswap32(*(u32*)p);
  170962. #elif SQLITE_BYTEORDER==4321
  170963. pCoord->u = *(u32*)p;
  170964. #else
  170965. pCoord->u = (
  170966. (((u32)p[0]) << 24) +
  170967. (((u32)p[1]) << 16) +
  170968. (((u32)p[2]) << 8) +
  170969. (((u32)p[3]) << 0)
  170970. );
  170971. #endif
  170972. }
  170973. static i64 readInt64(u8 *p){
  170974. #if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  170975. u64 x;
  170976. memcpy(&x, p, 8);
  170977. return (i64)_byteswap_uint64(x);
  170978. #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  170979. u64 x;
  170980. memcpy(&x, p, 8);
  170981. return (i64)__builtin_bswap64(x);
  170982. #elif SQLITE_BYTEORDER==4321
  170983. i64 x;
  170984. memcpy(&x, p, 8);
  170985. return x;
  170986. #else
  170987. return (i64)(
  170988. (((u64)p[0]) << 56) +
  170989. (((u64)p[1]) << 48) +
  170990. (((u64)p[2]) << 40) +
  170991. (((u64)p[3]) << 32) +
  170992. (((u64)p[4]) << 24) +
  170993. (((u64)p[5]) << 16) +
  170994. (((u64)p[6]) << 8) +
  170995. (((u64)p[7]) << 0)
  170996. );
  170997. #endif
  170998. }
  170999. /*
  171000. ** Functions to serialize a 16 bit integer, 32 bit real number and
  171001. ** 64 bit integer. The value returned is the number of bytes written
  171002. ** to the argument buffer (always 2, 4 and 8 respectively).
  171003. */
  171004. static void writeInt16(u8 *p, int i){
  171005. p[0] = (i>> 8)&0xFF;
  171006. p[1] = (i>> 0)&0xFF;
  171007. }
  171008. static int writeCoord(u8 *p, RtreeCoord *pCoord){
  171009. u32 i;
  171010. assert( ((((char*)p) - (char*)0)&3)==0 ); /* p is always 4-byte aligned */
  171011. assert( sizeof(RtreeCoord)==4 );
  171012. assert( sizeof(u32)==4 );
  171013. #if SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  171014. i = __builtin_bswap32(pCoord->u);
  171015. memcpy(p, &i, 4);
  171016. #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  171017. i = _byteswap_ulong(pCoord->u);
  171018. memcpy(p, &i, 4);
  171019. #elif SQLITE_BYTEORDER==4321
  171020. i = pCoord->u;
  171021. memcpy(p, &i, 4);
  171022. #else
  171023. i = pCoord->u;
  171024. p[0] = (i>>24)&0xFF;
  171025. p[1] = (i>>16)&0xFF;
  171026. p[2] = (i>> 8)&0xFF;
  171027. p[3] = (i>> 0)&0xFF;
  171028. #endif
  171029. return 4;
  171030. }
  171031. static int writeInt64(u8 *p, i64 i){
  171032. #if SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  171033. i = (i64)__builtin_bswap64((u64)i);
  171034. memcpy(p, &i, 8);
  171035. #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  171036. i = (i64)_byteswap_uint64((u64)i);
  171037. memcpy(p, &i, 8);
  171038. #elif SQLITE_BYTEORDER==4321
  171039. memcpy(p, &i, 8);
  171040. #else
  171041. p[0] = (i>>56)&0xFF;
  171042. p[1] = (i>>48)&0xFF;
  171043. p[2] = (i>>40)&0xFF;
  171044. p[3] = (i>>32)&0xFF;
  171045. p[4] = (i>>24)&0xFF;
  171046. p[5] = (i>>16)&0xFF;
  171047. p[6] = (i>> 8)&0xFF;
  171048. p[7] = (i>> 0)&0xFF;
  171049. #endif
  171050. return 8;
  171051. }
  171052. /*
  171053. ** Increment the reference count of node p.
  171054. */
  171055. static void nodeReference(RtreeNode *p){
  171056. if( p ){
  171057. assert( p->nRef>0 );
  171058. p->nRef++;
  171059. }
  171060. }
  171061. /*
  171062. ** Clear the content of node p (set all bytes to 0x00).
  171063. */
  171064. static void nodeZero(Rtree *pRtree, RtreeNode *p){
  171065. memset(&p->zData[2], 0, pRtree->iNodeSize-2);
  171066. p->isDirty = 1;
  171067. }
  171068. /*
  171069. ** Given a node number iNode, return the corresponding key to use
  171070. ** in the Rtree.aHash table.
  171071. */
  171072. static unsigned int nodeHash(i64 iNode){
  171073. return ((unsigned)iNode) % HASHSIZE;
  171074. }
  171075. /*
  171076. ** Search the node hash table for node iNode. If found, return a pointer
  171077. ** to it. Otherwise, return 0.
  171078. */
  171079. static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
  171080. RtreeNode *p;
  171081. for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
  171082. return p;
  171083. }
  171084. /*
  171085. ** Add node pNode to the node hash table.
  171086. */
  171087. static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
  171088. int iHash;
  171089. assert( pNode->pNext==0 );
  171090. iHash = nodeHash(pNode->iNode);
  171091. pNode->pNext = pRtree->aHash[iHash];
  171092. pRtree->aHash[iHash] = pNode;
  171093. }
  171094. /*
  171095. ** Remove node pNode from the node hash table.
  171096. */
  171097. static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
  171098. RtreeNode **pp;
  171099. if( pNode->iNode!=0 ){
  171100. pp = &pRtree->aHash[nodeHash(pNode->iNode)];
  171101. for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
  171102. *pp = pNode->pNext;
  171103. pNode->pNext = 0;
  171104. }
  171105. }
  171106. /*
  171107. ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
  171108. ** indicating that node has not yet been assigned a node number. It is
  171109. ** assigned a node number when nodeWrite() is called to write the
  171110. ** node contents out to the database.
  171111. */
  171112. static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
  171113. RtreeNode *pNode;
  171114. pNode = (RtreeNode *)sqlite3_malloc64(sizeof(RtreeNode) + pRtree->iNodeSize);
  171115. if( pNode ){
  171116. memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
  171117. pNode->zData = (u8 *)&pNode[1];
  171118. pNode->nRef = 1;
  171119. pRtree->nNodeRef++;
  171120. pNode->pParent = pParent;
  171121. pNode->isDirty = 1;
  171122. nodeReference(pParent);
  171123. }
  171124. return pNode;
  171125. }
  171126. /*
  171127. ** Clear the Rtree.pNodeBlob object
  171128. */
  171129. static void nodeBlobReset(Rtree *pRtree){
  171130. if( pRtree->pNodeBlob && pRtree->inWrTrans==0 && pRtree->nCursor==0 ){
  171131. sqlite3_blob *pBlob = pRtree->pNodeBlob;
  171132. pRtree->pNodeBlob = 0;
  171133. sqlite3_blob_close(pBlob);
  171134. }
  171135. }
  171136. /*
  171137. ** Check to see if pNode is the same as pParent or any of the parents
  171138. ** of pParent.
  171139. */
  171140. static int nodeInParentChain(const RtreeNode *pNode, const RtreeNode *pParent){
  171141. do{
  171142. if( pNode==pParent ) return 1;
  171143. pParent = pParent->pParent;
  171144. }while( pParent );
  171145. return 0;
  171146. }
  171147. /*
  171148. ** Obtain a reference to an r-tree node.
  171149. */
  171150. static int nodeAcquire(
  171151. Rtree *pRtree, /* R-tree structure */
  171152. i64 iNode, /* Node number to load */
  171153. RtreeNode *pParent, /* Either the parent node or NULL */
  171154. RtreeNode **ppNode /* OUT: Acquired node */
  171155. ){
  171156. int rc = SQLITE_OK;
  171157. RtreeNode *pNode = 0;
  171158. /* Check if the requested node is already in the hash table. If so,
  171159. ** increase its reference count and return it.
  171160. */
  171161. if( (pNode = nodeHashLookup(pRtree, iNode))!=0 ){
  171162. assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
  171163. if( pParent && !pNode->pParent ){
  171164. if( nodeInParentChain(pNode, pParent) ){
  171165. RTREE_IS_CORRUPT(pRtree);
  171166. return SQLITE_CORRUPT_VTAB;
  171167. }
  171168. pParent->nRef++;
  171169. pNode->pParent = pParent;
  171170. }
  171171. pNode->nRef++;
  171172. *ppNode = pNode;
  171173. return SQLITE_OK;
  171174. }
  171175. if( pRtree->pNodeBlob ){
  171176. sqlite3_blob *pBlob = pRtree->pNodeBlob;
  171177. pRtree->pNodeBlob = 0;
  171178. rc = sqlite3_blob_reopen(pBlob, iNode);
  171179. pRtree->pNodeBlob = pBlob;
  171180. if( rc ){
  171181. nodeBlobReset(pRtree);
  171182. if( rc==SQLITE_NOMEM ) return SQLITE_NOMEM;
  171183. }
  171184. }
  171185. if( pRtree->pNodeBlob==0 ){
  171186. char *zTab = sqlite3_mprintf("%s_node", pRtree->zName);
  171187. if( zTab==0 ) return SQLITE_NOMEM;
  171188. rc = sqlite3_blob_open(pRtree->db, pRtree->zDb, zTab, "data", iNode, 0,
  171189. &pRtree->pNodeBlob);
  171190. sqlite3_free(zTab);
  171191. }
  171192. if( rc ){
  171193. nodeBlobReset(pRtree);
  171194. *ppNode = 0;
  171195. /* If unable to open an sqlite3_blob on the desired row, that can only
  171196. ** be because the shadow tables hold erroneous data. */
  171197. if( rc==SQLITE_ERROR ){
  171198. rc = SQLITE_CORRUPT_VTAB;
  171199. RTREE_IS_CORRUPT(pRtree);
  171200. }
  171201. }else if( pRtree->iNodeSize==sqlite3_blob_bytes(pRtree->pNodeBlob) ){
  171202. pNode = (RtreeNode *)sqlite3_malloc64(sizeof(RtreeNode)+pRtree->iNodeSize);
  171203. if( !pNode ){
  171204. rc = SQLITE_NOMEM;
  171205. }else{
  171206. pNode->pParent = pParent;
  171207. pNode->zData = (u8 *)&pNode[1];
  171208. pNode->nRef = 1;
  171209. pRtree->nNodeRef++;
  171210. pNode->iNode = iNode;
  171211. pNode->isDirty = 0;
  171212. pNode->pNext = 0;
  171213. rc = sqlite3_blob_read(pRtree->pNodeBlob, pNode->zData,
  171214. pRtree->iNodeSize, 0);
  171215. }
  171216. }
  171217. /* If the root node was just loaded, set pRtree->iDepth to the height
  171218. ** of the r-tree structure. A height of zero means all data is stored on
  171219. ** the root node. A height of one means the children of the root node
  171220. ** are the leaves, and so on. If the depth as specified on the root node
  171221. ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
  171222. */
  171223. if( pNode && iNode==1 ){
  171224. pRtree->iDepth = readInt16(pNode->zData);
  171225. if( pRtree->iDepth>RTREE_MAX_DEPTH ){
  171226. rc = SQLITE_CORRUPT_VTAB;
  171227. RTREE_IS_CORRUPT(pRtree);
  171228. }
  171229. }
  171230. /* If no error has occurred so far, check if the "number of entries"
  171231. ** field on the node is too large. If so, set the return code to
  171232. ** SQLITE_CORRUPT_VTAB.
  171233. */
  171234. if( pNode && rc==SQLITE_OK ){
  171235. if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
  171236. rc = SQLITE_CORRUPT_VTAB;
  171237. RTREE_IS_CORRUPT(pRtree);
  171238. }
  171239. }
  171240. if( rc==SQLITE_OK ){
  171241. if( pNode!=0 ){
  171242. nodeReference(pParent);
  171243. nodeHashInsert(pRtree, pNode);
  171244. }else{
  171245. rc = SQLITE_CORRUPT_VTAB;
  171246. RTREE_IS_CORRUPT(pRtree);
  171247. }
  171248. *ppNode = pNode;
  171249. }else{
  171250. if( pNode ){
  171251. pRtree->nNodeRef--;
  171252. sqlite3_free(pNode);
  171253. }
  171254. *ppNode = 0;
  171255. }
  171256. return rc;
  171257. }
  171258. /*
  171259. ** Overwrite cell iCell of node pNode with the contents of pCell.
  171260. */
  171261. static void nodeOverwriteCell(
  171262. Rtree *pRtree, /* The overall R-Tree */
  171263. RtreeNode *pNode, /* The node into which the cell is to be written */
  171264. RtreeCell *pCell, /* The cell to write */
  171265. int iCell /* Index into pNode into which pCell is written */
  171266. ){
  171267. int ii;
  171268. u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
  171269. p += writeInt64(p, pCell->iRowid);
  171270. for(ii=0; ii<pRtree->nDim2; ii++){
  171271. p += writeCoord(p, &pCell->aCoord[ii]);
  171272. }
  171273. pNode->isDirty = 1;
  171274. }
  171275. /*
  171276. ** Remove the cell with index iCell from node pNode.
  171277. */
  171278. static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
  171279. u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
  171280. u8 *pSrc = &pDst[pRtree->nBytesPerCell];
  171281. int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
  171282. memmove(pDst, pSrc, nByte);
  171283. writeInt16(&pNode->zData[2], NCELL(pNode)-1);
  171284. pNode->isDirty = 1;
  171285. }
  171286. /*
  171287. ** Insert the contents of cell pCell into node pNode. If the insert
  171288. ** is successful, return SQLITE_OK.
  171289. **
  171290. ** If there is not enough free space in pNode, return SQLITE_FULL.
  171291. */
  171292. static int nodeInsertCell(
  171293. Rtree *pRtree, /* The overall R-Tree */
  171294. RtreeNode *pNode, /* Write new cell into this node */
  171295. RtreeCell *pCell /* The cell to be inserted */
  171296. ){
  171297. int nCell; /* Current number of cells in pNode */
  171298. int nMaxCell; /* Maximum number of cells for pNode */
  171299. nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
  171300. nCell = NCELL(pNode);
  171301. assert( nCell<=nMaxCell );
  171302. if( nCell<nMaxCell ){
  171303. nodeOverwriteCell(pRtree, pNode, pCell, nCell);
  171304. writeInt16(&pNode->zData[2], nCell+1);
  171305. pNode->isDirty = 1;
  171306. }
  171307. return (nCell==nMaxCell);
  171308. }
  171309. /*
  171310. ** If the node is dirty, write it out to the database.
  171311. */
  171312. static int nodeWrite(Rtree *pRtree, RtreeNode *pNode){
  171313. int rc = SQLITE_OK;
  171314. if( pNode->isDirty ){
  171315. sqlite3_stmt *p = pRtree->pWriteNode;
  171316. if( pNode->iNode ){
  171317. sqlite3_bind_int64(p, 1, pNode->iNode);
  171318. }else{
  171319. sqlite3_bind_null(p, 1);
  171320. }
  171321. sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
  171322. sqlite3_step(p);
  171323. pNode->isDirty = 0;
  171324. rc = sqlite3_reset(p);
  171325. sqlite3_bind_null(p, 2);
  171326. if( pNode->iNode==0 && rc==SQLITE_OK ){
  171327. pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
  171328. nodeHashInsert(pRtree, pNode);
  171329. }
  171330. }
  171331. return rc;
  171332. }
  171333. /*
  171334. ** Release a reference to a node. If the node is dirty and the reference
  171335. ** count drops to zero, the node data is written to the database.
  171336. */
  171337. static int nodeRelease(Rtree *pRtree, RtreeNode *pNode){
  171338. int rc = SQLITE_OK;
  171339. if( pNode ){
  171340. assert( pNode->nRef>0 );
  171341. assert( pRtree->nNodeRef>0 );
  171342. pNode->nRef--;
  171343. if( pNode->nRef==0 ){
  171344. pRtree->nNodeRef--;
  171345. if( pNode->iNode==1 ){
  171346. pRtree->iDepth = -1;
  171347. }
  171348. if( pNode->pParent ){
  171349. rc = nodeRelease(pRtree, pNode->pParent);
  171350. }
  171351. if( rc==SQLITE_OK ){
  171352. rc = nodeWrite(pRtree, pNode);
  171353. }
  171354. nodeHashDelete(pRtree, pNode);
  171355. sqlite3_free(pNode);
  171356. }
  171357. }
  171358. return rc;
  171359. }
  171360. /*
  171361. ** Return the 64-bit integer value associated with cell iCell of
  171362. ** node pNode. If pNode is a leaf node, this is a rowid. If it is
  171363. ** an internal node, then the 64-bit integer is a child page number.
  171364. */
  171365. static i64 nodeGetRowid(
  171366. Rtree *pRtree, /* The overall R-Tree */
  171367. RtreeNode *pNode, /* The node from which to extract the ID */
  171368. int iCell /* The cell index from which to extract the ID */
  171369. ){
  171370. assert( iCell<NCELL(pNode) );
  171371. return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
  171372. }
  171373. /*
  171374. ** Return coordinate iCoord from cell iCell in node pNode.
  171375. */
  171376. static void nodeGetCoord(
  171377. Rtree *pRtree, /* The overall R-Tree */
  171378. RtreeNode *pNode, /* The node from which to extract a coordinate */
  171379. int iCell, /* The index of the cell within the node */
  171380. int iCoord, /* Which coordinate to extract */
  171381. RtreeCoord *pCoord /* OUT: Space to write result to */
  171382. ){
  171383. readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
  171384. }
  171385. /*
  171386. ** Deserialize cell iCell of node pNode. Populate the structure pointed
  171387. ** to by pCell with the results.
  171388. */
  171389. static void nodeGetCell(
  171390. Rtree *pRtree, /* The overall R-Tree */
  171391. RtreeNode *pNode, /* The node containing the cell to be read */
  171392. int iCell, /* Index of the cell within the node */
  171393. RtreeCell *pCell /* OUT: Write the cell contents here */
  171394. ){
  171395. u8 *pData;
  171396. RtreeCoord *pCoord;
  171397. int ii = 0;
  171398. pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
  171399. pData = pNode->zData + (12 + pRtree->nBytesPerCell*iCell);
  171400. pCoord = pCell->aCoord;
  171401. do{
  171402. readCoord(pData, &pCoord[ii]);
  171403. readCoord(pData+4, &pCoord[ii+1]);
  171404. pData += 8;
  171405. ii += 2;
  171406. }while( ii<pRtree->nDim2 );
  171407. }
  171408. /* Forward declaration for the function that does the work of
  171409. ** the virtual table module xCreate() and xConnect() methods.
  171410. */
  171411. static int rtreeInit(
  171412. sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
  171413. );
  171414. /*
  171415. ** Rtree virtual table module xCreate method.
  171416. */
  171417. static int rtreeCreate(
  171418. sqlite3 *db,
  171419. void *pAux,
  171420. int argc, const char *const*argv,
  171421. sqlite3_vtab **ppVtab,
  171422. char **pzErr
  171423. ){
  171424. return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
  171425. }
  171426. /*
  171427. ** Rtree virtual table module xConnect method.
  171428. */
  171429. static int rtreeConnect(
  171430. sqlite3 *db,
  171431. void *pAux,
  171432. int argc, const char *const*argv,
  171433. sqlite3_vtab **ppVtab,
  171434. char **pzErr
  171435. ){
  171436. return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
  171437. }
  171438. /*
  171439. ** Increment the r-tree reference count.
  171440. */
  171441. static void rtreeReference(Rtree *pRtree){
  171442. pRtree->nBusy++;
  171443. }
  171444. /*
  171445. ** Decrement the r-tree reference count. When the reference count reaches
  171446. ** zero the structure is deleted.
  171447. */
  171448. static void rtreeRelease(Rtree *pRtree){
  171449. pRtree->nBusy--;
  171450. if( pRtree->nBusy==0 ){
  171451. pRtree->inWrTrans = 0;
  171452. assert( pRtree->nCursor==0 );
  171453. nodeBlobReset(pRtree);
  171454. assert( pRtree->nNodeRef==0 || pRtree->bCorrupt );
  171455. sqlite3_finalize(pRtree->pWriteNode);
  171456. sqlite3_finalize(pRtree->pDeleteNode);
  171457. sqlite3_finalize(pRtree->pReadRowid);
  171458. sqlite3_finalize(pRtree->pWriteRowid);
  171459. sqlite3_finalize(pRtree->pDeleteRowid);
  171460. sqlite3_finalize(pRtree->pReadParent);
  171461. sqlite3_finalize(pRtree->pWriteParent);
  171462. sqlite3_finalize(pRtree->pDeleteParent);
  171463. sqlite3_finalize(pRtree->pWriteAux);
  171464. sqlite3_free(pRtree->zReadAuxSql);
  171465. sqlite3_free(pRtree);
  171466. }
  171467. }
  171468. /*
  171469. ** Rtree virtual table module xDisconnect method.
  171470. */
  171471. static int rtreeDisconnect(sqlite3_vtab *pVtab){
  171472. rtreeRelease((Rtree *)pVtab);
  171473. return SQLITE_OK;
  171474. }
  171475. /*
  171476. ** Rtree virtual table module xDestroy method.
  171477. */
  171478. static int rtreeDestroy(sqlite3_vtab *pVtab){
  171479. Rtree *pRtree = (Rtree *)pVtab;
  171480. int rc;
  171481. char *zCreate = sqlite3_mprintf(
  171482. "DROP TABLE '%q'.'%q_node';"
  171483. "DROP TABLE '%q'.'%q_rowid';"
  171484. "DROP TABLE '%q'.'%q_parent';",
  171485. pRtree->zDb, pRtree->zName,
  171486. pRtree->zDb, pRtree->zName,
  171487. pRtree->zDb, pRtree->zName
  171488. );
  171489. if( !zCreate ){
  171490. rc = SQLITE_NOMEM;
  171491. }else{
  171492. nodeBlobReset(pRtree);
  171493. rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
  171494. sqlite3_free(zCreate);
  171495. }
  171496. if( rc==SQLITE_OK ){
  171497. rtreeRelease(pRtree);
  171498. }
  171499. return rc;
  171500. }
  171501. /*
  171502. ** Rtree virtual table module xOpen method.
  171503. */
  171504. static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  171505. int rc = SQLITE_NOMEM;
  171506. Rtree *pRtree = (Rtree *)pVTab;
  171507. RtreeCursor *pCsr;
  171508. pCsr = (RtreeCursor *)sqlite3_malloc64(sizeof(RtreeCursor));
  171509. if( pCsr ){
  171510. memset(pCsr, 0, sizeof(RtreeCursor));
  171511. pCsr->base.pVtab = pVTab;
  171512. rc = SQLITE_OK;
  171513. pRtree->nCursor++;
  171514. }
  171515. *ppCursor = (sqlite3_vtab_cursor *)pCsr;
  171516. return rc;
  171517. }
  171518. /*
  171519. ** Free the RtreeCursor.aConstraint[] array and its contents.
  171520. */
  171521. static void freeCursorConstraints(RtreeCursor *pCsr){
  171522. if( pCsr->aConstraint ){
  171523. int i; /* Used to iterate through constraint array */
  171524. for(i=0; i<pCsr->nConstraint; i++){
  171525. sqlite3_rtree_query_info *pInfo = pCsr->aConstraint[i].pInfo;
  171526. if( pInfo ){
  171527. if( pInfo->xDelUser ) pInfo->xDelUser(pInfo->pUser);
  171528. sqlite3_free(pInfo);
  171529. }
  171530. }
  171531. sqlite3_free(pCsr->aConstraint);
  171532. pCsr->aConstraint = 0;
  171533. }
  171534. }
  171535. /*
  171536. ** Rtree virtual table module xClose method.
  171537. */
  171538. static int rtreeClose(sqlite3_vtab_cursor *cur){
  171539. Rtree *pRtree = (Rtree *)(cur->pVtab);
  171540. int ii;
  171541. RtreeCursor *pCsr = (RtreeCursor *)cur;
  171542. assert( pRtree->nCursor>0 );
  171543. freeCursorConstraints(pCsr);
  171544. sqlite3_finalize(pCsr->pReadAux);
  171545. sqlite3_free(pCsr->aPoint);
  171546. for(ii=0; ii<RTREE_CACHE_SZ; ii++) nodeRelease(pRtree, pCsr->aNode[ii]);
  171547. sqlite3_free(pCsr);
  171548. pRtree->nCursor--;
  171549. nodeBlobReset(pRtree);
  171550. return SQLITE_OK;
  171551. }
  171552. /*
  171553. ** Rtree virtual table module xEof method.
  171554. **
  171555. ** Return non-zero if the cursor does not currently point to a valid
  171556. ** record (i.e if the scan has finished), or zero otherwise.
  171557. */
  171558. static int rtreeEof(sqlite3_vtab_cursor *cur){
  171559. RtreeCursor *pCsr = (RtreeCursor *)cur;
  171560. return pCsr->atEOF;
  171561. }
  171562. /*
  171563. ** Convert raw bits from the on-disk RTree record into a coordinate value.
  171564. ** The on-disk format is big-endian and needs to be converted for little-
  171565. ** endian platforms. The on-disk record stores integer coordinates if
  171566. ** eInt is true and it stores 32-bit floating point records if eInt is
  171567. ** false. a[] is the four bytes of the on-disk record to be decoded.
  171568. ** Store the results in "r".
  171569. **
  171570. ** There are five versions of this macro. The last one is generic. The
  171571. ** other four are various architectures-specific optimizations.
  171572. */
  171573. #if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  171574. #define RTREE_DECODE_COORD(eInt, a, r) { \
  171575. RtreeCoord c; /* Coordinate decoded */ \
  171576. c.u = _byteswap_ulong(*(u32*)a); \
  171577. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  171578. }
  171579. #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  171580. #define RTREE_DECODE_COORD(eInt, a, r) { \
  171581. RtreeCoord c; /* Coordinate decoded */ \
  171582. c.u = __builtin_bswap32(*(u32*)a); \
  171583. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  171584. }
  171585. #elif SQLITE_BYTEORDER==1234
  171586. #define RTREE_DECODE_COORD(eInt, a, r) { \
  171587. RtreeCoord c; /* Coordinate decoded */ \
  171588. memcpy(&c.u,a,4); \
  171589. c.u = ((c.u>>24)&0xff)|((c.u>>8)&0xff00)| \
  171590. ((c.u&0xff)<<24)|((c.u&0xff00)<<8); \
  171591. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  171592. }
  171593. #elif SQLITE_BYTEORDER==4321
  171594. #define RTREE_DECODE_COORD(eInt, a, r) { \
  171595. RtreeCoord c; /* Coordinate decoded */ \
  171596. memcpy(&c.u,a,4); \
  171597. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  171598. }
  171599. #else
  171600. #define RTREE_DECODE_COORD(eInt, a, r) { \
  171601. RtreeCoord c; /* Coordinate decoded */ \
  171602. c.u = ((u32)a[0]<<24) + ((u32)a[1]<<16) \
  171603. +((u32)a[2]<<8) + a[3]; \
  171604. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  171605. }
  171606. #endif
  171607. /*
  171608. ** Check the RTree node or entry given by pCellData and p against the MATCH
  171609. ** constraint pConstraint.
  171610. */
  171611. static int rtreeCallbackConstraint(
  171612. RtreeConstraint *pConstraint, /* The constraint to test */
  171613. int eInt, /* True if RTree holding integer coordinates */
  171614. u8 *pCellData, /* Raw cell content */
  171615. RtreeSearchPoint *pSearch, /* Container of this cell */
  171616. sqlite3_rtree_dbl *prScore, /* OUT: score for the cell */
  171617. int *peWithin /* OUT: visibility of the cell */
  171618. ){
  171619. sqlite3_rtree_query_info *pInfo = pConstraint->pInfo; /* Callback info */
  171620. int nCoord = pInfo->nCoord; /* No. of coordinates */
  171621. int rc; /* Callback return code */
  171622. RtreeCoord c; /* Translator union */
  171623. sqlite3_rtree_dbl aCoord[RTREE_MAX_DIMENSIONS*2]; /* Decoded coordinates */
  171624. assert( pConstraint->op==RTREE_MATCH || pConstraint->op==RTREE_QUERY );
  171625. assert( nCoord==2 || nCoord==4 || nCoord==6 || nCoord==8 || nCoord==10 );
  171626. if( pConstraint->op==RTREE_QUERY && pSearch->iLevel==1 ){
  171627. pInfo->iRowid = readInt64(pCellData);
  171628. }
  171629. pCellData += 8;
  171630. #ifndef SQLITE_RTREE_INT_ONLY
  171631. if( eInt==0 ){
  171632. switch( nCoord ){
  171633. case 10: readCoord(pCellData+36, &c); aCoord[9] = c.f;
  171634. readCoord(pCellData+32, &c); aCoord[8] = c.f;
  171635. case 8: readCoord(pCellData+28, &c); aCoord[7] = c.f;
  171636. readCoord(pCellData+24, &c); aCoord[6] = c.f;
  171637. case 6: readCoord(pCellData+20, &c); aCoord[5] = c.f;
  171638. readCoord(pCellData+16, &c); aCoord[4] = c.f;
  171639. case 4: readCoord(pCellData+12, &c); aCoord[3] = c.f;
  171640. readCoord(pCellData+8, &c); aCoord[2] = c.f;
  171641. default: readCoord(pCellData+4, &c); aCoord[1] = c.f;
  171642. readCoord(pCellData, &c); aCoord[0] = c.f;
  171643. }
  171644. }else
  171645. #endif
  171646. {
  171647. switch( nCoord ){
  171648. case 10: readCoord(pCellData+36, &c); aCoord[9] = c.i;
  171649. readCoord(pCellData+32, &c); aCoord[8] = c.i;
  171650. case 8: readCoord(pCellData+28, &c); aCoord[7] = c.i;
  171651. readCoord(pCellData+24, &c); aCoord[6] = c.i;
  171652. case 6: readCoord(pCellData+20, &c); aCoord[5] = c.i;
  171653. readCoord(pCellData+16, &c); aCoord[4] = c.i;
  171654. case 4: readCoord(pCellData+12, &c); aCoord[3] = c.i;
  171655. readCoord(pCellData+8, &c); aCoord[2] = c.i;
  171656. default: readCoord(pCellData+4, &c); aCoord[1] = c.i;
  171657. readCoord(pCellData, &c); aCoord[0] = c.i;
  171658. }
  171659. }
  171660. if( pConstraint->op==RTREE_MATCH ){
  171661. int eWithin = 0;
  171662. rc = pConstraint->u.xGeom((sqlite3_rtree_geometry*)pInfo,
  171663. nCoord, aCoord, &eWithin);
  171664. if( eWithin==0 ) *peWithin = NOT_WITHIN;
  171665. *prScore = RTREE_ZERO;
  171666. }else{
  171667. pInfo->aCoord = aCoord;
  171668. pInfo->iLevel = pSearch->iLevel - 1;
  171669. pInfo->rScore = pInfo->rParentScore = pSearch->rScore;
  171670. pInfo->eWithin = pInfo->eParentWithin = pSearch->eWithin;
  171671. rc = pConstraint->u.xQueryFunc(pInfo);
  171672. if( pInfo->eWithin<*peWithin ) *peWithin = pInfo->eWithin;
  171673. if( pInfo->rScore<*prScore || *prScore<RTREE_ZERO ){
  171674. *prScore = pInfo->rScore;
  171675. }
  171676. }
  171677. return rc;
  171678. }
  171679. /*
  171680. ** Check the internal RTree node given by pCellData against constraint p.
  171681. ** If this constraint cannot be satisfied by any child within the node,
  171682. ** set *peWithin to NOT_WITHIN.
  171683. */
  171684. static void rtreeNonleafConstraint(
  171685. RtreeConstraint *p, /* The constraint to test */
  171686. int eInt, /* True if RTree holds integer coordinates */
  171687. u8 *pCellData, /* Raw cell content as appears on disk */
  171688. int *peWithin /* Adjust downward, as appropriate */
  171689. ){
  171690. sqlite3_rtree_dbl val; /* Coordinate value convert to a double */
  171691. /* p->iCoord might point to either a lower or upper bound coordinate
  171692. ** in a coordinate pair. But make pCellData point to the lower bound.
  171693. */
  171694. pCellData += 8 + 4*(p->iCoord&0xfe);
  171695. assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
  171696. || p->op==RTREE_GT || p->op==RTREE_EQ );
  171697. assert( ((((char*)pCellData) - (char*)0)&3)==0 ); /* 4-byte aligned */
  171698. switch( p->op ){
  171699. case RTREE_LE:
  171700. case RTREE_LT:
  171701. case RTREE_EQ:
  171702. RTREE_DECODE_COORD(eInt, pCellData, val);
  171703. /* val now holds the lower bound of the coordinate pair */
  171704. if( p->u.rValue>=val ) return;
  171705. if( p->op!=RTREE_EQ ) break; /* RTREE_LE and RTREE_LT end here */
  171706. /* Fall through for the RTREE_EQ case */
  171707. default: /* RTREE_GT or RTREE_GE, or fallthrough of RTREE_EQ */
  171708. pCellData += 4;
  171709. RTREE_DECODE_COORD(eInt, pCellData, val);
  171710. /* val now holds the upper bound of the coordinate pair */
  171711. if( p->u.rValue<=val ) return;
  171712. }
  171713. *peWithin = NOT_WITHIN;
  171714. }
  171715. /*
  171716. ** Check the leaf RTree cell given by pCellData against constraint p.
  171717. ** If this constraint is not satisfied, set *peWithin to NOT_WITHIN.
  171718. ** If the constraint is satisfied, leave *peWithin unchanged.
  171719. **
  171720. ** The constraint is of the form: xN op $val
  171721. **
  171722. ** The op is given by p->op. The xN is p->iCoord-th coordinate in
  171723. ** pCellData. $val is given by p->u.rValue.
  171724. */
  171725. static void rtreeLeafConstraint(
  171726. RtreeConstraint *p, /* The constraint to test */
  171727. int eInt, /* True if RTree holds integer coordinates */
  171728. u8 *pCellData, /* Raw cell content as appears on disk */
  171729. int *peWithin /* Adjust downward, as appropriate */
  171730. ){
  171731. RtreeDValue xN; /* Coordinate value converted to a double */
  171732. assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
  171733. || p->op==RTREE_GT || p->op==RTREE_EQ );
  171734. pCellData += 8 + p->iCoord*4;
  171735. assert( ((((char*)pCellData) - (char*)0)&3)==0 ); /* 4-byte aligned */
  171736. RTREE_DECODE_COORD(eInt, pCellData, xN);
  171737. switch( p->op ){
  171738. case RTREE_LE: if( xN <= p->u.rValue ) return; break;
  171739. case RTREE_LT: if( xN < p->u.rValue ) return; break;
  171740. case RTREE_GE: if( xN >= p->u.rValue ) return; break;
  171741. case RTREE_GT: if( xN > p->u.rValue ) return; break;
  171742. default: if( xN == p->u.rValue ) return; break;
  171743. }
  171744. *peWithin = NOT_WITHIN;
  171745. }
  171746. /*
  171747. ** One of the cells in node pNode is guaranteed to have a 64-bit
  171748. ** integer value equal to iRowid. Return the index of this cell.
  171749. */
  171750. static int nodeRowidIndex(
  171751. Rtree *pRtree,
  171752. RtreeNode *pNode,
  171753. i64 iRowid,
  171754. int *piIndex
  171755. ){
  171756. int ii;
  171757. int nCell = NCELL(pNode);
  171758. assert( nCell<200 );
  171759. for(ii=0; ii<nCell; ii++){
  171760. if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
  171761. *piIndex = ii;
  171762. return SQLITE_OK;
  171763. }
  171764. }
  171765. RTREE_IS_CORRUPT(pRtree);
  171766. return SQLITE_CORRUPT_VTAB;
  171767. }
  171768. /*
  171769. ** Return the index of the cell containing a pointer to node pNode
  171770. ** in its parent. If pNode is the root node, return -1.
  171771. */
  171772. static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
  171773. RtreeNode *pParent = pNode->pParent;
  171774. if( pParent ){
  171775. return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
  171776. }
  171777. *piIndex = -1;
  171778. return SQLITE_OK;
  171779. }
  171780. /*
  171781. ** Compare two search points. Return negative, zero, or positive if the first
  171782. ** is less than, equal to, or greater than the second.
  171783. **
  171784. ** The rScore is the primary key. Smaller rScore values come first.
  171785. ** If the rScore is a tie, then use iLevel as the tie breaker with smaller
  171786. ** iLevel values coming first. In this way, if rScore is the same for all
  171787. ** SearchPoints, then iLevel becomes the deciding factor and the result
  171788. ** is a depth-first search, which is the desired default behavior.
  171789. */
  171790. static int rtreeSearchPointCompare(
  171791. const RtreeSearchPoint *pA,
  171792. const RtreeSearchPoint *pB
  171793. ){
  171794. if( pA->rScore<pB->rScore ) return -1;
  171795. if( pA->rScore>pB->rScore ) return +1;
  171796. if( pA->iLevel<pB->iLevel ) return -1;
  171797. if( pA->iLevel>pB->iLevel ) return +1;
  171798. return 0;
  171799. }
  171800. /*
  171801. ** Interchange two search points in a cursor.
  171802. */
  171803. static void rtreeSearchPointSwap(RtreeCursor *p, int i, int j){
  171804. RtreeSearchPoint t = p->aPoint[i];
  171805. assert( i<j );
  171806. p->aPoint[i] = p->aPoint[j];
  171807. p->aPoint[j] = t;
  171808. i++; j++;
  171809. if( i<RTREE_CACHE_SZ ){
  171810. if( j>=RTREE_CACHE_SZ ){
  171811. nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
  171812. p->aNode[i] = 0;
  171813. }else{
  171814. RtreeNode *pTemp = p->aNode[i];
  171815. p->aNode[i] = p->aNode[j];
  171816. p->aNode[j] = pTemp;
  171817. }
  171818. }
  171819. }
  171820. /*
  171821. ** Return the search point with the lowest current score.
  171822. */
  171823. static RtreeSearchPoint *rtreeSearchPointFirst(RtreeCursor *pCur){
  171824. return pCur->bPoint ? &pCur->sPoint : pCur->nPoint ? pCur->aPoint : 0;
  171825. }
  171826. /*
  171827. ** Get the RtreeNode for the search point with the lowest score.
  171828. */
  171829. static RtreeNode *rtreeNodeOfFirstSearchPoint(RtreeCursor *pCur, int *pRC){
  171830. sqlite3_int64 id;
  171831. int ii = 1 - pCur->bPoint;
  171832. assert( ii==0 || ii==1 );
  171833. assert( pCur->bPoint || pCur->nPoint );
  171834. if( pCur->aNode[ii]==0 ){
  171835. assert( pRC!=0 );
  171836. id = ii ? pCur->aPoint[0].id : pCur->sPoint.id;
  171837. *pRC = nodeAcquire(RTREE_OF_CURSOR(pCur), id, 0, &pCur->aNode[ii]);
  171838. }
  171839. return pCur->aNode[ii];
  171840. }
  171841. /*
  171842. ** Push a new element onto the priority queue
  171843. */
  171844. static RtreeSearchPoint *rtreeEnqueue(
  171845. RtreeCursor *pCur, /* The cursor */
  171846. RtreeDValue rScore, /* Score for the new search point */
  171847. u8 iLevel /* Level for the new search point */
  171848. ){
  171849. int i, j;
  171850. RtreeSearchPoint *pNew;
  171851. if( pCur->nPoint>=pCur->nPointAlloc ){
  171852. int nNew = pCur->nPointAlloc*2 + 8;
  171853. pNew = sqlite3_realloc64(pCur->aPoint, nNew*sizeof(pCur->aPoint[0]));
  171854. if( pNew==0 ) return 0;
  171855. pCur->aPoint = pNew;
  171856. pCur->nPointAlloc = nNew;
  171857. }
  171858. i = pCur->nPoint++;
  171859. pNew = pCur->aPoint + i;
  171860. pNew->rScore = rScore;
  171861. pNew->iLevel = iLevel;
  171862. assert( iLevel<=RTREE_MAX_DEPTH );
  171863. while( i>0 ){
  171864. RtreeSearchPoint *pParent;
  171865. j = (i-1)/2;
  171866. pParent = pCur->aPoint + j;
  171867. if( rtreeSearchPointCompare(pNew, pParent)>=0 ) break;
  171868. rtreeSearchPointSwap(pCur, j, i);
  171869. i = j;
  171870. pNew = pParent;
  171871. }
  171872. return pNew;
  171873. }
  171874. /*
  171875. ** Allocate a new RtreeSearchPoint and return a pointer to it. Return
  171876. ** NULL if malloc fails.
  171877. */
  171878. static RtreeSearchPoint *rtreeSearchPointNew(
  171879. RtreeCursor *pCur, /* The cursor */
  171880. RtreeDValue rScore, /* Score for the new search point */
  171881. u8 iLevel /* Level for the new search point */
  171882. ){
  171883. RtreeSearchPoint *pNew, *pFirst;
  171884. pFirst = rtreeSearchPointFirst(pCur);
  171885. pCur->anQueue[iLevel]++;
  171886. if( pFirst==0
  171887. || pFirst->rScore>rScore
  171888. || (pFirst->rScore==rScore && pFirst->iLevel>iLevel)
  171889. ){
  171890. if( pCur->bPoint ){
  171891. int ii;
  171892. pNew = rtreeEnqueue(pCur, rScore, iLevel);
  171893. if( pNew==0 ) return 0;
  171894. ii = (int)(pNew - pCur->aPoint) + 1;
  171895. if( ii<RTREE_CACHE_SZ ){
  171896. assert( pCur->aNode[ii]==0 );
  171897. pCur->aNode[ii] = pCur->aNode[0];
  171898. }else{
  171899. nodeRelease(RTREE_OF_CURSOR(pCur), pCur->aNode[0]);
  171900. }
  171901. pCur->aNode[0] = 0;
  171902. *pNew = pCur->sPoint;
  171903. }
  171904. pCur->sPoint.rScore = rScore;
  171905. pCur->sPoint.iLevel = iLevel;
  171906. pCur->bPoint = 1;
  171907. return &pCur->sPoint;
  171908. }else{
  171909. return rtreeEnqueue(pCur, rScore, iLevel);
  171910. }
  171911. }
  171912. #if 0
  171913. /* Tracing routines for the RtreeSearchPoint queue */
  171914. static void tracePoint(RtreeSearchPoint *p, int idx, RtreeCursor *pCur){
  171915. if( idx<0 ){ printf(" s"); }else{ printf("%2d", idx); }
  171916. printf(" %d.%05lld.%02d %g %d",
  171917. p->iLevel, p->id, p->iCell, p->rScore, p->eWithin
  171918. );
  171919. idx++;
  171920. if( idx<RTREE_CACHE_SZ ){
  171921. printf(" %p\n", pCur->aNode[idx]);
  171922. }else{
  171923. printf("\n");
  171924. }
  171925. }
  171926. static void traceQueue(RtreeCursor *pCur, const char *zPrefix){
  171927. int ii;
  171928. printf("=== %9s ", zPrefix);
  171929. if( pCur->bPoint ){
  171930. tracePoint(&pCur->sPoint, -1, pCur);
  171931. }
  171932. for(ii=0; ii<pCur->nPoint; ii++){
  171933. if( ii>0 || pCur->bPoint ) printf(" ");
  171934. tracePoint(&pCur->aPoint[ii], ii, pCur);
  171935. }
  171936. }
  171937. # define RTREE_QUEUE_TRACE(A,B) traceQueue(A,B)
  171938. #else
  171939. # define RTREE_QUEUE_TRACE(A,B) /* no-op */
  171940. #endif
  171941. /* Remove the search point with the lowest current score.
  171942. */
  171943. static void rtreeSearchPointPop(RtreeCursor *p){
  171944. int i, j, k, n;
  171945. i = 1 - p->bPoint;
  171946. assert( i==0 || i==1 );
  171947. if( p->aNode[i] ){
  171948. nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
  171949. p->aNode[i] = 0;
  171950. }
  171951. if( p->bPoint ){
  171952. p->anQueue[p->sPoint.iLevel]--;
  171953. p->bPoint = 0;
  171954. }else if( p->nPoint ){
  171955. p->anQueue[p->aPoint[0].iLevel]--;
  171956. n = --p->nPoint;
  171957. p->aPoint[0] = p->aPoint[n];
  171958. if( n<RTREE_CACHE_SZ-1 ){
  171959. p->aNode[1] = p->aNode[n+1];
  171960. p->aNode[n+1] = 0;
  171961. }
  171962. i = 0;
  171963. while( (j = i*2+1)<n ){
  171964. k = j+1;
  171965. if( k<n && rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[j])<0 ){
  171966. if( rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[i])<0 ){
  171967. rtreeSearchPointSwap(p, i, k);
  171968. i = k;
  171969. }else{
  171970. break;
  171971. }
  171972. }else{
  171973. if( rtreeSearchPointCompare(&p->aPoint[j], &p->aPoint[i])<0 ){
  171974. rtreeSearchPointSwap(p, i, j);
  171975. i = j;
  171976. }else{
  171977. break;
  171978. }
  171979. }
  171980. }
  171981. }
  171982. }
  171983. /*
  171984. ** Continue the search on cursor pCur until the front of the queue
  171985. ** contains an entry suitable for returning as a result-set row,
  171986. ** or until the RtreeSearchPoint queue is empty, indicating that the
  171987. ** query has completed.
  171988. */
  171989. static int rtreeStepToLeaf(RtreeCursor *pCur){
  171990. RtreeSearchPoint *p;
  171991. Rtree *pRtree = RTREE_OF_CURSOR(pCur);
  171992. RtreeNode *pNode;
  171993. int eWithin;
  171994. int rc = SQLITE_OK;
  171995. int nCell;
  171996. int nConstraint = pCur->nConstraint;
  171997. int ii;
  171998. int eInt;
  171999. RtreeSearchPoint x;
  172000. eInt = pRtree->eCoordType==RTREE_COORD_INT32;
  172001. while( (p = rtreeSearchPointFirst(pCur))!=0 && p->iLevel>0 ){
  172002. pNode = rtreeNodeOfFirstSearchPoint(pCur, &rc);
  172003. if( rc ) return rc;
  172004. nCell = NCELL(pNode);
  172005. assert( nCell<200 );
  172006. while( p->iCell<nCell ){
  172007. sqlite3_rtree_dbl rScore = (sqlite3_rtree_dbl)-1;
  172008. u8 *pCellData = pNode->zData + (4+pRtree->nBytesPerCell*p->iCell);
  172009. eWithin = FULLY_WITHIN;
  172010. for(ii=0; ii<nConstraint; ii++){
  172011. RtreeConstraint *pConstraint = pCur->aConstraint + ii;
  172012. if( pConstraint->op>=RTREE_MATCH ){
  172013. rc = rtreeCallbackConstraint(pConstraint, eInt, pCellData, p,
  172014. &rScore, &eWithin);
  172015. if( rc ) return rc;
  172016. }else if( p->iLevel==1 ){
  172017. rtreeLeafConstraint(pConstraint, eInt, pCellData, &eWithin);
  172018. }else{
  172019. rtreeNonleafConstraint(pConstraint, eInt, pCellData, &eWithin);
  172020. }
  172021. if( eWithin==NOT_WITHIN ) break;
  172022. }
  172023. p->iCell++;
  172024. if( eWithin==NOT_WITHIN ) continue;
  172025. x.iLevel = p->iLevel - 1;
  172026. if( x.iLevel ){
  172027. x.id = readInt64(pCellData);
  172028. x.iCell = 0;
  172029. }else{
  172030. x.id = p->id;
  172031. x.iCell = p->iCell - 1;
  172032. }
  172033. if( p->iCell>=nCell ){
  172034. RTREE_QUEUE_TRACE(pCur, "POP-S:");
  172035. rtreeSearchPointPop(pCur);
  172036. }
  172037. if( rScore<RTREE_ZERO ) rScore = RTREE_ZERO;
  172038. p = rtreeSearchPointNew(pCur, rScore, x.iLevel);
  172039. if( p==0 ) return SQLITE_NOMEM;
  172040. p->eWithin = (u8)eWithin;
  172041. p->id = x.id;
  172042. p->iCell = x.iCell;
  172043. RTREE_QUEUE_TRACE(pCur, "PUSH-S:");
  172044. break;
  172045. }
  172046. if( p->iCell>=nCell ){
  172047. RTREE_QUEUE_TRACE(pCur, "POP-Se:");
  172048. rtreeSearchPointPop(pCur);
  172049. }
  172050. }
  172051. pCur->atEOF = p==0;
  172052. return SQLITE_OK;
  172053. }
  172054. /*
  172055. ** Rtree virtual table module xNext method.
  172056. */
  172057. static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
  172058. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  172059. int rc = SQLITE_OK;
  172060. /* Move to the next entry that matches the configured constraints. */
  172061. RTREE_QUEUE_TRACE(pCsr, "POP-Nx:");
  172062. if( pCsr->bAuxValid ){
  172063. pCsr->bAuxValid = 0;
  172064. sqlite3_reset(pCsr->pReadAux);
  172065. }
  172066. rtreeSearchPointPop(pCsr);
  172067. rc = rtreeStepToLeaf(pCsr);
  172068. return rc;
  172069. }
  172070. /*
  172071. ** Rtree virtual table module xRowid method.
  172072. */
  172073. static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
  172074. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  172075. RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
  172076. int rc = SQLITE_OK;
  172077. RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
  172078. if( rc==SQLITE_OK && p ){
  172079. *pRowid = nodeGetRowid(RTREE_OF_CURSOR(pCsr), pNode, p->iCell);
  172080. }
  172081. return rc;
  172082. }
  172083. /*
  172084. ** Rtree virtual table module xColumn method.
  172085. */
  172086. static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
  172087. Rtree *pRtree = (Rtree *)cur->pVtab;
  172088. RtreeCursor *pCsr = (RtreeCursor *)cur;
  172089. RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
  172090. RtreeCoord c;
  172091. int rc = SQLITE_OK;
  172092. RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
  172093. if( rc ) return rc;
  172094. if( p==0 ) return SQLITE_OK;
  172095. if( i==0 ){
  172096. sqlite3_result_int64(ctx, nodeGetRowid(pRtree, pNode, p->iCell));
  172097. }else if( i<=pRtree->nDim2 ){
  172098. nodeGetCoord(pRtree, pNode, p->iCell, i-1, &c);
  172099. #ifndef SQLITE_RTREE_INT_ONLY
  172100. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  172101. sqlite3_result_double(ctx, c.f);
  172102. }else
  172103. #endif
  172104. {
  172105. assert( pRtree->eCoordType==RTREE_COORD_INT32 );
  172106. sqlite3_result_int(ctx, c.i);
  172107. }
  172108. }else{
  172109. if( !pCsr->bAuxValid ){
  172110. if( pCsr->pReadAux==0 ){
  172111. rc = sqlite3_prepare_v3(pRtree->db, pRtree->zReadAuxSql, -1, 0,
  172112. &pCsr->pReadAux, 0);
  172113. if( rc ) return rc;
  172114. }
  172115. sqlite3_bind_int64(pCsr->pReadAux, 1,
  172116. nodeGetRowid(pRtree, pNode, p->iCell));
  172117. rc = sqlite3_step(pCsr->pReadAux);
  172118. if( rc==SQLITE_ROW ){
  172119. pCsr->bAuxValid = 1;
  172120. }else{
  172121. sqlite3_reset(pCsr->pReadAux);
  172122. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  172123. return rc;
  172124. }
  172125. }
  172126. sqlite3_result_value(ctx,
  172127. sqlite3_column_value(pCsr->pReadAux, i - pRtree->nDim2 + 1));
  172128. }
  172129. return SQLITE_OK;
  172130. }
  172131. /*
  172132. ** Use nodeAcquire() to obtain the leaf node containing the record with
  172133. ** rowid iRowid. If successful, set *ppLeaf to point to the node and
  172134. ** return SQLITE_OK. If there is no such record in the table, set
  172135. ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
  172136. ** to zero and return an SQLite error code.
  172137. */
  172138. static int findLeafNode(
  172139. Rtree *pRtree, /* RTree to search */
  172140. i64 iRowid, /* The rowid searching for */
  172141. RtreeNode **ppLeaf, /* Write the node here */
  172142. sqlite3_int64 *piNode /* Write the node-id here */
  172143. ){
  172144. int rc;
  172145. *ppLeaf = 0;
  172146. sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
  172147. if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
  172148. i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
  172149. if( piNode ) *piNode = iNode;
  172150. rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
  172151. sqlite3_reset(pRtree->pReadRowid);
  172152. }else{
  172153. rc = sqlite3_reset(pRtree->pReadRowid);
  172154. }
  172155. return rc;
  172156. }
  172157. /*
  172158. ** This function is called to configure the RtreeConstraint object passed
  172159. ** as the second argument for a MATCH constraint. The value passed as the
  172160. ** first argument to this function is the right-hand operand to the MATCH
  172161. ** operator.
  172162. */
  172163. static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
  172164. RtreeMatchArg *pBlob, *pSrc; /* BLOB returned by geometry function */
  172165. sqlite3_rtree_query_info *pInfo; /* Callback information */
  172166. pSrc = sqlite3_value_pointer(pValue, "RtreeMatchArg");
  172167. if( pSrc==0 ) return SQLITE_ERROR;
  172168. pInfo = (sqlite3_rtree_query_info*)
  172169. sqlite3_malloc64( sizeof(*pInfo)+pSrc->iSize );
  172170. if( !pInfo ) return SQLITE_NOMEM;
  172171. memset(pInfo, 0, sizeof(*pInfo));
  172172. pBlob = (RtreeMatchArg*)&pInfo[1];
  172173. memcpy(pBlob, pSrc, pSrc->iSize);
  172174. pInfo->pContext = pBlob->cb.pContext;
  172175. pInfo->nParam = pBlob->nParam;
  172176. pInfo->aParam = pBlob->aParam;
  172177. pInfo->apSqlParam = pBlob->apSqlParam;
  172178. if( pBlob->cb.xGeom ){
  172179. pCons->u.xGeom = pBlob->cb.xGeom;
  172180. }else{
  172181. pCons->op = RTREE_QUERY;
  172182. pCons->u.xQueryFunc = pBlob->cb.xQueryFunc;
  172183. }
  172184. pCons->pInfo = pInfo;
  172185. return SQLITE_OK;
  172186. }
  172187. /*
  172188. ** Rtree virtual table module xFilter method.
  172189. */
  172190. static int rtreeFilter(
  172191. sqlite3_vtab_cursor *pVtabCursor,
  172192. int idxNum, const char *idxStr,
  172193. int argc, sqlite3_value **argv
  172194. ){
  172195. Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
  172196. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  172197. RtreeNode *pRoot = 0;
  172198. int ii;
  172199. int rc = SQLITE_OK;
  172200. int iCell = 0;
  172201. sqlite3_stmt *pStmt;
  172202. rtreeReference(pRtree);
  172203. /* Reset the cursor to the same state as rtreeOpen() leaves it in. */
  172204. freeCursorConstraints(pCsr);
  172205. sqlite3_free(pCsr->aPoint);
  172206. pStmt = pCsr->pReadAux;
  172207. memset(pCsr, 0, sizeof(RtreeCursor));
  172208. pCsr->base.pVtab = (sqlite3_vtab*)pRtree;
  172209. pCsr->pReadAux = pStmt;
  172210. pCsr->iStrategy = idxNum;
  172211. if( idxNum==1 ){
  172212. /* Special case - lookup by rowid. */
  172213. RtreeNode *pLeaf; /* Leaf on which the required cell resides */
  172214. RtreeSearchPoint *p; /* Search point for the leaf */
  172215. i64 iRowid = sqlite3_value_int64(argv[0]);
  172216. i64 iNode = 0;
  172217. rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode);
  172218. if( rc==SQLITE_OK && pLeaf!=0 ){
  172219. p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0);
  172220. assert( p!=0 ); /* Always returns pCsr->sPoint */
  172221. pCsr->aNode[0] = pLeaf;
  172222. p->id = iNode;
  172223. p->eWithin = PARTLY_WITHIN;
  172224. rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &iCell);
  172225. p->iCell = (u8)iCell;
  172226. RTREE_QUEUE_TRACE(pCsr, "PUSH-F1:");
  172227. }else{
  172228. pCsr->atEOF = 1;
  172229. }
  172230. }else{
  172231. /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
  172232. ** with the configured constraints.
  172233. */
  172234. rc = nodeAcquire(pRtree, 1, 0, &pRoot);
  172235. if( rc==SQLITE_OK && argc>0 ){
  172236. pCsr->aConstraint = sqlite3_malloc64(sizeof(RtreeConstraint)*argc);
  172237. pCsr->nConstraint = argc;
  172238. if( !pCsr->aConstraint ){
  172239. rc = SQLITE_NOMEM;
  172240. }else{
  172241. memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
  172242. memset(pCsr->anQueue, 0, sizeof(u32)*(pRtree->iDepth + 1));
  172243. assert( (idxStr==0 && argc==0)
  172244. || (idxStr && (int)strlen(idxStr)==argc*2) );
  172245. for(ii=0; ii<argc; ii++){
  172246. RtreeConstraint *p = &pCsr->aConstraint[ii];
  172247. p->op = idxStr[ii*2];
  172248. p->iCoord = idxStr[ii*2+1]-'0';
  172249. if( p->op>=RTREE_MATCH ){
  172250. /* A MATCH operator. The right-hand-side must be a blob that
  172251. ** can be cast into an RtreeMatchArg object. One created using
  172252. ** an sqlite3_rtree_geometry_callback() SQL user function.
  172253. */
  172254. rc = deserializeGeometry(argv[ii], p);
  172255. if( rc!=SQLITE_OK ){
  172256. break;
  172257. }
  172258. p->pInfo->nCoord = pRtree->nDim2;
  172259. p->pInfo->anQueue = pCsr->anQueue;
  172260. p->pInfo->mxLevel = pRtree->iDepth + 1;
  172261. }else{
  172262. #ifdef SQLITE_RTREE_INT_ONLY
  172263. p->u.rValue = sqlite3_value_int64(argv[ii]);
  172264. #else
  172265. p->u.rValue = sqlite3_value_double(argv[ii]);
  172266. #endif
  172267. }
  172268. }
  172269. }
  172270. }
  172271. if( rc==SQLITE_OK ){
  172272. RtreeSearchPoint *pNew;
  172273. pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, (u8)(pRtree->iDepth+1));
  172274. if( pNew==0 ) return SQLITE_NOMEM;
  172275. pNew->id = 1;
  172276. pNew->iCell = 0;
  172277. pNew->eWithin = PARTLY_WITHIN;
  172278. assert( pCsr->bPoint==1 );
  172279. pCsr->aNode[0] = pRoot;
  172280. pRoot = 0;
  172281. RTREE_QUEUE_TRACE(pCsr, "PUSH-Fm:");
  172282. rc = rtreeStepToLeaf(pCsr);
  172283. }
  172284. }
  172285. nodeRelease(pRtree, pRoot);
  172286. rtreeRelease(pRtree);
  172287. return rc;
  172288. }
  172289. /*
  172290. ** Rtree virtual table module xBestIndex method. There are three
  172291. ** table scan strategies to choose from (in order from most to
  172292. ** least desirable):
  172293. **
  172294. ** idxNum idxStr Strategy
  172295. ** ------------------------------------------------
  172296. ** 1 Unused Direct lookup by rowid.
  172297. ** 2 See below R-tree query or full-table scan.
  172298. ** ------------------------------------------------
  172299. **
  172300. ** If strategy 1 is used, then idxStr is not meaningful. If strategy
  172301. ** 2 is used, idxStr is formatted to contain 2 bytes for each
  172302. ** constraint used. The first two bytes of idxStr correspond to
  172303. ** the constraint in sqlite3_index_info.aConstraintUsage[] with
  172304. ** (argvIndex==1) etc.
  172305. **
  172306. ** The first of each pair of bytes in idxStr identifies the constraint
  172307. ** operator as follows:
  172308. **
  172309. ** Operator Byte Value
  172310. ** ----------------------
  172311. ** = 0x41 ('A')
  172312. ** <= 0x42 ('B')
  172313. ** < 0x43 ('C')
  172314. ** >= 0x44 ('D')
  172315. ** > 0x45 ('E')
  172316. ** MATCH 0x46 ('F')
  172317. ** ----------------------
  172318. **
  172319. ** The second of each pair of bytes identifies the coordinate column
  172320. ** to which the constraint applies. The leftmost coordinate column
  172321. ** is 'a', the second from the left 'b' etc.
  172322. */
  172323. static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  172324. Rtree *pRtree = (Rtree*)tab;
  172325. int rc = SQLITE_OK;
  172326. int ii;
  172327. int bMatch = 0; /* True if there exists a MATCH constraint */
  172328. i64 nRow; /* Estimated rows returned by this scan */
  172329. int iIdx = 0;
  172330. char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
  172331. memset(zIdxStr, 0, sizeof(zIdxStr));
  172332. /* Check if there exists a MATCH constraint - even an unusable one. If there
  172333. ** is, do not consider the lookup-by-rowid plan as using such a plan would
  172334. ** require the VDBE to evaluate the MATCH constraint, which is not currently
  172335. ** possible. */
  172336. for(ii=0; ii<pIdxInfo->nConstraint; ii++){
  172337. if( pIdxInfo->aConstraint[ii].op==SQLITE_INDEX_CONSTRAINT_MATCH ){
  172338. bMatch = 1;
  172339. }
  172340. }
  172341. assert( pIdxInfo->idxStr==0 );
  172342. for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
  172343. struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
  172344. if( bMatch==0 && p->usable
  172345. && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ
  172346. ){
  172347. /* We have an equality constraint on the rowid. Use strategy 1. */
  172348. int jj;
  172349. for(jj=0; jj<ii; jj++){
  172350. pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
  172351. pIdxInfo->aConstraintUsage[jj].omit = 0;
  172352. }
  172353. pIdxInfo->idxNum = 1;
  172354. pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
  172355. pIdxInfo->aConstraintUsage[jj].omit = 1;
  172356. /* This strategy involves a two rowid lookups on an B-Tree structures
  172357. ** and then a linear search of an R-Tree node. This should be
  172358. ** considered almost as quick as a direct rowid lookup (for which
  172359. ** sqlite uses an internal cost of 0.0). It is expected to return
  172360. ** a single row.
  172361. */
  172362. pIdxInfo->estimatedCost = 30.0;
  172363. pIdxInfo->estimatedRows = 1;
  172364. pIdxInfo->idxFlags = SQLITE_INDEX_SCAN_UNIQUE;
  172365. return SQLITE_OK;
  172366. }
  172367. if( p->usable
  172368. && ((p->iColumn>0 && p->iColumn<=pRtree->nDim2)
  172369. || p->op==SQLITE_INDEX_CONSTRAINT_MATCH)
  172370. ){
  172371. u8 op;
  172372. switch( p->op ){
  172373. case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
  172374. case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
  172375. case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
  172376. case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
  172377. case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
  172378. case SQLITE_INDEX_CONSTRAINT_MATCH: op = RTREE_MATCH; break;
  172379. default: op = 0; break;
  172380. }
  172381. if( op ){
  172382. zIdxStr[iIdx++] = op;
  172383. zIdxStr[iIdx++] = (char)(p->iColumn - 1 + '0');
  172384. pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
  172385. pIdxInfo->aConstraintUsage[ii].omit = 1;
  172386. }
  172387. }
  172388. }
  172389. pIdxInfo->idxNum = 2;
  172390. pIdxInfo->needToFreeIdxStr = 1;
  172391. if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
  172392. return SQLITE_NOMEM;
  172393. }
  172394. nRow = pRtree->nRowEst >> (iIdx/2);
  172395. pIdxInfo->estimatedCost = (double)6.0 * (double)nRow;
  172396. pIdxInfo->estimatedRows = nRow;
  172397. return rc;
  172398. }
  172399. /*
  172400. ** Return the N-dimensional volumn of the cell stored in *p.
  172401. */
  172402. static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
  172403. RtreeDValue area = (RtreeDValue)1;
  172404. assert( pRtree->nDim>=1 && pRtree->nDim<=5 );
  172405. #ifndef SQLITE_RTREE_INT_ONLY
  172406. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  172407. switch( pRtree->nDim ){
  172408. case 5: area = p->aCoord[9].f - p->aCoord[8].f;
  172409. case 4: area *= p->aCoord[7].f - p->aCoord[6].f;
  172410. case 3: area *= p->aCoord[5].f - p->aCoord[4].f;
  172411. case 2: area *= p->aCoord[3].f - p->aCoord[2].f;
  172412. default: area *= p->aCoord[1].f - p->aCoord[0].f;
  172413. }
  172414. }else
  172415. #endif
  172416. {
  172417. switch( pRtree->nDim ){
  172418. case 5: area = (i64)p->aCoord[9].i - (i64)p->aCoord[8].i;
  172419. case 4: area *= (i64)p->aCoord[7].i - (i64)p->aCoord[6].i;
  172420. case 3: area *= (i64)p->aCoord[5].i - (i64)p->aCoord[4].i;
  172421. case 2: area *= (i64)p->aCoord[3].i - (i64)p->aCoord[2].i;
  172422. default: area *= (i64)p->aCoord[1].i - (i64)p->aCoord[0].i;
  172423. }
  172424. }
  172425. return area;
  172426. }
  172427. /*
  172428. ** Return the margin length of cell p. The margin length is the sum
  172429. ** of the objects size in each dimension.
  172430. */
  172431. static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
  172432. RtreeDValue margin = 0;
  172433. int ii = pRtree->nDim2 - 2;
  172434. do{
  172435. margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
  172436. ii -= 2;
  172437. }while( ii>=0 );
  172438. return margin;
  172439. }
  172440. /*
  172441. ** Store the union of cells p1 and p2 in p1.
  172442. */
  172443. static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
  172444. int ii = 0;
  172445. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  172446. do{
  172447. p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
  172448. p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
  172449. ii += 2;
  172450. }while( ii<pRtree->nDim2 );
  172451. }else{
  172452. do{
  172453. p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
  172454. p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
  172455. ii += 2;
  172456. }while( ii<pRtree->nDim2 );
  172457. }
  172458. }
  172459. /*
  172460. ** Return true if the area covered by p2 is a subset of the area covered
  172461. ** by p1. False otherwise.
  172462. */
  172463. static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
  172464. int ii;
  172465. int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
  172466. for(ii=0; ii<pRtree->nDim2; ii+=2){
  172467. RtreeCoord *a1 = &p1->aCoord[ii];
  172468. RtreeCoord *a2 = &p2->aCoord[ii];
  172469. if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
  172470. || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
  172471. ){
  172472. return 0;
  172473. }
  172474. }
  172475. return 1;
  172476. }
  172477. /*
  172478. ** Return the amount cell p would grow by if it were unioned with pCell.
  172479. */
  172480. static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
  172481. RtreeDValue area;
  172482. RtreeCell cell;
  172483. memcpy(&cell, p, sizeof(RtreeCell));
  172484. area = cellArea(pRtree, &cell);
  172485. cellUnion(pRtree, &cell, pCell);
  172486. return (cellArea(pRtree, &cell)-area);
  172487. }
  172488. static RtreeDValue cellOverlap(
  172489. Rtree *pRtree,
  172490. RtreeCell *p,
  172491. RtreeCell *aCell,
  172492. int nCell
  172493. ){
  172494. int ii;
  172495. RtreeDValue overlap = RTREE_ZERO;
  172496. for(ii=0; ii<nCell; ii++){
  172497. int jj;
  172498. RtreeDValue o = (RtreeDValue)1;
  172499. for(jj=0; jj<pRtree->nDim2; jj+=2){
  172500. RtreeDValue x1, x2;
  172501. x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
  172502. x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
  172503. if( x2<x1 ){
  172504. o = (RtreeDValue)0;
  172505. break;
  172506. }else{
  172507. o = o * (x2-x1);
  172508. }
  172509. }
  172510. overlap += o;
  172511. }
  172512. return overlap;
  172513. }
  172514. /*
  172515. ** This function implements the ChooseLeaf algorithm from Gutman[84].
  172516. ** ChooseSubTree in r*tree terminology.
  172517. */
  172518. static int ChooseLeaf(
  172519. Rtree *pRtree, /* Rtree table */
  172520. RtreeCell *pCell, /* Cell to insert into rtree */
  172521. int iHeight, /* Height of sub-tree rooted at pCell */
  172522. RtreeNode **ppLeaf /* OUT: Selected leaf page */
  172523. ){
  172524. int rc;
  172525. int ii;
  172526. RtreeNode *pNode = 0;
  172527. rc = nodeAcquire(pRtree, 1, 0, &pNode);
  172528. for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
  172529. int iCell;
  172530. sqlite3_int64 iBest = 0;
  172531. RtreeDValue fMinGrowth = RTREE_ZERO;
  172532. RtreeDValue fMinArea = RTREE_ZERO;
  172533. int nCell = NCELL(pNode);
  172534. RtreeCell cell;
  172535. RtreeNode *pChild;
  172536. RtreeCell *aCell = 0;
  172537. /* Select the child node which will be enlarged the least if pCell
  172538. ** is inserted into it. Resolve ties by choosing the entry with
  172539. ** the smallest area.
  172540. */
  172541. for(iCell=0; iCell<nCell; iCell++){
  172542. int bBest = 0;
  172543. RtreeDValue growth;
  172544. RtreeDValue area;
  172545. nodeGetCell(pRtree, pNode, iCell, &cell);
  172546. growth = cellGrowth(pRtree, &cell, pCell);
  172547. area = cellArea(pRtree, &cell);
  172548. if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
  172549. bBest = 1;
  172550. }
  172551. if( bBest ){
  172552. fMinGrowth = growth;
  172553. fMinArea = area;
  172554. iBest = cell.iRowid;
  172555. }
  172556. }
  172557. sqlite3_free(aCell);
  172558. rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
  172559. nodeRelease(pRtree, pNode);
  172560. pNode = pChild;
  172561. }
  172562. *ppLeaf = pNode;
  172563. return rc;
  172564. }
  172565. /*
  172566. ** A cell with the same content as pCell has just been inserted into
  172567. ** the node pNode. This function updates the bounding box cells in
  172568. ** all ancestor elements.
  172569. */
  172570. static int AdjustTree(
  172571. Rtree *pRtree, /* Rtree table */
  172572. RtreeNode *pNode, /* Adjust ancestry of this node. */
  172573. RtreeCell *pCell /* This cell was just inserted */
  172574. ){
  172575. RtreeNode *p = pNode;
  172576. int cnt = 0;
  172577. while( p->pParent ){
  172578. RtreeNode *pParent = p->pParent;
  172579. RtreeCell cell;
  172580. int iCell;
  172581. if( (++cnt)>1000 || nodeParentIndex(pRtree, p, &iCell) ){
  172582. RTREE_IS_CORRUPT(pRtree);
  172583. return SQLITE_CORRUPT_VTAB;
  172584. }
  172585. nodeGetCell(pRtree, pParent, iCell, &cell);
  172586. if( !cellContains(pRtree, &cell, pCell) ){
  172587. cellUnion(pRtree, &cell, pCell);
  172588. nodeOverwriteCell(pRtree, pParent, &cell, iCell);
  172589. }
  172590. p = pParent;
  172591. }
  172592. return SQLITE_OK;
  172593. }
  172594. /*
  172595. ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
  172596. */
  172597. static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
  172598. sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
  172599. sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
  172600. sqlite3_step(pRtree->pWriteRowid);
  172601. return sqlite3_reset(pRtree->pWriteRowid);
  172602. }
  172603. /*
  172604. ** Write mapping (iNode->iPar) to the <rtree>_parent table.
  172605. */
  172606. static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
  172607. sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
  172608. sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
  172609. sqlite3_step(pRtree->pWriteParent);
  172610. return sqlite3_reset(pRtree->pWriteParent);
  172611. }
  172612. static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
  172613. /*
  172614. ** Arguments aIdx, aDistance and aSpare all point to arrays of size
  172615. ** nIdx. The aIdx array contains the set of integers from 0 to
  172616. ** (nIdx-1) in no particular order. This function sorts the values
  172617. ** in aIdx according to the indexed values in aDistance. For
  172618. ** example, assuming the inputs:
  172619. **
  172620. ** aIdx = { 0, 1, 2, 3 }
  172621. ** aDistance = { 5.0, 2.0, 7.0, 6.0 }
  172622. **
  172623. ** this function sets the aIdx array to contain:
  172624. **
  172625. ** aIdx = { 0, 1, 2, 3 }
  172626. **
  172627. ** The aSpare array is used as temporary working space by the
  172628. ** sorting algorithm.
  172629. */
  172630. static void SortByDistance(
  172631. int *aIdx,
  172632. int nIdx,
  172633. RtreeDValue *aDistance,
  172634. int *aSpare
  172635. ){
  172636. if( nIdx>1 ){
  172637. int iLeft = 0;
  172638. int iRight = 0;
  172639. int nLeft = nIdx/2;
  172640. int nRight = nIdx-nLeft;
  172641. int *aLeft = aIdx;
  172642. int *aRight = &aIdx[nLeft];
  172643. SortByDistance(aLeft, nLeft, aDistance, aSpare);
  172644. SortByDistance(aRight, nRight, aDistance, aSpare);
  172645. memcpy(aSpare, aLeft, sizeof(int)*nLeft);
  172646. aLeft = aSpare;
  172647. while( iLeft<nLeft || iRight<nRight ){
  172648. if( iLeft==nLeft ){
  172649. aIdx[iLeft+iRight] = aRight[iRight];
  172650. iRight++;
  172651. }else if( iRight==nRight ){
  172652. aIdx[iLeft+iRight] = aLeft[iLeft];
  172653. iLeft++;
  172654. }else{
  172655. RtreeDValue fLeft = aDistance[aLeft[iLeft]];
  172656. RtreeDValue fRight = aDistance[aRight[iRight]];
  172657. if( fLeft<fRight ){
  172658. aIdx[iLeft+iRight] = aLeft[iLeft];
  172659. iLeft++;
  172660. }else{
  172661. aIdx[iLeft+iRight] = aRight[iRight];
  172662. iRight++;
  172663. }
  172664. }
  172665. }
  172666. #if 0
  172667. /* Check that the sort worked */
  172668. {
  172669. int jj;
  172670. for(jj=1; jj<nIdx; jj++){
  172671. RtreeDValue left = aDistance[aIdx[jj-1]];
  172672. RtreeDValue right = aDistance[aIdx[jj]];
  172673. assert( left<=right );
  172674. }
  172675. }
  172676. #endif
  172677. }
  172678. }
  172679. /*
  172680. ** Arguments aIdx, aCell and aSpare all point to arrays of size
  172681. ** nIdx. The aIdx array contains the set of integers from 0 to
  172682. ** (nIdx-1) in no particular order. This function sorts the values
  172683. ** in aIdx according to dimension iDim of the cells in aCell. The
  172684. ** minimum value of dimension iDim is considered first, the
  172685. ** maximum used to break ties.
  172686. **
  172687. ** The aSpare array is used as temporary working space by the
  172688. ** sorting algorithm.
  172689. */
  172690. static void SortByDimension(
  172691. Rtree *pRtree,
  172692. int *aIdx,
  172693. int nIdx,
  172694. int iDim,
  172695. RtreeCell *aCell,
  172696. int *aSpare
  172697. ){
  172698. if( nIdx>1 ){
  172699. int iLeft = 0;
  172700. int iRight = 0;
  172701. int nLeft = nIdx/2;
  172702. int nRight = nIdx-nLeft;
  172703. int *aLeft = aIdx;
  172704. int *aRight = &aIdx[nLeft];
  172705. SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
  172706. SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
  172707. memcpy(aSpare, aLeft, sizeof(int)*nLeft);
  172708. aLeft = aSpare;
  172709. while( iLeft<nLeft || iRight<nRight ){
  172710. RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
  172711. RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
  172712. RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
  172713. RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
  172714. if( (iLeft!=nLeft) && ((iRight==nRight)
  172715. || (xleft1<xright1)
  172716. || (xleft1==xright1 && xleft2<xright2)
  172717. )){
  172718. aIdx[iLeft+iRight] = aLeft[iLeft];
  172719. iLeft++;
  172720. }else{
  172721. aIdx[iLeft+iRight] = aRight[iRight];
  172722. iRight++;
  172723. }
  172724. }
  172725. #if 0
  172726. /* Check that the sort worked */
  172727. {
  172728. int jj;
  172729. for(jj=1; jj<nIdx; jj++){
  172730. RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
  172731. RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
  172732. RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
  172733. RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
  172734. assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
  172735. }
  172736. }
  172737. #endif
  172738. }
  172739. }
  172740. /*
  172741. ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
  172742. */
  172743. static int splitNodeStartree(
  172744. Rtree *pRtree,
  172745. RtreeCell *aCell,
  172746. int nCell,
  172747. RtreeNode *pLeft,
  172748. RtreeNode *pRight,
  172749. RtreeCell *pBboxLeft,
  172750. RtreeCell *pBboxRight
  172751. ){
  172752. int **aaSorted;
  172753. int *aSpare;
  172754. int ii;
  172755. int iBestDim = 0;
  172756. int iBestSplit = 0;
  172757. RtreeDValue fBestMargin = RTREE_ZERO;
  172758. sqlite3_int64 nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
  172759. aaSorted = (int **)sqlite3_malloc64(nByte);
  172760. if( !aaSorted ){
  172761. return SQLITE_NOMEM;
  172762. }
  172763. aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
  172764. memset(aaSorted, 0, nByte);
  172765. for(ii=0; ii<pRtree->nDim; ii++){
  172766. int jj;
  172767. aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
  172768. for(jj=0; jj<nCell; jj++){
  172769. aaSorted[ii][jj] = jj;
  172770. }
  172771. SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
  172772. }
  172773. for(ii=0; ii<pRtree->nDim; ii++){
  172774. RtreeDValue margin = RTREE_ZERO;
  172775. RtreeDValue fBestOverlap = RTREE_ZERO;
  172776. RtreeDValue fBestArea = RTREE_ZERO;
  172777. int iBestLeft = 0;
  172778. int nLeft;
  172779. for(
  172780. nLeft=RTREE_MINCELLS(pRtree);
  172781. nLeft<=(nCell-RTREE_MINCELLS(pRtree));
  172782. nLeft++
  172783. ){
  172784. RtreeCell left;
  172785. RtreeCell right;
  172786. int kk;
  172787. RtreeDValue overlap;
  172788. RtreeDValue area;
  172789. memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
  172790. memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
  172791. for(kk=1; kk<(nCell-1); kk++){
  172792. if( kk<nLeft ){
  172793. cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
  172794. }else{
  172795. cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
  172796. }
  172797. }
  172798. margin += cellMargin(pRtree, &left);
  172799. margin += cellMargin(pRtree, &right);
  172800. overlap = cellOverlap(pRtree, &left, &right, 1);
  172801. area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
  172802. if( (nLeft==RTREE_MINCELLS(pRtree))
  172803. || (overlap<fBestOverlap)
  172804. || (overlap==fBestOverlap && area<fBestArea)
  172805. ){
  172806. iBestLeft = nLeft;
  172807. fBestOverlap = overlap;
  172808. fBestArea = area;
  172809. }
  172810. }
  172811. if( ii==0 || margin<fBestMargin ){
  172812. iBestDim = ii;
  172813. fBestMargin = margin;
  172814. iBestSplit = iBestLeft;
  172815. }
  172816. }
  172817. memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
  172818. memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
  172819. for(ii=0; ii<nCell; ii++){
  172820. RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
  172821. RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
  172822. RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
  172823. nodeInsertCell(pRtree, pTarget, pCell);
  172824. cellUnion(pRtree, pBbox, pCell);
  172825. }
  172826. sqlite3_free(aaSorted);
  172827. return SQLITE_OK;
  172828. }
  172829. static int updateMapping(
  172830. Rtree *pRtree,
  172831. i64 iRowid,
  172832. RtreeNode *pNode,
  172833. int iHeight
  172834. ){
  172835. int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
  172836. xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
  172837. if( iHeight>0 ){
  172838. RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
  172839. if( pChild ){
  172840. nodeRelease(pRtree, pChild->pParent);
  172841. nodeReference(pNode);
  172842. pChild->pParent = pNode;
  172843. }
  172844. }
  172845. return xSetMapping(pRtree, iRowid, pNode->iNode);
  172846. }
  172847. static int SplitNode(
  172848. Rtree *pRtree,
  172849. RtreeNode *pNode,
  172850. RtreeCell *pCell,
  172851. int iHeight
  172852. ){
  172853. int i;
  172854. int newCellIsRight = 0;
  172855. int rc = SQLITE_OK;
  172856. int nCell = NCELL(pNode);
  172857. RtreeCell *aCell;
  172858. int *aiUsed;
  172859. RtreeNode *pLeft = 0;
  172860. RtreeNode *pRight = 0;
  172861. RtreeCell leftbbox;
  172862. RtreeCell rightbbox;
  172863. /* Allocate an array and populate it with a copy of pCell and
  172864. ** all cells from node pLeft. Then zero the original node.
  172865. */
  172866. aCell = sqlite3_malloc64((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
  172867. if( !aCell ){
  172868. rc = SQLITE_NOMEM;
  172869. goto splitnode_out;
  172870. }
  172871. aiUsed = (int *)&aCell[nCell+1];
  172872. memset(aiUsed, 0, sizeof(int)*(nCell+1));
  172873. for(i=0; i<nCell; i++){
  172874. nodeGetCell(pRtree, pNode, i, &aCell[i]);
  172875. }
  172876. nodeZero(pRtree, pNode);
  172877. memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
  172878. nCell++;
  172879. if( pNode->iNode==1 ){
  172880. pRight = nodeNew(pRtree, pNode);
  172881. pLeft = nodeNew(pRtree, pNode);
  172882. pRtree->iDepth++;
  172883. pNode->isDirty = 1;
  172884. writeInt16(pNode->zData, pRtree->iDepth);
  172885. }else{
  172886. pLeft = pNode;
  172887. pRight = nodeNew(pRtree, pLeft->pParent);
  172888. pLeft->nRef++;
  172889. }
  172890. if( !pLeft || !pRight ){
  172891. rc = SQLITE_NOMEM;
  172892. goto splitnode_out;
  172893. }
  172894. memset(pLeft->zData, 0, pRtree->iNodeSize);
  172895. memset(pRight->zData, 0, pRtree->iNodeSize);
  172896. rc = splitNodeStartree(pRtree, aCell, nCell, pLeft, pRight,
  172897. &leftbbox, &rightbbox);
  172898. if( rc!=SQLITE_OK ){
  172899. goto splitnode_out;
  172900. }
  172901. /* Ensure both child nodes have node numbers assigned to them by calling
  172902. ** nodeWrite(). Node pRight always needs a node number, as it was created
  172903. ** by nodeNew() above. But node pLeft sometimes already has a node number.
  172904. ** In this case avoid the all to nodeWrite().
  172905. */
  172906. if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
  172907. || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
  172908. ){
  172909. goto splitnode_out;
  172910. }
  172911. rightbbox.iRowid = pRight->iNode;
  172912. leftbbox.iRowid = pLeft->iNode;
  172913. if( pNode->iNode==1 ){
  172914. rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
  172915. if( rc!=SQLITE_OK ){
  172916. goto splitnode_out;
  172917. }
  172918. }else{
  172919. RtreeNode *pParent = pLeft->pParent;
  172920. int iCell;
  172921. rc = nodeParentIndex(pRtree, pLeft, &iCell);
  172922. if( rc==SQLITE_OK ){
  172923. nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
  172924. rc = AdjustTree(pRtree, pParent, &leftbbox);
  172925. }
  172926. if( rc!=SQLITE_OK ){
  172927. goto splitnode_out;
  172928. }
  172929. }
  172930. if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
  172931. goto splitnode_out;
  172932. }
  172933. for(i=0; i<NCELL(pRight); i++){
  172934. i64 iRowid = nodeGetRowid(pRtree, pRight, i);
  172935. rc = updateMapping(pRtree, iRowid, pRight, iHeight);
  172936. if( iRowid==pCell->iRowid ){
  172937. newCellIsRight = 1;
  172938. }
  172939. if( rc!=SQLITE_OK ){
  172940. goto splitnode_out;
  172941. }
  172942. }
  172943. if( pNode->iNode==1 ){
  172944. for(i=0; i<NCELL(pLeft); i++){
  172945. i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
  172946. rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
  172947. if( rc!=SQLITE_OK ){
  172948. goto splitnode_out;
  172949. }
  172950. }
  172951. }else if( newCellIsRight==0 ){
  172952. rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
  172953. }
  172954. if( rc==SQLITE_OK ){
  172955. rc = nodeRelease(pRtree, pRight);
  172956. pRight = 0;
  172957. }
  172958. if( rc==SQLITE_OK ){
  172959. rc = nodeRelease(pRtree, pLeft);
  172960. pLeft = 0;
  172961. }
  172962. splitnode_out:
  172963. nodeRelease(pRtree, pRight);
  172964. nodeRelease(pRtree, pLeft);
  172965. sqlite3_free(aCell);
  172966. return rc;
  172967. }
  172968. /*
  172969. ** If node pLeaf is not the root of the r-tree and its pParent pointer is
  172970. ** still NULL, load all ancestor nodes of pLeaf into memory and populate
  172971. ** the pLeaf->pParent chain all the way up to the root node.
  172972. **
  172973. ** This operation is required when a row is deleted (or updated - an update
  172974. ** is implemented as a delete followed by an insert). SQLite provides the
  172975. ** rowid of the row to delete, which can be used to find the leaf on which
  172976. ** the entry resides (argument pLeaf). Once the leaf is located, this
  172977. ** function is called to determine its ancestry.
  172978. */
  172979. static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
  172980. int rc = SQLITE_OK;
  172981. RtreeNode *pChild = pLeaf;
  172982. while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
  172983. int rc2 = SQLITE_OK; /* sqlite3_reset() return code */
  172984. sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
  172985. rc = sqlite3_step(pRtree->pReadParent);
  172986. if( rc==SQLITE_ROW ){
  172987. RtreeNode *pTest; /* Used to test for reference loops */
  172988. i64 iNode; /* Node number of parent node */
  172989. /* Before setting pChild->pParent, test that we are not creating a
  172990. ** loop of references (as we would if, say, pChild==pParent). We don't
  172991. ** want to do this as it leads to a memory leak when trying to delete
  172992. ** the referenced counted node structures.
  172993. */
  172994. iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
  172995. for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
  172996. if( !pTest ){
  172997. rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
  172998. }
  172999. }
  173000. rc = sqlite3_reset(pRtree->pReadParent);
  173001. if( rc==SQLITE_OK ) rc = rc2;
  173002. if( rc==SQLITE_OK && !pChild->pParent ){
  173003. RTREE_IS_CORRUPT(pRtree);
  173004. rc = SQLITE_CORRUPT_VTAB;
  173005. }
  173006. pChild = pChild->pParent;
  173007. }
  173008. return rc;
  173009. }
  173010. static int deleteCell(Rtree *, RtreeNode *, int, int);
  173011. static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
  173012. int rc;
  173013. int rc2;
  173014. RtreeNode *pParent = 0;
  173015. int iCell;
  173016. assert( pNode->nRef==1 );
  173017. /* Remove the entry in the parent cell. */
  173018. rc = nodeParentIndex(pRtree, pNode, &iCell);
  173019. if( rc==SQLITE_OK ){
  173020. pParent = pNode->pParent;
  173021. pNode->pParent = 0;
  173022. rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
  173023. }
  173024. rc2 = nodeRelease(pRtree, pParent);
  173025. if( rc==SQLITE_OK ){
  173026. rc = rc2;
  173027. }
  173028. if( rc!=SQLITE_OK ){
  173029. return rc;
  173030. }
  173031. /* Remove the xxx_node entry. */
  173032. sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
  173033. sqlite3_step(pRtree->pDeleteNode);
  173034. if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
  173035. return rc;
  173036. }
  173037. /* Remove the xxx_parent entry. */
  173038. sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
  173039. sqlite3_step(pRtree->pDeleteParent);
  173040. if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
  173041. return rc;
  173042. }
  173043. /* Remove the node from the in-memory hash table and link it into
  173044. ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
  173045. */
  173046. nodeHashDelete(pRtree, pNode);
  173047. pNode->iNode = iHeight;
  173048. pNode->pNext = pRtree->pDeleted;
  173049. pNode->nRef++;
  173050. pRtree->pDeleted = pNode;
  173051. return SQLITE_OK;
  173052. }
  173053. static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
  173054. RtreeNode *pParent = pNode->pParent;
  173055. int rc = SQLITE_OK;
  173056. if( pParent ){
  173057. int ii;
  173058. int nCell = NCELL(pNode);
  173059. RtreeCell box; /* Bounding box for pNode */
  173060. nodeGetCell(pRtree, pNode, 0, &box);
  173061. for(ii=1; ii<nCell; ii++){
  173062. RtreeCell cell;
  173063. nodeGetCell(pRtree, pNode, ii, &cell);
  173064. cellUnion(pRtree, &box, &cell);
  173065. }
  173066. box.iRowid = pNode->iNode;
  173067. rc = nodeParentIndex(pRtree, pNode, &ii);
  173068. if( rc==SQLITE_OK ){
  173069. nodeOverwriteCell(pRtree, pParent, &box, ii);
  173070. rc = fixBoundingBox(pRtree, pParent);
  173071. }
  173072. }
  173073. return rc;
  173074. }
  173075. /*
  173076. ** Delete the cell at index iCell of node pNode. After removing the
  173077. ** cell, adjust the r-tree data structure if required.
  173078. */
  173079. static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
  173080. RtreeNode *pParent;
  173081. int rc;
  173082. if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
  173083. return rc;
  173084. }
  173085. /* Remove the cell from the node. This call just moves bytes around
  173086. ** the in-memory node image, so it cannot fail.
  173087. */
  173088. nodeDeleteCell(pRtree, pNode, iCell);
  173089. /* If the node is not the tree root and now has less than the minimum
  173090. ** number of cells, remove it from the tree. Otherwise, update the
  173091. ** cell in the parent node so that it tightly contains the updated
  173092. ** node.
  173093. */
  173094. pParent = pNode->pParent;
  173095. assert( pParent || pNode->iNode==1 );
  173096. if( pParent ){
  173097. if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
  173098. rc = removeNode(pRtree, pNode, iHeight);
  173099. }else{
  173100. rc = fixBoundingBox(pRtree, pNode);
  173101. }
  173102. }
  173103. return rc;
  173104. }
  173105. static int Reinsert(
  173106. Rtree *pRtree,
  173107. RtreeNode *pNode,
  173108. RtreeCell *pCell,
  173109. int iHeight
  173110. ){
  173111. int *aOrder;
  173112. int *aSpare;
  173113. RtreeCell *aCell;
  173114. RtreeDValue *aDistance;
  173115. int nCell;
  173116. RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
  173117. int iDim;
  173118. int ii;
  173119. int rc = SQLITE_OK;
  173120. int n;
  173121. memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
  173122. nCell = NCELL(pNode)+1;
  173123. n = (nCell+1)&(~1);
  173124. /* Allocate the buffers used by this operation. The allocation is
  173125. ** relinquished before this function returns.
  173126. */
  173127. aCell = (RtreeCell *)sqlite3_malloc64(n * (
  173128. sizeof(RtreeCell) + /* aCell array */
  173129. sizeof(int) + /* aOrder array */
  173130. sizeof(int) + /* aSpare array */
  173131. sizeof(RtreeDValue) /* aDistance array */
  173132. ));
  173133. if( !aCell ){
  173134. return SQLITE_NOMEM;
  173135. }
  173136. aOrder = (int *)&aCell[n];
  173137. aSpare = (int *)&aOrder[n];
  173138. aDistance = (RtreeDValue *)&aSpare[n];
  173139. for(ii=0; ii<nCell; ii++){
  173140. if( ii==(nCell-1) ){
  173141. memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
  173142. }else{
  173143. nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
  173144. }
  173145. aOrder[ii] = ii;
  173146. for(iDim=0; iDim<pRtree->nDim; iDim++){
  173147. aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
  173148. aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
  173149. }
  173150. }
  173151. for(iDim=0; iDim<pRtree->nDim; iDim++){
  173152. aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
  173153. }
  173154. for(ii=0; ii<nCell; ii++){
  173155. aDistance[ii] = RTREE_ZERO;
  173156. for(iDim=0; iDim<pRtree->nDim; iDim++){
  173157. RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) -
  173158. DCOORD(aCell[ii].aCoord[iDim*2]));
  173159. aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
  173160. }
  173161. }
  173162. SortByDistance(aOrder, nCell, aDistance, aSpare);
  173163. nodeZero(pRtree, pNode);
  173164. for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
  173165. RtreeCell *p = &aCell[aOrder[ii]];
  173166. nodeInsertCell(pRtree, pNode, p);
  173167. if( p->iRowid==pCell->iRowid ){
  173168. if( iHeight==0 ){
  173169. rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
  173170. }else{
  173171. rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
  173172. }
  173173. }
  173174. }
  173175. if( rc==SQLITE_OK ){
  173176. rc = fixBoundingBox(pRtree, pNode);
  173177. }
  173178. for(; rc==SQLITE_OK && ii<nCell; ii++){
  173179. /* Find a node to store this cell in. pNode->iNode currently contains
  173180. ** the height of the sub-tree headed by the cell.
  173181. */
  173182. RtreeNode *pInsert;
  173183. RtreeCell *p = &aCell[aOrder[ii]];
  173184. rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
  173185. if( rc==SQLITE_OK ){
  173186. int rc2;
  173187. rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
  173188. rc2 = nodeRelease(pRtree, pInsert);
  173189. if( rc==SQLITE_OK ){
  173190. rc = rc2;
  173191. }
  173192. }
  173193. }
  173194. sqlite3_free(aCell);
  173195. return rc;
  173196. }
  173197. /*
  173198. ** Insert cell pCell into node pNode. Node pNode is the head of a
  173199. ** subtree iHeight high (leaf nodes have iHeight==0).
  173200. */
  173201. static int rtreeInsertCell(
  173202. Rtree *pRtree,
  173203. RtreeNode *pNode,
  173204. RtreeCell *pCell,
  173205. int iHeight
  173206. ){
  173207. int rc = SQLITE_OK;
  173208. if( iHeight>0 ){
  173209. RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
  173210. if( pChild ){
  173211. nodeRelease(pRtree, pChild->pParent);
  173212. nodeReference(pNode);
  173213. pChild->pParent = pNode;
  173214. }
  173215. }
  173216. if( nodeInsertCell(pRtree, pNode, pCell) ){
  173217. if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
  173218. rc = SplitNode(pRtree, pNode, pCell, iHeight);
  173219. }else{
  173220. pRtree->iReinsertHeight = iHeight;
  173221. rc = Reinsert(pRtree, pNode, pCell, iHeight);
  173222. }
  173223. }else{
  173224. rc = AdjustTree(pRtree, pNode, pCell);
  173225. if( rc==SQLITE_OK ){
  173226. if( iHeight==0 ){
  173227. rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
  173228. }else{
  173229. rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
  173230. }
  173231. }
  173232. }
  173233. return rc;
  173234. }
  173235. static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
  173236. int ii;
  173237. int rc = SQLITE_OK;
  173238. int nCell = NCELL(pNode);
  173239. for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
  173240. RtreeNode *pInsert;
  173241. RtreeCell cell;
  173242. nodeGetCell(pRtree, pNode, ii, &cell);
  173243. /* Find a node to store this cell in. pNode->iNode currently contains
  173244. ** the height of the sub-tree headed by the cell.
  173245. */
  173246. rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
  173247. if( rc==SQLITE_OK ){
  173248. int rc2;
  173249. rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
  173250. rc2 = nodeRelease(pRtree, pInsert);
  173251. if( rc==SQLITE_OK ){
  173252. rc = rc2;
  173253. }
  173254. }
  173255. }
  173256. return rc;
  173257. }
  173258. /*
  173259. ** Select a currently unused rowid for a new r-tree record.
  173260. */
  173261. static int rtreeNewRowid(Rtree *pRtree, i64 *piRowid){
  173262. int rc;
  173263. sqlite3_bind_null(pRtree->pWriteRowid, 1);
  173264. sqlite3_bind_null(pRtree->pWriteRowid, 2);
  173265. sqlite3_step(pRtree->pWriteRowid);
  173266. rc = sqlite3_reset(pRtree->pWriteRowid);
  173267. *piRowid = sqlite3_last_insert_rowid(pRtree->db);
  173268. return rc;
  173269. }
  173270. /*
  173271. ** Remove the entry with rowid=iDelete from the r-tree structure.
  173272. */
  173273. static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
  173274. int rc; /* Return code */
  173275. RtreeNode *pLeaf = 0; /* Leaf node containing record iDelete */
  173276. int iCell; /* Index of iDelete cell in pLeaf */
  173277. RtreeNode *pRoot = 0; /* Root node of rtree structure */
  173278. /* Obtain a reference to the root node to initialize Rtree.iDepth */
  173279. rc = nodeAcquire(pRtree, 1, 0, &pRoot);
  173280. /* Obtain a reference to the leaf node that contains the entry
  173281. ** about to be deleted.
  173282. */
  173283. if( rc==SQLITE_OK ){
  173284. rc = findLeafNode(pRtree, iDelete, &pLeaf, 0);
  173285. }
  173286. #ifdef CORRUPT_DB
  173287. assert( pLeaf!=0 || rc!=SQLITE_OK || CORRUPT_DB );
  173288. #endif
  173289. /* Delete the cell in question from the leaf node. */
  173290. if( rc==SQLITE_OK && pLeaf ){
  173291. int rc2;
  173292. rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
  173293. if( rc==SQLITE_OK ){
  173294. rc = deleteCell(pRtree, pLeaf, iCell, 0);
  173295. }
  173296. rc2 = nodeRelease(pRtree, pLeaf);
  173297. if( rc==SQLITE_OK ){
  173298. rc = rc2;
  173299. }
  173300. }
  173301. /* Delete the corresponding entry in the <rtree>_rowid table. */
  173302. if( rc==SQLITE_OK ){
  173303. sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
  173304. sqlite3_step(pRtree->pDeleteRowid);
  173305. rc = sqlite3_reset(pRtree->pDeleteRowid);
  173306. }
  173307. /* Check if the root node now has exactly one child. If so, remove
  173308. ** it, schedule the contents of the child for reinsertion and
  173309. ** reduce the tree height by one.
  173310. **
  173311. ** This is equivalent to copying the contents of the child into
  173312. ** the root node (the operation that Gutman's paper says to perform
  173313. ** in this scenario).
  173314. */
  173315. if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
  173316. int rc2;
  173317. RtreeNode *pChild = 0;
  173318. i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
  173319. rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
  173320. if( rc==SQLITE_OK ){
  173321. rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
  173322. }
  173323. rc2 = nodeRelease(pRtree, pChild);
  173324. if( rc==SQLITE_OK ) rc = rc2;
  173325. if( rc==SQLITE_OK ){
  173326. pRtree->iDepth--;
  173327. writeInt16(pRoot->zData, pRtree->iDepth);
  173328. pRoot->isDirty = 1;
  173329. }
  173330. }
  173331. /* Re-insert the contents of any underfull nodes removed from the tree. */
  173332. for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
  173333. if( rc==SQLITE_OK ){
  173334. rc = reinsertNodeContent(pRtree, pLeaf);
  173335. }
  173336. pRtree->pDeleted = pLeaf->pNext;
  173337. pRtree->nNodeRef--;
  173338. sqlite3_free(pLeaf);
  173339. }
  173340. /* Release the reference to the root node. */
  173341. if( rc==SQLITE_OK ){
  173342. rc = nodeRelease(pRtree, pRoot);
  173343. }else{
  173344. nodeRelease(pRtree, pRoot);
  173345. }
  173346. return rc;
  173347. }
  173348. /*
  173349. ** Rounding constants for float->double conversion.
  173350. */
  173351. #define RNDTOWARDS (1.0 - 1.0/8388608.0) /* Round towards zero */
  173352. #define RNDAWAY (1.0 + 1.0/8388608.0) /* Round away from zero */
  173353. #if !defined(SQLITE_RTREE_INT_ONLY)
  173354. /*
  173355. ** Convert an sqlite3_value into an RtreeValue (presumably a float)
  173356. ** while taking care to round toward negative or positive, respectively.
  173357. */
  173358. static RtreeValue rtreeValueDown(sqlite3_value *v){
  173359. double d = sqlite3_value_double(v);
  173360. float f = (float)d;
  173361. if( f>d ){
  173362. f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
  173363. }
  173364. return f;
  173365. }
  173366. static RtreeValue rtreeValueUp(sqlite3_value *v){
  173367. double d = sqlite3_value_double(v);
  173368. float f = (float)d;
  173369. if( f<d ){
  173370. f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
  173371. }
  173372. return f;
  173373. }
  173374. #endif /* !defined(SQLITE_RTREE_INT_ONLY) */
  173375. /*
  173376. ** A constraint has failed while inserting a row into an rtree table.
  173377. ** Assuming no OOM error occurs, this function sets the error message
  173378. ** (at pRtree->base.zErrMsg) to an appropriate value and returns
  173379. ** SQLITE_CONSTRAINT.
  173380. **
  173381. ** Parameter iCol is the index of the leftmost column involved in the
  173382. ** constraint failure. If it is 0, then the constraint that failed is
  173383. ** the unique constraint on the id column. Otherwise, it is the rtree
  173384. ** (c1<=c2) constraint on columns iCol and iCol+1 that has failed.
  173385. **
  173386. ** If an OOM occurs, SQLITE_NOMEM is returned instead of SQLITE_CONSTRAINT.
  173387. */
  173388. static int rtreeConstraintError(Rtree *pRtree, int iCol){
  173389. sqlite3_stmt *pStmt = 0;
  173390. char *zSql;
  173391. int rc;
  173392. assert( iCol==0 || iCol%2 );
  173393. zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", pRtree->zDb, pRtree->zName);
  173394. if( zSql ){
  173395. rc = sqlite3_prepare_v2(pRtree->db, zSql, -1, &pStmt, 0);
  173396. }else{
  173397. rc = SQLITE_NOMEM;
  173398. }
  173399. sqlite3_free(zSql);
  173400. if( rc==SQLITE_OK ){
  173401. if( iCol==0 ){
  173402. const char *zCol = sqlite3_column_name(pStmt, 0);
  173403. pRtree->base.zErrMsg = sqlite3_mprintf(
  173404. "UNIQUE constraint failed: %s.%s", pRtree->zName, zCol
  173405. );
  173406. }else{
  173407. const char *zCol1 = sqlite3_column_name(pStmt, iCol);
  173408. const char *zCol2 = sqlite3_column_name(pStmt, iCol+1);
  173409. pRtree->base.zErrMsg = sqlite3_mprintf(
  173410. "rtree constraint failed: %s.(%s<=%s)", pRtree->zName, zCol1, zCol2
  173411. );
  173412. }
  173413. }
  173414. sqlite3_finalize(pStmt);
  173415. return (rc==SQLITE_OK ? SQLITE_CONSTRAINT : rc);
  173416. }
  173417. /*
  173418. ** The xUpdate method for rtree module virtual tables.
  173419. */
  173420. static int rtreeUpdate(
  173421. sqlite3_vtab *pVtab,
  173422. int nData,
  173423. sqlite3_value **aData,
  173424. sqlite_int64 *pRowid
  173425. ){
  173426. Rtree *pRtree = (Rtree *)pVtab;
  173427. int rc = SQLITE_OK;
  173428. RtreeCell cell; /* New cell to insert if nData>1 */
  173429. int bHaveRowid = 0; /* Set to 1 after new rowid is determined */
  173430. if( pRtree->nNodeRef ){
  173431. /* Unable to write to the btree while another cursor is reading from it,
  173432. ** since the write might do a rebalance which would disrupt the read
  173433. ** cursor. */
  173434. return SQLITE_LOCKED_VTAB;
  173435. }
  173436. rtreeReference(pRtree);
  173437. assert(nData>=1);
  173438. cell.iRowid = 0; /* Used only to suppress a compiler warning */
  173439. /* Constraint handling. A write operation on an r-tree table may return
  173440. ** SQLITE_CONSTRAINT for two reasons:
  173441. **
  173442. ** 1. A duplicate rowid value, or
  173443. ** 2. The supplied data violates the "x2>=x1" constraint.
  173444. **
  173445. ** In the first case, if the conflict-handling mode is REPLACE, then
  173446. ** the conflicting row can be removed before proceeding. In the second
  173447. ** case, SQLITE_CONSTRAINT must be returned regardless of the
  173448. ** conflict-handling mode specified by the user.
  173449. */
  173450. if( nData>1 ){
  173451. int ii;
  173452. int nn = nData - 4;
  173453. if( nn > pRtree->nDim2 ) nn = pRtree->nDim2;
  173454. /* Populate the cell.aCoord[] array. The first coordinate is aData[3].
  173455. **
  173456. ** NB: nData can only be less than nDim*2+3 if the rtree is mis-declared
  173457. ** with "column" that are interpreted as table constraints.
  173458. ** Example: CREATE VIRTUAL TABLE bad USING rtree(x,y,CHECK(y>5));
  173459. ** This problem was discovered after years of use, so we silently ignore
  173460. ** these kinds of misdeclared tables to avoid breaking any legacy.
  173461. */
  173462. #ifndef SQLITE_RTREE_INT_ONLY
  173463. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  173464. for(ii=0; ii<nn; ii+=2){
  173465. cell.aCoord[ii].f = rtreeValueDown(aData[ii+3]);
  173466. cell.aCoord[ii+1].f = rtreeValueUp(aData[ii+4]);
  173467. if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
  173468. rc = rtreeConstraintError(pRtree, ii+1);
  173469. goto constraint;
  173470. }
  173471. }
  173472. }else
  173473. #endif
  173474. {
  173475. for(ii=0; ii<nn; ii+=2){
  173476. cell.aCoord[ii].i = sqlite3_value_int(aData[ii+3]);
  173477. cell.aCoord[ii+1].i = sqlite3_value_int(aData[ii+4]);
  173478. if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
  173479. rc = rtreeConstraintError(pRtree, ii+1);
  173480. goto constraint;
  173481. }
  173482. }
  173483. }
  173484. /* If a rowid value was supplied, check if it is already present in
  173485. ** the table. If so, the constraint has failed. */
  173486. if( sqlite3_value_type(aData[2])!=SQLITE_NULL ){
  173487. cell.iRowid = sqlite3_value_int64(aData[2]);
  173488. if( sqlite3_value_type(aData[0])==SQLITE_NULL
  173489. || sqlite3_value_int64(aData[0])!=cell.iRowid
  173490. ){
  173491. int steprc;
  173492. sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
  173493. steprc = sqlite3_step(pRtree->pReadRowid);
  173494. rc = sqlite3_reset(pRtree->pReadRowid);
  173495. if( SQLITE_ROW==steprc ){
  173496. if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
  173497. rc = rtreeDeleteRowid(pRtree, cell.iRowid);
  173498. }else{
  173499. rc = rtreeConstraintError(pRtree, 0);
  173500. goto constraint;
  173501. }
  173502. }
  173503. }
  173504. bHaveRowid = 1;
  173505. }
  173506. }
  173507. /* If aData[0] is not an SQL NULL value, it is the rowid of a
  173508. ** record to delete from the r-tree table. The following block does
  173509. ** just that.
  173510. */
  173511. if( sqlite3_value_type(aData[0])!=SQLITE_NULL ){
  173512. rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(aData[0]));
  173513. }
  173514. /* If the aData[] array contains more than one element, elements
  173515. ** (aData[2]..aData[argc-1]) contain a new record to insert into
  173516. ** the r-tree structure.
  173517. */
  173518. if( rc==SQLITE_OK && nData>1 ){
  173519. /* Insert the new record into the r-tree */
  173520. RtreeNode *pLeaf = 0;
  173521. /* Figure out the rowid of the new row. */
  173522. if( bHaveRowid==0 ){
  173523. rc = rtreeNewRowid(pRtree, &cell.iRowid);
  173524. }
  173525. *pRowid = cell.iRowid;
  173526. if( rc==SQLITE_OK ){
  173527. rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
  173528. }
  173529. if( rc==SQLITE_OK ){
  173530. int rc2;
  173531. pRtree->iReinsertHeight = -1;
  173532. rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
  173533. rc2 = nodeRelease(pRtree, pLeaf);
  173534. if( rc==SQLITE_OK ){
  173535. rc = rc2;
  173536. }
  173537. }
  173538. if( rc==SQLITE_OK && pRtree->nAux ){
  173539. sqlite3_stmt *pUp = pRtree->pWriteAux;
  173540. int jj;
  173541. sqlite3_bind_int64(pUp, 1, *pRowid);
  173542. for(jj=0; jj<pRtree->nAux; jj++){
  173543. sqlite3_bind_value(pUp, jj+2, aData[pRtree->nDim2+3+jj]);
  173544. }
  173545. sqlite3_step(pUp);
  173546. rc = sqlite3_reset(pUp);
  173547. }
  173548. }
  173549. constraint:
  173550. rtreeRelease(pRtree);
  173551. return rc;
  173552. }
  173553. /*
  173554. ** Called when a transaction starts.
  173555. */
  173556. static int rtreeBeginTransaction(sqlite3_vtab *pVtab){
  173557. Rtree *pRtree = (Rtree *)pVtab;
  173558. assert( pRtree->inWrTrans==0 );
  173559. pRtree->inWrTrans++;
  173560. return SQLITE_OK;
  173561. }
  173562. /*
  173563. ** Called when a transaction completes (either by COMMIT or ROLLBACK).
  173564. ** The sqlite3_blob object should be released at this point.
  173565. */
  173566. static int rtreeEndTransaction(sqlite3_vtab *pVtab){
  173567. Rtree *pRtree = (Rtree *)pVtab;
  173568. pRtree->inWrTrans = 0;
  173569. nodeBlobReset(pRtree);
  173570. return SQLITE_OK;
  173571. }
  173572. /*
  173573. ** The xRename method for rtree module virtual tables.
  173574. */
  173575. static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
  173576. Rtree *pRtree = (Rtree *)pVtab;
  173577. int rc = SQLITE_NOMEM;
  173578. char *zSql = sqlite3_mprintf(
  173579. "ALTER TABLE %Q.'%q_node' RENAME TO \"%w_node\";"
  173580. "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
  173581. "ALTER TABLE %Q.'%q_rowid' RENAME TO \"%w_rowid\";"
  173582. , pRtree->zDb, pRtree->zName, zNewName
  173583. , pRtree->zDb, pRtree->zName, zNewName
  173584. , pRtree->zDb, pRtree->zName, zNewName
  173585. );
  173586. if( zSql ){
  173587. nodeBlobReset(pRtree);
  173588. rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
  173589. sqlite3_free(zSql);
  173590. }
  173591. return rc;
  173592. }
  173593. /*
  173594. ** The xSavepoint method.
  173595. **
  173596. ** This module does not need to do anything to support savepoints. However,
  173597. ** it uses this hook to close any open blob handle. This is done because a
  173598. ** DROP TABLE command - which fortunately always opens a savepoint - cannot
  173599. ** succeed if there are any open blob handles. i.e. if the blob handle were
  173600. ** not closed here, the following would fail:
  173601. **
  173602. ** BEGIN;
  173603. ** INSERT INTO rtree...
  173604. ** DROP TABLE <tablename>; -- Would fail with SQLITE_LOCKED
  173605. ** COMMIT;
  173606. */
  173607. static int rtreeSavepoint(sqlite3_vtab *pVtab, int iSavepoint){
  173608. Rtree *pRtree = (Rtree *)pVtab;
  173609. u8 iwt = pRtree->inWrTrans;
  173610. UNUSED_PARAMETER(iSavepoint);
  173611. pRtree->inWrTrans = 0;
  173612. nodeBlobReset(pRtree);
  173613. pRtree->inWrTrans = iwt;
  173614. return SQLITE_OK;
  173615. }
  173616. /*
  173617. ** This function populates the pRtree->nRowEst variable with an estimate
  173618. ** of the number of rows in the virtual table. If possible, this is based
  173619. ** on sqlite_stat1 data. Otherwise, use RTREE_DEFAULT_ROWEST.
  173620. */
  173621. static int rtreeQueryStat1(sqlite3 *db, Rtree *pRtree){
  173622. const char *zFmt = "SELECT stat FROM %Q.sqlite_stat1 WHERE tbl = '%q_rowid'";
  173623. char *zSql;
  173624. sqlite3_stmt *p;
  173625. int rc;
  173626. i64 nRow = 0;
  173627. rc = sqlite3_table_column_metadata(
  173628. db, pRtree->zDb, "sqlite_stat1",0,0,0,0,0,0
  173629. );
  173630. if( rc!=SQLITE_OK ){
  173631. pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
  173632. return rc==SQLITE_ERROR ? SQLITE_OK : rc;
  173633. }
  173634. zSql = sqlite3_mprintf(zFmt, pRtree->zDb, pRtree->zName);
  173635. if( zSql==0 ){
  173636. rc = SQLITE_NOMEM;
  173637. }else{
  173638. rc = sqlite3_prepare_v2(db, zSql, -1, &p, 0);
  173639. if( rc==SQLITE_OK ){
  173640. if( sqlite3_step(p)==SQLITE_ROW ) nRow = sqlite3_column_int64(p, 0);
  173641. rc = sqlite3_finalize(p);
  173642. }else if( rc!=SQLITE_NOMEM ){
  173643. rc = SQLITE_OK;
  173644. }
  173645. if( rc==SQLITE_OK ){
  173646. if( nRow==0 ){
  173647. pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
  173648. }else{
  173649. pRtree->nRowEst = MAX(nRow, RTREE_MIN_ROWEST);
  173650. }
  173651. }
  173652. sqlite3_free(zSql);
  173653. }
  173654. return rc;
  173655. }
  173656. /*
  173657. ** Return true if zName is the extension on one of the shadow tables used
  173658. ** by this module.
  173659. */
  173660. static int rtreeShadowName(const char *zName){
  173661. static const char *azName[] = {
  173662. "node", "parent", "rowid"
  173663. };
  173664. unsigned int i;
  173665. for(i=0; i<sizeof(azName)/sizeof(azName[0]); i++){
  173666. if( sqlite3_stricmp(zName, azName[i])==0 ) return 1;
  173667. }
  173668. return 0;
  173669. }
  173670. static sqlite3_module rtreeModule = {
  173671. 3, /* iVersion */
  173672. rtreeCreate, /* xCreate - create a table */
  173673. rtreeConnect, /* xConnect - connect to an existing table */
  173674. rtreeBestIndex, /* xBestIndex - Determine search strategy */
  173675. rtreeDisconnect, /* xDisconnect - Disconnect from a table */
  173676. rtreeDestroy, /* xDestroy - Drop a table */
  173677. rtreeOpen, /* xOpen - open a cursor */
  173678. rtreeClose, /* xClose - close a cursor */
  173679. rtreeFilter, /* xFilter - configure scan constraints */
  173680. rtreeNext, /* xNext - advance a cursor */
  173681. rtreeEof, /* xEof */
  173682. rtreeColumn, /* xColumn - read data */
  173683. rtreeRowid, /* xRowid - read data */
  173684. rtreeUpdate, /* xUpdate - write data */
  173685. rtreeBeginTransaction, /* xBegin - begin transaction */
  173686. rtreeEndTransaction, /* xSync - sync transaction */
  173687. rtreeEndTransaction, /* xCommit - commit transaction */
  173688. rtreeEndTransaction, /* xRollback - rollback transaction */
  173689. 0, /* xFindFunction - function overloading */
  173690. rtreeRename, /* xRename - rename the table */
  173691. rtreeSavepoint, /* xSavepoint */
  173692. 0, /* xRelease */
  173693. 0, /* xRollbackTo */
  173694. rtreeShadowName /* xShadowName */
  173695. };
  173696. static int rtreeSqlInit(
  173697. Rtree *pRtree,
  173698. sqlite3 *db,
  173699. const char *zDb,
  173700. const char *zPrefix,
  173701. int isCreate
  173702. ){
  173703. int rc = SQLITE_OK;
  173704. #define N_STATEMENT 8
  173705. static const char *azSql[N_STATEMENT] = {
  173706. /* Write the xxx_node table */
  173707. "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(?1, ?2)",
  173708. "DELETE FROM '%q'.'%q_node' WHERE nodeno = ?1",
  173709. /* Read and write the xxx_rowid table */
  173710. "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = ?1",
  173711. "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(?1, ?2)",
  173712. "DELETE FROM '%q'.'%q_rowid' WHERE rowid = ?1",
  173713. /* Read and write the xxx_parent table */
  173714. "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = ?1",
  173715. "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(?1, ?2)",
  173716. "DELETE FROM '%q'.'%q_parent' WHERE nodeno = ?1"
  173717. };
  173718. sqlite3_stmt **appStmt[N_STATEMENT];
  173719. int i;
  173720. const int f = SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_NO_VTAB;
  173721. pRtree->db = db;
  173722. if( isCreate ){
  173723. char *zCreate;
  173724. sqlite3_str *p = sqlite3_str_new(db);
  173725. int ii;
  173726. sqlite3_str_appendf(p,
  173727. "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY,nodeno",
  173728. zDb, zPrefix);
  173729. for(ii=0; ii<pRtree->nAux; ii++){
  173730. sqlite3_str_appendf(p,",a%d",ii);
  173731. }
  173732. sqlite3_str_appendf(p,
  173733. ");CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY,data);",
  173734. zDb, zPrefix);
  173735. sqlite3_str_appendf(p,
  173736. "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY,parentnode);",
  173737. zDb, zPrefix);
  173738. sqlite3_str_appendf(p,
  173739. "INSERT INTO \"%w\".\"%w_node\"VALUES(1,zeroblob(%d))",
  173740. zDb, zPrefix, pRtree->iNodeSize);
  173741. zCreate = sqlite3_str_finish(p);
  173742. if( !zCreate ){
  173743. return SQLITE_NOMEM;
  173744. }
  173745. rc = sqlite3_exec(db, zCreate, 0, 0, 0);
  173746. sqlite3_free(zCreate);
  173747. if( rc!=SQLITE_OK ){
  173748. return rc;
  173749. }
  173750. }
  173751. appStmt[0] = &pRtree->pWriteNode;
  173752. appStmt[1] = &pRtree->pDeleteNode;
  173753. appStmt[2] = &pRtree->pReadRowid;
  173754. appStmt[3] = &pRtree->pWriteRowid;
  173755. appStmt[4] = &pRtree->pDeleteRowid;
  173756. appStmt[5] = &pRtree->pReadParent;
  173757. appStmt[6] = &pRtree->pWriteParent;
  173758. appStmt[7] = &pRtree->pDeleteParent;
  173759. rc = rtreeQueryStat1(db, pRtree);
  173760. for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
  173761. char *zSql;
  173762. const char *zFormat;
  173763. if( i!=3 || pRtree->nAux==0 ){
  173764. zFormat = azSql[i];
  173765. }else {
  173766. /* An UPSERT is very slightly slower than REPLACE, but it is needed
  173767. ** if there are auxiliary columns */
  173768. zFormat = "INSERT INTO\"%w\".\"%w_rowid\"(rowid,nodeno)VALUES(?1,?2)"
  173769. "ON CONFLICT(rowid)DO UPDATE SET nodeno=excluded.nodeno";
  173770. }
  173771. zSql = sqlite3_mprintf(zFormat, zDb, zPrefix);
  173772. if( zSql ){
  173773. rc = sqlite3_prepare_v3(db, zSql, -1, f, appStmt[i], 0);
  173774. }else{
  173775. rc = SQLITE_NOMEM;
  173776. }
  173777. sqlite3_free(zSql);
  173778. }
  173779. if( pRtree->nAux ){
  173780. pRtree->zReadAuxSql = sqlite3_mprintf(
  173781. "SELECT * FROM \"%w\".\"%w_rowid\" WHERE rowid=?1",
  173782. zDb, zPrefix);
  173783. if( pRtree->zReadAuxSql==0 ){
  173784. rc = SQLITE_NOMEM;
  173785. }else{
  173786. sqlite3_str *p = sqlite3_str_new(db);
  173787. int ii;
  173788. char *zSql;
  173789. sqlite3_str_appendf(p, "UPDATE \"%w\".\"%w_rowid\"SET ", zDb, zPrefix);
  173790. for(ii=0; ii<pRtree->nAux; ii++){
  173791. if( ii ) sqlite3_str_append(p, ",", 1);
  173792. if( ii<pRtree->nAuxNotNull ){
  173793. sqlite3_str_appendf(p,"a%d=coalesce(?%d,a%d)",ii,ii+2,ii);
  173794. }else{
  173795. sqlite3_str_appendf(p,"a%d=?%d",ii,ii+2);
  173796. }
  173797. }
  173798. sqlite3_str_appendf(p, " WHERE rowid=?1");
  173799. zSql = sqlite3_str_finish(p);
  173800. if( zSql==0 ){
  173801. rc = SQLITE_NOMEM;
  173802. }else{
  173803. rc = sqlite3_prepare_v3(db, zSql, -1, f, &pRtree->pWriteAux, 0);
  173804. sqlite3_free(zSql);
  173805. }
  173806. }
  173807. }
  173808. return rc;
  173809. }
  173810. /*
  173811. ** The second argument to this function contains the text of an SQL statement
  173812. ** that returns a single integer value. The statement is compiled and executed
  173813. ** using database connection db. If successful, the integer value returned
  173814. ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
  173815. ** code is returned and the value of *piVal after returning is not defined.
  173816. */
  173817. static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
  173818. int rc = SQLITE_NOMEM;
  173819. if( zSql ){
  173820. sqlite3_stmt *pStmt = 0;
  173821. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  173822. if( rc==SQLITE_OK ){
  173823. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  173824. *piVal = sqlite3_column_int(pStmt, 0);
  173825. }
  173826. rc = sqlite3_finalize(pStmt);
  173827. }
  173828. }
  173829. return rc;
  173830. }
  173831. /*
  173832. ** This function is called from within the xConnect() or xCreate() method to
  173833. ** determine the node-size used by the rtree table being created or connected
  173834. ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
  173835. ** Otherwise, an SQLite error code is returned.
  173836. **
  173837. ** If this function is being called as part of an xConnect(), then the rtree
  173838. ** table already exists. In this case the node-size is determined by inspecting
  173839. ** the root node of the tree.
  173840. **
  173841. ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
  173842. ** This ensures that each node is stored on a single database page. If the
  173843. ** database page-size is so large that more than RTREE_MAXCELLS entries
  173844. ** would fit in a single node, use a smaller node-size.
  173845. */
  173846. static int getNodeSize(
  173847. sqlite3 *db, /* Database handle */
  173848. Rtree *pRtree, /* Rtree handle */
  173849. int isCreate, /* True for xCreate, false for xConnect */
  173850. char **pzErr /* OUT: Error message, if any */
  173851. ){
  173852. int rc;
  173853. char *zSql;
  173854. if( isCreate ){
  173855. int iPageSize = 0;
  173856. zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
  173857. rc = getIntFromStmt(db, zSql, &iPageSize);
  173858. if( rc==SQLITE_OK ){
  173859. pRtree->iNodeSize = iPageSize-64;
  173860. if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
  173861. pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
  173862. }
  173863. }else{
  173864. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  173865. }
  173866. }else{
  173867. zSql = sqlite3_mprintf(
  173868. "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
  173869. pRtree->zDb, pRtree->zName
  173870. );
  173871. rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
  173872. if( rc!=SQLITE_OK ){
  173873. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  173874. }else if( pRtree->iNodeSize<(512-64) ){
  173875. rc = SQLITE_CORRUPT_VTAB;
  173876. RTREE_IS_CORRUPT(pRtree);
  173877. *pzErr = sqlite3_mprintf("undersize RTree blobs in \"%q_node\"",
  173878. pRtree->zName);
  173879. }
  173880. }
  173881. sqlite3_free(zSql);
  173882. return rc;
  173883. }
  173884. /*
  173885. ** This function is the implementation of both the xConnect and xCreate
  173886. ** methods of the r-tree virtual table.
  173887. **
  173888. ** argv[0] -> module name
  173889. ** argv[1] -> database name
  173890. ** argv[2] -> table name
  173891. ** argv[...] -> column names...
  173892. */
  173893. static int rtreeInit(
  173894. sqlite3 *db, /* Database connection */
  173895. void *pAux, /* One of the RTREE_COORD_* constants */
  173896. int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */
  173897. sqlite3_vtab **ppVtab, /* OUT: New virtual table */
  173898. char **pzErr, /* OUT: Error message, if any */
  173899. int isCreate /* True for xCreate, false for xConnect */
  173900. ){
  173901. int rc = SQLITE_OK;
  173902. Rtree *pRtree;
  173903. int nDb; /* Length of string argv[1] */
  173904. int nName; /* Length of string argv[2] */
  173905. int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
  173906. sqlite3_str *pSql;
  173907. char *zSql;
  173908. int ii = 4;
  173909. int iErr;
  173910. const char *aErrMsg[] = {
  173911. 0, /* 0 */
  173912. "Wrong number of columns for an rtree table", /* 1 */
  173913. "Too few columns for an rtree table", /* 2 */
  173914. "Too many columns for an rtree table", /* 3 */
  173915. "Auxiliary rtree columns must be last" /* 4 */
  173916. };
  173917. assert( RTREE_MAX_AUX_COLUMN<256 ); /* Aux columns counted by a u8 */
  173918. if( argc>RTREE_MAX_AUX_COLUMN+3 ){
  173919. *pzErr = sqlite3_mprintf("%s", aErrMsg[3]);
  173920. return SQLITE_ERROR;
  173921. }
  173922. sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
  173923. /* Allocate the sqlite3_vtab structure */
  173924. nDb = (int)strlen(argv[1]);
  173925. nName = (int)strlen(argv[2]);
  173926. pRtree = (Rtree *)sqlite3_malloc64(sizeof(Rtree)+nDb+nName+2);
  173927. if( !pRtree ){
  173928. return SQLITE_NOMEM;
  173929. }
  173930. memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
  173931. pRtree->nBusy = 1;
  173932. pRtree->base.pModule = &rtreeModule;
  173933. pRtree->zDb = (char *)&pRtree[1];
  173934. pRtree->zName = &pRtree->zDb[nDb+1];
  173935. pRtree->eCoordType = (u8)eCoordType;
  173936. memcpy(pRtree->zDb, argv[1], nDb);
  173937. memcpy(pRtree->zName, argv[2], nName);
  173938. /* Create/Connect to the underlying relational database schema. If
  173939. ** that is successful, call sqlite3_declare_vtab() to configure
  173940. ** the r-tree table schema.
  173941. */
  173942. pSql = sqlite3_str_new(db);
  173943. sqlite3_str_appendf(pSql, "CREATE TABLE x(%s", argv[3]);
  173944. for(ii=4; ii<argc; ii++){
  173945. if( argv[ii][0]=='+' ){
  173946. pRtree->nAux++;
  173947. sqlite3_str_appendf(pSql, ",%s", argv[ii]+1);
  173948. }else if( pRtree->nAux>0 ){
  173949. break;
  173950. }else{
  173951. pRtree->nDim2++;
  173952. sqlite3_str_appendf(pSql, ",%s", argv[ii]);
  173953. }
  173954. }
  173955. sqlite3_str_appendf(pSql, ");");
  173956. zSql = sqlite3_str_finish(pSql);
  173957. if( !zSql ){
  173958. rc = SQLITE_NOMEM;
  173959. }else if( ii<argc ){
  173960. *pzErr = sqlite3_mprintf("%s", aErrMsg[4]);
  173961. rc = SQLITE_ERROR;
  173962. }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
  173963. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  173964. }
  173965. sqlite3_free(zSql);
  173966. if( rc ) goto rtreeInit_fail;
  173967. pRtree->nDim = pRtree->nDim2/2;
  173968. if( pRtree->nDim<1 ){
  173969. iErr = 2;
  173970. }else if( pRtree->nDim2>RTREE_MAX_DIMENSIONS*2 ){
  173971. iErr = 3;
  173972. }else if( pRtree->nDim2 % 2 ){
  173973. iErr = 1;
  173974. }else{
  173975. iErr = 0;
  173976. }
  173977. if( iErr ){
  173978. *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
  173979. goto rtreeInit_fail;
  173980. }
  173981. pRtree->nBytesPerCell = 8 + pRtree->nDim2*4;
  173982. /* Figure out the node size to use. */
  173983. rc = getNodeSize(db, pRtree, isCreate, pzErr);
  173984. if( rc ) goto rtreeInit_fail;
  173985. rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate);
  173986. if( rc ){
  173987. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  173988. goto rtreeInit_fail;
  173989. }
  173990. *ppVtab = (sqlite3_vtab *)pRtree;
  173991. return SQLITE_OK;
  173992. rtreeInit_fail:
  173993. if( rc==SQLITE_OK ) rc = SQLITE_ERROR;
  173994. assert( *ppVtab==0 );
  173995. assert( pRtree->nBusy==1 );
  173996. rtreeRelease(pRtree);
  173997. return rc;
  173998. }
  173999. /*
  174000. ** Implementation of a scalar function that decodes r-tree nodes to
  174001. ** human readable strings. This can be used for debugging and analysis.
  174002. **
  174003. ** The scalar function takes two arguments: (1) the number of dimensions
  174004. ** to the rtree (between 1 and 5, inclusive) and (2) a blob of data containing
  174005. ** an r-tree node. For a two-dimensional r-tree structure called "rt", to
  174006. ** deserialize all nodes, a statement like:
  174007. **
  174008. ** SELECT rtreenode(2, data) FROM rt_node;
  174009. **
  174010. ** The human readable string takes the form of a Tcl list with one
  174011. ** entry for each cell in the r-tree node. Each entry is itself a
  174012. ** list, containing the 8-byte rowid/pageno followed by the
  174013. ** <num-dimension>*2 coordinates.
  174014. */
  174015. static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
  174016. RtreeNode node;
  174017. Rtree tree;
  174018. int ii;
  174019. int nData;
  174020. int errCode;
  174021. sqlite3_str *pOut;
  174022. UNUSED_PARAMETER(nArg);
  174023. memset(&node, 0, sizeof(RtreeNode));
  174024. memset(&tree, 0, sizeof(Rtree));
  174025. tree.nDim = (u8)sqlite3_value_int(apArg[0]);
  174026. if( tree.nDim<1 || tree.nDim>5 ) return;
  174027. tree.nDim2 = tree.nDim*2;
  174028. tree.nBytesPerCell = 8 + 8 * tree.nDim;
  174029. node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
  174030. nData = sqlite3_value_bytes(apArg[1]);
  174031. if( nData<4 ) return;
  174032. if( nData<NCELL(&node)*tree.nBytesPerCell ) return;
  174033. pOut = sqlite3_str_new(0);
  174034. for(ii=0; ii<NCELL(&node); ii++){
  174035. RtreeCell cell;
  174036. int jj;
  174037. nodeGetCell(&tree, &node, ii, &cell);
  174038. if( ii>0 ) sqlite3_str_append(pOut, " ", 1);
  174039. sqlite3_str_appendf(pOut, "{%lld", cell.iRowid);
  174040. for(jj=0; jj<tree.nDim2; jj++){
  174041. #ifndef SQLITE_RTREE_INT_ONLY
  174042. sqlite3_str_appendf(pOut, " %g", (double)cell.aCoord[jj].f);
  174043. #else
  174044. sqlite3_str_appendf(pOut, " %d", cell.aCoord[jj].i);
  174045. #endif
  174046. }
  174047. sqlite3_str_append(pOut, "}", 1);
  174048. }
  174049. errCode = sqlite3_str_errcode(pOut);
  174050. sqlite3_result_text(ctx, sqlite3_str_finish(pOut), -1, sqlite3_free);
  174051. sqlite3_result_error_code(ctx, errCode);
  174052. }
  174053. /* This routine implements an SQL function that returns the "depth" parameter
  174054. ** from the front of a blob that is an r-tree node. For example:
  174055. **
  174056. ** SELECT rtreedepth(data) FROM rt_node WHERE nodeno=1;
  174057. **
  174058. ** The depth value is 0 for all nodes other than the root node, and the root
  174059. ** node always has nodeno=1, so the example above is the primary use for this
  174060. ** routine. This routine is intended for testing and analysis only.
  174061. */
  174062. static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
  174063. UNUSED_PARAMETER(nArg);
  174064. if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
  174065. || sqlite3_value_bytes(apArg[0])<2
  174066. ){
  174067. sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
  174068. }else{
  174069. u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
  174070. sqlite3_result_int(ctx, readInt16(zBlob));
  174071. }
  174072. }
  174073. /*
  174074. ** Context object passed between the various routines that make up the
  174075. ** implementation of integrity-check function rtreecheck().
  174076. */
  174077. typedef struct RtreeCheck RtreeCheck;
  174078. struct RtreeCheck {
  174079. sqlite3 *db; /* Database handle */
  174080. const char *zDb; /* Database containing rtree table */
  174081. const char *zTab; /* Name of rtree table */
  174082. int bInt; /* True for rtree_i32 table */
  174083. int nDim; /* Number of dimensions for this rtree tbl */
  174084. sqlite3_stmt *pGetNode; /* Statement used to retrieve nodes */
  174085. sqlite3_stmt *aCheckMapping[2]; /* Statements to query %_parent/%_rowid */
  174086. int nLeaf; /* Number of leaf cells in table */
  174087. int nNonLeaf; /* Number of non-leaf cells in table */
  174088. int rc; /* Return code */
  174089. char *zReport; /* Message to report */
  174090. int nErr; /* Number of lines in zReport */
  174091. };
  174092. #define RTREE_CHECK_MAX_ERROR 100
  174093. /*
  174094. ** Reset SQL statement pStmt. If the sqlite3_reset() call returns an error,
  174095. ** and RtreeCheck.rc==SQLITE_OK, set RtreeCheck.rc to the error code.
  174096. */
  174097. static void rtreeCheckReset(RtreeCheck *pCheck, sqlite3_stmt *pStmt){
  174098. int rc = sqlite3_reset(pStmt);
  174099. if( pCheck->rc==SQLITE_OK ) pCheck->rc = rc;
  174100. }
  174101. /*
  174102. ** The second and subsequent arguments to this function are a format string
  174103. ** and printf style arguments. This function formats the string and attempts
  174104. ** to compile it as an SQL statement.
  174105. **
  174106. ** If successful, a pointer to the new SQL statement is returned. Otherwise,
  174107. ** NULL is returned and an error code left in RtreeCheck.rc.
  174108. */
  174109. static sqlite3_stmt *rtreeCheckPrepare(
  174110. RtreeCheck *pCheck, /* RtreeCheck object */
  174111. const char *zFmt, ... /* Format string and trailing args */
  174112. ){
  174113. va_list ap;
  174114. char *z;
  174115. sqlite3_stmt *pRet = 0;
  174116. va_start(ap, zFmt);
  174117. z = sqlite3_vmprintf(zFmt, ap);
  174118. if( pCheck->rc==SQLITE_OK ){
  174119. if( z==0 ){
  174120. pCheck->rc = SQLITE_NOMEM;
  174121. }else{
  174122. pCheck->rc = sqlite3_prepare_v2(pCheck->db, z, -1, &pRet, 0);
  174123. }
  174124. }
  174125. sqlite3_free(z);
  174126. va_end(ap);
  174127. return pRet;
  174128. }
  174129. /*
  174130. ** The second and subsequent arguments to this function are a printf()
  174131. ** style format string and arguments. This function formats the string and
  174132. ** appends it to the report being accumuated in pCheck.
  174133. */
  174134. static void rtreeCheckAppendMsg(RtreeCheck *pCheck, const char *zFmt, ...){
  174135. va_list ap;
  174136. va_start(ap, zFmt);
  174137. if( pCheck->rc==SQLITE_OK && pCheck->nErr<RTREE_CHECK_MAX_ERROR ){
  174138. char *z = sqlite3_vmprintf(zFmt, ap);
  174139. if( z==0 ){
  174140. pCheck->rc = SQLITE_NOMEM;
  174141. }else{
  174142. pCheck->zReport = sqlite3_mprintf("%z%s%z",
  174143. pCheck->zReport, (pCheck->zReport ? "\n" : ""), z
  174144. );
  174145. if( pCheck->zReport==0 ){
  174146. pCheck->rc = SQLITE_NOMEM;
  174147. }
  174148. }
  174149. pCheck->nErr++;
  174150. }
  174151. va_end(ap);
  174152. }
  174153. /*
  174154. ** This function is a no-op if there is already an error code stored
  174155. ** in the RtreeCheck object indicated by the first argument. NULL is
  174156. ** returned in this case.
  174157. **
  174158. ** Otherwise, the contents of rtree table node iNode are loaded from
  174159. ** the database and copied into a buffer obtained from sqlite3_malloc().
  174160. ** If no error occurs, a pointer to the buffer is returned and (*pnNode)
  174161. ** is set to the size of the buffer in bytes.
  174162. **
  174163. ** Or, if an error does occur, NULL is returned and an error code left
  174164. ** in the RtreeCheck object. The final value of *pnNode is undefined in
  174165. ** this case.
  174166. */
  174167. static u8 *rtreeCheckGetNode(RtreeCheck *pCheck, i64 iNode, int *pnNode){
  174168. u8 *pRet = 0; /* Return value */
  174169. if( pCheck->rc==SQLITE_OK && pCheck->pGetNode==0 ){
  174170. pCheck->pGetNode = rtreeCheckPrepare(pCheck,
  174171. "SELECT data FROM %Q.'%q_node' WHERE nodeno=?",
  174172. pCheck->zDb, pCheck->zTab
  174173. );
  174174. }
  174175. if( pCheck->rc==SQLITE_OK ){
  174176. sqlite3_bind_int64(pCheck->pGetNode, 1, iNode);
  174177. if( sqlite3_step(pCheck->pGetNode)==SQLITE_ROW ){
  174178. int nNode = sqlite3_column_bytes(pCheck->pGetNode, 0);
  174179. const u8 *pNode = (const u8*)sqlite3_column_blob(pCheck->pGetNode, 0);
  174180. pRet = sqlite3_malloc64(nNode);
  174181. if( pRet==0 ){
  174182. pCheck->rc = SQLITE_NOMEM;
  174183. }else{
  174184. memcpy(pRet, pNode, nNode);
  174185. *pnNode = nNode;
  174186. }
  174187. }
  174188. rtreeCheckReset(pCheck, pCheck->pGetNode);
  174189. if( pCheck->rc==SQLITE_OK && pRet==0 ){
  174190. rtreeCheckAppendMsg(pCheck, "Node %lld missing from database", iNode);
  174191. }
  174192. }
  174193. return pRet;
  174194. }
  174195. /*
  174196. ** This function is used to check that the %_parent (if bLeaf==0) or %_rowid
  174197. ** (if bLeaf==1) table contains a specified entry. The schemas of the
  174198. ** two tables are:
  174199. **
  174200. ** CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
  174201. ** CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER, ...)
  174202. **
  174203. ** In both cases, this function checks that there exists an entry with
  174204. ** IPK value iKey and the second column set to iVal.
  174205. **
  174206. */
  174207. static void rtreeCheckMapping(
  174208. RtreeCheck *pCheck, /* RtreeCheck object */
  174209. int bLeaf, /* True for a leaf cell, false for interior */
  174210. i64 iKey, /* Key for mapping */
  174211. i64 iVal /* Expected value for mapping */
  174212. ){
  174213. int rc;
  174214. sqlite3_stmt *pStmt;
  174215. const char *azSql[2] = {
  174216. "SELECT parentnode FROM %Q.'%q_parent' WHERE nodeno=?1",
  174217. "SELECT nodeno FROM %Q.'%q_rowid' WHERE rowid=?1"
  174218. };
  174219. assert( bLeaf==0 || bLeaf==1 );
  174220. if( pCheck->aCheckMapping[bLeaf]==0 ){
  174221. pCheck->aCheckMapping[bLeaf] = rtreeCheckPrepare(pCheck,
  174222. azSql[bLeaf], pCheck->zDb, pCheck->zTab
  174223. );
  174224. }
  174225. if( pCheck->rc!=SQLITE_OK ) return;
  174226. pStmt = pCheck->aCheckMapping[bLeaf];
  174227. sqlite3_bind_int64(pStmt, 1, iKey);
  174228. rc = sqlite3_step(pStmt);
  174229. if( rc==SQLITE_DONE ){
  174230. rtreeCheckAppendMsg(pCheck, "Mapping (%lld -> %lld) missing from %s table",
  174231. iKey, iVal, (bLeaf ? "%_rowid" : "%_parent")
  174232. );
  174233. }else if( rc==SQLITE_ROW ){
  174234. i64 ii = sqlite3_column_int64(pStmt, 0);
  174235. if( ii!=iVal ){
  174236. rtreeCheckAppendMsg(pCheck,
  174237. "Found (%lld -> %lld) in %s table, expected (%lld -> %lld)",
  174238. iKey, ii, (bLeaf ? "%_rowid" : "%_parent"), iKey, iVal
  174239. );
  174240. }
  174241. }
  174242. rtreeCheckReset(pCheck, pStmt);
  174243. }
  174244. /*
  174245. ** Argument pCell points to an array of coordinates stored on an rtree page.
  174246. ** This function checks that the coordinates are internally consistent (no
  174247. ** x1>x2 conditions) and adds an error message to the RtreeCheck object
  174248. ** if they are not.
  174249. **
  174250. ** Additionally, if pParent is not NULL, then it is assumed to point to
  174251. ** the array of coordinates on the parent page that bound the page
  174252. ** containing pCell. In this case it is also verified that the two
  174253. ** sets of coordinates are mutually consistent and an error message added
  174254. ** to the RtreeCheck object if they are not.
  174255. */
  174256. static void rtreeCheckCellCoord(
  174257. RtreeCheck *pCheck,
  174258. i64 iNode, /* Node id to use in error messages */
  174259. int iCell, /* Cell number to use in error messages */
  174260. u8 *pCell, /* Pointer to cell coordinates */
  174261. u8 *pParent /* Pointer to parent coordinates */
  174262. ){
  174263. RtreeCoord c1, c2;
  174264. RtreeCoord p1, p2;
  174265. int i;
  174266. for(i=0; i<pCheck->nDim; i++){
  174267. readCoord(&pCell[4*2*i], &c1);
  174268. readCoord(&pCell[4*(2*i + 1)], &c2);
  174269. /* printf("%e, %e\n", c1.u.f, c2.u.f); */
  174270. if( pCheck->bInt ? c1.i>c2.i : c1.f>c2.f ){
  174271. rtreeCheckAppendMsg(pCheck,
  174272. "Dimension %d of cell %d on node %lld is corrupt", i, iCell, iNode
  174273. );
  174274. }
  174275. if( pParent ){
  174276. readCoord(&pParent[4*2*i], &p1);
  174277. readCoord(&pParent[4*(2*i + 1)], &p2);
  174278. if( (pCheck->bInt ? c1.i<p1.i : c1.f<p1.f)
  174279. || (pCheck->bInt ? c2.i>p2.i : c2.f>p2.f)
  174280. ){
  174281. rtreeCheckAppendMsg(pCheck,
  174282. "Dimension %d of cell %d on node %lld is corrupt relative to parent"
  174283. , i, iCell, iNode
  174284. );
  174285. }
  174286. }
  174287. }
  174288. }
  174289. /*
  174290. ** Run rtreecheck() checks on node iNode, which is at depth iDepth within
  174291. ** the r-tree structure. Argument aParent points to the array of coordinates
  174292. ** that bound node iNode on the parent node.
  174293. **
  174294. ** If any problems are discovered, an error message is appended to the
  174295. ** report accumulated in the RtreeCheck object.
  174296. */
  174297. static void rtreeCheckNode(
  174298. RtreeCheck *pCheck,
  174299. int iDepth, /* Depth of iNode (0==leaf) */
  174300. u8 *aParent, /* Buffer containing parent coords */
  174301. i64 iNode /* Node to check */
  174302. ){
  174303. u8 *aNode = 0;
  174304. int nNode = 0;
  174305. assert( iNode==1 || aParent!=0 );
  174306. assert( pCheck->nDim>0 );
  174307. aNode = rtreeCheckGetNode(pCheck, iNode, &nNode);
  174308. if( aNode ){
  174309. if( nNode<4 ){
  174310. rtreeCheckAppendMsg(pCheck,
  174311. "Node %lld is too small (%d bytes)", iNode, nNode
  174312. );
  174313. }else{
  174314. int nCell; /* Number of cells on page */
  174315. int i; /* Used to iterate through cells */
  174316. if( aParent==0 ){
  174317. iDepth = readInt16(aNode);
  174318. if( iDepth>RTREE_MAX_DEPTH ){
  174319. rtreeCheckAppendMsg(pCheck, "Rtree depth out of range (%d)", iDepth);
  174320. sqlite3_free(aNode);
  174321. return;
  174322. }
  174323. }
  174324. nCell = readInt16(&aNode[2]);
  174325. if( (4 + nCell*(8 + pCheck->nDim*2*4))>nNode ){
  174326. rtreeCheckAppendMsg(pCheck,
  174327. "Node %lld is too small for cell count of %d (%d bytes)",
  174328. iNode, nCell, nNode
  174329. );
  174330. }else{
  174331. for(i=0; i<nCell; i++){
  174332. u8 *pCell = &aNode[4 + i*(8 + pCheck->nDim*2*4)];
  174333. i64 iVal = readInt64(pCell);
  174334. rtreeCheckCellCoord(pCheck, iNode, i, &pCell[8], aParent);
  174335. if( iDepth>0 ){
  174336. rtreeCheckMapping(pCheck, 0, iVal, iNode);
  174337. rtreeCheckNode(pCheck, iDepth-1, &pCell[8], iVal);
  174338. pCheck->nNonLeaf++;
  174339. }else{
  174340. rtreeCheckMapping(pCheck, 1, iVal, iNode);
  174341. pCheck->nLeaf++;
  174342. }
  174343. }
  174344. }
  174345. }
  174346. sqlite3_free(aNode);
  174347. }
  174348. }
  174349. /*
  174350. ** The second argument to this function must be either "_rowid" or
  174351. ** "_parent". This function checks that the number of entries in the
  174352. ** %_rowid or %_parent table is exactly nExpect. If not, it adds
  174353. ** an error message to the report in the RtreeCheck object indicated
  174354. ** by the first argument.
  174355. */
  174356. static void rtreeCheckCount(RtreeCheck *pCheck, const char *zTbl, i64 nExpect){
  174357. if( pCheck->rc==SQLITE_OK ){
  174358. sqlite3_stmt *pCount;
  174359. pCount = rtreeCheckPrepare(pCheck, "SELECT count(*) FROM %Q.'%q%s'",
  174360. pCheck->zDb, pCheck->zTab, zTbl
  174361. );
  174362. if( pCount ){
  174363. if( sqlite3_step(pCount)==SQLITE_ROW ){
  174364. i64 nActual = sqlite3_column_int64(pCount, 0);
  174365. if( nActual!=nExpect ){
  174366. rtreeCheckAppendMsg(pCheck, "Wrong number of entries in %%%s table"
  174367. " - expected %lld, actual %lld" , zTbl, nExpect, nActual
  174368. );
  174369. }
  174370. }
  174371. pCheck->rc = sqlite3_finalize(pCount);
  174372. }
  174373. }
  174374. }
  174375. /*
  174376. ** This function does the bulk of the work for the rtree integrity-check.
  174377. ** It is called by rtreecheck(), which is the SQL function implementation.
  174378. */
  174379. static int rtreeCheckTable(
  174380. sqlite3 *db, /* Database handle to access db through */
  174381. const char *zDb, /* Name of db ("main", "temp" etc.) */
  174382. const char *zTab, /* Name of rtree table to check */
  174383. char **pzReport /* OUT: sqlite3_malloc'd report text */
  174384. ){
  174385. RtreeCheck check; /* Common context for various routines */
  174386. sqlite3_stmt *pStmt = 0; /* Used to find column count of rtree table */
  174387. int bEnd = 0; /* True if transaction should be closed */
  174388. int nAux = 0; /* Number of extra columns. */
  174389. /* Initialize the context object */
  174390. memset(&check, 0, sizeof(check));
  174391. check.db = db;
  174392. check.zDb = zDb;
  174393. check.zTab = zTab;
  174394. /* If there is not already an open transaction, open one now. This is
  174395. ** to ensure that the queries run as part of this integrity-check operate
  174396. ** on a consistent snapshot. */
  174397. if( sqlite3_get_autocommit(db) ){
  174398. check.rc = sqlite3_exec(db, "BEGIN", 0, 0, 0);
  174399. bEnd = 1;
  174400. }
  174401. /* Find the number of auxiliary columns */
  174402. if( check.rc==SQLITE_OK ){
  174403. pStmt = rtreeCheckPrepare(&check, "SELECT * FROM %Q.'%q_rowid'", zDb, zTab);
  174404. if( pStmt ){
  174405. nAux = sqlite3_column_count(pStmt) - 2;
  174406. sqlite3_finalize(pStmt);
  174407. }
  174408. check.rc = SQLITE_OK;
  174409. }
  174410. /* Find number of dimensions in the rtree table. */
  174411. pStmt = rtreeCheckPrepare(&check, "SELECT * FROM %Q.%Q", zDb, zTab);
  174412. if( pStmt ){
  174413. int rc;
  174414. check.nDim = (sqlite3_column_count(pStmt) - 1 - nAux) / 2;
  174415. if( check.nDim<1 ){
  174416. rtreeCheckAppendMsg(&check, "Schema corrupt or not an rtree");
  174417. }else if( SQLITE_ROW==sqlite3_step(pStmt) ){
  174418. check.bInt = (sqlite3_column_type(pStmt, 1)==SQLITE_INTEGER);
  174419. }
  174420. rc = sqlite3_finalize(pStmt);
  174421. if( rc!=SQLITE_CORRUPT ) check.rc = rc;
  174422. }
  174423. /* Do the actual integrity-check */
  174424. if( check.nDim>=1 ){
  174425. if( check.rc==SQLITE_OK ){
  174426. rtreeCheckNode(&check, 0, 0, 1);
  174427. }
  174428. rtreeCheckCount(&check, "_rowid", check.nLeaf);
  174429. rtreeCheckCount(&check, "_parent", check.nNonLeaf);
  174430. }
  174431. /* Finalize SQL statements used by the integrity-check */
  174432. sqlite3_finalize(check.pGetNode);
  174433. sqlite3_finalize(check.aCheckMapping[0]);
  174434. sqlite3_finalize(check.aCheckMapping[1]);
  174435. /* If one was opened, close the transaction */
  174436. if( bEnd ){
  174437. int rc = sqlite3_exec(db, "END", 0, 0, 0);
  174438. if( check.rc==SQLITE_OK ) check.rc = rc;
  174439. }
  174440. *pzReport = check.zReport;
  174441. return check.rc;
  174442. }
  174443. /*
  174444. ** Usage:
  174445. **
  174446. ** rtreecheck(<rtree-table>);
  174447. ** rtreecheck(<database>, <rtree-table>);
  174448. **
  174449. ** Invoking this SQL function runs an integrity-check on the named rtree
  174450. ** table. The integrity-check verifies the following:
  174451. **
  174452. ** 1. For each cell in the r-tree structure (%_node table), that:
  174453. **
  174454. ** a) for each dimension, (coord1 <= coord2).
  174455. **
  174456. ** b) unless the cell is on the root node, that the cell is bounded
  174457. ** by the parent cell on the parent node.
  174458. **
  174459. ** c) for leaf nodes, that there is an entry in the %_rowid
  174460. ** table corresponding to the cell's rowid value that
  174461. ** points to the correct node.
  174462. **
  174463. ** d) for cells on non-leaf nodes, that there is an entry in the
  174464. ** %_parent table mapping from the cell's child node to the
  174465. ** node that it resides on.
  174466. **
  174467. ** 2. That there are the same number of entries in the %_rowid table
  174468. ** as there are leaf cells in the r-tree structure, and that there
  174469. ** is a leaf cell that corresponds to each entry in the %_rowid table.
  174470. **
  174471. ** 3. That there are the same number of entries in the %_parent table
  174472. ** as there are non-leaf cells in the r-tree structure, and that
  174473. ** there is a non-leaf cell that corresponds to each entry in the
  174474. ** %_parent table.
  174475. */
  174476. static void rtreecheck(
  174477. sqlite3_context *ctx,
  174478. int nArg,
  174479. sqlite3_value **apArg
  174480. ){
  174481. if( nArg!=1 && nArg!=2 ){
  174482. sqlite3_result_error(ctx,
  174483. "wrong number of arguments to function rtreecheck()", -1
  174484. );
  174485. }else{
  174486. int rc;
  174487. char *zReport = 0;
  174488. const char *zDb = (const char*)sqlite3_value_text(apArg[0]);
  174489. const char *zTab;
  174490. if( nArg==1 ){
  174491. zTab = zDb;
  174492. zDb = "main";
  174493. }else{
  174494. zTab = (const char*)sqlite3_value_text(apArg[1]);
  174495. }
  174496. rc = rtreeCheckTable(sqlite3_context_db_handle(ctx), zDb, zTab, &zReport);
  174497. if( rc==SQLITE_OK ){
  174498. sqlite3_result_text(ctx, zReport ? zReport : "ok", -1, SQLITE_TRANSIENT);
  174499. }else{
  174500. sqlite3_result_error_code(ctx, rc);
  174501. }
  174502. sqlite3_free(zReport);
  174503. }
  174504. }
  174505. /* Conditionally include the geopoly code */
  174506. #ifdef SQLITE_ENABLE_GEOPOLY
  174507. /************** Include geopoly.c in the middle of rtree.c *******************/
  174508. /************** Begin file geopoly.c *****************************************/
  174509. /*
  174510. ** 2018-05-25
  174511. **
  174512. ** The author disclaims copyright to this source code. In place of
  174513. ** a legal notice, here is a blessing:
  174514. **
  174515. ** May you do good and not evil.
  174516. ** May you find forgiveness for yourself and forgive others.
  174517. ** May you share freely, never taking more than you give.
  174518. **
  174519. ******************************************************************************
  174520. **
  174521. ** This file implements an alternative R-Tree virtual table that
  174522. ** uses polygons to express the boundaries of 2-dimensional objects.
  174523. **
  174524. ** This file is #include-ed onto the end of "rtree.c" so that it has
  174525. ** access to all of the R-Tree internals.
  174526. */
  174527. /* #include <stdlib.h> */
  174528. /* Enable -DGEOPOLY_ENABLE_DEBUG for debugging facilities */
  174529. #ifdef GEOPOLY_ENABLE_DEBUG
  174530. static int geo_debug = 0;
  174531. # define GEODEBUG(X) if(geo_debug)printf X
  174532. #else
  174533. # define GEODEBUG(X)
  174534. #endif
  174535. #ifndef JSON_NULL /* The following stuff repeats things found in json1 */
  174536. /*
  174537. ** Versions of isspace(), isalnum() and isdigit() to which it is safe
  174538. ** to pass signed char values.
  174539. */
  174540. #ifdef sqlite3Isdigit
  174541. /* Use the SQLite core versions if this routine is part of the
  174542. ** SQLite amalgamation */
  174543. # define safe_isdigit(x) sqlite3Isdigit(x)
  174544. # define safe_isalnum(x) sqlite3Isalnum(x)
  174545. # define safe_isxdigit(x) sqlite3Isxdigit(x)
  174546. #else
  174547. /* Use the standard library for separate compilation */
  174548. #include <ctype.h> /* amalgamator: keep */
  174549. # define safe_isdigit(x) isdigit((unsigned char)(x))
  174550. # define safe_isalnum(x) isalnum((unsigned char)(x))
  174551. # define safe_isxdigit(x) isxdigit((unsigned char)(x))
  174552. #endif
  174553. /*
  174554. ** Growing our own isspace() routine this way is twice as fast as
  174555. ** the library isspace() function.
  174556. */
  174557. static const char geopolyIsSpace[] = {
  174558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0,
  174559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  174560. 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  174561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  174562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  174563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  174564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  174565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  174566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  174567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  174568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  174569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  174570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  174571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  174572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  174573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  174574. };
  174575. #define safe_isspace(x) (geopolyIsSpace[(unsigned char)x])
  174576. #endif /* JSON NULL - back to original code */
  174577. /* Compiler and version */
  174578. #ifndef GCC_VERSION
  174579. #if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC)
  174580. # define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)
  174581. #else
  174582. # define GCC_VERSION 0
  174583. #endif
  174584. #endif
  174585. #ifndef MSVC_VERSION
  174586. #if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC)
  174587. # define MSVC_VERSION _MSC_VER
  174588. #else
  174589. # define MSVC_VERSION 0
  174590. #endif
  174591. #endif
  174592. /* Datatype for coordinates
  174593. */
  174594. typedef float GeoCoord;
  174595. /*
  174596. ** Internal representation of a polygon.
  174597. **
  174598. ** The polygon consists of a sequence of vertexes. There is a line
  174599. ** segment between each pair of vertexes, and one final segment from
  174600. ** the last vertex back to the first. (This differs from the GeoJSON
  174601. ** standard in which the final vertex is a repeat of the first.)
  174602. **
  174603. ** The polygon follows the right-hand rule. The area to the right of
  174604. ** each segment is "outside" and the area to the left is "inside".
  174605. **
  174606. ** The on-disk representation consists of a 4-byte header followed by
  174607. ** the values. The 4-byte header is:
  174608. **
  174609. ** encoding (1 byte) 0=big-endian, 1=little-endian
  174610. ** nvertex (3 bytes) Number of vertexes as a big-endian integer
  174611. **
  174612. ** Enough space is allocated for 4 coordinates, to work around over-zealous
  174613. ** warnings coming from some compiler (notably, clang). In reality, the size
  174614. ** of each GeoPoly memory allocate is adjusted as necessary so that the
  174615. ** GeoPoly.a[] array at the end is the appropriate size.
  174616. */
  174617. typedef struct GeoPoly GeoPoly;
  174618. struct GeoPoly {
  174619. int nVertex; /* Number of vertexes */
  174620. unsigned char hdr[4]; /* Header for on-disk representation */
  174621. GeoCoord a[8]; /* 2*nVertex values. X (longitude) first, then Y */
  174622. };
  174623. /* The size of a memory allocation needed for a GeoPoly object sufficient
  174624. ** to hold N coordinate pairs.
  174625. */
  174626. #define GEOPOLY_SZ(N) (sizeof(GeoPoly) + sizeof(GeoCoord)*2*((N)-4))
  174627. /* Macros to access coordinates of a GeoPoly.
  174628. ** We have to use these macros, rather than just say p->a[i] in order
  174629. ** to silence (incorrect) UBSAN warnings if the array index is too large.
  174630. */
  174631. #define GeoX(P,I) (((GeoCoord*)(P)->a)[(I)*2])
  174632. #define GeoY(P,I) (((GeoCoord*)(P)->a)[(I)*2+1])
  174633. /*
  174634. ** State of a parse of a GeoJSON input.
  174635. */
  174636. typedef struct GeoParse GeoParse;
  174637. struct GeoParse {
  174638. const unsigned char *z; /* Unparsed input */
  174639. int nVertex; /* Number of vertexes in a[] */
  174640. int nAlloc; /* Space allocated to a[] */
  174641. int nErr; /* Number of errors encountered */
  174642. GeoCoord *a; /* Array of vertexes. From sqlite3_malloc64() */
  174643. };
  174644. /* Do a 4-byte byte swap */
  174645. static void geopolySwab32(unsigned char *a){
  174646. unsigned char t = a[0];
  174647. a[0] = a[3];
  174648. a[3] = t;
  174649. t = a[1];
  174650. a[1] = a[2];
  174651. a[2] = t;
  174652. }
  174653. /* Skip whitespace. Return the next non-whitespace character. */
  174654. static char geopolySkipSpace(GeoParse *p){
  174655. while( safe_isspace(p->z[0]) ) p->z++;
  174656. return p->z[0];
  174657. }
  174658. /* Parse out a number. Write the value into *pVal if pVal!=0.
  174659. ** return non-zero on success and zero if the next token is not a number.
  174660. */
  174661. static int geopolyParseNumber(GeoParse *p, GeoCoord *pVal){
  174662. char c = geopolySkipSpace(p);
  174663. const unsigned char *z = p->z;
  174664. int j = 0;
  174665. int seenDP = 0;
  174666. int seenE = 0;
  174667. if( c=='-' ){
  174668. j = 1;
  174669. c = z[j];
  174670. }
  174671. if( c=='0' && z[j+1]>='0' && z[j+1]<='9' ) return 0;
  174672. for(;; j++){
  174673. c = z[j];
  174674. if( safe_isdigit(c) ) continue;
  174675. if( c=='.' ){
  174676. if( z[j-1]=='-' ) return 0;
  174677. if( seenDP ) return 0;
  174678. seenDP = 1;
  174679. continue;
  174680. }
  174681. if( c=='e' || c=='E' ){
  174682. if( z[j-1]<'0' ) return 0;
  174683. if( seenE ) return -1;
  174684. seenDP = seenE = 1;
  174685. c = z[j+1];
  174686. if( c=='+' || c=='-' ){
  174687. j++;
  174688. c = z[j+1];
  174689. }
  174690. if( c<'0' || c>'9' ) return 0;
  174691. continue;
  174692. }
  174693. break;
  174694. }
  174695. if( z[j-1]<'0' ) return 0;
  174696. if( pVal ){
  174697. #ifdef SQLITE_AMALGAMATION
  174698. /* The sqlite3AtoF() routine is much much faster than atof(), if it
  174699. ** is available */
  174700. double r;
  174701. (void)sqlite3AtoF((const char*)p->z, &r, j, SQLITE_UTF8);
  174702. *pVal = r;
  174703. #else
  174704. *pVal = (GeoCoord)atof((const char*)p->z);
  174705. #endif
  174706. }
  174707. p->z += j;
  174708. return 1;
  174709. }
  174710. /*
  174711. ** If the input is a well-formed JSON array of coordinates with at least
  174712. ** four coordinates and where each coordinate is itself a two-value array,
  174713. ** then convert the JSON into a GeoPoly object and return a pointer to
  174714. ** that object.
  174715. **
  174716. ** If any error occurs, return NULL.
  174717. */
  174718. static GeoPoly *geopolyParseJson(const unsigned char *z, int *pRc){
  174719. GeoParse s;
  174720. int rc = SQLITE_OK;
  174721. memset(&s, 0, sizeof(s));
  174722. s.z = z;
  174723. if( geopolySkipSpace(&s)=='[' ){
  174724. s.z++;
  174725. while( geopolySkipSpace(&s)=='[' ){
  174726. int ii = 0;
  174727. char c;
  174728. s.z++;
  174729. if( s.nVertex>=s.nAlloc ){
  174730. GeoCoord *aNew;
  174731. s.nAlloc = s.nAlloc*2 + 16;
  174732. aNew = sqlite3_realloc64(s.a, s.nAlloc*sizeof(GeoCoord)*2 );
  174733. if( aNew==0 ){
  174734. rc = SQLITE_NOMEM;
  174735. s.nErr++;
  174736. break;
  174737. }
  174738. s.a = aNew;
  174739. }
  174740. while( geopolyParseNumber(&s, ii<=1 ? &s.a[s.nVertex*2+ii] : 0) ){
  174741. ii++;
  174742. if( ii==2 ) s.nVertex++;
  174743. c = geopolySkipSpace(&s);
  174744. s.z++;
  174745. if( c==',' ) continue;
  174746. if( c==']' && ii>=2 ) break;
  174747. s.nErr++;
  174748. rc = SQLITE_ERROR;
  174749. goto parse_json_err;
  174750. }
  174751. if( geopolySkipSpace(&s)==',' ){
  174752. s.z++;
  174753. continue;
  174754. }
  174755. break;
  174756. }
  174757. if( geopolySkipSpace(&s)==']'
  174758. && s.nVertex>=4
  174759. && s.a[0]==s.a[s.nVertex*2-2]
  174760. && s.a[1]==s.a[s.nVertex*2-1]
  174761. && (s.z++, geopolySkipSpace(&s)==0)
  174762. ){
  174763. GeoPoly *pOut;
  174764. int x = 1;
  174765. s.nVertex--; /* Remove the redundant vertex at the end */
  174766. pOut = sqlite3_malloc64( GEOPOLY_SZ((sqlite3_int64)s.nVertex) );
  174767. x = 1;
  174768. if( pOut==0 ) goto parse_json_err;
  174769. pOut->nVertex = s.nVertex;
  174770. memcpy(pOut->a, s.a, s.nVertex*2*sizeof(GeoCoord));
  174771. pOut->hdr[0] = *(unsigned char*)&x;
  174772. pOut->hdr[1] = (s.nVertex>>16)&0xff;
  174773. pOut->hdr[2] = (s.nVertex>>8)&0xff;
  174774. pOut->hdr[3] = s.nVertex&0xff;
  174775. sqlite3_free(s.a);
  174776. if( pRc ) *pRc = SQLITE_OK;
  174777. return pOut;
  174778. }else{
  174779. s.nErr++;
  174780. rc = SQLITE_ERROR;
  174781. }
  174782. }
  174783. parse_json_err:
  174784. if( pRc ) *pRc = rc;
  174785. sqlite3_free(s.a);
  174786. return 0;
  174787. }
  174788. /*
  174789. ** Given a function parameter, try to interpret it as a polygon, either
  174790. ** in the binary format or JSON text. Compute a GeoPoly object and
  174791. ** return a pointer to that object. Or if the input is not a well-formed
  174792. ** polygon, put an error message in sqlite3_context and return NULL.
  174793. */
  174794. static GeoPoly *geopolyFuncParam(
  174795. sqlite3_context *pCtx, /* Context for error messages */
  174796. sqlite3_value *pVal, /* The value to decode */
  174797. int *pRc /* Write error here */
  174798. ){
  174799. GeoPoly *p = 0;
  174800. int nByte;
  174801. if( sqlite3_value_type(pVal)==SQLITE_BLOB
  174802. && (nByte = sqlite3_value_bytes(pVal))>=(4+6*sizeof(GeoCoord))
  174803. ){
  174804. const unsigned char *a = sqlite3_value_blob(pVal);
  174805. int nVertex;
  174806. nVertex = (a[1]<<16) + (a[2]<<8) + a[3];
  174807. if( (a[0]==0 || a[0]==1)
  174808. && (nVertex*2*sizeof(GeoCoord) + 4)==(unsigned int)nByte
  174809. ){
  174810. p = sqlite3_malloc64( sizeof(*p) + (nVertex-1)*2*sizeof(GeoCoord) );
  174811. if( p==0 ){
  174812. if( pRc ) *pRc = SQLITE_NOMEM;
  174813. if( pCtx ) sqlite3_result_error_nomem(pCtx);
  174814. }else{
  174815. int x = 1;
  174816. p->nVertex = nVertex;
  174817. memcpy(p->hdr, a, nByte);
  174818. if( a[0] != *(unsigned char*)&x ){
  174819. int ii;
  174820. for(ii=0; ii<nVertex; ii++){
  174821. geopolySwab32((unsigned char*)&GeoX(p,ii));
  174822. geopolySwab32((unsigned char*)&GeoY(p,ii));
  174823. }
  174824. p->hdr[0] ^= 1;
  174825. }
  174826. }
  174827. }
  174828. if( pRc ) *pRc = SQLITE_OK;
  174829. return p;
  174830. }else if( sqlite3_value_type(pVal)==SQLITE_TEXT ){
  174831. const unsigned char *zJson = sqlite3_value_text(pVal);
  174832. if( zJson==0 ){
  174833. if( pRc ) *pRc = SQLITE_NOMEM;
  174834. return 0;
  174835. }
  174836. return geopolyParseJson(zJson, pRc);
  174837. }else{
  174838. if( pRc ) *pRc = SQLITE_ERROR;
  174839. return 0;
  174840. }
  174841. }
  174842. /*
  174843. ** Implementation of the geopoly_blob(X) function.
  174844. **
  174845. ** If the input is a well-formed Geopoly BLOB or JSON string
  174846. ** then return the BLOB representation of the polygon. Otherwise
  174847. ** return NULL.
  174848. */
  174849. static void geopolyBlobFunc(
  174850. sqlite3_context *context,
  174851. int argc,
  174852. sqlite3_value **argv
  174853. ){
  174854. GeoPoly *p = geopolyFuncParam(context, argv[0], 0);
  174855. if( p ){
  174856. sqlite3_result_blob(context, p->hdr,
  174857. 4+8*p->nVertex, SQLITE_TRANSIENT);
  174858. sqlite3_free(p);
  174859. }
  174860. }
  174861. /*
  174862. ** SQL function: geopoly_json(X)
  174863. **
  174864. ** Interpret X as a polygon and render it as a JSON array
  174865. ** of coordinates. Or, if X is not a valid polygon, return NULL.
  174866. */
  174867. static void geopolyJsonFunc(
  174868. sqlite3_context *context,
  174869. int argc,
  174870. sqlite3_value **argv
  174871. ){
  174872. GeoPoly *p = geopolyFuncParam(context, argv[0], 0);
  174873. if( p ){
  174874. sqlite3 *db = sqlite3_context_db_handle(context);
  174875. sqlite3_str *x = sqlite3_str_new(db);
  174876. int i;
  174877. sqlite3_str_append(x, "[", 1);
  174878. for(i=0; i<p->nVertex; i++){
  174879. sqlite3_str_appendf(x, "[%!g,%!g],", GeoX(p,i), GeoY(p,i));
  174880. }
  174881. sqlite3_str_appendf(x, "[%!g,%!g]]", GeoX(p,0), GeoY(p,0));
  174882. sqlite3_result_text(context, sqlite3_str_finish(x), -1, sqlite3_free);
  174883. sqlite3_free(p);
  174884. }
  174885. }
  174886. /*
  174887. ** SQL function: geopoly_svg(X, ....)
  174888. **
  174889. ** Interpret X as a polygon and render it as a SVG <polyline>.
  174890. ** Additional arguments are added as attributes to the <polyline>.
  174891. */
  174892. static void geopolySvgFunc(
  174893. sqlite3_context *context,
  174894. int argc,
  174895. sqlite3_value **argv
  174896. ){
  174897. GeoPoly *p;
  174898. if( argc<1 ) return;
  174899. p = geopolyFuncParam(context, argv[0], 0);
  174900. if( p ){
  174901. sqlite3 *db = sqlite3_context_db_handle(context);
  174902. sqlite3_str *x = sqlite3_str_new(db);
  174903. int i;
  174904. char cSep = '\'';
  174905. sqlite3_str_appendf(x, "<polyline points=");
  174906. for(i=0; i<p->nVertex; i++){
  174907. sqlite3_str_appendf(x, "%c%g,%g", cSep, GeoX(p,i), GeoY(p,i));
  174908. cSep = ' ';
  174909. }
  174910. sqlite3_str_appendf(x, " %g,%g'", GeoX(p,0), GeoY(p,0));
  174911. for(i=1; i<argc; i++){
  174912. const char *z = (const char*)sqlite3_value_text(argv[i]);
  174913. if( z && z[0] ){
  174914. sqlite3_str_appendf(x, " %s", z);
  174915. }
  174916. }
  174917. sqlite3_str_appendf(x, "></polyline>");
  174918. sqlite3_result_text(context, sqlite3_str_finish(x), -1, sqlite3_free);
  174919. sqlite3_free(p);
  174920. }
  174921. }
  174922. /*
  174923. ** SQL Function: geopoly_xform(poly, A, B, C, D, E, F)
  174924. **
  174925. ** Transform and/or translate a polygon as follows:
  174926. **
  174927. ** x1 = A*x0 + B*y0 + E
  174928. ** y1 = C*x0 + D*y0 + F
  174929. **
  174930. ** For a translation:
  174931. **
  174932. ** geopoly_xform(poly, 1, 0, 0, 1, x-offset, y-offset)
  174933. **
  174934. ** Rotate by R around the point (0,0):
  174935. **
  174936. ** geopoly_xform(poly, cos(R), sin(R), -sin(R), cos(R), 0, 0)
  174937. */
  174938. static void geopolyXformFunc(
  174939. sqlite3_context *context,
  174940. int argc,
  174941. sqlite3_value **argv
  174942. ){
  174943. GeoPoly *p = geopolyFuncParam(context, argv[0], 0);
  174944. double A = sqlite3_value_double(argv[1]);
  174945. double B = sqlite3_value_double(argv[2]);
  174946. double C = sqlite3_value_double(argv[3]);
  174947. double D = sqlite3_value_double(argv[4]);
  174948. double E = sqlite3_value_double(argv[5]);
  174949. double F = sqlite3_value_double(argv[6]);
  174950. GeoCoord x1, y1, x0, y0;
  174951. int ii;
  174952. if( p ){
  174953. for(ii=0; ii<p->nVertex; ii++){
  174954. x0 = GeoX(p,ii);
  174955. y0 = GeoY(p,ii);
  174956. x1 = (GeoCoord)(A*x0 + B*y0 + E);
  174957. y1 = (GeoCoord)(C*x0 + D*y0 + F);
  174958. GeoX(p,ii) = x1;
  174959. GeoY(p,ii) = y1;
  174960. }
  174961. sqlite3_result_blob(context, p->hdr,
  174962. 4+8*p->nVertex, SQLITE_TRANSIENT);
  174963. sqlite3_free(p);
  174964. }
  174965. }
  174966. /*
  174967. ** Compute the area enclosed by the polygon.
  174968. **
  174969. ** This routine can also be used to detect polygons that rotate in
  174970. ** the wrong direction. Polygons are suppose to be counter-clockwise (CCW).
  174971. ** This routine returns a negative value for clockwise (CW) polygons.
  174972. */
  174973. static double geopolyArea(GeoPoly *p){
  174974. double rArea = 0.0;
  174975. int ii;
  174976. for(ii=0; ii<p->nVertex-1; ii++){
  174977. rArea += (GeoX(p,ii) - GeoX(p,ii+1)) /* (x0 - x1) */
  174978. * (GeoY(p,ii) + GeoY(p,ii+1)) /* (y0 + y1) */
  174979. * 0.5;
  174980. }
  174981. rArea += (GeoX(p,ii) - GeoX(p,0)) /* (xN - x0) */
  174982. * (GeoY(p,ii) + GeoY(p,0)) /* (yN + y0) */
  174983. * 0.5;
  174984. return rArea;
  174985. }
  174986. /*
  174987. ** Implementation of the geopoly_area(X) function.
  174988. **
  174989. ** If the input is a well-formed Geopoly BLOB then return the area
  174990. ** enclosed by the polygon. If the polygon circulates clockwise instead
  174991. ** of counterclockwise (as it should) then return the negative of the
  174992. ** enclosed area. Otherwise return NULL.
  174993. */
  174994. static void geopolyAreaFunc(
  174995. sqlite3_context *context,
  174996. int argc,
  174997. sqlite3_value **argv
  174998. ){
  174999. GeoPoly *p = geopolyFuncParam(context, argv[0], 0);
  175000. if( p ){
  175001. sqlite3_result_double(context, geopolyArea(p));
  175002. sqlite3_free(p);
  175003. }
  175004. }
  175005. /*
  175006. ** Implementation of the geopoly_ccw(X) function.
  175007. **
  175008. ** If the rotation of polygon X is clockwise (incorrect) instead of
  175009. ** counter-clockwise (the correct winding order according to RFC7946)
  175010. ** then reverse the order of the vertexes in polygon X.
  175011. **
  175012. ** In other words, this routine returns a CCW polygon regardless of the
  175013. ** winding order of its input.
  175014. **
  175015. ** Use this routine to sanitize historical inputs that that sometimes
  175016. ** contain polygons that wind in the wrong direction.
  175017. */
  175018. static void geopolyCcwFunc(
  175019. sqlite3_context *context,
  175020. int argc,
  175021. sqlite3_value **argv
  175022. ){
  175023. GeoPoly *p = geopolyFuncParam(context, argv[0], 0);
  175024. if( p ){
  175025. if( geopolyArea(p)<0.0 ){
  175026. int ii, jj;
  175027. for(ii=1, jj=p->nVertex-1; ii<jj; ii++, jj--){
  175028. GeoCoord t = GeoX(p,ii);
  175029. GeoX(p,ii) = GeoX(p,jj);
  175030. GeoX(p,jj) = t;
  175031. t = GeoY(p,ii);
  175032. GeoY(p,ii) = GeoY(p,jj);
  175033. GeoY(p,jj) = t;
  175034. }
  175035. }
  175036. sqlite3_result_blob(context, p->hdr,
  175037. 4+8*p->nVertex, SQLITE_TRANSIENT);
  175038. sqlite3_free(p);
  175039. }
  175040. }
  175041. #define GEOPOLY_PI 3.1415926535897932385
  175042. /* Fast approximation for sine(X) for X between -0.5*pi and 2*pi
  175043. */
  175044. static double geopolySine(double r){
  175045. assert( r>=-0.5*GEOPOLY_PI && r<=2.0*GEOPOLY_PI );
  175046. if( r>=1.5*GEOPOLY_PI ){
  175047. r -= 2.0*GEOPOLY_PI;
  175048. }
  175049. if( r>=0.5*GEOPOLY_PI ){
  175050. return -geopolySine(r-GEOPOLY_PI);
  175051. }else{
  175052. double r2 = r*r;
  175053. double r3 = r2*r;
  175054. double r5 = r3*r2;
  175055. return 0.9996949*r - 0.1656700*r3 + 0.0075134*r5;
  175056. }
  175057. }
  175058. /*
  175059. ** Function: geopoly_regular(X,Y,R,N)
  175060. **
  175061. ** Construct a simple, convex, regular polygon centered at X, Y
  175062. ** with circumradius R and with N sides.
  175063. */
  175064. static void geopolyRegularFunc(
  175065. sqlite3_context *context,
  175066. int argc,
  175067. sqlite3_value **argv
  175068. ){
  175069. double x = sqlite3_value_double(argv[0]);
  175070. double y = sqlite3_value_double(argv[1]);
  175071. double r = sqlite3_value_double(argv[2]);
  175072. int n = sqlite3_value_int(argv[3]);
  175073. int i;
  175074. GeoPoly *p;
  175075. if( n<3 || r<=0.0 ) return;
  175076. if( n>1000 ) n = 1000;
  175077. p = sqlite3_malloc64( sizeof(*p) + (n-1)*2*sizeof(GeoCoord) );
  175078. if( p==0 ){
  175079. sqlite3_result_error_nomem(context);
  175080. return;
  175081. }
  175082. i = 1;
  175083. p->hdr[0] = *(unsigned char*)&i;
  175084. p->hdr[1] = 0;
  175085. p->hdr[2] = (n>>8)&0xff;
  175086. p->hdr[3] = n&0xff;
  175087. for(i=0; i<n; i++){
  175088. double rAngle = 2.0*GEOPOLY_PI*i/n;
  175089. GeoX(p,i) = x - r*geopolySine(rAngle-0.5*GEOPOLY_PI);
  175090. GeoY(p,i) = y + r*geopolySine(rAngle);
  175091. }
  175092. sqlite3_result_blob(context, p->hdr, 4+8*n, SQLITE_TRANSIENT);
  175093. sqlite3_free(p);
  175094. }
  175095. /*
  175096. ** If pPoly is a polygon, compute its bounding box. Then:
  175097. **
  175098. ** (1) if aCoord!=0 store the bounding box in aCoord, returning NULL
  175099. ** (2) otherwise, compute a GeoPoly for the bounding box and return the
  175100. ** new GeoPoly
  175101. **
  175102. ** If pPoly is NULL but aCoord is not NULL, then compute a new GeoPoly from
  175103. ** the bounding box in aCoord and return a pointer to that GeoPoly.
  175104. */
  175105. static GeoPoly *geopolyBBox(
  175106. sqlite3_context *context, /* For recording the error */
  175107. sqlite3_value *pPoly, /* The polygon */
  175108. RtreeCoord *aCoord, /* Results here */
  175109. int *pRc /* Error code here */
  175110. ){
  175111. GeoPoly *pOut = 0;
  175112. GeoPoly *p;
  175113. float mnX, mxX, mnY, mxY;
  175114. if( pPoly==0 && aCoord!=0 ){
  175115. p = 0;
  175116. mnX = aCoord[0].f;
  175117. mxX = aCoord[1].f;
  175118. mnY = aCoord[2].f;
  175119. mxY = aCoord[3].f;
  175120. goto geopolyBboxFill;
  175121. }else{
  175122. p = geopolyFuncParam(context, pPoly, pRc);
  175123. }
  175124. if( p ){
  175125. int ii;
  175126. mnX = mxX = GeoX(p,0);
  175127. mnY = mxY = GeoY(p,0);
  175128. for(ii=1; ii<p->nVertex; ii++){
  175129. double r = GeoX(p,ii);
  175130. if( r<mnX ) mnX = (float)r;
  175131. else if( r>mxX ) mxX = (float)r;
  175132. r = GeoY(p,ii);
  175133. if( r<mnY ) mnY = (float)r;
  175134. else if( r>mxY ) mxY = (float)r;
  175135. }
  175136. if( pRc ) *pRc = SQLITE_OK;
  175137. if( aCoord==0 ){
  175138. geopolyBboxFill:
  175139. pOut = sqlite3_realloc64(p, GEOPOLY_SZ(4));
  175140. if( pOut==0 ){
  175141. sqlite3_free(p);
  175142. if( context ) sqlite3_result_error_nomem(context);
  175143. if( pRc ) *pRc = SQLITE_NOMEM;
  175144. return 0;
  175145. }
  175146. pOut->nVertex = 4;
  175147. ii = 1;
  175148. pOut->hdr[0] = *(unsigned char*)&ii;
  175149. pOut->hdr[1] = 0;
  175150. pOut->hdr[2] = 0;
  175151. pOut->hdr[3] = 4;
  175152. GeoX(pOut,0) = mnX;
  175153. GeoY(pOut,0) = mnY;
  175154. GeoX(pOut,1) = mxX;
  175155. GeoY(pOut,1) = mnY;
  175156. GeoX(pOut,2) = mxX;
  175157. GeoY(pOut,2) = mxY;
  175158. GeoX(pOut,3) = mnX;
  175159. GeoY(pOut,3) = mxY;
  175160. }else{
  175161. sqlite3_free(p);
  175162. aCoord[0].f = mnX;
  175163. aCoord[1].f = mxX;
  175164. aCoord[2].f = mnY;
  175165. aCoord[3].f = mxY;
  175166. }
  175167. }
  175168. return pOut;
  175169. }
  175170. /*
  175171. ** Implementation of the geopoly_bbox(X) SQL function.
  175172. */
  175173. static void geopolyBBoxFunc(
  175174. sqlite3_context *context,
  175175. int argc,
  175176. sqlite3_value **argv
  175177. ){
  175178. GeoPoly *p = geopolyBBox(context, argv[0], 0, 0);
  175179. if( p ){
  175180. sqlite3_result_blob(context, p->hdr,
  175181. 4+8*p->nVertex, SQLITE_TRANSIENT);
  175182. sqlite3_free(p);
  175183. }
  175184. }
  175185. /*
  175186. ** State vector for the geopoly_group_bbox() aggregate function.
  175187. */
  175188. typedef struct GeoBBox GeoBBox;
  175189. struct GeoBBox {
  175190. int isInit;
  175191. RtreeCoord a[4];
  175192. };
  175193. /*
  175194. ** Implementation of the geopoly_group_bbox(X) aggregate SQL function.
  175195. */
  175196. static void geopolyBBoxStep(
  175197. sqlite3_context *context,
  175198. int argc,
  175199. sqlite3_value **argv
  175200. ){
  175201. RtreeCoord a[4];
  175202. int rc = SQLITE_OK;
  175203. (void)geopolyBBox(context, argv[0], a, &rc);
  175204. if( rc==SQLITE_OK ){
  175205. GeoBBox *pBBox;
  175206. pBBox = (GeoBBox*)sqlite3_aggregate_context(context, sizeof(*pBBox));
  175207. if( pBBox==0 ) return;
  175208. if( pBBox->isInit==0 ){
  175209. pBBox->isInit = 1;
  175210. memcpy(pBBox->a, a, sizeof(RtreeCoord)*4);
  175211. }else{
  175212. if( a[0].f < pBBox->a[0].f ) pBBox->a[0] = a[0];
  175213. if( a[1].f > pBBox->a[1].f ) pBBox->a[1] = a[1];
  175214. if( a[2].f < pBBox->a[2].f ) pBBox->a[2] = a[2];
  175215. if( a[3].f > pBBox->a[3].f ) pBBox->a[3] = a[3];
  175216. }
  175217. }
  175218. }
  175219. static void geopolyBBoxFinal(
  175220. sqlite3_context *context
  175221. ){
  175222. GeoPoly *p;
  175223. GeoBBox *pBBox;
  175224. pBBox = (GeoBBox*)sqlite3_aggregate_context(context, 0);
  175225. if( pBBox==0 ) return;
  175226. p = geopolyBBox(context, 0, pBBox->a, 0);
  175227. if( p ){
  175228. sqlite3_result_blob(context, p->hdr,
  175229. 4+8*p->nVertex, SQLITE_TRANSIENT);
  175230. sqlite3_free(p);
  175231. }
  175232. }
  175233. /*
  175234. ** Determine if point (x0,y0) is beneath line segment (x1,y1)->(x2,y2).
  175235. ** Returns:
  175236. **
  175237. ** +2 x0,y0 is on the line segement
  175238. **
  175239. ** +1 x0,y0 is beneath line segment
  175240. **
  175241. ** 0 x0,y0 is not on or beneath the line segment or the line segment
  175242. ** is vertical and x0,y0 is not on the line segment
  175243. **
  175244. ** The left-most coordinate min(x1,x2) is not considered to be part of
  175245. ** the line segment for the purposes of this analysis.
  175246. */
  175247. static int pointBeneathLine(
  175248. double x0, double y0,
  175249. double x1, double y1,
  175250. double x2, double y2
  175251. ){
  175252. double y;
  175253. if( x0==x1 && y0==y1 ) return 2;
  175254. if( x1<x2 ){
  175255. if( x0<=x1 || x0>x2 ) return 0;
  175256. }else if( x1>x2 ){
  175257. if( x0<=x2 || x0>x1 ) return 0;
  175258. }else{
  175259. /* Vertical line segment */
  175260. if( x0!=x1 ) return 0;
  175261. if( y0<y1 && y0<y2 ) return 0;
  175262. if( y0>y1 && y0>y2 ) return 0;
  175263. return 2;
  175264. }
  175265. y = y1 + (y2-y1)*(x0-x1)/(x2-x1);
  175266. if( y0==y ) return 2;
  175267. if( y0<y ) return 1;
  175268. return 0;
  175269. }
  175270. /*
  175271. ** SQL function: geopoly_contains_point(P,X,Y)
  175272. **
  175273. ** Return +2 if point X,Y is within polygon P.
  175274. ** Return +1 if point X,Y is on the polygon boundary.
  175275. ** Return 0 if point X,Y is outside the polygon
  175276. */
  175277. static void geopolyContainsPointFunc(
  175278. sqlite3_context *context,
  175279. int argc,
  175280. sqlite3_value **argv
  175281. ){
  175282. GeoPoly *p1 = geopolyFuncParam(context, argv[0], 0);
  175283. double x0 = sqlite3_value_double(argv[1]);
  175284. double y0 = sqlite3_value_double(argv[2]);
  175285. int v = 0;
  175286. int cnt = 0;
  175287. int ii;
  175288. if( p1==0 ) return;
  175289. for(ii=0; ii<p1->nVertex-1; ii++){
  175290. v = pointBeneathLine(x0,y0,GeoX(p1,ii), GeoY(p1,ii),
  175291. GeoX(p1,ii+1),GeoY(p1,ii+1));
  175292. if( v==2 ) break;
  175293. cnt += v;
  175294. }
  175295. if( v!=2 ){
  175296. v = pointBeneathLine(x0,y0,GeoX(p1,ii), GeoY(p1,ii),
  175297. GeoX(p1,0), GeoY(p1,0));
  175298. }
  175299. if( v==2 ){
  175300. sqlite3_result_int(context, 1);
  175301. }else if( ((v+cnt)&1)==0 ){
  175302. sqlite3_result_int(context, 0);
  175303. }else{
  175304. sqlite3_result_int(context, 2);
  175305. }
  175306. sqlite3_free(p1);
  175307. }
  175308. /* Forward declaration */
  175309. static int geopolyOverlap(GeoPoly *p1, GeoPoly *p2);
  175310. /*
  175311. ** SQL function: geopoly_within(P1,P2)
  175312. **
  175313. ** Return +2 if P1 and P2 are the same polygon
  175314. ** Return +1 if P2 is contained within P1
  175315. ** Return 0 if any part of P2 is on the outside of P1
  175316. **
  175317. */
  175318. static void geopolyWithinFunc(
  175319. sqlite3_context *context,
  175320. int argc,
  175321. sqlite3_value **argv
  175322. ){
  175323. GeoPoly *p1 = geopolyFuncParam(context, argv[0], 0);
  175324. GeoPoly *p2 = geopolyFuncParam(context, argv[1], 0);
  175325. if( p1 && p2 ){
  175326. int x = geopolyOverlap(p1, p2);
  175327. if( x<0 ){
  175328. sqlite3_result_error_nomem(context);
  175329. }else{
  175330. sqlite3_result_int(context, x==2 ? 1 : x==4 ? 2 : 0);
  175331. }
  175332. }
  175333. sqlite3_free(p1);
  175334. sqlite3_free(p2);
  175335. }
  175336. /* Objects used by the overlap algorihm. */
  175337. typedef struct GeoEvent GeoEvent;
  175338. typedef struct GeoSegment GeoSegment;
  175339. typedef struct GeoOverlap GeoOverlap;
  175340. struct GeoEvent {
  175341. double x; /* X coordinate at which event occurs */
  175342. int eType; /* 0 for ADD, 1 for REMOVE */
  175343. GeoSegment *pSeg; /* The segment to be added or removed */
  175344. GeoEvent *pNext; /* Next event in the sorted list */
  175345. };
  175346. struct GeoSegment {
  175347. double C, B; /* y = C*x + B */
  175348. double y; /* Current y value */
  175349. float y0; /* Initial y value */
  175350. unsigned char side; /* 1 for p1, 2 for p2 */
  175351. unsigned int idx; /* Which segment within the side */
  175352. GeoSegment *pNext; /* Next segment in a list sorted by y */
  175353. };
  175354. struct GeoOverlap {
  175355. GeoEvent *aEvent; /* Array of all events */
  175356. GeoSegment *aSegment; /* Array of all segments */
  175357. int nEvent; /* Number of events */
  175358. int nSegment; /* Number of segments */
  175359. };
  175360. /*
  175361. ** Add a single segment and its associated events.
  175362. */
  175363. static void geopolyAddOneSegment(
  175364. GeoOverlap *p,
  175365. GeoCoord x0,
  175366. GeoCoord y0,
  175367. GeoCoord x1,
  175368. GeoCoord y1,
  175369. unsigned char side,
  175370. unsigned int idx
  175371. ){
  175372. GeoSegment *pSeg;
  175373. GeoEvent *pEvent;
  175374. if( x0==x1 ) return; /* Ignore vertical segments */
  175375. if( x0>x1 ){
  175376. GeoCoord t = x0;
  175377. x0 = x1;
  175378. x1 = t;
  175379. t = y0;
  175380. y0 = y1;
  175381. y1 = t;
  175382. }
  175383. pSeg = p->aSegment + p->nSegment;
  175384. p->nSegment++;
  175385. pSeg->C = (y1-y0)/(x1-x0);
  175386. pSeg->B = y1 - x1*pSeg->C;
  175387. pSeg->y0 = y0;
  175388. pSeg->side = side;
  175389. pSeg->idx = idx;
  175390. pEvent = p->aEvent + p->nEvent;
  175391. p->nEvent++;
  175392. pEvent->x = x0;
  175393. pEvent->eType = 0;
  175394. pEvent->pSeg = pSeg;
  175395. pEvent = p->aEvent + p->nEvent;
  175396. p->nEvent++;
  175397. pEvent->x = x1;
  175398. pEvent->eType = 1;
  175399. pEvent->pSeg = pSeg;
  175400. }
  175401. /*
  175402. ** Insert all segments and events for polygon pPoly.
  175403. */
  175404. static void geopolyAddSegments(
  175405. GeoOverlap *p, /* Add segments to this Overlap object */
  175406. GeoPoly *pPoly, /* Take all segments from this polygon */
  175407. unsigned char side /* The side of pPoly */
  175408. ){
  175409. unsigned int i;
  175410. GeoCoord *x;
  175411. for(i=0; i<(unsigned)pPoly->nVertex-1; i++){
  175412. x = &GeoX(pPoly,i);
  175413. geopolyAddOneSegment(p, x[0], x[1], x[2], x[3], side, i);
  175414. }
  175415. x = &GeoX(pPoly,i);
  175416. geopolyAddOneSegment(p, x[0], x[1], pPoly->a[0], pPoly->a[1], side, i);
  175417. }
  175418. /*
  175419. ** Merge two lists of sorted events by X coordinate
  175420. */
  175421. static GeoEvent *geopolyEventMerge(GeoEvent *pLeft, GeoEvent *pRight){
  175422. GeoEvent head, *pLast;
  175423. head.pNext = 0;
  175424. pLast = &head;
  175425. while( pRight && pLeft ){
  175426. if( pRight->x <= pLeft->x ){
  175427. pLast->pNext = pRight;
  175428. pLast = pRight;
  175429. pRight = pRight->pNext;
  175430. }else{
  175431. pLast->pNext = pLeft;
  175432. pLast = pLeft;
  175433. pLeft = pLeft->pNext;
  175434. }
  175435. }
  175436. pLast->pNext = pRight ? pRight : pLeft;
  175437. return head.pNext;
  175438. }
  175439. /*
  175440. ** Sort an array of nEvent event objects into a list.
  175441. */
  175442. static GeoEvent *geopolySortEventsByX(GeoEvent *aEvent, int nEvent){
  175443. int mx = 0;
  175444. int i, j;
  175445. GeoEvent *p;
  175446. GeoEvent *a[50];
  175447. for(i=0; i<nEvent; i++){
  175448. p = &aEvent[i];
  175449. p->pNext = 0;
  175450. for(j=0; j<mx && a[j]; j++){
  175451. p = geopolyEventMerge(a[j], p);
  175452. a[j] = 0;
  175453. }
  175454. a[j] = p;
  175455. if( j>=mx ) mx = j+1;
  175456. }
  175457. p = 0;
  175458. for(i=0; i<mx; i++){
  175459. p = geopolyEventMerge(a[i], p);
  175460. }
  175461. return p;
  175462. }
  175463. /*
  175464. ** Merge two lists of sorted segments by Y, and then by C.
  175465. */
  175466. static GeoSegment *geopolySegmentMerge(GeoSegment *pLeft, GeoSegment *pRight){
  175467. GeoSegment head, *pLast;
  175468. head.pNext = 0;
  175469. pLast = &head;
  175470. while( pRight && pLeft ){
  175471. double r = pRight->y - pLeft->y;
  175472. if( r==0.0 ) r = pRight->C - pLeft->C;
  175473. if( r<0.0 ){
  175474. pLast->pNext = pRight;
  175475. pLast = pRight;
  175476. pRight = pRight->pNext;
  175477. }else{
  175478. pLast->pNext = pLeft;
  175479. pLast = pLeft;
  175480. pLeft = pLeft->pNext;
  175481. }
  175482. }
  175483. pLast->pNext = pRight ? pRight : pLeft;
  175484. return head.pNext;
  175485. }
  175486. /*
  175487. ** Sort a list of GeoSegments in order of increasing Y and in the event of
  175488. ** a tie, increasing C (slope).
  175489. */
  175490. static GeoSegment *geopolySortSegmentsByYAndC(GeoSegment *pList){
  175491. int mx = 0;
  175492. int i;
  175493. GeoSegment *p;
  175494. GeoSegment *a[50];
  175495. while( pList ){
  175496. p = pList;
  175497. pList = pList->pNext;
  175498. p->pNext = 0;
  175499. for(i=0; i<mx && a[i]; i++){
  175500. p = geopolySegmentMerge(a[i], p);
  175501. a[i] = 0;
  175502. }
  175503. a[i] = p;
  175504. if( i>=mx ) mx = i+1;
  175505. }
  175506. p = 0;
  175507. for(i=0; i<mx; i++){
  175508. p = geopolySegmentMerge(a[i], p);
  175509. }
  175510. return p;
  175511. }
  175512. /*
  175513. ** Determine the overlap between two polygons
  175514. */
  175515. static int geopolyOverlap(GeoPoly *p1, GeoPoly *p2){
  175516. sqlite3_int64 nVertex = p1->nVertex + p2->nVertex + 2;
  175517. GeoOverlap *p;
  175518. sqlite3_int64 nByte;
  175519. GeoEvent *pThisEvent;
  175520. double rX;
  175521. int rc = 0;
  175522. int needSort = 0;
  175523. GeoSegment *pActive = 0;
  175524. GeoSegment *pSeg;
  175525. unsigned char aOverlap[4];
  175526. nByte = sizeof(GeoEvent)*nVertex*2
  175527. + sizeof(GeoSegment)*nVertex
  175528. + sizeof(GeoOverlap);
  175529. p = sqlite3_malloc64( nByte );
  175530. if( p==0 ) return -1;
  175531. p->aEvent = (GeoEvent*)&p[1];
  175532. p->aSegment = (GeoSegment*)&p->aEvent[nVertex*2];
  175533. p->nEvent = p->nSegment = 0;
  175534. geopolyAddSegments(p, p1, 1);
  175535. geopolyAddSegments(p, p2, 2);
  175536. pThisEvent = geopolySortEventsByX(p->aEvent, p->nEvent);
  175537. rX = pThisEvent->x==0.0 ? -1.0 : 0.0;
  175538. memset(aOverlap, 0, sizeof(aOverlap));
  175539. while( pThisEvent ){
  175540. if( pThisEvent->x!=rX ){
  175541. GeoSegment *pPrev = 0;
  175542. int iMask = 0;
  175543. GEODEBUG(("Distinct X: %g\n", pThisEvent->x));
  175544. rX = pThisEvent->x;
  175545. if( needSort ){
  175546. GEODEBUG(("SORT\n"));
  175547. pActive = geopolySortSegmentsByYAndC(pActive);
  175548. needSort = 0;
  175549. }
  175550. for(pSeg=pActive; pSeg; pSeg=pSeg->pNext){
  175551. if( pPrev ){
  175552. if( pPrev->y!=pSeg->y ){
  175553. GEODEBUG(("MASK: %d\n", iMask));
  175554. aOverlap[iMask] = 1;
  175555. }
  175556. }
  175557. iMask ^= pSeg->side;
  175558. pPrev = pSeg;
  175559. }
  175560. pPrev = 0;
  175561. for(pSeg=pActive; pSeg; pSeg=pSeg->pNext){
  175562. double y = pSeg->C*rX + pSeg->B;
  175563. GEODEBUG(("Segment %d.%d %g->%g\n", pSeg->side, pSeg->idx, pSeg->y, y));
  175564. pSeg->y = y;
  175565. if( pPrev ){
  175566. if( pPrev->y>pSeg->y && pPrev->side!=pSeg->side ){
  175567. rc = 1;
  175568. GEODEBUG(("Crossing: %d.%d and %d.%d\n",
  175569. pPrev->side, pPrev->idx,
  175570. pSeg->side, pSeg->idx));
  175571. goto geopolyOverlapDone;
  175572. }else if( pPrev->y!=pSeg->y ){
  175573. GEODEBUG(("MASK: %d\n", iMask));
  175574. aOverlap[iMask] = 1;
  175575. }
  175576. }
  175577. iMask ^= pSeg->side;
  175578. pPrev = pSeg;
  175579. }
  175580. }
  175581. GEODEBUG(("%s %d.%d C=%g B=%g\n",
  175582. pThisEvent->eType ? "RM " : "ADD",
  175583. pThisEvent->pSeg->side, pThisEvent->pSeg->idx,
  175584. pThisEvent->pSeg->C,
  175585. pThisEvent->pSeg->B));
  175586. if( pThisEvent->eType==0 ){
  175587. /* Add a segment */
  175588. pSeg = pThisEvent->pSeg;
  175589. pSeg->y = pSeg->y0;
  175590. pSeg->pNext = pActive;
  175591. pActive = pSeg;
  175592. needSort = 1;
  175593. }else{
  175594. /* Remove a segment */
  175595. if( pActive==pThisEvent->pSeg ){
  175596. pActive = pActive->pNext;
  175597. }else{
  175598. for(pSeg=pActive; pSeg; pSeg=pSeg->pNext){
  175599. if( pSeg->pNext==pThisEvent->pSeg ){
  175600. pSeg->pNext = pSeg->pNext->pNext;
  175601. break;
  175602. }
  175603. }
  175604. }
  175605. }
  175606. pThisEvent = pThisEvent->pNext;
  175607. }
  175608. if( aOverlap[3]==0 ){
  175609. rc = 0;
  175610. }else if( aOverlap[1]!=0 && aOverlap[2]==0 ){
  175611. rc = 3;
  175612. }else if( aOverlap[1]==0 && aOverlap[2]!=0 ){
  175613. rc = 2;
  175614. }else if( aOverlap[1]==0 && aOverlap[2]==0 ){
  175615. rc = 4;
  175616. }else{
  175617. rc = 1;
  175618. }
  175619. geopolyOverlapDone:
  175620. sqlite3_free(p);
  175621. return rc;
  175622. }
  175623. /*
  175624. ** SQL function: geopoly_overlap(P1,P2)
  175625. **
  175626. ** Determine whether or not P1 and P2 overlap. Return value:
  175627. **
  175628. ** 0 The two polygons are disjoint
  175629. ** 1 They overlap
  175630. ** 2 P1 is completely contained within P2
  175631. ** 3 P2 is completely contained within P1
  175632. ** 4 P1 and P2 are the same polygon
  175633. ** NULL Either P1 or P2 or both are not valid polygons
  175634. */
  175635. static void geopolyOverlapFunc(
  175636. sqlite3_context *context,
  175637. int argc,
  175638. sqlite3_value **argv
  175639. ){
  175640. GeoPoly *p1 = geopolyFuncParam(context, argv[0], 0);
  175641. GeoPoly *p2 = geopolyFuncParam(context, argv[1], 0);
  175642. if( p1 && p2 ){
  175643. int x = geopolyOverlap(p1, p2);
  175644. if( x<0 ){
  175645. sqlite3_result_error_nomem(context);
  175646. }else{
  175647. sqlite3_result_int(context, x);
  175648. }
  175649. }
  175650. sqlite3_free(p1);
  175651. sqlite3_free(p2);
  175652. }
  175653. /*
  175654. ** Enable or disable debugging output
  175655. */
  175656. static void geopolyDebugFunc(
  175657. sqlite3_context *context,
  175658. int argc,
  175659. sqlite3_value **argv
  175660. ){
  175661. #ifdef GEOPOLY_ENABLE_DEBUG
  175662. geo_debug = sqlite3_value_int(argv[0]);
  175663. #endif
  175664. }
  175665. /*
  175666. ** This function is the implementation of both the xConnect and xCreate
  175667. ** methods of the geopoly virtual table.
  175668. **
  175669. ** argv[0] -> module name
  175670. ** argv[1] -> database name
  175671. ** argv[2] -> table name
  175672. ** argv[...] -> column names...
  175673. */
  175674. static int geopolyInit(
  175675. sqlite3 *db, /* Database connection */
  175676. void *pAux, /* One of the RTREE_COORD_* constants */
  175677. int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */
  175678. sqlite3_vtab **ppVtab, /* OUT: New virtual table */
  175679. char **pzErr, /* OUT: Error message, if any */
  175680. int isCreate /* True for xCreate, false for xConnect */
  175681. ){
  175682. int rc = SQLITE_OK;
  175683. Rtree *pRtree;
  175684. sqlite3_int64 nDb; /* Length of string argv[1] */
  175685. sqlite3_int64 nName; /* Length of string argv[2] */
  175686. sqlite3_str *pSql;
  175687. char *zSql;
  175688. int ii;
  175689. sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
  175690. /* Allocate the sqlite3_vtab structure */
  175691. nDb = strlen(argv[1]);
  175692. nName = strlen(argv[2]);
  175693. pRtree = (Rtree *)sqlite3_malloc64(sizeof(Rtree)+nDb+nName+2);
  175694. if( !pRtree ){
  175695. return SQLITE_NOMEM;
  175696. }
  175697. memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
  175698. pRtree->nBusy = 1;
  175699. pRtree->base.pModule = &rtreeModule;
  175700. pRtree->zDb = (char *)&pRtree[1];
  175701. pRtree->zName = &pRtree->zDb[nDb+1];
  175702. pRtree->eCoordType = RTREE_COORD_REAL32;
  175703. pRtree->nDim = 2;
  175704. pRtree->nDim2 = 4;
  175705. memcpy(pRtree->zDb, argv[1], nDb);
  175706. memcpy(pRtree->zName, argv[2], nName);
  175707. /* Create/Connect to the underlying relational database schema. If
  175708. ** that is successful, call sqlite3_declare_vtab() to configure
  175709. ** the r-tree table schema.
  175710. */
  175711. pSql = sqlite3_str_new(db);
  175712. sqlite3_str_appendf(pSql, "CREATE TABLE x(_shape");
  175713. pRtree->nAux = 1; /* Add one for _shape */
  175714. pRtree->nAuxNotNull = 1; /* The _shape column is always not-null */
  175715. for(ii=3; ii<argc; ii++){
  175716. pRtree->nAux++;
  175717. sqlite3_str_appendf(pSql, ",%s", argv[ii]);
  175718. }
  175719. sqlite3_str_appendf(pSql, ");");
  175720. zSql = sqlite3_str_finish(pSql);
  175721. if( !zSql ){
  175722. rc = SQLITE_NOMEM;
  175723. }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
  175724. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  175725. }
  175726. sqlite3_free(zSql);
  175727. if( rc ) goto geopolyInit_fail;
  175728. pRtree->nBytesPerCell = 8 + pRtree->nDim2*4;
  175729. /* Figure out the node size to use. */
  175730. rc = getNodeSize(db, pRtree, isCreate, pzErr);
  175731. if( rc ) goto geopolyInit_fail;
  175732. rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate);
  175733. if( rc ){
  175734. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  175735. goto geopolyInit_fail;
  175736. }
  175737. *ppVtab = (sqlite3_vtab *)pRtree;
  175738. return SQLITE_OK;
  175739. geopolyInit_fail:
  175740. if( rc==SQLITE_OK ) rc = SQLITE_ERROR;
  175741. assert( *ppVtab==0 );
  175742. assert( pRtree->nBusy==1 );
  175743. rtreeRelease(pRtree);
  175744. return rc;
  175745. }
  175746. /*
  175747. ** GEOPOLY virtual table module xCreate method.
  175748. */
  175749. static int geopolyCreate(
  175750. sqlite3 *db,
  175751. void *pAux,
  175752. int argc, const char *const*argv,
  175753. sqlite3_vtab **ppVtab,
  175754. char **pzErr
  175755. ){
  175756. return geopolyInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
  175757. }
  175758. /*
  175759. ** GEOPOLY virtual table module xConnect method.
  175760. */
  175761. static int geopolyConnect(
  175762. sqlite3 *db,
  175763. void *pAux,
  175764. int argc, const char *const*argv,
  175765. sqlite3_vtab **ppVtab,
  175766. char **pzErr
  175767. ){
  175768. return geopolyInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
  175769. }
  175770. /*
  175771. ** GEOPOLY virtual table module xFilter method.
  175772. **
  175773. ** Query plans:
  175774. **
  175775. ** 1 rowid lookup
  175776. ** 2 search for objects overlapping the same bounding box
  175777. ** that contains polygon argv[0]
  175778. ** 3 search for objects overlapping the same bounding box
  175779. ** that contains polygon argv[0]
  175780. ** 4 full table scan
  175781. */
  175782. static int geopolyFilter(
  175783. sqlite3_vtab_cursor *pVtabCursor, /* The cursor to initialize */
  175784. int idxNum, /* Query plan */
  175785. const char *idxStr, /* Not Used */
  175786. int argc, sqlite3_value **argv /* Parameters to the query plan */
  175787. ){
  175788. Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
  175789. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  175790. RtreeNode *pRoot = 0;
  175791. int rc = SQLITE_OK;
  175792. int iCell = 0;
  175793. sqlite3_stmt *pStmt;
  175794. rtreeReference(pRtree);
  175795. /* Reset the cursor to the same state as rtreeOpen() leaves it in. */
  175796. freeCursorConstraints(pCsr);
  175797. sqlite3_free(pCsr->aPoint);
  175798. pStmt = pCsr->pReadAux;
  175799. memset(pCsr, 0, sizeof(RtreeCursor));
  175800. pCsr->base.pVtab = (sqlite3_vtab*)pRtree;
  175801. pCsr->pReadAux = pStmt;
  175802. pCsr->iStrategy = idxNum;
  175803. if( idxNum==1 ){
  175804. /* Special case - lookup by rowid. */
  175805. RtreeNode *pLeaf; /* Leaf on which the required cell resides */
  175806. RtreeSearchPoint *p; /* Search point for the leaf */
  175807. i64 iRowid = sqlite3_value_int64(argv[0]);
  175808. i64 iNode = 0;
  175809. rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode);
  175810. if( rc==SQLITE_OK && pLeaf!=0 ){
  175811. p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0);
  175812. assert( p!=0 ); /* Always returns pCsr->sPoint */
  175813. pCsr->aNode[0] = pLeaf;
  175814. p->id = iNode;
  175815. p->eWithin = PARTLY_WITHIN;
  175816. rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &iCell);
  175817. p->iCell = (u8)iCell;
  175818. RTREE_QUEUE_TRACE(pCsr, "PUSH-F1:");
  175819. }else{
  175820. pCsr->atEOF = 1;
  175821. }
  175822. }else{
  175823. /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
  175824. ** with the configured constraints.
  175825. */
  175826. rc = nodeAcquire(pRtree, 1, 0, &pRoot);
  175827. if( rc==SQLITE_OK && idxNum<=3 ){
  175828. RtreeCoord bbox[4];
  175829. RtreeConstraint *p;
  175830. assert( argc==1 );
  175831. geopolyBBox(0, argv[0], bbox, &rc);
  175832. if( rc ){
  175833. goto geopoly_filter_end;
  175834. }
  175835. pCsr->aConstraint = p = sqlite3_malloc(sizeof(RtreeConstraint)*4);
  175836. pCsr->nConstraint = 4;
  175837. if( p==0 ){
  175838. rc = SQLITE_NOMEM;
  175839. }else{
  175840. memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*4);
  175841. memset(pCsr->anQueue, 0, sizeof(u32)*(pRtree->iDepth + 1));
  175842. if( idxNum==2 ){
  175843. /* Overlap query */
  175844. p->op = 'B';
  175845. p->iCoord = 0;
  175846. p->u.rValue = bbox[1].f;
  175847. p++;
  175848. p->op = 'D';
  175849. p->iCoord = 1;
  175850. p->u.rValue = bbox[0].f;
  175851. p++;
  175852. p->op = 'B';
  175853. p->iCoord = 2;
  175854. p->u.rValue = bbox[3].f;
  175855. p++;
  175856. p->op = 'D';
  175857. p->iCoord = 3;
  175858. p->u.rValue = bbox[2].f;
  175859. }else{
  175860. /* Within query */
  175861. p->op = 'D';
  175862. p->iCoord = 0;
  175863. p->u.rValue = bbox[0].f;
  175864. p++;
  175865. p->op = 'B';
  175866. p->iCoord = 1;
  175867. p->u.rValue = bbox[1].f;
  175868. p++;
  175869. p->op = 'D';
  175870. p->iCoord = 2;
  175871. p->u.rValue = bbox[2].f;
  175872. p++;
  175873. p->op = 'B';
  175874. p->iCoord = 3;
  175875. p->u.rValue = bbox[3].f;
  175876. }
  175877. }
  175878. }
  175879. if( rc==SQLITE_OK ){
  175880. RtreeSearchPoint *pNew;
  175881. pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, (u8)(pRtree->iDepth+1));
  175882. if( pNew==0 ){
  175883. rc = SQLITE_NOMEM;
  175884. goto geopoly_filter_end;
  175885. }
  175886. pNew->id = 1;
  175887. pNew->iCell = 0;
  175888. pNew->eWithin = PARTLY_WITHIN;
  175889. assert( pCsr->bPoint==1 );
  175890. pCsr->aNode[0] = pRoot;
  175891. pRoot = 0;
  175892. RTREE_QUEUE_TRACE(pCsr, "PUSH-Fm:");
  175893. rc = rtreeStepToLeaf(pCsr);
  175894. }
  175895. }
  175896. geopoly_filter_end:
  175897. nodeRelease(pRtree, pRoot);
  175898. rtreeRelease(pRtree);
  175899. return rc;
  175900. }
  175901. /*
  175902. ** Rtree virtual table module xBestIndex method. There are three
  175903. ** table scan strategies to choose from (in order from most to
  175904. ** least desirable):
  175905. **
  175906. ** idxNum idxStr Strategy
  175907. ** ------------------------------------------------
  175908. ** 1 "rowid" Direct lookup by rowid.
  175909. ** 2 "rtree" R-tree overlap query using geopoly_overlap()
  175910. ** 3 "rtree" R-tree within query using geopoly_within()
  175911. ** 4 "fullscan" full-table scan.
  175912. ** ------------------------------------------------
  175913. */
  175914. static int geopolyBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  175915. int ii;
  175916. int iRowidTerm = -1;
  175917. int iFuncTerm = -1;
  175918. int idxNum = 0;
  175919. for(ii=0; ii<pIdxInfo->nConstraint; ii++){
  175920. struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
  175921. if( !p->usable ) continue;
  175922. if( p->iColumn<0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
  175923. iRowidTerm = ii;
  175924. break;
  175925. }
  175926. if( p->iColumn==0 && p->op>=SQLITE_INDEX_CONSTRAINT_FUNCTION ){
  175927. /* p->op==SQLITE_INDEX_CONSTRAINT_FUNCTION for geopoly_overlap()
  175928. ** p->op==(SQLITE_INDEX_CONTRAINT_FUNCTION+1) for geopoly_within().
  175929. ** See geopolyFindFunction() */
  175930. iFuncTerm = ii;
  175931. idxNum = p->op - SQLITE_INDEX_CONSTRAINT_FUNCTION + 2;
  175932. }
  175933. }
  175934. if( iRowidTerm>=0 ){
  175935. pIdxInfo->idxNum = 1;
  175936. pIdxInfo->idxStr = "rowid";
  175937. pIdxInfo->aConstraintUsage[iRowidTerm].argvIndex = 1;
  175938. pIdxInfo->aConstraintUsage[iRowidTerm].omit = 1;
  175939. pIdxInfo->estimatedCost = 30.0;
  175940. pIdxInfo->estimatedRows = 1;
  175941. pIdxInfo->idxFlags = SQLITE_INDEX_SCAN_UNIQUE;
  175942. return SQLITE_OK;
  175943. }
  175944. if( iFuncTerm>=0 ){
  175945. pIdxInfo->idxNum = idxNum;
  175946. pIdxInfo->idxStr = "rtree";
  175947. pIdxInfo->aConstraintUsage[iFuncTerm].argvIndex = 1;
  175948. pIdxInfo->aConstraintUsage[iFuncTerm].omit = 0;
  175949. pIdxInfo->estimatedCost = 300.0;
  175950. pIdxInfo->estimatedRows = 10;
  175951. return SQLITE_OK;
  175952. }
  175953. pIdxInfo->idxNum = 4;
  175954. pIdxInfo->idxStr = "fullscan";
  175955. pIdxInfo->estimatedCost = 3000000.0;
  175956. pIdxInfo->estimatedRows = 100000;
  175957. return SQLITE_OK;
  175958. }
  175959. /*
  175960. ** GEOPOLY virtual table module xColumn method.
  175961. */
  175962. static int geopolyColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
  175963. Rtree *pRtree = (Rtree *)cur->pVtab;
  175964. RtreeCursor *pCsr = (RtreeCursor *)cur;
  175965. RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
  175966. int rc = SQLITE_OK;
  175967. RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
  175968. if( rc ) return rc;
  175969. if( p==0 ) return SQLITE_OK;
  175970. if( i==0 && sqlite3_vtab_nochange(ctx) ) return SQLITE_OK;
  175971. if( i<=pRtree->nAux ){
  175972. if( !pCsr->bAuxValid ){
  175973. if( pCsr->pReadAux==0 ){
  175974. rc = sqlite3_prepare_v3(pRtree->db, pRtree->zReadAuxSql, -1, 0,
  175975. &pCsr->pReadAux, 0);
  175976. if( rc ) return rc;
  175977. }
  175978. sqlite3_bind_int64(pCsr->pReadAux, 1,
  175979. nodeGetRowid(pRtree, pNode, p->iCell));
  175980. rc = sqlite3_step(pCsr->pReadAux);
  175981. if( rc==SQLITE_ROW ){
  175982. pCsr->bAuxValid = 1;
  175983. }else{
  175984. sqlite3_reset(pCsr->pReadAux);
  175985. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  175986. return rc;
  175987. }
  175988. }
  175989. sqlite3_result_value(ctx, sqlite3_column_value(pCsr->pReadAux, i+2));
  175990. }
  175991. return SQLITE_OK;
  175992. }
  175993. /*
  175994. ** The xUpdate method for GEOPOLY module virtual tables.
  175995. **
  175996. ** For DELETE:
  175997. **
  175998. ** argv[0] = the rowid to be deleted
  175999. **
  176000. ** For INSERT:
  176001. **
  176002. ** argv[0] = SQL NULL
  176003. ** argv[1] = rowid to insert, or an SQL NULL to select automatically
  176004. ** argv[2] = _shape column
  176005. ** argv[3] = first application-defined column....
  176006. **
  176007. ** For UPDATE:
  176008. **
  176009. ** argv[0] = rowid to modify. Never NULL
  176010. ** argv[1] = rowid after the change. Never NULL
  176011. ** argv[2] = new value for _shape
  176012. ** argv[3] = new value for first application-defined column....
  176013. */
  176014. static int geopolyUpdate(
  176015. sqlite3_vtab *pVtab,
  176016. int nData,
  176017. sqlite3_value **aData,
  176018. sqlite_int64 *pRowid
  176019. ){
  176020. Rtree *pRtree = (Rtree *)pVtab;
  176021. int rc = SQLITE_OK;
  176022. RtreeCell cell; /* New cell to insert if nData>1 */
  176023. i64 oldRowid; /* The old rowid */
  176024. int oldRowidValid; /* True if oldRowid is valid */
  176025. i64 newRowid; /* The new rowid */
  176026. int newRowidValid; /* True if newRowid is valid */
  176027. int coordChange = 0; /* Change in coordinates */
  176028. if( pRtree->nNodeRef ){
  176029. /* Unable to write to the btree while another cursor is reading from it,
  176030. ** since the write might do a rebalance which would disrupt the read
  176031. ** cursor. */
  176032. return SQLITE_LOCKED_VTAB;
  176033. }
  176034. rtreeReference(pRtree);
  176035. assert(nData>=1);
  176036. oldRowidValid = sqlite3_value_type(aData[0])!=SQLITE_NULL;;
  176037. oldRowid = oldRowidValid ? sqlite3_value_int64(aData[0]) : 0;
  176038. newRowidValid = nData>1 && sqlite3_value_type(aData[1])!=SQLITE_NULL;
  176039. newRowid = newRowidValid ? sqlite3_value_int64(aData[1]) : 0;
  176040. cell.iRowid = newRowid;
  176041. if( nData>1 /* not a DELETE */
  176042. && (!oldRowidValid /* INSERT */
  176043. || !sqlite3_value_nochange(aData[2]) /* UPDATE _shape */
  176044. || oldRowid!=newRowid) /* Rowid change */
  176045. ){
  176046. geopolyBBox(0, aData[2], cell.aCoord, &rc);
  176047. if( rc ){
  176048. if( rc==SQLITE_ERROR ){
  176049. pVtab->zErrMsg =
  176050. sqlite3_mprintf("_shape does not contain a valid polygon");
  176051. }
  176052. goto geopoly_update_end;
  176053. }
  176054. coordChange = 1;
  176055. /* If a rowid value was supplied, check if it is already present in
  176056. ** the table. If so, the constraint has failed. */
  176057. if( newRowidValid && (!oldRowidValid || oldRowid!=newRowid) ){
  176058. int steprc;
  176059. sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
  176060. steprc = sqlite3_step(pRtree->pReadRowid);
  176061. rc = sqlite3_reset(pRtree->pReadRowid);
  176062. if( SQLITE_ROW==steprc ){
  176063. if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
  176064. rc = rtreeDeleteRowid(pRtree, cell.iRowid);
  176065. }else{
  176066. rc = rtreeConstraintError(pRtree, 0);
  176067. }
  176068. }
  176069. }
  176070. }
  176071. /* If aData[0] is not an SQL NULL value, it is the rowid of a
  176072. ** record to delete from the r-tree table. The following block does
  176073. ** just that.
  176074. */
  176075. if( rc==SQLITE_OK && (nData==1 || (coordChange && oldRowidValid)) ){
  176076. rc = rtreeDeleteRowid(pRtree, oldRowid);
  176077. }
  176078. /* If the aData[] array contains more than one element, elements
  176079. ** (aData[2]..aData[argc-1]) contain a new record to insert into
  176080. ** the r-tree structure.
  176081. */
  176082. if( rc==SQLITE_OK && nData>1 && coordChange ){
  176083. /* Insert the new record into the r-tree */
  176084. RtreeNode *pLeaf = 0;
  176085. if( !newRowidValid ){
  176086. rc = rtreeNewRowid(pRtree, &cell.iRowid);
  176087. }
  176088. *pRowid = cell.iRowid;
  176089. if( rc==SQLITE_OK ){
  176090. rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
  176091. }
  176092. if( rc==SQLITE_OK ){
  176093. int rc2;
  176094. pRtree->iReinsertHeight = -1;
  176095. rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
  176096. rc2 = nodeRelease(pRtree, pLeaf);
  176097. if( rc==SQLITE_OK ){
  176098. rc = rc2;
  176099. }
  176100. }
  176101. }
  176102. /* Change the data */
  176103. if( rc==SQLITE_OK && nData>1 ){
  176104. sqlite3_stmt *pUp = pRtree->pWriteAux;
  176105. int jj;
  176106. int nChange = 0;
  176107. sqlite3_bind_int64(pUp, 1, cell.iRowid);
  176108. assert( pRtree->nAux>=1 );
  176109. if( sqlite3_value_nochange(aData[2]) ){
  176110. sqlite3_bind_null(pUp, 2);
  176111. }else{
  176112. GeoPoly *p = 0;
  176113. if( sqlite3_value_type(aData[2])==SQLITE_TEXT
  176114. && (p = geopolyFuncParam(0, aData[2], &rc))!=0
  176115. && rc==SQLITE_OK
  176116. ){
  176117. sqlite3_bind_blob(pUp, 2, p->hdr, 4+8*p->nVertex, SQLITE_TRANSIENT);
  176118. }else{
  176119. sqlite3_bind_value(pUp, 2, aData[2]);
  176120. }
  176121. sqlite3_free(p);
  176122. nChange = 1;
  176123. }
  176124. for(jj=1; jj<pRtree->nAux; jj++){
  176125. nChange++;
  176126. sqlite3_bind_value(pUp, jj+2, aData[jj+2]);
  176127. }
  176128. if( nChange ){
  176129. sqlite3_step(pUp);
  176130. rc = sqlite3_reset(pUp);
  176131. }
  176132. }
  176133. geopoly_update_end:
  176134. rtreeRelease(pRtree);
  176135. return rc;
  176136. }
  176137. /*
  176138. ** Report that geopoly_overlap() is an overloaded function suitable
  176139. ** for use in xBestIndex.
  176140. */
  176141. static int geopolyFindFunction(
  176142. sqlite3_vtab *pVtab,
  176143. int nArg,
  176144. const char *zName,
  176145. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
  176146. void **ppArg
  176147. ){
  176148. if( sqlite3_stricmp(zName, "geopoly_overlap")==0 ){
  176149. *pxFunc = geopolyOverlapFunc;
  176150. *ppArg = 0;
  176151. return SQLITE_INDEX_CONSTRAINT_FUNCTION;
  176152. }
  176153. if( sqlite3_stricmp(zName, "geopoly_within")==0 ){
  176154. *pxFunc = geopolyWithinFunc;
  176155. *ppArg = 0;
  176156. return SQLITE_INDEX_CONSTRAINT_FUNCTION+1;
  176157. }
  176158. return 0;
  176159. }
  176160. static sqlite3_module geopolyModule = {
  176161. 3, /* iVersion */
  176162. geopolyCreate, /* xCreate - create a table */
  176163. geopolyConnect, /* xConnect - connect to an existing table */
  176164. geopolyBestIndex, /* xBestIndex - Determine search strategy */
  176165. rtreeDisconnect, /* xDisconnect - Disconnect from a table */
  176166. rtreeDestroy, /* xDestroy - Drop a table */
  176167. rtreeOpen, /* xOpen - open a cursor */
  176168. rtreeClose, /* xClose - close a cursor */
  176169. geopolyFilter, /* xFilter - configure scan constraints */
  176170. rtreeNext, /* xNext - advance a cursor */
  176171. rtreeEof, /* xEof */
  176172. geopolyColumn, /* xColumn - read data */
  176173. rtreeRowid, /* xRowid - read data */
  176174. geopolyUpdate, /* xUpdate - write data */
  176175. rtreeBeginTransaction, /* xBegin - begin transaction */
  176176. rtreeEndTransaction, /* xSync - sync transaction */
  176177. rtreeEndTransaction, /* xCommit - commit transaction */
  176178. rtreeEndTransaction, /* xRollback - rollback transaction */
  176179. geopolyFindFunction, /* xFindFunction - function overloading */
  176180. rtreeRename, /* xRename - rename the table */
  176181. rtreeSavepoint, /* xSavepoint */
  176182. 0, /* xRelease */
  176183. 0, /* xRollbackTo */
  176184. rtreeShadowName /* xShadowName */
  176185. };
  176186. static int sqlite3_geopoly_init(sqlite3 *db){
  176187. int rc = SQLITE_OK;
  176188. static const struct {
  176189. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  176190. signed char nArg;
  176191. unsigned char bPure;
  176192. const char *zName;
  176193. } aFunc[] = {
  176194. { geopolyAreaFunc, 1, 1, "geopoly_area" },
  176195. { geopolyBlobFunc, 1, 1, "geopoly_blob" },
  176196. { geopolyJsonFunc, 1, 1, "geopoly_json" },
  176197. { geopolySvgFunc, -1, 1, "geopoly_svg" },
  176198. { geopolyWithinFunc, 2, 1, "geopoly_within" },
  176199. { geopolyContainsPointFunc, 3, 1, "geopoly_contains_point" },
  176200. { geopolyOverlapFunc, 2, 1, "geopoly_overlap" },
  176201. { geopolyDebugFunc, 1, 0, "geopoly_debug" },
  176202. { geopolyBBoxFunc, 1, 1, "geopoly_bbox" },
  176203. { geopolyXformFunc, 7, 1, "geopoly_xform" },
  176204. { geopolyRegularFunc, 4, 1, "geopoly_regular" },
  176205. { geopolyCcwFunc, 1, 1, "geopoly_ccw" },
  176206. };
  176207. static const struct {
  176208. void (*xStep)(sqlite3_context*,int,sqlite3_value**);
  176209. void (*xFinal)(sqlite3_context*);
  176210. const char *zName;
  176211. } aAgg[] = {
  176212. { geopolyBBoxStep, geopolyBBoxFinal, "geopoly_group_bbox" },
  176213. };
  176214. int i;
  176215. for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
  176216. int enc = aFunc[i].bPure ? SQLITE_UTF8|SQLITE_DETERMINISTIC : SQLITE_UTF8;
  176217. rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg,
  176218. enc, 0,
  176219. aFunc[i].xFunc, 0, 0);
  176220. }
  176221. for(i=0; i<sizeof(aAgg)/sizeof(aAgg[0]) && rc==SQLITE_OK; i++){
  176222. rc = sqlite3_create_function(db, aAgg[i].zName, 1, SQLITE_UTF8, 0,
  176223. 0, aAgg[i].xStep, aAgg[i].xFinal);
  176224. }
  176225. if( rc==SQLITE_OK ){
  176226. rc = sqlite3_create_module_v2(db, "geopoly", &geopolyModule, 0, 0);
  176227. }
  176228. return rc;
  176229. }
  176230. /************** End of geopoly.c *********************************************/
  176231. /************** Continuing where we left off in rtree.c **********************/
  176232. #endif
  176233. /*
  176234. ** Register the r-tree module with database handle db. This creates the
  176235. ** virtual table module "rtree" and the debugging/analysis scalar
  176236. ** function "rtreenode".
  176237. */
  176238. SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
  176239. const int utf8 = SQLITE_UTF8;
  176240. int rc;
  176241. rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
  176242. if( rc==SQLITE_OK ){
  176243. rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
  176244. }
  176245. if( rc==SQLITE_OK ){
  176246. rc = sqlite3_create_function(db, "rtreecheck", -1, utf8, 0,rtreecheck, 0,0);
  176247. }
  176248. if( rc==SQLITE_OK ){
  176249. #ifdef SQLITE_RTREE_INT_ONLY
  176250. void *c = (void *)RTREE_COORD_INT32;
  176251. #else
  176252. void *c = (void *)RTREE_COORD_REAL32;
  176253. #endif
  176254. rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
  176255. }
  176256. if( rc==SQLITE_OK ){
  176257. void *c = (void *)RTREE_COORD_INT32;
  176258. rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
  176259. }
  176260. #ifdef SQLITE_ENABLE_GEOPOLY
  176261. if( rc==SQLITE_OK ){
  176262. rc = sqlite3_geopoly_init(db);
  176263. }
  176264. #endif
  176265. return rc;
  176266. }
  176267. /*
  176268. ** This routine deletes the RtreeGeomCallback object that was attached
  176269. ** one of the SQL functions create by sqlite3_rtree_geometry_callback()
  176270. ** or sqlite3_rtree_query_callback(). In other words, this routine is the
  176271. ** destructor for an RtreeGeomCallback objecct. This routine is called when
  176272. ** the corresponding SQL function is deleted.
  176273. */
  176274. static void rtreeFreeCallback(void *p){
  176275. RtreeGeomCallback *pInfo = (RtreeGeomCallback*)p;
  176276. if( pInfo->xDestructor ) pInfo->xDestructor(pInfo->pContext);
  176277. sqlite3_free(p);
  176278. }
  176279. /*
  176280. ** This routine frees the BLOB that is returned by geomCallback().
  176281. */
  176282. static void rtreeMatchArgFree(void *pArg){
  176283. int i;
  176284. RtreeMatchArg *p = (RtreeMatchArg*)pArg;
  176285. for(i=0; i<p->nParam; i++){
  176286. sqlite3_value_free(p->apSqlParam[i]);
  176287. }
  176288. sqlite3_free(p);
  176289. }
  176290. /*
  176291. ** Each call to sqlite3_rtree_geometry_callback() or
  176292. ** sqlite3_rtree_query_callback() creates an ordinary SQLite
  176293. ** scalar function that is implemented by this routine.
  176294. **
  176295. ** All this function does is construct an RtreeMatchArg object that
  176296. ** contains the geometry-checking callback routines and a list of
  176297. ** parameters to this function, then return that RtreeMatchArg object
  176298. ** as a BLOB.
  176299. **
  176300. ** The R-Tree MATCH operator will read the returned BLOB, deserialize
  176301. ** the RtreeMatchArg object, and use the RtreeMatchArg object to figure
  176302. ** out which elements of the R-Tree should be returned by the query.
  176303. */
  176304. static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
  176305. RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
  176306. RtreeMatchArg *pBlob;
  176307. sqlite3_int64 nBlob;
  176308. int memErr = 0;
  176309. nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue)
  176310. + nArg*sizeof(sqlite3_value*);
  176311. pBlob = (RtreeMatchArg *)sqlite3_malloc64(nBlob);
  176312. if( !pBlob ){
  176313. sqlite3_result_error_nomem(ctx);
  176314. }else{
  176315. int i;
  176316. pBlob->iSize = nBlob;
  176317. pBlob->cb = pGeomCtx[0];
  176318. pBlob->apSqlParam = (sqlite3_value**)&pBlob->aParam[nArg];
  176319. pBlob->nParam = nArg;
  176320. for(i=0; i<nArg; i++){
  176321. pBlob->apSqlParam[i] = sqlite3_value_dup(aArg[i]);
  176322. if( pBlob->apSqlParam[i]==0 ) memErr = 1;
  176323. #ifdef SQLITE_RTREE_INT_ONLY
  176324. pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
  176325. #else
  176326. pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
  176327. #endif
  176328. }
  176329. if( memErr ){
  176330. sqlite3_result_error_nomem(ctx);
  176331. rtreeMatchArgFree(pBlob);
  176332. }else{
  176333. sqlite3_result_pointer(ctx, pBlob, "RtreeMatchArg", rtreeMatchArgFree);
  176334. }
  176335. }
  176336. }
  176337. /*
  176338. ** Register a new geometry function for use with the r-tree MATCH operator.
  176339. */
  176340. SQLITE_API int sqlite3_rtree_geometry_callback(
  176341. sqlite3 *db, /* Register SQL function on this connection */
  176342. const char *zGeom, /* Name of the new SQL function */
  176343. int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*), /* Callback */
  176344. void *pContext /* Extra data associated with the callback */
  176345. ){
  176346. RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
  176347. /* Allocate and populate the context object. */
  176348. pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
  176349. if( !pGeomCtx ) return SQLITE_NOMEM;
  176350. pGeomCtx->xGeom = xGeom;
  176351. pGeomCtx->xQueryFunc = 0;
  176352. pGeomCtx->xDestructor = 0;
  176353. pGeomCtx->pContext = pContext;
  176354. return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
  176355. (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
  176356. );
  176357. }
  176358. /*
  176359. ** Register a new 2nd-generation geometry function for use with the
  176360. ** r-tree MATCH operator.
  176361. */
  176362. SQLITE_API int sqlite3_rtree_query_callback(
  176363. sqlite3 *db, /* Register SQL function on this connection */
  176364. const char *zQueryFunc, /* Name of new SQL function */
  176365. int (*xQueryFunc)(sqlite3_rtree_query_info*), /* Callback */
  176366. void *pContext, /* Extra data passed into the callback */
  176367. void (*xDestructor)(void*) /* Destructor for the extra data */
  176368. ){
  176369. RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
  176370. /* Allocate and populate the context object. */
  176371. pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
  176372. if( !pGeomCtx ) return SQLITE_NOMEM;
  176373. pGeomCtx->xGeom = 0;
  176374. pGeomCtx->xQueryFunc = xQueryFunc;
  176375. pGeomCtx->xDestructor = xDestructor;
  176376. pGeomCtx->pContext = pContext;
  176377. return sqlite3_create_function_v2(db, zQueryFunc, -1, SQLITE_ANY,
  176378. (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
  176379. );
  176380. }
  176381. #if !SQLITE_CORE
  176382. #ifdef _WIN32
  176383. __declspec(dllexport)
  176384. #endif
  176385. SQLITE_API int sqlite3_rtree_init(
  176386. sqlite3 *db,
  176387. char **pzErrMsg,
  176388. const sqlite3_api_routines *pApi
  176389. ){
  176390. SQLITE_EXTENSION_INIT2(pApi)
  176391. return sqlite3RtreeInit(db);
  176392. }
  176393. #endif
  176394. #endif
  176395. /************** End of rtree.c ***********************************************/
  176396. /************** Begin file icu.c *********************************************/
  176397. /*
  176398. ** 2007 May 6
  176399. **
  176400. ** The author disclaims copyright to this source code. In place of
  176401. ** a legal notice, here is a blessing:
  176402. **
  176403. ** May you do good and not evil.
  176404. ** May you find forgiveness for yourself and forgive others.
  176405. ** May you share freely, never taking more than you give.
  176406. **
  176407. *************************************************************************
  176408. ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
  176409. **
  176410. ** This file implements an integration between the ICU library
  176411. ** ("International Components for Unicode", an open-source library
  176412. ** for handling unicode data) and SQLite. The integration uses
  176413. ** ICU to provide the following to SQLite:
  176414. **
  176415. ** * An implementation of the SQL regexp() function (and hence REGEXP
  176416. ** operator) using the ICU uregex_XX() APIs.
  176417. **
  176418. ** * Implementations of the SQL scalar upper() and lower() functions
  176419. ** for case mapping.
  176420. **
  176421. ** * Integration of ICU and SQLite collation sequences.
  176422. **
  176423. ** * An implementation of the LIKE operator that uses ICU to
  176424. ** provide case-independent matching.
  176425. */
  176426. #if !defined(SQLITE_CORE) \
  176427. || defined(SQLITE_ENABLE_ICU) \
  176428. || defined(SQLITE_ENABLE_ICU_COLLATIONS)
  176429. /* Include ICU headers */
  176430. #include <unicode/utypes.h>
  176431. #include <unicode/uregex.h>
  176432. #include <unicode/ustring.h>
  176433. #include <unicode/ucol.h>
  176434. /* #include <assert.h> */
  176435. #ifndef SQLITE_CORE
  176436. /* #include "sqlite3ext.h" */
  176437. SQLITE_EXTENSION_INIT1
  176438. #else
  176439. /* #include "sqlite3.h" */
  176440. #endif
  176441. /*
  176442. ** This function is called when an ICU function called from within
  176443. ** the implementation of an SQL scalar function returns an error.
  176444. **
  176445. ** The scalar function context passed as the first argument is
  176446. ** loaded with an error message based on the following two args.
  176447. */
  176448. static void icuFunctionError(
  176449. sqlite3_context *pCtx, /* SQLite scalar function context */
  176450. const char *zName, /* Name of ICU function that failed */
  176451. UErrorCode e /* Error code returned by ICU function */
  176452. ){
  176453. char zBuf[128];
  176454. sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
  176455. zBuf[127] = '\0';
  176456. sqlite3_result_error(pCtx, zBuf, -1);
  176457. }
  176458. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
  176459. /*
  176460. ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
  176461. ** operator.
  176462. */
  176463. #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
  176464. # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
  176465. #endif
  176466. /*
  176467. ** Version of sqlite3_free() that is always a function, never a macro.
  176468. */
  176469. static void xFree(void *p){
  176470. sqlite3_free(p);
  176471. }
  176472. /*
  176473. ** This lookup table is used to help decode the first byte of
  176474. ** a multi-byte UTF8 character. It is copied here from SQLite source
  176475. ** code file utf8.c.
  176476. */
  176477. static const unsigned char icuUtf8Trans1[] = {
  176478. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  176479. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  176480. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  176481. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  176482. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  176483. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  176484. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  176485. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  176486. };
  176487. #define SQLITE_ICU_READ_UTF8(zIn, c) \
  176488. c = *(zIn++); \
  176489. if( c>=0xc0 ){ \
  176490. c = icuUtf8Trans1[c-0xc0]; \
  176491. while( (*zIn & 0xc0)==0x80 ){ \
  176492. c = (c<<6) + (0x3f & *(zIn++)); \
  176493. } \
  176494. }
  176495. #define SQLITE_ICU_SKIP_UTF8(zIn) \
  176496. assert( *zIn ); \
  176497. if( *(zIn++)>=0xc0 ){ \
  176498. while( (*zIn & 0xc0)==0x80 ){zIn++;} \
  176499. }
  176500. /*
  176501. ** Compare two UTF-8 strings for equality where the first string is
  176502. ** a "LIKE" expression. Return true (1) if they are the same and
  176503. ** false (0) if they are different.
  176504. */
  176505. static int icuLikeCompare(
  176506. const uint8_t *zPattern, /* LIKE pattern */
  176507. const uint8_t *zString, /* The UTF-8 string to compare against */
  176508. const UChar32 uEsc /* The escape character */
  176509. ){
  176510. static const uint32_t MATCH_ONE = (uint32_t)'_';
  176511. static const uint32_t MATCH_ALL = (uint32_t)'%';
  176512. int prevEscape = 0; /* True if the previous character was uEsc */
  176513. while( 1 ){
  176514. /* Read (and consume) the next character from the input pattern. */
  176515. uint32_t uPattern;
  176516. SQLITE_ICU_READ_UTF8(zPattern, uPattern);
  176517. if( uPattern==0 ) break;
  176518. /* There are now 4 possibilities:
  176519. **
  176520. ** 1. uPattern is an unescaped match-all character "%",
  176521. ** 2. uPattern is an unescaped match-one character "_",
  176522. ** 3. uPattern is an unescaped escape character, or
  176523. ** 4. uPattern is to be handled as an ordinary character
  176524. */
  176525. if( !prevEscape && uPattern==MATCH_ALL ){
  176526. /* Case 1. */
  176527. uint8_t c;
  176528. /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
  176529. ** MATCH_ALL. For each MATCH_ONE, skip one character in the
  176530. ** test string.
  176531. */
  176532. while( (c=*zPattern) == MATCH_ALL || c == MATCH_ONE ){
  176533. if( c==MATCH_ONE ){
  176534. if( *zString==0 ) return 0;
  176535. SQLITE_ICU_SKIP_UTF8(zString);
  176536. }
  176537. zPattern++;
  176538. }
  176539. if( *zPattern==0 ) return 1;
  176540. while( *zString ){
  176541. if( icuLikeCompare(zPattern, zString, uEsc) ){
  176542. return 1;
  176543. }
  176544. SQLITE_ICU_SKIP_UTF8(zString);
  176545. }
  176546. return 0;
  176547. }else if( !prevEscape && uPattern==MATCH_ONE ){
  176548. /* Case 2. */
  176549. if( *zString==0 ) return 0;
  176550. SQLITE_ICU_SKIP_UTF8(zString);
  176551. }else if( !prevEscape && uPattern==(uint32_t)uEsc){
  176552. /* Case 3. */
  176553. prevEscape = 1;
  176554. }else{
  176555. /* Case 4. */
  176556. uint32_t uString;
  176557. SQLITE_ICU_READ_UTF8(zString, uString);
  176558. uString = (uint32_t)u_foldCase((UChar32)uString, U_FOLD_CASE_DEFAULT);
  176559. uPattern = (uint32_t)u_foldCase((UChar32)uPattern, U_FOLD_CASE_DEFAULT);
  176560. if( uString!=uPattern ){
  176561. return 0;
  176562. }
  176563. prevEscape = 0;
  176564. }
  176565. }
  176566. return *zString==0;
  176567. }
  176568. /*
  176569. ** Implementation of the like() SQL function. This function implements
  176570. ** the build-in LIKE operator. The first argument to the function is the
  176571. ** pattern and the second argument is the string. So, the SQL statements:
  176572. **
  176573. ** A LIKE B
  176574. **
  176575. ** is implemented as like(B, A). If there is an escape character E,
  176576. **
  176577. ** A LIKE B ESCAPE E
  176578. **
  176579. ** is mapped to like(B, A, E).
  176580. */
  176581. static void icuLikeFunc(
  176582. sqlite3_context *context,
  176583. int argc,
  176584. sqlite3_value **argv
  176585. ){
  176586. const unsigned char *zA = sqlite3_value_text(argv[0]);
  176587. const unsigned char *zB = sqlite3_value_text(argv[1]);
  176588. UChar32 uEsc = 0;
  176589. /* Limit the length of the LIKE or GLOB pattern to avoid problems
  176590. ** of deep recursion and N*N behavior in patternCompare().
  176591. */
  176592. if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
  176593. sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
  176594. return;
  176595. }
  176596. if( argc==3 ){
  176597. /* The escape character string must consist of a single UTF-8 character.
  176598. ** Otherwise, return an error.
  176599. */
  176600. int nE= sqlite3_value_bytes(argv[2]);
  176601. const unsigned char *zE = sqlite3_value_text(argv[2]);
  176602. int i = 0;
  176603. if( zE==0 ) return;
  176604. U8_NEXT(zE, i, nE, uEsc);
  176605. if( i!=nE){
  176606. sqlite3_result_error(context,
  176607. "ESCAPE expression must be a single character", -1);
  176608. return;
  176609. }
  176610. }
  176611. if( zA && zB ){
  176612. sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
  176613. }
  176614. }
  176615. /*
  176616. ** Function to delete compiled regexp objects. Registered as
  176617. ** a destructor function with sqlite3_set_auxdata().
  176618. */
  176619. static void icuRegexpDelete(void *p){
  176620. URegularExpression *pExpr = (URegularExpression *)p;
  176621. uregex_close(pExpr);
  176622. }
  176623. /*
  176624. ** Implementation of SQLite REGEXP operator. This scalar function takes
  176625. ** two arguments. The first is a regular expression pattern to compile
  176626. ** the second is a string to match against that pattern. If either
  176627. ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
  176628. ** is 1 if the string matches the pattern, or 0 otherwise.
  176629. **
  176630. ** SQLite maps the regexp() function to the regexp() operator such
  176631. ** that the following two are equivalent:
  176632. **
  176633. ** zString REGEXP zPattern
  176634. ** regexp(zPattern, zString)
  176635. **
  176636. ** Uses the following ICU regexp APIs:
  176637. **
  176638. ** uregex_open()
  176639. ** uregex_matches()
  176640. ** uregex_close()
  176641. */
  176642. static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
  176643. UErrorCode status = U_ZERO_ERROR;
  176644. URegularExpression *pExpr;
  176645. UBool res;
  176646. const UChar *zString = sqlite3_value_text16(apArg[1]);
  176647. (void)nArg; /* Unused parameter */
  176648. /* If the left hand side of the regexp operator is NULL,
  176649. ** then the result is also NULL.
  176650. */
  176651. if( !zString ){
  176652. return;
  176653. }
  176654. pExpr = sqlite3_get_auxdata(p, 0);
  176655. if( !pExpr ){
  176656. const UChar *zPattern = sqlite3_value_text16(apArg[0]);
  176657. if( !zPattern ){
  176658. return;
  176659. }
  176660. pExpr = uregex_open(zPattern, -1, 0, 0, &status);
  176661. if( U_SUCCESS(status) ){
  176662. sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
  176663. }else{
  176664. assert(!pExpr);
  176665. icuFunctionError(p, "uregex_open", status);
  176666. return;
  176667. }
  176668. }
  176669. /* Configure the text that the regular expression operates on. */
  176670. uregex_setText(pExpr, zString, -1, &status);
  176671. if( !U_SUCCESS(status) ){
  176672. icuFunctionError(p, "uregex_setText", status);
  176673. return;
  176674. }
  176675. /* Attempt the match */
  176676. res = uregex_matches(pExpr, 0, &status);
  176677. if( !U_SUCCESS(status) ){
  176678. icuFunctionError(p, "uregex_matches", status);
  176679. return;
  176680. }
  176681. /* Set the text that the regular expression operates on to a NULL
  176682. ** pointer. This is not really necessary, but it is tidier than
  176683. ** leaving the regular expression object configured with an invalid
  176684. ** pointer after this function returns.
  176685. */
  176686. uregex_setText(pExpr, 0, 0, &status);
  176687. /* Return 1 or 0. */
  176688. sqlite3_result_int(p, res ? 1 : 0);
  176689. }
  176690. /*
  176691. ** Implementations of scalar functions for case mapping - upper() and
  176692. ** lower(). Function upper() converts its input to upper-case (ABC).
  176693. ** Function lower() converts to lower-case (abc).
  176694. **
  176695. ** ICU provides two types of case mapping, "general" case mapping and
  176696. ** "language specific". Refer to ICU documentation for the differences
  176697. ** between the two.
  176698. **
  176699. ** To utilise "general" case mapping, the upper() or lower() scalar
  176700. ** functions are invoked with one argument:
  176701. **
  176702. ** upper('ABC') -> 'abc'
  176703. ** lower('abc') -> 'ABC'
  176704. **
  176705. ** To access ICU "language specific" case mapping, upper() or lower()
  176706. ** should be invoked with two arguments. The second argument is the name
  176707. ** of the locale to use. Passing an empty string ("") or SQL NULL value
  176708. ** as the second argument is the same as invoking the 1 argument version
  176709. ** of upper() or lower().
  176710. **
  176711. ** lower('I', 'en_us') -> 'i'
  176712. ** lower('I', 'tr_tr') -> '\u131' (small dotless i)
  176713. **
  176714. ** http://www.icu-project.org/userguide/posix.html#case_mappings
  176715. */
  176716. static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
  176717. const UChar *zInput; /* Pointer to input string */
  176718. UChar *zOutput = 0; /* Pointer to output buffer */
  176719. int nInput; /* Size of utf-16 input string in bytes */
  176720. int nOut; /* Size of output buffer in bytes */
  176721. int cnt;
  176722. int bToUpper; /* True for toupper(), false for tolower() */
  176723. UErrorCode status;
  176724. const char *zLocale = 0;
  176725. assert(nArg==1 || nArg==2);
  176726. bToUpper = (sqlite3_user_data(p)!=0);
  176727. if( nArg==2 ){
  176728. zLocale = (const char *)sqlite3_value_text(apArg[1]);
  176729. }
  176730. zInput = sqlite3_value_text16(apArg[0]);
  176731. if( !zInput ){
  176732. return;
  176733. }
  176734. nOut = nInput = sqlite3_value_bytes16(apArg[0]);
  176735. if( nOut==0 ){
  176736. sqlite3_result_text16(p, "", 0, SQLITE_STATIC);
  176737. return;
  176738. }
  176739. for(cnt=0; cnt<2; cnt++){
  176740. UChar *zNew = sqlite3_realloc(zOutput, nOut);
  176741. if( zNew==0 ){
  176742. sqlite3_free(zOutput);
  176743. sqlite3_result_error_nomem(p);
  176744. return;
  176745. }
  176746. zOutput = zNew;
  176747. status = U_ZERO_ERROR;
  176748. if( bToUpper ){
  176749. nOut = 2*u_strToUpper(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
  176750. }else{
  176751. nOut = 2*u_strToLower(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
  176752. }
  176753. if( U_SUCCESS(status) ){
  176754. sqlite3_result_text16(p, zOutput, nOut, xFree);
  176755. }else if( status==U_BUFFER_OVERFLOW_ERROR ){
  176756. assert( cnt==0 );
  176757. continue;
  176758. }else{
  176759. icuFunctionError(p, bToUpper ? "u_strToUpper" : "u_strToLower", status);
  176760. }
  176761. return;
  176762. }
  176763. assert( 0 ); /* Unreachable */
  176764. }
  176765. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU) */
  176766. /*
  176767. ** Collation sequence destructor function. The pCtx argument points to
  176768. ** a UCollator structure previously allocated using ucol_open().
  176769. */
  176770. static void icuCollationDel(void *pCtx){
  176771. UCollator *p = (UCollator *)pCtx;
  176772. ucol_close(p);
  176773. }
  176774. /*
  176775. ** Collation sequence comparison function. The pCtx argument points to
  176776. ** a UCollator structure previously allocated using ucol_open().
  176777. */
  176778. static int icuCollationColl(
  176779. void *pCtx,
  176780. int nLeft,
  176781. const void *zLeft,
  176782. int nRight,
  176783. const void *zRight
  176784. ){
  176785. UCollationResult res;
  176786. UCollator *p = (UCollator *)pCtx;
  176787. res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
  176788. switch( res ){
  176789. case UCOL_LESS: return -1;
  176790. case UCOL_GREATER: return +1;
  176791. case UCOL_EQUAL: return 0;
  176792. }
  176793. assert(!"Unexpected return value from ucol_strcoll()");
  176794. return 0;
  176795. }
  176796. /*
  176797. ** Implementation of the scalar function icu_load_collation().
  176798. **
  176799. ** This scalar function is used to add ICU collation based collation
  176800. ** types to an SQLite database connection. It is intended to be called
  176801. ** as follows:
  176802. **
  176803. ** SELECT icu_load_collation(<locale>, <collation-name>);
  176804. **
  176805. ** Where <locale> is a string containing an ICU locale identifier (i.e.
  176806. ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
  176807. ** collation sequence to create.
  176808. */
  176809. static void icuLoadCollation(
  176810. sqlite3_context *p,
  176811. int nArg,
  176812. sqlite3_value **apArg
  176813. ){
  176814. sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
  176815. UErrorCode status = U_ZERO_ERROR;
  176816. const char *zLocale; /* Locale identifier - (eg. "jp_JP") */
  176817. const char *zName; /* SQL Collation sequence name (eg. "japanese") */
  176818. UCollator *pUCollator; /* ICU library collation object */
  176819. int rc; /* Return code from sqlite3_create_collation_x() */
  176820. assert(nArg==2);
  176821. (void)nArg; /* Unused parameter */
  176822. zLocale = (const char *)sqlite3_value_text(apArg[0]);
  176823. zName = (const char *)sqlite3_value_text(apArg[1]);
  176824. if( !zLocale || !zName ){
  176825. return;
  176826. }
  176827. pUCollator = ucol_open(zLocale, &status);
  176828. if( !U_SUCCESS(status) ){
  176829. icuFunctionError(p, "ucol_open", status);
  176830. return;
  176831. }
  176832. assert(p);
  176833. rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
  176834. icuCollationColl, icuCollationDel
  176835. );
  176836. if( rc!=SQLITE_OK ){
  176837. ucol_close(pUCollator);
  176838. sqlite3_result_error(p, "Error registering collation function", -1);
  176839. }
  176840. }
  176841. /*
  176842. ** Register the ICU extension functions with database db.
  176843. */
  176844. SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
  176845. static const struct IcuScalar {
  176846. const char *zName; /* Function name */
  176847. unsigned char nArg; /* Number of arguments */
  176848. unsigned short enc; /* Optimal text encoding */
  176849. unsigned char iContext; /* sqlite3_user_data() context */
  176850. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  176851. } scalars[] = {
  176852. {"icu_load_collation", 2, SQLITE_UTF8, 1, icuLoadCollation},
  176853. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
  176854. {"regexp", 2, SQLITE_ANY|SQLITE_DETERMINISTIC, 0, icuRegexpFunc},
  176855. {"lower", 1, SQLITE_UTF16|SQLITE_DETERMINISTIC, 0, icuCaseFunc16},
  176856. {"lower", 2, SQLITE_UTF16|SQLITE_DETERMINISTIC, 0, icuCaseFunc16},
  176857. {"upper", 1, SQLITE_UTF16|SQLITE_DETERMINISTIC, 1, icuCaseFunc16},
  176858. {"upper", 2, SQLITE_UTF16|SQLITE_DETERMINISTIC, 1, icuCaseFunc16},
  176859. {"lower", 1, SQLITE_UTF8|SQLITE_DETERMINISTIC, 0, icuCaseFunc16},
  176860. {"lower", 2, SQLITE_UTF8|SQLITE_DETERMINISTIC, 0, icuCaseFunc16},
  176861. {"upper", 1, SQLITE_UTF8|SQLITE_DETERMINISTIC, 1, icuCaseFunc16},
  176862. {"upper", 2, SQLITE_UTF8|SQLITE_DETERMINISTIC, 1, icuCaseFunc16},
  176863. {"like", 2, SQLITE_UTF8|SQLITE_DETERMINISTIC, 0, icuLikeFunc},
  176864. {"like", 3, SQLITE_UTF8|SQLITE_DETERMINISTIC, 0, icuLikeFunc},
  176865. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU) */
  176866. };
  176867. int rc = SQLITE_OK;
  176868. int i;
  176869. for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
  176870. const struct IcuScalar *p = &scalars[i];
  176871. rc = sqlite3_create_function(
  176872. db, p->zName, p->nArg, p->enc,
  176873. p->iContext ? (void*)db : (void*)0,
  176874. p->xFunc, 0, 0
  176875. );
  176876. }
  176877. return rc;
  176878. }
  176879. #if !SQLITE_CORE
  176880. #ifdef _WIN32
  176881. __declspec(dllexport)
  176882. #endif
  176883. SQLITE_API int sqlite3_icu_init(
  176884. sqlite3 *db,
  176885. char **pzErrMsg,
  176886. const sqlite3_api_routines *pApi
  176887. ){
  176888. SQLITE_EXTENSION_INIT2(pApi)
  176889. return sqlite3IcuInit(db);
  176890. }
  176891. #endif
  176892. #endif
  176893. /************** End of icu.c *************************************************/
  176894. /************** Begin file fts3_icu.c ****************************************/
  176895. /*
  176896. ** 2007 June 22
  176897. **
  176898. ** The author disclaims copyright to this source code. In place of
  176899. ** a legal notice, here is a blessing:
  176900. **
  176901. ** May you do good and not evil.
  176902. ** May you find forgiveness for yourself and forgive others.
  176903. ** May you share freely, never taking more than you give.
  176904. **
  176905. *************************************************************************
  176906. ** This file implements a tokenizer for fts3 based on the ICU library.
  176907. */
  176908. /* #include "fts3Int.h" */
  176909. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  176910. #ifdef SQLITE_ENABLE_ICU
  176911. /* #include <assert.h> */
  176912. /* #include <string.h> */
  176913. /* #include "fts3_tokenizer.h" */
  176914. #include <unicode/ubrk.h>
  176915. /* #include <unicode/ucol.h> */
  176916. /* #include <unicode/ustring.h> */
  176917. #include <unicode/utf16.h>
  176918. typedef struct IcuTokenizer IcuTokenizer;
  176919. typedef struct IcuCursor IcuCursor;
  176920. struct IcuTokenizer {
  176921. sqlite3_tokenizer base;
  176922. char *zLocale;
  176923. };
  176924. struct IcuCursor {
  176925. sqlite3_tokenizer_cursor base;
  176926. UBreakIterator *pIter; /* ICU break-iterator object */
  176927. int nChar; /* Number of UChar elements in pInput */
  176928. UChar *aChar; /* Copy of input using utf-16 encoding */
  176929. int *aOffset; /* Offsets of each character in utf-8 input */
  176930. int nBuffer;
  176931. char *zBuffer;
  176932. int iToken;
  176933. };
  176934. /*
  176935. ** Create a new tokenizer instance.
  176936. */
  176937. static int icuCreate(
  176938. int argc, /* Number of entries in argv[] */
  176939. const char * const *argv, /* Tokenizer creation arguments */
  176940. sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
  176941. ){
  176942. IcuTokenizer *p;
  176943. int n = 0;
  176944. if( argc>0 ){
  176945. n = strlen(argv[0])+1;
  176946. }
  176947. p = (IcuTokenizer *)sqlite3_malloc64(sizeof(IcuTokenizer)+n);
  176948. if( !p ){
  176949. return SQLITE_NOMEM;
  176950. }
  176951. memset(p, 0, sizeof(IcuTokenizer));
  176952. if( n ){
  176953. p->zLocale = (char *)&p[1];
  176954. memcpy(p->zLocale, argv[0], n);
  176955. }
  176956. *ppTokenizer = (sqlite3_tokenizer *)p;
  176957. return SQLITE_OK;
  176958. }
  176959. /*
  176960. ** Destroy a tokenizer
  176961. */
  176962. static int icuDestroy(sqlite3_tokenizer *pTokenizer){
  176963. IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
  176964. sqlite3_free(p);
  176965. return SQLITE_OK;
  176966. }
  176967. /*
  176968. ** Prepare to begin tokenizing a particular string. The input
  176969. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  176970. ** used to incrementally tokenize this string is returned in
  176971. ** *ppCursor.
  176972. */
  176973. static int icuOpen(
  176974. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  176975. const char *zInput, /* Input string */
  176976. int nInput, /* Length of zInput in bytes */
  176977. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  176978. ){
  176979. IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
  176980. IcuCursor *pCsr;
  176981. const int32_t opt = U_FOLD_CASE_DEFAULT;
  176982. UErrorCode status = U_ZERO_ERROR;
  176983. int nChar;
  176984. UChar32 c;
  176985. int iInput = 0;
  176986. int iOut = 0;
  176987. *ppCursor = 0;
  176988. if( zInput==0 ){
  176989. nInput = 0;
  176990. zInput = "";
  176991. }else if( nInput<0 ){
  176992. nInput = strlen(zInput);
  176993. }
  176994. nChar = nInput+1;
  176995. pCsr = (IcuCursor *)sqlite3_malloc64(
  176996. sizeof(IcuCursor) + /* IcuCursor */
  176997. ((nChar+3)&~3) * sizeof(UChar) + /* IcuCursor.aChar[] */
  176998. (nChar+1) * sizeof(int) /* IcuCursor.aOffset[] */
  176999. );
  177000. if( !pCsr ){
  177001. return SQLITE_NOMEM;
  177002. }
  177003. memset(pCsr, 0, sizeof(IcuCursor));
  177004. pCsr->aChar = (UChar *)&pCsr[1];
  177005. pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3];
  177006. pCsr->aOffset[iOut] = iInput;
  177007. U8_NEXT(zInput, iInput, nInput, c);
  177008. while( c>0 ){
  177009. int isError = 0;
  177010. c = u_foldCase(c, opt);
  177011. U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
  177012. if( isError ){
  177013. sqlite3_free(pCsr);
  177014. return SQLITE_ERROR;
  177015. }
  177016. pCsr->aOffset[iOut] = iInput;
  177017. if( iInput<nInput ){
  177018. U8_NEXT(zInput, iInput, nInput, c);
  177019. }else{
  177020. c = 0;
  177021. }
  177022. }
  177023. pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
  177024. if( !U_SUCCESS(status) ){
  177025. sqlite3_free(pCsr);
  177026. return SQLITE_ERROR;
  177027. }
  177028. pCsr->nChar = iOut;
  177029. ubrk_first(pCsr->pIter);
  177030. *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
  177031. return SQLITE_OK;
  177032. }
  177033. /*
  177034. ** Close a tokenization cursor previously opened by a call to icuOpen().
  177035. */
  177036. static int icuClose(sqlite3_tokenizer_cursor *pCursor){
  177037. IcuCursor *pCsr = (IcuCursor *)pCursor;
  177038. ubrk_close(pCsr->pIter);
  177039. sqlite3_free(pCsr->zBuffer);
  177040. sqlite3_free(pCsr);
  177041. return SQLITE_OK;
  177042. }
  177043. /*
  177044. ** Extract the next token from a tokenization cursor.
  177045. */
  177046. static int icuNext(
  177047. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
  177048. const char **ppToken, /* OUT: *ppToken is the token text */
  177049. int *pnBytes, /* OUT: Number of bytes in token */
  177050. int *piStartOffset, /* OUT: Starting offset of token */
  177051. int *piEndOffset, /* OUT: Ending offset of token */
  177052. int *piPosition /* OUT: Position integer of token */
  177053. ){
  177054. IcuCursor *pCsr = (IcuCursor *)pCursor;
  177055. int iStart = 0;
  177056. int iEnd = 0;
  177057. int nByte = 0;
  177058. while( iStart==iEnd ){
  177059. UChar32 c;
  177060. iStart = ubrk_current(pCsr->pIter);
  177061. iEnd = ubrk_next(pCsr->pIter);
  177062. if( iEnd==UBRK_DONE ){
  177063. return SQLITE_DONE;
  177064. }
  177065. while( iStart<iEnd ){
  177066. int iWhite = iStart;
  177067. U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
  177068. if( u_isspace(c) ){
  177069. iStart = iWhite;
  177070. }else{
  177071. break;
  177072. }
  177073. }
  177074. assert(iStart<=iEnd);
  177075. }
  177076. do {
  177077. UErrorCode status = U_ZERO_ERROR;
  177078. if( nByte ){
  177079. char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
  177080. if( !zNew ){
  177081. return SQLITE_NOMEM;
  177082. }
  177083. pCsr->zBuffer = zNew;
  177084. pCsr->nBuffer = nByte;
  177085. }
  177086. u_strToUTF8(
  177087. pCsr->zBuffer, pCsr->nBuffer, &nByte, /* Output vars */
  177088. &pCsr->aChar[iStart], iEnd-iStart, /* Input vars */
  177089. &status /* Output success/failure */
  177090. );
  177091. } while( nByte>pCsr->nBuffer );
  177092. *ppToken = pCsr->zBuffer;
  177093. *pnBytes = nByte;
  177094. *piStartOffset = pCsr->aOffset[iStart];
  177095. *piEndOffset = pCsr->aOffset[iEnd];
  177096. *piPosition = pCsr->iToken++;
  177097. return SQLITE_OK;
  177098. }
  177099. /*
  177100. ** The set of routines that implement the simple tokenizer
  177101. */
  177102. static const sqlite3_tokenizer_module icuTokenizerModule = {
  177103. 0, /* iVersion */
  177104. icuCreate, /* xCreate */
  177105. icuDestroy, /* xCreate */
  177106. icuOpen, /* xOpen */
  177107. icuClose, /* xClose */
  177108. icuNext, /* xNext */
  177109. 0, /* xLanguageid */
  177110. };
  177111. /*
  177112. ** Set *ppModule to point at the implementation of the ICU tokenizer.
  177113. */
  177114. SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
  177115. sqlite3_tokenizer_module const**ppModule
  177116. ){
  177117. *ppModule = &icuTokenizerModule;
  177118. }
  177119. #endif /* defined(SQLITE_ENABLE_ICU) */
  177120. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  177121. /************** End of fts3_icu.c ********************************************/
  177122. /************** Begin file sqlite3rbu.c **************************************/
  177123. /*
  177124. ** 2014 August 30
  177125. **
  177126. ** The author disclaims copyright to this source code. In place of
  177127. ** a legal notice, here is a blessing:
  177128. **
  177129. ** May you do good and not evil.
  177130. ** May you find forgiveness for yourself and forgive others.
  177131. ** May you share freely, never taking more than you give.
  177132. **
  177133. *************************************************************************
  177134. **
  177135. **
  177136. ** OVERVIEW
  177137. **
  177138. ** The RBU extension requires that the RBU update be packaged as an
  177139. ** SQLite database. The tables it expects to find are described in
  177140. ** sqlite3rbu.h. Essentially, for each table xyz in the target database
  177141. ** that the user wishes to write to, a corresponding data_xyz table is
  177142. ** created in the RBU database and populated with one row for each row to
  177143. ** update, insert or delete from the target table.
  177144. **
  177145. ** The update proceeds in three stages:
  177146. **
  177147. ** 1) The database is updated. The modified database pages are written
  177148. ** to a *-oal file. A *-oal file is just like a *-wal file, except
  177149. ** that it is named "<database>-oal" instead of "<database>-wal".
  177150. ** Because regular SQLite clients do not look for file named
  177151. ** "<database>-oal", they go on using the original database in
  177152. ** rollback mode while the *-oal file is being generated.
  177153. **
  177154. ** During this stage RBU does not update the database by writing
  177155. ** directly to the target tables. Instead it creates "imposter"
  177156. ** tables using the SQLITE_TESTCTRL_IMPOSTER interface that it uses
  177157. ** to update each b-tree individually. All updates required by each
  177158. ** b-tree are completed before moving on to the next, and all
  177159. ** updates are done in sorted key order.
  177160. **
  177161. ** 2) The "<database>-oal" file is moved to the equivalent "<database>-wal"
  177162. ** location using a call to rename(2). Before doing this the RBU
  177163. ** module takes an EXCLUSIVE lock on the database file, ensuring
  177164. ** that there are no other active readers.
  177165. **
  177166. ** Once the EXCLUSIVE lock is released, any other database readers
  177167. ** detect the new *-wal file and read the database in wal mode. At
  177168. ** this point they see the new version of the database - including
  177169. ** the updates made as part of the RBU update.
  177170. **
  177171. ** 3) The new *-wal file is checkpointed. This proceeds in the same way
  177172. ** as a regular database checkpoint, except that a single frame is
  177173. ** checkpointed each time sqlite3rbu_step() is called. If the RBU
  177174. ** handle is closed before the entire *-wal file is checkpointed,
  177175. ** the checkpoint progress is saved in the RBU database and the
  177176. ** checkpoint can be resumed by another RBU client at some point in
  177177. ** the future.
  177178. **
  177179. ** POTENTIAL PROBLEMS
  177180. **
  177181. ** The rename() call might not be portable. And RBU is not currently
  177182. ** syncing the directory after renaming the file.
  177183. **
  177184. ** When state is saved, any commit to the *-oal file and the commit to
  177185. ** the RBU update database are not atomic. So if the power fails at the
  177186. ** wrong moment they might get out of sync. As the main database will be
  177187. ** committed before the RBU update database this will likely either just
  177188. ** pass unnoticed, or result in SQLITE_CONSTRAINT errors (due to UNIQUE
  177189. ** constraint violations).
  177190. **
  177191. ** If some client does modify the target database mid RBU update, or some
  177192. ** other error occurs, the RBU extension will keep throwing errors. It's
  177193. ** not really clear how to get out of this state. The system could just
  177194. ** by delete the RBU update database and *-oal file and have the device
  177195. ** download the update again and start over.
  177196. **
  177197. ** At present, for an UPDATE, both the new.* and old.* records are
  177198. ** collected in the rbu_xyz table. And for both UPDATEs and DELETEs all
  177199. ** fields are collected. This means we're probably writing a lot more
  177200. ** data to disk when saving the state of an ongoing update to the RBU
  177201. ** update database than is strictly necessary.
  177202. **
  177203. */
  177204. /* #include <assert.h> */
  177205. /* #include <string.h> */
  177206. /* #include <stdio.h> */
  177207. /* #include "sqlite3.h" */
  177208. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU)
  177209. /************** Include sqlite3rbu.h in the middle of sqlite3rbu.c ***********/
  177210. /************** Begin file sqlite3rbu.h **************************************/
  177211. /*
  177212. ** 2014 August 30
  177213. **
  177214. ** The author disclaims copyright to this source code. In place of
  177215. ** a legal notice, here is a blessing:
  177216. **
  177217. ** May you do good and not evil.
  177218. ** May you find forgiveness for yourself and forgive others.
  177219. ** May you share freely, never taking more than you give.
  177220. **
  177221. *************************************************************************
  177222. **
  177223. ** This file contains the public interface for the RBU extension.
  177224. */
  177225. /*
  177226. ** SUMMARY
  177227. **
  177228. ** Writing a transaction containing a large number of operations on
  177229. ** b-tree indexes that are collectively larger than the available cache
  177230. ** memory can be very inefficient.
  177231. **
  177232. ** The problem is that in order to update a b-tree, the leaf page (at least)
  177233. ** containing the entry being inserted or deleted must be modified. If the
  177234. ** working set of leaves is larger than the available cache memory, then a
  177235. ** single leaf that is modified more than once as part of the transaction
  177236. ** may be loaded from or written to the persistent media multiple times.
  177237. ** Additionally, because the index updates are likely to be applied in
  177238. ** random order, access to pages within the database is also likely to be in
  177239. ** random order, which is itself quite inefficient.
  177240. **
  177241. ** One way to improve the situation is to sort the operations on each index
  177242. ** by index key before applying them to the b-tree. This leads to an IO
  177243. ** pattern that resembles a single linear scan through the index b-tree,
  177244. ** and all but guarantees each modified leaf page is loaded and stored
  177245. ** exactly once. SQLite uses this trick to improve the performance of
  177246. ** CREATE INDEX commands. This extension allows it to be used to improve
  177247. ** the performance of large transactions on existing databases.
  177248. **
  177249. ** Additionally, this extension allows the work involved in writing the
  177250. ** large transaction to be broken down into sub-transactions performed
  177251. ** sequentially by separate processes. This is useful if the system cannot
  177252. ** guarantee that a single update process will run for long enough to apply
  177253. ** the entire update, for example because the update is being applied on a
  177254. ** mobile device that is frequently rebooted. Even after the writer process
  177255. ** has committed one or more sub-transactions, other database clients continue
  177256. ** to read from the original database snapshot. In other words, partially
  177257. ** applied transactions are not visible to other clients.
  177258. **
  177259. ** "RBU" stands for "Resumable Bulk Update". As in a large database update
  177260. ** transmitted via a wireless network to a mobile device. A transaction
  177261. ** applied using this extension is hence refered to as an "RBU update".
  177262. **
  177263. **
  177264. ** LIMITATIONS
  177265. **
  177266. ** An "RBU update" transaction is subject to the following limitations:
  177267. **
  177268. ** * The transaction must consist of INSERT, UPDATE and DELETE operations
  177269. ** only.
  177270. **
  177271. ** * INSERT statements may not use any default values.
  177272. **
  177273. ** * UPDATE and DELETE statements must identify their target rows by
  177274. ** non-NULL PRIMARY KEY values. Rows with NULL values stored in PRIMARY
  177275. ** KEY fields may not be updated or deleted. If the table being written
  177276. ** has no PRIMARY KEY, affected rows must be identified by rowid.
  177277. **
  177278. ** * UPDATE statements may not modify PRIMARY KEY columns.
  177279. **
  177280. ** * No triggers will be fired.
  177281. **
  177282. ** * No foreign key violations are detected or reported.
  177283. **
  177284. ** * CHECK constraints are not enforced.
  177285. **
  177286. ** * No constraint handling mode except for "OR ROLLBACK" is supported.
  177287. **
  177288. **
  177289. ** PREPARATION
  177290. **
  177291. ** An "RBU update" is stored as a separate SQLite database. A database
  177292. ** containing an RBU update is an "RBU database". For each table in the
  177293. ** target database to be updated, the RBU database should contain a table
  177294. ** named "data_<target name>" containing the same set of columns as the
  177295. ** target table, and one more - "rbu_control". The data_% table should
  177296. ** have no PRIMARY KEY or UNIQUE constraints, but each column should have
  177297. ** the same type as the corresponding column in the target database.
  177298. ** The "rbu_control" column should have no type at all. For example, if
  177299. ** the target database contains:
  177300. **
  177301. ** CREATE TABLE t1(a INTEGER PRIMARY KEY, b TEXT, c UNIQUE);
  177302. **
  177303. ** Then the RBU database should contain:
  177304. **
  177305. ** CREATE TABLE data_t1(a INTEGER, b TEXT, c, rbu_control);
  177306. **
  177307. ** The order of the columns in the data_% table does not matter.
  177308. **
  177309. ** Instead of a regular table, the RBU database may also contain virtual
  177310. ** tables or view named using the data_<target> naming scheme.
  177311. **
  177312. ** Instead of the plain data_<target> naming scheme, RBU database tables
  177313. ** may also be named data<integer>_<target>, where <integer> is any sequence
  177314. ** of zero or more numeric characters (0-9). This can be significant because
  177315. ** tables within the RBU database are always processed in order sorted by
  177316. ** name. By judicious selection of the <integer> portion of the names
  177317. ** of the RBU tables the user can therefore control the order in which they
  177318. ** are processed. This can be useful, for example, to ensure that "external
  177319. ** content" FTS4 tables are updated before their underlying content tables.
  177320. **
  177321. ** If the target database table is a virtual table or a table that has no
  177322. ** PRIMARY KEY declaration, the data_% table must also contain a column
  177323. ** named "rbu_rowid". This column is mapped to the tables implicit primary
  177324. ** key column - "rowid". Virtual tables for which the "rowid" column does
  177325. ** not function like a primary key value cannot be updated using RBU. For
  177326. ** example, if the target db contains either of the following:
  177327. **
  177328. ** CREATE VIRTUAL TABLE x1 USING fts3(a, b);
  177329. ** CREATE TABLE x1(a, b)
  177330. **
  177331. ** then the RBU database should contain:
  177332. **
  177333. ** CREATE TABLE data_x1(a, b, rbu_rowid, rbu_control);
  177334. **
  177335. ** All non-hidden columns (i.e. all columns matched by "SELECT *") of the
  177336. ** target table must be present in the input table. For virtual tables,
  177337. ** hidden columns are optional - they are updated by RBU if present in
  177338. ** the input table, or not otherwise. For example, to write to an fts4
  177339. ** table with a hidden languageid column such as:
  177340. **
  177341. ** CREATE VIRTUAL TABLE ft1 USING fts4(a, b, languageid='langid');
  177342. **
  177343. ** Either of the following input table schemas may be used:
  177344. **
  177345. ** CREATE TABLE data_ft1(a, b, langid, rbu_rowid, rbu_control);
  177346. ** CREATE TABLE data_ft1(a, b, rbu_rowid, rbu_control);
  177347. **
  177348. ** For each row to INSERT into the target database as part of the RBU
  177349. ** update, the corresponding data_% table should contain a single record
  177350. ** with the "rbu_control" column set to contain integer value 0. The
  177351. ** other columns should be set to the values that make up the new record
  177352. ** to insert.
  177353. **
  177354. ** If the target database table has an INTEGER PRIMARY KEY, it is not
  177355. ** possible to insert a NULL value into the IPK column. Attempting to
  177356. ** do so results in an SQLITE_MISMATCH error.
  177357. **
  177358. ** For each row to DELETE from the target database as part of the RBU
  177359. ** update, the corresponding data_% table should contain a single record
  177360. ** with the "rbu_control" column set to contain integer value 1. The
  177361. ** real primary key values of the row to delete should be stored in the
  177362. ** corresponding columns of the data_% table. The values stored in the
  177363. ** other columns are not used.
  177364. **
  177365. ** For each row to UPDATE from the target database as part of the RBU
  177366. ** update, the corresponding data_% table should contain a single record
  177367. ** with the "rbu_control" column set to contain a value of type text.
  177368. ** The real primary key values identifying the row to update should be
  177369. ** stored in the corresponding columns of the data_% table row, as should
  177370. ** the new values of all columns being update. The text value in the
  177371. ** "rbu_control" column must contain the same number of characters as
  177372. ** there are columns in the target database table, and must consist entirely
  177373. ** of 'x' and '.' characters (or in some special cases 'd' - see below). For
  177374. ** each column that is being updated, the corresponding character is set to
  177375. ** 'x'. For those that remain as they are, the corresponding character of the
  177376. ** rbu_control value should be set to '.'. For example, given the tables
  177377. ** above, the update statement:
  177378. **
  177379. ** UPDATE t1 SET c = 'usa' WHERE a = 4;
  177380. **
  177381. ** is represented by the data_t1 row created by:
  177382. **
  177383. ** INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..x');
  177384. **
  177385. ** Instead of an 'x' character, characters of the rbu_control value specified
  177386. ** for UPDATEs may also be set to 'd'. In this case, instead of updating the
  177387. ** target table with the value stored in the corresponding data_% column, the
  177388. ** user-defined SQL function "rbu_delta()" is invoked and the result stored in
  177389. ** the target table column. rbu_delta() is invoked with two arguments - the
  177390. ** original value currently stored in the target table column and the
  177391. ** value specified in the data_xxx table.
  177392. **
  177393. ** For example, this row:
  177394. **
  177395. ** INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..d');
  177396. **
  177397. ** is similar to an UPDATE statement such as:
  177398. **
  177399. ** UPDATE t1 SET c = rbu_delta(c, 'usa') WHERE a = 4;
  177400. **
  177401. ** Finally, if an 'f' character appears in place of a 'd' or 's' in an
  177402. ** ota_control string, the contents of the data_xxx table column is assumed
  177403. ** to be a "fossil delta" - a patch to be applied to a blob value in the
  177404. ** format used by the fossil source-code management system. In this case
  177405. ** the existing value within the target database table must be of type BLOB.
  177406. ** It is replaced by the result of applying the specified fossil delta to
  177407. ** itself.
  177408. **
  177409. ** If the target database table is a virtual table or a table with no PRIMARY
  177410. ** KEY, the rbu_control value should not include a character corresponding
  177411. ** to the rbu_rowid value. For example, this:
  177412. **
  177413. ** INSERT INTO data_ft1(a, b, rbu_rowid, rbu_control)
  177414. ** VALUES(NULL, 'usa', 12, '.x');
  177415. **
  177416. ** causes a result similar to:
  177417. **
  177418. ** UPDATE ft1 SET b = 'usa' WHERE rowid = 12;
  177419. **
  177420. ** The data_xxx tables themselves should have no PRIMARY KEY declarations.
  177421. ** However, RBU is more efficient if reading the rows in from each data_xxx
  177422. ** table in "rowid" order is roughly the same as reading them sorted by
  177423. ** the PRIMARY KEY of the corresponding target database table. In other
  177424. ** words, rows should be sorted using the destination table PRIMARY KEY
  177425. ** fields before they are inserted into the data_xxx tables.
  177426. **
  177427. ** USAGE
  177428. **
  177429. ** The API declared below allows an application to apply an RBU update
  177430. ** stored on disk to an existing target database. Essentially, the
  177431. ** application:
  177432. **
  177433. ** 1) Opens an RBU handle using the sqlite3rbu_open() function.
  177434. **
  177435. ** 2) Registers any required virtual table modules with the database
  177436. ** handle returned by sqlite3rbu_db(). Also, if required, register
  177437. ** the rbu_delta() implementation.
  177438. **
  177439. ** 3) Calls the sqlite3rbu_step() function one or more times on
  177440. ** the new handle. Each call to sqlite3rbu_step() performs a single
  177441. ** b-tree operation, so thousands of calls may be required to apply
  177442. ** a complete update.
  177443. **
  177444. ** 4) Calls sqlite3rbu_close() to close the RBU update handle. If
  177445. ** sqlite3rbu_step() has been called enough times to completely
  177446. ** apply the update to the target database, then the RBU database
  177447. ** is marked as fully applied. Otherwise, the state of the RBU
  177448. ** update application is saved in the RBU database for later
  177449. ** resumption.
  177450. **
  177451. ** See comments below for more detail on APIs.
  177452. **
  177453. ** If an update is only partially applied to the target database by the
  177454. ** time sqlite3rbu_close() is called, various state information is saved
  177455. ** within the RBU database. This allows subsequent processes to automatically
  177456. ** resume the RBU update from where it left off.
  177457. **
  177458. ** To remove all RBU extension state information, returning an RBU database
  177459. ** to its original contents, it is sufficient to drop all tables that begin
  177460. ** with the prefix "rbu_"
  177461. **
  177462. ** DATABASE LOCKING
  177463. **
  177464. ** An RBU update may not be applied to a database in WAL mode. Attempting
  177465. ** to do so is an error (SQLITE_ERROR).
  177466. **
  177467. ** While an RBU handle is open, a SHARED lock may be held on the target
  177468. ** database file. This means it is possible for other clients to read the
  177469. ** database, but not to write it.
  177470. **
  177471. ** If an RBU update is started and then suspended before it is completed,
  177472. ** then an external client writes to the database, then attempting to resume
  177473. ** the suspended RBU update is also an error (SQLITE_BUSY).
  177474. */
  177475. #ifndef _SQLITE3RBU_H
  177476. #define _SQLITE3RBU_H
  177477. /* #include "sqlite3.h" ** Required for error code definitions ** */
  177478. #if 0
  177479. extern "C" {
  177480. #endif
  177481. typedef struct sqlite3rbu sqlite3rbu;
  177482. /*
  177483. ** Open an RBU handle.
  177484. **
  177485. ** Argument zTarget is the path to the target database. Argument zRbu is
  177486. ** the path to the RBU database. Each call to this function must be matched
  177487. ** by a call to sqlite3rbu_close(). When opening the databases, RBU passes
  177488. ** the SQLITE_CONFIG_URI flag to sqlite3_open_v2(). So if either zTarget
  177489. ** or zRbu begin with "file:", it will be interpreted as an SQLite
  177490. ** database URI, not a regular file name.
  177491. **
  177492. ** If the zState argument is passed a NULL value, the RBU extension stores
  177493. ** the current state of the update (how many rows have been updated, which
  177494. ** indexes are yet to be updated etc.) within the RBU database itself. This
  177495. ** can be convenient, as it means that the RBU application does not need to
  177496. ** organize removing a separate state file after the update is concluded.
  177497. ** Or, if zState is non-NULL, it must be a path to a database file in which
  177498. ** the RBU extension can store the state of the update.
  177499. **
  177500. ** When resuming an RBU update, the zState argument must be passed the same
  177501. ** value as when the RBU update was started.
  177502. **
  177503. ** Once the RBU update is finished, the RBU extension does not
  177504. ** automatically remove any zState database file, even if it created it.
  177505. **
  177506. ** By default, RBU uses the default VFS to access the files on disk. To
  177507. ** use a VFS other than the default, an SQLite "file:" URI containing a
  177508. ** "vfs=..." option may be passed as the zTarget option.
  177509. **
  177510. ** IMPORTANT NOTE FOR ZIPVFS USERS: The RBU extension works with all of
  177511. ** SQLite's built-in VFSs, including the multiplexor VFS. However it does
  177512. ** not work out of the box with zipvfs. Refer to the comment describing
  177513. ** the zipvfs_create_vfs() API below for details on using RBU with zipvfs.
  177514. */
  177515. SQLITE_API sqlite3rbu *sqlite3rbu_open(
  177516. const char *zTarget,
  177517. const char *zRbu,
  177518. const char *zState
  177519. );
  177520. /*
  177521. ** Open an RBU handle to perform an RBU vacuum on database file zTarget.
  177522. ** An RBU vacuum is similar to SQLite's built-in VACUUM command, except
  177523. ** that it can be suspended and resumed like an RBU update.
  177524. **
  177525. ** The second argument to this function identifies a database in which
  177526. ** to store the state of the RBU vacuum operation if it is suspended. The
  177527. ** first time sqlite3rbu_vacuum() is called, to start an RBU vacuum
  177528. ** operation, the state database should either not exist or be empty
  177529. ** (contain no tables). If an RBU vacuum is suspended by calling
  177530. ** sqlite3rbu_close() on the RBU handle before sqlite3rbu_step() has
  177531. ** returned SQLITE_DONE, the vacuum state is stored in the state database.
  177532. ** The vacuum can be resumed by calling this function to open a new RBU
  177533. ** handle specifying the same target and state databases.
  177534. **
  177535. ** If the second argument passed to this function is NULL, then the
  177536. ** name of the state database is "<database>-vacuum", where <database>
  177537. ** is the name of the target database file. In this case, on UNIX, if the
  177538. ** state database is not already present in the file-system, it is created
  177539. ** with the same permissions as the target db is made.
  177540. **
  177541. ** With an RBU vacuum, it is an SQLITE_MISUSE error if the name of the
  177542. ** state database ends with "-vactmp". This name is reserved for internal
  177543. ** use.
  177544. **
  177545. ** This function does not delete the state database after an RBU vacuum
  177546. ** is completed, even if it created it. However, if the call to
  177547. ** sqlite3rbu_close() returns any value other than SQLITE_OK, the contents
  177548. ** of the state tables within the state database are zeroed. This way,
  177549. ** the next call to sqlite3rbu_vacuum() opens a handle that starts a
  177550. ** new RBU vacuum operation.
  177551. **
  177552. ** As with sqlite3rbu_open(), Zipvfs users should rever to the comment
  177553. ** describing the sqlite3rbu_create_vfs() API function below for
  177554. ** a description of the complications associated with using RBU with
  177555. ** zipvfs databases.
  177556. */
  177557. SQLITE_API sqlite3rbu *sqlite3rbu_vacuum(
  177558. const char *zTarget,
  177559. const char *zState
  177560. );
  177561. /*
  177562. ** Configure a limit for the amount of temp space that may be used by
  177563. ** the RBU handle passed as the first argument. The new limit is specified
  177564. ** in bytes by the second parameter. If it is positive, the limit is updated.
  177565. ** If the second parameter to this function is passed zero, then the limit
  177566. ** is removed entirely. If the second parameter is negative, the limit is
  177567. ** not modified (this is useful for querying the current limit).
  177568. **
  177569. ** In all cases the returned value is the current limit in bytes (zero
  177570. ** indicates unlimited).
  177571. **
  177572. ** If the temp space limit is exceeded during operation, an SQLITE_FULL
  177573. ** error is returned.
  177574. */
  177575. SQLITE_API sqlite3_int64 sqlite3rbu_temp_size_limit(sqlite3rbu*, sqlite3_int64);
  177576. /*
  177577. ** Return the current amount of temp file space, in bytes, currently used by
  177578. ** the RBU handle passed as the only argument.
  177579. */
  177580. SQLITE_API sqlite3_int64 sqlite3rbu_temp_size(sqlite3rbu*);
  177581. /*
  177582. ** Internally, each RBU connection uses a separate SQLite database
  177583. ** connection to access the target and rbu update databases. This
  177584. ** API allows the application direct access to these database handles.
  177585. **
  177586. ** The first argument passed to this function must be a valid, open, RBU
  177587. ** handle. The second argument should be passed zero to access the target
  177588. ** database handle, or non-zero to access the rbu update database handle.
  177589. ** Accessing the underlying database handles may be useful in the
  177590. ** following scenarios:
  177591. **
  177592. ** * If any target tables are virtual tables, it may be necessary to
  177593. ** call sqlite3_create_module() on the target database handle to
  177594. ** register the required virtual table implementations.
  177595. **
  177596. ** * If the data_xxx tables in the RBU source database are virtual
  177597. ** tables, the application may need to call sqlite3_create_module() on
  177598. ** the rbu update db handle to any required virtual table
  177599. ** implementations.
  177600. **
  177601. ** * If the application uses the "rbu_delta()" feature described above,
  177602. ** it must use sqlite3_create_function() or similar to register the
  177603. ** rbu_delta() implementation with the target database handle.
  177604. **
  177605. ** If an error has occurred, either while opening or stepping the RBU object,
  177606. ** this function may return NULL. The error code and message may be collected
  177607. ** when sqlite3rbu_close() is called.
  177608. **
  177609. ** Database handles returned by this function remain valid until the next
  177610. ** call to any sqlite3rbu_xxx() function other than sqlite3rbu_db().
  177611. */
  177612. SQLITE_API sqlite3 *sqlite3rbu_db(sqlite3rbu*, int bRbu);
  177613. /*
  177614. ** Do some work towards applying the RBU update to the target db.
  177615. **
  177616. ** Return SQLITE_DONE if the update has been completely applied, or
  177617. ** SQLITE_OK if no error occurs but there remains work to do to apply
  177618. ** the RBU update. If an error does occur, some other error code is
  177619. ** returned.
  177620. **
  177621. ** Once a call to sqlite3rbu_step() has returned a value other than
  177622. ** SQLITE_OK, all subsequent calls on the same RBU handle are no-ops
  177623. ** that immediately return the same value.
  177624. */
  177625. SQLITE_API int sqlite3rbu_step(sqlite3rbu *pRbu);
  177626. /*
  177627. ** Force RBU to save its state to disk.
  177628. **
  177629. ** If a power failure or application crash occurs during an update, following
  177630. ** system recovery RBU may resume the update from the point at which the state
  177631. ** was last saved. In other words, from the most recent successful call to
  177632. ** sqlite3rbu_close() or this function.
  177633. **
  177634. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  177635. */
  177636. SQLITE_API int sqlite3rbu_savestate(sqlite3rbu *pRbu);
  177637. /*
  177638. ** Close an RBU handle.
  177639. **
  177640. ** If the RBU update has been completely applied, mark the RBU database
  177641. ** as fully applied. Otherwise, assuming no error has occurred, save the
  177642. ** current state of the RBU update appliation to the RBU database.
  177643. **
  177644. ** If an error has already occurred as part of an sqlite3rbu_step()
  177645. ** or sqlite3rbu_open() call, or if one occurs within this function, an
  177646. ** SQLite error code is returned. Additionally, if pzErrmsg is not NULL,
  177647. ** *pzErrmsg may be set to point to a buffer containing a utf-8 formatted
  177648. ** English language error message. It is the responsibility of the caller to
  177649. ** eventually free any such buffer using sqlite3_free().
  177650. **
  177651. ** Otherwise, if no error occurs, this function returns SQLITE_OK if the
  177652. ** update has been partially applied, or SQLITE_DONE if it has been
  177653. ** completely applied.
  177654. */
  177655. SQLITE_API int sqlite3rbu_close(sqlite3rbu *pRbu, char **pzErrmsg);
  177656. /*
  177657. ** Return the total number of key-value operations (inserts, deletes or
  177658. ** updates) that have been performed on the target database since the
  177659. ** current RBU update was started.
  177660. */
  177661. SQLITE_API sqlite3_int64 sqlite3rbu_progress(sqlite3rbu *pRbu);
  177662. /*
  177663. ** Obtain permyriadage (permyriadage is to 10000 as percentage is to 100)
  177664. ** progress indications for the two stages of an RBU update. This API may
  177665. ** be useful for driving GUI progress indicators and similar.
  177666. **
  177667. ** An RBU update is divided into two stages:
  177668. **
  177669. ** * Stage 1, in which changes are accumulated in an oal/wal file, and
  177670. ** * Stage 2, in which the contents of the wal file are copied into the
  177671. ** main database.
  177672. **
  177673. ** The update is visible to non-RBU clients during stage 2. During stage 1
  177674. ** non-RBU reader clients may see the original database.
  177675. **
  177676. ** If this API is called during stage 2 of the update, output variable
  177677. ** (*pnOne) is set to 10000 to indicate that stage 1 has finished and (*pnTwo)
  177678. ** to a value between 0 and 10000 to indicate the permyriadage progress of
  177679. ** stage 2. A value of 5000 indicates that stage 2 is half finished,
  177680. ** 9000 indicates that it is 90% finished, and so on.
  177681. **
  177682. ** If this API is called during stage 1 of the update, output variable
  177683. ** (*pnTwo) is set to 0 to indicate that stage 2 has not yet started. The
  177684. ** value to which (*pnOne) is set depends on whether or not the RBU
  177685. ** database contains an "rbu_count" table. The rbu_count table, if it
  177686. ** exists, must contain the same columns as the following:
  177687. **
  177688. ** CREATE TABLE rbu_count(tbl TEXT PRIMARY KEY, cnt INTEGER) WITHOUT ROWID;
  177689. **
  177690. ** There must be one row in the table for each source (data_xxx) table within
  177691. ** the RBU database. The 'tbl' column should contain the name of the source
  177692. ** table. The 'cnt' column should contain the number of rows within the
  177693. ** source table.
  177694. **
  177695. ** If the rbu_count table is present and populated correctly and this
  177696. ** API is called during stage 1, the *pnOne output variable is set to the
  177697. ** permyriadage progress of the same stage. If the rbu_count table does
  177698. ** not exist, then (*pnOne) is set to -1 during stage 1. If the rbu_count
  177699. ** table exists but is not correctly populated, the value of the *pnOne
  177700. ** output variable during stage 1 is undefined.
  177701. */
  177702. SQLITE_API void sqlite3rbu_bp_progress(sqlite3rbu *pRbu, int *pnOne, int*pnTwo);
  177703. /*
  177704. ** Obtain an indication as to the current stage of an RBU update or vacuum.
  177705. ** This function always returns one of the SQLITE_RBU_STATE_XXX constants
  177706. ** defined in this file. Return values should be interpreted as follows:
  177707. **
  177708. ** SQLITE_RBU_STATE_OAL:
  177709. ** RBU is currently building a *-oal file. The next call to sqlite3rbu_step()
  177710. ** may either add further data to the *-oal file, or compute data that will
  177711. ** be added by a subsequent call.
  177712. **
  177713. ** SQLITE_RBU_STATE_MOVE:
  177714. ** RBU has finished building the *-oal file. The next call to sqlite3rbu_step()
  177715. ** will move the *-oal file to the equivalent *-wal path. If the current
  177716. ** operation is an RBU update, then the updated version of the database
  177717. ** file will become visible to ordinary SQLite clients following the next
  177718. ** call to sqlite3rbu_step().
  177719. **
  177720. ** SQLITE_RBU_STATE_CHECKPOINT:
  177721. ** RBU is currently performing an incremental checkpoint. The next call to
  177722. ** sqlite3rbu_step() will copy a page of data from the *-wal file into
  177723. ** the target database file.
  177724. **
  177725. ** SQLITE_RBU_STATE_DONE:
  177726. ** The RBU operation has finished. Any subsequent calls to sqlite3rbu_step()
  177727. ** will immediately return SQLITE_DONE.
  177728. **
  177729. ** SQLITE_RBU_STATE_ERROR:
  177730. ** An error has occurred. Any subsequent calls to sqlite3rbu_step() will
  177731. ** immediately return the SQLite error code associated with the error.
  177732. */
  177733. #define SQLITE_RBU_STATE_OAL 1
  177734. #define SQLITE_RBU_STATE_MOVE 2
  177735. #define SQLITE_RBU_STATE_CHECKPOINT 3
  177736. #define SQLITE_RBU_STATE_DONE 4
  177737. #define SQLITE_RBU_STATE_ERROR 5
  177738. SQLITE_API int sqlite3rbu_state(sqlite3rbu *pRbu);
  177739. /*
  177740. ** Create an RBU VFS named zName that accesses the underlying file-system
  177741. ** via existing VFS zParent. Or, if the zParent parameter is passed NULL,
  177742. ** then the new RBU VFS uses the default system VFS to access the file-system.
  177743. ** The new object is registered as a non-default VFS with SQLite before
  177744. ** returning.
  177745. **
  177746. ** Part of the RBU implementation uses a custom VFS object. Usually, this
  177747. ** object is created and deleted automatically by RBU.
  177748. **
  177749. ** The exception is for applications that also use zipvfs. In this case,
  177750. ** the custom VFS must be explicitly created by the user before the RBU
  177751. ** handle is opened. The RBU VFS should be installed so that the zipvfs
  177752. ** VFS uses the RBU VFS, which in turn uses any other VFS layers in use
  177753. ** (for example multiplexor) to access the file-system. For example,
  177754. ** to assemble an RBU enabled VFS stack that uses both zipvfs and
  177755. ** multiplexor (error checking omitted):
  177756. **
  177757. ** // Create a VFS named "multiplex" (not the default).
  177758. ** sqlite3_multiplex_initialize(0, 0);
  177759. **
  177760. ** // Create an rbu VFS named "rbu" that uses multiplexor. If the
  177761. ** // second argument were replaced with NULL, the "rbu" VFS would
  177762. ** // access the file-system via the system default VFS, bypassing the
  177763. ** // multiplexor.
  177764. ** sqlite3rbu_create_vfs("rbu", "multiplex");
  177765. **
  177766. ** // Create a zipvfs VFS named "zipvfs" that uses rbu.
  177767. ** zipvfs_create_vfs_v3("zipvfs", "rbu", 0, xCompressorAlgorithmDetector);
  177768. **
  177769. ** // Make zipvfs the default VFS.
  177770. ** sqlite3_vfs_register(sqlite3_vfs_find("zipvfs"), 1);
  177771. **
  177772. ** Because the default VFS created above includes a RBU functionality, it
  177773. ** may be used by RBU clients. Attempting to use RBU with a zipvfs VFS stack
  177774. ** that does not include the RBU layer results in an error.
  177775. **
  177776. ** The overhead of adding the "rbu" VFS to the system is negligible for
  177777. ** non-RBU users. There is no harm in an application accessing the
  177778. ** file-system via "rbu" all the time, even if it only uses RBU functionality
  177779. ** occasionally.
  177780. */
  177781. SQLITE_API int sqlite3rbu_create_vfs(const char *zName, const char *zParent);
  177782. /*
  177783. ** Deregister and destroy an RBU vfs created by an earlier call to
  177784. ** sqlite3rbu_create_vfs().
  177785. **
  177786. ** VFS objects are not reference counted. If a VFS object is destroyed
  177787. ** before all database handles that use it have been closed, the results
  177788. ** are undefined.
  177789. */
  177790. SQLITE_API void sqlite3rbu_destroy_vfs(const char *zName);
  177791. #if 0
  177792. } /* end of the 'extern "C"' block */
  177793. #endif
  177794. #endif /* _SQLITE3RBU_H */
  177795. /************** End of sqlite3rbu.h ******************************************/
  177796. /************** Continuing where we left off in sqlite3rbu.c *****************/
  177797. #if defined(_WIN32_WCE)
  177798. /* #include "windows.h" */
  177799. #endif
  177800. /* Maximum number of prepared UPDATE statements held by this module */
  177801. #define SQLITE_RBU_UPDATE_CACHESIZE 16
  177802. /* Delta checksums disabled by default. Compile with -DRBU_ENABLE_DELTA_CKSUM
  177803. ** to enable checksum verification.
  177804. */
  177805. #ifndef RBU_ENABLE_DELTA_CKSUM
  177806. # define RBU_ENABLE_DELTA_CKSUM 0
  177807. #endif
  177808. /*
  177809. ** Swap two objects of type TYPE.
  177810. */
  177811. #if !defined(SQLITE_AMALGAMATION)
  177812. # define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
  177813. #endif
  177814. /*
  177815. ** The rbu_state table is used to save the state of a partially applied
  177816. ** update so that it can be resumed later. The table consists of integer
  177817. ** keys mapped to values as follows:
  177818. **
  177819. ** RBU_STATE_STAGE:
  177820. ** May be set to integer values 1, 2, 4 or 5. As follows:
  177821. ** 1: the *-rbu file is currently under construction.
  177822. ** 2: the *-rbu file has been constructed, but not yet moved
  177823. ** to the *-wal path.
  177824. ** 4: the checkpoint is underway.
  177825. ** 5: the rbu update has been checkpointed.
  177826. **
  177827. ** RBU_STATE_TBL:
  177828. ** Only valid if STAGE==1. The target database name of the table
  177829. ** currently being written.
  177830. **
  177831. ** RBU_STATE_IDX:
  177832. ** Only valid if STAGE==1. The target database name of the index
  177833. ** currently being written, or NULL if the main table is currently being
  177834. ** updated.
  177835. **
  177836. ** RBU_STATE_ROW:
  177837. ** Only valid if STAGE==1. Number of rows already processed for the current
  177838. ** table/index.
  177839. **
  177840. ** RBU_STATE_PROGRESS:
  177841. ** Trbul number of sqlite3rbu_step() calls made so far as part of this
  177842. ** rbu update.
  177843. **
  177844. ** RBU_STATE_CKPT:
  177845. ** Valid if STAGE==4. The 64-bit checksum associated with the wal-index
  177846. ** header created by recovering the *-wal file. This is used to detect
  177847. ** cases when another client appends frames to the *-wal file in the
  177848. ** middle of an incremental checkpoint (an incremental checkpoint cannot
  177849. ** be continued if this happens).
  177850. **
  177851. ** RBU_STATE_COOKIE:
  177852. ** Valid if STAGE==1. The current change-counter cookie value in the
  177853. ** target db file.
  177854. **
  177855. ** RBU_STATE_OALSZ:
  177856. ** Valid if STAGE==1. The size in bytes of the *-oal file.
  177857. **
  177858. ** RBU_STATE_DATATBL:
  177859. ** Only valid if STAGE==1. The RBU database name of the table
  177860. ** currently being read.
  177861. */
  177862. #define RBU_STATE_STAGE 1
  177863. #define RBU_STATE_TBL 2
  177864. #define RBU_STATE_IDX 3
  177865. #define RBU_STATE_ROW 4
  177866. #define RBU_STATE_PROGRESS 5
  177867. #define RBU_STATE_CKPT 6
  177868. #define RBU_STATE_COOKIE 7
  177869. #define RBU_STATE_OALSZ 8
  177870. #define RBU_STATE_PHASEONESTEP 9
  177871. #define RBU_STATE_DATATBL 10
  177872. #define RBU_STAGE_OAL 1
  177873. #define RBU_STAGE_MOVE 2
  177874. #define RBU_STAGE_CAPTURE 3
  177875. #define RBU_STAGE_CKPT 4
  177876. #define RBU_STAGE_DONE 5
  177877. #define RBU_CREATE_STATE \
  177878. "CREATE TABLE IF NOT EXISTS %s.rbu_state(k INTEGER PRIMARY KEY, v)"
  177879. typedef struct RbuFrame RbuFrame;
  177880. typedef struct RbuObjIter RbuObjIter;
  177881. typedef struct RbuState RbuState;
  177882. typedef struct rbu_vfs rbu_vfs;
  177883. typedef struct rbu_file rbu_file;
  177884. typedef struct RbuUpdateStmt RbuUpdateStmt;
  177885. #if !defined(SQLITE_AMALGAMATION)
  177886. typedef unsigned int u32;
  177887. typedef unsigned short u16;
  177888. typedef unsigned char u8;
  177889. typedef sqlite3_int64 i64;
  177890. #endif
  177891. /*
  177892. ** These values must match the values defined in wal.c for the equivalent
  177893. ** locks. These are not magic numbers as they are part of the SQLite file
  177894. ** format.
  177895. */
  177896. #define WAL_LOCK_WRITE 0
  177897. #define WAL_LOCK_CKPT 1
  177898. #define WAL_LOCK_READ0 3
  177899. #define SQLITE_FCNTL_RBUCNT 5149216
  177900. /*
  177901. ** A structure to store values read from the rbu_state table in memory.
  177902. */
  177903. struct RbuState {
  177904. int eStage;
  177905. char *zTbl;
  177906. char *zDataTbl;
  177907. char *zIdx;
  177908. i64 iWalCksum;
  177909. int nRow;
  177910. i64 nProgress;
  177911. u32 iCookie;
  177912. i64 iOalSz;
  177913. i64 nPhaseOneStep;
  177914. };
  177915. struct RbuUpdateStmt {
  177916. char *zMask; /* Copy of update mask used with pUpdate */
  177917. sqlite3_stmt *pUpdate; /* Last update statement (or NULL) */
  177918. RbuUpdateStmt *pNext;
  177919. };
  177920. /*
  177921. ** An iterator of this type is used to iterate through all objects in
  177922. ** the target database that require updating. For each such table, the
  177923. ** iterator visits, in order:
  177924. **
  177925. ** * the table itself,
  177926. ** * each index of the table (zero or more points to visit), and
  177927. ** * a special "cleanup table" state.
  177928. **
  177929. ** abIndexed:
  177930. ** If the table has no indexes on it, abIndexed is set to NULL. Otherwise,
  177931. ** it points to an array of flags nTblCol elements in size. The flag is
  177932. ** set for each column that is either a part of the PK or a part of an
  177933. ** index. Or clear otherwise.
  177934. **
  177935. ** If there are one or more partial indexes on the table, all fields of
  177936. ** this array set set to 1. This is because in that case, the module has
  177937. ** no way to tell which fields will be required to add and remove entries
  177938. ** from the partial indexes.
  177939. **
  177940. */
  177941. struct RbuObjIter {
  177942. sqlite3_stmt *pTblIter; /* Iterate through tables */
  177943. sqlite3_stmt *pIdxIter; /* Index iterator */
  177944. int nTblCol; /* Size of azTblCol[] array */
  177945. char **azTblCol; /* Array of unquoted target column names */
  177946. char **azTblType; /* Array of target column types */
  177947. int *aiSrcOrder; /* src table col -> target table col */
  177948. u8 *abTblPk; /* Array of flags, set on target PK columns */
  177949. u8 *abNotNull; /* Array of flags, set on NOT NULL columns */
  177950. u8 *abIndexed; /* Array of flags, set on indexed & PK cols */
  177951. int eType; /* Table type - an RBU_PK_XXX value */
  177952. /* Output variables. zTbl==0 implies EOF. */
  177953. int bCleanup; /* True in "cleanup" state */
  177954. const char *zTbl; /* Name of target db table */
  177955. const char *zDataTbl; /* Name of rbu db table (or null) */
  177956. const char *zIdx; /* Name of target db index (or null) */
  177957. int iTnum; /* Root page of current object */
  177958. int iPkTnum; /* If eType==EXTERNAL, root of PK index */
  177959. int bUnique; /* Current index is unique */
  177960. int nIndex; /* Number of aux. indexes on table zTbl */
  177961. /* Statements created by rbuObjIterPrepareAll() */
  177962. int nCol; /* Number of columns in current object */
  177963. sqlite3_stmt *pSelect; /* Source data */
  177964. sqlite3_stmt *pInsert; /* Statement for INSERT operations */
  177965. sqlite3_stmt *pDelete; /* Statement for DELETE ops */
  177966. sqlite3_stmt *pTmpInsert; /* Insert into rbu_tmp_$zDataTbl */
  177967. /* Last UPDATE used (for PK b-tree updates only), or NULL. */
  177968. RbuUpdateStmt *pRbuUpdate;
  177969. };
  177970. /*
  177971. ** Values for RbuObjIter.eType
  177972. **
  177973. ** 0: Table does not exist (error)
  177974. ** 1: Table has an implicit rowid.
  177975. ** 2: Table has an explicit IPK column.
  177976. ** 3: Table has an external PK index.
  177977. ** 4: Table is WITHOUT ROWID.
  177978. ** 5: Table is a virtual table.
  177979. */
  177980. #define RBU_PK_NOTABLE 0
  177981. #define RBU_PK_NONE 1
  177982. #define RBU_PK_IPK 2
  177983. #define RBU_PK_EXTERNAL 3
  177984. #define RBU_PK_WITHOUT_ROWID 4
  177985. #define RBU_PK_VTAB 5
  177986. /*
  177987. ** Within the RBU_STAGE_OAL stage, each call to sqlite3rbu_step() performs
  177988. ** one of the following operations.
  177989. */
  177990. #define RBU_INSERT 1 /* Insert on a main table b-tree */
  177991. #define RBU_DELETE 2 /* Delete a row from a main table b-tree */
  177992. #define RBU_REPLACE 3 /* Delete and then insert a row */
  177993. #define RBU_IDX_DELETE 4 /* Delete a row from an aux. index b-tree */
  177994. #define RBU_IDX_INSERT 5 /* Insert on an aux. index b-tree */
  177995. #define RBU_UPDATE 6 /* Update a row in a main table b-tree */
  177996. /*
  177997. ** A single step of an incremental checkpoint - frame iWalFrame of the wal
  177998. ** file should be copied to page iDbPage of the database file.
  177999. */
  178000. struct RbuFrame {
  178001. u32 iDbPage;
  178002. u32 iWalFrame;
  178003. };
  178004. /*
  178005. ** RBU handle.
  178006. **
  178007. ** nPhaseOneStep:
  178008. ** If the RBU database contains an rbu_count table, this value is set to
  178009. ** a running estimate of the number of b-tree operations required to
  178010. ** finish populating the *-oal file. This allows the sqlite3_bp_progress()
  178011. ** API to calculate the permyriadage progress of populating the *-oal file
  178012. ** using the formula:
  178013. **
  178014. ** permyriadage = (10000 * nProgress) / nPhaseOneStep
  178015. **
  178016. ** nPhaseOneStep is initialized to the sum of:
  178017. **
  178018. ** nRow * (nIndex + 1)
  178019. **
  178020. ** for all source tables in the RBU database, where nRow is the number
  178021. ** of rows in the source table and nIndex the number of indexes on the
  178022. ** corresponding target database table.
  178023. **
  178024. ** This estimate is accurate if the RBU update consists entirely of
  178025. ** INSERT operations. However, it is inaccurate if:
  178026. **
  178027. ** * the RBU update contains any UPDATE operations. If the PK specified
  178028. ** for an UPDATE operation does not exist in the target table, then
  178029. ** no b-tree operations are required on index b-trees. Or if the
  178030. ** specified PK does exist, then (nIndex*2) such operations are
  178031. ** required (one delete and one insert on each index b-tree).
  178032. **
  178033. ** * the RBU update contains any DELETE operations for which the specified
  178034. ** PK does not exist. In this case no operations are required on index
  178035. ** b-trees.
  178036. **
  178037. ** * the RBU update contains REPLACE operations. These are similar to
  178038. ** UPDATE operations.
  178039. **
  178040. ** nPhaseOneStep is updated to account for the conditions above during the
  178041. ** first pass of each source table. The updated nPhaseOneStep value is
  178042. ** stored in the rbu_state table if the RBU update is suspended.
  178043. */
  178044. struct sqlite3rbu {
  178045. int eStage; /* Value of RBU_STATE_STAGE field */
  178046. sqlite3 *dbMain; /* target database handle */
  178047. sqlite3 *dbRbu; /* rbu database handle */
  178048. char *zTarget; /* Path to target db */
  178049. char *zRbu; /* Path to rbu db */
  178050. char *zState; /* Path to state db (or NULL if zRbu) */
  178051. char zStateDb[5]; /* Db name for state ("stat" or "main") */
  178052. int rc; /* Value returned by last rbu_step() call */
  178053. char *zErrmsg; /* Error message if rc!=SQLITE_OK */
  178054. int nStep; /* Rows processed for current object */
  178055. int nProgress; /* Rows processed for all objects */
  178056. RbuObjIter objiter; /* Iterator for skipping through tbl/idx */
  178057. const char *zVfsName; /* Name of automatically created rbu vfs */
  178058. rbu_file *pTargetFd; /* File handle open on target db */
  178059. int nPagePerSector; /* Pages per sector for pTargetFd */
  178060. i64 iOalSz;
  178061. i64 nPhaseOneStep;
  178062. /* The following state variables are used as part of the incremental
  178063. ** checkpoint stage (eStage==RBU_STAGE_CKPT). See comments surrounding
  178064. ** function rbuSetupCheckpoint() for details. */
  178065. u32 iMaxFrame; /* Largest iWalFrame value in aFrame[] */
  178066. u32 mLock;
  178067. int nFrame; /* Entries in aFrame[] array */
  178068. int nFrameAlloc; /* Allocated size of aFrame[] array */
  178069. RbuFrame *aFrame;
  178070. int pgsz;
  178071. u8 *aBuf;
  178072. i64 iWalCksum;
  178073. i64 szTemp; /* Current size of all temp files in use */
  178074. i64 szTempLimit; /* Total size limit for temp files */
  178075. /* Used in RBU vacuum mode only */
  178076. int nRbu; /* Number of RBU VFS in the stack */
  178077. rbu_file *pRbuFd; /* Fd for main db of dbRbu */
  178078. };
  178079. /*
  178080. ** An rbu VFS is implemented using an instance of this structure.
  178081. **
  178082. ** Variable pRbu is only non-NULL for automatically created RBU VFS objects.
  178083. ** It is NULL for RBU VFS objects created explicitly using
  178084. ** sqlite3rbu_create_vfs(). It is used to track the total amount of temp
  178085. ** space used by the RBU handle.
  178086. */
  178087. struct rbu_vfs {
  178088. sqlite3_vfs base; /* rbu VFS shim methods */
  178089. sqlite3_vfs *pRealVfs; /* Underlying VFS */
  178090. sqlite3_mutex *mutex; /* Mutex to protect pMain */
  178091. sqlite3rbu *pRbu; /* Owner RBU object */
  178092. rbu_file *pMain; /* List of main db files */
  178093. rbu_file *pMainRbu; /* List of main db files with pRbu!=0 */
  178094. };
  178095. /*
  178096. ** Each file opened by an rbu VFS is represented by an instance of
  178097. ** the following structure.
  178098. **
  178099. ** If this is a temporary file (pRbu!=0 && flags&DELETE_ON_CLOSE), variable
  178100. ** "sz" is set to the current size of the database file.
  178101. */
  178102. struct rbu_file {
  178103. sqlite3_file base; /* sqlite3_file methods */
  178104. sqlite3_file *pReal; /* Underlying file handle */
  178105. rbu_vfs *pRbuVfs; /* Pointer to the rbu_vfs object */
  178106. sqlite3rbu *pRbu; /* Pointer to rbu object (rbu target only) */
  178107. i64 sz; /* Size of file in bytes (temp only) */
  178108. int openFlags; /* Flags this file was opened with */
  178109. u32 iCookie; /* Cookie value for main db files */
  178110. u8 iWriteVer; /* "write-version" value for main db files */
  178111. u8 bNolock; /* True to fail EXCLUSIVE locks */
  178112. int nShm; /* Number of entries in apShm[] array */
  178113. char **apShm; /* Array of mmap'd *-shm regions */
  178114. char *zDel; /* Delete this when closing file */
  178115. const char *zWal; /* Wal filename for this main db file */
  178116. rbu_file *pWalFd; /* Wal file descriptor for this main db */
  178117. rbu_file *pMainNext; /* Next MAIN_DB file */
  178118. rbu_file *pMainRbuNext; /* Next MAIN_DB file with pRbu!=0 */
  178119. };
  178120. /*
  178121. ** True for an RBU vacuum handle, or false otherwise.
  178122. */
  178123. #define rbuIsVacuum(p) ((p)->zTarget==0)
  178124. /*************************************************************************
  178125. ** The following three functions, found below:
  178126. **
  178127. ** rbuDeltaGetInt()
  178128. ** rbuDeltaChecksum()
  178129. ** rbuDeltaApply()
  178130. **
  178131. ** are lifted from the fossil source code (http://fossil-scm.org). They
  178132. ** are used to implement the scalar SQL function rbu_fossil_delta().
  178133. */
  178134. /*
  178135. ** Read bytes from *pz and convert them into a positive integer. When
  178136. ** finished, leave *pz pointing to the first character past the end of
  178137. ** the integer. The *pLen parameter holds the length of the string
  178138. ** in *pz and is decremented once for each character in the integer.
  178139. */
  178140. static unsigned int rbuDeltaGetInt(const char **pz, int *pLen){
  178141. static const signed char zValue[] = {
  178142. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  178143. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  178144. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  178145. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
  178146. -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
  178147. 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, 36,
  178148. -1, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
  178149. 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, -1, -1, -1, 63, -1,
  178150. };
  178151. unsigned int v = 0;
  178152. int c;
  178153. unsigned char *z = (unsigned char*)*pz;
  178154. unsigned char *zStart = z;
  178155. while( (c = zValue[0x7f&*(z++)])>=0 ){
  178156. v = (v<<6) + c;
  178157. }
  178158. z--;
  178159. *pLen -= z - zStart;
  178160. *pz = (char*)z;
  178161. return v;
  178162. }
  178163. #if RBU_ENABLE_DELTA_CKSUM
  178164. /*
  178165. ** Compute a 32-bit checksum on the N-byte buffer. Return the result.
  178166. */
  178167. static unsigned int rbuDeltaChecksum(const char *zIn, size_t N){
  178168. const unsigned char *z = (const unsigned char *)zIn;
  178169. unsigned sum0 = 0;
  178170. unsigned sum1 = 0;
  178171. unsigned sum2 = 0;
  178172. unsigned sum3 = 0;
  178173. while(N >= 16){
  178174. sum0 += ((unsigned)z[0] + z[4] + z[8] + z[12]);
  178175. sum1 += ((unsigned)z[1] + z[5] + z[9] + z[13]);
  178176. sum2 += ((unsigned)z[2] + z[6] + z[10]+ z[14]);
  178177. sum3 += ((unsigned)z[3] + z[7] + z[11]+ z[15]);
  178178. z += 16;
  178179. N -= 16;
  178180. }
  178181. while(N >= 4){
  178182. sum0 += z[0];
  178183. sum1 += z[1];
  178184. sum2 += z[2];
  178185. sum3 += z[3];
  178186. z += 4;
  178187. N -= 4;
  178188. }
  178189. sum3 += (sum2 << 8) + (sum1 << 16) + (sum0 << 24);
  178190. switch(N){
  178191. case 3: sum3 += (z[2] << 8);
  178192. case 2: sum3 += (z[1] << 16);
  178193. case 1: sum3 += (z[0] << 24);
  178194. default: ;
  178195. }
  178196. return sum3;
  178197. }
  178198. #endif
  178199. /*
  178200. ** Apply a delta.
  178201. **
  178202. ** The output buffer should be big enough to hold the whole output
  178203. ** file and a NUL terminator at the end. The delta_output_size()
  178204. ** routine will determine this size for you.
  178205. **
  178206. ** The delta string should be null-terminated. But the delta string
  178207. ** may contain embedded NUL characters (if the input and output are
  178208. ** binary files) so we also have to pass in the length of the delta in
  178209. ** the lenDelta parameter.
  178210. **
  178211. ** This function returns the size of the output file in bytes (excluding
  178212. ** the final NUL terminator character). Except, if the delta string is
  178213. ** malformed or intended for use with a source file other than zSrc,
  178214. ** then this routine returns -1.
  178215. **
  178216. ** Refer to the delta_create() documentation above for a description
  178217. ** of the delta file format.
  178218. */
  178219. static int rbuDeltaApply(
  178220. const char *zSrc, /* The source or pattern file */
  178221. int lenSrc, /* Length of the source file */
  178222. const char *zDelta, /* Delta to apply to the pattern */
  178223. int lenDelta, /* Length of the delta */
  178224. char *zOut /* Write the output into this preallocated buffer */
  178225. ){
  178226. unsigned int limit;
  178227. unsigned int total = 0;
  178228. #if RBU_ENABLE_DELTA_CKSUM
  178229. char *zOrigOut = zOut;
  178230. #endif
  178231. limit = rbuDeltaGetInt(&zDelta, &lenDelta);
  178232. if( *zDelta!='\n' ){
  178233. /* ERROR: size integer not terminated by "\n" */
  178234. return -1;
  178235. }
  178236. zDelta++; lenDelta--;
  178237. while( *zDelta && lenDelta>0 ){
  178238. unsigned int cnt, ofst;
  178239. cnt = rbuDeltaGetInt(&zDelta, &lenDelta);
  178240. switch( zDelta[0] ){
  178241. case '@': {
  178242. zDelta++; lenDelta--;
  178243. ofst = rbuDeltaGetInt(&zDelta, &lenDelta);
  178244. if( lenDelta>0 && zDelta[0]!=',' ){
  178245. /* ERROR: copy command not terminated by ',' */
  178246. return -1;
  178247. }
  178248. zDelta++; lenDelta--;
  178249. total += cnt;
  178250. if( total>limit ){
  178251. /* ERROR: copy exceeds output file size */
  178252. return -1;
  178253. }
  178254. if( (int)(ofst+cnt) > lenSrc ){
  178255. /* ERROR: copy extends past end of input */
  178256. return -1;
  178257. }
  178258. memcpy(zOut, &zSrc[ofst], cnt);
  178259. zOut += cnt;
  178260. break;
  178261. }
  178262. case ':': {
  178263. zDelta++; lenDelta--;
  178264. total += cnt;
  178265. if( total>limit ){
  178266. /* ERROR: insert command gives an output larger than predicted */
  178267. return -1;
  178268. }
  178269. if( (int)cnt>lenDelta ){
  178270. /* ERROR: insert count exceeds size of delta */
  178271. return -1;
  178272. }
  178273. memcpy(zOut, zDelta, cnt);
  178274. zOut += cnt;
  178275. zDelta += cnt;
  178276. lenDelta -= cnt;
  178277. break;
  178278. }
  178279. case ';': {
  178280. zDelta++; lenDelta--;
  178281. zOut[0] = 0;
  178282. #if RBU_ENABLE_DELTA_CKSUM
  178283. if( cnt!=rbuDeltaChecksum(zOrigOut, total) ){
  178284. /* ERROR: bad checksum */
  178285. return -1;
  178286. }
  178287. #endif
  178288. if( total!=limit ){
  178289. /* ERROR: generated size does not match predicted size */
  178290. return -1;
  178291. }
  178292. return total;
  178293. }
  178294. default: {
  178295. /* ERROR: unknown delta operator */
  178296. return -1;
  178297. }
  178298. }
  178299. }
  178300. /* ERROR: unterminated delta */
  178301. return -1;
  178302. }
  178303. static int rbuDeltaOutputSize(const char *zDelta, int lenDelta){
  178304. int size;
  178305. size = rbuDeltaGetInt(&zDelta, &lenDelta);
  178306. if( *zDelta!='\n' ){
  178307. /* ERROR: size integer not terminated by "\n" */
  178308. return -1;
  178309. }
  178310. return size;
  178311. }
  178312. /*
  178313. ** End of code taken from fossil.
  178314. *************************************************************************/
  178315. /*
  178316. ** Implementation of SQL scalar function rbu_fossil_delta().
  178317. **
  178318. ** This function applies a fossil delta patch to a blob. Exactly two
  178319. ** arguments must be passed to this function. The first is the blob to
  178320. ** patch and the second the patch to apply. If no error occurs, this
  178321. ** function returns the patched blob.
  178322. */
  178323. static void rbuFossilDeltaFunc(
  178324. sqlite3_context *context,
  178325. int argc,
  178326. sqlite3_value **argv
  178327. ){
  178328. const char *aDelta;
  178329. int nDelta;
  178330. const char *aOrig;
  178331. int nOrig;
  178332. int nOut;
  178333. int nOut2;
  178334. char *aOut;
  178335. assert( argc==2 );
  178336. nOrig = sqlite3_value_bytes(argv[0]);
  178337. aOrig = (const char*)sqlite3_value_blob(argv[0]);
  178338. nDelta = sqlite3_value_bytes(argv[1]);
  178339. aDelta = (const char*)sqlite3_value_blob(argv[1]);
  178340. /* Figure out the size of the output */
  178341. nOut = rbuDeltaOutputSize(aDelta, nDelta);
  178342. if( nOut<0 ){
  178343. sqlite3_result_error(context, "corrupt fossil delta", -1);
  178344. return;
  178345. }
  178346. aOut = sqlite3_malloc(nOut+1);
  178347. if( aOut==0 ){
  178348. sqlite3_result_error_nomem(context);
  178349. }else{
  178350. nOut2 = rbuDeltaApply(aOrig, nOrig, aDelta, nDelta, aOut);
  178351. if( nOut2!=nOut ){
  178352. sqlite3_free(aOut);
  178353. sqlite3_result_error(context, "corrupt fossil delta", -1);
  178354. }else{
  178355. sqlite3_result_blob(context, aOut, nOut, sqlite3_free);
  178356. }
  178357. }
  178358. }
  178359. /*
  178360. ** Prepare the SQL statement in buffer zSql against database handle db.
  178361. ** If successful, set *ppStmt to point to the new statement and return
  178362. ** SQLITE_OK.
  178363. **
  178364. ** Otherwise, if an error does occur, set *ppStmt to NULL and return
  178365. ** an SQLite error code. Additionally, set output variable *pzErrmsg to
  178366. ** point to a buffer containing an error message. It is the responsibility
  178367. ** of the caller to (eventually) free this buffer using sqlite3_free().
  178368. */
  178369. static int prepareAndCollectError(
  178370. sqlite3 *db,
  178371. sqlite3_stmt **ppStmt,
  178372. char **pzErrmsg,
  178373. const char *zSql
  178374. ){
  178375. int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
  178376. if( rc!=SQLITE_OK ){
  178377. *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  178378. *ppStmt = 0;
  178379. }
  178380. return rc;
  178381. }
  178382. /*
  178383. ** Reset the SQL statement passed as the first argument. Return a copy
  178384. ** of the value returned by sqlite3_reset().
  178385. **
  178386. ** If an error has occurred, then set *pzErrmsg to point to a buffer
  178387. ** containing an error message. It is the responsibility of the caller
  178388. ** to eventually free this buffer using sqlite3_free().
  178389. */
  178390. static int resetAndCollectError(sqlite3_stmt *pStmt, char **pzErrmsg){
  178391. int rc = sqlite3_reset(pStmt);
  178392. if( rc!=SQLITE_OK ){
  178393. *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(sqlite3_db_handle(pStmt)));
  178394. }
  178395. return rc;
  178396. }
  178397. /*
  178398. ** Unless it is NULL, argument zSql points to a buffer allocated using
  178399. ** sqlite3_malloc containing an SQL statement. This function prepares the SQL
  178400. ** statement against database db and frees the buffer. If statement
  178401. ** compilation is successful, *ppStmt is set to point to the new statement
  178402. ** handle and SQLITE_OK is returned.
  178403. **
  178404. ** Otherwise, if an error occurs, *ppStmt is set to NULL and an error code
  178405. ** returned. In this case, *pzErrmsg may also be set to point to an error
  178406. ** message. It is the responsibility of the caller to free this error message
  178407. ** buffer using sqlite3_free().
  178408. **
  178409. ** If argument zSql is NULL, this function assumes that an OOM has occurred.
  178410. ** In this case SQLITE_NOMEM is returned and *ppStmt set to NULL.
  178411. */
  178412. static int prepareFreeAndCollectError(
  178413. sqlite3 *db,
  178414. sqlite3_stmt **ppStmt,
  178415. char **pzErrmsg,
  178416. char *zSql
  178417. ){
  178418. int rc;
  178419. assert( *pzErrmsg==0 );
  178420. if( zSql==0 ){
  178421. rc = SQLITE_NOMEM;
  178422. *ppStmt = 0;
  178423. }else{
  178424. rc = prepareAndCollectError(db, ppStmt, pzErrmsg, zSql);
  178425. sqlite3_free(zSql);
  178426. }
  178427. return rc;
  178428. }
  178429. /*
  178430. ** Free the RbuObjIter.azTblCol[] and RbuObjIter.abTblPk[] arrays allocated
  178431. ** by an earlier call to rbuObjIterCacheTableInfo().
  178432. */
  178433. static void rbuObjIterFreeCols(RbuObjIter *pIter){
  178434. int i;
  178435. for(i=0; i<pIter->nTblCol; i++){
  178436. sqlite3_free(pIter->azTblCol[i]);
  178437. sqlite3_free(pIter->azTblType[i]);
  178438. }
  178439. sqlite3_free(pIter->azTblCol);
  178440. pIter->azTblCol = 0;
  178441. pIter->azTblType = 0;
  178442. pIter->aiSrcOrder = 0;
  178443. pIter->abTblPk = 0;
  178444. pIter->abNotNull = 0;
  178445. pIter->nTblCol = 0;
  178446. pIter->eType = 0; /* Invalid value */
  178447. }
  178448. /*
  178449. ** Finalize all statements and free all allocations that are specific to
  178450. ** the current object (table/index pair).
  178451. */
  178452. static void rbuObjIterClearStatements(RbuObjIter *pIter){
  178453. RbuUpdateStmt *pUp;
  178454. sqlite3_finalize(pIter->pSelect);
  178455. sqlite3_finalize(pIter->pInsert);
  178456. sqlite3_finalize(pIter->pDelete);
  178457. sqlite3_finalize(pIter->pTmpInsert);
  178458. pUp = pIter->pRbuUpdate;
  178459. while( pUp ){
  178460. RbuUpdateStmt *pTmp = pUp->pNext;
  178461. sqlite3_finalize(pUp->pUpdate);
  178462. sqlite3_free(pUp);
  178463. pUp = pTmp;
  178464. }
  178465. pIter->pSelect = 0;
  178466. pIter->pInsert = 0;
  178467. pIter->pDelete = 0;
  178468. pIter->pRbuUpdate = 0;
  178469. pIter->pTmpInsert = 0;
  178470. pIter->nCol = 0;
  178471. }
  178472. /*
  178473. ** Clean up any resources allocated as part of the iterator object passed
  178474. ** as the only argument.
  178475. */
  178476. static void rbuObjIterFinalize(RbuObjIter *pIter){
  178477. rbuObjIterClearStatements(pIter);
  178478. sqlite3_finalize(pIter->pTblIter);
  178479. sqlite3_finalize(pIter->pIdxIter);
  178480. rbuObjIterFreeCols(pIter);
  178481. memset(pIter, 0, sizeof(RbuObjIter));
  178482. }
  178483. /*
  178484. ** Advance the iterator to the next position.
  178485. **
  178486. ** If no error occurs, SQLITE_OK is returned and the iterator is left
  178487. ** pointing to the next entry. Otherwise, an error code and message is
  178488. ** left in the RBU handle passed as the first argument. A copy of the
  178489. ** error code is returned.
  178490. */
  178491. static int rbuObjIterNext(sqlite3rbu *p, RbuObjIter *pIter){
  178492. int rc = p->rc;
  178493. if( rc==SQLITE_OK ){
  178494. /* Free any SQLite statements used while processing the previous object */
  178495. rbuObjIterClearStatements(pIter);
  178496. if( pIter->zIdx==0 ){
  178497. rc = sqlite3_exec(p->dbMain,
  178498. "DROP TRIGGER IF EXISTS temp.rbu_insert_tr;"
  178499. "DROP TRIGGER IF EXISTS temp.rbu_update1_tr;"
  178500. "DROP TRIGGER IF EXISTS temp.rbu_update2_tr;"
  178501. "DROP TRIGGER IF EXISTS temp.rbu_delete_tr;"
  178502. , 0, 0, &p->zErrmsg
  178503. );
  178504. }
  178505. if( rc==SQLITE_OK ){
  178506. if( pIter->bCleanup ){
  178507. rbuObjIterFreeCols(pIter);
  178508. pIter->bCleanup = 0;
  178509. rc = sqlite3_step(pIter->pTblIter);
  178510. if( rc!=SQLITE_ROW ){
  178511. rc = resetAndCollectError(pIter->pTblIter, &p->zErrmsg);
  178512. pIter->zTbl = 0;
  178513. }else{
  178514. pIter->zTbl = (const char*)sqlite3_column_text(pIter->pTblIter, 0);
  178515. pIter->zDataTbl = (const char*)sqlite3_column_text(pIter->pTblIter,1);
  178516. rc = (pIter->zDataTbl && pIter->zTbl) ? SQLITE_OK : SQLITE_NOMEM;
  178517. }
  178518. }else{
  178519. if( pIter->zIdx==0 ){
  178520. sqlite3_stmt *pIdx = pIter->pIdxIter;
  178521. rc = sqlite3_bind_text(pIdx, 1, pIter->zTbl, -1, SQLITE_STATIC);
  178522. }
  178523. if( rc==SQLITE_OK ){
  178524. rc = sqlite3_step(pIter->pIdxIter);
  178525. if( rc!=SQLITE_ROW ){
  178526. rc = resetAndCollectError(pIter->pIdxIter, &p->zErrmsg);
  178527. pIter->bCleanup = 1;
  178528. pIter->zIdx = 0;
  178529. }else{
  178530. pIter->zIdx = (const char*)sqlite3_column_text(pIter->pIdxIter, 0);
  178531. pIter->iTnum = sqlite3_column_int(pIter->pIdxIter, 1);
  178532. pIter->bUnique = sqlite3_column_int(pIter->pIdxIter, 2);
  178533. rc = pIter->zIdx ? SQLITE_OK : SQLITE_NOMEM;
  178534. }
  178535. }
  178536. }
  178537. }
  178538. }
  178539. if( rc!=SQLITE_OK ){
  178540. rbuObjIterFinalize(pIter);
  178541. p->rc = rc;
  178542. }
  178543. return rc;
  178544. }
  178545. /*
  178546. ** The implementation of the rbu_target_name() SQL function. This function
  178547. ** accepts one or two arguments. The first argument is the name of a table -
  178548. ** the name of a table in the RBU database. The second, if it is present, is 1
  178549. ** for a view or 0 for a table.
  178550. **
  178551. ** For a non-vacuum RBU handle, if the table name matches the pattern:
  178552. **
  178553. ** data[0-9]_<name>
  178554. **
  178555. ** where <name> is any sequence of 1 or more characters, <name> is returned.
  178556. ** Otherwise, if the only argument does not match the above pattern, an SQL
  178557. ** NULL is returned.
  178558. **
  178559. ** "data_t1" -> "t1"
  178560. ** "data0123_t2" -> "t2"
  178561. ** "dataAB_t3" -> NULL
  178562. **
  178563. ** For an rbu vacuum handle, a copy of the first argument is returned if
  178564. ** the second argument is either missing or 0 (not a view).
  178565. */
  178566. static void rbuTargetNameFunc(
  178567. sqlite3_context *pCtx,
  178568. int argc,
  178569. sqlite3_value **argv
  178570. ){
  178571. sqlite3rbu *p = sqlite3_user_data(pCtx);
  178572. const char *zIn;
  178573. assert( argc==1 || argc==2 );
  178574. zIn = (const char*)sqlite3_value_text(argv[0]);
  178575. if( zIn ){
  178576. if( rbuIsVacuum(p) ){
  178577. assert( argc==2 );
  178578. if( 0==sqlite3_value_int(argv[1]) ){
  178579. sqlite3_result_text(pCtx, zIn, -1, SQLITE_STATIC);
  178580. }
  178581. }else{
  178582. if( strlen(zIn)>4 && memcmp("data", zIn, 4)==0 ){
  178583. int i;
  178584. for(i=4; zIn[i]>='0' && zIn[i]<='9'; i++);
  178585. if( zIn[i]=='_' && zIn[i+1] ){
  178586. sqlite3_result_text(pCtx, &zIn[i+1], -1, SQLITE_STATIC);
  178587. }
  178588. }
  178589. }
  178590. }
  178591. }
  178592. /*
  178593. ** Initialize the iterator structure passed as the second argument.
  178594. **
  178595. ** If no error occurs, SQLITE_OK is returned and the iterator is left
  178596. ** pointing to the first entry. Otherwise, an error code and message is
  178597. ** left in the RBU handle passed as the first argument. A copy of the
  178598. ** error code is returned.
  178599. */
  178600. static int rbuObjIterFirst(sqlite3rbu *p, RbuObjIter *pIter){
  178601. int rc;
  178602. memset(pIter, 0, sizeof(RbuObjIter));
  178603. rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pTblIter, &p->zErrmsg,
  178604. sqlite3_mprintf(
  178605. "SELECT rbu_target_name(name, type='view') AS target, name "
  178606. "FROM sqlite_master "
  178607. "WHERE type IN ('table', 'view') AND target IS NOT NULL "
  178608. " %s "
  178609. "ORDER BY name"
  178610. , rbuIsVacuum(p) ? "AND rootpage!=0 AND rootpage IS NOT NULL" : ""));
  178611. if( rc==SQLITE_OK ){
  178612. rc = prepareAndCollectError(p->dbMain, &pIter->pIdxIter, &p->zErrmsg,
  178613. "SELECT name, rootpage, sql IS NULL OR substr(8, 6)=='UNIQUE' "
  178614. " FROM main.sqlite_master "
  178615. " WHERE type='index' AND tbl_name = ?"
  178616. );
  178617. }
  178618. pIter->bCleanup = 1;
  178619. p->rc = rc;
  178620. return rbuObjIterNext(p, pIter);
  178621. }
  178622. /*
  178623. ** This is a wrapper around "sqlite3_mprintf(zFmt, ...)". If an OOM occurs,
  178624. ** an error code is stored in the RBU handle passed as the first argument.
  178625. **
  178626. ** If an error has already occurred (p->rc is already set to something other
  178627. ** than SQLITE_OK), then this function returns NULL without modifying the
  178628. ** stored error code. In this case it still calls sqlite3_free() on any
  178629. ** printf() parameters associated with %z conversions.
  178630. */
  178631. static char *rbuMPrintf(sqlite3rbu *p, const char *zFmt, ...){
  178632. char *zSql = 0;
  178633. va_list ap;
  178634. va_start(ap, zFmt);
  178635. zSql = sqlite3_vmprintf(zFmt, ap);
  178636. if( p->rc==SQLITE_OK ){
  178637. if( zSql==0 ) p->rc = SQLITE_NOMEM;
  178638. }else{
  178639. sqlite3_free(zSql);
  178640. zSql = 0;
  178641. }
  178642. va_end(ap);
  178643. return zSql;
  178644. }
  178645. /*
  178646. ** Argument zFmt is a sqlite3_mprintf() style format string. The trailing
  178647. ** arguments are the usual subsitution values. This function performs
  178648. ** the printf() style substitutions and executes the result as an SQL
  178649. ** statement on the RBU handles database.
  178650. **
  178651. ** If an error occurs, an error code and error message is stored in the
  178652. ** RBU handle. If an error has already occurred when this function is
  178653. ** called, it is a no-op.
  178654. */
  178655. static int rbuMPrintfExec(sqlite3rbu *p, sqlite3 *db, const char *zFmt, ...){
  178656. va_list ap;
  178657. char *zSql;
  178658. va_start(ap, zFmt);
  178659. zSql = sqlite3_vmprintf(zFmt, ap);
  178660. if( p->rc==SQLITE_OK ){
  178661. if( zSql==0 ){
  178662. p->rc = SQLITE_NOMEM;
  178663. }else{
  178664. p->rc = sqlite3_exec(db, zSql, 0, 0, &p->zErrmsg);
  178665. }
  178666. }
  178667. sqlite3_free(zSql);
  178668. va_end(ap);
  178669. return p->rc;
  178670. }
  178671. /*
  178672. ** Attempt to allocate and return a pointer to a zeroed block of nByte
  178673. ** bytes.
  178674. **
  178675. ** If an error (i.e. an OOM condition) occurs, return NULL and leave an
  178676. ** error code in the rbu handle passed as the first argument. Or, if an
  178677. ** error has already occurred when this function is called, return NULL
  178678. ** immediately without attempting the allocation or modifying the stored
  178679. ** error code.
  178680. */
  178681. static void *rbuMalloc(sqlite3rbu *p, sqlite3_int64 nByte){
  178682. void *pRet = 0;
  178683. if( p->rc==SQLITE_OK ){
  178684. assert( nByte>0 );
  178685. pRet = sqlite3_malloc64(nByte);
  178686. if( pRet==0 ){
  178687. p->rc = SQLITE_NOMEM;
  178688. }else{
  178689. memset(pRet, 0, nByte);
  178690. }
  178691. }
  178692. return pRet;
  178693. }
  178694. /*
  178695. ** Allocate and zero the pIter->azTblCol[] and abTblPk[] arrays so that
  178696. ** there is room for at least nCol elements. If an OOM occurs, store an
  178697. ** error code in the RBU handle passed as the first argument.
  178698. */
  178699. static void rbuAllocateIterArrays(sqlite3rbu *p, RbuObjIter *pIter, int nCol){
  178700. sqlite3_int64 nByte = (2*sizeof(char*) + sizeof(int) + 3*sizeof(u8)) * nCol;
  178701. char **azNew;
  178702. azNew = (char**)rbuMalloc(p, nByte);
  178703. if( azNew ){
  178704. pIter->azTblCol = azNew;
  178705. pIter->azTblType = &azNew[nCol];
  178706. pIter->aiSrcOrder = (int*)&pIter->azTblType[nCol];
  178707. pIter->abTblPk = (u8*)&pIter->aiSrcOrder[nCol];
  178708. pIter->abNotNull = (u8*)&pIter->abTblPk[nCol];
  178709. pIter->abIndexed = (u8*)&pIter->abNotNull[nCol];
  178710. }
  178711. }
  178712. /*
  178713. ** The first argument must be a nul-terminated string. This function
  178714. ** returns a copy of the string in memory obtained from sqlite3_malloc().
  178715. ** It is the responsibility of the caller to eventually free this memory
  178716. ** using sqlite3_free().
  178717. **
  178718. ** If an OOM condition is encountered when attempting to allocate memory,
  178719. ** output variable (*pRc) is set to SQLITE_NOMEM before returning. Otherwise,
  178720. ** if the allocation succeeds, (*pRc) is left unchanged.
  178721. */
  178722. static char *rbuStrndup(const char *zStr, int *pRc){
  178723. char *zRet = 0;
  178724. assert( *pRc==SQLITE_OK );
  178725. if( zStr ){
  178726. size_t nCopy = strlen(zStr) + 1;
  178727. zRet = (char*)sqlite3_malloc64(nCopy);
  178728. if( zRet ){
  178729. memcpy(zRet, zStr, nCopy);
  178730. }else{
  178731. *pRc = SQLITE_NOMEM;
  178732. }
  178733. }
  178734. return zRet;
  178735. }
  178736. /*
  178737. ** Finalize the statement passed as the second argument.
  178738. **
  178739. ** If the sqlite3_finalize() call indicates that an error occurs, and the
  178740. ** rbu handle error code is not already set, set the error code and error
  178741. ** message accordingly.
  178742. */
  178743. static void rbuFinalize(sqlite3rbu *p, sqlite3_stmt *pStmt){
  178744. sqlite3 *db = sqlite3_db_handle(pStmt);
  178745. int rc = sqlite3_finalize(pStmt);
  178746. if( p->rc==SQLITE_OK && rc!=SQLITE_OK ){
  178747. p->rc = rc;
  178748. p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  178749. }
  178750. }
  178751. /* Determine the type of a table.
  178752. **
  178753. ** peType is of type (int*), a pointer to an output parameter of type
  178754. ** (int). This call sets the output parameter as follows, depending
  178755. ** on the type of the table specified by parameters dbName and zTbl.
  178756. **
  178757. ** RBU_PK_NOTABLE: No such table.
  178758. ** RBU_PK_NONE: Table has an implicit rowid.
  178759. ** RBU_PK_IPK: Table has an explicit IPK column.
  178760. ** RBU_PK_EXTERNAL: Table has an external PK index.
  178761. ** RBU_PK_WITHOUT_ROWID: Table is WITHOUT ROWID.
  178762. ** RBU_PK_VTAB: Table is a virtual table.
  178763. **
  178764. ** Argument *piPk is also of type (int*), and also points to an output
  178765. ** parameter. Unless the table has an external primary key index
  178766. ** (i.e. unless *peType is set to 3), then *piPk is set to zero. Or,
  178767. ** if the table does have an external primary key index, then *piPk
  178768. ** is set to the root page number of the primary key index before
  178769. ** returning.
  178770. **
  178771. ** ALGORITHM:
  178772. **
  178773. ** if( no entry exists in sqlite_master ){
  178774. ** return RBU_PK_NOTABLE
  178775. ** }else if( sql for the entry starts with "CREATE VIRTUAL" ){
  178776. ** return RBU_PK_VTAB
  178777. ** }else if( "PRAGMA index_list()" for the table contains a "pk" index ){
  178778. ** if( the index that is the pk exists in sqlite_master ){
  178779. ** *piPK = rootpage of that index.
  178780. ** return RBU_PK_EXTERNAL
  178781. ** }else{
  178782. ** return RBU_PK_WITHOUT_ROWID
  178783. ** }
  178784. ** }else if( "PRAGMA table_info()" lists one or more "pk" columns ){
  178785. ** return RBU_PK_IPK
  178786. ** }else{
  178787. ** return RBU_PK_NONE
  178788. ** }
  178789. */
  178790. static void rbuTableType(
  178791. sqlite3rbu *p,
  178792. const char *zTab,
  178793. int *peType,
  178794. int *piTnum,
  178795. int *piPk
  178796. ){
  178797. /*
  178798. ** 0) SELECT count(*) FROM sqlite_master where name=%Q AND IsVirtual(%Q)
  178799. ** 1) PRAGMA index_list = ?
  178800. ** 2) SELECT count(*) FROM sqlite_master where name=%Q
  178801. ** 3) PRAGMA table_info = ?
  178802. */
  178803. sqlite3_stmt *aStmt[4] = {0, 0, 0, 0};
  178804. *peType = RBU_PK_NOTABLE;
  178805. *piPk = 0;
  178806. assert( p->rc==SQLITE_OK );
  178807. p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[0], &p->zErrmsg,
  178808. sqlite3_mprintf(
  178809. "SELECT (sql LIKE 'create virtual%%'), rootpage"
  178810. " FROM sqlite_master"
  178811. " WHERE name=%Q", zTab
  178812. ));
  178813. if( p->rc!=SQLITE_OK || sqlite3_step(aStmt[0])!=SQLITE_ROW ){
  178814. /* Either an error, or no such table. */
  178815. goto rbuTableType_end;
  178816. }
  178817. if( sqlite3_column_int(aStmt[0], 0) ){
  178818. *peType = RBU_PK_VTAB; /* virtual table */
  178819. goto rbuTableType_end;
  178820. }
  178821. *piTnum = sqlite3_column_int(aStmt[0], 1);
  178822. p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[1], &p->zErrmsg,
  178823. sqlite3_mprintf("PRAGMA index_list=%Q",zTab)
  178824. );
  178825. if( p->rc ) goto rbuTableType_end;
  178826. while( sqlite3_step(aStmt[1])==SQLITE_ROW ){
  178827. const u8 *zOrig = sqlite3_column_text(aStmt[1], 3);
  178828. const u8 *zIdx = sqlite3_column_text(aStmt[1], 1);
  178829. if( zOrig && zIdx && zOrig[0]=='p' ){
  178830. p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[2], &p->zErrmsg,
  178831. sqlite3_mprintf(
  178832. "SELECT rootpage FROM sqlite_master WHERE name = %Q", zIdx
  178833. ));
  178834. if( p->rc==SQLITE_OK ){
  178835. if( sqlite3_step(aStmt[2])==SQLITE_ROW ){
  178836. *piPk = sqlite3_column_int(aStmt[2], 0);
  178837. *peType = RBU_PK_EXTERNAL;
  178838. }else{
  178839. *peType = RBU_PK_WITHOUT_ROWID;
  178840. }
  178841. }
  178842. goto rbuTableType_end;
  178843. }
  178844. }
  178845. p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[3], &p->zErrmsg,
  178846. sqlite3_mprintf("PRAGMA table_info=%Q",zTab)
  178847. );
  178848. if( p->rc==SQLITE_OK ){
  178849. while( sqlite3_step(aStmt[3])==SQLITE_ROW ){
  178850. if( sqlite3_column_int(aStmt[3],5)>0 ){
  178851. *peType = RBU_PK_IPK; /* explicit IPK column */
  178852. goto rbuTableType_end;
  178853. }
  178854. }
  178855. *peType = RBU_PK_NONE;
  178856. }
  178857. rbuTableType_end: {
  178858. unsigned int i;
  178859. for(i=0; i<sizeof(aStmt)/sizeof(aStmt[0]); i++){
  178860. rbuFinalize(p, aStmt[i]);
  178861. }
  178862. }
  178863. }
  178864. /*
  178865. ** This is a helper function for rbuObjIterCacheTableInfo(). It populates
  178866. ** the pIter->abIndexed[] array.
  178867. */
  178868. static void rbuObjIterCacheIndexedCols(sqlite3rbu *p, RbuObjIter *pIter){
  178869. sqlite3_stmt *pList = 0;
  178870. int bIndex = 0;
  178871. if( p->rc==SQLITE_OK ){
  178872. memcpy(pIter->abIndexed, pIter->abTblPk, sizeof(u8)*pIter->nTblCol);
  178873. p->rc = prepareFreeAndCollectError(p->dbMain, &pList, &p->zErrmsg,
  178874. sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
  178875. );
  178876. }
  178877. pIter->nIndex = 0;
  178878. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pList) ){
  178879. const char *zIdx = (const char*)sqlite3_column_text(pList, 1);
  178880. int bPartial = sqlite3_column_int(pList, 4);
  178881. sqlite3_stmt *pXInfo = 0;
  178882. if( zIdx==0 ) break;
  178883. if( bPartial ){
  178884. memset(pIter->abIndexed, 0x01, sizeof(u8)*pIter->nTblCol);
  178885. }
  178886. p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
  178887. sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
  178888. );
  178889. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
  178890. int iCid = sqlite3_column_int(pXInfo, 1);
  178891. if( iCid>=0 ) pIter->abIndexed[iCid] = 1;
  178892. }
  178893. rbuFinalize(p, pXInfo);
  178894. bIndex = 1;
  178895. pIter->nIndex++;
  178896. }
  178897. if( pIter->eType==RBU_PK_WITHOUT_ROWID ){
  178898. /* "PRAGMA index_list" includes the main PK b-tree */
  178899. pIter->nIndex--;
  178900. }
  178901. rbuFinalize(p, pList);
  178902. if( bIndex==0 ) pIter->abIndexed = 0;
  178903. }
  178904. /*
  178905. ** If they are not already populated, populate the pIter->azTblCol[],
  178906. ** pIter->abTblPk[], pIter->nTblCol and pIter->bRowid variables according to
  178907. ** the table (not index) that the iterator currently points to.
  178908. **
  178909. ** Return SQLITE_OK if successful, or an SQLite error code otherwise. If
  178910. ** an error does occur, an error code and error message are also left in
  178911. ** the RBU handle.
  178912. */
  178913. static int rbuObjIterCacheTableInfo(sqlite3rbu *p, RbuObjIter *pIter){
  178914. if( pIter->azTblCol==0 ){
  178915. sqlite3_stmt *pStmt = 0;
  178916. int nCol = 0;
  178917. int i; /* for() loop iterator variable */
  178918. int bRbuRowid = 0; /* If input table has column "rbu_rowid" */
  178919. int iOrder = 0;
  178920. int iTnum = 0;
  178921. /* Figure out the type of table this step will deal with. */
  178922. assert( pIter->eType==0 );
  178923. rbuTableType(p, pIter->zTbl, &pIter->eType, &iTnum, &pIter->iPkTnum);
  178924. if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_NOTABLE ){
  178925. p->rc = SQLITE_ERROR;
  178926. p->zErrmsg = sqlite3_mprintf("no such table: %s", pIter->zTbl);
  178927. }
  178928. if( p->rc ) return p->rc;
  178929. if( pIter->zIdx==0 ) pIter->iTnum = iTnum;
  178930. assert( pIter->eType==RBU_PK_NONE || pIter->eType==RBU_PK_IPK
  178931. || pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_WITHOUT_ROWID
  178932. || pIter->eType==RBU_PK_VTAB
  178933. );
  178934. /* Populate the azTblCol[] and nTblCol variables based on the columns
  178935. ** of the input table. Ignore any input table columns that begin with
  178936. ** "rbu_". */
  178937. p->rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
  178938. sqlite3_mprintf("SELECT * FROM '%q'", pIter->zDataTbl)
  178939. );
  178940. if( p->rc==SQLITE_OK ){
  178941. nCol = sqlite3_column_count(pStmt);
  178942. rbuAllocateIterArrays(p, pIter, nCol);
  178943. }
  178944. for(i=0; p->rc==SQLITE_OK && i<nCol; i++){
  178945. const char *zName = (const char*)sqlite3_column_name(pStmt, i);
  178946. if( sqlite3_strnicmp("rbu_", zName, 4) ){
  178947. char *zCopy = rbuStrndup(zName, &p->rc);
  178948. pIter->aiSrcOrder[pIter->nTblCol] = pIter->nTblCol;
  178949. pIter->azTblCol[pIter->nTblCol++] = zCopy;
  178950. }
  178951. else if( 0==sqlite3_stricmp("rbu_rowid", zName) ){
  178952. bRbuRowid = 1;
  178953. }
  178954. }
  178955. sqlite3_finalize(pStmt);
  178956. pStmt = 0;
  178957. if( p->rc==SQLITE_OK
  178958. && rbuIsVacuum(p)==0
  178959. && bRbuRowid!=(pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
  178960. ){
  178961. p->rc = SQLITE_ERROR;
  178962. p->zErrmsg = sqlite3_mprintf(
  178963. "table %q %s rbu_rowid column", pIter->zDataTbl,
  178964. (bRbuRowid ? "may not have" : "requires")
  178965. );
  178966. }
  178967. /* Check that all non-HIDDEN columns in the destination table are also
  178968. ** present in the input table. Populate the abTblPk[], azTblType[] and
  178969. ** aiTblOrder[] arrays at the same time. */
  178970. if( p->rc==SQLITE_OK ){
  178971. p->rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &p->zErrmsg,
  178972. sqlite3_mprintf("PRAGMA table_info(%Q)", pIter->zTbl)
  178973. );
  178974. }
  178975. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  178976. const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
  178977. if( zName==0 ) break; /* An OOM - finalize() below returns S_NOMEM */
  178978. for(i=iOrder; i<pIter->nTblCol; i++){
  178979. if( 0==strcmp(zName, pIter->azTblCol[i]) ) break;
  178980. }
  178981. if( i==pIter->nTblCol ){
  178982. p->rc = SQLITE_ERROR;
  178983. p->zErrmsg = sqlite3_mprintf("column missing from %q: %s",
  178984. pIter->zDataTbl, zName
  178985. );
  178986. }else{
  178987. int iPk = sqlite3_column_int(pStmt, 5);
  178988. int bNotNull = sqlite3_column_int(pStmt, 3);
  178989. const char *zType = (const char*)sqlite3_column_text(pStmt, 2);
  178990. if( i!=iOrder ){
  178991. SWAP(int, pIter->aiSrcOrder[i], pIter->aiSrcOrder[iOrder]);
  178992. SWAP(char*, pIter->azTblCol[i], pIter->azTblCol[iOrder]);
  178993. }
  178994. pIter->azTblType[iOrder] = rbuStrndup(zType, &p->rc);
  178995. assert( iPk>=0 );
  178996. pIter->abTblPk[iOrder] = (u8)iPk;
  178997. pIter->abNotNull[iOrder] = (u8)bNotNull || (iPk!=0);
  178998. iOrder++;
  178999. }
  179000. }
  179001. rbuFinalize(p, pStmt);
  179002. rbuObjIterCacheIndexedCols(p, pIter);
  179003. assert( pIter->eType!=RBU_PK_VTAB || pIter->abIndexed==0 );
  179004. assert( pIter->eType!=RBU_PK_VTAB || pIter->nIndex==0 );
  179005. }
  179006. return p->rc;
  179007. }
  179008. /*
  179009. ** This function constructs and returns a pointer to a nul-terminated
  179010. ** string containing some SQL clause or list based on one or more of the
  179011. ** column names currently stored in the pIter->azTblCol[] array.
  179012. */
  179013. static char *rbuObjIterGetCollist(
  179014. sqlite3rbu *p, /* RBU object */
  179015. RbuObjIter *pIter /* Object iterator for column names */
  179016. ){
  179017. char *zList = 0;
  179018. const char *zSep = "";
  179019. int i;
  179020. for(i=0; i<pIter->nTblCol; i++){
  179021. const char *z = pIter->azTblCol[i];
  179022. zList = rbuMPrintf(p, "%z%s\"%w\"", zList, zSep, z);
  179023. zSep = ", ";
  179024. }
  179025. return zList;
  179026. }
  179027. /*
  179028. ** Return a comma separated list of the quoted PRIMARY KEY column names,
  179029. ** in order, for the current table. Before each column name, add the text
  179030. ** zPre. After each column name, add the zPost text. Use zSeparator as
  179031. ** the separator text (usually ", ").
  179032. */
  179033. static char *rbuObjIterGetPkList(
  179034. sqlite3rbu *p, /* RBU object */
  179035. RbuObjIter *pIter, /* Object iterator for column names */
  179036. const char *zPre, /* Before each quoted column name */
  179037. const char *zSeparator, /* Separator to use between columns */
  179038. const char *zPost /* After each quoted column name */
  179039. ){
  179040. int iPk = 1;
  179041. char *zRet = 0;
  179042. const char *zSep = "";
  179043. while( 1 ){
  179044. int i;
  179045. for(i=0; i<pIter->nTblCol; i++){
  179046. if( (int)pIter->abTblPk[i]==iPk ){
  179047. const char *zCol = pIter->azTblCol[i];
  179048. zRet = rbuMPrintf(p, "%z%s%s\"%w\"%s", zRet, zSep, zPre, zCol, zPost);
  179049. zSep = zSeparator;
  179050. break;
  179051. }
  179052. }
  179053. if( i==pIter->nTblCol ) break;
  179054. iPk++;
  179055. }
  179056. return zRet;
  179057. }
  179058. /*
  179059. ** This function is called as part of restarting an RBU vacuum within
  179060. ** stage 1 of the process (while the *-oal file is being built) while
  179061. ** updating a table (not an index). The table may be a rowid table or
  179062. ** a WITHOUT ROWID table. It queries the target database to find the
  179063. ** largest key that has already been written to the target table and
  179064. ** constructs a WHERE clause that can be used to extract the remaining
  179065. ** rows from the source table. For a rowid table, the WHERE clause
  179066. ** is of the form:
  179067. **
  179068. ** "WHERE _rowid_ > ?"
  179069. **
  179070. ** and for WITHOUT ROWID tables:
  179071. **
  179072. ** "WHERE (key1, key2) > (?, ?)"
  179073. **
  179074. ** Instead of "?" placeholders, the actual WHERE clauses created by
  179075. ** this function contain literal SQL values.
  179076. */
  179077. static char *rbuVacuumTableStart(
  179078. sqlite3rbu *p, /* RBU handle */
  179079. RbuObjIter *pIter, /* RBU iterator object */
  179080. int bRowid, /* True for a rowid table */
  179081. const char *zWrite /* Target table name prefix */
  179082. ){
  179083. sqlite3_stmt *pMax = 0;
  179084. char *zRet = 0;
  179085. if( bRowid ){
  179086. p->rc = prepareFreeAndCollectError(p->dbMain, &pMax, &p->zErrmsg,
  179087. sqlite3_mprintf(
  179088. "SELECT max(_rowid_) FROM \"%s%w\"", zWrite, pIter->zTbl
  179089. )
  179090. );
  179091. if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pMax) ){
  179092. sqlite3_int64 iMax = sqlite3_column_int64(pMax, 0);
  179093. zRet = rbuMPrintf(p, " WHERE _rowid_ > %lld ", iMax);
  179094. }
  179095. rbuFinalize(p, pMax);
  179096. }else{
  179097. char *zOrder = rbuObjIterGetPkList(p, pIter, "", ", ", " DESC");
  179098. char *zSelect = rbuObjIterGetPkList(p, pIter, "quote(", "||','||", ")");
  179099. char *zList = rbuObjIterGetPkList(p, pIter, "", ", ", "");
  179100. if( p->rc==SQLITE_OK ){
  179101. p->rc = prepareFreeAndCollectError(p->dbMain, &pMax, &p->zErrmsg,
  179102. sqlite3_mprintf(
  179103. "SELECT %s FROM \"%s%w\" ORDER BY %s LIMIT 1",
  179104. zSelect, zWrite, pIter->zTbl, zOrder
  179105. )
  179106. );
  179107. if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pMax) ){
  179108. const char *zVal = (const char*)sqlite3_column_text(pMax, 0);
  179109. zRet = rbuMPrintf(p, " WHERE (%s) > (%s) ", zList, zVal);
  179110. }
  179111. rbuFinalize(p, pMax);
  179112. }
  179113. sqlite3_free(zOrder);
  179114. sqlite3_free(zSelect);
  179115. sqlite3_free(zList);
  179116. }
  179117. return zRet;
  179118. }
  179119. /*
  179120. ** This function is called as part of restating an RBU vacuum when the
  179121. ** current operation is writing content to an index. If possible, it
  179122. ** queries the target index b-tree for the largest key already written to
  179123. ** it, then composes and returns an expression that can be used in a WHERE
  179124. ** clause to select the remaining required rows from the source table.
  179125. ** It is only possible to return such an expression if:
  179126. **
  179127. ** * The index contains no DESC columns, and
  179128. ** * The last key written to the index before the operation was
  179129. ** suspended does not contain any NULL values.
  179130. **
  179131. ** The expression is of the form:
  179132. **
  179133. ** (index-field1, index-field2, ...) > (?, ?, ...)
  179134. **
  179135. ** except that the "?" placeholders are replaced with literal values.
  179136. **
  179137. ** If the expression cannot be created, NULL is returned. In this case,
  179138. ** the caller has to use an OFFSET clause to extract only the required
  179139. ** rows from the sourct table, just as it does for an RBU update operation.
  179140. */
  179141. char *rbuVacuumIndexStart(
  179142. sqlite3rbu *p, /* RBU handle */
  179143. RbuObjIter *pIter /* RBU iterator object */
  179144. ){
  179145. char *zOrder = 0;
  179146. char *zLhs = 0;
  179147. char *zSelect = 0;
  179148. char *zVector = 0;
  179149. char *zRet = 0;
  179150. int bFailed = 0;
  179151. const char *zSep = "";
  179152. int iCol = 0;
  179153. sqlite3_stmt *pXInfo = 0;
  179154. p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
  179155. sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", pIter->zIdx)
  179156. );
  179157. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
  179158. int iCid = sqlite3_column_int(pXInfo, 1);
  179159. const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
  179160. const char *zCol;
  179161. if( sqlite3_column_int(pXInfo, 3) ){
  179162. bFailed = 1;
  179163. break;
  179164. }
  179165. if( iCid<0 ){
  179166. if( pIter->eType==RBU_PK_IPK ){
  179167. int i;
  179168. for(i=0; pIter->abTblPk[i]==0; i++);
  179169. assert( i<pIter->nTblCol );
  179170. zCol = pIter->azTblCol[i];
  179171. }else{
  179172. zCol = "_rowid_";
  179173. }
  179174. }else{
  179175. zCol = pIter->azTblCol[iCid];
  179176. }
  179177. zLhs = rbuMPrintf(p, "%z%s \"%w\" COLLATE %Q",
  179178. zLhs, zSep, zCol, zCollate
  179179. );
  179180. zOrder = rbuMPrintf(p, "%z%s \"rbu_imp_%d%w\" COLLATE %Q DESC",
  179181. zOrder, zSep, iCol, zCol, zCollate
  179182. );
  179183. zSelect = rbuMPrintf(p, "%z%s quote(\"rbu_imp_%d%w\")",
  179184. zSelect, zSep, iCol, zCol
  179185. );
  179186. zSep = ", ";
  179187. iCol++;
  179188. }
  179189. rbuFinalize(p, pXInfo);
  179190. if( bFailed ) goto index_start_out;
  179191. if( p->rc==SQLITE_OK ){
  179192. sqlite3_stmt *pSel = 0;
  179193. p->rc = prepareFreeAndCollectError(p->dbMain, &pSel, &p->zErrmsg,
  179194. sqlite3_mprintf("SELECT %s FROM \"rbu_imp_%w\" ORDER BY %s LIMIT 1",
  179195. zSelect, pIter->zTbl, zOrder
  179196. )
  179197. );
  179198. if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSel) ){
  179199. zSep = "";
  179200. for(iCol=0; iCol<pIter->nCol; iCol++){
  179201. const char *zQuoted = (const char*)sqlite3_column_text(pSel, iCol);
  179202. if( zQuoted[0]=='N' ){
  179203. bFailed = 1;
  179204. break;
  179205. }
  179206. zVector = rbuMPrintf(p, "%z%s%s", zVector, zSep, zQuoted);
  179207. zSep = ", ";
  179208. }
  179209. if( !bFailed ){
  179210. zRet = rbuMPrintf(p, "(%s) > (%s)", zLhs, zVector);
  179211. }
  179212. }
  179213. rbuFinalize(p, pSel);
  179214. }
  179215. index_start_out:
  179216. sqlite3_free(zOrder);
  179217. sqlite3_free(zSelect);
  179218. sqlite3_free(zVector);
  179219. sqlite3_free(zLhs);
  179220. return zRet;
  179221. }
  179222. /*
  179223. ** This function is used to create a SELECT list (the list of SQL
  179224. ** expressions that follows a SELECT keyword) for a SELECT statement
  179225. ** used to read from an data_xxx or rbu_tmp_xxx table while updating the
  179226. ** index object currently indicated by the iterator object passed as the
  179227. ** second argument. A "PRAGMA index_xinfo = <idxname>" statement is used
  179228. ** to obtain the required information.
  179229. **
  179230. ** If the index is of the following form:
  179231. **
  179232. ** CREATE INDEX i1 ON t1(c, b COLLATE nocase);
  179233. **
  179234. ** and "t1" is a table with an explicit INTEGER PRIMARY KEY column
  179235. ** "ipk", the returned string is:
  179236. **
  179237. ** "`c` COLLATE 'BINARY', `b` COLLATE 'NOCASE', `ipk` COLLATE 'BINARY'"
  179238. **
  179239. ** As well as the returned string, three other malloc'd strings are
  179240. ** returned via output parameters. As follows:
  179241. **
  179242. ** pzImposterCols: ...
  179243. ** pzImposterPk: ...
  179244. ** pzWhere: ...
  179245. */
  179246. static char *rbuObjIterGetIndexCols(
  179247. sqlite3rbu *p, /* RBU object */
  179248. RbuObjIter *pIter, /* Object iterator for column names */
  179249. char **pzImposterCols, /* OUT: Columns for imposter table */
  179250. char **pzImposterPk, /* OUT: Imposter PK clause */
  179251. char **pzWhere, /* OUT: WHERE clause */
  179252. int *pnBind /* OUT: Trbul number of columns */
  179253. ){
  179254. int rc = p->rc; /* Error code */
  179255. int rc2; /* sqlite3_finalize() return code */
  179256. char *zRet = 0; /* String to return */
  179257. char *zImpCols = 0; /* String to return via *pzImposterCols */
  179258. char *zImpPK = 0; /* String to return via *pzImposterPK */
  179259. char *zWhere = 0; /* String to return via *pzWhere */
  179260. int nBind = 0; /* Value to return via *pnBind */
  179261. const char *zCom = ""; /* Set to ", " later on */
  179262. const char *zAnd = ""; /* Set to " AND " later on */
  179263. sqlite3_stmt *pXInfo = 0; /* PRAGMA index_xinfo = ? */
  179264. if( rc==SQLITE_OK ){
  179265. assert( p->zErrmsg==0 );
  179266. rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
  179267. sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", pIter->zIdx)
  179268. );
  179269. }
  179270. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
  179271. int iCid = sqlite3_column_int(pXInfo, 1);
  179272. int bDesc = sqlite3_column_int(pXInfo, 3);
  179273. const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
  179274. const char *zCol;
  179275. const char *zType;
  179276. if( iCid<0 ){
  179277. /* An integer primary key. If the table has an explicit IPK, use
  179278. ** its name. Otherwise, use "rbu_rowid". */
  179279. if( pIter->eType==RBU_PK_IPK ){
  179280. int i;
  179281. for(i=0; pIter->abTblPk[i]==0; i++);
  179282. assert( i<pIter->nTblCol );
  179283. zCol = pIter->azTblCol[i];
  179284. }else if( rbuIsVacuum(p) ){
  179285. zCol = "_rowid_";
  179286. }else{
  179287. zCol = "rbu_rowid";
  179288. }
  179289. zType = "INTEGER";
  179290. }else{
  179291. zCol = pIter->azTblCol[iCid];
  179292. zType = pIter->azTblType[iCid];
  179293. }
  179294. zRet = sqlite3_mprintf("%z%s\"%w\" COLLATE %Q", zRet, zCom, zCol, zCollate);
  179295. if( pIter->bUnique==0 || sqlite3_column_int(pXInfo, 5) ){
  179296. const char *zOrder = (bDesc ? " DESC" : "");
  179297. zImpPK = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\"%s",
  179298. zImpPK, zCom, nBind, zCol, zOrder
  179299. );
  179300. }
  179301. zImpCols = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\" %s COLLATE %Q",
  179302. zImpCols, zCom, nBind, zCol, zType, zCollate
  179303. );
  179304. zWhere = sqlite3_mprintf(
  179305. "%z%s\"rbu_imp_%d%w\" IS ?", zWhere, zAnd, nBind, zCol
  179306. );
  179307. if( zRet==0 || zImpPK==0 || zImpCols==0 || zWhere==0 ) rc = SQLITE_NOMEM;
  179308. zCom = ", ";
  179309. zAnd = " AND ";
  179310. nBind++;
  179311. }
  179312. rc2 = sqlite3_finalize(pXInfo);
  179313. if( rc==SQLITE_OK ) rc = rc2;
  179314. if( rc!=SQLITE_OK ){
  179315. sqlite3_free(zRet);
  179316. sqlite3_free(zImpCols);
  179317. sqlite3_free(zImpPK);
  179318. sqlite3_free(zWhere);
  179319. zRet = 0;
  179320. zImpCols = 0;
  179321. zImpPK = 0;
  179322. zWhere = 0;
  179323. p->rc = rc;
  179324. }
  179325. *pzImposterCols = zImpCols;
  179326. *pzImposterPk = zImpPK;
  179327. *pzWhere = zWhere;
  179328. *pnBind = nBind;
  179329. return zRet;
  179330. }
  179331. /*
  179332. ** Assuming the current table columns are "a", "b" and "c", and the zObj
  179333. ** paramter is passed "old", return a string of the form:
  179334. **
  179335. ** "old.a, old.b, old.b"
  179336. **
  179337. ** With the column names escaped.
  179338. **
  179339. ** For tables with implicit rowids - RBU_PK_EXTERNAL and RBU_PK_NONE, append
  179340. ** the text ", old._rowid_" to the returned value.
  179341. */
  179342. static char *rbuObjIterGetOldlist(
  179343. sqlite3rbu *p,
  179344. RbuObjIter *pIter,
  179345. const char *zObj
  179346. ){
  179347. char *zList = 0;
  179348. if( p->rc==SQLITE_OK && pIter->abIndexed ){
  179349. const char *zS = "";
  179350. int i;
  179351. for(i=0; i<pIter->nTblCol; i++){
  179352. if( pIter->abIndexed[i] ){
  179353. const char *zCol = pIter->azTblCol[i];
  179354. zList = sqlite3_mprintf("%z%s%s.\"%w\"", zList, zS, zObj, zCol);
  179355. }else{
  179356. zList = sqlite3_mprintf("%z%sNULL", zList, zS);
  179357. }
  179358. zS = ", ";
  179359. if( zList==0 ){
  179360. p->rc = SQLITE_NOMEM;
  179361. break;
  179362. }
  179363. }
  179364. /* For a table with implicit rowids, append "old._rowid_" to the list. */
  179365. if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
  179366. zList = rbuMPrintf(p, "%z, %s._rowid_", zList, zObj);
  179367. }
  179368. }
  179369. return zList;
  179370. }
  179371. /*
  179372. ** Return an expression that can be used in a WHERE clause to match the
  179373. ** primary key of the current table. For example, if the table is:
  179374. **
  179375. ** CREATE TABLE t1(a, b, c, PRIMARY KEY(b, c));
  179376. **
  179377. ** Return the string:
  179378. **
  179379. ** "b = ?1 AND c = ?2"
  179380. */
  179381. static char *rbuObjIterGetWhere(
  179382. sqlite3rbu *p,
  179383. RbuObjIter *pIter
  179384. ){
  179385. char *zList = 0;
  179386. if( pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE ){
  179387. zList = rbuMPrintf(p, "_rowid_ = ?%d", pIter->nTblCol+1);
  179388. }else if( pIter->eType==RBU_PK_EXTERNAL ){
  179389. const char *zSep = "";
  179390. int i;
  179391. for(i=0; i<pIter->nTblCol; i++){
  179392. if( pIter->abTblPk[i] ){
  179393. zList = rbuMPrintf(p, "%z%sc%d=?%d", zList, zSep, i, i+1);
  179394. zSep = " AND ";
  179395. }
  179396. }
  179397. zList = rbuMPrintf(p,
  179398. "_rowid_ = (SELECT id FROM rbu_imposter2 WHERE %z)", zList
  179399. );
  179400. }else{
  179401. const char *zSep = "";
  179402. int i;
  179403. for(i=0; i<pIter->nTblCol; i++){
  179404. if( pIter->abTblPk[i] ){
  179405. const char *zCol = pIter->azTblCol[i];
  179406. zList = rbuMPrintf(p, "%z%s\"%w\"=?%d", zList, zSep, zCol, i+1);
  179407. zSep = " AND ";
  179408. }
  179409. }
  179410. }
  179411. return zList;
  179412. }
  179413. /*
  179414. ** The SELECT statement iterating through the keys for the current object
  179415. ** (p->objiter.pSelect) currently points to a valid row. However, there
  179416. ** is something wrong with the rbu_control value in the rbu_control value
  179417. ** stored in the (p->nCol+1)'th column. Set the error code and error message
  179418. ** of the RBU handle to something reflecting this.
  179419. */
  179420. static void rbuBadControlError(sqlite3rbu *p){
  179421. p->rc = SQLITE_ERROR;
  179422. p->zErrmsg = sqlite3_mprintf("invalid rbu_control value");
  179423. }
  179424. /*
  179425. ** Return a nul-terminated string containing the comma separated list of
  179426. ** assignments that should be included following the "SET" keyword of
  179427. ** an UPDATE statement used to update the table object that the iterator
  179428. ** passed as the second argument currently points to if the rbu_control
  179429. ** column of the data_xxx table entry is set to zMask.
  179430. **
  179431. ** The memory for the returned string is obtained from sqlite3_malloc().
  179432. ** It is the responsibility of the caller to eventually free it using
  179433. ** sqlite3_free().
  179434. **
  179435. ** If an OOM error is encountered when allocating space for the new
  179436. ** string, an error code is left in the rbu handle passed as the first
  179437. ** argument and NULL is returned. Or, if an error has already occurred
  179438. ** when this function is called, NULL is returned immediately, without
  179439. ** attempting the allocation or modifying the stored error code.
  179440. */
  179441. static char *rbuObjIterGetSetlist(
  179442. sqlite3rbu *p,
  179443. RbuObjIter *pIter,
  179444. const char *zMask
  179445. ){
  179446. char *zList = 0;
  179447. if( p->rc==SQLITE_OK ){
  179448. int i;
  179449. if( (int)strlen(zMask)!=pIter->nTblCol ){
  179450. rbuBadControlError(p);
  179451. }else{
  179452. const char *zSep = "";
  179453. for(i=0; i<pIter->nTblCol; i++){
  179454. char c = zMask[pIter->aiSrcOrder[i]];
  179455. if( c=='x' ){
  179456. zList = rbuMPrintf(p, "%z%s\"%w\"=?%d",
  179457. zList, zSep, pIter->azTblCol[i], i+1
  179458. );
  179459. zSep = ", ";
  179460. }
  179461. else if( c=='d' ){
  179462. zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_delta(\"%w\", ?%d)",
  179463. zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
  179464. );
  179465. zSep = ", ";
  179466. }
  179467. else if( c=='f' ){
  179468. zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_fossil_delta(\"%w\", ?%d)",
  179469. zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
  179470. );
  179471. zSep = ", ";
  179472. }
  179473. }
  179474. }
  179475. }
  179476. return zList;
  179477. }
  179478. /*
  179479. ** Return a nul-terminated string consisting of nByte comma separated
  179480. ** "?" expressions. For example, if nByte is 3, return a pointer to
  179481. ** a buffer containing the string "?,?,?".
  179482. **
  179483. ** The memory for the returned string is obtained from sqlite3_malloc().
  179484. ** It is the responsibility of the caller to eventually free it using
  179485. ** sqlite3_free().
  179486. **
  179487. ** If an OOM error is encountered when allocating space for the new
  179488. ** string, an error code is left in the rbu handle passed as the first
  179489. ** argument and NULL is returned. Or, if an error has already occurred
  179490. ** when this function is called, NULL is returned immediately, without
  179491. ** attempting the allocation or modifying the stored error code.
  179492. */
  179493. static char *rbuObjIterGetBindlist(sqlite3rbu *p, int nBind){
  179494. char *zRet = 0;
  179495. sqlite3_int64 nByte = 2*(sqlite3_int64)nBind + 1;
  179496. zRet = (char*)rbuMalloc(p, nByte);
  179497. if( zRet ){
  179498. int i;
  179499. for(i=0; i<nBind; i++){
  179500. zRet[i*2] = '?';
  179501. zRet[i*2+1] = (i+1==nBind) ? '\0' : ',';
  179502. }
  179503. }
  179504. return zRet;
  179505. }
  179506. /*
  179507. ** The iterator currently points to a table (not index) of type
  179508. ** RBU_PK_WITHOUT_ROWID. This function creates the PRIMARY KEY
  179509. ** declaration for the corresponding imposter table. For example,
  179510. ** if the iterator points to a table created as:
  179511. **
  179512. ** CREATE TABLE t1(a, b, c, PRIMARY KEY(b, a DESC)) WITHOUT ROWID
  179513. **
  179514. ** this function returns:
  179515. **
  179516. ** PRIMARY KEY("b", "a" DESC)
  179517. */
  179518. static char *rbuWithoutRowidPK(sqlite3rbu *p, RbuObjIter *pIter){
  179519. char *z = 0;
  179520. assert( pIter->zIdx==0 );
  179521. if( p->rc==SQLITE_OK ){
  179522. const char *zSep = "PRIMARY KEY(";
  179523. sqlite3_stmt *pXList = 0; /* PRAGMA index_list = (pIter->zTbl) */
  179524. sqlite3_stmt *pXInfo = 0; /* PRAGMA index_xinfo = <pk-index> */
  179525. p->rc = prepareFreeAndCollectError(p->dbMain, &pXList, &p->zErrmsg,
  179526. sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
  179527. );
  179528. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXList) ){
  179529. const char *zOrig = (const char*)sqlite3_column_text(pXList,3);
  179530. if( zOrig && strcmp(zOrig, "pk")==0 ){
  179531. const char *zIdx = (const char*)sqlite3_column_text(pXList,1);
  179532. if( zIdx ){
  179533. p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
  179534. sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
  179535. );
  179536. }
  179537. break;
  179538. }
  179539. }
  179540. rbuFinalize(p, pXList);
  179541. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
  179542. if( sqlite3_column_int(pXInfo, 5) ){
  179543. /* int iCid = sqlite3_column_int(pXInfo, 0); */
  179544. const char *zCol = (const char*)sqlite3_column_text(pXInfo, 2);
  179545. const char *zDesc = sqlite3_column_int(pXInfo, 3) ? " DESC" : "";
  179546. z = rbuMPrintf(p, "%z%s\"%w\"%s", z, zSep, zCol, zDesc);
  179547. zSep = ", ";
  179548. }
  179549. }
  179550. z = rbuMPrintf(p, "%z)", z);
  179551. rbuFinalize(p, pXInfo);
  179552. }
  179553. return z;
  179554. }
  179555. /*
  179556. ** This function creates the second imposter table used when writing to
  179557. ** a table b-tree where the table has an external primary key. If the
  179558. ** iterator passed as the second argument does not currently point to
  179559. ** a table (not index) with an external primary key, this function is a
  179560. ** no-op.
  179561. **
  179562. ** Assuming the iterator does point to a table with an external PK, this
  179563. ** function creates a WITHOUT ROWID imposter table named "rbu_imposter2"
  179564. ** used to access that PK index. For example, if the target table is
  179565. ** declared as follows:
  179566. **
  179567. ** CREATE TABLE t1(a, b TEXT, c REAL, PRIMARY KEY(b, c));
  179568. **
  179569. ** then the imposter table schema is:
  179570. **
  179571. ** CREATE TABLE rbu_imposter2(c1 TEXT, c2 REAL, id INTEGER) WITHOUT ROWID;
  179572. **
  179573. */
  179574. static void rbuCreateImposterTable2(sqlite3rbu *p, RbuObjIter *pIter){
  179575. if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_EXTERNAL ){
  179576. int tnum = pIter->iPkTnum; /* Root page of PK index */
  179577. sqlite3_stmt *pQuery = 0; /* SELECT name ... WHERE rootpage = $tnum */
  179578. const char *zIdx = 0; /* Name of PK index */
  179579. sqlite3_stmt *pXInfo = 0; /* PRAGMA main.index_xinfo = $zIdx */
  179580. const char *zComma = "";
  179581. char *zCols = 0; /* Used to build up list of table cols */
  179582. char *zPk = 0; /* Used to build up table PK declaration */
  179583. /* Figure out the name of the primary key index for the current table.
  179584. ** This is needed for the argument to "PRAGMA index_xinfo". Set
  179585. ** zIdx to point to a nul-terminated string containing this name. */
  179586. p->rc = prepareAndCollectError(p->dbMain, &pQuery, &p->zErrmsg,
  179587. "SELECT name FROM sqlite_master WHERE rootpage = ?"
  179588. );
  179589. if( p->rc==SQLITE_OK ){
  179590. sqlite3_bind_int(pQuery, 1, tnum);
  179591. if( SQLITE_ROW==sqlite3_step(pQuery) ){
  179592. zIdx = (const char*)sqlite3_column_text(pQuery, 0);
  179593. }
  179594. }
  179595. if( zIdx ){
  179596. p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
  179597. sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
  179598. );
  179599. }
  179600. rbuFinalize(p, pQuery);
  179601. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
  179602. int bKey = sqlite3_column_int(pXInfo, 5);
  179603. if( bKey ){
  179604. int iCid = sqlite3_column_int(pXInfo, 1);
  179605. int bDesc = sqlite3_column_int(pXInfo, 3);
  179606. const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
  179607. zCols = rbuMPrintf(p, "%z%sc%d %s COLLATE %Q", zCols, zComma,
  179608. iCid, pIter->azTblType[iCid], zCollate
  179609. );
  179610. zPk = rbuMPrintf(p, "%z%sc%d%s", zPk, zComma, iCid, bDesc?" DESC":"");
  179611. zComma = ", ";
  179612. }
  179613. }
  179614. zCols = rbuMPrintf(p, "%z, id INTEGER", zCols);
  179615. rbuFinalize(p, pXInfo);
  179616. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
  179617. rbuMPrintfExec(p, p->dbMain,
  179618. "CREATE TABLE rbu_imposter2(%z, PRIMARY KEY(%z)) WITHOUT ROWID",
  179619. zCols, zPk
  179620. );
  179621. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
  179622. }
  179623. }
  179624. /*
  179625. ** If an error has already occurred when this function is called, it
  179626. ** immediately returns zero (without doing any work). Or, if an error
  179627. ** occurs during the execution of this function, it sets the error code
  179628. ** in the sqlite3rbu object indicated by the first argument and returns
  179629. ** zero.
  179630. **
  179631. ** The iterator passed as the second argument is guaranteed to point to
  179632. ** a table (not an index) when this function is called. This function
  179633. ** attempts to create any imposter table required to write to the main
  179634. ** table b-tree of the table before returning. Non-zero is returned if
  179635. ** an imposter table are created, or zero otherwise.
  179636. **
  179637. ** An imposter table is required in all cases except RBU_PK_VTAB. Only
  179638. ** virtual tables are written to directly. The imposter table has the
  179639. ** same schema as the actual target table (less any UNIQUE constraints).
  179640. ** More precisely, the "same schema" means the same columns, types,
  179641. ** collation sequences. For tables that do not have an external PRIMARY
  179642. ** KEY, it also means the same PRIMARY KEY declaration.
  179643. */
  179644. static void rbuCreateImposterTable(sqlite3rbu *p, RbuObjIter *pIter){
  179645. if( p->rc==SQLITE_OK && pIter->eType!=RBU_PK_VTAB ){
  179646. int tnum = pIter->iTnum;
  179647. const char *zComma = "";
  179648. char *zSql = 0;
  179649. int iCol;
  179650. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
  179651. for(iCol=0; p->rc==SQLITE_OK && iCol<pIter->nTblCol; iCol++){
  179652. const char *zPk = "";
  179653. const char *zCol = pIter->azTblCol[iCol];
  179654. const char *zColl = 0;
  179655. p->rc = sqlite3_table_column_metadata(
  179656. p->dbMain, "main", pIter->zTbl, zCol, 0, &zColl, 0, 0, 0
  179657. );
  179658. if( pIter->eType==RBU_PK_IPK && pIter->abTblPk[iCol] ){
  179659. /* If the target table column is an "INTEGER PRIMARY KEY", add
  179660. ** "PRIMARY KEY" to the imposter table column declaration. */
  179661. zPk = "PRIMARY KEY ";
  179662. }
  179663. zSql = rbuMPrintf(p, "%z%s\"%w\" %s %sCOLLATE %Q%s",
  179664. zSql, zComma, zCol, pIter->azTblType[iCol], zPk, zColl,
  179665. (pIter->abNotNull[iCol] ? " NOT NULL" : "")
  179666. );
  179667. zComma = ", ";
  179668. }
  179669. if( pIter->eType==RBU_PK_WITHOUT_ROWID ){
  179670. char *zPk = rbuWithoutRowidPK(p, pIter);
  179671. if( zPk ){
  179672. zSql = rbuMPrintf(p, "%z, %z", zSql, zPk);
  179673. }
  179674. }
  179675. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
  179676. rbuMPrintfExec(p, p->dbMain, "CREATE TABLE \"rbu_imp_%w\"(%z)%s",
  179677. pIter->zTbl, zSql,
  179678. (pIter->eType==RBU_PK_WITHOUT_ROWID ? " WITHOUT ROWID" : "")
  179679. );
  179680. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
  179681. }
  179682. }
  179683. /*
  179684. ** Prepare a statement used to insert rows into the "rbu_tmp_xxx" table.
  179685. ** Specifically a statement of the form:
  179686. **
  179687. ** INSERT INTO rbu_tmp_xxx VALUES(?, ?, ? ...);
  179688. **
  179689. ** The number of bound variables is equal to the number of columns in
  179690. ** the target table, plus one (for the rbu_control column), plus one more
  179691. ** (for the rbu_rowid column) if the target table is an implicit IPK or
  179692. ** virtual table.
  179693. */
  179694. static void rbuObjIterPrepareTmpInsert(
  179695. sqlite3rbu *p,
  179696. RbuObjIter *pIter,
  179697. const char *zCollist,
  179698. const char *zRbuRowid
  179699. ){
  179700. int bRbuRowid = (pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE);
  179701. char *zBind = rbuObjIterGetBindlist(p, pIter->nTblCol + 1 + bRbuRowid);
  179702. if( zBind ){
  179703. assert( pIter->pTmpInsert==0 );
  179704. p->rc = prepareFreeAndCollectError(
  179705. p->dbRbu, &pIter->pTmpInsert, &p->zErrmsg, sqlite3_mprintf(
  179706. "INSERT INTO %s.'rbu_tmp_%q'(rbu_control,%s%s) VALUES(%z)",
  179707. p->zStateDb, pIter->zDataTbl, zCollist, zRbuRowid, zBind
  179708. ));
  179709. }
  179710. }
  179711. static void rbuTmpInsertFunc(
  179712. sqlite3_context *pCtx,
  179713. int nVal,
  179714. sqlite3_value **apVal
  179715. ){
  179716. sqlite3rbu *p = sqlite3_user_data(pCtx);
  179717. int rc = SQLITE_OK;
  179718. int i;
  179719. assert( sqlite3_value_int(apVal[0])!=0
  179720. || p->objiter.eType==RBU_PK_EXTERNAL
  179721. || p->objiter.eType==RBU_PK_NONE
  179722. );
  179723. if( sqlite3_value_int(apVal[0])!=0 ){
  179724. p->nPhaseOneStep += p->objiter.nIndex;
  179725. }
  179726. for(i=0; rc==SQLITE_OK && i<nVal; i++){
  179727. rc = sqlite3_bind_value(p->objiter.pTmpInsert, i+1, apVal[i]);
  179728. }
  179729. if( rc==SQLITE_OK ){
  179730. sqlite3_step(p->objiter.pTmpInsert);
  179731. rc = sqlite3_reset(p->objiter.pTmpInsert);
  179732. }
  179733. if( rc!=SQLITE_OK ){
  179734. sqlite3_result_error_code(pCtx, rc);
  179735. }
  179736. }
  179737. static char *rbuObjIterGetIndexWhere(sqlite3rbu *p, RbuObjIter *pIter){
  179738. sqlite3_stmt *pStmt = 0;
  179739. int rc = p->rc;
  179740. char *zRet = 0;
  179741. if( rc==SQLITE_OK ){
  179742. rc = prepareAndCollectError(p->dbMain, &pStmt, &p->zErrmsg,
  179743. "SELECT trim(sql) FROM sqlite_master WHERE type='index' AND name=?"
  179744. );
  179745. }
  179746. if( rc==SQLITE_OK ){
  179747. int rc2;
  179748. rc = sqlite3_bind_text(pStmt, 1, pIter->zIdx, -1, SQLITE_STATIC);
  179749. if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  179750. const char *zSql = (const char*)sqlite3_column_text(pStmt, 0);
  179751. if( zSql ){
  179752. int nParen = 0; /* Number of open parenthesis */
  179753. int i;
  179754. for(i=0; zSql[i]; i++){
  179755. char c = zSql[i];
  179756. if( c=='(' ){
  179757. nParen++;
  179758. }
  179759. else if( c==')' ){
  179760. nParen--;
  179761. if( nParen==0 ){
  179762. i++;
  179763. break;
  179764. }
  179765. }else if( c=='"' || c=='\'' || c=='`' ){
  179766. for(i++; 1; i++){
  179767. if( zSql[i]==c ){
  179768. if( zSql[i+1]!=c ) break;
  179769. i++;
  179770. }
  179771. }
  179772. }else if( c=='[' ){
  179773. for(i++; 1; i++){
  179774. if( zSql[i]==']' ) break;
  179775. }
  179776. }
  179777. }
  179778. if( zSql[i] ){
  179779. zRet = rbuStrndup(&zSql[i], &rc);
  179780. }
  179781. }
  179782. }
  179783. rc2 = sqlite3_finalize(pStmt);
  179784. if( rc==SQLITE_OK ) rc = rc2;
  179785. }
  179786. p->rc = rc;
  179787. return zRet;
  179788. }
  179789. /*
  179790. ** Ensure that the SQLite statement handles required to update the
  179791. ** target database object currently indicated by the iterator passed
  179792. ** as the second argument are available.
  179793. */
  179794. static int rbuObjIterPrepareAll(
  179795. sqlite3rbu *p,
  179796. RbuObjIter *pIter,
  179797. int nOffset /* Add "LIMIT -1 OFFSET $nOffset" to SELECT */
  179798. ){
  179799. assert( pIter->bCleanup==0 );
  179800. if( pIter->pSelect==0 && rbuObjIterCacheTableInfo(p, pIter)==SQLITE_OK ){
  179801. const int tnum = pIter->iTnum;
  179802. char *zCollist = 0; /* List of indexed columns */
  179803. char **pz = &p->zErrmsg;
  179804. const char *zIdx = pIter->zIdx;
  179805. char *zLimit = 0;
  179806. if( nOffset ){
  179807. zLimit = sqlite3_mprintf(" LIMIT -1 OFFSET %d", nOffset);
  179808. if( !zLimit ) p->rc = SQLITE_NOMEM;
  179809. }
  179810. if( zIdx ){
  179811. const char *zTbl = pIter->zTbl;
  179812. char *zImposterCols = 0; /* Columns for imposter table */
  179813. char *zImposterPK = 0; /* Primary key declaration for imposter */
  179814. char *zWhere = 0; /* WHERE clause on PK columns */
  179815. char *zBind = 0;
  179816. char *zPart = 0;
  179817. int nBind = 0;
  179818. assert( pIter->eType!=RBU_PK_VTAB );
  179819. zCollist = rbuObjIterGetIndexCols(
  179820. p, pIter, &zImposterCols, &zImposterPK, &zWhere, &nBind
  179821. );
  179822. zBind = rbuObjIterGetBindlist(p, nBind);
  179823. zPart = rbuObjIterGetIndexWhere(p, pIter);
  179824. /* Create the imposter table used to write to this index. */
  179825. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
  179826. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1,tnum);
  179827. rbuMPrintfExec(p, p->dbMain,
  179828. "CREATE TABLE \"rbu_imp_%w\"( %s, PRIMARY KEY( %s ) ) WITHOUT ROWID",
  179829. zTbl, zImposterCols, zImposterPK
  179830. );
  179831. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
  179832. /* Create the statement to insert index entries */
  179833. pIter->nCol = nBind;
  179834. if( p->rc==SQLITE_OK ){
  179835. p->rc = prepareFreeAndCollectError(
  179836. p->dbMain, &pIter->pInsert, &p->zErrmsg,
  179837. sqlite3_mprintf("INSERT INTO \"rbu_imp_%w\" VALUES(%s)", zTbl, zBind)
  179838. );
  179839. }
  179840. /* And to delete index entries */
  179841. if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){
  179842. p->rc = prepareFreeAndCollectError(
  179843. p->dbMain, &pIter->pDelete, &p->zErrmsg,
  179844. sqlite3_mprintf("DELETE FROM \"rbu_imp_%w\" WHERE %s", zTbl, zWhere)
  179845. );
  179846. }
  179847. /* Create the SELECT statement to read keys in sorted order */
  179848. if( p->rc==SQLITE_OK ){
  179849. char *zSql;
  179850. if( rbuIsVacuum(p) ){
  179851. char *zStart = 0;
  179852. if( nOffset ){
  179853. zStart = rbuVacuumIndexStart(p, pIter);
  179854. if( zStart ){
  179855. sqlite3_free(zLimit);
  179856. zLimit = 0;
  179857. }
  179858. }
  179859. zSql = sqlite3_mprintf(
  179860. "SELECT %s, 0 AS rbu_control FROM '%q' %s %s %s ORDER BY %s%s",
  179861. zCollist,
  179862. pIter->zDataTbl,
  179863. zPart,
  179864. (zStart ? (zPart ? "AND" : "WHERE") : ""), zStart,
  179865. zCollist, zLimit
  179866. );
  179867. sqlite3_free(zStart);
  179868. }else
  179869. if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
  179870. zSql = sqlite3_mprintf(
  179871. "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' %s ORDER BY %s%s",
  179872. zCollist, p->zStateDb, pIter->zDataTbl,
  179873. zPart, zCollist, zLimit
  179874. );
  179875. }else{
  179876. zSql = sqlite3_mprintf(
  179877. "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' %s "
  179878. "UNION ALL "
  179879. "SELECT %s, rbu_control FROM '%q' "
  179880. "%s %s typeof(rbu_control)='integer' AND rbu_control!=1 "
  179881. "ORDER BY %s%s",
  179882. zCollist, p->zStateDb, pIter->zDataTbl, zPart,
  179883. zCollist, pIter->zDataTbl,
  179884. zPart,
  179885. (zPart ? "AND" : "WHERE"),
  179886. zCollist, zLimit
  179887. );
  179888. }
  179889. if( p->rc==SQLITE_OK ){
  179890. p->rc = prepareFreeAndCollectError(p->dbRbu,&pIter->pSelect,pz,zSql);
  179891. }else{
  179892. sqlite3_free(zSql);
  179893. }
  179894. }
  179895. sqlite3_free(zImposterCols);
  179896. sqlite3_free(zImposterPK);
  179897. sqlite3_free(zWhere);
  179898. sqlite3_free(zBind);
  179899. sqlite3_free(zPart);
  179900. }else{
  179901. int bRbuRowid = (pIter->eType==RBU_PK_VTAB)
  179902. ||(pIter->eType==RBU_PK_NONE)
  179903. ||(pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p));
  179904. const char *zTbl = pIter->zTbl; /* Table this step applies to */
  179905. const char *zWrite; /* Imposter table name */
  179906. char *zBindings = rbuObjIterGetBindlist(p, pIter->nTblCol + bRbuRowid);
  179907. char *zWhere = rbuObjIterGetWhere(p, pIter);
  179908. char *zOldlist = rbuObjIterGetOldlist(p, pIter, "old");
  179909. char *zNewlist = rbuObjIterGetOldlist(p, pIter, "new");
  179910. zCollist = rbuObjIterGetCollist(p, pIter);
  179911. pIter->nCol = pIter->nTblCol;
  179912. /* Create the imposter table or tables (if required). */
  179913. rbuCreateImposterTable(p, pIter);
  179914. rbuCreateImposterTable2(p, pIter);
  179915. zWrite = (pIter->eType==RBU_PK_VTAB ? "" : "rbu_imp_");
  179916. /* Create the INSERT statement to write to the target PK b-tree */
  179917. if( p->rc==SQLITE_OK ){
  179918. p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pInsert, pz,
  179919. sqlite3_mprintf(
  179920. "INSERT INTO \"%s%w\"(%s%s) VALUES(%s)",
  179921. zWrite, zTbl, zCollist, (bRbuRowid ? ", _rowid_" : ""), zBindings
  179922. )
  179923. );
  179924. }
  179925. /* Create the DELETE statement to write to the target PK b-tree.
  179926. ** Because it only performs INSERT operations, this is not required for
  179927. ** an rbu vacuum handle. */
  179928. if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){
  179929. p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pDelete, pz,
  179930. sqlite3_mprintf(
  179931. "DELETE FROM \"%s%w\" WHERE %s", zWrite, zTbl, zWhere
  179932. )
  179933. );
  179934. }
  179935. if( rbuIsVacuum(p)==0 && pIter->abIndexed ){
  179936. const char *zRbuRowid = "";
  179937. if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
  179938. zRbuRowid = ", rbu_rowid";
  179939. }
  179940. /* Create the rbu_tmp_xxx table and the triggers to populate it. */
  179941. rbuMPrintfExec(p, p->dbRbu,
  179942. "CREATE TABLE IF NOT EXISTS %s.'rbu_tmp_%q' AS "
  179943. "SELECT *%s FROM '%q' WHERE 0;"
  179944. , p->zStateDb, pIter->zDataTbl
  179945. , (pIter->eType==RBU_PK_EXTERNAL ? ", 0 AS rbu_rowid" : "")
  179946. , pIter->zDataTbl
  179947. );
  179948. rbuMPrintfExec(p, p->dbMain,
  179949. "CREATE TEMP TRIGGER rbu_delete_tr BEFORE DELETE ON \"%s%w\" "
  179950. "BEGIN "
  179951. " SELECT rbu_tmp_insert(3, %s);"
  179952. "END;"
  179953. "CREATE TEMP TRIGGER rbu_update1_tr BEFORE UPDATE ON \"%s%w\" "
  179954. "BEGIN "
  179955. " SELECT rbu_tmp_insert(3, %s);"
  179956. "END;"
  179957. "CREATE TEMP TRIGGER rbu_update2_tr AFTER UPDATE ON \"%s%w\" "
  179958. "BEGIN "
  179959. " SELECT rbu_tmp_insert(4, %s);"
  179960. "END;",
  179961. zWrite, zTbl, zOldlist,
  179962. zWrite, zTbl, zOldlist,
  179963. zWrite, zTbl, zNewlist
  179964. );
  179965. if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
  179966. rbuMPrintfExec(p, p->dbMain,
  179967. "CREATE TEMP TRIGGER rbu_insert_tr AFTER INSERT ON \"%s%w\" "
  179968. "BEGIN "
  179969. " SELECT rbu_tmp_insert(0, %s);"
  179970. "END;",
  179971. zWrite, zTbl, zNewlist
  179972. );
  179973. }
  179974. rbuObjIterPrepareTmpInsert(p, pIter, zCollist, zRbuRowid);
  179975. }
  179976. /* Create the SELECT statement to read keys from data_xxx */
  179977. if( p->rc==SQLITE_OK ){
  179978. const char *zRbuRowid = "";
  179979. char *zStart = 0;
  179980. char *zOrder = 0;
  179981. if( bRbuRowid ){
  179982. zRbuRowid = rbuIsVacuum(p) ? ",_rowid_ " : ",rbu_rowid";
  179983. }
  179984. if( rbuIsVacuum(p) ){
  179985. if( nOffset ){
  179986. zStart = rbuVacuumTableStart(p, pIter, bRbuRowid, zWrite);
  179987. if( zStart ){
  179988. sqlite3_free(zLimit);
  179989. zLimit = 0;
  179990. }
  179991. }
  179992. if( bRbuRowid ){
  179993. zOrder = rbuMPrintf(p, "_rowid_");
  179994. }else{
  179995. zOrder = rbuObjIterGetPkList(p, pIter, "", ", ", "");
  179996. }
  179997. }
  179998. if( p->rc==SQLITE_OK ){
  179999. p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz,
  180000. sqlite3_mprintf(
  180001. "SELECT %s,%s rbu_control%s FROM '%q'%s %s %s %s",
  180002. zCollist,
  180003. (rbuIsVacuum(p) ? "0 AS " : ""),
  180004. zRbuRowid,
  180005. pIter->zDataTbl, (zStart ? zStart : ""),
  180006. (zOrder ? "ORDER BY" : ""), zOrder,
  180007. zLimit
  180008. )
  180009. );
  180010. }
  180011. sqlite3_free(zStart);
  180012. sqlite3_free(zOrder);
  180013. }
  180014. sqlite3_free(zWhere);
  180015. sqlite3_free(zOldlist);
  180016. sqlite3_free(zNewlist);
  180017. sqlite3_free(zBindings);
  180018. }
  180019. sqlite3_free(zCollist);
  180020. sqlite3_free(zLimit);
  180021. }
  180022. return p->rc;
  180023. }
  180024. /*
  180025. ** Set output variable *ppStmt to point to an UPDATE statement that may
  180026. ** be used to update the imposter table for the main table b-tree of the
  180027. ** table object that pIter currently points to, assuming that the
  180028. ** rbu_control column of the data_xyz table contains zMask.
  180029. **
  180030. ** If the zMask string does not specify any columns to update, then this
  180031. ** is not an error. Output variable *ppStmt is set to NULL in this case.
  180032. */
  180033. static int rbuGetUpdateStmt(
  180034. sqlite3rbu *p, /* RBU handle */
  180035. RbuObjIter *pIter, /* Object iterator */
  180036. const char *zMask, /* rbu_control value ('x.x.') */
  180037. sqlite3_stmt **ppStmt /* OUT: UPDATE statement handle */
  180038. ){
  180039. RbuUpdateStmt **pp;
  180040. RbuUpdateStmt *pUp = 0;
  180041. int nUp = 0;
  180042. /* In case an error occurs */
  180043. *ppStmt = 0;
  180044. /* Search for an existing statement. If one is found, shift it to the front
  180045. ** of the LRU queue and return immediately. Otherwise, leave nUp pointing
  180046. ** to the number of statements currently in the cache and pUp to the
  180047. ** last object in the list. */
  180048. for(pp=&pIter->pRbuUpdate; *pp; pp=&((*pp)->pNext)){
  180049. pUp = *pp;
  180050. if( strcmp(pUp->zMask, zMask)==0 ){
  180051. *pp = pUp->pNext;
  180052. pUp->pNext = pIter->pRbuUpdate;
  180053. pIter->pRbuUpdate = pUp;
  180054. *ppStmt = pUp->pUpdate;
  180055. return SQLITE_OK;
  180056. }
  180057. nUp++;
  180058. }
  180059. assert( pUp==0 || pUp->pNext==0 );
  180060. if( nUp>=SQLITE_RBU_UPDATE_CACHESIZE ){
  180061. for(pp=&pIter->pRbuUpdate; *pp!=pUp; pp=&((*pp)->pNext));
  180062. *pp = 0;
  180063. sqlite3_finalize(pUp->pUpdate);
  180064. pUp->pUpdate = 0;
  180065. }else{
  180066. pUp = (RbuUpdateStmt*)rbuMalloc(p, sizeof(RbuUpdateStmt)+pIter->nTblCol+1);
  180067. }
  180068. if( pUp ){
  180069. char *zWhere = rbuObjIterGetWhere(p, pIter);
  180070. char *zSet = rbuObjIterGetSetlist(p, pIter, zMask);
  180071. char *zUpdate = 0;
  180072. pUp->zMask = (char*)&pUp[1];
  180073. memcpy(pUp->zMask, zMask, pIter->nTblCol);
  180074. pUp->pNext = pIter->pRbuUpdate;
  180075. pIter->pRbuUpdate = pUp;
  180076. if( zSet ){
  180077. const char *zPrefix = "";
  180078. if( pIter->eType!=RBU_PK_VTAB ) zPrefix = "rbu_imp_";
  180079. zUpdate = sqlite3_mprintf("UPDATE \"%s%w\" SET %s WHERE %s",
  180080. zPrefix, pIter->zTbl, zSet, zWhere
  180081. );
  180082. p->rc = prepareFreeAndCollectError(
  180083. p->dbMain, &pUp->pUpdate, &p->zErrmsg, zUpdate
  180084. );
  180085. *ppStmt = pUp->pUpdate;
  180086. }
  180087. sqlite3_free(zWhere);
  180088. sqlite3_free(zSet);
  180089. }
  180090. return p->rc;
  180091. }
  180092. static sqlite3 *rbuOpenDbhandle(
  180093. sqlite3rbu *p,
  180094. const char *zName,
  180095. int bUseVfs
  180096. ){
  180097. sqlite3 *db = 0;
  180098. if( p->rc==SQLITE_OK ){
  180099. const int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_URI;
  180100. p->rc = sqlite3_open_v2(zName, &db, flags, bUseVfs ? p->zVfsName : 0);
  180101. if( p->rc ){
  180102. p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  180103. sqlite3_close(db);
  180104. db = 0;
  180105. }
  180106. }
  180107. return db;
  180108. }
  180109. /*
  180110. ** Free an RbuState object allocated by rbuLoadState().
  180111. */
  180112. static void rbuFreeState(RbuState *p){
  180113. if( p ){
  180114. sqlite3_free(p->zTbl);
  180115. sqlite3_free(p->zDataTbl);
  180116. sqlite3_free(p->zIdx);
  180117. sqlite3_free(p);
  180118. }
  180119. }
  180120. /*
  180121. ** Allocate an RbuState object and load the contents of the rbu_state
  180122. ** table into it. Return a pointer to the new object. It is the
  180123. ** responsibility of the caller to eventually free the object using
  180124. ** sqlite3_free().
  180125. **
  180126. ** If an error occurs, leave an error code and message in the rbu handle
  180127. ** and return NULL.
  180128. */
  180129. static RbuState *rbuLoadState(sqlite3rbu *p){
  180130. RbuState *pRet = 0;
  180131. sqlite3_stmt *pStmt = 0;
  180132. int rc;
  180133. int rc2;
  180134. pRet = (RbuState*)rbuMalloc(p, sizeof(RbuState));
  180135. if( pRet==0 ) return 0;
  180136. rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
  180137. sqlite3_mprintf("SELECT k, v FROM %s.rbu_state", p->zStateDb)
  180138. );
  180139. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  180140. switch( sqlite3_column_int(pStmt, 0) ){
  180141. case RBU_STATE_STAGE:
  180142. pRet->eStage = sqlite3_column_int(pStmt, 1);
  180143. if( pRet->eStage!=RBU_STAGE_OAL
  180144. && pRet->eStage!=RBU_STAGE_MOVE
  180145. && pRet->eStage!=RBU_STAGE_CKPT
  180146. ){
  180147. p->rc = SQLITE_CORRUPT;
  180148. }
  180149. break;
  180150. case RBU_STATE_TBL:
  180151. pRet->zTbl = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
  180152. break;
  180153. case RBU_STATE_IDX:
  180154. pRet->zIdx = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
  180155. break;
  180156. case RBU_STATE_ROW:
  180157. pRet->nRow = sqlite3_column_int(pStmt, 1);
  180158. break;
  180159. case RBU_STATE_PROGRESS:
  180160. pRet->nProgress = sqlite3_column_int64(pStmt, 1);
  180161. break;
  180162. case RBU_STATE_CKPT:
  180163. pRet->iWalCksum = sqlite3_column_int64(pStmt, 1);
  180164. break;
  180165. case RBU_STATE_COOKIE:
  180166. pRet->iCookie = (u32)sqlite3_column_int64(pStmt, 1);
  180167. break;
  180168. case RBU_STATE_OALSZ:
  180169. pRet->iOalSz = (u32)sqlite3_column_int64(pStmt, 1);
  180170. break;
  180171. case RBU_STATE_PHASEONESTEP:
  180172. pRet->nPhaseOneStep = sqlite3_column_int64(pStmt, 1);
  180173. break;
  180174. case RBU_STATE_DATATBL:
  180175. pRet->zDataTbl = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
  180176. break;
  180177. default:
  180178. rc = SQLITE_CORRUPT;
  180179. break;
  180180. }
  180181. }
  180182. rc2 = sqlite3_finalize(pStmt);
  180183. if( rc==SQLITE_OK ) rc = rc2;
  180184. p->rc = rc;
  180185. return pRet;
  180186. }
  180187. /*
  180188. ** Open the database handle and attach the RBU database as "rbu". If an
  180189. ** error occurs, leave an error code and message in the RBU handle.
  180190. */
  180191. static void rbuOpenDatabase(sqlite3rbu *p, int *pbRetry){
  180192. assert( p->rc || (p->dbMain==0 && p->dbRbu==0) );
  180193. assert( p->rc || rbuIsVacuum(p) || p->zTarget!=0 );
  180194. /* Open the RBU database */
  180195. p->dbRbu = rbuOpenDbhandle(p, p->zRbu, 1);
  180196. if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
  180197. sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p);
  180198. if( p->zState==0 ){
  180199. const char *zFile = sqlite3_db_filename(p->dbRbu, "main");
  180200. p->zState = rbuMPrintf(p, "file://%s-vacuum?modeof=%s", zFile, zFile);
  180201. }
  180202. }
  180203. /* If using separate RBU and state databases, attach the state database to
  180204. ** the RBU db handle now. */
  180205. if( p->zState ){
  180206. rbuMPrintfExec(p, p->dbRbu, "ATTACH %Q AS stat", p->zState);
  180207. memcpy(p->zStateDb, "stat", 4);
  180208. }else{
  180209. memcpy(p->zStateDb, "main", 4);
  180210. }
  180211. #if 0
  180212. if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
  180213. p->rc = sqlite3_exec(p->dbRbu, "BEGIN", 0, 0, 0);
  180214. }
  180215. #endif
  180216. /* If it has not already been created, create the rbu_state table */
  180217. rbuMPrintfExec(p, p->dbRbu, RBU_CREATE_STATE, p->zStateDb);
  180218. #if 0
  180219. if( rbuIsVacuum(p) ){
  180220. if( p->rc==SQLITE_OK ){
  180221. int rc2;
  180222. int bOk = 0;
  180223. sqlite3_stmt *pCnt = 0;
  180224. p->rc = prepareAndCollectError(p->dbRbu, &pCnt, &p->zErrmsg,
  180225. "SELECT count(*) FROM stat.sqlite_master"
  180226. );
  180227. if( p->rc==SQLITE_OK
  180228. && sqlite3_step(pCnt)==SQLITE_ROW
  180229. && 1==sqlite3_column_int(pCnt, 0)
  180230. ){
  180231. bOk = 1;
  180232. }
  180233. rc2 = sqlite3_finalize(pCnt);
  180234. if( p->rc==SQLITE_OK ) p->rc = rc2;
  180235. if( p->rc==SQLITE_OK && bOk==0 ){
  180236. p->rc = SQLITE_ERROR;
  180237. p->zErrmsg = sqlite3_mprintf("invalid state database");
  180238. }
  180239. if( p->rc==SQLITE_OK ){
  180240. p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0);
  180241. }
  180242. }
  180243. }
  180244. #endif
  180245. if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
  180246. int bOpen = 0;
  180247. int rc;
  180248. p->nRbu = 0;
  180249. p->pRbuFd = 0;
  180250. rc = sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p);
  180251. if( rc!=SQLITE_NOTFOUND ) p->rc = rc;
  180252. if( p->eStage>=RBU_STAGE_MOVE ){
  180253. bOpen = 1;
  180254. }else{
  180255. RbuState *pState = rbuLoadState(p);
  180256. if( pState ){
  180257. bOpen = (pState->eStage>=RBU_STAGE_MOVE);
  180258. rbuFreeState(pState);
  180259. }
  180260. }
  180261. if( bOpen ) p->dbMain = rbuOpenDbhandle(p, p->zRbu, p->nRbu<=1);
  180262. }
  180263. p->eStage = 0;
  180264. if( p->rc==SQLITE_OK && p->dbMain==0 ){
  180265. if( !rbuIsVacuum(p) ){
  180266. p->dbMain = rbuOpenDbhandle(p, p->zTarget, 1);
  180267. }else if( p->pRbuFd->pWalFd ){
  180268. if( pbRetry ){
  180269. p->pRbuFd->bNolock = 0;
  180270. sqlite3_close(p->dbRbu);
  180271. sqlite3_close(p->dbMain);
  180272. p->dbMain = 0;
  180273. p->dbRbu = 0;
  180274. *pbRetry = 1;
  180275. return;
  180276. }
  180277. p->rc = SQLITE_ERROR;
  180278. p->zErrmsg = sqlite3_mprintf("cannot vacuum wal mode database");
  180279. }else{
  180280. char *zTarget;
  180281. char *zExtra = 0;
  180282. if( strlen(p->zRbu)>=5 && 0==memcmp("file:", p->zRbu, 5) ){
  180283. zExtra = &p->zRbu[5];
  180284. while( *zExtra ){
  180285. if( *zExtra++=='?' ) break;
  180286. }
  180287. if( *zExtra=='\0' ) zExtra = 0;
  180288. }
  180289. zTarget = sqlite3_mprintf("file:%s-vactmp?rbu_memory=1%s%s",
  180290. sqlite3_db_filename(p->dbRbu, "main"),
  180291. (zExtra==0 ? "" : "&"), (zExtra==0 ? "" : zExtra)
  180292. );
  180293. if( zTarget==0 ){
  180294. p->rc = SQLITE_NOMEM;
  180295. return;
  180296. }
  180297. p->dbMain = rbuOpenDbhandle(p, zTarget, p->nRbu<=1);
  180298. sqlite3_free(zTarget);
  180299. }
  180300. }
  180301. if( p->rc==SQLITE_OK ){
  180302. p->rc = sqlite3_create_function(p->dbMain,
  180303. "rbu_tmp_insert", -1, SQLITE_UTF8, (void*)p, rbuTmpInsertFunc, 0, 0
  180304. );
  180305. }
  180306. if( p->rc==SQLITE_OK ){
  180307. p->rc = sqlite3_create_function(p->dbMain,
  180308. "rbu_fossil_delta", 2, SQLITE_UTF8, 0, rbuFossilDeltaFunc, 0, 0
  180309. );
  180310. }
  180311. if( p->rc==SQLITE_OK ){
  180312. p->rc = sqlite3_create_function(p->dbRbu,
  180313. "rbu_target_name", -1, SQLITE_UTF8, (void*)p, rbuTargetNameFunc, 0, 0
  180314. );
  180315. }
  180316. if( p->rc==SQLITE_OK ){
  180317. p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
  180318. }
  180319. rbuMPrintfExec(p, p->dbMain, "SELECT * FROM sqlite_master");
  180320. /* Mark the database file just opened as an RBU target database. If
  180321. ** this call returns SQLITE_NOTFOUND, then the RBU vfs is not in use.
  180322. ** This is an error. */
  180323. if( p->rc==SQLITE_OK ){
  180324. p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
  180325. }
  180326. if( p->rc==SQLITE_NOTFOUND ){
  180327. p->rc = SQLITE_ERROR;
  180328. p->zErrmsg = sqlite3_mprintf("rbu vfs not found");
  180329. }
  180330. }
  180331. /*
  180332. ** This routine is a copy of the sqlite3FileSuffix3() routine from the core.
  180333. ** It is a no-op unless SQLITE_ENABLE_8_3_NAMES is defined.
  180334. **
  180335. ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
  180336. ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
  180337. ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
  180338. ** three characters, then shorten the suffix on z[] to be the last three
  180339. ** characters of the original suffix.
  180340. **
  180341. ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
  180342. ** do the suffix shortening regardless of URI parameter.
  180343. **
  180344. ** Examples:
  180345. **
  180346. ** test.db-journal => test.nal
  180347. ** test.db-wal => test.wal
  180348. ** test.db-shm => test.shm
  180349. ** test.db-mj7f3319fa => test.9fa
  180350. */
  180351. static void rbuFileSuffix3(const char *zBase, char *z){
  180352. #ifdef SQLITE_ENABLE_8_3_NAMES
  180353. #if SQLITE_ENABLE_8_3_NAMES<2
  180354. if( sqlite3_uri_boolean(zBase, "8_3_names", 0) )
  180355. #endif
  180356. {
  180357. int i, sz;
  180358. sz = (int)strlen(z)&0xffffff;
  180359. for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
  180360. if( z[i]=='.' && sz>i+4 ) memmove(&z[i+1], &z[sz-3], 4);
  180361. }
  180362. #endif
  180363. }
  180364. /*
  180365. ** Return the current wal-index header checksum for the target database
  180366. ** as a 64-bit integer.
  180367. **
  180368. ** The checksum is store in the first page of xShmMap memory as an 8-byte
  180369. ** blob starting at byte offset 40.
  180370. */
  180371. static i64 rbuShmChecksum(sqlite3rbu *p){
  180372. i64 iRet = 0;
  180373. if( p->rc==SQLITE_OK ){
  180374. sqlite3_file *pDb = p->pTargetFd->pReal;
  180375. u32 volatile *ptr;
  180376. p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, (void volatile**)&ptr);
  180377. if( p->rc==SQLITE_OK ){
  180378. iRet = ((i64)ptr[10] << 32) + ptr[11];
  180379. }
  180380. }
  180381. return iRet;
  180382. }
  180383. /*
  180384. ** This function is called as part of initializing or reinitializing an
  180385. ** incremental checkpoint.
  180386. **
  180387. ** It populates the sqlite3rbu.aFrame[] array with the set of
  180388. ** (wal frame -> db page) copy operations required to checkpoint the
  180389. ** current wal file, and obtains the set of shm locks required to safely
  180390. ** perform the copy operations directly on the file-system.
  180391. **
  180392. ** If argument pState is not NULL, then the incremental checkpoint is
  180393. ** being resumed. In this case, if the checksum of the wal-index-header
  180394. ** following recovery is not the same as the checksum saved in the RbuState
  180395. ** object, then the rbu handle is set to DONE state. This occurs if some
  180396. ** other client appends a transaction to the wal file in the middle of
  180397. ** an incremental checkpoint.
  180398. */
  180399. static void rbuSetupCheckpoint(sqlite3rbu *p, RbuState *pState){
  180400. /* If pState is NULL, then the wal file may not have been opened and
  180401. ** recovered. Running a read-statement here to ensure that doing so
  180402. ** does not interfere with the "capture" process below. */
  180403. if( pState==0 ){
  180404. p->eStage = 0;
  180405. if( p->rc==SQLITE_OK ){
  180406. p->rc = sqlite3_exec(p->dbMain, "SELECT * FROM sqlite_master", 0, 0, 0);
  180407. }
  180408. }
  180409. /* Assuming no error has occurred, run a "restart" checkpoint with the
  180410. ** sqlite3rbu.eStage variable set to CAPTURE. This turns on the following
  180411. ** special behaviour in the rbu VFS:
  180412. **
  180413. ** * If the exclusive shm WRITER or READ0 lock cannot be obtained,
  180414. ** the checkpoint fails with SQLITE_BUSY (normally SQLite would
  180415. ** proceed with running a passive checkpoint instead of failing).
  180416. **
  180417. ** * Attempts to read from the *-wal file or write to the database file
  180418. ** do not perform any IO. Instead, the frame/page combinations that
  180419. ** would be read/written are recorded in the sqlite3rbu.aFrame[]
  180420. ** array.
  180421. **
  180422. ** * Calls to xShmLock(UNLOCK) to release the exclusive shm WRITER,
  180423. ** READ0 and CHECKPOINT locks taken as part of the checkpoint are
  180424. ** no-ops. These locks will not be released until the connection
  180425. ** is closed.
  180426. **
  180427. ** * Attempting to xSync() the database file causes an SQLITE_INTERNAL
  180428. ** error.
  180429. **
  180430. ** As a result, unless an error (i.e. OOM or SQLITE_BUSY) occurs, the
  180431. ** checkpoint below fails with SQLITE_INTERNAL, and leaves the aFrame[]
  180432. ** array populated with a set of (frame -> page) mappings. Because the
  180433. ** WRITER, CHECKPOINT and READ0 locks are still held, it is safe to copy
  180434. ** data from the wal file into the database file according to the
  180435. ** contents of aFrame[].
  180436. */
  180437. if( p->rc==SQLITE_OK ){
  180438. int rc2;
  180439. p->eStage = RBU_STAGE_CAPTURE;
  180440. rc2 = sqlite3_exec(p->dbMain, "PRAGMA main.wal_checkpoint=restart", 0, 0,0);
  180441. if( rc2!=SQLITE_INTERNAL ) p->rc = rc2;
  180442. }
  180443. if( p->rc==SQLITE_OK && p->nFrame>0 ){
  180444. p->eStage = RBU_STAGE_CKPT;
  180445. p->nStep = (pState ? pState->nRow : 0);
  180446. p->aBuf = rbuMalloc(p, p->pgsz);
  180447. p->iWalCksum = rbuShmChecksum(p);
  180448. }
  180449. if( p->rc==SQLITE_OK ){
  180450. if( p->nFrame==0 || (pState && pState->iWalCksum!=p->iWalCksum) ){
  180451. p->rc = SQLITE_DONE;
  180452. p->eStage = RBU_STAGE_DONE;
  180453. }else{
  180454. int nSectorSize;
  180455. sqlite3_file *pDb = p->pTargetFd->pReal;
  180456. sqlite3_file *pWal = p->pTargetFd->pWalFd->pReal;
  180457. assert( p->nPagePerSector==0 );
  180458. nSectorSize = pDb->pMethods->xSectorSize(pDb);
  180459. if( nSectorSize>p->pgsz ){
  180460. p->nPagePerSector = nSectorSize / p->pgsz;
  180461. }else{
  180462. p->nPagePerSector = 1;
  180463. }
  180464. /* Call xSync() on the wal file. This causes SQLite to sync the
  180465. ** directory in which the target database and the wal file reside, in
  180466. ** case it has not been synced since the rename() call in
  180467. ** rbuMoveOalFile(). */
  180468. p->rc = pWal->pMethods->xSync(pWal, SQLITE_SYNC_NORMAL);
  180469. }
  180470. }
  180471. }
  180472. /*
  180473. ** Called when iAmt bytes are read from offset iOff of the wal file while
  180474. ** the rbu object is in capture mode. Record the frame number of the frame
  180475. ** being read in the aFrame[] array.
  180476. */
  180477. static int rbuCaptureWalRead(sqlite3rbu *pRbu, i64 iOff, int iAmt){
  180478. const u32 mReq = (1<<WAL_LOCK_WRITE)|(1<<WAL_LOCK_CKPT)|(1<<WAL_LOCK_READ0);
  180479. u32 iFrame;
  180480. if( pRbu->mLock!=mReq ){
  180481. pRbu->rc = SQLITE_BUSY;
  180482. return SQLITE_INTERNAL;
  180483. }
  180484. pRbu->pgsz = iAmt;
  180485. if( pRbu->nFrame==pRbu->nFrameAlloc ){
  180486. int nNew = (pRbu->nFrameAlloc ? pRbu->nFrameAlloc : 64) * 2;
  180487. RbuFrame *aNew;
  180488. aNew = (RbuFrame*)sqlite3_realloc64(pRbu->aFrame, nNew * sizeof(RbuFrame));
  180489. if( aNew==0 ) return SQLITE_NOMEM;
  180490. pRbu->aFrame = aNew;
  180491. pRbu->nFrameAlloc = nNew;
  180492. }
  180493. iFrame = (u32)((iOff-32) / (i64)(iAmt+24)) + 1;
  180494. if( pRbu->iMaxFrame<iFrame ) pRbu->iMaxFrame = iFrame;
  180495. pRbu->aFrame[pRbu->nFrame].iWalFrame = iFrame;
  180496. pRbu->aFrame[pRbu->nFrame].iDbPage = 0;
  180497. pRbu->nFrame++;
  180498. return SQLITE_OK;
  180499. }
  180500. /*
  180501. ** Called when a page of data is written to offset iOff of the database
  180502. ** file while the rbu handle is in capture mode. Record the page number
  180503. ** of the page being written in the aFrame[] array.
  180504. */
  180505. static int rbuCaptureDbWrite(sqlite3rbu *pRbu, i64 iOff){
  180506. pRbu->aFrame[pRbu->nFrame-1].iDbPage = (u32)(iOff / pRbu->pgsz) + 1;
  180507. return SQLITE_OK;
  180508. }
  180509. /*
  180510. ** This is called as part of an incremental checkpoint operation. Copy
  180511. ** a single frame of data from the wal file into the database file, as
  180512. ** indicated by the RbuFrame object.
  180513. */
  180514. static void rbuCheckpointFrame(sqlite3rbu *p, RbuFrame *pFrame){
  180515. sqlite3_file *pWal = p->pTargetFd->pWalFd->pReal;
  180516. sqlite3_file *pDb = p->pTargetFd->pReal;
  180517. i64 iOff;
  180518. assert( p->rc==SQLITE_OK );
  180519. iOff = (i64)(pFrame->iWalFrame-1) * (p->pgsz + 24) + 32 + 24;
  180520. p->rc = pWal->pMethods->xRead(pWal, p->aBuf, p->pgsz, iOff);
  180521. if( p->rc ) return;
  180522. iOff = (i64)(pFrame->iDbPage-1) * p->pgsz;
  180523. p->rc = pDb->pMethods->xWrite(pDb, p->aBuf, p->pgsz, iOff);
  180524. }
  180525. /*
  180526. ** Take an EXCLUSIVE lock on the database file.
  180527. */
  180528. static void rbuLockDatabase(sqlite3rbu *p){
  180529. sqlite3_file *pReal = p->pTargetFd->pReal;
  180530. assert( p->rc==SQLITE_OK );
  180531. p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_SHARED);
  180532. if( p->rc==SQLITE_OK ){
  180533. p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_EXCLUSIVE);
  180534. }
  180535. }
  180536. #if defined(_WIN32_WCE)
  180537. static LPWSTR rbuWinUtf8ToUnicode(const char *zFilename){
  180538. int nChar;
  180539. LPWSTR zWideFilename;
  180540. nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
  180541. if( nChar==0 ){
  180542. return 0;
  180543. }
  180544. zWideFilename = sqlite3_malloc64( nChar*sizeof(zWideFilename[0]) );
  180545. if( zWideFilename==0 ){
  180546. return 0;
  180547. }
  180548. memset(zWideFilename, 0, nChar*sizeof(zWideFilename[0]));
  180549. nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
  180550. nChar);
  180551. if( nChar==0 ){
  180552. sqlite3_free(zWideFilename);
  180553. zWideFilename = 0;
  180554. }
  180555. return zWideFilename;
  180556. }
  180557. #endif
  180558. /*
  180559. ** The RBU handle is currently in RBU_STAGE_OAL state, with a SHARED lock
  180560. ** on the database file. This proc moves the *-oal file to the *-wal path,
  180561. ** then reopens the database file (this time in vanilla, non-oal, WAL mode).
  180562. ** If an error occurs, leave an error code and error message in the rbu
  180563. ** handle.
  180564. */
  180565. static void rbuMoveOalFile(sqlite3rbu *p){
  180566. const char *zBase = sqlite3_db_filename(p->dbMain, "main");
  180567. const char *zMove = zBase;
  180568. char *zOal;
  180569. char *zWal;
  180570. if( rbuIsVacuum(p) ){
  180571. zMove = sqlite3_db_filename(p->dbRbu, "main");
  180572. }
  180573. zOal = sqlite3_mprintf("%s-oal", zMove);
  180574. zWal = sqlite3_mprintf("%s-wal", zMove);
  180575. assert( p->eStage==RBU_STAGE_MOVE );
  180576. assert( p->rc==SQLITE_OK && p->zErrmsg==0 );
  180577. if( zWal==0 || zOal==0 ){
  180578. p->rc = SQLITE_NOMEM;
  180579. }else{
  180580. /* Move the *-oal file to *-wal. At this point connection p->db is
  180581. ** holding a SHARED lock on the target database file (because it is
  180582. ** in WAL mode). So no other connection may be writing the db.
  180583. **
  180584. ** In order to ensure that there are no database readers, an EXCLUSIVE
  180585. ** lock is obtained here before the *-oal is moved to *-wal.
  180586. */
  180587. rbuLockDatabase(p);
  180588. if( p->rc==SQLITE_OK ){
  180589. rbuFileSuffix3(zBase, zWal);
  180590. rbuFileSuffix3(zBase, zOal);
  180591. /* Re-open the databases. */
  180592. rbuObjIterFinalize(&p->objiter);
  180593. sqlite3_close(p->dbRbu);
  180594. sqlite3_close(p->dbMain);
  180595. p->dbMain = 0;
  180596. p->dbRbu = 0;
  180597. #if defined(_WIN32_WCE)
  180598. {
  180599. LPWSTR zWideOal;
  180600. LPWSTR zWideWal;
  180601. zWideOal = rbuWinUtf8ToUnicode(zOal);
  180602. if( zWideOal ){
  180603. zWideWal = rbuWinUtf8ToUnicode(zWal);
  180604. if( zWideWal ){
  180605. if( MoveFileW(zWideOal, zWideWal) ){
  180606. p->rc = SQLITE_OK;
  180607. }else{
  180608. p->rc = SQLITE_IOERR;
  180609. }
  180610. sqlite3_free(zWideWal);
  180611. }else{
  180612. p->rc = SQLITE_IOERR_NOMEM;
  180613. }
  180614. sqlite3_free(zWideOal);
  180615. }else{
  180616. p->rc = SQLITE_IOERR_NOMEM;
  180617. }
  180618. }
  180619. #else
  180620. p->rc = rename(zOal, zWal) ? SQLITE_IOERR : SQLITE_OK;
  180621. #endif
  180622. if( p->rc==SQLITE_OK ){
  180623. rbuOpenDatabase(p, 0);
  180624. rbuSetupCheckpoint(p, 0);
  180625. }
  180626. }
  180627. }
  180628. sqlite3_free(zWal);
  180629. sqlite3_free(zOal);
  180630. }
  180631. /*
  180632. ** The SELECT statement iterating through the keys for the current object
  180633. ** (p->objiter.pSelect) currently points to a valid row. This function
  180634. ** determines the type of operation requested by this row and returns
  180635. ** one of the following values to indicate the result:
  180636. **
  180637. ** * RBU_INSERT
  180638. ** * RBU_DELETE
  180639. ** * RBU_IDX_DELETE
  180640. ** * RBU_UPDATE
  180641. **
  180642. ** If RBU_UPDATE is returned, then output variable *pzMask is set to
  180643. ** point to the text value indicating the columns to update.
  180644. **
  180645. ** If the rbu_control field contains an invalid value, an error code and
  180646. ** message are left in the RBU handle and zero returned.
  180647. */
  180648. static int rbuStepType(sqlite3rbu *p, const char **pzMask){
  180649. int iCol = p->objiter.nCol; /* Index of rbu_control column */
  180650. int res = 0; /* Return value */
  180651. switch( sqlite3_column_type(p->objiter.pSelect, iCol) ){
  180652. case SQLITE_INTEGER: {
  180653. int iVal = sqlite3_column_int(p->objiter.pSelect, iCol);
  180654. switch( iVal ){
  180655. case 0: res = RBU_INSERT; break;
  180656. case 1: res = RBU_DELETE; break;
  180657. case 2: res = RBU_REPLACE; break;
  180658. case 3: res = RBU_IDX_DELETE; break;
  180659. case 4: res = RBU_IDX_INSERT; break;
  180660. }
  180661. break;
  180662. }
  180663. case SQLITE_TEXT: {
  180664. const unsigned char *z = sqlite3_column_text(p->objiter.pSelect, iCol);
  180665. if( z==0 ){
  180666. p->rc = SQLITE_NOMEM;
  180667. }else{
  180668. *pzMask = (const char*)z;
  180669. }
  180670. res = RBU_UPDATE;
  180671. break;
  180672. }
  180673. default:
  180674. break;
  180675. }
  180676. if( res==0 ){
  180677. rbuBadControlError(p);
  180678. }
  180679. return res;
  180680. }
  180681. #ifdef SQLITE_DEBUG
  180682. /*
  180683. ** Assert that column iCol of statement pStmt is named zName.
  180684. */
  180685. static void assertColumnName(sqlite3_stmt *pStmt, int iCol, const char *zName){
  180686. const char *zCol = sqlite3_column_name(pStmt, iCol);
  180687. assert( 0==sqlite3_stricmp(zName, zCol) );
  180688. }
  180689. #else
  180690. # define assertColumnName(x,y,z)
  180691. #endif
  180692. /*
  180693. ** Argument eType must be one of RBU_INSERT, RBU_DELETE, RBU_IDX_INSERT or
  180694. ** RBU_IDX_DELETE. This function performs the work of a single
  180695. ** sqlite3rbu_step() call for the type of operation specified by eType.
  180696. */
  180697. static void rbuStepOneOp(sqlite3rbu *p, int eType){
  180698. RbuObjIter *pIter = &p->objiter;
  180699. sqlite3_value *pVal;
  180700. sqlite3_stmt *pWriter;
  180701. int i;
  180702. assert( p->rc==SQLITE_OK );
  180703. assert( eType!=RBU_DELETE || pIter->zIdx==0 );
  180704. assert( eType==RBU_DELETE || eType==RBU_IDX_DELETE
  180705. || eType==RBU_INSERT || eType==RBU_IDX_INSERT
  180706. );
  180707. /* If this is a delete, decrement nPhaseOneStep by nIndex. If the DELETE
  180708. ** statement below does actually delete a row, nPhaseOneStep will be
  180709. ** incremented by the same amount when SQL function rbu_tmp_insert()
  180710. ** is invoked by the trigger. */
  180711. if( eType==RBU_DELETE ){
  180712. p->nPhaseOneStep -= p->objiter.nIndex;
  180713. }
  180714. if( eType==RBU_IDX_DELETE || eType==RBU_DELETE ){
  180715. pWriter = pIter->pDelete;
  180716. }else{
  180717. pWriter = pIter->pInsert;
  180718. }
  180719. for(i=0; i<pIter->nCol; i++){
  180720. /* If this is an INSERT into a table b-tree and the table has an
  180721. ** explicit INTEGER PRIMARY KEY, check that this is not an attempt
  180722. ** to write a NULL into the IPK column. That is not permitted. */
  180723. if( eType==RBU_INSERT
  180724. && pIter->zIdx==0 && pIter->eType==RBU_PK_IPK && pIter->abTblPk[i]
  180725. && sqlite3_column_type(pIter->pSelect, i)==SQLITE_NULL
  180726. ){
  180727. p->rc = SQLITE_MISMATCH;
  180728. p->zErrmsg = sqlite3_mprintf("datatype mismatch");
  180729. return;
  180730. }
  180731. if( eType==RBU_DELETE && pIter->abTblPk[i]==0 ){
  180732. continue;
  180733. }
  180734. pVal = sqlite3_column_value(pIter->pSelect, i);
  180735. p->rc = sqlite3_bind_value(pWriter, i+1, pVal);
  180736. if( p->rc ) return;
  180737. }
  180738. if( pIter->zIdx==0 ){
  180739. if( pIter->eType==RBU_PK_VTAB
  180740. || pIter->eType==RBU_PK_NONE
  180741. || (pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p))
  180742. ){
  180743. /* For a virtual table, or a table with no primary key, the
  180744. ** SELECT statement is:
  180745. **
  180746. ** SELECT <cols>, rbu_control, rbu_rowid FROM ....
  180747. **
  180748. ** Hence column_value(pIter->nCol+1).
  180749. */
  180750. assertColumnName(pIter->pSelect, pIter->nCol+1,
  180751. rbuIsVacuum(p) ? "rowid" : "rbu_rowid"
  180752. );
  180753. pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
  180754. p->rc = sqlite3_bind_value(pWriter, pIter->nCol+1, pVal);
  180755. }
  180756. }
  180757. if( p->rc==SQLITE_OK ){
  180758. sqlite3_step(pWriter);
  180759. p->rc = resetAndCollectError(pWriter, &p->zErrmsg);
  180760. }
  180761. }
  180762. /*
  180763. ** This function does the work for an sqlite3rbu_step() call.
  180764. **
  180765. ** The object-iterator (p->objiter) currently points to a valid object,
  180766. ** and the input cursor (p->objiter.pSelect) currently points to a valid
  180767. ** input row. Perform whatever processing is required and return.
  180768. **
  180769. ** If no error occurs, SQLITE_OK is returned. Otherwise, an error code
  180770. ** and message is left in the RBU handle and a copy of the error code
  180771. ** returned.
  180772. */
  180773. static int rbuStep(sqlite3rbu *p){
  180774. RbuObjIter *pIter = &p->objiter;
  180775. const char *zMask = 0;
  180776. int eType = rbuStepType(p, &zMask);
  180777. if( eType ){
  180778. assert( eType==RBU_INSERT || eType==RBU_DELETE
  180779. || eType==RBU_REPLACE || eType==RBU_IDX_DELETE
  180780. || eType==RBU_IDX_INSERT || eType==RBU_UPDATE
  180781. );
  180782. assert( eType!=RBU_UPDATE || pIter->zIdx==0 );
  180783. if( pIter->zIdx==0 && (eType==RBU_IDX_DELETE || eType==RBU_IDX_INSERT) ){
  180784. rbuBadControlError(p);
  180785. }
  180786. else if( eType==RBU_REPLACE ){
  180787. if( pIter->zIdx==0 ){
  180788. p->nPhaseOneStep += p->objiter.nIndex;
  180789. rbuStepOneOp(p, RBU_DELETE);
  180790. }
  180791. if( p->rc==SQLITE_OK ) rbuStepOneOp(p, RBU_INSERT);
  180792. }
  180793. else if( eType!=RBU_UPDATE ){
  180794. rbuStepOneOp(p, eType);
  180795. }
  180796. else{
  180797. sqlite3_value *pVal;
  180798. sqlite3_stmt *pUpdate = 0;
  180799. assert( eType==RBU_UPDATE );
  180800. p->nPhaseOneStep -= p->objiter.nIndex;
  180801. rbuGetUpdateStmt(p, pIter, zMask, &pUpdate);
  180802. if( pUpdate ){
  180803. int i;
  180804. for(i=0; p->rc==SQLITE_OK && i<pIter->nCol; i++){
  180805. char c = zMask[pIter->aiSrcOrder[i]];
  180806. pVal = sqlite3_column_value(pIter->pSelect, i);
  180807. if( pIter->abTblPk[i] || c!='.' ){
  180808. p->rc = sqlite3_bind_value(pUpdate, i+1, pVal);
  180809. }
  180810. }
  180811. if( p->rc==SQLITE_OK
  180812. && (pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
  180813. ){
  180814. /* Bind the rbu_rowid value to column _rowid_ */
  180815. assertColumnName(pIter->pSelect, pIter->nCol+1, "rbu_rowid");
  180816. pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
  180817. p->rc = sqlite3_bind_value(pUpdate, pIter->nCol+1, pVal);
  180818. }
  180819. if( p->rc==SQLITE_OK ){
  180820. sqlite3_step(pUpdate);
  180821. p->rc = resetAndCollectError(pUpdate, &p->zErrmsg);
  180822. }
  180823. }
  180824. }
  180825. }
  180826. return p->rc;
  180827. }
  180828. /*
  180829. ** Increment the schema cookie of the main database opened by p->dbMain.
  180830. **
  180831. ** Or, if this is an RBU vacuum, set the schema cookie of the main db
  180832. ** opened by p->dbMain to one more than the schema cookie of the main
  180833. ** db opened by p->dbRbu.
  180834. */
  180835. static void rbuIncrSchemaCookie(sqlite3rbu *p){
  180836. if( p->rc==SQLITE_OK ){
  180837. sqlite3 *dbread = (rbuIsVacuum(p) ? p->dbRbu : p->dbMain);
  180838. int iCookie = 1000000;
  180839. sqlite3_stmt *pStmt;
  180840. p->rc = prepareAndCollectError(dbread, &pStmt, &p->zErrmsg,
  180841. "PRAGMA schema_version"
  180842. );
  180843. if( p->rc==SQLITE_OK ){
  180844. /* Coverage: it may be that this sqlite3_step() cannot fail. There
  180845. ** is already a transaction open, so the prepared statement cannot
  180846. ** throw an SQLITE_SCHEMA exception. The only database page the
  180847. ** statement reads is page 1, which is guaranteed to be in the cache.
  180848. ** And no memory allocations are required. */
  180849. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  180850. iCookie = sqlite3_column_int(pStmt, 0);
  180851. }
  180852. rbuFinalize(p, pStmt);
  180853. }
  180854. if( p->rc==SQLITE_OK ){
  180855. rbuMPrintfExec(p, p->dbMain, "PRAGMA schema_version = %d", iCookie+1);
  180856. }
  180857. }
  180858. }
  180859. /*
  180860. ** Update the contents of the rbu_state table within the rbu database. The
  180861. ** value stored in the RBU_STATE_STAGE column is eStage. All other values
  180862. ** are determined by inspecting the rbu handle passed as the first argument.
  180863. */
  180864. static void rbuSaveState(sqlite3rbu *p, int eStage){
  180865. if( p->rc==SQLITE_OK || p->rc==SQLITE_DONE ){
  180866. sqlite3_stmt *pInsert = 0;
  180867. rbu_file *pFd = (rbuIsVacuum(p) ? p->pRbuFd : p->pTargetFd);
  180868. int rc;
  180869. assert( p->zErrmsg==0 );
  180870. rc = prepareFreeAndCollectError(p->dbRbu, &pInsert, &p->zErrmsg,
  180871. sqlite3_mprintf(
  180872. "INSERT OR REPLACE INTO %s.rbu_state(k, v) VALUES "
  180873. "(%d, %d), "
  180874. "(%d, %Q), "
  180875. "(%d, %Q), "
  180876. "(%d, %d), "
  180877. "(%d, %d), "
  180878. "(%d, %lld), "
  180879. "(%d, %lld), "
  180880. "(%d, %lld), "
  180881. "(%d, %lld), "
  180882. "(%d, %Q) ",
  180883. p->zStateDb,
  180884. RBU_STATE_STAGE, eStage,
  180885. RBU_STATE_TBL, p->objiter.zTbl,
  180886. RBU_STATE_IDX, p->objiter.zIdx,
  180887. RBU_STATE_ROW, p->nStep,
  180888. RBU_STATE_PROGRESS, p->nProgress,
  180889. RBU_STATE_CKPT, p->iWalCksum,
  180890. RBU_STATE_COOKIE, (i64)pFd->iCookie,
  180891. RBU_STATE_OALSZ, p->iOalSz,
  180892. RBU_STATE_PHASEONESTEP, p->nPhaseOneStep,
  180893. RBU_STATE_DATATBL, p->objiter.zDataTbl
  180894. )
  180895. );
  180896. assert( pInsert==0 || rc==SQLITE_OK );
  180897. if( rc==SQLITE_OK ){
  180898. sqlite3_step(pInsert);
  180899. rc = sqlite3_finalize(pInsert);
  180900. }
  180901. if( rc!=SQLITE_OK ) p->rc = rc;
  180902. }
  180903. }
  180904. /*
  180905. ** The second argument passed to this function is the name of a PRAGMA
  180906. ** setting - "page_size", "auto_vacuum", "user_version" or "application_id".
  180907. ** This function executes the following on sqlite3rbu.dbRbu:
  180908. **
  180909. ** "PRAGMA main.$zPragma"
  180910. **
  180911. ** where $zPragma is the string passed as the second argument, then
  180912. ** on sqlite3rbu.dbMain:
  180913. **
  180914. ** "PRAGMA main.$zPragma = $val"
  180915. **
  180916. ** where $val is the value returned by the first PRAGMA invocation.
  180917. **
  180918. ** In short, it copies the value of the specified PRAGMA setting from
  180919. ** dbRbu to dbMain.
  180920. */
  180921. static void rbuCopyPragma(sqlite3rbu *p, const char *zPragma){
  180922. if( p->rc==SQLITE_OK ){
  180923. sqlite3_stmt *pPragma = 0;
  180924. p->rc = prepareFreeAndCollectError(p->dbRbu, &pPragma, &p->zErrmsg,
  180925. sqlite3_mprintf("PRAGMA main.%s", zPragma)
  180926. );
  180927. if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPragma) ){
  180928. p->rc = rbuMPrintfExec(p, p->dbMain, "PRAGMA main.%s = %d",
  180929. zPragma, sqlite3_column_int(pPragma, 0)
  180930. );
  180931. }
  180932. rbuFinalize(p, pPragma);
  180933. }
  180934. }
  180935. /*
  180936. ** The RBU handle passed as the only argument has just been opened and
  180937. ** the state database is empty. If this RBU handle was opened for an
  180938. ** RBU vacuum operation, create the schema in the target db.
  180939. */
  180940. static void rbuCreateTargetSchema(sqlite3rbu *p){
  180941. sqlite3_stmt *pSql = 0;
  180942. sqlite3_stmt *pInsert = 0;
  180943. assert( rbuIsVacuum(p) );
  180944. p->rc = sqlite3_exec(p->dbMain, "PRAGMA writable_schema=1", 0,0, &p->zErrmsg);
  180945. if( p->rc==SQLITE_OK ){
  180946. p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg,
  180947. "SELECT sql FROM sqlite_master WHERE sql!='' AND rootpage!=0"
  180948. " AND name!='sqlite_sequence' "
  180949. " ORDER BY type DESC"
  180950. );
  180951. }
  180952. while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){
  180953. const char *zSql = (const char*)sqlite3_column_text(pSql, 0);
  180954. p->rc = sqlite3_exec(p->dbMain, zSql, 0, 0, &p->zErrmsg);
  180955. }
  180956. rbuFinalize(p, pSql);
  180957. if( p->rc!=SQLITE_OK ) return;
  180958. if( p->rc==SQLITE_OK ){
  180959. p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg,
  180960. "SELECT * FROM sqlite_master WHERE rootpage=0 OR rootpage IS NULL"
  180961. );
  180962. }
  180963. if( p->rc==SQLITE_OK ){
  180964. p->rc = prepareAndCollectError(p->dbMain, &pInsert, &p->zErrmsg,
  180965. "INSERT INTO sqlite_master VALUES(?,?,?,?,?)"
  180966. );
  180967. }
  180968. while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){
  180969. int i;
  180970. for(i=0; i<5; i++){
  180971. sqlite3_bind_value(pInsert, i+1, sqlite3_column_value(pSql, i));
  180972. }
  180973. sqlite3_step(pInsert);
  180974. p->rc = sqlite3_reset(pInsert);
  180975. }
  180976. if( p->rc==SQLITE_OK ){
  180977. p->rc = sqlite3_exec(p->dbMain, "PRAGMA writable_schema=0",0,0,&p->zErrmsg);
  180978. }
  180979. rbuFinalize(p, pSql);
  180980. rbuFinalize(p, pInsert);
  180981. }
  180982. /*
  180983. ** Step the RBU object.
  180984. */
  180985. SQLITE_API int sqlite3rbu_step(sqlite3rbu *p){
  180986. if( p ){
  180987. switch( p->eStage ){
  180988. case RBU_STAGE_OAL: {
  180989. RbuObjIter *pIter = &p->objiter;
  180990. /* If this is an RBU vacuum operation and the state table was empty
  180991. ** when this handle was opened, create the target database schema. */
  180992. if( rbuIsVacuum(p) && p->nProgress==0 && p->rc==SQLITE_OK ){
  180993. rbuCreateTargetSchema(p);
  180994. rbuCopyPragma(p, "user_version");
  180995. rbuCopyPragma(p, "application_id");
  180996. }
  180997. while( p->rc==SQLITE_OK && pIter->zTbl ){
  180998. if( pIter->bCleanup ){
  180999. /* Clean up the rbu_tmp_xxx table for the previous table. It
  181000. ** cannot be dropped as there are currently active SQL statements.
  181001. ** But the contents can be deleted. */
  181002. if( rbuIsVacuum(p)==0 && pIter->abIndexed ){
  181003. rbuMPrintfExec(p, p->dbRbu,
  181004. "DELETE FROM %s.'rbu_tmp_%q'", p->zStateDb, pIter->zDataTbl
  181005. );
  181006. }
  181007. }else{
  181008. rbuObjIterPrepareAll(p, pIter, 0);
  181009. /* Advance to the next row to process. */
  181010. if( p->rc==SQLITE_OK ){
  181011. int rc = sqlite3_step(pIter->pSelect);
  181012. if( rc==SQLITE_ROW ){
  181013. p->nProgress++;
  181014. p->nStep++;
  181015. return rbuStep(p);
  181016. }
  181017. p->rc = sqlite3_reset(pIter->pSelect);
  181018. p->nStep = 0;
  181019. }
  181020. }
  181021. rbuObjIterNext(p, pIter);
  181022. }
  181023. if( p->rc==SQLITE_OK ){
  181024. assert( pIter->zTbl==0 );
  181025. rbuSaveState(p, RBU_STAGE_MOVE);
  181026. rbuIncrSchemaCookie(p);
  181027. if( p->rc==SQLITE_OK ){
  181028. p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg);
  181029. }
  181030. if( p->rc==SQLITE_OK ){
  181031. p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
  181032. }
  181033. p->eStage = RBU_STAGE_MOVE;
  181034. }
  181035. break;
  181036. }
  181037. case RBU_STAGE_MOVE: {
  181038. if( p->rc==SQLITE_OK ){
  181039. rbuMoveOalFile(p);
  181040. p->nProgress++;
  181041. }
  181042. break;
  181043. }
  181044. case RBU_STAGE_CKPT: {
  181045. if( p->rc==SQLITE_OK ){
  181046. if( p->nStep>=p->nFrame ){
  181047. sqlite3_file *pDb = p->pTargetFd->pReal;
  181048. /* Sync the db file */
  181049. p->rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
  181050. /* Update nBackfill */
  181051. if( p->rc==SQLITE_OK ){
  181052. void volatile *ptr;
  181053. p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, &ptr);
  181054. if( p->rc==SQLITE_OK ){
  181055. ((u32 volatile*)ptr)[24] = p->iMaxFrame;
  181056. }
  181057. }
  181058. if( p->rc==SQLITE_OK ){
  181059. p->eStage = RBU_STAGE_DONE;
  181060. p->rc = SQLITE_DONE;
  181061. }
  181062. }else{
  181063. /* At one point the following block copied a single frame from the
  181064. ** wal file to the database file. So that one call to sqlite3rbu_step()
  181065. ** checkpointed a single frame.
  181066. **
  181067. ** However, if the sector-size is larger than the page-size, and the
  181068. ** application calls sqlite3rbu_savestate() or close() immediately
  181069. ** after this step, then rbu_step() again, then a power failure occurs,
  181070. ** then the database page written here may be damaged. Work around
  181071. ** this by checkpointing frames until the next page in the aFrame[]
  181072. ** lies on a different disk sector to the current one. */
  181073. u32 iSector;
  181074. do{
  181075. RbuFrame *pFrame = &p->aFrame[p->nStep];
  181076. iSector = (pFrame->iDbPage-1) / p->nPagePerSector;
  181077. rbuCheckpointFrame(p, pFrame);
  181078. p->nStep++;
  181079. }while( p->nStep<p->nFrame
  181080. && iSector==((p->aFrame[p->nStep].iDbPage-1) / p->nPagePerSector)
  181081. && p->rc==SQLITE_OK
  181082. );
  181083. }
  181084. p->nProgress++;
  181085. }
  181086. break;
  181087. }
  181088. default:
  181089. break;
  181090. }
  181091. return p->rc;
  181092. }else{
  181093. return SQLITE_NOMEM;
  181094. }
  181095. }
  181096. /*
  181097. ** Compare strings z1 and z2, returning 0 if they are identical, or non-zero
  181098. ** otherwise. Either or both argument may be NULL. Two NULL values are
  181099. ** considered equal, and NULL is considered distinct from all other values.
  181100. */
  181101. static int rbuStrCompare(const char *z1, const char *z2){
  181102. if( z1==0 && z2==0 ) return 0;
  181103. if( z1==0 || z2==0 ) return 1;
  181104. return (sqlite3_stricmp(z1, z2)!=0);
  181105. }
  181106. /*
  181107. ** This function is called as part of sqlite3rbu_open() when initializing
  181108. ** an rbu handle in OAL stage. If the rbu update has not started (i.e.
  181109. ** the rbu_state table was empty) it is a no-op. Otherwise, it arranges
  181110. ** things so that the next call to sqlite3rbu_step() continues on from
  181111. ** where the previous rbu handle left off.
  181112. **
  181113. ** If an error occurs, an error code and error message are left in the
  181114. ** rbu handle passed as the first argument.
  181115. */
  181116. static void rbuSetupOal(sqlite3rbu *p, RbuState *pState){
  181117. assert( p->rc==SQLITE_OK );
  181118. if( pState->zTbl ){
  181119. RbuObjIter *pIter = &p->objiter;
  181120. int rc = SQLITE_OK;
  181121. while( rc==SQLITE_OK && pIter->zTbl && (pIter->bCleanup
  181122. || rbuStrCompare(pIter->zIdx, pState->zIdx)
  181123. || (pState->zDataTbl==0 && rbuStrCompare(pIter->zTbl, pState->zTbl))
  181124. || (pState->zDataTbl && rbuStrCompare(pIter->zDataTbl, pState->zDataTbl))
  181125. )){
  181126. rc = rbuObjIterNext(p, pIter);
  181127. }
  181128. if( rc==SQLITE_OK && !pIter->zTbl ){
  181129. rc = SQLITE_ERROR;
  181130. p->zErrmsg = sqlite3_mprintf("rbu_state mismatch error");
  181131. }
  181132. if( rc==SQLITE_OK ){
  181133. p->nStep = pState->nRow;
  181134. rc = rbuObjIterPrepareAll(p, &p->objiter, p->nStep);
  181135. }
  181136. p->rc = rc;
  181137. }
  181138. }
  181139. /*
  181140. ** If there is a "*-oal" file in the file-system corresponding to the
  181141. ** target database in the file-system, delete it. If an error occurs,
  181142. ** leave an error code and error message in the rbu handle.
  181143. */
  181144. static void rbuDeleteOalFile(sqlite3rbu *p){
  181145. char *zOal = rbuMPrintf(p, "%s-oal", p->zTarget);
  181146. if( zOal ){
  181147. sqlite3_vfs *pVfs = sqlite3_vfs_find(0);
  181148. assert( pVfs && p->rc==SQLITE_OK && p->zErrmsg==0 );
  181149. pVfs->xDelete(pVfs, zOal, 0);
  181150. sqlite3_free(zOal);
  181151. }
  181152. }
  181153. /*
  181154. ** Allocate a private rbu VFS for the rbu handle passed as the only
  181155. ** argument. This VFS will be used unless the call to sqlite3rbu_open()
  181156. ** specified a URI with a vfs=? option in place of a target database
  181157. ** file name.
  181158. */
  181159. static void rbuCreateVfs(sqlite3rbu *p){
  181160. int rnd;
  181161. char zRnd[64];
  181162. assert( p->rc==SQLITE_OK );
  181163. sqlite3_randomness(sizeof(int), (void*)&rnd);
  181164. sqlite3_snprintf(sizeof(zRnd), zRnd, "rbu_vfs_%d", rnd);
  181165. p->rc = sqlite3rbu_create_vfs(zRnd, 0);
  181166. if( p->rc==SQLITE_OK ){
  181167. sqlite3_vfs *pVfs = sqlite3_vfs_find(zRnd);
  181168. assert( pVfs );
  181169. p->zVfsName = pVfs->zName;
  181170. ((rbu_vfs*)pVfs)->pRbu = p;
  181171. }
  181172. }
  181173. /*
  181174. ** Destroy the private VFS created for the rbu handle passed as the only
  181175. ** argument by an earlier call to rbuCreateVfs().
  181176. */
  181177. static void rbuDeleteVfs(sqlite3rbu *p){
  181178. if( p->zVfsName ){
  181179. sqlite3rbu_destroy_vfs(p->zVfsName);
  181180. p->zVfsName = 0;
  181181. }
  181182. }
  181183. /*
  181184. ** This user-defined SQL function is invoked with a single argument - the
  181185. ** name of a table expected to appear in the target database. It returns
  181186. ** the number of auxilliary indexes on the table.
  181187. */
  181188. static void rbuIndexCntFunc(
  181189. sqlite3_context *pCtx,
  181190. int nVal,
  181191. sqlite3_value **apVal
  181192. ){
  181193. sqlite3rbu *p = (sqlite3rbu*)sqlite3_user_data(pCtx);
  181194. sqlite3_stmt *pStmt = 0;
  181195. char *zErrmsg = 0;
  181196. int rc;
  181197. assert( nVal==1 );
  181198. rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &zErrmsg,
  181199. sqlite3_mprintf("SELECT count(*) FROM sqlite_master "
  181200. "WHERE type='index' AND tbl_name = %Q", sqlite3_value_text(apVal[0]))
  181201. );
  181202. if( rc!=SQLITE_OK ){
  181203. sqlite3_result_error(pCtx, zErrmsg, -1);
  181204. }else{
  181205. int nIndex = 0;
  181206. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  181207. nIndex = sqlite3_column_int(pStmt, 0);
  181208. }
  181209. rc = sqlite3_finalize(pStmt);
  181210. if( rc==SQLITE_OK ){
  181211. sqlite3_result_int(pCtx, nIndex);
  181212. }else{
  181213. sqlite3_result_error(pCtx, sqlite3_errmsg(p->dbMain), -1);
  181214. }
  181215. }
  181216. sqlite3_free(zErrmsg);
  181217. }
  181218. /*
  181219. ** If the RBU database contains the rbu_count table, use it to initialize
  181220. ** the sqlite3rbu.nPhaseOneStep variable. The schema of the rbu_count table
  181221. ** is assumed to contain the same columns as:
  181222. **
  181223. ** CREATE TABLE rbu_count(tbl TEXT PRIMARY KEY, cnt INTEGER) WITHOUT ROWID;
  181224. **
  181225. ** There should be one row in the table for each data_xxx table in the
  181226. ** database. The 'tbl' column should contain the name of a data_xxx table,
  181227. ** and the cnt column the number of rows it contains.
  181228. **
  181229. ** sqlite3rbu.nPhaseOneStep is initialized to the sum of (1 + nIndex) * cnt
  181230. ** for all rows in the rbu_count table, where nIndex is the number of
  181231. ** indexes on the corresponding target database table.
  181232. */
  181233. static void rbuInitPhaseOneSteps(sqlite3rbu *p){
  181234. if( p->rc==SQLITE_OK ){
  181235. sqlite3_stmt *pStmt = 0;
  181236. int bExists = 0; /* True if rbu_count exists */
  181237. p->nPhaseOneStep = -1;
  181238. p->rc = sqlite3_create_function(p->dbRbu,
  181239. "rbu_index_cnt", 1, SQLITE_UTF8, (void*)p, rbuIndexCntFunc, 0, 0
  181240. );
  181241. /* Check for the rbu_count table. If it does not exist, or if an error
  181242. ** occurs, nPhaseOneStep will be left set to -1. */
  181243. if( p->rc==SQLITE_OK ){
  181244. p->rc = prepareAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
  181245. "SELECT 1 FROM sqlite_master WHERE tbl_name = 'rbu_count'"
  181246. );
  181247. }
  181248. if( p->rc==SQLITE_OK ){
  181249. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  181250. bExists = 1;
  181251. }
  181252. p->rc = sqlite3_finalize(pStmt);
  181253. }
  181254. if( p->rc==SQLITE_OK && bExists ){
  181255. p->rc = prepareAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
  181256. "SELECT sum(cnt * (1 + rbu_index_cnt(rbu_target_name(tbl))))"
  181257. "FROM rbu_count"
  181258. );
  181259. if( p->rc==SQLITE_OK ){
  181260. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  181261. p->nPhaseOneStep = sqlite3_column_int64(pStmt, 0);
  181262. }
  181263. p->rc = sqlite3_finalize(pStmt);
  181264. }
  181265. }
  181266. }
  181267. }
  181268. static sqlite3rbu *openRbuHandle(
  181269. const char *zTarget,
  181270. const char *zRbu,
  181271. const char *zState
  181272. ){
  181273. sqlite3rbu *p;
  181274. size_t nTarget = zTarget ? strlen(zTarget) : 0;
  181275. size_t nRbu = strlen(zRbu);
  181276. size_t nByte = sizeof(sqlite3rbu) + nTarget+1 + nRbu+1;
  181277. p = (sqlite3rbu*)sqlite3_malloc64(nByte);
  181278. if( p ){
  181279. RbuState *pState = 0;
  181280. /* Create the custom VFS. */
  181281. memset(p, 0, sizeof(sqlite3rbu));
  181282. rbuCreateVfs(p);
  181283. /* Open the target, RBU and state databases */
  181284. if( p->rc==SQLITE_OK ){
  181285. char *pCsr = (char*)&p[1];
  181286. int bRetry = 0;
  181287. if( zTarget ){
  181288. p->zTarget = pCsr;
  181289. memcpy(p->zTarget, zTarget, nTarget+1);
  181290. pCsr += nTarget+1;
  181291. }
  181292. p->zRbu = pCsr;
  181293. memcpy(p->zRbu, zRbu, nRbu+1);
  181294. pCsr += nRbu+1;
  181295. if( zState ){
  181296. p->zState = rbuMPrintf(p, "%s", zState);
  181297. }
  181298. /* If the first attempt to open the database file fails and the bRetry
  181299. ** flag it set, this means that the db was not opened because it seemed
  181300. ** to be a wal-mode db. But, this may have happened due to an earlier
  181301. ** RBU vacuum operation leaving an old wal file in the directory.
  181302. ** If this is the case, it will have been checkpointed and deleted
  181303. ** when the handle was closed and a second attempt to open the
  181304. ** database may succeed. */
  181305. rbuOpenDatabase(p, &bRetry);
  181306. if( bRetry ){
  181307. rbuOpenDatabase(p, 0);
  181308. }
  181309. }
  181310. if( p->rc==SQLITE_OK ){
  181311. pState = rbuLoadState(p);
  181312. assert( pState || p->rc!=SQLITE_OK );
  181313. if( p->rc==SQLITE_OK ){
  181314. if( pState->eStage==0 ){
  181315. rbuDeleteOalFile(p);
  181316. rbuInitPhaseOneSteps(p);
  181317. p->eStage = RBU_STAGE_OAL;
  181318. }else{
  181319. p->eStage = pState->eStage;
  181320. p->nPhaseOneStep = pState->nPhaseOneStep;
  181321. }
  181322. p->nProgress = pState->nProgress;
  181323. p->iOalSz = pState->iOalSz;
  181324. }
  181325. }
  181326. assert( p->rc!=SQLITE_OK || p->eStage!=0 );
  181327. if( p->rc==SQLITE_OK && p->pTargetFd->pWalFd ){
  181328. if( p->eStage==RBU_STAGE_OAL ){
  181329. p->rc = SQLITE_ERROR;
  181330. p->zErrmsg = sqlite3_mprintf("cannot update wal mode database");
  181331. }else if( p->eStage==RBU_STAGE_MOVE ){
  181332. p->eStage = RBU_STAGE_CKPT;
  181333. p->nStep = 0;
  181334. }
  181335. }
  181336. if( p->rc==SQLITE_OK
  181337. && (p->eStage==RBU_STAGE_OAL || p->eStage==RBU_STAGE_MOVE)
  181338. && pState->eStage!=0
  181339. ){
  181340. rbu_file *pFd = (rbuIsVacuum(p) ? p->pRbuFd : p->pTargetFd);
  181341. if( pFd->iCookie!=pState->iCookie ){
  181342. /* At this point (pTargetFd->iCookie) contains the value of the
  181343. ** change-counter cookie (the thing that gets incremented when a
  181344. ** transaction is committed in rollback mode) currently stored on
  181345. ** page 1 of the database file. */
  181346. p->rc = SQLITE_BUSY;
  181347. p->zErrmsg = sqlite3_mprintf("database modified during rbu %s",
  181348. (rbuIsVacuum(p) ? "vacuum" : "update")
  181349. );
  181350. }
  181351. }
  181352. if( p->rc==SQLITE_OK ){
  181353. if( p->eStage==RBU_STAGE_OAL ){
  181354. sqlite3 *db = p->dbMain;
  181355. p->rc = sqlite3_exec(p->dbRbu, "BEGIN", 0, 0, &p->zErrmsg);
  181356. /* Point the object iterator at the first object */
  181357. if( p->rc==SQLITE_OK ){
  181358. p->rc = rbuObjIterFirst(p, &p->objiter);
  181359. }
  181360. /* If the RBU database contains no data_xxx tables, declare the RBU
  181361. ** update finished. */
  181362. if( p->rc==SQLITE_OK && p->objiter.zTbl==0 ){
  181363. p->rc = SQLITE_DONE;
  181364. p->eStage = RBU_STAGE_DONE;
  181365. }else{
  181366. if( p->rc==SQLITE_OK && pState->eStage==0 && rbuIsVacuum(p) ){
  181367. rbuCopyPragma(p, "page_size");
  181368. rbuCopyPragma(p, "auto_vacuum");
  181369. }
  181370. /* Open transactions both databases. The *-oal file is opened or
  181371. ** created at this point. */
  181372. if( p->rc==SQLITE_OK ){
  181373. p->rc = sqlite3_exec(db, "BEGIN IMMEDIATE", 0, 0, &p->zErrmsg);
  181374. }
  181375. /* Check if the main database is a zipvfs db. If it is, set the upper
  181376. ** level pager to use "journal_mode=off". This prevents it from
  181377. ** generating a large journal using a temp file. */
  181378. if( p->rc==SQLITE_OK ){
  181379. int frc = sqlite3_file_control(db, "main", SQLITE_FCNTL_ZIPVFS, 0);
  181380. if( frc==SQLITE_OK ){
  181381. p->rc = sqlite3_exec(
  181382. db, "PRAGMA journal_mode=off",0,0,&p->zErrmsg);
  181383. }
  181384. }
  181385. if( p->rc==SQLITE_OK ){
  181386. rbuSetupOal(p, pState);
  181387. }
  181388. }
  181389. }else if( p->eStage==RBU_STAGE_MOVE ){
  181390. /* no-op */
  181391. }else if( p->eStage==RBU_STAGE_CKPT ){
  181392. rbuSetupCheckpoint(p, pState);
  181393. }else if( p->eStage==RBU_STAGE_DONE ){
  181394. p->rc = SQLITE_DONE;
  181395. }else{
  181396. p->rc = SQLITE_CORRUPT;
  181397. }
  181398. }
  181399. rbuFreeState(pState);
  181400. }
  181401. return p;
  181402. }
  181403. /*
  181404. ** Allocate and return an RBU handle with all fields zeroed except for the
  181405. ** error code, which is set to SQLITE_MISUSE.
  181406. */
  181407. static sqlite3rbu *rbuMisuseError(void){
  181408. sqlite3rbu *pRet;
  181409. pRet = sqlite3_malloc64(sizeof(sqlite3rbu));
  181410. if( pRet ){
  181411. memset(pRet, 0, sizeof(sqlite3rbu));
  181412. pRet->rc = SQLITE_MISUSE;
  181413. }
  181414. return pRet;
  181415. }
  181416. /*
  181417. ** Open and return a new RBU handle.
  181418. */
  181419. SQLITE_API sqlite3rbu *sqlite3rbu_open(
  181420. const char *zTarget,
  181421. const char *zRbu,
  181422. const char *zState
  181423. ){
  181424. if( zTarget==0 || zRbu==0 ){ return rbuMisuseError(); }
  181425. /* TODO: Check that zTarget and zRbu are non-NULL */
  181426. return openRbuHandle(zTarget, zRbu, zState);
  181427. }
  181428. /*
  181429. ** Open a handle to begin or resume an RBU VACUUM operation.
  181430. */
  181431. SQLITE_API sqlite3rbu *sqlite3rbu_vacuum(
  181432. const char *zTarget,
  181433. const char *zState
  181434. ){
  181435. if( zTarget==0 ){ return rbuMisuseError(); }
  181436. if( zState ){
  181437. int n = strlen(zState);
  181438. if( n>=7 && 0==memcmp("-vactmp", &zState[n-7], 7) ){
  181439. return rbuMisuseError();
  181440. }
  181441. }
  181442. /* TODO: Check that both arguments are non-NULL */
  181443. return openRbuHandle(0, zTarget, zState);
  181444. }
  181445. /*
  181446. ** Return the database handle used by pRbu.
  181447. */
  181448. SQLITE_API sqlite3 *sqlite3rbu_db(sqlite3rbu *pRbu, int bRbu){
  181449. sqlite3 *db = 0;
  181450. if( pRbu ){
  181451. db = (bRbu ? pRbu->dbRbu : pRbu->dbMain);
  181452. }
  181453. return db;
  181454. }
  181455. /*
  181456. ** If the error code currently stored in the RBU handle is SQLITE_CONSTRAINT,
  181457. ** then edit any error message string so as to remove all occurrences of
  181458. ** the pattern "rbu_imp_[0-9]*".
  181459. */
  181460. static void rbuEditErrmsg(sqlite3rbu *p){
  181461. if( p->rc==SQLITE_CONSTRAINT && p->zErrmsg ){
  181462. unsigned int i;
  181463. size_t nErrmsg = strlen(p->zErrmsg);
  181464. for(i=0; i<(nErrmsg-8); i++){
  181465. if( memcmp(&p->zErrmsg[i], "rbu_imp_", 8)==0 ){
  181466. int nDel = 8;
  181467. while( p->zErrmsg[i+nDel]>='0' && p->zErrmsg[i+nDel]<='9' ) nDel++;
  181468. memmove(&p->zErrmsg[i], &p->zErrmsg[i+nDel], nErrmsg + 1 - i - nDel);
  181469. nErrmsg -= nDel;
  181470. }
  181471. }
  181472. }
  181473. }
  181474. /*
  181475. ** Close the RBU handle.
  181476. */
  181477. SQLITE_API int sqlite3rbu_close(sqlite3rbu *p, char **pzErrmsg){
  181478. int rc;
  181479. if( p ){
  181480. /* Commit the transaction to the *-oal file. */
  181481. if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){
  181482. p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg);
  181483. }
  181484. /* Sync the db file if currently doing an incremental checkpoint */
  181485. if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_CKPT ){
  181486. sqlite3_file *pDb = p->pTargetFd->pReal;
  181487. p->rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
  181488. }
  181489. rbuSaveState(p, p->eStage);
  181490. if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){
  181491. p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
  181492. }
  181493. /* Close any open statement handles. */
  181494. rbuObjIterFinalize(&p->objiter);
  181495. /* If this is an RBU vacuum handle and the vacuum has either finished
  181496. ** successfully or encountered an error, delete the contents of the
  181497. ** state table. This causes the next call to sqlite3rbu_vacuum()
  181498. ** specifying the current target and state databases to start a new
  181499. ** vacuum from scratch. */
  181500. if( rbuIsVacuum(p) && p->rc!=SQLITE_OK && p->dbRbu ){
  181501. int rc2 = sqlite3_exec(p->dbRbu, "DELETE FROM stat.rbu_state", 0, 0, 0);
  181502. if( p->rc==SQLITE_DONE && rc2!=SQLITE_OK ) p->rc = rc2;
  181503. }
  181504. /* Close the open database handle and VFS object. */
  181505. sqlite3_close(p->dbRbu);
  181506. sqlite3_close(p->dbMain);
  181507. assert( p->szTemp==0 );
  181508. rbuDeleteVfs(p);
  181509. sqlite3_free(p->aBuf);
  181510. sqlite3_free(p->aFrame);
  181511. rbuEditErrmsg(p);
  181512. rc = p->rc;
  181513. if( pzErrmsg ){
  181514. *pzErrmsg = p->zErrmsg;
  181515. }else{
  181516. sqlite3_free(p->zErrmsg);
  181517. }
  181518. sqlite3_free(p->zState);
  181519. sqlite3_free(p);
  181520. }else{
  181521. rc = SQLITE_NOMEM;
  181522. *pzErrmsg = 0;
  181523. }
  181524. return rc;
  181525. }
  181526. /*
  181527. ** Return the total number of key-value operations (inserts, deletes or
  181528. ** updates) that have been performed on the target database since the
  181529. ** current RBU update was started.
  181530. */
  181531. SQLITE_API sqlite3_int64 sqlite3rbu_progress(sqlite3rbu *pRbu){
  181532. return pRbu->nProgress;
  181533. }
  181534. /*
  181535. ** Return permyriadage progress indications for the two main stages of
  181536. ** an RBU update.
  181537. */
  181538. SQLITE_API void sqlite3rbu_bp_progress(sqlite3rbu *p, int *pnOne, int *pnTwo){
  181539. const int MAX_PROGRESS = 10000;
  181540. switch( p->eStage ){
  181541. case RBU_STAGE_OAL:
  181542. if( p->nPhaseOneStep>0 ){
  181543. *pnOne = (int)(MAX_PROGRESS * (i64)p->nProgress/(i64)p->nPhaseOneStep);
  181544. }else{
  181545. *pnOne = -1;
  181546. }
  181547. *pnTwo = 0;
  181548. break;
  181549. case RBU_STAGE_MOVE:
  181550. *pnOne = MAX_PROGRESS;
  181551. *pnTwo = 0;
  181552. break;
  181553. case RBU_STAGE_CKPT:
  181554. *pnOne = MAX_PROGRESS;
  181555. *pnTwo = (int)(MAX_PROGRESS * (i64)p->nStep / (i64)p->nFrame);
  181556. break;
  181557. case RBU_STAGE_DONE:
  181558. *pnOne = MAX_PROGRESS;
  181559. *pnTwo = MAX_PROGRESS;
  181560. break;
  181561. default:
  181562. assert( 0 );
  181563. }
  181564. }
  181565. /*
  181566. ** Return the current state of the RBU vacuum or update operation.
  181567. */
  181568. SQLITE_API int sqlite3rbu_state(sqlite3rbu *p){
  181569. int aRes[] = {
  181570. 0, SQLITE_RBU_STATE_OAL, SQLITE_RBU_STATE_MOVE,
  181571. 0, SQLITE_RBU_STATE_CHECKPOINT, SQLITE_RBU_STATE_DONE
  181572. };
  181573. assert( RBU_STAGE_OAL==1 );
  181574. assert( RBU_STAGE_MOVE==2 );
  181575. assert( RBU_STAGE_CKPT==4 );
  181576. assert( RBU_STAGE_DONE==5 );
  181577. assert( aRes[RBU_STAGE_OAL]==SQLITE_RBU_STATE_OAL );
  181578. assert( aRes[RBU_STAGE_MOVE]==SQLITE_RBU_STATE_MOVE );
  181579. assert( aRes[RBU_STAGE_CKPT]==SQLITE_RBU_STATE_CHECKPOINT );
  181580. assert( aRes[RBU_STAGE_DONE]==SQLITE_RBU_STATE_DONE );
  181581. if( p->rc!=SQLITE_OK && p->rc!=SQLITE_DONE ){
  181582. return SQLITE_RBU_STATE_ERROR;
  181583. }else{
  181584. assert( p->rc!=SQLITE_DONE || p->eStage==RBU_STAGE_DONE );
  181585. assert( p->eStage==RBU_STAGE_OAL
  181586. || p->eStage==RBU_STAGE_MOVE
  181587. || p->eStage==RBU_STAGE_CKPT
  181588. || p->eStage==RBU_STAGE_DONE
  181589. );
  181590. return aRes[p->eStage];
  181591. }
  181592. }
  181593. SQLITE_API int sqlite3rbu_savestate(sqlite3rbu *p){
  181594. int rc = p->rc;
  181595. if( rc==SQLITE_DONE ) return SQLITE_OK;
  181596. assert( p->eStage>=RBU_STAGE_OAL && p->eStage<=RBU_STAGE_DONE );
  181597. if( p->eStage==RBU_STAGE_OAL ){
  181598. assert( rc!=SQLITE_DONE );
  181599. if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, 0);
  181600. }
  181601. /* Sync the db file */
  181602. if( rc==SQLITE_OK && p->eStage==RBU_STAGE_CKPT ){
  181603. sqlite3_file *pDb = p->pTargetFd->pReal;
  181604. rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
  181605. }
  181606. p->rc = rc;
  181607. rbuSaveState(p, p->eStage);
  181608. rc = p->rc;
  181609. if( p->eStage==RBU_STAGE_OAL ){
  181610. assert( rc!=SQLITE_DONE );
  181611. if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0);
  181612. if( rc==SQLITE_OK ){
  181613. const char *zBegin = rbuIsVacuum(p) ? "BEGIN" : "BEGIN IMMEDIATE";
  181614. rc = sqlite3_exec(p->dbRbu, zBegin, 0, 0, 0);
  181615. }
  181616. if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "BEGIN IMMEDIATE", 0, 0,0);
  181617. }
  181618. p->rc = rc;
  181619. return rc;
  181620. }
  181621. /**************************************************************************
  181622. ** Beginning of RBU VFS shim methods. The VFS shim modifies the behaviour
  181623. ** of a standard VFS in the following ways:
  181624. **
  181625. ** 1. Whenever the first page of a main database file is read or
  181626. ** written, the value of the change-counter cookie is stored in
  181627. ** rbu_file.iCookie. Similarly, the value of the "write-version"
  181628. ** database header field is stored in rbu_file.iWriteVer. This ensures
  181629. ** that the values are always trustworthy within an open transaction.
  181630. **
  181631. ** 2. Whenever an SQLITE_OPEN_WAL file is opened, the (rbu_file.pWalFd)
  181632. ** member variable of the associated database file descriptor is set
  181633. ** to point to the new file. A mutex protected linked list of all main
  181634. ** db fds opened using a particular RBU VFS is maintained at
  181635. ** rbu_vfs.pMain to facilitate this.
  181636. **
  181637. ** 3. Using a new file-control "SQLITE_FCNTL_RBU", a main db rbu_file
  181638. ** object can be marked as the target database of an RBU update. This
  181639. ** turns on the following extra special behaviour:
  181640. **
  181641. ** 3a. If xAccess() is called to check if there exists a *-wal file
  181642. ** associated with an RBU target database currently in RBU_STAGE_OAL
  181643. ** stage (preparing the *-oal file), the following special handling
  181644. ** applies:
  181645. **
  181646. ** * if the *-wal file does exist, return SQLITE_CANTOPEN. An RBU
  181647. ** target database may not be in wal mode already.
  181648. **
  181649. ** * if the *-wal file does not exist, set the output parameter to
  181650. ** non-zero (to tell SQLite that it does exist) anyway.
  181651. **
  181652. ** Then, when xOpen() is called to open the *-wal file associated with
  181653. ** the RBU target in RBU_STAGE_OAL stage, instead of opening the *-wal
  181654. ** file, the rbu vfs opens the corresponding *-oal file instead.
  181655. **
  181656. ** 3b. The *-shm pages returned by xShmMap() for a target db file in
  181657. ** RBU_STAGE_OAL mode are actually stored in heap memory. This is to
  181658. ** avoid creating a *-shm file on disk. Additionally, xShmLock() calls
  181659. ** are no-ops on target database files in RBU_STAGE_OAL mode. This is
  181660. ** because assert() statements in some VFS implementations fail if
  181661. ** xShmLock() is called before xShmMap().
  181662. **
  181663. ** 3c. If an EXCLUSIVE lock is attempted on a target database file in any
  181664. ** mode except RBU_STAGE_DONE (all work completed and checkpointed), it
  181665. ** fails with an SQLITE_BUSY error. This is to stop RBU connections
  181666. ** from automatically checkpointing a *-wal (or *-oal) file from within
  181667. ** sqlite3_close().
  181668. **
  181669. ** 3d. In RBU_STAGE_CAPTURE mode, all xRead() calls on the wal file, and
  181670. ** all xWrite() calls on the target database file perform no IO.
  181671. ** Instead the frame and page numbers that would be read and written
  181672. ** are recorded. Additionally, successful attempts to obtain exclusive
  181673. ** xShmLock() WRITER, CHECKPOINTER and READ0 locks on the target
  181674. ** database file are recorded. xShmLock() calls to unlock the same
  181675. ** locks are no-ops (so that once obtained, these locks are never
  181676. ** relinquished). Finally, calls to xSync() on the target database
  181677. ** file fail with SQLITE_INTERNAL errors.
  181678. */
  181679. static void rbuUnlockShm(rbu_file *p){
  181680. assert( p->openFlags & SQLITE_OPEN_MAIN_DB );
  181681. if( p->pRbu ){
  181682. int (*xShmLock)(sqlite3_file*,int,int,int) = p->pReal->pMethods->xShmLock;
  181683. int i;
  181684. for(i=0; i<SQLITE_SHM_NLOCK;i++){
  181685. if( (1<<i) & p->pRbu->mLock ){
  181686. xShmLock(p->pReal, i, 1, SQLITE_SHM_UNLOCK|SQLITE_SHM_EXCLUSIVE);
  181687. }
  181688. }
  181689. p->pRbu->mLock = 0;
  181690. }
  181691. }
  181692. /*
  181693. */
  181694. static int rbuUpdateTempSize(rbu_file *pFd, sqlite3_int64 nNew){
  181695. sqlite3rbu *pRbu = pFd->pRbu;
  181696. i64 nDiff = nNew - pFd->sz;
  181697. pRbu->szTemp += nDiff;
  181698. pFd->sz = nNew;
  181699. assert( pRbu->szTemp>=0 );
  181700. if( pRbu->szTempLimit && pRbu->szTemp>pRbu->szTempLimit ) return SQLITE_FULL;
  181701. return SQLITE_OK;
  181702. }
  181703. /*
  181704. ** Add an item to the main-db lists, if it is not already present.
  181705. **
  181706. ** There are two main-db lists. One for all file descriptors, and one
  181707. ** for all file descriptors with rbu_file.pDb!=0. If the argument has
  181708. ** rbu_file.pDb!=0, then it is assumed to already be present on the
  181709. ** main list and is only added to the pDb!=0 list.
  181710. */
  181711. static void rbuMainlistAdd(rbu_file *p){
  181712. rbu_vfs *pRbuVfs = p->pRbuVfs;
  181713. rbu_file *pIter;
  181714. assert( (p->openFlags & SQLITE_OPEN_MAIN_DB) );
  181715. sqlite3_mutex_enter(pRbuVfs->mutex);
  181716. if( p->pRbu==0 ){
  181717. for(pIter=pRbuVfs->pMain; pIter; pIter=pIter->pMainNext);
  181718. p->pMainNext = pRbuVfs->pMain;
  181719. pRbuVfs->pMain = p;
  181720. }else{
  181721. for(pIter=pRbuVfs->pMainRbu; pIter && pIter!=p; pIter=pIter->pMainRbuNext){}
  181722. if( pIter==0 ){
  181723. p->pMainRbuNext = pRbuVfs->pMainRbu;
  181724. pRbuVfs->pMainRbu = p;
  181725. }
  181726. }
  181727. sqlite3_mutex_leave(pRbuVfs->mutex);
  181728. }
  181729. /*
  181730. ** Remove an item from the main-db lists.
  181731. */
  181732. static void rbuMainlistRemove(rbu_file *p){
  181733. rbu_file **pp;
  181734. sqlite3_mutex_enter(p->pRbuVfs->mutex);
  181735. for(pp=&p->pRbuVfs->pMain; *pp && *pp!=p; pp=&((*pp)->pMainNext)){}
  181736. if( *pp ) *pp = p->pMainNext;
  181737. p->pMainNext = 0;
  181738. for(pp=&p->pRbuVfs->pMainRbu; *pp && *pp!=p; pp=&((*pp)->pMainRbuNext)){}
  181739. if( *pp ) *pp = p->pMainRbuNext;
  181740. p->pMainRbuNext = 0;
  181741. sqlite3_mutex_leave(p->pRbuVfs->mutex);
  181742. }
  181743. /*
  181744. ** Given that zWal points to a buffer containing a wal file name passed to
  181745. ** either the xOpen() or xAccess() VFS method, search the main-db list for
  181746. ** a file-handle opened by the same database connection on the corresponding
  181747. ** database file.
  181748. **
  181749. ** If parameter bRbu is true, only search for file-descriptors with
  181750. ** rbu_file.pDb!=0.
  181751. */
  181752. static rbu_file *rbuFindMaindb(rbu_vfs *pRbuVfs, const char *zWal, int bRbu){
  181753. rbu_file *pDb;
  181754. sqlite3_mutex_enter(pRbuVfs->mutex);
  181755. if( bRbu ){
  181756. for(pDb=pRbuVfs->pMainRbu; pDb && pDb->zWal!=zWal; pDb=pDb->pMainRbuNext){}
  181757. }else{
  181758. for(pDb=pRbuVfs->pMain; pDb && pDb->zWal!=zWal; pDb=pDb->pMainNext){}
  181759. }
  181760. sqlite3_mutex_leave(pRbuVfs->mutex);
  181761. return pDb;
  181762. }
  181763. /*
  181764. ** Close an rbu file.
  181765. */
  181766. static int rbuVfsClose(sqlite3_file *pFile){
  181767. rbu_file *p = (rbu_file*)pFile;
  181768. int rc;
  181769. int i;
  181770. /* Free the contents of the apShm[] array. And the array itself. */
  181771. for(i=0; i<p->nShm; i++){
  181772. sqlite3_free(p->apShm[i]);
  181773. }
  181774. sqlite3_free(p->apShm);
  181775. p->apShm = 0;
  181776. sqlite3_free(p->zDel);
  181777. if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
  181778. rbuMainlistRemove(p);
  181779. rbuUnlockShm(p);
  181780. p->pReal->pMethods->xShmUnmap(p->pReal, 0);
  181781. }
  181782. else if( (p->openFlags & SQLITE_OPEN_DELETEONCLOSE) && p->pRbu ){
  181783. rbuUpdateTempSize(p, 0);
  181784. }
  181785. assert( p->pMainNext==0 && p->pRbuVfs->pMain!=p );
  181786. /* Close the underlying file handle */
  181787. rc = p->pReal->pMethods->xClose(p->pReal);
  181788. return rc;
  181789. }
  181790. /*
  181791. ** Read and return an unsigned 32-bit big-endian integer from the buffer
  181792. ** passed as the only argument.
  181793. */
  181794. static u32 rbuGetU32(u8 *aBuf){
  181795. return ((u32)aBuf[0] << 24)
  181796. + ((u32)aBuf[1] << 16)
  181797. + ((u32)aBuf[2] << 8)
  181798. + ((u32)aBuf[3]);
  181799. }
  181800. /*
  181801. ** Write an unsigned 32-bit value in big-endian format to the supplied
  181802. ** buffer.
  181803. */
  181804. static void rbuPutU32(u8 *aBuf, u32 iVal){
  181805. aBuf[0] = (iVal >> 24) & 0xFF;
  181806. aBuf[1] = (iVal >> 16) & 0xFF;
  181807. aBuf[2] = (iVal >> 8) & 0xFF;
  181808. aBuf[3] = (iVal >> 0) & 0xFF;
  181809. }
  181810. static void rbuPutU16(u8 *aBuf, u16 iVal){
  181811. aBuf[0] = (iVal >> 8) & 0xFF;
  181812. aBuf[1] = (iVal >> 0) & 0xFF;
  181813. }
  181814. /*
  181815. ** Read data from an rbuVfs-file.
  181816. */
  181817. static int rbuVfsRead(
  181818. sqlite3_file *pFile,
  181819. void *zBuf,
  181820. int iAmt,
  181821. sqlite_int64 iOfst
  181822. ){
  181823. rbu_file *p = (rbu_file*)pFile;
  181824. sqlite3rbu *pRbu = p->pRbu;
  181825. int rc;
  181826. if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
  181827. assert( p->openFlags & SQLITE_OPEN_WAL );
  181828. rc = rbuCaptureWalRead(p->pRbu, iOfst, iAmt);
  181829. }else{
  181830. if( pRbu && pRbu->eStage==RBU_STAGE_OAL
  181831. && (p->openFlags & SQLITE_OPEN_WAL)
  181832. && iOfst>=pRbu->iOalSz
  181833. ){
  181834. rc = SQLITE_OK;
  181835. memset(zBuf, 0, iAmt);
  181836. }else{
  181837. rc = p->pReal->pMethods->xRead(p->pReal, zBuf, iAmt, iOfst);
  181838. #if 1
  181839. /* If this is being called to read the first page of the target
  181840. ** database as part of an rbu vacuum operation, synthesize the
  181841. ** contents of the first page if it does not yet exist. Otherwise,
  181842. ** SQLite will not check for a *-wal file. */
  181843. if( pRbu && rbuIsVacuum(pRbu)
  181844. && rc==SQLITE_IOERR_SHORT_READ && iOfst==0
  181845. && (p->openFlags & SQLITE_OPEN_MAIN_DB)
  181846. && pRbu->rc==SQLITE_OK
  181847. ){
  181848. sqlite3_file *pFd = (sqlite3_file*)pRbu->pRbuFd;
  181849. rc = pFd->pMethods->xRead(pFd, zBuf, iAmt, iOfst);
  181850. if( rc==SQLITE_OK ){
  181851. u8 *aBuf = (u8*)zBuf;
  181852. u32 iRoot = rbuGetU32(&aBuf[52]) ? 1 : 0;
  181853. rbuPutU32(&aBuf[52], iRoot); /* largest root page number */
  181854. rbuPutU32(&aBuf[36], 0); /* number of free pages */
  181855. rbuPutU32(&aBuf[32], 0); /* first page on free list trunk */
  181856. rbuPutU32(&aBuf[28], 1); /* size of db file in pages */
  181857. rbuPutU32(&aBuf[24], pRbu->pRbuFd->iCookie+1); /* Change counter */
  181858. if( iAmt>100 ){
  181859. memset(&aBuf[100], 0, iAmt-100);
  181860. rbuPutU16(&aBuf[105], iAmt & 0xFFFF);
  181861. aBuf[100] = 0x0D;
  181862. }
  181863. }
  181864. }
  181865. #endif
  181866. }
  181867. if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
  181868. /* These look like magic numbers. But they are stable, as they are part
  181869. ** of the definition of the SQLite file format, which may not change. */
  181870. u8 *pBuf = (u8*)zBuf;
  181871. p->iCookie = rbuGetU32(&pBuf[24]);
  181872. p->iWriteVer = pBuf[19];
  181873. }
  181874. }
  181875. return rc;
  181876. }
  181877. /*
  181878. ** Write data to an rbuVfs-file.
  181879. */
  181880. static int rbuVfsWrite(
  181881. sqlite3_file *pFile,
  181882. const void *zBuf,
  181883. int iAmt,
  181884. sqlite_int64 iOfst
  181885. ){
  181886. rbu_file *p = (rbu_file*)pFile;
  181887. sqlite3rbu *pRbu = p->pRbu;
  181888. int rc;
  181889. if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
  181890. assert( p->openFlags & SQLITE_OPEN_MAIN_DB );
  181891. rc = rbuCaptureDbWrite(p->pRbu, iOfst);
  181892. }else{
  181893. if( pRbu ){
  181894. if( pRbu->eStage==RBU_STAGE_OAL
  181895. && (p->openFlags & SQLITE_OPEN_WAL)
  181896. && iOfst>=pRbu->iOalSz
  181897. ){
  181898. pRbu->iOalSz = iAmt + iOfst;
  181899. }else if( p->openFlags & SQLITE_OPEN_DELETEONCLOSE ){
  181900. i64 szNew = iAmt+iOfst;
  181901. if( szNew>p->sz ){
  181902. rc = rbuUpdateTempSize(p, szNew);
  181903. if( rc!=SQLITE_OK ) return rc;
  181904. }
  181905. }
  181906. }
  181907. rc = p->pReal->pMethods->xWrite(p->pReal, zBuf, iAmt, iOfst);
  181908. if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
  181909. /* These look like magic numbers. But they are stable, as they are part
  181910. ** of the definition of the SQLite file format, which may not change. */
  181911. u8 *pBuf = (u8*)zBuf;
  181912. p->iCookie = rbuGetU32(&pBuf[24]);
  181913. p->iWriteVer = pBuf[19];
  181914. }
  181915. }
  181916. return rc;
  181917. }
  181918. /*
  181919. ** Truncate an rbuVfs-file.
  181920. */
  181921. static int rbuVfsTruncate(sqlite3_file *pFile, sqlite_int64 size){
  181922. rbu_file *p = (rbu_file*)pFile;
  181923. if( (p->openFlags & SQLITE_OPEN_DELETEONCLOSE) && p->pRbu ){
  181924. int rc = rbuUpdateTempSize(p, size);
  181925. if( rc!=SQLITE_OK ) return rc;
  181926. }
  181927. return p->pReal->pMethods->xTruncate(p->pReal, size);
  181928. }
  181929. /*
  181930. ** Sync an rbuVfs-file.
  181931. */
  181932. static int rbuVfsSync(sqlite3_file *pFile, int flags){
  181933. rbu_file *p = (rbu_file *)pFile;
  181934. if( p->pRbu && p->pRbu->eStage==RBU_STAGE_CAPTURE ){
  181935. if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
  181936. return SQLITE_INTERNAL;
  181937. }
  181938. return SQLITE_OK;
  181939. }
  181940. return p->pReal->pMethods->xSync(p->pReal, flags);
  181941. }
  181942. /*
  181943. ** Return the current file-size of an rbuVfs-file.
  181944. */
  181945. static int rbuVfsFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
  181946. rbu_file *p = (rbu_file *)pFile;
  181947. int rc;
  181948. rc = p->pReal->pMethods->xFileSize(p->pReal, pSize);
  181949. /* If this is an RBU vacuum operation and this is the target database,
  181950. ** pretend that it has at least one page. Otherwise, SQLite will not
  181951. ** check for the existance of a *-wal file. rbuVfsRead() contains
  181952. ** similar logic. */
  181953. if( rc==SQLITE_OK && *pSize==0
  181954. && p->pRbu && rbuIsVacuum(p->pRbu)
  181955. && (p->openFlags & SQLITE_OPEN_MAIN_DB)
  181956. ){
  181957. *pSize = 1024;
  181958. }
  181959. return rc;
  181960. }
  181961. /*
  181962. ** Lock an rbuVfs-file.
  181963. */
  181964. static int rbuVfsLock(sqlite3_file *pFile, int eLock){
  181965. rbu_file *p = (rbu_file*)pFile;
  181966. sqlite3rbu *pRbu = p->pRbu;
  181967. int rc = SQLITE_OK;
  181968. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
  181969. if( eLock==SQLITE_LOCK_EXCLUSIVE
  181970. && (p->bNolock || (pRbu && pRbu->eStage!=RBU_STAGE_DONE))
  181971. ){
  181972. /* Do not allow EXCLUSIVE locks. Preventing SQLite from taking this
  181973. ** prevents it from checkpointing the database from sqlite3_close(). */
  181974. rc = SQLITE_BUSY;
  181975. }else{
  181976. rc = p->pReal->pMethods->xLock(p->pReal, eLock);
  181977. }
  181978. return rc;
  181979. }
  181980. /*
  181981. ** Unlock an rbuVfs-file.
  181982. */
  181983. static int rbuVfsUnlock(sqlite3_file *pFile, int eLock){
  181984. rbu_file *p = (rbu_file *)pFile;
  181985. return p->pReal->pMethods->xUnlock(p->pReal, eLock);
  181986. }
  181987. /*
  181988. ** Check if another file-handle holds a RESERVED lock on an rbuVfs-file.
  181989. */
  181990. static int rbuVfsCheckReservedLock(sqlite3_file *pFile, int *pResOut){
  181991. rbu_file *p = (rbu_file *)pFile;
  181992. return p->pReal->pMethods->xCheckReservedLock(p->pReal, pResOut);
  181993. }
  181994. /*
  181995. ** File control method. For custom operations on an rbuVfs-file.
  181996. */
  181997. static int rbuVfsFileControl(sqlite3_file *pFile, int op, void *pArg){
  181998. rbu_file *p = (rbu_file *)pFile;
  181999. int (*xControl)(sqlite3_file*,int,void*) = p->pReal->pMethods->xFileControl;
  182000. int rc;
  182001. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB)
  182002. || p->openFlags & (SQLITE_OPEN_TRANSIENT_DB|SQLITE_OPEN_TEMP_JOURNAL)
  182003. );
  182004. if( op==SQLITE_FCNTL_RBU ){
  182005. sqlite3rbu *pRbu = (sqlite3rbu*)pArg;
  182006. /* First try to find another RBU vfs lower down in the vfs stack. If
  182007. ** one is found, this vfs will operate in pass-through mode. The lower
  182008. ** level vfs will do the special RBU handling. */
  182009. rc = xControl(p->pReal, op, pArg);
  182010. if( rc==SQLITE_NOTFOUND ){
  182011. /* Now search for a zipvfs instance lower down in the VFS stack. If
  182012. ** one is found, this is an error. */
  182013. void *dummy = 0;
  182014. rc = xControl(p->pReal, SQLITE_FCNTL_ZIPVFS, &dummy);
  182015. if( rc==SQLITE_OK ){
  182016. rc = SQLITE_ERROR;
  182017. pRbu->zErrmsg = sqlite3_mprintf("rbu/zipvfs setup error");
  182018. }else if( rc==SQLITE_NOTFOUND ){
  182019. pRbu->pTargetFd = p;
  182020. p->pRbu = pRbu;
  182021. rbuMainlistAdd(p);
  182022. if( p->pWalFd ) p->pWalFd->pRbu = pRbu;
  182023. rc = SQLITE_OK;
  182024. }
  182025. }
  182026. return rc;
  182027. }
  182028. else if( op==SQLITE_FCNTL_RBUCNT ){
  182029. sqlite3rbu *pRbu = (sqlite3rbu*)pArg;
  182030. pRbu->nRbu++;
  182031. pRbu->pRbuFd = p;
  182032. p->bNolock = 1;
  182033. }
  182034. rc = xControl(p->pReal, op, pArg);
  182035. if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){
  182036. rbu_vfs *pRbuVfs = p->pRbuVfs;
  182037. char *zIn = *(char**)pArg;
  182038. char *zOut = sqlite3_mprintf("rbu(%s)/%z", pRbuVfs->base.zName, zIn);
  182039. *(char**)pArg = zOut;
  182040. if( zOut==0 ) rc = SQLITE_NOMEM;
  182041. }
  182042. return rc;
  182043. }
  182044. /*
  182045. ** Return the sector-size in bytes for an rbuVfs-file.
  182046. */
  182047. static int rbuVfsSectorSize(sqlite3_file *pFile){
  182048. rbu_file *p = (rbu_file *)pFile;
  182049. return p->pReal->pMethods->xSectorSize(p->pReal);
  182050. }
  182051. /*
  182052. ** Return the device characteristic flags supported by an rbuVfs-file.
  182053. */
  182054. static int rbuVfsDeviceCharacteristics(sqlite3_file *pFile){
  182055. rbu_file *p = (rbu_file *)pFile;
  182056. return p->pReal->pMethods->xDeviceCharacteristics(p->pReal);
  182057. }
  182058. /*
  182059. ** Take or release a shared-memory lock.
  182060. */
  182061. static int rbuVfsShmLock(sqlite3_file *pFile, int ofst, int n, int flags){
  182062. rbu_file *p = (rbu_file*)pFile;
  182063. sqlite3rbu *pRbu = p->pRbu;
  182064. int rc = SQLITE_OK;
  182065. #ifdef SQLITE_AMALGAMATION
  182066. assert( WAL_CKPT_LOCK==1 );
  182067. #endif
  182068. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
  182069. if( pRbu && (pRbu->eStage==RBU_STAGE_OAL || pRbu->eStage==RBU_STAGE_MOVE) ){
  182070. /* Magic number 1 is the WAL_CKPT_LOCK lock. Preventing SQLite from
  182071. ** taking this lock also prevents any checkpoints from occurring.
  182072. ** todo: really, it's not clear why this might occur, as
  182073. ** wal_autocheckpoint ought to be turned off. */
  182074. if( ofst==WAL_LOCK_CKPT && n==1 ) rc = SQLITE_BUSY;
  182075. }else{
  182076. int bCapture = 0;
  182077. if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
  182078. bCapture = 1;
  182079. }
  182080. if( bCapture==0 || 0==(flags & SQLITE_SHM_UNLOCK) ){
  182081. rc = p->pReal->pMethods->xShmLock(p->pReal, ofst, n, flags);
  182082. if( bCapture && rc==SQLITE_OK ){
  182083. pRbu->mLock |= (1 << ofst);
  182084. }
  182085. }
  182086. }
  182087. return rc;
  182088. }
  182089. /*
  182090. ** Obtain a pointer to a mapping of a single 32KiB page of the *-shm file.
  182091. */
  182092. static int rbuVfsShmMap(
  182093. sqlite3_file *pFile,
  182094. int iRegion,
  182095. int szRegion,
  182096. int isWrite,
  182097. void volatile **pp
  182098. ){
  182099. rbu_file *p = (rbu_file*)pFile;
  182100. int rc = SQLITE_OK;
  182101. int eStage = (p->pRbu ? p->pRbu->eStage : 0);
  182102. /* If not in RBU_STAGE_OAL, allow this call to pass through. Or, if this
  182103. ** rbu is in the RBU_STAGE_OAL state, use heap memory for *-shm space
  182104. ** instead of a file on disk. */
  182105. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
  182106. if( eStage==RBU_STAGE_OAL ){
  182107. sqlite3_int64 nByte = (iRegion+1) * sizeof(char*);
  182108. char **apNew = (char**)sqlite3_realloc64(p->apShm, nByte);
  182109. /* This is an RBU connection that uses its own heap memory for the
  182110. ** pages of the *-shm file. Since no other process can have run
  182111. ** recovery, the connection must request *-shm pages in order
  182112. ** from start to finish. */
  182113. assert( iRegion==p->nShm );
  182114. if( apNew==0 ){
  182115. rc = SQLITE_NOMEM;
  182116. }else{
  182117. memset(&apNew[p->nShm], 0, sizeof(char*) * (1 + iRegion - p->nShm));
  182118. p->apShm = apNew;
  182119. p->nShm = iRegion+1;
  182120. }
  182121. if( rc==SQLITE_OK ){
  182122. char *pNew = (char*)sqlite3_malloc64(szRegion);
  182123. if( pNew==0 ){
  182124. rc = SQLITE_NOMEM;
  182125. }else{
  182126. memset(pNew, 0, szRegion);
  182127. p->apShm[iRegion] = pNew;
  182128. }
  182129. }
  182130. if( rc==SQLITE_OK ){
  182131. *pp = p->apShm[iRegion];
  182132. }else{
  182133. *pp = 0;
  182134. }
  182135. }else{
  182136. assert( p->apShm==0 );
  182137. rc = p->pReal->pMethods->xShmMap(p->pReal, iRegion, szRegion, isWrite, pp);
  182138. }
  182139. return rc;
  182140. }
  182141. /*
  182142. ** Memory barrier.
  182143. */
  182144. static void rbuVfsShmBarrier(sqlite3_file *pFile){
  182145. rbu_file *p = (rbu_file *)pFile;
  182146. p->pReal->pMethods->xShmBarrier(p->pReal);
  182147. }
  182148. /*
  182149. ** The xShmUnmap method.
  182150. */
  182151. static int rbuVfsShmUnmap(sqlite3_file *pFile, int delFlag){
  182152. rbu_file *p = (rbu_file*)pFile;
  182153. int rc = SQLITE_OK;
  182154. int eStage = (p->pRbu ? p->pRbu->eStage : 0);
  182155. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
  182156. if( eStage==RBU_STAGE_OAL || eStage==RBU_STAGE_MOVE ){
  182157. /* no-op */
  182158. }else{
  182159. /* Release the checkpointer and writer locks */
  182160. rbuUnlockShm(p);
  182161. rc = p->pReal->pMethods->xShmUnmap(p->pReal, delFlag);
  182162. }
  182163. return rc;
  182164. }
  182165. /*
  182166. ** A main database named zName has just been opened. The following
  182167. ** function returns a pointer to a buffer owned by SQLite that contains
  182168. ** the name of the *-wal file this db connection will use. SQLite
  182169. ** happens to pass a pointer to this buffer when using xAccess()
  182170. ** or xOpen() to operate on the *-wal file.
  182171. */
  182172. static const char *rbuMainToWal(const char *zName, int flags){
  182173. int n = (int)strlen(zName);
  182174. const char *z = &zName[n];
  182175. if( flags & SQLITE_OPEN_URI ){
  182176. int odd = 0;
  182177. while( 1 ){
  182178. if( z[0]==0 ){
  182179. odd = 1 - odd;
  182180. if( odd && z[1]==0 ) break;
  182181. }
  182182. z++;
  182183. }
  182184. z += 2;
  182185. }else{
  182186. while( *z==0 ) z++;
  182187. }
  182188. z += (n + 8 + 1);
  182189. return z;
  182190. }
  182191. /*
  182192. ** Open an rbu file handle.
  182193. */
  182194. static int rbuVfsOpen(
  182195. sqlite3_vfs *pVfs,
  182196. const char *zName,
  182197. sqlite3_file *pFile,
  182198. int flags,
  182199. int *pOutFlags
  182200. ){
  182201. static sqlite3_io_methods rbuvfs_io_methods = {
  182202. 2, /* iVersion */
  182203. rbuVfsClose, /* xClose */
  182204. rbuVfsRead, /* xRead */
  182205. rbuVfsWrite, /* xWrite */
  182206. rbuVfsTruncate, /* xTruncate */
  182207. rbuVfsSync, /* xSync */
  182208. rbuVfsFileSize, /* xFileSize */
  182209. rbuVfsLock, /* xLock */
  182210. rbuVfsUnlock, /* xUnlock */
  182211. rbuVfsCheckReservedLock, /* xCheckReservedLock */
  182212. rbuVfsFileControl, /* xFileControl */
  182213. rbuVfsSectorSize, /* xSectorSize */
  182214. rbuVfsDeviceCharacteristics, /* xDeviceCharacteristics */
  182215. rbuVfsShmMap, /* xShmMap */
  182216. rbuVfsShmLock, /* xShmLock */
  182217. rbuVfsShmBarrier, /* xShmBarrier */
  182218. rbuVfsShmUnmap, /* xShmUnmap */
  182219. 0, 0 /* xFetch, xUnfetch */
  182220. };
  182221. rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
  182222. sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
  182223. rbu_file *pFd = (rbu_file *)pFile;
  182224. int rc = SQLITE_OK;
  182225. const char *zOpen = zName;
  182226. int oflags = flags;
  182227. memset(pFd, 0, sizeof(rbu_file));
  182228. pFd->pReal = (sqlite3_file*)&pFd[1];
  182229. pFd->pRbuVfs = pRbuVfs;
  182230. pFd->openFlags = flags;
  182231. if( zName ){
  182232. if( flags & SQLITE_OPEN_MAIN_DB ){
  182233. /* A main database has just been opened. The following block sets
  182234. ** (pFd->zWal) to point to a buffer owned by SQLite that contains
  182235. ** the name of the *-wal file this db connection will use. SQLite
  182236. ** happens to pass a pointer to this buffer when using xAccess()
  182237. ** or xOpen() to operate on the *-wal file. */
  182238. pFd->zWal = rbuMainToWal(zName, flags);
  182239. }
  182240. else if( flags & SQLITE_OPEN_WAL ){
  182241. rbu_file *pDb = rbuFindMaindb(pRbuVfs, zName, 0);
  182242. if( pDb ){
  182243. if( pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){
  182244. /* This call is to open a *-wal file. Intead, open the *-oal. This
  182245. ** code ensures that the string passed to xOpen() is terminated by a
  182246. ** pair of '\0' bytes in case the VFS attempts to extract a URI
  182247. ** parameter from it. */
  182248. const char *zBase = zName;
  182249. size_t nCopy;
  182250. char *zCopy;
  182251. if( rbuIsVacuum(pDb->pRbu) ){
  182252. zBase = sqlite3_db_filename(pDb->pRbu->dbRbu, "main");
  182253. zBase = rbuMainToWal(zBase, SQLITE_OPEN_URI);
  182254. }
  182255. nCopy = strlen(zBase);
  182256. zCopy = sqlite3_malloc64(nCopy+2);
  182257. if( zCopy ){
  182258. memcpy(zCopy, zBase, nCopy);
  182259. zCopy[nCopy-3] = 'o';
  182260. zCopy[nCopy] = '\0';
  182261. zCopy[nCopy+1] = '\0';
  182262. zOpen = (const char*)(pFd->zDel = zCopy);
  182263. }else{
  182264. rc = SQLITE_NOMEM;
  182265. }
  182266. pFd->pRbu = pDb->pRbu;
  182267. }
  182268. pDb->pWalFd = pFd;
  182269. }
  182270. }
  182271. }else{
  182272. pFd->pRbu = pRbuVfs->pRbu;
  182273. }
  182274. if( oflags & SQLITE_OPEN_MAIN_DB
  182275. && sqlite3_uri_boolean(zName, "rbu_memory", 0)
  182276. ){
  182277. assert( oflags & SQLITE_OPEN_MAIN_DB );
  182278. oflags = SQLITE_OPEN_TEMP_DB | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  182279. SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
  182280. zOpen = 0;
  182281. }
  182282. if( rc==SQLITE_OK ){
  182283. rc = pRealVfs->xOpen(pRealVfs, zOpen, pFd->pReal, oflags, pOutFlags);
  182284. }
  182285. if( pFd->pReal->pMethods ){
  182286. /* The xOpen() operation has succeeded. Set the sqlite3_file.pMethods
  182287. ** pointer and, if the file is a main database file, link it into the
  182288. ** mutex protected linked list of all such files. */
  182289. pFile->pMethods = &rbuvfs_io_methods;
  182290. if( flags & SQLITE_OPEN_MAIN_DB ){
  182291. rbuMainlistAdd(pFd);
  182292. }
  182293. }else{
  182294. sqlite3_free(pFd->zDel);
  182295. }
  182296. return rc;
  182297. }
  182298. /*
  182299. ** Delete the file located at zPath.
  182300. */
  182301. static int rbuVfsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
  182302. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  182303. return pRealVfs->xDelete(pRealVfs, zPath, dirSync);
  182304. }
  182305. /*
  182306. ** Test for access permissions. Return true if the requested permission
  182307. ** is available, or false otherwise.
  182308. */
  182309. static int rbuVfsAccess(
  182310. sqlite3_vfs *pVfs,
  182311. const char *zPath,
  182312. int flags,
  182313. int *pResOut
  182314. ){
  182315. rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
  182316. sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
  182317. int rc;
  182318. rc = pRealVfs->xAccess(pRealVfs, zPath, flags, pResOut);
  182319. /* If this call is to check if a *-wal file associated with an RBU target
  182320. ** database connection exists, and the RBU update is in RBU_STAGE_OAL,
  182321. ** the following special handling is activated:
  182322. **
  182323. ** a) if the *-wal file does exist, return SQLITE_CANTOPEN. This
  182324. ** ensures that the RBU extension never tries to update a database
  182325. ** in wal mode, even if the first page of the database file has
  182326. ** been damaged.
  182327. **
  182328. ** b) if the *-wal file does not exist, claim that it does anyway,
  182329. ** causing SQLite to call xOpen() to open it. This call will also
  182330. ** be intercepted (see the rbuVfsOpen() function) and the *-oal
  182331. ** file opened instead.
  182332. */
  182333. if( rc==SQLITE_OK && flags==SQLITE_ACCESS_EXISTS ){
  182334. rbu_file *pDb = rbuFindMaindb(pRbuVfs, zPath, 1);
  182335. if( pDb && pDb->pRbu->eStage==RBU_STAGE_OAL ){
  182336. assert( pDb->pRbu );
  182337. if( *pResOut ){
  182338. rc = SQLITE_CANTOPEN;
  182339. }else{
  182340. sqlite3_int64 sz = 0;
  182341. rc = rbuVfsFileSize(&pDb->base, &sz);
  182342. *pResOut = (sz>0);
  182343. }
  182344. }
  182345. }
  182346. return rc;
  182347. }
  182348. /*
  182349. ** Populate buffer zOut with the full canonical pathname corresponding
  182350. ** to the pathname in zPath. zOut is guaranteed to point to a buffer
  182351. ** of at least (DEVSYM_MAX_PATHNAME+1) bytes.
  182352. */
  182353. static int rbuVfsFullPathname(
  182354. sqlite3_vfs *pVfs,
  182355. const char *zPath,
  182356. int nOut,
  182357. char *zOut
  182358. ){
  182359. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  182360. return pRealVfs->xFullPathname(pRealVfs, zPath, nOut, zOut);
  182361. }
  182362. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  182363. /*
  182364. ** Open the dynamic library located at zPath and return a handle.
  182365. */
  182366. static void *rbuVfsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
  182367. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  182368. return pRealVfs->xDlOpen(pRealVfs, zPath);
  182369. }
  182370. /*
  182371. ** Populate the buffer zErrMsg (size nByte bytes) with a human readable
  182372. ** utf-8 string describing the most recent error encountered associated
  182373. ** with dynamic libraries.
  182374. */
  182375. static void rbuVfsDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
  182376. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  182377. pRealVfs->xDlError(pRealVfs, nByte, zErrMsg);
  182378. }
  182379. /*
  182380. ** Return a pointer to the symbol zSymbol in the dynamic library pHandle.
  182381. */
  182382. static void (*rbuVfsDlSym(
  182383. sqlite3_vfs *pVfs,
  182384. void *pArg,
  182385. const char *zSym
  182386. ))(void){
  182387. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  182388. return pRealVfs->xDlSym(pRealVfs, pArg, zSym);
  182389. }
  182390. /*
  182391. ** Close the dynamic library handle pHandle.
  182392. */
  182393. static void rbuVfsDlClose(sqlite3_vfs *pVfs, void *pHandle){
  182394. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  182395. pRealVfs->xDlClose(pRealVfs, pHandle);
  182396. }
  182397. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  182398. /*
  182399. ** Populate the buffer pointed to by zBufOut with nByte bytes of
  182400. ** random data.
  182401. */
  182402. static int rbuVfsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  182403. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  182404. return pRealVfs->xRandomness(pRealVfs, nByte, zBufOut);
  182405. }
  182406. /*
  182407. ** Sleep for nMicro microseconds. Return the number of microseconds
  182408. ** actually slept.
  182409. */
  182410. static int rbuVfsSleep(sqlite3_vfs *pVfs, int nMicro){
  182411. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  182412. return pRealVfs->xSleep(pRealVfs, nMicro);
  182413. }
  182414. /*
  182415. ** Return the current time as a Julian Day number in *pTimeOut.
  182416. */
  182417. static int rbuVfsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
  182418. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  182419. return pRealVfs->xCurrentTime(pRealVfs, pTimeOut);
  182420. }
  182421. /*
  182422. ** No-op.
  182423. */
  182424. static int rbuVfsGetLastError(sqlite3_vfs *pVfs, int a, char *b){
  182425. return 0;
  182426. }
  182427. /*
  182428. ** Deregister and destroy an RBU vfs created by an earlier call to
  182429. ** sqlite3rbu_create_vfs().
  182430. */
  182431. SQLITE_API void sqlite3rbu_destroy_vfs(const char *zName){
  182432. sqlite3_vfs *pVfs = sqlite3_vfs_find(zName);
  182433. if( pVfs && pVfs->xOpen==rbuVfsOpen ){
  182434. sqlite3_mutex_free(((rbu_vfs*)pVfs)->mutex);
  182435. sqlite3_vfs_unregister(pVfs);
  182436. sqlite3_free(pVfs);
  182437. }
  182438. }
  182439. /*
  182440. ** Create an RBU VFS named zName that accesses the underlying file-system
  182441. ** via existing VFS zParent. The new object is registered as a non-default
  182442. ** VFS with SQLite before returning.
  182443. */
  182444. SQLITE_API int sqlite3rbu_create_vfs(const char *zName, const char *zParent){
  182445. /* Template for VFS */
  182446. static sqlite3_vfs vfs_template = {
  182447. 1, /* iVersion */
  182448. 0, /* szOsFile */
  182449. 0, /* mxPathname */
  182450. 0, /* pNext */
  182451. 0, /* zName */
  182452. 0, /* pAppData */
  182453. rbuVfsOpen, /* xOpen */
  182454. rbuVfsDelete, /* xDelete */
  182455. rbuVfsAccess, /* xAccess */
  182456. rbuVfsFullPathname, /* xFullPathname */
  182457. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  182458. rbuVfsDlOpen, /* xDlOpen */
  182459. rbuVfsDlError, /* xDlError */
  182460. rbuVfsDlSym, /* xDlSym */
  182461. rbuVfsDlClose, /* xDlClose */
  182462. #else
  182463. 0, 0, 0, 0,
  182464. #endif
  182465. rbuVfsRandomness, /* xRandomness */
  182466. rbuVfsSleep, /* xSleep */
  182467. rbuVfsCurrentTime, /* xCurrentTime */
  182468. rbuVfsGetLastError, /* xGetLastError */
  182469. 0, /* xCurrentTimeInt64 (version 2) */
  182470. 0, 0, 0 /* Unimplemented version 3 methods */
  182471. };
  182472. rbu_vfs *pNew = 0; /* Newly allocated VFS */
  182473. int rc = SQLITE_OK;
  182474. size_t nName;
  182475. size_t nByte;
  182476. nName = strlen(zName);
  182477. nByte = sizeof(rbu_vfs) + nName + 1;
  182478. pNew = (rbu_vfs*)sqlite3_malloc64(nByte);
  182479. if( pNew==0 ){
  182480. rc = SQLITE_NOMEM;
  182481. }else{
  182482. sqlite3_vfs *pParent; /* Parent VFS */
  182483. memset(pNew, 0, nByte);
  182484. pParent = sqlite3_vfs_find(zParent);
  182485. if( pParent==0 ){
  182486. rc = SQLITE_NOTFOUND;
  182487. }else{
  182488. char *zSpace;
  182489. memcpy(&pNew->base, &vfs_template, sizeof(sqlite3_vfs));
  182490. pNew->base.mxPathname = pParent->mxPathname;
  182491. pNew->base.szOsFile = sizeof(rbu_file) + pParent->szOsFile;
  182492. pNew->pRealVfs = pParent;
  182493. pNew->base.zName = (const char*)(zSpace = (char*)&pNew[1]);
  182494. memcpy(zSpace, zName, nName);
  182495. /* Allocate the mutex and register the new VFS (not as the default) */
  182496. pNew->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_RECURSIVE);
  182497. if( pNew->mutex==0 ){
  182498. rc = SQLITE_NOMEM;
  182499. }else{
  182500. rc = sqlite3_vfs_register(&pNew->base, 0);
  182501. }
  182502. }
  182503. if( rc!=SQLITE_OK ){
  182504. sqlite3_mutex_free(pNew->mutex);
  182505. sqlite3_free(pNew);
  182506. }
  182507. }
  182508. return rc;
  182509. }
  182510. /*
  182511. ** Configure the aggregate temp file size limit for this RBU handle.
  182512. */
  182513. SQLITE_API sqlite3_int64 sqlite3rbu_temp_size_limit(sqlite3rbu *pRbu, sqlite3_int64 n){
  182514. if( n>=0 ){
  182515. pRbu->szTempLimit = n;
  182516. }
  182517. return pRbu->szTempLimit;
  182518. }
  182519. SQLITE_API sqlite3_int64 sqlite3rbu_temp_size(sqlite3rbu *pRbu){
  182520. return pRbu->szTemp;
  182521. }
  182522. /**************************************************************************/
  182523. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU) */
  182524. /************** End of sqlite3rbu.c ******************************************/
  182525. /************** Begin file dbstat.c ******************************************/
  182526. /*
  182527. ** 2010 July 12
  182528. **
  182529. ** The author disclaims copyright to this source code. In place of
  182530. ** a legal notice, here is a blessing:
  182531. **
  182532. ** May you do good and not evil.
  182533. ** May you find forgiveness for yourself and forgive others.
  182534. ** May you share freely, never taking more than you give.
  182535. **
  182536. ******************************************************************************
  182537. **
  182538. ** This file contains an implementation of the "dbstat" virtual table.
  182539. **
  182540. ** The dbstat virtual table is used to extract low-level formatting
  182541. ** information from an SQLite database in order to implement the
  182542. ** "sqlite3_analyzer" utility. See the ../tool/spaceanal.tcl script
  182543. ** for an example implementation.
  182544. **
  182545. ** Additional information is available on the "dbstat.html" page of the
  182546. ** official SQLite documentation.
  182547. */
  182548. /* #include "sqliteInt.h" ** Requires access to internal data structures ** */
  182549. #if (defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)) \
  182550. && !defined(SQLITE_OMIT_VIRTUALTABLE)
  182551. /*
  182552. ** Page paths:
  182553. **
  182554. ** The value of the 'path' column describes the path taken from the
  182555. ** root-node of the b-tree structure to each page. The value of the
  182556. ** root-node path is '/'.
  182557. **
  182558. ** The value of the path for the left-most child page of the root of
  182559. ** a b-tree is '/000/'. (Btrees store content ordered from left to right
  182560. ** so the pages to the left have smaller keys than the pages to the right.)
  182561. ** The next to left-most child of the root page is
  182562. ** '/001', and so on, each sibling page identified by a 3-digit hex
  182563. ** value. The children of the 451st left-most sibling have paths such
  182564. ** as '/1c2/000/, '/1c2/001/' etc.
  182565. **
  182566. ** Overflow pages are specified by appending a '+' character and a
  182567. ** six-digit hexadecimal value to the path to the cell they are linked
  182568. ** from. For example, the three overflow pages in a chain linked from
  182569. ** the left-most cell of the 450th child of the root page are identified
  182570. ** by the paths:
  182571. **
  182572. ** '/1c2/000+000000' // First page in overflow chain
  182573. ** '/1c2/000+000001' // Second page in overflow chain
  182574. ** '/1c2/000+000002' // Third page in overflow chain
  182575. **
  182576. ** If the paths are sorted using the BINARY collation sequence, then
  182577. ** the overflow pages associated with a cell will appear earlier in the
  182578. ** sort-order than its child page:
  182579. **
  182580. ** '/1c2/000/' // Left-most child of 451st child of root
  182581. */
  182582. #define VTAB_SCHEMA \
  182583. "CREATE TABLE xx( " \
  182584. " name TEXT, /* Name of table or index */" \
  182585. " path TEXT, /* Path to page from root */" \
  182586. " pageno INTEGER, /* Page number */" \
  182587. " pagetype TEXT, /* 'internal', 'leaf' or 'overflow' */" \
  182588. " ncell INTEGER, /* Cells on page (0 for overflow) */" \
  182589. " payload INTEGER, /* Bytes of payload on this page */" \
  182590. " unused INTEGER, /* Bytes of unused space on this page */" \
  182591. " mx_payload INTEGER, /* Largest payload size of all cells */" \
  182592. " pgoffset INTEGER, /* Offset of page in file */" \
  182593. " pgsize INTEGER, /* Size of the page */" \
  182594. " schema TEXT HIDDEN /* Database schema being analyzed */" \
  182595. ");"
  182596. typedef struct StatTable StatTable;
  182597. typedef struct StatCursor StatCursor;
  182598. typedef struct StatPage StatPage;
  182599. typedef struct StatCell StatCell;
  182600. struct StatCell {
  182601. int nLocal; /* Bytes of local payload */
  182602. u32 iChildPg; /* Child node (or 0 if this is a leaf) */
  182603. int nOvfl; /* Entries in aOvfl[] */
  182604. u32 *aOvfl; /* Array of overflow page numbers */
  182605. int nLastOvfl; /* Bytes of payload on final overflow page */
  182606. int iOvfl; /* Iterates through aOvfl[] */
  182607. };
  182608. struct StatPage {
  182609. u32 iPgno;
  182610. DbPage *pPg;
  182611. int iCell;
  182612. char *zPath; /* Path to this page */
  182613. /* Variables populated by statDecodePage(): */
  182614. u8 flags; /* Copy of flags byte */
  182615. int nCell; /* Number of cells on page */
  182616. int nUnused; /* Number of unused bytes on page */
  182617. StatCell *aCell; /* Array of parsed cells */
  182618. u32 iRightChildPg; /* Right-child page number (or 0) */
  182619. int nMxPayload; /* Largest payload of any cell on this page */
  182620. };
  182621. struct StatCursor {
  182622. sqlite3_vtab_cursor base;
  182623. sqlite3_stmt *pStmt; /* Iterates through set of root pages */
  182624. int isEof; /* After pStmt has returned SQLITE_DONE */
  182625. int iDb; /* Schema used for this query */
  182626. StatPage aPage[32];
  182627. int iPage; /* Current entry in aPage[] */
  182628. /* Values to return. */
  182629. char *zName; /* Value of 'name' column */
  182630. char *zPath; /* Value of 'path' column */
  182631. u32 iPageno; /* Value of 'pageno' column */
  182632. char *zPagetype; /* Value of 'pagetype' column */
  182633. int nCell; /* Value of 'ncell' column */
  182634. int nPayload; /* Value of 'payload' column */
  182635. int nUnused; /* Value of 'unused' column */
  182636. int nMxPayload; /* Value of 'mx_payload' column */
  182637. i64 iOffset; /* Value of 'pgOffset' column */
  182638. int szPage; /* Value of 'pgSize' column */
  182639. };
  182640. struct StatTable {
  182641. sqlite3_vtab base;
  182642. sqlite3 *db;
  182643. int iDb; /* Index of database to analyze */
  182644. };
  182645. #ifndef get2byte
  182646. # define get2byte(x) ((x)[0]<<8 | (x)[1])
  182647. #endif
  182648. /*
  182649. ** Connect to or create a statvfs virtual table.
  182650. */
  182651. static int statConnect(
  182652. sqlite3 *db,
  182653. void *pAux,
  182654. int argc, const char *const*argv,
  182655. sqlite3_vtab **ppVtab,
  182656. char **pzErr
  182657. ){
  182658. StatTable *pTab = 0;
  182659. int rc = SQLITE_OK;
  182660. int iDb;
  182661. if( argc>=4 ){
  182662. Token nm;
  182663. sqlite3TokenInit(&nm, (char*)argv[3]);
  182664. iDb = sqlite3FindDb(db, &nm);
  182665. if( iDb<0 ){
  182666. *pzErr = sqlite3_mprintf("no such database: %s", argv[3]);
  182667. return SQLITE_ERROR;
  182668. }
  182669. }else{
  182670. iDb = 0;
  182671. }
  182672. rc = sqlite3_declare_vtab(db, VTAB_SCHEMA);
  182673. if( rc==SQLITE_OK ){
  182674. pTab = (StatTable *)sqlite3_malloc64(sizeof(StatTable));
  182675. if( pTab==0 ) rc = SQLITE_NOMEM_BKPT;
  182676. }
  182677. assert( rc==SQLITE_OK || pTab==0 );
  182678. if( rc==SQLITE_OK ){
  182679. memset(pTab, 0, sizeof(StatTable));
  182680. pTab->db = db;
  182681. pTab->iDb = iDb;
  182682. }
  182683. *ppVtab = (sqlite3_vtab*)pTab;
  182684. return rc;
  182685. }
  182686. /*
  182687. ** Disconnect from or destroy a statvfs virtual table.
  182688. */
  182689. static int statDisconnect(sqlite3_vtab *pVtab){
  182690. sqlite3_free(pVtab);
  182691. return SQLITE_OK;
  182692. }
  182693. /*
  182694. ** There is no "best-index". This virtual table always does a linear
  182695. ** scan. However, a schema=? constraint should cause this table to
  182696. ** operate on a different database schema, so check for it.
  182697. **
  182698. ** idxNum is normally 0, but will be 1 if a schema=? constraint exists.
  182699. */
  182700. static int statBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  182701. int i;
  182702. /* Look for a valid schema=? constraint. If found, change the idxNum to
  182703. ** 1 and request the value of that constraint be sent to xFilter. And
  182704. ** lower the cost estimate to encourage the constrained version to be
  182705. ** used.
  182706. */
  182707. for(i=0; i<pIdxInfo->nConstraint; i++){
  182708. if( pIdxInfo->aConstraint[i].iColumn!=10 ) continue;
  182709. if( pIdxInfo->aConstraint[i].usable==0 ) return SQLITE_CONSTRAINT;
  182710. if( pIdxInfo->aConstraint[i].op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
  182711. pIdxInfo->idxNum = 1;
  182712. pIdxInfo->estimatedCost = 1.0;
  182713. pIdxInfo->aConstraintUsage[i].argvIndex = 1;
  182714. pIdxInfo->aConstraintUsage[i].omit = 1;
  182715. break;
  182716. }
  182717. /* Records are always returned in ascending order of (name, path).
  182718. ** If this will satisfy the client, set the orderByConsumed flag so that
  182719. ** SQLite does not do an external sort.
  182720. */
  182721. if( ( pIdxInfo->nOrderBy==1
  182722. && pIdxInfo->aOrderBy[0].iColumn==0
  182723. && pIdxInfo->aOrderBy[0].desc==0
  182724. ) ||
  182725. ( pIdxInfo->nOrderBy==2
  182726. && pIdxInfo->aOrderBy[0].iColumn==0
  182727. && pIdxInfo->aOrderBy[0].desc==0
  182728. && pIdxInfo->aOrderBy[1].iColumn==1
  182729. && pIdxInfo->aOrderBy[1].desc==0
  182730. )
  182731. ){
  182732. pIdxInfo->orderByConsumed = 1;
  182733. }
  182734. return SQLITE_OK;
  182735. }
  182736. /*
  182737. ** Open a new statvfs cursor.
  182738. */
  182739. static int statOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  182740. StatTable *pTab = (StatTable *)pVTab;
  182741. StatCursor *pCsr;
  182742. pCsr = (StatCursor *)sqlite3_malloc64(sizeof(StatCursor));
  182743. if( pCsr==0 ){
  182744. return SQLITE_NOMEM_BKPT;
  182745. }else{
  182746. memset(pCsr, 0, sizeof(StatCursor));
  182747. pCsr->base.pVtab = pVTab;
  182748. pCsr->iDb = pTab->iDb;
  182749. }
  182750. *ppCursor = (sqlite3_vtab_cursor *)pCsr;
  182751. return SQLITE_OK;
  182752. }
  182753. static void statClearCells(StatPage *p){
  182754. int i;
  182755. if( p->aCell ){
  182756. for(i=0; i<p->nCell; i++){
  182757. sqlite3_free(p->aCell[i].aOvfl);
  182758. }
  182759. sqlite3_free(p->aCell);
  182760. }
  182761. p->nCell = 0;
  182762. p->aCell = 0;
  182763. }
  182764. static void statClearPage(StatPage *p){
  182765. statClearCells(p);
  182766. sqlite3PagerUnref(p->pPg);
  182767. sqlite3_free(p->zPath);
  182768. memset(p, 0, sizeof(StatPage));
  182769. }
  182770. static void statResetCsr(StatCursor *pCsr){
  182771. int i;
  182772. sqlite3_reset(pCsr->pStmt);
  182773. for(i=0; i<ArraySize(pCsr->aPage); i++){
  182774. statClearPage(&pCsr->aPage[i]);
  182775. }
  182776. pCsr->iPage = 0;
  182777. sqlite3_free(pCsr->zPath);
  182778. pCsr->zPath = 0;
  182779. pCsr->isEof = 0;
  182780. }
  182781. /*
  182782. ** Close a statvfs cursor.
  182783. */
  182784. static int statClose(sqlite3_vtab_cursor *pCursor){
  182785. StatCursor *pCsr = (StatCursor *)pCursor;
  182786. statResetCsr(pCsr);
  182787. sqlite3_finalize(pCsr->pStmt);
  182788. sqlite3_free(pCsr);
  182789. return SQLITE_OK;
  182790. }
  182791. static void getLocalPayload(
  182792. int nUsable, /* Usable bytes per page */
  182793. u8 flags, /* Page flags */
  182794. int nTotal, /* Total record (payload) size */
  182795. int *pnLocal /* OUT: Bytes stored locally */
  182796. ){
  182797. int nLocal;
  182798. int nMinLocal;
  182799. int nMaxLocal;
  182800. if( flags==0x0D ){ /* Table leaf node */
  182801. nMinLocal = (nUsable - 12) * 32 / 255 - 23;
  182802. nMaxLocal = nUsable - 35;
  182803. }else{ /* Index interior and leaf nodes */
  182804. nMinLocal = (nUsable - 12) * 32 / 255 - 23;
  182805. nMaxLocal = (nUsable - 12) * 64 / 255 - 23;
  182806. }
  182807. nLocal = nMinLocal + (nTotal - nMinLocal) % (nUsable - 4);
  182808. if( nLocal>nMaxLocal ) nLocal = nMinLocal;
  182809. *pnLocal = nLocal;
  182810. }
  182811. static int statDecodePage(Btree *pBt, StatPage *p){
  182812. int nUnused;
  182813. int iOff;
  182814. int nHdr;
  182815. int isLeaf;
  182816. int szPage;
  182817. u8 *aData = sqlite3PagerGetData(p->pPg);
  182818. u8 *aHdr = &aData[p->iPgno==1 ? 100 : 0];
  182819. p->flags = aHdr[0];
  182820. if( p->flags==0x0A || p->flags==0x0D ){
  182821. isLeaf = 1;
  182822. nHdr = 8;
  182823. }else if( p->flags==0x05 || p->flags==0x02 ){
  182824. isLeaf = 0;
  182825. nHdr = 12;
  182826. }else{
  182827. goto statPageIsCorrupt;
  182828. }
  182829. if( p->iPgno==1 ) nHdr += 100;
  182830. p->nCell = get2byte(&aHdr[3]);
  182831. p->nMxPayload = 0;
  182832. szPage = sqlite3BtreeGetPageSize(pBt);
  182833. nUnused = get2byte(&aHdr[5]) - nHdr - 2*p->nCell;
  182834. nUnused += (int)aHdr[7];
  182835. iOff = get2byte(&aHdr[1]);
  182836. while( iOff ){
  182837. int iNext;
  182838. if( iOff>=szPage ) goto statPageIsCorrupt;
  182839. nUnused += get2byte(&aData[iOff+2]);
  182840. iNext = get2byte(&aData[iOff]);
  182841. if( iNext<iOff+4 && iNext>0 ) goto statPageIsCorrupt;
  182842. iOff = iNext;
  182843. }
  182844. p->nUnused = nUnused;
  182845. p->iRightChildPg = isLeaf ? 0 : sqlite3Get4byte(&aHdr[8]);
  182846. if( p->nCell ){
  182847. int i; /* Used to iterate through cells */
  182848. int nUsable; /* Usable bytes per page */
  182849. sqlite3BtreeEnter(pBt);
  182850. nUsable = szPage - sqlite3BtreeGetReserveNoMutex(pBt);
  182851. sqlite3BtreeLeave(pBt);
  182852. p->aCell = sqlite3_malloc64((p->nCell+1) * sizeof(StatCell));
  182853. if( p->aCell==0 ) return SQLITE_NOMEM_BKPT;
  182854. memset(p->aCell, 0, (p->nCell+1) * sizeof(StatCell));
  182855. for(i=0; i<p->nCell; i++){
  182856. StatCell *pCell = &p->aCell[i];
  182857. iOff = get2byte(&aData[nHdr+i*2]);
  182858. if( iOff<nHdr || iOff>=szPage ) goto statPageIsCorrupt;
  182859. if( !isLeaf ){
  182860. pCell->iChildPg = sqlite3Get4byte(&aData[iOff]);
  182861. iOff += 4;
  182862. }
  182863. if( p->flags==0x05 ){
  182864. /* A table interior node. nPayload==0. */
  182865. }else{
  182866. u32 nPayload; /* Bytes of payload total (local+overflow) */
  182867. int nLocal; /* Bytes of payload stored locally */
  182868. iOff += getVarint32(&aData[iOff], nPayload);
  182869. if( p->flags==0x0D ){
  182870. u64 dummy;
  182871. iOff += sqlite3GetVarint(&aData[iOff], &dummy);
  182872. }
  182873. if( nPayload>(u32)p->nMxPayload ) p->nMxPayload = nPayload;
  182874. getLocalPayload(nUsable, p->flags, nPayload, &nLocal);
  182875. if( nLocal<0 ) goto statPageIsCorrupt;
  182876. pCell->nLocal = nLocal;
  182877. assert( nPayload>=(u32)nLocal );
  182878. assert( nLocal<=(nUsable-35) );
  182879. if( nPayload>(u32)nLocal ){
  182880. int j;
  182881. int nOvfl = ((nPayload - nLocal) + nUsable-4 - 1) / (nUsable - 4);
  182882. if( iOff+nLocal>nUsable ) goto statPageIsCorrupt;
  182883. pCell->nLastOvfl = (nPayload-nLocal) - (nOvfl-1) * (nUsable-4);
  182884. pCell->nOvfl = nOvfl;
  182885. pCell->aOvfl = sqlite3_malloc64(sizeof(u32)*nOvfl);
  182886. if( pCell->aOvfl==0 ) return SQLITE_NOMEM_BKPT;
  182887. pCell->aOvfl[0] = sqlite3Get4byte(&aData[iOff+nLocal]);
  182888. for(j=1; j<nOvfl; j++){
  182889. int rc;
  182890. u32 iPrev = pCell->aOvfl[j-1];
  182891. DbPage *pPg = 0;
  182892. rc = sqlite3PagerGet(sqlite3BtreePager(pBt), iPrev, &pPg, 0);
  182893. if( rc!=SQLITE_OK ){
  182894. assert( pPg==0 );
  182895. return rc;
  182896. }
  182897. pCell->aOvfl[j] = sqlite3Get4byte(sqlite3PagerGetData(pPg));
  182898. sqlite3PagerUnref(pPg);
  182899. }
  182900. }
  182901. }
  182902. }
  182903. }
  182904. return SQLITE_OK;
  182905. statPageIsCorrupt:
  182906. p->flags = 0;
  182907. statClearCells(p);
  182908. return SQLITE_OK;
  182909. }
  182910. /*
  182911. ** Populate the pCsr->iOffset and pCsr->szPage member variables. Based on
  182912. ** the current value of pCsr->iPageno.
  182913. */
  182914. static void statSizeAndOffset(StatCursor *pCsr){
  182915. StatTable *pTab = (StatTable *)((sqlite3_vtab_cursor *)pCsr)->pVtab;
  182916. Btree *pBt = pTab->db->aDb[pTab->iDb].pBt;
  182917. Pager *pPager = sqlite3BtreePager(pBt);
  182918. sqlite3_file *fd;
  182919. sqlite3_int64 x[2];
  182920. /* The default page size and offset */
  182921. pCsr->szPage = sqlite3BtreeGetPageSize(pBt);
  182922. pCsr->iOffset = (i64)pCsr->szPage * (pCsr->iPageno - 1);
  182923. /* If connected to a ZIPVFS backend, override the page size and
  182924. ** offset with actual values obtained from ZIPVFS.
  182925. */
  182926. fd = sqlite3PagerFile(pPager);
  182927. x[0] = pCsr->iPageno;
  182928. if( sqlite3OsFileControl(fd, 230440, &x)==SQLITE_OK ){
  182929. pCsr->iOffset = x[0];
  182930. pCsr->szPage = (int)x[1];
  182931. }
  182932. }
  182933. /*
  182934. ** Move a statvfs cursor to the next entry in the file.
  182935. */
  182936. static int statNext(sqlite3_vtab_cursor *pCursor){
  182937. int rc;
  182938. int nPayload;
  182939. char *z;
  182940. StatCursor *pCsr = (StatCursor *)pCursor;
  182941. StatTable *pTab = (StatTable *)pCursor->pVtab;
  182942. Btree *pBt = pTab->db->aDb[pCsr->iDb].pBt;
  182943. Pager *pPager = sqlite3BtreePager(pBt);
  182944. sqlite3_free(pCsr->zPath);
  182945. pCsr->zPath = 0;
  182946. statNextRestart:
  182947. if( pCsr->aPage[0].pPg==0 ){
  182948. rc = sqlite3_step(pCsr->pStmt);
  182949. if( rc==SQLITE_ROW ){
  182950. int nPage;
  182951. u32 iRoot = (u32)sqlite3_column_int64(pCsr->pStmt, 1);
  182952. sqlite3PagerPagecount(pPager, &nPage);
  182953. if( nPage==0 ){
  182954. pCsr->isEof = 1;
  182955. return sqlite3_reset(pCsr->pStmt);
  182956. }
  182957. rc = sqlite3PagerGet(pPager, iRoot, &pCsr->aPage[0].pPg, 0);
  182958. pCsr->aPage[0].iPgno = iRoot;
  182959. pCsr->aPage[0].iCell = 0;
  182960. pCsr->aPage[0].zPath = z = sqlite3_mprintf("/");
  182961. pCsr->iPage = 0;
  182962. if( z==0 ) rc = SQLITE_NOMEM_BKPT;
  182963. }else{
  182964. pCsr->isEof = 1;
  182965. return sqlite3_reset(pCsr->pStmt);
  182966. }
  182967. }else{
  182968. /* Page p itself has already been visited. */
  182969. StatPage *p = &pCsr->aPage[pCsr->iPage];
  182970. while( p->iCell<p->nCell ){
  182971. StatCell *pCell = &p->aCell[p->iCell];
  182972. if( pCell->iOvfl<pCell->nOvfl ){
  182973. int nUsable;
  182974. sqlite3BtreeEnter(pBt);
  182975. nUsable = sqlite3BtreeGetPageSize(pBt) -
  182976. sqlite3BtreeGetReserveNoMutex(pBt);
  182977. sqlite3BtreeLeave(pBt);
  182978. pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
  182979. pCsr->iPageno = pCell->aOvfl[pCell->iOvfl];
  182980. pCsr->zPagetype = "overflow";
  182981. pCsr->nCell = 0;
  182982. pCsr->nMxPayload = 0;
  182983. pCsr->zPath = z = sqlite3_mprintf(
  182984. "%s%.3x+%.6x", p->zPath, p->iCell, pCell->iOvfl
  182985. );
  182986. if( pCell->iOvfl<pCell->nOvfl-1 ){
  182987. pCsr->nUnused = 0;
  182988. pCsr->nPayload = nUsable - 4;
  182989. }else{
  182990. pCsr->nPayload = pCell->nLastOvfl;
  182991. pCsr->nUnused = nUsable - 4 - pCsr->nPayload;
  182992. }
  182993. pCell->iOvfl++;
  182994. statSizeAndOffset(pCsr);
  182995. return z==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK;
  182996. }
  182997. if( p->iRightChildPg ) break;
  182998. p->iCell++;
  182999. }
  183000. if( !p->iRightChildPg || p->iCell>p->nCell ){
  183001. statClearPage(p);
  183002. if( pCsr->iPage==0 ) return statNext(pCursor);
  183003. pCsr->iPage--;
  183004. goto statNextRestart; /* Tail recursion */
  183005. }
  183006. pCsr->iPage++;
  183007. if( pCsr->iPage>=ArraySize(pCsr->aPage) ){
  183008. statResetCsr(pCsr);
  183009. return SQLITE_CORRUPT_BKPT;
  183010. }
  183011. assert( p==&pCsr->aPage[pCsr->iPage-1] );
  183012. if( p->iCell==p->nCell ){
  183013. p[1].iPgno = p->iRightChildPg;
  183014. }else{
  183015. p[1].iPgno = p->aCell[p->iCell].iChildPg;
  183016. }
  183017. rc = sqlite3PagerGet(pPager, p[1].iPgno, &p[1].pPg, 0);
  183018. p[1].iCell = 0;
  183019. p[1].zPath = z = sqlite3_mprintf("%s%.3x/", p->zPath, p->iCell);
  183020. p->iCell++;
  183021. if( z==0 ) rc = SQLITE_NOMEM_BKPT;
  183022. }
  183023. /* Populate the StatCursor fields with the values to be returned
  183024. ** by the xColumn() and xRowid() methods.
  183025. */
  183026. if( rc==SQLITE_OK ){
  183027. int i;
  183028. StatPage *p = &pCsr->aPage[pCsr->iPage];
  183029. pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
  183030. pCsr->iPageno = p->iPgno;
  183031. rc = statDecodePage(pBt, p);
  183032. if( rc==SQLITE_OK ){
  183033. statSizeAndOffset(pCsr);
  183034. switch( p->flags ){
  183035. case 0x05: /* table internal */
  183036. case 0x02: /* index internal */
  183037. pCsr->zPagetype = "internal";
  183038. break;
  183039. case 0x0D: /* table leaf */
  183040. case 0x0A: /* index leaf */
  183041. pCsr->zPagetype = "leaf";
  183042. break;
  183043. default:
  183044. pCsr->zPagetype = "corrupted";
  183045. break;
  183046. }
  183047. pCsr->nCell = p->nCell;
  183048. pCsr->nUnused = p->nUnused;
  183049. pCsr->nMxPayload = p->nMxPayload;
  183050. pCsr->zPath = z = sqlite3_mprintf("%s", p->zPath);
  183051. if( z==0 ) rc = SQLITE_NOMEM_BKPT;
  183052. nPayload = 0;
  183053. for(i=0; i<p->nCell; i++){
  183054. nPayload += p->aCell[i].nLocal;
  183055. }
  183056. pCsr->nPayload = nPayload;
  183057. }
  183058. }
  183059. return rc;
  183060. }
  183061. static int statEof(sqlite3_vtab_cursor *pCursor){
  183062. StatCursor *pCsr = (StatCursor *)pCursor;
  183063. return pCsr->isEof;
  183064. }
  183065. static int statFilter(
  183066. sqlite3_vtab_cursor *pCursor,
  183067. int idxNum, const char *idxStr,
  183068. int argc, sqlite3_value **argv
  183069. ){
  183070. StatCursor *pCsr = (StatCursor *)pCursor;
  183071. StatTable *pTab = (StatTable*)(pCursor->pVtab);
  183072. char *zSql;
  183073. int rc = SQLITE_OK;
  183074. if( idxNum==1 ){
  183075. const char *zDbase = (const char*)sqlite3_value_text(argv[0]);
  183076. pCsr->iDb = sqlite3FindDbName(pTab->db, zDbase);
  183077. if( pCsr->iDb<0 ){
  183078. sqlite3_free(pCursor->pVtab->zErrMsg);
  183079. pCursor->pVtab->zErrMsg = sqlite3_mprintf("no such schema: %s", zDbase);
  183080. return pCursor->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM_BKPT;
  183081. }
  183082. }else{
  183083. pCsr->iDb = pTab->iDb;
  183084. }
  183085. statResetCsr(pCsr);
  183086. sqlite3_finalize(pCsr->pStmt);
  183087. pCsr->pStmt = 0;
  183088. zSql = sqlite3_mprintf(
  183089. "SELECT 'sqlite_master' AS name, 1 AS rootpage, 'table' AS type"
  183090. " UNION ALL "
  183091. "SELECT name, rootpage, type"
  183092. " FROM \"%w\".sqlite_master WHERE rootpage!=0"
  183093. " ORDER BY name", pTab->db->aDb[pCsr->iDb].zDbSName);
  183094. if( zSql==0 ){
  183095. return SQLITE_NOMEM_BKPT;
  183096. }else{
  183097. rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pStmt, 0);
  183098. sqlite3_free(zSql);
  183099. }
  183100. if( rc==SQLITE_OK ){
  183101. rc = statNext(pCursor);
  183102. }
  183103. return rc;
  183104. }
  183105. static int statColumn(
  183106. sqlite3_vtab_cursor *pCursor,
  183107. sqlite3_context *ctx,
  183108. int i
  183109. ){
  183110. StatCursor *pCsr = (StatCursor *)pCursor;
  183111. switch( i ){
  183112. case 0: /* name */
  183113. sqlite3_result_text(ctx, pCsr->zName, -1, SQLITE_TRANSIENT);
  183114. break;
  183115. case 1: /* path */
  183116. sqlite3_result_text(ctx, pCsr->zPath, -1, SQLITE_TRANSIENT);
  183117. break;
  183118. case 2: /* pageno */
  183119. sqlite3_result_int64(ctx, pCsr->iPageno);
  183120. break;
  183121. case 3: /* pagetype */
  183122. sqlite3_result_text(ctx, pCsr->zPagetype, -1, SQLITE_STATIC);
  183123. break;
  183124. case 4: /* ncell */
  183125. sqlite3_result_int(ctx, pCsr->nCell);
  183126. break;
  183127. case 5: /* payload */
  183128. sqlite3_result_int(ctx, pCsr->nPayload);
  183129. break;
  183130. case 6: /* unused */
  183131. sqlite3_result_int(ctx, pCsr->nUnused);
  183132. break;
  183133. case 7: /* mx_payload */
  183134. sqlite3_result_int(ctx, pCsr->nMxPayload);
  183135. break;
  183136. case 8: /* pgoffset */
  183137. sqlite3_result_int64(ctx, pCsr->iOffset);
  183138. break;
  183139. case 9: /* pgsize */
  183140. sqlite3_result_int(ctx, pCsr->szPage);
  183141. break;
  183142. default: { /* schema */
  183143. sqlite3 *db = sqlite3_context_db_handle(ctx);
  183144. int iDb = pCsr->iDb;
  183145. sqlite3_result_text(ctx, db->aDb[iDb].zDbSName, -1, SQLITE_STATIC);
  183146. break;
  183147. }
  183148. }
  183149. return SQLITE_OK;
  183150. }
  183151. static int statRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  183152. StatCursor *pCsr = (StatCursor *)pCursor;
  183153. *pRowid = pCsr->iPageno;
  183154. return SQLITE_OK;
  183155. }
  183156. /*
  183157. ** Invoke this routine to register the "dbstat" virtual table module
  183158. */
  183159. SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){
  183160. static sqlite3_module dbstat_module = {
  183161. 0, /* iVersion */
  183162. statConnect, /* xCreate */
  183163. statConnect, /* xConnect */
  183164. statBestIndex, /* xBestIndex */
  183165. statDisconnect, /* xDisconnect */
  183166. statDisconnect, /* xDestroy */
  183167. statOpen, /* xOpen - open a cursor */
  183168. statClose, /* xClose - close a cursor */
  183169. statFilter, /* xFilter - configure scan constraints */
  183170. statNext, /* xNext - advance a cursor */
  183171. statEof, /* xEof - check for end of scan */
  183172. statColumn, /* xColumn - read data */
  183173. statRowid, /* xRowid - read data */
  183174. 0, /* xUpdate */
  183175. 0, /* xBegin */
  183176. 0, /* xSync */
  183177. 0, /* xCommit */
  183178. 0, /* xRollback */
  183179. 0, /* xFindMethod */
  183180. 0, /* xRename */
  183181. 0, /* xSavepoint */
  183182. 0, /* xRelease */
  183183. 0, /* xRollbackTo */
  183184. 0 /* xShadowName */
  183185. };
  183186. return sqlite3_create_module(db, "dbstat", &dbstat_module, 0);
  183187. }
  183188. #elif defined(SQLITE_ENABLE_DBSTAT_VTAB)
  183189. SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){ return SQLITE_OK; }
  183190. #endif /* SQLITE_ENABLE_DBSTAT_VTAB */
  183191. /************** End of dbstat.c **********************************************/
  183192. /************** Begin file dbpage.c ******************************************/
  183193. /*
  183194. ** 2017-10-11
  183195. **
  183196. ** The author disclaims copyright to this source code. In place of
  183197. ** a legal notice, here is a blessing:
  183198. **
  183199. ** May you do good and not evil.
  183200. ** May you find forgiveness for yourself and forgive others.
  183201. ** May you share freely, never taking more than you give.
  183202. **
  183203. ******************************************************************************
  183204. **
  183205. ** This file contains an implementation of the "sqlite_dbpage" virtual table.
  183206. **
  183207. ** The sqlite_dbpage virtual table is used to read or write whole raw
  183208. ** pages of the database file. The pager interface is used so that
  183209. ** uncommitted changes and changes recorded in the WAL file are correctly
  183210. ** retrieved.
  183211. **
  183212. ** Usage example:
  183213. **
  183214. ** SELECT data FROM sqlite_dbpage('aux1') WHERE pgno=123;
  183215. **
  183216. ** This is an eponymous virtual table so it does not need to be created before
  183217. ** use. The optional argument to the sqlite_dbpage() table name is the
  183218. ** schema for the database file that is to be read. The default schema is
  183219. ** "main".
  183220. **
  183221. ** The data field of sqlite_dbpage table can be updated. The new
  183222. ** value must be a BLOB which is the correct page size, otherwise the
  183223. ** update fails. Rows may not be deleted or inserted.
  183224. */
  183225. /* #include "sqliteInt.h" ** Requires access to internal data structures ** */
  183226. #if (defined(SQLITE_ENABLE_DBPAGE_VTAB) || defined(SQLITE_TEST)) \
  183227. && !defined(SQLITE_OMIT_VIRTUALTABLE)
  183228. typedef struct DbpageTable DbpageTable;
  183229. typedef struct DbpageCursor DbpageCursor;
  183230. struct DbpageCursor {
  183231. sqlite3_vtab_cursor base; /* Base class. Must be first */
  183232. int pgno; /* Current page number */
  183233. int mxPgno; /* Last page to visit on this scan */
  183234. Pager *pPager; /* Pager being read/written */
  183235. DbPage *pPage1; /* Page 1 of the database */
  183236. int iDb; /* Index of database to analyze */
  183237. int szPage; /* Size of each page in bytes */
  183238. };
  183239. struct DbpageTable {
  183240. sqlite3_vtab base; /* Base class. Must be first */
  183241. sqlite3 *db; /* The database */
  183242. };
  183243. /* Columns */
  183244. #define DBPAGE_COLUMN_PGNO 0
  183245. #define DBPAGE_COLUMN_DATA 1
  183246. #define DBPAGE_COLUMN_SCHEMA 2
  183247. /*
  183248. ** Connect to or create a dbpagevfs virtual table.
  183249. */
  183250. static int dbpageConnect(
  183251. sqlite3 *db,
  183252. void *pAux,
  183253. int argc, const char *const*argv,
  183254. sqlite3_vtab **ppVtab,
  183255. char **pzErr
  183256. ){
  183257. DbpageTable *pTab = 0;
  183258. int rc = SQLITE_OK;
  183259. rc = sqlite3_declare_vtab(db,
  183260. "CREATE TABLE x(pgno INTEGER PRIMARY KEY, data BLOB, schema HIDDEN)");
  183261. if( rc==SQLITE_OK ){
  183262. pTab = (DbpageTable *)sqlite3_malloc64(sizeof(DbpageTable));
  183263. if( pTab==0 ) rc = SQLITE_NOMEM_BKPT;
  183264. }
  183265. assert( rc==SQLITE_OK || pTab==0 );
  183266. if( rc==SQLITE_OK ){
  183267. memset(pTab, 0, sizeof(DbpageTable));
  183268. pTab->db = db;
  183269. }
  183270. *ppVtab = (sqlite3_vtab*)pTab;
  183271. return rc;
  183272. }
  183273. /*
  183274. ** Disconnect from or destroy a dbpagevfs virtual table.
  183275. */
  183276. static int dbpageDisconnect(sqlite3_vtab *pVtab){
  183277. sqlite3_free(pVtab);
  183278. return SQLITE_OK;
  183279. }
  183280. /*
  183281. ** idxNum:
  183282. **
  183283. ** 0 schema=main, full table scan
  183284. ** 1 schema=main, pgno=?1
  183285. ** 2 schema=?1, full table scan
  183286. ** 3 schema=?1, pgno=?2
  183287. */
  183288. static int dbpageBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  183289. int i;
  183290. int iPlan = 0;
  183291. /* If there is a schema= constraint, it must be honored. Report a
  183292. ** ridiculously large estimated cost if the schema= constraint is
  183293. ** unavailable
  183294. */
  183295. for(i=0; i<pIdxInfo->nConstraint; i++){
  183296. struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[i];
  183297. if( p->iColumn!=DBPAGE_COLUMN_SCHEMA ) continue;
  183298. if( p->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
  183299. if( !p->usable ){
  183300. /* No solution. */
  183301. return SQLITE_CONSTRAINT;
  183302. }
  183303. iPlan = 2;
  183304. pIdxInfo->aConstraintUsage[i].argvIndex = 1;
  183305. pIdxInfo->aConstraintUsage[i].omit = 1;
  183306. break;
  183307. }
  183308. /* If we reach this point, it means that either there is no schema=
  183309. ** constraint (in which case we use the "main" schema) or else the
  183310. ** schema constraint was accepted. Lower the estimated cost accordingly
  183311. */
  183312. pIdxInfo->estimatedCost = 1.0e6;
  183313. /* Check for constraints against pgno */
  183314. for(i=0; i<pIdxInfo->nConstraint; i++){
  183315. struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[i];
  183316. if( p->usable && p->iColumn<=0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
  183317. pIdxInfo->estimatedRows = 1;
  183318. pIdxInfo->idxFlags = SQLITE_INDEX_SCAN_UNIQUE;
  183319. pIdxInfo->estimatedCost = 1.0;
  183320. pIdxInfo->aConstraintUsage[i].argvIndex = iPlan ? 2 : 1;
  183321. pIdxInfo->aConstraintUsage[i].omit = 1;
  183322. iPlan |= 1;
  183323. break;
  183324. }
  183325. }
  183326. pIdxInfo->idxNum = iPlan;
  183327. if( pIdxInfo->nOrderBy>=1
  183328. && pIdxInfo->aOrderBy[0].iColumn<=0
  183329. && pIdxInfo->aOrderBy[0].desc==0
  183330. ){
  183331. pIdxInfo->orderByConsumed = 1;
  183332. }
  183333. return SQLITE_OK;
  183334. }
  183335. /*
  183336. ** Open a new dbpagevfs cursor.
  183337. */
  183338. static int dbpageOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  183339. DbpageCursor *pCsr;
  183340. pCsr = (DbpageCursor *)sqlite3_malloc64(sizeof(DbpageCursor));
  183341. if( pCsr==0 ){
  183342. return SQLITE_NOMEM_BKPT;
  183343. }else{
  183344. memset(pCsr, 0, sizeof(DbpageCursor));
  183345. pCsr->base.pVtab = pVTab;
  183346. pCsr->pgno = -1;
  183347. }
  183348. *ppCursor = (sqlite3_vtab_cursor *)pCsr;
  183349. return SQLITE_OK;
  183350. }
  183351. /*
  183352. ** Close a dbpagevfs cursor.
  183353. */
  183354. static int dbpageClose(sqlite3_vtab_cursor *pCursor){
  183355. DbpageCursor *pCsr = (DbpageCursor *)pCursor;
  183356. if( pCsr->pPage1 ) sqlite3PagerUnrefPageOne(pCsr->pPage1);
  183357. sqlite3_free(pCsr);
  183358. return SQLITE_OK;
  183359. }
  183360. /*
  183361. ** Move a dbpagevfs cursor to the next entry in the file.
  183362. */
  183363. static int dbpageNext(sqlite3_vtab_cursor *pCursor){
  183364. int rc = SQLITE_OK;
  183365. DbpageCursor *pCsr = (DbpageCursor *)pCursor;
  183366. pCsr->pgno++;
  183367. return rc;
  183368. }
  183369. static int dbpageEof(sqlite3_vtab_cursor *pCursor){
  183370. DbpageCursor *pCsr = (DbpageCursor *)pCursor;
  183371. return pCsr->pgno > pCsr->mxPgno;
  183372. }
  183373. /*
  183374. ** idxNum:
  183375. **
  183376. ** 0 schema=main, full table scan
  183377. ** 1 schema=main, pgno=?1
  183378. ** 2 schema=?1, full table scan
  183379. ** 3 schema=?1, pgno=?2
  183380. **
  183381. ** idxStr is not used
  183382. */
  183383. static int dbpageFilter(
  183384. sqlite3_vtab_cursor *pCursor,
  183385. int idxNum, const char *idxStr,
  183386. int argc, sqlite3_value **argv
  183387. ){
  183388. DbpageCursor *pCsr = (DbpageCursor *)pCursor;
  183389. DbpageTable *pTab = (DbpageTable *)pCursor->pVtab;
  183390. int rc;
  183391. sqlite3 *db = pTab->db;
  183392. Btree *pBt;
  183393. /* Default setting is no rows of result */
  183394. pCsr->pgno = 1;
  183395. pCsr->mxPgno = 0;
  183396. if( idxNum & 2 ){
  183397. const char *zSchema;
  183398. assert( argc>=1 );
  183399. zSchema = (const char*)sqlite3_value_text(argv[0]);
  183400. pCsr->iDb = sqlite3FindDbName(db, zSchema);
  183401. if( pCsr->iDb<0 ) return SQLITE_OK;
  183402. }else{
  183403. pCsr->iDb = 0;
  183404. }
  183405. pBt = db->aDb[pCsr->iDb].pBt;
  183406. if( pBt==0 ) return SQLITE_OK;
  183407. pCsr->pPager = sqlite3BtreePager(pBt);
  183408. pCsr->szPage = sqlite3BtreeGetPageSize(pBt);
  183409. pCsr->mxPgno = sqlite3BtreeLastPage(pBt);
  183410. if( idxNum & 1 ){
  183411. assert( argc>(idxNum>>1) );
  183412. pCsr->pgno = sqlite3_value_int(argv[idxNum>>1]);
  183413. if( pCsr->pgno<1 || pCsr->pgno>pCsr->mxPgno ){
  183414. pCsr->pgno = 1;
  183415. pCsr->mxPgno = 0;
  183416. }else{
  183417. pCsr->mxPgno = pCsr->pgno;
  183418. }
  183419. }else{
  183420. assert( pCsr->pgno==1 );
  183421. }
  183422. if( pCsr->pPage1 ) sqlite3PagerUnrefPageOne(pCsr->pPage1);
  183423. rc = sqlite3PagerGet(pCsr->pPager, 1, &pCsr->pPage1, 0);
  183424. return rc;
  183425. }
  183426. static int dbpageColumn(
  183427. sqlite3_vtab_cursor *pCursor,
  183428. sqlite3_context *ctx,
  183429. int i
  183430. ){
  183431. DbpageCursor *pCsr = (DbpageCursor *)pCursor;
  183432. int rc = SQLITE_OK;
  183433. switch( i ){
  183434. case 0: { /* pgno */
  183435. sqlite3_result_int(ctx, pCsr->pgno);
  183436. break;
  183437. }
  183438. case 1: { /* data */
  183439. DbPage *pDbPage = 0;
  183440. rc = sqlite3PagerGet(pCsr->pPager, pCsr->pgno, (DbPage**)&pDbPage, 0);
  183441. if( rc==SQLITE_OK ){
  183442. sqlite3_result_blob(ctx, sqlite3PagerGetData(pDbPage), pCsr->szPage,
  183443. SQLITE_TRANSIENT);
  183444. }
  183445. sqlite3PagerUnref(pDbPage);
  183446. break;
  183447. }
  183448. default: { /* schema */
  183449. sqlite3 *db = sqlite3_context_db_handle(ctx);
  183450. sqlite3_result_text(ctx, db->aDb[pCsr->iDb].zDbSName, -1, SQLITE_STATIC);
  183451. break;
  183452. }
  183453. }
  183454. return SQLITE_OK;
  183455. }
  183456. static int dbpageRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  183457. DbpageCursor *pCsr = (DbpageCursor *)pCursor;
  183458. *pRowid = pCsr->pgno;
  183459. return SQLITE_OK;
  183460. }
  183461. static int dbpageUpdate(
  183462. sqlite3_vtab *pVtab,
  183463. int argc,
  183464. sqlite3_value **argv,
  183465. sqlite_int64 *pRowid
  183466. ){
  183467. DbpageTable *pTab = (DbpageTable *)pVtab;
  183468. Pgno pgno;
  183469. DbPage *pDbPage = 0;
  183470. int rc = SQLITE_OK;
  183471. char *zErr = 0;
  183472. const char *zSchema;
  183473. int iDb;
  183474. Btree *pBt;
  183475. Pager *pPager;
  183476. int szPage;
  183477. if( pTab->db->flags & SQLITE_Defensive ){
  183478. zErr = "read-only";
  183479. goto update_fail;
  183480. }
  183481. if( argc==1 ){
  183482. zErr = "cannot delete";
  183483. goto update_fail;
  183484. }
  183485. pgno = sqlite3_value_int(argv[0]);
  183486. if( (Pgno)sqlite3_value_int(argv[1])!=pgno ){
  183487. zErr = "cannot insert";
  183488. goto update_fail;
  183489. }
  183490. zSchema = (const char*)sqlite3_value_text(argv[4]);
  183491. iDb = zSchema ? sqlite3FindDbName(pTab->db, zSchema) : -1;
  183492. if( iDb<0 ){
  183493. zErr = "no such schema";
  183494. goto update_fail;
  183495. }
  183496. pBt = pTab->db->aDb[iDb].pBt;
  183497. if( pgno<1 || pBt==0 || pgno>(int)sqlite3BtreeLastPage(pBt) ){
  183498. zErr = "bad page number";
  183499. goto update_fail;
  183500. }
  183501. szPage = sqlite3BtreeGetPageSize(pBt);
  183502. if( sqlite3_value_type(argv[3])!=SQLITE_BLOB
  183503. || sqlite3_value_bytes(argv[3])!=szPage
  183504. ){
  183505. zErr = "bad page value";
  183506. goto update_fail;
  183507. }
  183508. pPager = sqlite3BtreePager(pBt);
  183509. rc = sqlite3PagerGet(pPager, pgno, (DbPage**)&pDbPage, 0);
  183510. if( rc==SQLITE_OK ){
  183511. rc = sqlite3PagerWrite(pDbPage);
  183512. if( rc==SQLITE_OK ){
  183513. memcpy(sqlite3PagerGetData(pDbPage),
  183514. sqlite3_value_blob(argv[3]),
  183515. szPage);
  183516. }
  183517. }
  183518. sqlite3PagerUnref(pDbPage);
  183519. return rc;
  183520. update_fail:
  183521. sqlite3_free(pVtab->zErrMsg);
  183522. pVtab->zErrMsg = sqlite3_mprintf("%s", zErr);
  183523. return SQLITE_ERROR;
  183524. }
  183525. /* Since we do not know in advance which database files will be
  183526. ** written by the sqlite_dbpage virtual table, start a write transaction
  183527. ** on them all.
  183528. */
  183529. static int dbpageBegin(sqlite3_vtab *pVtab){
  183530. DbpageTable *pTab = (DbpageTable *)pVtab;
  183531. sqlite3 *db = pTab->db;
  183532. int i;
  183533. for(i=0; i<db->nDb; i++){
  183534. Btree *pBt = db->aDb[i].pBt;
  183535. if( pBt ) sqlite3BtreeBeginTrans(pBt, 1, 0);
  183536. }
  183537. return SQLITE_OK;
  183538. }
  183539. /*
  183540. ** Invoke this routine to register the "dbpage" virtual table module
  183541. */
  183542. SQLITE_PRIVATE int sqlite3DbpageRegister(sqlite3 *db){
  183543. static sqlite3_module dbpage_module = {
  183544. 0, /* iVersion */
  183545. dbpageConnect, /* xCreate */
  183546. dbpageConnect, /* xConnect */
  183547. dbpageBestIndex, /* xBestIndex */
  183548. dbpageDisconnect, /* xDisconnect */
  183549. dbpageDisconnect, /* xDestroy */
  183550. dbpageOpen, /* xOpen - open a cursor */
  183551. dbpageClose, /* xClose - close a cursor */
  183552. dbpageFilter, /* xFilter - configure scan constraints */
  183553. dbpageNext, /* xNext - advance a cursor */
  183554. dbpageEof, /* xEof - check for end of scan */
  183555. dbpageColumn, /* xColumn - read data */
  183556. dbpageRowid, /* xRowid - read data */
  183557. dbpageUpdate, /* xUpdate */
  183558. dbpageBegin, /* xBegin */
  183559. 0, /* xSync */
  183560. 0, /* xCommit */
  183561. 0, /* xRollback */
  183562. 0, /* xFindMethod */
  183563. 0, /* xRename */
  183564. 0, /* xSavepoint */
  183565. 0, /* xRelease */
  183566. 0, /* xRollbackTo */
  183567. 0 /* xShadowName */
  183568. };
  183569. return sqlite3_create_module(db, "sqlite_dbpage", &dbpage_module, 0);
  183570. }
  183571. #elif defined(SQLITE_ENABLE_DBPAGE_VTAB)
  183572. SQLITE_PRIVATE int sqlite3DbpageRegister(sqlite3 *db){ return SQLITE_OK; }
  183573. #endif /* SQLITE_ENABLE_DBSTAT_VTAB */
  183574. /************** End of dbpage.c **********************************************/
  183575. /************** Begin file sqlite3session.c **********************************/
  183576. #if defined(SQLITE_ENABLE_SESSION) && defined(SQLITE_ENABLE_PREUPDATE_HOOK)
  183577. /* #include "sqlite3session.h" */
  183578. /* #include <assert.h> */
  183579. /* #include <string.h> */
  183580. #ifndef SQLITE_AMALGAMATION
  183581. /* # include "sqliteInt.h" */
  183582. /* # include "vdbeInt.h" */
  183583. #endif
  183584. typedef struct SessionTable SessionTable;
  183585. typedef struct SessionChange SessionChange;
  183586. typedef struct SessionBuffer SessionBuffer;
  183587. typedef struct SessionInput SessionInput;
  183588. /*
  183589. ** Minimum chunk size used by streaming versions of functions.
  183590. */
  183591. #ifndef SESSIONS_STRM_CHUNK_SIZE
  183592. # ifdef SQLITE_TEST
  183593. # define SESSIONS_STRM_CHUNK_SIZE 64
  183594. # else
  183595. # define SESSIONS_STRM_CHUNK_SIZE 1024
  183596. # endif
  183597. #endif
  183598. static int sessions_strm_chunk_size = SESSIONS_STRM_CHUNK_SIZE;
  183599. typedef struct SessionHook SessionHook;
  183600. struct SessionHook {
  183601. void *pCtx;
  183602. int (*xOld)(void*,int,sqlite3_value**);
  183603. int (*xNew)(void*,int,sqlite3_value**);
  183604. int (*xCount)(void*);
  183605. int (*xDepth)(void*);
  183606. };
  183607. /*
  183608. ** Session handle structure.
  183609. */
  183610. struct sqlite3_session {
  183611. sqlite3 *db; /* Database handle session is attached to */
  183612. char *zDb; /* Name of database session is attached to */
  183613. int bEnable; /* True if currently recording */
  183614. int bIndirect; /* True if all changes are indirect */
  183615. int bAutoAttach; /* True to auto-attach tables */
  183616. int rc; /* Non-zero if an error has occurred */
  183617. void *pFilterCtx; /* First argument to pass to xTableFilter */
  183618. int (*xTableFilter)(void *pCtx, const char *zTab);
  183619. sqlite3_value *pZeroBlob; /* Value containing X'' */
  183620. sqlite3_session *pNext; /* Next session object on same db. */
  183621. SessionTable *pTable; /* List of attached tables */
  183622. SessionHook hook; /* APIs to grab new and old data with */
  183623. };
  183624. /*
  183625. ** Instances of this structure are used to build strings or binary records.
  183626. */
  183627. struct SessionBuffer {
  183628. u8 *aBuf; /* Pointer to changeset buffer */
  183629. int nBuf; /* Size of buffer aBuf */
  183630. int nAlloc; /* Size of allocation containing aBuf */
  183631. };
  183632. /*
  183633. ** An object of this type is used internally as an abstraction for
  183634. ** input data. Input data may be supplied either as a single large buffer
  183635. ** (e.g. sqlite3changeset_start()) or using a stream function (e.g.
  183636. ** sqlite3changeset_start_strm()).
  183637. */
  183638. struct SessionInput {
  183639. int bNoDiscard; /* If true, do not discard in InputBuffer() */
  183640. int iCurrent; /* Offset in aData[] of current change */
  183641. int iNext; /* Offset in aData[] of next change */
  183642. u8 *aData; /* Pointer to buffer containing changeset */
  183643. int nData; /* Number of bytes in aData */
  183644. SessionBuffer buf; /* Current read buffer */
  183645. int (*xInput)(void*, void*, int*); /* Input stream call (or NULL) */
  183646. void *pIn; /* First argument to xInput */
  183647. int bEof; /* Set to true after xInput finished */
  183648. };
  183649. /*
  183650. ** Structure for changeset iterators.
  183651. */
  183652. struct sqlite3_changeset_iter {
  183653. SessionInput in; /* Input buffer or stream */
  183654. SessionBuffer tblhdr; /* Buffer to hold apValue/zTab/abPK/ */
  183655. int bPatchset; /* True if this is a patchset */
  183656. int bInvert; /* True to invert changeset */
  183657. int rc; /* Iterator error code */
  183658. sqlite3_stmt *pConflict; /* Points to conflicting row, if any */
  183659. char *zTab; /* Current table */
  183660. int nCol; /* Number of columns in zTab */
  183661. int op; /* Current operation */
  183662. int bIndirect; /* True if current change was indirect */
  183663. u8 *abPK; /* Primary key array */
  183664. sqlite3_value **apValue; /* old.* and new.* values */
  183665. };
  183666. /*
  183667. ** Each session object maintains a set of the following structures, one
  183668. ** for each table the session object is monitoring. The structures are
  183669. ** stored in a linked list starting at sqlite3_session.pTable.
  183670. **
  183671. ** The keys of the SessionTable.aChange[] hash table are all rows that have
  183672. ** been modified in any way since the session object was attached to the
  183673. ** table.
  183674. **
  183675. ** The data associated with each hash-table entry is a structure containing
  183676. ** a subset of the initial values that the modified row contained at the
  183677. ** start of the session. Or no initial values if the row was inserted.
  183678. */
  183679. struct SessionTable {
  183680. SessionTable *pNext;
  183681. char *zName; /* Local name of table */
  183682. int nCol; /* Number of columns in table zName */
  183683. int bStat1; /* True if this is sqlite_stat1 */
  183684. const char **azCol; /* Column names */
  183685. u8 *abPK; /* Array of primary key flags */
  183686. int nEntry; /* Total number of entries in hash table */
  183687. int nChange; /* Size of apChange[] array */
  183688. SessionChange **apChange; /* Hash table buckets */
  183689. };
  183690. /*
  183691. ** RECORD FORMAT:
  183692. **
  183693. ** The following record format is similar to (but not compatible with) that
  183694. ** used in SQLite database files. This format is used as part of the
  183695. ** change-set binary format, and so must be architecture independent.
  183696. **
  183697. ** Unlike the SQLite database record format, each field is self-contained -
  183698. ** there is no separation of header and data. Each field begins with a
  183699. ** single byte describing its type, as follows:
  183700. **
  183701. ** 0x00: Undefined value.
  183702. ** 0x01: Integer value.
  183703. ** 0x02: Real value.
  183704. ** 0x03: Text value.
  183705. ** 0x04: Blob value.
  183706. ** 0x05: SQL NULL value.
  183707. **
  183708. ** Note that the above match the definitions of SQLITE_INTEGER, SQLITE_TEXT
  183709. ** and so on in sqlite3.h. For undefined and NULL values, the field consists
  183710. ** only of the single type byte. For other types of values, the type byte
  183711. ** is followed by:
  183712. **
  183713. ** Text values:
  183714. ** A varint containing the number of bytes in the value (encoded using
  183715. ** UTF-8). Followed by a buffer containing the UTF-8 representation
  183716. ** of the text value. There is no nul terminator.
  183717. **
  183718. ** Blob values:
  183719. ** A varint containing the number of bytes in the value, followed by
  183720. ** a buffer containing the value itself.
  183721. **
  183722. ** Integer values:
  183723. ** An 8-byte big-endian integer value.
  183724. **
  183725. ** Real values:
  183726. ** An 8-byte big-endian IEEE 754-2008 real value.
  183727. **
  183728. ** Varint values are encoded in the same way as varints in the SQLite
  183729. ** record format.
  183730. **
  183731. ** CHANGESET FORMAT:
  183732. **
  183733. ** A changeset is a collection of DELETE, UPDATE and INSERT operations on
  183734. ** one or more tables. Operations on a single table are grouped together,
  183735. ** but may occur in any order (i.e. deletes, updates and inserts are all
  183736. ** mixed together).
  183737. **
  183738. ** Each group of changes begins with a table header:
  183739. **
  183740. ** 1 byte: Constant 0x54 (capital 'T')
  183741. ** Varint: Number of columns in the table.
  183742. ** nCol bytes: 0x01 for PK columns, 0x00 otherwise.
  183743. ** N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
  183744. **
  183745. ** Followed by one or more changes to the table.
  183746. **
  183747. ** 1 byte: Either SQLITE_INSERT (0x12), UPDATE (0x17) or DELETE (0x09).
  183748. ** 1 byte: The "indirect-change" flag.
  183749. ** old.* record: (delete and update only)
  183750. ** new.* record: (insert and update only)
  183751. **
  183752. ** The "old.*" and "new.*" records, if present, are N field records in the
  183753. ** format described above under "RECORD FORMAT", where N is the number of
  183754. ** columns in the table. The i'th field of each record is associated with
  183755. ** the i'th column of the table, counting from left to right in the order
  183756. ** in which columns were declared in the CREATE TABLE statement.
  183757. **
  183758. ** The new.* record that is part of each INSERT change contains the values
  183759. ** that make up the new row. Similarly, the old.* record that is part of each
  183760. ** DELETE change contains the values that made up the row that was deleted
  183761. ** from the database. In the changeset format, the records that are part
  183762. ** of INSERT or DELETE changes never contain any undefined (type byte 0x00)
  183763. ** fields.
  183764. **
  183765. ** Within the old.* record associated with an UPDATE change, all fields
  183766. ** associated with table columns that are not PRIMARY KEY columns and are
  183767. ** not modified by the UPDATE change are set to "undefined". Other fields
  183768. ** are set to the values that made up the row before the UPDATE that the
  183769. ** change records took place. Within the new.* record, fields associated
  183770. ** with table columns modified by the UPDATE change contain the new
  183771. ** values. Fields associated with table columns that are not modified
  183772. ** are set to "undefined".
  183773. **
  183774. ** PATCHSET FORMAT:
  183775. **
  183776. ** A patchset is also a collection of changes. It is similar to a changeset,
  183777. ** but leaves undefined those fields that are not useful if no conflict
  183778. ** resolution is required when applying the changeset.
  183779. **
  183780. ** Each group of changes begins with a table header:
  183781. **
  183782. ** 1 byte: Constant 0x50 (capital 'P')
  183783. ** Varint: Number of columns in the table.
  183784. ** nCol bytes: 0x01 for PK columns, 0x00 otherwise.
  183785. ** N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
  183786. **
  183787. ** Followed by one or more changes to the table.
  183788. **
  183789. ** 1 byte: Either SQLITE_INSERT (0x12), UPDATE (0x17) or DELETE (0x09).
  183790. ** 1 byte: The "indirect-change" flag.
  183791. ** single record: (PK fields for DELETE, PK and modified fields for UPDATE,
  183792. ** full record for INSERT).
  183793. **
  183794. ** As in the changeset format, each field of the single record that is part
  183795. ** of a patchset change is associated with the correspondingly positioned
  183796. ** table column, counting from left to right within the CREATE TABLE
  183797. ** statement.
  183798. **
  183799. ** For a DELETE change, all fields within the record except those associated
  183800. ** with PRIMARY KEY columns are omitted. The PRIMARY KEY fields contain the
  183801. ** values identifying the row to delete.
  183802. **
  183803. ** For an UPDATE change, all fields except those associated with PRIMARY KEY
  183804. ** columns and columns that are modified by the UPDATE are set to "undefined".
  183805. ** PRIMARY KEY fields contain the values identifying the table row to update,
  183806. ** and fields associated with modified columns contain the new column values.
  183807. **
  183808. ** The records associated with INSERT changes are in the same format as for
  183809. ** changesets. It is not possible for a record associated with an INSERT
  183810. ** change to contain a field set to "undefined".
  183811. **
  183812. ** REBASE BLOB FORMAT:
  183813. **
  183814. ** A rebase blob may be output by sqlite3changeset_apply_v2() and its
  183815. ** streaming equivalent for use with the sqlite3_rebaser APIs to rebase
  183816. ** existing changesets. A rebase blob contains one entry for each conflict
  183817. ** resolved using either the OMIT or REPLACE strategies within the apply_v2()
  183818. ** call.
  183819. **
  183820. ** The format used for a rebase blob is very similar to that used for
  183821. ** changesets. All entries related to a single table are grouped together.
  183822. **
  183823. ** Each group of entries begins with a table header in changeset format:
  183824. **
  183825. ** 1 byte: Constant 0x54 (capital 'T')
  183826. ** Varint: Number of columns in the table.
  183827. ** nCol bytes: 0x01 for PK columns, 0x00 otherwise.
  183828. ** N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
  183829. **
  183830. ** Followed by one or more entries associated with the table.
  183831. **
  183832. ** 1 byte: Either SQLITE_INSERT (0x12), DELETE (0x09).
  183833. ** 1 byte: Flag. 0x01 for REPLACE, 0x00 for OMIT.
  183834. ** record: (in the record format defined above).
  183835. **
  183836. ** In a rebase blob, the first field is set to SQLITE_INSERT if the change
  183837. ** that caused the conflict was an INSERT or UPDATE, or to SQLITE_DELETE if
  183838. ** it was a DELETE. The second field is set to 0x01 if the conflict
  183839. ** resolution strategy was REPLACE, or 0x00 if it was OMIT.
  183840. **
  183841. ** If the change that caused the conflict was a DELETE, then the single
  183842. ** record is a copy of the old.* record from the original changeset. If it
  183843. ** was an INSERT, then the single record is a copy of the new.* record. If
  183844. ** the conflicting change was an UPDATE, then the single record is a copy
  183845. ** of the new.* record with the PK fields filled in based on the original
  183846. ** old.* record.
  183847. */
  183848. /*
  183849. ** For each row modified during a session, there exists a single instance of
  183850. ** this structure stored in a SessionTable.aChange[] hash table.
  183851. */
  183852. struct SessionChange {
  183853. int op; /* One of UPDATE, DELETE, INSERT */
  183854. int bIndirect; /* True if this change is "indirect" */
  183855. int nRecord; /* Number of bytes in buffer aRecord[] */
  183856. u8 *aRecord; /* Buffer containing old.* record */
  183857. SessionChange *pNext; /* For hash-table collisions */
  183858. };
  183859. /*
  183860. ** Write a varint with value iVal into the buffer at aBuf. Return the
  183861. ** number of bytes written.
  183862. */
  183863. static int sessionVarintPut(u8 *aBuf, int iVal){
  183864. return putVarint32(aBuf, iVal);
  183865. }
  183866. /*
  183867. ** Return the number of bytes required to store value iVal as a varint.
  183868. */
  183869. static int sessionVarintLen(int iVal){
  183870. return sqlite3VarintLen(iVal);
  183871. }
  183872. /*
  183873. ** Read a varint value from aBuf[] into *piVal. Return the number of
  183874. ** bytes read.
  183875. */
  183876. static int sessionVarintGet(u8 *aBuf, int *piVal){
  183877. return getVarint32(aBuf, *piVal);
  183878. }
  183879. /* Load an unaligned and unsigned 32-bit integer */
  183880. #define SESSION_UINT32(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
  183881. /*
  183882. ** Read a 64-bit big-endian integer value from buffer aRec[]. Return
  183883. ** the value read.
  183884. */
  183885. static sqlite3_int64 sessionGetI64(u8 *aRec){
  183886. u64 x = SESSION_UINT32(aRec);
  183887. u32 y = SESSION_UINT32(aRec+4);
  183888. x = (x<<32) + y;
  183889. return (sqlite3_int64)x;
  183890. }
  183891. /*
  183892. ** Write a 64-bit big-endian integer value to the buffer aBuf[].
  183893. */
  183894. static void sessionPutI64(u8 *aBuf, sqlite3_int64 i){
  183895. aBuf[0] = (i>>56) & 0xFF;
  183896. aBuf[1] = (i>>48) & 0xFF;
  183897. aBuf[2] = (i>>40) & 0xFF;
  183898. aBuf[3] = (i>>32) & 0xFF;
  183899. aBuf[4] = (i>>24) & 0xFF;
  183900. aBuf[5] = (i>>16) & 0xFF;
  183901. aBuf[6] = (i>> 8) & 0xFF;
  183902. aBuf[7] = (i>> 0) & 0xFF;
  183903. }
  183904. /*
  183905. ** This function is used to serialize the contents of value pValue (see
  183906. ** comment titled "RECORD FORMAT" above).
  183907. **
  183908. ** If it is non-NULL, the serialized form of the value is written to
  183909. ** buffer aBuf. *pnWrite is set to the number of bytes written before
  183910. ** returning. Or, if aBuf is NULL, the only thing this function does is
  183911. ** set *pnWrite.
  183912. **
  183913. ** If no error occurs, SQLITE_OK is returned. Or, if an OOM error occurs
  183914. ** within a call to sqlite3_value_text() (may fail if the db is utf-16))
  183915. ** SQLITE_NOMEM is returned.
  183916. */
  183917. static int sessionSerializeValue(
  183918. u8 *aBuf, /* If non-NULL, write serialized value here */
  183919. sqlite3_value *pValue, /* Value to serialize */
  183920. sqlite3_int64 *pnWrite /* IN/OUT: Increment by bytes written */
  183921. ){
  183922. int nByte; /* Size of serialized value in bytes */
  183923. if( pValue ){
  183924. int eType; /* Value type (SQLITE_NULL, TEXT etc.) */
  183925. eType = sqlite3_value_type(pValue);
  183926. if( aBuf ) aBuf[0] = eType;
  183927. switch( eType ){
  183928. case SQLITE_NULL:
  183929. nByte = 1;
  183930. break;
  183931. case SQLITE_INTEGER:
  183932. case SQLITE_FLOAT:
  183933. if( aBuf ){
  183934. /* TODO: SQLite does something special to deal with mixed-endian
  183935. ** floating point values (e.g. ARM7). This code probably should
  183936. ** too. */
  183937. u64 i;
  183938. if( eType==SQLITE_INTEGER ){
  183939. i = (u64)sqlite3_value_int64(pValue);
  183940. }else{
  183941. double r;
  183942. assert( sizeof(double)==8 && sizeof(u64)==8 );
  183943. r = sqlite3_value_double(pValue);
  183944. memcpy(&i, &r, 8);
  183945. }
  183946. sessionPutI64(&aBuf[1], i);
  183947. }
  183948. nByte = 9;
  183949. break;
  183950. default: {
  183951. u8 *z;
  183952. int n;
  183953. int nVarint;
  183954. assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
  183955. if( eType==SQLITE_TEXT ){
  183956. z = (u8 *)sqlite3_value_text(pValue);
  183957. }else{
  183958. z = (u8 *)sqlite3_value_blob(pValue);
  183959. }
  183960. n = sqlite3_value_bytes(pValue);
  183961. if( z==0 && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;
  183962. nVarint = sessionVarintLen(n);
  183963. if( aBuf ){
  183964. sessionVarintPut(&aBuf[1], n);
  183965. if( n ) memcpy(&aBuf[nVarint + 1], z, n);
  183966. }
  183967. nByte = 1 + nVarint + n;
  183968. break;
  183969. }
  183970. }
  183971. }else{
  183972. nByte = 1;
  183973. if( aBuf ) aBuf[0] = '\0';
  183974. }
  183975. if( pnWrite ) *pnWrite += nByte;
  183976. return SQLITE_OK;
  183977. }
  183978. /*
  183979. ** This macro is used to calculate hash key values for data structures. In
  183980. ** order to use this macro, the entire data structure must be represented
  183981. ** as a series of unsigned integers. In order to calculate a hash-key value
  183982. ** for a data structure represented as three such integers, the macro may
  183983. ** then be used as follows:
  183984. **
  183985. ** int hash_key_value;
  183986. ** hash_key_value = HASH_APPEND(0, <value 1>);
  183987. ** hash_key_value = HASH_APPEND(hash_key_value, <value 2>);
  183988. ** hash_key_value = HASH_APPEND(hash_key_value, <value 3>);
  183989. **
  183990. ** In practice, the data structures this macro is used for are the primary
  183991. ** key values of modified rows.
  183992. */
  183993. #define HASH_APPEND(hash, add) ((hash) << 3) ^ (hash) ^ (unsigned int)(add)
  183994. /*
  183995. ** Append the hash of the 64-bit integer passed as the second argument to the
  183996. ** hash-key value passed as the first. Return the new hash-key value.
  183997. */
  183998. static unsigned int sessionHashAppendI64(unsigned int h, i64 i){
  183999. h = HASH_APPEND(h, i & 0xFFFFFFFF);
  184000. return HASH_APPEND(h, (i>>32)&0xFFFFFFFF);
  184001. }
  184002. /*
  184003. ** Append the hash of the blob passed via the second and third arguments to
  184004. ** the hash-key value passed as the first. Return the new hash-key value.
  184005. */
  184006. static unsigned int sessionHashAppendBlob(unsigned int h, int n, const u8 *z){
  184007. int i;
  184008. for(i=0; i<n; i++) h = HASH_APPEND(h, z[i]);
  184009. return h;
  184010. }
  184011. /*
  184012. ** Append the hash of the data type passed as the second argument to the
  184013. ** hash-key value passed as the first. Return the new hash-key value.
  184014. */
  184015. static unsigned int sessionHashAppendType(unsigned int h, int eType){
  184016. return HASH_APPEND(h, eType);
  184017. }
  184018. /*
  184019. ** This function may only be called from within a pre-update callback.
  184020. ** It calculates a hash based on the primary key values of the old.* or
  184021. ** new.* row currently available and, assuming no error occurs, writes it to
  184022. ** *piHash before returning. If the primary key contains one or more NULL
  184023. ** values, *pbNullPK is set to true before returning.
  184024. **
  184025. ** If an error occurs, an SQLite error code is returned and the final values
  184026. ** of *piHash asn *pbNullPK are undefined. Otherwise, SQLITE_OK is returned
  184027. ** and the output variables are set as described above.
  184028. */
  184029. static int sessionPreupdateHash(
  184030. sqlite3_session *pSession, /* Session object that owns pTab */
  184031. SessionTable *pTab, /* Session table handle */
  184032. int bNew, /* True to hash the new.* PK */
  184033. int *piHash, /* OUT: Hash value */
  184034. int *pbNullPK /* OUT: True if there are NULL values in PK */
  184035. ){
  184036. unsigned int h = 0; /* Hash value to return */
  184037. int i; /* Used to iterate through columns */
  184038. assert( *pbNullPK==0 );
  184039. assert( pTab->nCol==pSession->hook.xCount(pSession->hook.pCtx) );
  184040. for(i=0; i<pTab->nCol; i++){
  184041. if( pTab->abPK[i] ){
  184042. int rc;
  184043. int eType;
  184044. sqlite3_value *pVal;
  184045. if( bNew ){
  184046. rc = pSession->hook.xNew(pSession->hook.pCtx, i, &pVal);
  184047. }else{
  184048. rc = pSession->hook.xOld(pSession->hook.pCtx, i, &pVal);
  184049. }
  184050. if( rc!=SQLITE_OK ) return rc;
  184051. eType = sqlite3_value_type(pVal);
  184052. h = sessionHashAppendType(h, eType);
  184053. if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  184054. i64 iVal;
  184055. if( eType==SQLITE_INTEGER ){
  184056. iVal = sqlite3_value_int64(pVal);
  184057. }else{
  184058. double rVal = sqlite3_value_double(pVal);
  184059. assert( sizeof(iVal)==8 && sizeof(rVal)==8 );
  184060. memcpy(&iVal, &rVal, 8);
  184061. }
  184062. h = sessionHashAppendI64(h, iVal);
  184063. }else if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
  184064. const u8 *z;
  184065. int n;
  184066. if( eType==SQLITE_TEXT ){
  184067. z = (const u8 *)sqlite3_value_text(pVal);
  184068. }else{
  184069. z = (const u8 *)sqlite3_value_blob(pVal);
  184070. }
  184071. n = sqlite3_value_bytes(pVal);
  184072. if( !z && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;
  184073. h = sessionHashAppendBlob(h, n, z);
  184074. }else{
  184075. assert( eType==SQLITE_NULL );
  184076. assert( pTab->bStat1==0 || i!=1 );
  184077. *pbNullPK = 1;
  184078. }
  184079. }
  184080. }
  184081. *piHash = (h % pTab->nChange);
  184082. return SQLITE_OK;
  184083. }
  184084. /*
  184085. ** The buffer that the argument points to contains a serialized SQL value.
  184086. ** Return the number of bytes of space occupied by the value (including
  184087. ** the type byte).
  184088. */
  184089. static int sessionSerialLen(u8 *a){
  184090. int e = *a;
  184091. int n;
  184092. if( e==0 || e==0xFF ) return 1;
  184093. if( e==SQLITE_NULL ) return 1;
  184094. if( e==SQLITE_INTEGER || e==SQLITE_FLOAT ) return 9;
  184095. return sessionVarintGet(&a[1], &n) + 1 + n;
  184096. }
  184097. /*
  184098. ** Based on the primary key values stored in change aRecord, calculate a
  184099. ** hash key. Assume the has table has nBucket buckets. The hash keys
  184100. ** calculated by this function are compatible with those calculated by
  184101. ** sessionPreupdateHash().
  184102. **
  184103. ** The bPkOnly argument is non-zero if the record at aRecord[] is from
  184104. ** a patchset DELETE. In this case the non-PK fields are omitted entirely.
  184105. */
  184106. static unsigned int sessionChangeHash(
  184107. SessionTable *pTab, /* Table handle */
  184108. int bPkOnly, /* Record consists of PK fields only */
  184109. u8 *aRecord, /* Change record */
  184110. int nBucket /* Assume this many buckets in hash table */
  184111. ){
  184112. unsigned int h = 0; /* Value to return */
  184113. int i; /* Used to iterate through columns */
  184114. u8 *a = aRecord; /* Used to iterate through change record */
  184115. for(i=0; i<pTab->nCol; i++){
  184116. int eType = *a;
  184117. int isPK = pTab->abPK[i];
  184118. if( bPkOnly && isPK==0 ) continue;
  184119. /* It is not possible for eType to be SQLITE_NULL here. The session
  184120. ** module does not record changes for rows with NULL values stored in
  184121. ** primary key columns. */
  184122. assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT
  184123. || eType==SQLITE_TEXT || eType==SQLITE_BLOB
  184124. || eType==SQLITE_NULL || eType==0
  184125. );
  184126. assert( !isPK || (eType!=0 && eType!=SQLITE_NULL) );
  184127. if( isPK ){
  184128. a++;
  184129. h = sessionHashAppendType(h, eType);
  184130. if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  184131. h = sessionHashAppendI64(h, sessionGetI64(a));
  184132. a += 8;
  184133. }else{
  184134. int n;
  184135. a += sessionVarintGet(a, &n);
  184136. h = sessionHashAppendBlob(h, n, a);
  184137. a += n;
  184138. }
  184139. }else{
  184140. a += sessionSerialLen(a);
  184141. }
  184142. }
  184143. return (h % nBucket);
  184144. }
  184145. /*
  184146. ** Arguments aLeft and aRight are pointers to change records for table pTab.
  184147. ** This function returns true if the two records apply to the same row (i.e.
  184148. ** have the same values stored in the primary key columns), or false
  184149. ** otherwise.
  184150. */
  184151. static int sessionChangeEqual(
  184152. SessionTable *pTab, /* Table used for PK definition */
  184153. int bLeftPkOnly, /* True if aLeft[] contains PK fields only */
  184154. u8 *aLeft, /* Change record */
  184155. int bRightPkOnly, /* True if aRight[] contains PK fields only */
  184156. u8 *aRight /* Change record */
  184157. ){
  184158. u8 *a1 = aLeft; /* Cursor to iterate through aLeft */
  184159. u8 *a2 = aRight; /* Cursor to iterate through aRight */
  184160. int iCol; /* Used to iterate through table columns */
  184161. for(iCol=0; iCol<pTab->nCol; iCol++){
  184162. if( pTab->abPK[iCol] ){
  184163. int n1 = sessionSerialLen(a1);
  184164. int n2 = sessionSerialLen(a2);
  184165. if( n1!=n2 || memcmp(a1, a2, n1) ){
  184166. return 0;
  184167. }
  184168. a1 += n1;
  184169. a2 += n2;
  184170. }else{
  184171. if( bLeftPkOnly==0 ) a1 += sessionSerialLen(a1);
  184172. if( bRightPkOnly==0 ) a2 += sessionSerialLen(a2);
  184173. }
  184174. }
  184175. return 1;
  184176. }
  184177. /*
  184178. ** Arguments aLeft and aRight both point to buffers containing change
  184179. ** records with nCol columns. This function "merges" the two records into
  184180. ** a single records which is written to the buffer at *paOut. *paOut is
  184181. ** then set to point to one byte after the last byte written before
  184182. ** returning.
  184183. **
  184184. ** The merging of records is done as follows: For each column, if the
  184185. ** aRight record contains a value for the column, copy the value from
  184186. ** their. Otherwise, if aLeft contains a value, copy it. If neither
  184187. ** record contains a value for a given column, then neither does the
  184188. ** output record.
  184189. */
  184190. static void sessionMergeRecord(
  184191. u8 **paOut,
  184192. int nCol,
  184193. u8 *aLeft,
  184194. u8 *aRight
  184195. ){
  184196. u8 *a1 = aLeft; /* Cursor used to iterate through aLeft */
  184197. u8 *a2 = aRight; /* Cursor used to iterate through aRight */
  184198. u8 *aOut = *paOut; /* Output cursor */
  184199. int iCol; /* Used to iterate from 0 to nCol */
  184200. for(iCol=0; iCol<nCol; iCol++){
  184201. int n1 = sessionSerialLen(a1);
  184202. int n2 = sessionSerialLen(a2);
  184203. if( *a2 ){
  184204. memcpy(aOut, a2, n2);
  184205. aOut += n2;
  184206. }else{
  184207. memcpy(aOut, a1, n1);
  184208. aOut += n1;
  184209. }
  184210. a1 += n1;
  184211. a2 += n2;
  184212. }
  184213. *paOut = aOut;
  184214. }
  184215. /*
  184216. ** This is a helper function used by sessionMergeUpdate().
  184217. **
  184218. ** When this function is called, both *paOne and *paTwo point to a value
  184219. ** within a change record. Before it returns, both have been advanced so
  184220. ** as to point to the next value in the record.
  184221. **
  184222. ** If, when this function is called, *paTwo points to a valid value (i.e.
  184223. ** *paTwo[0] is not 0x00 - the "no value" placeholder), a copy of the *paTwo
  184224. ** pointer is returned and *pnVal is set to the number of bytes in the
  184225. ** serialized value. Otherwise, a copy of *paOne is returned and *pnVal
  184226. ** set to the number of bytes in the value at *paOne. If *paOne points
  184227. ** to the "no value" placeholder, *pnVal is set to 1. In other words:
  184228. **
  184229. ** if( *paTwo is valid ) return *paTwo;
  184230. ** return *paOne;
  184231. **
  184232. */
  184233. static u8 *sessionMergeValue(
  184234. u8 **paOne, /* IN/OUT: Left-hand buffer pointer */
  184235. u8 **paTwo, /* IN/OUT: Right-hand buffer pointer */
  184236. int *pnVal /* OUT: Bytes in returned value */
  184237. ){
  184238. u8 *a1 = *paOne;
  184239. u8 *a2 = *paTwo;
  184240. u8 *pRet = 0;
  184241. int n1;
  184242. assert( a1 );
  184243. if( a2 ){
  184244. int n2 = sessionSerialLen(a2);
  184245. if( *a2 ){
  184246. *pnVal = n2;
  184247. pRet = a2;
  184248. }
  184249. *paTwo = &a2[n2];
  184250. }
  184251. n1 = sessionSerialLen(a1);
  184252. if( pRet==0 ){
  184253. *pnVal = n1;
  184254. pRet = a1;
  184255. }
  184256. *paOne = &a1[n1];
  184257. return pRet;
  184258. }
  184259. /*
  184260. ** This function is used by changeset_concat() to merge two UPDATE changes
  184261. ** on the same row.
  184262. */
  184263. static int sessionMergeUpdate(
  184264. u8 **paOut, /* IN/OUT: Pointer to output buffer */
  184265. SessionTable *pTab, /* Table change pertains to */
  184266. int bPatchset, /* True if records are patchset records */
  184267. u8 *aOldRecord1, /* old.* record for first change */
  184268. u8 *aOldRecord2, /* old.* record for second change */
  184269. u8 *aNewRecord1, /* new.* record for first change */
  184270. u8 *aNewRecord2 /* new.* record for second change */
  184271. ){
  184272. u8 *aOld1 = aOldRecord1;
  184273. u8 *aOld2 = aOldRecord2;
  184274. u8 *aNew1 = aNewRecord1;
  184275. u8 *aNew2 = aNewRecord2;
  184276. u8 *aOut = *paOut;
  184277. int i;
  184278. if( bPatchset==0 ){
  184279. int bRequired = 0;
  184280. assert( aOldRecord1 && aNewRecord1 );
  184281. /* Write the old.* vector first. */
  184282. for(i=0; i<pTab->nCol; i++){
  184283. int nOld;
  184284. u8 *aOld;
  184285. int nNew;
  184286. u8 *aNew;
  184287. aOld = sessionMergeValue(&aOld1, &aOld2, &nOld);
  184288. aNew = sessionMergeValue(&aNew1, &aNew2, &nNew);
  184289. if( pTab->abPK[i] || nOld!=nNew || memcmp(aOld, aNew, nNew) ){
  184290. if( pTab->abPK[i]==0 ) bRequired = 1;
  184291. memcpy(aOut, aOld, nOld);
  184292. aOut += nOld;
  184293. }else{
  184294. *(aOut++) = '\0';
  184295. }
  184296. }
  184297. if( !bRequired ) return 0;
  184298. }
  184299. /* Write the new.* vector */
  184300. aOld1 = aOldRecord1;
  184301. aOld2 = aOldRecord2;
  184302. aNew1 = aNewRecord1;
  184303. aNew2 = aNewRecord2;
  184304. for(i=0; i<pTab->nCol; i++){
  184305. int nOld;
  184306. u8 *aOld;
  184307. int nNew;
  184308. u8 *aNew;
  184309. aOld = sessionMergeValue(&aOld1, &aOld2, &nOld);
  184310. aNew = sessionMergeValue(&aNew1, &aNew2, &nNew);
  184311. if( bPatchset==0
  184312. && (pTab->abPK[i] || (nOld==nNew && 0==memcmp(aOld, aNew, nNew)))
  184313. ){
  184314. *(aOut++) = '\0';
  184315. }else{
  184316. memcpy(aOut, aNew, nNew);
  184317. aOut += nNew;
  184318. }
  184319. }
  184320. *paOut = aOut;
  184321. return 1;
  184322. }
  184323. /*
  184324. ** This function is only called from within a pre-update-hook callback.
  184325. ** It determines if the current pre-update-hook change affects the same row
  184326. ** as the change stored in argument pChange. If so, it returns true. Otherwise
  184327. ** if the pre-update-hook does not affect the same row as pChange, it returns
  184328. ** false.
  184329. */
  184330. static int sessionPreupdateEqual(
  184331. sqlite3_session *pSession, /* Session object that owns SessionTable */
  184332. SessionTable *pTab, /* Table associated with change */
  184333. SessionChange *pChange, /* Change to compare to */
  184334. int op /* Current pre-update operation */
  184335. ){
  184336. int iCol; /* Used to iterate through columns */
  184337. u8 *a = pChange->aRecord; /* Cursor used to scan change record */
  184338. assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
  184339. for(iCol=0; iCol<pTab->nCol; iCol++){
  184340. if( !pTab->abPK[iCol] ){
  184341. a += sessionSerialLen(a);
  184342. }else{
  184343. sqlite3_value *pVal; /* Value returned by preupdate_new/old */
  184344. int rc; /* Error code from preupdate_new/old */
  184345. int eType = *a++; /* Type of value from change record */
  184346. /* The following calls to preupdate_new() and preupdate_old() can not
  184347. ** fail. This is because they cache their return values, and by the
  184348. ** time control flows to here they have already been called once from
  184349. ** within sessionPreupdateHash(). The first two asserts below verify
  184350. ** this (that the method has already been called). */
  184351. if( op==SQLITE_INSERT ){
  184352. /* assert( db->pPreUpdate->pNewUnpacked || db->pPreUpdate->aNew ); */
  184353. rc = pSession->hook.xNew(pSession->hook.pCtx, iCol, &pVal);
  184354. }else{
  184355. /* assert( db->pPreUpdate->pUnpacked ); */
  184356. rc = pSession->hook.xOld(pSession->hook.pCtx, iCol, &pVal);
  184357. }
  184358. assert( rc==SQLITE_OK );
  184359. if( sqlite3_value_type(pVal)!=eType ) return 0;
  184360. /* A SessionChange object never has a NULL value in a PK column */
  184361. assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT
  184362. || eType==SQLITE_BLOB || eType==SQLITE_TEXT
  184363. );
  184364. if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  184365. i64 iVal = sessionGetI64(a);
  184366. a += 8;
  184367. if( eType==SQLITE_INTEGER ){
  184368. if( sqlite3_value_int64(pVal)!=iVal ) return 0;
  184369. }else{
  184370. double rVal;
  184371. assert( sizeof(iVal)==8 && sizeof(rVal)==8 );
  184372. memcpy(&rVal, &iVal, 8);
  184373. if( sqlite3_value_double(pVal)!=rVal ) return 0;
  184374. }
  184375. }else{
  184376. int n;
  184377. const u8 *z;
  184378. a += sessionVarintGet(a, &n);
  184379. if( sqlite3_value_bytes(pVal)!=n ) return 0;
  184380. if( eType==SQLITE_TEXT ){
  184381. z = sqlite3_value_text(pVal);
  184382. }else{
  184383. z = sqlite3_value_blob(pVal);
  184384. }
  184385. if( n>0 && memcmp(a, z, n) ) return 0;
  184386. a += n;
  184387. }
  184388. }
  184389. }
  184390. return 1;
  184391. }
  184392. /*
  184393. ** If required, grow the hash table used to store changes on table pTab
  184394. ** (part of the session pSession). If a fatal OOM error occurs, set the
  184395. ** session object to failed and return SQLITE_ERROR. Otherwise, return
  184396. ** SQLITE_OK.
  184397. **
  184398. ** It is possible that a non-fatal OOM error occurs in this function. In
  184399. ** that case the hash-table does not grow, but SQLITE_OK is returned anyway.
  184400. ** Growing the hash table in this case is a performance optimization only,
  184401. ** it is not required for correct operation.
  184402. */
  184403. static int sessionGrowHash(int bPatchset, SessionTable *pTab){
  184404. if( pTab->nChange==0 || pTab->nEntry>=(pTab->nChange/2) ){
  184405. int i;
  184406. SessionChange **apNew;
  184407. sqlite3_int64 nNew = 2*(sqlite3_int64)(pTab->nChange ? pTab->nChange : 128);
  184408. apNew = (SessionChange **)sqlite3_malloc64(sizeof(SessionChange *) * nNew);
  184409. if( apNew==0 ){
  184410. if( pTab->nChange==0 ){
  184411. return SQLITE_ERROR;
  184412. }
  184413. return SQLITE_OK;
  184414. }
  184415. memset(apNew, 0, sizeof(SessionChange *) * nNew);
  184416. for(i=0; i<pTab->nChange; i++){
  184417. SessionChange *p;
  184418. SessionChange *pNext;
  184419. for(p=pTab->apChange[i]; p; p=pNext){
  184420. int bPkOnly = (p->op==SQLITE_DELETE && bPatchset);
  184421. int iHash = sessionChangeHash(pTab, bPkOnly, p->aRecord, nNew);
  184422. pNext = p->pNext;
  184423. p->pNext = apNew[iHash];
  184424. apNew[iHash] = p;
  184425. }
  184426. }
  184427. sqlite3_free(pTab->apChange);
  184428. pTab->nChange = nNew;
  184429. pTab->apChange = apNew;
  184430. }
  184431. return SQLITE_OK;
  184432. }
  184433. /*
  184434. ** This function queries the database for the names of the columns of table
  184435. ** zThis, in schema zDb.
  184436. **
  184437. ** Otherwise, if they are not NULL, variable *pnCol is set to the number
  184438. ** of columns in the database table and variable *pzTab is set to point to a
  184439. ** nul-terminated copy of the table name. *pazCol (if not NULL) is set to
  184440. ** point to an array of pointers to column names. And *pabPK (again, if not
  184441. ** NULL) is set to point to an array of booleans - true if the corresponding
  184442. ** column is part of the primary key.
  184443. **
  184444. ** For example, if the table is declared as:
  184445. **
  184446. ** CREATE TABLE tbl1(w, x, y, z, PRIMARY KEY(w, z));
  184447. **
  184448. ** Then the four output variables are populated as follows:
  184449. **
  184450. ** *pnCol = 4
  184451. ** *pzTab = "tbl1"
  184452. ** *pazCol = {"w", "x", "y", "z"}
  184453. ** *pabPK = {1, 0, 0, 1}
  184454. **
  184455. ** All returned buffers are part of the same single allocation, which must
  184456. ** be freed using sqlite3_free() by the caller
  184457. */
  184458. static int sessionTableInfo(
  184459. sqlite3 *db, /* Database connection */
  184460. const char *zDb, /* Name of attached database (e.g. "main") */
  184461. const char *zThis, /* Table name */
  184462. int *pnCol, /* OUT: number of columns */
  184463. const char **pzTab, /* OUT: Copy of zThis */
  184464. const char ***pazCol, /* OUT: Array of column names for table */
  184465. u8 **pabPK /* OUT: Array of booleans - true for PK col */
  184466. ){
  184467. char *zPragma;
  184468. sqlite3_stmt *pStmt;
  184469. int rc;
  184470. sqlite3_int64 nByte;
  184471. int nDbCol = 0;
  184472. int nThis;
  184473. int i;
  184474. u8 *pAlloc = 0;
  184475. char **azCol = 0;
  184476. u8 *abPK = 0;
  184477. assert( pazCol && pabPK );
  184478. nThis = sqlite3Strlen30(zThis);
  184479. if( nThis==12 && 0==sqlite3_stricmp("sqlite_stat1", zThis) ){
  184480. rc = sqlite3_table_column_metadata(db, zDb, zThis, 0, 0, 0, 0, 0, 0);
  184481. if( rc==SQLITE_OK ){
  184482. /* For sqlite_stat1, pretend that (tbl,idx) is the PRIMARY KEY. */
  184483. zPragma = sqlite3_mprintf(
  184484. "SELECT 0, 'tbl', '', 0, '', 1 UNION ALL "
  184485. "SELECT 1, 'idx', '', 0, '', 2 UNION ALL "
  184486. "SELECT 2, 'stat', '', 0, '', 0"
  184487. );
  184488. }else if( rc==SQLITE_ERROR ){
  184489. zPragma = sqlite3_mprintf("");
  184490. }else{
  184491. return rc;
  184492. }
  184493. }else{
  184494. zPragma = sqlite3_mprintf("PRAGMA '%q'.table_info('%q')", zDb, zThis);
  184495. }
  184496. if( !zPragma ) return SQLITE_NOMEM;
  184497. rc = sqlite3_prepare_v2(db, zPragma, -1, &pStmt, 0);
  184498. sqlite3_free(zPragma);
  184499. if( rc!=SQLITE_OK ) return rc;
  184500. nByte = nThis + 1;
  184501. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  184502. nByte += sqlite3_column_bytes(pStmt, 1);
  184503. nDbCol++;
  184504. }
  184505. rc = sqlite3_reset(pStmt);
  184506. if( rc==SQLITE_OK ){
  184507. nByte += nDbCol * (sizeof(const char *) + sizeof(u8) + 1);
  184508. pAlloc = sqlite3_malloc64(nByte);
  184509. if( pAlloc==0 ){
  184510. rc = SQLITE_NOMEM;
  184511. }
  184512. }
  184513. if( rc==SQLITE_OK ){
  184514. azCol = (char **)pAlloc;
  184515. pAlloc = (u8 *)&azCol[nDbCol];
  184516. abPK = (u8 *)pAlloc;
  184517. pAlloc = &abPK[nDbCol];
  184518. if( pzTab ){
  184519. memcpy(pAlloc, zThis, nThis+1);
  184520. *pzTab = (char *)pAlloc;
  184521. pAlloc += nThis+1;
  184522. }
  184523. i = 0;
  184524. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  184525. int nName = sqlite3_column_bytes(pStmt, 1);
  184526. const unsigned char *zName = sqlite3_column_text(pStmt, 1);
  184527. if( zName==0 ) break;
  184528. memcpy(pAlloc, zName, nName+1);
  184529. azCol[i] = (char *)pAlloc;
  184530. pAlloc += nName+1;
  184531. abPK[i] = sqlite3_column_int(pStmt, 5);
  184532. i++;
  184533. }
  184534. rc = sqlite3_reset(pStmt);
  184535. }
  184536. /* If successful, populate the output variables. Otherwise, zero them and
  184537. ** free any allocation made. An error code will be returned in this case.
  184538. */
  184539. if( rc==SQLITE_OK ){
  184540. *pazCol = (const char **)azCol;
  184541. *pabPK = abPK;
  184542. *pnCol = nDbCol;
  184543. }else{
  184544. *pazCol = 0;
  184545. *pabPK = 0;
  184546. *pnCol = 0;
  184547. if( pzTab ) *pzTab = 0;
  184548. sqlite3_free(azCol);
  184549. }
  184550. sqlite3_finalize(pStmt);
  184551. return rc;
  184552. }
  184553. /*
  184554. ** This function is only called from within a pre-update handler for a
  184555. ** write to table pTab, part of session pSession. If this is the first
  184556. ** write to this table, initalize the SessionTable.nCol, azCol[] and
  184557. ** abPK[] arrays accordingly.
  184558. **
  184559. ** If an error occurs, an error code is stored in sqlite3_session.rc and
  184560. ** non-zero returned. Or, if no error occurs but the table has no primary
  184561. ** key, sqlite3_session.rc is left set to SQLITE_OK and non-zero returned to
  184562. ** indicate that updates on this table should be ignored. SessionTable.abPK
  184563. ** is set to NULL in this case.
  184564. */
  184565. static int sessionInitTable(sqlite3_session *pSession, SessionTable *pTab){
  184566. if( pTab->nCol==0 ){
  184567. u8 *abPK;
  184568. assert( pTab->azCol==0 || pTab->abPK==0 );
  184569. pSession->rc = sessionTableInfo(pSession->db, pSession->zDb,
  184570. pTab->zName, &pTab->nCol, 0, &pTab->azCol, &abPK
  184571. );
  184572. if( pSession->rc==SQLITE_OK ){
  184573. int i;
  184574. for(i=0; i<pTab->nCol; i++){
  184575. if( abPK[i] ){
  184576. pTab->abPK = abPK;
  184577. break;
  184578. }
  184579. }
  184580. if( 0==sqlite3_stricmp("sqlite_stat1", pTab->zName) ){
  184581. pTab->bStat1 = 1;
  184582. }
  184583. }
  184584. }
  184585. return (pSession->rc || pTab->abPK==0);
  184586. }
  184587. /*
  184588. ** Versions of the four methods in object SessionHook for use with the
  184589. ** sqlite_stat1 table. The purpose of this is to substitute a zero-length
  184590. ** blob each time a NULL value is read from the "idx" column of the
  184591. ** sqlite_stat1 table.
  184592. */
  184593. typedef struct SessionStat1Ctx SessionStat1Ctx;
  184594. struct SessionStat1Ctx {
  184595. SessionHook hook;
  184596. sqlite3_session *pSession;
  184597. };
  184598. static int sessionStat1Old(void *pCtx, int iCol, sqlite3_value **ppVal){
  184599. SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx;
  184600. sqlite3_value *pVal = 0;
  184601. int rc = p->hook.xOld(p->hook.pCtx, iCol, &pVal);
  184602. if( rc==SQLITE_OK && iCol==1 && sqlite3_value_type(pVal)==SQLITE_NULL ){
  184603. pVal = p->pSession->pZeroBlob;
  184604. }
  184605. *ppVal = pVal;
  184606. return rc;
  184607. }
  184608. static int sessionStat1New(void *pCtx, int iCol, sqlite3_value **ppVal){
  184609. SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx;
  184610. sqlite3_value *pVal = 0;
  184611. int rc = p->hook.xNew(p->hook.pCtx, iCol, &pVal);
  184612. if( rc==SQLITE_OK && iCol==1 && sqlite3_value_type(pVal)==SQLITE_NULL ){
  184613. pVal = p->pSession->pZeroBlob;
  184614. }
  184615. *ppVal = pVal;
  184616. return rc;
  184617. }
  184618. static int sessionStat1Count(void *pCtx){
  184619. SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx;
  184620. return p->hook.xCount(p->hook.pCtx);
  184621. }
  184622. static int sessionStat1Depth(void *pCtx){
  184623. SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx;
  184624. return p->hook.xDepth(p->hook.pCtx);
  184625. }
  184626. /*
  184627. ** This function is only called from with a pre-update-hook reporting a
  184628. ** change on table pTab (attached to session pSession). The type of change
  184629. ** (UPDATE, INSERT, DELETE) is specified by the first argument.
  184630. **
  184631. ** Unless one is already present or an error occurs, an entry is added
  184632. ** to the changed-rows hash table associated with table pTab.
  184633. */
  184634. static void sessionPreupdateOneChange(
  184635. int op, /* One of SQLITE_UPDATE, INSERT, DELETE */
  184636. sqlite3_session *pSession, /* Session object pTab is attached to */
  184637. SessionTable *pTab /* Table that change applies to */
  184638. ){
  184639. int iHash;
  184640. int bNull = 0;
  184641. int rc = SQLITE_OK;
  184642. SessionStat1Ctx stat1 = {{0,0,0,0,0},0};
  184643. if( pSession->rc ) return;
  184644. /* Load table details if required */
  184645. if( sessionInitTable(pSession, pTab) ) return;
  184646. /* Check the number of columns in this xPreUpdate call matches the
  184647. ** number of columns in the table. */
  184648. if( pTab->nCol!=pSession->hook.xCount(pSession->hook.pCtx) ){
  184649. pSession->rc = SQLITE_SCHEMA;
  184650. return;
  184651. }
  184652. /* Grow the hash table if required */
  184653. if( sessionGrowHash(0, pTab) ){
  184654. pSession->rc = SQLITE_NOMEM;
  184655. return;
  184656. }
  184657. if( pTab->bStat1 ){
  184658. stat1.hook = pSession->hook;
  184659. stat1.pSession = pSession;
  184660. pSession->hook.pCtx = (void*)&stat1;
  184661. pSession->hook.xNew = sessionStat1New;
  184662. pSession->hook.xOld = sessionStat1Old;
  184663. pSession->hook.xCount = sessionStat1Count;
  184664. pSession->hook.xDepth = sessionStat1Depth;
  184665. if( pSession->pZeroBlob==0 ){
  184666. sqlite3_value *p = sqlite3ValueNew(0);
  184667. if( p==0 ){
  184668. rc = SQLITE_NOMEM;
  184669. goto error_out;
  184670. }
  184671. sqlite3ValueSetStr(p, 0, "", 0, SQLITE_STATIC);
  184672. pSession->pZeroBlob = p;
  184673. }
  184674. }
  184675. /* Calculate the hash-key for this change. If the primary key of the row
  184676. ** includes a NULL value, exit early. Such changes are ignored by the
  184677. ** session module. */
  184678. rc = sessionPreupdateHash(pSession, pTab, op==SQLITE_INSERT, &iHash, &bNull);
  184679. if( rc!=SQLITE_OK ) goto error_out;
  184680. if( bNull==0 ){
  184681. /* Search the hash table for an existing record for this row. */
  184682. SessionChange *pC;
  184683. for(pC=pTab->apChange[iHash]; pC; pC=pC->pNext){
  184684. if( sessionPreupdateEqual(pSession, pTab, pC, op) ) break;
  184685. }
  184686. if( pC==0 ){
  184687. /* Create a new change object containing all the old values (if
  184688. ** this is an SQLITE_UPDATE or SQLITE_DELETE), or just the PK
  184689. ** values (if this is an INSERT). */
  184690. SessionChange *pChange; /* New change object */
  184691. sqlite3_int64 nByte; /* Number of bytes to allocate */
  184692. int i; /* Used to iterate through columns */
  184693. assert( rc==SQLITE_OK );
  184694. pTab->nEntry++;
  184695. /* Figure out how large an allocation is required */
  184696. nByte = sizeof(SessionChange);
  184697. for(i=0; i<pTab->nCol; i++){
  184698. sqlite3_value *p = 0;
  184699. if( op!=SQLITE_INSERT ){
  184700. TESTONLY(int trc = ) pSession->hook.xOld(pSession->hook.pCtx, i, &p);
  184701. assert( trc==SQLITE_OK );
  184702. }else if( pTab->abPK[i] ){
  184703. TESTONLY(int trc = ) pSession->hook.xNew(pSession->hook.pCtx, i, &p);
  184704. assert( trc==SQLITE_OK );
  184705. }
  184706. /* This may fail if SQLite value p contains a utf-16 string that must
  184707. ** be converted to utf-8 and an OOM error occurs while doing so. */
  184708. rc = sessionSerializeValue(0, p, &nByte);
  184709. if( rc!=SQLITE_OK ) goto error_out;
  184710. }
  184711. /* Allocate the change object */
  184712. pChange = (SessionChange *)sqlite3_malloc64(nByte);
  184713. if( !pChange ){
  184714. rc = SQLITE_NOMEM;
  184715. goto error_out;
  184716. }else{
  184717. memset(pChange, 0, sizeof(SessionChange));
  184718. pChange->aRecord = (u8 *)&pChange[1];
  184719. }
  184720. /* Populate the change object. None of the preupdate_old(),
  184721. ** preupdate_new() or SerializeValue() calls below may fail as all
  184722. ** required values and encodings have already been cached in memory.
  184723. ** It is not possible for an OOM to occur in this block. */
  184724. nByte = 0;
  184725. for(i=0; i<pTab->nCol; i++){
  184726. sqlite3_value *p = 0;
  184727. if( op!=SQLITE_INSERT ){
  184728. pSession->hook.xOld(pSession->hook.pCtx, i, &p);
  184729. }else if( pTab->abPK[i] ){
  184730. pSession->hook.xNew(pSession->hook.pCtx, i, &p);
  184731. }
  184732. sessionSerializeValue(&pChange->aRecord[nByte], p, &nByte);
  184733. }
  184734. /* Add the change to the hash-table */
  184735. if( pSession->bIndirect || pSession->hook.xDepth(pSession->hook.pCtx) ){
  184736. pChange->bIndirect = 1;
  184737. }
  184738. pChange->nRecord = nByte;
  184739. pChange->op = op;
  184740. pChange->pNext = pTab->apChange[iHash];
  184741. pTab->apChange[iHash] = pChange;
  184742. }else if( pC->bIndirect ){
  184743. /* If the existing change is considered "indirect", but this current
  184744. ** change is "direct", mark the change object as direct. */
  184745. if( pSession->hook.xDepth(pSession->hook.pCtx)==0
  184746. && pSession->bIndirect==0
  184747. ){
  184748. pC->bIndirect = 0;
  184749. }
  184750. }
  184751. }
  184752. /* If an error has occurred, mark the session object as failed. */
  184753. error_out:
  184754. if( pTab->bStat1 ){
  184755. pSession->hook = stat1.hook;
  184756. }
  184757. if( rc!=SQLITE_OK ){
  184758. pSession->rc = rc;
  184759. }
  184760. }
  184761. static int sessionFindTable(
  184762. sqlite3_session *pSession,
  184763. const char *zName,
  184764. SessionTable **ppTab
  184765. ){
  184766. int rc = SQLITE_OK;
  184767. int nName = sqlite3Strlen30(zName);
  184768. SessionTable *pRet;
  184769. /* Search for an existing table */
  184770. for(pRet=pSession->pTable; pRet; pRet=pRet->pNext){
  184771. if( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) ) break;
  184772. }
  184773. if( pRet==0 && pSession->bAutoAttach ){
  184774. /* If there is a table-filter configured, invoke it. If it returns 0,
  184775. ** do not automatically add the new table. */
  184776. if( pSession->xTableFilter==0
  184777. || pSession->xTableFilter(pSession->pFilterCtx, zName)
  184778. ){
  184779. rc = sqlite3session_attach(pSession, zName);
  184780. if( rc==SQLITE_OK ){
  184781. for(pRet=pSession->pTable; pRet->pNext; pRet=pRet->pNext);
  184782. assert( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) );
  184783. }
  184784. }
  184785. }
  184786. assert( rc==SQLITE_OK || pRet==0 );
  184787. *ppTab = pRet;
  184788. return rc;
  184789. }
  184790. /*
  184791. ** The 'pre-update' hook registered by this module with SQLite databases.
  184792. */
  184793. static void xPreUpdate(
  184794. void *pCtx, /* Copy of third arg to preupdate_hook() */
  184795. sqlite3 *db, /* Database handle */
  184796. int op, /* SQLITE_UPDATE, DELETE or INSERT */
  184797. char const *zDb, /* Database name */
  184798. char const *zName, /* Table name */
  184799. sqlite3_int64 iKey1, /* Rowid of row about to be deleted/updated */
  184800. sqlite3_int64 iKey2 /* New rowid value (for a rowid UPDATE) */
  184801. ){
  184802. sqlite3_session *pSession;
  184803. int nDb = sqlite3Strlen30(zDb);
  184804. assert( sqlite3_mutex_held(db->mutex) );
  184805. for(pSession=(sqlite3_session *)pCtx; pSession; pSession=pSession->pNext){
  184806. SessionTable *pTab;
  184807. /* If this session is attached to a different database ("main", "temp"
  184808. ** etc.), or if it is not currently enabled, there is nothing to do. Skip
  184809. ** to the next session object attached to this database. */
  184810. if( pSession->bEnable==0 ) continue;
  184811. if( pSession->rc ) continue;
  184812. if( sqlite3_strnicmp(zDb, pSession->zDb, nDb+1) ) continue;
  184813. pSession->rc = sessionFindTable(pSession, zName, &pTab);
  184814. if( pTab ){
  184815. assert( pSession->rc==SQLITE_OK );
  184816. sessionPreupdateOneChange(op, pSession, pTab);
  184817. if( op==SQLITE_UPDATE ){
  184818. sessionPreupdateOneChange(SQLITE_INSERT, pSession, pTab);
  184819. }
  184820. }
  184821. }
  184822. }
  184823. /*
  184824. ** The pre-update hook implementations.
  184825. */
  184826. static int sessionPreupdateOld(void *pCtx, int iVal, sqlite3_value **ppVal){
  184827. return sqlite3_preupdate_old((sqlite3*)pCtx, iVal, ppVal);
  184828. }
  184829. static int sessionPreupdateNew(void *pCtx, int iVal, sqlite3_value **ppVal){
  184830. return sqlite3_preupdate_new((sqlite3*)pCtx, iVal, ppVal);
  184831. }
  184832. static int sessionPreupdateCount(void *pCtx){
  184833. return sqlite3_preupdate_count((sqlite3*)pCtx);
  184834. }
  184835. static int sessionPreupdateDepth(void *pCtx){
  184836. return sqlite3_preupdate_depth((sqlite3*)pCtx);
  184837. }
  184838. /*
  184839. ** Install the pre-update hooks on the session object passed as the only
  184840. ** argument.
  184841. */
  184842. static void sessionPreupdateHooks(
  184843. sqlite3_session *pSession
  184844. ){
  184845. pSession->hook.pCtx = (void*)pSession->db;
  184846. pSession->hook.xOld = sessionPreupdateOld;
  184847. pSession->hook.xNew = sessionPreupdateNew;
  184848. pSession->hook.xCount = sessionPreupdateCount;
  184849. pSession->hook.xDepth = sessionPreupdateDepth;
  184850. }
  184851. typedef struct SessionDiffCtx SessionDiffCtx;
  184852. struct SessionDiffCtx {
  184853. sqlite3_stmt *pStmt;
  184854. int nOldOff;
  184855. };
  184856. /*
  184857. ** The diff hook implementations.
  184858. */
  184859. static int sessionDiffOld(void *pCtx, int iVal, sqlite3_value **ppVal){
  184860. SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
  184861. *ppVal = sqlite3_column_value(p->pStmt, iVal+p->nOldOff);
  184862. return SQLITE_OK;
  184863. }
  184864. static int sessionDiffNew(void *pCtx, int iVal, sqlite3_value **ppVal){
  184865. SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
  184866. *ppVal = sqlite3_column_value(p->pStmt, iVal);
  184867. return SQLITE_OK;
  184868. }
  184869. static int sessionDiffCount(void *pCtx){
  184870. SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
  184871. return p->nOldOff ? p->nOldOff : sqlite3_column_count(p->pStmt);
  184872. }
  184873. static int sessionDiffDepth(void *pCtx){
  184874. return 0;
  184875. }
  184876. /*
  184877. ** Install the diff hooks on the session object passed as the only
  184878. ** argument.
  184879. */
  184880. static void sessionDiffHooks(
  184881. sqlite3_session *pSession,
  184882. SessionDiffCtx *pDiffCtx
  184883. ){
  184884. pSession->hook.pCtx = (void*)pDiffCtx;
  184885. pSession->hook.xOld = sessionDiffOld;
  184886. pSession->hook.xNew = sessionDiffNew;
  184887. pSession->hook.xCount = sessionDiffCount;
  184888. pSession->hook.xDepth = sessionDiffDepth;
  184889. }
  184890. static char *sessionExprComparePK(
  184891. int nCol,
  184892. const char *zDb1, const char *zDb2,
  184893. const char *zTab,
  184894. const char **azCol, u8 *abPK
  184895. ){
  184896. int i;
  184897. const char *zSep = "";
  184898. char *zRet = 0;
  184899. for(i=0; i<nCol; i++){
  184900. if( abPK[i] ){
  184901. zRet = sqlite3_mprintf("%z%s\"%w\".\"%w\".\"%w\"=\"%w\".\"%w\".\"%w\"",
  184902. zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i]
  184903. );
  184904. zSep = " AND ";
  184905. if( zRet==0 ) break;
  184906. }
  184907. }
  184908. return zRet;
  184909. }
  184910. static char *sessionExprCompareOther(
  184911. int nCol,
  184912. const char *zDb1, const char *zDb2,
  184913. const char *zTab,
  184914. const char **azCol, u8 *abPK
  184915. ){
  184916. int i;
  184917. const char *zSep = "";
  184918. char *zRet = 0;
  184919. int bHave = 0;
  184920. for(i=0; i<nCol; i++){
  184921. if( abPK[i]==0 ){
  184922. bHave = 1;
  184923. zRet = sqlite3_mprintf(
  184924. "%z%s\"%w\".\"%w\".\"%w\" IS NOT \"%w\".\"%w\".\"%w\"",
  184925. zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i]
  184926. );
  184927. zSep = " OR ";
  184928. if( zRet==0 ) break;
  184929. }
  184930. }
  184931. if( bHave==0 ){
  184932. assert( zRet==0 );
  184933. zRet = sqlite3_mprintf("0");
  184934. }
  184935. return zRet;
  184936. }
  184937. static char *sessionSelectFindNew(
  184938. int nCol,
  184939. const char *zDb1, /* Pick rows in this db only */
  184940. const char *zDb2, /* But not in this one */
  184941. const char *zTbl, /* Table name */
  184942. const char *zExpr
  184943. ){
  184944. char *zRet = sqlite3_mprintf(
  184945. "SELECT * FROM \"%w\".\"%w\" WHERE NOT EXISTS ("
  184946. " SELECT 1 FROM \"%w\".\"%w\" WHERE %s"
  184947. ")",
  184948. zDb1, zTbl, zDb2, zTbl, zExpr
  184949. );
  184950. return zRet;
  184951. }
  184952. static int sessionDiffFindNew(
  184953. int op,
  184954. sqlite3_session *pSession,
  184955. SessionTable *pTab,
  184956. const char *zDb1,
  184957. const char *zDb2,
  184958. char *zExpr
  184959. ){
  184960. int rc = SQLITE_OK;
  184961. char *zStmt = sessionSelectFindNew(pTab->nCol, zDb1, zDb2, pTab->zName,zExpr);
  184962. if( zStmt==0 ){
  184963. rc = SQLITE_NOMEM;
  184964. }else{
  184965. sqlite3_stmt *pStmt;
  184966. rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);
  184967. if( rc==SQLITE_OK ){
  184968. SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;
  184969. pDiffCtx->pStmt = pStmt;
  184970. pDiffCtx->nOldOff = 0;
  184971. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  184972. sessionPreupdateOneChange(op, pSession, pTab);
  184973. }
  184974. rc = sqlite3_finalize(pStmt);
  184975. }
  184976. sqlite3_free(zStmt);
  184977. }
  184978. return rc;
  184979. }
  184980. static int sessionDiffFindModified(
  184981. sqlite3_session *pSession,
  184982. SessionTable *pTab,
  184983. const char *zFrom,
  184984. const char *zExpr
  184985. ){
  184986. int rc = SQLITE_OK;
  184987. char *zExpr2 = sessionExprCompareOther(pTab->nCol,
  184988. pSession->zDb, zFrom, pTab->zName, pTab->azCol, pTab->abPK
  184989. );
  184990. if( zExpr2==0 ){
  184991. rc = SQLITE_NOMEM;
  184992. }else{
  184993. char *zStmt = sqlite3_mprintf(
  184994. "SELECT * FROM \"%w\".\"%w\", \"%w\".\"%w\" WHERE %s AND (%z)",
  184995. pSession->zDb, pTab->zName, zFrom, pTab->zName, zExpr, zExpr2
  184996. );
  184997. if( zStmt==0 ){
  184998. rc = SQLITE_NOMEM;
  184999. }else{
  185000. sqlite3_stmt *pStmt;
  185001. rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);
  185002. if( rc==SQLITE_OK ){
  185003. SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;
  185004. pDiffCtx->pStmt = pStmt;
  185005. pDiffCtx->nOldOff = pTab->nCol;
  185006. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  185007. sessionPreupdateOneChange(SQLITE_UPDATE, pSession, pTab);
  185008. }
  185009. rc = sqlite3_finalize(pStmt);
  185010. }
  185011. sqlite3_free(zStmt);
  185012. }
  185013. }
  185014. return rc;
  185015. }
  185016. SQLITE_API int sqlite3session_diff(
  185017. sqlite3_session *pSession,
  185018. const char *zFrom,
  185019. const char *zTbl,
  185020. char **pzErrMsg
  185021. ){
  185022. const char *zDb = pSession->zDb;
  185023. int rc = pSession->rc;
  185024. SessionDiffCtx d;
  185025. memset(&d, 0, sizeof(d));
  185026. sessionDiffHooks(pSession, &d);
  185027. sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
  185028. if( pzErrMsg ) *pzErrMsg = 0;
  185029. if( rc==SQLITE_OK ){
  185030. char *zExpr = 0;
  185031. sqlite3 *db = pSession->db;
  185032. SessionTable *pTo; /* Table zTbl */
  185033. /* Locate and if necessary initialize the target table object */
  185034. rc = sessionFindTable(pSession, zTbl, &pTo);
  185035. if( pTo==0 ) goto diff_out;
  185036. if( sessionInitTable(pSession, pTo) ){
  185037. rc = pSession->rc;
  185038. goto diff_out;
  185039. }
  185040. /* Check the table schemas match */
  185041. if( rc==SQLITE_OK ){
  185042. int bHasPk = 0;
  185043. int bMismatch = 0;
  185044. int nCol; /* Columns in zFrom.zTbl */
  185045. u8 *abPK;
  185046. const char **azCol = 0;
  185047. rc = sessionTableInfo(db, zFrom, zTbl, &nCol, 0, &azCol, &abPK);
  185048. if( rc==SQLITE_OK ){
  185049. if( pTo->nCol!=nCol ){
  185050. bMismatch = 1;
  185051. }else{
  185052. int i;
  185053. for(i=0; i<nCol; i++){
  185054. if( pTo->abPK[i]!=abPK[i] ) bMismatch = 1;
  185055. if( sqlite3_stricmp(azCol[i], pTo->azCol[i]) ) bMismatch = 1;
  185056. if( abPK[i] ) bHasPk = 1;
  185057. }
  185058. }
  185059. }
  185060. sqlite3_free((char*)azCol);
  185061. if( bMismatch ){
  185062. if( pzErrMsg ){
  185063. *pzErrMsg = sqlite3_mprintf("table schemas do not match");
  185064. }
  185065. rc = SQLITE_SCHEMA;
  185066. }
  185067. if( bHasPk==0 ){
  185068. /* Ignore tables with no primary keys */
  185069. goto diff_out;
  185070. }
  185071. }
  185072. if( rc==SQLITE_OK ){
  185073. zExpr = sessionExprComparePK(pTo->nCol,
  185074. zDb, zFrom, pTo->zName, pTo->azCol, pTo->abPK
  185075. );
  185076. }
  185077. /* Find new rows */
  185078. if( rc==SQLITE_OK ){
  185079. rc = sessionDiffFindNew(SQLITE_INSERT, pSession, pTo, zDb, zFrom, zExpr);
  185080. }
  185081. /* Find old rows */
  185082. if( rc==SQLITE_OK ){
  185083. rc = sessionDiffFindNew(SQLITE_DELETE, pSession, pTo, zFrom, zDb, zExpr);
  185084. }
  185085. /* Find modified rows */
  185086. if( rc==SQLITE_OK ){
  185087. rc = sessionDiffFindModified(pSession, pTo, zFrom, zExpr);
  185088. }
  185089. sqlite3_free(zExpr);
  185090. }
  185091. diff_out:
  185092. sessionPreupdateHooks(pSession);
  185093. sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
  185094. return rc;
  185095. }
  185096. /*
  185097. ** Create a session object. This session object will record changes to
  185098. ** database zDb attached to connection db.
  185099. */
  185100. SQLITE_API int sqlite3session_create(
  185101. sqlite3 *db, /* Database handle */
  185102. const char *zDb, /* Name of db (e.g. "main") */
  185103. sqlite3_session **ppSession /* OUT: New session object */
  185104. ){
  185105. sqlite3_session *pNew; /* Newly allocated session object */
  185106. sqlite3_session *pOld; /* Session object already attached to db */
  185107. int nDb = sqlite3Strlen30(zDb); /* Length of zDb in bytes */
  185108. /* Zero the output value in case an error occurs. */
  185109. *ppSession = 0;
  185110. /* Allocate and populate the new session object. */
  185111. pNew = (sqlite3_session *)sqlite3_malloc64(sizeof(sqlite3_session) + nDb + 1);
  185112. if( !pNew ) return SQLITE_NOMEM;
  185113. memset(pNew, 0, sizeof(sqlite3_session));
  185114. pNew->db = db;
  185115. pNew->zDb = (char *)&pNew[1];
  185116. pNew->bEnable = 1;
  185117. memcpy(pNew->zDb, zDb, nDb+1);
  185118. sessionPreupdateHooks(pNew);
  185119. /* Add the new session object to the linked list of session objects
  185120. ** attached to database handle $db. Do this under the cover of the db
  185121. ** handle mutex. */
  185122. sqlite3_mutex_enter(sqlite3_db_mutex(db));
  185123. pOld = (sqlite3_session*)sqlite3_preupdate_hook(db, xPreUpdate, (void*)pNew);
  185124. pNew->pNext = pOld;
  185125. sqlite3_mutex_leave(sqlite3_db_mutex(db));
  185126. *ppSession = pNew;
  185127. return SQLITE_OK;
  185128. }
  185129. /*
  185130. ** Free the list of table objects passed as the first argument. The contents
  185131. ** of the changed-rows hash tables are also deleted.
  185132. */
  185133. static void sessionDeleteTable(SessionTable *pList){
  185134. SessionTable *pNext;
  185135. SessionTable *pTab;
  185136. for(pTab=pList; pTab; pTab=pNext){
  185137. int i;
  185138. pNext = pTab->pNext;
  185139. for(i=0; i<pTab->nChange; i++){
  185140. SessionChange *p;
  185141. SessionChange *pNextChange;
  185142. for(p=pTab->apChange[i]; p; p=pNextChange){
  185143. pNextChange = p->pNext;
  185144. sqlite3_free(p);
  185145. }
  185146. }
  185147. sqlite3_free((char*)pTab->azCol); /* cast works around VC++ bug */
  185148. sqlite3_free(pTab->apChange);
  185149. sqlite3_free(pTab);
  185150. }
  185151. }
  185152. /*
  185153. ** Delete a session object previously allocated using sqlite3session_create().
  185154. */
  185155. SQLITE_API void sqlite3session_delete(sqlite3_session *pSession){
  185156. sqlite3 *db = pSession->db;
  185157. sqlite3_session *pHead;
  185158. sqlite3_session **pp;
  185159. /* Unlink the session from the linked list of sessions attached to the
  185160. ** database handle. Hold the db mutex while doing so. */
  185161. sqlite3_mutex_enter(sqlite3_db_mutex(db));
  185162. pHead = (sqlite3_session*)sqlite3_preupdate_hook(db, 0, 0);
  185163. for(pp=&pHead; ALWAYS((*pp)!=0); pp=&((*pp)->pNext)){
  185164. if( (*pp)==pSession ){
  185165. *pp = (*pp)->pNext;
  185166. if( pHead ) sqlite3_preupdate_hook(db, xPreUpdate, (void*)pHead);
  185167. break;
  185168. }
  185169. }
  185170. sqlite3_mutex_leave(sqlite3_db_mutex(db));
  185171. sqlite3ValueFree(pSession->pZeroBlob);
  185172. /* Delete all attached table objects. And the contents of their
  185173. ** associated hash-tables. */
  185174. sessionDeleteTable(pSession->pTable);
  185175. /* Free the session object itself. */
  185176. sqlite3_free(pSession);
  185177. }
  185178. /*
  185179. ** Set a table filter on a Session Object.
  185180. */
  185181. SQLITE_API void sqlite3session_table_filter(
  185182. sqlite3_session *pSession,
  185183. int(*xFilter)(void*, const char*),
  185184. void *pCtx /* First argument passed to xFilter */
  185185. ){
  185186. pSession->bAutoAttach = 1;
  185187. pSession->pFilterCtx = pCtx;
  185188. pSession->xTableFilter = xFilter;
  185189. }
  185190. /*
  185191. ** Attach a table to a session. All subsequent changes made to the table
  185192. ** while the session object is enabled will be recorded.
  185193. **
  185194. ** Only tables that have a PRIMARY KEY defined may be attached. It does
  185195. ** not matter if the PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias)
  185196. ** or not.
  185197. */
  185198. SQLITE_API int sqlite3session_attach(
  185199. sqlite3_session *pSession, /* Session object */
  185200. const char *zName /* Table name */
  185201. ){
  185202. int rc = SQLITE_OK;
  185203. sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
  185204. if( !zName ){
  185205. pSession->bAutoAttach = 1;
  185206. }else{
  185207. SessionTable *pTab; /* New table object (if required) */
  185208. int nName; /* Number of bytes in string zName */
  185209. /* First search for an existing entry. If one is found, this call is
  185210. ** a no-op. Return early. */
  185211. nName = sqlite3Strlen30(zName);
  185212. for(pTab=pSession->pTable; pTab; pTab=pTab->pNext){
  185213. if( 0==sqlite3_strnicmp(pTab->zName, zName, nName+1) ) break;
  185214. }
  185215. if( !pTab ){
  185216. /* Allocate new SessionTable object. */
  185217. pTab = (SessionTable *)sqlite3_malloc64(sizeof(SessionTable) + nName + 1);
  185218. if( !pTab ){
  185219. rc = SQLITE_NOMEM;
  185220. }else{
  185221. /* Populate the new SessionTable object and link it into the list.
  185222. ** The new object must be linked onto the end of the list, not
  185223. ** simply added to the start of it in order to ensure that tables
  185224. ** appear in the correct order when a changeset or patchset is
  185225. ** eventually generated. */
  185226. SessionTable **ppTab;
  185227. memset(pTab, 0, sizeof(SessionTable));
  185228. pTab->zName = (char *)&pTab[1];
  185229. memcpy(pTab->zName, zName, nName+1);
  185230. for(ppTab=&pSession->pTable; *ppTab; ppTab=&(*ppTab)->pNext);
  185231. *ppTab = pTab;
  185232. }
  185233. }
  185234. }
  185235. sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
  185236. return rc;
  185237. }
  185238. /*
  185239. ** Ensure that there is room in the buffer to append nByte bytes of data.
  185240. ** If not, use sqlite3_realloc() to grow the buffer so that there is.
  185241. **
  185242. ** If successful, return zero. Otherwise, if an OOM condition is encountered,
  185243. ** set *pRc to SQLITE_NOMEM and return non-zero.
  185244. */
  185245. static int sessionBufferGrow(SessionBuffer *p, size_t nByte, int *pRc){
  185246. if( *pRc==SQLITE_OK && (size_t)(p->nAlloc-p->nBuf)<nByte ){
  185247. u8 *aNew;
  185248. i64 nNew = p->nAlloc ? p->nAlloc : 128;
  185249. do {
  185250. nNew = nNew*2;
  185251. }while( (nNew-p->nBuf)<nByte );
  185252. aNew = (u8 *)sqlite3_realloc64(p->aBuf, nNew);
  185253. if( 0==aNew ){
  185254. *pRc = SQLITE_NOMEM;
  185255. }else{
  185256. p->aBuf = aNew;
  185257. p->nAlloc = nNew;
  185258. }
  185259. }
  185260. return (*pRc!=SQLITE_OK);
  185261. }
  185262. /*
  185263. ** Append the value passed as the second argument to the buffer passed
  185264. ** as the first.
  185265. **
  185266. ** This function is a no-op if *pRc is non-zero when it is called.
  185267. ** Otherwise, if an error occurs, *pRc is set to an SQLite error code
  185268. ** before returning.
  185269. */
  185270. static void sessionAppendValue(SessionBuffer *p, sqlite3_value *pVal, int *pRc){
  185271. int rc = *pRc;
  185272. if( rc==SQLITE_OK ){
  185273. sqlite3_int64 nByte = 0;
  185274. rc = sessionSerializeValue(0, pVal, &nByte);
  185275. sessionBufferGrow(p, nByte, &rc);
  185276. if( rc==SQLITE_OK ){
  185277. rc = sessionSerializeValue(&p->aBuf[p->nBuf], pVal, 0);
  185278. p->nBuf += nByte;
  185279. }else{
  185280. *pRc = rc;
  185281. }
  185282. }
  185283. }
  185284. /*
  185285. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  185286. ** called. Otherwise, append a single byte to the buffer.
  185287. **
  185288. ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
  185289. ** returning.
  185290. */
  185291. static void sessionAppendByte(SessionBuffer *p, u8 v, int *pRc){
  185292. if( 0==sessionBufferGrow(p, 1, pRc) ){
  185293. p->aBuf[p->nBuf++] = v;
  185294. }
  185295. }
  185296. /*
  185297. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  185298. ** called. Otherwise, append a single varint to the buffer.
  185299. **
  185300. ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
  185301. ** returning.
  185302. */
  185303. static void sessionAppendVarint(SessionBuffer *p, int v, int *pRc){
  185304. if( 0==sessionBufferGrow(p, 9, pRc) ){
  185305. p->nBuf += sessionVarintPut(&p->aBuf[p->nBuf], v);
  185306. }
  185307. }
  185308. /*
  185309. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  185310. ** called. Otherwise, append a blob of data to the buffer.
  185311. **
  185312. ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
  185313. ** returning.
  185314. */
  185315. static void sessionAppendBlob(
  185316. SessionBuffer *p,
  185317. const u8 *aBlob,
  185318. int nBlob,
  185319. int *pRc
  185320. ){
  185321. if( nBlob>0 && 0==sessionBufferGrow(p, nBlob, pRc) ){
  185322. memcpy(&p->aBuf[p->nBuf], aBlob, nBlob);
  185323. p->nBuf += nBlob;
  185324. }
  185325. }
  185326. /*
  185327. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  185328. ** called. Otherwise, append a string to the buffer. All bytes in the string
  185329. ** up to (but not including) the nul-terminator are written to the buffer.
  185330. **
  185331. ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
  185332. ** returning.
  185333. */
  185334. static void sessionAppendStr(
  185335. SessionBuffer *p,
  185336. const char *zStr,
  185337. int *pRc
  185338. ){
  185339. int nStr = sqlite3Strlen30(zStr);
  185340. if( 0==sessionBufferGrow(p, nStr, pRc) ){
  185341. memcpy(&p->aBuf[p->nBuf], zStr, nStr);
  185342. p->nBuf += nStr;
  185343. }
  185344. }
  185345. /*
  185346. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  185347. ** called. Otherwise, append the string representation of integer iVal
  185348. ** to the buffer. No nul-terminator is written.
  185349. **
  185350. ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
  185351. ** returning.
  185352. */
  185353. static void sessionAppendInteger(
  185354. SessionBuffer *p, /* Buffer to append to */
  185355. int iVal, /* Value to write the string rep. of */
  185356. int *pRc /* IN/OUT: Error code */
  185357. ){
  185358. char aBuf[24];
  185359. sqlite3_snprintf(sizeof(aBuf)-1, aBuf, "%d", iVal);
  185360. sessionAppendStr(p, aBuf, pRc);
  185361. }
  185362. /*
  185363. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  185364. ** called. Otherwise, append the string zStr enclosed in quotes (") and
  185365. ** with any embedded quote characters escaped to the buffer. No
  185366. ** nul-terminator byte is written.
  185367. **
  185368. ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
  185369. ** returning.
  185370. */
  185371. static void sessionAppendIdent(
  185372. SessionBuffer *p, /* Buffer to a append to */
  185373. const char *zStr, /* String to quote, escape and append */
  185374. int *pRc /* IN/OUT: Error code */
  185375. ){
  185376. int nStr = sqlite3Strlen30(zStr)*2 + 2 + 1;
  185377. if( 0==sessionBufferGrow(p, nStr, pRc) ){
  185378. char *zOut = (char *)&p->aBuf[p->nBuf];
  185379. const char *zIn = zStr;
  185380. *zOut++ = '"';
  185381. while( *zIn ){
  185382. if( *zIn=='"' ) *zOut++ = '"';
  185383. *zOut++ = *(zIn++);
  185384. }
  185385. *zOut++ = '"';
  185386. p->nBuf = (int)((u8 *)zOut - p->aBuf);
  185387. }
  185388. }
  185389. /*
  185390. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  185391. ** called. Otherwse, it appends the serialized version of the value stored
  185392. ** in column iCol of the row that SQL statement pStmt currently points
  185393. ** to to the buffer.
  185394. */
  185395. static void sessionAppendCol(
  185396. SessionBuffer *p, /* Buffer to append to */
  185397. sqlite3_stmt *pStmt, /* Handle pointing to row containing value */
  185398. int iCol, /* Column to read value from */
  185399. int *pRc /* IN/OUT: Error code */
  185400. ){
  185401. if( *pRc==SQLITE_OK ){
  185402. int eType = sqlite3_column_type(pStmt, iCol);
  185403. sessionAppendByte(p, (u8)eType, pRc);
  185404. if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  185405. sqlite3_int64 i;
  185406. u8 aBuf[8];
  185407. if( eType==SQLITE_INTEGER ){
  185408. i = sqlite3_column_int64(pStmt, iCol);
  185409. }else{
  185410. double r = sqlite3_column_double(pStmt, iCol);
  185411. memcpy(&i, &r, 8);
  185412. }
  185413. sessionPutI64(aBuf, i);
  185414. sessionAppendBlob(p, aBuf, 8, pRc);
  185415. }
  185416. if( eType==SQLITE_BLOB || eType==SQLITE_TEXT ){
  185417. u8 *z;
  185418. int nByte;
  185419. if( eType==SQLITE_BLOB ){
  185420. z = (u8 *)sqlite3_column_blob(pStmt, iCol);
  185421. }else{
  185422. z = (u8 *)sqlite3_column_text(pStmt, iCol);
  185423. }
  185424. nByte = sqlite3_column_bytes(pStmt, iCol);
  185425. if( z || (eType==SQLITE_BLOB && nByte==0) ){
  185426. sessionAppendVarint(p, nByte, pRc);
  185427. sessionAppendBlob(p, z, nByte, pRc);
  185428. }else{
  185429. *pRc = SQLITE_NOMEM;
  185430. }
  185431. }
  185432. }
  185433. }
  185434. /*
  185435. **
  185436. ** This function appends an update change to the buffer (see the comments
  185437. ** under "CHANGESET FORMAT" at the top of the file). An update change
  185438. ** consists of:
  185439. **
  185440. ** 1 byte: SQLITE_UPDATE (0x17)
  185441. ** n bytes: old.* record (see RECORD FORMAT)
  185442. ** m bytes: new.* record (see RECORD FORMAT)
  185443. **
  185444. ** The SessionChange object passed as the third argument contains the
  185445. ** values that were stored in the row when the session began (the old.*
  185446. ** values). The statement handle passed as the second argument points
  185447. ** at the current version of the row (the new.* values).
  185448. **
  185449. ** If all of the old.* values are equal to their corresponding new.* value
  185450. ** (i.e. nothing has changed), then no data at all is appended to the buffer.
  185451. **
  185452. ** Otherwise, the old.* record contains all primary key values and the
  185453. ** original values of any fields that have been modified. The new.* record
  185454. ** contains the new values of only those fields that have been modified.
  185455. */
  185456. static int sessionAppendUpdate(
  185457. SessionBuffer *pBuf, /* Buffer to append to */
  185458. int bPatchset, /* True for "patchset", 0 for "changeset" */
  185459. sqlite3_stmt *pStmt, /* Statement handle pointing at new row */
  185460. SessionChange *p, /* Object containing old values */
  185461. u8 *abPK /* Boolean array - true for PK columns */
  185462. ){
  185463. int rc = SQLITE_OK;
  185464. SessionBuffer buf2 = {0,0,0}; /* Buffer to accumulate new.* record in */
  185465. int bNoop = 1; /* Set to zero if any values are modified */
  185466. int nRewind = pBuf->nBuf; /* Set to zero if any values are modified */
  185467. int i; /* Used to iterate through columns */
  185468. u8 *pCsr = p->aRecord; /* Used to iterate through old.* values */
  185469. sessionAppendByte(pBuf, SQLITE_UPDATE, &rc);
  185470. sessionAppendByte(pBuf, p->bIndirect, &rc);
  185471. for(i=0; i<sqlite3_column_count(pStmt); i++){
  185472. int bChanged = 0;
  185473. int nAdvance;
  185474. int eType = *pCsr;
  185475. switch( eType ){
  185476. case SQLITE_NULL:
  185477. nAdvance = 1;
  185478. if( sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
  185479. bChanged = 1;
  185480. }
  185481. break;
  185482. case SQLITE_FLOAT:
  185483. case SQLITE_INTEGER: {
  185484. nAdvance = 9;
  185485. if( eType==sqlite3_column_type(pStmt, i) ){
  185486. sqlite3_int64 iVal = sessionGetI64(&pCsr[1]);
  185487. if( eType==SQLITE_INTEGER ){
  185488. if( iVal==sqlite3_column_int64(pStmt, i) ) break;
  185489. }else{
  185490. double dVal;
  185491. memcpy(&dVal, &iVal, 8);
  185492. if( dVal==sqlite3_column_double(pStmt, i) ) break;
  185493. }
  185494. }
  185495. bChanged = 1;
  185496. break;
  185497. }
  185498. default: {
  185499. int n;
  185500. int nHdr = 1 + sessionVarintGet(&pCsr[1], &n);
  185501. assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
  185502. nAdvance = nHdr + n;
  185503. if( eType==sqlite3_column_type(pStmt, i)
  185504. && n==sqlite3_column_bytes(pStmt, i)
  185505. && (n==0 || 0==memcmp(&pCsr[nHdr], sqlite3_column_blob(pStmt, i), n))
  185506. ){
  185507. break;
  185508. }
  185509. bChanged = 1;
  185510. }
  185511. }
  185512. /* If at least one field has been modified, this is not a no-op. */
  185513. if( bChanged ) bNoop = 0;
  185514. /* Add a field to the old.* record. This is omitted if this modules is
  185515. ** currently generating a patchset. */
  185516. if( bPatchset==0 ){
  185517. if( bChanged || abPK[i] ){
  185518. sessionAppendBlob(pBuf, pCsr, nAdvance, &rc);
  185519. }else{
  185520. sessionAppendByte(pBuf, 0, &rc);
  185521. }
  185522. }
  185523. /* Add a field to the new.* record. Or the only record if currently
  185524. ** generating a patchset. */
  185525. if( bChanged || (bPatchset && abPK[i]) ){
  185526. sessionAppendCol(&buf2, pStmt, i, &rc);
  185527. }else{
  185528. sessionAppendByte(&buf2, 0, &rc);
  185529. }
  185530. pCsr += nAdvance;
  185531. }
  185532. if( bNoop ){
  185533. pBuf->nBuf = nRewind;
  185534. }else{
  185535. sessionAppendBlob(pBuf, buf2.aBuf, buf2.nBuf, &rc);
  185536. }
  185537. sqlite3_free(buf2.aBuf);
  185538. return rc;
  185539. }
  185540. /*
  185541. ** Append a DELETE change to the buffer passed as the first argument. Use
  185542. ** the changeset format if argument bPatchset is zero, or the patchset
  185543. ** format otherwise.
  185544. */
  185545. static int sessionAppendDelete(
  185546. SessionBuffer *pBuf, /* Buffer to append to */
  185547. int bPatchset, /* True for "patchset", 0 for "changeset" */
  185548. SessionChange *p, /* Object containing old values */
  185549. int nCol, /* Number of columns in table */
  185550. u8 *abPK /* Boolean array - true for PK columns */
  185551. ){
  185552. int rc = SQLITE_OK;
  185553. sessionAppendByte(pBuf, SQLITE_DELETE, &rc);
  185554. sessionAppendByte(pBuf, p->bIndirect, &rc);
  185555. if( bPatchset==0 ){
  185556. sessionAppendBlob(pBuf, p->aRecord, p->nRecord, &rc);
  185557. }else{
  185558. int i;
  185559. u8 *a = p->aRecord;
  185560. for(i=0; i<nCol; i++){
  185561. u8 *pStart = a;
  185562. int eType = *a++;
  185563. switch( eType ){
  185564. case 0:
  185565. case SQLITE_NULL:
  185566. assert( abPK[i]==0 );
  185567. break;
  185568. case SQLITE_FLOAT:
  185569. case SQLITE_INTEGER:
  185570. a += 8;
  185571. break;
  185572. default: {
  185573. int n;
  185574. a += sessionVarintGet(a, &n);
  185575. a += n;
  185576. break;
  185577. }
  185578. }
  185579. if( abPK[i] ){
  185580. sessionAppendBlob(pBuf, pStart, (int)(a-pStart), &rc);
  185581. }
  185582. }
  185583. assert( (a - p->aRecord)==p->nRecord );
  185584. }
  185585. return rc;
  185586. }
  185587. /*
  185588. ** Formulate and prepare a SELECT statement to retrieve a row from table
  185589. ** zTab in database zDb based on its primary key. i.e.
  185590. **
  185591. ** SELECT * FROM zDb.zTab WHERE pk1 = ? AND pk2 = ? AND ...
  185592. */
  185593. static int sessionSelectStmt(
  185594. sqlite3 *db, /* Database handle */
  185595. const char *zDb, /* Database name */
  185596. const char *zTab, /* Table name */
  185597. int nCol, /* Number of columns in table */
  185598. const char **azCol, /* Names of table columns */
  185599. u8 *abPK, /* PRIMARY KEY array */
  185600. sqlite3_stmt **ppStmt /* OUT: Prepared SELECT statement */
  185601. ){
  185602. int rc = SQLITE_OK;
  185603. char *zSql = 0;
  185604. int nSql = -1;
  185605. if( 0==sqlite3_stricmp("sqlite_stat1", zTab) ){
  185606. zSql = sqlite3_mprintf(
  185607. "SELECT tbl, ?2, stat FROM %Q.sqlite_stat1 WHERE tbl IS ?1 AND "
  185608. "idx IS (CASE WHEN ?2=X'' THEN NULL ELSE ?2 END)", zDb
  185609. );
  185610. if( zSql==0 ) rc = SQLITE_NOMEM;
  185611. }else{
  185612. int i;
  185613. const char *zSep = "";
  185614. SessionBuffer buf = {0, 0, 0};
  185615. sessionAppendStr(&buf, "SELECT * FROM ", &rc);
  185616. sessionAppendIdent(&buf, zDb, &rc);
  185617. sessionAppendStr(&buf, ".", &rc);
  185618. sessionAppendIdent(&buf, zTab, &rc);
  185619. sessionAppendStr(&buf, " WHERE ", &rc);
  185620. for(i=0; i<nCol; i++){
  185621. if( abPK[i] ){
  185622. sessionAppendStr(&buf, zSep, &rc);
  185623. sessionAppendIdent(&buf, azCol[i], &rc);
  185624. sessionAppendStr(&buf, " IS ?", &rc);
  185625. sessionAppendInteger(&buf, i+1, &rc);
  185626. zSep = " AND ";
  185627. }
  185628. }
  185629. zSql = (char*)buf.aBuf;
  185630. nSql = buf.nBuf;
  185631. }
  185632. if( rc==SQLITE_OK ){
  185633. rc = sqlite3_prepare_v2(db, zSql, nSql, ppStmt, 0);
  185634. }
  185635. sqlite3_free(zSql);
  185636. return rc;
  185637. }
  185638. /*
  185639. ** Bind the PRIMARY KEY values from the change passed in argument pChange
  185640. ** to the SELECT statement passed as the first argument. The SELECT statement
  185641. ** is as prepared by function sessionSelectStmt().
  185642. **
  185643. ** Return SQLITE_OK if all PK values are successfully bound, or an SQLite
  185644. ** error code (e.g. SQLITE_NOMEM) otherwise.
  185645. */
  185646. static int sessionSelectBind(
  185647. sqlite3_stmt *pSelect, /* SELECT from sessionSelectStmt() */
  185648. int nCol, /* Number of columns in table */
  185649. u8 *abPK, /* PRIMARY KEY array */
  185650. SessionChange *pChange /* Change structure */
  185651. ){
  185652. int i;
  185653. int rc = SQLITE_OK;
  185654. u8 *a = pChange->aRecord;
  185655. for(i=0; i<nCol && rc==SQLITE_OK; i++){
  185656. int eType = *a++;
  185657. switch( eType ){
  185658. case 0:
  185659. case SQLITE_NULL:
  185660. assert( abPK[i]==0 );
  185661. break;
  185662. case SQLITE_INTEGER: {
  185663. if( abPK[i] ){
  185664. i64 iVal = sessionGetI64(a);
  185665. rc = sqlite3_bind_int64(pSelect, i+1, iVal);
  185666. }
  185667. a += 8;
  185668. break;
  185669. }
  185670. case SQLITE_FLOAT: {
  185671. if( abPK[i] ){
  185672. double rVal;
  185673. i64 iVal = sessionGetI64(a);
  185674. memcpy(&rVal, &iVal, 8);
  185675. rc = sqlite3_bind_double(pSelect, i+1, rVal);
  185676. }
  185677. a += 8;
  185678. break;
  185679. }
  185680. case SQLITE_TEXT: {
  185681. int n;
  185682. a += sessionVarintGet(a, &n);
  185683. if( abPK[i] ){
  185684. rc = sqlite3_bind_text(pSelect, i+1, (char *)a, n, SQLITE_TRANSIENT);
  185685. }
  185686. a += n;
  185687. break;
  185688. }
  185689. default: {
  185690. int n;
  185691. assert( eType==SQLITE_BLOB );
  185692. a += sessionVarintGet(a, &n);
  185693. if( abPK[i] ){
  185694. rc = sqlite3_bind_blob(pSelect, i+1, a, n, SQLITE_TRANSIENT);
  185695. }
  185696. a += n;
  185697. break;
  185698. }
  185699. }
  185700. }
  185701. return rc;
  185702. }
  185703. /*
  185704. ** This function is a no-op if *pRc is set to other than SQLITE_OK when it
  185705. ** is called. Otherwise, append a serialized table header (part of the binary
  185706. ** changeset format) to buffer *pBuf. If an error occurs, set *pRc to an
  185707. ** SQLite error code before returning.
  185708. */
  185709. static void sessionAppendTableHdr(
  185710. SessionBuffer *pBuf, /* Append header to this buffer */
  185711. int bPatchset, /* Use the patchset format if true */
  185712. SessionTable *pTab, /* Table object to append header for */
  185713. int *pRc /* IN/OUT: Error code */
  185714. ){
  185715. /* Write a table header */
  185716. sessionAppendByte(pBuf, (bPatchset ? 'P' : 'T'), pRc);
  185717. sessionAppendVarint(pBuf, pTab->nCol, pRc);
  185718. sessionAppendBlob(pBuf, pTab->abPK, pTab->nCol, pRc);
  185719. sessionAppendBlob(pBuf, (u8 *)pTab->zName, (int)strlen(pTab->zName)+1, pRc);
  185720. }
  185721. /*
  185722. ** Generate either a changeset (if argument bPatchset is zero) or a patchset
  185723. ** (if it is non-zero) based on the current contents of the session object
  185724. ** passed as the first argument.
  185725. **
  185726. ** If no error occurs, SQLITE_OK is returned and the new changeset/patchset
  185727. ** stored in output variables *pnChangeset and *ppChangeset. Or, if an error
  185728. ** occurs, an SQLite error code is returned and both output variables set
  185729. ** to 0.
  185730. */
  185731. static int sessionGenerateChangeset(
  185732. sqlite3_session *pSession, /* Session object */
  185733. int bPatchset, /* True for patchset, false for changeset */
  185734. int (*xOutput)(void *pOut, const void *pData, int nData),
  185735. void *pOut, /* First argument for xOutput */
  185736. int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */
  185737. void **ppChangeset /* OUT: Buffer containing changeset */
  185738. ){
  185739. sqlite3 *db = pSession->db; /* Source database handle */
  185740. SessionTable *pTab; /* Used to iterate through attached tables */
  185741. SessionBuffer buf = {0,0,0}; /* Buffer in which to accumlate changeset */
  185742. int rc; /* Return code */
  185743. assert( xOutput==0 || (pnChangeset==0 && ppChangeset==0 ) );
  185744. /* Zero the output variables in case an error occurs. If this session
  185745. ** object is already in the error state (sqlite3_session.rc != SQLITE_OK),
  185746. ** this call will be a no-op. */
  185747. if( xOutput==0 ){
  185748. *pnChangeset = 0;
  185749. *ppChangeset = 0;
  185750. }
  185751. if( pSession->rc ) return pSession->rc;
  185752. rc = sqlite3_exec(pSession->db, "SAVEPOINT changeset", 0, 0, 0);
  185753. if( rc!=SQLITE_OK ) return rc;
  185754. sqlite3_mutex_enter(sqlite3_db_mutex(db));
  185755. for(pTab=pSession->pTable; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
  185756. if( pTab->nEntry ){
  185757. const char *zName = pTab->zName;
  185758. int nCol; /* Number of columns in table */
  185759. u8 *abPK; /* Primary key array */
  185760. const char **azCol = 0; /* Table columns */
  185761. int i; /* Used to iterate through hash buckets */
  185762. sqlite3_stmt *pSel = 0; /* SELECT statement to query table pTab */
  185763. int nRewind = buf.nBuf; /* Initial size of write buffer */
  185764. int nNoop; /* Size of buffer after writing tbl header */
  185765. /* Check the table schema is still Ok. */
  185766. rc = sessionTableInfo(db, pSession->zDb, zName, &nCol, 0, &azCol, &abPK);
  185767. if( !rc && (pTab->nCol!=nCol || memcmp(abPK, pTab->abPK, nCol)) ){
  185768. rc = SQLITE_SCHEMA;
  185769. }
  185770. /* Write a table header */
  185771. sessionAppendTableHdr(&buf, bPatchset, pTab, &rc);
  185772. /* Build and compile a statement to execute: */
  185773. if( rc==SQLITE_OK ){
  185774. rc = sessionSelectStmt(
  185775. db, pSession->zDb, zName, nCol, azCol, abPK, &pSel);
  185776. }
  185777. nNoop = buf.nBuf;
  185778. for(i=0; i<pTab->nChange && rc==SQLITE_OK; i++){
  185779. SessionChange *p; /* Used to iterate through changes */
  185780. for(p=pTab->apChange[i]; rc==SQLITE_OK && p; p=p->pNext){
  185781. rc = sessionSelectBind(pSel, nCol, abPK, p);
  185782. if( rc!=SQLITE_OK ) continue;
  185783. if( sqlite3_step(pSel)==SQLITE_ROW ){
  185784. if( p->op==SQLITE_INSERT ){
  185785. int iCol;
  185786. sessionAppendByte(&buf, SQLITE_INSERT, &rc);
  185787. sessionAppendByte(&buf, p->bIndirect, &rc);
  185788. for(iCol=0; iCol<nCol; iCol++){
  185789. sessionAppendCol(&buf, pSel, iCol, &rc);
  185790. }
  185791. }else{
  185792. rc = sessionAppendUpdate(&buf, bPatchset, pSel, p, abPK);
  185793. }
  185794. }else if( p->op!=SQLITE_INSERT ){
  185795. rc = sessionAppendDelete(&buf, bPatchset, p, nCol, abPK);
  185796. }
  185797. if( rc==SQLITE_OK ){
  185798. rc = sqlite3_reset(pSel);
  185799. }
  185800. /* If the buffer is now larger than sessions_strm_chunk_size, pass
  185801. ** its contents to the xOutput() callback. */
  185802. if( xOutput
  185803. && rc==SQLITE_OK
  185804. && buf.nBuf>nNoop
  185805. && buf.nBuf>sessions_strm_chunk_size
  185806. ){
  185807. rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf);
  185808. nNoop = -1;
  185809. buf.nBuf = 0;
  185810. }
  185811. }
  185812. }
  185813. sqlite3_finalize(pSel);
  185814. if( buf.nBuf==nNoop ){
  185815. buf.nBuf = nRewind;
  185816. }
  185817. sqlite3_free((char*)azCol); /* cast works around VC++ bug */
  185818. }
  185819. }
  185820. if( rc==SQLITE_OK ){
  185821. if( xOutput==0 ){
  185822. *pnChangeset = buf.nBuf;
  185823. *ppChangeset = buf.aBuf;
  185824. buf.aBuf = 0;
  185825. }else if( buf.nBuf>0 ){
  185826. rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf);
  185827. }
  185828. }
  185829. sqlite3_free(buf.aBuf);
  185830. sqlite3_exec(db, "RELEASE changeset", 0, 0, 0);
  185831. sqlite3_mutex_leave(sqlite3_db_mutex(db));
  185832. return rc;
  185833. }
  185834. /*
  185835. ** Obtain a changeset object containing all changes recorded by the
  185836. ** session object passed as the first argument.
  185837. **
  185838. ** It is the responsibility of the caller to eventually free the buffer
  185839. ** using sqlite3_free().
  185840. */
  185841. SQLITE_API int sqlite3session_changeset(
  185842. sqlite3_session *pSession, /* Session object */
  185843. int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */
  185844. void **ppChangeset /* OUT: Buffer containing changeset */
  185845. ){
  185846. return sessionGenerateChangeset(pSession, 0, 0, 0, pnChangeset, ppChangeset);
  185847. }
  185848. /*
  185849. ** Streaming version of sqlite3session_changeset().
  185850. */
  185851. SQLITE_API int sqlite3session_changeset_strm(
  185852. sqlite3_session *pSession,
  185853. int (*xOutput)(void *pOut, const void *pData, int nData),
  185854. void *pOut
  185855. ){
  185856. return sessionGenerateChangeset(pSession, 0, xOutput, pOut, 0, 0);
  185857. }
  185858. /*
  185859. ** Streaming version of sqlite3session_patchset().
  185860. */
  185861. SQLITE_API int sqlite3session_patchset_strm(
  185862. sqlite3_session *pSession,
  185863. int (*xOutput)(void *pOut, const void *pData, int nData),
  185864. void *pOut
  185865. ){
  185866. return sessionGenerateChangeset(pSession, 1, xOutput, pOut, 0, 0);
  185867. }
  185868. /*
  185869. ** Obtain a patchset object containing all changes recorded by the
  185870. ** session object passed as the first argument.
  185871. **
  185872. ** It is the responsibility of the caller to eventually free the buffer
  185873. ** using sqlite3_free().
  185874. */
  185875. SQLITE_API int sqlite3session_patchset(
  185876. sqlite3_session *pSession, /* Session object */
  185877. int *pnPatchset, /* OUT: Size of buffer at *ppChangeset */
  185878. void **ppPatchset /* OUT: Buffer containing changeset */
  185879. ){
  185880. return sessionGenerateChangeset(pSession, 1, 0, 0, pnPatchset, ppPatchset);
  185881. }
  185882. /*
  185883. ** Enable or disable the session object passed as the first argument.
  185884. */
  185885. SQLITE_API int sqlite3session_enable(sqlite3_session *pSession, int bEnable){
  185886. int ret;
  185887. sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
  185888. if( bEnable>=0 ){
  185889. pSession->bEnable = bEnable;
  185890. }
  185891. ret = pSession->bEnable;
  185892. sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
  185893. return ret;
  185894. }
  185895. /*
  185896. ** Enable or disable the session object passed as the first argument.
  185897. */
  185898. SQLITE_API int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect){
  185899. int ret;
  185900. sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
  185901. if( bIndirect>=0 ){
  185902. pSession->bIndirect = bIndirect;
  185903. }
  185904. ret = pSession->bIndirect;
  185905. sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
  185906. return ret;
  185907. }
  185908. /*
  185909. ** Return true if there have been no changes to monitored tables recorded
  185910. ** by the session object passed as the only argument.
  185911. */
  185912. SQLITE_API int sqlite3session_isempty(sqlite3_session *pSession){
  185913. int ret = 0;
  185914. SessionTable *pTab;
  185915. sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
  185916. for(pTab=pSession->pTable; pTab && ret==0; pTab=pTab->pNext){
  185917. ret = (pTab->nEntry>0);
  185918. }
  185919. sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
  185920. return (ret==0);
  185921. }
  185922. /*
  185923. ** Do the work for either sqlite3changeset_start() or start_strm().
  185924. */
  185925. static int sessionChangesetStart(
  185926. sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
  185927. int (*xInput)(void *pIn, void *pData, int *pnData),
  185928. void *pIn,
  185929. int nChangeset, /* Size of buffer pChangeset in bytes */
  185930. void *pChangeset, /* Pointer to buffer containing changeset */
  185931. int bInvert /* True to invert changeset */
  185932. ){
  185933. sqlite3_changeset_iter *pRet; /* Iterator to return */
  185934. int nByte; /* Number of bytes to allocate for iterator */
  185935. assert( xInput==0 || (pChangeset==0 && nChangeset==0) );
  185936. /* Zero the output variable in case an error occurs. */
  185937. *pp = 0;
  185938. /* Allocate and initialize the iterator structure. */
  185939. nByte = sizeof(sqlite3_changeset_iter);
  185940. pRet = (sqlite3_changeset_iter *)sqlite3_malloc(nByte);
  185941. if( !pRet ) return SQLITE_NOMEM;
  185942. memset(pRet, 0, sizeof(sqlite3_changeset_iter));
  185943. pRet->in.aData = (u8 *)pChangeset;
  185944. pRet->in.nData = nChangeset;
  185945. pRet->in.xInput = xInput;
  185946. pRet->in.pIn = pIn;
  185947. pRet->in.bEof = (xInput ? 0 : 1);
  185948. pRet->bInvert = bInvert;
  185949. /* Populate the output variable and return success. */
  185950. *pp = pRet;
  185951. return SQLITE_OK;
  185952. }
  185953. /*
  185954. ** Create an iterator used to iterate through the contents of a changeset.
  185955. */
  185956. SQLITE_API int sqlite3changeset_start(
  185957. sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
  185958. int nChangeset, /* Size of buffer pChangeset in bytes */
  185959. void *pChangeset /* Pointer to buffer containing changeset */
  185960. ){
  185961. return sessionChangesetStart(pp, 0, 0, nChangeset, pChangeset, 0);
  185962. }
  185963. SQLITE_API int sqlite3changeset_start_v2(
  185964. sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
  185965. int nChangeset, /* Size of buffer pChangeset in bytes */
  185966. void *pChangeset, /* Pointer to buffer containing changeset */
  185967. int flags
  185968. ){
  185969. int bInvert = !!(flags & SQLITE_CHANGESETSTART_INVERT);
  185970. return sessionChangesetStart(pp, 0, 0, nChangeset, pChangeset, bInvert);
  185971. }
  185972. /*
  185973. ** Streaming version of sqlite3changeset_start().
  185974. */
  185975. SQLITE_API int sqlite3changeset_start_strm(
  185976. sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
  185977. int (*xInput)(void *pIn, void *pData, int *pnData),
  185978. void *pIn
  185979. ){
  185980. return sessionChangesetStart(pp, xInput, pIn, 0, 0, 0);
  185981. }
  185982. SQLITE_API int sqlite3changeset_start_v2_strm(
  185983. sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
  185984. int (*xInput)(void *pIn, void *pData, int *pnData),
  185985. void *pIn,
  185986. int flags
  185987. ){
  185988. int bInvert = !!(flags & SQLITE_CHANGESETSTART_INVERT);
  185989. return sessionChangesetStart(pp, xInput, pIn, 0, 0, bInvert);
  185990. }
  185991. /*
  185992. ** If the SessionInput object passed as the only argument is a streaming
  185993. ** object and the buffer is full, discard some data to free up space.
  185994. */
  185995. static void sessionDiscardData(SessionInput *pIn){
  185996. if( pIn->xInput && pIn->iNext>=sessions_strm_chunk_size ){
  185997. int nMove = pIn->buf.nBuf - pIn->iNext;
  185998. assert( nMove>=0 );
  185999. if( nMove>0 ){
  186000. memmove(pIn->buf.aBuf, &pIn->buf.aBuf[pIn->iNext], nMove);
  186001. }
  186002. pIn->buf.nBuf -= pIn->iNext;
  186003. pIn->iNext = 0;
  186004. pIn->nData = pIn->buf.nBuf;
  186005. }
  186006. }
  186007. /*
  186008. ** Ensure that there are at least nByte bytes available in the buffer. Or,
  186009. ** if there are not nByte bytes remaining in the input, that all available
  186010. ** data is in the buffer.
  186011. **
  186012. ** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
  186013. */
  186014. static int sessionInputBuffer(SessionInput *pIn, int nByte){
  186015. int rc = SQLITE_OK;
  186016. if( pIn->xInput ){
  186017. while( !pIn->bEof && (pIn->iNext+nByte)>=pIn->nData && rc==SQLITE_OK ){
  186018. int nNew = sessions_strm_chunk_size;
  186019. if( pIn->bNoDiscard==0 ) sessionDiscardData(pIn);
  186020. if( SQLITE_OK==sessionBufferGrow(&pIn->buf, nNew, &rc) ){
  186021. rc = pIn->xInput(pIn->pIn, &pIn->buf.aBuf[pIn->buf.nBuf], &nNew);
  186022. if( nNew==0 ){
  186023. pIn->bEof = 1;
  186024. }else{
  186025. pIn->buf.nBuf += nNew;
  186026. }
  186027. }
  186028. pIn->aData = pIn->buf.aBuf;
  186029. pIn->nData = pIn->buf.nBuf;
  186030. }
  186031. }
  186032. return rc;
  186033. }
  186034. /*
  186035. ** When this function is called, *ppRec points to the start of a record
  186036. ** that contains nCol values. This function advances the pointer *ppRec
  186037. ** until it points to the byte immediately following that record.
  186038. */
  186039. static void sessionSkipRecord(
  186040. u8 **ppRec, /* IN/OUT: Record pointer */
  186041. int nCol /* Number of values in record */
  186042. ){
  186043. u8 *aRec = *ppRec;
  186044. int i;
  186045. for(i=0; i<nCol; i++){
  186046. int eType = *aRec++;
  186047. if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
  186048. int nByte;
  186049. aRec += sessionVarintGet((u8*)aRec, &nByte);
  186050. aRec += nByte;
  186051. }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  186052. aRec += 8;
  186053. }
  186054. }
  186055. *ppRec = aRec;
  186056. }
  186057. /*
  186058. ** This function sets the value of the sqlite3_value object passed as the
  186059. ** first argument to a copy of the string or blob held in the aData[]
  186060. ** buffer. SQLITE_OK is returned if successful, or SQLITE_NOMEM if an OOM
  186061. ** error occurs.
  186062. */
  186063. static int sessionValueSetStr(
  186064. sqlite3_value *pVal, /* Set the value of this object */
  186065. u8 *aData, /* Buffer containing string or blob data */
  186066. int nData, /* Size of buffer aData[] in bytes */
  186067. u8 enc /* String encoding (0 for blobs) */
  186068. ){
  186069. /* In theory this code could just pass SQLITE_TRANSIENT as the final
  186070. ** argument to sqlite3ValueSetStr() and have the copy created
  186071. ** automatically. But doing so makes it difficult to detect any OOM
  186072. ** error. Hence the code to create the copy externally. */
  186073. u8 *aCopy = sqlite3_malloc64((sqlite3_int64)nData+1);
  186074. if( aCopy==0 ) return SQLITE_NOMEM;
  186075. memcpy(aCopy, aData, nData);
  186076. sqlite3ValueSetStr(pVal, nData, (char*)aCopy, enc, sqlite3_free);
  186077. return SQLITE_OK;
  186078. }
  186079. /*
  186080. ** Deserialize a single record from a buffer in memory. See "RECORD FORMAT"
  186081. ** for details.
  186082. **
  186083. ** When this function is called, *paChange points to the start of the record
  186084. ** to deserialize. Assuming no error occurs, *paChange is set to point to
  186085. ** one byte after the end of the same record before this function returns.
  186086. ** If the argument abPK is NULL, then the record contains nCol values. Or,
  186087. ** if abPK is other than NULL, then the record contains only the PK fields
  186088. ** (in other words, it is a patchset DELETE record).
  186089. **
  186090. ** If successful, each element of the apOut[] array (allocated by the caller)
  186091. ** is set to point to an sqlite3_value object containing the value read
  186092. ** from the corresponding position in the record. If that value is not
  186093. ** included in the record (i.e. because the record is part of an UPDATE change
  186094. ** and the field was not modified), the corresponding element of apOut[] is
  186095. ** set to NULL.
  186096. **
  186097. ** It is the responsibility of the caller to free all sqlite_value structures
  186098. ** using sqlite3_free().
  186099. **
  186100. ** If an error occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
  186101. ** The apOut[] array may have been partially populated in this case.
  186102. */
  186103. static int sessionReadRecord(
  186104. SessionInput *pIn, /* Input data */
  186105. int nCol, /* Number of values in record */
  186106. u8 *abPK, /* Array of primary key flags, or NULL */
  186107. sqlite3_value **apOut /* Write values to this array */
  186108. ){
  186109. int i; /* Used to iterate through columns */
  186110. int rc = SQLITE_OK;
  186111. for(i=0; i<nCol && rc==SQLITE_OK; i++){
  186112. int eType = 0; /* Type of value (SQLITE_NULL, TEXT etc.) */
  186113. if( abPK && abPK[i]==0 ) continue;
  186114. rc = sessionInputBuffer(pIn, 9);
  186115. if( rc==SQLITE_OK ){
  186116. if( pIn->iNext>=pIn->nData ){
  186117. rc = SQLITE_CORRUPT_BKPT;
  186118. }else{
  186119. eType = pIn->aData[pIn->iNext++];
  186120. assert( apOut[i]==0 );
  186121. if( eType ){
  186122. apOut[i] = sqlite3ValueNew(0);
  186123. if( !apOut[i] ) rc = SQLITE_NOMEM;
  186124. }
  186125. }
  186126. }
  186127. if( rc==SQLITE_OK ){
  186128. u8 *aVal = &pIn->aData[pIn->iNext];
  186129. if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
  186130. int nByte;
  186131. pIn->iNext += sessionVarintGet(aVal, &nByte);
  186132. rc = sessionInputBuffer(pIn, nByte);
  186133. if( rc==SQLITE_OK ){
  186134. if( nByte<0 || nByte>pIn->nData-pIn->iNext ){
  186135. rc = SQLITE_CORRUPT_BKPT;
  186136. }else{
  186137. u8 enc = (eType==SQLITE_TEXT ? SQLITE_UTF8 : 0);
  186138. rc = sessionValueSetStr(apOut[i],&pIn->aData[pIn->iNext],nByte,enc);
  186139. pIn->iNext += nByte;
  186140. }
  186141. }
  186142. }
  186143. if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  186144. sqlite3_int64 v = sessionGetI64(aVal);
  186145. if( eType==SQLITE_INTEGER ){
  186146. sqlite3VdbeMemSetInt64(apOut[i], v);
  186147. }else{
  186148. double d;
  186149. memcpy(&d, &v, 8);
  186150. sqlite3VdbeMemSetDouble(apOut[i], d);
  186151. }
  186152. pIn->iNext += 8;
  186153. }
  186154. }
  186155. }
  186156. return rc;
  186157. }
  186158. /*
  186159. ** The input pointer currently points to the second byte of a table-header.
  186160. ** Specifically, to the following:
  186161. **
  186162. ** + number of columns in table (varint)
  186163. ** + array of PK flags (1 byte per column),
  186164. ** + table name (nul terminated).
  186165. **
  186166. ** This function ensures that all of the above is present in the input
  186167. ** buffer (i.e. that it can be accessed without any calls to xInput()).
  186168. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
  186169. ** The input pointer is not moved.
  186170. */
  186171. static int sessionChangesetBufferTblhdr(SessionInput *pIn, int *pnByte){
  186172. int rc = SQLITE_OK;
  186173. int nCol = 0;
  186174. int nRead = 0;
  186175. rc = sessionInputBuffer(pIn, 9);
  186176. if( rc==SQLITE_OK ){
  186177. nRead += sessionVarintGet(&pIn->aData[pIn->iNext + nRead], &nCol);
  186178. /* The hard upper limit for the number of columns in an SQLite
  186179. ** database table is, according to sqliteLimit.h, 32676. So
  186180. ** consider any table-header that purports to have more than 65536
  186181. ** columns to be corrupt. This is convenient because otherwise,
  186182. ** if the (nCol>65536) condition below were omitted, a sufficiently
  186183. ** large value for nCol may cause nRead to wrap around and become
  186184. ** negative. Leading to a crash. */
  186185. if( nCol<0 || nCol>65536 ){
  186186. rc = SQLITE_CORRUPT_BKPT;
  186187. }else{
  186188. rc = sessionInputBuffer(pIn, nRead+nCol+100);
  186189. nRead += nCol;
  186190. }
  186191. }
  186192. while( rc==SQLITE_OK ){
  186193. while( (pIn->iNext + nRead)<pIn->nData && pIn->aData[pIn->iNext + nRead] ){
  186194. nRead++;
  186195. }
  186196. if( (pIn->iNext + nRead)<pIn->nData ) break;
  186197. rc = sessionInputBuffer(pIn, nRead + 100);
  186198. }
  186199. *pnByte = nRead+1;
  186200. return rc;
  186201. }
  186202. /*
  186203. ** The input pointer currently points to the first byte of the first field
  186204. ** of a record consisting of nCol columns. This function ensures the entire
  186205. ** record is buffered. It does not move the input pointer.
  186206. **
  186207. ** If successful, SQLITE_OK is returned and *pnByte is set to the size of
  186208. ** the record in bytes. Otherwise, an SQLite error code is returned. The
  186209. ** final value of *pnByte is undefined in this case.
  186210. */
  186211. static int sessionChangesetBufferRecord(
  186212. SessionInput *pIn, /* Input data */
  186213. int nCol, /* Number of columns in record */
  186214. int *pnByte /* OUT: Size of record in bytes */
  186215. ){
  186216. int rc = SQLITE_OK;
  186217. int nByte = 0;
  186218. int i;
  186219. for(i=0; rc==SQLITE_OK && i<nCol; i++){
  186220. int eType;
  186221. rc = sessionInputBuffer(pIn, nByte + 10);
  186222. if( rc==SQLITE_OK ){
  186223. eType = pIn->aData[pIn->iNext + nByte++];
  186224. if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
  186225. int n;
  186226. nByte += sessionVarintGet(&pIn->aData[pIn->iNext+nByte], &n);
  186227. nByte += n;
  186228. rc = sessionInputBuffer(pIn, nByte);
  186229. }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  186230. nByte += 8;
  186231. }
  186232. }
  186233. }
  186234. *pnByte = nByte;
  186235. return rc;
  186236. }
  186237. /*
  186238. ** The input pointer currently points to the second byte of a table-header.
  186239. ** Specifically, to the following:
  186240. **
  186241. ** + number of columns in table (varint)
  186242. ** + array of PK flags (1 byte per column),
  186243. ** + table name (nul terminated).
  186244. **
  186245. ** This function decodes the table-header and populates the p->nCol,
  186246. ** p->zTab and p->abPK[] variables accordingly. The p->apValue[] array is
  186247. ** also allocated or resized according to the new value of p->nCol. The
  186248. ** input pointer is left pointing to the byte following the table header.
  186249. **
  186250. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code
  186251. ** is returned and the final values of the various fields enumerated above
  186252. ** are undefined.
  186253. */
  186254. static int sessionChangesetReadTblhdr(sqlite3_changeset_iter *p){
  186255. int rc;
  186256. int nCopy;
  186257. assert( p->rc==SQLITE_OK );
  186258. rc = sessionChangesetBufferTblhdr(&p->in, &nCopy);
  186259. if( rc==SQLITE_OK ){
  186260. int nByte;
  186261. int nVarint;
  186262. nVarint = sessionVarintGet(&p->in.aData[p->in.iNext], &p->nCol);
  186263. if( p->nCol>0 ){
  186264. nCopy -= nVarint;
  186265. p->in.iNext += nVarint;
  186266. nByte = p->nCol * sizeof(sqlite3_value*) * 2 + nCopy;
  186267. p->tblhdr.nBuf = 0;
  186268. sessionBufferGrow(&p->tblhdr, nByte, &rc);
  186269. }else{
  186270. rc = SQLITE_CORRUPT_BKPT;
  186271. }
  186272. }
  186273. if( rc==SQLITE_OK ){
  186274. size_t iPK = sizeof(sqlite3_value*)*p->nCol*2;
  186275. memset(p->tblhdr.aBuf, 0, iPK);
  186276. memcpy(&p->tblhdr.aBuf[iPK], &p->in.aData[p->in.iNext], nCopy);
  186277. p->in.iNext += nCopy;
  186278. }
  186279. p->apValue = (sqlite3_value**)p->tblhdr.aBuf;
  186280. p->abPK = (u8*)&p->apValue[p->nCol*2];
  186281. p->zTab = (char*)&p->abPK[p->nCol];
  186282. return (p->rc = rc);
  186283. }
  186284. /*
  186285. ** Advance the changeset iterator to the next change.
  186286. **
  186287. ** If both paRec and pnRec are NULL, then this function works like the public
  186288. ** API sqlite3changeset_next(). If SQLITE_ROW is returned, then the
  186289. ** sqlite3changeset_new() and old() APIs may be used to query for values.
  186290. **
  186291. ** Otherwise, if paRec and pnRec are not NULL, then a pointer to the change
  186292. ** record is written to *paRec before returning and the number of bytes in
  186293. ** the record to *pnRec.
  186294. **
  186295. ** Either way, this function returns SQLITE_ROW if the iterator is
  186296. ** successfully advanced to the next change in the changeset, an SQLite
  186297. ** error code if an error occurs, or SQLITE_DONE if there are no further
  186298. ** changes in the changeset.
  186299. */
  186300. static int sessionChangesetNext(
  186301. sqlite3_changeset_iter *p, /* Changeset iterator */
  186302. u8 **paRec, /* If non-NULL, store record pointer here */
  186303. int *pnRec, /* If non-NULL, store size of record here */
  186304. int *pbNew /* If non-NULL, true if new table */
  186305. ){
  186306. int i;
  186307. u8 op;
  186308. assert( (paRec==0 && pnRec==0) || (paRec && pnRec) );
  186309. /* If the iterator is in the error-state, return immediately. */
  186310. if( p->rc!=SQLITE_OK ) return p->rc;
  186311. /* Free the current contents of p->apValue[], if any. */
  186312. if( p->apValue ){
  186313. for(i=0; i<p->nCol*2; i++){
  186314. sqlite3ValueFree(p->apValue[i]);
  186315. }
  186316. memset(p->apValue, 0, sizeof(sqlite3_value*)*p->nCol*2);
  186317. }
  186318. /* Make sure the buffer contains at least 10 bytes of input data, or all
  186319. ** remaining data if there are less than 10 bytes available. This is
  186320. ** sufficient either for the 'T' or 'P' byte and the varint that follows
  186321. ** it, or for the two single byte values otherwise. */
  186322. p->rc = sessionInputBuffer(&p->in, 2);
  186323. if( p->rc!=SQLITE_OK ) return p->rc;
  186324. /* If the iterator is already at the end of the changeset, return DONE. */
  186325. if( p->in.iNext>=p->in.nData ){
  186326. return SQLITE_DONE;
  186327. }
  186328. sessionDiscardData(&p->in);
  186329. p->in.iCurrent = p->in.iNext;
  186330. op = p->in.aData[p->in.iNext++];
  186331. while( op=='T' || op=='P' ){
  186332. if( pbNew ) *pbNew = 1;
  186333. p->bPatchset = (op=='P');
  186334. if( sessionChangesetReadTblhdr(p) ) return p->rc;
  186335. if( (p->rc = sessionInputBuffer(&p->in, 2)) ) return p->rc;
  186336. p->in.iCurrent = p->in.iNext;
  186337. if( p->in.iNext>=p->in.nData ) return SQLITE_DONE;
  186338. op = p->in.aData[p->in.iNext++];
  186339. }
  186340. if( p->zTab==0 || (p->bPatchset && p->bInvert) ){
  186341. /* The first record in the changeset is not a table header. Must be a
  186342. ** corrupt changeset. */
  186343. assert( p->in.iNext==1 || p->zTab );
  186344. return (p->rc = SQLITE_CORRUPT_BKPT);
  186345. }
  186346. p->op = op;
  186347. p->bIndirect = p->in.aData[p->in.iNext++];
  186348. if( p->op!=SQLITE_UPDATE && p->op!=SQLITE_DELETE && p->op!=SQLITE_INSERT ){
  186349. return (p->rc = SQLITE_CORRUPT_BKPT);
  186350. }
  186351. if( paRec ){
  186352. int nVal; /* Number of values to buffer */
  186353. if( p->bPatchset==0 && op==SQLITE_UPDATE ){
  186354. nVal = p->nCol * 2;
  186355. }else if( p->bPatchset && op==SQLITE_DELETE ){
  186356. nVal = 0;
  186357. for(i=0; i<p->nCol; i++) if( p->abPK[i] ) nVal++;
  186358. }else{
  186359. nVal = p->nCol;
  186360. }
  186361. p->rc = sessionChangesetBufferRecord(&p->in, nVal, pnRec);
  186362. if( p->rc!=SQLITE_OK ) return p->rc;
  186363. *paRec = &p->in.aData[p->in.iNext];
  186364. p->in.iNext += *pnRec;
  186365. }else{
  186366. sqlite3_value **apOld = (p->bInvert ? &p->apValue[p->nCol] : p->apValue);
  186367. sqlite3_value **apNew = (p->bInvert ? p->apValue : &p->apValue[p->nCol]);
  186368. /* If this is an UPDATE or DELETE, read the old.* record. */
  186369. if( p->op!=SQLITE_INSERT && (p->bPatchset==0 || p->op==SQLITE_DELETE) ){
  186370. u8 *abPK = p->bPatchset ? p->abPK : 0;
  186371. p->rc = sessionReadRecord(&p->in, p->nCol, abPK, apOld);
  186372. if( p->rc!=SQLITE_OK ) return p->rc;
  186373. }
  186374. /* If this is an INSERT or UPDATE, read the new.* record. */
  186375. if( p->op!=SQLITE_DELETE ){
  186376. p->rc = sessionReadRecord(&p->in, p->nCol, 0, apNew);
  186377. if( p->rc!=SQLITE_OK ) return p->rc;
  186378. }
  186379. if( (p->bPatchset || p->bInvert) && p->op==SQLITE_UPDATE ){
  186380. /* If this is an UPDATE that is part of a patchset, then all PK and
  186381. ** modified fields are present in the new.* record. The old.* record
  186382. ** is currently completely empty. This block shifts the PK fields from
  186383. ** new.* to old.*, to accommodate the code that reads these arrays. */
  186384. for(i=0; i<p->nCol; i++){
  186385. assert( p->bPatchset==0 || p->apValue[i]==0 );
  186386. if( p->abPK[i] ){
  186387. assert( p->apValue[i]==0 );
  186388. p->apValue[i] = p->apValue[i+p->nCol];
  186389. if( p->apValue[i]==0 ) return (p->rc = SQLITE_CORRUPT_BKPT);
  186390. p->apValue[i+p->nCol] = 0;
  186391. }
  186392. }
  186393. }else if( p->bInvert ){
  186394. if( p->op==SQLITE_INSERT ) p->op = SQLITE_DELETE;
  186395. else if( p->op==SQLITE_DELETE ) p->op = SQLITE_INSERT;
  186396. }
  186397. }
  186398. return SQLITE_ROW;
  186399. }
  186400. /*
  186401. ** Advance an iterator created by sqlite3changeset_start() to the next
  186402. ** change in the changeset. This function may return SQLITE_ROW, SQLITE_DONE
  186403. ** or SQLITE_CORRUPT.
  186404. **
  186405. ** This function may not be called on iterators passed to a conflict handler
  186406. ** callback by changeset_apply().
  186407. */
  186408. SQLITE_API int sqlite3changeset_next(sqlite3_changeset_iter *p){
  186409. return sessionChangesetNext(p, 0, 0, 0);
  186410. }
  186411. /*
  186412. ** The following function extracts information on the current change
  186413. ** from a changeset iterator. It may only be called after changeset_next()
  186414. ** has returned SQLITE_ROW.
  186415. */
  186416. SQLITE_API int sqlite3changeset_op(
  186417. sqlite3_changeset_iter *pIter, /* Iterator handle */
  186418. const char **pzTab, /* OUT: Pointer to table name */
  186419. int *pnCol, /* OUT: Number of columns in table */
  186420. int *pOp, /* OUT: SQLITE_INSERT, DELETE or UPDATE */
  186421. int *pbIndirect /* OUT: True if change is indirect */
  186422. ){
  186423. *pOp = pIter->op;
  186424. *pnCol = pIter->nCol;
  186425. *pzTab = pIter->zTab;
  186426. if( pbIndirect ) *pbIndirect = pIter->bIndirect;
  186427. return SQLITE_OK;
  186428. }
  186429. /*
  186430. ** Return information regarding the PRIMARY KEY and number of columns in
  186431. ** the database table affected by the change that pIter currently points
  186432. ** to. This function may only be called after changeset_next() returns
  186433. ** SQLITE_ROW.
  186434. */
  186435. SQLITE_API int sqlite3changeset_pk(
  186436. sqlite3_changeset_iter *pIter, /* Iterator object */
  186437. unsigned char **pabPK, /* OUT: Array of boolean - true for PK cols */
  186438. int *pnCol /* OUT: Number of entries in output array */
  186439. ){
  186440. *pabPK = pIter->abPK;
  186441. if( pnCol ) *pnCol = pIter->nCol;
  186442. return SQLITE_OK;
  186443. }
  186444. /*
  186445. ** This function may only be called while the iterator is pointing to an
  186446. ** SQLITE_UPDATE or SQLITE_DELETE change (see sqlite3changeset_op()).
  186447. ** Otherwise, SQLITE_MISUSE is returned.
  186448. **
  186449. ** It sets *ppValue to point to an sqlite3_value structure containing the
  186450. ** iVal'th value in the old.* record. Or, if that particular value is not
  186451. ** included in the record (because the change is an UPDATE and the field
  186452. ** was not modified and is not a PK column), set *ppValue to NULL.
  186453. **
  186454. ** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is
  186455. ** not modified. Otherwise, SQLITE_OK.
  186456. */
  186457. SQLITE_API int sqlite3changeset_old(
  186458. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  186459. int iVal, /* Index of old.* value to retrieve */
  186460. sqlite3_value **ppValue /* OUT: Old value (or NULL pointer) */
  186461. ){
  186462. if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_DELETE ){
  186463. return SQLITE_MISUSE;
  186464. }
  186465. if( iVal<0 || iVal>=pIter->nCol ){
  186466. return SQLITE_RANGE;
  186467. }
  186468. *ppValue = pIter->apValue[iVal];
  186469. return SQLITE_OK;
  186470. }
  186471. /*
  186472. ** This function may only be called while the iterator is pointing to an
  186473. ** SQLITE_UPDATE or SQLITE_INSERT change (see sqlite3changeset_op()).
  186474. ** Otherwise, SQLITE_MISUSE is returned.
  186475. **
  186476. ** It sets *ppValue to point to an sqlite3_value structure containing the
  186477. ** iVal'th value in the new.* record. Or, if that particular value is not
  186478. ** included in the record (because the change is an UPDATE and the field
  186479. ** was not modified), set *ppValue to NULL.
  186480. **
  186481. ** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is
  186482. ** not modified. Otherwise, SQLITE_OK.
  186483. */
  186484. SQLITE_API int sqlite3changeset_new(
  186485. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  186486. int iVal, /* Index of new.* value to retrieve */
  186487. sqlite3_value **ppValue /* OUT: New value (or NULL pointer) */
  186488. ){
  186489. if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_INSERT ){
  186490. return SQLITE_MISUSE;
  186491. }
  186492. if( iVal<0 || iVal>=pIter->nCol ){
  186493. return SQLITE_RANGE;
  186494. }
  186495. *ppValue = pIter->apValue[pIter->nCol+iVal];
  186496. return SQLITE_OK;
  186497. }
  186498. /*
  186499. ** The following two macros are used internally. They are similar to the
  186500. ** sqlite3changeset_new() and sqlite3changeset_old() functions, except that
  186501. ** they omit all error checking and return a pointer to the requested value.
  186502. */
  186503. #define sessionChangesetNew(pIter, iVal) (pIter)->apValue[(pIter)->nCol+(iVal)]
  186504. #define sessionChangesetOld(pIter, iVal) (pIter)->apValue[(iVal)]
  186505. /*
  186506. ** This function may only be called with a changeset iterator that has been
  186507. ** passed to an SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT
  186508. ** conflict-handler function. Otherwise, SQLITE_MISUSE is returned.
  186509. **
  186510. ** If successful, *ppValue is set to point to an sqlite3_value structure
  186511. ** containing the iVal'th value of the conflicting record.
  186512. **
  186513. ** If value iVal is out-of-range or some other error occurs, an SQLite error
  186514. ** code is returned. Otherwise, SQLITE_OK.
  186515. */
  186516. SQLITE_API int sqlite3changeset_conflict(
  186517. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  186518. int iVal, /* Index of conflict record value to fetch */
  186519. sqlite3_value **ppValue /* OUT: Value from conflicting row */
  186520. ){
  186521. if( !pIter->pConflict ){
  186522. return SQLITE_MISUSE;
  186523. }
  186524. if( iVal<0 || iVal>=pIter->nCol ){
  186525. return SQLITE_RANGE;
  186526. }
  186527. *ppValue = sqlite3_column_value(pIter->pConflict, iVal);
  186528. return SQLITE_OK;
  186529. }
  186530. /*
  186531. ** This function may only be called with an iterator passed to an
  186532. ** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case
  186533. ** it sets the output variable to the total number of known foreign key
  186534. ** violations in the destination database and returns SQLITE_OK.
  186535. **
  186536. ** In all other cases this function returns SQLITE_MISUSE.
  186537. */
  186538. SQLITE_API int sqlite3changeset_fk_conflicts(
  186539. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  186540. int *pnOut /* OUT: Number of FK violations */
  186541. ){
  186542. if( pIter->pConflict || pIter->apValue ){
  186543. return SQLITE_MISUSE;
  186544. }
  186545. *pnOut = pIter->nCol;
  186546. return SQLITE_OK;
  186547. }
  186548. /*
  186549. ** Finalize an iterator allocated with sqlite3changeset_start().
  186550. **
  186551. ** This function may not be called on iterators passed to a conflict handler
  186552. ** callback by changeset_apply().
  186553. */
  186554. SQLITE_API int sqlite3changeset_finalize(sqlite3_changeset_iter *p){
  186555. int rc = SQLITE_OK;
  186556. if( p ){
  186557. int i; /* Used to iterate through p->apValue[] */
  186558. rc = p->rc;
  186559. if( p->apValue ){
  186560. for(i=0; i<p->nCol*2; i++) sqlite3ValueFree(p->apValue[i]);
  186561. }
  186562. sqlite3_free(p->tblhdr.aBuf);
  186563. sqlite3_free(p->in.buf.aBuf);
  186564. sqlite3_free(p);
  186565. }
  186566. return rc;
  186567. }
  186568. static int sessionChangesetInvert(
  186569. SessionInput *pInput, /* Input changeset */
  186570. int (*xOutput)(void *pOut, const void *pData, int nData),
  186571. void *pOut,
  186572. int *pnInverted, /* OUT: Number of bytes in output changeset */
  186573. void **ppInverted /* OUT: Inverse of pChangeset */
  186574. ){
  186575. int rc = SQLITE_OK; /* Return value */
  186576. SessionBuffer sOut; /* Output buffer */
  186577. int nCol = 0; /* Number of cols in current table */
  186578. u8 *abPK = 0; /* PK array for current table */
  186579. sqlite3_value **apVal = 0; /* Space for values for UPDATE inversion */
  186580. SessionBuffer sPK = {0, 0, 0}; /* PK array for current table */
  186581. /* Initialize the output buffer */
  186582. memset(&sOut, 0, sizeof(SessionBuffer));
  186583. /* Zero the output variables in case an error occurs. */
  186584. if( ppInverted ){
  186585. *ppInverted = 0;
  186586. *pnInverted = 0;
  186587. }
  186588. while( 1 ){
  186589. u8 eType;
  186590. /* Test for EOF. */
  186591. if( (rc = sessionInputBuffer(pInput, 2)) ) goto finished_invert;
  186592. if( pInput->iNext>=pInput->nData ) break;
  186593. eType = pInput->aData[pInput->iNext];
  186594. switch( eType ){
  186595. case 'T': {
  186596. /* A 'table' record consists of:
  186597. **
  186598. ** * A constant 'T' character,
  186599. ** * Number of columns in said table (a varint),
  186600. ** * An array of nCol bytes (sPK),
  186601. ** * A nul-terminated table name.
  186602. */
  186603. int nByte;
  186604. int nVar;
  186605. pInput->iNext++;
  186606. if( (rc = sessionChangesetBufferTblhdr(pInput, &nByte)) ){
  186607. goto finished_invert;
  186608. }
  186609. nVar = sessionVarintGet(&pInput->aData[pInput->iNext], &nCol);
  186610. sPK.nBuf = 0;
  186611. sessionAppendBlob(&sPK, &pInput->aData[pInput->iNext+nVar], nCol, &rc);
  186612. sessionAppendByte(&sOut, eType, &rc);
  186613. sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc);
  186614. if( rc ) goto finished_invert;
  186615. pInput->iNext += nByte;
  186616. sqlite3_free(apVal);
  186617. apVal = 0;
  186618. abPK = sPK.aBuf;
  186619. break;
  186620. }
  186621. case SQLITE_INSERT:
  186622. case SQLITE_DELETE: {
  186623. int nByte;
  186624. int bIndirect = pInput->aData[pInput->iNext+1];
  186625. int eType2 = (eType==SQLITE_DELETE ? SQLITE_INSERT : SQLITE_DELETE);
  186626. pInput->iNext += 2;
  186627. assert( rc==SQLITE_OK );
  186628. rc = sessionChangesetBufferRecord(pInput, nCol, &nByte);
  186629. sessionAppendByte(&sOut, eType2, &rc);
  186630. sessionAppendByte(&sOut, bIndirect, &rc);
  186631. sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc);
  186632. pInput->iNext += nByte;
  186633. if( rc ) goto finished_invert;
  186634. break;
  186635. }
  186636. case SQLITE_UPDATE: {
  186637. int iCol;
  186638. if( 0==apVal ){
  186639. apVal = (sqlite3_value **)sqlite3_malloc64(sizeof(apVal[0])*nCol*2);
  186640. if( 0==apVal ){
  186641. rc = SQLITE_NOMEM;
  186642. goto finished_invert;
  186643. }
  186644. memset(apVal, 0, sizeof(apVal[0])*nCol*2);
  186645. }
  186646. /* Write the header for the new UPDATE change. Same as the original. */
  186647. sessionAppendByte(&sOut, eType, &rc);
  186648. sessionAppendByte(&sOut, pInput->aData[pInput->iNext+1], &rc);
  186649. /* Read the old.* and new.* records for the update change. */
  186650. pInput->iNext += 2;
  186651. rc = sessionReadRecord(pInput, nCol, 0, &apVal[0]);
  186652. if( rc==SQLITE_OK ){
  186653. rc = sessionReadRecord(pInput, nCol, 0, &apVal[nCol]);
  186654. }
  186655. /* Write the new old.* record. Consists of the PK columns from the
  186656. ** original old.* record, and the other values from the original
  186657. ** new.* record. */
  186658. for(iCol=0; iCol<nCol; iCol++){
  186659. sqlite3_value *pVal = apVal[iCol + (abPK[iCol] ? 0 : nCol)];
  186660. sessionAppendValue(&sOut, pVal, &rc);
  186661. }
  186662. /* Write the new new.* record. Consists of a copy of all values
  186663. ** from the original old.* record, except for the PK columns, which
  186664. ** are set to "undefined". */
  186665. for(iCol=0; iCol<nCol; iCol++){
  186666. sqlite3_value *pVal = (abPK[iCol] ? 0 : apVal[iCol]);
  186667. sessionAppendValue(&sOut, pVal, &rc);
  186668. }
  186669. for(iCol=0; iCol<nCol*2; iCol++){
  186670. sqlite3ValueFree(apVal[iCol]);
  186671. }
  186672. memset(apVal, 0, sizeof(apVal[0])*nCol*2);
  186673. if( rc!=SQLITE_OK ){
  186674. goto finished_invert;
  186675. }
  186676. break;
  186677. }
  186678. default:
  186679. rc = SQLITE_CORRUPT_BKPT;
  186680. goto finished_invert;
  186681. }
  186682. assert( rc==SQLITE_OK );
  186683. if( xOutput && sOut.nBuf>=sessions_strm_chunk_size ){
  186684. rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
  186685. sOut.nBuf = 0;
  186686. if( rc!=SQLITE_OK ) goto finished_invert;
  186687. }
  186688. }
  186689. assert( rc==SQLITE_OK );
  186690. if( pnInverted ){
  186691. *pnInverted = sOut.nBuf;
  186692. *ppInverted = sOut.aBuf;
  186693. sOut.aBuf = 0;
  186694. }else if( sOut.nBuf>0 ){
  186695. rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
  186696. }
  186697. finished_invert:
  186698. sqlite3_free(sOut.aBuf);
  186699. sqlite3_free(apVal);
  186700. sqlite3_free(sPK.aBuf);
  186701. return rc;
  186702. }
  186703. /*
  186704. ** Invert a changeset object.
  186705. */
  186706. SQLITE_API int sqlite3changeset_invert(
  186707. int nChangeset, /* Number of bytes in input */
  186708. const void *pChangeset, /* Input changeset */
  186709. int *pnInverted, /* OUT: Number of bytes in output changeset */
  186710. void **ppInverted /* OUT: Inverse of pChangeset */
  186711. ){
  186712. SessionInput sInput;
  186713. /* Set up the input stream */
  186714. memset(&sInput, 0, sizeof(SessionInput));
  186715. sInput.nData = nChangeset;
  186716. sInput.aData = (u8*)pChangeset;
  186717. return sessionChangesetInvert(&sInput, 0, 0, pnInverted, ppInverted);
  186718. }
  186719. /*
  186720. ** Streaming version of sqlite3changeset_invert().
  186721. */
  186722. SQLITE_API int sqlite3changeset_invert_strm(
  186723. int (*xInput)(void *pIn, void *pData, int *pnData),
  186724. void *pIn,
  186725. int (*xOutput)(void *pOut, const void *pData, int nData),
  186726. void *pOut
  186727. ){
  186728. SessionInput sInput;
  186729. int rc;
  186730. /* Set up the input stream */
  186731. memset(&sInput, 0, sizeof(SessionInput));
  186732. sInput.xInput = xInput;
  186733. sInput.pIn = pIn;
  186734. rc = sessionChangesetInvert(&sInput, xOutput, pOut, 0, 0);
  186735. sqlite3_free(sInput.buf.aBuf);
  186736. return rc;
  186737. }
  186738. typedef struct SessionApplyCtx SessionApplyCtx;
  186739. struct SessionApplyCtx {
  186740. sqlite3 *db;
  186741. sqlite3_stmt *pDelete; /* DELETE statement */
  186742. sqlite3_stmt *pUpdate; /* UPDATE statement */
  186743. sqlite3_stmt *pInsert; /* INSERT statement */
  186744. sqlite3_stmt *pSelect; /* SELECT statement */
  186745. int nCol; /* Size of azCol[] and abPK[] arrays */
  186746. const char **azCol; /* Array of column names */
  186747. u8 *abPK; /* Boolean array - true if column is in PK */
  186748. int bStat1; /* True if table is sqlite_stat1 */
  186749. int bDeferConstraints; /* True to defer constraints */
  186750. SessionBuffer constraints; /* Deferred constraints are stored here */
  186751. SessionBuffer rebase; /* Rebase information (if any) here */
  186752. u8 bRebaseStarted; /* If table header is already in rebase */
  186753. u8 bRebase; /* True to collect rebase information */
  186754. };
  186755. /*
  186756. ** Formulate a statement to DELETE a row from database db. Assuming a table
  186757. ** structure like this:
  186758. **
  186759. ** CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
  186760. **
  186761. ** The DELETE statement looks like this:
  186762. **
  186763. ** DELETE FROM x WHERE a = :1 AND c = :3 AND (:5 OR b IS :2 AND d IS :4)
  186764. **
  186765. ** Variable :5 (nCol+1) is a boolean. It should be set to 0 if we require
  186766. ** matching b and d values, or 1 otherwise. The second case comes up if the
  186767. ** conflict handler is invoked with NOTFOUND and returns CHANGESET_REPLACE.
  186768. **
  186769. ** If successful, SQLITE_OK is returned and SessionApplyCtx.pDelete is left
  186770. ** pointing to the prepared version of the SQL statement.
  186771. */
  186772. static int sessionDeleteRow(
  186773. sqlite3 *db, /* Database handle */
  186774. const char *zTab, /* Table name */
  186775. SessionApplyCtx *p /* Session changeset-apply context */
  186776. ){
  186777. int i;
  186778. const char *zSep = "";
  186779. int rc = SQLITE_OK;
  186780. SessionBuffer buf = {0, 0, 0};
  186781. int nPk = 0;
  186782. sessionAppendStr(&buf, "DELETE FROM ", &rc);
  186783. sessionAppendIdent(&buf, zTab, &rc);
  186784. sessionAppendStr(&buf, " WHERE ", &rc);
  186785. for(i=0; i<p->nCol; i++){
  186786. if( p->abPK[i] ){
  186787. nPk++;
  186788. sessionAppendStr(&buf, zSep, &rc);
  186789. sessionAppendIdent(&buf, p->azCol[i], &rc);
  186790. sessionAppendStr(&buf, " = ?", &rc);
  186791. sessionAppendInteger(&buf, i+1, &rc);
  186792. zSep = " AND ";
  186793. }
  186794. }
  186795. if( nPk<p->nCol ){
  186796. sessionAppendStr(&buf, " AND (?", &rc);
  186797. sessionAppendInteger(&buf, p->nCol+1, &rc);
  186798. sessionAppendStr(&buf, " OR ", &rc);
  186799. zSep = "";
  186800. for(i=0; i<p->nCol; i++){
  186801. if( !p->abPK[i] ){
  186802. sessionAppendStr(&buf, zSep, &rc);
  186803. sessionAppendIdent(&buf, p->azCol[i], &rc);
  186804. sessionAppendStr(&buf, " IS ?", &rc);
  186805. sessionAppendInteger(&buf, i+1, &rc);
  186806. zSep = "AND ";
  186807. }
  186808. }
  186809. sessionAppendStr(&buf, ")", &rc);
  186810. }
  186811. if( rc==SQLITE_OK ){
  186812. rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pDelete, 0);
  186813. }
  186814. sqlite3_free(buf.aBuf);
  186815. return rc;
  186816. }
  186817. /*
  186818. ** Formulate and prepare a statement to UPDATE a row from database db.
  186819. ** Assuming a table structure like this:
  186820. **
  186821. ** CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
  186822. **
  186823. ** The UPDATE statement looks like this:
  186824. **
  186825. ** UPDATE x SET
  186826. ** a = CASE WHEN ?2 THEN ?3 ELSE a END,
  186827. ** b = CASE WHEN ?5 THEN ?6 ELSE b END,
  186828. ** c = CASE WHEN ?8 THEN ?9 ELSE c END,
  186829. ** d = CASE WHEN ?11 THEN ?12 ELSE d END
  186830. ** WHERE a = ?1 AND c = ?7 AND (?13 OR
  186831. ** (?5==0 OR b IS ?4) AND (?11==0 OR d IS ?10) AND
  186832. ** )
  186833. **
  186834. ** For each column in the table, there are three variables to bind:
  186835. **
  186836. ** ?(i*3+1) The old.* value of the column, if any.
  186837. ** ?(i*3+2) A boolean flag indicating that the value is being modified.
  186838. ** ?(i*3+3) The new.* value of the column, if any.
  186839. **
  186840. ** Also, a boolean flag that, if set to true, causes the statement to update
  186841. ** a row even if the non-PK values do not match. This is required if the
  186842. ** conflict-handler is invoked with CHANGESET_DATA and returns
  186843. ** CHANGESET_REPLACE. This is variable "?(nCol*3+1)".
  186844. **
  186845. ** If successful, SQLITE_OK is returned and SessionApplyCtx.pUpdate is left
  186846. ** pointing to the prepared version of the SQL statement.
  186847. */
  186848. static int sessionUpdateRow(
  186849. sqlite3 *db, /* Database handle */
  186850. const char *zTab, /* Table name */
  186851. SessionApplyCtx *p /* Session changeset-apply context */
  186852. ){
  186853. int rc = SQLITE_OK;
  186854. int i;
  186855. const char *zSep = "";
  186856. SessionBuffer buf = {0, 0, 0};
  186857. /* Append "UPDATE tbl SET " */
  186858. sessionAppendStr(&buf, "UPDATE ", &rc);
  186859. sessionAppendIdent(&buf, zTab, &rc);
  186860. sessionAppendStr(&buf, " SET ", &rc);
  186861. /* Append the assignments */
  186862. for(i=0; i<p->nCol; i++){
  186863. sessionAppendStr(&buf, zSep, &rc);
  186864. sessionAppendIdent(&buf, p->azCol[i], &rc);
  186865. sessionAppendStr(&buf, " = CASE WHEN ?", &rc);
  186866. sessionAppendInteger(&buf, i*3+2, &rc);
  186867. sessionAppendStr(&buf, " THEN ?", &rc);
  186868. sessionAppendInteger(&buf, i*3+3, &rc);
  186869. sessionAppendStr(&buf, " ELSE ", &rc);
  186870. sessionAppendIdent(&buf, p->azCol[i], &rc);
  186871. sessionAppendStr(&buf, " END", &rc);
  186872. zSep = ", ";
  186873. }
  186874. /* Append the PK part of the WHERE clause */
  186875. sessionAppendStr(&buf, " WHERE ", &rc);
  186876. for(i=0; i<p->nCol; i++){
  186877. if( p->abPK[i] ){
  186878. sessionAppendIdent(&buf, p->azCol[i], &rc);
  186879. sessionAppendStr(&buf, " = ?", &rc);
  186880. sessionAppendInteger(&buf, i*3+1, &rc);
  186881. sessionAppendStr(&buf, " AND ", &rc);
  186882. }
  186883. }
  186884. /* Append the non-PK part of the WHERE clause */
  186885. sessionAppendStr(&buf, " (?", &rc);
  186886. sessionAppendInteger(&buf, p->nCol*3+1, &rc);
  186887. sessionAppendStr(&buf, " OR 1", &rc);
  186888. for(i=0; i<p->nCol; i++){
  186889. if( !p->abPK[i] ){
  186890. sessionAppendStr(&buf, " AND (?", &rc);
  186891. sessionAppendInteger(&buf, i*3+2, &rc);
  186892. sessionAppendStr(&buf, "=0 OR ", &rc);
  186893. sessionAppendIdent(&buf, p->azCol[i], &rc);
  186894. sessionAppendStr(&buf, " IS ?", &rc);
  186895. sessionAppendInteger(&buf, i*3+1, &rc);
  186896. sessionAppendStr(&buf, ")", &rc);
  186897. }
  186898. }
  186899. sessionAppendStr(&buf, ")", &rc);
  186900. if( rc==SQLITE_OK ){
  186901. rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pUpdate, 0);
  186902. }
  186903. sqlite3_free(buf.aBuf);
  186904. return rc;
  186905. }
  186906. /*
  186907. ** Formulate and prepare an SQL statement to query table zTab by primary
  186908. ** key. Assuming the following table structure:
  186909. **
  186910. ** CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
  186911. **
  186912. ** The SELECT statement looks like this:
  186913. **
  186914. ** SELECT * FROM x WHERE a = ?1 AND c = ?3
  186915. **
  186916. ** If successful, SQLITE_OK is returned and SessionApplyCtx.pSelect is left
  186917. ** pointing to the prepared version of the SQL statement.
  186918. */
  186919. static int sessionSelectRow(
  186920. sqlite3 *db, /* Database handle */
  186921. const char *zTab, /* Table name */
  186922. SessionApplyCtx *p /* Session changeset-apply context */
  186923. ){
  186924. return sessionSelectStmt(
  186925. db, "main", zTab, p->nCol, p->azCol, p->abPK, &p->pSelect);
  186926. }
  186927. /*
  186928. ** Formulate and prepare an INSERT statement to add a record to table zTab.
  186929. ** For example:
  186930. **
  186931. ** INSERT INTO main."zTab" VALUES(?1, ?2, ?3 ...);
  186932. **
  186933. ** If successful, SQLITE_OK is returned and SessionApplyCtx.pInsert is left
  186934. ** pointing to the prepared version of the SQL statement.
  186935. */
  186936. static int sessionInsertRow(
  186937. sqlite3 *db, /* Database handle */
  186938. const char *zTab, /* Table name */
  186939. SessionApplyCtx *p /* Session changeset-apply context */
  186940. ){
  186941. int rc = SQLITE_OK;
  186942. int i;
  186943. SessionBuffer buf = {0, 0, 0};
  186944. sessionAppendStr(&buf, "INSERT INTO main.", &rc);
  186945. sessionAppendIdent(&buf, zTab, &rc);
  186946. sessionAppendStr(&buf, "(", &rc);
  186947. for(i=0; i<p->nCol; i++){
  186948. if( i!=0 ) sessionAppendStr(&buf, ", ", &rc);
  186949. sessionAppendIdent(&buf, p->azCol[i], &rc);
  186950. }
  186951. sessionAppendStr(&buf, ") VALUES(?", &rc);
  186952. for(i=1; i<p->nCol; i++){
  186953. sessionAppendStr(&buf, ", ?", &rc);
  186954. }
  186955. sessionAppendStr(&buf, ")", &rc);
  186956. if( rc==SQLITE_OK ){
  186957. rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pInsert, 0);
  186958. }
  186959. sqlite3_free(buf.aBuf);
  186960. return rc;
  186961. }
  186962. static int sessionPrepare(sqlite3 *db, sqlite3_stmt **pp, const char *zSql){
  186963. return sqlite3_prepare_v2(db, zSql, -1, pp, 0);
  186964. }
  186965. /*
  186966. ** Prepare statements for applying changes to the sqlite_stat1 table.
  186967. ** These are similar to those created by sessionSelectRow(),
  186968. ** sessionInsertRow(), sessionUpdateRow() and sessionDeleteRow() for
  186969. ** other tables.
  186970. */
  186971. static int sessionStat1Sql(sqlite3 *db, SessionApplyCtx *p){
  186972. int rc = sessionSelectRow(db, "sqlite_stat1", p);
  186973. if( rc==SQLITE_OK ){
  186974. rc = sessionPrepare(db, &p->pInsert,
  186975. "INSERT INTO main.sqlite_stat1 VALUES(?1, "
  186976. "CASE WHEN length(?2)=0 AND typeof(?2)='blob' THEN NULL ELSE ?2 END, "
  186977. "?3)"
  186978. );
  186979. }
  186980. if( rc==SQLITE_OK ){
  186981. rc = sessionPrepare(db, &p->pUpdate,
  186982. "UPDATE main.sqlite_stat1 SET "
  186983. "tbl = CASE WHEN ?2 THEN ?3 ELSE tbl END, "
  186984. "idx = CASE WHEN ?5 THEN ?6 ELSE idx END, "
  186985. "stat = CASE WHEN ?8 THEN ?9 ELSE stat END "
  186986. "WHERE tbl=?1 AND idx IS "
  186987. "CASE WHEN length(?4)=0 AND typeof(?4)='blob' THEN NULL ELSE ?4 END "
  186988. "AND (?10 OR ?8=0 OR stat IS ?7)"
  186989. );
  186990. }
  186991. if( rc==SQLITE_OK ){
  186992. rc = sessionPrepare(db, &p->pDelete,
  186993. "DELETE FROM main.sqlite_stat1 WHERE tbl=?1 AND idx IS "
  186994. "CASE WHEN length(?2)=0 AND typeof(?2)='blob' THEN NULL ELSE ?2 END "
  186995. "AND (?4 OR stat IS ?3)"
  186996. );
  186997. }
  186998. return rc;
  186999. }
  187000. /*
  187001. ** A wrapper around sqlite3_bind_value() that detects an extra problem.
  187002. ** See comments in the body of this function for details.
  187003. */
  187004. static int sessionBindValue(
  187005. sqlite3_stmt *pStmt, /* Statement to bind value to */
  187006. int i, /* Parameter number to bind to */
  187007. sqlite3_value *pVal /* Value to bind */
  187008. ){
  187009. int eType = sqlite3_value_type(pVal);
  187010. /* COVERAGE: The (pVal->z==0) branch is never true using current versions
  187011. ** of SQLite. If a malloc fails in an sqlite3_value_xxx() function, either
  187012. ** the (pVal->z) variable remains as it was or the type of the value is
  187013. ** set to SQLITE_NULL. */
  187014. if( (eType==SQLITE_TEXT || eType==SQLITE_BLOB) && pVal->z==0 ){
  187015. /* This condition occurs when an earlier OOM in a call to
  187016. ** sqlite3_value_text() or sqlite3_value_blob() (perhaps from within
  187017. ** a conflict-handler) has zeroed the pVal->z pointer. Return NOMEM. */
  187018. return SQLITE_NOMEM;
  187019. }
  187020. return sqlite3_bind_value(pStmt, i, pVal);
  187021. }
  187022. /*
  187023. ** Iterator pIter must point to an SQLITE_INSERT entry. This function
  187024. ** transfers new.* values from the current iterator entry to statement
  187025. ** pStmt. The table being inserted into has nCol columns.
  187026. **
  187027. ** New.* value $i from the iterator is bound to variable ($i+1) of
  187028. ** statement pStmt. If parameter abPK is NULL, all values from 0 to (nCol-1)
  187029. ** are transfered to the statement. Otherwise, if abPK is not NULL, it points
  187030. ** to an array nCol elements in size. In this case only those values for
  187031. ** which abPK[$i] is true are read from the iterator and bound to the
  187032. ** statement.
  187033. **
  187034. ** An SQLite error code is returned if an error occurs. Otherwise, SQLITE_OK.
  187035. */
  187036. static int sessionBindRow(
  187037. sqlite3_changeset_iter *pIter, /* Iterator to read values from */
  187038. int(*xValue)(sqlite3_changeset_iter *, int, sqlite3_value **),
  187039. int nCol, /* Number of columns */
  187040. u8 *abPK, /* If not NULL, bind only if true */
  187041. sqlite3_stmt *pStmt /* Bind values to this statement */
  187042. ){
  187043. int i;
  187044. int rc = SQLITE_OK;
  187045. /* Neither sqlite3changeset_old or sqlite3changeset_new can fail if the
  187046. ** argument iterator points to a suitable entry. Make sure that xValue
  187047. ** is one of these to guarantee that it is safe to ignore the return
  187048. ** in the code below. */
  187049. assert( xValue==sqlite3changeset_old || xValue==sqlite3changeset_new );
  187050. for(i=0; rc==SQLITE_OK && i<nCol; i++){
  187051. if( !abPK || abPK[i] ){
  187052. sqlite3_value *pVal;
  187053. (void)xValue(pIter, i, &pVal);
  187054. if( pVal==0 ){
  187055. /* The value in the changeset was "undefined". This indicates a
  187056. ** corrupt changeset blob. */
  187057. rc = SQLITE_CORRUPT_BKPT;
  187058. }else{
  187059. rc = sessionBindValue(pStmt, i+1, pVal);
  187060. }
  187061. }
  187062. }
  187063. return rc;
  187064. }
  187065. /*
  187066. ** SQL statement pSelect is as generated by the sessionSelectRow() function.
  187067. ** This function binds the primary key values from the change that changeset
  187068. ** iterator pIter points to to the SELECT and attempts to seek to the table
  187069. ** entry. If a row is found, the SELECT statement left pointing at the row
  187070. ** and SQLITE_ROW is returned. Otherwise, if no row is found and no error
  187071. ** has occured, the statement is reset and SQLITE_OK is returned. If an
  187072. ** error occurs, the statement is reset and an SQLite error code is returned.
  187073. **
  187074. ** If this function returns SQLITE_ROW, the caller must eventually reset()
  187075. ** statement pSelect. If any other value is returned, the statement does
  187076. ** not require a reset().
  187077. **
  187078. ** If the iterator currently points to an INSERT record, bind values from the
  187079. ** new.* record to the SELECT statement. Or, if it points to a DELETE or
  187080. ** UPDATE, bind values from the old.* record.
  187081. */
  187082. static int sessionSeekToRow(
  187083. sqlite3 *db, /* Database handle */
  187084. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  187085. u8 *abPK, /* Primary key flags array */
  187086. sqlite3_stmt *pSelect /* SELECT statement from sessionSelectRow() */
  187087. ){
  187088. int rc; /* Return code */
  187089. int nCol; /* Number of columns in table */
  187090. int op; /* Changset operation (SQLITE_UPDATE etc.) */
  187091. const char *zDummy; /* Unused */
  187092. sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
  187093. rc = sessionBindRow(pIter,
  187094. op==SQLITE_INSERT ? sqlite3changeset_new : sqlite3changeset_old,
  187095. nCol, abPK, pSelect
  187096. );
  187097. if( rc==SQLITE_OK ){
  187098. rc = sqlite3_step(pSelect);
  187099. if( rc!=SQLITE_ROW ) rc = sqlite3_reset(pSelect);
  187100. }
  187101. return rc;
  187102. }
  187103. /*
  187104. ** This function is called from within sqlite3changeset_apply_v2() when
  187105. ** a conflict is encountered and resolved using conflict resolution
  187106. ** mode eType (either SQLITE_CHANGESET_OMIT or SQLITE_CHANGESET_REPLACE)..
  187107. ** It adds a conflict resolution record to the buffer in
  187108. ** SessionApplyCtx.rebase, which will eventually be returned to the caller
  187109. ** of apply_v2() as the "rebase" buffer.
  187110. **
  187111. ** Return SQLITE_OK if successful, or an SQLite error code otherwise.
  187112. */
  187113. static int sessionRebaseAdd(
  187114. SessionApplyCtx *p, /* Apply context */
  187115. int eType, /* Conflict resolution (OMIT or REPLACE) */
  187116. sqlite3_changeset_iter *pIter /* Iterator pointing at current change */
  187117. ){
  187118. int rc = SQLITE_OK;
  187119. if( p->bRebase ){
  187120. int i;
  187121. int eOp = pIter->op;
  187122. if( p->bRebaseStarted==0 ){
  187123. /* Append a table-header to the rebase buffer */
  187124. const char *zTab = pIter->zTab;
  187125. sessionAppendByte(&p->rebase, 'T', &rc);
  187126. sessionAppendVarint(&p->rebase, p->nCol, &rc);
  187127. sessionAppendBlob(&p->rebase, p->abPK, p->nCol, &rc);
  187128. sessionAppendBlob(&p->rebase, (u8*)zTab, (int)strlen(zTab)+1, &rc);
  187129. p->bRebaseStarted = 1;
  187130. }
  187131. assert( eType==SQLITE_CHANGESET_REPLACE||eType==SQLITE_CHANGESET_OMIT );
  187132. assert( eOp==SQLITE_DELETE || eOp==SQLITE_INSERT || eOp==SQLITE_UPDATE );
  187133. sessionAppendByte(&p->rebase,
  187134. (eOp==SQLITE_DELETE ? SQLITE_DELETE : SQLITE_INSERT), &rc
  187135. );
  187136. sessionAppendByte(&p->rebase, (eType==SQLITE_CHANGESET_REPLACE), &rc);
  187137. for(i=0; i<p->nCol; i++){
  187138. sqlite3_value *pVal = 0;
  187139. if( eOp==SQLITE_DELETE || (eOp==SQLITE_UPDATE && p->abPK[i]) ){
  187140. sqlite3changeset_old(pIter, i, &pVal);
  187141. }else{
  187142. sqlite3changeset_new(pIter, i, &pVal);
  187143. }
  187144. sessionAppendValue(&p->rebase, pVal, &rc);
  187145. }
  187146. }
  187147. return rc;
  187148. }
  187149. /*
  187150. ** Invoke the conflict handler for the change that the changeset iterator
  187151. ** currently points to.
  187152. **
  187153. ** Argument eType must be either CHANGESET_DATA or CHANGESET_CONFLICT.
  187154. ** If argument pbReplace is NULL, then the type of conflict handler invoked
  187155. ** depends solely on eType, as follows:
  187156. **
  187157. ** eType value Value passed to xConflict
  187158. ** -------------------------------------------------
  187159. ** CHANGESET_DATA CHANGESET_NOTFOUND
  187160. ** CHANGESET_CONFLICT CHANGESET_CONSTRAINT
  187161. **
  187162. ** Or, if pbReplace is not NULL, then an attempt is made to find an existing
  187163. ** record with the same primary key as the record about to be deleted, updated
  187164. ** or inserted. If such a record can be found, it is available to the conflict
  187165. ** handler as the "conflicting" record. In this case the type of conflict
  187166. ** handler invoked is as follows:
  187167. **
  187168. ** eType value PK Record found? Value passed to xConflict
  187169. ** ----------------------------------------------------------------
  187170. ** CHANGESET_DATA Yes CHANGESET_DATA
  187171. ** CHANGESET_DATA No CHANGESET_NOTFOUND
  187172. ** CHANGESET_CONFLICT Yes CHANGESET_CONFLICT
  187173. ** CHANGESET_CONFLICT No CHANGESET_CONSTRAINT
  187174. **
  187175. ** If pbReplace is not NULL, and a record with a matching PK is found, and
  187176. ** the conflict handler function returns SQLITE_CHANGESET_REPLACE, *pbReplace
  187177. ** is set to non-zero before returning SQLITE_OK.
  187178. **
  187179. ** If the conflict handler returns SQLITE_CHANGESET_ABORT, SQLITE_ABORT is
  187180. ** returned. Or, if the conflict handler returns an invalid value,
  187181. ** SQLITE_MISUSE. If the conflict handler returns SQLITE_CHANGESET_OMIT,
  187182. ** this function returns SQLITE_OK.
  187183. */
  187184. static int sessionConflictHandler(
  187185. int eType, /* Either CHANGESET_DATA or CONFLICT */
  187186. SessionApplyCtx *p, /* changeset_apply() context */
  187187. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  187188. int(*xConflict)(void *, int, sqlite3_changeset_iter*),
  187189. void *pCtx, /* First argument for conflict handler */
  187190. int *pbReplace /* OUT: Set to true if PK row is found */
  187191. ){
  187192. int res = 0; /* Value returned by conflict handler */
  187193. int rc;
  187194. int nCol;
  187195. int op;
  187196. const char *zDummy;
  187197. sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
  187198. assert( eType==SQLITE_CHANGESET_CONFLICT || eType==SQLITE_CHANGESET_DATA );
  187199. assert( SQLITE_CHANGESET_CONFLICT+1==SQLITE_CHANGESET_CONSTRAINT );
  187200. assert( SQLITE_CHANGESET_DATA+1==SQLITE_CHANGESET_NOTFOUND );
  187201. /* Bind the new.* PRIMARY KEY values to the SELECT statement. */
  187202. if( pbReplace ){
  187203. rc = sessionSeekToRow(p->db, pIter, p->abPK, p->pSelect);
  187204. }else{
  187205. rc = SQLITE_OK;
  187206. }
  187207. if( rc==SQLITE_ROW ){
  187208. /* There exists another row with the new.* primary key. */
  187209. pIter->pConflict = p->pSelect;
  187210. res = xConflict(pCtx, eType, pIter);
  187211. pIter->pConflict = 0;
  187212. rc = sqlite3_reset(p->pSelect);
  187213. }else if( rc==SQLITE_OK ){
  187214. if( p->bDeferConstraints && eType==SQLITE_CHANGESET_CONFLICT ){
  187215. /* Instead of invoking the conflict handler, append the change blob
  187216. ** to the SessionApplyCtx.constraints buffer. */
  187217. u8 *aBlob = &pIter->in.aData[pIter->in.iCurrent];
  187218. int nBlob = pIter->in.iNext - pIter->in.iCurrent;
  187219. sessionAppendBlob(&p->constraints, aBlob, nBlob, &rc);
  187220. return SQLITE_OK;
  187221. }else{
  187222. /* No other row with the new.* primary key. */
  187223. res = xConflict(pCtx, eType+1, pIter);
  187224. if( res==SQLITE_CHANGESET_REPLACE ) rc = SQLITE_MISUSE;
  187225. }
  187226. }
  187227. if( rc==SQLITE_OK ){
  187228. switch( res ){
  187229. case SQLITE_CHANGESET_REPLACE:
  187230. assert( pbReplace );
  187231. *pbReplace = 1;
  187232. break;
  187233. case SQLITE_CHANGESET_OMIT:
  187234. break;
  187235. case SQLITE_CHANGESET_ABORT:
  187236. rc = SQLITE_ABORT;
  187237. break;
  187238. default:
  187239. rc = SQLITE_MISUSE;
  187240. break;
  187241. }
  187242. if( rc==SQLITE_OK ){
  187243. rc = sessionRebaseAdd(p, res, pIter);
  187244. }
  187245. }
  187246. return rc;
  187247. }
  187248. /*
  187249. ** Attempt to apply the change that the iterator passed as the first argument
  187250. ** currently points to to the database. If a conflict is encountered, invoke
  187251. ** the conflict handler callback.
  187252. **
  187253. ** If argument pbRetry is NULL, then ignore any CHANGESET_DATA conflict. If
  187254. ** one is encountered, update or delete the row with the matching primary key
  187255. ** instead. Or, if pbRetry is not NULL and a CHANGESET_DATA conflict occurs,
  187256. ** invoke the conflict handler. If it returns CHANGESET_REPLACE, set *pbRetry
  187257. ** to true before returning. In this case the caller will invoke this function
  187258. ** again, this time with pbRetry set to NULL.
  187259. **
  187260. ** If argument pbReplace is NULL and a CHANGESET_CONFLICT conflict is
  187261. ** encountered invoke the conflict handler with CHANGESET_CONSTRAINT instead.
  187262. ** Or, if pbReplace is not NULL, invoke it with CHANGESET_CONFLICT. If such
  187263. ** an invocation returns SQLITE_CHANGESET_REPLACE, set *pbReplace to true
  187264. ** before retrying. In this case the caller attempts to remove the conflicting
  187265. ** row before invoking this function again, this time with pbReplace set
  187266. ** to NULL.
  187267. **
  187268. ** If any conflict handler returns SQLITE_CHANGESET_ABORT, this function
  187269. ** returns SQLITE_ABORT. Otherwise, if no error occurs, SQLITE_OK is
  187270. ** returned.
  187271. */
  187272. static int sessionApplyOneOp(
  187273. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  187274. SessionApplyCtx *p, /* changeset_apply() context */
  187275. int(*xConflict)(void *, int, sqlite3_changeset_iter *),
  187276. void *pCtx, /* First argument for the conflict handler */
  187277. int *pbReplace, /* OUT: True to remove PK row and retry */
  187278. int *pbRetry /* OUT: True to retry. */
  187279. ){
  187280. const char *zDummy;
  187281. int op;
  187282. int nCol;
  187283. int rc = SQLITE_OK;
  187284. assert( p->pDelete && p->pUpdate && p->pInsert && p->pSelect );
  187285. assert( p->azCol && p->abPK );
  187286. assert( !pbReplace || *pbReplace==0 );
  187287. sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
  187288. if( op==SQLITE_DELETE ){
  187289. /* Bind values to the DELETE statement. If conflict handling is required,
  187290. ** bind values for all columns and set bound variable (nCol+1) to true.
  187291. ** Or, if conflict handling is not required, bind just the PK column
  187292. ** values and, if it exists, set (nCol+1) to false. Conflict handling
  187293. ** is not required if:
  187294. **
  187295. ** * this is a patchset, or
  187296. ** * (pbRetry==0), or
  187297. ** * all columns of the table are PK columns (in this case there is
  187298. ** no (nCol+1) variable to bind to).
  187299. */
  187300. u8 *abPK = (pIter->bPatchset ? p->abPK : 0);
  187301. rc = sessionBindRow(pIter, sqlite3changeset_old, nCol, abPK, p->pDelete);
  187302. if( rc==SQLITE_OK && sqlite3_bind_parameter_count(p->pDelete)>nCol ){
  187303. rc = sqlite3_bind_int(p->pDelete, nCol+1, (pbRetry==0 || abPK));
  187304. }
  187305. if( rc!=SQLITE_OK ) return rc;
  187306. sqlite3_step(p->pDelete);
  187307. rc = sqlite3_reset(p->pDelete);
  187308. if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){
  187309. rc = sessionConflictHandler(
  187310. SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry
  187311. );
  187312. }else if( (rc&0xff)==SQLITE_CONSTRAINT ){
  187313. rc = sessionConflictHandler(
  187314. SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0
  187315. );
  187316. }
  187317. }else if( op==SQLITE_UPDATE ){
  187318. int i;
  187319. /* Bind values to the UPDATE statement. */
  187320. for(i=0; rc==SQLITE_OK && i<nCol; i++){
  187321. sqlite3_value *pOld = sessionChangesetOld(pIter, i);
  187322. sqlite3_value *pNew = sessionChangesetNew(pIter, i);
  187323. sqlite3_bind_int(p->pUpdate, i*3+2, !!pNew);
  187324. if( pOld ){
  187325. rc = sessionBindValue(p->pUpdate, i*3+1, pOld);
  187326. }
  187327. if( rc==SQLITE_OK && pNew ){
  187328. rc = sessionBindValue(p->pUpdate, i*3+3, pNew);
  187329. }
  187330. }
  187331. if( rc==SQLITE_OK ){
  187332. sqlite3_bind_int(p->pUpdate, nCol*3+1, pbRetry==0 || pIter->bPatchset);
  187333. }
  187334. if( rc!=SQLITE_OK ) return rc;
  187335. /* Attempt the UPDATE. In the case of a NOTFOUND or DATA conflict,
  187336. ** the result will be SQLITE_OK with 0 rows modified. */
  187337. sqlite3_step(p->pUpdate);
  187338. rc = sqlite3_reset(p->pUpdate);
  187339. if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){
  187340. /* A NOTFOUND or DATA error. Search the table to see if it contains
  187341. ** a row with a matching primary key. If so, this is a DATA conflict.
  187342. ** Otherwise, if there is no primary key match, it is a NOTFOUND. */
  187343. rc = sessionConflictHandler(
  187344. SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry
  187345. );
  187346. }else if( (rc&0xff)==SQLITE_CONSTRAINT ){
  187347. /* This is always a CONSTRAINT conflict. */
  187348. rc = sessionConflictHandler(
  187349. SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0
  187350. );
  187351. }
  187352. }else{
  187353. assert( op==SQLITE_INSERT );
  187354. if( p->bStat1 ){
  187355. /* Check if there is a conflicting row. For sqlite_stat1, this needs
  187356. ** to be done using a SELECT, as there is no PRIMARY KEY in the
  187357. ** database schema to throw an exception if a duplicate is inserted. */
  187358. rc = sessionSeekToRow(p->db, pIter, p->abPK, p->pSelect);
  187359. if( rc==SQLITE_ROW ){
  187360. rc = SQLITE_CONSTRAINT;
  187361. sqlite3_reset(p->pSelect);
  187362. }
  187363. }
  187364. if( rc==SQLITE_OK ){
  187365. rc = sessionBindRow(pIter, sqlite3changeset_new, nCol, 0, p->pInsert);
  187366. if( rc!=SQLITE_OK ) return rc;
  187367. sqlite3_step(p->pInsert);
  187368. rc = sqlite3_reset(p->pInsert);
  187369. }
  187370. if( (rc&0xff)==SQLITE_CONSTRAINT ){
  187371. rc = sessionConflictHandler(
  187372. SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, pbReplace
  187373. );
  187374. }
  187375. }
  187376. return rc;
  187377. }
  187378. /*
  187379. ** Attempt to apply the change that the iterator passed as the first argument
  187380. ** currently points to to the database. If a conflict is encountered, invoke
  187381. ** the conflict handler callback.
  187382. **
  187383. ** The difference between this function and sessionApplyOne() is that this
  187384. ** function handles the case where the conflict-handler is invoked and
  187385. ** returns SQLITE_CHANGESET_REPLACE - indicating that the change should be
  187386. ** retried in some manner.
  187387. */
  187388. static int sessionApplyOneWithRetry(
  187389. sqlite3 *db, /* Apply change to "main" db of this handle */
  187390. sqlite3_changeset_iter *pIter, /* Changeset iterator to read change from */
  187391. SessionApplyCtx *pApply, /* Apply context */
  187392. int(*xConflict)(void*, int, sqlite3_changeset_iter*),
  187393. void *pCtx /* First argument passed to xConflict */
  187394. ){
  187395. int bReplace = 0;
  187396. int bRetry = 0;
  187397. int rc;
  187398. rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, &bReplace, &bRetry);
  187399. if( rc==SQLITE_OK ){
  187400. /* If the bRetry flag is set, the change has not been applied due to an
  187401. ** SQLITE_CHANGESET_DATA problem (i.e. this is an UPDATE or DELETE and
  187402. ** a row with the correct PK is present in the db, but one or more other
  187403. ** fields do not contain the expected values) and the conflict handler
  187404. ** returned SQLITE_CHANGESET_REPLACE. In this case retry the operation,
  187405. ** but pass NULL as the final argument so that sessionApplyOneOp() ignores
  187406. ** the SQLITE_CHANGESET_DATA problem. */
  187407. if( bRetry ){
  187408. assert( pIter->op==SQLITE_UPDATE || pIter->op==SQLITE_DELETE );
  187409. rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);
  187410. }
  187411. /* If the bReplace flag is set, the change is an INSERT that has not
  187412. ** been performed because the database already contains a row with the
  187413. ** specified primary key and the conflict handler returned
  187414. ** SQLITE_CHANGESET_REPLACE. In this case remove the conflicting row
  187415. ** before reattempting the INSERT. */
  187416. else if( bReplace ){
  187417. assert( pIter->op==SQLITE_INSERT );
  187418. rc = sqlite3_exec(db, "SAVEPOINT replace_op", 0, 0, 0);
  187419. if( rc==SQLITE_OK ){
  187420. rc = sessionBindRow(pIter,
  187421. sqlite3changeset_new, pApply->nCol, pApply->abPK, pApply->pDelete);
  187422. sqlite3_bind_int(pApply->pDelete, pApply->nCol+1, 1);
  187423. }
  187424. if( rc==SQLITE_OK ){
  187425. sqlite3_step(pApply->pDelete);
  187426. rc = sqlite3_reset(pApply->pDelete);
  187427. }
  187428. if( rc==SQLITE_OK ){
  187429. rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);
  187430. }
  187431. if( rc==SQLITE_OK ){
  187432. rc = sqlite3_exec(db, "RELEASE replace_op", 0, 0, 0);
  187433. }
  187434. }
  187435. }
  187436. return rc;
  187437. }
  187438. /*
  187439. ** Retry the changes accumulated in the pApply->constraints buffer.
  187440. */
  187441. static int sessionRetryConstraints(
  187442. sqlite3 *db,
  187443. int bPatchset,
  187444. const char *zTab,
  187445. SessionApplyCtx *pApply,
  187446. int(*xConflict)(void*, int, sqlite3_changeset_iter*),
  187447. void *pCtx /* First argument passed to xConflict */
  187448. ){
  187449. int rc = SQLITE_OK;
  187450. while( pApply->constraints.nBuf ){
  187451. sqlite3_changeset_iter *pIter2 = 0;
  187452. SessionBuffer cons = pApply->constraints;
  187453. memset(&pApply->constraints, 0, sizeof(SessionBuffer));
  187454. rc = sessionChangesetStart(&pIter2, 0, 0, cons.nBuf, cons.aBuf, 0);
  187455. if( rc==SQLITE_OK ){
  187456. size_t nByte = 2*pApply->nCol*sizeof(sqlite3_value*);
  187457. int rc2;
  187458. pIter2->bPatchset = bPatchset;
  187459. pIter2->zTab = (char*)zTab;
  187460. pIter2->nCol = pApply->nCol;
  187461. pIter2->abPK = pApply->abPK;
  187462. sessionBufferGrow(&pIter2->tblhdr, nByte, &rc);
  187463. pIter2->apValue = (sqlite3_value**)pIter2->tblhdr.aBuf;
  187464. if( rc==SQLITE_OK ) memset(pIter2->apValue, 0, nByte);
  187465. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter2) ){
  187466. rc = sessionApplyOneWithRetry(db, pIter2, pApply, xConflict, pCtx);
  187467. }
  187468. rc2 = sqlite3changeset_finalize(pIter2);
  187469. if( rc==SQLITE_OK ) rc = rc2;
  187470. }
  187471. assert( pApply->bDeferConstraints || pApply->constraints.nBuf==0 );
  187472. sqlite3_free(cons.aBuf);
  187473. if( rc!=SQLITE_OK ) break;
  187474. if( pApply->constraints.nBuf>=cons.nBuf ){
  187475. /* No progress was made on the last round. */
  187476. pApply->bDeferConstraints = 0;
  187477. }
  187478. }
  187479. return rc;
  187480. }
  187481. /*
  187482. ** Argument pIter is a changeset iterator that has been initialized, but
  187483. ** not yet passed to sqlite3changeset_next(). This function applies the
  187484. ** changeset to the main database attached to handle "db". The supplied
  187485. ** conflict handler callback is invoked to resolve any conflicts encountered
  187486. ** while applying the change.
  187487. */
  187488. static int sessionChangesetApply(
  187489. sqlite3 *db, /* Apply change to "main" db of this handle */
  187490. sqlite3_changeset_iter *pIter, /* Changeset to apply */
  187491. int(*xFilter)(
  187492. void *pCtx, /* Copy of sixth arg to _apply() */
  187493. const char *zTab /* Table name */
  187494. ),
  187495. int(*xConflict)(
  187496. void *pCtx, /* Copy of fifth arg to _apply() */
  187497. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  187498. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  187499. ),
  187500. void *pCtx, /* First argument passed to xConflict */
  187501. void **ppRebase, int *pnRebase, /* OUT: Rebase information */
  187502. int flags /* SESSION_APPLY_XXX flags */
  187503. ){
  187504. int schemaMismatch = 0;
  187505. int rc = SQLITE_OK; /* Return code */
  187506. const char *zTab = 0; /* Name of current table */
  187507. int nTab = 0; /* Result of sqlite3Strlen30(zTab) */
  187508. SessionApplyCtx sApply; /* changeset_apply() context object */
  187509. int bPatchset;
  187510. assert( xConflict!=0 );
  187511. pIter->in.bNoDiscard = 1;
  187512. memset(&sApply, 0, sizeof(sApply));
  187513. sApply.bRebase = (ppRebase && pnRebase);
  187514. sqlite3_mutex_enter(sqlite3_db_mutex(db));
  187515. if( (flags & SQLITE_CHANGESETAPPLY_NOSAVEPOINT)==0 ){
  187516. rc = sqlite3_exec(db, "SAVEPOINT changeset_apply", 0, 0, 0);
  187517. }
  187518. if( rc==SQLITE_OK ){
  187519. rc = sqlite3_exec(db, "PRAGMA defer_foreign_keys = 1", 0, 0, 0);
  187520. }
  187521. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter) ){
  187522. int nCol;
  187523. int op;
  187524. const char *zNew;
  187525. sqlite3changeset_op(pIter, &zNew, &nCol, &op, 0);
  187526. if( zTab==0 || sqlite3_strnicmp(zNew, zTab, nTab+1) ){
  187527. u8 *abPK;
  187528. rc = sessionRetryConstraints(
  187529. db, pIter->bPatchset, zTab, &sApply, xConflict, pCtx
  187530. );
  187531. if( rc!=SQLITE_OK ) break;
  187532. sqlite3_free((char*)sApply.azCol); /* cast works around VC++ bug */
  187533. sqlite3_finalize(sApply.pDelete);
  187534. sqlite3_finalize(sApply.pUpdate);
  187535. sqlite3_finalize(sApply.pInsert);
  187536. sqlite3_finalize(sApply.pSelect);
  187537. sApply.db = db;
  187538. sApply.pDelete = 0;
  187539. sApply.pUpdate = 0;
  187540. sApply.pInsert = 0;
  187541. sApply.pSelect = 0;
  187542. sApply.nCol = 0;
  187543. sApply.azCol = 0;
  187544. sApply.abPK = 0;
  187545. sApply.bStat1 = 0;
  187546. sApply.bDeferConstraints = 1;
  187547. sApply.bRebaseStarted = 0;
  187548. memset(&sApply.constraints, 0, sizeof(SessionBuffer));
  187549. /* If an xFilter() callback was specified, invoke it now. If the
  187550. ** xFilter callback returns zero, skip this table. If it returns
  187551. ** non-zero, proceed. */
  187552. schemaMismatch = (xFilter && (0==xFilter(pCtx, zNew)));
  187553. if( schemaMismatch ){
  187554. zTab = sqlite3_mprintf("%s", zNew);
  187555. if( zTab==0 ){
  187556. rc = SQLITE_NOMEM;
  187557. break;
  187558. }
  187559. nTab = (int)strlen(zTab);
  187560. sApply.azCol = (const char **)zTab;
  187561. }else{
  187562. int nMinCol = 0;
  187563. int i;
  187564. sqlite3changeset_pk(pIter, &abPK, 0);
  187565. rc = sessionTableInfo(
  187566. db, "main", zNew, &sApply.nCol, &zTab, &sApply.azCol, &sApply.abPK
  187567. );
  187568. if( rc!=SQLITE_OK ) break;
  187569. for(i=0; i<sApply.nCol; i++){
  187570. if( sApply.abPK[i] ) nMinCol = i+1;
  187571. }
  187572. if( sApply.nCol==0 ){
  187573. schemaMismatch = 1;
  187574. sqlite3_log(SQLITE_SCHEMA,
  187575. "sqlite3changeset_apply(): no such table: %s", zTab
  187576. );
  187577. }
  187578. else if( sApply.nCol<nCol ){
  187579. schemaMismatch = 1;
  187580. sqlite3_log(SQLITE_SCHEMA,
  187581. "sqlite3changeset_apply(): table %s has %d columns, "
  187582. "expected %d or more",
  187583. zTab, sApply.nCol, nCol
  187584. );
  187585. }
  187586. else if( nCol<nMinCol || memcmp(sApply.abPK, abPK, nCol)!=0 ){
  187587. schemaMismatch = 1;
  187588. sqlite3_log(SQLITE_SCHEMA, "sqlite3changeset_apply(): "
  187589. "primary key mismatch for table %s", zTab
  187590. );
  187591. }
  187592. else{
  187593. sApply.nCol = nCol;
  187594. if( 0==sqlite3_stricmp(zTab, "sqlite_stat1") ){
  187595. if( (rc = sessionStat1Sql(db, &sApply) ) ){
  187596. break;
  187597. }
  187598. sApply.bStat1 = 1;
  187599. }else{
  187600. if((rc = sessionSelectRow(db, zTab, &sApply))
  187601. || (rc = sessionUpdateRow(db, zTab, &sApply))
  187602. || (rc = sessionDeleteRow(db, zTab, &sApply))
  187603. || (rc = sessionInsertRow(db, zTab, &sApply))
  187604. ){
  187605. break;
  187606. }
  187607. sApply.bStat1 = 0;
  187608. }
  187609. }
  187610. nTab = sqlite3Strlen30(zTab);
  187611. }
  187612. }
  187613. /* If there is a schema mismatch on the current table, proceed to the
  187614. ** next change. A log message has already been issued. */
  187615. if( schemaMismatch ) continue;
  187616. rc = sessionApplyOneWithRetry(db, pIter, &sApply, xConflict, pCtx);
  187617. }
  187618. bPatchset = pIter->bPatchset;
  187619. if( rc==SQLITE_OK ){
  187620. rc = sqlite3changeset_finalize(pIter);
  187621. }else{
  187622. sqlite3changeset_finalize(pIter);
  187623. }
  187624. if( rc==SQLITE_OK ){
  187625. rc = sessionRetryConstraints(db, bPatchset, zTab, &sApply, xConflict, pCtx);
  187626. }
  187627. if( rc==SQLITE_OK ){
  187628. int nFk, notUsed;
  187629. sqlite3_db_status(db, SQLITE_DBSTATUS_DEFERRED_FKS, &nFk, &notUsed, 0);
  187630. if( nFk!=0 ){
  187631. int res = SQLITE_CHANGESET_ABORT;
  187632. sqlite3_changeset_iter sIter;
  187633. memset(&sIter, 0, sizeof(sIter));
  187634. sIter.nCol = nFk;
  187635. res = xConflict(pCtx, SQLITE_CHANGESET_FOREIGN_KEY, &sIter);
  187636. if( res!=SQLITE_CHANGESET_OMIT ){
  187637. rc = SQLITE_CONSTRAINT;
  187638. }
  187639. }
  187640. }
  187641. sqlite3_exec(db, "PRAGMA defer_foreign_keys = 0", 0, 0, 0);
  187642. if( (flags & SQLITE_CHANGESETAPPLY_NOSAVEPOINT)==0 ){
  187643. if( rc==SQLITE_OK ){
  187644. rc = sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0);
  187645. }else{
  187646. sqlite3_exec(db, "ROLLBACK TO changeset_apply", 0, 0, 0);
  187647. sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0);
  187648. }
  187649. }
  187650. assert( sApply.bRebase || sApply.rebase.nBuf==0 );
  187651. if( rc==SQLITE_OK && bPatchset==0 && sApply.bRebase ){
  187652. *ppRebase = (void*)sApply.rebase.aBuf;
  187653. *pnRebase = sApply.rebase.nBuf;
  187654. sApply.rebase.aBuf = 0;
  187655. }
  187656. sqlite3_finalize(sApply.pInsert);
  187657. sqlite3_finalize(sApply.pDelete);
  187658. sqlite3_finalize(sApply.pUpdate);
  187659. sqlite3_finalize(sApply.pSelect);
  187660. sqlite3_free((char*)sApply.azCol); /* cast works around VC++ bug */
  187661. sqlite3_free((char*)sApply.constraints.aBuf);
  187662. sqlite3_free((char*)sApply.rebase.aBuf);
  187663. sqlite3_mutex_leave(sqlite3_db_mutex(db));
  187664. return rc;
  187665. }
  187666. /*
  187667. ** Apply the changeset passed via pChangeset/nChangeset to the main
  187668. ** database attached to handle "db".
  187669. */
  187670. SQLITE_API int sqlite3changeset_apply_v2(
  187671. sqlite3 *db, /* Apply change to "main" db of this handle */
  187672. int nChangeset, /* Size of changeset in bytes */
  187673. void *pChangeset, /* Changeset blob */
  187674. int(*xFilter)(
  187675. void *pCtx, /* Copy of sixth arg to _apply() */
  187676. const char *zTab /* Table name */
  187677. ),
  187678. int(*xConflict)(
  187679. void *pCtx, /* Copy of sixth arg to _apply() */
  187680. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  187681. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  187682. ),
  187683. void *pCtx, /* First argument passed to xConflict */
  187684. void **ppRebase, int *pnRebase,
  187685. int flags
  187686. ){
  187687. sqlite3_changeset_iter *pIter; /* Iterator to skip through changeset */
  187688. int bInverse = !!(flags & SQLITE_CHANGESETAPPLY_INVERT);
  187689. int rc = sessionChangesetStart(&pIter, 0, 0, nChangeset, pChangeset,bInverse);
  187690. if( rc==SQLITE_OK ){
  187691. rc = sessionChangesetApply(
  187692. db, pIter, xFilter, xConflict, pCtx, ppRebase, pnRebase, flags
  187693. );
  187694. }
  187695. return rc;
  187696. }
  187697. /*
  187698. ** Apply the changeset passed via pChangeset/nChangeset to the main database
  187699. ** attached to handle "db". Invoke the supplied conflict handler callback
  187700. ** to resolve any conflicts encountered while applying the change.
  187701. */
  187702. SQLITE_API int sqlite3changeset_apply(
  187703. sqlite3 *db, /* Apply change to "main" db of this handle */
  187704. int nChangeset, /* Size of changeset in bytes */
  187705. void *pChangeset, /* Changeset blob */
  187706. int(*xFilter)(
  187707. void *pCtx, /* Copy of sixth arg to _apply() */
  187708. const char *zTab /* Table name */
  187709. ),
  187710. int(*xConflict)(
  187711. void *pCtx, /* Copy of fifth arg to _apply() */
  187712. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  187713. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  187714. ),
  187715. void *pCtx /* First argument passed to xConflict */
  187716. ){
  187717. return sqlite3changeset_apply_v2(
  187718. db, nChangeset, pChangeset, xFilter, xConflict, pCtx, 0, 0, 0
  187719. );
  187720. }
  187721. /*
  187722. ** Apply the changeset passed via xInput/pIn to the main database
  187723. ** attached to handle "db". Invoke the supplied conflict handler callback
  187724. ** to resolve any conflicts encountered while applying the change.
  187725. */
  187726. SQLITE_API int sqlite3changeset_apply_v2_strm(
  187727. sqlite3 *db, /* Apply change to "main" db of this handle */
  187728. int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
  187729. void *pIn, /* First arg for xInput */
  187730. int(*xFilter)(
  187731. void *pCtx, /* Copy of sixth arg to _apply() */
  187732. const char *zTab /* Table name */
  187733. ),
  187734. int(*xConflict)(
  187735. void *pCtx, /* Copy of sixth arg to _apply() */
  187736. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  187737. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  187738. ),
  187739. void *pCtx, /* First argument passed to xConflict */
  187740. void **ppRebase, int *pnRebase,
  187741. int flags
  187742. ){
  187743. sqlite3_changeset_iter *pIter; /* Iterator to skip through changeset */
  187744. int bInverse = !!(flags & SQLITE_CHANGESETAPPLY_INVERT);
  187745. int rc = sessionChangesetStart(&pIter, xInput, pIn, 0, 0, bInverse);
  187746. if( rc==SQLITE_OK ){
  187747. rc = sessionChangesetApply(
  187748. db, pIter, xFilter, xConflict, pCtx, ppRebase, pnRebase, flags
  187749. );
  187750. }
  187751. return rc;
  187752. }
  187753. SQLITE_API int sqlite3changeset_apply_strm(
  187754. sqlite3 *db, /* Apply change to "main" db of this handle */
  187755. int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
  187756. void *pIn, /* First arg for xInput */
  187757. int(*xFilter)(
  187758. void *pCtx, /* Copy of sixth arg to _apply() */
  187759. const char *zTab /* Table name */
  187760. ),
  187761. int(*xConflict)(
  187762. void *pCtx, /* Copy of sixth arg to _apply() */
  187763. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  187764. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  187765. ),
  187766. void *pCtx /* First argument passed to xConflict */
  187767. ){
  187768. return sqlite3changeset_apply_v2_strm(
  187769. db, xInput, pIn, xFilter, xConflict, pCtx, 0, 0, 0
  187770. );
  187771. }
  187772. /*
  187773. ** sqlite3_changegroup handle.
  187774. */
  187775. struct sqlite3_changegroup {
  187776. int rc; /* Error code */
  187777. int bPatch; /* True to accumulate patchsets */
  187778. SessionTable *pList; /* List of tables in current patch */
  187779. };
  187780. /*
  187781. ** This function is called to merge two changes to the same row together as
  187782. ** part of an sqlite3changeset_concat() operation. A new change object is
  187783. ** allocated and a pointer to it stored in *ppNew.
  187784. */
  187785. static int sessionChangeMerge(
  187786. SessionTable *pTab, /* Table structure */
  187787. int bRebase, /* True for a rebase hash-table */
  187788. int bPatchset, /* True for patchsets */
  187789. SessionChange *pExist, /* Existing change */
  187790. int op2, /* Second change operation */
  187791. int bIndirect, /* True if second change is indirect */
  187792. u8 *aRec, /* Second change record */
  187793. int nRec, /* Number of bytes in aRec */
  187794. SessionChange **ppNew /* OUT: Merged change */
  187795. ){
  187796. SessionChange *pNew = 0;
  187797. int rc = SQLITE_OK;
  187798. if( !pExist ){
  187799. pNew = (SessionChange *)sqlite3_malloc64(sizeof(SessionChange) + nRec);
  187800. if( !pNew ){
  187801. return SQLITE_NOMEM;
  187802. }
  187803. memset(pNew, 0, sizeof(SessionChange));
  187804. pNew->op = op2;
  187805. pNew->bIndirect = bIndirect;
  187806. pNew->aRecord = (u8*)&pNew[1];
  187807. if( bIndirect==0 || bRebase==0 ){
  187808. pNew->nRecord = nRec;
  187809. memcpy(pNew->aRecord, aRec, nRec);
  187810. }else{
  187811. int i;
  187812. u8 *pIn = aRec;
  187813. u8 *pOut = pNew->aRecord;
  187814. for(i=0; i<pTab->nCol; i++){
  187815. int nIn = sessionSerialLen(pIn);
  187816. if( *pIn==0 ){
  187817. *pOut++ = 0;
  187818. }else if( pTab->abPK[i]==0 ){
  187819. *pOut++ = 0xFF;
  187820. }else{
  187821. memcpy(pOut, pIn, nIn);
  187822. pOut += nIn;
  187823. }
  187824. pIn += nIn;
  187825. }
  187826. pNew->nRecord = pOut - pNew->aRecord;
  187827. }
  187828. }else if( bRebase ){
  187829. if( pExist->op==SQLITE_DELETE && pExist->bIndirect ){
  187830. *ppNew = pExist;
  187831. }else{
  187832. sqlite3_int64 nByte = nRec + pExist->nRecord + sizeof(SessionChange);
  187833. pNew = (SessionChange*)sqlite3_malloc64(nByte);
  187834. if( pNew==0 ){
  187835. rc = SQLITE_NOMEM;
  187836. }else{
  187837. int i;
  187838. u8 *a1 = pExist->aRecord;
  187839. u8 *a2 = aRec;
  187840. u8 *pOut;
  187841. memset(pNew, 0, nByte);
  187842. pNew->bIndirect = bIndirect || pExist->bIndirect;
  187843. pNew->op = op2;
  187844. pOut = pNew->aRecord = (u8*)&pNew[1];
  187845. for(i=0; i<pTab->nCol; i++){
  187846. int n1 = sessionSerialLen(a1);
  187847. int n2 = sessionSerialLen(a2);
  187848. if( *a1==0xFF || (pTab->abPK[i]==0 && bIndirect) ){
  187849. *pOut++ = 0xFF;
  187850. }else if( *a2==0 ){
  187851. memcpy(pOut, a1, n1);
  187852. pOut += n1;
  187853. }else{
  187854. memcpy(pOut, a2, n2);
  187855. pOut += n2;
  187856. }
  187857. a1 += n1;
  187858. a2 += n2;
  187859. }
  187860. pNew->nRecord = pOut - pNew->aRecord;
  187861. }
  187862. sqlite3_free(pExist);
  187863. }
  187864. }else{
  187865. int op1 = pExist->op;
  187866. /*
  187867. ** op1=INSERT, op2=INSERT -> Unsupported. Discard op2.
  187868. ** op1=INSERT, op2=UPDATE -> INSERT.
  187869. ** op1=INSERT, op2=DELETE -> (none)
  187870. **
  187871. ** op1=UPDATE, op2=INSERT -> Unsupported. Discard op2.
  187872. ** op1=UPDATE, op2=UPDATE -> UPDATE.
  187873. ** op1=UPDATE, op2=DELETE -> DELETE.
  187874. **
  187875. ** op1=DELETE, op2=INSERT -> UPDATE.
  187876. ** op1=DELETE, op2=UPDATE -> Unsupported. Discard op2.
  187877. ** op1=DELETE, op2=DELETE -> Unsupported. Discard op2.
  187878. */
  187879. if( (op1==SQLITE_INSERT && op2==SQLITE_INSERT)
  187880. || (op1==SQLITE_UPDATE && op2==SQLITE_INSERT)
  187881. || (op1==SQLITE_DELETE && op2==SQLITE_UPDATE)
  187882. || (op1==SQLITE_DELETE && op2==SQLITE_DELETE)
  187883. ){
  187884. pNew = pExist;
  187885. }else if( op1==SQLITE_INSERT && op2==SQLITE_DELETE ){
  187886. sqlite3_free(pExist);
  187887. assert( pNew==0 );
  187888. }else{
  187889. u8 *aExist = pExist->aRecord;
  187890. sqlite3_int64 nByte;
  187891. u8 *aCsr;
  187892. /* Allocate a new SessionChange object. Ensure that the aRecord[]
  187893. ** buffer of the new object is large enough to hold any record that
  187894. ** may be generated by combining the input records. */
  187895. nByte = sizeof(SessionChange) + pExist->nRecord + nRec;
  187896. pNew = (SessionChange *)sqlite3_malloc64(nByte);
  187897. if( !pNew ){
  187898. sqlite3_free(pExist);
  187899. return SQLITE_NOMEM;
  187900. }
  187901. memset(pNew, 0, sizeof(SessionChange));
  187902. pNew->bIndirect = (bIndirect && pExist->bIndirect);
  187903. aCsr = pNew->aRecord = (u8 *)&pNew[1];
  187904. if( op1==SQLITE_INSERT ){ /* INSERT + UPDATE */
  187905. u8 *a1 = aRec;
  187906. assert( op2==SQLITE_UPDATE );
  187907. pNew->op = SQLITE_INSERT;
  187908. if( bPatchset==0 ) sessionSkipRecord(&a1, pTab->nCol);
  187909. sessionMergeRecord(&aCsr, pTab->nCol, aExist, a1);
  187910. }else if( op1==SQLITE_DELETE ){ /* DELETE + INSERT */
  187911. assert( op2==SQLITE_INSERT );
  187912. pNew->op = SQLITE_UPDATE;
  187913. if( bPatchset ){
  187914. memcpy(aCsr, aRec, nRec);
  187915. aCsr += nRec;
  187916. }else{
  187917. if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aExist, 0,aRec,0) ){
  187918. sqlite3_free(pNew);
  187919. pNew = 0;
  187920. }
  187921. }
  187922. }else if( op2==SQLITE_UPDATE ){ /* UPDATE + UPDATE */
  187923. u8 *a1 = aExist;
  187924. u8 *a2 = aRec;
  187925. assert( op1==SQLITE_UPDATE );
  187926. if( bPatchset==0 ){
  187927. sessionSkipRecord(&a1, pTab->nCol);
  187928. sessionSkipRecord(&a2, pTab->nCol);
  187929. }
  187930. pNew->op = SQLITE_UPDATE;
  187931. if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aRec, aExist,a1,a2) ){
  187932. sqlite3_free(pNew);
  187933. pNew = 0;
  187934. }
  187935. }else{ /* UPDATE + DELETE */
  187936. assert( op1==SQLITE_UPDATE && op2==SQLITE_DELETE );
  187937. pNew->op = SQLITE_DELETE;
  187938. if( bPatchset ){
  187939. memcpy(aCsr, aRec, nRec);
  187940. aCsr += nRec;
  187941. }else{
  187942. sessionMergeRecord(&aCsr, pTab->nCol, aRec, aExist);
  187943. }
  187944. }
  187945. if( pNew ){
  187946. pNew->nRecord = (int)(aCsr - pNew->aRecord);
  187947. }
  187948. sqlite3_free(pExist);
  187949. }
  187950. }
  187951. *ppNew = pNew;
  187952. return rc;
  187953. }
  187954. /*
  187955. ** Add all changes in the changeset traversed by the iterator passed as
  187956. ** the first argument to the changegroup hash tables.
  187957. */
  187958. static int sessionChangesetToHash(
  187959. sqlite3_changeset_iter *pIter, /* Iterator to read from */
  187960. sqlite3_changegroup *pGrp, /* Changegroup object to add changeset to */
  187961. int bRebase /* True if hash table is for rebasing */
  187962. ){
  187963. u8 *aRec;
  187964. int nRec;
  187965. int rc = SQLITE_OK;
  187966. SessionTable *pTab = 0;
  187967. while( SQLITE_ROW==sessionChangesetNext(pIter, &aRec, &nRec, 0) ){
  187968. const char *zNew;
  187969. int nCol;
  187970. int op;
  187971. int iHash;
  187972. int bIndirect;
  187973. SessionChange *pChange;
  187974. SessionChange *pExist = 0;
  187975. SessionChange **pp;
  187976. if( pGrp->pList==0 ){
  187977. pGrp->bPatch = pIter->bPatchset;
  187978. }else if( pIter->bPatchset!=pGrp->bPatch ){
  187979. rc = SQLITE_ERROR;
  187980. break;
  187981. }
  187982. sqlite3changeset_op(pIter, &zNew, &nCol, &op, &bIndirect);
  187983. if( !pTab || sqlite3_stricmp(zNew, pTab->zName) ){
  187984. /* Search the list for a matching table */
  187985. int nNew = (int)strlen(zNew);
  187986. u8 *abPK;
  187987. sqlite3changeset_pk(pIter, &abPK, 0);
  187988. for(pTab = pGrp->pList; pTab; pTab=pTab->pNext){
  187989. if( 0==sqlite3_strnicmp(pTab->zName, zNew, nNew+1) ) break;
  187990. }
  187991. if( !pTab ){
  187992. SessionTable **ppTab;
  187993. pTab = sqlite3_malloc64(sizeof(SessionTable) + nCol + nNew+1);
  187994. if( !pTab ){
  187995. rc = SQLITE_NOMEM;
  187996. break;
  187997. }
  187998. memset(pTab, 0, sizeof(SessionTable));
  187999. pTab->nCol = nCol;
  188000. pTab->abPK = (u8*)&pTab[1];
  188001. memcpy(pTab->abPK, abPK, nCol);
  188002. pTab->zName = (char*)&pTab->abPK[nCol];
  188003. memcpy(pTab->zName, zNew, nNew+1);
  188004. /* The new object must be linked on to the end of the list, not
  188005. ** simply added to the start of it. This is to ensure that the
  188006. ** tables within the output of sqlite3changegroup_output() are in
  188007. ** the right order. */
  188008. for(ppTab=&pGrp->pList; *ppTab; ppTab=&(*ppTab)->pNext);
  188009. *ppTab = pTab;
  188010. }else if( pTab->nCol!=nCol || memcmp(pTab->abPK, abPK, nCol) ){
  188011. rc = SQLITE_SCHEMA;
  188012. break;
  188013. }
  188014. }
  188015. if( sessionGrowHash(pIter->bPatchset, pTab) ){
  188016. rc = SQLITE_NOMEM;
  188017. break;
  188018. }
  188019. iHash = sessionChangeHash(
  188020. pTab, (pIter->bPatchset && op==SQLITE_DELETE), aRec, pTab->nChange
  188021. );
  188022. /* Search for existing entry. If found, remove it from the hash table.
  188023. ** Code below may link it back in.
  188024. */
  188025. for(pp=&pTab->apChange[iHash]; *pp; pp=&(*pp)->pNext){
  188026. int bPkOnly1 = 0;
  188027. int bPkOnly2 = 0;
  188028. if( pIter->bPatchset ){
  188029. bPkOnly1 = (*pp)->op==SQLITE_DELETE;
  188030. bPkOnly2 = op==SQLITE_DELETE;
  188031. }
  188032. if( sessionChangeEqual(pTab, bPkOnly1, (*pp)->aRecord, bPkOnly2, aRec) ){
  188033. pExist = *pp;
  188034. *pp = (*pp)->pNext;
  188035. pTab->nEntry--;
  188036. break;
  188037. }
  188038. }
  188039. rc = sessionChangeMerge(pTab, bRebase,
  188040. pIter->bPatchset, pExist, op, bIndirect, aRec, nRec, &pChange
  188041. );
  188042. if( rc ) break;
  188043. if( pChange ){
  188044. pChange->pNext = pTab->apChange[iHash];
  188045. pTab->apChange[iHash] = pChange;
  188046. pTab->nEntry++;
  188047. }
  188048. }
  188049. if( rc==SQLITE_OK ) rc = pIter->rc;
  188050. return rc;
  188051. }
  188052. /*
  188053. ** Serialize a changeset (or patchset) based on all changesets (or patchsets)
  188054. ** added to the changegroup object passed as the first argument.
  188055. **
  188056. ** If xOutput is not NULL, then the changeset/patchset is returned to the
  188057. ** user via one or more calls to xOutput, as with the other streaming
  188058. ** interfaces.
  188059. **
  188060. ** Or, if xOutput is NULL, then (*ppOut) is populated with a pointer to a
  188061. ** buffer containing the output changeset before this function returns. In
  188062. ** this case (*pnOut) is set to the size of the output buffer in bytes. It
  188063. ** is the responsibility of the caller to free the output buffer using
  188064. ** sqlite3_free() when it is no longer required.
  188065. **
  188066. ** If successful, SQLITE_OK is returned. Or, if an error occurs, an SQLite
  188067. ** error code. If an error occurs and xOutput is NULL, (*ppOut) and (*pnOut)
  188068. ** are both set to 0 before returning.
  188069. */
  188070. static int sessionChangegroupOutput(
  188071. sqlite3_changegroup *pGrp,
  188072. int (*xOutput)(void *pOut, const void *pData, int nData),
  188073. void *pOut,
  188074. int *pnOut,
  188075. void **ppOut
  188076. ){
  188077. int rc = SQLITE_OK;
  188078. SessionBuffer buf = {0, 0, 0};
  188079. SessionTable *pTab;
  188080. assert( xOutput==0 || (ppOut==0 && pnOut==0) );
  188081. /* Create the serialized output changeset based on the contents of the
  188082. ** hash tables attached to the SessionTable objects in list p->pList.
  188083. */
  188084. for(pTab=pGrp->pList; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
  188085. int i;
  188086. if( pTab->nEntry==0 ) continue;
  188087. sessionAppendTableHdr(&buf, pGrp->bPatch, pTab, &rc);
  188088. for(i=0; i<pTab->nChange; i++){
  188089. SessionChange *p;
  188090. for(p=pTab->apChange[i]; p; p=p->pNext){
  188091. sessionAppendByte(&buf, p->op, &rc);
  188092. sessionAppendByte(&buf, p->bIndirect, &rc);
  188093. sessionAppendBlob(&buf, p->aRecord, p->nRecord, &rc);
  188094. if( rc==SQLITE_OK && xOutput && buf.nBuf>=sessions_strm_chunk_size ){
  188095. rc = xOutput(pOut, buf.aBuf, buf.nBuf);
  188096. buf.nBuf = 0;
  188097. }
  188098. }
  188099. }
  188100. }
  188101. if( rc==SQLITE_OK ){
  188102. if( xOutput ){
  188103. if( buf.nBuf>0 ) rc = xOutput(pOut, buf.aBuf, buf.nBuf);
  188104. }else{
  188105. *ppOut = buf.aBuf;
  188106. *pnOut = buf.nBuf;
  188107. buf.aBuf = 0;
  188108. }
  188109. }
  188110. sqlite3_free(buf.aBuf);
  188111. return rc;
  188112. }
  188113. /*
  188114. ** Allocate a new, empty, sqlite3_changegroup.
  188115. */
  188116. SQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp){
  188117. int rc = SQLITE_OK; /* Return code */
  188118. sqlite3_changegroup *p; /* New object */
  188119. p = (sqlite3_changegroup*)sqlite3_malloc(sizeof(sqlite3_changegroup));
  188120. if( p==0 ){
  188121. rc = SQLITE_NOMEM;
  188122. }else{
  188123. memset(p, 0, sizeof(sqlite3_changegroup));
  188124. }
  188125. *pp = p;
  188126. return rc;
  188127. }
  188128. /*
  188129. ** Add the changeset currently stored in buffer pData, size nData bytes,
  188130. ** to changeset-group p.
  188131. */
  188132. SQLITE_API int sqlite3changegroup_add(sqlite3_changegroup *pGrp, int nData, void *pData){
  188133. sqlite3_changeset_iter *pIter; /* Iterator opened on pData/nData */
  188134. int rc; /* Return code */
  188135. rc = sqlite3changeset_start(&pIter, nData, pData);
  188136. if( rc==SQLITE_OK ){
  188137. rc = sessionChangesetToHash(pIter, pGrp, 0);
  188138. }
  188139. sqlite3changeset_finalize(pIter);
  188140. return rc;
  188141. }
  188142. /*
  188143. ** Obtain a buffer containing a changeset representing the concatenation
  188144. ** of all changesets added to the group so far.
  188145. */
  188146. SQLITE_API int sqlite3changegroup_output(
  188147. sqlite3_changegroup *pGrp,
  188148. int *pnData,
  188149. void **ppData
  188150. ){
  188151. return sessionChangegroupOutput(pGrp, 0, 0, pnData, ppData);
  188152. }
  188153. /*
  188154. ** Streaming versions of changegroup_add().
  188155. */
  188156. SQLITE_API int sqlite3changegroup_add_strm(
  188157. sqlite3_changegroup *pGrp,
  188158. int (*xInput)(void *pIn, void *pData, int *pnData),
  188159. void *pIn
  188160. ){
  188161. sqlite3_changeset_iter *pIter; /* Iterator opened on pData/nData */
  188162. int rc; /* Return code */
  188163. rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);
  188164. if( rc==SQLITE_OK ){
  188165. rc = sessionChangesetToHash(pIter, pGrp, 0);
  188166. }
  188167. sqlite3changeset_finalize(pIter);
  188168. return rc;
  188169. }
  188170. /*
  188171. ** Streaming versions of changegroup_output().
  188172. */
  188173. SQLITE_API int sqlite3changegroup_output_strm(
  188174. sqlite3_changegroup *pGrp,
  188175. int (*xOutput)(void *pOut, const void *pData, int nData),
  188176. void *pOut
  188177. ){
  188178. return sessionChangegroupOutput(pGrp, xOutput, pOut, 0, 0);
  188179. }
  188180. /*
  188181. ** Delete a changegroup object.
  188182. */
  188183. SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup *pGrp){
  188184. if( pGrp ){
  188185. sessionDeleteTable(pGrp->pList);
  188186. sqlite3_free(pGrp);
  188187. }
  188188. }
  188189. /*
  188190. ** Combine two changesets together.
  188191. */
  188192. SQLITE_API int sqlite3changeset_concat(
  188193. int nLeft, /* Number of bytes in lhs input */
  188194. void *pLeft, /* Lhs input changeset */
  188195. int nRight /* Number of bytes in rhs input */,
  188196. void *pRight, /* Rhs input changeset */
  188197. int *pnOut, /* OUT: Number of bytes in output changeset */
  188198. void **ppOut /* OUT: changeset (left <concat> right) */
  188199. ){
  188200. sqlite3_changegroup *pGrp;
  188201. int rc;
  188202. rc = sqlite3changegroup_new(&pGrp);
  188203. if( rc==SQLITE_OK ){
  188204. rc = sqlite3changegroup_add(pGrp, nLeft, pLeft);
  188205. }
  188206. if( rc==SQLITE_OK ){
  188207. rc = sqlite3changegroup_add(pGrp, nRight, pRight);
  188208. }
  188209. if( rc==SQLITE_OK ){
  188210. rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);
  188211. }
  188212. sqlite3changegroup_delete(pGrp);
  188213. return rc;
  188214. }
  188215. /*
  188216. ** Streaming version of sqlite3changeset_concat().
  188217. */
  188218. SQLITE_API int sqlite3changeset_concat_strm(
  188219. int (*xInputA)(void *pIn, void *pData, int *pnData),
  188220. void *pInA,
  188221. int (*xInputB)(void *pIn, void *pData, int *pnData),
  188222. void *pInB,
  188223. int (*xOutput)(void *pOut, const void *pData, int nData),
  188224. void *pOut
  188225. ){
  188226. sqlite3_changegroup *pGrp;
  188227. int rc;
  188228. rc = sqlite3changegroup_new(&pGrp);
  188229. if( rc==SQLITE_OK ){
  188230. rc = sqlite3changegroup_add_strm(pGrp, xInputA, pInA);
  188231. }
  188232. if( rc==SQLITE_OK ){
  188233. rc = sqlite3changegroup_add_strm(pGrp, xInputB, pInB);
  188234. }
  188235. if( rc==SQLITE_OK ){
  188236. rc = sqlite3changegroup_output_strm(pGrp, xOutput, pOut);
  188237. }
  188238. sqlite3changegroup_delete(pGrp);
  188239. return rc;
  188240. }
  188241. /*
  188242. ** Changeset rebaser handle.
  188243. */
  188244. struct sqlite3_rebaser {
  188245. sqlite3_changegroup grp; /* Hash table */
  188246. };
  188247. /*
  188248. ** Buffers a1 and a2 must both contain a sessions module record nCol
  188249. ** fields in size. This function appends an nCol sessions module
  188250. ** record to buffer pBuf that is a copy of a1, except that for
  188251. ** each field that is undefined in a1[], swap in the field from a2[].
  188252. */
  188253. static void sessionAppendRecordMerge(
  188254. SessionBuffer *pBuf, /* Buffer to append to */
  188255. int nCol, /* Number of columns in each record */
  188256. u8 *a1, int n1, /* Record 1 */
  188257. u8 *a2, int n2, /* Record 2 */
  188258. int *pRc /* IN/OUT: error code */
  188259. ){
  188260. sessionBufferGrow(pBuf, n1+n2, pRc);
  188261. if( *pRc==SQLITE_OK ){
  188262. int i;
  188263. u8 *pOut = &pBuf->aBuf[pBuf->nBuf];
  188264. for(i=0; i<nCol; i++){
  188265. int nn1 = sessionSerialLen(a1);
  188266. int nn2 = sessionSerialLen(a2);
  188267. if( *a1==0 || *a1==0xFF ){
  188268. memcpy(pOut, a2, nn2);
  188269. pOut += nn2;
  188270. }else{
  188271. memcpy(pOut, a1, nn1);
  188272. pOut += nn1;
  188273. }
  188274. a1 += nn1;
  188275. a2 += nn2;
  188276. }
  188277. pBuf->nBuf = pOut-pBuf->aBuf;
  188278. assert( pBuf->nBuf<=pBuf->nAlloc );
  188279. }
  188280. }
  188281. /*
  188282. ** This function is called when rebasing a local UPDATE change against one
  188283. ** or more remote UPDATE changes. The aRec/nRec buffer contains the current
  188284. ** old.* and new.* records for the change. The rebase buffer (a single
  188285. ** record) is in aChange/nChange. The rebased change is appended to buffer
  188286. ** pBuf.
  188287. **
  188288. ** Rebasing the UPDATE involves:
  188289. **
  188290. ** * Removing any changes to fields for which the corresponding field
  188291. ** in the rebase buffer is set to "replaced" (type 0xFF). If this
  188292. ** means the UPDATE change updates no fields, nothing is appended
  188293. ** to the output buffer.
  188294. **
  188295. ** * For each field modified by the local change for which the
  188296. ** corresponding field in the rebase buffer is not "undefined" (0x00)
  188297. ** or "replaced" (0xFF), the old.* value is replaced by the value
  188298. ** in the rebase buffer.
  188299. */
  188300. static void sessionAppendPartialUpdate(
  188301. SessionBuffer *pBuf, /* Append record here */
  188302. sqlite3_changeset_iter *pIter, /* Iterator pointed at local change */
  188303. u8 *aRec, int nRec, /* Local change */
  188304. u8 *aChange, int nChange, /* Record to rebase against */
  188305. int *pRc /* IN/OUT: Return Code */
  188306. ){
  188307. sessionBufferGrow(pBuf, 2+nRec+nChange, pRc);
  188308. if( *pRc==SQLITE_OK ){
  188309. int bData = 0;
  188310. u8 *pOut = &pBuf->aBuf[pBuf->nBuf];
  188311. int i;
  188312. u8 *a1 = aRec;
  188313. u8 *a2 = aChange;
  188314. *pOut++ = SQLITE_UPDATE;
  188315. *pOut++ = pIter->bIndirect;
  188316. for(i=0; i<pIter->nCol; i++){
  188317. int n1 = sessionSerialLen(a1);
  188318. int n2 = sessionSerialLen(a2);
  188319. if( pIter->abPK[i] || a2[0]==0 ){
  188320. if( !pIter->abPK[i] ) bData = 1;
  188321. memcpy(pOut, a1, n1);
  188322. pOut += n1;
  188323. }else if( a2[0]!=0xFF ){
  188324. bData = 1;
  188325. memcpy(pOut, a2, n2);
  188326. pOut += n2;
  188327. }else{
  188328. *pOut++ = '\0';
  188329. }
  188330. a1 += n1;
  188331. a2 += n2;
  188332. }
  188333. if( bData ){
  188334. a2 = aChange;
  188335. for(i=0; i<pIter->nCol; i++){
  188336. int n1 = sessionSerialLen(a1);
  188337. int n2 = sessionSerialLen(a2);
  188338. if( pIter->abPK[i] || a2[0]!=0xFF ){
  188339. memcpy(pOut, a1, n1);
  188340. pOut += n1;
  188341. }else{
  188342. *pOut++ = '\0';
  188343. }
  188344. a1 += n1;
  188345. a2 += n2;
  188346. }
  188347. pBuf->nBuf = (pOut - pBuf->aBuf);
  188348. }
  188349. }
  188350. }
  188351. /*
  188352. ** pIter is configured to iterate through a changeset. This function rebases
  188353. ** that changeset according to the current configuration of the rebaser
  188354. ** object passed as the first argument. If no error occurs and argument xOutput
  188355. ** is not NULL, then the changeset is returned to the caller by invoking
  188356. ** xOutput zero or more times and SQLITE_OK returned. Or, if xOutput is NULL,
  188357. ** then (*ppOut) is set to point to a buffer containing the rebased changeset
  188358. ** before this function returns. In this case (*pnOut) is set to the size of
  188359. ** the buffer in bytes. It is the responsibility of the caller to eventually
  188360. ** free the (*ppOut) buffer using sqlite3_free().
  188361. **
  188362. ** If an error occurs, an SQLite error code is returned. If ppOut and
  188363. ** pnOut are not NULL, then the two output parameters are set to 0 before
  188364. ** returning.
  188365. */
  188366. static int sessionRebase(
  188367. sqlite3_rebaser *p, /* Rebaser hash table */
  188368. sqlite3_changeset_iter *pIter, /* Input data */
  188369. int (*xOutput)(void *pOut, const void *pData, int nData),
  188370. void *pOut, /* Context for xOutput callback */
  188371. int *pnOut, /* OUT: Number of bytes in output changeset */
  188372. void **ppOut /* OUT: Inverse of pChangeset */
  188373. ){
  188374. int rc = SQLITE_OK;
  188375. u8 *aRec = 0;
  188376. int nRec = 0;
  188377. int bNew = 0;
  188378. SessionTable *pTab = 0;
  188379. SessionBuffer sOut = {0,0,0};
  188380. while( SQLITE_ROW==sessionChangesetNext(pIter, &aRec, &nRec, &bNew) ){
  188381. SessionChange *pChange = 0;
  188382. int bDone = 0;
  188383. if( bNew ){
  188384. const char *zTab = pIter->zTab;
  188385. for(pTab=p->grp.pList; pTab; pTab=pTab->pNext){
  188386. if( 0==sqlite3_stricmp(pTab->zName, zTab) ) break;
  188387. }
  188388. bNew = 0;
  188389. /* A patchset may not be rebased */
  188390. if( pIter->bPatchset ){
  188391. rc = SQLITE_ERROR;
  188392. }
  188393. /* Append a table header to the output for this new table */
  188394. sessionAppendByte(&sOut, pIter->bPatchset ? 'P' : 'T', &rc);
  188395. sessionAppendVarint(&sOut, pIter->nCol, &rc);
  188396. sessionAppendBlob(&sOut, pIter->abPK, pIter->nCol, &rc);
  188397. sessionAppendBlob(&sOut,(u8*)pIter->zTab,(int)strlen(pIter->zTab)+1,&rc);
  188398. }
  188399. if( pTab && rc==SQLITE_OK ){
  188400. int iHash = sessionChangeHash(pTab, 0, aRec, pTab->nChange);
  188401. for(pChange=pTab->apChange[iHash]; pChange; pChange=pChange->pNext){
  188402. if( sessionChangeEqual(pTab, 0, aRec, 0, pChange->aRecord) ){
  188403. break;
  188404. }
  188405. }
  188406. }
  188407. if( pChange ){
  188408. assert( pChange->op==SQLITE_DELETE || pChange->op==SQLITE_INSERT );
  188409. switch( pIter->op ){
  188410. case SQLITE_INSERT:
  188411. if( pChange->op==SQLITE_INSERT ){
  188412. bDone = 1;
  188413. if( pChange->bIndirect==0 ){
  188414. sessionAppendByte(&sOut, SQLITE_UPDATE, &rc);
  188415. sessionAppendByte(&sOut, pIter->bIndirect, &rc);
  188416. sessionAppendBlob(&sOut, pChange->aRecord, pChange->nRecord, &rc);
  188417. sessionAppendBlob(&sOut, aRec, nRec, &rc);
  188418. }
  188419. }
  188420. break;
  188421. case SQLITE_UPDATE:
  188422. bDone = 1;
  188423. if( pChange->op==SQLITE_DELETE ){
  188424. if( pChange->bIndirect==0 ){
  188425. u8 *pCsr = aRec;
  188426. sessionSkipRecord(&pCsr, pIter->nCol);
  188427. sessionAppendByte(&sOut, SQLITE_INSERT, &rc);
  188428. sessionAppendByte(&sOut, pIter->bIndirect, &rc);
  188429. sessionAppendRecordMerge(&sOut, pIter->nCol,
  188430. pCsr, nRec-(pCsr-aRec),
  188431. pChange->aRecord, pChange->nRecord, &rc
  188432. );
  188433. }
  188434. }else{
  188435. sessionAppendPartialUpdate(&sOut, pIter,
  188436. aRec, nRec, pChange->aRecord, pChange->nRecord, &rc
  188437. );
  188438. }
  188439. break;
  188440. default:
  188441. assert( pIter->op==SQLITE_DELETE );
  188442. bDone = 1;
  188443. if( pChange->op==SQLITE_INSERT ){
  188444. sessionAppendByte(&sOut, SQLITE_DELETE, &rc);
  188445. sessionAppendByte(&sOut, pIter->bIndirect, &rc);
  188446. sessionAppendRecordMerge(&sOut, pIter->nCol,
  188447. pChange->aRecord, pChange->nRecord, aRec, nRec, &rc
  188448. );
  188449. }
  188450. break;
  188451. }
  188452. }
  188453. if( bDone==0 ){
  188454. sessionAppendByte(&sOut, pIter->op, &rc);
  188455. sessionAppendByte(&sOut, pIter->bIndirect, &rc);
  188456. sessionAppendBlob(&sOut, aRec, nRec, &rc);
  188457. }
  188458. if( rc==SQLITE_OK && xOutput && sOut.nBuf>sessions_strm_chunk_size ){
  188459. rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
  188460. sOut.nBuf = 0;
  188461. }
  188462. if( rc ) break;
  188463. }
  188464. if( rc!=SQLITE_OK ){
  188465. sqlite3_free(sOut.aBuf);
  188466. memset(&sOut, 0, sizeof(sOut));
  188467. }
  188468. if( rc==SQLITE_OK ){
  188469. if( xOutput ){
  188470. if( sOut.nBuf>0 ){
  188471. rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
  188472. }
  188473. }else{
  188474. *ppOut = (void*)sOut.aBuf;
  188475. *pnOut = sOut.nBuf;
  188476. sOut.aBuf = 0;
  188477. }
  188478. }
  188479. sqlite3_free(sOut.aBuf);
  188480. return rc;
  188481. }
  188482. /*
  188483. ** Create a new rebaser object.
  188484. */
  188485. SQLITE_API int sqlite3rebaser_create(sqlite3_rebaser **ppNew){
  188486. int rc = SQLITE_OK;
  188487. sqlite3_rebaser *pNew;
  188488. pNew = sqlite3_malloc(sizeof(sqlite3_rebaser));
  188489. if( pNew==0 ){
  188490. rc = SQLITE_NOMEM;
  188491. }else{
  188492. memset(pNew, 0, sizeof(sqlite3_rebaser));
  188493. }
  188494. *ppNew = pNew;
  188495. return rc;
  188496. }
  188497. /*
  188498. ** Call this one or more times to configure a rebaser.
  188499. */
  188500. SQLITE_API int sqlite3rebaser_configure(
  188501. sqlite3_rebaser *p,
  188502. int nRebase, const void *pRebase
  188503. ){
  188504. sqlite3_changeset_iter *pIter = 0; /* Iterator opened on pData/nData */
  188505. int rc; /* Return code */
  188506. rc = sqlite3changeset_start(&pIter, nRebase, (void*)pRebase);
  188507. if( rc==SQLITE_OK ){
  188508. rc = sessionChangesetToHash(pIter, &p->grp, 1);
  188509. }
  188510. sqlite3changeset_finalize(pIter);
  188511. return rc;
  188512. }
  188513. /*
  188514. ** Rebase a changeset according to current rebaser configuration
  188515. */
  188516. SQLITE_API int sqlite3rebaser_rebase(
  188517. sqlite3_rebaser *p,
  188518. int nIn, const void *pIn,
  188519. int *pnOut, void **ppOut
  188520. ){
  188521. sqlite3_changeset_iter *pIter = 0; /* Iterator to skip through input */
  188522. int rc = sqlite3changeset_start(&pIter, nIn, (void*)pIn);
  188523. if( rc==SQLITE_OK ){
  188524. rc = sessionRebase(p, pIter, 0, 0, pnOut, ppOut);
  188525. sqlite3changeset_finalize(pIter);
  188526. }
  188527. return rc;
  188528. }
  188529. /*
  188530. ** Rebase a changeset according to current rebaser configuration
  188531. */
  188532. SQLITE_API int sqlite3rebaser_rebase_strm(
  188533. sqlite3_rebaser *p,
  188534. int (*xInput)(void *pIn, void *pData, int *pnData),
  188535. void *pIn,
  188536. int (*xOutput)(void *pOut, const void *pData, int nData),
  188537. void *pOut
  188538. ){
  188539. sqlite3_changeset_iter *pIter = 0; /* Iterator to skip through input */
  188540. int rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);
  188541. if( rc==SQLITE_OK ){
  188542. rc = sessionRebase(p, pIter, xOutput, pOut, 0, 0);
  188543. sqlite3changeset_finalize(pIter);
  188544. }
  188545. return rc;
  188546. }
  188547. /*
  188548. ** Destroy a rebaser object
  188549. */
  188550. SQLITE_API void sqlite3rebaser_delete(sqlite3_rebaser *p){
  188551. if( p ){
  188552. sessionDeleteTable(p->grp.pList);
  188553. sqlite3_free(p);
  188554. }
  188555. }
  188556. /*
  188557. ** Global configuration
  188558. */
  188559. SQLITE_API int sqlite3session_config(int op, void *pArg){
  188560. int rc = SQLITE_OK;
  188561. switch( op ){
  188562. case SQLITE_SESSION_CONFIG_STRMSIZE: {
  188563. int *pInt = (int*)pArg;
  188564. if( *pInt>0 ){
  188565. sessions_strm_chunk_size = *pInt;
  188566. }
  188567. *pInt = sessions_strm_chunk_size;
  188568. break;
  188569. }
  188570. default:
  188571. rc = SQLITE_MISUSE;
  188572. break;
  188573. }
  188574. return rc;
  188575. }
  188576. #endif /* SQLITE_ENABLE_SESSION && SQLITE_ENABLE_PREUPDATE_HOOK */
  188577. /************** End of sqlite3session.c **************************************/
  188578. /************** Begin file fts5.c ********************************************/
  188579. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5)
  188580. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  188581. # define NDEBUG 1
  188582. #endif
  188583. #if defined(NDEBUG) && defined(SQLITE_DEBUG)
  188584. # undef NDEBUG
  188585. #endif
  188586. /*
  188587. ** 2014 May 31
  188588. **
  188589. ** The author disclaims copyright to this source code. In place of
  188590. ** a legal notice, here is a blessing:
  188591. **
  188592. ** May you do good and not evil.
  188593. ** May you find forgiveness for yourself and forgive others.
  188594. ** May you share freely, never taking more than you give.
  188595. **
  188596. ******************************************************************************
  188597. **
  188598. ** Interfaces to extend FTS5. Using the interfaces defined in this file,
  188599. ** FTS5 may be extended with:
  188600. **
  188601. ** * custom tokenizers, and
  188602. ** * custom auxiliary functions.
  188603. */
  188604. #ifndef _FTS5_H
  188605. #define _FTS5_H
  188606. /* #include "sqlite3.h" */
  188607. #if 0
  188608. extern "C" {
  188609. #endif
  188610. /*************************************************************************
  188611. ** CUSTOM AUXILIARY FUNCTIONS
  188612. **
  188613. ** Virtual table implementations may overload SQL functions by implementing
  188614. ** the sqlite3_module.xFindFunction() method.
  188615. */
  188616. typedef struct Fts5ExtensionApi Fts5ExtensionApi;
  188617. typedef struct Fts5Context Fts5Context;
  188618. typedef struct Fts5PhraseIter Fts5PhraseIter;
  188619. typedef void (*fts5_extension_function)(
  188620. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  188621. Fts5Context *pFts, /* First arg to pass to pApi functions */
  188622. sqlite3_context *pCtx, /* Context for returning result/error */
  188623. int nVal, /* Number of values in apVal[] array */
  188624. sqlite3_value **apVal /* Array of trailing arguments */
  188625. );
  188626. struct Fts5PhraseIter {
  188627. const unsigned char *a;
  188628. const unsigned char *b;
  188629. };
  188630. /*
  188631. ** EXTENSION API FUNCTIONS
  188632. **
  188633. ** xUserData(pFts):
  188634. ** Return a copy of the context pointer the extension function was
  188635. ** registered with.
  188636. **
  188637. ** xColumnTotalSize(pFts, iCol, pnToken):
  188638. ** If parameter iCol is less than zero, set output variable *pnToken
  188639. ** to the total number of tokens in the FTS5 table. Or, if iCol is
  188640. ** non-negative but less than the number of columns in the table, return
  188641. ** the total number of tokens in column iCol, considering all rows in
  188642. ** the FTS5 table.
  188643. **
  188644. ** If parameter iCol is greater than or equal to the number of columns
  188645. ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
  188646. ** an OOM condition or IO error), an appropriate SQLite error code is
  188647. ** returned.
  188648. **
  188649. ** xColumnCount(pFts):
  188650. ** Return the number of columns in the table.
  188651. **
  188652. ** xColumnSize(pFts, iCol, pnToken):
  188653. ** If parameter iCol is less than zero, set output variable *pnToken
  188654. ** to the total number of tokens in the current row. Or, if iCol is
  188655. ** non-negative but less than the number of columns in the table, set
  188656. ** *pnToken to the number of tokens in column iCol of the current row.
  188657. **
  188658. ** If parameter iCol is greater than or equal to the number of columns
  188659. ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
  188660. ** an OOM condition or IO error), an appropriate SQLite error code is
  188661. ** returned.
  188662. **
  188663. ** This function may be quite inefficient if used with an FTS5 table
  188664. ** created with the "columnsize=0" option.
  188665. **
  188666. ** xColumnText:
  188667. ** This function attempts to retrieve the text of column iCol of the
  188668. ** current document. If successful, (*pz) is set to point to a buffer
  188669. ** containing the text in utf-8 encoding, (*pn) is set to the size in bytes
  188670. ** (not characters) of the buffer and SQLITE_OK is returned. Otherwise,
  188671. ** if an error occurs, an SQLite error code is returned and the final values
  188672. ** of (*pz) and (*pn) are undefined.
  188673. **
  188674. ** xPhraseCount:
  188675. ** Returns the number of phrases in the current query expression.
  188676. **
  188677. ** xPhraseSize:
  188678. ** Returns the number of tokens in phrase iPhrase of the query. Phrases
  188679. ** are numbered starting from zero.
  188680. **
  188681. ** xInstCount:
  188682. ** Set *pnInst to the total number of occurrences of all phrases within
  188683. ** the query within the current row. Return SQLITE_OK if successful, or
  188684. ** an error code (i.e. SQLITE_NOMEM) if an error occurs.
  188685. **
  188686. ** This API can be quite slow if used with an FTS5 table created with the
  188687. ** "detail=none" or "detail=column" option. If the FTS5 table is created
  188688. ** with either "detail=none" or "detail=column" and "content=" option
  188689. ** (i.e. if it is a contentless table), then this API always returns 0.
  188690. **
  188691. ** xInst:
  188692. ** Query for the details of phrase match iIdx within the current row.
  188693. ** Phrase matches are numbered starting from zero, so the iIdx argument
  188694. ** should be greater than or equal to zero and smaller than the value
  188695. ** output by xInstCount().
  188696. **
  188697. ** Usually, output parameter *piPhrase is set to the phrase number, *piCol
  188698. ** to the column in which it occurs and *piOff the token offset of the
  188699. ** first token of the phrase. Returns SQLITE_OK if successful, or an error
  188700. ** code (i.e. SQLITE_NOMEM) if an error occurs.
  188701. **
  188702. ** This API can be quite slow if used with an FTS5 table created with the
  188703. ** "detail=none" or "detail=column" option.
  188704. **
  188705. ** xRowid:
  188706. ** Returns the rowid of the current row.
  188707. **
  188708. ** xTokenize:
  188709. ** Tokenize text using the tokenizer belonging to the FTS5 table.
  188710. **
  188711. ** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):
  188712. ** This API function is used to query the FTS table for phrase iPhrase
  188713. ** of the current query. Specifically, a query equivalent to:
  188714. **
  188715. ** ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
  188716. **
  188717. ** with $p set to a phrase equivalent to the phrase iPhrase of the
  188718. ** current query is executed. Any column filter that applies to
  188719. ** phrase iPhrase of the current query is included in $p. For each
  188720. ** row visited, the callback function passed as the fourth argument
  188721. ** is invoked. The context and API objects passed to the callback
  188722. ** function may be used to access the properties of each matched row.
  188723. ** Invoking Api.xUserData() returns a copy of the pointer passed as
  188724. ** the third argument to pUserData.
  188725. **
  188726. ** If the callback function returns any value other than SQLITE_OK, the
  188727. ** query is abandoned and the xQueryPhrase function returns immediately.
  188728. ** If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
  188729. ** Otherwise, the error code is propagated upwards.
  188730. **
  188731. ** If the query runs to completion without incident, SQLITE_OK is returned.
  188732. ** Or, if some error occurs before the query completes or is aborted by
  188733. ** the callback, an SQLite error code is returned.
  188734. **
  188735. **
  188736. ** xSetAuxdata(pFts5, pAux, xDelete)
  188737. **
  188738. ** Save the pointer passed as the second argument as the extension functions
  188739. ** "auxiliary data". The pointer may then be retrieved by the current or any
  188740. ** future invocation of the same fts5 extension function made as part of
  188741. ** the same MATCH query using the xGetAuxdata() API.
  188742. **
  188743. ** Each extension function is allocated a single auxiliary data slot for
  188744. ** each FTS query (MATCH expression). If the extension function is invoked
  188745. ** more than once for a single FTS query, then all invocations share a
  188746. ** single auxiliary data context.
  188747. **
  188748. ** If there is already an auxiliary data pointer when this function is
  188749. ** invoked, then it is replaced by the new pointer. If an xDelete callback
  188750. ** was specified along with the original pointer, it is invoked at this
  188751. ** point.
  188752. **
  188753. ** The xDelete callback, if one is specified, is also invoked on the
  188754. ** auxiliary data pointer after the FTS5 query has finished.
  188755. **
  188756. ** If an error (e.g. an OOM condition) occurs within this function,
  188757. ** the auxiliary data is set to NULL and an error code returned. If the
  188758. ** xDelete parameter was not NULL, it is invoked on the auxiliary data
  188759. ** pointer before returning.
  188760. **
  188761. **
  188762. ** xGetAuxdata(pFts5, bClear)
  188763. **
  188764. ** Returns the current auxiliary data pointer for the fts5 extension
  188765. ** function. See the xSetAuxdata() method for details.
  188766. **
  188767. ** If the bClear argument is non-zero, then the auxiliary data is cleared
  188768. ** (set to NULL) before this function returns. In this case the xDelete,
  188769. ** if any, is not invoked.
  188770. **
  188771. **
  188772. ** xRowCount(pFts5, pnRow)
  188773. **
  188774. ** This function is used to retrieve the total number of rows in the table.
  188775. ** In other words, the same value that would be returned by:
  188776. **
  188777. ** SELECT count(*) FROM ftstable;
  188778. **
  188779. ** xPhraseFirst()
  188780. ** This function is used, along with type Fts5PhraseIter and the xPhraseNext
  188781. ** method, to iterate through all instances of a single query phrase within
  188782. ** the current row. This is the same information as is accessible via the
  188783. ** xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
  188784. ** to use, this API may be faster under some circumstances. To iterate
  188785. ** through instances of phrase iPhrase, use the following code:
  188786. **
  188787. ** Fts5PhraseIter iter;
  188788. ** int iCol, iOff;
  188789. ** for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
  188790. ** iCol>=0;
  188791. ** pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
  188792. ** ){
  188793. ** // An instance of phrase iPhrase at offset iOff of column iCol
  188794. ** }
  188795. **
  188796. ** The Fts5PhraseIter structure is defined above. Applications should not
  188797. ** modify this structure directly - it should only be used as shown above
  188798. ** with the xPhraseFirst() and xPhraseNext() API methods (and by
  188799. ** xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below).
  188800. **
  188801. ** This API can be quite slow if used with an FTS5 table created with the
  188802. ** "detail=none" or "detail=column" option. If the FTS5 table is created
  188803. ** with either "detail=none" or "detail=column" and "content=" option
  188804. ** (i.e. if it is a contentless table), then this API always iterates
  188805. ** through an empty set (all calls to xPhraseFirst() set iCol to -1).
  188806. **
  188807. ** xPhraseNext()
  188808. ** See xPhraseFirst above.
  188809. **
  188810. ** xPhraseFirstColumn()
  188811. ** This function and xPhraseNextColumn() are similar to the xPhraseFirst()
  188812. ** and xPhraseNext() APIs described above. The difference is that instead
  188813. ** of iterating through all instances of a phrase in the current row, these
  188814. ** APIs are used to iterate through the set of columns in the current row
  188815. ** that contain one or more instances of a specified phrase. For example:
  188816. **
  188817. ** Fts5PhraseIter iter;
  188818. ** int iCol;
  188819. ** for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol);
  188820. ** iCol>=0;
  188821. ** pApi->xPhraseNextColumn(pFts, &iter, &iCol)
  188822. ** ){
  188823. ** // Column iCol contains at least one instance of phrase iPhrase
  188824. ** }
  188825. **
  188826. ** This API can be quite slow if used with an FTS5 table created with the
  188827. ** "detail=none" option. If the FTS5 table is created with either
  188828. ** "detail=none" "content=" option (i.e. if it is a contentless table),
  188829. ** then this API always iterates through an empty set (all calls to
  188830. ** xPhraseFirstColumn() set iCol to -1).
  188831. **
  188832. ** The information accessed using this API and its companion
  188833. ** xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext
  188834. ** (or xInst/xInstCount). The chief advantage of this API is that it is
  188835. ** significantly more efficient than those alternatives when used with
  188836. ** "detail=column" tables.
  188837. **
  188838. ** xPhraseNextColumn()
  188839. ** See xPhraseFirstColumn above.
  188840. */
  188841. struct Fts5ExtensionApi {
  188842. int iVersion; /* Currently always set to 3 */
  188843. void *(*xUserData)(Fts5Context*);
  188844. int (*xColumnCount)(Fts5Context*);
  188845. int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
  188846. int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
  188847. int (*xTokenize)(Fts5Context*,
  188848. const char *pText, int nText, /* Text to tokenize */
  188849. void *pCtx, /* Context passed to xToken() */
  188850. int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
  188851. );
  188852. int (*xPhraseCount)(Fts5Context*);
  188853. int (*xPhraseSize)(Fts5Context*, int iPhrase);
  188854. int (*xInstCount)(Fts5Context*, int *pnInst);
  188855. int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);
  188856. sqlite3_int64 (*xRowid)(Fts5Context*);
  188857. int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);
  188858. int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);
  188859. int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,
  188860. int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)
  188861. );
  188862. int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));
  188863. void *(*xGetAuxdata)(Fts5Context*, int bClear);
  188864. int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);
  188865. void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);
  188866. int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*);
  188867. void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol);
  188868. };
  188869. /*
  188870. ** CUSTOM AUXILIARY FUNCTIONS
  188871. *************************************************************************/
  188872. /*************************************************************************
  188873. ** CUSTOM TOKENIZERS
  188874. **
  188875. ** Applications may also register custom tokenizer types. A tokenizer
  188876. ** is registered by providing fts5 with a populated instance of the
  188877. ** following structure. All structure methods must be defined, setting
  188878. ** any member of the fts5_tokenizer struct to NULL leads to undefined
  188879. ** behaviour. The structure methods are expected to function as follows:
  188880. **
  188881. ** xCreate:
  188882. ** This function is used to allocate and initialize a tokenizer instance.
  188883. ** A tokenizer instance is required to actually tokenize text.
  188884. **
  188885. ** The first argument passed to this function is a copy of the (void*)
  188886. ** pointer provided by the application when the fts5_tokenizer object
  188887. ** was registered with FTS5 (the third argument to xCreateTokenizer()).
  188888. ** The second and third arguments are an array of nul-terminated strings
  188889. ** containing the tokenizer arguments, if any, specified following the
  188890. ** tokenizer name as part of the CREATE VIRTUAL TABLE statement used
  188891. ** to create the FTS5 table.
  188892. **
  188893. ** The final argument is an output variable. If successful, (*ppOut)
  188894. ** should be set to point to the new tokenizer handle and SQLITE_OK
  188895. ** returned. If an error occurs, some value other than SQLITE_OK should
  188896. ** be returned. In this case, fts5 assumes that the final value of *ppOut
  188897. ** is undefined.
  188898. **
  188899. ** xDelete:
  188900. ** This function is invoked to delete a tokenizer handle previously
  188901. ** allocated using xCreate(). Fts5 guarantees that this function will
  188902. ** be invoked exactly once for each successful call to xCreate().
  188903. **
  188904. ** xTokenize:
  188905. ** This function is expected to tokenize the nText byte string indicated
  188906. ** by argument pText. pText may or may not be nul-terminated. The first
  188907. ** argument passed to this function is a pointer to an Fts5Tokenizer object
  188908. ** returned by an earlier call to xCreate().
  188909. **
  188910. ** The second argument indicates the reason that FTS5 is requesting
  188911. ** tokenization of the supplied text. This is always one of the following
  188912. ** four values:
  188913. **
  188914. ** <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into
  188915. ** or removed from the FTS table. The tokenizer is being invoked to
  188916. ** determine the set of tokens to add to (or delete from) the
  188917. ** FTS index.
  188918. **
  188919. ** <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed
  188920. ** against the FTS index. The tokenizer is being called to tokenize
  188921. ** a bareword or quoted string specified as part of the query.
  188922. **
  188923. ** <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
  188924. ** FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is
  188925. ** followed by a "*" character, indicating that the last token
  188926. ** returned by the tokenizer will be treated as a token prefix.
  188927. **
  188928. ** <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to
  188929. ** satisfy an fts5_api.xTokenize() request made by an auxiliary
  188930. ** function. Or an fts5_api.xColumnSize() request made by the same
  188931. ** on a columnsize=0 database.
  188932. ** </ul>
  188933. **
  188934. ** For each token in the input string, the supplied callback xToken() must
  188935. ** be invoked. The first argument to it should be a copy of the pointer
  188936. ** passed as the second argument to xTokenize(). The third and fourth
  188937. ** arguments are a pointer to a buffer containing the token text, and the
  188938. ** size of the token in bytes. The 4th and 5th arguments are the byte offsets
  188939. ** of the first byte of and first byte immediately following the text from
  188940. ** which the token is derived within the input.
  188941. **
  188942. ** The second argument passed to the xToken() callback ("tflags") should
  188943. ** normally be set to 0. The exception is if the tokenizer supports
  188944. ** synonyms. In this case see the discussion below for details.
  188945. **
  188946. ** FTS5 assumes the xToken() callback is invoked for each token in the
  188947. ** order that they occur within the input text.
  188948. **
  188949. ** If an xToken() callback returns any value other than SQLITE_OK, then
  188950. ** the tokenization should be abandoned and the xTokenize() method should
  188951. ** immediately return a copy of the xToken() return value. Or, if the
  188952. ** input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,
  188953. ** if an error occurs with the xTokenize() implementation itself, it
  188954. ** may abandon the tokenization and return any error code other than
  188955. ** SQLITE_OK or SQLITE_DONE.
  188956. **
  188957. ** SYNONYM SUPPORT
  188958. **
  188959. ** Custom tokenizers may also support synonyms. Consider a case in which a
  188960. ** user wishes to query for a phrase such as "first place". Using the
  188961. ** built-in tokenizers, the FTS5 query 'first + place' will match instances
  188962. ** of "first place" within the document set, but not alternative forms
  188963. ** such as "1st place". In some applications, it would be better to match
  188964. ** all instances of "first place" or "1st place" regardless of which form
  188965. ** the user specified in the MATCH query text.
  188966. **
  188967. ** There are several ways to approach this in FTS5:
  188968. **
  188969. ** <ol><li> By mapping all synonyms to a single token. In this case, the
  188970. ** In the above example, this means that the tokenizer returns the
  188971. ** same token for inputs "first" and "1st". Say that token is in
  188972. ** fact "first", so that when the user inserts the document "I won
  188973. ** 1st place" entries are added to the index for tokens "i", "won",
  188974. ** "first" and "place". If the user then queries for '1st + place',
  188975. ** the tokenizer substitutes "first" for "1st" and the query works
  188976. ** as expected.
  188977. **
  188978. ** <li> By querying the index for all synonyms of each query term
  188979. ** separately. In this case, when tokenizing query text, the
  188980. ** tokenizer may provide multiple synonyms for a single term
  188981. ** within the document. FTS5 then queries the index for each
  188982. ** synonym individually. For example, faced with the query:
  188983. **
  188984. ** <codeblock>
  188985. ** ... MATCH 'first place'</codeblock>
  188986. **
  188987. ** the tokenizer offers both "1st" and "first" as synonyms for the
  188988. ** first token in the MATCH query and FTS5 effectively runs a query
  188989. ** similar to:
  188990. **
  188991. ** <codeblock>
  188992. ** ... MATCH '(first OR 1st) place'</codeblock>
  188993. **
  188994. ** except that, for the purposes of auxiliary functions, the query
  188995. ** still appears to contain just two phrases - "(first OR 1st)"
  188996. ** being treated as a single phrase.
  188997. **
  188998. ** <li> By adding multiple synonyms for a single term to the FTS index.
  188999. ** Using this method, when tokenizing document text, the tokenizer
  189000. ** provides multiple synonyms for each token. So that when a
  189001. ** document such as "I won first place" is tokenized, entries are
  189002. ** added to the FTS index for "i", "won", "first", "1st" and
  189003. ** "place".
  189004. **
  189005. ** This way, even if the tokenizer does not provide synonyms
  189006. ** when tokenizing query text (it should not - to do so would be
  189007. ** inefficient), it doesn't matter if the user queries for
  189008. ** 'first + place' or '1st + place', as there are entries in the
  189009. ** FTS index corresponding to both forms of the first token.
  189010. ** </ol>
  189011. **
  189012. ** Whether it is parsing document or query text, any call to xToken that
  189013. ** specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit
  189014. ** is considered to supply a synonym for the previous token. For example,
  189015. ** when parsing the document "I won first place", a tokenizer that supports
  189016. ** synonyms would call xToken() 5 times, as follows:
  189017. **
  189018. ** <codeblock>
  189019. ** xToken(pCtx, 0, "i", 1, 0, 1);
  189020. ** xToken(pCtx, 0, "won", 3, 2, 5);
  189021. ** xToken(pCtx, 0, "first", 5, 6, 11);
  189022. ** xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3, 6, 11);
  189023. ** xToken(pCtx, 0, "place", 5, 12, 17);
  189024. **</codeblock>
  189025. **
  189026. ** It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
  189027. ** xToken() is called. Multiple synonyms may be specified for a single token
  189028. ** by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence.
  189029. ** There is no limit to the number of synonyms that may be provided for a
  189030. ** single token.
  189031. **
  189032. ** In many cases, method (1) above is the best approach. It does not add
  189033. ** extra data to the FTS index or require FTS5 to query for multiple terms,
  189034. ** so it is efficient in terms of disk space and query speed. However, it
  189035. ** does not support prefix queries very well. If, as suggested above, the
  189036. ** token "first" is substituted for "1st" by the tokenizer, then the query:
  189037. **
  189038. ** <codeblock>
  189039. ** ... MATCH '1s*'</codeblock>
  189040. **
  189041. ** will not match documents that contain the token "1st" (as the tokenizer
  189042. ** will probably not map "1s" to any prefix of "first").
  189043. **
  189044. ** For full prefix support, method (3) may be preferred. In this case,
  189045. ** because the index contains entries for both "first" and "1st", prefix
  189046. ** queries such as 'fi*' or '1s*' will match correctly. However, because
  189047. ** extra entries are added to the FTS index, this method uses more space
  189048. ** within the database.
  189049. **
  189050. ** Method (2) offers a midpoint between (1) and (3). Using this method,
  189051. ** a query such as '1s*' will match documents that contain the literal
  189052. ** token "1st", but not "first" (assuming the tokenizer is not able to
  189053. ** provide synonyms for prefixes). However, a non-prefix query like '1st'
  189054. ** will match against "1st" and "first". This method does not require
  189055. ** extra disk space, as no extra entries are added to the FTS index.
  189056. ** On the other hand, it may require more CPU cycles to run MATCH queries,
  189057. ** as separate queries of the FTS index are required for each synonym.
  189058. **
  189059. ** When using methods (2) or (3), it is important that the tokenizer only
  189060. ** provide synonyms when tokenizing document text (method (2)) or query
  189061. ** text (method (3)), not both. Doing so will not cause any errors, but is
  189062. ** inefficient.
  189063. */
  189064. typedef struct Fts5Tokenizer Fts5Tokenizer;
  189065. typedef struct fts5_tokenizer fts5_tokenizer;
  189066. struct fts5_tokenizer {
  189067. int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
  189068. void (*xDelete)(Fts5Tokenizer*);
  189069. int (*xTokenize)(Fts5Tokenizer*,
  189070. void *pCtx,
  189071. int flags, /* Mask of FTS5_TOKENIZE_* flags */
  189072. const char *pText, int nText,
  189073. int (*xToken)(
  189074. void *pCtx, /* Copy of 2nd argument to xTokenize() */
  189075. int tflags, /* Mask of FTS5_TOKEN_* flags */
  189076. const char *pToken, /* Pointer to buffer containing token */
  189077. int nToken, /* Size of token in bytes */
  189078. int iStart, /* Byte offset of token within input text */
  189079. int iEnd /* Byte offset of end of token within input text */
  189080. )
  189081. );
  189082. };
  189083. /* Flags that may be passed as the third argument to xTokenize() */
  189084. #define FTS5_TOKENIZE_QUERY 0x0001
  189085. #define FTS5_TOKENIZE_PREFIX 0x0002
  189086. #define FTS5_TOKENIZE_DOCUMENT 0x0004
  189087. #define FTS5_TOKENIZE_AUX 0x0008
  189088. /* Flags that may be passed by the tokenizer implementation back to FTS5
  189089. ** as the third argument to the supplied xToken callback. */
  189090. #define FTS5_TOKEN_COLOCATED 0x0001 /* Same position as prev. token */
  189091. /*
  189092. ** END OF CUSTOM TOKENIZERS
  189093. *************************************************************************/
  189094. /*************************************************************************
  189095. ** FTS5 EXTENSION REGISTRATION API
  189096. */
  189097. typedef struct fts5_api fts5_api;
  189098. struct fts5_api {
  189099. int iVersion; /* Currently always set to 2 */
  189100. /* Create a new tokenizer */
  189101. int (*xCreateTokenizer)(
  189102. fts5_api *pApi,
  189103. const char *zName,
  189104. void *pContext,
  189105. fts5_tokenizer *pTokenizer,
  189106. void (*xDestroy)(void*)
  189107. );
  189108. /* Find an existing tokenizer */
  189109. int (*xFindTokenizer)(
  189110. fts5_api *pApi,
  189111. const char *zName,
  189112. void **ppContext,
  189113. fts5_tokenizer *pTokenizer
  189114. );
  189115. /* Create a new auxiliary function */
  189116. int (*xCreateFunction)(
  189117. fts5_api *pApi,
  189118. const char *zName,
  189119. void *pContext,
  189120. fts5_extension_function xFunction,
  189121. void (*xDestroy)(void*)
  189122. );
  189123. };
  189124. /*
  189125. ** END OF REGISTRATION API
  189126. *************************************************************************/
  189127. #if 0
  189128. } /* end of the 'extern "C"' block */
  189129. #endif
  189130. #endif /* _FTS5_H */
  189131. /*
  189132. ** 2014 May 31
  189133. **
  189134. ** The author disclaims copyright to this source code. In place of
  189135. ** a legal notice, here is a blessing:
  189136. **
  189137. ** May you do good and not evil.
  189138. ** May you find forgiveness for yourself and forgive others.
  189139. ** May you share freely, never taking more than you give.
  189140. **
  189141. ******************************************************************************
  189142. **
  189143. */
  189144. #ifndef _FTS5INT_H
  189145. #define _FTS5INT_H
  189146. /* #include "fts5.h" */
  189147. /* #include "sqlite3ext.h" */
  189148. SQLITE_EXTENSION_INIT1
  189149. /* #include <string.h> */
  189150. /* #include <assert.h> */
  189151. #ifndef SQLITE_AMALGAMATION
  189152. typedef unsigned char u8;
  189153. typedef unsigned int u32;
  189154. typedef unsigned short u16;
  189155. typedef short i16;
  189156. typedef sqlite3_int64 i64;
  189157. typedef sqlite3_uint64 u64;
  189158. #ifndef ArraySize
  189159. # define ArraySize(x) ((int)(sizeof(x) / sizeof(x[0])))
  189160. #endif
  189161. #define testcase(x)
  189162. #define ALWAYS(x) 1
  189163. #define NEVER(x) 0
  189164. #define MIN(x,y) (((x) < (y)) ? (x) : (y))
  189165. #define MAX(x,y) (((x) > (y)) ? (x) : (y))
  189166. /*
  189167. ** Constants for the largest and smallest possible 64-bit signed integers.
  189168. */
  189169. # define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
  189170. # define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
  189171. #endif
  189172. /* Truncate very long tokens to this many bytes. Hard limit is
  189173. ** (65536-1-1-4-9)==65521 bytes. The limiting factor is the 16-bit offset
  189174. ** field that occurs at the start of each leaf page (see fts5_index.c). */
  189175. #define FTS5_MAX_TOKEN_SIZE 32768
  189176. /*
  189177. ** Maximum number of prefix indexes on single FTS5 table. This must be
  189178. ** less than 32. If it is set to anything large than that, an #error
  189179. ** directive in fts5_index.c will cause the build to fail.
  189180. */
  189181. #define FTS5_MAX_PREFIX_INDEXES 31
  189182. #define FTS5_DEFAULT_NEARDIST 10
  189183. #define FTS5_DEFAULT_RANK "bm25"
  189184. /* Name of rank and rowid columns */
  189185. #define FTS5_RANK_NAME "rank"
  189186. #define FTS5_ROWID_NAME "rowid"
  189187. #ifdef SQLITE_DEBUG
  189188. # define FTS5_CORRUPT sqlite3Fts5Corrupt()
  189189. static int sqlite3Fts5Corrupt(void);
  189190. #else
  189191. # define FTS5_CORRUPT SQLITE_CORRUPT_VTAB
  189192. #endif
  189193. /*
  189194. ** The assert_nc() macro is similar to the assert() macro, except that it
  189195. ** is used for assert() conditions that are true only if it can be
  189196. ** guranteed that the database is not corrupt.
  189197. */
  189198. #ifdef SQLITE_DEBUG
  189199. SQLITE_API extern int sqlite3_fts5_may_be_corrupt;
  189200. # define assert_nc(x) assert(sqlite3_fts5_may_be_corrupt || (x))
  189201. #else
  189202. # define assert_nc(x) assert(x)
  189203. #endif
  189204. /*
  189205. ** A version of memcmp() that does not cause asan errors if one of the pointer
  189206. ** parameters is NULL and the number of bytes to compare is zero.
  189207. */
  189208. #define fts5Memcmp(s1, s2, n) ((n)==0 ? 0 : memcmp((s1), (s2), (n)))
  189209. /* Mark a function parameter as unused, to suppress nuisance compiler
  189210. ** warnings. */
  189211. #ifndef UNUSED_PARAM
  189212. # define UNUSED_PARAM(X) (void)(X)
  189213. #endif
  189214. #ifndef UNUSED_PARAM2
  189215. # define UNUSED_PARAM2(X, Y) (void)(X), (void)(Y)
  189216. #endif
  189217. typedef struct Fts5Global Fts5Global;
  189218. typedef struct Fts5Colset Fts5Colset;
  189219. /* If a NEAR() clump or phrase may only match a specific set of columns,
  189220. ** then an object of the following type is used to record the set of columns.
  189221. ** Each entry in the aiCol[] array is a column that may be matched.
  189222. **
  189223. ** This object is used by fts5_expr.c and fts5_index.c.
  189224. */
  189225. struct Fts5Colset {
  189226. int nCol;
  189227. int aiCol[1];
  189228. };
  189229. /**************************************************************************
  189230. ** Interface to code in fts5_config.c. fts5_config.c contains contains code
  189231. ** to parse the arguments passed to the CREATE VIRTUAL TABLE statement.
  189232. */
  189233. typedef struct Fts5Config Fts5Config;
  189234. /*
  189235. ** An instance of the following structure encodes all information that can
  189236. ** be gleaned from the CREATE VIRTUAL TABLE statement.
  189237. **
  189238. ** And all information loaded from the %_config table.
  189239. **
  189240. ** nAutomerge:
  189241. ** The minimum number of segments that an auto-merge operation should
  189242. ** attempt to merge together. A value of 1 sets the object to use the
  189243. ** compile time default. Zero disables auto-merge altogether.
  189244. **
  189245. ** zContent:
  189246. **
  189247. ** zContentRowid:
  189248. ** The value of the content_rowid= option, if one was specified. Or
  189249. ** the string "rowid" otherwise. This text is not quoted - if it is
  189250. ** used as part of an SQL statement it needs to be quoted appropriately.
  189251. **
  189252. ** zContentExprlist:
  189253. **
  189254. ** pzErrmsg:
  189255. ** This exists in order to allow the fts5_index.c module to return a
  189256. ** decent error message if it encounters a file-format version it does
  189257. ** not understand.
  189258. **
  189259. ** bColumnsize:
  189260. ** True if the %_docsize table is created.
  189261. **
  189262. ** bPrefixIndex:
  189263. ** This is only used for debugging. If set to false, any prefix indexes
  189264. ** are ignored. This value is configured using:
  189265. **
  189266. ** INSERT INTO tbl(tbl, rank) VALUES('prefix-index', $bPrefixIndex);
  189267. **
  189268. */
  189269. struct Fts5Config {
  189270. sqlite3 *db; /* Database handle */
  189271. char *zDb; /* Database holding FTS index (e.g. "main") */
  189272. char *zName; /* Name of FTS index */
  189273. int nCol; /* Number of columns */
  189274. char **azCol; /* Column names */
  189275. u8 *abUnindexed; /* True for unindexed columns */
  189276. int nPrefix; /* Number of prefix indexes */
  189277. int *aPrefix; /* Sizes in bytes of nPrefix prefix indexes */
  189278. int eContent; /* An FTS5_CONTENT value */
  189279. char *zContent; /* content table */
  189280. char *zContentRowid; /* "content_rowid=" option value */
  189281. int bColumnsize; /* "columnsize=" option value (dflt==1) */
  189282. int eDetail; /* FTS5_DETAIL_XXX value */
  189283. char *zContentExprlist;
  189284. Fts5Tokenizer *pTok;
  189285. fts5_tokenizer *pTokApi;
  189286. /* Values loaded from the %_config table */
  189287. int iCookie; /* Incremented when %_config is modified */
  189288. int pgsz; /* Approximate page size used in %_data */
  189289. int nAutomerge; /* 'automerge' setting */
  189290. int nCrisisMerge; /* Maximum allowed segments per level */
  189291. int nUsermerge; /* 'usermerge' setting */
  189292. int nHashSize; /* Bytes of memory for in-memory hash */
  189293. char *zRank; /* Name of rank function */
  189294. char *zRankArgs; /* Arguments to rank function */
  189295. /* If non-NULL, points to sqlite3_vtab.base.zErrmsg. Often NULL. */
  189296. char **pzErrmsg;
  189297. #ifdef SQLITE_DEBUG
  189298. int bPrefixIndex; /* True to use prefix-indexes */
  189299. #endif
  189300. };
  189301. /* Current expected value of %_config table 'version' field */
  189302. #define FTS5_CURRENT_VERSION 4
  189303. #define FTS5_CONTENT_NORMAL 0
  189304. #define FTS5_CONTENT_NONE 1
  189305. #define FTS5_CONTENT_EXTERNAL 2
  189306. #define FTS5_DETAIL_FULL 0
  189307. #define FTS5_DETAIL_NONE 1
  189308. #define FTS5_DETAIL_COLUMNS 2
  189309. static int sqlite3Fts5ConfigParse(
  189310. Fts5Global*, sqlite3*, int, const char **, Fts5Config**, char**
  189311. );
  189312. static void sqlite3Fts5ConfigFree(Fts5Config*);
  189313. static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig);
  189314. static int sqlite3Fts5Tokenize(
  189315. Fts5Config *pConfig, /* FTS5 Configuration object */
  189316. int flags, /* FTS5_TOKENIZE_* flags */
  189317. const char *pText, int nText, /* Text to tokenize */
  189318. void *pCtx, /* Context passed to xToken() */
  189319. int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
  189320. );
  189321. static void sqlite3Fts5Dequote(char *z);
  189322. /* Load the contents of the %_config table */
  189323. static int sqlite3Fts5ConfigLoad(Fts5Config*, int);
  189324. /* Set the value of a single config attribute */
  189325. static int sqlite3Fts5ConfigSetValue(Fts5Config*, const char*, sqlite3_value*, int*);
  189326. static int sqlite3Fts5ConfigParseRank(const char*, char**, char**);
  189327. /*
  189328. ** End of interface to code in fts5_config.c.
  189329. **************************************************************************/
  189330. /**************************************************************************
  189331. ** Interface to code in fts5_buffer.c.
  189332. */
  189333. /*
  189334. ** Buffer object for the incremental building of string data.
  189335. */
  189336. typedef struct Fts5Buffer Fts5Buffer;
  189337. struct Fts5Buffer {
  189338. u8 *p;
  189339. int n;
  189340. int nSpace;
  189341. };
  189342. static int sqlite3Fts5BufferSize(int*, Fts5Buffer*, u32);
  189343. static void sqlite3Fts5BufferAppendVarint(int*, Fts5Buffer*, i64);
  189344. static void sqlite3Fts5BufferAppendBlob(int*, Fts5Buffer*, u32, const u8*);
  189345. static void sqlite3Fts5BufferAppendString(int *, Fts5Buffer*, const char*);
  189346. static void sqlite3Fts5BufferFree(Fts5Buffer*);
  189347. static void sqlite3Fts5BufferZero(Fts5Buffer*);
  189348. static void sqlite3Fts5BufferSet(int*, Fts5Buffer*, int, const u8*);
  189349. static void sqlite3Fts5BufferAppendPrintf(int *, Fts5Buffer*, char *zFmt, ...);
  189350. static char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...);
  189351. #define fts5BufferZero(x) sqlite3Fts5BufferZero(x)
  189352. #define fts5BufferAppendVarint(a,b,c) sqlite3Fts5BufferAppendVarint(a,b,c)
  189353. #define fts5BufferFree(a) sqlite3Fts5BufferFree(a)
  189354. #define fts5BufferAppendBlob(a,b,c,d) sqlite3Fts5BufferAppendBlob(a,b,c,d)
  189355. #define fts5BufferSet(a,b,c,d) sqlite3Fts5BufferSet(a,b,c,d)
  189356. #define fts5BufferGrow(pRc,pBuf,nn) ( \
  189357. (u32)((pBuf)->n) + (u32)(nn) <= (u32)((pBuf)->nSpace) ? 0 : \
  189358. sqlite3Fts5BufferSize((pRc),(pBuf),(nn)+(pBuf)->n) \
  189359. )
  189360. /* Write and decode big-endian 32-bit integer values */
  189361. static void sqlite3Fts5Put32(u8*, int);
  189362. static int sqlite3Fts5Get32(const u8*);
  189363. #define FTS5_POS2COLUMN(iPos) (int)(iPos >> 32)
  189364. #define FTS5_POS2OFFSET(iPos) (int)(iPos & 0x7FFFFFFF)
  189365. typedef struct Fts5PoslistReader Fts5PoslistReader;
  189366. struct Fts5PoslistReader {
  189367. /* Variables used only by sqlite3Fts5PoslistIterXXX() functions. */
  189368. const u8 *a; /* Position list to iterate through */
  189369. int n; /* Size of buffer at a[] in bytes */
  189370. int i; /* Current offset in a[] */
  189371. u8 bFlag; /* For client use (any custom purpose) */
  189372. /* Output variables */
  189373. u8 bEof; /* Set to true at EOF */
  189374. i64 iPos; /* (iCol<<32) + iPos */
  189375. };
  189376. static int sqlite3Fts5PoslistReaderInit(
  189377. const u8 *a, int n, /* Poslist buffer to iterate through */
  189378. Fts5PoslistReader *pIter /* Iterator object to initialize */
  189379. );
  189380. static int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader*);
  189381. typedef struct Fts5PoslistWriter Fts5PoslistWriter;
  189382. struct Fts5PoslistWriter {
  189383. i64 iPrev;
  189384. };
  189385. static int sqlite3Fts5PoslistWriterAppend(Fts5Buffer*, Fts5PoslistWriter*, i64);
  189386. static void sqlite3Fts5PoslistSafeAppend(Fts5Buffer*, i64*, i64);
  189387. static int sqlite3Fts5PoslistNext64(
  189388. const u8 *a, int n, /* Buffer containing poslist */
  189389. int *pi, /* IN/OUT: Offset within a[] */
  189390. i64 *piOff /* IN/OUT: Current offset */
  189391. );
  189392. /* Malloc utility */
  189393. static void *sqlite3Fts5MallocZero(int *pRc, sqlite3_int64 nByte);
  189394. static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn);
  189395. /* Character set tests (like isspace(), isalpha() etc.) */
  189396. static int sqlite3Fts5IsBareword(char t);
  189397. /* Bucket of terms object used by the integrity-check in offsets=0 mode. */
  189398. typedef struct Fts5Termset Fts5Termset;
  189399. static int sqlite3Fts5TermsetNew(Fts5Termset**);
  189400. static int sqlite3Fts5TermsetAdd(Fts5Termset*, int, const char*, int, int *pbPresent);
  189401. static void sqlite3Fts5TermsetFree(Fts5Termset*);
  189402. /*
  189403. ** End of interface to code in fts5_buffer.c.
  189404. **************************************************************************/
  189405. /**************************************************************************
  189406. ** Interface to code in fts5_index.c. fts5_index.c contains contains code
  189407. ** to access the data stored in the %_data table.
  189408. */
  189409. typedef struct Fts5Index Fts5Index;
  189410. typedef struct Fts5IndexIter Fts5IndexIter;
  189411. struct Fts5IndexIter {
  189412. i64 iRowid;
  189413. const u8 *pData;
  189414. int nData;
  189415. u8 bEof;
  189416. };
  189417. #define sqlite3Fts5IterEof(x) ((x)->bEof)
  189418. /*
  189419. ** Values used as part of the flags argument passed to IndexQuery().
  189420. */
  189421. #define FTS5INDEX_QUERY_PREFIX 0x0001 /* Prefix query */
  189422. #define FTS5INDEX_QUERY_DESC 0x0002 /* Docs in descending rowid order */
  189423. #define FTS5INDEX_QUERY_TEST_NOIDX 0x0004 /* Do not use prefix index */
  189424. #define FTS5INDEX_QUERY_SCAN 0x0008 /* Scan query (fts5vocab) */
  189425. /* The following are used internally by the fts5_index.c module. They are
  189426. ** defined here only to make it easier to avoid clashes with the flags
  189427. ** above. */
  189428. #define FTS5INDEX_QUERY_SKIPEMPTY 0x0010
  189429. #define FTS5INDEX_QUERY_NOOUTPUT 0x0020
  189430. /*
  189431. ** Create/destroy an Fts5Index object.
  189432. */
  189433. static int sqlite3Fts5IndexOpen(Fts5Config *pConfig, int bCreate, Fts5Index**, char**);
  189434. static int sqlite3Fts5IndexClose(Fts5Index *p);
  189435. /*
  189436. ** Return a simple checksum value based on the arguments.
  189437. */
  189438. static u64 sqlite3Fts5IndexEntryCksum(
  189439. i64 iRowid,
  189440. int iCol,
  189441. int iPos,
  189442. int iIdx,
  189443. const char *pTerm,
  189444. int nTerm
  189445. );
  189446. /*
  189447. ** Argument p points to a buffer containing utf-8 text that is n bytes in
  189448. ** size. Return the number of bytes in the nChar character prefix of the
  189449. ** buffer, or 0 if there are less than nChar characters in total.
  189450. */
  189451. static int sqlite3Fts5IndexCharlenToBytelen(
  189452. const char *p,
  189453. int nByte,
  189454. int nChar
  189455. );
  189456. /*
  189457. ** Open a new iterator to iterate though all rowids that match the
  189458. ** specified token or token prefix.
  189459. */
  189460. static int sqlite3Fts5IndexQuery(
  189461. Fts5Index *p, /* FTS index to query */
  189462. const char *pToken, int nToken, /* Token (or prefix) to query for */
  189463. int flags, /* Mask of FTS5INDEX_QUERY_X flags */
  189464. Fts5Colset *pColset, /* Match these columns only */
  189465. Fts5IndexIter **ppIter /* OUT: New iterator object */
  189466. );
  189467. /*
  189468. ** The various operations on open token or token prefix iterators opened
  189469. ** using sqlite3Fts5IndexQuery().
  189470. */
  189471. static int sqlite3Fts5IterNext(Fts5IndexIter*);
  189472. static int sqlite3Fts5IterNextFrom(Fts5IndexIter*, i64 iMatch);
  189473. /*
  189474. ** Close an iterator opened by sqlite3Fts5IndexQuery().
  189475. */
  189476. static void sqlite3Fts5IterClose(Fts5IndexIter*);
  189477. /*
  189478. ** This interface is used by the fts5vocab module.
  189479. */
  189480. static const char *sqlite3Fts5IterTerm(Fts5IndexIter*, int*);
  189481. static int sqlite3Fts5IterNextScan(Fts5IndexIter*);
  189482. /*
  189483. ** Insert or remove data to or from the index. Each time a document is
  189484. ** added to or removed from the index, this function is called one or more
  189485. ** times.
  189486. **
  189487. ** For an insert, it must be called once for each token in the new document.
  189488. ** If the operation is a delete, it must be called (at least) once for each
  189489. ** unique token in the document with an iCol value less than zero. The iPos
  189490. ** argument is ignored for a delete.
  189491. */
  189492. static int sqlite3Fts5IndexWrite(
  189493. Fts5Index *p, /* Index to write to */
  189494. int iCol, /* Column token appears in (-ve -> delete) */
  189495. int iPos, /* Position of token within column */
  189496. const char *pToken, int nToken /* Token to add or remove to or from index */
  189497. );
  189498. /*
  189499. ** Indicate that subsequent calls to sqlite3Fts5IndexWrite() pertain to
  189500. ** document iDocid.
  189501. */
  189502. static int sqlite3Fts5IndexBeginWrite(
  189503. Fts5Index *p, /* Index to write to */
  189504. int bDelete, /* True if current operation is a delete */
  189505. i64 iDocid /* Docid to add or remove data from */
  189506. );
  189507. /*
  189508. ** Flush any data stored in the in-memory hash tables to the database.
  189509. ** Also close any open blob handles.
  189510. */
  189511. static int sqlite3Fts5IndexSync(Fts5Index *p);
  189512. /*
  189513. ** Discard any data stored in the in-memory hash tables. Do not write it
  189514. ** to the database. Additionally, assume that the contents of the %_data
  189515. ** table may have changed on disk. So any in-memory caches of %_data
  189516. ** records must be invalidated.
  189517. */
  189518. static int sqlite3Fts5IndexRollback(Fts5Index *p);
  189519. /*
  189520. ** Get or set the "averages" values.
  189521. */
  189522. static int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize);
  189523. static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8*, int);
  189524. /*
  189525. ** Functions called by the storage module as part of integrity-check.
  189526. */
  189527. static int sqlite3Fts5IndexIntegrityCheck(Fts5Index*, u64 cksum);
  189528. /*
  189529. ** Called during virtual module initialization to register UDF
  189530. ** fts5_decode() with SQLite
  189531. */
  189532. static int sqlite3Fts5IndexInit(sqlite3*);
  189533. static int sqlite3Fts5IndexSetCookie(Fts5Index*, int);
  189534. /*
  189535. ** Return the total number of entries read from the %_data table by
  189536. ** this connection since it was created.
  189537. */
  189538. static int sqlite3Fts5IndexReads(Fts5Index *p);
  189539. static int sqlite3Fts5IndexReinit(Fts5Index *p);
  189540. static int sqlite3Fts5IndexOptimize(Fts5Index *p);
  189541. static int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge);
  189542. static int sqlite3Fts5IndexReset(Fts5Index *p);
  189543. static int sqlite3Fts5IndexLoadConfig(Fts5Index *p);
  189544. /*
  189545. ** End of interface to code in fts5_index.c.
  189546. **************************************************************************/
  189547. /**************************************************************************
  189548. ** Interface to code in fts5_varint.c.
  189549. */
  189550. static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v);
  189551. static int sqlite3Fts5GetVarintLen(u32 iVal);
  189552. static u8 sqlite3Fts5GetVarint(const unsigned char*, u64*);
  189553. static int sqlite3Fts5PutVarint(unsigned char *p, u64 v);
  189554. #define fts5GetVarint32(a,b) sqlite3Fts5GetVarint32(a,(u32*)&b)
  189555. #define fts5GetVarint sqlite3Fts5GetVarint
  189556. #define fts5FastGetVarint32(a, iOff, nVal) { \
  189557. nVal = (a)[iOff++]; \
  189558. if( nVal & 0x80 ){ \
  189559. iOff--; \
  189560. iOff += fts5GetVarint32(&(a)[iOff], nVal); \
  189561. } \
  189562. }
  189563. /*
  189564. ** End of interface to code in fts5_varint.c.
  189565. **************************************************************************/
  189566. /**************************************************************************
  189567. ** Interface to code in fts5_main.c.
  189568. */
  189569. /*
  189570. ** Virtual-table object.
  189571. */
  189572. typedef struct Fts5Table Fts5Table;
  189573. struct Fts5Table {
  189574. sqlite3_vtab base; /* Base class used by SQLite core */
  189575. Fts5Config *pConfig; /* Virtual table configuration */
  189576. Fts5Index *pIndex; /* Full-text index */
  189577. };
  189578. static int sqlite3Fts5GetTokenizer(
  189579. Fts5Global*,
  189580. const char **azArg,
  189581. int nArg,
  189582. Fts5Tokenizer**,
  189583. fts5_tokenizer**,
  189584. char **pzErr
  189585. );
  189586. static Fts5Table *sqlite3Fts5TableFromCsrid(Fts5Global*, i64);
  189587. static int sqlite3Fts5FlushToDisk(Fts5Table*);
  189588. /*
  189589. ** End of interface to code in fts5.c.
  189590. **************************************************************************/
  189591. /**************************************************************************
  189592. ** Interface to code in fts5_hash.c.
  189593. */
  189594. typedef struct Fts5Hash Fts5Hash;
  189595. /*
  189596. ** Create a hash table, free a hash table.
  189597. */
  189598. static int sqlite3Fts5HashNew(Fts5Config*, Fts5Hash**, int *pnSize);
  189599. static void sqlite3Fts5HashFree(Fts5Hash*);
  189600. static int sqlite3Fts5HashWrite(
  189601. Fts5Hash*,
  189602. i64 iRowid, /* Rowid for this entry */
  189603. int iCol, /* Column token appears in (-ve -> delete) */
  189604. int iPos, /* Position of token within column */
  189605. char bByte,
  189606. const char *pToken, int nToken /* Token to add or remove to or from index */
  189607. );
  189608. /*
  189609. ** Empty (but do not delete) a hash table.
  189610. */
  189611. static void sqlite3Fts5HashClear(Fts5Hash*);
  189612. static int sqlite3Fts5HashQuery(
  189613. Fts5Hash*, /* Hash table to query */
  189614. int nPre,
  189615. const char *pTerm, int nTerm, /* Query term */
  189616. void **ppObj, /* OUT: Pointer to doclist for pTerm */
  189617. int *pnDoclist /* OUT: Size of doclist in bytes */
  189618. );
  189619. static int sqlite3Fts5HashScanInit(
  189620. Fts5Hash*, /* Hash table to query */
  189621. const char *pTerm, int nTerm /* Query prefix */
  189622. );
  189623. static void sqlite3Fts5HashScanNext(Fts5Hash*);
  189624. static int sqlite3Fts5HashScanEof(Fts5Hash*);
  189625. static void sqlite3Fts5HashScanEntry(Fts5Hash *,
  189626. const char **pzTerm, /* OUT: term (nul-terminated) */
  189627. const u8 **ppDoclist, /* OUT: pointer to doclist */
  189628. int *pnDoclist /* OUT: size of doclist in bytes */
  189629. );
  189630. /*
  189631. ** End of interface to code in fts5_hash.c.
  189632. **************************************************************************/
  189633. /**************************************************************************
  189634. ** Interface to code in fts5_storage.c. fts5_storage.c contains contains
  189635. ** code to access the data stored in the %_content and %_docsize tables.
  189636. */
  189637. #define FTS5_STMT_SCAN_ASC 0 /* SELECT rowid, * FROM ... ORDER BY 1 ASC */
  189638. #define FTS5_STMT_SCAN_DESC 1 /* SELECT rowid, * FROM ... ORDER BY 1 DESC */
  189639. #define FTS5_STMT_LOOKUP 2 /* SELECT rowid, * FROM ... WHERE rowid=? */
  189640. typedef struct Fts5Storage Fts5Storage;
  189641. static int sqlite3Fts5StorageOpen(Fts5Config*, Fts5Index*, int, Fts5Storage**, char**);
  189642. static int sqlite3Fts5StorageClose(Fts5Storage *p);
  189643. static int sqlite3Fts5StorageRename(Fts5Storage*, const char *zName);
  189644. static int sqlite3Fts5DropAll(Fts5Config*);
  189645. static int sqlite3Fts5CreateTable(Fts5Config*, const char*, const char*, int, char **);
  189646. static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64, sqlite3_value**);
  189647. static int sqlite3Fts5StorageContentInsert(Fts5Storage *p, sqlite3_value**, i64*);
  189648. static int sqlite3Fts5StorageIndexInsert(Fts5Storage *p, sqlite3_value**, i64);
  189649. static int sqlite3Fts5StorageIntegrity(Fts5Storage *p);
  189650. static int sqlite3Fts5StorageStmt(Fts5Storage *p, int eStmt, sqlite3_stmt**, char**);
  189651. static void sqlite3Fts5StorageStmtRelease(Fts5Storage *p, int eStmt, sqlite3_stmt*);
  189652. static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol);
  189653. static int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnAvg);
  189654. static int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow);
  189655. static int sqlite3Fts5StorageSync(Fts5Storage *p);
  189656. static int sqlite3Fts5StorageRollback(Fts5Storage *p);
  189657. static int sqlite3Fts5StorageConfigValue(
  189658. Fts5Storage *p, const char*, sqlite3_value*, int
  189659. );
  189660. static int sqlite3Fts5StorageDeleteAll(Fts5Storage *p);
  189661. static int sqlite3Fts5StorageRebuild(Fts5Storage *p);
  189662. static int sqlite3Fts5StorageOptimize(Fts5Storage *p);
  189663. static int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge);
  189664. static int sqlite3Fts5StorageReset(Fts5Storage *p);
  189665. /*
  189666. ** End of interface to code in fts5_storage.c.
  189667. **************************************************************************/
  189668. /**************************************************************************
  189669. ** Interface to code in fts5_expr.c.
  189670. */
  189671. typedef struct Fts5Expr Fts5Expr;
  189672. typedef struct Fts5ExprNode Fts5ExprNode;
  189673. typedef struct Fts5Parse Fts5Parse;
  189674. typedef struct Fts5Token Fts5Token;
  189675. typedef struct Fts5ExprPhrase Fts5ExprPhrase;
  189676. typedef struct Fts5ExprNearset Fts5ExprNearset;
  189677. struct Fts5Token {
  189678. const char *p; /* Token text (not NULL terminated) */
  189679. int n; /* Size of buffer p in bytes */
  189680. };
  189681. /* Parse a MATCH expression. */
  189682. static int sqlite3Fts5ExprNew(
  189683. Fts5Config *pConfig,
  189684. int iCol, /* Column on LHS of MATCH operator */
  189685. const char *zExpr,
  189686. Fts5Expr **ppNew,
  189687. char **pzErr
  189688. );
  189689. /*
  189690. ** for(rc = sqlite3Fts5ExprFirst(pExpr, pIdx, bDesc);
  189691. ** rc==SQLITE_OK && 0==sqlite3Fts5ExprEof(pExpr);
  189692. ** rc = sqlite3Fts5ExprNext(pExpr)
  189693. ** ){
  189694. ** // The document with rowid iRowid matches the expression!
  189695. ** i64 iRowid = sqlite3Fts5ExprRowid(pExpr);
  189696. ** }
  189697. */
  189698. static int sqlite3Fts5ExprFirst(Fts5Expr*, Fts5Index *pIdx, i64 iMin, int bDesc);
  189699. static int sqlite3Fts5ExprNext(Fts5Expr*, i64 iMax);
  189700. static int sqlite3Fts5ExprEof(Fts5Expr*);
  189701. static i64 sqlite3Fts5ExprRowid(Fts5Expr*);
  189702. static void sqlite3Fts5ExprFree(Fts5Expr*);
  189703. /* Called during startup to register a UDF with SQLite */
  189704. static int sqlite3Fts5ExprInit(Fts5Global*, sqlite3*);
  189705. static int sqlite3Fts5ExprPhraseCount(Fts5Expr*);
  189706. static int sqlite3Fts5ExprPhraseSize(Fts5Expr*, int iPhrase);
  189707. static int sqlite3Fts5ExprPoslist(Fts5Expr*, int, const u8 **);
  189708. typedef struct Fts5PoslistPopulator Fts5PoslistPopulator;
  189709. static Fts5PoslistPopulator *sqlite3Fts5ExprClearPoslists(Fts5Expr*, int);
  189710. static int sqlite3Fts5ExprPopulatePoslists(
  189711. Fts5Config*, Fts5Expr*, Fts5PoslistPopulator*, int, const char*, int
  189712. );
  189713. static void sqlite3Fts5ExprCheckPoslists(Fts5Expr*, i64);
  189714. static int sqlite3Fts5ExprClonePhrase(Fts5Expr*, int, Fts5Expr**);
  189715. static int sqlite3Fts5ExprPhraseCollist(Fts5Expr *, int, const u8 **, int *);
  189716. /*******************************************
  189717. ** The fts5_expr.c API above this point is used by the other hand-written
  189718. ** C code in this module. The interfaces below this point are called by
  189719. ** the parser code in fts5parse.y. */
  189720. static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...);
  189721. static Fts5ExprNode *sqlite3Fts5ParseNode(
  189722. Fts5Parse *pParse,
  189723. int eType,
  189724. Fts5ExprNode *pLeft,
  189725. Fts5ExprNode *pRight,
  189726. Fts5ExprNearset *pNear
  189727. );
  189728. static Fts5ExprNode *sqlite3Fts5ParseImplicitAnd(
  189729. Fts5Parse *pParse,
  189730. Fts5ExprNode *pLeft,
  189731. Fts5ExprNode *pRight
  189732. );
  189733. static Fts5ExprPhrase *sqlite3Fts5ParseTerm(
  189734. Fts5Parse *pParse,
  189735. Fts5ExprPhrase *pPhrase,
  189736. Fts5Token *pToken,
  189737. int bPrefix
  189738. );
  189739. static void sqlite3Fts5ParseSetCaret(Fts5ExprPhrase*);
  189740. static Fts5ExprNearset *sqlite3Fts5ParseNearset(
  189741. Fts5Parse*,
  189742. Fts5ExprNearset*,
  189743. Fts5ExprPhrase*
  189744. );
  189745. static Fts5Colset *sqlite3Fts5ParseColset(
  189746. Fts5Parse*,
  189747. Fts5Colset*,
  189748. Fts5Token *
  189749. );
  189750. static void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase*);
  189751. static void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset*);
  189752. static void sqlite3Fts5ParseNodeFree(Fts5ExprNode*);
  189753. static void sqlite3Fts5ParseSetDistance(Fts5Parse*, Fts5ExprNearset*, Fts5Token*);
  189754. static void sqlite3Fts5ParseSetColset(Fts5Parse*, Fts5ExprNode*, Fts5Colset*);
  189755. static Fts5Colset *sqlite3Fts5ParseColsetInvert(Fts5Parse*, Fts5Colset*);
  189756. static void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p);
  189757. static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token*);
  189758. /*
  189759. ** End of interface to code in fts5_expr.c.
  189760. **************************************************************************/
  189761. /**************************************************************************
  189762. ** Interface to code in fts5_aux.c.
  189763. */
  189764. static int sqlite3Fts5AuxInit(fts5_api*);
  189765. /*
  189766. ** End of interface to code in fts5_aux.c.
  189767. **************************************************************************/
  189768. /**************************************************************************
  189769. ** Interface to code in fts5_tokenizer.c.
  189770. */
  189771. static int sqlite3Fts5TokenizerInit(fts5_api*);
  189772. /*
  189773. ** End of interface to code in fts5_tokenizer.c.
  189774. **************************************************************************/
  189775. /**************************************************************************
  189776. ** Interface to code in fts5_vocab.c.
  189777. */
  189778. static int sqlite3Fts5VocabInit(Fts5Global*, sqlite3*);
  189779. /*
  189780. ** End of interface to code in fts5_vocab.c.
  189781. **************************************************************************/
  189782. /**************************************************************************
  189783. ** Interface to automatically generated code in fts5_unicode2.c.
  189784. */
  189785. static int sqlite3Fts5UnicodeIsdiacritic(int c);
  189786. static int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic);
  189787. static int sqlite3Fts5UnicodeCatParse(const char*, u8*);
  189788. static int sqlite3Fts5UnicodeCategory(u32 iCode);
  189789. static void sqlite3Fts5UnicodeAscii(u8*, u8*);
  189790. /*
  189791. ** End of interface to code in fts5_unicode2.c.
  189792. **************************************************************************/
  189793. #endif
  189794. #define FTS5_OR 1
  189795. #define FTS5_AND 2
  189796. #define FTS5_NOT 3
  189797. #define FTS5_TERM 4
  189798. #define FTS5_COLON 5
  189799. #define FTS5_MINUS 6
  189800. #define FTS5_LCP 7
  189801. #define FTS5_RCP 8
  189802. #define FTS5_STRING 9
  189803. #define FTS5_LP 10
  189804. #define FTS5_RP 11
  189805. #define FTS5_CARET 12
  189806. #define FTS5_COMMA 13
  189807. #define FTS5_PLUS 14
  189808. #define FTS5_STAR 15
  189809. /*
  189810. ** 2000-05-29
  189811. **
  189812. ** The author disclaims copyright to this source code. In place of
  189813. ** a legal notice, here is a blessing:
  189814. **
  189815. ** May you do good and not evil.
  189816. ** May you find forgiveness for yourself and forgive others.
  189817. ** May you share freely, never taking more than you give.
  189818. **
  189819. *************************************************************************
  189820. ** Driver template for the LEMON parser generator.
  189821. **
  189822. ** The "lemon" program processes an LALR(1) input grammar file, then uses
  189823. ** this template to construct a parser. The "lemon" program inserts text
  189824. ** at each "%%" line. Also, any "P-a-r-s-e" identifer prefix (without the
  189825. ** interstitial "-" characters) contained in this template is changed into
  189826. ** the value of the %name directive from the grammar. Otherwise, the content
  189827. ** of this template is copied straight through into the generate parser
  189828. ** source file.
  189829. **
  189830. ** The following is the concatenation of all %include directives from the
  189831. ** input grammar file:
  189832. */
  189833. /* #include <stdio.h> */
  189834. /* #include <assert.h> */
  189835. /************ Begin %include sections from the grammar ************************/
  189836. /* #include "fts5Int.h" */
  189837. /* #include "fts5parse.h" */
  189838. /*
  189839. ** Disable all error recovery processing in the parser push-down
  189840. ** automaton.
  189841. */
  189842. #define fts5YYNOERRORRECOVERY 1
  189843. /*
  189844. ** Make fts5yytestcase() the same as testcase()
  189845. */
  189846. #define fts5yytestcase(X) testcase(X)
  189847. /*
  189848. ** Indicate that sqlite3ParserFree() will never be called with a null
  189849. ** pointer.
  189850. */
  189851. #define fts5YYPARSEFREENOTNULL 1
  189852. /*
  189853. ** Alternative datatype for the argument to the malloc() routine passed
  189854. ** into sqlite3ParserAlloc(). The default is size_t.
  189855. */
  189856. #define fts5YYMALLOCARGTYPE u64
  189857. /**************** End of %include directives **********************************/
  189858. /* These constants specify the various numeric values for terminal symbols
  189859. ** in a format understandable to "makeheaders". This section is blank unless
  189860. ** "lemon" is run with the "-m" command-line option.
  189861. ***************** Begin makeheaders token definitions *************************/
  189862. /**************** End makeheaders token definitions ***************************/
  189863. /* The next sections is a series of control #defines.
  189864. ** various aspects of the generated parser.
  189865. ** fts5YYCODETYPE is the data type used to store the integer codes
  189866. ** that represent terminal and non-terminal symbols.
  189867. ** "unsigned char" is used if there are fewer than
  189868. ** 256 symbols. Larger types otherwise.
  189869. ** fts5YYNOCODE is a number of type fts5YYCODETYPE that is not used for
  189870. ** any terminal or nonterminal symbol.
  189871. ** fts5YYFALLBACK If defined, this indicates that one or more tokens
  189872. ** (also known as: "terminal symbols") have fall-back
  189873. ** values which should be used if the original symbol
  189874. ** would not parse. This permits keywords to sometimes
  189875. ** be used as identifiers, for example.
  189876. ** fts5YYACTIONTYPE is the data type used for "action codes" - numbers
  189877. ** that indicate what to do in response to the next
  189878. ** token.
  189879. ** sqlite3Fts5ParserFTS5TOKENTYPE is the data type used for minor type for terminal
  189880. ** symbols. Background: A "minor type" is a semantic
  189881. ** value associated with a terminal or non-terminal
  189882. ** symbols. For example, for an "ID" terminal symbol,
  189883. ** the minor type might be the name of the identifier.
  189884. ** Each non-terminal can have a different minor type.
  189885. ** Terminal symbols all have the same minor type, though.
  189886. ** This macros defines the minor type for terminal
  189887. ** symbols.
  189888. ** fts5YYMINORTYPE is the data type used for all minor types.
  189889. ** This is typically a union of many types, one of
  189890. ** which is sqlite3Fts5ParserFTS5TOKENTYPE. The entry in the union
  189891. ** for terminal symbols is called "fts5yy0".
  189892. ** fts5YYSTACKDEPTH is the maximum depth of the parser's stack. If
  189893. ** zero the stack is dynamically sized using realloc()
  189894. ** sqlite3Fts5ParserARG_SDECL A static variable declaration for the %extra_argument
  189895. ** sqlite3Fts5ParserARG_PDECL A parameter declaration for the %extra_argument
  189896. ** sqlite3Fts5ParserARG_PARAM Code to pass %extra_argument as a subroutine parameter
  189897. ** sqlite3Fts5ParserARG_STORE Code to store %extra_argument into fts5yypParser
  189898. ** sqlite3Fts5ParserARG_FETCH Code to extract %extra_argument from fts5yypParser
  189899. ** sqlite3Fts5ParserCTX_* As sqlite3Fts5ParserARG_ except for %extra_context
  189900. ** fts5YYERRORSYMBOL is the code number of the error symbol. If not
  189901. ** defined, then do no error processing.
  189902. ** fts5YYNSTATE the combined number of states.
  189903. ** fts5YYNRULE the number of rules in the grammar
  189904. ** fts5YYNFTS5TOKEN Number of terminal symbols
  189905. ** fts5YY_MAX_SHIFT Maximum value for shift actions
  189906. ** fts5YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions
  189907. ** fts5YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions
  189908. ** fts5YY_ERROR_ACTION The fts5yy_action[] code for syntax error
  189909. ** fts5YY_ACCEPT_ACTION The fts5yy_action[] code for accept
  189910. ** fts5YY_NO_ACTION The fts5yy_action[] code for no-op
  189911. ** fts5YY_MIN_REDUCE Minimum value for reduce actions
  189912. ** fts5YY_MAX_REDUCE Maximum value for reduce actions
  189913. */
  189914. #ifndef INTERFACE
  189915. # define INTERFACE 1
  189916. #endif
  189917. /************* Begin control #defines *****************************************/
  189918. #define fts5YYCODETYPE unsigned char
  189919. #define fts5YYNOCODE 27
  189920. #define fts5YYACTIONTYPE unsigned char
  189921. #define sqlite3Fts5ParserFTS5TOKENTYPE Fts5Token
  189922. typedef union {
  189923. int fts5yyinit;
  189924. sqlite3Fts5ParserFTS5TOKENTYPE fts5yy0;
  189925. int fts5yy4;
  189926. Fts5Colset* fts5yy11;
  189927. Fts5ExprNode* fts5yy24;
  189928. Fts5ExprNearset* fts5yy46;
  189929. Fts5ExprPhrase* fts5yy53;
  189930. } fts5YYMINORTYPE;
  189931. #ifndef fts5YYSTACKDEPTH
  189932. #define fts5YYSTACKDEPTH 100
  189933. #endif
  189934. #define sqlite3Fts5ParserARG_SDECL Fts5Parse *pParse;
  189935. #define sqlite3Fts5ParserARG_PDECL ,Fts5Parse *pParse
  189936. #define sqlite3Fts5ParserARG_PARAM ,pParse
  189937. #define sqlite3Fts5ParserARG_FETCH Fts5Parse *pParse=fts5yypParser->pParse;
  189938. #define sqlite3Fts5ParserARG_STORE fts5yypParser->pParse=pParse;
  189939. #define sqlite3Fts5ParserCTX_SDECL
  189940. #define sqlite3Fts5ParserCTX_PDECL
  189941. #define sqlite3Fts5ParserCTX_PARAM
  189942. #define sqlite3Fts5ParserCTX_FETCH
  189943. #define sqlite3Fts5ParserCTX_STORE
  189944. #define fts5YYNSTATE 35
  189945. #define fts5YYNRULE 28
  189946. #define fts5YYNFTS5TOKEN 16
  189947. #define fts5YY_MAX_SHIFT 34
  189948. #define fts5YY_MIN_SHIFTREDUCE 52
  189949. #define fts5YY_MAX_SHIFTREDUCE 79
  189950. #define fts5YY_ERROR_ACTION 80
  189951. #define fts5YY_ACCEPT_ACTION 81
  189952. #define fts5YY_NO_ACTION 82
  189953. #define fts5YY_MIN_REDUCE 83
  189954. #define fts5YY_MAX_REDUCE 110
  189955. /************* End control #defines *******************************************/
  189956. #define fts5YY_NLOOKAHEAD ((int)(sizeof(fts5yy_lookahead)/sizeof(fts5yy_lookahead[0])))
  189957. /* Define the fts5yytestcase() macro to be a no-op if is not already defined
  189958. ** otherwise.
  189959. **
  189960. ** Applications can choose to define fts5yytestcase() in the %include section
  189961. ** to a macro that can assist in verifying code coverage. For production
  189962. ** code the fts5yytestcase() macro should be turned off. But it is useful
  189963. ** for testing.
  189964. */
  189965. #ifndef fts5yytestcase
  189966. # define fts5yytestcase(X)
  189967. #endif
  189968. /* Next are the tables used to determine what action to take based on the
  189969. ** current state and lookahead token. These tables are used to implement
  189970. ** functions that take a state number and lookahead value and return an
  189971. ** action integer.
  189972. **
  189973. ** Suppose the action integer is N. Then the action is determined as
  189974. ** follows
  189975. **
  189976. ** 0 <= N <= fts5YY_MAX_SHIFT Shift N. That is, push the lookahead
  189977. ** token onto the stack and goto state N.
  189978. **
  189979. ** N between fts5YY_MIN_SHIFTREDUCE Shift to an arbitrary state then
  189980. ** and fts5YY_MAX_SHIFTREDUCE reduce by rule N-fts5YY_MIN_SHIFTREDUCE.
  189981. **
  189982. ** N == fts5YY_ERROR_ACTION A syntax error has occurred.
  189983. **
  189984. ** N == fts5YY_ACCEPT_ACTION The parser accepts its input.
  189985. **
  189986. ** N == fts5YY_NO_ACTION No such action. Denotes unused
  189987. ** slots in the fts5yy_action[] table.
  189988. **
  189989. ** N between fts5YY_MIN_REDUCE Reduce by rule N-fts5YY_MIN_REDUCE
  189990. ** and fts5YY_MAX_REDUCE
  189991. **
  189992. ** The action table is constructed as a single large table named fts5yy_action[].
  189993. ** Given state S and lookahead X, the action is computed as either:
  189994. **
  189995. ** (A) N = fts5yy_action[ fts5yy_shift_ofst[S] + X ]
  189996. ** (B) N = fts5yy_default[S]
  189997. **
  189998. ** The (A) formula is preferred. The B formula is used instead if
  189999. ** fts5yy_lookahead[fts5yy_shift_ofst[S]+X] is not equal to X.
  190000. **
  190001. ** The formulas above are for computing the action when the lookahead is
  190002. ** a terminal symbol. If the lookahead is a non-terminal (as occurs after
  190003. ** a reduce action) then the fts5yy_reduce_ofst[] array is used in place of
  190004. ** the fts5yy_shift_ofst[] array.
  190005. **
  190006. ** The following are the tables generated in this section:
  190007. **
  190008. ** fts5yy_action[] A single table containing all actions.
  190009. ** fts5yy_lookahead[] A table containing the lookahead for each entry in
  190010. ** fts5yy_action. Used to detect hash collisions.
  190011. ** fts5yy_shift_ofst[] For each state, the offset into fts5yy_action for
  190012. ** shifting terminals.
  190013. ** fts5yy_reduce_ofst[] For each state, the offset into fts5yy_action for
  190014. ** shifting non-terminals after a reduce.
  190015. ** fts5yy_default[] Default action for each state.
  190016. **
  190017. *********** Begin parsing tables **********************************************/
  190018. #define fts5YY_ACTTAB_COUNT (105)
  190019. static const fts5YYACTIONTYPE fts5yy_action[] = {
  190020. /* 0 */ 81, 20, 96, 6, 28, 99, 98, 26, 26, 18,
  190021. /* 10 */ 96, 6, 28, 17, 98, 56, 26, 19, 96, 6,
  190022. /* 20 */ 28, 14, 98, 14, 26, 31, 92, 96, 6, 28,
  190023. /* 30 */ 108, 98, 25, 26, 21, 96, 6, 28, 78, 98,
  190024. /* 40 */ 58, 26, 29, 96, 6, 28, 107, 98, 22, 26,
  190025. /* 50 */ 24, 16, 12, 11, 1, 13, 13, 24, 16, 23,
  190026. /* 60 */ 11, 33, 34, 13, 97, 8, 27, 32, 98, 7,
  190027. /* 70 */ 26, 3, 4, 5, 3, 4, 5, 3, 83, 4,
  190028. /* 80 */ 5, 3, 63, 5, 3, 62, 12, 2, 86, 13,
  190029. /* 90 */ 9, 30, 10, 10, 54, 57, 75, 78, 78, 53,
  190030. /* 100 */ 57, 15, 82, 82, 71,
  190031. };
  190032. static const fts5YYCODETYPE fts5yy_lookahead[] = {
  190033. /* 0 */ 16, 17, 18, 19, 20, 22, 22, 24, 24, 17,
  190034. /* 10 */ 18, 19, 20, 7, 22, 9, 24, 17, 18, 19,
  190035. /* 20 */ 20, 9, 22, 9, 24, 13, 17, 18, 19, 20,
  190036. /* 30 */ 26, 22, 24, 24, 17, 18, 19, 20, 15, 22,
  190037. /* 40 */ 9, 24, 17, 18, 19, 20, 26, 22, 21, 24,
  190038. /* 50 */ 6, 7, 9, 9, 10, 12, 12, 6, 7, 21,
  190039. /* 60 */ 9, 24, 25, 12, 18, 5, 20, 14, 22, 5,
  190040. /* 70 */ 24, 3, 1, 2, 3, 1, 2, 3, 0, 1,
  190041. /* 80 */ 2, 3, 11, 2, 3, 11, 9, 10, 5, 12,
  190042. /* 90 */ 23, 24, 10, 10, 8, 9, 9, 15, 15, 8,
  190043. /* 100 */ 9, 9, 27, 27, 11, 27, 27, 27, 27, 27,
  190044. /* 110 */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  190045. /* 120 */ 27,
  190046. };
  190047. #define fts5YY_SHIFT_COUNT (34)
  190048. #define fts5YY_SHIFT_MIN (0)
  190049. #define fts5YY_SHIFT_MAX (93)
  190050. static const unsigned char fts5yy_shift_ofst[] = {
  190051. /* 0 */ 44, 44, 44, 44, 44, 44, 51, 77, 43, 12,
  190052. /* 10 */ 14, 83, 82, 14, 23, 23, 31, 31, 71, 74,
  190053. /* 20 */ 78, 81, 86, 91, 6, 53, 53, 60, 64, 68,
  190054. /* 30 */ 53, 87, 92, 53, 93,
  190055. };
  190056. #define fts5YY_REDUCE_COUNT (17)
  190057. #define fts5YY_REDUCE_MIN (-17)
  190058. #define fts5YY_REDUCE_MAX (67)
  190059. static const signed char fts5yy_reduce_ofst[] = {
  190060. /* 0 */ -16, -8, 0, 9, 17, 25, 46, -17, -17, 37,
  190061. /* 10 */ 67, 4, 4, 8, 4, 20, 27, 38,
  190062. };
  190063. static const fts5YYACTIONTYPE fts5yy_default[] = {
  190064. /* 0 */ 80, 80, 80, 80, 80, 80, 95, 80, 80, 105,
  190065. /* 10 */ 80, 110, 110, 80, 110, 110, 80, 80, 80, 80,
  190066. /* 20 */ 80, 91, 80, 80, 80, 101, 100, 80, 80, 90,
  190067. /* 30 */ 103, 80, 80, 104, 80,
  190068. };
  190069. /********** End of lemon-generated parsing tables *****************************/
  190070. /* The next table maps tokens (terminal symbols) into fallback tokens.
  190071. ** If a construct like the following:
  190072. **
  190073. ** %fallback ID X Y Z.
  190074. **
  190075. ** appears in the grammar, then ID becomes a fallback token for X, Y,
  190076. ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser
  190077. ** but it does not parse, the type of the token is changed to ID and
  190078. ** the parse is retried before an error is thrown.
  190079. **
  190080. ** This feature can be used, for example, to cause some keywords in a language
  190081. ** to revert to identifiers if they keyword does not apply in the context where
  190082. ** it appears.
  190083. */
  190084. #ifdef fts5YYFALLBACK
  190085. static const fts5YYCODETYPE fts5yyFallback[] = {
  190086. };
  190087. #endif /* fts5YYFALLBACK */
  190088. /* The following structure represents a single element of the
  190089. ** parser's stack. Information stored includes:
  190090. **
  190091. ** + The state number for the parser at this level of the stack.
  190092. **
  190093. ** + The value of the token stored at this level of the stack.
  190094. ** (In other words, the "major" token.)
  190095. **
  190096. ** + The semantic value stored at this level of the stack. This is
  190097. ** the information used by the action routines in the grammar.
  190098. ** It is sometimes called the "minor" token.
  190099. **
  190100. ** After the "shift" half of a SHIFTREDUCE action, the stateno field
  190101. ** actually contains the reduce action for the second half of the
  190102. ** SHIFTREDUCE.
  190103. */
  190104. struct fts5yyStackEntry {
  190105. fts5YYACTIONTYPE stateno; /* The state-number, or reduce action in SHIFTREDUCE */
  190106. fts5YYCODETYPE major; /* The major token value. This is the code
  190107. ** number for the token at this stack level */
  190108. fts5YYMINORTYPE minor; /* The user-supplied minor token value. This
  190109. ** is the value of the token */
  190110. };
  190111. typedef struct fts5yyStackEntry fts5yyStackEntry;
  190112. /* The state of the parser is completely contained in an instance of
  190113. ** the following structure */
  190114. struct fts5yyParser {
  190115. fts5yyStackEntry *fts5yytos; /* Pointer to top element of the stack */
  190116. #ifdef fts5YYTRACKMAXSTACKDEPTH
  190117. int fts5yyhwm; /* High-water mark of the stack */
  190118. #endif
  190119. #ifndef fts5YYNOERRORRECOVERY
  190120. int fts5yyerrcnt; /* Shifts left before out of the error */
  190121. #endif
  190122. sqlite3Fts5ParserARG_SDECL /* A place to hold %extra_argument */
  190123. sqlite3Fts5ParserCTX_SDECL /* A place to hold %extra_context */
  190124. #if fts5YYSTACKDEPTH<=0
  190125. int fts5yystksz; /* Current side of the stack */
  190126. fts5yyStackEntry *fts5yystack; /* The parser's stack */
  190127. fts5yyStackEntry fts5yystk0; /* First stack entry */
  190128. #else
  190129. fts5yyStackEntry fts5yystack[fts5YYSTACKDEPTH]; /* The parser's stack */
  190130. fts5yyStackEntry *fts5yystackEnd; /* Last entry in the stack */
  190131. #endif
  190132. };
  190133. typedef struct fts5yyParser fts5yyParser;
  190134. #ifndef NDEBUG
  190135. /* #include <stdio.h> */
  190136. static FILE *fts5yyTraceFILE = 0;
  190137. static char *fts5yyTracePrompt = 0;
  190138. #endif /* NDEBUG */
  190139. #ifndef NDEBUG
  190140. /*
  190141. ** Turn parser tracing on by giving a stream to which to write the trace
  190142. ** and a prompt to preface each trace message. Tracing is turned off
  190143. ** by making either argument NULL
  190144. **
  190145. ** Inputs:
  190146. ** <ul>
  190147. ** <li> A FILE* to which trace output should be written.
  190148. ** If NULL, then tracing is turned off.
  190149. ** <li> A prefix string written at the beginning of every
  190150. ** line of trace output. If NULL, then tracing is
  190151. ** turned off.
  190152. ** </ul>
  190153. **
  190154. ** Outputs:
  190155. ** None.
  190156. */
  190157. static void sqlite3Fts5ParserTrace(FILE *TraceFILE, char *zTracePrompt){
  190158. fts5yyTraceFILE = TraceFILE;
  190159. fts5yyTracePrompt = zTracePrompt;
  190160. if( fts5yyTraceFILE==0 ) fts5yyTracePrompt = 0;
  190161. else if( fts5yyTracePrompt==0 ) fts5yyTraceFILE = 0;
  190162. }
  190163. #endif /* NDEBUG */
  190164. #if defined(fts5YYCOVERAGE) || !defined(NDEBUG)
  190165. /* For tracing shifts, the names of all terminals and nonterminals
  190166. ** are required. The following table supplies these names */
  190167. static const char *const fts5yyTokenName[] = {
  190168. /* 0 */ "$",
  190169. /* 1 */ "OR",
  190170. /* 2 */ "AND",
  190171. /* 3 */ "NOT",
  190172. /* 4 */ "TERM",
  190173. /* 5 */ "COLON",
  190174. /* 6 */ "MINUS",
  190175. /* 7 */ "LCP",
  190176. /* 8 */ "RCP",
  190177. /* 9 */ "STRING",
  190178. /* 10 */ "LP",
  190179. /* 11 */ "RP",
  190180. /* 12 */ "CARET",
  190181. /* 13 */ "COMMA",
  190182. /* 14 */ "PLUS",
  190183. /* 15 */ "STAR",
  190184. /* 16 */ "input",
  190185. /* 17 */ "expr",
  190186. /* 18 */ "cnearset",
  190187. /* 19 */ "exprlist",
  190188. /* 20 */ "colset",
  190189. /* 21 */ "colsetlist",
  190190. /* 22 */ "nearset",
  190191. /* 23 */ "nearphrases",
  190192. /* 24 */ "phrase",
  190193. /* 25 */ "neardist_opt",
  190194. /* 26 */ "star_opt",
  190195. };
  190196. #endif /* defined(fts5YYCOVERAGE) || !defined(NDEBUG) */
  190197. #ifndef NDEBUG
  190198. /* For tracing reduce actions, the names of all rules are required.
  190199. */
  190200. static const char *const fts5yyRuleName[] = {
  190201. /* 0 */ "input ::= expr",
  190202. /* 1 */ "colset ::= MINUS LCP colsetlist RCP",
  190203. /* 2 */ "colset ::= LCP colsetlist RCP",
  190204. /* 3 */ "colset ::= STRING",
  190205. /* 4 */ "colset ::= MINUS STRING",
  190206. /* 5 */ "colsetlist ::= colsetlist STRING",
  190207. /* 6 */ "colsetlist ::= STRING",
  190208. /* 7 */ "expr ::= expr AND expr",
  190209. /* 8 */ "expr ::= expr OR expr",
  190210. /* 9 */ "expr ::= expr NOT expr",
  190211. /* 10 */ "expr ::= colset COLON LP expr RP",
  190212. /* 11 */ "expr ::= LP expr RP",
  190213. /* 12 */ "expr ::= exprlist",
  190214. /* 13 */ "exprlist ::= cnearset",
  190215. /* 14 */ "exprlist ::= exprlist cnearset",
  190216. /* 15 */ "cnearset ::= nearset",
  190217. /* 16 */ "cnearset ::= colset COLON nearset",
  190218. /* 17 */ "nearset ::= phrase",
  190219. /* 18 */ "nearset ::= CARET phrase",
  190220. /* 19 */ "nearset ::= STRING LP nearphrases neardist_opt RP",
  190221. /* 20 */ "nearphrases ::= phrase",
  190222. /* 21 */ "nearphrases ::= nearphrases phrase",
  190223. /* 22 */ "neardist_opt ::=",
  190224. /* 23 */ "neardist_opt ::= COMMA STRING",
  190225. /* 24 */ "phrase ::= phrase PLUS STRING star_opt",
  190226. /* 25 */ "phrase ::= STRING star_opt",
  190227. /* 26 */ "star_opt ::= STAR",
  190228. /* 27 */ "star_opt ::=",
  190229. };
  190230. #endif /* NDEBUG */
  190231. #if fts5YYSTACKDEPTH<=0
  190232. /*
  190233. ** Try to increase the size of the parser stack. Return the number
  190234. ** of errors. Return 0 on success.
  190235. */
  190236. static int fts5yyGrowStack(fts5yyParser *p){
  190237. int newSize;
  190238. int idx;
  190239. fts5yyStackEntry *pNew;
  190240. newSize = p->fts5yystksz*2 + 100;
  190241. idx = p->fts5yytos ? (int)(p->fts5yytos - p->fts5yystack) : 0;
  190242. if( p->fts5yystack==&p->fts5yystk0 ){
  190243. pNew = malloc(newSize*sizeof(pNew[0]));
  190244. if( pNew ) pNew[0] = p->fts5yystk0;
  190245. }else{
  190246. pNew = realloc(p->fts5yystack, newSize*sizeof(pNew[0]));
  190247. }
  190248. if( pNew ){
  190249. p->fts5yystack = pNew;
  190250. p->fts5yytos = &p->fts5yystack[idx];
  190251. #ifndef NDEBUG
  190252. if( fts5yyTraceFILE ){
  190253. fprintf(fts5yyTraceFILE,"%sStack grows from %d to %d entries.\n",
  190254. fts5yyTracePrompt, p->fts5yystksz, newSize);
  190255. }
  190256. #endif
  190257. p->fts5yystksz = newSize;
  190258. }
  190259. return pNew==0;
  190260. }
  190261. #endif
  190262. /* Datatype of the argument to the memory allocated passed as the
  190263. ** second argument to sqlite3Fts5ParserAlloc() below. This can be changed by
  190264. ** putting an appropriate #define in the %include section of the input
  190265. ** grammar.
  190266. */
  190267. #ifndef fts5YYMALLOCARGTYPE
  190268. # define fts5YYMALLOCARGTYPE size_t
  190269. #endif
  190270. /* Initialize a new parser that has already been allocated.
  190271. */
  190272. static void sqlite3Fts5ParserInit(void *fts5yypRawParser sqlite3Fts5ParserCTX_PDECL){
  190273. fts5yyParser *fts5yypParser = (fts5yyParser*)fts5yypRawParser;
  190274. sqlite3Fts5ParserCTX_STORE
  190275. #ifdef fts5YYTRACKMAXSTACKDEPTH
  190276. fts5yypParser->fts5yyhwm = 0;
  190277. #endif
  190278. #if fts5YYSTACKDEPTH<=0
  190279. fts5yypParser->fts5yytos = NULL;
  190280. fts5yypParser->fts5yystack = NULL;
  190281. fts5yypParser->fts5yystksz = 0;
  190282. if( fts5yyGrowStack(fts5yypParser) ){
  190283. fts5yypParser->fts5yystack = &fts5yypParser->fts5yystk0;
  190284. fts5yypParser->fts5yystksz = 1;
  190285. }
  190286. #endif
  190287. #ifndef fts5YYNOERRORRECOVERY
  190288. fts5yypParser->fts5yyerrcnt = -1;
  190289. #endif
  190290. fts5yypParser->fts5yytos = fts5yypParser->fts5yystack;
  190291. fts5yypParser->fts5yystack[0].stateno = 0;
  190292. fts5yypParser->fts5yystack[0].major = 0;
  190293. #if fts5YYSTACKDEPTH>0
  190294. fts5yypParser->fts5yystackEnd = &fts5yypParser->fts5yystack[fts5YYSTACKDEPTH-1];
  190295. #endif
  190296. }
  190297. #ifndef sqlite3Fts5Parser_ENGINEALWAYSONSTACK
  190298. /*
  190299. ** This function allocates a new parser.
  190300. ** The only argument is a pointer to a function which works like
  190301. ** malloc.
  190302. **
  190303. ** Inputs:
  190304. ** A pointer to the function used to allocate memory.
  190305. **
  190306. ** Outputs:
  190307. ** A pointer to a parser. This pointer is used in subsequent calls
  190308. ** to sqlite3Fts5Parser and sqlite3Fts5ParserFree.
  190309. */
  190310. static void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(fts5YYMALLOCARGTYPE) sqlite3Fts5ParserCTX_PDECL){
  190311. fts5yyParser *fts5yypParser;
  190312. fts5yypParser = (fts5yyParser*)(*mallocProc)( (fts5YYMALLOCARGTYPE)sizeof(fts5yyParser) );
  190313. if( fts5yypParser ){
  190314. sqlite3Fts5ParserCTX_STORE
  190315. sqlite3Fts5ParserInit(fts5yypParser sqlite3Fts5ParserCTX_PARAM);
  190316. }
  190317. return (void*)fts5yypParser;
  190318. }
  190319. #endif /* sqlite3Fts5Parser_ENGINEALWAYSONSTACK */
  190320. /* The following function deletes the "minor type" or semantic value
  190321. ** associated with a symbol. The symbol can be either a terminal
  190322. ** or nonterminal. "fts5yymajor" is the symbol code, and "fts5yypminor" is
  190323. ** a pointer to the value to be deleted. The code used to do the
  190324. ** deletions is derived from the %destructor and/or %token_destructor
  190325. ** directives of the input grammar.
  190326. */
  190327. static void fts5yy_destructor(
  190328. fts5yyParser *fts5yypParser, /* The parser */
  190329. fts5YYCODETYPE fts5yymajor, /* Type code for object to destroy */
  190330. fts5YYMINORTYPE *fts5yypminor /* The object to be destroyed */
  190331. ){
  190332. sqlite3Fts5ParserARG_FETCH
  190333. sqlite3Fts5ParserCTX_FETCH
  190334. switch( fts5yymajor ){
  190335. /* Here is inserted the actions which take place when a
  190336. ** terminal or non-terminal is destroyed. This can happen
  190337. ** when the symbol is popped from the stack during a
  190338. ** reduce or during error processing or when a parser is
  190339. ** being destroyed before it is finished parsing.
  190340. **
  190341. ** Note: during a reduce, the only symbols destroyed are those
  190342. ** which appear on the RHS of the rule, but which are *not* used
  190343. ** inside the C code.
  190344. */
  190345. /********* Begin destructor definitions ***************************************/
  190346. case 16: /* input */
  190347. {
  190348. (void)pParse;
  190349. }
  190350. break;
  190351. case 17: /* expr */
  190352. case 18: /* cnearset */
  190353. case 19: /* exprlist */
  190354. {
  190355. sqlite3Fts5ParseNodeFree((fts5yypminor->fts5yy24));
  190356. }
  190357. break;
  190358. case 20: /* colset */
  190359. case 21: /* colsetlist */
  190360. {
  190361. sqlite3_free((fts5yypminor->fts5yy11));
  190362. }
  190363. break;
  190364. case 22: /* nearset */
  190365. case 23: /* nearphrases */
  190366. {
  190367. sqlite3Fts5ParseNearsetFree((fts5yypminor->fts5yy46));
  190368. }
  190369. break;
  190370. case 24: /* phrase */
  190371. {
  190372. sqlite3Fts5ParsePhraseFree((fts5yypminor->fts5yy53));
  190373. }
  190374. break;
  190375. /********* End destructor definitions *****************************************/
  190376. default: break; /* If no destructor action specified: do nothing */
  190377. }
  190378. }
  190379. /*
  190380. ** Pop the parser's stack once.
  190381. **
  190382. ** If there is a destructor routine associated with the token which
  190383. ** is popped from the stack, then call it.
  190384. */
  190385. static void fts5yy_pop_parser_stack(fts5yyParser *pParser){
  190386. fts5yyStackEntry *fts5yytos;
  190387. assert( pParser->fts5yytos!=0 );
  190388. assert( pParser->fts5yytos > pParser->fts5yystack );
  190389. fts5yytos = pParser->fts5yytos--;
  190390. #ifndef NDEBUG
  190391. if( fts5yyTraceFILE ){
  190392. fprintf(fts5yyTraceFILE,"%sPopping %s\n",
  190393. fts5yyTracePrompt,
  190394. fts5yyTokenName[fts5yytos->major]);
  190395. }
  190396. #endif
  190397. fts5yy_destructor(pParser, fts5yytos->major, &fts5yytos->minor);
  190398. }
  190399. /*
  190400. ** Clear all secondary memory allocations from the parser
  190401. */
  190402. static void sqlite3Fts5ParserFinalize(void *p){
  190403. fts5yyParser *pParser = (fts5yyParser*)p;
  190404. while( pParser->fts5yytos>pParser->fts5yystack ) fts5yy_pop_parser_stack(pParser);
  190405. #if fts5YYSTACKDEPTH<=0
  190406. if( pParser->fts5yystack!=&pParser->fts5yystk0 ) free(pParser->fts5yystack);
  190407. #endif
  190408. }
  190409. #ifndef sqlite3Fts5Parser_ENGINEALWAYSONSTACK
  190410. /*
  190411. ** Deallocate and destroy a parser. Destructors are called for
  190412. ** all stack elements before shutting the parser down.
  190413. **
  190414. ** If the fts5YYPARSEFREENEVERNULL macro exists (for example because it
  190415. ** is defined in a %include section of the input grammar) then it is
  190416. ** assumed that the input pointer is never NULL.
  190417. */
  190418. static void sqlite3Fts5ParserFree(
  190419. void *p, /* The parser to be deleted */
  190420. void (*freeProc)(void*) /* Function used to reclaim memory */
  190421. ){
  190422. #ifndef fts5YYPARSEFREENEVERNULL
  190423. if( p==0 ) return;
  190424. #endif
  190425. sqlite3Fts5ParserFinalize(p);
  190426. (*freeProc)(p);
  190427. }
  190428. #endif /* sqlite3Fts5Parser_ENGINEALWAYSONSTACK */
  190429. /*
  190430. ** Return the peak depth of the stack for a parser.
  190431. */
  190432. #ifdef fts5YYTRACKMAXSTACKDEPTH
  190433. static int sqlite3Fts5ParserStackPeak(void *p){
  190434. fts5yyParser *pParser = (fts5yyParser*)p;
  190435. return pParser->fts5yyhwm;
  190436. }
  190437. #endif
  190438. /* This array of booleans keeps track of the parser statement
  190439. ** coverage. The element fts5yycoverage[X][Y] is set when the parser
  190440. ** is in state X and has a lookahead token Y. In a well-tested
  190441. ** systems, every element of this matrix should end up being set.
  190442. */
  190443. #if defined(fts5YYCOVERAGE)
  190444. static unsigned char fts5yycoverage[fts5YYNSTATE][fts5YYNFTS5TOKEN];
  190445. #endif
  190446. /*
  190447. ** Write into out a description of every state/lookahead combination that
  190448. **
  190449. ** (1) has not been used by the parser, and
  190450. ** (2) is not a syntax error.
  190451. **
  190452. ** Return the number of missed state/lookahead combinations.
  190453. */
  190454. #if defined(fts5YYCOVERAGE)
  190455. static int sqlite3Fts5ParserCoverage(FILE *out){
  190456. int stateno, iLookAhead, i;
  190457. int nMissed = 0;
  190458. for(stateno=0; stateno<fts5YYNSTATE; stateno++){
  190459. i = fts5yy_shift_ofst[stateno];
  190460. for(iLookAhead=0; iLookAhead<fts5YYNFTS5TOKEN; iLookAhead++){
  190461. if( fts5yy_lookahead[i+iLookAhead]!=iLookAhead ) continue;
  190462. if( fts5yycoverage[stateno][iLookAhead]==0 ) nMissed++;
  190463. if( out ){
  190464. fprintf(out,"State %d lookahead %s %s\n", stateno,
  190465. fts5yyTokenName[iLookAhead],
  190466. fts5yycoverage[stateno][iLookAhead] ? "ok" : "missed");
  190467. }
  190468. }
  190469. }
  190470. return nMissed;
  190471. }
  190472. #endif
  190473. /*
  190474. ** Find the appropriate action for a parser given the terminal
  190475. ** look-ahead token iLookAhead.
  190476. */
  190477. static fts5YYACTIONTYPE fts5yy_find_shift_action(
  190478. fts5YYCODETYPE iLookAhead, /* The look-ahead token */
  190479. fts5YYACTIONTYPE stateno /* Current state number */
  190480. ){
  190481. int i;
  190482. if( stateno>fts5YY_MAX_SHIFT ) return stateno;
  190483. assert( stateno <= fts5YY_SHIFT_COUNT );
  190484. #if defined(fts5YYCOVERAGE)
  190485. fts5yycoverage[stateno][iLookAhead] = 1;
  190486. #endif
  190487. do{
  190488. i = fts5yy_shift_ofst[stateno];
  190489. assert( i>=0 );
  190490. /* assert( i+fts5YYNFTS5TOKEN<=(int)fts5YY_NLOOKAHEAD ); */
  190491. assert( iLookAhead!=fts5YYNOCODE );
  190492. assert( iLookAhead < fts5YYNFTS5TOKEN );
  190493. i += iLookAhead;
  190494. if( i>=fts5YY_NLOOKAHEAD || fts5yy_lookahead[i]!=iLookAhead ){
  190495. #ifdef fts5YYFALLBACK
  190496. fts5YYCODETYPE iFallback; /* Fallback token */
  190497. if( iLookAhead<sizeof(fts5yyFallback)/sizeof(fts5yyFallback[0])
  190498. && (iFallback = fts5yyFallback[iLookAhead])!=0 ){
  190499. #ifndef NDEBUG
  190500. if( fts5yyTraceFILE ){
  190501. fprintf(fts5yyTraceFILE, "%sFALLBACK %s => %s\n",
  190502. fts5yyTracePrompt, fts5yyTokenName[iLookAhead], fts5yyTokenName[iFallback]);
  190503. }
  190504. #endif
  190505. assert( fts5yyFallback[iFallback]==0 ); /* Fallback loop must terminate */
  190506. iLookAhead = iFallback;
  190507. continue;
  190508. }
  190509. #endif
  190510. #ifdef fts5YYWILDCARD
  190511. {
  190512. int j = i - iLookAhead + fts5YYWILDCARD;
  190513. if(
  190514. #if fts5YY_SHIFT_MIN+fts5YYWILDCARD<0
  190515. j>=0 &&
  190516. #endif
  190517. #if fts5YY_SHIFT_MAX+fts5YYWILDCARD>=fts5YY_ACTTAB_COUNT
  190518. j<fts5YY_ACTTAB_COUNT &&
  190519. #endif
  190520. j<(int)(sizeof(fts5yy_lookahead)/sizeof(fts5yy_lookahead[0])) &&
  190521. fts5yy_lookahead[j]==fts5YYWILDCARD && iLookAhead>0
  190522. ){
  190523. #ifndef NDEBUG
  190524. if( fts5yyTraceFILE ){
  190525. fprintf(fts5yyTraceFILE, "%sWILDCARD %s => %s\n",
  190526. fts5yyTracePrompt, fts5yyTokenName[iLookAhead],
  190527. fts5yyTokenName[fts5YYWILDCARD]);
  190528. }
  190529. #endif /* NDEBUG */
  190530. return fts5yy_action[j];
  190531. }
  190532. }
  190533. #endif /* fts5YYWILDCARD */
  190534. return fts5yy_default[stateno];
  190535. }else{
  190536. return fts5yy_action[i];
  190537. }
  190538. }while(1);
  190539. }
  190540. /*
  190541. ** Find the appropriate action for a parser given the non-terminal
  190542. ** look-ahead token iLookAhead.
  190543. */
  190544. static fts5YYACTIONTYPE fts5yy_find_reduce_action(
  190545. fts5YYACTIONTYPE stateno, /* Current state number */
  190546. fts5YYCODETYPE iLookAhead /* The look-ahead token */
  190547. ){
  190548. int i;
  190549. #ifdef fts5YYERRORSYMBOL
  190550. if( stateno>fts5YY_REDUCE_COUNT ){
  190551. return fts5yy_default[stateno];
  190552. }
  190553. #else
  190554. assert( stateno<=fts5YY_REDUCE_COUNT );
  190555. #endif
  190556. i = fts5yy_reduce_ofst[stateno];
  190557. assert( iLookAhead!=fts5YYNOCODE );
  190558. i += iLookAhead;
  190559. #ifdef fts5YYERRORSYMBOL
  190560. if( i<0 || i>=fts5YY_ACTTAB_COUNT || fts5yy_lookahead[i]!=iLookAhead ){
  190561. return fts5yy_default[stateno];
  190562. }
  190563. #else
  190564. assert( i>=0 && i<fts5YY_ACTTAB_COUNT );
  190565. assert( fts5yy_lookahead[i]==iLookAhead );
  190566. #endif
  190567. return fts5yy_action[i];
  190568. }
  190569. /*
  190570. ** The following routine is called if the stack overflows.
  190571. */
  190572. static void fts5yyStackOverflow(fts5yyParser *fts5yypParser){
  190573. sqlite3Fts5ParserARG_FETCH
  190574. sqlite3Fts5ParserCTX_FETCH
  190575. #ifndef NDEBUG
  190576. if( fts5yyTraceFILE ){
  190577. fprintf(fts5yyTraceFILE,"%sStack Overflow!\n",fts5yyTracePrompt);
  190578. }
  190579. #endif
  190580. while( fts5yypParser->fts5yytos>fts5yypParser->fts5yystack ) fts5yy_pop_parser_stack(fts5yypParser);
  190581. /* Here code is inserted which will execute if the parser
  190582. ** stack every overflows */
  190583. /******** Begin %stack_overflow code ******************************************/
  190584. sqlite3Fts5ParseError(pParse, "fts5: parser stack overflow");
  190585. /******** End %stack_overflow code ********************************************/
  190586. sqlite3Fts5ParserARG_STORE /* Suppress warning about unused %extra_argument var */
  190587. sqlite3Fts5ParserCTX_STORE
  190588. }
  190589. /*
  190590. ** Print tracing information for a SHIFT action
  190591. */
  190592. #ifndef NDEBUG
  190593. static void fts5yyTraceShift(fts5yyParser *fts5yypParser, int fts5yyNewState, const char *zTag){
  190594. if( fts5yyTraceFILE ){
  190595. if( fts5yyNewState<fts5YYNSTATE ){
  190596. fprintf(fts5yyTraceFILE,"%s%s '%s', go to state %d\n",
  190597. fts5yyTracePrompt, zTag, fts5yyTokenName[fts5yypParser->fts5yytos->major],
  190598. fts5yyNewState);
  190599. }else{
  190600. fprintf(fts5yyTraceFILE,"%s%s '%s', pending reduce %d\n",
  190601. fts5yyTracePrompt, zTag, fts5yyTokenName[fts5yypParser->fts5yytos->major],
  190602. fts5yyNewState - fts5YY_MIN_REDUCE);
  190603. }
  190604. }
  190605. }
  190606. #else
  190607. # define fts5yyTraceShift(X,Y,Z)
  190608. #endif
  190609. /*
  190610. ** Perform a shift action.
  190611. */
  190612. static void fts5yy_shift(
  190613. fts5yyParser *fts5yypParser, /* The parser to be shifted */
  190614. fts5YYACTIONTYPE fts5yyNewState, /* The new state to shift in */
  190615. fts5YYCODETYPE fts5yyMajor, /* The major token to shift in */
  190616. sqlite3Fts5ParserFTS5TOKENTYPE fts5yyMinor /* The minor token to shift in */
  190617. ){
  190618. fts5yyStackEntry *fts5yytos;
  190619. fts5yypParser->fts5yytos++;
  190620. #ifdef fts5YYTRACKMAXSTACKDEPTH
  190621. if( (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack)>fts5yypParser->fts5yyhwm ){
  190622. fts5yypParser->fts5yyhwm++;
  190623. assert( fts5yypParser->fts5yyhwm == (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack) );
  190624. }
  190625. #endif
  190626. #if fts5YYSTACKDEPTH>0
  190627. if( fts5yypParser->fts5yytos>fts5yypParser->fts5yystackEnd ){
  190628. fts5yypParser->fts5yytos--;
  190629. fts5yyStackOverflow(fts5yypParser);
  190630. return;
  190631. }
  190632. #else
  190633. if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5yypParser->fts5yystksz] ){
  190634. if( fts5yyGrowStack(fts5yypParser) ){
  190635. fts5yypParser->fts5yytos--;
  190636. fts5yyStackOverflow(fts5yypParser);
  190637. return;
  190638. }
  190639. }
  190640. #endif
  190641. if( fts5yyNewState > fts5YY_MAX_SHIFT ){
  190642. fts5yyNewState += fts5YY_MIN_REDUCE - fts5YY_MIN_SHIFTREDUCE;
  190643. }
  190644. fts5yytos = fts5yypParser->fts5yytos;
  190645. fts5yytos->stateno = fts5yyNewState;
  190646. fts5yytos->major = fts5yyMajor;
  190647. fts5yytos->minor.fts5yy0 = fts5yyMinor;
  190648. fts5yyTraceShift(fts5yypParser, fts5yyNewState, "Shift");
  190649. }
  190650. /* For rule J, fts5yyRuleInfoLhs[J] contains the symbol on the left-hand side
  190651. ** of that rule */
  190652. static const fts5YYCODETYPE fts5yyRuleInfoLhs[] = {
  190653. 16, /* (0) input ::= expr */
  190654. 20, /* (1) colset ::= MINUS LCP colsetlist RCP */
  190655. 20, /* (2) colset ::= LCP colsetlist RCP */
  190656. 20, /* (3) colset ::= STRING */
  190657. 20, /* (4) colset ::= MINUS STRING */
  190658. 21, /* (5) colsetlist ::= colsetlist STRING */
  190659. 21, /* (6) colsetlist ::= STRING */
  190660. 17, /* (7) expr ::= expr AND expr */
  190661. 17, /* (8) expr ::= expr OR expr */
  190662. 17, /* (9) expr ::= expr NOT expr */
  190663. 17, /* (10) expr ::= colset COLON LP expr RP */
  190664. 17, /* (11) expr ::= LP expr RP */
  190665. 17, /* (12) expr ::= exprlist */
  190666. 19, /* (13) exprlist ::= cnearset */
  190667. 19, /* (14) exprlist ::= exprlist cnearset */
  190668. 18, /* (15) cnearset ::= nearset */
  190669. 18, /* (16) cnearset ::= colset COLON nearset */
  190670. 22, /* (17) nearset ::= phrase */
  190671. 22, /* (18) nearset ::= CARET phrase */
  190672. 22, /* (19) nearset ::= STRING LP nearphrases neardist_opt RP */
  190673. 23, /* (20) nearphrases ::= phrase */
  190674. 23, /* (21) nearphrases ::= nearphrases phrase */
  190675. 25, /* (22) neardist_opt ::= */
  190676. 25, /* (23) neardist_opt ::= COMMA STRING */
  190677. 24, /* (24) phrase ::= phrase PLUS STRING star_opt */
  190678. 24, /* (25) phrase ::= STRING star_opt */
  190679. 26, /* (26) star_opt ::= STAR */
  190680. 26, /* (27) star_opt ::= */
  190681. };
  190682. /* For rule J, fts5yyRuleInfoNRhs[J] contains the negative of the number
  190683. ** of symbols on the right-hand side of that rule. */
  190684. static const signed char fts5yyRuleInfoNRhs[] = {
  190685. -1, /* (0) input ::= expr */
  190686. -4, /* (1) colset ::= MINUS LCP colsetlist RCP */
  190687. -3, /* (2) colset ::= LCP colsetlist RCP */
  190688. -1, /* (3) colset ::= STRING */
  190689. -2, /* (4) colset ::= MINUS STRING */
  190690. -2, /* (5) colsetlist ::= colsetlist STRING */
  190691. -1, /* (6) colsetlist ::= STRING */
  190692. -3, /* (7) expr ::= expr AND expr */
  190693. -3, /* (8) expr ::= expr OR expr */
  190694. -3, /* (9) expr ::= expr NOT expr */
  190695. -5, /* (10) expr ::= colset COLON LP expr RP */
  190696. -3, /* (11) expr ::= LP expr RP */
  190697. -1, /* (12) expr ::= exprlist */
  190698. -1, /* (13) exprlist ::= cnearset */
  190699. -2, /* (14) exprlist ::= exprlist cnearset */
  190700. -1, /* (15) cnearset ::= nearset */
  190701. -3, /* (16) cnearset ::= colset COLON nearset */
  190702. -1, /* (17) nearset ::= phrase */
  190703. -2, /* (18) nearset ::= CARET phrase */
  190704. -5, /* (19) nearset ::= STRING LP nearphrases neardist_opt RP */
  190705. -1, /* (20) nearphrases ::= phrase */
  190706. -2, /* (21) nearphrases ::= nearphrases phrase */
  190707. 0, /* (22) neardist_opt ::= */
  190708. -2, /* (23) neardist_opt ::= COMMA STRING */
  190709. -4, /* (24) phrase ::= phrase PLUS STRING star_opt */
  190710. -2, /* (25) phrase ::= STRING star_opt */
  190711. -1, /* (26) star_opt ::= STAR */
  190712. 0, /* (27) star_opt ::= */
  190713. };
  190714. static void fts5yy_accept(fts5yyParser*); /* Forward Declaration */
  190715. /*
  190716. ** Perform a reduce action and the shift that must immediately
  190717. ** follow the reduce.
  190718. **
  190719. ** The fts5yyLookahead and fts5yyLookaheadToken parameters provide reduce actions
  190720. ** access to the lookahead token (if any). The fts5yyLookahead will be fts5YYNOCODE
  190721. ** if the lookahead token has already been consumed. As this procedure is
  190722. ** only called from one place, optimizing compilers will in-line it, which
  190723. ** means that the extra parameters have no performance impact.
  190724. */
  190725. static fts5YYACTIONTYPE fts5yy_reduce(
  190726. fts5yyParser *fts5yypParser, /* The parser */
  190727. unsigned int fts5yyruleno, /* Number of the rule by which to reduce */
  190728. int fts5yyLookahead, /* Lookahead token, or fts5YYNOCODE if none */
  190729. sqlite3Fts5ParserFTS5TOKENTYPE fts5yyLookaheadToken /* Value of the lookahead token */
  190730. sqlite3Fts5ParserCTX_PDECL /* %extra_context */
  190731. ){
  190732. int fts5yygoto; /* The next state */
  190733. fts5YYACTIONTYPE fts5yyact; /* The next action */
  190734. fts5yyStackEntry *fts5yymsp; /* The top of the parser's stack */
  190735. int fts5yysize; /* Amount to pop the stack */
  190736. sqlite3Fts5ParserARG_FETCH
  190737. (void)fts5yyLookahead;
  190738. (void)fts5yyLookaheadToken;
  190739. fts5yymsp = fts5yypParser->fts5yytos;
  190740. #ifndef NDEBUG
  190741. if( fts5yyTraceFILE && fts5yyruleno<(int)(sizeof(fts5yyRuleName)/sizeof(fts5yyRuleName[0])) ){
  190742. fts5yysize = fts5yyRuleInfoNRhs[fts5yyruleno];
  190743. if( fts5yysize ){
  190744. fprintf(fts5yyTraceFILE, "%sReduce %d [%s], go to state %d.\n",
  190745. fts5yyTracePrompt,
  190746. fts5yyruleno, fts5yyRuleName[fts5yyruleno], fts5yymsp[fts5yysize].stateno);
  190747. }else{
  190748. fprintf(fts5yyTraceFILE, "%sReduce %d [%s].\n",
  190749. fts5yyTracePrompt, fts5yyruleno, fts5yyRuleName[fts5yyruleno]);
  190750. }
  190751. }
  190752. #endif /* NDEBUG */
  190753. /* Check that the stack is large enough to grow by a single entry
  190754. ** if the RHS of the rule is empty. This ensures that there is room
  190755. ** enough on the stack to push the LHS value */
  190756. if( fts5yyRuleInfoNRhs[fts5yyruleno]==0 ){
  190757. #ifdef fts5YYTRACKMAXSTACKDEPTH
  190758. if( (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack)>fts5yypParser->fts5yyhwm ){
  190759. fts5yypParser->fts5yyhwm++;
  190760. assert( fts5yypParser->fts5yyhwm == (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack));
  190761. }
  190762. #endif
  190763. #if fts5YYSTACKDEPTH>0
  190764. if( fts5yypParser->fts5yytos>=fts5yypParser->fts5yystackEnd ){
  190765. fts5yyStackOverflow(fts5yypParser);
  190766. /* The call to fts5yyStackOverflow() above pops the stack until it is
  190767. ** empty, causing the main parser loop to exit. So the return value
  190768. ** is never used and does not matter. */
  190769. return 0;
  190770. }
  190771. #else
  190772. if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5yypParser->fts5yystksz-1] ){
  190773. if( fts5yyGrowStack(fts5yypParser) ){
  190774. fts5yyStackOverflow(fts5yypParser);
  190775. /* The call to fts5yyStackOverflow() above pops the stack until it is
  190776. ** empty, causing the main parser loop to exit. So the return value
  190777. ** is never used and does not matter. */
  190778. return 0;
  190779. }
  190780. fts5yymsp = fts5yypParser->fts5yytos;
  190781. }
  190782. #endif
  190783. }
  190784. switch( fts5yyruleno ){
  190785. /* Beginning here are the reduction cases. A typical example
  190786. ** follows:
  190787. ** case 0:
  190788. ** #line <lineno> <grammarfile>
  190789. ** { ... } // User supplied code
  190790. ** #line <lineno> <thisfile>
  190791. ** break;
  190792. */
  190793. /********** Begin reduce actions **********************************************/
  190794. fts5YYMINORTYPE fts5yylhsminor;
  190795. case 0: /* input ::= expr */
  190796. { sqlite3Fts5ParseFinished(pParse, fts5yymsp[0].minor.fts5yy24); }
  190797. break;
  190798. case 1: /* colset ::= MINUS LCP colsetlist RCP */
  190799. {
  190800. fts5yymsp[-3].minor.fts5yy11 = sqlite3Fts5ParseColsetInvert(pParse, fts5yymsp[-1].minor.fts5yy11);
  190801. }
  190802. break;
  190803. case 2: /* colset ::= LCP colsetlist RCP */
  190804. { fts5yymsp[-2].minor.fts5yy11 = fts5yymsp[-1].minor.fts5yy11; }
  190805. break;
  190806. case 3: /* colset ::= STRING */
  190807. {
  190808. fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
  190809. }
  190810. fts5yymsp[0].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
  190811. break;
  190812. case 4: /* colset ::= MINUS STRING */
  190813. {
  190814. fts5yymsp[-1].minor.fts5yy11 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
  190815. fts5yymsp[-1].minor.fts5yy11 = sqlite3Fts5ParseColsetInvert(pParse, fts5yymsp[-1].minor.fts5yy11);
  190816. }
  190817. break;
  190818. case 5: /* colsetlist ::= colsetlist STRING */
  190819. {
  190820. fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, fts5yymsp[-1].minor.fts5yy11, &fts5yymsp[0].minor.fts5yy0); }
  190821. fts5yymsp[-1].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
  190822. break;
  190823. case 6: /* colsetlist ::= STRING */
  190824. {
  190825. fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
  190826. }
  190827. fts5yymsp[0].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
  190828. break;
  190829. case 7: /* expr ::= expr AND expr */
  190830. {
  190831. fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_AND, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0);
  190832. }
  190833. fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  190834. break;
  190835. case 8: /* expr ::= expr OR expr */
  190836. {
  190837. fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_OR, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0);
  190838. }
  190839. fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  190840. break;
  190841. case 9: /* expr ::= expr NOT expr */
  190842. {
  190843. fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_NOT, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0);
  190844. }
  190845. fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  190846. break;
  190847. case 10: /* expr ::= colset COLON LP expr RP */
  190848. {
  190849. sqlite3Fts5ParseSetColset(pParse, fts5yymsp[-1].minor.fts5yy24, fts5yymsp[-4].minor.fts5yy11);
  190850. fts5yylhsminor.fts5yy24 = fts5yymsp[-1].minor.fts5yy24;
  190851. }
  190852. fts5yymsp[-4].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  190853. break;
  190854. case 11: /* expr ::= LP expr RP */
  190855. {fts5yymsp[-2].minor.fts5yy24 = fts5yymsp[-1].minor.fts5yy24;}
  190856. break;
  190857. case 12: /* expr ::= exprlist */
  190858. case 13: /* exprlist ::= cnearset */ fts5yytestcase(fts5yyruleno==13);
  190859. {fts5yylhsminor.fts5yy24 = fts5yymsp[0].minor.fts5yy24;}
  190860. fts5yymsp[0].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  190861. break;
  190862. case 14: /* exprlist ::= exprlist cnearset */
  190863. {
  190864. fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseImplicitAnd(pParse, fts5yymsp[-1].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24);
  190865. }
  190866. fts5yymsp[-1].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  190867. break;
  190868. case 15: /* cnearset ::= nearset */
  190869. {
  190870. fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy46);
  190871. }
  190872. fts5yymsp[0].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  190873. break;
  190874. case 16: /* cnearset ::= colset COLON nearset */
  190875. {
  190876. fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy46);
  190877. sqlite3Fts5ParseSetColset(pParse, fts5yylhsminor.fts5yy24, fts5yymsp[-2].minor.fts5yy11);
  190878. }
  190879. fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  190880. break;
  190881. case 17: /* nearset ::= phrase */
  190882. { fts5yylhsminor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy53); }
  190883. fts5yymsp[0].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
  190884. break;
  190885. case 18: /* nearset ::= CARET phrase */
  190886. {
  190887. sqlite3Fts5ParseSetCaret(fts5yymsp[0].minor.fts5yy53);
  190888. fts5yymsp[-1].minor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy53);
  190889. }
  190890. break;
  190891. case 19: /* nearset ::= STRING LP nearphrases neardist_opt RP */
  190892. {
  190893. sqlite3Fts5ParseNear(pParse, &fts5yymsp[-4].minor.fts5yy0);
  190894. sqlite3Fts5ParseSetDistance(pParse, fts5yymsp[-2].minor.fts5yy46, &fts5yymsp[-1].minor.fts5yy0);
  190895. fts5yylhsminor.fts5yy46 = fts5yymsp[-2].minor.fts5yy46;
  190896. }
  190897. fts5yymsp[-4].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
  190898. break;
  190899. case 20: /* nearphrases ::= phrase */
  190900. {
  190901. fts5yylhsminor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy53);
  190902. }
  190903. fts5yymsp[0].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
  190904. break;
  190905. case 21: /* nearphrases ::= nearphrases phrase */
  190906. {
  190907. fts5yylhsminor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, fts5yymsp[-1].minor.fts5yy46, fts5yymsp[0].minor.fts5yy53);
  190908. }
  190909. fts5yymsp[-1].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
  190910. break;
  190911. case 22: /* neardist_opt ::= */
  190912. { fts5yymsp[1].minor.fts5yy0.p = 0; fts5yymsp[1].minor.fts5yy0.n = 0; }
  190913. break;
  190914. case 23: /* neardist_opt ::= COMMA STRING */
  190915. { fts5yymsp[-1].minor.fts5yy0 = fts5yymsp[0].minor.fts5yy0; }
  190916. break;
  190917. case 24: /* phrase ::= phrase PLUS STRING star_opt */
  190918. {
  190919. fts5yylhsminor.fts5yy53 = sqlite3Fts5ParseTerm(pParse, fts5yymsp[-3].minor.fts5yy53, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy4);
  190920. }
  190921. fts5yymsp[-3].minor.fts5yy53 = fts5yylhsminor.fts5yy53;
  190922. break;
  190923. case 25: /* phrase ::= STRING star_opt */
  190924. {
  190925. fts5yylhsminor.fts5yy53 = sqlite3Fts5ParseTerm(pParse, 0, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy4);
  190926. }
  190927. fts5yymsp[-1].minor.fts5yy53 = fts5yylhsminor.fts5yy53;
  190928. break;
  190929. case 26: /* star_opt ::= STAR */
  190930. { fts5yymsp[0].minor.fts5yy4 = 1; }
  190931. break;
  190932. case 27: /* star_opt ::= */
  190933. { fts5yymsp[1].minor.fts5yy4 = 0; }
  190934. break;
  190935. default:
  190936. break;
  190937. /********** End reduce actions ************************************************/
  190938. };
  190939. assert( fts5yyruleno<sizeof(fts5yyRuleInfoLhs)/sizeof(fts5yyRuleInfoLhs[0]) );
  190940. fts5yygoto = fts5yyRuleInfoLhs[fts5yyruleno];
  190941. fts5yysize = fts5yyRuleInfoNRhs[fts5yyruleno];
  190942. fts5yyact = fts5yy_find_reduce_action(fts5yymsp[fts5yysize].stateno,(fts5YYCODETYPE)fts5yygoto);
  190943. /* There are no SHIFTREDUCE actions on nonterminals because the table
  190944. ** generator has simplified them to pure REDUCE actions. */
  190945. assert( !(fts5yyact>fts5YY_MAX_SHIFT && fts5yyact<=fts5YY_MAX_SHIFTREDUCE) );
  190946. /* It is not possible for a REDUCE to be followed by an error */
  190947. assert( fts5yyact!=fts5YY_ERROR_ACTION );
  190948. fts5yymsp += fts5yysize+1;
  190949. fts5yypParser->fts5yytos = fts5yymsp;
  190950. fts5yymsp->stateno = (fts5YYACTIONTYPE)fts5yyact;
  190951. fts5yymsp->major = (fts5YYCODETYPE)fts5yygoto;
  190952. fts5yyTraceShift(fts5yypParser, fts5yyact, "... then shift");
  190953. return fts5yyact;
  190954. }
  190955. /*
  190956. ** The following code executes when the parse fails
  190957. */
  190958. #ifndef fts5YYNOERRORRECOVERY
  190959. static void fts5yy_parse_failed(
  190960. fts5yyParser *fts5yypParser /* The parser */
  190961. ){
  190962. sqlite3Fts5ParserARG_FETCH
  190963. sqlite3Fts5ParserCTX_FETCH
  190964. #ifndef NDEBUG
  190965. if( fts5yyTraceFILE ){
  190966. fprintf(fts5yyTraceFILE,"%sFail!\n",fts5yyTracePrompt);
  190967. }
  190968. #endif
  190969. while( fts5yypParser->fts5yytos>fts5yypParser->fts5yystack ) fts5yy_pop_parser_stack(fts5yypParser);
  190970. /* Here code is inserted which will be executed whenever the
  190971. ** parser fails */
  190972. /************ Begin %parse_failure code ***************************************/
  190973. /************ End %parse_failure code *****************************************/
  190974. sqlite3Fts5ParserARG_STORE /* Suppress warning about unused %extra_argument variable */
  190975. sqlite3Fts5ParserCTX_STORE
  190976. }
  190977. #endif /* fts5YYNOERRORRECOVERY */
  190978. /*
  190979. ** The following code executes when a syntax error first occurs.
  190980. */
  190981. static void fts5yy_syntax_error(
  190982. fts5yyParser *fts5yypParser, /* The parser */
  190983. int fts5yymajor, /* The major type of the error token */
  190984. sqlite3Fts5ParserFTS5TOKENTYPE fts5yyminor /* The minor type of the error token */
  190985. ){
  190986. sqlite3Fts5ParserARG_FETCH
  190987. sqlite3Fts5ParserCTX_FETCH
  190988. #define FTS5TOKEN fts5yyminor
  190989. /************ Begin %syntax_error code ****************************************/
  190990. UNUSED_PARAM(fts5yymajor); /* Silence a compiler warning */
  190991. sqlite3Fts5ParseError(
  190992. pParse, "fts5: syntax error near \"%.*s\"",FTS5TOKEN.n,FTS5TOKEN.p
  190993. );
  190994. /************ End %syntax_error code ******************************************/
  190995. sqlite3Fts5ParserARG_STORE /* Suppress warning about unused %extra_argument variable */
  190996. sqlite3Fts5ParserCTX_STORE
  190997. }
  190998. /*
  190999. ** The following is executed when the parser accepts
  191000. */
  191001. static void fts5yy_accept(
  191002. fts5yyParser *fts5yypParser /* The parser */
  191003. ){
  191004. sqlite3Fts5ParserARG_FETCH
  191005. sqlite3Fts5ParserCTX_FETCH
  191006. #ifndef NDEBUG
  191007. if( fts5yyTraceFILE ){
  191008. fprintf(fts5yyTraceFILE,"%sAccept!\n",fts5yyTracePrompt);
  191009. }
  191010. #endif
  191011. #ifndef fts5YYNOERRORRECOVERY
  191012. fts5yypParser->fts5yyerrcnt = -1;
  191013. #endif
  191014. assert( fts5yypParser->fts5yytos==fts5yypParser->fts5yystack );
  191015. /* Here code is inserted which will be executed whenever the
  191016. ** parser accepts */
  191017. /*********** Begin %parse_accept code *****************************************/
  191018. /*********** End %parse_accept code *******************************************/
  191019. sqlite3Fts5ParserARG_STORE /* Suppress warning about unused %extra_argument variable */
  191020. sqlite3Fts5ParserCTX_STORE
  191021. }
  191022. /* The main parser program.
  191023. ** The first argument is a pointer to a structure obtained from
  191024. ** "sqlite3Fts5ParserAlloc" which describes the current state of the parser.
  191025. ** The second argument is the major token number. The third is
  191026. ** the minor token. The fourth optional argument is whatever the
  191027. ** user wants (and specified in the grammar) and is available for
  191028. ** use by the action routines.
  191029. **
  191030. ** Inputs:
  191031. ** <ul>
  191032. ** <li> A pointer to the parser (an opaque structure.)
  191033. ** <li> The major token number.
  191034. ** <li> The minor token number.
  191035. ** <li> An option argument of a grammar-specified type.
  191036. ** </ul>
  191037. **
  191038. ** Outputs:
  191039. ** None.
  191040. */
  191041. static void sqlite3Fts5Parser(
  191042. void *fts5yyp, /* The parser */
  191043. int fts5yymajor, /* The major token code number */
  191044. sqlite3Fts5ParserFTS5TOKENTYPE fts5yyminor /* The value for the token */
  191045. sqlite3Fts5ParserARG_PDECL /* Optional %extra_argument parameter */
  191046. ){
  191047. fts5YYMINORTYPE fts5yyminorunion;
  191048. fts5YYACTIONTYPE fts5yyact; /* The parser action. */
  191049. #if !defined(fts5YYERRORSYMBOL) && !defined(fts5YYNOERRORRECOVERY)
  191050. int fts5yyendofinput; /* True if we are at the end of input */
  191051. #endif
  191052. #ifdef fts5YYERRORSYMBOL
  191053. int fts5yyerrorhit = 0; /* True if fts5yymajor has invoked an error */
  191054. #endif
  191055. fts5yyParser *fts5yypParser = (fts5yyParser*)fts5yyp; /* The parser */
  191056. sqlite3Fts5ParserCTX_FETCH
  191057. sqlite3Fts5ParserARG_STORE
  191058. assert( fts5yypParser->fts5yytos!=0 );
  191059. #if !defined(fts5YYERRORSYMBOL) && !defined(fts5YYNOERRORRECOVERY)
  191060. fts5yyendofinput = (fts5yymajor==0);
  191061. #endif
  191062. fts5yyact = fts5yypParser->fts5yytos->stateno;
  191063. #ifndef NDEBUG
  191064. if( fts5yyTraceFILE ){
  191065. if( fts5yyact < fts5YY_MIN_REDUCE ){
  191066. fprintf(fts5yyTraceFILE,"%sInput '%s' in state %d\n",
  191067. fts5yyTracePrompt,fts5yyTokenName[fts5yymajor],fts5yyact);
  191068. }else{
  191069. fprintf(fts5yyTraceFILE,"%sInput '%s' with pending reduce %d\n",
  191070. fts5yyTracePrompt,fts5yyTokenName[fts5yymajor],fts5yyact-fts5YY_MIN_REDUCE);
  191071. }
  191072. }
  191073. #endif
  191074. do{
  191075. assert( fts5yyact==fts5yypParser->fts5yytos->stateno );
  191076. fts5yyact = fts5yy_find_shift_action((fts5YYCODETYPE)fts5yymajor,fts5yyact);
  191077. if( fts5yyact >= fts5YY_MIN_REDUCE ){
  191078. fts5yyact = fts5yy_reduce(fts5yypParser,fts5yyact-fts5YY_MIN_REDUCE,fts5yymajor,
  191079. fts5yyminor sqlite3Fts5ParserCTX_PARAM);
  191080. }else if( fts5yyact <= fts5YY_MAX_SHIFTREDUCE ){
  191081. fts5yy_shift(fts5yypParser,fts5yyact,(fts5YYCODETYPE)fts5yymajor,fts5yyminor);
  191082. #ifndef fts5YYNOERRORRECOVERY
  191083. fts5yypParser->fts5yyerrcnt--;
  191084. #endif
  191085. break;
  191086. }else if( fts5yyact==fts5YY_ACCEPT_ACTION ){
  191087. fts5yypParser->fts5yytos--;
  191088. fts5yy_accept(fts5yypParser);
  191089. return;
  191090. }else{
  191091. assert( fts5yyact == fts5YY_ERROR_ACTION );
  191092. fts5yyminorunion.fts5yy0 = fts5yyminor;
  191093. #ifdef fts5YYERRORSYMBOL
  191094. int fts5yymx;
  191095. #endif
  191096. #ifndef NDEBUG
  191097. if( fts5yyTraceFILE ){
  191098. fprintf(fts5yyTraceFILE,"%sSyntax Error!\n",fts5yyTracePrompt);
  191099. }
  191100. #endif
  191101. #ifdef fts5YYERRORSYMBOL
  191102. /* A syntax error has occurred.
  191103. ** The response to an error depends upon whether or not the
  191104. ** grammar defines an error token "ERROR".
  191105. **
  191106. ** This is what we do if the grammar does define ERROR:
  191107. **
  191108. ** * Call the %syntax_error function.
  191109. **
  191110. ** * Begin popping the stack until we enter a state where
  191111. ** it is legal to shift the error symbol, then shift
  191112. ** the error symbol.
  191113. **
  191114. ** * Set the error count to three.
  191115. **
  191116. ** * Begin accepting and shifting new tokens. No new error
  191117. ** processing will occur until three tokens have been
  191118. ** shifted successfully.
  191119. **
  191120. */
  191121. if( fts5yypParser->fts5yyerrcnt<0 ){
  191122. fts5yy_syntax_error(fts5yypParser,fts5yymajor,fts5yyminor);
  191123. }
  191124. fts5yymx = fts5yypParser->fts5yytos->major;
  191125. if( fts5yymx==fts5YYERRORSYMBOL || fts5yyerrorhit ){
  191126. #ifndef NDEBUG
  191127. if( fts5yyTraceFILE ){
  191128. fprintf(fts5yyTraceFILE,"%sDiscard input token %s\n",
  191129. fts5yyTracePrompt,fts5yyTokenName[fts5yymajor]);
  191130. }
  191131. #endif
  191132. fts5yy_destructor(fts5yypParser, (fts5YYCODETYPE)fts5yymajor, &fts5yyminorunion);
  191133. fts5yymajor = fts5YYNOCODE;
  191134. }else{
  191135. while( fts5yypParser->fts5yytos >= fts5yypParser->fts5yystack
  191136. && (fts5yyact = fts5yy_find_reduce_action(
  191137. fts5yypParser->fts5yytos->stateno,
  191138. fts5YYERRORSYMBOL)) > fts5YY_MAX_SHIFTREDUCE
  191139. ){
  191140. fts5yy_pop_parser_stack(fts5yypParser);
  191141. }
  191142. if( fts5yypParser->fts5yytos < fts5yypParser->fts5yystack || fts5yymajor==0 ){
  191143. fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
  191144. fts5yy_parse_failed(fts5yypParser);
  191145. #ifndef fts5YYNOERRORRECOVERY
  191146. fts5yypParser->fts5yyerrcnt = -1;
  191147. #endif
  191148. fts5yymajor = fts5YYNOCODE;
  191149. }else if( fts5yymx!=fts5YYERRORSYMBOL ){
  191150. fts5yy_shift(fts5yypParser,fts5yyact,fts5YYERRORSYMBOL,fts5yyminor);
  191151. }
  191152. }
  191153. fts5yypParser->fts5yyerrcnt = 3;
  191154. fts5yyerrorhit = 1;
  191155. if( fts5yymajor==fts5YYNOCODE ) break;
  191156. fts5yyact = fts5yypParser->fts5yytos->stateno;
  191157. #elif defined(fts5YYNOERRORRECOVERY)
  191158. /* If the fts5YYNOERRORRECOVERY macro is defined, then do not attempt to
  191159. ** do any kind of error recovery. Instead, simply invoke the syntax
  191160. ** error routine and continue going as if nothing had happened.
  191161. **
  191162. ** Applications can set this macro (for example inside %include) if
  191163. ** they intend to abandon the parse upon the first syntax error seen.
  191164. */
  191165. fts5yy_syntax_error(fts5yypParser,fts5yymajor, fts5yyminor);
  191166. fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
  191167. break;
  191168. #else /* fts5YYERRORSYMBOL is not defined */
  191169. /* This is what we do if the grammar does not define ERROR:
  191170. **
  191171. ** * Report an error message, and throw away the input token.
  191172. **
  191173. ** * If the input token is $, then fail the parse.
  191174. **
  191175. ** As before, subsequent error messages are suppressed until
  191176. ** three input tokens have been successfully shifted.
  191177. */
  191178. if( fts5yypParser->fts5yyerrcnt<=0 ){
  191179. fts5yy_syntax_error(fts5yypParser,fts5yymajor, fts5yyminor);
  191180. }
  191181. fts5yypParser->fts5yyerrcnt = 3;
  191182. fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
  191183. if( fts5yyendofinput ){
  191184. fts5yy_parse_failed(fts5yypParser);
  191185. #ifndef fts5YYNOERRORRECOVERY
  191186. fts5yypParser->fts5yyerrcnt = -1;
  191187. #endif
  191188. }
  191189. break;
  191190. #endif
  191191. }
  191192. }while( fts5yypParser->fts5yytos>fts5yypParser->fts5yystack );
  191193. #ifndef NDEBUG
  191194. if( fts5yyTraceFILE ){
  191195. fts5yyStackEntry *i;
  191196. char cDiv = '[';
  191197. fprintf(fts5yyTraceFILE,"%sReturn. Stack=",fts5yyTracePrompt);
  191198. for(i=&fts5yypParser->fts5yystack[1]; i<=fts5yypParser->fts5yytos; i++){
  191199. fprintf(fts5yyTraceFILE,"%c%s", cDiv, fts5yyTokenName[i->major]);
  191200. cDiv = ' ';
  191201. }
  191202. fprintf(fts5yyTraceFILE,"]\n");
  191203. }
  191204. #endif
  191205. return;
  191206. }
  191207. /*
  191208. ** Return the fallback token corresponding to canonical token iToken, or
  191209. ** 0 if iToken has no fallback.
  191210. */
  191211. static int sqlite3Fts5ParserFallback(int iToken){
  191212. #ifdef fts5YYFALLBACK
  191213. if( iToken<(int)(sizeof(fts5yyFallback)/sizeof(fts5yyFallback[0])) ){
  191214. return fts5yyFallback[iToken];
  191215. }
  191216. #else
  191217. (void)iToken;
  191218. #endif
  191219. return 0;
  191220. }
  191221. /*
  191222. ** 2014 May 31
  191223. **
  191224. ** The author disclaims copyright to this source code. In place of
  191225. ** a legal notice, here is a blessing:
  191226. **
  191227. ** May you do good and not evil.
  191228. ** May you find forgiveness for yourself and forgive others.
  191229. ** May you share freely, never taking more than you give.
  191230. **
  191231. ******************************************************************************
  191232. */
  191233. /* #include "fts5Int.h" */
  191234. #include <math.h> /* amalgamator: keep */
  191235. /*
  191236. ** Object used to iterate through all "coalesced phrase instances" in
  191237. ** a single column of the current row. If the phrase instances in the
  191238. ** column being considered do not overlap, this object simply iterates
  191239. ** through them. Or, if they do overlap (share one or more tokens in
  191240. ** common), each set of overlapping instances is treated as a single
  191241. ** match. See documentation for the highlight() auxiliary function for
  191242. ** details.
  191243. **
  191244. ** Usage is:
  191245. **
  191246. ** for(rc = fts5CInstIterNext(pApi, pFts, iCol, &iter);
  191247. ** (rc==SQLITE_OK && 0==fts5CInstIterEof(&iter);
  191248. ** rc = fts5CInstIterNext(&iter)
  191249. ** ){
  191250. ** printf("instance starts at %d, ends at %d\n", iter.iStart, iter.iEnd);
  191251. ** }
  191252. **
  191253. */
  191254. typedef struct CInstIter CInstIter;
  191255. struct CInstIter {
  191256. const Fts5ExtensionApi *pApi; /* API offered by current FTS version */
  191257. Fts5Context *pFts; /* First arg to pass to pApi functions */
  191258. int iCol; /* Column to search */
  191259. int iInst; /* Next phrase instance index */
  191260. int nInst; /* Total number of phrase instances */
  191261. /* Output variables */
  191262. int iStart; /* First token in coalesced phrase instance */
  191263. int iEnd; /* Last token in coalesced phrase instance */
  191264. };
  191265. /*
  191266. ** Advance the iterator to the next coalesced phrase instance. Return
  191267. ** an SQLite error code if an error occurs, or SQLITE_OK otherwise.
  191268. */
  191269. static int fts5CInstIterNext(CInstIter *pIter){
  191270. int rc = SQLITE_OK;
  191271. pIter->iStart = -1;
  191272. pIter->iEnd = -1;
  191273. while( rc==SQLITE_OK && pIter->iInst<pIter->nInst ){
  191274. int ip; int ic; int io;
  191275. rc = pIter->pApi->xInst(pIter->pFts, pIter->iInst, &ip, &ic, &io);
  191276. if( rc==SQLITE_OK ){
  191277. if( ic==pIter->iCol ){
  191278. int iEnd = io - 1 + pIter->pApi->xPhraseSize(pIter->pFts, ip);
  191279. if( pIter->iStart<0 ){
  191280. pIter->iStart = io;
  191281. pIter->iEnd = iEnd;
  191282. }else if( io<=pIter->iEnd ){
  191283. if( iEnd>pIter->iEnd ) pIter->iEnd = iEnd;
  191284. }else{
  191285. break;
  191286. }
  191287. }
  191288. pIter->iInst++;
  191289. }
  191290. }
  191291. return rc;
  191292. }
  191293. /*
  191294. ** Initialize the iterator object indicated by the final parameter to
  191295. ** iterate through coalesced phrase instances in column iCol.
  191296. */
  191297. static int fts5CInstIterInit(
  191298. const Fts5ExtensionApi *pApi,
  191299. Fts5Context *pFts,
  191300. int iCol,
  191301. CInstIter *pIter
  191302. ){
  191303. int rc;
  191304. memset(pIter, 0, sizeof(CInstIter));
  191305. pIter->pApi = pApi;
  191306. pIter->pFts = pFts;
  191307. pIter->iCol = iCol;
  191308. rc = pApi->xInstCount(pFts, &pIter->nInst);
  191309. if( rc==SQLITE_OK ){
  191310. rc = fts5CInstIterNext(pIter);
  191311. }
  191312. return rc;
  191313. }
  191314. /*************************************************************************
  191315. ** Start of highlight() implementation.
  191316. */
  191317. typedef struct HighlightContext HighlightContext;
  191318. struct HighlightContext {
  191319. CInstIter iter; /* Coalesced Instance Iterator */
  191320. int iPos; /* Current token offset in zIn[] */
  191321. int iRangeStart; /* First token to include */
  191322. int iRangeEnd; /* If non-zero, last token to include */
  191323. const char *zOpen; /* Opening highlight */
  191324. const char *zClose; /* Closing highlight */
  191325. const char *zIn; /* Input text */
  191326. int nIn; /* Size of input text in bytes */
  191327. int iOff; /* Current offset within zIn[] */
  191328. char *zOut; /* Output value */
  191329. };
  191330. /*
  191331. ** Append text to the HighlightContext output string - p->zOut. Argument
  191332. ** z points to a buffer containing n bytes of text to append. If n is
  191333. ** negative, everything up until the first '\0' is appended to the output.
  191334. **
  191335. ** If *pRc is set to any value other than SQLITE_OK when this function is
  191336. ** called, it is a no-op. If an error (i.e. an OOM condition) is encountered,
  191337. ** *pRc is set to an error code before returning.
  191338. */
  191339. static void fts5HighlightAppend(
  191340. int *pRc,
  191341. HighlightContext *p,
  191342. const char *z, int n
  191343. ){
  191344. if( *pRc==SQLITE_OK && z ){
  191345. if( n<0 ) n = (int)strlen(z);
  191346. p->zOut = sqlite3_mprintf("%z%.*s", p->zOut, n, z);
  191347. if( p->zOut==0 ) *pRc = SQLITE_NOMEM;
  191348. }
  191349. }
  191350. /*
  191351. ** Tokenizer callback used by implementation of highlight() function.
  191352. */
  191353. static int fts5HighlightCb(
  191354. void *pContext, /* Pointer to HighlightContext object */
  191355. int tflags, /* Mask of FTS5_TOKEN_* flags */
  191356. const char *pToken, /* Buffer containing token */
  191357. int nToken, /* Size of token in bytes */
  191358. int iStartOff, /* Start offset of token */
  191359. int iEndOff /* End offset of token */
  191360. ){
  191361. HighlightContext *p = (HighlightContext*)pContext;
  191362. int rc = SQLITE_OK;
  191363. int iPos;
  191364. UNUSED_PARAM2(pToken, nToken);
  191365. if( tflags & FTS5_TOKEN_COLOCATED ) return SQLITE_OK;
  191366. iPos = p->iPos++;
  191367. if( p->iRangeEnd>0 ){
  191368. if( iPos<p->iRangeStart || iPos>p->iRangeEnd ) return SQLITE_OK;
  191369. if( p->iRangeStart && iPos==p->iRangeStart ) p->iOff = iStartOff;
  191370. }
  191371. if( iPos==p->iter.iStart ){
  191372. fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iStartOff - p->iOff);
  191373. fts5HighlightAppend(&rc, p, p->zOpen, -1);
  191374. p->iOff = iStartOff;
  191375. }
  191376. if( iPos==p->iter.iEnd ){
  191377. if( p->iRangeEnd && p->iter.iStart<p->iRangeStart ){
  191378. fts5HighlightAppend(&rc, p, p->zOpen, -1);
  191379. }
  191380. fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
  191381. fts5HighlightAppend(&rc, p, p->zClose, -1);
  191382. p->iOff = iEndOff;
  191383. if( rc==SQLITE_OK ){
  191384. rc = fts5CInstIterNext(&p->iter);
  191385. }
  191386. }
  191387. if( p->iRangeEnd>0 && iPos==p->iRangeEnd ){
  191388. fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
  191389. p->iOff = iEndOff;
  191390. if( iPos>=p->iter.iStart && iPos<p->iter.iEnd ){
  191391. fts5HighlightAppend(&rc, p, p->zClose, -1);
  191392. }
  191393. }
  191394. return rc;
  191395. }
  191396. /*
  191397. ** Implementation of highlight() function.
  191398. */
  191399. static void fts5HighlightFunction(
  191400. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  191401. Fts5Context *pFts, /* First arg to pass to pApi functions */
  191402. sqlite3_context *pCtx, /* Context for returning result/error */
  191403. int nVal, /* Number of values in apVal[] array */
  191404. sqlite3_value **apVal /* Array of trailing arguments */
  191405. ){
  191406. HighlightContext ctx;
  191407. int rc;
  191408. int iCol;
  191409. if( nVal!=3 ){
  191410. const char *zErr = "wrong number of arguments to function highlight()";
  191411. sqlite3_result_error(pCtx, zErr, -1);
  191412. return;
  191413. }
  191414. iCol = sqlite3_value_int(apVal[0]);
  191415. memset(&ctx, 0, sizeof(HighlightContext));
  191416. ctx.zOpen = (const char*)sqlite3_value_text(apVal[1]);
  191417. ctx.zClose = (const char*)sqlite3_value_text(apVal[2]);
  191418. rc = pApi->xColumnText(pFts, iCol, &ctx.zIn, &ctx.nIn);
  191419. if( ctx.zIn ){
  191420. if( rc==SQLITE_OK ){
  191421. rc = fts5CInstIterInit(pApi, pFts, iCol, &ctx.iter);
  191422. }
  191423. if( rc==SQLITE_OK ){
  191424. rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb);
  191425. }
  191426. fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff);
  191427. if( rc==SQLITE_OK ){
  191428. sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT);
  191429. }
  191430. sqlite3_free(ctx.zOut);
  191431. }
  191432. if( rc!=SQLITE_OK ){
  191433. sqlite3_result_error_code(pCtx, rc);
  191434. }
  191435. }
  191436. /*
  191437. ** End of highlight() implementation.
  191438. **************************************************************************/
  191439. /*
  191440. ** Context object passed to the fts5SentenceFinderCb() function.
  191441. */
  191442. typedef struct Fts5SFinder Fts5SFinder;
  191443. struct Fts5SFinder {
  191444. int iPos; /* Current token position */
  191445. int nFirstAlloc; /* Allocated size of aFirst[] */
  191446. int nFirst; /* Number of entries in aFirst[] */
  191447. int *aFirst; /* Array of first token in each sentence */
  191448. const char *zDoc; /* Document being tokenized */
  191449. };
  191450. /*
  191451. ** Add an entry to the Fts5SFinder.aFirst[] array. Grow the array if
  191452. ** necessary. Return SQLITE_OK if successful, or SQLITE_NOMEM if an
  191453. ** error occurs.
  191454. */
  191455. static int fts5SentenceFinderAdd(Fts5SFinder *p, int iAdd){
  191456. if( p->nFirstAlloc==p->nFirst ){
  191457. int nNew = p->nFirstAlloc ? p->nFirstAlloc*2 : 64;
  191458. int *aNew;
  191459. aNew = (int*)sqlite3_realloc64(p->aFirst, nNew*sizeof(int));
  191460. if( aNew==0 ) return SQLITE_NOMEM;
  191461. p->aFirst = aNew;
  191462. p->nFirstAlloc = nNew;
  191463. }
  191464. p->aFirst[p->nFirst++] = iAdd;
  191465. return SQLITE_OK;
  191466. }
  191467. /*
  191468. ** This function is an xTokenize() callback used by the auxiliary snippet()
  191469. ** function. Its job is to identify tokens that are the first in a sentence.
  191470. ** For each such token, an entry is added to the SFinder.aFirst[] array.
  191471. */
  191472. static int fts5SentenceFinderCb(
  191473. void *pContext, /* Pointer to HighlightContext object */
  191474. int tflags, /* Mask of FTS5_TOKEN_* flags */
  191475. const char *pToken, /* Buffer containing token */
  191476. int nToken, /* Size of token in bytes */
  191477. int iStartOff, /* Start offset of token */
  191478. int iEndOff /* End offset of token */
  191479. ){
  191480. int rc = SQLITE_OK;
  191481. UNUSED_PARAM2(pToken, nToken);
  191482. UNUSED_PARAM(iEndOff);
  191483. if( (tflags & FTS5_TOKEN_COLOCATED)==0 ){
  191484. Fts5SFinder *p = (Fts5SFinder*)pContext;
  191485. if( p->iPos>0 ){
  191486. int i;
  191487. char c = 0;
  191488. for(i=iStartOff-1; i>=0; i--){
  191489. c = p->zDoc[i];
  191490. if( c!=' ' && c!='\t' && c!='\n' && c!='\r' ) break;
  191491. }
  191492. if( i!=iStartOff-1 && (c=='.' || c==':') ){
  191493. rc = fts5SentenceFinderAdd(p, p->iPos);
  191494. }
  191495. }else{
  191496. rc = fts5SentenceFinderAdd(p, 0);
  191497. }
  191498. p->iPos++;
  191499. }
  191500. return rc;
  191501. }
  191502. static int fts5SnippetScore(
  191503. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  191504. Fts5Context *pFts, /* First arg to pass to pApi functions */
  191505. int nDocsize, /* Size of column in tokens */
  191506. unsigned char *aSeen, /* Array with one element per query phrase */
  191507. int iCol, /* Column to score */
  191508. int iPos, /* Starting offset to score */
  191509. int nToken, /* Max tokens per snippet */
  191510. int *pnScore, /* OUT: Score */
  191511. int *piPos /* OUT: Adjusted offset */
  191512. ){
  191513. int rc;
  191514. int i;
  191515. int ip = 0;
  191516. int ic = 0;
  191517. int iOff = 0;
  191518. int iFirst = -1;
  191519. int nInst;
  191520. int nScore = 0;
  191521. int iLast = 0;
  191522. sqlite3_int64 iEnd = (sqlite3_int64)iPos + nToken;
  191523. rc = pApi->xInstCount(pFts, &nInst);
  191524. for(i=0; i<nInst && rc==SQLITE_OK; i++){
  191525. rc = pApi->xInst(pFts, i, &ip, &ic, &iOff);
  191526. if( rc==SQLITE_OK && ic==iCol && iOff>=iPos && iOff<iEnd ){
  191527. nScore += (aSeen[ip] ? 1 : 1000);
  191528. aSeen[ip] = 1;
  191529. if( iFirst<0 ) iFirst = iOff;
  191530. iLast = iOff + pApi->xPhraseSize(pFts, ip);
  191531. }
  191532. }
  191533. *pnScore = nScore;
  191534. if( piPos ){
  191535. sqlite3_int64 iAdj = iFirst - (nToken - (iLast-iFirst)) / 2;
  191536. if( (iAdj+nToken)>nDocsize ) iAdj = nDocsize - nToken;
  191537. if( iAdj<0 ) iAdj = 0;
  191538. *piPos = (int)iAdj;
  191539. }
  191540. return rc;
  191541. }
  191542. /*
  191543. ** Return the value in pVal interpreted as utf-8 text. Except, if pVal
  191544. ** contains a NULL value, return a pointer to a static string zero
  191545. ** bytes in length instead of a NULL pointer.
  191546. */
  191547. static const char *fts5ValueToText(sqlite3_value *pVal){
  191548. const char *zRet = (const char*)sqlite3_value_text(pVal);
  191549. return zRet ? zRet : "";
  191550. }
  191551. /*
  191552. ** Implementation of snippet() function.
  191553. */
  191554. static void fts5SnippetFunction(
  191555. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  191556. Fts5Context *pFts, /* First arg to pass to pApi functions */
  191557. sqlite3_context *pCtx, /* Context for returning result/error */
  191558. int nVal, /* Number of values in apVal[] array */
  191559. sqlite3_value **apVal /* Array of trailing arguments */
  191560. ){
  191561. HighlightContext ctx;
  191562. int rc = SQLITE_OK; /* Return code */
  191563. int iCol; /* 1st argument to snippet() */
  191564. const char *zEllips; /* 4th argument to snippet() */
  191565. int nToken; /* 5th argument to snippet() */
  191566. int nInst = 0; /* Number of instance matches this row */
  191567. int i; /* Used to iterate through instances */
  191568. int nPhrase; /* Number of phrases in query */
  191569. unsigned char *aSeen; /* Array of "seen instance" flags */
  191570. int iBestCol; /* Column containing best snippet */
  191571. int iBestStart = 0; /* First token of best snippet */
  191572. int nBestScore = 0; /* Score of best snippet */
  191573. int nColSize = 0; /* Total size of iBestCol in tokens */
  191574. Fts5SFinder sFinder; /* Used to find the beginnings of sentences */
  191575. int nCol;
  191576. if( nVal!=5 ){
  191577. const char *zErr = "wrong number of arguments to function snippet()";
  191578. sqlite3_result_error(pCtx, zErr, -1);
  191579. return;
  191580. }
  191581. nCol = pApi->xColumnCount(pFts);
  191582. memset(&ctx, 0, sizeof(HighlightContext));
  191583. iCol = sqlite3_value_int(apVal[0]);
  191584. ctx.zOpen = fts5ValueToText(apVal[1]);
  191585. ctx.zClose = fts5ValueToText(apVal[2]);
  191586. zEllips = fts5ValueToText(apVal[3]);
  191587. nToken = sqlite3_value_int(apVal[4]);
  191588. iBestCol = (iCol>=0 ? iCol : 0);
  191589. nPhrase = pApi->xPhraseCount(pFts);
  191590. aSeen = sqlite3_malloc(nPhrase);
  191591. if( aSeen==0 ){
  191592. rc = SQLITE_NOMEM;
  191593. }
  191594. if( rc==SQLITE_OK ){
  191595. rc = pApi->xInstCount(pFts, &nInst);
  191596. }
  191597. memset(&sFinder, 0, sizeof(Fts5SFinder));
  191598. for(i=0; i<nCol; i++){
  191599. if( iCol<0 || iCol==i ){
  191600. int nDoc;
  191601. int nDocsize;
  191602. int ii;
  191603. sFinder.iPos = 0;
  191604. sFinder.nFirst = 0;
  191605. rc = pApi->xColumnText(pFts, i, &sFinder.zDoc, &nDoc);
  191606. if( rc!=SQLITE_OK ) break;
  191607. rc = pApi->xTokenize(pFts,
  191608. sFinder.zDoc, nDoc, (void*)&sFinder,fts5SentenceFinderCb
  191609. );
  191610. if( rc!=SQLITE_OK ) break;
  191611. rc = pApi->xColumnSize(pFts, i, &nDocsize);
  191612. if( rc!=SQLITE_OK ) break;
  191613. for(ii=0; rc==SQLITE_OK && ii<nInst; ii++){
  191614. int ip, ic, io;
  191615. int iAdj;
  191616. int nScore;
  191617. int jj;
  191618. rc = pApi->xInst(pFts, ii, &ip, &ic, &io);
  191619. if( ic!=i ) continue;
  191620. if( io>nDocsize ) rc = FTS5_CORRUPT;
  191621. if( rc!=SQLITE_OK ) continue;
  191622. memset(aSeen, 0, nPhrase);
  191623. rc = fts5SnippetScore(pApi, pFts, nDocsize, aSeen, i,
  191624. io, nToken, &nScore, &iAdj
  191625. );
  191626. if( rc==SQLITE_OK && nScore>nBestScore ){
  191627. nBestScore = nScore;
  191628. iBestCol = i;
  191629. iBestStart = iAdj;
  191630. nColSize = nDocsize;
  191631. }
  191632. if( rc==SQLITE_OK && sFinder.nFirst && nDocsize>nToken ){
  191633. for(jj=0; jj<(sFinder.nFirst-1); jj++){
  191634. if( sFinder.aFirst[jj+1]>io ) break;
  191635. }
  191636. if( sFinder.aFirst[jj]<io ){
  191637. memset(aSeen, 0, nPhrase);
  191638. rc = fts5SnippetScore(pApi, pFts, nDocsize, aSeen, i,
  191639. sFinder.aFirst[jj], nToken, &nScore, 0
  191640. );
  191641. nScore += (sFinder.aFirst[jj]==0 ? 120 : 100);
  191642. if( rc==SQLITE_OK && nScore>nBestScore ){
  191643. nBestScore = nScore;
  191644. iBestCol = i;
  191645. iBestStart = sFinder.aFirst[jj];
  191646. nColSize = nDocsize;
  191647. }
  191648. }
  191649. }
  191650. }
  191651. }
  191652. }
  191653. if( rc==SQLITE_OK ){
  191654. rc = pApi->xColumnText(pFts, iBestCol, &ctx.zIn, &ctx.nIn);
  191655. }
  191656. if( rc==SQLITE_OK && nColSize==0 ){
  191657. rc = pApi->xColumnSize(pFts, iBestCol, &nColSize);
  191658. }
  191659. if( ctx.zIn ){
  191660. if( rc==SQLITE_OK ){
  191661. rc = fts5CInstIterInit(pApi, pFts, iBestCol, &ctx.iter);
  191662. }
  191663. ctx.iRangeStart = iBestStart;
  191664. ctx.iRangeEnd = iBestStart + nToken - 1;
  191665. if( iBestStart>0 ){
  191666. fts5HighlightAppend(&rc, &ctx, zEllips, -1);
  191667. }
  191668. /* Advance iterator ctx.iter so that it points to the first coalesced
  191669. ** phrase instance at or following position iBestStart. */
  191670. while( ctx.iter.iStart>=0 && ctx.iter.iStart<iBestStart && rc==SQLITE_OK ){
  191671. rc = fts5CInstIterNext(&ctx.iter);
  191672. }
  191673. if( rc==SQLITE_OK ){
  191674. rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb);
  191675. }
  191676. if( ctx.iRangeEnd>=(nColSize-1) ){
  191677. fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff);
  191678. }else{
  191679. fts5HighlightAppend(&rc, &ctx, zEllips, -1);
  191680. }
  191681. }
  191682. if( rc==SQLITE_OK ){
  191683. sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT);
  191684. }else{
  191685. sqlite3_result_error_code(pCtx, rc);
  191686. }
  191687. sqlite3_free(ctx.zOut);
  191688. sqlite3_free(aSeen);
  191689. sqlite3_free(sFinder.aFirst);
  191690. }
  191691. /************************************************************************/
  191692. /*
  191693. ** The first time the bm25() function is called for a query, an instance
  191694. ** of the following structure is allocated and populated.
  191695. */
  191696. typedef struct Fts5Bm25Data Fts5Bm25Data;
  191697. struct Fts5Bm25Data {
  191698. int nPhrase; /* Number of phrases in query */
  191699. double avgdl; /* Average number of tokens in each row */
  191700. double *aIDF; /* IDF for each phrase */
  191701. double *aFreq; /* Array used to calculate phrase freq. */
  191702. };
  191703. /*
  191704. ** Callback used by fts5Bm25GetData() to count the number of rows in the
  191705. ** table matched by each individual phrase within the query.
  191706. */
  191707. static int fts5CountCb(
  191708. const Fts5ExtensionApi *pApi,
  191709. Fts5Context *pFts,
  191710. void *pUserData /* Pointer to sqlite3_int64 variable */
  191711. ){
  191712. sqlite3_int64 *pn = (sqlite3_int64*)pUserData;
  191713. UNUSED_PARAM2(pApi, pFts);
  191714. (*pn)++;
  191715. return SQLITE_OK;
  191716. }
  191717. /*
  191718. ** Set *ppData to point to the Fts5Bm25Data object for the current query.
  191719. ** If the object has not already been allocated, allocate and populate it
  191720. ** now.
  191721. */
  191722. static int fts5Bm25GetData(
  191723. const Fts5ExtensionApi *pApi,
  191724. Fts5Context *pFts,
  191725. Fts5Bm25Data **ppData /* OUT: bm25-data object for this query */
  191726. ){
  191727. int rc = SQLITE_OK; /* Return code */
  191728. Fts5Bm25Data *p; /* Object to return */
  191729. p = pApi->xGetAuxdata(pFts, 0);
  191730. if( p==0 ){
  191731. int nPhrase; /* Number of phrases in query */
  191732. sqlite3_int64 nRow = 0; /* Number of rows in table */
  191733. sqlite3_int64 nToken = 0; /* Number of tokens in table */
  191734. sqlite3_int64 nByte; /* Bytes of space to allocate */
  191735. int i;
  191736. /* Allocate the Fts5Bm25Data object */
  191737. nPhrase = pApi->xPhraseCount(pFts);
  191738. nByte = sizeof(Fts5Bm25Data) + nPhrase*2*sizeof(double);
  191739. p = (Fts5Bm25Data*)sqlite3_malloc64(nByte);
  191740. if( p==0 ){
  191741. rc = SQLITE_NOMEM;
  191742. }else{
  191743. memset(p, 0, (size_t)nByte);
  191744. p->nPhrase = nPhrase;
  191745. p->aIDF = (double*)&p[1];
  191746. p->aFreq = &p->aIDF[nPhrase];
  191747. }
  191748. /* Calculate the average document length for this FTS5 table */
  191749. if( rc==SQLITE_OK ) rc = pApi->xRowCount(pFts, &nRow);
  191750. assert( rc!=SQLITE_OK || nRow>0 );
  191751. if( rc==SQLITE_OK ) rc = pApi->xColumnTotalSize(pFts, -1, &nToken);
  191752. if( rc==SQLITE_OK ) p->avgdl = (double)nToken / (double)nRow;
  191753. /* Calculate an IDF for each phrase in the query */
  191754. for(i=0; rc==SQLITE_OK && i<nPhrase; i++){
  191755. sqlite3_int64 nHit = 0;
  191756. rc = pApi->xQueryPhrase(pFts, i, (void*)&nHit, fts5CountCb);
  191757. if( rc==SQLITE_OK ){
  191758. /* Calculate the IDF (Inverse Document Frequency) for phrase i.
  191759. ** This is done using the standard BM25 formula as found on wikipedia:
  191760. **
  191761. ** IDF = log( (N - nHit + 0.5) / (nHit + 0.5) )
  191762. **
  191763. ** where "N" is the total number of documents in the set and nHit
  191764. ** is the number that contain at least one instance of the phrase
  191765. ** under consideration.
  191766. **
  191767. ** The problem with this is that if (N < 2*nHit), the IDF is
  191768. ** negative. Which is undesirable. So the mimimum allowable IDF is
  191769. ** (1e-6) - roughly the same as a term that appears in just over
  191770. ** half of set of 5,000,000 documents. */
  191771. double idf = log( (nRow - nHit + 0.5) / (nHit + 0.5) );
  191772. if( idf<=0.0 ) idf = 1e-6;
  191773. p->aIDF[i] = idf;
  191774. }
  191775. }
  191776. if( rc!=SQLITE_OK ){
  191777. sqlite3_free(p);
  191778. }else{
  191779. rc = pApi->xSetAuxdata(pFts, p, sqlite3_free);
  191780. }
  191781. if( rc!=SQLITE_OK ) p = 0;
  191782. }
  191783. *ppData = p;
  191784. return rc;
  191785. }
  191786. /*
  191787. ** Implementation of bm25() function.
  191788. */
  191789. static void fts5Bm25Function(
  191790. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  191791. Fts5Context *pFts, /* First arg to pass to pApi functions */
  191792. sqlite3_context *pCtx, /* Context for returning result/error */
  191793. int nVal, /* Number of values in apVal[] array */
  191794. sqlite3_value **apVal /* Array of trailing arguments */
  191795. ){
  191796. const double k1 = 1.2; /* Constant "k1" from BM25 formula */
  191797. const double b = 0.75; /* Constant "b" from BM25 formula */
  191798. int rc = SQLITE_OK; /* Error code */
  191799. double score = 0.0; /* SQL function return value */
  191800. Fts5Bm25Data *pData; /* Values allocated/calculated once only */
  191801. int i; /* Iterator variable */
  191802. int nInst = 0; /* Value returned by xInstCount() */
  191803. double D = 0.0; /* Total number of tokens in row */
  191804. double *aFreq = 0; /* Array of phrase freq. for current row */
  191805. /* Calculate the phrase frequency (symbol "f(qi,D)" in the documentation)
  191806. ** for each phrase in the query for the current row. */
  191807. rc = fts5Bm25GetData(pApi, pFts, &pData);
  191808. if( rc==SQLITE_OK ){
  191809. aFreq = pData->aFreq;
  191810. memset(aFreq, 0, sizeof(double) * pData->nPhrase);
  191811. rc = pApi->xInstCount(pFts, &nInst);
  191812. }
  191813. for(i=0; rc==SQLITE_OK && i<nInst; i++){
  191814. int ip; int ic; int io;
  191815. rc = pApi->xInst(pFts, i, &ip, &ic, &io);
  191816. if( rc==SQLITE_OK ){
  191817. double w = (nVal > ic) ? sqlite3_value_double(apVal[ic]) : 1.0;
  191818. aFreq[ip] += w;
  191819. }
  191820. }
  191821. /* Figure out the total size of the current row in tokens. */
  191822. if( rc==SQLITE_OK ){
  191823. int nTok;
  191824. rc = pApi->xColumnSize(pFts, -1, &nTok);
  191825. D = (double)nTok;
  191826. }
  191827. /* Determine the BM25 score for the current row. */
  191828. for(i=0; rc==SQLITE_OK && i<pData->nPhrase; i++){
  191829. score += pData->aIDF[i] * (
  191830. ( aFreq[i] * (k1 + 1.0) ) /
  191831. ( aFreq[i] + k1 * (1 - b + b * D / pData->avgdl) )
  191832. );
  191833. }
  191834. /* If no error has occurred, return the calculated score. Otherwise,
  191835. ** throw an SQL exception. */
  191836. if( rc==SQLITE_OK ){
  191837. sqlite3_result_double(pCtx, -1.0 * score);
  191838. }else{
  191839. sqlite3_result_error_code(pCtx, rc);
  191840. }
  191841. }
  191842. static int sqlite3Fts5AuxInit(fts5_api *pApi){
  191843. struct Builtin {
  191844. const char *zFunc; /* Function name (nul-terminated) */
  191845. void *pUserData; /* User-data pointer */
  191846. fts5_extension_function xFunc;/* Callback function */
  191847. void (*xDestroy)(void*); /* Destructor function */
  191848. } aBuiltin [] = {
  191849. { "snippet", 0, fts5SnippetFunction, 0 },
  191850. { "highlight", 0, fts5HighlightFunction, 0 },
  191851. { "bm25", 0, fts5Bm25Function, 0 },
  191852. };
  191853. int rc = SQLITE_OK; /* Return code */
  191854. int i; /* To iterate through builtin functions */
  191855. for(i=0; rc==SQLITE_OK && i<ArraySize(aBuiltin); i++){
  191856. rc = pApi->xCreateFunction(pApi,
  191857. aBuiltin[i].zFunc,
  191858. aBuiltin[i].pUserData,
  191859. aBuiltin[i].xFunc,
  191860. aBuiltin[i].xDestroy
  191861. );
  191862. }
  191863. return rc;
  191864. }
  191865. /*
  191866. ** 2014 May 31
  191867. **
  191868. ** The author disclaims copyright to this source code. In place of
  191869. ** a legal notice, here is a blessing:
  191870. **
  191871. ** May you do good and not evil.
  191872. ** May you find forgiveness for yourself and forgive others.
  191873. ** May you share freely, never taking more than you give.
  191874. **
  191875. ******************************************************************************
  191876. */
  191877. /* #include "fts5Int.h" */
  191878. static int sqlite3Fts5BufferSize(int *pRc, Fts5Buffer *pBuf, u32 nByte){
  191879. if( (u32)pBuf->nSpace<nByte ){
  191880. u64 nNew = pBuf->nSpace ? pBuf->nSpace : 64;
  191881. u8 *pNew;
  191882. while( nNew<nByte ){
  191883. nNew = nNew * 2;
  191884. }
  191885. pNew = sqlite3_realloc64(pBuf->p, nNew);
  191886. if( pNew==0 ){
  191887. *pRc = SQLITE_NOMEM;
  191888. return 1;
  191889. }else{
  191890. pBuf->nSpace = (int)nNew;
  191891. pBuf->p = pNew;
  191892. }
  191893. }
  191894. return 0;
  191895. }
  191896. /*
  191897. ** Encode value iVal as an SQLite varint and append it to the buffer object
  191898. ** pBuf. If an OOM error occurs, set the error code in p.
  191899. */
  191900. static void sqlite3Fts5BufferAppendVarint(int *pRc, Fts5Buffer *pBuf, i64 iVal){
  191901. if( fts5BufferGrow(pRc, pBuf, 9) ) return;
  191902. pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iVal);
  191903. }
  191904. static void sqlite3Fts5Put32(u8 *aBuf, int iVal){
  191905. aBuf[0] = (iVal>>24) & 0x00FF;
  191906. aBuf[1] = (iVal>>16) & 0x00FF;
  191907. aBuf[2] = (iVal>> 8) & 0x00FF;
  191908. aBuf[3] = (iVal>> 0) & 0x00FF;
  191909. }
  191910. static int sqlite3Fts5Get32(const u8 *aBuf){
  191911. return (int)((((u32)aBuf[0])<<24) + (aBuf[1]<<16) + (aBuf[2]<<8) + aBuf[3]);
  191912. }
  191913. /*
  191914. ** Append buffer nData/pData to buffer pBuf. If an OOM error occurs, set
  191915. ** the error code in p. If an error has already occurred when this function
  191916. ** is called, it is a no-op.
  191917. */
  191918. static void sqlite3Fts5BufferAppendBlob(
  191919. int *pRc,
  191920. Fts5Buffer *pBuf,
  191921. u32 nData,
  191922. const u8 *pData
  191923. ){
  191924. assert_nc( *pRc || nData>=0 );
  191925. if( nData ){
  191926. if( fts5BufferGrow(pRc, pBuf, nData) ) return;
  191927. memcpy(&pBuf->p[pBuf->n], pData, nData);
  191928. pBuf->n += nData;
  191929. }
  191930. }
  191931. /*
  191932. ** Append the nul-terminated string zStr to the buffer pBuf. This function
  191933. ** ensures that the byte following the buffer data is set to 0x00, even
  191934. ** though this byte is not included in the pBuf->n count.
  191935. */
  191936. static void sqlite3Fts5BufferAppendString(
  191937. int *pRc,
  191938. Fts5Buffer *pBuf,
  191939. const char *zStr
  191940. ){
  191941. int nStr = (int)strlen(zStr);
  191942. sqlite3Fts5BufferAppendBlob(pRc, pBuf, nStr+1, (const u8*)zStr);
  191943. pBuf->n--;
  191944. }
  191945. /*
  191946. ** Argument zFmt is a printf() style format string. This function performs
  191947. ** the printf() style processing, then appends the results to buffer pBuf.
  191948. **
  191949. ** Like sqlite3Fts5BufferAppendString(), this function ensures that the byte
  191950. ** following the buffer data is set to 0x00, even though this byte is not
  191951. ** included in the pBuf->n count.
  191952. */
  191953. static void sqlite3Fts5BufferAppendPrintf(
  191954. int *pRc,
  191955. Fts5Buffer *pBuf,
  191956. char *zFmt, ...
  191957. ){
  191958. if( *pRc==SQLITE_OK ){
  191959. char *zTmp;
  191960. va_list ap;
  191961. va_start(ap, zFmt);
  191962. zTmp = sqlite3_vmprintf(zFmt, ap);
  191963. va_end(ap);
  191964. if( zTmp==0 ){
  191965. *pRc = SQLITE_NOMEM;
  191966. }else{
  191967. sqlite3Fts5BufferAppendString(pRc, pBuf, zTmp);
  191968. sqlite3_free(zTmp);
  191969. }
  191970. }
  191971. }
  191972. static char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...){
  191973. char *zRet = 0;
  191974. if( *pRc==SQLITE_OK ){
  191975. va_list ap;
  191976. va_start(ap, zFmt);
  191977. zRet = sqlite3_vmprintf(zFmt, ap);
  191978. va_end(ap);
  191979. if( zRet==0 ){
  191980. *pRc = SQLITE_NOMEM;
  191981. }
  191982. }
  191983. return zRet;
  191984. }
  191985. /*
  191986. ** Free any buffer allocated by pBuf. Zero the structure before returning.
  191987. */
  191988. static void sqlite3Fts5BufferFree(Fts5Buffer *pBuf){
  191989. sqlite3_free(pBuf->p);
  191990. memset(pBuf, 0, sizeof(Fts5Buffer));
  191991. }
  191992. /*
  191993. ** Zero the contents of the buffer object. But do not free the associated
  191994. ** memory allocation.
  191995. */
  191996. static void sqlite3Fts5BufferZero(Fts5Buffer *pBuf){
  191997. pBuf->n = 0;
  191998. }
  191999. /*
  192000. ** Set the buffer to contain nData/pData. If an OOM error occurs, leave an
  192001. ** the error code in p. If an error has already occurred when this function
  192002. ** is called, it is a no-op.
  192003. */
  192004. static void sqlite3Fts5BufferSet(
  192005. int *pRc,
  192006. Fts5Buffer *pBuf,
  192007. int nData,
  192008. const u8 *pData
  192009. ){
  192010. pBuf->n = 0;
  192011. sqlite3Fts5BufferAppendBlob(pRc, pBuf, nData, pData);
  192012. }
  192013. static int sqlite3Fts5PoslistNext64(
  192014. const u8 *a, int n, /* Buffer containing poslist */
  192015. int *pi, /* IN/OUT: Offset within a[] */
  192016. i64 *piOff /* IN/OUT: Current offset */
  192017. ){
  192018. int i = *pi;
  192019. if( i>=n ){
  192020. /* EOF */
  192021. *piOff = -1;
  192022. return 1;
  192023. }else{
  192024. i64 iOff = *piOff;
  192025. int iVal;
  192026. fts5FastGetVarint32(a, i, iVal);
  192027. if( iVal<=1 ){
  192028. if( iVal==0 ){
  192029. *pi = i;
  192030. return 0;
  192031. }
  192032. fts5FastGetVarint32(a, i, iVal);
  192033. iOff = ((i64)iVal) << 32;
  192034. fts5FastGetVarint32(a, i, iVal);
  192035. if( iVal<2 ){
  192036. /* This is a corrupt record. So stop parsing it here. */
  192037. *piOff = -1;
  192038. return 1;
  192039. }
  192040. }
  192041. *piOff = iOff + ((iVal-2) & 0x7FFFFFFF);
  192042. *pi = i;
  192043. return 0;
  192044. }
  192045. }
  192046. /*
  192047. ** Advance the iterator object passed as the only argument. Return true
  192048. ** if the iterator reaches EOF, or false otherwise.
  192049. */
  192050. static int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader *pIter){
  192051. if( sqlite3Fts5PoslistNext64(pIter->a, pIter->n, &pIter->i, &pIter->iPos) ){
  192052. pIter->bEof = 1;
  192053. }
  192054. return pIter->bEof;
  192055. }
  192056. static int sqlite3Fts5PoslistReaderInit(
  192057. const u8 *a, int n, /* Poslist buffer to iterate through */
  192058. Fts5PoslistReader *pIter /* Iterator object to initialize */
  192059. ){
  192060. memset(pIter, 0, sizeof(*pIter));
  192061. pIter->a = a;
  192062. pIter->n = n;
  192063. sqlite3Fts5PoslistReaderNext(pIter);
  192064. return pIter->bEof;
  192065. }
  192066. /*
  192067. ** Append position iPos to the position list being accumulated in buffer
  192068. ** pBuf, which must be already be large enough to hold the new data.
  192069. ** The previous position written to this list is *piPrev. *piPrev is set
  192070. ** to iPos before returning.
  192071. */
  192072. static void sqlite3Fts5PoslistSafeAppend(
  192073. Fts5Buffer *pBuf,
  192074. i64 *piPrev,
  192075. i64 iPos
  192076. ){
  192077. static const i64 colmask = ((i64)(0x7FFFFFFF)) << 32;
  192078. if( (iPos & colmask) != (*piPrev & colmask) ){
  192079. pBuf->p[pBuf->n++] = 1;
  192080. pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos>>32));
  192081. *piPrev = (iPos & colmask);
  192082. }
  192083. pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos-*piPrev)+2);
  192084. *piPrev = iPos;
  192085. }
  192086. static int sqlite3Fts5PoslistWriterAppend(
  192087. Fts5Buffer *pBuf,
  192088. Fts5PoslistWriter *pWriter,
  192089. i64 iPos
  192090. ){
  192091. int rc = 0; /* Initialized only to suppress erroneous warning from Clang */
  192092. if( fts5BufferGrow(&rc, pBuf, 5+5+5) ) return rc;
  192093. sqlite3Fts5PoslistSafeAppend(pBuf, &pWriter->iPrev, iPos);
  192094. return SQLITE_OK;
  192095. }
  192096. static void *sqlite3Fts5MallocZero(int *pRc, sqlite3_int64 nByte){
  192097. void *pRet = 0;
  192098. if( *pRc==SQLITE_OK ){
  192099. pRet = sqlite3_malloc64(nByte);
  192100. if( pRet==0 ){
  192101. if( nByte>0 ) *pRc = SQLITE_NOMEM;
  192102. }else{
  192103. memset(pRet, 0, (size_t)nByte);
  192104. }
  192105. }
  192106. return pRet;
  192107. }
  192108. /*
  192109. ** Return a nul-terminated copy of the string indicated by pIn. If nIn
  192110. ** is non-negative, then it is the length of the string in bytes. Otherwise,
  192111. ** the length of the string is determined using strlen().
  192112. **
  192113. ** It is the responsibility of the caller to eventually free the returned
  192114. ** buffer using sqlite3_free(). If an OOM error occurs, NULL is returned.
  192115. */
  192116. static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn){
  192117. char *zRet = 0;
  192118. if( *pRc==SQLITE_OK ){
  192119. if( nIn<0 ){
  192120. nIn = (int)strlen(pIn);
  192121. }
  192122. zRet = (char*)sqlite3_malloc(nIn+1);
  192123. if( zRet ){
  192124. memcpy(zRet, pIn, nIn);
  192125. zRet[nIn] = '\0';
  192126. }else{
  192127. *pRc = SQLITE_NOMEM;
  192128. }
  192129. }
  192130. return zRet;
  192131. }
  192132. /*
  192133. ** Return true if character 't' may be part of an FTS5 bareword, or false
  192134. ** otherwise. Characters that may be part of barewords:
  192135. **
  192136. ** * All non-ASCII characters,
  192137. ** * The 52 upper and lower case ASCII characters, and
  192138. ** * The 10 integer ASCII characters.
  192139. ** * The underscore character "_" (0x5F).
  192140. ** * The unicode "subsitute" character (0x1A).
  192141. */
  192142. static int sqlite3Fts5IsBareword(char t){
  192143. u8 aBareword[128] = {
  192144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x00 .. 0x0F */
  192145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, /* 0x10 .. 0x1F */
  192146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x20 .. 0x2F */
  192147. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 0x30 .. 0x3F */
  192148. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x40 .. 0x4F */
  192149. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 0x50 .. 0x5F */
  192150. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x60 .. 0x6F */
  192151. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 /* 0x70 .. 0x7F */
  192152. };
  192153. return (t & 0x80) || aBareword[(int)t];
  192154. }
  192155. /*************************************************************************
  192156. */
  192157. typedef struct Fts5TermsetEntry Fts5TermsetEntry;
  192158. struct Fts5TermsetEntry {
  192159. char *pTerm;
  192160. int nTerm;
  192161. int iIdx; /* Index (main or aPrefix[] entry) */
  192162. Fts5TermsetEntry *pNext;
  192163. };
  192164. struct Fts5Termset {
  192165. Fts5TermsetEntry *apHash[512];
  192166. };
  192167. static int sqlite3Fts5TermsetNew(Fts5Termset **pp){
  192168. int rc = SQLITE_OK;
  192169. *pp = sqlite3Fts5MallocZero(&rc, sizeof(Fts5Termset));
  192170. return rc;
  192171. }
  192172. static int sqlite3Fts5TermsetAdd(
  192173. Fts5Termset *p,
  192174. int iIdx,
  192175. const char *pTerm, int nTerm,
  192176. int *pbPresent
  192177. ){
  192178. int rc = SQLITE_OK;
  192179. *pbPresent = 0;
  192180. if( p ){
  192181. int i;
  192182. u32 hash = 13;
  192183. Fts5TermsetEntry *pEntry;
  192184. /* Calculate a hash value for this term. This is the same hash checksum
  192185. ** used by the fts5_hash.c module. This is not important for correct
  192186. ** operation of the module, but is necessary to ensure that some tests
  192187. ** designed to produce hash table collisions really do work. */
  192188. for(i=nTerm-1; i>=0; i--){
  192189. hash = (hash << 3) ^ hash ^ pTerm[i];
  192190. }
  192191. hash = (hash << 3) ^ hash ^ iIdx;
  192192. hash = hash % ArraySize(p->apHash);
  192193. for(pEntry=p->apHash[hash]; pEntry; pEntry=pEntry->pNext){
  192194. if( pEntry->iIdx==iIdx
  192195. && pEntry->nTerm==nTerm
  192196. && memcmp(pEntry->pTerm, pTerm, nTerm)==0
  192197. ){
  192198. *pbPresent = 1;
  192199. break;
  192200. }
  192201. }
  192202. if( pEntry==0 ){
  192203. pEntry = sqlite3Fts5MallocZero(&rc, sizeof(Fts5TermsetEntry) + nTerm);
  192204. if( pEntry ){
  192205. pEntry->pTerm = (char*)&pEntry[1];
  192206. pEntry->nTerm = nTerm;
  192207. pEntry->iIdx = iIdx;
  192208. memcpy(pEntry->pTerm, pTerm, nTerm);
  192209. pEntry->pNext = p->apHash[hash];
  192210. p->apHash[hash] = pEntry;
  192211. }
  192212. }
  192213. }
  192214. return rc;
  192215. }
  192216. static void sqlite3Fts5TermsetFree(Fts5Termset *p){
  192217. if( p ){
  192218. u32 i;
  192219. for(i=0; i<ArraySize(p->apHash); i++){
  192220. Fts5TermsetEntry *pEntry = p->apHash[i];
  192221. while( pEntry ){
  192222. Fts5TermsetEntry *pDel = pEntry;
  192223. pEntry = pEntry->pNext;
  192224. sqlite3_free(pDel);
  192225. }
  192226. }
  192227. sqlite3_free(p);
  192228. }
  192229. }
  192230. /*
  192231. ** 2014 Jun 09
  192232. **
  192233. ** The author disclaims copyright to this source code. In place of
  192234. ** a legal notice, here is a blessing:
  192235. **
  192236. ** May you do good and not evil.
  192237. ** May you find forgiveness for yourself and forgive others.
  192238. ** May you share freely, never taking more than you give.
  192239. **
  192240. ******************************************************************************
  192241. **
  192242. ** This is an SQLite module implementing full-text search.
  192243. */
  192244. /* #include "fts5Int.h" */
  192245. #define FTS5_DEFAULT_PAGE_SIZE 4050
  192246. #define FTS5_DEFAULT_AUTOMERGE 4
  192247. #define FTS5_DEFAULT_USERMERGE 4
  192248. #define FTS5_DEFAULT_CRISISMERGE 16
  192249. #define FTS5_DEFAULT_HASHSIZE (1024*1024)
  192250. /* Maximum allowed page size */
  192251. #define FTS5_MAX_PAGE_SIZE (128*1024)
  192252. static int fts5_iswhitespace(char x){
  192253. return (x==' ');
  192254. }
  192255. static int fts5_isopenquote(char x){
  192256. return (x=='"' || x=='\'' || x=='[' || x=='`');
  192257. }
  192258. /*
  192259. ** Argument pIn points to a character that is part of a nul-terminated
  192260. ** string. Return a pointer to the first character following *pIn in
  192261. ** the string that is not a white-space character.
  192262. */
  192263. static const char *fts5ConfigSkipWhitespace(const char *pIn){
  192264. const char *p = pIn;
  192265. if( p ){
  192266. while( fts5_iswhitespace(*p) ){ p++; }
  192267. }
  192268. return p;
  192269. }
  192270. /*
  192271. ** Argument pIn points to a character that is part of a nul-terminated
  192272. ** string. Return a pointer to the first character following *pIn in
  192273. ** the string that is not a "bareword" character.
  192274. */
  192275. static const char *fts5ConfigSkipBareword(const char *pIn){
  192276. const char *p = pIn;
  192277. while ( sqlite3Fts5IsBareword(*p) ) p++;
  192278. if( p==pIn ) p = 0;
  192279. return p;
  192280. }
  192281. static int fts5_isdigit(char a){
  192282. return (a>='0' && a<='9');
  192283. }
  192284. static const char *fts5ConfigSkipLiteral(const char *pIn){
  192285. const char *p = pIn;
  192286. switch( *p ){
  192287. case 'n': case 'N':
  192288. if( sqlite3_strnicmp("null", p, 4)==0 ){
  192289. p = &p[4];
  192290. }else{
  192291. p = 0;
  192292. }
  192293. break;
  192294. case 'x': case 'X':
  192295. p++;
  192296. if( *p=='\'' ){
  192297. p++;
  192298. while( (*p>='a' && *p<='f')
  192299. || (*p>='A' && *p<='F')
  192300. || (*p>='0' && *p<='9')
  192301. ){
  192302. p++;
  192303. }
  192304. if( *p=='\'' && 0==((p-pIn)%2) ){
  192305. p++;
  192306. }else{
  192307. p = 0;
  192308. }
  192309. }else{
  192310. p = 0;
  192311. }
  192312. break;
  192313. case '\'':
  192314. p++;
  192315. while( p ){
  192316. if( *p=='\'' ){
  192317. p++;
  192318. if( *p!='\'' ) break;
  192319. }
  192320. p++;
  192321. if( *p==0 ) p = 0;
  192322. }
  192323. break;
  192324. default:
  192325. /* maybe a number */
  192326. if( *p=='+' || *p=='-' ) p++;
  192327. while( fts5_isdigit(*p) ) p++;
  192328. /* At this point, if the literal was an integer, the parse is
  192329. ** finished. Or, if it is a floating point value, it may continue
  192330. ** with either a decimal point or an 'E' character. */
  192331. if( *p=='.' && fts5_isdigit(p[1]) ){
  192332. p += 2;
  192333. while( fts5_isdigit(*p) ) p++;
  192334. }
  192335. if( p==pIn ) p = 0;
  192336. break;
  192337. }
  192338. return p;
  192339. }
  192340. /*
  192341. ** The first character of the string pointed to by argument z is guaranteed
  192342. ** to be an open-quote character (see function fts5_isopenquote()).
  192343. **
  192344. ** This function searches for the corresponding close-quote character within
  192345. ** the string and, if found, dequotes the string in place and adds a new
  192346. ** nul-terminator byte.
  192347. **
  192348. ** If the close-quote is found, the value returned is the byte offset of
  192349. ** the character immediately following it. Or, if the close-quote is not
  192350. ** found, -1 is returned. If -1 is returned, the buffer is left in an
  192351. ** undefined state.
  192352. */
  192353. static int fts5Dequote(char *z){
  192354. char q;
  192355. int iIn = 1;
  192356. int iOut = 0;
  192357. q = z[0];
  192358. /* Set stack variable q to the close-quote character */
  192359. assert( q=='[' || q=='\'' || q=='"' || q=='`' );
  192360. if( q=='[' ) q = ']';
  192361. while( ALWAYS(z[iIn]) ){
  192362. if( z[iIn]==q ){
  192363. if( z[iIn+1]!=q ){
  192364. /* Character iIn was the close quote. */
  192365. iIn++;
  192366. break;
  192367. }else{
  192368. /* Character iIn and iIn+1 form an escaped quote character. Skip
  192369. ** the input cursor past both and copy a single quote character
  192370. ** to the output buffer. */
  192371. iIn += 2;
  192372. z[iOut++] = q;
  192373. }
  192374. }else{
  192375. z[iOut++] = z[iIn++];
  192376. }
  192377. }
  192378. z[iOut] = '\0';
  192379. return iIn;
  192380. }
  192381. /*
  192382. ** Convert an SQL-style quoted string into a normal string by removing
  192383. ** the quote characters. The conversion is done in-place. If the
  192384. ** input does not begin with a quote character, then this routine
  192385. ** is a no-op.
  192386. **
  192387. ** Examples:
  192388. **
  192389. ** "abc" becomes abc
  192390. ** 'xyz' becomes xyz
  192391. ** [pqr] becomes pqr
  192392. ** `mno` becomes mno
  192393. */
  192394. static void sqlite3Fts5Dequote(char *z){
  192395. char quote; /* Quote character (if any ) */
  192396. assert( 0==fts5_iswhitespace(z[0]) );
  192397. quote = z[0];
  192398. if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
  192399. fts5Dequote(z);
  192400. }
  192401. }
  192402. struct Fts5Enum {
  192403. const char *zName;
  192404. int eVal;
  192405. };
  192406. typedef struct Fts5Enum Fts5Enum;
  192407. static int fts5ConfigSetEnum(
  192408. const Fts5Enum *aEnum,
  192409. const char *zEnum,
  192410. int *peVal
  192411. ){
  192412. int nEnum = (int)strlen(zEnum);
  192413. int i;
  192414. int iVal = -1;
  192415. for(i=0; aEnum[i].zName; i++){
  192416. if( sqlite3_strnicmp(aEnum[i].zName, zEnum, nEnum)==0 ){
  192417. if( iVal>=0 ) return SQLITE_ERROR;
  192418. iVal = aEnum[i].eVal;
  192419. }
  192420. }
  192421. *peVal = iVal;
  192422. return iVal<0 ? SQLITE_ERROR : SQLITE_OK;
  192423. }
  192424. /*
  192425. ** Parse a "special" CREATE VIRTUAL TABLE directive and update
  192426. ** configuration object pConfig as appropriate.
  192427. **
  192428. ** If successful, object pConfig is updated and SQLITE_OK returned. If
  192429. ** an error occurs, an SQLite error code is returned and an error message
  192430. ** may be left in *pzErr. It is the responsibility of the caller to
  192431. ** eventually free any such error message using sqlite3_free().
  192432. */
  192433. static int fts5ConfigParseSpecial(
  192434. Fts5Global *pGlobal,
  192435. Fts5Config *pConfig, /* Configuration object to update */
  192436. const char *zCmd, /* Special command to parse */
  192437. const char *zArg, /* Argument to parse */
  192438. char **pzErr /* OUT: Error message */
  192439. ){
  192440. int rc = SQLITE_OK;
  192441. int nCmd = (int)strlen(zCmd);
  192442. if( sqlite3_strnicmp("prefix", zCmd, nCmd)==0 ){
  192443. const int nByte = sizeof(int) * FTS5_MAX_PREFIX_INDEXES;
  192444. const char *p;
  192445. int bFirst = 1;
  192446. if( pConfig->aPrefix==0 ){
  192447. pConfig->aPrefix = sqlite3Fts5MallocZero(&rc, nByte);
  192448. if( rc ) return rc;
  192449. }
  192450. p = zArg;
  192451. while( 1 ){
  192452. int nPre = 0;
  192453. while( p[0]==' ' ) p++;
  192454. if( bFirst==0 && p[0]==',' ){
  192455. p++;
  192456. while( p[0]==' ' ) p++;
  192457. }else if( p[0]=='\0' ){
  192458. break;
  192459. }
  192460. if( p[0]<'0' || p[0]>'9' ){
  192461. *pzErr = sqlite3_mprintf("malformed prefix=... directive");
  192462. rc = SQLITE_ERROR;
  192463. break;
  192464. }
  192465. if( pConfig->nPrefix==FTS5_MAX_PREFIX_INDEXES ){
  192466. *pzErr = sqlite3_mprintf(
  192467. "too many prefix indexes (max %d)", FTS5_MAX_PREFIX_INDEXES
  192468. );
  192469. rc = SQLITE_ERROR;
  192470. break;
  192471. }
  192472. while( p[0]>='0' && p[0]<='9' && nPre<1000 ){
  192473. nPre = nPre*10 + (p[0] - '0');
  192474. p++;
  192475. }
  192476. if( nPre<=0 || nPre>=1000 ){
  192477. *pzErr = sqlite3_mprintf("prefix length out of range (max 999)");
  192478. rc = SQLITE_ERROR;
  192479. break;
  192480. }
  192481. pConfig->aPrefix[pConfig->nPrefix] = nPre;
  192482. pConfig->nPrefix++;
  192483. bFirst = 0;
  192484. }
  192485. assert( pConfig->nPrefix<=FTS5_MAX_PREFIX_INDEXES );
  192486. return rc;
  192487. }
  192488. if( sqlite3_strnicmp("tokenize", zCmd, nCmd)==0 ){
  192489. const char *p = (const char*)zArg;
  192490. sqlite3_int64 nArg = strlen(zArg) + 1;
  192491. char **azArg = sqlite3Fts5MallocZero(&rc, sizeof(char*) * nArg);
  192492. char *pDel = sqlite3Fts5MallocZero(&rc, nArg * 2);
  192493. char *pSpace = pDel;
  192494. if( azArg && pSpace ){
  192495. if( pConfig->pTok ){
  192496. *pzErr = sqlite3_mprintf("multiple tokenize=... directives");
  192497. rc = SQLITE_ERROR;
  192498. }else{
  192499. for(nArg=0; p && *p; nArg++){
  192500. const char *p2 = fts5ConfigSkipWhitespace(p);
  192501. if( *p2=='\'' ){
  192502. p = fts5ConfigSkipLiteral(p2);
  192503. }else{
  192504. p = fts5ConfigSkipBareword(p2);
  192505. }
  192506. if( p ){
  192507. memcpy(pSpace, p2, p-p2);
  192508. azArg[nArg] = pSpace;
  192509. sqlite3Fts5Dequote(pSpace);
  192510. pSpace += (p - p2) + 1;
  192511. p = fts5ConfigSkipWhitespace(p);
  192512. }
  192513. }
  192514. if( p==0 ){
  192515. *pzErr = sqlite3_mprintf("parse error in tokenize directive");
  192516. rc = SQLITE_ERROR;
  192517. }else{
  192518. rc = sqlite3Fts5GetTokenizer(pGlobal,
  192519. (const char**)azArg, (int)nArg, &pConfig->pTok, &pConfig->pTokApi,
  192520. pzErr
  192521. );
  192522. }
  192523. }
  192524. }
  192525. sqlite3_free(azArg);
  192526. sqlite3_free(pDel);
  192527. return rc;
  192528. }
  192529. if( sqlite3_strnicmp("content", zCmd, nCmd)==0 ){
  192530. if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){
  192531. *pzErr = sqlite3_mprintf("multiple content=... directives");
  192532. rc = SQLITE_ERROR;
  192533. }else{
  192534. if( zArg[0] ){
  192535. pConfig->eContent = FTS5_CONTENT_EXTERNAL;
  192536. pConfig->zContent = sqlite3Fts5Mprintf(&rc, "%Q.%Q", pConfig->zDb,zArg);
  192537. }else{
  192538. pConfig->eContent = FTS5_CONTENT_NONE;
  192539. }
  192540. }
  192541. return rc;
  192542. }
  192543. if( sqlite3_strnicmp("content_rowid", zCmd, nCmd)==0 ){
  192544. if( pConfig->zContentRowid ){
  192545. *pzErr = sqlite3_mprintf("multiple content_rowid=... directives");
  192546. rc = SQLITE_ERROR;
  192547. }else{
  192548. pConfig->zContentRowid = sqlite3Fts5Strndup(&rc, zArg, -1);
  192549. }
  192550. return rc;
  192551. }
  192552. if( sqlite3_strnicmp("columnsize", zCmd, nCmd)==0 ){
  192553. if( (zArg[0]!='0' && zArg[0]!='1') || zArg[1]!='\0' ){
  192554. *pzErr = sqlite3_mprintf("malformed columnsize=... directive");
  192555. rc = SQLITE_ERROR;
  192556. }else{
  192557. pConfig->bColumnsize = (zArg[0]=='1');
  192558. }
  192559. return rc;
  192560. }
  192561. if( sqlite3_strnicmp("detail", zCmd, nCmd)==0 ){
  192562. const Fts5Enum aDetail[] = {
  192563. { "none", FTS5_DETAIL_NONE },
  192564. { "full", FTS5_DETAIL_FULL },
  192565. { "columns", FTS5_DETAIL_COLUMNS },
  192566. { 0, 0 }
  192567. };
  192568. if( (rc = fts5ConfigSetEnum(aDetail, zArg, &pConfig->eDetail)) ){
  192569. *pzErr = sqlite3_mprintf("malformed detail=... directive");
  192570. }
  192571. return rc;
  192572. }
  192573. *pzErr = sqlite3_mprintf("unrecognized option: \"%.*s\"", nCmd, zCmd);
  192574. return SQLITE_ERROR;
  192575. }
  192576. /*
  192577. ** Allocate an instance of the default tokenizer ("simple") at
  192578. ** Fts5Config.pTokenizer. Return SQLITE_OK if successful, or an SQLite error
  192579. ** code if an error occurs.
  192580. */
  192581. static int fts5ConfigDefaultTokenizer(Fts5Global *pGlobal, Fts5Config *pConfig){
  192582. assert( pConfig->pTok==0 && pConfig->pTokApi==0 );
  192583. return sqlite3Fts5GetTokenizer(
  192584. pGlobal, 0, 0, &pConfig->pTok, &pConfig->pTokApi, 0
  192585. );
  192586. }
  192587. /*
  192588. ** Gobble up the first bareword or quoted word from the input buffer zIn.
  192589. ** Return a pointer to the character immediately following the last in
  192590. ** the gobbled word if successful, or a NULL pointer otherwise (failed
  192591. ** to find close-quote character).
  192592. **
  192593. ** Before returning, set pzOut to point to a new buffer containing a
  192594. ** nul-terminated, dequoted copy of the gobbled word. If the word was
  192595. ** quoted, *pbQuoted is also set to 1 before returning.
  192596. **
  192597. ** If *pRc is other than SQLITE_OK when this function is called, it is
  192598. ** a no-op (NULL is returned). Otherwise, if an OOM occurs within this
  192599. ** function, *pRc is set to SQLITE_NOMEM before returning. *pRc is *not*
  192600. ** set if a parse error (failed to find close quote) occurs.
  192601. */
  192602. static const char *fts5ConfigGobbleWord(
  192603. int *pRc, /* IN/OUT: Error code */
  192604. const char *zIn, /* Buffer to gobble string/bareword from */
  192605. char **pzOut, /* OUT: malloc'd buffer containing str/bw */
  192606. int *pbQuoted /* OUT: Set to true if dequoting required */
  192607. ){
  192608. const char *zRet = 0;
  192609. sqlite3_int64 nIn = strlen(zIn);
  192610. char *zOut = sqlite3_malloc64(nIn+1);
  192611. assert( *pRc==SQLITE_OK );
  192612. *pbQuoted = 0;
  192613. *pzOut = 0;
  192614. if( zOut==0 ){
  192615. *pRc = SQLITE_NOMEM;
  192616. }else{
  192617. memcpy(zOut, zIn, (size_t)(nIn+1));
  192618. if( fts5_isopenquote(zOut[0]) ){
  192619. int ii = fts5Dequote(zOut);
  192620. zRet = &zIn[ii];
  192621. *pbQuoted = 1;
  192622. }else{
  192623. zRet = fts5ConfigSkipBareword(zIn);
  192624. if( zRet ){
  192625. zOut[zRet-zIn] = '\0';
  192626. }
  192627. }
  192628. }
  192629. if( zRet==0 ){
  192630. sqlite3_free(zOut);
  192631. }else{
  192632. *pzOut = zOut;
  192633. }
  192634. return zRet;
  192635. }
  192636. static int fts5ConfigParseColumn(
  192637. Fts5Config *p,
  192638. char *zCol,
  192639. char *zArg,
  192640. char **pzErr
  192641. ){
  192642. int rc = SQLITE_OK;
  192643. if( 0==sqlite3_stricmp(zCol, FTS5_RANK_NAME)
  192644. || 0==sqlite3_stricmp(zCol, FTS5_ROWID_NAME)
  192645. ){
  192646. *pzErr = sqlite3_mprintf("reserved fts5 column name: %s", zCol);
  192647. rc = SQLITE_ERROR;
  192648. }else if( zArg ){
  192649. if( 0==sqlite3_stricmp(zArg, "unindexed") ){
  192650. p->abUnindexed[p->nCol] = 1;
  192651. }else{
  192652. *pzErr = sqlite3_mprintf("unrecognized column option: %s", zArg);
  192653. rc = SQLITE_ERROR;
  192654. }
  192655. }
  192656. p->azCol[p->nCol++] = zCol;
  192657. return rc;
  192658. }
  192659. /*
  192660. ** Populate the Fts5Config.zContentExprlist string.
  192661. */
  192662. static int fts5ConfigMakeExprlist(Fts5Config *p){
  192663. int i;
  192664. int rc = SQLITE_OK;
  192665. Fts5Buffer buf = {0, 0, 0};
  192666. sqlite3Fts5BufferAppendPrintf(&rc, &buf, "T.%Q", p->zContentRowid);
  192667. if( p->eContent!=FTS5_CONTENT_NONE ){
  192668. for(i=0; i<p->nCol; i++){
  192669. if( p->eContent==FTS5_CONTENT_EXTERNAL ){
  192670. sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.%Q", p->azCol[i]);
  192671. }else{
  192672. sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.c%d", i);
  192673. }
  192674. }
  192675. }
  192676. assert( p->zContentExprlist==0 );
  192677. p->zContentExprlist = (char*)buf.p;
  192678. return rc;
  192679. }
  192680. /*
  192681. ** Arguments nArg/azArg contain the string arguments passed to the xCreate
  192682. ** or xConnect method of the virtual table. This function attempts to
  192683. ** allocate an instance of Fts5Config containing the results of parsing
  192684. ** those arguments.
  192685. **
  192686. ** If successful, SQLITE_OK is returned and *ppOut is set to point to the
  192687. ** new Fts5Config object. If an error occurs, an SQLite error code is
  192688. ** returned, *ppOut is set to NULL and an error message may be left in
  192689. ** *pzErr. It is the responsibility of the caller to eventually free any
  192690. ** such error message using sqlite3_free().
  192691. */
  192692. static int sqlite3Fts5ConfigParse(
  192693. Fts5Global *pGlobal,
  192694. sqlite3 *db,
  192695. int nArg, /* Number of arguments */
  192696. const char **azArg, /* Array of nArg CREATE VIRTUAL TABLE args */
  192697. Fts5Config **ppOut, /* OUT: Results of parse */
  192698. char **pzErr /* OUT: Error message */
  192699. ){
  192700. int rc = SQLITE_OK; /* Return code */
  192701. Fts5Config *pRet; /* New object to return */
  192702. int i;
  192703. sqlite3_int64 nByte;
  192704. *ppOut = pRet = (Fts5Config*)sqlite3_malloc(sizeof(Fts5Config));
  192705. if( pRet==0 ) return SQLITE_NOMEM;
  192706. memset(pRet, 0, sizeof(Fts5Config));
  192707. pRet->db = db;
  192708. pRet->iCookie = -1;
  192709. nByte = nArg * (sizeof(char*) + sizeof(u8));
  192710. pRet->azCol = (char**)sqlite3Fts5MallocZero(&rc, nByte);
  192711. pRet->abUnindexed = (u8*)&pRet->azCol[nArg];
  192712. pRet->zDb = sqlite3Fts5Strndup(&rc, azArg[1], -1);
  192713. pRet->zName = sqlite3Fts5Strndup(&rc, azArg[2], -1);
  192714. pRet->bColumnsize = 1;
  192715. pRet->eDetail = FTS5_DETAIL_FULL;
  192716. #ifdef SQLITE_DEBUG
  192717. pRet->bPrefixIndex = 1;
  192718. #endif
  192719. if( rc==SQLITE_OK && sqlite3_stricmp(pRet->zName, FTS5_RANK_NAME)==0 ){
  192720. *pzErr = sqlite3_mprintf("reserved fts5 table name: %s", pRet->zName);
  192721. rc = SQLITE_ERROR;
  192722. }
  192723. for(i=3; rc==SQLITE_OK && i<nArg; i++){
  192724. const char *zOrig = azArg[i];
  192725. const char *z;
  192726. char *zOne = 0;
  192727. char *zTwo = 0;
  192728. int bOption = 0;
  192729. int bMustBeCol = 0;
  192730. z = fts5ConfigGobbleWord(&rc, zOrig, &zOne, &bMustBeCol);
  192731. z = fts5ConfigSkipWhitespace(z);
  192732. if( z && *z=='=' ){
  192733. bOption = 1;
  192734. z++;
  192735. if( bMustBeCol ) z = 0;
  192736. }
  192737. z = fts5ConfigSkipWhitespace(z);
  192738. if( z && z[0] ){
  192739. int bDummy;
  192740. z = fts5ConfigGobbleWord(&rc, z, &zTwo, &bDummy);
  192741. if( z && z[0] ) z = 0;
  192742. }
  192743. if( rc==SQLITE_OK ){
  192744. if( z==0 ){
  192745. *pzErr = sqlite3_mprintf("parse error in \"%s\"", zOrig);
  192746. rc = SQLITE_ERROR;
  192747. }else{
  192748. if( bOption ){
  192749. rc = fts5ConfigParseSpecial(pGlobal, pRet, zOne, zTwo?zTwo:"", pzErr);
  192750. }else{
  192751. rc = fts5ConfigParseColumn(pRet, zOne, zTwo, pzErr);
  192752. zOne = 0;
  192753. }
  192754. }
  192755. }
  192756. sqlite3_free(zOne);
  192757. sqlite3_free(zTwo);
  192758. }
  192759. /* If a tokenizer= option was successfully parsed, the tokenizer has
  192760. ** already been allocated. Otherwise, allocate an instance of the default
  192761. ** tokenizer (unicode61) now. */
  192762. if( rc==SQLITE_OK && pRet->pTok==0 ){
  192763. rc = fts5ConfigDefaultTokenizer(pGlobal, pRet);
  192764. }
  192765. /* If no zContent option was specified, fill in the default values. */
  192766. if( rc==SQLITE_OK && pRet->zContent==0 ){
  192767. const char *zTail = 0;
  192768. assert( pRet->eContent==FTS5_CONTENT_NORMAL
  192769. || pRet->eContent==FTS5_CONTENT_NONE
  192770. );
  192771. if( pRet->eContent==FTS5_CONTENT_NORMAL ){
  192772. zTail = "content";
  192773. }else if( pRet->bColumnsize ){
  192774. zTail = "docsize";
  192775. }
  192776. if( zTail ){
  192777. pRet->zContent = sqlite3Fts5Mprintf(
  192778. &rc, "%Q.'%q_%s'", pRet->zDb, pRet->zName, zTail
  192779. );
  192780. }
  192781. }
  192782. if( rc==SQLITE_OK && pRet->zContentRowid==0 ){
  192783. pRet->zContentRowid = sqlite3Fts5Strndup(&rc, "rowid", -1);
  192784. }
  192785. /* Formulate the zContentExprlist text */
  192786. if( rc==SQLITE_OK ){
  192787. rc = fts5ConfigMakeExprlist(pRet);
  192788. }
  192789. if( rc!=SQLITE_OK ){
  192790. sqlite3Fts5ConfigFree(pRet);
  192791. *ppOut = 0;
  192792. }
  192793. return rc;
  192794. }
  192795. /*
  192796. ** Free the configuration object passed as the only argument.
  192797. */
  192798. static void sqlite3Fts5ConfigFree(Fts5Config *pConfig){
  192799. if( pConfig ){
  192800. int i;
  192801. if( pConfig->pTok ){
  192802. pConfig->pTokApi->xDelete(pConfig->pTok);
  192803. }
  192804. sqlite3_free(pConfig->zDb);
  192805. sqlite3_free(pConfig->zName);
  192806. for(i=0; i<pConfig->nCol; i++){
  192807. sqlite3_free(pConfig->azCol[i]);
  192808. }
  192809. sqlite3_free(pConfig->azCol);
  192810. sqlite3_free(pConfig->aPrefix);
  192811. sqlite3_free(pConfig->zRank);
  192812. sqlite3_free(pConfig->zRankArgs);
  192813. sqlite3_free(pConfig->zContent);
  192814. sqlite3_free(pConfig->zContentRowid);
  192815. sqlite3_free(pConfig->zContentExprlist);
  192816. sqlite3_free(pConfig);
  192817. }
  192818. }
  192819. /*
  192820. ** Call sqlite3_declare_vtab() based on the contents of the configuration
  192821. ** object passed as the only argument. Return SQLITE_OK if successful, or
  192822. ** an SQLite error code if an error occurs.
  192823. */
  192824. static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig){
  192825. int i;
  192826. int rc = SQLITE_OK;
  192827. char *zSql;
  192828. zSql = sqlite3Fts5Mprintf(&rc, "CREATE TABLE x(");
  192829. for(i=0; zSql && i<pConfig->nCol; i++){
  192830. const char *zSep = (i==0?"":", ");
  192831. zSql = sqlite3Fts5Mprintf(&rc, "%z%s%Q", zSql, zSep, pConfig->azCol[i]);
  192832. }
  192833. zSql = sqlite3Fts5Mprintf(&rc, "%z, %Q HIDDEN, %s HIDDEN)",
  192834. zSql, pConfig->zName, FTS5_RANK_NAME
  192835. );
  192836. assert( zSql || rc==SQLITE_NOMEM );
  192837. if( zSql ){
  192838. rc = sqlite3_declare_vtab(pConfig->db, zSql);
  192839. sqlite3_free(zSql);
  192840. }
  192841. return rc;
  192842. }
  192843. /*
  192844. ** Tokenize the text passed via the second and third arguments.
  192845. **
  192846. ** The callback is invoked once for each token in the input text. The
  192847. ** arguments passed to it are, in order:
  192848. **
  192849. ** void *pCtx // Copy of 4th argument to sqlite3Fts5Tokenize()
  192850. ** const char *pToken // Pointer to buffer containing token
  192851. ** int nToken // Size of token in bytes
  192852. ** int iStart // Byte offset of start of token within input text
  192853. ** int iEnd // Byte offset of end of token within input text
  192854. ** int iPos // Position of token in input (first token is 0)
  192855. **
  192856. ** If the callback returns a non-zero value the tokenization is abandoned
  192857. ** and no further callbacks are issued.
  192858. **
  192859. ** This function returns SQLITE_OK if successful or an SQLite error code
  192860. ** if an error occurs. If the tokenization was abandoned early because
  192861. ** the callback returned SQLITE_DONE, this is not an error and this function
  192862. ** still returns SQLITE_OK. Or, if the tokenization was abandoned early
  192863. ** because the callback returned another non-zero value, it is assumed
  192864. ** to be an SQLite error code and returned to the caller.
  192865. */
  192866. static int sqlite3Fts5Tokenize(
  192867. Fts5Config *pConfig, /* FTS5 Configuration object */
  192868. int flags, /* FTS5_TOKENIZE_* flags */
  192869. const char *pText, int nText, /* Text to tokenize */
  192870. void *pCtx, /* Context passed to xToken() */
  192871. int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
  192872. ){
  192873. if( pText==0 ) return SQLITE_OK;
  192874. return pConfig->pTokApi->xTokenize(
  192875. pConfig->pTok, pCtx, flags, pText, nText, xToken
  192876. );
  192877. }
  192878. /*
  192879. ** Argument pIn points to the first character in what is expected to be
  192880. ** a comma-separated list of SQL literals followed by a ')' character.
  192881. ** If it actually is this, return a pointer to the ')'. Otherwise, return
  192882. ** NULL to indicate a parse error.
  192883. */
  192884. static const char *fts5ConfigSkipArgs(const char *pIn){
  192885. const char *p = pIn;
  192886. while( 1 ){
  192887. p = fts5ConfigSkipWhitespace(p);
  192888. p = fts5ConfigSkipLiteral(p);
  192889. p = fts5ConfigSkipWhitespace(p);
  192890. if( p==0 || *p==')' ) break;
  192891. if( *p!=',' ){
  192892. p = 0;
  192893. break;
  192894. }
  192895. p++;
  192896. }
  192897. return p;
  192898. }
  192899. /*
  192900. ** Parameter zIn contains a rank() function specification. The format of
  192901. ** this is:
  192902. **
  192903. ** + Bareword (function name)
  192904. ** + Open parenthesis - "("
  192905. ** + Zero or more SQL literals in a comma separated list
  192906. ** + Close parenthesis - ")"
  192907. */
  192908. static int sqlite3Fts5ConfigParseRank(
  192909. const char *zIn, /* Input string */
  192910. char **pzRank, /* OUT: Rank function name */
  192911. char **pzRankArgs /* OUT: Rank function arguments */
  192912. ){
  192913. const char *p = zIn;
  192914. const char *pRank;
  192915. char *zRank = 0;
  192916. char *zRankArgs = 0;
  192917. int rc = SQLITE_OK;
  192918. *pzRank = 0;
  192919. *pzRankArgs = 0;
  192920. if( p==0 ){
  192921. rc = SQLITE_ERROR;
  192922. }else{
  192923. p = fts5ConfigSkipWhitespace(p);
  192924. pRank = p;
  192925. p = fts5ConfigSkipBareword(p);
  192926. if( p ){
  192927. zRank = sqlite3Fts5MallocZero(&rc, 1 + p - pRank);
  192928. if( zRank ) memcpy(zRank, pRank, p-pRank);
  192929. }else{
  192930. rc = SQLITE_ERROR;
  192931. }
  192932. if( rc==SQLITE_OK ){
  192933. p = fts5ConfigSkipWhitespace(p);
  192934. if( *p!='(' ) rc = SQLITE_ERROR;
  192935. p++;
  192936. }
  192937. if( rc==SQLITE_OK ){
  192938. const char *pArgs;
  192939. p = fts5ConfigSkipWhitespace(p);
  192940. pArgs = p;
  192941. if( *p!=')' ){
  192942. p = fts5ConfigSkipArgs(p);
  192943. if( p==0 ){
  192944. rc = SQLITE_ERROR;
  192945. }else{
  192946. zRankArgs = sqlite3Fts5MallocZero(&rc, 1 + p - pArgs);
  192947. if( zRankArgs ) memcpy(zRankArgs, pArgs, p-pArgs);
  192948. }
  192949. }
  192950. }
  192951. }
  192952. if( rc!=SQLITE_OK ){
  192953. sqlite3_free(zRank);
  192954. assert( zRankArgs==0 );
  192955. }else{
  192956. *pzRank = zRank;
  192957. *pzRankArgs = zRankArgs;
  192958. }
  192959. return rc;
  192960. }
  192961. static int sqlite3Fts5ConfigSetValue(
  192962. Fts5Config *pConfig,
  192963. const char *zKey,
  192964. sqlite3_value *pVal,
  192965. int *pbBadkey
  192966. ){
  192967. int rc = SQLITE_OK;
  192968. if( 0==sqlite3_stricmp(zKey, "pgsz") ){
  192969. int pgsz = 0;
  192970. if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
  192971. pgsz = sqlite3_value_int(pVal);
  192972. }
  192973. if( pgsz<=0 || pgsz>FTS5_MAX_PAGE_SIZE ){
  192974. *pbBadkey = 1;
  192975. }else{
  192976. pConfig->pgsz = pgsz;
  192977. }
  192978. }
  192979. else if( 0==sqlite3_stricmp(zKey, "hashsize") ){
  192980. int nHashSize = -1;
  192981. if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
  192982. nHashSize = sqlite3_value_int(pVal);
  192983. }
  192984. if( nHashSize<=0 ){
  192985. *pbBadkey = 1;
  192986. }else{
  192987. pConfig->nHashSize = nHashSize;
  192988. }
  192989. }
  192990. else if( 0==sqlite3_stricmp(zKey, "automerge") ){
  192991. int nAutomerge = -1;
  192992. if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
  192993. nAutomerge = sqlite3_value_int(pVal);
  192994. }
  192995. if( nAutomerge<0 || nAutomerge>64 ){
  192996. *pbBadkey = 1;
  192997. }else{
  192998. if( nAutomerge==1 ) nAutomerge = FTS5_DEFAULT_AUTOMERGE;
  192999. pConfig->nAutomerge = nAutomerge;
  193000. }
  193001. }
  193002. else if( 0==sqlite3_stricmp(zKey, "usermerge") ){
  193003. int nUsermerge = -1;
  193004. if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
  193005. nUsermerge = sqlite3_value_int(pVal);
  193006. }
  193007. if( nUsermerge<2 || nUsermerge>16 ){
  193008. *pbBadkey = 1;
  193009. }else{
  193010. pConfig->nUsermerge = nUsermerge;
  193011. }
  193012. }
  193013. else if( 0==sqlite3_stricmp(zKey, "crisismerge") ){
  193014. int nCrisisMerge = -1;
  193015. if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
  193016. nCrisisMerge = sqlite3_value_int(pVal);
  193017. }
  193018. if( nCrisisMerge<0 ){
  193019. *pbBadkey = 1;
  193020. }else{
  193021. if( nCrisisMerge<=1 ) nCrisisMerge = FTS5_DEFAULT_CRISISMERGE;
  193022. pConfig->nCrisisMerge = nCrisisMerge;
  193023. }
  193024. }
  193025. else if( 0==sqlite3_stricmp(zKey, "rank") ){
  193026. const char *zIn = (const char*)sqlite3_value_text(pVal);
  193027. char *zRank;
  193028. char *zRankArgs;
  193029. rc = sqlite3Fts5ConfigParseRank(zIn, &zRank, &zRankArgs);
  193030. if( rc==SQLITE_OK ){
  193031. sqlite3_free(pConfig->zRank);
  193032. sqlite3_free(pConfig->zRankArgs);
  193033. pConfig->zRank = zRank;
  193034. pConfig->zRankArgs = zRankArgs;
  193035. }else if( rc==SQLITE_ERROR ){
  193036. rc = SQLITE_OK;
  193037. *pbBadkey = 1;
  193038. }
  193039. }else{
  193040. *pbBadkey = 1;
  193041. }
  193042. return rc;
  193043. }
  193044. /*
  193045. ** Load the contents of the %_config table into memory.
  193046. */
  193047. static int sqlite3Fts5ConfigLoad(Fts5Config *pConfig, int iCookie){
  193048. const char *zSelect = "SELECT k, v FROM %Q.'%q_config'";
  193049. char *zSql;
  193050. sqlite3_stmt *p = 0;
  193051. int rc = SQLITE_OK;
  193052. int iVersion = 0;
  193053. /* Set default values */
  193054. pConfig->pgsz = FTS5_DEFAULT_PAGE_SIZE;
  193055. pConfig->nAutomerge = FTS5_DEFAULT_AUTOMERGE;
  193056. pConfig->nUsermerge = FTS5_DEFAULT_USERMERGE;
  193057. pConfig->nCrisisMerge = FTS5_DEFAULT_CRISISMERGE;
  193058. pConfig->nHashSize = FTS5_DEFAULT_HASHSIZE;
  193059. zSql = sqlite3Fts5Mprintf(&rc, zSelect, pConfig->zDb, pConfig->zName);
  193060. if( zSql ){
  193061. rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &p, 0);
  193062. sqlite3_free(zSql);
  193063. }
  193064. assert( rc==SQLITE_OK || p==0 );
  193065. if( rc==SQLITE_OK ){
  193066. while( SQLITE_ROW==sqlite3_step(p) ){
  193067. const char *zK = (const char*)sqlite3_column_text(p, 0);
  193068. sqlite3_value *pVal = sqlite3_column_value(p, 1);
  193069. if( 0==sqlite3_stricmp(zK, "version") ){
  193070. iVersion = sqlite3_value_int(pVal);
  193071. }else{
  193072. int bDummy = 0;
  193073. sqlite3Fts5ConfigSetValue(pConfig, zK, pVal, &bDummy);
  193074. }
  193075. }
  193076. rc = sqlite3_finalize(p);
  193077. }
  193078. if( rc==SQLITE_OK && iVersion!=FTS5_CURRENT_VERSION ){
  193079. rc = SQLITE_ERROR;
  193080. if( pConfig->pzErrmsg ){
  193081. assert( 0==*pConfig->pzErrmsg );
  193082. *pConfig->pzErrmsg = sqlite3_mprintf(
  193083. "invalid fts5 file format (found %d, expected %d) - run 'rebuild'",
  193084. iVersion, FTS5_CURRENT_VERSION
  193085. );
  193086. }
  193087. }
  193088. if( rc==SQLITE_OK ){
  193089. pConfig->iCookie = iCookie;
  193090. }
  193091. return rc;
  193092. }
  193093. /*
  193094. ** 2014 May 31
  193095. **
  193096. ** The author disclaims copyright to this source code. In place of
  193097. ** a legal notice, here is a blessing:
  193098. **
  193099. ** May you do good and not evil.
  193100. ** May you find forgiveness for yourself and forgive others.
  193101. ** May you share freely, never taking more than you give.
  193102. **
  193103. ******************************************************************************
  193104. **
  193105. */
  193106. /* #include "fts5Int.h" */
  193107. /* #include "fts5parse.h" */
  193108. /*
  193109. ** All token types in the generated fts5parse.h file are greater than 0.
  193110. */
  193111. #define FTS5_EOF 0
  193112. #define FTS5_LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
  193113. typedef struct Fts5ExprTerm Fts5ExprTerm;
  193114. /*
  193115. ** Functions generated by lemon from fts5parse.y.
  193116. */
  193117. static void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(u64));
  193118. static void sqlite3Fts5ParserFree(void*, void (*freeProc)(void*));
  193119. static void sqlite3Fts5Parser(void*, int, Fts5Token, Fts5Parse*);
  193120. #ifndef NDEBUG
  193121. /* #include <stdio.h> */
  193122. static void sqlite3Fts5ParserTrace(FILE*, char*);
  193123. #endif
  193124. static int sqlite3Fts5ParserFallback(int);
  193125. struct Fts5Expr {
  193126. Fts5Index *pIndex;
  193127. Fts5Config *pConfig;
  193128. Fts5ExprNode *pRoot;
  193129. int bDesc; /* Iterate in descending rowid order */
  193130. int nPhrase; /* Number of phrases in expression */
  193131. Fts5ExprPhrase **apExprPhrase; /* Pointers to phrase objects */
  193132. };
  193133. /*
  193134. ** eType:
  193135. ** Expression node type. Always one of:
  193136. **
  193137. ** FTS5_AND (nChild, apChild valid)
  193138. ** FTS5_OR (nChild, apChild valid)
  193139. ** FTS5_NOT (nChild, apChild valid)
  193140. ** FTS5_STRING (pNear valid)
  193141. ** FTS5_TERM (pNear valid)
  193142. */
  193143. struct Fts5ExprNode {
  193144. int eType; /* Node type */
  193145. int bEof; /* True at EOF */
  193146. int bNomatch; /* True if entry is not a match */
  193147. /* Next method for this node. */
  193148. int (*xNext)(Fts5Expr*, Fts5ExprNode*, int, i64);
  193149. i64 iRowid; /* Current rowid */
  193150. Fts5ExprNearset *pNear; /* For FTS5_STRING - cluster of phrases */
  193151. /* Child nodes. For a NOT node, this array always contains 2 entries. For
  193152. ** AND or OR nodes, it contains 2 or more entries. */
  193153. int nChild; /* Number of child nodes */
  193154. Fts5ExprNode *apChild[1]; /* Array of child nodes */
  193155. };
  193156. #define Fts5NodeIsString(p) ((p)->eType==FTS5_TERM || (p)->eType==FTS5_STRING)
  193157. /*
  193158. ** Invoke the xNext method of an Fts5ExprNode object. This macro should be
  193159. ** used as if it has the same signature as the xNext() methods themselves.
  193160. */
  193161. #define fts5ExprNodeNext(a,b,c,d) (b)->xNext((a), (b), (c), (d))
  193162. /*
  193163. ** An instance of the following structure represents a single search term
  193164. ** or term prefix.
  193165. */
  193166. struct Fts5ExprTerm {
  193167. u8 bPrefix; /* True for a prefix term */
  193168. u8 bFirst; /* True if token must be first in column */
  193169. char *zTerm; /* nul-terminated term */
  193170. Fts5IndexIter *pIter; /* Iterator for this term */
  193171. Fts5ExprTerm *pSynonym; /* Pointer to first in list of synonyms */
  193172. };
  193173. /*
  193174. ** A phrase. One or more terms that must appear in a contiguous sequence
  193175. ** within a document for it to match.
  193176. */
  193177. struct Fts5ExprPhrase {
  193178. Fts5ExprNode *pNode; /* FTS5_STRING node this phrase is part of */
  193179. Fts5Buffer poslist; /* Current position list */
  193180. int nTerm; /* Number of entries in aTerm[] */
  193181. Fts5ExprTerm aTerm[1]; /* Terms that make up this phrase */
  193182. };
  193183. /*
  193184. ** One or more phrases that must appear within a certain token distance of
  193185. ** each other within each matching document.
  193186. */
  193187. struct Fts5ExprNearset {
  193188. int nNear; /* NEAR parameter */
  193189. Fts5Colset *pColset; /* Columns to search (NULL -> all columns) */
  193190. int nPhrase; /* Number of entries in aPhrase[] array */
  193191. Fts5ExprPhrase *apPhrase[1]; /* Array of phrase pointers */
  193192. };
  193193. /*
  193194. ** Parse context.
  193195. */
  193196. struct Fts5Parse {
  193197. Fts5Config *pConfig;
  193198. char *zErr;
  193199. int rc;
  193200. int nPhrase; /* Size of apPhrase array */
  193201. Fts5ExprPhrase **apPhrase; /* Array of all phrases */
  193202. Fts5ExprNode *pExpr; /* Result of a successful parse */
  193203. };
  193204. static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...){
  193205. va_list ap;
  193206. va_start(ap, zFmt);
  193207. if( pParse->rc==SQLITE_OK ){
  193208. pParse->zErr = sqlite3_vmprintf(zFmt, ap);
  193209. pParse->rc = SQLITE_ERROR;
  193210. }
  193211. va_end(ap);
  193212. }
  193213. static int fts5ExprIsspace(char t){
  193214. return t==' ' || t=='\t' || t=='\n' || t=='\r';
  193215. }
  193216. /*
  193217. ** Read the first token from the nul-terminated string at *pz.
  193218. */
  193219. static int fts5ExprGetToken(
  193220. Fts5Parse *pParse,
  193221. const char **pz, /* IN/OUT: Pointer into buffer */
  193222. Fts5Token *pToken
  193223. ){
  193224. const char *z = *pz;
  193225. int tok;
  193226. /* Skip past any whitespace */
  193227. while( fts5ExprIsspace(*z) ) z++;
  193228. pToken->p = z;
  193229. pToken->n = 1;
  193230. switch( *z ){
  193231. case '(': tok = FTS5_LP; break;
  193232. case ')': tok = FTS5_RP; break;
  193233. case '{': tok = FTS5_LCP; break;
  193234. case '}': tok = FTS5_RCP; break;
  193235. case ':': tok = FTS5_COLON; break;
  193236. case ',': tok = FTS5_COMMA; break;
  193237. case '+': tok = FTS5_PLUS; break;
  193238. case '*': tok = FTS5_STAR; break;
  193239. case '-': tok = FTS5_MINUS; break;
  193240. case '^': tok = FTS5_CARET; break;
  193241. case '\0': tok = FTS5_EOF; break;
  193242. case '"': {
  193243. const char *z2;
  193244. tok = FTS5_STRING;
  193245. for(z2=&z[1]; 1; z2++){
  193246. if( z2[0]=='"' ){
  193247. z2++;
  193248. if( z2[0]!='"' ) break;
  193249. }
  193250. if( z2[0]=='\0' ){
  193251. sqlite3Fts5ParseError(pParse, "unterminated string");
  193252. return FTS5_EOF;
  193253. }
  193254. }
  193255. pToken->n = (z2 - z);
  193256. break;
  193257. }
  193258. default: {
  193259. const char *z2;
  193260. if( sqlite3Fts5IsBareword(z[0])==0 ){
  193261. sqlite3Fts5ParseError(pParse, "fts5: syntax error near \"%.1s\"", z);
  193262. return FTS5_EOF;
  193263. }
  193264. tok = FTS5_STRING;
  193265. for(z2=&z[1]; sqlite3Fts5IsBareword(*z2); z2++);
  193266. pToken->n = (z2 - z);
  193267. if( pToken->n==2 && memcmp(pToken->p, "OR", 2)==0 ) tok = FTS5_OR;
  193268. if( pToken->n==3 && memcmp(pToken->p, "NOT", 3)==0 ) tok = FTS5_NOT;
  193269. if( pToken->n==3 && memcmp(pToken->p, "AND", 3)==0 ) tok = FTS5_AND;
  193270. break;
  193271. }
  193272. }
  193273. *pz = &pToken->p[pToken->n];
  193274. return tok;
  193275. }
  193276. static void *fts5ParseAlloc(u64 t){ return sqlite3_malloc64((sqlite3_int64)t);}
  193277. static void fts5ParseFree(void *p){ sqlite3_free(p); }
  193278. static int sqlite3Fts5ExprNew(
  193279. Fts5Config *pConfig, /* FTS5 Configuration */
  193280. int iCol,
  193281. const char *zExpr, /* Expression text */
  193282. Fts5Expr **ppNew,
  193283. char **pzErr
  193284. ){
  193285. Fts5Parse sParse;
  193286. Fts5Token token;
  193287. const char *z = zExpr;
  193288. int t; /* Next token type */
  193289. void *pEngine;
  193290. Fts5Expr *pNew;
  193291. *ppNew = 0;
  193292. *pzErr = 0;
  193293. memset(&sParse, 0, sizeof(sParse));
  193294. pEngine = sqlite3Fts5ParserAlloc(fts5ParseAlloc);
  193295. if( pEngine==0 ){ return SQLITE_NOMEM; }
  193296. sParse.pConfig = pConfig;
  193297. do {
  193298. t = fts5ExprGetToken(&sParse, &z, &token);
  193299. sqlite3Fts5Parser(pEngine, t, token, &sParse);
  193300. }while( sParse.rc==SQLITE_OK && t!=FTS5_EOF );
  193301. sqlite3Fts5ParserFree(pEngine, fts5ParseFree);
  193302. /* If the LHS of the MATCH expression was a user column, apply the
  193303. ** implicit column-filter. */
  193304. if( iCol<pConfig->nCol && sParse.pExpr && sParse.rc==SQLITE_OK ){
  193305. int n = sizeof(Fts5Colset);
  193306. Fts5Colset *pColset = (Fts5Colset*)sqlite3Fts5MallocZero(&sParse.rc, n);
  193307. if( pColset ){
  193308. pColset->nCol = 1;
  193309. pColset->aiCol[0] = iCol;
  193310. sqlite3Fts5ParseSetColset(&sParse, sParse.pExpr, pColset);
  193311. }
  193312. }
  193313. assert( sParse.rc!=SQLITE_OK || sParse.zErr==0 );
  193314. if( sParse.rc==SQLITE_OK ){
  193315. *ppNew = pNew = sqlite3_malloc(sizeof(Fts5Expr));
  193316. if( pNew==0 ){
  193317. sParse.rc = SQLITE_NOMEM;
  193318. sqlite3Fts5ParseNodeFree(sParse.pExpr);
  193319. }else{
  193320. if( !sParse.pExpr ){
  193321. const int nByte = sizeof(Fts5ExprNode);
  193322. pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&sParse.rc, nByte);
  193323. if( pNew->pRoot ){
  193324. pNew->pRoot->bEof = 1;
  193325. }
  193326. }else{
  193327. pNew->pRoot = sParse.pExpr;
  193328. }
  193329. pNew->pIndex = 0;
  193330. pNew->pConfig = pConfig;
  193331. pNew->apExprPhrase = sParse.apPhrase;
  193332. pNew->nPhrase = sParse.nPhrase;
  193333. sParse.apPhrase = 0;
  193334. }
  193335. }else{
  193336. sqlite3Fts5ParseNodeFree(sParse.pExpr);
  193337. }
  193338. sqlite3_free(sParse.apPhrase);
  193339. *pzErr = sParse.zErr;
  193340. return sParse.rc;
  193341. }
  193342. /*
  193343. ** Free the expression node object passed as the only argument.
  193344. */
  193345. static void sqlite3Fts5ParseNodeFree(Fts5ExprNode *p){
  193346. if( p ){
  193347. int i;
  193348. for(i=0; i<p->nChild; i++){
  193349. sqlite3Fts5ParseNodeFree(p->apChild[i]);
  193350. }
  193351. sqlite3Fts5ParseNearsetFree(p->pNear);
  193352. sqlite3_free(p);
  193353. }
  193354. }
  193355. /*
  193356. ** Free the expression object passed as the only argument.
  193357. */
  193358. static void sqlite3Fts5ExprFree(Fts5Expr *p){
  193359. if( p ){
  193360. sqlite3Fts5ParseNodeFree(p->pRoot);
  193361. sqlite3_free(p->apExprPhrase);
  193362. sqlite3_free(p);
  193363. }
  193364. }
  193365. /*
  193366. ** Argument pTerm must be a synonym iterator. Return the current rowid
  193367. ** that it points to.
  193368. */
  193369. static i64 fts5ExprSynonymRowid(Fts5ExprTerm *pTerm, int bDesc, int *pbEof){
  193370. i64 iRet = 0;
  193371. int bRetValid = 0;
  193372. Fts5ExprTerm *p;
  193373. assert( pTerm->pSynonym );
  193374. assert( bDesc==0 || bDesc==1 );
  193375. for(p=pTerm; p; p=p->pSynonym){
  193376. if( 0==sqlite3Fts5IterEof(p->pIter) ){
  193377. i64 iRowid = p->pIter->iRowid;
  193378. if( bRetValid==0 || (bDesc!=(iRowid<iRet)) ){
  193379. iRet = iRowid;
  193380. bRetValid = 1;
  193381. }
  193382. }
  193383. }
  193384. if( pbEof && bRetValid==0 ) *pbEof = 1;
  193385. return iRet;
  193386. }
  193387. /*
  193388. ** Argument pTerm must be a synonym iterator.
  193389. */
  193390. static int fts5ExprSynonymList(
  193391. Fts5ExprTerm *pTerm,
  193392. i64 iRowid,
  193393. Fts5Buffer *pBuf, /* Use this buffer for space if required */
  193394. u8 **pa, int *pn
  193395. ){
  193396. Fts5PoslistReader aStatic[4];
  193397. Fts5PoslistReader *aIter = aStatic;
  193398. int nIter = 0;
  193399. int nAlloc = 4;
  193400. int rc = SQLITE_OK;
  193401. Fts5ExprTerm *p;
  193402. assert( pTerm->pSynonym );
  193403. for(p=pTerm; p; p=p->pSynonym){
  193404. Fts5IndexIter *pIter = p->pIter;
  193405. if( sqlite3Fts5IterEof(pIter)==0 && pIter->iRowid==iRowid ){
  193406. if( pIter->nData==0 ) continue;
  193407. if( nIter==nAlloc ){
  193408. sqlite3_int64 nByte = sizeof(Fts5PoslistReader) * nAlloc * 2;
  193409. Fts5PoslistReader *aNew = (Fts5PoslistReader*)sqlite3_malloc64(nByte);
  193410. if( aNew==0 ){
  193411. rc = SQLITE_NOMEM;
  193412. goto synonym_poslist_out;
  193413. }
  193414. memcpy(aNew, aIter, sizeof(Fts5PoslistReader) * nIter);
  193415. nAlloc = nAlloc*2;
  193416. if( aIter!=aStatic ) sqlite3_free(aIter);
  193417. aIter = aNew;
  193418. }
  193419. sqlite3Fts5PoslistReaderInit(pIter->pData, pIter->nData, &aIter[nIter]);
  193420. assert( aIter[nIter].bEof==0 );
  193421. nIter++;
  193422. }
  193423. }
  193424. if( nIter==1 ){
  193425. *pa = (u8*)aIter[0].a;
  193426. *pn = aIter[0].n;
  193427. }else{
  193428. Fts5PoslistWriter writer = {0};
  193429. i64 iPrev = -1;
  193430. fts5BufferZero(pBuf);
  193431. while( 1 ){
  193432. int i;
  193433. i64 iMin = FTS5_LARGEST_INT64;
  193434. for(i=0; i<nIter; i++){
  193435. if( aIter[i].bEof==0 ){
  193436. if( aIter[i].iPos==iPrev ){
  193437. if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) continue;
  193438. }
  193439. if( aIter[i].iPos<iMin ){
  193440. iMin = aIter[i].iPos;
  193441. }
  193442. }
  193443. }
  193444. if( iMin==FTS5_LARGEST_INT64 || rc!=SQLITE_OK ) break;
  193445. rc = sqlite3Fts5PoslistWriterAppend(pBuf, &writer, iMin);
  193446. iPrev = iMin;
  193447. }
  193448. if( rc==SQLITE_OK ){
  193449. *pa = pBuf->p;
  193450. *pn = pBuf->n;
  193451. }
  193452. }
  193453. synonym_poslist_out:
  193454. if( aIter!=aStatic ) sqlite3_free(aIter);
  193455. return rc;
  193456. }
  193457. /*
  193458. ** All individual term iterators in pPhrase are guaranteed to be valid and
  193459. ** pointing to the same rowid when this function is called. This function
  193460. ** checks if the current rowid really is a match, and if so populates
  193461. ** the pPhrase->poslist buffer accordingly. Output parameter *pbMatch
  193462. ** is set to true if this is really a match, or false otherwise.
  193463. **
  193464. ** SQLITE_OK is returned if an error occurs, or an SQLite error code
  193465. ** otherwise. It is not considered an error code if the current rowid is
  193466. ** not a match.
  193467. */
  193468. static int fts5ExprPhraseIsMatch(
  193469. Fts5ExprNode *pNode, /* Node pPhrase belongs to */
  193470. Fts5ExprPhrase *pPhrase, /* Phrase object to initialize */
  193471. int *pbMatch /* OUT: Set to true if really a match */
  193472. ){
  193473. Fts5PoslistWriter writer = {0};
  193474. Fts5PoslistReader aStatic[4];
  193475. Fts5PoslistReader *aIter = aStatic;
  193476. int i;
  193477. int rc = SQLITE_OK;
  193478. int bFirst = pPhrase->aTerm[0].bFirst;
  193479. fts5BufferZero(&pPhrase->poslist);
  193480. /* If the aStatic[] array is not large enough, allocate a large array
  193481. ** using sqlite3_malloc(). This approach could be improved upon. */
  193482. if( pPhrase->nTerm>ArraySize(aStatic) ){
  193483. sqlite3_int64 nByte = sizeof(Fts5PoslistReader) * pPhrase->nTerm;
  193484. aIter = (Fts5PoslistReader*)sqlite3_malloc64(nByte);
  193485. if( !aIter ) return SQLITE_NOMEM;
  193486. }
  193487. memset(aIter, 0, sizeof(Fts5PoslistReader) * pPhrase->nTerm);
  193488. /* Initialize a term iterator for each term in the phrase */
  193489. for(i=0; i<pPhrase->nTerm; i++){
  193490. Fts5ExprTerm *pTerm = &pPhrase->aTerm[i];
  193491. int n = 0;
  193492. int bFlag = 0;
  193493. u8 *a = 0;
  193494. if( pTerm->pSynonym ){
  193495. Fts5Buffer buf = {0, 0, 0};
  193496. rc = fts5ExprSynonymList(pTerm, pNode->iRowid, &buf, &a, &n);
  193497. if( rc ){
  193498. sqlite3_free(a);
  193499. goto ismatch_out;
  193500. }
  193501. if( a==buf.p ) bFlag = 1;
  193502. }else{
  193503. a = (u8*)pTerm->pIter->pData;
  193504. n = pTerm->pIter->nData;
  193505. }
  193506. sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]);
  193507. aIter[i].bFlag = (u8)bFlag;
  193508. if( aIter[i].bEof ) goto ismatch_out;
  193509. }
  193510. while( 1 ){
  193511. int bMatch;
  193512. i64 iPos = aIter[0].iPos;
  193513. do {
  193514. bMatch = 1;
  193515. for(i=0; i<pPhrase->nTerm; i++){
  193516. Fts5PoslistReader *pPos = &aIter[i];
  193517. i64 iAdj = iPos + i;
  193518. if( pPos->iPos!=iAdj ){
  193519. bMatch = 0;
  193520. while( pPos->iPos<iAdj ){
  193521. if( sqlite3Fts5PoslistReaderNext(pPos) ) goto ismatch_out;
  193522. }
  193523. if( pPos->iPos>iAdj ) iPos = pPos->iPos-i;
  193524. }
  193525. }
  193526. }while( bMatch==0 );
  193527. /* Append position iPos to the output */
  193528. if( bFirst==0 || FTS5_POS2OFFSET(iPos)==0 ){
  193529. rc = sqlite3Fts5PoslistWriterAppend(&pPhrase->poslist, &writer, iPos);
  193530. if( rc!=SQLITE_OK ) goto ismatch_out;
  193531. }
  193532. for(i=0; i<pPhrase->nTerm; i++){
  193533. if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) goto ismatch_out;
  193534. }
  193535. }
  193536. ismatch_out:
  193537. *pbMatch = (pPhrase->poslist.n>0);
  193538. for(i=0; i<pPhrase->nTerm; i++){
  193539. if( aIter[i].bFlag ) sqlite3_free((u8*)aIter[i].a);
  193540. }
  193541. if( aIter!=aStatic ) sqlite3_free(aIter);
  193542. return rc;
  193543. }
  193544. typedef struct Fts5LookaheadReader Fts5LookaheadReader;
  193545. struct Fts5LookaheadReader {
  193546. const u8 *a; /* Buffer containing position list */
  193547. int n; /* Size of buffer a[] in bytes */
  193548. int i; /* Current offset in position list */
  193549. i64 iPos; /* Current position */
  193550. i64 iLookahead; /* Next position */
  193551. };
  193552. #define FTS5_LOOKAHEAD_EOF (((i64)1) << 62)
  193553. static int fts5LookaheadReaderNext(Fts5LookaheadReader *p){
  193554. p->iPos = p->iLookahead;
  193555. if( sqlite3Fts5PoslistNext64(p->a, p->n, &p->i, &p->iLookahead) ){
  193556. p->iLookahead = FTS5_LOOKAHEAD_EOF;
  193557. }
  193558. return (p->iPos==FTS5_LOOKAHEAD_EOF);
  193559. }
  193560. static int fts5LookaheadReaderInit(
  193561. const u8 *a, int n, /* Buffer to read position list from */
  193562. Fts5LookaheadReader *p /* Iterator object to initialize */
  193563. ){
  193564. memset(p, 0, sizeof(Fts5LookaheadReader));
  193565. p->a = a;
  193566. p->n = n;
  193567. fts5LookaheadReaderNext(p);
  193568. return fts5LookaheadReaderNext(p);
  193569. }
  193570. typedef struct Fts5NearTrimmer Fts5NearTrimmer;
  193571. struct Fts5NearTrimmer {
  193572. Fts5LookaheadReader reader; /* Input iterator */
  193573. Fts5PoslistWriter writer; /* Writer context */
  193574. Fts5Buffer *pOut; /* Output poslist */
  193575. };
  193576. /*
  193577. ** The near-set object passed as the first argument contains more than
  193578. ** one phrase. All phrases currently point to the same row. The
  193579. ** Fts5ExprPhrase.poslist buffers are populated accordingly. This function
  193580. ** tests if the current row contains instances of each phrase sufficiently
  193581. ** close together to meet the NEAR constraint. Non-zero is returned if it
  193582. ** does, or zero otherwise.
  193583. **
  193584. ** If in/out parameter (*pRc) is set to other than SQLITE_OK when this
  193585. ** function is called, it is a no-op. Or, if an error (e.g. SQLITE_NOMEM)
  193586. ** occurs within this function (*pRc) is set accordingly before returning.
  193587. ** The return value is undefined in both these cases.
  193588. **
  193589. ** If no error occurs and non-zero (a match) is returned, the position-list
  193590. ** of each phrase object is edited to contain only those entries that
  193591. ** meet the constraint before returning.
  193592. */
  193593. static int fts5ExprNearIsMatch(int *pRc, Fts5ExprNearset *pNear){
  193594. Fts5NearTrimmer aStatic[4];
  193595. Fts5NearTrimmer *a = aStatic;
  193596. Fts5ExprPhrase **apPhrase = pNear->apPhrase;
  193597. int i;
  193598. int rc = *pRc;
  193599. int bMatch;
  193600. assert( pNear->nPhrase>1 );
  193601. /* If the aStatic[] array is not large enough, allocate a large array
  193602. ** using sqlite3_malloc(). This approach could be improved upon. */
  193603. if( pNear->nPhrase>ArraySize(aStatic) ){
  193604. sqlite3_int64 nByte = sizeof(Fts5NearTrimmer) * pNear->nPhrase;
  193605. a = (Fts5NearTrimmer*)sqlite3Fts5MallocZero(&rc, nByte);
  193606. }else{
  193607. memset(aStatic, 0, sizeof(aStatic));
  193608. }
  193609. if( rc!=SQLITE_OK ){
  193610. *pRc = rc;
  193611. return 0;
  193612. }
  193613. /* Initialize a lookahead iterator for each phrase. After passing the
  193614. ** buffer and buffer size to the lookaside-reader init function, zero
  193615. ** the phrase poslist buffer. The new poslist for the phrase (containing
  193616. ** the same entries as the original with some entries removed on account
  193617. ** of the NEAR constraint) is written over the original even as it is
  193618. ** being read. This is safe as the entries for the new poslist are a
  193619. ** subset of the old, so it is not possible for data yet to be read to
  193620. ** be overwritten. */
  193621. for(i=0; i<pNear->nPhrase; i++){
  193622. Fts5Buffer *pPoslist = &apPhrase[i]->poslist;
  193623. fts5LookaheadReaderInit(pPoslist->p, pPoslist->n, &a[i].reader);
  193624. pPoslist->n = 0;
  193625. a[i].pOut = pPoslist;
  193626. }
  193627. while( 1 ){
  193628. int iAdv;
  193629. i64 iMin;
  193630. i64 iMax;
  193631. /* This block advances the phrase iterators until they point to a set of
  193632. ** entries that together comprise a match. */
  193633. iMax = a[0].reader.iPos;
  193634. do {
  193635. bMatch = 1;
  193636. for(i=0; i<pNear->nPhrase; i++){
  193637. Fts5LookaheadReader *pPos = &a[i].reader;
  193638. iMin = iMax - pNear->apPhrase[i]->nTerm - pNear->nNear;
  193639. if( pPos->iPos<iMin || pPos->iPos>iMax ){
  193640. bMatch = 0;
  193641. while( pPos->iPos<iMin ){
  193642. if( fts5LookaheadReaderNext(pPos) ) goto ismatch_out;
  193643. }
  193644. if( pPos->iPos>iMax ) iMax = pPos->iPos;
  193645. }
  193646. }
  193647. }while( bMatch==0 );
  193648. /* Add an entry to each output position list */
  193649. for(i=0; i<pNear->nPhrase; i++){
  193650. i64 iPos = a[i].reader.iPos;
  193651. Fts5PoslistWriter *pWriter = &a[i].writer;
  193652. if( a[i].pOut->n==0 || iPos!=pWriter->iPrev ){
  193653. sqlite3Fts5PoslistWriterAppend(a[i].pOut, pWriter, iPos);
  193654. }
  193655. }
  193656. iAdv = 0;
  193657. iMin = a[0].reader.iLookahead;
  193658. for(i=0; i<pNear->nPhrase; i++){
  193659. if( a[i].reader.iLookahead < iMin ){
  193660. iMin = a[i].reader.iLookahead;
  193661. iAdv = i;
  193662. }
  193663. }
  193664. if( fts5LookaheadReaderNext(&a[iAdv].reader) ) goto ismatch_out;
  193665. }
  193666. ismatch_out: {
  193667. int bRet = a[0].pOut->n>0;
  193668. *pRc = rc;
  193669. if( a!=aStatic ) sqlite3_free(a);
  193670. return bRet;
  193671. }
  193672. }
  193673. /*
  193674. ** Advance iterator pIter until it points to a value equal to or laster
  193675. ** than the initial value of *piLast. If this means the iterator points
  193676. ** to a value laster than *piLast, update *piLast to the new lastest value.
  193677. **
  193678. ** If the iterator reaches EOF, set *pbEof to true before returning. If
  193679. ** an error occurs, set *pRc to an error code. If either *pbEof or *pRc
  193680. ** are set, return a non-zero value. Otherwise, return zero.
  193681. */
  193682. static int fts5ExprAdvanceto(
  193683. Fts5IndexIter *pIter, /* Iterator to advance */
  193684. int bDesc, /* True if iterator is "rowid DESC" */
  193685. i64 *piLast, /* IN/OUT: Lastest rowid seen so far */
  193686. int *pRc, /* OUT: Error code */
  193687. int *pbEof /* OUT: Set to true if EOF */
  193688. ){
  193689. i64 iLast = *piLast;
  193690. i64 iRowid;
  193691. iRowid = pIter->iRowid;
  193692. if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){
  193693. int rc = sqlite3Fts5IterNextFrom(pIter, iLast);
  193694. if( rc || sqlite3Fts5IterEof(pIter) ){
  193695. *pRc = rc;
  193696. *pbEof = 1;
  193697. return 1;
  193698. }
  193699. iRowid = pIter->iRowid;
  193700. assert( (bDesc==0 && iRowid>=iLast) || (bDesc==1 && iRowid<=iLast) );
  193701. }
  193702. *piLast = iRowid;
  193703. return 0;
  193704. }
  193705. static int fts5ExprSynonymAdvanceto(
  193706. Fts5ExprTerm *pTerm, /* Term iterator to advance */
  193707. int bDesc, /* True if iterator is "rowid DESC" */
  193708. i64 *piLast, /* IN/OUT: Lastest rowid seen so far */
  193709. int *pRc /* OUT: Error code */
  193710. ){
  193711. int rc = SQLITE_OK;
  193712. i64 iLast = *piLast;
  193713. Fts5ExprTerm *p;
  193714. int bEof = 0;
  193715. for(p=pTerm; rc==SQLITE_OK && p; p=p->pSynonym){
  193716. if( sqlite3Fts5IterEof(p->pIter)==0 ){
  193717. i64 iRowid = p->pIter->iRowid;
  193718. if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){
  193719. rc = sqlite3Fts5IterNextFrom(p->pIter, iLast);
  193720. }
  193721. }
  193722. }
  193723. if( rc!=SQLITE_OK ){
  193724. *pRc = rc;
  193725. bEof = 1;
  193726. }else{
  193727. *piLast = fts5ExprSynonymRowid(pTerm, bDesc, &bEof);
  193728. }
  193729. return bEof;
  193730. }
  193731. static int fts5ExprNearTest(
  193732. int *pRc,
  193733. Fts5Expr *pExpr, /* Expression that pNear is a part of */
  193734. Fts5ExprNode *pNode /* The "NEAR" node (FTS5_STRING) */
  193735. ){
  193736. Fts5ExprNearset *pNear = pNode->pNear;
  193737. int rc = *pRc;
  193738. if( pExpr->pConfig->eDetail!=FTS5_DETAIL_FULL ){
  193739. Fts5ExprTerm *pTerm;
  193740. Fts5ExprPhrase *pPhrase = pNear->apPhrase[0];
  193741. pPhrase->poslist.n = 0;
  193742. for(pTerm=&pPhrase->aTerm[0]; pTerm; pTerm=pTerm->pSynonym){
  193743. Fts5IndexIter *pIter = pTerm->pIter;
  193744. if( sqlite3Fts5IterEof(pIter)==0 ){
  193745. if( pIter->iRowid==pNode->iRowid && pIter->nData>0 ){
  193746. pPhrase->poslist.n = 1;
  193747. }
  193748. }
  193749. }
  193750. return pPhrase->poslist.n;
  193751. }else{
  193752. int i;
  193753. /* Check that each phrase in the nearset matches the current row.
  193754. ** Populate the pPhrase->poslist buffers at the same time. If any
  193755. ** phrase is not a match, break out of the loop early. */
  193756. for(i=0; rc==SQLITE_OK && i<pNear->nPhrase; i++){
  193757. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  193758. if( pPhrase->nTerm>1 || pPhrase->aTerm[0].pSynonym
  193759. || pNear->pColset || pPhrase->aTerm[0].bFirst
  193760. ){
  193761. int bMatch = 0;
  193762. rc = fts5ExprPhraseIsMatch(pNode, pPhrase, &bMatch);
  193763. if( bMatch==0 ) break;
  193764. }else{
  193765. Fts5IndexIter *pIter = pPhrase->aTerm[0].pIter;
  193766. fts5BufferSet(&rc, &pPhrase->poslist, pIter->nData, pIter->pData);
  193767. }
  193768. }
  193769. *pRc = rc;
  193770. if( i==pNear->nPhrase && (i==1 || fts5ExprNearIsMatch(pRc, pNear)) ){
  193771. return 1;
  193772. }
  193773. return 0;
  193774. }
  193775. }
  193776. /*
  193777. ** Initialize all term iterators in the pNear object. If any term is found
  193778. ** to match no documents at all, return immediately without initializing any
  193779. ** further iterators.
  193780. **
  193781. ** If an error occurs, return an SQLite error code. Otherwise, return
  193782. ** SQLITE_OK. It is not considered an error if some term matches zero
  193783. ** documents.
  193784. */
  193785. static int fts5ExprNearInitAll(
  193786. Fts5Expr *pExpr,
  193787. Fts5ExprNode *pNode
  193788. ){
  193789. Fts5ExprNearset *pNear = pNode->pNear;
  193790. int i;
  193791. assert( pNode->bNomatch==0 );
  193792. for(i=0; i<pNear->nPhrase; i++){
  193793. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  193794. if( pPhrase->nTerm==0 ){
  193795. pNode->bEof = 1;
  193796. return SQLITE_OK;
  193797. }else{
  193798. int j;
  193799. for(j=0; j<pPhrase->nTerm; j++){
  193800. Fts5ExprTerm *pTerm = &pPhrase->aTerm[j];
  193801. Fts5ExprTerm *p;
  193802. int bHit = 0;
  193803. for(p=pTerm; p; p=p->pSynonym){
  193804. int rc;
  193805. if( p->pIter ){
  193806. sqlite3Fts5IterClose(p->pIter);
  193807. p->pIter = 0;
  193808. }
  193809. rc = sqlite3Fts5IndexQuery(
  193810. pExpr->pIndex, p->zTerm, (int)strlen(p->zTerm),
  193811. (pTerm->bPrefix ? FTS5INDEX_QUERY_PREFIX : 0) |
  193812. (pExpr->bDesc ? FTS5INDEX_QUERY_DESC : 0),
  193813. pNear->pColset,
  193814. &p->pIter
  193815. );
  193816. assert( (rc==SQLITE_OK)==(p->pIter!=0) );
  193817. if( rc!=SQLITE_OK ) return rc;
  193818. if( 0==sqlite3Fts5IterEof(p->pIter) ){
  193819. bHit = 1;
  193820. }
  193821. }
  193822. if( bHit==0 ){
  193823. pNode->bEof = 1;
  193824. return SQLITE_OK;
  193825. }
  193826. }
  193827. }
  193828. }
  193829. pNode->bEof = 0;
  193830. return SQLITE_OK;
  193831. }
  193832. /*
  193833. ** If pExpr is an ASC iterator, this function returns a value with the
  193834. ** same sign as:
  193835. **
  193836. ** (iLhs - iRhs)
  193837. **
  193838. ** Otherwise, if this is a DESC iterator, the opposite is returned:
  193839. **
  193840. ** (iRhs - iLhs)
  193841. */
  193842. static int fts5RowidCmp(
  193843. Fts5Expr *pExpr,
  193844. i64 iLhs,
  193845. i64 iRhs
  193846. ){
  193847. assert( pExpr->bDesc==0 || pExpr->bDesc==1 );
  193848. if( pExpr->bDesc==0 ){
  193849. if( iLhs<iRhs ) return -1;
  193850. return (iLhs > iRhs);
  193851. }else{
  193852. if( iLhs>iRhs ) return -1;
  193853. return (iLhs < iRhs);
  193854. }
  193855. }
  193856. static void fts5ExprSetEof(Fts5ExprNode *pNode){
  193857. int i;
  193858. pNode->bEof = 1;
  193859. pNode->bNomatch = 0;
  193860. for(i=0; i<pNode->nChild; i++){
  193861. fts5ExprSetEof(pNode->apChild[i]);
  193862. }
  193863. }
  193864. static void fts5ExprNodeZeroPoslist(Fts5ExprNode *pNode){
  193865. if( pNode->eType==FTS5_STRING || pNode->eType==FTS5_TERM ){
  193866. Fts5ExprNearset *pNear = pNode->pNear;
  193867. int i;
  193868. for(i=0; i<pNear->nPhrase; i++){
  193869. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  193870. pPhrase->poslist.n = 0;
  193871. }
  193872. }else{
  193873. int i;
  193874. for(i=0; i<pNode->nChild; i++){
  193875. fts5ExprNodeZeroPoslist(pNode->apChild[i]);
  193876. }
  193877. }
  193878. }
  193879. /*
  193880. ** Compare the values currently indicated by the two nodes as follows:
  193881. **
  193882. ** res = (*p1) - (*p2)
  193883. **
  193884. ** Nodes that point to values that come later in the iteration order are
  193885. ** considered to be larger. Nodes at EOF are the largest of all.
  193886. **
  193887. ** This means that if the iteration order is ASC, then numerically larger
  193888. ** rowids are considered larger. Or if it is the default DESC, numerically
  193889. ** smaller rowids are larger.
  193890. */
  193891. static int fts5NodeCompare(
  193892. Fts5Expr *pExpr,
  193893. Fts5ExprNode *p1,
  193894. Fts5ExprNode *p2
  193895. ){
  193896. if( p2->bEof ) return -1;
  193897. if( p1->bEof ) return +1;
  193898. return fts5RowidCmp(pExpr, p1->iRowid, p2->iRowid);
  193899. }
  193900. /*
  193901. ** All individual term iterators in pNear are guaranteed to be valid when
  193902. ** this function is called. This function checks if all term iterators
  193903. ** point to the same rowid, and if not, advances them until they do.
  193904. ** If an EOF is reached before this happens, *pbEof is set to true before
  193905. ** returning.
  193906. **
  193907. ** SQLITE_OK is returned if an error occurs, or an SQLite error code
  193908. ** otherwise. It is not considered an error code if an iterator reaches
  193909. ** EOF.
  193910. */
  193911. static int fts5ExprNodeTest_STRING(
  193912. Fts5Expr *pExpr, /* Expression pPhrase belongs to */
  193913. Fts5ExprNode *pNode
  193914. ){
  193915. Fts5ExprNearset *pNear = pNode->pNear;
  193916. Fts5ExprPhrase *pLeft = pNear->apPhrase[0];
  193917. int rc = SQLITE_OK;
  193918. i64 iLast; /* Lastest rowid any iterator points to */
  193919. int i, j; /* Phrase and token index, respectively */
  193920. int bMatch; /* True if all terms are at the same rowid */
  193921. const int bDesc = pExpr->bDesc;
  193922. /* Check that this node should not be FTS5_TERM */
  193923. assert( pNear->nPhrase>1
  193924. || pNear->apPhrase[0]->nTerm>1
  193925. || pNear->apPhrase[0]->aTerm[0].pSynonym
  193926. || pNear->apPhrase[0]->aTerm[0].bFirst
  193927. );
  193928. /* Initialize iLast, the "lastest" rowid any iterator points to. If the
  193929. ** iterator skips through rowids in the default ascending order, this means
  193930. ** the maximum rowid. Or, if the iterator is "ORDER BY rowid DESC", then it
  193931. ** means the minimum rowid. */
  193932. if( pLeft->aTerm[0].pSynonym ){
  193933. iLast = fts5ExprSynonymRowid(&pLeft->aTerm[0], bDesc, 0);
  193934. }else{
  193935. iLast = pLeft->aTerm[0].pIter->iRowid;
  193936. }
  193937. do {
  193938. bMatch = 1;
  193939. for(i=0; i<pNear->nPhrase; i++){
  193940. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  193941. for(j=0; j<pPhrase->nTerm; j++){
  193942. Fts5ExprTerm *pTerm = &pPhrase->aTerm[j];
  193943. if( pTerm->pSynonym ){
  193944. i64 iRowid = fts5ExprSynonymRowid(pTerm, bDesc, 0);
  193945. if( iRowid==iLast ) continue;
  193946. bMatch = 0;
  193947. if( fts5ExprSynonymAdvanceto(pTerm, bDesc, &iLast, &rc) ){
  193948. pNode->bNomatch = 0;
  193949. pNode->bEof = 1;
  193950. return rc;
  193951. }
  193952. }else{
  193953. Fts5IndexIter *pIter = pPhrase->aTerm[j].pIter;
  193954. if( pIter->iRowid==iLast || pIter->bEof ) continue;
  193955. bMatch = 0;
  193956. if( fts5ExprAdvanceto(pIter, bDesc, &iLast, &rc, &pNode->bEof) ){
  193957. return rc;
  193958. }
  193959. }
  193960. }
  193961. }
  193962. }while( bMatch==0 );
  193963. pNode->iRowid = iLast;
  193964. pNode->bNomatch = ((0==fts5ExprNearTest(&rc, pExpr, pNode)) && rc==SQLITE_OK);
  193965. assert( pNode->bEof==0 || pNode->bNomatch==0 );
  193966. return rc;
  193967. }
  193968. /*
  193969. ** Advance the first term iterator in the first phrase of pNear. Set output
  193970. ** variable *pbEof to true if it reaches EOF or if an error occurs.
  193971. **
  193972. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  193973. ** occurs.
  193974. */
  193975. static int fts5ExprNodeNext_STRING(
  193976. Fts5Expr *pExpr, /* Expression pPhrase belongs to */
  193977. Fts5ExprNode *pNode, /* FTS5_STRING or FTS5_TERM node */
  193978. int bFromValid,
  193979. i64 iFrom
  193980. ){
  193981. Fts5ExprTerm *pTerm = &pNode->pNear->apPhrase[0]->aTerm[0];
  193982. int rc = SQLITE_OK;
  193983. pNode->bNomatch = 0;
  193984. if( pTerm->pSynonym ){
  193985. int bEof = 1;
  193986. Fts5ExprTerm *p;
  193987. /* Find the firstest rowid any synonym points to. */
  193988. i64 iRowid = fts5ExprSynonymRowid(pTerm, pExpr->bDesc, 0);
  193989. /* Advance each iterator that currently points to iRowid. Or, if iFrom
  193990. ** is valid - each iterator that points to a rowid before iFrom. */
  193991. for(p=pTerm; p; p=p->pSynonym){
  193992. if( sqlite3Fts5IterEof(p->pIter)==0 ){
  193993. i64 ii = p->pIter->iRowid;
  193994. if( ii==iRowid
  193995. || (bFromValid && ii!=iFrom && (ii>iFrom)==pExpr->bDesc)
  193996. ){
  193997. if( bFromValid ){
  193998. rc = sqlite3Fts5IterNextFrom(p->pIter, iFrom);
  193999. }else{
  194000. rc = sqlite3Fts5IterNext(p->pIter);
  194001. }
  194002. if( rc!=SQLITE_OK ) break;
  194003. if( sqlite3Fts5IterEof(p->pIter)==0 ){
  194004. bEof = 0;
  194005. }
  194006. }else{
  194007. bEof = 0;
  194008. }
  194009. }
  194010. }
  194011. /* Set the EOF flag if either all synonym iterators are at EOF or an
  194012. ** error has occurred. */
  194013. pNode->bEof = (rc || bEof);
  194014. }else{
  194015. Fts5IndexIter *pIter = pTerm->pIter;
  194016. assert( Fts5NodeIsString(pNode) );
  194017. if( bFromValid ){
  194018. rc = sqlite3Fts5IterNextFrom(pIter, iFrom);
  194019. }else{
  194020. rc = sqlite3Fts5IterNext(pIter);
  194021. }
  194022. pNode->bEof = (rc || sqlite3Fts5IterEof(pIter));
  194023. }
  194024. if( pNode->bEof==0 ){
  194025. assert( rc==SQLITE_OK );
  194026. rc = fts5ExprNodeTest_STRING(pExpr, pNode);
  194027. }
  194028. return rc;
  194029. }
  194030. static int fts5ExprNodeTest_TERM(
  194031. Fts5Expr *pExpr, /* Expression that pNear is a part of */
  194032. Fts5ExprNode *pNode /* The "NEAR" node (FTS5_TERM) */
  194033. ){
  194034. /* As this "NEAR" object is actually a single phrase that consists
  194035. ** of a single term only, grab pointers into the poslist managed by the
  194036. ** fts5_index.c iterator object. This is much faster than synthesizing
  194037. ** a new poslist the way we have to for more complicated phrase or NEAR
  194038. ** expressions. */
  194039. Fts5ExprPhrase *pPhrase = pNode->pNear->apPhrase[0];
  194040. Fts5IndexIter *pIter = pPhrase->aTerm[0].pIter;
  194041. assert( pNode->eType==FTS5_TERM );
  194042. assert( pNode->pNear->nPhrase==1 && pPhrase->nTerm==1 );
  194043. assert( pPhrase->aTerm[0].pSynonym==0 );
  194044. pPhrase->poslist.n = pIter->nData;
  194045. if( pExpr->pConfig->eDetail==FTS5_DETAIL_FULL ){
  194046. pPhrase->poslist.p = (u8*)pIter->pData;
  194047. }
  194048. pNode->iRowid = pIter->iRowid;
  194049. pNode->bNomatch = (pPhrase->poslist.n==0);
  194050. return SQLITE_OK;
  194051. }
  194052. /*
  194053. ** xNext() method for a node of type FTS5_TERM.
  194054. */
  194055. static int fts5ExprNodeNext_TERM(
  194056. Fts5Expr *pExpr,
  194057. Fts5ExprNode *pNode,
  194058. int bFromValid,
  194059. i64 iFrom
  194060. ){
  194061. int rc;
  194062. Fts5IndexIter *pIter = pNode->pNear->apPhrase[0]->aTerm[0].pIter;
  194063. assert( pNode->bEof==0 );
  194064. if( bFromValid ){
  194065. rc = sqlite3Fts5IterNextFrom(pIter, iFrom);
  194066. }else{
  194067. rc = sqlite3Fts5IterNext(pIter);
  194068. }
  194069. if( rc==SQLITE_OK && sqlite3Fts5IterEof(pIter)==0 ){
  194070. rc = fts5ExprNodeTest_TERM(pExpr, pNode);
  194071. }else{
  194072. pNode->bEof = 1;
  194073. pNode->bNomatch = 0;
  194074. }
  194075. return rc;
  194076. }
  194077. static void fts5ExprNodeTest_OR(
  194078. Fts5Expr *pExpr, /* Expression of which pNode is a part */
  194079. Fts5ExprNode *pNode /* Expression node to test */
  194080. ){
  194081. Fts5ExprNode *pNext = pNode->apChild[0];
  194082. int i;
  194083. for(i=1; i<pNode->nChild; i++){
  194084. Fts5ExprNode *pChild = pNode->apChild[i];
  194085. int cmp = fts5NodeCompare(pExpr, pNext, pChild);
  194086. if( cmp>0 || (cmp==0 && pChild->bNomatch==0) ){
  194087. pNext = pChild;
  194088. }
  194089. }
  194090. pNode->iRowid = pNext->iRowid;
  194091. pNode->bEof = pNext->bEof;
  194092. pNode->bNomatch = pNext->bNomatch;
  194093. }
  194094. static int fts5ExprNodeNext_OR(
  194095. Fts5Expr *pExpr,
  194096. Fts5ExprNode *pNode,
  194097. int bFromValid,
  194098. i64 iFrom
  194099. ){
  194100. int i;
  194101. i64 iLast = pNode->iRowid;
  194102. for(i=0; i<pNode->nChild; i++){
  194103. Fts5ExprNode *p1 = pNode->apChild[i];
  194104. assert( p1->bEof || fts5RowidCmp(pExpr, p1->iRowid, iLast)>=0 );
  194105. if( p1->bEof==0 ){
  194106. if( (p1->iRowid==iLast)
  194107. || (bFromValid && fts5RowidCmp(pExpr, p1->iRowid, iFrom)<0)
  194108. ){
  194109. int rc = fts5ExprNodeNext(pExpr, p1, bFromValid, iFrom);
  194110. if( rc!=SQLITE_OK ){
  194111. pNode->bNomatch = 0;
  194112. return rc;
  194113. }
  194114. }
  194115. }
  194116. }
  194117. fts5ExprNodeTest_OR(pExpr, pNode);
  194118. return SQLITE_OK;
  194119. }
  194120. /*
  194121. ** Argument pNode is an FTS5_AND node.
  194122. */
  194123. static int fts5ExprNodeTest_AND(
  194124. Fts5Expr *pExpr, /* Expression pPhrase belongs to */
  194125. Fts5ExprNode *pAnd /* FTS5_AND node to advance */
  194126. ){
  194127. int iChild;
  194128. i64 iLast = pAnd->iRowid;
  194129. int rc = SQLITE_OK;
  194130. int bMatch;
  194131. assert( pAnd->bEof==0 );
  194132. do {
  194133. pAnd->bNomatch = 0;
  194134. bMatch = 1;
  194135. for(iChild=0; iChild<pAnd->nChild; iChild++){
  194136. Fts5ExprNode *pChild = pAnd->apChild[iChild];
  194137. int cmp = fts5RowidCmp(pExpr, iLast, pChild->iRowid);
  194138. if( cmp>0 ){
  194139. /* Advance pChild until it points to iLast or laster */
  194140. rc = fts5ExprNodeNext(pExpr, pChild, 1, iLast);
  194141. if( rc!=SQLITE_OK ){
  194142. pAnd->bNomatch = 0;
  194143. return rc;
  194144. }
  194145. }
  194146. /* If the child node is now at EOF, so is the parent AND node. Otherwise,
  194147. ** the child node is guaranteed to have advanced at least as far as
  194148. ** rowid iLast. So if it is not at exactly iLast, pChild->iRowid is the
  194149. ** new lastest rowid seen so far. */
  194150. assert( pChild->bEof || fts5RowidCmp(pExpr, iLast, pChild->iRowid)<=0 );
  194151. if( pChild->bEof ){
  194152. fts5ExprSetEof(pAnd);
  194153. bMatch = 1;
  194154. break;
  194155. }else if( iLast!=pChild->iRowid ){
  194156. bMatch = 0;
  194157. iLast = pChild->iRowid;
  194158. }
  194159. if( pChild->bNomatch ){
  194160. pAnd->bNomatch = 1;
  194161. }
  194162. }
  194163. }while( bMatch==0 );
  194164. if( pAnd->bNomatch && pAnd!=pExpr->pRoot ){
  194165. fts5ExprNodeZeroPoslist(pAnd);
  194166. }
  194167. pAnd->iRowid = iLast;
  194168. return SQLITE_OK;
  194169. }
  194170. static int fts5ExprNodeNext_AND(
  194171. Fts5Expr *pExpr,
  194172. Fts5ExprNode *pNode,
  194173. int bFromValid,
  194174. i64 iFrom
  194175. ){
  194176. int rc = fts5ExprNodeNext(pExpr, pNode->apChild[0], bFromValid, iFrom);
  194177. if( rc==SQLITE_OK ){
  194178. rc = fts5ExprNodeTest_AND(pExpr, pNode);
  194179. }else{
  194180. pNode->bNomatch = 0;
  194181. }
  194182. return rc;
  194183. }
  194184. static int fts5ExprNodeTest_NOT(
  194185. Fts5Expr *pExpr, /* Expression pPhrase belongs to */
  194186. Fts5ExprNode *pNode /* FTS5_NOT node to advance */
  194187. ){
  194188. int rc = SQLITE_OK;
  194189. Fts5ExprNode *p1 = pNode->apChild[0];
  194190. Fts5ExprNode *p2 = pNode->apChild[1];
  194191. assert( pNode->nChild==2 );
  194192. while( rc==SQLITE_OK && p1->bEof==0 ){
  194193. int cmp = fts5NodeCompare(pExpr, p1, p2);
  194194. if( cmp>0 ){
  194195. rc = fts5ExprNodeNext(pExpr, p2, 1, p1->iRowid);
  194196. cmp = fts5NodeCompare(pExpr, p1, p2);
  194197. }
  194198. assert( rc!=SQLITE_OK || cmp<=0 );
  194199. if( cmp || p2->bNomatch ) break;
  194200. rc = fts5ExprNodeNext(pExpr, p1, 0, 0);
  194201. }
  194202. pNode->bEof = p1->bEof;
  194203. pNode->bNomatch = p1->bNomatch;
  194204. pNode->iRowid = p1->iRowid;
  194205. if( p1->bEof ){
  194206. fts5ExprNodeZeroPoslist(p2);
  194207. }
  194208. return rc;
  194209. }
  194210. static int fts5ExprNodeNext_NOT(
  194211. Fts5Expr *pExpr,
  194212. Fts5ExprNode *pNode,
  194213. int bFromValid,
  194214. i64 iFrom
  194215. ){
  194216. int rc = fts5ExprNodeNext(pExpr, pNode->apChild[0], bFromValid, iFrom);
  194217. if( rc==SQLITE_OK ){
  194218. rc = fts5ExprNodeTest_NOT(pExpr, pNode);
  194219. }
  194220. if( rc!=SQLITE_OK ){
  194221. pNode->bNomatch = 0;
  194222. }
  194223. return rc;
  194224. }
  194225. /*
  194226. ** If pNode currently points to a match, this function returns SQLITE_OK
  194227. ** without modifying it. Otherwise, pNode is advanced until it does point
  194228. ** to a match or EOF is reached.
  194229. */
  194230. static int fts5ExprNodeTest(
  194231. Fts5Expr *pExpr, /* Expression of which pNode is a part */
  194232. Fts5ExprNode *pNode /* Expression node to test */
  194233. ){
  194234. int rc = SQLITE_OK;
  194235. if( pNode->bEof==0 ){
  194236. switch( pNode->eType ){
  194237. case FTS5_STRING: {
  194238. rc = fts5ExprNodeTest_STRING(pExpr, pNode);
  194239. break;
  194240. }
  194241. case FTS5_TERM: {
  194242. rc = fts5ExprNodeTest_TERM(pExpr, pNode);
  194243. break;
  194244. }
  194245. case FTS5_AND: {
  194246. rc = fts5ExprNodeTest_AND(pExpr, pNode);
  194247. break;
  194248. }
  194249. case FTS5_OR: {
  194250. fts5ExprNodeTest_OR(pExpr, pNode);
  194251. break;
  194252. }
  194253. default: assert( pNode->eType==FTS5_NOT ); {
  194254. rc = fts5ExprNodeTest_NOT(pExpr, pNode);
  194255. break;
  194256. }
  194257. }
  194258. }
  194259. return rc;
  194260. }
  194261. /*
  194262. ** Set node pNode, which is part of expression pExpr, to point to the first
  194263. ** match. If there are no matches, set the Node.bEof flag to indicate EOF.
  194264. **
  194265. ** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
  194266. ** It is not an error if there are no matches.
  194267. */
  194268. static int fts5ExprNodeFirst(Fts5Expr *pExpr, Fts5ExprNode *pNode){
  194269. int rc = SQLITE_OK;
  194270. pNode->bEof = 0;
  194271. pNode->bNomatch = 0;
  194272. if( Fts5NodeIsString(pNode) ){
  194273. /* Initialize all term iterators in the NEAR object. */
  194274. rc = fts5ExprNearInitAll(pExpr, pNode);
  194275. }else if( pNode->xNext==0 ){
  194276. pNode->bEof = 1;
  194277. }else{
  194278. int i;
  194279. int nEof = 0;
  194280. for(i=0; i<pNode->nChild && rc==SQLITE_OK; i++){
  194281. Fts5ExprNode *pChild = pNode->apChild[i];
  194282. rc = fts5ExprNodeFirst(pExpr, pNode->apChild[i]);
  194283. assert( pChild->bEof==0 || pChild->bEof==1 );
  194284. nEof += pChild->bEof;
  194285. }
  194286. pNode->iRowid = pNode->apChild[0]->iRowid;
  194287. switch( pNode->eType ){
  194288. case FTS5_AND:
  194289. if( nEof>0 ) fts5ExprSetEof(pNode);
  194290. break;
  194291. case FTS5_OR:
  194292. if( pNode->nChild==nEof ) fts5ExprSetEof(pNode);
  194293. break;
  194294. default:
  194295. assert( pNode->eType==FTS5_NOT );
  194296. pNode->bEof = pNode->apChild[0]->bEof;
  194297. break;
  194298. }
  194299. }
  194300. if( rc==SQLITE_OK ){
  194301. rc = fts5ExprNodeTest(pExpr, pNode);
  194302. }
  194303. return rc;
  194304. }
  194305. /*
  194306. ** Begin iterating through the set of documents in index pIdx matched by
  194307. ** the MATCH expression passed as the first argument. If the "bDesc"
  194308. ** parameter is passed a non-zero value, iteration is in descending rowid
  194309. ** order. Or, if it is zero, in ascending order.
  194310. **
  194311. ** If iterating in ascending rowid order (bDesc==0), the first document
  194312. ** visited is that with the smallest rowid that is larger than or equal
  194313. ** to parameter iFirst. Or, if iterating in ascending order (bDesc==1),
  194314. ** then the first document visited must have a rowid smaller than or
  194315. ** equal to iFirst.
  194316. **
  194317. ** Return SQLITE_OK if successful, or an SQLite error code otherwise. It
  194318. ** is not considered an error if the query does not match any documents.
  194319. */
  194320. static int sqlite3Fts5ExprFirst(Fts5Expr *p, Fts5Index *pIdx, i64 iFirst, int bDesc){
  194321. Fts5ExprNode *pRoot = p->pRoot;
  194322. int rc; /* Return code */
  194323. p->pIndex = pIdx;
  194324. p->bDesc = bDesc;
  194325. rc = fts5ExprNodeFirst(p, pRoot);
  194326. /* If not at EOF but the current rowid occurs earlier than iFirst in
  194327. ** the iteration order, move to document iFirst or later. */
  194328. if( rc==SQLITE_OK
  194329. && 0==pRoot->bEof
  194330. && fts5RowidCmp(p, pRoot->iRowid, iFirst)<0
  194331. ){
  194332. rc = fts5ExprNodeNext(p, pRoot, 1, iFirst);
  194333. }
  194334. /* If the iterator is not at a real match, skip forward until it is. */
  194335. while( pRoot->bNomatch ){
  194336. assert( pRoot->bEof==0 && rc==SQLITE_OK );
  194337. rc = fts5ExprNodeNext(p, pRoot, 0, 0);
  194338. }
  194339. return rc;
  194340. }
  194341. /*
  194342. ** Move to the next document
  194343. **
  194344. ** Return SQLITE_OK if successful, or an SQLite error code otherwise. It
  194345. ** is not considered an error if the query does not match any documents.
  194346. */
  194347. static int sqlite3Fts5ExprNext(Fts5Expr *p, i64 iLast){
  194348. int rc;
  194349. Fts5ExprNode *pRoot = p->pRoot;
  194350. assert( pRoot->bEof==0 && pRoot->bNomatch==0 );
  194351. do {
  194352. rc = fts5ExprNodeNext(p, pRoot, 0, 0);
  194353. assert( pRoot->bNomatch==0 || (rc==SQLITE_OK && pRoot->bEof==0) );
  194354. }while( pRoot->bNomatch );
  194355. if( fts5RowidCmp(p, pRoot->iRowid, iLast)>0 ){
  194356. pRoot->bEof = 1;
  194357. }
  194358. return rc;
  194359. }
  194360. static int sqlite3Fts5ExprEof(Fts5Expr *p){
  194361. return p->pRoot->bEof;
  194362. }
  194363. static i64 sqlite3Fts5ExprRowid(Fts5Expr *p){
  194364. return p->pRoot->iRowid;
  194365. }
  194366. static int fts5ParseStringFromToken(Fts5Token *pToken, char **pz){
  194367. int rc = SQLITE_OK;
  194368. *pz = sqlite3Fts5Strndup(&rc, pToken->p, pToken->n);
  194369. return rc;
  194370. }
  194371. /*
  194372. ** Free the phrase object passed as the only argument.
  194373. */
  194374. static void fts5ExprPhraseFree(Fts5ExprPhrase *pPhrase){
  194375. if( pPhrase ){
  194376. int i;
  194377. for(i=0; i<pPhrase->nTerm; i++){
  194378. Fts5ExprTerm *pSyn;
  194379. Fts5ExprTerm *pNext;
  194380. Fts5ExprTerm *pTerm = &pPhrase->aTerm[i];
  194381. sqlite3_free(pTerm->zTerm);
  194382. sqlite3Fts5IterClose(pTerm->pIter);
  194383. for(pSyn=pTerm->pSynonym; pSyn; pSyn=pNext){
  194384. pNext = pSyn->pSynonym;
  194385. sqlite3Fts5IterClose(pSyn->pIter);
  194386. fts5BufferFree((Fts5Buffer*)&pSyn[1]);
  194387. sqlite3_free(pSyn);
  194388. }
  194389. }
  194390. if( pPhrase->poslist.nSpace>0 ) fts5BufferFree(&pPhrase->poslist);
  194391. sqlite3_free(pPhrase);
  194392. }
  194393. }
  194394. /*
  194395. ** Set the "bFirst" flag on the first token of the phrase passed as the
  194396. ** only argument.
  194397. */
  194398. static void sqlite3Fts5ParseSetCaret(Fts5ExprPhrase *pPhrase){
  194399. if( pPhrase && pPhrase->nTerm ){
  194400. pPhrase->aTerm[0].bFirst = 1;
  194401. }
  194402. }
  194403. /*
  194404. ** If argument pNear is NULL, then a new Fts5ExprNearset object is allocated
  194405. ** and populated with pPhrase. Or, if pNear is not NULL, phrase pPhrase is
  194406. ** appended to it and the results returned.
  194407. **
  194408. ** If an OOM error occurs, both the pNear and pPhrase objects are freed and
  194409. ** NULL returned.
  194410. */
  194411. static Fts5ExprNearset *sqlite3Fts5ParseNearset(
  194412. Fts5Parse *pParse, /* Parse context */
  194413. Fts5ExprNearset *pNear, /* Existing nearset, or NULL */
  194414. Fts5ExprPhrase *pPhrase /* Recently parsed phrase */
  194415. ){
  194416. const int SZALLOC = 8;
  194417. Fts5ExprNearset *pRet = 0;
  194418. if( pParse->rc==SQLITE_OK ){
  194419. if( pPhrase==0 ){
  194420. return pNear;
  194421. }
  194422. if( pNear==0 ){
  194423. sqlite3_int64 nByte;
  194424. nByte = sizeof(Fts5ExprNearset) + SZALLOC * sizeof(Fts5ExprPhrase*);
  194425. pRet = sqlite3_malloc64(nByte);
  194426. if( pRet==0 ){
  194427. pParse->rc = SQLITE_NOMEM;
  194428. }else{
  194429. memset(pRet, 0, (size_t)nByte);
  194430. }
  194431. }else if( (pNear->nPhrase % SZALLOC)==0 ){
  194432. int nNew = pNear->nPhrase + SZALLOC;
  194433. sqlite3_int64 nByte;
  194434. nByte = sizeof(Fts5ExprNearset) + nNew * sizeof(Fts5ExprPhrase*);
  194435. pRet = (Fts5ExprNearset*)sqlite3_realloc64(pNear, nByte);
  194436. if( pRet==0 ){
  194437. pParse->rc = SQLITE_NOMEM;
  194438. }
  194439. }else{
  194440. pRet = pNear;
  194441. }
  194442. }
  194443. if( pRet==0 ){
  194444. assert( pParse->rc!=SQLITE_OK );
  194445. sqlite3Fts5ParseNearsetFree(pNear);
  194446. sqlite3Fts5ParsePhraseFree(pPhrase);
  194447. }else{
  194448. if( pRet->nPhrase>0 ){
  194449. Fts5ExprPhrase *pLast = pRet->apPhrase[pRet->nPhrase-1];
  194450. assert( pLast==pParse->apPhrase[pParse->nPhrase-2] );
  194451. if( pPhrase->nTerm==0 ){
  194452. fts5ExprPhraseFree(pPhrase);
  194453. pRet->nPhrase--;
  194454. pParse->nPhrase--;
  194455. pPhrase = pLast;
  194456. }else if( pLast->nTerm==0 ){
  194457. fts5ExprPhraseFree(pLast);
  194458. pParse->apPhrase[pParse->nPhrase-2] = pPhrase;
  194459. pParse->nPhrase--;
  194460. pRet->nPhrase--;
  194461. }
  194462. }
  194463. pRet->apPhrase[pRet->nPhrase++] = pPhrase;
  194464. }
  194465. return pRet;
  194466. }
  194467. typedef struct TokenCtx TokenCtx;
  194468. struct TokenCtx {
  194469. Fts5ExprPhrase *pPhrase;
  194470. int rc;
  194471. };
  194472. /*
  194473. ** Callback for tokenizing terms used by ParseTerm().
  194474. */
  194475. static int fts5ParseTokenize(
  194476. void *pContext, /* Pointer to Fts5InsertCtx object */
  194477. int tflags, /* Mask of FTS5_TOKEN_* flags */
  194478. const char *pToken, /* Buffer containing token */
  194479. int nToken, /* Size of token in bytes */
  194480. int iUnused1, /* Start offset of token */
  194481. int iUnused2 /* End offset of token */
  194482. ){
  194483. int rc = SQLITE_OK;
  194484. const int SZALLOC = 8;
  194485. TokenCtx *pCtx = (TokenCtx*)pContext;
  194486. Fts5ExprPhrase *pPhrase = pCtx->pPhrase;
  194487. UNUSED_PARAM2(iUnused1, iUnused2);
  194488. /* If an error has already occurred, this is a no-op */
  194489. if( pCtx->rc!=SQLITE_OK ) return pCtx->rc;
  194490. if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
  194491. if( pPhrase && pPhrase->nTerm>0 && (tflags & FTS5_TOKEN_COLOCATED) ){
  194492. Fts5ExprTerm *pSyn;
  194493. sqlite3_int64 nByte = sizeof(Fts5ExprTerm) + sizeof(Fts5Buffer) + nToken+1;
  194494. pSyn = (Fts5ExprTerm*)sqlite3_malloc64(nByte);
  194495. if( pSyn==0 ){
  194496. rc = SQLITE_NOMEM;
  194497. }else{
  194498. memset(pSyn, 0, (size_t)nByte);
  194499. pSyn->zTerm = ((char*)pSyn) + sizeof(Fts5ExprTerm) + sizeof(Fts5Buffer);
  194500. memcpy(pSyn->zTerm, pToken, nToken);
  194501. pSyn->pSynonym = pPhrase->aTerm[pPhrase->nTerm-1].pSynonym;
  194502. pPhrase->aTerm[pPhrase->nTerm-1].pSynonym = pSyn;
  194503. }
  194504. }else{
  194505. Fts5ExprTerm *pTerm;
  194506. if( pPhrase==0 || (pPhrase->nTerm % SZALLOC)==0 ){
  194507. Fts5ExprPhrase *pNew;
  194508. int nNew = SZALLOC + (pPhrase ? pPhrase->nTerm : 0);
  194509. pNew = (Fts5ExprPhrase*)sqlite3_realloc64(pPhrase,
  194510. sizeof(Fts5ExprPhrase) + sizeof(Fts5ExprTerm) * nNew
  194511. );
  194512. if( pNew==0 ){
  194513. rc = SQLITE_NOMEM;
  194514. }else{
  194515. if( pPhrase==0 ) memset(pNew, 0, sizeof(Fts5ExprPhrase));
  194516. pCtx->pPhrase = pPhrase = pNew;
  194517. pNew->nTerm = nNew - SZALLOC;
  194518. }
  194519. }
  194520. if( rc==SQLITE_OK ){
  194521. pTerm = &pPhrase->aTerm[pPhrase->nTerm++];
  194522. memset(pTerm, 0, sizeof(Fts5ExprTerm));
  194523. pTerm->zTerm = sqlite3Fts5Strndup(&rc, pToken, nToken);
  194524. }
  194525. }
  194526. pCtx->rc = rc;
  194527. return rc;
  194528. }
  194529. /*
  194530. ** Free the phrase object passed as the only argument.
  194531. */
  194532. static void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase *pPhrase){
  194533. fts5ExprPhraseFree(pPhrase);
  194534. }
  194535. /*
  194536. ** Free the phrase object passed as the second argument.
  194537. */
  194538. static void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset *pNear){
  194539. if( pNear ){
  194540. int i;
  194541. for(i=0; i<pNear->nPhrase; i++){
  194542. fts5ExprPhraseFree(pNear->apPhrase[i]);
  194543. }
  194544. sqlite3_free(pNear->pColset);
  194545. sqlite3_free(pNear);
  194546. }
  194547. }
  194548. static void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p){
  194549. assert( pParse->pExpr==0 );
  194550. pParse->pExpr = p;
  194551. }
  194552. /*
  194553. ** This function is called by the parser to process a string token. The
  194554. ** string may or may not be quoted. In any case it is tokenized and a
  194555. ** phrase object consisting of all tokens returned.
  194556. */
  194557. static Fts5ExprPhrase *sqlite3Fts5ParseTerm(
  194558. Fts5Parse *pParse, /* Parse context */
  194559. Fts5ExprPhrase *pAppend, /* Phrase to append to */
  194560. Fts5Token *pToken, /* String to tokenize */
  194561. int bPrefix /* True if there is a trailing "*" */
  194562. ){
  194563. Fts5Config *pConfig = pParse->pConfig;
  194564. TokenCtx sCtx; /* Context object passed to callback */
  194565. int rc; /* Tokenize return code */
  194566. char *z = 0;
  194567. memset(&sCtx, 0, sizeof(TokenCtx));
  194568. sCtx.pPhrase = pAppend;
  194569. rc = fts5ParseStringFromToken(pToken, &z);
  194570. if( rc==SQLITE_OK ){
  194571. int flags = FTS5_TOKENIZE_QUERY | (bPrefix ? FTS5_TOKENIZE_PREFIX : 0);
  194572. int n;
  194573. sqlite3Fts5Dequote(z);
  194574. n = (int)strlen(z);
  194575. rc = sqlite3Fts5Tokenize(pConfig, flags, z, n, &sCtx, fts5ParseTokenize);
  194576. }
  194577. sqlite3_free(z);
  194578. if( rc || (rc = sCtx.rc) ){
  194579. pParse->rc = rc;
  194580. fts5ExprPhraseFree(sCtx.pPhrase);
  194581. sCtx.pPhrase = 0;
  194582. }else{
  194583. if( pAppend==0 ){
  194584. if( (pParse->nPhrase % 8)==0 ){
  194585. sqlite3_int64 nByte = sizeof(Fts5ExprPhrase*) * (pParse->nPhrase + 8);
  194586. Fts5ExprPhrase **apNew;
  194587. apNew = (Fts5ExprPhrase**)sqlite3_realloc64(pParse->apPhrase, nByte);
  194588. if( apNew==0 ){
  194589. pParse->rc = SQLITE_NOMEM;
  194590. fts5ExprPhraseFree(sCtx.pPhrase);
  194591. return 0;
  194592. }
  194593. pParse->apPhrase = apNew;
  194594. }
  194595. pParse->nPhrase++;
  194596. }
  194597. if( sCtx.pPhrase==0 ){
  194598. /* This happens when parsing a token or quoted phrase that contains
  194599. ** no token characters at all. (e.g ... MATCH '""'). */
  194600. sCtx.pPhrase = sqlite3Fts5MallocZero(&pParse->rc, sizeof(Fts5ExprPhrase));
  194601. }else if( sCtx.pPhrase->nTerm ){
  194602. sCtx.pPhrase->aTerm[sCtx.pPhrase->nTerm-1].bPrefix = (u8)bPrefix;
  194603. }
  194604. pParse->apPhrase[pParse->nPhrase-1] = sCtx.pPhrase;
  194605. }
  194606. return sCtx.pPhrase;
  194607. }
  194608. /*
  194609. ** Create a new FTS5 expression by cloning phrase iPhrase of the
  194610. ** expression passed as the second argument.
  194611. */
  194612. static int sqlite3Fts5ExprClonePhrase(
  194613. Fts5Expr *pExpr,
  194614. int iPhrase,
  194615. Fts5Expr **ppNew
  194616. ){
  194617. int rc = SQLITE_OK; /* Return code */
  194618. Fts5ExprPhrase *pOrig; /* The phrase extracted from pExpr */
  194619. Fts5Expr *pNew = 0; /* Expression to return via *ppNew */
  194620. TokenCtx sCtx = {0,0}; /* Context object for fts5ParseTokenize */
  194621. pOrig = pExpr->apExprPhrase[iPhrase];
  194622. pNew = (Fts5Expr*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Expr));
  194623. if( rc==SQLITE_OK ){
  194624. pNew->apExprPhrase = (Fts5ExprPhrase**)sqlite3Fts5MallocZero(&rc,
  194625. sizeof(Fts5ExprPhrase*));
  194626. }
  194627. if( rc==SQLITE_OK ){
  194628. pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&rc,
  194629. sizeof(Fts5ExprNode));
  194630. }
  194631. if( rc==SQLITE_OK ){
  194632. pNew->pRoot->pNear = (Fts5ExprNearset*)sqlite3Fts5MallocZero(&rc,
  194633. sizeof(Fts5ExprNearset) + sizeof(Fts5ExprPhrase*));
  194634. }
  194635. if( rc==SQLITE_OK ){
  194636. Fts5Colset *pColsetOrig = pOrig->pNode->pNear->pColset;
  194637. if( pColsetOrig ){
  194638. sqlite3_int64 nByte;
  194639. Fts5Colset *pColset;
  194640. nByte = sizeof(Fts5Colset) + (pColsetOrig->nCol-1) * sizeof(int);
  194641. pColset = (Fts5Colset*)sqlite3Fts5MallocZero(&rc, nByte);
  194642. if( pColset ){
  194643. memcpy(pColset, pColsetOrig, (size_t)nByte);
  194644. }
  194645. pNew->pRoot->pNear->pColset = pColset;
  194646. }
  194647. }
  194648. if( pOrig->nTerm ){
  194649. int i; /* Used to iterate through phrase terms */
  194650. for(i=0; rc==SQLITE_OK && i<pOrig->nTerm; i++){
  194651. int tflags = 0;
  194652. Fts5ExprTerm *p;
  194653. for(p=&pOrig->aTerm[i]; p && rc==SQLITE_OK; p=p->pSynonym){
  194654. const char *zTerm = p->zTerm;
  194655. rc = fts5ParseTokenize((void*)&sCtx, tflags, zTerm, (int)strlen(zTerm),
  194656. 0, 0);
  194657. tflags = FTS5_TOKEN_COLOCATED;
  194658. }
  194659. if( rc==SQLITE_OK ){
  194660. sCtx.pPhrase->aTerm[i].bPrefix = pOrig->aTerm[i].bPrefix;
  194661. sCtx.pPhrase->aTerm[i].bFirst = pOrig->aTerm[i].bFirst;
  194662. }
  194663. }
  194664. }else{
  194665. /* This happens when parsing a token or quoted phrase that contains
  194666. ** no token characters at all. (e.g ... MATCH '""'). */
  194667. sCtx.pPhrase = sqlite3Fts5MallocZero(&rc, sizeof(Fts5ExprPhrase));
  194668. }
  194669. if( rc==SQLITE_OK ){
  194670. /* All the allocations succeeded. Put the expression object together. */
  194671. pNew->pIndex = pExpr->pIndex;
  194672. pNew->pConfig = pExpr->pConfig;
  194673. pNew->nPhrase = 1;
  194674. pNew->apExprPhrase[0] = sCtx.pPhrase;
  194675. pNew->pRoot->pNear->apPhrase[0] = sCtx.pPhrase;
  194676. pNew->pRoot->pNear->nPhrase = 1;
  194677. sCtx.pPhrase->pNode = pNew->pRoot;
  194678. if( pOrig->nTerm==1
  194679. && pOrig->aTerm[0].pSynonym==0
  194680. && pOrig->aTerm[0].bFirst==0
  194681. ){
  194682. pNew->pRoot->eType = FTS5_TERM;
  194683. pNew->pRoot->xNext = fts5ExprNodeNext_TERM;
  194684. }else{
  194685. pNew->pRoot->eType = FTS5_STRING;
  194686. pNew->pRoot->xNext = fts5ExprNodeNext_STRING;
  194687. }
  194688. }else{
  194689. sqlite3Fts5ExprFree(pNew);
  194690. fts5ExprPhraseFree(sCtx.pPhrase);
  194691. pNew = 0;
  194692. }
  194693. *ppNew = pNew;
  194694. return rc;
  194695. }
  194696. /*
  194697. ** Token pTok has appeared in a MATCH expression where the NEAR operator
  194698. ** is expected. If token pTok does not contain "NEAR", store an error
  194699. ** in the pParse object.
  194700. */
  194701. static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token *pTok){
  194702. if( pTok->n!=4 || memcmp("NEAR", pTok->p, 4) ){
  194703. sqlite3Fts5ParseError(
  194704. pParse, "fts5: syntax error near \"%.*s\"", pTok->n, pTok->p
  194705. );
  194706. }
  194707. }
  194708. static void sqlite3Fts5ParseSetDistance(
  194709. Fts5Parse *pParse,
  194710. Fts5ExprNearset *pNear,
  194711. Fts5Token *p
  194712. ){
  194713. if( pNear ){
  194714. int nNear = 0;
  194715. int i;
  194716. if( p->n ){
  194717. for(i=0; i<p->n; i++){
  194718. char c = (char)p->p[i];
  194719. if( c<'0' || c>'9' ){
  194720. sqlite3Fts5ParseError(
  194721. pParse, "expected integer, got \"%.*s\"", p->n, p->p
  194722. );
  194723. return;
  194724. }
  194725. nNear = nNear * 10 + (p->p[i] - '0');
  194726. }
  194727. }else{
  194728. nNear = FTS5_DEFAULT_NEARDIST;
  194729. }
  194730. pNear->nNear = nNear;
  194731. }
  194732. }
  194733. /*
  194734. ** The second argument passed to this function may be NULL, or it may be
  194735. ** an existing Fts5Colset object. This function returns a pointer to
  194736. ** a new colset object containing the contents of (p) with new value column
  194737. ** number iCol appended.
  194738. **
  194739. ** If an OOM error occurs, store an error code in pParse and return NULL.
  194740. ** The old colset object (if any) is not freed in this case.
  194741. */
  194742. static Fts5Colset *fts5ParseColset(
  194743. Fts5Parse *pParse, /* Store SQLITE_NOMEM here if required */
  194744. Fts5Colset *p, /* Existing colset object */
  194745. int iCol /* New column to add to colset object */
  194746. ){
  194747. int nCol = p ? p->nCol : 0; /* Num. columns already in colset object */
  194748. Fts5Colset *pNew; /* New colset object to return */
  194749. assert( pParse->rc==SQLITE_OK );
  194750. assert( iCol>=0 && iCol<pParse->pConfig->nCol );
  194751. pNew = sqlite3_realloc64(p, sizeof(Fts5Colset) + sizeof(int)*nCol);
  194752. if( pNew==0 ){
  194753. pParse->rc = SQLITE_NOMEM;
  194754. }else{
  194755. int *aiCol = pNew->aiCol;
  194756. int i, j;
  194757. for(i=0; i<nCol; i++){
  194758. if( aiCol[i]==iCol ) return pNew;
  194759. if( aiCol[i]>iCol ) break;
  194760. }
  194761. for(j=nCol; j>i; j--){
  194762. aiCol[j] = aiCol[j-1];
  194763. }
  194764. aiCol[i] = iCol;
  194765. pNew->nCol = nCol+1;
  194766. #ifndef NDEBUG
  194767. /* Check that the array is in order and contains no duplicate entries. */
  194768. for(i=1; i<pNew->nCol; i++) assert( pNew->aiCol[i]>pNew->aiCol[i-1] );
  194769. #endif
  194770. }
  194771. return pNew;
  194772. }
  194773. /*
  194774. ** Allocate and return an Fts5Colset object specifying the inverse of
  194775. ** the colset passed as the second argument. Free the colset passed
  194776. ** as the second argument before returning.
  194777. */
  194778. static Fts5Colset *sqlite3Fts5ParseColsetInvert(Fts5Parse *pParse, Fts5Colset *p){
  194779. Fts5Colset *pRet;
  194780. int nCol = pParse->pConfig->nCol;
  194781. pRet = (Fts5Colset*)sqlite3Fts5MallocZero(&pParse->rc,
  194782. sizeof(Fts5Colset) + sizeof(int)*nCol
  194783. );
  194784. if( pRet ){
  194785. int i;
  194786. int iOld = 0;
  194787. for(i=0; i<nCol; i++){
  194788. if( iOld>=p->nCol || p->aiCol[iOld]!=i ){
  194789. pRet->aiCol[pRet->nCol++] = i;
  194790. }else{
  194791. iOld++;
  194792. }
  194793. }
  194794. }
  194795. sqlite3_free(p);
  194796. return pRet;
  194797. }
  194798. static Fts5Colset *sqlite3Fts5ParseColset(
  194799. Fts5Parse *pParse, /* Store SQLITE_NOMEM here if required */
  194800. Fts5Colset *pColset, /* Existing colset object */
  194801. Fts5Token *p
  194802. ){
  194803. Fts5Colset *pRet = 0;
  194804. int iCol;
  194805. char *z; /* Dequoted copy of token p */
  194806. z = sqlite3Fts5Strndup(&pParse->rc, p->p, p->n);
  194807. if( pParse->rc==SQLITE_OK ){
  194808. Fts5Config *pConfig = pParse->pConfig;
  194809. sqlite3Fts5Dequote(z);
  194810. for(iCol=0; iCol<pConfig->nCol; iCol++){
  194811. if( 0==sqlite3_stricmp(pConfig->azCol[iCol], z) ) break;
  194812. }
  194813. if( iCol==pConfig->nCol ){
  194814. sqlite3Fts5ParseError(pParse, "no such column: %s", z);
  194815. }else{
  194816. pRet = fts5ParseColset(pParse, pColset, iCol);
  194817. }
  194818. sqlite3_free(z);
  194819. }
  194820. if( pRet==0 ){
  194821. assert( pParse->rc!=SQLITE_OK );
  194822. sqlite3_free(pColset);
  194823. }
  194824. return pRet;
  194825. }
  194826. /*
  194827. ** If argument pOrig is NULL, or if (*pRc) is set to anything other than
  194828. ** SQLITE_OK when this function is called, NULL is returned.
  194829. **
  194830. ** Otherwise, a copy of (*pOrig) is made into memory obtained from
  194831. ** sqlite3Fts5MallocZero() and a pointer to it returned. If the allocation
  194832. ** fails, (*pRc) is set to SQLITE_NOMEM and NULL is returned.
  194833. */
  194834. static Fts5Colset *fts5CloneColset(int *pRc, Fts5Colset *pOrig){
  194835. Fts5Colset *pRet;
  194836. if( pOrig ){
  194837. sqlite3_int64 nByte = sizeof(Fts5Colset) + (pOrig->nCol-1) * sizeof(int);
  194838. pRet = (Fts5Colset*)sqlite3Fts5MallocZero(pRc, nByte);
  194839. if( pRet ){
  194840. memcpy(pRet, pOrig, (size_t)nByte);
  194841. }
  194842. }else{
  194843. pRet = 0;
  194844. }
  194845. return pRet;
  194846. }
  194847. /*
  194848. ** Remove from colset pColset any columns that are not also in colset pMerge.
  194849. */
  194850. static void fts5MergeColset(Fts5Colset *pColset, Fts5Colset *pMerge){
  194851. int iIn = 0; /* Next input in pColset */
  194852. int iMerge = 0; /* Next input in pMerge */
  194853. int iOut = 0; /* Next output slot in pColset */
  194854. while( iIn<pColset->nCol && iMerge<pMerge->nCol ){
  194855. int iDiff = pColset->aiCol[iIn] - pMerge->aiCol[iMerge];
  194856. if( iDiff==0 ){
  194857. pColset->aiCol[iOut++] = pMerge->aiCol[iMerge];
  194858. iMerge++;
  194859. iIn++;
  194860. }else if( iDiff>0 ){
  194861. iMerge++;
  194862. }else{
  194863. iIn++;
  194864. }
  194865. }
  194866. pColset->nCol = iOut;
  194867. }
  194868. /*
  194869. ** Recursively apply colset pColset to expression node pNode and all of
  194870. ** its decendents. If (*ppFree) is not NULL, it contains a spare copy
  194871. ** of pColset. This function may use the spare copy and set (*ppFree) to
  194872. ** zero, or it may create copies of pColset using fts5CloneColset().
  194873. */
  194874. static void fts5ParseSetColset(
  194875. Fts5Parse *pParse,
  194876. Fts5ExprNode *pNode,
  194877. Fts5Colset *pColset,
  194878. Fts5Colset **ppFree
  194879. ){
  194880. if( pParse->rc==SQLITE_OK ){
  194881. assert( pNode->eType==FTS5_TERM || pNode->eType==FTS5_STRING
  194882. || pNode->eType==FTS5_AND || pNode->eType==FTS5_OR
  194883. || pNode->eType==FTS5_NOT || pNode->eType==FTS5_EOF
  194884. );
  194885. if( pNode->eType==FTS5_STRING || pNode->eType==FTS5_TERM ){
  194886. Fts5ExprNearset *pNear = pNode->pNear;
  194887. if( pNear->pColset ){
  194888. fts5MergeColset(pNear->pColset, pColset);
  194889. if( pNear->pColset->nCol==0 ){
  194890. pNode->eType = FTS5_EOF;
  194891. pNode->xNext = 0;
  194892. }
  194893. }else if( *ppFree ){
  194894. pNear->pColset = pColset;
  194895. *ppFree = 0;
  194896. }else{
  194897. pNear->pColset = fts5CloneColset(&pParse->rc, pColset);
  194898. }
  194899. }else{
  194900. int i;
  194901. assert( pNode->eType!=FTS5_EOF || pNode->nChild==0 );
  194902. for(i=0; i<pNode->nChild; i++){
  194903. fts5ParseSetColset(pParse, pNode->apChild[i], pColset, ppFree);
  194904. }
  194905. }
  194906. }
  194907. }
  194908. /*
  194909. ** Apply colset pColset to expression node pExpr and all of its descendents.
  194910. */
  194911. static void sqlite3Fts5ParseSetColset(
  194912. Fts5Parse *pParse,
  194913. Fts5ExprNode *pExpr,
  194914. Fts5Colset *pColset
  194915. ){
  194916. Fts5Colset *pFree = pColset;
  194917. if( pParse->pConfig->eDetail==FTS5_DETAIL_NONE ){
  194918. pParse->rc = SQLITE_ERROR;
  194919. pParse->zErr = sqlite3_mprintf(
  194920. "fts5: column queries are not supported (detail=none)"
  194921. );
  194922. }else{
  194923. fts5ParseSetColset(pParse, pExpr, pColset, &pFree);
  194924. }
  194925. sqlite3_free(pFree);
  194926. }
  194927. static void fts5ExprAssignXNext(Fts5ExprNode *pNode){
  194928. switch( pNode->eType ){
  194929. case FTS5_STRING: {
  194930. Fts5ExprNearset *pNear = pNode->pNear;
  194931. if( pNear->nPhrase==1 && pNear->apPhrase[0]->nTerm==1
  194932. && pNear->apPhrase[0]->aTerm[0].pSynonym==0
  194933. && pNear->apPhrase[0]->aTerm[0].bFirst==0
  194934. ){
  194935. pNode->eType = FTS5_TERM;
  194936. pNode->xNext = fts5ExprNodeNext_TERM;
  194937. }else{
  194938. pNode->xNext = fts5ExprNodeNext_STRING;
  194939. }
  194940. break;
  194941. };
  194942. case FTS5_OR: {
  194943. pNode->xNext = fts5ExprNodeNext_OR;
  194944. break;
  194945. };
  194946. case FTS5_AND: {
  194947. pNode->xNext = fts5ExprNodeNext_AND;
  194948. break;
  194949. };
  194950. default: assert( pNode->eType==FTS5_NOT ); {
  194951. pNode->xNext = fts5ExprNodeNext_NOT;
  194952. break;
  194953. };
  194954. }
  194955. }
  194956. static void fts5ExprAddChildren(Fts5ExprNode *p, Fts5ExprNode *pSub){
  194957. if( p->eType!=FTS5_NOT && pSub->eType==p->eType ){
  194958. int nByte = sizeof(Fts5ExprNode*) * pSub->nChild;
  194959. memcpy(&p->apChild[p->nChild], pSub->apChild, nByte);
  194960. p->nChild += pSub->nChild;
  194961. sqlite3_free(pSub);
  194962. }else{
  194963. p->apChild[p->nChild++] = pSub;
  194964. }
  194965. }
  194966. /*
  194967. ** Allocate and return a new expression object. If anything goes wrong (i.e.
  194968. ** OOM error), leave an error code in pParse and return NULL.
  194969. */
  194970. static Fts5ExprNode *sqlite3Fts5ParseNode(
  194971. Fts5Parse *pParse, /* Parse context */
  194972. int eType, /* FTS5_STRING, AND, OR or NOT */
  194973. Fts5ExprNode *pLeft, /* Left hand child expression */
  194974. Fts5ExprNode *pRight, /* Right hand child expression */
  194975. Fts5ExprNearset *pNear /* For STRING expressions, the near cluster */
  194976. ){
  194977. Fts5ExprNode *pRet = 0;
  194978. if( pParse->rc==SQLITE_OK ){
  194979. int nChild = 0; /* Number of children of returned node */
  194980. sqlite3_int64 nByte; /* Bytes of space to allocate for this node */
  194981. assert( (eType!=FTS5_STRING && !pNear)
  194982. || (eType==FTS5_STRING && !pLeft && !pRight)
  194983. );
  194984. if( eType==FTS5_STRING && pNear==0 ) return 0;
  194985. if( eType!=FTS5_STRING && pLeft==0 ) return pRight;
  194986. if( eType!=FTS5_STRING && pRight==0 ) return pLeft;
  194987. if( eType==FTS5_NOT ){
  194988. nChild = 2;
  194989. }else if( eType==FTS5_AND || eType==FTS5_OR ){
  194990. nChild = 2;
  194991. if( pLeft->eType==eType ) nChild += pLeft->nChild-1;
  194992. if( pRight->eType==eType ) nChild += pRight->nChild-1;
  194993. }
  194994. nByte = sizeof(Fts5ExprNode) + sizeof(Fts5ExprNode*)*(nChild-1);
  194995. pRet = (Fts5ExprNode*)sqlite3Fts5MallocZero(&pParse->rc, nByte);
  194996. if( pRet ){
  194997. pRet->eType = eType;
  194998. pRet->pNear = pNear;
  194999. fts5ExprAssignXNext(pRet);
  195000. if( eType==FTS5_STRING ){
  195001. int iPhrase;
  195002. for(iPhrase=0; iPhrase<pNear->nPhrase; iPhrase++){
  195003. pNear->apPhrase[iPhrase]->pNode = pRet;
  195004. if( pNear->apPhrase[iPhrase]->nTerm==0 ){
  195005. pRet->xNext = 0;
  195006. pRet->eType = FTS5_EOF;
  195007. }
  195008. }
  195009. if( pParse->pConfig->eDetail!=FTS5_DETAIL_FULL ){
  195010. Fts5ExprPhrase *pPhrase = pNear->apPhrase[0];
  195011. if( pNear->nPhrase!=1
  195012. || pPhrase->nTerm>1
  195013. || (pPhrase->nTerm>0 && pPhrase->aTerm[0].bFirst)
  195014. ){
  195015. assert( pParse->rc==SQLITE_OK );
  195016. pParse->rc = SQLITE_ERROR;
  195017. assert( pParse->zErr==0 );
  195018. pParse->zErr = sqlite3_mprintf(
  195019. "fts5: %s queries are not supported (detail!=full)",
  195020. pNear->nPhrase==1 ? "phrase": "NEAR"
  195021. );
  195022. sqlite3_free(pRet);
  195023. pRet = 0;
  195024. }
  195025. }
  195026. }else{
  195027. fts5ExprAddChildren(pRet, pLeft);
  195028. fts5ExprAddChildren(pRet, pRight);
  195029. }
  195030. }
  195031. }
  195032. if( pRet==0 ){
  195033. assert( pParse->rc!=SQLITE_OK );
  195034. sqlite3Fts5ParseNodeFree(pLeft);
  195035. sqlite3Fts5ParseNodeFree(pRight);
  195036. sqlite3Fts5ParseNearsetFree(pNear);
  195037. }
  195038. return pRet;
  195039. }
  195040. static Fts5ExprNode *sqlite3Fts5ParseImplicitAnd(
  195041. Fts5Parse *pParse, /* Parse context */
  195042. Fts5ExprNode *pLeft, /* Left hand child expression */
  195043. Fts5ExprNode *pRight /* Right hand child expression */
  195044. ){
  195045. Fts5ExprNode *pRet = 0;
  195046. Fts5ExprNode *pPrev;
  195047. if( pParse->rc ){
  195048. sqlite3Fts5ParseNodeFree(pLeft);
  195049. sqlite3Fts5ParseNodeFree(pRight);
  195050. }else{
  195051. assert( pLeft->eType==FTS5_STRING
  195052. || pLeft->eType==FTS5_TERM
  195053. || pLeft->eType==FTS5_EOF
  195054. || pLeft->eType==FTS5_AND
  195055. );
  195056. assert( pRight->eType==FTS5_STRING
  195057. || pRight->eType==FTS5_TERM
  195058. || pRight->eType==FTS5_EOF
  195059. );
  195060. if( pLeft->eType==FTS5_AND ){
  195061. pPrev = pLeft->apChild[pLeft->nChild-1];
  195062. }else{
  195063. pPrev = pLeft;
  195064. }
  195065. assert( pPrev->eType==FTS5_STRING
  195066. || pPrev->eType==FTS5_TERM
  195067. || pPrev->eType==FTS5_EOF
  195068. );
  195069. if( pRight->eType==FTS5_EOF ){
  195070. assert( pParse->apPhrase[pParse->nPhrase-1]==pRight->pNear->apPhrase[0] );
  195071. sqlite3Fts5ParseNodeFree(pRight);
  195072. pRet = pLeft;
  195073. pParse->nPhrase--;
  195074. }
  195075. else if( pPrev->eType==FTS5_EOF ){
  195076. Fts5ExprPhrase **ap;
  195077. if( pPrev==pLeft ){
  195078. pRet = pRight;
  195079. }else{
  195080. pLeft->apChild[pLeft->nChild-1] = pRight;
  195081. pRet = pLeft;
  195082. }
  195083. ap = &pParse->apPhrase[pParse->nPhrase-1-pRight->pNear->nPhrase];
  195084. assert( ap[0]==pPrev->pNear->apPhrase[0] );
  195085. memmove(ap, &ap[1], sizeof(Fts5ExprPhrase*)*pRight->pNear->nPhrase);
  195086. pParse->nPhrase--;
  195087. sqlite3Fts5ParseNodeFree(pPrev);
  195088. }
  195089. else{
  195090. pRet = sqlite3Fts5ParseNode(pParse, FTS5_AND, pLeft, pRight, 0);
  195091. }
  195092. }
  195093. return pRet;
  195094. }
  195095. static char *fts5ExprTermPrint(Fts5ExprTerm *pTerm){
  195096. sqlite3_int64 nByte = 0;
  195097. Fts5ExprTerm *p;
  195098. char *zQuoted;
  195099. /* Determine the maximum amount of space required. */
  195100. for(p=pTerm; p; p=p->pSynonym){
  195101. nByte += (int)strlen(pTerm->zTerm) * 2 + 3 + 2;
  195102. }
  195103. zQuoted = sqlite3_malloc64(nByte);
  195104. if( zQuoted ){
  195105. int i = 0;
  195106. for(p=pTerm; p; p=p->pSynonym){
  195107. char *zIn = p->zTerm;
  195108. zQuoted[i++] = '"';
  195109. while( *zIn ){
  195110. if( *zIn=='"' ) zQuoted[i++] = '"';
  195111. zQuoted[i++] = *zIn++;
  195112. }
  195113. zQuoted[i++] = '"';
  195114. if( p->pSynonym ) zQuoted[i++] = '|';
  195115. }
  195116. if( pTerm->bPrefix ){
  195117. zQuoted[i++] = ' ';
  195118. zQuoted[i++] = '*';
  195119. }
  195120. zQuoted[i++] = '\0';
  195121. }
  195122. return zQuoted;
  195123. }
  195124. static char *fts5PrintfAppend(char *zApp, const char *zFmt, ...){
  195125. char *zNew;
  195126. va_list ap;
  195127. va_start(ap, zFmt);
  195128. zNew = sqlite3_vmprintf(zFmt, ap);
  195129. va_end(ap);
  195130. if( zApp && zNew ){
  195131. char *zNew2 = sqlite3_mprintf("%s%s", zApp, zNew);
  195132. sqlite3_free(zNew);
  195133. zNew = zNew2;
  195134. }
  195135. sqlite3_free(zApp);
  195136. return zNew;
  195137. }
  195138. /*
  195139. ** Compose a tcl-readable representation of expression pExpr. Return a
  195140. ** pointer to a buffer containing that representation. It is the
  195141. ** responsibility of the caller to at some point free the buffer using
  195142. ** sqlite3_free().
  195143. */
  195144. static char *fts5ExprPrintTcl(
  195145. Fts5Config *pConfig,
  195146. const char *zNearsetCmd,
  195147. Fts5ExprNode *pExpr
  195148. ){
  195149. char *zRet = 0;
  195150. if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){
  195151. Fts5ExprNearset *pNear = pExpr->pNear;
  195152. int i;
  195153. int iTerm;
  195154. zRet = fts5PrintfAppend(zRet, "%s ", zNearsetCmd);
  195155. if( zRet==0 ) return 0;
  195156. if( pNear->pColset ){
  195157. int *aiCol = pNear->pColset->aiCol;
  195158. int nCol = pNear->pColset->nCol;
  195159. if( nCol==1 ){
  195160. zRet = fts5PrintfAppend(zRet, "-col %d ", aiCol[0]);
  195161. }else{
  195162. zRet = fts5PrintfAppend(zRet, "-col {%d", aiCol[0]);
  195163. for(i=1; i<pNear->pColset->nCol; i++){
  195164. zRet = fts5PrintfAppend(zRet, " %d", aiCol[i]);
  195165. }
  195166. zRet = fts5PrintfAppend(zRet, "} ");
  195167. }
  195168. if( zRet==0 ) return 0;
  195169. }
  195170. if( pNear->nPhrase>1 ){
  195171. zRet = fts5PrintfAppend(zRet, "-near %d ", pNear->nNear);
  195172. if( zRet==0 ) return 0;
  195173. }
  195174. zRet = fts5PrintfAppend(zRet, "--");
  195175. if( zRet==0 ) return 0;
  195176. for(i=0; i<pNear->nPhrase; i++){
  195177. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  195178. zRet = fts5PrintfAppend(zRet, " {");
  195179. for(iTerm=0; zRet && iTerm<pPhrase->nTerm; iTerm++){
  195180. char *zTerm = pPhrase->aTerm[iTerm].zTerm;
  195181. zRet = fts5PrintfAppend(zRet, "%s%s", iTerm==0?"":" ", zTerm);
  195182. if( pPhrase->aTerm[iTerm].bPrefix ){
  195183. zRet = fts5PrintfAppend(zRet, "*");
  195184. }
  195185. }
  195186. if( zRet ) zRet = fts5PrintfAppend(zRet, "}");
  195187. if( zRet==0 ) return 0;
  195188. }
  195189. }else{
  195190. char const *zOp = 0;
  195191. int i;
  195192. switch( pExpr->eType ){
  195193. case FTS5_AND: zOp = "AND"; break;
  195194. case FTS5_NOT: zOp = "NOT"; break;
  195195. default:
  195196. assert( pExpr->eType==FTS5_OR );
  195197. zOp = "OR";
  195198. break;
  195199. }
  195200. zRet = sqlite3_mprintf("%s", zOp);
  195201. for(i=0; zRet && i<pExpr->nChild; i++){
  195202. char *z = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->apChild[i]);
  195203. if( !z ){
  195204. sqlite3_free(zRet);
  195205. zRet = 0;
  195206. }else{
  195207. zRet = fts5PrintfAppend(zRet, " [%z]", z);
  195208. }
  195209. }
  195210. }
  195211. return zRet;
  195212. }
  195213. static char *fts5ExprPrint(Fts5Config *pConfig, Fts5ExprNode *pExpr){
  195214. char *zRet = 0;
  195215. if( pExpr->eType==0 ){
  195216. return sqlite3_mprintf("\"\"");
  195217. }else
  195218. if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){
  195219. Fts5ExprNearset *pNear = pExpr->pNear;
  195220. int i;
  195221. int iTerm;
  195222. if( pNear->pColset ){
  195223. int iCol = pNear->pColset->aiCol[0];
  195224. zRet = fts5PrintfAppend(zRet, "%s : ", pConfig->azCol[iCol]);
  195225. if( zRet==0 ) return 0;
  195226. }
  195227. if( pNear->nPhrase>1 ){
  195228. zRet = fts5PrintfAppend(zRet, "NEAR(");
  195229. if( zRet==0 ) return 0;
  195230. }
  195231. for(i=0; i<pNear->nPhrase; i++){
  195232. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  195233. if( i!=0 ){
  195234. zRet = fts5PrintfAppend(zRet, " ");
  195235. if( zRet==0 ) return 0;
  195236. }
  195237. for(iTerm=0; iTerm<pPhrase->nTerm; iTerm++){
  195238. char *zTerm = fts5ExprTermPrint(&pPhrase->aTerm[iTerm]);
  195239. if( zTerm ){
  195240. zRet = fts5PrintfAppend(zRet, "%s%s", iTerm==0?"":" + ", zTerm);
  195241. sqlite3_free(zTerm);
  195242. }
  195243. if( zTerm==0 || zRet==0 ){
  195244. sqlite3_free(zRet);
  195245. return 0;
  195246. }
  195247. }
  195248. }
  195249. if( pNear->nPhrase>1 ){
  195250. zRet = fts5PrintfAppend(zRet, ", %d)", pNear->nNear);
  195251. if( zRet==0 ) return 0;
  195252. }
  195253. }else{
  195254. char const *zOp = 0;
  195255. int i;
  195256. switch( pExpr->eType ){
  195257. case FTS5_AND: zOp = " AND "; break;
  195258. case FTS5_NOT: zOp = " NOT "; break;
  195259. default:
  195260. assert( pExpr->eType==FTS5_OR );
  195261. zOp = " OR ";
  195262. break;
  195263. }
  195264. for(i=0; i<pExpr->nChild; i++){
  195265. char *z = fts5ExprPrint(pConfig, pExpr->apChild[i]);
  195266. if( z==0 ){
  195267. sqlite3_free(zRet);
  195268. zRet = 0;
  195269. }else{
  195270. int e = pExpr->apChild[i]->eType;
  195271. int b = (e!=FTS5_STRING && e!=FTS5_TERM && e!=FTS5_EOF);
  195272. zRet = fts5PrintfAppend(zRet, "%s%s%z%s",
  195273. (i==0 ? "" : zOp),
  195274. (b?"(":""), z, (b?")":"")
  195275. );
  195276. }
  195277. if( zRet==0 ) break;
  195278. }
  195279. }
  195280. return zRet;
  195281. }
  195282. /*
  195283. ** The implementation of user-defined scalar functions fts5_expr() (bTcl==0)
  195284. ** and fts5_expr_tcl() (bTcl!=0).
  195285. */
  195286. static void fts5ExprFunction(
  195287. sqlite3_context *pCtx, /* Function call context */
  195288. int nArg, /* Number of args */
  195289. sqlite3_value **apVal, /* Function arguments */
  195290. int bTcl
  195291. ){
  195292. Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx);
  195293. sqlite3 *db = sqlite3_context_db_handle(pCtx);
  195294. const char *zExpr = 0;
  195295. char *zErr = 0;
  195296. Fts5Expr *pExpr = 0;
  195297. int rc;
  195298. int i;
  195299. const char **azConfig; /* Array of arguments for Fts5Config */
  195300. const char *zNearsetCmd = "nearset";
  195301. int nConfig; /* Size of azConfig[] */
  195302. Fts5Config *pConfig = 0;
  195303. int iArg = 1;
  195304. if( nArg<1 ){
  195305. zErr = sqlite3_mprintf("wrong number of arguments to function %s",
  195306. bTcl ? "fts5_expr_tcl" : "fts5_expr"
  195307. );
  195308. sqlite3_result_error(pCtx, zErr, -1);
  195309. sqlite3_free(zErr);
  195310. return;
  195311. }
  195312. if( bTcl && nArg>1 ){
  195313. zNearsetCmd = (const char*)sqlite3_value_text(apVal[1]);
  195314. iArg = 2;
  195315. }
  195316. nConfig = 3 + (nArg-iArg);
  195317. azConfig = (const char**)sqlite3_malloc64(sizeof(char*) * nConfig);
  195318. if( azConfig==0 ){
  195319. sqlite3_result_error_nomem(pCtx);
  195320. return;
  195321. }
  195322. azConfig[0] = 0;
  195323. azConfig[1] = "main";
  195324. azConfig[2] = "tbl";
  195325. for(i=3; iArg<nArg; iArg++){
  195326. azConfig[i++] = (const char*)sqlite3_value_text(apVal[iArg]);
  195327. }
  195328. zExpr = (const char*)sqlite3_value_text(apVal[0]);
  195329. rc = sqlite3Fts5ConfigParse(pGlobal, db, nConfig, azConfig, &pConfig, &zErr);
  195330. if( rc==SQLITE_OK ){
  195331. rc = sqlite3Fts5ExprNew(pConfig, pConfig->nCol, zExpr, &pExpr, &zErr);
  195332. }
  195333. if( rc==SQLITE_OK ){
  195334. char *zText;
  195335. if( pExpr->pRoot->xNext==0 ){
  195336. zText = sqlite3_mprintf("");
  195337. }else if( bTcl ){
  195338. zText = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->pRoot);
  195339. }else{
  195340. zText = fts5ExprPrint(pConfig, pExpr->pRoot);
  195341. }
  195342. if( zText==0 ){
  195343. rc = SQLITE_NOMEM;
  195344. }else{
  195345. sqlite3_result_text(pCtx, zText, -1, SQLITE_TRANSIENT);
  195346. sqlite3_free(zText);
  195347. }
  195348. }
  195349. if( rc!=SQLITE_OK ){
  195350. if( zErr ){
  195351. sqlite3_result_error(pCtx, zErr, -1);
  195352. sqlite3_free(zErr);
  195353. }else{
  195354. sqlite3_result_error_code(pCtx, rc);
  195355. }
  195356. }
  195357. sqlite3_free((void *)azConfig);
  195358. sqlite3Fts5ConfigFree(pConfig);
  195359. sqlite3Fts5ExprFree(pExpr);
  195360. }
  195361. static void fts5ExprFunctionHr(
  195362. sqlite3_context *pCtx, /* Function call context */
  195363. int nArg, /* Number of args */
  195364. sqlite3_value **apVal /* Function arguments */
  195365. ){
  195366. fts5ExprFunction(pCtx, nArg, apVal, 0);
  195367. }
  195368. static void fts5ExprFunctionTcl(
  195369. sqlite3_context *pCtx, /* Function call context */
  195370. int nArg, /* Number of args */
  195371. sqlite3_value **apVal /* Function arguments */
  195372. ){
  195373. fts5ExprFunction(pCtx, nArg, apVal, 1);
  195374. }
  195375. /*
  195376. ** The implementation of an SQLite user-defined-function that accepts a
  195377. ** single integer as an argument. If the integer is an alpha-numeric
  195378. ** unicode code point, 1 is returned. Otherwise 0.
  195379. */
  195380. static void fts5ExprIsAlnum(
  195381. sqlite3_context *pCtx, /* Function call context */
  195382. int nArg, /* Number of args */
  195383. sqlite3_value **apVal /* Function arguments */
  195384. ){
  195385. int iCode;
  195386. u8 aArr[32];
  195387. if( nArg!=1 ){
  195388. sqlite3_result_error(pCtx,
  195389. "wrong number of arguments to function fts5_isalnum", -1
  195390. );
  195391. return;
  195392. }
  195393. memset(aArr, 0, sizeof(aArr));
  195394. sqlite3Fts5UnicodeCatParse("L*", aArr);
  195395. sqlite3Fts5UnicodeCatParse("N*", aArr);
  195396. sqlite3Fts5UnicodeCatParse("Co", aArr);
  195397. iCode = sqlite3_value_int(apVal[0]);
  195398. sqlite3_result_int(pCtx, aArr[sqlite3Fts5UnicodeCategory((u32)iCode)]);
  195399. }
  195400. static void fts5ExprFold(
  195401. sqlite3_context *pCtx, /* Function call context */
  195402. int nArg, /* Number of args */
  195403. sqlite3_value **apVal /* Function arguments */
  195404. ){
  195405. if( nArg!=1 && nArg!=2 ){
  195406. sqlite3_result_error(pCtx,
  195407. "wrong number of arguments to function fts5_fold", -1
  195408. );
  195409. }else{
  195410. int iCode;
  195411. int bRemoveDiacritics = 0;
  195412. iCode = sqlite3_value_int(apVal[0]);
  195413. if( nArg==2 ) bRemoveDiacritics = sqlite3_value_int(apVal[1]);
  195414. sqlite3_result_int(pCtx, sqlite3Fts5UnicodeFold(iCode, bRemoveDiacritics));
  195415. }
  195416. }
  195417. /*
  195418. ** This is called during initialization to register the fts5_expr() scalar
  195419. ** UDF with the SQLite handle passed as the only argument.
  195420. */
  195421. static int sqlite3Fts5ExprInit(Fts5Global *pGlobal, sqlite3 *db){
  195422. struct Fts5ExprFunc {
  195423. const char *z;
  195424. void (*x)(sqlite3_context*,int,sqlite3_value**);
  195425. } aFunc[] = {
  195426. { "fts5_expr", fts5ExprFunctionHr },
  195427. { "fts5_expr_tcl", fts5ExprFunctionTcl },
  195428. { "fts5_isalnum", fts5ExprIsAlnum },
  195429. { "fts5_fold", fts5ExprFold },
  195430. };
  195431. int i;
  195432. int rc = SQLITE_OK;
  195433. void *pCtx = (void*)pGlobal;
  195434. for(i=0; rc==SQLITE_OK && i<ArraySize(aFunc); i++){
  195435. struct Fts5ExprFunc *p = &aFunc[i];
  195436. rc = sqlite3_create_function(db, p->z, -1, SQLITE_UTF8, pCtx, p->x, 0, 0);
  195437. }
  195438. /* Avoid warnings indicating that sqlite3Fts5ParserTrace() and
  195439. ** sqlite3Fts5ParserFallback() are unused */
  195440. #ifndef NDEBUG
  195441. (void)sqlite3Fts5ParserTrace;
  195442. #endif
  195443. (void)sqlite3Fts5ParserFallback;
  195444. return rc;
  195445. }
  195446. /*
  195447. ** Return the number of phrases in expression pExpr.
  195448. */
  195449. static int sqlite3Fts5ExprPhraseCount(Fts5Expr *pExpr){
  195450. return (pExpr ? pExpr->nPhrase : 0);
  195451. }
  195452. /*
  195453. ** Return the number of terms in the iPhrase'th phrase in pExpr.
  195454. */
  195455. static int sqlite3Fts5ExprPhraseSize(Fts5Expr *pExpr, int iPhrase){
  195456. if( iPhrase<0 || iPhrase>=pExpr->nPhrase ) return 0;
  195457. return pExpr->apExprPhrase[iPhrase]->nTerm;
  195458. }
  195459. /*
  195460. ** This function is used to access the current position list for phrase
  195461. ** iPhrase.
  195462. */
  195463. static int sqlite3Fts5ExprPoslist(Fts5Expr *pExpr, int iPhrase, const u8 **pa){
  195464. int nRet;
  195465. Fts5ExprPhrase *pPhrase = pExpr->apExprPhrase[iPhrase];
  195466. Fts5ExprNode *pNode = pPhrase->pNode;
  195467. if( pNode->bEof==0 && pNode->iRowid==pExpr->pRoot->iRowid ){
  195468. *pa = pPhrase->poslist.p;
  195469. nRet = pPhrase->poslist.n;
  195470. }else{
  195471. *pa = 0;
  195472. nRet = 0;
  195473. }
  195474. return nRet;
  195475. }
  195476. struct Fts5PoslistPopulator {
  195477. Fts5PoslistWriter writer;
  195478. int bOk; /* True if ok to populate */
  195479. int bMiss;
  195480. };
  195481. static Fts5PoslistPopulator *sqlite3Fts5ExprClearPoslists(Fts5Expr *pExpr, int bLive){
  195482. Fts5PoslistPopulator *pRet;
  195483. pRet = sqlite3_malloc64(sizeof(Fts5PoslistPopulator)*pExpr->nPhrase);
  195484. if( pRet ){
  195485. int i;
  195486. memset(pRet, 0, sizeof(Fts5PoslistPopulator)*pExpr->nPhrase);
  195487. for(i=0; i<pExpr->nPhrase; i++){
  195488. Fts5Buffer *pBuf = &pExpr->apExprPhrase[i]->poslist;
  195489. Fts5ExprNode *pNode = pExpr->apExprPhrase[i]->pNode;
  195490. assert( pExpr->apExprPhrase[i]->nTerm==1 );
  195491. if( bLive &&
  195492. (pBuf->n==0 || pNode->iRowid!=pExpr->pRoot->iRowid || pNode->bEof)
  195493. ){
  195494. pRet[i].bMiss = 1;
  195495. }else{
  195496. pBuf->n = 0;
  195497. }
  195498. }
  195499. }
  195500. return pRet;
  195501. }
  195502. struct Fts5ExprCtx {
  195503. Fts5Expr *pExpr;
  195504. Fts5PoslistPopulator *aPopulator;
  195505. i64 iOff;
  195506. };
  195507. typedef struct Fts5ExprCtx Fts5ExprCtx;
  195508. /*
  195509. ** TODO: Make this more efficient!
  195510. */
  195511. static int fts5ExprColsetTest(Fts5Colset *pColset, int iCol){
  195512. int i;
  195513. for(i=0; i<pColset->nCol; i++){
  195514. if( pColset->aiCol[i]==iCol ) return 1;
  195515. }
  195516. return 0;
  195517. }
  195518. static int fts5ExprPopulatePoslistsCb(
  195519. void *pCtx, /* Copy of 2nd argument to xTokenize() */
  195520. int tflags, /* Mask of FTS5_TOKEN_* flags */
  195521. const char *pToken, /* Pointer to buffer containing token */
  195522. int nToken, /* Size of token in bytes */
  195523. int iUnused1, /* Byte offset of token within input text */
  195524. int iUnused2 /* Byte offset of end of token within input text */
  195525. ){
  195526. Fts5ExprCtx *p = (Fts5ExprCtx*)pCtx;
  195527. Fts5Expr *pExpr = p->pExpr;
  195528. int i;
  195529. UNUSED_PARAM2(iUnused1, iUnused2);
  195530. if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
  195531. if( (tflags & FTS5_TOKEN_COLOCATED)==0 ) p->iOff++;
  195532. for(i=0; i<pExpr->nPhrase; i++){
  195533. Fts5ExprTerm *pTerm;
  195534. if( p->aPopulator[i].bOk==0 ) continue;
  195535. for(pTerm=&pExpr->apExprPhrase[i]->aTerm[0]; pTerm; pTerm=pTerm->pSynonym){
  195536. int nTerm = (int)strlen(pTerm->zTerm);
  195537. if( (nTerm==nToken || (nTerm<nToken && pTerm->bPrefix))
  195538. && memcmp(pTerm->zTerm, pToken, nTerm)==0
  195539. ){
  195540. int rc = sqlite3Fts5PoslistWriterAppend(
  195541. &pExpr->apExprPhrase[i]->poslist, &p->aPopulator[i].writer, p->iOff
  195542. );
  195543. if( rc ) return rc;
  195544. break;
  195545. }
  195546. }
  195547. }
  195548. return SQLITE_OK;
  195549. }
  195550. static int sqlite3Fts5ExprPopulatePoslists(
  195551. Fts5Config *pConfig,
  195552. Fts5Expr *pExpr,
  195553. Fts5PoslistPopulator *aPopulator,
  195554. int iCol,
  195555. const char *z, int n
  195556. ){
  195557. int i;
  195558. Fts5ExprCtx sCtx;
  195559. sCtx.pExpr = pExpr;
  195560. sCtx.aPopulator = aPopulator;
  195561. sCtx.iOff = (((i64)iCol) << 32) - 1;
  195562. for(i=0; i<pExpr->nPhrase; i++){
  195563. Fts5ExprNode *pNode = pExpr->apExprPhrase[i]->pNode;
  195564. Fts5Colset *pColset = pNode->pNear->pColset;
  195565. if( (pColset && 0==fts5ExprColsetTest(pColset, iCol))
  195566. || aPopulator[i].bMiss
  195567. ){
  195568. aPopulator[i].bOk = 0;
  195569. }else{
  195570. aPopulator[i].bOk = 1;
  195571. }
  195572. }
  195573. return sqlite3Fts5Tokenize(pConfig,
  195574. FTS5_TOKENIZE_DOCUMENT, z, n, (void*)&sCtx, fts5ExprPopulatePoslistsCb
  195575. );
  195576. }
  195577. static void fts5ExprClearPoslists(Fts5ExprNode *pNode){
  195578. if( pNode->eType==FTS5_TERM || pNode->eType==FTS5_STRING ){
  195579. pNode->pNear->apPhrase[0]->poslist.n = 0;
  195580. }else{
  195581. int i;
  195582. for(i=0; i<pNode->nChild; i++){
  195583. fts5ExprClearPoslists(pNode->apChild[i]);
  195584. }
  195585. }
  195586. }
  195587. static int fts5ExprCheckPoslists(Fts5ExprNode *pNode, i64 iRowid){
  195588. pNode->iRowid = iRowid;
  195589. pNode->bEof = 0;
  195590. switch( pNode->eType ){
  195591. case FTS5_TERM:
  195592. case FTS5_STRING:
  195593. return (pNode->pNear->apPhrase[0]->poslist.n>0);
  195594. case FTS5_AND: {
  195595. int i;
  195596. for(i=0; i<pNode->nChild; i++){
  195597. if( fts5ExprCheckPoslists(pNode->apChild[i], iRowid)==0 ){
  195598. fts5ExprClearPoslists(pNode);
  195599. return 0;
  195600. }
  195601. }
  195602. break;
  195603. }
  195604. case FTS5_OR: {
  195605. int i;
  195606. int bRet = 0;
  195607. for(i=0; i<pNode->nChild; i++){
  195608. if( fts5ExprCheckPoslists(pNode->apChild[i], iRowid) ){
  195609. bRet = 1;
  195610. }
  195611. }
  195612. return bRet;
  195613. }
  195614. default: {
  195615. assert( pNode->eType==FTS5_NOT );
  195616. if( 0==fts5ExprCheckPoslists(pNode->apChild[0], iRowid)
  195617. || 0!=fts5ExprCheckPoslists(pNode->apChild[1], iRowid)
  195618. ){
  195619. fts5ExprClearPoslists(pNode);
  195620. return 0;
  195621. }
  195622. break;
  195623. }
  195624. }
  195625. return 1;
  195626. }
  195627. static void sqlite3Fts5ExprCheckPoslists(Fts5Expr *pExpr, i64 iRowid){
  195628. fts5ExprCheckPoslists(pExpr->pRoot, iRowid);
  195629. }
  195630. /*
  195631. ** This function is only called for detail=columns tables.
  195632. */
  195633. static int sqlite3Fts5ExprPhraseCollist(
  195634. Fts5Expr *pExpr,
  195635. int iPhrase,
  195636. const u8 **ppCollist,
  195637. int *pnCollist
  195638. ){
  195639. Fts5ExprPhrase *pPhrase = pExpr->apExprPhrase[iPhrase];
  195640. Fts5ExprNode *pNode = pPhrase->pNode;
  195641. int rc = SQLITE_OK;
  195642. assert( iPhrase>=0 && iPhrase<pExpr->nPhrase );
  195643. assert( pExpr->pConfig->eDetail==FTS5_DETAIL_COLUMNS );
  195644. if( pNode->bEof==0
  195645. && pNode->iRowid==pExpr->pRoot->iRowid
  195646. && pPhrase->poslist.n>0
  195647. ){
  195648. Fts5ExprTerm *pTerm = &pPhrase->aTerm[0];
  195649. if( pTerm->pSynonym ){
  195650. Fts5Buffer *pBuf = (Fts5Buffer*)&pTerm->pSynonym[1];
  195651. rc = fts5ExprSynonymList(
  195652. pTerm, pNode->iRowid, pBuf, (u8**)ppCollist, pnCollist
  195653. );
  195654. }else{
  195655. *ppCollist = pPhrase->aTerm[0].pIter->pData;
  195656. *pnCollist = pPhrase->aTerm[0].pIter->nData;
  195657. }
  195658. }else{
  195659. *ppCollist = 0;
  195660. *pnCollist = 0;
  195661. }
  195662. return rc;
  195663. }
  195664. /*
  195665. ** 2014 August 11
  195666. **
  195667. ** The author disclaims copyright to this source code. In place of
  195668. ** a legal notice, here is a blessing:
  195669. **
  195670. ** May you do good and not evil.
  195671. ** May you find forgiveness for yourself and forgive others.
  195672. ** May you share freely, never taking more than you give.
  195673. **
  195674. ******************************************************************************
  195675. **
  195676. */
  195677. /* #include "fts5Int.h" */
  195678. typedef struct Fts5HashEntry Fts5HashEntry;
  195679. /*
  195680. ** This file contains the implementation of an in-memory hash table used
  195681. ** to accumuluate "term -> doclist" content before it is flused to a level-0
  195682. ** segment.
  195683. */
  195684. struct Fts5Hash {
  195685. int eDetail; /* Copy of Fts5Config.eDetail */
  195686. int *pnByte; /* Pointer to bytes counter */
  195687. int nEntry; /* Number of entries currently in hash */
  195688. int nSlot; /* Size of aSlot[] array */
  195689. Fts5HashEntry *pScan; /* Current ordered scan item */
  195690. Fts5HashEntry **aSlot; /* Array of hash slots */
  195691. };
  195692. /*
  195693. ** Each entry in the hash table is represented by an object of the
  195694. ** following type. Each object, its key (a nul-terminated string) and
  195695. ** its current data are stored in a single memory allocation. The
  195696. ** key immediately follows the object in memory. The position list
  195697. ** data immediately follows the key data in memory.
  195698. **
  195699. ** The data that follows the key is in a similar, but not identical format
  195700. ** to the doclist data stored in the database. It is:
  195701. **
  195702. ** * Rowid, as a varint
  195703. ** * Position list, without 0x00 terminator.
  195704. ** * Size of previous position list and rowid, as a 4 byte
  195705. ** big-endian integer.
  195706. **
  195707. ** iRowidOff:
  195708. ** Offset of last rowid written to data area. Relative to first byte of
  195709. ** structure.
  195710. **
  195711. ** nData:
  195712. ** Bytes of data written since iRowidOff.
  195713. */
  195714. struct Fts5HashEntry {
  195715. Fts5HashEntry *pHashNext; /* Next hash entry with same hash-key */
  195716. Fts5HashEntry *pScanNext; /* Next entry in sorted order */
  195717. int nAlloc; /* Total size of allocation */
  195718. int iSzPoslist; /* Offset of space for 4-byte poslist size */
  195719. int nData; /* Total bytes of data (incl. structure) */
  195720. int nKey; /* Length of key in bytes */
  195721. u8 bDel; /* Set delete-flag @ iSzPoslist */
  195722. u8 bContent; /* Set content-flag (detail=none mode) */
  195723. i16 iCol; /* Column of last value written */
  195724. int iPos; /* Position of last value written */
  195725. i64 iRowid; /* Rowid of last value written */
  195726. };
  195727. /*
  195728. ** Eqivalent to:
  195729. **
  195730. ** char *fts5EntryKey(Fts5HashEntry *pEntry){ return zKey; }
  195731. */
  195732. #define fts5EntryKey(p) ( ((char *)(&(p)[1])) )
  195733. /*
  195734. ** Allocate a new hash table.
  195735. */
  195736. static int sqlite3Fts5HashNew(Fts5Config *pConfig, Fts5Hash **ppNew, int *pnByte){
  195737. int rc = SQLITE_OK;
  195738. Fts5Hash *pNew;
  195739. *ppNew = pNew = (Fts5Hash*)sqlite3_malloc(sizeof(Fts5Hash));
  195740. if( pNew==0 ){
  195741. rc = SQLITE_NOMEM;
  195742. }else{
  195743. sqlite3_int64 nByte;
  195744. memset(pNew, 0, sizeof(Fts5Hash));
  195745. pNew->pnByte = pnByte;
  195746. pNew->eDetail = pConfig->eDetail;
  195747. pNew->nSlot = 1024;
  195748. nByte = sizeof(Fts5HashEntry*) * pNew->nSlot;
  195749. pNew->aSlot = (Fts5HashEntry**)sqlite3_malloc64(nByte);
  195750. if( pNew->aSlot==0 ){
  195751. sqlite3_free(pNew);
  195752. *ppNew = 0;
  195753. rc = SQLITE_NOMEM;
  195754. }else{
  195755. memset(pNew->aSlot, 0, (size_t)nByte);
  195756. }
  195757. }
  195758. return rc;
  195759. }
  195760. /*
  195761. ** Free a hash table object.
  195762. */
  195763. static void sqlite3Fts5HashFree(Fts5Hash *pHash){
  195764. if( pHash ){
  195765. sqlite3Fts5HashClear(pHash);
  195766. sqlite3_free(pHash->aSlot);
  195767. sqlite3_free(pHash);
  195768. }
  195769. }
  195770. /*
  195771. ** Empty (but do not delete) a hash table.
  195772. */
  195773. static void sqlite3Fts5HashClear(Fts5Hash *pHash){
  195774. int i;
  195775. for(i=0; i<pHash->nSlot; i++){
  195776. Fts5HashEntry *pNext;
  195777. Fts5HashEntry *pSlot;
  195778. for(pSlot=pHash->aSlot[i]; pSlot; pSlot=pNext){
  195779. pNext = pSlot->pHashNext;
  195780. sqlite3_free(pSlot);
  195781. }
  195782. }
  195783. memset(pHash->aSlot, 0, pHash->nSlot * sizeof(Fts5HashEntry*));
  195784. pHash->nEntry = 0;
  195785. }
  195786. static unsigned int fts5HashKey(int nSlot, const u8 *p, int n){
  195787. int i;
  195788. unsigned int h = 13;
  195789. for(i=n-1; i>=0; i--){
  195790. h = (h << 3) ^ h ^ p[i];
  195791. }
  195792. return (h % nSlot);
  195793. }
  195794. static unsigned int fts5HashKey2(int nSlot, u8 b, const u8 *p, int n){
  195795. int i;
  195796. unsigned int h = 13;
  195797. for(i=n-1; i>=0; i--){
  195798. h = (h << 3) ^ h ^ p[i];
  195799. }
  195800. h = (h << 3) ^ h ^ b;
  195801. return (h % nSlot);
  195802. }
  195803. /*
  195804. ** Resize the hash table by doubling the number of slots.
  195805. */
  195806. static int fts5HashResize(Fts5Hash *pHash){
  195807. int nNew = pHash->nSlot*2;
  195808. int i;
  195809. Fts5HashEntry **apNew;
  195810. Fts5HashEntry **apOld = pHash->aSlot;
  195811. apNew = (Fts5HashEntry**)sqlite3_malloc64(nNew*sizeof(Fts5HashEntry*));
  195812. if( !apNew ) return SQLITE_NOMEM;
  195813. memset(apNew, 0, nNew*sizeof(Fts5HashEntry*));
  195814. for(i=0; i<pHash->nSlot; i++){
  195815. while( apOld[i] ){
  195816. unsigned int iHash;
  195817. Fts5HashEntry *p = apOld[i];
  195818. apOld[i] = p->pHashNext;
  195819. iHash = fts5HashKey(nNew, (u8*)fts5EntryKey(p),
  195820. (int)strlen(fts5EntryKey(p)));
  195821. p->pHashNext = apNew[iHash];
  195822. apNew[iHash] = p;
  195823. }
  195824. }
  195825. sqlite3_free(apOld);
  195826. pHash->nSlot = nNew;
  195827. pHash->aSlot = apNew;
  195828. return SQLITE_OK;
  195829. }
  195830. static int fts5HashAddPoslistSize(
  195831. Fts5Hash *pHash,
  195832. Fts5HashEntry *p,
  195833. Fts5HashEntry *p2
  195834. ){
  195835. int nRet = 0;
  195836. if( p->iSzPoslist ){
  195837. u8 *pPtr = p2 ? (u8*)p2 : (u8*)p;
  195838. int nData = p->nData;
  195839. if( pHash->eDetail==FTS5_DETAIL_NONE ){
  195840. assert( nData==p->iSzPoslist );
  195841. if( p->bDel ){
  195842. pPtr[nData++] = 0x00;
  195843. if( p->bContent ){
  195844. pPtr[nData++] = 0x00;
  195845. }
  195846. }
  195847. }else{
  195848. int nSz = (nData - p->iSzPoslist - 1); /* Size in bytes */
  195849. int nPos = nSz*2 + p->bDel; /* Value of nPos field */
  195850. assert( p->bDel==0 || p->bDel==1 );
  195851. if( nPos<=127 ){
  195852. pPtr[p->iSzPoslist] = (u8)nPos;
  195853. }else{
  195854. int nByte = sqlite3Fts5GetVarintLen((u32)nPos);
  195855. memmove(&pPtr[p->iSzPoslist + nByte], &pPtr[p->iSzPoslist + 1], nSz);
  195856. sqlite3Fts5PutVarint(&pPtr[p->iSzPoslist], nPos);
  195857. nData += (nByte-1);
  195858. }
  195859. }
  195860. nRet = nData - p->nData;
  195861. if( p2==0 ){
  195862. p->iSzPoslist = 0;
  195863. p->bDel = 0;
  195864. p->bContent = 0;
  195865. p->nData = nData;
  195866. }
  195867. }
  195868. return nRet;
  195869. }
  195870. /*
  195871. ** Add an entry to the in-memory hash table. The key is the concatenation
  195872. ** of bByte and (pToken/nToken). The value is (iRowid/iCol/iPos).
  195873. **
  195874. ** (bByte || pToken) -> (iRowid,iCol,iPos)
  195875. **
  195876. ** Or, if iCol is negative, then the value is a delete marker.
  195877. */
  195878. static int sqlite3Fts5HashWrite(
  195879. Fts5Hash *pHash,
  195880. i64 iRowid, /* Rowid for this entry */
  195881. int iCol, /* Column token appears in (-ve -> delete) */
  195882. int iPos, /* Position of token within column */
  195883. char bByte, /* First byte of token */
  195884. const char *pToken, int nToken /* Token to add or remove to or from index */
  195885. ){
  195886. unsigned int iHash;
  195887. Fts5HashEntry *p;
  195888. u8 *pPtr;
  195889. int nIncr = 0; /* Amount to increment (*pHash->pnByte) by */
  195890. int bNew; /* If non-delete entry should be written */
  195891. bNew = (pHash->eDetail==FTS5_DETAIL_FULL);
  195892. /* Attempt to locate an existing hash entry */
  195893. iHash = fts5HashKey2(pHash->nSlot, (u8)bByte, (const u8*)pToken, nToken);
  195894. for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){
  195895. char *zKey = fts5EntryKey(p);
  195896. if( zKey[0]==bByte
  195897. && p->nKey==nToken
  195898. && memcmp(&zKey[1], pToken, nToken)==0
  195899. ){
  195900. break;
  195901. }
  195902. }
  195903. /* If an existing hash entry cannot be found, create a new one. */
  195904. if( p==0 ){
  195905. /* Figure out how much space to allocate */
  195906. char *zKey;
  195907. sqlite3_int64 nByte = sizeof(Fts5HashEntry) + (nToken+1) + 1 + 64;
  195908. if( nByte<128 ) nByte = 128;
  195909. /* Grow the Fts5Hash.aSlot[] array if necessary. */
  195910. if( (pHash->nEntry*2)>=pHash->nSlot ){
  195911. int rc = fts5HashResize(pHash);
  195912. if( rc!=SQLITE_OK ) return rc;
  195913. iHash = fts5HashKey2(pHash->nSlot, (u8)bByte, (const u8*)pToken, nToken);
  195914. }
  195915. /* Allocate new Fts5HashEntry and add it to the hash table. */
  195916. p = (Fts5HashEntry*)sqlite3_malloc64(nByte);
  195917. if( !p ) return SQLITE_NOMEM;
  195918. memset(p, 0, sizeof(Fts5HashEntry));
  195919. p->nAlloc = (int)nByte;
  195920. zKey = fts5EntryKey(p);
  195921. zKey[0] = bByte;
  195922. memcpy(&zKey[1], pToken, nToken);
  195923. assert( iHash==fts5HashKey(pHash->nSlot, (u8*)zKey, nToken+1) );
  195924. p->nKey = nToken;
  195925. zKey[nToken+1] = '\0';
  195926. p->nData = nToken+1 + 1 + sizeof(Fts5HashEntry);
  195927. p->pHashNext = pHash->aSlot[iHash];
  195928. pHash->aSlot[iHash] = p;
  195929. pHash->nEntry++;
  195930. /* Add the first rowid field to the hash-entry */
  195931. p->nData += sqlite3Fts5PutVarint(&((u8*)p)[p->nData], iRowid);
  195932. p->iRowid = iRowid;
  195933. p->iSzPoslist = p->nData;
  195934. if( pHash->eDetail!=FTS5_DETAIL_NONE ){
  195935. p->nData += 1;
  195936. p->iCol = (pHash->eDetail==FTS5_DETAIL_FULL ? 0 : -1);
  195937. }
  195938. nIncr += p->nData;
  195939. }else{
  195940. /* Appending to an existing hash-entry. Check that there is enough
  195941. ** space to append the largest possible new entry. Worst case scenario
  195942. ** is:
  195943. **
  195944. ** + 9 bytes for a new rowid,
  195945. ** + 4 byte reserved for the "poslist size" varint.
  195946. ** + 1 byte for a "new column" byte,
  195947. ** + 3 bytes for a new column number (16-bit max) as a varint,
  195948. ** + 5 bytes for the new position offset (32-bit max).
  195949. */
  195950. if( (p->nAlloc - p->nData) < (9 + 4 + 1 + 3 + 5) ){
  195951. sqlite3_int64 nNew = p->nAlloc * 2;
  195952. Fts5HashEntry *pNew;
  195953. Fts5HashEntry **pp;
  195954. pNew = (Fts5HashEntry*)sqlite3_realloc64(p, nNew);
  195955. if( pNew==0 ) return SQLITE_NOMEM;
  195956. pNew->nAlloc = (int)nNew;
  195957. for(pp=&pHash->aSlot[iHash]; *pp!=p; pp=&(*pp)->pHashNext);
  195958. *pp = pNew;
  195959. p = pNew;
  195960. }
  195961. nIncr -= p->nData;
  195962. }
  195963. assert( (p->nAlloc - p->nData) >= (9 + 4 + 1 + 3 + 5) );
  195964. pPtr = (u8*)p;
  195965. /* If this is a new rowid, append the 4-byte size field for the previous
  195966. ** entry, and the new rowid for this entry. */
  195967. if( iRowid!=p->iRowid ){
  195968. fts5HashAddPoslistSize(pHash, p, 0);
  195969. p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iRowid - p->iRowid);
  195970. p->iRowid = iRowid;
  195971. bNew = 1;
  195972. p->iSzPoslist = p->nData;
  195973. if( pHash->eDetail!=FTS5_DETAIL_NONE ){
  195974. p->nData += 1;
  195975. p->iCol = (pHash->eDetail==FTS5_DETAIL_FULL ? 0 : -1);
  195976. p->iPos = 0;
  195977. }
  195978. }
  195979. if( iCol>=0 ){
  195980. if( pHash->eDetail==FTS5_DETAIL_NONE ){
  195981. p->bContent = 1;
  195982. }else{
  195983. /* Append a new column value, if necessary */
  195984. assert( iCol>=p->iCol );
  195985. if( iCol!=p->iCol ){
  195986. if( pHash->eDetail==FTS5_DETAIL_FULL ){
  195987. pPtr[p->nData++] = 0x01;
  195988. p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iCol);
  195989. p->iCol = (i16)iCol;
  195990. p->iPos = 0;
  195991. }else{
  195992. bNew = 1;
  195993. p->iCol = (i16)(iPos = iCol);
  195994. }
  195995. }
  195996. /* Append the new position offset, if necessary */
  195997. if( bNew ){
  195998. p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iPos - p->iPos + 2);
  195999. p->iPos = iPos;
  196000. }
  196001. }
  196002. }else{
  196003. /* This is a delete. Set the delete flag. */
  196004. p->bDel = 1;
  196005. }
  196006. nIncr += p->nData;
  196007. *pHash->pnByte += nIncr;
  196008. return SQLITE_OK;
  196009. }
  196010. /*
  196011. ** Arguments pLeft and pRight point to linked-lists of hash-entry objects,
  196012. ** each sorted in key order. This function merges the two lists into a
  196013. ** single list and returns a pointer to its first element.
  196014. */
  196015. static Fts5HashEntry *fts5HashEntryMerge(
  196016. Fts5HashEntry *pLeft,
  196017. Fts5HashEntry *pRight
  196018. ){
  196019. Fts5HashEntry *p1 = pLeft;
  196020. Fts5HashEntry *p2 = pRight;
  196021. Fts5HashEntry *pRet = 0;
  196022. Fts5HashEntry **ppOut = &pRet;
  196023. while( p1 || p2 ){
  196024. if( p1==0 ){
  196025. *ppOut = p2;
  196026. p2 = 0;
  196027. }else if( p2==0 ){
  196028. *ppOut = p1;
  196029. p1 = 0;
  196030. }else{
  196031. int i = 0;
  196032. char *zKey1 = fts5EntryKey(p1);
  196033. char *zKey2 = fts5EntryKey(p2);
  196034. while( zKey1[i]==zKey2[i] ) i++;
  196035. if( ((u8)zKey1[i])>((u8)zKey2[i]) ){
  196036. /* p2 is smaller */
  196037. *ppOut = p2;
  196038. ppOut = &p2->pScanNext;
  196039. p2 = p2->pScanNext;
  196040. }else{
  196041. /* p1 is smaller */
  196042. *ppOut = p1;
  196043. ppOut = &p1->pScanNext;
  196044. p1 = p1->pScanNext;
  196045. }
  196046. *ppOut = 0;
  196047. }
  196048. }
  196049. return pRet;
  196050. }
  196051. /*
  196052. ** Extract all tokens from hash table iHash and link them into a list
  196053. ** in sorted order. The hash table is cleared before returning. It is
  196054. ** the responsibility of the caller to free the elements of the returned
  196055. ** list.
  196056. */
  196057. static int fts5HashEntrySort(
  196058. Fts5Hash *pHash,
  196059. const char *pTerm, int nTerm, /* Query prefix, if any */
  196060. Fts5HashEntry **ppSorted
  196061. ){
  196062. const int nMergeSlot = 32;
  196063. Fts5HashEntry **ap;
  196064. Fts5HashEntry *pList;
  196065. int iSlot;
  196066. int i;
  196067. *ppSorted = 0;
  196068. ap = sqlite3_malloc64(sizeof(Fts5HashEntry*) * nMergeSlot);
  196069. if( !ap ) return SQLITE_NOMEM;
  196070. memset(ap, 0, sizeof(Fts5HashEntry*) * nMergeSlot);
  196071. for(iSlot=0; iSlot<pHash->nSlot; iSlot++){
  196072. Fts5HashEntry *pIter;
  196073. for(pIter=pHash->aSlot[iSlot]; pIter; pIter=pIter->pHashNext){
  196074. if( pTerm==0
  196075. || (pIter->nKey+1>=nTerm && 0==memcmp(fts5EntryKey(pIter), pTerm, nTerm))
  196076. ){
  196077. Fts5HashEntry *pEntry = pIter;
  196078. pEntry->pScanNext = 0;
  196079. for(i=0; ap[i]; i++){
  196080. pEntry = fts5HashEntryMerge(pEntry, ap[i]);
  196081. ap[i] = 0;
  196082. }
  196083. ap[i] = pEntry;
  196084. }
  196085. }
  196086. }
  196087. pList = 0;
  196088. for(i=0; i<nMergeSlot; i++){
  196089. pList = fts5HashEntryMerge(pList, ap[i]);
  196090. }
  196091. pHash->nEntry = 0;
  196092. sqlite3_free(ap);
  196093. *ppSorted = pList;
  196094. return SQLITE_OK;
  196095. }
  196096. /*
  196097. ** Query the hash table for a doclist associated with term pTerm/nTerm.
  196098. */
  196099. static int sqlite3Fts5HashQuery(
  196100. Fts5Hash *pHash, /* Hash table to query */
  196101. int nPre,
  196102. const char *pTerm, int nTerm, /* Query term */
  196103. void **ppOut, /* OUT: Pointer to new object */
  196104. int *pnDoclist /* OUT: Size of doclist in bytes */
  196105. ){
  196106. unsigned int iHash = fts5HashKey(pHash->nSlot, (const u8*)pTerm, nTerm);
  196107. char *zKey = 0;
  196108. Fts5HashEntry *p;
  196109. for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){
  196110. zKey = fts5EntryKey(p);
  196111. assert( p->nKey+1==(int)strlen(zKey) );
  196112. if( nTerm==p->nKey+1 && memcmp(zKey, pTerm, nTerm)==0 ) break;
  196113. }
  196114. if( p ){
  196115. int nHashPre = sizeof(Fts5HashEntry) + nTerm + 1;
  196116. int nList = p->nData - nHashPre;
  196117. u8 *pRet = (u8*)(*ppOut = sqlite3_malloc64(nPre + nList + 10));
  196118. if( pRet ){
  196119. Fts5HashEntry *pFaux = (Fts5HashEntry*)&pRet[nPre-nHashPre];
  196120. memcpy(&pRet[nPre], &((u8*)p)[nHashPre], nList);
  196121. nList += fts5HashAddPoslistSize(pHash, p, pFaux);
  196122. *pnDoclist = nList;
  196123. }else{
  196124. *pnDoclist = 0;
  196125. return SQLITE_NOMEM;
  196126. }
  196127. }else{
  196128. *ppOut = 0;
  196129. *pnDoclist = 0;
  196130. }
  196131. return SQLITE_OK;
  196132. }
  196133. static int sqlite3Fts5HashScanInit(
  196134. Fts5Hash *p, /* Hash table to query */
  196135. const char *pTerm, int nTerm /* Query prefix */
  196136. ){
  196137. return fts5HashEntrySort(p, pTerm, nTerm, &p->pScan);
  196138. }
  196139. static void sqlite3Fts5HashScanNext(Fts5Hash *p){
  196140. assert( !sqlite3Fts5HashScanEof(p) );
  196141. p->pScan = p->pScan->pScanNext;
  196142. }
  196143. static int sqlite3Fts5HashScanEof(Fts5Hash *p){
  196144. return (p->pScan==0);
  196145. }
  196146. static void sqlite3Fts5HashScanEntry(
  196147. Fts5Hash *pHash,
  196148. const char **pzTerm, /* OUT: term (nul-terminated) */
  196149. const u8 **ppDoclist, /* OUT: pointer to doclist */
  196150. int *pnDoclist /* OUT: size of doclist in bytes */
  196151. ){
  196152. Fts5HashEntry *p;
  196153. if( (p = pHash->pScan) ){
  196154. char *zKey = fts5EntryKey(p);
  196155. int nTerm = (int)strlen(zKey);
  196156. fts5HashAddPoslistSize(pHash, p, 0);
  196157. *pzTerm = zKey;
  196158. *ppDoclist = (const u8*)&zKey[nTerm+1];
  196159. *pnDoclist = p->nData - (sizeof(Fts5HashEntry) + nTerm + 1);
  196160. }else{
  196161. *pzTerm = 0;
  196162. *ppDoclist = 0;
  196163. *pnDoclist = 0;
  196164. }
  196165. }
  196166. /*
  196167. ** 2014 May 31
  196168. **
  196169. ** The author disclaims copyright to this source code. In place of
  196170. ** a legal notice, here is a blessing:
  196171. **
  196172. ** May you do good and not evil.
  196173. ** May you find forgiveness for yourself and forgive others.
  196174. ** May you share freely, never taking more than you give.
  196175. **
  196176. ******************************************************************************
  196177. **
  196178. ** Low level access to the FTS index stored in the database file. The
  196179. ** routines in this file file implement all read and write access to the
  196180. ** %_data table. Other parts of the system access this functionality via
  196181. ** the interface defined in fts5Int.h.
  196182. */
  196183. /* #include "fts5Int.h" */
  196184. /*
  196185. ** Overview:
  196186. **
  196187. ** The %_data table contains all the FTS indexes for an FTS5 virtual table.
  196188. ** As well as the main term index, there may be up to 31 prefix indexes.
  196189. ** The format is similar to FTS3/4, except that:
  196190. **
  196191. ** * all segment b-tree leaf data is stored in fixed size page records
  196192. ** (e.g. 1000 bytes). A single doclist may span multiple pages. Care is
  196193. ** taken to ensure it is possible to iterate in either direction through
  196194. ** the entries in a doclist, or to seek to a specific entry within a
  196195. ** doclist, without loading it into memory.
  196196. **
  196197. ** * large doclists that span many pages have associated "doclist index"
  196198. ** records that contain a copy of the first rowid on each page spanned by
  196199. ** the doclist. This is used to speed up seek operations, and merges of
  196200. ** large doclists with very small doclists.
  196201. **
  196202. ** * extra fields in the "structure record" record the state of ongoing
  196203. ** incremental merge operations.
  196204. **
  196205. */
  196206. #define FTS5_OPT_WORK_UNIT 1000 /* Number of leaf pages per optimize step */
  196207. #define FTS5_WORK_UNIT 64 /* Number of leaf pages in unit of work */
  196208. #define FTS5_MIN_DLIDX_SIZE 4 /* Add dlidx if this many empty pages */
  196209. #define FTS5_MAIN_PREFIX '0'
  196210. #if FTS5_MAX_PREFIX_INDEXES > 31
  196211. # error "FTS5_MAX_PREFIX_INDEXES is too large"
  196212. #endif
  196213. /*
  196214. ** Details:
  196215. **
  196216. ** The %_data table managed by this module,
  196217. **
  196218. ** CREATE TABLE %_data(id INTEGER PRIMARY KEY, block BLOB);
  196219. **
  196220. ** , contains the following 5 types of records. See the comments surrounding
  196221. ** the FTS5_*_ROWID macros below for a description of how %_data rowids are
  196222. ** assigned to each fo them.
  196223. **
  196224. ** 1. Structure Records:
  196225. **
  196226. ** The set of segments that make up an index - the index structure - are
  196227. ** recorded in a single record within the %_data table. The record consists
  196228. ** of a single 32-bit configuration cookie value followed by a list of
  196229. ** SQLite varints. If the FTS table features more than one index (because
  196230. ** there are one or more prefix indexes), it is guaranteed that all share
  196231. ** the same cookie value.
  196232. **
  196233. ** Immediately following the configuration cookie, the record begins with
  196234. ** three varints:
  196235. **
  196236. ** + number of levels,
  196237. ** + total number of segments on all levels,
  196238. ** + value of write counter.
  196239. **
  196240. ** Then, for each level from 0 to nMax:
  196241. **
  196242. ** + number of input segments in ongoing merge.
  196243. ** + total number of segments in level.
  196244. ** + for each segment from oldest to newest:
  196245. ** + segment id (always > 0)
  196246. ** + first leaf page number (often 1, always greater than 0)
  196247. ** + final leaf page number
  196248. **
  196249. ** 2. The Averages Record:
  196250. **
  196251. ** A single record within the %_data table. The data is a list of varints.
  196252. ** The first value is the number of rows in the index. Then, for each column
  196253. ** from left to right, the total number of tokens in the column for all
  196254. ** rows of the table.
  196255. **
  196256. ** 3. Segment leaves:
  196257. **
  196258. ** TERM/DOCLIST FORMAT:
  196259. **
  196260. ** Most of each segment leaf is taken up by term/doclist data. The
  196261. ** general format of term/doclist, starting with the first term
  196262. ** on the leaf page, is:
  196263. **
  196264. ** varint : size of first term
  196265. ** blob: first term data
  196266. ** doclist: first doclist
  196267. ** zero-or-more {
  196268. ** varint: number of bytes in common with previous term
  196269. ** varint: number of bytes of new term data (nNew)
  196270. ** blob: nNew bytes of new term data
  196271. ** doclist: next doclist
  196272. ** }
  196273. **
  196274. ** doclist format:
  196275. **
  196276. ** varint: first rowid
  196277. ** poslist: first poslist
  196278. ** zero-or-more {
  196279. ** varint: rowid delta (always > 0)
  196280. ** poslist: next poslist
  196281. ** }
  196282. **
  196283. ** poslist format:
  196284. **
  196285. ** varint: size of poslist in bytes multiplied by 2, not including
  196286. ** this field. Plus 1 if this entry carries the "delete" flag.
  196287. ** collist: collist for column 0
  196288. ** zero-or-more {
  196289. ** 0x01 byte
  196290. ** varint: column number (I)
  196291. ** collist: collist for column I
  196292. ** }
  196293. **
  196294. ** collist format:
  196295. **
  196296. ** varint: first offset + 2
  196297. ** zero-or-more {
  196298. ** varint: offset delta + 2
  196299. ** }
  196300. **
  196301. ** PAGE FORMAT
  196302. **
  196303. ** Each leaf page begins with a 4-byte header containing 2 16-bit
  196304. ** unsigned integer fields in big-endian format. They are:
  196305. **
  196306. ** * The byte offset of the first rowid on the page, if it exists
  196307. ** and occurs before the first term (otherwise 0).
  196308. **
  196309. ** * The byte offset of the start of the page footer. If the page
  196310. ** footer is 0 bytes in size, then this field is the same as the
  196311. ** size of the leaf page in bytes.
  196312. **
  196313. ** The page footer consists of a single varint for each term located
  196314. ** on the page. Each varint is the byte offset of the current term
  196315. ** within the page, delta-compressed against the previous value. In
  196316. ** other words, the first varint in the footer is the byte offset of
  196317. ** the first term, the second is the byte offset of the second less that
  196318. ** of the first, and so on.
  196319. **
  196320. ** The term/doclist format described above is accurate if the entire
  196321. ** term/doclist data fits on a single leaf page. If this is not the case,
  196322. ** the format is changed in two ways:
  196323. **
  196324. ** + if the first rowid on a page occurs before the first term, it
  196325. ** is stored as a literal value:
  196326. **
  196327. ** varint: first rowid
  196328. **
  196329. ** + the first term on each page is stored in the same way as the
  196330. ** very first term of the segment:
  196331. **
  196332. ** varint : size of first term
  196333. ** blob: first term data
  196334. **
  196335. ** 5. Segment doclist indexes:
  196336. **
  196337. ** Doclist indexes are themselves b-trees, however they usually consist of
  196338. ** a single leaf record only. The format of each doclist index leaf page
  196339. ** is:
  196340. **
  196341. ** * Flags byte. Bits are:
  196342. ** 0x01: Clear if leaf is also the root page, otherwise set.
  196343. **
  196344. ** * Page number of fts index leaf page. As a varint.
  196345. **
  196346. ** * First rowid on page indicated by previous field. As a varint.
  196347. **
  196348. ** * A list of varints, one for each subsequent termless page. A
  196349. ** positive delta if the termless page contains at least one rowid,
  196350. ** or an 0x00 byte otherwise.
  196351. **
  196352. ** Internal doclist index nodes are:
  196353. **
  196354. ** * Flags byte. Bits are:
  196355. ** 0x01: Clear for root page, otherwise set.
  196356. **
  196357. ** * Page number of first child page. As a varint.
  196358. **
  196359. ** * Copy of first rowid on page indicated by previous field. As a varint.
  196360. **
  196361. ** * A list of delta-encoded varints - the first rowid on each subsequent
  196362. ** child page.
  196363. **
  196364. */
  196365. /*
  196366. ** Rowids for the averages and structure records in the %_data table.
  196367. */
  196368. #define FTS5_AVERAGES_ROWID 1 /* Rowid used for the averages record */
  196369. #define FTS5_STRUCTURE_ROWID 10 /* The structure record */
  196370. /*
  196371. ** Macros determining the rowids used by segment leaves and dlidx leaves
  196372. ** and nodes. All nodes and leaves are stored in the %_data table with large
  196373. ** positive rowids.
  196374. **
  196375. ** Each segment has a unique non-zero 16-bit id.
  196376. **
  196377. ** The rowid for each segment leaf is found by passing the segment id and
  196378. ** the leaf page number to the FTS5_SEGMENT_ROWID macro. Leaves are numbered
  196379. ** sequentially starting from 1.
  196380. */
  196381. #define FTS5_DATA_ID_B 16 /* Max seg id number 65535 */
  196382. #define FTS5_DATA_DLI_B 1 /* Doclist-index flag (1 bit) */
  196383. #define FTS5_DATA_HEIGHT_B 5 /* Max dlidx tree height of 32 */
  196384. #define FTS5_DATA_PAGE_B 31 /* Max page number of 2147483648 */
  196385. #define fts5_dri(segid, dlidx, height, pgno) ( \
  196386. ((i64)(segid) << (FTS5_DATA_PAGE_B+FTS5_DATA_HEIGHT_B+FTS5_DATA_DLI_B)) + \
  196387. ((i64)(dlidx) << (FTS5_DATA_PAGE_B + FTS5_DATA_HEIGHT_B)) + \
  196388. ((i64)(height) << (FTS5_DATA_PAGE_B)) + \
  196389. ((i64)(pgno)) \
  196390. )
  196391. #define FTS5_SEGMENT_ROWID(segid, pgno) fts5_dri(segid, 0, 0, pgno)
  196392. #define FTS5_DLIDX_ROWID(segid, height, pgno) fts5_dri(segid, 1, height, pgno)
  196393. /*
  196394. ** Maximum segments permitted in a single index
  196395. */
  196396. #define FTS5_MAX_SEGMENT 2000
  196397. #ifdef SQLITE_DEBUG
  196398. static int sqlite3Fts5Corrupt() { return SQLITE_CORRUPT_VTAB; }
  196399. #endif
  196400. /*
  196401. ** Each time a blob is read from the %_data table, it is padded with this
  196402. ** many zero bytes. This makes it easier to decode the various record formats
  196403. ** without overreading if the records are corrupt.
  196404. */
  196405. #define FTS5_DATA_ZERO_PADDING 8
  196406. #define FTS5_DATA_PADDING 20
  196407. typedef struct Fts5Data Fts5Data;
  196408. typedef struct Fts5DlidxIter Fts5DlidxIter;
  196409. typedef struct Fts5DlidxLvl Fts5DlidxLvl;
  196410. typedef struct Fts5DlidxWriter Fts5DlidxWriter;
  196411. typedef struct Fts5Iter Fts5Iter;
  196412. typedef struct Fts5PageWriter Fts5PageWriter;
  196413. typedef struct Fts5SegIter Fts5SegIter;
  196414. typedef struct Fts5DoclistIter Fts5DoclistIter;
  196415. typedef struct Fts5SegWriter Fts5SegWriter;
  196416. typedef struct Fts5Structure Fts5Structure;
  196417. typedef struct Fts5StructureLevel Fts5StructureLevel;
  196418. typedef struct Fts5StructureSegment Fts5StructureSegment;
  196419. struct Fts5Data {
  196420. u8 *p; /* Pointer to buffer containing record */
  196421. int nn; /* Size of record in bytes */
  196422. int szLeaf; /* Size of leaf without page-index */
  196423. };
  196424. /*
  196425. ** One object per %_data table.
  196426. */
  196427. struct Fts5Index {
  196428. Fts5Config *pConfig; /* Virtual table configuration */
  196429. char *zDataTbl; /* Name of %_data table */
  196430. int nWorkUnit; /* Leaf pages in a "unit" of work */
  196431. /*
  196432. ** Variables related to the accumulation of tokens and doclists within the
  196433. ** in-memory hash tables before they are flushed to disk.
  196434. */
  196435. Fts5Hash *pHash; /* Hash table for in-memory data */
  196436. int nPendingData; /* Current bytes of pending data */
  196437. i64 iWriteRowid; /* Rowid for current doc being written */
  196438. int bDelete; /* Current write is a delete */
  196439. /* Error state. */
  196440. int rc; /* Current error code */
  196441. /* State used by the fts5DataXXX() functions. */
  196442. sqlite3_blob *pReader; /* RO incr-blob open on %_data table */
  196443. sqlite3_stmt *pWriter; /* "INSERT ... %_data VALUES(?,?)" */
  196444. sqlite3_stmt *pDeleter; /* "DELETE FROM %_data ... id>=? AND id<=?" */
  196445. sqlite3_stmt *pIdxWriter; /* "INSERT ... %_idx VALUES(?,?,?,?)" */
  196446. sqlite3_stmt *pIdxDeleter; /* "DELETE FROM %_idx WHERE segid=? */
  196447. sqlite3_stmt *pIdxSelect;
  196448. int nRead; /* Total number of blocks read */
  196449. sqlite3_stmt *pDataVersion;
  196450. i64 iStructVersion; /* data_version when pStruct read */
  196451. Fts5Structure *pStruct; /* Current db structure (or NULL) */
  196452. };
  196453. struct Fts5DoclistIter {
  196454. u8 *aEof; /* Pointer to 1 byte past end of doclist */
  196455. /* Output variables. aPoslist==0 at EOF */
  196456. i64 iRowid;
  196457. u8 *aPoslist;
  196458. int nPoslist;
  196459. int nSize;
  196460. };
  196461. /*
  196462. ** The contents of the "structure" record for each index are represented
  196463. ** using an Fts5Structure record in memory. Which uses instances of the
  196464. ** other Fts5StructureXXX types as components.
  196465. */
  196466. struct Fts5StructureSegment {
  196467. int iSegid; /* Segment id */
  196468. int pgnoFirst; /* First leaf page number in segment */
  196469. int pgnoLast; /* Last leaf page number in segment */
  196470. };
  196471. struct Fts5StructureLevel {
  196472. int nMerge; /* Number of segments in incr-merge */
  196473. int nSeg; /* Total number of segments on level */
  196474. Fts5StructureSegment *aSeg; /* Array of segments. aSeg[0] is oldest. */
  196475. };
  196476. struct Fts5Structure {
  196477. int nRef; /* Object reference count */
  196478. u64 nWriteCounter; /* Total leaves written to level 0 */
  196479. int nSegment; /* Total segments in this structure */
  196480. int nLevel; /* Number of levels in this index */
  196481. Fts5StructureLevel aLevel[1]; /* Array of nLevel level objects */
  196482. };
  196483. /*
  196484. ** An object of type Fts5SegWriter is used to write to segments.
  196485. */
  196486. struct Fts5PageWriter {
  196487. int pgno; /* Page number for this page */
  196488. int iPrevPgidx; /* Previous value written into pgidx */
  196489. Fts5Buffer buf; /* Buffer containing leaf data */
  196490. Fts5Buffer pgidx; /* Buffer containing page-index */
  196491. Fts5Buffer term; /* Buffer containing previous term on page */
  196492. };
  196493. struct Fts5DlidxWriter {
  196494. int pgno; /* Page number for this page */
  196495. int bPrevValid; /* True if iPrev is valid */
  196496. i64 iPrev; /* Previous rowid value written to page */
  196497. Fts5Buffer buf; /* Buffer containing page data */
  196498. };
  196499. struct Fts5SegWriter {
  196500. int iSegid; /* Segid to write to */
  196501. Fts5PageWriter writer; /* PageWriter object */
  196502. i64 iPrevRowid; /* Previous rowid written to current leaf */
  196503. u8 bFirstRowidInDoclist; /* True if next rowid is first in doclist */
  196504. u8 bFirstRowidInPage; /* True if next rowid is first in page */
  196505. /* TODO1: Can use (writer.pgidx.n==0) instead of bFirstTermInPage */
  196506. u8 bFirstTermInPage; /* True if next term will be first in leaf */
  196507. int nLeafWritten; /* Number of leaf pages written */
  196508. int nEmpty; /* Number of contiguous term-less nodes */
  196509. int nDlidx; /* Allocated size of aDlidx[] array */
  196510. Fts5DlidxWriter *aDlidx; /* Array of Fts5DlidxWriter objects */
  196511. /* Values to insert into the %_idx table */
  196512. Fts5Buffer btterm; /* Next term to insert into %_idx table */
  196513. int iBtPage; /* Page number corresponding to btterm */
  196514. };
  196515. typedef struct Fts5CResult Fts5CResult;
  196516. struct Fts5CResult {
  196517. u16 iFirst; /* aSeg[] index of firstest iterator */
  196518. u8 bTermEq; /* True if the terms are equal */
  196519. };
  196520. /*
  196521. ** Object for iterating through a single segment, visiting each term/rowid
  196522. ** pair in the segment.
  196523. **
  196524. ** pSeg:
  196525. ** The segment to iterate through.
  196526. **
  196527. ** iLeafPgno:
  196528. ** Current leaf page number within segment.
  196529. **
  196530. ** iLeafOffset:
  196531. ** Byte offset within the current leaf that is the first byte of the
  196532. ** position list data (one byte passed the position-list size field).
  196533. ** rowid field of the current entry. Usually this is the size field of the
  196534. ** position list data. The exception is if the rowid for the current entry
  196535. ** is the last thing on the leaf page.
  196536. **
  196537. ** pLeaf:
  196538. ** Buffer containing current leaf page data. Set to NULL at EOF.
  196539. **
  196540. ** iTermLeafPgno, iTermLeafOffset:
  196541. ** Leaf page number containing the last term read from the segment. And
  196542. ** the offset immediately following the term data.
  196543. **
  196544. ** flags:
  196545. ** Mask of FTS5_SEGITER_XXX values. Interpreted as follows:
  196546. **
  196547. ** FTS5_SEGITER_ONETERM:
  196548. ** If set, set the iterator to point to EOF after the current doclist
  196549. ** has been exhausted. Do not proceed to the next term in the segment.
  196550. **
  196551. ** FTS5_SEGITER_REVERSE:
  196552. ** This flag is only ever set if FTS5_SEGITER_ONETERM is also set. If
  196553. ** it is set, iterate through rowid in descending order instead of the
  196554. ** default ascending order.
  196555. **
  196556. ** iRowidOffset/nRowidOffset/aRowidOffset:
  196557. ** These are used if the FTS5_SEGITER_REVERSE flag is set.
  196558. **
  196559. ** For each rowid on the page corresponding to the current term, the
  196560. ** corresponding aRowidOffset[] entry is set to the byte offset of the
  196561. ** start of the "position-list-size" field within the page.
  196562. **
  196563. ** iTermIdx:
  196564. ** Index of current term on iTermLeafPgno.
  196565. */
  196566. struct Fts5SegIter {
  196567. Fts5StructureSegment *pSeg; /* Segment to iterate through */
  196568. int flags; /* Mask of configuration flags */
  196569. int iLeafPgno; /* Current leaf page number */
  196570. Fts5Data *pLeaf; /* Current leaf data */
  196571. Fts5Data *pNextLeaf; /* Leaf page (iLeafPgno+1) */
  196572. int iLeafOffset; /* Byte offset within current leaf */
  196573. /* Next method */
  196574. void (*xNext)(Fts5Index*, Fts5SegIter*, int*);
  196575. /* The page and offset from which the current term was read. The offset
  196576. ** is the offset of the first rowid in the current doclist. */
  196577. int iTermLeafPgno;
  196578. int iTermLeafOffset;
  196579. int iPgidxOff; /* Next offset in pgidx */
  196580. int iEndofDoclist;
  196581. /* The following are only used if the FTS5_SEGITER_REVERSE flag is set. */
  196582. int iRowidOffset; /* Current entry in aRowidOffset[] */
  196583. int nRowidOffset; /* Allocated size of aRowidOffset[] array */
  196584. int *aRowidOffset; /* Array of offset to rowid fields */
  196585. Fts5DlidxIter *pDlidx; /* If there is a doclist-index */
  196586. /* Variables populated based on current entry. */
  196587. Fts5Buffer term; /* Current term */
  196588. i64 iRowid; /* Current rowid */
  196589. int nPos; /* Number of bytes in current position list */
  196590. u8 bDel; /* True if the delete flag is set */
  196591. };
  196592. /*
  196593. ** Argument is a pointer to an Fts5Data structure that contains a
  196594. ** leaf page.
  196595. */
  196596. #define ASSERT_SZLEAF_OK(x) assert( \
  196597. (x)->szLeaf==(x)->nn || (x)->szLeaf==fts5GetU16(&(x)->p[2]) \
  196598. )
  196599. #define FTS5_SEGITER_ONETERM 0x01
  196600. #define FTS5_SEGITER_REVERSE 0x02
  196601. /*
  196602. ** Argument is a pointer to an Fts5Data structure that contains a leaf
  196603. ** page. This macro evaluates to true if the leaf contains no terms, or
  196604. ** false if it contains at least one term.
  196605. */
  196606. #define fts5LeafIsTermless(x) ((x)->szLeaf >= (x)->nn)
  196607. #define fts5LeafTermOff(x, i) (fts5GetU16(&(x)->p[(x)->szLeaf + (i)*2]))
  196608. #define fts5LeafFirstRowidOff(x) (fts5GetU16((x)->p))
  196609. /*
  196610. ** Object for iterating through the merged results of one or more segments,
  196611. ** visiting each term/rowid pair in the merged data.
  196612. **
  196613. ** nSeg is always a power of two greater than or equal to the number of
  196614. ** segments that this object is merging data from. Both the aSeg[] and
  196615. ** aFirst[] arrays are sized at nSeg entries. The aSeg[] array is padded
  196616. ** with zeroed objects - these are handled as if they were iterators opened
  196617. ** on empty segments.
  196618. **
  196619. ** The results of comparing segments aSeg[N] and aSeg[N+1], where N is an
  196620. ** even number, is stored in aFirst[(nSeg+N)/2]. The "result" of the
  196621. ** comparison in this context is the index of the iterator that currently
  196622. ** points to the smaller term/rowid combination. Iterators at EOF are
  196623. ** considered to be greater than all other iterators.
  196624. **
  196625. ** aFirst[1] contains the index in aSeg[] of the iterator that points to
  196626. ** the smallest key overall. aFirst[0] is unused.
  196627. **
  196628. ** poslist:
  196629. ** Used by sqlite3Fts5IterPoslist() when the poslist needs to be buffered.
  196630. ** There is no way to tell if this is populated or not.
  196631. */
  196632. struct Fts5Iter {
  196633. Fts5IndexIter base; /* Base class containing output vars */
  196634. Fts5Index *pIndex; /* Index that owns this iterator */
  196635. Fts5Buffer poslist; /* Buffer containing current poslist */
  196636. Fts5Colset *pColset; /* Restrict matches to these columns */
  196637. /* Invoked to set output variables. */
  196638. void (*xSetOutputs)(Fts5Iter*, Fts5SegIter*);
  196639. int nSeg; /* Size of aSeg[] array */
  196640. int bRev; /* True to iterate in reverse order */
  196641. u8 bSkipEmpty; /* True to skip deleted entries */
  196642. i64 iSwitchRowid; /* Firstest rowid of other than aFirst[1] */
  196643. Fts5CResult *aFirst; /* Current merge state (see above) */
  196644. Fts5SegIter aSeg[1]; /* Array of segment iterators */
  196645. };
  196646. /*
  196647. ** An instance of the following type is used to iterate through the contents
  196648. ** of a doclist-index record.
  196649. **
  196650. ** pData:
  196651. ** Record containing the doclist-index data.
  196652. **
  196653. ** bEof:
  196654. ** Set to true once iterator has reached EOF.
  196655. **
  196656. ** iOff:
  196657. ** Set to the current offset within record pData.
  196658. */
  196659. struct Fts5DlidxLvl {
  196660. Fts5Data *pData; /* Data for current page of this level */
  196661. int iOff; /* Current offset into pData */
  196662. int bEof; /* At EOF already */
  196663. int iFirstOff; /* Used by reverse iterators */
  196664. /* Output variables */
  196665. int iLeafPgno; /* Page number of current leaf page */
  196666. i64 iRowid; /* First rowid on leaf iLeafPgno */
  196667. };
  196668. struct Fts5DlidxIter {
  196669. int nLvl;
  196670. int iSegid;
  196671. Fts5DlidxLvl aLvl[1];
  196672. };
  196673. static void fts5PutU16(u8 *aOut, u16 iVal){
  196674. aOut[0] = (iVal>>8);
  196675. aOut[1] = (iVal&0xFF);
  196676. }
  196677. static u16 fts5GetU16(const u8 *aIn){
  196678. return ((u16)aIn[0] << 8) + aIn[1];
  196679. }
  196680. /*
  196681. ** Allocate and return a buffer at least nByte bytes in size.
  196682. **
  196683. ** If an OOM error is encountered, return NULL and set the error code in
  196684. ** the Fts5Index handle passed as the first argument.
  196685. */
  196686. static void *fts5IdxMalloc(Fts5Index *p, sqlite3_int64 nByte){
  196687. return sqlite3Fts5MallocZero(&p->rc, nByte);
  196688. }
  196689. /*
  196690. ** Compare the contents of the pLeft buffer with the pRight/nRight blob.
  196691. **
  196692. ** Return -ve if pLeft is smaller than pRight, 0 if they are equal or
  196693. ** +ve if pRight is smaller than pLeft. In other words:
  196694. **
  196695. ** res = *pLeft - *pRight
  196696. */
  196697. #ifdef SQLITE_DEBUG
  196698. static int fts5BufferCompareBlob(
  196699. Fts5Buffer *pLeft, /* Left hand side of comparison */
  196700. const u8 *pRight, int nRight /* Right hand side of comparison */
  196701. ){
  196702. int nCmp = MIN(pLeft->n, nRight);
  196703. int res = memcmp(pLeft->p, pRight, nCmp);
  196704. return (res==0 ? (pLeft->n - nRight) : res);
  196705. }
  196706. #endif
  196707. /*
  196708. ** Compare the contents of the two buffers using memcmp(). If one buffer
  196709. ** is a prefix of the other, it is considered the lesser.
  196710. **
  196711. ** Return -ve if pLeft is smaller than pRight, 0 if they are equal or
  196712. ** +ve if pRight is smaller than pLeft. In other words:
  196713. **
  196714. ** res = *pLeft - *pRight
  196715. */
  196716. static int fts5BufferCompare(Fts5Buffer *pLeft, Fts5Buffer *pRight){
  196717. int nCmp = MIN(pLeft->n, pRight->n);
  196718. int res = fts5Memcmp(pLeft->p, pRight->p, nCmp);
  196719. return (res==0 ? (pLeft->n - pRight->n) : res);
  196720. }
  196721. static int fts5LeafFirstTermOff(Fts5Data *pLeaf){
  196722. int ret;
  196723. fts5GetVarint32(&pLeaf->p[pLeaf->szLeaf], ret);
  196724. return ret;
  196725. }
  196726. /*
  196727. ** Close the read-only blob handle, if it is open.
  196728. */
  196729. static void fts5CloseReader(Fts5Index *p){
  196730. if( p->pReader ){
  196731. sqlite3_blob *pReader = p->pReader;
  196732. p->pReader = 0;
  196733. sqlite3_blob_close(pReader);
  196734. }
  196735. }
  196736. /*
  196737. ** Retrieve a record from the %_data table.
  196738. **
  196739. ** If an error occurs, NULL is returned and an error left in the
  196740. ** Fts5Index object.
  196741. */
  196742. static Fts5Data *fts5DataRead(Fts5Index *p, i64 iRowid){
  196743. Fts5Data *pRet = 0;
  196744. if( p->rc==SQLITE_OK ){
  196745. int rc = SQLITE_OK;
  196746. if( p->pReader ){
  196747. /* This call may return SQLITE_ABORT if there has been a savepoint
  196748. ** rollback since it was last used. In this case a new blob handle
  196749. ** is required. */
  196750. sqlite3_blob *pBlob = p->pReader;
  196751. p->pReader = 0;
  196752. rc = sqlite3_blob_reopen(pBlob, iRowid);
  196753. assert( p->pReader==0 );
  196754. p->pReader = pBlob;
  196755. if( rc!=SQLITE_OK ){
  196756. fts5CloseReader(p);
  196757. }
  196758. if( rc==SQLITE_ABORT ) rc = SQLITE_OK;
  196759. }
  196760. /* If the blob handle is not open at this point, open it and seek
  196761. ** to the requested entry. */
  196762. if( p->pReader==0 && rc==SQLITE_OK ){
  196763. Fts5Config *pConfig = p->pConfig;
  196764. rc = sqlite3_blob_open(pConfig->db,
  196765. pConfig->zDb, p->zDataTbl, "block", iRowid, 0, &p->pReader
  196766. );
  196767. }
  196768. /* If either of the sqlite3_blob_open() or sqlite3_blob_reopen() calls
  196769. ** above returned SQLITE_ERROR, return SQLITE_CORRUPT_VTAB instead.
  196770. ** All the reasons those functions might return SQLITE_ERROR - missing
  196771. ** table, missing row, non-blob/text in block column - indicate
  196772. ** backing store corruption. */
  196773. if( rc==SQLITE_ERROR ) rc = FTS5_CORRUPT;
  196774. if( rc==SQLITE_OK ){
  196775. u8 *aOut = 0; /* Read blob data into this buffer */
  196776. int nByte = sqlite3_blob_bytes(p->pReader);
  196777. sqlite3_int64 nAlloc = sizeof(Fts5Data) + nByte + FTS5_DATA_PADDING;
  196778. pRet = (Fts5Data*)sqlite3_malloc64(nAlloc);
  196779. if( pRet ){
  196780. pRet->nn = nByte;
  196781. aOut = pRet->p = (u8*)&pRet[1];
  196782. }else{
  196783. rc = SQLITE_NOMEM;
  196784. }
  196785. if( rc==SQLITE_OK ){
  196786. rc = sqlite3_blob_read(p->pReader, aOut, nByte, 0);
  196787. }
  196788. if( rc!=SQLITE_OK ){
  196789. sqlite3_free(pRet);
  196790. pRet = 0;
  196791. }else{
  196792. /* TODO1: Fix this */
  196793. pRet->p[nByte] = 0x00;
  196794. pRet->szLeaf = fts5GetU16(&pRet->p[2]);
  196795. }
  196796. }
  196797. p->rc = rc;
  196798. p->nRead++;
  196799. }
  196800. assert( (pRet==0)==(p->rc!=SQLITE_OK) );
  196801. return pRet;
  196802. }
  196803. /*
  196804. ** Release a reference to data record returned by an earlier call to
  196805. ** fts5DataRead().
  196806. */
  196807. static void fts5DataRelease(Fts5Data *pData){
  196808. sqlite3_free(pData);
  196809. }
  196810. static Fts5Data *fts5LeafRead(Fts5Index *p, i64 iRowid){
  196811. Fts5Data *pRet = fts5DataRead(p, iRowid);
  196812. if( pRet ){
  196813. if( pRet->szLeaf>pRet->nn ){
  196814. p->rc = FTS5_CORRUPT;
  196815. fts5DataRelease(pRet);
  196816. pRet = 0;
  196817. }
  196818. }
  196819. return pRet;
  196820. }
  196821. static int fts5IndexPrepareStmt(
  196822. Fts5Index *p,
  196823. sqlite3_stmt **ppStmt,
  196824. char *zSql
  196825. ){
  196826. if( p->rc==SQLITE_OK ){
  196827. if( zSql ){
  196828. p->rc = sqlite3_prepare_v3(p->pConfig->db, zSql, -1,
  196829. SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_NO_VTAB,
  196830. ppStmt, 0);
  196831. }else{
  196832. p->rc = SQLITE_NOMEM;
  196833. }
  196834. }
  196835. sqlite3_free(zSql);
  196836. return p->rc;
  196837. }
  196838. /*
  196839. ** INSERT OR REPLACE a record into the %_data table.
  196840. */
  196841. static void fts5DataWrite(Fts5Index *p, i64 iRowid, const u8 *pData, int nData){
  196842. if( p->rc!=SQLITE_OK ) return;
  196843. if( p->pWriter==0 ){
  196844. Fts5Config *pConfig = p->pConfig;
  196845. fts5IndexPrepareStmt(p, &p->pWriter, sqlite3_mprintf(
  196846. "REPLACE INTO '%q'.'%q_data'(id, block) VALUES(?,?)",
  196847. pConfig->zDb, pConfig->zName
  196848. ));
  196849. if( p->rc ) return;
  196850. }
  196851. sqlite3_bind_int64(p->pWriter, 1, iRowid);
  196852. sqlite3_bind_blob(p->pWriter, 2, pData, nData, SQLITE_STATIC);
  196853. sqlite3_step(p->pWriter);
  196854. p->rc = sqlite3_reset(p->pWriter);
  196855. sqlite3_bind_null(p->pWriter, 2);
  196856. }
  196857. /*
  196858. ** Execute the following SQL:
  196859. **
  196860. ** DELETE FROM %_data WHERE id BETWEEN $iFirst AND $iLast
  196861. */
  196862. static void fts5DataDelete(Fts5Index *p, i64 iFirst, i64 iLast){
  196863. if( p->rc!=SQLITE_OK ) return;
  196864. if( p->pDeleter==0 ){
  196865. Fts5Config *pConfig = p->pConfig;
  196866. char *zSql = sqlite3_mprintf(
  196867. "DELETE FROM '%q'.'%q_data' WHERE id>=? AND id<=?",
  196868. pConfig->zDb, pConfig->zName
  196869. );
  196870. if( fts5IndexPrepareStmt(p, &p->pDeleter, zSql) ) return;
  196871. }
  196872. sqlite3_bind_int64(p->pDeleter, 1, iFirst);
  196873. sqlite3_bind_int64(p->pDeleter, 2, iLast);
  196874. sqlite3_step(p->pDeleter);
  196875. p->rc = sqlite3_reset(p->pDeleter);
  196876. }
  196877. /*
  196878. ** Remove all records associated with segment iSegid.
  196879. */
  196880. static void fts5DataRemoveSegment(Fts5Index *p, int iSegid){
  196881. i64 iFirst = FTS5_SEGMENT_ROWID(iSegid, 0);
  196882. i64 iLast = FTS5_SEGMENT_ROWID(iSegid+1, 0)-1;
  196883. fts5DataDelete(p, iFirst, iLast);
  196884. if( p->pIdxDeleter==0 ){
  196885. Fts5Config *pConfig = p->pConfig;
  196886. fts5IndexPrepareStmt(p, &p->pIdxDeleter, sqlite3_mprintf(
  196887. "DELETE FROM '%q'.'%q_idx' WHERE segid=?",
  196888. pConfig->zDb, pConfig->zName
  196889. ));
  196890. }
  196891. if( p->rc==SQLITE_OK ){
  196892. sqlite3_bind_int(p->pIdxDeleter, 1, iSegid);
  196893. sqlite3_step(p->pIdxDeleter);
  196894. p->rc = sqlite3_reset(p->pIdxDeleter);
  196895. }
  196896. }
  196897. /*
  196898. ** Release a reference to an Fts5Structure object returned by an earlier
  196899. ** call to fts5StructureRead() or fts5StructureDecode().
  196900. */
  196901. static void fts5StructureRelease(Fts5Structure *pStruct){
  196902. if( pStruct && 0>=(--pStruct->nRef) ){
  196903. int i;
  196904. assert( pStruct->nRef==0 );
  196905. for(i=0; i<pStruct->nLevel; i++){
  196906. sqlite3_free(pStruct->aLevel[i].aSeg);
  196907. }
  196908. sqlite3_free(pStruct);
  196909. }
  196910. }
  196911. static void fts5StructureRef(Fts5Structure *pStruct){
  196912. pStruct->nRef++;
  196913. }
  196914. /*
  196915. ** Deserialize and return the structure record currently stored in serialized
  196916. ** form within buffer pData/nData.
  196917. **
  196918. ** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array
  196919. ** are over-allocated by one slot. This allows the structure contents
  196920. ** to be more easily edited.
  196921. **
  196922. ** If an error occurs, *ppOut is set to NULL and an SQLite error code
  196923. ** returned. Otherwise, *ppOut is set to point to the new object and
  196924. ** SQLITE_OK returned.
  196925. */
  196926. static int fts5StructureDecode(
  196927. const u8 *pData, /* Buffer containing serialized structure */
  196928. int nData, /* Size of buffer pData in bytes */
  196929. int *piCookie, /* Configuration cookie value */
  196930. Fts5Structure **ppOut /* OUT: Deserialized object */
  196931. ){
  196932. int rc = SQLITE_OK;
  196933. int i = 0;
  196934. int iLvl;
  196935. int nLevel = 0;
  196936. int nSegment = 0;
  196937. sqlite3_int64 nByte; /* Bytes of space to allocate at pRet */
  196938. Fts5Structure *pRet = 0; /* Structure object to return */
  196939. /* Grab the cookie value */
  196940. if( piCookie ) *piCookie = sqlite3Fts5Get32(pData);
  196941. i = 4;
  196942. /* Read the total number of levels and segments from the start of the
  196943. ** structure record. */
  196944. i += fts5GetVarint32(&pData[i], nLevel);
  196945. i += fts5GetVarint32(&pData[i], nSegment);
  196946. if( nLevel>FTS5_MAX_SEGMENT || nLevel<0
  196947. || nSegment>FTS5_MAX_SEGMENT || nSegment<0
  196948. ){
  196949. return FTS5_CORRUPT;
  196950. }
  196951. nByte = (
  196952. sizeof(Fts5Structure) + /* Main structure */
  196953. sizeof(Fts5StructureLevel) * (nLevel-1) /* aLevel[] array */
  196954. );
  196955. pRet = (Fts5Structure*)sqlite3Fts5MallocZero(&rc, nByte);
  196956. if( pRet ){
  196957. pRet->nRef = 1;
  196958. pRet->nLevel = nLevel;
  196959. pRet->nSegment = nSegment;
  196960. i += sqlite3Fts5GetVarint(&pData[i], &pRet->nWriteCounter);
  196961. for(iLvl=0; rc==SQLITE_OK && iLvl<nLevel; iLvl++){
  196962. Fts5StructureLevel *pLvl = &pRet->aLevel[iLvl];
  196963. int nTotal = 0;
  196964. int iSeg;
  196965. if( i>=nData ){
  196966. rc = FTS5_CORRUPT;
  196967. }else{
  196968. i += fts5GetVarint32(&pData[i], pLvl->nMerge);
  196969. i += fts5GetVarint32(&pData[i], nTotal);
  196970. if( nTotal<pLvl->nMerge ) rc = FTS5_CORRUPT;
  196971. pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&rc,
  196972. nTotal * sizeof(Fts5StructureSegment)
  196973. );
  196974. nSegment -= nTotal;
  196975. }
  196976. if( rc==SQLITE_OK ){
  196977. pLvl->nSeg = nTotal;
  196978. for(iSeg=0; iSeg<nTotal; iSeg++){
  196979. Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
  196980. if( i>=nData ){
  196981. rc = FTS5_CORRUPT;
  196982. break;
  196983. }
  196984. i += fts5GetVarint32(&pData[i], pSeg->iSegid);
  196985. i += fts5GetVarint32(&pData[i], pSeg->pgnoFirst);
  196986. i += fts5GetVarint32(&pData[i], pSeg->pgnoLast);
  196987. if( pSeg->pgnoLast<pSeg->pgnoFirst ){
  196988. rc = FTS5_CORRUPT;
  196989. break;
  196990. }
  196991. }
  196992. if( iLvl>0 && pLvl[-1].nMerge && nTotal==0 ) rc = FTS5_CORRUPT;
  196993. if( iLvl==nLevel-1 && pLvl->nMerge ) rc = FTS5_CORRUPT;
  196994. }
  196995. }
  196996. if( nSegment!=0 && rc==SQLITE_OK ) rc = FTS5_CORRUPT;
  196997. if( rc!=SQLITE_OK ){
  196998. fts5StructureRelease(pRet);
  196999. pRet = 0;
  197000. }
  197001. }
  197002. *ppOut = pRet;
  197003. return rc;
  197004. }
  197005. /*
  197006. **
  197007. */
  197008. static void fts5StructureAddLevel(int *pRc, Fts5Structure **ppStruct){
  197009. if( *pRc==SQLITE_OK ){
  197010. Fts5Structure *pStruct = *ppStruct;
  197011. int nLevel = pStruct->nLevel;
  197012. sqlite3_int64 nByte = (
  197013. sizeof(Fts5Structure) + /* Main structure */
  197014. sizeof(Fts5StructureLevel) * (nLevel+1) /* aLevel[] array */
  197015. );
  197016. pStruct = sqlite3_realloc64(pStruct, nByte);
  197017. if( pStruct ){
  197018. memset(&pStruct->aLevel[nLevel], 0, sizeof(Fts5StructureLevel));
  197019. pStruct->nLevel++;
  197020. *ppStruct = pStruct;
  197021. }else{
  197022. *pRc = SQLITE_NOMEM;
  197023. }
  197024. }
  197025. }
  197026. /*
  197027. ** Extend level iLvl so that there is room for at least nExtra more
  197028. ** segments.
  197029. */
  197030. static void fts5StructureExtendLevel(
  197031. int *pRc,
  197032. Fts5Structure *pStruct,
  197033. int iLvl,
  197034. int nExtra,
  197035. int bInsert
  197036. ){
  197037. if( *pRc==SQLITE_OK ){
  197038. Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
  197039. Fts5StructureSegment *aNew;
  197040. sqlite3_int64 nByte;
  197041. nByte = (pLvl->nSeg + nExtra) * sizeof(Fts5StructureSegment);
  197042. aNew = sqlite3_realloc64(pLvl->aSeg, nByte);
  197043. if( aNew ){
  197044. if( bInsert==0 ){
  197045. memset(&aNew[pLvl->nSeg], 0, sizeof(Fts5StructureSegment) * nExtra);
  197046. }else{
  197047. int nMove = pLvl->nSeg * sizeof(Fts5StructureSegment);
  197048. memmove(&aNew[nExtra], aNew, nMove);
  197049. memset(aNew, 0, sizeof(Fts5StructureSegment) * nExtra);
  197050. }
  197051. pLvl->aSeg = aNew;
  197052. }else{
  197053. *pRc = SQLITE_NOMEM;
  197054. }
  197055. }
  197056. }
  197057. static Fts5Structure *fts5StructureReadUncached(Fts5Index *p){
  197058. Fts5Structure *pRet = 0;
  197059. Fts5Config *pConfig = p->pConfig;
  197060. int iCookie; /* Configuration cookie */
  197061. Fts5Data *pData;
  197062. pData = fts5DataRead(p, FTS5_STRUCTURE_ROWID);
  197063. if( p->rc==SQLITE_OK ){
  197064. /* TODO: Do we need this if the leaf-index is appended? Probably... */
  197065. memset(&pData->p[pData->nn], 0, FTS5_DATA_PADDING);
  197066. p->rc = fts5StructureDecode(pData->p, pData->nn, &iCookie, &pRet);
  197067. if( p->rc==SQLITE_OK && (pConfig->pgsz==0 || pConfig->iCookie!=iCookie) ){
  197068. p->rc = sqlite3Fts5ConfigLoad(pConfig, iCookie);
  197069. }
  197070. fts5DataRelease(pData);
  197071. if( p->rc!=SQLITE_OK ){
  197072. fts5StructureRelease(pRet);
  197073. pRet = 0;
  197074. }
  197075. }
  197076. return pRet;
  197077. }
  197078. static i64 fts5IndexDataVersion(Fts5Index *p){
  197079. i64 iVersion = 0;
  197080. if( p->rc==SQLITE_OK ){
  197081. if( p->pDataVersion==0 ){
  197082. p->rc = fts5IndexPrepareStmt(p, &p->pDataVersion,
  197083. sqlite3_mprintf("PRAGMA %Q.data_version", p->pConfig->zDb)
  197084. );
  197085. if( p->rc ) return 0;
  197086. }
  197087. if( SQLITE_ROW==sqlite3_step(p->pDataVersion) ){
  197088. iVersion = sqlite3_column_int64(p->pDataVersion, 0);
  197089. }
  197090. p->rc = sqlite3_reset(p->pDataVersion);
  197091. }
  197092. return iVersion;
  197093. }
  197094. /*
  197095. ** Read, deserialize and return the structure record.
  197096. **
  197097. ** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array
  197098. ** are over-allocated as described for function fts5StructureDecode()
  197099. ** above.
  197100. **
  197101. ** If an error occurs, NULL is returned and an error code left in the
  197102. ** Fts5Index handle. If an error has already occurred when this function
  197103. ** is called, it is a no-op.
  197104. */
  197105. static Fts5Structure *fts5StructureRead(Fts5Index *p){
  197106. if( p->pStruct==0 ){
  197107. p->iStructVersion = fts5IndexDataVersion(p);
  197108. if( p->rc==SQLITE_OK ){
  197109. p->pStruct = fts5StructureReadUncached(p);
  197110. }
  197111. }
  197112. #if 0
  197113. else{
  197114. Fts5Structure *pTest = fts5StructureReadUncached(p);
  197115. if( pTest ){
  197116. int i, j;
  197117. assert_nc( p->pStruct->nSegment==pTest->nSegment );
  197118. assert_nc( p->pStruct->nLevel==pTest->nLevel );
  197119. for(i=0; i<pTest->nLevel; i++){
  197120. assert_nc( p->pStruct->aLevel[i].nMerge==pTest->aLevel[i].nMerge );
  197121. assert_nc( p->pStruct->aLevel[i].nSeg==pTest->aLevel[i].nSeg );
  197122. for(j=0; j<pTest->aLevel[i].nSeg; j++){
  197123. Fts5StructureSegment *p1 = &pTest->aLevel[i].aSeg[j];
  197124. Fts5StructureSegment *p2 = &p->pStruct->aLevel[i].aSeg[j];
  197125. assert_nc( p1->iSegid==p2->iSegid );
  197126. assert_nc( p1->pgnoFirst==p2->pgnoFirst );
  197127. assert_nc( p1->pgnoLast==p2->pgnoLast );
  197128. }
  197129. }
  197130. fts5StructureRelease(pTest);
  197131. }
  197132. }
  197133. #endif
  197134. if( p->rc!=SQLITE_OK ) return 0;
  197135. assert( p->iStructVersion!=0 );
  197136. assert( p->pStruct!=0 );
  197137. fts5StructureRef(p->pStruct);
  197138. return p->pStruct;
  197139. }
  197140. static void fts5StructureInvalidate(Fts5Index *p){
  197141. if( p->pStruct ){
  197142. fts5StructureRelease(p->pStruct);
  197143. p->pStruct = 0;
  197144. }
  197145. }
  197146. /*
  197147. ** Return the total number of segments in index structure pStruct. This
  197148. ** function is only ever used as part of assert() conditions.
  197149. */
  197150. #ifdef SQLITE_DEBUG
  197151. static int fts5StructureCountSegments(Fts5Structure *pStruct){
  197152. int nSegment = 0; /* Total number of segments */
  197153. if( pStruct ){
  197154. int iLvl; /* Used to iterate through levels */
  197155. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  197156. nSegment += pStruct->aLevel[iLvl].nSeg;
  197157. }
  197158. }
  197159. return nSegment;
  197160. }
  197161. #endif
  197162. #define fts5BufferSafeAppendBlob(pBuf, pBlob, nBlob) { \
  197163. assert( (pBuf)->nSpace>=((pBuf)->n+nBlob) ); \
  197164. memcpy(&(pBuf)->p[(pBuf)->n], pBlob, nBlob); \
  197165. (pBuf)->n += nBlob; \
  197166. }
  197167. #define fts5BufferSafeAppendVarint(pBuf, iVal) { \
  197168. (pBuf)->n += sqlite3Fts5PutVarint(&(pBuf)->p[(pBuf)->n], (iVal)); \
  197169. assert( (pBuf)->nSpace>=(pBuf)->n ); \
  197170. }
  197171. /*
  197172. ** Serialize and store the "structure" record.
  197173. **
  197174. ** If an error occurs, leave an error code in the Fts5Index object. If an
  197175. ** error has already occurred, this function is a no-op.
  197176. */
  197177. static void fts5StructureWrite(Fts5Index *p, Fts5Structure *pStruct){
  197178. if( p->rc==SQLITE_OK ){
  197179. Fts5Buffer buf; /* Buffer to serialize record into */
  197180. int iLvl; /* Used to iterate through levels */
  197181. int iCookie; /* Cookie value to store */
  197182. assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
  197183. memset(&buf, 0, sizeof(Fts5Buffer));
  197184. /* Append the current configuration cookie */
  197185. iCookie = p->pConfig->iCookie;
  197186. if( iCookie<0 ) iCookie = 0;
  197187. if( 0==sqlite3Fts5BufferSize(&p->rc, &buf, 4+9+9+9) ){
  197188. sqlite3Fts5Put32(buf.p, iCookie);
  197189. buf.n = 4;
  197190. fts5BufferSafeAppendVarint(&buf, pStruct->nLevel);
  197191. fts5BufferSafeAppendVarint(&buf, pStruct->nSegment);
  197192. fts5BufferSafeAppendVarint(&buf, (i64)pStruct->nWriteCounter);
  197193. }
  197194. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  197195. int iSeg; /* Used to iterate through segments */
  197196. Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
  197197. fts5BufferAppendVarint(&p->rc, &buf, pLvl->nMerge);
  197198. fts5BufferAppendVarint(&p->rc, &buf, pLvl->nSeg);
  197199. assert( pLvl->nMerge<=pLvl->nSeg );
  197200. for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
  197201. fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].iSegid);
  197202. fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].pgnoFirst);
  197203. fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].pgnoLast);
  197204. }
  197205. }
  197206. fts5DataWrite(p, FTS5_STRUCTURE_ROWID, buf.p, buf.n);
  197207. fts5BufferFree(&buf);
  197208. }
  197209. }
  197210. #if 0
  197211. static void fts5DebugStructure(int*,Fts5Buffer*,Fts5Structure*);
  197212. static void fts5PrintStructure(const char *zCaption, Fts5Structure *pStruct){
  197213. int rc = SQLITE_OK;
  197214. Fts5Buffer buf;
  197215. memset(&buf, 0, sizeof(buf));
  197216. fts5DebugStructure(&rc, &buf, pStruct);
  197217. fprintf(stdout, "%s: %s\n", zCaption, buf.p);
  197218. fflush(stdout);
  197219. fts5BufferFree(&buf);
  197220. }
  197221. #else
  197222. # define fts5PrintStructure(x,y)
  197223. #endif
  197224. static int fts5SegmentSize(Fts5StructureSegment *pSeg){
  197225. return 1 + pSeg->pgnoLast - pSeg->pgnoFirst;
  197226. }
  197227. /*
  197228. ** Return a copy of index structure pStruct. Except, promote as many
  197229. ** segments as possible to level iPromote. If an OOM occurs, NULL is
  197230. ** returned.
  197231. */
  197232. static void fts5StructurePromoteTo(
  197233. Fts5Index *p,
  197234. int iPromote,
  197235. int szPromote,
  197236. Fts5Structure *pStruct
  197237. ){
  197238. int il, is;
  197239. Fts5StructureLevel *pOut = &pStruct->aLevel[iPromote];
  197240. if( pOut->nMerge==0 ){
  197241. for(il=iPromote+1; il<pStruct->nLevel; il++){
  197242. Fts5StructureLevel *pLvl = &pStruct->aLevel[il];
  197243. if( pLvl->nMerge ) return;
  197244. for(is=pLvl->nSeg-1; is>=0; is--){
  197245. int sz = fts5SegmentSize(&pLvl->aSeg[is]);
  197246. if( sz>szPromote ) return;
  197247. fts5StructureExtendLevel(&p->rc, pStruct, iPromote, 1, 1);
  197248. if( p->rc ) return;
  197249. memcpy(pOut->aSeg, &pLvl->aSeg[is], sizeof(Fts5StructureSegment));
  197250. pOut->nSeg++;
  197251. pLvl->nSeg--;
  197252. }
  197253. }
  197254. }
  197255. }
  197256. /*
  197257. ** A new segment has just been written to level iLvl of index structure
  197258. ** pStruct. This function determines if any segments should be promoted
  197259. ** as a result. Segments are promoted in two scenarios:
  197260. **
  197261. ** a) If the segment just written is smaller than one or more segments
  197262. ** within the previous populated level, it is promoted to the previous
  197263. ** populated level.
  197264. **
  197265. ** b) If the segment just written is larger than the newest segment on
  197266. ** the next populated level, then that segment, and any other adjacent
  197267. ** segments that are also smaller than the one just written, are
  197268. ** promoted.
  197269. **
  197270. ** If one or more segments are promoted, the structure object is updated
  197271. ** to reflect this.
  197272. */
  197273. static void fts5StructurePromote(
  197274. Fts5Index *p, /* FTS5 backend object */
  197275. int iLvl, /* Index level just updated */
  197276. Fts5Structure *pStruct /* Index structure */
  197277. ){
  197278. if( p->rc==SQLITE_OK ){
  197279. int iTst;
  197280. int iPromote = -1;
  197281. int szPromote = 0; /* Promote anything this size or smaller */
  197282. Fts5StructureSegment *pSeg; /* Segment just written */
  197283. int szSeg; /* Size of segment just written */
  197284. int nSeg = pStruct->aLevel[iLvl].nSeg;
  197285. if( nSeg==0 ) return;
  197286. pSeg = &pStruct->aLevel[iLvl].aSeg[pStruct->aLevel[iLvl].nSeg-1];
  197287. szSeg = (1 + pSeg->pgnoLast - pSeg->pgnoFirst);
  197288. /* Check for condition (a) */
  197289. for(iTst=iLvl-1; iTst>=0 && pStruct->aLevel[iTst].nSeg==0; iTst--);
  197290. if( iTst>=0 ){
  197291. int i;
  197292. int szMax = 0;
  197293. Fts5StructureLevel *pTst = &pStruct->aLevel[iTst];
  197294. assert( pTst->nMerge==0 );
  197295. for(i=0; i<pTst->nSeg; i++){
  197296. int sz = pTst->aSeg[i].pgnoLast - pTst->aSeg[i].pgnoFirst + 1;
  197297. if( sz>szMax ) szMax = sz;
  197298. }
  197299. if( szMax>=szSeg ){
  197300. /* Condition (a) is true. Promote the newest segment on level
  197301. ** iLvl to level iTst. */
  197302. iPromote = iTst;
  197303. szPromote = szMax;
  197304. }
  197305. }
  197306. /* If condition (a) is not met, assume (b) is true. StructurePromoteTo()
  197307. ** is a no-op if it is not. */
  197308. if( iPromote<0 ){
  197309. iPromote = iLvl;
  197310. szPromote = szSeg;
  197311. }
  197312. fts5StructurePromoteTo(p, iPromote, szPromote, pStruct);
  197313. }
  197314. }
  197315. /*
  197316. ** Advance the iterator passed as the only argument. If the end of the
  197317. ** doclist-index page is reached, return non-zero.
  197318. */
  197319. static int fts5DlidxLvlNext(Fts5DlidxLvl *pLvl){
  197320. Fts5Data *pData = pLvl->pData;
  197321. if( pLvl->iOff==0 ){
  197322. assert( pLvl->bEof==0 );
  197323. pLvl->iOff = 1;
  197324. pLvl->iOff += fts5GetVarint32(&pData->p[1], pLvl->iLeafPgno);
  197325. pLvl->iOff += fts5GetVarint(&pData->p[pLvl->iOff], (u64*)&pLvl->iRowid);
  197326. pLvl->iFirstOff = pLvl->iOff;
  197327. }else{
  197328. int iOff;
  197329. for(iOff=pLvl->iOff; iOff<pData->nn; iOff++){
  197330. if( pData->p[iOff] ) break;
  197331. }
  197332. if( iOff<pData->nn ){
  197333. i64 iVal;
  197334. pLvl->iLeafPgno += (iOff - pLvl->iOff) + 1;
  197335. iOff += fts5GetVarint(&pData->p[iOff], (u64*)&iVal);
  197336. pLvl->iRowid += iVal;
  197337. pLvl->iOff = iOff;
  197338. }else{
  197339. pLvl->bEof = 1;
  197340. }
  197341. }
  197342. return pLvl->bEof;
  197343. }
  197344. /*
  197345. ** Advance the iterator passed as the only argument.
  197346. */
  197347. static int fts5DlidxIterNextR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
  197348. Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];
  197349. assert( iLvl<pIter->nLvl );
  197350. if( fts5DlidxLvlNext(pLvl) ){
  197351. if( (iLvl+1) < pIter->nLvl ){
  197352. fts5DlidxIterNextR(p, pIter, iLvl+1);
  197353. if( pLvl[1].bEof==0 ){
  197354. fts5DataRelease(pLvl->pData);
  197355. memset(pLvl, 0, sizeof(Fts5DlidxLvl));
  197356. pLvl->pData = fts5DataRead(p,
  197357. FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)
  197358. );
  197359. if( pLvl->pData ) fts5DlidxLvlNext(pLvl);
  197360. }
  197361. }
  197362. }
  197363. return pIter->aLvl[0].bEof;
  197364. }
  197365. static int fts5DlidxIterNext(Fts5Index *p, Fts5DlidxIter *pIter){
  197366. return fts5DlidxIterNextR(p, pIter, 0);
  197367. }
  197368. /*
  197369. ** The iterator passed as the first argument has the following fields set
  197370. ** as follows. This function sets up the rest of the iterator so that it
  197371. ** points to the first rowid in the doclist-index.
  197372. **
  197373. ** pData:
  197374. ** pointer to doclist-index record,
  197375. **
  197376. ** When this function is called pIter->iLeafPgno is the page number the
  197377. ** doclist is associated with (the one featuring the term).
  197378. */
  197379. static int fts5DlidxIterFirst(Fts5DlidxIter *pIter){
  197380. int i;
  197381. for(i=0; i<pIter->nLvl; i++){
  197382. fts5DlidxLvlNext(&pIter->aLvl[i]);
  197383. }
  197384. return pIter->aLvl[0].bEof;
  197385. }
  197386. static int fts5DlidxIterEof(Fts5Index *p, Fts5DlidxIter *pIter){
  197387. return p->rc!=SQLITE_OK || pIter->aLvl[0].bEof;
  197388. }
  197389. static void fts5DlidxIterLast(Fts5Index *p, Fts5DlidxIter *pIter){
  197390. int i;
  197391. /* Advance each level to the last entry on the last page */
  197392. for(i=pIter->nLvl-1; p->rc==SQLITE_OK && i>=0; i--){
  197393. Fts5DlidxLvl *pLvl = &pIter->aLvl[i];
  197394. while( fts5DlidxLvlNext(pLvl)==0 );
  197395. pLvl->bEof = 0;
  197396. if( i>0 ){
  197397. Fts5DlidxLvl *pChild = &pLvl[-1];
  197398. fts5DataRelease(pChild->pData);
  197399. memset(pChild, 0, sizeof(Fts5DlidxLvl));
  197400. pChild->pData = fts5DataRead(p,
  197401. FTS5_DLIDX_ROWID(pIter->iSegid, i-1, pLvl->iLeafPgno)
  197402. );
  197403. }
  197404. }
  197405. }
  197406. /*
  197407. ** Move the iterator passed as the only argument to the previous entry.
  197408. */
  197409. static int fts5DlidxLvlPrev(Fts5DlidxLvl *pLvl){
  197410. int iOff = pLvl->iOff;
  197411. assert( pLvl->bEof==0 );
  197412. if( iOff<=pLvl->iFirstOff ){
  197413. pLvl->bEof = 1;
  197414. }else{
  197415. u8 *a = pLvl->pData->p;
  197416. i64 iVal;
  197417. int iLimit;
  197418. int ii;
  197419. int nZero = 0;
  197420. /* Currently iOff points to the first byte of a varint. This block
  197421. ** decrements iOff until it points to the first byte of the previous
  197422. ** varint. Taking care not to read any memory locations that occur
  197423. ** before the buffer in memory. */
  197424. iLimit = (iOff>9 ? iOff-9 : 0);
  197425. for(iOff--; iOff>iLimit; iOff--){
  197426. if( (a[iOff-1] & 0x80)==0 ) break;
  197427. }
  197428. fts5GetVarint(&a[iOff], (u64*)&iVal);
  197429. pLvl->iRowid -= iVal;
  197430. pLvl->iLeafPgno--;
  197431. /* Skip backwards past any 0x00 varints. */
  197432. for(ii=iOff-1; ii>=pLvl->iFirstOff && a[ii]==0x00; ii--){
  197433. nZero++;
  197434. }
  197435. if( ii>=pLvl->iFirstOff && (a[ii] & 0x80) ){
  197436. /* The byte immediately before the last 0x00 byte has the 0x80 bit
  197437. ** set. So the last 0x00 is only a varint 0 if there are 8 more 0x80
  197438. ** bytes before a[ii]. */
  197439. int bZero = 0; /* True if last 0x00 counts */
  197440. if( (ii-8)>=pLvl->iFirstOff ){
  197441. int j;
  197442. for(j=1; j<=8 && (a[ii-j] & 0x80); j++);
  197443. bZero = (j>8);
  197444. }
  197445. if( bZero==0 ) nZero--;
  197446. }
  197447. pLvl->iLeafPgno -= nZero;
  197448. pLvl->iOff = iOff - nZero;
  197449. }
  197450. return pLvl->bEof;
  197451. }
  197452. static int fts5DlidxIterPrevR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
  197453. Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];
  197454. assert( iLvl<pIter->nLvl );
  197455. if( fts5DlidxLvlPrev(pLvl) ){
  197456. if( (iLvl+1) < pIter->nLvl ){
  197457. fts5DlidxIterPrevR(p, pIter, iLvl+1);
  197458. if( pLvl[1].bEof==0 ){
  197459. fts5DataRelease(pLvl->pData);
  197460. memset(pLvl, 0, sizeof(Fts5DlidxLvl));
  197461. pLvl->pData = fts5DataRead(p,
  197462. FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)
  197463. );
  197464. if( pLvl->pData ){
  197465. while( fts5DlidxLvlNext(pLvl)==0 );
  197466. pLvl->bEof = 0;
  197467. }
  197468. }
  197469. }
  197470. }
  197471. return pIter->aLvl[0].bEof;
  197472. }
  197473. static int fts5DlidxIterPrev(Fts5Index *p, Fts5DlidxIter *pIter){
  197474. return fts5DlidxIterPrevR(p, pIter, 0);
  197475. }
  197476. /*
  197477. ** Free a doclist-index iterator object allocated by fts5DlidxIterInit().
  197478. */
  197479. static void fts5DlidxIterFree(Fts5DlidxIter *pIter){
  197480. if( pIter ){
  197481. int i;
  197482. for(i=0; i<pIter->nLvl; i++){
  197483. fts5DataRelease(pIter->aLvl[i].pData);
  197484. }
  197485. sqlite3_free(pIter);
  197486. }
  197487. }
  197488. static Fts5DlidxIter *fts5DlidxIterInit(
  197489. Fts5Index *p, /* Fts5 Backend to iterate within */
  197490. int bRev, /* True for ORDER BY ASC */
  197491. int iSegid, /* Segment id */
  197492. int iLeafPg /* Leaf page number to load dlidx for */
  197493. ){
  197494. Fts5DlidxIter *pIter = 0;
  197495. int i;
  197496. int bDone = 0;
  197497. for(i=0; p->rc==SQLITE_OK && bDone==0; i++){
  197498. sqlite3_int64 nByte = sizeof(Fts5DlidxIter) + i * sizeof(Fts5DlidxLvl);
  197499. Fts5DlidxIter *pNew;
  197500. pNew = (Fts5DlidxIter*)sqlite3_realloc64(pIter, nByte);
  197501. if( pNew==0 ){
  197502. p->rc = SQLITE_NOMEM;
  197503. }else{
  197504. i64 iRowid = FTS5_DLIDX_ROWID(iSegid, i, iLeafPg);
  197505. Fts5DlidxLvl *pLvl = &pNew->aLvl[i];
  197506. pIter = pNew;
  197507. memset(pLvl, 0, sizeof(Fts5DlidxLvl));
  197508. pLvl->pData = fts5DataRead(p, iRowid);
  197509. if( pLvl->pData && (pLvl->pData->p[0] & 0x0001)==0 ){
  197510. bDone = 1;
  197511. }
  197512. pIter->nLvl = i+1;
  197513. }
  197514. }
  197515. if( p->rc==SQLITE_OK ){
  197516. pIter->iSegid = iSegid;
  197517. if( bRev==0 ){
  197518. fts5DlidxIterFirst(pIter);
  197519. }else{
  197520. fts5DlidxIterLast(p, pIter);
  197521. }
  197522. }
  197523. if( p->rc!=SQLITE_OK ){
  197524. fts5DlidxIterFree(pIter);
  197525. pIter = 0;
  197526. }
  197527. return pIter;
  197528. }
  197529. static i64 fts5DlidxIterRowid(Fts5DlidxIter *pIter){
  197530. return pIter->aLvl[0].iRowid;
  197531. }
  197532. static int fts5DlidxIterPgno(Fts5DlidxIter *pIter){
  197533. return pIter->aLvl[0].iLeafPgno;
  197534. }
  197535. /*
  197536. ** Load the next leaf page into the segment iterator.
  197537. */
  197538. static void fts5SegIterNextPage(
  197539. Fts5Index *p, /* FTS5 backend object */
  197540. Fts5SegIter *pIter /* Iterator to advance to next page */
  197541. ){
  197542. Fts5Data *pLeaf;
  197543. Fts5StructureSegment *pSeg = pIter->pSeg;
  197544. fts5DataRelease(pIter->pLeaf);
  197545. pIter->iLeafPgno++;
  197546. if( pIter->pNextLeaf ){
  197547. pIter->pLeaf = pIter->pNextLeaf;
  197548. pIter->pNextLeaf = 0;
  197549. }else if( pIter->iLeafPgno<=pSeg->pgnoLast ){
  197550. pIter->pLeaf = fts5LeafRead(p,
  197551. FTS5_SEGMENT_ROWID(pSeg->iSegid, pIter->iLeafPgno)
  197552. );
  197553. }else{
  197554. pIter->pLeaf = 0;
  197555. }
  197556. pLeaf = pIter->pLeaf;
  197557. if( pLeaf ){
  197558. pIter->iPgidxOff = pLeaf->szLeaf;
  197559. if( fts5LeafIsTermless(pLeaf) ){
  197560. pIter->iEndofDoclist = pLeaf->nn+1;
  197561. }else{
  197562. pIter->iPgidxOff += fts5GetVarint32(&pLeaf->p[pIter->iPgidxOff],
  197563. pIter->iEndofDoclist
  197564. );
  197565. }
  197566. }
  197567. }
  197568. /*
  197569. ** Argument p points to a buffer containing a varint to be interpreted as a
  197570. ** position list size field. Read the varint and return the number of bytes
  197571. ** read. Before returning, set *pnSz to the number of bytes in the position
  197572. ** list, and *pbDel to true if the delete flag is set, or false otherwise.
  197573. */
  197574. static int fts5GetPoslistSize(const u8 *p, int *pnSz, int *pbDel){
  197575. int nSz;
  197576. int n = 0;
  197577. fts5FastGetVarint32(p, n, nSz);
  197578. assert_nc( nSz>=0 );
  197579. *pnSz = nSz/2;
  197580. *pbDel = nSz & 0x0001;
  197581. return n;
  197582. }
  197583. /*
  197584. ** Fts5SegIter.iLeafOffset currently points to the first byte of a
  197585. ** position-list size field. Read the value of the field and store it
  197586. ** in the following variables:
  197587. **
  197588. ** Fts5SegIter.nPos
  197589. ** Fts5SegIter.bDel
  197590. **
  197591. ** Leave Fts5SegIter.iLeafOffset pointing to the first byte of the
  197592. ** position list content (if any).
  197593. */
  197594. static void fts5SegIterLoadNPos(Fts5Index *p, Fts5SegIter *pIter){
  197595. if( p->rc==SQLITE_OK ){
  197596. int iOff = pIter->iLeafOffset; /* Offset to read at */
  197597. ASSERT_SZLEAF_OK(pIter->pLeaf);
  197598. if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
  197599. int iEod = MIN(pIter->iEndofDoclist, pIter->pLeaf->szLeaf);
  197600. pIter->bDel = 0;
  197601. pIter->nPos = 1;
  197602. if( iOff<iEod && pIter->pLeaf->p[iOff]==0 ){
  197603. pIter->bDel = 1;
  197604. iOff++;
  197605. if( iOff<iEod && pIter->pLeaf->p[iOff]==0 ){
  197606. pIter->nPos = 1;
  197607. iOff++;
  197608. }else{
  197609. pIter->nPos = 0;
  197610. }
  197611. }
  197612. }else{
  197613. int nSz;
  197614. fts5FastGetVarint32(pIter->pLeaf->p, iOff, nSz);
  197615. pIter->bDel = (nSz & 0x0001);
  197616. pIter->nPos = nSz>>1;
  197617. assert_nc( pIter->nPos>=0 );
  197618. }
  197619. pIter->iLeafOffset = iOff;
  197620. }
  197621. }
  197622. static void fts5SegIterLoadRowid(Fts5Index *p, Fts5SegIter *pIter){
  197623. u8 *a = pIter->pLeaf->p; /* Buffer to read data from */
  197624. int iOff = pIter->iLeafOffset;
  197625. ASSERT_SZLEAF_OK(pIter->pLeaf);
  197626. if( iOff>=pIter->pLeaf->szLeaf ){
  197627. fts5SegIterNextPage(p, pIter);
  197628. if( pIter->pLeaf==0 ){
  197629. if( p->rc==SQLITE_OK ) p->rc = FTS5_CORRUPT;
  197630. return;
  197631. }
  197632. iOff = 4;
  197633. a = pIter->pLeaf->p;
  197634. }
  197635. iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);
  197636. pIter->iLeafOffset = iOff;
  197637. }
  197638. /*
  197639. ** Fts5SegIter.iLeafOffset currently points to the first byte of the
  197640. ** "nSuffix" field of a term. Function parameter nKeep contains the value
  197641. ** of the "nPrefix" field (if there was one - it is passed 0 if this is
  197642. ** the first term in the segment).
  197643. **
  197644. ** This function populates:
  197645. **
  197646. ** Fts5SegIter.term
  197647. ** Fts5SegIter.rowid
  197648. **
  197649. ** accordingly and leaves (Fts5SegIter.iLeafOffset) set to the content of
  197650. ** the first position list. The position list belonging to document
  197651. ** (Fts5SegIter.iRowid).
  197652. */
  197653. static void fts5SegIterLoadTerm(Fts5Index *p, Fts5SegIter *pIter, int nKeep){
  197654. u8 *a = pIter->pLeaf->p; /* Buffer to read data from */
  197655. int iOff = pIter->iLeafOffset; /* Offset to read at */
  197656. int nNew; /* Bytes of new data */
  197657. iOff += fts5GetVarint32(&a[iOff], nNew);
  197658. if( iOff+nNew>pIter->pLeaf->szLeaf || nKeep>pIter->term.n || nNew==0 ){
  197659. p->rc = FTS5_CORRUPT;
  197660. return;
  197661. }
  197662. pIter->term.n = nKeep;
  197663. fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]);
  197664. assert( pIter->term.n<=pIter->term.nSpace );
  197665. iOff += nNew;
  197666. pIter->iTermLeafOffset = iOff;
  197667. pIter->iTermLeafPgno = pIter->iLeafPgno;
  197668. pIter->iLeafOffset = iOff;
  197669. if( pIter->iPgidxOff>=pIter->pLeaf->nn ){
  197670. pIter->iEndofDoclist = pIter->pLeaf->nn+1;
  197671. }else{
  197672. int nExtra;
  197673. pIter->iPgidxOff += fts5GetVarint32(&a[pIter->iPgidxOff], nExtra);
  197674. pIter->iEndofDoclist += nExtra;
  197675. }
  197676. fts5SegIterLoadRowid(p, pIter);
  197677. }
  197678. static void fts5SegIterNext(Fts5Index*, Fts5SegIter*, int*);
  197679. static void fts5SegIterNext_Reverse(Fts5Index*, Fts5SegIter*, int*);
  197680. static void fts5SegIterNext_None(Fts5Index*, Fts5SegIter*, int*);
  197681. static void fts5SegIterSetNext(Fts5Index *p, Fts5SegIter *pIter){
  197682. if( pIter->flags & FTS5_SEGITER_REVERSE ){
  197683. pIter->xNext = fts5SegIterNext_Reverse;
  197684. }else if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
  197685. pIter->xNext = fts5SegIterNext_None;
  197686. }else{
  197687. pIter->xNext = fts5SegIterNext;
  197688. }
  197689. }
  197690. /*
  197691. ** Initialize the iterator object pIter to iterate through the entries in
  197692. ** segment pSeg. The iterator is left pointing to the first entry when
  197693. ** this function returns.
  197694. **
  197695. ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
  197696. ** an error has already occurred when this function is called, it is a no-op.
  197697. */
  197698. static void fts5SegIterInit(
  197699. Fts5Index *p, /* FTS index object */
  197700. Fts5StructureSegment *pSeg, /* Description of segment */
  197701. Fts5SegIter *pIter /* Object to populate */
  197702. ){
  197703. if( pSeg->pgnoFirst==0 ){
  197704. /* This happens if the segment is being used as an input to an incremental
  197705. ** merge and all data has already been "trimmed". See function
  197706. ** fts5TrimSegments() for details. In this case leave the iterator empty.
  197707. ** The caller will see the (pIter->pLeaf==0) and assume the iterator is
  197708. ** at EOF already. */
  197709. assert( pIter->pLeaf==0 );
  197710. return;
  197711. }
  197712. if( p->rc==SQLITE_OK ){
  197713. memset(pIter, 0, sizeof(*pIter));
  197714. fts5SegIterSetNext(p, pIter);
  197715. pIter->pSeg = pSeg;
  197716. pIter->iLeafPgno = pSeg->pgnoFirst-1;
  197717. fts5SegIterNextPage(p, pIter);
  197718. }
  197719. if( p->rc==SQLITE_OK ){
  197720. pIter->iLeafOffset = 4;
  197721. assert_nc( pIter->pLeaf->nn>4 );
  197722. assert_nc( fts5LeafFirstTermOff(pIter->pLeaf)==4 );
  197723. pIter->iPgidxOff = pIter->pLeaf->szLeaf+1;
  197724. fts5SegIterLoadTerm(p, pIter, 0);
  197725. fts5SegIterLoadNPos(p, pIter);
  197726. }
  197727. }
  197728. /*
  197729. ** This function is only ever called on iterators created by calls to
  197730. ** Fts5IndexQuery() with the FTS5INDEX_QUERY_DESC flag set.
  197731. **
  197732. ** The iterator is in an unusual state when this function is called: the
  197733. ** Fts5SegIter.iLeafOffset variable is set to the offset of the start of
  197734. ** the position-list size field for the first relevant rowid on the page.
  197735. ** Fts5SegIter.rowid is set, but nPos and bDel are not.
  197736. **
  197737. ** This function advances the iterator so that it points to the last
  197738. ** relevant rowid on the page and, if necessary, initializes the
  197739. ** aRowidOffset[] and iRowidOffset variables. At this point the iterator
  197740. ** is in its regular state - Fts5SegIter.iLeafOffset points to the first
  197741. ** byte of the position list content associated with said rowid.
  197742. */
  197743. static void fts5SegIterReverseInitPage(Fts5Index *p, Fts5SegIter *pIter){
  197744. int eDetail = p->pConfig->eDetail;
  197745. int n = pIter->pLeaf->szLeaf;
  197746. int i = pIter->iLeafOffset;
  197747. u8 *a = pIter->pLeaf->p;
  197748. int iRowidOffset = 0;
  197749. if( n>pIter->iEndofDoclist ){
  197750. n = pIter->iEndofDoclist;
  197751. }
  197752. ASSERT_SZLEAF_OK(pIter->pLeaf);
  197753. while( 1 ){
  197754. i64 iDelta = 0;
  197755. if( eDetail==FTS5_DETAIL_NONE ){
  197756. /* todo */
  197757. if( i<n && a[i]==0 ){
  197758. i++;
  197759. if( i<n && a[i]==0 ) i++;
  197760. }
  197761. }else{
  197762. int nPos;
  197763. int bDummy;
  197764. i += fts5GetPoslistSize(&a[i], &nPos, &bDummy);
  197765. i += nPos;
  197766. }
  197767. if( i>=n ) break;
  197768. i += fts5GetVarint(&a[i], (u64*)&iDelta);
  197769. pIter->iRowid += iDelta;
  197770. /* If necessary, grow the pIter->aRowidOffset[] array. */
  197771. if( iRowidOffset>=pIter->nRowidOffset ){
  197772. int nNew = pIter->nRowidOffset + 8;
  197773. int *aNew = (int*)sqlite3_realloc64(pIter->aRowidOffset,nNew*sizeof(int));
  197774. if( aNew==0 ){
  197775. p->rc = SQLITE_NOMEM;
  197776. break;
  197777. }
  197778. pIter->aRowidOffset = aNew;
  197779. pIter->nRowidOffset = nNew;
  197780. }
  197781. pIter->aRowidOffset[iRowidOffset++] = pIter->iLeafOffset;
  197782. pIter->iLeafOffset = i;
  197783. }
  197784. pIter->iRowidOffset = iRowidOffset;
  197785. fts5SegIterLoadNPos(p, pIter);
  197786. }
  197787. /*
  197788. **
  197789. */
  197790. static void fts5SegIterReverseNewPage(Fts5Index *p, Fts5SegIter *pIter){
  197791. assert( pIter->flags & FTS5_SEGITER_REVERSE );
  197792. assert( pIter->flags & FTS5_SEGITER_ONETERM );
  197793. fts5DataRelease(pIter->pLeaf);
  197794. pIter->pLeaf = 0;
  197795. while( p->rc==SQLITE_OK && pIter->iLeafPgno>pIter->iTermLeafPgno ){
  197796. Fts5Data *pNew;
  197797. pIter->iLeafPgno--;
  197798. pNew = fts5DataRead(p, FTS5_SEGMENT_ROWID(
  197799. pIter->pSeg->iSegid, pIter->iLeafPgno
  197800. ));
  197801. if( pNew ){
  197802. /* iTermLeafOffset may be equal to szLeaf if the term is the last
  197803. ** thing on the page - i.e. the first rowid is on the following page.
  197804. ** In this case leave pIter->pLeaf==0, this iterator is at EOF. */
  197805. if( pIter->iLeafPgno==pIter->iTermLeafPgno ){
  197806. assert( pIter->pLeaf==0 );
  197807. if( pIter->iTermLeafOffset<pNew->szLeaf ){
  197808. pIter->pLeaf = pNew;
  197809. pIter->iLeafOffset = pIter->iTermLeafOffset;
  197810. }
  197811. }else{
  197812. int iRowidOff;
  197813. iRowidOff = fts5LeafFirstRowidOff(pNew);
  197814. if( iRowidOff ){
  197815. pIter->pLeaf = pNew;
  197816. pIter->iLeafOffset = iRowidOff;
  197817. }
  197818. }
  197819. if( pIter->pLeaf ){
  197820. u8 *a = &pIter->pLeaf->p[pIter->iLeafOffset];
  197821. pIter->iLeafOffset += fts5GetVarint(a, (u64*)&pIter->iRowid);
  197822. break;
  197823. }else{
  197824. fts5DataRelease(pNew);
  197825. }
  197826. }
  197827. }
  197828. if( pIter->pLeaf ){
  197829. pIter->iEndofDoclist = pIter->pLeaf->nn+1;
  197830. fts5SegIterReverseInitPage(p, pIter);
  197831. }
  197832. }
  197833. /*
  197834. ** Return true if the iterator passed as the second argument currently
  197835. ** points to a delete marker. A delete marker is an entry with a 0 byte
  197836. ** position-list.
  197837. */
  197838. static int fts5MultiIterIsEmpty(Fts5Index *p, Fts5Iter *pIter){
  197839. Fts5SegIter *pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
  197840. return (p->rc==SQLITE_OK && pSeg->pLeaf && pSeg->nPos==0);
  197841. }
  197842. /*
  197843. ** Advance iterator pIter to the next entry.
  197844. **
  197845. ** This version of fts5SegIterNext() is only used by reverse iterators.
  197846. */
  197847. static void fts5SegIterNext_Reverse(
  197848. Fts5Index *p, /* FTS5 backend object */
  197849. Fts5SegIter *pIter, /* Iterator to advance */
  197850. int *pbUnused /* Unused */
  197851. ){
  197852. assert( pIter->flags & FTS5_SEGITER_REVERSE );
  197853. assert( pIter->pNextLeaf==0 );
  197854. UNUSED_PARAM(pbUnused);
  197855. if( pIter->iRowidOffset>0 ){
  197856. u8 *a = pIter->pLeaf->p;
  197857. int iOff;
  197858. i64 iDelta;
  197859. pIter->iRowidOffset--;
  197860. pIter->iLeafOffset = pIter->aRowidOffset[pIter->iRowidOffset];
  197861. fts5SegIterLoadNPos(p, pIter);
  197862. iOff = pIter->iLeafOffset;
  197863. if( p->pConfig->eDetail!=FTS5_DETAIL_NONE ){
  197864. iOff += pIter->nPos;
  197865. }
  197866. fts5GetVarint(&a[iOff], (u64*)&iDelta);
  197867. pIter->iRowid -= iDelta;
  197868. }else{
  197869. fts5SegIterReverseNewPage(p, pIter);
  197870. }
  197871. }
  197872. /*
  197873. ** Advance iterator pIter to the next entry.
  197874. **
  197875. ** This version of fts5SegIterNext() is only used if detail=none and the
  197876. ** iterator is not a reverse direction iterator.
  197877. */
  197878. static void fts5SegIterNext_None(
  197879. Fts5Index *p, /* FTS5 backend object */
  197880. Fts5SegIter *pIter, /* Iterator to advance */
  197881. int *pbNewTerm /* OUT: Set for new term */
  197882. ){
  197883. int iOff;
  197884. assert( p->rc==SQLITE_OK );
  197885. assert( (pIter->flags & FTS5_SEGITER_REVERSE)==0 );
  197886. assert( p->pConfig->eDetail==FTS5_DETAIL_NONE );
  197887. ASSERT_SZLEAF_OK(pIter->pLeaf);
  197888. iOff = pIter->iLeafOffset;
  197889. /* Next entry is on the next page */
  197890. if( pIter->pSeg && iOff>=pIter->pLeaf->szLeaf ){
  197891. fts5SegIterNextPage(p, pIter);
  197892. if( p->rc || pIter->pLeaf==0 ) return;
  197893. pIter->iRowid = 0;
  197894. iOff = 4;
  197895. }
  197896. if( iOff<pIter->iEndofDoclist ){
  197897. /* Next entry is on the current page */
  197898. i64 iDelta;
  197899. iOff += sqlite3Fts5GetVarint(&pIter->pLeaf->p[iOff], (u64*)&iDelta);
  197900. pIter->iLeafOffset = iOff;
  197901. pIter->iRowid += iDelta;
  197902. }else if( (pIter->flags & FTS5_SEGITER_ONETERM)==0 ){
  197903. if( pIter->pSeg ){
  197904. int nKeep = 0;
  197905. if( iOff!=fts5LeafFirstTermOff(pIter->pLeaf) ){
  197906. iOff += fts5GetVarint32(&pIter->pLeaf->p[iOff], nKeep);
  197907. }
  197908. pIter->iLeafOffset = iOff;
  197909. fts5SegIterLoadTerm(p, pIter, nKeep);
  197910. }else{
  197911. const u8 *pList = 0;
  197912. const char *zTerm = 0;
  197913. int nList;
  197914. sqlite3Fts5HashScanNext(p->pHash);
  197915. sqlite3Fts5HashScanEntry(p->pHash, &zTerm, &pList, &nList);
  197916. if( pList==0 ) goto next_none_eof;
  197917. pIter->pLeaf->p = (u8*)pList;
  197918. pIter->pLeaf->nn = nList;
  197919. pIter->pLeaf->szLeaf = nList;
  197920. pIter->iEndofDoclist = nList;
  197921. sqlite3Fts5BufferSet(&p->rc,&pIter->term, (int)strlen(zTerm), (u8*)zTerm);
  197922. pIter->iLeafOffset = fts5GetVarint(pList, (u64*)&pIter->iRowid);
  197923. }
  197924. if( pbNewTerm ) *pbNewTerm = 1;
  197925. }else{
  197926. goto next_none_eof;
  197927. }
  197928. fts5SegIterLoadNPos(p, pIter);
  197929. return;
  197930. next_none_eof:
  197931. fts5DataRelease(pIter->pLeaf);
  197932. pIter->pLeaf = 0;
  197933. }
  197934. /*
  197935. ** Advance iterator pIter to the next entry.
  197936. **
  197937. ** If an error occurs, Fts5Index.rc is set to an appropriate error code. It
  197938. ** is not considered an error if the iterator reaches EOF. If an error has
  197939. ** already occurred when this function is called, it is a no-op.
  197940. */
  197941. static void fts5SegIterNext(
  197942. Fts5Index *p, /* FTS5 backend object */
  197943. Fts5SegIter *pIter, /* Iterator to advance */
  197944. int *pbNewTerm /* OUT: Set for new term */
  197945. ){
  197946. Fts5Data *pLeaf = pIter->pLeaf;
  197947. int iOff;
  197948. int bNewTerm = 0;
  197949. int nKeep = 0;
  197950. u8 *a;
  197951. int n;
  197952. assert( pbNewTerm==0 || *pbNewTerm==0 );
  197953. assert( p->pConfig->eDetail!=FTS5_DETAIL_NONE );
  197954. /* Search for the end of the position list within the current page. */
  197955. a = pLeaf->p;
  197956. n = pLeaf->szLeaf;
  197957. ASSERT_SZLEAF_OK(pLeaf);
  197958. iOff = pIter->iLeafOffset + pIter->nPos;
  197959. if( iOff<n ){
  197960. /* The next entry is on the current page. */
  197961. assert_nc( iOff<=pIter->iEndofDoclist );
  197962. if( iOff>=pIter->iEndofDoclist ){
  197963. bNewTerm = 1;
  197964. if( iOff!=fts5LeafFirstTermOff(pLeaf) ){
  197965. iOff += fts5GetVarint32(&a[iOff], nKeep);
  197966. }
  197967. }else{
  197968. u64 iDelta;
  197969. iOff += sqlite3Fts5GetVarint(&a[iOff], &iDelta);
  197970. pIter->iRowid += iDelta;
  197971. assert_nc( iDelta>0 );
  197972. }
  197973. pIter->iLeafOffset = iOff;
  197974. }else if( pIter->pSeg==0 ){
  197975. const u8 *pList = 0;
  197976. const char *zTerm = 0;
  197977. int nList = 0;
  197978. assert( (pIter->flags & FTS5_SEGITER_ONETERM) || pbNewTerm );
  197979. if( 0==(pIter->flags & FTS5_SEGITER_ONETERM) ){
  197980. sqlite3Fts5HashScanNext(p->pHash);
  197981. sqlite3Fts5HashScanEntry(p->pHash, &zTerm, &pList, &nList);
  197982. }
  197983. if( pList==0 ){
  197984. fts5DataRelease(pIter->pLeaf);
  197985. pIter->pLeaf = 0;
  197986. }else{
  197987. pIter->pLeaf->p = (u8*)pList;
  197988. pIter->pLeaf->nn = nList;
  197989. pIter->pLeaf->szLeaf = nList;
  197990. pIter->iEndofDoclist = nList+1;
  197991. sqlite3Fts5BufferSet(&p->rc, &pIter->term, (int)strlen(zTerm),
  197992. (u8*)zTerm);
  197993. pIter->iLeafOffset = fts5GetVarint(pList, (u64*)&pIter->iRowid);
  197994. *pbNewTerm = 1;
  197995. }
  197996. }else{
  197997. iOff = 0;
  197998. /* Next entry is not on the current page */
  197999. while( iOff==0 ){
  198000. fts5SegIterNextPage(p, pIter);
  198001. pLeaf = pIter->pLeaf;
  198002. if( pLeaf==0 ) break;
  198003. ASSERT_SZLEAF_OK(pLeaf);
  198004. if( (iOff = fts5LeafFirstRowidOff(pLeaf)) && iOff<pLeaf->szLeaf ){
  198005. iOff += sqlite3Fts5GetVarint(&pLeaf->p[iOff], (u64*)&pIter->iRowid);
  198006. pIter->iLeafOffset = iOff;
  198007. if( pLeaf->nn>pLeaf->szLeaf ){
  198008. pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(
  198009. &pLeaf->p[pLeaf->szLeaf], pIter->iEndofDoclist
  198010. );
  198011. }
  198012. }
  198013. else if( pLeaf->nn>pLeaf->szLeaf ){
  198014. pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(
  198015. &pLeaf->p[pLeaf->szLeaf], iOff
  198016. );
  198017. pIter->iLeafOffset = iOff;
  198018. pIter->iEndofDoclist = iOff;
  198019. bNewTerm = 1;
  198020. }
  198021. assert_nc( iOff<pLeaf->szLeaf );
  198022. if( iOff>pLeaf->szLeaf ){
  198023. p->rc = FTS5_CORRUPT;
  198024. return;
  198025. }
  198026. }
  198027. }
  198028. /* Check if the iterator is now at EOF. If so, return early. */
  198029. if( pIter->pLeaf ){
  198030. if( bNewTerm ){
  198031. if( pIter->flags & FTS5_SEGITER_ONETERM ){
  198032. fts5DataRelease(pIter->pLeaf);
  198033. pIter->pLeaf = 0;
  198034. }else{
  198035. fts5SegIterLoadTerm(p, pIter, nKeep);
  198036. fts5SegIterLoadNPos(p, pIter);
  198037. if( pbNewTerm ) *pbNewTerm = 1;
  198038. }
  198039. }else{
  198040. /* The following could be done by calling fts5SegIterLoadNPos(). But
  198041. ** this block is particularly performance critical, so equivalent
  198042. ** code is inlined.
  198043. **
  198044. ** Later: Switched back to fts5SegIterLoadNPos() because it supports
  198045. ** detail=none mode. Not ideal.
  198046. */
  198047. int nSz;
  198048. assert( p->rc==SQLITE_OK );
  198049. assert( pIter->iLeafOffset<=pIter->pLeaf->nn );
  198050. fts5FastGetVarint32(pIter->pLeaf->p, pIter->iLeafOffset, nSz);
  198051. pIter->bDel = (nSz & 0x0001);
  198052. pIter->nPos = nSz>>1;
  198053. assert_nc( pIter->nPos>=0 );
  198054. }
  198055. }
  198056. }
  198057. #define SWAPVAL(T, a, b) { T tmp; tmp=a; a=b; b=tmp; }
  198058. #define fts5IndexSkipVarint(a, iOff) { \
  198059. int iEnd = iOff+9; \
  198060. while( (a[iOff++] & 0x80) && iOff<iEnd ); \
  198061. }
  198062. /*
  198063. ** Iterator pIter currently points to the first rowid in a doclist. This
  198064. ** function sets the iterator up so that iterates in reverse order through
  198065. ** the doclist.
  198066. */
  198067. static void fts5SegIterReverse(Fts5Index *p, Fts5SegIter *pIter){
  198068. Fts5DlidxIter *pDlidx = pIter->pDlidx;
  198069. Fts5Data *pLast = 0;
  198070. int pgnoLast = 0;
  198071. if( pDlidx ){
  198072. int iSegid = pIter->pSeg->iSegid;
  198073. pgnoLast = fts5DlidxIterPgno(pDlidx);
  198074. pLast = fts5DataRead(p, FTS5_SEGMENT_ROWID(iSegid, pgnoLast));
  198075. }else{
  198076. Fts5Data *pLeaf = pIter->pLeaf; /* Current leaf data */
  198077. /* Currently, Fts5SegIter.iLeafOffset points to the first byte of
  198078. ** position-list content for the current rowid. Back it up so that it
  198079. ** points to the start of the position-list size field. */
  198080. int iPoslist;
  198081. if( pIter->iTermLeafPgno==pIter->iLeafPgno ){
  198082. iPoslist = pIter->iTermLeafOffset;
  198083. }else{
  198084. iPoslist = 4;
  198085. }
  198086. fts5IndexSkipVarint(pLeaf->p, iPoslist);
  198087. pIter->iLeafOffset = iPoslist;
  198088. /* If this condition is true then the largest rowid for the current
  198089. ** term may not be stored on the current page. So search forward to
  198090. ** see where said rowid really is. */
  198091. if( pIter->iEndofDoclist>=pLeaf->szLeaf ){
  198092. int pgno;
  198093. Fts5StructureSegment *pSeg = pIter->pSeg;
  198094. /* The last rowid in the doclist may not be on the current page. Search
  198095. ** forward to find the page containing the last rowid. */
  198096. for(pgno=pIter->iLeafPgno+1; !p->rc && pgno<=pSeg->pgnoLast; pgno++){
  198097. i64 iAbs = FTS5_SEGMENT_ROWID(pSeg->iSegid, pgno);
  198098. Fts5Data *pNew = fts5DataRead(p, iAbs);
  198099. if( pNew ){
  198100. int iRowid, bTermless;
  198101. iRowid = fts5LeafFirstRowidOff(pNew);
  198102. bTermless = fts5LeafIsTermless(pNew);
  198103. if( iRowid ){
  198104. SWAPVAL(Fts5Data*, pNew, pLast);
  198105. pgnoLast = pgno;
  198106. }
  198107. fts5DataRelease(pNew);
  198108. if( bTermless==0 ) break;
  198109. }
  198110. }
  198111. }
  198112. }
  198113. /* If pLast is NULL at this point, then the last rowid for this doclist
  198114. ** lies on the page currently indicated by the iterator. In this case
  198115. ** pIter->iLeafOffset is already set to point to the position-list size
  198116. ** field associated with the first relevant rowid on the page.
  198117. **
  198118. ** Or, if pLast is non-NULL, then it is the page that contains the last
  198119. ** rowid. In this case configure the iterator so that it points to the
  198120. ** first rowid on this page.
  198121. */
  198122. if( pLast ){
  198123. int iOff;
  198124. fts5DataRelease(pIter->pLeaf);
  198125. pIter->pLeaf = pLast;
  198126. pIter->iLeafPgno = pgnoLast;
  198127. iOff = fts5LeafFirstRowidOff(pLast);
  198128. iOff += fts5GetVarint(&pLast->p[iOff], (u64*)&pIter->iRowid);
  198129. pIter->iLeafOffset = iOff;
  198130. if( fts5LeafIsTermless(pLast) ){
  198131. pIter->iEndofDoclist = pLast->nn+1;
  198132. }else{
  198133. pIter->iEndofDoclist = fts5LeafFirstTermOff(pLast);
  198134. }
  198135. }
  198136. fts5SegIterReverseInitPage(p, pIter);
  198137. }
  198138. /*
  198139. ** Iterator pIter currently points to the first rowid of a doclist.
  198140. ** There is a doclist-index associated with the final term on the current
  198141. ** page. If the current term is the last term on the page, load the
  198142. ** doclist-index from disk and initialize an iterator at (pIter->pDlidx).
  198143. */
  198144. static void fts5SegIterLoadDlidx(Fts5Index *p, Fts5SegIter *pIter){
  198145. int iSeg = pIter->pSeg->iSegid;
  198146. int bRev = (pIter->flags & FTS5_SEGITER_REVERSE);
  198147. Fts5Data *pLeaf = pIter->pLeaf; /* Current leaf data */
  198148. assert( pIter->flags & FTS5_SEGITER_ONETERM );
  198149. assert( pIter->pDlidx==0 );
  198150. /* Check if the current doclist ends on this page. If it does, return
  198151. ** early without loading the doclist-index (as it belongs to a different
  198152. ** term. */
  198153. if( pIter->iTermLeafPgno==pIter->iLeafPgno
  198154. && pIter->iEndofDoclist<pLeaf->szLeaf
  198155. ){
  198156. return;
  198157. }
  198158. pIter->pDlidx = fts5DlidxIterInit(p, bRev, iSeg, pIter->iTermLeafPgno);
  198159. }
  198160. /*
  198161. ** The iterator object passed as the second argument currently contains
  198162. ** no valid values except for the Fts5SegIter.pLeaf member variable. This
  198163. ** function searches the leaf page for a term matching (pTerm/nTerm).
  198164. **
  198165. ** If the specified term is found on the page, then the iterator is left
  198166. ** pointing to it. If argument bGe is zero and the term is not found,
  198167. ** the iterator is left pointing at EOF.
  198168. **
  198169. ** If bGe is non-zero and the specified term is not found, then the
  198170. ** iterator is left pointing to the smallest term in the segment that
  198171. ** is larger than the specified term, even if this term is not on the
  198172. ** current page.
  198173. */
  198174. static void fts5LeafSeek(
  198175. Fts5Index *p, /* Leave any error code here */
  198176. int bGe, /* True for a >= search */
  198177. Fts5SegIter *pIter, /* Iterator to seek */
  198178. const u8 *pTerm, int nTerm /* Term to search for */
  198179. ){
  198180. int iOff;
  198181. const u8 *a = pIter->pLeaf->p;
  198182. int szLeaf = pIter->pLeaf->szLeaf;
  198183. int n = pIter->pLeaf->nn;
  198184. u32 nMatch = 0;
  198185. u32 nKeep = 0;
  198186. u32 nNew = 0;
  198187. u32 iTermOff;
  198188. int iPgidx; /* Current offset in pgidx */
  198189. int bEndOfPage = 0;
  198190. assert( p->rc==SQLITE_OK );
  198191. iPgidx = szLeaf;
  198192. iPgidx += fts5GetVarint32(&a[iPgidx], iTermOff);
  198193. iOff = iTermOff;
  198194. if( iOff>n ){
  198195. p->rc = FTS5_CORRUPT;
  198196. return;
  198197. }
  198198. while( 1 ){
  198199. /* Figure out how many new bytes are in this term */
  198200. fts5FastGetVarint32(a, iOff, nNew);
  198201. if( nKeep<nMatch ){
  198202. goto search_failed;
  198203. }
  198204. assert( nKeep>=nMatch );
  198205. if( nKeep==nMatch ){
  198206. u32 nCmp;
  198207. u32 i;
  198208. nCmp = (u32)MIN(nNew, nTerm-nMatch);
  198209. for(i=0; i<nCmp; i++){
  198210. if( a[iOff+i]!=pTerm[nMatch+i] ) break;
  198211. }
  198212. nMatch += i;
  198213. if( (u32)nTerm==nMatch ){
  198214. if( i==nNew ){
  198215. goto search_success;
  198216. }else{
  198217. goto search_failed;
  198218. }
  198219. }else if( i<nNew && a[iOff+i]>pTerm[nMatch] ){
  198220. goto search_failed;
  198221. }
  198222. }
  198223. if( iPgidx>=n ){
  198224. bEndOfPage = 1;
  198225. break;
  198226. }
  198227. iPgidx += fts5GetVarint32(&a[iPgidx], nKeep);
  198228. iTermOff += nKeep;
  198229. iOff = iTermOff;
  198230. if( iOff>=n ){
  198231. p->rc = FTS5_CORRUPT;
  198232. return;
  198233. }
  198234. /* Read the nKeep field of the next term. */
  198235. fts5FastGetVarint32(a, iOff, nKeep);
  198236. }
  198237. search_failed:
  198238. if( bGe==0 ){
  198239. fts5DataRelease(pIter->pLeaf);
  198240. pIter->pLeaf = 0;
  198241. return;
  198242. }else if( bEndOfPage ){
  198243. do {
  198244. fts5SegIterNextPage(p, pIter);
  198245. if( pIter->pLeaf==0 ) return;
  198246. a = pIter->pLeaf->p;
  198247. if( fts5LeafIsTermless(pIter->pLeaf)==0 ){
  198248. iPgidx = pIter->pLeaf->szLeaf;
  198249. iPgidx += fts5GetVarint32(&pIter->pLeaf->p[iPgidx], iOff);
  198250. if( iOff<4 || iOff>=pIter->pLeaf->szLeaf ){
  198251. p->rc = FTS5_CORRUPT;
  198252. return;
  198253. }else{
  198254. nKeep = 0;
  198255. iTermOff = iOff;
  198256. n = pIter->pLeaf->nn;
  198257. iOff += fts5GetVarint32(&a[iOff], nNew);
  198258. break;
  198259. }
  198260. }
  198261. }while( 1 );
  198262. }
  198263. search_success:
  198264. pIter->iLeafOffset = iOff + nNew;
  198265. if( pIter->iLeafOffset>n || nNew<1 ){
  198266. p->rc = FTS5_CORRUPT;
  198267. return;
  198268. }
  198269. pIter->iTermLeafOffset = pIter->iLeafOffset;
  198270. pIter->iTermLeafPgno = pIter->iLeafPgno;
  198271. fts5BufferSet(&p->rc, &pIter->term, nKeep, pTerm);
  198272. fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]);
  198273. if( iPgidx>=n ){
  198274. pIter->iEndofDoclist = pIter->pLeaf->nn+1;
  198275. }else{
  198276. int nExtra;
  198277. iPgidx += fts5GetVarint32(&a[iPgidx], nExtra);
  198278. pIter->iEndofDoclist = iTermOff + nExtra;
  198279. }
  198280. pIter->iPgidxOff = iPgidx;
  198281. fts5SegIterLoadRowid(p, pIter);
  198282. fts5SegIterLoadNPos(p, pIter);
  198283. }
  198284. static sqlite3_stmt *fts5IdxSelectStmt(Fts5Index *p){
  198285. if( p->pIdxSelect==0 ){
  198286. Fts5Config *pConfig = p->pConfig;
  198287. fts5IndexPrepareStmt(p, &p->pIdxSelect, sqlite3_mprintf(
  198288. "SELECT pgno FROM '%q'.'%q_idx' WHERE "
  198289. "segid=? AND term<=? ORDER BY term DESC LIMIT 1",
  198290. pConfig->zDb, pConfig->zName
  198291. ));
  198292. }
  198293. return p->pIdxSelect;
  198294. }
  198295. /*
  198296. ** Initialize the object pIter to point to term pTerm/nTerm within segment
  198297. ** pSeg. If there is no such term in the index, the iterator is set to EOF.
  198298. **
  198299. ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
  198300. ** an error has already occurred when this function is called, it is a no-op.
  198301. */
  198302. static void fts5SegIterSeekInit(
  198303. Fts5Index *p, /* FTS5 backend */
  198304. const u8 *pTerm, int nTerm, /* Term to seek to */
  198305. int flags, /* Mask of FTS5INDEX_XXX flags */
  198306. Fts5StructureSegment *pSeg, /* Description of segment */
  198307. Fts5SegIter *pIter /* Object to populate */
  198308. ){
  198309. int iPg = 1;
  198310. int bGe = (flags & FTS5INDEX_QUERY_SCAN);
  198311. int bDlidx = 0; /* True if there is a doclist-index */
  198312. sqlite3_stmt *pIdxSelect = 0;
  198313. assert( bGe==0 || (flags & FTS5INDEX_QUERY_DESC)==0 );
  198314. assert( pTerm && nTerm );
  198315. memset(pIter, 0, sizeof(*pIter));
  198316. pIter->pSeg = pSeg;
  198317. /* This block sets stack variable iPg to the leaf page number that may
  198318. ** contain term (pTerm/nTerm), if it is present in the segment. */
  198319. pIdxSelect = fts5IdxSelectStmt(p);
  198320. if( p->rc ) return;
  198321. sqlite3_bind_int(pIdxSelect, 1, pSeg->iSegid);
  198322. sqlite3_bind_blob(pIdxSelect, 2, pTerm, nTerm, SQLITE_STATIC);
  198323. if( SQLITE_ROW==sqlite3_step(pIdxSelect) ){
  198324. i64 val = sqlite3_column_int(pIdxSelect, 0);
  198325. iPg = (int)(val>>1);
  198326. bDlidx = (val & 0x0001);
  198327. }
  198328. p->rc = sqlite3_reset(pIdxSelect);
  198329. sqlite3_bind_null(pIdxSelect, 2);
  198330. if( iPg<pSeg->pgnoFirst ){
  198331. iPg = pSeg->pgnoFirst;
  198332. bDlidx = 0;
  198333. }
  198334. pIter->iLeafPgno = iPg - 1;
  198335. fts5SegIterNextPage(p, pIter);
  198336. if( pIter->pLeaf ){
  198337. fts5LeafSeek(p, bGe, pIter, pTerm, nTerm);
  198338. }
  198339. if( p->rc==SQLITE_OK && bGe==0 ){
  198340. pIter->flags |= FTS5_SEGITER_ONETERM;
  198341. if( pIter->pLeaf ){
  198342. if( flags & FTS5INDEX_QUERY_DESC ){
  198343. pIter->flags |= FTS5_SEGITER_REVERSE;
  198344. }
  198345. if( bDlidx ){
  198346. fts5SegIterLoadDlidx(p, pIter);
  198347. }
  198348. if( flags & FTS5INDEX_QUERY_DESC ){
  198349. fts5SegIterReverse(p, pIter);
  198350. }
  198351. }
  198352. }
  198353. fts5SegIterSetNext(p, pIter);
  198354. /* Either:
  198355. **
  198356. ** 1) an error has occurred, or
  198357. ** 2) the iterator points to EOF, or
  198358. ** 3) the iterator points to an entry with term (pTerm/nTerm), or
  198359. ** 4) the FTS5INDEX_QUERY_SCAN flag was set and the iterator points
  198360. ** to an entry with a term greater than or equal to (pTerm/nTerm).
  198361. */
  198362. assert_nc( p->rc!=SQLITE_OK /* 1 */
  198363. || pIter->pLeaf==0 /* 2 */
  198364. || fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)==0 /* 3 */
  198365. || (bGe && fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)>0) /* 4 */
  198366. );
  198367. }
  198368. /*
  198369. ** Initialize the object pIter to point to term pTerm/nTerm within the
  198370. ** in-memory hash table. If there is no such term in the hash-table, the
  198371. ** iterator is set to EOF.
  198372. **
  198373. ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
  198374. ** an error has already occurred when this function is called, it is a no-op.
  198375. */
  198376. static void fts5SegIterHashInit(
  198377. Fts5Index *p, /* FTS5 backend */
  198378. const u8 *pTerm, int nTerm, /* Term to seek to */
  198379. int flags, /* Mask of FTS5INDEX_XXX flags */
  198380. Fts5SegIter *pIter /* Object to populate */
  198381. ){
  198382. int nList = 0;
  198383. const u8 *z = 0;
  198384. int n = 0;
  198385. Fts5Data *pLeaf = 0;
  198386. assert( p->pHash );
  198387. assert( p->rc==SQLITE_OK );
  198388. if( pTerm==0 || (flags & FTS5INDEX_QUERY_SCAN) ){
  198389. const u8 *pList = 0;
  198390. p->rc = sqlite3Fts5HashScanInit(p->pHash, (const char*)pTerm, nTerm);
  198391. sqlite3Fts5HashScanEntry(p->pHash, (const char**)&z, &pList, &nList);
  198392. n = (z ? (int)strlen((const char*)z) : 0);
  198393. if( pList ){
  198394. pLeaf = fts5IdxMalloc(p, sizeof(Fts5Data));
  198395. if( pLeaf ){
  198396. pLeaf->p = (u8*)pList;
  198397. }
  198398. }
  198399. }else{
  198400. p->rc = sqlite3Fts5HashQuery(p->pHash, sizeof(Fts5Data),
  198401. (const char*)pTerm, nTerm, (void**)&pLeaf, &nList
  198402. );
  198403. if( pLeaf ){
  198404. pLeaf->p = (u8*)&pLeaf[1];
  198405. }
  198406. z = pTerm;
  198407. n = nTerm;
  198408. pIter->flags |= FTS5_SEGITER_ONETERM;
  198409. }
  198410. if( pLeaf ){
  198411. sqlite3Fts5BufferSet(&p->rc, &pIter->term, n, z);
  198412. pLeaf->nn = pLeaf->szLeaf = nList;
  198413. pIter->pLeaf = pLeaf;
  198414. pIter->iLeafOffset = fts5GetVarint(pLeaf->p, (u64*)&pIter->iRowid);
  198415. pIter->iEndofDoclist = pLeaf->nn;
  198416. if( flags & FTS5INDEX_QUERY_DESC ){
  198417. pIter->flags |= FTS5_SEGITER_REVERSE;
  198418. fts5SegIterReverseInitPage(p, pIter);
  198419. }else{
  198420. fts5SegIterLoadNPos(p, pIter);
  198421. }
  198422. }
  198423. fts5SegIterSetNext(p, pIter);
  198424. }
  198425. /*
  198426. ** Zero the iterator passed as the only argument.
  198427. */
  198428. static void fts5SegIterClear(Fts5SegIter *pIter){
  198429. fts5BufferFree(&pIter->term);
  198430. fts5DataRelease(pIter->pLeaf);
  198431. fts5DataRelease(pIter->pNextLeaf);
  198432. fts5DlidxIterFree(pIter->pDlidx);
  198433. sqlite3_free(pIter->aRowidOffset);
  198434. memset(pIter, 0, sizeof(Fts5SegIter));
  198435. }
  198436. #ifdef SQLITE_DEBUG
  198437. /*
  198438. ** This function is used as part of the big assert() procedure implemented by
  198439. ** fts5AssertMultiIterSetup(). It ensures that the result currently stored
  198440. ** in *pRes is the correct result of comparing the current positions of the
  198441. ** two iterators.
  198442. */
  198443. static void fts5AssertComparisonResult(
  198444. Fts5Iter *pIter,
  198445. Fts5SegIter *p1,
  198446. Fts5SegIter *p2,
  198447. Fts5CResult *pRes
  198448. ){
  198449. int i1 = p1 - pIter->aSeg;
  198450. int i2 = p2 - pIter->aSeg;
  198451. if( p1->pLeaf || p2->pLeaf ){
  198452. if( p1->pLeaf==0 ){
  198453. assert( pRes->iFirst==i2 );
  198454. }else if( p2->pLeaf==0 ){
  198455. assert( pRes->iFirst==i1 );
  198456. }else{
  198457. int nMin = MIN(p1->term.n, p2->term.n);
  198458. int res = fts5Memcmp(p1->term.p, p2->term.p, nMin);
  198459. if( res==0 ) res = p1->term.n - p2->term.n;
  198460. if( res==0 ){
  198461. assert( pRes->bTermEq==1 );
  198462. assert( p1->iRowid!=p2->iRowid );
  198463. res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : 1;
  198464. }else{
  198465. assert( pRes->bTermEq==0 );
  198466. }
  198467. if( res<0 ){
  198468. assert( pRes->iFirst==i1 );
  198469. }else{
  198470. assert( pRes->iFirst==i2 );
  198471. }
  198472. }
  198473. }
  198474. }
  198475. /*
  198476. ** This function is a no-op unless SQLITE_DEBUG is defined when this module
  198477. ** is compiled. In that case, this function is essentially an assert()
  198478. ** statement used to verify that the contents of the pIter->aFirst[] array
  198479. ** are correct.
  198480. */
  198481. static void fts5AssertMultiIterSetup(Fts5Index *p, Fts5Iter *pIter){
  198482. if( p->rc==SQLITE_OK ){
  198483. Fts5SegIter *pFirst = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  198484. int i;
  198485. assert( (pFirst->pLeaf==0)==pIter->base.bEof );
  198486. /* Check that pIter->iSwitchRowid is set correctly. */
  198487. for(i=0; i<pIter->nSeg; i++){
  198488. Fts5SegIter *p1 = &pIter->aSeg[i];
  198489. assert( p1==pFirst
  198490. || p1->pLeaf==0
  198491. || fts5BufferCompare(&pFirst->term, &p1->term)
  198492. || p1->iRowid==pIter->iSwitchRowid
  198493. || (p1->iRowid<pIter->iSwitchRowid)==pIter->bRev
  198494. );
  198495. }
  198496. for(i=0; i<pIter->nSeg; i+=2){
  198497. Fts5SegIter *p1 = &pIter->aSeg[i];
  198498. Fts5SegIter *p2 = &pIter->aSeg[i+1];
  198499. Fts5CResult *pRes = &pIter->aFirst[(pIter->nSeg + i) / 2];
  198500. fts5AssertComparisonResult(pIter, p1, p2, pRes);
  198501. }
  198502. for(i=1; i<(pIter->nSeg / 2); i+=2){
  198503. Fts5SegIter *p1 = &pIter->aSeg[ pIter->aFirst[i*2].iFirst ];
  198504. Fts5SegIter *p2 = &pIter->aSeg[ pIter->aFirst[i*2+1].iFirst ];
  198505. Fts5CResult *pRes = &pIter->aFirst[i];
  198506. fts5AssertComparisonResult(pIter, p1, p2, pRes);
  198507. }
  198508. }
  198509. }
  198510. #else
  198511. # define fts5AssertMultiIterSetup(x,y)
  198512. #endif
  198513. /*
  198514. ** Do the comparison necessary to populate pIter->aFirst[iOut].
  198515. **
  198516. ** If the returned value is non-zero, then it is the index of an entry
  198517. ** in the pIter->aSeg[] array that is (a) not at EOF, and (b) pointing
  198518. ** to a key that is a duplicate of another, higher priority,
  198519. ** segment-iterator in the pSeg->aSeg[] array.
  198520. */
  198521. static int fts5MultiIterDoCompare(Fts5Iter *pIter, int iOut){
  198522. int i1; /* Index of left-hand Fts5SegIter */
  198523. int i2; /* Index of right-hand Fts5SegIter */
  198524. int iRes;
  198525. Fts5SegIter *p1; /* Left-hand Fts5SegIter */
  198526. Fts5SegIter *p2; /* Right-hand Fts5SegIter */
  198527. Fts5CResult *pRes = &pIter->aFirst[iOut];
  198528. assert( iOut<pIter->nSeg && iOut>0 );
  198529. assert( pIter->bRev==0 || pIter->bRev==1 );
  198530. if( iOut>=(pIter->nSeg/2) ){
  198531. i1 = (iOut - pIter->nSeg/2) * 2;
  198532. i2 = i1 + 1;
  198533. }else{
  198534. i1 = pIter->aFirst[iOut*2].iFirst;
  198535. i2 = pIter->aFirst[iOut*2+1].iFirst;
  198536. }
  198537. p1 = &pIter->aSeg[i1];
  198538. p2 = &pIter->aSeg[i2];
  198539. pRes->bTermEq = 0;
  198540. if( p1->pLeaf==0 ){ /* If p1 is at EOF */
  198541. iRes = i2;
  198542. }else if( p2->pLeaf==0 ){ /* If p2 is at EOF */
  198543. iRes = i1;
  198544. }else{
  198545. int res = fts5BufferCompare(&p1->term, &p2->term);
  198546. if( res==0 ){
  198547. assert_nc( i2>i1 );
  198548. assert_nc( i2!=0 );
  198549. pRes->bTermEq = 1;
  198550. if( p1->iRowid==p2->iRowid ){
  198551. p1->bDel = p2->bDel;
  198552. return i2;
  198553. }
  198554. res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : +1;
  198555. }
  198556. assert( res!=0 );
  198557. if( res<0 ){
  198558. iRes = i1;
  198559. }else{
  198560. iRes = i2;
  198561. }
  198562. }
  198563. pRes->iFirst = (u16)iRes;
  198564. return 0;
  198565. }
  198566. /*
  198567. ** Move the seg-iter so that it points to the first rowid on page iLeafPgno.
  198568. ** It is an error if leaf iLeafPgno does not exist or contains no rowids.
  198569. */
  198570. static void fts5SegIterGotoPage(
  198571. Fts5Index *p, /* FTS5 backend object */
  198572. Fts5SegIter *pIter, /* Iterator to advance */
  198573. int iLeafPgno
  198574. ){
  198575. assert( iLeafPgno>pIter->iLeafPgno );
  198576. if( iLeafPgno>pIter->pSeg->pgnoLast ){
  198577. p->rc = FTS5_CORRUPT;
  198578. }else{
  198579. fts5DataRelease(pIter->pNextLeaf);
  198580. pIter->pNextLeaf = 0;
  198581. pIter->iLeafPgno = iLeafPgno-1;
  198582. fts5SegIterNextPage(p, pIter);
  198583. assert( p->rc!=SQLITE_OK || pIter->iLeafPgno==iLeafPgno );
  198584. if( p->rc==SQLITE_OK ){
  198585. int iOff;
  198586. u8 *a = pIter->pLeaf->p;
  198587. int n = pIter->pLeaf->szLeaf;
  198588. iOff = fts5LeafFirstRowidOff(pIter->pLeaf);
  198589. if( iOff<4 || iOff>=n ){
  198590. p->rc = FTS5_CORRUPT;
  198591. }else{
  198592. iOff += fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);
  198593. pIter->iLeafOffset = iOff;
  198594. fts5SegIterLoadNPos(p, pIter);
  198595. }
  198596. }
  198597. }
  198598. }
  198599. /*
  198600. ** Advance the iterator passed as the second argument until it is at or
  198601. ** past rowid iFrom. Regardless of the value of iFrom, the iterator is
  198602. ** always advanced at least once.
  198603. */
  198604. static void fts5SegIterNextFrom(
  198605. Fts5Index *p, /* FTS5 backend object */
  198606. Fts5SegIter *pIter, /* Iterator to advance */
  198607. i64 iMatch /* Advance iterator at least this far */
  198608. ){
  198609. int bRev = (pIter->flags & FTS5_SEGITER_REVERSE);
  198610. Fts5DlidxIter *pDlidx = pIter->pDlidx;
  198611. int iLeafPgno = pIter->iLeafPgno;
  198612. int bMove = 1;
  198613. assert( pIter->flags & FTS5_SEGITER_ONETERM );
  198614. assert( pIter->pDlidx );
  198615. assert( pIter->pLeaf );
  198616. if( bRev==0 ){
  198617. while( !fts5DlidxIterEof(p, pDlidx) && iMatch>fts5DlidxIterRowid(pDlidx) ){
  198618. iLeafPgno = fts5DlidxIterPgno(pDlidx);
  198619. fts5DlidxIterNext(p, pDlidx);
  198620. }
  198621. assert_nc( iLeafPgno>=pIter->iLeafPgno || p->rc );
  198622. if( iLeafPgno>pIter->iLeafPgno ){
  198623. fts5SegIterGotoPage(p, pIter, iLeafPgno);
  198624. bMove = 0;
  198625. }
  198626. }else{
  198627. assert( pIter->pNextLeaf==0 );
  198628. assert( iMatch<pIter->iRowid );
  198629. while( !fts5DlidxIterEof(p, pDlidx) && iMatch<fts5DlidxIterRowid(pDlidx) ){
  198630. fts5DlidxIterPrev(p, pDlidx);
  198631. }
  198632. iLeafPgno = fts5DlidxIterPgno(pDlidx);
  198633. assert( fts5DlidxIterEof(p, pDlidx) || iLeafPgno<=pIter->iLeafPgno );
  198634. if( iLeafPgno<pIter->iLeafPgno ){
  198635. pIter->iLeafPgno = iLeafPgno+1;
  198636. fts5SegIterReverseNewPage(p, pIter);
  198637. bMove = 0;
  198638. }
  198639. }
  198640. do{
  198641. if( bMove && p->rc==SQLITE_OK ) pIter->xNext(p, pIter, 0);
  198642. if( pIter->pLeaf==0 ) break;
  198643. if( bRev==0 && pIter->iRowid>=iMatch ) break;
  198644. if( bRev!=0 && pIter->iRowid<=iMatch ) break;
  198645. bMove = 1;
  198646. }while( p->rc==SQLITE_OK );
  198647. }
  198648. /*
  198649. ** Free the iterator object passed as the second argument.
  198650. */
  198651. static void fts5MultiIterFree(Fts5Iter *pIter){
  198652. if( pIter ){
  198653. int i;
  198654. for(i=0; i<pIter->nSeg; i++){
  198655. fts5SegIterClear(&pIter->aSeg[i]);
  198656. }
  198657. fts5BufferFree(&pIter->poslist);
  198658. sqlite3_free(pIter);
  198659. }
  198660. }
  198661. static void fts5MultiIterAdvanced(
  198662. Fts5Index *p, /* FTS5 backend to iterate within */
  198663. Fts5Iter *pIter, /* Iterator to update aFirst[] array for */
  198664. int iChanged, /* Index of sub-iterator just advanced */
  198665. int iMinset /* Minimum entry in aFirst[] to set */
  198666. ){
  198667. int i;
  198668. for(i=(pIter->nSeg+iChanged)/2; i>=iMinset && p->rc==SQLITE_OK; i=i/2){
  198669. int iEq;
  198670. if( (iEq = fts5MultiIterDoCompare(pIter, i)) ){
  198671. Fts5SegIter *pSeg = &pIter->aSeg[iEq];
  198672. assert( p->rc==SQLITE_OK );
  198673. pSeg->xNext(p, pSeg, 0);
  198674. i = pIter->nSeg + iEq;
  198675. }
  198676. }
  198677. }
  198678. /*
  198679. ** Sub-iterator iChanged of iterator pIter has just been advanced. It still
  198680. ** points to the same term though - just a different rowid. This function
  198681. ** attempts to update the contents of the pIter->aFirst[] accordingly.
  198682. ** If it does so successfully, 0 is returned. Otherwise 1.
  198683. **
  198684. ** If non-zero is returned, the caller should call fts5MultiIterAdvanced()
  198685. ** on the iterator instead. That function does the same as this one, except
  198686. ** that it deals with more complicated cases as well.
  198687. */
  198688. static int fts5MultiIterAdvanceRowid(
  198689. Fts5Iter *pIter, /* Iterator to update aFirst[] array for */
  198690. int iChanged, /* Index of sub-iterator just advanced */
  198691. Fts5SegIter **ppFirst
  198692. ){
  198693. Fts5SegIter *pNew = &pIter->aSeg[iChanged];
  198694. if( pNew->iRowid==pIter->iSwitchRowid
  198695. || (pNew->iRowid<pIter->iSwitchRowid)==pIter->bRev
  198696. ){
  198697. int i;
  198698. Fts5SegIter *pOther = &pIter->aSeg[iChanged ^ 0x0001];
  198699. pIter->iSwitchRowid = pIter->bRev ? SMALLEST_INT64 : LARGEST_INT64;
  198700. for(i=(pIter->nSeg+iChanged)/2; 1; i=i/2){
  198701. Fts5CResult *pRes = &pIter->aFirst[i];
  198702. assert( pNew->pLeaf );
  198703. assert( pRes->bTermEq==0 || pOther->pLeaf );
  198704. if( pRes->bTermEq ){
  198705. if( pNew->iRowid==pOther->iRowid ){
  198706. return 1;
  198707. }else if( (pOther->iRowid>pNew->iRowid)==pIter->bRev ){
  198708. pIter->iSwitchRowid = pOther->iRowid;
  198709. pNew = pOther;
  198710. }else if( (pOther->iRowid>pIter->iSwitchRowid)==pIter->bRev ){
  198711. pIter->iSwitchRowid = pOther->iRowid;
  198712. }
  198713. }
  198714. pRes->iFirst = (u16)(pNew - pIter->aSeg);
  198715. if( i==1 ) break;
  198716. pOther = &pIter->aSeg[ pIter->aFirst[i ^ 0x0001].iFirst ];
  198717. }
  198718. }
  198719. *ppFirst = pNew;
  198720. return 0;
  198721. }
  198722. /*
  198723. ** Set the pIter->bEof variable based on the state of the sub-iterators.
  198724. */
  198725. static void fts5MultiIterSetEof(Fts5Iter *pIter){
  198726. Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  198727. pIter->base.bEof = pSeg->pLeaf==0;
  198728. pIter->iSwitchRowid = pSeg->iRowid;
  198729. }
  198730. /*
  198731. ** Move the iterator to the next entry.
  198732. **
  198733. ** If an error occurs, an error code is left in Fts5Index.rc. It is not
  198734. ** considered an error if the iterator reaches EOF, or if it is already at
  198735. ** EOF when this function is called.
  198736. */
  198737. static void fts5MultiIterNext(
  198738. Fts5Index *p,
  198739. Fts5Iter *pIter,
  198740. int bFrom, /* True if argument iFrom is valid */
  198741. i64 iFrom /* Advance at least as far as this */
  198742. ){
  198743. int bUseFrom = bFrom;
  198744. assert( pIter->base.bEof==0 );
  198745. while( p->rc==SQLITE_OK ){
  198746. int iFirst = pIter->aFirst[1].iFirst;
  198747. int bNewTerm = 0;
  198748. Fts5SegIter *pSeg = &pIter->aSeg[iFirst];
  198749. assert( p->rc==SQLITE_OK );
  198750. if( bUseFrom && pSeg->pDlidx ){
  198751. fts5SegIterNextFrom(p, pSeg, iFrom);
  198752. }else{
  198753. pSeg->xNext(p, pSeg, &bNewTerm);
  198754. }
  198755. if( pSeg->pLeaf==0 || bNewTerm
  198756. || fts5MultiIterAdvanceRowid(pIter, iFirst, &pSeg)
  198757. ){
  198758. fts5MultiIterAdvanced(p, pIter, iFirst, 1);
  198759. fts5MultiIterSetEof(pIter);
  198760. pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
  198761. if( pSeg->pLeaf==0 ) return;
  198762. }
  198763. fts5AssertMultiIterSetup(p, pIter);
  198764. assert( pSeg==&pIter->aSeg[pIter->aFirst[1].iFirst] && pSeg->pLeaf );
  198765. if( pIter->bSkipEmpty==0 || pSeg->nPos ){
  198766. pIter->xSetOutputs(pIter, pSeg);
  198767. return;
  198768. }
  198769. bUseFrom = 0;
  198770. }
  198771. }
  198772. static void fts5MultiIterNext2(
  198773. Fts5Index *p,
  198774. Fts5Iter *pIter,
  198775. int *pbNewTerm /* OUT: True if *might* be new term */
  198776. ){
  198777. assert( pIter->bSkipEmpty );
  198778. if( p->rc==SQLITE_OK ){
  198779. *pbNewTerm = 0;
  198780. do{
  198781. int iFirst = pIter->aFirst[1].iFirst;
  198782. Fts5SegIter *pSeg = &pIter->aSeg[iFirst];
  198783. int bNewTerm = 0;
  198784. assert( p->rc==SQLITE_OK );
  198785. pSeg->xNext(p, pSeg, &bNewTerm);
  198786. if( pSeg->pLeaf==0 || bNewTerm
  198787. || fts5MultiIterAdvanceRowid(pIter, iFirst, &pSeg)
  198788. ){
  198789. fts5MultiIterAdvanced(p, pIter, iFirst, 1);
  198790. fts5MultiIterSetEof(pIter);
  198791. *pbNewTerm = 1;
  198792. }
  198793. fts5AssertMultiIterSetup(p, pIter);
  198794. }while( fts5MultiIterIsEmpty(p, pIter) );
  198795. }
  198796. }
  198797. static void fts5IterSetOutputs_Noop(Fts5Iter *pUnused1, Fts5SegIter *pUnused2){
  198798. UNUSED_PARAM2(pUnused1, pUnused2);
  198799. }
  198800. static Fts5Iter *fts5MultiIterAlloc(
  198801. Fts5Index *p, /* FTS5 backend to iterate within */
  198802. int nSeg
  198803. ){
  198804. Fts5Iter *pNew;
  198805. int nSlot; /* Power of two >= nSeg */
  198806. for(nSlot=2; nSlot<nSeg; nSlot=nSlot*2);
  198807. pNew = fts5IdxMalloc(p,
  198808. sizeof(Fts5Iter) + /* pNew */
  198809. sizeof(Fts5SegIter) * (nSlot-1) + /* pNew->aSeg[] */
  198810. sizeof(Fts5CResult) * nSlot /* pNew->aFirst[] */
  198811. );
  198812. if( pNew ){
  198813. pNew->nSeg = nSlot;
  198814. pNew->aFirst = (Fts5CResult*)&pNew->aSeg[nSlot];
  198815. pNew->pIndex = p;
  198816. pNew->xSetOutputs = fts5IterSetOutputs_Noop;
  198817. }
  198818. return pNew;
  198819. }
  198820. static void fts5PoslistCallback(
  198821. Fts5Index *pUnused,
  198822. void *pContext,
  198823. const u8 *pChunk, int nChunk
  198824. ){
  198825. UNUSED_PARAM(pUnused);
  198826. assert_nc( nChunk>=0 );
  198827. if( nChunk>0 ){
  198828. fts5BufferSafeAppendBlob((Fts5Buffer*)pContext, pChunk, nChunk);
  198829. }
  198830. }
  198831. typedef struct PoslistCallbackCtx PoslistCallbackCtx;
  198832. struct PoslistCallbackCtx {
  198833. Fts5Buffer *pBuf; /* Append to this buffer */
  198834. Fts5Colset *pColset; /* Restrict matches to this column */
  198835. int eState; /* See above */
  198836. };
  198837. typedef struct PoslistOffsetsCtx PoslistOffsetsCtx;
  198838. struct PoslistOffsetsCtx {
  198839. Fts5Buffer *pBuf; /* Append to this buffer */
  198840. Fts5Colset *pColset; /* Restrict matches to this column */
  198841. int iRead;
  198842. int iWrite;
  198843. };
  198844. /*
  198845. ** TODO: Make this more efficient!
  198846. */
  198847. static int fts5IndexColsetTest(Fts5Colset *pColset, int iCol){
  198848. int i;
  198849. for(i=0; i<pColset->nCol; i++){
  198850. if( pColset->aiCol[i]==iCol ) return 1;
  198851. }
  198852. return 0;
  198853. }
  198854. static void fts5PoslistOffsetsCallback(
  198855. Fts5Index *pUnused,
  198856. void *pContext,
  198857. const u8 *pChunk, int nChunk
  198858. ){
  198859. PoslistOffsetsCtx *pCtx = (PoslistOffsetsCtx*)pContext;
  198860. UNUSED_PARAM(pUnused);
  198861. assert_nc( nChunk>=0 );
  198862. if( nChunk>0 ){
  198863. int i = 0;
  198864. while( i<nChunk ){
  198865. int iVal;
  198866. i += fts5GetVarint32(&pChunk[i], iVal);
  198867. iVal += pCtx->iRead - 2;
  198868. pCtx->iRead = iVal;
  198869. if( fts5IndexColsetTest(pCtx->pColset, iVal) ){
  198870. fts5BufferSafeAppendVarint(pCtx->pBuf, iVal + 2 - pCtx->iWrite);
  198871. pCtx->iWrite = iVal;
  198872. }
  198873. }
  198874. }
  198875. }
  198876. static void fts5PoslistFilterCallback(
  198877. Fts5Index *pUnused,
  198878. void *pContext,
  198879. const u8 *pChunk, int nChunk
  198880. ){
  198881. PoslistCallbackCtx *pCtx = (PoslistCallbackCtx*)pContext;
  198882. UNUSED_PARAM(pUnused);
  198883. assert_nc( nChunk>=0 );
  198884. if( nChunk>0 ){
  198885. /* Search through to find the first varint with value 1. This is the
  198886. ** start of the next columns hits. */
  198887. int i = 0;
  198888. int iStart = 0;
  198889. if( pCtx->eState==2 ){
  198890. int iCol;
  198891. fts5FastGetVarint32(pChunk, i, iCol);
  198892. if( fts5IndexColsetTest(pCtx->pColset, iCol) ){
  198893. pCtx->eState = 1;
  198894. fts5BufferSafeAppendVarint(pCtx->pBuf, 1);
  198895. }else{
  198896. pCtx->eState = 0;
  198897. }
  198898. }
  198899. do {
  198900. while( i<nChunk && pChunk[i]!=0x01 ){
  198901. while( pChunk[i] & 0x80 ) i++;
  198902. i++;
  198903. }
  198904. if( pCtx->eState ){
  198905. fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
  198906. }
  198907. if( i<nChunk ){
  198908. int iCol;
  198909. iStart = i;
  198910. i++;
  198911. if( i>=nChunk ){
  198912. pCtx->eState = 2;
  198913. }else{
  198914. fts5FastGetVarint32(pChunk, i, iCol);
  198915. pCtx->eState = fts5IndexColsetTest(pCtx->pColset, iCol);
  198916. if( pCtx->eState ){
  198917. fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
  198918. iStart = i;
  198919. }
  198920. }
  198921. }
  198922. }while( i<nChunk );
  198923. }
  198924. }
  198925. static void fts5ChunkIterate(
  198926. Fts5Index *p, /* Index object */
  198927. Fts5SegIter *pSeg, /* Poslist of this iterator */
  198928. void *pCtx, /* Context pointer for xChunk callback */
  198929. void (*xChunk)(Fts5Index*, void*, const u8*, int)
  198930. ){
  198931. int nRem = pSeg->nPos; /* Number of bytes still to come */
  198932. Fts5Data *pData = 0;
  198933. u8 *pChunk = &pSeg->pLeaf->p[pSeg->iLeafOffset];
  198934. int nChunk = MIN(nRem, pSeg->pLeaf->szLeaf - pSeg->iLeafOffset);
  198935. int pgno = pSeg->iLeafPgno;
  198936. int pgnoSave = 0;
  198937. /* This function does notmwork with detail=none databases. */
  198938. assert( p->pConfig->eDetail!=FTS5_DETAIL_NONE );
  198939. if( (pSeg->flags & FTS5_SEGITER_REVERSE)==0 ){
  198940. pgnoSave = pgno+1;
  198941. }
  198942. while( 1 ){
  198943. xChunk(p, pCtx, pChunk, nChunk);
  198944. nRem -= nChunk;
  198945. fts5DataRelease(pData);
  198946. if( nRem<=0 ){
  198947. break;
  198948. }else{
  198949. pgno++;
  198950. pData = fts5LeafRead(p, FTS5_SEGMENT_ROWID(pSeg->pSeg->iSegid, pgno));
  198951. if( pData==0 ) break;
  198952. pChunk = &pData->p[4];
  198953. nChunk = MIN(nRem, pData->szLeaf - 4);
  198954. if( pgno==pgnoSave ){
  198955. assert( pSeg->pNextLeaf==0 );
  198956. pSeg->pNextLeaf = pData;
  198957. pData = 0;
  198958. }
  198959. }
  198960. }
  198961. }
  198962. /*
  198963. ** Iterator pIter currently points to a valid entry (not EOF). This
  198964. ** function appends the position list data for the current entry to
  198965. ** buffer pBuf. It does not make a copy of the position-list size
  198966. ** field.
  198967. */
  198968. static void fts5SegiterPoslist(
  198969. Fts5Index *p,
  198970. Fts5SegIter *pSeg,
  198971. Fts5Colset *pColset,
  198972. Fts5Buffer *pBuf
  198973. ){
  198974. if( 0==fts5BufferGrow(&p->rc, pBuf, pSeg->nPos+FTS5_DATA_ZERO_PADDING) ){
  198975. memset(&pBuf->p[pBuf->n+pSeg->nPos], 0, FTS5_DATA_ZERO_PADDING);
  198976. if( pColset==0 ){
  198977. fts5ChunkIterate(p, pSeg, (void*)pBuf, fts5PoslistCallback);
  198978. }else{
  198979. if( p->pConfig->eDetail==FTS5_DETAIL_FULL ){
  198980. PoslistCallbackCtx sCtx;
  198981. sCtx.pBuf = pBuf;
  198982. sCtx.pColset = pColset;
  198983. sCtx.eState = fts5IndexColsetTest(pColset, 0);
  198984. assert( sCtx.eState==0 || sCtx.eState==1 );
  198985. fts5ChunkIterate(p, pSeg, (void*)&sCtx, fts5PoslistFilterCallback);
  198986. }else{
  198987. PoslistOffsetsCtx sCtx;
  198988. memset(&sCtx, 0, sizeof(sCtx));
  198989. sCtx.pBuf = pBuf;
  198990. sCtx.pColset = pColset;
  198991. fts5ChunkIterate(p, pSeg, (void*)&sCtx, fts5PoslistOffsetsCallback);
  198992. }
  198993. }
  198994. }
  198995. }
  198996. /*
  198997. ** IN/OUT parameter (*pa) points to a position list n bytes in size. If
  198998. ** the position list contains entries for column iCol, then (*pa) is set
  198999. ** to point to the sub-position-list for that column and the number of
  199000. ** bytes in it returned. Or, if the argument position list does not
  199001. ** contain any entries for column iCol, return 0.
  199002. */
  199003. static int fts5IndexExtractCol(
  199004. const u8 **pa, /* IN/OUT: Pointer to poslist */
  199005. int n, /* IN: Size of poslist in bytes */
  199006. int iCol /* Column to extract from poslist */
  199007. ){
  199008. int iCurrent = 0; /* Anything before the first 0x01 is col 0 */
  199009. const u8 *p = *pa;
  199010. const u8 *pEnd = &p[n]; /* One byte past end of position list */
  199011. while( iCol>iCurrent ){
  199012. /* Advance pointer p until it points to pEnd or an 0x01 byte that is
  199013. ** not part of a varint. Note that it is not possible for a negative
  199014. ** or extremely large varint to occur within an uncorrupted position
  199015. ** list. So the last byte of each varint may be assumed to have a clear
  199016. ** 0x80 bit. */
  199017. while( *p!=0x01 ){
  199018. while( *p++ & 0x80 );
  199019. if( p>=pEnd ) return 0;
  199020. }
  199021. *pa = p++;
  199022. iCurrent = *p++;
  199023. if( iCurrent & 0x80 ){
  199024. p--;
  199025. p += fts5GetVarint32(p, iCurrent);
  199026. }
  199027. }
  199028. if( iCol!=iCurrent ) return 0;
  199029. /* Advance pointer p until it points to pEnd or an 0x01 byte that is
  199030. ** not part of a varint */
  199031. while( p<pEnd && *p!=0x01 ){
  199032. while( *p++ & 0x80 );
  199033. }
  199034. return p - (*pa);
  199035. }
  199036. static void fts5IndexExtractColset(
  199037. int *pRc,
  199038. Fts5Colset *pColset, /* Colset to filter on */
  199039. const u8 *pPos, int nPos, /* Position list */
  199040. Fts5Buffer *pBuf /* Output buffer */
  199041. ){
  199042. if( *pRc==SQLITE_OK ){
  199043. int i;
  199044. fts5BufferZero(pBuf);
  199045. for(i=0; i<pColset->nCol; i++){
  199046. const u8 *pSub = pPos;
  199047. int nSub = fts5IndexExtractCol(&pSub, nPos, pColset->aiCol[i]);
  199048. if( nSub ){
  199049. fts5BufferAppendBlob(pRc, pBuf, nSub, pSub);
  199050. }
  199051. }
  199052. }
  199053. }
  199054. /*
  199055. ** xSetOutputs callback used by detail=none tables.
  199056. */
  199057. static void fts5IterSetOutputs_None(Fts5Iter *pIter, Fts5SegIter *pSeg){
  199058. assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_NONE );
  199059. pIter->base.iRowid = pSeg->iRowid;
  199060. pIter->base.nData = pSeg->nPos;
  199061. }
  199062. /*
  199063. ** xSetOutputs callback used by detail=full and detail=col tables when no
  199064. ** column filters are specified.
  199065. */
  199066. static void fts5IterSetOutputs_Nocolset(Fts5Iter *pIter, Fts5SegIter *pSeg){
  199067. pIter->base.iRowid = pSeg->iRowid;
  199068. pIter->base.nData = pSeg->nPos;
  199069. assert( pIter->pIndex->pConfig->eDetail!=FTS5_DETAIL_NONE );
  199070. assert( pIter->pColset==0 );
  199071. if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf ){
  199072. /* All data is stored on the current page. Populate the output
  199073. ** variables to point into the body of the page object. */
  199074. pIter->base.pData = &pSeg->pLeaf->p[pSeg->iLeafOffset];
  199075. }else{
  199076. /* The data is distributed over two or more pages. Copy it into the
  199077. ** Fts5Iter.poslist buffer and then set the output pointer to point
  199078. ** to this buffer. */
  199079. fts5BufferZero(&pIter->poslist);
  199080. fts5SegiterPoslist(pIter->pIndex, pSeg, 0, &pIter->poslist);
  199081. pIter->base.pData = pIter->poslist.p;
  199082. }
  199083. }
  199084. /*
  199085. ** xSetOutputs callback used when the Fts5Colset object has nCol==0 (match
  199086. ** against no columns at all).
  199087. */
  199088. static void fts5IterSetOutputs_ZeroColset(Fts5Iter *pIter, Fts5SegIter *pSeg){
  199089. UNUSED_PARAM(pSeg);
  199090. pIter->base.nData = 0;
  199091. }
  199092. /*
  199093. ** xSetOutputs callback used by detail=col when there is a column filter
  199094. ** and there are 100 or more columns. Also called as a fallback from
  199095. ** fts5IterSetOutputs_Col100 if the column-list spans more than one page.
  199096. */
  199097. static void fts5IterSetOutputs_Col(Fts5Iter *pIter, Fts5SegIter *pSeg){
  199098. fts5BufferZero(&pIter->poslist);
  199099. fts5SegiterPoslist(pIter->pIndex, pSeg, pIter->pColset, &pIter->poslist);
  199100. pIter->base.iRowid = pSeg->iRowid;
  199101. pIter->base.pData = pIter->poslist.p;
  199102. pIter->base.nData = pIter->poslist.n;
  199103. }
  199104. /*
  199105. ** xSetOutputs callback used when:
  199106. **
  199107. ** * detail=col,
  199108. ** * there is a column filter, and
  199109. ** * the table contains 100 or fewer columns.
  199110. **
  199111. ** The last point is to ensure all column numbers are stored as
  199112. ** single-byte varints.
  199113. */
  199114. static void fts5IterSetOutputs_Col100(Fts5Iter *pIter, Fts5SegIter *pSeg){
  199115. assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_COLUMNS );
  199116. assert( pIter->pColset );
  199117. if( pSeg->iLeafOffset+pSeg->nPos>pSeg->pLeaf->szLeaf ){
  199118. fts5IterSetOutputs_Col(pIter, pSeg);
  199119. }else{
  199120. u8 *a = (u8*)&pSeg->pLeaf->p[pSeg->iLeafOffset];
  199121. u8 *pEnd = (u8*)&a[pSeg->nPos];
  199122. int iPrev = 0;
  199123. int *aiCol = pIter->pColset->aiCol;
  199124. int *aiColEnd = &aiCol[pIter->pColset->nCol];
  199125. u8 *aOut = pIter->poslist.p;
  199126. int iPrevOut = 0;
  199127. pIter->base.iRowid = pSeg->iRowid;
  199128. while( a<pEnd ){
  199129. iPrev += (int)a++[0] - 2;
  199130. while( *aiCol<iPrev ){
  199131. aiCol++;
  199132. if( aiCol==aiColEnd ) goto setoutputs_col_out;
  199133. }
  199134. if( *aiCol==iPrev ){
  199135. *aOut++ = (u8)((iPrev - iPrevOut) + 2);
  199136. iPrevOut = iPrev;
  199137. }
  199138. }
  199139. setoutputs_col_out:
  199140. pIter->base.pData = pIter->poslist.p;
  199141. pIter->base.nData = aOut - pIter->poslist.p;
  199142. }
  199143. }
  199144. /*
  199145. ** xSetOutputs callback used by detail=full when there is a column filter.
  199146. */
  199147. static void fts5IterSetOutputs_Full(Fts5Iter *pIter, Fts5SegIter *pSeg){
  199148. Fts5Colset *pColset = pIter->pColset;
  199149. pIter->base.iRowid = pSeg->iRowid;
  199150. assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_FULL );
  199151. assert( pColset );
  199152. if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf ){
  199153. /* All data is stored on the current page. Populate the output
  199154. ** variables to point into the body of the page object. */
  199155. const u8 *a = &pSeg->pLeaf->p[pSeg->iLeafOffset];
  199156. if( pColset->nCol==1 ){
  199157. pIter->base.nData = fts5IndexExtractCol(&a, pSeg->nPos,pColset->aiCol[0]);
  199158. pIter->base.pData = a;
  199159. }else{
  199160. int *pRc = &pIter->pIndex->rc;
  199161. fts5BufferZero(&pIter->poslist);
  199162. fts5IndexExtractColset(pRc, pColset, a, pSeg->nPos, &pIter->poslist);
  199163. pIter->base.pData = pIter->poslist.p;
  199164. pIter->base.nData = pIter->poslist.n;
  199165. }
  199166. }else{
  199167. /* The data is distributed over two or more pages. Copy it into the
  199168. ** Fts5Iter.poslist buffer and then set the output pointer to point
  199169. ** to this buffer. */
  199170. fts5BufferZero(&pIter->poslist);
  199171. fts5SegiterPoslist(pIter->pIndex, pSeg, pColset, &pIter->poslist);
  199172. pIter->base.pData = pIter->poslist.p;
  199173. pIter->base.nData = pIter->poslist.n;
  199174. }
  199175. }
  199176. static void fts5IterSetOutputCb(int *pRc, Fts5Iter *pIter){
  199177. if( *pRc==SQLITE_OK ){
  199178. Fts5Config *pConfig = pIter->pIndex->pConfig;
  199179. if( pConfig->eDetail==FTS5_DETAIL_NONE ){
  199180. pIter->xSetOutputs = fts5IterSetOutputs_None;
  199181. }
  199182. else if( pIter->pColset==0 ){
  199183. pIter->xSetOutputs = fts5IterSetOutputs_Nocolset;
  199184. }
  199185. else if( pIter->pColset->nCol==0 ){
  199186. pIter->xSetOutputs = fts5IterSetOutputs_ZeroColset;
  199187. }
  199188. else if( pConfig->eDetail==FTS5_DETAIL_FULL ){
  199189. pIter->xSetOutputs = fts5IterSetOutputs_Full;
  199190. }
  199191. else{
  199192. assert( pConfig->eDetail==FTS5_DETAIL_COLUMNS );
  199193. if( pConfig->nCol<=100 ){
  199194. pIter->xSetOutputs = fts5IterSetOutputs_Col100;
  199195. sqlite3Fts5BufferSize(pRc, &pIter->poslist, pConfig->nCol);
  199196. }else{
  199197. pIter->xSetOutputs = fts5IterSetOutputs_Col;
  199198. }
  199199. }
  199200. }
  199201. }
  199202. /*
  199203. ** Allocate a new Fts5Iter object.
  199204. **
  199205. ** The new object will be used to iterate through data in structure pStruct.
  199206. ** If iLevel is -ve, then all data in all segments is merged. Or, if iLevel
  199207. ** is zero or greater, data from the first nSegment segments on level iLevel
  199208. ** is merged.
  199209. **
  199210. ** The iterator initially points to the first term/rowid entry in the
  199211. ** iterated data.
  199212. */
  199213. static void fts5MultiIterNew(
  199214. Fts5Index *p, /* FTS5 backend to iterate within */
  199215. Fts5Structure *pStruct, /* Structure of specific index */
  199216. int flags, /* FTS5INDEX_QUERY_XXX flags */
  199217. Fts5Colset *pColset, /* Colset to filter on (or NULL) */
  199218. const u8 *pTerm, int nTerm, /* Term to seek to (or NULL/0) */
  199219. int iLevel, /* Level to iterate (-1 for all) */
  199220. int nSegment, /* Number of segments to merge (iLevel>=0) */
  199221. Fts5Iter **ppOut /* New object */
  199222. ){
  199223. int nSeg = 0; /* Number of segment-iters in use */
  199224. int iIter = 0; /* */
  199225. int iSeg; /* Used to iterate through segments */
  199226. Fts5StructureLevel *pLvl;
  199227. Fts5Iter *pNew;
  199228. assert( (pTerm==0 && nTerm==0) || iLevel<0 );
  199229. /* Allocate space for the new multi-seg-iterator. */
  199230. if( p->rc==SQLITE_OK ){
  199231. if( iLevel<0 ){
  199232. assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
  199233. nSeg = pStruct->nSegment;
  199234. nSeg += (p->pHash ? 1 : 0);
  199235. }else{
  199236. nSeg = MIN(pStruct->aLevel[iLevel].nSeg, nSegment);
  199237. }
  199238. }
  199239. *ppOut = pNew = fts5MultiIterAlloc(p, nSeg);
  199240. if( pNew==0 ) return;
  199241. pNew->bRev = (0!=(flags & FTS5INDEX_QUERY_DESC));
  199242. pNew->bSkipEmpty = (0!=(flags & FTS5INDEX_QUERY_SKIPEMPTY));
  199243. pNew->pColset = pColset;
  199244. if( (flags & FTS5INDEX_QUERY_NOOUTPUT)==0 ){
  199245. fts5IterSetOutputCb(&p->rc, pNew);
  199246. }
  199247. /* Initialize each of the component segment iterators. */
  199248. if( p->rc==SQLITE_OK ){
  199249. if( iLevel<0 ){
  199250. Fts5StructureLevel *pEnd = &pStruct->aLevel[pStruct->nLevel];
  199251. if( p->pHash ){
  199252. /* Add a segment iterator for the current contents of the hash table. */
  199253. Fts5SegIter *pIter = &pNew->aSeg[iIter++];
  199254. fts5SegIterHashInit(p, pTerm, nTerm, flags, pIter);
  199255. }
  199256. for(pLvl=&pStruct->aLevel[0]; pLvl<pEnd; pLvl++){
  199257. for(iSeg=pLvl->nSeg-1; iSeg>=0; iSeg--){
  199258. Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
  199259. Fts5SegIter *pIter = &pNew->aSeg[iIter++];
  199260. if( pTerm==0 ){
  199261. fts5SegIterInit(p, pSeg, pIter);
  199262. }else{
  199263. fts5SegIterSeekInit(p, pTerm, nTerm, flags, pSeg, pIter);
  199264. }
  199265. }
  199266. }
  199267. }else{
  199268. pLvl = &pStruct->aLevel[iLevel];
  199269. for(iSeg=nSeg-1; iSeg>=0; iSeg--){
  199270. fts5SegIterInit(p, &pLvl->aSeg[iSeg], &pNew->aSeg[iIter++]);
  199271. }
  199272. }
  199273. assert( iIter==nSeg );
  199274. }
  199275. /* If the above was successful, each component iterators now points
  199276. ** to the first entry in its segment. In this case initialize the
  199277. ** aFirst[] array. Or, if an error has occurred, free the iterator
  199278. ** object and set the output variable to NULL. */
  199279. if( p->rc==SQLITE_OK ){
  199280. for(iIter=pNew->nSeg-1; iIter>0; iIter--){
  199281. int iEq;
  199282. if( (iEq = fts5MultiIterDoCompare(pNew, iIter)) ){
  199283. Fts5SegIter *pSeg = &pNew->aSeg[iEq];
  199284. if( p->rc==SQLITE_OK ) pSeg->xNext(p, pSeg, 0);
  199285. fts5MultiIterAdvanced(p, pNew, iEq, iIter);
  199286. }
  199287. }
  199288. fts5MultiIterSetEof(pNew);
  199289. fts5AssertMultiIterSetup(p, pNew);
  199290. if( pNew->bSkipEmpty && fts5MultiIterIsEmpty(p, pNew) ){
  199291. fts5MultiIterNext(p, pNew, 0, 0);
  199292. }else if( pNew->base.bEof==0 ){
  199293. Fts5SegIter *pSeg = &pNew->aSeg[pNew->aFirst[1].iFirst];
  199294. pNew->xSetOutputs(pNew, pSeg);
  199295. }
  199296. }else{
  199297. fts5MultiIterFree(pNew);
  199298. *ppOut = 0;
  199299. }
  199300. }
  199301. /*
  199302. ** Create an Fts5Iter that iterates through the doclist provided
  199303. ** as the second argument.
  199304. */
  199305. static void fts5MultiIterNew2(
  199306. Fts5Index *p, /* FTS5 backend to iterate within */
  199307. Fts5Data *pData, /* Doclist to iterate through */
  199308. int bDesc, /* True for descending rowid order */
  199309. Fts5Iter **ppOut /* New object */
  199310. ){
  199311. Fts5Iter *pNew;
  199312. pNew = fts5MultiIterAlloc(p, 2);
  199313. if( pNew ){
  199314. Fts5SegIter *pIter = &pNew->aSeg[1];
  199315. pIter->flags = FTS5_SEGITER_ONETERM;
  199316. if( pData->szLeaf>0 ){
  199317. pIter->pLeaf = pData;
  199318. pIter->iLeafOffset = fts5GetVarint(pData->p, (u64*)&pIter->iRowid);
  199319. pIter->iEndofDoclist = pData->nn;
  199320. pNew->aFirst[1].iFirst = 1;
  199321. if( bDesc ){
  199322. pNew->bRev = 1;
  199323. pIter->flags |= FTS5_SEGITER_REVERSE;
  199324. fts5SegIterReverseInitPage(p, pIter);
  199325. }else{
  199326. fts5SegIterLoadNPos(p, pIter);
  199327. }
  199328. pData = 0;
  199329. }else{
  199330. pNew->base.bEof = 1;
  199331. }
  199332. fts5SegIterSetNext(p, pIter);
  199333. *ppOut = pNew;
  199334. }
  199335. fts5DataRelease(pData);
  199336. }
  199337. /*
  199338. ** Return true if the iterator is at EOF or if an error has occurred.
  199339. ** False otherwise.
  199340. */
  199341. static int fts5MultiIterEof(Fts5Index *p, Fts5Iter *pIter){
  199342. assert( p->rc
  199343. || (pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf==0)==pIter->base.bEof
  199344. );
  199345. return (p->rc || pIter->base.bEof);
  199346. }
  199347. /*
  199348. ** Return the rowid of the entry that the iterator currently points
  199349. ** to. If the iterator points to EOF when this function is called the
  199350. ** results are undefined.
  199351. */
  199352. static i64 fts5MultiIterRowid(Fts5Iter *pIter){
  199353. assert( pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf );
  199354. return pIter->aSeg[ pIter->aFirst[1].iFirst ].iRowid;
  199355. }
  199356. /*
  199357. ** Move the iterator to the next entry at or following iMatch.
  199358. */
  199359. static void fts5MultiIterNextFrom(
  199360. Fts5Index *p,
  199361. Fts5Iter *pIter,
  199362. i64 iMatch
  199363. ){
  199364. while( 1 ){
  199365. i64 iRowid;
  199366. fts5MultiIterNext(p, pIter, 1, iMatch);
  199367. if( fts5MultiIterEof(p, pIter) ) break;
  199368. iRowid = fts5MultiIterRowid(pIter);
  199369. if( pIter->bRev==0 && iRowid>=iMatch ) break;
  199370. if( pIter->bRev!=0 && iRowid<=iMatch ) break;
  199371. }
  199372. }
  199373. /*
  199374. ** Return a pointer to a buffer containing the term associated with the
  199375. ** entry that the iterator currently points to.
  199376. */
  199377. static const u8 *fts5MultiIterTerm(Fts5Iter *pIter, int *pn){
  199378. Fts5SegIter *p = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  199379. *pn = p->term.n;
  199380. return p->term.p;
  199381. }
  199382. /*
  199383. ** Allocate a new segment-id for the structure pStruct. The new segment
  199384. ** id must be between 1 and 65335 inclusive, and must not be used by
  199385. ** any currently existing segment. If a free segment id cannot be found,
  199386. ** SQLITE_FULL is returned.
  199387. **
  199388. ** If an error has already occurred, this function is a no-op. 0 is
  199389. ** returned in this case.
  199390. */
  199391. static int fts5AllocateSegid(Fts5Index *p, Fts5Structure *pStruct){
  199392. int iSegid = 0;
  199393. if( p->rc==SQLITE_OK ){
  199394. if( pStruct->nSegment>=FTS5_MAX_SEGMENT ){
  199395. p->rc = SQLITE_FULL;
  199396. }else{
  199397. /* FTS5_MAX_SEGMENT is currently defined as 2000. So the following
  199398. ** array is 63 elements, or 252 bytes, in size. */
  199399. u32 aUsed[(FTS5_MAX_SEGMENT+31) / 32];
  199400. int iLvl, iSeg;
  199401. int i;
  199402. u32 mask;
  199403. memset(aUsed, 0, sizeof(aUsed));
  199404. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  199405. for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
  199406. int iId = pStruct->aLevel[iLvl].aSeg[iSeg].iSegid;
  199407. if( iId<=FTS5_MAX_SEGMENT && iId>0 ){
  199408. aUsed[(iId-1) / 32] |= (u32)1 << ((iId-1) % 32);
  199409. }
  199410. }
  199411. }
  199412. for(i=0; aUsed[i]==0xFFFFFFFF; i++);
  199413. mask = aUsed[i];
  199414. for(iSegid=0; mask & ((u32)1 << iSegid); iSegid++);
  199415. iSegid += 1 + i*32;
  199416. #ifdef SQLITE_DEBUG
  199417. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  199418. for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
  199419. assert_nc( iSegid!=pStruct->aLevel[iLvl].aSeg[iSeg].iSegid );
  199420. }
  199421. }
  199422. assert_nc( iSegid>0 && iSegid<=FTS5_MAX_SEGMENT );
  199423. {
  199424. sqlite3_stmt *pIdxSelect = fts5IdxSelectStmt(p);
  199425. if( p->rc==SQLITE_OK ){
  199426. u8 aBlob[2] = {0xff, 0xff};
  199427. sqlite3_bind_int(pIdxSelect, 1, iSegid);
  199428. sqlite3_bind_blob(pIdxSelect, 2, aBlob, 2, SQLITE_STATIC);
  199429. assert_nc( sqlite3_step(pIdxSelect)!=SQLITE_ROW );
  199430. p->rc = sqlite3_reset(pIdxSelect);
  199431. sqlite3_bind_null(pIdxSelect, 2);
  199432. }
  199433. }
  199434. #endif
  199435. }
  199436. }
  199437. return iSegid;
  199438. }
  199439. /*
  199440. ** Discard all data currently cached in the hash-tables.
  199441. */
  199442. static void fts5IndexDiscardData(Fts5Index *p){
  199443. assert( p->pHash || p->nPendingData==0 );
  199444. if( p->pHash ){
  199445. sqlite3Fts5HashClear(p->pHash);
  199446. p->nPendingData = 0;
  199447. }
  199448. }
  199449. /*
  199450. ** Return the size of the prefix, in bytes, that buffer
  199451. ** (pNew/<length-unknown>) shares with buffer (pOld/nOld).
  199452. **
  199453. ** Buffer (pNew/<length-unknown>) is guaranteed to be greater
  199454. ** than buffer (pOld/nOld).
  199455. */
  199456. static int fts5PrefixCompress(int nOld, const u8 *pOld, const u8 *pNew){
  199457. int i;
  199458. for(i=0; i<nOld; i++){
  199459. if( pOld[i]!=pNew[i] ) break;
  199460. }
  199461. return i;
  199462. }
  199463. static void fts5WriteDlidxClear(
  199464. Fts5Index *p,
  199465. Fts5SegWriter *pWriter,
  199466. int bFlush /* If true, write dlidx to disk */
  199467. ){
  199468. int i;
  199469. assert( bFlush==0 || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n>0) );
  199470. for(i=0; i<pWriter->nDlidx; i++){
  199471. Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i];
  199472. if( pDlidx->buf.n==0 ) break;
  199473. if( bFlush ){
  199474. assert( pDlidx->pgno!=0 );
  199475. fts5DataWrite(p,
  199476. FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),
  199477. pDlidx->buf.p, pDlidx->buf.n
  199478. );
  199479. }
  199480. sqlite3Fts5BufferZero(&pDlidx->buf);
  199481. pDlidx->bPrevValid = 0;
  199482. }
  199483. }
  199484. /*
  199485. ** Grow the pWriter->aDlidx[] array to at least nLvl elements in size.
  199486. ** Any new array elements are zeroed before returning.
  199487. */
  199488. static int fts5WriteDlidxGrow(
  199489. Fts5Index *p,
  199490. Fts5SegWriter *pWriter,
  199491. int nLvl
  199492. ){
  199493. if( p->rc==SQLITE_OK && nLvl>=pWriter->nDlidx ){
  199494. Fts5DlidxWriter *aDlidx = (Fts5DlidxWriter*)sqlite3_realloc64(
  199495. pWriter->aDlidx, sizeof(Fts5DlidxWriter) * nLvl
  199496. );
  199497. if( aDlidx==0 ){
  199498. p->rc = SQLITE_NOMEM;
  199499. }else{
  199500. size_t nByte = sizeof(Fts5DlidxWriter) * (nLvl - pWriter->nDlidx);
  199501. memset(&aDlidx[pWriter->nDlidx], 0, nByte);
  199502. pWriter->aDlidx = aDlidx;
  199503. pWriter->nDlidx = nLvl;
  199504. }
  199505. }
  199506. return p->rc;
  199507. }
  199508. /*
  199509. ** If the current doclist-index accumulating in pWriter->aDlidx[] is large
  199510. ** enough, flush it to disk and return 1. Otherwise discard it and return
  199511. ** zero.
  199512. */
  199513. static int fts5WriteFlushDlidx(Fts5Index *p, Fts5SegWriter *pWriter){
  199514. int bFlag = 0;
  199515. /* If there were FTS5_MIN_DLIDX_SIZE or more empty leaf pages written
  199516. ** to the database, also write the doclist-index to disk. */
  199517. if( pWriter->aDlidx[0].buf.n>0 && pWriter->nEmpty>=FTS5_MIN_DLIDX_SIZE ){
  199518. bFlag = 1;
  199519. }
  199520. fts5WriteDlidxClear(p, pWriter, bFlag);
  199521. pWriter->nEmpty = 0;
  199522. return bFlag;
  199523. }
  199524. /*
  199525. ** This function is called whenever processing of the doclist for the
  199526. ** last term on leaf page (pWriter->iBtPage) is completed.
  199527. **
  199528. ** The doclist-index for that term is currently stored in-memory within the
  199529. ** Fts5SegWriter.aDlidx[] array. If it is large enough, this function
  199530. ** writes it out to disk. Or, if it is too small to bother with, discards
  199531. ** it.
  199532. **
  199533. ** Fts5SegWriter.btterm currently contains the first term on page iBtPage.
  199534. */
  199535. static void fts5WriteFlushBtree(Fts5Index *p, Fts5SegWriter *pWriter){
  199536. int bFlag;
  199537. assert( pWriter->iBtPage || pWriter->nEmpty==0 );
  199538. if( pWriter->iBtPage==0 ) return;
  199539. bFlag = fts5WriteFlushDlidx(p, pWriter);
  199540. if( p->rc==SQLITE_OK ){
  199541. const char *z = (pWriter->btterm.n>0?(const char*)pWriter->btterm.p:"");
  199542. /* The following was already done in fts5WriteInit(): */
  199543. /* sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid); */
  199544. sqlite3_bind_blob(p->pIdxWriter, 2, z, pWriter->btterm.n, SQLITE_STATIC);
  199545. sqlite3_bind_int64(p->pIdxWriter, 3, bFlag + ((i64)pWriter->iBtPage<<1));
  199546. sqlite3_step(p->pIdxWriter);
  199547. p->rc = sqlite3_reset(p->pIdxWriter);
  199548. sqlite3_bind_null(p->pIdxWriter, 2);
  199549. }
  199550. pWriter->iBtPage = 0;
  199551. }
  199552. /*
  199553. ** This is called once for each leaf page except the first that contains
  199554. ** at least one term. Argument (nTerm/pTerm) is the split-key - a term that
  199555. ** is larger than all terms written to earlier leaves, and equal to or
  199556. ** smaller than the first term on the new leaf.
  199557. **
  199558. ** If an error occurs, an error code is left in Fts5Index.rc. If an error
  199559. ** has already occurred when this function is called, it is a no-op.
  199560. */
  199561. static void fts5WriteBtreeTerm(
  199562. Fts5Index *p, /* FTS5 backend object */
  199563. Fts5SegWriter *pWriter, /* Writer object */
  199564. int nTerm, const u8 *pTerm /* First term on new page */
  199565. ){
  199566. fts5WriteFlushBtree(p, pWriter);
  199567. if( p->rc==SQLITE_OK ){
  199568. fts5BufferSet(&p->rc, &pWriter->btterm, nTerm, pTerm);
  199569. pWriter->iBtPage = pWriter->writer.pgno;
  199570. }
  199571. }
  199572. /*
  199573. ** This function is called when flushing a leaf page that contains no
  199574. ** terms at all to disk.
  199575. */
  199576. static void fts5WriteBtreeNoTerm(
  199577. Fts5Index *p, /* FTS5 backend object */
  199578. Fts5SegWriter *pWriter /* Writer object */
  199579. ){
  199580. /* If there were no rowids on the leaf page either and the doclist-index
  199581. ** has already been started, append an 0x00 byte to it. */
  199582. if( pWriter->bFirstRowidInPage && pWriter->aDlidx[0].buf.n>0 ){
  199583. Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[0];
  199584. assert( pDlidx->bPrevValid );
  199585. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, 0);
  199586. }
  199587. /* Increment the "number of sequential leaves without a term" counter. */
  199588. pWriter->nEmpty++;
  199589. }
  199590. static i64 fts5DlidxExtractFirstRowid(Fts5Buffer *pBuf){
  199591. i64 iRowid;
  199592. int iOff;
  199593. iOff = 1 + fts5GetVarint(&pBuf->p[1], (u64*)&iRowid);
  199594. fts5GetVarint(&pBuf->p[iOff], (u64*)&iRowid);
  199595. return iRowid;
  199596. }
  199597. /*
  199598. ** Rowid iRowid has just been appended to the current leaf page. It is the
  199599. ** first on the page. This function appends an appropriate entry to the current
  199600. ** doclist-index.
  199601. */
  199602. static void fts5WriteDlidxAppend(
  199603. Fts5Index *p,
  199604. Fts5SegWriter *pWriter,
  199605. i64 iRowid
  199606. ){
  199607. int i;
  199608. int bDone = 0;
  199609. for(i=0; p->rc==SQLITE_OK && bDone==0; i++){
  199610. i64 iVal;
  199611. Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i];
  199612. if( pDlidx->buf.n>=p->pConfig->pgsz ){
  199613. /* The current doclist-index page is full. Write it to disk and push
  199614. ** a copy of iRowid (which will become the first rowid on the next
  199615. ** doclist-index leaf page) up into the next level of the b-tree
  199616. ** hierarchy. If the node being flushed is currently the root node,
  199617. ** also push its first rowid upwards. */
  199618. pDlidx->buf.p[0] = 0x01; /* Not the root node */
  199619. fts5DataWrite(p,
  199620. FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),
  199621. pDlidx->buf.p, pDlidx->buf.n
  199622. );
  199623. fts5WriteDlidxGrow(p, pWriter, i+2);
  199624. pDlidx = &pWriter->aDlidx[i];
  199625. if( p->rc==SQLITE_OK && pDlidx[1].buf.n==0 ){
  199626. i64 iFirst = fts5DlidxExtractFirstRowid(&pDlidx->buf);
  199627. /* This was the root node. Push its first rowid up to the new root. */
  199628. pDlidx[1].pgno = pDlidx->pgno;
  199629. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, 0);
  199630. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, pDlidx->pgno);
  199631. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, iFirst);
  199632. pDlidx[1].bPrevValid = 1;
  199633. pDlidx[1].iPrev = iFirst;
  199634. }
  199635. sqlite3Fts5BufferZero(&pDlidx->buf);
  199636. pDlidx->bPrevValid = 0;
  199637. pDlidx->pgno++;
  199638. }else{
  199639. bDone = 1;
  199640. }
  199641. if( pDlidx->bPrevValid ){
  199642. iVal = iRowid - pDlidx->iPrev;
  199643. }else{
  199644. i64 iPgno = (i==0 ? pWriter->writer.pgno : pDlidx[-1].pgno);
  199645. assert( pDlidx->buf.n==0 );
  199646. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, !bDone);
  199647. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iPgno);
  199648. iVal = iRowid;
  199649. }
  199650. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iVal);
  199651. pDlidx->bPrevValid = 1;
  199652. pDlidx->iPrev = iRowid;
  199653. }
  199654. }
  199655. static void fts5WriteFlushLeaf(Fts5Index *p, Fts5SegWriter *pWriter){
  199656. static const u8 zero[] = { 0x00, 0x00, 0x00, 0x00 };
  199657. Fts5PageWriter *pPage = &pWriter->writer;
  199658. i64 iRowid;
  199659. assert( (pPage->pgidx.n==0)==(pWriter->bFirstTermInPage) );
  199660. /* Set the szLeaf header field. */
  199661. assert( 0==fts5GetU16(&pPage->buf.p[2]) );
  199662. fts5PutU16(&pPage->buf.p[2], (u16)pPage->buf.n);
  199663. if( pWriter->bFirstTermInPage ){
  199664. /* No term was written to this page. */
  199665. assert( pPage->pgidx.n==0 );
  199666. fts5WriteBtreeNoTerm(p, pWriter);
  199667. }else{
  199668. /* Append the pgidx to the page buffer. Set the szLeaf header field. */
  199669. fts5BufferAppendBlob(&p->rc, &pPage->buf, pPage->pgidx.n, pPage->pgidx.p);
  199670. }
  199671. /* Write the page out to disk */
  199672. iRowid = FTS5_SEGMENT_ROWID(pWriter->iSegid, pPage->pgno);
  199673. fts5DataWrite(p, iRowid, pPage->buf.p, pPage->buf.n);
  199674. /* Initialize the next page. */
  199675. fts5BufferZero(&pPage->buf);
  199676. fts5BufferZero(&pPage->pgidx);
  199677. fts5BufferAppendBlob(&p->rc, &pPage->buf, 4, zero);
  199678. pPage->iPrevPgidx = 0;
  199679. pPage->pgno++;
  199680. /* Increase the leaves written counter */
  199681. pWriter->nLeafWritten++;
  199682. /* The new leaf holds no terms or rowids */
  199683. pWriter->bFirstTermInPage = 1;
  199684. pWriter->bFirstRowidInPage = 1;
  199685. }
  199686. /*
  199687. ** Append term pTerm/nTerm to the segment being written by the writer passed
  199688. ** as the second argument.
  199689. **
  199690. ** If an error occurs, set the Fts5Index.rc error code. If an error has
  199691. ** already occurred, this function is a no-op.
  199692. */
  199693. static void fts5WriteAppendTerm(
  199694. Fts5Index *p,
  199695. Fts5SegWriter *pWriter,
  199696. int nTerm, const u8 *pTerm
  199697. ){
  199698. int nPrefix; /* Bytes of prefix compression for term */
  199699. Fts5PageWriter *pPage = &pWriter->writer;
  199700. Fts5Buffer *pPgidx = &pWriter->writer.pgidx;
  199701. int nMin = MIN(pPage->term.n, nTerm);
  199702. assert( p->rc==SQLITE_OK );
  199703. assert( pPage->buf.n>=4 );
  199704. assert( pPage->buf.n>4 || pWriter->bFirstTermInPage );
  199705. /* If the current leaf page is full, flush it to disk. */
  199706. if( (pPage->buf.n + pPgidx->n + nTerm + 2)>=p->pConfig->pgsz ){
  199707. if( pPage->buf.n>4 ){
  199708. fts5WriteFlushLeaf(p, pWriter);
  199709. if( p->rc!=SQLITE_OK ) return;
  199710. }
  199711. fts5BufferGrow(&p->rc, &pPage->buf, nTerm+FTS5_DATA_PADDING);
  199712. }
  199713. /* TODO1: Updating pgidx here. */
  199714. pPgidx->n += sqlite3Fts5PutVarint(
  199715. &pPgidx->p[pPgidx->n], pPage->buf.n - pPage->iPrevPgidx
  199716. );
  199717. pPage->iPrevPgidx = pPage->buf.n;
  199718. #if 0
  199719. fts5PutU16(&pPgidx->p[pPgidx->n], pPage->buf.n);
  199720. pPgidx->n += 2;
  199721. #endif
  199722. if( pWriter->bFirstTermInPage ){
  199723. nPrefix = 0;
  199724. if( pPage->pgno!=1 ){
  199725. /* This is the first term on a leaf that is not the leftmost leaf in
  199726. ** the segment b-tree. In this case it is necessary to add a term to
  199727. ** the b-tree hierarchy that is (a) larger than the largest term
  199728. ** already written to the segment and (b) smaller than or equal to
  199729. ** this term. In other words, a prefix of (pTerm/nTerm) that is one
  199730. ** byte longer than the longest prefix (pTerm/nTerm) shares with the
  199731. ** previous term.
  199732. **
  199733. ** Usually, the previous term is available in pPage->term. The exception
  199734. ** is if this is the first term written in an incremental-merge step.
  199735. ** In this case the previous term is not available, so just write a
  199736. ** copy of (pTerm/nTerm) into the parent node. This is slightly
  199737. ** inefficient, but still correct. */
  199738. int n = nTerm;
  199739. if( pPage->term.n ){
  199740. n = 1 + fts5PrefixCompress(nMin, pPage->term.p, pTerm);
  199741. }
  199742. fts5WriteBtreeTerm(p, pWriter, n, pTerm);
  199743. if( p->rc!=SQLITE_OK ) return;
  199744. pPage = &pWriter->writer;
  199745. }
  199746. }else{
  199747. nPrefix = fts5PrefixCompress(nMin, pPage->term.p, pTerm);
  199748. fts5BufferAppendVarint(&p->rc, &pPage->buf, nPrefix);
  199749. }
  199750. /* Append the number of bytes of new data, then the term data itself
  199751. ** to the page. */
  199752. fts5BufferAppendVarint(&p->rc, &pPage->buf, nTerm - nPrefix);
  199753. fts5BufferAppendBlob(&p->rc, &pPage->buf, nTerm - nPrefix, &pTerm[nPrefix]);
  199754. /* Update the Fts5PageWriter.term field. */
  199755. fts5BufferSet(&p->rc, &pPage->term, nTerm, pTerm);
  199756. pWriter->bFirstTermInPage = 0;
  199757. pWriter->bFirstRowidInPage = 0;
  199758. pWriter->bFirstRowidInDoclist = 1;
  199759. assert( p->rc || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n==0) );
  199760. pWriter->aDlidx[0].pgno = pPage->pgno;
  199761. }
  199762. /*
  199763. ** Append a rowid and position-list size field to the writers output.
  199764. */
  199765. static void fts5WriteAppendRowid(
  199766. Fts5Index *p,
  199767. Fts5SegWriter *pWriter,
  199768. i64 iRowid
  199769. ){
  199770. if( p->rc==SQLITE_OK ){
  199771. Fts5PageWriter *pPage = &pWriter->writer;
  199772. if( (pPage->buf.n + pPage->pgidx.n)>=p->pConfig->pgsz ){
  199773. fts5WriteFlushLeaf(p, pWriter);
  199774. }
  199775. /* If this is to be the first rowid written to the page, set the
  199776. ** rowid-pointer in the page-header. Also append a value to the dlidx
  199777. ** buffer, in case a doclist-index is required. */
  199778. if( pWriter->bFirstRowidInPage ){
  199779. fts5PutU16(pPage->buf.p, (u16)pPage->buf.n);
  199780. fts5WriteDlidxAppend(p, pWriter, iRowid);
  199781. }
  199782. /* Write the rowid. */
  199783. if( pWriter->bFirstRowidInDoclist || pWriter->bFirstRowidInPage ){
  199784. fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid);
  199785. }else{
  199786. assert_nc( p->rc || iRowid>pWriter->iPrevRowid );
  199787. fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid - pWriter->iPrevRowid);
  199788. }
  199789. pWriter->iPrevRowid = iRowid;
  199790. pWriter->bFirstRowidInDoclist = 0;
  199791. pWriter->bFirstRowidInPage = 0;
  199792. }
  199793. }
  199794. static void fts5WriteAppendPoslistData(
  199795. Fts5Index *p,
  199796. Fts5SegWriter *pWriter,
  199797. const u8 *aData,
  199798. int nData
  199799. ){
  199800. Fts5PageWriter *pPage = &pWriter->writer;
  199801. const u8 *a = aData;
  199802. int n = nData;
  199803. assert( p->pConfig->pgsz>0 );
  199804. while( p->rc==SQLITE_OK
  199805. && (pPage->buf.n + pPage->pgidx.n + n)>=p->pConfig->pgsz
  199806. ){
  199807. int nReq = p->pConfig->pgsz - pPage->buf.n - pPage->pgidx.n;
  199808. int nCopy = 0;
  199809. while( nCopy<nReq ){
  199810. i64 dummy;
  199811. nCopy += fts5GetVarint(&a[nCopy], (u64*)&dummy);
  199812. }
  199813. fts5BufferAppendBlob(&p->rc, &pPage->buf, nCopy, a);
  199814. a += nCopy;
  199815. n -= nCopy;
  199816. fts5WriteFlushLeaf(p, pWriter);
  199817. }
  199818. if( n>0 ){
  199819. fts5BufferAppendBlob(&p->rc, &pPage->buf, n, a);
  199820. }
  199821. }
  199822. /*
  199823. ** Flush any data cached by the writer object to the database. Free any
  199824. ** allocations associated with the writer.
  199825. */
  199826. static void fts5WriteFinish(
  199827. Fts5Index *p,
  199828. Fts5SegWriter *pWriter, /* Writer object */
  199829. int *pnLeaf /* OUT: Number of leaf pages in b-tree */
  199830. ){
  199831. int i;
  199832. Fts5PageWriter *pLeaf = &pWriter->writer;
  199833. if( p->rc==SQLITE_OK ){
  199834. assert( pLeaf->pgno>=1 );
  199835. if( pLeaf->buf.n>4 ){
  199836. fts5WriteFlushLeaf(p, pWriter);
  199837. }
  199838. *pnLeaf = pLeaf->pgno-1;
  199839. if( pLeaf->pgno>1 ){
  199840. fts5WriteFlushBtree(p, pWriter);
  199841. }
  199842. }
  199843. fts5BufferFree(&pLeaf->term);
  199844. fts5BufferFree(&pLeaf->buf);
  199845. fts5BufferFree(&pLeaf->pgidx);
  199846. fts5BufferFree(&pWriter->btterm);
  199847. for(i=0; i<pWriter->nDlidx; i++){
  199848. sqlite3Fts5BufferFree(&pWriter->aDlidx[i].buf);
  199849. }
  199850. sqlite3_free(pWriter->aDlidx);
  199851. }
  199852. static void fts5WriteInit(
  199853. Fts5Index *p,
  199854. Fts5SegWriter *pWriter,
  199855. int iSegid
  199856. ){
  199857. const int nBuffer = p->pConfig->pgsz + FTS5_DATA_PADDING;
  199858. memset(pWriter, 0, sizeof(Fts5SegWriter));
  199859. pWriter->iSegid = iSegid;
  199860. fts5WriteDlidxGrow(p, pWriter, 1);
  199861. pWriter->writer.pgno = 1;
  199862. pWriter->bFirstTermInPage = 1;
  199863. pWriter->iBtPage = 1;
  199864. assert( pWriter->writer.buf.n==0 );
  199865. assert( pWriter->writer.pgidx.n==0 );
  199866. /* Grow the two buffers to pgsz + padding bytes in size. */
  199867. sqlite3Fts5BufferSize(&p->rc, &pWriter->writer.pgidx, nBuffer);
  199868. sqlite3Fts5BufferSize(&p->rc, &pWriter->writer.buf, nBuffer);
  199869. if( p->pIdxWriter==0 ){
  199870. Fts5Config *pConfig = p->pConfig;
  199871. fts5IndexPrepareStmt(p, &p->pIdxWriter, sqlite3_mprintf(
  199872. "INSERT INTO '%q'.'%q_idx'(segid,term,pgno) VALUES(?,?,?)",
  199873. pConfig->zDb, pConfig->zName
  199874. ));
  199875. }
  199876. if( p->rc==SQLITE_OK ){
  199877. /* Initialize the 4-byte leaf-page header to 0x00. */
  199878. memset(pWriter->writer.buf.p, 0, 4);
  199879. pWriter->writer.buf.n = 4;
  199880. /* Bind the current output segment id to the index-writer. This is an
  199881. ** optimization over binding the same value over and over as rows are
  199882. ** inserted into %_idx by the current writer. */
  199883. sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid);
  199884. }
  199885. }
  199886. /*
  199887. ** Iterator pIter was used to iterate through the input segments of on an
  199888. ** incremental merge operation. This function is called if the incremental
  199889. ** merge step has finished but the input has not been completely exhausted.
  199890. */
  199891. static void fts5TrimSegments(Fts5Index *p, Fts5Iter *pIter){
  199892. int i;
  199893. Fts5Buffer buf;
  199894. memset(&buf, 0, sizeof(Fts5Buffer));
  199895. for(i=0; i<pIter->nSeg && p->rc==SQLITE_OK; i++){
  199896. Fts5SegIter *pSeg = &pIter->aSeg[i];
  199897. if( pSeg->pSeg==0 ){
  199898. /* no-op */
  199899. }else if( pSeg->pLeaf==0 ){
  199900. /* All keys from this input segment have been transfered to the output.
  199901. ** Set both the first and last page-numbers to 0 to indicate that the
  199902. ** segment is now empty. */
  199903. pSeg->pSeg->pgnoLast = 0;
  199904. pSeg->pSeg->pgnoFirst = 0;
  199905. }else{
  199906. int iOff = pSeg->iTermLeafOffset; /* Offset on new first leaf page */
  199907. i64 iLeafRowid;
  199908. Fts5Data *pData;
  199909. int iId = pSeg->pSeg->iSegid;
  199910. u8 aHdr[4] = {0x00, 0x00, 0x00, 0x00};
  199911. iLeafRowid = FTS5_SEGMENT_ROWID(iId, pSeg->iTermLeafPgno);
  199912. pData = fts5LeafRead(p, iLeafRowid);
  199913. if( pData ){
  199914. if( iOff>pData->szLeaf ){
  199915. /* This can occur if the pages that the segments occupy overlap - if
  199916. ** a single page has been assigned to more than one segment. In
  199917. ** this case a prior iteration of this loop may have corrupted the
  199918. ** segment currently being trimmed. */
  199919. p->rc = FTS5_CORRUPT;
  199920. }else{
  199921. fts5BufferZero(&buf);
  199922. fts5BufferGrow(&p->rc, &buf, pData->nn);
  199923. fts5BufferAppendBlob(&p->rc, &buf, sizeof(aHdr), aHdr);
  199924. fts5BufferAppendVarint(&p->rc, &buf, pSeg->term.n);
  199925. fts5BufferAppendBlob(&p->rc, &buf, pSeg->term.n, pSeg->term.p);
  199926. fts5BufferAppendBlob(&p->rc, &buf, pData->szLeaf-iOff,&pData->p[iOff]);
  199927. if( p->rc==SQLITE_OK ){
  199928. /* Set the szLeaf field */
  199929. fts5PutU16(&buf.p[2], (u16)buf.n);
  199930. }
  199931. /* Set up the new page-index array */
  199932. fts5BufferAppendVarint(&p->rc, &buf, 4);
  199933. if( pSeg->iLeafPgno==pSeg->iTermLeafPgno
  199934. && pSeg->iEndofDoclist<pData->szLeaf
  199935. && pSeg->iPgidxOff<=pData->nn
  199936. ){
  199937. int nDiff = pData->szLeaf - pSeg->iEndofDoclist;
  199938. fts5BufferAppendVarint(&p->rc, &buf, buf.n - 1 - nDiff - 4);
  199939. fts5BufferAppendBlob(&p->rc, &buf,
  199940. pData->nn - pSeg->iPgidxOff, &pData->p[pSeg->iPgidxOff]
  199941. );
  199942. }
  199943. pSeg->pSeg->pgnoFirst = pSeg->iTermLeafPgno;
  199944. fts5DataDelete(p, FTS5_SEGMENT_ROWID(iId, 1), iLeafRowid);
  199945. fts5DataWrite(p, iLeafRowid, buf.p, buf.n);
  199946. }
  199947. fts5DataRelease(pData);
  199948. }
  199949. }
  199950. }
  199951. fts5BufferFree(&buf);
  199952. }
  199953. static void fts5MergeChunkCallback(
  199954. Fts5Index *p,
  199955. void *pCtx,
  199956. const u8 *pChunk, int nChunk
  199957. ){
  199958. Fts5SegWriter *pWriter = (Fts5SegWriter*)pCtx;
  199959. fts5WriteAppendPoslistData(p, pWriter, pChunk, nChunk);
  199960. }
  199961. /*
  199962. **
  199963. */
  199964. static void fts5IndexMergeLevel(
  199965. Fts5Index *p, /* FTS5 backend object */
  199966. Fts5Structure **ppStruct, /* IN/OUT: Stucture of index */
  199967. int iLvl, /* Level to read input from */
  199968. int *pnRem /* Write up to this many output leaves */
  199969. ){
  199970. Fts5Structure *pStruct = *ppStruct;
  199971. Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
  199972. Fts5StructureLevel *pLvlOut;
  199973. Fts5Iter *pIter = 0; /* Iterator to read input data */
  199974. int nRem = pnRem ? *pnRem : 0; /* Output leaf pages left to write */
  199975. int nInput; /* Number of input segments */
  199976. Fts5SegWriter writer; /* Writer object */
  199977. Fts5StructureSegment *pSeg; /* Output segment */
  199978. Fts5Buffer term;
  199979. int bOldest; /* True if the output segment is the oldest */
  199980. int eDetail = p->pConfig->eDetail;
  199981. const int flags = FTS5INDEX_QUERY_NOOUTPUT;
  199982. int bTermWritten = 0; /* True if current term already output */
  199983. assert( iLvl<pStruct->nLevel );
  199984. assert( pLvl->nMerge<=pLvl->nSeg );
  199985. memset(&writer, 0, sizeof(Fts5SegWriter));
  199986. memset(&term, 0, sizeof(Fts5Buffer));
  199987. if( pLvl->nMerge ){
  199988. pLvlOut = &pStruct->aLevel[iLvl+1];
  199989. assert( pLvlOut->nSeg>0 );
  199990. nInput = pLvl->nMerge;
  199991. pSeg = &pLvlOut->aSeg[pLvlOut->nSeg-1];
  199992. fts5WriteInit(p, &writer, pSeg->iSegid);
  199993. writer.writer.pgno = pSeg->pgnoLast+1;
  199994. writer.iBtPage = 0;
  199995. }else{
  199996. int iSegid = fts5AllocateSegid(p, pStruct);
  199997. /* Extend the Fts5Structure object as required to ensure the output
  199998. ** segment exists. */
  199999. if( iLvl==pStruct->nLevel-1 ){
  200000. fts5StructureAddLevel(&p->rc, ppStruct);
  200001. pStruct = *ppStruct;
  200002. }
  200003. fts5StructureExtendLevel(&p->rc, pStruct, iLvl+1, 1, 0);
  200004. if( p->rc ) return;
  200005. pLvl = &pStruct->aLevel[iLvl];
  200006. pLvlOut = &pStruct->aLevel[iLvl+1];
  200007. fts5WriteInit(p, &writer, iSegid);
  200008. /* Add the new segment to the output level */
  200009. pSeg = &pLvlOut->aSeg[pLvlOut->nSeg];
  200010. pLvlOut->nSeg++;
  200011. pSeg->pgnoFirst = 1;
  200012. pSeg->iSegid = iSegid;
  200013. pStruct->nSegment++;
  200014. /* Read input from all segments in the input level */
  200015. nInput = pLvl->nSeg;
  200016. }
  200017. bOldest = (pLvlOut->nSeg==1 && pStruct->nLevel==iLvl+2);
  200018. assert( iLvl>=0 );
  200019. for(fts5MultiIterNew(p, pStruct, flags, 0, 0, 0, iLvl, nInput, &pIter);
  200020. fts5MultiIterEof(p, pIter)==0;
  200021. fts5MultiIterNext(p, pIter, 0, 0)
  200022. ){
  200023. Fts5SegIter *pSegIter = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  200024. int nPos; /* position-list size field value */
  200025. int nTerm;
  200026. const u8 *pTerm;
  200027. pTerm = fts5MultiIterTerm(pIter, &nTerm);
  200028. if( nTerm!=term.n || fts5Memcmp(pTerm, term.p, nTerm) ){
  200029. if( pnRem && writer.nLeafWritten>nRem ){
  200030. break;
  200031. }
  200032. fts5BufferSet(&p->rc, &term, nTerm, pTerm);
  200033. bTermWritten =0;
  200034. }
  200035. /* Check for key annihilation. */
  200036. if( pSegIter->nPos==0 && (bOldest || pSegIter->bDel==0) ) continue;
  200037. if( p->rc==SQLITE_OK && bTermWritten==0 ){
  200038. /* This is a new term. Append a term to the output segment. */
  200039. fts5WriteAppendTerm(p, &writer, nTerm, pTerm);
  200040. bTermWritten = 1;
  200041. }
  200042. /* Append the rowid to the output */
  200043. /* WRITEPOSLISTSIZE */
  200044. fts5WriteAppendRowid(p, &writer, fts5MultiIterRowid(pIter));
  200045. if( eDetail==FTS5_DETAIL_NONE ){
  200046. if( pSegIter->bDel ){
  200047. fts5BufferAppendVarint(&p->rc, &writer.writer.buf, 0);
  200048. if( pSegIter->nPos>0 ){
  200049. fts5BufferAppendVarint(&p->rc, &writer.writer.buf, 0);
  200050. }
  200051. }
  200052. }else{
  200053. /* Append the position-list data to the output */
  200054. nPos = pSegIter->nPos*2 + pSegIter->bDel;
  200055. fts5BufferAppendVarint(&p->rc, &writer.writer.buf, nPos);
  200056. fts5ChunkIterate(p, pSegIter, (void*)&writer, fts5MergeChunkCallback);
  200057. }
  200058. }
  200059. /* Flush the last leaf page to disk. Set the output segment b-tree height
  200060. ** and last leaf page number at the same time. */
  200061. fts5WriteFinish(p, &writer, &pSeg->pgnoLast);
  200062. if( fts5MultiIterEof(p, pIter) ){
  200063. int i;
  200064. /* Remove the redundant segments from the %_data table */
  200065. for(i=0; i<nInput; i++){
  200066. fts5DataRemoveSegment(p, pLvl->aSeg[i].iSegid);
  200067. }
  200068. /* Remove the redundant segments from the input level */
  200069. if( pLvl->nSeg!=nInput ){
  200070. int nMove = (pLvl->nSeg - nInput) * sizeof(Fts5StructureSegment);
  200071. memmove(pLvl->aSeg, &pLvl->aSeg[nInput], nMove);
  200072. }
  200073. pStruct->nSegment -= nInput;
  200074. pLvl->nSeg -= nInput;
  200075. pLvl->nMerge = 0;
  200076. if( pSeg->pgnoLast==0 ){
  200077. pLvlOut->nSeg--;
  200078. pStruct->nSegment--;
  200079. }
  200080. }else{
  200081. assert( pSeg->pgnoLast>0 );
  200082. fts5TrimSegments(p, pIter);
  200083. pLvl->nMerge = nInput;
  200084. }
  200085. fts5MultiIterFree(pIter);
  200086. fts5BufferFree(&term);
  200087. if( pnRem ) *pnRem -= writer.nLeafWritten;
  200088. }
  200089. /*
  200090. ** Do up to nPg pages of automerge work on the index.
  200091. **
  200092. ** Return true if any changes were actually made, or false otherwise.
  200093. */
  200094. static int fts5IndexMerge(
  200095. Fts5Index *p, /* FTS5 backend object */
  200096. Fts5Structure **ppStruct, /* IN/OUT: Current structure of index */
  200097. int nPg, /* Pages of work to do */
  200098. int nMin /* Minimum number of segments to merge */
  200099. ){
  200100. int nRem = nPg;
  200101. int bRet = 0;
  200102. Fts5Structure *pStruct = *ppStruct;
  200103. while( nRem>0 && p->rc==SQLITE_OK ){
  200104. int iLvl; /* To iterate through levels */
  200105. int iBestLvl = 0; /* Level offering the most input segments */
  200106. int nBest = 0; /* Number of input segments on best level */
  200107. /* Set iBestLvl to the level to read input segments from. */
  200108. assert( pStruct->nLevel>0 );
  200109. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  200110. Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
  200111. if( pLvl->nMerge ){
  200112. if( pLvl->nMerge>nBest ){
  200113. iBestLvl = iLvl;
  200114. nBest = pLvl->nMerge;
  200115. }
  200116. break;
  200117. }
  200118. if( pLvl->nSeg>nBest ){
  200119. nBest = pLvl->nSeg;
  200120. iBestLvl = iLvl;
  200121. }
  200122. }
  200123. /* If nBest is still 0, then the index must be empty. */
  200124. #ifdef SQLITE_DEBUG
  200125. for(iLvl=0; nBest==0 && iLvl<pStruct->nLevel; iLvl++){
  200126. assert( pStruct->aLevel[iLvl].nSeg==0 );
  200127. }
  200128. #endif
  200129. if( nBest<nMin && pStruct->aLevel[iBestLvl].nMerge==0 ){
  200130. break;
  200131. }
  200132. bRet = 1;
  200133. fts5IndexMergeLevel(p, &pStruct, iBestLvl, &nRem);
  200134. if( p->rc==SQLITE_OK && pStruct->aLevel[iBestLvl].nMerge==0 ){
  200135. fts5StructurePromote(p, iBestLvl+1, pStruct);
  200136. }
  200137. }
  200138. *ppStruct = pStruct;
  200139. return bRet;
  200140. }
  200141. /*
  200142. ** A total of nLeaf leaf pages of data has just been flushed to a level-0
  200143. ** segment. This function updates the write-counter accordingly and, if
  200144. ** necessary, performs incremental merge work.
  200145. **
  200146. ** If an error occurs, set the Fts5Index.rc error code. If an error has
  200147. ** already occurred, this function is a no-op.
  200148. */
  200149. static void fts5IndexAutomerge(
  200150. Fts5Index *p, /* FTS5 backend object */
  200151. Fts5Structure **ppStruct, /* IN/OUT: Current structure of index */
  200152. int nLeaf /* Number of output leaves just written */
  200153. ){
  200154. if( p->rc==SQLITE_OK && p->pConfig->nAutomerge>0 ){
  200155. Fts5Structure *pStruct = *ppStruct;
  200156. u64 nWrite; /* Initial value of write-counter */
  200157. int nWork; /* Number of work-quanta to perform */
  200158. int nRem; /* Number of leaf pages left to write */
  200159. /* Update the write-counter. While doing so, set nWork. */
  200160. nWrite = pStruct->nWriteCounter;
  200161. nWork = (int)(((nWrite + nLeaf) / p->nWorkUnit) - (nWrite / p->nWorkUnit));
  200162. pStruct->nWriteCounter += nLeaf;
  200163. nRem = (int)(p->nWorkUnit * nWork * pStruct->nLevel);
  200164. fts5IndexMerge(p, ppStruct, nRem, p->pConfig->nAutomerge);
  200165. }
  200166. }
  200167. static void fts5IndexCrisismerge(
  200168. Fts5Index *p, /* FTS5 backend object */
  200169. Fts5Structure **ppStruct /* IN/OUT: Current structure of index */
  200170. ){
  200171. const int nCrisis = p->pConfig->nCrisisMerge;
  200172. Fts5Structure *pStruct = *ppStruct;
  200173. int iLvl = 0;
  200174. assert( p->rc!=SQLITE_OK || pStruct->nLevel>0 );
  200175. while( p->rc==SQLITE_OK && pStruct->aLevel[iLvl].nSeg>=nCrisis ){
  200176. fts5IndexMergeLevel(p, &pStruct, iLvl, 0);
  200177. assert( p->rc!=SQLITE_OK || pStruct->nLevel>(iLvl+1) );
  200178. fts5StructurePromote(p, iLvl+1, pStruct);
  200179. iLvl++;
  200180. }
  200181. *ppStruct = pStruct;
  200182. }
  200183. static int fts5IndexReturn(Fts5Index *p){
  200184. int rc = p->rc;
  200185. p->rc = SQLITE_OK;
  200186. return rc;
  200187. }
  200188. typedef struct Fts5FlushCtx Fts5FlushCtx;
  200189. struct Fts5FlushCtx {
  200190. Fts5Index *pIdx;
  200191. Fts5SegWriter writer;
  200192. };
  200193. /*
  200194. ** Buffer aBuf[] contains a list of varints, all small enough to fit
  200195. ** in a 32-bit integer. Return the size of the largest prefix of this
  200196. ** list nMax bytes or less in size.
  200197. */
  200198. static int fts5PoslistPrefix(const u8 *aBuf, int nMax){
  200199. int ret;
  200200. u32 dummy;
  200201. ret = fts5GetVarint32(aBuf, dummy);
  200202. if( ret<nMax ){
  200203. while( 1 ){
  200204. int i = fts5GetVarint32(&aBuf[ret], dummy);
  200205. if( (ret + i) > nMax ) break;
  200206. ret += i;
  200207. }
  200208. }
  200209. return ret;
  200210. }
  200211. /*
  200212. ** Flush the contents of in-memory hash table iHash to a new level-0
  200213. ** segment on disk. Also update the corresponding structure record.
  200214. **
  200215. ** If an error occurs, set the Fts5Index.rc error code. If an error has
  200216. ** already occurred, this function is a no-op.
  200217. */
  200218. static void fts5FlushOneHash(Fts5Index *p){
  200219. Fts5Hash *pHash = p->pHash;
  200220. Fts5Structure *pStruct;
  200221. int iSegid;
  200222. int pgnoLast = 0; /* Last leaf page number in segment */
  200223. /* Obtain a reference to the index structure and allocate a new segment-id
  200224. ** for the new level-0 segment. */
  200225. pStruct = fts5StructureRead(p);
  200226. iSegid = fts5AllocateSegid(p, pStruct);
  200227. fts5StructureInvalidate(p);
  200228. if( iSegid ){
  200229. const int pgsz = p->pConfig->pgsz;
  200230. int eDetail = p->pConfig->eDetail;
  200231. Fts5StructureSegment *pSeg; /* New segment within pStruct */
  200232. Fts5Buffer *pBuf; /* Buffer in which to assemble leaf page */
  200233. Fts5Buffer *pPgidx; /* Buffer in which to assemble pgidx */
  200234. Fts5SegWriter writer;
  200235. fts5WriteInit(p, &writer, iSegid);
  200236. pBuf = &writer.writer.buf;
  200237. pPgidx = &writer.writer.pgidx;
  200238. /* fts5WriteInit() should have initialized the buffers to (most likely)
  200239. ** the maximum space required. */
  200240. assert( p->rc || pBuf->nSpace>=(pgsz + FTS5_DATA_PADDING) );
  200241. assert( p->rc || pPgidx->nSpace>=(pgsz + FTS5_DATA_PADDING) );
  200242. /* Begin scanning through hash table entries. This loop runs once for each
  200243. ** term/doclist currently stored within the hash table. */
  200244. if( p->rc==SQLITE_OK ){
  200245. p->rc = sqlite3Fts5HashScanInit(pHash, 0, 0);
  200246. }
  200247. while( p->rc==SQLITE_OK && 0==sqlite3Fts5HashScanEof(pHash) ){
  200248. const char *zTerm; /* Buffer containing term */
  200249. const u8 *pDoclist; /* Pointer to doclist for this term */
  200250. int nDoclist; /* Size of doclist in bytes */
  200251. /* Write the term for this entry to disk. */
  200252. sqlite3Fts5HashScanEntry(pHash, &zTerm, &pDoclist, &nDoclist);
  200253. fts5WriteAppendTerm(p, &writer, (int)strlen(zTerm), (const u8*)zTerm);
  200254. if( p->rc!=SQLITE_OK ) break;
  200255. assert( writer.bFirstRowidInPage==0 );
  200256. if( pgsz>=(pBuf->n + pPgidx->n + nDoclist + 1) ){
  200257. /* The entire doclist will fit on the current leaf. */
  200258. fts5BufferSafeAppendBlob(pBuf, pDoclist, nDoclist);
  200259. }else{
  200260. i64 iRowid = 0;
  200261. i64 iDelta = 0;
  200262. int iOff = 0;
  200263. /* The entire doclist will not fit on this leaf. The following
  200264. ** loop iterates through the poslists that make up the current
  200265. ** doclist. */
  200266. while( p->rc==SQLITE_OK && iOff<nDoclist ){
  200267. iOff += fts5GetVarint(&pDoclist[iOff], (u64*)&iDelta);
  200268. iRowid += iDelta;
  200269. if( writer.bFirstRowidInPage ){
  200270. fts5PutU16(&pBuf->p[0], (u16)pBuf->n); /* first rowid on page */
  200271. pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iRowid);
  200272. writer.bFirstRowidInPage = 0;
  200273. fts5WriteDlidxAppend(p, &writer, iRowid);
  200274. if( p->rc!=SQLITE_OK ) break;
  200275. }else{
  200276. pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iDelta);
  200277. }
  200278. assert( pBuf->n<=pBuf->nSpace );
  200279. if( eDetail==FTS5_DETAIL_NONE ){
  200280. if( iOff<nDoclist && pDoclist[iOff]==0 ){
  200281. pBuf->p[pBuf->n++] = 0;
  200282. iOff++;
  200283. if( iOff<nDoclist && pDoclist[iOff]==0 ){
  200284. pBuf->p[pBuf->n++] = 0;
  200285. iOff++;
  200286. }
  200287. }
  200288. if( (pBuf->n + pPgidx->n)>=pgsz ){
  200289. fts5WriteFlushLeaf(p, &writer);
  200290. }
  200291. }else{
  200292. int bDummy;
  200293. int nPos;
  200294. int nCopy = fts5GetPoslistSize(&pDoclist[iOff], &nPos, &bDummy);
  200295. nCopy += nPos;
  200296. if( (pBuf->n + pPgidx->n + nCopy) <= pgsz ){
  200297. /* The entire poslist will fit on the current leaf. So copy
  200298. ** it in one go. */
  200299. fts5BufferSafeAppendBlob(pBuf, &pDoclist[iOff], nCopy);
  200300. }else{
  200301. /* The entire poslist will not fit on this leaf. So it needs
  200302. ** to be broken into sections. The only qualification being
  200303. ** that each varint must be stored contiguously. */
  200304. const u8 *pPoslist = &pDoclist[iOff];
  200305. int iPos = 0;
  200306. while( p->rc==SQLITE_OK ){
  200307. int nSpace = pgsz - pBuf->n - pPgidx->n;
  200308. int n = 0;
  200309. if( (nCopy - iPos)<=nSpace ){
  200310. n = nCopy - iPos;
  200311. }else{
  200312. n = fts5PoslistPrefix(&pPoslist[iPos], nSpace);
  200313. }
  200314. assert( n>0 );
  200315. fts5BufferSafeAppendBlob(pBuf, &pPoslist[iPos], n);
  200316. iPos += n;
  200317. if( (pBuf->n + pPgidx->n)>=pgsz ){
  200318. fts5WriteFlushLeaf(p, &writer);
  200319. }
  200320. if( iPos>=nCopy ) break;
  200321. }
  200322. }
  200323. iOff += nCopy;
  200324. }
  200325. }
  200326. }
  200327. /* TODO2: Doclist terminator written here. */
  200328. /* pBuf->p[pBuf->n++] = '\0'; */
  200329. assert( pBuf->n<=pBuf->nSpace );
  200330. if( p->rc==SQLITE_OK ) sqlite3Fts5HashScanNext(pHash);
  200331. }
  200332. sqlite3Fts5HashClear(pHash);
  200333. fts5WriteFinish(p, &writer, &pgnoLast);
  200334. /* Update the Fts5Structure. It is written back to the database by the
  200335. ** fts5StructureRelease() call below. */
  200336. if( pStruct->nLevel==0 ){
  200337. fts5StructureAddLevel(&p->rc, &pStruct);
  200338. }
  200339. fts5StructureExtendLevel(&p->rc, pStruct, 0, 1, 0);
  200340. if( p->rc==SQLITE_OK ){
  200341. pSeg = &pStruct->aLevel[0].aSeg[ pStruct->aLevel[0].nSeg++ ];
  200342. pSeg->iSegid = iSegid;
  200343. pSeg->pgnoFirst = 1;
  200344. pSeg->pgnoLast = pgnoLast;
  200345. pStruct->nSegment++;
  200346. }
  200347. fts5StructurePromote(p, 0, pStruct);
  200348. }
  200349. fts5IndexAutomerge(p, &pStruct, pgnoLast);
  200350. fts5IndexCrisismerge(p, &pStruct);
  200351. fts5StructureWrite(p, pStruct);
  200352. fts5StructureRelease(pStruct);
  200353. }
  200354. /*
  200355. ** Flush any data stored in the in-memory hash tables to the database.
  200356. */
  200357. static void fts5IndexFlush(Fts5Index *p){
  200358. /* Unless it is empty, flush the hash table to disk */
  200359. if( p->nPendingData ){
  200360. assert( p->pHash );
  200361. p->nPendingData = 0;
  200362. fts5FlushOneHash(p);
  200363. }
  200364. }
  200365. static Fts5Structure *fts5IndexOptimizeStruct(
  200366. Fts5Index *p,
  200367. Fts5Structure *pStruct
  200368. ){
  200369. Fts5Structure *pNew = 0;
  200370. sqlite3_int64 nByte = sizeof(Fts5Structure);
  200371. int nSeg = pStruct->nSegment;
  200372. int i;
  200373. /* Figure out if this structure requires optimization. A structure does
  200374. ** not require optimization if either:
  200375. **
  200376. ** + it consists of fewer than two segments, or
  200377. ** + all segments are on the same level, or
  200378. ** + all segments except one are currently inputs to a merge operation.
  200379. **
  200380. ** In the first case, return NULL. In the second, increment the ref-count
  200381. ** on *pStruct and return a copy of the pointer to it.
  200382. */
  200383. if( nSeg<2 ) return 0;
  200384. for(i=0; i<pStruct->nLevel; i++){
  200385. int nThis = pStruct->aLevel[i].nSeg;
  200386. if( nThis==nSeg || (nThis==nSeg-1 && pStruct->aLevel[i].nMerge==nThis) ){
  200387. fts5StructureRef(pStruct);
  200388. return pStruct;
  200389. }
  200390. assert( pStruct->aLevel[i].nMerge<=nThis );
  200391. }
  200392. nByte += (pStruct->nLevel+1) * sizeof(Fts5StructureLevel);
  200393. pNew = (Fts5Structure*)sqlite3Fts5MallocZero(&p->rc, nByte);
  200394. if( pNew ){
  200395. Fts5StructureLevel *pLvl;
  200396. nByte = nSeg * sizeof(Fts5StructureSegment);
  200397. pNew->nLevel = pStruct->nLevel+1;
  200398. pNew->nRef = 1;
  200399. pNew->nWriteCounter = pStruct->nWriteCounter;
  200400. pLvl = &pNew->aLevel[pStruct->nLevel];
  200401. pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&p->rc, nByte);
  200402. if( pLvl->aSeg ){
  200403. int iLvl, iSeg;
  200404. int iSegOut = 0;
  200405. /* Iterate through all segments, from oldest to newest. Add them to
  200406. ** the new Fts5Level object so that pLvl->aSeg[0] is the oldest
  200407. ** segment in the data structure. */
  200408. for(iLvl=pStruct->nLevel-1; iLvl>=0; iLvl--){
  200409. for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
  200410. pLvl->aSeg[iSegOut] = pStruct->aLevel[iLvl].aSeg[iSeg];
  200411. iSegOut++;
  200412. }
  200413. }
  200414. pNew->nSegment = pLvl->nSeg = nSeg;
  200415. }else{
  200416. sqlite3_free(pNew);
  200417. pNew = 0;
  200418. }
  200419. }
  200420. return pNew;
  200421. }
  200422. static int sqlite3Fts5IndexOptimize(Fts5Index *p){
  200423. Fts5Structure *pStruct;
  200424. Fts5Structure *pNew = 0;
  200425. assert( p->rc==SQLITE_OK );
  200426. fts5IndexFlush(p);
  200427. pStruct = fts5StructureRead(p);
  200428. fts5StructureInvalidate(p);
  200429. if( pStruct ){
  200430. pNew = fts5IndexOptimizeStruct(p, pStruct);
  200431. }
  200432. fts5StructureRelease(pStruct);
  200433. assert( pNew==0 || pNew->nSegment>0 );
  200434. if( pNew ){
  200435. int iLvl;
  200436. for(iLvl=0; pNew->aLevel[iLvl].nSeg==0; iLvl++){}
  200437. while( p->rc==SQLITE_OK && pNew->aLevel[iLvl].nSeg>0 ){
  200438. int nRem = FTS5_OPT_WORK_UNIT;
  200439. fts5IndexMergeLevel(p, &pNew, iLvl, &nRem);
  200440. }
  200441. fts5StructureWrite(p, pNew);
  200442. fts5StructureRelease(pNew);
  200443. }
  200444. return fts5IndexReturn(p);
  200445. }
  200446. /*
  200447. ** This is called to implement the special "VALUES('merge', $nMerge)"
  200448. ** INSERT command.
  200449. */
  200450. static int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge){
  200451. Fts5Structure *pStruct = fts5StructureRead(p);
  200452. if( pStruct ){
  200453. int nMin = p->pConfig->nUsermerge;
  200454. fts5StructureInvalidate(p);
  200455. if( nMerge<0 ){
  200456. Fts5Structure *pNew = fts5IndexOptimizeStruct(p, pStruct);
  200457. fts5StructureRelease(pStruct);
  200458. pStruct = pNew;
  200459. nMin = 2;
  200460. nMerge = nMerge*-1;
  200461. }
  200462. if( pStruct && pStruct->nLevel ){
  200463. if( fts5IndexMerge(p, &pStruct, nMerge, nMin) ){
  200464. fts5StructureWrite(p, pStruct);
  200465. }
  200466. }
  200467. fts5StructureRelease(pStruct);
  200468. }
  200469. return fts5IndexReturn(p);
  200470. }
  200471. static void fts5AppendRowid(
  200472. Fts5Index *p,
  200473. i64 iDelta,
  200474. Fts5Iter *pUnused,
  200475. Fts5Buffer *pBuf
  200476. ){
  200477. UNUSED_PARAM(pUnused);
  200478. fts5BufferAppendVarint(&p->rc, pBuf, iDelta);
  200479. }
  200480. static void fts5AppendPoslist(
  200481. Fts5Index *p,
  200482. i64 iDelta,
  200483. Fts5Iter *pMulti,
  200484. Fts5Buffer *pBuf
  200485. ){
  200486. int nData = pMulti->base.nData;
  200487. int nByte = nData + 9 + 9 + FTS5_DATA_ZERO_PADDING;
  200488. assert( nData>0 );
  200489. if( p->rc==SQLITE_OK && 0==fts5BufferGrow(&p->rc, pBuf, nByte) ){
  200490. fts5BufferSafeAppendVarint(pBuf, iDelta);
  200491. fts5BufferSafeAppendVarint(pBuf, nData*2);
  200492. fts5BufferSafeAppendBlob(pBuf, pMulti->base.pData, nData);
  200493. memset(&pBuf->p[pBuf->n], 0, FTS5_DATA_ZERO_PADDING);
  200494. }
  200495. }
  200496. static void fts5DoclistIterNext(Fts5DoclistIter *pIter){
  200497. u8 *p = pIter->aPoslist + pIter->nSize + pIter->nPoslist;
  200498. assert( pIter->aPoslist );
  200499. if( p>=pIter->aEof ){
  200500. pIter->aPoslist = 0;
  200501. }else{
  200502. i64 iDelta;
  200503. p += fts5GetVarint(p, (u64*)&iDelta);
  200504. pIter->iRowid += iDelta;
  200505. /* Read position list size */
  200506. if( p[0] & 0x80 ){
  200507. int nPos;
  200508. pIter->nSize = fts5GetVarint32(p, nPos);
  200509. pIter->nPoslist = (nPos>>1);
  200510. }else{
  200511. pIter->nPoslist = ((int)(p[0])) >> 1;
  200512. pIter->nSize = 1;
  200513. }
  200514. pIter->aPoslist = p;
  200515. }
  200516. }
  200517. static void fts5DoclistIterInit(
  200518. Fts5Buffer *pBuf,
  200519. Fts5DoclistIter *pIter
  200520. ){
  200521. memset(pIter, 0, sizeof(*pIter));
  200522. pIter->aPoslist = pBuf->p;
  200523. pIter->aEof = &pBuf->p[pBuf->n];
  200524. fts5DoclistIterNext(pIter);
  200525. }
  200526. #if 0
  200527. /*
  200528. ** Append a doclist to buffer pBuf.
  200529. **
  200530. ** This function assumes that space within the buffer has already been
  200531. ** allocated.
  200532. */
  200533. static void fts5MergeAppendDocid(
  200534. Fts5Buffer *pBuf, /* Buffer to write to */
  200535. i64 *piLastRowid, /* IN/OUT: Previous rowid written (if any) */
  200536. i64 iRowid /* Rowid to append */
  200537. ){
  200538. assert( pBuf->n!=0 || (*piLastRowid)==0 );
  200539. fts5BufferSafeAppendVarint(pBuf, iRowid - *piLastRowid);
  200540. *piLastRowid = iRowid;
  200541. }
  200542. #endif
  200543. #define fts5MergeAppendDocid(pBuf, iLastRowid, iRowid) { \
  200544. assert( (pBuf)->n!=0 || (iLastRowid)==0 ); \
  200545. fts5BufferSafeAppendVarint((pBuf), (iRowid) - (iLastRowid)); \
  200546. (iLastRowid) = (iRowid); \
  200547. }
  200548. /*
  200549. ** Swap the contents of buffer *p1 with that of *p2.
  200550. */
  200551. static void fts5BufferSwap(Fts5Buffer *p1, Fts5Buffer *p2){
  200552. Fts5Buffer tmp = *p1;
  200553. *p1 = *p2;
  200554. *p2 = tmp;
  200555. }
  200556. static void fts5NextRowid(Fts5Buffer *pBuf, int *piOff, i64 *piRowid){
  200557. int i = *piOff;
  200558. if( i>=pBuf->n ){
  200559. *piOff = -1;
  200560. }else{
  200561. u64 iVal;
  200562. *piOff = i + sqlite3Fts5GetVarint(&pBuf->p[i], &iVal);
  200563. *piRowid += iVal;
  200564. }
  200565. }
  200566. /*
  200567. ** This is the equivalent of fts5MergePrefixLists() for detail=none mode.
  200568. ** In this case the buffers consist of a delta-encoded list of rowids only.
  200569. */
  200570. static void fts5MergeRowidLists(
  200571. Fts5Index *p, /* FTS5 backend object */
  200572. Fts5Buffer *p1, /* First list to merge */
  200573. Fts5Buffer *p2 /* Second list to merge */
  200574. ){
  200575. int i1 = 0;
  200576. int i2 = 0;
  200577. i64 iRowid1 = 0;
  200578. i64 iRowid2 = 0;
  200579. i64 iOut = 0;
  200580. Fts5Buffer out;
  200581. memset(&out, 0, sizeof(out));
  200582. sqlite3Fts5BufferSize(&p->rc, &out, p1->n + p2->n);
  200583. if( p->rc ) return;
  200584. fts5NextRowid(p1, &i1, &iRowid1);
  200585. fts5NextRowid(p2, &i2, &iRowid2);
  200586. while( i1>=0 || i2>=0 ){
  200587. if( i1>=0 && (i2<0 || iRowid1<iRowid2) ){
  200588. assert( iOut==0 || iRowid1>iOut );
  200589. fts5BufferSafeAppendVarint(&out, iRowid1 - iOut);
  200590. iOut = iRowid1;
  200591. fts5NextRowid(p1, &i1, &iRowid1);
  200592. }else{
  200593. assert( iOut==0 || iRowid2>iOut );
  200594. fts5BufferSafeAppendVarint(&out, iRowid2 - iOut);
  200595. iOut = iRowid2;
  200596. if( i1>=0 && iRowid1==iRowid2 ){
  200597. fts5NextRowid(p1, &i1, &iRowid1);
  200598. }
  200599. fts5NextRowid(p2, &i2, &iRowid2);
  200600. }
  200601. }
  200602. fts5BufferSwap(&out, p1);
  200603. fts5BufferFree(&out);
  200604. }
  200605. /*
  200606. ** Buffers p1 and p2 contain doclists. This function merges the content
  200607. ** of the two doclists together and sets buffer p1 to the result before
  200608. ** returning.
  200609. **
  200610. ** If an error occurs, an error code is left in p->rc. If an error has
  200611. ** already occurred, this function is a no-op.
  200612. */
  200613. static void fts5MergePrefixLists(
  200614. Fts5Index *p, /* FTS5 backend object */
  200615. Fts5Buffer *p1, /* First list to merge */
  200616. Fts5Buffer *p2 /* Second list to merge */
  200617. ){
  200618. if( p2->n ){
  200619. i64 iLastRowid = 0;
  200620. Fts5DoclistIter i1;
  200621. Fts5DoclistIter i2;
  200622. Fts5Buffer out = {0, 0, 0};
  200623. Fts5Buffer tmp = {0, 0, 0};
  200624. /* The maximum size of the output is equal to the sum of the two
  200625. ** input sizes + 1 varint (9 bytes). The extra varint is because if the
  200626. ** first rowid in one input is a large negative number, and the first in
  200627. ** the other a non-negative number, the delta for the non-negative
  200628. ** number will be larger on disk than the literal integer value
  200629. ** was.
  200630. **
  200631. ** Or, if the input position-lists are corrupt, then the output might
  200632. ** include up to 2 extra 10-byte positions created by interpreting -1
  200633. ** (the value PoslistNext64() uses for EOF) as a position and appending
  200634. ** it to the output. This can happen at most once for each input
  200635. ** position-list, hence two 10 byte paddings. */
  200636. if( sqlite3Fts5BufferSize(&p->rc, &out, p1->n + p2->n + 9+10+10) ) return;
  200637. fts5DoclistIterInit(p1, &i1);
  200638. fts5DoclistIterInit(p2, &i2);
  200639. while( 1 ){
  200640. if( i1.iRowid<i2.iRowid ){
  200641. /* Copy entry from i1 */
  200642. fts5MergeAppendDocid(&out, iLastRowid, i1.iRowid);
  200643. fts5BufferSafeAppendBlob(&out, i1.aPoslist, i1.nPoslist+i1.nSize);
  200644. fts5DoclistIterNext(&i1);
  200645. if( i1.aPoslist==0 ) break;
  200646. assert( out.n<=((i1.aPoslist-p1->p) + (i2.aPoslist-p2->p)+9+10+10) );
  200647. }
  200648. else if( i2.iRowid!=i1.iRowid ){
  200649. /* Copy entry from i2 */
  200650. fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
  200651. fts5BufferSafeAppendBlob(&out, i2.aPoslist, i2.nPoslist+i2.nSize);
  200652. fts5DoclistIterNext(&i2);
  200653. if( i2.aPoslist==0 ) break;
  200654. assert( out.n<=((i1.aPoslist-p1->p) + (i2.aPoslist-p2->p)+9+10+10) );
  200655. }
  200656. else{
  200657. /* Merge the two position lists. */
  200658. i64 iPos1 = 0;
  200659. i64 iPos2 = 0;
  200660. int iOff1 = 0;
  200661. int iOff2 = 0;
  200662. u8 *a1 = &i1.aPoslist[i1.nSize];
  200663. u8 *a2 = &i2.aPoslist[i2.nSize];
  200664. int nCopy;
  200665. u8 *aCopy;
  200666. i64 iPrev = 0;
  200667. Fts5PoslistWriter writer;
  200668. memset(&writer, 0, sizeof(writer));
  200669. fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
  200670. fts5BufferZero(&tmp);
  200671. sqlite3Fts5BufferSize(&p->rc, &tmp, i1.nPoslist + i2.nPoslist);
  200672. if( p->rc ) break;
  200673. sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
  200674. sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
  200675. assert_nc( iPos1>=0 && iPos2>=0 );
  200676. if( iPos1<iPos2 ){
  200677. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
  200678. sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
  200679. }else{
  200680. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
  200681. sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
  200682. }
  200683. if( iPos1>=0 && iPos2>=0 ){
  200684. while( 1 ){
  200685. if( iPos1<iPos2 ){
  200686. if( iPos1!=iPrev ){
  200687. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
  200688. }
  200689. sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
  200690. if( iPos1<0 ) break;
  200691. }else{
  200692. assert_nc( iPos2!=iPrev );
  200693. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
  200694. sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
  200695. if( iPos2<0 ) break;
  200696. }
  200697. }
  200698. }
  200699. if( iPos1>=0 ){
  200700. if( iPos1!=iPrev ){
  200701. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
  200702. }
  200703. aCopy = &a1[iOff1];
  200704. nCopy = i1.nPoslist - iOff1;
  200705. }else{
  200706. assert_nc( iPos2>=0 && iPos2!=iPrev );
  200707. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
  200708. aCopy = &a2[iOff2];
  200709. nCopy = i2.nPoslist - iOff2;
  200710. }
  200711. if( nCopy>0 ){
  200712. fts5BufferSafeAppendBlob(&tmp, aCopy, nCopy);
  200713. }
  200714. /* WRITEPOSLISTSIZE */
  200715. fts5BufferSafeAppendVarint(&out, tmp.n * 2);
  200716. fts5BufferSafeAppendBlob(&out, tmp.p, tmp.n);
  200717. fts5DoclistIterNext(&i1);
  200718. fts5DoclistIterNext(&i2);
  200719. assert_nc( out.n<=(p1->n+p2->n+9) );
  200720. if( i1.aPoslist==0 || i2.aPoslist==0 ) break;
  200721. assert( out.n<=((i1.aPoslist-p1->p) + (i2.aPoslist-p2->p)+9+10+10) );
  200722. }
  200723. }
  200724. if( i1.aPoslist ){
  200725. fts5MergeAppendDocid(&out, iLastRowid, i1.iRowid);
  200726. fts5BufferSafeAppendBlob(&out, i1.aPoslist, i1.aEof - i1.aPoslist);
  200727. }
  200728. else if( i2.aPoslist ){
  200729. fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
  200730. fts5BufferSafeAppendBlob(&out, i2.aPoslist, i2.aEof - i2.aPoslist);
  200731. }
  200732. assert_nc( out.n<=(p1->n+p2->n+9) );
  200733. fts5BufferSet(&p->rc, p1, out.n, out.p);
  200734. fts5BufferFree(&tmp);
  200735. fts5BufferFree(&out);
  200736. }
  200737. }
  200738. static void fts5SetupPrefixIter(
  200739. Fts5Index *p, /* Index to read from */
  200740. int bDesc, /* True for "ORDER BY rowid DESC" */
  200741. const u8 *pToken, /* Buffer containing prefix to match */
  200742. int nToken, /* Size of buffer pToken in bytes */
  200743. Fts5Colset *pColset, /* Restrict matches to these columns */
  200744. Fts5Iter **ppIter /* OUT: New iterator */
  200745. ){
  200746. Fts5Structure *pStruct;
  200747. Fts5Buffer *aBuf;
  200748. const int nBuf = 32;
  200749. void (*xMerge)(Fts5Index*, Fts5Buffer*, Fts5Buffer*);
  200750. void (*xAppend)(Fts5Index*, i64, Fts5Iter*, Fts5Buffer*);
  200751. if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
  200752. xMerge = fts5MergeRowidLists;
  200753. xAppend = fts5AppendRowid;
  200754. }else{
  200755. xMerge = fts5MergePrefixLists;
  200756. xAppend = fts5AppendPoslist;
  200757. }
  200758. aBuf = (Fts5Buffer*)fts5IdxMalloc(p, sizeof(Fts5Buffer)*nBuf);
  200759. pStruct = fts5StructureRead(p);
  200760. if( aBuf && pStruct ){
  200761. const int flags = FTS5INDEX_QUERY_SCAN
  200762. | FTS5INDEX_QUERY_SKIPEMPTY
  200763. | FTS5INDEX_QUERY_NOOUTPUT;
  200764. int i;
  200765. i64 iLastRowid = 0;
  200766. Fts5Iter *p1 = 0; /* Iterator used to gather data from index */
  200767. Fts5Data *pData;
  200768. Fts5Buffer doclist;
  200769. int bNewTerm = 1;
  200770. memset(&doclist, 0, sizeof(doclist));
  200771. fts5MultiIterNew(p, pStruct, flags, pColset, pToken, nToken, -1, 0, &p1);
  200772. fts5IterSetOutputCb(&p->rc, p1);
  200773. for( /* no-op */ ;
  200774. fts5MultiIterEof(p, p1)==0;
  200775. fts5MultiIterNext2(p, p1, &bNewTerm)
  200776. ){
  200777. Fts5SegIter *pSeg = &p1->aSeg[ p1->aFirst[1].iFirst ];
  200778. int nTerm = pSeg->term.n;
  200779. const u8 *pTerm = pSeg->term.p;
  200780. p1->xSetOutputs(p1, pSeg);
  200781. assert_nc( memcmp(pToken, pTerm, MIN(nToken, nTerm))<=0 );
  200782. if( bNewTerm ){
  200783. if( nTerm<nToken || memcmp(pToken, pTerm, nToken) ) break;
  200784. }
  200785. if( p1->base.nData==0 ) continue;
  200786. if( p1->base.iRowid<=iLastRowid && doclist.n>0 ){
  200787. for(i=0; p->rc==SQLITE_OK && doclist.n; i++){
  200788. assert( i<nBuf );
  200789. if( aBuf[i].n==0 ){
  200790. fts5BufferSwap(&doclist, &aBuf[i]);
  200791. fts5BufferZero(&doclist);
  200792. }else{
  200793. xMerge(p, &doclist, &aBuf[i]);
  200794. fts5BufferZero(&aBuf[i]);
  200795. }
  200796. }
  200797. iLastRowid = 0;
  200798. }
  200799. xAppend(p, p1->base.iRowid-iLastRowid, p1, &doclist);
  200800. iLastRowid = p1->base.iRowid;
  200801. }
  200802. for(i=0; i<nBuf; i++){
  200803. if( p->rc==SQLITE_OK ){
  200804. xMerge(p, &doclist, &aBuf[i]);
  200805. }
  200806. fts5BufferFree(&aBuf[i]);
  200807. }
  200808. fts5MultiIterFree(p1);
  200809. pData = fts5IdxMalloc(p, sizeof(Fts5Data)+doclist.n+FTS5_DATA_ZERO_PADDING);
  200810. if( pData ){
  200811. pData->p = (u8*)&pData[1];
  200812. pData->nn = pData->szLeaf = doclist.n;
  200813. if( doclist.n ) memcpy(pData->p, doclist.p, doclist.n);
  200814. fts5MultiIterNew2(p, pData, bDesc, ppIter);
  200815. }
  200816. fts5BufferFree(&doclist);
  200817. }
  200818. fts5StructureRelease(pStruct);
  200819. sqlite3_free(aBuf);
  200820. }
  200821. /*
  200822. ** Indicate that all subsequent calls to sqlite3Fts5IndexWrite() pertain
  200823. ** to the document with rowid iRowid.
  200824. */
  200825. static int sqlite3Fts5IndexBeginWrite(Fts5Index *p, int bDelete, i64 iRowid){
  200826. assert( p->rc==SQLITE_OK );
  200827. /* Allocate the hash table if it has not already been allocated */
  200828. if( p->pHash==0 ){
  200829. p->rc = sqlite3Fts5HashNew(p->pConfig, &p->pHash, &p->nPendingData);
  200830. }
  200831. /* Flush the hash table to disk if required */
  200832. if( iRowid<p->iWriteRowid
  200833. || (iRowid==p->iWriteRowid && p->bDelete==0)
  200834. || (p->nPendingData > p->pConfig->nHashSize)
  200835. ){
  200836. fts5IndexFlush(p);
  200837. }
  200838. p->iWriteRowid = iRowid;
  200839. p->bDelete = bDelete;
  200840. return fts5IndexReturn(p);
  200841. }
  200842. /*
  200843. ** Commit data to disk.
  200844. */
  200845. static int sqlite3Fts5IndexSync(Fts5Index *p){
  200846. assert( p->rc==SQLITE_OK );
  200847. fts5IndexFlush(p);
  200848. fts5CloseReader(p);
  200849. return fts5IndexReturn(p);
  200850. }
  200851. /*
  200852. ** Discard any data stored in the in-memory hash tables. Do not write it
  200853. ** to the database. Additionally, assume that the contents of the %_data
  200854. ** table may have changed on disk. So any in-memory caches of %_data
  200855. ** records must be invalidated.
  200856. */
  200857. static int sqlite3Fts5IndexRollback(Fts5Index *p){
  200858. fts5CloseReader(p);
  200859. fts5IndexDiscardData(p);
  200860. fts5StructureInvalidate(p);
  200861. /* assert( p->rc==SQLITE_OK ); */
  200862. return SQLITE_OK;
  200863. }
  200864. /*
  200865. ** The %_data table is completely empty when this function is called. This
  200866. ** function populates it with the initial structure objects for each index,
  200867. ** and the initial version of the "averages" record (a zero-byte blob).
  200868. */
  200869. static int sqlite3Fts5IndexReinit(Fts5Index *p){
  200870. Fts5Structure s;
  200871. fts5StructureInvalidate(p);
  200872. memset(&s, 0, sizeof(Fts5Structure));
  200873. fts5DataWrite(p, FTS5_AVERAGES_ROWID, (const u8*)"", 0);
  200874. fts5StructureWrite(p, &s);
  200875. return fts5IndexReturn(p);
  200876. }
  200877. /*
  200878. ** Open a new Fts5Index handle. If the bCreate argument is true, create
  200879. ** and initialize the underlying %_data table.
  200880. **
  200881. ** If successful, set *pp to point to the new object and return SQLITE_OK.
  200882. ** Otherwise, set *pp to NULL and return an SQLite error code.
  200883. */
  200884. static int sqlite3Fts5IndexOpen(
  200885. Fts5Config *pConfig,
  200886. int bCreate,
  200887. Fts5Index **pp,
  200888. char **pzErr
  200889. ){
  200890. int rc = SQLITE_OK;
  200891. Fts5Index *p; /* New object */
  200892. *pp = p = (Fts5Index*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Index));
  200893. if( rc==SQLITE_OK ){
  200894. p->pConfig = pConfig;
  200895. p->nWorkUnit = FTS5_WORK_UNIT;
  200896. p->zDataTbl = sqlite3Fts5Mprintf(&rc, "%s_data", pConfig->zName);
  200897. if( p->zDataTbl && bCreate ){
  200898. rc = sqlite3Fts5CreateTable(
  200899. pConfig, "data", "id INTEGER PRIMARY KEY, block BLOB", 0, pzErr
  200900. );
  200901. if( rc==SQLITE_OK ){
  200902. rc = sqlite3Fts5CreateTable(pConfig, "idx",
  200903. "segid, term, pgno, PRIMARY KEY(segid, term)",
  200904. 1, pzErr
  200905. );
  200906. }
  200907. if( rc==SQLITE_OK ){
  200908. rc = sqlite3Fts5IndexReinit(p);
  200909. }
  200910. }
  200911. }
  200912. assert( rc!=SQLITE_OK || p->rc==SQLITE_OK );
  200913. if( rc ){
  200914. sqlite3Fts5IndexClose(p);
  200915. *pp = 0;
  200916. }
  200917. return rc;
  200918. }
  200919. /*
  200920. ** Close a handle opened by an earlier call to sqlite3Fts5IndexOpen().
  200921. */
  200922. static int sqlite3Fts5IndexClose(Fts5Index *p){
  200923. int rc = SQLITE_OK;
  200924. if( p ){
  200925. assert( p->pReader==0 );
  200926. fts5StructureInvalidate(p);
  200927. sqlite3_finalize(p->pWriter);
  200928. sqlite3_finalize(p->pDeleter);
  200929. sqlite3_finalize(p->pIdxWriter);
  200930. sqlite3_finalize(p->pIdxDeleter);
  200931. sqlite3_finalize(p->pIdxSelect);
  200932. sqlite3_finalize(p->pDataVersion);
  200933. sqlite3Fts5HashFree(p->pHash);
  200934. sqlite3_free(p->zDataTbl);
  200935. sqlite3_free(p);
  200936. }
  200937. return rc;
  200938. }
  200939. /*
  200940. ** Argument p points to a buffer containing utf-8 text that is n bytes in
  200941. ** size. Return the number of bytes in the nChar character prefix of the
  200942. ** buffer, or 0 if there are less than nChar characters in total.
  200943. */
  200944. static int sqlite3Fts5IndexCharlenToBytelen(
  200945. const char *p,
  200946. int nByte,
  200947. int nChar
  200948. ){
  200949. int n = 0;
  200950. int i;
  200951. for(i=0; i<nChar; i++){
  200952. if( n>=nByte ) return 0; /* Input contains fewer than nChar chars */
  200953. if( (unsigned char)p[n++]>=0xc0 ){
  200954. while( (p[n] & 0xc0)==0x80 ){
  200955. n++;
  200956. if( n>=nByte ) break;
  200957. }
  200958. }
  200959. }
  200960. return n;
  200961. }
  200962. /*
  200963. ** pIn is a UTF-8 encoded string, nIn bytes in size. Return the number of
  200964. ** unicode characters in the string.
  200965. */
  200966. static int fts5IndexCharlen(const char *pIn, int nIn){
  200967. int nChar = 0;
  200968. int i = 0;
  200969. while( i<nIn ){
  200970. if( (unsigned char)pIn[i++]>=0xc0 ){
  200971. while( i<nIn && (pIn[i] & 0xc0)==0x80 ) i++;
  200972. }
  200973. nChar++;
  200974. }
  200975. return nChar;
  200976. }
  200977. /*
  200978. ** Insert or remove data to or from the index. Each time a document is
  200979. ** added to or removed from the index, this function is called one or more
  200980. ** times.
  200981. **
  200982. ** For an insert, it must be called once for each token in the new document.
  200983. ** If the operation is a delete, it must be called (at least) once for each
  200984. ** unique token in the document with an iCol value less than zero. The iPos
  200985. ** argument is ignored for a delete.
  200986. */
  200987. static int sqlite3Fts5IndexWrite(
  200988. Fts5Index *p, /* Index to write to */
  200989. int iCol, /* Column token appears in (-ve -> delete) */
  200990. int iPos, /* Position of token within column */
  200991. const char *pToken, int nToken /* Token to add or remove to or from index */
  200992. ){
  200993. int i; /* Used to iterate through indexes */
  200994. int rc = SQLITE_OK; /* Return code */
  200995. Fts5Config *pConfig = p->pConfig;
  200996. assert( p->rc==SQLITE_OK );
  200997. assert( (iCol<0)==p->bDelete );
  200998. /* Add the entry to the main terms index. */
  200999. rc = sqlite3Fts5HashWrite(
  201000. p->pHash, p->iWriteRowid, iCol, iPos, FTS5_MAIN_PREFIX, pToken, nToken
  201001. );
  201002. for(i=0; i<pConfig->nPrefix && rc==SQLITE_OK; i++){
  201003. const int nChar = pConfig->aPrefix[i];
  201004. int nByte = sqlite3Fts5IndexCharlenToBytelen(pToken, nToken, nChar);
  201005. if( nByte ){
  201006. rc = sqlite3Fts5HashWrite(p->pHash,
  201007. p->iWriteRowid, iCol, iPos, (char)(FTS5_MAIN_PREFIX+i+1), pToken,
  201008. nByte
  201009. );
  201010. }
  201011. }
  201012. return rc;
  201013. }
  201014. /*
  201015. ** Open a new iterator to iterate though all rowid that match the
  201016. ** specified token or token prefix.
  201017. */
  201018. static int sqlite3Fts5IndexQuery(
  201019. Fts5Index *p, /* FTS index to query */
  201020. const char *pToken, int nToken, /* Token (or prefix) to query for */
  201021. int flags, /* Mask of FTS5INDEX_QUERY_X flags */
  201022. Fts5Colset *pColset, /* Match these columns only */
  201023. Fts5IndexIter **ppIter /* OUT: New iterator object */
  201024. ){
  201025. Fts5Config *pConfig = p->pConfig;
  201026. Fts5Iter *pRet = 0;
  201027. Fts5Buffer buf = {0, 0, 0};
  201028. /* If the QUERY_SCAN flag is set, all other flags must be clear. */
  201029. assert( (flags & FTS5INDEX_QUERY_SCAN)==0 || flags==FTS5INDEX_QUERY_SCAN );
  201030. if( sqlite3Fts5BufferSize(&p->rc, &buf, nToken+1)==0 ){
  201031. int iIdx = 0; /* Index to search */
  201032. if( nToken ) memcpy(&buf.p[1], pToken, nToken);
  201033. /* Figure out which index to search and set iIdx accordingly. If this
  201034. ** is a prefix query for which there is no prefix index, set iIdx to
  201035. ** greater than pConfig->nPrefix to indicate that the query will be
  201036. ** satisfied by scanning multiple terms in the main index.
  201037. **
  201038. ** If the QUERY_TEST_NOIDX flag was specified, then this must be a
  201039. ** prefix-query. Instead of using a prefix-index (if one exists),
  201040. ** evaluate the prefix query using the main FTS index. This is used
  201041. ** for internal sanity checking by the integrity-check in debug
  201042. ** mode only. */
  201043. #ifdef SQLITE_DEBUG
  201044. if( pConfig->bPrefixIndex==0 || (flags & FTS5INDEX_QUERY_TEST_NOIDX) ){
  201045. assert( flags & FTS5INDEX_QUERY_PREFIX );
  201046. iIdx = 1+pConfig->nPrefix;
  201047. }else
  201048. #endif
  201049. if( flags & FTS5INDEX_QUERY_PREFIX ){
  201050. int nChar = fts5IndexCharlen(pToken, nToken);
  201051. for(iIdx=1; iIdx<=pConfig->nPrefix; iIdx++){
  201052. if( pConfig->aPrefix[iIdx-1]==nChar ) break;
  201053. }
  201054. }
  201055. if( iIdx<=pConfig->nPrefix ){
  201056. /* Straight index lookup */
  201057. Fts5Structure *pStruct = fts5StructureRead(p);
  201058. buf.p[0] = (u8)(FTS5_MAIN_PREFIX + iIdx);
  201059. if( pStruct ){
  201060. fts5MultiIterNew(p, pStruct, flags | FTS5INDEX_QUERY_SKIPEMPTY,
  201061. pColset, buf.p, nToken+1, -1, 0, &pRet
  201062. );
  201063. fts5StructureRelease(pStruct);
  201064. }
  201065. }else{
  201066. /* Scan multiple terms in the main index */
  201067. int bDesc = (flags & FTS5INDEX_QUERY_DESC)!=0;
  201068. buf.p[0] = FTS5_MAIN_PREFIX;
  201069. fts5SetupPrefixIter(p, bDesc, buf.p, nToken+1, pColset, &pRet);
  201070. assert( p->rc!=SQLITE_OK || pRet->pColset==0 );
  201071. fts5IterSetOutputCb(&p->rc, pRet);
  201072. if( p->rc==SQLITE_OK ){
  201073. Fts5SegIter *pSeg = &pRet->aSeg[pRet->aFirst[1].iFirst];
  201074. if( pSeg->pLeaf ) pRet->xSetOutputs(pRet, pSeg);
  201075. }
  201076. }
  201077. if( p->rc ){
  201078. sqlite3Fts5IterClose((Fts5IndexIter*)pRet);
  201079. pRet = 0;
  201080. fts5CloseReader(p);
  201081. }
  201082. *ppIter = (Fts5IndexIter*)pRet;
  201083. sqlite3Fts5BufferFree(&buf);
  201084. }
  201085. return fts5IndexReturn(p);
  201086. }
  201087. /*
  201088. ** Return true if the iterator passed as the only argument is at EOF.
  201089. */
  201090. /*
  201091. ** Move to the next matching rowid.
  201092. */
  201093. static int sqlite3Fts5IterNext(Fts5IndexIter *pIndexIter){
  201094. Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
  201095. assert( pIter->pIndex->rc==SQLITE_OK );
  201096. fts5MultiIterNext(pIter->pIndex, pIter, 0, 0);
  201097. return fts5IndexReturn(pIter->pIndex);
  201098. }
  201099. /*
  201100. ** Move to the next matching term/rowid. Used by the fts5vocab module.
  201101. */
  201102. static int sqlite3Fts5IterNextScan(Fts5IndexIter *pIndexIter){
  201103. Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
  201104. Fts5Index *p = pIter->pIndex;
  201105. assert( pIter->pIndex->rc==SQLITE_OK );
  201106. fts5MultiIterNext(p, pIter, 0, 0);
  201107. if( p->rc==SQLITE_OK ){
  201108. Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  201109. if( pSeg->pLeaf && pSeg->term.p[0]!=FTS5_MAIN_PREFIX ){
  201110. fts5DataRelease(pSeg->pLeaf);
  201111. pSeg->pLeaf = 0;
  201112. pIter->base.bEof = 1;
  201113. }
  201114. }
  201115. return fts5IndexReturn(pIter->pIndex);
  201116. }
  201117. /*
  201118. ** Move to the next matching rowid that occurs at or after iMatch. The
  201119. ** definition of "at or after" depends on whether this iterator iterates
  201120. ** in ascending or descending rowid order.
  201121. */
  201122. static int sqlite3Fts5IterNextFrom(Fts5IndexIter *pIndexIter, i64 iMatch){
  201123. Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
  201124. fts5MultiIterNextFrom(pIter->pIndex, pIter, iMatch);
  201125. return fts5IndexReturn(pIter->pIndex);
  201126. }
  201127. /*
  201128. ** Return the current term.
  201129. */
  201130. static const char *sqlite3Fts5IterTerm(Fts5IndexIter *pIndexIter, int *pn){
  201131. int n;
  201132. const char *z = (const char*)fts5MultiIterTerm((Fts5Iter*)pIndexIter, &n);
  201133. *pn = n-1;
  201134. return &z[1];
  201135. }
  201136. /*
  201137. ** Close an iterator opened by an earlier call to sqlite3Fts5IndexQuery().
  201138. */
  201139. static void sqlite3Fts5IterClose(Fts5IndexIter *pIndexIter){
  201140. if( pIndexIter ){
  201141. Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
  201142. Fts5Index *pIndex = pIter->pIndex;
  201143. fts5MultiIterFree(pIter);
  201144. fts5CloseReader(pIndex);
  201145. }
  201146. }
  201147. /*
  201148. ** Read and decode the "averages" record from the database.
  201149. **
  201150. ** Parameter anSize must point to an array of size nCol, where nCol is
  201151. ** the number of user defined columns in the FTS table.
  201152. */
  201153. static int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize){
  201154. int nCol = p->pConfig->nCol;
  201155. Fts5Data *pData;
  201156. *pnRow = 0;
  201157. memset(anSize, 0, sizeof(i64) * nCol);
  201158. pData = fts5DataRead(p, FTS5_AVERAGES_ROWID);
  201159. if( p->rc==SQLITE_OK && pData->nn ){
  201160. int i = 0;
  201161. int iCol;
  201162. i += fts5GetVarint(&pData->p[i], (u64*)pnRow);
  201163. for(iCol=0; i<pData->nn && iCol<nCol; iCol++){
  201164. i += fts5GetVarint(&pData->p[i], (u64*)&anSize[iCol]);
  201165. }
  201166. }
  201167. fts5DataRelease(pData);
  201168. return fts5IndexReturn(p);
  201169. }
  201170. /*
  201171. ** Replace the current "averages" record with the contents of the buffer
  201172. ** supplied as the second argument.
  201173. */
  201174. static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8 *pData, int nData){
  201175. assert( p->rc==SQLITE_OK );
  201176. fts5DataWrite(p, FTS5_AVERAGES_ROWID, pData, nData);
  201177. return fts5IndexReturn(p);
  201178. }
  201179. /*
  201180. ** Return the total number of blocks this module has read from the %_data
  201181. ** table since it was created.
  201182. */
  201183. static int sqlite3Fts5IndexReads(Fts5Index *p){
  201184. return p->nRead;
  201185. }
  201186. /*
  201187. ** Set the 32-bit cookie value stored at the start of all structure
  201188. ** records to the value passed as the second argument.
  201189. **
  201190. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  201191. ** occurs.
  201192. */
  201193. static int sqlite3Fts5IndexSetCookie(Fts5Index *p, int iNew){
  201194. int rc; /* Return code */
  201195. Fts5Config *pConfig = p->pConfig; /* Configuration object */
  201196. u8 aCookie[4]; /* Binary representation of iNew */
  201197. sqlite3_blob *pBlob = 0;
  201198. assert( p->rc==SQLITE_OK );
  201199. sqlite3Fts5Put32(aCookie, iNew);
  201200. rc = sqlite3_blob_open(pConfig->db, pConfig->zDb, p->zDataTbl,
  201201. "block", FTS5_STRUCTURE_ROWID, 1, &pBlob
  201202. );
  201203. if( rc==SQLITE_OK ){
  201204. sqlite3_blob_write(pBlob, aCookie, 4, 0);
  201205. rc = sqlite3_blob_close(pBlob);
  201206. }
  201207. return rc;
  201208. }
  201209. static int sqlite3Fts5IndexLoadConfig(Fts5Index *p){
  201210. Fts5Structure *pStruct;
  201211. pStruct = fts5StructureRead(p);
  201212. fts5StructureRelease(pStruct);
  201213. return fts5IndexReturn(p);
  201214. }
  201215. /*************************************************************************
  201216. **************************************************************************
  201217. ** Below this point is the implementation of the integrity-check
  201218. ** functionality.
  201219. */
  201220. /*
  201221. ** Return a simple checksum value based on the arguments.
  201222. */
  201223. static u64 sqlite3Fts5IndexEntryCksum(
  201224. i64 iRowid,
  201225. int iCol,
  201226. int iPos,
  201227. int iIdx,
  201228. const char *pTerm,
  201229. int nTerm
  201230. ){
  201231. int i;
  201232. u64 ret = iRowid;
  201233. ret += (ret<<3) + iCol;
  201234. ret += (ret<<3) + iPos;
  201235. if( iIdx>=0 ) ret += (ret<<3) + (FTS5_MAIN_PREFIX + iIdx);
  201236. for(i=0; i<nTerm; i++) ret += (ret<<3) + pTerm[i];
  201237. return ret;
  201238. }
  201239. #ifdef SQLITE_DEBUG
  201240. /*
  201241. ** This function is purely an internal test. It does not contribute to
  201242. ** FTS functionality, or even the integrity-check, in any way.
  201243. **
  201244. ** Instead, it tests that the same set of pgno/rowid combinations are
  201245. ** visited regardless of whether the doclist-index identified by parameters
  201246. ** iSegid/iLeaf is iterated in forwards or reverse order.
  201247. */
  201248. static void fts5TestDlidxReverse(
  201249. Fts5Index *p,
  201250. int iSegid, /* Segment id to load from */
  201251. int iLeaf /* Load doclist-index for this leaf */
  201252. ){
  201253. Fts5DlidxIter *pDlidx = 0;
  201254. u64 cksum1 = 13;
  201255. u64 cksum2 = 13;
  201256. for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iLeaf);
  201257. fts5DlidxIterEof(p, pDlidx)==0;
  201258. fts5DlidxIterNext(p, pDlidx)
  201259. ){
  201260. i64 iRowid = fts5DlidxIterRowid(pDlidx);
  201261. int pgno = fts5DlidxIterPgno(pDlidx);
  201262. assert( pgno>iLeaf );
  201263. cksum1 += iRowid + ((i64)pgno<<32);
  201264. }
  201265. fts5DlidxIterFree(pDlidx);
  201266. pDlidx = 0;
  201267. for(pDlidx=fts5DlidxIterInit(p, 1, iSegid, iLeaf);
  201268. fts5DlidxIterEof(p, pDlidx)==0;
  201269. fts5DlidxIterPrev(p, pDlidx)
  201270. ){
  201271. i64 iRowid = fts5DlidxIterRowid(pDlidx);
  201272. int pgno = fts5DlidxIterPgno(pDlidx);
  201273. assert( fts5DlidxIterPgno(pDlidx)>iLeaf );
  201274. cksum2 += iRowid + ((i64)pgno<<32);
  201275. }
  201276. fts5DlidxIterFree(pDlidx);
  201277. pDlidx = 0;
  201278. if( p->rc==SQLITE_OK && cksum1!=cksum2 ) p->rc = FTS5_CORRUPT;
  201279. }
  201280. static int fts5QueryCksum(
  201281. Fts5Index *p, /* Fts5 index object */
  201282. int iIdx,
  201283. const char *z, /* Index key to query for */
  201284. int n, /* Size of index key in bytes */
  201285. int flags, /* Flags for Fts5IndexQuery */
  201286. u64 *pCksum /* IN/OUT: Checksum value */
  201287. ){
  201288. int eDetail = p->pConfig->eDetail;
  201289. u64 cksum = *pCksum;
  201290. Fts5IndexIter *pIter = 0;
  201291. int rc = sqlite3Fts5IndexQuery(p, z, n, flags, 0, &pIter);
  201292. while( rc==SQLITE_OK && 0==sqlite3Fts5IterEof(pIter) ){
  201293. i64 rowid = pIter->iRowid;
  201294. if( eDetail==FTS5_DETAIL_NONE ){
  201295. cksum ^= sqlite3Fts5IndexEntryCksum(rowid, 0, 0, iIdx, z, n);
  201296. }else{
  201297. Fts5PoslistReader sReader;
  201298. for(sqlite3Fts5PoslistReaderInit(pIter->pData, pIter->nData, &sReader);
  201299. sReader.bEof==0;
  201300. sqlite3Fts5PoslistReaderNext(&sReader)
  201301. ){
  201302. int iCol = FTS5_POS2COLUMN(sReader.iPos);
  201303. int iOff = FTS5_POS2OFFSET(sReader.iPos);
  201304. cksum ^= sqlite3Fts5IndexEntryCksum(rowid, iCol, iOff, iIdx, z, n);
  201305. }
  201306. }
  201307. if( rc==SQLITE_OK ){
  201308. rc = sqlite3Fts5IterNext(pIter);
  201309. }
  201310. }
  201311. sqlite3Fts5IterClose(pIter);
  201312. *pCksum = cksum;
  201313. return rc;
  201314. }
  201315. /*
  201316. ** This function is also purely an internal test. It does not contribute to
  201317. ** FTS functionality, or even the integrity-check, in any way.
  201318. */
  201319. static void fts5TestTerm(
  201320. Fts5Index *p,
  201321. Fts5Buffer *pPrev, /* Previous term */
  201322. const char *z, int n, /* Possibly new term to test */
  201323. u64 expected,
  201324. u64 *pCksum
  201325. ){
  201326. int rc = p->rc;
  201327. if( pPrev->n==0 ){
  201328. fts5BufferSet(&rc, pPrev, n, (const u8*)z);
  201329. }else
  201330. if( rc==SQLITE_OK && (pPrev->n!=n || memcmp(pPrev->p, z, n)) ){
  201331. u64 cksum3 = *pCksum;
  201332. const char *zTerm = (const char*)&pPrev->p[1]; /* term sans prefix-byte */
  201333. int nTerm = pPrev->n-1; /* Size of zTerm in bytes */
  201334. int iIdx = (pPrev->p[0] - FTS5_MAIN_PREFIX);
  201335. int flags = (iIdx==0 ? 0 : FTS5INDEX_QUERY_PREFIX);
  201336. u64 ck1 = 0;
  201337. u64 ck2 = 0;
  201338. /* Check that the results returned for ASC and DESC queries are
  201339. ** the same. If not, call this corruption. */
  201340. rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, flags, &ck1);
  201341. if( rc==SQLITE_OK ){
  201342. int f = flags|FTS5INDEX_QUERY_DESC;
  201343. rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
  201344. }
  201345. if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
  201346. /* If this is a prefix query, check that the results returned if the
  201347. ** the index is disabled are the same. In both ASC and DESC order.
  201348. **
  201349. ** This check may only be performed if the hash table is empty. This
  201350. ** is because the hash table only supports a single scan query at
  201351. ** a time, and the multi-iter loop from which this function is called
  201352. ** is already performing such a scan. */
  201353. if( p->nPendingData==0 ){
  201354. if( iIdx>0 && rc==SQLITE_OK ){
  201355. int f = flags|FTS5INDEX_QUERY_TEST_NOIDX;
  201356. ck2 = 0;
  201357. rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
  201358. if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
  201359. }
  201360. if( iIdx>0 && rc==SQLITE_OK ){
  201361. int f = flags|FTS5INDEX_QUERY_TEST_NOIDX|FTS5INDEX_QUERY_DESC;
  201362. ck2 = 0;
  201363. rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
  201364. if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
  201365. }
  201366. }
  201367. cksum3 ^= ck1;
  201368. fts5BufferSet(&rc, pPrev, n, (const u8*)z);
  201369. if( rc==SQLITE_OK && cksum3!=expected ){
  201370. rc = FTS5_CORRUPT;
  201371. }
  201372. *pCksum = cksum3;
  201373. }
  201374. p->rc = rc;
  201375. }
  201376. #else
  201377. # define fts5TestDlidxReverse(x,y,z)
  201378. # define fts5TestTerm(u,v,w,x,y,z)
  201379. #endif
  201380. /*
  201381. ** Check that:
  201382. **
  201383. ** 1) All leaves of pSeg between iFirst and iLast (inclusive) exist and
  201384. ** contain zero terms.
  201385. ** 2) All leaves of pSeg between iNoRowid and iLast (inclusive) exist and
  201386. ** contain zero rowids.
  201387. */
  201388. static void fts5IndexIntegrityCheckEmpty(
  201389. Fts5Index *p,
  201390. Fts5StructureSegment *pSeg, /* Segment to check internal consistency */
  201391. int iFirst,
  201392. int iNoRowid,
  201393. int iLast
  201394. ){
  201395. int i;
  201396. /* Now check that the iter.nEmpty leaves following the current leaf
  201397. ** (a) exist and (b) contain no terms. */
  201398. for(i=iFirst; p->rc==SQLITE_OK && i<=iLast; i++){
  201399. Fts5Data *pLeaf = fts5DataRead(p, FTS5_SEGMENT_ROWID(pSeg->iSegid, i));
  201400. if( pLeaf ){
  201401. if( !fts5LeafIsTermless(pLeaf) ) p->rc = FTS5_CORRUPT;
  201402. if( i>=iNoRowid && 0!=fts5LeafFirstRowidOff(pLeaf) ) p->rc = FTS5_CORRUPT;
  201403. }
  201404. fts5DataRelease(pLeaf);
  201405. }
  201406. }
  201407. static void fts5IntegrityCheckPgidx(Fts5Index *p, Fts5Data *pLeaf){
  201408. int iTermOff = 0;
  201409. int ii;
  201410. Fts5Buffer buf1 = {0,0,0};
  201411. Fts5Buffer buf2 = {0,0,0};
  201412. ii = pLeaf->szLeaf;
  201413. while( ii<pLeaf->nn && p->rc==SQLITE_OK ){
  201414. int res;
  201415. int iOff;
  201416. int nIncr;
  201417. ii += fts5GetVarint32(&pLeaf->p[ii], nIncr);
  201418. iTermOff += nIncr;
  201419. iOff = iTermOff;
  201420. if( iOff>=pLeaf->szLeaf ){
  201421. p->rc = FTS5_CORRUPT;
  201422. }else if( iTermOff==nIncr ){
  201423. int nByte;
  201424. iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);
  201425. if( (iOff+nByte)>pLeaf->szLeaf ){
  201426. p->rc = FTS5_CORRUPT;
  201427. }else{
  201428. fts5BufferSet(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);
  201429. }
  201430. }else{
  201431. int nKeep, nByte;
  201432. iOff += fts5GetVarint32(&pLeaf->p[iOff], nKeep);
  201433. iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);
  201434. if( nKeep>buf1.n || (iOff+nByte)>pLeaf->szLeaf ){
  201435. p->rc = FTS5_CORRUPT;
  201436. }else{
  201437. buf1.n = nKeep;
  201438. fts5BufferAppendBlob(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);
  201439. }
  201440. if( p->rc==SQLITE_OK ){
  201441. res = fts5BufferCompare(&buf1, &buf2);
  201442. if( res<=0 ) p->rc = FTS5_CORRUPT;
  201443. }
  201444. }
  201445. fts5BufferSet(&p->rc, &buf2, buf1.n, buf1.p);
  201446. }
  201447. fts5BufferFree(&buf1);
  201448. fts5BufferFree(&buf2);
  201449. }
  201450. static void fts5IndexIntegrityCheckSegment(
  201451. Fts5Index *p, /* FTS5 backend object */
  201452. Fts5StructureSegment *pSeg /* Segment to check internal consistency */
  201453. ){
  201454. Fts5Config *pConfig = p->pConfig;
  201455. sqlite3_stmt *pStmt = 0;
  201456. int rc2;
  201457. int iIdxPrevLeaf = pSeg->pgnoFirst-1;
  201458. int iDlidxPrevLeaf = pSeg->pgnoLast;
  201459. if( pSeg->pgnoFirst==0 ) return;
  201460. fts5IndexPrepareStmt(p, &pStmt, sqlite3_mprintf(
  201461. "SELECT segid, term, (pgno>>1), (pgno&1) FROM %Q.'%q_idx' WHERE segid=%d",
  201462. pConfig->zDb, pConfig->zName, pSeg->iSegid
  201463. ));
  201464. /* Iterate through the b-tree hierarchy. */
  201465. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  201466. i64 iRow; /* Rowid for this leaf */
  201467. Fts5Data *pLeaf; /* Data for this leaf */
  201468. int nIdxTerm = sqlite3_column_bytes(pStmt, 1);
  201469. const char *zIdxTerm = (const char*)sqlite3_column_text(pStmt, 1);
  201470. int iIdxLeaf = sqlite3_column_int(pStmt, 2);
  201471. int bIdxDlidx = sqlite3_column_int(pStmt, 3);
  201472. /* If the leaf in question has already been trimmed from the segment,
  201473. ** ignore this b-tree entry. Otherwise, load it into memory. */
  201474. if( iIdxLeaf<pSeg->pgnoFirst ) continue;
  201475. iRow = FTS5_SEGMENT_ROWID(pSeg->iSegid, iIdxLeaf);
  201476. pLeaf = fts5LeafRead(p, iRow);
  201477. if( pLeaf==0 ) break;
  201478. /* Check that the leaf contains at least one term, and that it is equal
  201479. ** to or larger than the split-key in zIdxTerm. Also check that if there
  201480. ** is also a rowid pointer within the leaf page header, it points to a
  201481. ** location before the term. */
  201482. if( pLeaf->nn<=pLeaf->szLeaf ){
  201483. p->rc = FTS5_CORRUPT;
  201484. }else{
  201485. int iOff; /* Offset of first term on leaf */
  201486. int iRowidOff; /* Offset of first rowid on leaf */
  201487. int nTerm; /* Size of term on leaf in bytes */
  201488. int res; /* Comparison of term and split-key */
  201489. iOff = fts5LeafFirstTermOff(pLeaf);
  201490. iRowidOff = fts5LeafFirstRowidOff(pLeaf);
  201491. if( iRowidOff>=iOff || iOff>=pLeaf->szLeaf ){
  201492. p->rc = FTS5_CORRUPT;
  201493. }else{
  201494. iOff += fts5GetVarint32(&pLeaf->p[iOff], nTerm);
  201495. res = fts5Memcmp(&pLeaf->p[iOff], zIdxTerm, MIN(nTerm, nIdxTerm));
  201496. if( res==0 ) res = nTerm - nIdxTerm;
  201497. if( res<0 ) p->rc = FTS5_CORRUPT;
  201498. }
  201499. fts5IntegrityCheckPgidx(p, pLeaf);
  201500. }
  201501. fts5DataRelease(pLeaf);
  201502. if( p->rc ) break;
  201503. /* Now check that the iter.nEmpty leaves following the current leaf
  201504. ** (a) exist and (b) contain no terms. */
  201505. fts5IndexIntegrityCheckEmpty(
  201506. p, pSeg, iIdxPrevLeaf+1, iDlidxPrevLeaf+1, iIdxLeaf-1
  201507. );
  201508. if( p->rc ) break;
  201509. /* If there is a doclist-index, check that it looks right. */
  201510. if( bIdxDlidx ){
  201511. Fts5DlidxIter *pDlidx = 0; /* For iterating through doclist index */
  201512. int iPrevLeaf = iIdxLeaf;
  201513. int iSegid = pSeg->iSegid;
  201514. int iPg = 0;
  201515. i64 iKey;
  201516. for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iIdxLeaf);
  201517. fts5DlidxIterEof(p, pDlidx)==0;
  201518. fts5DlidxIterNext(p, pDlidx)
  201519. ){
  201520. /* Check any rowid-less pages that occur before the current leaf. */
  201521. for(iPg=iPrevLeaf+1; iPg<fts5DlidxIterPgno(pDlidx); iPg++){
  201522. iKey = FTS5_SEGMENT_ROWID(iSegid, iPg);
  201523. pLeaf = fts5DataRead(p, iKey);
  201524. if( pLeaf ){
  201525. if( fts5LeafFirstRowidOff(pLeaf)!=0 ) p->rc = FTS5_CORRUPT;
  201526. fts5DataRelease(pLeaf);
  201527. }
  201528. }
  201529. iPrevLeaf = fts5DlidxIterPgno(pDlidx);
  201530. /* Check that the leaf page indicated by the iterator really does
  201531. ** contain the rowid suggested by the same. */
  201532. iKey = FTS5_SEGMENT_ROWID(iSegid, iPrevLeaf);
  201533. pLeaf = fts5DataRead(p, iKey);
  201534. if( pLeaf ){
  201535. i64 iRowid;
  201536. int iRowidOff = fts5LeafFirstRowidOff(pLeaf);
  201537. ASSERT_SZLEAF_OK(pLeaf);
  201538. if( iRowidOff>=pLeaf->szLeaf ){
  201539. p->rc = FTS5_CORRUPT;
  201540. }else{
  201541. fts5GetVarint(&pLeaf->p[iRowidOff], (u64*)&iRowid);
  201542. if( iRowid!=fts5DlidxIterRowid(pDlidx) ) p->rc = FTS5_CORRUPT;
  201543. }
  201544. fts5DataRelease(pLeaf);
  201545. }
  201546. }
  201547. iDlidxPrevLeaf = iPg;
  201548. fts5DlidxIterFree(pDlidx);
  201549. fts5TestDlidxReverse(p, iSegid, iIdxLeaf);
  201550. }else{
  201551. iDlidxPrevLeaf = pSeg->pgnoLast;
  201552. /* TODO: Check there is no doclist index */
  201553. }
  201554. iIdxPrevLeaf = iIdxLeaf;
  201555. }
  201556. rc2 = sqlite3_finalize(pStmt);
  201557. if( p->rc==SQLITE_OK ) p->rc = rc2;
  201558. /* Page iter.iLeaf must now be the rightmost leaf-page in the segment */
  201559. #if 0
  201560. if( p->rc==SQLITE_OK && iter.iLeaf!=pSeg->pgnoLast ){
  201561. p->rc = FTS5_CORRUPT;
  201562. }
  201563. #endif
  201564. }
  201565. /*
  201566. ** Run internal checks to ensure that the FTS index (a) is internally
  201567. ** consistent and (b) contains entries for which the XOR of the checksums
  201568. ** as calculated by sqlite3Fts5IndexEntryCksum() is cksum.
  201569. **
  201570. ** Return SQLITE_CORRUPT if any of the internal checks fail, or if the
  201571. ** checksum does not match. Return SQLITE_OK if all checks pass without
  201572. ** error, or some other SQLite error code if another error (e.g. OOM)
  201573. ** occurs.
  201574. */
  201575. static int sqlite3Fts5IndexIntegrityCheck(Fts5Index *p, u64 cksum){
  201576. int eDetail = p->pConfig->eDetail;
  201577. u64 cksum2 = 0; /* Checksum based on contents of indexes */
  201578. Fts5Buffer poslist = {0,0,0}; /* Buffer used to hold a poslist */
  201579. Fts5Iter *pIter; /* Used to iterate through entire index */
  201580. Fts5Structure *pStruct; /* Index structure */
  201581. #ifdef SQLITE_DEBUG
  201582. /* Used by extra internal tests only run if NDEBUG is not defined */
  201583. u64 cksum3 = 0; /* Checksum based on contents of indexes */
  201584. Fts5Buffer term = {0,0,0}; /* Buffer used to hold most recent term */
  201585. #endif
  201586. const int flags = FTS5INDEX_QUERY_NOOUTPUT;
  201587. /* Load the FTS index structure */
  201588. pStruct = fts5StructureRead(p);
  201589. /* Check that the internal nodes of each segment match the leaves */
  201590. if( pStruct ){
  201591. int iLvl, iSeg;
  201592. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  201593. for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
  201594. Fts5StructureSegment *pSeg = &pStruct->aLevel[iLvl].aSeg[iSeg];
  201595. fts5IndexIntegrityCheckSegment(p, pSeg);
  201596. }
  201597. }
  201598. }
  201599. /* The cksum argument passed to this function is a checksum calculated
  201600. ** based on all expected entries in the FTS index (including prefix index
  201601. ** entries). This block checks that a checksum calculated based on the
  201602. ** actual contents of FTS index is identical.
  201603. **
  201604. ** Two versions of the same checksum are calculated. The first (stack
  201605. ** variable cksum2) based on entries extracted from the full-text index
  201606. ** while doing a linear scan of each individual index in turn.
  201607. **
  201608. ** As each term visited by the linear scans, a separate query for the
  201609. ** same term is performed. cksum3 is calculated based on the entries
  201610. ** extracted by these queries.
  201611. */
  201612. for(fts5MultiIterNew(p, pStruct, flags, 0, 0, 0, -1, 0, &pIter);
  201613. fts5MultiIterEof(p, pIter)==0;
  201614. fts5MultiIterNext(p, pIter, 0, 0)
  201615. ){
  201616. int n; /* Size of term in bytes */
  201617. i64 iPos = 0; /* Position read from poslist */
  201618. int iOff = 0; /* Offset within poslist */
  201619. i64 iRowid = fts5MultiIterRowid(pIter);
  201620. char *z = (char*)fts5MultiIterTerm(pIter, &n);
  201621. /* If this is a new term, query for it. Update cksum3 with the results. */
  201622. fts5TestTerm(p, &term, z, n, cksum2, &cksum3);
  201623. if( eDetail==FTS5_DETAIL_NONE ){
  201624. if( 0==fts5MultiIterIsEmpty(p, pIter) ){
  201625. cksum2 ^= sqlite3Fts5IndexEntryCksum(iRowid, 0, 0, -1, z, n);
  201626. }
  201627. }else{
  201628. poslist.n = 0;
  201629. fts5SegiterPoslist(p, &pIter->aSeg[pIter->aFirst[1].iFirst], 0, &poslist);
  201630. while( 0==sqlite3Fts5PoslistNext64(poslist.p, poslist.n, &iOff, &iPos) ){
  201631. int iCol = FTS5_POS2COLUMN(iPos);
  201632. int iTokOff = FTS5_POS2OFFSET(iPos);
  201633. cksum2 ^= sqlite3Fts5IndexEntryCksum(iRowid, iCol, iTokOff, -1, z, n);
  201634. }
  201635. }
  201636. }
  201637. fts5TestTerm(p, &term, 0, 0, cksum2, &cksum3);
  201638. fts5MultiIterFree(pIter);
  201639. if( p->rc==SQLITE_OK && cksum!=cksum2 ) p->rc = FTS5_CORRUPT;
  201640. fts5StructureRelease(pStruct);
  201641. #ifdef SQLITE_DEBUG
  201642. fts5BufferFree(&term);
  201643. #endif
  201644. fts5BufferFree(&poslist);
  201645. return fts5IndexReturn(p);
  201646. }
  201647. /*************************************************************************
  201648. **************************************************************************
  201649. ** Below this point is the implementation of the fts5_decode() scalar
  201650. ** function only.
  201651. */
  201652. /*
  201653. ** Decode a segment-data rowid from the %_data table. This function is
  201654. ** the opposite of macro FTS5_SEGMENT_ROWID().
  201655. */
  201656. static void fts5DecodeRowid(
  201657. i64 iRowid, /* Rowid from %_data table */
  201658. int *piSegid, /* OUT: Segment id */
  201659. int *pbDlidx, /* OUT: Dlidx flag */
  201660. int *piHeight, /* OUT: Height */
  201661. int *piPgno /* OUT: Page number */
  201662. ){
  201663. *piPgno = (int)(iRowid & (((i64)1 << FTS5_DATA_PAGE_B) - 1));
  201664. iRowid >>= FTS5_DATA_PAGE_B;
  201665. *piHeight = (int)(iRowid & (((i64)1 << FTS5_DATA_HEIGHT_B) - 1));
  201666. iRowid >>= FTS5_DATA_HEIGHT_B;
  201667. *pbDlidx = (int)(iRowid & 0x0001);
  201668. iRowid >>= FTS5_DATA_DLI_B;
  201669. *piSegid = (int)(iRowid & (((i64)1 << FTS5_DATA_ID_B) - 1));
  201670. }
  201671. static void fts5DebugRowid(int *pRc, Fts5Buffer *pBuf, i64 iKey){
  201672. int iSegid, iHeight, iPgno, bDlidx; /* Rowid compenents */
  201673. fts5DecodeRowid(iKey, &iSegid, &bDlidx, &iHeight, &iPgno);
  201674. if( iSegid==0 ){
  201675. if( iKey==FTS5_AVERAGES_ROWID ){
  201676. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{averages} ");
  201677. }else{
  201678. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{structure}");
  201679. }
  201680. }
  201681. else{
  201682. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{%ssegid=%d h=%d pgno=%d}",
  201683. bDlidx ? "dlidx " : "", iSegid, iHeight, iPgno
  201684. );
  201685. }
  201686. }
  201687. static void fts5DebugStructure(
  201688. int *pRc, /* IN/OUT: error code */
  201689. Fts5Buffer *pBuf,
  201690. Fts5Structure *p
  201691. ){
  201692. int iLvl, iSeg; /* Iterate through levels, segments */
  201693. for(iLvl=0; iLvl<p->nLevel; iLvl++){
  201694. Fts5StructureLevel *pLvl = &p->aLevel[iLvl];
  201695. sqlite3Fts5BufferAppendPrintf(pRc, pBuf,
  201696. " {lvl=%d nMerge=%d nSeg=%d", iLvl, pLvl->nMerge, pLvl->nSeg
  201697. );
  201698. for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
  201699. Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
  201700. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " {id=%d leaves=%d..%d}",
  201701. pSeg->iSegid, pSeg->pgnoFirst, pSeg->pgnoLast
  201702. );
  201703. }
  201704. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "}");
  201705. }
  201706. }
  201707. /*
  201708. ** This is part of the fts5_decode() debugging aid.
  201709. **
  201710. ** Arguments pBlob/nBlob contain a serialized Fts5Structure object. This
  201711. ** function appends a human-readable representation of the same object
  201712. ** to the buffer passed as the second argument.
  201713. */
  201714. static void fts5DecodeStructure(
  201715. int *pRc, /* IN/OUT: error code */
  201716. Fts5Buffer *pBuf,
  201717. const u8 *pBlob, int nBlob
  201718. ){
  201719. int rc; /* Return code */
  201720. Fts5Structure *p = 0; /* Decoded structure object */
  201721. rc = fts5StructureDecode(pBlob, nBlob, 0, &p);
  201722. if( rc!=SQLITE_OK ){
  201723. *pRc = rc;
  201724. return;
  201725. }
  201726. fts5DebugStructure(pRc, pBuf, p);
  201727. fts5StructureRelease(p);
  201728. }
  201729. /*
  201730. ** This is part of the fts5_decode() debugging aid.
  201731. **
  201732. ** Arguments pBlob/nBlob contain an "averages" record. This function
  201733. ** appends a human-readable representation of record to the buffer passed
  201734. ** as the second argument.
  201735. */
  201736. static void fts5DecodeAverages(
  201737. int *pRc, /* IN/OUT: error code */
  201738. Fts5Buffer *pBuf,
  201739. const u8 *pBlob, int nBlob
  201740. ){
  201741. int i = 0;
  201742. const char *zSpace = "";
  201743. while( i<nBlob ){
  201744. u64 iVal;
  201745. i += sqlite3Fts5GetVarint(&pBlob[i], &iVal);
  201746. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "%s%d", zSpace, (int)iVal);
  201747. zSpace = " ";
  201748. }
  201749. }
  201750. /*
  201751. ** Buffer (a/n) is assumed to contain a list of serialized varints. Read
  201752. ** each varint and append its string representation to buffer pBuf. Return
  201753. ** after either the input buffer is exhausted or a 0 value is read.
  201754. **
  201755. ** The return value is the number of bytes read from the input buffer.
  201756. */
  201757. static int fts5DecodePoslist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
  201758. int iOff = 0;
  201759. while( iOff<n ){
  201760. int iVal;
  201761. iOff += fts5GetVarint32(&a[iOff], iVal);
  201762. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %d", iVal);
  201763. }
  201764. return iOff;
  201765. }
  201766. /*
  201767. ** The start of buffer (a/n) contains the start of a doclist. The doclist
  201768. ** may or may not finish within the buffer. This function appends a text
  201769. ** representation of the part of the doclist that is present to buffer
  201770. ** pBuf.
  201771. **
  201772. ** The return value is the number of bytes read from the input buffer.
  201773. */
  201774. static int fts5DecodeDoclist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
  201775. i64 iDocid = 0;
  201776. int iOff = 0;
  201777. if( n>0 ){
  201778. iOff = sqlite3Fts5GetVarint(a, (u64*)&iDocid);
  201779. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid);
  201780. }
  201781. while( iOff<n ){
  201782. int nPos;
  201783. int bDel;
  201784. iOff += fts5GetPoslistSize(&a[iOff], &nPos, &bDel);
  201785. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " nPos=%d%s", nPos, bDel?"*":"");
  201786. iOff += fts5DecodePoslist(pRc, pBuf, &a[iOff], MIN(n-iOff, nPos));
  201787. if( iOff<n ){
  201788. i64 iDelta;
  201789. iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&iDelta);
  201790. iDocid += iDelta;
  201791. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid);
  201792. }
  201793. }
  201794. return iOff;
  201795. }
  201796. /*
  201797. ** This function is part of the fts5_decode() debugging function. It is
  201798. ** only ever used with detail=none tables.
  201799. **
  201800. ** Buffer (pData/nData) contains a doclist in the format used by detail=none
  201801. ** tables. This function appends a human-readable version of that list to
  201802. ** buffer pBuf.
  201803. **
  201804. ** If *pRc is other than SQLITE_OK when this function is called, it is a
  201805. ** no-op. If an OOM or other error occurs within this function, *pRc is
  201806. ** set to an SQLite error code before returning. The final state of buffer
  201807. ** pBuf is undefined in this case.
  201808. */
  201809. static void fts5DecodeRowidList(
  201810. int *pRc, /* IN/OUT: Error code */
  201811. Fts5Buffer *pBuf, /* Buffer to append text to */
  201812. const u8 *pData, int nData /* Data to decode list-of-rowids from */
  201813. ){
  201814. int i = 0;
  201815. i64 iRowid = 0;
  201816. while( i<nData ){
  201817. const char *zApp = "";
  201818. u64 iVal;
  201819. i += sqlite3Fts5GetVarint(&pData[i], &iVal);
  201820. iRowid += iVal;
  201821. if( i<nData && pData[i]==0x00 ){
  201822. i++;
  201823. if( i<nData && pData[i]==0x00 ){
  201824. i++;
  201825. zApp = "+";
  201826. }else{
  201827. zApp = "*";
  201828. }
  201829. }
  201830. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %lld%s", iRowid, zApp);
  201831. }
  201832. }
  201833. /*
  201834. ** The implementation of user-defined scalar function fts5_decode().
  201835. */
  201836. static void fts5DecodeFunction(
  201837. sqlite3_context *pCtx, /* Function call context */
  201838. int nArg, /* Number of args (always 2) */
  201839. sqlite3_value **apVal /* Function arguments */
  201840. ){
  201841. i64 iRowid; /* Rowid for record being decoded */
  201842. int iSegid,iHeight,iPgno,bDlidx;/* Rowid components */
  201843. const u8 *aBlob; int n; /* Record to decode */
  201844. u8 *a = 0;
  201845. Fts5Buffer s; /* Build up text to return here */
  201846. int rc = SQLITE_OK; /* Return code */
  201847. sqlite3_int64 nSpace = 0;
  201848. int eDetailNone = (sqlite3_user_data(pCtx)!=0);
  201849. assert( nArg==2 );
  201850. UNUSED_PARAM(nArg);
  201851. memset(&s, 0, sizeof(Fts5Buffer));
  201852. iRowid = sqlite3_value_int64(apVal[0]);
  201853. /* Make a copy of the second argument (a blob) in aBlob[]. The aBlob[]
  201854. ** copy is followed by FTS5_DATA_ZERO_PADDING 0x00 bytes, which prevents
  201855. ** buffer overreads even if the record is corrupt. */
  201856. n = sqlite3_value_bytes(apVal[1]);
  201857. aBlob = sqlite3_value_blob(apVal[1]);
  201858. nSpace = n + FTS5_DATA_ZERO_PADDING;
  201859. a = (u8*)sqlite3Fts5MallocZero(&rc, nSpace);
  201860. if( a==0 ) goto decode_out;
  201861. if( n>0 ) memcpy(a, aBlob, n);
  201862. fts5DecodeRowid(iRowid, &iSegid, &bDlidx, &iHeight, &iPgno);
  201863. fts5DebugRowid(&rc, &s, iRowid);
  201864. if( bDlidx ){
  201865. Fts5Data dlidx;
  201866. Fts5DlidxLvl lvl;
  201867. dlidx.p = a;
  201868. dlidx.nn = n;
  201869. memset(&lvl, 0, sizeof(Fts5DlidxLvl));
  201870. lvl.pData = &dlidx;
  201871. lvl.iLeafPgno = iPgno;
  201872. for(fts5DlidxLvlNext(&lvl); lvl.bEof==0; fts5DlidxLvlNext(&lvl)){
  201873. sqlite3Fts5BufferAppendPrintf(&rc, &s,
  201874. " %d(%lld)", lvl.iLeafPgno, lvl.iRowid
  201875. );
  201876. }
  201877. }else if( iSegid==0 ){
  201878. if( iRowid==FTS5_AVERAGES_ROWID ){
  201879. fts5DecodeAverages(&rc, &s, a, n);
  201880. }else{
  201881. fts5DecodeStructure(&rc, &s, a, n);
  201882. }
  201883. }else if( eDetailNone ){
  201884. Fts5Buffer term; /* Current term read from page */
  201885. int szLeaf;
  201886. int iPgidxOff = szLeaf = fts5GetU16(&a[2]);
  201887. int iTermOff;
  201888. int nKeep = 0;
  201889. int iOff;
  201890. memset(&term, 0, sizeof(Fts5Buffer));
  201891. /* Decode any entries that occur before the first term. */
  201892. if( szLeaf<n ){
  201893. iPgidxOff += fts5GetVarint32(&a[iPgidxOff], iTermOff);
  201894. }else{
  201895. iTermOff = szLeaf;
  201896. }
  201897. fts5DecodeRowidList(&rc, &s, &a[4], iTermOff-4);
  201898. iOff = iTermOff;
  201899. while( iOff<szLeaf ){
  201900. int nAppend;
  201901. /* Read the term data for the next term*/
  201902. iOff += fts5GetVarint32(&a[iOff], nAppend);
  201903. term.n = nKeep;
  201904. fts5BufferAppendBlob(&rc, &term, nAppend, &a[iOff]);
  201905. sqlite3Fts5BufferAppendPrintf(
  201906. &rc, &s, " term=%.*s", term.n, (const char*)term.p
  201907. );
  201908. iOff += nAppend;
  201909. /* Figure out where the doclist for this term ends */
  201910. if( iPgidxOff<n ){
  201911. int nIncr;
  201912. iPgidxOff += fts5GetVarint32(&a[iPgidxOff], nIncr);
  201913. iTermOff += nIncr;
  201914. }else{
  201915. iTermOff = szLeaf;
  201916. }
  201917. fts5DecodeRowidList(&rc, &s, &a[iOff], iTermOff-iOff);
  201918. iOff = iTermOff;
  201919. if( iOff<szLeaf ){
  201920. iOff += fts5GetVarint32(&a[iOff], nKeep);
  201921. }
  201922. }
  201923. fts5BufferFree(&term);
  201924. }else{
  201925. Fts5Buffer term; /* Current term read from page */
  201926. int szLeaf; /* Offset of pgidx in a[] */
  201927. int iPgidxOff;
  201928. int iPgidxPrev = 0; /* Previous value read from pgidx */
  201929. int iTermOff = 0;
  201930. int iRowidOff = 0;
  201931. int iOff;
  201932. int nDoclist;
  201933. memset(&term, 0, sizeof(Fts5Buffer));
  201934. if( n<4 ){
  201935. sqlite3Fts5BufferSet(&rc, &s, 7, (const u8*)"corrupt");
  201936. goto decode_out;
  201937. }else{
  201938. iRowidOff = fts5GetU16(&a[0]);
  201939. iPgidxOff = szLeaf = fts5GetU16(&a[2]);
  201940. if( iPgidxOff<n ){
  201941. fts5GetVarint32(&a[iPgidxOff], iTermOff);
  201942. }else if( iPgidxOff>n ){
  201943. rc = FTS5_CORRUPT;
  201944. goto decode_out;
  201945. }
  201946. }
  201947. /* Decode the position list tail at the start of the page */
  201948. if( iRowidOff!=0 ){
  201949. iOff = iRowidOff;
  201950. }else if( iTermOff!=0 ){
  201951. iOff = iTermOff;
  201952. }else{
  201953. iOff = szLeaf;
  201954. }
  201955. if( iOff>n ){
  201956. rc = FTS5_CORRUPT;
  201957. goto decode_out;
  201958. }
  201959. fts5DecodePoslist(&rc, &s, &a[4], iOff-4);
  201960. /* Decode any more doclist data that appears on the page before the
  201961. ** first term. */
  201962. nDoclist = (iTermOff ? iTermOff : szLeaf) - iOff;
  201963. if( nDoclist+iOff>n ){
  201964. rc = FTS5_CORRUPT;
  201965. goto decode_out;
  201966. }
  201967. fts5DecodeDoclist(&rc, &s, &a[iOff], nDoclist);
  201968. while( iPgidxOff<n && rc==SQLITE_OK ){
  201969. int bFirst = (iPgidxOff==szLeaf); /* True for first term on page */
  201970. int nByte; /* Bytes of data */
  201971. int iEnd;
  201972. iPgidxOff += fts5GetVarint32(&a[iPgidxOff], nByte);
  201973. iPgidxPrev += nByte;
  201974. iOff = iPgidxPrev;
  201975. if( iPgidxOff<n ){
  201976. fts5GetVarint32(&a[iPgidxOff], nByte);
  201977. iEnd = iPgidxPrev + nByte;
  201978. }else{
  201979. iEnd = szLeaf;
  201980. }
  201981. if( iEnd>szLeaf ){
  201982. rc = FTS5_CORRUPT;
  201983. break;
  201984. }
  201985. if( bFirst==0 ){
  201986. iOff += fts5GetVarint32(&a[iOff], nByte);
  201987. if( nByte>term.n ){
  201988. rc = FTS5_CORRUPT;
  201989. break;
  201990. }
  201991. term.n = nByte;
  201992. }
  201993. iOff += fts5GetVarint32(&a[iOff], nByte);
  201994. if( iOff+nByte>n ){
  201995. rc = FTS5_CORRUPT;
  201996. break;
  201997. }
  201998. fts5BufferAppendBlob(&rc, &term, nByte, &a[iOff]);
  201999. iOff += nByte;
  202000. sqlite3Fts5BufferAppendPrintf(
  202001. &rc, &s, " term=%.*s", term.n, (const char*)term.p
  202002. );
  202003. iOff += fts5DecodeDoclist(&rc, &s, &a[iOff], iEnd-iOff);
  202004. }
  202005. fts5BufferFree(&term);
  202006. }
  202007. decode_out:
  202008. sqlite3_free(a);
  202009. if( rc==SQLITE_OK ){
  202010. sqlite3_result_text(pCtx, (const char*)s.p, s.n, SQLITE_TRANSIENT);
  202011. }else{
  202012. sqlite3_result_error_code(pCtx, rc);
  202013. }
  202014. fts5BufferFree(&s);
  202015. }
  202016. /*
  202017. ** The implementation of user-defined scalar function fts5_rowid().
  202018. */
  202019. static void fts5RowidFunction(
  202020. sqlite3_context *pCtx, /* Function call context */
  202021. int nArg, /* Number of args (always 2) */
  202022. sqlite3_value **apVal /* Function arguments */
  202023. ){
  202024. const char *zArg;
  202025. if( nArg==0 ){
  202026. sqlite3_result_error(pCtx, "should be: fts5_rowid(subject, ....)", -1);
  202027. }else{
  202028. zArg = (const char*)sqlite3_value_text(apVal[0]);
  202029. if( 0==sqlite3_stricmp(zArg, "segment") ){
  202030. i64 iRowid;
  202031. int segid, pgno;
  202032. if( nArg!=3 ){
  202033. sqlite3_result_error(pCtx,
  202034. "should be: fts5_rowid('segment', segid, pgno))", -1
  202035. );
  202036. }else{
  202037. segid = sqlite3_value_int(apVal[1]);
  202038. pgno = sqlite3_value_int(apVal[2]);
  202039. iRowid = FTS5_SEGMENT_ROWID(segid, pgno);
  202040. sqlite3_result_int64(pCtx, iRowid);
  202041. }
  202042. }else{
  202043. sqlite3_result_error(pCtx,
  202044. "first arg to fts5_rowid() must be 'segment'" , -1
  202045. );
  202046. }
  202047. }
  202048. }
  202049. /*
  202050. ** This is called as part of registering the FTS5 module with database
  202051. ** connection db. It registers several user-defined scalar functions useful
  202052. ** with FTS5.
  202053. **
  202054. ** If successful, SQLITE_OK is returned. If an error occurs, some other
  202055. ** SQLite error code is returned instead.
  202056. */
  202057. static int sqlite3Fts5IndexInit(sqlite3 *db){
  202058. int rc = sqlite3_create_function(
  202059. db, "fts5_decode", 2, SQLITE_UTF8, 0, fts5DecodeFunction, 0, 0
  202060. );
  202061. if( rc==SQLITE_OK ){
  202062. rc = sqlite3_create_function(
  202063. db, "fts5_decode_none", 2,
  202064. SQLITE_UTF8, (void*)db, fts5DecodeFunction, 0, 0
  202065. );
  202066. }
  202067. if( rc==SQLITE_OK ){
  202068. rc = sqlite3_create_function(
  202069. db, "fts5_rowid", -1, SQLITE_UTF8, 0, fts5RowidFunction, 0, 0
  202070. );
  202071. }
  202072. return rc;
  202073. }
  202074. static int sqlite3Fts5IndexReset(Fts5Index *p){
  202075. assert( p->pStruct==0 || p->iStructVersion!=0 );
  202076. if( fts5IndexDataVersion(p)!=p->iStructVersion ){
  202077. fts5StructureInvalidate(p);
  202078. }
  202079. return fts5IndexReturn(p);
  202080. }
  202081. /*
  202082. ** 2014 Jun 09
  202083. **
  202084. ** The author disclaims copyright to this source code. In place of
  202085. ** a legal notice, here is a blessing:
  202086. **
  202087. ** May you do good and not evil.
  202088. ** May you find forgiveness for yourself and forgive others.
  202089. ** May you share freely, never taking more than you give.
  202090. **
  202091. ******************************************************************************
  202092. **
  202093. ** This is an SQLite module implementing full-text search.
  202094. */
  202095. /* #include "fts5Int.h" */
  202096. /*
  202097. ** This variable is set to false when running tests for which the on disk
  202098. ** structures should not be corrupt. Otherwise, true. If it is false, extra
  202099. ** assert() conditions in the fts5 code are activated - conditions that are
  202100. ** only true if it is guaranteed that the fts5 database is not corrupt.
  202101. */
  202102. SQLITE_API int sqlite3_fts5_may_be_corrupt = 1;
  202103. typedef struct Fts5Auxdata Fts5Auxdata;
  202104. typedef struct Fts5Auxiliary Fts5Auxiliary;
  202105. typedef struct Fts5Cursor Fts5Cursor;
  202106. typedef struct Fts5FullTable Fts5FullTable;
  202107. typedef struct Fts5Sorter Fts5Sorter;
  202108. typedef struct Fts5TokenizerModule Fts5TokenizerModule;
  202109. /*
  202110. ** NOTES ON TRANSACTIONS:
  202111. **
  202112. ** SQLite invokes the following virtual table methods as transactions are
  202113. ** opened and closed by the user:
  202114. **
  202115. ** xBegin(): Start of a new transaction.
  202116. ** xSync(): Initial part of two-phase commit.
  202117. ** xCommit(): Final part of two-phase commit.
  202118. ** xRollback(): Rollback the transaction.
  202119. **
  202120. ** Anything that is required as part of a commit that may fail is performed
  202121. ** in the xSync() callback. Current versions of SQLite ignore any errors
  202122. ** returned by xCommit().
  202123. **
  202124. ** And as sub-transactions are opened/closed:
  202125. **
  202126. ** xSavepoint(int S): Open savepoint S.
  202127. ** xRelease(int S): Commit and close savepoint S.
  202128. ** xRollbackTo(int S): Rollback to start of savepoint S.
  202129. **
  202130. ** During a write-transaction the fts5_index.c module may cache some data
  202131. ** in-memory. It is flushed to disk whenever xSync(), xRelease() or
  202132. ** xSavepoint() is called. And discarded whenever xRollback() or xRollbackTo()
  202133. ** is called.
  202134. **
  202135. ** Additionally, if SQLITE_DEBUG is defined, an instance of the following
  202136. ** structure is used to record the current transaction state. This information
  202137. ** is not required, but it is used in the assert() statements executed by
  202138. ** function fts5CheckTransactionState() (see below).
  202139. */
  202140. struct Fts5TransactionState {
  202141. int eState; /* 0==closed, 1==open, 2==synced */
  202142. int iSavepoint; /* Number of open savepoints (0 -> none) */
  202143. };
  202144. /*
  202145. ** A single object of this type is allocated when the FTS5 module is
  202146. ** registered with a database handle. It is used to store pointers to
  202147. ** all registered FTS5 extensions - tokenizers and auxiliary functions.
  202148. */
  202149. struct Fts5Global {
  202150. fts5_api api; /* User visible part of object (see fts5.h) */
  202151. sqlite3 *db; /* Associated database connection */
  202152. i64 iNextId; /* Used to allocate unique cursor ids */
  202153. Fts5Auxiliary *pAux; /* First in list of all aux. functions */
  202154. Fts5TokenizerModule *pTok; /* First in list of all tokenizer modules */
  202155. Fts5TokenizerModule *pDfltTok; /* Default tokenizer module */
  202156. Fts5Cursor *pCsr; /* First in list of all open cursors */
  202157. };
  202158. /*
  202159. ** Each auxiliary function registered with the FTS5 module is represented
  202160. ** by an object of the following type. All such objects are stored as part
  202161. ** of the Fts5Global.pAux list.
  202162. */
  202163. struct Fts5Auxiliary {
  202164. Fts5Global *pGlobal; /* Global context for this function */
  202165. char *zFunc; /* Function name (nul-terminated) */
  202166. void *pUserData; /* User-data pointer */
  202167. fts5_extension_function xFunc; /* Callback function */
  202168. void (*xDestroy)(void*); /* Destructor function */
  202169. Fts5Auxiliary *pNext; /* Next registered auxiliary function */
  202170. };
  202171. /*
  202172. ** Each tokenizer module registered with the FTS5 module is represented
  202173. ** by an object of the following type. All such objects are stored as part
  202174. ** of the Fts5Global.pTok list.
  202175. */
  202176. struct Fts5TokenizerModule {
  202177. char *zName; /* Name of tokenizer */
  202178. void *pUserData; /* User pointer passed to xCreate() */
  202179. fts5_tokenizer x; /* Tokenizer functions */
  202180. void (*xDestroy)(void*); /* Destructor function */
  202181. Fts5TokenizerModule *pNext; /* Next registered tokenizer module */
  202182. };
  202183. struct Fts5FullTable {
  202184. Fts5Table p; /* Public class members from fts5Int.h */
  202185. Fts5Storage *pStorage; /* Document store */
  202186. Fts5Global *pGlobal; /* Global (connection wide) data */
  202187. Fts5Cursor *pSortCsr; /* Sort data from this cursor */
  202188. #ifdef SQLITE_DEBUG
  202189. struct Fts5TransactionState ts;
  202190. #endif
  202191. };
  202192. struct Fts5MatchPhrase {
  202193. Fts5Buffer *pPoslist; /* Pointer to current poslist */
  202194. int nTerm; /* Size of phrase in terms */
  202195. };
  202196. /*
  202197. ** pStmt:
  202198. ** SELECT rowid, <fts> FROM <fts> ORDER BY +rank;
  202199. **
  202200. ** aIdx[]:
  202201. ** There is one entry in the aIdx[] array for each phrase in the query,
  202202. ** the value of which is the offset within aPoslist[] following the last
  202203. ** byte of the position list for the corresponding phrase.
  202204. */
  202205. struct Fts5Sorter {
  202206. sqlite3_stmt *pStmt;
  202207. i64 iRowid; /* Current rowid */
  202208. const u8 *aPoslist; /* Position lists for current row */
  202209. int nIdx; /* Number of entries in aIdx[] */
  202210. int aIdx[1]; /* Offsets into aPoslist for current row */
  202211. };
  202212. /*
  202213. ** Virtual-table cursor object.
  202214. **
  202215. ** iSpecial:
  202216. ** If this is a 'special' query (refer to function fts5SpecialMatch()),
  202217. ** then this variable contains the result of the query.
  202218. **
  202219. ** iFirstRowid, iLastRowid:
  202220. ** These variables are only used for FTS5_PLAN_MATCH cursors. Assuming the
  202221. ** cursor iterates in ascending order of rowids, iFirstRowid is the lower
  202222. ** limit of rowids to return, and iLastRowid the upper. In other words, the
  202223. ** WHERE clause in the user's query might have been:
  202224. **
  202225. ** <tbl> MATCH <expr> AND rowid BETWEEN $iFirstRowid AND $iLastRowid
  202226. **
  202227. ** If the cursor iterates in descending order of rowid, iFirstRowid
  202228. ** is the upper limit (i.e. the "first" rowid visited) and iLastRowid
  202229. ** the lower.
  202230. */
  202231. struct Fts5Cursor {
  202232. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  202233. Fts5Cursor *pNext; /* Next cursor in Fts5Cursor.pCsr list */
  202234. int *aColumnSize; /* Values for xColumnSize() */
  202235. i64 iCsrId; /* Cursor id */
  202236. /* Zero from this point onwards on cursor reset */
  202237. int ePlan; /* FTS5_PLAN_XXX value */
  202238. int bDesc; /* True for "ORDER BY rowid DESC" queries */
  202239. i64 iFirstRowid; /* Return no rowids earlier than this */
  202240. i64 iLastRowid; /* Return no rowids later than this */
  202241. sqlite3_stmt *pStmt; /* Statement used to read %_content */
  202242. Fts5Expr *pExpr; /* Expression for MATCH queries */
  202243. Fts5Sorter *pSorter; /* Sorter for "ORDER BY rank" queries */
  202244. int csrflags; /* Mask of cursor flags (see below) */
  202245. i64 iSpecial; /* Result of special query */
  202246. /* "rank" function. Populated on demand from vtab.xColumn(). */
  202247. char *zRank; /* Custom rank function */
  202248. char *zRankArgs; /* Custom rank function args */
  202249. Fts5Auxiliary *pRank; /* Rank callback (or NULL) */
  202250. int nRankArg; /* Number of trailing arguments for rank() */
  202251. sqlite3_value **apRankArg; /* Array of trailing arguments */
  202252. sqlite3_stmt *pRankArgStmt; /* Origin of objects in apRankArg[] */
  202253. /* Auxiliary data storage */
  202254. Fts5Auxiliary *pAux; /* Currently executing extension function */
  202255. Fts5Auxdata *pAuxdata; /* First in linked list of saved aux-data */
  202256. /* Cache used by auxiliary functions xInst() and xInstCount() */
  202257. Fts5PoslistReader *aInstIter; /* One for each phrase */
  202258. int nInstAlloc; /* Size of aInst[] array (entries / 3) */
  202259. int nInstCount; /* Number of phrase instances */
  202260. int *aInst; /* 3 integers per phrase instance */
  202261. };
  202262. /*
  202263. ** Bits that make up the "idxNum" parameter passed indirectly by
  202264. ** xBestIndex() to xFilter().
  202265. */
  202266. #define FTS5_BI_MATCH 0x0001 /* <tbl> MATCH ? */
  202267. #define FTS5_BI_RANK 0x0002 /* rank MATCH ? */
  202268. #define FTS5_BI_ROWID_EQ 0x0004 /* rowid == ? */
  202269. #define FTS5_BI_ROWID_LE 0x0008 /* rowid <= ? */
  202270. #define FTS5_BI_ROWID_GE 0x0010 /* rowid >= ? */
  202271. #define FTS5_BI_ORDER_RANK 0x0020
  202272. #define FTS5_BI_ORDER_ROWID 0x0040
  202273. #define FTS5_BI_ORDER_DESC 0x0080
  202274. /*
  202275. ** Values for Fts5Cursor.csrflags
  202276. */
  202277. #define FTS5CSR_EOF 0x01
  202278. #define FTS5CSR_REQUIRE_CONTENT 0x02
  202279. #define FTS5CSR_REQUIRE_DOCSIZE 0x04
  202280. #define FTS5CSR_REQUIRE_INST 0x08
  202281. #define FTS5CSR_FREE_ZRANK 0x10
  202282. #define FTS5CSR_REQUIRE_RESEEK 0x20
  202283. #define FTS5CSR_REQUIRE_POSLIST 0x40
  202284. #define BitFlagAllTest(x,y) (((x) & (y))==(y))
  202285. #define BitFlagTest(x,y) (((x) & (y))!=0)
  202286. /*
  202287. ** Macros to Set(), Clear() and Test() cursor flags.
  202288. */
  202289. #define CsrFlagSet(pCsr, flag) ((pCsr)->csrflags |= (flag))
  202290. #define CsrFlagClear(pCsr, flag) ((pCsr)->csrflags &= ~(flag))
  202291. #define CsrFlagTest(pCsr, flag) ((pCsr)->csrflags & (flag))
  202292. struct Fts5Auxdata {
  202293. Fts5Auxiliary *pAux; /* Extension to which this belongs */
  202294. void *pPtr; /* Pointer value */
  202295. void(*xDelete)(void*); /* Destructor */
  202296. Fts5Auxdata *pNext; /* Next object in linked list */
  202297. };
  202298. #ifdef SQLITE_DEBUG
  202299. #define FTS5_BEGIN 1
  202300. #define FTS5_SYNC 2
  202301. #define FTS5_COMMIT 3
  202302. #define FTS5_ROLLBACK 4
  202303. #define FTS5_SAVEPOINT 5
  202304. #define FTS5_RELEASE 6
  202305. #define FTS5_ROLLBACKTO 7
  202306. static void fts5CheckTransactionState(Fts5FullTable *p, int op, int iSavepoint){
  202307. switch( op ){
  202308. case FTS5_BEGIN:
  202309. assert( p->ts.eState==0 );
  202310. p->ts.eState = 1;
  202311. p->ts.iSavepoint = -1;
  202312. break;
  202313. case FTS5_SYNC:
  202314. assert( p->ts.eState==1 );
  202315. p->ts.eState = 2;
  202316. break;
  202317. case FTS5_COMMIT:
  202318. assert( p->ts.eState==2 );
  202319. p->ts.eState = 0;
  202320. break;
  202321. case FTS5_ROLLBACK:
  202322. assert( p->ts.eState==1 || p->ts.eState==2 || p->ts.eState==0 );
  202323. p->ts.eState = 0;
  202324. break;
  202325. case FTS5_SAVEPOINT:
  202326. assert( p->ts.eState==1 );
  202327. assert( iSavepoint>=0 );
  202328. assert( iSavepoint>=p->ts.iSavepoint );
  202329. p->ts.iSavepoint = iSavepoint;
  202330. break;
  202331. case FTS5_RELEASE:
  202332. assert( p->ts.eState==1 );
  202333. assert( iSavepoint>=0 );
  202334. assert( iSavepoint<=p->ts.iSavepoint );
  202335. p->ts.iSavepoint = iSavepoint-1;
  202336. break;
  202337. case FTS5_ROLLBACKTO:
  202338. assert( p->ts.eState==1 );
  202339. assert( iSavepoint>=-1 );
  202340. assert( iSavepoint<=p->ts.iSavepoint );
  202341. p->ts.iSavepoint = iSavepoint;
  202342. break;
  202343. }
  202344. }
  202345. #else
  202346. # define fts5CheckTransactionState(x,y,z)
  202347. #endif
  202348. /*
  202349. ** Return true if pTab is a contentless table.
  202350. */
  202351. static int fts5IsContentless(Fts5FullTable *pTab){
  202352. return pTab->p.pConfig->eContent==FTS5_CONTENT_NONE;
  202353. }
  202354. /*
  202355. ** Delete a virtual table handle allocated by fts5InitVtab().
  202356. */
  202357. static void fts5FreeVtab(Fts5FullTable *pTab){
  202358. if( pTab ){
  202359. sqlite3Fts5IndexClose(pTab->p.pIndex);
  202360. sqlite3Fts5StorageClose(pTab->pStorage);
  202361. sqlite3Fts5ConfigFree(pTab->p.pConfig);
  202362. sqlite3_free(pTab);
  202363. }
  202364. }
  202365. /*
  202366. ** The xDisconnect() virtual table method.
  202367. */
  202368. static int fts5DisconnectMethod(sqlite3_vtab *pVtab){
  202369. fts5FreeVtab((Fts5FullTable*)pVtab);
  202370. return SQLITE_OK;
  202371. }
  202372. /*
  202373. ** The xDestroy() virtual table method.
  202374. */
  202375. static int fts5DestroyMethod(sqlite3_vtab *pVtab){
  202376. Fts5Table *pTab = (Fts5Table*)pVtab;
  202377. int rc = sqlite3Fts5DropAll(pTab->pConfig);
  202378. if( rc==SQLITE_OK ){
  202379. fts5FreeVtab((Fts5FullTable*)pVtab);
  202380. }
  202381. return rc;
  202382. }
  202383. /*
  202384. ** This function is the implementation of both the xConnect and xCreate
  202385. ** methods of the FTS3 virtual table.
  202386. **
  202387. ** The argv[] array contains the following:
  202388. **
  202389. ** argv[0] -> module name ("fts5")
  202390. ** argv[1] -> database name
  202391. ** argv[2] -> table name
  202392. ** argv[...] -> "column name" and other module argument fields.
  202393. */
  202394. static int fts5InitVtab(
  202395. int bCreate, /* True for xCreate, false for xConnect */
  202396. sqlite3 *db, /* The SQLite database connection */
  202397. void *pAux, /* Hash table containing tokenizers */
  202398. int argc, /* Number of elements in argv array */
  202399. const char * const *argv, /* xCreate/xConnect argument array */
  202400. sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
  202401. char **pzErr /* Write any error message here */
  202402. ){
  202403. Fts5Global *pGlobal = (Fts5Global*)pAux;
  202404. const char **azConfig = (const char**)argv;
  202405. int rc = SQLITE_OK; /* Return code */
  202406. Fts5Config *pConfig = 0; /* Results of parsing argc/argv */
  202407. Fts5FullTable *pTab = 0; /* New virtual table object */
  202408. /* Allocate the new vtab object and parse the configuration */
  202409. pTab = (Fts5FullTable*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5FullTable));
  202410. if( rc==SQLITE_OK ){
  202411. rc = sqlite3Fts5ConfigParse(pGlobal, db, argc, azConfig, &pConfig, pzErr);
  202412. assert( (rc==SQLITE_OK && *pzErr==0) || pConfig==0 );
  202413. }
  202414. if( rc==SQLITE_OK ){
  202415. pTab->p.pConfig = pConfig;
  202416. pTab->pGlobal = pGlobal;
  202417. }
  202418. /* Open the index sub-system */
  202419. if( rc==SQLITE_OK ){
  202420. rc = sqlite3Fts5IndexOpen(pConfig, bCreate, &pTab->p.pIndex, pzErr);
  202421. }
  202422. /* Open the storage sub-system */
  202423. if( rc==SQLITE_OK ){
  202424. rc = sqlite3Fts5StorageOpen(
  202425. pConfig, pTab->p.pIndex, bCreate, &pTab->pStorage, pzErr
  202426. );
  202427. }
  202428. /* Call sqlite3_declare_vtab() */
  202429. if( rc==SQLITE_OK ){
  202430. rc = sqlite3Fts5ConfigDeclareVtab(pConfig);
  202431. }
  202432. /* Load the initial configuration */
  202433. if( rc==SQLITE_OK ){
  202434. assert( pConfig->pzErrmsg==0 );
  202435. pConfig->pzErrmsg = pzErr;
  202436. rc = sqlite3Fts5IndexLoadConfig(pTab->p.pIndex);
  202437. sqlite3Fts5IndexRollback(pTab->p.pIndex);
  202438. pConfig->pzErrmsg = 0;
  202439. }
  202440. if( rc!=SQLITE_OK ){
  202441. fts5FreeVtab(pTab);
  202442. pTab = 0;
  202443. }else if( bCreate ){
  202444. fts5CheckTransactionState(pTab, FTS5_BEGIN, 0);
  202445. }
  202446. *ppVTab = (sqlite3_vtab*)pTab;
  202447. return rc;
  202448. }
  202449. /*
  202450. ** The xConnect() and xCreate() methods for the virtual table. All the
  202451. ** work is done in function fts5InitVtab().
  202452. */
  202453. static int fts5ConnectMethod(
  202454. sqlite3 *db, /* Database connection */
  202455. void *pAux, /* Pointer to tokenizer hash table */
  202456. int argc, /* Number of elements in argv array */
  202457. const char * const *argv, /* xCreate/xConnect argument array */
  202458. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  202459. char **pzErr /* OUT: sqlite3_malloc'd error message */
  202460. ){
  202461. return fts5InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
  202462. }
  202463. static int fts5CreateMethod(
  202464. sqlite3 *db, /* Database connection */
  202465. void *pAux, /* Pointer to tokenizer hash table */
  202466. int argc, /* Number of elements in argv array */
  202467. const char * const *argv, /* xCreate/xConnect argument array */
  202468. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  202469. char **pzErr /* OUT: sqlite3_malloc'd error message */
  202470. ){
  202471. return fts5InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
  202472. }
  202473. /*
  202474. ** The different query plans.
  202475. */
  202476. #define FTS5_PLAN_MATCH 1 /* (<tbl> MATCH ?) */
  202477. #define FTS5_PLAN_SOURCE 2 /* A source cursor for SORTED_MATCH */
  202478. #define FTS5_PLAN_SPECIAL 3 /* An internal query */
  202479. #define FTS5_PLAN_SORTED_MATCH 4 /* (<tbl> MATCH ? ORDER BY rank) */
  202480. #define FTS5_PLAN_SCAN 5 /* No usable constraint */
  202481. #define FTS5_PLAN_ROWID 6 /* (rowid = ?) */
  202482. /*
  202483. ** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this
  202484. ** extension is currently being used by a version of SQLite too old to
  202485. ** support index-info flags. In that case this function is a no-op.
  202486. */
  202487. static void fts5SetUniqueFlag(sqlite3_index_info *pIdxInfo){
  202488. #if SQLITE_VERSION_NUMBER>=3008012
  202489. #ifndef SQLITE_CORE
  202490. if( sqlite3_libversion_number()>=3008012 )
  202491. #endif
  202492. {
  202493. pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE;
  202494. }
  202495. #endif
  202496. }
  202497. /*
  202498. ** Implementation of the xBestIndex method for FTS5 tables. Within the
  202499. ** WHERE constraint, it searches for the following:
  202500. **
  202501. ** 1. A MATCH constraint against the special column.
  202502. ** 2. A MATCH constraint against the "rank" column.
  202503. ** 3. An == constraint against the rowid column.
  202504. ** 4. A < or <= constraint against the rowid column.
  202505. ** 5. A > or >= constraint against the rowid column.
  202506. **
  202507. ** Within the ORDER BY, either:
  202508. **
  202509. ** 5. ORDER BY rank [ASC|DESC]
  202510. ** 6. ORDER BY rowid [ASC|DESC]
  202511. **
  202512. ** Costs are assigned as follows:
  202513. **
  202514. ** a) If an unusable MATCH operator is present in the WHERE clause, the
  202515. ** cost is unconditionally set to 1e50 (a really big number).
  202516. **
  202517. ** a) If a MATCH operator is present, the cost depends on the other
  202518. ** constraints also present. As follows:
  202519. **
  202520. ** * No other constraints: cost=1000.0
  202521. ** * One rowid range constraint: cost=750.0
  202522. ** * Both rowid range constraints: cost=500.0
  202523. ** * An == rowid constraint: cost=100.0
  202524. **
  202525. ** b) Otherwise, if there is no MATCH:
  202526. **
  202527. ** * No other constraints: cost=1000000.0
  202528. ** * One rowid range constraint: cost=750000.0
  202529. ** * Both rowid range constraints: cost=250000.0
  202530. ** * An == rowid constraint: cost=10.0
  202531. **
  202532. ** Costs are not modified by the ORDER BY clause.
  202533. */
  202534. static int fts5BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
  202535. Fts5Table *pTab = (Fts5Table*)pVTab;
  202536. Fts5Config *pConfig = pTab->pConfig;
  202537. const int nCol = pConfig->nCol;
  202538. int idxFlags = 0; /* Parameter passed through to xFilter() */
  202539. int bHasMatch;
  202540. int iNext;
  202541. int i;
  202542. struct Constraint {
  202543. int op; /* Mask against sqlite3_index_constraint.op */
  202544. int fts5op; /* FTS5 mask for idxFlags */
  202545. int iCol; /* 0==rowid, 1==tbl, 2==rank */
  202546. int omit; /* True to omit this if found */
  202547. int iConsIndex; /* Index in pInfo->aConstraint[] */
  202548. } aConstraint[] = {
  202549. {SQLITE_INDEX_CONSTRAINT_MATCH|SQLITE_INDEX_CONSTRAINT_EQ,
  202550. FTS5_BI_MATCH, 1, 1, -1},
  202551. {SQLITE_INDEX_CONSTRAINT_MATCH|SQLITE_INDEX_CONSTRAINT_EQ,
  202552. FTS5_BI_RANK, 2, 1, -1},
  202553. {SQLITE_INDEX_CONSTRAINT_EQ, FTS5_BI_ROWID_EQ, 0, 0, -1},
  202554. {SQLITE_INDEX_CONSTRAINT_LT|SQLITE_INDEX_CONSTRAINT_LE,
  202555. FTS5_BI_ROWID_LE, 0, 0, -1},
  202556. {SQLITE_INDEX_CONSTRAINT_GT|SQLITE_INDEX_CONSTRAINT_GE,
  202557. FTS5_BI_ROWID_GE, 0, 0, -1},
  202558. };
  202559. int aColMap[3];
  202560. aColMap[0] = -1;
  202561. aColMap[1] = nCol;
  202562. aColMap[2] = nCol+1;
  202563. assert( SQLITE_INDEX_CONSTRAINT_EQ<SQLITE_INDEX_CONSTRAINT_MATCH );
  202564. assert( SQLITE_INDEX_CONSTRAINT_GT<SQLITE_INDEX_CONSTRAINT_MATCH );
  202565. assert( SQLITE_INDEX_CONSTRAINT_LE<SQLITE_INDEX_CONSTRAINT_MATCH );
  202566. assert( SQLITE_INDEX_CONSTRAINT_GE<SQLITE_INDEX_CONSTRAINT_MATCH );
  202567. assert( SQLITE_INDEX_CONSTRAINT_LE<SQLITE_INDEX_CONSTRAINT_MATCH );
  202568. /* Set idxFlags flags for all WHERE clause terms that will be used. */
  202569. for(i=0; i<pInfo->nConstraint; i++){
  202570. struct sqlite3_index_constraint *p = &pInfo->aConstraint[i];
  202571. int iCol = p->iColumn;
  202572. if( (p->op==SQLITE_INDEX_CONSTRAINT_MATCH && iCol>=0 && iCol<=nCol)
  202573. || (p->op==SQLITE_INDEX_CONSTRAINT_EQ && iCol==nCol)
  202574. ){
  202575. /* A MATCH operator or equivalent */
  202576. if( p->usable ){
  202577. idxFlags = (idxFlags & 0xFFFF) | FTS5_BI_MATCH | (iCol << 16);
  202578. aConstraint[0].iConsIndex = i;
  202579. }else{
  202580. /* As there exists an unusable MATCH constraint this is an
  202581. ** unusable plan. Set a prohibitively high cost. */
  202582. pInfo->estimatedCost = 1e50;
  202583. return SQLITE_OK;
  202584. }
  202585. }else if( p->op<=SQLITE_INDEX_CONSTRAINT_MATCH ){
  202586. int j;
  202587. for(j=1; j<ArraySize(aConstraint); j++){
  202588. struct Constraint *pC = &aConstraint[j];
  202589. if( iCol==aColMap[pC->iCol] && (p->op & pC->op) && p->usable ){
  202590. pC->iConsIndex = i;
  202591. idxFlags |= pC->fts5op;
  202592. }
  202593. }
  202594. }
  202595. }
  202596. /* Set idxFlags flags for the ORDER BY clause */
  202597. if( pInfo->nOrderBy==1 ){
  202598. int iSort = pInfo->aOrderBy[0].iColumn;
  202599. if( iSort==(pConfig->nCol+1) && BitFlagTest(idxFlags, FTS5_BI_MATCH) ){
  202600. idxFlags |= FTS5_BI_ORDER_RANK;
  202601. }else if( iSort==-1 ){
  202602. idxFlags |= FTS5_BI_ORDER_ROWID;
  202603. }
  202604. if( BitFlagTest(idxFlags, FTS5_BI_ORDER_RANK|FTS5_BI_ORDER_ROWID) ){
  202605. pInfo->orderByConsumed = 1;
  202606. if( pInfo->aOrderBy[0].desc ){
  202607. idxFlags |= FTS5_BI_ORDER_DESC;
  202608. }
  202609. }
  202610. }
  202611. /* Calculate the estimated cost based on the flags set in idxFlags. */
  202612. bHasMatch = BitFlagTest(idxFlags, FTS5_BI_MATCH);
  202613. if( BitFlagTest(idxFlags, FTS5_BI_ROWID_EQ) ){
  202614. pInfo->estimatedCost = bHasMatch ? 100.0 : 10.0;
  202615. if( bHasMatch==0 ) fts5SetUniqueFlag(pInfo);
  202616. }else if( BitFlagAllTest(idxFlags, FTS5_BI_ROWID_LE|FTS5_BI_ROWID_GE) ){
  202617. pInfo->estimatedCost = bHasMatch ? 500.0 : 250000.0;
  202618. }else if( BitFlagTest(idxFlags, FTS5_BI_ROWID_LE|FTS5_BI_ROWID_GE) ){
  202619. pInfo->estimatedCost = bHasMatch ? 750.0 : 750000.0;
  202620. }else{
  202621. pInfo->estimatedCost = bHasMatch ? 1000.0 : 1000000.0;
  202622. }
  202623. /* Assign argvIndex values to each constraint in use. */
  202624. iNext = 1;
  202625. for(i=0; i<ArraySize(aConstraint); i++){
  202626. struct Constraint *pC = &aConstraint[i];
  202627. if( pC->iConsIndex>=0 ){
  202628. pInfo->aConstraintUsage[pC->iConsIndex].argvIndex = iNext++;
  202629. pInfo->aConstraintUsage[pC->iConsIndex].omit = (unsigned char)pC->omit;
  202630. }
  202631. }
  202632. pInfo->idxNum = idxFlags;
  202633. return SQLITE_OK;
  202634. }
  202635. static int fts5NewTransaction(Fts5FullTable *pTab){
  202636. Fts5Cursor *pCsr;
  202637. for(pCsr=pTab->pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
  202638. if( pCsr->base.pVtab==(sqlite3_vtab*)pTab ) return SQLITE_OK;
  202639. }
  202640. return sqlite3Fts5StorageReset(pTab->pStorage);
  202641. }
  202642. /*
  202643. ** Implementation of xOpen method.
  202644. */
  202645. static int fts5OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  202646. Fts5FullTable *pTab = (Fts5FullTable*)pVTab;
  202647. Fts5Config *pConfig = pTab->p.pConfig;
  202648. Fts5Cursor *pCsr = 0; /* New cursor object */
  202649. sqlite3_int64 nByte; /* Bytes of space to allocate */
  202650. int rc; /* Return code */
  202651. rc = fts5NewTransaction(pTab);
  202652. if( rc==SQLITE_OK ){
  202653. nByte = sizeof(Fts5Cursor) + pConfig->nCol * sizeof(int);
  202654. pCsr = (Fts5Cursor*)sqlite3_malloc64(nByte);
  202655. if( pCsr ){
  202656. Fts5Global *pGlobal = pTab->pGlobal;
  202657. memset(pCsr, 0, (size_t)nByte);
  202658. pCsr->aColumnSize = (int*)&pCsr[1];
  202659. pCsr->pNext = pGlobal->pCsr;
  202660. pGlobal->pCsr = pCsr;
  202661. pCsr->iCsrId = ++pGlobal->iNextId;
  202662. }else{
  202663. rc = SQLITE_NOMEM;
  202664. }
  202665. }
  202666. *ppCsr = (sqlite3_vtab_cursor*)pCsr;
  202667. return rc;
  202668. }
  202669. static int fts5StmtType(Fts5Cursor *pCsr){
  202670. if( pCsr->ePlan==FTS5_PLAN_SCAN ){
  202671. return (pCsr->bDesc) ? FTS5_STMT_SCAN_DESC : FTS5_STMT_SCAN_ASC;
  202672. }
  202673. return FTS5_STMT_LOOKUP;
  202674. }
  202675. /*
  202676. ** This function is called after the cursor passed as the only argument
  202677. ** is moved to point at a different row. It clears all cached data
  202678. ** specific to the previous row stored by the cursor object.
  202679. */
  202680. static void fts5CsrNewrow(Fts5Cursor *pCsr){
  202681. CsrFlagSet(pCsr,
  202682. FTS5CSR_REQUIRE_CONTENT
  202683. | FTS5CSR_REQUIRE_DOCSIZE
  202684. | FTS5CSR_REQUIRE_INST
  202685. | FTS5CSR_REQUIRE_POSLIST
  202686. );
  202687. }
  202688. static void fts5FreeCursorComponents(Fts5Cursor *pCsr){
  202689. Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);
  202690. Fts5Auxdata *pData;
  202691. Fts5Auxdata *pNext;
  202692. sqlite3_free(pCsr->aInstIter);
  202693. sqlite3_free(pCsr->aInst);
  202694. if( pCsr->pStmt ){
  202695. int eStmt = fts5StmtType(pCsr);
  202696. sqlite3Fts5StorageStmtRelease(pTab->pStorage, eStmt, pCsr->pStmt);
  202697. }
  202698. if( pCsr->pSorter ){
  202699. Fts5Sorter *pSorter = pCsr->pSorter;
  202700. sqlite3_finalize(pSorter->pStmt);
  202701. sqlite3_free(pSorter);
  202702. }
  202703. if( pCsr->ePlan!=FTS5_PLAN_SOURCE ){
  202704. sqlite3Fts5ExprFree(pCsr->pExpr);
  202705. }
  202706. for(pData=pCsr->pAuxdata; pData; pData=pNext){
  202707. pNext = pData->pNext;
  202708. if( pData->xDelete ) pData->xDelete(pData->pPtr);
  202709. sqlite3_free(pData);
  202710. }
  202711. sqlite3_finalize(pCsr->pRankArgStmt);
  202712. sqlite3_free(pCsr->apRankArg);
  202713. if( CsrFlagTest(pCsr, FTS5CSR_FREE_ZRANK) ){
  202714. sqlite3_free(pCsr->zRank);
  202715. sqlite3_free(pCsr->zRankArgs);
  202716. }
  202717. memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan - (u8*)pCsr));
  202718. }
  202719. /*
  202720. ** Close the cursor. For additional information see the documentation
  202721. ** on the xClose method of the virtual table interface.
  202722. */
  202723. static int fts5CloseMethod(sqlite3_vtab_cursor *pCursor){
  202724. if( pCursor ){
  202725. Fts5FullTable *pTab = (Fts5FullTable*)(pCursor->pVtab);
  202726. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  202727. Fts5Cursor **pp;
  202728. fts5FreeCursorComponents(pCsr);
  202729. /* Remove the cursor from the Fts5Global.pCsr list */
  202730. for(pp=&pTab->pGlobal->pCsr; (*pp)!=pCsr; pp=&(*pp)->pNext);
  202731. *pp = pCsr->pNext;
  202732. sqlite3_free(pCsr);
  202733. }
  202734. return SQLITE_OK;
  202735. }
  202736. static int fts5SorterNext(Fts5Cursor *pCsr){
  202737. Fts5Sorter *pSorter = pCsr->pSorter;
  202738. int rc;
  202739. rc = sqlite3_step(pSorter->pStmt);
  202740. if( rc==SQLITE_DONE ){
  202741. rc = SQLITE_OK;
  202742. CsrFlagSet(pCsr, FTS5CSR_EOF);
  202743. }else if( rc==SQLITE_ROW ){
  202744. const u8 *a;
  202745. const u8 *aBlob;
  202746. int nBlob;
  202747. int i;
  202748. int iOff = 0;
  202749. rc = SQLITE_OK;
  202750. pSorter->iRowid = sqlite3_column_int64(pSorter->pStmt, 0);
  202751. nBlob = sqlite3_column_bytes(pSorter->pStmt, 1);
  202752. aBlob = a = sqlite3_column_blob(pSorter->pStmt, 1);
  202753. /* nBlob==0 in detail=none mode. */
  202754. if( nBlob>0 ){
  202755. for(i=0; i<(pSorter->nIdx-1); i++){
  202756. int iVal;
  202757. a += fts5GetVarint32(a, iVal);
  202758. iOff += iVal;
  202759. pSorter->aIdx[i] = iOff;
  202760. }
  202761. pSorter->aIdx[i] = &aBlob[nBlob] - a;
  202762. pSorter->aPoslist = a;
  202763. }
  202764. fts5CsrNewrow(pCsr);
  202765. }
  202766. return rc;
  202767. }
  202768. /*
  202769. ** Set the FTS5CSR_REQUIRE_RESEEK flag on all FTS5_PLAN_MATCH cursors
  202770. ** open on table pTab.
  202771. */
  202772. static void fts5TripCursors(Fts5FullTable *pTab){
  202773. Fts5Cursor *pCsr;
  202774. for(pCsr=pTab->pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
  202775. if( pCsr->ePlan==FTS5_PLAN_MATCH
  202776. && pCsr->base.pVtab==(sqlite3_vtab*)pTab
  202777. ){
  202778. CsrFlagSet(pCsr, FTS5CSR_REQUIRE_RESEEK);
  202779. }
  202780. }
  202781. }
  202782. /*
  202783. ** If the REQUIRE_RESEEK flag is set on the cursor passed as the first
  202784. ** argument, close and reopen all Fts5IndexIter iterators that the cursor
  202785. ** is using. Then attempt to move the cursor to a rowid equal to or laster
  202786. ** (in the cursors sort order - ASC or DESC) than the current rowid.
  202787. **
  202788. ** If the new rowid is not equal to the old, set output parameter *pbSkip
  202789. ** to 1 before returning. Otherwise, leave it unchanged.
  202790. **
  202791. ** Return SQLITE_OK if successful or if no reseek was required, or an
  202792. ** error code if an error occurred.
  202793. */
  202794. static int fts5CursorReseek(Fts5Cursor *pCsr, int *pbSkip){
  202795. int rc = SQLITE_OK;
  202796. assert( *pbSkip==0 );
  202797. if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_RESEEK) ){
  202798. Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);
  202799. int bDesc = pCsr->bDesc;
  202800. i64 iRowid = sqlite3Fts5ExprRowid(pCsr->pExpr);
  202801. rc = sqlite3Fts5ExprFirst(pCsr->pExpr, pTab->p.pIndex, iRowid, bDesc);
  202802. if( rc==SQLITE_OK && iRowid!=sqlite3Fts5ExprRowid(pCsr->pExpr) ){
  202803. *pbSkip = 1;
  202804. }
  202805. CsrFlagClear(pCsr, FTS5CSR_REQUIRE_RESEEK);
  202806. fts5CsrNewrow(pCsr);
  202807. if( sqlite3Fts5ExprEof(pCsr->pExpr) ){
  202808. CsrFlagSet(pCsr, FTS5CSR_EOF);
  202809. *pbSkip = 1;
  202810. }
  202811. }
  202812. return rc;
  202813. }
  202814. /*
  202815. ** Advance the cursor to the next row in the table that matches the
  202816. ** search criteria.
  202817. **
  202818. ** Return SQLITE_OK if nothing goes wrong. SQLITE_OK is returned
  202819. ** even if we reach end-of-file. The fts5EofMethod() will be called
  202820. ** subsequently to determine whether or not an EOF was hit.
  202821. */
  202822. static int fts5NextMethod(sqlite3_vtab_cursor *pCursor){
  202823. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  202824. int rc;
  202825. assert( (pCsr->ePlan<3)==
  202826. (pCsr->ePlan==FTS5_PLAN_MATCH || pCsr->ePlan==FTS5_PLAN_SOURCE)
  202827. );
  202828. assert( !CsrFlagTest(pCsr, FTS5CSR_EOF) );
  202829. if( pCsr->ePlan<3 ){
  202830. int bSkip = 0;
  202831. if( (rc = fts5CursorReseek(pCsr, &bSkip)) || bSkip ) return rc;
  202832. rc = sqlite3Fts5ExprNext(pCsr->pExpr, pCsr->iLastRowid);
  202833. CsrFlagSet(pCsr, sqlite3Fts5ExprEof(pCsr->pExpr));
  202834. fts5CsrNewrow(pCsr);
  202835. }else{
  202836. switch( pCsr->ePlan ){
  202837. case FTS5_PLAN_SPECIAL: {
  202838. CsrFlagSet(pCsr, FTS5CSR_EOF);
  202839. rc = SQLITE_OK;
  202840. break;
  202841. }
  202842. case FTS5_PLAN_SORTED_MATCH: {
  202843. rc = fts5SorterNext(pCsr);
  202844. break;
  202845. }
  202846. default:
  202847. rc = sqlite3_step(pCsr->pStmt);
  202848. if( rc!=SQLITE_ROW ){
  202849. CsrFlagSet(pCsr, FTS5CSR_EOF);
  202850. rc = sqlite3_reset(pCsr->pStmt);
  202851. }else{
  202852. rc = SQLITE_OK;
  202853. }
  202854. break;
  202855. }
  202856. }
  202857. return rc;
  202858. }
  202859. static int fts5PrepareStatement(
  202860. sqlite3_stmt **ppStmt,
  202861. Fts5Config *pConfig,
  202862. const char *zFmt,
  202863. ...
  202864. ){
  202865. sqlite3_stmt *pRet = 0;
  202866. int rc;
  202867. char *zSql;
  202868. va_list ap;
  202869. va_start(ap, zFmt);
  202870. zSql = sqlite3_vmprintf(zFmt, ap);
  202871. if( zSql==0 ){
  202872. rc = SQLITE_NOMEM;
  202873. }else{
  202874. rc = sqlite3_prepare_v3(pConfig->db, zSql, -1,
  202875. SQLITE_PREPARE_PERSISTENT, &pRet, 0);
  202876. if( rc!=SQLITE_OK ){
  202877. *pConfig->pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(pConfig->db));
  202878. }
  202879. sqlite3_free(zSql);
  202880. }
  202881. va_end(ap);
  202882. *ppStmt = pRet;
  202883. return rc;
  202884. }
  202885. static int fts5CursorFirstSorted(
  202886. Fts5FullTable *pTab,
  202887. Fts5Cursor *pCsr,
  202888. int bDesc
  202889. ){
  202890. Fts5Config *pConfig = pTab->p.pConfig;
  202891. Fts5Sorter *pSorter;
  202892. int nPhrase;
  202893. sqlite3_int64 nByte;
  202894. int rc;
  202895. const char *zRank = pCsr->zRank;
  202896. const char *zRankArgs = pCsr->zRankArgs;
  202897. nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
  202898. nByte = sizeof(Fts5Sorter) + sizeof(int) * (nPhrase-1);
  202899. pSorter = (Fts5Sorter*)sqlite3_malloc64(nByte);
  202900. if( pSorter==0 ) return SQLITE_NOMEM;
  202901. memset(pSorter, 0, (size_t)nByte);
  202902. pSorter->nIdx = nPhrase;
  202903. /* TODO: It would be better to have some system for reusing statement
  202904. ** handles here, rather than preparing a new one for each query. But that
  202905. ** is not possible as SQLite reference counts the virtual table objects.
  202906. ** And since the statement required here reads from this very virtual
  202907. ** table, saving it creates a circular reference.
  202908. **
  202909. ** If SQLite a built-in statement cache, this wouldn't be a problem. */
  202910. rc = fts5PrepareStatement(&pSorter->pStmt, pConfig,
  202911. "SELECT rowid, rank FROM %Q.%Q ORDER BY %s(%s%s%s) %s",
  202912. pConfig->zDb, pConfig->zName, zRank, pConfig->zName,
  202913. (zRankArgs ? ", " : ""),
  202914. (zRankArgs ? zRankArgs : ""),
  202915. bDesc ? "DESC" : "ASC"
  202916. );
  202917. pCsr->pSorter = pSorter;
  202918. if( rc==SQLITE_OK ){
  202919. assert( pTab->pSortCsr==0 );
  202920. pTab->pSortCsr = pCsr;
  202921. rc = fts5SorterNext(pCsr);
  202922. pTab->pSortCsr = 0;
  202923. }
  202924. if( rc!=SQLITE_OK ){
  202925. sqlite3_finalize(pSorter->pStmt);
  202926. sqlite3_free(pSorter);
  202927. pCsr->pSorter = 0;
  202928. }
  202929. return rc;
  202930. }
  202931. static int fts5CursorFirst(Fts5FullTable *pTab, Fts5Cursor *pCsr, int bDesc){
  202932. int rc;
  202933. Fts5Expr *pExpr = pCsr->pExpr;
  202934. rc = sqlite3Fts5ExprFirst(pExpr, pTab->p.pIndex, pCsr->iFirstRowid, bDesc);
  202935. if( sqlite3Fts5ExprEof(pExpr) ){
  202936. CsrFlagSet(pCsr, FTS5CSR_EOF);
  202937. }
  202938. fts5CsrNewrow(pCsr);
  202939. return rc;
  202940. }
  202941. /*
  202942. ** Process a "special" query. A special query is identified as one with a
  202943. ** MATCH expression that begins with a '*' character. The remainder of
  202944. ** the text passed to the MATCH operator are used as the special query
  202945. ** parameters.
  202946. */
  202947. static int fts5SpecialMatch(
  202948. Fts5FullTable *pTab,
  202949. Fts5Cursor *pCsr,
  202950. const char *zQuery
  202951. ){
  202952. int rc = SQLITE_OK; /* Return code */
  202953. const char *z = zQuery; /* Special query text */
  202954. int n; /* Number of bytes in text at z */
  202955. while( z[0]==' ' ) z++;
  202956. for(n=0; z[n] && z[n]!=' '; n++);
  202957. assert( pTab->p.base.zErrMsg==0 );
  202958. pCsr->ePlan = FTS5_PLAN_SPECIAL;
  202959. if( 0==sqlite3_strnicmp("reads", z, n) ){
  202960. pCsr->iSpecial = sqlite3Fts5IndexReads(pTab->p.pIndex);
  202961. }
  202962. else if( 0==sqlite3_strnicmp("id", z, n) ){
  202963. pCsr->iSpecial = pCsr->iCsrId;
  202964. }
  202965. else{
  202966. /* An unrecognized directive. Return an error message. */
  202967. pTab->p.base.zErrMsg = sqlite3_mprintf("unknown special query: %.*s", n, z);
  202968. rc = SQLITE_ERROR;
  202969. }
  202970. return rc;
  202971. }
  202972. /*
  202973. ** Search for an auxiliary function named zName that can be used with table
  202974. ** pTab. If one is found, return a pointer to the corresponding Fts5Auxiliary
  202975. ** structure. Otherwise, if no such function exists, return NULL.
  202976. */
  202977. static Fts5Auxiliary *fts5FindAuxiliary(Fts5FullTable *pTab, const char *zName){
  202978. Fts5Auxiliary *pAux;
  202979. for(pAux=pTab->pGlobal->pAux; pAux; pAux=pAux->pNext){
  202980. if( sqlite3_stricmp(zName, pAux->zFunc)==0 ) return pAux;
  202981. }
  202982. /* No function of the specified name was found. Return 0. */
  202983. return 0;
  202984. }
  202985. static int fts5FindRankFunction(Fts5Cursor *pCsr){
  202986. Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);
  202987. Fts5Config *pConfig = pTab->p.pConfig;
  202988. int rc = SQLITE_OK;
  202989. Fts5Auxiliary *pAux = 0;
  202990. const char *zRank = pCsr->zRank;
  202991. const char *zRankArgs = pCsr->zRankArgs;
  202992. if( zRankArgs ){
  202993. char *zSql = sqlite3Fts5Mprintf(&rc, "SELECT %s", zRankArgs);
  202994. if( zSql ){
  202995. sqlite3_stmt *pStmt = 0;
  202996. rc = sqlite3_prepare_v3(pConfig->db, zSql, -1,
  202997. SQLITE_PREPARE_PERSISTENT, &pStmt, 0);
  202998. sqlite3_free(zSql);
  202999. assert( rc==SQLITE_OK || pCsr->pRankArgStmt==0 );
  203000. if( rc==SQLITE_OK ){
  203001. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  203002. sqlite3_int64 nByte;
  203003. pCsr->nRankArg = sqlite3_column_count(pStmt);
  203004. nByte = sizeof(sqlite3_value*)*pCsr->nRankArg;
  203005. pCsr->apRankArg = (sqlite3_value**)sqlite3Fts5MallocZero(&rc, nByte);
  203006. if( rc==SQLITE_OK ){
  203007. int i;
  203008. for(i=0; i<pCsr->nRankArg; i++){
  203009. pCsr->apRankArg[i] = sqlite3_column_value(pStmt, i);
  203010. }
  203011. }
  203012. pCsr->pRankArgStmt = pStmt;
  203013. }else{
  203014. rc = sqlite3_finalize(pStmt);
  203015. assert( rc!=SQLITE_OK );
  203016. }
  203017. }
  203018. }
  203019. }
  203020. if( rc==SQLITE_OK ){
  203021. pAux = fts5FindAuxiliary(pTab, zRank);
  203022. if( pAux==0 ){
  203023. assert( pTab->p.base.zErrMsg==0 );
  203024. pTab->p.base.zErrMsg = sqlite3_mprintf("no such function: %s", zRank);
  203025. rc = SQLITE_ERROR;
  203026. }
  203027. }
  203028. pCsr->pRank = pAux;
  203029. return rc;
  203030. }
  203031. static int fts5CursorParseRank(
  203032. Fts5Config *pConfig,
  203033. Fts5Cursor *pCsr,
  203034. sqlite3_value *pRank
  203035. ){
  203036. int rc = SQLITE_OK;
  203037. if( pRank ){
  203038. const char *z = (const char*)sqlite3_value_text(pRank);
  203039. char *zRank = 0;
  203040. char *zRankArgs = 0;
  203041. if( z==0 ){
  203042. if( sqlite3_value_type(pRank)==SQLITE_NULL ) rc = SQLITE_ERROR;
  203043. }else{
  203044. rc = sqlite3Fts5ConfigParseRank(z, &zRank, &zRankArgs);
  203045. }
  203046. if( rc==SQLITE_OK ){
  203047. pCsr->zRank = zRank;
  203048. pCsr->zRankArgs = zRankArgs;
  203049. CsrFlagSet(pCsr, FTS5CSR_FREE_ZRANK);
  203050. }else if( rc==SQLITE_ERROR ){
  203051. pCsr->base.pVtab->zErrMsg = sqlite3_mprintf(
  203052. "parse error in rank function: %s", z
  203053. );
  203054. }
  203055. }else{
  203056. if( pConfig->zRank ){
  203057. pCsr->zRank = (char*)pConfig->zRank;
  203058. pCsr->zRankArgs = (char*)pConfig->zRankArgs;
  203059. }else{
  203060. pCsr->zRank = (char*)FTS5_DEFAULT_RANK;
  203061. pCsr->zRankArgs = 0;
  203062. }
  203063. }
  203064. return rc;
  203065. }
  203066. static i64 fts5GetRowidLimit(sqlite3_value *pVal, i64 iDefault){
  203067. if( pVal ){
  203068. int eType = sqlite3_value_numeric_type(pVal);
  203069. if( eType==SQLITE_INTEGER ){
  203070. return sqlite3_value_int64(pVal);
  203071. }
  203072. }
  203073. return iDefault;
  203074. }
  203075. /*
  203076. ** This is the xFilter interface for the virtual table. See
  203077. ** the virtual table xFilter method documentation for additional
  203078. ** information.
  203079. **
  203080. ** There are three possible query strategies:
  203081. **
  203082. ** 1. Full-text search using a MATCH operator.
  203083. ** 2. A by-rowid lookup.
  203084. ** 3. A full-table scan.
  203085. */
  203086. static int fts5FilterMethod(
  203087. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  203088. int idxNum, /* Strategy index */
  203089. const char *zUnused, /* Unused */
  203090. int nVal, /* Number of elements in apVal */
  203091. sqlite3_value **apVal /* Arguments for the indexing scheme */
  203092. ){
  203093. Fts5FullTable *pTab = (Fts5FullTable*)(pCursor->pVtab);
  203094. Fts5Config *pConfig = pTab->p.pConfig;
  203095. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  203096. int rc = SQLITE_OK; /* Error code */
  203097. int iVal = 0; /* Counter for apVal[] */
  203098. int bDesc; /* True if ORDER BY [rank|rowid] DESC */
  203099. int bOrderByRank; /* True if ORDER BY rank */
  203100. sqlite3_value *pMatch = 0; /* <tbl> MATCH ? expression (or NULL) */
  203101. sqlite3_value *pRank = 0; /* rank MATCH ? expression (or NULL) */
  203102. sqlite3_value *pRowidEq = 0; /* rowid = ? expression (or NULL) */
  203103. sqlite3_value *pRowidLe = 0; /* rowid <= ? expression (or NULL) */
  203104. sqlite3_value *pRowidGe = 0; /* rowid >= ? expression (or NULL) */
  203105. int iCol; /* Column on LHS of MATCH operator */
  203106. char **pzErrmsg = pConfig->pzErrmsg;
  203107. UNUSED_PARAM(zUnused);
  203108. UNUSED_PARAM(nVal);
  203109. if( pCsr->ePlan ){
  203110. fts5FreeCursorComponents(pCsr);
  203111. memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan-(u8*)pCsr));
  203112. }
  203113. assert( pCsr->pStmt==0 );
  203114. assert( pCsr->pExpr==0 );
  203115. assert( pCsr->csrflags==0 );
  203116. assert( pCsr->pRank==0 );
  203117. assert( pCsr->zRank==0 );
  203118. assert( pCsr->zRankArgs==0 );
  203119. assert( pzErrmsg==0 || pzErrmsg==&pTab->p.base.zErrMsg );
  203120. pConfig->pzErrmsg = &pTab->p.base.zErrMsg;
  203121. /* Decode the arguments passed through to this function.
  203122. **
  203123. ** Note: The following set of if(...) statements must be in the same
  203124. ** order as the corresponding entries in the struct at the top of
  203125. ** fts5BestIndexMethod(). */
  203126. if( BitFlagTest(idxNum, FTS5_BI_MATCH) ) pMatch = apVal[iVal++];
  203127. if( BitFlagTest(idxNum, FTS5_BI_RANK) ) pRank = apVal[iVal++];
  203128. if( BitFlagTest(idxNum, FTS5_BI_ROWID_EQ) ) pRowidEq = apVal[iVal++];
  203129. if( BitFlagTest(idxNum, FTS5_BI_ROWID_LE) ) pRowidLe = apVal[iVal++];
  203130. if( BitFlagTest(idxNum, FTS5_BI_ROWID_GE) ) pRowidGe = apVal[iVal++];
  203131. iCol = (idxNum>>16);
  203132. assert( iCol>=0 && iCol<=pConfig->nCol );
  203133. assert( iVal==nVal );
  203134. bOrderByRank = ((idxNum & FTS5_BI_ORDER_RANK) ? 1 : 0);
  203135. pCsr->bDesc = bDesc = ((idxNum & FTS5_BI_ORDER_DESC) ? 1 : 0);
  203136. /* Set the cursor upper and lower rowid limits. Only some strategies
  203137. ** actually use them. This is ok, as the xBestIndex() method leaves the
  203138. ** sqlite3_index_constraint.omit flag clear for range constraints
  203139. ** on the rowid field. */
  203140. if( pRowidEq ){
  203141. pRowidLe = pRowidGe = pRowidEq;
  203142. }
  203143. if( bDesc ){
  203144. pCsr->iFirstRowid = fts5GetRowidLimit(pRowidLe, LARGEST_INT64);
  203145. pCsr->iLastRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64);
  203146. }else{
  203147. pCsr->iLastRowid = fts5GetRowidLimit(pRowidLe, LARGEST_INT64);
  203148. pCsr->iFirstRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64);
  203149. }
  203150. if( pTab->pSortCsr ){
  203151. /* If pSortCsr is non-NULL, then this call is being made as part of
  203152. ** processing for a "... MATCH <expr> ORDER BY rank" query (ePlan is
  203153. ** set to FTS5_PLAN_SORTED_MATCH). pSortCsr is the cursor that will
  203154. ** return results to the user for this query. The current cursor
  203155. ** (pCursor) is used to execute the query issued by function
  203156. ** fts5CursorFirstSorted() above. */
  203157. assert( pRowidEq==0 && pRowidLe==0 && pRowidGe==0 && pRank==0 );
  203158. assert( nVal==0 && pMatch==0 && bOrderByRank==0 && bDesc==0 );
  203159. assert( pCsr->iLastRowid==LARGEST_INT64 );
  203160. assert( pCsr->iFirstRowid==SMALLEST_INT64 );
  203161. if( pTab->pSortCsr->bDesc ){
  203162. pCsr->iLastRowid = pTab->pSortCsr->iFirstRowid;
  203163. pCsr->iFirstRowid = pTab->pSortCsr->iLastRowid;
  203164. }else{
  203165. pCsr->iLastRowid = pTab->pSortCsr->iLastRowid;
  203166. pCsr->iFirstRowid = pTab->pSortCsr->iFirstRowid;
  203167. }
  203168. pCsr->ePlan = FTS5_PLAN_SOURCE;
  203169. pCsr->pExpr = pTab->pSortCsr->pExpr;
  203170. rc = fts5CursorFirst(pTab, pCsr, bDesc);
  203171. }else if( pMatch ){
  203172. const char *zExpr = (const char*)sqlite3_value_text(apVal[0]);
  203173. if( zExpr==0 ) zExpr = "";
  203174. rc = fts5CursorParseRank(pConfig, pCsr, pRank);
  203175. if( rc==SQLITE_OK ){
  203176. if( zExpr[0]=='*' ){
  203177. /* The user has issued a query of the form "MATCH '*...'". This
  203178. ** indicates that the MATCH expression is not a full text query,
  203179. ** but a request for an internal parameter. */
  203180. rc = fts5SpecialMatch(pTab, pCsr, &zExpr[1]);
  203181. }else{
  203182. char **pzErr = &pTab->p.base.zErrMsg;
  203183. rc = sqlite3Fts5ExprNew(pConfig, iCol, zExpr, &pCsr->pExpr, pzErr);
  203184. if( rc==SQLITE_OK ){
  203185. if( bOrderByRank ){
  203186. pCsr->ePlan = FTS5_PLAN_SORTED_MATCH;
  203187. rc = fts5CursorFirstSorted(pTab, pCsr, bDesc);
  203188. }else{
  203189. pCsr->ePlan = FTS5_PLAN_MATCH;
  203190. rc = fts5CursorFirst(pTab, pCsr, bDesc);
  203191. }
  203192. }
  203193. }
  203194. }
  203195. }else if( pConfig->zContent==0 ){
  203196. *pConfig->pzErrmsg = sqlite3_mprintf(
  203197. "%s: table does not support scanning", pConfig->zName
  203198. );
  203199. rc = SQLITE_ERROR;
  203200. }else{
  203201. /* This is either a full-table scan (ePlan==FTS5_PLAN_SCAN) or a lookup
  203202. ** by rowid (ePlan==FTS5_PLAN_ROWID). */
  203203. pCsr->ePlan = (pRowidEq ? FTS5_PLAN_ROWID : FTS5_PLAN_SCAN);
  203204. rc = sqlite3Fts5StorageStmt(
  203205. pTab->pStorage, fts5StmtType(pCsr), &pCsr->pStmt, &pTab->p.base.zErrMsg
  203206. );
  203207. if( rc==SQLITE_OK ){
  203208. if( pCsr->ePlan==FTS5_PLAN_ROWID ){
  203209. sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
  203210. }else{
  203211. sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iFirstRowid);
  203212. sqlite3_bind_int64(pCsr->pStmt, 2, pCsr->iLastRowid);
  203213. }
  203214. rc = fts5NextMethod(pCursor);
  203215. }
  203216. }
  203217. pConfig->pzErrmsg = pzErrmsg;
  203218. return rc;
  203219. }
  203220. /*
  203221. ** This is the xEof method of the virtual table. SQLite calls this
  203222. ** routine to find out if it has reached the end of a result set.
  203223. */
  203224. static int fts5EofMethod(sqlite3_vtab_cursor *pCursor){
  203225. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  203226. return (CsrFlagTest(pCsr, FTS5CSR_EOF) ? 1 : 0);
  203227. }
  203228. /*
  203229. ** Return the rowid that the cursor currently points to.
  203230. */
  203231. static i64 fts5CursorRowid(Fts5Cursor *pCsr){
  203232. assert( pCsr->ePlan==FTS5_PLAN_MATCH
  203233. || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH
  203234. || pCsr->ePlan==FTS5_PLAN_SOURCE
  203235. );
  203236. if( pCsr->pSorter ){
  203237. return pCsr->pSorter->iRowid;
  203238. }else{
  203239. return sqlite3Fts5ExprRowid(pCsr->pExpr);
  203240. }
  203241. }
  203242. /*
  203243. ** This is the xRowid method. The SQLite core calls this routine to
  203244. ** retrieve the rowid for the current row of the result set. fts5
  203245. ** exposes %_content.rowid as the rowid for the virtual table. The
  203246. ** rowid should be written to *pRowid.
  203247. */
  203248. static int fts5RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  203249. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  203250. int ePlan = pCsr->ePlan;
  203251. assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 );
  203252. switch( ePlan ){
  203253. case FTS5_PLAN_SPECIAL:
  203254. *pRowid = 0;
  203255. break;
  203256. case FTS5_PLAN_SOURCE:
  203257. case FTS5_PLAN_MATCH:
  203258. case FTS5_PLAN_SORTED_MATCH:
  203259. *pRowid = fts5CursorRowid(pCsr);
  203260. break;
  203261. default:
  203262. *pRowid = sqlite3_column_int64(pCsr->pStmt, 0);
  203263. break;
  203264. }
  203265. return SQLITE_OK;
  203266. }
  203267. /*
  203268. ** If the cursor requires seeking (bSeekRequired flag is set), seek it.
  203269. ** Return SQLITE_OK if no error occurs, or an SQLite error code otherwise.
  203270. **
  203271. ** If argument bErrormsg is true and an error occurs, an error message may
  203272. ** be left in sqlite3_vtab.zErrMsg.
  203273. */
  203274. static int fts5SeekCursor(Fts5Cursor *pCsr, int bErrormsg){
  203275. int rc = SQLITE_OK;
  203276. /* If the cursor does not yet have a statement handle, obtain one now. */
  203277. if( pCsr->pStmt==0 ){
  203278. Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);
  203279. int eStmt = fts5StmtType(pCsr);
  203280. rc = sqlite3Fts5StorageStmt(
  203281. pTab->pStorage, eStmt, &pCsr->pStmt, (bErrormsg?&pTab->p.base.zErrMsg:0)
  203282. );
  203283. assert( rc!=SQLITE_OK || pTab->p.base.zErrMsg==0 );
  203284. assert( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) );
  203285. }
  203286. if( rc==SQLITE_OK && CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) ){
  203287. assert( pCsr->pExpr );
  203288. sqlite3_reset(pCsr->pStmt);
  203289. sqlite3_bind_int64(pCsr->pStmt, 1, fts5CursorRowid(pCsr));
  203290. rc = sqlite3_step(pCsr->pStmt);
  203291. if( rc==SQLITE_ROW ){
  203292. rc = SQLITE_OK;
  203293. CsrFlagClear(pCsr, FTS5CSR_REQUIRE_CONTENT);
  203294. }else{
  203295. rc = sqlite3_reset(pCsr->pStmt);
  203296. if( rc==SQLITE_OK ){
  203297. rc = FTS5_CORRUPT;
  203298. }
  203299. }
  203300. }
  203301. return rc;
  203302. }
  203303. static void fts5SetVtabError(Fts5FullTable *p, const char *zFormat, ...){
  203304. va_list ap; /* ... printf arguments */
  203305. va_start(ap, zFormat);
  203306. assert( p->p.base.zErrMsg==0 );
  203307. p->p.base.zErrMsg = sqlite3_vmprintf(zFormat, ap);
  203308. va_end(ap);
  203309. }
  203310. /*
  203311. ** This function is called to handle an FTS INSERT command. In other words,
  203312. ** an INSERT statement of the form:
  203313. **
  203314. ** INSERT INTO fts(fts) VALUES($pCmd)
  203315. ** INSERT INTO fts(fts, rank) VALUES($pCmd, $pVal)
  203316. **
  203317. ** Argument pVal is the value assigned to column "fts" by the INSERT
  203318. ** statement. This function returns SQLITE_OK if successful, or an SQLite
  203319. ** error code if an error occurs.
  203320. **
  203321. ** The commands implemented by this function are documented in the "Special
  203322. ** INSERT Directives" section of the documentation. It should be updated if
  203323. ** more commands are added to this function.
  203324. */
  203325. static int fts5SpecialInsert(
  203326. Fts5FullTable *pTab, /* Fts5 table object */
  203327. const char *zCmd, /* Text inserted into table-name column */
  203328. sqlite3_value *pVal /* Value inserted into rank column */
  203329. ){
  203330. Fts5Config *pConfig = pTab->p.pConfig;
  203331. int rc = SQLITE_OK;
  203332. int bError = 0;
  203333. if( 0==sqlite3_stricmp("delete-all", zCmd) ){
  203334. if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
  203335. fts5SetVtabError(pTab,
  203336. "'delete-all' may only be used with a "
  203337. "contentless or external content fts5 table"
  203338. );
  203339. rc = SQLITE_ERROR;
  203340. }else{
  203341. rc = sqlite3Fts5StorageDeleteAll(pTab->pStorage);
  203342. }
  203343. }else if( 0==sqlite3_stricmp("rebuild", zCmd) ){
  203344. if( pConfig->eContent==FTS5_CONTENT_NONE ){
  203345. fts5SetVtabError(pTab,
  203346. "'rebuild' may not be used with a contentless fts5 table"
  203347. );
  203348. rc = SQLITE_ERROR;
  203349. }else{
  203350. rc = sqlite3Fts5StorageRebuild(pTab->pStorage);
  203351. }
  203352. }else if( 0==sqlite3_stricmp("optimize", zCmd) ){
  203353. rc = sqlite3Fts5StorageOptimize(pTab->pStorage);
  203354. }else if( 0==sqlite3_stricmp("merge", zCmd) ){
  203355. int nMerge = sqlite3_value_int(pVal);
  203356. rc = sqlite3Fts5StorageMerge(pTab->pStorage, nMerge);
  203357. }else if( 0==sqlite3_stricmp("integrity-check", zCmd) ){
  203358. rc = sqlite3Fts5StorageIntegrity(pTab->pStorage);
  203359. #ifdef SQLITE_DEBUG
  203360. }else if( 0==sqlite3_stricmp("prefix-index", zCmd) ){
  203361. pConfig->bPrefixIndex = sqlite3_value_int(pVal);
  203362. #endif
  203363. }else{
  203364. rc = sqlite3Fts5IndexLoadConfig(pTab->p.pIndex);
  203365. if( rc==SQLITE_OK ){
  203366. rc = sqlite3Fts5ConfigSetValue(pTab->p.pConfig, zCmd, pVal, &bError);
  203367. }
  203368. if( rc==SQLITE_OK ){
  203369. if( bError ){
  203370. rc = SQLITE_ERROR;
  203371. }else{
  203372. rc = sqlite3Fts5StorageConfigValue(pTab->pStorage, zCmd, pVal, 0);
  203373. }
  203374. }
  203375. }
  203376. return rc;
  203377. }
  203378. static int fts5SpecialDelete(
  203379. Fts5FullTable *pTab,
  203380. sqlite3_value **apVal
  203381. ){
  203382. int rc = SQLITE_OK;
  203383. int eType1 = sqlite3_value_type(apVal[1]);
  203384. if( eType1==SQLITE_INTEGER ){
  203385. sqlite3_int64 iDel = sqlite3_value_int64(apVal[1]);
  203386. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel, &apVal[2]);
  203387. }
  203388. return rc;
  203389. }
  203390. static void fts5StorageInsert(
  203391. int *pRc,
  203392. Fts5FullTable *pTab,
  203393. sqlite3_value **apVal,
  203394. i64 *piRowid
  203395. ){
  203396. int rc = *pRc;
  203397. if( rc==SQLITE_OK ){
  203398. rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, piRowid);
  203399. }
  203400. if( rc==SQLITE_OK ){
  203401. rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal, *piRowid);
  203402. }
  203403. *pRc = rc;
  203404. }
  203405. /*
  203406. ** This function is the implementation of the xUpdate callback used by
  203407. ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
  203408. ** inserted, updated or deleted.
  203409. **
  203410. ** A delete specifies a single argument - the rowid of the row to remove.
  203411. **
  203412. ** Update and insert operations pass:
  203413. **
  203414. ** 1. The "old" rowid, or NULL.
  203415. ** 2. The "new" rowid.
  203416. ** 3. Values for each of the nCol matchable columns.
  203417. ** 4. Values for the two hidden columns (<tablename> and "rank").
  203418. */
  203419. static int fts5UpdateMethod(
  203420. sqlite3_vtab *pVtab, /* Virtual table handle */
  203421. int nArg, /* Size of argument array */
  203422. sqlite3_value **apVal, /* Array of arguments */
  203423. sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
  203424. ){
  203425. Fts5FullTable *pTab = (Fts5FullTable*)pVtab;
  203426. Fts5Config *pConfig = pTab->p.pConfig;
  203427. int eType0; /* value_type() of apVal[0] */
  203428. int rc = SQLITE_OK; /* Return code */
  203429. /* A transaction must be open when this is called. */
  203430. assert( pTab->ts.eState==1 );
  203431. assert( pVtab->zErrMsg==0 );
  203432. assert( nArg==1 || nArg==(2+pConfig->nCol+2) );
  203433. assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER
  203434. || sqlite3_value_type(apVal[0])==SQLITE_NULL
  203435. );
  203436. assert( pTab->p.pConfig->pzErrmsg==0 );
  203437. pTab->p.pConfig->pzErrmsg = &pTab->p.base.zErrMsg;
  203438. /* Put any active cursors into REQUIRE_SEEK state. */
  203439. fts5TripCursors(pTab);
  203440. eType0 = sqlite3_value_type(apVal[0]);
  203441. if( eType0==SQLITE_NULL
  203442. && sqlite3_value_type(apVal[2+pConfig->nCol])!=SQLITE_NULL
  203443. ){
  203444. /* A "special" INSERT op. These are handled separately. */
  203445. const char *z = (const char*)sqlite3_value_text(apVal[2+pConfig->nCol]);
  203446. if( pConfig->eContent!=FTS5_CONTENT_NORMAL
  203447. && 0==sqlite3_stricmp("delete", z)
  203448. ){
  203449. rc = fts5SpecialDelete(pTab, apVal);
  203450. }else{
  203451. rc = fts5SpecialInsert(pTab, z, apVal[2 + pConfig->nCol + 1]);
  203452. }
  203453. }else{
  203454. /* A regular INSERT, UPDATE or DELETE statement. The trick here is that
  203455. ** any conflict on the rowid value must be detected before any
  203456. ** modifications are made to the database file. There are 4 cases:
  203457. **
  203458. ** 1) DELETE
  203459. ** 2) UPDATE (rowid not modified)
  203460. ** 3) UPDATE (rowid modified)
  203461. ** 4) INSERT
  203462. **
  203463. ** Cases 3 and 4 may violate the rowid constraint.
  203464. */
  203465. int eConflict = SQLITE_ABORT;
  203466. if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
  203467. eConflict = sqlite3_vtab_on_conflict(pConfig->db);
  203468. }
  203469. assert( eType0==SQLITE_INTEGER || eType0==SQLITE_NULL );
  203470. assert( nArg!=1 || eType0==SQLITE_INTEGER );
  203471. /* Filter out attempts to run UPDATE or DELETE on contentless tables.
  203472. ** This is not suported. */
  203473. if( eType0==SQLITE_INTEGER && fts5IsContentless(pTab) ){
  203474. pTab->p.base.zErrMsg = sqlite3_mprintf(
  203475. "cannot %s contentless fts5 table: %s",
  203476. (nArg>1 ? "UPDATE" : "DELETE from"), pConfig->zName
  203477. );
  203478. rc = SQLITE_ERROR;
  203479. }
  203480. /* DELETE */
  203481. else if( nArg==1 ){
  203482. i64 iDel = sqlite3_value_int64(apVal[0]); /* Rowid to delete */
  203483. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel, 0);
  203484. }
  203485. /* INSERT or UPDATE */
  203486. else{
  203487. int eType1 = sqlite3_value_numeric_type(apVal[1]);
  203488. if( eType1!=SQLITE_INTEGER && eType1!=SQLITE_NULL ){
  203489. rc = SQLITE_MISMATCH;
  203490. }
  203491. else if( eType0!=SQLITE_INTEGER ){
  203492. /* If this is a REPLACE, first remove the current entry (if any) */
  203493. if( eConflict==SQLITE_REPLACE && eType1==SQLITE_INTEGER ){
  203494. i64 iNew = sqlite3_value_int64(apVal[1]); /* Rowid to delete */
  203495. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew, 0);
  203496. }
  203497. fts5StorageInsert(&rc, pTab, apVal, pRowid);
  203498. }
  203499. /* UPDATE */
  203500. else{
  203501. i64 iOld = sqlite3_value_int64(apVal[0]); /* Old rowid */
  203502. i64 iNew = sqlite3_value_int64(apVal[1]); /* New rowid */
  203503. if( eType1==SQLITE_INTEGER && iOld!=iNew ){
  203504. if( eConflict==SQLITE_REPLACE ){
  203505. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
  203506. if( rc==SQLITE_OK ){
  203507. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew, 0);
  203508. }
  203509. fts5StorageInsert(&rc, pTab, apVal, pRowid);
  203510. }else{
  203511. rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, pRowid);
  203512. if( rc==SQLITE_OK ){
  203513. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
  203514. }
  203515. if( rc==SQLITE_OK ){
  203516. rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal,*pRowid);
  203517. }
  203518. }
  203519. }else{
  203520. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
  203521. fts5StorageInsert(&rc, pTab, apVal, pRowid);
  203522. }
  203523. }
  203524. }
  203525. }
  203526. pTab->p.pConfig->pzErrmsg = 0;
  203527. return rc;
  203528. }
  203529. /*
  203530. ** Implementation of xSync() method.
  203531. */
  203532. static int fts5SyncMethod(sqlite3_vtab *pVtab){
  203533. int rc;
  203534. Fts5FullTable *pTab = (Fts5FullTable*)pVtab;
  203535. fts5CheckTransactionState(pTab, FTS5_SYNC, 0);
  203536. pTab->p.pConfig->pzErrmsg = &pTab->p.base.zErrMsg;
  203537. fts5TripCursors(pTab);
  203538. rc = sqlite3Fts5StorageSync(pTab->pStorage);
  203539. pTab->p.pConfig->pzErrmsg = 0;
  203540. return rc;
  203541. }
  203542. /*
  203543. ** Implementation of xBegin() method.
  203544. */
  203545. static int fts5BeginMethod(sqlite3_vtab *pVtab){
  203546. fts5CheckTransactionState((Fts5FullTable*)pVtab, FTS5_BEGIN, 0);
  203547. fts5NewTransaction((Fts5FullTable*)pVtab);
  203548. return SQLITE_OK;
  203549. }
  203550. /*
  203551. ** Implementation of xCommit() method. This is a no-op. The contents of
  203552. ** the pending-terms hash-table have already been flushed into the database
  203553. ** by fts5SyncMethod().
  203554. */
  203555. static int fts5CommitMethod(sqlite3_vtab *pVtab){
  203556. UNUSED_PARAM(pVtab); /* Call below is a no-op for NDEBUG builds */
  203557. fts5CheckTransactionState((Fts5FullTable*)pVtab, FTS5_COMMIT, 0);
  203558. return SQLITE_OK;
  203559. }
  203560. /*
  203561. ** Implementation of xRollback(). Discard the contents of the pending-terms
  203562. ** hash-table. Any changes made to the database are reverted by SQLite.
  203563. */
  203564. static int fts5RollbackMethod(sqlite3_vtab *pVtab){
  203565. int rc;
  203566. Fts5FullTable *pTab = (Fts5FullTable*)pVtab;
  203567. fts5CheckTransactionState(pTab, FTS5_ROLLBACK, 0);
  203568. rc = sqlite3Fts5StorageRollback(pTab->pStorage);
  203569. return rc;
  203570. }
  203571. static int fts5CsrPoslist(Fts5Cursor*, int, const u8**, int*);
  203572. static void *fts5ApiUserData(Fts5Context *pCtx){
  203573. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  203574. return pCsr->pAux->pUserData;
  203575. }
  203576. static int fts5ApiColumnCount(Fts5Context *pCtx){
  203577. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  203578. return ((Fts5Table*)(pCsr->base.pVtab))->pConfig->nCol;
  203579. }
  203580. static int fts5ApiColumnTotalSize(
  203581. Fts5Context *pCtx,
  203582. int iCol,
  203583. sqlite3_int64 *pnToken
  203584. ){
  203585. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  203586. Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);
  203587. return sqlite3Fts5StorageSize(pTab->pStorage, iCol, pnToken);
  203588. }
  203589. static int fts5ApiRowCount(Fts5Context *pCtx, i64 *pnRow){
  203590. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  203591. Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);
  203592. return sqlite3Fts5StorageRowCount(pTab->pStorage, pnRow);
  203593. }
  203594. static int fts5ApiTokenize(
  203595. Fts5Context *pCtx,
  203596. const char *pText, int nText,
  203597. void *pUserData,
  203598. int (*xToken)(void*, int, const char*, int, int, int)
  203599. ){
  203600. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  203601. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  203602. return sqlite3Fts5Tokenize(
  203603. pTab->pConfig, FTS5_TOKENIZE_AUX, pText, nText, pUserData, xToken
  203604. );
  203605. }
  203606. static int fts5ApiPhraseCount(Fts5Context *pCtx){
  203607. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  203608. return sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
  203609. }
  203610. static int fts5ApiPhraseSize(Fts5Context *pCtx, int iPhrase){
  203611. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  203612. return sqlite3Fts5ExprPhraseSize(pCsr->pExpr, iPhrase);
  203613. }
  203614. static int fts5ApiColumnText(
  203615. Fts5Context *pCtx,
  203616. int iCol,
  203617. const char **pz,
  203618. int *pn
  203619. ){
  203620. int rc = SQLITE_OK;
  203621. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  203622. if( fts5IsContentless((Fts5FullTable*)(pCsr->base.pVtab))
  203623. || pCsr->ePlan==FTS5_PLAN_SPECIAL
  203624. ){
  203625. *pz = 0;
  203626. *pn = 0;
  203627. }else{
  203628. rc = fts5SeekCursor(pCsr, 0);
  203629. if( rc==SQLITE_OK ){
  203630. *pz = (const char*)sqlite3_column_text(pCsr->pStmt, iCol+1);
  203631. *pn = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
  203632. }
  203633. }
  203634. return rc;
  203635. }
  203636. static int fts5CsrPoslist(
  203637. Fts5Cursor *pCsr,
  203638. int iPhrase,
  203639. const u8 **pa,
  203640. int *pn
  203641. ){
  203642. Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
  203643. int rc = SQLITE_OK;
  203644. int bLive = (pCsr->pSorter==0);
  203645. if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_POSLIST) ){
  203646. if( pConfig->eDetail!=FTS5_DETAIL_FULL ){
  203647. Fts5PoslistPopulator *aPopulator;
  203648. int i;
  203649. aPopulator = sqlite3Fts5ExprClearPoslists(pCsr->pExpr, bLive);
  203650. if( aPopulator==0 ) rc = SQLITE_NOMEM;
  203651. for(i=0; i<pConfig->nCol && rc==SQLITE_OK; i++){
  203652. int n; const char *z;
  203653. rc = fts5ApiColumnText((Fts5Context*)pCsr, i, &z, &n);
  203654. if( rc==SQLITE_OK ){
  203655. rc = sqlite3Fts5ExprPopulatePoslists(
  203656. pConfig, pCsr->pExpr, aPopulator, i, z, n
  203657. );
  203658. }
  203659. }
  203660. sqlite3_free(aPopulator);
  203661. if( pCsr->pSorter ){
  203662. sqlite3Fts5ExprCheckPoslists(pCsr->pExpr, pCsr->pSorter->iRowid);
  203663. }
  203664. }
  203665. CsrFlagClear(pCsr, FTS5CSR_REQUIRE_POSLIST);
  203666. }
  203667. if( pCsr->pSorter && pConfig->eDetail==FTS5_DETAIL_FULL ){
  203668. Fts5Sorter *pSorter = pCsr->pSorter;
  203669. int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]);
  203670. *pn = pSorter->aIdx[iPhrase] - i1;
  203671. *pa = &pSorter->aPoslist[i1];
  203672. }else{
  203673. *pn = sqlite3Fts5ExprPoslist(pCsr->pExpr, iPhrase, pa);
  203674. }
  203675. return rc;
  203676. }
  203677. /*
  203678. ** Ensure that the Fts5Cursor.nInstCount and aInst[] variables are populated
  203679. ** correctly for the current view. Return SQLITE_OK if successful, or an
  203680. ** SQLite error code otherwise.
  203681. */
  203682. static int fts5CacheInstArray(Fts5Cursor *pCsr){
  203683. int rc = SQLITE_OK;
  203684. Fts5PoslistReader *aIter; /* One iterator for each phrase */
  203685. int nIter; /* Number of iterators/phrases */
  203686. int nCol = ((Fts5Table*)pCsr->base.pVtab)->pConfig->nCol;
  203687. nIter = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
  203688. if( pCsr->aInstIter==0 ){
  203689. sqlite3_int64 nByte = sizeof(Fts5PoslistReader) * nIter;
  203690. pCsr->aInstIter = (Fts5PoslistReader*)sqlite3Fts5MallocZero(&rc, nByte);
  203691. }
  203692. aIter = pCsr->aInstIter;
  203693. if( aIter ){
  203694. int nInst = 0; /* Number instances seen so far */
  203695. int i;
  203696. /* Initialize all iterators */
  203697. for(i=0; i<nIter && rc==SQLITE_OK; i++){
  203698. const u8 *a;
  203699. int n;
  203700. rc = fts5CsrPoslist(pCsr, i, &a, &n);
  203701. if( rc==SQLITE_OK ){
  203702. sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]);
  203703. }
  203704. }
  203705. if( rc==SQLITE_OK ){
  203706. while( 1 ){
  203707. int *aInst;
  203708. int iBest = -1;
  203709. for(i=0; i<nIter; i++){
  203710. if( (aIter[i].bEof==0)
  203711. && (iBest<0 || aIter[i].iPos<aIter[iBest].iPos)
  203712. ){
  203713. iBest = i;
  203714. }
  203715. }
  203716. if( iBest<0 ) break;
  203717. nInst++;
  203718. if( nInst>=pCsr->nInstAlloc ){
  203719. pCsr->nInstAlloc = pCsr->nInstAlloc ? pCsr->nInstAlloc*2 : 32;
  203720. aInst = (int*)sqlite3_realloc64(
  203721. pCsr->aInst, pCsr->nInstAlloc*sizeof(int)*3
  203722. );
  203723. if( aInst ){
  203724. pCsr->aInst = aInst;
  203725. }else{
  203726. rc = SQLITE_NOMEM;
  203727. break;
  203728. }
  203729. }
  203730. aInst = &pCsr->aInst[3 * (nInst-1)];
  203731. aInst[0] = iBest;
  203732. aInst[1] = FTS5_POS2COLUMN(aIter[iBest].iPos);
  203733. aInst[2] = FTS5_POS2OFFSET(aIter[iBest].iPos);
  203734. if( aInst[1]<0 || aInst[1]>=nCol ){
  203735. rc = FTS5_CORRUPT;
  203736. break;
  203737. }
  203738. sqlite3Fts5PoslistReaderNext(&aIter[iBest]);
  203739. }
  203740. }
  203741. pCsr->nInstCount = nInst;
  203742. CsrFlagClear(pCsr, FTS5CSR_REQUIRE_INST);
  203743. }
  203744. return rc;
  203745. }
  203746. static int fts5ApiInstCount(Fts5Context *pCtx, int *pnInst){
  203747. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  203748. int rc = SQLITE_OK;
  203749. if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0
  203750. || SQLITE_OK==(rc = fts5CacheInstArray(pCsr)) ){
  203751. *pnInst = pCsr->nInstCount;
  203752. }
  203753. return rc;
  203754. }
  203755. static int fts5ApiInst(
  203756. Fts5Context *pCtx,
  203757. int iIdx,
  203758. int *piPhrase,
  203759. int *piCol,
  203760. int *piOff
  203761. ){
  203762. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  203763. int rc = SQLITE_OK;
  203764. if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0
  203765. || SQLITE_OK==(rc = fts5CacheInstArray(pCsr))
  203766. ){
  203767. if( iIdx<0 || iIdx>=pCsr->nInstCount ){
  203768. rc = SQLITE_RANGE;
  203769. #if 0
  203770. }else if( fts5IsOffsetless((Fts5Table*)pCsr->base.pVtab) ){
  203771. *piPhrase = pCsr->aInst[iIdx*3];
  203772. *piCol = pCsr->aInst[iIdx*3 + 2];
  203773. *piOff = -1;
  203774. #endif
  203775. }else{
  203776. *piPhrase = pCsr->aInst[iIdx*3];
  203777. *piCol = pCsr->aInst[iIdx*3 + 1];
  203778. *piOff = pCsr->aInst[iIdx*3 + 2];
  203779. }
  203780. }
  203781. return rc;
  203782. }
  203783. static sqlite3_int64 fts5ApiRowid(Fts5Context *pCtx){
  203784. return fts5CursorRowid((Fts5Cursor*)pCtx);
  203785. }
  203786. static int fts5ColumnSizeCb(
  203787. void *pContext, /* Pointer to int */
  203788. int tflags,
  203789. const char *pUnused, /* Buffer containing token */
  203790. int nUnused, /* Size of token in bytes */
  203791. int iUnused1, /* Start offset of token */
  203792. int iUnused2 /* End offset of token */
  203793. ){
  203794. int *pCnt = (int*)pContext;
  203795. UNUSED_PARAM2(pUnused, nUnused);
  203796. UNUSED_PARAM2(iUnused1, iUnused2);
  203797. if( (tflags & FTS5_TOKEN_COLOCATED)==0 ){
  203798. (*pCnt)++;
  203799. }
  203800. return SQLITE_OK;
  203801. }
  203802. static int fts5ApiColumnSize(Fts5Context *pCtx, int iCol, int *pnToken){
  203803. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  203804. Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);
  203805. Fts5Config *pConfig = pTab->p.pConfig;
  203806. int rc = SQLITE_OK;
  203807. if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_DOCSIZE) ){
  203808. if( pConfig->bColumnsize ){
  203809. i64 iRowid = fts5CursorRowid(pCsr);
  203810. rc = sqlite3Fts5StorageDocsize(pTab->pStorage, iRowid, pCsr->aColumnSize);
  203811. }else if( pConfig->zContent==0 ){
  203812. int i;
  203813. for(i=0; i<pConfig->nCol; i++){
  203814. if( pConfig->abUnindexed[i]==0 ){
  203815. pCsr->aColumnSize[i] = -1;
  203816. }
  203817. }
  203818. }else{
  203819. int i;
  203820. for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
  203821. if( pConfig->abUnindexed[i]==0 ){
  203822. const char *z; int n;
  203823. void *p = (void*)(&pCsr->aColumnSize[i]);
  203824. pCsr->aColumnSize[i] = 0;
  203825. rc = fts5ApiColumnText(pCtx, i, &z, &n);
  203826. if( rc==SQLITE_OK ){
  203827. rc = sqlite3Fts5Tokenize(
  203828. pConfig, FTS5_TOKENIZE_AUX, z, n, p, fts5ColumnSizeCb
  203829. );
  203830. }
  203831. }
  203832. }
  203833. }
  203834. CsrFlagClear(pCsr, FTS5CSR_REQUIRE_DOCSIZE);
  203835. }
  203836. if( iCol<0 ){
  203837. int i;
  203838. *pnToken = 0;
  203839. for(i=0; i<pConfig->nCol; i++){
  203840. *pnToken += pCsr->aColumnSize[i];
  203841. }
  203842. }else if( iCol<pConfig->nCol ){
  203843. *pnToken = pCsr->aColumnSize[iCol];
  203844. }else{
  203845. *pnToken = 0;
  203846. rc = SQLITE_RANGE;
  203847. }
  203848. return rc;
  203849. }
  203850. /*
  203851. ** Implementation of the xSetAuxdata() method.
  203852. */
  203853. static int fts5ApiSetAuxdata(
  203854. Fts5Context *pCtx, /* Fts5 context */
  203855. void *pPtr, /* Pointer to save as auxdata */
  203856. void(*xDelete)(void*) /* Destructor for pPtr (or NULL) */
  203857. ){
  203858. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  203859. Fts5Auxdata *pData;
  203860. /* Search through the cursors list of Fts5Auxdata objects for one that
  203861. ** corresponds to the currently executing auxiliary function. */
  203862. for(pData=pCsr->pAuxdata; pData; pData=pData->pNext){
  203863. if( pData->pAux==pCsr->pAux ) break;
  203864. }
  203865. if( pData ){
  203866. if( pData->xDelete ){
  203867. pData->xDelete(pData->pPtr);
  203868. }
  203869. }else{
  203870. int rc = SQLITE_OK;
  203871. pData = (Fts5Auxdata*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Auxdata));
  203872. if( pData==0 ){
  203873. if( xDelete ) xDelete(pPtr);
  203874. return rc;
  203875. }
  203876. pData->pAux = pCsr->pAux;
  203877. pData->pNext = pCsr->pAuxdata;
  203878. pCsr->pAuxdata = pData;
  203879. }
  203880. pData->xDelete = xDelete;
  203881. pData->pPtr = pPtr;
  203882. return SQLITE_OK;
  203883. }
  203884. static void *fts5ApiGetAuxdata(Fts5Context *pCtx, int bClear){
  203885. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  203886. Fts5Auxdata *pData;
  203887. void *pRet = 0;
  203888. for(pData=pCsr->pAuxdata; pData; pData=pData->pNext){
  203889. if( pData->pAux==pCsr->pAux ) break;
  203890. }
  203891. if( pData ){
  203892. pRet = pData->pPtr;
  203893. if( bClear ){
  203894. pData->pPtr = 0;
  203895. pData->xDelete = 0;
  203896. }
  203897. }
  203898. return pRet;
  203899. }
  203900. static void fts5ApiPhraseNext(
  203901. Fts5Context *pUnused,
  203902. Fts5PhraseIter *pIter,
  203903. int *piCol, int *piOff
  203904. ){
  203905. UNUSED_PARAM(pUnused);
  203906. if( pIter->a>=pIter->b ){
  203907. *piCol = -1;
  203908. *piOff = -1;
  203909. }else{
  203910. int iVal;
  203911. pIter->a += fts5GetVarint32(pIter->a, iVal);
  203912. if( iVal==1 ){
  203913. pIter->a += fts5GetVarint32(pIter->a, iVal);
  203914. *piCol = iVal;
  203915. *piOff = 0;
  203916. pIter->a += fts5GetVarint32(pIter->a, iVal);
  203917. }
  203918. *piOff += (iVal-2);
  203919. }
  203920. }
  203921. static int fts5ApiPhraseFirst(
  203922. Fts5Context *pCtx,
  203923. int iPhrase,
  203924. Fts5PhraseIter *pIter,
  203925. int *piCol, int *piOff
  203926. ){
  203927. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  203928. int n;
  203929. int rc = fts5CsrPoslist(pCsr, iPhrase, &pIter->a, &n);
  203930. if( rc==SQLITE_OK ){
  203931. pIter->b = &pIter->a[n];
  203932. *piCol = 0;
  203933. *piOff = 0;
  203934. fts5ApiPhraseNext(pCtx, pIter, piCol, piOff);
  203935. }
  203936. return rc;
  203937. }
  203938. static void fts5ApiPhraseNextColumn(
  203939. Fts5Context *pCtx,
  203940. Fts5PhraseIter *pIter,
  203941. int *piCol
  203942. ){
  203943. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  203944. Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
  203945. if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
  203946. if( pIter->a>=pIter->b ){
  203947. *piCol = -1;
  203948. }else{
  203949. int iIncr;
  203950. pIter->a += fts5GetVarint32(&pIter->a[0], iIncr);
  203951. *piCol += (iIncr-2);
  203952. }
  203953. }else{
  203954. while( 1 ){
  203955. int dummy;
  203956. if( pIter->a>=pIter->b ){
  203957. *piCol = -1;
  203958. return;
  203959. }
  203960. if( pIter->a[0]==0x01 ) break;
  203961. pIter->a += fts5GetVarint32(pIter->a, dummy);
  203962. }
  203963. pIter->a += 1 + fts5GetVarint32(&pIter->a[1], *piCol);
  203964. }
  203965. }
  203966. static int fts5ApiPhraseFirstColumn(
  203967. Fts5Context *pCtx,
  203968. int iPhrase,
  203969. Fts5PhraseIter *pIter,
  203970. int *piCol
  203971. ){
  203972. int rc = SQLITE_OK;
  203973. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  203974. Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
  203975. if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
  203976. Fts5Sorter *pSorter = pCsr->pSorter;
  203977. int n;
  203978. if( pSorter ){
  203979. int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]);
  203980. n = pSorter->aIdx[iPhrase] - i1;
  203981. pIter->a = &pSorter->aPoslist[i1];
  203982. }else{
  203983. rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, iPhrase, &pIter->a, &n);
  203984. }
  203985. if( rc==SQLITE_OK ){
  203986. pIter->b = &pIter->a[n];
  203987. *piCol = 0;
  203988. fts5ApiPhraseNextColumn(pCtx, pIter, piCol);
  203989. }
  203990. }else{
  203991. int n;
  203992. rc = fts5CsrPoslist(pCsr, iPhrase, &pIter->a, &n);
  203993. if( rc==SQLITE_OK ){
  203994. pIter->b = &pIter->a[n];
  203995. if( n<=0 ){
  203996. *piCol = -1;
  203997. }else if( pIter->a[0]==0x01 ){
  203998. pIter->a += 1 + fts5GetVarint32(&pIter->a[1], *piCol);
  203999. }else{
  204000. *piCol = 0;
  204001. }
  204002. }
  204003. }
  204004. return rc;
  204005. }
  204006. static int fts5ApiQueryPhrase(Fts5Context*, int, void*,
  204007. int(*)(const Fts5ExtensionApi*, Fts5Context*, void*)
  204008. );
  204009. static const Fts5ExtensionApi sFts5Api = {
  204010. 2, /* iVersion */
  204011. fts5ApiUserData,
  204012. fts5ApiColumnCount,
  204013. fts5ApiRowCount,
  204014. fts5ApiColumnTotalSize,
  204015. fts5ApiTokenize,
  204016. fts5ApiPhraseCount,
  204017. fts5ApiPhraseSize,
  204018. fts5ApiInstCount,
  204019. fts5ApiInst,
  204020. fts5ApiRowid,
  204021. fts5ApiColumnText,
  204022. fts5ApiColumnSize,
  204023. fts5ApiQueryPhrase,
  204024. fts5ApiSetAuxdata,
  204025. fts5ApiGetAuxdata,
  204026. fts5ApiPhraseFirst,
  204027. fts5ApiPhraseNext,
  204028. fts5ApiPhraseFirstColumn,
  204029. fts5ApiPhraseNextColumn,
  204030. };
  204031. /*
  204032. ** Implementation of API function xQueryPhrase().
  204033. */
  204034. static int fts5ApiQueryPhrase(
  204035. Fts5Context *pCtx,
  204036. int iPhrase,
  204037. void *pUserData,
  204038. int(*xCallback)(const Fts5ExtensionApi*, Fts5Context*, void*)
  204039. ){
  204040. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  204041. Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);
  204042. int rc;
  204043. Fts5Cursor *pNew = 0;
  204044. rc = fts5OpenMethod(pCsr->base.pVtab, (sqlite3_vtab_cursor**)&pNew);
  204045. if( rc==SQLITE_OK ){
  204046. pNew->ePlan = FTS5_PLAN_MATCH;
  204047. pNew->iFirstRowid = SMALLEST_INT64;
  204048. pNew->iLastRowid = LARGEST_INT64;
  204049. pNew->base.pVtab = (sqlite3_vtab*)pTab;
  204050. rc = sqlite3Fts5ExprClonePhrase(pCsr->pExpr, iPhrase, &pNew->pExpr);
  204051. }
  204052. if( rc==SQLITE_OK ){
  204053. for(rc = fts5CursorFirst(pTab, pNew, 0);
  204054. rc==SQLITE_OK && CsrFlagTest(pNew, FTS5CSR_EOF)==0;
  204055. rc = fts5NextMethod((sqlite3_vtab_cursor*)pNew)
  204056. ){
  204057. rc = xCallback(&sFts5Api, (Fts5Context*)pNew, pUserData);
  204058. if( rc!=SQLITE_OK ){
  204059. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  204060. break;
  204061. }
  204062. }
  204063. }
  204064. fts5CloseMethod((sqlite3_vtab_cursor*)pNew);
  204065. return rc;
  204066. }
  204067. static void fts5ApiInvoke(
  204068. Fts5Auxiliary *pAux,
  204069. Fts5Cursor *pCsr,
  204070. sqlite3_context *context,
  204071. int argc,
  204072. sqlite3_value **argv
  204073. ){
  204074. assert( pCsr->pAux==0 );
  204075. pCsr->pAux = pAux;
  204076. pAux->xFunc(&sFts5Api, (Fts5Context*)pCsr, context, argc, argv);
  204077. pCsr->pAux = 0;
  204078. }
  204079. static Fts5Cursor *fts5CursorFromCsrid(Fts5Global *pGlobal, i64 iCsrId){
  204080. Fts5Cursor *pCsr;
  204081. for(pCsr=pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
  204082. if( pCsr->iCsrId==iCsrId ) break;
  204083. }
  204084. return pCsr;
  204085. }
  204086. static void fts5ApiCallback(
  204087. sqlite3_context *context,
  204088. int argc,
  204089. sqlite3_value **argv
  204090. ){
  204091. Fts5Auxiliary *pAux;
  204092. Fts5Cursor *pCsr;
  204093. i64 iCsrId;
  204094. assert( argc>=1 );
  204095. pAux = (Fts5Auxiliary*)sqlite3_user_data(context);
  204096. iCsrId = sqlite3_value_int64(argv[0]);
  204097. pCsr = fts5CursorFromCsrid(pAux->pGlobal, iCsrId);
  204098. if( pCsr==0 ){
  204099. char *zErr = sqlite3_mprintf("no such cursor: %lld", iCsrId);
  204100. sqlite3_result_error(context, zErr, -1);
  204101. sqlite3_free(zErr);
  204102. }else{
  204103. fts5ApiInvoke(pAux, pCsr, context, argc-1, &argv[1]);
  204104. }
  204105. }
  204106. /*
  204107. ** Given cursor id iId, return a pointer to the corresponding Fts5Table
  204108. ** object. Or NULL If the cursor id does not exist.
  204109. */
  204110. static Fts5Table *sqlite3Fts5TableFromCsrid(
  204111. Fts5Global *pGlobal, /* FTS5 global context for db handle */
  204112. i64 iCsrId /* Id of cursor to find */
  204113. ){
  204114. Fts5Cursor *pCsr;
  204115. pCsr = fts5CursorFromCsrid(pGlobal, iCsrId);
  204116. if( pCsr ){
  204117. return (Fts5Table*)pCsr->base.pVtab;
  204118. }
  204119. return 0;
  204120. }
  204121. /*
  204122. ** Return a "position-list blob" corresponding to the current position of
  204123. ** cursor pCsr via sqlite3_result_blob(). A position-list blob contains
  204124. ** the current position-list for each phrase in the query associated with
  204125. ** cursor pCsr.
  204126. **
  204127. ** A position-list blob begins with (nPhrase-1) varints, where nPhrase is
  204128. ** the number of phrases in the query. Following the varints are the
  204129. ** concatenated position lists for each phrase, in order.
  204130. **
  204131. ** The first varint (if it exists) contains the size of the position list
  204132. ** for phrase 0. The second (same disclaimer) contains the size of position
  204133. ** list 1. And so on. There is no size field for the final position list,
  204134. ** as it can be derived from the total size of the blob.
  204135. */
  204136. static int fts5PoslistBlob(sqlite3_context *pCtx, Fts5Cursor *pCsr){
  204137. int i;
  204138. int rc = SQLITE_OK;
  204139. int nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
  204140. Fts5Buffer val;
  204141. memset(&val, 0, sizeof(Fts5Buffer));
  204142. switch( ((Fts5Table*)(pCsr->base.pVtab))->pConfig->eDetail ){
  204143. case FTS5_DETAIL_FULL:
  204144. /* Append the varints */
  204145. for(i=0; i<(nPhrase-1); i++){
  204146. const u8 *dummy;
  204147. int nByte = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &dummy);
  204148. sqlite3Fts5BufferAppendVarint(&rc, &val, nByte);
  204149. }
  204150. /* Append the position lists */
  204151. for(i=0; i<nPhrase; i++){
  204152. const u8 *pPoslist;
  204153. int nPoslist;
  204154. nPoslist = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &pPoslist);
  204155. sqlite3Fts5BufferAppendBlob(&rc, &val, nPoslist, pPoslist);
  204156. }
  204157. break;
  204158. case FTS5_DETAIL_COLUMNS:
  204159. /* Append the varints */
  204160. for(i=0; rc==SQLITE_OK && i<(nPhrase-1); i++){
  204161. const u8 *dummy;
  204162. int nByte;
  204163. rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, i, &dummy, &nByte);
  204164. sqlite3Fts5BufferAppendVarint(&rc, &val, nByte);
  204165. }
  204166. /* Append the position lists */
  204167. for(i=0; rc==SQLITE_OK && i<nPhrase; i++){
  204168. const u8 *pPoslist;
  204169. int nPoslist;
  204170. rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, i, &pPoslist, &nPoslist);
  204171. sqlite3Fts5BufferAppendBlob(&rc, &val, nPoslist, pPoslist);
  204172. }
  204173. break;
  204174. default:
  204175. break;
  204176. }
  204177. sqlite3_result_blob(pCtx, val.p, val.n, sqlite3_free);
  204178. return rc;
  204179. }
  204180. /*
  204181. ** This is the xColumn method, called by SQLite to request a value from
  204182. ** the row that the supplied cursor currently points to.
  204183. */
  204184. static int fts5ColumnMethod(
  204185. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  204186. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  204187. int iCol /* Index of column to read value from */
  204188. ){
  204189. Fts5FullTable *pTab = (Fts5FullTable*)(pCursor->pVtab);
  204190. Fts5Config *pConfig = pTab->p.pConfig;
  204191. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  204192. int rc = SQLITE_OK;
  204193. assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 );
  204194. if( pCsr->ePlan==FTS5_PLAN_SPECIAL ){
  204195. if( iCol==pConfig->nCol ){
  204196. sqlite3_result_int64(pCtx, pCsr->iSpecial);
  204197. }
  204198. }else
  204199. if( iCol==pConfig->nCol ){
  204200. /* User is requesting the value of the special column with the same name
  204201. ** as the table. Return the cursor integer id number. This value is only
  204202. ** useful in that it may be passed as the first argument to an FTS5
  204203. ** auxiliary function. */
  204204. sqlite3_result_int64(pCtx, pCsr->iCsrId);
  204205. }else if( iCol==pConfig->nCol+1 ){
  204206. /* The value of the "rank" column. */
  204207. if( pCsr->ePlan==FTS5_PLAN_SOURCE ){
  204208. fts5PoslistBlob(pCtx, pCsr);
  204209. }else if(
  204210. pCsr->ePlan==FTS5_PLAN_MATCH
  204211. || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH
  204212. ){
  204213. if( pCsr->pRank || SQLITE_OK==(rc = fts5FindRankFunction(pCsr)) ){
  204214. fts5ApiInvoke(pCsr->pRank, pCsr, pCtx, pCsr->nRankArg, pCsr->apRankArg);
  204215. }
  204216. }
  204217. }else if( !fts5IsContentless(pTab) ){
  204218. rc = fts5SeekCursor(pCsr, 1);
  204219. if( rc==SQLITE_OK ){
  204220. sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
  204221. }
  204222. }
  204223. return rc;
  204224. }
  204225. /*
  204226. ** This routine implements the xFindFunction method for the FTS3
  204227. ** virtual table.
  204228. */
  204229. static int fts5FindFunctionMethod(
  204230. sqlite3_vtab *pVtab, /* Virtual table handle */
  204231. int nUnused, /* Number of SQL function arguments */
  204232. const char *zName, /* Name of SQL function */
  204233. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
  204234. void **ppArg /* OUT: User data for *pxFunc */
  204235. ){
  204236. Fts5FullTable *pTab = (Fts5FullTable*)pVtab;
  204237. Fts5Auxiliary *pAux;
  204238. UNUSED_PARAM(nUnused);
  204239. pAux = fts5FindAuxiliary(pTab, zName);
  204240. if( pAux ){
  204241. *pxFunc = fts5ApiCallback;
  204242. *ppArg = (void*)pAux;
  204243. return 1;
  204244. }
  204245. /* No function of the specified name was found. Return 0. */
  204246. return 0;
  204247. }
  204248. /*
  204249. ** Implementation of FTS5 xRename method. Rename an fts5 table.
  204250. */
  204251. static int fts5RenameMethod(
  204252. sqlite3_vtab *pVtab, /* Virtual table handle */
  204253. const char *zName /* New name of table */
  204254. ){
  204255. Fts5FullTable *pTab = (Fts5FullTable*)pVtab;
  204256. return sqlite3Fts5StorageRename(pTab->pStorage, zName);
  204257. }
  204258. static int sqlite3Fts5FlushToDisk(Fts5Table *pTab){
  204259. fts5TripCursors((Fts5FullTable*)pTab);
  204260. return sqlite3Fts5StorageSync(((Fts5FullTable*)pTab)->pStorage);
  204261. }
  204262. /*
  204263. ** The xSavepoint() method.
  204264. **
  204265. ** Flush the contents of the pending-terms table to disk.
  204266. */
  204267. static int fts5SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
  204268. UNUSED_PARAM(iSavepoint); /* Call below is a no-op for NDEBUG builds */
  204269. fts5CheckTransactionState((Fts5FullTable*)pVtab, FTS5_SAVEPOINT, iSavepoint);
  204270. return sqlite3Fts5FlushToDisk((Fts5Table*)pVtab);
  204271. }
  204272. /*
  204273. ** The xRelease() method.
  204274. **
  204275. ** This is a no-op.
  204276. */
  204277. static int fts5ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
  204278. UNUSED_PARAM(iSavepoint); /* Call below is a no-op for NDEBUG builds */
  204279. fts5CheckTransactionState((Fts5FullTable*)pVtab, FTS5_RELEASE, iSavepoint);
  204280. return sqlite3Fts5FlushToDisk((Fts5Table*)pVtab);
  204281. }
  204282. /*
  204283. ** The xRollbackTo() method.
  204284. **
  204285. ** Discard the contents of the pending terms table.
  204286. */
  204287. static int fts5RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
  204288. Fts5FullTable *pTab = (Fts5FullTable*)pVtab;
  204289. UNUSED_PARAM(iSavepoint); /* Call below is a no-op for NDEBUG builds */
  204290. fts5CheckTransactionState(pTab, FTS5_ROLLBACKTO, iSavepoint);
  204291. fts5TripCursors(pTab);
  204292. return sqlite3Fts5StorageRollback(pTab->pStorage);
  204293. }
  204294. /*
  204295. ** Register a new auxiliary function with global context pGlobal.
  204296. */
  204297. static int fts5CreateAux(
  204298. fts5_api *pApi, /* Global context (one per db handle) */
  204299. const char *zName, /* Name of new function */
  204300. void *pUserData, /* User data for aux. function */
  204301. fts5_extension_function xFunc, /* Aux. function implementation */
  204302. void(*xDestroy)(void*) /* Destructor for pUserData */
  204303. ){
  204304. Fts5Global *pGlobal = (Fts5Global*)pApi;
  204305. int rc = sqlite3_overload_function(pGlobal->db, zName, -1);
  204306. if( rc==SQLITE_OK ){
  204307. Fts5Auxiliary *pAux;
  204308. sqlite3_int64 nName; /* Size of zName in bytes, including \0 */
  204309. sqlite3_int64 nByte; /* Bytes of space to allocate */
  204310. nName = strlen(zName) + 1;
  204311. nByte = sizeof(Fts5Auxiliary) + nName;
  204312. pAux = (Fts5Auxiliary*)sqlite3_malloc64(nByte);
  204313. if( pAux ){
  204314. memset(pAux, 0, (size_t)nByte);
  204315. pAux->zFunc = (char*)&pAux[1];
  204316. memcpy(pAux->zFunc, zName, nName);
  204317. pAux->pGlobal = pGlobal;
  204318. pAux->pUserData = pUserData;
  204319. pAux->xFunc = xFunc;
  204320. pAux->xDestroy = xDestroy;
  204321. pAux->pNext = pGlobal->pAux;
  204322. pGlobal->pAux = pAux;
  204323. }else{
  204324. rc = SQLITE_NOMEM;
  204325. }
  204326. }
  204327. return rc;
  204328. }
  204329. /*
  204330. ** Register a new tokenizer. This is the implementation of the
  204331. ** fts5_api.xCreateTokenizer() method.
  204332. */
  204333. static int fts5CreateTokenizer(
  204334. fts5_api *pApi, /* Global context (one per db handle) */
  204335. const char *zName, /* Name of new function */
  204336. void *pUserData, /* User data for aux. function */
  204337. fts5_tokenizer *pTokenizer, /* Tokenizer implementation */
  204338. void(*xDestroy)(void*) /* Destructor for pUserData */
  204339. ){
  204340. Fts5Global *pGlobal = (Fts5Global*)pApi;
  204341. Fts5TokenizerModule *pNew;
  204342. sqlite3_int64 nName; /* Size of zName and its \0 terminator */
  204343. sqlite3_int64 nByte; /* Bytes of space to allocate */
  204344. int rc = SQLITE_OK;
  204345. nName = strlen(zName) + 1;
  204346. nByte = sizeof(Fts5TokenizerModule) + nName;
  204347. pNew = (Fts5TokenizerModule*)sqlite3_malloc64(nByte);
  204348. if( pNew ){
  204349. memset(pNew, 0, (size_t)nByte);
  204350. pNew->zName = (char*)&pNew[1];
  204351. memcpy(pNew->zName, zName, nName);
  204352. pNew->pUserData = pUserData;
  204353. pNew->x = *pTokenizer;
  204354. pNew->xDestroy = xDestroy;
  204355. pNew->pNext = pGlobal->pTok;
  204356. pGlobal->pTok = pNew;
  204357. if( pNew->pNext==0 ){
  204358. pGlobal->pDfltTok = pNew;
  204359. }
  204360. }else{
  204361. rc = SQLITE_NOMEM;
  204362. }
  204363. return rc;
  204364. }
  204365. static Fts5TokenizerModule *fts5LocateTokenizer(
  204366. Fts5Global *pGlobal,
  204367. const char *zName
  204368. ){
  204369. Fts5TokenizerModule *pMod = 0;
  204370. if( zName==0 ){
  204371. pMod = pGlobal->pDfltTok;
  204372. }else{
  204373. for(pMod=pGlobal->pTok; pMod; pMod=pMod->pNext){
  204374. if( sqlite3_stricmp(zName, pMod->zName)==0 ) break;
  204375. }
  204376. }
  204377. return pMod;
  204378. }
  204379. /*
  204380. ** Find a tokenizer. This is the implementation of the
  204381. ** fts5_api.xFindTokenizer() method.
  204382. */
  204383. static int fts5FindTokenizer(
  204384. fts5_api *pApi, /* Global context (one per db handle) */
  204385. const char *zName, /* Name of new function */
  204386. void **ppUserData,
  204387. fts5_tokenizer *pTokenizer /* Populate this object */
  204388. ){
  204389. int rc = SQLITE_OK;
  204390. Fts5TokenizerModule *pMod;
  204391. pMod = fts5LocateTokenizer((Fts5Global*)pApi, zName);
  204392. if( pMod ){
  204393. *pTokenizer = pMod->x;
  204394. *ppUserData = pMod->pUserData;
  204395. }else{
  204396. memset(pTokenizer, 0, sizeof(fts5_tokenizer));
  204397. rc = SQLITE_ERROR;
  204398. }
  204399. return rc;
  204400. }
  204401. static int sqlite3Fts5GetTokenizer(
  204402. Fts5Global *pGlobal,
  204403. const char **azArg,
  204404. int nArg,
  204405. Fts5Tokenizer **ppTok,
  204406. fts5_tokenizer **ppTokApi,
  204407. char **pzErr
  204408. ){
  204409. Fts5TokenizerModule *pMod;
  204410. int rc = SQLITE_OK;
  204411. pMod = fts5LocateTokenizer(pGlobal, nArg==0 ? 0 : azArg[0]);
  204412. if( pMod==0 ){
  204413. assert( nArg>0 );
  204414. rc = SQLITE_ERROR;
  204415. *pzErr = sqlite3_mprintf("no such tokenizer: %s", azArg[0]);
  204416. }else{
  204417. rc = pMod->x.xCreate(pMod->pUserData, &azArg[1], (nArg?nArg-1:0), ppTok);
  204418. *ppTokApi = &pMod->x;
  204419. if( rc!=SQLITE_OK && pzErr ){
  204420. *pzErr = sqlite3_mprintf("error in tokenizer constructor");
  204421. }
  204422. }
  204423. if( rc!=SQLITE_OK ){
  204424. *ppTokApi = 0;
  204425. *ppTok = 0;
  204426. }
  204427. return rc;
  204428. }
  204429. static void fts5ModuleDestroy(void *pCtx){
  204430. Fts5TokenizerModule *pTok, *pNextTok;
  204431. Fts5Auxiliary *pAux, *pNextAux;
  204432. Fts5Global *pGlobal = (Fts5Global*)pCtx;
  204433. for(pAux=pGlobal->pAux; pAux; pAux=pNextAux){
  204434. pNextAux = pAux->pNext;
  204435. if( pAux->xDestroy ) pAux->xDestroy(pAux->pUserData);
  204436. sqlite3_free(pAux);
  204437. }
  204438. for(pTok=pGlobal->pTok; pTok; pTok=pNextTok){
  204439. pNextTok = pTok->pNext;
  204440. if( pTok->xDestroy ) pTok->xDestroy(pTok->pUserData);
  204441. sqlite3_free(pTok);
  204442. }
  204443. sqlite3_free(pGlobal);
  204444. }
  204445. static void fts5Fts5Func(
  204446. sqlite3_context *pCtx, /* Function call context */
  204447. int nArg, /* Number of args */
  204448. sqlite3_value **apArg /* Function arguments */
  204449. ){
  204450. Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx);
  204451. fts5_api **ppApi;
  204452. UNUSED_PARAM(nArg);
  204453. assert( nArg==1 );
  204454. ppApi = (fts5_api**)sqlite3_value_pointer(apArg[0], "fts5_api_ptr");
  204455. if( ppApi ) *ppApi = &pGlobal->api;
  204456. }
  204457. /*
  204458. ** Implementation of fts5_source_id() function.
  204459. */
  204460. static void fts5SourceIdFunc(
  204461. sqlite3_context *pCtx, /* Function call context */
  204462. int nArg, /* Number of args */
  204463. sqlite3_value **apUnused /* Function arguments */
  204464. ){
  204465. assert( nArg==0 );
  204466. UNUSED_PARAM2(nArg, apUnused);
  204467. sqlite3_result_text(pCtx, "fts5: 2019-07-10 17:32:03 fc82b73eaac8b36950e527f12c4b5dc1e147e6f4ad2217ae43ad82882a88bfa6", -1, SQLITE_TRANSIENT);
  204468. }
  204469. /*
  204470. ** Return true if zName is the extension on one of the shadow tables used
  204471. ** by this module.
  204472. */
  204473. static int fts5ShadowName(const char *zName){
  204474. static const char *azName[] = {
  204475. "config", "content", "data", "docsize", "idx"
  204476. };
  204477. unsigned int i;
  204478. for(i=0; i<sizeof(azName)/sizeof(azName[0]); i++){
  204479. if( sqlite3_stricmp(zName, azName[i])==0 ) return 1;
  204480. }
  204481. return 0;
  204482. }
  204483. static int fts5Init(sqlite3 *db){
  204484. static const sqlite3_module fts5Mod = {
  204485. /* iVersion */ 3,
  204486. /* xCreate */ fts5CreateMethod,
  204487. /* xConnect */ fts5ConnectMethod,
  204488. /* xBestIndex */ fts5BestIndexMethod,
  204489. /* xDisconnect */ fts5DisconnectMethod,
  204490. /* xDestroy */ fts5DestroyMethod,
  204491. /* xOpen */ fts5OpenMethod,
  204492. /* xClose */ fts5CloseMethod,
  204493. /* xFilter */ fts5FilterMethod,
  204494. /* xNext */ fts5NextMethod,
  204495. /* xEof */ fts5EofMethod,
  204496. /* xColumn */ fts5ColumnMethod,
  204497. /* xRowid */ fts5RowidMethod,
  204498. /* xUpdate */ fts5UpdateMethod,
  204499. /* xBegin */ fts5BeginMethod,
  204500. /* xSync */ fts5SyncMethod,
  204501. /* xCommit */ fts5CommitMethod,
  204502. /* xRollback */ fts5RollbackMethod,
  204503. /* xFindFunction */ fts5FindFunctionMethod,
  204504. /* xRename */ fts5RenameMethod,
  204505. /* xSavepoint */ fts5SavepointMethod,
  204506. /* xRelease */ fts5ReleaseMethod,
  204507. /* xRollbackTo */ fts5RollbackToMethod,
  204508. /* xShadowName */ fts5ShadowName
  204509. };
  204510. int rc;
  204511. Fts5Global *pGlobal = 0;
  204512. pGlobal = (Fts5Global*)sqlite3_malloc(sizeof(Fts5Global));
  204513. if( pGlobal==0 ){
  204514. rc = SQLITE_NOMEM;
  204515. }else{
  204516. void *p = (void*)pGlobal;
  204517. memset(pGlobal, 0, sizeof(Fts5Global));
  204518. pGlobal->db = db;
  204519. pGlobal->api.iVersion = 2;
  204520. pGlobal->api.xCreateFunction = fts5CreateAux;
  204521. pGlobal->api.xCreateTokenizer = fts5CreateTokenizer;
  204522. pGlobal->api.xFindTokenizer = fts5FindTokenizer;
  204523. rc = sqlite3_create_module_v2(db, "fts5", &fts5Mod, p, fts5ModuleDestroy);
  204524. if( rc==SQLITE_OK ) rc = sqlite3Fts5IndexInit(db);
  204525. if( rc==SQLITE_OK ) rc = sqlite3Fts5ExprInit(pGlobal, db);
  204526. if( rc==SQLITE_OK ) rc = sqlite3Fts5AuxInit(&pGlobal->api);
  204527. if( rc==SQLITE_OK ) rc = sqlite3Fts5TokenizerInit(&pGlobal->api);
  204528. if( rc==SQLITE_OK ) rc = sqlite3Fts5VocabInit(pGlobal, db);
  204529. if( rc==SQLITE_OK ){
  204530. rc = sqlite3_create_function(
  204531. db, "fts5", 1, SQLITE_UTF8, p, fts5Fts5Func, 0, 0
  204532. );
  204533. }
  204534. if( rc==SQLITE_OK ){
  204535. rc = sqlite3_create_function(
  204536. db, "fts5_source_id", 0, SQLITE_UTF8, p, fts5SourceIdFunc, 0, 0
  204537. );
  204538. }
  204539. }
  204540. /* If SQLITE_FTS5_ENABLE_TEST_MI is defined, assume that the file
  204541. ** fts5_test_mi.c is compiled and linked into the executable. And call
  204542. ** its entry point to enable the matchinfo() demo. */
  204543. #ifdef SQLITE_FTS5_ENABLE_TEST_MI
  204544. if( rc==SQLITE_OK ){
  204545. extern int sqlite3Fts5TestRegisterMatchinfo(sqlite3*);
  204546. rc = sqlite3Fts5TestRegisterMatchinfo(db);
  204547. }
  204548. #endif
  204549. return rc;
  204550. }
  204551. /*
  204552. ** The following functions are used to register the module with SQLite. If
  204553. ** this module is being built as part of the SQLite core (SQLITE_CORE is
  204554. ** defined), then sqlite3_open() will call sqlite3Fts5Init() directly.
  204555. **
  204556. ** Or, if this module is being built as a loadable extension,
  204557. ** sqlite3Fts5Init() is omitted and the two standard entry points
  204558. ** sqlite3_fts_init() and sqlite3_fts5_init() defined instead.
  204559. */
  204560. #ifndef SQLITE_CORE
  204561. #ifdef _WIN32
  204562. __declspec(dllexport)
  204563. #endif
  204564. SQLITE_API int sqlite3_fts_init(
  204565. sqlite3 *db,
  204566. char **pzErrMsg,
  204567. const sqlite3_api_routines *pApi
  204568. ){
  204569. SQLITE_EXTENSION_INIT2(pApi);
  204570. (void)pzErrMsg; /* Unused parameter */
  204571. return fts5Init(db);
  204572. }
  204573. #ifdef _WIN32
  204574. __declspec(dllexport)
  204575. #endif
  204576. SQLITE_API int sqlite3_fts5_init(
  204577. sqlite3 *db,
  204578. char **pzErrMsg,
  204579. const sqlite3_api_routines *pApi
  204580. ){
  204581. SQLITE_EXTENSION_INIT2(pApi);
  204582. (void)pzErrMsg; /* Unused parameter */
  204583. return fts5Init(db);
  204584. }
  204585. #else
  204586. SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3 *db){
  204587. return fts5Init(db);
  204588. }
  204589. #endif
  204590. /*
  204591. ** 2014 May 31
  204592. **
  204593. ** The author disclaims copyright to this source code. In place of
  204594. ** a legal notice, here is a blessing:
  204595. **
  204596. ** May you do good and not evil.
  204597. ** May you find forgiveness for yourself and forgive others.
  204598. ** May you share freely, never taking more than you give.
  204599. **
  204600. ******************************************************************************
  204601. **
  204602. */
  204603. /* #include "fts5Int.h" */
  204604. struct Fts5Storage {
  204605. Fts5Config *pConfig;
  204606. Fts5Index *pIndex;
  204607. int bTotalsValid; /* True if nTotalRow/aTotalSize[] are valid */
  204608. i64 nTotalRow; /* Total number of rows in FTS table */
  204609. i64 *aTotalSize; /* Total sizes of each column */
  204610. sqlite3_stmt *aStmt[11];
  204611. };
  204612. #if FTS5_STMT_SCAN_ASC!=0
  204613. # error "FTS5_STMT_SCAN_ASC mismatch"
  204614. #endif
  204615. #if FTS5_STMT_SCAN_DESC!=1
  204616. # error "FTS5_STMT_SCAN_DESC mismatch"
  204617. #endif
  204618. #if FTS5_STMT_LOOKUP!=2
  204619. # error "FTS5_STMT_LOOKUP mismatch"
  204620. #endif
  204621. #define FTS5_STMT_INSERT_CONTENT 3
  204622. #define FTS5_STMT_REPLACE_CONTENT 4
  204623. #define FTS5_STMT_DELETE_CONTENT 5
  204624. #define FTS5_STMT_REPLACE_DOCSIZE 6
  204625. #define FTS5_STMT_DELETE_DOCSIZE 7
  204626. #define FTS5_STMT_LOOKUP_DOCSIZE 8
  204627. #define FTS5_STMT_REPLACE_CONFIG 9
  204628. #define FTS5_STMT_SCAN 10
  204629. /*
  204630. ** Prepare the two insert statements - Fts5Storage.pInsertContent and
  204631. ** Fts5Storage.pInsertDocsize - if they have not already been prepared.
  204632. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  204633. ** occurs.
  204634. */
  204635. static int fts5StorageGetStmt(
  204636. Fts5Storage *p, /* Storage handle */
  204637. int eStmt, /* FTS5_STMT_XXX constant */
  204638. sqlite3_stmt **ppStmt, /* OUT: Prepared statement handle */
  204639. char **pzErrMsg /* OUT: Error message (if any) */
  204640. ){
  204641. int rc = SQLITE_OK;
  204642. /* If there is no %_docsize table, there should be no requests for
  204643. ** statements to operate on it. */
  204644. assert( p->pConfig->bColumnsize || (
  204645. eStmt!=FTS5_STMT_REPLACE_DOCSIZE
  204646. && eStmt!=FTS5_STMT_DELETE_DOCSIZE
  204647. && eStmt!=FTS5_STMT_LOOKUP_DOCSIZE
  204648. ));
  204649. assert( eStmt>=0 && eStmt<ArraySize(p->aStmt) );
  204650. if( p->aStmt[eStmt]==0 ){
  204651. const char *azStmt[] = {
  204652. "SELECT %s FROM %s T WHERE T.%Q >= ? AND T.%Q <= ? ORDER BY T.%Q ASC",
  204653. "SELECT %s FROM %s T WHERE T.%Q <= ? AND T.%Q >= ? ORDER BY T.%Q DESC",
  204654. "SELECT %s FROM %s T WHERE T.%Q=?", /* LOOKUP */
  204655. "INSERT INTO %Q.'%q_content' VALUES(%s)", /* INSERT_CONTENT */
  204656. "REPLACE INTO %Q.'%q_content' VALUES(%s)", /* REPLACE_CONTENT */
  204657. "DELETE FROM %Q.'%q_content' WHERE id=?", /* DELETE_CONTENT */
  204658. "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)", /* REPLACE_DOCSIZE */
  204659. "DELETE FROM %Q.'%q_docsize' WHERE id=?", /* DELETE_DOCSIZE */
  204660. "SELECT sz FROM %Q.'%q_docsize' WHERE id=?", /* LOOKUP_DOCSIZE */
  204661. "REPLACE INTO %Q.'%q_config' VALUES(?,?)", /* REPLACE_CONFIG */
  204662. "SELECT %s FROM %s AS T", /* SCAN */
  204663. };
  204664. Fts5Config *pC = p->pConfig;
  204665. char *zSql = 0;
  204666. switch( eStmt ){
  204667. case FTS5_STMT_SCAN:
  204668. zSql = sqlite3_mprintf(azStmt[eStmt],
  204669. pC->zContentExprlist, pC->zContent
  204670. );
  204671. break;
  204672. case FTS5_STMT_SCAN_ASC:
  204673. case FTS5_STMT_SCAN_DESC:
  204674. zSql = sqlite3_mprintf(azStmt[eStmt], pC->zContentExprlist,
  204675. pC->zContent, pC->zContentRowid, pC->zContentRowid,
  204676. pC->zContentRowid
  204677. );
  204678. break;
  204679. case FTS5_STMT_LOOKUP:
  204680. zSql = sqlite3_mprintf(azStmt[eStmt],
  204681. pC->zContentExprlist, pC->zContent, pC->zContentRowid
  204682. );
  204683. break;
  204684. case FTS5_STMT_INSERT_CONTENT:
  204685. case FTS5_STMT_REPLACE_CONTENT: {
  204686. int nCol = pC->nCol + 1;
  204687. char *zBind;
  204688. int i;
  204689. zBind = sqlite3_malloc64(1 + nCol*2);
  204690. if( zBind ){
  204691. for(i=0; i<nCol; i++){
  204692. zBind[i*2] = '?';
  204693. zBind[i*2 + 1] = ',';
  204694. }
  204695. zBind[i*2-1] = '\0';
  204696. zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName, zBind);
  204697. sqlite3_free(zBind);
  204698. }
  204699. break;
  204700. }
  204701. default:
  204702. zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName);
  204703. break;
  204704. }
  204705. if( zSql==0 ){
  204706. rc = SQLITE_NOMEM;
  204707. }else{
  204708. int f = SQLITE_PREPARE_PERSISTENT;
  204709. if( eStmt>FTS5_STMT_LOOKUP ) f |= SQLITE_PREPARE_NO_VTAB;
  204710. rc = sqlite3_prepare_v3(pC->db, zSql, -1, f, &p->aStmt[eStmt], 0);
  204711. sqlite3_free(zSql);
  204712. if( rc!=SQLITE_OK && pzErrMsg ){
  204713. *pzErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pC->db));
  204714. }
  204715. }
  204716. }
  204717. *ppStmt = p->aStmt[eStmt];
  204718. sqlite3_reset(*ppStmt);
  204719. return rc;
  204720. }
  204721. static int fts5ExecPrintf(
  204722. sqlite3 *db,
  204723. char **pzErr,
  204724. const char *zFormat,
  204725. ...
  204726. ){
  204727. int rc;
  204728. va_list ap; /* ... printf arguments */
  204729. char *zSql;
  204730. va_start(ap, zFormat);
  204731. zSql = sqlite3_vmprintf(zFormat, ap);
  204732. if( zSql==0 ){
  204733. rc = SQLITE_NOMEM;
  204734. }else{
  204735. rc = sqlite3_exec(db, zSql, 0, 0, pzErr);
  204736. sqlite3_free(zSql);
  204737. }
  204738. va_end(ap);
  204739. return rc;
  204740. }
  204741. /*
  204742. ** Drop all shadow tables. Return SQLITE_OK if successful or an SQLite error
  204743. ** code otherwise.
  204744. */
  204745. static int sqlite3Fts5DropAll(Fts5Config *pConfig){
  204746. int rc = fts5ExecPrintf(pConfig->db, 0,
  204747. "DROP TABLE IF EXISTS %Q.'%q_data';"
  204748. "DROP TABLE IF EXISTS %Q.'%q_idx';"
  204749. "DROP TABLE IF EXISTS %Q.'%q_config';",
  204750. pConfig->zDb, pConfig->zName,
  204751. pConfig->zDb, pConfig->zName,
  204752. pConfig->zDb, pConfig->zName
  204753. );
  204754. if( rc==SQLITE_OK && pConfig->bColumnsize ){
  204755. rc = fts5ExecPrintf(pConfig->db, 0,
  204756. "DROP TABLE IF EXISTS %Q.'%q_docsize';",
  204757. pConfig->zDb, pConfig->zName
  204758. );
  204759. }
  204760. if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){
  204761. rc = fts5ExecPrintf(pConfig->db, 0,
  204762. "DROP TABLE IF EXISTS %Q.'%q_content';",
  204763. pConfig->zDb, pConfig->zName
  204764. );
  204765. }
  204766. return rc;
  204767. }
  204768. static void fts5StorageRenameOne(
  204769. Fts5Config *pConfig, /* Current FTS5 configuration */
  204770. int *pRc, /* IN/OUT: Error code */
  204771. const char *zTail, /* Tail of table name e.g. "data", "config" */
  204772. const char *zName /* New name of FTS5 table */
  204773. ){
  204774. if( *pRc==SQLITE_OK ){
  204775. *pRc = fts5ExecPrintf(pConfig->db, 0,
  204776. "ALTER TABLE %Q.'%q_%s' RENAME TO '%q_%s';",
  204777. pConfig->zDb, pConfig->zName, zTail, zName, zTail
  204778. );
  204779. }
  204780. }
  204781. static int sqlite3Fts5StorageRename(Fts5Storage *pStorage, const char *zName){
  204782. Fts5Config *pConfig = pStorage->pConfig;
  204783. int rc = sqlite3Fts5StorageSync(pStorage);
  204784. fts5StorageRenameOne(pConfig, &rc, "data", zName);
  204785. fts5StorageRenameOne(pConfig, &rc, "idx", zName);
  204786. fts5StorageRenameOne(pConfig, &rc, "config", zName);
  204787. if( pConfig->bColumnsize ){
  204788. fts5StorageRenameOne(pConfig, &rc, "docsize", zName);
  204789. }
  204790. if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
  204791. fts5StorageRenameOne(pConfig, &rc, "content", zName);
  204792. }
  204793. return rc;
  204794. }
  204795. /*
  204796. ** Create the shadow table named zPost, with definition zDefn. Return
  204797. ** SQLITE_OK if successful, or an SQLite error code otherwise.
  204798. */
  204799. static int sqlite3Fts5CreateTable(
  204800. Fts5Config *pConfig, /* FTS5 configuration */
  204801. const char *zPost, /* Shadow table to create (e.g. "content") */
  204802. const char *zDefn, /* Columns etc. for shadow table */
  204803. int bWithout, /* True for without rowid */
  204804. char **pzErr /* OUT: Error message */
  204805. ){
  204806. int rc;
  204807. char *zErr = 0;
  204808. rc = fts5ExecPrintf(pConfig->db, &zErr, "CREATE TABLE %Q.'%q_%q'(%s)%s",
  204809. pConfig->zDb, pConfig->zName, zPost, zDefn,
  204810. #ifndef SQLITE_FTS5_NO_WITHOUT_ROWID
  204811. bWithout?" WITHOUT ROWID":
  204812. #endif
  204813. ""
  204814. );
  204815. if( zErr ){
  204816. *pzErr = sqlite3_mprintf(
  204817. "fts5: error creating shadow table %q_%s: %s",
  204818. pConfig->zName, zPost, zErr
  204819. );
  204820. sqlite3_free(zErr);
  204821. }
  204822. return rc;
  204823. }
  204824. /*
  204825. ** Open a new Fts5Index handle. If the bCreate argument is true, create
  204826. ** and initialize the underlying tables
  204827. **
  204828. ** If successful, set *pp to point to the new object and return SQLITE_OK.
  204829. ** Otherwise, set *pp to NULL and return an SQLite error code.
  204830. */
  204831. static int sqlite3Fts5StorageOpen(
  204832. Fts5Config *pConfig,
  204833. Fts5Index *pIndex,
  204834. int bCreate,
  204835. Fts5Storage **pp,
  204836. char **pzErr /* OUT: Error message */
  204837. ){
  204838. int rc = SQLITE_OK;
  204839. Fts5Storage *p; /* New object */
  204840. sqlite3_int64 nByte; /* Bytes of space to allocate */
  204841. nByte = sizeof(Fts5Storage) /* Fts5Storage object */
  204842. + pConfig->nCol * sizeof(i64); /* Fts5Storage.aTotalSize[] */
  204843. *pp = p = (Fts5Storage*)sqlite3_malloc64(nByte);
  204844. if( !p ) return SQLITE_NOMEM;
  204845. memset(p, 0, (size_t)nByte);
  204846. p->aTotalSize = (i64*)&p[1];
  204847. p->pConfig = pConfig;
  204848. p->pIndex = pIndex;
  204849. if( bCreate ){
  204850. if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
  204851. int nDefn = 32 + pConfig->nCol*10;
  204852. char *zDefn = sqlite3_malloc64(32 + (sqlite3_int64)pConfig->nCol * 10);
  204853. if( zDefn==0 ){
  204854. rc = SQLITE_NOMEM;
  204855. }else{
  204856. int i;
  204857. int iOff;
  204858. sqlite3_snprintf(nDefn, zDefn, "id INTEGER PRIMARY KEY");
  204859. iOff = (int)strlen(zDefn);
  204860. for(i=0; i<pConfig->nCol; i++){
  204861. sqlite3_snprintf(nDefn-iOff, &zDefn[iOff], ", c%d", i);
  204862. iOff += (int)strlen(&zDefn[iOff]);
  204863. }
  204864. rc = sqlite3Fts5CreateTable(pConfig, "content", zDefn, 0, pzErr);
  204865. }
  204866. sqlite3_free(zDefn);
  204867. }
  204868. if( rc==SQLITE_OK && pConfig->bColumnsize ){
  204869. rc = sqlite3Fts5CreateTable(
  204870. pConfig, "docsize", "id INTEGER PRIMARY KEY, sz BLOB", 0, pzErr
  204871. );
  204872. }
  204873. if( rc==SQLITE_OK ){
  204874. rc = sqlite3Fts5CreateTable(
  204875. pConfig, "config", "k PRIMARY KEY, v", 1, pzErr
  204876. );
  204877. }
  204878. if( rc==SQLITE_OK ){
  204879. rc = sqlite3Fts5StorageConfigValue(p, "version", 0, FTS5_CURRENT_VERSION);
  204880. }
  204881. }
  204882. if( rc ){
  204883. sqlite3Fts5StorageClose(p);
  204884. *pp = 0;
  204885. }
  204886. return rc;
  204887. }
  204888. /*
  204889. ** Close a handle opened by an earlier call to sqlite3Fts5StorageOpen().
  204890. */
  204891. static int sqlite3Fts5StorageClose(Fts5Storage *p){
  204892. int rc = SQLITE_OK;
  204893. if( p ){
  204894. int i;
  204895. /* Finalize all SQL statements */
  204896. for(i=0; i<ArraySize(p->aStmt); i++){
  204897. sqlite3_finalize(p->aStmt[i]);
  204898. }
  204899. sqlite3_free(p);
  204900. }
  204901. return rc;
  204902. }
  204903. typedef struct Fts5InsertCtx Fts5InsertCtx;
  204904. struct Fts5InsertCtx {
  204905. Fts5Storage *pStorage;
  204906. int iCol;
  204907. int szCol; /* Size of column value in tokens */
  204908. };
  204909. /*
  204910. ** Tokenization callback used when inserting tokens into the FTS index.
  204911. */
  204912. static int fts5StorageInsertCallback(
  204913. void *pContext, /* Pointer to Fts5InsertCtx object */
  204914. int tflags,
  204915. const char *pToken, /* Buffer containing token */
  204916. int nToken, /* Size of token in bytes */
  204917. int iUnused1, /* Start offset of token */
  204918. int iUnused2 /* End offset of token */
  204919. ){
  204920. Fts5InsertCtx *pCtx = (Fts5InsertCtx*)pContext;
  204921. Fts5Index *pIdx = pCtx->pStorage->pIndex;
  204922. UNUSED_PARAM2(iUnused1, iUnused2);
  204923. if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
  204924. if( (tflags & FTS5_TOKEN_COLOCATED)==0 || pCtx->szCol==0 ){
  204925. pCtx->szCol++;
  204926. }
  204927. return sqlite3Fts5IndexWrite(pIdx, pCtx->iCol, pCtx->szCol-1, pToken, nToken);
  204928. }
  204929. /*
  204930. ** If a row with rowid iDel is present in the %_content table, add the
  204931. ** delete-markers to the FTS index necessary to delete it. Do not actually
  204932. ** remove the %_content row at this time though.
  204933. */
  204934. static int fts5StorageDeleteFromIndex(
  204935. Fts5Storage *p,
  204936. i64 iDel,
  204937. sqlite3_value **apVal
  204938. ){
  204939. Fts5Config *pConfig = p->pConfig;
  204940. sqlite3_stmt *pSeek = 0; /* SELECT to read row iDel from %_data */
  204941. int rc; /* Return code */
  204942. int rc2; /* sqlite3_reset() return code */
  204943. int iCol;
  204944. Fts5InsertCtx ctx;
  204945. if( apVal==0 ){
  204946. rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP, &pSeek, 0);
  204947. if( rc!=SQLITE_OK ) return rc;
  204948. sqlite3_bind_int64(pSeek, 1, iDel);
  204949. if( sqlite3_step(pSeek)!=SQLITE_ROW ){
  204950. return sqlite3_reset(pSeek);
  204951. }
  204952. }
  204953. ctx.pStorage = p;
  204954. ctx.iCol = -1;
  204955. rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 1, iDel);
  204956. for(iCol=1; rc==SQLITE_OK && iCol<=pConfig->nCol; iCol++){
  204957. if( pConfig->abUnindexed[iCol-1]==0 ){
  204958. const char *zText;
  204959. int nText;
  204960. if( pSeek ){
  204961. zText = (const char*)sqlite3_column_text(pSeek, iCol);
  204962. nText = sqlite3_column_bytes(pSeek, iCol);
  204963. }else{
  204964. zText = (const char*)sqlite3_value_text(apVal[iCol-1]);
  204965. nText = sqlite3_value_bytes(apVal[iCol-1]);
  204966. }
  204967. ctx.szCol = 0;
  204968. rc = sqlite3Fts5Tokenize(pConfig, FTS5_TOKENIZE_DOCUMENT,
  204969. zText, nText, (void*)&ctx, fts5StorageInsertCallback
  204970. );
  204971. p->aTotalSize[iCol-1] -= (i64)ctx.szCol;
  204972. }
  204973. }
  204974. p->nTotalRow--;
  204975. rc2 = sqlite3_reset(pSeek);
  204976. if( rc==SQLITE_OK ) rc = rc2;
  204977. return rc;
  204978. }
  204979. /*
  204980. ** Insert a record into the %_docsize table. Specifically, do:
  204981. **
  204982. ** INSERT OR REPLACE INTO %_docsize(id, sz) VALUES(iRowid, pBuf);
  204983. **
  204984. ** If there is no %_docsize table (as happens if the columnsize=0 option
  204985. ** is specified when the FTS5 table is created), this function is a no-op.
  204986. */
  204987. static int fts5StorageInsertDocsize(
  204988. Fts5Storage *p, /* Storage module to write to */
  204989. i64 iRowid, /* id value */
  204990. Fts5Buffer *pBuf /* sz value */
  204991. ){
  204992. int rc = SQLITE_OK;
  204993. if( p->pConfig->bColumnsize ){
  204994. sqlite3_stmt *pReplace = 0;
  204995. rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_DOCSIZE, &pReplace, 0);
  204996. if( rc==SQLITE_OK ){
  204997. sqlite3_bind_int64(pReplace, 1, iRowid);
  204998. sqlite3_bind_blob(pReplace, 2, pBuf->p, pBuf->n, SQLITE_STATIC);
  204999. sqlite3_step(pReplace);
  205000. rc = sqlite3_reset(pReplace);
  205001. sqlite3_bind_null(pReplace, 2);
  205002. }
  205003. }
  205004. return rc;
  205005. }
  205006. /*
  205007. ** Load the contents of the "averages" record from disk into the
  205008. ** p->nTotalRow and p->aTotalSize[] variables. If successful, and if
  205009. ** argument bCache is true, set the p->bTotalsValid flag to indicate
  205010. ** that the contents of aTotalSize[] and nTotalRow are valid until
  205011. ** further notice.
  205012. **
  205013. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  205014. ** occurs.
  205015. */
  205016. static int fts5StorageLoadTotals(Fts5Storage *p, int bCache){
  205017. int rc = SQLITE_OK;
  205018. if( p->bTotalsValid==0 ){
  205019. rc = sqlite3Fts5IndexGetAverages(p->pIndex, &p->nTotalRow, p->aTotalSize);
  205020. p->bTotalsValid = bCache;
  205021. }
  205022. return rc;
  205023. }
  205024. /*
  205025. ** Store the current contents of the p->nTotalRow and p->aTotalSize[]
  205026. ** variables in the "averages" record on disk.
  205027. **
  205028. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  205029. ** occurs.
  205030. */
  205031. static int fts5StorageSaveTotals(Fts5Storage *p){
  205032. int nCol = p->pConfig->nCol;
  205033. int i;
  205034. Fts5Buffer buf;
  205035. int rc = SQLITE_OK;
  205036. memset(&buf, 0, sizeof(buf));
  205037. sqlite3Fts5BufferAppendVarint(&rc, &buf, p->nTotalRow);
  205038. for(i=0; i<nCol; i++){
  205039. sqlite3Fts5BufferAppendVarint(&rc, &buf, p->aTotalSize[i]);
  205040. }
  205041. if( rc==SQLITE_OK ){
  205042. rc = sqlite3Fts5IndexSetAverages(p->pIndex, buf.p, buf.n);
  205043. }
  205044. sqlite3_free(buf.p);
  205045. return rc;
  205046. }
  205047. /*
  205048. ** Remove a row from the FTS table.
  205049. */
  205050. static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64 iDel, sqlite3_value **apVal){
  205051. Fts5Config *pConfig = p->pConfig;
  205052. int rc;
  205053. sqlite3_stmt *pDel = 0;
  205054. assert( pConfig->eContent!=FTS5_CONTENT_NORMAL || apVal==0 );
  205055. rc = fts5StorageLoadTotals(p, 1);
  205056. /* Delete the index records */
  205057. if( rc==SQLITE_OK ){
  205058. rc = fts5StorageDeleteFromIndex(p, iDel, apVal);
  205059. }
  205060. /* Delete the %_docsize record */
  205061. if( rc==SQLITE_OK && pConfig->bColumnsize ){
  205062. rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_DOCSIZE, &pDel, 0);
  205063. if( rc==SQLITE_OK ){
  205064. sqlite3_bind_int64(pDel, 1, iDel);
  205065. sqlite3_step(pDel);
  205066. rc = sqlite3_reset(pDel);
  205067. }
  205068. }
  205069. /* Delete the %_content record */
  205070. if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
  205071. if( rc==SQLITE_OK ){
  205072. rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_CONTENT, &pDel, 0);
  205073. }
  205074. if( rc==SQLITE_OK ){
  205075. sqlite3_bind_int64(pDel, 1, iDel);
  205076. sqlite3_step(pDel);
  205077. rc = sqlite3_reset(pDel);
  205078. }
  205079. }
  205080. return rc;
  205081. }
  205082. /*
  205083. ** Delete all entries in the FTS5 index.
  205084. */
  205085. static int sqlite3Fts5StorageDeleteAll(Fts5Storage *p){
  205086. Fts5Config *pConfig = p->pConfig;
  205087. int rc;
  205088. /* Delete the contents of the %_data and %_docsize tables. */
  205089. rc = fts5ExecPrintf(pConfig->db, 0,
  205090. "DELETE FROM %Q.'%q_data';"
  205091. "DELETE FROM %Q.'%q_idx';",
  205092. pConfig->zDb, pConfig->zName,
  205093. pConfig->zDb, pConfig->zName
  205094. );
  205095. if( rc==SQLITE_OK && pConfig->bColumnsize ){
  205096. rc = fts5ExecPrintf(pConfig->db, 0,
  205097. "DELETE FROM %Q.'%q_docsize';",
  205098. pConfig->zDb, pConfig->zName
  205099. );
  205100. }
  205101. /* Reinitialize the %_data table. This call creates the initial structure
  205102. ** and averages records. */
  205103. if( rc==SQLITE_OK ){
  205104. rc = sqlite3Fts5IndexReinit(p->pIndex);
  205105. }
  205106. if( rc==SQLITE_OK ){
  205107. rc = sqlite3Fts5StorageConfigValue(p, "version", 0, FTS5_CURRENT_VERSION);
  205108. }
  205109. return rc;
  205110. }
  205111. static int sqlite3Fts5StorageRebuild(Fts5Storage *p){
  205112. Fts5Buffer buf = {0,0,0};
  205113. Fts5Config *pConfig = p->pConfig;
  205114. sqlite3_stmt *pScan = 0;
  205115. Fts5InsertCtx ctx;
  205116. int rc, rc2;
  205117. memset(&ctx, 0, sizeof(Fts5InsertCtx));
  205118. ctx.pStorage = p;
  205119. rc = sqlite3Fts5StorageDeleteAll(p);
  205120. if( rc==SQLITE_OK ){
  205121. rc = fts5StorageLoadTotals(p, 1);
  205122. }
  205123. if( rc==SQLITE_OK ){
  205124. rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0);
  205125. }
  205126. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pScan) ){
  205127. i64 iRowid = sqlite3_column_int64(pScan, 0);
  205128. sqlite3Fts5BufferZero(&buf);
  205129. rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid);
  205130. for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){
  205131. ctx.szCol = 0;
  205132. if( pConfig->abUnindexed[ctx.iCol]==0 ){
  205133. rc = sqlite3Fts5Tokenize(pConfig,
  205134. FTS5_TOKENIZE_DOCUMENT,
  205135. (const char*)sqlite3_column_text(pScan, ctx.iCol+1),
  205136. sqlite3_column_bytes(pScan, ctx.iCol+1),
  205137. (void*)&ctx,
  205138. fts5StorageInsertCallback
  205139. );
  205140. }
  205141. sqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol);
  205142. p->aTotalSize[ctx.iCol] += (i64)ctx.szCol;
  205143. }
  205144. p->nTotalRow++;
  205145. if( rc==SQLITE_OK ){
  205146. rc = fts5StorageInsertDocsize(p, iRowid, &buf);
  205147. }
  205148. }
  205149. sqlite3_free(buf.p);
  205150. rc2 = sqlite3_reset(pScan);
  205151. if( rc==SQLITE_OK ) rc = rc2;
  205152. /* Write the averages record */
  205153. if( rc==SQLITE_OK ){
  205154. rc = fts5StorageSaveTotals(p);
  205155. }
  205156. return rc;
  205157. }
  205158. static int sqlite3Fts5StorageOptimize(Fts5Storage *p){
  205159. return sqlite3Fts5IndexOptimize(p->pIndex);
  205160. }
  205161. static int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge){
  205162. return sqlite3Fts5IndexMerge(p->pIndex, nMerge);
  205163. }
  205164. static int sqlite3Fts5StorageReset(Fts5Storage *p){
  205165. return sqlite3Fts5IndexReset(p->pIndex);
  205166. }
  205167. /*
  205168. ** Allocate a new rowid. This is used for "external content" tables when
  205169. ** a NULL value is inserted into the rowid column. The new rowid is allocated
  205170. ** by inserting a dummy row into the %_docsize table. The dummy will be
  205171. ** overwritten later.
  205172. **
  205173. ** If the %_docsize table does not exist, SQLITE_MISMATCH is returned. In
  205174. ** this case the user is required to provide a rowid explicitly.
  205175. */
  205176. static int fts5StorageNewRowid(Fts5Storage *p, i64 *piRowid){
  205177. int rc = SQLITE_MISMATCH;
  205178. if( p->pConfig->bColumnsize ){
  205179. sqlite3_stmt *pReplace = 0;
  205180. rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_DOCSIZE, &pReplace, 0);
  205181. if( rc==SQLITE_OK ){
  205182. sqlite3_bind_null(pReplace, 1);
  205183. sqlite3_bind_null(pReplace, 2);
  205184. sqlite3_step(pReplace);
  205185. rc = sqlite3_reset(pReplace);
  205186. }
  205187. if( rc==SQLITE_OK ){
  205188. *piRowid = sqlite3_last_insert_rowid(p->pConfig->db);
  205189. }
  205190. }
  205191. return rc;
  205192. }
  205193. /*
  205194. ** Insert a new row into the FTS content table.
  205195. */
  205196. static int sqlite3Fts5StorageContentInsert(
  205197. Fts5Storage *p,
  205198. sqlite3_value **apVal,
  205199. i64 *piRowid
  205200. ){
  205201. Fts5Config *pConfig = p->pConfig;
  205202. int rc = SQLITE_OK;
  205203. /* Insert the new row into the %_content table. */
  205204. if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){
  205205. if( sqlite3_value_type(apVal[1])==SQLITE_INTEGER ){
  205206. *piRowid = sqlite3_value_int64(apVal[1]);
  205207. }else{
  205208. rc = fts5StorageNewRowid(p, piRowid);
  205209. }
  205210. }else{
  205211. sqlite3_stmt *pInsert = 0; /* Statement to write %_content table */
  205212. int i; /* Counter variable */
  205213. rc = fts5StorageGetStmt(p, FTS5_STMT_INSERT_CONTENT, &pInsert, 0);
  205214. for(i=1; rc==SQLITE_OK && i<=pConfig->nCol+1; i++){
  205215. rc = sqlite3_bind_value(pInsert, i, apVal[i]);
  205216. }
  205217. if( rc==SQLITE_OK ){
  205218. sqlite3_step(pInsert);
  205219. rc = sqlite3_reset(pInsert);
  205220. }
  205221. *piRowid = sqlite3_last_insert_rowid(pConfig->db);
  205222. }
  205223. return rc;
  205224. }
  205225. /*
  205226. ** Insert new entries into the FTS index and %_docsize table.
  205227. */
  205228. static int sqlite3Fts5StorageIndexInsert(
  205229. Fts5Storage *p,
  205230. sqlite3_value **apVal,
  205231. i64 iRowid
  205232. ){
  205233. Fts5Config *pConfig = p->pConfig;
  205234. int rc = SQLITE_OK; /* Return code */
  205235. Fts5InsertCtx ctx; /* Tokenization callback context object */
  205236. Fts5Buffer buf; /* Buffer used to build up %_docsize blob */
  205237. memset(&buf, 0, sizeof(Fts5Buffer));
  205238. ctx.pStorage = p;
  205239. rc = fts5StorageLoadTotals(p, 1);
  205240. if( rc==SQLITE_OK ){
  205241. rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid);
  205242. }
  205243. for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){
  205244. ctx.szCol = 0;
  205245. if( pConfig->abUnindexed[ctx.iCol]==0 ){
  205246. rc = sqlite3Fts5Tokenize(pConfig,
  205247. FTS5_TOKENIZE_DOCUMENT,
  205248. (const char*)sqlite3_value_text(apVal[ctx.iCol+2]),
  205249. sqlite3_value_bytes(apVal[ctx.iCol+2]),
  205250. (void*)&ctx,
  205251. fts5StorageInsertCallback
  205252. );
  205253. }
  205254. sqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol);
  205255. p->aTotalSize[ctx.iCol] += (i64)ctx.szCol;
  205256. }
  205257. p->nTotalRow++;
  205258. /* Write the %_docsize record */
  205259. if( rc==SQLITE_OK ){
  205260. rc = fts5StorageInsertDocsize(p, iRowid, &buf);
  205261. }
  205262. sqlite3_free(buf.p);
  205263. return rc;
  205264. }
  205265. static int fts5StorageCount(Fts5Storage *p, const char *zSuffix, i64 *pnRow){
  205266. Fts5Config *pConfig = p->pConfig;
  205267. char *zSql;
  205268. int rc;
  205269. zSql = sqlite3_mprintf("SELECT count(*) FROM %Q.'%q_%s'",
  205270. pConfig->zDb, pConfig->zName, zSuffix
  205271. );
  205272. if( zSql==0 ){
  205273. rc = SQLITE_NOMEM;
  205274. }else{
  205275. sqlite3_stmt *pCnt = 0;
  205276. rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pCnt, 0);
  205277. if( rc==SQLITE_OK ){
  205278. if( SQLITE_ROW==sqlite3_step(pCnt) ){
  205279. *pnRow = sqlite3_column_int64(pCnt, 0);
  205280. }
  205281. rc = sqlite3_finalize(pCnt);
  205282. }
  205283. }
  205284. sqlite3_free(zSql);
  205285. return rc;
  205286. }
  205287. /*
  205288. ** Context object used by sqlite3Fts5StorageIntegrity().
  205289. */
  205290. typedef struct Fts5IntegrityCtx Fts5IntegrityCtx;
  205291. struct Fts5IntegrityCtx {
  205292. i64 iRowid;
  205293. int iCol;
  205294. int szCol;
  205295. u64 cksum;
  205296. Fts5Termset *pTermset;
  205297. Fts5Config *pConfig;
  205298. };
  205299. /*
  205300. ** Tokenization callback used by integrity check.
  205301. */
  205302. static int fts5StorageIntegrityCallback(
  205303. void *pContext, /* Pointer to Fts5IntegrityCtx object */
  205304. int tflags,
  205305. const char *pToken, /* Buffer containing token */
  205306. int nToken, /* Size of token in bytes */
  205307. int iUnused1, /* Start offset of token */
  205308. int iUnused2 /* End offset of token */
  205309. ){
  205310. Fts5IntegrityCtx *pCtx = (Fts5IntegrityCtx*)pContext;
  205311. Fts5Termset *pTermset = pCtx->pTermset;
  205312. int bPresent;
  205313. int ii;
  205314. int rc = SQLITE_OK;
  205315. int iPos;
  205316. int iCol;
  205317. UNUSED_PARAM2(iUnused1, iUnused2);
  205318. if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
  205319. if( (tflags & FTS5_TOKEN_COLOCATED)==0 || pCtx->szCol==0 ){
  205320. pCtx->szCol++;
  205321. }
  205322. switch( pCtx->pConfig->eDetail ){
  205323. case FTS5_DETAIL_FULL:
  205324. iPos = pCtx->szCol-1;
  205325. iCol = pCtx->iCol;
  205326. break;
  205327. case FTS5_DETAIL_COLUMNS:
  205328. iPos = pCtx->iCol;
  205329. iCol = 0;
  205330. break;
  205331. default:
  205332. assert( pCtx->pConfig->eDetail==FTS5_DETAIL_NONE );
  205333. iPos = 0;
  205334. iCol = 0;
  205335. break;
  205336. }
  205337. rc = sqlite3Fts5TermsetAdd(pTermset, 0, pToken, nToken, &bPresent);
  205338. if( rc==SQLITE_OK && bPresent==0 ){
  205339. pCtx->cksum ^= sqlite3Fts5IndexEntryCksum(
  205340. pCtx->iRowid, iCol, iPos, 0, pToken, nToken
  205341. );
  205342. }
  205343. for(ii=0; rc==SQLITE_OK && ii<pCtx->pConfig->nPrefix; ii++){
  205344. const int nChar = pCtx->pConfig->aPrefix[ii];
  205345. int nByte = sqlite3Fts5IndexCharlenToBytelen(pToken, nToken, nChar);
  205346. if( nByte ){
  205347. rc = sqlite3Fts5TermsetAdd(pTermset, ii+1, pToken, nByte, &bPresent);
  205348. if( bPresent==0 ){
  205349. pCtx->cksum ^= sqlite3Fts5IndexEntryCksum(
  205350. pCtx->iRowid, iCol, iPos, ii+1, pToken, nByte
  205351. );
  205352. }
  205353. }
  205354. }
  205355. return rc;
  205356. }
  205357. /*
  205358. ** Check that the contents of the FTS index match that of the %_content
  205359. ** table. Return SQLITE_OK if they do, or SQLITE_CORRUPT if not. Return
  205360. ** some other SQLite error code if an error occurs while attempting to
  205361. ** determine this.
  205362. */
  205363. static int sqlite3Fts5StorageIntegrity(Fts5Storage *p){
  205364. Fts5Config *pConfig = p->pConfig;
  205365. int rc; /* Return code */
  205366. int *aColSize; /* Array of size pConfig->nCol */
  205367. i64 *aTotalSize; /* Array of size pConfig->nCol */
  205368. Fts5IntegrityCtx ctx;
  205369. sqlite3_stmt *pScan;
  205370. memset(&ctx, 0, sizeof(Fts5IntegrityCtx));
  205371. ctx.pConfig = p->pConfig;
  205372. aTotalSize = (i64*)sqlite3_malloc64(pConfig->nCol*(sizeof(int)+sizeof(i64)));
  205373. if( !aTotalSize ) return SQLITE_NOMEM;
  205374. aColSize = (int*)&aTotalSize[pConfig->nCol];
  205375. memset(aTotalSize, 0, sizeof(i64) * pConfig->nCol);
  205376. /* Generate the expected index checksum based on the contents of the
  205377. ** %_content table. This block stores the checksum in ctx.cksum. */
  205378. rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0);
  205379. if( rc==SQLITE_OK ){
  205380. int rc2;
  205381. while( SQLITE_ROW==sqlite3_step(pScan) ){
  205382. int i;
  205383. ctx.iRowid = sqlite3_column_int64(pScan, 0);
  205384. ctx.szCol = 0;
  205385. if( pConfig->bColumnsize ){
  205386. rc = sqlite3Fts5StorageDocsize(p, ctx.iRowid, aColSize);
  205387. }
  205388. if( rc==SQLITE_OK && pConfig->eDetail==FTS5_DETAIL_NONE ){
  205389. rc = sqlite3Fts5TermsetNew(&ctx.pTermset);
  205390. }
  205391. for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
  205392. if( pConfig->abUnindexed[i] ) continue;
  205393. ctx.iCol = i;
  205394. ctx.szCol = 0;
  205395. if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
  205396. rc = sqlite3Fts5TermsetNew(&ctx.pTermset);
  205397. }
  205398. if( rc==SQLITE_OK ){
  205399. rc = sqlite3Fts5Tokenize(pConfig,
  205400. FTS5_TOKENIZE_DOCUMENT,
  205401. (const char*)sqlite3_column_text(pScan, i+1),
  205402. sqlite3_column_bytes(pScan, i+1),
  205403. (void*)&ctx,
  205404. fts5StorageIntegrityCallback
  205405. );
  205406. }
  205407. if( rc==SQLITE_OK && pConfig->bColumnsize && ctx.szCol!=aColSize[i] ){
  205408. rc = FTS5_CORRUPT;
  205409. }
  205410. aTotalSize[i] += ctx.szCol;
  205411. if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
  205412. sqlite3Fts5TermsetFree(ctx.pTermset);
  205413. ctx.pTermset = 0;
  205414. }
  205415. }
  205416. sqlite3Fts5TermsetFree(ctx.pTermset);
  205417. ctx.pTermset = 0;
  205418. if( rc!=SQLITE_OK ) break;
  205419. }
  205420. rc2 = sqlite3_reset(pScan);
  205421. if( rc==SQLITE_OK ) rc = rc2;
  205422. }
  205423. /* Test that the "totals" (sometimes called "averages") record looks Ok */
  205424. if( rc==SQLITE_OK ){
  205425. int i;
  205426. rc = fts5StorageLoadTotals(p, 0);
  205427. for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
  205428. if( p->aTotalSize[i]!=aTotalSize[i] ) rc = FTS5_CORRUPT;
  205429. }
  205430. }
  205431. /* Check that the %_docsize and %_content tables contain the expected
  205432. ** number of rows. */
  205433. if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){
  205434. i64 nRow = 0;
  205435. rc = fts5StorageCount(p, "content", &nRow);
  205436. if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT;
  205437. }
  205438. if( rc==SQLITE_OK && pConfig->bColumnsize ){
  205439. i64 nRow = 0;
  205440. rc = fts5StorageCount(p, "docsize", &nRow);
  205441. if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT;
  205442. }
  205443. /* Pass the expected checksum down to the FTS index module. It will
  205444. ** verify, amongst other things, that it matches the checksum generated by
  205445. ** inspecting the index itself. */
  205446. if( rc==SQLITE_OK ){
  205447. rc = sqlite3Fts5IndexIntegrityCheck(p->pIndex, ctx.cksum);
  205448. }
  205449. sqlite3_free(aTotalSize);
  205450. return rc;
  205451. }
  205452. /*
  205453. ** Obtain an SQLite statement handle that may be used to read data from the
  205454. ** %_content table.
  205455. */
  205456. static int sqlite3Fts5StorageStmt(
  205457. Fts5Storage *p,
  205458. int eStmt,
  205459. sqlite3_stmt **pp,
  205460. char **pzErrMsg
  205461. ){
  205462. int rc;
  205463. assert( eStmt==FTS5_STMT_SCAN_ASC
  205464. || eStmt==FTS5_STMT_SCAN_DESC
  205465. || eStmt==FTS5_STMT_LOOKUP
  205466. );
  205467. rc = fts5StorageGetStmt(p, eStmt, pp, pzErrMsg);
  205468. if( rc==SQLITE_OK ){
  205469. assert( p->aStmt[eStmt]==*pp );
  205470. p->aStmt[eStmt] = 0;
  205471. }
  205472. return rc;
  205473. }
  205474. /*
  205475. ** Release an SQLite statement handle obtained via an earlier call to
  205476. ** sqlite3Fts5StorageStmt(). The eStmt parameter passed to this function
  205477. ** must match that passed to the sqlite3Fts5StorageStmt() call.
  205478. */
  205479. static void sqlite3Fts5StorageStmtRelease(
  205480. Fts5Storage *p,
  205481. int eStmt,
  205482. sqlite3_stmt *pStmt
  205483. ){
  205484. assert( eStmt==FTS5_STMT_SCAN_ASC
  205485. || eStmt==FTS5_STMT_SCAN_DESC
  205486. || eStmt==FTS5_STMT_LOOKUP
  205487. );
  205488. if( p->aStmt[eStmt]==0 ){
  205489. sqlite3_reset(pStmt);
  205490. p->aStmt[eStmt] = pStmt;
  205491. }else{
  205492. sqlite3_finalize(pStmt);
  205493. }
  205494. }
  205495. static int fts5StorageDecodeSizeArray(
  205496. int *aCol, int nCol, /* Array to populate */
  205497. const u8 *aBlob, int nBlob /* Record to read varints from */
  205498. ){
  205499. int i;
  205500. int iOff = 0;
  205501. for(i=0; i<nCol; i++){
  205502. if( iOff>=nBlob ) return 1;
  205503. iOff += fts5GetVarint32(&aBlob[iOff], aCol[i]);
  205504. }
  205505. return (iOff!=nBlob);
  205506. }
  205507. /*
  205508. ** Argument aCol points to an array of integers containing one entry for
  205509. ** each table column. This function reads the %_docsize record for the
  205510. ** specified rowid and populates aCol[] with the results.
  205511. **
  205512. ** An SQLite error code is returned if an error occurs, or SQLITE_OK
  205513. ** otherwise.
  205514. */
  205515. static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol){
  205516. int nCol = p->pConfig->nCol; /* Number of user columns in table */
  205517. sqlite3_stmt *pLookup = 0; /* Statement to query %_docsize */
  205518. int rc; /* Return Code */
  205519. assert( p->pConfig->bColumnsize );
  205520. rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP_DOCSIZE, &pLookup, 0);
  205521. if( rc==SQLITE_OK ){
  205522. int bCorrupt = 1;
  205523. sqlite3_bind_int64(pLookup, 1, iRowid);
  205524. if( SQLITE_ROW==sqlite3_step(pLookup) ){
  205525. const u8 *aBlob = sqlite3_column_blob(pLookup, 0);
  205526. int nBlob = sqlite3_column_bytes(pLookup, 0);
  205527. if( 0==fts5StorageDecodeSizeArray(aCol, nCol, aBlob, nBlob) ){
  205528. bCorrupt = 0;
  205529. }
  205530. }
  205531. rc = sqlite3_reset(pLookup);
  205532. if( bCorrupt && rc==SQLITE_OK ){
  205533. rc = FTS5_CORRUPT;
  205534. }
  205535. }
  205536. return rc;
  205537. }
  205538. static int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnToken){
  205539. int rc = fts5StorageLoadTotals(p, 0);
  205540. if( rc==SQLITE_OK ){
  205541. *pnToken = 0;
  205542. if( iCol<0 ){
  205543. int i;
  205544. for(i=0; i<p->pConfig->nCol; i++){
  205545. *pnToken += p->aTotalSize[i];
  205546. }
  205547. }else if( iCol<p->pConfig->nCol ){
  205548. *pnToken = p->aTotalSize[iCol];
  205549. }else{
  205550. rc = SQLITE_RANGE;
  205551. }
  205552. }
  205553. return rc;
  205554. }
  205555. static int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow){
  205556. int rc = fts5StorageLoadTotals(p, 0);
  205557. if( rc==SQLITE_OK ){
  205558. /* nTotalRow being zero does not necessarily indicate a corrupt
  205559. ** database - it might be that the FTS5 table really does contain zero
  205560. ** rows. However this function is only called from the xRowCount() API,
  205561. ** and there is no way for that API to be invoked if the table contains
  205562. ** no rows. Hence the FTS5_CORRUPT return. */
  205563. *pnRow = p->nTotalRow;
  205564. if( p->nTotalRow<=0 ) rc = FTS5_CORRUPT;
  205565. }
  205566. return rc;
  205567. }
  205568. /*
  205569. ** Flush any data currently held in-memory to disk.
  205570. */
  205571. static int sqlite3Fts5StorageSync(Fts5Storage *p){
  205572. int rc = SQLITE_OK;
  205573. i64 iLastRowid = sqlite3_last_insert_rowid(p->pConfig->db);
  205574. if( p->bTotalsValid ){
  205575. rc = fts5StorageSaveTotals(p);
  205576. p->bTotalsValid = 0;
  205577. }
  205578. if( rc==SQLITE_OK ){
  205579. rc = sqlite3Fts5IndexSync(p->pIndex);
  205580. }
  205581. sqlite3_set_last_insert_rowid(p->pConfig->db, iLastRowid);
  205582. return rc;
  205583. }
  205584. static int sqlite3Fts5StorageRollback(Fts5Storage *p){
  205585. p->bTotalsValid = 0;
  205586. return sqlite3Fts5IndexRollback(p->pIndex);
  205587. }
  205588. static int sqlite3Fts5StorageConfigValue(
  205589. Fts5Storage *p,
  205590. const char *z,
  205591. sqlite3_value *pVal,
  205592. int iVal
  205593. ){
  205594. sqlite3_stmt *pReplace = 0;
  205595. int rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_CONFIG, &pReplace, 0);
  205596. if( rc==SQLITE_OK ){
  205597. sqlite3_bind_text(pReplace, 1, z, -1, SQLITE_STATIC);
  205598. if( pVal ){
  205599. sqlite3_bind_value(pReplace, 2, pVal);
  205600. }else{
  205601. sqlite3_bind_int(pReplace, 2, iVal);
  205602. }
  205603. sqlite3_step(pReplace);
  205604. rc = sqlite3_reset(pReplace);
  205605. sqlite3_bind_null(pReplace, 1);
  205606. }
  205607. if( rc==SQLITE_OK && pVal ){
  205608. int iNew = p->pConfig->iCookie + 1;
  205609. rc = sqlite3Fts5IndexSetCookie(p->pIndex, iNew);
  205610. if( rc==SQLITE_OK ){
  205611. p->pConfig->iCookie = iNew;
  205612. }
  205613. }
  205614. return rc;
  205615. }
  205616. /*
  205617. ** 2014 May 31
  205618. **
  205619. ** The author disclaims copyright to this source code. In place of
  205620. ** a legal notice, here is a blessing:
  205621. **
  205622. ** May you do good and not evil.
  205623. ** May you find forgiveness for yourself and forgive others.
  205624. ** May you share freely, never taking more than you give.
  205625. **
  205626. ******************************************************************************
  205627. */
  205628. /* #include "fts5Int.h" */
  205629. /**************************************************************************
  205630. ** Start of ascii tokenizer implementation.
  205631. */
  205632. /*
  205633. ** For tokenizers with no "unicode" modifier, the set of token characters
  205634. ** is the same as the set of ASCII range alphanumeric characters.
  205635. */
  205636. static unsigned char aAsciiTokenChar[128] = {
  205637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x00..0x0F */
  205638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x10..0x1F */
  205639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x20..0x2F */
  205640. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 0x30..0x3F */
  205641. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x40..0x4F */
  205642. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 0x50..0x5F */
  205643. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x60..0x6F */
  205644. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 0x70..0x7F */
  205645. };
  205646. typedef struct AsciiTokenizer AsciiTokenizer;
  205647. struct AsciiTokenizer {
  205648. unsigned char aTokenChar[128];
  205649. };
  205650. static void fts5AsciiAddExceptions(
  205651. AsciiTokenizer *p,
  205652. const char *zArg,
  205653. int bTokenChars
  205654. ){
  205655. int i;
  205656. for(i=0; zArg[i]; i++){
  205657. if( (zArg[i] & 0x80)==0 ){
  205658. p->aTokenChar[(int)zArg[i]] = (unsigned char)bTokenChars;
  205659. }
  205660. }
  205661. }
  205662. /*
  205663. ** Delete a "ascii" tokenizer.
  205664. */
  205665. static void fts5AsciiDelete(Fts5Tokenizer *p){
  205666. sqlite3_free(p);
  205667. }
  205668. /*
  205669. ** Create an "ascii" tokenizer.
  205670. */
  205671. static int fts5AsciiCreate(
  205672. void *pUnused,
  205673. const char **azArg, int nArg,
  205674. Fts5Tokenizer **ppOut
  205675. ){
  205676. int rc = SQLITE_OK;
  205677. AsciiTokenizer *p = 0;
  205678. UNUSED_PARAM(pUnused);
  205679. if( nArg%2 ){
  205680. rc = SQLITE_ERROR;
  205681. }else{
  205682. p = sqlite3_malloc(sizeof(AsciiTokenizer));
  205683. if( p==0 ){
  205684. rc = SQLITE_NOMEM;
  205685. }else{
  205686. int i;
  205687. memset(p, 0, sizeof(AsciiTokenizer));
  205688. memcpy(p->aTokenChar, aAsciiTokenChar, sizeof(aAsciiTokenChar));
  205689. for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
  205690. const char *zArg = azArg[i+1];
  205691. if( 0==sqlite3_stricmp(azArg[i], "tokenchars") ){
  205692. fts5AsciiAddExceptions(p, zArg, 1);
  205693. }else
  205694. if( 0==sqlite3_stricmp(azArg[i], "separators") ){
  205695. fts5AsciiAddExceptions(p, zArg, 0);
  205696. }else{
  205697. rc = SQLITE_ERROR;
  205698. }
  205699. }
  205700. if( rc!=SQLITE_OK ){
  205701. fts5AsciiDelete((Fts5Tokenizer*)p);
  205702. p = 0;
  205703. }
  205704. }
  205705. }
  205706. *ppOut = (Fts5Tokenizer*)p;
  205707. return rc;
  205708. }
  205709. static void asciiFold(char *aOut, const char *aIn, int nByte){
  205710. int i;
  205711. for(i=0; i<nByte; i++){
  205712. char c = aIn[i];
  205713. if( c>='A' && c<='Z' ) c += 32;
  205714. aOut[i] = c;
  205715. }
  205716. }
  205717. /*
  205718. ** Tokenize some text using the ascii tokenizer.
  205719. */
  205720. static int fts5AsciiTokenize(
  205721. Fts5Tokenizer *pTokenizer,
  205722. void *pCtx,
  205723. int iUnused,
  205724. const char *pText, int nText,
  205725. int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
  205726. ){
  205727. AsciiTokenizer *p = (AsciiTokenizer*)pTokenizer;
  205728. int rc = SQLITE_OK;
  205729. int ie;
  205730. int is = 0;
  205731. char aFold[64];
  205732. int nFold = sizeof(aFold);
  205733. char *pFold = aFold;
  205734. unsigned char *a = p->aTokenChar;
  205735. UNUSED_PARAM(iUnused);
  205736. while( is<nText && rc==SQLITE_OK ){
  205737. int nByte;
  205738. /* Skip any leading divider characters. */
  205739. while( is<nText && ((pText[is]&0x80)==0 && a[(int)pText[is]]==0) ){
  205740. is++;
  205741. }
  205742. if( is==nText ) break;
  205743. /* Count the token characters */
  205744. ie = is+1;
  205745. while( ie<nText && ((pText[ie]&0x80) || a[(int)pText[ie]] ) ){
  205746. ie++;
  205747. }
  205748. /* Fold to lower case */
  205749. nByte = ie-is;
  205750. if( nByte>nFold ){
  205751. if( pFold!=aFold ) sqlite3_free(pFold);
  205752. pFold = sqlite3_malloc64((sqlite3_int64)nByte*2);
  205753. if( pFold==0 ){
  205754. rc = SQLITE_NOMEM;
  205755. break;
  205756. }
  205757. nFold = nByte*2;
  205758. }
  205759. asciiFold(pFold, &pText[is], nByte);
  205760. /* Invoke the token callback */
  205761. rc = xToken(pCtx, 0, pFold, nByte, is, ie);
  205762. is = ie+1;
  205763. }
  205764. if( pFold!=aFold ) sqlite3_free(pFold);
  205765. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  205766. return rc;
  205767. }
  205768. /**************************************************************************
  205769. ** Start of unicode61 tokenizer implementation.
  205770. */
  205771. /*
  205772. ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
  205773. ** from the sqlite3 source file utf.c. If this file is compiled as part
  205774. ** of the amalgamation, they are not required.
  205775. */
  205776. #ifndef SQLITE_AMALGAMATION
  205777. static const unsigned char sqlite3Utf8Trans1[] = {
  205778. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  205779. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  205780. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  205781. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  205782. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  205783. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  205784. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  205785. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  205786. };
  205787. #define READ_UTF8(zIn, zTerm, c) \
  205788. c = *(zIn++); \
  205789. if( c>=0xc0 ){ \
  205790. c = sqlite3Utf8Trans1[c-0xc0]; \
  205791. while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
  205792. c = (c<<6) + (0x3f & *(zIn++)); \
  205793. } \
  205794. if( c<0x80 \
  205795. || (c&0xFFFFF800)==0xD800 \
  205796. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
  205797. }
  205798. #define WRITE_UTF8(zOut, c) { \
  205799. if( c<0x00080 ){ \
  205800. *zOut++ = (unsigned char)(c&0xFF); \
  205801. } \
  205802. else if( c<0x00800 ){ \
  205803. *zOut++ = 0xC0 + (unsigned char)((c>>6)&0x1F); \
  205804. *zOut++ = 0x80 + (unsigned char)(c & 0x3F); \
  205805. } \
  205806. else if( c<0x10000 ){ \
  205807. *zOut++ = 0xE0 + (unsigned char)((c>>12)&0x0F); \
  205808. *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F); \
  205809. *zOut++ = 0x80 + (unsigned char)(c & 0x3F); \
  205810. }else{ \
  205811. *zOut++ = 0xF0 + (unsigned char)((c>>18) & 0x07); \
  205812. *zOut++ = 0x80 + (unsigned char)((c>>12) & 0x3F); \
  205813. *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F); \
  205814. *zOut++ = 0x80 + (unsigned char)(c & 0x3F); \
  205815. } \
  205816. }
  205817. #endif /* ifndef SQLITE_AMALGAMATION */
  205818. typedef struct Unicode61Tokenizer Unicode61Tokenizer;
  205819. struct Unicode61Tokenizer {
  205820. unsigned char aTokenChar[128]; /* ASCII range token characters */
  205821. char *aFold; /* Buffer to fold text into */
  205822. int nFold; /* Size of aFold[] in bytes */
  205823. int eRemoveDiacritic; /* True if remove_diacritics=1 is set */
  205824. int nException;
  205825. int *aiException;
  205826. unsigned char aCategory[32]; /* True for token char categories */
  205827. };
  205828. /* Values for eRemoveDiacritic (must match internals of fts5_unicode2.c) */
  205829. #define FTS5_REMOVE_DIACRITICS_NONE 0
  205830. #define FTS5_REMOVE_DIACRITICS_SIMPLE 1
  205831. #define FTS5_REMOVE_DIACRITICS_COMPLEX 2
  205832. static int fts5UnicodeAddExceptions(
  205833. Unicode61Tokenizer *p, /* Tokenizer object */
  205834. const char *z, /* Characters to treat as exceptions */
  205835. int bTokenChars /* 1 for 'tokenchars', 0 for 'separators' */
  205836. ){
  205837. int rc = SQLITE_OK;
  205838. int n = (int)strlen(z);
  205839. int *aNew;
  205840. if( n>0 ){
  205841. aNew = (int*)sqlite3_realloc64(p->aiException,
  205842. (n+p->nException)*sizeof(int));
  205843. if( aNew ){
  205844. int nNew = p->nException;
  205845. const unsigned char *zCsr = (const unsigned char*)z;
  205846. const unsigned char *zTerm = (const unsigned char*)&z[n];
  205847. while( zCsr<zTerm ){
  205848. u32 iCode;
  205849. int bToken;
  205850. READ_UTF8(zCsr, zTerm, iCode);
  205851. if( iCode<128 ){
  205852. p->aTokenChar[iCode] = (unsigned char)bTokenChars;
  205853. }else{
  205854. bToken = p->aCategory[sqlite3Fts5UnicodeCategory(iCode)];
  205855. assert( (bToken==0 || bToken==1) );
  205856. assert( (bTokenChars==0 || bTokenChars==1) );
  205857. if( bToken!=bTokenChars && sqlite3Fts5UnicodeIsdiacritic(iCode)==0 ){
  205858. int i;
  205859. for(i=0; i<nNew; i++){
  205860. if( (u32)aNew[i]>iCode ) break;
  205861. }
  205862. memmove(&aNew[i+1], &aNew[i], (nNew-i)*sizeof(int));
  205863. aNew[i] = iCode;
  205864. nNew++;
  205865. }
  205866. }
  205867. }
  205868. p->aiException = aNew;
  205869. p->nException = nNew;
  205870. }else{
  205871. rc = SQLITE_NOMEM;
  205872. }
  205873. }
  205874. return rc;
  205875. }
  205876. /*
  205877. ** Return true if the p->aiException[] array contains the value iCode.
  205878. */
  205879. static int fts5UnicodeIsException(Unicode61Tokenizer *p, int iCode){
  205880. if( p->nException>0 ){
  205881. int *a = p->aiException;
  205882. int iLo = 0;
  205883. int iHi = p->nException-1;
  205884. while( iHi>=iLo ){
  205885. int iTest = (iHi + iLo) / 2;
  205886. if( iCode==a[iTest] ){
  205887. return 1;
  205888. }else if( iCode>a[iTest] ){
  205889. iLo = iTest+1;
  205890. }else{
  205891. iHi = iTest-1;
  205892. }
  205893. }
  205894. }
  205895. return 0;
  205896. }
  205897. /*
  205898. ** Delete a "unicode61" tokenizer.
  205899. */
  205900. static void fts5UnicodeDelete(Fts5Tokenizer *pTok){
  205901. if( pTok ){
  205902. Unicode61Tokenizer *p = (Unicode61Tokenizer*)pTok;
  205903. sqlite3_free(p->aiException);
  205904. sqlite3_free(p->aFold);
  205905. sqlite3_free(p);
  205906. }
  205907. return;
  205908. }
  205909. static int unicodeSetCategories(Unicode61Tokenizer *p, const char *zCat){
  205910. const char *z = zCat;
  205911. while( *z ){
  205912. while( *z==' ' || *z=='\t' ) z++;
  205913. if( *z && sqlite3Fts5UnicodeCatParse(z, p->aCategory) ){
  205914. return SQLITE_ERROR;
  205915. }
  205916. while( *z!=' ' && *z!='\t' && *z!='\0' ) z++;
  205917. }
  205918. sqlite3Fts5UnicodeAscii(p->aCategory, p->aTokenChar);
  205919. return SQLITE_OK;
  205920. }
  205921. /*
  205922. ** Create a "unicode61" tokenizer.
  205923. */
  205924. static int fts5UnicodeCreate(
  205925. void *pUnused,
  205926. const char **azArg, int nArg,
  205927. Fts5Tokenizer **ppOut
  205928. ){
  205929. int rc = SQLITE_OK; /* Return code */
  205930. Unicode61Tokenizer *p = 0; /* New tokenizer object */
  205931. UNUSED_PARAM(pUnused);
  205932. if( nArg%2 ){
  205933. rc = SQLITE_ERROR;
  205934. }else{
  205935. p = (Unicode61Tokenizer*)sqlite3_malloc(sizeof(Unicode61Tokenizer));
  205936. if( p ){
  205937. const char *zCat = "L* N* Co";
  205938. int i;
  205939. memset(p, 0, sizeof(Unicode61Tokenizer));
  205940. p->eRemoveDiacritic = FTS5_REMOVE_DIACRITICS_SIMPLE;
  205941. p->nFold = 64;
  205942. p->aFold = sqlite3_malloc64(p->nFold * sizeof(char));
  205943. if( p->aFold==0 ){
  205944. rc = SQLITE_NOMEM;
  205945. }
  205946. /* Search for a "categories" argument */
  205947. for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
  205948. if( 0==sqlite3_stricmp(azArg[i], "categories") ){
  205949. zCat = azArg[i+1];
  205950. }
  205951. }
  205952. if( rc==SQLITE_OK ){
  205953. rc = unicodeSetCategories(p, zCat);
  205954. }
  205955. for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
  205956. const char *zArg = azArg[i+1];
  205957. if( 0==sqlite3_stricmp(azArg[i], "remove_diacritics") ){
  205958. if( (zArg[0]!='0' && zArg[0]!='1' && zArg[0]!='2') || zArg[1] ){
  205959. rc = SQLITE_ERROR;
  205960. }else{
  205961. p->eRemoveDiacritic = (zArg[0] - '0');
  205962. assert( p->eRemoveDiacritic==FTS5_REMOVE_DIACRITICS_NONE
  205963. || p->eRemoveDiacritic==FTS5_REMOVE_DIACRITICS_SIMPLE
  205964. || p->eRemoveDiacritic==FTS5_REMOVE_DIACRITICS_COMPLEX
  205965. );
  205966. }
  205967. }else
  205968. if( 0==sqlite3_stricmp(azArg[i], "tokenchars") ){
  205969. rc = fts5UnicodeAddExceptions(p, zArg, 1);
  205970. }else
  205971. if( 0==sqlite3_stricmp(azArg[i], "separators") ){
  205972. rc = fts5UnicodeAddExceptions(p, zArg, 0);
  205973. }else
  205974. if( 0==sqlite3_stricmp(azArg[i], "categories") ){
  205975. /* no-op */
  205976. }else{
  205977. rc = SQLITE_ERROR;
  205978. }
  205979. }
  205980. }else{
  205981. rc = SQLITE_NOMEM;
  205982. }
  205983. if( rc!=SQLITE_OK ){
  205984. fts5UnicodeDelete((Fts5Tokenizer*)p);
  205985. p = 0;
  205986. }
  205987. *ppOut = (Fts5Tokenizer*)p;
  205988. }
  205989. return rc;
  205990. }
  205991. /*
  205992. ** Return true if, for the purposes of tokenizing with the tokenizer
  205993. ** passed as the first argument, codepoint iCode is considered a token
  205994. ** character (not a separator).
  205995. */
  205996. static int fts5UnicodeIsAlnum(Unicode61Tokenizer *p, int iCode){
  205997. return (
  205998. p->aCategory[sqlite3Fts5UnicodeCategory((u32)iCode)]
  205999. ^ fts5UnicodeIsException(p, iCode)
  206000. );
  206001. }
  206002. static int fts5UnicodeTokenize(
  206003. Fts5Tokenizer *pTokenizer,
  206004. void *pCtx,
  206005. int iUnused,
  206006. const char *pText, int nText,
  206007. int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
  206008. ){
  206009. Unicode61Tokenizer *p = (Unicode61Tokenizer*)pTokenizer;
  206010. int rc = SQLITE_OK;
  206011. unsigned char *a = p->aTokenChar;
  206012. unsigned char *zTerm = (unsigned char*)&pText[nText];
  206013. unsigned char *zCsr = (unsigned char *)pText;
  206014. /* Output buffer */
  206015. char *aFold = p->aFold;
  206016. int nFold = p->nFold;
  206017. const char *pEnd = &aFold[nFold-6];
  206018. UNUSED_PARAM(iUnused);
  206019. /* Each iteration of this loop gobbles up a contiguous run of separators,
  206020. ** then the next token. */
  206021. while( rc==SQLITE_OK ){
  206022. u32 iCode; /* non-ASCII codepoint read from input */
  206023. char *zOut = aFold;
  206024. int is;
  206025. int ie;
  206026. /* Skip any separator characters. */
  206027. while( 1 ){
  206028. if( zCsr>=zTerm ) goto tokenize_done;
  206029. if( *zCsr & 0x80 ) {
  206030. /* A character outside of the ascii range. Skip past it if it is
  206031. ** a separator character. Or break out of the loop if it is not. */
  206032. is = zCsr - (unsigned char*)pText;
  206033. READ_UTF8(zCsr, zTerm, iCode);
  206034. if( fts5UnicodeIsAlnum(p, iCode) ){
  206035. goto non_ascii_tokenchar;
  206036. }
  206037. }else{
  206038. if( a[*zCsr] ){
  206039. is = zCsr - (unsigned char*)pText;
  206040. goto ascii_tokenchar;
  206041. }
  206042. zCsr++;
  206043. }
  206044. }
  206045. /* Run through the tokenchars. Fold them into the output buffer along
  206046. ** the way. */
  206047. while( zCsr<zTerm ){
  206048. /* Grow the output buffer so that there is sufficient space to fit the
  206049. ** largest possible utf-8 character. */
  206050. if( zOut>pEnd ){
  206051. aFold = sqlite3_malloc64((sqlite3_int64)nFold*2);
  206052. if( aFold==0 ){
  206053. rc = SQLITE_NOMEM;
  206054. goto tokenize_done;
  206055. }
  206056. zOut = &aFold[zOut - p->aFold];
  206057. memcpy(aFold, p->aFold, nFold);
  206058. sqlite3_free(p->aFold);
  206059. p->aFold = aFold;
  206060. p->nFold = nFold = nFold*2;
  206061. pEnd = &aFold[nFold-6];
  206062. }
  206063. if( *zCsr & 0x80 ){
  206064. /* An non-ascii-range character. Fold it into the output buffer if
  206065. ** it is a token character, or break out of the loop if it is not. */
  206066. READ_UTF8(zCsr, zTerm, iCode);
  206067. if( fts5UnicodeIsAlnum(p,iCode)||sqlite3Fts5UnicodeIsdiacritic(iCode) ){
  206068. non_ascii_tokenchar:
  206069. iCode = sqlite3Fts5UnicodeFold(iCode, p->eRemoveDiacritic);
  206070. if( iCode ) WRITE_UTF8(zOut, iCode);
  206071. }else{
  206072. break;
  206073. }
  206074. }else if( a[*zCsr]==0 ){
  206075. /* An ascii-range separator character. End of token. */
  206076. break;
  206077. }else{
  206078. ascii_tokenchar:
  206079. if( *zCsr>='A' && *zCsr<='Z' ){
  206080. *zOut++ = *zCsr + 32;
  206081. }else{
  206082. *zOut++ = *zCsr;
  206083. }
  206084. zCsr++;
  206085. }
  206086. ie = zCsr - (unsigned char*)pText;
  206087. }
  206088. /* Invoke the token callback */
  206089. rc = xToken(pCtx, 0, aFold, zOut-aFold, is, ie);
  206090. }
  206091. tokenize_done:
  206092. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  206093. return rc;
  206094. }
  206095. /**************************************************************************
  206096. ** Start of porter stemmer implementation.
  206097. */
  206098. /* Any tokens larger than this (in bytes) are passed through without
  206099. ** stemming. */
  206100. #define FTS5_PORTER_MAX_TOKEN 64
  206101. typedef struct PorterTokenizer PorterTokenizer;
  206102. struct PorterTokenizer {
  206103. fts5_tokenizer tokenizer; /* Parent tokenizer module */
  206104. Fts5Tokenizer *pTokenizer; /* Parent tokenizer instance */
  206105. char aBuf[FTS5_PORTER_MAX_TOKEN + 64];
  206106. };
  206107. /*
  206108. ** Delete a "porter" tokenizer.
  206109. */
  206110. static void fts5PorterDelete(Fts5Tokenizer *pTok){
  206111. if( pTok ){
  206112. PorterTokenizer *p = (PorterTokenizer*)pTok;
  206113. if( p->pTokenizer ){
  206114. p->tokenizer.xDelete(p->pTokenizer);
  206115. }
  206116. sqlite3_free(p);
  206117. }
  206118. }
  206119. /*
  206120. ** Create a "porter" tokenizer.
  206121. */
  206122. static int fts5PorterCreate(
  206123. void *pCtx,
  206124. const char **azArg, int nArg,
  206125. Fts5Tokenizer **ppOut
  206126. ){
  206127. fts5_api *pApi = (fts5_api*)pCtx;
  206128. int rc = SQLITE_OK;
  206129. PorterTokenizer *pRet;
  206130. void *pUserdata = 0;
  206131. const char *zBase = "unicode61";
  206132. if( nArg>0 ){
  206133. zBase = azArg[0];
  206134. }
  206135. pRet = (PorterTokenizer*)sqlite3_malloc(sizeof(PorterTokenizer));
  206136. if( pRet ){
  206137. memset(pRet, 0, sizeof(PorterTokenizer));
  206138. rc = pApi->xFindTokenizer(pApi, zBase, &pUserdata, &pRet->tokenizer);
  206139. }else{
  206140. rc = SQLITE_NOMEM;
  206141. }
  206142. if( rc==SQLITE_OK ){
  206143. int nArg2 = (nArg>0 ? nArg-1 : 0);
  206144. const char **azArg2 = (nArg2 ? &azArg[1] : 0);
  206145. rc = pRet->tokenizer.xCreate(pUserdata, azArg2, nArg2, &pRet->pTokenizer);
  206146. }
  206147. if( rc!=SQLITE_OK ){
  206148. fts5PorterDelete((Fts5Tokenizer*)pRet);
  206149. pRet = 0;
  206150. }
  206151. *ppOut = (Fts5Tokenizer*)pRet;
  206152. return rc;
  206153. }
  206154. typedef struct PorterContext PorterContext;
  206155. struct PorterContext {
  206156. void *pCtx;
  206157. int (*xToken)(void*, int, const char*, int, int, int);
  206158. char *aBuf;
  206159. };
  206160. typedef struct PorterRule PorterRule;
  206161. struct PorterRule {
  206162. const char *zSuffix;
  206163. int nSuffix;
  206164. int (*xCond)(char *zStem, int nStem);
  206165. const char *zOutput;
  206166. int nOutput;
  206167. };
  206168. #if 0
  206169. static int fts5PorterApply(char *aBuf, int *pnBuf, PorterRule *aRule){
  206170. int ret = -1;
  206171. int nBuf = *pnBuf;
  206172. PorterRule *p;
  206173. for(p=aRule; p->zSuffix; p++){
  206174. assert( strlen(p->zSuffix)==p->nSuffix );
  206175. assert( strlen(p->zOutput)==p->nOutput );
  206176. if( nBuf<p->nSuffix ) continue;
  206177. if( 0==memcmp(&aBuf[nBuf - p->nSuffix], p->zSuffix, p->nSuffix) ) break;
  206178. }
  206179. if( p->zSuffix ){
  206180. int nStem = nBuf - p->nSuffix;
  206181. if( p->xCond==0 || p->xCond(aBuf, nStem) ){
  206182. memcpy(&aBuf[nStem], p->zOutput, p->nOutput);
  206183. *pnBuf = nStem + p->nOutput;
  206184. ret = p - aRule;
  206185. }
  206186. }
  206187. return ret;
  206188. }
  206189. #endif
  206190. static int fts5PorterIsVowel(char c, int bYIsVowel){
  206191. return (
  206192. c=='a' || c=='e' || c=='i' || c=='o' || c=='u' || (bYIsVowel && c=='y')
  206193. );
  206194. }
  206195. static int fts5PorterGobbleVC(char *zStem, int nStem, int bPrevCons){
  206196. int i;
  206197. int bCons = bPrevCons;
  206198. /* Scan for a vowel */
  206199. for(i=0; i<nStem; i++){
  206200. if( 0==(bCons = !fts5PorterIsVowel(zStem[i], bCons)) ) break;
  206201. }
  206202. /* Scan for a consonent */
  206203. for(i++; i<nStem; i++){
  206204. if( (bCons = !fts5PorterIsVowel(zStem[i], bCons)) ) return i+1;
  206205. }
  206206. return 0;
  206207. }
  206208. /* porter rule condition: (m > 0) */
  206209. static int fts5Porter_MGt0(char *zStem, int nStem){
  206210. return !!fts5PorterGobbleVC(zStem, nStem, 0);
  206211. }
  206212. /* porter rule condition: (m > 1) */
  206213. static int fts5Porter_MGt1(char *zStem, int nStem){
  206214. int n;
  206215. n = fts5PorterGobbleVC(zStem, nStem, 0);
  206216. if( n && fts5PorterGobbleVC(&zStem[n], nStem-n, 1) ){
  206217. return 1;
  206218. }
  206219. return 0;
  206220. }
  206221. /* porter rule condition: (m = 1) */
  206222. static int fts5Porter_MEq1(char *zStem, int nStem){
  206223. int n;
  206224. n = fts5PorterGobbleVC(zStem, nStem, 0);
  206225. if( n && 0==fts5PorterGobbleVC(&zStem[n], nStem-n, 1) ){
  206226. return 1;
  206227. }
  206228. return 0;
  206229. }
  206230. /* porter rule condition: (*o) */
  206231. static int fts5Porter_Ostar(char *zStem, int nStem){
  206232. if( zStem[nStem-1]=='w' || zStem[nStem-1]=='x' || zStem[nStem-1]=='y' ){
  206233. return 0;
  206234. }else{
  206235. int i;
  206236. int mask = 0;
  206237. int bCons = 0;
  206238. for(i=0; i<nStem; i++){
  206239. bCons = !fts5PorterIsVowel(zStem[i], bCons);
  206240. assert( bCons==0 || bCons==1 );
  206241. mask = (mask << 1) + bCons;
  206242. }
  206243. return ((mask & 0x0007)==0x0005);
  206244. }
  206245. }
  206246. /* porter rule condition: (m > 1 and (*S or *T)) */
  206247. static int fts5Porter_MGt1_and_S_or_T(char *zStem, int nStem){
  206248. assert( nStem>0 );
  206249. return (zStem[nStem-1]=='s' || zStem[nStem-1]=='t')
  206250. && fts5Porter_MGt1(zStem, nStem);
  206251. }
  206252. /* porter rule condition: (*v*) */
  206253. static int fts5Porter_Vowel(char *zStem, int nStem){
  206254. int i;
  206255. for(i=0; i<nStem; i++){
  206256. if( fts5PorterIsVowel(zStem[i], i>0) ){
  206257. return 1;
  206258. }
  206259. }
  206260. return 0;
  206261. }
  206262. /**************************************************************************
  206263. ***************************************************************************
  206264. ** GENERATED CODE STARTS HERE (mkportersteps.tcl)
  206265. */
  206266. static int fts5PorterStep4(char *aBuf, int *pnBuf){
  206267. int ret = 0;
  206268. int nBuf = *pnBuf;
  206269. switch( aBuf[nBuf-2] ){
  206270. case 'a':
  206271. if( nBuf>2 && 0==memcmp("al", &aBuf[nBuf-2], 2) ){
  206272. if( fts5Porter_MGt1(aBuf, nBuf-2) ){
  206273. *pnBuf = nBuf - 2;
  206274. }
  206275. }
  206276. break;
  206277. case 'c':
  206278. if( nBuf>4 && 0==memcmp("ance", &aBuf[nBuf-4], 4) ){
  206279. if( fts5Porter_MGt1(aBuf, nBuf-4) ){
  206280. *pnBuf = nBuf - 4;
  206281. }
  206282. }else if( nBuf>4 && 0==memcmp("ence", &aBuf[nBuf-4], 4) ){
  206283. if( fts5Porter_MGt1(aBuf, nBuf-4) ){
  206284. *pnBuf = nBuf - 4;
  206285. }
  206286. }
  206287. break;
  206288. case 'e':
  206289. if( nBuf>2 && 0==memcmp("er", &aBuf[nBuf-2], 2) ){
  206290. if( fts5Porter_MGt1(aBuf, nBuf-2) ){
  206291. *pnBuf = nBuf - 2;
  206292. }
  206293. }
  206294. break;
  206295. case 'i':
  206296. if( nBuf>2 && 0==memcmp("ic", &aBuf[nBuf-2], 2) ){
  206297. if( fts5Porter_MGt1(aBuf, nBuf-2) ){
  206298. *pnBuf = nBuf - 2;
  206299. }
  206300. }
  206301. break;
  206302. case 'l':
  206303. if( nBuf>4 && 0==memcmp("able", &aBuf[nBuf-4], 4) ){
  206304. if( fts5Porter_MGt1(aBuf, nBuf-4) ){
  206305. *pnBuf = nBuf - 4;
  206306. }
  206307. }else if( nBuf>4 && 0==memcmp("ible", &aBuf[nBuf-4], 4) ){
  206308. if( fts5Porter_MGt1(aBuf, nBuf-4) ){
  206309. *pnBuf = nBuf - 4;
  206310. }
  206311. }
  206312. break;
  206313. case 'n':
  206314. if( nBuf>3 && 0==memcmp("ant", &aBuf[nBuf-3], 3) ){
  206315. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  206316. *pnBuf = nBuf - 3;
  206317. }
  206318. }else if( nBuf>5 && 0==memcmp("ement", &aBuf[nBuf-5], 5) ){
  206319. if( fts5Porter_MGt1(aBuf, nBuf-5) ){
  206320. *pnBuf = nBuf - 5;
  206321. }
  206322. }else if( nBuf>4 && 0==memcmp("ment", &aBuf[nBuf-4], 4) ){
  206323. if( fts5Porter_MGt1(aBuf, nBuf-4) ){
  206324. *pnBuf = nBuf - 4;
  206325. }
  206326. }else if( nBuf>3 && 0==memcmp("ent", &aBuf[nBuf-3], 3) ){
  206327. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  206328. *pnBuf = nBuf - 3;
  206329. }
  206330. }
  206331. break;
  206332. case 'o':
  206333. if( nBuf>3 && 0==memcmp("ion", &aBuf[nBuf-3], 3) ){
  206334. if( fts5Porter_MGt1_and_S_or_T(aBuf, nBuf-3) ){
  206335. *pnBuf = nBuf - 3;
  206336. }
  206337. }else if( nBuf>2 && 0==memcmp("ou", &aBuf[nBuf-2], 2) ){
  206338. if( fts5Porter_MGt1(aBuf, nBuf-2) ){
  206339. *pnBuf = nBuf - 2;
  206340. }
  206341. }
  206342. break;
  206343. case 's':
  206344. if( nBuf>3 && 0==memcmp("ism", &aBuf[nBuf-3], 3) ){
  206345. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  206346. *pnBuf = nBuf - 3;
  206347. }
  206348. }
  206349. break;
  206350. case 't':
  206351. if( nBuf>3 && 0==memcmp("ate", &aBuf[nBuf-3], 3) ){
  206352. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  206353. *pnBuf = nBuf - 3;
  206354. }
  206355. }else if( nBuf>3 && 0==memcmp("iti", &aBuf[nBuf-3], 3) ){
  206356. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  206357. *pnBuf = nBuf - 3;
  206358. }
  206359. }
  206360. break;
  206361. case 'u':
  206362. if( nBuf>3 && 0==memcmp("ous", &aBuf[nBuf-3], 3) ){
  206363. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  206364. *pnBuf = nBuf - 3;
  206365. }
  206366. }
  206367. break;
  206368. case 'v':
  206369. if( nBuf>3 && 0==memcmp("ive", &aBuf[nBuf-3], 3) ){
  206370. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  206371. *pnBuf = nBuf - 3;
  206372. }
  206373. }
  206374. break;
  206375. case 'z':
  206376. if( nBuf>3 && 0==memcmp("ize", &aBuf[nBuf-3], 3) ){
  206377. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  206378. *pnBuf = nBuf - 3;
  206379. }
  206380. }
  206381. break;
  206382. }
  206383. return ret;
  206384. }
  206385. static int fts5PorterStep1B2(char *aBuf, int *pnBuf){
  206386. int ret = 0;
  206387. int nBuf = *pnBuf;
  206388. switch( aBuf[nBuf-2] ){
  206389. case 'a':
  206390. if( nBuf>2 && 0==memcmp("at", &aBuf[nBuf-2], 2) ){
  206391. memcpy(&aBuf[nBuf-2], "ate", 3);
  206392. *pnBuf = nBuf - 2 + 3;
  206393. ret = 1;
  206394. }
  206395. break;
  206396. case 'b':
  206397. if( nBuf>2 && 0==memcmp("bl", &aBuf[nBuf-2], 2) ){
  206398. memcpy(&aBuf[nBuf-2], "ble", 3);
  206399. *pnBuf = nBuf - 2 + 3;
  206400. ret = 1;
  206401. }
  206402. break;
  206403. case 'i':
  206404. if( nBuf>2 && 0==memcmp("iz", &aBuf[nBuf-2], 2) ){
  206405. memcpy(&aBuf[nBuf-2], "ize", 3);
  206406. *pnBuf = nBuf - 2 + 3;
  206407. ret = 1;
  206408. }
  206409. break;
  206410. }
  206411. return ret;
  206412. }
  206413. static int fts5PorterStep2(char *aBuf, int *pnBuf){
  206414. int ret = 0;
  206415. int nBuf = *pnBuf;
  206416. switch( aBuf[nBuf-2] ){
  206417. case 'a':
  206418. if( nBuf>7 && 0==memcmp("ational", &aBuf[nBuf-7], 7) ){
  206419. if( fts5Porter_MGt0(aBuf, nBuf-7) ){
  206420. memcpy(&aBuf[nBuf-7], "ate", 3);
  206421. *pnBuf = nBuf - 7 + 3;
  206422. }
  206423. }else if( nBuf>6 && 0==memcmp("tional", &aBuf[nBuf-6], 6) ){
  206424. if( fts5Porter_MGt0(aBuf, nBuf-6) ){
  206425. memcpy(&aBuf[nBuf-6], "tion", 4);
  206426. *pnBuf = nBuf - 6 + 4;
  206427. }
  206428. }
  206429. break;
  206430. case 'c':
  206431. if( nBuf>4 && 0==memcmp("enci", &aBuf[nBuf-4], 4) ){
  206432. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  206433. memcpy(&aBuf[nBuf-4], "ence", 4);
  206434. *pnBuf = nBuf - 4 + 4;
  206435. }
  206436. }else if( nBuf>4 && 0==memcmp("anci", &aBuf[nBuf-4], 4) ){
  206437. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  206438. memcpy(&aBuf[nBuf-4], "ance", 4);
  206439. *pnBuf = nBuf - 4 + 4;
  206440. }
  206441. }
  206442. break;
  206443. case 'e':
  206444. if( nBuf>4 && 0==memcmp("izer", &aBuf[nBuf-4], 4) ){
  206445. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  206446. memcpy(&aBuf[nBuf-4], "ize", 3);
  206447. *pnBuf = nBuf - 4 + 3;
  206448. }
  206449. }
  206450. break;
  206451. case 'g':
  206452. if( nBuf>4 && 0==memcmp("logi", &aBuf[nBuf-4], 4) ){
  206453. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  206454. memcpy(&aBuf[nBuf-4], "log", 3);
  206455. *pnBuf = nBuf - 4 + 3;
  206456. }
  206457. }
  206458. break;
  206459. case 'l':
  206460. if( nBuf>3 && 0==memcmp("bli", &aBuf[nBuf-3], 3) ){
  206461. if( fts5Porter_MGt0(aBuf, nBuf-3) ){
  206462. memcpy(&aBuf[nBuf-3], "ble", 3);
  206463. *pnBuf = nBuf - 3 + 3;
  206464. }
  206465. }else if( nBuf>4 && 0==memcmp("alli", &aBuf[nBuf-4], 4) ){
  206466. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  206467. memcpy(&aBuf[nBuf-4], "al", 2);
  206468. *pnBuf = nBuf - 4 + 2;
  206469. }
  206470. }else if( nBuf>5 && 0==memcmp("entli", &aBuf[nBuf-5], 5) ){
  206471. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  206472. memcpy(&aBuf[nBuf-5], "ent", 3);
  206473. *pnBuf = nBuf - 5 + 3;
  206474. }
  206475. }else if( nBuf>3 && 0==memcmp("eli", &aBuf[nBuf-3], 3) ){
  206476. if( fts5Porter_MGt0(aBuf, nBuf-3) ){
  206477. memcpy(&aBuf[nBuf-3], "e", 1);
  206478. *pnBuf = nBuf - 3 + 1;
  206479. }
  206480. }else if( nBuf>5 && 0==memcmp("ousli", &aBuf[nBuf-5], 5) ){
  206481. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  206482. memcpy(&aBuf[nBuf-5], "ous", 3);
  206483. *pnBuf = nBuf - 5 + 3;
  206484. }
  206485. }
  206486. break;
  206487. case 'o':
  206488. if( nBuf>7 && 0==memcmp("ization", &aBuf[nBuf-7], 7) ){
  206489. if( fts5Porter_MGt0(aBuf, nBuf-7) ){
  206490. memcpy(&aBuf[nBuf-7], "ize", 3);
  206491. *pnBuf = nBuf - 7 + 3;
  206492. }
  206493. }else if( nBuf>5 && 0==memcmp("ation", &aBuf[nBuf-5], 5) ){
  206494. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  206495. memcpy(&aBuf[nBuf-5], "ate", 3);
  206496. *pnBuf = nBuf - 5 + 3;
  206497. }
  206498. }else if( nBuf>4 && 0==memcmp("ator", &aBuf[nBuf-4], 4) ){
  206499. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  206500. memcpy(&aBuf[nBuf-4], "ate", 3);
  206501. *pnBuf = nBuf - 4 + 3;
  206502. }
  206503. }
  206504. break;
  206505. case 's':
  206506. if( nBuf>5 && 0==memcmp("alism", &aBuf[nBuf-5], 5) ){
  206507. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  206508. memcpy(&aBuf[nBuf-5], "al", 2);
  206509. *pnBuf = nBuf - 5 + 2;
  206510. }
  206511. }else if( nBuf>7 && 0==memcmp("iveness", &aBuf[nBuf-7], 7) ){
  206512. if( fts5Porter_MGt0(aBuf, nBuf-7) ){
  206513. memcpy(&aBuf[nBuf-7], "ive", 3);
  206514. *pnBuf = nBuf - 7 + 3;
  206515. }
  206516. }else if( nBuf>7 && 0==memcmp("fulness", &aBuf[nBuf-7], 7) ){
  206517. if( fts5Porter_MGt0(aBuf, nBuf-7) ){
  206518. memcpy(&aBuf[nBuf-7], "ful", 3);
  206519. *pnBuf = nBuf - 7 + 3;
  206520. }
  206521. }else if( nBuf>7 && 0==memcmp("ousness", &aBuf[nBuf-7], 7) ){
  206522. if( fts5Porter_MGt0(aBuf, nBuf-7) ){
  206523. memcpy(&aBuf[nBuf-7], "ous", 3);
  206524. *pnBuf = nBuf - 7 + 3;
  206525. }
  206526. }
  206527. break;
  206528. case 't':
  206529. if( nBuf>5 && 0==memcmp("aliti", &aBuf[nBuf-5], 5) ){
  206530. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  206531. memcpy(&aBuf[nBuf-5], "al", 2);
  206532. *pnBuf = nBuf - 5 + 2;
  206533. }
  206534. }else if( nBuf>5 && 0==memcmp("iviti", &aBuf[nBuf-5], 5) ){
  206535. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  206536. memcpy(&aBuf[nBuf-5], "ive", 3);
  206537. *pnBuf = nBuf - 5 + 3;
  206538. }
  206539. }else if( nBuf>6 && 0==memcmp("biliti", &aBuf[nBuf-6], 6) ){
  206540. if( fts5Porter_MGt0(aBuf, nBuf-6) ){
  206541. memcpy(&aBuf[nBuf-6], "ble", 3);
  206542. *pnBuf = nBuf - 6 + 3;
  206543. }
  206544. }
  206545. break;
  206546. }
  206547. return ret;
  206548. }
  206549. static int fts5PorterStep3(char *aBuf, int *pnBuf){
  206550. int ret = 0;
  206551. int nBuf = *pnBuf;
  206552. switch( aBuf[nBuf-2] ){
  206553. case 'a':
  206554. if( nBuf>4 && 0==memcmp("ical", &aBuf[nBuf-4], 4) ){
  206555. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  206556. memcpy(&aBuf[nBuf-4], "ic", 2);
  206557. *pnBuf = nBuf - 4 + 2;
  206558. }
  206559. }
  206560. break;
  206561. case 's':
  206562. if( nBuf>4 && 0==memcmp("ness", &aBuf[nBuf-4], 4) ){
  206563. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  206564. *pnBuf = nBuf - 4;
  206565. }
  206566. }
  206567. break;
  206568. case 't':
  206569. if( nBuf>5 && 0==memcmp("icate", &aBuf[nBuf-5], 5) ){
  206570. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  206571. memcpy(&aBuf[nBuf-5], "ic", 2);
  206572. *pnBuf = nBuf - 5 + 2;
  206573. }
  206574. }else if( nBuf>5 && 0==memcmp("iciti", &aBuf[nBuf-5], 5) ){
  206575. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  206576. memcpy(&aBuf[nBuf-5], "ic", 2);
  206577. *pnBuf = nBuf - 5 + 2;
  206578. }
  206579. }
  206580. break;
  206581. case 'u':
  206582. if( nBuf>3 && 0==memcmp("ful", &aBuf[nBuf-3], 3) ){
  206583. if( fts5Porter_MGt0(aBuf, nBuf-3) ){
  206584. *pnBuf = nBuf - 3;
  206585. }
  206586. }
  206587. break;
  206588. case 'v':
  206589. if( nBuf>5 && 0==memcmp("ative", &aBuf[nBuf-5], 5) ){
  206590. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  206591. *pnBuf = nBuf - 5;
  206592. }
  206593. }
  206594. break;
  206595. case 'z':
  206596. if( nBuf>5 && 0==memcmp("alize", &aBuf[nBuf-5], 5) ){
  206597. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  206598. memcpy(&aBuf[nBuf-5], "al", 2);
  206599. *pnBuf = nBuf - 5 + 2;
  206600. }
  206601. }
  206602. break;
  206603. }
  206604. return ret;
  206605. }
  206606. static int fts5PorterStep1B(char *aBuf, int *pnBuf){
  206607. int ret = 0;
  206608. int nBuf = *pnBuf;
  206609. switch( aBuf[nBuf-2] ){
  206610. case 'e':
  206611. if( nBuf>3 && 0==memcmp("eed", &aBuf[nBuf-3], 3) ){
  206612. if( fts5Porter_MGt0(aBuf, nBuf-3) ){
  206613. memcpy(&aBuf[nBuf-3], "ee", 2);
  206614. *pnBuf = nBuf - 3 + 2;
  206615. }
  206616. }else if( nBuf>2 && 0==memcmp("ed", &aBuf[nBuf-2], 2) ){
  206617. if( fts5Porter_Vowel(aBuf, nBuf-2) ){
  206618. *pnBuf = nBuf - 2;
  206619. ret = 1;
  206620. }
  206621. }
  206622. break;
  206623. case 'n':
  206624. if( nBuf>3 && 0==memcmp("ing", &aBuf[nBuf-3], 3) ){
  206625. if( fts5Porter_Vowel(aBuf, nBuf-3) ){
  206626. *pnBuf = nBuf - 3;
  206627. ret = 1;
  206628. }
  206629. }
  206630. break;
  206631. }
  206632. return ret;
  206633. }
  206634. /*
  206635. ** GENERATED CODE ENDS HERE (mkportersteps.tcl)
  206636. ***************************************************************************
  206637. **************************************************************************/
  206638. static void fts5PorterStep1A(char *aBuf, int *pnBuf){
  206639. int nBuf = *pnBuf;
  206640. if( aBuf[nBuf-1]=='s' ){
  206641. if( aBuf[nBuf-2]=='e' ){
  206642. if( (nBuf>4 && aBuf[nBuf-4]=='s' && aBuf[nBuf-3]=='s')
  206643. || (nBuf>3 && aBuf[nBuf-3]=='i' )
  206644. ){
  206645. *pnBuf = nBuf-2;
  206646. }else{
  206647. *pnBuf = nBuf-1;
  206648. }
  206649. }
  206650. else if( aBuf[nBuf-2]!='s' ){
  206651. *pnBuf = nBuf-1;
  206652. }
  206653. }
  206654. }
  206655. static int fts5PorterCb(
  206656. void *pCtx,
  206657. int tflags,
  206658. const char *pToken,
  206659. int nToken,
  206660. int iStart,
  206661. int iEnd
  206662. ){
  206663. PorterContext *p = (PorterContext*)pCtx;
  206664. char *aBuf;
  206665. int nBuf;
  206666. if( nToken>FTS5_PORTER_MAX_TOKEN || nToken<3 ) goto pass_through;
  206667. aBuf = p->aBuf;
  206668. nBuf = nToken;
  206669. memcpy(aBuf, pToken, nBuf);
  206670. /* Step 1. */
  206671. fts5PorterStep1A(aBuf, &nBuf);
  206672. if( fts5PorterStep1B(aBuf, &nBuf) ){
  206673. if( fts5PorterStep1B2(aBuf, &nBuf)==0 ){
  206674. char c = aBuf[nBuf-1];
  206675. if( fts5PorterIsVowel(c, 0)==0
  206676. && c!='l' && c!='s' && c!='z' && c==aBuf[nBuf-2]
  206677. ){
  206678. nBuf--;
  206679. }else if( fts5Porter_MEq1(aBuf, nBuf) && fts5Porter_Ostar(aBuf, nBuf) ){
  206680. aBuf[nBuf++] = 'e';
  206681. }
  206682. }
  206683. }
  206684. /* Step 1C. */
  206685. if( aBuf[nBuf-1]=='y' && fts5Porter_Vowel(aBuf, nBuf-1) ){
  206686. aBuf[nBuf-1] = 'i';
  206687. }
  206688. /* Steps 2 through 4. */
  206689. fts5PorterStep2(aBuf, &nBuf);
  206690. fts5PorterStep3(aBuf, &nBuf);
  206691. fts5PorterStep4(aBuf, &nBuf);
  206692. /* Step 5a. */
  206693. assert( nBuf>0 );
  206694. if( aBuf[nBuf-1]=='e' ){
  206695. if( fts5Porter_MGt1(aBuf, nBuf-1)
  206696. || (fts5Porter_MEq1(aBuf, nBuf-1) && !fts5Porter_Ostar(aBuf, nBuf-1))
  206697. ){
  206698. nBuf--;
  206699. }
  206700. }
  206701. /* Step 5b. */
  206702. if( nBuf>1 && aBuf[nBuf-1]=='l'
  206703. && aBuf[nBuf-2]=='l' && fts5Porter_MGt1(aBuf, nBuf-1)
  206704. ){
  206705. nBuf--;
  206706. }
  206707. return p->xToken(p->pCtx, tflags, aBuf, nBuf, iStart, iEnd);
  206708. pass_through:
  206709. return p->xToken(p->pCtx, tflags, pToken, nToken, iStart, iEnd);
  206710. }
  206711. /*
  206712. ** Tokenize using the porter tokenizer.
  206713. */
  206714. static int fts5PorterTokenize(
  206715. Fts5Tokenizer *pTokenizer,
  206716. void *pCtx,
  206717. int flags,
  206718. const char *pText, int nText,
  206719. int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
  206720. ){
  206721. PorterTokenizer *p = (PorterTokenizer*)pTokenizer;
  206722. PorterContext sCtx;
  206723. sCtx.xToken = xToken;
  206724. sCtx.pCtx = pCtx;
  206725. sCtx.aBuf = p->aBuf;
  206726. return p->tokenizer.xTokenize(
  206727. p->pTokenizer, (void*)&sCtx, flags, pText, nText, fts5PorterCb
  206728. );
  206729. }
  206730. /*
  206731. ** Register all built-in tokenizers with FTS5.
  206732. */
  206733. static int sqlite3Fts5TokenizerInit(fts5_api *pApi){
  206734. struct BuiltinTokenizer {
  206735. const char *zName;
  206736. fts5_tokenizer x;
  206737. } aBuiltin[] = {
  206738. { "unicode61", {fts5UnicodeCreate, fts5UnicodeDelete, fts5UnicodeTokenize}},
  206739. { "ascii", {fts5AsciiCreate, fts5AsciiDelete, fts5AsciiTokenize }},
  206740. { "porter", {fts5PorterCreate, fts5PorterDelete, fts5PorterTokenize }},
  206741. };
  206742. int rc = SQLITE_OK; /* Return code */
  206743. int i; /* To iterate through builtin functions */
  206744. for(i=0; rc==SQLITE_OK && i<ArraySize(aBuiltin); i++){
  206745. rc = pApi->xCreateTokenizer(pApi,
  206746. aBuiltin[i].zName,
  206747. (void*)pApi,
  206748. &aBuiltin[i].x,
  206749. 0
  206750. );
  206751. }
  206752. return rc;
  206753. }
  206754. /*
  206755. ** 2012-05-25
  206756. **
  206757. ** The author disclaims copyright to this source code. In place of
  206758. ** a legal notice, here is a blessing:
  206759. **
  206760. ** May you do good and not evil.
  206761. ** May you find forgiveness for yourself and forgive others.
  206762. ** May you share freely, never taking more than you give.
  206763. **
  206764. ******************************************************************************
  206765. */
  206766. /*
  206767. ** DO NOT EDIT THIS MACHINE GENERATED FILE.
  206768. */
  206769. /* #include <assert.h> */
  206770. /*
  206771. ** If the argument is a codepoint corresponding to a lowercase letter
  206772. ** in the ASCII range with a diacritic added, return the codepoint
  206773. ** of the ASCII letter only. For example, if passed 235 - "LATIN
  206774. ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
  206775. ** E"). The resuls of passing a codepoint that corresponds to an
  206776. ** uppercase letter are undefined.
  206777. */
  206778. static int fts5_remove_diacritic(int c, int bComplex){
  206779. unsigned short aDia[] = {
  206780. 0, 1797, 1848, 1859, 1891, 1928, 1940, 1995,
  206781. 2024, 2040, 2060, 2110, 2168, 2206, 2264, 2286,
  206782. 2344, 2383, 2472, 2488, 2516, 2596, 2668, 2732,
  206783. 2782, 2842, 2894, 2954, 2984, 3000, 3028, 3336,
  206784. 3456, 3696, 3712, 3728, 3744, 3766, 3832, 3896,
  206785. 3912, 3928, 3944, 3968, 4008, 4040, 4056, 4106,
  206786. 4138, 4170, 4202, 4234, 4266, 4296, 4312, 4344,
  206787. 4408, 4424, 4442, 4472, 4488, 4504, 6148, 6198,
  206788. 6264, 6280, 6360, 6429, 6505, 6529, 61448, 61468,
  206789. 61512, 61534, 61592, 61610, 61642, 61672, 61688, 61704,
  206790. 61726, 61784, 61800, 61816, 61836, 61880, 61896, 61914,
  206791. 61948, 61998, 62062, 62122, 62154, 62184, 62200, 62218,
  206792. 62252, 62302, 62364, 62410, 62442, 62478, 62536, 62554,
  206793. 62584, 62604, 62640, 62648, 62656, 62664, 62730, 62766,
  206794. 62830, 62890, 62924, 62974, 63032, 63050, 63082, 63118,
  206795. 63182, 63242, 63274, 63310, 63368, 63390,
  206796. };
  206797. #define HIBIT ((unsigned char)0x80)
  206798. unsigned char aChar[] = {
  206799. '\0', 'a', 'c', 'e', 'i', 'n',
  206800. 'o', 'u', 'y', 'y', 'a', 'c',
  206801. 'd', 'e', 'e', 'g', 'h', 'i',
  206802. 'j', 'k', 'l', 'n', 'o', 'r',
  206803. 's', 't', 'u', 'u', 'w', 'y',
  206804. 'z', 'o', 'u', 'a', 'i', 'o',
  206805. 'u', 'u'|HIBIT, 'a'|HIBIT, 'g', 'k', 'o',
  206806. 'o'|HIBIT, 'j', 'g', 'n', 'a'|HIBIT, 'a',
  206807. 'e', 'i', 'o', 'r', 'u', 's',
  206808. 't', 'h', 'a', 'e', 'o'|HIBIT, 'o',
  206809. 'o'|HIBIT, 'y', '\0', '\0', '\0', '\0',
  206810. '\0', '\0', '\0', '\0', 'a', 'b',
  206811. 'c'|HIBIT, 'd', 'd', 'e'|HIBIT, 'e', 'e'|HIBIT,
  206812. 'f', 'g', 'h', 'h', 'i', 'i'|HIBIT,
  206813. 'k', 'l', 'l'|HIBIT, 'l', 'm', 'n',
  206814. 'o'|HIBIT, 'p', 'r', 'r'|HIBIT, 'r', 's',
  206815. 's'|HIBIT, 't', 'u', 'u'|HIBIT, 'v', 'w',
  206816. 'w', 'x', 'y', 'z', 'h', 't',
  206817. 'w', 'y', 'a', 'a'|HIBIT, 'a'|HIBIT, 'a'|HIBIT,
  206818. 'e', 'e'|HIBIT, 'e'|HIBIT, 'i', 'o', 'o'|HIBIT,
  206819. 'o'|HIBIT, 'o'|HIBIT, 'u', 'u'|HIBIT, 'u'|HIBIT, 'y',
  206820. };
  206821. unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
  206822. int iRes = 0;
  206823. int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
  206824. int iLo = 0;
  206825. while( iHi>=iLo ){
  206826. int iTest = (iHi + iLo) / 2;
  206827. if( key >= aDia[iTest] ){
  206828. iRes = iTest;
  206829. iLo = iTest+1;
  206830. }else{
  206831. iHi = iTest-1;
  206832. }
  206833. }
  206834. assert( key>=aDia[iRes] );
  206835. if( bComplex==0 && (aChar[iRes] & 0x80) ) return c;
  206836. return (c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : ((int)aChar[iRes] & 0x7F);
  206837. }
  206838. /*
  206839. ** Return true if the argument interpreted as a unicode codepoint
  206840. ** is a diacritical modifier character.
  206841. */
  206842. static int sqlite3Fts5UnicodeIsdiacritic(int c){
  206843. unsigned int mask0 = 0x08029FDF;
  206844. unsigned int mask1 = 0x000361F8;
  206845. if( c<768 || c>817 ) return 0;
  206846. return (c < 768+32) ?
  206847. (mask0 & ((unsigned int)1 << (c-768))) :
  206848. (mask1 & ((unsigned int)1 << (c-768-32)));
  206849. }
  206850. /*
  206851. ** Interpret the argument as a unicode codepoint. If the codepoint
  206852. ** is an upper case character that has a lower case equivalent,
  206853. ** return the codepoint corresponding to the lower case version.
  206854. ** Otherwise, return a copy of the argument.
  206855. **
  206856. ** The results are undefined if the value passed to this function
  206857. ** is less than zero.
  206858. */
  206859. static int sqlite3Fts5UnicodeFold(int c, int eRemoveDiacritic){
  206860. /* Each entry in the following array defines a rule for folding a range
  206861. ** of codepoints to lower case. The rule applies to a range of nRange
  206862. ** codepoints starting at codepoint iCode.
  206863. **
  206864. ** If the least significant bit in flags is clear, then the rule applies
  206865. ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
  206866. ** need to be folded). Or, if it is set, then the rule only applies to
  206867. ** every second codepoint in the range, starting with codepoint C.
  206868. **
  206869. ** The 7 most significant bits in flags are an index into the aiOff[]
  206870. ** array. If a specific codepoint C does require folding, then its lower
  206871. ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
  206872. **
  206873. ** The contents of this array are generated by parsing the CaseFolding.txt
  206874. ** file distributed as part of the "Unicode Character Database". See
  206875. ** http://www.unicode.org for details.
  206876. */
  206877. static const struct TableEntry {
  206878. unsigned short iCode;
  206879. unsigned char flags;
  206880. unsigned char nRange;
  206881. } aEntry[] = {
  206882. {65, 14, 26}, {181, 64, 1}, {192, 14, 23},
  206883. {216, 14, 7}, {256, 1, 48}, {306, 1, 6},
  206884. {313, 1, 16}, {330, 1, 46}, {376, 116, 1},
  206885. {377, 1, 6}, {383, 104, 1}, {385, 50, 1},
  206886. {386, 1, 4}, {390, 44, 1}, {391, 0, 1},
  206887. {393, 42, 2}, {395, 0, 1}, {398, 32, 1},
  206888. {399, 38, 1}, {400, 40, 1}, {401, 0, 1},
  206889. {403, 42, 1}, {404, 46, 1}, {406, 52, 1},
  206890. {407, 48, 1}, {408, 0, 1}, {412, 52, 1},
  206891. {413, 54, 1}, {415, 56, 1}, {416, 1, 6},
  206892. {422, 60, 1}, {423, 0, 1}, {425, 60, 1},
  206893. {428, 0, 1}, {430, 60, 1}, {431, 0, 1},
  206894. {433, 58, 2}, {435, 1, 4}, {439, 62, 1},
  206895. {440, 0, 1}, {444, 0, 1}, {452, 2, 1},
  206896. {453, 0, 1}, {455, 2, 1}, {456, 0, 1},
  206897. {458, 2, 1}, {459, 1, 18}, {478, 1, 18},
  206898. {497, 2, 1}, {498, 1, 4}, {502, 122, 1},
  206899. {503, 134, 1}, {504, 1, 40}, {544, 110, 1},
  206900. {546, 1, 18}, {570, 70, 1}, {571, 0, 1},
  206901. {573, 108, 1}, {574, 68, 1}, {577, 0, 1},
  206902. {579, 106, 1}, {580, 28, 1}, {581, 30, 1},
  206903. {582, 1, 10}, {837, 36, 1}, {880, 1, 4},
  206904. {886, 0, 1}, {902, 18, 1}, {904, 16, 3},
  206905. {908, 26, 1}, {910, 24, 2}, {913, 14, 17},
  206906. {931, 14, 9}, {962, 0, 1}, {975, 4, 1},
  206907. {976, 140, 1}, {977, 142, 1}, {981, 146, 1},
  206908. {982, 144, 1}, {984, 1, 24}, {1008, 136, 1},
  206909. {1009, 138, 1}, {1012, 130, 1}, {1013, 128, 1},
  206910. {1015, 0, 1}, {1017, 152, 1}, {1018, 0, 1},
  206911. {1021, 110, 3}, {1024, 34, 16}, {1040, 14, 32},
  206912. {1120, 1, 34}, {1162, 1, 54}, {1216, 6, 1},
  206913. {1217, 1, 14}, {1232, 1, 88}, {1329, 22, 38},
  206914. {4256, 66, 38}, {4295, 66, 1}, {4301, 66, 1},
  206915. {7680, 1, 150}, {7835, 132, 1}, {7838, 96, 1},
  206916. {7840, 1, 96}, {7944, 150, 8}, {7960, 150, 6},
  206917. {7976, 150, 8}, {7992, 150, 8}, {8008, 150, 6},
  206918. {8025, 151, 8}, {8040, 150, 8}, {8072, 150, 8},
  206919. {8088, 150, 8}, {8104, 150, 8}, {8120, 150, 2},
  206920. {8122, 126, 2}, {8124, 148, 1}, {8126, 100, 1},
  206921. {8136, 124, 4}, {8140, 148, 1}, {8152, 150, 2},
  206922. {8154, 120, 2}, {8168, 150, 2}, {8170, 118, 2},
  206923. {8172, 152, 1}, {8184, 112, 2}, {8186, 114, 2},
  206924. {8188, 148, 1}, {8486, 98, 1}, {8490, 92, 1},
  206925. {8491, 94, 1}, {8498, 12, 1}, {8544, 8, 16},
  206926. {8579, 0, 1}, {9398, 10, 26}, {11264, 22, 47},
  206927. {11360, 0, 1}, {11362, 88, 1}, {11363, 102, 1},
  206928. {11364, 90, 1}, {11367, 1, 6}, {11373, 84, 1},
  206929. {11374, 86, 1}, {11375, 80, 1}, {11376, 82, 1},
  206930. {11378, 0, 1}, {11381, 0, 1}, {11390, 78, 2},
  206931. {11392, 1, 100}, {11499, 1, 4}, {11506, 0, 1},
  206932. {42560, 1, 46}, {42624, 1, 24}, {42786, 1, 14},
  206933. {42802, 1, 62}, {42873, 1, 4}, {42877, 76, 1},
  206934. {42878, 1, 10}, {42891, 0, 1}, {42893, 74, 1},
  206935. {42896, 1, 4}, {42912, 1, 10}, {42922, 72, 1},
  206936. {65313, 14, 26},
  206937. };
  206938. static const unsigned short aiOff[] = {
  206939. 1, 2, 8, 15, 16, 26, 28, 32,
  206940. 37, 38, 40, 48, 63, 64, 69, 71,
  206941. 79, 80, 116, 202, 203, 205, 206, 207,
  206942. 209, 210, 211, 213, 214, 217, 218, 219,
  206943. 775, 7264, 10792, 10795, 23228, 23256, 30204, 54721,
  206944. 54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
  206945. 57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
  206946. 65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
  206947. 65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
  206948. 65514, 65521, 65527, 65528, 65529,
  206949. };
  206950. int ret = c;
  206951. assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
  206952. if( c<128 ){
  206953. if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
  206954. }else if( c<65536 ){
  206955. const struct TableEntry *p;
  206956. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  206957. int iLo = 0;
  206958. int iRes = -1;
  206959. assert( c>aEntry[0].iCode );
  206960. while( iHi>=iLo ){
  206961. int iTest = (iHi + iLo) / 2;
  206962. int cmp = (c - aEntry[iTest].iCode);
  206963. if( cmp>=0 ){
  206964. iRes = iTest;
  206965. iLo = iTest+1;
  206966. }else{
  206967. iHi = iTest-1;
  206968. }
  206969. }
  206970. assert( iRes>=0 && c>=aEntry[iRes].iCode );
  206971. p = &aEntry[iRes];
  206972. if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
  206973. ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
  206974. assert( ret>0 );
  206975. }
  206976. if( eRemoveDiacritic ){
  206977. ret = fts5_remove_diacritic(ret, eRemoveDiacritic==2);
  206978. }
  206979. }
  206980. else if( c>=66560 && c<66600 ){
  206981. ret = c + 40;
  206982. }
  206983. return ret;
  206984. }
  206985. static int sqlite3Fts5UnicodeCatParse(const char *zCat, u8 *aArray){
  206986. aArray[0] = 1;
  206987. switch( zCat[0] ){
  206988. case 'C':
  206989. switch( zCat[1] ){
  206990. case 'c': aArray[1] = 1; break;
  206991. case 'f': aArray[2] = 1; break;
  206992. case 'n': aArray[3] = 1; break;
  206993. case 's': aArray[4] = 1; break;
  206994. case 'o': aArray[31] = 1; break;
  206995. case '*':
  206996. aArray[1] = 1;
  206997. aArray[2] = 1;
  206998. aArray[3] = 1;
  206999. aArray[4] = 1;
  207000. aArray[31] = 1;
  207001. break;
  207002. default: return 1; }
  207003. break;
  207004. case 'L':
  207005. switch( zCat[1] ){
  207006. case 'l': aArray[5] = 1; break;
  207007. case 'm': aArray[6] = 1; break;
  207008. case 'o': aArray[7] = 1; break;
  207009. case 't': aArray[8] = 1; break;
  207010. case 'u': aArray[9] = 1; break;
  207011. case 'C': aArray[30] = 1; break;
  207012. case '*':
  207013. aArray[5] = 1;
  207014. aArray[6] = 1;
  207015. aArray[7] = 1;
  207016. aArray[8] = 1;
  207017. aArray[9] = 1;
  207018. aArray[30] = 1;
  207019. break;
  207020. default: return 1; }
  207021. break;
  207022. case 'M':
  207023. switch( zCat[1] ){
  207024. case 'c': aArray[10] = 1; break;
  207025. case 'e': aArray[11] = 1; break;
  207026. case 'n': aArray[12] = 1; break;
  207027. case '*':
  207028. aArray[10] = 1;
  207029. aArray[11] = 1;
  207030. aArray[12] = 1;
  207031. break;
  207032. default: return 1; }
  207033. break;
  207034. case 'N':
  207035. switch( zCat[1] ){
  207036. case 'd': aArray[13] = 1; break;
  207037. case 'l': aArray[14] = 1; break;
  207038. case 'o': aArray[15] = 1; break;
  207039. case '*':
  207040. aArray[13] = 1;
  207041. aArray[14] = 1;
  207042. aArray[15] = 1;
  207043. break;
  207044. default: return 1; }
  207045. break;
  207046. case 'P':
  207047. switch( zCat[1] ){
  207048. case 'c': aArray[16] = 1; break;
  207049. case 'd': aArray[17] = 1; break;
  207050. case 'e': aArray[18] = 1; break;
  207051. case 'f': aArray[19] = 1; break;
  207052. case 'i': aArray[20] = 1; break;
  207053. case 'o': aArray[21] = 1; break;
  207054. case 's': aArray[22] = 1; break;
  207055. case '*':
  207056. aArray[16] = 1;
  207057. aArray[17] = 1;
  207058. aArray[18] = 1;
  207059. aArray[19] = 1;
  207060. aArray[20] = 1;
  207061. aArray[21] = 1;
  207062. aArray[22] = 1;
  207063. break;
  207064. default: return 1; }
  207065. break;
  207066. case 'S':
  207067. switch( zCat[1] ){
  207068. case 'c': aArray[23] = 1; break;
  207069. case 'k': aArray[24] = 1; break;
  207070. case 'm': aArray[25] = 1; break;
  207071. case 'o': aArray[26] = 1; break;
  207072. case '*':
  207073. aArray[23] = 1;
  207074. aArray[24] = 1;
  207075. aArray[25] = 1;
  207076. aArray[26] = 1;
  207077. break;
  207078. default: return 1; }
  207079. break;
  207080. case 'Z':
  207081. switch( zCat[1] ){
  207082. case 'l': aArray[27] = 1; break;
  207083. case 'p': aArray[28] = 1; break;
  207084. case 's': aArray[29] = 1; break;
  207085. case '*':
  207086. aArray[27] = 1;
  207087. aArray[28] = 1;
  207088. aArray[29] = 1;
  207089. break;
  207090. default: return 1; }
  207091. break;
  207092. }
  207093. return 0;
  207094. }
  207095. static u16 aFts5UnicodeBlock[] = {
  207096. 0, 1471, 1753, 1760, 1760, 1760, 1760, 1760, 1760, 1760,
  207097. 1760, 1760, 1760, 1760, 1760, 1763, 1765,
  207098. };
  207099. static u16 aFts5UnicodeMap[] = {
  207100. 0, 32, 33, 36, 37, 40, 41, 42, 43, 44,
  207101. 45, 46, 48, 58, 60, 63, 65, 91, 92, 93,
  207102. 94, 95, 96, 97, 123, 124, 125, 126, 127, 160,
  207103. 161, 162, 166, 167, 168, 169, 170, 171, 172, 173,
  207104. 174, 175, 176, 177, 178, 180, 181, 182, 184, 185,
  207105. 186, 187, 188, 191, 192, 215, 216, 223, 247, 248,
  207106. 256, 312, 313, 329, 330, 377, 383, 385, 387, 388,
  207107. 391, 394, 396, 398, 402, 403, 405, 406, 409, 412,
  207108. 414, 415, 417, 418, 423, 427, 428, 431, 434, 436,
  207109. 437, 440, 442, 443, 444, 446, 448, 452, 453, 454,
  207110. 455, 456, 457, 458, 459, 460, 461, 477, 478, 496,
  207111. 497, 498, 499, 500, 503, 505, 506, 564, 570, 572,
  207112. 573, 575, 577, 580, 583, 584, 592, 660, 661, 688,
  207113. 706, 710, 722, 736, 741, 748, 749, 750, 751, 768,
  207114. 880, 884, 885, 886, 890, 891, 894, 900, 902, 903,
  207115. 904, 908, 910, 912, 913, 931, 940, 975, 977, 978,
  207116. 981, 984, 1008, 1012, 1014, 1015, 1018, 1020, 1021, 1072,
  207117. 1120, 1154, 1155, 1160, 1162, 1217, 1231, 1232, 1329, 1369,
  207118. 1370, 1377, 1417, 1418, 1423, 1425, 1470, 1471, 1472, 1473,
  207119. 1475, 1476, 1478, 1479, 1488, 1520, 1523, 1536, 1542, 1545,
  207120. 1547, 1548, 1550, 1552, 1563, 1566, 1568, 1600, 1601, 1611,
  207121. 1632, 1642, 1646, 1648, 1649, 1748, 1749, 1750, 1757, 1758,
  207122. 1759, 1765, 1767, 1769, 1770, 1774, 1776, 1786, 1789, 1791,
  207123. 1792, 1807, 1808, 1809, 1810, 1840, 1869, 1958, 1969, 1984,
  207124. 1994, 2027, 2036, 2038, 2039, 2042, 2048, 2070, 2074, 2075,
  207125. 2084, 2085, 2088, 2089, 2096, 2112, 2137, 2142, 2208, 2210,
  207126. 2276, 2304, 2307, 2308, 2362, 2363, 2364, 2365, 2366, 2369,
  207127. 2377, 2381, 2382, 2384, 2385, 2392, 2402, 2404, 2406, 2416,
  207128. 2417, 2418, 2425, 2433, 2434, 2437, 2447, 2451, 2474, 2482,
  207129. 2486, 2492, 2493, 2494, 2497, 2503, 2507, 2509, 2510, 2519,
  207130. 2524, 2527, 2530, 2534, 2544, 2546, 2548, 2554, 2555, 2561,
  207131. 2563, 2565, 2575, 2579, 2602, 2610, 2613, 2616, 2620, 2622,
  207132. 2625, 2631, 2635, 2641, 2649, 2654, 2662, 2672, 2674, 2677,
  207133. 2689, 2691, 2693, 2703, 2707, 2730, 2738, 2741, 2748, 2749,
  207134. 2750, 2753, 2759, 2761, 2763, 2765, 2768, 2784, 2786, 2790,
  207135. 2800, 2801, 2817, 2818, 2821, 2831, 2835, 2858, 2866, 2869,
  207136. 2876, 2877, 2878, 2879, 2880, 2881, 2887, 2891, 2893, 2902,
  207137. 2903, 2908, 2911, 2914, 2918, 2928, 2929, 2930, 2946, 2947,
  207138. 2949, 2958, 2962, 2969, 2972, 2974, 2979, 2984, 2990, 3006,
  207139. 3008, 3009, 3014, 3018, 3021, 3024, 3031, 3046, 3056, 3059,
  207140. 3065, 3066, 3073, 3077, 3086, 3090, 3114, 3125, 3133, 3134,
  207141. 3137, 3142, 3146, 3157, 3160, 3168, 3170, 3174, 3192, 3199,
  207142. 3202, 3205, 3214, 3218, 3242, 3253, 3260, 3261, 3262, 3263,
  207143. 3264, 3270, 3271, 3274, 3276, 3285, 3294, 3296, 3298, 3302,
  207144. 3313, 3330, 3333, 3342, 3346, 3389, 3390, 3393, 3398, 3402,
  207145. 3405, 3406, 3415, 3424, 3426, 3430, 3440, 3449, 3450, 3458,
  207146. 3461, 3482, 3507, 3517, 3520, 3530, 3535, 3538, 3542, 3544,
  207147. 3570, 3572, 3585, 3633, 3634, 3636, 3647, 3648, 3654, 3655,
  207148. 3663, 3664, 3674, 3713, 3716, 3719, 3722, 3725, 3732, 3737,
  207149. 3745, 3749, 3751, 3754, 3757, 3761, 3762, 3764, 3771, 3773,
  207150. 3776, 3782, 3784, 3792, 3804, 3840, 3841, 3844, 3859, 3860,
  207151. 3861, 3864, 3866, 3872, 3882, 3892, 3893, 3894, 3895, 3896,
  207152. 3897, 3898, 3899, 3900, 3901, 3902, 3904, 3913, 3953, 3967,
  207153. 3968, 3973, 3974, 3976, 3981, 3993, 4030, 4038, 4039, 4046,
  207154. 4048, 4053, 4057, 4096, 4139, 4141, 4145, 4146, 4152, 4153,
  207155. 4155, 4157, 4159, 4160, 4170, 4176, 4182, 4184, 4186, 4190,
  207156. 4193, 4194, 4197, 4199, 4206, 4209, 4213, 4226, 4227, 4229,
  207157. 4231, 4237, 4238, 4239, 4240, 4250, 4253, 4254, 4256, 4295,
  207158. 4301, 4304, 4347, 4348, 4349, 4682, 4688, 4696, 4698, 4704,
  207159. 4746, 4752, 4786, 4792, 4800, 4802, 4808, 4824, 4882, 4888,
  207160. 4957, 4960, 4969, 4992, 5008, 5024, 5120, 5121, 5741, 5743,
  207161. 5760, 5761, 5787, 5788, 5792, 5867, 5870, 5888, 5902, 5906,
  207162. 5920, 5938, 5941, 5952, 5970, 5984, 5998, 6002, 6016, 6068,
  207163. 6070, 6071, 6078, 6086, 6087, 6089, 6100, 6103, 6104, 6107,
  207164. 6108, 6109, 6112, 6128, 6144, 6150, 6151, 6155, 6158, 6160,
  207165. 6176, 6211, 6212, 6272, 6313, 6314, 6320, 6400, 6432, 6435,
  207166. 6439, 6441, 6448, 6450, 6451, 6457, 6464, 6468, 6470, 6480,
  207167. 6512, 6528, 6576, 6593, 6600, 6608, 6618, 6622, 6656, 6679,
  207168. 6681, 6686, 6688, 6741, 6742, 6743, 6744, 6752, 6753, 6754,
  207169. 6755, 6757, 6765, 6771, 6783, 6784, 6800, 6816, 6823, 6824,
  207170. 6912, 6916, 6917, 6964, 6965, 6966, 6971, 6972, 6973, 6978,
  207171. 6979, 6981, 6992, 7002, 7009, 7019, 7028, 7040, 7042, 7043,
  207172. 7073, 7074, 7078, 7080, 7082, 7083, 7084, 7086, 7088, 7098,
  207173. 7142, 7143, 7144, 7146, 7149, 7150, 7151, 7154, 7164, 7168,
  207174. 7204, 7212, 7220, 7222, 7227, 7232, 7245, 7248, 7258, 7288,
  207175. 7294, 7360, 7376, 7379, 7380, 7393, 7394, 7401, 7405, 7406,
  207176. 7410, 7412, 7413, 7424, 7468, 7531, 7544, 7545, 7579, 7616,
  207177. 7676, 7680, 7830, 7838, 7936, 7944, 7952, 7960, 7968, 7976,
  207178. 7984, 7992, 8000, 8008, 8016, 8025, 8027, 8029, 8031, 8033,
  207179. 8040, 8048, 8064, 8072, 8080, 8088, 8096, 8104, 8112, 8118,
  207180. 8120, 8124, 8125, 8126, 8127, 8130, 8134, 8136, 8140, 8141,
  207181. 8144, 8150, 8152, 8157, 8160, 8168, 8173, 8178, 8182, 8184,
  207182. 8188, 8189, 8192, 8203, 8208, 8214, 8216, 8217, 8218, 8219,
  207183. 8221, 8222, 8223, 8224, 8232, 8233, 8234, 8239, 8240, 8249,
  207184. 8250, 8251, 8255, 8257, 8260, 8261, 8262, 8263, 8274, 8275,
  207185. 8276, 8277, 8287, 8288, 8298, 8304, 8305, 8308, 8314, 8317,
  207186. 8318, 8319, 8320, 8330, 8333, 8334, 8336, 8352, 8400, 8413,
  207187. 8417, 8418, 8421, 8448, 8450, 8451, 8455, 8456, 8458, 8459,
  207188. 8462, 8464, 8467, 8468, 8469, 8470, 8472, 8473, 8478, 8484,
  207189. 8485, 8486, 8487, 8488, 8489, 8490, 8494, 8495, 8496, 8500,
  207190. 8501, 8505, 8506, 8508, 8510, 8512, 8517, 8519, 8522, 8523,
  207191. 8524, 8526, 8527, 8528, 8544, 8579, 8581, 8585, 8592, 8597,
  207192. 8602, 8604, 8608, 8609, 8611, 8612, 8614, 8615, 8622, 8623,
  207193. 8654, 8656, 8658, 8659, 8660, 8661, 8692, 8960, 8968, 8972,
  207194. 8992, 8994, 9001, 9002, 9003, 9084, 9085, 9115, 9140, 9180,
  207195. 9186, 9216, 9280, 9312, 9372, 9450, 9472, 9655, 9656, 9665,
  207196. 9666, 9720, 9728, 9839, 9840, 9985, 10088, 10089, 10090, 10091,
  207197. 10092, 10093, 10094, 10095, 10096, 10097, 10098, 10099, 10100, 10101,
  207198. 10102, 10132, 10176, 10181, 10182, 10183, 10214, 10215, 10216, 10217,
  207199. 10218, 10219, 10220, 10221, 10222, 10223, 10224, 10240, 10496, 10627,
  207200. 10628, 10629, 10630, 10631, 10632, 10633, 10634, 10635, 10636, 10637,
  207201. 10638, 10639, 10640, 10641, 10642, 10643, 10644, 10645, 10646, 10647,
  207202. 10648, 10649, 10712, 10713, 10714, 10715, 10716, 10748, 10749, 10750,
  207203. 11008, 11056, 11077, 11079, 11088, 11264, 11312, 11360, 11363, 11365,
  207204. 11367, 11374, 11377, 11378, 11380, 11381, 11383, 11388, 11390, 11393,
  207205. 11394, 11492, 11493, 11499, 11503, 11506, 11513, 11517, 11518, 11520,
  207206. 11559, 11565, 11568, 11631, 11632, 11647, 11648, 11680, 11688, 11696,
  207207. 11704, 11712, 11720, 11728, 11736, 11744, 11776, 11778, 11779, 11780,
  207208. 11781, 11782, 11785, 11786, 11787, 11788, 11789, 11790, 11799, 11800,
  207209. 11802, 11803, 11804, 11805, 11806, 11808, 11809, 11810, 11811, 11812,
  207210. 11813, 11814, 11815, 11816, 11817, 11818, 11823, 11824, 11834, 11904,
  207211. 11931, 12032, 12272, 12288, 12289, 12292, 12293, 12294, 12295, 12296,
  207212. 12297, 12298, 12299, 12300, 12301, 12302, 12303, 12304, 12305, 12306,
  207213. 12308, 12309, 12310, 12311, 12312, 12313, 12314, 12315, 12316, 12317,
  207214. 12318, 12320, 12321, 12330, 12334, 12336, 12337, 12342, 12344, 12347,
  207215. 12348, 12349, 12350, 12353, 12441, 12443, 12445, 12447, 12448, 12449,
  207216. 12539, 12540, 12543, 12549, 12593, 12688, 12690, 12694, 12704, 12736,
  207217. 12784, 12800, 12832, 12842, 12872, 12880, 12881, 12896, 12928, 12938,
  207218. 12977, 12992, 13056, 13312, 19893, 19904, 19968, 40908, 40960, 40981,
  207219. 40982, 42128, 42192, 42232, 42238, 42240, 42508, 42509, 42512, 42528,
  207220. 42538, 42560, 42606, 42607, 42608, 42611, 42612, 42622, 42623, 42624,
  207221. 42655, 42656, 42726, 42736, 42738, 42752, 42775, 42784, 42786, 42800,
  207222. 42802, 42864, 42865, 42873, 42878, 42888, 42889, 42891, 42896, 42912,
  207223. 43000, 43002, 43003, 43010, 43011, 43014, 43015, 43019, 43020, 43043,
  207224. 43045, 43047, 43048, 43056, 43062, 43064, 43065, 43072, 43124, 43136,
  207225. 43138, 43188, 43204, 43214, 43216, 43232, 43250, 43256, 43259, 43264,
  207226. 43274, 43302, 43310, 43312, 43335, 43346, 43359, 43360, 43392, 43395,
  207227. 43396, 43443, 43444, 43446, 43450, 43452, 43453, 43457, 43471, 43472,
  207228. 43486, 43520, 43561, 43567, 43569, 43571, 43573, 43584, 43587, 43588,
  207229. 43596, 43597, 43600, 43612, 43616, 43632, 43633, 43639, 43642, 43643,
  207230. 43648, 43696, 43697, 43698, 43701, 43703, 43705, 43710, 43712, 43713,
  207231. 43714, 43739, 43741, 43742, 43744, 43755, 43756, 43758, 43760, 43762,
  207232. 43763, 43765, 43766, 43777, 43785, 43793, 43808, 43816, 43968, 44003,
  207233. 44005, 44006, 44008, 44009, 44011, 44012, 44013, 44016, 44032, 55203,
  207234. 55216, 55243, 55296, 56191, 56319, 57343, 57344, 63743, 63744, 64112,
  207235. 64256, 64275, 64285, 64286, 64287, 64297, 64298, 64312, 64318, 64320,
  207236. 64323, 64326, 64434, 64467, 64830, 64831, 64848, 64914, 65008, 65020,
  207237. 65021, 65024, 65040, 65047, 65048, 65049, 65056, 65072, 65073, 65075,
  207238. 65077, 65078, 65079, 65080, 65081, 65082, 65083, 65084, 65085, 65086,
  207239. 65087, 65088, 65089, 65090, 65091, 65092, 65093, 65095, 65096, 65097,
  207240. 65101, 65104, 65108, 65112, 65113, 65114, 65115, 65116, 65117, 65118,
  207241. 65119, 65122, 65123, 65124, 65128, 65129, 65130, 65136, 65142, 65279,
  207242. 65281, 65284, 65285, 65288, 65289, 65290, 65291, 65292, 65293, 65294,
  207243. 65296, 65306, 65308, 65311, 65313, 65339, 65340, 65341, 65342, 65343,
  207244. 65344, 65345, 65371, 65372, 65373, 65374, 65375, 65376, 65377, 65378,
  207245. 65379, 65380, 65382, 65392, 65393, 65438, 65440, 65474, 65482, 65490,
  207246. 65498, 65504, 65506, 65507, 65508, 65509, 65512, 65513, 65517, 65529,
  207247. 65532, 0, 13, 40, 60, 63, 80, 128, 256, 263,
  207248. 311, 320, 373, 377, 394, 400, 464, 509, 640, 672,
  207249. 768, 800, 816, 833, 834, 842, 896, 927, 928, 968,
  207250. 976, 977, 1024, 1064, 1104, 1184, 2048, 2056, 2058, 2103,
  207251. 2108, 2111, 2135, 2136, 2304, 2326, 2335, 2336, 2367, 2432,
  207252. 2494, 2560, 2561, 2565, 2572, 2576, 2581, 2585, 2616, 2623,
  207253. 2624, 2640, 2656, 2685, 2687, 2816, 2873, 2880, 2904, 2912,
  207254. 2936, 3072, 3680, 4096, 4097, 4098, 4099, 4152, 4167, 4178,
  207255. 4198, 4224, 4226, 4227, 4272, 4275, 4279, 4281, 4283, 4285,
  207256. 4286, 4304, 4336, 4352, 4355, 4391, 4396, 4397, 4406, 4416,
  207257. 4480, 4482, 4483, 4531, 4534, 4543, 4545, 4549, 4560, 5760,
  207258. 5803, 5804, 5805, 5806, 5808, 5814, 5815, 5824, 8192, 9216,
  207259. 9328, 12288, 26624, 28416, 28496, 28497, 28559, 28563, 45056, 53248,
  207260. 53504, 53545, 53605, 53607, 53610, 53613, 53619, 53627, 53635, 53637,
  207261. 53644, 53674, 53678, 53760, 53826, 53829, 54016, 54112, 54272, 54298,
  207262. 54324, 54350, 54358, 54376, 54402, 54428, 54430, 54434, 54437, 54441,
  207263. 54446, 54454, 54459, 54461, 54469, 54480, 54506, 54532, 54535, 54541,
  207264. 54550, 54558, 54584, 54587, 54592, 54598, 54602, 54610, 54636, 54662,
  207265. 54688, 54714, 54740, 54766, 54792, 54818, 54844, 54870, 54896, 54922,
  207266. 54952, 54977, 54978, 55003, 55004, 55010, 55035, 55036, 55061, 55062,
  207267. 55068, 55093, 55094, 55119, 55120, 55126, 55151, 55152, 55177, 55178,
  207268. 55184, 55209, 55210, 55235, 55236, 55242, 55246, 60928, 60933, 60961,
  207269. 60964, 60967, 60969, 60980, 60985, 60987, 60994, 60999, 61001, 61003,
  207270. 61005, 61009, 61012, 61015, 61017, 61019, 61021, 61023, 61025, 61028,
  207271. 61031, 61036, 61044, 61049, 61054, 61056, 61067, 61089, 61093, 61099,
  207272. 61168, 61440, 61488, 61600, 61617, 61633, 61649, 61696, 61712, 61744,
  207273. 61808, 61926, 61968, 62016, 62032, 62208, 62256, 62263, 62336, 62368,
  207274. 62406, 62432, 62464, 62528, 62530, 62713, 62720, 62784, 62800, 62971,
  207275. 63045, 63104, 63232, 0, 42710, 42752, 46900, 46912, 47133, 63488,
  207276. 1, 32, 256, 0, 65533,
  207277. };
  207278. static u16 aFts5UnicodeData[] = {
  207279. 1025, 61, 117, 55, 117, 54, 50, 53, 57, 53,
  207280. 49, 85, 333, 85, 121, 85, 841, 54, 53, 50,
  207281. 56, 48, 56, 837, 54, 57, 50, 57, 1057, 61,
  207282. 53, 151, 58, 53, 56, 58, 39, 52, 57, 34,
  207283. 58, 56, 58, 57, 79, 56, 37, 85, 56, 47,
  207284. 39, 51, 111, 53, 745, 57, 233, 773, 57, 261,
  207285. 1822, 37, 542, 37, 1534, 222, 69, 73, 37, 126,
  207286. 126, 73, 69, 137, 37, 73, 37, 105, 101, 73,
  207287. 37, 73, 37, 190, 158, 37, 126, 126, 73, 37,
  207288. 126, 94, 37, 39, 94, 69, 135, 41, 40, 37,
  207289. 41, 40, 37, 41, 40, 37, 542, 37, 606, 37,
  207290. 41, 40, 37, 126, 73, 37, 1886, 197, 73, 37,
  207291. 73, 69, 126, 105, 37, 286, 2181, 39, 869, 582,
  207292. 152, 390, 472, 166, 248, 38, 56, 38, 568, 3596,
  207293. 158, 38, 56, 94, 38, 101, 53, 88, 41, 53,
  207294. 105, 41, 73, 37, 553, 297, 1125, 94, 37, 105,
  207295. 101, 798, 133, 94, 57, 126, 94, 37, 1641, 1541,
  207296. 1118, 58, 172, 75, 1790, 478, 37, 2846, 1225, 38,
  207297. 213, 1253, 53, 49, 55, 1452, 49, 44, 53, 76,
  207298. 53, 76, 53, 44, 871, 103, 85, 162, 121, 85,
  207299. 55, 85, 90, 364, 53, 85, 1031, 38, 327, 684,
  207300. 333, 149, 71, 44, 3175, 53, 39, 236, 34, 58,
  207301. 204, 70, 76, 58, 140, 71, 333, 103, 90, 39,
  207302. 469, 34, 39, 44, 967, 876, 2855, 364, 39, 333,
  207303. 1063, 300, 70, 58, 117, 38, 711, 140, 38, 300,
  207304. 38, 108, 38, 172, 501, 807, 108, 53, 39, 359,
  207305. 876, 108, 42, 1735, 44, 42, 44, 39, 106, 268,
  207306. 138, 44, 74, 39, 236, 327, 76, 85, 333, 53,
  207307. 38, 199, 231, 44, 74, 263, 71, 711, 231, 39,
  207308. 135, 44, 39, 106, 140, 74, 74, 44, 39, 42,
  207309. 71, 103, 76, 333, 71, 87, 207, 58, 55, 76,
  207310. 42, 199, 71, 711, 231, 71, 71, 71, 44, 106,
  207311. 76, 76, 108, 44, 135, 39, 333, 76, 103, 44,
  207312. 76, 42, 295, 103, 711, 231, 71, 167, 44, 39,
  207313. 106, 172, 76, 42, 74, 44, 39, 71, 76, 333,
  207314. 53, 55, 44, 74, 263, 71, 711, 231, 71, 167,
  207315. 44, 39, 42, 44, 42, 140, 74, 74, 44, 44,
  207316. 42, 71, 103, 76, 333, 58, 39, 207, 44, 39,
  207317. 199, 103, 135, 71, 39, 71, 71, 103, 391, 74,
  207318. 44, 74, 106, 106, 44, 39, 42, 333, 111, 218,
  207319. 55, 58, 106, 263, 103, 743, 327, 167, 39, 108,
  207320. 138, 108, 140, 76, 71, 71, 76, 333, 239, 58,
  207321. 74, 263, 103, 743, 327, 167, 44, 39, 42, 44,
  207322. 170, 44, 74, 74, 76, 74, 39, 71, 76, 333,
  207323. 71, 74, 263, 103, 1319, 39, 106, 140, 106, 106,
  207324. 44, 39, 42, 71, 76, 333, 207, 58, 199, 74,
  207325. 583, 775, 295, 39, 231, 44, 106, 108, 44, 266,
  207326. 74, 53, 1543, 44, 71, 236, 55, 199, 38, 268,
  207327. 53, 333, 85, 71, 39, 71, 39, 39, 135, 231,
  207328. 103, 39, 39, 71, 135, 44, 71, 204, 76, 39,
  207329. 167, 38, 204, 333, 135, 39, 122, 501, 58, 53,
  207330. 122, 76, 218, 333, 335, 58, 44, 58, 44, 58,
  207331. 44, 54, 50, 54, 50, 74, 263, 1159, 460, 42,
  207332. 172, 53, 76, 167, 364, 1164, 282, 44, 218, 90,
  207333. 181, 154, 85, 1383, 74, 140, 42, 204, 42, 76,
  207334. 74, 76, 39, 333, 213, 199, 74, 76, 135, 108,
  207335. 39, 106, 71, 234, 103, 140, 423, 44, 74, 76,
  207336. 202, 44, 39, 42, 333, 106, 44, 90, 1225, 41,
  207337. 41, 1383, 53, 38, 10631, 135, 231, 39, 135, 1319,
  207338. 135, 1063, 135, 231, 39, 135, 487, 1831, 135, 2151,
  207339. 108, 309, 655, 519, 346, 2727, 49, 19847, 85, 551,
  207340. 61, 839, 54, 50, 2407, 117, 110, 423, 135, 108,
  207341. 583, 108, 85, 583, 76, 423, 103, 76, 1671, 76,
  207342. 42, 236, 266, 44, 74, 364, 117, 38, 117, 55,
  207343. 39, 44, 333, 335, 213, 49, 149, 108, 61, 333,
  207344. 1127, 38, 1671, 1319, 44, 39, 2247, 935, 108, 138,
  207345. 76, 106, 74, 44, 202, 108, 58, 85, 333, 967,
  207346. 167, 1415, 554, 231, 74, 333, 47, 1114, 743, 76,
  207347. 106, 85, 1703, 42, 44, 42, 236, 44, 42, 44,
  207348. 74, 268, 202, 332, 44, 333, 333, 245, 38, 213,
  207349. 140, 42, 1511, 44, 42, 172, 42, 44, 170, 44,
  207350. 74, 231, 333, 245, 346, 300, 314, 76, 42, 967,
  207351. 42, 140, 74, 76, 42, 44, 74, 71, 333, 1415,
  207352. 44, 42, 76, 106, 44, 42, 108, 74, 149, 1159,
  207353. 266, 268, 74, 76, 181, 333, 103, 333, 967, 198,
  207354. 85, 277, 108, 53, 428, 42, 236, 135, 44, 135,
  207355. 74, 44, 71, 1413, 2022, 421, 38, 1093, 1190, 1260,
  207356. 140, 4830, 261, 3166, 261, 265, 197, 201, 261, 265,
  207357. 261, 265, 197, 201, 261, 41, 41, 41, 94, 229,
  207358. 265, 453, 261, 264, 261, 264, 261, 264, 165, 69,
  207359. 137, 40, 56, 37, 120, 101, 69, 137, 40, 120,
  207360. 133, 69, 137, 120, 261, 169, 120, 101, 69, 137,
  207361. 40, 88, 381, 162, 209, 85, 52, 51, 54, 84,
  207362. 51, 54, 52, 277, 59, 60, 162, 61, 309, 52,
  207363. 51, 149, 80, 117, 57, 54, 50, 373, 57, 53,
  207364. 48, 341, 61, 162, 194, 47, 38, 207, 121, 54,
  207365. 50, 38, 335, 121, 54, 50, 422, 855, 428, 139,
  207366. 44, 107, 396, 90, 41, 154, 41, 90, 37, 105,
  207367. 69, 105, 37, 58, 41, 90, 57, 169, 218, 41,
  207368. 58, 41, 58, 41, 58, 137, 58, 37, 137, 37,
  207369. 135, 37, 90, 69, 73, 185, 94, 101, 58, 57,
  207370. 90, 37, 58, 527, 1134, 94, 142, 47, 185, 186,
  207371. 89, 154, 57, 90, 57, 90, 57, 250, 57, 1018,
  207372. 89, 90, 57, 58, 57, 1018, 8601, 282, 153, 666,
  207373. 89, 250, 54, 50, 2618, 57, 986, 825, 1306, 217,
  207374. 602, 1274, 378, 1935, 2522, 719, 5882, 57, 314, 57,
  207375. 1754, 281, 3578, 57, 4634, 3322, 54, 50, 54, 50,
  207376. 54, 50, 54, 50, 54, 50, 54, 50, 54, 50,
  207377. 975, 1434, 185, 54, 50, 1017, 54, 50, 54, 50,
  207378. 54, 50, 54, 50, 54, 50, 537, 8218, 4217, 54,
  207379. 50, 54, 50, 54, 50, 54, 50, 54, 50, 54,
  207380. 50, 54, 50, 54, 50, 54, 50, 54, 50, 54,
  207381. 50, 2041, 54, 50, 54, 50, 1049, 54, 50, 8281,
  207382. 1562, 697, 90, 217, 346, 1513, 1509, 126, 73, 69,
  207383. 254, 105, 37, 94, 37, 94, 165, 70, 105, 37,
  207384. 3166, 37, 218, 158, 108, 94, 149, 47, 85, 1221,
  207385. 37, 37, 1799, 38, 53, 44, 743, 231, 231, 231,
  207386. 231, 231, 231, 231, 231, 1036, 85, 52, 51, 52,
  207387. 51, 117, 52, 51, 53, 52, 51, 309, 49, 85,
  207388. 49, 53, 52, 51, 85, 52, 51, 54, 50, 54,
  207389. 50, 54, 50, 54, 50, 181, 38, 341, 81, 858,
  207390. 2874, 6874, 410, 61, 117, 58, 38, 39, 46, 54,
  207391. 50, 54, 50, 54, 50, 54, 50, 54, 50, 90,
  207392. 54, 50, 54, 50, 54, 50, 54, 50, 49, 54,
  207393. 82, 58, 302, 140, 74, 49, 166, 90, 110, 38,
  207394. 39, 53, 90, 2759, 76, 88, 70, 39, 49, 2887,
  207395. 53, 102, 39, 1319, 3015, 90, 143, 346, 871, 1178,
  207396. 519, 1018, 335, 986, 271, 58, 495, 1050, 335, 1274,
  207397. 495, 2042, 8218, 39, 39, 2074, 39, 39, 679, 38,
  207398. 36583, 1786, 1287, 198, 85, 8583, 38, 117, 519, 333,
  207399. 71, 1502, 39, 44, 107, 53, 332, 53, 38, 798,
  207400. 44, 2247, 334, 76, 213, 760, 294, 88, 478, 69,
  207401. 2014, 38, 261, 190, 350, 38, 88, 158, 158, 382,
  207402. 70, 37, 231, 44, 103, 44, 135, 44, 743, 74,
  207403. 76, 42, 154, 207, 90, 55, 58, 1671, 149, 74,
  207404. 1607, 522, 44, 85, 333, 588, 199, 117, 39, 333,
  207405. 903, 268, 85, 743, 364, 74, 53, 935, 108, 42,
  207406. 1511, 44, 74, 140, 74, 44, 138, 437, 38, 333,
  207407. 85, 1319, 204, 74, 76, 74, 76, 103, 44, 263,
  207408. 44, 42, 333, 149, 519, 38, 199, 122, 39, 42,
  207409. 1543, 44, 39, 108, 71, 76, 167, 76, 39, 44,
  207410. 39, 71, 38, 85, 359, 42, 76, 74, 85, 39,
  207411. 70, 42, 44, 199, 199, 199, 231, 231, 1127, 74,
  207412. 44, 74, 44, 74, 53, 42, 44, 333, 39, 39,
  207413. 743, 1575, 36, 68, 68, 36, 63, 63, 11719, 3399,
  207414. 229, 165, 39, 44, 327, 57, 423, 167, 39, 71,
  207415. 71, 3463, 536, 11623, 54, 50, 2055, 1735, 391, 55,
  207416. 58, 524, 245, 54, 50, 53, 236, 53, 81, 80,
  207417. 54, 50, 54, 50, 54, 50, 54, 50, 54, 50,
  207418. 54, 50, 54, 50, 54, 50, 85, 54, 50, 149,
  207419. 112, 117, 149, 49, 54, 50, 54, 50, 54, 50,
  207420. 117, 57, 49, 121, 53, 55, 85, 167, 4327, 34,
  207421. 117, 55, 117, 54, 50, 53, 57, 53, 49, 85,
  207422. 333, 85, 121, 85, 841, 54, 53, 50, 56, 48,
  207423. 56, 837, 54, 57, 50, 57, 54, 50, 53, 54,
  207424. 50, 85, 327, 38, 1447, 70, 999, 199, 199, 199,
  207425. 103, 87, 57, 56, 58, 87, 58, 153, 90, 98,
  207426. 90, 391, 839, 615, 71, 487, 455, 3943, 117, 1455,
  207427. 314, 1710, 143, 570, 47, 410, 1466, 44, 935, 1575,
  207428. 999, 143, 551, 46, 263, 46, 967, 53, 1159, 263,
  207429. 53, 174, 1289, 1285, 2503, 333, 199, 39, 1415, 71,
  207430. 39, 743, 53, 271, 711, 207, 53, 839, 53, 1799,
  207431. 71, 39, 108, 76, 140, 135, 103, 871, 108, 44,
  207432. 271, 309, 935, 79, 53, 1735, 245, 711, 271, 615,
  207433. 271, 2343, 1007, 42, 44, 42, 1703, 492, 245, 655,
  207434. 333, 76, 42, 1447, 106, 140, 74, 76, 85, 34,
  207435. 149, 807, 333, 108, 1159, 172, 42, 268, 333, 149,
  207436. 76, 42, 1543, 106, 300, 74, 135, 149, 333, 1383,
  207437. 44, 42, 44, 74, 204, 42, 44, 333, 28135, 3182,
  207438. 149, 34279, 18215, 2215, 39, 1482, 140, 422, 71, 7898,
  207439. 1274, 1946, 74, 108, 122, 202, 258, 268, 90, 236,
  207440. 986, 140, 1562, 2138, 108, 58, 2810, 591, 841, 837,
  207441. 841, 229, 581, 841, 837, 41, 73, 41, 73, 137,
  207442. 265, 133, 37, 229, 357, 841, 837, 73, 137, 265,
  207443. 233, 837, 73, 137, 169, 41, 233, 837, 841, 837,
  207444. 841, 837, 841, 837, 841, 837, 841, 837, 841, 901,
  207445. 809, 57, 805, 57, 197, 809, 57, 805, 57, 197,
  207446. 809, 57, 805, 57, 197, 809, 57, 805, 57, 197,
  207447. 809, 57, 805, 57, 197, 94, 1613, 135, 871, 71,
  207448. 39, 39, 327, 135, 39, 39, 39, 39, 39, 39,
  207449. 103, 71, 39, 39, 39, 39, 39, 39, 71, 39,
  207450. 135, 231, 135, 135, 39, 327, 551, 103, 167, 551,
  207451. 89, 1434, 3226, 506, 474, 506, 506, 367, 1018, 1946,
  207452. 1402, 954, 1402, 314, 90, 1082, 218, 2266, 666, 1210,
  207453. 186, 570, 2042, 58, 5850, 154, 2010, 154, 794, 2266,
  207454. 378, 2266, 3738, 39, 39, 39, 39, 39, 39, 17351,
  207455. 34, 3074, 7692, 63, 63,
  207456. };
  207457. static int sqlite3Fts5UnicodeCategory(u32 iCode) {
  207458. int iRes = -1;
  207459. int iHi;
  207460. int iLo;
  207461. int ret;
  207462. u16 iKey;
  207463. if( iCode>=(1<<20) ){
  207464. return 0;
  207465. }
  207466. iLo = aFts5UnicodeBlock[(iCode>>16)];
  207467. iHi = aFts5UnicodeBlock[1+(iCode>>16)];
  207468. iKey = (iCode & 0xFFFF);
  207469. while( iHi>iLo ){
  207470. int iTest = (iHi + iLo) / 2;
  207471. assert( iTest>=iLo && iTest<iHi );
  207472. if( iKey>=aFts5UnicodeMap[iTest] ){
  207473. iRes = iTest;
  207474. iLo = iTest+1;
  207475. }else{
  207476. iHi = iTest;
  207477. }
  207478. }
  207479. if( iRes<0 ) return 0;
  207480. if( iKey>=(aFts5UnicodeMap[iRes]+(aFts5UnicodeData[iRes]>>5)) ) return 0;
  207481. ret = aFts5UnicodeData[iRes] & 0x1F;
  207482. if( ret!=30 ) return ret;
  207483. return ((iKey - aFts5UnicodeMap[iRes]) & 0x01) ? 5 : 9;
  207484. }
  207485. static void sqlite3Fts5UnicodeAscii(u8 *aArray, u8 *aAscii){
  207486. int i = 0;
  207487. int iTbl = 0;
  207488. while( i<128 ){
  207489. int bToken = aArray[ aFts5UnicodeData[iTbl] & 0x1F ];
  207490. int n = (aFts5UnicodeData[iTbl] >> 5) + i;
  207491. for(; i<128 && i<n; i++){
  207492. aAscii[i] = (u8)bToken;
  207493. }
  207494. iTbl++;
  207495. }
  207496. }
  207497. /*
  207498. ** 2015 May 30
  207499. **
  207500. ** The author disclaims copyright to this source code. In place of
  207501. ** a legal notice, here is a blessing:
  207502. **
  207503. ** May you do good and not evil.
  207504. ** May you find forgiveness for yourself and forgive others.
  207505. ** May you share freely, never taking more than you give.
  207506. **
  207507. ******************************************************************************
  207508. **
  207509. ** Routines for varint serialization and deserialization.
  207510. */
  207511. /* #include "fts5Int.h" */
  207512. /*
  207513. ** This is a copy of the sqlite3GetVarint32() routine from the SQLite core.
  207514. ** Except, this version does handle the single byte case that the core
  207515. ** version depends on being handled before its function is called.
  207516. */
  207517. static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v){
  207518. u32 a,b;
  207519. /* The 1-byte case. Overwhelmingly the most common. */
  207520. a = *p;
  207521. /* a: p0 (unmasked) */
  207522. if (!(a&0x80))
  207523. {
  207524. /* Values between 0 and 127 */
  207525. *v = a;
  207526. return 1;
  207527. }
  207528. /* The 2-byte case */
  207529. p++;
  207530. b = *p;
  207531. /* b: p1 (unmasked) */
  207532. if (!(b&0x80))
  207533. {
  207534. /* Values between 128 and 16383 */
  207535. a &= 0x7f;
  207536. a = a<<7;
  207537. *v = a | b;
  207538. return 2;
  207539. }
  207540. /* The 3-byte case */
  207541. p++;
  207542. a = a<<14;
  207543. a |= *p;
  207544. /* a: p0<<14 | p2 (unmasked) */
  207545. if (!(a&0x80))
  207546. {
  207547. /* Values between 16384 and 2097151 */
  207548. a &= (0x7f<<14)|(0x7f);
  207549. b &= 0x7f;
  207550. b = b<<7;
  207551. *v = a | b;
  207552. return 3;
  207553. }
  207554. /* A 32-bit varint is used to store size information in btrees.
  207555. ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
  207556. ** A 3-byte varint is sufficient, for example, to record the size
  207557. ** of a 1048569-byte BLOB or string.
  207558. **
  207559. ** We only unroll the first 1-, 2-, and 3- byte cases. The very
  207560. ** rare larger cases can be handled by the slower 64-bit varint
  207561. ** routine.
  207562. */
  207563. {
  207564. u64 v64;
  207565. u8 n;
  207566. p -= 2;
  207567. n = sqlite3Fts5GetVarint(p, &v64);
  207568. *v = ((u32)v64) & 0x7FFFFFFF;
  207569. assert( n>3 && n<=9 );
  207570. return n;
  207571. }
  207572. }
  207573. /*
  207574. ** Bitmasks used by sqlite3GetVarint(). These precomputed constants
  207575. ** are defined here rather than simply putting the constant expressions
  207576. ** inline in order to work around bugs in the RVT compiler.
  207577. **
  207578. ** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
  207579. **
  207580. ** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
  207581. */
  207582. #define SLOT_2_0 0x001fc07f
  207583. #define SLOT_4_2_0 0xf01fc07f
  207584. /*
  207585. ** Read a 64-bit variable-length integer from memory starting at p[0].
  207586. ** Return the number of bytes read. The value is stored in *v.
  207587. */
  207588. static u8 sqlite3Fts5GetVarint(const unsigned char *p, u64 *v){
  207589. u32 a,b,s;
  207590. a = *p;
  207591. /* a: p0 (unmasked) */
  207592. if (!(a&0x80))
  207593. {
  207594. *v = a;
  207595. return 1;
  207596. }
  207597. p++;
  207598. b = *p;
  207599. /* b: p1 (unmasked) */
  207600. if (!(b&0x80))
  207601. {
  207602. a &= 0x7f;
  207603. a = a<<7;
  207604. a |= b;
  207605. *v = a;
  207606. return 2;
  207607. }
  207608. /* Verify that constants are precomputed correctly */
  207609. assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
  207610. assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
  207611. p++;
  207612. a = a<<14;
  207613. a |= *p;
  207614. /* a: p0<<14 | p2 (unmasked) */
  207615. if (!(a&0x80))
  207616. {
  207617. a &= SLOT_2_0;
  207618. b &= 0x7f;
  207619. b = b<<7;
  207620. a |= b;
  207621. *v = a;
  207622. return 3;
  207623. }
  207624. /* CSE1 from below */
  207625. a &= SLOT_2_0;
  207626. p++;
  207627. b = b<<14;
  207628. b |= *p;
  207629. /* b: p1<<14 | p3 (unmasked) */
  207630. if (!(b&0x80))
  207631. {
  207632. b &= SLOT_2_0;
  207633. /* moved CSE1 up */
  207634. /* a &= (0x7f<<14)|(0x7f); */
  207635. a = a<<7;
  207636. a |= b;
  207637. *v = a;
  207638. return 4;
  207639. }
  207640. /* a: p0<<14 | p2 (masked) */
  207641. /* b: p1<<14 | p3 (unmasked) */
  207642. /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  207643. /* moved CSE1 up */
  207644. /* a &= (0x7f<<14)|(0x7f); */
  207645. b &= SLOT_2_0;
  207646. s = a;
  207647. /* s: p0<<14 | p2 (masked) */
  207648. p++;
  207649. a = a<<14;
  207650. a |= *p;
  207651. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  207652. if (!(a&0x80))
  207653. {
  207654. /* we can skip these cause they were (effectively) done above in calc'ing s */
  207655. /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  207656. /* b &= (0x7f<<14)|(0x7f); */
  207657. b = b<<7;
  207658. a |= b;
  207659. s = s>>18;
  207660. *v = ((u64)s)<<32 | a;
  207661. return 5;
  207662. }
  207663. /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  207664. s = s<<7;
  207665. s |= b;
  207666. /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  207667. p++;
  207668. b = b<<14;
  207669. b |= *p;
  207670. /* b: p1<<28 | p3<<14 | p5 (unmasked) */
  207671. if (!(b&0x80))
  207672. {
  207673. /* we can skip this cause it was (effectively) done above in calc'ing s */
  207674. /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  207675. a &= SLOT_2_0;
  207676. a = a<<7;
  207677. a |= b;
  207678. s = s>>18;
  207679. *v = ((u64)s)<<32 | a;
  207680. return 6;
  207681. }
  207682. p++;
  207683. a = a<<14;
  207684. a |= *p;
  207685. /* a: p2<<28 | p4<<14 | p6 (unmasked) */
  207686. if (!(a&0x80))
  207687. {
  207688. a &= SLOT_4_2_0;
  207689. b &= SLOT_2_0;
  207690. b = b<<7;
  207691. a |= b;
  207692. s = s>>11;
  207693. *v = ((u64)s)<<32 | a;
  207694. return 7;
  207695. }
  207696. /* CSE2 from below */
  207697. a &= SLOT_2_0;
  207698. p++;
  207699. b = b<<14;
  207700. b |= *p;
  207701. /* b: p3<<28 | p5<<14 | p7 (unmasked) */
  207702. if (!(b&0x80))
  207703. {
  207704. b &= SLOT_4_2_0;
  207705. /* moved CSE2 up */
  207706. /* a &= (0x7f<<14)|(0x7f); */
  207707. a = a<<7;
  207708. a |= b;
  207709. s = s>>4;
  207710. *v = ((u64)s)<<32 | a;
  207711. return 8;
  207712. }
  207713. p++;
  207714. a = a<<15;
  207715. a |= *p;
  207716. /* a: p4<<29 | p6<<15 | p8 (unmasked) */
  207717. /* moved CSE2 up */
  207718. /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
  207719. b &= SLOT_2_0;
  207720. b = b<<8;
  207721. a |= b;
  207722. s = s<<4;
  207723. b = p[-4];
  207724. b &= 0x7f;
  207725. b = b>>3;
  207726. s |= b;
  207727. *v = ((u64)s)<<32 | a;
  207728. return 9;
  207729. }
  207730. /*
  207731. ** The variable-length integer encoding is as follows:
  207732. **
  207733. ** KEY:
  207734. ** A = 0xxxxxxx 7 bits of data and one flag bit
  207735. ** B = 1xxxxxxx 7 bits of data and one flag bit
  207736. ** C = xxxxxxxx 8 bits of data
  207737. **
  207738. ** 7 bits - A
  207739. ** 14 bits - BA
  207740. ** 21 bits - BBA
  207741. ** 28 bits - BBBA
  207742. ** 35 bits - BBBBA
  207743. ** 42 bits - BBBBBA
  207744. ** 49 bits - BBBBBBA
  207745. ** 56 bits - BBBBBBBA
  207746. ** 64 bits - BBBBBBBBC
  207747. */
  207748. #ifdef SQLITE_NOINLINE
  207749. # define FTS5_NOINLINE SQLITE_NOINLINE
  207750. #else
  207751. # define FTS5_NOINLINE
  207752. #endif
  207753. /*
  207754. ** Write a 64-bit variable-length integer to memory starting at p[0].
  207755. ** The length of data write will be between 1 and 9 bytes. The number
  207756. ** of bytes written is returned.
  207757. **
  207758. ** A variable-length integer consists of the lower 7 bits of each byte
  207759. ** for all bytes that have the 8th bit set and one byte with the 8th
  207760. ** bit clear. Except, if we get to the 9th byte, it stores the full
  207761. ** 8 bits and is the last byte.
  207762. */
  207763. static int FTS5_NOINLINE fts5PutVarint64(unsigned char *p, u64 v){
  207764. int i, j, n;
  207765. u8 buf[10];
  207766. if( v & (((u64)0xff000000)<<32) ){
  207767. p[8] = (u8)v;
  207768. v >>= 8;
  207769. for(i=7; i>=0; i--){
  207770. p[i] = (u8)((v & 0x7f) | 0x80);
  207771. v >>= 7;
  207772. }
  207773. return 9;
  207774. }
  207775. n = 0;
  207776. do{
  207777. buf[n++] = (u8)((v & 0x7f) | 0x80);
  207778. v >>= 7;
  207779. }while( v!=0 );
  207780. buf[0] &= 0x7f;
  207781. assert( n<=9 );
  207782. for(i=0, j=n-1; j>=0; j--, i++){
  207783. p[i] = buf[j];
  207784. }
  207785. return n;
  207786. }
  207787. static int sqlite3Fts5PutVarint(unsigned char *p, u64 v){
  207788. if( v<=0x7f ){
  207789. p[0] = v&0x7f;
  207790. return 1;
  207791. }
  207792. if( v<=0x3fff ){
  207793. p[0] = ((v>>7)&0x7f)|0x80;
  207794. p[1] = v&0x7f;
  207795. return 2;
  207796. }
  207797. return fts5PutVarint64(p,v);
  207798. }
  207799. static int sqlite3Fts5GetVarintLen(u32 iVal){
  207800. #if 0
  207801. if( iVal<(1 << 7 ) ) return 1;
  207802. #endif
  207803. assert( iVal>=(1 << 7) );
  207804. if( iVal<(1 << 14) ) return 2;
  207805. if( iVal<(1 << 21) ) return 3;
  207806. if( iVal<(1 << 28) ) return 4;
  207807. return 5;
  207808. }
  207809. /*
  207810. ** 2015 May 08
  207811. **
  207812. ** The author disclaims copyright to this source code. In place of
  207813. ** a legal notice, here is a blessing:
  207814. **
  207815. ** May you do good and not evil.
  207816. ** May you find forgiveness for yourself and forgive others.
  207817. ** May you share freely, never taking more than you give.
  207818. **
  207819. ******************************************************************************
  207820. **
  207821. ** This is an SQLite virtual table module implementing direct access to an
  207822. ** existing FTS5 index. The module may create several different types of
  207823. ** tables:
  207824. **
  207825. ** col:
  207826. ** CREATE TABLE vocab(term, col, doc, cnt, PRIMARY KEY(term, col));
  207827. **
  207828. ** One row for each term/column combination. The value of $doc is set to
  207829. ** the number of fts5 rows that contain at least one instance of term
  207830. ** $term within column $col. Field $cnt is set to the total number of
  207831. ** instances of term $term in column $col (in any row of the fts5 table).
  207832. **
  207833. ** row:
  207834. ** CREATE TABLE vocab(term, doc, cnt, PRIMARY KEY(term));
  207835. **
  207836. ** One row for each term in the database. The value of $doc is set to
  207837. ** the number of fts5 rows that contain at least one instance of term
  207838. ** $term. Field $cnt is set to the total number of instances of term
  207839. ** $term in the database.
  207840. **
  207841. ** instance:
  207842. ** CREATE TABLE vocab(term, doc, col, offset, PRIMARY KEY(<all-fields>));
  207843. **
  207844. ** One row for each term instance in the database.
  207845. */
  207846. /* #include "fts5Int.h" */
  207847. typedef struct Fts5VocabTable Fts5VocabTable;
  207848. typedef struct Fts5VocabCursor Fts5VocabCursor;
  207849. struct Fts5VocabTable {
  207850. sqlite3_vtab base;
  207851. char *zFts5Tbl; /* Name of fts5 table */
  207852. char *zFts5Db; /* Db containing fts5 table */
  207853. sqlite3 *db; /* Database handle */
  207854. Fts5Global *pGlobal; /* FTS5 global object for this database */
  207855. int eType; /* FTS5_VOCAB_COL, ROW or INSTANCE */
  207856. };
  207857. struct Fts5VocabCursor {
  207858. sqlite3_vtab_cursor base;
  207859. sqlite3_stmt *pStmt; /* Statement holding lock on pIndex */
  207860. Fts5Table *pFts5; /* Associated FTS5 table */
  207861. int bEof; /* True if this cursor is at EOF */
  207862. Fts5IndexIter *pIter; /* Term/rowid iterator object */
  207863. int nLeTerm; /* Size of zLeTerm in bytes */
  207864. char *zLeTerm; /* (term <= $zLeTerm) paramater, or NULL */
  207865. /* These are used by 'col' tables only */
  207866. int iCol;
  207867. i64 *aCnt;
  207868. i64 *aDoc;
  207869. /* Output values used by all tables. */
  207870. i64 rowid; /* This table's current rowid value */
  207871. Fts5Buffer term; /* Current value of 'term' column */
  207872. /* Output values Used by 'instance' tables only */
  207873. i64 iInstPos;
  207874. int iInstOff;
  207875. };
  207876. #define FTS5_VOCAB_COL 0
  207877. #define FTS5_VOCAB_ROW 1
  207878. #define FTS5_VOCAB_INSTANCE 2
  207879. #define FTS5_VOCAB_COL_SCHEMA "term, col, doc, cnt"
  207880. #define FTS5_VOCAB_ROW_SCHEMA "term, doc, cnt"
  207881. #define FTS5_VOCAB_INST_SCHEMA "term, doc, col, offset"
  207882. /*
  207883. ** Bits for the mask used as the idxNum value by xBestIndex/xFilter.
  207884. */
  207885. #define FTS5_VOCAB_TERM_EQ 0x01
  207886. #define FTS5_VOCAB_TERM_GE 0x02
  207887. #define FTS5_VOCAB_TERM_LE 0x04
  207888. /*
  207889. ** Translate a string containing an fts5vocab table type to an
  207890. ** FTS5_VOCAB_XXX constant. If successful, set *peType to the output
  207891. ** value and return SQLITE_OK. Otherwise, set *pzErr to an error message
  207892. ** and return SQLITE_ERROR.
  207893. */
  207894. static int fts5VocabTableType(const char *zType, char **pzErr, int *peType){
  207895. int rc = SQLITE_OK;
  207896. char *zCopy = sqlite3Fts5Strndup(&rc, zType, -1);
  207897. if( rc==SQLITE_OK ){
  207898. sqlite3Fts5Dequote(zCopy);
  207899. if( sqlite3_stricmp(zCopy, "col")==0 ){
  207900. *peType = FTS5_VOCAB_COL;
  207901. }else
  207902. if( sqlite3_stricmp(zCopy, "row")==0 ){
  207903. *peType = FTS5_VOCAB_ROW;
  207904. }else
  207905. if( sqlite3_stricmp(zCopy, "instance")==0 ){
  207906. *peType = FTS5_VOCAB_INSTANCE;
  207907. }else
  207908. {
  207909. *pzErr = sqlite3_mprintf("fts5vocab: unknown table type: %Q", zCopy);
  207910. rc = SQLITE_ERROR;
  207911. }
  207912. sqlite3_free(zCopy);
  207913. }
  207914. return rc;
  207915. }
  207916. /*
  207917. ** The xDisconnect() virtual table method.
  207918. */
  207919. static int fts5VocabDisconnectMethod(sqlite3_vtab *pVtab){
  207920. Fts5VocabTable *pTab = (Fts5VocabTable*)pVtab;
  207921. sqlite3_free(pTab);
  207922. return SQLITE_OK;
  207923. }
  207924. /*
  207925. ** The xDestroy() virtual table method.
  207926. */
  207927. static int fts5VocabDestroyMethod(sqlite3_vtab *pVtab){
  207928. Fts5VocabTable *pTab = (Fts5VocabTable*)pVtab;
  207929. sqlite3_free(pTab);
  207930. return SQLITE_OK;
  207931. }
  207932. /*
  207933. ** This function is the implementation of both the xConnect and xCreate
  207934. ** methods of the FTS3 virtual table.
  207935. **
  207936. ** The argv[] array contains the following:
  207937. **
  207938. ** argv[0] -> module name ("fts5vocab")
  207939. ** argv[1] -> database name
  207940. ** argv[2] -> table name
  207941. **
  207942. ** then:
  207943. **
  207944. ** argv[3] -> name of fts5 table
  207945. ** argv[4] -> type of fts5vocab table
  207946. **
  207947. ** or, for tables in the TEMP schema only.
  207948. **
  207949. ** argv[3] -> name of fts5 tables database
  207950. ** argv[4] -> name of fts5 table
  207951. ** argv[5] -> type of fts5vocab table
  207952. */
  207953. static int fts5VocabInitVtab(
  207954. sqlite3 *db, /* The SQLite database connection */
  207955. void *pAux, /* Pointer to Fts5Global object */
  207956. int argc, /* Number of elements in argv array */
  207957. const char * const *argv, /* xCreate/xConnect argument array */
  207958. sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
  207959. char **pzErr /* Write any error message here */
  207960. ){
  207961. const char *azSchema[] = {
  207962. "CREATE TABlE vocab(" FTS5_VOCAB_COL_SCHEMA ")",
  207963. "CREATE TABlE vocab(" FTS5_VOCAB_ROW_SCHEMA ")",
  207964. "CREATE TABlE vocab(" FTS5_VOCAB_INST_SCHEMA ")"
  207965. };
  207966. Fts5VocabTable *pRet = 0;
  207967. int rc = SQLITE_OK; /* Return code */
  207968. int bDb;
  207969. bDb = (argc==6 && strlen(argv[1])==4 && memcmp("temp", argv[1], 4)==0);
  207970. if( argc!=5 && bDb==0 ){
  207971. *pzErr = sqlite3_mprintf("wrong number of vtable arguments");
  207972. rc = SQLITE_ERROR;
  207973. }else{
  207974. int nByte; /* Bytes of space to allocate */
  207975. const char *zDb = bDb ? argv[3] : argv[1];
  207976. const char *zTab = bDb ? argv[4] : argv[3];
  207977. const char *zType = bDb ? argv[5] : argv[4];
  207978. int nDb = (int)strlen(zDb)+1;
  207979. int nTab = (int)strlen(zTab)+1;
  207980. int eType = 0;
  207981. rc = fts5VocabTableType(zType, pzErr, &eType);
  207982. if( rc==SQLITE_OK ){
  207983. assert( eType>=0 && eType<ArraySize(azSchema) );
  207984. rc = sqlite3_declare_vtab(db, azSchema[eType]);
  207985. }
  207986. nByte = sizeof(Fts5VocabTable) + nDb + nTab;
  207987. pRet = sqlite3Fts5MallocZero(&rc, nByte);
  207988. if( pRet ){
  207989. pRet->pGlobal = (Fts5Global*)pAux;
  207990. pRet->eType = eType;
  207991. pRet->db = db;
  207992. pRet->zFts5Tbl = (char*)&pRet[1];
  207993. pRet->zFts5Db = &pRet->zFts5Tbl[nTab];
  207994. memcpy(pRet->zFts5Tbl, zTab, nTab);
  207995. memcpy(pRet->zFts5Db, zDb, nDb);
  207996. sqlite3Fts5Dequote(pRet->zFts5Tbl);
  207997. sqlite3Fts5Dequote(pRet->zFts5Db);
  207998. }
  207999. }
  208000. *ppVTab = (sqlite3_vtab*)pRet;
  208001. return rc;
  208002. }
  208003. /*
  208004. ** The xConnect() and xCreate() methods for the virtual table. All the
  208005. ** work is done in function fts5VocabInitVtab().
  208006. */
  208007. static int fts5VocabConnectMethod(
  208008. sqlite3 *db, /* Database connection */
  208009. void *pAux, /* Pointer to tokenizer hash table */
  208010. int argc, /* Number of elements in argv array */
  208011. const char * const *argv, /* xCreate/xConnect argument array */
  208012. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  208013. char **pzErr /* OUT: sqlite3_malloc'd error message */
  208014. ){
  208015. return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr);
  208016. }
  208017. static int fts5VocabCreateMethod(
  208018. sqlite3 *db, /* Database connection */
  208019. void *pAux, /* Pointer to tokenizer hash table */
  208020. int argc, /* Number of elements in argv array */
  208021. const char * const *argv, /* xCreate/xConnect argument array */
  208022. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  208023. char **pzErr /* OUT: sqlite3_malloc'd error message */
  208024. ){
  208025. return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr);
  208026. }
  208027. /*
  208028. ** Implementation of the xBestIndex method.
  208029. **
  208030. ** Only constraints of the form:
  208031. **
  208032. ** term <= ?
  208033. ** term == ?
  208034. ** term >= ?
  208035. **
  208036. ** are interpreted. Less-than and less-than-or-equal are treated
  208037. ** identically, as are greater-than and greater-than-or-equal.
  208038. */
  208039. static int fts5VocabBestIndexMethod(
  208040. sqlite3_vtab *pUnused,
  208041. sqlite3_index_info *pInfo
  208042. ){
  208043. int i;
  208044. int iTermEq = -1;
  208045. int iTermGe = -1;
  208046. int iTermLe = -1;
  208047. int idxNum = 0;
  208048. int nArg = 0;
  208049. UNUSED_PARAM(pUnused);
  208050. for(i=0; i<pInfo->nConstraint; i++){
  208051. struct sqlite3_index_constraint *p = &pInfo->aConstraint[i];
  208052. if( p->usable==0 ) continue;
  208053. if( p->iColumn==0 ){ /* term column */
  208054. if( p->op==SQLITE_INDEX_CONSTRAINT_EQ ) iTermEq = i;
  208055. if( p->op==SQLITE_INDEX_CONSTRAINT_LE ) iTermLe = i;
  208056. if( p->op==SQLITE_INDEX_CONSTRAINT_LT ) iTermLe = i;
  208057. if( p->op==SQLITE_INDEX_CONSTRAINT_GE ) iTermGe = i;
  208058. if( p->op==SQLITE_INDEX_CONSTRAINT_GT ) iTermGe = i;
  208059. }
  208060. }
  208061. if( iTermEq>=0 ){
  208062. idxNum |= FTS5_VOCAB_TERM_EQ;
  208063. pInfo->aConstraintUsage[iTermEq].argvIndex = ++nArg;
  208064. pInfo->estimatedCost = 100;
  208065. }else{
  208066. pInfo->estimatedCost = 1000000;
  208067. if( iTermGe>=0 ){
  208068. idxNum |= FTS5_VOCAB_TERM_GE;
  208069. pInfo->aConstraintUsage[iTermGe].argvIndex = ++nArg;
  208070. pInfo->estimatedCost = pInfo->estimatedCost / 2;
  208071. }
  208072. if( iTermLe>=0 ){
  208073. idxNum |= FTS5_VOCAB_TERM_LE;
  208074. pInfo->aConstraintUsage[iTermLe].argvIndex = ++nArg;
  208075. pInfo->estimatedCost = pInfo->estimatedCost / 2;
  208076. }
  208077. }
  208078. /* This virtual table always delivers results in ascending order of
  208079. ** the "term" column (column 0). So if the user has requested this
  208080. ** specifically - "ORDER BY term" or "ORDER BY term ASC" - set the
  208081. ** sqlite3_index_info.orderByConsumed flag to tell the core the results
  208082. ** are already in sorted order. */
  208083. if( pInfo->nOrderBy==1
  208084. && pInfo->aOrderBy[0].iColumn==0
  208085. && pInfo->aOrderBy[0].desc==0
  208086. ){
  208087. pInfo->orderByConsumed = 1;
  208088. }
  208089. pInfo->idxNum = idxNum;
  208090. return SQLITE_OK;
  208091. }
  208092. /*
  208093. ** Implementation of xOpen method.
  208094. */
  208095. static int fts5VocabOpenMethod(
  208096. sqlite3_vtab *pVTab,
  208097. sqlite3_vtab_cursor **ppCsr
  208098. ){
  208099. Fts5VocabTable *pTab = (Fts5VocabTable*)pVTab;
  208100. Fts5Table *pFts5 = 0;
  208101. Fts5VocabCursor *pCsr = 0;
  208102. int rc = SQLITE_OK;
  208103. sqlite3_stmt *pStmt = 0;
  208104. char *zSql = 0;
  208105. zSql = sqlite3Fts5Mprintf(&rc,
  208106. "SELECT t.%Q FROM %Q.%Q AS t WHERE t.%Q MATCH '*id'",
  208107. pTab->zFts5Tbl, pTab->zFts5Db, pTab->zFts5Tbl, pTab->zFts5Tbl
  208108. );
  208109. if( zSql ){
  208110. rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pStmt, 0);
  208111. }
  208112. sqlite3_free(zSql);
  208113. assert( rc==SQLITE_OK || pStmt==0 );
  208114. if( rc==SQLITE_ERROR ) rc = SQLITE_OK;
  208115. if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
  208116. i64 iId = sqlite3_column_int64(pStmt, 0);
  208117. pFts5 = sqlite3Fts5TableFromCsrid(pTab->pGlobal, iId);
  208118. }
  208119. if( rc==SQLITE_OK ){
  208120. if( pFts5==0 ){
  208121. rc = sqlite3_finalize(pStmt);
  208122. pStmt = 0;
  208123. if( rc==SQLITE_OK ){
  208124. pVTab->zErrMsg = sqlite3_mprintf(
  208125. "no such fts5 table: %s.%s", pTab->zFts5Db, pTab->zFts5Tbl
  208126. );
  208127. rc = SQLITE_ERROR;
  208128. }
  208129. }else{
  208130. rc = sqlite3Fts5FlushToDisk(pFts5);
  208131. }
  208132. }
  208133. if( rc==SQLITE_OK ){
  208134. int nByte = pFts5->pConfig->nCol * sizeof(i64)*2 + sizeof(Fts5VocabCursor);
  208135. pCsr = (Fts5VocabCursor*)sqlite3Fts5MallocZero(&rc, nByte);
  208136. }
  208137. if( pCsr ){
  208138. pCsr->pFts5 = pFts5;
  208139. pCsr->pStmt = pStmt;
  208140. pCsr->aCnt = (i64*)&pCsr[1];
  208141. pCsr->aDoc = &pCsr->aCnt[pFts5->pConfig->nCol];
  208142. }else{
  208143. sqlite3_finalize(pStmt);
  208144. }
  208145. *ppCsr = (sqlite3_vtab_cursor*)pCsr;
  208146. return rc;
  208147. }
  208148. static void fts5VocabResetCursor(Fts5VocabCursor *pCsr){
  208149. pCsr->rowid = 0;
  208150. sqlite3Fts5IterClose(pCsr->pIter);
  208151. pCsr->pIter = 0;
  208152. sqlite3_free(pCsr->zLeTerm);
  208153. pCsr->nLeTerm = -1;
  208154. pCsr->zLeTerm = 0;
  208155. pCsr->bEof = 0;
  208156. }
  208157. /*
  208158. ** Close the cursor. For additional information see the documentation
  208159. ** on the xClose method of the virtual table interface.
  208160. */
  208161. static int fts5VocabCloseMethod(sqlite3_vtab_cursor *pCursor){
  208162. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  208163. fts5VocabResetCursor(pCsr);
  208164. sqlite3Fts5BufferFree(&pCsr->term);
  208165. sqlite3_finalize(pCsr->pStmt);
  208166. sqlite3_free(pCsr);
  208167. return SQLITE_OK;
  208168. }
  208169. static int fts5VocabInstanceNewTerm(Fts5VocabCursor *pCsr){
  208170. int rc = SQLITE_OK;
  208171. if( sqlite3Fts5IterEof(pCsr->pIter) ){
  208172. pCsr->bEof = 1;
  208173. }else{
  208174. const char *zTerm;
  208175. int nTerm;
  208176. zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
  208177. if( pCsr->nLeTerm>=0 ){
  208178. int nCmp = MIN(nTerm, pCsr->nLeTerm);
  208179. int bCmp = memcmp(pCsr->zLeTerm, zTerm, nCmp);
  208180. if( bCmp<0 || (bCmp==0 && pCsr->nLeTerm<nTerm) ){
  208181. pCsr->bEof = 1;
  208182. }
  208183. }
  208184. sqlite3Fts5BufferSet(&rc, &pCsr->term, nTerm, (const u8*)zTerm);
  208185. }
  208186. return rc;
  208187. }
  208188. static int fts5VocabInstanceNext(Fts5VocabCursor *pCsr){
  208189. int eDetail = pCsr->pFts5->pConfig->eDetail;
  208190. int rc = SQLITE_OK;
  208191. Fts5IndexIter *pIter = pCsr->pIter;
  208192. i64 *pp = &pCsr->iInstPos;
  208193. int *po = &pCsr->iInstOff;
  208194. assert( sqlite3Fts5IterEof(pIter)==0 );
  208195. assert( pCsr->bEof==0 );
  208196. while( eDetail==FTS5_DETAIL_NONE
  208197. || sqlite3Fts5PoslistNext64(pIter->pData, pIter->nData, po, pp)
  208198. ){
  208199. pCsr->iInstPos = 0;
  208200. pCsr->iInstOff = 0;
  208201. rc = sqlite3Fts5IterNextScan(pCsr->pIter);
  208202. if( rc==SQLITE_OK ){
  208203. rc = fts5VocabInstanceNewTerm(pCsr);
  208204. if( pCsr->bEof || eDetail==FTS5_DETAIL_NONE ) break;
  208205. }
  208206. if( rc ){
  208207. pCsr->bEof = 1;
  208208. break;
  208209. }
  208210. }
  208211. return rc;
  208212. }
  208213. /*
  208214. ** Advance the cursor to the next row in the table.
  208215. */
  208216. static int fts5VocabNextMethod(sqlite3_vtab_cursor *pCursor){
  208217. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  208218. Fts5VocabTable *pTab = (Fts5VocabTable*)pCursor->pVtab;
  208219. int rc = SQLITE_OK;
  208220. int nCol = pCsr->pFts5->pConfig->nCol;
  208221. pCsr->rowid++;
  208222. if( pTab->eType==FTS5_VOCAB_INSTANCE ){
  208223. return fts5VocabInstanceNext(pCsr);
  208224. }
  208225. if( pTab->eType==FTS5_VOCAB_COL ){
  208226. for(pCsr->iCol++; pCsr->iCol<nCol; pCsr->iCol++){
  208227. if( pCsr->aDoc[pCsr->iCol] ) break;
  208228. }
  208229. }
  208230. if( pTab->eType!=FTS5_VOCAB_COL || pCsr->iCol>=nCol ){
  208231. if( sqlite3Fts5IterEof(pCsr->pIter) ){
  208232. pCsr->bEof = 1;
  208233. }else{
  208234. const char *zTerm;
  208235. int nTerm;
  208236. zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
  208237. assert( nTerm>=0 );
  208238. if( pCsr->nLeTerm>=0 ){
  208239. int nCmp = MIN(nTerm, pCsr->nLeTerm);
  208240. int bCmp = memcmp(pCsr->zLeTerm, zTerm, nCmp);
  208241. if( bCmp<0 || (bCmp==0 && pCsr->nLeTerm<nTerm) ){
  208242. pCsr->bEof = 1;
  208243. return SQLITE_OK;
  208244. }
  208245. }
  208246. sqlite3Fts5BufferSet(&rc, &pCsr->term, nTerm, (const u8*)zTerm);
  208247. memset(pCsr->aCnt, 0, nCol * sizeof(i64));
  208248. memset(pCsr->aDoc, 0, nCol * sizeof(i64));
  208249. pCsr->iCol = 0;
  208250. assert( pTab->eType==FTS5_VOCAB_COL || pTab->eType==FTS5_VOCAB_ROW );
  208251. while( rc==SQLITE_OK ){
  208252. int eDetail = pCsr->pFts5->pConfig->eDetail;
  208253. const u8 *pPos; int nPos; /* Position list */
  208254. i64 iPos = 0; /* 64-bit position read from poslist */
  208255. int iOff = 0; /* Current offset within position list */
  208256. pPos = pCsr->pIter->pData;
  208257. nPos = pCsr->pIter->nData;
  208258. switch( pTab->eType ){
  208259. case FTS5_VOCAB_ROW:
  208260. if( eDetail==FTS5_DETAIL_FULL ){
  208261. while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){
  208262. pCsr->aCnt[0]++;
  208263. }
  208264. }
  208265. pCsr->aDoc[0]++;
  208266. break;
  208267. case FTS5_VOCAB_COL:
  208268. if( eDetail==FTS5_DETAIL_FULL ){
  208269. int iCol = -1;
  208270. while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){
  208271. int ii = FTS5_POS2COLUMN(iPos);
  208272. if( iCol!=ii ){
  208273. if( ii>=nCol ){
  208274. rc = FTS5_CORRUPT;
  208275. break;
  208276. }
  208277. pCsr->aDoc[ii]++;
  208278. iCol = ii;
  208279. }
  208280. pCsr->aCnt[ii]++;
  208281. }
  208282. }else if( eDetail==FTS5_DETAIL_COLUMNS ){
  208283. while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff,&iPos) ){
  208284. assert_nc( iPos>=0 && iPos<nCol );
  208285. if( iPos>=nCol ){
  208286. rc = FTS5_CORRUPT;
  208287. break;
  208288. }
  208289. pCsr->aDoc[iPos]++;
  208290. }
  208291. }else{
  208292. assert( eDetail==FTS5_DETAIL_NONE );
  208293. pCsr->aDoc[0]++;
  208294. }
  208295. break;
  208296. default:
  208297. assert( pTab->eType==FTS5_VOCAB_INSTANCE );
  208298. break;
  208299. }
  208300. if( rc==SQLITE_OK ){
  208301. rc = sqlite3Fts5IterNextScan(pCsr->pIter);
  208302. }
  208303. if( pTab->eType==FTS5_VOCAB_INSTANCE ) break;
  208304. if( rc==SQLITE_OK ){
  208305. zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
  208306. if( nTerm!=pCsr->term.n
  208307. || (nTerm>0 && memcmp(zTerm, pCsr->term.p, nTerm))
  208308. ){
  208309. break;
  208310. }
  208311. if( sqlite3Fts5IterEof(pCsr->pIter) ) break;
  208312. }
  208313. }
  208314. }
  208315. }
  208316. if( rc==SQLITE_OK && pCsr->bEof==0 && pTab->eType==FTS5_VOCAB_COL ){
  208317. for(/* noop */; pCsr->iCol<nCol && pCsr->aDoc[pCsr->iCol]==0; pCsr->iCol++);
  208318. if( pCsr->iCol==nCol ){
  208319. rc = FTS5_CORRUPT;
  208320. }
  208321. }
  208322. return rc;
  208323. }
  208324. /*
  208325. ** This is the xFilter implementation for the virtual table.
  208326. */
  208327. static int fts5VocabFilterMethod(
  208328. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  208329. int idxNum, /* Strategy index */
  208330. const char *zUnused, /* Unused */
  208331. int nUnused, /* Number of elements in apVal */
  208332. sqlite3_value **apVal /* Arguments for the indexing scheme */
  208333. ){
  208334. Fts5VocabTable *pTab = (Fts5VocabTable*)pCursor->pVtab;
  208335. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  208336. int eType = pTab->eType;
  208337. int rc = SQLITE_OK;
  208338. int iVal = 0;
  208339. int f = FTS5INDEX_QUERY_SCAN;
  208340. const char *zTerm = 0;
  208341. int nTerm = 0;
  208342. sqlite3_value *pEq = 0;
  208343. sqlite3_value *pGe = 0;
  208344. sqlite3_value *pLe = 0;
  208345. UNUSED_PARAM2(zUnused, nUnused);
  208346. fts5VocabResetCursor(pCsr);
  208347. if( idxNum & FTS5_VOCAB_TERM_EQ ) pEq = apVal[iVal++];
  208348. if( idxNum & FTS5_VOCAB_TERM_GE ) pGe = apVal[iVal++];
  208349. if( idxNum & FTS5_VOCAB_TERM_LE ) pLe = apVal[iVal++];
  208350. if( pEq ){
  208351. zTerm = (const char *)sqlite3_value_text(pEq);
  208352. nTerm = sqlite3_value_bytes(pEq);
  208353. f = 0;
  208354. }else{
  208355. if( pGe ){
  208356. zTerm = (const char *)sqlite3_value_text(pGe);
  208357. nTerm = sqlite3_value_bytes(pGe);
  208358. }
  208359. if( pLe ){
  208360. const char *zCopy = (const char *)sqlite3_value_text(pLe);
  208361. if( zCopy==0 ) zCopy = "";
  208362. pCsr->nLeTerm = sqlite3_value_bytes(pLe);
  208363. pCsr->zLeTerm = sqlite3_malloc(pCsr->nLeTerm+1);
  208364. if( pCsr->zLeTerm==0 ){
  208365. rc = SQLITE_NOMEM;
  208366. }else{
  208367. memcpy(pCsr->zLeTerm, zCopy, pCsr->nLeTerm+1);
  208368. }
  208369. }
  208370. }
  208371. if( rc==SQLITE_OK ){
  208372. Fts5Index *pIndex = pCsr->pFts5->pIndex;
  208373. rc = sqlite3Fts5IndexQuery(pIndex, zTerm, nTerm, f, 0, &pCsr->pIter);
  208374. }
  208375. if( rc==SQLITE_OK && eType==FTS5_VOCAB_INSTANCE ){
  208376. rc = fts5VocabInstanceNewTerm(pCsr);
  208377. }
  208378. if( rc==SQLITE_OK && !pCsr->bEof
  208379. && (eType!=FTS5_VOCAB_INSTANCE
  208380. || pCsr->pFts5->pConfig->eDetail!=FTS5_DETAIL_NONE)
  208381. ){
  208382. rc = fts5VocabNextMethod(pCursor);
  208383. }
  208384. return rc;
  208385. }
  208386. /*
  208387. ** This is the xEof method of the virtual table. SQLite calls this
  208388. ** routine to find out if it has reached the end of a result set.
  208389. */
  208390. static int fts5VocabEofMethod(sqlite3_vtab_cursor *pCursor){
  208391. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  208392. return pCsr->bEof;
  208393. }
  208394. static int fts5VocabColumnMethod(
  208395. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  208396. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  208397. int iCol /* Index of column to read value from */
  208398. ){
  208399. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  208400. int eDetail = pCsr->pFts5->pConfig->eDetail;
  208401. int eType = ((Fts5VocabTable*)(pCursor->pVtab))->eType;
  208402. i64 iVal = 0;
  208403. if( iCol==0 ){
  208404. sqlite3_result_text(
  208405. pCtx, (const char*)pCsr->term.p, pCsr->term.n, SQLITE_TRANSIENT
  208406. );
  208407. }else if( eType==FTS5_VOCAB_COL ){
  208408. assert( iCol==1 || iCol==2 || iCol==3 );
  208409. if( iCol==1 ){
  208410. if( eDetail!=FTS5_DETAIL_NONE ){
  208411. const char *z = pCsr->pFts5->pConfig->azCol[pCsr->iCol];
  208412. sqlite3_result_text(pCtx, z, -1, SQLITE_STATIC);
  208413. }
  208414. }else if( iCol==2 ){
  208415. iVal = pCsr->aDoc[pCsr->iCol];
  208416. }else{
  208417. iVal = pCsr->aCnt[pCsr->iCol];
  208418. }
  208419. }else if( eType==FTS5_VOCAB_ROW ){
  208420. assert( iCol==1 || iCol==2 );
  208421. if( iCol==1 ){
  208422. iVal = pCsr->aDoc[0];
  208423. }else{
  208424. iVal = pCsr->aCnt[0];
  208425. }
  208426. }else{
  208427. assert( eType==FTS5_VOCAB_INSTANCE );
  208428. switch( iCol ){
  208429. case 1:
  208430. sqlite3_result_int64(pCtx, pCsr->pIter->iRowid);
  208431. break;
  208432. case 2: {
  208433. int ii = -1;
  208434. if( eDetail==FTS5_DETAIL_FULL ){
  208435. ii = FTS5_POS2COLUMN(pCsr->iInstPos);
  208436. }else if( eDetail==FTS5_DETAIL_COLUMNS ){
  208437. ii = (int)pCsr->iInstPos;
  208438. }
  208439. if( ii>=0 && ii<pCsr->pFts5->pConfig->nCol ){
  208440. const char *z = pCsr->pFts5->pConfig->azCol[ii];
  208441. sqlite3_result_text(pCtx, z, -1, SQLITE_STATIC);
  208442. }
  208443. break;
  208444. }
  208445. default: {
  208446. assert( iCol==3 );
  208447. if( eDetail==FTS5_DETAIL_FULL ){
  208448. int ii = FTS5_POS2OFFSET(pCsr->iInstPos);
  208449. sqlite3_result_int(pCtx, ii);
  208450. }
  208451. break;
  208452. }
  208453. }
  208454. }
  208455. if( iVal>0 ) sqlite3_result_int64(pCtx, iVal);
  208456. return SQLITE_OK;
  208457. }
  208458. /*
  208459. ** This is the xRowid method. The SQLite core calls this routine to
  208460. ** retrieve the rowid for the current row of the result set. The
  208461. ** rowid should be written to *pRowid.
  208462. */
  208463. static int fts5VocabRowidMethod(
  208464. sqlite3_vtab_cursor *pCursor,
  208465. sqlite_int64 *pRowid
  208466. ){
  208467. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  208468. *pRowid = pCsr->rowid;
  208469. return SQLITE_OK;
  208470. }
  208471. static int sqlite3Fts5VocabInit(Fts5Global *pGlobal, sqlite3 *db){
  208472. static const sqlite3_module fts5Vocab = {
  208473. /* iVersion */ 2,
  208474. /* xCreate */ fts5VocabCreateMethod,
  208475. /* xConnect */ fts5VocabConnectMethod,
  208476. /* xBestIndex */ fts5VocabBestIndexMethod,
  208477. /* xDisconnect */ fts5VocabDisconnectMethod,
  208478. /* xDestroy */ fts5VocabDestroyMethod,
  208479. /* xOpen */ fts5VocabOpenMethod,
  208480. /* xClose */ fts5VocabCloseMethod,
  208481. /* xFilter */ fts5VocabFilterMethod,
  208482. /* xNext */ fts5VocabNextMethod,
  208483. /* xEof */ fts5VocabEofMethod,
  208484. /* xColumn */ fts5VocabColumnMethod,
  208485. /* xRowid */ fts5VocabRowidMethod,
  208486. /* xUpdate */ 0,
  208487. /* xBegin */ 0,
  208488. /* xSync */ 0,
  208489. /* xCommit */ 0,
  208490. /* xRollback */ 0,
  208491. /* xFindFunction */ 0,
  208492. /* xRename */ 0,
  208493. /* xSavepoint */ 0,
  208494. /* xRelease */ 0,
  208495. /* xRollbackTo */ 0,
  208496. /* xShadowName */ 0
  208497. };
  208498. void *p = (void*)pGlobal;
  208499. return sqlite3_create_module_v2(db, "fts5vocab", &fts5Vocab, p, 0);
  208500. }
  208501. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5) */
  208502. /************** End of fts5.c ************************************************/
  208503. /************** Begin file stmt.c ********************************************/
  208504. /*
  208505. ** 2017-05-31
  208506. **
  208507. ** The author disclaims copyright to this source code. In place of
  208508. ** a legal notice, here is a blessing:
  208509. **
  208510. ** May you do good and not evil.
  208511. ** May you find forgiveness for yourself and forgive others.
  208512. ** May you share freely, never taking more than you give.
  208513. **
  208514. *************************************************************************
  208515. **
  208516. ** This file demonstrates an eponymous virtual table that returns information
  208517. ** about all prepared statements for the database connection.
  208518. **
  208519. ** Usage example:
  208520. **
  208521. ** .load ./stmt
  208522. ** .mode line
  208523. ** .header on
  208524. ** SELECT * FROM stmt;
  208525. */
  208526. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_STMTVTAB)
  208527. #if !defined(SQLITEINT_H)
  208528. /* #include "sqlite3ext.h" */
  208529. #endif
  208530. SQLITE_EXTENSION_INIT1
  208531. /* #include <assert.h> */
  208532. /* #include <string.h> */
  208533. #ifndef SQLITE_OMIT_VIRTUALTABLE
  208534. /* stmt_vtab is a subclass of sqlite3_vtab which will
  208535. ** serve as the underlying representation of a stmt virtual table
  208536. */
  208537. typedef struct stmt_vtab stmt_vtab;
  208538. struct stmt_vtab {
  208539. sqlite3_vtab base; /* Base class - must be first */
  208540. sqlite3 *db; /* Database connection for this stmt vtab */
  208541. };
  208542. /* stmt_cursor is a subclass of sqlite3_vtab_cursor which will
  208543. ** serve as the underlying representation of a cursor that scans
  208544. ** over rows of the result
  208545. */
  208546. typedef struct stmt_cursor stmt_cursor;
  208547. struct stmt_cursor {
  208548. sqlite3_vtab_cursor base; /* Base class - must be first */
  208549. sqlite3 *db; /* Database connection for this cursor */
  208550. sqlite3_stmt *pStmt; /* Statement cursor is currently pointing at */
  208551. sqlite3_int64 iRowid; /* The rowid */
  208552. };
  208553. /*
  208554. ** The stmtConnect() method is invoked to create a new
  208555. ** stmt_vtab that describes the stmt virtual table.
  208556. **
  208557. ** Think of this routine as the constructor for stmt_vtab objects.
  208558. **
  208559. ** All this routine needs to do is:
  208560. **
  208561. ** (1) Allocate the stmt_vtab object and initialize all fields.
  208562. **
  208563. ** (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
  208564. ** result set of queries against stmt will look like.
  208565. */
  208566. static int stmtConnect(
  208567. sqlite3 *db,
  208568. void *pAux,
  208569. int argc, const char *const*argv,
  208570. sqlite3_vtab **ppVtab,
  208571. char **pzErr
  208572. ){
  208573. stmt_vtab *pNew;
  208574. int rc;
  208575. /* Column numbers */
  208576. #define STMT_COLUMN_SQL 0 /* SQL for the statement */
  208577. #define STMT_COLUMN_NCOL 1 /* Number of result columns */
  208578. #define STMT_COLUMN_RO 2 /* True if read-only */
  208579. #define STMT_COLUMN_BUSY 3 /* True if currently busy */
  208580. #define STMT_COLUMN_NSCAN 4 /* SQLITE_STMTSTATUS_FULLSCAN_STEP */
  208581. #define STMT_COLUMN_NSORT 5 /* SQLITE_STMTSTATUS_SORT */
  208582. #define STMT_COLUMN_NAIDX 6 /* SQLITE_STMTSTATUS_AUTOINDEX */
  208583. #define STMT_COLUMN_NSTEP 7 /* SQLITE_STMTSTATUS_VM_STEP */
  208584. #define STMT_COLUMN_REPREP 8 /* SQLITE_STMTSTATUS_REPREPARE */
  208585. #define STMT_COLUMN_RUN 9 /* SQLITE_STMTSTATUS_RUN */
  208586. #define STMT_COLUMN_MEM 10 /* SQLITE_STMTSTATUS_MEMUSED */
  208587. rc = sqlite3_declare_vtab(db,
  208588. "CREATE TABLE x(sql,ncol,ro,busy,nscan,nsort,naidx,nstep,"
  208589. "reprep,run,mem)");
  208590. if( rc==SQLITE_OK ){
  208591. pNew = sqlite3_malloc( sizeof(*pNew) );
  208592. *ppVtab = (sqlite3_vtab*)pNew;
  208593. if( pNew==0 ) return SQLITE_NOMEM;
  208594. memset(pNew, 0, sizeof(*pNew));
  208595. pNew->db = db;
  208596. }
  208597. return rc;
  208598. }
  208599. /*
  208600. ** This method is the destructor for stmt_cursor objects.
  208601. */
  208602. static int stmtDisconnect(sqlite3_vtab *pVtab){
  208603. sqlite3_free(pVtab);
  208604. return SQLITE_OK;
  208605. }
  208606. /*
  208607. ** Constructor for a new stmt_cursor object.
  208608. */
  208609. static int stmtOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
  208610. stmt_cursor *pCur;
  208611. pCur = sqlite3_malloc( sizeof(*pCur) );
  208612. if( pCur==0 ) return SQLITE_NOMEM;
  208613. memset(pCur, 0, sizeof(*pCur));
  208614. pCur->db = ((stmt_vtab*)p)->db;
  208615. *ppCursor = &pCur->base;
  208616. return SQLITE_OK;
  208617. }
  208618. /*
  208619. ** Destructor for a stmt_cursor.
  208620. */
  208621. static int stmtClose(sqlite3_vtab_cursor *cur){
  208622. sqlite3_free(cur);
  208623. return SQLITE_OK;
  208624. }
  208625. /*
  208626. ** Advance a stmt_cursor to its next row of output.
  208627. */
  208628. static int stmtNext(sqlite3_vtab_cursor *cur){
  208629. stmt_cursor *pCur = (stmt_cursor*)cur;
  208630. pCur->iRowid++;
  208631. pCur->pStmt = sqlite3_next_stmt(pCur->db, pCur->pStmt);
  208632. return SQLITE_OK;
  208633. }
  208634. /*
  208635. ** Return values of columns for the row at which the stmt_cursor
  208636. ** is currently pointing.
  208637. */
  208638. static int stmtColumn(
  208639. sqlite3_vtab_cursor *cur, /* The cursor */
  208640. sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
  208641. int i /* Which column to return */
  208642. ){
  208643. stmt_cursor *pCur = (stmt_cursor*)cur;
  208644. switch( i ){
  208645. case STMT_COLUMN_SQL: {
  208646. sqlite3_result_text(ctx, sqlite3_sql(pCur->pStmt), -1, SQLITE_TRANSIENT);
  208647. break;
  208648. }
  208649. case STMT_COLUMN_NCOL: {
  208650. sqlite3_result_int(ctx, sqlite3_column_count(pCur->pStmt));
  208651. break;
  208652. }
  208653. case STMT_COLUMN_RO: {
  208654. sqlite3_result_int(ctx, sqlite3_stmt_readonly(pCur->pStmt));
  208655. break;
  208656. }
  208657. case STMT_COLUMN_BUSY: {
  208658. sqlite3_result_int(ctx, sqlite3_stmt_busy(pCur->pStmt));
  208659. break;
  208660. }
  208661. case STMT_COLUMN_MEM: {
  208662. i = SQLITE_STMTSTATUS_MEMUSED +
  208663. STMT_COLUMN_NSCAN - SQLITE_STMTSTATUS_FULLSCAN_STEP;
  208664. /* Fall thru */
  208665. }
  208666. case STMT_COLUMN_NSCAN:
  208667. case STMT_COLUMN_NSORT:
  208668. case STMT_COLUMN_NAIDX:
  208669. case STMT_COLUMN_NSTEP:
  208670. case STMT_COLUMN_REPREP:
  208671. case STMT_COLUMN_RUN: {
  208672. sqlite3_result_int(ctx, sqlite3_stmt_status(pCur->pStmt,
  208673. i-STMT_COLUMN_NSCAN+SQLITE_STMTSTATUS_FULLSCAN_STEP, 0));
  208674. break;
  208675. }
  208676. }
  208677. return SQLITE_OK;
  208678. }
  208679. /*
  208680. ** Return the rowid for the current row. In this implementation, the
  208681. ** rowid is the same as the output value.
  208682. */
  208683. static int stmtRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
  208684. stmt_cursor *pCur = (stmt_cursor*)cur;
  208685. *pRowid = pCur->iRowid;
  208686. return SQLITE_OK;
  208687. }
  208688. /*
  208689. ** Return TRUE if the cursor has been moved off of the last
  208690. ** row of output.
  208691. */
  208692. static int stmtEof(sqlite3_vtab_cursor *cur){
  208693. stmt_cursor *pCur = (stmt_cursor*)cur;
  208694. return pCur->pStmt==0;
  208695. }
  208696. /*
  208697. ** This method is called to "rewind" the stmt_cursor object back
  208698. ** to the first row of output. This method is always called at least
  208699. ** once prior to any call to stmtColumn() or stmtRowid() or
  208700. ** stmtEof().
  208701. */
  208702. static int stmtFilter(
  208703. sqlite3_vtab_cursor *pVtabCursor,
  208704. int idxNum, const char *idxStr,
  208705. int argc, sqlite3_value **argv
  208706. ){
  208707. stmt_cursor *pCur = (stmt_cursor *)pVtabCursor;
  208708. pCur->pStmt = 0;
  208709. pCur->iRowid = 0;
  208710. return stmtNext(pVtabCursor);
  208711. }
  208712. /*
  208713. ** SQLite will invoke this method one or more times while planning a query
  208714. ** that uses the stmt virtual table. This routine needs to create
  208715. ** a query plan for each invocation and compute an estimated cost for that
  208716. ** plan.
  208717. */
  208718. static int stmtBestIndex(
  208719. sqlite3_vtab *tab,
  208720. sqlite3_index_info *pIdxInfo
  208721. ){
  208722. pIdxInfo->estimatedCost = (double)500;
  208723. pIdxInfo->estimatedRows = 500;
  208724. return SQLITE_OK;
  208725. }
  208726. /*
  208727. ** This following structure defines all the methods for the
  208728. ** stmt virtual table.
  208729. */
  208730. static sqlite3_module stmtModule = {
  208731. 0, /* iVersion */
  208732. 0, /* xCreate */
  208733. stmtConnect, /* xConnect */
  208734. stmtBestIndex, /* xBestIndex */
  208735. stmtDisconnect, /* xDisconnect */
  208736. 0, /* xDestroy */
  208737. stmtOpen, /* xOpen - open a cursor */
  208738. stmtClose, /* xClose - close a cursor */
  208739. stmtFilter, /* xFilter - configure scan constraints */
  208740. stmtNext, /* xNext - advance a cursor */
  208741. stmtEof, /* xEof - check for end of scan */
  208742. stmtColumn, /* xColumn - read data */
  208743. stmtRowid, /* xRowid - read data */
  208744. 0, /* xUpdate */
  208745. 0, /* xBegin */
  208746. 0, /* xSync */
  208747. 0, /* xCommit */
  208748. 0, /* xRollback */
  208749. 0, /* xFindMethod */
  208750. 0, /* xRename */
  208751. 0, /* xSavepoint */
  208752. 0, /* xRelease */
  208753. 0, /* xRollbackTo */
  208754. 0, /* xShadowName */
  208755. };
  208756. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  208757. SQLITE_PRIVATE int sqlite3StmtVtabInit(sqlite3 *db){
  208758. int rc = SQLITE_OK;
  208759. #ifndef SQLITE_OMIT_VIRTUALTABLE
  208760. rc = sqlite3_create_module(db, "sqlite_stmt", &stmtModule, 0);
  208761. #endif
  208762. return rc;
  208763. }
  208764. #ifndef SQLITE_CORE
  208765. #ifdef _WIN32
  208766. __declspec(dllexport)
  208767. #endif
  208768. SQLITE_API int sqlite3_stmt_init(
  208769. sqlite3 *db,
  208770. char **pzErrMsg,
  208771. const sqlite3_api_routines *pApi
  208772. ){
  208773. int rc = SQLITE_OK;
  208774. SQLITE_EXTENSION_INIT2(pApi);
  208775. #ifndef SQLITE_OMIT_VIRTUALTABLE
  208776. rc = sqlite3StmtVtabInit(db);
  208777. #endif
  208778. return rc;
  208779. }
  208780. #endif /* SQLITE_CORE */
  208781. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_STMTVTAB) */
  208782. /************** End of stmt.c ************************************************/
  208783. #if __LINE__!=223781
  208784. #undef SQLITE_SOURCE_ID
  208785. #define SQLITE_SOURCE_ID "2019-07-10 17:32:03 fc82b73eaac8b36950e527f12c4b5dc1e147e6f4ad2217ae43ad82882a88alt2"
  208786. #endif
  208787. /* Return the source-id for this library */
  208788. SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
  208789. /************************** End of sqlite3.c ******************************/
  208790. #else // USE_LIBSQLITE3
  208791. // If users really want to link against the system sqlite3 we
  208792. // need to make this file a noop.
  208793. #endif
  208794. /*
  208795. ** 2014-09-08
  208796. **
  208797. ** The author disclaims copyright to this source code. In place of
  208798. ** a legal notice, here is a blessing:
  208799. **
  208800. ** May you do good and not evil.
  208801. ** May you find forgiveness for yourself and forgive others.
  208802. ** May you share freely, never taking more than you give.
  208803. **
  208804. *************************************************************************
  208805. **
  208806. ** This file contains the bulk of the implementation of the
  208807. ** user-authentication extension feature. Some parts of the user-
  208808. ** authentication code are contained within the SQLite core (in the
  208809. ** src/ subdirectory of the main source code tree) but those parts
  208810. ** that could reasonable be separated out are moved into this file.
  208811. **
  208812. ** To compile with the user-authentication feature, append this file to
  208813. ** end of an SQLite amalgamation, then add the SQLITE_USER_AUTHENTICATION
  208814. ** compile-time option. See the user-auth.txt file in the same source
  208815. ** directory as this file for additional information.
  208816. */
  208817. #ifdef SQLITE_USER_AUTHENTICATION
  208818. #ifndef SQLITEINT_H
  208819. # include "sqliteInt.h"
  208820. #endif
  208821. /*
  208822. ** Prepare an SQL statement for use by the user authentication logic.
  208823. ** Return a pointer to the prepared statement on success. Return a
  208824. ** NULL pointer if there is an error of any kind.
  208825. */
  208826. static sqlite3_stmt *sqlite3UserAuthPrepare(
  208827. sqlite3 *db,
  208828. const char *zFormat,
  208829. ...
  208830. ){
  208831. sqlite3_stmt *pStmt;
  208832. char *zSql;
  208833. int rc;
  208834. va_list ap;
  208835. int savedFlags = db->flags;
  208836. va_start(ap, zFormat);
  208837. zSql = sqlite3_vmprintf(zFormat, ap);
  208838. va_end(ap);
  208839. if( zSql==0 ) return 0;
  208840. db->flags |= SQLITE_WriteSchema;
  208841. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  208842. db->flags = savedFlags;
  208843. sqlite3_free(zSql);
  208844. if( rc ){
  208845. sqlite3_finalize(pStmt);
  208846. pStmt = 0;
  208847. }
  208848. return pStmt;
  208849. }
  208850. /*
  208851. ** Check to see if the sqlite_user table exists in database zDb.
  208852. */
  208853. static int userTableExists(sqlite3 *db, const char *zDb){
  208854. int rc;
  208855. sqlite3_mutex_enter(db->mutex);
  208856. sqlite3BtreeEnterAll(db);
  208857. if( db->init.busy==0 ){
  208858. char *zErr = 0;
  208859. sqlite3Init(db, &zErr);
  208860. sqlite3DbFree(db, zErr);
  208861. }
  208862. rc = sqlite3FindTable(db, "sqlite_user", zDb)!=0;
  208863. sqlite3BtreeLeaveAll(db);
  208864. sqlite3_mutex_leave(db->mutex);
  208865. return rc;
  208866. }
  208867. /*
  208868. ** Check to see if database zDb has a "sqlite_user" table and if it does
  208869. ** whether that table can authenticate zUser with nPw,zPw. Write one of
  208870. ** the UAUTH_* user authorization level codes into *peAuth and return a
  208871. ** result code.
  208872. */
  208873. static int userAuthCheckLogin(
  208874. sqlite3 *db, /* The database connection to check */
  208875. const char *zDb, /* Name of specific database to check */
  208876. u8 *peAuth /* OUT: One of UAUTH_* constants */
  208877. ){
  208878. sqlite3_stmt *pStmt;
  208879. int rc;
  208880. *peAuth = UAUTH_Unknown;
  208881. if( !userTableExists(db, "main") ){
  208882. *peAuth = UAUTH_Admin; /* No sqlite_user table. Everybody is admin. */
  208883. return SQLITE_OK;
  208884. }
  208885. if( db->auth.zAuthUser==0 ){
  208886. *peAuth = UAUTH_Fail;
  208887. return SQLITE_OK;
  208888. }
  208889. pStmt = sqlite3UserAuthPrepare(db,
  208890. "SELECT pw=sqlite_crypt(?1,pw), isAdmin FROM \"%w\".sqlite_user"
  208891. " WHERE uname=?2", zDb);
  208892. if( pStmt==0 ) return SQLITE_NOMEM;
  208893. sqlite3_bind_blob(pStmt, 1, db->auth.zAuthPW, db->auth.nAuthPW,SQLITE_STATIC);
  208894. sqlite3_bind_text(pStmt, 2, db->auth.zAuthUser, -1, SQLITE_STATIC);
  208895. rc = sqlite3_step(pStmt);
  208896. if( rc==SQLITE_ROW && sqlite3_column_int(pStmt,0) ){
  208897. *peAuth = sqlite3_column_int(pStmt, 1) + UAUTH_User;
  208898. }else{
  208899. *peAuth = UAUTH_Fail;
  208900. }
  208901. return sqlite3_finalize(pStmt);
  208902. }
  208903. int sqlite3UserAuthCheckLogin(
  208904. sqlite3 *db, /* The database connection to check */
  208905. const char *zDb, /* Name of specific database to check */
  208906. u8 *peAuth /* OUT: One of UAUTH_* constants */
  208907. ){
  208908. int rc;
  208909. u8 savedAuthLevel;
  208910. assert( zDb!=0 );
  208911. assert( peAuth!=0 );
  208912. savedAuthLevel = db->auth.authLevel;
  208913. db->auth.authLevel = UAUTH_Admin;
  208914. rc = userAuthCheckLogin(db, zDb, peAuth);
  208915. db->auth.authLevel = savedAuthLevel;
  208916. return rc;
  208917. }
  208918. /*
  208919. ** If the current authLevel is UAUTH_Unknown, the take actions to figure
  208920. ** out what authLevel should be
  208921. */
  208922. void sqlite3UserAuthInit(sqlite3 *db){
  208923. if( db->auth.authLevel==UAUTH_Unknown ){
  208924. u8 authLevel = UAUTH_Fail;
  208925. sqlite3UserAuthCheckLogin(db, "main", &authLevel);
  208926. db->auth.authLevel = authLevel;
  208927. if( authLevel<UAUTH_Admin ) db->flags &= ~SQLITE_WriteSchema;
  208928. }
  208929. }
  208930. /*
  208931. ** Implementation of the sqlite_crypt(X,Y) function.
  208932. **
  208933. ** If Y is NULL then generate a new hash for password X and return that
  208934. ** hash. If Y is not null, then generate a hash for password X using the
  208935. ** same salt as the previous hash Y and return the new hash.
  208936. */
  208937. void sqlite3CryptFunc(
  208938. sqlite3_context *context,
  208939. int NotUsed,
  208940. sqlite3_value **argv
  208941. ){
  208942. const char *zIn;
  208943. int nIn, ii;
  208944. u8 *zOut;
  208945. char zSalt[8];
  208946. zIn = sqlite3_value_blob(argv[0]);
  208947. nIn = sqlite3_value_bytes(argv[0]);
  208948. if( sqlite3_value_type(argv[1])==SQLITE_BLOB
  208949. && sqlite3_value_bytes(argv[1])==nIn+sizeof(zSalt)
  208950. ){
  208951. memcpy(zSalt, sqlite3_value_blob(argv[1]), sizeof(zSalt));
  208952. }else{
  208953. sqlite3_randomness(sizeof(zSalt), zSalt);
  208954. }
  208955. zOut = sqlite3_malloc( nIn+sizeof(zSalt) );
  208956. if( zOut==0 ){
  208957. sqlite3_result_error_nomem(context);
  208958. }else{
  208959. memcpy(zOut, zSalt, sizeof(zSalt));
  208960. for(ii=0; ii<nIn; ii++){
  208961. zOut[ii+sizeof(zSalt)] = zIn[ii]^zSalt[ii&0x7];
  208962. }
  208963. sqlite3_result_blob(context, zOut, nIn+sizeof(zSalt), sqlite3_free);
  208964. }
  208965. }
  208966. /*
  208967. ** If a database contains the SQLITE_USER table, then the
  208968. ** sqlite3_user_authenticate() interface must be invoked with an
  208969. ** appropriate username and password prior to enable read and write
  208970. ** access to the database.
  208971. **
  208972. ** Return SQLITE_OK on success or SQLITE_ERROR if the username/password
  208973. ** combination is incorrect or unknown.
  208974. **
  208975. ** If the SQLITE_USER table is not present in the database file, then
  208976. ** this interface is a harmless no-op returnning SQLITE_OK.
  208977. */
  208978. int sqlite3_user_authenticate(
  208979. sqlite3 *db, /* The database connection */
  208980. const char *zUsername, /* Username */
  208981. const char *zPW, /* Password or credentials */
  208982. int nPW /* Number of bytes in aPW[] */
  208983. ){
  208984. int rc;
  208985. u8 authLevel = UAUTH_Fail;
  208986. db->auth.authLevel = UAUTH_Unknown;
  208987. sqlite3_free(db->auth.zAuthUser);
  208988. sqlite3_free(db->auth.zAuthPW);
  208989. memset(&db->auth, 0, sizeof(db->auth));
  208990. db->auth.zAuthUser = sqlite3_mprintf("%s", zUsername);
  208991. if( db->auth.zAuthUser==0 ) return SQLITE_NOMEM;
  208992. db->auth.zAuthPW = sqlite3_malloc( nPW+1 );
  208993. if( db->auth.zAuthPW==0 ) return SQLITE_NOMEM;
  208994. memcpy(db->auth.zAuthPW,zPW,nPW);
  208995. db->auth.nAuthPW = nPW;
  208996. rc = sqlite3UserAuthCheckLogin(db, "main", &authLevel);
  208997. db->auth.authLevel = authLevel;
  208998. sqlite3ExpirePreparedStatements(db, 0);
  208999. if( rc ){
  209000. return rc; /* OOM error, I/O error, etc. */
  209001. }
  209002. if( authLevel<UAUTH_User ){
  209003. return SQLITE_AUTH; /* Incorrect username and/or password */
  209004. }
  209005. return SQLITE_OK; /* Successful login */
  209006. }
  209007. /*
  209008. ** The sqlite3_user_add() interface can be used (by an admin user only)
  209009. ** to create a new user. When called on a no-authentication-required
  209010. ** database, this routine converts the database into an authentication-
  209011. ** required database, automatically makes the added user an
  209012. ** administrator, and logs in the current connection as that user.
  209013. ** The sqlite3_user_add() interface only works for the "main" database, not
  209014. ** for any ATTACH-ed databases. Any call to sqlite3_user_add() by a
  209015. ** non-admin user results in an error.
  209016. */
  209017. int sqlite3_user_add(
  209018. sqlite3 *db, /* Database connection */
  209019. const char *zUsername, /* Username to be added */
  209020. const char *aPW, /* Password or credentials */
  209021. int nPW, /* Number of bytes in aPW[] */
  209022. int isAdmin /* True to give new user admin privilege */
  209023. ){
  209024. sqlite3_stmt *pStmt;
  209025. int rc;
  209026. sqlite3UserAuthInit(db);
  209027. if( db->auth.authLevel<UAUTH_Admin ) return SQLITE_AUTH;
  209028. if( !userTableExists(db, "main") ){
  209029. if( !isAdmin ) return SQLITE_AUTH;
  209030. pStmt = sqlite3UserAuthPrepare(db,
  209031. "CREATE TABLE sqlite_user(\n"
  209032. " uname TEXT PRIMARY KEY,\n"
  209033. " isAdmin BOOLEAN,\n"
  209034. " pw BLOB\n"
  209035. ") WITHOUT ROWID;");
  209036. if( pStmt==0 ) return SQLITE_NOMEM;
  209037. sqlite3_step(pStmt);
  209038. rc = sqlite3_finalize(pStmt);
  209039. if( rc ) return rc;
  209040. }
  209041. pStmt = sqlite3UserAuthPrepare(db,
  209042. "INSERT INTO sqlite_user(uname,isAdmin,pw)"
  209043. " VALUES(%Q,%d,sqlite_crypt(?1,NULL))",
  209044. zUsername, isAdmin!=0);
  209045. if( pStmt==0 ) return SQLITE_NOMEM;
  209046. sqlite3_bind_blob(pStmt, 1, aPW, nPW, SQLITE_STATIC);
  209047. sqlite3_step(pStmt);
  209048. rc = sqlite3_finalize(pStmt);
  209049. if( rc ) return rc;
  209050. if( db->auth.zAuthUser==0 ){
  209051. assert( isAdmin!=0 );
  209052. sqlite3_user_authenticate(db, zUsername, aPW, nPW);
  209053. }
  209054. return SQLITE_OK;
  209055. }
  209056. /*
  209057. ** The sqlite3_user_change() interface can be used to change a users
  209058. ** login credentials or admin privilege. Any user can change their own
  209059. ** login credentials. Only an admin user can change another users login
  209060. ** credentials or admin privilege setting. No user may change their own
  209061. ** admin privilege setting.
  209062. */
  209063. int sqlite3_user_change(
  209064. sqlite3 *db, /* Database connection */
  209065. const char *zUsername, /* Username to change */
  209066. const char *aPW, /* Modified password or credentials */
  209067. int nPW, /* Number of bytes in aPW[] */
  209068. int isAdmin /* Modified admin privilege for the user */
  209069. ){
  209070. sqlite3_stmt *pStmt;
  209071. int rc;
  209072. u8 authLevel;
  209073. authLevel = db->auth.authLevel;
  209074. if( authLevel<UAUTH_User ){
  209075. /* Must be logged in to make a change */
  209076. return SQLITE_AUTH;
  209077. }
  209078. if( strcmp(db->auth.zAuthUser, zUsername)!=0 ){
  209079. if( db->auth.authLevel<UAUTH_Admin ){
  209080. /* Must be an administrator to change a different user */
  209081. return SQLITE_AUTH;
  209082. }
  209083. }else if( isAdmin!=(authLevel==UAUTH_Admin) ){
  209084. /* Cannot change the isAdmin setting for self */
  209085. return SQLITE_AUTH;
  209086. }
  209087. db->auth.authLevel = UAUTH_Admin;
  209088. if( !userTableExists(db, "main") ){
  209089. /* This routine is a no-op if the user to be modified does not exist */
  209090. }else{
  209091. pStmt = sqlite3UserAuthPrepare(db,
  209092. "UPDATE sqlite_user SET isAdmin=%d, pw=sqlite_crypt(?1,NULL)"
  209093. " WHERE uname=%Q", isAdmin, zUsername);
  209094. if( pStmt==0 ){
  209095. rc = SQLITE_NOMEM;
  209096. }else{
  209097. sqlite3_bind_blob(pStmt, 1, aPW, nPW, SQLITE_STATIC);
  209098. sqlite3_step(pStmt);
  209099. rc = sqlite3_finalize(pStmt);
  209100. }
  209101. }
  209102. db->auth.authLevel = authLevel;
  209103. return rc;
  209104. }
  209105. /*
  209106. ** The sqlite3_user_delete() interface can be used (by an admin user only)
  209107. ** to delete a user. The currently logged-in user cannot be deleted,
  209108. ** which guarantees that there is always an admin user and hence that
  209109. ** the database cannot be converted into a no-authentication-required
  209110. ** database.
  209111. */
  209112. int sqlite3_user_delete(
  209113. sqlite3 *db, /* Database connection */
  209114. const char *zUsername /* Username to remove */
  209115. ){
  209116. sqlite3_stmt *pStmt;
  209117. if( db->auth.authLevel<UAUTH_Admin ){
  209118. /* Must be an administrator to delete a user */
  209119. return SQLITE_AUTH;
  209120. }
  209121. if( strcmp(db->auth.zAuthUser, zUsername)==0 ){
  209122. /* Cannot delete self */
  209123. return SQLITE_AUTH;
  209124. }
  209125. if( !userTableExists(db, "main") ){
  209126. /* This routine is a no-op if the user to be deleted does not exist */
  209127. return SQLITE_OK;
  209128. }
  209129. pStmt = sqlite3UserAuthPrepare(db,
  209130. "DELETE FROM sqlite_user WHERE uname=%Q", zUsername);
  209131. if( pStmt==0 ) return SQLITE_NOMEM;
  209132. sqlite3_step(pStmt);
  209133. return sqlite3_finalize(pStmt);
  209134. }
  209135. #endif /* SQLITE_USER_AUTHENTICATION */
上海开阖软件有限公司 沪ICP备12045867号-1